-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathFFmpegMovie.php
772 lines (691 loc) · 21.5 KB
/
FFmpegMovie.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
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
<?php
/**
* FFmpegMovie represents a movie file
*
* @author huangzengbing
* @package FFmpegPHP
* @license New BSD
* @version 2.6
*/
namespace Phpffmpeg;
use Serializable;
use Exception;
use Phpffmpeg\provider\FFmpegOutputProvider;
use Phpffmpeg\provider\OutputProvider;
class FFmpegMovie implements Serializable {
protected static $REGEX_DURATION = '/Duration: ([0-9]{2}):([0-9]{2}):([0-9]{2})(\.([0-9]+))?/';
protected static $REGEX_FRAME_RATE = '/([0-9\.]+\sfps,\s)?([0-9\.]+)\stbr/';
protected static $REGEX_COMMENT = '/comment\s*(:|=)\s*(.+)/i';
protected static $REGEX_TITLE = '/title\s*(:|=)\s*(.+)/i';
protected static $REGEX_ARTIST = '/(artist|author)\s*(:|=)\s*(.+)/i';
protected static $REGEX_COPYRIGHT = '/copyright\s*(:|=)\s*(.+)/i';
protected static $REGEX_GENRE = '/genre\s*(:|=)\s*(.+)/i';
protected static $REGEX_TRACK_NUMBER = '/track\s*(:|=)\s*(.+)/i';
protected static $REGEX_YEAR = '/year\s*(:|=)\s*(.+)/i';
protected static $REGEX_FRAME_WH = '/Video:.+?([1-9][0-9]*)x([1-9][0-9]*)/';
protected static $REGEX_PIXEL_FORMAT = '/Video: [^,]+, ([^,]+)/';
protected static $REGEX_BITRATE = '/bitrate: ([0-9]+) kb\/s/';
protected static $REGEX_VIDEO_BITRATE = '/Video:.+?([0-9]+) kb\/s/';
protected static $REGEX_AUDIO_BITRATE = '/Audio:.+?([0-9]+) kb\/s/';
protected static $REGEX_AUDIO_SAMPLE_RATE = '/Audio:.+?([0-9]+) Hz/';
protected static $REGEX_VIDEO_CODEC = '/Video:\s([^,]+),/';
protected static $REGEX_AUDIO_CODEC = '/Audio:\s([^,]+),/';
protected static $REGEX_AUDIO_CHANNELS = '/Audio:\s[^,]+,[^,]+,([^,]+)/';
protected static $REGEX_HAS_AUDIO = '/Stream.+Audio/';
protected static $REGEX_HAS_VIDEO = '/Stream.+Video/';
protected static $REGEX_ERRORS = '/.*(Error|Permission denied|could not seek to position|Invalid pixel format|Unknown encoder|could not find codec|does not contain any stream).*/i';
/**
* FFmpeg binary
*
* @var string
*/
protected $ffmpegBinary;
/**
* Output provider
*
* @var OutputProvider
*/
protected $provider;
/**
* Movie file path
*
* @var string
*/
protected $movieFile;
/**
* provider output
*
* @var string
*/
protected $output;
/**
* Movie duration in seconds
*
* @var float
*/
protected $duration;
/**
* Current frame index
*
* @var int
*/
protected $frameCount;
/**
* Movie frame rate
*
* @var float
*/
protected $frameRate;
/**
* Comment ID3 field
*
* @var string
*/
protected $comment;
/**
* Title ID3 field
*
* @var string
*/
protected $title;
/**
* Author ID3 field
*
* @var string
*/
protected $artist;
/**
* Copyright ID3 field
*
* @var string
*/
protected $copyright;
/**
* Genre ID3 field
*
* @var string
*/
protected $genre;
/**
* Track ID3 field
*
* @var int
*/
protected $trackNumber;
/**
* Year ID3 field
*
* @var int
*/
protected $year;
/**
* Movie frame height
*
* @var int
*/
protected $frameHeight;
/**
* Movie frame width
*
* @var int
*/
protected $frameWidth;
/**
* Movie pixel format
*
* @var string
*/
protected $pixelFormat;
/**
* Movie bit rate combined with audio bit rate
*
* @var int
*/
protected $bitRate;
/**
* Movie video stream bit rate
*
* @var int
*/
protected $videoBitRate;
/**
* Movie audio stream bit rate
*
* @var int
*/
protected $audioBitRate;
/**
* Audio sample rate
*
* @var int
*/
protected $audioSampleRate;
/**
* Current frame number
*
* @var int
*/
protected $frameNumber;
/**
* Movie video cocec
*
* @var string
*/
protected $videoCodec;
/**
* Movie audio coded
*
* @var string
*/
protected $audioCodec;
/**
* Movie audio channels
*
* @var int
*/
protected $audioChannels;
/**
* Open a video or audio file and return it as an FFmpegMovie object.
* If ffmpeg and ffprobe are both installed on host system, ffmpeg
* gets priority in extracting info from the movie file. However
* to override this default behaviour use any implementation of OutputProvider interface
* as the second constructor argumentwhile instantiating
*
*
* @param string $moviePath full path to the movie file
* @param OutputProvider $outputProvider provides parsable output
* @param string $ffmpegBinary ffmpeg executable, if $outputProvider not specified
* @throws Exception
* @return FFmpegMovie
*/
public function __construct($moviePath, OutputProvider $outputProvider = null, $ffmpegBinary = 'ffmpeg') {
$this->movieFile = $moviePath;
$this->frameNumber = 0;
$this->ffmpegBinary = $ffmpegBinary;
if ($outputProvider === null) {
$outputProvider = new FFmpegOutputProvider($ffmpegBinary);
}
$this->setProvider($outputProvider);
}
/**
* Setting provider implementation
*
* @param OutputProvider $outputProvider
*/
public function setProvider(OutputProvider $outputProvider) {
$this->provider = $outputProvider;
$this->provider->setMovieFile($this->movieFile);
$this->output = $this->provider->getOutput();
}
/**
* Getting current provider implementation
*
* @return OutputProvider
*/
public function getProvider() {
return $this->provider;
}
/**
* Return the duration of a movie or audio file in seconds.
*
* @return float movie duration in seconds
*/
public function getDuration() {
if ($this->duration === null) {
$match = array();
preg_match(self::$REGEX_DURATION, $this->output, $match);
if (array_key_exists(1, $match) && array_key_exists(2, $match) && array_key_exists(3, $match)) {
$hours = (int) $match[1];
$minutes = (int) $match[2];
$seconds = (int) $match[3];
$fractions = (float) ((array_key_exists(5, $match)) ? "0.$match[5]" : 0.0);
$this->duration = (($hours * (3600)) + ($minutes * 60) + $seconds + $fractions);
} else {
$this->duration = 0.0;
}
return $this->duration;
}
return $this->duration;
}
/**
* Return the number of frames in a movie or audio file.
*
* @return int
*/
public function getFrameCount() {
if ($this->frameCount === null) {
$this->frameCount = (int) ($this->getDuration() * $this->getFrameRate());
}
return $this->frameCount;
}
/**
* Return the frame rate of a movie in fps.
*
* @return float
*/
public function getFrameRate() {
if ($this->frameRate === null) {
$match = array();
preg_match(self::$REGEX_FRAME_RATE, $this->output, $match);
$this->frameRate = (float) ((array_key_exists(1, $match)) ? $match[1] : 0.0);
}
return $this->frameRate;
}
/**
* Return the path and name of the movie file or audio file.
*
* @return string
*/
public function getFilename() {
return $this->movieFile;
}
/**
* Return the comment field from the movie or audio file.
*
* @return string
*/
public function getComment() {
if ($this->comment === null) {
$match = array();
preg_match(self::$REGEX_COMMENT, $this->output, $match);
$this->comment = (array_key_exists(2, $match)) ? trim($match[2]) : '';
}
return $this->comment;
}
/**
* Return the title field from the movie or audio file.
*
* @return string
*/
public function getTitle() {
if ($this->title === null) {
$match = array();
preg_match(self::$REGEX_TITLE, $this->output, $match);
$this->title = (array_key_exists(2, $match)) ? trim($match[2]) : '';
}
return $this->title;
}
/**
* Return the author field from the movie or the artist ID3 field from an mp3 file; alias $movie->getArtist()
*
* @return string
*/
public function getArtist() {
if ($this->artist === null) {
$match = array();
preg_match(self::$REGEX_ARTIST, $this->output, $match);
$this->artist = (array_key_exists(3, $match)) ? trim($match[3]) : '';
}
return $this->artist;
}
/**
* Return the author field from the movie or the artist ID3 field from an mp3 file.
*
* @return string
*/
public function getAuthor() {
return $this->getArtist();
}
/**
* Return the copyright field from the movie or audio file.
*
* @return string
*/
public function getCopyright() {
if ($this->copyright === null) {
$match = array();
preg_match(self::$REGEX_COPYRIGHT, $this->output, $match);
$this->copyright = (array_key_exists(2, $match)) ? trim($match[2]) : '';
}
return $this->copyright;
}
/**
* Return the genre ID3 field from an mp3 file.
*
* @return string
*/
public function getGenre() {
if ($this->genre === null) {
$match = array();
preg_match(self::$REGEX_GENRE, $this->output, $match);
$this->genre = (array_key_exists(2, $match)) ? trim($match[2]) : '';
}
return $this->genre;
}
/**
* Return the track ID3 field from an mp3 file.
*
* @return int
*/
public function getTrackNumber() {
if ($this->trackNumber === null) {
$match = array();
preg_match(self::$REGEX_TRACK_NUMBER, $this->output, $match);
$this->trackNumber = (int) ((array_key_exists(2, $match)) ? $match[2] : 0);
}
return $this->trackNumber;
}
/**
* Return the year ID3 field from an mp3 file.
*
* @return int
*/
public function getYear() {
if ($this->year === null) {
$match = array();
preg_match(self::$REGEX_YEAR, $this->output, $match);
$this->year = (int) ((array_key_exists(2, $match)) ? $match[2] : 0);
}
return $this->year;
}
/**
* Return the height of the movie in pixels.
*
* @return int
*/
public function getFrameHeight() {
if ($this->frameHeight == null) {
$match = array();
preg_match(self::$REGEX_FRAME_WH, $this->output, $match);
if (array_key_exists(1, $match) && array_key_exists(2, $match)) {
$this->frameWidth = (int) $match[1];
$this->frameHeight = (int) $match[2];
} else {
$this->frameWidth = 0;
$this->frameHeight = 0;
}
}
return $this->frameHeight;
}
/**
* Return the width of the movie in pixels.
*
* @return int
*/
public function getFrameWidth() {
if ($this->frameWidth === null) {
$this->getFrameHeight();
}
return $this->frameWidth;
}
/**
* Return the pixel format of the movie.
*
* @return string
*/
public function getPixelFormat() {
if ($this->pixelFormat === null) {
$match = array();
preg_match(self::$REGEX_PIXEL_FORMAT, $this->output, $match);
$this->pixelFormat = (array_key_exists(1, $match)) ? trim($match[1]) : '';
}
return $this->pixelFormat;
}
/**
* Return the bit rate of the movie or audio file in bits per second.
*
* @return int
*/
public function getBitRate() {
if ($this->bitRate === null) {
$match = array();
preg_match(self::$REGEX_BITRATE, $this->output, $match);
$this->bitRate = (int) ((array_key_exists(1, $match)) ? ($match[1] * 1000) : 0);
}
return $this->bitRate;
}
/**
* Return the bit rate of the video in bits per second.
*
* NOTE: This only works for files with constant bit rate.
*
* @return int
*/
public function getVideoBitRate() {
if ($this->videoBitRate === null) {
$match = array();
preg_match(self::$REGEX_VIDEO_BITRATE, $this->output, $match);
$this->videoBitRate = (int) ((array_key_exists(1, $match)) ? ($match[1] * 1000) : 0);
}
return $this->videoBitRate;
}
/**
* Return the audio bit rate of the media file in bits per second.
*
* @return int
*/
public function getAudioBitRate() {
if ($this->audioBitRate === null) {
$match = array();
preg_match(self::$REGEX_AUDIO_BITRATE, $this->output, $match);
$this->audioBitRate = (int) ((array_key_exists(1, $match)) ? ($match[1] * 1000) : 0);
}
return $this->audioBitRate;
}
/**
* Return the audio sample rate of the media file in bits per second.
*
* @return int
*/
public function getAudioSampleRate() {
if ($this->audioSampleRate === null) {
$match = array();
preg_match(self::$REGEX_AUDIO_SAMPLE_RATE, $this->output, $match);
$this->audioSampleRate = (int) ((array_key_exists(1, $match)) ? $match[1] : 0);
}
return $this->audioSampleRate;
}
/**
* Return the current frame index.
*
* @return int
*/
public function getFrameNumber() {
return ($this->frameNumber == 0) ? 1 : $this->frameNumber;
}
/**
* Return the name of the video codec used to encode this movie as a string.
*
* @return string
*/
public function getVideoCodec() {
if ($this->videoCodec === null) {
$match = array();
preg_match(self::$REGEX_VIDEO_CODEC, $this->output, $match);
$this->videoCodec = (array_key_exists(1, $match)) ? trim($match[1]) : '';
}
return $this->videoCodec;
}
/**
* Return the name of the audio codec used to encode this movie as a string.
*
* @return string
*/
public function getAudioCodec() {
if ($this->audioCodec === null) {
$match = array();
preg_match(self::$REGEX_AUDIO_CODEC, $this->output, $match);
$this->audioCodec = (array_key_exists(1, $match)) ? trim($match[1]) : '';
}
return $this->audioCodec;
}
/**
* Return the number of audio channels in this movie as an integer.
*
* @return int
*/
public function getAudioChannels() {
if ($this->audioChannels === null) {
$match = array();
preg_match(self::$REGEX_AUDIO_CHANNELS, $this->output, $match);
if (array_key_exists(1, $match)) {
switch (trim($match[1])) {
case 'mono':
$this->audioChannels = 1; break;
case 'stereo':
$this->audioChannels = 2; break;
case '5.1':
$this->audioChannels = 6; break;
case '5:1':
$this->audioChannels = 6; break;
default:
$this->audioChannels = (int) $match[1];
}
} else {
$this->audioChannels = 0;
}
}
return $this->audioChannels;
}
/**
* Return boolean value indicating whether the movie has an audio stream.
*
* @return boolean
*/
public function hasAudio() {
return (boolean) preg_match(self::$REGEX_HAS_AUDIO, $this->output);
}
/**
* Return boolean value indicating whether the movie has a video stream.
*
* @return boolean
*/
public function hasVideo() {
return (boolean) preg_match(self::$REGEX_HAS_VIDEO, $this->output);
}
/**
* Returns a frame from the movie as an FFmpegFrame object. Returns false if the frame was not found.
*
* * framenumber - Frame from the movie to return. If no framenumber is specified, returns the next frame of the movie.
*
* @param int $framenumber
* @param int $height
* @param int $width
* @param int $quality
* @return FFmpegFrame|boolean
*/
public function getFrame($framenumber = null, $height = null, $width = null, $quality = null) {
$framePos = ($framenumber === null) ? $this->frameNumber : (((int) $framenumber) - 1);
// Frame position out of range
if (!is_numeric($framePos) || $framePos < 0 || $framePos > $this->getFrameCount()) {
return false;
}
$frameTime = round((($framePos / $this->getFrameCount()) * $this->getDuration()), 4);
$frame = $this->getFrameAtTime($frameTime, $height, $width, $quality);
// Increment internal frame number
if ($framenumber === null) {
++$this->frameNumber;
}
return $frame;
}
/**
* Returns a frame from the movie as an FFmpegFrame object. Returns false if the frame was not found.
*
* @param float $seconds
* @param int $width
* @param int $height
* @param int $quality
* @param string $frameFilePath
* @param array $output
*
* @throws Exception
*
* @return FFmpegFrame|boolean
*
*/
public function getFrameAtTime($seconds = null, $width = null, $height = null, $quality = null, $frameFilePath = null, &$output = null) {
// Set frame position for frame extraction
$frameTime = ($seconds === null) ? 0 : $seconds;
// time out of range
if (!is_numeric($frameTime) || $frameTime < 0 || $frameTime > $this->getDuration()) {
throw(new Exception('Frame time is not in range '.$frameTime.'/'.$this->getDuration().' '.$this->getFilename()));
}
if(is_numeric($height) && is_numeric($width)) {
$image_size = ' -s '.$width.'x'.$height;
} else {
$image_size = '';
}
if(is_numeric($quality)) {
$quality = ' -qscale '.$quality;
} else {
$quality = '';
}
$deleteTmp = false;
if ($frameFilePath === null) {
$frameFilePath = sys_get_temp_dir().DIRECTORY_SEPARATOR.uniqid('frame', true).'.jpg';
$deleteTmp = true;
}
$output = array();
// Fast and accurate way to seek. First quick-seek before input up to
// a point just before the frame, and then accurately seek after input
// to the exact point.
// See: http://ffmpeg.org/trac/ffmpeg/wiki/Seeking%20with%20FFmpeg
if ($frameTime > 30) {
$seek1 = $frameTime - 30;
$seek2 = 30;
} else {
$seek1 = 0;
$seek2 = $frameTime;
}
exec(implode(' ', array(
$this->ffmpegBinary,
'-ss '.$seek1,
'-i '.escapeshellarg($this->movieFile),
'-f image2',
'-ss '.$seek2,
'-vframes 1',
$image_size,
$quality,
escapeshellarg($frameFilePath),
'2>&1',
)), $output, $retVar);
$output = join(PHP_EOL, $output);
// Cannot write frame to the data storage
if (!file_exists($frameFilePath)) {
// Find error in output
preg_match(self::$REGEX_ERRORS, $output, $errors);
if ($errors) {
throw new Exception($errors[0]);
}
// Default file not found error
throw new Exception('TMP image not found/written '. $frameFilePath);
}
// Create gdimage and delete temporary image
$gdImage = imagecreatefromjpeg($frameFilePath);
if ($deleteTmp && is_writable($frameFilePath)) {
unlink($frameFilePath);
}
$frame = new FFmpegFrame($gdImage, $frameTime);
imagedestroy($gdImage);
return $frame;
}
/**
* Returns the next key frame from the movie as an FFmpegFrame object. Returns false if the frame was not found.
*
* @return FFmpegFrame|boolean
*/
public function getNextKeyFrame() {
return $this->getFrame();
}
public function __clone() {
$this->provider = clone $this->provider;
}
public function serialize() {
$data = serialize(array(
$this->ffmpegBinary,
$this->movieFile,
$this->output,
$this->frameNumber,
$this->provider
));
return $data;
}
public function unserialize($serialized) {
list($this->ffmpegBinary,
$this->movieFile,
$this->output,
$this->frameNumber,
$this->provider
) = unserialize($serialized);
}
}