PageRenderTime 69ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/sites/all/modules/video/libraries/phpvideotoolkit/phpvideotoolkit.php5.php

https://bitbucket.org/priyadarshan_salkar/thinkshaddi
PHP | 3585 lines | 1847 code | 226 blank | 1512 comment | 363 complexity | 4eb049d3aced0707eddc3f2d885b42de MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, AGPL-1.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @file
  4. * Libary to access FFmpeg
  5. */
  6. /**
  7. * @author Oliver Lillie (aka buggedcom) <publicmail@buggedcom.co.uk>
  8. *
  9. * @license GPL 2.0
  10. *
  11. * @package FFMPEG (was called PHPVideoToolkit)
  12. * @version 0.1.9
  13. *
  14. * @abstract This class can be used in conjunction with several server binary libraries to manipulate video and audio
  15. * through PHP. It is not intended to solve any particular problems, however you may find it useful. This php class
  16. * is in no way associated with the actual FFmpeg releases. Any mistakes contained in this php class are mine and mine
  17. * alone.
  18. *
  19. * Please Note: There are several prerequisites that are required before this class can be used as an aid to manipulate
  20. * video and audio. You must at the very least have FFMPEG compiled on your server. If you wish to use this class for FLV
  21. * manipulation you must compile FFMPEG with LAME and Ruby's FLVTOOL2. I cannot answer questions regarding the install of
  22. * the server binaries needed by this class. I had too learn the hard way and it isn't easy, however it is a good learning
  23. * experience. For those of you who do need help read the install.txt file supplied along side this class. It wasn't written
  24. * by me however I found it useful when installing ffmpeg for the first time. The original source for the install.txt file
  25. * is located http://www.luar.com.hk/blog/?p=669 and the author is Lunar.
  26. *
  27. * @uses ffmpeg http://ffmpeg.org
  28. */
  29. if (!defined('DS')) {
  30. define('DS', DIRECTORY_SEPARATOR);
  31. }
  32. /**
  33. * Set the flvtool2 binary path
  34. */
  35. if (!defined('PHPVIDEOTOOLKIT_FLVTOOLS_BINARY')) {
  36. define('PHPVIDEOTOOLKIT_FLVTOOLS_BINARY', '/usr/bin/flvtool2');
  37. }
  38. /**
  39. * Set the watermark vhook path
  40. */
  41. if (!defined('PHPVIDEOTOOLKIT_FFMPEG_WATERMARK_VHOOK')) {
  42. define('PHPVIDEOTOOLKIT_FFMPEG_WATERMARK_VHOOK', '/usr/local/lib/vhook/watermark.so');
  43. }
  44. /**
  45. * Set the memcoder path
  46. */
  47. if (!defined('PHPVIDEOTOOLKIT_MENCODER_BINARY')) {
  48. define('PHPVIDEOTOOLKIT_MENCODER_BINARY', '/usr/local/bin/mencoder');
  49. }
  50. class PHPVideoToolkit {
  51. public $version = '0.1.9';
  52. /**
  53. * Error strings
  54. */
  55. protected $_messages = array(
  56. 'generic_temp_404' => 'The temporary directory does not exist.',
  57. 'generic_temp_writable' => 'The temporary directory is not write-able by the web server.',
  58. 'inputFileHasVideo_no_input' => 'Input file does not exist so no information can be retrieved.',
  59. 'inputFileHasAudio_no_input' => 'Input file does not exist so no information can be retrieved.',
  60. 'getFileInfo_no_input' => 'Input file does not exist so no information can be retrieved.',
  61. 'streamFLV_no_input' => 'Input file has not been set so the FLV cannot be streamed.',
  62. 'streamFLV_passed_eof' => 'You have tried to stream to a point in the file that does not exit.',
  63. 'setInputFile_file_existence' => 'Input file "#file" does not exist',
  64. 'extractAudio_valid_format' => 'Value "#format" set from $toolkit->extractAudio, is not a valid audio format. Valid values ffmpeg self::FORMAT_AAC, PHPVideoToolkit::FORMAT_AIFF, PHPVideoToolkit::FORMAT_MP2, PHPVideoToolkit::FORMAT_MP3, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG4, PHPVideoToolkit::FORMAT_M4A or PHPVideoToolkit::FORMAT_WAV. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-f" and $argument to your required value.',
  65. 'extractFrame_video_frame_rate_404' => 'You have attempted to extract a thumbnail from a video while automagically guessing the framerate of the video, but the framerate could not be accessed. You can remove this error by manually setting the frame rate of the video.',
  66. 'extractFrame_video_info_404' => 'You have attempted to extract a thumbnail from a video and check to see if the thumbnail exists, however it was not possible to access the video information. Please check your temporary directory permissions for read/write access by the webserver.',
  67. 'extractFrame_video_frame_count' => 'You have attempted to extract a thumbnail from a video but the thumbnail you are trying to extract does not exist in the video.',
  68. 'extractFrames_video_begin_frame_count' => 'You have attempted to extract thumbnails from a video but the thumbnail you are trying to start the extraction from does not exist in the video.',
  69. 'extractFrames_video_end_frame_count' => 'You have attempted to extract thumbnails from a video but the thumbnail you are trying to end the extraction at does not exist in the video.',
  70. 'setFormat_valid_format' => 'Value "#format" set from $toolkit->setFormat, is not a valid format. Valid values are PHPVideoToolkit::FORMAT_3GP2, PHPVideoToolkit::FORMAT_3GP, PHPVideoToolkit::FORMAT_AAC, PHPVideoToolkit::FORMAT_AIFF, PHPVideoToolkit::FORMAT_AMR, PHPVideoToolkit::FORMAT_ASF, PHPVideoToolkit::FORMAT_AVI, PHPVideoToolkit::FORMAT_FLV, PHPVideoToolkit::FORMAT_GIF, PHPVideoToolkit::FORMAT_MJ2, PHPVideoToolkit::FORMAT_MP2, PHPVideoToolkit::FORMAT_MP3, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG4, PHPVideoToolkit::FORMAT_M4A, PHPVideoToolkit::FORMAT_MPEG, PHPVideoToolkit::FORMAT_MPEG1, PHPVideoToolkit::FORMAT_MPEG2, PHPVideoToolkit::FORMAT_MPEGVIDEO, PHPVideoToolkit::FORMAT_PSP, PHPVideoToolkit::FORMAT_RM, PHPVideoToolkit::FORMAT_SWF, PHPVideoToolkit::FORMAT_VOB, PHPVideoToolkit::FORMAT_WAV, PHPVideoToolkit::FORMAT_JPG. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-f" and $argument to your required value.',
  71. 'setAudioChannels_valid_channels' => 'Value "#channels" set from $toolkit->setAudioChannels, is not a valid integer. Valid values are 1, or 2. If you wish to specifically try to set another channels value you should use the advanced function $toolkit->addCommand. Set $command to "-ac" and $argument to your required value.',
  72. 'setAudioSampleFrequency_valid_frequency' => 'Value "#frequency" set from $toolkit->setAudioSampleFrequency, is not a valid integer. Valid values are 11025, 22050, 44100. If you wish to specifically try to set another frequency you should use the advanced function $toolkit->addCommand. Set $command to "-ar" and $argument to your required value.',
  73. 'setAudioFormat_valid_format' => 'Value "#format" set from $toolkit->setAudioCodec, is not a valid format. Valid values are PHPVideoToolkit::FORMAT_AAC, PHPVideoToolkit::FORMAT_AIFF, PHPVideoToolkit::FORMAT_AMR, PHPVideoToolkit::FORMAT_ASF, PHPVideoToolkit::FORMAT_MP2, PHPVideoToolkit::FORMAT_MP3, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG2, PHPVideoToolkit::FORMAT_RM, PHPVideoToolkit::FORMAT_WAV. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-acodec" and $argument to your required value.',
  74. 'setAudioFormat_cannnot_encode' => 'Value "#codec" set from $toolkit->setAudioCodec, can not be used to encode the output as the version of FFmpeg that you are using does not have the capability to encode audio with this codec.',
  75. 'setVideoFormat_valid_format' => 'Value "#format" set from $toolkit->setVideoCodec, is not a valid format. Valid values are PHPVideoToolkit::FORMAT_3GP2, PHPVideoToolkit::FORMAT_3GP, PHPVideoToolkit::FORMAT_AVI, PHPVideoToolkit::FORMAT_FLV, PHPVideoToolkit::FORMAT_GIF, PHPVideoToolkit::FORMAT_MJ2, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG4, PHPVideoToolkit::FORMAT_M4A, PHPVideoToolkit::FORMAT_MPEG, PHPVideoToolkit::FORMAT_MPEG1, PHPVideoToolkit::FORMAT_MPEG2, PHPVideoToolkit::FORMAT_MPEGVIDEO. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-vcodec" and $argument to your required value.',
  76. 'setVideoFormat_cannnot_encode' => 'Value "#codec" set from $toolkit->setVideoCodec, can not be used to encode the output as the version of FFmpeg that you are using does not have the capability to encode video with this codec.',
  77. 'setAudioBitRate_valid_bitrate' => 'Value "#bitrate" set from $toolkit->setAudioBitRate, is not a valid integer. Valid values are 16, 32, 64, 128. If you wish to specifically try to set another bitrate you should use the advanced function $toolkit->addCommand. Set $command to "-ab" and $argument to your required value.',
  78. 'prepareImagesForConversionToVideo_one_img' => 'When compiling a movie from a series of images, you must include at least one image.',
  79. 'prepareImagesForConversionToVideo_img_404' => '"#img" does not exist.',
  80. 'prepareImagesForConversionToVideo_img_copy' => '"#img" can not be copied to "#tmpfile"',
  81. 'prepareImagesForConversionToVideo_img_type' => 'The images can not be prepared for conversion to video. Please make sure all images are of the same type, ie gif, png, jpeg and then try again.',
  82. 'setVideoOutputDimensions_valid_format' => 'Value "#format" set from $toolkit->setVideoOutputDimensions, is not a valid preset dimension. Valid values are PHPVideoToolkit::SIZE_SQCIF, PHPVideoToolkit::SIZE_SAS, PHPVideoToolkit::SIZE_QCIF, PHPVideoToolkit::SIZE_CIF, PHPVideoToolkit::SIZE_4CIF, PHPVideoToolkit::SIZE_QQVGA, PHPVideoToolkit::SIZE_QVGA, PHPVideoToolkit::SIZE_VGA, PHPVideoToolkit::SIZE_SVGA, PHPVideoToolkit::SIZE_XGA, PHPVideoToolkit::SIZE_UXGA, PHPVideoToolkit::SIZE_QXGA, PHPVideoToolkit::SIZE_SXGA, PHPVideoToolkit::SIZE_QSXGA, PHPVideoToolkit::SIZE_HSXGA, PHPVideoToolkit::SIZE_WVGA, PHPVideoToolkit::SIZE_WXGA, PHPVideoToolkit::SIZE_WSXGA, PHPVideoToolkit::SIZE_WUXGA, PHPVideoToolkit::SIZE_WOXGA, PHPVideoToolkit::SIZE_WQSXGA, PHPVideoToolkit::SIZE_WQUXGA, PHPVideoToolkit::SIZE_WHSXGA, PHPVideoToolkit::SIZE_WHUXGA, PHPVideoToolkit::SIZE_CGA, PHPVideoToolkit::SIZE_EGA, PHPVideoToolkit::SIZE_HD480, PHPVideoToolkit::SIZE_HD720, PHPVideoToolkit::SIZE_HD1080. You can also manually set the width and height.',
  83. 'setVideoOutputDimensions_sas_dim' => 'It was not possible to determine the input video dimensions so it was not possible to continue. If you wish to override this error please change the call to setVideoOutputDimensions and add a TRUE argument to the arguments list... setVideoOutputDimensions(PHPVideoToolkit::SIZE_SAS, TRUE);',
  84. 'setVideoOutputDimensions_valid_integer' => 'You tried to set the video output dimensions to an odd number. FFmpeg requires that the video output dimensions are of event value and divisible by 2. ie 2, 4, 6,... etc',
  85. 'setVideoAspectRatio_valid_ratio' => 'Value "#ratio" set from $toolkit->setVideoOutputDimensions, is not a valid preset dimension. Valid values are PHPVideoToolkit::RATIO_STANDARD, PHPVideoToolkit::RATIO_WIDE, PHPVideoToolkit::RATIO_CINEMATIC. If you wish to specifically try to set another video aspect ratio you should use the advanced function $toolkit->addCommand. Set $command to "-aspect" and $argument to your required value.',
  86. 'addWatermark_img_404' => 'Watermark file "#watermark" does not exist.',
  87. 'addWatermark_vhook_disabled' => 'Vhooking is not enabled in your FFmpeg binary. In order to allow video watermarking you must have FFmpeg compiled with --enable-vhook set. You can however watermark any extracted images using GD. To enable frame watermarking, call $toolkit->addGDWatermark($file) before you execute the extraction.',
  88. 'addVideo_file_404' => 'File "#file" does not exist.',
  89. 'setOutput_output_dir_404' => 'Output directory "#dir" does not exist!',
  90. 'setOutput_output_dir_writable' => 'Output directory "#dir" is not writable!',
  91. 'setOutput_%_missing' => 'The output of this command will be images yet you have not included the "%index" or "%timecode" in the $output_name.',
  92. 'setOutput_%d_depreciated' => 'The use of %d in the output file name is now depreciated. Please use %index. Number padding is still supported. You may also use %timecode instead to add a timecode to the filename.',
  93. 'execute_input_404' => 'Execute error. Input file missing.',
  94. 'execute_output_not_set' => 'Execute error. Output not set.',
  95. 'execute_temp_unwritable' => 'Execute error. The tmp directory supplied is not writable.',
  96. 'execute_overwrite_process' => 'Execute error. A file exists in the temp directory and is of the same name as this process file. It will conflict with this conversion. Conversion stopped.',
  97. 'execute_overwrite_fail' => 'Execute error. Output file exists. Process halted. If you wish to automatically overwrite files set the third argument in "PHPVideoToolkit::setOutput();" to "PHPVideoToolkit::OVERWRITE_EXISTING".',
  98. 'execute_ffmpeg_return_error' => 'Execute error. It was not possible to encode "#input" as FFmpeg returned an error. The error #stream of the input file. FFmpeg reports the error to be "#message".',
  99. 'execute_ffmpeg_return_error_multipass' => 'Execute error. It was not possible to encode "#input" as FFmpeg returned an error. Note, however the error was encountered on the second pass of the encoding process and the first pass appear to go fine. The error #stream of the input file. FFmpeg reports the error to be "#message".',
  100. 'execute_partial_error' => 'Execute error. Output for file "#input" encountered a partial error. Files were generated, however one or more of them were empty.',
  101. 'execute_image_error' => 'Execute error. Output for file "#input" was not found. No images were generated.',
  102. 'execute_output_404' => 'Execute error. Output for file "#input" was not found. Please check server write permissions and/or available codecs compiled with FFmpeg. You can check the encode decode availability by inspecting the output array from PHPVideoToolkit::getFFmpegInfo().',
  103. 'execute_output_empty' => 'Execute error. Output for file "#input" was found, but the file contained no data. Please check the available codecs compiled with FFmpeg can support this type of conversion. You can check the encode decode availability by inspecting the output array from PHPVideoToolkit::getFFmpegInfo().',
  104. 'execute_image_file_exists' => 'Execute error. There is a file name conflict. The file "#file" already exists in the filesystem. If you wish to automatically overwrite files set the third argument in "PHPVideoToolkit::setOutput();" to "PHPVideoToolkit::OVERWRITE_EXISTING".',
  105. 'execute_result_ok_but_unwritable' => 'Process Partially Completed. The process successfully completed however it was not possible to output to "#output". The output was left in the temp directory "#process" for a manual file movement.',
  106. 'execute_result_ok' => 'Process Completed. The process successfully completed. Output was generated to "#output".',
  107. 'ffmpeg_log_ffmpeg_output' => 'OUTPUT',
  108. 'ffmpeg_log_ffmpeg_result' => 'RESULT',
  109. 'ffmpeg_log_ffmpeg_command' => 'COMMAND',
  110. 'ffmpeg_log_ffmpeg_join_gunk' => 'FFMPEG JOIN OUTPUT',
  111. 'ffmpeg_log_ffmpeg_gunk' => 'FFMPEG OUTPUT',
  112. 'ffmpeg_log_separator' => '-------------------------------'
  113. );
  114. /**
  115. * Process Results from PHPVideoToolkit::execute
  116. */
  117. // any return value with this means everything is ok
  118. const RESULT_OK = TRUE;
  119. // any return value with this means the file has been processed/converted ok however it was
  120. // not able to be written to the output address. If this occurs you will need to move the
  121. // processed file manually from the temp location
  122. const RESULT_OK_BUT_UNWRITABLE = -1;
  123. /**
  124. * Codec support constants
  125. */
  126. const ENCODE = 'encode';
  127. const DECODE = 'decode';
  128. /**
  129. * Overwrite constants used in setOutput
  130. */
  131. const OVERWRITE_FAIL = 'fail';
  132. const OVERWRITE_PRESERVE = 'preserve';
  133. const OVERWRITE_EXISTING = 'existing';
  134. const OVERWRITE_UNIQUE = 'unique';
  135. /**
  136. * Formats supported
  137. * 3g2 3gp2 format
  138. * 3gp 3gp format
  139. * aac ADTS AAC
  140. * aiff Audio IFF
  141. * amr 3gpp amr file format
  142. * asf asf format
  143. * avi avi format
  144. * flv flv format
  145. * gif GIF Animation
  146. * mov mov format
  147. * mov,mp4,m4a,3gp,3g2,mj2 QuickTime/MPEG4/Motion JPEG 2000 format
  148. * mp2 MPEG audio layer 2
  149. * mp3 MPEG audio layer 3
  150. * mp4 mp4 format
  151. * mpeg MPEG1 System format
  152. * mpeg1video MPEG video
  153. * mpeg2video MPEG2 video
  154. * mpegvideo MPEG video
  155. * psp psp mp4 format
  156. * rm rm format
  157. * swf Flash format
  158. * vob MPEG2 PS format (VOB)
  159. * wav wav format
  160. * jpeg mjpeg format
  161. * yuv4mpegpipe yuv4mpegpipe format
  162. */
  163. const FORMAT_3GP2 = '3g2';
  164. const FORMAT_3GP = '3gp';
  165. const FORMAT_AAC = 'aac';
  166. const FORMAT_AIFF = 'aiff';
  167. const FORMAT_AMR = 'amr';
  168. const FORMAT_ASF = 'asf';
  169. const FORMAT_AVI = 'avi';
  170. const FORMAT_FLV = 'flv';
  171. const FORMAT_GIF = 'gif';
  172. const FORMAT_MJ2 = 'mj2';
  173. const FORMAT_MP2 = 'mp2';
  174. const FORMAT_MP3 = 'mp3';
  175. const FORMAT_MP4 = 'mp4';
  176. const FORMAT_MPEG4 = 'mpeg4';
  177. const FORMAT_M4A = 'm4a';
  178. const FORMAT_MPEG = 'mpeg';
  179. const FORMAT_MPEG1 = 'mpeg1video';
  180. const FORMAT_MPEG2 = 'mpeg2video';
  181. const FORMAT_MPEGVIDEO = 'mpegvideo';
  182. const FORMAT_PSP = 'psp';
  183. const FORMAT_RM = 'rm';
  184. const FORMAT_SWF = 'swf';
  185. const FORMAT_VOB = 'vob';
  186. const FORMAT_WAV = 'wav';
  187. const FORMAT_JPG = 'mjpeg';
  188. const FORMAT_Y4MP = 'yuv4mpegpipe';
  189. /**
  190. * Size Presets
  191. */
  192. const SIZE_SAS = 'SameAsSource';
  193. const SIZE_SQCIF = '128x96';
  194. const SIZE_QCIF = '176x144';
  195. const SIZE_CIF = '352x288';
  196. const SIZE_4CIF = '704x576';
  197. const SIZE_QQVGA = '160x120';
  198. const SIZE_QVGA = '320x240';
  199. const SIZE_VGA = '640x480';
  200. const SIZE_SVGA = '800x600';
  201. const SIZE_XGA = '1024x768';
  202. const SIZE_UXGA = '1600x1200';
  203. const SIZE_QXGA = '2048x1536';
  204. const SIZE_SXGA = '1280x1024';
  205. const SIZE_QSXGA = '2560x2048';
  206. const SIZE_HSXGA = '5120x4096';
  207. const SIZE_WVGA = '852x480';
  208. const SIZE_WXGA = '1366x768';
  209. const SIZE_WSXGA = '1600x1024';
  210. const SIZE_WUXGA = '1920x1200';
  211. const SIZE_WOXGA = '2560x1600';
  212. const SIZE_WQSXGA = '3200x2048';
  213. const SIZE_WQUXGA = '3840x2400';
  214. const SIZE_WHSXGA = '6400x4096';
  215. const SIZE_WHUXGA = '7680x4800';
  216. const SIZE_CGA = '320x200';
  217. const SIZE_EGA = '640x350';
  218. const SIZE_HD480 = '852x480';
  219. const SIZE_HD720 = '1280x720';
  220. const SIZE_HD1080 = '1920x1080';
  221. /**
  222. * Ratio Presets
  223. */
  224. const RATIO_STANDARD = '4:3';
  225. const RATIO_WIDE = '16:9';
  226. const RATIO_CINEMATIC = '1.85';
  227. /**
  228. * Audio Channel Presets
  229. */
  230. const AUDIO_STEREO = 2;
  231. const AUDIO_MONO = 1;
  232. /**
  233. * A public var that is to the information available about
  234. * the current ffmpeg compiled binary.
  235. * @var mixed
  236. * @access public
  237. */
  238. public static $ffmpeg_info = FALSE;
  239. /**
  240. * A public var that determines if the ffmpeg binary has been found. The default value
  241. * is NULL unless getFFmpegInfo is called whereby depending on the results it is set to
  242. * TRUE or FALSE
  243. * @var mixed
  244. * @access public
  245. */
  246. public static $ffmpeg_found = NULL;
  247. /**
  248. * A protected var that contains the info of any file that is accessed by PHPVideoToolkit::getFileInfo();
  249. * @var array
  250. * @access protected
  251. */
  252. protected static $_file_info = array();
  253. /**
  254. * Determines what happens when an error occurs
  255. * @var boolean If TRUE then the script will die, if not FALSE is return by the error
  256. * @access public
  257. */
  258. public $on_error_die = FALSE;
  259. /**
  260. * Holds the log file name
  261. * @var string
  262. * @access protected
  263. */
  264. protected $_log_file = NULL;
  265. /**
  266. * Determines if when outputting image frames if the outputted files should have the %d number
  267. * replaced with the frames timecode.
  268. * @var boolean If TRUE then the files will be renamed.
  269. * @access public
  270. */
  271. public $image_output_timecode = TRUE;
  272. /**
  273. * Holds the timecode separator for when using $image_output_timecode = TRUE
  274. * Not all systems allow ':' in filenames.
  275. * @var string
  276. * @access public
  277. */
  278. public $timecode_seperator_output = '-';
  279. /**
  280. * Holds the starting time code when outputting image frames.
  281. * @var string The timecode hh(n):mm:ss:ff
  282. * @access protected
  283. */
  284. protected $_image_output_timecode_start = '00:00:00.00';
  285. /**
  286. * The format in which the image %timecode placeholder string is outputted.
  287. * - %hh (hours) representative of hours
  288. * - %mm (minutes) representative of minutes
  289. * - %ss (seconds) representative of seconds
  290. * - %fn (frame number) representative of frames (of the current second, not total frames)
  291. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  292. * - %ft (frames total) representative of total frames (ie frame number)
  293. * - %st (seconds total) representative of total seconds (rounded).
  294. * - %sf (seconds floored) representative of total seconds (floored).
  295. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  296. * NOTE; there are special characters that will be replace by PHPVideoToolkit::$timecode_seperator_output, these characters are
  297. * - :
  298. * - .
  299. * @var string
  300. * @access public
  301. */
  302. protected $image_output_timecode_format = '%hh-%mm-%ss-%fn';
  303. /**
  304. * Holds the fps of image extracts
  305. * @var integer
  306. * @access protected
  307. */
  308. protected $_image_output_timecode_fps = 1;
  309. /**
  310. * Holds the current execute commands that will need to be combined
  311. * @var array
  312. * @access protected
  313. */
  314. protected $_commands = array();
  315. /**
  316. * Holds the commands executed
  317. * @var array
  318. * @access protected
  319. */
  320. protected $_processed = array();
  321. /**
  322. * Holds the file references to those that have been processed
  323. * @var array
  324. * @access protected
  325. */
  326. protected $_files = array();
  327. /**
  328. * Holds the errors encountered
  329. * @access protected
  330. * @var array
  331. */
  332. protected $_errors = array();
  333. /**
  334. * Holds the input file / input file sequence
  335. * @access protected
  336. * @var string
  337. */
  338. protected $_input_file = NULL;
  339. /**
  340. * Holds the output file / output file sequence
  341. * @access protected
  342. * @var string
  343. */
  344. protected $_output_address = NULL;
  345. /**
  346. * Holds the process file / process file sequence
  347. * @access protected
  348. * @var string
  349. */
  350. protected $_process_address = NULL;
  351. /**
  352. * Temporary filename prefix
  353. * @access protected
  354. * @var string
  355. */
  356. protected $_tmp_file_prefix = 'tmp_';
  357. /**
  358. * Holds the temporary directory name
  359. * @access protected
  360. * @var string
  361. */
  362. protected $_tmp_directory = NULL;
  363. /**
  364. * Holds the directory paths that need to be removed by the ___destruct function
  365. * @access protected
  366. * @var array
  367. */
  368. protected $_unlink_dirs = array();
  369. /**
  370. * Holds the file paths that need to be deleted by the ___destruct function
  371. * @access protected
  372. * @var array
  373. */
  374. protected $_unlink_files = array();
  375. /**
  376. * Holds the timer start micro-float.
  377. * @access protected
  378. * @var integer
  379. */
  380. protected $_timer_start = 0;
  381. /**
  382. * Holds the times taken to process each file.
  383. * @access protected
  384. * @var array
  385. */
  386. protected $_timers = array();
  387. /**
  388. * Holds the times taken to process each file.
  389. * @access protected
  390. * @var constant
  391. */
  392. protected $_overwrite_mode = NULL;
  393. /**
  394. * Holds a integer value that flags if the image extraction is just a single frame.
  395. * @access protected
  396. * @var integer
  397. */
  398. protected $_single_frame_extraction = NULL;
  399. /**
  400. * Holds the watermark file that is used to watermark any outputted images via GD.
  401. * @access protected
  402. * @var string
  403. */
  404. protected $_watermark_url = NULL;
  405. /**
  406. * Holds the watermark options used to watermark any outputted images via GD.
  407. * @access protected
  408. * @var array
  409. */
  410. protected $_watermark_options = NULL;
  411. /**
  412. * Holds the number of files processed per run.
  413. * @access protected
  414. * @var integer
  415. */
  416. protected $_process_file_count = 0;
  417. /**
  418. * Holds the times taken to process each file.
  419. * @access protected
  420. * @var array
  421. */
  422. protected $_post_processes = array();
  423. /**
  424. * Stores command output
  425. * @var array
  426. */
  427. protected $_command_output = array();
  428. // Stores the FFMPEG Binary Path
  429. protected $_ffmpeg_binary;
  430. /**
  431. * Constructs the class and sets the temporary directory.
  432. *
  433. * @access protected
  434. * @param string $tmp_directory A full absolute path to you temporary directory
  435. */
  436. function __construct($ffmpeg_binary = '/usr/bin/ffmpeg', $tmp_dir='/tmp/') {
  437. // print_r(array(debug_backtrace(), $tmp_dir));
  438. $this->_ffmpeg_binary = $ffmpeg_binary;
  439. $this->_tmp_directory = $tmp_dir;
  440. }
  441. public static function microtimeFloat() {
  442. list($usec, $sec) = explode(" ", microtime());
  443. return ((float) $usec + (float) $sec);
  444. }
  445. /**
  446. * Resets the class
  447. *
  448. * @access public
  449. * @param boolean $keep_input_file Determines whether or not to reset the input file currently set.
  450. */
  451. public function reset($keep_input_file=FALSE, $keep_processes=FALSE) {
  452. if ($keep_input_file === FALSE) {
  453. $this->_input_file = NULL;
  454. }
  455. if ($keep_processes === FALSE) {
  456. $this->_post_processes = array();
  457. }
  458. $this->_single_frame_extraction = NULL;
  459. $this->_output_address = NULL;
  460. $this->_process_address = NULL;
  461. $this->_log_file = NULL;
  462. $this->_commands = array();
  463. $this->_command_output = array();
  464. $this->_timer_start = 0;
  465. $this->_process_file_count = 0;
  466. $this->__destruct();
  467. }
  468. private function _captureExecBufferFallback() {
  469. $commands = func_get_args();
  470. foreach ($commands as $command) {
  471. $buffer = array();
  472. $err = 0;
  473. exec($command . ' 2>&1', $buffer, $err);
  474. if ($err === 0) {
  475. return $buffer;
  476. }
  477. }
  478. return array();
  479. }
  480. private function _captureExecBuffer($command) {
  481. $buffer = array();
  482. $err = 0;
  483. exec($command . ' 2>&1', $buffer, $err);
  484. if ($err !== 127) {
  485. if (isset($buffer[0]) === FALSE) {
  486. $tmp_file = $this->_tmp_directory . '_temp_' . uniqid(time() . '-') . '.txt';
  487. exec($command . ' &>' . $tmp_file, $buffer, $err);
  488. if ($handle = fopen($tmp_file, 'r')) {
  489. $buffer = array();
  490. while (!feof($handle)) {
  491. array_push($buffer, fgets($handle, 4096));
  492. }
  493. fclose($handle);
  494. }
  495. @unlink($tmp_file);
  496. }
  497. }
  498. $this->_command_output[] = array(
  499. 'command' => $command,
  500. 'output' => implode("\n", $buffer),
  501. );
  502. return $buffer;
  503. }
  504. /**
  505. * Returns information about the specified file without having to use ffmpeg-php
  506. * as it consults the ffmpeg binary directly.
  507. * NOTE: calling this statically for caching to work you must set the temp directory.
  508. *
  509. * @access public
  510. * @return mixed FALSE on error encountered, TRUE otherwise
  511. * */
  512. public function getFFmpegInfo($read_from_cache = TRUE) {
  513. // check to see if the info has already been cached
  514. if ($read_from_cache && PHPVideoToolkit::$ffmpeg_info !== FALSE) {
  515. return PHPVideoToolkit::$ffmpeg_info;
  516. }
  517. $data = array();
  518. $formats = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -formats');
  519. $codecs = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -codecs');
  520. $filters = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -bsfs');
  521. $protocols = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -protocols');
  522. $pixformats = $this->_captureExecBufferFallback($this->_ffmpeg_binary . ' -pix_fmts', $this->_ffmpeg_binary . ' -pix_fmt list');
  523. $help = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -h');
  524. self::$ffmpeg_found = $data['ffmpeg-found'] = !empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE;
  525. $data['compiler'] = array();
  526. $data['binary'] = array();
  527. $data['ffmpeg-php-support'] = self::hasFFmpegPHPSupport();
  528. // FFmpeg 0.5 and lower don't support -codecs, -bsfs or -protocols, but the info is in -formats
  529. if (strpos(end($codecs), 'missing argument for option')) {
  530. $formats = implode("\n", $formats);
  531. $codecs = $formats;
  532. $filters = $formats;
  533. $protocols = $formats;
  534. $pixformats = implode("\n", $pixformats);
  535. $help = implode("\n", $help);
  536. $data['raw'] = $formats . $pixformats;
  537. }
  538. else {
  539. $formats = implode("\n", $formats);
  540. $codecs = implode("\n", $codecs);
  541. $filters = implode("\n", $filters);
  542. $protocols = implode("\n", $protocols);
  543. $pixformats = implode("\n", $pixformats);
  544. $help = implode("\n", $help);
  545. $data['raw'] = $formats . "\n" . $codecs . "\n" . $filters . "\n" . $protocols . "\n" . $pixformats;
  546. }
  547. if (!self::$ffmpeg_found) {
  548. self::$ffmpeg_info = $data;
  549. return $data;
  550. }
  551. // grab the versions
  552. $data['binary']['versions'] = self::getVersion($data['raw']);
  553. // grab the ffmpeg configuration flags
  554. $config_flags = array();
  555. if (preg_match_all('/--[a-zA-Z0-9\-]+/', $formats, $config_flags)) {
  556. $data['binary']['configuration'] = $config_flags[0];
  557. $data['binary']['vhook-support'] = in_array('--enable-vhook', $config_flags[0]) || !in_array('--disable-vhook', $config_flags[0]);
  558. // grab the ffmpeg compile info
  559. preg_match('/built on (.*), gcc: (.*)/', $formats, $conf);
  560. if (count($conf) > 0) {
  561. $data['compiler']['gcc'] = $conf[2];
  562. $data['compiler']['build_date'] = $conf[1];
  563. $data['compiler']['build_date_timestamp'] = strtotime($conf[1]);
  564. }
  565. }
  566. // grab the file formats available to ffmpeg
  567. $formatmatches = array();
  568. $data['formats'] = array();
  569. if (preg_match_all('/ (DE|D|E) (.*) {1,} (.*)/', $formats, $formatmatches)) {
  570. // loop and clean
  571. // Formats:
  572. // D. = Demuxing supported
  573. // .E = Muxing supported
  574. for ($i = 0, $a = count($formatmatches[0]); $i < $a; $i++) {
  575. $data['formats'][strtolower(trim($formatmatches[2][$i]))] = array(
  576. 'mux' => $formatmatches[1][$i] == 'DE' || $formatmatches[1][$i] == 'E',
  577. 'demux' => $formatmatches[1][$i] == 'DE' || $formatmatches[1][$i] == 'D',
  578. 'fullname' => $formatmatches[3][$i]
  579. );
  580. }
  581. }
  582. // grab the codecs available
  583. $codecsmatches = array();
  584. $data['codecs'] = array('video' => array(), 'audio' => array(), 'subtitle' => array());
  585. if (preg_match_all('/ ((?:[DEVAST ]{6})|(?:[DEVASTFB ]{8})|(?:[DEVASIL\.]{6})) ([A-Za-z0-9\_]+) (.+)/', $codecs, $codecsmatches)) {
  586. // FFmpeg 0.12+
  587. // D..... = Decoding supported
  588. // .E.... = Encoding supported
  589. // ..V... = Video codec
  590. // ..A... = Audio codec
  591. // ..S... = Subtitle codec
  592. // ...I.. = Intra frame-only codec
  593. // ....L. = Lossy compression
  594. // .....S = Lossless compression
  595. // FFmpeg other
  596. // D..... = Decoding supported
  597. // .E.... = Encoding supported
  598. // ..V... = Video codec
  599. // ..A... = Audio codec
  600. // ..S... = Subtitle codec
  601. // ...S.. = Supports draw_horiz_band
  602. // ....D. = Supports direct rendering method 1
  603. // .....T = Supports weird frame truncation
  604. for ($i = 0, $a = count($codecsmatches[0]); $i < $a; $i++) {
  605. $options = preg_split('//', $codecsmatches[1][$i], -1, PREG_SPLIT_NO_EMPTY);
  606. if ($options) {
  607. $id = trim($codecsmatches[2][$i]);
  608. $type = $options[2] === 'V' ? 'video' : ($options[2] === 'A' ? 'audio' : 'subtitle');
  609. switch ($options[2]) {
  610. // video
  611. case 'V' :
  612. $data['codecs'][$type][$id] = array(
  613. 'encode' => isset($options[1]) === TRUE && $options[1] === 'E',
  614. 'decode' => isset($options[0]) === TRUE && $options[0] === 'D',
  615. 'draw_horizontal_band' => isset($options[3]) === TRUE && $options[3] === 'S',
  616. 'direct_rendering_method_1' => isset($options[4]) === TRUE && $options[4] === 'D',
  617. 'weird_frame_truncation' => isset($options[5]) === TRUE && $options[5] === 'T',
  618. 'fullname' => trim($codecsmatches[3][$i])
  619. );
  620. break;
  621. // audio
  622. case 'A' :
  623. // subtitle
  624. case 'S' :
  625. $data['codecs'][$type][$id] = array(
  626. 'encode' => isset($options[1]) === TRUE && $options[1] === 'E',
  627. 'decode' => isset($options[0]) === TRUE && $options[0] === 'D',
  628. 'fullname' => trim($codecsmatches[3][$i])
  629. );
  630. break;
  631. }
  632. }
  633. }
  634. }
  635. // grab the bitstream filters available to ffmpeg
  636. $data['filters'] = array();
  637. $locate = 'Bitstream filters:';
  638. if (!empty($filters) && ($pos = strpos($filters, $locate)) !== FALSE) {
  639. $filters = trim(substr($filters, $pos + strlen($locate)));
  640. $data['filters'] = explode("\n", $filters);
  641. }
  642. // grab the file protocols available to ffmpeg
  643. $data['protocols'] = array();
  644. $locate = 'Supported file protocols:';
  645. if (!empty($protocols) && ($pos = strpos($protocols, $locate)) !== FALSE) {
  646. $protocols = trim(substr($filters, $pos + strlen($locate)));
  647. $data['protocols'] = explode("\n", $protocols);
  648. }
  649. // grab the pixel formats available to ffmpeg
  650. $data['pixelformats'] = array();
  651. // Separate code for FFmpeg 0.5
  652. if (strpos($pixformats, 'Pixel formats') === FALSE) {
  653. // Format:
  654. // name nb_channels depth is_alpha
  655. // yuv420p 3 8 n
  656. // yuyv422 1 8 n
  657. $matches = array();
  658. preg_match_all('#(\w+)\s+(\d+)\s+(\d+)\s+(y|n)#', $pixformats, $matches, PREG_SET_ORDER);
  659. foreach ($matches as $match) {
  660. $data['pixelformats'][$match[1]] = array(
  661. 'encode' => TRUE, // Assume true
  662. 'decode' => TRUE, // Assume true
  663. 'components' => intval($match[2]),
  664. 'bpp' => intval($match[3]),
  665. );
  666. }
  667. }
  668. else {
  669. // Format:
  670. // Pixel formats:
  671. // I.... = Supported Input format for conversion
  672. // .O... = Supported Output format for conversion
  673. // ..H.. = Hardware accelerated format
  674. // ...P. = Paletted format
  675. // ....B = Bitstream format
  676. // FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL
  677. // -----
  678. // IO... yuv420p 3 12
  679. $matches = array();
  680. preg_match_all('#(I|\.)(O|\.)(H|\.)(P|\.)(B|\.)\s+(\w+)\s+(\d+)\s+(\d+)#', $pixformats, $matches, PREG_SET_ORDER);
  681. foreach ($matches as $match) {
  682. $data['pixelformats'][$match[6]] = array(
  683. 'encode' => $match[1] == 'I',
  684. 'decode' => $match[2] == 'O',
  685. 'components' => intval($match[7]),
  686. 'bpp' => intval($match[8]),
  687. );
  688. }
  689. }
  690. // grab the command line options available to ffmpeg
  691. $data['commandoptions'] = array();
  692. $matches = array();
  693. preg_match_all('#\n-(\w+)(?:\s+<(int|string|binary|flags|int64|float|rational)>)?#', $help, $matches, PREG_SET_ORDER);
  694. foreach ($matches as $match) {
  695. $data['commandoptions'][$match[1]] = array(
  696. 'datatype' => isset($match[2]) ? $match[2] : NULL,
  697. );
  698. }
  699. PHPVideoToolkit::$ffmpeg_info = $data;
  700. return $data;
  701. }
  702. /**
  703. * Returns the installed version of FFmpeg
  704. * @param $format
  705. * one of raw, version
  706. * @return $version
  707. * String, FFmpeg version
  708. */
  709. protected function getVersion($output) {
  710. // Search for SVN string
  711. // FFmpeg version SVN-r20438, Copyright (c) 2000-2009 Fabrice Bellard, et al.
  712. $pattern = "/(?:ffmpeg|avconv) version SVN-r([0-9.]*)/i";
  713. if (preg_match($pattern, $output, $matches)) {
  714. return $matches[1];
  715. }
  716. // Some OSX versions are built from a very early CVS
  717. // I do not know what to do with this version- using 1 for now
  718. $pattern = "/(?:ffmpeg|avconv) version.*CVS.*Mac OSX universal/msUi";
  719. if (preg_match($pattern, $output, $matches)) {
  720. return 0;
  721. }
  722. // Search for git string
  723. // FFmpeg version git-N-29240-gefb5fa7, Copyright (c) 2000-2011 the FFmpeg developers.
  724. // ffmpeg version N-31145-g59bd0fe, Copyright (c) 2000-2011 the FFmpeg developers
  725. $pattern = "/(?:ffmpeg|avconv) version.*N-([0-9.]*)/i";
  726. if (preg_match($pattern, $output, $matches)) {
  727. // Versions above this seem to be ok
  728. if ($matches[1] >= 29240) {
  729. return array(
  730. 'svn' => (int) $matches[1],
  731. 'version' => NULL, // Return NULL as there appears to be no version number.
  732. );
  733. }
  734. }
  735. // Do we have a release?
  736. // ffmpeg version 0.4.9-pre1, build 4736, Copyright (c) 2000-2004 Fabrice Bellard
  737. $pattern = "/(?:ffmpeg|avconv) version ([0-9.]*)/i";
  738. if (preg_match($pattern, $output, $matches)) {
  739. return $matches[1];
  740. }
  741. // Do we have a build version?
  742. // ffmpeg version 0.4.9-pre1, build 4736, Copyright (c) 2000-2004 Fabrice Bellard
  743. $pattern = "/(?:ffmpeg|avconv) version.*, build ([0-9]*)/i";
  744. if (preg_match($pattern, $output, $matches)) {
  745. return $matches[1];
  746. }
  747. return FALSE;
  748. }
  749. /**
  750. * Determines if your ffmpeg has particular codec support for encode or decode.
  751. *
  752. * @access public
  753. * @param $codec
  754. * The name of the codec you are checking for.
  755. * @param $support
  756. * PHPVideoToolkit::ENCODE or PHPVideoToolkit::DECODE, depending on which functionality is desired.
  757. * @return
  758. * Boolean FALSE if there is no support, TRUE if there is support.
  759. */
  760. public function hasCodecSupport($codec, $support=PHPVideoToolkit::ENCODE) {
  761. $codec = strtolower($codec);
  762. $data = $this->getFFmpegInfo();
  763. return isset($data['formats'][$codec]) === TRUE ? $data['formats'][$codec][$support] : FALSE;
  764. }
  765. /**
  766. * Determines the type of support that exists for the FFmpeg-PHP module.
  767. *
  768. * @access public
  769. * @return mixed. Boolean FALSE if there is no support, String 'module' if the actuall
  770. * FFmpeg-PHP module is loaded, or String 'emulated' if the FFmpeg-PHP classes
  771. * can be emulated through the adapter classes.
  772. */
  773. public function hasFFmpegPHPSupport() {
  774. return self::$ffmpeg_found === FALSE ? FALSE : (extension_loaded('ffmpeg') ? 'module' : (is_file(dirname(__FILE__) . DS . 'adapters' . DS . 'ffmpeg-php' . DS . 'ffmpeg_movie.php') && is_file(dirname(__FILE__) . DS . 'adapters' . DS . 'ffmpeg-php' . DS . 'ffmpeg_frame.php') && is_file(dirname(__FILE__) . DS . 'adapters' . DS . 'ffmpeg-php' . DS . 'ffmpeg_animated_gif.php') ? 'emulated' : FALSE));
  775. }
  776. /**
  777. * Determines if the ffmpeg binary has been compiled with vhook support.
  778. *
  779. * @access public
  780. * @return mixed. Boolean FALSE if there is no support, TRUE there is support.
  781. */
  782. public function hasVHookSupport() {
  783. $info = $this->getFFmpegInfo();
  784. return $info['binary']['vhook-support'];
  785. }
  786. /**
  787. * Returns information about the specified file without having to use ffmpeg-php
  788. * as it consults the ffmpeg binary directly. This idea for this function has been borrowed from
  789. * a French ffmpeg class located: http://www.phpcs.com/codesource.aspx?ID=45279
  790. *
  791. * @param $file
  792. * The absolute path of the file that is required to be manipulated.
  793. * @return
  794. * FALSE on error encountered, TRUE otherwise
  795. */
  796. public function getFileInfo($file = FALSE) {
  797. // if the file has not been specified check to see if an input file has been specified
  798. if ($file === FALSE) {
  799. if (!$this->_input_file) {
  800. return $this->_raiseError('getFileInfo_no_input');
  801. }
  802. $file = $this->_input_file;
  803. }
  804. $file = escapeshellarg($file);
  805. // create a hash of the filename
  806. $hash = md5($file);
  807. // check to see if the info has already been generated
  808. if (isset(self::$_file_info[$hash]) === TRUE) {
  809. return self::$_file_info[$hash];
  810. }
  811. // execute the ffmpeg lookup
  812. $buffer = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -i ' . $file);
  813. $buffer = implode("\r\n", $buffer);
  814. $data = $this->parseFileInfo($buffer);
  815. // check that some data has been obtained
  816. if (empty($data)) {
  817. $data = FALSE;
  818. }
  819. else {
  820. $data['_raw_info'] = $buffer;
  821. }
  822. // cache info and return
  823. return self::$_file_info[$hash] = $data;
  824. }
  825. /**
  826. * Parses file information returned by ffmpeg -i
  827. *
  828. * @param $raw
  829. * Return text of ffmpeg -i
  830. * @return
  831. * Array containing various data about the file
  832. */
  833. public function parseFileInfo($raw) {
  834. $data = array();
  835. $matches = array();
  836. // grab the duration and bitrate data
  837. preg_match_all('/Duration: (.*)/', $raw, $matches);
  838. if (!empty($matches)) {
  839. $line = trim($matches[0][0]);
  840. // capture any data
  841. preg_match_all('/(Duration|start|bitrate): ([^,]*)/', $line, $matches);
  842. // setup the default data
  843. $data['duration'] = array(
  844. 'timecode' => array(
  845. 'seconds' => array(
  846. 'exact' => -1,
  847. 'excess' => -1
  848. ),
  849. 'rounded' => -1,
  850. )
  851. );
  852. // get the data
  853. foreach ($matches[1] as $key => $detail) {
  854. $value = $matches[2][$key];
  855. switch (strtolower($detail)) {
  856. case 'duration' :
  857. $data['duration']['timecode']['rounded'] = substr($value, 0, 8);
  858. $data['duration']['timecode']['frames'] = array();
  859. $data['duration']['timecode']['frames']['exact'] = $value;
  860. $data['duration']['timecode']['frames']['excess'] = intval(substr($value, 9));
  861. break;
  862. case 'bitrate' :
  863. $data['bitrate'] = strtoupper($value) === 'N/A' ? -1 : intval($value);
  864. break;
  865. case 'start' :
  866. $data['duration']['start'] = $value;
  867. break;
  868. }
  869. }
  870. }
  871. // match the video stream info
  872. preg_match('/Stream(.*): Video: (.*)/', $raw, $matches);
  873. if (count($matches) > 0) {
  874. $data['video'] = array();
  875. // get the dimension parts
  876. preg_match('/([1-9][0-9]*)x([1-9][0-9]*)/', $matches[2], $dimensions_matches);
  877. $dimensions_value = $dimensions_matches[0];
  878. $data['video']['dimensions'] = array(
  879. 'width' => floatval($dimensions_matches[1]),
  880. 'height' => floatval($dimensions_matches[2])
  881. );
  882. // get the timebases
  883. $data['video']['time_bases'] = array();
  884. preg_match_all('/([0-9\.k]+) (fps|tbr|tbc|tbn)/', $matches[0], $fps_matches);
  885. if (count($fps_matches[0]) > 0) {
  886. foreach ($fps_matches[2] as $key => $abrv) {
  887. $data['video']['time_bases'][$abrv] = $fps_matches[1][$key];
  888. }
  889. }
  890. // get the video frames per second
  891. $data['duration']['timecode']['seconds']['total'] = $data['duration']['seconds'] = (float)$this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%ms', '%ss.%ms');
  892. $fps = isset($data['video']['time_bases']['fps']) === TRUE ? $data['video']['time_bases']['fps'] : (isset($data['video']['time_bases']['tbr']) === TRUE ? $data['video']['time_bases']['tbr'] : FALSE);
  893. if ($fps !== FALSE) {
  894. $fps = floatval($fps);
  895. $data['duration']['timecode']['frames']['frame_rate'] = $data['video']['frame_rate'] = $fps;
  896. // set the total frame count for the video
  897. $data['video']['frame_count'] = ceil($data['duration']['seconds'] * $data['video']['frame_rate']);
  898. $data['duration']['timecode']['frames']['exact'] = $this->formatTimecode($data['video']['frame_count'], '%ft', '%hh:%mm:%ss.%fn', $fps);
  899. $data['duration']['timecode']['frames']['total'] = $data['video']['frame_count'];
  900. }
  901. $fps_value = $fps_matches[0];
  902. // get the ratios
  903. preg_match('/\[PAR ([0-9\:\.]+) DAR ([0-9\:\.]+)\]/', $matches[0], $ratio_matches);
  904. if (count($ratio_matches)) {
  905. $data['video']['pixel_aspect_ratio'] = $ratio_matches[1];
  906. $data['video']['display_aspect_ratio'] = $ratio_matches[2];
  907. }
  908. // work out the number of frames
  909. if (isset($data['duration']) === TRUE && isset($data['video']) === TRUE) {
  910. // set the framecode
  911. $data['duration']['timecode']['seconds']['excess'] = floatval($data['duration']['seconds']) - floor($data['duration']['seconds']);
  912. $data['duration']['timecode']['seconds']['exact'] = $this->formatSeconds($data['duration']['seconds'], '%hh:%mm:%ss.%ms');
  913. }
  914. // formats should be anything left over, let me know if anything else exists
  915. $parts = explode(',', $matches[2]);
  916. $other_parts = array($dimensions_value, $fps_value);
  917. $formats = array();
  918. foreach ($parts as $key => $part) {
  919. $part = trim($part);
  920. if (!in_array($part, $other_parts)) {
  921. array_push($formats, $part);
  922. }
  923. }
  924. $data['video']['pixel_format'] = $formats[1];
  925. $data['video']['codec'] = $formats[0];
  926. }
  927. // match the audio stream info
  928. preg_match('/Stream(.*): Audio: (.*)/', $raw, $matches);
  929. if (count($matches) > 0) {
  930. // setup audio values
  931. $data['audio'] = array(
  932. 'stereo' => -1,
  933. 'sample_rate' => -1,
  934. 'sample_rate' => -1
  935. );
  936. $other_parts = array();
  937. // get the stereo value
  938. preg_match('/(stereo|mono)/i', $matches[0], $stereo_matches);
  939. if (count($stereo_matches)) {
  940. $data['audio']['stereo'] = $stereo_matches[0];
  941. array_push($other_parts, $stereo_matches[0]);
  942. }
  943. // get the sample_rate
  944. preg_match('/([0-9]{3,6}) Hz/', $matches[0], $sample_matches);
  945. if (count($sample_matches)) {
  946. $data['audio']['sample_rate'] = count($sample_matches) ? floatval($sample_matches[1]) : -1;
  947. array_push($other_parts, $sample_matches[0]);
  948. }
  949. // get the bit rate
  950. preg_match('/([0-9]{1,3}) kb\/s/', $matches[0], $bitrate_matches);
  951. if (count($bitrate_matches)) {
  952. $data['audio']['bitrate'] = count($bitrate_matches) ? floatval($bitrate_matches[1]) : -1;
  953. array_push($other_parts, $bitrate_matches[0]);
  954. }
  955. // formats should be anything left over, let me know if anything else exists
  956. $parts = explode(',', $matches[2]);
  957. $formats = array();
  958. foreach ($parts as $key => $part) {
  959. $part = trim($part);
  960. if (!in_array($part, $other_parts)) {
  961. array_push($formats, $part);
  962. }
  963. }
  964. $data['audio']['codec'] = $formats[0];
  965. // if no video is set then no audio frame rate is set
  966. if ($data['duration']['timecode']['seconds']['exact'] === -1) {
  967. $exact_timecode = $this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%fn', '%hh:%mm:%ss.%ms', 1000);
  968. $data['duration']['timecode']['seconds'] = array(
  969. 'exact' => $exact_timecode,
  970. 'excess' => intval(substr($exact_timecode, 8)),
  971. 'total' => $this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%fn', '%ss.%ms', 1000)
  972. );
  973. $data['duration']['timecode']['frames']['frame_rate'] = 1000;
  974. $data['duration']['seconds'] = $data['duration']['timecode']['seconds']['total'];
  975. }
  976. }
  977. return $data;
  978. }
  979. /**
  980. * Determines if the input media has a video stream.
  981. *
  982. * @access public
  983. * @param string $file The absolute path of the file that is required to be manipulated.
  984. * @return bool
  985. * */
  986. public function fileHasVideo($file=FALSE) {
  987. // check to see if this is a static call
  988. if ($file !== FALSE && isset($this) === FALSE) {
  989. $toolkit = new PHPVideoToolkit();
  990. $data = $toolkit->getFileInfo($file);
  991. }
  992. // if the file has not been specified check to see if an input file has been specified
  993. elseif ($file === FALSE) {
  994. if (!$this->_input_file) {
  995. // input file not valid
  996. return $this->_raiseError('inputFileHasVideo_no_input');
  997. // <- exits
  998. }
  999. $file = $this->_input_file;
  1000. $data = $this->getFileInfo($file);
  1001. }
  1002. return isset($data['video']);
  1003. }
  1004. /**
  1005. * Determines if the input media has an audio stream.
  1006. *
  1007. * @access public
  1008. * @param string $file The absolute path of the file that is required to be manipulated.
  1009. * @return bool
  1010. * */
  1011. public function fileHasAudio($file=FALSE) {
  1012. // check to see if this is a static call
  1013. if ($file !== FALSE && isset($this) === FALSE) {
  1014. $toolkit = new PHPVideoToolkit();
  1015. $data = $toolkit->getFileInfo($file);
  1016. }
  1017. // if the file has not been specified check to see if an input file has been specified
  1018. elseif ($file === FALSE) {
  1019. if (!$this->_input_file) {
  1020. // input file not valid
  1021. return $this->_raiseError('inputFileHasAudio_no_input');
  1022. // <- exits
  1023. }
  1024. $file = $this->_input_file;
  1025. $data = $this->getFileInfo($file);
  1026. }
  1027. return isset($data['audio']);
  1028. }
  1029. /**
  1030. * Sets the input file that is going to be manipulated.
  1031. *
  1032. * @access public
  1033. * @param string $file The absolute path of the file that is required to be manipulated.
  1034. * @param mixed $input_frame_rate If 0 (default) then no input frame rate is set, if FALSE it is automatically retrieved, otherwise
  1035. * any other integer will be set as the incoming frame rate.
  1036. * @return boolean FALSE on error encountered, TRUE otherwise
  1037. */
  1038. public function setInputFile($file, $input_frame_rate=0, $validate_decode_codecs=TRUE) {
  1039. $files_length = count($file);
  1040. // if the total number of files entered is 1 then only one file is being processed
  1041. if ($files_length == 1) {
  1042. // check the input file, if there is a %d in there or a similar %03d then the file inputted is a sequence, if neither of those is found
  1043. // then qheck to see if the file exists
  1044. if (!preg_match('/\%([0-9]+)d/', $file) && strpos($file, '%d') === FALSE && !is_file($file)) {
  1045. // input file not valid
  1046. return $this->_raiseError('setInputFile_file_existence', array('file' => $file));
  1047. // <- exits
  1048. }
  1049. $escaped_name = $file;
  1050. // $escaped_name = escapeshellarg($files[0]);
  1051. $this->_input

Large files files are truncated, but you can click here to view the full file