]> git.sesse.net Git - vlc/blob - modules/codec/theora.c
Removed es_format_t::i_aspect.
[vlc] / modules / codec / theora.c
1 /*****************************************************************************
2  * theora.c: theora decoder module making use of libtheora.
3  *****************************************************************************
4  * Copyright (C) 1999-2001 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program 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.
13  *
14  * This program 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.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_codec.h>
34 #include <vlc_sout.h>
35 #include <vlc_input.h>
36 #include <ogg/ogg.h>
37
38 #include <theora/theora.h>
39
40 /*****************************************************************************
41  * decoder_sys_t : theora decoder descriptor
42  *****************************************************************************/
43 struct decoder_sys_t
44 {
45     /* Module mode */
46     bool b_packetizer;
47
48     /*
49      * Input properties
50      */
51     int i_headers;
52
53     /*
54      * Theora properties
55      */
56     theora_info      ti;                        /* theora bitstream settings */
57     theora_comment   tc;                            /* theora comment header */
58     theora_state     td;                   /* theora bitstream user comments */
59
60     /*
61      * Decoding properties
62      */
63     bool b_decoded_first_keyframe;
64
65     /*
66      * Common properties
67      */
68     mtime_t i_pts;
69 };
70
71 /*****************************************************************************
72  * Local prototypes
73  *****************************************************************************/
74 static int  OpenDecoder   ( vlc_object_t * );
75 static int  OpenPacketizer( vlc_object_t * );
76 static void CloseDecoder  ( vlc_object_t * );
77
78 static void *DecodeBlock  ( decoder_t *, block_t ** );
79 static int  ProcessHeaders( decoder_t * );
80 static void *ProcessPacket ( decoder_t *, ogg_packet *, block_t ** );
81
82 static picture_t *DecodePacket( decoder_t *, ogg_packet * );
83
84 static void ParseTheoraComments( decoder_t * );
85 static void theora_CopyPicture( picture_t *, yuv_buffer * );
86
87 static int  OpenEncoder( vlc_object_t *p_this );
88 static void CloseEncoder( vlc_object_t *p_this );
89 static block_t *Encode( encoder_t *p_enc, picture_t *p_pict );
90
91 /*****************************************************************************
92  * Module descriptor
93  *****************************************************************************/
94 #define ENC_QUALITY_TEXT N_("Encoding quality")
95 #define ENC_QUALITY_LONGTEXT N_( \
96   "Enforce a quality between 1 (low) and 10 (high), instead " \
97   "of specifying a particular bitrate. This will produce a VBR stream." )
98
99 vlc_module_begin ()
100     set_category( CAT_INPUT )
101     set_subcategory( SUBCAT_INPUT_VCODEC )
102     set_shortname( "Theora" )
103     set_description( N_("Theora video decoder") )
104     set_capability( "decoder", 100 )
105     set_callbacks( OpenDecoder, CloseDecoder )
106     add_shortcut( "theora" )
107
108     add_submodule ()
109     set_description( N_("Theora video packetizer") )
110     set_capability( "packetizer", 100 )
111     set_callbacks( OpenPacketizer, CloseDecoder )
112     add_shortcut( "theora" )
113
114     add_submodule ()
115     set_description( N_("Theora video encoder") )
116     set_capability( "encoder", 150 )
117     set_callbacks( OpenEncoder, CloseEncoder )
118     add_shortcut( "theora" )
119
120 #   define ENC_CFG_PREFIX "sout-theora-"
121     add_integer( ENC_CFG_PREFIX "quality", 2, NULL, ENC_QUALITY_TEXT,
122                  ENC_QUALITY_LONGTEXT, false )
123 vlc_module_end ()
124
125 static const char *const ppsz_enc_options[] = {
126     "quality", NULL
127 };
128
129 /*****************************************************************************
130  * OpenDecoder: probe the decoder and return score
131  *****************************************************************************/
132 static int OpenDecoder( vlc_object_t *p_this )
133 {
134     decoder_t *p_dec = (decoder_t*)p_this;
135     decoder_sys_t *p_sys;
136
137     if( p_dec->fmt_in.i_codec != VLC_CODEC_THEORA )
138     {
139         return VLC_EGENERIC;
140     }
141
142     /* Allocate the memory needed to store the decoder's structure */
143     if( ( p_dec->p_sys = p_sys = malloc(sizeof(*p_sys)) ) == NULL )
144         return VLC_ENOMEM;
145     p_dec->p_sys->b_packetizer = false;
146
147     p_sys->i_pts = VLC_TS_INVALID;
148     p_sys->b_decoded_first_keyframe = false;
149
150     /* Set output properties */
151     p_dec->fmt_out.i_cat = VIDEO_ES;
152     p_dec->fmt_out.i_codec = VLC_CODEC_I420;
153
154     /* Set callbacks */
155     p_dec->pf_decode_video = (picture_t *(*)(decoder_t *, block_t **))
156         DecodeBlock;
157     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
158         DecodeBlock;
159
160     /* Init supporting Theora structures needed in header parsing */
161     theora_comment_init( &p_sys->tc );
162     theora_info_init( &p_sys->ti );
163
164     p_sys->i_headers = 0;
165
166     return VLC_SUCCESS;
167 }
168
169 static int OpenPacketizer( vlc_object_t *p_this )
170 {
171     decoder_t *p_dec = (decoder_t*)p_this;
172
173     int i_ret = OpenDecoder( p_this );
174
175     if( i_ret == VLC_SUCCESS )
176     {
177         p_dec->p_sys->b_packetizer = true;
178         p_dec->fmt_out.i_codec = VLC_CODEC_THEORA;
179     }
180
181     return i_ret;
182 }
183
184 /****************************************************************************
185  * DecodeBlock: the whole thing
186  ****************************************************************************
187  * This function must be fed with ogg packets.
188  ****************************************************************************/
189 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
190 {
191     decoder_sys_t *p_sys = p_dec->p_sys;
192     block_t *p_block;
193     ogg_packet oggpacket;
194
195     if( !pp_block || !*pp_block ) return NULL;
196
197     p_block = *pp_block;
198
199     /* Block to Ogg packet */
200     oggpacket.packet = p_block->p_buffer;
201     oggpacket.bytes = p_block->i_buffer;
202     oggpacket.granulepos = p_block->i_dts;
203     oggpacket.b_o_s = 0;
204     oggpacket.e_o_s = 0;
205     oggpacket.packetno = 0;
206
207     /* Check for headers */
208     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
209     {
210         /* Headers already available as extra data */
211         p_sys->i_headers = 3;
212     }
213     else if( oggpacket.bytes && p_sys->i_headers < 3 )
214     {
215         /* Backup headers as extra data */
216         uint8_t *p_extra;
217
218         p_dec->fmt_in.p_extra = xrealloc( p_dec->fmt_in.p_extra,
219                                 p_dec->fmt_in.i_extra + oggpacket.bytes + 2 );
220         p_extra = ((uint8_t *)p_dec->fmt_in.p_extra) + p_dec->fmt_in.i_extra;
221         *(p_extra++) = oggpacket.bytes >> 8;
222         *(p_extra++) = oggpacket.bytes & 0xFF;
223
224         memcpy( p_extra, oggpacket.packet, oggpacket.bytes );
225         p_dec->fmt_in.i_extra += oggpacket.bytes + 2;
226
227         block_Release( *pp_block );
228         p_sys->i_headers++;
229         return NULL;
230     }
231
232     if( p_sys->i_headers == 3 )
233     {
234         if( ProcessHeaders( p_dec ) != VLC_SUCCESS )
235         {
236             p_sys->i_headers = 0;
237             p_dec->fmt_in.i_extra = 0;
238             block_Release( *pp_block );
239             return NULL;
240         }
241         else p_sys->i_headers++;
242     }
243
244     return ProcessPacket( p_dec, &oggpacket, pp_block );
245 }
246
247 /*****************************************************************************
248  * ProcessHeaders: process Theora headers.
249  *****************************************************************************/
250 static int ProcessHeaders( decoder_t *p_dec )
251 {
252     decoder_sys_t *p_sys = p_dec->p_sys;
253     ogg_packet oggpacket;
254     uint8_t *p_extra;
255     int i_extra;
256
257     if( !p_dec->fmt_in.i_extra ) return VLC_EGENERIC;
258
259     oggpacket.granulepos = -1;
260     oggpacket.b_o_s = 1; /* yes this actually is a b_o_s packet :) */
261     oggpacket.e_o_s = 0;
262     oggpacket.packetno = 0;
263     p_extra = p_dec->fmt_in.p_extra;
264     i_extra = p_dec->fmt_in.i_extra;
265
266     /* Take care of the initial Vorbis header */
267     oggpacket.bytes = *(p_extra++) << 8;
268     oggpacket.bytes |= (*(p_extra++) & 0xFF);
269     oggpacket.packet = p_extra;
270     p_extra += oggpacket.bytes;
271     i_extra -= (oggpacket.bytes + 2);
272     if( i_extra < 0 )
273     {
274         msg_Err( p_dec, "header data corrupted");
275         return VLC_EGENERIC;
276     }
277
278     if( theora_decode_header( &p_sys->ti, &p_sys->tc, &oggpacket ) < 0 )
279     {
280         msg_Err( p_dec, "this bitstream does not contain Theora video data" );
281         return VLC_EGENERIC;
282     }
283
284     /* Set output properties */
285     switch( p_sys->ti.pixelformat )
286     {
287       case OC_PF_420:
288         p_dec->fmt_out.i_codec = VLC_CODEC_I420;
289         break;
290       case OC_PF_422:
291         p_dec->fmt_out.i_codec = VLC_CODEC_I422;
292         break;
293       case OC_PF_444:
294         p_dec->fmt_out.i_codec = VLC_CODEC_I444;
295         break;
296       case OC_PF_RSVD:
297       default:
298         msg_Err( p_dec, "unknown chroma in theora sample" );
299         break;
300     }
301     p_dec->fmt_out.video.i_width = p_sys->ti.width;
302     p_dec->fmt_out.video.i_height = p_sys->ti.height;
303     if( p_sys->ti.frame_width && p_sys->ti.frame_height )
304     {
305         p_dec->fmt_out.video.i_visible_width = p_sys->ti.frame_width;
306         p_dec->fmt_out.video.i_visible_height = p_sys->ti.frame_height;
307         if( p_sys->ti.offset_x || p_sys->ti.offset_y )
308         {
309             p_dec->fmt_out.video.i_x_offset = p_sys->ti.offset_x;
310             p_dec->fmt_out.video.i_y_offset = p_sys->ti.offset_y;
311         }
312     }
313
314     if( p_sys->ti.aspect_denominator && p_sys->ti.aspect_numerator )
315     {
316         p_dec->fmt_out.video.i_sar_num = p_sys->ti.aspect_numerator;
317         p_dec->fmt_out.video.i_sar_den = p_sys->ti.aspect_denominator;
318     }
319     else
320     {
321         p_dec->fmt_out.video.i_sar_num = 1;
322         p_dec->fmt_out.video.i_sar_den = 1;
323     }
324
325     if( p_sys->ti.fps_numerator > 0 && p_sys->ti.fps_denominator > 0 )
326     {
327         p_dec->fmt_out.video.i_frame_rate = p_sys->ti.fps_numerator;
328         p_dec->fmt_out.video.i_frame_rate_base = p_sys->ti.fps_denominator;
329     }
330
331     msg_Dbg( p_dec, "%dx%d %.02f fps video, frame content "
332              "is %dx%d with offset (%d,%d)",
333              p_sys->ti.width, p_sys->ti.height,
334              (double)p_sys->ti.fps_numerator/p_sys->ti.fps_denominator,
335              p_sys->ti.frame_width, p_sys->ti.frame_height,
336              p_sys->ti.offset_x, p_sys->ti.offset_y );
337
338     /* Sanity check that seems necessary for some corrupted files */
339     if( p_sys->ti.width < p_sys->ti.frame_width ||
340         p_sys->ti.height < p_sys->ti.frame_height )
341     {
342         msg_Warn( p_dec, "trying to correct invalid theora header "
343                   "(frame size (%dx%d) is smaller than frame content (%d,%d))",
344                   p_sys->ti.width, p_sys->ti.height,
345                   p_sys->ti.frame_width, p_sys->ti.frame_height );
346
347         if( p_sys->ti.width < p_sys->ti.frame_width )
348             p_sys->ti.width = p_sys->ti.frame_width;
349         if( p_sys->ti.height < p_sys->ti.frame_height )
350             p_sys->ti.height = p_sys->ti.frame_height;
351     }
352
353     /* The next packet in order is the comments header */
354     oggpacket.b_o_s = 0;
355     oggpacket.bytes = *(p_extra++) << 8;
356     oggpacket.bytes |= (*(p_extra++) & 0xFF);
357     oggpacket.packet = p_extra;
358     p_extra += oggpacket.bytes;
359     i_extra -= (oggpacket.bytes + 2);
360     if( i_extra < 0 )
361     {
362         msg_Err( p_dec, "header data corrupted");
363         return VLC_EGENERIC;
364     }
365
366     /* The next packet in order is the comments header */
367     if( theora_decode_header( &p_sys->ti, &p_sys->tc, &oggpacket ) < 0 )
368     {
369         msg_Err( p_dec, "2nd Theora header is corrupted" );
370         return VLC_EGENERIC;
371     }
372
373     ParseTheoraComments( p_dec );
374
375     /* The next packet in order is the codebooks header
376      * We need to watch out that this packet is not missing as a
377      * missing or corrupted header is fatal. */
378     oggpacket.bytes = *(p_extra++) << 8;
379     oggpacket.bytes |= (*(p_extra++) & 0xFF);
380     oggpacket.packet = p_extra;
381     i_extra -= (oggpacket.bytes + 2);
382     if( i_extra < 0 )
383     {
384         msg_Err( p_dec, "header data corrupted");
385         return VLC_EGENERIC;
386     }
387
388     /* The next packet in order is the codebooks header
389      * We need to watch out that this packet is not missing as a
390      * missing or corrupted header is fatal */
391     if( theora_decode_header( &p_sys->ti, &p_sys->tc, &oggpacket ) < 0 )
392     {
393         msg_Err( p_dec, "3rd Theora header is corrupted" );
394         return VLC_EGENERIC;
395     }
396
397     if( !p_sys->b_packetizer )
398     {
399         /* We have all the headers, initialize decoder */
400         theora_decode_init( &p_sys->td, &p_sys->ti );
401     }
402     else
403     {
404         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
405         p_dec->fmt_out.p_extra = xrealloc( p_dec->fmt_out.p_extra,
406                                                   p_dec->fmt_out.i_extra );
407         memcpy( p_dec->fmt_out.p_extra,
408                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
409     }
410
411     return VLC_SUCCESS;
412 }
413
414 /*****************************************************************************
415  * ProcessPacket: processes a theora packet.
416  *****************************************************************************/
417 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
418                             block_t **pp_block )
419 {
420     decoder_sys_t *p_sys = p_dec->p_sys;
421     block_t *p_block = *pp_block;
422     void *p_buf;
423
424     if( ( p_block->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) ) != 0 )
425     {
426         /* Don't send the the first packet after a discontinuity to
427          * theora_decode, otherwise we get purple/green display artifacts
428          * appearing in the video output */
429         return NULL;
430     }
431
432     /* Date management */
433     if( p_block->i_pts > VLC_TS_INVALID && p_block->i_pts != p_sys->i_pts )
434     {
435         p_sys->i_pts = p_block->i_pts;
436     }
437
438     *pp_block = NULL; /* To avoid being fed the same packet again */
439
440     if( p_sys->b_packetizer )
441     {
442         /* Date management */
443         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
444
445         if( p_sys->i_headers >= 3 )
446             p_block->i_length = p_sys->i_pts - p_block->i_pts;
447         else
448             p_block->i_length = 0;
449
450         p_buf = p_block;
451     }
452     else
453     {
454         if( p_sys->i_headers >= 3 )
455             p_buf = DecodePacket( p_dec, p_oggpacket );
456         else
457             p_buf = NULL;
458
459         if( p_block ) block_Release( p_block );
460     }
461
462     /* Date management */
463     p_sys->i_pts += ( INT64_C(1000000) * p_sys->ti.fps_denominator /
464                       p_sys->ti.fps_numerator ); /* 1 frame per packet */
465
466     return p_buf;
467 }
468
469 /*****************************************************************************
470  * DecodePacket: decodes a Theora packet.
471  *****************************************************************************/
472 static picture_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
473 {
474     decoder_sys_t *p_sys = p_dec->p_sys;
475     picture_t *p_pic;
476     yuv_buffer yuv;
477
478     theora_decode_packetin( &p_sys->td, p_oggpacket );
479
480     /* Check for keyframe */
481     if( !(p_oggpacket->packet[0] & 0x80) /* data packet */ &&
482         !(p_oggpacket->packet[0] & 0x40) /* intra frame */ )
483         p_sys->b_decoded_first_keyframe = true;
484
485     /* If we haven't seen a single keyframe yet, don't let Theora decode
486      * anything, otherwise we'll get display artifacts.  (This is impossible
487      * in the general case, but can happen if e.g. we play a network stream
488      * using a timed URL, such that the server doesn't start the video with a
489      * keyframe). */
490     if( p_sys->b_decoded_first_keyframe )
491         theora_decode_YUVout( &p_sys->td, &yuv );
492     else
493         return NULL;
494
495     /* Get a new picture */
496     p_pic = decoder_NewPicture( p_dec );
497     if( !p_pic ) return NULL;
498
499     theora_CopyPicture( p_pic, &yuv );
500
501     p_pic->date = p_sys->i_pts;
502
503     return p_pic;
504 }
505
506 /*****************************************************************************
507  * ParseTheoraComments:
508  *****************************************************************************/
509 static void ParseTheoraComments( decoder_t *p_dec )
510 {
511     char *psz_name, *psz_value, *psz_comment;
512     int i = 0;
513
514     while ( i < p_dec->p_sys->tc.comments )
515     {
516         psz_comment = strdup( p_dec->p_sys->tc.user_comments[i] );
517         if( !psz_comment )
518             break;
519         psz_name = psz_comment;
520         psz_value = strchr( psz_comment, '=' );
521         if( psz_value )
522         {
523             *psz_value = '\0';
524             psz_value++;
525
526             if( !p_dec->p_description )
527                 p_dec->p_description = vlc_meta_New();
528             if( p_dec->p_description )
529                 vlc_meta_AddExtra( p_dec->p_description, psz_name, psz_value );
530         }
531         free( psz_comment );
532         i++;
533     }
534 }
535
536 /*****************************************************************************
537  * CloseDecoder: theora decoder destruction
538  *****************************************************************************/
539 static void CloseDecoder( vlc_object_t *p_this )
540 {
541     decoder_t *p_dec = (decoder_t *)p_this;
542     decoder_sys_t *p_sys = p_dec->p_sys;
543
544     theora_info_clear( &p_sys->ti );
545     theora_comment_clear( &p_sys->tc );
546
547     free( p_sys );
548 }
549
550 /*****************************************************************************
551  * theora_CopyPicture: copy a picture from theora internal buffers to a
552  *                     picture_t structure.
553  *****************************************************************************/
554 static void theora_CopyPicture( picture_t *p_pic,
555                                 yuv_buffer *yuv )
556 {
557     int i_plane, i_line, i_dst_stride, i_src_stride;
558     uint8_t *p_dst, *p_src;
559
560     for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
561     {
562         p_dst = p_pic->p[i_plane].p_pixels;
563         p_src = i_plane ? (i_plane - 1 ? yuv->v : yuv->u ) : yuv->y;
564         i_dst_stride  = p_pic->p[i_plane].i_pitch;
565         i_src_stride  = i_plane ? yuv->uv_stride : yuv->y_stride;
566
567         for( i_line = 0; i_line < p_pic->p[i_plane].i_lines; i_line++ )
568         {
569             vlc_memcpy( p_dst, p_src,
570                         i_plane ? yuv->uv_width : yuv->y_width );
571             p_src += i_src_stride;
572             p_dst += i_dst_stride;
573         }
574     }
575 }
576
577 /*****************************************************************************
578  * encoder_sys_t : theora encoder descriptor
579  *****************************************************************************/
580 struct encoder_sys_t
581 {
582     /*
583      * Input properties
584      */
585     bool b_headers;
586
587     /*
588      * Theora properties
589      */
590     theora_info      ti;                        /* theora bitstream settings */
591     theora_comment   tc;                            /* theora comment header */
592     theora_state     td;                   /* theora bitstream user comments */
593
594     int i_width, i_height;
595 };
596
597 /*****************************************************************************
598  * OpenEncoder: probe the encoder and return score
599  *****************************************************************************/
600 static int OpenEncoder( vlc_object_t *p_this )
601 {
602     encoder_t *p_enc = (encoder_t *)p_this;
603     encoder_sys_t *p_sys;
604     ogg_packet header;
605     uint8_t *p_extra;
606     int i_quality, i;
607
608     if( p_enc->fmt_out.i_codec != VLC_CODEC_THEORA &&
609         !p_enc->b_force )
610     {
611         return VLC_EGENERIC;
612     }
613
614     /* Allocate the memory needed to store the decoder's structure */
615     if( ( p_sys = malloc(sizeof(encoder_sys_t)) ) == NULL )
616         return VLC_ENOMEM;
617     p_enc->p_sys = p_sys;
618
619     p_enc->pf_encode_video = Encode;
620     p_enc->fmt_in.i_codec = VLC_CODEC_I420;
621     p_enc->fmt_out.i_codec = VLC_CODEC_THEORA;
622
623     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
624
625     i_quality = var_GetInteger( p_enc, ENC_CFG_PREFIX "quality" );
626     if( i_quality > 10 ) i_quality = 10;
627     if( i_quality < 0 ) i_quality = 0;
628
629     theora_info_init( &p_sys->ti );
630
631     p_sys->ti.width = p_enc->fmt_in.video.i_width;
632     p_sys->ti.height = p_enc->fmt_in.video.i_height;
633
634     if( p_sys->ti.width % 16 || p_sys->ti.height % 16 )
635     {
636         /* Pictures from the transcoder should always have a pitch
637          * which is a multiple of 16 */
638         p_sys->ti.width = (p_sys->ti.width + 15) >> 4 << 4;
639         p_sys->ti.height = (p_sys->ti.height + 15) >> 4 << 4;
640
641         msg_Dbg( p_enc, "padding video from %dx%d to %dx%d",
642                  p_enc->fmt_in.video.i_width, p_enc->fmt_in.video.i_height,
643                  p_sys->ti.width, p_sys->ti.height );
644     }
645
646     p_sys->ti.frame_width = p_enc->fmt_in.video.i_width;
647     p_sys->ti.frame_height = p_enc->fmt_in.video.i_height;
648     p_sys->ti.offset_x = 0 /*frame_x_offset*/;
649     p_sys->ti.offset_y = 0 /*frame_y_offset*/;
650
651     p_sys->i_width = p_sys->ti.width;
652     p_sys->i_height = p_sys->ti.height;
653
654     if( !p_enc->fmt_in.video.i_frame_rate ||
655         !p_enc->fmt_in.video.i_frame_rate_base )
656     {
657         p_sys->ti.fps_numerator = 25;
658         p_sys->ti.fps_denominator = 1;
659     }
660     else
661     {
662         p_sys->ti.fps_numerator = p_enc->fmt_in.video.i_frame_rate;
663         p_sys->ti.fps_denominator = p_enc->fmt_in.video.i_frame_rate_base;
664     }
665
666     if( p_enc->fmt_in.video.i_sar_num > 0 && p_enc->fmt_in.video.i_sar_den > 0 )
667     {
668         unsigned i_dst_num, i_dst_den;
669         vlc_ureduce( &i_dst_num, &i_dst_den,
670                      p_enc->fmt_in.video.i_sar_num,
671                      p_enc->fmt_in.video.i_sar_den, 0 );
672         p_sys->ti.aspect_numerator = i_dst_num;
673         p_sys->ti.aspect_denominator = i_dst_den;
674     }
675     else
676     {
677         p_sys->ti.aspect_numerator = 4;
678         p_sys->ti.aspect_denominator = 3;
679     }
680
681     p_sys->ti.target_bitrate = p_enc->fmt_out.i_bitrate;
682     p_sys->ti.quality = ((float)i_quality) * 6.3;
683
684     p_sys->ti.dropframes_p = 0;
685     p_sys->ti.quick_p = 1;
686     p_sys->ti.keyframe_auto_p = 1;
687     p_sys->ti.keyframe_frequency = 64;
688     p_sys->ti.keyframe_frequency_force = 64;
689     p_sys->ti.keyframe_data_target_bitrate = p_enc->fmt_out.i_bitrate * 1.5;
690     p_sys->ti.keyframe_auto_threshold = 80;
691     p_sys->ti.keyframe_mindistance = 8;
692     p_sys->ti.noise_sensitivity = 1;
693
694     theora_encode_init( &p_sys->td, &p_sys->ti );
695     theora_comment_init( &p_sys->tc );
696
697     /* Create and store headers */
698     p_enc->fmt_out.i_extra = 3 * 2;
699     for( i = 0; i < 3; i++ )
700     {
701         if( i == 0 ) theora_encode_header( &p_sys->td, &header );
702         else if( i == 1 ) theora_encode_comment( &p_sys->tc, &header );
703         else if( i == 2 ) theora_encode_tables( &p_sys->td, &header );
704
705         p_enc->fmt_out.p_extra = xrealloc( p_enc->fmt_out.p_extra,
706                                       p_enc->fmt_out.i_extra + header.bytes );
707         p_extra = p_enc->fmt_out.p_extra;
708         p_extra += p_enc->fmt_out.i_extra + (i-3)*2;
709         p_enc->fmt_out.i_extra += header.bytes;
710
711         *(p_extra++) = header.bytes >> 8;
712         *(p_extra++) = header.bytes & 0xFF;
713
714         memcpy( p_extra, header.packet, header.bytes );
715     }
716
717     return VLC_SUCCESS;
718 }
719
720 /****************************************************************************
721  * Encode: the whole thing
722  ****************************************************************************
723  * This function spits out ogg packets.
724  ****************************************************************************/
725 static block_t *Encode( encoder_t *p_enc, picture_t *p_pict )
726 {
727     encoder_sys_t *p_sys = p_enc->p_sys;
728     ogg_packet oggpacket;
729     block_t *p_block;
730     yuv_buffer yuv;
731     int i;
732
733     /* Sanity check */
734     if( p_pict->p[0].i_pitch < (int)p_sys->i_width ||
735         p_pict->p[0].i_lines < (int)p_sys->i_height )
736     {
737         msg_Warn( p_enc, "frame is smaller than encoding size"
738                   "(%ix%i->%ix%i) -> dropping frame",
739                   p_pict->p[0].i_pitch, p_pict->p[0].i_lines,
740                   p_sys->i_width, p_sys->i_height );
741         return NULL;
742     }
743
744     /* Fill padding */
745     if( p_pict->p[0].i_visible_pitch < (int)p_sys->i_width )
746     {
747         for( i = 0; i < p_sys->i_height; i++ )
748         {
749             memset( p_pict->p[0].p_pixels + i * p_pict->p[0].i_pitch +
750                     p_pict->p[0].i_visible_pitch,
751                     *( p_pict->p[0].p_pixels + i * p_pict->p[0].i_pitch +
752                        p_pict->p[0].i_visible_pitch - 1 ),
753                     p_sys->i_width - p_pict->p[0].i_visible_pitch );
754         }
755         for( i = 0; i < p_sys->i_height / 2; i++ )
756         {
757             memset( p_pict->p[1].p_pixels + i * p_pict->p[1].i_pitch +
758                     p_pict->p[1].i_visible_pitch,
759                     *( p_pict->p[1].p_pixels + i * p_pict->p[1].i_pitch +
760                        p_pict->p[1].i_visible_pitch - 1 ),
761                     p_sys->i_width / 2 - p_pict->p[1].i_visible_pitch );
762             memset( p_pict->p[2].p_pixels + i * p_pict->p[2].i_pitch +
763                     p_pict->p[2].i_visible_pitch,
764                     *( p_pict->p[2].p_pixels + i * p_pict->p[2].i_pitch +
765                        p_pict->p[2].i_visible_pitch - 1 ),
766                     p_sys->i_width / 2 - p_pict->p[2].i_visible_pitch );
767         }
768     }
769
770     if( p_pict->p[0].i_visible_lines < (int)p_sys->i_height )
771     {
772         for( i = p_pict->p[0].i_visible_lines; i < p_sys->i_height; i++ )
773         {
774             memset( p_pict->p[0].p_pixels + i * p_pict->p[0].i_pitch, 0,
775                     p_sys->i_width );
776         }
777         for( i = p_pict->p[1].i_visible_lines; i < p_sys->i_height / 2; i++ )
778         {
779             memset( p_pict->p[1].p_pixels + i * p_pict->p[1].i_pitch, 0x80,
780                     p_sys->i_width / 2 );
781             memset( p_pict->p[2].p_pixels + i * p_pict->p[2].i_pitch, 0x80,
782                     p_sys->i_width / 2 );
783         }
784     }
785
786     /* Theora is a one-frame-in, one-frame-out system. Submit a frame
787      * for compression and pull out the packet. */
788
789     yuv.y_width  = p_sys->i_width;
790     yuv.y_height = p_sys->i_height;
791     yuv.y_stride = p_pict->p[0].i_pitch;
792
793     yuv.uv_width  = p_sys->i_width / 2;
794     yuv.uv_height = p_sys->i_height / 2;
795     yuv.uv_stride = p_pict->p[1].i_pitch;
796
797     yuv.y = p_pict->p[0].p_pixels;
798     yuv.u = p_pict->p[1].p_pixels;
799     yuv.v = p_pict->p[2].p_pixels;
800
801     if( theora_encode_YUVin( &p_sys->td, &yuv ) < 0 )
802     {
803         msg_Warn( p_enc, "failed encoding a frame" );
804         return NULL;
805     }
806
807     theora_encode_packetout( &p_sys->td, 0, &oggpacket );
808
809     /* Ogg packet to block */
810     p_block = block_New( p_enc, oggpacket.bytes );
811     memcpy( p_block->p_buffer, oggpacket.packet, oggpacket.bytes );
812     p_block->i_dts = p_block->i_pts = p_pict->date;
813
814     if( theora_packet_iskeyframe( &oggpacket ) )
815     {
816         p_block->i_flags |= BLOCK_FLAG_TYPE_I;
817     }
818
819     return p_block;
820 }
821
822 /*****************************************************************************
823  * CloseEncoder: theora encoder destruction
824  *****************************************************************************/
825 static void CloseEncoder( vlc_object_t *p_this )
826 {
827     encoder_t *p_enc = (encoder_t *)p_this;
828     encoder_sys_t *p_sys = p_enc->p_sys;
829
830     theora_info_clear( &p_sys->ti );
831     theora_comment_clear( &p_sys->tc );
832
833     free( p_sys );
834 }