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