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.

831 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. /**
  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 = { 0 };
  124. struct xvid_ff_pass1 rc2pass1 = { 0 };
  125. xvid_plugin_2pass2_t rc2pass2 = { 0 };
  126. xvid_gbl_init_t xvid_gbl_init = { 0 };
  127. xvid_enc_create_t xvid_enc_create = { 0 };
  128. xvid_enc_plugin_t plugins[7];
  129. /* Bring in VOP flags from avconv 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 avconv 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. xvid_gbl_init.version = XVID_VERSION;
  189. xvid_gbl_init.debug = 0;
  190. #if ARCH_PPC
  191. /* Xvid's PPC support is borked, use libavcodec to detect */
  192. #if HAVE_ALTIVEC
  193. if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
  194. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
  195. } else
  196. #endif
  197. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
  198. #else
  199. /* Xvid can detect on x86 */
  200. xvid_gbl_init.cpu_flags = 0;
  201. #endif
  202. /* Initialize */
  203. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  204. /* Create the encoder reference */
  205. xvid_enc_create.version = XVID_VERSION;
  206. /* Store the desired frame size */
  207. xvid_enc_create.width = x->xsize = avctx->width;
  208. xvid_enc_create.height = x->ysize = avctx->height;
  209. /* Xvid can determine the proper profile to use */
  210. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  211. /* We don't use zones */
  212. xvid_enc_create.zones = NULL;
  213. xvid_enc_create.num_zones = 0;
  214. xvid_enc_create.num_threads = avctx->thread_count;
  215. xvid_enc_create.plugins = plugins;
  216. xvid_enc_create.num_plugins = 0;
  217. /* Initialize Buffers */
  218. x->twopassbuffer = NULL;
  219. x->old_twopassbuffer = NULL;
  220. x->twopassfile = NULL;
  221. if( xvid_flags & CODEC_FLAG_PASS1 ) {
  222. rc2pass1.version = XVID_VERSION;
  223. rc2pass1.context = x;
  224. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  225. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  226. if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
  227. av_log(avctx, AV_LOG_ERROR,
  228. "Xvid: Cannot allocate 2-pass log buffers\n");
  229. return -1;
  230. }
  231. x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
  232. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  233. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  234. xvid_enc_create.num_plugins++;
  235. } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
  236. rc2pass2.version = XVID_VERSION;
  237. rc2pass2.bitrate = avctx->bit_rate;
  238. fd = ff_tempfile("xvidff.", &x->twopassfile);
  239. if( fd == -1 ) {
  240. av_log(avctx, AV_LOG_ERROR,
  241. "Xvid: Cannot write 2-pass pipe\n");
  242. return -1;
  243. }
  244. if( avctx->stats_in == NULL ) {
  245. av_log(avctx, AV_LOG_ERROR,
  246. "Xvid: No 2-pass information loaded for second pass\n");
  247. return -1;
  248. }
  249. if( strlen(avctx->stats_in) >
  250. write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
  251. close(fd);
  252. av_log(avctx, AV_LOG_ERROR,
  253. "Xvid: Cannot write to 2-pass pipe\n");
  254. return -1;
  255. }
  256. close(fd);
  257. rc2pass2.filename = x->twopassfile;
  258. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  259. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  260. xvid_enc_create.num_plugins++;
  261. } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
  262. /* Single Pass Bitrate Control! */
  263. single.version = XVID_VERSION;
  264. single.bitrate = avctx->bit_rate;
  265. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  266. plugins[xvid_enc_create.num_plugins].param = &single;
  267. xvid_enc_create.num_plugins++;
  268. }
  269. /* Luminance Masking */
  270. if( 0.0 != avctx->lumi_masking ) {
  271. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  272. plugins[xvid_enc_create.num_plugins].param = NULL;
  273. xvid_enc_create.num_plugins++;
  274. }
  275. /* Frame Rate and Key Frames */
  276. xvid_correct_framerate(avctx);
  277. xvid_enc_create.fincr = avctx->time_base.num;
  278. xvid_enc_create.fbase = avctx->time_base.den;
  279. if( avctx->gop_size > 0 )
  280. xvid_enc_create.max_key_interval = avctx->gop_size;
  281. else
  282. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  283. /* Quants */
  284. if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
  285. else x->qscale = 0;
  286. xvid_enc_create.min_quant[0] = avctx->qmin;
  287. xvid_enc_create.min_quant[1] = avctx->qmin;
  288. xvid_enc_create.min_quant[2] = avctx->qmin;
  289. xvid_enc_create.max_quant[0] = avctx->qmax;
  290. xvid_enc_create.max_quant[1] = avctx->qmax;
  291. xvid_enc_create.max_quant[2] = avctx->qmax;
  292. /* Quant Matrices */
  293. x->intra_matrix = x->inter_matrix = NULL;
  294. if( avctx->mpeg_quant )
  295. x->vol_flags |= XVID_VOL_MPEGQUANT;
  296. if( (avctx->intra_matrix || avctx->inter_matrix) ) {
  297. x->vol_flags |= XVID_VOL_MPEGQUANT;
  298. if( avctx->intra_matrix ) {
  299. intra = avctx->intra_matrix;
  300. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  301. } else
  302. intra = NULL;
  303. if( avctx->inter_matrix ) {
  304. inter = avctx->inter_matrix;
  305. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  306. } else
  307. inter = NULL;
  308. for( i = 0; i < 64; i++ ) {
  309. if( intra )
  310. x->intra_matrix[i] = (unsigned char)intra[i];
  311. if( inter )
  312. x->inter_matrix[i] = (unsigned char)inter[i];
  313. }
  314. }
  315. /* Misc Settings */
  316. xvid_enc_create.frame_drop_ratio = 0;
  317. xvid_enc_create.global = 0;
  318. if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
  319. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  320. /* Determines which codec mode we are operating in */
  321. avctx->extradata = NULL;
  322. avctx->extradata_size = 0;
  323. if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
  324. /* In this case, we are claiming to be MPEG4 */
  325. x->quicktime_format = 1;
  326. avctx->codec_id = CODEC_ID_MPEG4;
  327. } else {
  328. /* We are claiming to be Xvid */
  329. x->quicktime_format = 0;
  330. if(!avctx->codec_tag)
  331. avctx->codec_tag = AV_RL32("xvid");
  332. }
  333. /* Bframes */
  334. xvid_enc_create.max_bframes = avctx->max_b_frames;
  335. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  336. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  337. if( avctx->max_b_frames > 0 && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  338. /* Create encoder context */
  339. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  340. if( xerr ) {
  341. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  342. return -1;
  343. }
  344. x->encoder_handle = xvid_enc_create.handle;
  345. avctx->coded_frame = &x->encoded_picture;
  346. return 0;
  347. }
  348. /**
  349. * Encode a single frame.
  350. *
  351. * @param avctx AVCodecContext pointer to context
  352. * @param frame Pointer to encoded frame buffer
  353. * @param buf_size Size of encoded frame buffer
  354. * @param data Pointer to AVFrame of unencoded frame
  355. * @return Returns 0 on success, -1 on failure
  356. */
  357. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  358. const AVFrame *picture, int *got_packet)
  359. {
  360. int xerr, i, ret, user_packet = !!pkt->data;
  361. char *tmp;
  362. struct xvid_context *x = avctx->priv_data;
  363. AVFrame *p = &x->encoded_picture;
  364. int mb_width = (avctx->width + 15) / 16;
  365. int mb_height = (avctx->height + 15) / 16;
  366. xvid_enc_frame_t xvid_enc_frame = { 0 };
  367. xvid_enc_stats_t xvid_enc_stats = { 0 };
  368. if (!user_packet &&
  369. (ret = av_new_packet(pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0) {
  370. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  371. return ret;
  372. }
  373. /* Start setting up the frame */
  374. xvid_enc_frame.version = XVID_VERSION;
  375. xvid_enc_stats.version = XVID_VERSION;
  376. *p = *picture;
  377. /* Let Xvid know where to put the frame. */
  378. xvid_enc_frame.bitstream = pkt->data;
  379. xvid_enc_frame.length = pkt->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 < 1 || avctx->sample_aspect_ratio.num > 255 ||
  401. avctx->sample_aspect_ratio.den < 1 || 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 (xerr > 0) {
  430. *got_packet = 1;
  431. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  432. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  433. p->pict_type = AV_PICTURE_TYPE_P;
  434. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  435. p->pict_type = AV_PICTURE_TYPE_B;
  436. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  437. p->pict_type = AV_PICTURE_TYPE_S;
  438. else
  439. p->pict_type = AV_PICTURE_TYPE_I;
  440. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  441. p->key_frame = 1;
  442. pkt->flags |= AV_PKT_FLAG_KEY;
  443. if( x->quicktime_format )
  444. return xvid_strip_vol_header(avctx, pkt,
  445. xvid_enc_stats.hlength, xerr);
  446. } else
  447. p->key_frame = 0;
  448. pkt->size = xerr;
  449. return 0;
  450. } else {
  451. if (!user_packet)
  452. av_free_packet(pkt);
  453. if (!xerr)
  454. return 0;
  455. av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
  456. return -1;
  457. }
  458. }
  459. /**
  460. * Destroy the private context for the encoder.
  461. * All buffers are freed, and the Xvid encoder context is destroyed.
  462. *
  463. * @param avctx AVCodecContext pointer to context
  464. * @return Returns 0, success guaranteed
  465. */
  466. static av_cold int xvid_encode_close(AVCodecContext *avctx) {
  467. struct xvid_context *x = avctx->priv_data;
  468. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  469. av_freep(&avctx->extradata);
  470. if( x->twopassbuffer != NULL ) {
  471. av_free(x->twopassbuffer);
  472. av_free(x->old_twopassbuffer);
  473. }
  474. av_free(x->twopassfile);
  475. av_free(x->intra_matrix);
  476. av_free(x->inter_matrix);
  477. return 0;
  478. }
  479. /**
  480. * Routine to create a global VO/VOL header for MP4 container.
  481. * What we do here is extract the header from the Xvid bitstream
  482. * as it is encoded. We also strip the repeated headers from the
  483. * bitstream when a global header is requested for MPEG-4 ISO
  484. * compliance.
  485. *
  486. * @param avctx AVCodecContext pointer to context
  487. * @param frame Pointer to encoded frame data
  488. * @param header_len Length of header to search
  489. * @param frame_len Length of encoded frame data
  490. * @return Returns new length of frame data
  491. */
  492. int xvid_strip_vol_header(AVCodecContext *avctx,
  493. AVPacket *pkt,
  494. unsigned int header_len,
  495. unsigned int frame_len) {
  496. int vo_len = 0, i;
  497. for( i = 0; i < header_len - 3; i++ ) {
  498. if( pkt->data[i] == 0x00 &&
  499. pkt->data[i+1] == 0x00 &&
  500. pkt->data[i+2] == 0x01 &&
  501. pkt->data[i+3] == 0xB6 ) {
  502. vo_len = i;
  503. break;
  504. }
  505. }
  506. if( vo_len > 0 ) {
  507. /* We need to store the header, so extract it */
  508. if( avctx->extradata == NULL ) {
  509. avctx->extradata = av_malloc(vo_len);
  510. memcpy(avctx->extradata, pkt->data, vo_len);
  511. avctx->extradata_size = vo_len;
  512. }
  513. /* Less dangerous now, memmove properly copies the two
  514. chunks of overlapping data */
  515. memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
  516. pkt->size = frame_len - vo_len;
  517. }
  518. return 0;
  519. }
  520. /**
  521. * Routine to correct a possibly erroneous framerate being fed to us.
  522. * Xvid currently chokes on framerates where the ticks per frame is
  523. * extremely large. This function works to correct problems in this area
  524. * by estimating a new framerate and taking the simpler fraction of
  525. * the two presented.
  526. *
  527. * @param avctx Context that contains the framerate to correct.
  528. */
  529. void xvid_correct_framerate(AVCodecContext *avctx) {
  530. int frate, fbase;
  531. int est_frate, est_fbase;
  532. int gcd;
  533. float est_fps, fps;
  534. frate = avctx->time_base.den;
  535. fbase = avctx->time_base.num;
  536. gcd = av_gcd(frate, fbase);
  537. if( gcd > 1 ) {
  538. frate /= gcd;
  539. fbase /= gcd;
  540. }
  541. if( frate <= 65000 && fbase <= 65000 ) {
  542. avctx->time_base.den = frate;
  543. avctx->time_base.num = fbase;
  544. return;
  545. }
  546. fps = (float)frate / (float)fbase;
  547. est_fps = roundf(fps * 1000.0) / 1000.0;
  548. est_frate = (int)est_fps;
  549. if( est_fps > (int)est_fps ) {
  550. est_frate = (est_frate + 1) * 1000;
  551. est_fbase = (int)roundf((float)est_frate / est_fps);
  552. } else
  553. est_fbase = 1;
  554. gcd = av_gcd(est_frate, est_fbase);
  555. if( gcd > 1 ) {
  556. est_frate /= gcd;
  557. est_fbase /= gcd;
  558. }
  559. if( fbase > est_fbase ) {
  560. avctx->time_base.den = est_frate;
  561. avctx->time_base.num = est_fbase;
  562. av_log(avctx, AV_LOG_DEBUG,
  563. "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
  564. est_fps, (((est_fps - fps)/fps) * 100.0));
  565. } else {
  566. avctx->time_base.den = frate;
  567. avctx->time_base.num = fbase;
  568. }
  569. }
  570. /*
  571. * Xvid 2-Pass Kludge Section
  572. *
  573. * Xvid's default 2-pass doesn't allow us to create data as we need to, so
  574. * this section spends time replacing the first pass plugin so we can write
  575. * statistic information as libavcodec requests in. We have another kludge
  576. * that allows us to pass data to the second pass in Xvid without a custom
  577. * rate-control plugin.
  578. */
  579. /**
  580. * Initialize the two-pass plugin and context.
  581. *
  582. * @param param Input construction parameter structure
  583. * @param handle Private context handle
  584. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  585. */
  586. static int xvid_ff_2pass_create(xvid_plg_create_t * param,
  587. void ** handle) {
  588. struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *)param->param;
  589. char *log = x->context->twopassbuffer;
  590. /* Do a quick bounds check */
  591. if( log == NULL )
  592. return XVID_ERR_FAIL;
  593. /* We use snprintf() */
  594. /* This is because we can safely prevent a buffer overflow */
  595. log[0] = 0;
  596. snprintf(log, BUFFER_REMAINING(log),
  597. "# avconv 2-pass log file, using xvid codec\n");
  598. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  599. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  600. XVID_VERSION_MAJOR(XVID_VERSION),
  601. XVID_VERSION_MINOR(XVID_VERSION),
  602. XVID_VERSION_PATCH(XVID_VERSION));
  603. *handle = x->context;
  604. return 0;
  605. }
  606. /**
  607. * Destroy the two-pass plugin context.
  608. *
  609. * @param ref Context pointer for the plugin
  610. * @param param Destrooy context
  611. * @return Returns 0, success guaranteed
  612. */
  613. static int xvid_ff_2pass_destroy(struct xvid_context *ref,
  614. xvid_plg_destroy_t *param) {
  615. /* Currently cannot think of anything to do on destruction */
  616. /* Still, the framework should be here for reference/use */
  617. if( ref->twopassbuffer != NULL )
  618. ref->twopassbuffer[0] = 0;
  619. return 0;
  620. }
  621. /**
  622. * Enable fast encode mode during the first pass.
  623. *
  624. * @param ref Context pointer for the plugin
  625. * @param param Frame data
  626. * @return Returns 0, success guaranteed
  627. */
  628. static int xvid_ff_2pass_before(struct xvid_context *ref,
  629. xvid_plg_data_t *param) {
  630. int motion_remove;
  631. int motion_replacements;
  632. int vop_remove;
  633. /* Nothing to do here, result is changed too much */
  634. if( param->zone && param->zone->mode == XVID_ZONE_QUANT )
  635. return 0;
  636. /* We can implement a 'turbo' first pass mode here */
  637. param->quant = 2;
  638. /* Init values */
  639. motion_remove = ~XVID_ME_CHROMA_PVOP &
  640. ~XVID_ME_CHROMA_BVOP &
  641. ~XVID_ME_EXTSEARCH16 &
  642. ~XVID_ME_ADVANCEDDIAMOND16;
  643. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  644. XVID_ME_SKIP_DELTASEARCH |
  645. XVID_ME_FASTREFINE16 |
  646. XVID_ME_BFRAME_EARLYSTOP;
  647. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  648. ~XVID_VOP_FAST_MODEDECISION_RD &
  649. ~XVID_VOP_TRELLISQUANT &
  650. ~XVID_VOP_INTER4V &
  651. ~XVID_VOP_HQACPRED;
  652. param->vol_flags &= ~XVID_VOL_GMC;
  653. param->vop_flags &= vop_remove;
  654. param->motion_flags &= motion_remove;
  655. param->motion_flags |= motion_replacements;
  656. return 0;
  657. }
  658. /**
  659. * Capture statistic data and write it during first pass.
  660. *
  661. * @param ref Context pointer for the plugin
  662. * @param param Statistic data
  663. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  664. */
  665. static int xvid_ff_2pass_after(struct xvid_context *ref,
  666. xvid_plg_data_t *param) {
  667. char *log = ref->twopassbuffer;
  668. const char *frame_types = " ipbs";
  669. char frame_type;
  670. /* Quick bounds check */
  671. if( log == NULL )
  672. return XVID_ERR_FAIL;
  673. /* Convert the type given to us into a character */
  674. if( param->type < 5 && param->type > 0 ) {
  675. frame_type = frame_types[param->type];
  676. } else {
  677. return XVID_ERR_FAIL;
  678. }
  679. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  680. "%c %d %d %d %d %d %d\n",
  681. frame_type, param->stats.quant, param->stats.kblks, param->stats.mblks,
  682. param->stats.ublks, param->stats.length, param->stats.hlength);
  683. return 0;
  684. }
  685. /**
  686. * Dispatch function for our custom plugin.
  687. * This handles the dispatch for the Xvid plugin. It passes data
  688. * on to other functions for actual processing.
  689. *
  690. * @param ref Context pointer for the plugin
  691. * @param cmd The task given for us to complete
  692. * @param p1 First parameter (varies)
  693. * @param p2 Second parameter (varies)
  694. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  695. */
  696. int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2) {
  697. switch( cmd ) {
  698. case XVID_PLG_INFO:
  699. case XVID_PLG_FRAME:
  700. return 0;
  701. case XVID_PLG_BEFORE:
  702. return xvid_ff_2pass_before(ref, p1);
  703. case XVID_PLG_CREATE:
  704. return xvid_ff_2pass_create(p1, p2);
  705. case XVID_PLG_AFTER:
  706. return xvid_ff_2pass_after(ref, p1);
  707. case XVID_PLG_DESTROY:
  708. return xvid_ff_2pass_destroy(ref, p1);
  709. default:
  710. return XVID_ERR_FAIL;
  711. }
  712. }
  713. /**
  714. * Xvid codec definition for libavcodec.
  715. */
  716. AVCodec ff_libxvid_encoder = {
  717. .name = "libxvid",
  718. .type = AVMEDIA_TYPE_VIDEO,
  719. .id = CODEC_ID_MPEG4,
  720. .priv_data_size = sizeof(struct xvid_context),
  721. .init = xvid_encode_init,
  722. .encode2 = xvid_encode_frame,
  723. .close = xvid_encode_close,
  724. .pix_fmts = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
  725. .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  726. };