This repository has been archived by the owner on Apr 11, 2018. It is now read-only.
/
PMSEncoder.groovy
672 lines (549 loc) · 21.4 KB
/
PMSEncoder.groovy
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
@Typed
package com.chocolatey.pmsencoder
import net.pms.PMS
// if these extend Exception (rather than RuntimeException) Groovy(++?) wraps them in
// InvokerInvocationException, which causes all kinds of tedium.
// For the time being: extend RuntimeException - even though they're both checked
public class MatchFailureException extends RuntimeException { }
public class PMSEncoderException extends RuntimeException {
// grrr: get "cannot find constructor" errors without this (another GString issue?)
PMSEncoderException(String msg) {
super(msg)
}
}
// a long-winded way of getting Java Strings and Groovy GStrings to play nice
public class Stash extends LinkedHashMap<java.lang.String, java.lang.String> {
public Stash() {
super()
}
public Stash(Stash old) {
super()
old.each { key, value -> this.put(key.toString(), value.toString()) }
}
public Stash(Map<String, String> map) {
map.each { key, value -> this.put(key.toString(), value.toString()) }
}
public java.lang.String put(Object key, Object value) {
super.put(key.toString(), value.toString())
}
public java.lang.String get(Object key) {
super.get(key.toString())
}
}
/*
* this object encapsulates the input/output parameters passed from/to the PMS transcode launcher (Engine.java).
* Input parameters are stored in the Stash object's key/value pairs, specifically the executable, uri and output
* fields; and the output (a command) is returned via the same stash (i.e. the executable and URI can be overridden)
* as well as in a list of strings accessible via the args field
*/
public class Command extends Logger {
Stash stash
List<String> args
List<String> matches
private Command(Stash stash, List<String> args, List<String> matches) {
this.stash = stash
this.args = args
this.matches = matches
}
public Command() {
this(new Stash(), [], [])
}
public Command(Stash stash) {
this(stash, [])
}
public Command(List<String> args) {
this(new Stash(), args)
}
public Command(Stash stash, List<String> args) {
this(stash, args, [])
}
// convenience constructor: allow the stash to be supplied as a Map<String, String>
// e.g. new Command([ uri: uri ])
public Command(Map<String, String> map) {
this(new Stash(map), [], [])
}
// copy constructor (clone doesn't work in Groovy++)
public Command(Command other) {
this(new Stash(other.stash), new ArrayList<String>(other.args), new ArrayList<String>(other.matches))
}
public boolean equals(Command other) {
this.stash == other.stash && this.args == other.args && this.matches == other.matches
}
public java.lang.String toString() {
"{ stash: $stash, args: $args, matches: $matches }".toString()
}
// setter implementation with logged stash assignments
@Typed(TypePolicy.MIXED) // XXX try to handle GStrings
public String let(String name, String value) {
if ((stash[name] == null) || (stash[name] != value.toString())) {
log.info("setting $name to $value")
stash[name] = value
}
return value // for chaining: foo = bar = baz i.e. foo = (bar = baz)
}
}
class Matcher extends Logger {
private final Config config
Matcher(PMS pms) {
this.config = new Config(pms)
}
void load(String path) {
load(new File(path))
}
void load(File file) {
load(new FileInputStream(file))
}
void load(URL url) {
load(url.openStream())
}
void load(InputStream stream) {
load(new InputStreamReader(stream))
}
void load(Reader reader) {
// XXX squashed bug: don't drain the reader by logging its value!
Script script = new GroovyShell().parse(reader)
ExpandoMetaClass emc = new ExpandoMetaClass(script.class, false)
emc.setProperty('config', config.&config) // set the DSL's sole top-level method: config
emc.initialize()
script.metaClass = emc
script.run()
}
@Typed(TypePolicy.DYNAMIC) // XXX needed to handle GStrings
boolean match(Command command, boolean useDefault = true) {
if (useDefault) {
// watch out: there's a GString about
config.$DEFAULT_MENCODER_ARGS.each { command.args << it.toString() }
}
def matched = config.match(command) // we could use the @Delegate annotation, but this is cleaner/clearer
if (matched) {
log.debug("command: $command")
}
return matched
}
}
class Config extends Logger {
private final Map<String, Profile> profiles = [:] // defaults to LinkedHashMap
// DSL fields (mutable)
public List<String> $DEFAULT_MENCODER_ARGS = []
public List<Integer> $YOUTUBE_ACCEPT = []
public PMS $PMS
public Config(PMS pms) {
$PMS = pms
}
boolean match(Command command) {
log.info("matching URI: ${command.stash['$URI']}")
profiles.each { name, profile ->
if (profile.match(command)) {
command.matches << name
}
}
return command.matches.size() > 0
}
// DSL method
@Typed(TypePolicy.MIXED) // Groovy++ doesn't support delegation
void config(Closure closure) {
this.with(closure) // run at (config file) compile-time
}
// DSL method
@Typed(TypePolicy.MIXED) // Groovy++ doesn't support delegation
// a Profile consists of a name, a pattern block and an action block - all
// determined when the config file is loaded/compiled
void profile (String name, Closure closure) {
// run the profile block at compile-time to extract its pattern and action blocks,
// but invoke them at runtime
log.info("registering profile: $name")
Profile profile = new Profile(name, this)
try {
profile.extractBlocks(closure)
profiles[name] = profile
} catch (Throwable e) {
log.error("invalid profile ($name): " + e.getMessage());
}
}
}
// this holds a reference to the pattern and action, and isn't delegated to at runtime
class Profile extends Logger {
private final Config config
private Closure patternBlock
private Closure actionBlock
public final String name
Profile(String name, Config config) {
this.name = name
this.config = config
}
@Typed(TypePolicy.MIXED) // Groovy++ doesn't support delegation
void extractBlocks(Closure closure) {
def delegate = new CompileTimeProfileDelegate(config, name)
// wrapper method: runs the closure then validates the result, raising an exception if anything is amiss
delegate.runProfileBlock(closure)
// we made it without triggering an exception, so the two fields are sane: save them
this.patternBlock = delegate.patternBlock
this.actionBlock = delegate.actionBlock
}
// pulled out of the match method below so that type-softening is isolated
// note: keep it here rather than making it a method in Pattern: trying to keep the delegates
// clean (cf. Ruby's BlankSlate)
@Typed(TypePolicy.MIXED) // Groovy++ doesn't support delegation
boolean runPatternBlock(Pattern delegate) {
// pattern methods short-circuit matching on failure by throwing a MatchFailureException,
// so we need to wrap this in a try/catch block
try {
delegate.with(patternBlock)
} catch (MatchFailureException e) {
log.debug("pattern block: caught match exception")
// one of the match methods failed, so the whole block failed
return false
}
// success simply means "no match failure exception was thrown" - this also handles cases where the
// pattern block is empty.
log.debug("pattern block: matched OK")
return true
}
// pulled out of the match method below so that type-softening is isolated
// note: keep it here rather than making it a method in Action: trying to keep the delegates
// clean (cf. Ruby's BlankSlate)
@Typed(TypePolicy.MIXED) // Groovy++ doesn't support delegation
boolean runActionBlock(Action delegate) {
delegate.with(actionBlock)
}
boolean match(Command command) {
def newCommand = new Command(command) // clone() doesn't work with Groovy++
// the pattern block has its own command object (which is initially the same as the action block's).
// if the match succeeds, then the pattern block's stash is merged into the action block's stash.
// this ensures that a partial match (i.e. a failed match) with side-effects/bindings doesn't contaminate
// the action, and, more importantly, it defers logging until the whole pattern block has
// completed successfully
def pattern = new Pattern(config, newCommand)
log.info("matching $name")
// returns true if all matches in the block succeed, false otherwise
if (runPatternBlock(pattern)) {
// we can now merge any side-effects (currently only modifications to the stash).
// first merge (with logging)
newCommand.stash.each { name, value -> command.let(name, value) }
// now run the actions
def action = new Action(config, command)
runActionBlock(action)
return true
} else {
return false
}
}
}
// i.e. a delegate with access to a Config
public class ConfigDelegate extends Logger {
private Config config
public ConfigDelegate(Config config) {
this.config = config
}
// DSL properties
// $CONFIG: read-only
protected final Config get$CONFIG() {
config
}
// $PMS: read-only
protected final PMS get$PMS() {
config.$PMS
}
// DSL getter: $DEFAULT_MENCODER_ARGS
protected List<String> get$DEFAULT_MENCODER_ARGS() {
config.$DEFAULT_MENCODER_ARGS
}
// DSL setter: $DEFAULT_MENCODER_ARGS
protected List<String> get$DEFAULT_MENCODER_ARGS(List<String> args) {
config.$DEFAULT_MENCODER_ARGS = args
}
// DSL getter: $YOUTUBE_ACCEPT
protected List<String> get$YOUTUBE_ACCEPT() {
config.$YOUTUBE_ACCEPT
}
// DSL setter: $YOUTUBE_ACCEPT
protected List<String> get$YOUTUBE_ACCEPT(List<String> args) {
config.$YOUTUBE_ACCEPT = args
}
}
// i.e. a delegate with access to a Command
public class CommandDelegate extends ConfigDelegate {
private Command command
public CommandDelegate(Config config, Command command) {
super(config)
this.command = command
}
// DSL properties
// $command: read-only
protected Command get$command() {
command
}
// $stash: read-only
protected final Stash get$stash() {
command.stash
}
// DSL accessor ($ARGS): read-only
protected List<String> get$ARGS() {
command.args
}
// DSL accessor ($ARGS): read-write
@Typed(TypePolicy.DYNAMIC) // try to handle GStrings
// FIXME: test this!
protected List<String> set$ARGS(List<String> args) {
command.args = args.collect { it.toString() } // handle GStrings
}
// DSL accessor ($MATCHES): read-only
protected List<String> get$MATCHES() {
command.matches
}
// DSL getter
protected String propertyMissing(String name) throws PMSEncoderException {
def val = command.stash[name]
if (val == null) {
throw new PMSEncoderException("invalid property access: $name is not defined")
} else {
return val
}
}
// DSL setter
protected String propertyMissing(String name, Object value) {
command.let(name, value.toString())
}
}
class CompileTimeProfileDelegate extends ConfigDelegate {
public Closure patternBlock = null
public Closure actionBlock = null
public String name
CompileTimeProfileDelegate(Config config, String name) {
super(config)
this.name = name
}
// DSL method
private void pattern(Closure closure) throws PMSEncoderException {
if (this.patternBlock == null) {
this.patternBlock = closure
} else {
throw new PMSEncoderException("invalid profile ($name): multiple pattern blocks defined")
}
}
// DSL method
private void action(Closure closure) throws PMSEncoderException {
if (this.actionBlock == null) {
this.actionBlock = closure
} else {
throw new PMSEncoderException("invalid profile ($name): multiple action blocks defined")
}
}
@Typed(TypePolicy.MIXED) // Groovy++ doesn't support delegation
private runProfileBlock(Closure closure) throws PMSEncoderException {
this.with(closure)
if (patternBlock == null) {
throw new PMSEncoderException("invalid profile ($name): no pattern block defined")
}
if (actionBlock == null) {
throw new PMSEncoderException("invalid profile ($name): no action block defined")
}
}
}
class Pattern extends CommandDelegate {
private static final MatchFailureException STOP_MATCHING = new MatchFailureException()
Pattern(Config config, Command command) {
super(config, command)
}
// DSL setter - overrides the CommandDelegate method to avoid logging,
// which is handled later (if the match succeeds) by merging the pattern
// block's temporary stash
protected String propertyMissing(String name, Object value) {
$stash[name] = value
}
// DSL method
@Typed(TypePolicy.DYNAMIC) // XXX try to handle GStrings
void match(Map<String, String> map) {
map.each { name, value -> match(name, value) }
}
// DSL method
@Typed(TypePolicy.DYNAMIC) // XXX try to handle GStrings
void match(String name, String value) {
assert name && value
if ($stash[name] == null) { // this will happen for old custom configs that use let $URI: ...
log.warn("invalid match: $name is not defined")
// fall through
} else {
log.info("matching $name against $value")
if (RegexHelper.match($stash[name], value, $stash)) {
log.info("success")
return // abort default failure exception below
} else {
log.info("failure")
}
}
throw STOP_MATCHING
}
// DSL method
@Typed(TypePolicy.DYNAMIC) // XXX try to handle GStrings
void match(Closure closure) {
log.info("running match block")
if (closure()) {
log.info("success")
} else {
log.info("failure")
throw STOP_MATCHING
}
}
}
/* XXX: add configurable HTTP proxy support? */
class Action extends CommandDelegate {
private final Map<String, String> cache = [:]
@Lazy private HTTPClient http = new HTTPClient()
Action(Config config, Command command) {
super(config, command)
}
/*
1) get the URI pointed to by options['uri'] or stash['$URI'] (if it hasn't already been retrieved)
2) perform a regex match against the document
3) update the stash with any named captures
*/
// DSL method
@Typed(TypePolicy.MIXED) // XXX try to handle GStrings
void scrape(String regex, Map<String, String> options = [:]) {
def uri = options['uri'] ?: $stash['$URI']
def document = cache[uri]
def newStash = new Stash()
if (document == null) {
log.info("getting $uri")
document = cache[uri] = http.get(uri)
}
assert document != null
log.info("matching content of $uri against $regex")
if (RegexHelper.match(document, regex, newStash)) {
log.info("success")
newStash.each { name, value -> $command.let(name, value) }
} else {
log.info("failure")
}
}
// define a variable in the stash
// DSL method
@Typed(TypePolicy.DYNAMIC) // XXX try to handle GStrings
void let(Map<String, String> map) {
map.each { key, value ->
$command.let(key, value)
}
}
// DSL method
@Typed(TypePolicy.DYNAMIC) // XXX try to handle GStrings
void set(Map<String, String> map) {
// the sort order is predictable (for tests) as long as we (and Groovy) use LinkedHashMap
map.each { name, value -> setArg(name.toString(), value.toString()) }
}
// set an MEncoder option - create it if it doesn't exist
// DSL method
@Typed(TypePolicy.MIXED) // XXX try to handle GStrings
void setArg(String name, String value = null) {
assert name != null
def index = $ARGS.findIndexOf { it == name }
if (index == -1) {
if (value != null) {
log.info("adding $name $value")
/*
XXX squashed bug: careful not to perform operations on $stash or $command.args
that return and subsequenly operate on a new value
(i.e. make sure they're modified in place):
def args = $command.args
args += ... // XXX doesn't modify $command.args
*/
$ARGS << name << value
} else {
log.info("adding $name")
$ARGS << name
}
} else if (value != null) {
log.info("setting $name to $value")
$ARGS[ index + 1 ] = value
}
}
/*
perform a search-and-replace in the value of an MEncoder option
TODO: signature: handle null, a single map and an array of maps
*/
// DSL method
@Typed(TypePolicy.MIXED) // XXX try to handle GStrings
void tr(Map<String, Map<String, String>> replaceMap) {
// the sort order is predictable (for tests) as long as we (and Groovy) use LinkedHashMap
replaceMap.each { name, map ->
// squashed bug (see above): take care to $ARGS in-place
def index = $ARGS.findIndexOf { it == name }
if (index != -1) {
map.each { search, replace ->
log.info("replacing $search with $replace in $name")
// TODO support named captures
def value = $ARGS[ index + 1 ]
if (value) {
// XXX bugfix: strings are immutable!
$ARGS[ index + 1 ] = value.replaceAll(search, replace)
}
}
}
}
}
/*
given (in the stash) the $youtube_video_id and $youtube_t values of a YouTube stream URI
(i.e. the direct link to a video), construct the full URI with various $fmt values in
succession and set the stash $URI value to the first one that's valid (based on a HEAD request)
*/
// DSL method
@Typed(TypePolicy.MIXED) // XXX try to handle GStrings
void youtube(List<Integer> formats = $YOUTUBE_ACCEPT) {
def uri = $stash['$URI']
def video_id = $stash['youtube_video_id']
def t = $stash['youtube_t']
def found = false
assert video_id != null
assert t != null
$command.let('youtube_uri', uri)
if (formats.size() > 0) {
found = formats.any { fmt ->
def stream_uri = "http://www.youtube.com/get_video?fmt=$fmt&video_id=$video_id&t=$t&asv="
log.info("trying fmt $fmt: $stream_uri")
if (http.head(stream_uri)) {
log.info("success")
// set the new URI - note: use the low-level interface NOT the (deferred) DSL interface!
$command.let('$URI', stream_uri)
$command.let('youtube_fmt', fmt)
return true
} else {
log.info("failure")
return false
}
}
} else {
log.fatal("no formats defined for $uri")
}
if (!found) {
log.fatal("can't retrieve stream URI for $uri")
}
}
// DSL method: append a list of options to the command's args list
void append(List<String> args) {
$command.args += args
}
// DSL method: prepend a list of options to the command's args list
void prepend(List<String> args) {
$command.args = args + $ARGS
}
// private helper method containing code common to replace and remove
private boolean splice(List<String> args, String optionName, List<String> replaceList, int andFollowing = 0) {
def index = args.indexOf(optionName)
if (index == -1) {
log.warn("invalid splice: can't find $optionName in $args")
return false
} else {
log.info("setting ${args[ index .. (index + andFollowing) ]} to $replaceList")
args[ index .. (index + andFollowing) ] = replaceList
return true
}
}
// DSL method: remove an option (and optionally the following n arguments) from the command's arg list
void remove(String optionName, int andFollowing = 0) {
splice($ARGS, optionName, [], andFollowing)
}
// DSL method: replace an option (and optionally the following n arguments) with the supplied arg list
void replace(String optionName, List<String> replaceList, int andFollowing = 0) {
splice($ARGS, optionName, replaceList, andFollowing)
}
}