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.

789 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. /**
  304. * Create the private context for the encoder.
  305. * All buffers are allocated, settings are loaded from the user,
  306. * and the encoder context created.
  307. *
  308. * @param avctx AVCodecContext pointer to context
  309. * @return Returns 0 on success, -1 on failure
  310. */
  311. static av_cold int xvid_encode_init(AVCodecContext *avctx) {
  312. int xerr, i;
  313. int xvid_flags = avctx->flags;
  314. struct xvid_context *x = avctx->priv_data;
  315. uint16_t *intra, *inter;
  316. int fd;
  317. xvid_plugin_single_t single = { 0 };
  318. struct xvid_ff_pass1 rc2pass1 = { 0 };
  319. xvid_plugin_2pass2_t rc2pass2 = { 0 };
  320. xvid_gbl_init_t xvid_gbl_init = { 0 };
  321. xvid_enc_create_t xvid_enc_create = { 0 };
  322. xvid_enc_plugin_t plugins[7];
  323. /* Bring in VOP flags from avconv command-line */
  324. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  325. if( xvid_flags & CODEC_FLAG_4MV )
  326. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  327. if( avctx->trellis
  328. )
  329. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  330. if( xvid_flags & CODEC_FLAG_AC_PRED )
  331. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  332. if( xvid_flags & CODEC_FLAG_GRAY )
  333. x->vop_flags |= XVID_VOP_GREYSCALE;
  334. /* Decide which ME quality setting to use */
  335. x->me_flags = 0;
  336. switch( avctx->me_method ) {
  337. case ME_FULL: /* Quality 6 */
  338. x->me_flags |= XVID_ME_EXTSEARCH16
  339. | XVID_ME_EXTSEARCH8;
  340. case ME_EPZS: /* Quality 4 */
  341. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8
  342. | XVID_ME_HALFPELREFINE8
  343. | XVID_ME_CHROMA_PVOP
  344. | XVID_ME_CHROMA_BVOP;
  345. case ME_LOG: /* Quality 2 */
  346. case ME_PHODS:
  347. case ME_X1:
  348. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16
  349. | XVID_ME_HALFPELREFINE16;
  350. case ME_ZERO: /* Quality 0 */
  351. default:
  352. break;
  353. }
  354. /* Decide how we should decide blocks */
  355. switch( avctx->mb_decision ) {
  356. case 2:
  357. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  358. x->me_flags |= XVID_ME_HALFPELREFINE8_RD
  359. | XVID_ME_QUARTERPELREFINE8_RD
  360. | XVID_ME_EXTSEARCH_RD
  361. | XVID_ME_CHECKPREDICTION_RD;
  362. case 1:
  363. if( !(x->vop_flags & XVID_VOP_MODEDECISION_RD) )
  364. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  365. x->me_flags |= XVID_ME_HALFPELREFINE16_RD
  366. | XVID_ME_QUARTERPELREFINE16_RD;
  367. default:
  368. break;
  369. }
  370. /* Bring in VOL flags from avconv command-line */
  371. x->vol_flags = 0;
  372. if( xvid_flags & CODEC_FLAG_GMC ) {
  373. x->vol_flags |= XVID_VOL_GMC;
  374. x->me_flags |= XVID_ME_GME_REFINE;
  375. }
  376. if( xvid_flags & CODEC_FLAG_QPEL ) {
  377. x->vol_flags |= XVID_VOL_QUARTERPEL;
  378. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  379. if( x->vop_flags & XVID_VOP_INTER4V )
  380. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  381. }
  382. xvid_gbl_init.version = XVID_VERSION;
  383. xvid_gbl_init.debug = 0;
  384. #if ARCH_PPC
  385. /* Xvid's PPC support is borked, use libavcodec to detect */
  386. #if HAVE_ALTIVEC
  387. if (av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC) {
  388. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ALTIVEC;
  389. } else
  390. #endif
  391. xvid_gbl_init.cpu_flags = XVID_CPU_FORCE;
  392. #else
  393. /* Xvid can detect on x86 */
  394. xvid_gbl_init.cpu_flags = 0;
  395. #endif
  396. /* Initialize */
  397. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  398. /* Create the encoder reference */
  399. xvid_enc_create.version = XVID_VERSION;
  400. /* Store the desired frame size */
  401. xvid_enc_create.width = x->xsize = avctx->width;
  402. xvid_enc_create.height = x->ysize = avctx->height;
  403. /* Xvid can determine the proper profile to use */
  404. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  405. /* We don't use zones */
  406. xvid_enc_create.zones = NULL;
  407. xvid_enc_create.num_zones = 0;
  408. xvid_enc_create.num_threads = avctx->thread_count;
  409. xvid_enc_create.plugins = plugins;
  410. xvid_enc_create.num_plugins = 0;
  411. /* Initialize Buffers */
  412. x->twopassbuffer = NULL;
  413. x->old_twopassbuffer = NULL;
  414. x->twopassfile = NULL;
  415. if( xvid_flags & CODEC_FLAG_PASS1 ) {
  416. rc2pass1.version = XVID_VERSION;
  417. rc2pass1.context = x;
  418. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  419. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  420. if( x->twopassbuffer == NULL || x->old_twopassbuffer == NULL ) {
  421. av_log(avctx, AV_LOG_ERROR,
  422. "Xvid: Cannot allocate 2-pass log buffers\n");
  423. return -1;
  424. }
  425. x->twopassbuffer[0] = x->old_twopassbuffer[0] = 0;
  426. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  427. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  428. xvid_enc_create.num_plugins++;
  429. } else if( xvid_flags & CODEC_FLAG_PASS2 ) {
  430. rc2pass2.version = XVID_VERSION;
  431. rc2pass2.bitrate = avctx->bit_rate;
  432. fd = ff_tempfile("xvidff.", &x->twopassfile);
  433. if( fd == -1 ) {
  434. av_log(avctx, AV_LOG_ERROR,
  435. "Xvid: Cannot write 2-pass pipe\n");
  436. return -1;
  437. }
  438. if( avctx->stats_in == NULL ) {
  439. av_log(avctx, AV_LOG_ERROR,
  440. "Xvid: No 2-pass information loaded for second pass\n");
  441. return -1;
  442. }
  443. if( strlen(avctx->stats_in) >
  444. write(fd, avctx->stats_in, strlen(avctx->stats_in)) ) {
  445. close(fd);
  446. av_log(avctx, AV_LOG_ERROR,
  447. "Xvid: Cannot write to 2-pass pipe\n");
  448. return -1;
  449. }
  450. close(fd);
  451. rc2pass2.filename = x->twopassfile;
  452. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  453. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  454. xvid_enc_create.num_plugins++;
  455. } else if( !(xvid_flags & CODEC_FLAG_QSCALE) ) {
  456. /* Single Pass Bitrate Control! */
  457. single.version = XVID_VERSION;
  458. single.bitrate = avctx->bit_rate;
  459. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  460. plugins[xvid_enc_create.num_plugins].param = &single;
  461. xvid_enc_create.num_plugins++;
  462. }
  463. /* Luminance Masking */
  464. if( 0.0 != avctx->lumi_masking ) {
  465. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  466. plugins[xvid_enc_create.num_plugins].param = NULL;
  467. xvid_enc_create.num_plugins++;
  468. }
  469. /* Frame Rate and Key Frames */
  470. xvid_correct_framerate(avctx);
  471. xvid_enc_create.fincr = avctx->time_base.num;
  472. xvid_enc_create.fbase = avctx->time_base.den;
  473. if( avctx->gop_size > 0 )
  474. xvid_enc_create.max_key_interval = avctx->gop_size;
  475. else
  476. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  477. /* Quants */
  478. if( xvid_flags & CODEC_FLAG_QSCALE ) x->qscale = 1;
  479. else x->qscale = 0;
  480. xvid_enc_create.min_quant[0] = avctx->qmin;
  481. xvid_enc_create.min_quant[1] = avctx->qmin;
  482. xvid_enc_create.min_quant[2] = avctx->qmin;
  483. xvid_enc_create.max_quant[0] = avctx->qmax;
  484. xvid_enc_create.max_quant[1] = avctx->qmax;
  485. xvid_enc_create.max_quant[2] = avctx->qmax;
  486. /* Quant Matrices */
  487. x->intra_matrix = x->inter_matrix = NULL;
  488. if( avctx->mpeg_quant )
  489. x->vol_flags |= XVID_VOL_MPEGQUANT;
  490. if( (avctx->intra_matrix || avctx->inter_matrix) ) {
  491. x->vol_flags |= XVID_VOL_MPEGQUANT;
  492. if( avctx->intra_matrix ) {
  493. intra = avctx->intra_matrix;
  494. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  495. } else
  496. intra = NULL;
  497. if( avctx->inter_matrix ) {
  498. inter = avctx->inter_matrix;
  499. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  500. } else
  501. inter = NULL;
  502. for( i = 0; i < 64; i++ ) {
  503. if( intra )
  504. x->intra_matrix[i] = (unsigned char)intra[i];
  505. if( inter )
  506. x->inter_matrix[i] = (unsigned char)inter[i];
  507. }
  508. }
  509. /* Misc Settings */
  510. xvid_enc_create.frame_drop_ratio = 0;
  511. xvid_enc_create.global = 0;
  512. if( xvid_flags & CODEC_FLAG_CLOSED_GOP )
  513. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  514. /* Determines which codec mode we are operating in */
  515. avctx->extradata = NULL;
  516. avctx->extradata_size = 0;
  517. if( xvid_flags & CODEC_FLAG_GLOBAL_HEADER ) {
  518. /* In this case, we are claiming to be MPEG4 */
  519. x->quicktime_format = 1;
  520. avctx->codec_id = AV_CODEC_ID_MPEG4;
  521. } else {
  522. /* We are claiming to be Xvid */
  523. x->quicktime_format = 0;
  524. if(!avctx->codec_tag)
  525. avctx->codec_tag = AV_RL32("xvid");
  526. }
  527. /* Bframes */
  528. xvid_enc_create.max_bframes = avctx->max_b_frames;
  529. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  530. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  531. if( avctx->max_b_frames > 0 && !x->quicktime_format ) xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  532. /* Create encoder context */
  533. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  534. if( xerr ) {
  535. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  536. return -1;
  537. }
  538. x->encoder_handle = xvid_enc_create.handle;
  539. avctx->coded_frame = &x->encoded_picture;
  540. return 0;
  541. }
  542. /**
  543. * Encode a single frame.
  544. *
  545. * @param avctx AVCodecContext pointer to context
  546. * @param frame Pointer to encoded frame buffer
  547. * @param buf_size Size of encoded frame buffer
  548. * @param data Pointer to AVFrame of unencoded frame
  549. * @return Returns 0 on success, -1 on failure
  550. */
  551. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  552. const AVFrame *picture, int *got_packet)
  553. {
  554. int xerr, i, ret, user_packet = !!pkt->data;
  555. char *tmp;
  556. struct xvid_context *x = avctx->priv_data;
  557. AVFrame *p = &x->encoded_picture;
  558. int mb_width = (avctx->width + 15) / 16;
  559. int mb_height = (avctx->height + 15) / 16;
  560. xvid_enc_frame_t xvid_enc_frame = { 0 };
  561. xvid_enc_stats_t xvid_enc_stats = { 0 };
  562. if (!user_packet &&
  563. (ret = av_new_packet(pkt, mb_width*mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE)) < 0) {
  564. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  565. return ret;
  566. }
  567. /* Start setting up the frame */
  568. xvid_enc_frame.version = XVID_VERSION;
  569. xvid_enc_stats.version = XVID_VERSION;
  570. *p = *picture;
  571. /* Let Xvid know where to put the frame. */
  572. xvid_enc_frame.bitstream = pkt->data;
  573. xvid_enc_frame.length = pkt->size;
  574. /* Initialize input image fields */
  575. if( avctx->pix_fmt != PIX_FMT_YUV420P ) {
  576. av_log(avctx, AV_LOG_ERROR, "Xvid: Color spaces other than 420p not supported\n");
  577. return -1;
  578. }
  579. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  580. for( i = 0; i < 4; i++ ) {
  581. xvid_enc_frame.input.plane[i] = picture->data[i];
  582. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  583. }
  584. /* Encoder Flags */
  585. xvid_enc_frame.vop_flags = x->vop_flags;
  586. xvid_enc_frame.vol_flags = x->vol_flags;
  587. xvid_enc_frame.motion = x->me_flags;
  588. xvid_enc_frame.type =
  589. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  590. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  591. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  592. XVID_TYPE_AUTO;
  593. /* Pixel aspect ratio setting */
  594. if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
  595. avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
  596. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  597. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  598. return -1;
  599. }
  600. xvid_enc_frame.par = XVID_PAR_EXT;
  601. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  602. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  603. /* Quant Setting */
  604. if( x->qscale ) xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  605. else xvid_enc_frame.quant = 0;
  606. /* Matrices */
  607. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  608. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  609. /* Encode */
  610. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  611. &xvid_enc_frame, &xvid_enc_stats);
  612. /* Two-pass log buffer swapping */
  613. avctx->stats_out = NULL;
  614. if( x->twopassbuffer ) {
  615. tmp = x->old_twopassbuffer;
  616. x->old_twopassbuffer = x->twopassbuffer;
  617. x->twopassbuffer = tmp;
  618. x->twopassbuffer[0] = 0;
  619. if( x->old_twopassbuffer[0] != 0 ) {
  620. avctx->stats_out = x->old_twopassbuffer;
  621. }
  622. }
  623. if (xerr > 0) {
  624. *got_packet = 1;
  625. p->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  626. if( xvid_enc_stats.type == XVID_TYPE_PVOP )
  627. p->pict_type = AV_PICTURE_TYPE_P;
  628. else if( xvid_enc_stats.type == XVID_TYPE_BVOP )
  629. p->pict_type = AV_PICTURE_TYPE_B;
  630. else if( xvid_enc_stats.type == XVID_TYPE_SVOP )
  631. p->pict_type = AV_PICTURE_TYPE_S;
  632. else
  633. p->pict_type = AV_PICTURE_TYPE_I;
  634. if( xvid_enc_frame.out_flags & XVID_KEYFRAME ) {
  635. p->key_frame = 1;
  636. pkt->flags |= AV_PKT_FLAG_KEY;
  637. if( x->quicktime_format )
  638. return xvid_strip_vol_header(avctx, pkt,
  639. xvid_enc_stats.hlength, xerr);
  640. } else
  641. p->key_frame = 0;
  642. pkt->size = xerr;
  643. return 0;
  644. } else {
  645. if (!user_packet)
  646. av_free_packet(pkt);
  647. if (!xerr)
  648. return 0;
  649. av_log(avctx, AV_LOG_ERROR, "Xvid: Encoding Error Occurred: %i\n", xerr);
  650. return -1;
  651. }
  652. }
  653. /**
  654. * Destroy the private context for the encoder.
  655. * All buffers are freed, and the Xvid encoder context is destroyed.
  656. *
  657. * @param avctx AVCodecContext pointer to context
  658. * @return Returns 0, success guaranteed
  659. */
  660. static av_cold int xvid_encode_close(AVCodecContext *avctx) {
  661. struct xvid_context *x = avctx->priv_data;
  662. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  663. av_freep(&avctx->extradata);
  664. if( x->twopassbuffer != NULL ) {
  665. av_free(x->twopassbuffer);
  666. av_free(x->old_twopassbuffer);
  667. }
  668. av_free(x->twopassfile);
  669. av_free(x->intra_matrix);
  670. av_free(x->inter_matrix);
  671. return 0;
  672. }
  673. /**
  674. * Xvid codec definition for libavcodec.
  675. */
  676. AVCodec ff_libxvid_encoder = {
  677. .name = "libxvid",
  678. .type = AVMEDIA_TYPE_VIDEO,
  679. .id = AV_CODEC_ID_MPEG4,
  680. .priv_data_size = sizeof(struct xvid_context),
  681. .init = xvid_encode_init,
  682. .encode2 = xvid_encode_frame,
  683. .close = xvid_encode_close,
  684. .pix_fmts = (const enum PixelFormat[]){ PIX_FMT_YUV420P, PIX_FMT_NONE },
  685. .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  686. };