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.

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