OSDN Git Service

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