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.

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