You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

828 lines
27KB

  1. /*
  2. * Interface to xvidcore for mpeg4 encoding
  3. * Copyright (c) 2004 Adam Thayer <krevnik@comcast.net>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Interface to xvidcore for MPEG-4 compliant encoding.
  24. * @author Adam Thayer (krevnik@comcast.net)
  25. */
  26. /* needed for mkstemp() */
  27. #define _XOPEN_SOURCE 600
  28. #include <xvid.h>
  29. #include <unistd.h>
  30. #include "avcodec.h"
  31. #include "libavutil/intreadwrite.h"
  32. #include "libxvid_internal.h"
  33. #if !HAVE_MKSTEMP
  34. #include <fcntl.h>
  35. #endif
  36. /**
  37. * Buffer management macros.
  38. */
  39. #define BUFFER_SIZE 1024
  40. #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
  41. #define BUFFER_CAT(x) (&((x)[strlen(x)]))
  42. /* For PPC Use */
  43. int has_altivec(void);
  44. /**
  45. * Structure for the private Xvid context.
  46. * This stores all the private context for the codec.
  47. */
  48. struct xvid_context {
  49. void *encoder_handle; /**< Handle for Xvid encoder */
  50. int xsize; /**< Frame x size */
  51. int ysize; /**< Frame y size */
  52. int vop_flags; /**< VOP flags for Xvid encoder */
  53. int vol_flags; /**< VOL flags for Xvid encoder */
  54. int me_flags; /**< Motion Estimation flags */
  55. int qscale; /**< Do we use constant scale? */
  56. int quicktime_format; /**< Are we in a QT-based format? */
  57. AVFrame encoded_picture; /**< Encoded frame information */
  58. char *twopassbuffer; /**< Character buffer for two-pass */
  59. char *old_twopassbuffer; /**< Old character buffer (two-pass) */
  60. char *twopassfile; /**< second pass temp file name */
  61. unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
  62. unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
  63. };
  64. /**
  65. * Structure for the private first-pass plugin.
  66. */
  67. struct xvid_ff_pass1 {
  68. int version; /**< Xvid version */
  69. struct xvid_context *context; /**< Pointer to private context */
  70. };
  71. /* Prototypes - See function implementation for details */
  72. int xvid_strip_vol_header(AVCodecContext *avctx, unsigned char *frame, unsigned int header_len, unsigned int frame_len);
  73. int xvid_ff_2pass(void *ref, int opt, void *p1, void *p2);
  74. void xvid_correct_framerate(AVCodecContext *avctx);
  75. /* Wrapper to work around the lack of mkstemp() on mingw.
  76. * Also, tries to create file in /tmp first, if possible.
  77. * *prefix can be a character constant; *filename will be allocated internally.
  78. * @return file descriptor of opened file (or -1 on error)
  79. * and opened file name in **filename. */
  80. int ff_tempfile(const char *prefix, char **filename) {
  81. int fd=-1;
  82. #if !HAVE_MKSTEMP
  83. *filename = tempnam(".", prefix);
  84. #else
  85. size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */
  86. *filename = av_malloc(len);
  87. #endif
  88. /* -----common section-----*/
  89. if (*filename == NULL) {
  90. av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");
  91. return -1;
  92. }
  93. #if !HAVE_MKSTEMP
  94. fd = open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);
  95. #else
  96. snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);
  97. fd = mkstemp(*filename);
  98. if (fd < 0) {
  99. snprintf(*filename, len, "./%sXXXXXX", prefix);
  100. fd = mkstemp(*filename);
  101. }
  102. #endif
  103. /* -----common section-----*/
  104. if (fd < 0) {
  105. av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
  106. return -1;
  107. }
  108. return fd; /* success */
  109. }
  110. #if CONFIG_LIBXVID_ENCODER
  111. /**
  112. * Create the private context for the encoder.
  113. * All buffers are allocated, settings are loaded from the user,
  114. * and the encoder context created.
  115. *
  116. * @param avctx AVCodecContext pointer to context
  117. * @return Returns 0 on success, -1 on failure
  118. */
  119. static av_cold int xvid_encode_init(AVCodecContext *avctx) {
  120. int xerr, i;
  121. int xvid_flags = avctx->flags;
  122. struct xvid_context *x = avctx->priv_data;
  123. uint16_t *intra, *inter;
  124. int fd;
  125. xvid_plugin_single_t single;
  126. struct xvid_ff_pass1 rc2pass1;
  127. xvid_plugin_2pass2_t rc2pass2;
  128. xvid_gbl_init_t xvid_gbl_init;
  129. xvid_enc_create_t xvid_enc_create;
  130. xvid_enc_plugin_t plugins[7];
  131. /* Bring in VOP flags from ffmpeg command-line */
  132. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  133. if( xvid_flags & CODEC_FLAG_4MV )
  134. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  135. if( avctx->trellis
  136. )
  137. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  138. if( xvid_flags & CODEC_FLAG_AC_PRED )
  139. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  140. if( xvid_flags & CODEC_FLAG_GRAY )
  141. x->vop_flags |= XVID_VOP_GREYSCALE;
  142. /* Decide which ME quality setting to use */
  143. x->me_flags = 0;
  144. switch( avctx->me_method ) {
  145. case ME_FULL: /* Quality 6 */
  146. x->me_flags |= XVID_ME_EXTSEARCH16
  147. | XVID_ME_EXTSEARCH8;
  148. case ME_EPZS: /* Quality 4 */
  149. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8
  150. | XVID_ME_HALFPELREFINE8
  151. | XVID_ME_CHROMA_PVOP
  152. | XVID_ME_CHROMA_BVOP;
  153. case ME_LOG: /* Quality 2 */
  154. case ME_PHODS:
  155. case ME_X1:
  156. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16
  157. | XVID_ME_HALFPELREFINE16;
  158. case ME_ZERO: /* Quality 0 */
  159. default:
  160. break;
  161. }
  162. /* Decide how we should decide blocks */
  163. switch( avctx->mb_decision ) {
  164. case 2:
  165. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  166. x->me_flags |= XVID_ME_HALFPELREFINE8_RD
  167. | XVID_ME_QUARTERPELREFINE8_RD
  168. | XVID_ME_EXTSEARCH_RD
  169. | XVID_ME_CHECKPREDICTION_RD;
  170. case 1:
  171. if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
  172. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  173. x->me_flags |= XVID_ME_HALFPELREFINE16_RD
  174. | XVID_ME_QUARTERPELREFINE16_RD;
  175. default:
  176. break;
  177. }
  178. /* Bring in VOL flags from ffmpeg command-line */
  179. x->vol_flags = 0;
  180. if( xvid_flags & CODEC_FLAG_GMC ) {
  181. x->vol_flags |= XVID_VOL_GMC;
  182. x->me_flags |= XVID_ME_GME_REFINE;
  183. }
  184. if( xvid_flags & CODEC_FLAG_QPEL ) {
  185. x->vol_flags |= XVID_VOL_QUARTERPEL;
  186. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  187. if( x->vop_flags & XVID_VOP_INTER4V )
  188. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  189. }
  190. memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
  191. xvid_gbl_init.version = XVID_VERSION;
  192. xvid_gbl_init.debug = 0;
  193. #if ARCH_PPC
  194. /* Xvid's PPC support is borked, use libavcodec to detect */
  195. #if HAVE_ALTIVEC
  196. if( has_altivec() ) {
  197. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
  198. } else
  199. #endif
  200. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
  201. #else
  202. /* Xvid can detect on x86 */
  203. xvid_gbl_init.cpu_flags = 0;
  204. #endif
  205. /* Initialize */
  206. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  207. /* Create the encoder reference */
  208. memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
  209. xvid_enc_create.version = XVID_VERSION;
  210. /* Store the desired frame size */
  211. xvid_enc_create.width = x->xsize = avctx->width;
  212. xvid_enc_create.height = x->ysize = avctx->height;
  213. /* Xvid can determine the proper profile to use */
  214. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  215. /* We don't use zones */
  216. xvid_enc_create.zones = NULL;
  217. xvid_enc_create.num_zones = 0;
  218. xvid_enc_create.num_threads = avctx->thread_count;
  219. xvid_enc_create.plugins = plugins;
  220. xvid_enc_create.num_plugins = 0;
  221. /* Initialize Buffers */
  222. x->twopassbuffer = NULL;
  223. x->old_twopassbuffer = NULL;
  224. x->twopassfile = NULL;
  225. if( xvid_flags & CODEC_FLAG_PASS1 ) {
  226. memset(&rc2pass1, 0, sizeof(struct xvid_ff_pass1));
  227. rc2pass1.version = XVID_VERSION;
  228. rc2pass1.context = x;
  229. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  230. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  231. if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
  232. av_log(avctx, AV_LOG_ERROR,
  233. "Xvid: Cannot allocate 2-pass log buffers\n");
  234. return -1;
  235. }
  236. x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
  237. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  238. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  239. xvid_enc_create.num_plugins++;
  240. } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
  241. memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
  242. rc2pass2.version = XVID_VERSION;
  243. rc2pass2.bitrate = avctx->bit_rate;
  244. fd = ff_tempfile("xvidff.", &(x->twopassfile));
  245. if( fd == -1 ) {
  246. av_log(avctx, AV_LOG_ERROR,
  247. "Xvid: Cannot write 2-pass pipe\n");
  248. return -1;
  249. }
  250. if( avctx->stats_in == NULL ) {
  251. av_log(avctx, AV_LOG_ERROR,
  252. "Xvid: No 2-pass information loaded for second pass\n");
  253. return -1;
  254. }
  255. if( strlen(avctx->stats_in) >
  256. write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
  257. close(fd);
  258. av_log(avctx, AV_LOG_ERROR,
  259. "Xvid: Cannot write to 2-pass pipe\n");
  260. return -1;
  261. }
  262. close(fd);
  263. rc2pass2.filename = x->twopassfile;
  264. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  265. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  266. xvid_enc_create.num_plugins++;
  267. } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
  268. /* Single Pass Bitrate Control! */
  269. memset(&single, 0, sizeof(xvid_plugin_single_t));
  270. single.version = XVID_VERSION;
  271. single.bitrate = avctx->bit_rate;
  272. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  273. plugins[xvid_enc_create.num_plugins].param = &single;
  274. xvid_enc_create.num_plugins++;
  275. }
  276. /* Luminance Masking */
  277. if( 0.0 != avctx->lumi_masking ) {
  278. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  279. plugins[xvid_enc_create.num_plugins].param = NULL;
  280. xvid_enc_create.num_plugins++;
  281. }
  282. /* Frame Rate and Key Frames */
  283. xvid_correct_framerate(avctx);
  284. xvid_enc_create.fincr = avctx->time_base.num;
  285. xvid_enc_create.fbase = avctx->time_base.den;
  286. if( avctx->gop_size > 0 )
  287. xvid_enc_create.max_key_interval = avctx->gop_size;
  288. else
  289. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  290. /* Quants */
  291. if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
  292. else x->qscale = 0;
  293. xvid_enc_create.min_quant[0] = avctx->qmin;
  294. xvid_enc_create.min_quant[1] = avctx->qmin;
  295. xvid_enc_create.min_quant[2] = avctx->qmin;
  296. xvid_enc_create.max_quant[0] = avctx->qmax;
  297. xvid_enc_create.max_quant[1] = avctx->qmax;
  298. xvid_enc_create.max_quant[2] = avctx->qmax;
  299. /* Quant Matrices */
  300. x->intra_matrix = x->inter_matrix = NULL;
  301. if( avctx->mpeg_quant )
  302. x->vol_flags |= XVID_VOL_MPEGQUANT;
  303. if( (avctx->intra_matrix || avctx->inter_matrix) ) {
  304. x->vol_flags |= XVID_VOL_MPEGQUANT;
  305. if( avctx->intra_matrix ) {
  306. intra = avctx->intra_matrix;
  307. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  308. } else
  309. intra = NULL;
  310. if( avctx->inter_matrix ) {
  311. inter = avctx->inter_matrix;
  312. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  313. } else
  314. inter = NULL;
  315. for( i = 0; i < 64; i++ ) {
  316. if( intra )
  317. x->intra_matrix[i] = (unsigned char)intra[i];
  318. if( inter )
  319. x->inter_matrix[i] = (unsigned char)inter[i];
  320. }
  321. }
  322. /* Misc Settings */
  323. xvid_enc_create.frame_drop_ratio = 0;
  324. xvid_enc_create.global = 0;
  325. if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
  326. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  327. /* Determines which codec mode we are operating in */
  328. avctx->extradata = NULL;
  329. avctx->extradata_size = 0;
  330. if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
  331. /* In this case, we are claiming to be MPEG4 */
  332. x->quicktime_format = 1;
  333. avctx->codec_id = CODEC_ID_MPEG4;
  334. } else {
  335. /* We are claiming to be Xvid */
  336. x->quicktime_format = 0;
  337. if(!avctx->codec_tag)
  338. avctx->codec_tag = AV_RL32("xvid");
  339. }
  340. /* Bframes */
  341. xvid_enc_create.max_bframes = avctx->max_b_frames;
  342. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  343. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  344. if( avctx->max_b_frames > 0 && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  345. /* Create encoder context */
  346. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  347. if( xerr ) {
  348. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  349. return -1;
  350. }
  351. x->encoder_handle = xvid_enc_create.handle;
  352. avctx->coded_frame = &x->encoded_picture;
  353. return 0;
  354. }
  355. /**
  356. * Encode a single frame.
  357. *
  358. * @param avctx AVCodecContext pointer to context
  359. * @param frame Pointer to encoded frame buffer
  360. * @param buf_size Size of encoded frame buffer
  361. * @param data Pointer to AVFrame of unencoded frame
  362. * @return Returns 0 on success, -1 on failure
  363. */
  364. static int xvid_encode_frame(AVCodecContext *avctx,
  365. unsigned char *frame, int buf_size, void *data) {
  366. int xerr, i;
  367. char *tmp;
  368. struct xvid_context *x = avctx->priv_data;
  369. AVFrame *picture = data;
  370. AVFrame *p = &(x->encoded_picture);
  371. xvid_enc_frame_t xvid_enc_frame;
  372. xvid_enc_stats_t xvid_enc_stats;
  373. /* Start setting up the frame */
  374. memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
  375. xvid_enc_frame.version = XVID_VERSION;
  376. memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
  377. xvid_enc_stats.version = XVID_VERSION;
  378. *p = *picture;
  379. /* Let Xvid know where to put the frame. */
  380. xvid_enc_frame.bitstream = frame;
  381. xvid_enc_frame.length = buf_size;
  382. /* Initialize input image fields */
  383. if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
  384. av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
  385. return -1;
  386. }
  387. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  388. for( i = 0; i < 4; i++ ) {
  389. xvid_enc_frame.input.plane[i] = picture->data[i];
  390. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  391. }
  392. /* Encoder Flags */
  393. xvid_enc_frame.vop_flags = x->vop_flags;
  394. xvid_enc_frame.vol_flags = x->vol_flags;
  395. xvid_enc_frame.motion = x->me_flags;
  396. xvid_enc_frame.type = XVID_TYPE_AUTO;
  397. /* Pixel aspect ratio setting */
  398. if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
  399. avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
  400. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  401. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  402. return -1;
  403. }
  404. xvid_enc_frame.par = XVID_PAR_EXT;
  405. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  406. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  407. /* Quant Setting */
  408. if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  409. else xvid_enc_frame.quant = 0;
  410. /* Matrices */
  411. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  412. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  413. /* Encode */
  414. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  415. &xvid_enc_frame, &xvid_enc_stats);
  416. /* Two-pass log buffer swapping */
  417. avctx->stats_out = NULL;
  418. if( x->twopassbuffer ) {
  419. tmp = x->old_twopassbuffer;
  420. x->old_twopassbuffer = x->twopassbuffer;
  421. x->twopassbuffer = tmp;
  422. x->twopassbuffer[0] = 0;
  423. if( x->old_twopassbuffer[0] != 0 ) {
  424. avctx->stats_out = x->old_twopassbuffer;
  425. }
  426. }
  427. if( 0 <= xerr ) {
  428. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  429. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  430. p->pict_type = FF_P_TYPE;
  431. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  432. p->pict_type = FF_B_TYPE;
  433. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  434. p->pict_type = FF_S_TYPE;
  435. else
  436. p->pict_type = FF_I_TYPE;
  437. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  438. p->key_frame = 1;
  439. if( x->quicktime_format )
  440. return xvid_strip_vol_header(avctx, frame,
  441. xvid_enc_stats.hlength, xerr);
  442. } else
  443. p->key_frame = 0;
  444. return xerr;
  445. } else {
  446. av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
  447. return -1;
  448. }
  449. }
  450. /**
  451. * Destroy the private context for the encoder.
  452. * All buffers are freed, and the Xvid encoder context is destroyed.
  453. *
  454. * @param avctx AVCodecContext pointer to context
  455. * @return Returns 0, success guaranteed
  456. */
  457. static av_cold int xvid_encode_close(AVCodecContext *avctx) {
  458. struct xvid_context *x = avctx->priv_data;
  459. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  460. if( avctx->extradata != NULL )
  461. av_freep(&avctx->extradata);
  462. if( x->twopassbuffer != NULL ) {
  463. av_free(x->twopassbuffer);
  464. av_free(x->old_twopassbuffer);
  465. }
  466. if( x->twopassfile != NULL )
  467. av_free(x->twopassfile);
  468. if( x->intra_matrix != NULL )
  469. av_free(x->intra_matrix);
  470. if( x->inter_matrix != NULL )
  471. av_free(x->inter_matrix);
  472. return 0;
  473. }
  474. /**
  475. * Routine to create a global VO/VOL header for MP4 container.
  476. * What we do here is extract the header from the Xvid bitstream
  477. * as it is encoded. We also strip the repeated headers from the
  478. * bitstream when a global header is requested for MPEG-4 ISO
  479. * compliance.
  480. *
  481. * @param avctx AVCodecContext pointer to context
  482. * @param frame Pointer to encoded frame data
  483. * @param header_len Length of header to search
  484. * @param frame_len Length of encoded frame data
  485. * @return Returns new length of frame data
  486. */
  487. int xvid_strip_vol_header(AVCodecContext *avctx,
  488. unsigned char *frame,
  489. unsigned int header_len,
  490. unsigned int frame_len) {
  491. int vo_len = 0, i;
  492. for( i = 0; i < header_len - 3; i++ ) {
  493. if( frame[i] == 0x00 &&
  494. frame[i+1] == 0x00 &&
  495. frame[i+2] == 0x01 &&
  496. frame[i+3] == 0xB6 ) {
  497. vo_len = i;
  498. break;
  499. }
  500. }
  501. if( vo_len > 0 ) {
  502. /* We need to store the header, so extract it */
  503. if( avctx->extradata == NULL ) {
  504. avctx->extradata = av_malloc(vo_len);
  505. memcpy(avctx->extradata, frame, vo_len);
  506. avctx->extradata_size = vo_len;
  507. }
  508. /* Less dangerous now, memmove properly copies the two
  509. chunks of overlapping data */
  510. memmove(frame, &(frame[vo_len]), frame_len - vo_len);
  511. return frame_len - vo_len;
  512. } else
  513. return frame_len;
  514. }
  515. /**
  516. * Routine to correct a possibly erroneous framerate being fed to us.
  517. * Xvid currently chokes on framerates where the ticks per frame is
  518. * extremely large. This function works to correct problems in this area
  519. * by estimating a new framerate and taking the simpler fraction of
  520. * the two presented.
  521. *
  522. * @param avctx Context that contains the framerate to correct.
  523. */
  524. void xvid_correct_framerate(AVCodecContext *avctx) {
  525. int frate, fbase;
  526. int est_frate, est_fbase;
  527. int gcd;
  528. float est_fps, fps;
  529. frate = avctx->time_base.den;
  530. fbase = avctx->time_base.num;
  531. gcd = av_gcd(frate, fbase);
  532. if( gcd > 1 ) {
  533. frate /= gcd;
  534. fbase /= gcd;
  535. }
  536. if( frate <= 65000 && fbase <= 65000 ) {
  537. avctx->time_base.den = frate;
  538. avctx->time_base.num = fbase;
  539. return;
  540. }
  541. fps = (float)frate / (float)fbase;
  542. est_fps = roundf(fps * 1000.0) / 1000.0;
  543. est_frate = (int)est_fps;
  544. if( est_fps > (int)est_fps ) {
  545. est_frate = (est_frate + 1) * 1000;
  546. est_fbase = (int)roundf((float)est_frate / est_fps);
  547. } else
  548. est_fbase = 1;
  549. gcd = av_gcd(est_frate, est_fbase);
  550. if( gcd > 1 ) {
  551. est_frate /= gcd;
  552. est_fbase /= gcd;
  553. }
  554. if( fbase > est_fbase ) {
  555. avctx->time_base.den = est_frate;
  556. avctx->time_base.num = est_fbase;
  557. av_log(avctx, AV_LOG_DEBUG,
  558. "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
  559. est_fps, (((est_fps - fps)/fps) * 100.0));
  560. } else {
  561. avctx->time_base.den = frate;
  562. avctx->time_base.num = fbase;
  563. }
  564. }
  565. /*
  566. * Xvid 2-Pass Kludge Section
  567. *
  568. * Xvid's default 2-pass doesn't allow us to create data as we need to, so
  569. * this section spends time replacing the first pass plugin so we can write
  570. * statistic information as libavcodec requests in. We have another kludge
  571. * that allows us to pass data to the second pass in Xvid without a custom
  572. * rate-control plugin.
  573. */
  574. /**
  575. * Initialize the two-pass plugin and context.
  576. *
  577. * @param param Input construction parameter structure
  578. * @param handle Private context handle
  579. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  580. */
  581. static int xvid_ff_2pass_create(xvid_plg_create_t * param,
  582. void ** handle) {
  583. struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *)param->param;
  584. char *log = x->context->twopassbuffer;
  585. /* Do a quick bounds check */
  586. if( log == NULL )
  587. return XVID_ERR_FAIL;
  588. /* We use snprintf() */
  589. /* This is because we can safely prevent a buffer overflow */
  590. log[0] = 0;
  591. snprintf(log, BUFFER_REMAINING(log),
  592. "# ffmpeg 2-pass log file, using xvid codec\n");
  593. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  594. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  595. XVID_VERSION_MAJOR(XVID_VERSION),
  596. XVID_VERSION_MINOR(XVID_VERSION),
  597. XVID_VERSION_PATCH(XVID_VERSION));
  598. *handle = x->context;
  599. return 0;
  600. }
  601. /**
  602. * Destroy the two-pass plugin context.
  603. *
  604. * @param ref Context pointer for the plugin
  605. * @param param Destrooy context
  606. * @return Returns 0, success guaranteed
  607. */
  608. static int xvid_ff_2pass_destroy(struct xvid_context *ref,
  609. xvid_plg_destroy_t *param) {
  610. /* Currently cannot think of anything to do on destruction */
  611. /* Still, the framework should be here for reference/use */
  612. if( ref->twopassbuffer != NULL )
  613. ref->twopassbuffer[0] = 0;
  614. return 0;
  615. }
  616. /**
  617. * Enable fast encode mode during the first pass.
  618. *
  619. * @param ref Context pointer for the plugin
  620. * @param param Frame data
  621. * @return Returns 0, success guaranteed
  622. */
  623. static int xvid_ff_2pass_before(struct xvid_context *ref,
  624. xvid_plg_data_t *param) {
  625. int motion_remove;
  626. int motion_replacements;
  627. int vop_remove;
  628. /* Nothing to do here, result is changed too much */
  629. if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
  630. return 0;
  631. /* We can implement a 'turbo' first pass mode here */
  632. param->quant = 2;
  633. /* Init values */
  634. motion_remove = ~XVID_ME_CHROMA_PVOP &
  635. ~XVID_ME_CHROMA_BVOP &
  636. ~XVID_ME_EXTSEARCH16 &
  637. ~XVID_ME_ADVANCEDDIAMOND16;
  638. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  639. XVID_ME_SKIP_DELTASEARCH |
  640. XVID_ME_FASTREFINE16 |
  641. XVID_ME_BFRAME_EARLYSTOP;
  642. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  643. ~XVID_VOP_FAST_MODEDECISION_RD &
  644. ~XVID_VOP_TRELLISQUANT &
  645. ~XVID_VOP_INTER4V &
  646. ~XVID_VOP_HQACPRED;
  647. param->vol_flags &= ~XVID_VOL_GMC;
  648. param->vop_flags &= vop_remove;
  649. param->motion_flags &= motion_remove;
  650. param->motion_flags |= motion_replacements;
  651. return 0;
  652. }
  653. /**
  654. * Capture statistic data and write it during first pass.
  655. *
  656. * @param ref Context pointer for the plugin
  657. * @param param Statistic data
  658. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  659. */
  660. static int xvid_ff_2pass_after(struct xvid_context *ref,
  661. xvid_plg_data_t *param) {
  662. char *log = ref->twopassbuffer;
  663. char *frame_types = " ipbs";
  664. char frame_type;
  665. /* Quick bounds check */
  666. if( log == NULL )
  667. return XVID_ERR_FAIL;
  668. /* Convert the type given to us into a character */
  669. if( param->type < 5 && param->type > 0 ) {
  670. frame_type = frame_types[param->type];
  671. } else {
  672. return XVID_ERR_FAIL;
  673. }
  674. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  675. "%c %d %d %d %d %d %d\n",
  676. frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
  677. param->stats.ublks, param->stats.length, param->stats.hlength);
  678. return 0;
  679. }
  680. /**
  681. * Dispatch function for our custom plugin.
  682. * This handles the dispatch for the Xvid plugin. It passes data
  683. * on to other functions for actual processing.
  684. *
  685. * @param ref Context pointer for the plugin
  686. * @param cmd The task given for us to complete
  687. * @param p1 First parameter (varies)
  688. * @param p2 Second parameter (varies)
  689. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  690. */
  691. int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
  692. switch( cmd ) {
  693. case XVID_PLG_INFO:
  694. case XVID_PLG_FRAME:
  695. return 0;
  696. case XVID_PLG_BEFORE:
  697. return xvid_ff_2pass_before(ref, p1);
  698. case XVID_PLG_CREATE:
  699. return xvid_ff_2pass_create(p1, p2);
  700. case XVID_PLG_AFTER:
  701. return xvid_ff_2pass_after(ref, p1);
  702. case XVID_PLG_DESTROY:
  703. return xvid_ff_2pass_destroy(ref, p1);
  704. default:
  705. return XVID_ERR_FAIL;
  706. }
  707. }
  708. /**
  709. * Xvid codec definition for libavcodec.
  710. */
  711. AVCodec libxvid_encoder = {
  712. "libxvid",
  713. AVMEDIA_TYPE_VIDEO,
  714. CODEC_ID_MPEG4,
  715. sizeof(struct xvid_context),
  716. xvid_encode_init,
  717. xvid_encode_frame,
  718. xvid_encode_close,
  719. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  720. .long_name= NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  721. };
  722. #endif /* CONFIG_LIBXVID_ENCODER */