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