bunch-o compiler bitch'n
[goodguy/history.git] / cinelerra-5.1 / libzmpeg3 / libzmpeg3.h
1 #ifndef LIBMPEG3_H
2 #define LIBMPEG3_H
3
4 /* for quicktime build */
5 #define MAXFRAMESAMPLES 65536
6 #define ZDVB
7 #define USE_FUTEX
8
9 #ifndef __STDC_LIMIT_MACROS
10 #define __STDC_LIMIT_MACROS
11 #endif
12
13 #include <stdio.h>
14 #include <stdint.h>
15
16 typedef int (*zthumbnail_cb)(void *p, int trk);
17 typedef int (*zcc_text_cb)(int sid, int id, int sfrm, int efrm, const char *txt);
18
19 #ifdef __cplusplus
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <byteswap.h>
23 #include <dirent.h>
24 #include <fcntl.h>
25 #include <string.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <endian.h>
29 #include <signal.h>
30 #include <pthread.h>
31 #include <mntent.h>
32 #include <linux/cdrom.h>
33 #include <sys/ioctl.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <sys/syscall.h>
38 #ifdef USE_FUTEX
39 #include <linux/futex.h>
40 #endif
41
42 extern "C" {
43 #include "a52.h"
44 }
45
46 #define ZMPEG3_MAJOR   2
47 #define ZMPEG3_MINOR   0
48 #define ZMPEG3_RELEASE 0
49 #define ZRENDERFARM_FS_PREFIX "vfs://"
50
51 #define ZIO_SINGLE_ACCESS zfs_t::io_SINGLE_ACCESS
52 #define ZIO_UNBUFFERED zfs_t::io_UNBUFFERED
53 #define ZIO_NONBLOCK zfs_t::io_NONBLOCK
54 #define ZIO_SEQUENTIAL zfs_t::io_SEQUENTIAL
55 #define ZIO_THREADED zfs_t::io_THREADED
56 #define ZIO_ERRFAIL zfs_t::io_ERRFAIL
57 #define ZIO_RETRIES 1
58
59 #define TOC_SAMPLE_OFFSETS zmpeg3_t::show_toc_SAMPLE_OFFSETS
60 #define TOC_AUDIO_INDEX zmpeg3_t::show_toc_AUDIO_INDEX
61 #define TOC_FRAME_OFFSETS zmpeg3_t::show_toc_FRAME_OFFSETS
62
63 #define ZMPEG3_PROC_CPUINFO "/proc/cpuinfo"
64 #if BYTE_ORDER == LITTLE_ENDIAN
65 #define ZMPEG3_LITTLE_ENDIAN 1
66 #else
67 #define ZMPEG3_LITTLE_ENDIAN 0
68 #endif
69
70 // Combine the pid and the stream id into one unit
71 #define CUSTOM_ID(pid, stream_id) (((pid << 8) | stream_id) & 0xffff)
72 #define CUSTOM_ID_PID(id) (id >> 8)
73 #define CUSTOM_ID_STREAMID(id) (id & 0xff)
74
75 #ifndef ZMAX
76 #define ZMAX(a, b) ((a) > (b) ? (a) : (b))
77 #endif
78
79 #ifndef ZMIN
80 #define ZMIN(a, b) ((a) < (b) ? (a) : (b))
81 #endif
82
83 #ifndef isizeof
84 #define isizeof(x) ((int)sizeof(x))
85 #endif
86 #ifndef lengthof
87 #define lengthof(x) ((int)(sizeof(x)/sizeof(x[0])))
88 #endif
89
90 #define zlikely(x)   __builtin_expect((x),1)
91 #define zunlikely(x) __builtin_expect((x),0)
92
93 #define bcd(n) ((((n)>>4)&0x0f)*10+((n)&0x0f))
94
95 #define new_memset(s) \
96   void *operator new(size_t n) { \
97     void * volatile t = (void*) new char[n]; \
98     memset(t,s,n); \
99     return t; \
100   } \
101   void operator delete(void *t,size_t n) { \
102     delete[](char*)t; \
103   } \
104   void *operator new[](size_t n) { \
105     void * volatile t = (void*) new char[n]; \
106     memset(t,s,n); \
107     return t; \
108   } \
109   void operator delete[](void *t,size_t n) { \
110     delete[](char*)t; \
111   }
112
113 #define znew(T,n) ((T*)memset(new T[n],0,(n)*sizeof(T)))
114 #define zmsg(fmt) printf("%s: " fmt, __func__)
115 #define zmsgs(fmt,args...) printf("%s: " fmt, __func__, args)
116 #define zerr(fmt) fprintf(stderr,"%s:err " fmt, __func__)
117 #define zerrs(fmt,args...) fprintf(stderr,"%s:err " fmt, __func__, args)
118 #define perr(fmt) do { char msg[512]; \
119  snprintf(&msg[0],sizeof(msg), "%s: " fmt,__func__); perror(&msg[0]); \
120 } while(0)
121 #define perrs(fmt,args...) do { char msg[512]; \
122  snprintf(&msg[0],sizeof(msg), "%s: " fmt,__func__,args); perror(&msg[0]); \
123 } while(0)
124
125 class zmpeg3_t;
126
127 class zmpeg3_t {
128 public:
129   new_memset(0);
130   class zlock_t;
131   class zblock_t;
132   class zrwlock_t;
133   class fs_t;
134   class bits_t;
135   class index_t;
136   class bitfont_t;
137   class timecode_t;
138   class audio_t;
139   class slice_buffer_t;
140   class video_t;
141   class slice_decoder_t;
142   class subtitle_t;
143   class demuxer_t;
144   class cacheframe_t;
145   class cache_t;
146   class atrack_t;
147   class vtrack_t;
148   class strack_t;
149 #ifdef ZDVB
150   class dvb_t;
151 #endif
152
153   enum {
154     // Error codes for the error_return variable
155     ERR_UNDEFINED_ERROR              = 1,
156     ERR_INVALID_TOC_VERSION          = 2,
157     ERR_TOC_DATE_MISMATCH            = 3,
158
159     TOC_PREFIX                       = 0x544f4320,
160     // This decreases with every new version
161     TOC_VERSION                      = 0x000000f9,
162     ID3_PREFIX                       = 0x494433,
163     IFO_PREFIX                       = 0x44564456,
164     // First byte to read when opening a file
165     START_BYTE                       = 0x0,
166     // Bytes read by mpeg3io at a time
167     MAX_IO_SIZE                      = 0x10000,
168     IO_SIZE                          = 0x80000,
169     SEQ_IO_SIZE                      = 0xc00000,
170     MAX_TS_PROBE                     = 0x800000,
171     MAX_PGM_PROBE                    = 0x800000,
172     // Largest possible packet
173     RAW_SIZE                         = 0x400000,
174     RIFF_CODE                        = 0x52494646,
175     BD_PACKET_SIZE                   = 192,
176     TS_PACKET_SIZE                   = 188,
177     DVD_PACKET_SIZE                  = 0x800,
178     ERR_PACKET_SIZE                  = 0x800,
179     IO_ERR_LIMIT                     = 2,
180     SYNC_BYTE                        = 0x47,
181     PROGRAM_END_CODE                 = 0x000001b9,
182     PACK_START_CODE                  = 0x000001ba,
183     SEQUENCE_START_CODE              = 0x000001b3,
184     SEQUENCE_END_CODE                = 0x000001b7,
185     SYSTEM_START_CODE                = 0x000001bb,
186     STRLEN                           = 1024,
187     // Maximum number of PIDs in one stream
188     PIDMAX                          = 256,
189     PROGRAM_ASSOCIATION_TABLE       = 0x00,
190     CONDITIONAL_ACCESS_TABLE        = 0x01,
191     PACKET_START_CODE_PREFIX        = 0x000001,
192     // NAV/PRIVATE_STREAM_2 are the same id
193     PRIVATE_STREAM_2                = 0xbf,
194     NAV_PACKET_STREAM               = 0xbf,
195     NAV_PCI_BYTES                   = 0x3d3,
196     NAV_DSI_BYTES                   = 0x3f9,
197     NAV_PCI_SSID                    = 0x00,
198     NAV_DSI_SSID                    = 0x01,
199     NAV_SRI_END_OF_CELL             = 0x3fffffff,
200     PADDING_STREAM                  = 0xbe,
201     GOP_START_CODE                  = 0x000001b8,
202     PICTURE_START_CODE              = 0x00000100,
203     EXT_START_CODE                  = 0x000001b5,
204     USER_START_CODE                 = 0x000001b2,
205     SLICE_MIN_START                 = 0x00000101,
206     SLICE_MAX_START                 = 0x000001af,
207     AC3_START_CODE                  = 0x0b77,
208     PCM_START_CODE                  = 0x7f7f807f,
209     MAX_CPUS                        = 256,
210     MAX_STREAMZ                     = 0x10000,
211     MAX_PACKSIZE                    = 262144,
212     MAX_CACHE_FRAMES                = 128,
213     // Maximum number of complete subtitles to buffer in a subtitle track
214     // or number of incomplete subtitles to buffer in demuxer.
215     MAX_SUBTITLES                   = 16,
216     // Positive difference before declaring timecodes discontinuous
217     CONTIGUOUS_THRESHOLD            = 10  ,
218     // Minimum number of seconds before interleaving programs
219     PROGRAM_THRESHOLD               = 5   ,
220     // Number of frames difference before absolute seeking
221     SEEK_THRESHOLD                  = 16  ,
222     // Size of chunk of audio in table of contents
223     AUDIO_CHUNKSIZE                 = 0x10000 ,
224     // Minimum amount of data required to read a video header in streaming mode.
225     VIDEO_STREAM_SIZE               = 0x100,
226     // Number of samples in audio history
227     AUDIO_HISTORY                   = 0x100000 ,
228     // max number of samples returned by decoder per input frame
229     AUDIO_MAX_DECODE                = 0x800 ,
230     // Range to scan for pts after byte seek
231     PTS_RANGE                       = 0x100000,
232     // stream type
233     FT_PROGRAM_STREAM               = 0x0001,
234     FT_TRANSPORT_STREAM             = 0x0002,
235     FT_AUDIO_STREAM                 = 0x0004,
236     FT_VIDEO_STREAM                 = 0x0008,
237     FT_IFO_FILE                     = 0x0010,
238     FT_BD_FILE                      = 0x0020,
239     SUBTITLE_HOLD_TIME              = 3,
240     CCAPTION_HOLD_TIME              = 15,
241   };
242
243   enum color_model {
244     // All color models supported for read_frame
245     cmdl_BGR888=0,
246     cmdl_BGRA8888=1,
247     cmdl_RGB565=2,
248     cmdl_RGB888=3,
249     cmdl_RGBA8888=4,
250     cmdl_RGBA16161616=5,
251     // Color models for the 601 to RGB conversion
252     // 601 not implemented for scalar code
253     cmdl_601_BGR888=7,
254     cmdl_601_BGRA8888=8,
255     cmdl_601_RGB888=9,
256     cmdl_601_RGBA8888=10,
257     cmdl_601_RGB565=11,
258     // next 2 are supported color models for read_yuvframe
259     //  also YVU420P/YVU422P with uv output_row ptrs reversed for read_frame
260     cmdl_YUV420P=12,
261     cmdl_YUV422P=13,
262     // the rest are supported color models for read_frame
263     cmdl_601_YUV420P=14,
264     cmdl_601_YUV422P=15,
265     cmdl_UYVY=16,
266     cmdl_YUYV=17,
267     cmdl_601_UYVY=18,
268     cmdl_601_YUYV=19,
269     cmdl_YUV888=20,
270     cmdl_YUVA8888=21,
271     cmdl_601_YUV888=22,
272     cmdl_601_YUVA8888=23,
273   };
274
275   // Values for audio input/output formats
276   enum audio_format {
277     afmt_IGNORE=-1,
278     afmt_UNKNOWN=0,
279     afmt_MPEG=1,
280     afmt_AC3=2,
281     afmt_PCM=3,
282     afmt_AAC=4,
283     afmt_JESUS=5,
284
285     atyp_NONE=0,
286     atyp_DOUBLE=1,
287     atyp_FLOAT=2,
288     atyp_INT=3,
289     atyp_SHORT=4,
290   };
291
292   // Table of contents sections
293   enum toc_section_type {
294     toc_FILE_TYPE_PROGRAM=0,
295     toc_FILE_TYPE_TRANSPORT=1,
296     toc_FILE_TYPE_AUDIO=2,
297     toc_FILE_TYPE_VIDEO=3,
298     toc_STREAM_AUDIO=4,
299     toc_STREAM_VIDEO=5,
300     toc_STREAM_SUBTITLE=6,
301     toc_OFFSETS_AUDIO=7,
302     toc_OFFSETS_VIDEO=8,
303     toc_ATRACK_COUNT=9,
304     toc_VTRACK_COUNT=10,
305     toc_STRACK_COUNT=11,
306     toc_TITLE_PATH=12,
307     toc_IFO_PALETTE=13,
308     toc_FILE_INFO=14,
309     toc_IFO_PLAYINFO=15,
310     toc_SRC_PROGRAM=16,
311   };
312
313
314 #ifdef USE_FUTEX
315 #define ZMPEG3_ZLOCK_INIT zzlock_t()
316   class zloc_t {
317   protected:
318     volatile int loc;
319     int zfutex(int op, int val, timespec *time=0) {
320       return syscall(SYS_futex,&loc,op,val,time,0,0);
321     }
322     int zyield();
323     int zgettid();
324   public:
325     int zwake(int nwakeups);
326     int zwait(int val);
327     int zwait() { return zwait(loc); }
328     static void zincr(volatile int &v) { /* atomic(++v) */
329       asm ( " lock incl %1\n" : "+m" (v) :: );
330     }
331     static void zdecr(volatile int &v) { /* atomic(--v) */
332       asm ( " lock decl %1\n" : "+m" (v) :: );
333     }
334     static char tdecr(volatile int &v) {
335       char ret; /* ret = atomic(--loc >= 0 ? 1 : 0) */
336       asm ( " lock decl %1\n setge %0\n" : "=r" (ret), "+m" (v) :: );
337       return ret;
338     }
339     static char tincr(volatile int &v) {
340       char ret; /* ret = atomic(++loc > 0 ? 1 : 0) */
341       asm ( " lock incl %1\n setg %0\n" : "=r" (ret), "+m" (v) :: );
342       return ret;
343     }
344     static int zcmpxchg(int old, int val, volatile int &v) {
345       int ret = old;
346       asm volatile( " lock\n cmpxchgl %2,%1\n"
347         : "+a" (ret), "+m" (v) :  "r" (val) : "memory" );
348       return ret;
349     }
350     static int zxchg(int val, volatile int &v) {
351       asm volatile( " xchgl %0,%1\n"
352         : "+r" (val), "+m" (v) :: "memory" );
353       return val;
354     }
355     static int zadd(int n, volatile int &v) {
356       int old, mod, val;
357       do { val = (old=v)+n; mod = zcmpxchg(old,val,v);
358       } while( mod != old );
359       return val;
360     }
361     static void zmfence() {
362       asm volatile ( " mfence\n" ::: "memory" );
363     }
364
365     zloc_t() : loc(-1) {}
366     ~zloc_t() {}
367   };
368
369   class zlock_t : zloc_t {
370   protected:
371     friend class zblock_t;
372     friend class zrwlock_t;
373     int zlock(int v);
374     int zunlock(int nwakeups=1);
375     static int zemsg1();
376   public:
377     int lock() {
378       int v, ret = zunlikely( (v=zcmpxchg(-1,0,loc)) >= 0 ) ? zlock(v) : 0;
379       return ret;
380     }
381     int unlock() {
382       if( zunlikely(loc < 0) ) { return zemsg1(); }
383       int v, ret = zunlikely( (v=zcmpxchg(0,-1,loc)) != 0 ) ? zunlock() : 0;
384       return ret;
385     }
386     zlock_t() {}
387     ~zlock_t() {}
388   };
389
390   class zblock_t : zlock_t {
391   public:
392     void block() { loc = 0; zwait(0); }
393     void unblock() { if( !loc ) { loc = -1; zwake(INT_MAX); } }
394     zblock_t() {}
395     ~zblock_t() {}
396   };
397
398   class zrwlock_t : zloc_t {
399     zlock_t lk;
400     void zenter();
401     void zleave();
402     void zwrite_enter(int r); // r==0: do nothing, r>0: write_lock
403     void zwrite_leave(int r); // r<0: write_lock while read_lock
404   public:
405     void enter() { zincr(loc); if( zunlikely( lk.loc >= 0 ) ) zenter(); }
406     void leave() { if( zunlikely( !tdecr(loc) ) ) zleave(); }
407     void write_enter(int r=1) { if( r ) zwrite_enter(r); }
408     void write_leave(int r=1) { if( r ) zwrite_leave(r); }
409     zrwlock_t() {}
410     ~zrwlock_t() {}
411   };
412
413 #else
414 #define ZMPEG3_ZLOCK_INIT { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }
415
416   class zlock_t {
417   protected:
418     pthread_mutex_t zlock;
419   public:
420     void lock() { pthread_mutex_lock(&zlock); }
421     void unlock() { pthread_mutex_unlock(&zlock); }
422     zlock_t() { pthread_mutex_init(&zlock, 0); }
423     ~zlock_t() { pthread_mutex_destroy(&zlock); }
424   };
425
426   class zblock_t {
427     pthread_mutex_t zblock;
428     pthread_cond_t cond;
429   public:
430     zblock_t() {
431       pthread_mutex_init(&zblock, 0);
432       pthread_cond_init(&cond, 0);
433     }
434     ~zblock_t() {
435       pthread_mutex_destroy(&zblock);
436       pthread_cond_destroy(&cond);
437     }
438     void block() {
439       pthread_mutex_lock(&zblock);
440       pthread_cond_wait(&cond, &zblock);
441       pthread_mutex_unlock(&zblock);
442     }
443     void unblock() { pthread_cond_broadcast(&cond); }
444   };
445
446   class zrwlock_t : zlock_t {
447     volatile pthread_t blocking;
448     volatile int users;
449     zlock_t lk;
450     pthread_cond_t cond;
451     void wait() { pthread_cond_wait(&cond, &zlock); }
452     void wake() { pthread_cond_signal(&cond); }
453     void zwrite_enter(int r);
454     void zwrite_leave(int r);
455   public:
456     void enter();
457     void leave();
458     void write_enter(int r=1) { if( r ) zwrite_enter(r); }
459     void write_leave(int r=1) { if( r ) zwrite_leave(r); }
460     int count() { return users; }
461
462     zrwlock_t() { pthread_cond_init(&cond, 0); }
463     ~zrwlock_t() { pthread_cond_destroy(&cond); }
464   };
465
466 #endif
467
468   // I/O
469
470   // Filesystem structure
471   // We buffer in IO_SIZE buffers.  Stream IO would require back
472   // buffering a buffer since the stream must be rewound for packet headers,
473   // sequence start codes, format parsing, decryption, and mpeg3cat.
474
475   class fs_t {
476     int sync() {
477       return buffer->sync(current_byte);
478     }
479     int enter() {
480       buffer->lock();
481       return sync();
482     }
483     void leave() {
484       buffer->unlock();
485     }
486   public:
487     new_memset(0);
488     class css_t;
489
490     class css_t { // Encryption object
491     public:
492       class playkey_t;
493       class keytext_t;
494
495       typedef uint8_t key_t[5];
496       typedef uint8_t blk_t[5];
497       class playkey_t {
498       public:
499         int offset;
500         key_t key;
501       };
502       class keytext_t {
503       public:
504         keytext_t *lt, *rt;
505         uint8_t ktxt[4], ctxt[10];
506         keytext_t(const uint8_t *kp, const uint8_t *cp) {
507           lt = rt = 0;
508           memcpy(&ktxt[0],kp,sizeof(ktxt));
509           memcpy(&ctxt[0],cp,sizeof(ctxt));
510         }
511         ~keytext_t() {}
512       } *key_root;
513       void add_key_text(const uint8_t *kp, const uint8_t *cp);
514       uint8_t *find_key_text(const uint8_t *kp);
515       int attack_pattern(uint8_t const *sec, uint8_t *key);
516       void del_keytexts(keytext_t *p);
517     private:
518       void css_engine(int v,uint8_t const *input, blk_t &output);
519       void crypt_key1(int v, blk_t &key);
520       void crypt_key2(blk_t &key);
521       void crypt_bus_key(blk_t &key);
522       int get_asf();
523       int authenticate_drive(key_t &key);
524       int hostauth(dvd_authinfo *ai);
525       int get_title_key(key_t &key);
526       int get_disk_key(key_t &key);
527       int validate(int do_title);
528       int validate_path(int do_title);
529       int decrypt_title_key(uint8_t *dkey, uint8_t *tkey);
530     public:
531       key_t key1;
532       key_t key2;
533       key_t keycheck;
534       key_t title_key;
535       int lba, fsz, agid, encrypted;
536       char device_path[STRLEN];    // Device where the file is located
537       uint8_t disk_key[DVD_PACKET_SIZE];
538       char challenge[10];
539       int varient;
540       int fd;
541       char path[STRLEN];
542
543       css_t();
544       ~css_t();
545
546       int get_keys(char *fpath);
547       int decrypt_packet(uint8_t *sector, int offset);
548       int crack_title_key(key_t &ckey, key_t &tkey);
549     } css;
550
551     enum access_strategy {
552       io_SINGLE_ACCESS=1,
553       io_UNBUFFERED=2,
554       io_NONBLOCK=4,
555       io_SEQUENTIAL=8,
556       io_THREADED=16,
557       io_ERRFAIL=32,
558     };
559
560     class buffer_t {
561       void unblock();
562       void block();
563       void reader();
564       static void *reader(void *the_buffer);
565       void writer();
566       static void *writer(void *the_buffer);
567       int64_t read_in(int64_t len);
568       int read_fin(int64_t len);
569       int wait_in(int64_t pos);
570       int seek_in(int64_t pos);
571       int seek_to(int64_t pos, int64_t len);
572       int read_to(int64_t pos);
573       zmpeg3_t *src;
574       zlock_t io_lock;          // buffer_t access lock
575       zblock_t io_block;        // buffer_t access block
576       int errs;                 // number of consecutive errors
577       uint8_t *data;            // Readahead buffer
578       int alloc;                // buffer byte allocate
579       int size;                 // defined bytes in buffer
580       int in;                   // buffer byte in, owned by read_in
581       int out;                  // buffer byte out
582       int64_t out_pos;          // file offset next byte from last read
583       int64_t file_pos;         // file position of next readable byte
584       int64_t file_nudge;       // sync position offset
585       int fin;                  // locked version of in, synced with file_pos
586       pthread_t the_reader;     // reader thread if io_THREADED
587       pthread_t the_writer;     // writer thread if io_THREADED and recording
588       pthread_t owner;          // for debugging
589       int restarted;            // reader restarted
590       int reader_done;          // reader thread termination flag
591       int writer_done;          // writer thread termination flag
592       int wout;                 // write record file buffer byte out
593       int64_t write_pos;        // file_pos written to recd_fd
594       zblock_t write_lock;      // write record block
595     public:
596       new_memset(0);
597       buffer_t(zmpeg3_t *zsrc, int access);
598       ~buffer_t();
599       int access_type;          // io_ flags
600       int paused;               // reader discard data
601       int do_restart;           // reader restart buffer
602       int ref_count;            // number of fs_t referencing this
603       int open_count;           // number of is_open fs_t
604       int fd;                   // unbuffered file descriptor
605       FILE *fp;                 // buffered file handle
606       int open_file(char *path);
607       void close_file();
608       void reset();
609       void restart(int lk=1);
610       int64_t tell() { return out_pos; }
611       int64_t file_tell() { return file_pos; }
612       int sync(int64_t pos);
613       int errors() { return errs; }
614       uint32_t next_byte() {
615         return data[out];
616       }
617       uint32_t get_byte() {
618         uint32_t result = next_byte();
619         if( ++out >= alloc ) out = 0;
620         ++out_pos;
621         return result;
622       }
623       int read_out(uint8_t *bfr,int len);
624       int get_fd() {
625         return (access_type & io_UNBUFFERED) ? fd : fileno(fp);
626       }
627       void lock() {
628         if( (access_type & io_SINGLE_ACCESS) )
629           io_lock.lock();
630         if( !data ) data = new uint8_t[alloc];
631       }
632       void unlock() {
633         if( (access_type & io_SINGLE_ACCESS) )
634           io_lock.unlock();
635       }
636       void start_reader();
637       void stop_reader();
638       int start_record();
639       int stop_record();
640       int write_align(int sz);
641       void write_record(int sz, int mask);
642     } *buffer;
643
644     zmpeg3_t *src;
645     char path[STRLEN];
646     int64_t current_byte;       // Hypothetical position of file pointer
647     int64_t total_bytes;
648     int is_open;
649
650     fs_t(zmpeg3_t *zsrc, const char *fpath, int access=io_UNBUFFERED+io_SINGLE_ACCESS);
651     fs_t(zmpeg3_t *zsrc, int fd, int access=io_UNBUFFERED+io_SINGLE_ACCESS);
652     fs_t(zmpeg3_t *zsrc, FILE *fp, int access=io_SINGLE_ACCESS);
653     fs_t(fs_t &fs);
654     ~fs_t();
655     int open_file();
656     void close_file();
657     int errors() { return buffer ? buffer->errors() : 0; }
658     int get_fd() { return buffer ? buffer->get_fd() : -1; }
659     int read_data(uint8_t *bfr, int64_t len);
660     uint8_t next_char();
661     uint8_t read_char();
662     uint32_t read_uint16();
663     uint32_t read_uint24();
664     uint32_t read_uint32();
665     uint64_t read_uint64();
666     int seek(int64_t byte);
667     int seek_relative(int64_t bytes);
668     int64_t tell() { return current_byte; }
669     int64_t eof() { return current_byte >= total_bytes; }
670     int64_t bof() { return current_byte < 0; }
671     int64_t get_total_bytes();
672     int64_t ztotal_bytes() { return total_bytes; }
673     void chk_next() {
674       if( ++current_byte >= buffer->file_tell() ) sync();
675     }
676     void restart();
677     int pause_reader(int v);
678     int access() { return !buffer ? 0 : buffer->access_type; }
679     void sequential() { buffer->access_type |= io_SEQUENTIAL; }
680     int start_record(int bsz);
681     int stop_record();
682     void attach(fs_t *zfs);
683     void detach();
684     void close_buffer();
685   };
686
687
688   // Bitstream                                      
689   //    next bit in forward direction               
690   //  next bit in reverse direction |               
691   //                              v v               
692   // ... | | | | | | | | |1|1|1|1|1|1|              
693   //                     ^         ^                
694   //                     |         bit_number = 1   
695   //                     bfr_size = 6               
696
697   class bits_t {
698   public:
699     new_memset(0);
700     zmpeg3_t *src;
701     uint32_t bfr;   // bfr = buffer for bits
702     int bit_number; // position of pointer in bfr
703     int bfr_size;   // number of bits in bfr.  Should always be a multiple of 8
704     demuxer_t *demuxer; // Mpeg2 demuxer
705     uint8_t *input_ptr; // when input_ptr!=0, data is read from it instead of the demuxer.
706
707     bits_t(zmpeg3_t *zsrc, demuxer_t *demux);
708     ~bits_t();
709     int read_buffer(uint8_t *buffer, int byte);
710     void use_ptr(uint8_t *buffer);
711     int eos(uint8_t *ptr) {
712       return input_ptr - (bit_number+7)/8 >= ptr;
713     }
714     int eos(uint8_t *ptr,int bits) {
715       int n = bits - bit_number;
716       if( n <= 0 ) return 0;
717       return input_ptr + (n+7)/8 > ptr;
718     }
719     void use_demuxer();
720     void start_reverse();
721     void start_forward();
722     int refill_ptr();
723     int refill_noptr();
724     int refill() { return input_ptr ? refill_ptr() : refill_noptr(); }
725     int refill_reverse();
726     int open_title(int title);
727     int seek_byte(int64_t position);
728     void reset() { bfr_size = bit_number = 0; }
729     void reset(uint32_t v) { bfr = v; bfr_size = bit_number = 32; }
730     int get_bit_offset() { return bit_number & 7; }
731     void prev_byte_align() { bit_number = (bit_number+7) & ~7; }
732     void next_byte_align() { bit_number &= ~7; }
733     int bof() { return demuxer->zdata.bof() && demuxer->bof(); }
734     int eof() { return demuxer->zdata.eof() && demuxer->eof(); }
735     int error() { return demuxer->error(); }
736     int64_t tell();
737     int next_code(uint32_t zcode);
738     int prev_code(uint32_t zcode);
739     int next_start_code();
740     void pack_bits(uint32_t v, int n) {
741       bfr = (bfr << n) | v;
742       if( (bfr_size+=n) > (int)(8*sizeof(bfr)) )
743          bfr_size = 8*sizeof(bfr);
744       bit_number += n;
745     }
746     void pack_8bits(uint32_t v) { pack_bits(v, 8); }
747     void fill_bits_ptr(int bits) {
748       while( bit_number < bits ) { pack_8bits(*input_ptr++); }
749     }
750     void fill_bits_noptr(int bits) {
751       while( bit_number < bits ) { pack_8bits(demuxer->read_char()); }
752     }
753     void fill_bits(int bits) {
754       return input_ptr ? fill_bits_ptr(bits) : fill_bits_noptr(bits);
755     }
756     uint32_t show_bits_noptr(int bits) {
757       if( bits <= 0 ) return 0;
758       fill_bits_noptr(bits);
759       return (bfr >> (bit_number-bits)) & (0xffffffff >> (32-bits));
760     }
761     uint32_t show_bit_noptr(int bits) { return show_bits_noptr(1); }
762     uint32_t show_byte_noptr() { return show_bits_noptr(8); }
763     uint32_t show_bits24_noptr() { return show_bits_noptr(24); }
764     uint32_t show_bits32_noptr() { fill_bits_noptr(32); return bfr; }
765     int show_bits(int bits) {
766       if( bits <= 0 ) return 0;
767       fill_bits(bits);
768       return (bfr >> (bit_number-bits)) & (0xffffffff >> (32-bits));
769     }
770     uint32_t get_bits_noptr(int bits) {
771       uint32_t result = show_bits_noptr(bits);
772       bit_number -= bits;
773       return result;
774     }
775     uint32_t get_bit_noptr() { return get_bits_noptr(1); }
776     int get_bits(int bits) {
777       uint32_t result = show_bits(bits);
778       bit_number -= bits;
779       return result;
780     }
781     uint32_t get_byte_noptr() { return get_bits_noptr(8); }
782     uint32_t get_bits24_noptr() { return get_bits_noptr(24); }
783     void fill_bits_reverse(int bits) {
784       int n = (bit_number & ~7);
785       if( n ) { bfr >>= n;  bfr_size -= n;  bit_number -= n; }
786       n = bit_number + bits;
787       while( bfr_size < n ) {
788         uint32_t prev_byte = input_ptr ?
789           *--input_ptr : demuxer->read_prev_char();
790         bfr |= prev_byte << bfr_size;
791         bfr_size += 8;
792       }
793     }
794     int show_bits_reverse(int bits) {
795       fill_bits_reverse(bits);
796       return (bfr >> bit_number) & (0xffffffff >> (32 - bits));
797     }
798     int get_bits_reverse(int bits) {
799       uint32_t result = show_bits_reverse(bits);
800       bit_number += bits;
801       return result;
802     }
803   };
804
805
806   class index_t {
807   public:
808     new_memset(0);
809     float **index_data; // Buffer of frames for index.  A frame is a high/low pair.
810     int index_allocated; // Number of frames allocated in each index channel.
811     int index_channels; // Number of index channels allocated
812     int index_size; // Number of high/low pairs in index channel
813     int index_zoom; // Downsampling of index buffers when constructing index
814
815     index_t();
816     ~index_t();
817   };
818
819
820   class bitfont_t {
821   public:
822     class bitchar_t;
823     static bitfont_t *fonts[];
824     static int total_fonts;
825     static int font_refs;
826     static void init_fonts();
827     static void destroy_fonts();
828     class static_init_t {
829     public:
830       static_init_t();
831       ~static_init_t();
832     };
833     class bitchar_t {
834     public:
835       uint16_t ch;
836       int16_t left, right;
837       int16_t ascent, decent;
838       uint8_t *bitmap;
839     } *chrs;
840     int16_t nch, idx, idy, imy;
841   };
842   static bitfont_t *bitfont(int style,int pen_size,int italics,int size);
843
844   class timecode_t {
845   public:
846     new_memset(0);
847     int hour;
848     int minute;
849     int second;
850     int frame;
851
852     timecode_t() {}
853     ~timecode_t() {}
854   };
855
856
857   class audio_t {
858   public:
859     new_memset(0);
860     class imdct_complex_t;
861     class imdct_al_table_t;
862     class audio_decoder_layer_t;
863     class audio_decoder_ac3_t;
864     class audio_decoder_pcm_t;
865     class ac3audblk_t; /*???*/
866
867     enum {
868       AC3_N                          = 512,
869       MAXFRAMESIZE                   = 4096,
870       MAXFRAMESAMPLEZ                = MAXFRAMESAMPLES,
871       HDRCMPMASK                     = 0xfffffd00,
872       SBLIMIT                        = 32,
873       SSLIMIT                        = 18,
874       SCALE_BLOCK                    = 12,
875       MPEG3AUDIO_PADDING             = 1024,
876       MAX_AC3_FRAMESIZE              = 1920 * 2 + 512,
877     };
878
879     enum exponent_type { // Exponent strategy constants
880       exp_REUSE=0,
881       exp_D15=1,
882       exp_D25=2,
883       exp_D45=3,
884     };
885
886     enum delta_type { // Delta bit allocation constants
887       bit_REUSE=0,
888       bit_NEW=1,
889       bit_NONE=2,
890       bit_RESERVED=3,
891     };
892
893     enum mpg_md { // Values for mode
894       md_STEREO=0,
895       md_JOINT_STEREO=1,
896       md_DUAL_CHANNEL=2,
897       md_MONO=3,
898     };
899
900     enum { PCM_HEADERSIZE = 20, };
901
902     enum id3_state {
903       id3_IDLE=0, // No ID3 tag found
904       id3_HEADER=1, // Reading header
905       id3_SKIP=2, // Skipping ID3 tag
906     };
907
908     // IMDCT variables
909     class imdct_complex_t {
910     public:
911       float real;
912       float imag;
913     };
914
915     class imdct_al_table_t {
916     public:
917       short bits;
918       short d;
919     };
920
921     zmpeg3_t *src;
922     atrack_t *track;
923
924     class l3_info_t {
925     public:
926       int scfsi;
927       uint32_t part2_3_length;
928       uint32_t big_values;
929       uint32_t scalefac_compress;
930       uint32_t block_type;
931       uint32_t mixed_block_flag;
932       uint32_t table_select[3];
933       uint32_t subblock_gain[3];
934       uint32_t maxband[3];
935       uint32_t maxbandl;
936       uint32_t maxb;
937       uint32_t region1start;
938       uint32_t region2start;
939       uint32_t preflag;
940       uint32_t scalefac_scale;
941       uint32_t count1table_select;
942       float *full_gain[3];
943       float *pow2gain;
944     };
945
946     class l3_sideinfo_t {
947     public:
948       uint32_t main_data_begin;
949       uint32_t private_bits;
950       class { public: l3_info_t gr[2]; } ch[2];
951     };
952
953     class audio_decoder_layer_t {
954       static int tabsel_123[2][3][16];
955       static long freqs[9];
956       static float decwin[512 + 32];
957       static float cos64[16], cos32[8], cos16[4], cos8[2], cos4[1];
958       static float *pnts[5];
959       static int grp_3tab[32 * 3];   /* used: 27 */
960       static int grp_5tab[128 * 3];  /* used: 125 */
961       static int grp_9tab[1024 * 3]; /* used: 729 */
962       static float muls[27][64];     /* also used by layer 1 */
963       static float gainpow2[256 + 118 + 4];
964       static long intwinbase[257];
965       static float ispow[8207];
966       static float aa_ca[8], aa_cs[8];
967       static float win[4][36];
968       static float win1[4][36];
969       static float COS1[12][6];
970       static float COS9[9];
971       static float COS6_1, COS6_2;
972       static float tfcos36[9];
973       static float tfcos12[3];
974       static float cos9[3], cos18[3];
975       static float tan1_1[16], tan2_1[16], tan1_2[16], tan2_2[16];
976       static float pow1_1[2][16], pow2_1[2][16];
977       static float pow1_2[2][16], pow2_2[2][16];
978       static int longLimit[9][23];
979       static int shortLimit[9][14];
980       static class bandInfoStruct {
981       public:
982         int longIdx[23], longDiff[22];
983         int shortIdx[14], shortDiff[13];
984       } bandInfo[9];
985       static int mapbuf0[9][152];
986       static int mapbuf1[9][156];
987       static int mapbuf2[9][44];
988       static int *map[9][3];
989       static int *mapend[9][3];
990       static uint32_t n_slen2[512]; /* MPEG 2.0 slen for 'normal' mode */
991       static uint32_t i_slen2[256]; /* MPEG 2.0 slen for intensity stereo */
992
993       static short tab0 [  1], tab1 [  7], tab2  [17],  tab3[ 17];
994       static short tab5 [ 31], tab6 [ 31], tab7  [71],  tab8[ 71];
995       static short tab9 [ 71], tab10[127], tab11[127], tab12[127];
996       static short tab13[511], tab15[511], tab16[511], tab24[511];
997       static short tab_c0[31], tab_c1[31];
998       static class huffman_t {
999       public:
1000         unsigned int linbits;
1001         short *table;
1002       } ht[32], htc[2];
1003
1004       static int dct64_1(float *out0,float *out1,float *b1,float *b2,
1005         float *samples);
1006       static int dct64(float *a,float *b,float *c);
1007       static int dct36(float *inbuf,float *o1,float *o2,float *wintab,
1008         float *tsbuf);
1009       static int dct12(float *in,float *rawout1,float *rawout2,float *wi,
1010         float *ts);
1011
1012       int get_scale_factors_1(int *scf,l3_info_t *l3_info,int ch,int gr);
1013       int get_scale_factors_2(int *scf,l3_info_t *l3_info,int i_stereo);
1014       int dequantize_sample(float xr[SBLIMIT][SSLIMIT],int *scf,
1015          l3_info_t *l3_info,int sfreq,int part2bits);
1016       int get_side_info(l3_sideinfo_t *si,int channels,int ms_stereo,
1017          long sfreq,int single,int lsf);
1018       int hybrid(float fsIn[SBLIMIT][SSLIMIT],
1019          float tsOut[SSLIMIT][SBLIMIT],int ch,l3_info_t *l3_info);
1020       int antialias(float xr[SBLIMIT][SSLIMIT],l3_info_t *l3_info);
1021       int calc_i_stereo(float xr_buf[2][SBLIMIT][SSLIMIT],int *scalefac,
1022          l3_info_t *l3_info,int sfreq,int ms_stereo,int lsf);
1023       int synth_stereo(float *bandPtr,int channel,float *out, int *pnt);
1024       int init_audio(zmpeg3_t *zsrc, atrack_t *ztrack, int zformat);
1025       int synths_reset();
1026       int select_table();
1027       int step_one(uint8_t *bit_alloc, int *scale);
1028       int step_two(uint8_t *bit_alloc, float fraction[2][4][SBLIMIT],
1029          int *scale, int x1);
1030     public:
1031       new_memset(0);
1032       bits_t *stream;
1033       // Layer 3
1034       uint8_t *bsbuf, *prev_bsbuf;
1035       uint8_t bsspace[2][MAXFRAMESIZE + 512]; // MAXFRAMESIZE
1036       int bsnum;
1037       // For mp3 current framesize without header.  For AC3 current framesize with header.
1038       long framesize;
1039       long prev_framesize, past_framesize;
1040       int channels;
1041       int samplerate;
1042       int single;
1043       int sampling_frequency_code;
1044       int error_protection;
1045       int mode;
1046       int mode_ext;
1047       int lsf;
1048       long ssize;
1049       int mpeg35;
1050       int padding;
1051       int layer;
1052       int extension;
1053       int copyright;
1054       int original;
1055       int emphasis;
1056       int bitrate;
1057       // Static variable in synthesizer
1058       int bo;                      
1059       // Ignore first frame after a seek
1060       int first_frame;
1061       float synth_stereo_buffs[2][2][0x110];
1062       float synth_mono_buff[64];
1063       float mp3_block[2][2][SBLIMIT * SSLIMIT];
1064       int mp3_blc[2];
1065
1066       // State of ID3 parsing
1067       int id3_state;
1068       int id3_current_byte;
1069       int id3_size;
1070       // Layer 2
1071       int bitrate_index;
1072       imdct_al_table_t *alloc;
1073       int jsbound;
1074       int II_sblimit;
1075       uint8_t layer2_scfsi_buf[64];
1076
1077       void layer_reset();
1078       static int layer_check(uint8_t *data);
1079       static int id3_check(uint8_t *data);
1080       int layer3_header(uint8_t *data);
1081       audio_decoder_layer_t();
1082       ~audio_decoder_layer_t();
1083       int do_layer2(uint8_t *zframe,int zframe_size,float **zoutput,int render);
1084       int do_layer3(uint8_t *zframe,int zframe_size,float **zoutput,int render);
1085       int init_layer2();
1086       int init_layer3();
1087       int init_decode_tables();
1088     } *layer_decoder;
1089
1090     class audio_decoder_ac3_t {
1091     public:
1092       new_memset(0);
1093       static int ac3_samplerates[3];
1094
1095       bits_t *stream;
1096       int samplerate;
1097       int bitrate;
1098       int flags;
1099       int channels;
1100       a52_state_t *state;
1101       sample_t *output;
1102       int framesize;
1103       static int ac3_check(uint8_t *data);
1104       int ac3_header(uint8_t *data);
1105       int do_ac3(uint8_t *zframe, int zframe_size, float **zoutput, int render);
1106       audio_decoder_ac3_t();
1107       ~audio_decoder_ac3_t();
1108     } *ac3_decoder;
1109
1110     class audio_decoder_pcm_t {
1111     public:
1112       new_memset(0);
1113       int samplerate;
1114       int bits;
1115       int channels;
1116       int framesize;
1117       int pcm_header(uint8_t *data);
1118       int do_pcm(uint8_t *zframe, int zframe_size, float **zoutput, int render);
1119       audio_decoder_pcm_t() {}
1120       ~audio_decoder_pcm_t() {}
1121     } *pcm_decoder;
1122
1123     int channels;            // channels from read_header
1124     int samplerate;          // samplerate from read_header
1125     int framenum;            // Number of current frame being decoded
1126     int framesize;           // Size of frame including header
1127     int64_t start_byte;      // First byte of audio data in the file
1128     int output_channels;     // number of defined output buffers
1129     float **output;          // Output from synthesizer in linear floats
1130     int output_size;         // Number of pcm samples in the buffer
1131     int output_allocated;    // Allocated number of samples in output
1132     int64_t output_position; // Sample position in file of start of output buffer
1133     int64_t sample_seek;     // Perform a seek to the sample
1134     int64_t byte_seek;       // Perform a seek to the absolute byte
1135     // +/- number of samples of difference between audio and video
1136     int seek_correction;
1137     // Buffer containing current packet
1138     uint8_t packet_buffer[MAXFRAMESIZE];
1139     // Position in packet buffer of next byte to read
1140     int packet_position;
1141
1142     audio_t() {}
1143     int init_audio(zmpeg3_t *zsrc, atrack_t *ztrack, int zformat);
1144     ~audio_t();
1145
1146     int rewind_audio();
1147     int read_header();
1148     void update_channels();
1149     int audio_pts_padding();
1150     int audio_pts_skipping(int samples);
1151     void update_audio_history();
1152     int read_frame(int render);
1153     int get_length();
1154     int seek();
1155     int seek_byte(int64_t byte);
1156     int seek_sample(long sample);
1157     int read_raw(uint8_t *output,long *size,long max_size);
1158     void shift_audio(int64_t diff);
1159     int decode_audio(void *output_v,int atyp,int channel,int len);
1160     int64_t audio_position() { return output_position + output_size; }
1161   };
1162
1163   class VLCtab_t {
1164   public:
1165     int8_t val, len;
1166   };
1167
1168   class DCTtab_t {
1169   public:
1170     int8_t run, level;
1171     int16_t len;
1172   };
1173
1174   class slice_buffer_t {
1175     static VLCtab_t DClumtab0[32];
1176     static VLCtab_t DClumtab1[16];
1177     static VLCtab_t DCchromtab0[32];
1178     static VLCtab_t DCchromtab1[32];
1179   
1180   public:
1181     slice_buffer_t *next;    // avail list link
1182     uint8_t *data;           // Buffer for holding the slice data
1183     video_t *video;          // decoder
1184     int buffer_size;         // Size of buffer
1185     int buffer_allocation;   // Space allocated for buffer 
1186     int buffer_position;     // Position in buffer
1187     uint32_t bits;
1188     int bits_size;
1189
1190     int eob() { return buffer_position >= buffer_size; }
1191     uint32_t get_data_byte() { return data[buffer_position++]; }
1192     void fill_bits(int nbits) {
1193       while( bits_size < nbits ) {
1194         bits <<= 8;
1195         if( !eob() ) bits |= get_data_byte();
1196         bits_size += 8;
1197       }
1198     }
1199     void flush_bits(int nbits) { fill_bits(nbits); bits_size -= nbits; }
1200     void flush_bit() { flush_bits(1); }
1201     uint32_t show_bits(int nbits) {
1202       fill_bits(nbits);
1203       return (bits >> (bits_size-nbits)) & (0xffffffff >> (32-nbits));
1204     }
1205     uint32_t get_bits(int nbits) {
1206       uint32_t result = show_bits(nbits);
1207       bits_size -= nbits;
1208       return result;
1209     }
1210     uint32_t get_bit() { return get_bits(1); }
1211     int get_dc_lum();
1212     int get_dc_chrom();
1213     uint8_t *expand_buffer(int bfrsz);
1214     void fill_buffer(bits_t *vstream);
1215     int ext_bit_info();
1216
1217     slice_buffer_t();
1218     ~slice_buffer_t();
1219   };
1220
1221
1222   class video_t {
1223     static uint8_t zig_zag_scan_nommx[64]; // zig-zag scan
1224     static uint8_t alternate_scan_nommx[64]; // alternate scan
1225     // default intra quantization matrix
1226     static uint8_t default_intra_quantizer_matrix[64];
1227     // Frame rate table must agree with the one in the encoder
1228     static double frame_rate_table[16];
1229
1230     inline void recon_comp(uint8_t *s, uint8_t *d,
1231            int lx, int lx2, int h, int type);
1232     void recon(uint8_t *src[], int sfield,
1233            uint8_t *dst[], int dfield, int lx, int lx2,
1234            int w, int h, int x, int y, int dx, int dy, int addflag);
1235     int delete_decoder();
1236     void init_scantables();
1237     int read_frame_backend(int skip_bframes);
1238     int *get_scaletable(int input_w, int output_w);
1239     int get_gop_header();
1240     long gop_to_frame(timecode_t *gop_timecode);
1241     int seek();
1242
1243   public:
1244     new_memset(0);
1245     class cc_t;
1246
1247     enum chroma_format {
1248       cfmt_420=1,
1249       cfmt_422=2,
1250       cfmt_444=3,
1251     };
1252
1253     enum ext_start_code {
1254       ext_id_SEQ=1,
1255       ext_id_DISP=2,
1256       ext_id_QUANT=3,
1257       ext_id_SEQSCAL=5,
1258       ext_id_PANSCAN=7,
1259       ext_id_CODING=8,
1260       ext_id_SPATSCAL=9,
1261       ext_id_TEMPSCAL=10,
1262     };
1263
1264     enum picture_type {
1265       pic_type_I=1,
1266       pic_type_P=2,
1267       pic_type_B=3,
1268       pic_type_D=4,
1269     };
1270
1271     enum picture_structure {
1272       pics_TOP_FIELD=1,
1273       pics_BOTTOM_FIELD=2,
1274       pics_FRAME_PICTURE=3,
1275     };
1276
1277     slice_buffer_t *slice_buffers, *avail_slice_buffers;
1278     int total_slice_buffers;
1279     void allocate_slice_buffers();
1280     void delete_slice_buffers();
1281     void reallocate_slice_buffers();
1282     zlock_t slice_lock, slice_wait, slice_active;
1283     int slice_wait_locked, slice_active_locked;
1284
1285     zmpeg3_t *src;
1286     vtrack_t *track;
1287
1288     // ================================= Seeking variables =========================
1289     bits_t *vstream;
1290     int decoder_initted;
1291     uint8_t **output_rows;     // Output frame buffer supplied by user
1292     int in_x, in_y, in_w, in_h, out_w, out_h; // Output dimensions
1293     int row_span;
1294     int *x_table, *y_table;          // Location of every output pixel in the input
1295     int color_model;
1296     int want_yvu;                    // Want to return a YUV frame
1297     char *y_output, *u_output, *v_output; // Output pointers for a YUV frame
1298
1299     int blockreadsize;
1300     int maxframe;          // Max value of frame num to read
1301     int64_t byte_seek;     // Perform absolute byte seek before the next frame is read
1302     int frame_seek;        // Perform a frame seek before the next frame is read
1303     int framenum;          // Number of the next frame to be decoded
1304     int last_number;       // Last framenum rendered
1305     int ref_frames;        // ref_frames since last seek
1306     int found_seqhdr;
1307     int bitrate;
1308     timecode_t gop_timecode;     // Timecode for the last GOP header read.
1309     int has_gops; // Some streams have no GOPs so try sequence start codes instead
1310
1311     class cc_t {        // close captioning (atsc only)
1312       video_t *video;
1313       uint8_t data[3][128];   // reorder buffers
1314       int frs_history, font_size;
1315       void decode(int idx);
1316     public:
1317       class svc_t;
1318   
1319       enum {
1320         MX_SVC = 64, MX_WIN=8,MX_CX=48,MX_CY=16,
1321         /* frame struct history */
1322         frs_tf1 = 0x01, /* top field in data[1] */
1323         frs_bf2 = 0x02, /* bottom field in data[2] */
1324         frs_frm = 0x04, /* frame in data[1] */
1325         frs_prc = 0x08, /* frame processed */
1326         st_unmap=-1, st_hidden=0, st_visible=1, /* state */
1327         dir_rt=0, dir_lt=1, dir_up=2, dir_dn=3, /* print/scroll/effect dir */
1328         jfy_left=0, jfy_right=1, jfy_center=2, jfy_full=3, /* justify */
1329         eft_snap = 0, eft_fade = 1, eft_wipe = 2, /* effect */
1330         oty_solid=0, oty_flash=1, oty_translucent=2,
1331         oty_transparent=3, bdr_width=5, /* opacity/border width */
1332         edg_none=0, edg_raised=1, edg_depressed=2, edg_uniform=3,
1333         edg_shadow_left=4, edg_shadow_right=5, /* edge type */
1334         psz_small=0, psz_standard=1, psz_large=2, /* pen size */
1335         fst_default=0, fst_mono_serif=1, fst_prop_serif=2,
1336         fst_mono_sans=3, fst_prop_sans=4, fst_casual=5,
1337         fst_cursive=6, fst_small_caps=7, /* font style */
1338         fsz_small=0, fsz_normal=1, fsz_large=2, /* font size */
1339         tag_dialog=0, tag_source_id=1, tag_device=2,
1340         tag_dialog_2=3, tag_voiceover=4, tag_audible_transl=5,
1341         tag_subtitle_transl=6, tag_voice_descr=7, tag_lyrics=8,
1342         tag_effect_descr=9, tag_score_descr=10, tag_expletive=11,
1343         tag_not_displayable=15, /* text tag */
1344         ofs_subscript=0, ofs_normal=1, ofs_superscript=2, /* offset */
1345       };
1346       /* color RGB 2:2:2 (lsb = B). */
1347       class svc_t {
1348         cc_t *cc;
1349         int sid, ctrk, size;
1350         uint8_t *bp, *ep;
1351         uint8_t data[128];
1352       public:
1353         class chr_t {
1354         public:
1355           uint16_t glyph;
1356           uint8_t fg_opacity : 2;
1357           uint8_t fg_color : 6;
1358           uint8_t bg_opacity : 2;
1359           uint8_t bg_color : 6;
1360           uint8_t pen_size : 2;
1361           uint8_t edge_color : 6;
1362           uint8_t italics : 1;
1363           uint8_t edge_type : 3;
1364           uint8_t underline : 1;
1365           uint8_t font_style : 3; 
1366           uint8_t font_size : 2; 
1367           uint8_t offset : 2; 
1368           uint8_t text_tag : 4;
1369           uint8_t rsvd2;
1370         } *bfrs;
1371         chr_t *get_bfr();
1372         void bfr_put(chr_t *&bfr);
1373
1374         class win_t;
1375         class win_t {
1376         public:
1377           class chr_attr_t;
1378           int8_t id, st, pdir, sdir;
1379           uint8_t cx, cy, cw, ch; /* pen/dim in bytes */
1380           int ax, ay, x, y, bw; /* anchor/pen/border in pixels */
1381           uint32_t fg_yuva, bg_yuva, edge_yuva; /* pen color */
1382           uint32_t fill_yuva, border_yuva; /* window color */
1383           int start_frame, end_frame;
1384           svc_t *svc;
1385           subtitle_t *subtitle;
1386           uint8_t anchor_point, anchor_horizontal, anchor_vertical;
1387           uint8_t anchor_relative, row_lock, col_lock, dirty;
1388           uint8_t priority, window_style, pen_style;
1389           /* pen style properties */
1390           uint8_t pen_size, font_style, offset, italics, underline;
1391           uint8_t fg_color, fg_opacity, bg_color, bg_opacity;
1392           uint8_t text_tag, edge_color, edge_type, scale;
1393           /* window style properties */
1394           uint8_t justify, wordwrap, fill_opacity, fill_color;
1395           uint8_t display_effect, effect_speed, effect_direction;
1396           uint8_t border_type, border_color, border_width;
1397           chr_t *bfr;
1398
1399           win_t();
1400           ~win_t();
1401           void reset(int i,svc_t *svc);
1402           int BS();   int FF();   int CR();   int HCR();
1403           int init(int ncw, int nch);
1404           int resize(int ncw, int nch);
1405           static int is_breakable(int b);
1406           int wrap();
1407           int ovfl();
1408           int store(int ch);
1409           void set_window_style(int i);
1410           void set_pen_style(int i);
1411           void default_window();
1412           void print_buffer();
1413           void hbar(int x, int y, int ww, int hh, int lm, int rm, int clr);
1414           void vbar(int x, int y, int ww, int hh, int tm, int bm, int clr);
1415           void border(int ilt, int olt, int irt, int ort,
1416                       int iup, int oup, int idn, int odn);
1417           void put_chr(chr_t *chr);
1418           static bitfont_t *chr_font(chr_t *bp, int scale);
1419           void render();
1420           void output_text();
1421           void set_state(int8_t st);
1422         } win[MX_WIN], *curw;    
1423         svc_t(cc_t *cc);
1424         ~svc_t();
1425         int id() { return sid; }
1426         int trk() { return ctrk; }
1427         void append(uint8_t *bp, int len);
1428         void decode();
1429         int render();
1430         void reset(int sid,cc_t *cc);
1431         int CWx(int id);  int DFz(int id);
1432         int DFx(int id);  int RSVD();   int ETX();
1433         int BS();   int FF();   int CR();   int HCR();
1434         int RST();  int DLC();  int DLW();  int DLY();
1435         int CLW();  int DSW();  int HDW();  int TGW();
1436         int SPA();  int SPC();  int SPL();  int SWA();
1437         int command(int cmd);
1438         static uint32_t pen_yuva(int color, int opacity);
1439       } svc;
1440   
1441       cc_t(video_t *video);
1442       ~cc_t();
1443       void reset();
1444       void get_atsc_data(bits_t *v);
1445       void decode();
1446       void reorder();
1447       zcc_text_cb text_cb;
1448     } *cc;
1449     cc_t *get_cc();
1450     int subtitle_track; // Subtitle track to composite if >= 0
1451     int show_subtitle(int strk);
1452
1453     // These are only available from elementary streams.
1454     int frames_per_gop;       // Frames per GOP after the first GOP.
1455     int first_gop_frames;     // Frames in the first GOP.
1456     int first_frame;     // Number of first frame stored in timecode
1457     int last_frame;      // Last frame in file
1458
1459     // ================================= Compression variables =====================
1460     // Malloced frame buffers.  2 refframes are swapped in and out.
1461     // while only 1 auxframe is used.
1462     uint8_t *yuv_buffer[5];  // Make YVU buffers contiguous for all frames
1463     uint8_t *oldrefframe[3], *refframe[3], *auxframe[3];
1464     uint8_t *llframe0[3], *llframe1[3];
1465     uint8_t *zigzag_scan_table;
1466     uint8_t *alternate_scan_table;
1467     // Source for the next frame presentation
1468     uint8_t *output_src[3];
1469     // Pointers to frame buffers.
1470     uint8_t *newframe[3];
1471     uint8_t *tdat;
1472     int horizontal_size, vertical_size, mb_width, mb_height;
1473     int coded_picture_width,  coded_picture_height;
1474     int chroma_format, chrom_width, chrom_height, blk_cnt;
1475     int8_t pict_type, pict_struct, field_sequence, intravlc;
1476     int8_t forw_r_size, back_r_size, full_forw, full_back;
1477     int8_t prog_seq, prog_frame, repeatfirst, secondfield;
1478     int8_t h_forw_r_size, v_forw_r_size, h_back_r_size, v_back_r_size;
1479     int8_t dc_prec, topfirst, frame_pred_dct, conceal_mv;
1480     union {
1481       struct { int8_t got_top, got_bottom, repeat_fields, current_field; };
1482       int32_t repeat_data;
1483     };
1484     int skip_bframes;
1485     int frame_time, seek_time;
1486     int stwc_table_index, llw, llh, hm, hn, vm, vn;
1487     int lltempref, llx0, lly0, llprog_frame, llfieldsel;
1488     int matrix_coefficients;
1489     int framerate_code;
1490     double frame_rate;
1491     int *cr_to_r, *crb_to_g, *cb_to_b;
1492     int intra_quantizer_matrix[64], non_intra_quantizer_matrix[64];
1493     int chroma_intra_quantizer_matrix[64], chroma_non_intra_quantizer_matrix[64];
1494     int mpeg2;
1495     int skim;                     // skip reconstruction/motion
1496     int thumb, ithumb;            // thumbnail scan/ thumbnail frame ready 
1497     int qscale_type, altscan;     // picture coding extension
1498     int pict_scal;                // picture spatial scalable extension
1499     int scalable_mode;            // sequence scalable extension
1500
1501     // Subtitling frame
1502     uint8_t *subtitle_frame[3];
1503
1504     video_t(zmpeg3_t *zsrc, vtrack_t *ztrack);
1505     ~video_t();
1506     void init_video();
1507     int seek_video() { return seek(); }
1508     void reset_subtitles();
1509     int eof();
1510
1511     int set_cpus(int cpus);
1512     int set_mmx(int use_mmx);
1513     void cache_frame();
1514     int drop_frames(long frames, int cache_it);
1515     int colormodel();
1516     int read_frame(uint8_t **output_rows,
1517       int in_x, int in_y, int in_w, int in_h,
1518       int out_w, int out_h, int color_model);
1519     int read_yuvframe(char *y_output, char *u_output, char *v_output,
1520       int in_x, int in_y, int in_w, int in_h);
1521     int read_yuvframe_ptr(char **y_output, char **u_output, char **v_output);
1522     int read_raw(uint8_t *output, long *size, long max_size);
1523     int seek_frame(long frame);
1524     int seek_byte(int64_t byte);
1525     int rewind_video(int preload=1);
1526     int previous_frame();
1527     int init_decoder();
1528     void new_output();
1529     int reconstruct( int bx, int by, int mb_type, int motion_type,
1530            int PMV[2][2][2], int mv_field_sel[2][2],
1531            int dmvector[2], int stwtype);
1532     void dump();
1533     slice_buffer_t *get_slice_buffer();
1534     void put_slice_buffer(slice_buffer_t* buffer);
1535     int get_macroblocks();
1536     int display_second_field();
1537     int video_pts_padding();
1538     int video_pts_skipping();
1539     int read_picture();
1540     int get_picture();
1541     int get_seq_hdr();
1542     int sequence_extension();
1543     int sequence_display_extension();
1544     int quant_matrix_extension();
1545     int sequence_scalable_extension();
1546     int picture_display_extension();
1547     int picture_coding_extension();
1548     int picture_spatial_scalable_extension();
1549     int picture_temporal_scalable_extension();
1550     int ext_user_data();
1551     int get_picture_hdr();
1552     int find_header();
1553     int get_header();
1554     void overlay_subtitle(subtitle_t *subtitle);
1555     void decode_subtitle();
1556     int init_output();
1557     int dither_frame(uint8_t *yy, uint8_t *uu, uint8_t *vv,uint8_t **output_rows);
1558     int dither_frame444(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1559     int dithertop(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1560     int dithertop444(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1561     int ditherbot(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1562     int ditherbot444(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1563     int present_frame(uint8_t *yy, uint8_t *uu, uint8_t *vv);
1564     void calc_dmv(int DMV[][2],int *dmvector,int mvx,int mvy);
1565     int is_refframe() { return pict_type == pic_type_B ? 0 :
1566       pict_struct == pics_FRAME_PICTURE ? 1 : secondfield;
1567     }
1568   };
1569
1570
1571   class slice_decoder_t {
1572   public:
1573     static VLCtab_t PMBtab0[8];
1574     static VLCtab_t PMBtab1[8];
1575     static VLCtab_t BMBtab0[16];
1576     static VLCtab_t BMBtab1[8];
1577     static VLCtab_t spIMBtab[16];
1578     static VLCtab_t spPMBtab0[16];
1579     static VLCtab_t spPMBtab1[16];
1580     static VLCtab_t spBMBtab0[14];
1581     static VLCtab_t spBMBtab1[12];
1582     static VLCtab_t spBMBtab2[8];
1583     static VLCtab_t SNRMBtab[8];
1584     static VLCtab_t MVtab0[8];
1585     static VLCtab_t MVtab1[8];
1586     static VLCtab_t MVtab2[12];
1587     static VLCtab_t CBPtab0[32];
1588     static VLCtab_t CBPtab1[64];
1589     static VLCtab_t CBPtab2[8];
1590     static VLCtab_t MBAtab1[16];
1591     static VLCtab_t MBAtab2[104];
1592
1593     static DCTtab_t DCTtabfirst[12];
1594     static DCTtab_t DCTtabnext[12];
1595     static DCTtab_t DCTtab0[60];
1596     static DCTtab_t DCTtab0a[252];
1597     static DCTtab_t DCTtab1[8];
1598     static DCTtab_t DCTtab1a[8];
1599     static DCTtab_t DCTtab2[16];
1600     static DCTtab_t DCTtab3[16];
1601     static DCTtab_t DCTtab4[16];
1602     static DCTtab_t DCTtab5[16];
1603     static DCTtab_t DCTtab6[16];
1604
1605     // non-linear quantization coefficient table
1606     static uint8_t non_linear_mquant_table[32];
1607
1608     enum macroblock_type {
1609       mb_INTRA=1,
1610       mb_PATTERN=2,
1611       mb_BACKWARD=4,
1612       mb_FORWARD=8,
1613       mb_QUANT=16,
1614       mb_WEIGHT=32,
1615       mb_CLASS4=64,
1616     };
1617
1618     enum motion_type {
1619       mc_FIELD=1,
1620       mc_FRAME=2,
1621       mc_16X8=2,
1622       mc_DMV=3,
1623     };
1624
1625     enum mv_format {
1626       mv_FIELD=0,
1627       mv_FRAME=1,
1628     };
1629
1630     enum scalable_mode {
1631       sc_NONE=0,
1632       sc_DP=1,
1633       sc_SPAT=2,
1634       sc_SNR=3,
1635       sc_TEMP=4,
1636     };
1637
1638     slice_decoder_t *next;
1639     zmpeg3_t *src;
1640     video_t *video;
1641     pthread_t owner;        // for debugging
1642     slice_buffer_t *slice_buffer;
1643     int fault;
1644     int done;
1645     int quant_scale;
1646     int pri_brk;            // slice/macroblock
1647     short block[12][64];
1648     int sparse[12];
1649     pthread_t tid;          // ID of thread
1650     zlock_t input_lock;
1651
1652     int val, sign, idx;
1653     int get_cbp();
1654     int clear_block(int comp, int size);
1655     static uint16_t *DCTlutab[3];
1656     static uint16_t lu_pack(DCTtab_t *lp) {
1657       int run = lp->run>=64 ? lp->run-32 : lp->run;
1658       return run | ((lp->len-1)<<6) | (lp->level<<10);
1659     }
1660     static int lu_run(uint16_t lu) { return lu & 0x3f; }
1661     static int lu_level(uint16_t lu) { return lu >> 10; }
1662     static int lu_len(uint16_t lu) { return ((lu>>6) & 0x0f) + 1; }
1663     static void init_lut(uint16_t *&lutbl, DCTtab_t *tabn, DCTtab_t *tab0, DCTtab_t *tab1);
1664     static void init_tables();
1665     int get_coef(uint16_t *lut);
1666     int get_mpg2_coef(uint16_t *lut);
1667     void get_intra_block(int comp, int dc_dct_pred[]);
1668     void get_mpg2_intra_block(int comp, int dc_dct_pred[]);
1669     void get_inter_block(int comp);
1670     void get_mpg2_inter_block(int comp);
1671     int get_slice_hdr();
1672     int decode_slice();
1673     void slice_loop();
1674     static void *the_slice_loop(void *the_slice_decoder);
1675     int get_mv();
1676     int get_dmv();
1677     void motion_vector(int *PMV, int *dmvector, int h_r_size, int v_r_size,
1678       int dmv, int mvscale, int full_pel_vector);
1679     int motion_vectors(int PMV[2][2][2], int dmvector[2], int mv_field_sel[2][2],
1680       int s, int mv_count, int mv_format, int h_r_size, int v_r_size,
1681       int dmv, int mvscale);
1682     int get_macroblock_address();
1683     inline int getsp_imb_type();
1684     inline int getsp_pmb_type();
1685     inline int getsp_bmb_type();
1686     inline int get_imb_type();
1687     inline int get_pmb_type();
1688     inline int get_bmb_type();
1689     inline int get_dmb_type();
1690     inline int get_snrmb_type();
1691     int get_mb_type();
1692     int macroblock_modes(int *pmb_type,int *pstwtype, int *pstwclass,
1693        int *pmotion_type,int *pmv_count,int *pmv_format,int *pdmv,
1694        int *pmvscale,int *pdct_type);
1695     int add_block(int comp,int bx,int by,int dct_type,int addflag);
1696     static void idct_conversion(short* block);
1697     int get_active_slice_buffer();
1698
1699     slice_decoder_t();
1700     ~slice_decoder_t();
1701   } *slice_decoders, *avail_slice_decoders;
1702
1703   int total_slice_decoders;
1704   slice_buffer_t *active_slice_buffers;
1705   zlock_t decoder_lock, decoder_active;
1706   int decoder_active_locked;
1707   void allocate_slice_decoders();
1708   void delete_slice_decoders();
1709   void reallocate_slice_decoders();
1710   void decode_slice(slice_buffer_t* buffer);
1711   
1712
1713   class subtitle_t {
1714   public:
1715     new_memset(0);
1716     uint8_t *data;   // Raw data of subtitle
1717     int data_allocated, data_used;
1718     int id;         // Number of stream starting at 0x20
1719     int done;       // -1 avail, 0 read in, 1 decode
1720     int active;     // 1 subtitle is contructed, -1 subtitle is close caption
1721     int draw;       // -1 never draw, 0 draw based on frame time, 1 always draw
1722     int64_t offset; // Program offset of start of subtitle
1723     int force;      // 1 Force display, -1 force delete
1724     // image in YUV444
1725     int w, h, sz;
1726     uint8_t *image_y, *image_u, *image_v, *image_a;
1727     int x1, x2, y1, y2;
1728     int start_time; // Time after detection of subtitle to display it in msec
1729     int stop_time;  // Time after detection of subtitle to hide it in msec
1730     int palette[4]; // Indexes in the main palette
1731     int alpha[4];
1732     int start_frame, stop_frame; // framenum start/stop drawing
1733     int frame_time; // presentation frame_time at creation
1734
1735     subtitle_t();
1736     subtitle_t(int nid, int ww, int hh);
1737     ~subtitle_t();
1738
1739     void realloc_data(int count);
1740     int decompress_subtitle(zmpeg3_t *zsrc);
1741     void set_image_size(int isz);
1742     void set_image_size(int ww, int hh);
1743     int decode(video_t *video);
1744   };
1745
1746   class demuxer_t {
1747     friend class bits_t;
1748
1749     uint8_t packet_next_char() { return raw_data[raw_offset]; }
1750     uint8_t packet_read_char() { return raw_data[raw_offset++]; }
1751     uint32_t packet_read_int16() {
1752       uint32_t a = raw_data[raw_offset++];
1753       uint32_t b = raw_data[raw_offset++];
1754       return (a << 8) | b;
1755     }
1756     uint32_t packet_next_int24() {
1757       uint32_t a = raw_data[raw_offset+0];
1758       uint32_t b = raw_data[raw_offset+1];
1759       uint32_t c = raw_data[raw_offset+2];
1760       return (a << 16) | (b << 8) | c;
1761     }
1762     uint32_t packet_read_int24() {
1763       uint32_t a = raw_data[raw_offset++];
1764       uint32_t b = raw_data[raw_offset++];
1765       uint32_t c = raw_data[raw_offset++];
1766       return (a << 16) | (b << 8) | c;
1767     }
1768     uint32_t packet_read_int32() {
1769       uint32_t a = raw_data[raw_offset++];
1770       uint32_t b = raw_data[raw_offset++];
1771       uint32_t c = raw_data[raw_offset++];
1772       uint32_t d = raw_data[raw_offset++];
1773       return (a << 24) | (b << 16) | (c << 8) | d;
1774     }
1775     void packet_skip(int length) { raw_offset += length; }
1776     int get_adaptation_field();
1777     int get_program_association_table();
1778     int get_transport_payload(int is_audio, int is_video);
1779     int get_pes_packet_header(uint64_t *pts, uint64_t *dts);
1780     int get_unknown_data();
1781     int get_transport_pes_packet();
1782     int get_pes_packet();
1783     int get_payload();
1784     int read_transport();
1785     int get_system_header();
1786     uint64_t get_timestamp();
1787     int get_pack_header();
1788     int get_program_payload(int bytes, int is_audio, int is_video);
1789     int handle_scrambling(int decryption_offset);
1790     void del_subtitle(int idx);
1791     subtitle_t* get_subtitle(int id,int64_t offset);
1792     void handle_subtitle(zmpeg3_t *src, int stream_id, int bytes);
1793     int handle_pcm(int bytes);
1794     int get_program_pes_packet(uint32_t header);
1795     int previous_code(uint32_t zcode);
1796
1797   public:
1798     new_memset(0);
1799     class zstream_t;
1800     class title_t;
1801     class nav_t {
1802     public:
1803 #include "nav.h"
1804       new_memset(0);
1805     } *nav;
1806
1807     zmpeg3_t* src;
1808     uint8_t *raw_data; // One unparsed packet.
1809     int raw_offset; // Offset in raw_data of read pointer
1810     int raw_size; // Amount loaded in last raw_data
1811
1812     // Elementary stream data when only one stream is to be read.
1813     // Erased in every call to read a packet.
1814     class zstream_t {
1815     public:
1816       new_memset(0);
1817       uint8_t *buffer;
1818       int allocated; // Allocation of data_buffer
1819       int size; // Position in data_buffer of write pointer
1820       int position; // Position in data_buffer of read pointer
1821       int start; // Start of the next pes packet
1822       int length() { return size - position; }
1823       bool eof() { return position >= size; }
1824       bool bof() { return position == 0; }
1825     } zdata;
1826     // Elementary stream data when all streams are to be read.  There is no
1827     // read pointer since data is expected to be copied directly to a track.
1828     // Some packets contain audio and video.  Further division into
1829     // stream ID may be needed.
1830     zstream_t zaudio;
1831     zstream_t zvideo;
1832
1833     subtitle_t *subtitles[MAX_SUBTITLES];
1834     int total_subtitles;
1835
1836     // What type of data to read, which track is accessing
1837     atrack_t *do_audio;
1838     vtrack_t *do_video;
1839     int read_all;
1840     // Direction of reads
1841     int reverse;
1842     // Set to 1 when eof or attempt to read before beginning
1843     int error_flag;
1844     int discontinuity;
1845     // Temp variables for returning
1846     uint8_t next_char;
1847     // Info for mpeg3cat
1848     int64_t last_packet_start;
1849     int64_t last_packet_end;
1850     int64_t last_packet_decryption;
1851
1852   // Table of contents
1853     class title_t { // Titles
1854       void extend_cell_table();
1855     public:
1856       new_memset(0);
1857       class cell_t;
1858
1859       zmpeg3_t *src;
1860       fs_t *fs;
1861       int64_t total_bytes; // Total bytes in title file.
1862       int64_t start_byte; // Absolute starting byte of the title in the stream
1863       int64_t end_byte; // Absolute ending byte of the title in the stream + 1
1864       // May get rid of time values and rename to a cell offset table.
1865       // May also get rid of end byte.
1866
1867       class cell_t {
1868       public:
1869         new_memset(0);
1870         int64_t title_start; // Starting byte of cell in the title (start_byte)
1871         int64_t title_end;  // Ending byte of cell in the title (end_byte)
1872         int64_t program_start; // Starting byte of the cell in the program
1873         int64_t program_end; // Ending byte of the cell in the program
1874         double cell_time; // play time at end of cell, -1 if unknown
1875         int cell_no; // cell in original cell table
1876         int discontinuity;
1877
1878         cell_t() {}
1879         ~cell_t() {}
1880       } *cell_table; // Timecode table
1881       int cell_table_size; // Number of entries
1882       int cell_table_allocation; // Number of available slots
1883
1884       title_t(zmpeg3_t *zsrc, char *fpath);
1885       title_t(zmpeg3_t *zsrc);
1886       ~title_t();
1887       title_t(title_t &title);
1888       void new_cell(int cell_no,
1889         int64_t title_start, int64_t title_end,
1890         int64_t program_start, int64_t program_end,
1891         int discontinuity);
1892       void new_cell(int64_t byte_end) { // default cell
1893         new_cell(0, 0, byte_end, 0, byte_end, 0);
1894       }
1895       int dump_title();
1896       int print_cells(FILE *output);
1897     } *titles[MAX_STREAMZ];
1898     int total_titles;
1899     int current_title; // Title currently being used
1900
1901     // Tables of every stream ID encountered
1902     int8_t astream_table[MAX_STREAMZ];  // afmt index
1903     int8_t vstream_table[MAX_STREAMZ];  // 1 if video
1904     int8_t sstream_table[MAX_STREAMZ];  // 1 if subtitle
1905
1906     // Cell in the current title currently used
1907     int title_cell;
1908     int64_t nav_cell_next_vobu;
1909     int64_t nav_cell_end_byte;
1910
1911     // Byte position in current program.
1912     int64_t program_byte;
1913     // Total bytes in all titles
1914     int64_t total_bytes;
1915     // The end of the current stream in the current program
1916     int64_t stream_end;
1917
1918     int transport_error_indicator;
1919     int payload_unit_start_indicator;
1920     int pid; // PID of last packet
1921     int stream_id; // Stream ID of last packet
1922     int custom_id; // Custom ID of last packet
1923     int transport_scrambling_control;
1924     int adaptation_field_control;
1925     int continuity_counter;
1926     int is_padding;
1927     int pid_table[PIDMAX];
1928     int continuity_counters[PIDMAX];
1929     int total_pids;
1930     int adaptation_fields;
1931     double time;           // Time in seconds
1932     uint32_t last_code;
1933     int audio_pid;
1934     int video_pid;
1935     int subtitle_pid;
1936     int got_audio;
1937     int got_video;
1938     // if subtitle object was created in last packet
1939     int got_subtitle;
1940     // When only one stream is to be read, these store the stream IDs
1941     // Audio stream ID being decoded.  -1 = select first ID in stream
1942     int astream;     
1943     // Video stream ID being decoded.  -1 = select first ID in stream
1944     int vstream;
1945     // Multiplexed streams have the audio type
1946     // Format of the audio derived from multiplexing codes
1947     int aformat;      
1948     int program_association_tables;
1949     int table_id;
1950     int section_length;
1951     int transport_stream_id;
1952     int pes_packets;
1953     double pes_audio_time;  // Presentation Time stamps
1954     double pes_video_time;
1955     int pes_audio_pid;      // custom_id of timestamp
1956     int pes_video_pid;
1957     // Cause the stream parameters to be dumped in human readable format
1958     int dump;
1959
1960     demuxer_t(zmpeg3_t *zsrc,atrack_t *do_aud,vtrack_t *do_vid,int cust_id);
1961     ~demuxer_t();
1962
1963     int create_title(int full_scan=0);
1964     int64_t tell_byte() { return program_byte; }
1965     int64_t absolute_position() {
1966       return titles[current_title]->fs->tell() + titles[current_title]->start_byte;
1967     }
1968     bool eof();
1969     bool bof();
1970     bool error() { return error_flag; }
1971     int64_t movie_size();
1972     double get_time() { return time; }
1973     int get_cell(int no, title_t::cell_t *&v);
1974     void start_reverse();
1975     void start_forward();
1976     int seek_byte(int64_t byte);
1977     double scan_pts();
1978     int goto_pts(double pts);
1979     int seek_phys();
1980     int read_program();
1981     int64_t prog2abs_fwd(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell);
1982     int64_t prog2abs_rev(int64_t byte, int64_t *nbyte, int *ntitle, int *ncell);
1983     int64_t program_to_absolute(int64_t byte, int64_t *nbyte=0, int *ntitle=0, int *ncell=0);
1984     int64_t absolute_to_program(int64_t byte);
1985     int64_t title_bytes();
1986     void append_data(uint8_t *data, int bytes);
1987     void shift_data();
1988     int open_title(int title_number);
1989     int copy_titles(demuxer_t *dst);
1990     void end_title(int64_t end_byte);
1991     int next_code(uint32_t zcode);
1992     int prev_code(uint32_t zcode);
1993     uint8_t read_char_packet();
1994     uint8_t read_prev_char_packet();
1995     uint8_t read_char() {
1996       if( zunlikely(zdata.eof()) ) return read_char_packet();
1997       return zdata.buffer[zdata.position++];
1998     }
1999     uint8_t read_prev_char();
2000     int read_data(uint8_t *output,int size);
2001     int read_next_packet();
2002     int read_prev_packet();
2003     void skip_video_frame();
2004     int64_t next_cell();
2005     int64_t playinfo_next_cell();
2006     double video_pts() { double pts = pes_video_time; pes_video_time = -1.; return pts; }
2007     double audio_pts() { double pts = pes_audio_time; pes_audio_time = -1.; return pts; }
2008     void reset_pts();
2009     void set_audio_pts(uint64_t pts, const double denom);
2010     void set_video_pts(uint64_t pts, const double denom);
2011     int current_cell_no();
2012   };
2013
2014   class cacheframe_t {
2015   public:
2016     new_memset(0);
2017     uint8_t *y, *u, *v;
2018     int y_alloc, u_alloc, v_alloc;
2019     int y_size, u_size, v_size;
2020     int64_t frame_number;
2021     uint32_t age;
2022
2023     cacheframe_t() {}
2024     ~cacheframe_t() {}
2025   };
2026
2027   class cache_t {
2028     int extend_cache();
2029   public:
2030     new_memset(0);
2031     cacheframe_t *frames;
2032     int total;
2033     int allocation;
2034     uint32_t seq;
2035
2036     cache_t() {}
2037     ~cache_t();
2038     void clear();
2039     void reset() { total = 0; }
2040     void put_frame(int64_t zframe_number,
2041       uint8_t *zy, uint8_t *zu, uint8_t *zv,
2042       int zy_size, int zu_size, int zv_size);
2043     int get_frame( int64_t frame_number,
2044         uint8_t **zy, uint8_t **zu, uint8_t **zv);
2045     int has_frame(int64_t frame_number);
2046     int64_t memory_usage();
2047   };
2048
2049   fs_t *fs; // Store entry path here
2050   demuxer_t *demuxer; // Master title tables copied to all tracks
2051   int iopened; // file opened by user (before init)
2052
2053 // Media specific
2054
2055   int total_atracks;
2056   class atrack_t {
2057     void extend_sample_offsets();
2058   public:
2059     new_memset(0);
2060     int channels;
2061     int sample_rate;
2062     demuxer_t *demuxer;
2063     audio_t *audio;
2064     int64_t current_position;
2065     int64_t total_samples;
2066     int format;               // format of audio
2067     int number, pid;
2068     long nudge;
2069     // If we got the header information yet.  Used in streaming mode.
2070     int got_header;
2071     // Pointer to master table of contents when the TOC is read.
2072     // Pointer to private table when the TOC is being created
2073     // Stores the absolute byte of each audio chunk
2074     int64_t *sample_offsets;
2075     int total_sample_offsets;
2076     int sample_offsets_allocated;
2077     // If this sample offset table must be deleted by the track
2078     int private_offsets;
2079     // End of stream in table of contents construction
2080     int64_t audio_eof;
2081     // Starting byte of previous/current packet for making TOC
2082     int64_t prev_offset, curr_offset;
2083     double audio_time;     // audio pts based time
2084     int askip;             // skipping
2085     int64_t pts_position;  // sample position at pts
2086     double pts_origin;
2087     double pts_starttime;  // demuxer first pts
2088     double pts_offset;     // pts offset due to discontinuity
2089     double frame_pts;
2090     void reset_pts();
2091     double last_pts() { return pts_starttime+audio_time-pts_offset; }
2092
2093     atrack_t(zmpeg3_t *zsrc, int custom_id, int format, demuxer_t *demux, int no);
2094     ~atrack_t();
2095
2096     int calculate_format(zmpeg3_t *src);
2097     int handle_audio_data(int track_number);
2098     int handle_audio(int track_number);
2099     int64_t track_position() { return current_position+nudge; }
2100     void append_samples(int64_t offset);
2101     void update_frame_pts() { if( frame_pts < 0 ) frame_pts = demuxer->audio_pts(); }
2102     void update_audio_time();
2103     double get_audio_time();
2104     double pts_audio_time(double pts) {
2105       return pts_starttime<0. ? pts_starttime : pts-pts_starttime+pts_offset;
2106     }
2107     int64_t apparent_position();
2108   } *atrack[MAX_STREAMZ];
2109
2110   int total_vtracks;
2111   class vtrack_t {
2112     void extend_frame_offsets();
2113     void extend_keyframe_numbers();
2114   public:
2115     new_memset(0);
2116     int width, height;
2117     uint32_t tcode;
2118     double frame_rate;
2119     float aspect_ratio;
2120     demuxer_t *demuxer;
2121     video_t *video; // Video decoding object
2122     long current_position;  // Number of next frame to be played
2123     long total_frames;      // Total frames in the file
2124     int number, pid;
2125     slice_buffer_t *slice;  // toc slice data
2126     uint8_t *sbp;
2127     int sb_size;
2128     // Pointer to master table of contents when the TOC is read.
2129     // Pointer to private table when the TOC is being created
2130     // Stores the absolute byte of each frame
2131     int64_t *frame_offsets;
2132     int total_frame_offsets;
2133     int frame_offsets_allocated;
2134     int *keyframe_numbers;
2135     int total_keyframe_numbers;
2136     int keyframe_numbers_allocated;
2137     // Starting byte of previous/current packet for making TOC
2138     int64_t prev_frame_offset;
2139     int64_t prev_offset, curr_offset;
2140     int vskip;             // skipping
2141     double video_time;     // reshuffled pts
2142     // End of stream in table of contents construction
2143     int64_t video_eof;
2144     int got_top;
2145     int got_keyframe;
2146     cache_t *frame_cache;
2147     // If these tables must be deleted by the track
2148     int private_offsets;
2149     int pts_position;      // framenum at pts
2150     double pts_origin;
2151     double pts_starttime;  // first pts
2152     double pts_offset;     // pts offset due to discontinuity
2153     double refframe_pts;   // last refframe pts
2154     double frame_pts;
2155     double pts_video_time(double pts) {
2156       return pts_starttime<0. ? pts_starttime : pts-pts_starttime+pts_offset;
2157     }
2158     void reset_pts();
2159     double last_pts() { return pts_starttime+video_time-pts_offset; }
2160
2161     vtrack_t(zmpeg3_t *zsrc, int custom_id, demuxer_t *demux, int no);
2162     ~vtrack_t();
2163
2164     int handle_video_data(int track_number, int prev_data_size);
2165     int handle_video(int track_number);
2166     int find_keyframe_index(int64_t frame);
2167     void append_frame(int64_t offset, int is_keyframe);
2168     void update_frame_pts() { if( frame_pts < 0 ) frame_pts = demuxer->video_pts(); }
2169     void update_video_time();
2170     double get_video_time();
2171     int apparent_position();
2172   } *vtrack[MAX_STREAMZ];
2173
2174   // Subtitle track
2175   // Stores the program offsets of subtitle images.
2176   // Only used for seeking off of table of contents for editing.
2177   // Doesn't have its own demuxer but hangs off the video demuxer.
2178   int total_stracks;
2179   class strack_t {
2180     void extend_offsets();
2181     void extend_subtitles();
2182   public:
2183     new_memset(0);
2184     zrwlock_t rwlock;
2185     int id; // 0x2X
2186     video_t *video;   // if non-zero, decoder owns track
2187     int64_t *offsets; // Offsets in program of subtitle packets
2188     int total_offsets;
2189     int allocated_offsets;
2190     subtitle_t *subtitles[MAX_SUBTITLES]; // Last subtitle objects found in stream.
2191     int total_subtitles;
2192
2193     strack_t(int zid, video_t *vid=0);
2194     strack_t(strack_t &strack);
2195     ~strack_t();
2196
2197     int append_subtitle(subtitle_t *subtitle, int lock=1);
2198     void append_subtitle_offset(int64_t program_offset);
2199     void del_subtitle(subtitle_t *subtitle, int lock=0);
2200     void del_subtitle(int i, int lock=0);
2201     void del_all_subtitles();
2202   } *strack[MAX_STREAMZ];
2203
2204   static uint64_t get8bytes(uint8_t *buf) {
2205     return bswap_64(*((uint64_t *)buf));
2206   }
2207   static uint32_t get4bytes(uint8_t *buf) {
2208     return bswap_32(*((uint32_t *)buf));
2209   }
2210   static uint32_t get2bytes(uint8_t *buf) {
2211     return bswap_16(*((uint16_t *)buf));
2212   }
2213
2214   class icell_t {
2215   public:
2216     new_memset(0);
2217     int64_t start_byte, end_byte;  // Bytes relative to start of stream.
2218     short vob_id, cell_id;         // cell address vob/cell id
2219     uint32_t inlv;                 // bit vector of allowed interleaves
2220     short angle, discon;           // angle interleave no, discontinuity flag
2221
2222     int has_inlv(int i) { return (inlv >> i) & 1; }
2223   };
2224
2225   class icell_table_t {
2226   public:
2227     icell_t *cells;
2228     long total_cells;
2229     long cells_allocated;
2230     icell_table_t() { cells = 0;  total_cells = cells_allocated = 0; }
2231     ~icell_table_t();
2232     icell_t *append_cell();
2233   };
2234
2235   class ifo_t {
2236   public:
2237     new_memset(0);
2238     enum ifo_id_type {
2239       id_NUM_MENU_VOBS          = 0,
2240       id_NUM_TITLE_VOBS         = 1,
2241       id_MAT                    = 0,
2242       id_PTT                    = 1,
2243       id_TSP                    = 1,
2244       id_TITLE_PGCI             = 2,
2245       id_MENU_PGCI              = 3,
2246       id_TMT                    = 4,
2247       id_MENU_CELL_ADDR         = 5,
2248       id_MENU_VOBU_ADDR_MAP     = 6,
2249       id_TITLE_CELL_ADDR        = 7,
2250       id_TITLE_VOBU_ADDR_MAP    = 8,
2251     };
2252
2253     uint32_t num_menu_vobs;
2254     uint32_t vob_start;
2255     uint32_t empirical;               // scan for audio/subtitle stream data
2256     uint8_t *data[10];
2257     int fd;                           // file descriptor
2258     int64_t pos;                      // offset of ifo file on device 
2259     int current_vob_id;
2260     int max_inlv;
2261     int64_t current_byte;
2262 #include "ifo.h"
2263
2264     int type_vts() {
2265       return !strncmp((char*)data[id_MAT], "DVDVIDEO-VTS", 12) ? 0 : -1;
2266     }
2267     int type_vmg() {
2268       return !strncmp((char*)data[id_MAT], "DVDVIDEO-VMG", 12) ? 0 : -1;
2269     }
2270
2271     void get_playlist(zmpeg3_t *zsrc);
2272     int ifo_read(long pos, long count, uint8_t *data);
2273     int read_mat();
2274
2275     ifo_t(int zfd, long zpos);
2276     ~ifo_t();
2277     int ifo_close();
2278     int init_tables();
2279     int get_table(int64_t offset,unsigned long tbl_id);
2280     void get_palette(zmpeg3_t *zsrc);
2281     void get_header(demuxer_t *demux);
2282     void get_playinfo(zmpeg3_t *zsrc, icell_table_t *icell_addrs);
2283     void icell_addresses(icell_table_t *cell_addrs);
2284     int64_t ifo_chapter_cell_time(zmpeg3_t *zsrc, int chapter);
2285     void get_ititle(zmpeg3_t *zsrc, int chapter=0);
2286     void icell_map(zmpeg3_t *zsrc, icell_table_t *icell_addrs);
2287     int chk(int vts_title, int chapter, int inlv, int angle,
2288       icell_table_t *icell_addrs, int &sectors, int &pcells, int &max_angle);
2289   };
2290
2291   // Table of contents storage
2292   int64_t **frame_offsets;
2293   int64_t **sample_offsets;
2294   int **keyframe_numbers;
2295   int64_t *video_eof;
2296   int64_t *audio_eof;
2297   int *total_frame_offsets;
2298   int *total_sample_offsets;
2299   int64_t *total_samples;
2300   int *total_keyframe_numbers;
2301   // Handles changes in channel count after the start of a stream
2302   int *channel_counts, *nudging;
2303   // Indexes for audio tracks
2304   index_t **indexes;
2305   int total_indexes;
2306   double cell_time; // time at start of last cell
2307   // toc/skim thumbnail data callback
2308   zthumbnail_cb thumbnail_fn;
2309   void *thumbnail_priv;
2310
2311   // Number of bytes to devote to the index of a single track
2312   // in the index building process.
2313   int64_t index_bytes;
2314   int file_type, log_errs;
2315   int err_logging(int v=-1) { int lv = log_errs; if( v>=0 ) log_errs=v; return lv; }
2316   // Only one of these is set to 1 to specify what kind of stream we have.
2317   int is_transport_stream() { return file_type & FT_TRANSPORT_STREAM; }
2318   int is_program_stream() { return file_type & FT_PROGRAM_STREAM; }
2319   int is_audio_stream() { return file_type & FT_AUDIO_STREAM; } // Elemental stream
2320   int is_video_stream() { return file_type & FT_VIDEO_STREAM; } // Elemental stream
2321   int is_ifo_file() { return file_type & FT_IFO_FILE; } // dvd ifo file
2322   // Special kind of transport stream for BD or AVC-HD
2323   int is_bd() { return 0; /* file_type & FT_BD_FILE; */ }
2324   int packet_size; // > 0 if known otherwise determine empirically for every packet
2325   // Type and stream for getting current absolute byte
2326   int last_type_read;  // 1 - audio   2 - video
2327   int last_stream_read;
2328   int vts_title;  // video titleset title number (counting from 0)
2329   int total_vts_titles;
2330   int interleave, angle; // active program sector interleave/angle index
2331   int total_interleaves;
2332   int cpus; // number of decode threads
2333   int seekable; // Filesystem is seekable.  Also means the file isn't a stream.
2334   int last_cell_no; // last known cell no in TOC build
2335   int pts_padding; // use pts data to add padding to sync damaged data
2336   FILE *toc_fp; // For building TOC, the output file.
2337   int recd_fd; // record file
2338   int64_t recd_pos; // record file size
2339   /* The first color palette in the IFO file.  Used for subtitles.
2340    * Byte order: YUVX * 16 */
2341   int have_palette;
2342   uint8_t palette[16 * 4];
2343   // Date of source file index was created from.
2344   // Used to compare DVD source file to table of contents source.
2345   int64_t source_date;
2346   // playback cell table
2347   icell_table_t *playinfo;
2348
2349   int calculate_packet_size();
2350   int get_file_type(int *toc_atracks, int *toc_vtracks, const char *title_path);
2351   int read_toc(int *toc_atracks, int *toc_vtracks, const char *title_path);
2352   enum { show_toc_SAMPLE_OFFSETS=1, show_toc_AUDIO_INDEX=2, show_toc_FRAME_OFFSETS=4 };
2353   int show_toc(int flags);
2354   int handle_nudging();
2355   void divide_index(int track_number);
2356   int update_index(int track_number,int flush);
2357   static ifo_t *ifo_open(int fd,long pos);
2358   int read_ifo();
2359   atrack_t *new_atrack_t(int custom_id, int format,
2360     demuxer_t *demux, int number);
2361   vtrack_t *new_vtrack_t(int custom_id, demuxer_t *demux, int number);
2362   audio_t *new_audio_t(atrack_t *ztrack, int zformat);
2363   video_t *new_video_t(vtrack_t *ztrack);
2364   strack_t* get_strack_id(int id, video_t *vid);
2365   strack_t* get_strack(int number);
2366   strack_t* create_strack(int id, video_t *vid=0);
2367   int display_subtitle(int stream, int sid, int id,
2368     uint8_t *yp, uint8_t *up, uint8_t *vp, uint8_t *ap,
2369     int x, int y, int w, int h, double start_msecs, double stop_msecs);
2370   int delete_subtitle(int stream, int sid, int id);
2371   static int clip(int v, int mn, int mx) {
2372     if( v > mx ) return mx;
2373     if( v < mn ) return mn;
2374     return v;
2375   }
2376   static uint8_t clip(int32_t v) {
2377     return ((uint8_t)v) == v ? v : clip(v,0,255);
2378   }
2379   void handle_subtitle();
2380   void handle_cell(int this_cell_no);
2381
2382 #ifdef ZDVB
2383   class dvb_t {
2384     uint8_t *xbfr, *eob;
2385     uint32_t get8bits()  { return xbfr < eob ? *xbfr++ : 0; }
2386     uint32_t get16bits() { uint32_t v = get8bits();  return (v<<8) | get8bits(); }
2387     uint32_t get24bits() { uint32_t v = get16bits(); return (v<<8) | get8bits(); }
2388     uint32_t get32bits() { uint32_t v = get24bits(); return (v<<8) | get8bits(); }
2389   public:
2390     class mgt_t;  // master guide table
2391     class vct_t;  // virtual channel table
2392     class rrt_t;  // rating region table
2393     class eit_t;  // event information table
2394     class ett_t;  // extended text table
2395     class stt_t;  // system time table
2396
2397     class mgt_t {
2398     public:
2399       new_memset(0);
2400
2401       dvb_t *dvb;
2402       uint32_t ver;
2403       int items;
2404       class mitem_t {
2405       public:
2406         new_memset(0);
2407         uint8_t *bfr;
2408         int bfr_size, bfr_alloc;
2409         int src_id, tbl_id, tbl_len;
2410         uint16_t type;
2411         uint16_t pid;
2412         uint32_t version;
2413         uint32_t size;
2414         void init(int len);
2415         void clear();
2416         void extract(uint8_t *dat, int len);
2417         int bfr_len() { return  tbl_len - bfr_size; }
2418         mitem_t() {}
2419         mitem_t(int zpid) : pid(zpid) { bfr=0; bfr_size=bfr_alloc=0; }
2420         ~mitem_t() { clear(); }
2421       } *mitems;
2422       void clear();
2423       void extract();
2424       mitem_t *search(uint16_t pid);
2425       mgt_t(dvb_t *p) : dvb(p) {}
2426       ~mgt_t() { clear(); }
2427     } *mgt;
2428
2429     class vct_t {
2430     public:
2431       new_memset(0);
2432       class vitem_t;
2433
2434       dvb_t *dvb;
2435       uint32_t version;
2436       uint32_t transport_stream_id;
2437       int items, items_allocated;
2438
2439       class vitem_t {
2440       public:
2441         new_memset(0);
2442         class ch_elts_t;
2443
2444         uint16_t short_name[7+1];
2445         uint32_t major_channel_number;
2446         uint32_t minor_channel_number;
2447         uint32_t modulation_mode;
2448         uint32_t carrier_frequency;
2449         uint32_t channel_TSID;
2450         uint32_t program_number;
2451         uint32_t etm_location;
2452         uint8_t access_controlled;
2453         uint8_t hidden;
2454         uint8_t path_select;
2455         uint8_t out_of_band;
2456         uint32_t service_type;
2457         uint32_t source_id;
2458         uint32_t pcr_pid;
2459         int num_ch_elts;
2460         class ch_elts_t {
2461         public:
2462           uint32_t stream_id;
2463           uint32_t pes_pid;
2464           uint8_t  code_639[3];
2465           void extract(dvb_t *dvb);
2466         } elts[10];
2467         void extract(dvb_t *dvb);
2468       } **vct_tbl;
2469
2470       vct_t(dvb_t *p) : dvb(p) {}
2471       ~vct_t() { clear(); }
2472       void extract();
2473       void clear();
2474       int search(vitem_t &new_item);
2475       void append(vitem_t &new_item);
2476     } *tvct, *cvct;
2477
2478     class rrt_t {
2479     public:
2480       new_memset(0);
2481       class ritem_t;
2482
2483       dvb_t *dvb;
2484       uint32_t version;
2485       uint8_t region_nlen;
2486       uint8_t region_name[2*32+1];
2487       int items;
2488
2489       class ritem_t {
2490       public:
2491         new_memset(0);
2492         class rating_vt;
2493
2494         uint8_t dim_nlen;
2495         uint8_t dim_name[2*20+1];
2496         uint8_t graduated_scale;
2497         uint8_t num_values;
2498         class rating_vt {
2499         public:
2500           uint8_t rating_nlen;
2501           uint8_t rating_name[2*8+1];
2502           uint8_t rating_tlen;
2503           uint8_t rating_text[2*150+1];
2504           void extract(dvb_t *dvb);
2505         } *abrevs;
2506         void extract(dvb_t *dvb);
2507         void clear();
2508         ritem_t() {}
2509         ~ritem_t() { clear(); }
2510       } *ratings;
2511
2512       rrt_t(dvb_t *p) : dvb(p) {}
2513       ~rrt_t() { clear(); }
2514       void extract();
2515       void clear();
2516     } *rrt;
2517
2518     class eit_t {
2519     public:
2520       new_memset(0);
2521       class einfo_t;
2522
2523       dvb_t *dvb;
2524       eit_t *next;
2525       int id;
2526       uint32_t version;
2527       uint32_t source_id;
2528       int items, nitems;
2529
2530       class einfo_t {
2531       public:
2532         new_memset(0);
2533         uint16_t event_id;
2534         uint16_t location;
2535         uint32_t start_time;
2536         uint32_t seconds;
2537         uint8_t title_tlen;
2538         uint8_t *title_text;
2539         void extract(dvb_t *dvb);
2540         void clear();
2541         einfo_t() {}
2542         ~einfo_t() { clear(); }
2543       } *infos;
2544
2545       eit_t(dvb_t *p, int id) : dvb(p), id(id) {}
2546       ~eit_t() { clear(); }
2547       void extract();
2548       int search(uint16_t evt_id);
2549       void clear();
2550     } *eit;
2551
2552     class ett_t {
2553     public:
2554       new_memset(0);
2555       class etext_t;
2556
2557       dvb_t *dvb;
2558       ett_t *next;
2559       int id;
2560
2561       class etext_t {
2562       public:
2563         new_memset(0);
2564
2565         etext_t *next;
2566         int id;
2567         uint32_t version;
2568         uint16_t table_id;
2569         uint32_t etm_id;
2570         uint16_t msg_tlen;
2571         uint8_t *msg_text;
2572         void extract(dvb_t *dvb, uint32_t eid);
2573         void clear();
2574         etext_t(int id) : id(id) {}
2575         ~etext_t() { clear(); }
2576       } *texts;
2577
2578       ett_t(dvb_t *p, int id) : dvb(p), id(id) {}
2579       ~ett_t() { clear(); }
2580       void extract();
2581       void clear();
2582     } *ett;
2583
2584     class stt_t {
2585       dvb_t *dvb;
2586     public:
2587       new_memset(0);
2588
2589       uint32_t version;
2590       uint16_t table_id;
2591       uint32_t system_time;
2592       uint8_t utc_offset;
2593       uint16_t daylight_saving;
2594
2595       stt_t(dvb_t *p) : dvb(p) {}
2596       ~stt_t() { clear(); }
2597       void extract();
2598       void clear();
2599     } *stt;
2600
2601     uint32_t stt_start_time;
2602     int64_t stt_offset() {
2603       return (365*10+7)*24*3600L - (stt ? stt->utc_offset : 0);
2604     }
2605
2606     int64_t get_system_time() {
2607       return stt && stt->system_time ? stt->system_time + stt_offset() : -1;
2608     }
2609     zmpeg3_t *src;
2610     int sect_len;
2611     int stream_id;
2612     uint32_t version;
2613     int cur_next;
2614     int sect_num;
2615     int proto_ver;
2616     int empirical;
2617
2618     int bfr_pos()  { return xbfr - active->bfr; }
2619     int bfr_len()  { return active->bfr_size - bfr_pos(); }
2620     void skip_bfr(int n);
2621     void skp_bfr(int n) { if( n > 0 ) skip_bfr(n); }
2622
2623     int text_length, text_allocated;
2624     char *text;
2625     int get_text(uint8_t *dat, int bytes);
2626     void append_text(char *dat, int bytes);
2627     char *mstring(uint8_t *bp, int len);
2628
2629     dvb_t(zmpeg3_t *zsrc);
2630     ~dvb_t();
2631     void reset();
2632     void extract();
2633
2634     mgt_t::mitem_t *active;
2635     mgt_t::mitem_t *atsc_pid(int pid);
2636     mgt_t::mitem_t base_pid;
2637
2638     int atsc_tables(demuxer_t *demux, int pid);
2639     void skip_descr(int descr_len);
2640
2641     int channel_count();
2642     int signal_time();
2643     int get_channel(int n, int &major, int &minor);
2644     int get_station_id(int n, char *name);
2645     int total_astreams(int n, int &count);
2646     int astream_number(int n, int ord, int &stream, char *enc=0);
2647     int total_vstreams(int n, int &count);
2648     int vstream_number(int n, int ord, int &stream);
2649     int read_dvb(demuxer_t *demux);
2650     int get_chan_info(int n, int ord, int i, char *txt, int len);
2651   } dvb;
2652
2653 #endif
2654
2655   // Interface
2656
2657   // Get version information
2658   static int zmajor()   { return ZMPEG3_MAJOR; };
2659   static int zminor()   { return ZMPEG3_MINOR; };
2660   static int zrelease() { return ZMPEG3_RELEASE; };
2661
2662   // Check for file compatibility.  Return 1 if compatible.
2663   static int check_sig(char *path);
2664
2665   // Open the MPEG stream.
2666   // An error code is put into *ret if it fails and error_return is nonzero.
2667   zmpeg3_t(const char *path);
2668   zmpeg3_t(const char *path, int &ret, int access=fs_t::io_UNBUFFERED, const char *title_path=0);
2669   zmpeg3_t(int fd, int &ret, int access=0);
2670   zmpeg3_t(FILE *fp, int &ret, int access=0);
2671   int init(const char *title_path=0);
2672   ~zmpeg3_t();
2673
2674   // Performance
2675   int set_cpus(int cpus);
2676   int set_pts_padding(int v);
2677
2678   // Query the MPEG3 stream about audio.
2679   int has_audio();
2680   int total_astreams();
2681   int audio_channels(int stream);
2682   double sample_rate(int stream);
2683   const char *audio_format(int stream);
2684
2685   // Total length obtained from the timecode.
2686   // For DVD files, this is unreliable.
2687   long audio_nudge(int stream); 
2688   long audio_samples(int stream); 
2689   int set_sample(long sample, int stream);
2690   long get_sample(int stream);
2691
2692   // Stream defines the number of the multiplexed stream to read.
2693   // If output argument is null the audio is not rendered.
2694   // Read a PCM buffer of audio from 1 channel and advance the position.
2695   int read_audio(void *output_v, int type, int channel, long samples, int stream);
2696   int read_audio(double *output_d, int channel, long samples, int stream);
2697   int read_audio(float *output_f, int channel, long samples, int stream);
2698   int read_audio(int *output_i, int channel, long samples, int stream);
2699   int read_audio(short *output_s, int channel, long samples, int stream);
2700   // Read a PCM buffer of audio from 1 channel without advancing the position.
2701   int reread_audio(void *output_v, int type, int channel, long samples, int stream);
2702   int reread_audio(double *output_d, int channel, long samples, int stream);
2703   int reread_audio(float *output_f, int channel, long samples, int stream);
2704   int reread_audio(int *output_i, int channel, long samples, int stream);
2705   int reread_audio(short *output_s, int channel, long samples, int stream);
2706
2707   // Read the next compressed audio chunk.  Store the size in size and return a 
2708   // Stream defines the number of the multiplexed stream to read.
2709   int read_audio_chunk(uint8_t *output, long *size, long max_size, int stream);
2710
2711   // Query the stream about video.
2712   int has_video();
2713   int total_vstreams();
2714   int video_width(int stream);
2715   int video_height(int stream);
2716   int coded_width(int stream);
2717   int coded_height(int stream);
2718   int video_pid(int stream);
2719   float aspect_ratio(int stream); // aspect ratio.  0 if none
2720   double frame_rate(int stream);  // Frames/sec
2721
2722   long video_frames(int stream);  // total length - for TOC files only.
2723   int set_frame(long frame, int stream); // Seek to a frame
2724   // int skip_frames(); /*???*/
2725   long get_frame(int stream);            // Tell current position
2726
2727   // Total bytes.  Used for absolute byte seeking.
2728   int64_t get_bytes();
2729
2730   // Seek all the tracks to the absolute byte in the 
2731   // file.  This eliminates the need for tocs but doesn't 
2732   // give frame accuracy.
2733   int seek_byte(int64_t byte);
2734   int64_t tell_byte();
2735
2736   int previous_frame(int stream);
2737   int end_of_audio(int stream);
2738   int end_of_video(int stream);
2739
2740   // Give the seconds time in the last packet read
2741   double get_time();
2742   double get_audio_time(int stream);
2743   double get_video_time(int stream);
2744   int get_cell_time(int no, double &time);
2745
2746   // Read input frame and scale to the output frame
2747   // The last row of **output_rows must contain 4 extra bytes for scratch work.
2748   int read_frame(uint8_t **output_rows, // row start pointers
2749     int in_x, int in_y, int in_w, int in_h, // Location in input frame
2750     int out_w, int out_h, // Dimensions of output_rows
2751     int color_model, int stream);
2752
2753   // Get the colormodel being used natively by the stream
2754   int colormodel(int stream);
2755   // Set the row stride to be used in read_yuvframe
2756   int set_rowspan(int bytes, int stream);
2757
2758   // Read a frame in the native color model used by the stream. 
2759   // The Y, U, and V planes are copied into the y, u, and v
2760   // BUFFERS Provided.
2761   // The input is cropped to the dimensions given but not scaled.
2762   int read_yuvframe(char *y_output, char *u_output, char *v_output,
2763     int in_x, int in_y, int in_w, int in_h, int stream);
2764
2765   // Read a frame in the native color model used by the stream. 
2766   // The Y, U, and V planes are not copied but the _output pointers
2767   // are redirected to the frame buffer.
2768   int read_yuvframe_ptr(char **y_output, char **u_output, char **v_output,
2769     int stream);
2770
2771   // Drop frames number of frames
2772   int drop_frames(long frames, int stream);
2773
2774   // Read the next compressed frame including headers.
2775   // Store the size in size and return a 1 if error.
2776   // Stream defines the number of the multiplexed stream to read.
2777   int read_video_chunk(uint8_t *output, long *size, long max_size,
2778     int stream);
2779
2780   // Master control
2781   int get_total_vts_titles();
2782   int set_vts_title(int title=-1);
2783   int get_total_interleaves();
2784   int set_interleave(int inlv=-1);
2785   int set_angle(int a=-1);
2786   int set_program(int no); // legacy
2787
2788   // Memory used by video caches.
2789   int64_t memory_usage();
2790   // write incoming datastream on file descr fd
2791   //   buffer access must be io_THREADED.  useful to record dvb device data
2792   //   bsz records up to bsz bytes of past buffer data in write_align
2793   int start_record(int fd, int bsz=0);
2794   int stop_record();
2795   void write_record(uint8_t *data, int len);
2796   // limit position for start of last full packet
2797   int64_t record_position() { return recd_pos - packet_size + 1; }
2798   // restart streams, discard device buffer and reinit file positions
2799   void restart();
2800   // enable/disable data xfr from reader thread
2801   int pause_reader(int v);
2802
2803   // subtitle functions
2804   // get number of subtitle tracks
2805   int subtitle_tracks() { return total_stracks; }
2806   // Enable overlay of a subtitle track.
2807   // track - the number of the subtitle track starting from 0
2808   // The same subtitle track is overlayed for all video tracks.
2809   // track=-1 to disable subtitles.
2810   int show_subtitle(int stream, int strk);
2811
2812   // Table of contents generation
2813   // Begin constructing table of contents
2814   static zmpeg3_t *start_toc(const char *path, const char *toc_path,
2815     int program=0, int64_t *total_bytes=0);
2816   // Set the maximum number of bytes per index track
2817   void set_index_bytes(int64_t bytes) { index_bytes = bytes; }
2818   // Process one packet
2819   int do_toc(int64_t *bytes_processed);
2820   // Write table of contents
2821   void stop_toc();
2822   int set_thumbnail_callback(int trk, int skim, int thumb, zthumbnail_cb fn, void *p);
2823   int get_thumbnail(int trk, int64_t &frn, uint8_t *&t, int &w, int &h);
2824   int set_cc_text_callback(int trk, zcc_text_cb fn);
2825
2826   // Get modification date of source file from table of contents.
2827   // Used to compare DVD source file to table of contents source.
2828   int64_t get_source_date() { return source_date; }
2829   // Get modification date of source file from source file.
2830   static int64_t calculate_source_date(char *path);
2831   static int64_t calculate_source_date(int fd);
2832   // Table of contents queries
2833   int index_tracks();
2834   int index_channels(int track);
2835   int index_zoom();
2836   int index_size(int track);
2837   float* index_data(int track, int channel);
2838   // Returns 1 if the file has a table of contents
2839   int has_toc() {
2840     return frame_offsets || sample_offsets ? 1 : 0;
2841   }
2842   // Return the path of the title number or 0 if no more titles.
2843   char* title_path(int number) {
2844     return number>=0 && number<demuxer->total_titles ?
2845       demuxer->titles[number]->fs->path : 0;
2846   }
2847
2848   static inline void complete_path(char *full_path, char *path) {
2849     char dir[STRLEN];
2850     if( path[0] != '/' && getcwd(dir, sizeof(dir)) )
2851       snprintf(full_path, STRLEN, "%s/%s", dir, path);
2852     else
2853       strcpy(full_path, path);
2854   }
2855
2856   static inline void get_directory(char *directory, char *path) {
2857     char *ptr = strrchr(path, '/');
2858     int i = 0;
2859     if( ptr ) {
2860       int n = ptr-path;
2861       while( i < n ) {
2862         directory[i] = path[i];
2863         ++i;
2864       }
2865     }
2866     if( i == 0 ) directory[i++] = '.';
2867     directory[i] = 0;
2868   }
2869
2870   static inline void get_filename(char *filename, char *path) {
2871     char *ptr = strrchr(path, '/');
2872     if( ptr ) ++ptr;
2873     else ptr = path;
2874     strcpy(filename, ptr);
2875   }
2876
2877   static inline void joinpath(char *path, char *dir, char *filename) {
2878     snprintf(path, STRLEN, "%s/%s", dir, filename);
2879   }
2880
2881   static inline int64_t path_total_bytes(char *path) {
2882     struct stat64 st;
2883     return stat64(path, &st )<0 ? 0 : st.st_size;
2884   }
2885
2886 };
2887
2888 typedef zmpeg3_t::zlock_t                       zzlock_t;
2889 typedef zmpeg3_t::zblock_t                      zzblock_t;
2890 typedef zmpeg3_t::zrwlock_t                     zzrwlock_t;
2891 typedef zmpeg3_t::fs_t                          zfs_t;
2892 typedef   zfs_t::css_t                          zcss_t;
2893 typedef     zcss_t::key_t                       zkey_t;
2894 typedef     zcss_t::blk_t                       zblk_t;
2895 typedef     zcss_t::playkey_t                   zplaykey_t;
2896 typedef   zfs_t::buffer_t                       zbuffer_t;
2897 typedef zmpeg3_t::bits_t                        zbits_t;
2898 typedef zmpeg3_t::index_t                       zindex_t;
2899 typedef zmpeg3_t::bitfont_t                     zbitfont_t;
2900 typedef   zbitfont_t::bitchar_t                 zbitchar_t;
2901 typedef   zbitfont_t::static_init_t             zstatic_init_t;
2902 typedef zmpeg3_t::timecode_t                    ztimecode_t;
2903 typedef zmpeg3_t::audio_t                       zaudio_t;
2904 typedef   zaudio_t::imdct_complex_t             zimdct_complex_t;
2905 typedef   zaudio_t::imdct_al_table_t            zimdct_al_table_t;
2906 typedef   zaudio_t::audio_decoder_layer_t       zaudio_decoder_layer_t;
2907 typedef   zaudio_t::audio_decoder_ac3_t         zaudio_decoder_ac3_t;
2908 typedef   zaudio_t::audio_decoder_pcm_t         zaudio_decoder_pcm_t;
2909 typedef zmpeg3_t::VLCtab_t                      zVLCtab_t;
2910 typedef zmpeg3_t::DCTtab_t                      zDCTtab_t;
2911 typedef zmpeg3_t::slice_buffer_t                zslice_buffer_t;
2912 typedef zmpeg3_t::video_t                       zvideo_t;
2913 typedef   zvideo_t::cc_t                        zcc_t;
2914 typedef     zcc_t::svc_t                        zsvc_t;
2915 typedef       zsvc_t::win_t                     zwin_t;
2916 typedef       zsvc_t::chr_t                     zchr_t;
2917 typedef zmpeg3_t::slice_decoder_t               zslice_decoder_t;
2918 typedef zmpeg3_t::subtitle_t                    zsubtitle_t;
2919 typedef zmpeg3_t::demuxer_t                     zdemuxer_t;
2920 typedef   zdemuxer_t::zstream_t                 zzstream_t;
2921 typedef   zdemuxer_t::title_t                   ztitle_t;
2922 typedef     ztitle_t::cell_t                    zcell_t;
2923 typedef zmpeg3_t::cacheframe_t                  zcacheframe_t;
2924 typedef zmpeg3_t::cache_t                       zcache_t;
2925 typedef zmpeg3_t::atrack_t                      zatrack_t;
2926 typedef zmpeg3_t::vtrack_t                      zvtrack_t;
2927 typedef zmpeg3_t::strack_t                      zstrack_t;
2928 typedef zmpeg3_t::icell_t                       zicell_t;
2929 typedef zmpeg3_t::icell_table_t                 zicell_table_t;
2930 typedef zmpeg3_t::ifo_t                         zifo_t;
2931 #ifdef ZDVB
2932 typedef zmpeg3_t::dvb_t                         zdvb_t;
2933 typedef   zdvb_t::mgt_t                         zmgt_t;
2934 typedef     zmgt_t::mitem_t                     zmitem_t;
2935 typedef   zdvb_t::vct_t                         zvct_t;
2936 typedef     zvct_t::vitem_t                     zvitem_t;
2937 typedef       zvitem_t::ch_elts_t               zch_elts_t;
2938 typedef   zdvb_t::rrt_t                         zrrt_t;
2939 typedef     zrrt_t::ritem_t                     zritem_t;
2940 typedef       zritem_t::rating_vt               zrating_vt;
2941 typedef   zdvb_t::eit_t                         zeit_t;
2942 typedef     zeit_t::einfo_t                     zeinfo_t;
2943 typedef   zdvb_t::ett_t                         zett_t;
2944 typedef     zett_t::etext_t                     zetext_t;
2945 typedef   zdvb_t::stt_t                         zstt_t;
2946 #endif
2947
2948 /* legacy */
2949 extern "C" {
2950 #else
2951 typedef struct {} zmpeg3_t;
2952 #endif /*__cplusplus */
2953 typedef zmpeg3_t mpeg3_t;
2954
2955 int mpeg3_major(void);
2956 int mpeg3_minor(void);
2957 int mpeg3_release(void);
2958 int mpeg3_check_sig(char *path);
2959 int mpeg3_is_program_stream(zmpeg3_t * zsrc);
2960 int mpeg3_is_transport_stream(zmpeg3_t * zsrc);
2961 int mpeg3_is_video_stream(zmpeg3_t * zsrc);
2962 int mpeg3_is_audio_stream(zmpeg3_t * zsrc);
2963 int mpeg3_is_ifo_file(zmpeg3_t * zsrc);
2964 int mpeg3_create_title(zmpeg3_t * zsrc,int full_scan);
2965 zmpeg3_t *mpeg3_open(const char *path,int *error_return);
2966 zmpeg3_t *mpeg3_open_title(const char *title_path,const char *path,int *error_return);
2967 zmpeg3_t *mpeg3_zopen(const char *title_path,const char *path,int *error_return, int access);
2968 zmpeg3_t *mpeg3_open_copy(const char *path,zmpeg3_t *old_src,int *error_return);
2969 int mpeg3_close(zmpeg3_t *zsrc);
2970 int mpeg3_set_pts_padding(zmpeg3_t *zsrc, int v);
2971 int mpeg3_set_cpus(zmpeg3_t *zsrc,int cpus);
2972 int mpeg3_has_audio(zmpeg3_t *zsrc);
2973 int mpeg3_total_astreams(zmpeg3_t *zsrc);
2974 int mpeg3_audio_channels(zmpeg3_t *zsrc,int stream);
2975 int mpeg3_sample_rate(zmpeg3_t *zsrc,int stream);
2976 const char *mpeg3_audio_format(zmpeg3_t *zsrc,int stream);
2977 long mpeg3_get_audio_nudge(zmpeg3_t *zsrc,int stream);
2978 long mpeg3_audio_samples(zmpeg3_t *zsrc,int stream);
2979 int mpeg3_set_sample(zmpeg3_t *zsrc,long sample,int stream);
2980 long mpeg3_get_sample(zmpeg3_t *zsrc,int stream);
2981 int mpeg3_read_audio(zmpeg3_t *zsrc,float *output_f,short *output_i,int channel,
2982    long samples,int stream);
2983 int mpeg3_read_audio_d(zmpeg3_t *zsrc,double *output_d, int channel,
2984    long samples, int stream);
2985 int mpeg3_read_audio_f(zmpeg3_t *zsrc,float *output_f, int channel,
2986    long samples, int stream);
2987 int mpeg3_read_audio_i(zmpeg3_t *zsrc,int *output_i, int channel,
2988    long samples, int stream);
2989 int mpeg3_read_audio_s(zmpeg3_t *zsrc,short *output_s, int channel,
2990    long samples, int stream);
2991 int mpeg3_reread_audio_d(zmpeg3_t *zsrc,double *output_d, int channel,
2992    long samples, int stream);
2993 int mpeg3_reread_audio_f(zmpeg3_t *zsrc,float *output_f, int channel,
2994    long samples, int stream);
2995 int mpeg3_reread_audio_i(zmpeg3_t *zsrc,int *output_i, int channel,
2996    long samples, int stream);
2997 int mpeg3_reread_audio_s(zmpeg3_t *zsrc,short *output_s, int channel,
2998    long samples, int stream);
2999 int mpeg3_reread_audio(zmpeg3_t *zsrc,float *output_f,short *output_i,
3000    int channel,long samples,int stream);
3001 int mpeg3_read_audio_chunk(zmpeg3_t *zsrc,unsigned char *output,long *size,
3002    long max_size,int stream);
3003 int mpeg3_has_video(zmpeg3_t *zsrc);
3004 int mpeg3_total_vstreams(zmpeg3_t *zsrc);
3005 int mpeg3_video_width(zmpeg3_t *zsrc,int stream);
3006 int mpeg3_video_height(zmpeg3_t *zsrc,int stream);
3007 int mpeg3_coded_width(zmpeg3_t *zsrc,int stream);
3008 int mpeg3_coded_height(zmpeg3_t *zsrc,int stream);
3009 int mpeg3_video_pid(zmpeg3_t *zsrc,int stream);
3010 float mpeg3_aspect_ratio(zmpeg3_t *zsrc,int stream);
3011 double mpeg3_frame_rate(zmpeg3_t *zsrc,int stream);
3012 long mpeg3_video_frames(zmpeg3_t *zsrc,int stream);
3013 int mpeg3_set_frame(zmpeg3_t *zsrc,long frame,int stream);
3014 //int mpeg3_skip_frames(zmpeg3_t *zsrc);
3015 long mpeg3_get_frame(zmpeg3_t *zsrc,int stream);
3016 int64_t mpeg3_get_bytes(zmpeg3_t *zsrc);
3017 int mpeg3_seek_byte(zmpeg3_t *zsrc,int64_t byte);
3018 int64_t mpeg3_tell_byte(zmpeg3_t *zsrc);
3019 int mpeg3_previous_frame(zmpeg3_t *zsrc,int stream);
3020 int mpeg3_end_of_audio(zmpeg3_t *zsrc,int stream);
3021 int mpeg3_end_of_video(zmpeg3_t *zsrc,int stream);
3022 double mpeg3_get_time(zmpeg3_t *zsrc);
3023 double mpeg3_get_audio_time(zmpeg3_t *zsrc, int stream);
3024 double mpeg3_get_video_time(zmpeg3_t *zsrc, int stream);
3025 double mpeg3_get_cell_time(zmpeg3_t *zsrc, int no, double *time);
3026 int mpeg3_read_frame(zmpeg3_t *zsrc,unsigned char **output_rows,int in_x,
3027    int in_y,int in_w,int in_h,int out_w,int out_h,int color_model,int stream);
3028 int mpeg3_colormodel(zmpeg3_t *zsrc,int stream);
3029 int mpeg3_set_rowspan(zmpeg3_t *zsrc,int bytes,int stream);
3030 int mpeg3_read_yuvframe(zmpeg3_t *zsrc,char *y_output,char *u_output,
3031    char *v_output,int in_x,int in_y,int in_w,int in_h,int stream);
3032 int mpeg3_read_yuvframe_ptr(zmpeg3_t *zsrc,char **y_output,char **u_output,
3033    char **v_output,int stream);
3034 int mpeg3_drop_frames(zmpeg3_t *zsrc,long frames,int stream);
3035 int mpeg3_read_video_chunk(zmpeg3_t *zsrc,unsigned char *output,long *size,
3036    long max_size,int stream);
3037 int mpeg3_get_total_vts_titles(zmpeg3_t *zsrc);
3038 int mpeg3_set_vts_title(zmpeg3_t *zsrc,int title); // toc build only
3039 int mpeg3_get_total_interleaves(zmpeg3_t *zsrc);
3040 int mpeg3_set_interleave(zmpeg3_t *zsrc,int inlv); // toc build only
3041 int mpeg3_set_angle(zmpeg3_t *zsrc,int a); // toc build only
3042 int mpeg3_set_program(zmpeg3_t *zsrc,int no); // toc build only
3043 int64_t mpeg3_memory_usage(zmpeg3_t *zsrc);
3044 int mpeg3_get_thumbnail(zmpeg3_t *zsrc, int trk,
3045    int64_t *frn, uint8_t **t, int *w, int *h);
3046 int mpeg3_set_thumbnail_callback(zmpeg3_t *zsrc, int trk,
3047    int skim, int thumb, zthumbnail_cb fn, void *p);
3048 int mpeg3_set_cc_text_callback(zmpeg3_t *zsrc, int trk, zcc_text_cb fn);
3049 int mpeg3_subtitle_tracks(zmpeg3_t *zsrc);
3050 int mpeg3_show_subtitle(zmpeg3_t *zsrc,int vtrk, int strk);
3051 int mpeg3_display_subtitle(zmpeg3_t *zsrc,int stream,int sid,int id,
3052    uint8_t *yp,uint8_t *up,uint8_t *vp,uint8_t *ap,
3053    int x,int y,int w,int h,double start_msecs,double stop_msecs);
3054 int mpeg3_delete_subtitle(zmpeg3_t *zsrc,int stream,int sid,int id);
3055 zmpeg3_t *mpeg3_start_toc(char *path,char *toc_path,int program,int64_t *total_bytes);
3056 void mpeg3_set_index_bytes(zmpeg3_t *zsrc,int64_t bytes);
3057 int mpeg3_do_toc(zmpeg3_t *zsrc,int64_t *bytes_processed);
3058 void mpeg3_stop_toc(zmpeg3_t *zsrc);
3059 int64_t mpeg3_get_source_date(zmpeg3_t *zsrc);
3060 int64_t mpeg3_calculate_source_date(char *path);
3061 int mpeg3_index_tracks(zmpeg3_t *zsrc);
3062 int mpeg3_index_channels(zmpeg3_t *zsrc,int track);
3063 int mpeg3_index_zoom(zmpeg3_t *zsrc);
3064 int mpeg3_index_size(zmpeg3_t *zsrc,int track);
3065 float *mpeg3_index_data(zmpeg3_t *zsrc,int track,int channel);
3066 int mpeg3_has_toc(zmpeg3_t *zsrc);
3067 char *mpeg3_title_path(zmpeg3_t *zsrc,int number);
3068 // hooks needed for quicktime
3069 typedef struct {} mpeg3_layer_t;
3070 int mpeg3audio_dolayer3(mpeg3_layer_t *audio,
3071    char *frame, int frame_size, float **output, int render);
3072 int mpeg3_layer_header(mpeg3_layer_t *layer_data, unsigned char *data);
3073 void mpeg3_layer_reset(mpeg3_layer_t *zlayer_data);
3074 mpeg3_layer_t* mpeg3_new_layer();
3075 void mpeg3_delete_layer(mpeg3_layer_t *audio);
3076 // hooks needed for mplexlo
3077 void mpeg3_skip_video_frame(mpeg3_t *zsrc, int stream);
3078 int64_t mpeg3_video_tell_byte(mpeg3_t *zsrc, int stream);
3079 int64_t mpeg3_audio_tell_byte(mpeg3_t *zsrc, int stream);
3080 #ifdef ZDVB
3081 int mpeg3_dvb_channel_count(zmpeg3_t *zsrc);
3082 int mpeg3_dvb_get_channel(mpeg3_t *zsrc,int n, int *major, int *minor);
3083 int mpeg3_dvb_get_station_id(mpeg3_t *zsrc,int n, char *name);
3084 int mpeg3_dvb_total_astreams(mpeg3_t *zsrc,int n, int *count);
3085 int mpeg3_dvb_astream_number(mpeg3_t *zsrc,int n, int ord, int *stream, char *enc);
3086 int mpeg3_dvb_total_vstreams(mpeg3_t *zsrc,int n, int *count);
3087 int mpeg3_dvb_vstream_number(mpeg3_t *zsrc,int n, int ord, int *stream);
3088 int mpeg3_dvb_get_chan_info(mpeg3_t *zsrc,int n, int ord, int i, char *cp, int len);
3089 int mpeg3_dvb_get_system_time(mpeg3_t *zsrc, int64_t *tm);
3090 #endif
3091 #ifdef __cplusplus
3092 }
3093 #endif
3094 #endif