]> git.scottworley.com Git - srec/blob - srec.py
Rename: Recording → Stream
[srec] / srec.py
1 # srec: A simple GUI for screen recording
2 #
3 # This program is free software: you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation, version 3.
6
7 from dataclasses import dataclass
8 from datetime import datetime
9 import os
10 import subprocess
11 import sys
12 from typing import Any, Callable
13
14 import gi
15 gi.require_version("Gtk", "4.0")
16 gi.require_version("GLib", "2.0")
17
18 from gi.repository import Gtk # nopep8 pylint: disable=wrong-import-position
19 from gi.repository import GLib # nopep8 pylint: disable=wrong-import-position
20
21
22 @dataclass
23 class Stream:
24 process: subprocess.Popen[bytes]
25
26 def stop(self) -> None:
27 stdin = self.process.stdin
28 assert stdin is not None
29 try:
30 stdin.write(b'q')
31 stdin.flush()
32 except BrokenPipeError:
33 print("Stream already stopped?", file=sys.stderr)
34 self.process.wait()
35
36
37 recording: Stream | None = None
38
39
40 def make_filename() -> str:
41 directory = os.environ.get(
42 'XDG_VIDEOS_DIR',
43 os.path.expanduser('~/Videos/SRec'))
44 os.makedirs(directory, exist_ok=True)
45 timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
46 return os.path.join(directory, f'srec {timestamp}.mkv')
47
48
49 def video_source(stack: Gtk.Stack) -> list[str]:
50 if stack.get_child_by_name('not_recording').get_first_child().get_active():
51 return ['-f', 'x11grab', '-i', ':0.0+0,0']
52 return ['-f', 'v4l2', '-i', '/dev/video0']
53
54
55 def find_size_display(stack: Gtk.Stack) -> Gtk.Label:
56 return stack.get_child_by_name(
57 'recording').get_first_child().get_next_sibling()
58
59
60 def summarize_size(n: int) -> str:
61 if n > 100_000_000:
62 m = int(n / (1024 * 1024))
63 return f'{m}M'
64 if n > 100_000:
65 k = int(n / 1024)
66 return f'{k}K'
67 return str(n)
68
69
70 def on_start_recording(_: Gtk.Button, stack: Gtk.Stack) -> None:
71 global recording # pylint: disable=global-statement
72 assert recording is None
73
74 filename = make_filename()
75 size_display = find_size_display(stack)
76
77 def update_size_display() -> Any:
78 try:
79 size = summarize_size(os.stat(filename).st_size)
80 except FileNotFoundError:
81 size = '--'
82 size_display.set_label(f'<big>{size}</big>')
83 return GLib.SOURCE_REMOVE if recording is None else GLib.SOURCE_CONTINUE
84 GLib.timeout_add_seconds(1, update_size_display)
85
86 command = (['ffmpeg', '-framerate', '25'] + video_source(stack) +
87 ['-f', 'pulse', '-ac', '2', '-i', 'default', filename])
88 # pylint: disable=consider-using-with
89 recording = Stream(
90 process=subprocess.Popen(command, stdin=subprocess.PIPE))
91 stack.set_visible_child_name("recording")
92
93
94 def on_stop_recording(_: Gtk.Button, stack: Gtk.Stack) -> None:
95 global recording # pylint: disable=global-statement
96 assert recording is not None
97 recording.stop()
98 recording = None
99 stack.set_visible_child_name("not_recording")
100
101
102 def make_button(label: str, action: Callable[[
103 Gtk.Button, Gtk.Stack], None], stack: Gtk.Stack) -> Gtk.Button:
104 button = Gtk.Button(label=label)
105 button.connect('clicked', action, stack)
106 button.set_margin_top(10)
107 button.set_margin_start(10)
108 button.set_margin_end(10)
109 button.set_margin_bottom(10)
110 return button
111
112
113 def make_share_control() -> Gtk.CheckButton:
114 can_share = os.path.exists('/sys/module/v4l2loopback')
115 control = Gtk.CheckButton(
116 label='Share Webcam', sensitive=can_share, active=can_share)
117 control.set_margin_start(20)
118 return control
119
120
121 def on_activate(app: Gtk.Application) -> None:
122 win = Gtk.ApplicationWindow(application=app)
123 win.set_title('SRec')
124 win.set_icon_name('srec')
125
126 stack = Gtk.Stack()
127
128 nr_box = Gtk.Box()
129 nr_box.set_orientation(Gtk.Orientation.VERTICAL)
130 screen = Gtk.CheckButton(label='Screen')
131 nr_box.append(screen)
132 nr_box.append(Gtk.CheckButton(label='Webcam', active=True, group=screen))
133 nr_box.append(make_share_control())
134 nr_box.append(make_button("Start Recording", on_start_recording, stack))
135 stack.add_named(nr_box, "not_recording")
136
137 r_box = Gtk.Box()
138 r_box.set_orientation(Gtk.Orientation.VERTICAL)
139 r_box.append(make_button("Stop Recording", on_stop_recording, stack))
140 r_box.append(Gtk.Label(use_markup=True, justify=Gtk.Justification.CENTER))
141 stack.add_named(r_box, "recording")
142
143 win.set_child(stack)
144 win.present()
145
146
147 def main() -> None:
148 app = Gtk.Application(application_id='net.chkno.srec')
149 app.connect('activate', on_activate)
150 app.run(None)
151
152
153 if __name__ == '__main__':
154 main()