-
Notifications
You must be signed in to change notification settings - Fork 3
/
Transcoder.php
674 lines (566 loc) · 21.9 KB
/
Transcoder.php
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
673
674
<?php
namespace AC\Transcoding;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\Event;
use AC\Transcoding\Event\TranscodeEvents;
use AC\Transcoding\Event\TranscodeEvent;
use AC\Transcoding\Event\FileEvent;
/**
* Main transcoding class. Standardizes input/output before executing a transcode process via an adapter.
*
* @package Transcoding
* @author Evan Villemez
*/
class Transcoder
{
/**
* The general version for the library, stored as a constant here as this object is the main entry point.
*/
const VERSION = "0.3.0";
/**
* If a file already exists, remove the pre-existing file before initiating the transcode
*/
const ONCONFLICT_DELETE = 1;
/**
* If a file already exists, throw an exception.
*/
const ONCONFLICT_EXCEPTION = 2;
/**
* If file already exists, create a derivative file path with numerical increment to avoid conflicts.
*/
const ONCONFLICT_INCREMENT = 3;
/**
* If a transcode process fails, delete any newly created files
*/
const ONFAIL_DELETE = 1;
/**
* If the transcode process fails, keep any created files
*/
const ONFAIL_PRESERVE = 2;
/**
* If the transcode requires creating a directory, create the necessary directories recursively
*/
const ONDIR_CREATE = 1;
/**
* If the transcode requires creating a directory, fail with exception
*/
const ONDIR_EXCEPTION = 2;
/**
* The octal file creation mode to set for any files created during a transcode process
*
* @var octal
*/
protected $fileCreationMode = 0644;
/**
* The octal directory creation mode to set for any directories created during the transcode process
*
* @var octal
*/
protected $directoryCreationMode = 0755;
/**
* Storage array of registered adapters
*
* Format is hash of adapter_name => object
*
* @var array
*/
protected $adapters = array();
/**
* Storage array of registered presets
*
* Format is hash of preset_name => object
*
* @var array
*/
protected $presets = array();
/**
* Dispatcher for events notified by the Transcoder
*
* @var EventDispatcher
*/
private $dispatcher;
/**
* Constructor. EventDispatcher can be injected, otherwise builds a default.
*
* @param EventDispatcher $dispatcher
*/
public function __construct(EventDispatcherInterface $dispatcher = null)
{
$this->dispatcher = $dispatcher;
if (!$this->dispatcher) {
$this->dispatcher = new EventDispatcher();
}
}
/**
* The core method of the transcode process. Takes file input, validates, runs a transcode process, validates return, and returns file output.
*
* @param mixed $inFile - if a string filepath is given instead of an instance of \AC\Transcoding\File, then a new File instance will be created automatically
* @param mixed $preset - if a string is given instead of an instance of \AC\Transcoding\Preset, then it will look for a Preset with a name matching the received string
* @param string $outFile - an optional output file path, even if provided explicity, the Transcoder will validate and process it before starting a transcode process
* @param string $conflictMode - flag for what to do if an output file already exists at the given output path
* @param string $failMode - flag for what to do with the output file(s) on a failed transcode
* @return File - \AC\Transcoding\File instance for newly created file
*/
public function transcodeWithPreset($inFile, $preset, $outFile = false, $conflictMode = self::ONCONFLICT_INCREMENT, $dirMode = self::ONDIR_EXCEPTION, $failMode = self::ONFAIL_DELETE)
{
//figure out input file path and preset key, without throwing exceptions
$inputPath = ($inFile instanceof File) ? $inFile->getRealPath() : $inFile;
$presetKey = ($preset instanceof Preset) ? $preset->getKey() : $preset;
$outFilePath = $outFile;
//validate all inputs before attempting to run the transcode process
try {
//get file
if (!$inFile instanceof File && is_string($inFile)) {
$inFile = new File($inFile);
}
//get preset
if (!$preset instanceof Preset) {
$preset = $this->getPreset($preset);
}
//have preset validate file
$preset->validateInputFile($inFile);
//get adapter
$adapter = $this->getAdapter($preset->getRequiredAdapter());
//verify if this adapter can work in the current environment (happens only the first time it's loaded)
if (!$adapter->verify()) {
throw new \RuntimeException($adapter->getVerificationError());
}
//have adapter verify inputs
$adapter->validateInputFile($inFile);
$adapter->validatePreset($preset);
//generate the final output string
$outFilePath = $preset->generateOutputPath($inFile, $outFile);
//make sure the output path is valid, create any directories as necessary
$outFilePath = $this->processOutputFilepath($outFilePath, $conflictMode, $dirMode);
} catch (\Exception $e) {
//notify listeners of failure
$this->dispatcher->dispatch(TranscodeEvents::ERROR, new TranscodeEvent($inputPath, $presetKey, $outFilePath, null, $e));
//rethrow for containing environment to handle
throw $e;
}
//attempt to run the actual transcode process
try {
//notify listeners of transcode start
$this->dispatcher->dispatch(TranscodeEvents::BEFORE, new TranscodeEvent($inputPath, $presetKey, $outFilePath));
//run the transcode
$return = $adapter->transcodeFile($inFile, $preset, $outFilePath);
//validate return
if (!$return instanceof File) {
throw new Exception\InvalidOutputException("Adapters must return an instance of AC\Transcoding\File, or throw an exception upon error.");
}
$preset->validateOutputFile($return);
$adapter->validateOutputFile($return);
$this->cleanOutputFile($return);
$returnPath = $return->getRealPath();
//notify listeners of completion
$this->dispatcher->dispatch(TranscodeEvents::AFTER, new TranscodeEvent($inputPath, $presetKey, $returnPath));
//notify of new file
$this->dispatcher->dispatch(TranscodeEvents::FILE_CREATED, new FileEvent($returnPath));
//return newly created file
return $return;
} catch (\Exception $e) {
//clean up files after failure
$this->cleanFailedTranscode($adapter, $outFilePath, $failMode);
//notify listeners of failure
$this->dispatcher->dispatch(TranscodeEvents::ERROR, new TranscodeEvent($inputPath, $presetKey, $outFilePath, null, $e));
//re-throw exception so environment can handle appropriately
throw $e;
}
return false;
}
/**
* Transcode a file with a specific adapter directly. Internally builds a dynamic preset with the specified options.
*
* @param mixed $inFile - either string filepath or instance of \AC\Transcoding\File
* @param string $adapterName - string name of adapter to use
* @param array $options - key/val option hash to pass to adapter
* @param string $outFile - optional output file path, if not provided will be derived automatically by the Transcoder
* @param string $conflictMode - flag for how to handle output file conflicts
* @param string $failMode - flag for how to handle failed transcodes
* @return \AC\Transcoding\File
*/
public function transcodeWithAdapter($inFile, $adapterName, $options = array(), $outFile = false, $conflictMode = self::ONCONFLICT_INCREMENT, $dirMode = self::ONDIR_EXCEPTION, $failMode = self::ONFAIL_DELETE)
{
//build a preset on the fly based on the options provided
$preset = new Preset('dynamic', $adapterName, $options);
return $this->transcodeWithPreset($inFile, $preset, $outFile, $conflictMode, $dirMode, $failMode);
}
/**
* Retrieve the outfile path of a hypothetical transcode process
*/
public function getOutfilePath($inFile, $preset, $outFile = false, $conflictMode = self::ONCONFLICT_INCREMENT, $dirMode = self::ONDIR_EXCEPTION, $failMode = self::ONFAIL_DELETE)
{
//figure out input file path and preset key, without throwing exceptions
$inputPath = ($inFile instanceof File) ? $inFile->getRealPath() : $inFile;
$presetKey = ($preset instanceof Preset) ? $preset->getKey() : $preset;
$outFilePath = $outFile;
//validate all inputs before attempting to run the transcode process
try {
//get file
if (!$inFile instanceof File && is_string($inFile)) {
$inFile = new File($inFile);
}
//get preset
if (!$preset instanceof Preset) {
$preset = $this->getPreset($preset);
}
//have preset validate file
$preset->validateInputFile($inFile);
//get adapter
$adapter = $this->getAdapter($preset->getRequiredAdapter());
//verify if this adapter can work in the current environment (happens only the first time it's loaded)
if (!$adapter->verify()) {
throw new \RuntimeException($adapter->getVerificationError());
}
//have adapter verify inputs
$adapter->validateInputFile($inFile);
$adapter->validatePreset($preset);
//generate the final output string
$outFilePath = $preset->generateOutputPath($inFile, $outFile);
//make sure the output path is valid, create any directories as necessary
$outFilePath = $this->processOutputFilepath($outFilePath, $conflictMode, $dirMode);
} catch (\Exception $e) {
//notify listeners of failure
$this->dispatch(TranscodeEvents::ERROR, new TranscodeEvent($inputPath, $presetKey, $outFilePath, null, $e));
//rethrow for containing environment to handle
throw $e;
}
return $outFilePath;
}
/**
* Scan an output path to make sure there are no conflicts. Handle conflicts according to mode. Check to make sure final path is actually writable.
* Returns the final output path, which may have been altered depending on the mode.
*
* @param string $outputPath
* @param string $conflictMode
* @param string $dirMode
* @return string
*/
protected function processOutputFilepath($outputPath, $conflictMode, $dirMode)
{
$outputIsDirectory = $this->pathIsDirectory($outputPath);
//check for pre-existing file and handle based on conflict mode
if (file_exists($outputPath)) {
if ($conflictMode === self::ONCONFLICT_EXCEPTION) {
throw new Exception\FileAlreadyExistsException(sprintf("File %s already exists.", $outputPath));
}
if ($conflictMode === self::ONCONFLICT_DELETE) {
if ($outputIsDirectory) {
$this->removeDirectory($outputPath);
} else {
@unlink($outputPath);
}
}
if ($conflictMode === self::ONCONFLICT_INCREMENT) {
$outputPath = $this->incrementConflictingPath($outputPath);
}
}
//check for necessary containing directory creation, handle based on directory mode
$outputDirectory = dirname($outputPath);
if (!file_exists($outputDirectory)) {
if ($dirMode === self::ONDIR_EXCEPTION) {
throw new Exception\InvalidModeException("The Transcoder is not permitted to create new directories if needed.");
}
//try creating the necessary containing directories recursively
if (!mkdir($outputDirectory, $this->getDirectoryCreationMode(), true)) {
throw new Exception\FilePermissionException("The required containing directories could not be created.");
}
$this->dispatcher->dispatch(TranscodeEvents::DIR_CREATED, new FileEvent($outputDirectory));
}
//check for write permissions
if (!is_writable($outputDirectory)) {
throw new Exception\FilePermissionException(sprintf("Cannot transcode because the directory %s is not writable.", $outputDirectory));
}
//if the output is a directory, make sure the actual required directory is created
if ($outputIsDirectory) {
if (!mkdir($outputPath, $this->getDirectoryCreationMode())) {
throw new Exception\FilePermissionException(sprintf("Could not properly create the required output directory %s.", $outputPath));
}
$this->dispatcher->dispatch(TranscodeEvents::DIR_CREATED, new FileEvent($outputDirectory));
}
return $outputPath;
}
/**
* If a previous file exists, create a new path, numerically incrementing a number in the string to avoid conflicts.
*
* @param string $path
* @return string
*/
protected function incrementConflictingPath($path)
{
$isDir = $this->pathIsDirectory($path);
$expPath = explode(DIRECTORY_SEPARATOR, $path);
$oldFileName = array_pop($expPath);
$basePath = implode(DIRECTORY_SEPARATOR, $expPath);
if ($isDir) {
//for directories append incremented number after underscore
$i = 1;
while (file_exists($newFileName = $basePath.DIRECTORY_SEPARATOR.$oldFileName."_".$i)) {
$i++;
}
} else {
//for files insert incremented number between filename and extension
$exp = explode(".", $oldFileName);
$extension = array_pop($exp);
$name = implode(".", $exp);
$i = 1;
while (file_exists($newFileName = $basePath.DIRECTORY_SEPARATOR.$name.".".$i.".".$extension)) {
$i++;
}
}
return $newFileName;
}
/**
* Remove a directory and all of its contents
*
* @param string $path
* @return void
*/
protected function removeDirectory($path)
{
foreach (scandir($path) as $item) {
if (!in_array($item, array('.','..'))) {
@unlink($path.DIRECTORY_SEPARATOR.$item);
$this->dispatcher->dispatch(TranscodeEvents::DIR_REMOVED, new FileEvent($outputPath));
}
}
if (!rmdir($path)) {
throw new Exception\FilePermissionException(sprintf("Could not remove directory %s", $path));
}
}
/**
* Return boolean if a given path is likely a directory (this isn't just for pre-existing files)
*
* @param string $path
* @return boolean true or false
*/
protected function pathIsDirectory($path)
{
$exp = explode(DIRECTORY_SEPARATOR, $path);
$name = end($exp);
$exp = explode(".", $name);
return !(count($exp) >= 2);
}
/**
* Post process newly created files by setting proper file permissions based on set permission modes
*
* @param File $file
* @return void
*/
protected function cleanOutputFile(File $file)
{
$path = $file->getRealPath();
if ($file->isDir()) {
chmod($path, $this->getDirectoryCreationMode());
$this->dispatcher->dispatch(TranscodeEvents::DIR_MODIFIED, new FileEvent($path));
} else {
chmod($path, $this->getFileCreationMode());
$this->dispatcher->dispatch(TranscodeEvents::FILE_MODIFIED, new FileEvent($path));
}
}
/**
* Cleanup after a failed transcode - this may entail deleting newly created files, depending on the mode in which the transcode process executed
*
* This will also call the corresponding `Adapter::cleanFailedTranscode()` method for the adapter that was used.
*
* @param AC\Transcoding\Adapter $adapter
* @param string $outputFilePath
* @param string $failMode
* @return void
*/
protected function cleanFailedTranscode(Adapter $adapter, $outputFilePath, $failMode)
{
if (file_exists($outputFilePath)) {
if ($failMode === self::ONFAIL_DELETE) {
@unlink($outputFilePath);
$this->dispatcher->dispatch(TranscodeEvents::FILE_REMOVED, new FileEvent($outputFilePath));
}
}
$adapter->cleanFailedTranscode($outputFilePath);
}
/**
* Dispatch event, used by Adapters to notify adapter specific events
*
* @see EventDispatcher::dispatch
*/
public function dispatch($name, Event $e = null)
{
return $this->dispatcher->dispatch($name, $e);
}
/**
* Get the Transcoder's EventDispatcher
*
* @return EventDispatcher
*/
public function getDispatcher()
{
return $this->dispatcher;
}
/**
* Return an adapter instance by key
*
* @param string $key
* @return AC\Transcoding\Adapter on success, throws exception if not found
*/
public function getAdapter($key)
{
if (!isset($this->adapters[$key])) {
throw new Exception\AdapterNotFoundException(sprintf("Requested adapter %s was not found in the Transcoder.", $key));
}
return $this->adapters[$key];
}
/**
* Return true of Transcoder has an Adapter with the given key
*
* @param string $key
* @return boolean
*/
public function hasAdapter($key)
{
return isset($this->adapters[$key]);
}
/**
* Register an adapter instance with the Transcoder
*
* @param Adapter $adapter
* @return self
*/
public function registerAdapter(Adapter $adapter)
{
$adapter->setTranscoder($this);
$this->adapters[$adapter->getKey()] = $adapter;
return $this;
}
/**
* Remove an adapter instance with the given key from the Transcoder
*
* @param string $key
* @return self
*/
public function removeAdapter($key)
{
if (isset($this->adapters[$key])) {
$this->adapters[$key]->setTranscoder();
unset($this->adapters[$key]);
}
return $this;
}
/**
* Return array of all adapters registered with the Transcoder
*
* @return array
*/
public function getAdapters()
{
return $this->adapters;
}
/**
* Get a preset instance with the given key
*
* @param string $key
* @return AC\Transcoding\Preset
*/
public function getPreset($key)
{
if (!isset($this->presets[$key])) {
throw new Exception\PresetNotFoundException(sprintf("Requested preset %s was not found in the Transcoder.", $key));
}
return $this->presets[$key];
}
/**
* Return true if Preset with the given key is available
*
* @param string $key
* @return boolean
*/
public function hasPreset($key)
{
return isset($this->presets[$key]);
}
/**
* Register a new preset instance
*
* @param Preset $preset
* @return self
*/
public function registerPreset(Preset $preset)
{
$this->presets[$preset->getKey()] = $preset;
return $this;
}
/**
* Remove a preset with the given key
*
* @param string $key
* @return self
*/
public function removePreset($key)
{
if (isset($this->presets[$key])) {
unset($this->presets[$key]);
}
return $this;
}
/**
* Get array of all registered Presets
*
* @return array
*/
public function getPresets()
{
return $this->presets;
}
/**
* Set the file creation mode used when new files are created during a transcode process
*
* @return int (octal)
*/
public function getFileCreationMode()
{
return $this->fileCreationMode;
}
/**
* Set the file creation mode to use when new files are created during a transcode process.
*
* Note you can set the property as either a string or octal int, but it will always be converted to the octal format required by `chmod`
*
* @param string|int $mode
* @return self
*/
public function setFileCreationMode($mode)
{
//force format into octal if a string was received, for example "755" instead of 0755
if (0 != $mode[0]) {
$mode = "0".$mode;
}
$this->fileCreationMode = intval($mode, 8);
return $this;
}
/**
* Get the directory creation mode used when creating new directories.
*
* @return int (octal)
*/
public function getDirectoryCreationMode()
{
return $this->directoryCreationMode;
}
/**
* Set the file creation mode to use when new directories are created during a transcode process.
*
* Note you can set the property as either a string or octal int, but it will always be converted to the octal format required by `chmod`
*
* @param string|int $mode
* @return self
*/
public function setDirectoryCreationMode($mode)
{
//force format into octal if a string was received, for example "755" instead of 0755
if (0 != $mode[0]) {
$mode = "0".$mode;
}
$this->directoryCreationMode = intval($mode, 8);
return $this;
}
}