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