Coverage Report

Created: 2026-12-01 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gpac/src/media_tools/avilib.c
Line
Count
Source
1
/*
2
 *  avilib.c
3
 *
4
 *  Copyright (C) Thomas ostreich - June 2001
5
 *  multiple audio track support Copyright (C) 2002 Thomas ostreich
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 Lesser 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 Lesser General Public License for more details.
21
 *
22
 *  You should have received a copy of the GNU Lesser General Public
23
 *  License aint with this library; 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 <gpac/setup.h>
29
30
#ifndef GPAC_DISABLE_AVILIB
31
32
#if defined(__GNUC__) && __GNUC__ >= 11
33
#pragma GCC diagnostic ignored "-Wstringop-overflow"
34
#pragma GCC diagnostic ignored "-Warray-bounds"
35
#endif
36
37
#include <gpac/internal/avilib.h>
38
39
40
#define INFO_LIST
41
42
// add a new riff chunk after XX MB
43
#define NEW_RIFF_THRES (1900*1024*1024)
44
45
// Maximum number of indices per stream
46
0
#define NR_IXNN_CHUNKS 96
47
48
49
#define DEBUG_ODML
50
#undef DEBUG_ODML
51
52
/* The following variable indicates the kind of error */
53
54
int AVI_errno = 0;
55
56
0
#define MAX_INFO_STRLEN 64
57
static char id_str[MAX_INFO_STRLEN];
58
59
0
#define FRAME_RATE_SCALE 1000000
60
61
/*******************************************************************
62
 *                                                                 *
63
 *    Utilities for writing an AVI File                            *
64
 *                                                                 *
65
 *******************************************************************/
66
67
static u32 avi_read(FILE *fd, char *buf, u32 len)
68
0
{
69
0
  u32 r = 0;
70
71
0
  while (r < len) {
72
0
    s32 n = (s32) gf_fread(buf + r, len - r, fd);
73
0
    if (n == 0) break;
74
0
    if (n < 0) return r;
75
0
    r += n;
76
0
  }
77
78
0
  return r;
79
0
}
80
81
static u32 avi_write (FILE *fd, char *buf, u32 len)
82
0
{
83
0
  u32 r = 0;
84
85
0
  while (r < len) {
86
0
    s32 n = (u32) gf_fwrite (buf + r, len - r, fd);
87
0
    if (n < 0)
88
0
      return n;
89
90
0
    r += n;
91
0
  }
92
0
  return r;
93
0
}
94
95
/* HEADERBYTES: The number of bytes to reserve for the header */
96
97
0
#define HEADERBYTES 2048
98
99
/* AVI_MAX_LEN: The maximum length of an AVI file, we stay a bit below
100
    the 2GB limit (Remember: 2*10^9 is smaller than 2 GB) */
101
102
0
#define AVI_MAX_LEN (UINT_MAX-(1<<20)*16-HEADERBYTES)
103
104
0
#define PAD_EVEN(x) ( ((x)+1) & ~1 )
105
106
107
/* Copy n into dst as a 4 or 2 byte, little endian number.
108
   Should also work on big endian machines */
109
110
static void long2str(unsigned char *dst, s32 n)
111
0
{
112
0
  dst[0] = (n    )&0xff;
113
0
  dst[1] = (n>> 8)&0xff;
114
0
  dst[2] = (n>>16)&0xff;
115
0
  dst[3] = (n>>24)&0xff;
116
0
}
117
118
#ifdef WORDS_BIGENDIAN
119
static void short2str(unsigned char *dst, s32 n)
120
{
121
  dst[0] = (n    )&0xff;
122
  dst[1] = (n>> 8)&0xff;
123
}
124
#endif
125
126
/* Convert a string of 4 or 2 bytes to a number,
127
   also working on big endian machines */
128
129
static u64 str2ullong(unsigned char *str)
130
0
{
131
0
  u64 r = ((u32)str[0] | ((u32)str[1]<<8) | ((u32)str[2]<<16) | ((u32)str[3]<<24));
132
0
  u64 s = ((u32)str[4] | ((u32)str[5]<<8) | ((u32)str[6]<<16) | ((u32)str[7]<<24));
133
0
#ifdef __GNUC__
134
0
  return ((s<<32)&0xffffffff00000000ULL)|(r&0xffffffff);
135
#else
136
  return ((s<<32)&0xffffffff00000000)|(r&0xffffffff);
137
#endif
138
0
}
139
140
static u32 str2ulong(unsigned char *str)
141
0
{
142
0
  return ( (u32)str[0] | ((u32)str[1]<<8) | ((u32)str[2]<<16) | ((u32)str[3]<<24) );
143
0
}
144
static u32 str2ushort(unsigned char *str)
145
0
{
146
0
  return ( (u32)str[0] | ((u32)str[1]<<8) );
147
0
}
148
149
// bit 31 denotes a keyframe
150
static u32 str2ulong_len (unsigned char *str)
151
0
{
152
0
  return str2ulong(str) & 0x7fffffff;
153
0
}
154
155
156
// if bit 31 is 0, its a keyframe
157
static u32 str2ulong_key (unsigned char *str)
158
0
{
159
0
  u32 c = str2ulong(str);
160
0
  c &= 0x80000000;
161
0
  if (c == 0) return 0x10;
162
0
  else return 0;
163
0
}
164
165
/* Calculate audio sample size from number of bits and number of channels.
166
   This may have to be adjusted for eg. 12 bits and stereo */
167
168
static int avi_sampsize(avi_t *AVI, int j)
169
0
{
170
0
  int s;
171
0
  s = ((AVI->track[j].a_bits+7)/8)*AVI->track[j].a_chans;
172
  //   if(s==0) s=1; /* avoid possible zero divisions */
173
0
  if(s<4) s=4; /* avoid possible zero divisions */
174
0
  return s;
175
0
}
176
177
/* Add a chunk (=tag and data) to the AVI file,
178
   returns -1 on write error, 0 on success */
179
180
static int avi_add_chunk(avi_t *AVI, unsigned char *tag, unsigned char *data, u32 length)
181
0
{
182
0
  unsigned char c[8];
183
0
  char p=0;
184
185
  /* Copy tag and length int c, so that we need only 1 write system call
186
     for these two values */
187
188
0
  memcpy(c,tag,4);
189
0
  long2str(c+4,length);
190
191
  /* Output tag, length and data, restore previous position
192
     if the write fails */
193
194
0
  if( avi_write(AVI->fdes,(char *)c,8) != 8 ||
195
0
          avi_write(AVI->fdes,(char *)data,length) != length ||
196
0
          avi_write(AVI->fdes,&p,length&1) != (length&1)) // if len is uneven, write a pad byte
197
0
  {
198
0
    gf_fseek(AVI->fdes,AVI->pos,SEEK_SET);
199
0
    AVI_errno = AVI_ERR_WRITE;
200
0
    return -1;
201
0
  }
202
203
  /* Update file position */
204
205
0
  AVI->pos += 8 + PAD_EVEN(length);
206
207
  //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] pos=%lu %s\n", AVI->pos, tag));
208
209
0
  return 0;
210
0
}
211
212
0
#define OUTD(n) long2str((unsigned char*) (ix00+bl),(s32)n); bl+=4
213
0
#define OUTW(n) ix00[bl] = (n)&0xff; ix00[bl+1] = (n>>8)&0xff; bl+=2
214
0
#define OUTC(n) ix00[bl] = (n)&0xff; bl+=1
215
0
#define OUTS(s) memcpy(ix00+bl,s,4); bl+=4
216
217
// this does the physical writeout of the ix## structure
218
static int avi_ixnn_entry(avi_t *AVI, avistdindex_chunk *ch, avisuperindex_entry *en)
219
0
{
220
0
  int bl;
221
0
  u32 k;
222
0
  unsigned int max = ch->nEntriesInUse * sizeof (u32) * ch->wLongsPerEntry + 24; // header
223
0
  char *ix00 = (char *)gf_malloc (max);
224
0
  char dfcc[5];
225
0
  memcpy (dfcc, ch->fcc, 4);
226
0
  dfcc[4] = 0;
227
228
0
  bl = 0;
229
230
0
  if (en) {
231
0
    en->qwOffset = AVI->pos;
232
0
    en->dwSize = max;
233
    //en->dwDuration = ch->nEntriesInUse -1; // NUMBER OF stream ticks == frames for video/samples for audio
234
0
  }
235
236
#ifdef DEBUG_ODML
237
  //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] ODML Write %s: Entries %ld size %d \n", dfcc, ch->nEntriesInUse, max));
238
#endif
239
240
  //OUTS(ch->fcc);
241
  //OUTD(max);
242
0
  OUTW(ch->wLongsPerEntry);
243
0
  OUTC(ch->bIndexSubType);
244
0
  OUTC(ch->bIndexType);
245
0
  OUTD(ch->nEntriesInUse);
246
0
  OUTS(ch->dwChunkId);
247
0
  OUTD(ch->qwBaseOffset&0xffffffff);
248
0
  OUTD((ch->qwBaseOffset>>32)&0xffffffff);
249
0
  OUTD(ch->dwReserved3);
250
251
0
  for (k = 0; k < ch->nEntriesInUse; k++) {
252
0
    OUTD(ch->aIndex[k].dwOffset);
253
0
    OUTD(ch->aIndex[k].dwSize);
254
255
0
  }
256
0
  avi_add_chunk (AVI, (unsigned char*)ch->fcc, (unsigned char*)ix00, max);
257
258
0
  gf_free(ix00);
259
260
0
  return 0;
261
0
}
262
#undef OUTS
263
#undef OUTW
264
#undef OUTD
265
#undef OUTC
266
267
// inits a super index structure including its enclosed stdindex
268
static int avi_init_super_index(avi_t *AVI, unsigned char *idxtag, avisuperindex_chunk **si)
269
0
{
270
0
  int k;
271
272
0
  avisuperindex_chunk *sil = NULL;
273
274
0
  if ((sil = (avisuperindex_chunk *) gf_malloc (sizeof (avisuperindex_chunk))) == NULL) {
275
0
    AVI_errno = AVI_ERR_NO_MEM;
276
0
    return -1;
277
0
  }
278
0
  memcpy (sil->fcc, "indx", 4);
279
0
  sil->dwSize = 0; // size of this chunk
280
0
  sil->wLongsPerEntry = 4;
281
0
  sil->bIndexSubType = 0;
282
0
  sil->bIndexType = AVI_INDEX_OF_INDEXES;
283
0
  sil->nEntriesInUse = 0; // none are in use
284
0
  memcpy (sil->dwChunkId, idxtag, 4);
285
0
  memset (sil->dwReserved, 0, sizeof (sil->dwReserved));
286
287
  // NR_IXNN_CHUNKS == allow 32 indices which means 32 GB files -- arbitrary
288
0
  sil->aIndex = (avisuperindex_entry *) gf_malloc (sil->wLongsPerEntry * NR_IXNN_CHUNKS * sizeof (void*));
289
0
  if (!sil->aIndex) {
290
0
    AVI_errno = AVI_ERR_NO_MEM;
291
0
    return -1;
292
0
  }
293
0
  memset (sil->aIndex, 0, sil->wLongsPerEntry * NR_IXNN_CHUNKS * sizeof (u32));
294
295
0
  sil->stdindex = (avistdindex_chunk **)gf_malloc (NR_IXNN_CHUNKS * sizeof (avistdindex_chunk *));
296
0
  if (!sil->stdindex) {
297
0
    AVI_errno = AVI_ERR_NO_MEM;
298
0
    return -1;
299
0
  }
300
0
  for (k = 0; k < NR_IXNN_CHUNKS; k++) {
301
0
    sil->stdindex[k] = (avistdindex_chunk *) gf_malloc (sizeof (avistdindex_chunk));
302
    // gets rewritten later
303
0
    sil->stdindex[k]->qwBaseOffset = (u64)k * AVI->new_riff_threshold;
304
0
    sil->stdindex[k]->aIndex = NULL;
305
0
  }
306
307
0
  *si = sil;
308
309
0
  return 0;
310
0
}
311
312
// fills an alloc'ed stdindex structure and mallocs some entries for the actual chunks
313
static int avi_add_std_index(avi_t *AVI, unsigned char *idxtag, unsigned char *strtag,
314
                             avistdindex_chunk *stdil)
315
0
{
316
317
0
  memcpy (stdil->fcc, idxtag, 4);
318
0
  stdil->dwSize = 4096;
319
0
  stdil->wLongsPerEntry = 2; //sizeof(avistdindex_entry)/sizeof(u32);
320
0
  stdil->bIndexSubType = 0;
321
0
  stdil->bIndexType = AVI_INDEX_OF_CHUNKS;
322
0
  stdil->nEntriesInUse = 0;
323
324
  // cp 00db ChunkId
325
0
  memcpy(stdil->dwChunkId, strtag, 4);
326
327
  //stdil->qwBaseOffset = AVI->video_superindex->aIndex[ cur_std_idx ]->qwOffset;
328
329
0
  stdil->aIndex = (avistdindex_entry *)gf_malloc(stdil->dwSize * sizeof (u32) * stdil->wLongsPerEntry);
330
331
0
  if (!stdil->aIndex) {
332
0
    AVI_errno = AVI_ERR_NO_MEM;
333
0
    return -1;
334
0
  }
335
336
337
0
  return 0;
338
0
}
339
340
static int avi_add_odml_index_entry_core(avi_t *AVI, int flags, u64 pos, unsigned int len, avistdindex_chunk *si)
341
0
{
342
0
  u32 cur_chunk_idx;
343
  // put new chunk into index
344
0
  si->nEntriesInUse++;
345
0
  cur_chunk_idx = si->nEntriesInUse-1;
346
347
  // need to fetch more memory
348
0
  if (cur_chunk_idx >= si->dwSize) {
349
0
    si->dwSize += 4096;
350
0
    si->aIndex = (avistdindex_entry *)gf_realloc ( si->aIndex, si->dwSize * sizeof (u32) * si->wLongsPerEntry);
351
0
  }
352
353
0
  if(len>AVI->max_len) AVI->max_len=len;
354
355
  // if bit 31 is set, it is NOT a keyframe
356
0
  if (flags != 0x10) {
357
0
    len |= 0x80000000;
358
0
  }
359
360
0
  si->aIndex [ cur_chunk_idx ].dwSize = len;
361
0
  si->aIndex [ cur_chunk_idx ].dwOffset = (u32) (pos - si->qwBaseOffset + 8);
362
363
  //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] ODML: POS: 0x%lX\n", si->aIndex [ cur_chunk_idx ].dwOffset));
364
365
0
  return 0;
366
0
}
367
368
static int avi_add_odml_index_entry(avi_t *AVI, unsigned char *tag, int flags, u64 pos, unsigned int len)
369
0
{
370
0
  char fcc[5];
371
372
0
  int audio = (strchr ((char*)tag, 'w')?1:0);
373
0
  int video = !audio;
374
375
0
  unsigned int cur_std_idx;
376
0
  u32 audtr;
377
0
  s64 towrite = 0;
378
379
0
  if (video) {
380
381
0
    if (!AVI->video_superindex) {
382
0
      if (avi_init_super_index(AVI, (unsigned char *)"ix00", &AVI->video_superindex) < 0) return -1;
383
0
      AVI->video_superindex->nEntriesInUse++;
384
0
      cur_std_idx = AVI->video_superindex->nEntriesInUse-1;
385
386
0
      if (avi_add_std_index (AVI, (unsigned char *)"ix00", (unsigned char *)"00db", AVI->video_superindex->stdindex[ cur_std_idx ]) < 0)
387
0
        return -1;
388
0
    } // init
389
390
0
  } // video
391
392
0
  if (audio) {
393
394
0
    fcc[0] = 'i';
395
0
    fcc[1] = 'x';
396
0
    fcc[2] = tag[0];
397
0
    fcc[3] = tag[1];
398
0
    fcc[4] = '\0';
399
0
    if (!AVI->track[AVI->aptr].audio_superindex) {
400
401
#ifdef DEBUG_ODML
402
      GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] ODML: fcc = %s\n", fcc));
403
#endif
404
0
      if (avi_init_super_index(AVI, (unsigned char *)fcc, &AVI->track[AVI->aptr].audio_superindex) < 0) return -1;
405
406
407
0
      AVI->track[AVI->aptr].audio_superindex->nEntriesInUse++;
408
409
0
      sprintf(fcc, "ix%02d", AVI->aptr+1);
410
0
      if (avi_add_std_index (AVI, (unsigned char *)fcc, tag, AVI->track[AVI->aptr].audio_superindex->stdindex[
411
0
                                 AVI->track[AVI->aptr].audio_superindex->nEntriesInUse - 1 ]) < 0
412
0
         ) return -1;
413
0
    } // init
414
415
0
  }
416
417
0
  towrite = 0;
418
0
  if (AVI->video_superindex) {
419
420
0
    cur_std_idx = AVI->video_superindex->nEntriesInUse-1;
421
0
    towrite += AVI->video_superindex->stdindex[cur_std_idx]->nEntriesInUse*8
422
0
               + 4+4+2+1+1+4+4+8+4;
423
0
    if (cur_std_idx == 0) {
424
0
      towrite += AVI->n_idx*16 + 8;
425
0
      towrite += HEADERBYTES;
426
0
    }
427
0
  }
428
429
0
  for (audtr=0; audtr<AVI->anum; audtr++) {
430
0
    if (AVI->track[audtr].audio_superindex) {
431
0
      cur_std_idx = AVI->track[audtr].audio_superindex->nEntriesInUse-1;
432
0
      towrite += AVI->track[audtr].audio_superindex->stdindex[cur_std_idx]->nEntriesInUse*8
433
0
                 + 4+4+2+1+1+4+4+8+4;
434
0
    }
435
0
  }
436
0
  towrite += len + (len&1) + 8;
437
438
  //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] ODML: towrite = 0x%llX = %"LLD"\n", towrite, towrite));
439
440
0
  if (AVI->video_superindex &&
441
0
          (s64)(AVI->pos+towrite) > (s64)((s64) AVI->new_riff_threshold*AVI->video_superindex->nEntriesInUse)) {
442
443
0
    GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] Adding a new RIFF chunk: %d\n", AVI->video_superindex->nEntriesInUse));
444
445
    // rotate ALL indices
446
0
    AVI->video_superindex->nEntriesInUse++;
447
0
    cur_std_idx = AVI->video_superindex->nEntriesInUse-1;
