BxDolTranscoderVideo.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup TridentCore Trident Core
  7. * @{
  8. */
  9. /**
  10. * @page objects
  11. * @section transcoder_videos Videos Transcoder
  12. * @ref BxDolTranscoderVideo
  13. */
  14. /**
  15. * This class transcodes videos and generates video thumbnails.
  16. *
  17. * To generate video which plays in all moders browsers along with video poster,
  18. * you need to create 3 different video transcoding objects which will generate .mp4, .webm videos and video poster.
  19. * Video is converting upon first access, so it is probably better to force video conversion by calling @see BxDolTranscoderVideo::getFileUrl just after video uploading.
  20. * Video for conversion is queued and when cron is run video conversion is performed.
  21. * While video is pending for conversion or in the process then
  22. * @see BxDolTranscoderVideo::getFileUrl methods returns empty string for video and predefined image for video poster.
  23. *
  24. * Transcoder object and other params are the same as in @see BxDolTranscoderImage, but it is highly recommended to disable 'atime_pruning' and 'atime_tracking',
  25. * or set it to fairly big value, since video transcoding is not performed on the fly and takes some time.
  26. *
  27. * Video conversion can be performed on separate server or multiple servers, to do it:
  28. * - install the script on separate server(s), but connect to the same DB which your main site is using
  29. * - enable 'sys_transcoder_queue_files' option (when it is enabled it takes a little longer to convert videos)
  30. * - add the following code to the begining of inc/header.inc.php file on the main site, where your actual site in installed:
  31. * @code
  32. * define('BX_TRANSCODER_PROCESS_COMPLETED', '');
  33. * @endcode
  34. * - if you don't want your main site to convert videos, so all conversion will be performed on the separate server, add the following code to the begining of inc/header.inc.php file on the main site:
  35. * @code
  36. * define('BX_TRANSCODER_NO_TRANSCODING', '');
  37. * @endcode
  38. * - all servers must have different host name
  39. * - only main server must be used as site, additional sites are just for video conversion, don't perform any action on these sites
  40. *
  41. *
  42. * Available filters:
  43. * - Mp4 - this filter convert video into .mp4 format along with resizing, the parameters are the following:
  44. * - h - height of resulted video (360px by default), for video it is highly recommended to specify only height parameter (without width parameter)
  45. * - video_bitrate - video bitrate (512k by default)
  46. * - audio_bitrate - video bitrate (128k by default)
  47. * - ffmpeg_options - additional command line options for ffmepeg, as key => value array (empty by default)
  48. * - Webm - this filter convert video into .webm format along with resizing, the parameters are the same as for Mp4 filter
  49. * - Poster - this filter generates video thumbnail, it tries to get poster at 0, 3 and 5 seconds from the beginning, it gets first not fully black/white thumb
  50. *
  51. *
  52. * Example of usage:
  53. * @code
  54. * // transcoder objects which generate .mp4, .webm videos and image poster
  55. * $oTranscoderMp4 = BxDolTranscoder::getObjectInstance('bx_video_mp4');
  56. * $oTranscoderWebm = BxDolTranscoder::getObjectInstance('bx_video_webm');
  57. * $oTranscoderPoster = BxDolTranscoder::getObjectInstance('bx_video_poster');
  58. *
  59. * // make sure to call it only once (for example: during module installation), before the first usage, no need to call it every time
  60. * $oTranscoderMp4->registerHandlers();
  61. * $oTranscoderWebm->registerHandlers();
  62. * $oTranscoderPoster->registerHandlers();
  63. *
  64. * // get URLs of transcoded videos and video thumbnail, 33 is ID of original video file stored in specified storage object
  65. * $sUrlMp4 = $oTranscoderMp4->getFileUrl(33);
  66. * $sUrlWebM = $oTranscoderWebm->getFileUrl(33);
  67. * $sUrlPoster = $oTranscoderPoster->getFileUrl(33);
  68. *
  69. * echo 'My cat:' . BxTemplFunctions::getInstance()->videoPlayer($sUrlPoster, $sUrlMP4, $sUrlWebM);
  70. * @endcode
  71. *
  72. * Also @see transcoder_videos sample for complete example.
  73. */
  74. class BxDolTranscoderVideo extends BxDolTranscoder implements iBxDolFactoryObject
  75. {
  76. protected function __construct($aObject, $oStorage)
  77. {
  78. parent::__construct($aObject, $oStorage);
  79. $this->_sQueueStorage = getParam('sys_transcoder_queue_storage') ? 'sys_transcoder_queue_files' : '';
  80. $this->_oDb = new BxDolTranscoderVideoQuery($aObject);
  81. $this->_sQueueTable = $this->_oDb->getQueueTable();
  82. }
  83. public function getDevicePixelRatioHandlerSuffix ()
  84. {
  85. return '';
  86. }
  87. /**
  88. * If video isn't processed yet then empty string is returned for video, or predefined image is returned for video poster
  89. */
  90. public function getFileUrlNotReady($mixedHandler)
  91. {
  92. return false === $this->getFilterParams('Poster') ? '' : BxDolTemplate::getInstance()->getImageUrl('video-na.png');
  93. }
  94. /**
  95. * Convert video to .jpg format - video poster
  96. */
  97. protected function applyFilter_Poster ($sFile, $aParams)
  98. {
  99. $oImage = BxDolImageResize::getInstance();
  100. $sFileOut = $this->getTmpFilename('.jpg');
  101. $bRet = false;
  102. $aSeconds = array (0, 3, 5, 0);
  103. $sSize = $this->_getOptionSizeForVideo ($sFile, $aParams);
  104. foreach ($aSeconds as $iSecond) {
  105. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', $aParams, array (
  106. 's' => $sSize,
  107. 'ss' => $iSecond,
  108. 'vframes' => 1,
  109. 'f' => 'image2',
  110. 'an' => ' ',
  111. ));
  112. if (!$bRet)
  113. continue;
  114. $aRgb = $oImage->getAverageColor($sFileOut);
  115. $fRgb = ($aRgb['r'] + $aRgb['g'] + $aRgb['b']) / 3;
  116. if ($fRgb > 32 && $fRgb < 224)
  117. break;
  118. }
  119. if (!$bRet) {
  120. @unlink($sFileOut);
  121. return false;
  122. }
  123. return rename($sFileOut, $sFile);
  124. }
  125. /**
  126. * Convert video to .mp4 format
  127. */
  128. protected function applyFilter_Mp4 ($sFile, $aParams)
  129. {
  130. return $this->_convertVideo($sFile, $sFile, '.mp4', $aParams, array (
  131. 'strict' => 'experimental',
  132. 'vcodec' => 'libx264',
  133. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  134. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  135. 'movflags' => '+faststart',
  136. 'acodec' => 'aac',
  137. 'ar' => '44100',
  138. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  139. ));
  140. }
  141. /**
  142. * Convert video to .webm format
  143. */
  144. protected function applyFilter_Webm ($sFile, $aParams)
  145. {
  146. return $this->_convertVideo($sFile, $sFile, '.webm', $aParams, array (
  147. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  148. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  149. 'acodec' => 'libvorbis',
  150. 'ar' => '44100',
  151. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  152. ));
  153. }
  154. /**
  155. * Convert video using ffmpeg binary. Video conversion otput is written to the 'log' variable.
  156. * @param $sFile input file for conversion
  157. * @param $sFileOut output file for conversion, can be the same as input file
  158. * @param $sExt output file extension, in the format '.ext'
  159. * @param $aParams filter params
  160. * @param $aOptions ffmpeg options as array
  161. * @return false on error, or true on success
  162. */
  163. protected function _convertVideo ($sFile, $sFileOut, $sExt, $aParams, $aOptions)
  164. {
  165. if (!empty($aParams['ffmpeg_options']) && is_array($aParams['ffmpeg_options']))
  166. $aOptions = array_merge($aOptions, $aParams['ffmpeg_options']);
  167. $sOptions = '';
  168. foreach ($aOptions as $k => $v)
  169. if ($v)
  170. $sOptions .= "-{$k} {$v} ";
  171. $bRename = false;
  172. if ($sFileOut == $sFile) { // if output file is the same as input - generate new tmp file
  173. $sFileOut = $this->getTmpFilename($sExt);
  174. $bRename = true;
  175. }
  176. elseif (file_exists($sFileOut)) {
  177. @unlink($sFileOut);
  178. }
  179. $sCommand = escapeshellcmd(BX_SYSTEM_FFMPEG) . ' -y -i ' . escapeshellarg($sFile) . ' ' . $sOptions . ' ' . escapeshellarg($sFileOut) . ' 2>&1';
  180. $sOutput = `$sCommand`;
  181. $this->addToLog("\n---\n{$sCommand}\n{$sOutput}\n");
  182. if (!file_exists($sFileOut) || 0 == filesize($sFileOut))
  183. return false;
  184. if ($bRename && !rename($sFileOut, $sFile)) // rename tmp file, if tmp file was generated
  185. return false;
  186. return true;
  187. }
  188. /**
  189. * Get video size.
  190. * It generated image from the video and returns size of the image.
  191. * @param $sFile path to the video file
  192. * @return array where 'w' key is width and 'h' key is height
  193. */
  194. protected function _getVideoSize ($sFile)
  195. {
  196. $sFileOut = $this->getTmpFilename('.jpg');
  197. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', array(), array (
  198. 'ss' => 0,
  199. 'vframes' => 1,
  200. 'f' => 'image2',
  201. 'an' => ' ',
  202. ));
  203. if (!$bRet) {
  204. @unlink($sFileOut);
  205. return false;
  206. }
  207. $oImage = BxDolImageResize::getInstance();
  208. $aSize = $oImage->getImageSize($sFileOut);
  209. @unlink($sFileOut);
  210. return $aSize;
  211. }
  212. /**
  213. * Get output video size as 'WxH' string.
  214. * It check filter params for 'w' and 'h' options and original video ratio and return the resulted video size.
  215. * - If only height specified in params (desired behavior) or no width or height is specified (default height is 360),
  216. * then width is automatically calculated using original video size ratio.
  217. * - If only width specified in params, then height is automatically calculated using original video size ratio.
  218. * - If width and height specified in params then these values are returned, but the resulted video size can be unproportionate.
  219. * @param $sFile original video file path (to check original video size ratio)
  220. * @param $aParams filter params
  221. * @return WxH string
  222. */
  223. protected function _getOptionSizeForVideo ($sFile, $aParams)
  224. {
  225. if (isset($aParams['w']) && isset($aParams['h']))
  226. return $aParams['w'] . 'x' . $aParams['h'];
  227. if (!isset($aParams['w']) && !isset($aParams['h']))
  228. $aParams['h'] = '360';
  229. $fRatio = 16/9;
  230. $aSize = $this->_getVideoSize($sFile);
  231. if ($aSize)
  232. $fRatio = $aSize['w'] / $aSize['h'];
  233. if (isset($aParams['h']))
  234. return round($fRatio * $aParams['h'] / 2) * 2 . 'x' . $aParams['h'];
  235. if (isset($aParams['w']))
  236. return $aParams['w'] . 'x' . round($aParams['w'] / $fRatio / 2) * 2;
  237. return '640x360'; // should never happen
  238. }
  239. }
  240. /** @} */