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.

776 lines
25KB

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