OSDN Git Service

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