libxvidff.c 26 KB

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