libxvid.c 31 KB

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