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.

842 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 Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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 "libavutil/mathematics.h"
  32. #include "libxvid_internal.h"
  33. #include "mpegvideo.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, AVPacket *pkt, 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 avconv 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 avconv 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, AVPacket *pkt,
  364. const AVFrame *picture, int *got_packet)
  365. {
  366. int xerr, i, ret, user_packet = !!pkt->data;
  367. char *tmp;
  368. struct xvid_context *x = avctx->priv_data;
  369. AVFrame *p = &x->encoded_picture;
  370. int mb_width = (avctx->width + 15) / 16;
  371. int mb_height = (avctx->height + 15) / 16;
  372. xvid_enc_frame_t xvid_enc_frame;
  373. xvid_enc_stats_t xvid_enc_stats;
  374. if (!user_packet &&
  375. (ret = av_new_packet(pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0) {
  376. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  377. return ret;
  378. }
  379. /* Start setting up the frame */
  380. memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
  381. xvid_enc_frame.version = XVID_VERSION;
  382. memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
  383. xvid_enc_stats.version = XVID_VERSION;
  384. *p = *picture;
  385. /* Let Xvid know where to put the frame. */
  386. xvid_enc_frame.bitstream = pkt->data;
  387. xvid_enc_frame.length = pkt->size;
  388. /* Initialize input image fields */
  389. if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
  390. av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
  391. return -1;
  392. }
  393. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  394. for( i = 0; i < 4; i++ ) {
  395. xvid_enc_frame.input.plane[i] = picture->data[i];
  396. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  397. }
  398. /* Encoder Flags */
  399. xvid_enc_frame.vop_flags = x->vop_flags;
  400. xvid_enc_frame.vol_flags = x->vol_flags;
  401. xvid_enc_frame.motion = x->me_flags;
  402. xvid_enc_frame.type =
  403. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  404. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  405. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  406. XVID_TYPE_AUTO;
  407. /* Pixel aspect ratio setting */
  408. if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
  409. avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
  410. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  411. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  412. return -1;
  413. }
  414. xvid_enc_frame.par = XVID_PAR_EXT;
  415. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  416. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  417. /* Quant Setting */
  418. if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  419. else xvid_enc_frame.quant = 0;
  420. /* Matrices */
  421. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  422. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  423. /* Encode */
  424. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  425. &xvid_enc_frame, &xvid_enc_stats);
  426. /* Two-pass log buffer swapping */
  427. avctx->stats_out = NULL;
  428. if( x->twopassbuffer ) {
  429. tmp = x->old_twopassbuffer;
  430. x->old_twopassbuffer = x->twopassbuffer;
  431. x->twopassbuffer = tmp;
  432. x->twopassbuffer[0] = 0;
  433. if( x->old_twopassbuffer[0] != 0 ) {
  434. avctx->stats_out = x->old_twopassbuffer;
  435. }
  436. }
  437. if (xerr > 0) {
  438. *got_packet = 1;
  439. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  440. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  441. p->pict_type = AV_PICTURE_TYPE_P;
  442. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  443. p->pict_type = AV_PICTURE_TYPE_B;
  444. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  445. p->pict_type = AV_PICTURE_TYPE_S;
  446. else
  447. p->pict_type = AV_PICTURE_TYPE_I;
  448. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  449. p->key_frame = 1;
  450. pkt->flags |= AV_PKT_FLAG_KEY;
  451. if( x->quicktime_format )
  452. return xvid_strip_vol_header(avctx, pkt,
  453. xvid_enc_stats.hlength, xerr);
  454. } else
  455. p->key_frame = 0;
  456. pkt->size = xerr;
  457. return 0;
  458. } else {
  459. if (!user_packet)
  460. av_free_packet(pkt);
  461. if (!xerr)
  462. return 0;
  463. av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
  464. return -1;
  465. }
  466. }
  467. /**
  468. * Destroy the private context for the encoder.
  469. * All buffers are freed, and the Xvid encoder context is destroyed.
  470. *
  471. * @param avctx AVCodecContext pointer to context
  472. * @return Returns 0, success guaranteed
  473. */
  474. static av_cold int xvid_encode_close(AVCodecContext *avctx) {
  475. struct xvid_context *x = avctx->priv_data;
  476. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  477. av_freep(&avctx->extradata);
  478. if( x->twopassbuffer != NULL ) {
  479. av_free(x->twopassbuffer);
  480. av_free(x->old_twopassbuffer);
  481. }
  482. av_free(x->twopassfile);
  483. av_free(x->intra_matrix);
  484. av_free(x->inter_matrix);
  485. return 0;
  486. }
  487. /**
  488. * Routine to create a global VO/VOL header for MP4 container.
  489. * What we do here is extract the header from the Xvid bitstream
  490. * as it is encoded. We also strip the repeated headers from the
  491. * bitstream when a global header is requested for MPEG-4 ISO
  492. * compliance.
  493. *
  494. * @param avctx AVCodecContext pointer to context
  495. * @param frame Pointer to encoded frame data
  496. * @param header_len Length of header to search
  497. * @param frame_len Length of encoded frame data
  498. * @return Returns new length of frame data
  499. */
  500. int xvid_strip_vol_header(AVCodecContext *avctx,
  501. AVPacket *pkt,
  502. unsigned int header_len,
  503. unsigned int frame_len) {
  504. int vo_len = 0, i;
  505. for( i = 0; i < header_len - 3; i++ ) {
  506. if( pkt->data[i] == 0x00 &&
  507. pkt->data[i+1] == 0x00 &&
  508. pkt->data[i+2] == 0x01 &&
  509. pkt->data[i+3] == 0xB6 ) {
  510. vo_len = i;
  511. break;
  512. }
  513. }
  514. if( vo_len > 0 ) {
  515. /* We need to store the header, so extract it */
  516. if( avctx->extradata == NULL ) {
  517. avctx->extradata = av_malloc(vo_len);
  518. memcpy(avctx->extradata, pkt->data, vo_len);
  519. avctx->extradata_size = vo_len;
  520. }
  521. /* Less dangerous now, memmove properly copies the two
  522. chunks of overlapping data */
  523. memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
  524. pkt->size = frame_len - vo_len;
  525. }
  526. return 0;
  527. }
  528. /**
  529. * Routine to correct a possibly erroneous framerate being fed to us.
  530. * Xvid currently chokes on framerates where the ticks per frame is
  531. * extremely large. This function works to correct problems in this area
  532. * by estimating a new framerate and taking the simpler fraction of
  533. * the two presented.
  534. *
  535. * @param avctx Context that contains the framerate to correct.
  536. */
  537. void xvid_correct_framerate(AVCodecContext *avctx) {
  538. int frate, fbase;
  539. int est_frate, est_fbase;
  540. int gcd;
  541. float est_fps, fps;
  542. frate = avctx->time_base.den;
  543. fbase = avctx->time_base.num;
  544. gcd = av_gcd(frate, fbase);
  545. if( gcd > 1 ) {
  546. frate /= gcd;
  547. fbase /= gcd;
  548. }
  549. if( frate <= 65000 && fbase <= 65000 ) {
  550. avctx->time_base.den = frate;
  551. avctx->time_base.num = fbase;
  552. return;
  553. }
  554. fps = (float)frate / (float)fbase;
  555. est_fps = roundf(fps * 1000.0) / 1000.0;
  556. est_frate = (int)est_fps;
  557. if( est_fps > (int)est_fps ) {
  558. est_frate = (est_frate + 1) * 1000;
  559. est_fbase = (int)roundf((float)est_frate / est_fps);
  560. } else
  561. est_fbase = 1;
  562. gcd = av_gcd(est_frate, est_fbase);
  563. if( gcd > 1 ) {
  564. est_frate /= gcd;
  565. est_fbase /= gcd;
  566. }
  567. if( fbase > est_fbase ) {
  568. avctx->time_base.den = est_frate;
  569. avctx->time_base.num = est_fbase;
  570. av_log(avctx, AV_LOG_DEBUG,
  571. "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
  572. est_fps, (((est_fps - fps)/fps) * 100.0));
  573. } else {
  574. avctx->time_base.den = frate;
  575. avctx->time_base.num = fbase;
  576. }
  577. }
  578. /*
  579. * Xvid 2-Pass Kludge Section
  580. *
  581. * Xvid's default 2-pass doesn't allow us to create data as we need to, so
  582. * this section spends time replacing the first pass plugin so we can write
  583. * statistic information as libavcodec requests in. We have another kludge
  584. * that allows us to pass data to the second pass in Xvid without a custom
  585. * rate-control plugin.
  586. */
  587. /**
  588. * Initialize the two-pass plugin and context.
  589. *
  590. * @param param Input construction parameter structure
  591. * @param handle Private context handle
  592. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  593. */
  594. static int xvid_ff_2pass_create(xvid_plg_create_t * param,
  595. void ** handle) {
  596. struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *)param->param;
  597. char *log = x->context->twopassbuffer;
  598. /* Do a quick bounds check */
  599. if( log == NULL )
  600. return XVID_ERR_FAIL;
  601. /* We use snprintf() */
  602. /* This is because we can safely prevent a buffer overflow */
  603. log[0] = 0;
  604. snprintf(log, BUFFER_REMAINING(log),
  605. "# avconv 2-pass log file, using xvid codec\n");
  606. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  607. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  608. XVID_VERSION_MAJOR(XVID_VERSION),
  609. XVID_VERSION_MINOR(XVID_VERSION),
  610. XVID_VERSION_PATCH(XVID_VERSION));
  611. *handle = x->context;
  612. return 0;
  613. }
  614. /**
  615. * Destroy the two-pass plugin context.
  616. *
  617. * @param ref Context pointer for the plugin
  618. * @param param Destrooy context
  619. * @return Returns 0, success guaranteed
  620. */
  621. static int xvid_ff_2pass_destroy(struct xvid_context *ref,
  622. xvid_plg_destroy_t *param) {
  623. /* Currently cannot think of anything to do on destruction */
  624. /* Still, the framework should be here for reference/use */
  625. if( ref->twopassbuffer != NULL )
  626. ref->twopassbuffer[0] = 0;
  627. return 0;
  628. }
  629. /**
  630. * Enable fast encode mode during the first pass.
  631. *
  632. * @param ref Context pointer for the plugin
  633. * @param param Frame data
  634. * @return Returns 0, success guaranteed
  635. */
  636. static int xvid_ff_2pass_before(struct xvid_context *ref,
  637. xvid_plg_data_t *param) {
  638. int motion_remove;
  639. int motion_replacements;
  640. int vop_remove;
  641. /* Nothing to do here, result is changed too much */
  642. if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
  643. return 0;
  644. /* We can implement a 'turbo' first pass mode here */
  645. param->quant = 2;
  646. /* Init values */
  647. motion_remove = ~XVID_ME_CHROMA_PVOP &
  648. ~XVID_ME_CHROMA_BVOP &
  649. ~XVID_ME_EXTSEARCH16 &
  650. ~XVID_ME_ADVANCEDDIAMOND16;
  651. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  652. XVID_ME_SKIP_DELTASEARCH |
  653. XVID_ME_FASTREFINE16 |
  654. XVID_ME_BFRAME_EARLYSTOP;
  655. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  656. ~XVID_VOP_FAST_MODEDECISION_RD &
  657. ~XVID_VOP_TRELLISQUANT &
  658. ~XVID_VOP_INTER4V &
  659. ~XVID_VOP_HQACPRED;
  660. param->vol_flags &= ~XVID_VOL_GMC;
  661. param->vop_flags &= vop_remove;
  662. param->motion_flags &= motion_remove;
  663. param->motion_flags |= motion_replacements;
  664. return 0;
  665. }
  666. /**
  667. * Capture statistic data and write it during first pass.
  668. *
  669. * @param ref Context pointer for the plugin
  670. * @param param Statistic data
  671. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  672. */
  673. static int xvid_ff_2pass_after(struct xvid_context *ref,
  674. xvid_plg_data_t *param) {
  675. char *log = ref->twopassbuffer;
  676. const char *frame_types = " ipbs";
  677. char frame_type;
  678. /* Quick bounds check */
  679. if( log == NULL )
  680. return XVID_ERR_FAIL;
  681. /* Convert the type given to us into a character */
  682. if( param->type < 5 && param->type > 0 ) {
  683. frame_type = frame_types[param->type];
  684. } else {
  685. return XVID_ERR_FAIL;
  686. }
  687. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  688. "%c %d %d %d %d %d %d\n",
  689. frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
  690. param->stats.ublks, param->stats.length, param->stats.hlength);
  691. return 0;
  692. }
  693. /**
  694. * Dispatch function for our custom plugin.
  695. * This handles the dispatch for the Xvid plugin. It passes data
  696. * on to other functions for actual processing.
  697. *
  698. * @param ref Context pointer for the plugin
  699. * @param cmd The task given for us to complete
  700. * @param p1 First parameter (varies)
  701. * @param p2 Second parameter (varies)
  702. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  703. */
  704. int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
  705. switch( cmd ) {
  706. case XVID_PLG_INFO:
  707. case XVID_PLG_FRAME:
  708. return 0;
  709. case XVID_PLG_BEFORE:
  710. return xvid_ff_2pass_before(ref, p1);
  711. case XVID_PLG_CREATE:
  712. return xvid_ff_2pass_create(p1, p2);
  713. case XVID_PLG_AFTER:
  714. return xvid_ff_2pass_after(ref, p1);
  715. case XVID_PLG_DESTROY:
  716. return xvid_ff_2pass_destroy(ref, p1);
  717. default:
  718. return XVID_ERR_FAIL;
  719. }
  720. }
  721. /**
  722. * Xvid codec definition for libavcodec.
  723. */
  724. AVCodec ff_libxvid_encoder = {
  725. .name = "libxvid",
  726. .type = AVMEDIA_TYPE_VIDEO,
  727. .id = CODEC_ID_MPEG4,
  728. .priv_data_size = sizeof(struct xvid_context),
  729. .init = xvid_encode_init,
  730. .encode2 = xvid_encode_frame,
  731. .close = xvid_encode_close,
  732. .pix_fmts= (const enum PixelFormat[]){PIX_FMT_YUV420P, PIX_FMT_NONE},
  733. .long_name= NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  734. };
  735. #endif /* CONFIG_LIBXVID_ENCODER */