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.

825 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 "libavutil/mathematics.h"
  32. #include "libxvid_internal.h"
  33. #if !HAVE_MKSTEMP
  34. #include <fcntl.h>
  35. #endif
  36. /**
  37. * Buffer management macros.
  38. */
  39. #define BUFFER_SIZE 1024
  40. #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
  41. #define BUFFER_CAT(x) (&((x)[strlen(x)]))
  42. /**
  43. * Structure for the private Xvid context.
  44. * This stores all the private context for the codec.
  45. */
  46. struct xvid_context {
  47. void *encoder_handle; /**< Handle for Xvid encoder */
  48. int xsize; /**< Frame x size */
  49. int ysize; /**< Frame y size */
  50. int vop_flags; /**< VOP flags for Xvid encoder */
  51. int vol_flags; /**< VOL flags for Xvid encoder */
  52. int me_flags; /**< Motion Estimation flags */
  53. int qscale; /**< Do we use constant scale? */
  54. int quicktime_format; /**< Are we in a QT-based format? */
  55. AVFrame encoded_picture; /**< Encoded frame information */
  56. char *twopassbuffer; /**< Character buffer for two-pass */
  57. char *old_twopassbuffer; /**< Old character buffer (two-pass) */
  58. char *twopassfile; /**< second pass temp file name */
  59. unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
  60. unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
  61. };
  62. /**
  63. * Structure for the private first-pass plugin.
  64. */
  65. struct xvid_ff_pass1 {
  66. int version; /**< Xvid version */
  67. struct xvid_context *context; /**< Pointer to private context */
  68. };
  69. /* Prototypes - See function implementation for details */
  70. int xvid_strip_vol_header(AVCodecContext *avctx, unsigned char *frame, unsigned int header_len, unsigned int frame_len);
  71. int xvid_ff_2pass(void *ref, int opt, void *p1, void *p2);
  72. void xvid_correct_framerate(AVCodecContext *avctx);
  73. /* Wrapper to work around the lack of mkstemp() on mingw.
  74. * Also, tries to create file in /tmp first, if possible.
  75. * *prefix can be a character constant; *filename will be allocated internally.
  76. * @return file descriptor of opened file (or -1 on error)
  77. * and opened file name in **filename. */
  78. int ff_tempfile(const char *prefix, char **filename) {
  79. int fd=-1;
  80. #if !HAVE_MKSTEMP
  81. *filename = tempnam(".", prefix);
  82. #else
  83. size_t len = strlen(prefix) + 12; /* room for "/tmp/" and "XXXXXX\0" */
  84. *filename = av_malloc(len);
  85. #endif
  86. /* -----common section-----*/
  87. if (*filename == NULL) {
  88. av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot allocate file name\n");
  89. return -1;
  90. }
  91. #if !HAVE_MKSTEMP
  92. fd = open(*filename, O_RDWR | O_BINARY | O_CREAT, 0444);
  93. #else
  94. snprintf(*filename, len, "/tmp/%sXXXXXX", prefix);
  95. fd = mkstemp(*filename);
  96. if (fd < 0) {
  97. snprintf(*filename, len, "./%sXXXXXX", prefix);
  98. fd = mkstemp(*filename);
  99. }
  100. #endif
  101. /* -----common section-----*/
  102. if (fd < 0) {
  103. av_log(NULL, AV_LOG_ERROR, "ff_tempfile: Cannot open temporary file %s\n", *filename);
  104. return -1;
  105. }
  106. return fd; /* success */
  107. }
  108. #if CONFIG_LIBXVID_ENCODER
  109. /**
  110. * Create the private context for the encoder.
  111. * All buffers are allocated, settings are loaded from the user,
  112. * and the encoder context created.
  113. *
  114. * @param avctx AVCodecContext pointer to context
  115. * @return Returns 0 on success, -1 on failure
  116. */
  117. static av_cold int xvid_encode_init(AVCodecContext *avctx) {
  118. int xerr, i;
  119. int xvid_flags = avctx->flags;
  120. struct xvid_context *x = avctx->priv_data;
  121. uint16_t *intra, *inter;
  122. int fd;
  123. xvid_plugin_single_t single;
  124. struct xvid_ff_pass1 rc2pass1;
  125. xvid_plugin_2pass2_t rc2pass2;
  126. xvid_gbl_init_t xvid_gbl_init;
  127. xvid_enc_create_t xvid_enc_create;
  128. xvid_enc_plugin_t plugins[7];
  129. /* Bring in VOP flags from ffmpeg command-line */
  130. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  131. if( xvid_flags & CODEC_FLAG_4MV )
  132. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  133. if( avctx->trellis
  134. )
  135. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  136. if( xvid_flags & CODEC_FLAG_AC_PRED )
  137. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  138. if( xvid_flags & CODEC_FLAG_GRAY )
  139. x->vop_flags |= XVID_VOP_GREYSCALE;
  140. /* Decide which ME quality setting to use */
  141. x->me_flags = 0;
  142. switch( avctx->me_method ) {
  143. case ME_FULL: /* Quality 6 */
  144. x->me_flags |= XVID_ME_EXTSEARCH16
  145. | XVID_ME_EXTSEARCH8;
  146. case ME_EPZS: /* Quality 4 */
  147. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8
  148. | XVID_ME_HALFPELREFINE8
  149. | XVID_ME_CHROMA_PVOP
  150. | XVID_ME_CHROMA_BVOP;
  151. case ME_LOG: /* Quality 2 */
  152. case ME_PHODS:
  153. case ME_X1:
  154. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16
  155. | XVID_ME_HALFPELREFINE16;
  156. case ME_ZERO: /* Quality 0 */
  157. default:
  158. break;
  159. }
  160. /* Decide how we should decide blocks */
  161. switch( avctx->mb_decision ) {
  162. case 2:
  163. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  164. x->me_flags |= XVID_ME_HALFPELREFINE8_RD
  165. | XVID_ME_QUARTERPELREFINE8_RD
  166. | XVID_ME_EXTSEARCH_RD
  167. | XVID_ME_CHECKPREDICTION_RD;
  168. case 1:
  169. if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
  170. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  171. x->me_flags |= XVID_ME_HALFPELREFINE16_RD
  172. | XVID_ME_QUARTERPELREFINE16_RD;
  173. default:
  174. break;
  175. }
  176. /* Bring in VOL flags from ffmpeg command-line */
  177. x->vol_flags = 0;
  178. if( xvid_flags & CODEC_FLAG_GMC ) {
  179. x->vol_flags |= XVID_VOL_GMC;
  180. x->me_flags |= XVID_ME_GME_REFINE;
  181. }
  182. if( xvid_flags & CODEC_FLAG_QPEL ) {
  183. x->vol_flags |= XVID_VOL_QUARTERPEL;
  184. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  185. if( x->vop_flags & XVID_VOP_INTER4V )
  186. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  187. }
  188. memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
  189. xvid_gbl_init.version = XVID_VERSION;
  190. xvid_gbl_init.debug = 0;
  191. #if ARCH_PPC
  192. /* Xvid's PPC support is borked, use libavcodec to detect */
  193. #if HAVE_ALTIVEC
  194. if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
  195. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
  196. } else
  197. #endif
  198. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
  199. #else
  200. /* Xvid can detect on x86 */
  201. xvid_gbl_init.cpu_flags = 0;
  202. #endif
  203. /* Initialize */
  204. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  205. /* Create the encoder reference */
  206. memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
  207. xvid_enc_create.version = XVID_VERSION;
  208. /* Store the desired frame size */
  209. xvid_enc_create.width = x->xsize = avctx->width;
  210. xvid_enc_create.height = x->ysize = avctx->height;
  211. /* Xvid can determine the proper profile to use */
  212. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  213. /* We don't use zones */
  214. xvid_enc_create.zones = NULL;
  215. xvid_enc_create.num_zones = 0;
  216. xvid_enc_create.num_threads = avctx->thread_count;
  217. xvid_enc_create.plugins = plugins;
  218. xvid_enc_create.num_plugins = 0;
  219. /* Initialize Buffers */
  220. x->twopassbuffer = NULL;
  221. x->old_twopassbuffer = NULL;
  222. x->twopassfile = NULL;
  223. if( xvid_flags & CODEC_FLAG_PASS1 ) {
  224. memset(&rc2pass1, 0, sizeof(struct xvid_ff_pass1));
  225. rc2pass1.version = XVID_VERSION;
  226. rc2pass1.context = x;
  227. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  228. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  229. if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
  230. av_log(avctx, AV_LOG_ERROR,
  231. "Xvid: Cannot allocate 2-pass log buffers\n");
  232. return -1;
  233. }
  234. x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
  235. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  236. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  237. xvid_enc_create.num_plugins++;
  238. } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
  239. memset(&rc2pass2, 0, sizeof(xvid_plugin_2pass2_t));
  240. rc2pass2.version = XVID_VERSION;
  241. rc2pass2.bitrate = avctx->bit_rate;
  242. fd = ff_tempfile("xvidff.", &(x->twopassfile));
  243. if( fd == -1 ) {
  244. av_log(avctx, AV_LOG_ERROR,
  245. "Xvid: Cannot write 2-pass pipe\n");
  246. return -1;
  247. }
  248. if( avctx->stats_in == NULL ) {
  249. av_log(avctx, AV_LOG_ERROR,
  250. "Xvid: No 2-pass information loaded for second pass\n");
  251. return -1;
  252. }
  253. if( strlen(avctx->stats_in) >
  254. write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
  255. close(fd);
  256. av_log(avctx, AV_LOG_ERROR,
  257. "Xvid: Cannot write to 2-pass pipe\n");
  258. return -1;
  259. }
  260. close(fd);
  261. rc2pass2.filename = x->twopassfile;
  262. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  263. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  264. xvid_enc_create.num_plugins++;
  265. } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
  266. /* Single Pass Bitrate Control! */
  267. memset(&single, 0, sizeof(xvid_plugin_single_t));
  268. single.version = XVID_VERSION;
  269. single.bitrate = avctx->bit_rate;
  270. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  271. plugins[xvid_enc_create.num_plugins].param = &single;
  272. xvid_enc_create.num_plugins++;
  273. }
  274. /* Luminance Masking */
  275. if( 0.0 != avctx->lumi_masking ) {
  276. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  277. plugins[xvid_enc_create.num_plugins].param = NULL;
  278. xvid_enc_create.num_plugins++;
  279. }
  280. /* Frame Rate and Key Frames */
  281. xvid_correct_framerate(avctx);
  282. xvid_enc_create.fincr = avctx->time_base.num;
  283. xvid_enc_create.fbase = avctx->time_base.den;
  284. if( avctx->gop_size > 0 )
  285. xvid_enc_create.max_key_interval = avctx->gop_size;
  286. else
  287. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  288. /* Quants */
  289. if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
  290. else x->qscale = 0;
  291. xvid_enc_create.min_quant[0] = avctx->qmin;
  292. xvid_enc_create.min_quant[1] = avctx->qmin;
  293. xvid_enc_create.min_quant[2] = avctx->qmin;
  294. xvid_enc_create.max_quant[0] = avctx->qmax;
  295. xvid_enc_create.max_quant[1] = avctx->qmax;
  296. xvid_enc_create.max_quant[2] = avctx->qmax;
  297. /* Quant Matrices */
  298. x->intra_matrix = x->inter_matrix = NULL;
  299. if( avctx->mpeg_quant )
  300. x->vol_flags |= XVID_VOL_MPEGQUANT;
  301. if( (avctx->intra_matrix || avctx->inter_matrix) ) {
  302. x->vol_flags |= XVID_VOL_MPEGQUANT;
  303. if( avctx->intra_matrix ) {
  304. intra = avctx->intra_matrix;
  305. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  306. } else
  307. intra = NULL;
  308. if( avctx->inter_matrix ) {
  309. inter = avctx->inter_matrix;
  310. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  311. } else
  312. inter = NULL;
  313. for( i = 0; i < 64; i++ ) {
  314. if( intra )
  315. x->intra_matrix[i] = (unsigned char)intra[i];
  316. if( inter )
  317. x->inter_matrix[i] = (unsigned char)inter[i];
  318. }
  319. }
  320. /* Misc Settings */
  321. xvid_enc_create.frame_drop_ratio = 0;
  322. xvid_enc_create.global = 0;
  323. if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
  324. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  325. /* Determines which codec mode we are operating in */
  326. avctx->extradata = NULL;
  327. avctx->extradata_size = 0;
  328. if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
  329. /* In this case, we are claiming to be MPEG4 */
  330. x->quicktime_format = 1;
  331. avctx->codec_id = CODEC_ID_MPEG4;
  332. } else {
  333. /* We are claiming to be Xvid */
  334. x->quicktime_format = 0;
  335. if(!avctx->codec_tag)
  336. avctx->codec_tag = AV_RL32("xvid");
  337. }
  338. /* Bframes */
  339. xvid_enc_create.max_bframes = avctx->max_b_frames;
  340. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  341. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  342. if( avctx->max_b_frames > 0 && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  343. /* Create encoder context */
  344. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  345. if( xerr ) {
  346. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  347. return -1;
  348. }
  349. x->encoder_handle = xvid_enc_create.handle;
  350. avctx->coded_frame = &x->encoded_picture;
  351. return 0;
  352. }
  353. /**
  354. * Encode a single frame.
  355. *
  356. * @param avctx AVCodecContext pointer to context
  357. * @param frame Pointer to encoded frame buffer
  358. * @param buf_size Size of encoded frame buffer
  359. * @param data Pointer to AVFrame of unencoded frame
  360. * @return Returns 0 on success, -1 on failure
  361. */
  362. static int xvid_encode_frame(AVCodecContext *avctx,
  363. unsigned char *frame, int buf_size, void *data) {
  364. int xerr, i;
  365. char *tmp;
  366. struct xvid_context *x = avctx->priv_data;
  367. AVFrame *picture = data;
  368. AVFrame *p = &(x->encoded_picture);
  369. xvid_enc_frame_t xvid_enc_frame;
  370. xvid_enc_stats_t xvid_enc_stats;
  371. /* Start setting up the frame */
  372. memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
  373. xvid_enc_frame.version = XVID_VERSION;
  374. memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
  375. xvid_enc_stats.version = XVID_VERSION;
  376. *p = *picture;
  377. /* Let Xvid know where to put the frame. */
  378. xvid_enc_frame.bitstream = frame;
  379. xvid_enc_frame.length = buf_size;
  380. /* Initialize input image fields */
  381. if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
  382. av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
  383. return -1;
  384. }
  385. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  386. for( i = 0; i < 4; i++ ) {
  387. xvid_enc_frame.input.plane[i] = picture->data[i];
  388. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  389. }
  390. /* Encoder Flags */
  391. xvid_enc_frame.vop_flags = x->vop_flags;
  392. xvid_enc_frame.vol_flags = x->vol_flags;
  393. xvid_enc_frame.motion = x->me_flags;
  394. xvid_enc_frame.type =
  395. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  396. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  397. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  398. XVID_TYPE_AUTO;
  399. /* Pixel aspect ratio setting */
  400. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||
  401. avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {
  402. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  403. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  404. return -1;
  405. }
  406. xvid_enc_frame.par = XVID_PAR_EXT;
  407. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  408. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  409. /* Quant Setting */
  410. if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  411. else xvid_enc_frame.quant = 0;
  412. /* Matrices */
  413. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  414. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  415. /* Encode */
  416. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  417. &xvid_enc_frame, &xvid_enc_stats);
  418. /* Two-pass log buffer swapping */
  419. avctx->stats_out = NULL;
  420. if( x->twopassbuffer ) {
  421. tmp = x->old_twopassbuffer;
  422. x->old_twopassbuffer = x->twopassbuffer;
  423. x->twopassbuffer = tmp;
  424. x->twopassbuffer[0] = 0;
  425. if( x->old_twopassbuffer[0] != 0 ) {
  426. avctx->stats_out = x->old_twopassbuffer;
  427. }
  428. }
  429. if( 0 <= xerr ) {
  430. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  431. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  432. p->pict_type = AV_PICTURE_TYPE_P;
  433. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  434. p->pict_type = AV_PICTURE_TYPE_B;
  435. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  436. p->pict_type = AV_PICTURE_TYPE_S;
  437. else
  438. p->pict_type = AV_PICTURE_TYPE_I;
  439. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  440. p->key_frame = 1;
  441. if( x->quicktime_format )
  442. return xvid_strip_vol_header(avctx, frame,
  443. xvid_enc_stats.hlength, xerr);
  444. } else
  445. p->key_frame = 0;
  446. return xerr;
  447. } else {
  448. av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
  449. return -1;
  450. }
  451. }
  452. /**
  453. * Destroy the private context for the encoder.
  454. * All buffers are freed, and the Xvid encoder context is destroyed.
  455. *
  456. * @param avctx AVCodecContext pointer to context
  457. * @return Returns 0, success guaranteed
  458. */
  459. static av_cold int xvid_encode_close(AVCodecContext *avctx) {
  460. struct xvid_context *x = avctx->priv_data;
  461. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  462. av_freep(&avctx->extradata);
  463. if( x->twopassbuffer != NULL ) {
  464. av_free(x->twopassbuffer);
  465. av_free(x->old_twopassbuffer);
  466. avctx->stats_out = NULL;
  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. const 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. .name = "libxvid",
  712. .type = AVMEDIA_TYPE_VIDEO,
  713. .id = CODEC_ID_MPEG4,
  714. .priv_data_size = sizeof(struct xvid_context),
  715. .init = xvid_encode_init,
  716. .encode = xvid_encode_frame,
  717. .close = 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 */