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.

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