BxDolTranscoderVideo.php 10 KB

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