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