448
449
0
    if (AVI->video_superindex->nEntriesInUse > NR_IXNN_CHUNKS) {
450
0
      GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] Internal error in avilib - redefine NR_IXNN_CHUNKS\n"));
451
0
      GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] cur_std_idx=%d NR_IXNN_CHUNKS=%d"
452
0
                                              "POS=%"LLD" towrite=%"LLD"\n",
453
0
                                              cur_std_idx,NR_IXNN_CHUNKS, AVI->pos, towrite));
454
0
      return -1;
455
0
    }
456
457
0
    if (avi_add_std_index (AVI, (unsigned char *)"ix00", (unsigned char *)"00db", AVI->video_superindex->stdindex[ cur_std_idx ]) < 0)
458
0
      return -1;
459
460
0
    for (audtr = 0; audtr < AVI->anum; audtr++) {
461
0
      char aud[5];
462
0
      if (!AVI->track[audtr].audio_superindex) {
463
        // not initialized -> no index
464
0
        continue;
465
0
      }
466
0
      AVI->track[audtr].audio_superindex->nEntriesInUse++;
467
468
0
      sprintf(fcc, "ix%02d", audtr+1);
469
0
      sprintf(aud, "0%01dwb", audtr+1);
470
0
      if (avi_add_std_index (AVI, (unsigned char *)fcc, (unsigned char *)aud, AVI->track[audtr].audio_superindex->stdindex[
471
0
                                 AVI->track[audtr].audio_superindex->nEntriesInUse - 1 ]) < 0
472
0
         ) return -1;
473
0
    }
474
475
    // write the new riff;
476
0
    if (cur_std_idx > 0) {
477
478
      // dump the _previous_ == already finished index
479
0
      avi_ixnn_entry (AVI, AVI->video_superindex->stdindex[cur_std_idx - 1],
480
0
                      &AVI->video_superindex->aIndex[cur_std_idx - 1]);
481
0
      AVI->video_superindex->aIndex[cur_std_idx - 1].dwDuration =
482
0
          AVI->video_superindex->stdindex[cur_std_idx - 1]->nEntriesInUse - 1;
483
484
0
      for (audtr = 0; audtr < AVI->anum; audtr++) {
485
486
0
        if (!AVI->track[audtr].audio_superindex) {
487
          // not initialized -> no index
488
0
          continue;
489
0
        }
490
0
        avi_ixnn_entry (AVI, AVI->track[audtr].audio_superindex->stdindex[cur_std_idx - 1],
491
0
                        &AVI->track[audtr].audio_superindex->aIndex[cur_std_idx - 1]);
492
493
0
        AVI->track[audtr].audio_superindex->aIndex[cur_std_idx - 1].dwDuration =
494
0
            AVI->track[audtr].audio_superindex->stdindex[cur_std_idx - 1]->nEntriesInUse - 1;
495
0
        if (AVI->track[audtr].a_fmt == 0x1) {
496
0
          AVI->track[audtr].audio_superindex->aIndex[cur_std_idx - 1].dwDuration *=
497
0
              AVI->track[audtr].a_bits*AVI->track[audtr].a_rate*AVI->track[audtr].a_chans/800;
498
0
        }
499
0
      }
500
501
      // XXX: dump idx1 structure
502
0
      if (cur_std_idx == 1) {
503
0
        avi_add_chunk(AVI, (unsigned char *)"idx1", (unsigned char *)AVI->idx, AVI->n_idx*16);
504
        // qwBaseOffset will contain the start of the second riff chunk
505
0
      }
506
      // Fix the Offsets later at closing time
507
0
      avi_add_chunk(AVI, (unsigned char *)"RIFF", (unsigned char *)"AVIXLIST\0\0\0\0movi", 16);
508
509
0
      AVI->video_superindex->stdindex[ cur_std_idx ]->qwBaseOffset = AVI->pos -16 -8;
510
#ifdef DEBUG_ODML
511
      GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] ODML: RIFF No.%02d at Offset 0x%llX\n", cur_std_idx, AVI->pos -16 -8));
512
#endif
513
514
0
      for (audtr = 0; audtr < AVI->anum; audtr++) {
515
0
        if (AVI->track[audtr].audio_superindex)
516
0
          AVI->track[audtr].audio_superindex->stdindex[ cur_std_idx ]->qwBaseOffset =
517
0
              AVI->pos -16 -8;
518
519
0
      }
520
521
      // now we can be sure
522
0
      AVI->is_opendml++;
523
0
    }
524
525
0
  }
526
527
528
0
  if (video) {
529
0
    avi_add_odml_index_entry_core(AVI, flags, AVI->pos, len,
530
0
                                  AVI->video_superindex->stdindex[ AVI->video_superindex->nEntriesInUse-1 ]);
531
532
0
    AVI->total_frames++;
533
0
  } // video
534
535
0
  if (audio) {
536
0
    avi_add_odml_index_entry_core(AVI, flags, AVI->pos, len,
537
0
                                  AVI->track[AVI->aptr].audio_superindex->stdindex[
538
0
                                      AVI->track[AVI->aptr].audio_superindex->nEntriesInUse-1 ]);
539
0
  }
540
541
542
0
  return 0;
543
0
}
544
545
// #undef NR_IXNN_CHUNKS
546
547
static int avi_add_index_entry(avi_t *AVI, unsigned char *tag, int flags, u64 pos, u64 len)
548
0
{
549
0
  if(AVI->n_idx>=AVI->max_idx) {
550
0
    void *ptr = gf_realloc((void *)AVI->idx,(AVI->max_idx+4096)*16);
551
552
0
    if(ptr == 0) {
553
0
      AVI_errno = AVI_ERR_NO_MEM;
554
0
      return -1;
555
0
    }
556
0
    AVI->max_idx += 4096;
557
0
    AVI->idx = (unsigned char((*)[16]) ) ptr;
558
0
  }
559
560
  /* Add index entry */
561
562
  //   GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] INDEX %s %ld %lu %lu\n", tag, flags, pos, len));
563
564
0
  memcpy(AVI->idx[AVI->n_idx],tag,4);
565
0
  long2str(AVI->idx[AVI->n_idx]+ 4,flags);
566
0
  long2str(AVI->idx[AVI->n_idx]+ 8, (s32) pos);
567
0
  long2str(AVI->idx[AVI->n_idx]+12, (s32) len);
568
569
  /* Update counter */
570
571
0
  AVI->n_idx++;
572
573
0
  if(len>AVI->max_len) AVI->max_len=(u32) len;
574
575
0
  return 0;
576
0
}
577
578
#if 0
579
/* Returns 1 if more audio is in that video junk */
580
int AVI_can_read_audio(avi_t *AVI)
581
{
582
  if(AVI->mode==AVI_MODE_WRITE) {
583
    return -1;
584
  }
585
  if(!AVI->video_index)         {
586
    return -1;
587
  }
588
  if(!AVI->track[AVI->aptr].audio_index)         {
589
    return -1;
590
  }
591
592
  // is it -1? the last ones got left out --tibit
593
  //if (AVI->track[AVI->aptr].audio_posc>=AVI->track[AVI->aptr].audio_chunks-1) {
594
  if (AVI->track[AVI->aptr].audio_posc>=AVI->track[AVI->aptr].audio_chunks) {
595
    return 0;
596
  }
597
598
  if (AVI->video_pos >= AVI->video_frames) return 1;
599
600
  if (AVI->track[AVI->aptr].audio_index[AVI->track[AVI->aptr].audio_posc].pos < AVI->video_index[AVI->video_pos].pos) return 1;
601
  else return 0;
602
}
603
#endif
604
605
/*
606
   AVI_open_output_file: Open an AVI File and write a bunch
607
                         of zero bytes as space for the header.
608
609
   returns a pointer to avi_t on success, a zero pointer on error
610
*/
611
612
GF_EXPORT
613
avi_t* AVI_open_output_file(char * filename, u64 opendml_threshold)
614
0
{
615
0
  avi_t *AVI;
616
0
  int i;
617
618
0
  unsigned char AVI_header[HEADERBYTES];
619
620
  /* Allocate the avi_t struct and zero it */
621
622
0
  AVI = (avi_t *) gf_malloc(sizeof(avi_t));
623
0
  if(AVI==0)
624
0
  {
625
0
    AVI_errno = AVI_ERR_NO_MEM;
626
0
    return 0;
627
0
  }
628
0
  memset((void *)AVI,0,sizeof(avi_t));
629
630
0
  AVI->fdes = gf_fopen(filename, "w+b");
631
0
  if (!AVI->fdes )
632
0
  {
633
0
    AVI_errno = AVI_ERR_OPEN;
634
0
    gf_free(AVI);
635
0
    return 0;
636
0
  }
637
638
  /* Write out HEADERBYTES bytes, the header will go here
639
     when we are finished with writing */
640
641
0
  for (i=0; i<HEADERBYTES; i++) AVI_header[i] = 0;
642
0
  i = avi_write(AVI->fdes,(char *)AVI_header,HEADERBYTES);
643
0
  if (i != HEADERBYTES)
644
0
  {
645
0
    gf_fclose(AVI->fdes);
646
0
    AVI_errno = AVI_ERR_WRITE;
647
0
    gf_free(AVI);
648
0
    return 0;
649
0
  }
650
651
0
  AVI->pos  = HEADERBYTES;
652
0
  AVI->mode = AVI_MODE_WRITE; /* open for writing */
653
0
  if (opendml_threshold)
654
0
    AVI->new_riff_threshold = opendml_threshold;
655
0
  else
656
0
    AVI->new_riff_threshold = (1900*1024*1024);
657
658
  //init
659
0
  AVI->anum = 0;
660
0
  AVI->aptr = 0;
661
662
0
  return AVI;
663
0
}
664
665
GF_EXPORT
666
void AVI_set_video(avi_t *AVI, int width, int height, double fps, char *compressor)
667
0
{
668
  /* may only be called if file is open for writing */
669
670
0
  if(AVI->mode==AVI_MODE_READ) return;
671
672
0
  AVI->width  = width;
673
0
  AVI->height = height;
674
0
  AVI->fps    = fps;
675
676
0
  if(strncmp(compressor, "RGB", 3)==0) {
677
0
    memset(AVI->compressor, 0, 4);
678
0
  } else {
679
0
    memcpy(AVI->compressor,compressor,4);
680
0
  }
681
682
0
  AVI->compressor[4] = 0;
683
684
0
  avi_update_header(AVI);
685
0
}
686
687
GF_EXPORT
688
void AVI_set_audio(avi_t *AVI, int channels, int rate, int bits, int format, int mp3rate)
689
0
{
690
  /* may only be called if file is open for writing */
691
692
0
  if(AVI->mode==AVI_MODE_READ) return;
693
694
  //inc audio tracks
695
0
  AVI->aptr=AVI->anum;
696
0
  ++AVI->anum;
697
698
0
  if(AVI->anum > AVI_MAX_TRACKS) {
699
0
    GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] error - only %d audio tracks supported\n", AVI_MAX_TRACKS));
700
0
    exit(1);
701
0
  }
702
703
0
  AVI->track[AVI->aptr].a_chans = channels;
704
0
  AVI->track[AVI->aptr].a_rate  = rate;
705
0
  AVI->track[AVI->aptr].a_bits  = bits;
706
0
  AVI->track[AVI->aptr].a_fmt   = format;
707
0
  AVI->track[AVI->aptr].mp3rate = mp3rate;
708
709
0
  avi_update_header(AVI);
710
0
}
711
712
#define OUT4CC(s) \
713
0
   if(nhb<=HEADERBYTES-4) memcpy(AVI_header+nhb,s,4); \
714
0
   nhb += 4
715
716
#define OUTLONG(n) \
717
0
   if(nhb<=HEADERBYTES-4) long2str(AVI_header+nhb, (s32)(n)); \
718
0
   nhb += 4
719
720
#define OUTSHRT(n) \
721
0
   if(nhb<=HEADERBYTES-2) { \
722
0
      AVI_header[nhb  ] = (u8) ((n   )&0xff); \
723
0
      AVI_header[nhb+1] = (u8) ((n>>8)&0xff); \
724
0
   } \
725
0
   nhb += 2
726
727
#define OUTCHR(n) \
728
0
   if(nhb<=HEADERBYTES-1) { \
729
0
      AVI_header[nhb  ] = (n   )&0xff; \
730
0
   } \
731
0
   nhb += 1
732
733
#define OUTMEM(d, s) \
734
0
   { \
735
0
     u32 s_ = (u32) (s); \
736
0
     if(nhb + s_ <= HEADERBYTES) \
737
0
        memcpy(AVI_header+nhb, (d), s_); \
738
0
     nhb += s_; \
739
0
   }
740
741
742
//ThOe write preliminary AVI file header: 0 frames, max vid/aud size
743
int avi_update_header(avi_t *AVI)
744
0
{
745
0
  int njunk, ms_per_frame, frate, flag;
746
0
  int movi_len, hdrl_start, strl_start;
747
0
  u32 j;
748
0
  unsigned char AVI_header[HEADERBYTES];
749
0
  u32 nhb;
750
0
  unsigned int xd_size, xd_size_align2;
751
752
  //assume max size
753
0
  movi_len = AVI_MAX_LEN - HEADERBYTES + 4;
754
755
  //assume index will be written
756
//  int hasIndex=1;
757
758
0
  if(AVI->fps < 0.001) {
759
0
    frate=0;
760
0
    ms_per_frame=0;
761
0
  } else {
762
0
    frate = (int) (FRAME_RATE_SCALE*AVI->fps + 0.5);
763
0
    ms_per_frame=(int) (1000000/AVI->fps + 0.5);
764
0
  }
765
766
  /* Prepare the file header */
767
768
0
  nhb = 0;
769
770
  /* The RIFF header */
771
772
0
  OUT4CC ("RIFF");
773
0
  OUTLONG(movi_len);    // assume max size
774
0
  OUT4CC ("AVI ");
775
776
  /* Start the header list */
777
778
0
  OUT4CC ("LIST");
779
0
  OUTLONG(0);        /* Length of list in bytes, don't know yet */
780
0
  hdrl_start = nhb;  /* Store start position */
781
0
  OUT4CC ("hdrl");
782
783
  /* The main AVI header */
784
785
  /* The Flags in AVI File header */
786
787
0
#define AVIF_HASINDEX           0x00000010      /* Index at end of file */
788
0
#define AVIF_MUSTUSEINDEX       0x00000020
789
0
#define AVIF_ISINTERLEAVED      0x00000100
790
0
#define AVIF_TRUSTCKTYPE        0x00000800      /* Use CKType to find key frames */
791
0
#define AVIF_WASCAPTUREFILE     0x00010000
792
0
#define AVIF_COPYRIGHTED        0x00020000
793
794
0
  OUT4CC ("avih");
795
0
  OUTLONG(56);                 /* # of bytes to follow */
796
0
  OUTLONG(ms_per_frame);       /* Microseconds per frame */
797
  //ThOe ->0
798
  //   OUTLONG(10000000);           /* MaxBytesPerSec, I hope this will never be used */
799
0
  OUTLONG(0);
800
0
  OUTLONG(0);                  /* PaddingGranularity (whatever that might be) */
801
  /* Other sources call it 'reserved' */
802
0
  flag = AVIF_ISINTERLEAVED;
803
  //if (hasIndex)
804
0
    flag |= AVIF_HASINDEX;
805
0
  if (/*hasIndex && */AVI->must_use_index)
806
0
    flag |= AVIF_MUSTUSEINDEX;
807
0
  OUTLONG(flag);               /* Flags */
808
0
  OUTLONG(0);                  // no frames yet
809
0
  OUTLONG(0);                  /* InitialFrames */
810
811
0
  OUTLONG(AVI->anum+1);
812
813
0
  OUTLONG(0);                  /* SuggestedBufferSize */
814
0
  OUTLONG(AVI->width);         /* Width */
815
0
  OUTLONG(AVI->height);        /* Height */
816
  /* MS calls the following 'reserved': */
817
0
  OUTLONG(0);                  /* TimeScale:  Unit used to measure time */
818
0
  OUTLONG(0);                  /* DataRate:   Data rate of playback     */
819
0
  OUTLONG(0);                  /* StartTime:  Starting time of AVI data */
820
0
  OUTLONG(0);                  /* DataLength: Size of AVI data chunk    */
821
822
823
  /* Start the video stream list ---------------------------------- */
824
825
0
  OUT4CC ("LIST");
826
0
  OUTLONG(0);        /* Length of list in bytes, don't know yet */
827
0
  strl_start = nhb;  /* Store start position */
828
0
  OUT4CC ("strl");
829
830
  /* The video stream header */
831
832
0
  OUT4CC ("strh");
833
0
  OUTLONG(56);                 /* # of bytes to follow */
834
0
  OUT4CC ("vids");             /* Type */
835
0
  OUT4CC (AVI->compressor);    /* Handler */
836
0
  OUTLONG(0);                  /* Flags */
837
0
  OUTLONG(0);                  /* Reserved, MS says: wPriority, wLanguage */
838
0
  OUTLONG(0);                  /* InitialFrames */
839
0
  OUTLONG(FRAME_RATE_SCALE);              /* Scale */
840
0
  OUTLONG(frate);              /* Rate: Rate/Scale == samples/second */
841
0
  OUTLONG(0);                  /* Start */
842
0
  OUTLONG(0);                  // no frames yet
843
0
  OUTLONG(0);                  /* SuggestedBufferSize */
844
0
  OUTLONG(-1);                 /* Quality */
845
0
  OUTLONG(0);                  /* SampleSize */
846
0
  OUTLONG(0);                  /* Frame */
847
0
  OUTLONG(0);                  /* Frame */
848
  //   OUTLONG(0);                  /* Frame */
849
  //OUTLONG(0);                  /* Frame */
850
851
  /* The video stream format */
852
853
0
  xd_size        = AVI->extradata_size;
854
0
  xd_size_align2 = (AVI->extradata_size+1) & ~1;
855
856
0
  OUT4CC ("strf");
857
0
  OUTLONG(40 + xd_size_align2);/* # of bytes to follow */
858
0
  OUTLONG(40 + xd_size); /* Size */
859
0
  OUTLONG(AVI->width);         /* Width */
860
0
  OUTLONG(AVI->height);        /* Height */
861
0
  OUTSHRT(1);
862
0
  OUTSHRT(24);     /* Planes, Count */
863
0
  OUT4CC (AVI->compressor);    /* Compression */
864
  // ThOe (*3)
865
0
  OUTLONG(AVI->width*AVI->height*3);  /* SizeImage (in bytes?) */
866
0
  OUTLONG(0);                  /* XPelsPerMeter */
867
0
  OUTLONG(0);                  /* YPelsPerMeter */
868
0
  OUTLONG(0);                  /* ClrUsed: Number of colors used */
869
0
  OUTLONG(0);                  /* ClrImportant: Number of colors important */
870
871
  // write extradata
872
0
  if (xd_size > 0 && AVI->extradata) {
873
0
    OUTMEM(AVI->extradata, xd_size);
874
0
    if (xd_size != xd_size_align2) {
875
0
      OUTCHR(0);
876
0
    }
877
0
  }
878
879
  /* Finish stream list, i.e. put number of bytes in the list to proper pos */
880
881
0
  long2str(AVI_header+strl_start-4,nhb-strl_start);
882
883
884
  /* Start the audio stream list ---------------------------------- */
885
886
0
  for(j=0; j<AVI->anum; ++j) {
887
0
    int sampsize = avi_sampsize(AVI, j);
888
889
0
    OUT4CC ("LIST");
890
0
    OUTLONG(0);        /* Length of list in bytes, don't know yet */
891
0
    strl_start = nhb;  /* Store start position */
892
0
    OUT4CC ("strl");
893
894
    /* The audio stream header */
895
896
0
    OUT4CC ("strh");
897
0
    OUTLONG(56);            /* # of bytes to follow */
898
0
    OUT4CC ("auds");
899
900
    // -----------
901
    // ThOe
902
0
    OUTLONG(0);             /* Format (Optionally) */
903
    // -----------
904
905
0
    OUTLONG(0);             /* Flags */
906
0
    OUTLONG(0);             /* Reserved, MS says: wPriority, wLanguage */
907
0
    OUTLONG(0);             /* InitialFrames */
908
909
    // ThOe /4
910
0
    OUTLONG(sampsize/4);      /* Scale */
911
0
    OUTLONG(1000*AVI->track[j].mp3rate/8);
912
0
    OUTLONG(0);             /* Start */
913
0
    OUTLONG(4*AVI->track[j].audio_bytes/sampsize);   /* Length */
914
0
    OUTLONG(0);             /* SuggestedBufferSize */
915
0
    OUTLONG(-1);            /* Quality */
916
917
    // ThOe /4
918
0
    OUTLONG(sampsize/4);    /* SampleSize */
919
920
0
    OUTLONG(0);             /* Frame */
921
0
    OUTLONG(0);             /* Frame */
922
    //       OUTLONG(0);             /* Frame */
923
    //OUTLONG(0);             /* Frame */
924
925
    /* The audio stream format */
926
927
0
    OUT4CC ("strf");
928
0
    OUTLONG(16);                   /* # of bytes to follow */
929
0
    OUTSHRT(AVI->track[j].a_fmt);           /* Format */
930
0
    OUTSHRT(AVI->track[j].a_chans);         /* Number of channels */
931
0
    OUTLONG(AVI->track[j].a_rate);          /* SamplesPerSec */
932
    // ThOe
933
0
    OUTLONG(1000*AVI->track[j].mp3rate/8);
934
    //ThOe (/4)
935
936
0
    OUTSHRT(sampsize/4);           /* BlockAlign */
937
938
939
0
    OUTSHRT(AVI->track[j].a_bits);          /* BitsPerSample */
940
941
    /* Finish stream list, i.e. put number of bytes in the list to proper pos */
942
943
0
    long2str(AVI_header+strl_start-4,nhb-strl_start);
944
0
  }
945
946
  /* Finish header list */
947
948
0
  long2str(AVI_header+hdrl_start-4,nhb-hdrl_start);
949
950
951
  /* Calculate the needed amount of junk bytes, output junk */
952
953
0
  njunk = HEADERBYTES - nhb - 8 - 12;
954
955
  /* Safety first: if njunk <= 0, somebody has played with
956
     HEADERBYTES without knowing what (s)he did.
957
     This is a fatal error */
958
959
0
  if(njunk<=0)
960
0
  {
961
0
    GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] AVI_close_output_file: # of header bytes too small\n"));
962
0
    exit(1);
963
0
  }
