libxvidff.c 27 KB

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