/
presets.py
648 lines (558 loc) · 22.2 KB
/
presets.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
#!/usr/bin/env python
"""
Arista Presets
==============
Objects for handling devices, presets, etc.
Example Use
-----------
Presets are automatically loaded when the module is initialized.
>>> import arista.presets
>>> arista.presets.get()
{ "name": Device, ... }
If you have other paths to load, use:
>>> arista.presets.load("file")
>>> arista.presets.load_directory("path")
License
-------
Copyright 2008 - 2011 Daniel G. Taylor <dan@programmer-art.org>
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/>.
"""
try:
import json
except ImportError:
import simplejson as json
import gettext
import shutil
import logging
import os
import subprocess
import sys
import tarfile
import urllib2
import gobject
import gst
import gst.pbutils
import utils
_ = gettext.gettext
_presets = {}
_log = logging.getLogger("arista.presets")
class Fraction(gst.Fraction):
"""
An object for storing a fraction as two integers. This is a subclass
of gst.Fraction that allows initialization from a string representation
like "1/2".
"""
def __init__(self, value = "1"):
"""
@type value: str
@param value: Either a single number or two numbers separated by
a '/' that represent a fraction
"""
parts = str(value).split("/")
if len(parts) == 1:
gst.Fraction.__init__(self, int(value), 1)
elif len(parts) == 2:
gst.Fraction.__init__(self, int(parts[0]), int(parts[1]))
else:
raise ValueError(_("Not a valid integer or fraction: %(value)s!") % {
"value": value,
})
class Author(object):
"""
An author object that stores a name and an email.
"""
def __init__(self, name = "", email = ""):
"""
@type name: str
@param name: The author's full name
@type email: str
@param email: The email address of the author
"""
self.name = name
self.email = email
def __repr__(self):
return (self.name or self.email) and "%s <%s>" % (self.name, self.email) or ""
class Device(object):
"""
A device holds information about a product and several presets for that
product. This includes the make, model, version, etc.
"""
def __init__(self, make = "Generic", model = "", description = "",
author = None, version = "", presets = None, icon = "",
default = ""):
"""
@type make: str
@param make: The make of the product, e.g. Apple
@type model: str
@param model: The model of the product, e.g. iPod
@type description: str
@param description: A user-friendly description of these presets
@type author: Author
@param author: The author of these presets
@type version: str
@param version: The version of these presets (not the product)
@type presets: dict
@param presets: A dictionary of presets where the keys are the
preset names
@type icon: str
@param icon: A URI to an icon. Only file:// and stock:// are
allowed, where stock refers to a GTK stock icon
@type default: str
@param default: The default preset name to use (if blank then the
first available preset is used)
"""
self.make = make
self.model = model
self.description = description
if author is not None:
self.author = author
else:
self.author = Author()
self.version = version
self.presets = presets and presets or {}
self.icon = icon
self.default = default
self.filename = None
def __repr__(self):
return "%s %s" % (self.make, self.model)
@property
def name(self):
"""
Get a friendly name for this device.
@rtype: str
@return: Either the make and model or just the model of the device
for generic devices
"""
if self.make == "Generic":
return self.model
else:
return "%s %s" % (self.make, self.model)
@property
def short_name(self):
"""
Return the short name of this device preset.
"""
return ".".join(os.path.basename(self.filename).split(".")[:-1])
@property
def default_preset(self):
"""
Get the default preset for this device. If no default has been
defined, the first preset that was loaded is returned. If no
presets have been defined an exception is raised.
@rtype: Preset
@return: The default preset for this device
@raise ValueError: No presets have been defined for this device
"""
if self.default in self.presets:
preset = self.presets[self.default]
elif len(self.presets):
preset = self.presets.values()[0]
else:
raise ValueError(_("No presets have been defined for " \
"%(name)s") % { "name": self.name })
return preset
@property
def json(self):
data = {
"make": self.make,
"model": self.model,
"description": self.description,
"author": {
"name": self.author.name,
"email": self.author.email,
},
"version": self.version,
"icon": self.icon,
"default": self.default,
"presets": [],
}
for name, preset in self.presets.items():
rates = []
for x in preset.acodec.rate[0], preset.acodec.rate[1], preset.vcodec.rate[0], preset.vcodec.rate[1]:
if isinstance(x, gst.Fraction):
if x.denom == 1:
rates.append("%s" % x.num)
else:
rates.append("%s/%s" % (x.num, x.denom))
else:
rates.append("%s" % x)
data["presets"].append({
"name": preset.name,
"description": preset.description,
"author": {
"name": preset.author.name,
"email": preset.author.email,
},
"container": preset.container,
"extension": preset.extension,
"icon": preset.icon,
"version": preset.version,
"acodec": {
"name": preset.acodec.name,
"container": preset.acodec.container,
"rate": [rates[0], rates[1]],
"passes": preset.acodec.passes,
"width": preset.acodec.width,
"depth": preset.acodec.depth,
"channels": preset.acodec.channels,
},
"vcodec": {
"name": preset.vcodec.name,
"container": preset.vcodec.container,
"rate": [rates[2], rates[3]],
"passes": preset.vcodec.passes,
"width": preset.vcodec.width,
"height": preset.vcodec.height,
"transform": preset.vcodec.transform,
},
})
return json.dumps(data, indent=4)
def save(self):
"""
Save this device and its presets to a file. The device.filename must
be set to a valid path or an error will be thrown.
"""
open(self.filename, "w").write(self.json)
def export(self, filename):
"""
Export this device and all presets to a file. Creates a bzipped
tarball of the JSON and all associated images that can be easily
imported later.
"""
# Make sure all changes are saved
self.save()
# Gather image files
images = set()
for name, preset in self.presets.items():
if preset.icon:
images.add(preset.icon[7:])
files = " ".join([os.path.basename(self.filename)] + list(images))
cwd = os.getcwd()
os.chdir(os.path.dirname(self.filename))
subprocess.call("tar -cjf %s %s" % (filename, files), shell=True)
os.chdir(cwd)
@staticmethod
def from_json(data):
parsed = json.loads(data)
device = Device(**{
"make": parsed.get("make", "Generic"),
"model": parsed.get("model", ""),
"description": parsed.get("description", ""),
"author": Author(
name = parsed.get("author", {}).get("name", ""),
email = parsed.get("author", {}).get("email", ""),
),
"version": parsed.get("version", ""),
"icon": parsed.get("icon", ""),
"default": parsed.get("default", ""),
})
for preset in parsed.get("presets", []):
acodec = preset.get("acodec", {})
vcodec = preset.get("vcodec", {})
device.presets[preset.get("name", "")] = Preset(**{
"name": preset.get("name", ""),
"description": preset.get("description", device.description),
"author": Author(
name = preset.get("author", {}).get("name", device.author.name),
email = preset.get("author", {}).get("email", device.author.email),
),
"container": preset.get("container", ""),
"extension": preset.get("extension", ""),
"version": preset.get("version", device.version),
"icon": preset.get("icon", device.icon),
"acodec": AudioCodec(**{
"name": acodec.get("name", ""),
"container": acodec.get("container", ""),
"rate": [int(x) for x in acodec.get("rate", [])],
"passes": acodec.get("passes", []),
"width": acodec.get("width", []),
"depth": acodec.get("depth", []),
"channels": acodec.get("channels", []),
}),
"vcodec": VideoCodec(**{
"name": vcodec.get("name", ""),
"container": vcodec.get("container", ""),
"rate": [Fraction(x) for x in vcodec.get("rate", [])],
"passes": vcodec.get("passes", []),
"width": vcodec.get("width", []),
"height": vcodec.get("height", []),
"transform": vcodec.get("transform", ""),
}),
"device": device,
})
return device
class Preset(object):
"""
A preset representing audio and video encoding options for a particular
device.
"""
def __init__(self, name = "", container = "", extension = "",
acodec = None, vcodec = None, device = None, icon = None,
version = None, description = None, author = None):
"""
@type name: str
@param name: The name of the preset, e.g. "High Quality"
@type container: str
@param container: The container element name, e.g. ffmux_mp4
@type extension: str
@param extension: The filename extension to use, e.g. mp4
@type acodec: AudioCodec
@param acodec: The audio encoding settings
@type vcodec: VideoCodec
@param vcodec: The video encoding settings
@type device: Device
@param device: A link back to the device this preset belongs to
"""
self.name = name
self.description = description
self.author = author
self.container = container
self.extension = extension
self.acodec = acodec
self.vcodec = vcodec
self.device = device
self.version = version
self.icon = icon
def __repr__(self):
return "%s %s" % (self.name, self.container)
@property
def pass_count(self):
"""
@rtype: int
@return: The number of passes in this preset
"""
return max(len(self.vcodec.passes), len(self.acodec.passes))
@property
def slug(self):
"""
@rtype: str
@return: A slug based on the preset name safe to use as a filename
or in links
"""
slug = ".".join(os.path.basename(self.device.filename).split(".")[:-1]) + "-" + self.name.lower()
return slug.replace(" ", "_").replace("'", "").replace("/", "")
def check_elements(self, callback, *args):
"""
Check the elements used in this preset. If they don't exist then
let GStreamer offer to install them.
@type callback: callable(preset, success, *args)
@param callback: A method to call when the elements are all
available or installation failed
@rtype: bool
@return: True if required elements are available, False otherwise
"""
elements = [
# Elements defined in external files
self.container,
self.acodec.name,
self.vcodec.name,
# Elements used internally
"decodebin2",
"videobox",
"ffmpegcolorspace",
"videoscale",
"videorate",
"ffdeinterlace",
"audioconvert",
"audiorate",
"audioresample",
"tee",
"queue",
]
missing = []
missingdesc = ""
for element in elements:
if not gst.element_factory_find(element):
missing.append(gst.pbutils.missing_element_installer_detail_new(element))
if missingdesc:
missingdesc += ", %s" % element
else:
missingdesc += element
if missing:
_log.info("Attempting to install elements: %s" % missingdesc)
if gst.pbutils.install_plugins_supported():
def install_done(result, null):
if result == gst.pbutils.INSTALL_PLUGINS_INSTALL_IN_PROGRESS:
# Ignore start of installer message
pass
elif result == gst.pbutils.INSTALL_PLUGINS_SUCCESS:
callback(self, True, *args)
else:
_log.error("Unable to install required elements!")
callback(self, False, *args)
context = gst.pbutils.InstallPluginsContext()
gst.pbutils.install_plugins_async(missing, context,
install_done, "")
else:
_log.error("Installing elements not supported!")
gobject.idle_add(callback, self, False, *args)
else:
gobject.idle_add(callback, self, True, *args)
class Codec(object):
"""
Settings for encoding audio or video. This object defines options
common to both audio and video encoding.
"""
def __init__(self, name=None, container=None, passes=None):
"""
@type name: str
@param name: The name of the encoding GStreamer element, e.g. faac
@type container: str
@param container: A container to fall back to if only audio xor
video is present, e.g. for plain mp3 audio you
may not want to wrap it in an avi or mp4; if not
set it defaults to the preset container
"""
self.name = name and name or ""
self.container = container and container or ""
self.passes = passes and passes or []
self.rate = (Fraction(), Fraction())
def __repr__(self):
return "%s %s" % (self.name, self.container)
class AudioCodec(Codec):
"""
Settings for encoding audio.
"""
def __init__(self, name=None, container=None, rate=None, passes=None, width=None, depth=None, channels=None):
Codec.__init__(self, name=name, container=container, passes=passes)
self.rate = rate and rate or (8000, 96000)
self.width = width and width or (8, 24)
self.depth = depth and depth or (8, 24)
self.channels = channels and channels or (1, 6)
class VideoCodec(Codec):
"""
Settings for encoding video.
"""
def __init__(self, name=None, container=None, rate=None, passes=None, width=None, height=None, transform=None):
Codec.__init__(self, name=name, container=container, passes=passes)
self.rate = rate and rate or (Fraction("1"), Fraction("60"))
self.width = width and width or (2, 1920)
self.height = height and height or (2, 1080)
self.transform = transform
def load(filename):
"""
Load a filename into a new Device.
@type filename: str
@param filename: The file to load
@rtype: Device
@return: A new device instance loaded from the file
"""
device = Device.from_json(open(filename).read())
device.filename = filename
_log.debug(_("Loaded device %(device)s (%(presets)d presets)") % {
"device": device.name,
"presets": len(device.presets),
})
return device
def load_directory(directory):
"""
Load an entire directory of device presets.
@type directory: str
@param directory: The path to load
@rtype: dict
@return: A dictionary of all the loaded devices
"""
global _presets
for filename in os.listdir(directory):
if filename.endswith("json"):
try:
_presets[filename[:-5]] = load(os.path.join(directory, filename))
except Exception, e:
_log.warning("Problem loading %s! %s" % (filename, str(e)))
return _presets
def get():
"""
Get all loaded device presets.
@rtype: dict
@return: A dictionary of Device objects where the keys are the short
name for the device
"""
return _presets
def version_info():
"""
Generate a string of version information. Each line contains
"name, version" for a particular preset file, where name is the key
found in arista.presets.get().
This is used for checking for updates.
"""
info = ""
for name, device in _presets.items():
info += "%s, %s\n" % (name, device.version)
return info
def extract(stream):
"""
Extract a preset file into the user's local presets directory.
@type stream: a file-like object
@param stream: The opened bzip2-compressed tar file of the preset
@rtype: list
@return: The installed device preset shortnames ["name1", "name2", ...]
"""
local_path = os.path.expanduser(os.path.join("~", ".arista", "presets"))
if not os.path.exists(local_path):
os.makedirs(local_path)
tar = tarfile.open(mode="r|bz2", fileobj=stream)
_log.debug(_("Extracting %(filename)s") % {
"filename": hasattr(stream, "name") and stream.name or "data stream",
})
tar.extractall(path=local_path)
return [x[:-5] for x in tar.getnames() if x.endswith(".json")]
def fetch(location, name):
"""
Attempt to fetch and install a preset. Presets are always installed
to ~/.arista/presets/.
@type location: str
@param location: The location of the preset
@type name: str
@param name: The name of the preset to fetch, without any extension
@rtype: list
@return: The installed device preset shortnames ["name1", "name2", ...]
"""
if not location.endswith("/"):
location = location + "/"
path = location + name + ".tar.bz2"
_log.debug(_("Fetching %(location)s") % {
"location": path,
})
updated = []
try:
f = urllib2.urlopen(path)
updated += extract(f)
except Exception, e:
_log.warning(_("There was an error fetching and installing " \
"%(location)s: %(error)s") % {
"location": path,
"error": str(e),
})
return updated
def reset(overwrite=False, ignore_initial=False):
# Automatically load presets
global _presets
_presets = {}
load_path = utils.get_write_path("presets")
if ignore_initial or not os.path.exists(os.path.join(load_path, ".initial_complete")):
# Do initial population of presets from system install / cwd
if not os.path.exists(load_path):
os.makedirs(load_path)
# Write file to say we have done this
open(os.path.join(load_path, ".initial_complete"), "w").close()
# Copy actual files
for path in utils.get_search_paths():
full = os.path.join(path, "presets")
if full != load_path and os.path.exists(full):
for f in os.listdir(full):
# Do not overwrite existing files
if overwrite or not os.path.exists(os.path.join(load_path, f)):
shutil.copy2(os.path.join(full, f), load_path)
load_directory(load_path)
reset()