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