You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

823 lines
26KB

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