1 /*
2  *  avilib.h
3  *
4  *  Copyright (C) Thomas �streich - June 2001
5  *  multiple audio track support Copyright (C) 2002 Thomas �streich
6  *
7  *  Original code:
8  *  Copyright (C) 1999 Rainer Johanni <Rainer@Johanni.de>
9  *
10  *  This file is part of transcode, a linux video stream processing tool
11  *
12  *  transcode is free software; you can redistribute it and/or modify
13  *  it under the terms of the GNU General Public License as published by
14  *  the Free Software Foundation; either version 2, or (at your option)
15  *  any later version.
16  *
17  *  transcode is distributed in the hope that it will be useful,
18  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  *  GNU General Public License for more details.
21  *
22  *  You should have received a copy of the GNU General Public License
23  *  along with GNU Make; see the file COPYING.  If not, write to
24  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25  *
26  */
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <stdio.h>
31 #include <fcntl.h>
32 
33 #include <unistd.h>
34 #include <inttypes.h>
35 
36 #include <limits.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40 
41 #ifndef AVILIB_H
42 #define AVILIB_H
43 
44 #define COMP_GCC
45 #define SYS_LINUX
46 #define SYS_UNIX
47 
48 #define AVI_MAX_TRACKS 8
49 
50 typedef struct
51 {
52   int64_t key;
53   int64_t pos;
54   int64_t len;
55 } video_index_entry;
56 
57 typedef struct
58 {
59    int64_t pos;
60    int64_t len;
61    int64_t tot;
62 } audio_index_entry;
63 
64 
65 // Index types
66 
67 
68 #define AVI_INDEX_OF_INDEXES 0x00             // when each entry in aIndex
69                                               // array points to an index chunk
70 #define AVI_INDEX_OF_CHUNKS  0x01             // when each entry in aIndex
71                                               // array points to a chunk in the file
72 #define AVI_INDEX_IS_DATA    0x80             // when each entry is aIndex is
73                                               // really the data
74 // bIndexSubtype codes for INDEX_OF_CHUNKS
75 //
76 #define AVI_INDEX_2FIELD     0x01             // when fields within frames
77                                               // are also indexed
78 
79 
80 
81 typedef struct _avisuperindex_entry {
82     uint64_t qwOffset;           // absolute file offset
83     uint32_t dwSize;                  // size of index chunk at this offset
84     uint32_t dwDuration;              // time span in stream ticks
85 } avisuperindex_entry;
86 
87 typedef struct _avistdindex_entry {
88     uint32_t dwOffset;                // qwBaseOffset + this is absolute file offset
89     uint32_t dwSize;                  // bit 31 is set if this is NOT a keyframe
90 } avistdindex_entry;
91 
92 // Standard index
93 typedef struct _avistdindex_chunk {
94     char           fcc[4];                 // ix##
95     uint32_t  dwSize;                 // size of this chunk
96     uint16_t wLongsPerEntry;         // must be sizeof(aIndex[0])/sizeof(DWORD)
97     uint8_t  bIndexSubType;          // must be 0
98     uint8_t  bIndexType;             // must be AVI_INDEX_OF_CHUNKS
99     uint32_t  nEntriesInUse;          //
100     char           dwChunkId[4];           // '##dc' or '##db' or '##wb' etc..
101     uint64_t qwBaseOffset;       // all dwOffsets in aIndex array are relative to this
102     uint32_t  dwReserved3;            // must be 0
103     avistdindex_entry *aIndex;
104 } avistdindex_chunk;
105 
106 
107 // Base Index Form 'indx'
108 typedef struct _avisuperindex_chunk {
109     char           fcc[4];
110     uint32_t  dwSize;                 // size of this chunk
111     uint16_t wLongsPerEntry;         // size of each entry in aIndex array (must be 8 for us)
112     uint8_t  bIndexSubType;          // future use. must be 0
113     uint8_t  bIndexType;             // one of AVI_INDEX_* codes
114     uint32_t  nEntriesInUse;          // index of first unused member in aIndex array
115     char           dwChunkId[4];           // fcc of what is indexed
116     uint32_t  dwReserved[3];          // meaning differs for each index type/subtype.
117                                            // 0 if unused
118     avisuperindex_entry *aIndex;           // where are the ix## chunks
119     avistdindex_chunk **stdindex;          // the ix## chunks itself (array)
120 } avisuperindex_chunk;
121 
122 
123 
124 typedef struct track_s
125 {
126 
127     long   a_fmt;             /* Audio format, see #defines below */
128     long   a_chans;           /* Audio channels, 0 for no audio */
129     long   a_rate;            /* Rate in Hz */
130     long   a_bits;            /* bits per audio sample */
131     long   mp3rate;           /* mp3 bitrate kbs*/
132     long   a_vbr;             /* 0 == no Variable BitRate */
133     long   padrate;	      /* byte rate used for zero padding */
134 
135     long   audio_strn;        /* Audio stream number */
136     int64_t  audio_bytes;       /* Total number of bytes of audio data */
137     long   audio_chunks;      /* Chunks of audio data in the file */
138 
139     char   audio_tag[4];      /* Tag of audio data */
140     long   audio_posc;        /* Audio position: chunk */
141     long   audio_posb;        /* Audio position: byte within chunk */
142 
143     int64_t  a_codech_off;       /* absolut offset of audio codec information */
144     int64_t  a_codecf_off;       /* absolut offset of audio codec information */
145 
146     audio_index_entry *audio_index;
147     avisuperindex_chunk *audio_superindex;
148 
149 } track_t;
150 
151 typedef struct
152 {
153   uint32_t  bi_size;
154   uint32_t  bi_width;
155   uint32_t  bi_height;
156   uint16_t  bi_planes;
157   uint16_t  bi_bit_count;
158   uint32_t  bi_compression;
159   uint32_t  bi_size_image;
160   uint32_t  bi_x_pels_per_meter;
161   uint32_t  bi_y_pels_per_meter;
162   uint32_t  bi_clr_used;
163   uint32_t  bi_clr_important;
164 } alBITMAPINFOHEADER;
165 
166 typedef struct __attribute__((__packed__))
167 {
168   uint16_t  w_format_tag;
169   uint16_t  n_channels;
170   uint32_t  n_samples_per_sec;
171   uint32_t  n_avg_bytes_per_sec;
172   uint16_t  n_block_align;
173   uint16_t  w_bits_per_sample;
174   uint16_t  cb_size;
175 } alWAVEFORMATEX;
176 
177 typedef struct __attribute__((__packed__))
178 {
179   uint32_t fcc_type;
180   uint32_t fcc_handler;
181   uint32_t dw_flags;
182   uint32_t dw_caps;
183   uint16_t w_priority;
184   uint16_t w_language;
185   uint32_t dw_scale;
186   uint32_t dw_rate;
187   uint32_t dw_start;
188   uint32_t dw_length;
189   uint32_t dw_initial_frames;
190   uint32_t dw_suggested_buffer_size;
191   uint32_t dw_quality;
192   uint32_t dw_sample_size;
193   uint16_t dw_left;
194   uint16_t dw_top;
195   uint16_t dw_right;
196   uint16_t dw_bottom;
197 } alAVISTREAMHEADER;
198 
199 typedef struct
200 {
201 
202   long   fdes;              /* File descriptor of AVI file */
203   long   mode;              /* 0 for reading, 1 for writing */
204 
205   long   width;             /* Width  of a video frame */
206   long   height;            /* Height of a video frame */
207   double fps;               /* Frames per second */
208   char   compressor[8];     /* Type of compressor, 4 bytes + padding for 0 byte */
209   char   compressor2[8];     /* Type of compressor, 4 bytes + padding for 0 byte */
210   long   video_strn;        /* Video stream number */
211   long   video_frames;      /* Number of video frames */
212   char   video_tag[4];      /* Tag of video data */
213   long   video_pos;         /* Number of next frame to be read
214 			       (if index present) */
215   alAVISTREAMHEADER video_stream_header;
216 
217   uint32_t max_len;    /* maximum video chunk present */
218 
219   track_t track[AVI_MAX_TRACKS];  // up to AVI_MAX_TRACKS audio tracks supported
220 
221   int64_t  pos;               /* position in file */
222   long   n_idx;             /* number of index entries actually filled */
223   long   max_idx;           /* number of index entries actually allocated */
224 
225   int64_t  v_codech_off;      /* absolut offset of video codec (strh) info */
226   int64_t  v_codecf_off;      /* absolut offset of video codec (strf) info */
227 
228   uint8_t (*idx)[16]; /* index entries (AVI idx1 tag) */
229 
230   video_index_entry *video_index;
231   avisuperindex_chunk *video_superindex;  /* index of indices */
232   int is_opendml;           /* set to 1 if this is an odml file with multiple index chunks */
233 
234   int64_t  last_pos;          /* Position of last frame written */
235   uint32_t last_len;   /* Length of last frame written */
236   int must_use_index;       /* Flag if frames are duplicated */
237   int64_t  movi_start;
238   int total_frames;         /* total number of frames if dmlh is present */
239 
240   int anum;            // total number of audio tracks
241   int aptr;            // current audio working track
242   int comment_fd;      // Read avi header comments from this fd
243   char *index_file;    // read the avi index from this file
244 
245   alBITMAPINFOHEADER *bitmap_info_header;
246   alWAVEFORMATEX *wave_format_ex[AVI_MAX_TRACKS];
247   alAVISTREAMHEADER stream_headers[AVI_MAX_TRACKS];
248 
249   void*		extradata;
250   unsigned long	extradata_size;
251 } avi_t;
252 
253 #define AVI_MODE_WRITE  0
254 #define AVI_MODE_READ   1
255 
256 /* The error codes delivered by avi_open_input_file */
257 
258 #define AVI_ERR_SIZELIM      1     /* The write of the data would exceed
259                                       the maximum size of the AVI file.
260                                       This is more a warning than an error
261                                       since the file may be closed safely */
262 
263 #define AVI_ERR_OPEN         2     /* Error opening the AVI file - wrong path
264                                       name or file nor readable/writable */
265 
266 #define AVI_ERR_READ         3     /* Error reading from AVI File */
267 
268 #define AVI_ERR_WRITE        4     /* Error writing to AVI File,
269                                       disk full ??? */
270 
271 #define AVI_ERR_WRITE_INDEX  5     /* Could not write index to AVI file
272                                       during close, file may still be
273                                       usable */
274 
275 #define AVI_ERR_CLOSE        6     /* Could not write header to AVI file
276                                       or not truncate the file during close,
277                                       file is most probably corrupted */
278 
279 #define AVI_ERR_NOT_PERM     7     /* Operation not permitted:
280                                       trying to read from a file open
281                                       for writing or vice versa */
282 
283 #define AVI_ERR_NO_MEM       8     /* malloc failed */
284 
285 #define AVI_ERR_NO_AVI       9     /* Not an AVI file */
286 
287 #define AVI_ERR_NO_HDRL     10     /* AVI file has no has no header list,
288                                       corrupted ??? */
289 
290 #define AVI_ERR_NO_MOVI     11     /* AVI file has no has no MOVI list,
291                                       corrupted ??? */
292 
293 #define AVI_ERR_NO_VIDS     12     /* AVI file contains no video data */
294 
295 #define AVI_ERR_NO_IDX      13     /* The file has been opened with
296                                       getIndex==0, but an operation has been
297                                       performed that needs an index */
298 
299 /* Possible Audio formats */
300 
301 #ifndef WAVE_FORMAT_PCM
302 #define WAVE_FORMAT_UNKNOWN             (0x0000)
303 #define WAVE_FORMAT_PCM                 (0x0001)
304 #define WAVE_FORMAT_ADPCM               (0x0002)
305 #define WAVE_FORMAT_IBM_CVSD            (0x0005)
306 #define WAVE_FORMAT_ALAW                (0x0006)
307 #define WAVE_FORMAT_MULAW               (0x0007)
308 #define WAVE_FORMAT_OKI_ADPCM           (0x0010)
309 #define WAVE_FORMAT_DVI_ADPCM           (0x0011)
310 #define WAVE_FORMAT_DIGISTD             (0x0015)
311 #define WAVE_FORMAT_DIGIFIX             (0x0016)
312 #define WAVE_FORMAT_YAMAHA_ADPCM        (0x0020)
313 #define WAVE_FORMAT_DSP_TRUESPEECH      (0x0022)
314 #define WAVE_FORMAT_GSM610              (0x0031)
315 #define IBM_FORMAT_MULAW                (0x0101)
316 #define IBM_FORMAT_ALAW                 (0x0102)
317 #define IBM_FORMAT_ADPCM                (0x0103)
318 #endif
319 
320 avi_t* AVI_open_output_file(char * filename);
321 void AVI_set_video(avi_t *AVI, int width, int height, double fps, char *compressor);
322 void AVI_set_audio(avi_t *AVI, int channels, long rate, int bits, int format, long mp3rate);
323 int  AVI_write_frame(avi_t *AVI, char *data, long bytes, int keyframe);
324 int  AVI_dup_frame(avi_t *AVI);
325 int  AVI_write_audio(avi_t *AVI, char *data, long bytes);
326 int  AVI_append_audio(avi_t *AVI, char *data, long bytes);
327 long AVI_bytes_remain(avi_t *AVI);
328 int  AVI_close(avi_t *AVI);
329 long AVI_bytes_written(avi_t *AVI);
330 
331 avi_t *AVI_open_input_file(char *filename, int getIndex);
332 avi_t *AVI_open_input_indexfile(char *filename, int getIndex, char *indexfile);
333 avi_t *AVI_open_fd(int fd, int getIndex);
334 avi_t *AVI_open_indexfd(int fd, int getIndex, char *indexfile);
335 int avi_parse_input_file(avi_t *AVI, int getIndex);
336 int avi_parse_index_from_file(avi_t *AVI, char *filename);
337 long AVI_audio_mp3rate(avi_t *AVI);
338 long AVI_audio_padrate(avi_t *AVI);
339 long AVI_video_frames(avi_t *AVI);
340 int  AVI_video_width(avi_t *AVI);
341 int  AVI_video_height(avi_t *AVI);
342 double AVI_frame_rate(avi_t *AVI);
343 char* AVI_video_compressor(avi_t *AVI);
344 
345 int  AVI_audio_channels(avi_t *AVI);
346 int  AVI_audio_bits(avi_t *AVI);
347 int  AVI_audio_format(avi_t *AVI);
348 long AVI_audio_rate(avi_t *AVI);
349 long AVI_audio_bytes(avi_t *AVI);
350 long AVI_audio_chunks(avi_t *AVI);
351 int  AVI_can_read_audio(avi_t *AVI);
352 
353 long AVI_max_video_chunk(avi_t *AVI);
354 
355 long AVI_frame_size(avi_t *AVI, long frame);
356 long AVI_audio_size(avi_t *AVI, long frame);
357 int  AVI_seek_start(avi_t *AVI);
358 int  AVI_set_video_position(avi_t *AVI, long frame);
359 long AVI_get_video_position(avi_t *AVI, long frame);
360 long AVI_read_frame(avi_t *AVI, char *vidbuf, int *keyframe);
361 
362 int  AVI_set_audio_position(avi_t *AVI, long byte);
363 int  AVI_set_audio_bitrate(avi_t *AVI, long bitrate);
364 
365 long AVI_get_audio_position_index(avi_t *AVI);
366 int  AVI_set_audio_position_index(avi_t *AVI, long indexpos);
367 
368 long AVI_read_audio(avi_t *AVI, char *audbuf, long bytes);
369 long AVI_read_audio_chunk(avi_t *AVI, char *audbuf);
370 
371 long AVI_audio_codech_offset(avi_t *AVI);
372 long AVI_audio_codecf_offset(avi_t *AVI);
373 long AVI_video_codech_offset(avi_t *AVI);
374 long AVI_video_codecf_offset(avi_t *AVI);
375 
376 int  AVI_read_data(avi_t *AVI, char *vidbuf, long max_vidbuf,
377                                char *audbuf, long max_audbuf,
378                                long *len);
379 
380 void AVI_print_error(char *str);
381 char *AVI_strerror(void);
382 char *AVI_syserror(void);
383 
384 int AVI_scan(char *name);
385 int AVI_dump(char *name, int mode);
386 
387 char *AVI_codec2str(short cc);
388 int AVI_file_check(char *import_file);
389 
390 void AVI_info(avi_t *avifile);
391 uint64_t AVI_max_size(void);
392 int avi_update_header(avi_t *AVI);
393 
394 int AVI_set_audio_track(avi_t *AVI, int track);
395 int AVI_get_audio_track(avi_t *AVI);
396 int AVI_audio_tracks(avi_t *AVI);
397 
398 void AVI_set_audio_vbr(avi_t *AVI, long is_vbr);
399 long AVI_get_audio_vbr(avi_t *AVI);
400 
401 void AVI_set_comment_fd(avi_t *AVI, int fd);
402 int  AVI_get_comment_fd(avi_t *AVI);
403 
404 struct riff_struct
405 {
406   uint8_t id[4];   /* RIFF */
407   uint32_t len;
408   uint8_t wave_id[4]; /* WAVE */
409 };
410 
411 
412 struct chunk_struct
413 {
414 	uint8_t id[4];
415 	uint32_t len;
416 };
417 
418 struct common_struct
419 {
420 	uint16_t wFormatTag;
421 	uint16_t wChannels;
422 	uint32_t dwSamplesPerSec;
423 	uint32_t dwAvgBytesPerSec;
424 	uint16_t wBlockAlign;
425 	uint16_t wBitsPerSample;  /* Only for PCM */
426 };
427 
428 struct wave_header
429 {
430 	struct riff_struct   riff;
431 	struct chunk_struct  format;
432 	struct common_struct common;
433 	struct chunk_struct  data;
434 };
435 
436 // Simple WAV IO
437 int AVI_read_wave_header( int fd, struct wave_header * wave );
438 int AVI_write_wave_header( int fd, const struct wave_header * wave );
439 size_t AVI_read_wave_pcm_data( int fd, void * buffer, size_t buflen );
440 size_t AVI_write_wave_pcm_data( int fd, const void * buffer, size_t buflen );
441 
442 
443 struct AVIStreamHeader {
444   long  fccType;
445   long  fccHandler;
446   long  dwFlags;
447   long  dwPriority;
448   long  dwInitialFrames;
449   long  dwScale;
450   long  dwRate;
451   long  dwStart;
452   long  dwLength;
453   long  dwSuggestedBufferSize;
454   long  dwQuality;
455   long  dwSampleSize;
456 };
457 
458 #endif
459