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