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.

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