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