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.

932 lines
32KB

  1. /*
  2. * Interface to xvidcore for MPEG-4 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 <stdio.h>
  27. #include <string.h>
  28. #include <unistd.h>
  29. #include <xvid.h>
  30. #include "libavutil/cpu.h"
  31. #include "libavutil/internal.h"
  32. #include "libavutil/intreadwrite.h"
  33. #include "libavutil/mathematics.h"
  34. #include "libavutil/mem.h"
  35. #include "libavutil/opt.h"
  36. #include "avcodec.h"
  37. #include "internal.h"
  38. #include "libxvid.h"
  39. #include "mpegutils.h"
  40. /**
  41. * Buffer management macros.
  42. */
  43. #define BUFFER_SIZE 1024
  44. #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
  45. #define BUFFER_CAT(x) (&((x)[strlen(x)]))
  46. /**
  47. * Structure for the private Xvid context.
  48. * This stores all the private context for the codec.
  49. */
  50. struct xvid_context {
  51. AVClass *class; /**< Handle for Xvid encoder */
  52. void *encoder_handle; /**< Handle for Xvid encoder */
  53. int xsize; /**< Frame x size */
  54. int ysize; /**< Frame y size */
  55. int vop_flags; /**< VOP flags for Xvid encoder */
  56. int vol_flags; /**< VOL flags for Xvid encoder */
  57. int me_flags; /**< Motion Estimation flags */
  58. int qscale; /**< Do we use constant scale? */
  59. int quicktime_format; /**< Are we in a QT-based format? */
  60. char *twopassbuffer; /**< Character buffer for two-pass */
  61. char *old_twopassbuffer; /**< Old character buffer (two-pass) */
  62. char *twopassfile; /**< second pass temp file name */
  63. unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
  64. unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
  65. int lumi_aq; /**< Lumi masking as an aq method */
  66. int variance_aq; /**< Variance adaptive quantization */
  67. int ssim; /**< SSIM information display mode */
  68. int ssim_acc; /**< SSIM accuracy. 0: accurate. 4: fast. */
  69. int gmc;
  70. int me_quality; /**< Motion estimation quality. 0: fast 6: best. */
  71. int mpeg_quant; /**< Quantization type. 0: H.263, 1: MPEG */
  72. };
  73. /**
  74. * Structure for the private first-pass plugin.
  75. */
  76. struct xvid_ff_pass1 {
  77. int version; /**< Xvid version */
  78. struct xvid_context *context; /**< Pointer to private context */
  79. };
  80. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  81. const AVFrame *picture, int *got_packet);
  82. /*
  83. * Xvid 2-Pass Kludge Section
  84. *
  85. * Xvid's default 2-pass doesn't allow us to create data as we need to, so
  86. * this section spends time replacing the first pass plugin so we can write
  87. * statistic information as libavcodec requests in. We have another kludge
  88. * that allows us to pass data to the second pass in Xvid without a custom
  89. * rate-control plugin.
  90. */
  91. /**
  92. * Initialize the two-pass plugin and context.
  93. *
  94. * @param param Input construction parameter structure
  95. * @param handle Private context handle
  96. * @return Returns XVID_ERR_xxxx on failure, or 0 on success.
  97. */
  98. static int xvid_ff_2pass_create(xvid_plg_create_t *param, void **handle)
  99. {
  100. struct xvid_ff_pass1 *x = (struct xvid_ff_pass1 *) param->param;
  101. char *log = x->context->twopassbuffer;
  102. /* Do a quick bounds check */
  103. if (!log)
  104. return XVID_ERR_FAIL;
  105. /* We use snprintf() */
  106. /* This is because we can safely prevent a buffer overflow */
  107. log[0] = 0;
  108. snprintf(log, BUFFER_REMAINING(log),
  109. "# avconv 2-pass log file, using xvid codec\n");
  110. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  111. "# Do not modify. libxvidcore version: %d.%d.%d\n\n",
  112. XVID_VERSION_MAJOR(XVID_VERSION),
  113. XVID_VERSION_MINOR(XVID_VERSION),
  114. XVID_VERSION_PATCH(XVID_VERSION));
  115. *handle = x->context;
  116. return 0;
  117. }
  118. /**
  119. * Destroy the two-pass plugin context.
  120. *
  121. * @param ref Context pointer for the plugin
  122. * @param param Destroy context
  123. * @return Returns 0, success guaranteed
  124. */
  125. static int xvid_ff_2pass_destroy(struct xvid_context *ref,
  126. xvid_plg_destroy_t *param)
  127. {
  128. /* Currently cannot think of anything to do on destruction */
  129. /* Still, the framework should be here for reference/use */
  130. if (ref->twopassbuffer)
  131. ref->twopassbuffer[0] = 0;
  132. return 0;
  133. }
  134. /**
  135. * Enable fast encode mode during the first pass.
  136. *
  137. * @param ref Context pointer for the plugin
  138. * @param param Frame data
  139. * @return Returns 0, success guaranteed
  140. */
  141. static int xvid_ff_2pass_before(struct xvid_context *ref,
  142. xvid_plg_data_t *param)
  143. {
  144. int motion_remove;
  145. int motion_replacements;
  146. int vop_remove;
  147. /* Nothing to do here, result is changed too much */
  148. if (param->zone && param->zone->mode == XVID_ZONE_QUANT)
  149. return 0;
  150. /* We can implement a 'turbo' first pass mode here */
  151. param->quant = 2;
  152. /* Init values */
  153. motion_remove = ~XVID_ME_CHROMA_PVOP &
  154. ~XVID_ME_CHROMA_BVOP &
  155. ~XVID_ME_EXTSEARCH16 &
  156. ~XVID_ME_ADVANCEDDIAMOND16;
  157. motion_replacements = XVID_ME_FAST_MODEINTERPOLATE |
  158. XVID_ME_SKIP_DELTASEARCH |
  159. XVID_ME_FASTREFINE16 |
  160. XVID_ME_BFRAME_EARLYSTOP;
  161. vop_remove = ~XVID_VOP_MODEDECISION_RD &
  162. ~XVID_VOP_FAST_MODEDECISION_RD &
  163. ~XVID_VOP_TRELLISQUANT &
  164. ~XVID_VOP_INTER4V &
  165. ~XVID_VOP_HQACPRED;
  166. param->vol_flags &= ~XVID_VOL_GMC;
  167. param->vop_flags &= vop_remove;
  168. param->motion_flags &= motion_remove;
  169. param->motion_flags |= motion_replacements;
  170. return 0;
  171. }
  172. /**
  173. * Capture statistic data and write it during first pass.
  174. *
  175. * @param ref Context pointer for the plugin
  176. * @param param Statistic data
  177. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  178. */
  179. static int xvid_ff_2pass_after(struct xvid_context *ref,
  180. xvid_plg_data_t *param)
  181. {
  182. char *log = ref->twopassbuffer;
  183. const char *frame_types = " ipbs";
  184. char frame_type;
  185. /* Quick bounds check */
  186. if (!log)
  187. return XVID_ERR_FAIL;
  188. /* Convert the type given to us into a character */
  189. if (param->type < 5 && param->type > 0)
  190. frame_type = frame_types[param->type];
  191. else
  192. return XVID_ERR_FAIL;
  193. snprintf(BUFFER_CAT(log), BUFFER_REMAINING(log),
  194. "%c %d %d %d %d %d %d\n",
  195. frame_type, param->stats.quant, param->stats.kblks,
  196. param->stats.mblks, param->stats.ublks,
  197. param->stats.length, param->stats.hlength);
  198. return 0;
  199. }
  200. /**
  201. * Dispatch function for our custom plugin.
  202. * This handles the dispatch for the Xvid plugin. It passes data
  203. * on to other functions for actual processing.
  204. *
  205. * @param ref Context pointer for the plugin
  206. * @param cmd The task given for us to complete
  207. * @param p1 First parameter (varies)
  208. * @param p2 Second parameter (varies)
  209. * @return Returns XVID_ERR_xxxx on failure, or 0 on success
  210. */
  211. static int xvid_ff_2pass(void *ref, int cmd, void *p1, void *p2)
  212. {
  213. switch (cmd) {
  214. case XVID_PLG_INFO:
  215. case XVID_PLG_FRAME:
  216. return 0;
  217. case XVID_PLG_BEFORE:
  218. return xvid_ff_2pass_before(ref, p1);
  219. case XVID_PLG_CREATE:
  220. return xvid_ff_2pass_create(p1, p2);
  221. case XVID_PLG_AFTER:
  222. return xvid_ff_2pass_after(ref, p1);
  223. case XVID_PLG_DESTROY:
  224. return xvid_ff_2pass_destroy(ref, p1);
  225. default:
  226. return XVID_ERR_FAIL;
  227. }
  228. }
  229. /**
  230. * Routine to create a global VO/VOL header for MP4 container.
  231. * What we do here is extract the header from the Xvid bitstream
  232. * as it is encoded. We also strip the repeated headers from the
  233. * bitstream when a global header is requested for MPEG-4 ISO
  234. * compliance.
  235. *
  236. * @param avctx AVCodecContext pointer to context
  237. * @param frame Pointer to encoded frame data
  238. * @param header_len Length of header to search
  239. * @param frame_len Length of encoded frame data
  240. * @return Returns new length of frame data
  241. */
  242. static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,
  243. unsigned int header_len,
  244. unsigned int frame_len)
  245. {
  246. int vo_len = 0, i;
  247. for (i = 0; i < header_len - 3; i++) {
  248. if (pkt->data[i] == 0x00 &&
  249. pkt->data[i + 1] == 0x00 &&
  250. pkt->data[i + 2] == 0x01 &&
  251. pkt->data[i + 3] == 0xB6) {
  252. vo_len = i;
  253. break;
  254. }
  255. }
  256. if (vo_len > 0) {
  257. /* We need to store the header, so extract it */
  258. if (!avctx->extradata) {
  259. avctx->extradata = av_malloc(vo_len);
  260. if (!avctx->extradata)
  261. return AVERROR(ENOMEM);
  262. memcpy(avctx->extradata, pkt->data, vo_len);
  263. avctx->extradata_size = vo_len;
  264. }
  265. /* Less dangerous now, memmove properly copies the two
  266. * chunks of overlapping data */
  267. memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);
  268. pkt->size = frame_len - vo_len;
  269. }
  270. return 0;
  271. }
  272. /**
  273. * Routine to correct a possibly erroneous framerate being fed to us.
  274. * Xvid currently chokes on framerates where the ticks per frame is
  275. * extremely large. This function works to correct problems in this area
  276. * by estimating a new framerate and taking the simpler fraction of
  277. * the two presented.
  278. *
  279. * @param avctx Context that contains the framerate to correct.
  280. */
  281. static void xvid_correct_framerate(AVCodecContext *avctx)
  282. {
  283. int frate, fbase;
  284. int est_frate, est_fbase;
  285. int gcd;
  286. float est_fps, fps;
  287. frate = avctx->time_base.den;
  288. fbase = avctx->time_base.num;
  289. gcd = av_gcd(frate, fbase);
  290. if (gcd > 1) {
  291. frate /= gcd;
  292. fbase /= gcd;
  293. }
  294. if (frate <= 65000 && fbase <= 65000) {
  295. avctx->time_base.den = frate;
  296. avctx->time_base.num = fbase;
  297. return;
  298. }
  299. fps = (float) frate / (float) fbase;
  300. est_fps = roundf(fps * 1000.0) / 1000.0;
  301. est_frate = (int) est_fps;
  302. if (est_fps > (int) est_fps) {
  303. est_frate = (est_frate + 1) * 1000;
  304. est_fbase = (int) roundf((float) est_frate / est_fps);
  305. } else
  306. est_fbase = 1;
  307. gcd = av_gcd(est_frate, est_fbase);
  308. if (gcd > 1) {
  309. est_frate /= gcd;
  310. est_fbase /= gcd;
  311. }
  312. if (fbase > est_fbase) {
  313. avctx->time_base.den = est_frate;
  314. avctx->time_base.num = est_fbase;
  315. av_log(avctx, AV_LOG_DEBUG,
  316. "Xvid: framerate re-estimated: %.2f, %.3f%% correction\n",
  317. est_fps, (((est_fps - fps) / fps) * 100.0));
  318. } else {
  319. avctx->time_base.den = frate;
  320. avctx->time_base.num = fbase;
  321. }
  322. }
  323. static av_cold int xvid_encode_init(AVCodecContext *avctx)
  324. {
  325. int xerr, i;
  326. int xvid_flags = avctx->flags;
  327. struct xvid_context *x = avctx->priv_data;
  328. uint16_t *intra, *inter;
  329. int fd;
  330. xvid_plugin_single_t single = { 0 };
  331. struct xvid_ff_pass1 rc2pass1 = { 0 };
  332. xvid_plugin_2pass2_t rc2pass2 = { 0 };
  333. xvid_plugin_lumimasking_t masking_l = { 0 }; /* For lumi masking */
  334. xvid_plugin_lumimasking_t masking_v = { 0 }; /* For variance AQ */
  335. xvid_plugin_ssim_t ssim = { 0 };
  336. xvid_gbl_init_t xvid_gbl_init = { 0 };
  337. xvid_enc_create_t xvid_enc_create = { 0 };
  338. xvid_enc_plugin_t plugins[7];
  339. /* Bring in VOP flags from avconv command-line */
  340. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  341. if (xvid_flags & AV_CODEC_FLAG_4MV)
  342. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  343. if (avctx->trellis)
  344. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  345. if (xvid_flags & AV_CODEC_FLAG_AC_PRED)
  346. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  347. if (xvid_flags & AV_CODEC_FLAG_GRAY)
  348. x->vop_flags |= XVID_VOP_GREYSCALE;
  349. /* Decide which ME quality setting to use */
  350. x->me_flags = 0;
  351. switch (x->me_quality) {
  352. case 6:
  353. case 5:
  354. x->me_flags |= XVID_ME_EXTSEARCH16 |
  355. XVID_ME_EXTSEARCH8;
  356. case 4:
  357. case 3:
  358. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
  359. XVID_ME_HALFPELREFINE8 |
  360. XVID_ME_CHROMA_PVOP |
  361. XVID_ME_CHROMA_BVOP;
  362. case 2:
  363. case 1:
  364. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
  365. XVID_ME_HALFPELREFINE16;
  366. #if FF_API_MOTION_EST
  367. FF_DISABLE_DEPRECATION_WARNINGS
  368. break;
  369. default:
  370. switch (avctx->me_method) {
  371. case ME_FULL: /* Quality 6 */
  372. x->me_flags |= XVID_ME_EXTSEARCH16 |
  373. XVID_ME_EXTSEARCH8;
  374. case ME_EPZS: /* Quality 4 */
  375. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
  376. XVID_ME_HALFPELREFINE8 |
  377. XVID_ME_CHROMA_PVOP |
  378. XVID_ME_CHROMA_BVOP;
  379. case ME_LOG: /* Quality 2 */
  380. case ME_PHODS:
  381. case ME_X1:
  382. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
  383. XVID_ME_HALFPELREFINE16;
  384. case ME_ZERO: /* Quality 0 */
  385. default:
  386. break;
  387. }
  388. FF_ENABLE_DEPRECATION_WARNINGS
  389. #endif
  390. }
  391. /* Decide how we should decide blocks */
  392. switch (avctx->mb_decision) {
  393. case 2:
  394. x->vop_flags |= XVID_VOP_MODEDECISION_RD;
  395. x->me_flags |= XVID_ME_HALFPELREFINE8_RD |
  396. XVID_ME_QUARTERPELREFINE8_RD |
  397. XVID_ME_EXTSEARCH_RD |
  398. XVID_ME_CHECKPREDICTION_RD;
  399. case 1:
  400. if (!(x->vop_flags & XVID_VOP_MODEDECISION_RD))
  401. x->vop_flags |= XVID_VOP_FAST_MODEDECISION_RD;
  402. x->me_flags |= XVID_ME_HALFPELREFINE16_RD |
  403. XVID_ME_QUARTERPELREFINE16_RD;
  404. default:
  405. break;
  406. }
  407. /* Bring in VOL flags from avconv command-line */
  408. #if FF_API_GMC
  409. if (avctx->flags & CODEC_FLAG_GMC)
  410. x->gmc = 1;
  411. #endif
  412. x->vol_flags = 0;
  413. if (x->gmc) {
  414. x->vol_flags |= XVID_VOL_GMC;
  415. x->me_flags |= XVID_ME_GME_REFINE;
  416. }
  417. if (xvid_flags & AV_CODEC_FLAG_QPEL) {
  418. x->vol_flags |= XVID_VOL_QUARTERPEL;
  419. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  420. if (x->vop_flags & XVID_VOP_INTER4V)
  421. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  422. }
  423. xvid_gbl_init.version = XVID_VERSION;
  424. xvid_gbl_init.debug = 0;
  425. xvid_gbl_init.cpu_flags = 0;
  426. /* Initialize */
  427. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  428. /* Create the encoder reference */
  429. xvid_enc_create.version = XVID_VERSION;
  430. /* Store the desired frame size */
  431. xvid_enc_create.width =
  432. x->xsize = avctx->width;
  433. xvid_enc_create.height =
  434. x->ysize = avctx->height;
  435. /* Xvid can determine the proper profile to use */
  436. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  437. /* We don't use zones */
  438. xvid_enc_create.zones = NULL;
  439. xvid_enc_create.num_zones = 0;
  440. xvid_enc_create.num_threads = avctx->thread_count;
  441. xvid_enc_create.plugins = plugins;
  442. xvid_enc_create.num_plugins = 0;
  443. /* Initialize Buffers */
  444. x->twopassbuffer = NULL;
  445. x->old_twopassbuffer = NULL;
  446. x->twopassfile = NULL;
  447. if (xvid_flags & AV_CODEC_FLAG_PASS1) {
  448. rc2pass1.version = XVID_VERSION;
  449. rc2pass1.context = x;
  450. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  451. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  452. if (!x->twopassbuffer || !x->old_twopassbuffer) {
  453. av_log(avctx, AV_LOG_ERROR,
  454. "Xvid: Cannot allocate 2-pass log buffers\n");
  455. return AVERROR(ENOMEM);
  456. }
  457. x->twopassbuffer[0] =
  458. x->old_twopassbuffer[0] = 0;
  459. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  460. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  461. xvid_enc_create.num_plugins++;
  462. } else if (xvid_flags & AV_CODEC_FLAG_PASS2) {
  463. rc2pass2.version = XVID_VERSION;
  464. rc2pass2.bitrate = avctx->bit_rate;
  465. fd = ff_tempfile("xvidff.", &x->twopassfile);
  466. if (fd < 0) {
  467. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
  468. return fd;
  469. }
  470. if (!avctx->stats_in) {
  471. av_log(avctx, AV_LOG_ERROR,
  472. "Xvid: No 2-pass information loaded for second pass\n");
  473. return AVERROR_INVALIDDATA;
  474. }
  475. if (strlen(avctx->stats_in) >
  476. write(fd, avctx->stats_in, strlen(avctx->stats_in))) {
  477. close(fd);
  478. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
  479. return AVERROR(EIO);
  480. }
  481. close(fd);
  482. rc2pass2.filename = x->twopassfile;
  483. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  484. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  485. xvid_enc_create.num_plugins++;
  486. } else if (!(xvid_flags & AV_CODEC_FLAG_QSCALE)) {
  487. /* Single Pass Bitrate Control! */
  488. single.version = XVID_VERSION;
  489. single.bitrate = avctx->bit_rate;
  490. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  491. plugins[xvid_enc_create.num_plugins].param = &single;
  492. xvid_enc_create.num_plugins++;
  493. }
  494. if (avctx->lumi_masking != 0.0)
  495. x->lumi_aq = 1;
  496. if (x->lumi_aq && x->variance_aq) {
  497. x->variance_aq = 0;
  498. av_log(avctx, AV_LOG_WARNING,
  499. "variance_aq is ignored when lumi_aq is set.\n");
  500. }
  501. /* Luminance Masking */
  502. if (x->lumi_aq) {
  503. masking_l.method = 0;
  504. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  505. /* The old behavior is that when avctx->lumi_masking is specified,
  506. * plugins[...].param = NULL. Trying to keep the old behavior here. */
  507. plugins[xvid_enc_create.num_plugins].param =
  508. avctx->lumi_masking ? NULL : &masking_l;
  509. xvid_enc_create.num_plugins++;
  510. }
  511. /* Variance AQ */
  512. if (x->variance_aq) {
  513. masking_v.method = 1;
  514. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  515. plugins[xvid_enc_create.num_plugins].param = &masking_v;
  516. xvid_enc_create.num_plugins++;
  517. }
  518. /* SSIM */
  519. if (x->ssim) {
  520. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
  521. ssim.b_printstat = x->ssim == 2;
  522. ssim.acc = x->ssim_acc;
  523. ssim.cpu_flags = xvid_gbl_init.cpu_flags;
  524. ssim.b_visualize = 0;
  525. plugins[xvid_enc_create.num_plugins].param = &ssim;
  526. xvid_enc_create.num_plugins++;
  527. }
  528. /* Frame Rate and Key Frames */
  529. xvid_correct_framerate(avctx);
  530. xvid_enc_create.fincr = avctx->time_base.num;
  531. xvid_enc_create.fbase = avctx->time_base.den;
  532. if (avctx->gop_size > 0)
  533. xvid_enc_create.max_key_interval = avctx->gop_size;
  534. else
  535. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  536. /* Quants */
  537. if (xvid_flags & AV_CODEC_FLAG_QSCALE)
  538. x->qscale = 1;
  539. else
  540. x->qscale = 0;
  541. xvid_enc_create.min_quant[0] = avctx->qmin;
  542. xvid_enc_create.min_quant[1] = avctx->qmin;
  543. xvid_enc_create.min_quant[2] = avctx->qmin;
  544. xvid_enc_create.max_quant[0] = avctx->qmax;
  545. xvid_enc_create.max_quant[1] = avctx->qmax;
  546. xvid_enc_create.max_quant[2] = avctx->qmax;
  547. /* Quant Matrices */
  548. x->intra_matrix =
  549. x->inter_matrix = NULL;
  550. #if FF_API_PRIVATE_OPT
  551. FF_DISABLE_DEPRECATION_WARNINGS
  552. if (avctx->mpeg_quant)
  553. x->mpeg_quant = avctx->mpeg_quant;
  554. FF_ENABLE_DEPRECATION_WARNINGS
  555. #endif
  556. if (x->mpeg_quant)
  557. x->vol_flags |= XVID_VOL_MPEGQUANT;
  558. if ((avctx->intra_matrix || avctx->inter_matrix)) {
  559. x->vol_flags |= XVID_VOL_MPEGQUANT;
  560. if (avctx->intra_matrix) {
  561. intra = avctx->intra_matrix;
  562. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  563. if (!x->intra_matrix)
  564. return AVERROR(ENOMEM);
  565. } else
  566. intra = NULL;
  567. if (avctx->inter_matrix) {
  568. inter = avctx->inter_matrix;
  569. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  570. if (!x->inter_matrix)
  571. return AVERROR(ENOMEM);
  572. } else
  573. inter = NULL;
  574. for (i = 0; i < 64; i++) {
  575. if (intra)
  576. x->intra_matrix[i] = (unsigned char) intra[i];
  577. if (inter)
  578. x->inter_matrix[i] = (unsigned char) inter[i];
  579. }
  580. }
  581. /* Misc Settings */
  582. xvid_enc_create.frame_drop_ratio = 0;
  583. xvid_enc_create.global = 0;
  584. if (xvid_flags & AV_CODEC_FLAG_CLOSED_GOP)
  585. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  586. /* Determines which codec mode we are operating in */
  587. avctx->extradata = NULL;
  588. avctx->extradata_size = 0;
  589. if (xvid_flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  590. /* In this case, we are claiming to be MPEG-4 */
  591. x->quicktime_format = 1;
  592. avctx->codec_id = AV_CODEC_ID_MPEG4;
  593. } else {
  594. /* We are claiming to be Xvid */
  595. x->quicktime_format = 0;
  596. if (!avctx->codec_tag)
  597. avctx->codec_tag = AV_RL32("xvid");
  598. }
  599. /* Bframes */
  600. xvid_enc_create.max_bframes = avctx->max_b_frames;
  601. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  602. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  603. if (avctx->max_b_frames > 0 && !x->quicktime_format)
  604. xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  605. /* Encode a dummy frame to get the extradata immediately */
  606. if (x->quicktime_format) {
  607. AVFrame *picture;
  608. AVPacket packet;
  609. int got_packet, ret;
  610. av_init_packet(&packet);
  611. picture = av_frame_alloc();
  612. if (!picture)
  613. return AVERROR(ENOMEM);
  614. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  615. if (xerr) {
  616. av_frame_free(&picture);
  617. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  618. return AVERROR_UNKNOWN;
  619. }
  620. x->encoder_handle = xvid_enc_create.handle;
  621. picture->width = avctx->width;
  622. picture->height = avctx->height;
  623. picture->format = avctx->pix_fmt;
  624. if ((ret = av_frame_get_buffer(picture, 32)) < 0) {
  625. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  626. av_frame_free(&picture);
  627. return ret;
  628. }
  629. ret = xvid_encode_frame(avctx, &packet, picture, &got_packet);
  630. if (!ret && got_packet)
  631. av_packet_unref(&packet);
  632. av_frame_free(&picture);
  633. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  634. }
  635. /* Create encoder context */
  636. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  637. if (xerr) {
  638. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  639. return -1;
  640. }
  641. x->encoder_handle = xvid_enc_create.handle;
  642. return 0;
  643. }
  644. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  645. const AVFrame *picture, int *got_packet)
  646. {
  647. int xerr, i, ret, user_packet = !!pkt->data;
  648. struct xvid_context *x = avctx->priv_data;
  649. int mb_width = (avctx->width + 15) / 16;
  650. int mb_height = (avctx->height + 15) / 16;
  651. char *tmp;
  652. xvid_enc_frame_t xvid_enc_frame = { 0 };
  653. xvid_enc_stats_t xvid_enc_stats = { 0 };
  654. if (!user_packet &&
  655. (ret = av_new_packet(pkt, mb_width * mb_height * MAX_MB_BYTES + AV_INPUT_BUFFER_MIN_SIZE)) < 0) {
  656. av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
  657. return ret;
  658. }
  659. /* Start setting up the frame */
  660. xvid_enc_frame.version = XVID_VERSION;
  661. xvid_enc_stats.version = XVID_VERSION;
  662. /* Let Xvid know where to put the frame. */
  663. xvid_enc_frame.bitstream = pkt->data;
  664. xvid_enc_frame.length = pkt->size;
  665. /* Initialize input image fields */
  666. if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
  667. av_log(avctx, AV_LOG_ERROR,
  668. "Xvid: Color spaces other than 420P not supported\n");
  669. return -1;
  670. }
  671. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  672. for (i = 0; i < 4; i++) {
  673. xvid_enc_frame.input.plane[i] = picture->data[i];
  674. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  675. }
  676. /* Encoder Flags */
  677. xvid_enc_frame.vop_flags = x->vop_flags;
  678. xvid_enc_frame.vol_flags = x->vol_flags;
  679. xvid_enc_frame.motion = x->me_flags;
  680. xvid_enc_frame.type =
  681. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  682. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  683. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  684. XVID_TYPE_AUTO;
  685. /* Pixel aspect ratio setting */
  686. if (avctx->sample_aspect_ratio.num < 1 || avctx->sample_aspect_ratio.num > 255 ||
  687. avctx->sample_aspect_ratio.den < 1 || avctx->sample_aspect_ratio.den > 255) {
  688. av_log(avctx, AV_LOG_ERROR, "Invalid pixel aspect ratio %i/%i\n",
  689. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  690. return -1;
  691. }
  692. xvid_enc_frame.par = XVID_PAR_EXT;
  693. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  694. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  695. /* Quant Setting */
  696. if (x->qscale)
  697. xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  698. else
  699. xvid_enc_frame.quant = 0;
  700. /* Matrices */
  701. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  702. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  703. /* Encode */
  704. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  705. &xvid_enc_frame, &xvid_enc_stats);
  706. /* Two-pass log buffer swapping */
  707. avctx->stats_out = NULL;
  708. if (x->twopassbuffer) {
  709. tmp = x->old_twopassbuffer;
  710. x->old_twopassbuffer = x->twopassbuffer;
  711. x->twopassbuffer = tmp;
  712. x->twopassbuffer[0] = 0;
  713. if (x->old_twopassbuffer[0] != 0) {
  714. avctx->stats_out = x->old_twopassbuffer;
  715. }
  716. }
  717. if (xerr > 0) {
  718. uint8_t *sd = av_packet_new_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
  719. sizeof(int));
  720. if (!sd)
  721. return AVERROR(ENOMEM);
  722. *(int *)sd = xvid_enc_stats.quant * FF_QP2LAMBDA;
  723. *got_packet = 1;
  724. #if FF_API_CODED_FRAME
  725. FF_DISABLE_DEPRECATION_WARNINGS
  726. avctx->coded_frame->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  727. if (xvid_enc_stats.type == XVID_TYPE_PVOP)
  728. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  729. else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
  730. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  731. else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
  732. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_S;
  733. else
  734. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  735. FF_ENABLE_DEPRECATION_WARNINGS
  736. #endif
  737. if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
  738. #if FF_API_CODED_FRAME
  739. FF_DISABLE_DEPRECATION_WARNINGS
  740. avctx->coded_frame->key_frame = 1;
  741. FF_ENABLE_DEPRECATION_WARNINGS
  742. #endif
  743. pkt->flags |= AV_PKT_FLAG_KEY;
  744. if (x->quicktime_format)
  745. return xvid_strip_vol_header(avctx, pkt,
  746. xvid_enc_stats.hlength, xerr);
  747. } else {
  748. #if FF_API_CODED_FRAME
  749. FF_DISABLE_DEPRECATION_WARNINGS
  750. avctx->coded_frame->key_frame = 0;
  751. FF_ENABLE_DEPRECATION_WARNINGS
  752. #endif
  753. }
  754. pkt->size = xerr;
  755. return 0;
  756. } else {
  757. if (!user_packet)
  758. av_packet_unref(pkt);
  759. if (!xerr)
  760. return 0;
  761. av_log(avctx, AV_LOG_ERROR,
  762. "Xvid: Encoding Error Occurred: %i\n", xerr);
  763. return xerr;
  764. }
  765. }
  766. static av_cold int xvid_encode_close(AVCodecContext *avctx)
  767. {
  768. struct xvid_context *x = avctx->priv_data;
  769. if (x->encoder_handle) {
  770. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  771. x->encoder_handle = NULL;
  772. }
  773. av_freep(&avctx->extradata);
  774. if (x->twopassbuffer) {
  775. av_free(x->twopassbuffer);
  776. av_free(x->old_twopassbuffer);
  777. }
  778. av_free(x->twopassfile);
  779. av_free(x->intra_matrix);
  780. av_free(x->inter_matrix);
  781. return 0;
  782. }
  783. #define OFFSET(x) offsetof(struct xvid_context, x)
  784. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  785. static const AVOption options[] = {
  786. { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  787. { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  788. { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
  789. { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
  790. { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
  791. { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
  792. { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
  793. { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  794. { "me_quality", "Motion estimation quality", OFFSET(me_quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 6, VE },
  795. { "mpeg_quant", "Use MPEG quantizers instead of H.263", OFFSET(mpeg_quant), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  796. { NULL },
  797. };
  798. static const AVClass xvid_class = {
  799. .class_name = "libxvid",
  800. .item_name = av_default_item_name,
  801. .option = options,
  802. .version = LIBAVUTIL_VERSION_INT,
  803. };
  804. AVCodec ff_libxvid_encoder = {
  805. .name = "libxvid",
  806. .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  807. .type = AVMEDIA_TYPE_VIDEO,
  808. .id = AV_CODEC_ID_MPEG4,
  809. .priv_data_size = sizeof(struct xvid_context),
  810. .init = xvid_encode_init,
  811. .encode2 = xvid_encode_frame,
  812. .close = xvid_encode_close,
  813. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  814. .priv_class = &xvid_class,
  815. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
  816. FF_CODEC_CAP_INIT_CLEANUP,
  817. };