964
965
0
  OUT4CC ("JUNK");
966
0
  OUTLONG(njunk);
967
0
  memset(AVI_header+nhb,0,njunk);
968
969
0
  nhb += njunk;
970
971
  /* Start the movi list */
972
973
0
  OUT4CC ("LIST");
974
0
  OUTLONG(movi_len); /* Length of list in bytes */
975
0
  OUT4CC ("movi");
976
977
  /* Output the header, truncate the file to the number of bytes
978
     actually written, report an error if someting goes wrong */
979
980
0
  if ( (gf_fseek(AVI->fdes, 0, SEEK_SET) ==(u64)-1) ||
981
0
          avi_write(AVI->fdes,(char *)AVI_header,HEADERBYTES)!=HEADERBYTES ||
982
0
          (gf_fseek(AVI->fdes,AVI->pos,SEEK_SET)==(u64)-1)
983
0
     ) {
984
0
    AVI_errno = AVI_ERR_CLOSE;
985
0
    return -1;
986
0
  }
987
988
0
  return 0;
989
0
}
990
991
992
//SLM
993
#ifndef S_IRUSR
994
#define S_IRWXU       00700       /* read, write, execute: owner */
995
#define S_IRUSR       00400       /* read permission: owner */
996
#define S_IWUSR       00200       /* write permission: owner */
997
#define S_IXUSR       00100       /* execute permission: owner */
998
#define S_IRWXG       00070       /* read, write, execute: group */
999
#define S_IRGRP       00040       /* read permission: group */
1000
#define S_IWGRP       00020       /* write permission: group */
1001
#define S_IXGRP       00010       /* execute permission: group */
1002
#define S_IRWXO       00007       /* read, write, execute: other */
1003
#define S_IROTH       00004       /* read permission: other */
1004
#define S_IWOTH       00002       /* write permission: other */
1005
#define S_IXOTH       00001       /* execute permission: other */
1006
#endif
1007
1008
/*
1009
  Write the header of an AVI file and close it.
1010
  returns 0 on success, -1 on write error.
1011
*/
1012
1013
static int avi_close_output_file(avi_t *AVI)
1014
0
{
1015
0
  int njunk, hasIndex, ms_per_frame, frate, idxerror, flag;
1016
0
  u64 movi_len;
1017
0
  int hdrl_start, strl_start;
1018
0
  u32 j;
1019
0
  unsigned char AVI_header[HEADERBYTES];
1020
0
  int nhb;
1021
0
  unsigned int xd_size, xd_size_align2;
1022
1023
0
#ifdef INFO_LIST
1024
0
  int info_len;
1025
0
  int id_len, real_id_len;
1026
0
  int info_start_pos;
1027
//   time_t calptr;
1028
0
#endif
1029
1030
  /* Calculate length of movi list */
1031
1032
  // dump the rest of the index
1033
0
  if (AVI->is_opendml) {
1034
0
    int cur_std_idx = AVI->video_superindex->nEntriesInUse-1;
1035
0
    u32 audtr;
1036
1037
#ifdef DEBUG_ODML
1038
    GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] ODML dump the rest indices\n"));
1039
#endif
1040
0
    avi_ixnn_entry (AVI, AVI->video_superindex->stdindex[cur_std_idx],
1041
0
                    &AVI->video_superindex->aIndex[cur_std_idx]);
1042
1043
0
    AVI->video_superindex->aIndex[cur_std_idx].dwDuration =
1044
0
        AVI->video_superindex->stdindex[cur_std_idx]->nEntriesInUse - 1;
1045
1046
0
    for (audtr = 0; audtr < AVI->anum; audtr++) {
1047
0
      if (!AVI->track[audtr].audio_superindex) {
1048
        // not initialized -> no index
1049
0
        continue;
1050
0
      }
1051
0
      avi_ixnn_entry (AVI, AVI->track[audtr].audio_superindex->stdindex[cur_std_idx],
1052
0
                      &AVI->track[audtr].audio_superindex->aIndex[cur_std_idx]);
1053
0
      AVI->track[audtr].audio_superindex->aIndex[cur_std_idx].dwDuration =
1054
0
          AVI->track[audtr].audio_superindex->stdindex[cur_std_idx]->nEntriesInUse - 1;
1055
0
      if (AVI->track[audtr].a_fmt == 0x1) {
1056
0
        AVI->track[audtr].audio_superindex->aIndex[cur_std_idx].dwDuration *=
1057
0
            AVI->track[audtr].a_bits*AVI->track[audtr].a_rate*AVI->track[audtr].a_chans/800;
1058
0
      }
1059
0
    }
1060
    // The AVI->video_superindex->nEntriesInUse contains the offset
1061
0
    AVI->video_superindex->stdindex[ cur_std_idx+1 ]->qwBaseOffset = AVI->pos;
1062
1063
    // Correct!
1064
0
    movi_len = AVI->video_superindex->stdindex[ 1 ]->qwBaseOffset - HEADERBYTES+4 - AVI->n_idx*16 - 8;
1065
0
  } else {
1066
0
    movi_len = AVI->pos - HEADERBYTES + 4;
1067
0
  }
1068
1069
1070
  /* Try to output the index entries. This may fail e.g. if no space
1071
     is left on device. We will report this as an error, but we still
1072
     try to write the header correctly (so that the file still may be
1073
     readable in the most cases */
1074
1075
0
  idxerror = 0;
1076
0
  hasIndex = 1;
1077
0
  if (!AVI->is_opendml) {
1078
    //   GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] pos=%lu, index_len=%ld             \n", AVI->pos, AVI->n_idx*16));
1079
0
    int ret = avi_add_chunk(AVI, (unsigned char *)"idx1", (unsigned char *)AVI->idx, AVI->n_idx*16);
1080
0
    hasIndex = (ret==0);
1081
    //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] pos=%lu, index_len=%d\n", AVI->pos, hasIndex));
1082
1083
0
    if(ret) {
1084
0
      idxerror = 1;
1085
0
      AVI_errno = AVI_ERR_WRITE_INDEX;
1086
0
    }
1087
0
  }
1088
1089
  /* Calculate Microseconds per frame */
1090
1091
0
  if(AVI->fps < 0.001) {
1092
0
    frate=0;
1093
0
    ms_per_frame=0;
1094
0
  } else {
1095
0
    frate = (int) (FRAME_RATE_SCALE*AVI->fps + 0.5);
1096
0
    ms_per_frame=(int) (1000000/AVI->fps + 0.5);
1097
0
  }
1098
1099
  /* Prepare the file header */
1100
1101
0
  nhb = 0;
1102
1103
  /* The RIFF header */
1104
1105
0
  OUT4CC ("RIFF");
1106
0
  if (AVI->is_opendml) {
1107
0
    OUTLONG(AVI->video_superindex->stdindex[ 1 ]->qwBaseOffset - 8);    /* # of bytes to follow */
1108
0
  } else {
1109
0
    OUTLONG(AVI->pos - 8);    /* # of bytes to follow */
1110
0
  }
1111
1112
0
  OUT4CC ("AVI ");
1113
1114
  /* Start the header list */
1115
1116
0
  OUT4CC ("LIST");
1117
0
  OUTLONG(0);        /* Length of list in bytes, don't know yet */
1118
0
  hdrl_start = nhb;  /* Store start position */
1119
0
  OUT4CC ("hdrl");
1120
1121
  /* The main AVI header */
1122
1123
  /* The Flags in AVI File header */
1124
1125
0
#define AVIF_HASINDEX           0x00000010      /* Index at end of file */
1126
0
#define AVIF_MUSTUSEINDEX       0x00000020
1127
0
#define AVIF_ISINTERLEAVED      0x00000100
1128
0
#define AVIF_TRUSTCKTYPE        0x00000800      /* Use CKType to find key frames */
1129
0
#define AVIF_WASCAPTUREFILE     0x00010000
1130
0
#define AVIF_COPYRIGHTED        0x00020000
1131
1132
0
  OUT4CC ("avih");
1133
0
  OUTLONG(56);                 /* # of bytes to follow */
1134
0
  OUTLONG(ms_per_frame);       /* Microseconds per frame */
1135
  //ThOe ->0
1136
  //   OUTLONG(10000000);           /* MaxBytesPerSec, I hope this will never be used */
1137
0
  OUTLONG(0);
1138
0
  OUTLONG(0);                  /* PaddingGranularity (whatever that might be) */
1139
  /* Other sources call it 'reserved' */
1140
0
  flag = AVIF_ISINTERLEAVED;
1141
0
  if(hasIndex) flag |= AVIF_HASINDEX;
1142
0
  if(hasIndex && AVI->must_use_index) flag |= AVIF_MUSTUSEINDEX;
1143
0
  OUTLONG(flag);               /* Flags */
1144
0
  OUTLONG(AVI->video_frames);  /* TotalFrames */
1145
0
  OUTLONG(0);                  /* InitialFrames */
1146
1147
0
  OUTLONG(AVI->anum+1);
1148
//   if (AVI->track[0].audio_bytes)
1149
//      { OUTLONG(2); }           /* Streams */
1150
//   else
1151
//      { OUTLONG(1); }           /* Streams */
1152
1153
0
  OUTLONG(0);                  /* SuggestedBufferSize */
1154
0
  OUTLONG(AVI->width);         /* Width */
1155
0
  OUTLONG(AVI->height);        /* Height */
1156
  /* MS calls the following 'reserved': */
1157
0
  OUTLONG(0);                  /* TimeScale:  Unit used to measure time */
1158
0
  OUTLONG(0);                  /* DataRate:   Data rate of playback     */
1159
0
  OUTLONG(0);                  /* StartTime:  Starting time of AVI data */
1160
0
  OUTLONG(0);                  /* DataLength: Size of AVI data chunk    */
1161
1162
1163
  /* Start the video stream list ---------------------------------- */
1164
1165
0
  OUT4CC ("LIST");
1166
0
  OUTLONG(0);        /* Length of list in bytes, don't know yet */
1167
0
  strl_start = nhb;  /* Store start position */
1168
0
  OUT4CC ("strl");
1169
1170
  /* The video stream header */
1171
1172
0
  OUT4CC ("strh");
1173
0
  OUTLONG(56);                 /* # of bytes to follow */
1174
0
  OUT4CC ("vids");             /* Type */
1175
0
  OUT4CC (AVI->compressor);    /* Handler */
1176
0
  OUTLONG(0);                  /* Flags */
1177
0
  OUTLONG(0);                  /* Reserved, MS says: wPriority, wLanguage */
1178
0
  OUTLONG(0);                  /* InitialFrames */
1179
0
  OUTLONG(FRAME_RATE_SCALE);   /* Scale */
1180
0
  OUTLONG(frate);              /* Rate: Rate/Scale == samples/second */
1181
0
  OUTLONG(0);                  /* Start */
1182
0
  OUTLONG(AVI->video_frames);  /* Length */
1183
0
  OUTLONG(AVI->max_len);       /* SuggestedBufferSize */
1184
0
  OUTLONG(0);                  /* Quality */
1185
0
  OUTLONG(0);                  /* SampleSize */
1186
0
  OUTLONG(0);                  /* Frame */
1187
0
  OUTLONG(0);                  /* Frame */
1188
  //OUTLONG(0);                  /* Frame */
1189
  //OUTLONG(0);                  /* Frame */
1190
1191
  /* The video stream format */
1192
1193
0
  xd_size        = AVI->extradata_size;
1194
0
  xd_size_align2 = (AVI->extradata_size+1) & ~1;
1195
1196
0
  OUT4CC ("strf");
1197
0
  OUTLONG(40 + xd_size_align2);/* # of bytes to follow */
1198
0
  OUTLONG(40 + xd_size); /* Size */
1199
0
  OUTLONG(AVI->width);         /* Width */
1200
0
  OUTLONG(AVI->height);        /* Height */
1201
0
  OUTSHRT(1);
1202
0
  OUTSHRT(24);     /* Planes, Count */
1203
0
  OUT4CC (AVI->compressor);    /* Compression */
1204
  // ThOe (*3)
1205
0
  OUTLONG(AVI->width*AVI->height*3);  /* SizeImage (in bytes?) */
1206
0
  OUTLONG(0);                  /* XPelsPerMeter */
1207
0
  OUTLONG(0);                  /* YPelsPerMeter */
1208
0
  OUTLONG(0);                  /* ClrUsed: Number of colors used */
1209
0
  OUTLONG(0);                  /* ClrImportant: Number of colors important */
1210
1211
  // write extradata if present
1212
0
  if (xd_size > 0 && AVI->extradata) {
1213
0
    OUTMEM(AVI->extradata, xd_size);
1214
0
    if (xd_size != xd_size_align2) {
1215
0
      OUTCHR(0);
1216
0
    }
1217
0
  }
1218
1219
  // dump index of indices for audio
1220
0
  if (AVI->is_opendml) {
1221
0
    u32 k;
1222
1223
0
    OUT4CC(AVI->video_superindex->fcc);
1224
0
    OUTLONG(2+1+1+4+4+3*4 + AVI->video_superindex->nEntriesInUse * (8+4+4));
1225
0
    OUTSHRT(AVI->video_superindex->wLongsPerEntry);
1226
0
    OUTCHR(AVI->video_superindex->bIndexSubType);
1227
0
    OUTCHR(AVI->video_superindex->bIndexType);
1228
0
    OUTLONG(AVI->video_superindex->nEntriesInUse);
1229
0
    OUT4CC(AVI->video_superindex->dwChunkId);
1230
0
    OUTLONG(0);
1231
0
    OUTLONG(0);
1232
0
    OUTLONG(0);
1233
1234
1235
0
    for (k = 0; k < AVI->video_superindex->nEntriesInUse; k++) {
1236
0
      u32 r = (u32) ((AVI->video_superindex->aIndex[k].qwOffset >> 32) & 0xffffffff);
1237
0
      u32 s = (u32) ((AVI->video_superindex->aIndex[k].qwOffset) & 0xffffffff);
1238
1239
0
      OUTLONG(s);
1240
0
      OUTLONG(r);
1241
0
      OUTLONG(AVI->video_superindex->aIndex[k].dwSize);
1242
0
      OUTLONG(AVI->video_superindex->aIndex[k].dwDuration);
1243
0
    }
1244
1245
0
  }
1246
1247
  /* Finish stream list, i.e. put number of bytes in the list to proper pos */
1248
1249
0
  long2str(AVI_header+strl_start-4,nhb-strl_start);
1250
1251
  /* Start the audio stream list ---------------------------------- */
