Limit the number of entires to the amount that does fit into the chunk.
[mplayer/glamo.git] / libmpdemux / aviheader.c
blobe19e3198c12707d8fb5925b708114962f21ca184
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <errno.h>
7 #include "config.h"
8 #include "mp_msg.h"
9 #include "help_mp.h"
11 #include "stream.h"
12 #include "demuxer.h"
13 #include "stheader.h"
15 #include "bswap.h"
16 #include "aviheader.h"
18 #define MIN(a,b) (((a)<(b))?(a):(b))
21 static MainAVIHeader avih;
23 extern void print_avih(MainAVIHeader *h, int verbose_level);
24 extern void print_avih_flags(MainAVIHeader *h, int verbose_level);
25 extern void print_strh(AVIStreamHeader *h, int verbose_level);
26 extern void print_wave_header(WAVEFORMATEX *h, int verbose_level);
27 extern void print_video_header(BITMAPINFOHEADER *h, int verbose_level);
28 extern void print_index(AVIINDEXENTRY *idx,int idx_size, int verbose_level);
29 extern void print_avistdindex_chunk(avistdindex_chunk *h, int verbose_level);
30 extern void print_avisuperindex_chunk(avisuperindex_chunk *h, int verbose_level);
31 extern void print_vprp(VideoPropHeader *vprp, int verbose_level);
33 static int odml_get_vstream_id(int id, unsigned char res[])
35 unsigned char *p = (unsigned char *)&id;
36 id = le2me_32(id);
38 if (p[2] == 'd') {
39 if (res) {
40 res[0] = p[0];
41 res[1] = p[1];
43 return 1;
45 return 0;
48 int avi_idx_cmp(const void *elem1,const void *elem2) {
49 register off_t a = AVI_IDX_OFFSET((AVIINDEXENTRY *)elem1);
50 register off_t b = AVI_IDX_OFFSET((AVIINDEXENTRY *)elem2);
51 return (a > b) - (b > a);
54 void read_avi_header(demuxer_t *demuxer,int index_mode){
55 sh_audio_t *sh_audio=NULL;
56 sh_video_t *sh_video=NULL;
57 int stream_id=-1;
58 int idxfix_videostream=0;
59 int idxfix_divx=0;
60 avi_priv_t* priv=demuxer->priv;
61 off_t list_end=0;
63 //---- AVI header:
64 priv->idx_size=0;
65 priv->audio_streams=0;
66 while(1){
67 int id=stream_read_dword_le(demuxer->stream);
68 unsigned chunksize,size2;
69 static int last_fccType=0;
70 char* hdr=NULL;
72 if(stream_eof(demuxer->stream)) break;
73 // Imply -forceidx if -saveidx is specified
74 if (index_file_save)
75 index_mode = 2;
77 if(id==mmioFOURCC('L','I','S','T')){
78 unsigned len=stream_read_dword_le(demuxer->stream); // list size
79 id=stream_read_dword_le(demuxer->stream); // list type
80 mp_msg(MSGT_HEADER,MSGL_DBG2,"LIST %.4s len=%u\n",(char *) &id,len);
81 if(len >= 4) {
82 len -= 4;
83 list_end=stream_tell(demuxer->stream)+((len+1)&(~1));
84 } else {
85 mp_msg(MSGT_HEADER,MSGL_WARN,MSGTR_MPDEMUX_AVIHDR_EmptyList);
86 list_end = 0;
88 mp_msg(MSGT_HEADER,MSGL_V,"list_end=0x%X\n",(int)list_end);
89 if(id==listtypeAVIMOVIE){
90 // found MOVI header
91 if(!demuxer->movi_start) demuxer->movi_start=stream_tell(demuxer->stream);
92 demuxer->movi_end=stream_tell(demuxer->stream)+len;
93 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundMovieAt,(int)demuxer->movi_start,(int)demuxer->movi_end);
94 if(demuxer->stream->end_pos>demuxer->movi_end) demuxer->movi_end=demuxer->stream->end_pos;
95 if(index_mode==-2 || index_mode==2 || index_mode==0)
96 break; // reading from non-seekable source (stdin) or forced index or no index forced
97 if(list_end>0) stream_seek(demuxer->stream,list_end); // skip movi
98 list_end=0;
100 continue;
102 size2=stream_read_dword_le(demuxer->stream);
103 mp_msg(MSGT_HEADER,MSGL_DBG2,"CHUNK %.4s len=%u\n",(char *) &id,size2);
104 chunksize=(size2+1)&(~1);
105 switch(id){
107 // Indicates where the subject of the file is archived
108 case mmioFOURCC('I','A','R','L'): hdr="Archival Location";break;
109 // Lists the artist of the original subject of the file;
110 // for example, "Michaelangelo."
111 case mmioFOURCC('I','A','R','T'): hdr="Artist";break;
112 // Lists the name of the person or organization that commissioned
113 // the subject of the file; for example "Pope Julian II."
114 case mmioFOURCC('I','C','M','S'): hdr="Commissioned";break;
115 // Provides general comments about the file or the subject
116 // of the file. If the comment is several sentences long, end each
117 // sentence with a period. Do not include new-line characters.
118 case mmioFOURCC('I','C','M','T'): hdr="Comments";break;
119 // Records the copyright information for the file; for example,
120 // "Copyright Encyclopedia International 1991." If there are multiple
121 // copyrights, separate them by semicolon followed by a space.
122 case mmioFOURCC('I','C','O','P'): hdr="Copyright";break;
123 // Describes whether an image has been cropped and, if so, how it
124 // was cropped; for example, "lower-right corner."
125 case mmioFOURCC('I','C','R','D'): hdr="Creation Date";break;
126 // Describes whether an image has been cropped and, if so, how it
127 // was cropped; for example, "lower-right corner."
128 case mmioFOURCC('I','C','R','P'): hdr="Cropped";break;
129 // Specifies the size of the original subject of the file; for
130 // example, "8.5 in h, 11 in w."
131 case mmioFOURCC('I','D','I','M'): hdr="Dimensions";break;
132 // Stores dots per inch setting of the digitizer used to
133 // produce the file, such as "300."
134 case mmioFOURCC('I','D','P','I'): hdr="Dots Per Inch";break;
135 // Stores the of the engineer who worked on the file. If there are
136 // multiple engineers, separate the names by a semicolon and a blank;
137 // for example, "Smith, John; Adams, Joe."
138 case mmioFOURCC('I','E','N','G'): hdr="Engineer";break;
139 // Describes the original work, such as "landscape,", "portrait,"
140 // "still liefe," etc.
141 case mmioFOURCC('I','G','N','R'): hdr="Genre";break;
142 // Provides a list of keywords that refer to the file or subject of the
143 // file. Separate multiple keywords with a semicolon and a blank;
144 // for example, "Seattle, aerial view; scenery."
145 case mmioFOURCC('I','K','E','Y'): hdr="Keywords";break;
146 // ILGT - Describes the changes in the lightness settings on the digitizer
147 // required to produce the file. Note that the format of this information
148 // depends on the hardware used.
149 case mmioFOURCC('I','L','G','T'): hdr="Lightness";break;
150 // IMED - Decribes the original subject of the file, such as
151 // "computer image," "drawing," "lithograph," and so on.
152 case mmioFOURCC('I','M','E','D'): hdr="Medium";break;
153 // INAM - Stores the title of the subject of the file, such as
154 // "Seattle from Above."
155 case mmioFOURCC('I','N','A','M'): hdr="Name";break;
156 // IPLT - Specifies the number of colors requested when digitizing
157 // an image, such as "256."
158 case mmioFOURCC('I','P','L','T'): hdr="Palette Setting";break;
159 // IPRD - Specifies the name of title the file was originally intended
160 // for, such as "Encyclopedia of Pacific Northwest Geography."
161 case mmioFOURCC('I','P','R','D'): hdr="Product";break;
162 // ISBJ - Decsribes the contents of the file, such as
163 // "Aerial view of Seattle."
164 case mmioFOURCC('I','S','B','J'): hdr="Subject";break;
165 // ISFT - Identifies the name of the software packages used to create the
166 // file, such as "Microsoft WaveEdit"
167 case mmioFOURCC('I','S','F','T'): hdr="Software";break;
168 // ISHP - Identifies the change in sharpness for the digitizer
169 // required to produce the file (the format depends on the hardware used).
170 case mmioFOURCC('I','S','H','P'): hdr="Sharpness";break;
171 // ISRC - Identifies the name of the person or organization who
172 // suplied the original subject of the file; for example, "Try Research."
173 case mmioFOURCC('I','S','R','C'): hdr="Source";break;
174 // ISRF - Identifies the original form of the material that was digitized,
175 // such as "slide," "paper," "map," and so on. This is not necessarily
176 // the same as IMED
177 case mmioFOURCC('I','S','R','F'): hdr="Source Form";break;
178 // ITCH - Identifies the technician who digitized the subject file;
179 // for example, "Smith, John."
180 case mmioFOURCC('I','T','C','H'): hdr="Technician";break;
181 case mmioFOURCC('I','S','M','P'): hdr="Time Code";break;
182 case mmioFOURCC('I','D','I','T'): hdr="Digitization Time";break;
184 case ckidAVIMAINHDR: // read 'avih'
185 stream_read(demuxer->stream,(char*) &avih,MIN(size2,sizeof(avih)));
186 le2me_MainAVIHeader(&avih); // swap to machine endian
187 chunksize-=MIN(size2,sizeof(avih));
188 if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_avih(&avih,MSGL_V); // else print_avih_flags(&avih,MSGL_V);
189 break;
190 case ckidSTREAMHEADER: { // read 'strh'
191 AVIStreamHeader h;
192 stream_read(demuxer->stream,(char*) &h,MIN(size2,sizeof(h)));
193 le2me_AVIStreamHeader(&h); // swap to machine endian
194 chunksize-=MIN(size2,sizeof(h));
195 ++stream_id;
196 if(h.fccType==streamtypeVIDEO){
197 sh_video=new_sh_video(demuxer,stream_id);
198 memcpy(&sh_video->video,&h,sizeof(h));
199 } else
200 if(h.fccType==streamtypeAUDIO){
201 sh_audio=new_sh_audio(demuxer,stream_id);
202 memcpy(&sh_audio->audio,&h,sizeof(h));
204 last_fccType=h.fccType;
205 if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_strh(&h,MSGL_V);
206 break; }
207 case mmioFOURCC('i', 'n', 'd', 'x'): {
208 uint32_t i;
209 unsigned msize = 0;
210 avisuperindex_chunk *s;
211 priv->suidx_size++;
212 priv->suidx = realloc(priv->suidx, priv->suidx_size * sizeof (avisuperindex_chunk));
213 s = &priv->suidx[priv->suidx_size-1];
215 chunksize-=24;
216 memcpy(s->fcc, "indx", 4);
217 s->dwSize = size2;
218 s->wLongsPerEntry = stream_read_word_le(demuxer->stream);
219 s->bIndexSubType = stream_read_char(demuxer->stream);
220 s->bIndexType = stream_read_char(demuxer->stream);
221 s->nEntriesInUse = stream_read_dword_le(demuxer->stream);
222 *(uint32_t *)s->dwChunkId = stream_read_dword_le(demuxer->stream);
223 stream_read(demuxer->stream, (char *)s->dwReserved, 3*4);
224 memset(s->dwReserved, 0, 3*4);
226 print_avisuperindex_chunk(s,MSGL_V);
228 if( ((chunksize/4)/s->wLongsPerEntry) < s->nEntriesInUse){
229 mp_msg (MSGT_HEADER, MSGL_WARN, "Broken super index chunk\n");
230 s->nEntriesInUse = (chunksize/4)/s->wLongsPerEntry;
233 // Check and fix this useless crap
234 if(s->wLongsPerEntry != sizeof (avisuperindex_entry)/4) {
235 mp_msg (MSGT_HEADER, MSGL_WARN, "Broken super index chunk size: %u\n",s->wLongsPerEntry);
236 s->wLongsPerEntry = sizeof(avisuperindex_entry)/4;
238 msize = sizeof (avisuperindex_entry) * s->nEntriesInUse;
239 s->aIndex = malloc(msize);
240 memset (s->aIndex, 0, msize);
241 s->stdidx = malloc (s->nEntriesInUse * sizeof (avistdindex_chunk));
242 memset (s->stdidx, 0, s->nEntriesInUse * sizeof (avistdindex_chunk));
244 // now the real index of indices
245 for (i=0; i<s->nEntriesInUse; i++) {
246 chunksize-=16;
247 s->aIndex[i].qwOffset = stream_read_dword_le(demuxer->stream) & 0xffffffff;
248 s->aIndex[i].qwOffset |= ((uint64_t)stream_read_dword_le(demuxer->stream) & 0xffffffff)<<32;
249 s->aIndex[i].dwSize = stream_read_dword_le(demuxer->stream);
250 s->aIndex[i].dwDuration = stream_read_dword_le(demuxer->stream);
251 mp_msg (MSGT_HEADER, MSGL_V, "ODML (%.4s): [%d] 0x%016"PRIx64" 0x%04x %u\n",
252 (s->dwChunkId), i,
253 (uint64_t)s->aIndex[i].qwOffset, s->aIndex[i].dwSize, s->aIndex[i].dwDuration);
256 break; }
257 case ckidSTREAMFORMAT: { // read 'strf'
258 if(last_fccType==streamtypeVIDEO){
259 sh_video->bih=calloc((chunksize<sizeof(BITMAPINFOHEADER))?sizeof(BITMAPINFOHEADER):chunksize,1);
260 // sh_video->bih=malloc(chunksize); memset(sh_video->bih,0,chunksize);
261 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundBitmapInfoHeader,chunksize,sizeof(BITMAPINFOHEADER));
262 stream_read(demuxer->stream,(char*) sh_video->bih,chunksize);
263 le2me_BITMAPINFOHEADER(sh_video->bih); // swap to machine endian
264 // fixup MS-RLE header (seems to be broken for <256 color files)
265 if(sh_video->bih->biCompression<=1 && sh_video->bih->biSize==40)
266 sh_video->bih->biSize=chunksize;
267 if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_video_header(sh_video->bih,MSGL_V);
268 chunksize=0;
269 // sh_video->fps=(float)sh_video->video.dwRate/(float)sh_video->video.dwScale;
270 // sh_video->frametime=(float)sh_video->video.dwScale/(float)sh_video->video.dwRate;
271 // if(demuxer->video->id==-1) demuxer->video->id=stream_id;
272 // IdxFix:
273 idxfix_videostream=stream_id;
274 switch(sh_video->bih->biCompression){
275 case mmioFOURCC('M', 'P', 'G', '4'):
276 case mmioFOURCC('m', 'p', 'g', '4'):
277 case mmioFOURCC('D', 'I', 'V', '1'):
278 idxfix_divx=3; // set index recovery mpeg4 flavour: msmpeg4v1
279 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_RegeneratingKeyfTableForMPG4V1);
280 break;
281 case mmioFOURCC('D', 'I', 'V', '3'):
282 case mmioFOURCC('d', 'i', 'v', '3'):
283 case mmioFOURCC('D', 'I', 'V', '4'):
284 case mmioFOURCC('d', 'i', 'v', '4'):
285 case mmioFOURCC('D', 'I', 'V', '5'):
286 case mmioFOURCC('d', 'i', 'v', '5'):
287 case mmioFOURCC('D', 'I', 'V', '6'):
288 case mmioFOURCC('d', 'i', 'v', '6'):
289 case mmioFOURCC('M', 'P', '4', '3'):
290 case mmioFOURCC('m', 'p', '4', '3'):
291 case mmioFOURCC('M', 'P', '4', '2'):
292 case mmioFOURCC('m', 'p', '4', '2'):
293 case mmioFOURCC('D', 'I', 'V', '2'):
294 case mmioFOURCC('A', 'P', '4', '1'):
295 idxfix_divx=1; // set index recovery mpeg4 flavour: msmpeg4v3
296 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_RegeneratingKeyfTableForDIVX3);
297 break;
298 case mmioFOURCC('D', 'I', 'V', 'X'):
299 case mmioFOURCC('d', 'i', 'v', 'x'):
300 case mmioFOURCC('D', 'X', '5', '0'):
301 case mmioFOURCC('X', 'V', 'I', 'D'):
302 case mmioFOURCC('x', 'v', 'i', 'd'):
303 case mmioFOURCC('F', 'M', 'P', '4'):
304 case mmioFOURCC('f', 'm', 'p', '4'):
305 idxfix_divx=2; // set index recovery mpeg4 flavour: generic mpeg4
306 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_RegeneratingKeyfTableForMPEG4);
307 break;
309 } else
310 if(last_fccType==streamtypeAUDIO){
311 unsigned wf_size = chunksize<sizeof(WAVEFORMATEX)?sizeof(WAVEFORMATEX):chunksize;
312 sh_audio->wf=calloc(wf_size,1);
313 // sh_audio->wf=malloc(chunksize); memset(sh_audio->wf,0,chunksize);
314 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundWaveFmt,chunksize,sizeof(WAVEFORMATEX));
315 stream_read(demuxer->stream,(char*) sh_audio->wf,chunksize);
316 le2me_WAVEFORMATEX(sh_audio->wf);
317 if (sh_audio->wf->cbSize != 0 &&
318 wf_size < sizeof(WAVEFORMATEX)+sh_audio->wf->cbSize) {
319 sh_audio->wf=realloc(sh_audio->wf, sizeof(WAVEFORMATEX)+sh_audio->wf->cbSize);
321 chunksize=0;
322 if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_wave_header(sh_audio->wf,MSGL_V);
323 ++priv->audio_streams;
324 // if(demuxer->audio->id==-1) demuxer->audio->id=stream_id;
326 break;
328 case mmioFOURCC('v', 'p', 'r', 'p'): {
329 VideoPropHeader *vprp = malloc(chunksize);
330 unsigned int i;
331 stream_read(demuxer->stream, (void*)vprp, chunksize);
332 le2me_VideoPropHeader(vprp);
333 chunksize -= sizeof(*vprp)-sizeof(vprp->FieldInfo);
334 chunksize /= sizeof(VIDEO_FIELD_DESC);
335 if (vprp->nbFieldPerFrame > chunksize) {
336 vprp->nbFieldPerFrame = chunksize;
338 chunksize = 0;
339 for (i=0; i<vprp->nbFieldPerFrame; i++) {
340 le2me_VIDEO_FIELD_DESC(&vprp->FieldInfo[i]);
342 if (sh_video) {
343 sh_video->aspect = GET_AVI_ASPECT(vprp->dwFrameAspectRatio);
345 if( mp_msg_test(MSGT_HEADER,MSGL_V) ) print_vprp(vprp,MSGL_V);
346 free(vprp);
347 break;
349 case mmioFOURCC('d', 'm', 'l', 'h'): {
350 // dmlh 00 00 00 04 frms
351 unsigned int total_frames = stream_read_dword_le(demuxer->stream);
352 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_FoundAVIV2Header, chunksize, total_frames);
353 stream_skip(demuxer->stream, chunksize-4);
354 chunksize = 0;
356 break;
357 case ckidAVINEWINDEX:
358 if(demuxer->movi_end>stream_tell(demuxer->stream))
359 demuxer->movi_end=stream_tell(demuxer->stream); // fixup movi-end
360 if(index_mode && !priv->isodml){
361 int i;
362 off_t base = 0;
363 uint32_t last_off = 0;
364 priv->idx_size=size2>>4;
365 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_ReadingIndexBlockChunksForFrames,
366 priv->idx_size,avih.dwTotalFrames, (int64_t)stream_tell(demuxer->stream));
367 priv->idx=malloc(priv->idx_size<<4);
368 // printf("\nindex to %p !!!!! (priv=%p)\n",priv->idx,priv);
369 stream_read(demuxer->stream,(char*)priv->idx,priv->idx_size<<4);
370 for (i = 0; i < priv->idx_size; i++) { // swap index to machine endian
371 AVIINDEXENTRY *entry=(AVIINDEXENTRY*)priv->idx + i;
372 le2me_AVIINDEXENTRY(entry);
374 * We (ab)use the upper word for bits 32-47 of the offset, so
375 * we'll clear them here.
376 * FIXME: AFAIK no codec uses them, but if one does it will break
378 entry->dwFlags&=0xffff;
380 chunksize-=priv->idx_size<<4;
381 if( mp_msg_test(MSGT_HEADER,MSGL_DBG2) ) print_index(priv->idx,priv->idx_size,MSGL_DBG2);
383 break;
384 /* added May 2002 */
385 case mmioFOURCC('R','I','F','F'): {
386 char riff_type[4];
388 mp_msg(MSGT_HEADER, MSGL_V, MSGTR_MPDEMUX_AVIHDR_AdditionalRIFFHdr);
389 stream_read(demuxer->stream, riff_type, sizeof riff_type);
390 if (strncmp(riff_type, "AVIX", sizeof riff_type))
391 mp_msg(MSGT_HEADER, MSGL_WARN, MSGTR_MPDEMUX_AVIHDR_WarnNotExtendedAVIHdr);
392 else {
394 * We got an extended AVI header, so we need to switch to
395 * ODML to get seeking to work, provided we got indx chunks
396 * in the header (suidx_size > 0).
398 if (priv->suidx_size > 0)
399 priv->isodml = 1;
401 chunksize = 0;
402 list_end = 0; /* a new list will follow */
403 break; }
404 case ckidAVIPADDING:
405 stream_skip(demuxer->stream, chunksize);
406 chunksize = 0;
407 break;
409 if(hdr){
410 mp_msg(MSGT_HEADER,MSGL_V,"hdr=%s size=%u\n",hdr,size2);
411 if(size2==3)
412 chunksize=1; // empty
413 else {
414 char buf[256];
415 int len=(size2<250)?size2:250;
416 stream_read(demuxer->stream,buf,len);
417 chunksize-=len;
418 buf[len]=0;
419 mp_msg(MSGT_HEADER,MSGL_V,"%-10s: %s\n",hdr,buf);
420 demux_info_add(demuxer, hdr, buf);
423 mp_msg(MSGT_HEADER,MSGL_DBG2,"list_end=0x%"PRIX64" pos=0x%"PRIX64" chunksize=0x%"PRIX64" next=0x%"PRIX64"\n",
424 (int64_t)list_end, (int64_t)stream_tell(demuxer->stream),
425 (int64_t)chunksize, (int64_t)chunksize+(int64_t)stream_tell(demuxer->stream));
426 if(list_end>0 &&
427 chunksize+stream_tell(demuxer->stream) == list_end) list_end=0;
428 if(list_end>0 && chunksize+stream_tell(demuxer->stream)>list_end){
429 mp_msg(MSGT_HEADER,MSGL_V,MSGTR_MPDEMUX_AVIHDR_BrokenChunk,chunksize,(char *) &id);
430 stream_seek(demuxer->stream,list_end);
431 list_end=0;
432 } else
433 if(chunksize>0) stream_skip(demuxer->stream,chunksize); else
434 if((int)chunksize<0) mp_msg(MSGT_HEADER,MSGL_WARN,"chunksize=%u (id=%.4s)\n",chunksize,(char *) &id);
438 if (priv->suidx_size > 0 && priv->idx_size == 0) {
440 * No NEWAVIINDEX, but we got an OpenDML index.
442 priv->isodml = 1;
445 if (priv->isodml && (index_mode==-1 || index_mode==0 || index_mode==1)) {
446 int i, j, k;
447 int safety=1000;
449 avisuperindex_chunk *cx;
450 AVIINDEXENTRY *idx;
453 if (priv->idx_size) free(priv->idx);
454 priv->idx_size = 0;
455 priv->idx_offset = 0;
456 priv->idx = NULL;
458 mp_msg(MSGT_HEADER, MSGL_INFO, MSGTR_MPDEMUX_AVIHDR_BuildingODMLidx, priv->suidx_size);
460 // read the standard indices
461 for (cx = &priv->suidx[0], i=0; i<priv->suidx_size; cx++, i++) {
462 stream_reset(demuxer->stream);
463 for (j=0; j<cx->nEntriesInUse; j++) {
464 int ret1, ret2;
465 memset(&cx->stdidx[j], 0, 32);
466 ret1 = stream_seek(demuxer->stream, (off_t)cx->aIndex[j].qwOffset);
467 ret2 = stream_read(demuxer->stream, (char *)&cx->stdidx[j], 32);
468 if (ret1 != 1 || ret2 != 32 || cx->stdidx[j].nEntriesInUse==0) {
469 // this is a broken file (probably incomplete) let the standard
470 // gen_index routine handle this
471 priv->isodml = 0;
472 priv->idx_size = 0;
473 mp_msg(MSGT_HEADER, MSGL_WARN, MSGTR_MPDEMUX_AVIHDR_BrokenODMLfile);
474 goto freeout;
477 le2me_AVISTDIDXCHUNK(&cx->stdidx[j]);
478 print_avistdindex_chunk(&cx->stdidx[j],MSGL_V);
479 priv->idx_size += cx->stdidx[j].nEntriesInUse;
480 cx->stdidx[j].aIndex = malloc(cx->stdidx[j].nEntriesInUse*sizeof(avistdindex_entry));
481 stream_read(demuxer->stream, (char *)cx->stdidx[j].aIndex,
482 cx->stdidx[j].nEntriesInUse*sizeof(avistdindex_entry));
483 for (k=0;k<cx->stdidx[j].nEntriesInUse; k++)
484 le2me_AVISTDIDXENTRY(&cx->stdidx[j].aIndex[k]);
486 cx->stdidx[j].dwReserved3 = 0;
492 * We convert the index by translating all entries into AVIINDEXENTRYs
493 * and sorting them by offset. The result should be the same index
494 * we would get with -forceidx.
497 idx = priv->idx = malloc(priv->idx_size * sizeof (AVIINDEXENTRY));
499 for (cx = priv->suidx; cx != &priv->suidx[priv->suidx_size]; cx++) {
500 avistdindex_chunk *sic;
501 for (sic = cx->stdidx; sic != &cx->stdidx[cx->nEntriesInUse]; sic++) {
502 avistdindex_entry *sie;
503 for (sie = sic->aIndex; sie != &sic->aIndex[sic->nEntriesInUse]; sie++) {
504 uint64_t off = sic->qwBaseOffset + sie->dwOffset - 8;
505 memcpy(&idx->ckid, sic->dwChunkId, 4);
506 idx->dwChunkOffset = off;
507 idx->dwFlags = (off >> 32) << 16;
508 idx->dwChunkLength = sie->dwSize & 0x7fffffff;
509 idx->dwFlags |= (sie->dwSize&0x80000000)?0x0:AVIIF_KEYFRAME; // bit 31 denotes !keyframe
510 idx++;
514 qsort(priv->idx, priv->idx_size, sizeof(AVIINDEXENTRY), avi_idx_cmp);
517 Hack to work around a "wrong" index in some divx odml files
518 (processor_burning.avi as an example)
519 They have ##dc on non keyframes but the ix00 tells us they are ##db.
520 Read the fcc of a non-keyframe vid frame and check it.
524 uint32_t id;
525 uint32_t db = 0;
526 stream_reset (demuxer->stream);
528 // find out the video stream id. I have seen files with 01db.
529 for (idx = &((AVIINDEXENTRY *)priv->idx)[0], i=0; i<priv->idx_size; i++, idx++){
530 unsigned char res[2];
531 if (odml_get_vstream_id(idx->ckid, res)) {
532 db = mmioFOURCC(res[0], res[1], 'd', 'b');
533 break;
537 // find first non keyframe
538 for (idx = &((AVIINDEXENTRY *)priv->idx)[0], i=0; i<priv->idx_size; i++, idx++){
539 if (!(idx->dwFlags & AVIIF_KEYFRAME) && idx->ckid == db) break;
541 if (i<priv->idx_size && db) {
542 stream_seek(demuxer->stream, AVI_IDX_OFFSET(idx));
543 id = stream_read_dword_le(demuxer->stream);
544 if (id && id != db) // index fcc and real fcc differ? fix it.
545 for (idx = &((AVIINDEXENTRY *)priv->idx)[0], i=0; i<priv->idx_size; i++, idx++){
546 if (!(idx->dwFlags & AVIIF_KEYFRAME) && idx->ckid == db)
547 idx->ckid = id;
552 if ( mp_msg_test(MSGT_HEADER,MSGL_DBG2) ) print_index(priv->idx, priv->idx_size,MSGL_DBG2);
554 demuxer->movi_end=demuxer->stream->end_pos;
556 freeout:
558 // free unneeded stuff
559 cx = &priv->suidx[0];
560 do {
561 for (j=0;j<cx->nEntriesInUse;j++)
562 if (cx->stdidx[j].nEntriesInUse) free(cx->stdidx[j].aIndex);
563 free(cx->stdidx);
565 } while (cx++ != &priv->suidx[priv->suidx_size-1]);
566 free(priv->suidx);
570 /* Read a saved index file */
571 if (index_file_load) {
572 FILE *fp;
573 char magic[7];
574 unsigned int i;
576 if ((fp = fopen(index_file_load, "r")) == NULL) {
577 mp_msg(MSGT_HEADER,MSGL_ERR, MSGTR_MPDEMUX_AVIHDR_CantReadIdxFile, index_file_load, strerror(errno));
578 goto gen_index;
580 fread(&magic, 6, 1, fp);
581 if (strncmp(magic, "MPIDX1", 6)) {
582 mp_msg(MSGT_HEADER,MSGL_ERR, MSGTR_MPDEMUX_AVIHDR_NotValidMPidxFile, index_file_load);
583 goto gen_index;
585 fread(&priv->idx_size, sizeof(priv->idx_size), 1, fp);
586 priv->idx=malloc(priv->idx_size*sizeof(AVIINDEXENTRY));
587 if (!priv->idx) {
588 mp_msg(MSGT_HEADER,MSGL_ERR, MSGTR_MPDEMUX_AVIHDR_FailedMallocForIdxFile, index_file_load);
589 priv->idx_size = 0;
590 goto gen_index;
593 for (i=0; i<priv->idx_size;i++) {
594 AVIINDEXENTRY *idx;
595 idx=&((AVIINDEXENTRY *)priv->idx)[i];
596 fread(idx, sizeof(AVIINDEXENTRY), 1, fp);
597 if (feof(fp)) {
598 mp_msg(MSGT_HEADER,MSGL_ERR, MSGTR_MPDEMUX_AVIHDR_PrematureEOF, index_file_load);
599 free(priv->idx);
600 priv->idx_size = 0;
601 goto gen_index;
604 fclose(fp);
605 mp_msg(MSGT_HEADER,MSGL_INFO, MSGTR_MPDEMUX_AVIHDR_IdxFileLoaded, index_file_load);
607 gen_index:
608 if(index_mode>=2 || (priv->idx_size==0 && index_mode==1)){
609 // build index for file:
610 stream_reset(demuxer->stream);
611 stream_seek(demuxer->stream,demuxer->movi_start);
613 priv->idx_pos=0;
614 priv->idx_size=0;
615 priv->idx=NULL;
617 while(1){
618 int id;
619 unsigned len;
620 off_t skip;
621 AVIINDEXENTRY* idx;
622 unsigned int c;
623 demuxer->filepos=stream_tell(demuxer->stream);
624 if(demuxer->filepos>=demuxer->movi_end && demuxer->movi_start<demuxer->movi_end) break;
625 id=stream_read_dword_le(demuxer->stream);
626 len=stream_read_dword_le(demuxer->stream);
627 if(id==mmioFOURCC('L','I','S','T') || id==mmioFOURCC('R', 'I', 'F', 'F')){
628 id=stream_read_dword_le(demuxer->stream); // list or RIFF type
629 continue;
631 if(stream_eof(demuxer->stream)) break;
632 if(!id || avi_stream_id(id)==100) goto skip_chunk; // bad ID (or padding?)
634 if(priv->idx_pos>=priv->idx_size){
635 // priv->idx_size+=32;
636 priv->idx_size+=1024; // +16kB
637 priv->idx=realloc(priv->idx,priv->idx_size*sizeof(AVIINDEXENTRY));
638 if(!priv->idx){priv->idx_pos=0; break;} // error!
640 idx=&((AVIINDEXENTRY *)priv->idx)[priv->idx_pos++];
641 idx->ckid=id;
642 idx->dwFlags=AVIIF_KEYFRAME; // FIXME
643 idx->dwFlags|=(demuxer->filepos>>16)&0xffff0000U;
644 idx->dwChunkOffset=(unsigned long)demuxer->filepos;
645 idx->dwChunkLength=len;
647 c=stream_read_dword(demuxer->stream);
649 // Fix keyframes for DivX files:
650 if(idxfix_divx)
651 if(avi_stream_id(id)==idxfix_videostream){
652 switch(idxfix_divx){
653 case 3: c=stream_read_dword(demuxer->stream)<<5; //skip 32+5 bits for m$mpeg4v1
654 case 1: if(c&0x40000000) idx->dwFlags&=~AVIIF_KEYFRAME;break; // divx 3
655 case 2: if(c==0x1B6) idx->dwFlags&=~AVIIF_KEYFRAME;break; // divx 4
659 // update status line:
660 { static off_t lastpos;
661 off_t pos;
662 off_t len=demuxer->movi_end-demuxer->movi_start;
663 if(len){
664 pos=100*(demuxer->filepos-demuxer->movi_start)/len; // %
665 } else {
666 pos=(demuxer->filepos-demuxer->movi_start)>>20; // MB
668 if(pos!=lastpos){
669 lastpos=pos;
670 mp_msg(MSGT_HEADER,MSGL_STATUS,MSGTR_MPDEMUX_AVIHDR_GeneratingIdx,
671 (unsigned long)pos, len?"%":"MB");
674 mp_dbg(MSGT_HEADER,MSGL_DBG2,"%08X %08X %.4s %08X %X\n",(unsigned int)demuxer->filepos,id,(char *) &id,(int)c,(unsigned int) idx->dwFlags);
675 #if 0
676 { unsigned char tmp[64];
677 int i;
678 stream_read(demuxer->stream,tmp,64);
679 printf("%.4s",&id);
680 for(i=0;i<64;i++) printf(" %02X",tmp[i]);
681 printf("\n");
683 #endif
684 skip_chunk:
685 skip=(len+1)&(~1UL); // total bytes in this chunk
686 stream_seek(demuxer->stream,8+demuxer->filepos+skip);
688 priv->idx_size=priv->idx_pos;
689 mp_msg(MSGT_HEADER,MSGL_INFO,MSGTR_MPDEMUX_AVIHDR_IdxGeneratedForHowManyChunks,priv->idx_size);
690 if( mp_msg_test(MSGT_HEADER,MSGL_DBG2) ) print_index(priv->idx,priv->idx_size,MSGL_DBG2);
692 /* Write generated index to a file */
693 if (index_file_save) {
694 FILE *fp;
695 unsigned int i;
697 if ((fp=fopen(index_file_save, "w")) == NULL) {
698 mp_msg(MSGT_HEADER,MSGL_ERR, MSGTR_MPDEMUX_AVIHDR_Failed2WriteIdxFile, index_file_save, strerror(errno));
699 return;
701 fwrite("MPIDX1", 6, 1, fp);
702 fwrite(&priv->idx_size, sizeof(priv->idx_size), 1, fp);
703 for (i=0; i<priv->idx_size; i++) {
704 AVIINDEXENTRY *idx = &((AVIINDEXENTRY *)priv->idx)[i];
705 fwrite(idx, sizeof(AVIINDEXENTRY), 1, fp);
707 fclose(fp);
708 mp_msg(MSGT_HEADER,MSGL_INFO, MSGTR_MPDEMUX_AVIHDR_IdxFileSaved, index_file_save);
713 #undef MIN