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.

828 lines
27KB

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