1252
1253
0
  for(j=0; j<AVI->anum; ++j) {
1254
1255
    //if (AVI->track[j].a_chans && AVI->track[j].audio_bytes)
1256
0
    {
1257
0
      unsigned int nBlockAlign = 0;
1258
0
      unsigned int avgbsec = 0;
1259
0
      unsigned int scalerate = 0;
1260
1261
0
      int sampsize = avi_sampsize(AVI, j);
1262
0
      sampsize = AVI->track[j].a_fmt==0x1?sampsize*4:sampsize;
1263
1264
0
      nBlockAlign = (AVI->track[j].a_rate<32000)?576:1152;
1265
      /*
1266
      GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] XXX sampsize (%d) block (%ld) rate (%ld) audio_bytes (%ld) mp3rate(%ld,%ld)\n",
1267
       sampsize, nBlockAlign, AVI->track[j].a_rate,
1268
       (int int)AVI->track[j].audio_bytes,
1269
       1000*AVI->track[j].mp3rate/8, AVI->track[j].mp3rate));
1270
       */
1271
1272
0
      if (AVI->track[j].a_fmt==0x1) {
1273
0
        sampsize = (AVI->track[j].a_chans<2)?sampsize/2:sampsize;
1274
0
        avgbsec = AVI->track[j].a_rate*sampsize/4;
1275
0
        scalerate = AVI->track[j].a_rate*sampsize/4;
1276
0
      } else  {
1277
0
        avgbsec = 1000*AVI->track[j].mp3rate/8;
1278
0
        scalerate = 1000*AVI->track[j].mp3rate/8;
1279
0
      }
1280
1281
0
      OUT4CC ("LIST");
1282
0
      OUTLONG(0);        /* Length of list in bytes, don't know yet */
1283
0
      strl_start = nhb;  /* Store start position */
1284
0
      OUT4CC ("strl");
1285
1286
      /* The audio stream header */
1287
1288
0
      OUT4CC ("strh");
1289
0
      OUTLONG(56);            /* # of bytes to follow */
1290
0
      OUT4CC ("auds");
1291
1292
      // -----------
1293
      // ThOe
1294
0
      OUTLONG(0);             /* Format (Optionally) */
1295
      // -----------
1296
1297
0
      OUTLONG(0);             /* Flags */
1298
0
      OUTLONG(0);             /* Reserved, MS says: wPriority, wLanguage */
1299
0
      OUTLONG(0);             /* InitialFrames */
1300
1301
      // VBR
1302
0
      if (AVI->track[j].a_fmt == 0x55 && AVI->track[j].a_vbr) {
1303
0
        OUTLONG(nBlockAlign);                   /* Scale */
1304
0
        OUTLONG(AVI->track[j].a_rate);          /* Rate */
1305
0
        OUTLONG(0);                             /* Start */
1306
0
        OUTLONG(AVI->track[j].audio_chunks);    /* Length */
1307
0
        OUTLONG(0);                      /* SuggestedBufferSize */
1308
0
        OUTLONG(0);                             /* Quality */
1309
0
        OUTLONG(0);                             /* SampleSize */
1310
0
        OUTLONG(0);                             /* Frame */
1311
0
        OUTLONG(0);                             /* Frame */
1312
0
      } else {
1313
0
        OUTLONG(sampsize/4);                    /* Scale */
1314
0
        OUTLONG(scalerate);  /* Rate */
1315
0
        OUTLONG(0);                             /* Start */
1316
0
        OUTLONG(4*AVI->track[j].audio_bytes/sampsize);   /* Length */
1317
0
        OUTLONG(0);                             /* SuggestedBufferSize */
1318
0
        OUTLONG(0xffffffff);                             /* Quality */
1319
0
        OUTLONG(sampsize/4);                    /* SampleSize */
1320
0
        OUTLONG(0);                             /* Frame */
1321
0
        OUTLONG(0);                             /* Frame */
1322
0
      }
1323
1324
      /* The audio stream format */
1325
1326
0
      OUT4CC ("strf");
1327
1328
0
      if (AVI->track[j].a_fmt == 0x55 && AVI->track[j].a_vbr) {
1329
1330
0
        OUTLONG(30);                            /* # of bytes to follow */ // mplayer writes 28
1331
0
        OUTSHRT(AVI->track[j].a_fmt);           /* Format */                  // 2
1332
0
        OUTSHRT(AVI->track[j].a_chans);         /* Number of channels */      // 2
1333
0
        OUTLONG(AVI->track[j].a_rate);          /* SamplesPerSec */           // 4
1334
        //ThOe/tibit
1335
0
        OUTLONG(1000*AVI->track[j].mp3rate/8);  /* maybe we should write an avg. */ // 4
1336
0
        OUTSHRT(nBlockAlign);                   /* BlockAlign */              // 2
1337
0
        OUTSHRT(AVI->track[j].a_bits);          /* BitsPerSample */           // 2
1338
1339
0
        OUTSHRT(12);                           /* cbSize */                   // 2
1340
0
        OUTSHRT(1);                            /* wID */                      // 2
1341
0
        OUTLONG(2);                            /* fdwFlags */                 // 4
1342
0
        OUTSHRT(nBlockAlign);                  /* nBlockSize */               // 2
1343
0
        OUTSHRT(1);                            /* nFramesPerBlock */          // 2
1344
0
        OUTSHRT(0);                            /* nCodecDelay */              // 2
1345
1346
0
      } else if (AVI->track[j].a_fmt == 0x55 && !AVI->track[j].a_vbr) {
1347
1348
0
        OUTLONG(30);                            /* # of bytes to follow */
1349
0
        OUTSHRT(AVI->track[j].a_fmt);           /* Format */
1350
0
        OUTSHRT(AVI->track[j].a_chans);         /* Number of channels */
1351
0
        OUTLONG(AVI->track[j].a_rate);          /* SamplesPerSec */
1352
        //ThOe/tibit
1353
0
        OUTLONG(1000*AVI->track[j].mp3rate/8);
1354
0
        OUTSHRT(sampsize/4);                    /* BlockAlign */
1355
0
        OUTSHRT(AVI->track[j].a_bits);          /* BitsPerSample */
1356
1357
0
        OUTSHRT(12);                           /* cbSize */
1358
0
        OUTSHRT(1);                            /* wID */
1359
0
        OUTLONG(2);                            /* fdwFlags */
1360
0
        OUTSHRT(nBlockAlign);                  /* nBlockSize */
1361
0
        OUTSHRT(1);                            /* nFramesPerBlock */
1362
0
        OUTSHRT(0);                            /* nCodecDelay */
1363
1364
0
      } else {
1365
1366
0
        OUTLONG(18);                   /* # of bytes to follow */
1367
0
        OUTSHRT(AVI->track[j].a_fmt);           /* Format */
1368
0
        OUTSHRT(AVI->track[j].a_chans);         /* Number of channels */
1369
0
        OUTLONG(AVI->track[j].a_rate);          /* SamplesPerSec */
1370
        //ThOe/tibit
1371
0
        OUTLONG(avgbsec);  /* Avg bytes/sec */
1372
0
        OUTSHRT(sampsize/4);                    /* BlockAlign */
1373
0
        OUTSHRT(AVI->track[j].a_bits);          /* BitsPerSample */
1374
0
        OUTSHRT(0);                           /* cbSize */
1375
1376
0
      }
1377
0
    }
1378
0
    if (AVI->is_opendml) {
1379
0
      u32 k;
1380
1381
0
      if (!AVI->track[j].audio_superindex) {
1382
        // not initialized -> no index
1383
0
        continue;
1384
0
      }
1385
1386
0
      OUT4CC(AVI->track[j].audio_superindex->fcc);    /* "indx" */
1387
0
      OUTLONG(2+1+1+4+4+3*4 + AVI->track[j].audio_superindex->nEntriesInUse * (8+4+4));
1388
0
      OUTSHRT(AVI->track[j].audio_superindex->wLongsPerEntry);
1389
0
      OUTCHR(AVI->track[j].audio_superindex->bIndexSubType);
1390
0
      OUTCHR(AVI->track[j].audio_superindex->bIndexType);
1391
0
      OUTLONG(AVI->track[j].audio_superindex->nEntriesInUse);
1392
0
      OUT4CC(AVI->track[j].audio_superindex->dwChunkId);
1393
0
      OUTLONG(0);
1394
0
      OUTLONG(0);
1395
0
      OUTLONG(0);
1396
1397
0
      for (k = 0; k < AVI->track[j].audio_superindex->nEntriesInUse; k++) {
1398
0
        u32 r = (u32) ((AVI->track[j].audio_superindex->aIndex[k].qwOffset >> 32) & 0xffffffff);
1399
0
        u32 s = (u32) ((AVI->track[j].audio_superindex->aIndex[k].qwOffset) & 0xffffffff);
1400
1401
        /*
1402
        GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] AUD[%d] NrEntries %d/%ld (%c%c%c%c) |0x%llX|%ld|%ld| \n",  j, k,
1403
                AVI->track[j].audio_superindex->nEntriesInUse,
1404
            AVI->track[j].audio_superindex->dwChunkId[0], AVI->track[j].audio_superindex->dwChunkId[1],
1405
            AVI->track[j].audio_superindex->dwChunkId[2], AVI->track[j].audio_superindex->dwChunkId[3],
1406
            AVI->track[j].audio_superindex->aIndex[k].qwOffset,
1407
            AVI->track[j].audio_superindex->aIndex[k].dwSize,
1408
            AVI->track[j].audio_superindex->aIndex[k].dwDuration
1409
          ));
1410
          */
1411
1412
0
        OUTLONG(s);
1413
0
        OUTLONG(r);
1414
0
        OUTLONG(AVI->track[j].audio_superindex->aIndex[k].dwSize);
1415
0
        OUTLONG(AVI->track[j].audio_superindex->aIndex[k].dwDuration);
1416
0
      }
1417
0
    }
1418
    /* Finish stream list, i.e. put number of bytes in the list to proper pos */
1419
0
    long2str(AVI_header+strl_start-4,nhb-strl_start);
1420
0
  }
1421
1422
0
  if (AVI->is_opendml) {
1423
0
    OUT4CC("LIST");
1424
0
    OUTLONG(16);
1425
0
    OUT4CC("odml");
1426
0
    OUT4CC("dmlh");
1427
0
    OUTLONG(4);
1428
0
    OUTLONG(AVI->total_frames);
1429
0
  }
1430
1431
  /* Finish header list */
1432
1433
0
  long2str(AVI_header+hdrl_start-4,nhb-hdrl_start);
1434
1435
1436
  // add INFO list --- (0.6.0pre4)
1437
1438
0
#ifdef INFO_LIST
1439
0
  OUT4CC ("LIST");
1440
1441
0
  info_start_pos = nhb;
1442
0
  info_len = MAX_INFO_STRLEN + 12;
1443
0
  OUTLONG(info_len); // rewritten later
1444
0
  OUT4CC ("INFO");
1445
1446
0
  OUT4CC ("ISFT");
1447
  //OUTLONG(MAX_INFO_STRLEN);
1448
0
  memset(id_str, 0, MAX_INFO_STRLEN);
1449
0
  if (gf_sys_is_test_mode()) {
1450
0
    snprintf(id_str, MAX_INFO_STRLEN, "GPAC/avilib");
1451
0
  } else {
1452
0
    snprintf(id_str, MAX_INFO_STRLEN, "GPAC/avilib-%s", gf_gpac_version());
1453
0
  }
1454
0
  real_id_len = id_len = (u32) strlen(id_str)+1;
1455
0
  if (id_len&1) id_len++;
1456
1457
0
  OUTLONG(real_id_len);
1458
1459
0
  memset(AVI_header+nhb, 0, id_len);
1460
0
  memcpy(AVI_header+nhb, id_str, id_len);
1461
0
  nhb += id_len;
1462
1463
0
  info_len = 0;
1464
1465
  // write correct len
1466
0
  long2str(AVI_header+info_start_pos, info_len + id_len + 4+4+4);
1467
1468
0
  nhb += info_len;
1469
1470
//   OUT4CC ("ICMT");
1471
//   OUTLONG(MAX_INFO_STRLEN);
1472
1473
//   calptr=time(NULL);
1474
//   sprintf(id_str, "\t%s %s", ctime(&calptr), "");
1475
//   memset(AVI_header+nhb, 0, MAX_INFO_STRLEN);
1476
//   memcpy(AVI_header+nhb, id_str, 25);
1477
//   nhb += MAX_INFO_STRLEN;
1478
0
#endif
1479
1480
  // ----------------------------
1481
1482
  /* Calculate the needed amount of junk bytes, output junk */
1483
1484
0
  njunk = HEADERBYTES - nhb - 8 - 12;
1485
1486
  /* Safety first: if njunk <= 0, somebody has played with
1487
     HEADERBYTES without knowing what (s)he did.
1488
     This is a fatal error */
1489
1490
0
  if(njunk<=0)
1491
0
  {
1492
0
    GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] AVI_close_output_file: # of header bytes too small\n"));
1493
0
    exit(1);
1494
0
  }
1495
1496
0
  OUT4CC ("JUNK");
1497
0
  OUTLONG(njunk);
1498
0
  memset(AVI_header+nhb,0,njunk);
1499
1500
0
  nhb += njunk;
1501
1502
  /* Start the movi list */
1503
1504
0
  OUT4CC ("LIST");
1505
0
  OUTLONG(movi_len); /* Length of list in bytes */
1506
0
  OUT4CC ("movi");
1507
1508
  /* Output the header, truncate the file to the number of bytes
1509
     actually written, report an error if someting goes wrong */
1510
1511
0
  if ( (gf_fseek(AVI->fdes,0,SEEK_SET)==(u64)-1) ||
1512
0
          avi_write(AVI->fdes,(char *)AVI_header,HEADERBYTES)!=HEADERBYTES
1513
//    || ftruncate(AVI->fdes,AVI->pos)<0
1514
0
     )
1515
0
  {
1516
0
    AVI_errno = AVI_ERR_CLOSE;
1517
0
    return -1;
1518
0
  }
1519
1520
1521
  // Fix up the empty additional RIFF and LIST chunks
1522
0
  if (AVI->is_opendml) {
1523
0
    u32 k;
1524
0
    char f[4];
1525
0
    u32 len;
1526
1527
0
    for (k=1; k<AVI->video_superindex->nEntriesInUse; k++) {
1528
      // the len of the RIFF Chunk
1529
0
      gf_fseek(AVI->fdes, AVI->video_superindex->stdindex[k]->qwBaseOffset+4, SEEK_SET);
1530
0
      len = (u32) (AVI->video_superindex->stdindex[k+1]->qwBaseOffset - AVI->video_superindex->stdindex[k]->qwBaseOffset - 8);
1531
0
      long2str((unsigned char *)f, len);
1532
0
      avi_write(AVI->fdes, f, 4);
1533
1534
      // len of the LIST/movi chunk
1535
0
      gf_fseek(AVI->fdes, 8, SEEK_CUR);
1536
0
      len -= 12;
1537
0
      long2str((unsigned char *)f, len);
1538
0
      avi_write(AVI->fdes, f, 4);
1539
0
    }
1540
0
  }
1541
1542
1543
0
  if(idxerror) return -1;
1544
1545
0
  return 0;
