PageRenderTime 43ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/becomplete/enrollment123
PHP | 3981 lines | 2216 code | 216 blank | 1549 comment | 360 complexity | edf50c07061923642b7b7af8d90f17e3 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /* SVN FILE: $Id$ */
  3. /**
  4. * @author Oliver Lillie (aka buggedcom) <publicmail@buggedcom.co.uk>
  5. *
  6. * @license BSD
  7. * @copyright Copyright (c) 2008 Oliver Lillie <http://www.buggedcom.co.uk>
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
  10. * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
  11. * is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be
  12. * included in all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  15. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  16. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  17. * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  18. *
  19. * @package PHPVideoToolkit (was called ffmpeg)
  20. * @version 0.1.9
  21. * @changelog SEE CHANGELOG
  22. * @abstract This class can be used in conjunction with several server binary libraries to manipulate video and audio
  23. * through PHP. It is not intended to solve any particular problems, however you may find it useful. This php class
  24. * is in no way associated with the actual FFmpeg releases. Any mistakes contained in this php class are mine and mine
  25. * alone.
  26. *
  27. * Please Note: There are several prerequisites that are required before this class can be used as an aid to manipulate
  28. * video and audio. You must at the very least have FFMPEG compiled on your server. If you wish to use this class for FLV
  29. * manipulation you must compile FFMPEG with LAME and Ruby's FLVTOOL2. I cannot answer questions regarding the install of
  30. * the server binaries needed by this class. I had too learn the hard way and it isn't easy, however it is a good learning
  31. * experience. For those of you who do need help read the install.txt file supplied along side this class. It wasn't written
  32. * by me however I found it useful when installing ffmpeg for the first time. The original source for the install.txt file
  33. * is located http://www.luar.com.hk/blog/?p=669 and the author is Lunar.
  34. *
  35. * @see install.txt
  36. *
  37. * @uses ffmpeg http://ffmpeg.sourceforge.net/
  38. * @uses lame http://lame.sourceforge.net/
  39. * @uses flvtool2 http://www.inlet-media.de/flvtool2 (and ruby http://www.ruby-lang.org/en/)
  40. *
  41. * @config examples/example-config.php Please edit this files in order for the examples to work.
  42. * @example examples/example01.php Converts video to Flash Video (ie FLV).
  43. * @example examples/example02.php Screen grabs video frames.
  44. * @example examples/example03.php Compile a movie from multiple jpegs
  45. * @example examples/example04.php Watermark a video.
  46. * @example examples/example05.php Access media metadata without using the ffmpeg-php library.
  47. * @example examples/example06.php Extract audio from video.
  48. * @example examples/example07.php Join multiple videos together.
  49. * @example examples/example08.php Easy video conversion to common formats using the adapters.
  50. * @example examples/example09.php Shows you how to access the information about your ffmpeg installation.
  51. * @example examples/example10.php Shows you how to extract a specific frame from a movie.
  52. * @example examples/example11.php Shows you how to use the ffmpeg-php adapters to provide a pure php emulation of ffmpeg-php.
  53. * @example examples/example12.php Shows you how to manipulate/format timecode strings.
  54. * @example examples/example13.php This demonstrates how to simply create a FLV stream script.
  55. */
  56. if(!defined('DS'))
  57. {
  58. define('DS', DIRECTORY_SEPARATOR);
  59. }
  60. /**
  61. * Set the flvtool2 binary path
  62. */
  63. if(!defined('PHPVIDEOTOOLKIT_FLVTOOLS_BINARY'))
  64. {
  65. define('PHPVIDEOTOOLKIT_FLVTOOLS_BINARY', '/usr/bin/flvtool2');
  66. }
  67. /**
  68. * Set the watermark vhook path
  69. */
  70. if(!defined('PHPVIDEOTOOLKIT_FFMPEG_WATERMARK_VHOOK'))
  71. {
  72. define('PHPVIDEOTOOLKIT_FFMPEG_WATERMARK_VHOOK', '/usr/local/lib/vhook/watermark.so');
  73. }
  74. /**
  75. * Set the memcoder path
  76. */
  77. if(!defined('PHPVIDEOTOOLKIT_MENCODER_BINARY'))
  78. {
  79. define('PHPVIDEOTOOLKIT_MENCODER_BINARY', '/usr/local/bin/mencoder');
  80. }
  81. class PHPVideoToolkit
  82. {
  83. public $version = '0.1.9';
  84. /**
  85. * Error strings
  86. */
  87. protected $_messages = array(
  88. 'generic_temp_404' => 'The temporary directory does not exist.',
  89. 'generic_temp_writable' => 'The temporary directory is not write-able by the web server.',
  90. 'inputFileHasVideo_no_input' => 'Input file does not exist so no information can be retrieved.',
  91. 'inputFileHasAudio_no_input' => 'Input file does not exist so no information can be retrieved.',
  92. 'getFileInfo_no_input' => 'Input file does not exist so no information can be retrieved.',
  93. 'streamFLV_no_input' => 'Input file has not been set so the FLV cannot be streamed.',
  94. 'streamFLV_passed_eof' => 'You have tried to stream to a point in the file that does not exit.',
  95. 'setInputFile_file_existence' => 'Input file "#file" does not exist',
  96. 'extractAudio_valid_format' => 'Value "#format" set from $toolkit->extractAudio, is not a valid audio format. Valid values ffmpeg self::FORMAT_AAC, PHPVideoToolkit::FORMAT_AIFF, PHPVideoToolkit::FORMAT_MP2, PHPVideoToolkit::FORMAT_MP3, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG4, PHPVideoToolkit::FORMAT_M4A or PHPVideoToolkit::FORMAT_WAV. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-f" and $argument to your required value.',
  97. 'extractFrame_video_frame_rate_404' => 'You have attempted to extract a thumbnail from a video while automagically guessing the framerate of the video, but the framerate could not be accessed. You can remove this error by manually setting the frame rate of the video.',
  98. 'extractFrame_video_info_404' => 'You have attempted to extract a thumbnail from a video and check to see if the thumbnail exists, however it was not possible to access the video information. Please check your temporary directory permissions for read/write access by the webserver.',
  99. 'extractFrame_video_frame_count' => 'You have attempted to extract a thumbnail from a video but the thumbnail you are trying to extract does not exist in the video.',
  100. 'extractFrames_video_begin_frame_count' => 'You have attempted to extract thumbnails from a video but the thumbnail you are trying to start the extraction from does not exist in the video.',
  101. 'extractFrames_video_end_frame_count' => 'You have attempted to extract thumbnails from a video but the thumbnail you are trying to end the extraction at does not exist in the video.',
  102. 'setFormat_valid_format' => 'Value "#format" set from $toolkit->setFormat, is not a valid format. Valid values are PHPVideoToolkit::FORMAT_3GP2, PHPVideoToolkit::FORMAT_3GP, PHPVideoToolkit::FORMAT_AAC, PHPVideoToolkit::FORMAT_AIFF, PHPVideoToolkit::FORMAT_AMR, PHPVideoToolkit::FORMAT_ASF, PHPVideoToolkit::FORMAT_AVI, PHPVideoToolkit::FORMAT_FLV, PHPVideoToolkit::FORMAT_GIF, PHPVideoToolkit::FORMAT_MJ2, PHPVideoToolkit::FORMAT_MP2, PHPVideoToolkit::FORMAT_MP3, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG4, PHPVideoToolkit::FORMAT_M4A, PHPVideoToolkit::FORMAT_MPEG, PHPVideoToolkit::FORMAT_MPEG1, PHPVideoToolkit::FORMAT_MPEG2, PHPVideoToolkit::FORMAT_MPEGVIDEO, PHPVideoToolkit::FORMAT_PSP, PHPVideoToolkit::FORMAT_RM, PHPVideoToolkit::FORMAT_SWF, PHPVideoToolkit::FORMAT_VOB, PHPVideoToolkit::FORMAT_WAV, PHPVideoToolkit::FORMAT_JPG. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-f" and $argument to your required value.',
  103. 'setAudioChannels_valid_channels' => 'Value "#channels" set from $toolkit->setAudioChannels, is not a valid integer. Valid values are 1, or 2. If you wish to specifically try to set another channels value you should use the advanced function $toolkit->addCommand. Set $command to "-ac" and $argument to your required value.',
  104. 'setAudioSampleFrequency_valid_frequency' => 'Value "#frequency" set from $toolkit->setAudioSampleFrequency, is not a valid integer. Valid values are 11025, 22050, 44100. If you wish to specifically try to set another frequency you should use the advanced function $toolkit->addCommand. Set $command to "-ar" and $argument to your required value.',
  105. 'setAudioFormat_valid_format' => 'Value "#format" set from $toolkit->setAudioCodec, is not a valid format. Valid values are PHPVideoToolkit::FORMAT_AAC, PHPVideoToolkit::FORMAT_AIFF, PHPVideoToolkit::FORMAT_AMR, PHPVideoToolkit::FORMAT_ASF, PHPVideoToolkit::FORMAT_MP2, PHPVideoToolkit::FORMAT_MP3, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG2, PHPVideoToolkit::FORMAT_RM, PHPVideoToolkit::FORMAT_WAV. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-acodec" and $argument to your required value.',
  106. 'setAudioFormat_cannnot_encode' => 'Value "#codec" set from $toolkit->setAudioCodec, can not be used to encode the output as the version of FFmpeg that you are using does not have the capability to encode audio with this codec.',
  107. 'setVideoFormat_valid_format' => 'Value "#format" set from $toolkit->setVideoCodec, is not a valid format. Valid values are PHPVideoToolkit::FORMAT_3GP2, PHPVideoToolkit::FORMAT_3GP, PHPVideoToolkit::FORMAT_AVI, PHPVideoToolkit::FORMAT_FLV, PHPVideoToolkit::FORMAT_GIF, PHPVideoToolkit::FORMAT_MJ2, PHPVideoToolkit::FORMAT_MP4, PHPVideoToolkit::FORMAT_MPEG4, PHPVideoToolkit::FORMAT_M4A, PHPVideoToolkit::FORMAT_MPEG, PHPVideoToolkit::FORMAT_MPEG1, PHPVideoToolkit::FORMAT_MPEG2, PHPVideoToolkit::FORMAT_MPEGVIDEO. If you wish to specifically try to set another format you should use the advanced function $toolkit->addCommand. Set $command to "-vcodec" and $argument to your required value.',
  108. 'setVideoFormat_cannnot_encode' => 'Value "#codec" set from $toolkit->setVideoCodec, can not be used to encode the output as the version of FFmpeg that you are using does not have the capability to encode video with this codec.',
  109. 'setAudioBitRate_valid_bitrate' => 'Value "#bitrate" set from $toolkit->setAudioBitRate, is not a valid integer. Valid values are 16, 32, 64, 128. If you wish to specifically try to set another bitrate you should use the advanced function $toolkit->addCommand. Set $command to "-ab" and $argument to your required value.',
  110. 'prepareImagesForConversionToVideo_one_img' => 'When compiling a movie from a series of images, you must include at least one image.',
  111. 'prepareImagesForConversionToVideo_img_404' => '"#img" does not exist.',
  112. 'prepareImagesForConversionToVideo_img_copy' => '"#img" can not be copied to "#tmpfile"',
  113. 'prepareImagesForConversionToVideo_img_type' => 'The images can not be prepared for conversion to video. Please make sure all images are of the same type, ie gif, png, jpeg and then try again.',
  114. 'setVideoOutputDimensions_valid_format' => 'Value "#format" set from $toolkit->setVideoOutputDimensions, is not a valid preset dimension. Valid values are PHPVideoToolkit::SIZE_SQCIF, PHPVideoToolkit::SIZE_SAS, PHPVideoToolkit::SIZE_QCIF, PHPVideoToolkit::SIZE_CIF, PHPVideoToolkit::SIZE_4CIF, PHPVideoToolkit::SIZE_QQVGA, PHPVideoToolkit::SIZE_QVGA, PHPVideoToolkit::SIZE_VGA, PHPVideoToolkit::SIZE_SVGA, PHPVideoToolkit::SIZE_XGA, PHPVideoToolkit::SIZE_UXGA, PHPVideoToolkit::SIZE_QXGA, PHPVideoToolkit::SIZE_SXGA, PHPVideoToolkit::SIZE_QSXGA, PHPVideoToolkit::SIZE_HSXGA, PHPVideoToolkit::SIZE_WVGA, PHPVideoToolkit::SIZE_WXGA, PHPVideoToolkit::SIZE_WSXGA, PHPVideoToolkit::SIZE_WUXGA, PHPVideoToolkit::SIZE_WOXGA, PHPVideoToolkit::SIZE_WQSXGA, PHPVideoToolkit::SIZE_WQUXGA, PHPVideoToolkit::SIZE_WHSXGA, PHPVideoToolkit::SIZE_WHUXGA, PHPVideoToolkit::SIZE_CGA, PHPVideoToolkit::SIZE_EGA, PHPVideoToolkit::SIZE_HD480, PHPVideoToolkit::SIZE_HD720, PHPVideoToolkit::SIZE_HD1080. You can also manually set the width and height.',
  115. 'setVideoOutputDimensions_sas_dim' => 'It was not possible to determine the input video dimensions so it was not possible to continue. If you wish to override this error please change the call to setVideoOutputDimensions and add a true argument to the arguments list... setVideoOutputDimensions(PHPVideoToolkit::SIZE_SAS, true);',
  116. 'setVideoOutputDimensions_valid_integer' => 'You tried to set the video output dimensions to an odd number. FFmpeg requires that the video output dimensions are of event value and divisible by 2. ie 2, 4, 6,... etc',
  117. 'setVideoAspectRatio_valid_ratio' => 'Value "#ratio" set from $toolkit->setVideoOutputDimensions, is not a valid preset dimension. Valid values are PHPVideoToolkit::RATIO_STANDARD, PHPVideoToolkit::RATIO_WIDE, PHPVideoToolkit::RATIO_CINEMATIC. If you wish to specifically try to set another video aspect ratio you should use the advanced function $toolkit->addCommand. Set $command to "-aspect" and $argument to your required value.',
  118. 'addWatermark_img_404' => 'Watermark file "#watermark" does not exist.',
  119. 'addWatermark_vhook_disabled' => 'Vhooking is not enabled in your FFmpeg binary. In order to allow video watermarking you must have FFmpeg compiled with --enable-vhook set. You can however watermark any extracted images using GD. To enable frame watermarking, call $toolkit->addGDWatermark($file) before you execute the extraction.',
  120. 'addVideo_file_404' => 'File "#file" does not exist.',
  121. 'setOutput_output_dir_404' => 'Output directory "#dir" does not exist!',
  122. 'setOutput_output_dir_writable' => 'Output directory "#dir" is not writable!',
  123. 'setOutput_%_missing' => 'The output of this command will be images yet you have not included the "%index" or "%timecode" in the $output_name.',
  124. 'setOutput_%d_depreciated' => 'The use of %d in the output file name is now depreciated. Please use %index. Number padding is still supported. You may also use %timecode instead to add a timecode to the filename.',
  125. 'execute_input_404' => 'Execute error. Input file missing.',
  126. 'execute_output_not_set' => 'Execute error. Output not set.',
  127. 'execute_temp_unwritable' => 'Execute error. The tmp directory supplied is not writable.',
  128. 'execute_overwrite_process' => 'Execute error. A file exists in the temp directory and is of the same name as this process file. It will conflict with this conversion. Conversion stopped.',
  129. 'execute_overwrite_fail' => 'Execute error. Output file exists. Process halted. If you wish to automatically overwrite files set the third argument in "PHPVideoToolkit::setOutput();" to "PHPVideoToolkit::OVERWRITE_EXISTING".',
  130. 'execute_ffmpeg_return_error' => 'Execute error. It was not possible to encode "#input" as FFmpeg returned an error. The error #stream of the input file. FFmpeg reports the error to be "#message".',
  131. 'execute_ffmpeg_return_error_multipass' => 'Execute error. It was not possible to encode "#input" as FFmpeg returned an error. Note, however the error was encountered on the second pass of the encoding process and the first pass appear to go fine. The error #stream of the input file. FFmpeg reports the error to be "#message".',
  132. 'execute_partial_error' => 'Execute error. Output for file "#input" encountered a partial error. Files were generated, however one or more of them were empty.',
  133. 'execute_image_error' => 'Execute error. Output for file "#input" was not found. No images were generated.',
  134. 'execute_output_404' => 'Execute error. Output for file "#input" was not found. Please check server write permissions and/or available codecs compiled with FFmpeg. You can check the encode decode availability by inspecting the output array from PHPVideoToolkit::getFFmpegInfo().',
  135. 'execute_output_empty' => 'Execute error. Output for file "#input" was found, but the file contained no data. Please check the available codecs compiled with FFmpeg can support this type of conversion. You can check the encode decode availability by inspecting the output array from PHPVideoToolkit::getFFmpegInfo().',
  136. 'execute_image_file_exists' => 'Execute error. There is a file name conflict. The file "#file" already exists in the filesystem. If you wish to automatically overwrite files set the third argument in "PHPVideoToolkit::setOutput();" to "PHPVideoToolkit::OVERWRITE_EXISTING".',
  137. 'execute_result_ok_but_unwritable' => 'Process Partially Completed. The process successfully completed however it was not possible to output to "#output". The output was left in the temp directory "#process" for a manual file movement.',
  138. 'execute_result_ok' => 'Process Completed. The process successfully completed. Output was generated to "#output".',
  139. 'ffmpeg_log_ffmpeg_output' => 'OUTPUT',
  140. 'ffmpeg_log_ffmpeg_result' => 'RESULT',
  141. 'ffmpeg_log_ffmpeg_command' => 'COMMAND',
  142. 'ffmpeg_log_ffmpeg_join_gunk' => 'FFMPEG JOIN OUTPUT',
  143. 'ffmpeg_log_ffmpeg_gunk' => 'FFMPEG OUTPUT',
  144. 'ffmpeg_log_separator' => '-------------------------------'
  145. );
  146. /**
  147. * Process Results from PHPVideoToolkit::execute
  148. */
  149. // any return value with this means everything is ok
  150. const RESULT_OK = true;
  151. // any return value with this means the file has been processed/converted ok however it was
  152. // not able to be written to the output address. If this occurs you will need to move the
  153. // processed file manually from the temp location
  154. const RESULT_OK_BUT_UNWRITABLE = -1;
  155. /**
  156. * Codec support constants
  157. */
  158. const ENCODE = 'encode';
  159. const DECODE = 'decode';
  160. /**
  161. * Overwrite constants used in setOutput
  162. */
  163. const OVERWRITE_FAIL = 'fail';
  164. const OVERWRITE_PRESERVE = 'preserve';
  165. const OVERWRITE_EXISTING = 'existing';
  166. const OVERWRITE_UNIQUE = 'unique';
  167. /**
  168. * Formats supported
  169. * 3g2 3gp2 format
  170. * 3gp 3gp format
  171. * aac ADTS AAC
  172. * aiff Audio IFF
  173. * amr 3gpp amr file format
  174. * asf asf format
  175. * avi avi format
  176. * flv flv format
  177. * gif GIF Animation
  178. * mov mov format
  179. * mov,mp4,m4a,3gp,3g2,mj2 QuickTime/MPEG4/Motion JPEG 2000 format
  180. * mp2 MPEG audio layer 2
  181. * mp3 MPEG audio layer 3
  182. * mp4 mp4 format
  183. * mpeg MPEG1 System format
  184. * mpeg1video MPEG video
  185. * mpeg2video MPEG2 video
  186. * mpegvideo MPEG video
  187. * psp psp mp4 format
  188. * rm rm format
  189. * swf Flash format
  190. * vob MPEG2 PS format (VOB)
  191. * wav wav format
  192. * jpeg mjpeg format
  193. * yuv4mpegpipe yuv4mpegpipe format
  194. */
  195. const FORMAT_3GP2 = '3g2';
  196. const FORMAT_3GP = '3gp';
  197. const FORMAT_AAC = 'aac';
  198. const FORMAT_AIFF = 'aiff';
  199. const FORMAT_AMR = 'amr';
  200. const FORMAT_ASF = 'asf';
  201. const FORMAT_AVI = 'avi';
  202. const FORMAT_FLV = 'flv';
  203. const FORMAT_GIF = 'gif';
  204. const FORMAT_MJ2 = 'mj2';
  205. const FORMAT_MP2 = 'mp2';
  206. const FORMAT_MP3 = 'mp3';
  207. const FORMAT_MP4 = 'mp4';
  208. const FORMAT_MPEG4 = 'mpeg4';
  209. const FORMAT_M4A = 'm4a';
  210. const FORMAT_MPEG = 'mpeg';
  211. const FORMAT_MPEG1 = 'mpeg1video';
  212. const FORMAT_MPEG2 = 'mpeg2video';
  213. const FORMAT_MPEGVIDEO = 'mpegvideo';
  214. const FORMAT_PSP = 'psp';
  215. const FORMAT_RM = 'rm';
  216. const FORMAT_SWF = 'swf';
  217. const FORMAT_VOB = 'vob';
  218. const FORMAT_WAV = 'wav';
  219. const FORMAT_JPG = 'mjpeg';
  220. const FORMAT_Y4MP = 'yuv4mpegpipe';
  221. /**
  222. * Size Presets
  223. */
  224. const SIZE_SAS = 'SameAsSource';
  225. const SIZE_SQCIF = '128x96';
  226. const SIZE_QCIF = '176x144';
  227. const SIZE_CIF = '352x288';
  228. const SIZE_4CIF = '704x576';
  229. const SIZE_QQVGA = '160x120';
  230. const SIZE_QVGA = '320x240';
  231. const SIZE_VGA = '640x480';
  232. const SIZE_SVGA = '800x600';
  233. const SIZE_XGA = '1024x768';
  234. const SIZE_UXGA = '1600x1200';
  235. const SIZE_QXGA = '2048x1536';
  236. const SIZE_SXGA = '1280x1024';
  237. const SIZE_QSXGA = '2560x2048';
  238. const SIZE_HSXGA = '5120x4096';
  239. const SIZE_WVGA = '852x480';
  240. const SIZE_WXGA = '1366x768';
  241. const SIZE_WSXGA = '1600x1024';
  242. const SIZE_WUXGA = '1920x1200';
  243. const SIZE_WOXGA = '2560x1600';
  244. const SIZE_WQSXGA = '3200x2048';
  245. const SIZE_WQUXGA = '3840x2400';
  246. const SIZE_WHSXGA = '6400x4096';
  247. const SIZE_WHUXGA = '7680x4800';
  248. const SIZE_CGA = '320x200';
  249. const SIZE_EGA = '640x350';
  250. const SIZE_HD480 = '852x480';
  251. const SIZE_HD720 = '1280x720';
  252. const SIZE_HD1080 = '1920x1080';
  253. /**
  254. * Ratio Presets
  255. */
  256. const RATIO_STANDARD = '4:3';
  257. const RATIO_WIDE = '16:9';
  258. const RATIO_CINEMATIC = '1.85';
  259. /**
  260. * Audio Channel Presets
  261. */
  262. const AUDIO_STEREO = 2;
  263. const AUDIO_MONO = 1;
  264. /**
  265. * A public var that is to the information available about
  266. * the current ffmpeg compiled binary.
  267. * @var mixed
  268. * @access public
  269. */
  270. public static $ffmpeg_info = false;
  271. /**
  272. * A public var that determines if the ffmpeg binary has been found. The default value
  273. * is null unless getFFmpegInfo is called whereby depending on the results it is set to
  274. * true or false
  275. * @var mixed
  276. * @access public
  277. */
  278. public static $ffmpeg_found = null;
  279. /**
  280. * A protected var that contains the info of any file that is accessed by PHPVideoToolkit::getFileInfo();
  281. * @var array
  282. * @access protected
  283. */
  284. protected static $_file_info = array();
  285. /**
  286. * Determines what happens when an error occurs
  287. * @var boolean If true then the script will die, if not false is return by the error
  288. * @access public
  289. */
  290. public $on_error_die = false;
  291. /**
  292. * Holds the log file name
  293. * @var string
  294. * @access protected
  295. */
  296. protected $_log_file = null;
  297. /**
  298. * Determines if when outputting image frames if the outputted files should have the %d number
  299. * replaced with the frames timecode.
  300. * @var boolean If true then the files will be renamed.
  301. * @access public
  302. */
  303. public $image_output_timecode = true;
  304. /**
  305. * Holds the timecode separator for when using $image_output_timecode = true
  306. * Not all systems allow ':' in filenames.
  307. * @var string
  308. * @access public
  309. */
  310. public $timecode_seperator_output = '-';
  311. /**
  312. * Holds the starting time code when outputting image frames.
  313. * @var string The timecode hh(n):mm:ss:ff
  314. * @access protected
  315. */
  316. protected $_image_output_timecode_start = '00:00:00.00';
  317. /**
  318. * The format in which the image %timecode placeholder string is outputted.
  319. * - %hh (hours) representative of hours
  320. * - %mm (minutes) representative of minutes
  321. * - %ss (seconds) representative of seconds
  322. * - %fn (frame number) representative of frames (of the current second, not total frames)
  323. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  324. * - %ft (frames total) representative of total frames (ie frame number)
  325. * - %st (seconds total) representative of total seconds (rounded).
  326. * - %sf (seconds floored) representative of total seconds (floored).
  327. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  328. * NOTE; there are special characters that will be replace by PHPVideoToolkit::$timecode_seperator_output, these characters are
  329. * - :
  330. * - .
  331. * @var string
  332. * @access public
  333. */
  334. protected $image_output_timecode_format = '%hh-%mm-%ss-%fn';
  335. /**
  336. * Holds the fps of image extracts
  337. * @var integer
  338. * @access protected
  339. */
  340. protected $_image_output_timecode_fps = 1;
  341. /**
  342. * Holds the current execute commands that will need to be combined
  343. * @var array
  344. * @access protected
  345. */
  346. protected $_commands = array();
  347. /**
  348. * Holds the commands executed
  349. * @var array
  350. * @access protected
  351. */
  352. protected $_processed = array();
  353. /**
  354. * Holds the file references to those that have been processed
  355. * @var array
  356. * @access protected
  357. */
  358. protected $_files = array();
  359. /**
  360. * Holds the errors encountered
  361. * @access protected
  362. * @var array
  363. */
  364. protected $_errors = array();
  365. /**
  366. * Holds the input file / input file sequence
  367. * @access protected
  368. * @var string
  369. */
  370. protected $_input_file = null;
  371. /**
  372. * Holds the output file / output file sequence
  373. * @access protected
  374. * @var string
  375. */
  376. protected $_output_address = null;
  377. /**
  378. * Holds the process file / process file sequence
  379. * @access protected
  380. * @var string
  381. */
  382. protected $_process_address = null;
  383. /**
  384. * Temporary filename prefix
  385. * @access protected
  386. * @var string
  387. */
  388. protected $_tmp_file_prefix = 'tmp_';
  389. /**
  390. * Holds the temporary directory name
  391. * @access protected
  392. * @var string
  393. */
  394. protected $_tmp_directory = null;
  395. /**
  396. * Holds the directory paths that need to be removed by the ___destruct function
  397. * @access protected
  398. * @var array
  399. */
  400. protected $_unlink_dirs = array();
  401. /**
  402. * Holds the file paths that need to be deleted by the ___destruct function
  403. * @access protected
  404. * @var array
  405. */
  406. protected $_unlink_files = array();
  407. /**
  408. * Holds the timer start micro-float.
  409. * @access protected
  410. * @var integer
  411. */
  412. protected $_timer_start = 0;
  413. /**
  414. * Holds the times taken to process each file.
  415. * @access protected
  416. * @var array
  417. */
  418. protected $_timers = array();
  419. /**
  420. * Holds the times taken to process each file.
  421. * @access protected
  422. * @var constant
  423. */
  424. protected $_overwrite_mode = null;
  425. /**
  426. * Holds a integer value that flags if the image extraction is just a single frame.
  427. * @access protected
  428. * @var integer
  429. */
  430. protected $_single_frame_extraction = null;
  431. /**
  432. * Holds the watermark file that is used to watermark any outputted images via GD.
  433. * @access protected
  434. * @var string
  435. */
  436. protected $_watermark_url = null;
  437. /**
  438. * Holds the watermark options used to watermark any outputted images via GD.
  439. * @access protected
  440. * @var array
  441. */
  442. protected $_watermark_options = null;
  443. /**
  444. * Holds the number of files processed per run.
  445. * @access protected
  446. * @var integer
  447. */
  448. protected $_process_file_count = 0;
  449. /**
  450. * Holds the times taken to process each file.
  451. * @access protected
  452. * @var array
  453. */
  454. protected $_post_processes = array();
  455. /**
  456. * Holds commands should be sent added to the exec before the input file, this is by no means a definitive list
  457. * of all the ffmpeg commands, as it only utilizes the ones in use by this class. Also only commands that have
  458. * specific required places are entered in the arrays below. Anything not in these arrays will be treated as an
  459. * after-input item.
  460. * @access protected
  461. * @var array
  462. */
  463. // protected $_cmds_before_input = array();
  464. protected $_cmds_before_input = array('-inputr');
  465. // protected $_cmds_before_input = array('-r', '-f');
  466. // Stores the FFMPEG Binary Path
  467. protected $_ffmpeg_binary;
  468. /**
  469. * Constructs the class and sets the temporary directory.
  470. *
  471. * @access protected
  472. * @param string $tmp_directory A full absolute path to you temporary directory
  473. */
  474. function __construct($ffmpeg_binary = '/usr/bin/ffmpeg', $tmp_dir='/tmp/')
  475. {
  476. // print_r(array(debug_backtrace(), $tmp_dir));
  477. $this->_ffmpeg_binary = $ffmpeg_binary;
  478. $this->_tmp_directory = $tmp_dir;
  479. }
  480. public static function microtimeFloat()
  481. {
  482. list($usec, $sec) = explode(" ", microtime());
  483. return ((float) $usec + (float) $sec);
  484. }
  485. /**
  486. * Resets the class
  487. *
  488. * @access public
  489. * @param boolean $keep_input_file Determines whether or not to reset the input file currently set.
  490. */
  491. public function reset($keep_input_file=false, $keep_processes=false)
  492. {
  493. if($keep_input_file === false)
  494. {
  495. $this->_input_file = null;
  496. }
  497. if($keep_processes === false)
  498. {
  499. $this->_post_processes = array();
  500. }
  501. $this->_single_frame_extraction = null;
  502. $this->_output_address = null;
  503. $this->_process_address = null;
  504. $this->_log_file = null;
  505. $this->_commands = array();
  506. $this->_timer_start = 0;
  507. $this->_process_file_count = 0;
  508. $this->__destruct();
  509. }
  510. private function _captureExecBuffer($command, $tmp_dir=false)
  511. {
  512. exec($command.' 2>&1', $buffer, $err);
  513. if($err !== 127)
  514. {
  515. if(isset($buffer[0]) === false)
  516. {
  517. $tmp_file = ($tmp_dir === false ? $this->_tmp_directory : $tmp_dir).'_temp_'.uniqid(time().'-').'.txt';
  518. exec($command.' &>'.$tmp_file, $buffer, $err);
  519. if($handle = fopen($tmp_file, 'r'))
  520. {
  521. $buffer = array();
  522. // loop through the lines of data and collect the buffer
  523. while (!feof($handle))
  524. {
  525. array_push($buffer, fgets($handle, 4096));
  526. }
  527. }
  528. @unlink($tmp_file);
  529. }
  530. }
  531. else
  532. {
  533. // throw ffmpeg not found error
  534. $buffer = array();
  535. }
  536. return $buffer;
  537. }
  538. /**
  539. * Returns information about the specified file without having to use ffmpeg-php
  540. * as it consults the ffmpeg binary directly.
  541. * NOTE: calling this statically for caching to work you must set the temp directory.
  542. *
  543. * @access public
  544. * @return mixed false on error encountered, true otherwise
  545. **/
  546. public function getFFmpegInfo($read_from_cache=true, $tmp_dir=false)
  547. {
  548. $cache_file = isset($this) === true || $tmp_dir !== false ? true : false;
  549. if($read_from_cache === true && $cache_file !== false)
  550. {
  551. $cache_file = ($tmp_dir === false ? $this->_tmp_directory : $tmp_dir).'_ffmpeg_info.php';
  552. if(is_file($cache_file) === true)
  553. {
  554. require_once $cache_file;
  555. if(isset($info) === true && $info['_cache_date'] > time()-2678400)
  556. {
  557. $info['reading_from_cache'] = true;
  558. PHPVideoToolkit::$ffmpeg_info = $info;
  559. }
  560. }
  561. }
  562. //check to see if the info has already been cached
  563. if(PHPVideoToolkit::$ffmpeg_info !== false)
  564. {
  565. return PHPVideoToolkit::$ffmpeg_info;
  566. }
  567. //check to see if this is a static call
  568. if(isset($this) === false)
  569. {
  570. $toolkit = new PHPVideoToolkit();
  571. return $toolkit->getFFmpegInfo($read_from_cache, $tmp_dir);
  572. }
  573. $format = '';
  574. $data = array('reading_from_cache'=>false);
  575. // execute the ffmpeg lookup
  576. $buffer = self::_captureExecBuffer($this->_ffmpeg_binary.' -formats', $tmp_dir);
  577. $codecs = self::_captureExecBuffer($this->_ffmpeg_binary.' -codecs', $tmp_dir);
  578. $filters = self::_captureExecBuffer($this->_ffmpeg_binary.' -bsfs', $tmp_dir);
  579. $protocols = self::_captureExecBuffer($this->_ffmpeg_binary.' -protocols', $tmp_dir);
  580. self::$ffmpeg_found = $data['ffmpeg-found'] = !(strpos($buffer[0], 'command not found') !== false || strpos($buffer[0], 'No such file or directory') !== false);
  581. $data['compiler'] = array();
  582. $data['binary'] = array();
  583. $data['ffmpeg-php-support'] = self::hasFFmpegPHPSupport();
  584. $data['raw'] = implode("\r\n", $buffer)."\r\n".implode("\r\n", $codecs)."\r\n".implode("\r\n", $filters).implode("\r\n", $protocols);
  585. if(!self::$ffmpeg_found)
  586. {
  587. self::$ffmpeg_info = $data;
  588. return $data;
  589. }
  590. $buffer = $data['raw'];
  591. // start building the info array
  592. $look_ups = array('formats'=>'File formats:', 'configuration'=>'configuration: ', 'codecs'=>'Codecs:', 'filters'=>'Bitstream filters:', 'protocols'=>'Supported file protocols:', 'abbreviations'=>'Frame size, frame rate abbreviations:', 'Note:');
  593. $total_lookups = count($look_ups);
  594. $pregs = array();
  595. $indexs = array();
  596. // search for the content
  597. foreach($look_ups as $key=>$reg)
  598. {
  599. if(strpos($buffer, $reg) !== false)
  600. {
  601. $index = array_push($pregs, $reg);
  602. $indexs[$key] = $index;
  603. }
  604. }
  605. preg_match('/'.implode('(.*)', $pregs).'(.*)/s', $buffer, $matches);
  606. $configuration = trim($matches[$indexs['configuration']]);
  607. // grab the ffmpeg configuration flags
  608. preg_match_all('/--[a-zA-Z0-9\-]+/', $configuration, $config_flags);
  609. $data['binary']['configuration'] = $config_flags[0];
  610. $data['binary']['vhook-support'] = in_array('--enable-vhook', $config_flags[0]) || !in_array('--disable-vhook', $config_flags[0]);
  611. // grab the versions
  612. $data['binary']['versions'] = array();
  613. preg_match_all('/([a-zA-Z0-9\-]+) version: ([0-9\.]+)/', $configuration, $versions);
  614. for($i=0, $a=count($versions[0]); $i<$a; $i++)
  615. {
  616. $data['binary']['versions'][strtolower(trim($versions[1][$i]))] = $versions[2][$i];
  617. }
  618. // grab the ffmpeg compile info
  619. preg_match('/built on (.*), gcc: (.*)/', $configuration, $conf);
  620. if(count($conf) > 0)
  621. {
  622. $data['compiler']['gcc'] = $conf[2];
  623. $data['compiler']['build_date'] = $conf[1];
  624. $data['compiler']['build_date_timestamp'] = strtotime($conf[1]);
  625. }
  626. // grab the file formats available to ffmpeg
  627. preg_match_all('/ (DE|D|E) (.*) {1,} (.*)/', $matches[$indexs['formats']], $formats);
  628. $data['formats'] = array();
  629. // loop and clean
  630. // Formats:
  631. // D. = Demuxing supported
  632. // .E = Muxing supported
  633. for($i=0, $a=count($formats[0]); $i<$a; $i++)
  634. {
  635. $data['formats'][strtolower(trim($formats[2][$i]))] = array(
  636. 'mux' => $formats[1][$i] == 'DE' || $formats[1][$i] == 'E',
  637. 'demux' => $formats[1][$i] == 'DE' || $formats[1][$i] == 'D',
  638. 'fullname' => $formats[3][$i]
  639. );
  640. }
  641. // grab the codecs available
  642. preg_match_all('/ ([DEVAST ]{0,6}) ([A-Za-z0-9\_]*) (.*)/', $matches[$indexs['codecs']], $codecs);
  643. $data['codecs'] = array('video'=>array(), 'audio'=>array(), 'subtitle'=>array());
  644. // Codecs:
  645. // D..... = Decoding supported
  646. // .E.... = Encoding supported
  647. // ..V... = Video codec
  648. // ..A... = Audio codec
  649. // ..S... = Subtitle codec
  650. // ...S.. = Supports draw_horiz_band
  651. // ....D. = Supports direct rendering method 1
  652. // .....T = Supports weird frame truncation
  653. for ($i=0, $a=count($codecs[0]); $i<$a; $i++)
  654. {
  655. $options = preg_split('//', $codecs[1][$i], -1, PREG_SPLIT_NO_EMPTY);
  656. if ($options) {
  657. $id = trim($codecs[2][$i]);
  658. $type = $options[2] === 'V' ? 'video' : ($options[2] === 'A' ? 'audio' : 'subtitle');
  659. switch($options[2])
  660. {
  661. // video
  662. case 'V' :
  663. $data['codecs'][$type][$id] = array(
  664. 'encode' => isset($options[1]) === true && $options[1] === 'E',
  665. 'decode' => isset($options[0]) === true && $options[0] === 'D',
  666. 'draw_horizontal_band' => isset($options[3]) === true && $options[3] === 'S',
  667. 'direct_rendering_method_1' => isset($options[4]) === true && $options[4] === 'D',
  668. 'weird_frame_truncation' => isset($options[5]) === true && $options[5] === 'T',
  669. 'fullname' => trim($codecs[3][$i])
  670. );
  671. break;
  672. // audio
  673. case 'A' :
  674. // subtitle
  675. case 'S' :
  676. $data['codecs'][$type][$id] = array(
  677. 'encode' => isset($options[1]) === true && $options[1] === 'E',
  678. 'decode' => isset($options[0]) === true && $options[0] === 'D',
  679. 'fullname' => trim($codecs[3][$i])
  680. );
  681. break;
  682. }
  683. }
  684. }
  685. // grab the bitstream filters available to ffmpeg
  686. $data['filters'] = array();
  687. if(isset($indexs['filters']) === true && isset($matches[$indexs['filters']]) === true)
  688. {
  689. $filters = trim($matches[$indexs['filters']]);
  690. if(empty($filters) === false)
  691. {
  692. $data['filters'] = explode(' ', $filters);
  693. }
  694. }
  695. // grab the file prototcols available to ffmpeg
  696. $data['protocols'] = array();
  697. if(isset($indexs['protocols']) === true && isset($matches[$indexs['protocols']]) === true)
  698. {
  699. $protocols = trim($matches[$indexs['protocols']]);
  700. if(empty($protocols) === false)
  701. {
  702. $data['protocols'] = explode(' ', str_replace(':', '', $protocols));
  703. }
  704. }
  705. // grab the abbreviations available to ffmpeg
  706. $data['abbreviations'] = array();
  707. if(isset($indexs['abbreviations']) === true && isset($matches[$indexs['abbreviations']]) === true)
  708. {
  709. $abbreviations = array_shift(explode("\r", trim($matches[$indexs['abbreviations']])));
  710. if(empty($abbreviations) === false)
  711. {
  712. $data['abbreviations'] = explode(' ', $abbreviations);
  713. }
  714. }
  715. PHPVideoToolkit::$ffmpeg_info = $data;
  716. // cache the data
  717. if($cache_file !== false && $read_from_cache === true)
  718. {
  719. $data['_cache_date'] = time();
  720. file_put_contents($cache_file, '<?php
  721. $info = '.var_export($data, true).';');
  722. }
  723. return $data;
  724. }
  725. /**
  726. * Determines if your ffmpeg has particular codec support for encode or decode.
  727. *
  728. * @access public
  729. * @param string $codec The name of the codec you are checking for.
  730. * @param const $support PHPVideoToolkit::ENCODE or PHPVideoToolkit::DECODE, depending on which functionality is desired.
  731. * @return mixed. Boolean false if there is no support, true if there is support.
  732. */
  733. public function hasCodecSupport($codec, $support=PHPVideoToolkit::ENCODE)
  734. {
  735. $codec = strtolower($codec);
  736. $data = $this->getFFmpegInfo(true);
  737. return isset($data['formats'][$codec]) === true ? $data['formats'][$codec][$support] : false;
  738. }
  739. /**
  740. * Determines the type of support that exists for the FFmpeg-PHP module.
  741. *
  742. * @access public
  743. * @return mixed. Boolean false if there is no support, String 'module' if the actuall
  744. * FFmpeg-PHP module is loaded, or String 'emulated' if the FFmpeg-PHP classes
  745. * can be emulated through the adapter classes.
  746. */
  747. public function hasFFmpegPHPSupport()
  748. {
  749. return self::$ffmpeg_found === false ? false : (extension_loaded('ffmpeg') ? 'module' : (is_file(dirname(__FILE__).DS.'adapters'.DS.'ffmpeg-php'.DS.'ffmpeg_movie.php') && is_file(dirname(__FILE__).DS.'adapters'.DS.'ffmpeg-php'.DS.'ffmpeg_frame.php') && is_file(dirname(__FILE__).DS.'adapters'.DS.'ffmpeg-php'.DS.'ffmpeg_animated_gif.php') ? 'emulated' : false));
  750. }
  751. /**
  752. * Determines if the ffmpeg binary has been compiled with vhook support.
  753. *
  754. * @access public
  755. * @return mixed. Boolean false if there is no support, true there is support.
  756. */
  757. public function hasVHookSupport()
  758. {
  759. $info = $this->getFFmpegInfo(true);
  760. return $info['binary']['vhook-support'];
  761. }
  762. /**
  763. * Returns information about the specified file without having to use ffmpeg-php
  764. * as it consults the ffmpeg binary directly. This idea for this function has been borrowed from
  765. * a French ffmpeg class located: http://www.phpcs.com/codesource.aspx?ID=45279
  766. *
  767. * @access public
  768. * @param string $file The absolute path of the file that is required to be manipulated.
  769. * @return mixed false on error encountered, true otherwise
  770. **/
  771. public function getFileInfo($file=false)
  772. {
  773. // check to see if this is a static call
  774. if($file !== false && isset($this) === false)
  775. {
  776. $toolkit = new PHPVideoToolkit();
  777. return $toolkit->getFileInfo($file);
  778. }
  779. // if the file has not been specified check to see if an input file has been specified
  780. if($file === false)
  781. {
  782. if(!$this->_input_file)
  783. {
  784. // input file not valid
  785. return $this->_raiseError('getFileInfo_no_input');
  786. //<- exits
  787. }
  788. $file = $this->_input_file;
  789. }
  790. $file = escapeshellarg($file);
  791. // create a hash of the filename
  792. $hash = md5($file);
  793. // check to see if the info has already been generated
  794. if(isset(self::$_file_info[$hash]) === true)
  795. {
  796. return self::$_file_info[$hash];
  797. }
  798. // execute the ffmpeg lookup
  799. $buffer = self::_captureExecBuffer($this->_ffmpeg_binary.' -i '.$file, $this->_tmp_directory);
  800. // exec(PHPVIDEOTOOLKIT_FFMPEG_BINARY.' 2>&1', $buffer);
  801. $buffer = implode("\r\n", $buffer);
  802. $data = array();
  803. // grab the duration and bitrate data
  804. preg_match_all('/Duration: (.*)/', $buffer, $matches);
  805. if(count($matches) > 0)
  806. {
  807. $line = trim($matches[0][0]);
  808. // capture any data
  809. preg_match_all('/(Duration|start|bitrate): ([^,]*)/', $line, $matches);
  810. // setup the default data
  811. $data['duration'] = array(
  812. 'timecode' => array(
  813. 'seconds' => array(
  814. 'exact' => -1,
  815. 'excess' => -1
  816. ),
  817. 'rounded' => -1,
  818. )
  819. );
  820. // get the data
  821. foreach ($matches[1] as $key => $detail)
  822. {
  823. $value = $matches[2][$key];
  824. switch(strtolower($detail))
  825. {
  826. case 'duration' :
  827. $data['duration']['timecode']['rounded'] = substr($value, 0, 8);
  828. $data['duration']['timecode']['frames'] = array();
  829. $data['duration']['timecode']['frames']['exact'] = $value;
  830. $data['duration']['timecode']['frames']['excess'] = intval(substr($value, 9));
  831. break;
  832. case 'bitrate' :
  833. $data['bitrate'] = strtoupper($value) === 'N/A' ? -1 : intval($value);
  834. break;
  835. case 'start' :
  836. $data['duration']['start'] = $value;
  837. break;
  838. }
  839. }
  840. }
  841. // match the video stream info
  842. preg_match('/Stream(.*): Video: (.*)/', $buffer, $matches);
  843. if(count($matches) > 0)
  844. {
  845. $data['video'] = array();
  846. // get the dimension parts
  847. preg_match('/([0-9]{1,5})x([0-9]{1,5})/', $matches[2], $dimensions_matches);
  848. // print_r($dimensions_matches);
  849. $dimensions_value = $dimensions_matches[0];
  850. $data['video']['dimensions'] = array(
  851. 'width' => floatval($dimensions_matches[1]),
  852. 'height' => floatval($dimensions_matches[2])
  853. );
  854. // get the timebases
  855. $data['video']['time_bases'] = array();
  856. preg_match_all('/([0-9\.k]+) (fps|tbr|tbc|tbn)/', $matches[0], $fps_matches);
  857. if(count($fps_matches[0]) > 0)
  858. {
  859. foreach ($fps_matches[2] as $key => $abrv)
  860. {
  861. $data['video']['time_bases'][$abrv] = $fps_matches[1][$key];
  862. }
  863. }
  864. // get the video frames per second
  865. $fps = isset($data['video']['time_bases']['fps']) === true ? $data['video']['time_bases']['fps'] : (isset($data['video']['time_bases']['tbr']) === true ? $data['video']['time_bases']['tbr'] : false);
  866. if($fps !== false)
  867. {
  868. $fps = floatval($fps);
  869. $data['duration']['timecode']['frames']['frame_rate'] = $data['video']['frame_rate'] = $fps;
  870. $data['duration']['timecode']['seconds']['total'] = $data['duration']['seconds'] = $this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%fn', '%st.%ms', $data['video']['frame_rate']);
  871. }
  872. $fps_value = $fps_matches[0];
  873. // get the ratios
  874. preg_match('/\[PAR ([0-9\:\.]+) DAR ([0-9\:\.]+)\]/', $matches[0], $ratio_matches);
  875. if(count($ratio_matches))
  876. {
  877. $data['video']['pixel_aspect_ratio'] = $ratio_matches[1];
  878. $data['video']['display_aspect_ratio'] = $ratio_matches[2];
  879. }
  880. // work out the number of frames
  881. if(isset($data['duration']) === true && isset($data['video']) === true)
  882. {
  883. // set the total frame count for the video
  884. $data['video']['frame_count'] = ceil($data['duration']['seconds'] * $data['video']['frame_rate']);
  885. // set the framecode
  886. $data['duration']['timecode']['seconds']['excess'] = floatval($data['duration']['seconds']) - floor($data['duration']['seconds']);
  887. $data['duration']['timecode']['seconds']['exact'] = $this->formatSeconds($data['duration']['seconds'], '%hh:%mm:%ss.%ms');
  888. $data['duration']['timecode']['frames']['exact'] = $this->formatTimecode($data['video']['frame_count'], '%ft', '%hh:%mm:%ss.%fn', $fps);
  889. $data['duration']['timecode']['frames']['total'] = $data['video']['frame_count'];
  890. }
  891. // formats should be anything left over, let me know if anything else exists
  892. $parts = explode(',', $matches[2]);
  893. $other_parts = array($dimensions_value, $fps_value);
  894. $formats = array();
  895. foreach($parts as $key=>$part)
  896. {
  897. $part = trim($part);
  898. if(!in_array($part, $other_parts))
  899. {
  900. array_push($formats, $part);
  901. }
  902. }
  903. $data['video']['pixel_format'] = $formats[1];
  904. $data['video']['codec'] = $formats[0];
  905. }
  906. // match the audio stream info
  907. preg_match('/Stream(.*): Audio: (.*)/', $buffer, $matches);
  908. if(count($matches) > 0)
  909. {
  910. // setup audio values
  911. $data['audio'] = array(
  912. 'stereo' => -1,
  913. 'sample_rate' => -1,
  914. 'sample_rate' => -1
  915. );
  916. $other_parts = array();
  917. // get the stereo value
  918. preg_match('/(stereo|mono)/i', $matches[0], $stereo_matches);
  919. if(count($stereo_matches))
  920. {
  921. $data['audio']['stereo'] = $stereo_matches[0];
  922. array_push($other_parts, $stereo_matches[0]);
  923. }
  924. // get the sample_rate
  925. preg_match('/([0-9]{3,6}) Hz/', $matches[0], $sample_matches);
  926. if(count($sample_matches))
  927. {
  928. $data['audio']['sample_rate'] = count($sample_matches) ? floatval($sample_matches[1]) : -1;
  929. array_push($other_parts, $sample_matches[0]);
  930. }
  931. // get the bit rate
  932. preg_match('/([0-9]{1,3}) kb\/s/', $matches[0], $bitrate_matches);
  933. if(count($bitrate_matches))
  934. {
  935. $data['audio']['bitrate'] = count($bitrate_matches) ? floatval($bitrate_matches[1]) : -1;
  936. array_push($other_parts, $bitrate_matches[0]);
  937. }
  938. // formats should be anything left over, let me know if anything else exists
  939. $parts = explode(',', $matches[2]);
  940. $formats = array();
  941. foreach($parts as $key=>$part)
  942. {
  943. $part = trim($part);
  944. if(!in_array($part, $other_parts))
  945. {
  946. array_push($formats, $part);
  947. }
  948. }
  949. $data['audio']['codec'] = $formats[0];
  950. // if no video is set then no audio frame rate is set
  951. if($data['duration']['timecode']['seconds']['exact'] === -1)
  952. {
  953. $exact_timecode = $this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%fn', '%hh:%mm:%ss.%ms', 1000);
  954. $data['duration']['timecode']['seconds'] = array(
  955. 'exact' => $exact_timecode,
  956. 'excess' => intval(substr($exact_timecode, 8)),
  957. 'total' => $this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%fn', '%ss.%ms', 1000)
  958. );
  959. $data['duration']['timecode']['frames']['frame_rate'] = 1000;
  960. $data['duration']['seconds'] = $data['duration']['timecode']['seconds']['total'];
  961. //$this->formatTimecode($data['duration']['timecode']['frames']['exact'], '%hh:%mm:%ss.%fn', '%st.%ms', $data['video']['frame_rate']);
  962. }
  963. }
  964. // check that some data has been obtained
  965. if(!count($data))
  966. {
  967. $data = false;
  968. }
  969. else
  970. {
  971. $data['_raw_info'] = $buffer;
  972. }
  973. // cache info and return
  974. return self::$_file_info[$hash] = $data;
  975. }
  976. /**
  977. * Determines if the input media has a video stream.
  978. *
  979. * @access public
  980. * @param string $file The absolute path of the file that is required to be manipulated.
  981. * @return bool
  982. **/
  983. public function fileHasVideo($file=false)
  984. {
  985. // check to see if this is a static call
  986. if($file !== false && isset($this) === false)
  987. {
  988. $toolkit = new PHPVideoToolkit();
  989. $data = $toolkit->getFileInfo($file);
  990. }
  991. // if the file has not been specified check to see if an input file has been specified
  992. else if($file === false)
  993. {
  994. if(!$this->_input_file)
  995. {
  996. // input file not valid
  997. return $this->_raiseError('inputFileHasVideo_no_input');
  998. //<- exits
  999. }
  1000. $file = $this->_input_file;
  1001. $data = $this->getFileInfo($file);
  1002. }
  1003. return isset($data['video']);
  1004. }
  1005. /**
  1006. * Determines if the input media has an audio stream.
  1007. *
  1008. * @access public
  1009. * @param string $file The absolute path of the file that is required to be manipulated.
  1010. * @return bool
  1011. **/
  1012. public function fileHasAudio($file=false)
  1013. {
  1014. // check to see if this is a static call
  1015. if($file !== false && isset($this) === false)
  1016. {
  1017. $toolkit = new PHPVideoToolkit();
  1018. $data = $toolkit->getFileInfo($file);
  1019. }
  1020. // if the file has not been specified check to see if an input file has been specified
  1021. else if($file === false)
  1022. {
  1023. if(!$this->_input_file)
  1024. {
  1025. // input file not valid
  1026. return $this->_raiseError('inputFileHasAudio_no_input');
  1027. //<- exits
  1028. }
  1029. $file = $this->_input_file;
  1030. $data = $this->getFileInfo($file);
  1031. }
  1032. return isset($data['audio']);
  1033. }
  1034. /**
  1035. * Sets the input file that is going to be manipulated.
  1036. *
  1037. * @access public
  1038. * @param string $file The absolute path of the file that is required to be manipulated.
  1039. * @param mixed $input_frame_rate If 0 (default) then no input frame rate is set, if false it is automatically retrieved, otherwise
  1040. * any other integer will be set as the incoming frame rate.
  1041. * @return boolean false on error encountered, true otherwise
  1042. */
  1043. public function setInputFile($file, $input_frame_rate=0, $validate_decode_codecs=true)
  1044. {
  1045. $files_length = count($file);
  1046. // if the total number of files entered is 1 then only one file is being processed
  1047. if($files_length == 1)
  1048. {
  1049. // check the input file, if there is a %d in there or a similar %03d then the file inputted is a sequence, if neither of those is found
  1050. // then qheck to see if the file exists
  1051. if(!preg_match('/\%([0-9]+)d/', $file) && strpos($file, '%d') === false && !is_file($file))
  1052. {
  1053. // input file not valid
  1054. return $this->_raiseError('setInputFile_file_existence', array('file'=>$file));
  1055. //<- exits
  1056. }
  1057. $escaped_name = $file;
  1058. // $escaped_name = escapeshellarg($files[0]);
  1059. $this->_input_file = $escaped_name;
  1060. $this->_input_file_id = md5($escaped_name);
  1061. // the -inputr is a hack for -r to come before the input
  1062. if($input_frame_rate !== 0)
  1063. {
  1064. $info = $this->getFileInfo();
  1065. if(isset($info['video']) === true)
  1066. {
  1067. if($input_frame_rate === false)
  1068. {
  1069. $input_frame_rate = $info['video']['frame_rate'];
  1070. }
  1071. // input frame rate is a command hack
  1072. $this->addCommand('-inputr', $input_frame_rate);
  1073. }
  1074. }
  1075. }
  1076. else
  1077. {
  1078. // more than one video is being added as input so we must join them all
  1079. call_user_func_array(array(&$this, 'addVideo'), array($file, $input_frame_rate));
  1080. }
  1081. return true;
  1082. }
  1083. /**
  1084. * A shortcut for converting video to FLV.
  1085. *
  1086. * @access public
  1087. * @param integer $audio_sample_frequency
  1088. * @param integer $audio_bitrate
  1089. * @param boolean $validate_codecs
  1090. * @return mixed
  1091. */
  1092. public function setFormatToFLV($audio_sample_frequency=44100, $audio_bitrate=64, $validate_codecs=true)
  1093. {
  1094. $this->addCommand('-sameq');
  1095. $audio_able = $this->setAudioFormat(self::FORMAT_MP3, $validate_codecs);
  1096. // adjust the audio rates
  1097. $this->setAudioBitRate($audio_bitrate);
  1098. $this->setAudioSampleFrequency($audio_sample_frequency);
  1099. // set the video format
  1100. $flv_able = $this->setFormat(self::FORMAT_FLV, $validate_codecs);
  1101. // flag that the flv has to have meta data added after the excecution of this command
  1102. // register the post tidy process
  1103. $this->registerPostProcess('_addMetaToFLV', $this);
  1104. return $audio_able !== false && $flv_able !== false;
  1105. }
  1106. /**
  1107. * When converting video to FLV the meta data has to be added by a ruby program called FLVTools2.
  1108. * This is a second exec call only after the video has been converted to FLV
  1109. * http://inlet-media.de/flvtool2
  1110. *
  1111. * @access protected
  1112. */
  1113. protected function _addMetaToFLV($files)
  1114. {
  1115. $file = array_pop($files);
  1116. // prepare the command suitable for exec
  1117. $exec_string = $this->_prepareCommand(PHPVIDEOTOOLKIT_FLVTOOLS_BINARY, '-U '.$file);
  1118. // execute the command
  1119. exec($exec_string);
  1120. if(is_array($this->_processed[0]))
  1121. {
  1122. array_push($this->_processed[0], $exec_string);
  1123. }
  1124. else
  1125. {
  1126. $this->_processed[0] = array($this->_processed[0], $exec_string);
  1127. }
  1128. return true;
  1129. }
  1130. /**
  1131. * Streams a FLV file from a given point. You can control bandwidth, cache and session options.
  1132. * Inspired by xmoov-php
  1133. * @see xmoov-php,
  1134. * - @link http://xmoov.com/
  1135. * - @author Eric Lorenzo Benjamin jr
  1136. * @access public
  1137. * @param integer $seek_pos The position in the file to seek to.
  1138. * @param array|boolean $bandwidth_options If a boolean value, false then no bandwidth limiting will take place.
  1139. * If true then bandwidth limiting will take place with packet_size = 90 and packet_interval = 0.3.
  1140. * If an array the following values are default packet_size = 90 and packet_interval = 0.3, you will also
  1141. * have to set active = true, ie array('active'=>true, 'packet_size'=>90, 'packet_interval'=>0.3)
  1142. * @param boolean $allow_cache If true the file will be allowed to cache in the browser, if false then it won't
  1143. * @return boolean
  1144. */
  1145. public function flvStreamSeek($seek_pos=0, $bandwidth_options=array(), $allow_cache=true)
  1146. {
  1147. // check for input file
  1148. if(!$this->_input_file)
  1149. {
  1150. // input file not valid
  1151. return $this->_raiseError('streamFLV_no_input');
  1152. //<- exits
  1153. }
  1154. // make the pos safe
  1155. $seek_pos = intval($seek_pos);
  1156. // absorb the bandwidth options
  1157. $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);
  1158. // if this file is not allowed to be cached send cache headers for all browsers.
  1159. if(!$allow_cache)
  1160. {
  1161. session_cache_limiter('nocache');
  1162. header('Expires: Thu, 19 Nov 1981 08:52:00 GMT');
  1163. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  1164. header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  1165. header('Pragma: no-cache');
  1166. }
  1167. // open file
  1168. $handle = fopen($this->_input_file, 'rb');
  1169. $file_size = filesize($this->_input_file) - (($seek_pos > 0) ? $seek_pos + 1 : 0);
  1170. // send the flv headers
  1171. header('Content-Type: video/x-flv');
  1172. header('Content-Disposition: attachment; filename="'.basename($this->_input_file).'"');
  1173. header('Content-Length: '.$file_size);
  1174. // flv format header
  1175. if($seek_pos != 0)
  1176. {
  1177. print('FLV');
  1178. print(pack('C', 1));
  1179. print(pack('C', 1));
  1180. print(pack('N', 9));
  1181. print(pack('N', 9));
  1182. }
  1183. // seek to the required point
  1184. if(fseek($handle, $seek_pos) === -1)
  1185. {
  1186. // input file not valid
  1187. return $this->_raiseError('streamFLV_passed_eof');
  1188. //<- exits
  1189. }
  1190. // if bandwidth control is active then workout the options
  1191. if($bandwidth_options['active'])
  1192. {
  1193. $packet_interval = intval($bandwidth_options['packet_interval']);
  1194. $packet_size = intval($bandwidth_options['packet_size']) * 1042;
  1195. }
  1196. // output the file
  1197. while(!feof($handle))
  1198. {
  1199. // limit the bandwidth
  1200. if($bandwidth_options['active'] && $packet_interval > 0)
  1201. {
  1202. // output the required packet
  1203. $time_start = self::microtimeFloat();
  1204. echo fread($handle, $packet_size);
  1205. $time_stop = self::microtimeFloat();
  1206. // delay the output
  1207. $time_difference = $time_stop - $time_start;
  1208. if($time_difference < $packet_interval)
  1209. {
  1210. usleep(($packet_interval * 1000000) - ($time_difference * 1000000));
  1211. }
  1212. }
  1213. // no bandwidth limiting
  1214. else
  1215. {
  1216. echo fread($handle, $file_size);
  1217. }
  1218. }
  1219. // close the file
  1220. fclose($handle);
  1221. return true;
  1222. }
  1223. /**
  1224. * This is an alias for setFormat, but restricts it to audio only formats.
  1225. *
  1226. * @access public
  1227. * @param integer $format A supported audio format.
  1228. * @param integer $audio_sample_frequency
  1229. * @param integer $audio_bitrate
  1230. **/
  1231. public function extractAudio($format=PHPVideoToolkit::FORMAT_MP3, $audio_sample_frequency=44100, $audio_bitrate=64)
  1232. {
  1233. // check the format is one of the audio formats
  1234. 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)))
  1235. {
  1236. return $this->_raiseError('extractAudio_valid_format', array('format'=>$format));
  1237. //<- exits
  1238. }
  1239. $this->setFormat($format);
  1240. // adjust the audio rates
  1241. $this->setAudioBitRate($audio_bitrate);
  1242. $this->setAudioSampleFrequency($audio_sample_frequency);
  1243. }
  1244. /**
  1245. * Sets the new video format.
  1246. *
  1247. * @access public
  1248. * @param defined $format The format should use one of the defined variables stated below.
  1249. * PHPVideoToolkit::FORMAT_3GP2 - 3g2
  1250. * PHPVideoToolkit::FORMAT_3GP - 3gp
  1251. * PHPVideoToolkit::FORMAT_AAC - aac
  1252. * PHPVideoToolkit::FORMAT_AIFF - aiff
  1253. * PHPVideoToolkit::FORMAT_AMR - amr
  1254. * PHPVideoToolkit::FORMAT_ASF - asf
  1255. * PHPVideoToolkit::FORMAT_AVI - avi
  1256. * PHPVideoToolkit::FORMAT_FLV - flv
  1257. * PHPVideoToolkit::FORMAT_GIF - gif
  1258. * PHPVideoToolkit::FORMAT_MJ2 - mj2
  1259. * PHPVideoToolkit::FORMAT_MP2 - mp2
  1260. * PHPVideoToolkit::FORMAT_MP3 - mp3
  1261. * PHPVideoToolkit::FORMAT_MP4 - mp4
  1262. * PHPVideoToolkit::FORMAT_MPEG4 - mpeg4
  1263. * PHPVideoToolkit::FORMAT_M4A - m4a
  1264. * PHPVideoToolkit::FORMAT_MPEG - mpeg
  1265. * PHPVideoToolkit::FORMAT_MPEG1 - mpeg1video
  1266. * PHPVideoToolkit::FORMAT_MPEG2 - mpeg2video
  1267. * PHPVideoToolkit::FORMAT_MPEGVIDEO - mpegvideo
  1268. * PHPVideoToolkit::FORMAT_PSP - psp
  1269. * PHPVideoToolkit::FORMAT_RM - rm
  1270. * PHPVideoToolkit::FORMAT_SWF - swf
  1271. * PHPVideoToolkit::FORMAT_VOB - vob
  1272. * PHPVideoToolkit::FORMAT_WAV - wav
  1273. * PHPVideoToolkit::FORMAT_JPG - jpg
  1274. * @return boolean false on error encountered, true otherwise
  1275. */
  1276. public function setFormat($format)
  1277. {
  1278. // validate input
  1279. 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)))
  1280. {
  1281. //return $this->_raiseError('setFormat_valid_format', array('format'=>$format));
  1282. //<- exits
  1283. }
  1284. return $this->addCommand('-f', $format);
  1285. }
  1286. /**
  1287. * Sets the audio sample frequency for audio outputs
  1288. *
  1289. * @access public
  1290. * @param integer $audio_sample_frequency Valid values are 11025, 22050, 44100
  1291. * @return boolean false on error encountered, true otherwise
  1292. */
  1293. public function setAudioSampleFrequency($audio_sample_frequency)
  1294. {
  1295. // validate input
  1296. if(!in_array(intval($audio_sample_frequency), array(11025, 22050, 44100)))
  1297. {
  1298. return $this->_raiseError('setAudioSampleFrequency_valid_frequency', array('frequency'=>$audio_sample_frequency));
  1299. //<- exits
  1300. }
  1301. return $this->addCommand('-ar', $audio_sample_frequency);
  1302. }
  1303. /**
  1304. * @access public
  1305. * @depreciated
  1306. * @see PHPVideoToolkit::setAudioCodec()
  1307. */
  1308. public function setAudioFormat($audio_codec, $validate_codec=true)
  1309. {
  1310. return $this->setAudioCodec($audio_codec, $validate_codec);
  1311. }
  1312. /**
  1313. * Sets the audio format for audio outputs
  1314. *
  1315. * @access public
  1316. * @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
  1317. * @param boolean $validate_codec Queries ffmpeg to see if this codec is available to use.
  1318. * @return boolean false on error encountered, true otherwise
  1319. */
  1320. public function setAudioCodec($audio_codec, $validate_codec=true)
  1321. {
  1322. // validate input
  1323. 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)))
  1324. {
  1325. //return $this->_raiseError('setAudioFormat_valid_format', array('format'=>$audio_codec));
  1326. //<- exits
  1327. }
  1328. // run a libmp3lame check as it require different mp3 codec
  1329. // updated thanks to Varon for providing the research
  1330. if($audio_codec == self::FORMAT_MP3)
  1331. {
  1332. $info = $this->getFFmpegInfo(false);
  1333. if(isset($info['formats']['libmp3lame']) === true || in_array('--enable-libmp3lame', $info['binary']['configuration']) === true)
  1334. {
  1335. $audio_codec = 'libmp3lame';
  1336. }
  1337. }
  1338. // do we need to validate this codec?
  1339. if($validate_codec === true)
  1340. {
  1341. if($this->canCodecBeEncoded('audio', $audio_codec) === false)
  1342. {
  1343. return $this->_raiseError('setAudioFormat_cannnot_encode', array('codec'=>$audio_codec));
  1344. //<- exits
  1345. }
  1346. }
  1347. return $this->addCommand('-acodec', $audio_codec);
  1348. }
  1349. /**
  1350. * @access public
  1351. * @depreciated
  1352. * @see PHPVideoToolkit::setVideoCodec()
  1353. */
  1354. public function setVideoFormat($video_format, $validate_codec=true)
  1355. {
  1356. return $this->setVideoCodec($video_format);
  1357. }
  1358. /**
  1359. * Forces the video format for video outputs to a specific codec. This should not be confused with setFormat. setVideoFormat does not generally need to
  1360. * be called unless setting a specific video format for a type of media format. It gets a little confusing...
  1361. *
  1362. * @access public
  1363. * @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
  1364. * @param boolean $validate_codec Queries ffmpeg to see if this codec is available to use.
  1365. * @return boolean false on error encountered, true otherwise
  1366. */
  1367. public function setVideoCodec($video_codec, $validate_codec=true)
  1368. {
  1369. // validate input
  1370. 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)))
  1371. {
  1372. //return $this->_raiseError('setVideoFormat_valid_format', array('format'=>$video_codec));
  1373. //<- exits
  1374. }
  1375. // do we need to validate this codec?
  1376. if($validate_codec === true)
  1377. {
  1378. if($this->canCodecBeEncoded('video', $video_codec) === false)
  1379. {
  1380. return $this->_raiseError('setVideoFormat_cannnot_encode', array('codec'=>$video_codec));
  1381. //<- exits
  1382. }
  1383. }
  1384. return $this->addCommand('-vcodec', $video_codec);
  1385. }
  1386. /**
  1387. * Disables audio encoding
  1388. *
  1389. * @access public
  1390. * @return boolean false on error encountered, true otherwise
  1391. */
  1392. public function disableAudio()
  1393. {
  1394. return $this->addCommand('-an');
  1395. }
  1396. /**
  1397. * Disables video encoding
  1398. *
  1399. * @access public
  1400. * @return boolean false on error encountered, true otherwise
  1401. */
  1402. public function disableVideo()
  1403. {
  1404. return $this->addCommand('-vn');
  1405. }
  1406. /**
  1407. * Sets the number of audio channels
  1408. *
  1409. * @access public
  1410. * @param integer $channel_type Valid values are PHPVideoToolkit::AUDIO_MONO, PHPVideoToolkit::AUDIO_STEREO
  1411. * @return boolean false on error encountered, true otherwise
  1412. */
  1413. public function setAudioChannels($channel_type=PHPVideoToolkit::AUDIO_MONO)
  1414. {
  1415. // validate input
  1416. if(!in_array($channel_type, array(self::AUDIO_MONO, self::AUDIO_STEREO)))
  1417. {
  1418. return $this->_raiseError('setAudioChannels_valid_channels', array('channels'=>$channel_type));
  1419. //<- exits
  1420. }
  1421. return $this->addCommand('-ac', $channel_type);
  1422. }
  1423. /**
  1424. * Sets the audio bitrate
  1425. *
  1426. * @access public
  1427. * @param integer $audio_bitrate Valid values are 16, 32, 64
  1428. * @return boolean false on error encountered, true otherwise
  1429. */
  1430. public function setAudioBitRate($bitrate)
  1431. {
  1432. // validate input
  1433. if(!in_array(intval($bitrate), array(16, 32, 64, 128, 160, 256, 320)))
  1434. {
  1435. //return $this->_raiseError('setAudioBitRate_valid_bitrate', array('bitrate'=>$bitrate));
  1436. //<- exits
  1437. }
  1438. return $this->addCommand('-ab', $bitrate);
  1439. }
  1440. /**
  1441. * Compiles an array of images into a video. This sets the input file (setInputFile) so you do not need to set it.
  1442. * The images should be a full absolute path to the actual image file.
  1443. * 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
  1444. * creating the ffmpeg instance you will need to set the absolute path to the temporary folder. The default path is '/tmp/'.
  1445. * NOTE 2; Please make sure all of the images are all of the same type.
  1446. *
  1447. * @access public
  1448. * @param array $images An array of images that are to be joined and converted into a video
  1449. * @param integer $input_frame_rate An integer that will specify the input frame rate for the images.
  1450. * @return boolean Returns false on encountering an error
  1451. */
  1452. public function prepareImagesForConversionToVideo($images, $input_frame_rate)
  1453. {
  1454. // http://ffmpeg.mplayerhq.hu/faq.html#TOC3
  1455. // ffmpeg -f image2 -i img%d.jpg /tmp/a.mpg
  1456. if(empty($images))
  1457. {
  1458. return $this->_raiseError('prepareImagesForConversionToVideo_one_img');
  1459. //<- exits
  1460. }
  1461. // loop through and validate existence first before making a temporary copy
  1462. foreach ($images as $key=>$img)
  1463. {
  1464. if(!is_file($img))
  1465. {
  1466. return $this->_raiseError('prepareImagesForConversionToVideo_img_404', array('img'=>$img));
  1467. //<- exits
  1468. }
  1469. }
  1470. if(!is_dir($this->_tmp_directory))
  1471. {
  1472. return $this->_raiseError('generic_temp_404');
  1473. //<- exits
  1474. }
  1475. if(!is_writable($this->_tmp_directory))
  1476. {
  1477. return $this->_raiseError('generic_temp_writable');
  1478. //<- exits
  1479. }
  1480. // get the number of preceding places for the files based on how many files there are to copy
  1481. $total = count($images);
  1482. // create a temp dir in the temp dir
  1483. $uniqid = $this->unique();
  1484. mkdir($this->_tmp_directory.$uniqid, 0777);
  1485. // loop through, copy and rename specified images to the temp dir
  1486. $ext = false;
  1487. foreach ($images as $key=>$img)
  1488. {
  1489. $file_ext = array_pop(explode('.', $img));
  1490. if($ext !== false && $ext !== $file_ext)
  1491. {
  1492. return $this->_raiseError('prepareImagesForConversionToVideo_img_type');
  1493. //<- exits
  1494. }
  1495. $ext = $file_ext;
  1496. $tmp_file = $this->_tmp_directory.$uniqid.DS.$this->_tmp_file_prefix.$key.'.'.$ext;
  1497. if(!@copy($img, $tmp_file))
  1498. {
  1499. return $this->_raiseError('prepareImagesForConversionToVideo_img_copy', array('img'=>$img, 'tmpfile'=>$tmp_file));
  1500. //<- exits
  1501. }
  1502. // push the tmp file name into the unlinks so they can be deleted on class destruction
  1503. array_push($this->_unlink_files, $tmp_file);
  1504. }
  1505. // the inputr is a hack for -r to come before the input
  1506. $this->addCommand('-inputr', $input_frame_rate);
  1507. // exit;
  1508. // add the directory to the unlinks
  1509. array_push($this->_unlink_dirs, $this->_tmp_directory.$uniqid);
  1510. // get the input file format
  1511. $file_iteration = $this->_tmp_file_prefix.'%d.'.$ext;
  1512. // set the input filename
  1513. return $this->setInputFile($this->_tmp_directory.$uniqid.DS.$file_iteration);
  1514. }
  1515. /**
  1516. * Sets the video bitrate
  1517. *
  1518. * @access public
  1519. * @param integer $bitrate
  1520. * @return boolean
  1521. */
  1522. public function setVideoBitRate($bitrate)
  1523. {
  1524. $bitrate = intval($bitrate);
  1525. return $this->addCommand('-b', $bitrate.'k');
  1526. }
  1527. /**
  1528. * Sets the amount of time an animated gif output will loop
  1529. *
  1530. * @access public
  1531. * @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.
  1532. */
  1533. public function setGifLoops($loop_count)
  1534. {
  1535. if($loop_count !== false)
  1536. {
  1537. $this->addCommand('-loop_output', $loop_count);
  1538. }
  1539. }
  1540. /**
  1541. * @access public
  1542. * @depreciated
  1543. * @see PHPVideoToolkit::setVideoDimensions()
  1544. */
  1545. public function setVideoOutputDimensions($width, $height=null)
  1546. {
  1547. return $this->setVideoDimensions($width, $height);
  1548. }
  1549. /**
  1550. * Sets the video output dimensions (in pixels)
  1551. *
  1552. * @access public
  1553. * @param mixed $width If an integer height also has to be specified, otherwise you can use one of the class constants
  1554. * PHPVideoToolkit::SIZE_SAS = Same as input source
  1555. * PHPVideoToolkit::SIZE_SQCIF = 128 x 96
  1556. * PHPVideoToolkit::SIZE_QCIF = 176 x 144
  1557. * PHPVideoToolkit::SIZE_CIF = 352 x 288
  1558. * PHPVideoToolkit::SIZE_4CIF = 704 x 576
  1559. * PHPVideoToolkit::SIZE_QQVGA = 160 x 120
  1560. * PHPVideoToolkit::SIZE_QVGA = 320 x 240
  1561. * PHPVideoToolkit::SIZE_VGA = 640 x 480
  1562. * PHPVideoToolkit::SIZE_SVGA = 800 x 600
  1563. * PHPVideoToolkit::SIZE_XGA = 1024 x 768
  1564. * PHPVideoToolkit::SIZE_UXGA = 1600 x 1200
  1565. * PHPVideoToolkit::SIZE_QXGA = 2048 x 1536
  1566. * PHPVideoToolkit::SIZE_SXGA = 1280 x 1024
  1567. * PHPVideoToolkit::SIZE_QSXGA = 2560 x 2048
  1568. * PHPVideoToolkit::SIZE_HSXGA = 5120 x 4096
  1569. * PHPVideoToolkit::SIZE_WVGA = 852 x 480
  1570. * PHPVideoToolkit::SIZE_WXGA = 1366 x 768
  1571. * PHPVideoToolkit::SIZE_WSXGA = 1600 x 1024
  1572. * PHPVideoToolkit::SIZE_WUXGA = 1920 x 1200
  1573. * PHPVideoToolkit::SIZE_WOXGA = 2560 x 1600
  1574. * PHPVideoToolkit::SIZE_WQSXGA = 3200 x 2048
  1575. * PHPVideoToolkit::SIZE_WQUXGA = 3840 x 2400
  1576. * PHPVideoToolkit::SIZE_WHSXGA = 6400 x 4096
  1577. * PHPVideoToolkit::SIZE_WHUXGA = 7680 x 4800
  1578. * PHPVideoToolkit::SIZE_CGA = 320 x 200
  1579. * PHPVideoToolkit::SIZE_EGA = 640 x 350
  1580. * PHPVideoToolkit::SIZE_HD480 = 852 x 480
  1581. * PHPVideoToolkit::SIZE_HD720 = 1280 x 720
  1582. * PHPVideoToolkit::SIZE_HD1080 = 1920 x 1080
  1583. * @param integer $height
  1584. * @return boolean
  1585. */
  1586. public function setVideoDimensions($width=PHPVideoToolkit::SIZE_SAS, $height=null)
  1587. {
  1588. if($height === null || $height === true)
  1589. {
  1590. // validate input
  1591. 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)))
  1592. {
  1593. return $this->_raiseError('setVideoOutputDimensions_valid_format', array('format'=>$format));
  1594. //<- exits
  1595. }
  1596. if($width === self::SIZE_SAS)
  1597. {
  1598. // and override is made so no command is added in the hope that ffmpeg will just output the source
  1599. if($height === true)
  1600. {
  1601. return true;
  1602. }
  1603. // get the file info
  1604. $info = $this->getFileInfo();
  1605. if(isset($info['video']) === false || isset($info['video']['dimensions']) === false)
  1606. {
  1607. return $this->_raiseError('setVideoOutputDimensions_sas_dim');
  1608. }
  1609. else
  1610. {
  1611. $width = $info['video']['dimensions']['width'].'x'.$info['video']['dimensions']['height'];
  1612. }
  1613. }
  1614. }
  1615. else
  1616. {
  1617. $height_split = explode(' ',$height);
  1618. // check that the width and height are even
  1619. if($width % 2 !== 0 || $height_split[0] % 2 !== 0)
  1620. {
  1621. return $this->_raiseError('setVideoOutputDimensions_valid_integer');
  1622. //<- exits
  1623. }
  1624. $width = $width.'x'.$height_split[0];
  1625. }
  1626. $this->addCommand('-s', $width);
  1627. if (isset($height_split) && count($height_split) > 1) {
  1628. $commands = $height_split;
  1629. array_shift($commands);
  1630. $commands = implode(' ',$commands);
  1631. preg_match_all('/-(\S*)\s(\S*)/',$commands,$matches);
  1632. foreach($matches[0] as $match) {
  1633. $command = explode(' ',$match);
  1634. if (count($command) == 2) {
  1635. $command[0] = preg_replace('/\"/','',$command[0]);
  1636. $command[1] = preg_replace('/\"/','',$command[1]);
  1637. $this->addCommand($command[0], $command[1]);
  1638. }
  1639. }
  1640. }
  1641. return true;
  1642. }
  1643. /**
  1644. * Sets the video aspect ratio.
  1645. * IMPORTANT! Setting an aspect ratio will change the width of the video output if the specified dimensions aren't already
  1646. * in the correct ratio. ie, Setting the aspect ratio to RATIO_STANDARD when you set the output dimensions to 176 x 144
  1647. * 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
  1648. * which is obviously invalid.
  1649. *
  1650. * @access public
  1651. * @param string|integer $ratio Valid values are PHPVideoToolkit::RATIO_STANDARD, PHPVideoToolkit::RATIO_WIDE, PHPVideoToolkit::RATIO_CINEMATIC, or '4:3', '16:9', '1.85'
  1652. * @return boolean
  1653. */
  1654. public function setVideoAspectRatio($ratio)
  1655. {
  1656. if(!in_array($ratio, array(self::RATIO_STANDARD, self::RATIO_WIDE, self::RATIO_CINEMATIC)))
  1657. {
  1658. return $this->_raiseError('setVideoAspectRatio_valid_ratio', array('ratio'=>$ratio));
  1659. }
  1660. $this->addCommand('-aspect', $ratio);
  1661. return true;
  1662. }
  1663. /**
  1664. * Sets the frame rate of the video
  1665. *
  1666. * @access public
  1667. * @param string|integer $fps 1 being 1 frame per second, 1:2 being 0.5 frames per second
  1668. * @return boolean
  1669. */
  1670. public function setVideoFrameRate($fps)
  1671. {
  1672. return $this->addCommand('-r', $fps);
  1673. }
  1674. /**
  1675. * Extracts a segment of video and/or audio
  1676. * (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.
  1677. * 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
  1678. * 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
  1679. * 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
  1680. * 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,
  1681. * say 1 second in you should set $extract_begin_timecode='00:00:01' and set $extract_end_timecode='00:00:01'.)
  1682. *
  1683. * @access public
  1684. * @param string $extract_begin_timecode A timecode (hh:mm:ss.fn - you can change the timecode format by changing the $timecode_format param
  1685. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info)
  1686. * @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
  1687. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info)
  1688. * @param integer $timecode_format The format of the $extract_begin_timecode and $extract_end_timecode timecodes are being given in.
  1689. * default '%hh:%mm:%ss'
  1690. * - %hh (hours) representative of hours
  1691. * - %mm (minutes) representative of minutes
  1692. * - %ss (seconds) representative of seconds
  1693. * - %fn (frame number) representative of frames (of the current second, not total frames)
  1694. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  1695. * - %ft (frames total) representative of total frames (ie frame number)
  1696. * - %st (seconds total) representative of total seconds (rounded).
  1697. * - %sf (seconds floored) representative of total seconds (floored).
  1698. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  1699. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  1700. * @param boolean $check_frames_exist Determines if a frame exists check should be made to ensure the timecode given by $extract_end_timecode
  1701. * actually exists.
  1702. */
  1703. public function extractSegment($extract_begin_timecode, $extract_end_timecode, $timecode_format='%hh:%mm:%ss.%fn', $frames_per_second=false, $check_frames_exist=true)
  1704. {
  1705. // check for frames per second, if it's not set auto set it.
  1706. if($frames_per_second === false)
  1707. {
  1708. $info = $this->getFileInfo();
  1709. $frames_per_second = $info['duration']['timecode']['frames']['frame_rate'];
  1710. }
  1711. // check if frame exists
  1712. if($check_frames_exist)
  1713. {
  1714. if($info['duration']['seconds'] < floatval($this->formatTimecode($extract_end_timecode, $timecode_format, '%ss.%ms', $frames_per_second)))
  1715. {
  1716. // the input has not returned any video data so the frame rate can not be guessed
  1717. return $this->_raiseError('extractSegment_end_timecode');
  1718. }
  1719. else if($extract_end_timecode !== false && $info['duration']['seconds'] < floatval($this->formatTimecode($extract_begin_timecode, $timecode_format, '%ss.%ms', $frames_per_second)))
  1720. {
  1721. // the input has not returned any video data so the frame rate can not be guessed
  1722. return $this->_raiseError('extractSegment_begin_timecode');
  1723. }
  1724. }
  1725. // format the begin timecode if the timecode format is not already ok.
  1726. $begin_position = (float) $this->formatTimecode($extract_begin_timecode, $timecode_format, '%ss.%ms', $frames_per_second);
  1727. if($timecode_format !== '%hh:%mm:%ss.%ms')
  1728. {
  1729. $extract_begin_timecode = $this->formatTimecode($extract_begin_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1730. }
  1731. $this->addCommand('-ss', $extract_begin_timecode);
  1732. // allows for exporting the entire timeline
  1733. if($extract_end_timecode !== false)
  1734. {
  1735. $end_position = (float) $this->formatTimecode($extract_end_timecode, $timecode_format, '%ss.%ms', $frames_per_second);
  1736. // format the end timecode if the timecode format is not already ok.
  1737. if($timecode_format !== '%hh:%mm:%ss.%ms')
  1738. {
  1739. $extract_end_timecode = $this->formatTimecode($extract_end_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1740. }
  1741. $this->addCommand('-t', $end_position-$begin_position);
  1742. }
  1743. return true;
  1744. }
  1745. /**
  1746. * Extracts frames from a video.
  1747. * (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.
  1748. * 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
  1749. * 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
  1750. * 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
  1751. * 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,
  1752. * say 1 second in you should set $extract_begin_timecode='00:00:01' and set $extract_end_timecode='00:00:01'.)
  1753. *
  1754. * @access public
  1755. * @param string $extract_begin_timecode A timecode (hh:mm:ss.fn - you can change the timecode format by changing the $timecode_format param
  1756. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info)
  1757. * @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
  1758. * it obeys the formatting of PHPVideoToolkit::formatTimecode(), see below for more info), or false
  1759. * if all frames from the begin timecode are to be exported. (Boolean added by Matthias. Thanks. 12th March 2007)
  1760. * @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
  1761. * will be automagically gained from PHPVideoToolkit::fileGetInfo();
  1762. * @param boolean|integer $frame_limit Frame limiter. If set to false then all the frames will be exported from the given time codes, however
  1763. * 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
  1764. * $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
  1765. * 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
  1766. * then you set $frame_limit=10. You could of course alter the timecode to reflect you desired frame number, however there are situations
  1767. * when a shortcut such as this is useful and necessary.
  1768. * @param integer $timecode_format The format of the $extract_begin_timecode and $extract_end_timecode timecodes are being given in.
  1769. * default '%hh:%mm:%ss'
  1770. * - %hh (hours) representative of hours
  1771. * - %mm (minutes) representative of minutes
  1772. * - %ss (seconds) representative of seconds
  1773. * - %fn (frame number) representative of frames (of the current second, not total frames)
  1774. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  1775. * - %ft (frames total) representative of total frames (ie frame number)
  1776. * - %st (seconds total) representative of total seconds (rounded).
  1777. * - %sf (seconds floored) representative of total seconds (floored).
  1778. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  1779. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  1780. * @param boolean $check_frames_exist Determines if a frame exists check should be made to ensure the timecode given by $extract_end_timecode
  1781. * actually exists.
  1782. */
  1783. 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)
  1784. {
  1785. // are we autoguessing the frame rate?
  1786. if($frames_per_second === false || $check_frames_exist)
  1787. {
  1788. // get the file info, will exit if no input has been set
  1789. $info = $this->getFileInfo();
  1790. if($info === false || isset($info['video']) === false)
  1791. {
  1792. // the input has not returned any video data so the frame rate can not be guessed
  1793. return $this->_raiseError('extractFrame_video_frame_rate_404');
  1794. }
  1795. $frames_per_second = $info['video']['frame_rate'];
  1796. }
  1797. // check if frame exists
  1798. if($check_frames_exist)
  1799. {
  1800. if($info['video']['frame_count'] < $this->formatTimecode($extract_end_timecode, $timecode_format, '%ft', $frames_per_second))
  1801. {
  1802. // the input has not returned any video data so the frame rate can not be guessed
  1803. return $this->_raiseError('extractFrames_video_end_frame_count');
  1804. }
  1805. else if($extract_end_timecode !== false && $info['video']['frame_count'] < $this->formatTimecode($extract_begin_timecode, $timecode_format, '%ft', $frames_per_second))
  1806. {
  1807. // the input has not returned any video data so the frame rate can not be guessed
  1808. return $this->_raiseError('extractFrames_video_begin_frame_count');
  1809. }
  1810. }
  1811. // disable audio output
  1812. $this->disableAudio();
  1813. // format the begin timecode if the timecode format is not already ok.
  1814. /*
  1815. if($timecode_format !== '%hh:%mm:%ss.%ms')
  1816. {
  1817. $extract_begin_timecode = $this->formatTimecode($extract_begin_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1818. }
  1819. */
  1820. $this->addCommand('-ss', $extract_begin_timecode);
  1821. // added by Matthias on 12th March 2007
  1822. // allows for exporting the entire timeline
  1823. if($extract_end_timecode !== false)
  1824. {
  1825. // format the end timecode if the timecode format is not already ok.
  1826. if($timecode_format !== '%hh:%mm:%ss.%ms')
  1827. {
  1828. $extract_end_timecode = $this->formatTimecode($extract_end_timecode, $timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1829. }
  1830. $this->addCommand('-t', $extract_end_timecode);
  1831. }
  1832. // set the output frame rate
  1833. $this->setVideoFrameRate($frames_per_second);
  1834. // do we need to limit the number of frames outputted?
  1835. if($frame_limit !== false)
  1836. {
  1837. $this->addCommand('-vframes', $frame_limit);
  1838. }
  1839. $this->_image_output_timecode_start = $extract_begin_timecode;
  1840. $this->_image_output_timecode_fps = $frames_per_second;
  1841. }
  1842. /**
  1843. * Extracts exactly one frame
  1844. *
  1845. * @access public
  1846. * @uses $toolkit->extractFrames
  1847. * @param string $frame_timecode A timecode (hh:mm:ss.fn) where fn is the frame number of that second
  1848. * @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
  1849. * the actual frame rate. It is recommended that it is left as false because an incorrect frame rate may produce unexpected results.
  1850. * @param integer $timecode_format The format of the $extract_begin_timecode and $extract_end_timecode timecodes are being given in.
  1851. * default '%hh:%mm:%ss'
  1852. * - %hh (hours) representative of hours
  1853. * - %mm (minutes) representative of minutes
  1854. * - %ss (seconds) representative of seconds
  1855. * - %fn (frame number) representative of frames (of the current second, not total frames)
  1856. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  1857. * - %ft (frames total) representative of total frames (ie frame number)
  1858. * - %st (seconds total) representative of total seconds (rounded).
  1859. * - %sf (seconds floored) representative of total seconds (floored).
  1860. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  1861. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  1862. * @param boolean $check_frame_exists Makes an explicit check to see if the frame exists, default = true.
  1863. * Thanks to Istvan Szakacs for suggesting this check. Note, to improve performance disable this check.
  1864. */
  1865. public function extractFrame($frame_timecode, $frames_per_second=false, $frame_timecode_format='%hh:%mm:%ss.%fn', $check_frame_exists=true)
  1866. {
  1867. // get the file info, will exit if no input has been set
  1868. if($check_frame_exists || $frames_per_second === false)
  1869. {
  1870. $info = $this->getFileInfo();
  1871. if($info === false || isset($info['video']) === false)
  1872. {
  1873. // the input has not returned any video data so the frame rate can not be guessed
  1874. return $this->_raiseError('extractFrame_video_info_404');
  1875. }
  1876. }
  1877. // are we autoguessing the frame rate?
  1878. if($frames_per_second === false)
  1879. {
  1880. if(isset($info['video']['frame_rate']) === false)
  1881. {
  1882. // the input has not returned any video data so the frame rate can not be guessed
  1883. return $this->_raiseError('extractFrame_video_frame_rate_404');
  1884. }
  1885. $frames_per_second = $info['video']['frame_rate'];
  1886. }
  1887. // check if frame exists
  1888. if($check_frame_exists)
  1889. {
  1890. if($info['video']['frame_count'] < $this->formatTimecode($frame_timecode, $frame_timecode_format, '%ft', $frames_per_second))
  1891. {
  1892. // the input has not returned any video data so the frame rate can not be guessed
  1893. return $this->_raiseError('extractFrame_video_frame_count');
  1894. }
  1895. }
  1896. // format the frame details if the timecode format is not already ok.
  1897. /*
  1898. if($frame_timecode_format !== '%hh:%mm:%ss.%ms')
  1899. $frame_timecode = $this->formatTimecode($frame_timecode, $frame_timecode_format, '%hh:%mm:%ss.%ms', $frames_per_second);
  1900. }
  1901. */
  1902. $this->_single_frame_extraction = 1;
  1903. // we will limit the number of frames produced so the desired frame is the last image
  1904. // this way we limit the cpu usage of ffmpeg
  1905. // Thanks to Istvan Szakacs for pointing out that ffmpeg can export frames using the -ss hh:mm:ss[.xxx]
  1906. // it has saved a lot of cpu intensive processes.
  1907. $this->extractFrames($frame_timecode, $frame_timecode, $frames_per_second, 1, '%hh:%mm:%ss.%ms', false);
  1908. // register the post tidy process
  1909. // $this->registerPostProcess('_extractFrameTidy', $this);
  1910. }
  1911. // /**
  1912. // * Tidies up after ffmpeg exports all frames from one second of video.
  1913. // *
  1914. // * @access public
  1915. // * @uses $toolkit->extractFrames
  1916. // * @param string $frame_timecode A timecode (hh:mm:ss.fn) where fn is the frame number of that second
  1917. // * @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
  1918. // * the actual frame rate. It is recommended that it is left as false because an incorrect frame rate may produce unexpected results.
  1919. // */
  1920. // protected function _extractFrameTidy(&$files)
  1921. // {
  1922. // $frame_number = 1;
  1923. // $frame_file = array();
  1924. // // print_r($files);
  1925. // foreach($files as $file=>$filename)
  1926. // {
  1927. // // print_R(array($this->_single_frame_extraction, $frame_number));
  1928. // if($this->_single_frame_extraction == $frame_number)
  1929. // {
  1930. // // leave this file alone as it is the required frame
  1931. // $frame_file[$file] = $filename;
  1932. // }
  1933. // else
  1934. // {
  1935. // // add the frame to the unlink files list
  1936. // array_push($this->_unlink_files, $file);
  1937. // }
  1938. // $frame_number += 1;
  1939. // }
  1940. // // print_r($frame_file);
  1941. // // update the files list
  1942. // $files = $frame_file;
  1943. // return true;
  1944. // }
  1945. /**
  1946. * Adds a watermark to the outputted files. This effects both video and image output.
  1947. *
  1948. * @access public
  1949. * @param string $watermark_url The absolute path to the watermark image.
  1950. * @param string $vhook The absolute path to the ffmpeg vhook watermark library.
  1951. * @param string $watermark_options Any additional options to supply to the vhook.
  1952. */
  1953. public function addWatermark($watermark_url, $vhook=PHPVIDEOTOOLKIT_FFMPEG_WATERMARK_VHOOK, $watermark_options=false)
  1954. {
  1955. // check to see if the ffmpeg binary has support for vhooking
  1956. if(!$this->hasVHookSupport())
  1957. {
  1958. return $this->_raiseError('addWatermark_vhook_disabled');
  1959. }
  1960. // does the file exist?
  1961. if(!is_file($watermark_url))
  1962. {
  1963. return $this->_raiseError('addWatermark_img_404', array('watermark'=>$watermark_url));
  1964. }
  1965. // determine which vhook library is being called and set appropriate input param
  1966. $file_input_switch = preg_match("/watermark.*/", $vhook) ? ' -f ' : ' -i ';
  1967. $this->addCommand('-vhook', $vhook.$file_input_switch.$watermark_url.($watermark_options !== false ? ' '.$watermark_options : ''));
  1968. }
  1969. /**
  1970. * Adds a watermark to the outputted image files using the PHP GD module.
  1971. * This effects only image output.
  1972. *
  1973. * @access public
  1974. * @param string $watermark_url The absolute path to the watermark image.
  1975. */
  1976. public function addGDWatermark($watermark_url, $options=array('x-offset'=>0, 'y-offset'=>0, 'position'=>'bottom-right'))
  1977. {
  1978. // does the file exist?
  1979. if(!is_file($watermark_url))
  1980. {
  1981. return $this->_raiseError('addWatermark_img_404', array('watermark'=>$watermark_url));
  1982. }
  1983. // save the watermark_url
  1984. $this->_watermark_url = $watermark_url;
  1985. $this->_watermark_options = array_merge(array('x-offset'=>0, 'y-offset'=>0, 'position'=>'bottom-right'), $options);
  1986. // register the post process
  1987. $this->registerPostProcess('_addGDWatermark', $this);
  1988. }
  1989. /**
  1990. * Adds watermark to any outputted images via GD instead of using vhooking.
  1991. *
  1992. * @access protected
  1993. * @param array $files An array of image files.
  1994. * @return array
  1995. */
  1996. protected function _addGDWatermark($files)
  1997. {
  1998. // create the watermark resource and give it alpha blending
  1999. $info = pathinfo($this->_watermark_url);
  2000. switch(strtolower($info['extension']))
  2001. {
  2002. case 'jpeg' :
  2003. case 'jpg' :
  2004. $watermark = imagecreatefromjpeg($this->_watermark_url);
  2005. break;
  2006. case 'gif' :
  2007. $watermark = imagecreatefromgif($this->_watermark_url);
  2008. break;
  2009. case 'png' :
  2010. $watermark = imagecreatefrompng($this->_watermark_url);
  2011. break;
  2012. default :
  2013. return false;
  2014. }
  2015. imagealphablending($watermark, true);
  2016. imagesavealpha($watermark, true);
  2017. // get the watermark dimensions
  2018. $watermark_width = imagesx($watermark);
  2019. $watermark_height = imagesy($watermark);
  2020. // $image = imagecreatetruecolor($watermark_width, $watermark_height);
  2021. // loop and watermark each file
  2022. $blended_files = array();
  2023. foreach($files as $file=>$filename)
  2024. {
  2025. // detect the file extension and create the resource from them appropriate function
  2026. $info = pathinfo($file);
  2027. $quality = $output_function = null;
  2028. switch(strtolower($info['extension']))
  2029. {
  2030. case 'jpeg' :
  2031. case 'jpg' :
  2032. $quality = 80;
  2033. $output_function = 'imagejpeg';
  2034. $image = imagecreatefromjpeg($file);
  2035. break;
  2036. case 'gif' :
  2037. $output_function = 'imagegif';
  2038. $image = imagecreatefromgif($file);
  2039. break;
  2040. case 'png' :
  2041. $quality = 9;
  2042. $output_function = 'imagepng';
  2043. $image = imagecreatefrompng($file);
  2044. break;
  2045. default :
  2046. continue 1;
  2047. }
  2048. // the dimensions will/should be the same for each image however still best to check
  2049. $image_width = imagesx($image);
  2050. $image_height = imagesy($image);
  2051. // calculate where to position the watermark
  2052. $dest_x = 0;
  2053. $dest_y = 0;
  2054. switch($this->_watermark_options['position'])
  2055. {
  2056. case 'top-left' :
  2057. $dest_x = 0;
  2058. $dest_y = 0;
  2059. break;
  2060. case 'top-middle' :
  2061. $dest_x = ($image_width-$watermark_width)/2;
  2062. $dest_y = 0;
  2063. break;
  2064. case 'top-right' :
  2065. $dest_x = $image_width-$watermark_width;
  2066. $dest_y = 0;
  2067. break;
  2068. case 'center-left' :
  2069. $dest_x = 0;
  2070. $dest_y = ($image_height-$watermark_height)/2;
  2071. break;
  2072. case 'center-middle' :
  2073. $dest_x = ($image_width-$watermark_width)/2;
  2074. $dest_y = ($image_height-$watermark_height)/2;
  2075. break;
  2076. case 'center-right' :
  2077. $dest_x = $image_width-$watermark_width;
  2078. $dest_y = ($image_height-$watermark_height)/2;
  2079. break;
  2080. case 'bottom-left' :
  2081. $dest_x = 0;
  2082. $dest_y = $image_height - $watermark_height;
  2083. break;
  2084. case 'bottom-middle' :
  2085. $dest_x = ($image_width-$watermark_width)/2;
  2086. $dest_y = $image_height - $watermark_height;
  2087. break;
  2088. case 'bottom-right' :
  2089. default :
  2090. $dest_x = $image_width-$watermark_width;
  2091. $dest_y = $image_height - $watermark_height;
  2092. break;
  2093. }
  2094. $dest_x += $this->_watermark_options['x-offset'];
  2095. $dest_y += $this->_watermark_options['y-offset'];
  2096. // copy the watermark to the new image
  2097. imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
  2098. // delete the old image
  2099. unlink($file);
  2100. // save the new image in place of the old
  2101. $output_function($image, $file, $quality);
  2102. // remove the image resouce
  2103. imagedestroy($image);
  2104. array_push($blended_files, $file);
  2105. }
  2106. // remove the watermark resource
  2107. imagedestroy($watermark);
  2108. return $blended_files;
  2109. }
  2110. // /**
  2111. // * This will overlay an audio file over the top of a video file
  2112. // **/
  2113. // public function overlayAudio($audio_file)
  2114. // {
  2115. // $this->addCommand('-newaudio', '');
  2116. // }
  2117. /**
  2118. * This will adjust the audio volume.
  2119. *
  2120. * @access public
  2121. * @param integer $vol 256 = normal
  2122. **/
  2123. public function adjustVolume($vol=256)
  2124. {
  2125. $this->addCommand('-vol', '');
  2126. }
  2127. /**
  2128. * This process will combine the original input video with the video specified by this function.
  2129. * This function accepts more than one video as arguments. They will be added in order of the arguments.
  2130. * ie. input_video -> video1 -> video2 etc
  2131. * The process of doing this can take a long time as each incoming video has to be first converted
  2132. * into a format that accepts joining. The default joining codec is "mpg". However for almost lossless
  2133. * quality you can use the "yuv4mpegpipe" format. This is of course dependent upon your ffmpeg binary.
  2134. * You can check to see if you server supports yuv4mpegpipe by typing "ffmpeg -formats" into the
  2135. * command line. If you want to use the yuv4mpegpipe format you can add the flag, FFMPEG_USE_HQ_JOIN to the
  2136. * end of the video inputs. WARNING: High Quality joins will take longer to process. (well duh!)
  2137. *
  2138. * @access public
  2139. * @param $video1, $video2, $video3... $video(n) Paths of videos to attach to the input video.
  2140. * @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.
  2141. */
  2142. public function addVideo()
  2143. {
  2144. $videos = func_get_args();
  2145. $videos_length = count($videos);
  2146. // is last arg the hq join flag
  2147. // check to see if a starter file has been added, if not set the input as an array
  2148. if($this->_input_file === null)
  2149. {
  2150. $this->_input_file = array();
  2151. }
  2152. // if the input file is already set as a string that means as start file has been added so absorb into the input array
  2153. else if(is_string($this->_input_file))
  2154. {
  2155. $this->_input_file = array($this->_input_file);
  2156. }
  2157. foreach($videos as $key=>$file)
  2158. {
  2159. if(!preg_match('/\%([0-9]+)d/', $file) && strpos($file, '%d') === false && !is_file($file))
  2160. {
  2161. // input file not valid
  2162. return $this->_raiseError('addVideo_file_404', array('file'=>$file));
  2163. //<- exits
  2164. }
  2165. array_push($this->_input_file, $file);
  2166. // array_push($this->_input_file, escapeshellarg($file));
  2167. }
  2168. }
  2169. /**
  2170. * @access public
  2171. * @uses addVideo()
  2172. */
  2173. public function addVideos()
  2174. {
  2175. $videos = func_get_args();
  2176. call_user_func_array(array(&$this, 'addVideo'), $videos);
  2177. }
  2178. /**
  2179. * Sets the output.
  2180. *
  2181. * @access public
  2182. * @param string $output_directory The directory to output the command output to
  2183. * @param string $output_name The filename to output to.
  2184. * (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
  2185. * to contain '%d'. '%d' is replaced by the image number. Thus entering setting output_name $output_name='img%d.jpg' will output
  2186. * 'img1.jpg', 'img2.jpg', etc... However 'img%03d.jpg' generates `img001.jpg', `img002.jpg', etc...)
  2187. * @param boolean $overwrite_mode Accepts one of the following class constants
  2188. * - PHPVideoToolkit::OVERWRITE_FAIL - This produces an error if there is a file conflict and the processing is halted.
  2189. * - PHPVideoToolkit::OVERWRITE_PRESERVE - This continues with the processing but no file overwrite takes place. The processed file is left in the temp directory
  2190. * for you to manually move.
  2191. * - PHPVideoToolkit::OVERWRITE_EXISTING - This will replace any existing files with the freshly processed ones.
  2192. * - PHPVideoToolkit::OVERWRITE_UNIQUE - This will appended every output with a unique hash so that the filesystem is preserved.
  2193. * @return boolean false on error encountered, true otherwise
  2194. */
  2195. public function setOutput($output_directory, $output_name, $overwrite_mode=PHPVideoToolkit::OVERWRITE_FAIL)
  2196. {
  2197. // check if directoy exists
  2198. if(!is_dir($output_directory))
  2199. {
  2200. return $this->_raiseError('setOutput_output_dir_404', array('dir'=>$output_directory));
  2201. //<- exits
  2202. }
  2203. // check if directory is writeable
  2204. if(!is_writable($output_directory))
  2205. {
  2206. return $this->_raiseError('setOutput_output_dir_writable', array('dir'=>$output_directory));
  2207. //<- exits
  2208. }
  2209. $process_name = '';
  2210. // check to see if a output delimiter is set
  2211. $has_d = preg_match('/\%([0-9]+)d/', $output_name) || strpos($output_name, '%d') !== false;
  2212. if($has_d)
  2213. {
  2214. return $this->_raiseError('setOutput_%d_depreciated');
  2215. //<- exits
  2216. }
  2217. else
  2218. {
  2219. // determine if the extension is an image. If it is then we will be extracting frames so check for %d
  2220. $output_name_info = pathinfo($output_name);
  2221. $is_image = in_array(strtolower($output_name_info['extension']), array('jpg', 'jpeg', 'png'));
  2222. $is_gif = strtolower($output_name_info['extension']) === 'gif';
  2223. // NOTE: for now we'll just stick to the common image formats, SUBNOTE: gif is ignore because ffmpeg can create animated gifs
  2224. if($this->_single_frame_extraction !== null && strpos($output_name, '%timecode') === false && !(preg_match('/\%index/', $output_name) || strpos($output_name, '%index') !== false) && $is_image)
  2225. {
  2226. //return $this->_raiseError('setOutput_%_missing');
  2227. //<- exits
  2228. }
  2229. $process_name = '.'.$output_name_info['extension'];
  2230. if($is_image || ($this->_single_frame_extraction !== null && $is_gif))
  2231. {
  2232. $process_name = '-%12d'.$process_name;
  2233. }
  2234. }
  2235. // set the output address
  2236. $this->_output_address = $output_directory.$output_name;
  2237. // set the processing address in the temp folder so it does not conflict with any other conversions
  2238. $this->_process_address = $this->_tmp_directory.$this->unique().$process_name;
  2239. $this->_overwrite_mode = $overwrite_mode;
  2240. return true;
  2241. }
  2242. /**
  2243. * Sets a constant quality value to the encoding. (but a variable bitrate)
  2244. *
  2245. * @param integer $quality The quality to adhere to. 100 is highest quality, 1 is the lowest quality
  2246. */
  2247. public function setConstantQuality($quality)
  2248. {
  2249. // interpret quality into ffmpeg value
  2250. $quality = 31 - round(($quality/100) * 31);
  2251. if($quality > 31)
  2252. {
  2253. $quality = 31;
  2254. }
  2255. else if($quality < 1)
  2256. {
  2257. $quality = 1;
  2258. }
  2259. $this->addCommand('-qscale', $quality);
  2260. }
  2261. /**
  2262. * Translates a number of seconds to a timecode.
  2263. * NOTE: this is now a depreciated, use formatSeconds() instead.
  2264. *
  2265. * @depreciated Use formatSeconds() instead.
  2266. * @access public
  2267. * @uses PHPVideoToolkit::formatSeconds()
  2268. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2269. */
  2270. public function secondsToTimecode($input_seconds=0)
  2271. {
  2272. return $this->formatSeconds($input_seconds, '%hh:%mm:%ss');
  2273. }
  2274. /**
  2275. * Translates a timecode to the number of seconds.
  2276. * NOTE: this is now a depreciated, use formatTimecode() instead.
  2277. *
  2278. * @depreciated Use formatTimecode() instead.
  2279. * @access public
  2280. * @uses PHPVideoToolkit::formatTimecode()
  2281. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2282. */
  2283. public function timecodeToSeconds($input_timecode='00:00:00')
  2284. {
  2285. return $this->formatTimecode($input_timecode, '%hh:%mm:%ss', '%st');
  2286. }
  2287. /**
  2288. * Translates a number of seconds to a timecode.
  2289. *
  2290. * @access public
  2291. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2292. * @param integer $return_format The format of the timecode to return. The default is
  2293. * default '%hh:%mm:%ss'
  2294. * - %hh (hours) representative of hours
  2295. * - %mm (minutes) representative of minutes
  2296. * - %ss (seconds) representative of seconds
  2297. * - %fn (frame number) representative of frames (of the current second, not total frames)
  2298. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  2299. * - %ft (frames total) representative of total frames (ie frame number)
  2300. * - %st (seconds total) representative of total seconds (rounded).
  2301. * - %sf (seconds floored) representative of total seconds (floored).
  2302. * - %sc (seconds ceiled) representative of total seconds (ceiled).
  2303. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  2304. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  2305. * @param mixed|boolean|integer $frames_per_second The number of frames per second to translate for. If left false
  2306. * the class automagically gets the fps from PHPVideoToolkit::getFileInfo(), but the input has to be set
  2307. * first for this to work properly.
  2308. * @param boolean $use_smart_values Default value is true, if a format is found (ie %ss - secs) but no higher format (ie %mm - mins)
  2309. * is found then if $use_smart_values is true the value of of the format will be totaled.
  2310. * @return string|integer Returns the timecode, but if $frames_per_second is not set and a frame rate lookup is required
  2311. * but can't be reached then -1 will be returned.
  2312. */
  2313. public function formatSeconds($input_seconds, $return_format='%hh:%mm:%ss', $frames_per_second=false, $use_smart_values=true)
  2314. {
  2315. $timestamp = mktime(0, 0, $input_seconds, 0, 0);
  2316. $floored = floor($input_seconds);
  2317. $hours = $input_seconds > 3600 ? floor($input_seconds/3600) : 0;
  2318. $mins = date('i', $timestamp);
  2319. $searches = array();
  2320. $replacements = array();
  2321. // these ones are the simple replacements
  2322. // replace the hours
  2323. $using_hours = strpos($return_format, '%hh') !== false;
  2324. if($using_hours)
  2325. {
  2326. array_push($searches, '%hh');
  2327. array_push($replacements, $hours);
  2328. }
  2329. // replace the minutes
  2330. $using_mins = strpos($return_format, '%mm') !== false;
  2331. if($using_mins)
  2332. {
  2333. array_push($searches, '%mm');
  2334. // check if hours are being used, if not and hours are required enable smart minutes
  2335. if($use_smart_values === true && !$using_hours && $hours > 0)
  2336. {
  2337. $value = ($hours * 60) + $mins;
  2338. }
  2339. else
  2340. {
  2341. $value = $mins;
  2342. }
  2343. array_push($replacements, $value);
  2344. }
  2345. // replace the seconds
  2346. if(strpos($return_format, '%ss') !== false)
  2347. {
  2348. // check if hours are being used, if not and hours are required enable smart minutes
  2349. if($use_smart_values === true && !$using_mins && !$using_hours && $hours > 0)
  2350. {
  2351. $mins = ($hours * 60) + $mins;
  2352. }
  2353. // check if mins are being used, if not and hours are required enable smart minutes
  2354. if($use_smart_values === true && !$using_mins && $mins > 0)
  2355. {
  2356. $value = ($mins * 60) + date('s', $timestamp);
  2357. }
  2358. else
  2359. {
  2360. $value = date('s', $timestamp);
  2361. }
  2362. array_push($searches, '%ss');
  2363. array_push($replacements, $value);
  2364. }
  2365. // replace the milliseconds
  2366. if(strpos($return_format, '%ms') !== false)
  2367. {
  2368. $milli = round($input_seconds - $floored, 3);
  2369. $milli = substr($milli, 2);
  2370. $milli = empty($milli) ? '0' : $milli;
  2371. array_push($searches, '%ms');
  2372. array_push($replacements, $milli);
  2373. }
  2374. // replace the total seconds (rounded)
  2375. if(strpos($return_format, '%st') !== false)
  2376. {
  2377. array_push($searches, '%st');
  2378. array_push($replacements, round($input_seconds));
  2379. }
  2380. // replace the total seconds (floored)
  2381. if(strpos($return_format, '%sf') !== false)
  2382. {
  2383. array_push($searches, '%sf');
  2384. array_push($replacements, floor($input_seconds));
  2385. }
  2386. // replace the total seconds (ceiled)
  2387. if(strpos($return_format, '%sc') !== false)
  2388. {
  2389. array_push($searches, '%sc');
  2390. array_push($replacements, ceil($input_seconds));
  2391. }
  2392. // replace the total seconds
  2393. if(strpos($return_format, '%mt') !== false)
  2394. {
  2395. array_push($searches, '%mt');
  2396. array_push($replacements, round($input_seconds, 3));
  2397. }
  2398. // these are the more complicated as they depend on $frames_per_second / frames per second of the current input
  2399. $has_frames = strpos($return_format, '%fn') !== false;
  2400. $has_total_frames = strpos($return_format, '%ft') !== false;
  2401. if($has_frames || $has_total_frames)
  2402. {
  2403. // if the fps is false then we must automagically detect it from the input file
  2404. if($frames_per_second === false)
  2405. {
  2406. $info = $this->getFileInfo();
  2407. // check the information has been received
  2408. if($info === false || (isset($info['video']) === false || isset($info['video']['frame_rate']) === false))
  2409. {
  2410. // fps cannot be reached so return -1
  2411. return -1;
  2412. }
  2413. $frames_per_second = $info['video']['frame_rate'];
  2414. }
  2415. // replace the frames
  2416. $excess_frames = false;
  2417. if($has_frames)
  2418. {
  2419. $excess_frames = ceil(($input_seconds - $floored) * $frames_per_second);
  2420. array_push($searches, '%fn');
  2421. array_push($replacements, $excess_frames);
  2422. }
  2423. // replace the total frames (ie frame number)
  2424. if($has_total_frames)
  2425. {
  2426. $round_frames = $floored * $frames_per_second;
  2427. if(!$excess_frames)
  2428. {
  2429. $excess_frames = ceil(($input_seconds - $floored) * $frames_per_second);
  2430. }
  2431. array_push($searches, '%ft');
  2432. array_push($replacements, $round_frames + $excess_frames);
  2433. }
  2434. }
  2435. return str_replace($searches, $replacements, $return_format);
  2436. }
  2437. /**
  2438. * Translates a timecode to the number of seconds
  2439. *
  2440. * @access public
  2441. * @param integer $input_seconds The number of seconds you want to calculate the timecode for.
  2442. * @param integer $input_format The format of the timecode is being given in.
  2443. * default '%hh:%mm:%ss'
  2444. * - %hh (hours) representative of hours
  2445. * - %mm (minutes) representative of minutes
  2446. * - %ss (seconds) representative of seconds
  2447. * - %fn (frame number) representative of frames (of the current second, not total frames)
  2448. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  2449. * - %ft (frames total) representative of total frames (ie frame number)
  2450. * - %st (seconds total) representative of total seconds (rounded).
  2451. * - %sf (seconds floored) representative of total seconds (floored).
  2452. * - %sc (seconds ceiled) representative of total seconds (ceiled).
  2453. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  2454. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  2455. * @param integer $return_format The format of the timecode to return. The default is
  2456. * default '%ts'
  2457. * - %hh (hours) representative of hours
  2458. * - %mm (minutes) representative of minutes
  2459. * - %ss (seconds) representative of seconds
  2460. * - %fn (frame number) representative of frames (of the current second, not total frames)
  2461. * - %ms (milliseconds) representative of milliseconds (of the current second, not total milliseconds) (rounded to 3 decimal places)
  2462. * - %ft (frames total) representative of total frames (ie frame number)
  2463. * - %st (seconds total) representative of total seconds (rounded).
  2464. * - %sf (seconds floored) representative of total seconds (floored).
  2465. * - %sc (seconds ceiled) representative of total seconds (ceiled).
  2466. * - %mt (milliseconds total) representative of total milliseconds. (rounded to 3 decimal places)
  2467. * Thus you could use an alternative, '%hh:%mm:%ss:%ms', or '%hh:%mm:%ss' dependent on your usage.
  2468. * @param mixed|boolean|integer $frames_per_second The number of frames per second to translate for. If left false
  2469. * the class automagically gets the fps from PHPVideoToolkit::getFileInfo(), but the input has to be set
  2470. * first for this to work properly.
  2471. * @param boolean $use_smart_values Default value is true, if a format is found (ie %ss - secs) but no higher format (ie %mm - mins)
  2472. * is found then if $use_smart_values is true the value of of the format will be totaled.
  2473. * @return float Returns the value of the timecode in seconds.
  2474. */
  2475. public function formatTimecode($input_timecode, $input_format='%hh:%mm:%ss', $return_format='%ts', $frames_per_second=false, $use_smart_values=true)
  2476. {
  2477. // first we must get the timecode into the current seconds
  2478. $input_quoted = preg_quote($input_format);
  2479. $placeholders = array('%hh', '%mm', '%ss', '%fn', '%ms', '%ft', '%st', '%sf', '%sc', '%mt');
  2480. $seconds = 0;
  2481. $input_regex = str_replace($placeholders, '([0-9]+)', preg_quote($input_format));
  2482. preg_match('/'.$input_regex.'/', $input_timecode, $matches);
  2483. // work out the sort order for the placeholders
  2484. $sort_table = array();
  2485. foreach($placeholders as $key=>$placeholder)
  2486. {
  2487. if(($pos = strpos($input_format, $placeholder)) !== false)
  2488. {
  2489. $sort_table[$pos] = $placeholder;
  2490. }
  2491. }
  2492. ksort($sort_table);
  2493. // check to see if frame related values are in the input
  2494. $has_frames = strpos($input_format, '%fn') !== false;
  2495. $has_total_frames = strpos($input_format, '%ft') !== false;
  2496. if($has_frames || $has_total_frames)
  2497. {
  2498. // if the fps is false then we must automagically detect it from the input file
  2499. if($frames_per_second === false)
  2500. {
  2501. $info = $this->getFileInfo();
  2502. // check the information has been received
  2503. if($info === false || (isset($info['duration']) === false || isset($info['duration']['timecode']['frames']['frame_rate']) === false))
  2504. {
  2505. // fps cannot be reached so return -1
  2506. return -1;
  2507. }
  2508. $frames_per_second = $info['duration']['timecode']['frames']['frame_rate'];
  2509. }
  2510. }
  2511. // increment the seconds with each placeholder value
  2512. $key = 1;
  2513. foreach($sort_table as $placeholder)
  2514. {
  2515. if(isset($matches[$key]) === false)
  2516. {
  2517. break;
  2518. }
  2519. $value = $matches[$key];
  2520. switch($placeholder)
  2521. {
  2522. // time related ones
  2523. case '%hh' :
  2524. $seconds += $value * 3600;
  2525. break;
  2526. case '%mm' :
  2527. $seconds += $value * 60;
  2528. break;
  2529. case '%ss' :
  2530. case '%sf' :
  2531. case '%sc' :
  2532. $seconds += $value;
  2533. break;
  2534. case '%ms' :
  2535. $seconds += floatval('0.'.$value);
  2536. break;
  2537. case '%st' :
  2538. case '%mt' :
  2539. $seconds = $value;
  2540. break 1;
  2541. break;
  2542. // frame related ones
  2543. case '%fn' :
  2544. $seconds += $value/$frames_per_second;
  2545. break;
  2546. case '%ft' :
  2547. $seconds = $value/$frames_per_second;
  2548. break 1;
  2549. break;
  2550. }
  2551. $key += 1;
  2552. }
  2553. // then we just format the seconds
  2554. return $this->formatSeconds($seconds, $return_format, $frames_per_second, $use_smart_values);
  2555. }
  2556. /**
  2557. * This is a protected function that joins multiple input sources into one source before
  2558. * the final processing takes place. All videos are temporarily converted into mpg for
  2559. * joining.
  2560. *
  2561. * PLEASE NOTE. This process is experimental an might not work on all systems.
  2562. *
  2563. * @access protected
  2564. * @param boolean $log
  2565. */
  2566. protected function _joinInput($log)
  2567. {
  2568. die('INPUT CANNOT YET BE JOINED.');
  2569. // ---- ffmpeg works
  2570. /*
  2571. mkfifo /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/intermediate1.mpg
  2572. mkfifo /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/intermediate2.mpg
  2573. ffmpeg -i /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/MOV02820.MPG -sameq -y /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/intermediate1.mpg < /dev/null &
  2574. ffmpeg -i /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/MOV02832.MPG -sameq -y /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/intermediate2.mpg < /dev/null &
  2575. cat /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/intermediate1.mpg /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/intermediate2.mpg |\
  2576. ffmpeg -f mpeg -i - -sameq -vcodec flv -acodec mp3 -ar 22050 /Users/ollie/Sites/@Projects/ffmpeg/checkout/root/examples/tmp/output.flv
  2577. */
  2578. // ---- mencoder works
  2579. /*
  2580. PHPVIDEOTOOLKIT_MENCODER_BINARY.' -oac copy -ovc copy -idx -o '.$temp_file.' '.implode(' ', $this->_input_file);
  2581. */
  2582. // run a libmp3lame check as it require different mp3 codec
  2583. $audio_codec = 'mp3';
  2584. $info = $this->getFFmpegInfo(true);
  2585. if(isset($info['binary']['configuration']) === true && in_array('--enable-libmp3lame', $info['binary']['configuration']) === true)
  2586. {
  2587. // $audio_codec = 'liblamemp3';
  2588. $audio_codec = 'libmp3lame';
  2589. }
  2590. // build commands
  2591. $temp_files = array();
  2592. $mkinfo_commands = array();
  2593. $ffmpeg_commands = array();
  2594. $cat_files = array();
  2595. $unique = $this->unique();
  2596. foreach($this->_input_file as $key=>$file)
  2597. {
  2598. $unique_name = $this->_tmp_directory.$unique.'-'.$key.'-temp.mpg';
  2599. $unique_name_escaped = escapeshellarg($unique_name);
  2600. $logfile1 = $this->_tmp_directory.$unique.'-'.$key.'-log1.log';
  2601. $logfile2 = $this->_tmp_directory.$unique.'-'.$key.'-log2.log';
  2602. array_push($mkinfo_commands, array('cmd'=> 'mkfifo '.$unique_name_escaped.($log ? ' &> '.$logfile1 : ''), 'logfile'=>$logfile1));
  2603. array_push($ffmpeg_commands, array('cmd'=> $this->_ffmpeg_binary.' -i '.escapeshellarg($file).' -acodec '.$audio_codec.' -sameq '.$unique_name_escaped.' < /dev/null '.($log ? '&> '.$logfile2 : '&'), 'logfile'=>$logfile2));
  2604. array_push($cat_files, $unique_name_escaped);
  2605. // array_push($this->_unlink_files, $unique_name);
  2606. if($log)
  2607. {
  2608. // array_push($this->_unlink_files, $logfile1);
  2609. // array_push($this->_unlink_files, $logfile2);
  2610. }
  2611. }
  2612. // start log
  2613. if($log)
  2614. {
  2615. $log_lines = array();
  2616. array_unshift($log_lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_join_gunk'), $this->_getMessage('ffmpeg_log_separator'));
  2617. }
  2618. // mkinfo for temp files
  2619. foreach($mkinfo_commands as $cmd)
  2620. {
  2621. // exec($cmd['cmd']);
  2622. echo($cmd['cmd']."\r\n");
  2623. if($log)
  2624. {
  2625. array_push($log_lines, '---------', trim(file_get_contents($cmd['logfile'])));
  2626. }
  2627. }
  2628. // extract data
  2629. foreach($ffmpeg_commands as $cmd)
  2630. {
  2631. // exec($cmd['cmd']);
  2632. echo($cmd['cmd']."\r\n");
  2633. if($log)
  2634. {
  2635. array_push($log_lines, trim(file_get_contents($cmd['logfile'])), '---------');
  2636. }
  2637. }
  2638. // join command
  2639. $unique = $this->unique();
  2640. $temp_join_file = $this->_tmp_directory.$unique.'-combined-joined.mpg';
  2641. $temp_join_file_escaped = escapeshellarg($temp_join_file);
  2642. $temp_process_file = $this->_tmp_directory.$unique.'-combined-temp.mpg';
  2643. $temp_process_file_escaped = escapeshellarg($temp_process_file);
  2644. $logfile = $this->_tmp_directory.$unique.'.log';
  2645. // command for use with cat mkinfo files
  2646. // exec('cat '.implode(' ', $cat_files).' |\
  2647. // '.PHPVIDEOTOOLKIT_FFMPEG_BINARY.' -f mpeg -i - -sameq -vcodec mpeg4 -acodec '.$audio_codec.' '.escapeshellarg($temp_process_file).($log ? ' &> '.$logfile : ''));
  2648. echo('cat '.implode(' ', $cat_files).' |\
  2649. '.$this->_ffmpeg_binary.' -f mpeg -i - -sameq -vcodec mpeg4 -acodec '.$audio_codec.' '.escapeshellarg($temp_process_file).($log ? ' &> '.$logfile : '')."\r\n");
  2650. // echo('cat '.implode(' ', $cat_files).' > '.$temp_join_file_escaped.'
  2651. // '.PHPVIDEOTOOLKIT_FFMPEG_BINARY.' -i '.$temp_join_file_escaped.' -sameq -vcodec mpeg4 -acodec '.$audio_codec.' '.$temp_process_file_escaped.($log ? ' &> '.$logfile : ''));
  2652. // exec('cat '.implode(' ', $cat_files).' > '.$temp_join_file_escaped.'
  2653. // '.PHPVIDEOTOOLKIT_FFMPEG_BINARY.' -i '.$temp_join_file_escaped.' -sameq -vcodec mpeg4 -acodec '.$audio_codec.' '.$temp_process_file_escaped.($log ? ' &> '.$logfile : ''));
  2654. if($log)
  2655. {
  2656. array_push($log_lines, trim(file_get_contents($logfile)));
  2657. array_push($this->_unlink_files, $logfile);
  2658. $this->_addToLog($log_lines, 'a+');
  2659. // print_r($log_lines);
  2660. }
  2661. // create a temp dir in the temp dir
  2662. // $temp_file = $this->_tmp_directory.$this->unique().'.'.array_pop(explode('.', $this->_process_address));
  2663. // print_r($temp_file);
  2664. $this->addCommand('-i', $temp_process_file);
  2665. // array_push($this->_unlink_files, $temp_process_file);
  2666. exit;
  2667. }
  2668. /**
  2669. * Checks to see if a given codec can be encoded by the current ffmpeg binary.
  2670. * @access public
  2671. * @param $codec string The shortcode for the codec to check for.
  2672. * @return boolean True if the codec can be encoded by ffmpeg, otherwise false.
  2673. */
  2674. public static function canCodecBeEncoded($type, $codec)
  2675. {
  2676. return self::validateCodec($codec, $type, 'encode');
  2677. }
  2678. /**
  2679. * Checks to see if a given codec can be decoded by the current ffmpeg binary.
  2680. * @access public
  2681. * @param $codec string The shortcode for the codec to check for.
  2682. * @return boolean True if the codec can be decoded by ffmpeg, otherwise false.
  2683. */
  2684. public static function canCodecBeDecoded($type, $codec)
  2685. {
  2686. return self::validateCodec($codec, $type, 'decode');
  2687. }
  2688. /**
  2689. * Checks to see if a given codec can be decoded/encoded by the current ffmpeg binary.
  2690. * @access public
  2691. * @param $codec string The shortcode for the codec to check for.
  2692. * @param $type string either 'video', 'audio', or 'subtitle'. The type of codec to check for.
  2693. * @param $method string 'encode' or 'decode', The method to check against the codec
  2694. * @return boolean True if the codec can be used with the given method by ffmpeg, otherwise false.
  2695. */
  2696. public static function validateCodec($codec, $type, $method)
  2697. {
  2698. // check to see if this is a static call
  2699. if(isset($this) === false)
  2700. {
  2701. $toolkit = new PHPVideoToolkit();
  2702. $info = $toolkit->getFFmpegInfo(true);
  2703. }
  2704. else
  2705. {
  2706. $info = $this->getFFmpegInfo(true);
  2707. }
  2708. 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;
  2709. }
  2710. /**
  2711. * Checks to see if a given format can be muxed by the current ffmpeg binary.
  2712. * @access public
  2713. * @param $format string The shortcode for the codec to check for.
  2714. * @return boolean True if the codec can be encoded by ffmpeg, otherwise false.
  2715. */
  2716. public static function canFormatBeMuxed($format)
  2717. {
  2718. return self::validateFormat($format, 'mux');
  2719. }
  2720. /**
  2721. * Checks to see if a given format can be demuxed by the current ffmpeg binary.
  2722. * @access public
  2723. * @param $codec string The shortcode for the codec to check for.
  2724. * @return boolean True if the codec can be decoded by ffmpeg, otherwise false.
  2725. */
  2726. public static function canFormatBeDemuxed($format)
  2727. {
  2728. return self::validateFormat($format, 'demux');
  2729. }
  2730. /**
  2731. * Checks to see if a given codec can be decoded/encoded by the current ffmpeg binary.
  2732. * @access public
  2733. * @param $format string The shortcode for the codec to check for.
  2734. * @param $method string 'mux' or 'demux', The method to check against the format
  2735. * @return boolean True if the format can be used with the given method by ffmpeg, otherwise false.
  2736. */
  2737. public static function validateFormat($format, $method)
  2738. {
  2739. // check to see if this is a static call
  2740. if(isset($this) === false)
  2741. {
  2742. $toolkit = new PHPVideoToolkit();
  2743. $info = $toolkit->getFFmpegInfo(true);
  2744. }
  2745. else
  2746. {
  2747. $info = $this->getFFmpegInfo(true);
  2748. }
  2749. return isset($info['formats'][$format]) === true && isset($info['formats'][$format][$method]) === true ? $info['formats'][$format][$method] : false;
  2750. }
  2751. /**
  2752. * Returns the available formats.
  2753. * @access public
  2754. * @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.
  2755. * @return array An array of formats available to ffmpeg.
  2756. */
  2757. public static function getAvailableFormats($method=false)
  2758. {
  2759. // check to see if this is a static call
  2760. if(isset($this) === false)
  2761. {
  2762. $toolkit = new PHPVideoToolkit();
  2763. $info = $toolkit->getFFmpegInfo(true);
  2764. }
  2765. else
  2766. {
  2767. $info = $this->getFFmpegInfo(true);
  2768. }
  2769. // are we checking for particluar method?
  2770. $return_vals = array();
  2771. switch($method)
  2772. {
  2773. case false :
  2774. return array_keys($info['formats']);
  2775. case 'both' :
  2776. foreach ($info['formats'] as $id => $data)
  2777. {
  2778. if($data['muxing'] === true && $data['demuxing'] === true)
  2779. {
  2780. array_push($return_vals, $id);
  2781. }
  2782. }
  2783. break;
  2784. case 'muxing' :
  2785. foreach ($info['formats'] as $id => $data)
  2786. {
  2787. if($data['muxing'] === true)
  2788. {
  2789. array_push($return_vals, $id);
  2790. }
  2791. }
  2792. break;
  2793. case 'demuxing' :
  2794. foreach ($info['formats'] as $id => $data)
  2795. {
  2796. if($data['demuxing'] === true)
  2797. {
  2798. array_push($return_vals, $id);
  2799. }
  2800. }
  2801. break;
  2802. }
  2803. return $return_vals;
  2804. }
  2805. /**
  2806. * Returns the available codecs.
  2807. * @access public
  2808. * @param mixed $type The type of codec list to return, false (to return all codecs), or either 'audio', 'video', or 'subtitle'.
  2809. * @return array An array of codecs available to ffmpeg.
  2810. */
  2811. public static function getAvailableCodecs($type=false)
  2812. {
  2813. // check to see if this is a static call
  2814. if(isset($this) === false)
  2815. {
  2816. $toolkit = new PHPVideoToolkit();
  2817. $info = $toolkit->getFFmpegInfo(true);
  2818. }
  2819. else
  2820. {
  2821. $info = $this->getFFmpegInfo(true);
  2822. }
  2823. // are we checking for particluar method?
  2824. $return_vals = array();
  2825. if($type === false)
  2826. {
  2827. $video_keys = array_keys($info['codecs']['video']);
  2828. $audio_keys = array_keys($info['codecs']['audio']);
  2829. $subtitle_keys = array_keys($info['codecs']['subtitle']);
  2830. return array_merge($video_keys, $audio_keys, $subtitle_keys);
  2831. }
  2832. return isset($info['codecs'][$type]) === true ? array_keys($info['codecs'][$type]) : false;
  2833. }
  2834. /**
  2835. * Commits all the commands and executes the ffmpeg procedure. This will also attempt to validate any outputted files in order to provide
  2836. * some level of stop and check system.
  2837. *
  2838. * @access public
  2839. * @param $multi_pass_encode boolean Determines if multi (2) pass encoding should be used.
  2840. * @param $log boolean Determines if a log file of the results should be generated.
  2841. * @return mixed
  2842. * - false On error encountered.
  2843. * - PHPVideoToolkit::RESULT_OK (bool true) If the file has successfully been processed and moved ok to the output address
  2844. * - 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
  2845. * If this is the case you will manually need to move the processed file from the temp directory. You can
  2846. * get around this by settings the third argument from PHPVideoToolkit::setOutput(), $overwrite to true.
  2847. * - n (int) A positive integer is only returned when outputting a series of frame grabs from a movie. It dictates
  2848. * the total number of frames grabbed from the input video. You should also not however, that if a conflict exists
  2849. * with one of the filenames then this return value will not be returned, but PHPVideoToolkit::RESULT_OK_BUT_UNWRITABLE
  2850. * will be returned instead.
  2851. * Because of the mixed return value you should always go a strict evaluation of the returned value. ie
  2852. *
  2853. * $result = $toolkit->excecute();
  2854. * if($result === false)
  2855. * {
  2856. * // error
  2857. * }
  2858. * else if($result === PHPVideoToolkit::RESULT_OK_BUT_UNWRITABLE)
  2859. * {
  2860. * // ok but a manual move is required. The file to move can be it can be retrieved by $toolkit->getLastOutput();
  2861. * }
  2862. * else if($result === PHPVideoToolkit::RESULT_OK)
  2863. * {
  2864. * // everything is ok.
  2865. * }
  2866. */
  2867. public function execute($multi_pass_encode=false, $log=false)
  2868. {
  2869. // check for inut and output params
  2870. $has_placeholder = preg_match('/\%([0-9]+)index/', $this->_process_address) || (strpos($this->_process_address, '%index') === false && strpos($this->_process_address, '%timecode') === false);
  2871. if($this->_input_file === null && !$has_placeholder)
  2872. {
  2873. return $this->_raiseError('execute_input_404');
  2874. //<- exits
  2875. }
  2876. // check to see if the output address has been set
  2877. if($this->_process_address === null)
  2878. {
  2879. return $this->_raiseError('execute_output_not_set');
  2880. //<- exits
  2881. }
  2882. // check if temp dir is required and is writable
  2883. if(($multi_pass_encode || $log) && !is_writable($this->_tmp_directory))
  2884. {
  2885. return $this->_raiseError('execute_temp_unwritable');
  2886. //<- exits
  2887. }
  2888. if(($this->_overwrite_mode == self::OVERWRITE_PRESERVE || $this->_overwrite_mode == self::OVERWRITE_FAIL) && is_file($this->_process_address))
  2889. {
  2890. return $this->_raiseError('execute_overwrite_process');
  2891. //<- exits
  2892. }
  2893. // carry out some overwrite checks if required
  2894. $overwrite = '';
  2895. switch($this->_overwrite_mode)
  2896. {
  2897. case self::OVERWRITE_UNIQUE :
  2898. // insert a unique id into the output address (the process address already has one)
  2899. $unique = $this->unique();
  2900. $last_index = strrpos($this->_output_address, DS);
  2901. $this->_output_address = substr($this->_output_address, 0, $last_index+1).$unique.'-'.substr($this->_output_address, $last_index+1);
  2902. break;
  2903. case self::OVERWRITE_EXISTING :
  2904. // add an overwrite command to ffmpeg execution call
  2905. $overwrite = '-y ';
  2906. break;
  2907. case self::OVERWRITE_PRESERVE :
  2908. // do nothing as the preservation comes later
  2909. break;
  2910. case self::OVERWRITE_FAIL :
  2911. default :
  2912. // if the file should fail
  2913. if(!$has_placeholder && is_file($this->_output_address))
  2914. {
  2915. return $this->_raiseError('execute_overwrite_fail');
  2916. //<- exits
  2917. }
  2918. break;
  2919. }
  2920. $this->_timer_start = self::microtimeFloat();
  2921. // we have multiple inputs that require joining so convert them to a joinable format and join
  2922. if(is_array($this->_input_file))
  2923. {
  2924. $this->_joinInput($log);
  2925. }
  2926. // check to see if the format has been set and if it hasn't been set and the extension is a gif
  2927. // we need to add an extra argument to set the pix format.
  2928. $format = $this->hasCommand('-f');
  2929. if($format === false)
  2930. {
  2931. $extension = strtolower(array_pop(explode('.', $this->_input_file)));
  2932. if($extension === 'gif')
  2933. {
  2934. $this->addCommand('-pix_fmt', 'rgb24');
  2935. }
  2936. }
  2937. else if($format === self::FORMAT_GIF)
  2938. {
  2939. $this->addCommand('-pix_fmt', 'rgb24');
  2940. }
  2941. // check to see if an aspect ratio is set, if it is correct the width and heights to reflect that aspect ratio.
  2942. // This isn't strictly needed it is purely for informational purposes that this is done, because if the width is not
  2943. // inline with what is should be according to the aspect ratio ffmpeg will report the wrong final width and height
  2944. // when using it to lookup information about the file.
  2945. $ratio = $this->hasCommand('-aspect');
  2946. if($ratio !== false)
  2947. {
  2948. $size = $this->hasCommand('-s');
  2949. if($size === false)
  2950. {
  2951. $info = $this->getFileInfo();
  2952. if(isset($info['video']) === true && isset($info['video']['dimensions']) === true)
  2953. {
  2954. $size = $info['video']['dimensions']['width'].'x'.$info['video']['dimensions']['height'];
  2955. }
  2956. }
  2957. if($size !== false)
  2958. {
  2959. $dim = explode('x', substr($size, 1, -1));
  2960. if(($boundry = strpos($ratio, ':')) !== false)
  2961. {
  2962. $ratio = substr($ratio, 1, $boundry-1)/substr($ratio, $boundry+1, -1);
  2963. $new_width = round($dim[1]*$ratio);
  2964. // make sure new width is an even number
  2965. $ceiled = ceil($new_width);
  2966. $new_width = $ceiled % 2 !== 0 ? floor($new_width) : $ceiled;
  2967. if($new_width != $dim[0])
  2968. {
  2969. $this->setVideoDimensions($new_width, $dim[1]);
  2970. }
  2971. }
  2972. else if(strpos($ratio, '.') !== false)
  2973. {
  2974. $ratio = floatval($ratio);
  2975. $new_width = $dim[1]*$ratio;
  2976. // make sure new width is an even number
  2977. $ceiled = ceil($new_width);
  2978. $new_width = $ceiled % 2 !== 0 ? floor($new_width) : $ceiled;
  2979. if($new_width != $dim[0])
  2980. {
  2981. $this->setVideoDimensions($new_width, $dim[1]);
  2982. }
  2983. }
  2984. }
  2985. }
  2986. // add the input file command to the mix
  2987. $this->addCommand('-i', $this->_input_file);
  2988. // if multi pass encoding is enabled add the commands and logfile
  2989. if($multi_pass_encode)
  2990. {
  2991. $multi_pass_file = $this->_tmp_directory.$this->unique().'-multipass';
  2992. $this->addCommand('-pass', 1);
  2993. $this->addCommand('-passlogfile', $multi_pass_file);
  2994. }
  2995. // combine all the output commands
  2996. $command_string = $this->_combineCommands();
  2997. // prepare the command suitable for exec
  2998. // the input and overwrite commands have specific places to be set so they have to be added outside of the combineCommands function
  2999. $exec_string = $this->_prepareCommand($this->_ffmpeg_binary, $command_string, $overwrite.$this->_process_address);
  3000. // $exec_string = $this->_prepareCommand(PHPVIDEOTOOLKIT_FFMPEG_BINARY, '-i '.$this->_commands['-i'].' '.$command_string, $overwrite.escapeshellcmd($this->_process_address));
  3001. if($log)
  3002. {
  3003. $this->_log_file = $this->_tmp_directory.$this->unique().'.info';
  3004. array_push($this->_unlink_files, $this->_log_file);
  3005. }
  3006. // execute the command
  3007. // $exec_string = $exec_string.' 2>&1';// &> '.$this->_log_file;
  3008. $buffer = self::_captureExecBuffer($exec_string, $this->_tmp_directory);
  3009. // exec($exec_string, $buffer);
  3010. if($log)
  3011. {
  3012. $this->_addToLog($buffer, 'a+');
  3013. }
  3014. // track the processed command by adding it to the class
  3015. array_unshift($this->_processed, $exec_string);
  3016. // scan buffer for any errors
  3017. $last_line = $buffer[count($buffer)-1];
  3018. if(preg_match('/(.*)(Unsupported codec|Error while opening)(.*)/s', $last_line, $error_matches) > 0)
  3019. {
  3020. $type = $error_matches[2];
  3021. switch($error_matches[2])
  3022. {
  3023. case 'Unsupported codec' :
  3024. break;
  3025. case 'Error while opening' :
  3026. break;
  3027. }
  3028. $stream = 'could be with either the audio or video codec';
  3029. if(preg_match('/#0.(0|1)/', $last_line, $stream_matches) > 0)
  3030. {
  3031. $stream = $stream_matches[1] === '0' ? 'is with the video codec' : 'is with the audio codec';
  3032. }
  3033. // add the error to the log file
  3034. if($log)
  3035. {
  3036. $this->_logResult('execute_ffmpeg_return_error', array('input'=>$this->_input_file, 'type'=>$type, 'message'=>$error_matches[0], 'stream'=>$stream));
  3037. }
  3038. return $this->_raiseError('execute_ffmpeg_return_error', array('input'=>$this->_input_file, 'type'=>$type, 'message'=>$error_matches[0], 'stream'=>$stream));
  3039. }
  3040. // create the multiple pass encode
  3041. if($multi_pass_encode)
  3042. {
  3043. $pass2_exc_string = str_replace('-pass '.escapeshellarg(1), '-pass '.escapeshellarg(2), $exec_string);
  3044. $buffer = self::_captureExecBuffer($pass2_exc_string, $this->_tmp_directory);
  3045. // exec($pass2_exc_string, $buffer);
  3046. if($log)
  3047. {
  3048. $this->_addToLog($buffer, 'a+');
  3049. }
  3050. $this->_processed[0] = array($this->_processed[0], $pass2_exc_string);
  3051. // tidy up the multipass log file
  3052. array_push($this->_unlink_files, $multi_pass_file.'-0.log');
  3053. // scan buffer for any errors
  3054. $last_line = $buffer[count($buffer)-1];
  3055. if(preg_match('/(.*)(Unsupported codec|Error while opening)(.*)/s', $last_line, $error_matches) > 0)
  3056. {
  3057. $type = $error_matches[2];
  3058. switch($error_matches[2])
  3059. {
  3060. case 'Unsupported codec' :
  3061. break;
  3062. case 'Error while opening' :
  3063. break;
  3064. }
  3065. $stream = 'could be with either the audio or video codec';
  3066. if(preg_match('/#0.(0|1)/', $last_line, $stream_matches) > 0)
  3067. {
  3068. $stream = $stream_matches[1] === '0' ? 'is with the video codec' : 'is with the audio codec';
  3069. }
  3070. // add the error to the log file
  3071. if($log)
  3072. {
  3073. $this->_logResult('execute_ffmpeg_return_error_multipass', array('input'=>$this->_input_file, 'type'=>$type, 'message'=>$error_matches[0], 'stream'=>$stream));
  3074. }
  3075. return $this->_raiseError('execute_ffmpeg_return_error_multipass', array('input'=>$this->_input_file, 'type'=>$type, 'message'=>$error_matches[0], 'stream'=>$stream));
  3076. }
  3077. }
  3078. // keep track of the time taken
  3079. $execution_time = self::microtimeFloat() - $this->_timer_start;
  3080. array_unshift($this->_timers, $execution_time);
  3081. // add the exec string to the log file
  3082. if($log)
  3083. {
  3084. $lines = $this->_processed[0];
  3085. if(!is_array($lines))
  3086. {
  3087. $lines = array($lines);
  3088. }
  3089. // array_unshift($lines, $exec_string);
  3090. array_unshift($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_command'), $this->_getMessage('ffmpeg_log_separator'));
  3091. // if($multi_pass_encode)
  3092. // {
  3093. // array_unshift($lines, $pass2_exc_string);
  3094. // }
  3095. array_unshift($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_gunk'), $this->_getMessage('ffmpeg_log_separator'));
  3096. $this->_addToLog($lines, 'a+');
  3097. }
  3098. // must validate a series of outputed items
  3099. // detect if the output address is a sequence output
  3100. if(preg_match('/\%([0-9]+)d/', $this->_process_address, $d_matches) || strpos($this->_process_address, '%d') !== false)
  3101. {
  3102. // get the path details
  3103. $process_info = pathinfo($this->_process_address);
  3104. $output_info = pathinfo($this->_output_address);
  3105. $pad_amount = intval($d_matches[1]);
  3106. // print_r(array($process_info, $output_info));
  3107. // get the %index padd amounts
  3108. $has_preg_index = preg_match('/\%([0-9]+)index/', $output_info['basename'], $index_matches);
  3109. $output_index_pad_amount = isset($index_matches[1]) === true ? intval($index_matches[1], 1) : 0;
  3110. // var_dump($index_matches);
  3111. // init the iteration values
  3112. $num = 1;
  3113. $files = array();
  3114. $produced = array();
  3115. $error = false;
  3116. $name_conflict = false;
  3117. $file_exists = false;
  3118. // get the first files name
  3119. $filename = $process_info['dirname'].DS.str_replace($d_matches[0], str_pad($num, $pad_amount, '0', STR_PAD_LEFT), $process_info['basename']);
  3120. $use_timecode = strpos($output_info['basename'], '%timecode') !== false;
  3121. $use_index = $has_preg_index || strpos($output_info['basename'], '%index') !== false;
  3122. // start the timecode pattern replacement values
  3123. if($use_timecode)
  3124. {
  3125. $secs_start = $this->formatTimecode($this->_image_output_timecode_start, '%hh:%mm:%ss.%ms', '%mt', $this->_image_output_timecode_fps);
  3126. $fps_inc = 1/$this->_image_output_timecode_fps;
  3127. $fps_current_sec = 0;
  3128. $fps_current_frame = 0;
  3129. }
  3130. // loop checking for file existence
  3131. while(@is_file($filename))
  3132. {
  3133. // check for empty file
  3134. $size = filesize($filename);
  3135. if($size == 0)
  3136. {
  3137. $error = true;
  3138. }
  3139. array_push($produced, $filename);
  3140. // create the substitution arrays
  3141. $searches = array();
  3142. $replacements = array();
  3143. if($use_index)
  3144. {
  3145. array_push($searches, isset($index_matches[0]) === true ? $index_matches[0] : '%index');
  3146. array_push($replacements, str_pad($num, $output_index_pad_amount, '0', STR_PAD_LEFT));
  3147. }
  3148. // check if timecode is in the output name, no need to use it if not
  3149. if($use_timecode)
  3150. {
  3151. $fps_current_sec += $fps_inc;
  3152. $fps_current_frame += 1;
  3153. if($fps_current_sec >= 1)
  3154. {
  3155. $fps_current_sec = $fps_inc;
  3156. $secs_start += 1;
  3157. $fps_current_frame = 1;
  3158. }
  3159. $timecode = $this->formatSeconds($secs_start, $this->image_output_timecode_format, $this->_image_output_timecode_fps);
  3160. $timecode = str_replace(array(':', '.'), $this->timecode_seperator_output, $timecode);
  3161. // add to the substitution array
  3162. array_push($searches, '%timecode');
  3163. array_push($replacements, $timecode);
  3164. }
  3165. // check if the file exists already and if it does check that it can be overriden
  3166. $old_filename = $filename;
  3167. // print_r(array($searches, $replacements, $output_info['basename']));
  3168. $new_file = str_replace($searches, $replacements, $output_info['basename']);
  3169. $new_filename = $output_info['dirname'].DS.$new_file;
  3170. // var_dump($filename, $new_filename);
  3171. if(!is_file($new_filename) || $this->_overwrite_mode == self::OVERWRITE_EXISTING)
  3172. {
  3173. if (is_file($new_filename)) {
  3174. unlink($new_filename);
  3175. }
  3176. rename($filename, $new_filename);
  3177. $filename = $new_filename;
  3178. }
  3179. // the file exists and is not allowed to be overriden so just rename in the temp directory using the timecode
  3180. else if($this->_overwrite_mode == self::OVERWRITE_PRESERVE)
  3181. {
  3182. $new_filename = $process_info['dirname'].DS.'tbm-'.$this->unique().'-'.$new_file;
  3183. rename($filename, $new_filename);
  3184. $filename = $new_filename;
  3185. // add the error to the log file
  3186. if($log)
  3187. {
  3188. $this->_logResult('execute_image_file_exists', array('file'=>$new_filename));
  3189. }
  3190. // flag the conflict
  3191. $file_exists = true;
  3192. }
  3193. // the file exists so the process must fail
  3194. else
  3195. {
  3196. // add the error to the log file
  3197. if($log)
  3198. {
  3199. $this->_logResult('execute_overwrite_fail');
  3200. }
  3201. // tidy up the produced files
  3202. array_merge($this->_unlink_files, $produced);
  3203. return $this->_raiseError('execute_overwrite_fail');
  3204. }
  3205. // process the name change if the %d is to be replaced with the timecode
  3206. $num += 1;
  3207. $files[$filename] = $size > 0 ? basename($filename) : false;
  3208. // print_r("\r\n\r\n".is_file($old_filename)." - ".$old_filename.' => '.$new_filename);
  3209. // print_r($files);
  3210. // get the next incremented filename to check for existance
  3211. $filename = $process_info['dirname'].DS.str_replace($d_matches[0], str_pad($num, $pad_amount, '0', STR_PAD_LEFT), $process_info['basename']);
  3212. }
  3213. // de-increment the last num as it wasn't found
  3214. $num -= 1;
  3215. // if the file was detected but were empty then display a different error
  3216. if($error === true)
  3217. {
  3218. // add the error to the log file
  3219. if($log)
  3220. {
  3221. $this->_logResult('execute_partial_error', array('input'=>$this->_input_file));
  3222. }
  3223. return $this->_raiseError('execute_partial_error', array('input'=>$this->_input_file));
  3224. //<- exits
  3225. }
  3226. // post process any files
  3227. // print_r($files);
  3228. $post_process_result = $this->_postProcess($log, $files);
  3229. // print_r($files);
  3230. if(is_array($post_process_result))
  3231. {
  3232. // post process has occurred and everything is fine
  3233. $num = count($files);
  3234. }
  3235. else if($post_process_result !== false)
  3236. {
  3237. // the file has encountered an error in the post processing of the files
  3238. return $post_process_result;
  3239. }
  3240. // var_dump("\r\n\r\n", $files, __LINE__, __FILE__, "\r\n\r\n"); exit;
  3241. $this->_process_file_count = $num;
  3242. // no files were generated in this sequence
  3243. if($num == 0)
  3244. {
  3245. // add the error to the log file
  3246. if($log)
  3247. {
  3248. $this->_logResult('execute_image_error', array('input'=>$this->_input_file));
  3249. }
  3250. return $this->_raiseError('execute_image_error', array('input'=>$this->_input_file));
  3251. //<- exits
  3252. }
  3253. // add the files the the class a record of what has been generated
  3254. array_unshift($this->_files, $files);
  3255. array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), implode("\n", $files));
  3256. $this->_addToLog($lines, 'a+');
  3257. return $file_exists ? self::RESULT_OK_BUT_UNWRITABLE : self::RESULT_OK;
  3258. }
  3259. // must validate one file
  3260. else
  3261. {
  3262. // check that it is a file
  3263. if(!is_file($this->_process_address))
  3264. {
  3265. // add the error to the log file
  3266. if($log)
  3267. {
  3268. $this->_logResult('execute_output_404', array('input'=>$this->_input_file));
  3269. }
  3270. return $this->_raiseError('execute_output_404', array('input'=>$this->_input_file));
  3271. //<- exits
  3272. }
  3273. // the file does exist but is it empty?
  3274. if(filesize($this->_process_address) == 0)
  3275. {
  3276. // add the error to the log file
  3277. if($log)
  3278. {
  3279. $this->_logResult('execute_output_empty', array('input'=>$this->_input_file));
  3280. }
  3281. return $this->_raiseError('execute_output_empty', array('input'=>$this->_input_file));
  3282. //<- exits
  3283. }
  3284. // the file is ok so move to output address
  3285. if(!is_file($this->_output_address) || $this->_overwrite_mode == self::OVERWRITE_EXISTING)
  3286. {
  3287. // post process any files
  3288. $post_process_result = $this->_postProcess($log, array($this->_process_address));
  3289. if(is_array($post_process_result) || $post_process_result === true)
  3290. {
  3291. // post process has occurred and everything is fine
  3292. }
  3293. else if($post_process_result !== false)
  3294. {
  3295. return $post_process_result;
  3296. }
  3297. // if the result is false then no post process has taken place
  3298. if (is_file($this->_output_address)) {
  3299. unlink($this->_output_address);
  3300. }
  3301. // rename the file to the final destination and check it went ok
  3302. if(rename($this->_process_address, $this->_output_address))
  3303. {
  3304. array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), $this->_output_address);
  3305. $this->_addToLog($lines, 'a+');
  3306. // the file has been renamed ok
  3307. // add the error to the log file
  3308. if($log)
  3309. {
  3310. $this->_logResult('execute_result_ok', array('output'=>$this->_output_address));
  3311. }
  3312. $this->_process_file_count = 1;
  3313. // add the file the the class a record of what has been generated
  3314. array_unshift($this->_files, array($this->_output_address));
  3315. return self::RESULT_OK;
  3316. }
  3317. // renaming failed so return ok but erro
  3318. else
  3319. {
  3320. // add the error to the log file
  3321. if($log)
  3322. {
  3323. $this->_logResult('execute_result_ok_but_unwritable', array('process'=>$this->_process_address, 'output'=>$this->_output_address));
  3324. }
  3325. // add the file the the class a record of what has been generated
  3326. array_unshift($this->_files, array($this->_process_address));
  3327. array_push($lines, $this->_getMessage('ffmpeg_log_separator'), $this->_getMessage('ffmpeg_log_ffmpeg_output'), $this->_getMessage('ffmpeg_log_separator'), $this->_process_address);
  3328. $this->_addToLog($lines, 'a+');
  3329. return self::RESULT_OK_BUT_UNWRITABLE;
  3330. }
  3331. }
  3332. // if it is not we signal that it has been created but has not been moved.
  3333. else if($this->_overwrite_mode == self::OVERWRITE_PRESERVE)
  3334. {
  3335. // add the error to the log file
  3336. if($log)
  3337. {
  3338. $this->_logResult('execute_result_ok_but_unwritable', array('process'=>$this->_process_address, 'output'=>$this->_output_address));
  3339. }
  3340. // add the file the the class a record of what has been generated
  3341. array_unshift($this->_files, array($this->_process_address));
  3342. return self::RESULT_OK_BUT_UNWRITABLE;
  3343. }
  3344. // the file exists so the process must fail
  3345. else
  3346. {
  3347. // add the error to the log file
  3348. if($log)
  3349. {
  3350. $this->_logResult('execute_overwrite_fail');
  3351. }
  3352. // tidy up the produced files
  3353. array_push($this->_unlink_files, $this->_process_address);
  3354. return $this->_raiseError('execute_overwrite_fail');
  3355. }
  3356. }
  3357. return null;
  3358. }
  3359. /**
  3360. * This function registers a post process after the internal handling of the ffmpeg output has been cleaned and checked.
  3361. * Each function that is set will be called in the order it is set unless an index is specified. All callbacks will be
  3362. * supplied with one argument with is an array of the outputted files.
  3363. *
  3364. * NOTE1: If a post process function is being applied to an outputted video or audio then the process will be applied
  3365. * before it has been moved to it's final destination, however if the output is an image sequence the post process
  3366. * function will be called after the images have been moved to their final destinations.
  3367. *
  3368. * NOTE2: Also it is important to return a boolean 'true' if the post process has been carried out ok. If the process is not
  3369. * a true value then the value will be treated/returned as an error and if applicable logged.
  3370. *
  3371. * @access public
  3372. * @param string $function The name of a function
  3373. * @param object|boolean $class The name of the callback class. If left as false the callback will be treated as a standalone function.
  3374. * @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.
  3375. */
  3376. public function registerPostProcess($function, $class=false, $index=false)
  3377. {
  3378. // create the callback
  3379. $callback = $class === false ? $function : array(&$class, $function);
  3380. // add it to the post process array
  3381. if($index === false)
  3382. {
  3383. array_push($this->_post_processes, $callback);
  3384. }
  3385. else
  3386. {
  3387. $this->_post_processes[$index] = $callback;
  3388. }
  3389. }
  3390. /**
  3391. * Carries out the post processing of the files.
  3392. *
  3393. * @access protected
  3394. * @param boolean $log Determines if logging of errors should be carried out.
  3395. * @param array $files The array of files that have just been processed.
  3396. * @return mixed
  3397. */
  3398. protected function _postProcess($log, $files)
  3399. {
  3400. if(count($this->_post_processes))
  3401. {
  3402. // loop through the post processes
  3403. foreach($this->_post_processes as $key=>$process)
  3404. {
  3405. // call the process
  3406. $return_value = call_user_func_array($process, array($files));
  3407. // if the return value is not strictly equal to true the result will be treated as an error and exit the process loop
  3408. if(!is_array($return_value) && $return_value !== true)
  3409. {
  3410. if($log)
  3411. {
  3412. $this->_logResult($return_value);
  3413. }
  3414. return $this->_raiseError($return_value);
  3415. }
  3416. }
  3417. return $return_value;
  3418. }
  3419. return false;
  3420. }
  3421. /**
  3422. * Returns the number of files outputted in this run. It will be reset when you call PHPVideoToolkit::reset();
  3423. *
  3424. * @access public
  3425. * @return integer
  3426. */
  3427. public function getFileOutputCount()
  3428. {
  3429. return $this->_process_file_count;
  3430. }
  3431. /**
  3432. * Adds lines to the current log file.
  3433. *
  3434. * @access protected
  3435. * @param $message
  3436. * @param $replacements
  3437. */
  3438. protected function _logResult($message, $replacements=false)
  3439. {
  3440. $last = $this->getLastCommand();
  3441. if(is_array($last) === true)
  3442. {
  3443. $last = implode("\r", $last);
  3444. }
  3445. $this->_addToLog(array(
  3446. $this->_getMessage('ffmpeg_log_separator'),
  3447. $this->_getMessage('ffmpeg_log_ffmpeg_result'),
  3448. $this->_getMessage('ffmpeg_log_separator'),
  3449. $this->_getMessage($message, $replacements),
  3450. $this->_getMessage('ffmpeg_log_separator'),
  3451. $this->_getMessage('ffmpeg_log_ffmpeg_command'),
  3452. $this->_getMessage('ffmpeg_log_separator'),
  3453. $last
  3454. ));
  3455. }
  3456. /**
  3457. * Adds lines to the current log file.
  3458. *
  3459. * @access protected
  3460. * @param $lines array An array of lines to add to the log file.
  3461. */
  3462. protected function _addToLog($lines, $where='a')
  3463. {
  3464. $handle = fopen($this->_log_file, $where);
  3465. if(is_array($lines))
  3466. {
  3467. $data = implode("\n", $lines)."\n";
  3468. }
  3469. else
  3470. {
  3471. $data = $lines."\n";
  3472. }
  3473. fwrite($handle, $data);
  3474. fclose($handle);
  3475. }
  3476. /**
  3477. * Moves the current log file to another file.
  3478. *
  3479. * @access public
  3480. * @param $destination string The absolute path of the new filename for the log.
  3481. * @return boolean Returns the result of the log file rename.
  3482. */
  3483. public function moveLog($destination)
  3484. {
  3485. $result = false;
  3486. if($this->_log_file !== null && is_file($this->_log_file))
  3487. {
  3488. if (is_file($destination)) {
  3489. unlink($destination);
  3490. }
  3491. $result = rename($this->_log_file, $destination);
  3492. $this->_log_file = $destination;
  3493. }
  3494. return $result;
  3495. }
  3496. /**
  3497. * Reads the current log file
  3498. *
  3499. * @access public
  3500. * @return string|boolean Returns the current log file content. Returns false on failure.
  3501. */
  3502. public function readLog()
  3503. {
  3504. if($this->_log_file !== null && is_file($this->_log_file))
  3505. {
  3506. $handle = fopen($this->_log_file, 'r');
  3507. $contents = fread($handle, filesize($this->_log_file));
  3508. fclose($handle);
  3509. return $contents;
  3510. }
  3511. return false;
  3512. }
  3513. /**
  3514. * Returns the last outputted file that was processed by ffmpeg from this class.
  3515. *
  3516. * @access public
  3517. * @return mixed array|string Will return an array if the output was a sequence, or string if it was a single file output
  3518. */
  3519. public function getLastOutput()
  3520. {
  3521. return $this->_files[0];
  3522. }
  3523. /**
  3524. * Returns all the outputted files that were processed by ffmpeg from this class.
  3525. *
  3526. * @access public
  3527. * @return array
  3528. */
  3529. public function getOutput()
  3530. {
  3531. return $this->_files;
  3532. }
  3533. /**
  3534. * Returns the amount of time taken of the last file to be processed by ffmpeg.
  3535. *
  3536. * @access public
  3537. * @return mixed integer Will return the time taken in seconds.
  3538. */
  3539. public function getLastProcessTime()
  3540. {
  3541. return $this->_timers[0];
  3542. }
  3543. /**
  3544. * Returns the amount of time taken of all the files to be processed by ffmpeg.
  3545. *
  3546. * @access public
  3547. * @return array
  3548. */
  3549. public function getProcessTime()
  3550. {
  3551. return $this->_timers;
  3552. }
  3553. /**
  3554. * Returns the last encountered error message.
  3555. *
  3556. * @access public
  3557. * @return string
  3558. */
  3559. public function getLastError()
  3560. {
  3561. return $this->_errors[0];
  3562. }
  3563. /**
  3564. * Returns all the encountered errors as an array of strings
  3565. *
  3566. * @access public
  3567. * @return array
  3568. */
  3569. public function getErrors()
  3570. {
  3571. return $this->_errors;
  3572. }
  3573. /**
  3574. * Returns the last command that ffmpeg was given.
  3575. * (Note; if setFormatToFLV was used in the last command then an array is returned as a command was also sent to FLVTool2)
  3576. *
  3577. * @access public
  3578. * @return mixed array|string
  3579. */
  3580. public function getLastCommand()
  3581. {
  3582. return isset($this->_processed[0]) === true ? $this->_processed[0] : false;
  3583. }
  3584. /**
  3585. * Returns all the commands sent to ffmpeg from this class
  3586. *
  3587. * @access public
  3588. * @return unknown
  3589. */
  3590. public function getCommands()
  3591. {
  3592. return $this->_processed;
  3593. }
  3594. /**
  3595. * Raises an error
  3596. *
  3597. * @access protected
  3598. * @param string $message
  3599. * @param array $replacements a list of replacements in search=>replacement format
  3600. * @return boolean Only returns false if $toolkit->on_error_die is set to false
  3601. */
  3602. protected function _raiseError($message, $replacements=false)
  3603. {
  3604. $msg = 'PHPVideoToolkit Error: '.$this->_getMessage($message, $replacements);
  3605. // check what the error is supposed to do
  3606. if($this->on_error_die === true)
  3607. {
  3608. die($msg);
  3609. //<- exits
  3610. }
  3611. // add the error message to the collection
  3612. array_unshift($this->_errors, $msg);
  3613. return false;
  3614. }
  3615. /**
  3616. * Gets a message.
  3617. *
  3618. * @access protected
  3619. * @param string $message
  3620. * @param array $replacements a list of replacements in search=>replacement format
  3621. * @return boolean Only returns false if $toolkit->on_error_die is set to false
  3622. */
  3623. protected function _getMessage($message, $replacements=false)
  3624. {
  3625. $message = isset($this->_messages[$message]) === true ? $this->_messages[$message] : 'Unknown!!!';
  3626. if($replacements)
  3627. {
  3628. $searches = $replaces = array();
  3629. foreach($replacements as $search=>$replace)
  3630. {
  3631. array_push($searches, '#'.$search);
  3632. array_push($replaces, $replace);
  3633. }
  3634. $message = str_replace($searches, $replaces, $message);
  3635. }
  3636. return $message;
  3637. }
  3638. /**
  3639. * Adds a command to be bundled into the ffmpeg command call.
  3640. * (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
  3641. * however it is still best to check and sanitize any params given to this function)
  3642. *
  3643. * @access public
  3644. * @param string $command
  3645. * @param mixed $argument
  3646. * @return boolean
  3647. */
  3648. public function addCommand($command, $argument=false)
  3649. {
  3650. $this->_commands[$command] = $argument === false ? false : escapeshellarg($argument);
  3651. return true;
  3652. }
  3653. /**
  3654. * Determines if the the command exits.
  3655. *
  3656. * @access public
  3657. * @param string $command
  3658. * @return mixed boolean if failure or value if exists.
  3659. */
  3660. public function hasCommand($command)
  3661. {
  3662. return isset($this->_commands[$command]) === true ? ($this->_commands[$command] === false ? true : $this->_commands[$command]): false;
  3663. }
  3664. /**
  3665. * Combines the commands stored into a string
  3666. *
  3667. * @access protected
  3668. * @return string
  3669. */
  3670. protected function _combineCommands()
  3671. {
  3672. $before_input = array();
  3673. $after_input = array();
  3674. $input = null;
  3675. foreach ($this->_commands as $command=>$argument)
  3676. {
  3677. $command_string = trim($command.(!empty($argument) ? ' '.$argument : ''));
  3678. // check for specific none combinable commands as they have specific places they have to go in the string
  3679. switch($command)
  3680. {
  3681. case '-i' :
  3682. $input = $command_string;
  3683. break;
  3684. case '-inputr' :
  3685. $command_string = trim('-r'.($argument ? ' '.$argument : ''));;
  3686. default :
  3687. if(in_array($command, $this->_cmds_before_input))
  3688. {
  3689. array_push($before_input, $command_string);
  3690. }
  3691. else
  3692. {
  3693. array_push($after_input, $command_string);
  3694. }
  3695. }
  3696. }
  3697. $before_input = count($before_input) ? implode(' ', $before_input).' ' : '';
  3698. $after_input_string = ' ';
  3699. if(count($after_input))
  3700. {
  3701. $input .= ' ';
  3702. $after_input_string = implode(' ', $after_input).' ';
  3703. }
  3704. return $before_input.$input.$after_input_string;
  3705. }
  3706. /**
  3707. * Prepares the command for execution
  3708. *
  3709. * @access protected
  3710. * @param string $path Path to the binary
  3711. * @param string $command Command string to execute
  3712. * @param string $args Any additional arguments
  3713. * @return string
  3714. */
  3715. protected function _prepareCommand($path, $command, $args='')
  3716. {
  3717. if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' || !preg_match('/\s/', $path))
  3718. {
  3719. return $path.' '.$command.' '.$args;
  3720. }
  3721. return 'start /D "'.$path.'" /B '.$command.' '.$args;
  3722. }
  3723. /**
  3724. * Generates a unique id. Primarily used in jpeg to movie production
  3725. *
  3726. * @access public
  3727. * @param string $prefix
  3728. * @return string
  3729. */
  3730. public function unique($prefix='')
  3731. {
  3732. return uniqid($prefix.time().'-');
  3733. }
  3734. /**
  3735. * Destructs ffmpeg and removes any temp files/dirs
  3736. */
  3737. function __destruct()
  3738. {
  3739. // loop through the temp files to remove first as they have to be removed before the dir can be removed
  3740. if(!empty($this->_unlink_files))
  3741. {
  3742. foreach ($this->_unlink_files as $key=>$file)
  3743. {
  3744. if(is_file($file))
  3745. {
  3746. @unlink($file);
  3747. }
  3748. }
  3749. $this->_unlink_files = array();
  3750. }
  3751. // loop through the dirs to remove
  3752. if(!empty($this->_unlink_dirs))
  3753. {
  3754. foreach ($this->_unlink_dirs as $key=>$dir)
  3755. {
  3756. if(is_dir($dir))
  3757. {
  3758. @rmdir($dir);
  3759. }
  3760. }
  3761. $this->_unlink_dirs = array();
  3762. }
  3763. }
  3764. }