OSDN Git Service

Add metadata support to libhb, add importing of MP4 metadata, add export of MP4 metad...
[handbrake-jp/handbrake-jp-git.git] / libhb / decavcodec.c
1 /* $Id: decavcodec.c,v 1.6 2005/03/06 04:08:54 titer Exp $
2
3    This file is part of the HandBrake source code.
4    Homepage: <http://handbrake.fr/>.
5    It may be used under the terms of the GNU General Public License. */
6
7 /* This module is Handbrake's interface to the ffmpeg decoder library
8    (libavcodec & small parts of libavformat). It contains four Handbrake
9    "work objects":
10
11     decavcodec  connects HB to an ffmpeg audio decoder
12     decavcodecv connects HB to an ffmpeg video decoder
13
14         (Two different routines are needed because the ffmpeg library
15         has different decoder calling conventions for audio & video.
16         The audio decoder should have had its name changed to "decavcodeca"
17         but I got lazy.) These work objects are self-contained & follow all
18         of HB's conventions for a decoder module. They can be used like
19         any other HB decoder (deca52, decmpeg2, etc.).
20
21     decavcodecai "internal" (incestuous?) version of decavcodec
22     decavcodecvi "internal" (incestuous?) version of decavcodecv
23
24         These routine are functionally equivalent to the routines above but
25         can only be used by the ffmpeg-based stream reader in libhb/stream.c.
26         The reason they exist is because the ffmpeg library leaves some of
27         the information needed by the decoder in the AVStream (the data
28         structure used by the stream reader) and we need to retrieve it
29         to successfully decode frames. But in HB the reader and decoder
30         modules are in completely separate threads and nothing goes between
31         them but hb_buffers containing frames to be decoded. I.e., there's
32         no easy way for the ffmpeg stream reader to pass a pointer to its
33         AVStream over to the ffmpeg video or audio decoder. So the *i work
34         objects use a private back door to the stream reader to get access
35         to the AVStream (routines hb_ffmpeg_avstream and hb_ffmpeg_context)
36         and the codec_param passed to these work objects is the key to this
37         back door (it's basically an index that allows the correct AVStream
38         to be retrieved).
39
40     The normal & *i objects share a lot of code (the basic frame decoding
41     and bitstream info code is factored out into subroutines that can be
42     called by either) but the top level routines of the *i objects
43     (decavcodecviWork, decavcodecviInfo, etc.) are different because:
44      1) they *have* to use the AVCodecContext that's contained in the
45         reader's AVStream rather than just allocating & using their own,
46      2) the Info routines have access to stuff kept in the AVStream in addition
47         to stuff kept in the AVCodecContext. This shouldn't be necessary but
48         crucial information like video frame rate that should be in the
49         AVCodecContext is either missing or wrong in the version of ffmpeg
50         we're currently using.
51
52     A consequence of the above is that the non-i work objects *can't* use
53     information from the AVStream because there isn't one - they get their
54     data from either the dvd reader or the mpeg reader, not the ffmpeg stream
55     reader. That means that they have to make up for deficiencies in the
56     AVCodecContext info by using stuff kept in the HB "title" struct. It
57     also means that ffmpeg codecs that randomly scatter state needed by
58     the decoder across both the AVCodecContext & the AVStream (e.g., the
59     VC1 decoder) can't easily be used by the HB mpeg stream reader.
60  */
61
62 #include "hb.h"
63
64 #include "libavcodec/avcodec.h"
65 #include "libavformat/avformat.h"
66 #include "libswscale/swscale.h"
67
68 static int  decavcodecInit( hb_work_object_t *, hb_job_t * );
69 static int  decavcodecWork( hb_work_object_t *, hb_buffer_t **, hb_buffer_t ** );
70 static void decavcodecClose( hb_work_object_t * );
71 static int decavcodecInfo( hb_work_object_t *, hb_work_info_t * );
72 static int decavcodecBSInfo( hb_work_object_t *, const hb_buffer_t *, hb_work_info_t * );
73
74 hb_work_object_t hb_decavcodec =
75 {
76     WORK_DECAVCODEC,
77     "MPGA decoder (libavcodec)",
78     decavcodecInit,
79     decavcodecWork,
80     decavcodecClose,
81     decavcodecInfo,
82     decavcodecBSInfo
83 };
84
85 #define HEAP_SIZE 8
86 typedef struct {
87     // there are nheap items on the heap indexed 1..nheap (i.e., top of
88     // heap is 1). The 0th slot is unused - a marker is put there to check
89     // for overwrite errs.
90     int64_t h[HEAP_SIZE+1];
91     int     nheap;
92 } pts_heap_t;
93
94 struct hb_work_private_s
95 {
96     hb_job_t        *job;
97     AVCodecContext  *context;
98     AVCodecParserContext *parser;
99     hb_list_t       *list;
100     double          duration;   // frame duration (for video)
101     double          pts_next;   // next pts we expect to generate
102     int64_t         pts;        // (video) pts passing from parser to decoder
103     int64_t         chap_time;  // time of next chap mark (if new_chap != 0)
104     int             new_chap;   // output chapter mark pending
105     uint32_t        nframes;
106     uint32_t        ndrops;
107     uint32_t        decode_errors;
108     int             brokenByMicrosoft; // video stream may contain packed b-frames
109     hb_buffer_t*    delayq[HEAP_SIZE];
110     pts_heap_t      pts_heap;
111     void*           buffer;
112     struct SwsContext *sws_context; // if we have to rescale or convert color space
113 };
114
115 static int64_t heap_pop( pts_heap_t *heap )
116 {
117     int64_t result;
118
119     if ( heap->nheap <= 0 )
120     {
121         return -1;
122     }
123
124     // return the top of the heap then put the bottom element on top,
125     // decrease the heap size by one & rebalence the heap.
126     result = heap->h[1];
127
128     int64_t v = heap->h[heap->nheap--];
129     int parent = 1;
130     int child = parent << 1;
131     while ( child <= heap->nheap )
132     {
133         // find the smallest of the two children of parent
134         if (child < heap->nheap && heap->h[child] > heap->h[child+1] )
135             ++child;
136
137         if (v <= heap->h[child])
138             // new item is smaller than either child so it's the new parent.
139             break;
140
141         // smallest child is smaller than new item so move it up then
142         // check its children.
143         int64_t hp = heap->h[child];
144         heap->h[parent] = hp;
145         parent = child;
146         child = parent << 1;
147     }
148     heap->h[parent] = v;
149     return result;
150 }
151
152 static void heap_push( pts_heap_t *heap, int64_t v )
153 {
154     if ( heap->nheap < HEAP_SIZE )
155     {
156         ++heap->nheap;
157     }
158
159     // stick the new value on the bottom of the heap then bubble it
160     // up to its correct spot.
161         int child = heap->nheap;
162         while (child > 1) {
163                 int parent = child >> 1;
164                 if (heap->h[parent] <= v)
165                         break;
166                 // move parent down
167                 int64_t hp = heap->h[parent];
168                 heap->h[child] = hp;
169                 child = parent;
170         }
171         heap->h[child] = v;
172 }
173
174
175 /***********************************************************************
176  * hb_work_decavcodec_init
177  ***********************************************************************
178  *
179  **********************************************************************/
180 static int decavcodecInit( hb_work_object_t * w, hb_job_t * job )
181 {
182     AVCodec * codec;
183
184     hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) );
185     w->private_data = pv;
186
187     pv->job   = job;
188
189     int codec_id = w->codec_param;
190     /*XXX*/
191     if ( codec_id == 0 )
192         codec_id = CODEC_ID_MP2;
193
194     codec = avcodec_find_decoder( codec_id );
195     pv->parser = av_parser_init( codec_id );
196
197     pv->context = avcodec_alloc_context();
198     avcodec_open( pv->context, codec );
199
200     return 0;
201 }
202
203 /***********************************************************************
204  * Close
205  ***********************************************************************
206  *
207  **********************************************************************/
208 static void decavcodecClose( hb_work_object_t * w )
209 {
210     hb_work_private_t * pv = w->private_data;
211
212     if ( pv )
213     {
214         if ( pv->job && pv->context && pv->context->codec )
215         {
216             hb_log( "%s-decoder done: %u frames, %u decoder errors, %u drops",
217                     pv->context->codec->name, pv->nframes, pv->decode_errors,
218                     pv->ndrops );
219         }
220         if ( pv->sws_context )
221         {
222             sws_freeContext( pv->sws_context );
223         }
224         if ( pv->parser )
225         {
226             av_parser_close(pv->parser);
227         }
228         if ( pv->context && pv->context->codec )
229         {
230             avcodec_close( pv->context );
231         }
232         if ( pv->list )
233         {
234             hb_list_close( &pv->list );
235         }
236         if ( pv->buffer )
237         {
238             free( pv->buffer );
239             pv->buffer = NULL;
240         }
241         free( pv );
242         w->private_data = NULL;
243     }
244 }
245
246 /***********************************************************************
247  * Work
248  ***********************************************************************
249  *
250  **********************************************************************/
251 static int decavcodecWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
252                     hb_buffer_t ** buf_out )
253 {
254     hb_work_private_t * pv = w->private_data;
255     hb_buffer_t * in = *buf_in, * buf, * last = NULL;
256     int   pos, len, out_size, i, uncompressed_len;
257     short buffer[AVCODEC_MAX_AUDIO_FRAME_SIZE];
258     uint64_t cur;
259     unsigned char *parser_output_buffer;
260     int parser_output_buffer_len;
261
262     if ( (*buf_in)->size <= 0 )
263     {
264         /* EOF on input stream - send it downstream & say that we're done */
265         *buf_out = *buf_in;
266         *buf_in = NULL;
267         return HB_WORK_DONE;
268     }
269
270     *buf_out = NULL;
271
272     cur = ( in->start < 0 )? pv->pts_next : in->start;
273
274     pos = 0;
275     while( pos < in->size )
276     {
277         len = av_parser_parse( pv->parser, pv->context,
278                                &parser_output_buffer, &parser_output_buffer_len,
279                                in->data + pos, in->size - pos, cur, cur );
280         out_size = 0;
281         uncompressed_len = 0;
282         if (parser_output_buffer_len)
283         {
284             out_size = sizeof(buffer);
285             uncompressed_len = avcodec_decode_audio2( pv->context, buffer,
286                                                       &out_size,
287                                                       parser_output_buffer,
288                                                       parser_output_buffer_len );
289         }
290         if( out_size )
291         {
292             short * s16;
293             float * fl32;
294
295             buf = hb_buffer_init( 2 * out_size );
296
297             int sample_size_in_bytes = 2;   // Default to 2 bytes
298             switch (pv->context->sample_fmt)
299             {
300               case SAMPLE_FMT_S16:
301                 sample_size_in_bytes = 2;
302                 break;
303               /* We should handle other formats here - but that needs additional format conversion work below */
304               /* For now we'll just report the error and try to carry on */
305               default:
306                 hb_log("decavcodecWork - Unknown Sample Format from avcodec_decode_audio (%d) !", pv->context->sample_fmt);
307                 break;
308             }
309
310             buf->start = cur;
311             buf->stop  = cur + 90000 * ( out_size / (sample_size_in_bytes * pv->context->channels) ) /
312                          pv->context->sample_rate;
313             cur = buf->stop;
314
315             s16  = buffer;
316             fl32 = (float *) buf->data;
317             for( i = 0; i < out_size / 2; i++ )
318             {
319                 fl32[i] = s16[i];
320             }
321
322             if( last )
323             {
324                 last = last->next = buf;
325             }
326             else
327             {
328                 *buf_out = last = buf;
329             }
330         }
331
332         pos += len;
333     }
334
335     pv->pts_next = cur;
336
337     return HB_WORK_OK;
338 }
339
340 static int decavcodecInfo( hb_work_object_t *w, hb_work_info_t *info )
341 {
342     hb_work_private_t *pv = w->private_data;
343
344     memset( info, 0, sizeof(*info) );
345
346     if ( pv && pv->context )
347     {
348         AVCodecContext *context = pv->context;
349         info->bitrate = context->bit_rate;
350         info->rate = context->time_base.num;
351         info->rate_base = context->time_base.den;
352         info->profile = context->profile;
353         info->level = context->level;
354         return 1;
355     }
356     return 0;
357 }
358
359 static int decavcodecBSInfo( hb_work_object_t *w, const hb_buffer_t *buf,
360                              hb_work_info_t *info )
361 {
362     hb_work_private_t *pv = w->private_data;
363
364     memset( info, 0, sizeof(*info) );
365
366     if ( pv && pv->context )
367     {
368         return decavcodecInfo( w, info );
369     }
370     // XXX
371     // We should parse the bitstream to find its parameters but for right
372     // now we just return dummy values if there's a codec that will handle it.
373     AVCodec *codec = avcodec_find_decoder( w->codec_param? w->codec_param :
374                                                            CODEC_ID_MP2 );
375     if ( codec )
376     {
377         static char codec_name[64];
378
379         info->name =  strncpy( codec_name, codec->name, sizeof(codec_name)-1 );
380         info->bitrate = 384000;
381         info->rate = 48000;
382         info->rate_base = 1;
383         info->channel_layout = HB_INPUT_CH_LAYOUT_STEREO;
384         return 1;
385     }
386     return -1;
387 }
388
389 /* -------------------------------------------------------------
390  * General purpose video decoder using libavcodec
391  */
392
393 static uint8_t *copy_plane( uint8_t *dst, uint8_t* src, int dstride, int sstride,
394                             int h )
395 {
396     if ( dstride == sstride )
397     {
398         memcpy( dst, src, dstride * h );
399         return dst + dstride * h;
400     }
401     int lbytes = dstride <= sstride? dstride : sstride;
402     while ( --h >= 0 )
403     {
404         memcpy( dst, src, lbytes );
405         src += sstride;
406         dst += dstride;
407     }
408     return dst;
409 }
410
411 // copy one video frame into an HB buf. If the frame isn't in our color space
412 // or at least one of its dimensions is odd, use sws_scale to convert/rescale it.
413 // Otherwise just copy the bits.
414 static hb_buffer_t *copy_frame( hb_work_private_t *pv, AVFrame *frame )
415 {
416     AVCodecContext *context = pv->context;
417     int w, h;
418     if ( ! pv->job )
419     {
420         // if the dimensions are odd, drop the lsb since h264 requires that
421         // both width and height be even.
422         w = ( context->width >> 1 ) << 1;
423         h = ( context->height >> 1 ) << 1;
424     }
425     else
426     {
427         w =  pv->job->title->width;
428         h =  pv->job->title->height;
429     }
430     hb_buffer_t *buf = hb_video_buffer_init( w, h );
431     uint8_t *dst = buf->data;
432
433     if ( context->pix_fmt != PIX_FMT_YUV420P || w != context->width ||
434          h != context->height )
435     {
436         // have to convert to our internal color space and/or rescale
437         AVPicture dstpic;
438         avpicture_fill( &dstpic, dst, PIX_FMT_YUV420P, w, h );
439
440         if ( ! pv->sws_context )
441         {
442             pv->sws_context = sws_getContext( context->width, context->height, context->pix_fmt,
443                                               w, h, PIX_FMT_YUV420P,
444                                               SWS_LANCZOS|SWS_ACCURATE_RND,
445                                               NULL, NULL, NULL );
446         }
447         sws_scale( pv->sws_context, frame->data, frame->linesize, 0, h,
448                    dstpic.data, dstpic.linesize );
449     }
450     else
451     {
452         dst = copy_plane( dst, frame->data[0], w, frame->linesize[0], h );
453         w = (w + 1) >> 1; h = (h + 1) >> 1;
454         dst = copy_plane( dst, frame->data[1], w, frame->linesize[1], h );
455         dst = copy_plane( dst, frame->data[2], w, frame->linesize[2], h );
456     }
457     return buf;
458 }
459
460 static int get_frame_buf( AVCodecContext *context, AVFrame *frame )
461 {
462     hb_work_private_t *pv = context->opaque;
463     frame->pts = pv->pts;
464     pv->pts = -1;
465     return avcodec_default_get_buffer( context, frame );
466 }
467
468 static void log_chapter( hb_work_private_t *pv, int chap_num, int64_t pts )
469 {
470     hb_chapter_t *c = hb_list_item( pv->job->title->list_chapter, chap_num - 1 );
471     if ( c && c->title )
472     {
473         hb_log( "%s: \"%s\" (%d) at frame %u time %lld",
474                 pv->context->codec->name, c->title, chap_num, pv->nframes, pts );
475     }
476     else
477     {
478         hb_log( "%s: Chapter %d at frame %u time %lld",
479                 pv->context->codec->name, chap_num, pv->nframes, pts );
480     }
481 }
482
483 static void flushDelayQueue( hb_work_private_t *pv )
484 {
485     hb_buffer_t *buf;
486     int slot = pv->nframes & (HEAP_SIZE-1);
487
488     // flush all the video packets left on our timestamp-reordering delay q
489     while ( ( buf = pv->delayq[slot] ) != NULL )
490     {
491         buf->start = heap_pop( &pv->pts_heap );
492         hb_list_add( pv->list, buf );
493         pv->delayq[slot] = NULL;
494         slot = ( slot + 1 ) & (HEAP_SIZE-1);
495     }
496 }
497
498 static int decodeFrame( hb_work_private_t *pv, uint8_t *data, int size )
499 {
500     int got_picture;
501     AVFrame frame;
502
503     if ( avcodec_decode_video( pv->context, &frame, &got_picture, data, size ) < 0 )
504     {
505         ++pv->decode_errors;     
506     }
507     if( got_picture )
508     {
509         // ffmpeg makes it hard to attach a pts to a frame. if the MPEG ES
510         // packet had a pts we handed it to av_parser_parse (if the packet had
511         // no pts we set it to -1 but before the parse we can't distinguish between
512         // the start of a video frame with no pts & an intermediate packet of
513         // some frame which never has a pts). we hope that when parse returns
514         // the frame to us the pts we originally handed it will be in parser->pts.
515         // we put this pts into pv->pts so that when a avcodec_decode_video
516         // finally gets around to allocating an AVFrame to hold the decoded
517         // frame we can stuff that pts into the frame. if all of these relays
518         // worked at this point frame.pts should hold the frame's pts from the
519         // original data stream or -1 if it didn't have one. in the latter case
520         // we generate the next pts in sequence for it.
521         double frame_dur = pv->duration;
522         if ( frame_dur <= 0 )
523         {
524             frame_dur = 90000. * (double)pv->context->time_base.num /
525                         (double)pv->context->time_base.den;
526             pv->duration = frame_dur;
527         }
528         if ( frame.repeat_pict )
529         {
530             frame_dur += frame.repeat_pict * frame_dur * 0.5;
531         }
532         // If there was no pts for this frame, assume constant frame rate
533         // video & estimate the next frame time from the last & duration.
534         double pts = frame.pts;
535         if ( pts < 0 )
536         {
537             pts = pv->pts_next;
538         }
539         pv->pts_next = pts + frame_dur;
540
541         hb_buffer_t *buf;
542
543         // if we're doing a scan or this content couldn't have been broken
544         // by Microsoft we don't worry about timestamp reordering
545         if ( ! pv->job || ! pv->brokenByMicrosoft )
546         {
547             buf = copy_frame( pv, &frame );
548             buf->start = pts;
549             hb_list_add( pv->list, buf );
550             ++pv->nframes;
551             return got_picture;
552         }
553
554         // XXX This following probably addresses a libavcodec bug but I don't
555         //     see an easy fix so we workaround it here.
556         //
557         // The M$ 'packed B-frames' atrocity results in decoded frames with
558         // the wrong timestamp. E.g., if there are 2 b-frames the timestamps
559         // we see here will be "2 3 1 5 6 4 ..." instead of "1 2 3 4 5 6".
560         // The frames are actually delivered in the right order but with
561         // the wrong timestamp. To get the correct timestamp attached to
562         // each frame we have a delay queue (longer than the max number of
563         // b-frames) & a sorting heap for the timestamps. As each frame
564         // comes out of the decoder the oldest frame in the queue is removed
565         // and associated with the smallest timestamp. Then the new frame is
566         // added to the queue & its timestamp is pushed on the heap.
567         // This does nothing if the timestamps are correct (i.e., the video
568         // uses a codec that Micro$oft hasn't broken yet) but the frames
569         // get timestamped correctly even when M$ has munged them.
570
571         // remove the oldest picture from the frame queue (if any) &
572         // give it the smallest timestamp from our heap. The queue size
573         // is a power of two so we get the slot of the oldest by masking
574         // the frame count & this will become the slot of the newest
575         // once we've removed & processed the oldest.
576         int slot = pv->nframes & (HEAP_SIZE-1);
577         if ( ( buf = pv->delayq[slot] ) != NULL )
578         {
579             buf->start = heap_pop( &pv->pts_heap );
580
581             if ( pv->new_chap && buf->start >= pv->chap_time )
582             {
583                 buf->new_chap = pv->new_chap;
584                 pv->new_chap = 0;
585                 pv->chap_time = 0;
586                 log_chapter( pv, buf->new_chap, buf->start );
587             }
588             else if ( pv->nframes == 0 )
589             {
590                 log_chapter( pv, pv->job->chapter_start, buf->start );
591             }
592             hb_list_add( pv->list, buf );
593         }
594
595         // add the new frame to the delayq & push its timestamp on the heap
596         pv->delayq[slot] = copy_frame( pv, &frame );
597         heap_push( &pv->pts_heap, pts );
598
599         ++pv->nframes;
600     }
601
602     return got_picture;
603 }
604
605 static void decodeVideo( hb_work_private_t *pv, uint8_t *data, int size,
606                          int64_t pts, int64_t dts )
607 {
608     /*
609      * The following loop is a do..while because we need to handle both
610      * data & the flush at the end (signaled by size=0). At the end there's
611      * generally a frame in the parser & one or more frames in the decoder
612      * (depending on the bframes setting).
613      */
614     int pos = 0;
615     do {
616         uint8_t *pout;
617         int pout_len;
618         int len = av_parser_parse( pv->parser, pv->context, &pout, &pout_len,
619                                    data + pos, size - pos, pts, dts );
620         pos += len;
621
622         if ( pout_len > 0 )
623         {
624             pv->pts = pv->parser->pts;
625             decodeFrame( pv, pout, pout_len );
626         }
627     } while ( pos < size );
628
629     /* the stuff above flushed the parser, now flush the decoder */
630     if ( size <= 0 )
631     {
632         while ( decodeFrame( pv, NULL, 0 ) )
633         {
634         }
635         flushDelayQueue( pv );
636     }
637 }
638
639 static hb_buffer_t *link_buf_list( hb_work_private_t *pv )
640 {
641     hb_buffer_t *head = hb_list_item( pv->list, 0 );
642
643     if ( head )
644     {
645         hb_list_rem( pv->list, head );
646
647         hb_buffer_t *last = head, *buf;
648
649         while ( ( buf = hb_list_item( pv->list, 0 ) ) != NULL )
650         {
651             hb_list_rem( pv->list, buf );
652             last->next = buf;
653             last = buf;
654         }
655     }
656     return head;
657 }
658
659
660 static int decavcodecvInit( hb_work_object_t * w, hb_job_t * job )
661 {
662
663     hb_work_private_t *pv = calloc( 1, sizeof( hb_work_private_t ) );
664     w->private_data = pv;
665     pv->job   = job;
666     pv->list = hb_list_init();
667
668     int codec_id = w->codec_param;
669     pv->parser = av_parser_init( codec_id );
670     pv->context = avcodec_alloc_context2( CODEC_TYPE_VIDEO );
671
672     /* we have to wrap ffmpeg's get_buffer to be able to set the pts (?!) */
673     pv->context->opaque = pv;
674     pv->context->get_buffer = get_frame_buf;
675
676     AVCodec *codec = avcodec_find_decoder( codec_id );
677
678     // we can't call the avstream funcs but the read_header func in the
679     // AVInputFormat may set up some state in the AVContext. In particular 
680     // vc1t_read_header allocates 'extradata' to deal with header issues
681     // related to Microsoft's bizarre engineering notions. We alloc a chunk
682     // of space to make vc1 work then associate the codec with the context.
683     pv->context->extradata_size = 32;
684     pv->context->extradata = av_malloc(pv->context->extradata_size);
685     avcodec_open( pv->context, codec );
686
687     return 0;
688 }
689
690 static int decavcodecvWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
691                             hb_buffer_t ** buf_out )
692 {
693     hb_work_private_t *pv = w->private_data;
694     hb_buffer_t *in = *buf_in;
695     int64_t pts = AV_NOPTS_VALUE;
696     int64_t dts = pts;
697
698     *buf_in = NULL;
699
700     /* if we got an empty buffer signaling end-of-stream send it downstream */
701     if ( in->size == 0 )
702     {
703         decodeVideo( pv, in->data, in->size, pts, dts );
704         hb_list_add( pv->list, in );
705         *buf_out = link_buf_list( pv );
706         return HB_WORK_DONE;
707     }
708
709     if( in->start >= 0 )
710     {
711         pts = in->start;
712         dts = in->renderOffset;
713     }
714     if ( in->new_chap )
715     {
716         pv->new_chap = in->new_chap;
717         pv->chap_time = pts >= 0? pts : pv->pts_next;
718     }
719     decodeVideo( pv, in->data, in->size, pts, dts );
720     hb_buffer_close( &in );
721     *buf_out = link_buf_list( pv );
722     return HB_WORK_OK;
723 }
724
725 static int decavcodecvInfo( hb_work_object_t *w, hb_work_info_t *info )
726 {
727     hb_work_private_t *pv = w->private_data;
728
729     memset( info, 0, sizeof(*info) );
730
731     if ( pv && pv->context )
732     {
733         AVCodecContext *context = pv->context;
734         info->bitrate = context->bit_rate;
735         info->width = context->width;
736         info->height = context->height;
737
738         /* ffmpeg gives the frame rate in frames per second while HB wants
739          * it in units of the 27MHz MPEG clock. */
740         info->rate = 27000000;
741         info->rate_base = (int64_t)context->time_base.num * 27000000LL /
742                           context->time_base.den;
743         
744         /* Sometimes there's no pixel aspect set in the source. In that case,
745            assume a 1:1 PAR. Otherwise, preserve the source PAR.             */
746         info->pixel_aspect_width = context->sample_aspect_ratio.num ?
747                                         context->sample_aspect_ratio.num : 1;
748         info->pixel_aspect_height = context->sample_aspect_ratio.den ?
749                                         context->sample_aspect_ratio.den : 1;
750
751         /* ffmpeg returns the Pixel Aspect Ratio (PAR). Handbrake wants the
752          * Display Aspect Ratio so we convert by scaling by the Storage
753          * Aspect Ratio (w/h). We do the calc in floating point to get the
754          * rounding right. */
755         info->aspect = (double)info->pixel_aspect_width * 
756                        (double)context->width /
757                        (double)info->pixel_aspect_height /
758                        (double)context->height;
759
760         info->profile = context->profile;
761         info->level = context->level;
762         info->name = context->codec->name;
763         return 1;
764     }
765     return 0;
766 }
767
768 static int decavcodecvBSInfo( hb_work_object_t *w, const hb_buffer_t *buf,
769                              hb_work_info_t *info )
770 {
771     return 0;
772 }
773
774 hb_work_object_t hb_decavcodecv =
775 {
776     WORK_DECAVCODECV,
777     "Video decoder (libavcodec)",
778     decavcodecvInit,
779     decavcodecvWork,
780     decavcodecClose,
781     decavcodecvInfo,
782     decavcodecvBSInfo
783 };
784
785
786 // This is a special decoder for ffmpeg streams. The ffmpeg stream reader
787 // includes a parser and passes information from the parser to the decoder
788 // via a codec context kept in the AVStream of the reader's AVFormatContext.
789 // We *have* to use that codec context to decode the stream or we'll get
790 // garbage. ffmpeg_title_scan put a cookie that can be used to get to that
791 // codec context in our codec_param.
792
793 // this routine gets the appropriate context pointer from the ffmpeg
794 // stream reader. it can't be called until we get the first buffer because
795 // we can't guarantee that reader will be called before the our init
796 // routine and if our init is called first we'll get a pointer to the
797 // old scan stream (which has already been closed).
798 static void init_ffmpeg_context( hb_work_object_t *w )
799 {
800     hb_work_private_t *pv = w->private_data;
801     pv->context = hb_ffmpeg_context( w->codec_param );
802
803     // during scan the decoder gets closed & reopened which will
804     // close the codec so reopen it if it's not there
805     if ( ! pv->context->codec )
806     {
807         AVCodec *codec = avcodec_find_decoder( pv->context->codec_id );
808         avcodec_open( pv->context, codec );
809     }
810     // set up our best guess at the frame duration.
811     // the frame rate in the codec is usually bogus but it's sometimes
812     // ok in the stream.
813     AVStream *st = hb_ffmpeg_avstream( w->codec_param );
814
815     if ( st->nb_frames && st->duration )
816     {
817         // compute the average frame duration from the total number
818         // of frames & the total duration.
819         pv->duration = ( (double)st->duration * (double)st->time_base.num ) /
820                        ( (double)st->nb_frames * (double)st->time_base.den );
821     }
822     else
823     {
824         // XXX We don't have a frame count or duration so try to use the
825         // far less reliable time base info in the stream.
826         // Because the time bases are so screwed up, we only take values
827         // in the range 8fps - 64fps.
828         AVRational tb;
829         if ( st->time_base.num * 64 > st->time_base.den &&
830              st->time_base.den > st->time_base.num * 8 )
831         {
832             tb = st->time_base;
833         }
834         else if ( st->r_frame_rate.den * 64 > st->r_frame_rate.num &&
835                   st->r_frame_rate.num > st->r_frame_rate.den * 8 )
836         {
837             tb.num = st->r_frame_rate.den;
838             tb.den = st->r_frame_rate.num;
839         }
840         else
841         {
842             tb.num = 1001;  /*XXX*/
843             tb.den = 24000; /*XXX*/
844         }
845         pv->duration =  (double)tb.num / (double)tb.den;
846     }
847     pv->duration *= 90000.;
848
849     // we have to wrap ffmpeg's get_buffer to be able to set the pts (?!)
850     pv->context->opaque = pv;
851     pv->context->get_buffer = get_frame_buf;
852
853     // avi, mkv and possibly mp4 containers can contain the M$ VFW packed
854     // b-frames abortion that messes up frame ordering and timestamps.
855     // XXX ffmpeg knows which streams are broken but doesn't expose the
856     //     info externally. We should patch ffmpeg to add a flag to the
857     //     codec context for this but until then we mark all ffmpeg streams
858     //     as suspicious.
859     pv->brokenByMicrosoft = 1;
860 }
861
862 static void prepare_ffmpeg_buffer( hb_buffer_t * in )
863 {
864     // ffmpeg requires an extra 8 bytes of zero at the end of the buffer and
865     // will seg fault in odd, data dependent ways if it's not there. (my guess
866     // is this is a case of a local performance optimization creating a global
867     // performance degradation since all the time wasted by extraneous data
868     // copies & memory zeroing has to be huge compared to the minor reduction
869     // in inner-loop instructions this affords - modern cpus bottleneck on
870     // memory bandwidth not instruction bandwidth).
871     if ( in->size + FF_INPUT_BUFFER_PADDING_SIZE > in->alloc )
872     {
873         // have to realloc to add the padding
874         hb_buffer_realloc( in, in->size + FF_INPUT_BUFFER_PADDING_SIZE );
875     }
876     memset( in->data + in->size, 0, FF_INPUT_BUFFER_PADDING_SIZE );
877 }
878
879 static int decavcodecviInit( hb_work_object_t * w, hb_job_t * job )
880 {
881
882     hb_work_private_t *pv = calloc( 1, sizeof( hb_work_private_t ) );
883     w->private_data = pv;
884     pv->job   = job;
885     pv->list = hb_list_init();
886     pv->pts_next = -1;
887     pv->pts = -1;
888     return 0;
889 }
890
891 static int decavcodecviWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
892                              hb_buffer_t ** buf_out )
893 {
894     hb_work_private_t *pv = w->private_data;
895     if ( ! pv->context )
896     {
897         init_ffmpeg_context( w );
898     }
899     hb_buffer_t *in = *buf_in;
900     *buf_in = NULL;
901
902     /* if we got an empty buffer signaling end-of-stream send it downstream */
903     if ( in->size == 0 )
904     {
905         /* flush any frames left in the decoder */
906         while ( decodeFrame( pv, NULL, 0 ) )
907         {
908         }
909         flushDelayQueue( pv );
910         hb_list_add( pv->list, in );
911         *buf_out = link_buf_list( pv );
912         return HB_WORK_DONE;
913     }
914
915     int64_t pts = in->start;
916     if( pts >= 0 )
917     {
918         // use the first timestamp as our 'next expected' pts
919         if ( pv->pts_next < 0 )
920         {
921             pv->pts_next = pts;
922         }
923         pv->pts = pts;
924     }
925
926     if ( in->new_chap )
927     {
928         pv->new_chap = in->new_chap;
929         pv->chap_time = pts >= 0? pts : pv->pts_next;
930     }
931     prepare_ffmpeg_buffer( in );
932     decodeFrame( pv, in->data, in->size );
933     hb_buffer_close( &in );
934     *buf_out = link_buf_list( pv );
935     return HB_WORK_OK;
936 }
937
938 static int decavcodecviInfo( hb_work_object_t *w, hb_work_info_t *info )
939 {
940     if ( decavcodecvInfo( w, info ) )
941     {
942         hb_work_private_t *pv = w->private_data;
943         if ( ! pv->context )
944         {
945             init_ffmpeg_context( w );
946         }
947         // we have the frame duration in units of the 90KHz pts clock but
948         // need it in units of the 27MHz MPEG clock. */
949         info->rate = 27000000;
950         info->rate_base = pv->duration * 300.;
951         return 1;
952     }
953     return 0;
954 }
955
956 static void decodeAudio( hb_work_private_t *pv, uint8_t *data, int size )
957 {
958     AVCodecContext *context = pv->context;
959     int pos = 0;
960
961     while ( pos < size )
962     {
963         int16_t *buffer = pv->buffer;
964         if ( buffer == NULL )
965         {
966             // XXX ffmpeg bug workaround
967             // malloc a buffer for the audio decode. On an x86, ffmpeg
968             // uses mmx/sse instructions on this buffer without checking
969             // that it's 16 byte aligned and this will cause an abort if
970             // the buffer is allocated on our stack. Rather than doing
971             // complicated, machine dependent alignment here we use the
972             // fact that malloc returns an aligned pointer on most architectures.
973             pv->buffer = malloc( AVCODEC_MAX_AUDIO_FRAME_SIZE );
974             buffer = pv->buffer;
975         }
976         int out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
977         int len = avcodec_decode_audio2( context, buffer, &out_size,
978                                          data + pos, size - pos );
979         if ( len <= 0 )
980         {
981             return;
982         }
983         pos += len;
984         if( out_size > 0 )
985         {
986             hb_buffer_t *buf = hb_buffer_init( 2 * out_size );
987
988             // convert from bytes to total samples
989             out_size >>= 1;
990
991             double pts = pv->pts_next;
992             buf->start = pts;
993             pts += out_size * pv->duration;
994             buf->stop  = pts;
995             pv->pts_next = pts;
996
997             float *fl32 = (float *)buf->data;
998             int i;
999             for( i = 0; i < out_size; ++i )
1000             {
1001                 fl32[i] = buffer[i];
1002             }
1003             hb_list_add( pv->list, buf );
1004         }
1005     }
1006 }
1007
1008 static int decavcodecaiWork( hb_work_object_t *w, hb_buffer_t **buf_in,
1009                     hb_buffer_t **buf_out )
1010 {
1011     if ( (*buf_in)->size <= 0 )
1012     {
1013         /* EOF on input stream - send it downstream & say that we're done */
1014         *buf_out = *buf_in;
1015         *buf_in = NULL;
1016         return HB_WORK_DONE;
1017     }
1018
1019     hb_work_private_t *pv = w->private_data;
1020     if ( ! pv->context )
1021     {
1022         init_ffmpeg_context( w );
1023         // duration is a scaling factor to go from #bytes in the decoded
1024         // frame to frame time (in 90KHz mpeg ticks). 'channels' converts
1025         // total samples to per-channel samples. 'sample_rate' converts
1026         // per-channel samples to seconds per sample and the 90000
1027         // is mpeg ticks per second.
1028         pv->duration = 90000. /
1029                     (double)( pv->context->sample_rate * pv->context->channels );
1030     }
1031     hb_buffer_t *in = *buf_in;
1032
1033     // if the packet has a timestamp use it if we don't have a timestamp yet
1034     // or if there's been a timing discontinuity of more than 100ms.
1035     if ( in->start >= 0 &&
1036          ( pv->pts_next < 0 || ( in->start - pv->pts_next ) > 90*100 ) )
1037     {
1038         pv->pts_next = in->start;
1039     }
1040     prepare_ffmpeg_buffer( in );
1041     decodeAudio( pv, in->data, in->size );
1042     *buf_out = link_buf_list( pv );
1043
1044     return HB_WORK_OK;
1045 }
1046
1047 hb_work_object_t hb_decavcodecvi =
1048 {
1049     WORK_DECAVCODECVI,
1050     "Video decoder (ffmpeg streams)",
1051     decavcodecviInit,
1052     decavcodecviWork,
1053     decavcodecClose,
1054     decavcodecviInfo,
1055     decavcodecvBSInfo
1056 };
1057
1058 hb_work_object_t hb_decavcodecai =
1059 {
1060     WORK_DECAVCODECAI,
1061     "Audio decoder (ffmpeg streams)",
1062     decavcodecviInit,
1063     decavcodecaiWork,
1064     decavcodecClose,
1065     decavcodecInfo,
1066     decavcodecBSInfo
1067 };