1546
0
}
1547
1548
/*
1549
   AVI_write_data:
1550
   Add video or audio data to the file;
1551
1552
   Return values:
1553
    0    No error;
1554
   -1    Error, AVI_errno is set appropriatly;
1555
1556
*/
1557
1558
static int avi_write_data(avi_t *AVI, char *data, unsigned int length, int audio, int keyframe)
1559
0
{
1560
0
  int n = 0;
1561
1562
0
  unsigned char astr[5];
1563
1564
  // transcode core itself checks for the size -- unneeded and
1565
  // does harm to xvid 2pass encodes where the first pass can get
1566
  // _very_ large -- tibit.
1567
1568
#if 0
1569
  /* Check for maximum file length */
1570
1571
  if ( (AVI->pos + 8 + length + 8 + (AVI->n_idx+1)*16) > AVI_MAX_LEN ) {
1572
    AVI_errno = AVI_ERR_SIZELIM;
1573
    return -1;
1574
  }
1575
#endif
1576
1577
  /* Add index entry */
1578
1579
  //set tag for current audio track
1580
0
  sprintf((char *)astr, "0%1dwb", (int)(AVI->aptr+1));
1581
1582
0
  if(audio) {
1583
0
    if (!AVI->is_opendml) n = avi_add_index_entry(AVI,astr,0x10,AVI->pos,length);
1584
0
    n += avi_add_odml_index_entry(AVI,astr,0x10,AVI->pos,length);
1585
0
  } else {
1586
0
    if (!AVI->is_opendml) n = avi_add_index_entry(AVI,(unsigned char *)"00db",((keyframe)?0x10:0x0),AVI->pos,length);
1587
0
    n += avi_add_odml_index_entry(AVI,(unsigned char *)"00db",((keyframe)?0x10:0x0),AVI->pos,length);
1588
0
  }
1589
1590
0
  if(n) return -1;
1591
1592
  /* Output tag and data */
1593
1594
0
  if(audio)
1595
0
    n = avi_add_chunk(AVI,(unsigned char *)astr, (unsigned char *)data, length);
1596
0
  else
1597
0
    n = avi_add_chunk(AVI,(unsigned char *)"00db", (unsigned char *)data, length);
1598
1599
0
  if (n) return -1;
1600
1601
0
  return 0;
1602
0
}
1603
1604
GF_EXPORT
1605
int AVI_write_frame(avi_t *AVI, u8 *data, int bytes, int keyframe)
1606
0
{
1607
0
  s64 pos;
1608
1609
0
  if(AVI->mode==AVI_MODE_READ) {
1610
0
    AVI_errno = AVI_ERR_NOT_PERM;
1611
0
    return -1;
1612
0
  }
1613
1614
0
  pos = AVI->pos;
1615
1616
0
  if(avi_write_data(AVI,data,bytes,0,keyframe)) return -1;
1617
1618
0
  AVI->last_pos = pos;
1619
0
  AVI->last_len = bytes;
1620
0
  AVI->video_frames++;
1621
0
  return 0;
1622
0
}
1623
1624
#if 0 //unused
1625
int AVI_dup_frame(avi_t *AVI)
1626
{
1627
  if(AVI->mode==AVI_MODE_READ) {
1628
    AVI_errno = AVI_ERR_NOT_PERM;
1629
    return -1;
1630
  }
1631
1632
  if(AVI->last_pos==0) return 0; /* No previous real frame */
1633
  if(avi_add_index_entry(AVI,(unsigned char *)"00db",0x10,AVI->last_pos,AVI->last_len)) return -1;
1634
  AVI->video_frames++;
1635
  AVI->must_use_index = 1;
1636
  return 0;
1637
}
1638
#endif
1639
1640
GF_EXPORT
1641
int AVI_write_audio(avi_t *AVI, u8 *data, int bytes)
1642
0
{
1643
0
  if(AVI->mode==AVI_MODE_READ) {
1644
0
    AVI_errno = AVI_ERR_NOT_PERM;
1645
0
    return -1;
1646
0
  }
1647
1648
0
  if( avi_write_data(AVI,data,bytes,1,0) ) return -1;
1649
0
  AVI->track[AVI->aptr].audio_bytes += bytes;
1650
0
  AVI->track[AVI->aptr].audio_chunks++;
1651
0
  return 0;
1652
0
}
1653
1654
#if 0 //unused
1655
1656
int AVI_append_audio(avi_t *AVI, u8 *data, int bytes)
1657
{
1658
1659
  // won't work for >2gb
1660
  int i, length, pos;
1661
  unsigned char c[4];
1662
1663
  if(AVI->mode==AVI_MODE_READ) {
1664
    AVI_errno = AVI_ERR_NOT_PERM;
1665
    return -1;
1666
  }
1667
1668
  // update last index entry:
1669
1670
  --AVI->n_idx;
1671
  length = str2ulong(AVI->idx[AVI->n_idx]+12);
1672
  pos    = str2ulong(AVI->idx[AVI->n_idx]+8);
1673
1674
  //update;
1675
  long2str(AVI->idx[AVI->n_idx]+12,length+bytes);
1676
1677
  ++AVI->n_idx;
1678
1679
  AVI->track[AVI->aptr].audio_bytes += bytes;
1680
1681
  //update chunk header
1682
  gf_fseek(AVI->fdes, pos+4, SEEK_SET);
1683
  long2str(c, length+bytes);
1684
  avi_write(AVI->fdes, (char *)c, 4);
1685
1686
  gf_fseek(AVI->fdes, pos+8+length, SEEK_SET);
1687
1688
  i=PAD_EVEN(length + bytes);
1689
1690
  bytes = i - length;
1691
  avi_write(AVI->fdes, data, bytes);
1692
  AVI->pos = pos + 8 + i;
1693
1694
  return 0;
1695
}
1696
1697
u64 AVI_bytes_remain(avi_t *AVI)
1698
{
1699
  if(AVI->mode==AVI_MODE_READ) return 0;
1700
1701
  return ( AVI_MAX_LEN - (AVI->pos + 8 + 16*AVI->n_idx));
1702
}
1703
1704
u64 AVI_bytes_written(avi_t *AVI)
1705
{
1706
  if(AVI->mode==AVI_MODE_READ) return 0;
1707
1708
  return (AVI->pos + 8 + 16*AVI->n_idx);
1709
}
1710
#endif
1711
1712
int AVI_set_audio_track(avi_t *AVI, u32 track)
1713
0
{
1714
1715
0
  if (track + 1 > AVI->anum) return(-1);
1716
1717
  //this info is not written to file anyway
1718
0
  AVI->aptr=track;
1719
0
  return 0;
1720
0
}
1721
1722
int AVI_get_audio_track(avi_t *AVI)
1723
0
{
1724
0
  return(AVI->aptr);
1725
0
}
1726
1727
#if 0 //unused
1728
void AVI_set_audio_vbr(avi_t *AVI, int is_vbr)
1729
{
1730
  AVI->track[AVI->aptr].a_vbr = is_vbr;
1731
}
1732
1733
int AVI_get_audio_vbr(avi_t *AVI)
1734
{
1735
  return(AVI->track[AVI->aptr].a_vbr);
1736
}
1737
#endif
1738
1739
1740
/*******************************************************************
1741
 *                                                                 *
1742
 *    Utilities for reading video and audio from an AVI File       *
1743
 *                                                                 *
1744
 *******************************************************************/
1745
1746
GF_EXPORT
1747
int AVI_close(avi_t *AVI)
1748
0
{
1749
0
  int ret;
1750
0
  u32 j;
1751
1752
  /* If the file was open for writing, the header and index still have
1753
     to be written */
1754
1755
0
  if(AVI->mode == AVI_MODE_WRITE)
1756
0
    ret = avi_close_output_file(AVI);
1757
0
  else
1758
0
    ret = 0;
1759
1760
  /* Even if there happened an error, we first clean up */
1761
1762
0
  gf_fclose(AVI->fdes);
1763
0
  if(AVI->idx) gf_free(AVI->idx);
1764
0
  if(AVI->video_index) gf_free(AVI->video_index);
1765
0
  if(AVI->video_superindex) {
1766
0
    if(AVI->video_superindex->aIndex) gf_free(AVI->video_superindex->aIndex);
1767
0
    if (AVI->video_superindex->stdindex) {
1768
0
      for (j=0; j < NR_IXNN_CHUNKS; j++) {
1769
0
        if (AVI->video_superindex->stdindex[j]->aIndex)
1770
0
          gf_free(AVI->video_superindex->stdindex[j]->aIndex);
1771
0
        gf_free(AVI->video_superindex->stdindex[j]);
1772
0
      }
1773
0
      gf_free(AVI->video_superindex->stdindex);
1774
0
    }
1775
0
    gf_free(AVI->video_superindex);
1776
0
  }
1777
0
  for (j=0; j<AVI->anum; j++)
1778
0
  {
1779
0
    u32 k;
1780
0
    if(AVI->track[j].audio_index) gf_free(AVI->track[j].audio_index);
1781
0
    if(AVI->track[j].audio_superindex) {
1782
0
      avisuperindex_chunk *asi = AVI->track[j].audio_superindex;
1783
0
      if (asi->aIndex) gf_free(asi->aIndex);
1784
1785
0
      if (asi->stdindex) {
1786
0
        for (k=0; k < NR_IXNN_CHUNKS; k++) {
1787
0
          if (!asi->stdindex[k]) continue;
1788
0
          if (asi->stdindex[k]->aIndex)
1789
0
            gf_free(asi->stdindex[k]->aIndex);
1790
0
          gf_free(asi->stdindex[k]);
1791
0
        }
1792
0
        gf_free(asi->stdindex);
1793
0
      }
1794
0
      gf_free(asi);
1795
0
    }
1796
0
  }
1797
1798
0
  if (AVI->bitmap_info_header)
1799
0
    gf_free(AVI->bitmap_info_header);
1800
0
  for (j = 0; j < AVI->anum; j++)
1801
0
    if (AVI->wave_format_ex[j])
1802
0
      gf_free(AVI->wave_format_ex[j]);
1803
0
  if (AVI->extradata)
1804
0
    gf_free(AVI->extradata);
1805
1806
0
  gf_free(AVI);
1807
0
  return ret;
1808
0
}
1809
1810
1811
0
#define ERR_EXIT(x) \
1812
0
{ \
1813
0
   if (hdrl_data) { gf_free(hdrl_data); hdrl_data=NULL; }\
1814
0
   AVI_close(AVI); \
1815
0
   AVI_errno = x; \
1816
0
   return 0; \
1817
0
}
1818
1819
1820
avi_t *AVI_open_input_file(char *filename, int getIndex)
1821
0
{
1822
0
  avi_t *AVI;
1823
1824
  /* Create avi_t structure */
1825
1826
0
  AVI = (avi_t *) gf_malloc(sizeof(avi_t));
1827
0
  if(AVI==NULL)
1828
0
  {
1829
0
    AVI_errno = AVI_ERR_NO_MEM;
1830
0
    return 0;
1831
0
  }
1832
0
  memset((void *)AVI,0,sizeof(avi_t));
1833
1834
0
  AVI->mode = AVI_MODE_READ; /* open for reading */
1835
1836
  /* Open the file */
1837
1838
0
  AVI->fdes = gf_fopen(filename,"rb");
1839
0
  if(!AVI->fdes )
1840
0
  {
1841
0
    AVI_errno = AVI_ERR_OPEN;
1842
0
    gf_free(AVI);
1843
0
    return 0;
1844
0
  }
1845
1846
0
  AVI_errno = 0;
1847
0
  avi_parse_input_file(AVI, getIndex);
1848
1849
0
  if (AVI != NULL && !AVI_errno) {
1850
0
    AVI->aptr=0; //reset
1851
0
  }
1852
1853
0
  if (AVI_errno) return NULL;
1854
1855
0
  return AVI;
1856
0
}
1857
1858
#if 0
1859
avi_t *AVI_open_fd(FILE *fd, int getIndex)
1860
{
1861
  avi_t *AVI=NULL;
1862
1863
  /* Create avi_t structure */
1864
1865
  AVI = (avi_t *) gf_malloc(sizeof(avi_t));
1866
  if(AVI==NULL)
1867
  {
1868
    AVI_errno = AVI_ERR_NO_MEM;
1869
    return 0;
1870
  }
1871
  memset((void *)AVI,0,sizeof(avi_t));
1872
1873
  AVI->mode = AVI_MODE_READ; /* open for reading */
1874
1875
  // file alread open
1876
  AVI->fdes = fd;
1877
1878
  AVI_errno = 0;
1879
  avi_parse_input_file(AVI, getIndex);
1880
1881
  if (AVI != NULL && !AVI_errno) {
1882
    AVI->aptr=0; //reset
1883
  }
1884
1885
  if (AVI_errno)
1886
    return AVI=NULL;
1887
  else
1888
    return AVI;
1889
}
1890
#endif
1891
1892
int avi_parse_input_file(avi_t *AVI, int getIndex)
1893
0
{
1894
0
  int rate, scale, idx_type;
1895
0
  s64 n, i;
1896
0
  unsigned char *hdrl_data = NULL;
1897
0
  u64 header_offset=0;
1898
0
  int hdrl_len=0;
1899
0
  int nvi, nai[AVI_MAX_TRACKS], ioff;
1900
0
  u64 tot[AVI_MAX_TRACKS];
1901
0
  u32 j;
1902
0
  int lasttag = 0;
1903
0
  int vids_strh_seen = 0;
1904
0
  int vids_strf_seen = 0;
1905
0
  int auds_strh_seen = 0;
1906
  //  int auds_strf_seen = 0;
1907
0
  int num_stream = 0;
1908
0
  char data[256];
1909
0
  s64 oldpos=-1, newpos=-1;
1910
1911
0
  int aud_chunks = 0;
1912
0
  if (!AVI) {
1913
0
     AVI_errno = AVI_ERR_OPEN;
1914
0
     return 0;
1915
0
  }
1916
1917
  /* Read first 12 bytes and check that this is an AVI file */
1918
0
  if (avi_read(AVI->fdes,data,12) != 12 )
1919
0
    ERR_EXIT(AVI_ERR_READ)
1920
1921
0
  if (strnicmp(data  ,"RIFF",4) !=0 || strnicmp(data+8,"AVI ",4) !=0 )
1922
0
    ERR_EXIT(AVI_ERR_NO_AVI)
1923
1924
  /* Go through the AVI file and extract the header list,
1925
     the start position of the 'movi' list and an optionally
1926
     present idx1 tag */
1927
1928
0
  hdrl_data = 0;
1929
1930
0
  while(1)
1931
0
  {
1932
0
    if( avi_read(AVI->fdes,data,8) != 8 ) break; /* We assume it's EOF */
1933
0
    newpos = gf_ftell(AVI->fdes);
1934
0
    if(oldpos==newpos) {
1935
      /* This is a broken AVI stream... */
1936
0
      return -1;
1937
0
    }
1938
0
    oldpos=newpos;
1939
1940
0
    n = str2ulong((unsigned char *)data+4);
1941
0
    n = PAD_EVEN(n);
1942
1943
0
    if(strnicmp(data,"LIST",4) == 0)
1944
0
    {
1945
0
      if( avi_read(AVI->fdes,data,4) != 4 ) ERR_EXIT(AVI_ERR_READ)
1946
0
        n -= 4;
1947
0
      if(strnicmp(data,"hdrl",4) == 0)
1948
0
      {
1949
0
        if (n>0xFFFFFFFF) ERR_EXIT(AVI_ERR_READ)
1950
0
        hdrl_len = (u32) n;
1951
0
        if (hdrl_data)
1952
0
          gf_free(hdrl_data);
1953
0
        hdrl_data = (unsigned char *) gf_malloc((u32)n);
1954
0
        if(hdrl_data==0) ERR_EXIT(AVI_ERR_NO_MEM);
1955
1956
        // offset of header
1957
1958
0
        header_offset = gf_ftell(AVI->fdes);
1959
1960
0
        if( avi_read(AVI->fdes,(char *)hdrl_data, (u32) n) != n ) {
1961
0
          ERR_EXIT(AVI_ERR_READ)
1962
0
        }
1963
0
      }
1964
0
      else if(strnicmp(data,"movi",4) == 0)
1965
0
      {
1966
0
        AVI->movi_start = gf_ftell(AVI->fdes);
1967
0
        if (gf_fseek(AVI->fdes,n,SEEK_CUR)==(u64)-1) break;
1968
0
      }
1969
0
      else if (gf_fseek(AVI->fdes,n,SEEK_CUR)==(u64)-1) break;
1970
0
    }
1971
0
    else if(strnicmp(data,"idx1",4) == 0)
1972
0
    {
1973
      /* n must be a multiple of 16, but the reading does not
1974
         break if this is not the case */
1975
1976
0
      AVI->n_idx = AVI->max_idx = (u32) (n/16);
1977
0
      if (AVI->idx) gf_free(AVI->idx);
1978
0
      AVI->idx = (unsigned  char((*)[16]) ) gf_malloc((u32)n);
1979
0
      if(AVI->idx==0) {
1980
0
        ERR_EXIT(AVI_ERR_NO_MEM)
1981
0
      }
1982
0
      if(avi_read(AVI->fdes, (char *) AVI->idx, (u32) n) != n ) {
1983
0
        gf_free( AVI->idx);
1984
0
        AVI->idx=NULL;
1985
0
        AVI->n_idx = 0;
1986
0
        ERR_EXIT(AVI_ERR_READ)
1987
0
      }
1988
0
    }
1989
0
    else
1990
0
      gf_fseek(AVI->fdes,n,SEEK_CUR);
1991
0
  }
1992
1993
0
  if(!hdrl_data) ERR_EXIT(AVI_ERR_NO_HDRL)
1994
0
  if(!AVI->movi_start) ERR_EXIT(AVI_ERR_NO_MOVI)
1995
1996
      /* Interpret the header list */
1997
1998
0
      for(i=0; i<hdrl_len;)
1999
0
      {
2000
0
        if (i+4>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2001
2002
        /* List tags are completly ignored */
2003
#ifdef DEBUG_ODML
2004
        GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] TAG %c%c%c%c\n", (hdrl_data+i)[0], (hdrl_data+i)[1], (hdrl_data+i)[2], (hdrl_data+i)[3]));
2005
#endif
2006
2007
0
        if(strnicmp((char *)hdrl_data+i,"LIST",4)==0) {
2008
0
          i+= 12;
2009
0
          continue;
2010
0
        }
2011
2012
0
        if (i+8>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2013
2014
0
        n = str2ulong(hdrl_data+i+4);
2015
0
        n = PAD_EVEN(n);
2016
0
        if (i+n>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2017
2018
2019
        /* Interpret the tag and its args */
2020
2021
0
        if(strnicmp((char *)hdrl_data+i,"strh",4)==0)
2022
0
        {
2023
0
          i += 8;
2024
0
          if (i+4>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2025
#ifdef DEBUG_ODML
2026
          GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] TAG   %c%c%c%c\n", (hdrl_data+i)[0], (hdrl_data+i)[1], (hdrl_data+i)[2], (hdrl_data+i)[3]));
2027
#endif
2028
0
          if(strnicmp((char *)hdrl_data+i,"vids",4) == 0 && !vids_strh_seen)
2029
0
          {
2030
0
            if ( (i+32+4>hdrl_len) || (i+sizeof(alAVISTREAMHEADER))>hdrl_len ) ERR_EXIT(AVI_ERR_READ)
2031
2032
0
            memcpy(AVI->compressor,hdrl_data+i+4,4);
2033
2034
0
            AVI->compressor[4] = 0;
2035
2036
            // ThOe
2037
0
            AVI->v_codech_off = header_offset + i+4;
2038
2039
0
            scale = str2ulong(hdrl_data+i+20);
2040
0
            rate  = str2ulong(hdrl_data+i+24);
2041
0
            if(scale!=0) AVI->fps = (double)rate/(double)scale;
2042
0
            AVI->video_frames = str2ulong(hdrl_data+i+32);
2043
0
            AVI->video_strn = num_stream;
2044
0
            AVI->max_len = 0;
2045
0
            vids_strh_seen = 1;
2046
0
            lasttag = 1; /* vids */
2047
0
            memcpy(&AVI->video_stream_header, hdrl_data + i,
2048
0
                   sizeof(alAVISTREAMHEADER));
2049
0
          }
2050
0
          else if (strnicmp ((char *)hdrl_data+i,"auds",4) ==0 && ! auds_strh_seen)
2051
0
          {
2052
2053
            //inc audio tracks
2054
0
            if(AVI->anum >= AVI_MAX_TRACKS) {
2055
0
              GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] error - only %d audio tracks supported\n", AVI_MAX_TRACKS));
2056
0
              ERR_EXIT(AVI_ERR_READ)
2057
0
            }
2058
2059
0
            AVI->aptr=AVI->anum;
2060
0
            ++AVI->anum;
2061
2062
0
            if ( (i+44+4>hdrl_len) || (i+sizeof(alAVISTREAMHEADER))>hdrl_len ) ERR_EXIT(AVI_ERR_READ)
2063
2064
0
            AVI->track[AVI->aptr].audio_bytes = str2ulong(hdrl_data+i+32)*avi_sampsize(AVI, 0);
2065
0
            AVI->track[AVI->aptr].audio_strn = num_stream;
2066
2067
            // if samplesize==0 -> vbr
2068
0
            AVI->track[AVI->aptr].a_vbr = !str2ulong(hdrl_data+i+44);
2069
2070
0
            AVI->track[AVI->aptr].padrate = str2ulong(hdrl_data+i+24);
2071
2072
0
            memcpy(&AVI->stream_headers[AVI->aptr], hdrl_data + i, sizeof(alAVISTREAMHEADER));
2073
2074
            //     auds_strh_seen = 1;
2075
0
            lasttag = 2; /* auds */
2076
2077
            // ThOe
2078
0
            AVI->track[AVI->aptr].a_codech_off = header_offset + i;
2079
2080
0
          }
2081
0
          else if (strnicmp ((char*)hdrl_data+i,"iavs",4) ==0 && ! auds_strh_seen) {
2082
0
            GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] AVILIB: error - DV AVI Type 1 no supported\n"));
2083
0
            ERR_EXIT(AVI_ERR_READ)
2084
0
          }
2085
0
          else
2086
0
            lasttag = 0;
2087
0
          num_stream++;
2088
0
        }
2089
0
        else if(strnicmp((char*)hdrl_data+i,"dmlh",4) == 0) {
2090
2091
0
          if (i+8+4>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2092
2093
0
          AVI->total_frames = str2ulong(hdrl_data+i+8);
2094
#ifdef DEBUG_ODML
2095
          GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] real number of frames %d\n", AVI->total_frames));
2096
#endif
2097
0
          i += 8;
2098
0
        }
2099
0
        else if(strnicmp((char *)hdrl_data+i,"strf",4)==0)
2100
0
        {
2101
0
          i += 8;
2102
0
          if(lasttag == 1)
2103
0
          {
2104
0
            if (i+sizeof(alBITMAPINFOHEADER)>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2105
2106
0
            alBITMAPINFOHEADER bih;
2107
2108
0
            memcpy(&bih, hdrl_data + i, sizeof(alBITMAPINFOHEADER));
2109
0
            if (bih.bi_size < 4) ERR_EXIT(AVI_ERR_READ)
2110
0
            bih.bi_size = str2ulong((unsigned char *)&bih.bi_size);
2111
2112
0
            if (i + bih.bi_size > hdrl_len) ERR_EXIT(AVI_ERR_READ)
2113
2114
0
            if (AVI->bitmap_info_header)
2115
0
              gf_free(AVI->bitmap_info_header);
2116
0
            AVI->bitmap_info_header = (alBITMAPINFOHEADER *) gf_malloc(bih.bi_size);
2117
0
            if (AVI->bitmap_info_header != NULL)
2118
0
              memcpy(AVI->bitmap_info_header, hdrl_data + i, bih.bi_size);
2119
2120
0
            if (i+16+4>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2121
2122
0
            AVI->width  = str2ulong(hdrl_data+i+4);
2123
0
            AVI->height = str2ulong(hdrl_data+i+8);
2124
0
            vids_strf_seen = 1;
2125
            //ThOe
2126
0
            AVI->v_codecf_off = header_offset + i+16;
2127
2128
0
            memcpy(AVI->compressor2, hdrl_data+i+16, 4);
2129
0
            AVI->compressor2[4] = 0;
2130
2131
0
            if ((n>40) && (hdrl_len > (i+40))) {
2132
0
              if (n>0xFFFFFFFF) ERR_EXIT(AVI_ERR_READ)
2133
0
              AVI->extradata_size = (u32) MIN(n - 40, hdrl_len-i-40);
2134
0
              AVI->extradata = gf_malloc(sizeof(u8)* AVI->extradata_size);
2135
0
              if (!AVI->extradata) ERR_EXIT(AVI_ERR_NO_MEM)
2136
0
              memcpy(AVI->extradata, hdrl_data + i + 40, AVI->extradata_size);
2137
0
            }
2138
2139
0
          }
2140
0
          else if(lasttag == 2)
2141
0
          {
2142
0
            if (i>=hdrl_len) ERR_EXIT(AVI_ERR_READ)
2143
2144
0
            alWAVEFORMATEX *wfe;
2145
0
            char *nwfe;
2146
0
            int wfes;
2147
2148
0
            if ((u32) (hdrl_len - i) < sizeof(alWAVEFORMATEX))
2149
0
              wfes = (int) (hdrl_len - i);
2150
0
            else
2151
0
              wfes = sizeof(alWAVEFORMATEX);
2152
0
            wfe = (alWAVEFORMATEX *)gf_malloc(sizeof(alWAVEFORMATEX));
2153
0
            if (wfe != NULL) {
2154
0
              memset(wfe, 0, sizeof(alWAVEFORMATEX));
2155
0
              memcpy(wfe, hdrl_data + i, wfes);
2156
0
              if (str2ushort((unsigned char *)&wfe->cb_size) != 0) {
2157
0
                nwfe = (char *)
2158
0
                       gf_realloc(wfe, sizeof(alWAVEFORMATEX) +
2159
0
                                  str2ushort((unsigned char *)&wfe->cb_size));
2160
0
                if (nwfe != 0) {
2161
0
                  s64 lpos = gf_ftell(AVI->fdes);
2162
0
                  gf_fseek(AVI->fdes, header_offset + i + sizeof(alWAVEFORMATEX),
2163
0
                           SEEK_SET);
2164
0
                  wfe = (alWAVEFORMATEX *)nwfe;
2165
0
                  nwfe = &nwfe[sizeof(alWAVEFORMATEX)];
2166
0
                  avi_read(AVI->fdes, nwfe,
2167
0
                           str2ushort((unsigned char *)&wfe->cb_size));
2168
0
                  gf_fseek(AVI->fdes, lpos, SEEK_SET);
2169
0
                }
2170
0
              }
2171
0
              if (AVI->wave_format_ex[AVI->aptr])
2172
0
                gf_free(AVI->wave_format_ex[AVI->aptr]);
2173
2174
0
              AVI->wave_format_ex[AVI->aptr] = wfe;
2175
0
            }
2176
0
            if (i+14+4>hdrl_len) ERR_EXIT(AVI_ERR_READ)
2177
2178
0
            AVI->track[AVI->aptr].a_fmt   = str2ushort(hdrl_data+i  );
2179
2180
            //ThOe
2181
0
            AVI->track[AVI->aptr].a_codecf_off = header_offset + i;
2182
2183
0
            AVI->track[AVI->aptr].a_chans = str2ushort(hdrl_data+i+2);
2184
0
            AVI->track[AVI->aptr].a_rate  = str2ulong (hdrl_data+i+4);
2185
            //ThOe: read mp3bitrate
2186
0
            AVI->track[AVI->aptr].mp3rate = 8*str2ulong(hdrl_data+i+8)/1000;
2187
            //:ThOe
2188
0
            AVI->track[AVI->aptr].a_bits  = str2ushort(hdrl_data+i+14);
2189
            //            auds_strf_seen = 1;
2190
0
          }
2191
0
        }
2192
0
        else if(strnicmp((char*)hdrl_data+i,"indx",4) == 0) {
2193
0
          char *a;
2194
2195
0
          if(lasttag == 1) // V I D E O
2196
0
          {
2197
2198
0
            a = (char*)hdrl_data+i;
2199
0
            int avail =(int) (hdrl_len-i);
2200
0
            if (avail<32) ERR_EXIT(AVI_ERR_READ)
2201
2202
0
            AVI->video_superindex = (avisuperindex_chunk *) gf_malloc (sizeof (avisuperindex_chunk));
2203
0
            memset(AVI->video_superindex, 0, sizeof (avisuperindex_chunk));
2204
0
            memcpy (AVI->video_superindex->fcc, a, 4);
2205
0
            a += 4;
2206
0
            AVI->video_superindex->dwSize = str2ulong((unsigned char *)a);
2207
0
            a += 4;
2208
0
            AVI->video_superindex->wLongsPerEntry = str2ushort((unsigned char *)a);
2209
0
            a += 2;
2210
0
            AVI->video_superindex->bIndexSubType = *a;
2211
0
            a += 1;
2212
0
            AVI->video_superindex->bIndexType = *a;
2213
0
            a += 1;
2214
0
            AVI->video_superindex->nEntriesInUse = str2ulong((unsigned char *)a);
2215
0
            a += 4;
2216
0
            memcpy (AVI->video_superindex->dwChunkId, a, 4);
2217
0
            a += 4;
2218
2219
            // 3 * reserved
2220
0
            a += 4;
2221
0
            a += 4;
2222
0
            a += 4;
2223
2224
0
            if (AVI->video_superindex->bIndexSubType != 0) {
2225
0
              GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] Invalid Header, bIndexSubType != 0\n"));
2226
0
            }
2227
0
            avail -= 32;
2228
0
            if (AVI->video_superindex->nEntriesInUse >= GF_INT_MAX/16 ||
2229
0
              avail < (int) AVI->video_superindex->nEntriesInUse*16) {
2230
2231
0
                ERR_EXIT(AVI_ERR_READ)
2232
0
            }
2233
2234
            // must be 4 so that wLongsPerEntry*sizeof(u32) == sizeof(avisuperindex_entry)
2235
0
            if (AVI->video_superindex->wLongsPerEntry != 4) {
2236
0
              ERR_EXIT(AVI_ERR_READ)
2237
0
            }
2238
2239
0
            AVI->video_superindex->aIndex = (avisuperindex_entry*)
2240
0
                                            gf_malloc (AVI->video_superindex->wLongsPerEntry * AVI->video_superindex->nEntriesInUse * sizeof (u32));
2241
2242
            // position of ix## chunks
2243
0
            for (j=0; j<AVI->video_superindex->nEntriesInUse; ++j) {
2244
0
              AVI->video_superindex->aIndex[j].qwOffset = str2ullong ((unsigned char*)a);
2245
0
              a += 8;
2246
0
              AVI->video_superindex->aIndex[j].dwSize = str2ulong ((unsigned char*)a);
2247
0
              a += 4;
2248
0
              AVI->video_superindex->aIndex[j].dwDuration = str2ulong ((unsigned char*)a);
2249
0
              a += 4;
2250
2251
#ifdef DEBUG_ODML
2252
              GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] [%d] 0x%llx 0x%lx %lu\n", j,
2253
                                                      (unsigned int long)AVI->video_superindex->aIndex[j].qwOffset,
2254
                                                      (unsigned long)AVI->video_superindex->aIndex[j].dwSize,
2255
                                                      (unsigned long)AVI->video_superindex->aIndex[j].dwDuration));
2256
#endif
2257
0
            }
2258
2259
2260
#ifdef DEBUG_ODML
2261
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] FOURCC \"%c%c%c%c\"\n", AVI->video_superindex->fcc[0], AVI->video_superindex->fcc[1],
2262
                                                    AVI->video_superindex->fcc[2], AVI->video_superindex->fcc[3]));
