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