BxDolTranscoderVideo.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 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 (360 by default), for video it is highly recommended to specify only height parameter (no 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 blacke/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. */
  81. class BxDolTranscoderVideo extends BxDolTranscoder implements iBxDolFactoryObject
  82. {
  83. protected function __construct($aObject, $oStorage)
  84. {
  85. parent::__construct($aObject, $oStorage);
  86. $this->_sQueueStorage = getParam('sys_transcoder_queue_storage') ? 'sys_transcoder_queue_files' : '';
  87. $this->_oDb = new BxDolTranscoderVideoQuery($aObject);
  88. $this->_sQueueTable = $this->_oDb->getQueueTable();
  89. }
  90. public function getDevicePixelRatioHandlerSuffix ()
  91. {
  92. return '';
  93. }
  94. /**
  95. * If video isn't processed yet then empty string is returned for video, or predefined image is returned for video poster
  96. */
  97. public function getFileUrlNotReady($mixedHandler)
  98. {
  99. return $this->_isPosterFilter() ? BxDolTemplate::getInstance()->getImageUrl('video-na.png') : '';
  100. }
  101. /**
  102. * Convert video to .jpg format - video poster
  103. */
  104. protected function applyFilter_Poster ($sFile, $aParams)
  105. {
  106. bx_import('BxDolImageResize');
  107. $oImage = BxDolImageResize::getInstance();
  108. $sFileOut = $this->getTmpFilename('.jpg');
  109. $bRet = false;
  110. $aSeconds = array (0, 3, 5, 0);
  111. $sSize = $this->_getOptionSizeForVideo ($sFile, $aParams);
  112. foreach ($aSeconds as $iSecond) {
  113. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', $aParams, array (
  114. 's' => $sSize,
  115. 'ss' => $iSecond,
  116. 'vframes' => 1,
  117. 'f' => 'image2',
  118. 'an' => ' ',
  119. ));
  120. if (!$bRet)
  121. continue;
  122. $aRgb = $oImage->getAverageColor($sFileOut);
  123. $fRgb = ($aRgb['r'] + $aRgb['g'] + $aRgb['b']) / 3;
  124. if ($fRgb > 32 && $fRgb < 224)
  125. break;
  126. }
  127. if (!$bRet) {
  128. @unlink($sFileOut);
  129. return false;
  130. }
  131. return rename($sFileOut, $sFile);
  132. }
  133. /**
  134. * Convert video to .mp4 format
  135. */
  136. protected function applyFilter_Mp4 ($sFile, $aParams)
  137. {
  138. return $this->_convertVideo($sFile, $sFile, '.mp4', $aParams, array (
  139. 'strict' => 'experimental',
  140. 'vcodec' => 'libx264',
  141. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  142. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  143. 'movflags' => '+faststart',
  144. 'acodec' => 'aac',
  145. 'ar' => '44100',
  146. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  147. ));
  148. }
  149. /**
  150. * Convert video to .webm format
  151. */
  152. protected function applyFilter_Webm ($sFile, $aParams)
  153. {
  154. return $this->_convertVideo($sFile, $sFile, '.webm', $aParams, array (
  155. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  156. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  157. 'acodec' => 'libvorbis',
  158. 'ar' => '44100',
  159. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  160. ));
  161. }
  162. /**
  163. * Convert video using ffmpeg binary. Video conversion otput is written to the 'log' variable.
  164. * @param $sFile input file for conversion
  165. * @param $sFileOut output file for conversion, can be the same as input file
  166. * @param $sExt output file extension, in the format '.ext'
  167. * @param $aParams filter params
  168. * @param $aOptions ffmpeg options as array
  169. * @return false on error, or true on success
  170. */
  171. protected function _convertVideo ($sFile, $sFileOut, $sExt, $aParams, $aOptions)
  172. {
  173. if (!empty($aParams['ffmpeg_options']) && is_array($aParams['ffmpeg_options']))
  174. $aOptions = array_merge($aOptions, $aParams['ffmpeg_options']);
  175. $sOptions = '';
  176. foreach ($aOptions as $k => $v)
  177. if ($v)
  178. $sOptions .= "-{$k} {$v} ";
  179. $bRename = false;
  180. if ($sFileOut == $sFile) { // if output file is the same as input - generate new tmp file
  181. $sFileOut = $this->getTmpFilename($sExt);
  182. $bRename = true;
  183. }
  184. elseif (file_exists($sFileOut)) {
  185. @unlink($sFileOut);
  186. }
  187. $sCommand = BX_SYSTEM_FFMPEG . ' -y -i "' . escapeshellcmd($sFile) . '" ' . $sOptions . ' ' . $sFileOut . ' 2>&1';
  188. $sOutput = `$sCommand`;
  189. $this->addToLog("\n---\n{$sCommand}\n{$sOutput}\n");
  190. if (!file_exists($sFileOut) || 0 == filesize($sFileOut))
  191. return false;
  192. if ($bRename && !rename($sFileOut, $sFile)) // rename tmp file, if tmp file was generated
  193. return false;
  194. return true;
  195. }
  196. /**
  197. * Get video size.
  198. * It generated image from the video and returns size of the image.
  199. * @param $sFile path to the video file
  200. * @return array where 'w' key is width and 'h' key is height
  201. */
  202. protected function _getVideoSize ($sFile)
  203. {
  204. $sFileOut = $this->getTmpFilename('.jpg');
  205. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', array(), array (
  206. 'ss' => 0,
  207. 'vframes' => 1,
  208. 'f' => 'image2',
  209. 'an' => ' ',
  210. ));
  211. if (!$bRet) {
  212. @unlink($sFileOut);
  213. return false;
  214. }
  215. bx_import('BxDolImageResize');
  216. $oImage = BxDolImageResize::getInstance();
  217. $aSize = $oImage->getImageSize($sFileOut);
  218. @unlink($sFileOut);
  219. return $aSize;
  220. }
  221. /**
  222. * Get output video size as 'WxH' string.
  223. * It check filter params for 'w' and 'h' options and original video ratio and return the resulted video size.
  224. * - If only height specified in params (desired behavior) or no width or height is specified (default height is 360),
  225. * then width is automatically calculated using original video size ratio.
  226. * - If only width specified in params, then height is automatically calculated using original video size ratio.
  227. * - If width and height specified in params then these values are returned, but the resulted video size can be unproportionate.
  228. * @param $sFile original video file path (to check original video size ratio)
  229. * @param $aParams filter params
  230. * @return WxH string
  231. */
  232. protected function _getOptionSizeForVideo ($sFile, $aParams)
  233. {
  234. if (isset($aParams['w']) && isset($aParams['h']))
  235. return $aParams['w'] . 'x' . $aParams['h'];
  236. if (!isset($aParams['w']) && !isset($aParams['h']))
  237. $aParams['h'] = '360';
  238. $fRatio = 16/9;
  239. $aSize = $this->_getVideoSize($sFile);
  240. if ($aSize)
  241. $fRatio = $aSize['w'] / $aSize['h'];
  242. if (isset($aParams['h']))
  243. return round($fRatio * $aParams['h'] / 2) * 2 . 'x' . $aParams['h'];
  244. if (isset($aParams['w']))
  245. return $aParams['w'] . 'x' . round($aParams['w'] / $fRatio / 2) * 2;
  246. return '640x360'; // should never happen
  247. }
  248. /**
  249. * Checks if 'Poster' filter is enabled for curent transcoder
  250. */
  251. protected function _isPosterFilter ()
  252. {
  253. $this->initFilters ();
  254. foreach ($this->_aObject['filters'] as $aParams)
  255. if ('Poster' == $aParams['filter'])
  256. return true;
  257. return false;
  258. }
  259. }
  260. /** @} */