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