PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/becomplete/enrollment123
PHP | 3981 lines | 2216 code | 216 blank | 1549 comment | 360 complexity | edf50c07061923642b7b7af8d90f17e3 MD5 | raw file
Possible License(s): AGPL-1.0

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

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

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