]> git.sesse.net Git - vlc/blob - modules/codec/theora.c
* modules/codec/theora.c: sanity check for invalid theora header.
[vlc] / modules / codec / theora.c
1 /*****************************************************************************
2  * theora.c: theora decoder module making use of libtheora.
3  *****************************************************************************
4  * Copyright (C) 1999-2001 VideoLAN
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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <vlc/vlc.h>
28 #include <vlc/decoder.h>
29 #include <vlc/input.h>
30 #include <vlc/sout.h>
31
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   "Allows you to specify 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_description( _("Theora video decoder") );
99     set_capability( "decoder", 100 );
100     set_callbacks( OpenDecoder, CloseDecoder );
101     add_shortcut( "theora" );
102
103     add_submodule();
104     set_description( _("Theora video packetizer") );
105     set_capability( "packetizer", 100 );
106     set_callbacks( OpenPacketizer, CloseDecoder );
107     add_shortcut( "theora" );
108
109     add_submodule();
110     set_description( _("Theora video encoder") );
111     set_capability( "encoder", 100 );
112     set_callbacks( OpenEncoder, CloseEncoder );
113     add_shortcut( "theora" );
114
115 #   define ENC_CFG_PREFIX "sout-theora-"
116     add_integer( ENC_CFG_PREFIX "quality", 2, NULL, ENC_QUALITY_TEXT,
117                  ENC_QUALITY_LONGTEXT, VLC_FALSE );
118 vlc_module_end();
119
120 static const char *ppsz_enc_options[] = {
121     "quality", NULL
122 };
123
124 /*****************************************************************************
125  * OpenDecoder: probe the decoder and return score
126  *****************************************************************************/
127 static int OpenDecoder( vlc_object_t *p_this )
128 {
129     decoder_t *p_dec = (decoder_t*)p_this;
130     decoder_sys_t *p_sys;
131
132     if( p_dec->fmt_in.i_codec != VLC_FOURCC('t','h','e','o') )
133     {
134         return VLC_EGENERIC;
135     }
136
137     /* Allocate the memory needed to store the decoder's structure */
138     if( ( p_dec->p_sys = p_sys =
139           (decoder_sys_t *)malloc(sizeof(decoder_sys_t)) ) == NULL )
140     {
141         msg_Err( p_dec, "out of memory" );
142         return VLC_EGENERIC;
143     }
144     p_dec->p_sys->b_packetizer = VLC_FALSE;
145
146     p_sys->i_pts = 0;
147     p_sys->b_decoded_first_keyframe = VLC_FALSE;
148
149     /* Set output properties */
150     p_dec->fmt_out.i_cat = VIDEO_ES;
151     p_dec->fmt_out.i_codec = VLC_FOURCC('I','4','2','0');
152
153     /* Set callbacks */
154     p_dec->pf_decode_video = (picture_t *(*)(decoder_t *, block_t **))
155         DecodeBlock;
156     p_dec->pf_packetize    = (block_t *(*)(decoder_t *, block_t **))
157         DecodeBlock;
158
159     /* Init supporting Theora structures needed in header parsing */
160     theora_comment_init( &p_sys->tc );
161     theora_info_init( &p_sys->ti );
162
163     p_sys->i_headers = 0;
164
165     return VLC_SUCCESS;
166 }
167
168 static int OpenPacketizer( vlc_object_t *p_this )
169 {
170     decoder_t *p_dec = (decoder_t*)p_this;
171
172     int i_ret = OpenDecoder( p_this );
173
174     if( i_ret == VLC_SUCCESS )
175     {
176         p_dec->p_sys->b_packetizer = VLC_TRUE;
177         p_dec->fmt_out.i_codec = VLC_FOURCC( 't', 'h', 'e', 'o' );
178     }
179
180     return i_ret;
181 }
182
183 /****************************************************************************
184  * DecodeBlock: the whole thing
185  ****************************************************************************
186  * This function must be fed with ogg packets.
187  ****************************************************************************/
188 static void *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
189 {
190     decoder_sys_t *p_sys = p_dec->p_sys;
191     block_t *p_block;
192     ogg_packet oggpacket;
193
194     if( !pp_block || !*pp_block ) return NULL;
195
196     p_block = *pp_block;
197
198     /* Block to Ogg packet */
199     oggpacket.packet = p_block->p_buffer;
200     oggpacket.bytes = p_block->i_buffer;
201     oggpacket.granulepos = p_block->i_dts;
202     oggpacket.b_o_s = 0;
203     oggpacket.e_o_s = 0;
204     oggpacket.packetno = 0;
205
206     /* Check for headers */
207     if( p_sys->i_headers == 0 && p_dec->fmt_in.i_extra )
208     {
209         /* Headers already available as extra data */
210         p_sys->i_headers = 3;
211     }
212     else if( oggpacket.bytes && p_sys->i_headers < 3 )
213     {
214         /* Backup headers as extra data */
215         uint8_t *p_extra;
216
217         p_dec->fmt_in.p_extra =
218             realloc( p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra +
219                      oggpacket.bytes + 2 );
220         p_extra = 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     p_dec->fmt_out.video.i_width = p_sys->ti.width;
286     p_dec->fmt_out.video.i_height = p_sys->ti.height;
287     if( p_sys->ti.frame_width && p_sys->ti.frame_height )
288     {
289         p_dec->fmt_out.video.i_width = p_sys->ti.frame_width;
290         p_dec->fmt_out.video.i_height = p_sys->ti.frame_height;
291     }
292
293     if( p_sys->ti.aspect_denominator && p_sys->ti.aspect_numerator )
294     {
295         p_dec->fmt_out.video.i_aspect = ((int64_t)VOUT_ASPECT_FACTOR) *
296             ( p_sys->ti.aspect_numerator * p_sys->ti.width ) /
297             ( p_sys->ti.aspect_denominator * p_sys->ti.height );
298     }
299     else
300     {
301         p_dec->fmt_out.video.i_aspect = VOUT_ASPECT_FACTOR *
302             p_sys->ti.frame_width / p_sys->ti.frame_height;
303     }
304
305     if( p_sys->ti.fps_numerator > 0 && p_sys->ti.fps_denominator > 0 )
306     {
307         p_dec->fmt_out.video.i_frame_rate = p_sys->ti.fps_numerator;
308         p_dec->fmt_out.video.i_frame_rate_base = p_sys->ti.fps_denominator;
309     }
310
311     msg_Dbg( p_dec, "%dx%d %.02f fps video, frame content "
312              "is %dx%d with offset (%d,%d)",
313              p_sys->ti.width, p_sys->ti.height,
314              (double)p_sys->ti.fps_numerator/p_sys->ti.fps_denominator,
315              p_sys->ti.frame_width, p_sys->ti.frame_height,
316              p_sys->ti.offset_x, p_sys->ti.offset_y );
317
318     /* Sanity check that seems necessary for some corrupted files */
319     if( p_sys->ti.width < p_sys->ti.frame_width ||
320         p_sys->ti.height < p_sys->ti.frame_height )
321     {
322         msg_Warn( p_dec, "trying to correct invalid theora header "
323                   "(frame size (%dx%d) is smaller than frame content (%d,%d))",
324                   p_sys->ti.width, p_sys->ti.height,
325                   p_sys->ti.frame_width, p_sys->ti.frame_height );
326
327         if( p_sys->ti.width < p_sys->ti.frame_width )
328             p_sys->ti.width = p_sys->ti.frame_width;
329         if( p_sys->ti.height < p_sys->ti.frame_height )
330             p_sys->ti.height = p_sys->ti.frame_height;
331     }
332
333     /* The next packet in order is the comments header */
334     oggpacket.b_o_s = 0;
335     oggpacket.bytes = *(p_extra++) << 8;
336     oggpacket.bytes |= (*(p_extra++) & 0xFF);
337     oggpacket.packet = p_extra;
338     p_extra += oggpacket.bytes;
339     i_extra -= (oggpacket.bytes + 2);
340     if( i_extra < 0 )
341     {
342         msg_Err( p_dec, "header data corrupted");
343         return VLC_EGENERIC;
344     }
345
346     /* The next packet in order is the comments header */
347     if( theora_decode_header( &p_sys->ti, &p_sys->tc, &oggpacket ) < 0 )
348     {
349         msg_Err( p_dec, "2nd Theora header is corrupted" );
350         return VLC_EGENERIC;
351     }
352
353     ParseTheoraComments( p_dec );
354
355     /* The next packet in order is the codebooks header
356      * We need to watch out that this packet is not missing as a
357      * missing or corrupted header is fatal. */
358     oggpacket.bytes = *(p_extra++) << 8;
359     oggpacket.bytes |= (*(p_extra++) & 0xFF);
360     oggpacket.packet = p_extra;
361     i_extra -= (oggpacket.bytes + 2);
362     if( i_extra < 0 )
363     {
364         msg_Err( p_dec, "header data corrupted");
365         return VLC_EGENERIC;
366     }
367
368     /* The next packet in order is the codebooks header
369      * We need to watch out that this packet is not missing as a
370      * missing or corrupted header is fatal */
371     if( theora_decode_header( &p_sys->ti, &p_sys->tc, &oggpacket ) < 0 )
372     {
373         msg_Err( p_dec, "3rd Theora header is corrupted" );
374         return VLC_EGENERIC;
375     }
376
377     if( !p_sys->b_packetizer )
378     {
379         /* We have all the headers, initialize decoder */
380         theora_decode_init( &p_sys->td, &p_sys->ti );
381     }
382     else
383     {
384         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
385         p_dec->fmt_out.p_extra =
386             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
387         memcpy( p_dec->fmt_out.p_extra,
388                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
389     }
390
391     return VLC_SUCCESS;
392 }
393
394 /*****************************************************************************
395  * ProcessPacket: processes a theora packet.
396  *****************************************************************************/
397 static void *ProcessPacket( decoder_t *p_dec, ogg_packet *p_oggpacket,
398                             block_t **pp_block )
399 {
400     decoder_sys_t *p_sys = p_dec->p_sys;
401     block_t *p_block = *pp_block;
402     void *p_buf;
403
404     if( ( p_block->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) ) != 0 )
405     {
406         /* Don't send the the first packet after a discontinuity to
407          * theora_decode, otherwise we get purple/green display artifacts
408          * appearing in the video output */
409         return NULL;
410     }
411
412     /* Date management */
413     if( p_block->i_pts > 0 && p_block->i_pts != p_sys->i_pts )
414     {
415         p_sys->i_pts = p_block->i_pts;
416     }
417
418     *pp_block = NULL; /* To avoid being fed the same packet again */
419
420     if( p_sys->b_packetizer )
421     {
422         /* Date management */
423         p_block->i_dts = p_block->i_pts = p_sys->i_pts;
424
425         if( p_sys->i_headers >= 3 )
426             p_block->i_length = p_sys->i_pts - p_block->i_pts;
427         else
428             p_block->i_length = 0;
429
430         p_buf = p_block;
431     }
432     else
433     {
434         if( p_sys->i_headers >= 3 )
435             p_buf = DecodePacket( p_dec, p_oggpacket );
436         else
437             p_buf = NULL;
438
439         if( p_block ) block_Release( p_block );
440     }
441
442     /* Date management */
443     p_sys->i_pts += ( I64C(1000000) * p_sys->ti.fps_denominator /
444                       p_sys->ti.fps_numerator ); /* 1 frame per packet */
445
446     return p_buf;
447 }
448
449 /*****************************************************************************
450  * DecodePacket: decodes a Theora packet.
451  *****************************************************************************/
452 static picture_t *DecodePacket( decoder_t *p_dec, ogg_packet *p_oggpacket )
453 {
454     decoder_sys_t *p_sys = p_dec->p_sys;
455     picture_t *p_pic;
456     yuv_buffer yuv;
457
458     theora_decode_packetin( &p_sys->td, p_oggpacket );
459
460     /* Check for keyframe */
461     if( !(p_oggpacket->packet[0] & 0x80) /* data packet */ &&
462         !(p_oggpacket->packet[0] & 0x40) /* intra frame */ )
463         p_sys->b_decoded_first_keyframe = VLC_TRUE;
464
465     /* If we haven't seen a single keyframe yet, don't let Theora decode
466      * anything, otherwise we'll get display artifacts.  (This is impossible
467      * in the general case, but can happen if e.g. we play a network stream
468      * using a timed URL, such that the server doesn't start the video with a
469      * keyframe). */
470     if( p_sys->b_decoded_first_keyframe )
471         theora_decode_YUVout( &p_sys->td, &yuv );
472     else
473         return NULL;
474
475     /* Get a new picture */
476     p_pic = p_dec->pf_vout_buffer_new( p_dec );
477     if( !p_pic ) return NULL;
478
479     theora_CopyPicture( p_dec, p_pic, &yuv );
480
481     p_pic->date = p_sys->i_pts;
482
483     return p_pic;
484 }
485
486 /*****************************************************************************
487  * ParseTheoraComments: FIXME should be done in demuxer
488  *****************************************************************************/
489 static void ParseTheoraComments( decoder_t *p_dec )
490 {
491     input_thread_t *p_input = (input_thread_t *)p_dec->p_parent;
492     char *psz_name, *psz_value, *psz_comment;
493     int i = 0;
494
495     if( p_input->i_object_type != VLC_OBJECT_INPUT ) return;
496
497     while ( i < p_dec->p_sys->tc.comments )
498     {
499         psz_comment = strdup( p_dec->p_sys->tc.user_comments[i] );
500         if( !psz_comment )
501         {
502             msg_Warn( p_dec, "out of memory" );
503             break;
504         }
505         psz_name = psz_comment;
506         psz_value = strchr( psz_comment, '=' );
507         if( psz_value )
508         {
509             *psz_value = '\0';
510             psz_value++;
511             input_Control( p_input, INPUT_ADD_INFO, _("Theora comment"),
512                            psz_name, psz_value );
513         }
514         free( psz_comment );
515         i++;
516     }
517 }
518
519 /*****************************************************************************
520  * CloseDecoder: theora decoder destruction
521  *****************************************************************************/
522 static void CloseDecoder( vlc_object_t *p_this )
523 {
524     decoder_t *p_dec = (decoder_t *)p_this;
525     decoder_sys_t *p_sys = p_dec->p_sys;
526
527     theora_info_clear( &p_sys->ti );
528     theora_comment_clear( &p_sys->tc );
529
530     free( p_sys );
531 }
532
533 /*****************************************************************************
534  * theora_CopyPicture: copy a picture from theora internal buffers to a
535  *                     picture_t structure.
536  *****************************************************************************/
537 static void theora_CopyPicture( decoder_t *p_dec, picture_t *p_pic,
538                                 yuv_buffer *yuv )
539 {
540     int i_plane, i_line, i_width, i_dst_stride, i_src_stride;
541     int i_src_xoffset, i_src_yoffset;
542     uint8_t *p_dst, *p_src;
543
544     for( i_plane = 0; i_plane < p_pic->i_planes; i_plane++ )
545     {
546         p_dst = p_pic->p[i_plane].p_pixels;
547         p_src = i_plane ? (i_plane - 1 ? yuv->v : yuv->u ) : yuv->y;
548         i_width = p_pic->p[i_plane].i_visible_pitch;
549         i_dst_stride  = p_pic->p[i_plane].i_pitch;
550         i_src_stride  = i_plane ? yuv->uv_stride : yuv->y_stride;
551         i_src_xoffset = p_dec->p_sys->ti.offset_x;
552         i_src_yoffset = p_dec->p_sys->ti.offset_y;
553         if( i_plane )
554         {
555             i_src_xoffset /= 2;
556             i_src_yoffset /= 2;
557         }
558
559         p_src += (i_src_yoffset * i_src_stride + i_src_yoffset);
560
561         for( i_line = 0; i_line < p_pic->p[i_plane].i_visible_lines; i_line++ )
562         {
563             p_dec->p_vlc->pf_memcpy( p_dst, p_src + i_src_xoffset,
564                                      i_plane ? yuv->uv_width : yuv->y_width );
565             p_src += i_src_stride;
566             p_dst += i_dst_stride;
567         }
568     }
569 }
570
571 /*****************************************************************************
572  * encoder_sys_t : theora encoder descriptor
573  *****************************************************************************/
574 struct encoder_sys_t
575 {
576     /*
577      * Input properties
578      */
579     vlc_bool_t b_headers;
580
581     /*
582      * Theora properties
583      */
584     theora_info      ti;                        /* theora bitstream settings */
585     theora_comment   tc;                            /* theora comment header */
586     theora_state     td;                   /* theora bitstream user comments */
587
588     int i_width, i_height;
589 };
590
591 /*****************************************************************************
592  * OpenEncoder: probe the encoder and return score
593  *****************************************************************************/
594 static int OpenEncoder( vlc_object_t *p_this )
595 {
596     encoder_t *p_enc = (encoder_t *)p_this;
597     encoder_sys_t *p_sys = p_enc->p_sys;
598     ogg_packet header;
599     uint8_t *p_extra;
600     vlc_value_t val;
601     int i_quality, i;
602
603     if( p_enc->fmt_out.i_codec != VLC_FOURCC('t','h','e','o') &&
604         !p_enc->b_force )
605     {
606         return VLC_EGENERIC;
607     }
608
609     /* Allocate the memory needed to store the decoder's structure */
610     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
611     {
612         msg_Err( p_enc, "out of memory" );
613         return VLC_EGENERIC;
614     }
615     p_enc->p_sys = p_sys;
616
617     p_enc->pf_encode_video = Encode;
618     p_enc->fmt_in.i_codec = VLC_FOURCC('I','4','2','0');
619     p_enc->fmt_out.i_codec = VLC_FOURCC('t','h','e','o');
620
621     sout_CfgParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
622
623     var_Get( p_enc, ENC_CFG_PREFIX "quality", &val );
624     i_quality = val.i_int;
625     if( i_quality > 10 ) i_quality = 10;
626     if( i_quality < 0 ) i_quality = 0;
627
628     theora_info_init( &p_sys->ti );
629
630     p_sys->ti.width = p_enc->fmt_in.video.i_width;
631     p_sys->ti.height = p_enc->fmt_in.video.i_height;
632
633     if( p_sys->ti.width % 16 || p_sys->ti.height % 16 )
634     {
635         /* Pictures from the transcoder should always have a pitch
636          * which is a multiple of 16 */
637         p_sys->ti.width = (p_sys->ti.width + 15) >> 4 << 4;
638         p_sys->ti.height = (p_sys->ti.height + 15) >> 4 << 4;
639
640         msg_Dbg( p_enc, "padding video from %dx%d to %dx%d",
641                  p_enc->fmt_in.video.i_width, p_enc->fmt_in.video.i_height,
642                  p_sys->ti.width, p_sys->ti.height );
643     }
644
645     p_sys->ti.frame_width = p_enc->fmt_in.video.i_width;
646     p_sys->ti.frame_height = p_enc->fmt_in.video.i_height;
647     p_sys->ti.offset_x = 0 /*frame_x_offset*/;
648     p_sys->ti.offset_y = 0 /*frame_y_offset*/;
649
650     p_sys->i_width = p_sys->ti.width;
651     p_sys->i_height = p_sys->ti.height;
652
653     if( !p_enc->fmt_in.video.i_frame_rate ||
654         !p_enc->fmt_in.video.i_frame_rate_base )
655     {
656         p_sys->ti.fps_numerator = 25;
657         p_sys->ti.fps_denominator = 1;
658     }
659     else
660     {
661         p_sys->ti.fps_numerator = p_enc->fmt_in.video.i_frame_rate;
662         p_sys->ti.fps_denominator = p_enc->fmt_in.video.i_frame_rate_base;
663     }
664
665     if( p_enc->fmt_in.video.i_aspect )
666     {
667         int64_t i_num, i_den;
668         int i_dst_num, i_dst_den;
669
670         i_num = p_enc->fmt_in.video.i_aspect * (int64_t)p_sys->ti.height;
671         i_den = VOUT_ASPECT_FACTOR * p_sys->ti.width;
672         vlc_reduce( &i_dst_num, &i_dst_den, i_num, i_den, 0 );
673         p_sys->ti.aspect_numerator = i_dst_num;
674         p_sys->ti.aspect_denominator = i_dst_den;
675     }
676     else
677     {
678         p_sys->ti.aspect_numerator = 4;
679         p_sys->ti.aspect_denominator = 3;
680     }
681
682     p_sys->ti.target_bitrate = p_enc->fmt_out.i_bitrate;
683     p_sys->ti.quality = ((float)i_quality) * 6.3;
684
685     p_sys->ti.dropframes_p = 0;
686     p_sys->ti.quick_p = 1;
687     p_sys->ti.keyframe_auto_p = 1;
688     p_sys->ti.keyframe_frequency = 64;
689     p_sys->ti.keyframe_frequency_force = 64;
690     p_sys->ti.keyframe_data_target_bitrate = p_enc->fmt_out.i_bitrate * 1.5;
691     p_sys->ti.keyframe_auto_threshold = 80;
692     p_sys->ti.keyframe_mindistance = 8;
693     p_sys->ti.noise_sensitivity = 1;
694
695     theora_encode_init( &p_sys->td, &p_sys->ti );
696     theora_info_clear( &p_sys->ti );
697     theora_comment_init( &p_sys->tc );
698
699     /* Create and store headers */
700     p_enc->fmt_out.i_extra = 3 * 2;
701     for( i = 0; i < 3; i++ )
702     {
703         if( i == 0 ) theora_encode_header( &p_sys->td, &header );
704         else if( i == 1 ) theora_encode_comment( &p_sys->tc, &header );
705         else if( i == 2 ) theora_encode_tables( &p_sys->td, &header );
706
707         p_enc->fmt_out.p_extra =
708             realloc( p_enc->fmt_out.p_extra,
709                      p_enc->fmt_out.i_extra + header.bytes );
710         p_extra = p_enc->fmt_out.p_extra;
711         p_extra += p_enc->fmt_out.i_extra + (i-3)*2;
712         p_enc->fmt_out.i_extra += header.bytes;
713
714         *(p_extra++) = header.bytes >> 8;
715         *(p_extra++) = header.bytes & 0xFF;
716
717         memcpy( p_extra, header.packet, header.bytes );
718     }
719
720     return VLC_SUCCESS;
721 }
722
723 /****************************************************************************
724  * Encode: the whole thing
725  ****************************************************************************
726  * This function spits out ogg packets.
727  ****************************************************************************/
728 static block_t *Encode( encoder_t *p_enc, picture_t *p_pict )
729 {
730     encoder_sys_t *p_sys = p_enc->p_sys;
731     ogg_packet oggpacket;
732     block_t *p_block;
733     yuv_buffer yuv;
734     int i;
735
736     /* Sanity check */
737     if( p_pict->p[0].i_pitch < (int)p_sys->i_width ||
738         p_pict->p[0].i_lines < (int)p_sys->i_height )
739     {
740         msg_Warn( p_enc, "frame is smaller than encoding size"
741                   "(%ix%i->%ix%i) -> dropping frame",
742                   p_pict->p[0].i_pitch, p_pict->p[0].i_lines,
743                   p_sys->i_width, p_sys->i_height );
744         return NULL;
745     }
746
747     /* Fill padding */
748     if( p_pict->p[0].i_visible_pitch < (int)p_sys->i_width )
749     {
750         for( i = 0; i < p_sys->i_height; i++ )
751         {
752             memset( p_pict->p[0].p_pixels + i * p_pict->p[0].i_pitch +
753                     p_pict->p[0].i_visible_pitch,
754                     *( p_pict->p[0].p_pixels + i * p_pict->p[0].i_pitch +
755                        p_pict->p[0].i_visible_pitch - 1 ),
756                     p_sys->i_width - p_pict->p[0].i_visible_pitch );
757         }
758         for( i = 0; i < p_sys->i_height / 2; i++ )
759         {
760             memset( p_pict->p[1].p_pixels + i * p_pict->p[1].i_pitch +
761                     p_pict->p[1].i_visible_pitch,
762                     *( p_pict->p[1].p_pixels + i * p_pict->p[1].i_pitch +
763                        p_pict->p[1].i_visible_pitch - 1 ),
764                     p_sys->i_width / 2 - p_pict->p[1].i_visible_pitch );
765             memset( p_pict->p[2].p_pixels + i * p_pict->p[2].i_pitch +
766                     p_pict->p[2].i_visible_pitch,
767                     *( p_pict->p[2].p_pixels + i * p_pict->p[2].i_pitch +
768                        p_pict->p[2].i_visible_pitch - 1 ),
769                     p_sys->i_width / 2 - p_pict->p[2].i_visible_pitch );
770         }
771     }
772
773     if( p_pict->p[0].i_visible_lines < (int)p_sys->i_height )
774     {
775         for( i = p_pict->p[0].i_visible_lines; i < p_sys->i_height; i++ )
776         {
777             memset( p_pict->p[0].p_pixels + i * p_pict->p[0].i_pitch, 0,
778                     p_sys->i_width );
779         }
780         for( i = p_pict->p[1].i_visible_lines; i < p_sys->i_height / 2; i++ )
781         {
782             memset( p_pict->p[1].p_pixels + i * p_pict->p[1].i_pitch, 0x80,
783                     p_sys->i_width / 2 );
784             memset( p_pict->p[2].p_pixels + i * p_pict->p[2].i_pitch, 0x80,
785                     p_sys->i_width / 2 );
786         }
787     }
788
789     /* Theora is a one-frame-in, one-frame-out system. Submit a frame
790      * for compression and pull out the packet. */
791
792     yuv.y_width  = p_sys->i_width;
793     yuv.y_height = p_sys->i_height;
794     yuv.y_stride = p_pict->p[0].i_pitch;
795
796     yuv.uv_width  = p_sys->i_width / 2;
797     yuv.uv_height = p_sys->i_height / 2;
798     yuv.uv_stride = p_pict->p[1].i_pitch;
799
800     yuv.y = p_pict->p[0].p_pixels;
801     yuv.u = p_pict->p[1].p_pixels;
802     yuv.v = p_pict->p[2].p_pixels;
803
804     if( theora_encode_YUVin( &p_sys->td, &yuv ) < 0 )
805     {
806         msg_Warn( p_enc, "failed encoding a frame" );
807         return NULL;
808     }
809
810     theora_encode_packetout( &p_sys->td, 0, &oggpacket );
811
812     /* Ogg packet to block */
813     p_block = block_New( p_enc, oggpacket.bytes );
814     memcpy( p_block->p_buffer, oggpacket.packet, oggpacket.bytes );
815     p_block->i_dts = p_block->i_pts = p_pict->date;
816
817     return p_block;
818 }
819
820 /*****************************************************************************
821  * CloseEncoder: theora encoder destruction
822  *****************************************************************************/
823 static void CloseEncoder( vlc_object_t *p_this )
824 {
825     encoder_t *p_enc = (encoder_t *)p_this;
826     encoder_sys_t *p_sys = p_enc->p_sys;
827
828     theora_info_clear( &p_sys->ti );
829     theora_comment_clear( &p_sys->tc );
830
831     free( p_sys );
832 }