-
Notifications
You must be signed in to change notification settings - Fork 0
/
ffmpeg_wrapper.module
1366 lines (1220 loc) · 46.3 KB
/
ffmpeg_wrapper.module
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This implements a wrapper for FFmpeg so that we don't have to reinvent the
// the wheel every time we want to do something with video, audio, or images
/* ************************************************ */
/* DRUPAL HOOKS */
/* ************************************************ */
/**
* Implementation of hook_menu().
*/
function ffmpeg_wrapper_menu() {
$items = array();
$items['admin/settings/ffmpeg_wrapper'] = array(
'title' => 'FFmpeg Wrapper',
'page callback' => 'drupal_get_form',
'page arguments' => array('ffmpeg_wrapper_admin'),
'access arguments' => array('administer ffmpeg wrapper'),
);
$items[] = array(
'path' => 'admin/settings/ffmpeg_wrapper/default',
'title' => 'FFmpeg Wrapper',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
// hand back the specific configurations for a codec
$items['ffmpeg_wrapper/output'] = array(
'title' => 'FFmpeg Wrapper',
'page callback' => 'ffmpeg_wrapper_output_display',
'page arguments' => array(2),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
// testing utilities
$items['admin/settings/ffmpeg_wrapper/test'] = array(
'title' => t('FFmpeg Wrapper Test Conversion'),
'page callback' => 'drupal_get_form',
'page arguments' => array('ffmpeg_wrapper_ffmpeg_test_form'),
'type' => MENU_LOCAL_TASK,
'access arguments' => array('administer ffmpeg wrapper'),
'file' => 'ffmpeg_wrapper_test_convert.inc',
);
$items['admin/settings/ffmpeg_wrapper/test_cleanup'] = array(
'title' => 'FFmpeg Wrapper Test Cleanup',
'page callback' => 'drupal_get_form',
'page arguments' => array('ffmpeg_wrapper_test_cleanup_form'),
'type' => MENU_LOCAL_TASK,
'access arguments' => array('administer ffmpeg wrapper'),
'file' => 'ffmpeg_wrapper_test_convert.inc',
);
// hand back the specific configurations for a codec
$items['ffmpeg_wrapper/file_data'] = array(
'title' => 'FFmpeg Wrapper',
'page callback' => 'ffmpeg_wrapper_file_type_ahah',
'access arguments' => array('administer ffmpeg wrapper'),
'file' => 'ffmpeg_wrapper_test_convert.inc',
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implementation of hook_perm().
*/
function ffmpeg_wrapper_perm() {
return array('administer ffmpeg wrapper');
}
/**
* add a link to do conversion testing on the standard file display
* checks to make sure the file is usable by ffmpeg
*
* @param string $form_id
* @param array $form
*/
function ffmpeg_wrapper_form_alter(&$form, $form_state, $form_id) {
// if user does not have rights to test with ffmpeg
if (! user_access('administer ffmpeg wrapper')) {
return;
}
// Are there attached files?
if (isset($form['attachments']) && $files = $form['attachments']['wrapper']['files']) {
foreach ($files as $fid => $file) {
// check to make sure this is a file array and if this file is decodeable by ffmpeg
// we are dealing with a form element, so we have to make sure that this is the part that we want
if (is_array($file)) {
// can ffmpeg decode this?
if (ffmpeg_wrapper_can_decode($file['filepath']['#value'])) {
$arguments = array();
// are we on a node page? Add a $nid to the arguments
if ($nid = $form['#node']->nid) { $arguments[] = "nid=$nid"; }
// we need a path to the file to the arguments
$arguments[] = 'path='. $file['filepath']['#value'];
// create the link for test conversion
$link = '<br />'. l(t('Test convert file with FFmpeg'), 'admin/settings/ffmpeg_wrapper/test', array('query' => implode('&', $arguments)));
// now we alter the description of this item
$form['attachments']['wrapper']['files'][$fid]['description']['#description'] .= $link;
}
}
}
}
}
/**
* Implementation of Drupal 6's theme registry
* @return array
*/
function ffmpeg_wrapper_theme() {
return array(
'ffmpeg_wrapper_files_checkboxes' => array(
'arguments' => array('form' => NULL),
),
'ffmpeg_wrapper_files_radios' => array(
'arguments' => array('form' => NULL),
),
);
}
/* ************************************************ */
/* FFmpeg Wrapper Admin Functions */
/* ************************************************ */
/**
* Build the admin form.
*/
function ffmpeg_wrapper_admin() {
// always clear caches when if settings are updated
cache_clear_all('ffmpeg_wrapper_codecs', 'cache');
cache_clear_all('ffmpeg_wrapper_output_formats', 'cache');
cache_clear_all('ffmpeg_wrapper_file_formats', 'cache');
$form['ffmpeg_wrapper'] = array(
'#type' => 'fieldset',
'#title' => t('FFmpeg'),
);
$form['ffmpeg_wrapper']['ffmpeg_wrapper_path'] = array(
'#type' => 'textfield',
'#title' => t('FFmpeg path'),
'#default_value' => variable_get('ffmpeg_wrapper_path', '/usr/bin/ffmpeg'),
'#description' => t('Absolute path to the FFmpeg exeutable. Leave blank if you do not need this.'),
);
$form['ffmpeg_wrapper']['ffmpeg_wrapper_vhook'] = array(
'#type' => 'textfield',
'#title' => t('Path to the FFmpeg vhook libraries'),
'#default_value' => variable_get('ffmpeg_wrapper_vhook', '/usr/local/lib/vhook'),
'#description' => t('Absolute path to the FFmpeg vhook directory. No trailing slash. Leave blank if you do not need this'),
);
// configuration options
// only display if we can reach the binary
if (ffmpeg_wrapper_run_command()) {
$form['ffmpeg_wrapper']['ffmpeg_wrapper_about'] = array(
'#type' => 'fieldset',
'#title' => t('About FFmpeg installation'),
'#collapsible' => true,
'#collapsed' => true,
);
$form['ffmpeg_wrapper']['ffmpeg_wrapper_about']['ffmpeg_wrapper_version'] = array(
'#type' => 'item',
'#title' => t('FFmpeg version'),
'#value' => '<blockquote>'. ffmpeg_wrapper_get_version('string') .'</blockquote>',
'#description' => t('Version of FFmpeg running on your system'),
);
$form['ffmpeg_wrapper']['ffmpeg_wrapper_about']['ffmpeg_wrapper_formats'] = array(
'#type' => 'item',
'#title' => t('Supported file formats'),
'#value' => ffmpeg_wrapper_formats_data_display(),
'#description' => t('File formats that the installed version of FFmpeg supports.'),
);
$form['ffmpeg_wrapper']['ffmpeg_wrapper_about']['ffmpeg_wrapper_codecs'] = array(
'#type' => 'item',
'#title' => t('Installed codecs'),
'#value' => ffmpeg_wrapper_get_codecs_display(),
'#description' => t('FFmpeg was either compiled with these codecs, or these are the codecs available on your system'),
);
}
// get a list of the vhooks in the system
if (ffmpeg_wrapper_vhook_list()) {
$form['ffmpeg_wrapper']['ffmpeg_wrapper_vhooks'] = array(
'#type' => 'fieldset',
'#title' => t('vhook files installed on this system'),
'#collapsible' => true,
'#collapsed' => true,
);
$form['ffmpeg_wrapper']['ffmpeg_wrapper_vhooks']['ffmpeg_wrapper_vhook'] = array(
'#type' => 'item',
'#title' => t('vhook files'),
'#value' => implode('<br />', ffmpeg_wrapper_vhook_list()),
'#description' => t('List of all the Vhook files found.'),
);
}
return system_settings_form($form);
}
/**
* validate the options on the ffmpeg form
*
* @param int $form_id
* @param array $form_values
*/
function ffmpeg_wrapper_admin_validate($form, &$form_state) {
// make sure we've got the path to the ffmpeg binary
if (! ffmpeg_wrapper_run_command(null, false, $form_state['values']['ffmpeg_wrapper_path']) && $form_values['ffmpeg_wrapper_path']) {
form_set_error('ffmpeg_wrapper_path', t('FFmpeg binary was not found on the path you specified. Maybe try a different path?'));
}
// check and see if we can find the vhook directory
if (! is_dir($form_state['values']['ffmpeg_wrapper_vhook']) && $form_state['values']['ffmpeg_wrapper_vhook']) {
form_set_error('ffmpeg_wrapper_vhook', t('The vhook directory was not found on the path you specified. Maybe try a different path?'));
}
}
/* ************************************************ */
/* Interactions with ffmpeg */
/* ************************************************ */
/**
* Get data from ffmpeg.
*
* @param $command
* The options to run ffmpeg with.
* @param $error_check
* If TRUE, runs error checking on the output.
* @param $path
* Overrides the system settings.
* @param $ffmpeg_object
* Object for passing debug and other kinds of data through the system.
* @return
* Output of the command.
*/
function ffmpeg_wrapper_run_command($command = '', $error_check = true, $path = '', &$ffmpeg_object = null) {
// override the system path?
if (! $path) {
$path = variable_get('ffmpeg_wrapper_path', '/usr/bin/ffmpeg');
}
if (empty($ffmpeg_object)) {
$ffmpeg_object = new stdClass();
}
// Create some exceptions for dealing with pipes and semicolons
$pattern = array('\;', '\|');
$replace = array(';', '|');
// Escape our command, but make sure that we allow | and ;
$ffmpeg_object->command = str_replace($pattern, $replace, escapeshellcmd($path .' '. $command));
$ffmpeg_object->cwd = getcwd();
// does binary exist?
if (! file_exists($path)) {
return false;
}
$descriptor_spec = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')
);
$pipes = array();
$process = proc_open($ffmpeg_object->command, $descriptor_spec, $pipes, $ffmpeg_object->cwd , null, array('binary_pipes' => true));
if (is_resource($process)) {
fclose($pipes[0]);
$ffmpeg_object->output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$ffmpeg_object->output .= stream_get_contents($pipes[2]);
fclose($pipes[2]);
$command_return = proc_close($process);
}
// Find the output file in the command if there was one.
// This is sort of hacky but is helpful for passing the file out.
preg_match("/.*'(.*)'$/i", $command, $matches);
$ffmpeg_object->output_file = !empty($matches[1]) ? $matches[1] : null;
// do error handling if requested
if ($error_check) {
if (! ffmpeg_wrapper_error_check($ffmpeg_object, true)){
return false;
}
}
return $ffmpeg_object->output;
}
/**
* builds a list of the ffmpeg vhook options installed on this machine
* @TODO we need to get more information on how the vhook system works and how
* admins can utilize it
*
* @param string $path
* @return array
*/
function ffmpeg_wrapper_vhook_list($path = '') {
static $files;
// if we have a list already
if ($files) {
return $files;
}
// build the path
if (! $path) {
$path = variable_get('ffmpeg_wrapper_vhook', '/usr/local/lib/vhook');
}
// @TODO replace below with file_scan_directory($path);
// check to see if the directory is correct
if (is_dir($path)) {
// open the directory
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
// do not this or parrent directory
if ($file != "." && $file != "..") {
$files[] = $path .'/'. $file;
}
}
closedir($dir);
}
if (count($files)) {
return $files;
}
}
}
/**
* Check an incoming file to see if it can be decoded by comparing the file's codec
* and format against the list of decode formats in FFMPEG.
*
* @param $file
* string, A full system filepath.
* @param $types
* array, what kind of decode do we need to check for
* @return
* boolean, TRUE if file is in the list of decodeable files.
*/
function ffmpeg_wrapper_can_decode($path, $types = array('video', 'audio')) {
// get the kind of files
$file_types = ffmpeg_wrapper_get_file_formats('decode');
// get the format and codec information on this file
$file_data = ffmpeg_wrapper_file_data($path);
// Issue http://drupal.org/node/479972
$codec = ffmpeg_wrapper_get_codecs('decode');
foreach (array('video', 'audio') as $media) {
// some files have multiple formats attached to them
foreach(explode(',', $file_data[$media]['codec']) as $type) {
// is this type in the array of items that we can decode?
if (in_array($type, $codec)) {
return true;
}
}
}
// if the file has multiple formats, all formats
// must be in $file_types Otherwise, it is
// not supported by ffmpeg.
foreach(explode(',', $file_data['format']) as $type) {
if (! in_array($type, $file_types)) {
return false;
}
}
// if we have na values for the audio and video codecs, the file can not be decoded
// @ TODO is this really true? The logic below does not seem to indicate this,
// however, I might not understand what the 'na' value really means
if ($file_data['audio']['codec'] == 'na' && $file_data['video']['codec'] == 'na') {
return false;
}
// Now get installed codecs to compare file codecs
foreach (ffmpeg_wrapper_get_codecs('decode') as $codec) {
if ($codec == $file_data['audio']['codec'] || $file_data['audio']['codec'] == 'na' ) {
// are we only handing back audio?
if ($types['audio'] && ! $types['video']) { return true; }
$can_audio_decode = true;
}
if ($codec == $file_data['video']['codec'] || $file_data['video']['codec'] == 'na') {
// are we only handing back video?
if ($types['video'] && ! $types['audio']) { return true; }
$can_video_decode = true;
}
// If we can decode both audio and video, the file is ok
if ($can_audio_decode && $can_video_decode) {
return true;
}
}
return false;
}
/**
* Get an array of codec types usable on this system.
* This should probably be smoothed out so that it doesn't rely on text so
* much.
* Caches data to avoid extra command line hits.
*
* @ TODO this needs to be rethought to pass params right
*
* @param $return
* Determins hand back of encode/decode.
* @return
* Array of codecs or specific encode/decode options.
*/
function ffmpeg_wrapper_get_codecs($return = 'rows') {
$cache_id = 'ffmpeg_wrapper_codecs';
$cache = cache_get($cache_id, 'cache');
if (!isset($cache->data)) {
$data = array();
// we know where the codecs are by looking at the output of ffmpeg -formats or ffmpeg -codecs
// depending of version SVN-r > 20561 or version > 0.5
$ffmpeg_version = ffmpeg_wrapper_get_version('svn');
if ( ((int)$ffmpeg_version >= 20561) || ((int)$ffmpeg_version < 1000 && (float)$ffmpeg_version > 0.5) ) {
$output = ffmpeg_wrapper_run_command('-codecs');
$codecs_formats_pos = strpos($output, 'Codecs:');
$codecs_formats_pos_end = strpos($output, 'Note,');
}
else {
$output = ffmpeg_wrapper_run_command('-formats');
$codecs_formats_pos = strpos($output, 'Codecs:');
$codecs_formats_pos_end = strpos($output, 'Supported file protocols:');
}
$codecs = substr($output, $codecs_formats_pos, ($codecs_formats_pos_end - $codecs_formats_pos));
// remove the extra text
$codecs = str_replace('Codecs:', '', $codecs);
// convert to array
$codecs = explode("\n", $codecs);
$rows = array();
foreach ($codecs as $codec) {
// match the decode, encode, type, S|D|T options (see: http://lists.mplayerhq.hu/pipermail/ffmpeg-user/2006-January/002003.html)
// name
$pattern ='/[ ]*([D ])([E ])([ VA])([S ])([ D])([ T])[ ]*([a-zA-Z0-9_,]*)[ ]*([a-zA-Z0-9,_ ]*)/';
preg_match($pattern, $codec, $matches);
// codec names
$a_format['name'] = $matches[7];
// get the codec type
if ($matches[3] == 'A') {
$a_format['type'] = t('audio');
$encode_formats[] = $a_format['name'];
}
else {
$a_format['type'] = t('video');
}
// get the decode value
if ($matches[1] == 'D') {
$a_format['decode'] = t('yes');
$decode_formats[] = $a_format['name'];
}
else {
$a_format['decode'] = t('no');
}
// get the encode value
if ($matches[2] == 'E') {
$a_format['encode'] = t('yes');
$encode_formats[] = $a_format['name'];
}
else {
$a_format['encode'] = t('no');
}
if ($a_format['name']) {
$rows[] = $a_format;
}
$a_format = null;
}
$data['encode'] = $encode_formats;
$data['decode'] = $decode_formats;
$data['rows'] = $rows;
cache_set($cache_id, $data, 'cache', CACHE_TEMPORARY);
}
else {
$data = $cache->data;
}
return $data[$return];
}
/**
* Get a list of codecs in key value form- for use in form display
*
* @param $type
* audio or video.
* @return
* Array of codec names.
*/
function ffmpeg_wrapper_return_codecs($type) {
static $codecs;
if (! empty($codecs[$type])) {
return $codecs[$type];
}
$codecs = array();
$codecs[$type] = array(0 => t('Use default'));
// get list of avaiable audio and video codecs
$codec_list = ffmpeg_wrapper_get_codecs();
if ($codec_list) {
foreach ($codec_list as $codec) {
if ($codec['encode'] == "yes" && $codec['type'] == $type) {
$codecs[$type][$codec['name']] = $codec['name'];
}
}
}
return $codecs[$type];
}
/**
* Helper function to build the list of output formats on the system.
* Data is cached to reduce hits to ffmpeg.
*
* @return
* Array of key values
*/
function ffmpeg_wrapper_output_formats() {
$cache_id = 'ffmpeg_wrapper_output_formats';
$cache = cache_get($cache_id, 'cache');
if (!isset($cache->data)) {
// get all the encoding options
if (! $outputs = ffmpeg_wrapper_get_file_formats('encode')) {
watchdog('ffmpeg_wrapper', 'No output formats found. Path to ffmpeg is probably wrong', array(), WATCHDOG_ERROR);
return array();
}
// rebuild as a select array
$formats = array(t('Select output type'));
foreach ($outputs as $output) {
$formats[$output] = $output;
}
cache_set($cache_id, $formats, 'cache', CACHE_TEMPORARY);
}
else {
$formats = $cache->data;
}
return $formats;
}
/**
* Build the output rates for each type of bit rate that ffmpeg offers.
*
* @param $type
* Type of bit rate: "ab", "ar", "fps" or "br".
* @return
* Array of key values.
*/
function ffmpeg_wrapper_output_rates($type) {
static $rates;
if (! $rates) {
$rates = array(
'ab' => array('16k' => '16k', '22k' => '22k', '32k' => '32k', '64k' => t('64k (default)'), '128k' => '128k', '192k' => '192k', '256k' => '256k'),
'ar' => array('11025' => t('11khz'), '22050' => t('22khz'), '32000' => t('32khz'), '44100' => t('44.1khz (default)') ),
'fps' => array(10 => 10, 15 => 15, 20 => 20, 25 => t('25 (default)'), 29.97 => 29.97),
'br' => array('50k' => t('50kps'), '100k' => t('100kps'), '150k' => t('150kps'), '200k' => t('200kps'), '250k' => t('250kps (default)'), '300k' => t('300kps'), '500k' => t('500kps'), '750k' => t('750kps'), '1000k' => t('1000kps'), '1250k' => t('1250kps'), '1500k' => t('1500kps'), '2000k' => t('2000kps')),
);
}
return $rates[$type];
}
/**
* Output dimentions form settings.
* @return
* An array of frame sizes.
*/
function ffmpeg_wrapper_frame_sizes(){
$frame_sizes = array(
'0' => t('No alteration'),
'128x96' => '128x96',
'176x144' => '176x144',
'320x240' => '320x240',
'352x288' => '352x288',
'512x386' => '512x386',
'704x576' => '704x576'
);
$frame_sizes['other'] = t('Other');
return $frame_sizes;
}
/**
* Get an array of format types usable on this system.
* This should probably be smoothed out so that it doesn't rely on text so
* much. If no value for $ret is given, return the descriptions. This data
* is all built by scanning the output from ffmpeg.
*
* @param $ret
* Determins what to hand back (encode/decode).
* @return
* Array of options.
*/
function ffmpeg_wrapper_get_file_formats($ret = 'row') {
$cache_id = 'ffmpeg_wrapper_file_formats';
$cache = cache_get($cache_id, 'cache');
// do we have cached data?
if (!isset($cache->data)) {
// if we can't get formats, do not bother
if (! $formats = ffmpeg_wrapper_run_command('-formats') ) {
return;
}
// slice up the format output
$startpos = strpos($formats, 'File formats:');
// depending of version SVN-r > 20561 or version > 0.5 string changes
$ffmpeg_version = ffmpeg_wrapper_get_version('svn');
if ( ((int)$ffmpeg_version >= 20561) || ((int)$ffmpeg_version < 1000 && (float)$ffmpeg_version > 0.5) ) {
$endpos = strpos($formats, 'FFmpeg version');
}
else {
$endpos = strpos($formats, 'Codecs:');
}
$formats = substr($formats, $startpos, $endpos - $startpos);
//remove the header
$formats = str_replace('File formats:', '', $formats);
$decode_formats = array();
$encode_formats = array();
$rows = array();
foreach (explode("\n", $formats) as $format) {
// match the decode, encode, format, description
$pattern ='/[ ]*([D ])([E ])[ ]*([a-zA-Z0-9_,]*)[ ]*([^\$]*)/';
preg_match($pattern, $format, $matches);
$a_format['type'] = $matches[3];
$a_format['name'] = $matches[4];
// check for decoding
if ($matches[1] == 'D') {
$a_format['decode'] = t('yes');
// we can have multiple types per format
$types = explode(',', $a_format['type']);
foreach ($types as $type) {
$decode_formats[] = $type;
}
}
else {
$a_format['decode'] = t('no');
}
// check for encoding
if ($matches[2] == 'E') {
$a_format['encode'] = t('yes');
// we can have multiple types per format
$types = explode(',', $a_format['type']);
foreach ($types as $type) {
$encode_formats[] = $type;
}
}
else {
$a_format['encode'] = t('no');
}
$a_format['description'] = $matches[4];
if ($a_format['description']) {
$rows[] = $a_format;
}
}
$output = array();
$output['encode'] = $encode_formats;
$output['decode'] = $decode_formats;
$output['row'] = $rows;
cache_set($cache_id, $output, 'cache', CACHE_TEMPORARY);
}
else {
$output = $cache->data;
}
// return the requested data
return $output[$ret];
}
/**
* Get FFMpeg version
*
* @param $format
* (string/version/svn)
* @return
* Version string.
*/
function ffmpeg_wrapper_get_version($format) {
// get string from ffmpeg and return it if it is enough
$version = ffmpeg_wrapper_run_command('-version');
if ($format == 'string') {
return $version;
}
//anything else return the version string or SVN-r
// slice up the version output
$startpos = strpos($version, 'FFmpeg version ') +15;
$endpos = strpos($version, ', Copyright');
$version_number = substr($version, $startpos, $endpos - $startpos);
if ($format == 'version') {
return $version_number;
}
// Return SVN revision number format used by Debian lenny.
if (preg_match('/^r([0-9]+)\+/', $version_number, $matches)) {
return $matches[1];
}
// is FALSE if the string is not found
if (strpos($version_number, 'SVN-r') === 0) {
$version_release = substr($version_number, 5);
return $version_release;
}
// then is a full release version as 0.5
return $version_number;
}
/**
* Get the duration of a video.
*
* @param $path
* The path to file.
* @param $timecode
* If TRUE, return time code, otherwise return seconds.
* @param $output
* string, output of ffmpeg if it has already been run
* @return
* Duration in seconds as an integer or timecode as string.
*/
function ffmpeg_wrapper_file_duration($path, $timecode = null, $output = null) {
// do we have any output from ffmpeg already?
if (! $output) {
// get duration from ffmpeg
// need quotes around the path parameter in case filename has spaces.
$output = ffmpeg_wrapper_run_command("-i \"$path\"");
}
// parse the output looking for "Duration: 00:02:12"
$pattern = "/Duration: ([0-9]+:[0-9]+:[0-9]+)\.[0-9]+/";
preg_match($pattern, $output, $matches);
$time = $matches[1];
if (! $timecode) {
// now we need to convert the time code to seconds
// get the time into an array
$time = explode(':', $time);
$seconds = 0;
if ($time[0] != '00') {
$seconds += $time[0] * 60 * 60;
}
if ($time[1] != '00') {
$seconds += $time[1] * 60;
}
$seconds += $time[2];
$time = $seconds;
}
return $time;
}
/**
* This function produces file data from an incoming file
* @param $path
* @param $timecode
* @return array
*/
function ffmpeg_wrapper_file_data($path = null) {
if (file_exists($path)) {
// get duration from ffmpeg
// need quotes around the path parameter in case filename has spaces.
$output = ffmpeg_wrapper_run_command("-i \"$path\"");
// get file format
$pattern = '/Input #0, (.*),/';
preg_match($pattern, $output, $matches);
$file['format'] = !empty($matches[1]) ? $matches[1] : 'na';
// get file duration
$file['duration'] = ffmpeg_wrapper_file_duration(null, null, $output);
// get bit rate
$pattern = "/bitrate: ([0-9].*\/s)/";
preg_match($pattern, $output, $matches);
$file['bitrate'] = !empty($matches[1]) ? $matches[1] : 'na';
// get audio settings
// format is: codec, sample rate, stereo/mono, bitrate
$pattern = "/Audio: (.*), ([0-9]*) Hz, (stereo|mono|([0-9]+) channels)/";
preg_match($pattern, $output, $matches);
$file['audio']['codec'] = !empty($matches[1]) ? $matches[1] : 'na';
$file['audio']['ar'] = !empty($matches[2]) ? $matches[2] : 'na';
$file['audio']['ac'] = !empty($matches[4]) ? $matches[4] : (!empty($matches[3]) && $matches[3] == 'stereo' ? 2 : 1);
// take the last match and extract the bit rate if present
$pattern = "/Audio: .* (.*) kb\/s/";
preg_match($pattern, $output, $matches);
$file['audio']['ab'] = !empty($matches[1]) ? $matches[1] : 'na';
// VIDEO ----------------------------------------
// The formating of video can be difficult. We use 3 different
// patterns to look for the video information
// try pattern that takes into account a codec's color space (example: yuv420p)
// eg: Video: mpeg1video, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 990 kb/s, 30.00 tb(r)
// the above is: codec, color space, frame size, bitrate, frame rate
$pattern1 = "/Video: ([^,]+), ([^,]+), ([0-9x]+)[^,]*, ([0-9]*.*\/s|[A-Za-z]+[^,]*), ([0-9\.]*)/";
// pattern that omits video bitrate but not color space.
// eg: Video: mpeg4, yuv420p, 640x480 [PAR 1:1 DAR 4:3], 23.98 tb(r)
// the above is: codec, color space, frame size, frame rate
$pattern2 = "/Video: ([^,]+), ([^0-9][^,]*), ([0-9x]+)[^,]*, ([0-9\.]*)/";
// pattern that omits a codec's color space and video bitrate
// eg: Video: mpeg4, 640x480, 29.97 tb(r)
// the above is: codec, frame size, frame rate
$pattern3 = "/Video: ([^,]+), ([0-9x]+)[^,]*, ([0-9\.]*)/";
// did we find the video information on the first try ?
if (preg_match($pattern1, $output, $matches)) {
$file['video']['codec'] = !empty($matches[1]) ? $matches[1] : 'na';
// $file['video']['type'] = $matches[2];
$file['video']['s'] = !empty($matches[3]) ? $matches[3] : 'na';
$file['video']['br'] = !empty($matches[4]) ? $matches[4] : 'na';
}
elseif (preg_match($pattern2, $output, $matches)) {
$file['video']['codec'] = !empty($matches[1]) ? $matches[1] : 'na';
$file['video']['s'] = !empty($matches[3]) ? $matches[3] : 'na';
$file['video']['br'] = 'na';
}
elseif (preg_match($pattern3, $output, $matches)) {
$file['video']['codec'] = !empty($matches[1]) ? $matches[1] : 'na';
$file['video']['s'] = !empty($matches[3]) ? $matches[3] : 'na';
$file['video']['br'] = 'na';
}
return $file;
}
}
/**
* Calculate an output size and a padding value for a video file.
*
* @param $file
* Path to the file to be converted.
* @param $size
* The maximum dimensions of the output file, expressed as XXXxYYY. This will
* be cropped to match the original file's proportions and the remaining
* space will be used to calculate the padding.
* @param $return
* Either 'padding' or 'size'.
* @return
* Depending on the value of $return, the function returns either the size
* expressed as XXXxYYY, or the actual padding argument for FFmpeg, ie.
* "-padtop XX -padbottom XX". The result is statically cached, so you can
* call it multiple times without permormance issues.
*/
function ffmpeg_wrapper_padded_size($file, $size, $return = 'padding') {
static $file_proportions;
// Cache file proportions statically.
if (!isset($file_proportions)) {
$file_proportions = array();
}
if (isset($file_proportions[$file])) {
return ($return == 'size') ? $file_proportions[$file][0] : $file_proportions[$file][1];
}
else {
$pad = '';
// Determine source file's dimensions and proportions.
$info = ffmpeg_wrapper_file_data($file);
if ($info && isset($info['video'])) {
list($orig_x, $orig_y) = explode('x', $info['video']['s']);
$orig_q = $orig_x / $orig_y;
// Determine output dimensions and proportions.
list($dest_x, $dest_y) = explode('x', $size);
$dest_q = $dest_x / $dest_y;
// Calculate new output size and padding.
if ($orig_q > $dest_q) {
// Width is the determining factor.
$dest_y_calc = round($dest_x / $orig_q);
// Make sure height is divisible by 2, otherwise ffmpeg freaks out.
$dest_y_calc &= ~1;
$size = $dest_x . 'x' . $dest_y_calc;
$padding = $dest_y - $dest_y_calc;
$padoptions = '-padtop %d -padbottom %d';
}
elseif ($dest_q > $orig_q) {
// Height is the determining factor.
$dest_x_calc = round($dest_y * $orig_q);
// Make sure width is divisible by 2, otherwise ffmpeg freaks out.
$dest_x_calc &= ~1;
$size = $dest_x_calc . 'x' . $dest_y;
$padding = $dest_x - $dest_x_calc;
$padoptions = '-padleft %d -padright %d';
}
// Calculate padding on each side. Each value has to be a multiple of 2.
$padding &= ~1;
$padding1 = floor($padding / 2);
$padding1 &= ~1;
$padding2 = $padding - $padding1;
$pad = sprintf($padoptions, $padding1, $padding2);
}
// Save and return the results.
$file_proportions[$file] = array($size, $pad);
return ($return == 'size') ? $size : $pad;
}
}
/**
* Check to make sure that FFmpeg is in the path.
*
* @return
* TRUE if FFmpeg can be executed, FALSE otherwise.
*/
function ffmpeg_wrapper_executable() {
if (! ffmpeg_wrapper_run_command('')) {
return false;
}
return true;
}
/**
* Display a table of the supported ffmpeg file formats.
*
* @return
* The themed HTML form.
*/
function ffmpeg_wrapper_formats_data_display() {
$header = array(t('name'), t('type'), t('decode'), t('encode'), t('description') );
$output = theme('table', $header, ffmpeg_wrapper_get_file_formats() );
return $output;
}
/**
* Display a table of the ffmpeg encoding and decoding options.
*
* @return
* The themed HTML form.
*/
function ffmpeg_wrapper_get_codecs_display() {
$header = array(t('codec'), t('codec type'), t('decode'), t('encode'));
$output = theme('table', $header, ffmpeg_wrapper_get_codecs() );
return $output;
}
/**
* Check FFmpeg's output for errors and try to handle them some way.
*
* @param $ffmpeg_object
* Object containing all the data to check errors against
* - shell output and command run.
* @param boolean $watchdog
* If TRUE, log errors to Drupal's watchdog.
* @return
* TRUE if no errors, FALSE if errors.
*
**/
function ffmpeg_wrapper_error_check(&$ffmpeg_object, $watchdog = true) {
$return = true;
// build the error conditions these are all pulled by hand at this point
// @NOTE one has to be careful to have a specific match as there are strings
// in the output from #ffmpeg which containg "error"
$errors = array(
'/Segmentation fault .*/i',
'/Unsupported .*/i',
// match: bad formats
'/Unknown format .*/i',
'/Unable for find a suitable output format for .*/i',
'/Incorrect frame size .*/i',