2263
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] LEN \"%ld\"\n", (long)AVI->video_superindex->dwSize));
2264
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] wLongsPerEntry \"%d\"\n", AVI->video_superindex->wLongsPerEntry));
2265
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] bIndexSubType \"%d\"\n", AVI->video_superindex->bIndexSubType));
2266
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] bIndexType \"%d\"\n", AVI->video_superindex->bIndexType));
2267
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] nEntriesInUse \"%ld\"\n", (long)AVI->video_superindex->nEntriesInUse));
2268
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] dwChunkId \"%c%c%c%c\"\n", AVI->video_superindex->dwChunkId[0], AVI->video_superindex->dwChunkId[1],
2269
                                                    AVI->video_superindex->dwChunkId[2], AVI->video_superindex->dwChunkId[3]));
2270
#endif
2271
2272
0
            AVI->is_opendml = 1;
2273
2274
0
          }
2275
0
          else if(lasttag == 2) // A U D I O
2276
0
          {
2277
2278
0
            a = (char*) hdrl_data+i;
2279
0
            int avail = (int) (hdrl_len-i);
2280
0
            if (avail<32) ERR_EXIT(AVI_ERR_READ)
2281
2282
0
            GF_SAFEALLOC(AVI->track[AVI->aptr].audio_superindex, avisuperindex_chunk);
2283
0
            memcpy (AVI->track[AVI->aptr].audio_superindex->fcc, a, 4);
2284
0
            a += 4;
2285
0
            AVI->track[AVI->aptr].audio_superindex->dwSize = str2ulong((unsigned char*)a);
2286
0
            a += 4;
2287
0
            AVI->track[AVI->aptr].audio_superindex->wLongsPerEntry = str2ushort((unsigned char*)a);
2288
0
            a += 2;
2289
0
            AVI->track[AVI->aptr].audio_superindex->bIndexSubType = *a;
2290
0
            a += 1;
2291
0
            AVI->track[AVI->aptr].audio_superindex->bIndexType = *a;
2292
0
            a += 1;
2293
0
            AVI->track[AVI->aptr].audio_superindex->nEntriesInUse = str2ulong((unsigned char*)a);
2294
0
            a += 4;
2295
0
            memcpy (AVI->track[AVI->aptr].audio_superindex->dwChunkId, a, 4);
2296
0
            a += 4;
2297
2298
            // 3 * reserved
2299
0
            a += 4;
2300
0
            a += 4;
2301
0
            a += 4;
2302
2303
0
            if (AVI->track[AVI->aptr].audio_superindex->bIndexSubType != 0) {
2304
0
              GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] Invalid Header, bIndexSubType != 0\n"));
2305
0
            }
2306
2307
0
            avail -= 32;
2308
0
            if (AVI->track[AVI->aptr].audio_superindex->nEntriesInUse >= GF_INT_MAX/16
2309
0
              || avail < (int) AVI->track[AVI->aptr].audio_superindex->nEntriesInUse*16) {
2310
2311
0
                ERR_EXIT(AVI_ERR_READ)
2312
0
            }
2313
2314
0
            if (AVI->track[AVI->aptr].audio_superindex->nEntriesInUse) {
2315
2316
              // must be 4 so that wLongsPerEntry*sizeof(u32) == sizeof(avisuperindex_entry)
2317
0
              if (AVI->track[AVI->aptr].audio_superindex->wLongsPerEntry != 4) {
2318
0
                ERR_EXIT(AVI_ERR_READ)
2319
0
              }
2320
2321
0
              AVI->track[AVI->aptr].audio_superindex->aIndex = (avisuperindex_entry*)
2322
0
                    gf_malloc (AVI->track[AVI->aptr].audio_superindex->wLongsPerEntry *
2323
0
                               AVI->track[AVI->aptr].audio_superindex->nEntriesInUse * sizeof (u32));
2324
0
            }
2325
0
            else {
2326
0
              AVI->track[AVI->aptr].audio_superindex->aIndex = NULL;
2327
0
            }
2328
2329
            // position of ix## chunks
2330
0
            for (j=0; j<AVI->track[AVI->aptr].audio_superindex->nEntriesInUse; ++j) {
2331
0
              AVI->track[AVI->aptr].audio_superindex->aIndex[j].qwOffset = str2ullong ((unsigned char*)a);
2332
0
              a += 8;
2333
0
              AVI->track[AVI->aptr].audio_superindex->aIndex[j].dwSize = str2ulong ((unsigned char*)a);
2334
0
              a += 4;
2335
0
              AVI->track[AVI->aptr].audio_superindex->aIndex[j].dwDuration = str2ulong ((unsigned char*)a);
2336
0
              a += 4;
2337
2338
#ifdef DEBUG_ODML
2339
              GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] [%d] 0x%llx 0x%lx %lu\n", j,
2340
                                                      (unsigned int long)AVI->track[AVI->aptr].audio_superindex->aIndex[j].qwOffset,
2341
                                                      (unsigned long)AVI->track[AVI->aptr].audio_superindex->aIndex[j].dwSize,
2342
                                                      (unsigned long)AVI->track[AVI->aptr].audio_superindex->aIndex[j].dwDuration));
2343
#endif
2344
0
            }
2345
2346
0
            AVI->track[AVI->aptr].audio_superindex->stdindex = NULL;
2347
2348
#ifdef DEBUG_ODML
2349
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] FOURCC \"%.4s\"\n", AVI->track[AVI->aptr].audio_superindex->fcc));
2350
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] LEN \"%ld\"\n", (long)AVI->track[AVI->aptr].audio_superindex->dwSize));
2351
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] wLongsPerEntry \"%d\"\n", AVI->track[AVI->aptr].audio_superindex->wLongsPerEntry));
2352
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] bIndexSubType \"%d\"\n", AVI->track[AVI->aptr].audio_superindex->bIndexSubType));
2353
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] bIndexType \"%d\"\n", AVI->track[AVI->aptr].audio_superindex->bIndexType));
2354
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] nEntriesInUse \"%ld\"\n", (long)AVI->track[AVI->aptr].audio_superindex->nEntriesInUse));
2355
            GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] dwChunkId \"%.4s\"\n", AVI->track[AVI->aptr].audio_superindex->dwChunkId[0]));
2356
#endif
2357
2358
0
          }
2359
0
          i += 8;
2360
0
        }
2361
0
        else if((strnicmp((char*)hdrl_data+i,"JUNK",4) == 0) ||
2362
0
                (strnicmp((char*)hdrl_data+i,"strn",4) == 0) ||
2363
0
                (strnicmp((char*)hdrl_data+i,"vprp",4) == 0)) {
2364
0
          i += 8;
2365
          // do not reset lasttag
2366
0
        } else
2367
0
        {
2368
0
          i += 8;
2369
0
          lasttag = 0;
2370
0
        }
2371
        //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] adding %ld bytes\n", (int int)n));
2372
2373
0
        i += (u32) n;
2374
0
      }
2375
2376
0
  gf_free(hdrl_data);
2377
0
  hdrl_data = NULL;
2378
2379
0
  if(!vids_strh_seen || !vids_strf_seen) ERR_EXIT(AVI_ERR_NO_VIDS)
2380
2381
0
    AVI->video_tag[0] = AVI->video_strn/10 + '0';
2382
0
  AVI->video_tag[1] = AVI->video_strn%10 + '0';
2383
0
  AVI->video_tag[2] = 'd';
2384
0
  AVI->video_tag[3] = 'b';
2385
2386
  /* Audio tag is set to "99wb" if no audio present */
2387
0
  if(!AVI->track[0].a_chans) AVI->track[0].audio_strn = 99;
2388
2389
0
  {
2390
0
    int tk=0;
2391
0
    for(j=0; j<AVI->anum+1 && tk<AVI_MAX_TRACKS; ++j) {
2392
0
      if (j == AVI->video_strn) continue;
2393
0
      AVI->track[tk].audio_tag[0] = j/10 + '0';
2394
0
      AVI->track[tk].audio_tag[1] = j%10 + '0';
2395
0
      AVI->track[tk].audio_tag[2] = 'w';
2396
0
      AVI->track[tk].audio_tag[3] = 'b';
2397
0
      ++tk;
2398
0
    }
2399
0
  }
