forked from cessen/recordscreen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecordscreen.py
executable file
·376 lines (331 loc) · 13.5 KB
/
recordscreen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python
""" A simple screen-capture utility. Utilizes ffmpeg with h264 support.
By default it captures the entire desktop.
"""
################################ LICENSE BLOCK ################################
# Copyright (c) 2011 Nathan Vegdahl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
###############################################################################
# Easy-to-change defaults for users
DEFAULT_FPS = 15
DEFAULT_FILE_EXTENSION = "mkv"
ACCEPTABLE_FILE_EXTENSIONS = ["avi", "mp4", "mov", "mkv", "ogv", "webm"]
DEFAULT_CAPTURE_AUDIO_DEVICE = "pulse"
DEFAULT_CAPTURE_DISPLAY_DEVICE = ":0.0"
DEFAULT_AUDIO_CODEC = "aac"
DEFAULT_VIDEO_CODEC = "h264"
import os
import sys
import os.path
import glob
import time
import random
import tempfile
import optparse
import subprocess
import re
PYTHON_3 = (sys.version_info[0] == 3)
# Optional packages
try:
import Tkinter
have_tk = True
except ImportError:
have_tk = False
try:
import multiprocessing
have_multiproc = True
except ImportError:
have_multiproc = False
# Video codec lines
vcodecs = {}
vcodecs["h264_lossless"] = ["-c:v", "libx264", "-g", "15", "-crf", "0", "-pix_fmt", "yuv444p"]
vcodecs["h264"] = ["-c:v", "libx264", "-vprofile", "baseline", "-g", "15", "-crf", "1", "-pix_fmt", "yuv420p"]
vcodecs["mpeg4"] = ["-c:v", "mpeg4", "-g", "15", "-qmax", "1", "-qmin", "1"]
#vcodecs["xvid"] = ["-c:v", "libxvid", "-g", "15", "-b:v", "40000k"]
vcodecs["huffyuv"] = ["-c:v", "huffyuv"]
vcodecs["vp8"] = ["-c:v", "libvpx", "-g", "15", "-qmax", "1", "-qmin", "1"]
vcodecs["theora"] = ["-c:v", "libtheora", "-g", "15", "-b:v", "40000k"]
#vcodecs["dirac"] = ["-c:v", "libschroedinger", "-g", "15", "-b:v", "40000k"]
# Audio codec lines
acodecs = {}
acodecs["pcm"] = ["-c:a", "pcm_s16le"]
#acodecs["flac"] = ["-c:a", "flac"]
acodecs["vorbis"] = ["-c:a", "libvorbis", "-b:a", "320k"]
acodecs["mp3"] = ["-c:a", "libmp3lame", "-b:a", "320k"]
acodecs["aac"] = ["-c:a", "libvo_aacenc", "-b:a", "320k"]
def capture_line(fps, x, y, height, width, display_device, audio_device, video_codec, audio_codec, output_path):
""" Returns the command line to capture video+audio, in a list form
compatible with Popen.
"""
threads = 2
if have_multiproc:
# Detect the number of threads we have available
threads = multiprocessing.cpu_count()
line = ["avconv",
"-f", "alsa",
"-ac", "2",
"-i", str(audio_device),
"-f", "x11grab",
"-r", str(fps),
"-s", "%dx%d" % (int(height), int(width)),
"-i", display_device + "+" + str(x) + "," + str(y)]
line += acodecs[audio_codec]
line += vcodecs[video_codec]
line += ["-threads", str(threads), str(output_path)]
return line
def video_capture_line(fps, x, y, height, width, display_device, video_codec, output_path):
""" Returns the command line to capture video (no audio), in a list form
compatible with Popen.
"""
threads = 2
if have_multiproc:
# Detect the number of threads we have available
threads = multiprocessing.cpu_count()
line = ["avconv",
"-f", "x11grab",
"-r", str(fps),
"-s", "%dx%d" % (int(height), int(width)),
"-i", display_device + "+" + str(x) + "," + str(y)]
line += vcodecs[video_codec]
line += ["-threads", str(threads), str(output_path)]
return line
def audio_capture_line(audio_device, audio_codec, output_path):
""" Returns the command line to capture audio (no video), in a list form
compatible with Popen.
"""
line = ["avconv",
"-f", "alsa",
"-ac", "2",
"-i", str(audio_device)]
line += acodecs[audio_codec]
line += [str(output_path)]
return line
def get_desktop_resolution():
""" Returns the resolution of the desktop as a tuple.
"""
if have_tk:
# Use tk to get the desktop resolution if we have it
root = Tkinter.Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.destroy()
return (width, height)
else:
# Otherwise call xdpyinfo and parse its output
try:
proc = subprocess.Popen("xdpyinfo", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
return None
out, err = proc.communicate()
if PYTHON_3:
lines = str(out).split("\\n")
else:
lines = out.split("\n")
for line in lines:
if "dimensions" in line:
line = re.sub(".*dimensions:[ ]*", "", line)
line = re.sub("[ ]*pixels.*", "", line)
wh = line.strip().split("x")
return (int(wh[0]), int(wh[1]))
def get_window_position_and_size():
""" Prompts the user to click on a window, and returns the window's
position and size.
"""
try:
proc = subprocess.Popen("xwininfo", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
return None
out, err = proc.communicate()
if PYTHON_3:
lines = str(out).split("\\n")
else:
lines = out.split("\n")
x = 0
y = 0
w = 0
h = 0
xt = False
yt = False
wt = False
ht = False
for line in lines:
if "Absolute upper-left X:" in line:
x = int(re.sub("[^0-9]", "", line))
xt = True
elif "Absolute upper-left Y:" in line:
y = int(re.sub("[^0-9]", "", line))
yt = True
elif "Width:" in line:
w = int(re.sub("[^0-9]", "", line))
wt = True
elif "Height:" in line:
h = int(re.sub("[^0-9]", "", line))
ht = True
if xt and yt and wt and ht:
return (x, y, w, h)
else:
return None
def get_default_output_path(ext=DEFAULT_FILE_EXTENSION):
""" Creates a default output file path.
Pattern: out_####.ext
"""
filenames = glob.glob("out_????" + "." + ext)
for i in range(1, 9999):
name = "out_" + str(i).rjust(4,'0') + "." + ext
tally = 0
for f in filenames:
if f == name:
tally += 1
if tally == 0:
return name
return "out_9999" + "." + ext
def print_codecs():
""" Prints a list of the available audio/video codecs.
"""
a = []
v = []
for i in acodecs:
a += [i]
for i in vcodecs:
v += [i]
a.sort()
v.sort()
print("Audio codecs:")
for i in a:
print(" " + str(i))
print("Video codecs:")
for i in vcodecs:
print(" " + str(i))
if __name__ == "__main__":
# Parse command line arguments
parser = optparse.OptionParser(usage="%prog [options] [output_file" + "." + DEFAULT_FILE_EXTENSION + "]")
parser.add_option("-w", "--capture-window", action="store_true", dest="capture_window",
default=False,
help="prompt user to click on a window to capture")
parser.add_option("-n", "--no-audio", action="store_true", dest="no_audio",
default=False,
help="don't capture audio")
parser.add_option("-r", "--fps", dest="fps",
type="int", default=DEFAULT_FPS,
help="frame rate to capture video at. Default: " + str(DEFAULT_FPS))
parser.add_option("-p", "--position", dest="xy", metavar="XxY",
type="string", default=None,
help="upper left corner of the capture area (in pixels from the upper left of the screen). Default: 0x0")
parser.add_option("-s", "--size", dest="size",
type="string", default=None, metavar="WIDTHxHEIGHT",
help="resolution of the capture area (in pixels). Default: entire desktop")
parser.add_option("--crop-top", dest="crop_top",
type="int", default=0,
help="number of pixels to crop off the top of the capture area")
parser.add_option("--crop-bottom", dest="crop_bottom",
type="int", default=0,
help="number of pixels to crop off the bottom of the capture area")
parser.add_option("--crop-left", dest="crop_left",
type="int", default=0,
help="number of pixels to crop off the left of the capture area")
parser.add_option("--crop-right", dest="crop_right",
type="int", default=0,
help="number of pixels to crop off the right of the capture area")
parser.add_option("-a", "--audio-device", dest="audio_device",
default=DEFAULT_CAPTURE_AUDIO_DEVICE,
help="the audio device to capture from (eg. hw:0). Default: " + DEFAULT_CAPTURE_AUDIO_DEVICE)
parser.add_option("-d", "--display-device", dest="display_device",
default=DEFAULT_CAPTURE_DISPLAY_DEVICE,
help="the display device to capture from (eg. :0.0). Default: " + DEFAULT_CAPTURE_DISPLAY_DEVICE)
parser.add_option("--acodec", dest="acodec",
default=DEFAULT_AUDIO_CODEC,
help="the audio codec to encode with. Default: " + DEFAULT_AUDIO_CODEC)
parser.add_option("--vcodec", dest="vcodec",
default=DEFAULT_VIDEO_CODEC,
help="the video codec to encode with. Default: " + DEFAULT_VIDEO_CODEC)
parser.add_option("--codecs", action="store_true", dest="list_codecs",
default=False,
help="display the available audio and video codecs")
parser.add_option("--container", dest="container",
default=DEFAULT_FILE_EXTENSION,
help="the media container format to use if a filename is not given. Specified by file extension. Default: " + DEFAULT_FILE_EXTENSION)
opts, args = parser.parse_args()
# Print list of codecs, if requested
if opts.list_codecs:
print_codecs()
exit(0)
# Check that the container format specified is supported
if opts.container not in ACCEPTABLE_FILE_EXTENSIONS:
print("" + opts.container + " is not a supported container format.")
exit(0)
# Set up default file path
out_path = get_default_output_path(ext=opts.container)
# Output file path specified on command line
if len(args) >= 1:
out_path = args[0]
exts = out_path.rsplit(".", 1)
if len(exts) == 1 or exts[1] not in ACCEPTABLE_FILE_EXTENSIONS:
out_path += "." + opts.container
# Get desktop resolution
try:
dres = get_desktop_resolution()
except:
print("Error: unable to determine desktop resolution.")
raise
# Capture values
fps = opts.fps
if opts.capture_window:
print("Please click on a window to capture.")
x, y, width, height = get_window_position_and_size()
else:
if opts.xy:
if re.match("^[0-9]*x[0-9]*$", opts.xy.strip()):
xy = opts.xy.strip().split("x")
x = int(xy[0])
y = int(xy[1])
else:
raise parser.error("position option must be of form XxY (e.g. 50x64)")
else:
x = 0
y = 0
if opts.size:
if re.match("^[0-9]*x[0-9]*$", opts.size.strip()):
size = opts.size.strip().split("x")
width = int(size[0])
height = int(size[1])
else:
raise parser.error("size option must be of form HxW (e.g. 1280x720)")
else:
width = dres[0]
height = dres[1]
# Calculate cropping
width -= opts.crop_left + opts.crop_right
height -= opts.crop_top + opts.crop_bottom
x += opts.crop_left
y += opts.crop_top
# Make sure the capture resolution conforms to the restrictions
# of the video codec. Crop to conform, if necessary.
mults = {"h264": 2, "h264_lossless": 2, "mpeg4": 2, "dirac": 2, "xvid": 2, "theora": 8, "huffyuv": 2, "vp8": 1}
width -= width % mults[opts.vcodec]
height -= height % mults[opts.vcodec]
# Verify that capture area is on screen
if (x + width) > dres[0] or (y + height) > dres[1]:
parser.error("specified capture area is off screen.")
# Capture!
if not opts.no_audio:
proc = subprocess.Popen(capture_line(fps, x, y, width, height, opts.display_device, opts.audio_device, opts.vcodec, opts.acodec, out_path)).wait()
else:
proc = subprocess.Popen(video_capture_line(fps, x, y, width, height, opts.display_device, opts.vcodec, out_path)).wait()
print("Done!")