PageRenderTime 69ms CodeModel.GetById 16ms 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
  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_file = $escaped_name;
  1052. $this->_input_file_id = md5($escaped_name);
  1053. if ($input_frame_rate !== 0) {
  1054. $info = $this->getFileInfo();
  1055. if (isset($info['video']) === TRUE) {
  1056. if ($input_frame_rate === FALSE) {
  1057. $input_frame_rate = $info['video']['frame_rate'];
  1058. }
  1059. // input frame rate is a command hack
  1060. $this->addCommand('-r', $input_frame_rate, TRUE);
  1061. }
  1062. }
  1063. }
  1064. else {
  1065. // more than one video is being added as input so we must join them all
  1066. call_user_func_array(array(&$this, 'addVideo'), array($file, $input_frame_rate));
  1067. }
  1068. return TRUE;
  1069. }
  1070. /**
  1071. * A shortcut for converting video to FLV.
  1072. *
  1073. * @access public
  1074. * @param integer $audio_sample_frequency
  1075. * @param integer $audio_bitrate
  1076. * @param boolean $validate_codecs
  1077. * @return mixed
  1078. */
  1079. public function setFormatToFLV($audio_sample_frequency=44100, $audio_bitrate=64, $validate_codecs=TRUE) {
  1080. $this->addCommand('-sameq');
  1081. $audio_able = $this->setAudioFormat(self::FORMAT_MP3, $validate_codecs);
  1082. // adjust the audio rates
  1083. $this->setAudioBitRate($audio_bitrate);
  1084. $this->setAudioSampleFrequency($audio_sample_frequency);
  1085. // set the video format
  1086. $flv_able = $this->setFormat(self::FORMAT_FLV, $validate_codecs);
  1087. // flag that the flv has to have meta data added after the excecution of this command
  1088. // register the post tidy process
  1089. $this->registerPostProcess('_addMetaToFLV', $this);
  1090. return $audio_able !== FALSE && $flv_able !== FALSE;
  1091. }
  1092. /**
  1093. * When converting video to FLV the meta data has to be added by a ruby program called FLVTools2.
  1094. * This is a second exec call only after the video has been converted to FLV
  1095. * http://inlet-media.de/flvtool2
  1096. *
  1097. * @access protected
  1098. */
  1099. protected function _addMetaToFLV($files) {
  1100. $file = array_pop($files);
  1101. // prepare the command suitable for exec
  1102. $exec_string = $this->_prepareCommand(PHPVIDEOTOOLKIT_FLVTOOLS_BINARY, '-U ' . $file);
  1103. // execute the command
  1104. exec($exec_string);
  1105. if (is_array($this->_processed[0])) {
  1106. array_push($this->_processed[0], $exec_string);
  1107. }
  1108. else {
  1109. $this->_processed[0] = array($this->_processed[0], $exec_string);
  1110. }
  1111. return TRUE;
  1112. }
  1113. /**
  1114. * Streams a FLV file from a given point. You can control bandwidth, cache and session options.
  1115. * Inspired by xmoov-php
  1116. * @see http://xmoov.com/
  1117. * @access public
  1118. * @param integer $seek_pos The position in the file to seek to.
  1119. * @param array|boolean $bandwidth_options If a boolean value, FALSE then no bandwidth limiting will take place.
  1120. * If TRUE then bandwidth limiting will take place with packet_size = 90 and packet_interval = 0.3.
  1121. * If an array the following values are default packet_size = 90 and packet_interval = 0.3, you will also
  1122. * have to set active = TRUE, ie array('active'=>true, 'packet_size'=>90, 'packet_interval'=>0.3)
  1123. * @param boolean $allow_cache If TRUE the file will be allowed to cache in the browser, if FALSE then it won't
  1124. * @return boolean
  1125. */
  1126. public function flvStreamSeek($seek_pos=0, $bandwidth_options=array(), $allow_cache=TRUE) {
  1127. // check for input file
  1128. if (!$this->_input_file) {
  1129. // input file not valid
  1130. return $this->_raiseError('streamFLV_no_input');
  1131. // <- exits
  1132. }
  1133. // make the pos safe
  1134. $seek_pos = intval($seek_pos);
  1135. // absorb the bandwidth options
  1136. $bandwidth_options = is_array($bandwidth_options) ? array_merge(array('active' => FALSE, 'packet_size' => 90, 'packet_interval' => 0.3), $bandwidth_options) : array('active' => $bandwidth_options, 'packet_size' => 90, 'packet_interval' => 0.3);
  1137. // if this file is not allowed to be cached send cache headers for all browsers.
  1138. if (!$allow_cache) {
  1139. session_cache_limiter('nocache');
  1140. header('Expires: Thu, 19 Nov 1981 08:52:00 GMT');
  1141. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  1142. header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  1143. header('Pragma: no-cache');
  1144. }
  1145. // open file
  1146. $handle = fopen($this->_input_file, 'rb');
  1147. $file_size = filesize($this->_input_file) - (($seek_pos > 0) ? $seek_pos + 1 : 0);
  1148. // send the flv headers
  1149. header('Content-Type: video/x-flv');
  1150. header('Content-Disposition: attachment; filename="' . basename($this->_input_file) . '"');
  1151. header('Content-Length: ' . $file_size);
  1152. // flv format header
  1153. if ($seek_pos != 0) {
  1154. print('FLV');
  1155. print(pack('C', 1));
  1156. print(pack('C', 1));
  1157. print(pack('N', 9));
  1158. print(pack('N', 9));
  1159. }
  1160. // seek to the required point
  1161. if (fseek($handle, $seek_pos) === -1) {
  1162. // input file not valid
  1163. return $this->_raiseError('streamFLV_passed_eof');
  1164. // <- exits
  1165. }
  1166. // if bandwidth control is active then workout the options
  1167. if ($bandwidth_options['active']) {
  1168. $packet_interval = intval($bandwidth_options['packet_interval']);
  1169. $packet_size = intval($bandwidth_options['packet_size']) * 1042;
  1170. }
  1171. // output the file
  1172. while (!feof($handle)) {
  1173. // limit the bandwidth
  1174. if ($bandwidth_options['active'] && $packet_interval > 0) {
  1175. // output the required packet
  1176. $time_start = self::microtimeFloat();
  1177. echo fread($handle, $packet_size);
  1178. $time_stop = self::microtimeFloat();
  1179. // delay the output
  1180. $time_difference = $time_stop - $time_start;
  1181. if ($time_difference < $packet_interval) {
  1182. usleep(($packet_interval * 1000000) - ($time_difference * 1000000));
  1183. }
  1184. }
  1185. // no bandwidth limiting
  1186. else {
  1187. echo fread($handle, $file_size);
  1188. }
  1189. }
  1190. // close the file
  1191. fclose($handle);
  1192. return TRUE;
  1193. }
  1194. /**
  1195. * This is an alias for setFormat, but restricts it to audio only formats.
  1196. *
  1197. * @access public
  1198. * @param integer $format A supported audio format.
  1199. * @param integer $audio_sample_frequency
  1200. * @param integer $audio_bitrate
  1201. * */
  1202. public function extractAudio($format=PHPVideoToolkit::FORMAT_MP3, $audio_sample_frequency=44100, $audio_bitrate=64) {
  1203. // check the format is one of the audio formats
  1204. if (!in_array($format, array(self::FORMAT_AAC, self::FORMAT_AIFF, self::FORMAT_MP2, self::FORMAT_MP3, self::FORMAT_MP4, self::FORMAT_MPEG4, self::FORMAT_M4A, self::FORMAT_WAV))) {
  1205. return $this->_raiseError('extractAudio_valid_format', array('format' => $format));
  1206. // <- exits
  1207. }
  1208. $this->setFormat($format);
  1209. // adjust the audio rates
  1210. $this->setAudioBitRate($audio_bitrate);
  1211. $this->setAudioSampleFrequency($audio_sample_frequency);
  1212. }
  1213. /**
  1214. * Sets the new video format.
  1215. *
  1216. * @access public
  1217. * @param $format
  1218. * The format should use one of the defined variables stated below.
  1219. * PHPVideoToolkit::FORMAT_3GP2 - 3g2
  1220. * PHPVideoToolkit::FORMAT_3GP - 3gp
  1221. * PHPVideoToolkit::FORMAT_AAC - aac
  1222. * PHPVideoToolkit::FORMAT_AIFF - aiff
  1223. * PHPVideoToolkit::FORMAT_AMR - amr
  1224. * PHPVideoToolkit::FORMAT_ASF - asf
  1225. * PHPVideoToolkit::FORMAT_AVI - avi
  1226. * PHPVideoToolkit::FORMAT_FLV - flv
  1227. * PHPVideoToolkit::FORMAT_GIF - gif
  1228. * PHPVideoToolkit::FORMAT_MJ2 - mj2
  1229. * PHPVideoToolkit::FORMAT_MP2 - mp2
  1230. * PHPVideoToolkit::FORMAT_MP3 - mp3
  1231. * PHPVideoToolkit::FORMAT_MP4 - mp4
  1232. * PHPVideoToolkit::FORMAT_MPEG4 - mpeg4
  1233. * PHPVideoToolkit::FORMAT_M4A - m4a
  1234. * PHPVideoToolkit::FORMAT_MPEG - mpeg
  1235. * PHPVideoToolkit::FORMAT_MPEG1 - mpeg1video
  1236. * PHPVideoToolkit::FORMAT_MPEG2 - mpeg2video
  1237. * PHPVideoToolkit::FORMAT_MPEGVIDEO - mpegvideo
  1238. * PHPVideoToolkit::FORMAT_PSP - psp
  1239. * PHPVideoToolkit::FORMAT_RM - rm
  1240. * PHPVideoToolkit::FORMAT_SWF - swf
  1241. * PHPVideoToolkit::FORMAT_VOB - vob
  1242. * PHPVideoToolkit::FORMAT_WAV - wav
  1243. * PHPVideoToolkit::FORMAT_JPG - jpg
  1244. * @return boolean FALSE on error encountered, TRUE otherwise
  1245. */
  1246. public function setFormat($format) {
  1247. // validate input
  1248. if (!in_array($format, array(self::FORMAT_3GP2, self::FORMAT_3GP, self::FORMAT_AAC, self::FORMAT_AIFF, self::FORMAT_AMR, self::FORMAT_ASF, self::FORMAT_AVI, self::FORMAT_FLV, self::FORMAT_GIF, self::FORMAT_MJ2, self::FORMAT_MP2, self::FORMAT_MP3, self::FORMAT_MP4, self::FORMAT_MPEG4, self::FORMAT_M4A, self::FORMAT_MPEG, self::FORMAT_MPEG1, self::FORMAT_MPEG2, self::FORMAT_MPEGVIDEO, self::FORMAT_PSP, self::FORMAT_RM, self::FORMAT_SWF, self::FORMAT_VOB, self::FORMAT_WAV, self::FORMAT_JPG))) {
  1249. // return $this->_raiseError('setFormat_valid_format', array('format'=>$format));
  1250. // <- exits
  1251. }
  1252. return $this->addCommand('-f', $format);
  1253. }
  1254. public function setPixelFormat($format) {
  1255. $formats = $this->getAvailablePixelFormats();
  1256. if (in_array($format, $formats)) {
  1257. return $this->addCommand('-pix_fmt', $format);
  1258. }
  1259. return FALSE;
  1260. }
  1261. /**
  1262. * Sets the audio sample frequency for audio outputs
  1263. *
  1264. * @access public
  1265. * @param integer $audio_sample_frequency Valid values are 11025, 22050, 44100
  1266. * @return boolean FALSE on error encountered, TRUE otherwise
  1267. */
  1268. public function setAudioSampleFrequency($audio_sample_frequency) {
  1269. // validate input
  1270. if (!in_array(intval($audio_sample_frequency), array(11025, 22050, 44100))) {
  1271. return $this->_raiseError('setAudioSampleFrequency_valid_frequency', array('frequency' => $audio_sample_frequency));
  1272. // <- exits
  1273. }
  1274. return $this->addCommand('-ar', $audio_sample_frequency);
  1275. }
  1276. /**
  1277. * Sets the audio format for audio outputs
  1278. *
  1279. * @access public
  1280. * @param integer $audio_codec 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
  1281. * @param boolean $validate_codec Queries ffmpeg to see if this codec is available to use.
  1282. * @return boolean FALSE on error encountered, TRUE otherwise
  1283. */
  1284. public function setAudioCodec($audio_codec, $validate_codec=TRUE) {
  1285. // validate input
  1286. if (!in_array($audio_codec, array(self::FORMAT_AAC, self::FORMAT_AIFF, self::FORMAT_AMR, self::FORMAT_ASF, self::FORMAT_MP2, self::FORMAT_MP3, self::FORMAT_MP4, self::FORMAT_MPEG2, self::FORMAT_RM, self::FORMAT_WAV))) {
  1287. // return $this->_raiseError('setAudioFormat_valid_format', array('format'=>$audio_codec));
  1288. // <- exits
  1289. }
  1290. // run a libmp3lame check as it require different mp3 codec
  1291. // updated thanks to Varon for providing the research
  1292. if ($audio_codec == self::FORMAT_MP3) {
  1293. $info = $this->getFFmpegInfo();
  1294. if (isset($info['formats']['libmp3lame']) === TRUE || in_array('--enable-libmp3lame', $info['binary']['configuration']) === TRUE) {
  1295. $audio_codec = 'libmp3lame';
  1296. }
  1297. }
  1298. // do we need to validate this codec?
  1299. if ($validate_codec === TRUE) {
  1300. if ($this->canCodecBeEncoded('audio', $audio_codec) === FALSE) {
  1301. return $this->_raiseError('setAudioFormat_cannnot_encode', array('codec' => $audio_codec));
  1302. // <- exits
  1303. }
  1304. }
  1305. return $this->addCommand('-acodec', $audio_codec);
  1306. }
  1307. /**
  1308. * Forces the video format for video outputs to a specific codec. This should not be confused with setFormat. setVideoFormat does not generally need to
  1309. * be called unless setting a specific video format for a type of media format. It gets a little confusing...
  1310. *
  1311. * @access public
  1312. * @param integer $video_codec 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
  1313. * @param boolean $validate_codec Queries ffmpeg to see if this codec is available to use.
  1314. * @return boolean FALSE on error encountered, TRUE otherwise
  1315. */
  1316. public function setVideoCodec($video_codec, $validate_codec=TRUE) {
  1317. // validate input
  1318. if (!in_array($video_codec, array(self::FORMAT_3GP2, self::FORMAT_3GP, self::FORMAT_AVI, self::FORMAT_FLV, self::FORMAT_GIF, self::FORMAT_MJ2, self::FORMAT_MP4, self::FORMAT_MPEG4, self::FORMAT_M4A, self::FORMAT_MPEG, self::FORMAT_MPEG1, self::FORMAT_MPEG2, self::FORMAT_MPEGVIDEO))) {
  1319. // return $this->_raiseError('setVideoFormat_valid_format', array('format'=>$video_codec));
  1320. // <- exits
  1321. }
  1322. // do we need to validate this codec?
  1323. if ($validate_codec === TRUE) {
  1324. if ($this->canCodecBeEncoded('video', $video_codec) === FALSE) {
  1325. return $this->_raiseError('setVideoFormat_cannnot_encode', array('codec' => $video_codec));
  1326. // <- exits
  1327. }
  1328. }
  1329. return $this->addCommand('-strict experimental -vcodec', $video_codec);
  1330. }
  1331. /**
  1332. * Disables audio encoding
  1333. *
  1334. * @access public
  1335. * @return boolean FALSE on error encountered, TRUE otherwise
  1336. */
  1337. public function disableAudio() {
  1338. return $this->addCommand('-an');
  1339. }
  1340. /**
  1341. * Disables video encoding
  1342. *
  1343. * @access public
  1344. * @return boolean FALSE on error encountered, TRUE otherwise
  1345. */
  1346. public function disableVideo() {
  1347. return $this->addCommand('-vn');
  1348. }
  1349. /**
  1350. * Sets the number of audio channels
  1351. *
  1352. * @access public
  1353. * @param integer $channel_type Valid values are PHPVideoToolkit::AUDIO_MONO, PHPVideoToolkit::AUDIO_STEREO
  1354. * @return boolean FALSE on error encountered, TRUE otherwise
  1355. */
  1356. public function setAudioChannels($channel_type=PHPVideoToolkit::AUDIO_MONO) {
  1357. // validate input
  1358. if (!in_array($channel_type, array(self::AUDIO_MONO, self::AUDIO_STEREO))) {
  1359. return $this->_raiseError('setAudioChannels_valid_channels', array('channels' => $channel_type));
  1360. // <- exits
  1361. }
  1362. return $this->addCommand('-ac', $channel_type);
  1363. }
  1364. /**
  1365. * Sets the audio bitrate
  1366. *
  1367. * @access public
  1368. * @param integer $audio_bitrate Valid values are 16, 32, 64
  1369. * @return boolean FALSE on error encountered, TRUE otherwise
  1370. */
  1371. public function setAudioBitRate($bitrate) {
  1372. // validate input
  1373. if (!in_array(intval($bitrate), array(16, 32, 64, 128, 160, 256, 320))) {
  1374. // return $this->_raiseError('setAudioBitRate_valid_bitrate', array('bitrate'=>$bitrate));
  1375. // <- exits
  1376. }
  1377. return $this->addCommand('-ab', $bitrate);
  1378. }
  1379. /**
  1380. * Compiles an array of images into a video. This sets the input file (setInputFile) so you do not need to set it.
  1381. * The images should be a full absolute path to the actual image file.
  1382. * NOTE 1; This copies and renames all the supplied images into a temporary folder so the images don't have to be specifically named. However, when
  1383. * creating the ffmpeg instance you will need to set the absolute path to the temporary folder. The default path is '/tmp/'.
  1384. * NOTE 2; Please make sure all of the images are all of the same type.
  1385. *
  1386. * @access public
  1387. * @param array $images An array of images that are to be joined and converted into a video
  1388. * @param integer $input_frame_rate An integer that will specify the input frame rate for the images.
  1389. * @return boolean Returns FALSE on encountering an error
  1390. */
  1391. public function prepareImagesForConversionToVideo($images, $input_frame_rate) {
  1392. // http://ffmpeg.mplayerhq.hu/faq.html#TOC3
  1393. // ffmpeg -f image2 -i img%d.jpg /tmp/a.mpg
  1394. if (empty($images)) {
  1395. return $this->_raiseError('prepareImagesForConversionToVideo_one_img');
  1396. // <- exits
  1397. }
  1398. // loop through and validate existence first before making a temporary copy
  1399. foreach ($images as $key => $img) {
  1400. if (!is_file($img)) {
  1401. return $this->_raiseError('prepareImagesForConversionToVideo_img_404', array('img' => $img));
  1402. // <- exits
  1403. }
  1404. }
  1405. if (!is_dir($this->_tmp_directory)) {
  1406. return $this->_raiseError('generic_temp_404');
  1407. // <- exits
  1408. }
  1409. if (!is_writable($this->_tmp_directory)) {
  1410. return $this->_raiseError('generic_temp_writable');
  1411. // <- exits
  1412. }
  1413. // get the number of preceding places for the files based on how many files there are to copy
  1414. $total = count($images);
  1415. // create a temp dir in the temp dir
  1416. $uniqid = $this->unique();
  1417. mkdir($this->_tmp_directory . $uniqid, 0777);
  1418. // loop through, copy and rename specified images to the temp dir
  1419. $ext = FALSE;
  1420. foreach ($images as $key => $img) {
  1421. $file_ext = array_pop(explode('.', $img));
  1422. if ($ext !== FALSE && $ext !== $file_ext) {
  1423. return $this->_raiseError('prepareImagesForConversionToVideo_img_type');
  1424. // <- exits
  1425. }
  1426. $ext = $file_ext;
  1427. $tmp_file = $this->_tmp_directory . $uniqid . DS . $this->_tmp_file_prefix . $key . '.' . $ext;
  1428. if (!@copy($img, $tmp_file)) {
  1429. return $this->_raiseError('prepareImagesForConversionToVideo_img_copy', array('img' => $img, 'tmpfile' => $tmp_file));
  1430. // <- exits
  1431. }
  1432. // push the tmp file name into the unlinks so they can be deleted on class destruction
  1433. array_push($this->_unlink_files, $tmp_file);
  1434. }
  1435. // the inputr is a hack for -r to come before the input
  1436. $this->addCommand('-r', $input_frame_rate, TRUE);
  1437. // exit;
  1438. // add the directory to the unlinks
  1439. array_push($this->_unlink_dirs, $this->_tmp_directory . $uniqid);
  1440. // get the input file format
  1441. $file_iteration = $this->_tmp_file_prefix . '%d.' . $ext;
  1442. // set the input filename
  1443. return $this->setInputFile($this->_tmp_directory . $uniqid . DS . $file_iteration);
  1444. }
  1445. /**
  1446. * Sets the video bitrate
  1447. *
  1448. * @access public
  1449. * @param integer $bitrate
  1450. * @return boolean
  1451. */
  1452. public function setVideoBitRate($bitrate) {
  1453. $bitrate = intval($bitrate);
  1454. return $this->addCommand('-b', $bitrate . 'k');
  1455. }
  1456. /**
  1457. * Sets the amount of time an animated gif output will loop
  1458. *
  1459. * @access public
  1460. * @param integer $loop_count If FALSE the gif will not loop, if 0 it will loop endlessly, any other number it will loop that amount.
  1461. */
  1462. public function setGifLoops($loop_count) {
  1463. if ($loop_count !== FALSE) {
  1464. $this->addCommand('-loop_output', $loop_count);
  1465. }
  1466. }
  1467. /**
  1468. * Sets the video output dimensions (in pixels)
  1469. *
  1470. * @access public
  1471. * @param mixed $width If an integer height also has to be specified, otherwise you can use one of the class constants
  1472. * PHPVideoToolkit::SIZE_SAS = Same as input source
  1473. * PHPVideoToolkit::SIZE_SQCIF = 128 x 96
  1474. * PHPVideoToolkit::SIZE_QCIF = 176 x 144
  1475. * PHPVideoToolkit::SIZE_CIF = 352 x 288
  1476. * PHPVideoToolkit::SIZE_4CIF = 704 x 576
  1477. * PHPVideoToolkit::SIZE_QQVGA = 160 x 120
  1478. * PHPVideoToolkit::SIZE_QVGA = 320 x 240
  1479. * PHPVideoToolkit::SIZE_VGA = 640 x 480
  1480. * PHPVideoToolkit::SIZE_SVGA = 800 x 600
  1481. * PHPVideoToolkit::SIZE_XGA = 1024 x 768
  1482. * PHPVideoToolkit::SIZE_UXGA = 1600 x 1200
  1483. * PHPVideoToolkit::SIZE_QXGA = 2048 x 1536
  1484. * PHPVideoToolkit::SIZE_SXGA = 1280 x 1024
  1485. * PHPVideoToolkit::SIZE_QSXGA = 2560 x 2048
  1486. * PHPVideoToolkit::SIZE_HSXGA = 5120 x 4096
  1487. * PHPVideoToolkit::SIZE_WVGA = 852 x 480
  1488. * PHPVideoToolkit::SIZE_WXGA = 1366 x 768
  1489. * PHPVideoToolkit::SIZE_WSXGA = 1600 x 1024
  1490. * PHPVideoToolkit::SIZE_WUXGA = 1920 x 1200
  1491. * PHPVideoToolkit::SIZE_WOXGA = 2560 x 1600
  1492. * PHPVideoToolkit::SIZE_WQSXGA = 3200 x 2048
  1493. * PHPVideoToolkit::SIZE_WQUXGA = 3840 x 2400
  1494. * PHPVideoToolkit::SIZE_WHSXGA = 6400 x 4096
  1495. * PHPVideoToolkit::SIZE_WHUXGA = 7680 x 4800
  1496. * PHPVideoToolkit::SIZE_CGA = 320 x 200
  1497. * PHPVideoToolkit::SIZE_EGA = 640 x 350
  1498. * PHPVideoToolkit::SIZE_HD480 = 852 x 480
  1499. * PHPVideoToolkit::SIZE_HD720 = 1280 x 720
  1500. * PHPVideoToolkit::SIZE_HD1080 = 1920 x 1080
  1501. * @param integer $height
  1502. * @return boolean
  1503. */
  1504. public function setVideoDimensions($width=PHPVideoToolkit::SIZE_SAS, $height=NULL) {
  1505. if ($height === NULL || $height === TRUE) {
  1506. // validate input
  1507. if (!in_array($width, array(self::SIZE_SAS, self::SIZE_SQCIF, self::SIZE_QCIF, self::SIZE_CIF, self::SIZE_4CIF, self::SIZE_QQVGA, self::SIZE_QVGA, self::SIZE_VGA, self::SIZE_SVGA, self::SIZE_XGA, self::SIZE_UXGA, self::SIZE_QXGA, self::SIZE_SXGA, self::SIZE_QSXGA, self::SIZE_HSXGA, self::SIZE_WVGA, self::SIZE_WXGA, self::SIZE_WSXGA, self::SIZE_WUXGA, self::SIZE_WOXGA, self::SIZE_WQSXGA, self::SIZE_WQUXGA, self::SIZE_WHSXGA, self::SIZE_WHUXGA, self::SIZE_CGA, self::SIZE_EGA, self::SIZE_HD480, self::SIZE_HD720, self::SIZE_HD1080))) {
  1508. return $this->_raiseError('setVideoOutputDimensions_valid_format', array('format' => $format));
  1509. // <- exits
  1510. }
  1511. if ($width === self::SIZE_SAS) {
  1512. // and override is made so no command is added in the hope that ffmpeg will just output the source
  1513. if ($height === TRUE) {
  1514. return TRUE;
  1515. }
  1516. // get the file info
  1517. $info = $this->getFileInfo();
  1518. if (isset($info['video']) === FALSE || isset($info['video']['dimensions']) === FALSE) {
  1519. return $this->_raiseError('setVideoOutputDimensions_sas_dim');
  1520. }
  1521. else {
  1522. $width = $info['video']['dimensions']['width'] . 'x' . $info['video']['dimensions']['height'];
  1523. }
  1524. }
  1525. }
  1526. else {
  1527. $height_split = explode(' ', $height);
  1528. // check that the width and height are even
  1529. if ($width % 2 !== 0 || $height_split[0] % 2 !== 0) {
  1530. return $this->_raiseError('setVideoOutputDimensions_valid_integer');
  1531. // <- exits
  1532. }
  1533. $width = $width . 'x' . $height_split[0];
  1534. }
  1535. $this->addCommand('-s', $width);
  1536. if (isset($height_split) && count($height_split) > 1) {
  1537. $commands = $height_split;
  1538. array_shift($commands);
  1539. $commands = implode(' ', $commands);
  1540. preg_match_all('/-(\S*)\s(\S*)/', $commands, $matches);
  1541. foreach ($matches[0] as $match) {
  1542. $command = explode(' ', $match);
  1543. if (count($command) == 2) {
  1544. $command[0] = preg_replace('/\"/', '', $command[0]);
  1545. $command[1] = preg_replace('/\"/', '', $command[1]);
  1546. $this->addCommand($command[0], $command[1]);
  1547. }
  1548. }
  1549. }
  1550. return TRUE;
  1551. }
  1552. /**
  1553. * Sets the video aspect ratio.
  1554. * IMPORTANT! Setting an aspect ratio will change the width of the video output if the specified dimensions aren't already
  1555. * in the correct ratio. ie, Setting the aspect ratio to RATIO_STANDARD when you set the output dimensions to 176 x 144
  1556. * will in fact output a video with 192 x 144, but the information returned by ffmpeg will give return the size as 176 x 144
  1557. * which is obviously invalid.
  1558. *
  1559. * @access public
  1560. * @param string|integer $ratio Valid values are PHPVideoToolkit::RATIO_STANDARD, PHPVideoToolkit::RATIO_WIDE, PHPVideoToolkit::RATIO_CINEMATIC, or '4:3', '16:9', '1.85'
  1561. * @return boolean
  1562. */
  1563. public function setVideoAspectRatio($ratio) {
  1564. if (!in_array($ratio, array(self::RATIO_STANDARD, self::RATIO_WIDE, self::RATIO_CINEMATIC))) {
  1565. return $this->_raiseError('setVideoAspectRatio_valid_ratio', array('ratio' => $ratio));
  1566. }
  1567. $this->addCommand('-aspect', $ratio);
  1568. return TRUE;
  1569. }
  1570. /**
  1571. * Sets the frame rate of the video
  1572. *
  1573. * @access public
  1574. * @param string|integer $fps 1 being 1 frame per second, 1:2 being 0.5 frames per second
  1575. * @return boolean
  1576. */
  1577. public function setVideoFrameRate($fps) {
  1578. return $this->addCommand('-r', $fps);
  1579. }
  1580. /**
  1581. * Sets the video bitrate
  1582. *
  1583. * @access public
  1584. * @param integer $bitrate
  1585. * @return boolean
  1586. */
  1587. public function setVideoPreset($preset) {
  1588. return $this->addCommand('-vpre', $preset);
  1589. }
  1590. /**
  1591. * Extracts a segment of video and/or audio
  1592. * (Note; If set to 1 and the duration set by $extract_begin_timecode and $extract_end_timecode is equal to 1 you get more than one frame.
  1593. * For example if you set $extract_begin_timecode='00:00:00' and $extract_end_timecode='00:00:01' you might expect because the time span is
  1594. * 1 second only to get one frame if you set $frames_per_second=1. However this is not correct. The timecode you set in $extract_begin_timecode
  1595. * acts as the beginning frame. Thus in this example the first frame exported will be from the very beginning of the video, the video will
  1596. * then move onto the next frame and export a frame there. Therefore if you wish to export just one frame from one position in the video,
  1597. * say 1 second in you should set $extract_begin_timecode='00:00:01' and set $extract_end_timecode='00:00:01'.)
  1598. *
  1599. * @access public
  1600. * @param string $extract_begin_timecode A timecode (hh:mm:ss.fn - you can change the timecode format by changing the $timecode_format param
  1601. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info)
  1602. * @param string|integer|boolean $extract_end_timecode A timecode (hh:mm:ss.fn - you can change the timecode format by changing the $timecode_format param
  1603. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info)
  1604. * @param integer $timecode_format The format of the $extract_begin_timecode and $extract_end_timecode timecodes are being given in.
  1605. * default '%hh:%mm:%ss'
  1606. * - %hh (hours) representative of hours
  1607. * - %mm (minutes) representative of minutes
  1608. * - %ss (seconds) representative of seconds
  1609. * - %fn (frame number) representative of frames (of the current second, not total frames)
  1610. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  1611. * - %ft (frames total) representative of total frames (ie frame number)
  1612. * - %st (seconds total) representative of total seconds (rounded).
  1613. * - %sf (seconds floored) representative of total seconds (floored).
  1614. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  1615. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  1616. * @param boolean $check_frames_exist Determines if a frame exists check should be made to ensure the timecode given by $extract_end_timecode
  1617. * actually exists.
  1618. */
  1619. public function extractSegment($extract_begin_timecode, $extract_end_timecode, $timecode_format='%hh:%mm:%ss.%fn', $frames_per_second=FALSE, $check_frames_exist=TRUE) {
  1620. // check for frames per second, if it's not set auto set it.
  1621. if ($frames_per_second === FALSE) {
  1622. $info = $this->getFileInfo();
  1623. $frames_per_second = $info['duration']['timecode']['frames']['frame_rate'];
  1624. }
  1625. // check if frame exists
  1626. if ($check_frames_exist) {
  1627. if ($info['duration']['seconds'] < floatval($this->formatTimecode($extract_end_timecode, $timecode_format, '%ss.%ms', $frames_per_second))) {
  1628. // the input has not returned any video data so the frame rate can not be guessed
  1629. return $this->_raiseError('extractSegment_end_timecode');
  1630. }
  1631. elseif ($extract_end_timecode !== FALSE && $info['duration']['seconds'] < floatval($this->formatTimecode($extract_begin_timecode, $timecode_format, '%ss.%ms', $frames_per_second))) {
  1632. // the input has not returned any video data so the frame rate can not be guessed
  1633. return $this->_raiseError('extractSegment_begin_timecode');
  1634. }
  1635. }
  1636. // format the begin timecode if the timecode format is not already ok.
  1637. $begin_position = (float) $this->formatTimecode($extract_begin_timecode, $timecode_format, '%ss.%ms', $frames_per_second);
  1638. if ($timecode_format !== '%hh:%mm:%ss.%ms') {
  1639. $extract_begin_timecode = $this->formatTimecode($extract_begin_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1640. }
  1641. $this->addCommand('-ss', $extract_begin_timecode);
  1642. // allows for exporting the entire timeline
  1643. if ($extract_end_timecode !== FALSE) {
  1644. $end_position = (float) $this->formatTimecode($extract_end_timecode, $timecode_format, '%ss.%ms', $frames_per_second);
  1645. // format the end timecode if the timecode format is not already ok.
  1646. if ($timecode_format !== '%hh:%mm:%ss.%ms') {
  1647. $extract_end_timecode = $this->formatTimecode($extract_end_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1648. }
  1649. $this->addCommand('-t', $end_position - $begin_position);
  1650. }
  1651. return TRUE;
  1652. }
  1653. /**
  1654. * Extracts frames from a video.
  1655. * (Note; If set to 1 and the duration set by $extract_begin_timecode and $extract_end_timecode is equal to 1 you get more than one frame.
  1656. * For example if you set $extract_begin_timecode='00:00:00' and $extract_end_timecode='00:00:01' you might expect because the time span is
  1657. * 1 second only to get one frame if you set $frames_per_second=1. However this is not correct. The timecode you set in $extract_begin_timecode
  1658. * acts as the beginning frame. Thus in this example the first frame exported will be from the very beginning of the video, the video will
  1659. * then move onto the next frame and export a frame there. Therefore if you wish to export just one frame from one position in the video,
  1660. * say 1 second in you should set $extract_begin_timecode='00:00:01' and set $extract_end_timecode='00:00:01'.)
  1661. *
  1662. * @access public
  1663. * @param string $extract_begin_timecode A timecode (hh:mm:ss.fn - you can change the timecode format by changing the $timecode_format param
  1664. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info)
  1665. * @param string|integer|boolean $extract_end_timecode A timecode (hh:mm:ss.fn - you can change the timecode format by changing the $timecode_format param
  1666. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info), or FALSE
  1667. * if all frames from the begin timecode are to be exported. (Boolean added by Matthias. Thanks. 12th March 2007)
  1668. * @param boolean|integer $frames_per_second The number of frames per second to extract. If left as default FALSE, then the number of frames per second
  1669. * will be automagically gained from PHPVideoToolkit::fileGetInfo();
  1670. * @param boolean|integer $frame_limit Frame limiter. If set to FALSE then all the frames will be exported from the given time codes, however
  1671. * if you wish to set a export limit to the number of frames that are exported you can set an integer. For example; if you set
  1672. * $extract_begin_timecode='00:00:11.01', $extract_end_timecode='00:01:10.01', $frames_per_second=1, you will get one frame for every second
  1673. * in the video between 00:00:11 and 00:01:10 (ie 60 frames), however if you ant to artificially limit this to exporting only ten frames
  1674. * then you set $frame_limit=10. You could of course alter the timecode to reflect you desired frame number, however there are situations
  1675. * when a shortcut such as this is useful and necessary.
  1676. * @param integer $timecode_format The format of the $extract_begin_timecode and $extract_end_timecode timecodes are being given in.
  1677. * default '%hh:%mm:%ss'
  1678. * - %hh (hours) representative of hours
  1679. * - %mm (minutes) representative of minutes
  1680. * - %ss (seconds) representative of seconds
  1681. * - %fn (frame number) representative of frames (of the current second, not total frames)
  1682. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  1683. * - %ft (frames total) representative of total frames (ie frame number)
  1684. * - %st (seconds total) representative of total seconds (rounded).
  1685. * - %sf (seconds floored) representative of total seconds (floored).
  1686. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  1687. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  1688. * @param boolean $check_frames_exist Determines if a frame exists check should be made to ensure the timecode given by $extract_end_timecode
  1689. * actually exists.
  1690. */
  1691. public function extractFrames($extract_begin_timecode, $extract_end_timecode, $frames_per_second=FALSE, $frame_limit=FALSE, $timecode_format='%hh:%mm:%ss.%fn', $check_frames_exist=TRUE) {
  1692. // are we autoguessing the frame rate?
  1693. if ($frames_per_second === FALSE || $check_frames_exist) {
  1694. // get the file info, will exit if no input has been set
  1695. $info = $this->getFileInfo();
  1696. if ($info === FALSE || isset($info['video']) === FALSE) {
  1697. // the input has not returned any video data so the frame rate can not be guessed
  1698. return $this->_raiseError('extractFrame_video_frame_rate_404');
  1699. }
  1700. $frames_per_second = $info['video']['frame_rate'];
  1701. }
  1702. // check if frame exists
  1703. if ($check_frames_exist) {
  1704. if ($info['video']['frame_count'] < $this->formatTimecode($extract_end_timecode, $timecode_format, '%ft', $frames_per_second)) {
  1705. // the input has not returned any video data so the frame rate can not be guessed
  1706. return $this->_raiseError('extractFrames_video_end_frame_count');
  1707. }
  1708. elseif ($extract_end_timecode !== FALSE && $info['video']['frame_count'] < $this->formatTimecode($extract_begin_timecode, $timecode_format, '%ft', $frames_per_second)) {
  1709. // the input has not returned any video data so the frame rate can not be guessed
  1710. return $this->_raiseError('extractFrames_video_begin_frame_count');
  1711. }
  1712. }
  1713. // disable audio output
  1714. $this->disableAudio();
  1715. // format the begin timecode if the timecode format is not already ok.
  1716. /*
  1717. if($timecode_format !== '%hh:%mm:%ss.%ms')
  1718. {
  1719. $extract_begin_timecode = $this->formatTimecode($extract_begin_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1720. }
  1721. */
  1722. // Use seek before the input tag to quickly move to the approximate location,
  1723. // then use the seek after the input tag to locate the exact frames.
  1724. // See http://ffmpeg.org/trac/ffmpeg/wiki/Seeking%20with%20FFmpeg
  1725. $seconds = $this->formatTimecode($extract_begin_timecode, $timecode_format, '%st', $frames_per_second);
  1726. if ($seconds > 5) {
  1727. $this->addCommand('-ss', $this->formatTimecode($seconds - 5, $timecode_format, '%hh:%mm:%ss:%ms', $frames_per_second), TRUE);
  1728. $this->addCommand('-ss', $this->formatTimecode(5, $timecode_format, '%hh:%mm:%ss:%ms', $frames_per_second), FALSE);
  1729. }
  1730. else {
  1731. $this->addCommand('-ss', $extract_begin_timecode);
  1732. }
  1733. // added by Matthias on 12th March 2007
  1734. // allows for exporting the entire timeline
  1735. if ($extract_end_timecode !== FALSE) {
  1736. // format the end timecode if the timecode format is not already ok.
  1737. if ($timecode_format !== '%hh:%mm:%ss.%ms') {
  1738. $extract_end_timecode = $this->formatTimecode($extract_end_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1739. }
  1740. $this->addCommand('-t', $extract_end_timecode);
  1741. }
  1742. // set the output frame rate
  1743. $this->setVideoFrameRate($frames_per_second);
  1744. // do we need to limit the number of frames outputted?
  1745. if ($frame_limit !== FALSE) {
  1746. $this->addCommand('-vframes', $frame_limit);
  1747. }
  1748. $this->_image_output_timecode_start = $extract_begin_timecode;
  1749. $this->_image_output_timecode_fps = $frames_per_second;
  1750. }
  1751. /**
  1752. * Extracts exactly one frame
  1753. *
  1754. * @access public
  1755. * @uses $toolkit->extractFrames
  1756. * @param string $frame_timecode A timecode (hh:mm:ss.fn) where fn is the frame number of that second
  1757. * @param integer|boolean $frames_per_second The frame rate of the movie. If left as the default, FALSE. We will use PHPVideoToolkit::getFileInfo() to get
  1758. * the actual frame rate. It is recommended that it is left as FALSE because an incorrect frame rate may produce unexpected results.
  1759. * @param integer $timecode_format The format of the $extract_begin_timecode and $extract_end_timecode timecodes are being given in.
  1760. * default '%hh:%mm:%ss'
  1761. * - %hh (hours) representative of hours
  1762. * - %mm (minutes) representative of minutes
  1763. * - %ss (seconds) representative of seconds
  1764. * - %fn (frame number) representative of frames (of the current second, not total frames)
  1765. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  1766. * - %ft (frames total) representative of total frames (ie frame number)
  1767. * - %st (seconds total) representative of total seconds (rounded).
  1768. * - %sf (seconds floored) representative of total seconds (floored).
  1769. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  1770. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  1771. * @param boolean $check_frame_exists Makes an explicit check to see if the frame exists, default = TRUE.
  1772. * Thanks to Istvan Szakacs for suggesting this check. Note, to improve performance disable this check.
  1773. */
  1774. public function extractFrame($frame_timecode, $frames_per_second=FALSE, $frame_timecode_format='%hh:%mm:%ss.%fn', $check_frame_exists=TRUE) {
  1775. // get the file info, will exit if no input has been set
  1776. if ($check_frame_exists || $frames_per_second === FALSE) {
  1777. $info = $this->getFileInfo();
  1778. if ($info === FALSE || isset($info['video']) === FALSE) {
  1779. // the input has not returned any video data so the frame rate can not be guessed
  1780. return $this->_raiseError('extractFrame_video_info_404');
  1781. }
  1782. }
  1783. // are we autoguessing the frame rate?
  1784. if ($frames_per_second === FALSE) {
  1785. if (isset($info['video']['frame_rate']) === FALSE) {
  1786. // the input has not returned any video data so the frame rate can not be guessed
  1787. return $this->_raiseError('extractFrame_video_frame_rate_404');
  1788. }
  1789. $frames_per_second = $info['video']['frame_rate'];
  1790. }
  1791. // check if frame exists
  1792. if ($check_frame_exists) {
  1793. if ($info['video']['frame_count'] < $this->formatTimecode($frame_timecode, $frame_timecode_format, '%ft', $frames_per_second)) {
  1794. // the input has not returned any video data so the frame rate can not be guessed
  1795. return $this->_raiseError('extractFrame_video_frame_count');
  1796. }
  1797. }
  1798. // format the frame details if the timecode format is not already ok.
  1799. /*
  1800. if($frame_timecode_format !== '%hh:%mm:%ss.%ms')
  1801. $frame_timecode = $this->formatTimecode($frame_timecode, $frame_timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1802. }
  1803. */
  1804. $this->_single_frame_extraction = 1;
  1805. // we will limit the number of frames produced so the desired frame is the last image
  1806. // this way we limit the cpu usage of ffmpeg
  1807. // Thanks to Istvan Szakacs for pointing out that ffmpeg can export frames using the -ss hh:mm:ss[.xxx]
  1808. // it has saved a lot of cpu intensive processes.
  1809. $this->extractFrames($frame_timecode, $frame_timecode, $frames_per_second, 1, $frame_timecode_format, FALSE);
  1810. // register the post tidy process
  1811. // $this->registerPostProcess('_extractFrameTidy', $this);
  1812. }
  1813. // /**
  1814. // * Tidies up after ffmpeg exports all frames from one second of video.
  1815. // *
  1816. // * @access public
  1817. // * @uses $toolkit->extractFrames
  1818. // * @param string $frame_timecode A timecode (hh:mm:ss.fn) where fn is the frame number of that second
  1819. // * @param integer|boolean $frames_per_second The frame rate of the movie. If left as the default, FALSE. We will use PHPVideoToolkit::getFileInfo() to get
  1820. // * the actual frame rate. It is recommended that it is left as FALSE because an incorrect frame rate may produce unexpected results.
  1821. // */
  1822. // protected function _extractFrameTidy(&$files)
  1823. // {
  1824. // $frame_number = 1;
  1825. // $frame_file = array();
  1826. // // print_r($files);
  1827. // foreach($files as $file=>$filename)
  1828. // {
  1829. // // print_R(array($this->_single_frame_extraction, $frame_number));
  1830. // if($this->_single_frame_extraction == $frame_number)
  1831. // {
  1832. // // leave this file alone as it is the required frame
  1833. // $frame_file[$file] = $filename;
  1834. // }
  1835. // else
  1836. // {
  1837. // // add the frame to the unlink files list
  1838. // array_push($this->_unlink_files, $file);
  1839. // }
  1840. // $frame_number += 1;
  1841. // }
  1842. // // print_r($frame_file);
  1843. // // update the files list
  1844. // $files = $frame_file;
  1845. // return TRUE;
  1846. // }
  1847. /**
  1848. * Adds a watermark to the outputted files. This effects both video and image output.
  1849. *
  1850. * @access public
  1851. * @param string $watermark_url The absolute path to the watermark image.
  1852. * @param string $vhook The absolute path to the ffmpeg vhook watermark library.
  1853. * @param string $watermark_options Any additional options to supply to the vhook.
  1854. */
  1855. public function addWatermark($watermark_url, $vhook=PHPVIDEOTOOLKIT_FFMPEG_WATERMARK_VHOOK, $watermark_options=FALSE) {
  1856. // check to see if the ffmpeg binary has support for vhooking
  1857. if (!$this->hasVHookSupport()) {
  1858. return $this->_raiseError('addWatermark_vhook_disabled');
  1859. }
  1860. // does the file exist?
  1861. if (!is_file($watermark_url)) {
  1862. return $this->_raiseError('addWatermark_img_404', array('watermark' => $watermark_url));
  1863. }
  1864. // determine which vhook library is being called and set appropriate input param
  1865. // vhook depricated so now we have to ues http://ffmpeg.org/libavfilter.html
  1866. $file_input_switch = preg_match("/watermark.*/", $vhook) ? ' -f ' : ' -i ';
  1867. $this->addCommand('-vhook', $vhook . $file_input_switch . $watermark_url . ($watermark_options !== FALSE ? ' ' . $watermark_options : ''));
  1868. }
  1869. /**
  1870. * Adds a watermark to the outputted image files using the PHP GD module.
  1871. * This effects only image output.
  1872. *
  1873. * @access public
  1874. * @param string $watermark_url The absolute path to the watermark image.
  1875. */
  1876. public function addGDWatermark($watermark_url, $options=array('x-offset' => 0, 'y-offset' => 0, 'position' => 'bottom-right')) {
  1877. // does the file exist?
  1878. if (!is_file($watermark_url)) {
  1879. return $this->_raiseError('addWatermark_img_404', array('watermark' => $watermark_url));
  1880. }
  1881. // save the watermark_url
  1882. $this->_watermark_url = $watermark_url;
  1883. $this->_watermark_options = array_merge(array('x-offset' => 0, 'y-offset' => 0, 'position' => 'bottom-right'), $options);
  1884. // register the post process
  1885. $this->registerPostProcess('_addGDWatermark', $this);
  1886. }
  1887. /**
  1888. * Adds watermark to any outputted images via GD instead of using vhooking.
  1889. *
  1890. * @access protected
  1891. * @param array $files An array of image files.
  1892. * @return array
  1893. */
  1894. protected function _addGDWatermark($files) {
  1895. // create the watermark resource and give it alpha blending
  1896. $info = pathinfo($this->_watermark_url);
  1897. switch (strtolower($info['extension'])) {
  1898. case 'jpeg' :
  1899. case 'jpg' :
  1900. $watermark = imagecreatefromjpeg($this->_watermark_url);
  1901. break;
  1902. case 'gif' :
  1903. $watermark = imagecreatefromgif($this->_watermark_url);
  1904. break;
  1905. case 'png' :
  1906. $watermark = imagecreatefrompng($this->_watermark_url);
  1907. break;
  1908. default :
  1909. return FALSE;
  1910. }
  1911. imagealphablending($watermark, TRUE);
  1912. imagesavealpha($watermark, TRUE);
  1913. // get the watermark dimensions
  1914. $watermark_width = imagesx($watermark);
  1915. $watermark_height = imagesy($watermark);
  1916. // $image = imagecreatetruecolor($watermark_width, $watermark_height);
  1917. // loop and watermark each file
  1918. $blended_files = array();
  1919. foreach ($files as $file => $filename) {
  1920. // detect the file extension and create the resource from them appropriate function
  1921. $info = pathinfo($file);
  1922. $quality = $output_function = NULL;
  1923. switch (strtolower($info['extension'])) {
  1924. case 'jpeg' :
  1925. case 'jpg' :
  1926. $quality = 80;
  1927. $output_function = 'imagejpeg';
  1928. $image = imagecreatefromjpeg($file);
  1929. break;
  1930. case 'gif' :
  1931. $output_function = 'imagegif';
  1932. $image = imagecreatefromgif($file);
  1933. break;
  1934. case 'png' :
  1935. $quality = 9;
  1936. $output_function = 'imagepng';
  1937. $image = imagecreatefrompng($file);
  1938. break;
  1939. default :
  1940. continue 1;
  1941. }
  1942. // the dimensions will/should be the same for each image however still best to check
  1943. $image_width = imagesx($image);
  1944. $image_height = imagesy($image);
  1945. // calculate where to position the watermark
  1946. $dest_x = 0;
  1947. $dest_y = 0;
  1948. switch ($this->_watermark_options['position']) {
  1949. case 'top-left' :
  1950. $dest_x = 0;
  1951. $dest_y = 0;
  1952. break;
  1953. case 'top-middle' :
  1954. $dest_x = ($image_width - $watermark_width) / 2;
  1955. $dest_y = 0;
  1956. break;
  1957. case 'top-right' :
  1958. $dest_x = $image_width - $watermark_width;
  1959. $dest_y = 0;
  1960. break;
  1961. case 'center-left' :
  1962. $dest_x = 0;
  1963. $dest_y = ($image_height - $watermark_height) / 2;
  1964. break;
  1965. case 'center-middle' :
  1966. $dest_x = ($image_width - $watermark_width) / 2;
  1967. $dest_y = ($image_height - $watermark_height) / 2;
  1968. break;
  1969. case 'center-right' :
  1970. $dest_x = $image_width - $watermark_width;
  1971. $dest_y = ($image_height - $watermark_height) / 2;
  1972. break;
  1973. case 'bottom-left' :
  1974. $dest_x = 0;
  1975. $dest_y = $image_height - $watermark_height;
  1976. break;
  1977. case 'bottom-middle' :
  1978. $dest_x = ($image_width - $watermark_width) / 2;
  1979. $dest_y = $image_height - $watermark_height;
  1980. break;
  1981. case 'bottom-right' :
  1982. default :
  1983. $dest_x = $image_width - $watermark_width;
  1984. $dest_y = $image_height - $watermark_height;
  1985. break;
  1986. }
  1987. $dest_x += $this->_watermark_options['x-offset'];
  1988. $dest_y += $this->_watermark_options['y-offset'];
  1989. // copy the watermark to the new image
  1990. imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
  1991. // delete the old image
  1992. unlink($file);
  1993. // save the new image in place of the old
  1994. $output_function($image, $file, $quality);
  1995. // remove the image resouce
  1996. imagedestroy($image);
  1997. array_push($blended_files, $file);
  1998. }
  1999. // remove the watermark resource
  2000. imagedestroy($watermark);
  2001. return $blended_files;
  2002. }
  2003. // /**
  2004. // * This will overlay an audio file over the top of a video file
  2005. // **/
  2006. // public function overlayAudio($audio_file)
  2007. // {
  2008. // $this->addCommand('-newaudio', '');
  2009. // }
  2010. /**
  2011. * This will adjust the audio volume.
  2012. *
  2013. * @access public
  2014. * @param integer $vol 256 = normal
  2015. * */
  2016. public function adjustVolume($vol=256) {
  2017. $this->addCommand('-vol', '');
  2018. }
  2019. /**
  2020. * This process will combine the original input video with the video specified by this function.
  2021. * This function accepts more than one video as arguments. They will be added in order of the arguments.
  2022. * ie. input_video -> video1 -> video2 etc
  2023. * The process of doing this can take a long time as each incoming video has to be first converted
  2024. * into a format that accepts joining. The default joining codec is "mpg". However for almost lossless
  2025. * quality you can use the "yuv4mpegpipe" format. This is of course dependent upon your ffmpeg binary.
  2026. * You can check to see if you server supports yuv4mpegpipe by typing "ffmpeg -formats" into the
  2027. * command line. If you want to use the yuv4mpegpipe format you can add the flag, FFMPEG_USE_HQ_JOIN to the
  2028. * end of the video inputs. WARNING: High Quality joins will take longer to process. (well duh!)
  2029. *
  2030. * @access public
  2031. * @param $video1, $video2, $video3... $video(n) Paths of videos to attach to the input video.
  2032. * @param $flag integer FFMPEG_USE_HQ_JOIN If you wish to use the yuv4mpegpipe format for join add this to the end of the video list.
  2033. */
  2034. public function addVideo() {
  2035. $videos = func_get_args();
  2036. $videos_length = count($videos);
  2037. // is last arg the hq join flag
  2038. // check to see if a starter file has been added, if not set the input as an array
  2039. if ($this->_input_file === NULL) {
  2040. $this->_input_file = array();
  2041. }
  2042. // if the input file is already set as a string that means as start file has been added so absorb into the input array
  2043. elseif (is_string($this->_input_file)) {
  2044. $this->_input_file = array($this->_input_file);
  2045. }
  2046. foreach ($videos as $key => $file) {
  2047. if (!preg_match('/\%([0-9]+)d/', $file) && strpos($file, '%d') === FALSE && !is_file($file)) {
  2048. // input file not valid
  2049. return $this->_raiseError('addVideo_file_404', array('file' => $file));
  2050. // <- exits
  2051. }
  2052. array_push($this->_input_file, $file);
  2053. // array_push($this->_input_file, escapeshellarg($file));
  2054. }
  2055. }
  2056. /**
  2057. * @access public
  2058. * @uses addVideo()
  2059. */
  2060. public function addVideos() {
  2061. $videos = func_get_args();
  2062. call_user_func_array(array(&$this, 'addVideo'), $videos);
  2063. }
  2064. /**
  2065. * Sets the output.
  2066. *
  2067. * @access public
  2068. * @param string $output_directory The directory to output the command output to
  2069. * @param string $output_name The filename to output to.
  2070. * (Note; if you are outputting frames from a video then you will need to add an extra item to the output_name. The output name you set is required
  2071. * to contain '%d'. '%d' is replaced by the image number. Thus entering setting output_name $output_name='img%d.jpg' will output
  2072. * 'img1.jpg', 'img2.jpg', etc... However 'img%03d.jpg' generates `img001.jpg', `img002.jpg', etc...)
  2073. * @param boolean $overwrite_mode Accepts one of the following class constants
  2074. * - PHPVideoToolkit::OVERWRITE_FAIL - This produces an error if there is a file conflict and the processing is halted.
  2075. * - PHPVideoToolkit::OVERWRITE_PRESERVE - This continues with the processing but no file overwrite takes place. The processed file is left in the temp directory
  2076. * for you to manually move.
  2077. * - PHPVideoToolkit::OVERWRITE_EXISTING - This will replace any existing files with the freshly processed ones.
  2078. * - PHPVideoToolkit::OVERWRITE_UNIQUE - This will appended every output with a unique hash so that the filesystem is preserved.
  2079. * @return boolean FALSE on error encountered, TRUE otherwise
  2080. */
  2081. public function setOutput($output_directory, $output_name, $overwrite_mode=PHPVideoToolkit::OVERWRITE_FAIL) {
  2082. // check if directoy exists
  2083. if (!is_dir($output_directory)) {
  2084. return $this->_raiseError('setOutput_output_dir_404', array('dir' => $output_directory));
  2085. // <- exits
  2086. }
  2087. // check if directory is writeable
  2088. if (!is_writable($output_directory)) {
  2089. return $this->_raiseError('setOutput_output_dir_writable', array('dir' => $output_directory));
  2090. // <- exits
  2091. }
  2092. $process_name = '';
  2093. // check to see if a output delimiter is set
  2094. $has_d = preg_match('/\%([0-9]+)d/', $output_name) || strpos($output_name, '%d') !== FALSE;
  2095. if ($has_d) {
  2096. return $this->_raiseError('setOutput_%d_depreciated');
  2097. // <- exits
  2098. }
  2099. else {
  2100. // determine if the extension is an image. If it is then we will be extracting frames so check for %d
  2101. $output_name_info = pathinfo($output_name);
  2102. $is_image = in_array(strtolower($output_name_info['extension']), array('jpg', 'jpeg', 'png'));
  2103. $is_gif = strtolower($output_name_info['extension']) === 'gif';
  2104. // NOTE: for now we'll just stick to the common image formats, SUBNOTE: gif is ignore because ffmpeg can create animated gifs
  2105. if ($this->_single_frame_extraction !== NULL && strpos($output_name, '%timecode') === FALSE && !(preg_match('/\%index/', $output_name) || strpos($output_name, '%index') !== FALSE) && $is_image) {
  2106. // return $this->_raiseError('setOutput_%_missing');
  2107. // <- exits
  2108. }
  2109. $process_name = '.' . $output_name_info['extension'];
  2110. if ($is_image || ($this->_single_frame_extraction !== NULL && $is_gif)) {
  2111. $process_name = '-%12d' . $process_name;
  2112. }
  2113. }
  2114. // set the output address
  2115. $this->_output_address = $output_directory . $output_name;
  2116. // set the processing address in the temp folder so it does not conflict with any other conversions
  2117. $this->_process_address = $this->_tmp_directory . $this->unique() . $process_name;
  2118. $this->_overwrite_mode = $overwrite_mode;
  2119. return TRUE;
  2120. }
  2121. /**
  2122. * Sets a constant quality value to the encoding. (but a variable bitrate)
  2123. *
  2124. * @param integer $quality The quality to adhere to. 100 is highest quality, 1 is the lowest quality
  2125. */
  2126. public function setConstantQuality($quality) {
  2127. // interpret quality into ffmpeg value
  2128. $quality = 31 - round(($quality / 100) * 31);
  2129. if ($quality > 31) {
  2130. $quality = 31;
  2131. }
  2132. elseif ($quality < 1) {
  2133. $quality = 1;
  2134. }
  2135. return $this->addCommand('-qscale', $quality);
  2136. }
  2137. /**
  2138. * Translates a number of seconds to a timecode.
  2139. * NOTE: this is now a depreciated, use formatSeconds() instead.
  2140. *
  2141. * @deprecated Use formatSeconds() instead.
  2142. * @access public
  2143. * @uses PHPVideoToolkit::formatSeconds()
  2144. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2145. */
  2146. public function secondsToTimecode($input_seconds=0) {
  2147. return $this->formatSeconds($input_seconds, '%hh:%mm:%ss');
  2148. }
  2149. /**
  2150. * Translates a timecode to the number of seconds.
  2151. * NOTE: this is now a depreciated, use formatTimecode() instead.
  2152. *
  2153. * @deprecated Use formatTimecode() instead.
  2154. * @access public
  2155. * @uses PHPVideoToolkit::formatTimecode()
  2156. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2157. */
  2158. public function timecodeToSeconds($input_timecode='00:00:00') {
  2159. return $this->formatTimecode($input_timecode, '%hh:%mm:%ss', '%st');
  2160. }
  2161. /**
  2162. * Translates a number of seconds to a timecode.
  2163. *
  2164. * @access public
  2165. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2166. * @param integer $return_format The format of the timecode to return. The default is
  2167. * default '%hh:%mm:%ss'
  2168. * - %hh (hours) representative of hours
  2169. * - %mm (minutes) representative of minutes
  2170. * - %ss (seconds) representative of seconds
  2171. * - %fn (frame number) representative of frames (of the current second, not total frames)
  2172. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  2173. * - %ft (frames total) representative of total frames (ie frame number)
  2174. * - %st (seconds total) representative of total seconds (rounded).
  2175. * - %sf (seconds floored) representative of total seconds (floored).
  2176. * - %sc (seconds ceiled) representative of total seconds (ceiled).
  2177. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  2178. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  2179. * @param mixed|boolean|integer $frames_per_second The number of frames per second to translate for. If left FALSE
  2180. * the class automagically gets the fps from PHPVideoToolkit::getFileInfo(), but the input has to be set
  2181. * first for this to work properly.
  2182. * @param boolean $use_smart_values Default value is TRUE, if a format is found (ie %ss - secs) but no higher format (ie %mm - mins)
  2183. * is found then if $use_smart_values is TRUE the value of of the format will be totaled.
  2184. * @return string|integer Returns the timecode, but if $frames_per_second is not set and a frame rate lookup is required
  2185. * but can't be reached then -1 will be returned.
  2186. */
  2187. public function formatSeconds($input_seconds, $return_format='%hh:%mm:%ss', $frames_per_second=FALSE, $use_smart_values=TRUE) {
  2188. $timestamp = mktime(0, 0, $input_seconds, 0, 0);
  2189. $floored = floor($input_seconds);
  2190. $hours = $input_seconds > 3600 ? floor($input_seconds / 3600) : 0;
  2191. $mins = date('i', $timestamp);
  2192. $searches = array();
  2193. $replacements = array();
  2194. // these ones are the simple replacements
  2195. // replace the hours
  2196. $using_hours = strpos($return_format, '%hh') !== FALSE;
  2197. if ($using_hours) {
  2198. array_push($searches, '%hh');
  2199. array_push($replacements, $hours);
  2200. }
  2201. // replace the minutes
  2202. $using_mins = strpos($return_format, '%mm') !== FALSE;
  2203. if ($using_mins) {
  2204. array_push($searches, '%mm');
  2205. // check if hours are being used, if not and hours are required enable smart minutes
  2206. if ($use_smart_values === TRUE && !$using_hours && $hours > 0) {
  2207. $value = ($hours * 60) + $mins;
  2208. }
  2209. else {
  2210. $value = $mins;
  2211. }
  2212. array_push($replacements, $value);
  2213. }
  2214. // replace the seconds
  2215. if (strpos($return_format, '%ss') !== FALSE) {
  2216. // check if hours are being used, if not and hours are required enable smart minutes
  2217. if ($use_smart_values === TRUE && !$using_mins && !$using_hours && $hours > 0) {
  2218. $mins = ($hours * 60) + $mins;
  2219. }
  2220. // check if mins are being used, if not and hours are required enable smart minutes
  2221. if ($use_smart_values === TRUE && !$using_mins && $mins > 0) {
  2222. $value = ($mins * 60) + date('s', $timestamp);
  2223. }
  2224. else {
  2225. $value = date('s', $timestamp);
  2226. }
  2227. array_push($searches, '%ss');
  2228. array_push($replacements, $value);
  2229. }
  2230. // replace the milliseconds
  2231. if (strpos($return_format, '%ms') !== FALSE) {
  2232. $milli = round($input_seconds - $floored, 3);
  2233. $milli = substr($milli, 2);
  2234. $milli = empty($milli) ? '0' : $milli;
  2235. array_push($searches, '%ms');
  2236. array_push($replacements, $milli);
  2237. }
  2238. // replace the total seconds (rounded)
  2239. if (strpos($return_format, '%st') !== FALSE) {
  2240. array_push($searches, '%st');
  2241. array_push($replacements, round($input_seconds));
  2242. }
  2243. // replace the total seconds (floored)
  2244. if (strpos($return_format, '%sf') !== FALSE) {
  2245. array_push($searches, '%sf');
  2246. array_push($replacements, floor($input_seconds));
  2247. }
  2248. // replace the total seconds (ceiled)
  2249. if (strpos($return_format, '%sc') !== FALSE) {
  2250. array_push($searches, '%sc');
  2251. array_push($replacements, ceil($input_seconds));
  2252. }
  2253. // replace the total seconds
  2254. if (strpos($return_format, '%mt') !== FALSE) {
  2255. array_push($searches, '%mt');
  2256. array_push($replacements, round($input_seconds, 3));
  2257. }
  2258. // these are the more complicated as they depend on $frames_per_second / frames per second of the current input
  2259. $has_frames = strpos($return_format, '%fn') !== FALSE;
  2260. $has_total_frames = strpos($return_format, '%ft') !== FALSE;
  2261. if ($has_frames || $has_total_frames) {
  2262. // if the fps is FALSE then we must automagically detect it from the input file
  2263. if ($frames_per_second === FALSE) {
  2264. $info = $this->getFileInfo();
  2265. // check the information has been received
  2266. if ($info === FALSE || (isset($info['video']) === FALSE || isset($info['video']['frame_rate']) === FALSE)) {
  2267. // fps cannot be reached so return -1
  2268. return -1;
  2269. }
  2270. $frames_per_second = $info['video']['frame_rate'];
  2271. }
  2272. // replace the frames
  2273. $excess_frames = FALSE;
  2274. if ($has_frames) {
  2275. $excess_frames = ceil(($input_seconds - $floored) * $frames_per_second);
  2276. array_push($searches, '%fn');
  2277. array_push($replacements, $excess_frames);
  2278. }
  2279. // replace the total frames (ie frame number)
  2280. if ($has_total_frames) {
  2281. $round_frames = $floored * $frames_per_second;
  2282. if (!$excess_frames) {
  2283. $excess_frames = ceil(($input_seconds - $floored) * $frames_per_second);
  2284. }
  2285. array_push($searches, '%ft');
  2286. array_push($replacements, $round_frames + $excess_frames);
  2287. }
  2288. }
  2289. return str_replace($searches, $replacements, $return_format);
  2290. }
  2291. /**
  2292. * Translates a timecode to the number of seconds
  2293. *
  2294. * @access public
  2295. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2296. * @param integer $input_format The format of the timecode is being given in.
  2297. * default '%hh:%mm:%ss'
  2298. * - %hh (hours) representative of hours
  2299. * - %mm (minutes) representative of minutes
  2300. * - %ss (seconds) representative of seconds
  2301. * - %fn (frame number) representative of frames (of the current second, not total frames)
  2302. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  2303. * - %ft (frames total) representative of total frames (ie frame number)
  2304. * - %st (seconds total) representative of total seconds (rounded).
  2305. * - %sf (seconds floored) representative of total seconds (floored).
  2306. * - %sc (seconds ceiled) representative of total seconds (ceiled).
  2307. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  2308. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  2309. * @param integer $return_format The format of the timecode to return. The default is
  2310. * default '%ts'
  2311. * - %hh (hours) representative of hours
  2312. * - %mm (minutes) representative of minutes
  2313. * - %ss (seconds) representative of seconds
  2314. * - %fn (frame number) representative of frames (of the current second, not total frames)
  2315. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  2316. * - %ft (frames total) representative of total frames (ie frame number)
  2317. * - %st (seconds total) representative of total seconds (rounded).
  2318. * - %sf (seconds floored) representative of total seconds (floored).
  2319. * - %sc (seconds ceiled) representative of total seconds (ceiled).
  2320. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  2321. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  2322. * @param mixed|boolean|integer $frames_per_second The number of frames per second to translate for. If left FALSE
  2323. * the class automagically gets the fps from PHPVideoToolkit::getFileInfo(), but the input has to be set
  2324. * first for this to work properly.
  2325. * @param boolean $use_smart_values Default value is TRUE, if a format is found (ie %ss - secs) but no higher format (ie %mm - mins)
  2326. * is found then if $use_smart_values is TRUE the value of of the format will be totaled.
  2327. * @return float Returns the value of the timecode in seconds.
  2328. */
  2329. public function formatTimecode($input_timecode, $input_format='%hh:%mm:%ss', $return_format='%ts', $frames_per_second=FALSE, $use_smart_values=TRUE) {
  2330. // first we must get the timecode into the current seconds
  2331. $input_quoted = preg_quote($input_format);
  2332. $placeholders = array('%hh', '%mm', '%ss', '%fn', '%ms', '%ft', '%st', '%sf', '%sc', '%mt');
  2333. $seconds = 0;
  2334. $input_regex = str_replace($placeholders, '([0-9]+)', preg_quote($input_format));
  2335. preg_match('/' . $input_regex . '/', $input_timecode, $matches);
  2336. // work out the sort order for the placeholders
  2337. $sort_table = array();
  2338. foreach ($placeholders as $key => $placeholder) {
  2339. if (($pos = strpos($input_format, $placeholder)) !== FALSE) {
  2340. $sort_table[$pos] = $placeholder;
  2341. }
  2342. }
  2343. ksort($sort_table);
  2344. // check to see if frame related values are in the input
  2345. $has_frames = strpos($input_format, '%fn') !== FALSE;
  2346. $has_total_frames = strpos($input_format, '%ft') !== FALSE;
  2347. if ($has_frames || $has_total_frames) {
  2348. // if the fps is FALSE then we must automagically detect it from the input file
  2349. if ($frames_per_second === FALSE) {
  2350. $info = $this->getFileInfo();
  2351. // check the information has been received
  2352. if ($info === FALSE || (isset($info['duration']) === FALSE || isset($info['duration']['timecode']['frames']['frame_rate']) === FALSE)) {
  2353. // fps cannot be reached so return -1
  2354. return -1;
  2355. }
  2356. $frames_per_second = $info['duration']['timecode']['frames']['frame_rate'];
  2357. }
  2358. }
  2359. // increment the seconds with each placeholder value
  2360. $key = 1;
  2361. foreach ($sort_table as $placeholder) {
  2362. if (isset($matches[$key]) === FALSE) {
  2363. break;
  2364. }
  2365. $value = $matches[$key];
  2366. switch ($placeholder) {
  2367. // time related ones
  2368. case '%hh' :
  2369. $seconds += $value * 3600;
  2370. break;
  2371. case '%mm' :
  2372. $seconds += $value * 60;
  2373. break;
  2374. case '%ss' :
  2375. case '%sf' :
  2376. case '%sc' :
  2377. $seconds += $value;
  2378. break;
  2379. case '%ms' :
  2380. $seconds += floatval('0.' . $value);
  2381. break;
  2382. case '%st' :
  2383. case '%mt' :
  2384. $seconds = $value;
  2385. break 1;
  2386. break;
  2387. // frame related ones
  2388. case '%fn' :
  2389. $seconds += $value / $frames_per_second;
  2390. break;
  2391. case '%ft' :
  2392. $seconds = $value / $frames_per_second;
  2393. break 1;
  2394. break;
  2395. }
  2396. $key += 1;
  2397. }
  2398. // then we just format the seconds
  2399. return $this->formatSeconds($seconds, $return_format, $frames_per_second, $use_smart_values);
  2400. }
  2401. /**
  2402. * Checks to see if a given codec can be encoded by the current ffmpeg binary.
  2403. * @access public
  2404. * @param $codec string The shortcode for the codec to check for.
  2405. * @return boolean True if the codec can be encoded by ffmpeg, otherwise FALSE.
  2406. */
  2407. public function canCodecBeEncoded($type, $codec) {
  2408. return $this->validateCodec($codec, $type, 'encode');
  2409. }
  2410. /**
  2411. * Checks to see if a given codec can be decoded by the current ffmpeg binary.
  2412. * @access public
  2413. * @param $codec string The shortcode for the codec to check for.
  2414. * @return boolean True if the codec can be decoded by ffmpeg, otherwise FALSE.
  2415. */
  2416. public function canCodecBeDecoded($type, $codec) {
  2417. return $this->validateCodec($codec, $type, 'decode');
  2418. }
  2419. /**
  2420. * Checks to see if a given codec can be decoded/encoded by the current ffmpeg binary.
  2421. * @access public
  2422. * @param $codec string The shortcode for the codec to check for.
  2423. * @param $type string either 'video', 'audio', or 'subtitle'. The type of codec to check for.
  2424. * @param $method string 'encode' or 'decode', The method to check against the codec
  2425. * @return boolean True if the codec can be used with the given method by ffmpeg, otherwise FALSE.
  2426. */
  2427. public function validateCodec($codec, $type, $method) {
  2428. $info = $this->getFFmpegInfo();
  2429. return isset($info['codecs'][$type]) === TRUE && isset($info['codecs'][$type][$codec]) === TRUE && isset($info['codecs'][$type][$codec][$method]) === TRUE ? $info['codecs'][$type][$codec][$method] : FALSE;
  2430. }
  2431. /**
  2432. * Checks to see if a given format can be muxed by the current ffmpeg binary.
  2433. * @access public
  2434. * @param $format string The shortcode for the codec to check for.
  2435. * @return boolean True if the codec can be encoded by ffmpeg, otherwise FALSE.
  2436. */
  2437. public function canFormatBeMuxed($format) {
  2438. return $this->validateFormat($format, 'mux');
  2439. }
  2440. /**
  2441. * Checks to see if a given format can be demuxed by the current ffmpeg binary.
  2442. * @access public
  2443. * @param $codec string The shortcode for the codec to check for.
  2444. * @return boolean True if the codec can be decoded by ffmpeg, otherwise FALSE.
  2445. */
  2446. public function canFormatBeDemuxed($format) {
  2447. return $this->validateFormat($format, 'demux');
  2448. }
  2449. /**
  2450. * Checks to see if a given codec can be decoded/encoded by the current ffmpeg binary.
  2451. * @access public
  2452. * @param $format string The shortcode for the codec to check for.
  2453. * @param $method string 'mux' or 'demux', The method to check against the format
  2454. * @return boolean True if the format can be used with the given method by ffmpeg, otherwise FALSE.
  2455. */
  2456. public function validateFormat($format, $method) {
  2457. $info = $this->getFFmpegInfo();
  2458. return isset($info['formats'][$format]) === TRUE && isset($info['formats'][$format][$method]) === TRUE ? $info['formats'][$format][$method] : FALSE;
  2459. }
  2460. /**
  2461. * Returns the available formats.
  2462. * @access public
  2463. * @param mixed $method The mux method to check for, either 'muxing', 'demuxing' or 'both' (formats that can both mux and demux), otherwise FALSE will return a complete list.
  2464. * @return array An array of formats available to ffmpeg.
  2465. */
  2466. public function getAvailableFormats($method=FALSE) {
  2467. $info = $this->getFFmpegInfo();
  2468. $return_vals = array();
  2469. switch ($method) {
  2470. case FALSE :
  2471. return array_keys($info['formats']);
  2472. case 'both' :
  2473. foreach ($info['formats'] as $id => $data) {
  2474. if ($data['mux'] === TRUE && $data['demux'] === TRUE) {
  2475. array_push($return_vals, $id);
  2476. }
  2477. }
  2478. break;
  2479. case 'muxing' :
  2480. foreach ($info['formats'] as $id => $data) {
  2481. if ($data['mux'] === TRUE) {
  2482. array_push($return_vals, $id);
  2483. }
  2484. }
  2485. break;
  2486. case 'demuxing' :
  2487. foreach ($info['formats'] as $id => $data) {
  2488. if ($data['demux'] === TRUE) {
  2489. array_push($return_vals, $id);
  2490. }
  2491. }
  2492. break;
  2493. }
  2494. return $return_vals;
  2495. }
  2496. /**
  2497. * Returns the available codecs.
  2498. * @access public
  2499. * @param mixed $type The type of codec list to return, FALSE (to return all codecs), or either 'audio', 'video', or 'subtitle'.
  2500. * @return array An array of codecs available to ffmpeg.
  2501. */
  2502. public static function getAvailableCodecs($type=FALSE) {
  2503. // check to see if this is a static call
  2504. if (isset($this) === FALSE) {
  2505. $toolkit = new PHPVideoToolkit();
  2506. $info = $toolkit->getFFmpegInfo();
  2507. }
  2508. else {
  2509. $info = $this->getFFmpegInfo();
  2510. }
  2511. // are we checking for particluar method?
  2512. $return_vals = array();
  2513. if ($type === FALSE) {
  2514. $video_keys = array_keys($info['codecs']['video']);
  2515. $audio_keys = array_keys($info['codecs']['audio']);
  2516. $subtitle_keys = array_keys($info['codecs']['subtitle']);
  2517. return array_merge($video_keys, $audio_keys, $subtitle_keys);
  2518. }
  2519. return isset($info['codecs'][$type]) === TRUE ? array_keys($info['codecs'][$type]) : FALSE;
  2520. }
  2521. /**
  2522. * Returns the available pixel formats.
  2523. *
  2524. * @return
  2525. * array An array of pixel formats available to ffmpeg.
  2526. */
  2527. public function getAvailablePixelFormats() {
  2528. $info = $this->getFFmpegInfo();
  2529. if (!isset($info['pixelformats'])) {
  2530. $info = $this->getFFmpegInfo(FALSE);
  2531. if (!isset($info['pixelformats'])) {
  2532. return array();
  2533. }
  2534. }
  2535. return array_keys($info['pixelformats']);
  2536. }
  2537. /**
  2538. * Commits all the commands and executes the ffmpeg procedure. This will also attempt to validate any outputted files in order to provide
  2539. * some level of stop and check system.
  2540. *
  2541. * @access public
  2542. * @param $multi_pass_encode boolean Determines if multi (2) pass encoding should be used.
  2543. * @param $log boolean Determines if a log file of the results should be generated.
  2544. * @return mixed
  2545. * - FALSE On error encountered.
  2546. * - PHPVideoToolkit::RESULT_OK (bool TRUE) If the file has successfully been processed and moved ok to the output address
  2547. * - PHPVideoToolkit::RESULT_OK_BUT_UNWRITABLE (int -1) If the file has successfully been processed but was not able to be moved correctly to the output address
  2548. * If this is the case you will manually need to move the processed file from the temp directory. You can
  2549. * get around this by settings the third argument from PHPVideoToolkit::setOutput(), $overwrite to TRUE.
  2550. * - n (int) A positive integer is only returned when outputting a series of frame grabs from a movie. It dictates
  2551. * the total number of frames grabbed from the input video. You should also not however, that if a conflict exists
  2552. * with one of the filenames then this return value will not be returned, but PHPVideoToolkit::RESULT_OK_BUT_UNWRITABLE
  2553. * will be returned instead.
  2554. * Because of the mixed return value you should always go a strict evaluation of the returned value. ie
  2555. *
  2556. * $result = $toolkit->excecute();
  2557. * if($result === FALSE)
  2558. * {
  2559. * // error
  2560. * }
  2561. * elseif($result === PHPVideoToolkit::RESULT_OK_BUT_UNWRITABLE)
  2562. * {
  2563. * // ok but a manual move is required. The file to move can be it can be retrieved by $toolkit->getLastOutput();
  2564. * }
  2565. * elseif($result === PHPVideoToolkit::RESULT_OK)
  2566. * {
  2567. * // everything is ok.
  2568. * }
  2569. */
  2570. public function execute($multi_pass_encode=FALSE, $log=FALSE) {
  2571. // check for inut and output params
  2572. $has_placeholder = preg_match('/\%([0-9]+)index/', $this->_process_address) || (strpos($this->_process_address, '%index') === FALSE && strpos($this->_process_address, '%timecode') === FALSE);
  2573. if ($this->_input_file === NULL && !$has_placeholder) {
  2574. return $this->_raiseError('execute_input_404');
  2575. // <- exits
  2576. }
  2577. // check to see if the output address has been set
  2578. if ($this->_process_address === NULL) {
  2579. return $this->_raiseError('execute_output_not_set');
  2580. // <- exits
  2581. }
  2582. // check if temp dir is required and is writable
  2583. if (($multi_pass_encode || $log) && !is_writable($this->_tmp_directory)) {
  2584. return $this->_raiseError('execute_temp_unwritable');
  2585. // <- exits
  2586. }
  2587. if (($this->_overwrite_mode == self::OVERWRITE_PRESERVE || $this->_overwrite_mode == self::OVERWRITE_FAIL) && is_file($this->_process_address)) {
  2588. return $this->_raiseError('execute_overwrite_process');
  2589. // <- exits
  2590. }
  2591. // carry out some overwrite checks if required
  2592. $overwrite = '';
  2593. switch ($this->_overwrite_mode) {
  2594. case self::OVERWRITE_UNIQUE :
  2595. // insert a unique id into the output address (the process address already has one)
  2596. $unique = $this->unique();
  2597. $last_index = strrpos($this->_output_address, DS);
  2598. $this->_output_address = substr($this->_output_address, 0, $last_index + 1) . $unique . '-' . substr($this->_output_address, $last_index + 1);
  2599. break;
  2600. case self::OVERWRITE_EXISTING :
  2601. // add an overwrite command to ffmpeg execution call
  2602. $overwrite = '-y ';
  2603. break;
  2604. case self::OVERWRITE_PRESERVE :
  2605. // do nothing as the preservation comes later
  2606. break;
  2607. case self::OVERWRITE_FAIL :
  2608. default :
  2609. // if the file should fail
  2610. if (!$has_placeholder && is_file($this->_output_address)) {
  2611. return $this->_raiseError('execute_overwrite_fail');
  2612. // <- exits
  2613. }
  2614. break;
  2615. }
  2616. $this->_timer_start = self::microtimeFloat();
  2617. // check to see if the format has been set and if it hasn't been set and the extension is a gif
  2618. // we need to add an extra argument to set the pix format.
  2619. $format = $this->hasCommand('-f');
  2620. if ($format === FALSE) {
  2621. $extension = pathinfo($this->_input_file, PATHINFO_EXTENSION);
  2622. if ($extension === 'gif') {
  2623. $this->addCommand('-pix_fmt', 'rgb24');
  2624. }
  2625. }
  2626. elseif ($format === self::FORMAT_GIF) {
  2627. $this->addCommand('-pix_fmt', 'rgb24');
  2628. }
  2629. // check to see if an aspect ratio is set, if it is correct the width and heights to reflect that aspect ratio.
  2630. // This isn't strictly needed it is purely for informational purposes that this is done, because if the width is not
  2631. // inline with what is should be according to the aspect ratio ffmpeg will report the wrong final width and height
  2632. // when using it to lookup information about the file.
  2633. $ratio = $this->hasCommand('-aspect');
  2634. if ($ratio !== FALSE) {
  2635. $size = $this->hasCommand('-s');
  2636. if ($size === FALSE) {
  2637. $info = $this->getFileInfo();
  2638. if (isset($info['video']) === TRUE && isset($info['video']['dimensions']) === TRUE) {
  2639. $size = $info['video']['dimensions']['width'] . 'x' . $info['video']['dimensions']['height'];
  2640. }
  2641. }
  2642. if ($size !== FALSE) {
  2643. $dim = explode('x', substr($size, 1, -1));
  2644. if (($boundry = strpos($ratio, ':')) !== FALSE) {
  2645. $ratio = substr($ratio, 1, $boundry - 1) / substr($ratio, $boundry + 1, -1);
  2646. $new_width = round($dim[1] * $ratio);
  2647. // make sure new width is an even number
  2648. $ceiled = ceil($new_width);
  2649. $new_width = $ceiled % 2 !== 0 ? floor($new_width) : $ceiled;
  2650. if ($new_width != $dim[0]) {
  2651. $this->setVideoDimensions($new_width, $dim[1]);
  2652. }
  2653. }
  2654. elseif (strpos($ratio, '.') !== FALSE) {
  2655. $ratio = floatval($ratio);
  2656. $new_width = $dim[1] * $ratio;
  2657. // make sure new width is an even number
  2658. $ceiled = ceil($new_width);
  2659. $new_width = $ceiled % 2 !== 0 ? floor($new_width) : $ceiled;
  2660. if ($new_width != $dim[0]) {
  2661. $this->setVideoDimensions($new_width, $dim[1]);
  2662. }
  2663. }
  2664. }
  2665. }
  2666. // add the input file command to the mix
  2667. $this->addCommand('-i', $this->_input_file);
  2668. // if multi pass encoding is enabled add the commands and logfile
  2669. if ($multi_pass_encode) {
  2670. $multi_pass_file = $this->_tmp_directory . $this->unique() . '-multipass';
  2671. $this->addCommand('-pass', 1);
  2672. $this->addCommand('-passlogfile', $multi_pass_file);
  2673. }
  2674. // combine all the output commands
  2675. $command_string = $this->_combineCommands();
  2676. // prepare the command suitable for exec
  2677. // the input and overwrite commands have specific places to be set so they have to be added outside of the combineCommands function
  2678. $exec_string = $this->_prepareCommand($this->_ffmpeg_binary, $command_string, $overwrite . $this->_process_address);
  2679. // $exec_string = $this->_prepareCommand(PHPVIDEOTOOLKIT_FFMPEG_BINARY, '-i '.$this->_commands['-i'].' '.$command_string, $overwrite.escapeshellcmd($this->_process_address));
  2680. if ($log) {
  2681. $this->_log_file = $this->_tmp_directory . $this->unique() . '.info';
  2682. array_push($this->_unlink_files, $this->_log_file);
  2683. }
  2684. // execute the command
  2685. // $exec_string = $exec_string.' 2>&1';// &> '.$this->_log_file;
  2686. $buffer = $this->_captureExecBuffer($exec_string);
  2687. // exec($exec_string, $buffer);
  2688. if ($log) {
  2689. $this->_addToLog($buffer, 'a+');
  2690. }
  2691. // track the processed command by adding it to the class
  2692. array_unshift($this->_processed, $exec_string);
  2693. // scan buffer for any errors
  2694. $last_line = $buffer[count($buffer) - 1];
  2695. if (preg_match('/(.*)(Unsupported codec|Error while opening)(.*)/s', $last_line, $error_matches) > 0) {
  2696. $type = $error_matches[2];
  2697. switch ($error_matches[2]) {
  2698. case 'Unsupported codec' :
  2699. break;
  2700. case 'Error while opening' :
  2701. break;
  2702. }
  2703. $stream = 'could be with either the audio or video codec';
  2704. if (preg_match('/#0.(0|1)/', $last_line, $stream_matches) > 0) {
  2705. $stream = $stream_matches[1] === '0' ? 'is with the video codec' : 'is with the audio codec';
  2706. }
  2707. // add the error to the log file
  2708. if ($log) {
  2709. $this->_logResult('execute_ffmpeg_return_error', array('input' => $this->_input_file, 'type' => $type, 'message' => $error_matches[0], 'stream' => $stream));
  2710. }
  2711. return $this->_raiseError('execute_ffmpeg_return_error', array('input' => $this->_input_file, 'type' => $type, 'message' => $error_matches[0], 'stream' => $stream));
  2712. }
  2713. // create the multiple pass encode
  2714. if ($multi_pass_encode) {
  2715. $pass2_exc_string = str_replace('-pass ' . escapeshellarg(1), '-pass ' . escapeshellarg(2), $exec_string);
  2716. $buffer = $this->_captureExecBuffer($pass2_exc_string);
  2717. // exec($pass2_exc_string, $buffer);
  2718. if ($log) {
  2719. $this->_addToLog($buffer, 'a+');
  2720. }
  2721. $this->_processed[0] = array($this->_processed[0], $pass2_exc_string);
  2722. // tidy up the multipass log file
  2723. array_push($this->_unlink_files, $multi_pass_file . '-0.log');
  2724. // scan buffer for any errors
  2725. $last_line = $buffer[count($buffer) - 1];
  2726. if (preg_match('/(.*)(Unsupported codec|Error while opening)(.*)/s', $last_line, $error_matches) > 0) {
  2727. $type = $error_matches[2];
  2728. switch ($error_matches[2]) {
  2729. case 'Unsupported codec' :
  2730. break;
  2731. case 'Error while opening' :
  2732. break;
  2733. }
  2734. $stream = 'could be with either the audio or video codec';
  2735. if (preg_match('/#0.(0|1)/', $last_line, $stream_matches) > 0) {
  2736. $stream = $stream_matches[1] === '0' ? 'is with the video codec' : 'is with the audio codec';
  2737. }
  2738. // add the error to the log file
  2739. if ($log) {
  2740. $this->_logResult('execute_ffmpeg_return_error_multipass', array('input' => $this->_input_file, 'type' => $type, 'message' => $error_matches[0], 'stream' => $stream));
  2741. }
  2742. return $this->_raiseError('execute_ffmpeg_return_error_multipass', array('input' => $this->_input_file, 'type' => $type, 'message' => $error_matches[0], 'stream' => $stream));
  2743. }
  2744. }
  2745. // keep track of the time taken
  2746. $execution_time = self::microtimeFloat() - $this->_timer_start;
  2747. array_unshift($this->_timers, $execution_time);
  2748. // add the exec string to the log file
  2749. if ($log) {
  2750. $lines = $this->_processed[0];
  2751. if (!is_array($lines)) {
  2752. $lines = array($lines);
  2753. }
  2754. // array_unshift($lines, $exec_string);
  2755. array_unshift($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_command'), $this->_getMessage('ffmpeg_log_separator'));
  2756. // if($multi_pass_encode)
  2757. // {
  2758. // array_unshift($lines, $pass2_exc_string);
  2759. // }
  2760. array_unshift($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_gunk'), $this->_getMessage('ffmpeg_log_separator'));
  2761. $this->_addToLog($lines, 'a+');
  2762. }
  2763. // must validate a series of outputed items
  2764. // detect if the output address is a sequence output
  2765. if (preg_match('/\%([0-9]+)d/', $this->_process_address, $d_matches) || strpos($this->_process_address, '%d') !== FALSE) {
  2766. // get the path details
  2767. $process_info = pathinfo($this->_process_address);
  2768. $output_info = pathinfo($this->_output_address);
  2769. $pad_amount = intval($d_matches[1]);
  2770. // print_r(array($process_info, $output_info));
  2771. // get the %index padd amounts
  2772. $has_preg_index = preg_match('/\%([0-9]+)index/', $output_info['basename'], $index_matches);
  2773. $output_index_pad_amount = isset($index_matches[1]) === TRUE ? intval($index_matches[1], 1) : 0;
  2774. // var_dump($index_matches);
  2775. // init the iteration values
  2776. $num = 1;
  2777. $files = array();
  2778. $produced = array();
  2779. $error = FALSE;
  2780. $name_conflict = FALSE;
  2781. $file_exists = FALSE;
  2782. // get the first files name
  2783. $filename = $process_info['dirname'] . DS . str_replace($d_matches[0], str_pad($num, $pad_amount, '0', STR_PAD_LEFT), $process_info['basename']);
  2784. $use_timecode = strpos($output_info['basename'], '%timecode') !== FALSE;
  2785. $use_index = $has_preg_index || strpos($output_info['basename'], '%index') !== FALSE;
  2786. // start the timecode pattern replacement values
  2787. if ($use_timecode) {
  2788. $secs_start = $this->formatTimecode($this->_image_output_timecode_start, '%hh:%mm:%ss.%ms', '%mt', $this->_image_output_timecode_fps);
  2789. $fps_inc = 1 / $this->_image_output_timecode_fps;
  2790. $fps_current_sec = 0;
  2791. $fps_current_frame = 0;
  2792. }
  2793. // loop checking for file existence
  2794. while (@is_file($filename)) {
  2795. // check for empty file
  2796. $size = filesize($filename);
  2797. if ($size == 0) {
  2798. $error = TRUE;
  2799. }
  2800. array_push($produced, $filename);
  2801. // create the substitution arrays
  2802. $searches = array();
  2803. $replacements = array();
  2804. if ($use_index) {
  2805. array_push($searches, isset($index_matches[0]) === TRUE ? $index_matches[0] : '%index');
  2806. array_push($replacements, str_pad($num, $output_index_pad_amount, '0', STR_PAD_LEFT));
  2807. }
  2808. // check if timecode is in the output name, no need to use it if not
  2809. if ($use_timecode) {
  2810. $fps_current_sec += $fps_inc;
  2811. $fps_current_frame += 1;
  2812. if ($fps_current_sec >= 1) {
  2813. $fps_current_sec = $fps_inc;
  2814. $secs_start += 1;
  2815. $fps_current_frame = 1;
  2816. }
  2817. $timecode = $this->formatSeconds($secs_start, $this->image_output_timecode_format, $this->_image_output_timecode_fps);
  2818. $timecode = str_replace(array(':', '.'), $this->timecode_seperator_output, $timecode);
  2819. // add to the substitution array
  2820. array_push($searches, '%timecode');
  2821. array_push($replacements, $timecode);
  2822. }
  2823. // check if the file exists already and if it does check that it can be overriden
  2824. $old_filename = $filename;
  2825. // print_r(array($searches, $replacements, $output_info['basename']));
  2826. $new_file = str_replace($searches, $replacements, $output_info['basename']);
  2827. $new_filename = $output_info['dirname'] . DS . $new_file;
  2828. // var_dump($filename, $new_filename);
  2829. if (!is_file($new_filename) || $this->_overwrite_mode == self::OVERWRITE_EXISTING) {
  2830. if (is_file($new_filename)) {
  2831. unlink($new_filename);
  2832. }
  2833. rename($filename, $new_filename);
  2834. $filename = $new_filename;
  2835. }
  2836. // the file exists and is not allowed to be overriden so just rename in the temp directory using the timecode
  2837. elseif ($this->_overwrite_mode == self::OVERWRITE_PRESERVE) {
  2838. $new_filename = $process_info['dirname'] . DS . 'tbm-' . $this->unique() . '-' . $new_file;
  2839. rename($filename, $new_filename);
  2840. $filename = $new_filename;
  2841. // add the error to the log file
  2842. if ($log) {
  2843. $this->_logResult('execute_image_file_exists', array('file' => $new_filename));
  2844. }
  2845. // flag the conflict
  2846. $file_exists = TRUE;
  2847. }
  2848. // the file exists so the process must fail
  2849. else {
  2850. // add the error to the log file
  2851. if ($log) {
  2852. $this->_logResult('execute_overwrite_fail');
  2853. }
  2854. // tidy up the produced files
  2855. array_merge($this->_unlink_files, $produced);
  2856. return $this->_raiseError('execute_overwrite_fail');
  2857. }
  2858. // process the name change if the %d is to be replaced with the timecode
  2859. $num += 1;
  2860. $files[$filename] = $size > 0 ? basename($filename) : FALSE;
  2861. // print_r("\r\n\r\n".is_file($old_filename)." - ".$old_filename.' => '.$new_filename);
  2862. // print_r($files);
  2863. // get the next incremented filename to check for existance
  2864. $filename = $process_info['dirname'] . DS . str_replace($d_matches[0], str_pad($num, $pad_amount, '0', STR_PAD_LEFT), $process_info['basename']);
  2865. }
  2866. // de-increment the last num as it wasn't found
  2867. $num -= 1;
  2868. // if the file was detected but were empty then display a different error
  2869. if ($error === TRUE) {
  2870. // add the error to the log file
  2871. if ($log) {
  2872. $this->_logResult('execute_partial_error', array('input' => $this->_input_file));
  2873. }
  2874. return $this->_raiseError('execute_partial_error', array('input' => $this->_input_file));
  2875. // <- exits
  2876. }
  2877. // post process any files
  2878. // print_r($files);
  2879. $post_process_result = $this->_postProcess($log, $files);
  2880. // print_r($files);
  2881. if (is_array($post_process_result)) {
  2882. // post process has occurred and everything is fine
  2883. $num = count($files);
  2884. }
  2885. elseif ($post_process_result !== FALSE) {
  2886. // the file has encountered an error in the post processing of the files
  2887. return $post_process_result;
  2888. }
  2889. // var_dump("\r\n\r\n", $files, __LINE__, __FILE__, "\r\n\r\n"); exit;
  2890. $this->_process_file_count = $num;
  2891. // no files were generated in this sequence
  2892. if ($num == 0) {
  2893. // add the error to the log file
  2894. if ($log) {
  2895. $this->_logResult('execute_image_error', array('input' => $this->_input_file));
  2896. }
  2897. return $this->_raiseError('execute_image_error', array('input' => $this->_input_file));
  2898. // <- exits
  2899. }
  2900. // add the files the the class a record of what has been generated
  2901. array_unshift($this->_files, $files);
  2902. if ($log) {
  2903. array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), implode("\n", $files));
  2904. $this->_addToLog($lines, 'a+');
  2905. }
  2906. return $file_exists ? self::RESULT_OK_BUT_UNWRITABLE : self::RESULT_OK;
  2907. }
  2908. // must validate one file
  2909. else {
  2910. // check that it is a file
  2911. if (!is_file($this->_process_address)) {
  2912. // add the error to the log file
  2913. if ($log) {
  2914. $this->_logResult('execute_output_404', array('input' => $this->_input_file));
  2915. }
  2916. return $this->_raiseError('execute_output_404', array('input' => $this->_input_file));
  2917. // <- exits
  2918. }
  2919. // the file does exist but is it empty?
  2920. if (filesize($this->_process_address) == 0) {
  2921. // add the error to the log file
  2922. if ($log) {
  2923. $this->_logResult('execute_output_empty', array('input' => $this->_input_file));
  2924. }
  2925. return $this->_raiseError('execute_output_empty', array('input' => $this->_input_file));
  2926. // <- exits
  2927. }
  2928. // the file is ok so move to output address
  2929. if (!is_file($this->_output_address) || $this->_overwrite_mode == self::OVERWRITE_EXISTING) {
  2930. // post process any files
  2931. $post_process_result = $this->_postProcess($log, array($this->_process_address));
  2932. if (is_array($post_process_result) || $post_process_result === TRUE) {
  2933. // post process has occurred and everything is fine
  2934. }
  2935. elseif ($post_process_result !== FALSE) {
  2936. return $post_process_result;
  2937. }
  2938. // if the result is FALSE then no post process has taken place
  2939. if (is_file($this->_output_address)) {
  2940. unlink($this->_output_address);
  2941. }
  2942. // rename the file to the final destination and check it went ok
  2943. if (rename($this->_process_address, $this->_output_address)) {
  2944. if ($log) {
  2945. array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), $this->_output_address);
  2946. $this->_addToLog($lines, 'a+');
  2947. }
  2948. // the file has been renamed ok
  2949. // add the error to the log file
  2950. if ($log) {
  2951. $this->_logResult('execute_result_ok', array('output' => $this->_output_address));
  2952. }
  2953. $this->_process_file_count = 1;
  2954. // add the file the the class a record of what has been generated
  2955. array_unshift($this->_files, array($this->_output_address));
  2956. return self::RESULT_OK;
  2957. }
  2958. // renaming failed so return ok but erro
  2959. else {
  2960. // add the error to the log file
  2961. if ($log) {
  2962. $this->_logResult('execute_result_ok_but_unwritable', array('process' => $this->_process_address, 'output' => $this->_output_address));
  2963. }
  2964. // add the file the the class a record of what has been generated
  2965. array_unshift($this->_files, array($this->_process_address));
  2966. array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), $this->_process_address);
  2967. $this->_addToLog($lines, 'a+');
  2968. return self::RESULT_OK_BUT_UNWRITABLE;
  2969. }
  2970. }
  2971. // if it is not we signal that it has been created but has not been moved.
  2972. elseif ($this->_overwrite_mode == self::OVERWRITE_PRESERVE) {
  2973. // add the error to the log file
  2974. if ($log) {
  2975. $this->_logResult('execute_result_ok_but_unwritable', array('process' => $this->_process_address, 'output' => $this->_output_address));
  2976. }
  2977. // add the file the the class a record of what has been generated
  2978. array_unshift($this->_files, array($this->_process_address));
  2979. return self::RESULT_OK_BUT_UNWRITABLE;
  2980. }
  2981. // the file exists so the process must fail
  2982. else {
  2983. // add the error to the log file
  2984. if ($log) {
  2985. $this->_logResult('execute_overwrite_fail');
  2986. }
  2987. // tidy up the produced files
  2988. array_push($this->_unlink_files, $this->_process_address);
  2989. return $this->_raiseError('execute_overwrite_fail');
  2990. }
  2991. }
  2992. return NULL;
  2993. }
  2994. /**
  2995. * This function registers a post process after the internal handling of the ffmpeg output has been cleaned and checked.
  2996. * Each function that is set will be called in the order it is set unless an index is specified. All callbacks will be
  2997. * supplied with one argument with is an array of the outputted files.
  2998. *
  2999. * NOTE1: If a post process function is being applied to an outputted video or audio then the process will be applied
  3000. * before it has been moved to it's final destination, however if the output is an image sequence the post process
  3001. * function will be called after the images have been moved to their final destinations.
  3002. *
  3003. * NOTE2: Also it is important to return a boolean 'true' if the post process has been carried out ok. If the process is not
  3004. * a TRUE value then the value will be treated/returned as an error and if applicable logged.
  3005. *
  3006. * @access public
  3007. * @param string $function The name of a function
  3008. * @param object|boolean $class The name of the callback class. If left as FALSE the callback will be treated as a standalone function.
  3009. * @param integer|boolean $index The index of the callback array to put the callback into. If left as FALSE it will be pushed to the end of the array.
  3010. */
  3011. public function registerPostProcess($function, $class=FALSE, $index=FALSE) {
  3012. // create the callback
  3013. $callback = $class === FALSE ? $function : array(&$class, $function);
  3014. // add it to the post process array
  3015. if ($index === FALSE) {
  3016. array_push($this->_post_processes, $callback);
  3017. }
  3018. else {
  3019. $this->_post_processes[$index] = $callback;
  3020. }
  3021. }
  3022. /**
  3023. * Carries out the post processing of the files.
  3024. *
  3025. * @access protected
  3026. * @param boolean $log Determines if logging of errors should be carried out.
  3027. * @param array $files The array of files that have just been processed.
  3028. * @return mixed
  3029. */
  3030. protected function _postProcess($log, $files) {
  3031. if (count($this->_post_processes)) {
  3032. // loop through the post processes
  3033. foreach ($this->_post_processes as $key => $process) {
  3034. // call the process
  3035. $return_value = call_user_func_array($process, array($files));
  3036. // if the return value is not strictly equal to TRUE the result will be treated as an error and exit the process loop
  3037. if (!is_array($return_value) && $return_value !== TRUE) {
  3038. if ($log) {
  3039. $this->_logResult($return_value);
  3040. }
  3041. return $this->_raiseError($return_value);
  3042. }
  3043. }
  3044. return $return_value;
  3045. }
  3046. return FALSE;
  3047. }
  3048. /**
  3049. * Returns the number of files outputted in this run. It will be reset when you call PHPVideoToolkit::reset();
  3050. *
  3051. * @access public
  3052. * @return integer
  3053. */
  3054. public function getFileOutputCount() {
  3055. return $this->_process_file_count;
  3056. }
  3057. /**
  3058. * Adds lines to the current log file.
  3059. *
  3060. * @access protected
  3061. * @param $message
  3062. * @param $replacements
  3063. */
  3064. protected function _logResult($message, $replacements=FALSE) {
  3065. $last = $this->getLastCommand();
  3066. if (is_array($last) === TRUE) {
  3067. $last = implode("\r", $last);
  3068. }
  3069. $this->_addToLog(array(
  3070. $this->_getMessage('ffmpeg_log_separator'),
  3071. $this->_getMessage('ffmpeg_log_ffmpeg_result'),
  3072. $this->_getMessage('ffmpeg_log_separator'),
  3073. $this->_getMessage($message, $replacements),
  3074. $this->_getMessage('ffmpeg_log_separator'),
  3075. $this->_getMessage('ffmpeg_log_ffmpeg_command'),
  3076. $this->_getMessage('ffmpeg_log_separator'),
  3077. $last
  3078. ));
  3079. }
  3080. /**
  3081. * Adds lines to the current log file.
  3082. *
  3083. * @access protected
  3084. * @param $lines array An array of lines to add to the log file.
  3085. */
  3086. protected function _addToLog($lines, $where='a') {
  3087. $handle = fopen($this->_log_file, $where);
  3088. if (is_array($lines)) {
  3089. $data = implode("\n", $lines) . "\n";
  3090. }
  3091. else {
  3092. $data = $lines . "\n";
  3093. }
  3094. fwrite($handle, $data);
  3095. fclose($handle);
  3096. }
  3097. /**
  3098. * Moves the current log file to another file.
  3099. *
  3100. * @access public
  3101. * @param $destination string The absolute path of the new filename for the log.
  3102. * @return boolean Returns the result of the log file rename.
  3103. */
  3104. public function moveLog($destination) {
  3105. $result = FALSE;
  3106. if ($this->_log_file !== NULL && is_file($this->_log_file)) {
  3107. if (is_file($destination)) {
  3108. unlink($destination);
  3109. }
  3110. $result = rename($this->_log_file, $destination);
  3111. $this->_log_file = $destination;
  3112. }
  3113. return $result;
  3114. }
  3115. /**
  3116. * Reads the current log file
  3117. *
  3118. * @access public
  3119. * @return string|boolean Returns the current log file content. Returns FALSE on failure.
  3120. */
  3121. public function readLog() {
  3122. if ($this->_log_file !== NULL && is_file($this->_log_file)) {
  3123. $handle = fopen($this->_log_file, 'r');
  3124. $contents = fread($handle, filesize($this->_log_file));
  3125. fclose($handle);
  3126. return $contents;
  3127. }
  3128. return FALSE;
  3129. }
  3130. /**
  3131. * Returns the last outputted file that was processed by ffmpeg from this class.
  3132. *
  3133. * @access public
  3134. * @return mixed array|string Will return an array if the output was a sequence, or string if it was a single file output
  3135. */
  3136. public function getLastOutput() {
  3137. return $this->_files[0];
  3138. }
  3139. /**
  3140. * Returns all the outputted files that were processed by ffmpeg from this class.
  3141. *
  3142. * @access public
  3143. * @return array
  3144. */
  3145. public function getOutput() {
  3146. return $this->_files;
  3147. }
  3148. /**
  3149. * Returns the amount of time taken of the last file to be processed by ffmpeg.
  3150. *
  3151. * @access public
  3152. * @return mixed integer Will return the time taken in seconds.
  3153. */
  3154. public function getLastProcessTime() {
  3155. return $this->_timers[0];
  3156. }
  3157. /**
  3158. * Returns the amount of time taken of all the files to be processed by ffmpeg.
  3159. *
  3160. * @access public
  3161. * @return array
  3162. */
  3163. public function getProcessTime() {
  3164. return $this->_timers;
  3165. }
  3166. /**
  3167. * Returns the last encountered error message.
  3168. *
  3169. * @access public
  3170. * @return string
  3171. */
  3172. public function getLastError() {
  3173. return $this->_errors[0];
  3174. }
  3175. /**
  3176. * Returns all the encountered errors as an array of strings
  3177. *
  3178. * @access public
  3179. * @return array
  3180. */
  3181. public function getErrors() {
  3182. return $this->_errors;
  3183. }
  3184. /**
  3185. * Returns the last command that ffmpeg was given.
  3186. * (Note; if setFormatToFLV was used in the last command then an array is returned as a command was also sent to FLVTool2)
  3187. *
  3188. * @access public
  3189. * @return mixed array|string
  3190. */
  3191. public function getLastCommand() {
  3192. return isset($this->_processed[0]) === TRUE ? $this->_processed[0] : FALSE;
  3193. }
  3194. /**
  3195. * Returns all the commands sent to ffmpeg from this class
  3196. *
  3197. * @access public
  3198. */
  3199. public function getCommands() {
  3200. return $this->_processed;
  3201. }
  3202. /**
  3203. * Returns all commands and their output
  3204. *
  3205. * @return
  3206. * array of arrays, the inner array contains keys command and output.
  3207. */
  3208. public function getCommandOutput() {
  3209. return $this->_command_output;
  3210. }
  3211. /**
  3212. * Raises an error
  3213. *
  3214. * @access protected
  3215. * @param string $message
  3216. * @param array $replacements a list of replacements in search=>replacement format
  3217. * @return boolean Only returns FALSE if $toolkit->on_error_die is set to FALSE
  3218. */
  3219. protected function _raiseError($message, $replacements=FALSE) {
  3220. $msg = 'PHPVideoToolkit error: ' . $this->_getMessage($message, $replacements);
  3221. // check what the error is supposed to do
  3222. if ($this->on_error_die === TRUE) {
  3223. exit($msg);
  3224. // <- exits
  3225. }
  3226. // add the error message to the collection
  3227. array_unshift($this->_errors, $msg);
  3228. return FALSE;
  3229. }
  3230. /**
  3231. * Gets a message.
  3232. *
  3233. * @access protected
  3234. * @param string $message
  3235. * @param array $replacements a list of replacements in search=>replacement format
  3236. * @return boolean Only returns FALSE if $toolkit->on_error_die is set to FALSE
  3237. */
  3238. protected function _getMessage($message, $replacements=FALSE) {
  3239. $message = isset($this->_messages[$message]) === TRUE ? $this->_messages[$message] : 'Unknown!!!';
  3240. if ($replacements) {
  3241. $searches = $replaces = array();
  3242. foreach ($replacements as $search => $replace) {
  3243. array_push($searches, '#' . $search);
  3244. array_push($replaces, $replace);
  3245. }
  3246. $message = str_replace($searches, $replaces, $message);
  3247. }
  3248. return $message;
  3249. }
  3250. /**
  3251. * Adds a command to be bundled into the ffmpeg command call.
  3252. * (SPECIAL NOTE; None of the arguments are checked or sanitized by this function. BE CAREFUL if manually using this. The commands and arguments are escaped
  3253. * however it is still best to check and sanitize any params given to this function)
  3254. *
  3255. * @access public
  3256. * @param string $command
  3257. * @param mixed $argument
  3258. * @return boolean
  3259. */
  3260. public function addCommand($command, $argument = FALSE, $before_input = FALSE) {
  3261. $this->_commands[$before_input][$command] = $argument === FALSE ? FALSE : escapeshellarg($argument);
  3262. return TRUE;
  3263. }
  3264. /**
  3265. * Determines if the the command exits.
  3266. *
  3267. * @access public
  3268. * @param string $command
  3269. * @return mixed boolean if failure or value if exists.
  3270. */
  3271. public function hasCommand($command, $before_input = FALSE) {
  3272. return isset($this->_commands[$before_input][$command]) ? ($this->_commands[$before_input][$command] === FALSE ? TRUE : $this->_commands[$before_input][$command]) : FALSE;
  3273. }
  3274. /**
  3275. * Combines the commands stored into a string
  3276. *
  3277. * @access protected
  3278. * @return string
  3279. */
  3280. protected function _combineCommands() {
  3281. $before_input = array();
  3282. $after_input = array();
  3283. $input = NULL;
  3284. foreach ($this->_commands as $is_before_input => $commands) {
  3285. foreach ($commands as $command => $argument) {
  3286. $command_string = trim($command . (!empty($argument) ? ' ' . $argument : ''));
  3287. if ($command === '-i') {
  3288. $input = $command_string;
  3289. }
  3290. else {
  3291. if ($is_before_input) {
  3292. array_push($before_input, $command_string);
  3293. }
  3294. else {
  3295. array_push($after_input, $command_string);
  3296. }
  3297. }
  3298. }
  3299. }
  3300. $before_input = count($before_input) ? implode(' ', $before_input) . ' ' : '';
  3301. $after_input_string = ' ';
  3302. if (count($after_input)) {
  3303. $input .= ' ';
  3304. $after_input_string = implode(' ', $after_input) . ' ';
  3305. }
  3306. return $before_input . $input . $after_input_string;
  3307. }
  3308. /**
  3309. * Prepares the command for execution
  3310. *
  3311. * @access protected
  3312. * @param string $path Path to the binary
  3313. * @param string $command Command string to execute
  3314. * @param string $args Any additional arguments
  3315. * @return string
  3316. */
  3317. protected function _prepareCommand($path, $command, $args='') {
  3318. if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' || !preg_match('/\s/', $path)) {
  3319. return $path . ' ' . $command . ' ' . $args;
  3320. }
  3321. return 'start /D "' . $path . '" /B ' . $command . ' ' . $args;
  3322. }
  3323. /**
  3324. * Generates a unique id. Primarily used in jpeg to movie production
  3325. *
  3326. * @access public
  3327. * @param string $prefix
  3328. * @return string
  3329. */
  3330. public function unique($prefix='') {
  3331. return uniqid($prefix . time() . '-');
  3332. }
  3333. public function getInputFile() {
  3334. return $this->_input_file;
  3335. }
  3336. /**
  3337. * Destructs ffmpeg and removes any temp files/dirs
  3338. */
  3339. function __destruct() {
  3340. // loop through the temp files to remove first as they have to be removed before the dir can be removed
  3341. if (!empty($this->_unlink_files)) {
  3342. foreach ($this->_unlink_files as $key => $file) {
  3343. if (is_file($file)) {
  3344. @unlink($file);
  3345. }
  3346. }
  3347. $this->_unlink_files = array();
  3348. }
  3349. // loop through the dirs to remove
  3350. if (!empty($this->_unlink_dirs)) {
  3351. foreach ($this->_unlink_dirs as $key => $dir) {
  3352. if (is_dir($dir)) {
  3353. @rmdir($dir);
  3354. }
  3355. }
  3356. $this->_unlink_dirs = array();
  3357. }
  3358. }
  3359. }