BxDolTranscoderVideo.php 11 KB

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