Add webm/VP8 support to native matroska demuxer.
[mplayer/glamo.git] / libmpcodecs / ve_xvid4.c
blobfc6aa2d23b40bc2dd82c1489cafa089523f2055e
1 /*
2 * - XviD 1.x decoder module for mplayer/mencoder -
4 * Copyright(C) 2003 Marco Belli <elcabesa@inwind.it>
5 * 2003-2004 Edouard Gomez <ed.gomez@free.fr>
7 * This file is part of MPlayer.
9 * MPlayer is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * MPlayer is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 /*****************************************************************************
25 * Includes
26 ****************************************************************************/
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <math.h>
33 #include <limits.h>
34 #include <time.h>
36 #include "config.h"
37 #include "mp_msg.h"
39 #include "codec-cfg.h"
40 #include "stream/stream.h"
41 #include "libmpdemux/demuxer.h"
42 #include "libmpdemux/stheader.h"
44 #include "stream/stream.h"
45 #include "libmpdemux/muxer.h"
47 #include "img_format.h"
48 #include "mp_image.h"
49 #include "vf.h"
51 #include <xvid.h>
52 #include <stdio.h>
53 #include <stdarg.h>
54 #include <limits.h>
55 #include <assert.h>
57 #include "m_option.h"
58 #include "libavutil/avutil.h"
60 #define FINE (!0)
61 #define BAD (!FINE)
63 #define MAX_ZONES 64
65 // Profile flag definitions
66 #define PROFILE_ADAPTQUANT 0x00000001
67 #define PROFILE_BVOP 0x00000002
68 #define PROFILE_MPEGQUANT 0x00000004
69 #define PROFILE_INTERLACE 0x00000008
70 #define PROFILE_QPEL 0x00000010
71 #define PROFILE_GMC 0x00000020
72 #define PROFILE_4MV 0x00000040
73 #define PROFILE_DXN 0x00000080
75 // Reduce code duplication in profiles[] array
76 #define PROFILE_S (PROFILE_4MV)
77 #define PROFILE_AS (PROFILE_4MV|PROFILE_ADAPTQUANT|PROFILE_BVOP|PROFILE_MPEGQUANT|PROFILE_INTERLACE|PROFILE_QPEL|PROFILE_GMC)
79 typedef const struct
81 const char *name; ///< profile name
82 int id; ///< mpeg-4 profile id; iso/iec 14496-2:2001 table G-1
83 int width; ///< profile width restriction
84 int height; ///< profile height restriction
85 int fps; ///< profile frame rate restriction
86 int max_objects; ///< ??????
87 int total_vmv_buffer_sz; ///< macroblock memory; when BVOPS=false, vmv = 2*vcv; when BVOPS=true, vmv = 3*vcv
88 int max_vmv_buffer_sz; ///< max macroblocks per vop
89 int vcv_decoder_rate; ///< macroblocks decoded per second
90 int max_acpred_mbs; ///< percentage
91 int max_vbv_size; ///< max vbv size (bits) 16368 bits
92 int max_video_packet_length; ///< bits
93 int max_bitrate; ///< bits per second
94 int vbv_peakrate; ///< max bits over anyone second period; 0=don't care
95 int dxn_max_bframes; ///< dxn: max consecutive bframes
96 unsigned int flags; ///< flags for allowed options/dxn note the definitions for PROFILE_S and PROFILE_AS
97 } profile_t;
99 // Code taken from XviD VfW source for profile support
101 /* default vbv_occupancy is (64/170)*vbv_buffer_size */
103 static const profile_t profiles[] =
105 /* name p@l w h fps obj Tvmv vmv vcv ac% vbv pkt bps vbv_peak dbf flags */
106 /* unrestricted profile (default) */
107 { "unrestricted", 0x00, 0, 0, 0, 0, 0, 0, 0, 100, 0*16368, -1, 0, 0, -1, 0xffffffff & ~PROFILE_DXN },
109 { "sp0", 0x08, 176, 144, 15, 1, 198, 99, 1485, 100, 10*16368, 2048, 64000, 0, -1, PROFILE_S },
110 /* simple@l0: max f_code=1, intra_dc_vlc_threshold=0 */
111 /* if ac preidition is used, adaptive quantization must not be used */
112 /* <=qcif must be used */
113 { "sp1", 0x01, 176, 144, 15, 4, 198, 99, 1485, 100, 10*16368, 2048, 64000, 0, -1, PROFILE_S|PROFILE_ADAPTQUANT },
114 { "sp2", 0x02, 352, 288, 15, 4, 792, 396, 5940, 100, 40*16368, 4096, 128000, 0, -1, PROFILE_S|PROFILE_ADAPTQUANT },
115 { "sp3", 0x03, 352, 288, 15, 4, 792, 396, 11880, 100, 40*16368, 8192, 384000, 0, -1, PROFILE_S|PROFILE_ADAPTQUANT },
117 { "asp0", 0xf0, 176, 144, 30, 1, 297, 99, 2970, 100, 10*16368, 2048, 128000, 0, -1, PROFILE_AS },
118 { "asp1", 0xf1, 176, 144, 30, 4, 297, 99, 2970, 100, 10*16368, 2048, 128000, 0, -1, PROFILE_AS },
119 { "asp2", 0xf2, 352, 288, 15, 4, 1188, 396, 5940, 100, 40*16368, 4096, 384000, 0, -1, PROFILE_AS },
120 { "asp3", 0xf3, 352, 288, 30, 4, 1188, 396, 11880, 100, 40*16368, 4096, 768000, 0, -1, PROFILE_AS },
121 /* ISMA Profile 1, (ASP) @ L3b (CIF, 1.5 Mb/s) CIF(352x288), 30fps, 1.5Mbps max ??? */
122 { "asp4", 0xf4, 352, 576, 30, 4, 2376, 792, 23760, 50, 80*16368, 8192, 3000000, 0, -1, PROFILE_AS },
123 { "asp5", 0xf5, 720, 576, 30, 4, 4860, 1620, 48600, 25, 112*16368, 16384, 8000000, 0, -1, PROFILE_AS },
125 // information provided by DivXNetworks, USA.
126 // "DivX Certified Profile Compatibility v1.1", February 2005
127 { "dxnhandheld", 0x00, 176, 144, 15, 1, 198, 99, 1485, 100, 32*8192, -1, 537600, 800000, 0, PROFILE_ADAPTQUANT|PROFILE_DXN },
128 { "dxnportntsc", 0x00, 352, 240, 30, 1, 990, 330, 36000, 100, 384*8192, -1, 4854000, 8000000, 1, PROFILE_4MV|PROFILE_ADAPTQUANT|PROFILE_BVOP|PROFILE_DXN },
129 { "dxnportpal", 0x00, 352, 288, 25, 1, 1188, 396, 36000, 100, 384*8192, -1, 4854000, 8000000, 1, PROFILE_4MV|PROFILE_ADAPTQUANT|PROFILE_BVOP|PROFILE_DXN },
130 { "dxnhtntsc", 0x00, 720, 480, 30, 1, 4050, 1350, 40500, 100, 384*8192, -1, 4854000, 8000000, 1, PROFILE_4MV|PROFILE_ADAPTQUANT|PROFILE_BVOP|PROFILE_INTERLACE|PROFILE_DXN },
131 { "dxnhtpal", 0x00, 720, 576, 25, 1, 4860, 1620, 40500, 100, 384*8192, -1, 4854000, 8000000, 1, PROFILE_4MV|PROFILE_ADAPTQUANT|PROFILE_BVOP|PROFILE_INTERLACE|PROFILE_DXN },
132 { "dxnhdtv", 0x00, 1280, 720, 30, 1,10800, 3600, 108000, 100, 768*8192, -1, 9708400, 16000000, 2, PROFILE_4MV|PROFILE_ADAPTQUANT|PROFILE_BVOP|PROFILE_INTERLACE|PROFILE_DXN },
134 { NULL, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00000000 },
138 * \brief return the pointer to a chosen profile
139 * \param str the profile name
140 * \return pointer of the appropriate profiles array entry or NULL for a mistyped profile name
142 static const profile_t *profileFromName(const char *str)
144 profile_t *cur = profiles;
145 while (cur->name && strcasecmp(cur->name, str)) cur++;
146 if(!cur->name) return NULL;
147 return cur;
150 /*****************************************************************************
151 * Configuration options
152 ****************************************************************************/
154 extern char* passtmpfile;
156 static int xvidenc_bitrate = 0;
157 static int xvidenc_pass = 0;
158 static float xvidenc_quantizer = 0;
160 static int xvidenc_packed = 0;
161 static int xvidenc_closed_gop = 1;
162 static int xvidenc_interlaced = 0;
163 static int xvidenc_quarterpel = 0;
164 static int xvidenc_gmc = 0;
165 static int xvidenc_trellis = 1;
166 static int xvidenc_cartoon = 0;
167 static int xvidenc_hqacpred = 1;
168 static int xvidenc_chromame = 1;
169 static int xvidenc_chroma_opt = 0;
170 static int xvidenc_vhq = 1;
171 static int xvidenc_bvhq = 1;
172 static int xvidenc_motion = 6;
173 static int xvidenc_turbo = 0;
174 static int xvidenc_stats = 0;
175 static int xvidenc_max_key_interval = 0; /* Let xvidcore set a 10s interval by default */
176 static int xvidenc_frame_drop_ratio = 0;
177 static int xvidenc_greyscale = 0;
178 static int xvidenc_luminance_masking = 0;
179 static int xvidenc_debug = 0;
180 static int xvidenc_psnr = 0;
182 static int xvidenc_max_bframes = 2;
183 static int xvidenc_num_threads = 0;
184 static int xvidenc_bquant_ratio = 150;
185 static int xvidenc_bquant_offset = 100;
186 static int xvidenc_bframe_threshold = 0;
188 static int xvidenc_min_quant[3] = {2, 2, 2};
189 static int xvidenc_max_quant[3] = {31, 31, 31};
190 static char *xvidenc_intra_matrix_file = NULL;
191 static char *xvidenc_inter_matrix_file = NULL;
192 static char *xvidenc_quant_method = NULL;
194 static int xvidenc_cbr_reaction_delay_factor = 0;
195 static int xvidenc_cbr_averaging_period = 0;
196 static int xvidenc_cbr_buffer = 0;
198 static int xvidenc_vbr_keyframe_boost = 0;
199 static int xvidenc_vbr_overflow_control_strength = 5;
200 static int xvidenc_vbr_curve_compression_high = 0;
201 static int xvidenc_vbr_curve_compression_low = 0;
202 static int xvidenc_vbr_max_overflow_improvement = 5;
203 static int xvidenc_vbr_max_overflow_degradation = 5;
204 static int xvidenc_vbr_kfreduction = 0;
205 static int xvidenc_vbr_kfthreshold = 0;
206 static int xvidenc_vbr_container_frame_overhead = 24; /* mencoder uses AVI container */
208 // commandline profile option string - default to unrestricted
209 static char *xvidenc_profile = "unrestricted";
211 static char *xvidenc_par = NULL;
212 static int xvidenc_par_width = 0;
213 static int xvidenc_par_height = 0;
214 static float xvidenc_dar_aspect = 0.0f;
215 static int xvidenc_autoaspect = 0;
217 static char *xvidenc_zones = NULL; // zones string
219 const m_option_t xvidencopts_conf[] =
221 /* Standard things mencoder should be able to treat directly */
222 {"bitrate", &xvidenc_bitrate, CONF_TYPE_INT, 0, 0, 0, NULL},
223 {"pass", &xvidenc_pass, CONF_TYPE_INT, CONF_RANGE, 1, 2, NULL},
224 {"fixed_quant", &xvidenc_quantizer, CONF_TYPE_FLOAT, CONF_RANGE, 1, 31, NULL},
226 /* Features */
227 {"quant_type", &xvidenc_quant_method, CONF_TYPE_STRING, 0, 0, 0, NULL},
228 {"me_quality", &xvidenc_motion, CONF_TYPE_INT, CONF_RANGE, 0, 6, NULL},
229 {"chroma_me", &xvidenc_chromame, CONF_TYPE_FLAG, 0, 0, 1, NULL},
230 {"nochroma_me", &xvidenc_chromame, CONF_TYPE_FLAG, 0, 1, 0, NULL},
231 {"chroma_opt", &xvidenc_chroma_opt, CONF_TYPE_FLAG, 0, 0, 1, NULL},
232 {"nochroma_opt", &xvidenc_chroma_opt, CONF_TYPE_FLAG, 0, 1, 0, NULL},
233 {"vhq", &xvidenc_vhq, CONF_TYPE_INT, CONF_RANGE, 0, 4, NULL},
234 {"bvhq", &xvidenc_bvhq, CONF_TYPE_INT, CONF_RANGE, 0, 1, NULL},
235 {"max_bframes", &xvidenc_max_bframes, CONF_TYPE_INT, CONF_RANGE, 0, 20, NULL},
236 {"threads", &xvidenc_num_threads, CONF_TYPE_INT, 0, 0, 0, NULL},
237 {"bquant_ratio", &xvidenc_bquant_ratio, CONF_TYPE_INT, CONF_RANGE, 0, 200, NULL},
238 {"bquant_offset", &xvidenc_bquant_offset, CONF_TYPE_INT, CONF_RANGE, 0, 200, NULL},
239 {"bf_threshold", &xvidenc_bframe_threshold, CONF_TYPE_INT, CONF_RANGE, -255, 255, NULL},
240 {"qpel", &xvidenc_quarterpel, CONF_TYPE_FLAG, 0, 0, 1, NULL},
241 {"noqpel", &xvidenc_quarterpel, CONF_TYPE_FLAG, 0, 1, 0, NULL},
242 {"gmc", &xvidenc_gmc, CONF_TYPE_FLAG, 0, 0, 1, NULL},
243 {"nogmc", &xvidenc_gmc, CONF_TYPE_FLAG, 0, 1, 0, NULL},
244 {"trellis", &xvidenc_trellis, CONF_TYPE_FLAG, 0, 0, 1, NULL},
245 {"notrellis", &xvidenc_trellis, CONF_TYPE_FLAG, 0, 1, 0, NULL},
246 {"packed", &xvidenc_packed, CONF_TYPE_FLAG, 0, 0, 1, NULL},
247 {"nopacked", &xvidenc_packed, CONF_TYPE_FLAG, 0, 1, 0, NULL},
248 {"closed_gop", &xvidenc_closed_gop, CONF_TYPE_FLAG, 0, 0, 1, NULL},
249 {"noclosed_gop", &xvidenc_closed_gop, CONF_TYPE_FLAG, 0, 1, 0, NULL},
250 {"interlacing", &xvidenc_interlaced, CONF_TYPE_FLAG, 0, 0, 1, NULL},
251 {"nointerlacing", &xvidenc_interlaced, CONF_TYPE_FLAG, 0, 1, 0, NULL},
252 {"cartoon", &xvidenc_cartoon, CONF_TYPE_FLAG, 0, 0, 1, NULL},
253 {"nocartoon", &xvidenc_cartoon, CONF_TYPE_FLAG, 0, 1, 0, NULL},
254 {"hq_ac", &xvidenc_hqacpred, CONF_TYPE_FLAG, 0, 0, 1, NULL},
255 {"nohq_ac", &xvidenc_hqacpred, CONF_TYPE_FLAG, 0, 1, 0, NULL},
256 {"frame_drop_ratio", &xvidenc_frame_drop_ratio, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
257 {"max_key_interval", &xvidenc_max_key_interval, CONF_TYPE_INT, CONF_MIN, 0, 0, NULL},
258 {"greyscale", &xvidenc_greyscale, CONF_TYPE_FLAG, 0, 0, 1, NULL}, /* kept for backward compatibility */
259 {"grayscale", &xvidenc_greyscale, CONF_TYPE_FLAG, 0, 0, 1, NULL},
260 {"nogreyscale", &xvidenc_greyscale, CONF_TYPE_FLAG, 0, 1, 0, NULL},
261 {"lumi_mask", &xvidenc_luminance_masking, CONF_TYPE_FLAG, 0, 0, 1, NULL},
262 {"nolumi_mask", &xvidenc_luminance_masking, CONF_TYPE_FLAG, 0, 1, 0, NULL},
263 {"turbo", &xvidenc_turbo, CONF_TYPE_FLAG, 0, 0, 1, NULL},
264 {"debug", &xvidenc_debug, CONF_TYPE_INT , 0 ,0,-1,NULL},
265 {"stats", &xvidenc_stats, CONF_TYPE_FLAG, 0, 0, 1, NULL},
266 {"psnr", &xvidenc_psnr , CONF_TYPE_FLAG, 0, 0, 1, NULL},
269 /* section [quantizer] */
270 {"min_iquant", &xvidenc_min_quant[0], CONF_TYPE_INT, CONF_RANGE, 1, 31, NULL},
271 {"max_iquant", &xvidenc_max_quant[0], CONF_TYPE_INT, CONF_RANGE, 1, 31, NULL},
272 {"min_pquant", &xvidenc_min_quant[1], CONF_TYPE_INT, CONF_RANGE, 1, 31, NULL},
273 {"max_pquant", &xvidenc_max_quant[1], CONF_TYPE_INT, CONF_RANGE, 1, 31, NULL},
274 {"min_bquant", &xvidenc_min_quant[2], CONF_TYPE_INT, CONF_RANGE, 1, 31, NULL},
275 {"max_bquant", &xvidenc_max_quant[2], CONF_TYPE_INT, CONF_RANGE, 1, 31, NULL},
276 {"quant_intra_matrix", &xvidenc_intra_matrix_file, CONF_TYPE_STRING, 0, 0, 100, NULL},
277 {"quant_inter_matrix", &xvidenc_inter_matrix_file, CONF_TYPE_STRING, 0, 0, 100, NULL},
279 /* section [cbr] */
280 {"rc_reaction_delay_factor", &xvidenc_cbr_reaction_delay_factor, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
281 {"rc_averaging_period", &xvidenc_cbr_averaging_period, CONF_TYPE_INT, CONF_MIN, 0, 0, NULL},
282 {"rc_buffer", &xvidenc_cbr_buffer, CONF_TYPE_INT, CONF_MIN, 0, 0, NULL},
284 /* section [vbr] */
285 {"keyframe_boost", &xvidenc_vbr_keyframe_boost, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
286 {"curve_compression_high", &xvidenc_vbr_curve_compression_high, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
287 {"curve_compression_low", &xvidenc_vbr_curve_compression_low, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
288 {"overflow_control_strength", &xvidenc_vbr_overflow_control_strength, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
289 {"max_overflow_improvement", &xvidenc_vbr_max_overflow_improvement, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
290 {"max_overflow_degradation", &xvidenc_vbr_max_overflow_degradation, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
291 {"kfreduction", &xvidenc_vbr_kfreduction, CONF_TYPE_INT, CONF_RANGE, 0, 100, NULL},
292 {"kfthreshold", &xvidenc_vbr_kfthreshold, CONF_TYPE_INT, CONF_MIN, 0, 0, NULL},
293 {"container_frame_overhead", &xvidenc_vbr_container_frame_overhead, CONF_TYPE_INT, CONF_MIN, 0, 0, NULL},
295 /* Section Aspect Ratio */
296 {"par", &xvidenc_par, CONF_TYPE_STRING, 0, 0, 0, NULL},
297 {"par_width", &xvidenc_par_width, CONF_TYPE_INT, CONF_RANGE, 0, 255, NULL},
298 {"par_height", &xvidenc_par_height, CONF_TYPE_INT, CONF_RANGE, 0, 255, NULL},
299 {"aspect", &xvidenc_dar_aspect, CONF_TYPE_FLOAT, CONF_RANGE, 0.1, 9.99, NULL},
300 {"autoaspect", &xvidenc_autoaspect, CONF_TYPE_FLAG, 0, 0, 1, NULL},
301 {"noautoaspect", &xvidenc_autoaspect, CONF_TYPE_FLAG, 0, 1, 0, NULL},
303 /* Section Zones */
304 {"zones", &xvidenc_zones, CONF_TYPE_STRING, 0, 0, 0, NULL},
306 /* section profiles */
307 {"profile", &xvidenc_profile, CONF_TYPE_STRING, 0, 0, 0, NULL},
309 /* End of the config array */
310 {NULL, 0, 0, 0, 0, 0, NULL}
313 /*****************************************************************************
314 * Module private data
315 ****************************************************************************/
317 typedef struct xvid_mplayer_module_t
319 /* Instance related global vars */
320 void *instance;
321 xvid_gbl_init_t init;
322 xvid_enc_create_t create;
323 xvid_enc_frame_t frame;
324 xvid_plugin_single_t onepass;
325 xvid_plugin_2pass1_t pass1;
326 xvid_plugin_2pass2_t pass2;
328 /* This data must survive local block scope, so here it is */
329 xvid_enc_plugin_t plugins[7];
330 xvid_enc_zone_t zones[MAX_ZONES];
332 /* MPEG4 stream buffer */
333 muxer_stream_t *mux;
335 /* Stats accumulators */
336 int frames;
337 long long sse_y;
338 long long sse_u;
339 long long sse_v;
341 /* Min & Max PSNR */
342 int min_sse_y;
343 int min_sse_u;
344 int min_sse_v;
345 int min_framenum;
346 int max_sse_y;
347 int max_sse_u;
348 int max_sse_v;
349 int max_framenum;
351 int pixels;
353 /* DAR/PAR and all that thingies */
354 int d_width;
355 int d_height;
356 FILE *fvstats;
357 } xvid_mplayer_module_t;
359 static int dispatch_settings(xvid_mplayer_module_t *mod);
360 static int set_create_struct(xvid_mplayer_module_t *mod);
361 static int set_frame_struct(xvid_mplayer_module_t *mod, mp_image_t *mpi);
362 static void update_stats(xvid_mplayer_module_t *mod, xvid_enc_stats_t *stats);
363 static void print_stats(xvid_mplayer_module_t *mod);
364 static void flush_internal_buffers(xvid_mplayer_module_t *mod);
365 static const char *par_string(int parcode);
366 static const char *errorstring(int err);
368 /*****************************************************************************
369 * Video Filter API function definitions
370 ****************************************************************************/
372 /*============================================================================
373 * config
374 *==========================================================================*/
376 static int
377 config(struct vf_instance *vf,
378 int width, int height, int d_width, int d_height,
379 unsigned int flags, unsigned int outfmt)
381 int err;
382 xvid_mplayer_module_t *mod = (xvid_mplayer_module_t *)vf->priv;
384 /* Complete the muxer initialization */
385 mod->mux->bih->biWidth = width;
386 mod->mux->bih->biHeight = height;
387 mod->mux->bih->biSizeImage =
388 mod->mux->bih->biWidth * mod->mux->bih->biHeight * 3 / 2;
389 mod->mux->aspect = (float)d_width/d_height;
391 /* Message the FourCC type */
392 mp_msg(MSGT_MENCODER, MSGL_INFO,
393 "videocodec: XviD (%dx%d fourcc=%x [%.4s])\n",
394 width, height, mod->mux->bih->biCompression,
395 (char *)&mod->mux->bih->biCompression);
397 /* Total number of pixels per frame required for PSNR */
398 mod->pixels = mod->mux->bih->biWidth*mod->mux->bih->biHeight;
400 /*--------------------------------------------------------------------
401 * Dispatch all module settings to XviD structures
402 *------------------------------------------------------------------*/
404 mod->d_width = d_width;
405 mod->d_height = d_height;
407 if(dispatch_settings(mod) == BAD)
408 return BAD;
410 /*--------------------------------------------------------------------
411 * Set remaining information in the xvid_enc_create_t structure
412 *------------------------------------------------------------------*/
414 if(set_create_struct(mod) == BAD)
415 return BAD;
417 /*--------------------------------------------------------------------
418 * Encoder instance creation
419 *------------------------------------------------------------------*/
421 err = xvid_encore(NULL, XVID_ENC_CREATE, &mod->create, NULL);
423 if(err<0) {
424 mp_msg(MSGT_MENCODER, MSGL_ERR,
425 "xvid: xvidcore returned a '%s' error\n", errorstring(err));
426 return BAD;
429 /* Store the encoder instance into the private data */
430 mod->instance = mod->create.handle;
432 mod->mux->decoder_delay = mod->create.max_bframes ? 1 : 0;
434 return FINE;
437 /*============================================================================
438 * uninit
439 *==========================================================================*/
441 static void
442 uninit(struct vf_instance *vf)
445 xvid_mplayer_module_t *mod = (xvid_mplayer_module_t *)vf->priv;
447 /* Destroy xvid instance */
448 xvid_encore(mod->instance, XVID_ENC_DESTROY, NULL, NULL);
450 /* Display stats (if any) */
451 print_stats(mod);
453 /* Close PSNR file if ever opened */
454 if (mod->fvstats) {
455 fclose(mod->fvstats);
456 mod->fvstats = NULL;
459 /* Free allocated memory */
460 if(mod->frame.quant_intra_matrix)
461 free(mod->frame.quant_intra_matrix);
463 if(mod->frame.quant_inter_matrix)
464 free(mod->frame.quant_inter_matrix);
466 if(mod->mux->bih)
467 free(mod->mux->bih);
469 free(vf->priv);
470 vf->priv=NULL;
472 return;
475 /*============================================================================
476 * control
477 *==========================================================================*/
479 static int
480 control(struct vf_instance *vf, int request, void* data)
482 xvid_mplayer_module_t *mod = (xvid_mplayer_module_t *)vf->priv;
484 switch(request){
485 case VFCTRL_FLUSH_FRAMES:
486 if(mod)/*paranoid*/
487 flush_internal_buffers(mod);
488 break;
490 return CONTROL_UNKNOWN;
493 /*============================================================================
494 * query_format
495 *==========================================================================*/
497 static int
498 query_format(struct vf_instance *vf, unsigned int fmt)
500 switch(fmt){
501 case IMGFMT_YV12:
502 case IMGFMT_IYUV:
503 case IMGFMT_I420:
504 return VFCAP_CSP_SUPPORTED | VFCAP_CSP_SUPPORTED_BY_HW;
505 case IMGFMT_YUY2:
506 case IMGFMT_UYVY:
507 return VFCAP_CSP_SUPPORTED;
509 return BAD;
512 /*============================================================================
513 * put_image
514 *==========================================================================*/
516 static int
517 put_image(struct vf_instance *vf, mp_image_t *mpi, double pts)
519 int size;
520 xvid_enc_stats_t stats;
521 xvid_mplayer_module_t *mod = (xvid_mplayer_module_t *)vf->priv;
523 /* Prepare the stats */
524 memset(&stats,0,sizeof( xvid_enc_stats_t));
525 stats.version = XVID_VERSION;
527 /* -------------------------------------------------------------------
528 * Set remaining information in the xvid_enc_frame_t structure
529 * NB: all the other struct members were initialized by
530 * dispatch_settings
531 * -----------------------------------------------------------------*/
533 if(set_frame_struct(mod, mpi) == BAD)
534 return BAD;
536 /* -------------------------------------------------------------------
537 * Encode the frame
538 * ---------------------------------------------------------------- */
540 size = xvid_encore(mod->instance, XVID_ENC_ENCODE, &mod->frame, &stats);
542 /* Analyse the returned value */
543 if(size<0) {
544 mp_msg(MSGT_MENCODER, MSGL_ERR,
545 "xvid: xvidcore returned a '%s' error\n", errorstring(size));
546 return BAD;
549 /* If size is == 0, we're done with that frame */
550 if(size == 0) {
551 ++mod->mux->encoder_delay;
552 return FINE;
555 /* xvidcore returns stats about encoded frame in an asynchronous way
556 * accumulate these stats */
557 update_stats(mod, &stats);
559 /* xvidcore outputed bitstream -- mux it */
560 muxer_write_chunk(mod->mux,
561 size,
562 (mod->frame.out_flags & XVID_KEYFRAME)?0x10:0, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
564 return FINE;
567 /*============================================================================
568 * vf_open
569 *==========================================================================*/
571 static int
572 vf_open(vf_instance_t *vf, char* args)
574 xvid_mplayer_module_t *mod;
575 xvid_gbl_init_t xvid_gbl_init;
576 xvid_gbl_info_t xvid_gbl_info;
578 /* Setting libmpcodec module API pointers */
579 vf->config = config;
580 vf->default_caps = VFCAP_CONSTANT;
581 vf->control = control;
582 vf->uninit = uninit;
583 vf->query_format = query_format;
584 vf->put_image = put_image;
586 /* Allocate the private part of the codec module */
587 vf->priv = malloc(sizeof(xvid_mplayer_module_t));
588 mod = (xvid_mplayer_module_t*)vf->priv;
590 if(mod == NULL) {
591 mp_msg(MSGT_MENCODER,MSGL_ERR,
592 "xvid: memory allocation failure (private data)\n");
593 return BAD;
596 /* Initialize the module to zeros */
597 memset(mod, 0, sizeof(xvid_mplayer_module_t));
598 mod->min_sse_y = mod->min_sse_u = mod->min_sse_v = INT_MAX;
599 mod->max_sse_y = mod->max_sse_u = mod->max_sse_v = INT_MIN;
601 /* Bind the Muxer */
602 mod->mux = (muxer_stream_t*)args;
604 /* Initialize muxer BITMAP header */
605 mod->mux->bih = calloc(1, sizeof(BITMAPINFOHEADER));
607 if(mod->mux->bih == NULL) {
608 mp_msg(MSGT_MENCODER,MSGL_ERR,
609 "xvid: memory allocation failure (BITMAP header)\n");
610 return BAD;
613 mod->mux->bih->biSize = sizeof(BITMAPINFOHEADER);
614 mod->mux->bih->biWidth = 0;
615 mod->mux->bih->biHeight = 0;
616 mod->mux->bih->biPlanes = 1;
617 mod->mux->bih->biBitCount = 12;
618 mod->mux->bih->biCompression = mmioFOURCC('X','V','I','D');
620 /* Retrieve information about the host XviD library */
621 memset(&xvid_gbl_info, 0, sizeof(xvid_gbl_info_t));
622 xvid_gbl_info.version = XVID_VERSION;
624 if (xvid_global(NULL, XVID_GBL_INFO, &xvid_gbl_info, NULL) < 0) {
625 mp_msg(MSGT_MENCODER,MSGL_WARN, "xvid: could not get information about the library\n");
626 } else {
627 mp_msg(MSGT_MENCODER,MSGL_INFO, "xvid: using library version %d.%d.%d (build %s)\n",
628 XVID_VERSION_MAJOR(xvid_gbl_info.actual_version),
629 XVID_VERSION_MINOR(xvid_gbl_info.actual_version),
630 XVID_VERSION_PATCH(xvid_gbl_info.actual_version),
631 xvid_gbl_info.build);
634 /* Initialize the xvid_gbl_init structure */
635 memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init_t));
636 xvid_gbl_init.version = XVID_VERSION;
637 xvid_gbl_init.debug = xvidenc_debug;
639 /* Initialize the xvidcore library */
640 if (xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL) < 0) {
641 mp_msg(MSGT_MENCODER,MSGL_ERR, "xvid: initialisation failure\n");
642 return BAD;
645 return FINE;
648 /*****************************************************************************
649 * Helper functions
650 ****************************************************************************/
652 static void *read_matrix(unsigned char *filename);
654 static int dispatch_settings(xvid_mplayer_module_t *mod)
656 xvid_enc_create_t *create = &mod->create;
657 xvid_enc_frame_t *frame = &mod->frame;
658 xvid_plugin_single_t *onepass = &mod->onepass;
659 xvid_plugin_2pass2_t *pass2 = &mod->pass2;
660 AVRational ar;
662 const int motion_presets[7] =
668 XVID_ME_HALFPELREFINE16,
669 XVID_ME_HALFPELREFINE16 | XVID_ME_ADVANCEDDIAMOND16,
670 XVID_ME_HALFPELREFINE16 | XVID_ME_EXTSEARCH16 |
671 XVID_ME_HALFPELREFINE8 | XVID_ME_USESQUARES16
674 //profile is unrestricted as default
675 const profile_t *selected_profile = profileFromName("unrestricted");
676 if(xvidenc_profile)
677 selected_profile = profileFromName(xvidenc_profile);
678 if(!selected_profile)
680 mp_msg(MSGT_MENCODER,MSGL_ERR,
681 "xvid:[ERROR] \"%s\" is an invalid profile name\n", xvidenc_profile);
682 return BAD;
685 /* -------------------------------------------------------------------
686 * Dispatch all settings having an impact on the "create" structure
687 * This includes plugins as they are passed to encore through the
688 * create structure
689 * -----------------------------------------------------------------*/
691 /* -------------------------------------------------------------------
692 * The create structure
693 * ---------------------------------------------------------------- */
695 create->global = 0;
697 if(xvidenc_psnr)
698 xvidenc_stats = 1;
700 if(xvidenc_stats)
701 create->global |= XVID_GLOBAL_EXTRASTATS_ENABLE;
703 create->num_zones = 0;
704 create->zones = NULL;
705 create->num_plugins = 0;
706 create->plugins = NULL;
707 create->num_threads = xvidenc_num_threads;
709 if( (selected_profile->flags & PROFILE_BVOP) &&
710 /* dxn: prevent bframes usage if interlacing is selected */
711 !((selected_profile->flags & PROFILE_DXN) && xvidenc_interlaced) )
713 create->max_bframes = xvidenc_max_bframes;
714 create->bquant_ratio = xvidenc_bquant_ratio;
715 create->bquant_offset = xvidenc_bquant_offset;
716 if(xvidenc_packed)
717 create->global |= XVID_GLOBAL_PACKED;
718 if(xvidenc_closed_gop)
719 create->global |= XVID_GLOBAL_CLOSED_GOP;
721 /* dxn: restrict max bframes, require closed gop
722 and require packed b-frames */
723 if(selected_profile->flags & PROFILE_DXN)
725 if(create->max_bframes > selected_profile->dxn_max_bframes)
726 create->max_bframes = selected_profile->dxn_max_bframes;
727 create->global |= XVID_GLOBAL_CLOSED_GOP;
728 create->global |= XVID_GLOBAL_PACKED;
731 else
732 create->max_bframes = 0;
734 #if XVID_API >= XVID_MAKE_API(4,1)
735 /* dxn: always write divx5 userdata */
736 if(selected_profile->flags & PROFILE_DXN)
737 create->global |= XVID_GLOBAL_DIVX5_USERDATA;
738 #endif
740 create->max_key_interval = xvidenc_max_key_interval;
741 create->frame_drop_ratio = xvidenc_frame_drop_ratio;
742 create->min_quant[0] = xvidenc_min_quant[0];
743 create->min_quant[1] = xvidenc_min_quant[1];
744 create->min_quant[2] = xvidenc_min_quant[2];
745 create->max_quant[0] = xvidenc_max_quant[0];
746 create->max_quant[1] = xvidenc_max_quant[1];
747 create->max_quant[2] = xvidenc_max_quant[2];
750 /* -------------------------------------------------------------------
751 * The single pass plugin
752 * ---------------------------------------------------------------- */
754 if (xvidenc_bitrate > 16000) onepass->bitrate = xvidenc_bitrate;
755 else onepass->bitrate = xvidenc_bitrate*1000;
756 onepass->reaction_delay_factor = xvidenc_cbr_reaction_delay_factor;
757 onepass->averaging_period = xvidenc_cbr_averaging_period;
758 onepass->buffer = xvidenc_cbr_buffer;
760 /* -------------------------------------------------------------------
761 * The pass2 plugin
762 * ---------------------------------------------------------------- */
764 pass2->keyframe_boost = xvidenc_vbr_keyframe_boost;
765 pass2->overflow_control_strength = xvidenc_vbr_overflow_control_strength;
766 pass2->curve_compression_high = xvidenc_vbr_curve_compression_high;
767 pass2->curve_compression_low = xvidenc_vbr_curve_compression_low;
768 pass2->max_overflow_improvement = xvidenc_vbr_max_overflow_improvement;
769 pass2->max_overflow_degradation = xvidenc_vbr_max_overflow_degradation;
770 pass2->kfreduction = xvidenc_vbr_kfreduction;
771 pass2->kfthreshold = xvidenc_vbr_kfthreshold;
772 pass2->container_frame_overhead = xvidenc_vbr_container_frame_overhead;
774 /* VBV */
776 #if XVID_API >= XVID_MAKE_API(4,1)
777 pass2->vbv_size = selected_profile->max_vbv_size;
778 pass2->vbv_initial = (selected_profile->max_vbv_size*3)>>2; /* 75% */
779 pass2->vbv_maxrate = selected_profile->max_bitrate;
780 pass2->vbv_peakrate = selected_profile->vbv_peakrate*3;
781 #endif
782 // XXX: xvidcore currently provides a "peak bits over 3 seconds" constraint.
783 // according to the latest dxn literature, a 1 second constraint is now used
785 create->profile = selected_profile->id;
787 /* -------------------------------------------------------------------
788 * The frame structure
789 * ---------------------------------------------------------------- */
790 frame->vol_flags = 0;
791 frame->vop_flags = 0;
792 frame->motion = 0;
794 frame->vop_flags |= XVID_VOP_HALFPEL;
795 frame->motion |= motion_presets[xvidenc_motion];
797 if(xvidenc_stats)
798 frame->vol_flags |= XVID_VOL_EXTRASTATS;
800 if(xvidenc_greyscale)
801 frame->vop_flags |= XVID_VOP_GREYSCALE;
803 if(xvidenc_cartoon) {
804 frame->vop_flags |= XVID_VOP_CARTOON;
805 frame->motion |= XVID_ME_DETECT_STATIC_MOTION;
808 // MPEG quantisation is only supported in ASP and unrestricted profiles
809 if((selected_profile->flags & PROFILE_MPEGQUANT) &&
810 (xvidenc_quant_method != NULL) &&
811 !strcasecmp(xvidenc_quant_method, "mpeg"))
813 frame->vol_flags |= XVID_VOL_MPEGQUANT;
814 if(xvidenc_intra_matrix_file != NULL) {
815 frame->quant_intra_matrix = (unsigned char*)read_matrix(xvidenc_intra_matrix_file);
816 if(frame->quant_intra_matrix != NULL) {
817 mp_msg(MSGT_MENCODER, MSGL_INFO, "xvid: Loaded Intra matrix (switching to mpeg quantization type)\n");
818 if(xvidenc_quant_method) free(xvidenc_quant_method);
819 xvidenc_quant_method = strdup("mpeg");
822 if(xvidenc_inter_matrix_file != NULL) {
823 frame->quant_inter_matrix = read_matrix(xvidenc_inter_matrix_file);
824 if(frame->quant_inter_matrix) {
825 mp_msg(MSGT_MENCODER, MSGL_INFO, "\nxvid: Loaded Inter matrix (switching to mpeg quantization type)\n");
826 if(xvidenc_quant_method) free(xvidenc_quant_method);
827 xvidenc_quant_method = strdup("mpeg");
831 if(xvidenc_quarterpel && (selected_profile->flags & PROFILE_QPEL)) {
832 frame->vol_flags |= XVID_VOL_QUARTERPEL;
833 frame->motion |= XVID_ME_QUARTERPELREFINE16;
834 frame->motion |= XVID_ME_QUARTERPELREFINE8;
836 if(xvidenc_gmc && (selected_profile->flags & PROFILE_GMC)) {
837 frame->vol_flags |= XVID_VOL_GMC;
838 frame->motion |= XVID_ME_GME_REFINE;
840 if(xvidenc_interlaced && (selected_profile->flags & PROFILE_INTERLACE)) {
841 frame->vol_flags |= XVID_VOL_INTERLACING;
843 if(xvidenc_trellis) {
844 frame->vop_flags |= XVID_VOP_TRELLISQUANT;
846 if(xvidenc_hqacpred) {
847 frame->vop_flags |= XVID_VOP_HQACPRED;
849 if(xvidenc_chroma_opt) {
850 frame->vop_flags |= XVID_VOP_CHROMAOPT;
852 if((xvidenc_motion > 4) && (selected_profile->flags & PROFILE_4MV)) {
853 frame->vop_flags |= XVID_VOP_INTER4V;
855 if(xvidenc_chromame) {
856 frame->motion |= XVID_ME_CHROMA_PVOP;
857 frame->motion |= XVID_ME_CHROMA_BVOP;
859 if(xvidenc_vhq >= 1) {
860 frame->vop_flags |= XVID_VOP_MODEDECISION_RD;
862 if(xvidenc_vhq >= 2) {
863 frame->motion |= XVID_ME_HALFPELREFINE16_RD;
864 frame->motion |= XVID_ME_QUARTERPELREFINE16_RD;
866 if(xvidenc_vhq >= 3) {
867 frame->motion |= XVID_ME_HALFPELREFINE8_RD;
868 frame->motion |= XVID_ME_QUARTERPELREFINE8_RD;
869 frame->motion |= XVID_ME_CHECKPREDICTION_RD;
871 if(xvidenc_vhq >= 4) {
872 frame->motion |= XVID_ME_EXTSEARCH_RD;
874 if(xvidenc_bvhq >= 1) {
875 #if XVID_API >= XVID_MAKE_API(4,1)
876 frame->vop_flags |= XVID_VOP_RD_BVOP;
877 #endif
879 if(xvidenc_turbo) {
880 frame->motion |= XVID_ME_FASTREFINE16;
881 frame->motion |= XVID_ME_FASTREFINE8;
882 frame->motion |= XVID_ME_SKIP_DELTASEARCH;
883 frame->motion |= XVID_ME_FAST_MODEINTERPOLATE;
884 frame->motion |= XVID_ME_BFRAME_EARLYSTOP;
887 /* motion level == 0 means no motion search which is equivalent to
888 * intra coding only */
889 if(xvidenc_motion == 0) {
890 frame->type = XVID_TYPE_IVOP;
891 } else {
892 frame->type = XVID_TYPE_AUTO;
895 frame->bframe_threshold = xvidenc_bframe_threshold;
897 /* PAR related initialization */
898 frame->par = XVID_PAR_11_VGA; /* Default */
900 if( !(selected_profile->flags & PROFILE_DXN) )
902 if(xvidenc_dar_aspect > 0)
903 ar = av_d2q(xvidenc_dar_aspect * mod->mux->bih->biHeight / mod->mux->bih->biWidth, 255);
904 else if(xvidenc_autoaspect)
905 ar = av_d2q((float)mod->d_width / mod->d_height * mod->mux->bih->biHeight / mod->mux->bih->biWidth, 255);
906 else ar.num = ar.den = 0;
908 if(ar.den != 0) {
909 if(ar.num == 12 && ar.den == 11)
910 frame->par = XVID_PAR_43_PAL;
911 else if(ar.num == 10 && ar.den == 11)
912 frame->par = XVID_PAR_43_NTSC;
913 else if(ar.num == 16 && ar.den == 11)
914 frame->par = XVID_PAR_169_PAL;
915 else if(ar.num == 40 && ar.den == 33)
916 frame->par = XVID_PAR_169_NTSC;
917 else
919 frame->par = XVID_PAR_EXT;
920 frame->par_width = ar.num;
921 frame->par_height= ar.den;
924 } else if(xvidenc_par != NULL) {
925 if(strcasecmp(xvidenc_par, "pal43") == 0)
926 frame->par = XVID_PAR_43_PAL;
927 else if(strcasecmp(xvidenc_par, "pal169") == 0)
928 frame->par = XVID_PAR_169_PAL;
929 else if(strcasecmp(xvidenc_par, "ntsc43") == 0)
930 frame->par = XVID_PAR_43_NTSC;
931 else if(strcasecmp(xvidenc_par, "ntsc169") == 0)
932 frame->par = XVID_PAR_169_NTSC;
933 else if(strcasecmp(xvidenc_par, "ext") == 0)
934 frame->par = XVID_PAR_EXT;
936 if(frame->par == XVID_PAR_EXT) {
937 if(xvidenc_par_width)
938 frame->par_width = xvidenc_par_width;
939 else
940 frame->par_width = 1;
942 if(xvidenc_par_height)
943 frame->par_height = xvidenc_par_height;
944 else
945 frame->par_height = 1;
949 /* Display par information */
950 mp_msg(MSGT_MENCODER, MSGL_INFO, "xvid: par=%d/%d (%s), displayed=%dx%d, sampled=%dx%d\n",
951 ar.num, ar.den, par_string(frame->par),
952 mod->d_width, mod->d_height, mod->mux->bih->biWidth, mod->mux->bih->biHeight);
954 else
955 mp_msg(MSGT_MENCODER, MSGL_INFO,
956 "xvid: par=0/0 (vga11) forced by choosing a DXN profile\n");
957 return FINE;
960 static int set_create_struct(xvid_mplayer_module_t *mod)
962 int pass;
963 int doZones = 0;
964 xvid_enc_create_t *create = &mod->create;
966 // profile is unrestricted as default
967 profile_t *selected_profile = profileFromName("unrestricted");
968 if(xvidenc_profile)
969 selected_profile = profileFromName(xvidenc_profile);
970 if(!selected_profile)
971 return BAD;
973 /* Most of the structure is initialized by dispatch settings, only a
974 * few things are missing */
975 create->version = XVID_VERSION;
977 /* Width and Height */
978 create->width = mod->mux->bih->biWidth;
979 create->height = mod->mux->bih->biHeight;
981 /* Check resolution of video to be coded is within profile width/height
982 restrictions */
983 if( ((selected_profile->width != 0) &&
984 (mod->mux->bih->biWidth > selected_profile->width)) ||
985 ((selected_profile->height != 0) &&
986 (mod->mux->bih->biHeight > selected_profile->height)) )
988 mp_msg(MSGT_MENCODER,MSGL_ERR,
989 "xvid:[ERROR] resolution must be <= %dx%d for the chosen profile\n",
990 selected_profile->width, selected_profile->height);
991 return BAD;
994 /* FPS */
995 create->fincr = mod->mux->h.dwScale;
996 create->fbase = mod->mux->h.dwRate;
998 // Check frame rate is within profile restrictions
999 if( ((float)mod->mux->h.dwRate/(float)mod->mux->h.dwScale > (float)selected_profile->fps) &&
1000 (selected_profile->fps != 0))
1002 mp_msg(MSGT_MENCODER,MSGL_ERR,
1003 "xvid:[ERROR] frame rate must be <= %d for the chosen profile\n",
1004 selected_profile->fps);
1005 return BAD;
1008 /* Encodings zones */
1009 memset(mod->zones, 0, sizeof(mod->zones));
1010 create->zones = mod->zones;
1011 create->num_zones = 0;
1013 /* Plugins */
1014 memset(mod->plugins, 0, sizeof(mod->plugins));
1015 create->plugins = mod->plugins;
1016 create->num_plugins = 0;
1018 /* -------------------------------------------------------------------
1019 * Initialize and bind the right rate controller plugin
1020 * ---------------------------------------------------------------- */
1022 /* First we try to sort out configuration conflicts */
1023 if(xvidenc_quantizer != 0 && (xvidenc_bitrate || xvidenc_pass)) {
1024 mp_msg(MSGT_MENCODER, MSGL_ERR,
1025 "xvid: you can't mix Fixed Quantizer Rate Control"
1026 " with other Rate Control mechanisms\n");
1027 return BAD;
1030 if(xvidenc_bitrate != 0 && xvidenc_pass == 1) {
1031 mp_msg(MSGT_MENCODER, MSGL_WARN,
1032 "xvid: bitrate setting is ignored during first pass\n");
1035 /* Sort out which sort of pass we are supposed to do
1036 * pass == 1<<0 CBR
1037 * pass == 1<<1 Two pass first pass
1038 * pass == 1<<2 Two pass second pass
1039 * pass == 1<<3 Constant quantizer
1041 #define MODE_CBR (1<<0)
1042 #define MODE_2PASS1 (1<<1)
1043 #define MODE_2PASS2 (1<<2)
1044 #define MODE_QUANT (1<<3)
1046 pass = 0;
1048 if(xvidenc_bitrate != 0 && xvidenc_pass == 0)
1049 pass |= MODE_CBR;
1051 if(xvidenc_pass == 1)
1052 pass |= MODE_2PASS1;
1054 if(xvidenc_bitrate != 0 && xvidenc_pass == 2)
1055 pass |= MODE_2PASS2;
1057 if(xvidenc_quantizer != 0 && xvidenc_pass == 0)
1058 pass |= MODE_QUANT;
1060 /* We must be in at least one RC mode */
1061 if(pass == 0) {
1062 mp_msg(MSGT_MENCODER, MSGL_ERR,
1063 "xvid: you must specify one or a valid combination of "
1064 "'bitrate', 'pass', 'fixed_quant' settings\n");
1065 return BAD;
1068 /* Sanity checking */
1069 if(pass != MODE_CBR && pass != MODE_QUANT &&
1070 pass != MODE_2PASS1 && pass != MODE_2PASS2) {
1071 mp_msg(MSGT_MENCODER, MSGL_ERR,
1072 "xvid: this code should not be reached - fill a bug "
1073 "report\n");
1074 return BAD;
1077 /* This is a single pass encoding: either a CBR pass or a constant
1078 * quantizer pass */
1079 if(pass == MODE_CBR || pass == MODE_QUANT) {
1080 xvid_plugin_single_t *onepass = &mod->onepass;
1082 /* There is not much left to initialize after dispatch settings */
1083 onepass->version = XVID_VERSION;
1084 if (xvidenc_bitrate > 16000) onepass->bitrate = xvidenc_bitrate;
1085 else onepass->bitrate = xvidenc_bitrate*1000;
1087 /* Quantizer mode uses the same plugin, we have only to define
1088 * a constant quantizer zone beginning at frame 0 */
1089 if(pass == MODE_QUANT) {
1090 AVRational squant;
1091 squant = av_d2q(xvidenc_quantizer,128);
1093 create->zones[create->num_zones].mode = XVID_ZONE_QUANT;
1094 create->zones[create->num_zones].frame = 0;
1095 create->zones[create->num_zones].increment = squant.num;
1096 create->zones[create->num_zones].base = squant.den;
1097 create->num_zones++;
1099 mp_msg(MSGT_MENCODER, MSGL_INFO,
1100 "xvid: Fixed Quant Rate Control -- quantizer=%d/%d=%2.2f\n",
1101 squant.num,
1102 squant.den,
1103 (float)(squant.num)/(float)(squant.den));
1105 } else {
1106 mp_msg(MSGT_MENCODER, MSGL_INFO,
1107 "xvid: CBR Rate Control -- bitrate=%dkbit/s\n",
1108 xvidenc_bitrate>16000?xvidenc_bitrate/1000:xvidenc_bitrate);
1109 doZones = 1;
1112 create->plugins[create->num_plugins].func = xvid_plugin_single;
1113 create->plugins[create->num_plugins].param = onepass;
1114 create->num_plugins++;
1117 /* This is the first pass of a Two pass process */
1118 if(pass == MODE_2PASS1) {
1119 xvid_plugin_2pass1_t *pass1 = &mod->pass1;
1121 /* There is not much to initialize for this plugin */
1122 pass1->version = XVID_VERSION;
1123 pass1->filename = passtmpfile;
1125 create->plugins[create->num_plugins].func = xvid_plugin_2pass1;
1126 create->plugins[create->num_plugins].param = pass1;
1127 create->num_plugins++;
1129 mp_msg(MSGT_MENCODER, MSGL_INFO,
1130 "xvid: 2Pass Rate Control -- 1st pass\n");
1133 /* This is the second pass of a Two pass process */
1134 if(pass == MODE_2PASS2) {
1135 xvid_plugin_2pass2_t *pass2 = &mod->pass2;
1137 /* There is not much left to initialize after dispatch settings */
1138 pass2->version = XVID_VERSION;
1139 pass2->filename = passtmpfile;
1141 /* Positive bitrate values are bitrates as usual but if the
1142 * value is negative it is considered as being a total size
1143 * to reach (in kilobytes) */
1144 if(xvidenc_bitrate > 0) {
1145 if(xvidenc_bitrate > 16000) pass2->bitrate = xvidenc_bitrate;
1146 else pass2->bitrate = xvidenc_bitrate*1000;
1147 mp_msg(MSGT_MENCODER, MSGL_INFO,
1148 "xvid: 2Pass Rate Control -- 2nd pass -- bitrate=%dkbit/s\n",
1149 xvidenc_bitrate>16000?xvidenc_bitrate/1000:xvidenc_bitrate);
1150 } else {
1151 pass2->bitrate = xvidenc_bitrate;
1152 mp_msg(MSGT_MENCODER, MSGL_INFO,
1153 "xvid: 2Pass Rate Control -- 2nd pass -- total size=%dkB\n",
1154 -xvidenc_bitrate);
1157 create->plugins[create->num_plugins].func = xvid_plugin_2pass2;
1158 create->plugins[create->num_plugins].param = pass2;
1159 create->num_plugins++;
1160 doZones = 1;
1163 if(xvidenc_luminance_masking && (selected_profile->flags & PROFILE_ADAPTQUANT)) {
1164 create->plugins[create->num_plugins].func = xvid_plugin_lumimasking;
1165 create->plugins[create->num_plugins].param = NULL;
1166 create->num_plugins++;
1169 // parse zones
1170 if (xvidenc_zones != NULL && doZones > 0) // do not apply zones in CQ, and first pass mode (xvid vfw doesn't allow them in those modes either)
1172 char *p;
1173 int i;
1174 p = xvidenc_zones;
1175 create->num_zones = 0; // set the number of zones back to zero, this overwrites the zone defined for CQ - desired because each zone has to be specified on the commandline even in cq mode
1176 for(i = 0; p; i++)
1178 int start;
1179 int q;
1180 double value;
1181 char mode;
1182 int e = sscanf(p, "%d,%c,%lf", &start, &mode, &value); // start,mode(q = constant quant, w = weight),value
1183 if(e != 3)
1185 mp_msg(MSGT_MENCODER,MSGL_ERR, "error parsing zones\n");
1186 return BAD;
1188 q = (int)(value * 100);
1189 if (mode == 'q')
1191 if (q < 200 || q > 3100) // make sure that quantizer is in allowable range
1193 mp_msg(MSGT_MENCODER, MSGL_ERR, "zone quantizer must be between 2 and 31\n");
1194 return BAD;
1196 else
1198 create->zones[create->num_zones].mode = XVID_ZONE_QUANT;
1201 if (mode == 'w')
1203 if (q < 1 || q > 200)
1205 mp_msg(MSGT_MENCODER, MSGL_ERR, "zone weight must be between 1 and 200\n");
1206 return BAD;
1208 else
1210 create->zones[create->num_zones].mode = XVID_ZONE_WEIGHT;
1213 create->zones[create->num_zones].frame = start;
1214 create->zones[create->num_zones].increment = q;
1215 create->zones[create->num_zones].base = 100; // increment is 100 times the actual value
1216 create->num_zones++;
1217 if (create->num_zones > MAX_ZONES) // show warning if we have too many zones
1219 mp_msg(MSGT_MENCODER, MSGL_ERR, "too many zones, zones will be ignored\n");
1221 p = strchr(p, '/');
1222 if(p) p++;
1225 return FINE;
1228 static int set_frame_struct(xvid_mplayer_module_t *mod, mp_image_t *mpi)
1230 xvid_enc_frame_t *frame = &mod->frame;
1232 /* Most of the initialization is done during dispatch_settings */
1233 frame->version = XVID_VERSION;
1235 /* Bind output buffer */
1236 frame->bitstream = mod->mux->buffer;
1237 frame->length = -1;
1239 /* Frame format */
1240 switch(mpi->imgfmt) {
1241 case IMGFMT_YV12:
1242 case IMGFMT_IYUV:
1243 case IMGFMT_I420:
1244 frame->input.csp = XVID_CSP_USER;
1245 break;
1246 case IMGFMT_YUY2:
1247 frame->input.csp = XVID_CSP_YUY2;
1248 break;
1249 case IMGFMT_UYVY:
1250 frame->input.csp = XVID_CSP_UYVY;
1251 break;
1252 default:
1253 mp_msg(MSGT_MENCODER, MSGL_ERR,
1254 "xvid: unsupported picture format (%s)!\n",
1255 vo_format_name(mpi->imgfmt));
1256 return BAD;
1259 /* Bind source frame */
1260 frame->input.plane[0] = mpi->planes[0];
1261 frame->input.plane[1] = mpi->planes[1];
1262 frame->input.plane[2] = mpi->planes[2];
1263 frame->input.stride[0] = mpi->stride[0];
1264 frame->input.stride[1] = mpi->stride[1];
1265 frame->input.stride[2] = mpi->stride[2];
1267 /* Force the right quantizer -- It is internally managed by RC
1268 * plugins */
1269 frame->quant = 0;
1271 return FINE;
1274 static void
1275 flush_internal_buffers(xvid_mplayer_module_t *mod)
1277 int size;
1278 xvid_enc_frame_t *frame = &mod->frame;
1280 if (mod->instance == NULL)
1281 return; /* encoder not initialized */
1283 /* Init a fake frame to force flushing */
1284 frame->version = XVID_VERSION;
1285 frame->bitstream = mod->mux->buffer;
1286 frame->length = -1;
1287 frame->input.csp = XVID_CSP_NULL;
1288 frame->input.plane[0] = NULL;
1289 frame->input.plane[1] = NULL;
1290 frame->input.plane[2] = NULL;
1291 frame->input.stride[0] = 0;
1292 frame->input.stride[1] = 0;
1293 frame->input.stride[2] = 0;
1294 frame->quant = 0;
1296 /* Flush encoder buffers caused by bframes usage */
1297 do {
1298 xvid_enc_stats_t stats;
1299 memset(&stats, 0, sizeof(xvid_enc_stats_t));
1300 stats.version = XVID_VERSION;
1302 /* Encode internal buffer */
1303 size = xvid_encore(mod->instance, XVID_ENC_ENCODE, &mod->frame, &stats);
1305 if (size>0) {
1306 /* Update stats */
1307 update_stats(mod, &stats);
1309 /* xvidcore outputed bitstream -- mux it */
1310 muxer_write_chunk(mod->mux, size,
1311 (mod->frame.out_flags & XVID_KEYFRAME)?0x10:0, MP_NOPTS_VALUE, MP_NOPTS_VALUE);
1313 } while (size>0);
1316 #define SSE2PSNR(sse, nbpixels) \
1317 ((!(sse)) ? 99.99f : 48.131f - 10*(double)log10((double)(sse)/(double)((nbpixels))))
1318 static void
1319 update_stats(xvid_mplayer_module_t *mod, xvid_enc_stats_t *stats)
1321 if(xvidenc_stats && stats->type > 0) {
1322 mod->sse_y += stats->sse_y;
1323 mod->sse_u += stats->sse_u;
1324 mod->sse_v += stats->sse_v;
1326 if(mod->min_sse_y > stats->sse_y) {
1327 mod->min_sse_y = stats->sse_y;
1328 mod->min_sse_u = stats->sse_u;
1329 mod->min_sse_v = stats->sse_v;
1330 mod->min_framenum = mod->frames;
1333 if(mod->max_sse_y < stats->sse_y) {
1334 mod->max_sse_y = stats->sse_y;
1335 mod->max_sse_u = stats->sse_u;
1336 mod->max_sse_v = stats->sse_v;
1337 mod->max_framenum = mod->frames;
1340 if (xvidenc_psnr) {
1341 if (!mod->fvstats) {
1342 char filename[20];
1343 time_t today2;
1344 struct tm *today;
1345 today2 = time (NULL);
1346 today = localtime (&today2);
1347 sprintf (filename, "psnr_%02d%02d%02d.log", today->tm_hour, today->tm_min, today->tm_sec);
1348 mod->fvstats = fopen (filename,"w");
1349 if (!mod->fvstats) {
1350 perror ("fopen");
1351 /* Disable PSNR file output so we don't get here again */
1352 xvidenc_psnr = 0;
1355 fprintf (mod->fvstats, "%6d, %2d, %6d, %2.2f, %2.2f, %2.2f, %2.2f %c\n",
1356 mod->frames,
1357 stats->quant,
1358 stats->length,
1359 SSE2PSNR (stats->sse_y, mod->pixels),
1360 SSE2PSNR (stats->sse_u, mod->pixels / 4),
1361 SSE2PSNR (stats->sse_v, mod->pixels / 4),
1362 SSE2PSNR (stats->sse_y + stats->sse_u + stats->sse_v,(double)mod->pixels * 1.5),
1363 stats->type==1?'I':stats->type==2?'P':stats->type==3?'B':stats->type?'S':'?'
1366 mod->frames++;
1370 static void
1371 print_stats(xvid_mplayer_module_t *mod)
1373 if (mod->frames) {
1374 mod->sse_y /= mod->frames;
1375 mod->sse_u /= mod->frames;
1376 mod->sse_v /= mod->frames;
1378 mp_msg(MSGT_MENCODER, MSGL_INFO,
1379 "The value 99.99dB is a special value and represents "
1380 "the upper range limit\n");
1381 mp_msg(MSGT_MENCODER, MSGL_INFO,
1382 "xvid: Min PSNR Y:%.2f, Cb:%.2f, Cr:%.2f, All:%.2f in frame %d\n",
1383 SSE2PSNR(mod->max_sse_y, mod->pixels),
1384 SSE2PSNR(mod->max_sse_u, mod->pixels/4),
1385 SSE2PSNR(mod->max_sse_v, mod->pixels/4),
1386 SSE2PSNR(mod->max_sse_y + mod->max_sse_u + mod->max_sse_v, mod->pixels*1.5),
1387 mod->max_framenum);
1388 mp_msg(MSGT_MENCODER, MSGL_INFO,
1389 "xvid: Average PSNR Y:%.2f, Cb:%.2f, Cr:%.2f, All:%.2f for %d frames\n",
1390 SSE2PSNR(mod->sse_y, mod->pixels),
1391 SSE2PSNR(mod->sse_u, mod->pixels/4),
1392 SSE2PSNR(mod->sse_v, mod->pixels/4),
1393 SSE2PSNR(mod->sse_y + mod->sse_u + mod->sse_v, mod->pixels*1.5),
1394 mod->frames);
1395 mp_msg(MSGT_MENCODER, MSGL_INFO,
1396 "xvid: Max PSNR Y:%.2f, Cb:%.2f, Cr:%.2f, All:%.2f in frame %d\n",
1397 SSE2PSNR(mod->min_sse_y, mod->pixels),
1398 SSE2PSNR(mod->min_sse_u, mod->pixels/4),
1399 SSE2PSNR(mod->min_sse_v, mod->pixels/4),
1400 SSE2PSNR(mod->min_sse_y + mod->min_sse_u + mod->min_sse_v, mod->pixels*1.5),
1401 mod->min_framenum);
1404 #undef SSE2PSNR
1406 static void *read_matrix(unsigned char *filename)
1408 int i;
1409 unsigned char *matrix;
1410 FILE *input;
1412 /* Allocate matrix space */
1413 if((matrix = malloc(64*sizeof(unsigned char))) == NULL)
1414 return NULL;
1416 /* Open the matrix file */
1417 if((input = fopen(filename, "rb")) == NULL) {
1418 mp_msg(MSGT_MENCODER, MSGL_ERR,
1419 "xvid: Error opening the matrix file %s\n",
1420 filename);
1421 free(matrix);
1422 return NULL;
1425 /* Read the matrix */
1426 for(i=0; i<64; i++) {
1428 int value;
1430 /* If fscanf fails then get out of the loop */
1431 if(fscanf(input, "%d", &value) != 1) {
1432 mp_msg(MSGT_MENCODER, MSGL_ERR,
1433 "xvid: Error reading the matrix file %s\n",
1434 filename);
1435 free(matrix);
1436 fclose(input);
1437 return NULL;
1440 /* Clamp the value to safe range */
1441 value = (value< 1)?1 :value;
1442 value = (value>255)?255:value;
1443 matrix[i] = value;
1446 /* Fills the rest with 1 */
1447 while(i<64) matrix[i++] = 1;
1449 /* We're done */
1450 fclose(input);
1452 return matrix;
1457 static const char *
1458 par_string(int parcode)
1460 const char *par_string;
1461 switch (parcode) {
1462 case XVID_PAR_11_VGA:
1463 par_string = "vga11";
1464 break;
1465 case XVID_PAR_43_PAL:
1466 par_string = "pal43";
1467 break;
1468 case XVID_PAR_43_NTSC:
1469 par_string = "ntsc43";
1470 break;
1471 case XVID_PAR_169_PAL:
1472 par_string = "pal169";
1473 break;
1474 case XVID_PAR_169_NTSC:
1475 par_string = "ntsc69";
1476 break;
1477 case XVID_PAR_EXT:
1478 par_string = "ext";
1479 break;
1480 default:
1481 par_string = "unknown";
1482 break;
1484 return par_string;
1487 static const char *errorstring(int err)
1489 const char *error;
1490 switch(err) {
1491 case XVID_ERR_FAIL:
1492 error = "General fault";
1493 break;
1494 case XVID_ERR_MEMORY:
1495 error = "Memory allocation error";
1496 break;
1497 case XVID_ERR_FORMAT:
1498 error = "File format error";
1499 break;
1500 case XVID_ERR_VERSION:
1501 error = "Structure version not supported";
1502 break;
1503 case XVID_ERR_END:
1504 error = "End of stream reached";
1505 break;
1506 default:
1507 error = "Unknown";
1510 return error;
1513 /*****************************************************************************
1514 * Module structure definition
1515 ****************************************************************************/
1517 vf_info_t ve_info_xvid = {
1518 "XviD 1.0 encoder",
1519 "xvid",
1520 "Marco Belli <elcabesa@inwind.it>, Edouard Gomez <ed.gomez@free.fr>",
1521 "No comment",
1522 vf_open
1526 /* Please do not change that tag comment.
1527 * arch-tag: 42ccc257-0548-4a3e-9617-2876c4e8ac88 mplayer xvid encoder module */