]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cap_ogg.c
disable use of stdint.h on MSVC2003 and earlier
[xonotic/darkplaces.git] / cap_ogg.c
1 #ifndef _MSC_VER
2 #include <stdint.h>
3 #endif
4 #include <sys/types.h>
5
6 #include "quakedef.h"
7 #include "client.h"
8 #include "cap_ogg.h"
9
10 // video capture cvars
11 static cvar_t cl_capturevideo_ogg_theora_quality = {CVAR_SAVE, "cl_capturevideo_ogg_theora_quality", "32", "video quality factor (0 to 63), or -1 to use bitrate only; higher is better"};
12 static cvar_t cl_capturevideo_ogg_theora_bitrate = {CVAR_SAVE, "cl_capturevideo_ogg_theora_bitrate", "-1", "video bitrate (45 to 2000 kbps), or -1 to use quality only; higher is better"};
13 static cvar_t cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier = {CVAR_SAVE, "cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier", "1.5", "how much more bit rate to use for keyframes, specified as a factor of at least 1"};
14 static cvar_t cl_capturevideo_ogg_theora_keyframe_frequency = {CVAR_SAVE, "cl_capturevideo_ogg_theora_keyframe_frequency", "64", "maximum number of frames between two key frames (1 to 1000)"};
15 static cvar_t cl_capturevideo_ogg_theora_keyframe_mindistance = {CVAR_SAVE, "cl_capturevideo_ogg_theora_keyframe_mindistance", "8", "minimum number of frames between two key frames (1 to 1000)"};
16 static cvar_t cl_capturevideo_ogg_theora_keyframe_auto_threshold = {CVAR_SAVE, "cl_capturevideo_ogg_theora_keyframe_auto_threshold", "80", "threshold for key frame decision (0 to 100)"};
17 static cvar_t cl_capturevideo_ogg_theora_noise_sensitivity = {CVAR_SAVE, "cl_capturevideo_ogg_theora_noise_sensitivity", "1", "video noise sensitivity (0 to 6); lower is better"};
18 static cvar_t cl_capturevideo_ogg_theora_sharpness = {CVAR_SAVE, "cl_capturevideo_ogg_theora_sharpness", "0", "sharpness (0 to 2); lower is sharper"};
19 static cvar_t cl_capturevideo_ogg_vorbis_quality = {CVAR_SAVE, "cl_capturevideo_ogg_vorbis_quality", "1", "audio quality (-1 to 10); higher is better"};
20
21 // ogg.h stuff
22 #ifdef _MSC_VER
23 typedef __int16 ogg_int16_t;
24 typedef unsigned __int16 ogg_uint16_t;
25 typedef __int32 ogg_int32_t;
26 typedef unsigned __int32 ogg_uint32_t;
27 typedef __int64 ogg_int64_t;
28 #else
29 typedef int16_t ogg_int16_t;
30 typedef uint16_t ogg_uint16_t;
31 typedef int32_t ogg_int32_t;
32 typedef uint32_t ogg_uint32_t;
33 typedef int64_t ogg_int64_t;
34 #endif
35
36 typedef struct {
37   long endbyte;
38   int  endbit;
39
40   unsigned char *buffer;
41   unsigned char *ptr;
42   long storage;
43 } oggpack_buffer;
44
45 /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
46
47 typedef struct {
48   unsigned char *header;
49   long header_len;
50   unsigned char *body;
51   long body_len;
52 } ogg_page;
53
54 /* ogg_stream_state contains the current encode/decode state of a logical
55    Ogg bitstream **********************************************************/
56
57 typedef struct {
58   unsigned char   *body_data;    /* bytes from packet bodies */
59   long    body_storage;          /* storage elements allocated */
60   long    body_fill;             /* elements stored; fill mark */
61   long    body_returned;         /* elements of fill returned */
62
63
64   int     *lacing_vals;      /* The values that will go to the segment table */
65   ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
66                                 this way, but it is simple coupled to the
67                                 lacing fifo */
68   long    lacing_storage;
69   long    lacing_fill;
70   long    lacing_packet;
71   long    lacing_returned;
72
73   unsigned char    header[282];      /* working space for header encode */
74   int              header_fill;
75
76   int     e_o_s;          /* set when we have buffered the last packet in the
77                              logical bitstream */
78   int     b_o_s;          /* set after we've written the initial page
79                              of a logical bitstream */
80   long    serialno;
81   long    pageno;
82   ogg_int64_t  packetno;      /* sequence number for decode; the framing
83                              knows where there's a hole in the data,
84                              but we need coupling so that the codec
85                              (which is in a seperate abstraction
86                              layer) also knows about the gap */
87   ogg_int64_t   granulepos;
88
89 } ogg_stream_state;
90
91 /* ogg_packet is used to encapsulate the data and metadata belonging
92    to a single raw Ogg/Vorbis packet *************************************/
93
94 typedef struct {
95   unsigned char *packet;
96   long  bytes;
97   long  b_o_s;
98   long  e_o_s;
99
100   ogg_int64_t  granulepos;
101   
102   ogg_int64_t  packetno;     /* sequence number for decode; the framing
103                                 knows where there's a hole in the data,
104                                 but we need coupling so that the codec
105                                 (which is in a seperate abstraction
106                                 layer) also knows about the gap */
107 } ogg_packet;
108
109 typedef struct {
110   unsigned char *data;
111   int storage;
112   int fill;
113   int returned;
114
115   int unsynced;
116   int headerbytes;
117   int bodybytes;
118 } ogg_sync_state;
119
120 /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
121
122 static int      (*qogg_stream_packetin) (ogg_stream_state *os, ogg_packet *op);
123 static int      (*qogg_stream_pageout) (ogg_stream_state *os, ogg_page *og);
124 static int      (*qogg_stream_flush) (ogg_stream_state *os, ogg_page *og);
125
126 /* Ogg BITSTREAM PRIMITIVES: general ***************************/
127
128 static int      (*qogg_stream_init) (ogg_stream_state *os,int serialno);
129 static int      (*qogg_stream_clear) (ogg_stream_state *os);
130 static ogg_int64_t  (*qogg_page_granulepos) (ogg_page *og);
131
132 // end of ogg.h stuff
133
134 // vorbis/codec.h stuff
135 typedef struct vorbis_info{
136   int version;
137   int channels;
138   long rate;
139
140   /* The below bitrate declarations are *hints*.
141      Combinations of the three values carry the following implications:
142
143      all three set to the same value:
144        implies a fixed rate bitstream
145      only nominal set:
146        implies a VBR stream that averages the nominal bitrate.  No hard
147        upper/lower limit
148      upper and or lower set:
149        implies a VBR bitstream that obeys the bitrate limits. nominal
150        may also be set to give a nominal rate.
151      none set:
152        the coder does not care to speculate.
153   */
154
155   long bitrate_upper;
156   long bitrate_nominal;
157   long bitrate_lower;
158   long bitrate_window;
159
160   void *codec_setup;
161 } vorbis_info;
162
163 /* vorbis_dsp_state buffers the current vorbis audio
164    analysis/synthesis state.  The DSP state belongs to a specific
165    logical bitstream ****************************************************/
166 typedef struct vorbis_dsp_state{
167   int analysisp;
168   vorbis_info *vi;
169
170   float **pcm;
171   float **pcmret;
172   int      pcm_storage;
173   int      pcm_current;
174   int      pcm_returned;
175
176   int  preextrapolate;
177   int  eofflag;
178
179   long lW;
180   long W;
181   long nW;
182   long centerW;
183
184   ogg_int64_t granulepos;
185   ogg_int64_t sequence;
186
187   ogg_int64_t glue_bits;
188   ogg_int64_t time_bits;
189   ogg_int64_t floor_bits;
190   ogg_int64_t res_bits;
191
192   void       *backend_state;
193 } vorbis_dsp_state;
194
195 typedef struct vorbis_block{
196   /* necessary stream state for linking to the framing abstraction */
197   float  **pcm;       /* this is a pointer into local storage */
198   oggpack_buffer opb;
199
200   long  lW;
201   long  W;
202   long  nW;
203   int   pcmend;
204   int   mode;
205
206   int         eofflag;
207   ogg_int64_t granulepos;
208   ogg_int64_t sequence;
209   vorbis_dsp_state *vd; /* For read-only access of configuration */
210
211   /* local storage to avoid remallocing; it's up to the mapping to
212      structure it */
213   void               *localstore;
214   long                localtop;
215   long                localalloc;
216   long                totaluse;
217   struct alloc_chain *reap;
218
219   /* bitmetrics for the frame */
220   long glue_bits;
221   long time_bits;
222   long floor_bits;
223   long res_bits;
224
225   void *internal;
226
227 } vorbis_block;
228
229 /* vorbis_block is a single block of data to be processed as part of
230 the analysis/synthesis stream; it belongs to a specific logical
231 bitstream, but is independant from other vorbis_blocks belonging to
232 that logical bitstream. *************************************************/
233
234 struct alloc_chain{
235   void *ptr;
236   struct alloc_chain *next;
237 };
238
239 /* vorbis_info contains all the setup information specific to the
240    specific compression/decompression mode in progress (eg,
241    psychoacoustic settings, channel setup, options, codebook
242    etc). vorbis_info and substructures are in backends.h.
243 *********************************************************************/
244
245 /* the comments are not part of vorbis_info so that vorbis_info can be
246    static storage */
247 typedef struct vorbis_comment{
248   /* unlimited user comment fields.  libvorbis writes 'libvorbis'
249      whatever vendor is set to in encode */
250   char **user_comments;
251   int   *comment_lengths;
252   int    comments;
253   char  *vendor;
254
255 } vorbis_comment;
256
257
258 /* libvorbis encodes in two abstraction layers; first we perform DSP
259    and produce a packet (see docs/analysis.txt).  The packet is then
260    coded into a framed OggSquish bitstream by the second layer (see
261    docs/framing.txt).  Decode is the reverse process; we sync/frame
262    the bitstream and extract individual packets, then decode the
263    packet back into PCM audio.
264
265    The extra framing/packetizing is used in streaming formats, such as
266    files.  Over the net (such as with UDP), the framing and
267    packetization aren't necessary as they're provided by the transport
268    and the streaming layer is not used */
269
270 /* Vorbis PRIMITIVES: general ***************************************/
271
272 static void     (*qvorbis_info_init) (vorbis_info *vi);
273 static void     (*qvorbis_info_clear) (vorbis_info *vi);
274 static void     (*qvorbis_comment_init) (vorbis_comment *vc);
275 static void     (*qvorbis_comment_clear) (vorbis_comment *vc);
276
277 static int      (*qvorbis_block_init) (vorbis_dsp_state *v, vorbis_block *vb);
278 static int      (*qvorbis_block_clear) (vorbis_block *vb);
279 static void     (*qvorbis_dsp_clear) (vorbis_dsp_state *v);
280 static double   (*qvorbis_granule_time) (vorbis_dsp_state *v,
281                                     ogg_int64_t granulepos);
282
283 /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
284
285 static int      (*qvorbis_analysis_init) (vorbis_dsp_state *v,vorbis_info *vi);
286 static int      (*qvorbis_commentheader_out) (vorbis_comment *vc, ogg_packet *op);
287 static int      (*qvorbis_analysis_headerout) (vorbis_dsp_state *v,
288                                           vorbis_comment *vc,
289                                           ogg_packet *op,
290                                           ogg_packet *op_comm,
291                                           ogg_packet *op_code);
292 static float ** (*qvorbis_analysis_buffer) (vorbis_dsp_state *v,int vals);
293 static int      (*qvorbis_analysis_wrote) (vorbis_dsp_state *v,int vals);
294 static int      (*qvorbis_analysis_blockout) (vorbis_dsp_state *v,vorbis_block *vb);
295 static int      (*qvorbis_analysis) (vorbis_block *vb,ogg_packet *op);
296
297 static int      (*qvorbis_bitrate_addblock) (vorbis_block *vb);
298 static int      (*qvorbis_bitrate_flushpacket) (vorbis_dsp_state *vd,
299                                            ogg_packet *op);
300
301 // end of vorbis/codec.h stuff
302
303 // vorbisenc.h stuff
304 static int (*qvorbis_encode_init_vbr) (vorbis_info *vi,
305                                   long channels,
306                                   long rate,
307
308                                   float base_quality /* quality level from 0. (lo) to 1. (hi) */
309                                   );
310 // end of vorbisenc.h stuff
311
312 // theora.h stuff
313 typedef struct {
314     int   y_width;      /**< Width of the Y' luminance plane */
315     int   y_height;     /**< Height of the luminance plane */
316     int   y_stride;     /**< Offset in bytes between successive rows */
317
318     int   uv_width;     /**< Width of the Cb and Cr chroma planes */
319     int   uv_height;    /**< Height of the chroma planes */
320     int   uv_stride;    /**< Offset between successive chroma rows */
321     unsigned char *y;   /**< Pointer to start of luminance data */
322     unsigned char *u;   /**< Pointer to start of Cb data */
323     unsigned char *v;   /**< Pointer to start of Cr data */
324
325 } yuv_buffer;
326
327 /**
328  * A Colorspace.
329  */
330 typedef enum {
331   OC_CS_UNSPECIFIED,    /**< The colorspace is unknown or unspecified */
332   OC_CS_ITU_REC_470M,   /**< This is the best option for 'NTSC' content */
333   OC_CS_ITU_REC_470BG,  /**< This is the best option for 'PAL' content */
334   OC_CS_NSPACES         /**< This marks the end of the defined colorspaces */
335 } theora_colorspace;
336
337 /**
338  * A Chroma subsampling
339  *
340  * These enumerate the available chroma subsampling options supported
341  * by the theora format. See Section 4.4 of the specification for
342  * exact definitions.
343  */
344 typedef enum {
345   OC_PF_420,    /**< Chroma subsampling by 2 in each direction (4:2:0) */
346   OC_PF_RSVD,   /**< Reserved value */
347   OC_PF_422,    /**< Horizonatal chroma subsampling by 2 (4:2:2) */
348   OC_PF_444,    /**< No chroma subsampling at all (4:4:4) */
349 } theora_pixelformat;
350 /**
351  * Theora bitstream info.
352  * Contains the basic playback parameters for a stream,
353  * corresponding to the initial 'info' header packet.
354  * 
355  * Encoded theora frames must be a multiple of 16 in width and height.
356  * To handle other frame sizes, a crop rectangle is specified in
357  * frame_height and frame_width, offset_x and * offset_y. The offset
358  * and size should still be a multiple of 2 to avoid chroma sampling
359  * shifts. Offset values in this structure are measured from the
360  * upper left of the image.
361  *
362  * Frame rate, in frames per second, is stored as a rational
363  * fraction. Aspect ratio is also stored as a rational fraction, and
364  * refers to the aspect ratio of the frame pixels, not of the
365  * overall frame itself.
366  * 
367  * See <a href="http://svn.xiph.org/trunk/theora/examples/encoder_example.c">
368  * examples/encoder_example.c</a> for usage examples of the
369  * other paramters and good default settings for the encoder parameters.
370  */
371 typedef struct {
372   ogg_uint32_t  width;      /**< encoded frame width  */
373   ogg_uint32_t  height;     /**< encoded frame height */
374   ogg_uint32_t  frame_width;    /**< display frame width  */
375   ogg_uint32_t  frame_height;   /**< display frame height */
376   ogg_uint32_t  offset_x;   /**< horizontal offset of the displayed frame */
377   ogg_uint32_t  offset_y;   /**< vertical offset of the displayed frame */
378   ogg_uint32_t  fps_numerator;      /**< frame rate numerator **/
379   ogg_uint32_t  fps_denominator;    /**< frame rate denominator **/
380   ogg_uint32_t  aspect_numerator;   /**< pixel aspect ratio numerator */
381   ogg_uint32_t  aspect_denominator; /**< pixel aspect ratio denominator */
382   theora_colorspace colorspace;     /**< colorspace */
383   int           target_bitrate;     /**< nominal bitrate in bits per second */
384   int           quality;  /**< Nominal quality setting, 0-63 */
385   int           quick_p;  /**< Quick encode/decode */
386
387   /* decode only */
388   unsigned char version_major;
389   unsigned char version_minor;
390   unsigned char version_subminor;
391
392   void *codec_setup;
393
394   /* encode only */
395   int           dropframes_p;
396   int           keyframe_auto_p;
397   ogg_uint32_t  keyframe_frequency;
398   ogg_uint32_t  keyframe_frequency_force;  /* also used for decode init to
399                                               get granpos shift correct */
400   ogg_uint32_t  keyframe_data_target_bitrate;
401   ogg_int32_t   keyframe_auto_threshold;
402   ogg_uint32_t  keyframe_mindistance;
403   ogg_int32_t   noise_sensitivity;
404   ogg_int32_t   sharpness;
405
406   theora_pixelformat pixelformat;   /**< chroma subsampling mode to expect */
407
408 } theora_info;
409
410 /** Codec internal state and context.
411  */
412 typedef struct{
413   theora_info *i;
414   ogg_int64_t granulepos;
415
416   void *internal_encode;
417   void *internal_decode;
418
419 } theora_state;
420
421 /** 
422  * Comment header metadata.
423  *
424  * This structure holds the in-stream metadata corresponding to
425  * the 'comment' header packet.
426  *
427  * Meta data is stored as a series of (tag, value) pairs, in
428  * length-encoded string vectors. The first occurence of the 
429  * '=' character delimits the tag and value. A particular tag
430  * may occur more than once. The character set encoding for
431  * the strings is always UTF-8, but the tag names are limited
432  * to case-insensitive ASCII. See the spec for details.
433  *
434  * In filling in this structure, qtheora_decode_header() will
435  * null-terminate the user_comment strings for safety. However,
436  * the bitstream format itself treats them as 8-bit clean,
437  * and so the length array should be treated as authoritative
438  * for their length.
439  */
440 typedef struct theora_comment{
441   char **user_comments;         /**< An array of comment string vectors */
442   int   *comment_lengths;       /**< An array of corresponding string vector lengths in bytes */
443   int    comments;              /**< The total number of comment string vectors */
444   char  *vendor;                /**< The vendor string identifying the encoder, null terminated */
445
446 } theora_comment;
447 static int (*qtheora_encode_init) (theora_state *th, theora_info *ti);
448 static int (*qtheora_encode_YUVin) (theora_state *t, yuv_buffer *yuv);
449 static int (*qtheora_encode_packetout) ( theora_state *t, int last_p,
450                                     ogg_packet *op);
451 static int (*qtheora_encode_header) (theora_state *t, ogg_packet *op);
452 static int (*qtheora_encode_comment) (theora_comment *tc, ogg_packet *op);
453 static int (*qtheora_encode_tables) (theora_state *t, ogg_packet *op);
454 static void (*qtheora_info_init) (theora_info *c);
455 static void (*qtheora_info_clear) (theora_info *c);
456 static void (*qtheora_clear) (theora_state *t);
457 static void (*qtheora_comment_init) (theora_comment *tc);
458 static void  (*qtheora_comment_clear) (theora_comment *tc);
459 static double (*qtheora_granule_time) (theora_state *th,ogg_int64_t granulepos);
460 // end of theora.h stuff
461
462 static dllfunction_t oggfuncs[] =
463 {
464         {"ogg_stream_packetin", (void **) &qogg_stream_packetin},
465         {"ogg_stream_pageout", (void **) &qogg_stream_pageout},
466         {"ogg_stream_flush", (void **) &qogg_stream_flush},
467         {"ogg_stream_init", (void **) &qogg_stream_init},
468         {"ogg_stream_clear", (void **) &qogg_stream_clear},
469         {"ogg_page_granulepos", (void **) &qogg_page_granulepos},
470         {NULL, NULL}
471 };
472
473 static dllfunction_t vorbisencfuncs[] =
474 {
475         {"vorbis_encode_init_vbr", (void **) &qvorbis_encode_init_vbr},
476         {NULL, NULL}
477 };
478
479 static dllfunction_t vorbisfuncs[] =
480 {
481         {"vorbis_info_init", (void **) &qvorbis_info_init},
482         {"vorbis_info_clear", (void **) &qvorbis_info_clear},
483         {"vorbis_comment_init", (void **) &qvorbis_comment_init},
484         {"vorbis_comment_clear", (void **) &qvorbis_comment_clear},
485         {"vorbis_block_init", (void **) &qvorbis_block_init},
486         {"vorbis_block_clear", (void **) &qvorbis_block_clear},
487         {"vorbis_dsp_clear", (void **) &qvorbis_dsp_clear},
488         {"vorbis_analysis_init", (void **) &qvorbis_analysis_init},
489         {"vorbis_commentheader_out", (void **) &qvorbis_commentheader_out},
490         {"vorbis_analysis_headerout", (void **) &qvorbis_analysis_headerout},
491         {"vorbis_analysis_buffer", (void **) &qvorbis_analysis_buffer},
492         {"vorbis_analysis_wrote", (void **) &qvorbis_analysis_wrote},
493         {"vorbis_analysis_blockout", (void **) &qvorbis_analysis_blockout},
494         {"vorbis_analysis", (void **) &qvorbis_analysis},
495         {"vorbis_bitrate_addblock", (void **) &qvorbis_bitrate_addblock},
496         {"vorbis_bitrate_flushpacket", (void **) &qvorbis_bitrate_flushpacket},
497         {"vorbis_granule_time", (void **) &qvorbis_granule_time},
498         {NULL, NULL}
499 };
500
501 static dllfunction_t theorafuncs[] =
502 {
503         {"theora_info_init", (void **) &qtheora_info_init},
504         {"theora_info_clear", (void **) &qtheora_info_clear},
505         {"theora_comment_init", (void **) &qtheora_comment_init},
506         {"theora_comment_clear", (void **) &qtheora_comment_clear},
507         {"theora_encode_init", (void **) &qtheora_encode_init},
508         {"theora_encode_YUVin", (void **) &qtheora_encode_YUVin},
509         {"theora_encode_packetout", (void **) &qtheora_encode_packetout},
510         {"theora_encode_header", (void **) &qtheora_encode_header},
511         {"theora_encode_comment", (void **) &qtheora_encode_comment},
512         {"theora_encode_tables", (void **) &qtheora_encode_tables},
513         {"theora_clear", (void **) &qtheora_clear},
514         {"theora_granule_time", (void **) &qtheora_granule_time},
515         {NULL, NULL}
516 };
517
518 static dllhandle_t og_dll = NULL, vo_dll = NULL, ve_dll = NULL, th_dll = NULL;
519
520 qboolean SCR_CaptureVideo_Ogg_OpenLibrary()
521 {
522         const char* dllnames_og [] =
523         {
524 #if defined(WIN64)
525                 "libogg64.dll",
526 #elif defined(WIN32)
527                 "libogg.dll",
528                 "ogg.dll",
529 #elif defined(MACOSX)
530                 "libogg.dylib",
531 #else
532                 "libogg.so.0",
533                 "libogg.so",
534 #endif
535                 NULL
536         };
537         const char* dllnames_vo [] =
538         {
539 #if defined(WIN64)
540                 "libvorbis64.dll",
541 #elif defined(WIN32)
542                 "libvorbis.dll",
543                 "vorbis.dll",
544 #elif defined(MACOSX)
545                 "libvorbis.dylib",
546 #else
547                 "libvorbis.so.0",
548                 "libvorbis.so",
549 #endif
550                 NULL
551         };
552         const char* dllnames_ve [] =
553         {
554 #if defined(WIN64)
555                 "libvorbisenc64.dll",
556 #elif defined(WIN32)
557                 "libvorbisenc.dll",
558                 "vorbisenc.dll",
559 #elif defined(MACOSX)
560                 "libvorbisenc.dylib",
561 #else
562                 "libvorbisenc.so.2",
563                 "libvorbisenc.so",
564 #endif
565                 NULL
566         };
567         const char* dllnames_th [] =
568         {
569 #if defined(WIN64)
570                 "libtheora64.dll",
571 #elif defined(WIN32)
572                 "libtheora.dll",
573                 "theora.dll",
574 #elif defined(MACOSX)
575                 "libtheora.dylib",
576 #else
577                 "libtheora.so.0",
578                 "libtheora.so",
579 #endif
580                 NULL
581         };
582
583         return
584                 Sys_LoadLibrary (dllnames_og, &og_dll, oggfuncs)
585                 &&
586                 Sys_LoadLibrary (dllnames_th, &th_dll, theorafuncs)
587                 &&
588                 Sys_LoadLibrary (dllnames_vo, &vo_dll, vorbisfuncs)
589                 &&
590                 Sys_LoadLibrary (dllnames_ve, &ve_dll, vorbisencfuncs);
591 }
592
593 void SCR_CaptureVideo_Ogg_Init()
594 {
595         SCR_CaptureVideo_Ogg_OpenLibrary();
596
597         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_quality);
598         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_bitrate);
599         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier);
600         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_keyframe_frequency);
601         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_keyframe_mindistance);
602         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_keyframe_auto_threshold);
603         Cvar_RegisterVariable(&cl_capturevideo_ogg_theora_noise_sensitivity);
604         Cvar_RegisterVariable(&cl_capturevideo_ogg_vorbis_quality);
605 }
606
607 qboolean SCR_CaptureVideo_Ogg_Available()
608 {
609         return og_dll && th_dll && vo_dll && ve_dll;
610 }
611
612 void SCR_CaptureVideo_Ogg_CloseDLL()
613 {
614         Sys_UnloadLibrary (&ve_dll);
615         Sys_UnloadLibrary (&vo_dll);
616         Sys_UnloadLibrary (&th_dll);
617         Sys_UnloadLibrary (&og_dll);
618 }
619
620 typedef struct capturevideostate_ogg_formatspecific_s
621 {
622         ogg_stream_state to, vo;
623         int serial1, serial2;
624         theora_state ts;
625         vorbis_dsp_state vd;
626         vorbis_block vb;
627         vorbis_info vi;
628         yuv_buffer yuv;
629         int channels;
630
631         // for interleaving
632         ogg_page videopage;
633         ogg_page audiopage;
634         qboolean have_videopage;
635         qboolean have_audiopage;
636 }
637 capturevideostate_ogg_formatspecific_t;
638 #define LOAD_FORMATSPECIFIC_OGG() capturevideostate_ogg_formatspecific_t *format = (capturevideostate_ogg_formatspecific_t *) cls.capturevideo.formatspecific
639
640 static void SCR_CaptureVideo_Ogg_Interleave()
641 {
642         LOAD_FORMATSPECIFIC_OGG();
643
644         //fprintf(stderr, "<");
645
646         if(!cls.capturevideo.soundrate)
647         {
648                 for(;;)
649                 {
650                         // first: make sure we have a page of both types
651                         if(!format->have_videopage)
652                                 if(qogg_stream_pageout(&format->to, &format->videopage) > 0)
653                                         format->have_videopage = true;
654                         if(format->have_videopage)
655                         {
656                                 FS_Write(cls.capturevideo.videofile, format->videopage.header, format->videopage.header_len);
657                                 FS_Write(cls.capturevideo.videofile, format->videopage.body, format->videopage.body_len);
658                                 format->have_videopage = false;
659                         }
660                 }
661                 return;
662         }
663
664         for(;;)
665         {
666                 // first: make sure we have a page of both types
667                 if(!format->have_videopage)
668                         if(qogg_stream_pageout(&format->to, &format->videopage) > 0)
669                         {
670                                 //fprintf(stderr, "V");
671                                 format->have_videopage = true;
672
673                                 // why do I have to do this? the code should work without the
674                                 // following three lines, which turn this attempt at correct
675                                 // interleaving back into the old stupid one that oggz-validate
676                                 // hates
677                                 FS_Write(cls.capturevideo.videofile, format->videopage.header, format->videopage.header_len);
678                                 FS_Write(cls.capturevideo.videofile, format->videopage.body, format->videopage.body_len);
679                                 format->have_videopage = false;
680                         }
681                 if(!format->have_audiopage)
682                         if(qogg_stream_pageout(&format->vo, &format->audiopage) > 0)
683                         {
684                                 //fprintf(stderr, "A");
685                                 format->have_audiopage = true;
686
687                                 // why do I have to do this? the code should work without the
688                                 // following three lines, which turn this attempt at correct
689                                 // interleaving back into the old stupid one that oggz-validate
690                                 // hates
691                                 FS_Write(cls.capturevideo.videofile, format->audiopage.header, format->audiopage.header_len);
692                                 FS_Write(cls.capturevideo.videofile, format->audiopage.body, format->audiopage.body_len);
693                                 format->have_audiopage = false;
694                         }
695
696                 if(format->have_videopage && format->have_audiopage)
697                 {
698                         // output the page that ends first
699                         double audiotime = qvorbis_granule_time(&format->vd, qogg_page_granulepos(&format->audiopage));
700                         double videotime = qtheora_granule_time(&format->ts, qogg_page_granulepos(&format->videopage));
701                         if(audiotime < videotime)
702                         {
703                                 FS_Write(cls.capturevideo.videofile, format->audiopage.header, format->audiopage.header_len);
704                                 FS_Write(cls.capturevideo.videofile, format->audiopage.body, format->audiopage.body_len);
705                                 format->have_audiopage = false;
706
707                                 //fprintf(stderr, "a");
708                         }
709                         else
710                         {
711                                 FS_Write(cls.capturevideo.videofile, format->videopage.header, format->videopage.header_len);
712                                 FS_Write(cls.capturevideo.videofile, format->videopage.body, format->videopage.body_len);
713                                 format->have_videopage = false;
714
715                                 //fprintf(stderr, "v");
716                         }
717                 }
718                 else
719                         break;
720         }
721
722         //fprintf(stderr, ">");
723 }
724
725 static void SCR_CaptureVideo_Ogg_FlushInterleaving()
726 {
727         LOAD_FORMATSPECIFIC_OGG();
728
729         if(cls.capturevideo.soundrate)
730         if(format->have_audiopage)
731         {
732                 FS_Write(cls.capturevideo.videofile, format->audiopage.header, format->audiopage.header_len);
733                 FS_Write(cls.capturevideo.videofile, format->audiopage.body, format->audiopage.body_len);
734                 format->have_audiopage = false;
735         }
736
737         if(format->have_videopage)
738         {
739                 FS_Write(cls.capturevideo.videofile, format->videopage.header, format->videopage.header_len);
740                 FS_Write(cls.capturevideo.videofile, format->videopage.body, format->videopage.body_len);
741                 format->have_videopage = false;
742         }
743 }
744
745 static void SCR_CaptureVideo_Ogg_EndVideo()
746 {
747         LOAD_FORMATSPECIFIC_OGG();
748         ogg_page pg;
749         ogg_packet pt;
750
751         // repeat the last frame so we can set the end-of-stream flag
752         qtheora_encode_YUVin(&format->ts, &format->yuv);
753         qtheora_encode_packetout(&format->ts, true, &pt);
754         qogg_stream_packetin(&format->to, &pt);
755         SCR_CaptureVideo_Ogg_Interleave();
756
757         if(cls.capturevideo.soundrate)
758         {
759                 qvorbis_analysis_wrote(&format->vd, 0);
760                 while(qvorbis_analysis_blockout(&format->vd, &format->vb) == 1)
761                 {
762                         qvorbis_analysis(&format->vb, NULL);
763                         qvorbis_bitrate_addblock(&format->vb);
764                         while(qvorbis_bitrate_flushpacket(&format->vd, &pt))
765                                 qogg_stream_packetin(&format->vo, &pt);
766                         SCR_CaptureVideo_Ogg_Interleave();
767                 }
768         }
769
770         SCR_CaptureVideo_Ogg_FlushInterleaving();
771
772         while(qogg_stream_pageout(&format->to, &pg) > 0)
773         {
774                 FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
775                 FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
776         }
777
778         if(cls.capturevideo.soundrate)
779         {
780                 while(qogg_stream_pageout(&format->vo, &pg) > 0)
781                 {
782                         FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
783                         FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
784                 }
785         }
786                 
787         while (1) {
788                 int result = qogg_stream_flush (&format->to, &pg);
789                 if (result < 0)
790                         fprintf (stderr, "Internal Ogg library error.\n"); // TODO Host_Error
791                 if (result <= 0)
792                         break;
793                 FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
794                 FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
795         }
796
797         if(cls.capturevideo.soundrate)
798         {
799                 while (1) {
800                         int result = qogg_stream_flush (&format->vo, &pg);
801                         if (result < 0)
802                                 fprintf (stderr, "Internal Ogg library error.\n"); // TODO Host_Error
803                         if (result <= 0)
804                                 break;
805                         FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
806                         FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
807                 }
808
809                 qogg_stream_clear(&format->vo);
810                 qvorbis_block_clear(&format->vb);
811                 qvorbis_dsp_clear(&format->vd);
812         }
813
814         qogg_stream_clear(&format->to);
815         qtheora_clear(&format->ts);
816         qvorbis_info_clear(&format->vi);
817
818         Mem_Free(format->yuv.y);
819         Mem_Free(format->yuv.u);
820         Mem_Free(format->yuv.v);
821         Mem_Free(format);
822
823         FS_Close(cls.capturevideo.videofile);
824         cls.capturevideo.videofile = NULL;
825 }
826
827 static void SCR_CaptureVideo_Ogg_ConvertFrame_BGRA_to_YUV()
828 {
829         LOAD_FORMATSPECIFIC_OGG();
830         int x, y;
831         int blockr, blockg, blockb;
832         unsigned char *b = cls.capturevideo.outbuffer;
833         int w = cls.capturevideo.width;
834         int h = cls.capturevideo.height;
835         int inpitch = w*4;
836
837         for(y = 0; y < h; ++y)
838         {
839                 for(b = cls.capturevideo.outbuffer + (h-1-y)*w*4, x = 0; x < w; ++x)
840                 {
841                         blockr = b[2];
842                         blockg = b[1];
843                         blockb = b[0];
844                         format->yuv.y[x + format->yuv.y_stride * y] =
845                                 cls.capturevideo.yuvnormalizetable[0][cls.capturevideo.rgbtoyuvscaletable[0][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[0][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[0][2][blockb]];
846                         b += 4;
847                 }
848
849                 if((y & 1) == 0)
850                 {
851                         for(b = cls.capturevideo.outbuffer + (h-2-y)*w*4, x = 0; x < w/2; ++x)
852                         {
853                                 blockr = (b[2] + b[6] + b[inpitch+2] + b[inpitch+6]) >> 2;
854                                 blockg = (b[1] + b[5] + b[inpitch+1] + b[inpitch+5]) >> 2;
855                                 blockb = (b[0] + b[4] + b[inpitch+0] + b[inpitch+4]) >> 2;
856                                 format->yuv.u[x + format->yuv.uv_stride * (y/2)] =
857                                         cls.capturevideo.yuvnormalizetable[1][cls.capturevideo.rgbtoyuvscaletable[1][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[1][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[1][2][blockb] + 128];
858                                 format->yuv.v[x + format->yuv.uv_stride * (y/2)] =
859                                         cls.capturevideo.yuvnormalizetable[2][cls.capturevideo.rgbtoyuvscaletable[2][0][blockr] + cls.capturevideo.rgbtoyuvscaletable[2][1][blockg] + cls.capturevideo.rgbtoyuvscaletable[2][2][blockb] + 128];
860                                 b += 8;
861                         }
862                 }
863         }
864 }
865
866 static void SCR_CaptureVideo_Ogg_VideoFrames(int num)
867 {
868         LOAD_FORMATSPECIFIC_OGG();
869         ogg_packet pt;
870
871         // data is in cls.capturevideo.outbuffer as BGRA and has size width*height
872
873         SCR_CaptureVideo_Ogg_ConvertFrame_BGRA_to_YUV();
874
875         while(num-- > 0)
876         {
877                 qtheora_encode_YUVin(&format->ts, &format->yuv);
878
879                 while(qtheora_encode_packetout(&format->ts, false, &pt))
880                         qogg_stream_packetin(&format->to, &pt);
881
882                 SCR_CaptureVideo_Ogg_Interleave();
883         }
884 }
885
886 static void SCR_CaptureVideo_Ogg_SoundFrame(const portable_sampleframe_t *paintbuffer, size_t length)
887 {
888         LOAD_FORMATSPECIFIC_OGG();
889         float **vorbis_buffer;
890         size_t i;
891         int j;
892         ogg_packet pt;
893
894         vorbis_buffer = qvorbis_analysis_buffer(&format->vd, length);
895         for(i = 0; i < length; ++i)
896         {
897                 for(j = 0; j < cls.capturevideo.soundchannels; ++j)
898                         vorbis_buffer[j][i] = paintbuffer[i].sample[j] / 32768.0f;
899         }
900         qvorbis_analysis_wrote(&format->vd, length);
901
902         while(qvorbis_analysis_blockout(&format->vd, &format->vb) == 1)
903         {
904                 qvorbis_analysis(&format->vb, NULL);
905                 qvorbis_bitrate_addblock(&format->vb);
906
907                 while(qvorbis_bitrate_flushpacket(&format->vd, &pt))
908                         qogg_stream_packetin(&format->vo, &pt);
909         }
910
911         SCR_CaptureVideo_Ogg_Interleave();
912 }
913
914 void SCR_CaptureVideo_Ogg_BeginVideo()
915 {
916         cls.capturevideo.format = CAPTUREVIDEOFORMAT_OGG_VORBIS_THEORA;
917         cls.capturevideo.videofile = FS_OpenRealFile(va("%s.ogv", cls.capturevideo.basename), "wb", false);
918         cls.capturevideo.endvideo = SCR_CaptureVideo_Ogg_EndVideo;
919         cls.capturevideo.videoframes = SCR_CaptureVideo_Ogg_VideoFrames;
920         cls.capturevideo.soundframe = SCR_CaptureVideo_Ogg_SoundFrame;
921         cls.capturevideo.formatspecific = Mem_Alloc(tempmempool, sizeof(capturevideostate_ogg_formatspecific_t));
922         {
923                 LOAD_FORMATSPECIFIC_OGG();
924                 int num, denom;
925                 ogg_page pg;
926                 ogg_packet pt, pt2, pt3;
927                 theora_comment tc;
928                 vorbis_comment vc;
929                 theora_info ti;
930
931                 format->serial1 = rand();
932                 qogg_stream_init(&format->to, format->serial1);
933
934                 if(cls.capturevideo.soundrate)
935                 {
936                         do
937                         {
938                                 format->serial2 = rand();
939                         }
940                         while(format->serial1 == format->serial2);
941                         qogg_stream_init(&format->vo, format->serial2);
942                 }
943
944                 format->have_videopage = format->have_audiopage = false;
945
946                 qtheora_info_init(&ti);
947                 ti.frame_width = cls.capturevideo.width;
948                 ti.frame_height = cls.capturevideo.height;
949                 ti.width = (ti.frame_width + 15) & ~15;
950                 ti.height = (ti.frame_height + 15) & ~15;
951                 //ti.offset_x = ((ti.width - ti.frame_width) / 2) & ~1;
952                 //ti.offset_y = ((ti.height - ti.frame_height) / 2) & ~1;
953
954                 format->yuv.y_width = ti.width;
955                 format->yuv.y_height = ti.height;
956                 format->yuv.y_stride = ti.width;
957
958                 format->yuv.uv_width = ti.width / 2;
959                 format->yuv.uv_height = ti.height / 2;
960                 format->yuv.uv_stride = ti.width / 2;
961
962                 format->yuv.y = Mem_Alloc(tempmempool, format->yuv.y_stride * format->yuv.y_height);
963                 format->yuv.u = Mem_Alloc(tempmempool, format->yuv.uv_stride * format->yuv.uv_height);
964                 format->yuv.v = Mem_Alloc(tempmempool, format->yuv.uv_stride * format->yuv.uv_height);
965
966                 FindFraction(cls.capturevideo.framerate, &num, &denom, 1001);
967                 ti.fps_numerator = num;
968                 ti.fps_denominator = denom;
969
970                 FindFraction(1 / vid_pixelheight.value, &num, &denom, 1000);
971                 ti.aspect_numerator = num;
972                 ti.aspect_denominator = denom;
973
974                 ti.colorspace = OC_CS_UNSPECIFIED;
975                 ti.pixelformat = OC_PF_420;
976
977                 ti.quick_p = true; // http://mlblog.osdir.com/multimedia.ogg.theora.general/2004-07/index.shtml
978                 ti.dropframes_p = false;
979
980                 ti.target_bitrate = cl_capturevideo_ogg_theora_bitrate.integer * 1000;
981                 ti.quality = cl_capturevideo_ogg_theora_quality.integer;
982
983                 if(ti.target_bitrate <= 0)
984                 {
985                         if(ti.quality < 0)
986                         {
987                                 ti.target_bitrate = -1;
988                                 ti.keyframe_data_target_bitrate = -1;
989                                 ti.quality = 63;
990                         }
991                         else
992                         {
993                                 ti.target_bitrate = -1;
994                                 ti.keyframe_data_target_bitrate = -1;
995                                 ti.quality = bound(0, ti.quality, 63);
996                         }
997                 }
998                 else
999                 {
1000                         if(ti.quality < 0)
1001                         {
1002                                 ti.target_bitrate = bound(45000, ti.target_bitrate, 2000000);
1003                                 ti.keyframe_data_target_bitrate = ti.target_bitrate * max(1, cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier.value);
1004                                 ti.quality = -1;
1005                         }
1006                         else
1007                         {
1008                                 ti.target_bitrate = bound(45000, ti.target_bitrate, 2000000);
1009                                 ti.keyframe_data_target_bitrate = ti.target_bitrate * max(1, cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier.value);
1010                                 ti.quality = -1;
1011                         }
1012                 }
1013
1014                 ti.keyframe_frequency = bound(1, cl_capturevideo_ogg_theora_keyframe_frequency.integer, 1000);
1015                 ti.keyframe_mindistance = bound(1, cl_capturevideo_ogg_theora_keyframe_mindistance.integer, (int) ti.keyframe_frequency);
1016                 ti.noise_sensitivity = bound(0, cl_capturevideo_ogg_theora_noise_sensitivity.integer, 6);
1017                 ti.sharpness = bound(0, cl_capturevideo_ogg_theora_sharpness.integer, 2);
1018                 ti.keyframe_auto_threshold = bound(0, cl_capturevideo_ogg_theora_keyframe_auto_threshold.integer, 100);
1019
1020                 ti.keyframe_frequency_force = ti.keyframe_frequency;
1021                 ti.keyframe_auto_p = (ti.keyframe_frequency != ti.keyframe_mindistance);
1022
1023                 qtheora_encode_init(&format->ts, &ti);
1024                 qtheora_info_clear(&ti);
1025
1026                 // vorbis?
1027                 if(cls.capturevideo.soundrate)
1028                 {
1029                         qvorbis_info_init(&format->vi);
1030                         qvorbis_encode_init_vbr(&format->vi, cls.capturevideo.soundchannels, cls.capturevideo.soundrate, bound(-1, cl_capturevideo_ogg_vorbis_quality.value, 10) * 0.099);
1031                         qvorbis_comment_init(&vc);
1032                         qvorbis_analysis_init(&format->vd, &format->vi);
1033                         qvorbis_block_init(&format->vd, &format->vb);
1034                 }
1035
1036                 qtheora_comment_init(&tc);
1037
1038                 /* create the remaining theora headers */
1039                 qtheora_encode_header(&format->ts, &pt);
1040                 qogg_stream_packetin(&format->to, &pt);
1041                 if (qogg_stream_pageout (&format->to, &pg) != 1)
1042                         fprintf (stderr, "Internal Ogg library error.\n");
1043                 FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
1044                 FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
1045
1046                 qtheora_encode_comment(&tc, &pt);
1047                 qogg_stream_packetin(&format->to, &pt);
1048                 qtheora_encode_tables(&format->ts, &pt);
1049                 qogg_stream_packetin (&format->to, &pt);
1050
1051                 qtheora_comment_clear(&tc);
1052
1053                 if(cls.capturevideo.soundrate)
1054                 {
1055                         qvorbis_analysis_headerout(&format->vd, &vc, &pt, &pt2, &pt3);
1056                         qogg_stream_packetin(&format->vo, &pt);
1057                         if (qogg_stream_pageout (&format->vo, &pg) != 1)
1058                                 fprintf (stderr, "Internal Ogg library error.\n");
1059                         FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
1060                         FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
1061
1062                         qogg_stream_packetin(&format->vo, &pt2);
1063                         qogg_stream_packetin(&format->vo, &pt3);
1064
1065                         qvorbis_comment_clear(&vc);
1066                 }
1067
1068                 for(;;)
1069                 {
1070                         int result = qogg_stream_flush (&format->to, &pg);
1071                         if (result < 0)
1072                                 fprintf (stderr, "Internal Ogg library error.\n"); // TODO Host_Error
1073                         if (result <= 0)
1074                                 break;
1075                         FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
1076                         FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
1077                 }
1078
1079                 if(cls.capturevideo.soundrate)
1080                 for(;;)
1081                 {
1082                         int result = qogg_stream_flush (&format->vo, &pg);
1083                         if (result < 0)
1084                                 fprintf (stderr, "Internal Ogg library error.\n"); // TODO Host_Error
1085                         if (result <= 0)
1086                                 break;
1087                         FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
1088                         FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
1089                 }
1090         }
1091 }