forked from danielgtaylor/arista
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharista-transcode
executable file
·367 lines (302 loc) · 12.8 KB
/
arista-transcode
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
#!/usr/bin/python
"""
Arista Transcoder (command-line client)
=======================================
An audio/video transcoder based on simple device profiles provided by
plugins. This is the command-line version.
License
-------
Copyright 2008 - 2010 Daniel G. Taylor <[email protected]>
This file is part of Arista.
Arista is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 2.1 of
the License, or (at your option) any later version.
Arista is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Arista. If not, see
<http://www.gnu.org/licenses/>.
"""
import gettext
import locale
import logging
import os
import signal
import sys
import time
from optparse import OptionParser
import gobject
# FIXME: Stupid hack, see the other fixme comment below!
if __name__ != "__main__":
import gst
import arista
_ = gettext.gettext
# Initialize threads for gstreamer
gobject.threads_init()
status_time = None
status_msg = ""
transcoder = None
loop = None
interrupted = False
def print_status(enc, options):
"""
Print the current status to the terminal with the estimated time
remaining.
"""
global status_msg
global interrupted
percent = 0.0
if interrupted or not enc:
return True
if enc.state == gst.STATE_NULL and interrupted:
gobject.idle_add(loop.quit)
return False
elif enc.state != gst.STATE_PLAYING:
return True
try:
percent, time_rem = enc.status
if not options.quiet:
msg = _("Encoding... %(percent)i%% (%(time)s remaining)") % {
"percent": int(percent * 100),
"time": time_rem,
}
sys.stdout.write("\b" * len(status_msg))
sys.stdout.write(msg)
sys.stdout.flush()
status_msg = msg
except arista.transcoder.TranscoderStatusException, e:
print str(e)
return (percent < 100)
def entry_start(queue, entry, options):
if not options.quiet:
print _("Encoding %(filename)s for %(device)s (%(preset)s)") % {
"filename": os.path.basename(entry.options.uri),
"device": options.device,
"preset": options.preset or _("default"),
}
gobject.timeout_add(500, print_status, entry.transcoder, options)
def entry_pass_setup(queue, entry, options):
if not options.quiet:
if entry.transcoder.enc_pass > 0:
print # blank line
info = entry.transcoder.info
preset = entry.transcoder.preset
if (info.is_video and len(preset.vcodec.passes) > 1) or \
(info.is_audio and len(preset.vcodec.passes) > 1):
print _("Starting pass %(pass)d of %(total)d") % {
"pass": entry.transcoder.enc_pass + 1,
"total": entry.transcoder.preset.pass_count,
}
def entry_complete(queue, entry, options):
if not options.quiet:
print
entry.transcoder.stop()
if len(queue) == 1:
# We are the last item!
gobject.idle_add(loop.quit)
def entry_error(queue, entry, errorstr, options):
if not options.quiet:
print _("Encoding %(filename)s for %(device)s (%(preset)s) failed!") % {
"filename": os.path.basename(entry.options.uri),
"device": options.device,
"preset": options.preset or _("default"),
}
print errorstr
entry.transcoder.stop()
if len(queue) == 1:
# We are the last item!
gobject.idle_add(loop.quit)
def check_interrupted():
"""
Check whether we have been interrupted by Ctrl-C and stop the
transcoder.
"""
if interrupted:
try:
source = transcoder.pipe.get_by_name("source")
source.send_event(gst.event_new_eos())
except:
# Something pretty bad happened... just exit!
gobject.idle_add(loop.quit)
return False
return True
def signal_handler(signum, frame):
"""
Handle Ctr-C gracefully and shut down the transcoder.
"""
global interrupted
print
print _("Interrupt caught. Cleaning up... (Ctrl-C to force exit)")
interrupted = True
signal.signal(signal.SIGINT, signal.SIG_DFL)
if __name__ == "__main__":
parser = OptionParser(usage = _("%prog [options] infile [infile infile ...]"),
version = _("Arista Transcoder " + arista.__version__))
parser.add_option("-i", "--info", dest = "info", action = "store_true",
default = False,
help = _("Show information about available devices " \
"[false]"))
parser.add_option("-S", "--subtitle", dest = "subtitle", default = None,
help = _("Subtitle file to render"))
parser.add_option("-e", "--ssa", dest = "ssa", action = "store_true",
default = False,
help = _("Render embedded SSA subtitles"))
parser.add_option("--subtitle-encoding", dest = "subtitle_encoding",
default = None, help = _("Subtitle file encoding"))
parser.add_option("-f", "--font", dest = "font", default = "Sans Bold 16",
help = _("Font to use when rendering subtitles"))
parser.add_option("-c", "--crop", dest = "crop", default = None, nargs=4, type=int,
help = _("Amount of pixels to crop before transcoding " \
"Specify as: Top Right Bottom Left, default: None"))
parser.add_option("-p", "--preset", dest = "preset", default = None,
help = _("Preset to encode to [default]"))
parser.add_option("-d", "--device", dest = "device", default = "computer",
help = _("Device to encode to [computer]"))
parser.add_option("-o", "--output", dest = "output", default = None,
help = _("Output file name [auto]"), metavar = "FILENAME")
parser.add_option("-s", "--source-info", dest = "source_info",
action = "store_true", default = False,
help = _("Show information about input file and exit"))
parser.add_option("-q", "--quiet", dest = "quiet", action = "store_true",
default = False,
help = _("Don't show status and time remaining"))
parser.add_option("-v", "--verbose", dest = "verbose",
action = "store_true", default = False,
help = _("Show verbose (debug) output"))
parser.add_option("-u", "--update", dest = "update",
action = "store_true", default = False,
help = _("Check for and download updated device " \
"presets if they are available"))
parser.add_option("--install-preset", dest = "install",
action = "store_true", default=False,
help = _("Install a downloaded device preset file"))
options, args = parser.parse_args()
logging.basicConfig(level = options.verbose and logging.DEBUG \
or logging.INFO, format = "%(name)s [%(lineno)d]: " \
"%(levelname)s %(message)s")
# FIXME: OMGWTFBBQ gstreamer hijacks sys.argv unless we import AFTER we use
# the optionparser stuff above...
# This seems to be fixed http://bugzilla.gnome.org/show_bug.cgi?id=425847
# but in my testing it is NOT. Leaving hacks for now.
import gst
arista.init()
from arista.transcoder import TranscoderOptions
lc_path = arista.utils.get_path("locale", default = "")
if lc_path:
if hasattr(gettext, "bindtextdomain"):
gettext.bindtextdomain("arista", lc_path)
if hasattr(locale, "bindtextdomain"):
locale.bindtextdomain("arista", lc_path)
if hasattr(gettext, "bind_textdomain_codeset"):
gettext.bind_textdomain_codeset("arista", "UTF-8")
if hasattr(locale, "bind_textdomain_codeset"):
locale.bind_textdomain_codeset("arista", "UTF-8")
if hasattr(gettext, "textdomain"):
gettext.textdomain("arista")
if hasattr(locale, "textdomain"):
locale.textdomain("arista")
devices = arista.presets.get()
if options.info and not args:
print _("Available devices:")
print
longest = 0
for name in devices:
longest = max(longest, len(name))
for name in sorted(devices.keys()):
print _("%(name)s: %(description)s") % {
"name": name.rjust(longest + 1),
"description": devices[name].description,
}
print
print _("Use --info device_name for more information on a device.")
raise SystemExit()
elif options.info:
print _("Preset info:")
print
device = devices[args[0]]
info = [
(_("ID:"), args[0]),
(_("Make:"), device.make),
(_("Model:"), device.model),
(_("Description:"), device.description),
(_("Author:"), unicode(device.author)),
(_("Version:"), device.version),
(_("Presets:"), ", ".join([(p.name == device.default and "*" + p.name or p.name) for (id, p) in device.presets.items()])),
]
longest = 0
for (attr, value) in info:
longest = max(longest, len(attr))
for (attr, value) in info:
print "%(attr)s %(value)s" % {
"attr": attr.rjust(longest + 1),
"value": value,
}
print
raise SystemExit()
elif options.source_info:
if len(args) != 1:
print _("You may only pass one filename for --source-info!")
parser.print_help()
raise SystemExit(1)
def _got_info(info, is_media):
discoverer.print_info()
loop.quit()
discoverer = arista.discoverer.Discoverer(args[0])
discoverer.connect("discovered", _got_info)
discoverer.discover()
print _("Discovering file info...")
loop = gobject.MainLoop()
loop.run()
elif options.update:
# Update the local presets to the latest versions
arista.presets.check_and_install_updates()
elif options.install:
for arg in args:
arista.presets.extract(open(arg))
else:
if len(args) < 1:
parser.print_help()
raise SystemExit(1)
device = devices[options.device]
if not options.preset:
preset = device.presets[device.default]
else:
for (id, preset) in device.presets.items():
if preset.name == options.preset:
break
if options.crop:
for c in options.crop:
if c < 0:
print _("All parameters to --crop/-c must be non negative integers. %i is negative, aborting.") % c
raise SystemExit()
outputs = []
queue = arista.queue.TranscodeQueue()
for arg in args:
if len(args) == 1 and options.output:
output = options.output
else:
output = arista.utils.generate_output_path(arg, preset,
to_be_created=outputs, device_name=options.device)
outputs.append(output)
opts = TranscoderOptions(arg, preset, output,
ssa=options.ssa,
subfile = options.subtitle,
subfile_charset = options.subtitle_encoding,
font = options.font,
crop = options.crop)
queue.append(opts)
queue.connect("entry-start", entry_start, options)
queue.connect("entry-pass-setup", entry_pass_setup, options)
queue.connect("entry-error", entry_error, options)
queue.connect("entry-complete", entry_complete, options)
if len(queue) > 1:
print _("Processing %(job_count)d jobs...") % {
"job_count": len(queue),
}
signal.signal(signal.SIGINT, signal_handler)
gobject.timeout_add(50, check_interrupted)
loop = gobject.MainLoop()
loop.run()