BxDolTranscoderVideo.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. 'acodec' => 'aac',
  127. 'ar' => '44100',
  128. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  129. ));
  130. }
  131. /**
  132. * Convert video to .webm format
  133. */
  134. protected function applyFilter_Webm ($sFile, $aParams)
  135. {
  136. return $this->_convertVideo($sFile, $sFile, '.webm', $aParams, array (
  137. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  138. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  139. 'acodec' => 'libvorbis',
  140. 'ar' => '44100',
  141. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  142. ));
  143. }
  144. /**
  145. * Convert video using ffmpeg binary. Video conversion otput is written to the 'log' variable.
  146. * @param $sFile input file for conversion
  147. * @param $sFileOut output file for conversion, can be the same as input file
  148. * @param $sExt output file extension, in the format '.ext'
  149. * @param $aParams filter params
  150. * @param $aOptions ffmpeg options as array
  151. * @return false on error, or true on success
  152. */
  153. protected function _convertVideo ($sFile, $sFileOut, $sExt, $aParams, $aOptions)
  154. {
  155. if (!empty($aParams['ffmpeg_options']) && is_array($aParams['ffmpeg_options']))
  156. $aOptions = array_merge($aOptions, $aParams['ffmpeg_options']);
  157. $sOptions = '';
  158. foreach ($aOptions as $k => $v)
  159. if ($v)
  160. $sOptions .= "-{$k} {$v} ";
  161. $bRename = false;
  162. if ($sFileOut == $sFile) { // if output file is the same as input - generate new tmp file
  163. $sFileOut = $this->getTmpFilename($sExt);
  164. $bRename = true;
  165. }
  166. elseif (file_exists($sFileOut)) {
  167. @unlink($sFileOut);
  168. }
  169. $sCommand = BX_SYSTEM_FFMPEG . ' -y -i "' . escapeshellcmd($sFile) . '" ' . $sOptions . ' ' . $sFileOut;
  170. $sOutput = `$sCommand`;
  171. $this->addToLog("\n---\n{$sCommand}\n{$sOutput}\n");
  172. if (!file_exists($sFileOut) || 0 == filesize($sFileOut))
  173. return false;
  174. if ($bRename && !rename($sFileOut, $sFile)) // rename tmp file, if tmp file was generated
  175. return false;
  176. return true;
  177. }
  178. /**
  179. * Get video size.
  180. * It generated image from the video and returns size of the image.
  181. * @param $sFile path to the video file
  182. * @return array where 'w' key is width and 'h' key is height
  183. */
  184. protected function _getVideoSize ($sFile)
  185. {
  186. $sFileOut = $this->getTmpFilename('.jpg');
  187. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', array(), array (
  188. 'ss' => 0,
  189. 'vframes' => 1,
  190. 'f' => 'image2',
  191. 'an' => ' ',
  192. ));
  193. if (!$bRet)
  194. return false;
  195. bx_import('BxDolImageResize');
  196. $oImage = BxDolImageResize::getInstance();
  197. $aSize = $oImage->getImageSize($sFileOut);
  198. @unlink($sFileOut);
  199. return $aSize;
  200. }
  201. /**
  202. * Get output video size as 'WxH' string.
  203. * It check filter params for 'w' and 'h' options and original video ratio and return the resulted video size.
  204. * - If only height specified in params (desired behavior) or no width or height is specified (default height is 360),
  205. * then width is automatically calculated using original video size ratio.
  206. * - If only width specified in params, then height is automatically calculated using original video size ratio.
  207. * - If width and height specified in params then these values are returned, but the resulted video size can be unproportionate.
  208. * @param $sFile original video file path (to check original video size ratio)
  209. * @param $aParams filter params
  210. * @return WxH string
  211. */
  212. protected function _getOptionSizeForVideo ($sFile, $aParams)
  213. {
  214. if (isset($aParams['w']) && isset($aParams['h']))
  215. return $aParams['w'] . 'x' . $aParams['h'];
  216. if (!isset($aParams['w']) && !isset($aParams['h']))
  217. $aParams['h'] = '360';
  218. $fRatio = 16/9;
  219. $aSize = $this->_getVideoSize($sFile);
  220. if ($aSize)
  221. $fRatio = $aSize['w'] / $aSize['h'];
  222. if (isset($aParams['h']))
  223. return round($fRatio * $aParams['h'] / 2) * 2 . 'x' . $aParams['h'];
  224. if (isset($aParams['w']))
  225. return $aParams['w'] . 'x' . round($aParams['w'] / $fRatio / 2) * 2;
  226. return '640x360'; // should never happen
  227. }
  228. /**
  229. * Checks if 'Poster' filter is enabled for curent transcoder
  230. */
  231. protected function _isPosterFilter ()
  232. {
  233. $this->initFilters ();
  234. foreach ($this->_aObject['filters'] as $aParams)
  235. if ('Poster' == $aParams['filter'])
  236. return true;
  237. return false;
  238. }
  239. }
  240. /** @} */