2400
2401
0
  gf_fseek(AVI->fdes,AVI->movi_start,SEEK_SET);
2402
2403
0
  if(!getIndex) return(0);
2404
2405
  /* if the file has an idx1, check if this is relative
2406
     to the start of the file or to the start of the movi list */
2407
2408
0
  idx_type = 0;
2409
2410
0
  if(AVI->idx)
2411
0
  {
2412
0
    s64 pos, len;
2413
2414
    /* Search the first videoframe in the idx1 and look where
2415
       it is in the file */
2416
2417
0
    for(i=0; i<AVI->n_idx; i++)
2418
0
      if( strnicmp((char *)AVI->idx[i],(char *)AVI->video_tag,3)==0 ) break;
2419
0
    if(i>=AVI->n_idx) ERR_EXIT(AVI_ERR_NO_VIDS)
2420
2421
0
      pos = str2ulong(AVI->idx[i]+ 8);
2422
0
    len = str2ulong(AVI->idx[i]+12);
2423
2424
0
    gf_fseek(AVI->fdes,pos,SEEK_SET);
2425
0
    if(avi_read(AVI->fdes,data,8)!=8) ERR_EXIT(AVI_ERR_READ)
2426
0
      if( strnicmp(data,(char *)AVI->idx[i],4)==0 && str2ulong((unsigned char *)data+4)==len )
2427
0
      {
2428
0
        idx_type = 1; /* Index from start of file */
2429
0
      }
2430
0
      else
2431
0
      {
2432
0
        gf_fseek(AVI->fdes,pos+AVI->movi_start-4,SEEK_SET);
2433
0
        if(avi_read(AVI->fdes,data,8)!=8) ERR_EXIT(AVI_ERR_READ)
2434
0
          if( strnicmp(data,(char *)AVI->idx[i],4)==0 && str2ulong((unsigned char *)data+4)==len )
2435
0
          {
2436
0
            idx_type = 2; /* Index from start of movi list */
2437
0
          }
2438
0
      }
2439
    /* idx_type remains 0 if neither of the two tests above succeeds */
2440
0
  }
2441
2442
2443
0
  if(idx_type == 0 && !AVI->is_opendml && !AVI->total_frames)
2444
0
  {
2445
    /* we must search through the file to get the index */
2446
2447
0
    gf_fseek(AVI->fdes, AVI->movi_start, SEEK_SET);
2448
2449
0
    AVI->n_idx = 0;
2450
2451
0
    while(1)
2452
0
    {
2453
0
      if( avi_read(AVI->fdes,data,8) != 8 ) break;
2454
0
      n = str2ulong((unsigned char *)data+4);
2455
2456
      /* The movi list may contain sub-lists, ignore them */
2457
2458
0
      if(strnicmp(data,"LIST",4)==0)
2459
0
      {
2460
0
        gf_fseek(AVI->fdes,4,SEEK_CUR);
2461
0
        continue;
2462
0
      }
2463
2464
      /* Check if we got a tag ##db, ##dc or ##wb */
2465
2466
0
      if( ( (data[2]=='d' || data[2]=='D') &&
2467
0
              (data[3]=='b' || data[3]=='B' || data[3]=='c' || data[3]=='C') )
2468
0
              || ( (data[2]=='w' || data[2]=='W') &&
2469
0
                   (data[3]=='b' || data[3]=='B') ) )
2470
0
      {
2471
0
        u64 __pos = gf_ftell(AVI->fdes) - 8;
2472
0
        avi_add_index_entry(AVI,(unsigned char *)data,0,__pos,n);
2473
0
      }
2474
2475
0
      gf_fseek(AVI->fdes,PAD_EVEN(n),SEEK_CUR);
2476
0
    }
2477
0
    idx_type = 1;
2478
0
  }
2479
2480
  // ************************
2481
  // OPENDML
2482
  // ************************
2483
2484
  // read extended index chunks
2485
0
  if (AVI->is_opendml) {
2486
0
    u64 offset = 0;
2487
0
    hdrl_len = 4+4+2+1+1+4+4+8+4;
2488
0
    char *en, *chunk_start;
2489
0
    int k = 0;
2490
0
    u32 audtr = 0;
2491
0
    u32 nrEntries = 0;
2492
2493
0
    AVI->video_index = NULL;
2494
2495
0
    nvi = 0;
2496
0
    for(audtr=0; audtr<AVI->anum; ++audtr) {
2497
0
      nai[audtr] = 0;
2498
0
      tot[audtr] = 0;
2499
0
    }
2500
2501
    // ************************
2502
    // VIDEO
2503
    // ************************
2504
2505
0
    for (j=0; j<AVI->video_superindex->nEntriesInUse; j++) {
2506
2507
      // read from file
2508
0
      u32 chunk_size = (u32) (AVI->video_superindex->aIndex[j].dwSize+hdrl_len);
2509
0
      if (!chunk_size || chunk_size < 28)
2510
0
        continue;
2511
0
      chunk_start = en = (char*) gf_malloc(chunk_size);
2512
2513
0
      if (gf_fseek(AVI->fdes, AVI->video_superindex->aIndex[j].qwOffset, SEEK_SET) == (u64)-1) {
2514
0
        gf_free(chunk_start);
2515
0
        continue;
2516
0
      }
2517
2518
0
      if (avi_read(AVI->fdes, en, (u32) (AVI->video_superindex->aIndex[j].dwSize+hdrl_len) ) <= 0) {
2519
0
        gf_free(chunk_start);
2520
0
        continue;
2521
0
      }
2522
2523
0
      nrEntries = str2ulong((unsigned char*)en + 12);
2524
#ifdef DEBUG_ODML
2525
      //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] [%d:0] Video nrEntries %ld\n", j, nrEntries));
2526
#endif
2527
0
      offset = str2ullong((unsigned char*)en + 20);
2528
2529
      // skip header
2530
0
      en += hdrl_len;
2531
0
      nvi += nrEntries;
2532
2533
0
      if (nvi <= 0 || nvi >= GF_INT_MAX/sizeof(video_index_entry)) {
2534
0
        GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] invalid nvi value %d\n", nvi));
2535
0
        gf_free(chunk_start);
2536
0
        ERR_EXIT(AVI_ERR_READ);
2537
0
      }
2538
2539
0
      AVI->video_index = (video_index_entry *) gf_realloc (AVI->video_index, nvi * sizeof (video_index_entry));
2540
2541
0
      if (!AVI->video_index) {
2542
0
        GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] out of mem (size = %ld)\n", nvi * sizeof (video_index_entry)));
2543
0
        gf_free(chunk_start);
2544
0
        ERR_EXIT(AVI_ERR_NO_MEM);
2545
0
      }
2546
2547
0
      while (k < nvi) {
2548
2549
0
        if (en-chunk_start+8 > chunk_size)
2550
0
          break;
2551
2552
0
        AVI->video_index[k].pos = offset + str2ulong((unsigned char*)en);
2553
0
        en += 4;
2554
0
        AVI->video_index[k].len = str2ulong_len((unsigned char*)en);
2555
0
        AVI->video_index[k].key = str2ulong_key((unsigned char*)en);
2556
0
        en += 4;
2557
2558
        // completely empty chunk
2559
0
        if (AVI->video_index[k].pos-offset == 0 && AVI->video_index[k].len == 0) {
2560
0
          k--;
2561
0
          nvi--;
2562
0
        }
2563
2564
#ifdef DEBUG_ODML
2565
        /*
2566
        GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] [%d] POS 0x%llX len=%d key=%s offset (%llx) (%ld)\n", k,
2567
          AVI->video_index[k].pos,
2568
          (int)AVI->video_index[k].len,
2569
          AVI->video_index[k].key?"yes":"no ", offset,
2570
          AVI->video_superindex->aIndex[j].dwSize));
2571
          */
2572
#endif
2573
2574
0
        k++;
2575
0
      }
2576
2577
0
      gf_free(chunk_start);
2578
0
    }
2579
2580
0
    AVI->video_frames = nvi;
2581
    // this should deal with broken 'rec ' odml files.
2582
0
    if (AVI->video_frames == 0) {
2583
0
      AVI->is_opendml=0;
2584
0
      goto multiple_riff;
2585
0
    }
2586
2587
    // ************************
2588
    // AUDIO
2589
    // ************************
2590
2591
0
    for(audtr=0; audtr<AVI->anum; ++audtr) {
2592
2593
0
      k = 0;
2594
0
      if (!AVI->track[audtr].audio_superindex) {
2595
0
        GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] (%s) cannot read audio index for track %d\n", __FILE__, audtr));
2596
0
        continue;
2597
0
      }
2598
0
      for (j=0; j<AVI->track[audtr].audio_superindex->nEntriesInUse; j++) {
2599
2600
        // read from file
2601
0
        u32 chunk_size = (u32) (AVI->track[audtr].audio_superindex->aIndex[j].dwSize+hdrl_len);
2602
0
        if (!chunk_size || chunk_size < 28)
2603
0
          continue;
2604
0
        chunk_start = en = (char*)gf_malloc(chunk_size);
2605
2606
0
        if (gf_fseek(AVI->fdes, AVI->track[audtr].audio_superindex->aIndex[j].qwOffset, SEEK_SET) == (u64)-1) {
2607
0
          gf_free(chunk_start);
2608
0
          continue;
2609
0
        }
2610
2611
0
        if (avi_read(AVI->fdes, en, (u32) (AVI->track[audtr].audio_superindex->aIndex[j].dwSize+hdrl_len)) <= 0) {
2612
0
          gf_free(chunk_start);
2613
0
          continue;
2614
0
        }
2615
2616
0
        nrEntries = str2ulong((unsigned char*)en + 12);
2617
        //if (nrEntries > 50) nrEntries = 2; // XXX
2618
#ifdef DEBUG_ODML
2619
        //GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] [%d:%d] Audio nrEntries %ld\n", j, audtr, nrEntries));
2620
#endif
2621
0
        offset = str2ullong((unsigned char*)en + 20);
2622
2623
        // skip header
2624
0
        en += hdrl_len;
2625
0
        nai[audtr] += nrEntries;
2626
2627
0
        if (nai[audtr] <= 0 || nai[audtr] >= GF_INT_MAX/sizeof(audio_index_entry)) {
2628
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] invalid nai value %d\n", nai[audtr]));
2629
0
          gf_free(chunk_start);
2630
0
          ERR_EXIT(AVI_ERR_READ);
2631
0
        }
2632
2633
0
        AVI->track[audtr].audio_index = (audio_index_entry *) gf_realloc (AVI->track[audtr].audio_index, nai[audtr] * sizeof (audio_index_entry));
2634
2635
0
        if (!AVI->track[audtr].audio_index) {
2636
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] out of mem (size = %ld)\n", nai[audtr] * sizeof (audio_index_entry)));
2637
0
          gf_free(chunk_start);
2638
0
          ERR_EXIT(AVI_ERR_NO_MEM);
2639
0
        }
2640
2641
0
        while (k < nai[audtr]) {
2642
2643
0
          if (en - chunk_start + 8 > chunk_size)
2644
0
            break;
2645
2646
0
          AVI->track[audtr].audio_index[k].pos = offset + str2ulong((unsigned char*)en);
2647
0
          en += 4;
2648
0
          AVI->track[audtr].audio_index[k].len = str2ulong_len((unsigned char*)en);
2649
0
          en += 4;
2650
0
          AVI->track[audtr].audio_index[k].tot = tot[audtr];
2651
0
          tot[audtr] += AVI->track[audtr].audio_index[k].len;
2652
2653
#ifdef DEBUG_ODML
2654
          /*
2655
          GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] [%d:%d] POS 0x%llX len=%d offset (%llx) (%ld)\n", k, audtr,
2656
            AVI->track[audtr].audio_index[k].pos,
2657
            (int)AVI->track[audtr].audio_index[k].len,
2658
            offset, AVI->track[audtr].audio_superindex->aIndex[j].dwSize));
2659
            */
2660
#endif
2661
2662
0
          ++k;
2663
0
        }
2664
2665
0
        gf_free(chunk_start);
2666
0
      }
2667
2668
0
      AVI->track[audtr].audio_chunks = nai[audtr];
2669
0
      AVI->track[audtr].audio_bytes = tot[audtr];
2670
0
    }
2671
0
  } // is opendml
2672
2673
0
  else if (AVI->total_frames && !AVI->is_opendml && idx_type==0) {
2674
2675
    // *********************
2676
    // MULTIPLE RIFF CHUNKS (and no index)
2677
    // *********************
2678
2679
0
multiple_riff:
2680
2681
0
    gf_fseek(AVI->fdes, AVI->movi_start, SEEK_SET);
2682
2683
0
    AVI->n_idx = 0;
2684
2685
0
    GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] Reconstructing index..."));
2686
2687
    // Number of frames; only one audio track supported
2688
0
    nvi = AVI->video_frames = AVI->total_frames;
2689
2690
0
    if (nvi <= 0 || nvi >= GF_INT_MAX/sizeof(video_index_entry)) {
2691
0
      GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] invalid nvi value %d\n", nvi));
2692
0
      ERR_EXIT(AVI_ERR_READ);
2693
0
    }
2694
2695
0
    nai[0] = AVI->track[0].audio_chunks = AVI->total_frames;
2696
0
    for(j=1; j<AVI->anum; ++j) AVI->track[j].audio_chunks = 0;
2697
2698
0
    AVI->video_index = (video_index_entry *) gf_malloc(nvi*sizeof(video_index_entry));
2699
2700
0
    if(AVI->video_index==0) ERR_EXIT(AVI_ERR_NO_MEM);
2701
2702
0
    for(j=0; j<AVI->anum; ++j) {
2703
0
      if(AVI->track[j].audio_chunks) {
2704
0
        if (AVI->track[j].audio_index) gf_free(AVI->track[j].audio_index);
2705
0
        AVI->track[j].audio_index = (audio_index_entry *) gf_malloc((nai[j]+1)*sizeof(audio_index_entry));
2706
0
        memset(AVI->track[j].audio_index, 0, (nai[j]+1)*(sizeof(audio_index_entry)));
2707
0
        if(AVI->track[j].audio_index==0) ERR_EXIT(AVI_ERR_NO_MEM);
2708
0
      }
2709
0
    }
2710
2711
0
    nvi = 0;
2712
0
    for(j=0; j<AVI->anum; ++j) {
2713
0
      nai[j] = 0;
2714
0
      tot[j] = 0;
2715
0
    }
2716
2717
0
    aud_chunks = AVI->total_frames;
2718
2719
0
    while(1)
2720
0
    {
2721
0
      if (nvi >= AVI->total_frames) break;
2722
2723
0
      if( avi_read(AVI->fdes,data,8) != 8 ) break;
2724
0
      n = str2ulong((unsigned char *)data+4);
2725
2726
2727
0
      j=0;
2728
2729
0
      if (aud_chunks - nai[j] -1 <= 0) {
2730
0
        aud_chunks += AVI->total_frames;
2731
0
        AVI->track[j].audio_index = (audio_index_entry *)
2732
0
                                    gf_realloc( AVI->track[j].audio_index, (aud_chunks+1)*sizeof(audio_index_entry));
2733
2734
0
        if (!AVI->track[j].audio_index) {
2735
0
          GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] Internal error in avilib -- no mem\n"));
2736
0
          AVI_errno = AVI_ERR_NO_MEM;
2737
0
          return -1;
2738
0
        }
2739
2740
0
        if (AVI->anum <= j)
2741
0
          AVI->anum = j+1;
2742
0
      }
2743
2744
      /* Check if we got a tag ##db, ##dc or ##wb */
2745
2746
      // VIDEO
2747
0
      if(
2748
0
          (data[0]=='0' || data[1]=='0') &&
2749
0
          (data[2]=='d' || data[2]=='D') &&
2750
0
          (data[3]=='b' || data[3]=='B' || data[3]=='c' || data[3]=='C') ) {
2751
2752
0
        AVI->video_index[nvi].key = 0x0;
2753
0
        AVI->video_index[nvi].pos = gf_ftell(AVI->fdes);
2754
0
        AVI->video_index[nvi].len = (u32) n;
2755
2756
        /*
2757
        GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] Frame %ld pos %"LLD" len %"LLD" key %ld\n",
2758
            nvi, AVI->video_index[nvi].pos,  AVI->video_index[nvi].len, (long)AVI->video_index[nvi].key));
2759
            */
2760
0
        nvi++;
2761
0
        gf_fseek(AVI->fdes,PAD_EVEN(n),SEEK_CUR);
2762
0
      }
2763
2764
      //AUDIO
2765
0
      else if(
2766
0
          (data[0]=='0' || data[1]=='1') &&
2767
0
          (data[2]=='w' || data[2]=='W') &&
2768
0
          (data[3]=='b' || data[3]=='B') ) {
2769
2770
2771
0
        AVI->track[j].audio_index[nai[j]].pos = gf_ftell(AVI->fdes);
2772
0
        AVI->track[j].audio_index[nai[j]].len = (u32) n;
2773
0
        AVI->track[j].audio_index[nai[j]].tot = tot[j];
2774
0
        tot[j] += AVI->track[j].audio_index[nai[j]].len;
2775
0
        nai[j]++;
2776
2777
0
        gf_fseek(AVI->fdes,PAD_EVEN(n),SEEK_CUR);
2778
0
      }
2779
0
      else {
2780
0
        gf_fseek(AVI->fdes,-4,SEEK_CUR);
2781
0
      }
2782
2783
0
    }
2784
0
    if (nvi < AVI->total_frames) {
2785
0
      GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[avilib] Uh? Some frames seems missing (%ld/%d)\n",
2786
0
              nvi,  AVI->total_frames));
2787
0
    }
2788
2789
2790
0
    AVI->video_frames = nvi;
2791
0
    AVI->track[0].audio_chunks = nai[0];
2792
2793
0
    for(j=0; j<AVI->anum; ++j) AVI->track[j].audio_bytes = tot[j];
2794
0
    GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[avilib] done. nvi=%ld nai=%ld tot=%ld\n", nvi, nai[0], tot[0]));
2795
2796
0
  } // total_frames but no indx chunk (xawtv does this)
2797
2798
0
  else
