OSDN Git Service

HD Home Run seems to strip the PCR from some streams (which makes HB refuse to proces...
[handbrake-jp/handbrake-jp-git.git] / libhb / stream.c
1 /* $Id$
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 #include <string.h>
8 #include <ctype.h>
9 #include <errno.h>
10
11 #include "hb.h"
12 #include "lang.h"
13 #include "a52dec/a52.h"
14 #include "libavcodec/avcodec.h"
15 #include "libavformat/avformat.h"
16
17 #define min(a, b) a < b ? a : b
18
19 /*
20  * This table defines how ISO MPEG stream type codes map to HandBrake
21  * codecs. It is indexed by the 8 bit stream type and contains the codec
22  * worker object id and a parameter for that worker proc (ignored except
23  * for the ffmpeg-based codecs in which case it is the ffmpeg codec id).
24  *
25  * Entries with a worker proc id of 0 or a kind of 'U' indicate that HB
26  * doesn't handle the stream type.
27  */
28 typedef struct {
29     enum { U, A, V } kind; /* unknown / audio / video */
30     int codec;          /* HB worker object id of codec */
31     int codec_param;    /* param for codec (usually ffmpeg codec id) */
32     const char* name;   /* description of type */
33 } stream2codec_t;
34
35 #define st(id, kind, codec, codec_param, name) \
36  [id] = { kind, codec, codec_param, name }
37
38 static const stream2codec_t st2codec[256] = {
39     st(0x01, V, WORK_DECMPEG2,     0,              "MPEG1"),
40     st(0x02, V, WORK_DECMPEG2,     0,              "MPEG2"),
41     st(0x03, A, HB_ACODEC_MPGA,    CODEC_ID_MP2,   "MPEG1"),
42     st(0x04, A, HB_ACODEC_MPGA,    CODEC_ID_MP2,   "MPEG2"),
43     st(0x05, U, 0,                 0,              "ISO 13818-1 private section"),
44     st(0x06, U, 0,                 0,              "ISO 13818-1 PES private data"),
45     st(0x07, U, 0,                 0,              "ISO 13522 MHEG"),
46     st(0x08, U, 0,                 0,              "ISO 13818-1 DSM-CC"),
47     st(0x09, U, 0,                 0,              "ISO 13818-1 auxiliary"),
48     st(0x0a, U, 0,                 0,              "ISO 13818-6 encap"),
49     st(0x0b, U, 0,                 0,              "ISO 13818-6 DSM-CC U-N msgs"),
50     st(0x0c, U, 0,                 0,              "ISO 13818-6 Stream descriptors"),
51     st(0x0d, U, 0,                 0,              "ISO 13818-6 Sections"),
52     st(0x0e, U, 0,                 0,              "ISO 13818-1 auxiliary"),
53     st(0x0f, A, HB_ACODEC_MPGA,    CODEC_ID_AAC,   "ISO 13818-7 AAC Audio"),
54     st(0x10, V, WORK_DECAVCODECV,  CODEC_ID_MPEG4, "MPEG4"),
55     st(0x11, A, HB_ACODEC_MPGA,    CODEC_ID_AAC_LATM, "MPEG4 LATM AAC"),
56     st(0x12, U, 0,                 0,              "MPEG4 generic"),
57
58     st(0x14, U, 0,                 0,              "ISO 13818-6 DSM-CC download"),
59
60     st(0x1b, V, WORK_DECAVCODECV,  CODEC_ID_H264,  "H.264"),
61
62     st(0x80, U, 0,                 0,              "DigiCipher II Video"),
63     st(0x81, A, HB_ACODEC_AC3,     0,              "AC-3"),
64     st(0x82, A, HB_ACODEC_MPGA,    CODEC_ID_DTS,   "HDMV DTS"),
65     st(0x83, A, HB_ACODEC_LPCM,    0,              "LPCM"),
66     st(0x84, A, 0,                 0,              "SDDS"),
67     st(0x85, U, 0,                 0,              "ATSC Program ID"),
68     st(0x86, U, 0,                 0,              "SCTE 35 splice info"),
69     st(0x87, A, 0,                 0,              "E-AC-3"),
70
71     st(0x8a, A, HB_ACODEC_DCA,     0,              "DTS"),
72
73     st(0x91, A, HB_ACODEC_AC3,     0,              "AC-3"),
74     st(0x92, U, 0,                 0,              "Subtitle"),
75
76     st(0x94, A, 0,                 0,              "SDDS"),
77     st(0xa0, V, 0,                 0,              "MSCODEC"),
78
79     st(0xea, V, WORK_DECAVCODECV,  CODEC_ID_VC1,   "VC1"),
80 };
81 #undef st
82
83 typedef enum {
84     hb_stream_type_unknown = 0,
85     transport,
86     program,
87     dvd_program,
88     ffmpeg
89 } hb_stream_type_t;
90
91 #define kMaxNumberVideoPIDS 1
92 #define kMaxNumberAudioPIDS 15
93 #define kMaxNumberDecodeStreams (kMaxNumberVideoPIDS+kMaxNumberAudioPIDS)
94 #define kMaxNumberPMTStreams 32
95
96
97 struct hb_stream_s
98 {
99     int     frames;             /* video frames so far */
100     int     errors;             /* total errors so far */
101     int     last_error_frame;   /* frame # at last error message */
102     int     last_error_count;   /* # errors at last error message */
103     int     packetsize;         /* Transport Stream packet size */
104
105     int64_t ts_lastpcr;         /* the last pcr we found in the TS stream */
106     int64_t ts_nextpcr;         /* the next pcr to put in a PS packet */
107
108     uint8_t *ts_packet;         /* buffer for one TS packet */
109     uint8_t *ts_buf[kMaxNumberDecodeStreams];
110     int     ts_pos[kMaxNumberDecodeStreams];
111     int8_t  ts_foundfirst[kMaxNumberDecodeStreams];
112     int8_t  ts_skipbad[kMaxNumberDecodeStreams];
113     int8_t  ts_streamcont[kMaxNumberDecodeStreams];
114     int8_t  ts_start[kMaxNumberDecodeStreams];
115
116     uint8_t *fwrite_buf;        /* PS buffer (set by hb_ts_stream_decode) */
117     uint8_t *fwrite_buf_orig;   /* PS buffer start (set by hb_ts_stream_decode) */
118
119     /*
120      * Stuff before this point is dynamic state updated as we read the
121      * stream. Stuff after this point is stream description state that
122      * we learn during the initial scan but cache so it can be
123      * reused during the conversion read.
124      */
125     uint8_t ts_number_video_pids;
126     uint8_t ts_number_audio_pids;
127
128     int16_t ts_video_pids[kMaxNumberVideoPIDS];
129     int16_t ts_audio_pids[kMaxNumberAudioPIDS];
130
131     uint8_t ts_streamid[kMaxNumberDecodeStreams];
132     uint8_t ts_stream_type[kMaxNumberDecodeStreams];
133
134     char    *path;
135     FILE    *file_handle;
136     hb_stream_type_t hb_stream_type;
137     hb_title_t *title;
138
139     AVFormatContext *ffmpeg_ic;
140     AVPacket *ffmpeg_pkt;
141     double ffmpeg_tsconv[MAX_STREAMS];
142
143     struct {
144         int lang_code;
145         int flags;
146         int rate;
147         int bitrate;
148     } a52_info[kMaxNumberAudioPIDS];
149
150     struct
151     {
152         unsigned short program_number;
153         unsigned short program_map_PID;
154     } pat_info[kMaxNumberPMTStreams];
155     int     ts_number_pat_entries;
156
157     struct
158     {
159         int reading;
160         unsigned char *tablebuf;
161         unsigned int tablepos;
162         unsigned char current_continuity_counter;
163
164         int section_length;
165         int program_number;
166         unsigned int PCR_PID;
167         int program_info_length;
168         unsigned char *progam_info_descriptor_data;
169         struct
170         {
171             unsigned char stream_type;
172             unsigned short elementary_PID;
173             unsigned short ES_info_length;
174             unsigned char *es_info_descriptor_data;
175         } pmt_stream_info[kMaxNumberPMTStreams];
176     } pmt_info;
177 };
178
179 /***********************************************************************
180  * Local prototypes
181  **********************************************************************/
182 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle);
183 static void hb_ts_stream_init(hb_stream_t *stream);
184 static void hb_ts_stream_find_pids(hb_stream_t *stream);
185 static int hb_ts_stream_decode(hb_stream_t *stream, uint8_t *obuf);
186 static void hb_ts_stream_reset(hb_stream_t *stream);
187 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
188                                                        int aud_pid_index);
189 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title);
190 static off_t align_to_next_packet(hb_stream_t *stream);
191
192 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title );
193 static void ffmpeg_close( hb_stream_t *d );
194 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream );
195 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf );
196 static int ffmpeg_seek( hb_stream_t *stream, float frac );
197
198 /*
199  * streams have a bunch of state that's learned during the scan. We don't
200  * want to throw away the state when scan does a close then relearn
201  * everything when reader does an open. So we save the stream state on
202  * the close following a scan and reuse it when 'reader' does an open.
203  */
204 static hb_list_t *stream_state_list;
205
206 static hb_stream_t *hb_stream_lookup( const char *path )
207 {
208     if ( stream_state_list == NULL )
209         return NULL;
210
211     hb_stream_t *ss;
212     int i = 0;
213
214     while ( ( ss = hb_list_item( stream_state_list, i++ ) ) != NULL )
215     {
216         if ( strcmp( path, ss->path ) == 0 )
217         {
218             break;
219         }
220     }
221     return ss;
222 }
223
224 static void hb_stream_state_delete( hb_stream_t *ss )
225 {
226     hb_list_rem( stream_state_list, ss );
227     free( ss->path );
228     free( ss );
229 }
230
231 /*
232  * logging routines.
233  * these frontend hb_log because transport streams can have a lot of errors
234  * so we want to rate limit messages. this routine limits the number of
235  * messages to at most one per minute of video. other errors that occur
236  * during the minute are counted & the count is output with the next
237  * error msg we print.
238  */
239 static void ts_warn_helper( hb_stream_t *stream, char *log, va_list args )
240 {
241     // limit error printing to at most one per minute of video (at 30fps)
242     ++stream->errors;
243     if ( stream->frames - stream->last_error_frame >= 30*60 )
244     {
245         char msg[256];
246
247         vsnprintf( msg, sizeof(msg), log, args );
248
249         if ( stream->errors - stream->last_error_count < 10 )
250         {
251             hb_log( "stream: error near frame %d: %s", stream->frames, msg );
252         }
253         else
254         {
255             int Edelta = stream->errors - stream->last_error_count;
256             double Epcnt = (double)Edelta * 100. /
257                             (stream->frames - stream->last_error_frame);
258             hb_log( "stream: %d new errors (%.0f%%) up to frame %d: %s",
259                     Edelta, Epcnt, stream->frames, msg );
260         }
261         stream->last_error_frame = stream->frames;
262         stream->last_error_count = stream->errors;
263     }
264 }
265
266 static void ts_warn( hb_stream_t *stream, char *log, ... )
267 {
268     va_list     args;
269     va_start( args, log );
270     ts_warn_helper( stream, log, args );
271     va_end( args );
272 }
273
274 static void ts_err( hb_stream_t *stream, int curstream, char *log, ... )
275 {
276     va_list     args;
277     va_start( args, log );
278     ts_warn_helper( stream, log, args );
279     va_end( args );
280
281     stream->ts_skipbad[curstream] = 1;
282     stream->ts_pos[curstream] = 0;
283     stream->ts_streamcont[curstream] = -1;
284 }
285
286 static int check_ps_sync(const uint8_t *buf)
287 {
288     // a legal MPEG program stream must start with a Pack header in the
289     // first four bytes.
290     return (buf[0] == 0x00) && (buf[1] == 0x00) &&
291            (buf[2] == 0x01) && (buf[3] == 0xba);
292 }
293
294 static int check_ps_sys(const uint8_t *buf)
295 {
296     // a legal MPEG program stream must start with a Pack followed by a
297     // SYS. If we've already verified the pack, this skips over it and checks
298     // for the sys header.
299     int pos = 14 + ( buf[13] & 0x7 );   // skip over the PACK
300     return (buf[pos+0] == 0x00) && (buf[pos+1] == 0x00) &&
301            (buf[pos+2] == 0x01) && (buf[pos+3] == 0xbb);
302 }
303
304 static int check_ts_sync(const uint8_t *buf)
305 {
306     // must have initial sync byte, no scrambling & a legal adaptation ctrl
307     return (buf[0] == 0x47) && ((buf[3] >> 6) == 0) && ((buf[3] >> 4) > 0);
308 }
309
310 static int have_ts_sync(const uint8_t *buf, int psize)
311 {
312     return check_ts_sync(&buf[0*psize]) && check_ts_sync(&buf[1*psize]) &&
313            check_ts_sync(&buf[2*psize]) && check_ts_sync(&buf[3*psize]) &&
314            check_ts_sync(&buf[4*psize]) && check_ts_sync(&buf[5*psize]) &&
315            check_ts_sync(&buf[6*psize]) && check_ts_sync(&buf[7*psize]);
316 }
317
318 static int hb_stream_check_for_ts(const uint8_t *buf)
319 {
320     // transport streams should have a sync byte every 188 bytes.
321     // search the first 8KB of buf looking for at least 8 consecutive
322     // correctly located sync patterns.
323     int offset = 0;
324
325     for ( offset = 0; offset < 8*1024-8*188; ++offset )
326     {
327         if ( have_ts_sync( &buf[offset], 188) )
328             return 188 | (offset << 8);
329         if ( have_ts_sync( &buf[offset], 192) )
330             return 192 | (offset << 8);
331         if ( have_ts_sync( &buf[offset], 204) )
332             return 204 | (offset << 8);
333         if ( have_ts_sync( &buf[offset], 208) )
334             return 208 | (offset << 8);
335     }
336     return 0;
337 }
338
339 static int hb_stream_check_for_ps(const uint8_t *buf)
340 {
341     // program streams should start with a PACK then a SYS header.
342     return check_ps_sync(buf) && check_ps_sys(buf);
343 }
344
345 static int hb_stream_check_for_dvd_ps(const uint8_t *buf)
346 {
347     // DVD program streams should have a Pack header every 2048 bytes.
348     // check that we have 4 of these in a row.
349     return check_ps_sync(&buf[0*2048]) && check_ps_sync(&buf[1*2048]) &&
350            check_ps_sync(&buf[2*2048]) && check_ps_sync(&buf[3*2048]);
351 }
352
353 static int hb_stream_get_type(hb_stream_t *stream)
354 {
355     uint8_t buf[2048*4];
356
357     if ( fread(buf, 1, sizeof(buf), stream->file_handle) == sizeof(buf) )
358     {
359         int psize;
360         if ( ( psize = hb_stream_check_for_ts(buf) ) != 0 )
361         {
362             int offset = psize >> 8;
363             psize &= 0xff;
364             hb_log("file is MPEG Transport Stream with %d byte packets"
365                    " offset %d bytes", psize, offset);
366             stream->packetsize = psize;
367             stream->hb_stream_type = transport;
368             hb_ts_stream_init(stream);
369             return 1;
370         }
371         if ( hb_stream_check_for_dvd_ps(buf) != 0 )
372         {
373             hb_log("file is MPEG DVD Program Stream");
374             stream->hb_stream_type = dvd_program;
375             return 1;
376         }
377         if ( hb_stream_check_for_ps(buf) != 0 )
378         {
379             hb_log("file is MPEG Program Stream");
380             stream->hb_stream_type = program;
381             return 1;
382         }
383     }
384     return 0;
385 }
386
387 static void hb_stream_delete_dynamic( hb_stream_t *d )
388 {
389     if( d->file_handle )
390     {
391         fclose( d->file_handle );
392                 d->file_handle = NULL;
393     }
394
395         int i=0;
396
397     if ( d->ts_packet )
398     {
399         free( d->ts_packet );
400         d->ts_packet = NULL;
401     }
402         for (i = 0; i < kMaxNumberDecodeStreams; i++)
403         {
404                 if (d->ts_buf[i])
405                 {
406                         free(d->ts_buf[i]);
407                         d->ts_buf[i] = NULL;
408                 }
409         }
410 }
411
412 static void hb_stream_delete( hb_stream_t *d )
413 {
414     hb_stream_delete_dynamic( d );
415     free( d->path );
416     free( d );
417 }
418
419 /***********************************************************************
420  * hb_stream_open
421  ***********************************************************************
422  *
423  **********************************************************************/
424 hb_stream_t * hb_stream_open( char *path, hb_title_t *title )
425 {
426     FILE *f = fopen( path, "r" );
427     if ( f == NULL )
428     {
429         hb_log( "hb_stream_open: open %s failed", path );
430         return NULL;
431     }
432
433     hb_stream_t *d = calloc( sizeof( hb_stream_t ), 1 );
434     if ( d == NULL )
435     {
436         fclose( f );
437         hb_log( "hb_stream_open: can't allocate space for %s stream state", path );
438         return NULL;
439     }
440
441     /*
442      * if we're opening the stream to read & convert, we need
443      * the state we saved when we scanned the stream. if we're
444      * opening the stream to scan it we want to rebuild the state
445      * (even if we have saved state, the stream may have changed).
446      */
447     hb_stream_t *ss = hb_stream_lookup( path );
448     if ( title && ss && ss->hb_stream_type != ffmpeg )
449     {
450         /*
451          * copy the saved state since we might be encoding the same stream
452          * multiple times.
453          */
454         memcpy( d, ss, sizeof(*d) );
455         d->file_handle = f;
456         d->title = title;
457         d->path = strdup( path );
458
459         if ( d->hb_stream_type == transport )
460         {
461             d->ts_packet = malloc( d->packetsize );
462
463             int i = 0;
464             for ( ; i < d->ts_number_video_pids + d->ts_number_audio_pids; i++)
465             {
466                 d->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
467             }
468             hb_stream_seek( d, 0. );
469         }
470         return d;
471     }
472
473     /*
474      * opening for scan - delete any saved state then (re)scan the stream.
475      * If it's something we can deal with (MPEG2 PS or TS) return a stream
476      * reference structure & null otherwise.
477      */
478     if ( ss != NULL )
479     {
480         hb_stream_state_delete( ss );
481     }
482     d->file_handle = f;
483     d->title = title;
484     d->path = strdup( path );
485     if (d->path != NULL )
486     {
487         if ( hb_stream_get_type( d ) != 0 )
488         {
489             return d;
490         }
491         fclose( d->file_handle );
492                 d->file_handle = NULL;
493         if ( ffmpeg_open( d, title ) )
494         {
495             return d;
496         }
497     }
498     if ( d->file_handle )
499     {
500         fclose( d->file_handle );
501     }
502     if (d->path)
503     {
504         free( d->path );
505     }
506     hb_log( "hb_stream_open: open %s failed", path );
507     free( d );
508     return NULL;
509 }
510
511 /***********************************************************************
512  * hb_stream_close
513  ***********************************************************************
514  * Closes and frees everything
515  **********************************************************************/
516 void hb_stream_close( hb_stream_t ** _d )
517 {
518     hb_stream_t *stream = * _d;
519
520     if ( stream->hb_stream_type == ffmpeg )
521     {
522         ffmpeg_close( stream );
523         hb_stream_delete( stream );
524         *_d = NULL;
525         return;
526     }
527
528     if ( stream->frames )
529     {
530         hb_log( "stream: %d good frames, %d errors (%.0f%%)", stream->frames,
531                 stream->errors, (double)stream->errors * 100. /
532                 (double)stream->frames );
533     }
534
535     /*
536      * if the stream was opened for a scan, cache the result, otherwise delete
537      * the state.
538      */
539     if ( stream->title == NULL )
540     {
541         hb_stream_delete_dynamic( stream );
542         if ( stream_state_list == NULL )
543         {
544             stream_state_list = hb_list_init();
545         }
546         hb_list_add( stream_state_list, stream );
547     }
548     else
549     {
550         hb_stream_delete( stream );
551     }
552     *_d = NULL;
553 }
554
555 /* when the file was first opened we made entries for all the audio elementary
556  * streams we found in it. Streams that were later found during the preview scan
557  * now have an audio codec, type, rate, etc., associated with them. At the end
558  * of the scan we delete all the audio entries that weren't found by the scan
559  * or don't have a format we support. This routine deletes audio entry 'indx'
560  * by copying all later entries down one slot. */
561 static void hb_stream_delete_audio_entry(hb_stream_t *stream, int indx)
562 {
563     int i;
564
565     for (i = indx+1; i < stream->ts_number_audio_pids; ++i)
566     {
567         stream->ts_audio_pids[indx] = stream->ts_audio_pids[i];
568         stream->ts_stream_type[1 + indx] = stream->ts_stream_type[1+i];
569         stream->ts_streamid[1 + indx] = stream->ts_streamid[1 + i];
570         ++indx;
571     }
572     --stream->ts_number_audio_pids;
573 }
574
575 static int index_of_pid(int pid, hb_stream_t *stream)
576 {
577     int i;
578
579     if ( pid == stream->ts_video_pids[0] )
580         return 0;
581
582     for ( i = 0; i < stream->ts_number_audio_pids; ++i )
583         if ( pid == stream->ts_audio_pids[i] )
584             return i + 1;
585
586     return -1;
587 }
588
589 /***********************************************************************
590  * hb_ps_stream_title_scan
591  ***********************************************************************
592  *
593  **********************************************************************/
594 hb_title_t * hb_stream_title_scan(hb_stream_t *stream)
595 {
596         if ( stream->hb_stream_type == ffmpeg )
597         return ffmpeg_title_scan( stream );
598
599     // 'Barebones Title'
600     hb_title_t *aTitle = hb_title_init( stream->path, 0 );
601     aTitle->index = 1;
602
603         // Copy part of the stream path to the title name
604         char *sep = strrchr(stream->path, '/');
605         if (sep)
606                 strcpy(aTitle->name, sep+1);
607         char *dot_term = strrchr(aTitle->name, '.');
608         if (dot_term)
609                 *dot_term = '\0';
610
611     // Height, width,  rate and aspect ratio information is filled in when the previews are built
612
613     hb_stream_duration(stream, aTitle);
614
615     // One Chapter
616     hb_chapter_t * chapter;
617     chapter = calloc( sizeof( hb_chapter_t ), 1 );
618     chapter->index = 1;
619     chapter->duration = aTitle->duration;
620     chapter->hours = aTitle->hours;
621     chapter->minutes = aTitle->minutes;
622     chapter->seconds = aTitle->seconds;
623     hb_list_add( aTitle->list_chapter, chapter );
624
625     // Figure out how many audio streams we really have:
626     // - For transport streams, for each PID listed in the PMT (whether
627     //   or not it was an audio stream type) read the bitstream until we
628     //   find an packet from that PID containing a PES header and see if
629     //   the elementary stream is an audio type.
630     // - For program streams read the first 4MB and take every unique
631     //   audio stream we find.
632         if (stream->hb_stream_type == transport)
633         {
634         int i;
635
636         for (i=0; i < stream->ts_number_audio_pids; i++)
637         {
638             hb_audio_t *audio = hb_ts_stream_set_audio_id_and_codec(stream, i);
639             if (audio->config.in.codec)
640                 hb_list_add( aTitle->list_audio, audio );
641             else
642             {
643                 free(audio);
644                 hb_stream_delete_audio_entry(stream, i);
645                 --i;
646             }
647         }
648
649         // add the PCR PID if we don't already have it
650         if ( index_of_pid( stream->pmt_info.PCR_PID, stream ) < 0 )
651         {
652             stream->ts_audio_pids[stream->ts_number_audio_pids++] =
653                 stream->pmt_info.PCR_PID;
654         }
655
656         // set up the video codec to use for this title
657         aTitle->video_codec = st2codec[stream->ts_stream_type[0]].codec;
658         aTitle->video_codec_param = st2codec[stream->ts_stream_type[0]].codec_param;
659         }
660     else
661     {
662         hb_ps_stream_find_audio_ids(stream, aTitle);
663     }
664
665   return aTitle;
666 }
667
668 /*
669  * read the next transport stream packet from 'stream'. Return NULL if
670  * we hit eof & a pointer to the sync byte otherwise.
671  */
672 static const uint8_t *next_packet( hb_stream_t *stream )
673 {
674     uint8_t *buf = stream->ts_packet + stream->packetsize - 188;
675
676     while ( 1 )
677     {
678         if ( fread(stream->ts_packet, 1, stream->packetsize, stream->file_handle) !=
679              stream->packetsize )
680         {
681             return NULL;
682         }
683         if (buf[0] == 0x47)
684         {
685             return buf;
686         }
687         // lost sync - back up to where we started then try to re-establish.
688         off_t pos = ftello(stream->file_handle) - stream->packetsize;
689         off_t pos2 = align_to_next_packet(stream);
690         if ( pos2 == 0 )
691         {
692             hb_log( "next_packet: eof while re-establishing sync @ %lld", pos );
693             return NULL;
694         }
695         ts_warn( stream, "next_packet: sync lost @ %lld, regained after %lld bytes",
696                  pos, pos2 );
697     }
698 }
699
700 /*
701  * skip to the start of the next PACK header in program stream src_stream.
702  */
703 static void skip_to_next_pack( hb_stream_t *src_stream )
704 {
705     // scan forward until we find the start of the next pack
706     uint32_t strt_code = -1;
707     int c;
708
709     flockfile( src_stream->file_handle );
710     while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
711     {
712         strt_code = ( strt_code << 8 ) | c;
713         if ( strt_code == 0x000001ba )
714             // we found the start of the next pack
715             break;
716     }
717     funlockfile( src_stream->file_handle );
718
719     // if we didn't terminate on an eof back up so the next read
720     // starts on the pack boundary.
721     if ( c != EOF )
722     {
723         fseeko( src_stream->file_handle, -4, SEEK_CUR );
724     }
725 }
726
727 /*
728  * scan the next MB of 'stream' to find the next start packet for
729  * the Packetized Elementary Stream associated with TS PID 'pid'.
730  */
731 static const uint8_t *hb_ts_stream_getPEStype(hb_stream_t *stream, uint32_t pid)
732 {
733     int npack = 300000; // max packets to read
734
735     while (--npack >= 0)
736     {
737         const uint8_t *buf = next_packet( stream );
738         if ( buf == NULL )
739         {
740             hb_log("hb_ts_stream_getPEStype: EOF while searching for PID 0x%x", pid);
741             return 0;
742         }
743
744         /*
745          * The PES header is only in TS packets with 'start' set so we check
746          * that first then check for the right PID.
747          */
748         if ((buf[1] & 0x40) == 0 || (buf[1] & 0x1f) != (pid >> 8) ||
749             buf[2] != (pid & 0xff))
750         {
751             // not a start packet or not the pid we want
752             continue;
753         }
754
755         /* skip over the TS hdr to return a pointer to the PES hdr */
756         int udata = 4;
757         switch (buf[3] & 0x30)
758         {
759             case 0x00: // illegal
760             case 0x20: // fill packet
761                 continue;
762
763             case 0x30: // adaptation
764                 if (buf[4] > 182)
765                 {
766                     hb_log("hb_ts_stream_getPEStype: invalid adaptation field length %d for PID 0x%x", buf[4], pid);
767                     continue;
768                 }
769                 udata += buf[4] + 1;
770                 break;
771         }
772         /* PES hdr has to begin with an mpeg start code */
773         if (buf[udata+0] == 0x00 && buf[udata+1] == 0x00 && buf[udata+2] == 0x01)
774         {
775             return &buf[udata];
776         }
777     }
778
779     /* didn't find it */
780     return 0;
781 }
782
783 static uint64_t hb_ps_stream_getVideoPTS(hb_stream_t *stream)
784 {
785     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
786     hb_list_t *list = hb_list_init();
787     // how many blocks we read while searching for a video PES header
788     int blksleft = 1024;
789     uint64_t pts = 0;
790
791     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
792     {
793         hb_buffer_t *es;
794
795         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
796         hb_demux_ps( buf, list, 0 );
797
798         while ( ( es = hb_list_item( list, 0 ) ) )
799         {
800             hb_list_rem( list, es );
801             if ( es->id == 0xe0 )
802             {
803                 // this PES contains video - if there's a PTS we're done
804                 // hb_demux_ps left the PTS in buf_es->start.
805                 if ( es->start != ~0 )
806                 {
807                     pts = es->start;
808                     blksleft = 0;
809                     break;
810                 }
811             }
812             hb_buffer_close( &es );
813         }
814     }
815     hb_list_empty( &list );
816     hb_buffer_close(&buf);
817     return pts;
818 }
819
820 /***********************************************************************
821  * hb_stream_duration
822  ***********************************************************************
823  *
824  * Finding stream duration is difficult.  One issue is that the video file
825  * may have chunks from several different program fragments (main feature,
826  * commercials, station id, trailers, etc.) all with their own base pts
827  * value.  We can't find the piece boundaries without reading the entire
828  * file but if we compute a rate based on time stamps from two different
829  * pieces the result will be meaningless.  The second issue is that the
830  * data rate of compressed video normally varies by 5-10x over the length
831  * of the video. This says that we want to compute the rate over relatively
832  * long segments to get a representative average but long segments increase
833  * the likelihood that we'll cross a piece boundary.
834  *
835  * What we do is take time stamp samples at several places in the file
836  * (currently 16) then compute the average rate (i.e., ticks of video per
837  * byte of the file) for all pairs of samples (N^2 rates computed for N
838  * samples). Some of those rates will be absurd because the samples came
839  * from different segments. Some will be way low or high because the
840  * samples came from a low or high motion part of the segment. But given
841  * that we're comparing *all* pairs the majority of the computed rates
842  * should be near the overall average.  So we median filter the computed
843  * rates to pick the most representative value.
844  *
845  **********************************************************************/
846 struct pts_pos {
847     uint64_t pos;   /* file position of this PTS sample */
848     uint64_t pts;   /* PTS from video stream */
849 };
850
851 #define NDURSAMPLES 16
852
853 // get one (position, timestamp) sampple from a transport or program
854 // stream.
855 static struct pts_pos hb_sample_pts(hb_stream_t *stream, uint64_t fpos)
856 {
857     struct pts_pos pp = { 0, 0 };
858
859     if ( stream->hb_stream_type == transport )
860     {
861         const uint8_t *buf;
862         fseeko( stream->file_handle, fpos, SEEK_SET );
863         align_to_next_packet( stream );
864         buf = hb_ts_stream_getPEStype( stream, stream->ts_video_pids[0] );
865         if ( buf == NULL )
866         {
867             hb_log("hb_sample_pts: couldn't find video packet near %llu", fpos);
868             return pp;
869         }
870         if ( ( buf[7] >> 7 ) != 1 )
871         {
872             hb_log("hb_sample_pts: no PTS in video packet near %llu", fpos);
873             return pp;
874         }
875         pp.pts = ( ( (uint64_t)buf[9] >> 1 ) & 7 << 30 ) |
876                  ( (uint64_t)buf[10] << 22 ) |
877                  ( ( (uint64_t)buf[11] >> 1 ) << 15 ) |
878                  ( (uint64_t)buf[12] << 7 ) |
879                  ( (uint64_t)buf[13] >> 1 );
880     }
881     else
882     {
883         // round address down to nearest dvd sector start
884         fpos &=~ ( HB_DVD_READ_BUFFER_SIZE - 1 );
885         fseeko( stream->file_handle, fpos, SEEK_SET );
886         if ( stream->hb_stream_type == program )
887         {
888             skip_to_next_pack( stream );
889         }
890         pp.pts = hb_ps_stream_getVideoPTS( stream );
891     }
892     pp.pos = ftello(stream->file_handle);
893     return pp;
894 }
895
896 static int dur_compare( const void *a, const void *b )
897 {
898     const double *aval = a, *bval = b;
899     return ( *aval < *bval ? -1 : ( *aval == *bval ? 0 : 1 ) );
900 }
901
902 // given an array of (position, time) samples, compute a max-likelihood
903 // estimate of the average rate by computing the rate between all pairs
904 // of samples then taking the median of those rates.
905 static double compute_stream_rate( struct pts_pos *pp, int n )
906 {
907     int i, j;
908     double rates[NDURSAMPLES * NDURSAMPLES / 2];
909     double *rp = rates;
910
911     // the following nested loops compute the rates between all pairs.
912     *rp = 0;
913     for ( i = 0; i < n-1; ++i )
914     {
915         // Bias the median filter by not including pairs that are "far"
916         // from one another. This is to handle cases where the file is
917         // made of roughly equal size pieces where a symmetric choice of
918         // pairs results in having the same number of intra-piece &
919         // inter-piece rate estimates. This would mean that the median
920         // could easily fall in the inter-piece part of the data which
921         // would give a bogus estimate. The 'ns' index creates an
922         // asymmetry that favors locality.
923         int ns = i + ( n >> 1 );
924         if ( ns > n )
925             ns = n;
926         for ( j = i+1; j < ns; ++j )
927         {
928             if ( pp[j].pts != pp[i].pts && pp[j].pos > pp[i].pos )
929             {
930                 *rp = ((double)( pp[j].pts - pp[i].pts )) /
931                       ((double)( pp[j].pos - pp[i].pos ));
932                                 ++rp;
933             }
934         }
935     }
936     // now compute and return the median of all the (n*n/2) rates we computed
937     // above.
938     int nrates = rp - rates;
939     qsort( rates, nrates, sizeof (rates[0] ), dur_compare );
940     return rates[nrates >> 1];
941 }
942
943 static void hb_stream_duration(hb_stream_t *stream, hb_title_t *inTitle)
944 {
945     struct pts_pos ptspos[NDURSAMPLES];
946     struct pts_pos *pp = ptspos;
947     int i;
948
949     fseeko(stream->file_handle, 0, SEEK_END);
950     uint64_t fsize = ftello(stream->file_handle);
951     uint64_t fincr = fsize / NDURSAMPLES;
952     uint64_t fpos = fincr / 2;
953     for ( i = NDURSAMPLES; --i >= 0; fpos += fincr )
954     {
955         *pp++ = hb_sample_pts(stream, fpos);
956     }
957     uint64_t dur = compute_stream_rate( ptspos, pp - ptspos ) * (double)fsize;
958     inTitle->duration = dur;
959     dur /= 90000;
960     inTitle->hours    = dur / 3600;
961     inTitle->minutes  = ( dur % 3600 ) / 60;
962     inTitle->seconds  = dur % 60;
963
964     rewind(stream->file_handle);
965 }
966
967 /***********************************************************************
968  * hb_stream_read
969  ***********************************************************************
970  *
971  **********************************************************************/
972 int hb_stream_read( hb_stream_t * src_stream, hb_buffer_t * b )
973 {
974         if ( src_stream->hb_stream_type == ffmpeg )
975     {
976         return ffmpeg_read( src_stream, b );
977     }
978     if ( src_stream->hb_stream_type == dvd_program )
979     {
980         size_t amt_read = fread(b->data, HB_DVD_READ_BUFFER_SIZE, 1,
981                                 src_stream->file_handle);
982         return (amt_read > 0);
983     }
984     if ( src_stream->hb_stream_type == program )
985     {
986         // a general program stream has arbitrary sized pack's. we're
987         // currently positioned at the start of a pack so read up to but
988         // not including the start of the next, expanding the buffer
989         // as necessary.
990         uint8_t *cp = b->data;
991         uint8_t *ep = cp + b->alloc;
992         uint32_t strt_code = -1;
993         int c;
994
995         // consume the first byte of the initial pack so we don't match on
996         // it in the loop below.
997         if ( ( c = getc( src_stream->file_handle ) ) == EOF )
998             return 0;
999
1000         *cp++ = c;
1001
1002         flockfile( src_stream->file_handle );
1003         while ( ( c = getc_unlocked( src_stream->file_handle ) ) != EOF )
1004         {
1005             strt_code = ( strt_code << 8 ) | c;
1006             if ( strt_code == 0x000001ba )
1007                 // we found the start of the next pack
1008                 break;
1009             if ( cp >= ep )
1010             {
1011                 // need to expand the buffer
1012                 int curSize = cp - b->data;
1013                 hb_buffer_realloc( b, curSize * 2 );
1014                 cp = b->data + curSize;
1015                 ep = b->data + b->alloc;
1016             }
1017             *cp++ = c;
1018         }
1019         funlockfile( src_stream->file_handle );
1020
1021         // if we didn't terminate on an eof back up so the next read
1022         // starts on the pack boundary.
1023         b->size = cp - b->data;
1024         if ( c != EOF )
1025         {
1026             fseeko( src_stream->file_handle, -4, SEEK_CUR );
1027             b->size -= 4;
1028         }
1029         return 1;
1030     }
1031     return hb_ts_stream_decode( src_stream, b->data );
1032 }
1033
1034 /***********************************************************************
1035  * hb_stream_seek
1036  ***********************************************************************
1037  *
1038  **********************************************************************/
1039 int hb_stream_seek( hb_stream_t * src_stream, float f )
1040 {
1041         if ( src_stream->hb_stream_type == ffmpeg )
1042     {
1043         return ffmpeg_seek( src_stream, f );
1044     }
1045     off_t stream_size, cur_pos, new_pos;
1046     double pos_ratio = f;
1047     cur_pos = ftello( src_stream->file_handle );
1048     fseeko( src_stream->file_handle, 0, SEEK_END );
1049     stream_size = ftello( src_stream->file_handle );
1050     new_pos = (off_t) ((double) (stream_size) * pos_ratio);
1051     new_pos &=~ (HB_DVD_READ_BUFFER_SIZE - 1);
1052
1053     int r = fseeko( src_stream->file_handle, new_pos, SEEK_SET );
1054     if (r == -1)
1055     {
1056         fseeko( src_stream->file_handle, cur_pos, SEEK_SET );
1057         return 0;
1058     }
1059
1060     if ( src_stream->hb_stream_type == transport )
1061     {
1062         // We need to drop the current decoder output and move
1063         // forwards to the next transport stream packet.
1064         hb_ts_stream_reset(src_stream);
1065     }
1066     else if ( src_stream->hb_stream_type == program )
1067     {
1068         skip_to_next_pack( src_stream );
1069     }
1070
1071     return 1;
1072 }
1073
1074 static const char* make_upper( const char* s )
1075 {
1076     static char name[8];
1077     char *cp = name;
1078     char *ep = cp + sizeof(name)-1;
1079
1080     while ( *s && cp < ep )
1081     {
1082         *cp++ = islower(*s)? toupper(*s) : *s;
1083         ++s;
1084     }
1085     *cp = 0;
1086     return name;
1087 }
1088
1089 static void set_audio_description( hb_audio_t *audio, iso639_lang_t *lang )
1090 {
1091     /* XXX
1092      * This is a duplicate of code in dvd.c - it should get factored out
1093      * into a common routine. We probably should only be putting the lang
1094      * code or a lang pointer into the audio config & let the common description
1095      * formatting routine in scan.c do all the stuff below.
1096      */
1097     const char *codec_name;
1098     AVCodecContext *cc;
1099
1100     if ( audio->config.in.codec == HB_ACODEC_FFMPEG &&
1101          ( cc = hb_ffmpeg_context( audio->config.in.codec_param ) ) &&
1102          avcodec_find_decoder( cc->codec_id ) )
1103     {
1104         codec_name = make_upper( avcodec_find_decoder( cc->codec_id )->name );
1105         if ( !strcmp( codec_name, "LIBFAAD" ) )
1106         {
1107             codec_name = "AAC";
1108         }
1109     }
1110     else if ( audio->config.in.codec == HB_ACODEC_MPGA &&
1111               avcodec_find_decoder( audio->config.in.codec_param ) )
1112     {
1113         codec_name = avcodec_find_decoder( audio->config.in.codec_param )->name;
1114     }
1115     else
1116     {
1117         codec_name = audio->config.in.codec == HB_ACODEC_AC3 ? "AC3" :
1118                      audio->config.in.codec == HB_ACODEC_DCA ? "DTS" :
1119                      audio->config.in.codec == HB_ACODEC_MPGA ? "MPEG" : 
1120                      audio->config.in.codec == HB_ACODEC_LPCM ? "LPCM" : 
1121                      audio->config.in.codec == HB_ACODEC_FFMPEG ? "FFMPEG" :
1122                      "Unknown";
1123     }
1124     snprintf( audio->config.lang.description,
1125               sizeof( audio->config.lang.description ), "%s (%s)",
1126               strlen(lang->native_name) ? lang->native_name : lang->eng_name,
1127               codec_name );
1128     snprintf( audio->config.lang.simple, sizeof( audio->config.lang.simple ), "%s",
1129               strlen(lang->native_name) ? lang->native_name : lang->eng_name );
1130     snprintf( audio->config.lang.iso639_2, sizeof( audio->config.lang.iso639_2 ),
1131               "%s", lang->iso639_2);
1132 }
1133
1134 static hb_audio_t *hb_ts_stream_set_audio_id_and_codec(hb_stream_t *stream,
1135                                                        int aud_pid_index)
1136 {
1137     off_t cur_pos = ftello(stream->file_handle);
1138     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1139     const uint8_t *buf;
1140
1141     fseeko(stream->file_handle, 0, SEEK_SET);
1142     align_to_next_packet(stream);
1143     buf = hb_ts_stream_getPEStype(stream, stream->ts_audio_pids[aud_pid_index]);
1144
1145     /* check that we found a PES header */
1146     uint8_t stype = 0;
1147     if (buf && buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0x01)
1148     {
1149         // 0xbd is the normal container for AC3/DCA/PCM/etc. 0xfd indicates an
1150         // extended stream id (ISO 13818-1(2007)). If we cared about the
1151         // real id we'd have to look inside the PES extension to find it.
1152         // But since we remap stream id's when we generate PS packets from
1153         // the TS packets we can just ignore the actual id.
1154         if ( buf[3] == 0xbd || buf[3] == 0xfd )
1155         {
1156             audio->id = 0x80bd | (aud_pid_index << 8);
1157             stype = stream->ts_stream_type[1 + aud_pid_index];
1158             if ( st2codec[stype].kind == U )
1159             {
1160                 // XXX assume unknown stream types are AC-3 (if they're not
1161                 // audio we'll find that out during the scan but if they're
1162                 // some other type of audio we'll end up ignoring them).
1163                 stype = 0x81;
1164                 stream->ts_stream_type[1 + aud_pid_index] = 0x81;
1165             }
1166             stream->ts_streamid[1 + aud_pid_index] = 0xbd;
1167         }
1168         else if ((buf[3] & 0xe0) == 0xc0)
1169         {
1170             audio->id = 0xc0 | aud_pid_index;
1171             stype = stream->ts_stream_type[1 + aud_pid_index];
1172             if ( st2codec[stype].kind == U )
1173             {
1174                 // XXX assume unknown stream types are MPEG audio
1175                 stype = 0x03;
1176                 stream->ts_stream_type[1 + aud_pid_index] = 0x03;
1177             }
1178         }
1179     }
1180     // if we found an audio stream type & HB has a codec that can decode it
1181     // finish configuring the audio so we'll add it to the title's list.
1182     if ( st2codec[stype].kind == A && st2codec[stype].codec )
1183     {
1184         stream->ts_streamid[1 + aud_pid_index] = audio->id;
1185         audio->config.in.codec = st2codec[stype].codec;
1186         audio->config.in.codec_param = st2codec[stype].codec_param;
1187                 set_audio_description( audio,
1188                   lang_for_code( stream->a52_info[aud_pid_index].lang_code ) );
1189         hb_log("transport stream pid 0x%x (type 0x%x) is %s audio id 0x%x",
1190                stream->ts_audio_pids[aud_pid_index],
1191                stype, st2codec[stype].name, audio->id);
1192     }
1193     else
1194     {
1195         if ( buf )
1196         {
1197             hb_log("transport stream pid 0x%x (type 0x%x, substream 0x%x) "
1198                     "isn't audio", stream->ts_audio_pids[aud_pid_index],
1199                     stream->ts_stream_type[1 + aud_pid_index], buf[3]);
1200         }
1201         else
1202         {
1203             hb_log("transport stream pid 0x%x (type 0x%x) isn't audio",
1204                     stream->ts_audio_pids[aud_pid_index],
1205                     stream->ts_stream_type[1 + aud_pid_index]);
1206         }
1207         }
1208     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1209     return audio;
1210 }
1211
1212 static void add_audio_to_title(hb_title_t *title, int id)
1213 {
1214     hb_audio_t *audio = calloc( sizeof( hb_audio_t ), 1 );
1215
1216     audio->id = id;
1217     switch ( id >> 12 )
1218     {
1219         case 0x0:
1220             audio->config.in.codec = HB_ACODEC_MPGA;
1221             hb_log("add_audio_to_title: added MPEG audio stream 0x%x", id);
1222             break;
1223         case 0x2:
1224             // type 2 is a DVD subtitle stream - just ignore it */
1225             free( audio );
1226             return;
1227         case 0x8:
1228             audio->config.in.codec = HB_ACODEC_AC3;
1229             hb_log("add_audio_to_title: added AC3 audio stream 0x%x", id);
1230             break;
1231         case 0xa:
1232             audio->config.in.codec = HB_ACODEC_LPCM;
1233             hb_log("add_audio_to_title: added LPCM audio stream 0x%x", id);
1234             break;
1235         default:
1236             hb_log("add_audio_to_title: unknown audio stream type 0x%x", id);
1237             free( audio );
1238             return;
1239
1240     }
1241     set_audio_description( audio, lang_for_code( 0 ) );
1242     hb_list_add( title->list_audio, audio );
1243 }
1244
1245 static void hb_ps_stream_find_audio_ids(hb_stream_t *stream, hb_title_t *title)
1246 {
1247     off_t cur_pos = ftello(stream->file_handle);
1248     hb_buffer_t *buf  = hb_buffer_init(HB_DVD_READ_BUFFER_SIZE);
1249     hb_list_t *list = hb_list_init();
1250     // how many blocks we read while searching for audio streams
1251     int blksleft = 4096;
1252     // there can be at most 16 unique streams in an MPEG PS (8 in a DVD)
1253     // so we use a bitmap to keep track of the ones we've already seen.
1254     // Bit 'i' of smap is set if we've already added the audio for
1255     // audio substream id 'i' to the title's audio list.
1256     uint32_t smap = 0;
1257
1258     // start looking 20% into the file since there's occasionally no
1259     // audio at the beginning (particularly for vobs).
1260     hb_stream_seek(stream, 0.2f);
1261
1262     while (--blksleft >= 0 && hb_stream_read(stream, buf) == 1)
1263     {
1264         hb_buffer_t *es;
1265
1266         // 'buf' contains an MPEG2 PACK - get a list of all it's elementary streams
1267         hb_demux_ps( buf, list, 0 );
1268
1269         while ( ( es = hb_list_item( list, 0 ) ) )
1270         {
1271             hb_list_rem( list, es );
1272             if ( (es->id & 0xff) == 0xbd || (es->id & 0xe0) == 0xc0 )
1273             {
1274                 // this PES contains some kind of audio - get the substream id
1275                 // and check if we've seen it already.
1276                 int ssid = (es->id > 0xff ? es->id >> 8 : es->id) & 0xf;
1277                 if ( (smap & (1 << ssid)) == 0 )
1278                 {
1279                     // we haven't seen this stream before - add it to the
1280                     // title's list of audio streams.
1281                     smap |= (1 << ssid);
1282                     add_audio_to_title(title, es->id);
1283                 }
1284             }
1285             hb_buffer_close( &es );
1286         }
1287     }
1288     hb_list_empty( &list );
1289     hb_buffer_close(&buf);
1290     fseeko(stream->file_handle, cur_pos, SEEK_SET);
1291 }
1292
1293 /***********************************************************************
1294  * hb_ts_stream_init
1295  ***********************************************************************
1296  *
1297  **********************************************************************/
1298
1299 static void hb_ts_stream_init(hb_stream_t *stream)
1300 {
1301         int i;
1302
1303         for (i=0; i < kMaxNumberDecodeStreams; i++)
1304         {
1305                 stream->ts_streamcont[i] = -1;
1306         }
1307         stream->ts_video_pids[0] = -1;
1308     for ( i = 0; i < stream->ts_number_audio_pids; i++ )
1309     {
1310         stream-> ts_audio_pids[i] = -1;
1311     }
1312
1313     stream->ts_packet = malloc( stream->packetsize );
1314
1315         // Find the audio and video pids in the stream
1316         hb_ts_stream_find_pids(stream);
1317
1318         for (i = 0; i < stream->ts_number_video_pids + stream->ts_number_audio_pids; i++)
1319         {
1320         // demuxing buffer for TS to PS conversion
1321                 stream->ts_buf[i] = malloc( HB_DVD_READ_BUFFER_SIZE );
1322         }
1323
1324     stream->ts_streamid[0] = 0xE0;              // stream 0 must be video
1325 }
1326
1327 #define MAX_HOLE 208*80
1328
1329 static off_t align_to_next_packet(hb_stream_t *stream)
1330 {
1331     uint8_t buf[MAX_HOLE];
1332         off_t pos = 0;
1333     off_t start = ftello(stream->file_handle);
1334
1335     if ( start >= stream->packetsize ) {
1336         start -= stream->packetsize;
1337         fseeko(stream->file_handle, start, SEEK_SET);
1338     }
1339
1340     if (fread(buf, sizeof(buf), 1, stream->file_handle) == 1)
1341         {
1342         const uint8_t *bp = buf;
1343         int i;
1344
1345         for ( i = sizeof(buf); --i >= 0; ++bp )
1346         {
1347             if ( have_ts_sync( bp, stream->packetsize ) )
1348             {
1349                 break;
1350             }
1351         }
1352         if ( i >= 0 )
1353         {
1354             pos = ( bp - buf ) - stream->packetsize + 188;
1355             if ( pos < 0 )
1356                 pos = 0;
1357         }
1358         }
1359     fseeko(stream->file_handle, start+pos, SEEK_SET);
1360         return pos;
1361 }
1362
1363
1364 typedef struct {
1365     uint8_t *buf;
1366     uint32_t val;
1367     int pos;
1368 } bitbuf_t;
1369
1370 static const unsigned int bitmask[] = {
1371         0x0,0x1,0x3,0x7,0xf,0x1f,0x3f,0x7f,0xff,
1372         0x1ff,0x3ff,0x7ff,0xfff,0x1fff,0x3fff,0x7fff,0xffff,
1373         0x1ffff,0x3ffff,0x7ffff,0xfffff,0x1fffff,0x3fffff,0x7fffff,0xffffff,
1374         0x1ffffff,0x3ffffff,0x7ffffff,0xfffffff,0x1fffffff,0x3fffffff,0x7fffffff,0xffffffff};
1375
1376 static inline void set_buf(bitbuf_t *bb, uint8_t* buf, int bufsize, int clear)
1377 {
1378         bb->pos = 0;
1379         bb->buf = buf;
1380         bb->val = (bb->buf[0] << 24) | (bb->buf[1] << 16) |
1381               (bb->buf[2] << 8) | bb->buf[3];
1382         if (clear)
1383                 memset(bb->buf, 0, bufsize);
1384 }
1385
1386 static inline int buf_size(bitbuf_t *bb)
1387 {
1388         return bb->pos >> 3;
1389 }
1390
1391 static inline unsigned int get_bits(bitbuf_t *bb, int bits)
1392 {
1393         unsigned int val;
1394         int left = 32 - (bb->pos & 31);
1395
1396         if (bits < left)
1397         {
1398                 val = (bb->val >> (left - bits)) & bitmask[bits];
1399                 bb->pos += bits;
1400         }
1401         else
1402         {
1403                 val = (bb->val & bitmask[left]) << (bits - left);
1404                 bb->pos += left;
1405                 bits -= left;
1406
1407                 int pos = bb->pos >> 3;
1408                 bb->val = (bb->buf[pos] << 24) | (bb->buf[pos + 1] << 16) | (bb->buf[pos + 2] << 8) | bb->buf[pos + 3];
1409
1410                 if (bits > 0)
1411                 {
1412                         val |= (bb->val >> (32 - bits)) & bitmask[bits];
1413                         bb->pos += bits;
1414                 }
1415         }
1416
1417         return val;
1418 }
1419
1420 // extract what useful information we can from the elementary stream
1421 // descriptor list at 'dp' and add it to the stream at 'esindx'.
1422 // Descriptors with info we don't currently use are ignored.
1423 // The descriptor list & descriptor item formats are defined in
1424 // ISO 13818-1 (2000E) section 2.6 (pg. 62).
1425 static void decode_element_descriptors(hb_stream_t* stream, int esindx,
1426                                        const uint8_t *dp, uint8_t dlen)
1427 {
1428     const uint8_t *ep = dp + dlen;
1429
1430     while (dp < ep)
1431     {
1432         switch (dp[0])
1433         {
1434             case 10:    // ISO_639_language descriptor
1435                 stream->a52_info[esindx].lang_code = lang_to_code(lang_for_code2((const char *)&dp[2]));
1436                 break;
1437
1438             default:
1439                 break;
1440         }
1441         dp += dp[1] + 2;
1442     }
1443 }
1444
1445 static const char *stream_type_name (uint8_t stream_type)
1446 {
1447     return st2codec[stream_type].name? st2codec[stream_type].name : "Unknown";
1448 }
1449
1450 int decode_program_map(hb_stream_t* stream)
1451 {
1452     bitbuf_t bb;
1453         set_buf(&bb, stream->pmt_info.tablebuf, stream->pmt_info.tablepos, 0);
1454
1455     get_bits(&bb, 8);  // table_id
1456     get_bits(&bb, 4);
1457     unsigned int section_length = get_bits(&bb, 12);
1458     stream->pmt_info.section_length = section_length;
1459
1460     unsigned int program_number = get_bits(&bb, 16);
1461     stream->pmt_info.program_number = program_number;
1462     get_bits(&bb, 2);
1463     get_bits(&bb, 5);  // version_number
1464     get_bits(&bb, 1);
1465     get_bits(&bb, 8);  // section_number
1466     get_bits(&bb, 8);  // last_section_number
1467     get_bits(&bb, 3);
1468     unsigned int PCR_PID = get_bits(&bb, 13);
1469     stream->pmt_info.PCR_PID = PCR_PID;
1470     get_bits(&bb, 4);
1471     unsigned int program_info_length = get_bits(&bb, 12);
1472     stream->pmt_info.program_info_length = program_info_length;
1473
1474         int i=0;
1475         unsigned char *descriptor_buf = (unsigned char *) malloc(program_info_length);
1476         for (i = 0; i < program_info_length; i++)
1477         {
1478           descriptor_buf[i] = get_bits(&bb, 8);
1479         }
1480
1481         int cur_pos =  9 /* data after the section length field*/ + program_info_length;
1482         int done_reading_stream_types = 0;
1483         while (!done_reading_stream_types)
1484     {
1485         unsigned char stream_type = get_bits(&bb, 8);
1486         get_bits(&bb, 3);
1487         unsigned int elementary_PID = get_bits(&bb, 13);
1488         get_bits(&bb, 4);
1489         unsigned int ES_info_length = get_bits(&bb, 12);
1490
1491         int i=0;
1492         unsigned char *ES_info_buf = (unsigned char *) malloc(ES_info_length);
1493         for (i=0; i < ES_info_length; i++)
1494         {
1495             ES_info_buf[i] = get_bits(&bb, 8);
1496         }
1497
1498
1499         if (stream->ts_number_video_pids == 0 && st2codec[stream_type].kind == V )
1500         {
1501             stream->ts_video_pids[0] = elementary_PID;
1502             stream->ts_stream_type[0] = stream_type;
1503             stream->ts_number_video_pids = 1;
1504         }
1505         else
1506         {
1507             // Defined audio stream types are 0x81 for AC-3/A52 audio and 0x03
1508             // for mpeg audio. But content producers seem to use other
1509             // values (0x04 and 0x06 have both been observed) so at this point
1510             // we say everything that isn't a video pid is audio then at the end
1511             // of hb_stream_title_scan we'll figure out which are really audio
1512             // by looking at the PES headers.
1513             i = stream->ts_number_audio_pids;
1514             if (i < kMaxNumberAudioPIDS)
1515             {
1516                 stream->ts_audio_pids[i] = elementary_PID;
1517                 stream->ts_stream_type[1 + i] = stream_type;
1518                 if (ES_info_length > 0)
1519                 {
1520                     decode_element_descriptors(stream, i, ES_info_buf,
1521                                                ES_info_length);
1522                 }
1523                 ++stream->ts_number_audio_pids;
1524             }
1525         }
1526
1527         cur_pos += 5 /* stream header */ + ES_info_length;
1528
1529         free(ES_info_buf);
1530
1531         if (cur_pos >= section_length - 4 /* stop before the CRC */)
1532         done_reading_stream_types = 1;
1533     }
1534
1535         free(descriptor_buf);
1536         return 1;
1537 }
1538
1539 static int build_program_map(const uint8_t *buf, hb_stream_t *stream)
1540 {
1541     // Get adaption header info
1542     int adapt_len = 0;
1543     int adaption = (buf[3] & 0x30) >> 4;
1544     if (adaption == 0)
1545             return 0;
1546     else if (adaption == 0x2)
1547             adapt_len = 184;
1548     else if (adaption == 0x3)
1549             adapt_len = buf[4] + 1;
1550     if (adapt_len > 184)
1551             return 0;
1552
1553     // Get payload start indicator
1554     int start;
1555     start = (buf[1] & 0x40) != 0;
1556
1557     // Get pointer length - only valid in packets with a start flag
1558     int pointer_len = 0;
1559         if (start && stream->pmt_info.reading)
1560         {
1561                 // We just finished a bunch of packets - parse the program map details
1562                 int decode_ok = 0;
1563                 if (stream->pmt_info.tablebuf[0] == 0x02)
1564                         decode_ok = decode_program_map(stream);
1565                 free(stream->pmt_info.tablebuf);
1566                 stream->pmt_info.tablebuf = NULL;
1567                 stream->pmt_info.tablepos = 0;
1568         stream->pmt_info.reading = 0;
1569         if (decode_ok)
1570                         return decode_ok;
1571         }
1572
1573         if (start)
1574         {
1575                 pointer_len = buf[4 + adapt_len] + 1;
1576                 stream->pmt_info.tablepos = 0;
1577         }
1578         // Get Continuity Counter
1579         int continuity_counter = buf[3] & 0x0f;
1580         if (!start && (stream->pmt_info.current_continuity_counter + 1 != continuity_counter))
1581         {
1582                 hb_log("build_program_map - Continuity Counter %d out of sequence - expected %d", continuity_counter, stream->pmt_info.current_continuity_counter+1);
1583                 return 0;
1584         }
1585         stream->pmt_info.current_continuity_counter = continuity_counter;
1586         stream->pmt_info.reading |= start;
1587
1588     // Add the payload for this packet to the current buffer
1589         int amount_to_copy = 184 - adapt_len - pointer_len;
1590     if (stream->pmt_info.reading && (amount_to_copy > 0))
1591     {
1592                         stream->pmt_info.tablebuf = realloc(stream->pmt_info.tablebuf, stream->pmt_info.tablepos + amount_to_copy);
1593
1594             memcpy(stream->pmt_info.tablebuf + stream->pmt_info.tablepos, buf + 4 + adapt_len + pointer_len, amount_to_copy);
1595             stream->pmt_info.tablepos += amount_to_copy;
1596     }
1597
1598     return 0;
1599 }
1600
1601 static int decode_PAT(const uint8_t *buf, hb_stream_t *stream)
1602 {
1603     unsigned char tablebuf[1024];
1604     unsigned int tablepos = 0;
1605
1606     int reading = 0;
1607
1608
1609     // Get adaption header info
1610     int adapt_len = 0;
1611     int adaption = (buf[3] & 0x30) >> 4;
1612     if (adaption == 0)
1613             return 0;
1614     else if (adaption == 0x2)
1615             adapt_len = 184;
1616     else if (adaption == 0x3)
1617             adapt_len = buf[4] + 1;
1618     if (adapt_len > 184)
1619             return 0;
1620
1621     // Get pointer length
1622     int pointer_len = buf[4 + adapt_len] + 1;
1623
1624     // Get payload start indicator
1625     int start;
1626     start = (buf[1] & 0x40) != 0;
1627
1628     if (start)
1629             reading = 1;
1630
1631     // Add the payload for this packet to the current buffer
1632     if (reading && (184 - adapt_len) > 0)
1633     {
1634             if (tablepos + 184 - adapt_len - pointer_len > 1024)
1635             {
1636                     hb_log("decode_PAT - Bad program section length (> 1024)");
1637                     return 0;
1638             }
1639             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + pointer_len, 184 - adapt_len - pointer_len);
1640             tablepos += 184 - adapt_len - pointer_len;
1641     }
1642
1643     if (start && reading)
1644     {
1645             memcpy(tablebuf + tablepos, buf + 4 + adapt_len + 1, pointer_len - 1);
1646
1647
1648             unsigned int pos = 0;
1649             //while (pos < tablepos)
1650             {
1651                     bitbuf_t bb;
1652                     set_buf(&bb, tablebuf + pos, tablepos - pos, 0);
1653
1654                     unsigned char section_id    = get_bits(&bb, 8);
1655                     get_bits(&bb, 4);
1656                     unsigned int section_len    = get_bits(&bb, 12);
1657                     get_bits(&bb, 16); // transport_id
1658                     get_bits(&bb, 2);
1659                     get_bits(&bb, 5);  // version_num
1660                     get_bits(&bb, 1);  // current_next
1661                     get_bits(&bb, 8);  // section_num
1662                     get_bits(&bb, 8);  // last_section
1663
1664                     switch (section_id)
1665                     {
1666                       case 0x00:
1667                         {
1668                           // Program Association Section
1669                           section_len -= 5;    // Already read transport stream ID, version num, section num, and last section num
1670                           section_len -= 4;   // Ignore the CRC
1671                           int curr_pos = 0;
1672                                                   stream->ts_number_pat_entries = 0;
1673                           while ((curr_pos < section_len) && (stream->ts_number_pat_entries < kMaxNumberPMTStreams))
1674                           {
1675                             unsigned int pkt_program_num = get_bits(&bb, 16);
1676                                                         stream->pat_info[stream->ts_number_pat_entries].program_number = pkt_program_num;
1677
1678                             get_bits(&bb, 3);  // Reserved
1679                             if (pkt_program_num == 0)
1680                             {
1681                               get_bits(&bb, 13); // pkt_network_id
1682                             }
1683                             else
1684                             {
1685                               unsigned int pkt_program_map_PID = get_bits(&bb, 13);
1686                                 stream->pat_info[stream->ts_number_pat_entries].program_map_PID = pkt_program_map_PID;
1687                             }
1688                             curr_pos += 4;
1689                                                         stream->ts_number_pat_entries++;
1690                           }
1691                         }
1692                         break;
1693                       case 0xC7:
1694                             {
1695                                     break;
1696                             }
1697                       case 0xC8:
1698                             {
1699                                     break;
1700                             }
1701                     }
1702
1703                     pos += 3 + section_len;
1704             }
1705
1706             tablepos = 0;
1707     }
1708     return 1;
1709 }
1710
1711 static void hb_ts_stream_find_pids(hb_stream_t *stream)
1712 {
1713         // align to first packet
1714     align_to_next_packet(stream);
1715
1716         // Read the Transport Stream Packets (188 bytes each) looking at first for PID 0 (the PAT PID), then decode that
1717         // to find the program map PID and then decode that to get the list of audio and video PIDs
1718
1719         for (;;)
1720         {
1721         const uint8_t *buf = next_packet( stream );
1722         if ( buf == NULL )
1723         {
1724                         hb_log("hb_ts_stream_find_pids - end of file");
1725                         break;
1726                 }
1727
1728                 // Get pid
1729                 int pid = (((buf[1] & 0x1F) << 8) | buf[2]) & 0x1FFF;
1730
1731         if ((pid == 0x0000) && (stream->ts_number_pat_entries == 0))
1732                 {
1733                   decode_PAT(buf, stream);
1734                   continue;
1735                 }
1736
1737                 int pat_index = 0;
1738                 for (pat_index = 0; pat_index < stream->ts_number_pat_entries; pat_index++)
1739                 {
1740                         // There are some streams where the PAT table has multiple entries as if their are
1741                         // multiple programs in the same transport stream, and yet there's actually only one
1742                         // program really in the stream. This seems to be true for transport streams that
1743                         // originate in the HDHomeRun but have been output by EyeTV's export utility. What I think
1744                         // is happening is that the HDHomeRun is sending the entire transport stream as broadcast,
1745                         // but the EyeTV is only recording a single (selected) program number and not rewriting the
1746                         // PAT info on export to match what's actually on the stream.
1747                         // Until we have a way of handling multiple programs per transport stream elegantly we'll match
1748                         // on the first pat entry for which we find a matching program map PID.  The ideal solution would
1749                         // be to build a title choice popup from the PAT program number details and then select from
1750                         // their - but right now the API's not capable of that.
1751                         if (pid == stream->pat_info[pat_index].program_map_PID)
1752                         {
1753                           if (build_program_map(buf, stream) > 0)
1754                                 break;
1755                         }
1756                 }
1757                 // Keep going  until we have a complete set of PIDs
1758                 if ((stream->ts_number_video_pids > 0) && (stream->ts_number_audio_pids > 0))
1759                   break;
1760         }
1761
1762         hb_log("hb_ts_stream_find_pids - found the following PIDS");
1763         hb_log("    Video PIDS : ");
1764     int i;
1765         for (i=0; i < stream->ts_number_video_pids; i++)
1766         {
1767         hb_log( "      0x%x type %s (0x%x)", 
1768                 stream->ts_video_pids[i],
1769                 stream_type_name(stream->ts_stream_type[i]),
1770                 stream->ts_stream_type[i]);
1771         }
1772         hb_log("    Audio PIDS : ");
1773         for (i = 0; i < stream->ts_number_audio_pids; i++)
1774         {
1775         hb_log( "      0x%x type %s (0x%x)", 
1776                 stream->ts_audio_pids[i],
1777                 stream_type_name(stream->ts_stream_type[i+1]),
1778                 stream->ts_stream_type[i+1] );
1779         }
1780  }
1781
1782
1783 static void fwrite64( hb_stream_t *stream, void *buf, int size )
1784 {
1785     if ( (stream->fwrite_buf - stream->fwrite_buf_orig) + size > 2048 )
1786     {
1787         hb_log( "steam fwrite64 buffer overflow - writing %d with %d already",
1788                 size, stream->fwrite_buf - stream->fwrite_buf_orig );
1789         return;
1790     }
1791     memcpy( stream->fwrite_buf, buf, size );
1792     stream->fwrite_buf += size;
1793 }
1794
1795 static void write_pack(hb_stream_t* stream, uint64_t time, int stuffing)
1796 {
1797         uint8_t buf[24];
1798
1799     buf[0] = 0x00;      // pack id
1800     buf[1] = 0x00;
1801     buf[2] = 0x01;
1802     buf[3] = 0xba;
1803
1804     buf[4] = 0x44 |     // SCR
1805              ( ( ( time >> 30 ) & 7 ) << 3 ) |
1806              ( ( time >> 28 ) & 3 );
1807     buf[5] = time >> 20;
1808     buf[6] = 0x04 |
1809              ( ( ( time >> 15 ) & 0x1f ) << 3 ) |
1810              ( ( time >> 13 ) & 3 );
1811     buf[7] = time >> 5;
1812     buf[8] = 0x04 | ( time << 3 );
1813
1814     buf[9] = 0x01;      // SCR extension
1815
1816     buf[10] = 384000 >> (22 - 8);     // program mux rate
1817     buf[11] = (uint8_t)( 384000 >> (22 - 16) );
1818     buf[12] = (uint8_t)( 384000 << 2 ) | 0x03;
1819
1820     buf[13] = 0xf8 | stuffing;
1821
1822     int i;
1823     for (i = 0; i < stuffing; ++i )
1824         buf[14+i] = 0xff;
1825
1826         fwrite64(stream, buf, 14 + stuffing );
1827 }
1828
1829 static void pad_buffer(hb_stream_t* stream, int pad)
1830 {
1831         pad -= 6;
1832
1833         uint8_t buf[6];
1834         buf[0] = 0;
1835     buf[1] = 0;
1836     buf[2] = 0;
1837     buf[3] = 0xbe;
1838         buf[4] = pad >> 8;
1839     buf[5] = pad;
1840
1841         fwrite64(stream, buf, 6);
1842
1843         buf[0] = 0xff;
1844     while ( --pad >= 0 )
1845     {
1846                 fwrite64(stream, buf, 1);
1847         }
1848 }
1849
1850 static void make_pes_header(hb_stream_t* stream, int len, uint8_t streamid)
1851 {
1852         uint8_t buf[9];
1853
1854     memset(buf, 0, sizeof(buf) );
1855     buf[2] = 1;
1856     buf[3] = streamid;
1857     buf[4] = ( len + 3 ) >> 8;
1858     buf[5] = len + 3;
1859     buf[6] = 0x88;
1860
1861     fwrite64(stream, buf, 9);
1862 }
1863
1864 static void generate_output_data(hb_stream_t *stream, int curstream)
1865 {
1866     uint8_t *tdat = stream->ts_buf[curstream];
1867     int len;
1868
1869     // we always ship a PACK header plus all the data in our demux buf.
1870     // AC3 audio also always needs its substream header.
1871     len = 14 + stream->ts_pos[curstream];
1872     if ( stream->ts_stream_type[curstream] == 0x81)
1873     {
1874         len += 4;
1875     }
1876
1877     if ( ! stream->ts_start[curstream] )
1878     {
1879         // we're in the middle of a chunk of PES data - we need to add
1880         // a 'continuation' PES header after the PACK header.
1881         len += 9;
1882     }
1883
1884     // Write out pack header
1885     // If we don't have 2048 bytes we need to pad to 2048. We can
1886     // add a padding frame after our data but we need at least 7
1887     // bytes of space to do it (6 bytes of header & 1 of pad). If
1888     // we have fewer than 7 bytes left we need to fill the excess
1889     // space with stuffing bytes added to the pack header.
1890     int stuffing = 0;
1891     if ( len > HB_DVD_READ_BUFFER_SIZE )
1892     {
1893         hb_log( "stream ts length botch %d", len );
1894     }
1895     if ( HB_DVD_READ_BUFFER_SIZE - len < 8)
1896     {
1897         stuffing = HB_DVD_READ_BUFFER_SIZE - len;
1898     }
1899     write_pack(stream, stream->ts_nextpcr, stuffing );
1900     stream->ts_nextpcr += 10;
1901
1902     if ( stream->ts_start[curstream] )
1903     {
1904         // Start frames already have a PES header but we have modify it
1905         // to map from TS PID to PS stream id. Also, if the stream is AC3
1906         // audio we have to insert an AC3 stream header between the end of
1907         // the PES header and the start of the stream data.
1908
1909         stream->ts_start[curstream] = 0;
1910         tdat[3] = stream->ts_streamid[curstream];
1911
1912         uint16_t plen = stream->ts_pos[curstream] - 6;
1913         if ( stream->ts_stream_type[curstream] == 0x81)
1914         {
1915             // We have to add an AC3 header in front of the data. Add its
1916             // size to the PES packet length.
1917             plen += 4;
1918             tdat[4] = plen >> 8;
1919             tdat[5] = plen;
1920
1921             // Write out the PES header
1922             int hdrsize = 9 + tdat[8];
1923             fwrite64(stream, tdat, hdrsize);
1924
1925             // add a four byte DVD ac3 stream header
1926             uint8_t ac3_substream_id[4];
1927             int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1928             ac3_substream_id[0] = 0x80 | ssid;  // substream id
1929             ac3_substream_id[1] = 0x01;         // number of sync words
1930             ac3_substream_id[2] = 0x00;         // first offset (16 bits)
1931             ac3_substream_id[3] = 0x02;
1932             fwrite64(stream, ac3_substream_id, 4);
1933
1934             // add the rest of the data
1935             fwrite64(stream, tdat + hdrsize, stream->ts_pos[curstream] - hdrsize);
1936         }
1937         else
1938         {
1939             // not audio - don't need to modify the stream so write what we've got
1940             tdat[4] = plen >> 8;
1941             tdat[5] = plen;
1942             fwrite64( stream,  tdat, stream->ts_pos[curstream] );
1943         }
1944     }
1945     else
1946     {
1947         // data without a PES start header needs a simple 'continuation'
1948         // PES header. AC3 audio also needs its substream header.
1949         if ( stream->ts_stream_type[curstream] != 0x81)
1950         {
1951             make_pes_header(stream, stream->ts_pos[curstream],
1952                             stream->ts_streamid[curstream]);
1953         }
1954         else
1955         {
1956             make_pes_header(stream, stream->ts_pos[curstream] + 4,
1957                             stream->ts_streamid[curstream]);
1958
1959             // add a four byte DVD ac3 stream header
1960             uint8_t ac3_substream_id[4];
1961             int ssid = (curstream - stream->ts_number_video_pids) & 0xf;
1962             ac3_substream_id[0] = 0x80 | ssid;  // substream id
1963             ac3_substream_id[1] = 0x01;         // number of sync words
1964             ac3_substream_id[2] = 0x00;         // first offset (16 bits)
1965             ac3_substream_id[3] = 0x02;
1966             fwrite64(stream, ac3_substream_id, 4);
1967         }
1968         fwrite64( stream, tdat, stream->ts_pos[curstream] );
1969     }
1970
1971     // Write padding
1972     int left = HB_DVD_READ_BUFFER_SIZE - len;
1973     if ( left >= 8 )
1974     {
1975         pad_buffer(stream, left);
1976     }
1977
1978     stream->ts_pos[curstream] = 0;
1979 }
1980
1981 static int isIframe( hb_stream_t *stream, const uint8_t *buf, int adapt_len )
1982 {
1983     // For mpeg2: look for a gop start or i-frame picture start
1984     // for h.264: look for idr nal type or a slice header for an i-frame
1985     // for vc1:   ???
1986     int i;
1987     uint32_t strid = 0;
1988
1989
1990     if ( stream->ts_stream_type[0] <= 2 )
1991     {
1992         // This section of the code handles MPEG-1 and MPEG-2 video streams
1993         for (i = 13 + adapt_len; i < 188; i++)
1994         {
1995             strid = (strid << 8) | buf[i];
1996             if ( ( strid >> 8 ) == 1 )
1997             {
1998                 // we found a start code
1999                 uint8_t id = strid;
2000                 switch ( id )
2001                 {
2002                     case 0xB8: // group_start_code (GOP header)
2003                     case 0xB3: // sequence_header code
2004                         return 1;
2005
2006                     case 0x00: // picture_start_code
2007                         // picture_header, let's see if it's an I-frame
2008                         if (i<185)
2009                         {
2010                             // check if picture_coding_type == 1
2011                             if ((buf[i+2] & (0x7 << 3)) == (1 << 3))
2012                             {
2013                                 // found an I-frame picture
2014                                 return 1;
2015                             }
2016                         }
2017                         break;
2018                 }
2019             }
2020         }
2021         // didn't find an I-frame
2022         return 0;
2023     }
2024     if ( stream->ts_stream_type[0] == 0x1b )
2025     {
2026         // we have an h.264 stream 
2027         for (i = 13 + adapt_len; i < 188; i++)
2028         {
2029             strid = (strid << 8) | buf[i];
2030             if ( ( strid >> 8 ) == 1 )
2031             {
2032                 // we found a start code - remove the ref_idc from the nal type
2033                 uint8_t nal_type = strid & 0x1f;
2034                 if ( nal_type == 0x05 )
2035                     // h.264 IDR picture start
2036                     return 1;
2037
2038                 if ( nal_type == 0x01 )
2039                 {
2040                     // h.264 slice: has to be start MB 0 & type I (2, 4, 7 or 9)
2041                     uint8_t id = buf[i+1];
2042                     if ( ( id >> 4 ) == 0x0b || ( id >> 2 ) == 0x25 ||
2043                          id == 0x88 || id == 0x8a )
2044                     {
2045                         return 1;
2046                     }
2047                 }
2048             }
2049         }
2050         // didn't find an I-frame
2051         return 0;
2052     }
2053
2054     // we don't understand the stream type so just say "yes" otherwise
2055     // we'll discard all the video.
2056     return 1;
2057 }
2058
2059 /***********************************************************************
2060  * hb_ts_stream_decode
2061  ***********************************************************************
2062  *
2063  **********************************************************************/
2064 static int hb_ts_stream_decode( hb_stream_t *stream, uint8_t *obuf )
2065 {
2066     /*
2067      * stash the output buffer pointer in our stream so we don't have to
2068      * pass it & its original value to everything we call.
2069      */
2070     stream->fwrite_buf = obuf;
2071     stream->fwrite_buf_orig = obuf;
2072
2073         // spin until we get a packet of data from some stream or hit eof
2074         while ( 1 )
2075         {
2076         int64_t pcr = stream->ts_lastpcr;
2077         int curstream;
2078
2079         const uint8_t *buf = next_packet(stream);
2080         if ( buf == NULL )
2081         {
2082             // end of file - we didn't finish filling our ps write buffer
2083             // so just discard the remainder (the partial buffer is useless)
2084             hb_log("hb_ts_stream_decode - eof");
2085             return 0;
2086                 }
2087
2088         /* This next section validates the packet */
2089
2090                 // Get pid and use it to find stream state.
2091                 int pid = ((buf[1] & 0x1F) << 8) | buf[2];
2092         if ( ( curstream = index_of_pid( pid, stream ) ) < 0 )
2093             continue;
2094
2095                 // Get error
2096                 int errorbit = (buf[1] & 0x80) != 0;
2097                 if (errorbit)
2098                 {
2099                         ts_err( stream, curstream,  "packet error bit set");
2100                         continue;
2101                 }
2102
2103                 // Get adaption header info
2104                 int adaption = (buf[3] & 0x30) >> 4;
2105                 int adapt_len = 0;
2106                 if (adaption == 0)
2107                 {
2108                         ts_err( stream, curstream,  "adaptation code 0");
2109                         continue;
2110                 }
2111                 else if (adaption == 0x2)
2112                         adapt_len = 184;
2113                 else if (adaption == 0x3)
2114                 {
2115                         adapt_len = buf[4] + 1;
2116                         if (adapt_len > 184)
2117                         {
2118                                 ts_err( stream, curstream,  "invalid adapt len %d", adapt_len);
2119                 continue;
2120                         }
2121                 }
2122
2123         // if there's an adaptation header & PCR_flag is set
2124         // get the PCR (Program Clock Reference)
2125         if ( adapt_len > 7 && ( buf[5] & 0x10 ) != 0 )
2126         {
2127             pcr = ( (uint64_t)buf[6] << (33 - 8) ) |
2128                   ( (uint64_t)buf[7] << (33 - 16) ) |
2129                   ( (uint64_t)buf[8] << (33 - 24) ) |
2130                   ( (uint64_t)buf[9] << (33 - 32) ) |
2131                   ( buf[10] >> 7 );
2132             stream->ts_nextpcr = pcr;
2133
2134             // remember the pcr across calls to this routine
2135             stream->ts_lastpcr = pcr;
2136         }
2137
2138         // If we don't have a pcr yet, the right thing to do here would
2139         // be a 'continue' so we don't process anything until we have a
2140         // clock reference. Unfortunately the HD Home Run appears to null
2141         // out the pcr field of some streams so we keep going & substitute
2142         // the video stream dts for the pcr when there's no pcr.
2143
2144                 // Get continuity
2145         // Continuity only increments for adaption values of 0x3 or 0x01
2146         // and is not checked for start packets.
2147
2148                 int start = (buf[1] & 0x40) != 0;
2149
2150         if ( (adaption & 0x01) != 0 )
2151                 {
2152             int continuity = (buf[3] & 0xF);
2153             if ( continuity == stream->ts_streamcont[curstream] )
2154             {
2155                 // we got a duplicate packet (usually used to introduce
2156                 // a PCR when one is needed). The only thing that can
2157                 // change in the dup is the PCR which we grabbed above
2158                 // so ignore the rest.
2159                 continue;
2160             }
2161             if ( !start && (stream->ts_streamcont[curstream] != -1) &&
2162                  stream->ts_foundfirst[curstream] &&
2163                  (continuity != ( (stream->ts_streamcont[curstream] + 1) & 0xf ) ) )
2164                         {
2165                                 ts_err( stream, curstream,  "continuity error: got %d expected %d",
2166                         (int)continuity,
2167                         (stream->ts_streamcont[curstream] + 1) & 0xf );
2168                 stream->ts_streamcont[curstream] = continuity;
2169                                 continue;
2170                         }
2171                         stream->ts_streamcont[curstream] = continuity;
2172                 }
2173
2174         /* If we get here the packet is valid - process its data */
2175
2176         if ( start )
2177         {
2178             // Found a random access point (now we can start a frame/audio packet..)
2179
2180                         // If we were skipping a bad packet, start fresh on this new PES packet..
2181                         if (stream->ts_skipbad[curstream] == 1)
2182                         {
2183                 // video skips to an iframe after a bad packet to minimize
2184                 // screen corruption
2185                 if ( curstream == 0 && !isIframe( stream, buf, adapt_len ) )
2186                 {
2187                     continue;
2188                 }
2189                                 stream->ts_skipbad[curstream] = 0;
2190                         }
2191
2192                         // If we don't have video yet, check to see if this is an
2193             // i_frame (group of picture start)
2194                         if ( curstream == 0 )
2195             {
2196                 if ( !stream->ts_foundfirst[0] )
2197                 {
2198                     if ( !isIframe( stream, buf, adapt_len ) )
2199                     {
2200                         // didn't find an I frame
2201                         continue;
2202                     }
2203                     stream->ts_foundfirst[0] = 1;
2204                 }
2205                 ++stream->frames;
2206
2207                 // if we don't have a pcr yet use the dts from this frame
2208                 if ( pcr == -1 )
2209                 {
2210                     // PES must begin with an mpeg start code & contain
2211                     // a DTS or PTS.
2212                     uint8_t *pes = buf + adapt_len + 4;
2213                     if ( pes[0] != 0x00 || pes[1] != 0x00 || pes[2] != 0x01 ||
2214                          ( pes[7] >> 6 ) == 0 )
2215                     {
2216                         continue;
2217                     }
2218                     // if we have a dts use it otherwise use the pts
2219                     pes += (pes[7] & 0x40)? 9 : 14;
2220
2221                     pcr = ( ( (uint64_t)pes[0] >> 1 ) & 7 << 30 ) |
2222                           ( (uint64_t)pes[1] << 22 ) |
2223                           ( ( (uint64_t)pes[2] >> 1 ) << 15 ) |
2224                           ( (uint64_t)pes[3] << 7 ) |
2225                           ( (uint64_t)pes[4] >> 1 );
2226                     stream->ts_nextpcr = pcr;
2227                 }
2228             }
2229             else if ( ! stream->ts_foundfirst[curstream] )
2230             {
2231                 // start other streams only after first video frame found.
2232                 if ( ! stream->ts_foundfirst[0] )
2233                 {
2234                     continue;
2235                 }
2236                 stream->ts_foundfirst[curstream] = 1;
2237                         }
2238
2239             // If we have some data already on this stream, turn it into
2240             // a program stream packet. Then add the payload for this
2241             // packet to the current pid's buffer.
2242             if ( stream->ts_pos[curstream] )
2243             {
2244                 generate_output_data(stream, curstream);
2245                 stream->ts_start[curstream] = 1;
2246                 memcpy(stream->ts_buf[curstream],
2247                        buf + 4 + adapt_len, 184 - adapt_len);
2248                 stream->ts_pos[curstream] = 184 - adapt_len;
2249                 return 1;
2250             }
2251             stream->ts_start[curstream] = 1;
2252         }
2253
2254                 // Add the payload for this packet to the current buffer
2255                 if (!stream->ts_skipbad[curstream] && stream->ts_foundfirst[curstream] &&
2256             (184 - adapt_len) > 0)
2257                 {
2258                         memcpy(stream->ts_buf[curstream] + stream->ts_pos[curstream],
2259                    buf + 4 + adapt_len, 184 - adapt_len);
2260                         stream->ts_pos[curstream] += 184 - adapt_len;
2261
2262             // if the next TS packet could possibly overflow our 2K output buffer
2263             // we need to generate a packet now. Overflow would be 184 bytes of
2264             // data + the 9 byte PES hdr + the 14 byte PACK hdr = 211 bytes.
2265             if ( stream->ts_pos[curstream] >= (HB_DVD_READ_BUFFER_SIZE - 216) )
2266             {
2267                 // we have enough data to make a PS packet
2268                 generate_output_data(stream, curstream);
2269                 return 1;
2270             }
2271                 }
2272         }
2273 }
2274
2275 static void hb_ts_stream_reset(hb_stream_t *stream)
2276 {
2277         int i;
2278
2279         for (i=0; i < kMaxNumberDecodeStreams; i++)
2280         {
2281                 stream->ts_pos[i] = 0;
2282                 stream->ts_foundfirst[i] = 0;
2283                 stream->ts_skipbad[i] = 0;
2284                 stream->ts_streamcont[i] = -1;
2285                 stream->ts_start[i] = 0;
2286         }
2287
2288     stream->ts_lastpcr = -1;
2289     stream->ts_nextpcr = -1;
2290
2291     stream->frames = 0;
2292     stream->errors = 0;
2293     stream->last_error_frame = -10000;
2294     stream->last_error_count = 0;
2295
2296     align_to_next_packet(stream);
2297 }
2298
2299 // ------------------------------------------------------------------
2300 // Support for reading media files via the ffmpeg libraries.
2301
2302 static void ffmpeg_add_codec( hb_stream_t *stream, int stream_index )
2303 {
2304     // add a codec to the context here so it will be there when we
2305     // read the first packet.
2306     AVCodecContext *context = stream->ffmpeg_ic->streams[stream_index]->codec;
2307     context->workaround_bugs = FF_BUG_AUTODETECT;
2308     context->error_resilience = 1;
2309     context->error_concealment = FF_EC_GUESS_MVS|FF_EC_DEBLOCK;
2310     AVCodec *codec = avcodec_find_decoder( context->codec_id );
2311     avcodec_open( context, codec );
2312 }
2313
2314 // The ffmpeg stream reader / parser shares a lot of state with the 
2315 // decoder via a codec context kept in the AVStream of the reader's
2316 // AVFormatContext. Since decoding is done in a different thread we
2317 // have to somehow pass this codec context to the decoder and we have
2318 // to do it before the first packet is read (so we can't put the info
2319 // in the buf we'll send downstream). Decoders don't have any way to
2320 // get to the stream directly (they're not passed the title or job
2321 // pointers during a scan) so this is a back door for the decoder to
2322 // get the codec context. We just stick the stream pointer in the next
2323 // slot an array of pointers maintained as a circular list then return
2324 // the index into the list combined with the ffmpeg stream index as the
2325 // codec_param that will be passed to the decoder init routine. We make
2326 // the list 'big' (enough for 1024 simultaneously open ffmpeg streams)
2327 // so that we don't have to do a complicated allocator or worry about
2328 // deleting entries on close. 
2329 //
2330 // Entries can only be added to this list during a scan and are never
2331 // deleted so the list access doesn't require locking.
2332 static hb_stream_t **ffmpeg_streams;    // circular list of stream pointers
2333 static int ffmpeg_stream_cur;           // where we put the last stream pointer
2334 #define ffmpeg_sl_bits (10)             // log2 stream list size (in entries)
2335 #define ffmpeg_sl_size (1 << ffmpeg_sl_bits)
2336
2337 // add a stream to the list & return the appropriate codec_param to access it
2338 static int ffmpeg_codec_param( hb_stream_t *stream, int stream_index )
2339 {
2340     if ( !ffmpeg_streams )
2341     {
2342         ffmpeg_streams = calloc( ffmpeg_sl_size, sizeof(stream) );
2343     }
2344
2345     // the title scan adds all the ffmpeg media streams at once so we
2346     // only add a new entry to our stream list if the stream is different
2347     // than last time.
2348     int slot = ffmpeg_stream_cur;
2349     if ( ffmpeg_streams[slot] != stream )
2350     {
2351         // new stream - put it in the next slot of the stream list
2352         slot = ++ffmpeg_stream_cur & (ffmpeg_sl_size - 1);
2353         ffmpeg_streams[slot] = stream;
2354     }
2355
2356     ffmpeg_add_codec( stream, stream_index );
2357
2358     return ( stream_index << ffmpeg_sl_bits ) | slot;
2359 }
2360
2361 // we're about to open 'title' to convert it - remap the stream associated
2362 // with the video & audio codec params of the title to refer to 'stream'
2363 // (the original scan stream was closed and no longer exists).
2364 static void ffmpeg_remap_stream( hb_stream_t *stream, hb_title_t *title )
2365 {
2366     // tell ffmpeg we want a pts on every frame it returns
2367     stream->ffmpeg_ic->flags |= AVFMT_FLAG_GENPTS;
2368
2369     // all the video & audio came from the same stream so remapping
2370     // the video's stream slot takes care of everything.
2371     int slot = title->video_codec_param & (ffmpeg_sl_size - 1);
2372     ffmpeg_streams[slot] = stream;
2373
2374     // add codecs for all the streams used by the title
2375     ffmpeg_add_codec( stream, title->video_codec_param >> ffmpeg_sl_bits );
2376
2377     int i;
2378     hb_audio_t *audio;
2379     for ( i = 0; ( audio = hb_list_item( title->list_audio, i ) ); ++i )
2380     {
2381         if ( audio->config.in.codec == HB_ACODEC_FFMPEG )
2382         {
2383             ffmpeg_add_codec( stream,
2384                               audio->config.in.codec_param >> ffmpeg_sl_bits );
2385         }
2386     }
2387 }
2388
2389 void *hb_ffmpeg_context( int codec_param )
2390 {
2391     int slot = codec_param & (ffmpeg_sl_size - 1);
2392     int stream_index = codec_param >> ffmpeg_sl_bits;
2393     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index]->codec;
2394 }
2395
2396 void *hb_ffmpeg_avstream( int codec_param )
2397 {
2398     int slot = codec_param & (ffmpeg_sl_size - 1);
2399     int stream_index = codec_param >> ffmpeg_sl_bits;
2400     return ffmpeg_streams[slot]->ffmpeg_ic->streams[stream_index];
2401 }
2402
2403 static AVFormatContext *ffmpeg_deferred_close;
2404
2405 static int ffmpeg_open( hb_stream_t *stream, hb_title_t *title )
2406 {
2407     if ( ffmpeg_deferred_close )
2408     {
2409         av_close_input_file( ffmpeg_deferred_close );
2410         ffmpeg_deferred_close = NULL;
2411     }
2412     AVFormatContext *ic;
2413
2414     av_log_set_level( AV_LOG_ERROR );
2415     if ( av_open_input_file( &ic, stream->path, NULL, 0, NULL ) < 0 )
2416     {
2417         return 0;
2418     }
2419     if ( av_find_stream_info( ic ) < 0 )
2420         goto fail;
2421
2422     stream->ffmpeg_ic = ic;
2423     stream->hb_stream_type = ffmpeg;
2424     stream->ffmpeg_pkt = malloc(sizeof(*stream->ffmpeg_pkt));
2425     av_init_packet( stream->ffmpeg_pkt );
2426
2427     if ( title )
2428     {
2429         // we're opening for read. scan passed out codec params that
2430         // indexed its stream so we need to remap them so they point
2431         // to this stream.
2432         ffmpeg_remap_stream( stream, title );
2433         ffmpeg_seek( stream, 0. );
2434         av_log_set_level( AV_LOG_ERROR );
2435     }
2436     else
2437     {
2438         // we're opening for scan. let ffmpeg put some info into the
2439         // log about what we've got.
2440         av_log_set_level( AV_LOG_INFO );
2441         dump_format( ic, 0, stream->path, 0 );
2442         av_log_set_level( AV_LOG_ERROR );
2443
2444         // accept this file if it has at least one video stream we can decode
2445         int i;
2446         for (i = 0; i < ic->nb_streams; ++i )
2447         {
2448             if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO )
2449             {
2450                 break;
2451             }
2452         }
2453         if ( i >= ic->nb_streams )
2454             goto fail;
2455     }
2456     return 1;
2457
2458   fail:
2459     av_close_input_file( ic );
2460     return 0;
2461 }
2462
2463 static void ffmpeg_close( hb_stream_t *d )
2464 {
2465     // XXX since we're sharing the CodecContext with the downstream
2466     // decoder proc we can't close the stream. We need to reference count
2467     // this so we can close it when both are done with their instance but
2468     // for now just defer the close until the next stream open or close.
2469     if ( ffmpeg_deferred_close )
2470     {
2471         av_close_input_file( ffmpeg_deferred_close );
2472     }
2473     ffmpeg_deferred_close = d->ffmpeg_ic;
2474     if ( d->ffmpeg_pkt != NULL )
2475     {
2476         free( d->ffmpeg_pkt );
2477         d->ffmpeg_pkt = NULL;
2478     }
2479 }
2480
2481 static void add_ffmpeg_audio( hb_title_t *title, hb_stream_t *stream, int id )
2482 {
2483     AVStream *st = stream->ffmpeg_ic->streams[id];
2484     AVCodecContext *codec = st->codec;
2485
2486     // scan will ignore any audio without a bitrate. Since we've already
2487     // typed the audio in order to determine its codec we set up the audio
2488     // paramters here.
2489     if ( codec->bit_rate || codec->sample_rate )
2490     {
2491         static const int chan2layout[] = {
2492             HB_INPUT_CH_LAYOUT_MONO,  // We should allow no audio really.
2493             HB_INPUT_CH_LAYOUT_MONO,   
2494             HB_INPUT_CH_LAYOUT_STEREO,
2495             HB_INPUT_CH_LAYOUT_2F1R,   
2496             HB_INPUT_CH_LAYOUT_2F2R,
2497             HB_INPUT_CH_LAYOUT_3F2R,   
2498             HB_INPUT_CH_LAYOUT_4F2R,
2499             HB_INPUT_CH_LAYOUT_STEREO, 
2500             HB_INPUT_CH_LAYOUT_STEREO,
2501         };
2502
2503         hb_audio_t *audio = calloc( 1, sizeof(*audio) );;
2504
2505         audio->id = id;
2506         if ( codec->codec_id == CODEC_ID_AC3 )
2507         {
2508             audio->config.in.codec = HB_ACODEC_AC3;
2509         }
2510         else
2511         {
2512             audio->config.in.codec = HB_ACODEC_FFMPEG;
2513             audio->config.in.codec_param = ffmpeg_codec_param( stream, id );
2514
2515             audio->config.in.bitrate = codec->bit_rate? codec->bit_rate : 1;
2516             audio->config.in.samplerate = codec->sample_rate;
2517             audio->config.in.channel_layout = chan2layout[codec->channels & 7];
2518         }
2519
2520         set_audio_description( audio, lang_for_code2( st->language ) );
2521
2522         hb_list_add( title->list_audio, audio );
2523     }
2524 }
2525
2526 static hb_title_t *ffmpeg_title_scan( hb_stream_t *stream )
2527 {
2528     AVFormatContext *ic = stream->ffmpeg_ic;
2529
2530     // 'Barebones Title'
2531     hb_title_t *title = hb_title_init( stream->path, 0 );
2532     title->index = 1;
2533
2534         // Copy part of the stream path to the title name
2535         char *sep = strrchr(stream->path, '/');
2536         if (sep)
2537                 strcpy(title->name, sep+1);
2538         char *dot_term = strrchr(title->name, '.');
2539         if (dot_term)
2540                 *dot_term = '\0';
2541
2542     uint64_t dur = ic->duration * 90000 / AV_TIME_BASE;
2543     title->duration = dur;
2544     dur /= 90000;
2545     title->hours    = dur / 3600;
2546     title->minutes  = ( dur % 3600 ) / 60;
2547     title->seconds  = dur % 60;
2548
2549     // One Chapter
2550     hb_chapter_t * chapter;
2551     chapter = calloc( sizeof( hb_chapter_t ), 1 );
2552     chapter->index = 1;
2553     chapter->duration = title->duration;
2554     chapter->hours = title->hours;
2555     chapter->minutes = title->minutes;
2556     chapter->seconds = title->seconds;
2557     hb_list_add( title->list_chapter, chapter );
2558
2559     // set the title to decode the first video stream in the file
2560     title->demuxer = HB_NULL_DEMUXER;
2561     title->video_codec = 0;
2562     int i;
2563     for (i = 0; i < ic->nb_streams; ++i )
2564     {
2565         if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO &&
2566              avcodec_find_decoder( ic->streams[i]->codec->codec_id ) &&
2567              title->video_codec == 0 )
2568         {
2569             title->video_id = i;
2570
2571             // We have to use the 'internal' avcodec decoder because
2572             // it needs to share the codec context from this video
2573             // stream. The parser internal to av_read_frame
2574             // passes a bunch of state info to the decoder via the context.
2575             title->video_codec = WORK_DECAVCODECVI;
2576             title->video_codec_param = ffmpeg_codec_param( stream, i );
2577         }
2578         else if ( ic->streams[i]->codec->codec_type == CODEC_TYPE_AUDIO &&
2579                   avcodec_find_decoder( ic->streams[i]->codec->codec_id ) )
2580         {
2581             add_ffmpeg_audio( title, stream, i );
2582         }
2583     }
2584
2585     title->container_name = strdup( ic->iformat->name );
2586     title->data_rate = ic->bit_rate;
2587
2588     return title;
2589 }
2590
2591 static int64_t av_to_hb_pts( int64_t pts, double conv_factor )
2592 {
2593     if ( pts == AV_NOPTS_VALUE )
2594         return -1;
2595     return (int64_t)( (double)pts * conv_factor );
2596 }
2597
2598 static int ffmpeg_read( hb_stream_t *stream, hb_buffer_t *buf )
2599 {
2600     int err;
2601     if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
2602     {
2603         // XXX the following conditional is to handle avi files that
2604         // use M$ 'packed b-frames' and occasionally have negative
2605         // sizes for the null frames these require.
2606         if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
2607             // eof
2608             return 0;
2609     }
2610     if ( stream->ffmpeg_pkt->size <= 0 )
2611     {
2612         // M$ "invalid and inefficient" packed b-frames require 'null frames'
2613         // following them to preserve the timing (since the packing puts two
2614         // or more frames in what looks like one avi frame). The contents and
2615         // size of these null frames are ignored by the ff_h263_decode_frame
2616         // as long as they're < 20 bytes. We need a positive size so we use
2617         // one byte if we're given a zero or negative size. We don't know
2618         // if the pkt data points anywhere reasonable so we just stick a
2619         // byte of zero in our outbound buf.
2620         buf->size = 1;
2621         *buf->data = 0;
2622     }
2623     else
2624     {
2625         if ( stream->ffmpeg_pkt->size > buf->alloc )
2626         {
2627             // need to expand buffer
2628             hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
2629         }
2630         memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
2631         buf->size = stream->ffmpeg_pkt->size;
2632     }
2633     buf->id = stream->ffmpeg_pkt->stream_index;
2634
2635     // if we haven't done it already, compute a conversion factor to go
2636     // from the ffmpeg timebase for the stream to HB's 90KHz timebase.
2637     double tsconv = stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index];
2638     if ( ! tsconv )
2639     {
2640         AVStream *s = stream->ffmpeg_ic->streams[stream->ffmpeg_pkt->stream_index];
2641         tsconv = 90000. * (double)s->time_base.num / (double)s->time_base.den;
2642         stream->ffmpeg_tsconv[stream->ffmpeg_pkt->stream_index] = tsconv;
2643     }
2644
2645     buf->start = av_to_hb_pts( stream->ffmpeg_pkt->pts, tsconv );
2646     buf->renderOffset = av_to_hb_pts( stream->ffmpeg_pkt->dts, tsconv );
2647     if ( buf->renderOffset >= 0 && buf->start == -1 )
2648     {
2649         buf->start = buf->renderOffset;
2650     }
2651     av_free_packet( stream->ffmpeg_pkt );
2652     return 1;
2653 }
2654
2655 static int ffmpeg_seek( hb_stream_t *stream, float frac )
2656 {
2657     AVFormatContext *ic = stream->ffmpeg_ic;
2658     int64_t pos = (double)ic->duration * (double)frac;
2659     av_seek_frame( ic, -1, pos, pos? 0 : AVSEEK_FLAG_BACKWARD );
2660     return 1;
2661 }