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.

911 lines
31KB

  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 "libavutil/cpu.h"
  28. #include "libavutil/file.h"
  29. #include "libavutil/intreadwrite.h"
  30. #include "libavutil/mathematics.h"
  31. #include "avcodec.h"
  32. #include "internal.h"
  33. #include "libxvid.h"
  34. #include "mpegvideo.h"
  35. #if HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #if HAVE_IO_H
  39. #include <io.h>
  40. #endif
  41. /**
  42. * Buffer management macros.
  43. */
  44. #define BUFFER_SIZE 1024
  45. #define BUFFER_REMAINING(x) (BUFFER_SIZE - strlen(x))
  46. #define BUFFER_CAT(x) (&((x)[strlen(x)]))
  47. /**
  48. * Structure for the private Xvid context.
  49. * This stores all the private context for the codec.
  50. */
  51. struct xvid_context {
  52. AVClass *class;
  53. void *encoder_handle; /**< Handle for Xvid encoder */
  54. int xsize; /**< Frame x size */
  55. int ysize; /**< Frame y size */
  56. int vop_flags; /**< VOP flags for Xvid encoder */
  57. int vol_flags; /**< VOL flags for Xvid encoder */
  58. int me_flags; /**< Motion Estimation flags */
  59. int qscale; /**< Do we use constant scale? */
  60. int quicktime_format; /**< Are we in a QT-based format? */
  61. char *twopassbuffer; /**< Character buffer for two-pass */
  62. char *old_twopassbuffer; /**< Old character buffer (two-pass) */
  63. char *twopassfile; /**< second pass temp file name */
  64. int twopassfd;
  65. unsigned char *intra_matrix; /**< P-Frame Quant Matrix */
  66. unsigned char *inter_matrix; /**< I-Frame Quant Matrix */
  67. int lumi_aq; /**< Lumi masking as an aq method */
  68. int variance_aq; /**< Variance adaptive quantization */
  69. int ssim; /**< SSIM information display mode */
  70. int ssim_acc; /**< SSIM accuracy. 0: accurate. 4: fast. */
  71. int gmc;
  72. int me_quality; /**< Motion estimation quality. 0: fast 6: best. */
  73. };
  74. /**
  75. * Structure for the private first-pass plugin.
  76. */
  77. struct xvid_ff_pass1 {
  78. int version; /**< Xvid version */
  79. struct xvid_context *context; /**< Pointer to private context */
  80. };
  81. static int xvid_encode_close(AVCodecContext *avctx);
  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. "# ffmpeg 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 Destrooy 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, ret = -1;
  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[4];
  339. x->twopassfd = -1;
  340. /* Bring in VOP flags from ffmpeg command-line */
  341. x->vop_flags = XVID_VOP_HALFPEL; /* Bare minimum quality */
  342. if (xvid_flags & CODEC_FLAG_4MV)
  343. x->vop_flags |= XVID_VOP_INTER4V; /* Level 3 */
  344. if (avctx->trellis)
  345. x->vop_flags |= XVID_VOP_TRELLISQUANT; /* Level 5 */
  346. if (xvid_flags & CODEC_FLAG_AC_PRED)
  347. x->vop_flags |= XVID_VOP_HQACPRED; /* Level 6 */
  348. if (xvid_flags & CODEC_FLAG_GRAY)
  349. x->vop_flags |= XVID_VOP_GREYSCALE;
  350. /* Decide which ME quality setting to use */
  351. x->me_flags = 0;
  352. switch (x->me_quality) {
  353. case 6:
  354. case 5:
  355. x->me_flags |= XVID_ME_EXTSEARCH16 |
  356. XVID_ME_EXTSEARCH8;
  357. case 4:
  358. case 3:
  359. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
  360. XVID_ME_HALFPELREFINE8 |
  361. XVID_ME_CHROMA_PVOP |
  362. XVID_ME_CHROMA_BVOP;
  363. case 2:
  364. case 1:
  365. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
  366. XVID_ME_HALFPELREFINE16;
  367. #if FF_API_MOTION_EST
  368. FF_DISABLE_DEPRECATION_WARNINGS
  369. break;
  370. default:
  371. switch (avctx->me_method) {
  372. case ME_FULL: /* Quality 6 */
  373. x->me_flags |= XVID_ME_EXTSEARCH16 |
  374. XVID_ME_EXTSEARCH8;
  375. case ME_EPZS: /* Quality 4 */
  376. x->me_flags |= XVID_ME_ADVANCEDDIAMOND8 |
  377. XVID_ME_HALFPELREFINE8 |
  378. XVID_ME_CHROMA_PVOP |
  379. XVID_ME_CHROMA_BVOP;
  380. case ME_LOG: /* Quality 2 */
  381. case ME_PHODS:
  382. case ME_X1:
  383. x->me_flags |= XVID_ME_ADVANCEDDIAMOND16 |
  384. XVID_ME_HALFPELREFINE16;
  385. case ME_ZERO: /* Quality 0 */
  386. default:
  387. break;
  388. }
  389. FF_ENABLE_DEPRECATION_WARNINGS
  390. #endif
  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 ffmpeg command-line */
  409. #if FF_API_GMC
  410. if (avctx->flags & CODEC_FLAG_GMC)
  411. x->gmc = 1;
  412. #endif
  413. x->vol_flags = 0;
  414. if (x->gmc) {
  415. x->vol_flags |= XVID_VOL_GMC;
  416. x->me_flags |= XVID_ME_GME_REFINE;
  417. }
  418. if (xvid_flags & CODEC_FLAG_QPEL) {
  419. x->vol_flags |= XVID_VOL_QUARTERPEL;
  420. x->me_flags |= XVID_ME_QUARTERPELREFINE16;
  421. if (x->vop_flags & XVID_VOP_INTER4V)
  422. x->me_flags |= XVID_ME_QUARTERPELREFINE8;
  423. }
  424. xvid_gbl_init.version = XVID_VERSION;
  425. xvid_gbl_init.debug = 0;
  426. xvid_gbl_init.cpu_flags = 0;
  427. /* Initialize */
  428. xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
  429. /* Create the encoder reference */
  430. xvid_enc_create.version = XVID_VERSION;
  431. /* Store the desired frame size */
  432. xvid_enc_create.width =
  433. x->xsize = avctx->width;
  434. xvid_enc_create.height =
  435. x->ysize = avctx->height;
  436. /* Xvid can determine the proper profile to use */
  437. /* xvid_enc_create.profile = XVID_PROFILE_S_L3; */
  438. /* We don't use zones */
  439. xvid_enc_create.zones = NULL;
  440. xvid_enc_create.num_zones = 0;
  441. xvid_enc_create.num_threads = avctx->thread_count;
  442. #if (XVID_VERSION <= 0x010303) && (XVID_VERSION >= 0x010300)
  443. /* workaround for a bug in libxvidcore */
  444. if (avctx->height <= 16) {
  445. if (avctx->thread_count < 2) {
  446. xvid_enc_create.num_threads = 0;
  447. } else {
  448. av_log(avctx, AV_LOG_ERROR,
  449. "Too small height for threads > 1.");
  450. return AVERROR(EINVAL);
  451. }
  452. }
  453. #endif
  454. xvid_enc_create.plugins = plugins;
  455. xvid_enc_create.num_plugins = 0;
  456. /* Initialize Buffers */
  457. x->twopassbuffer = NULL;
  458. x->old_twopassbuffer = NULL;
  459. x->twopassfile = NULL;
  460. if (xvid_flags & CODEC_FLAG_PASS1) {
  461. rc2pass1.version = XVID_VERSION;
  462. rc2pass1.context = x;
  463. x->twopassbuffer = av_malloc(BUFFER_SIZE);
  464. x->old_twopassbuffer = av_malloc(BUFFER_SIZE);
  465. if (!x->twopassbuffer || !x->old_twopassbuffer) {
  466. av_log(avctx, AV_LOG_ERROR,
  467. "Xvid: Cannot allocate 2-pass log buffers\n");
  468. return AVERROR(ENOMEM);
  469. }
  470. x->twopassbuffer[0] =
  471. x->old_twopassbuffer[0] = 0;
  472. plugins[xvid_enc_create.num_plugins].func = xvid_ff_2pass;
  473. plugins[xvid_enc_create.num_plugins].param = &rc2pass1;
  474. xvid_enc_create.num_plugins++;
  475. } else if (xvid_flags & CODEC_FLAG_PASS2) {
  476. rc2pass2.version = XVID_VERSION;
  477. rc2pass2.bitrate = avctx->bit_rate;
  478. fd = av_tempfile("xvidff.", &x->twopassfile, 0, avctx);
  479. if (fd < 0) {
  480. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write 2-pass pipe\n");
  481. return fd;
  482. }
  483. x->twopassfd = fd;
  484. if (!avctx->stats_in) {
  485. av_log(avctx, AV_LOG_ERROR,
  486. "Xvid: No 2-pass information loaded for second pass\n");
  487. return AVERROR(EINVAL);
  488. }
  489. ret = write(fd, avctx->stats_in, strlen(avctx->stats_in));
  490. if (ret == -1)
  491. ret = AVERROR(errno);
  492. else if (strlen(avctx->stats_in) > ret) {
  493. av_log(avctx, AV_LOG_ERROR, "Xvid: Cannot write to 2-pass pipe\n");
  494. ret = AVERROR(EIO);
  495. }
  496. if (ret < 0)
  497. return ret;
  498. rc2pass2.filename = x->twopassfile;
  499. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_2pass2;
  500. plugins[xvid_enc_create.num_plugins].param = &rc2pass2;
  501. xvid_enc_create.num_plugins++;
  502. } else if (!(xvid_flags & CODEC_FLAG_QSCALE)) {
  503. /* Single Pass Bitrate Control! */
  504. single.version = XVID_VERSION;
  505. single.bitrate = avctx->bit_rate;
  506. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_single;
  507. plugins[xvid_enc_create.num_plugins].param = &single;
  508. xvid_enc_create.num_plugins++;
  509. }
  510. if (avctx->lumi_masking != 0.0)
  511. x->lumi_aq = 1;
  512. /* Luminance Masking */
  513. if (x->lumi_aq) {
  514. masking_l.method = 0;
  515. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  516. /* The old behavior is that when avctx->lumi_masking is specified,
  517. * plugins[...].param = NULL. Trying to keep the old behavior here. */
  518. plugins[xvid_enc_create.num_plugins].param =
  519. avctx->lumi_masking ? NULL : &masking_l;
  520. xvid_enc_create.num_plugins++;
  521. }
  522. /* Variance AQ */
  523. if (x->variance_aq) {
  524. masking_v.method = 1;
  525. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_lumimasking;
  526. plugins[xvid_enc_create.num_plugins].param = &masking_v;
  527. xvid_enc_create.num_plugins++;
  528. }
  529. if (x->lumi_aq && x->variance_aq )
  530. av_log(avctx, AV_LOG_INFO,
  531. "Both lumi_aq and variance_aq are enabled. The resulting quality"
  532. "will be the worse one of the two effects made by the AQ.\n");
  533. /* SSIM */
  534. if (x->ssim) {
  535. plugins[xvid_enc_create.num_plugins].func = xvid_plugin_ssim;
  536. ssim.b_printstat = x->ssim == 2;
  537. ssim.acc = x->ssim_acc;
  538. ssim.cpu_flags = xvid_gbl_init.cpu_flags;
  539. ssim.b_visualize = 0;
  540. plugins[xvid_enc_create.num_plugins].param = &ssim;
  541. xvid_enc_create.num_plugins++;
  542. }
  543. /* Frame Rate and Key Frames */
  544. xvid_correct_framerate(avctx);
  545. xvid_enc_create.fincr = avctx->time_base.num;
  546. xvid_enc_create.fbase = avctx->time_base.den;
  547. if (avctx->gop_size > 0)
  548. xvid_enc_create.max_key_interval = avctx->gop_size;
  549. else
  550. xvid_enc_create.max_key_interval = 240; /* Xvid's best default */
  551. /* Quants */
  552. if (xvid_flags & CODEC_FLAG_QSCALE)
  553. x->qscale = 1;
  554. else
  555. x->qscale = 0;
  556. xvid_enc_create.min_quant[0] = avctx->qmin;
  557. xvid_enc_create.min_quant[1] = avctx->qmin;
  558. xvid_enc_create.min_quant[2] = avctx->qmin;
  559. xvid_enc_create.max_quant[0] = avctx->qmax;
  560. xvid_enc_create.max_quant[1] = avctx->qmax;
  561. xvid_enc_create.max_quant[2] = avctx->qmax;
  562. /* Quant Matrices */
  563. x->intra_matrix =
  564. x->inter_matrix = NULL;
  565. if (avctx->mpeg_quant)
  566. x->vol_flags |= XVID_VOL_MPEGQUANT;
  567. if ((avctx->intra_matrix || avctx->inter_matrix)) {
  568. x->vol_flags |= XVID_VOL_MPEGQUANT;
  569. if (avctx->intra_matrix) {
  570. intra = avctx->intra_matrix;
  571. x->intra_matrix = av_malloc(sizeof(unsigned char) * 64);
  572. if (!x->intra_matrix)
  573. return AVERROR(ENOMEM);
  574. } else
  575. intra = NULL;
  576. if (avctx->inter_matrix) {
  577. inter = avctx->inter_matrix;
  578. x->inter_matrix = av_malloc(sizeof(unsigned char) * 64);
  579. if (!x->inter_matrix)
  580. return AVERROR(ENOMEM);
  581. } else
  582. inter = NULL;
  583. for (i = 0; i < 64; i++) {
  584. if (intra)
  585. x->intra_matrix[i] = (unsigned char) intra[i];
  586. if (inter)
  587. x->inter_matrix[i] = (unsigned char) inter[i];
  588. }
  589. }
  590. /* Misc Settings */
  591. xvid_enc_create.frame_drop_ratio = 0;
  592. xvid_enc_create.global = 0;
  593. if (xvid_flags & CODEC_FLAG_CLOSED_GOP)
  594. xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
  595. /* Determines which codec mode we are operating in */
  596. avctx->extradata = NULL;
  597. avctx->extradata_size = 0;
  598. if (xvid_flags & CODEC_FLAG_GLOBAL_HEADER) {
  599. /* In this case, we are claiming to be MPEG4 */
  600. x->quicktime_format = 1;
  601. avctx->codec_id = AV_CODEC_ID_MPEG4;
  602. } else {
  603. /* We are claiming to be Xvid */
  604. x->quicktime_format = 0;
  605. if (!avctx->codec_tag)
  606. avctx->codec_tag = AV_RL32("xvid");
  607. }
  608. /* Bframes */
  609. xvid_enc_create.max_bframes = avctx->max_b_frames;
  610. xvid_enc_create.bquant_offset = 100 * avctx->b_quant_offset;
  611. xvid_enc_create.bquant_ratio = 100 * avctx->b_quant_factor;
  612. if (avctx->max_b_frames > 0 && !x->quicktime_format)
  613. xvid_enc_create.global |= XVID_GLOBAL_PACKED;
  614. av_assert0(xvid_enc_create.num_plugins + (!!x->ssim) + (!!x->variance_aq) + (!!x->lumi_aq) <= FF_ARRAY_ELEMS(plugins));
  615. /* Create encoder context */
  616. xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
  617. if (xerr) {
  618. av_log(avctx, AV_LOG_ERROR, "Xvid: Could not create encoder reference\n");
  619. return AVERROR_EXTERNAL;
  620. }
  621. x->encoder_handle = xvid_enc_create.handle;
  622. return 0;
  623. }
  624. static int xvid_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  625. const AVFrame *picture, int *got_packet)
  626. {
  627. int xerr, i, ret, user_packet = !!pkt->data;
  628. struct xvid_context *x = avctx->priv_data;
  629. int mb_width = (avctx->width + 15) / 16;
  630. int mb_height = (avctx->height + 15) / 16;
  631. char *tmp;
  632. xvid_enc_frame_t xvid_enc_frame = { 0 };
  633. xvid_enc_stats_t xvid_enc_stats = { 0 };
  634. if ((ret = ff_alloc_packet2(avctx, pkt, mb_width*(int64_t)mb_height*MAX_MB_BYTES + FF_MIN_BUFFER_SIZE, 0)) < 0)
  635. return ret;
  636. /* Start setting up the frame */
  637. xvid_enc_frame.version = XVID_VERSION;
  638. xvid_enc_stats.version = XVID_VERSION;
  639. /* Let Xvid know where to put the frame. */
  640. xvid_enc_frame.bitstream = pkt->data;
  641. xvid_enc_frame.length = pkt->size;
  642. /* Initialize input image fields */
  643. if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
  644. av_log(avctx, AV_LOG_ERROR,
  645. "Xvid: Color spaces other than 420P not supported\n");
  646. return AVERROR(EINVAL);
  647. }
  648. xvid_enc_frame.input.csp = XVID_CSP_PLANAR; /* YUV420P */
  649. for (i = 0; i < 4; i++) {
  650. xvid_enc_frame.input.plane[i] = picture->data[i];
  651. xvid_enc_frame.input.stride[i] = picture->linesize[i];
  652. }
  653. /* Encoder Flags */
  654. xvid_enc_frame.vop_flags = x->vop_flags;
  655. xvid_enc_frame.vol_flags = x->vol_flags;
  656. xvid_enc_frame.motion = x->me_flags;
  657. xvid_enc_frame.type =
  658. picture->pict_type == AV_PICTURE_TYPE_I ? XVID_TYPE_IVOP :
  659. picture->pict_type == AV_PICTURE_TYPE_P ? XVID_TYPE_PVOP :
  660. picture->pict_type == AV_PICTURE_TYPE_B ? XVID_TYPE_BVOP :
  661. XVID_TYPE_AUTO;
  662. /* Pixel aspect ratio setting */
  663. if (avctx->sample_aspect_ratio.num < 0 || avctx->sample_aspect_ratio.num > 255 ||
  664. avctx->sample_aspect_ratio.den < 0 || avctx->sample_aspect_ratio.den > 255) {
  665. av_log(avctx, AV_LOG_WARNING,
  666. "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
  667. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  668. av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,
  669. avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 255);
  670. }
  671. xvid_enc_frame.par = XVID_PAR_EXT;
  672. xvid_enc_frame.par_width = avctx->sample_aspect_ratio.num;
  673. xvid_enc_frame.par_height = avctx->sample_aspect_ratio.den;
  674. /* Quant Setting */
  675. if (x->qscale)
  676. xvid_enc_frame.quant = picture->quality / FF_QP2LAMBDA;
  677. else
  678. xvid_enc_frame.quant = 0;
  679. /* Matrices */
  680. xvid_enc_frame.quant_intra_matrix = x->intra_matrix;
  681. xvid_enc_frame.quant_inter_matrix = x->inter_matrix;
  682. /* Encode */
  683. xerr = xvid_encore(x->encoder_handle, XVID_ENC_ENCODE,
  684. &xvid_enc_frame, &xvid_enc_stats);
  685. /* Two-pass log buffer swapping */
  686. avctx->stats_out = NULL;
  687. if (x->twopassbuffer) {
  688. tmp = x->old_twopassbuffer;
  689. x->old_twopassbuffer = x->twopassbuffer;
  690. x->twopassbuffer = tmp;
  691. x->twopassbuffer[0] = 0;
  692. if (x->old_twopassbuffer[0] != 0) {
  693. avctx->stats_out = x->old_twopassbuffer;
  694. }
  695. }
  696. if (xerr > 0) {
  697. int pict_type;
  698. *got_packet = 1;
  699. if (xvid_enc_stats.type == XVID_TYPE_PVOP)
  700. pict_type = AV_PICTURE_TYPE_P;
  701. else if (xvid_enc_stats.type == XVID_TYPE_BVOP)
  702. pict_type = AV_PICTURE_TYPE_B;
  703. else if (xvid_enc_stats.type == XVID_TYPE_SVOP)
  704. pict_type = AV_PICTURE_TYPE_S;
  705. else
  706. pict_type = AV_PICTURE_TYPE_I;
  707. #if FF_API_CODED_FRAME
  708. FF_DISABLE_DEPRECATION_WARNINGS
  709. avctx->coded_frame->pict_type = pict_type;
  710. avctx->coded_frame->quality = xvid_enc_stats.quant * FF_QP2LAMBDA;
  711. FF_ENABLE_DEPRECATION_WARNINGS
  712. #endif
  713. ff_side_data_set_encoder_stats(pkt, xvid_enc_stats.quant * FF_QP2LAMBDA, NULL, 0, pict_type);
  714. if (xvid_enc_frame.out_flags & XVID_KEYFRAME) {
  715. #if FF_API_CODED_FRAME
  716. FF_DISABLE_DEPRECATION_WARNINGS
  717. avctx->coded_frame->key_frame = 1;
  718. FF_ENABLE_DEPRECATION_WARNINGS
  719. #endif
  720. pkt->flags |= AV_PKT_FLAG_KEY;
  721. if (x->quicktime_format)
  722. return xvid_strip_vol_header(avctx, pkt,
  723. xvid_enc_stats.hlength, xerr);
  724. } else {
  725. #if FF_API_CODED_FRAME
  726. FF_DISABLE_DEPRECATION_WARNINGS
  727. avctx->coded_frame->key_frame = 0;
  728. FF_ENABLE_DEPRECATION_WARNINGS
  729. #endif
  730. }
  731. pkt->size = xerr;
  732. return 0;
  733. } else {
  734. if (!user_packet)
  735. av_free_packet(pkt);
  736. if (!xerr)
  737. return 0;
  738. av_log(avctx, AV_LOG_ERROR,
  739. "Xvid: Encoding Error Occurred: %i\n", xerr);
  740. return AVERROR_EXTERNAL;
  741. }
  742. }
  743. static av_cold int xvid_encode_close(AVCodecContext *avctx)
  744. {
  745. struct xvid_context *x = avctx->priv_data;
  746. if (x->encoder_handle) {
  747. xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);
  748. x->encoder_handle = NULL;
  749. }
  750. av_freep(&avctx->extradata);
  751. if (x->twopassbuffer) {
  752. av_freep(&x->twopassbuffer);
  753. av_freep(&x->old_twopassbuffer);
  754. avctx->stats_out = NULL;
  755. }
  756. if (x->twopassfd>=0) {
  757. unlink(x->twopassfile);
  758. close(x->twopassfd);
  759. x->twopassfd = -1;
  760. }
  761. av_freep(&x->twopassfile);
  762. av_freep(&x->intra_matrix);
  763. av_freep(&x->inter_matrix);
  764. return 0;
  765. }
  766. #define OFFSET(x) offsetof(struct xvid_context, x)
  767. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  768. static const AVOption options[] = {
  769. { "lumi_aq", "Luminance masking AQ", OFFSET(lumi_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  770. { "variance_aq", "Variance AQ", OFFSET(variance_aq), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  771. { "ssim", "Show SSIM information to stdout", OFFSET(ssim), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, VE, "ssim" },
  772. { "off", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, INT_MIN, INT_MAX, VE, "ssim" },
  773. { "avg", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, INT_MIN, INT_MAX, VE, "ssim" },
  774. { "frame", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, INT_MIN, INT_MAX, VE, "ssim" },
  775. { "ssim_acc", "SSIM accuracy", OFFSET(ssim_acc), AV_OPT_TYPE_INT, { .i64 = 2 }, 0, 4, VE },
  776. { "gmc", "use GMC", OFFSET(gmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  777. { "me_quality", "Motion estimation quality", OFFSET(me_quality), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 6, VE },
  778. { NULL },
  779. };
  780. static const AVClass xvid_class = {
  781. .class_name = "libxvid",
  782. .item_name = av_default_item_name,
  783. .option = options,
  784. .version = LIBAVUTIL_VERSION_INT,
  785. };
  786. AVCodec ff_libxvid_encoder = {
  787. .name = "libxvid",
  788. .long_name = NULL_IF_CONFIG_SMALL("libxvidcore MPEG-4 part 2"),
  789. .type = AVMEDIA_TYPE_VIDEO,
  790. .id = AV_CODEC_ID_MPEG4,
  791. .priv_data_size = sizeof(struct xvid_context),
  792. .init = xvid_encode_init,
  793. .encode2 = xvid_encode_frame,
  794. .close = xvid_encode_close,
  795. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  796. .priv_class = &xvid_class,
  797. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
  798. FF_CODEC_CAP_INIT_CLEANUP,
  799. };