2799
2800
0
  {
2801
    // ******************
2802
    // NO OPENDML
2803
    // ******************
2804
2805
    /* Now generate the video index and audio index arrays */
2806
2807
0
    nvi = 0;
2808
0
    for(j=0; j<AVI->anum; ++j) nai[j] = 0;
2809
2810
0
    for(i=0; i<AVI->n_idx; i++) {
2811
2812
0
      if(strnicmp((char *)AVI->idx[i],AVI->video_tag,3) == 0) nvi++;
2813
2814
0
      for(j=0; j<AVI->anum; ++j) if(strnicmp((char *)AVI->idx[i], AVI->track[j].audio_tag,4) == 0) nai[j]++;
2815
0
    }
2816
2817
0
    AVI->video_frames = nvi;
2818
0
    for(j=0; j<AVI->anum; ++j) AVI->track[j].audio_chunks = nai[j];
2819
2820
2821
0
    if(AVI->video_frames==0) ERR_EXIT(AVI_ERR_NO_VIDS);
2822
0
    AVI->video_index = (video_index_entry *) gf_malloc(nvi*sizeof(video_index_entry));
2823
0
    if(AVI->video_index==0) ERR_EXIT(AVI_ERR_NO_MEM);
2824
2825
0
    for(j=0; j<AVI->anum; ++j) {
2826
0
      if(AVI->track[j].audio_chunks) {
2827
0
        if (AVI->track[j].audio_index) gf_free(AVI->track[j].audio_index);
2828
0
        AVI->track[j].audio_index = (audio_index_entry *) gf_malloc((nai[j]+1)*sizeof(audio_index_entry));
2829
0
        memset(AVI->track[j].audio_index, 0, (nai[j]+1)*(sizeof(audio_index_entry)));
2830
0
        if(AVI->track[j].audio_index==0) ERR_EXIT(AVI_ERR_NO_MEM);
2831
0
      }
2832
0
    }
2833
2834
0
    nvi = 0;
2835
0
    for(j=0; j<AVI->anum; ++j) {
2836
0
      nai[j] = 0;
2837
0
      tot[j] = 0;
2838
0
    }
2839
2840
0
    ioff = idx_type == 1 ? 8 : (u32)AVI->movi_start+4;
2841
2842
0
    for(i=0; i<AVI->n_idx; i++) {
2843
2844
      //video
2845
0
      if(strnicmp((char *)AVI->idx[i],AVI->video_tag,3) == 0) {
2846
0
        AVI->video_index[nvi].key = str2ulong(AVI->idx[i]+ 4);
2847
0
        AVI->video_index[nvi].pos = str2ulong(AVI->idx[i]+ 8)+ioff;
2848
0
        AVI->video_index[nvi].len = str2ulong(AVI->idx[i]+12);
2849
0
        nvi++;
2850
0
      }
2851
2852
      //audio
2853
0
      for(j=0; j<AVI->anum; ++j) {
2854
2855
0
        if(strnicmp((char *)AVI->idx[i],AVI->track[j].audio_tag,4) == 0) {
2856
0
          AVI->track[j].audio_index[nai[j]].pos = str2ulong(AVI->idx[i]+ 8)+ioff;
2857
0
          AVI->track[j].audio_index[nai[j]].len = str2ulong(AVI->idx[i]+12);
2858
0
          AVI->track[j].audio_index[nai[j]].tot = tot[j];
2859
0
          tot[j] += AVI->track[j].audio_index[nai[j]].len;
2860
0
          nai[j]++;
2861
0
        }
2862
0
      }
2863
0
    }
2864
2865
2866
0
    for(j=0; j<AVI->anum; ++j) AVI->track[j].audio_bytes = tot[j];
2867
2868
0
  } // is no opendml
2869
2870
  /* Reposition the file */
2871
2872
0
  gf_fseek(AVI->fdes,AVI->movi_start,SEEK_SET);
2873
0
  AVI->video_pos = 0;
2874
2875
0
  return(0);
2876
0
}
2877
2878
int AVI_video_frames(avi_t *AVI)
2879
0
{
2880
0
  return AVI->video_frames;
2881
0
}
2882
int  AVI_video_width(avi_t *AVI)
2883
0
{
2884
0
  return AVI->width;
2885
0
}
2886
int  AVI_video_height(avi_t *AVI)
2887
0
{
2888
0
  return AVI->height;
2889
0
}
2890
double AVI_frame_rate(avi_t *AVI)
2891
0
{
2892
0
  return AVI->fps;
2893
0
}
2894
char* AVI_video_compressor(avi_t *AVI)
2895
0
{
2896
0
  return AVI->compressor2;
2897
0
}
2898
2899
#if 0
2900
int AVI_max_video_chunk(avi_t *AVI)
2901
{
2902
  return AVI->max_len;
2903
}
2904
#endif
2905
2906
int AVI_audio_tracks(avi_t *AVI)
2907
0
{
2908
0
  return(AVI->anum);
2909
0
}
2910
2911
int AVI_audio_channels(avi_t *AVI)
2912
0
{
2913
0
  return AVI->track[AVI->aptr].a_chans;
2914
0
}
2915
2916
int AVI_audio_mp3rate(avi_t *AVI)
2917
0
{
2918
0
  return AVI->track[AVI->aptr].mp3rate;
2919
0
}
2920
2921
#if 0 //unused
2922
int AVI_audio_padrate(avi_t *AVI)
2923
{
2924
  return AVI->track[AVI->aptr].padrate;
2925
}
2926
#endif
2927
2928
int AVI_audio_bits(avi_t *AVI)
2929
0
{
2930
0
  return AVI->track[AVI->aptr].a_bits;
2931
0
}
2932
2933
int AVI_audio_format(avi_t *AVI)
2934
0
{
2935
0
  return AVI->track[AVI->aptr].a_fmt;
2936
0
}
2937
2938
int AVI_audio_rate(avi_t *AVI)
2939
0
{
2940
0
  return AVI->track[AVI->aptr].a_rate;
2941
0
}
2942
2943
2944
int AVI_frame_size(avi_t *AVI, int frame)
2945
0
{
2946
0
  if(AVI->mode==AVI_MODE_WRITE) {
2947
0
    AVI_errno = AVI_ERR_NOT_PERM;
2948
0
    return -1;
2949
0
  }
2950
0
  if(!AVI->video_index)         {
2951
0
    AVI_errno = AVI_ERR_NO_IDX;
2952
0
    return -1;
2953
0
  }
2954
2955
0
  if(frame < 0 || frame >= AVI->video_frames) return 0;
2956
0
  return (u32) (AVI->video_index[frame].len);
2957
0
}
2958
2959
int AVI_audio_size(avi_t *AVI, int frame)
2960
0
{
2961
0
  if(AVI->mode==AVI_MODE_WRITE) {
2962
0
    AVI_errno = AVI_ERR_NOT_PERM;
2963
0
    return -1;
2964
0
  }
2965
0
  if(!AVI->track[AVI->aptr].audio_index)         {
2966
0
    AVI_errno = AVI_ERR_NO_IDX;
2967
0
    return -1;
2968
0
  }
2969
2970
0
  if(frame < 0 || frame >= AVI->track[AVI->aptr].audio_chunks) return -1;
2971
0
  return (u32) (AVI->track[AVI->aptr].audio_index[frame].len);
2972
0
}
2973
2974
u64 AVI_get_video_position(avi_t *AVI, int frame)
2975
0
{
2976
0
  if(AVI->mode==AVI_MODE_WRITE) {
2977
0
    AVI_errno = AVI_ERR_NOT_PERM;
2978
0
    return (u64) -1;
2979
0
  }
2980
0
  if(!AVI->video_index)         {
2981
0
    AVI_errno = AVI_ERR_NO_IDX;
2982
0
    return (u64) -1;
2983
0
  }
2984
2985
0
  if(frame < 0 || frame >= AVI->video_frames) return 0;
2986
0
  return(AVI->video_index[frame].pos);
2987
0
}
2988
2989
2990
int AVI_seek_start(avi_t *AVI)
2991
0
{
2992
0
  if(AVI->mode==AVI_MODE_WRITE) {
2993
0
    AVI_errno = AVI_ERR_NOT_PERM;
2994
0
    return -1;
2995
0
  }
2996
2997
0
  gf_fseek(AVI->fdes,AVI->movi_start,SEEK_SET);
2998
0
  AVI->video_pos = 0;
2999
0
  return 0;
3000
0
}
3001
3002
int AVI_set_video_position(avi_t *AVI, int frame)
3003
0
{
3004
0
  if(AVI->mode==AVI_MODE_WRITE) {
3005
0
    AVI_errno = AVI_ERR_NOT_PERM;
3006
0
    return -1;
3007
0
  }
3008
0
  if(!AVI->video_index)         {
3009
0
    AVI_errno = AVI_ERR_NO_IDX;
3010
0
    return -1;
3011
0
  }
3012
3013
0
  if (frame < 0 ) frame = 0;
3014
0
  AVI->video_pos = frame;
3015
0
  return 0;
3016
0
}
3017
3018
#if 0 //unused
3019
int AVI_set_audio_bitrate(avi_t *AVI, int bitrate)
3020
{
3021
  if(AVI->mode==AVI_MODE_READ) {
3022
    AVI_errno = AVI_ERR_NOT_PERM;
3023
    return -1;
3024
  }
3025
3026
  AVI->track[AVI->aptr].mp3rate = bitrate;
3027
  return 0;
3028
}
3029
#endif
3030
3031
int AVI_read_frame(avi_t *AVI, u8 *vidbuf, int *keyframe)
3032
0
{
3033
0
  int n;
3034
3035
0
  if(AVI->mode==AVI_MODE_WRITE) {
3036
0
    AVI_errno = AVI_ERR_NOT_PERM;
3037
0
    return -1;
3038
0
  }
3039
0
  if(!AVI->video_index)         {
3040
0
    AVI_errno = AVI_ERR_NO_IDX;
3041
0
    return -1;
3042
0
  }
3043
3044
0
  if(AVI->video_pos < 0 || AVI->video_pos >= AVI->video_frames) return -1;
3045
0
  n = (u32) AVI->video_index[AVI->video_pos].len;
3046
3047
0
  *keyframe = (AVI->video_index[AVI->video_pos].key==0x10) ? 1:0;
3048
3049
0
  if (vidbuf == NULL) {
3050
0
    AVI->video_pos++;
3051
0
    return n;
3052
0
  }
3053
3054
0
  gf_fseek(AVI->fdes, AVI->video_index[AVI->video_pos].pos, SEEK_SET);
3055
0
  AVI->video_pos++;
3056
3057
0
  if (avi_read(AVI->fdes,vidbuf,n) != (u32) n)
3058
0
  {
3059
0
    AVI_errno = AVI_ERR_READ;
3060
0
    return -1;
3061
0
  }
3062
3063
0
  return n;
3064
0
}
3065
3066
#if 0 //unused
3067
int AVI_get_audio_position_index(avi_t *AVI)
3068
{
3069
  if(AVI->mode==AVI_MODE_WRITE) {
3070
    AVI_errno = AVI_ERR_NOT_PERM;
3071
    return -1;
3072
  }
3073
  if(!AVI->track[AVI->aptr].audio_index) {
3074
    AVI_errno = AVI_ERR_NO_IDX;
3075
    return -1;
3076
  }
3077
3078
  return (AVI->track[AVI->aptr].audio_posc);
3079
}
3080
3081
int AVI_set_audio_position_index(avi_t *AVI, int indexpos)
3082
{
3083
  if(AVI->mode==AVI_MODE_WRITE) {
3084
    AVI_errno = AVI_ERR_NOT_PERM;
3085
    return -1;
3086
  }
3087
  if(!AVI->track[AVI->aptr].audio_index)         {
3088
    AVI_errno = AVI_ERR_NO_IDX;
3089
    return -1;
3090
  }
3091
  if(indexpos > AVI->track[AVI->aptr].audio_chunks)     {
3092
    AVI_errno = AVI_ERR_NO_IDX;
3093
    return -1;
3094
  }
3095
3096
  AVI->track[AVI->aptr].audio_posc = indexpos;
3097
  AVI->track[AVI->aptr].audio_posb = 0;
3098
3099
  return 0;
3100
}
3101
#endif
3102
3103
3104
int AVI_set_audio_position(avi_t *AVI, int byte)
3105
0
{
3106
0
  int n0, n1;
3107
3108
0
  if(AVI->mode==AVI_MODE_WRITE) {
3109
0
    AVI_errno = AVI_ERR_NOT_PERM;
3110
0
    return -1;
3111
0
  }
3112
0
  if(!AVI->track[AVI->aptr].audio_index)         {
3113
0
    AVI_errno = AVI_ERR_NO_IDX;
3114
0
    return -1;
3115
0
  }
3116
3117
0
  if(byte < 0) byte = 0;
3118
3119
  /* Binary search in the audio chunks */
3120
3121
0
  n0 = 0;
3122
0
  n1 = AVI->track[AVI->aptr].audio_chunks;
3123
3124
0
  while(n0<n1-1)
3125
0
  {
3126
0
    int n = (n0+n1)/2;
3127
0
    if(AVI->track[AVI->aptr].audio_index[n].tot>(u32) byte)
3128
0
      n1 = n;
3129
0
    else
3130
0
      n0 = n;
3131
0
  }
3132
3133
0
  AVI->track[AVI->aptr].audio_posc = n0;
3134
0
  AVI->track[AVI->aptr].audio_posb = (u32) (byte - AVI->track[AVI->aptr].audio_index[n0].tot);
3135
3136
0
  return 0;
3137
0
}
3138
3139
3140
int AVI_read_audio(avi_t *AVI, u8 *audbuf, int bytes, int *continuous)
3141
0
{
3142
0
  int nr;
3143
0
  u32 todo;
3144
0
  s64 pos;
3145
3146
0
  if(AVI->mode==AVI_MODE_WRITE) {
3147
0
    AVI_errno = AVI_ERR_NOT_PERM;
3148
0
    return -1;
3149
0
  }
3150
0
  if(!AVI->track[AVI->aptr].audio_index)         {
3151
0
    AVI_errno = AVI_ERR_NO_IDX;
3152
0
    return -1;
3153
0
  }
3154
3155
0
  nr = 0; /* total number of bytes read */
3156
3157
0
  if (bytes==0) {
3158
0
    AVI->track[AVI->aptr].audio_posc++;
3159
0
    AVI->track[AVI->aptr].audio_posb = 0;
3160
0
  }
3161
3162
0
  *continuous = 1;
3163
0
  while(bytes>0)
3164
0
  {
3165
0
    s64 ret;
3166
0
    u32 left = (u32) (AVI->track[AVI->aptr].audio_index[AVI->track[AVI->aptr].audio_posc].len - AVI->track[AVI->aptr].audio_posb);
3167
0
    if(left==0)
3168
0
    {
3169
0
      if(AVI->track[AVI->aptr].audio_posc>=AVI->track[AVI->aptr].audio_chunks-1) return nr;
3170
0
      AVI->track[AVI->aptr].audio_posc++;
3171
0
      AVI->track[AVI->aptr].audio_posb = 0;
3172
0
      *continuous = 0;
3173
0
      continue;
3174
0
    }
3175
0
    if((u32)bytes<left)
3176
0
      todo = bytes;
3177
0
    else
3178
0
      todo = left;
3179
0
    pos = AVI->track[AVI->aptr].audio_index[AVI->track[AVI->aptr].audio_posc].pos + AVI->track[AVI->aptr].audio_posb;
3180
0
    gf_fseek(AVI->fdes, pos, SEEK_SET);
3181
0
    AVI->track[AVI->aptr].audio_posb += (int)todo;
3182
0
    if ( (ret = avi_read(AVI->fdes,audbuf+nr,todo)) != (s64)todo)
3183
0
    {
3184
0
      GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[avilib] avi_read returned before being done :: pos = "LLD", ret = "LLD", todo = %ld\n", pos, ret, todo));
3185
0
      AVI_errno = AVI_ERR_READ;
3186
0
      return -1;
3187
0
    }
3188
0
    bytes -= todo;
3189
0
    nr    += todo;
3190
0
  }
3191
3192
0
  return nr;
3193
0
}
3194
3195
3196
#if 0 //unused
3197
/* AVI_read_data: Special routine for reading the next audio or video chunk
3198
                  without having an index of the file. */
3199
3200
int AVI_read_data(avi_t *AVI, char *vidbuf, int max_vidbuf,
3201
                  char *audbuf, int max_audbuf,
3202
                  int *len)
3203
{
3204
3205
  /*
3206
   * Return codes:
3207
   *
3208
   *    1 = video data read
3209
   *    2 = audio data read
3210
   *    0 = reached EOF
3211
   *   -1 = video buffer too small
3212
   *   -2 = audio buffer too small
3213
   */
3214
3215
  s64 n;
3216
  char data[8];
3217
3218
  if(AVI->mode==AVI_MODE_WRITE) return 0;
3219
3220
  while(1)
3221
  {
3222
    /* Read tag and length */
3223
3224
    if( avi_read(AVI->fdes,data,8) != 8 ) return 0;
3225
3226
    /* if we got a list tag, ignore it */
3227
3228
    if(strnicmp(data,"LIST",4) == 0)
3229
    {
3230
      gf_fseek(AVI->fdes,4,SEEK_CUR);
3231
      continue;
3232
    }
3233
3234
    n = PAD_EVEN(str2ulong((unsigned char *)data+4));
3235
3236
    if(strnicmp(data,AVI->video_tag,3) == 0)
3237
    {
3238
      *len = (u32) n;
3239
      AVI->video_pos++;
3240
      if(n>max_vidbuf)
3241
      {
3242
        gf_fseek(AVI->fdes,n,SEEK_CUR);
3243
        return -1;
3244
      }
3245
      if(avi_read(AVI->fdes,vidbuf, (u32) n) != n ) return 0;
3246
      return 1;
3247
    }
3248
    else if(strnicmp(data,AVI->track[AVI->aptr].audio_tag,4) == 0)
3249
    {
3250
      *len = (u32) n;
3251
      if(n>max_audbuf)
3252
      {
3253
        gf_fseek(AVI->fdes,n,SEEK_CUR);
3254
        return -2;
3255
      }
3256
      if(avi_read(AVI->fdes,audbuf, (u32) n) != n ) return 0;
3257
      return 2;
3258
      break;
3259
    }
3260
    else if(gf_fseek(AVI->fdes,n,SEEK_CUR) == (u64) -1)  return 0;
3261
  }
3262
}
3263
3264
u64 AVI_max_size(void)
3265
{
3266
  return((u64) AVI_MAX_LEN);
3267
}
3268
#endif
3269
3270
3271
#endif /*GPAC_DISABLE_AVILIB*/