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.

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