Update to MPlayer SVN rev 34180.
[vaapi:kinkis-mplayer.git] / libmpdemux / demux_real.c
1 /*
2  * Real parser & demuxer
3  * copyright (C) 2001 Alex Beregszaszi
4  * copyright (C) 2005, 2006 Roberto Togni
5  * based on FFmpeg's libav/rm.c
6  *
7  * audio codecs: (supported by RealPlayer8 for Linux)
8  *  DNET - RealAudio 3.0, really it's AC3 in swapped-byteorder
9  *  SIPR - SiproLab's audio codec, ACELP decoder working with MPlayer,
10  *         needs fine-tuning too :)
11  *  ATRC - RealAudio 8 (ATRAC3) - www.minidisc.org/atrac3_article.pdf,
12  *         ACM decoder uploaded, needs some fine-tuning to work
13  *         -> RealAudio 8
14  *  COOK/COKR - Real Cooker -> RealAudio G2
15  *
16  * video codecs: (supported by RealPlayer8 for Linux)
17  *  RV10 - H.263 based, working with libavcodec's decoder
18  *  RV20-RV40 - using RealPlayer's codec plugins
19  *
20  * This file is part of MPlayer.
21  *
22  * MPlayer is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License as published by
24  * the Free Software Foundation; either version 2 of the License, or
25  * (at your option) any later version.
26  *
27  * MPlayer is distributed in the hope that it will be useful,
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30  * GNU General Public License for more details.
31  *
32  * You should have received a copy of the GNU General Public License along
33  * with MPlayer; if not, write to the Free Software Foundation, Inc.,
34  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
35  */
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <unistd.h>
40 #include <inttypes.h>
41
42 #include "config.h"
43 #include "mp_msg.h"
44 #include "help_mp.h"
45 #include "mpbswap.h"
46 #include "libavutil/common.h"
47 #include "libavutil/intreadwrite.h"
48 #include "stream/stream.h"
49 #include "aviprint.h"
50 #include "demuxer.h"
51 #include "stheader.h"
52 #include "demux_real.h"
53
54 //#define mp_dbg(mod,lev, args... ) mp_msg_c((mod<<8)|lev, ## args )
55
56 #define MAX_STREAMS 32
57
58 static unsigned char sipr_swaps[38][2]={
59     {0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
60     {13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
61     {25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
62     {42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
63     {77,80} };
64
65 typedef struct {
66     unsigned int        timestamp;
67     int         offset;
68 //    int               packetno;
69 //    int               len; /* only filled by our index generator */
70 //    int               flags; /* only filled by our index generator */
71 } real_index_table_t;
72
73 typedef struct {
74     /* for seeking */
75     int         index_chunk_offset;
76     real_index_table_t *index_table[MAX_STREAMS];
77
78 //    int               *index_table[MAX_STREAMS];
79     int         index_table_size[MAX_STREAMS];
80     int         index_malloc_size[MAX_STREAMS];
81     int         data_chunk_offset;
82     int         num_of_packets;
83     int         current_packet;
84
85 // need for seek
86     int         audio_need_keyframe;
87     int         video_after_seek;
88
89     int         current_apacket;
90     int         current_vpacket;
91
92     // timestamp correction:
93     int64_t             kf_base;// timestamp of the prev. video keyframe
94     unsigned int        kf_pts; // timestamp of next video keyframe
95     unsigned int        a_pts;  // previous audio timestamp
96     double      v_pts;  // previous video timestamp
97     unsigned long       duration;
98
99     /* stream id table */
100 //    int               last_a_stream;
101 //    int       a_streams[MAX_STREAMS];
102 //    int               last_v_stream;
103 //    int       v_streams[MAX_STREAMS];
104
105     /**
106      * Used to demux multirate files
107      */
108     int is_multirate; ///< != 0 for multirate files
109     int str_data_offset[MAX_STREAMS]; ///< Data chunk offset for every audio/video stream
110     int audio_curpos; ///< Current file position for audio demuxing
111     int video_curpos; ///< Current file position for video demuxing
112     int a_num_of_packets; ///< Number of audio packets
113     int v_num_of_packets; ///< Number of video packets
114     int a_bitrate; ///< Audio bitrate
115     int v_bitrate; ///< Video bitrate
116     int stream_switch; ///< Flag used to switch audio/video demuxing
117
118    /**
119     * Used to reorder audio data
120     */
121     unsigned int intl_id[MAX_STREAMS]; ///< interleaver id, per stream
122     int sub_packet_size[MAX_STREAMS]; ///< sub packet size, per stream
123     int sub_packet_h[MAX_STREAMS]; ///< number of coded frames per block
124     int coded_framesize[MAX_STREAMS]; ///< coded frame size, per stream
125     int audiopk_size[MAX_STREAMS]; ///< audio packet size
126     unsigned char *audio_buf; ///< place to store reordered audio data
127     double *audio_timestamp; ///< timestamp for each audio packet
128     int sub_packet_cnt; ///< number of subpacket already received
129     int audio_filepos; ///< file position of first audio packet in block
130 } real_priv_t;
131
132 //! use at most 200 MB of memory for index, corresponds to around 25 million entries
133 #define MAX_INDEX_ENTRIES (200*1024*1024 / sizeof(real_index_table_t))
134
135 /* originally from FFmpeg */
136 static void get_str(int isbyte, demuxer_t *demuxer, char *buf, int buf_size)
137 {
138     int len;
139
140     if (isbyte)
141         len = stream_read_char(demuxer->stream);
142     else
143         len = stream_read_word(demuxer->stream);
144
145     stream_read(demuxer->stream, buf, (len > buf_size) ? buf_size : len);
146     if (len > buf_size)
147         stream_skip(demuxer->stream, len-buf_size);
148
149     mp_msg(MSGT_DEMUX, MSGL_V, "read_str: %d bytes read\n", len);
150 }
151
152 static void dump_index(demuxer_t *demuxer, int stream_id)
153 {
154     real_priv_t *priv = demuxer->priv;
155     real_index_table_t *index;
156     int i, entries;
157
158     if (!mp_msg_test(MSGT_DEMUX,MSGL_V))
159         return;
160
161     if ((unsigned)stream_id >= MAX_STREAMS)
162         return;
163
164     index = priv->index_table[stream_id];
165     entries = priv->index_table_size[stream_id];
166
167     mp_msg(MSGT_DEMUX, MSGL_V, "Index table for stream %d\n", stream_id);
168     for (i = 0; i < entries; i++)
169     {
170 #if 1
171         mp_msg(MSGT_DEMUX, MSGL_V,"i: %d, pos: %d, timestamp: %u\n", i, index[i].offset, index[i].timestamp);
172 #else
173         mp_msg(MSGT_DEMUX, MSGL_V,"packetno: %x pos: %x len: %x timestamp: %x flags: %x\n",
174             index[i].packetno, index[i].offset, index[i].len, index[i].timestamp,
175             index[i].flags);
176 #endif
177     }
178 }
179
180 static int parse_index_chunk(demuxer_t *demuxer)
181 {
182     real_priv_t *priv = demuxer->priv;
183     int origpos = stream_tell(demuxer->stream);
184     int next_header_pos = priv->index_chunk_offset;
185     int i, entries, stream_id;
186
187 read_index:
188     stream_seek(demuxer->stream, next_header_pos);
189
190     i = stream_read_dword_le(demuxer->stream);
191     if ((i == -256) || (i != MKTAG('I', 'N', 'D', 'X')))
192     {
193         mp_msg(MSGT_DEMUX, MSGL_WARN,"Something went wrong, no index chunk found on given address (%d)\n",
194             next_header_pos);
195         index_mode = -1;
196         if (i == -256)
197             stream_reset(demuxer->stream);
198         stream_seek(demuxer->stream, origpos);
199         return 0;
200         //goto end;
201     }
202
203     mp_msg(MSGT_DEMUX, MSGL_V,"Reading index table from index chunk (%d)\n",
204         next_header_pos);
205
206     i = stream_read_dword(demuxer->stream);
207     mp_msg(MSGT_DEMUX, MSGL_V,"size: %d bytes\n", i);
208
209     i = stream_read_word(demuxer->stream);
210     if (i != 0)
211         mp_msg(MSGT_DEMUX, MSGL_WARN,"Hmm, index table with unknown version (%d), please report it to MPlayer developers!\n", i);
212
213     entries = stream_read_dword(demuxer->stream);
214     mp_msg(MSGT_DEMUX, MSGL_V,"entries: %d\n", entries);
215
216     stream_id = stream_read_word(demuxer->stream);
217     mp_msg(MSGT_DEMUX, MSGL_V,"stream_id: %d\n", stream_id);
218
219     next_header_pos = stream_read_dword(demuxer->stream);
220     mp_msg(MSGT_DEMUX, MSGL_V,"next_header_pos: %d\n", next_header_pos);
221     if (entries <= 0 || entries > MAX_INDEX_ENTRIES)
222     {
223         if (next_header_pos)
224             goto read_index;
225         i = entries;
226         goto end;
227     }
228
229     priv->index_table_size[stream_id] = entries;
230     priv->index_table[stream_id] = calloc(priv->index_table_size[stream_id], sizeof(real_index_table_t));
231
232     for (i = 0; i < entries; i++)
233     {
234         stream_skip(demuxer->stream, 2); /* version */
235         priv->index_table[stream_id][i].timestamp = stream_read_dword(demuxer->stream);
236         priv->index_table[stream_id][i].offset = stream_read_dword(demuxer->stream);
237         stream_skip(demuxer->stream, 4); /* packetno */
238 //      priv->index_table[stream_id][i].packetno = stream_read_dword(demuxer->stream);
239 //      printf("Index table: Stream#%d: entry: %d: pos: %d\n",
240 //          stream_id, i, priv->index_table[stream_id][i].offset);
241     }
242
243     dump_index(demuxer, stream_id);
244
245     if (next_header_pos > 0)
246         goto read_index;
247
248 end:
249     if (i == -256)
250         stream_reset(demuxer->stream);
251     stream_seek(demuxer->stream, origpos);
252     if (i == -256)
253         return 0;
254     else
255         return 1;
256 }
257
258 #if 1
259
260 static void add_index_item(demuxer_t *demuxer, int stream_id, unsigned int timestamp, int offset)
261 {
262   if ((unsigned)stream_id < MAX_STREAMS)
263   {
264     real_priv_t *priv = demuxer->priv;
265     real_index_table_t *index;
266     if (priv->index_table_size[stream_id] >= MAX_INDEX_ENTRIES) {
267       mp_msg(MSGT_DEMUXER, MSGL_WARN, "Index too large during building\n");
268       return;
269     }
270     if (priv->index_table_size[stream_id] >= priv->index_malloc_size[stream_id])
271     {
272       if (priv->index_malloc_size[stream_id] == 0)
273         priv->index_malloc_size[stream_id] = 2048;
274       else
275         priv->index_malloc_size[stream_id] += priv->index_malloc_size[stream_id] / 2;
276       // in case we have a really large chunk...
277       if (priv->index_table_size[stream_id] >=
278             priv->index_malloc_size[stream_id])
279         priv->index_malloc_size[stream_id] =
280           priv->index_table_size[stream_id] + 1;
281       priv->index_table[stream_id] = realloc(priv->index_table[stream_id], priv->index_malloc_size[stream_id]*sizeof(priv->index_table[0][0]));
282     }
283     if (priv->index_table_size[stream_id] > 0)
284     {
285       index = &priv->index_table[stream_id][priv->index_table_size[stream_id] - 1];
286       if (index->timestamp >= timestamp || index->offset >= offset)
287         return;
288     }
289     index = &priv->index_table[stream_id][priv->index_table_size[stream_id]++];
290     index->timestamp = timestamp;
291     index->offset = offset;
292   }
293 }
294
295 static void add_index_segment(demuxer_t *demuxer, int seek_stream_id, int64_t seek_timestamp)
296 {
297   int tag, len, stream_id, flags;
298   unsigned int timestamp;
299   if (seek_timestamp != -1 && (unsigned)seek_stream_id >= MAX_STREAMS)
300     return;
301   while (1)
302   {
303     demuxer->filepos = stream_tell(demuxer->stream);
304
305     tag = stream_read_dword(demuxer->stream);
306     if (tag == MKTAG('A', 'T', 'A', 'D'))
307     {
308       stream_skip(demuxer->stream, 14);
309       continue; /* skip to next loop */
310     }
311     len = tag & 0xffff;
312     if (tag == -256 || len < 12)
313       break;
314
315     stream_id = stream_read_word(demuxer->stream);
316     timestamp = stream_read_dword(demuxer->stream);
317
318     stream_skip(demuxer->stream, 1); /* reserved */
319     flags = stream_read_char(demuxer->stream);
320
321     if (flags == -256)
322       break;
323
324     if (flags & 2)
325     {
326       add_index_item(demuxer, stream_id, timestamp, demuxer->filepos);
327       if (stream_id == seek_stream_id && timestamp >= seek_timestamp)
328       {
329         stream_seek(demuxer->stream, demuxer->filepos);
330         return;
331       }
332     }
333     // printf("Index: stream=%d packet=%d timestamp=%u len=%d flags=0x%x datapos=0x%x\n", stream_id, entries, timestamp, len, flags, index->offset);
334     /* skip data */
335     stream_skip(demuxer->stream, len-12);
336   }
337 }
338
339 static int generate_index(demuxer_t *demuxer)
340 {
341   real_priv_t *priv = demuxer->priv;
342   int origpos = stream_tell(demuxer->stream);
343   int data_pos = priv->data_chunk_offset-10;
344   int i;
345   int tag;
346
347   stream_seek(demuxer->stream, data_pos);
348   tag = stream_read_dword(demuxer->stream);
349   if (tag != MKTAG('A', 'T', 'A', 'D'))
350   {
351     mp_msg(MSGT_DEMUX, MSGL_WARN,"Something went wrong, no data chunk found on given address (%d)\n", data_pos);
352   }
353   else
354   {
355     stream_skip(demuxer->stream, 14);
356     add_index_segment(demuxer, -1, -1);
357   }
358   for (i = 0; i < MAX_STREAMS; i++)
359   {
360     if (priv->index_table_size[i] > 0)
361     {
362       dump_index(demuxer, i);
363     }
364   }
365   stream_reset(demuxer->stream);
366   stream_seek(demuxer->stream, origpos);
367   return 0;
368 }
369
370 #else
371
372 static int generate_index(demuxer_t *demuxer)
373 {
374     real_priv_t *priv = demuxer->priv;
375     int origpos = stream_tell(demuxer->stream);
376     int data_pos = priv->data_chunk_offset-10;
377     int num_of_packets = 0;
378     int i, entries = 0;
379     int len, stream_id = 0, flags;
380     unsigned int timestamp;
381     int tab_pos = 0;
382
383 read_index:
384     stream_seek(demuxer->stream, data_pos);
385
386     i = stream_read_dword_le(demuxer->stream);
387     if ((i == -256) || (i != MKTAG('D', 'A', 'T', 'A')))
388     {
389         mp_msg(MSGT_DEMUX, MSGL_WARN,"Something went wrong, no data chunk found on given address (%d)\n",
390             data_pos);
391         goto end;
392     }
393     stream_skip(demuxer->stream, 4); /* chunk size */
394     stream_skip(demuxer->stream, 2); /* version */
395
396     num_of_packets = stream_read_dword(demuxer->stream);
397     mp_msg(MSGT_DEMUX, MSGL_V,"Generating index table from raw data (pos: 0x%x) for %d packets\n",
398         data_pos, num_of_packets);
399
400     data_pos = stream_read_dword_le(demuxer->stream)-10; /* next data chunk */
401
402     for (i = 0; i < MAX_STREAMS; i++)
403     {
404     priv->index_table_size[i] = num_of_packets;
405     priv->index_table[i] = calloc(priv->index_table_size[i], sizeof(real_index_table_t));
406 //    priv->index_table[stream_id] = realloc(priv->index_table[stream_id],
407 //      priv->index_table_size[stream_id] * sizeof(real_index_table_t));
408     }
409
410     tab_pos = 0;
411
412 //    memset(priv->index_table_size, 0, sizeof(int)*MAX_STREAMS);
413 //    memset(priv->index_table, 0, sizeof(real_index_table_t)*MAX_STREAMS);
414
415     while (tab_pos < num_of_packets)
416     {
417     i = stream_read_char(demuxer->stream);
418     if (i == -256)
419         goto end;
420     stream_skip(demuxer->stream, 1);
421 //    stream_skip(demuxer->stream, 2); /* version */
422
423     len = stream_read_word(demuxer->stream);
424     stream_id = stream_read_word(demuxer->stream);
425     timestamp = stream_read_dword(demuxer->stream);
426
427     stream_skip(demuxer->stream, 1); /* reserved */
428     flags = stream_read_char(demuxer->stream);
429
430     i = tab_pos;
431
432 //    priv->index_table_size[stream_id] = i;
433 //    if (priv->index_table[stream_id] == NULL)
434 //      priv->index_table[stream_id] = malloc(priv->index_table_size[stream_id] * sizeof(real_index_table_t));
435 //    else
436 //      priv->index_table[stream_id] = realloc(priv->index_table[stream_id],
437 //          priv->index_table_size[stream_id] * sizeof(real_index_table_t));
438
439     priv->index_table[stream_id][i].timestamp = timestamp;
440     priv->index_table[stream_id][i].offset = stream_tell(demuxer->stream)-12;
441     priv->index_table[stream_id][i].len = len;
442     priv->index_table[stream_id][i].packetno = entries;
443     priv->index_table[stream_id][i].flags = flags;
444
445     tab_pos++;
446
447     /* skip data */
448     stream_skip(demuxer->stream, len-12);
449     }
450     dump_index(demuxer, stream_id);
451     if (data_pos)
452         goto read_index;
453
454 end:
455     if (i == -256)
456         stream_reset(demuxer->stream);
457     stream_seek(demuxer->stream, origpos);
458     if (i == -256)
459         return 0;
460     else
461         return 1;
462 }
463 #endif
464
465
466 static int real_check_file(demuxer_t* demuxer)
467 {
468     real_priv_t *priv;
469     int c;
470
471     mp_msg(MSGT_DEMUX,MSGL_V,"Checking for REAL\n");
472
473     c = stream_read_dword_le(demuxer->stream);
474     if (c == -256)
475         return 0; /* EOF */
476     if (c != MKTAG('.', 'R', 'M', 'F'))
477         return 0; /* bad magic */
478
479     priv = calloc(1, sizeof(real_priv_t));
480     demuxer->priv = priv;
481
482     return DEMUXER_TYPE_REAL;
483 }
484
485 #define SKIP_BITS(n) buffer<<=n
486 #define SHOW_BITS(n) ((buffer)>>(32-(n)))
487
488 double real_fix_timestamp(unsigned char *buf, unsigned int timestamp, unsigned int format, int64_t *kf_base, int *kf_pts, double *pts){
489   double v_pts;
490   unsigned char *s = buf + 1 + (*buf+1)*8;
491   uint32_t buffer= (s[0]<<24) + (s[1]<<16) + (s[2]<<8) + s[3];
492   unsigned int kf=timestamp;
493   int pict_type;
494   unsigned int orig_kf;
495
496   if(format==mmioFOURCC('R','V','3','0') || format==mmioFOURCC('R','V','4','0')){
497     if(format==mmioFOURCC('R','V','3','0')){
498       SKIP_BITS(3);
499       pict_type= SHOW_BITS(2);
500       SKIP_BITS(2 + 7);
501     }else{
502       SKIP_BITS(1);
503       pict_type= SHOW_BITS(2);
504       SKIP_BITS(2 + 7 + 3);
505     }
506     orig_kf=
507     kf= SHOW_BITS(13);  //    kf= 2*SHOW_BITS(12);
508 //    if(pict_type==0)
509     if(pict_type<=1){
510       // I frame, sync timestamps:
511       *kf_base=(int64_t)timestamp-kf;
512       mp_msg(MSGT_DEMUX, MSGL_DBG2,"\nTS: base=%08"PRIX64"\n",*kf_base);
513       kf=timestamp;
514     } else {
515       // P/B frame, merge timestamps:
516       int64_t tmp=(int64_t)timestamp-*kf_base;
517       kf|=tmp&(~0x1fff);        // combine with packet timestamp
518       if(kf<tmp-4096) kf+=8192; else // workaround wrap-around problems
519       if(kf>tmp+4096) kf-=8192;
520       kf+=*kf_base;
521     }
522     if(pict_type != 3){ // P || I  frame -> swap timestamps
523         unsigned int tmp=kf;
524         kf=*kf_pts;
525         *kf_pts=tmp;
526 //      if(kf<=tmp) kf=0;
527     }
528     mp_msg(MSGT_DEMUX, MSGL_DBG2,"\nTS: %08X -> %08X (%04X) %d %02X %02X %02X %02X %5u\n",timestamp,kf,orig_kf,pict_type,s[0],s[1],s[2],s[3],pts?kf-(unsigned int)(*pts*1000.0):0);
529   }
530     v_pts=kf*0.001f;
531 //    if(pts && (v_pts<*pts || !kf)) v_pts=*pts+frametime;
532     if(pts) *pts=v_pts;
533     return v_pts;
534 }
535
536 typedef struct dp_hdr_s {
537     uint32_t chunks;    // number of chunks
538     uint32_t timestamp; // timestamp from packet header
539     uint32_t len;       // length of actual data
540     uint32_t chunktab;  // offset to chunk offset array
541 } dp_hdr_t;
542
543 static void queue_video_packet(real_priv_t *priv, demux_stream_t *ds, demux_packet_t *dp)
544 {
545     dp_hdr_t hdr = *(dp_hdr_t*)dp->buffer;
546     unsigned char *tmp = malloc(8*(1+hdr.chunks));
547     memcpy(tmp, dp->buffer+hdr.chunktab, 8*(1+hdr.chunks));
548     memmove(dp->buffer+1+8*(1+hdr.chunks), dp->buffer+sizeof(dp_hdr_t), hdr.len);
549     memcpy(dp->buffer+1, tmp, 8*(1+hdr.chunks));
550     *dp->buffer = (uint8_t)hdr.chunks;
551     free(tmp);
552
553     if(priv->video_after_seek){
554         priv->kf_base = 0;
555         priv->kf_pts = hdr.timestamp;
556         priv->video_after_seek = 0;
557     }
558     if(hdr.len >= 3)  /* this check may be useless */
559         dp->pts = real_fix_timestamp(dp->buffer, hdr.timestamp,
560                                      ((sh_video_t *)ds->sh)->format,
561                                      &priv->kf_base, &priv->kf_pts,
562                                      &priv->v_pts);
563     ds_add_packet(ds, dp);
564 }
565
566 // return value:
567 //     0 = EOF or no stream found
568 //     1 = successfully read a packet
569 static int demux_real_fill_buffer(demuxer_t *demuxer, demux_stream_t *dsds)
570 {
571     real_priv_t *priv = demuxer->priv;
572     demux_stream_t *ds = NULL;
573     int len;
574     unsigned int timestamp;
575     int stream_id;
576 #ifdef CRACK_MATRIX
577     int i;
578 #endif
579     int flags;
580     int version;
581     int reserved;
582     demux_packet_t *dp;
583     int x, sps, cfs, sph, spc, w;
584     int audioreorder_getnextpk = 0;
585
586   // Don't demux video if video codec init failed
587   if (demuxer->video->id >= 0 && !demuxer->video->sh)
588     demuxer->video->id = -2;
589
590   while(!stream_eof(demuxer->stream)){
591
592     /* Handle audio/video demxing switch for multirate files (non-interleaved) */
593     if (priv->is_multirate && priv->stream_switch) {
594         if (priv->current_apacket >= priv->index_table_size[demuxer->audio->id])
595             demuxer->audio->eof = 1;
596         if (priv->current_vpacket >= priv->index_table_size[demuxer->video->id])
597             demuxer->video->eof = 1;
598         if (demuxer->audio->eof && demuxer->video->eof)
599             return 0;
600         else if (!demuxer->audio->eof && demuxer->video->eof)
601             stream_seek(demuxer->stream, priv->audio_curpos); // Get audio
602         else if (demuxer->audio->eof && !demuxer->video->eof)
603             stream_seek(demuxer->stream, priv->video_curpos); // Get video
604         else if (priv->index_table[demuxer->audio->id][priv->current_apacket].timestamp <
605             priv->index_table[demuxer->video->id][priv->current_vpacket].timestamp)
606             stream_seek(demuxer->stream, priv->audio_curpos); // Get audio
607         else
608             stream_seek(demuxer->stream, priv->video_curpos); // Get video
609         priv->stream_switch = 0;
610     }
611
612     demuxer->filepos = stream_tell(demuxer->stream);
613     version = stream_read_word(demuxer->stream); /* version */
614     len = stream_read_word(demuxer->stream);
615     if ((version==0x4441) && (len==0x5441)) { // new data chunk
616         mp_msg(MSGT_DEMUX,MSGL_INFO,"demux_real: New data chunk is coming!!!\n");
617     if (priv->is_multirate)
618         return 0; // EOF
619         stream_skip(demuxer->stream,14);
620         demuxer->filepos = stream_tell(demuxer->stream);
621         version = stream_read_word(demuxer->stream); /* version */
622         len = stream_read_word(demuxer->stream);
623     } else if ((version == 0x494e) && (len == 0x4458)) {
624         mp_msg(MSGT_DEMUX,MSGL_V,"demux_real: Found INDX chunk. EOF.\n");
625         demuxer->stream->eof=1;
626         return 0;
627     }
628
629
630     if (len == -256){ /* EOF */
631 //      printf("len==-256!\n");
632         return 0;
633     }
634     if (len < 12){
635         mp_msg(MSGT_DEMUX, MSGL_V,"%08X: packet v%d len=%d  \n",(int)demuxer->filepos,(int)version,(int)len);
636         mp_msg(MSGT_DEMUX, MSGL_WARN,"bad packet len (%d)\n", len);
637         if ((unsigned)demuxer->video->id < MAX_STREAMS) {
638             if (priv->current_vpacket + 1 < priv->index_table_size[demuxer->video->id]) {
639                 stream_seek(demuxer->stream, priv->index_table[demuxer->video->id][++priv->current_vpacket].offset);
640             }
641         } else if ((unsigned)demuxer->audio->id < MAX_STREAMS) {
642             if (priv->current_apacket + 1 < priv->index_table_size[demuxer->audio->id]) {
643                 stream_seek(demuxer->stream, priv->index_table[demuxer->audio->id][++priv->current_apacket].offset);
644             }
645         }
646         continue; //goto loop;
647     }
648
649     stream_id = stream_read_word(demuxer->stream);
650     timestamp = stream_read_dword(demuxer->stream);
651     reserved = stream_read_char(demuxer->stream);
652     flags = stream_read_char(demuxer->stream);
653     /* flags:           */
654     /*  0x1 - reliable  */
655     /*  0x2 - keyframe  */
656
657     if (version == 1) {
658         int tmp;
659         tmp = stream_read_char(demuxer->stream);
660         mp_msg(MSGT_DEMUX, MSGL_DBG2,"Version: %d, skipped byte is %d\n", version, tmp);
661         len--;
662     }
663
664     if (flags & 2)
665       add_index_item(demuxer, stream_id, timestamp, demuxer->filepos);
666
667 //    printf("%08X: packet v%d len=%4d  id=%d  pts=%6d  rvd=%d  flags=%d  \n",
668 //      (int)demuxer->filepos,(int)version,(int)len, stream_id,
669 //      (int) timestamp, reserved, flags);
670
671     mp_dbg(MSGT_DEMUX,MSGL_DBG2,  "\npacket#%d: pos: 0x%0x, len: %d, id: %d, pts: %u, flags: %x rvd:%d\n",
672         priv->current_packet, (int)demuxer->filepos, len, stream_id, timestamp, flags, reserved);
673
674     priv->current_packet++;
675     len -= 12;
676
677 //    printf("s_id=%d  aid=%d  vid=%d  \n",stream_id,demuxer->audio->id,demuxer->video->id);
678
679     /* check stream_id: */
680
681     if(demuxer->audio->id==stream_id){
682         if (priv->audio_need_keyframe == 1&& flags != 0x2)
683                 goto discard;
684 got_audio:
685         ds=demuxer->audio;
686         mp_dbg(MSGT_DEMUX,MSGL_DBG2, "packet is audio (id: %d)\n", stream_id);
687
688         if (flags & 2) {
689             priv->sub_packet_cnt = 0;
690             audioreorder_getnextpk = 0;
691         }
692
693         // parse audio chunk:
694         {
695 #ifdef CRACK_MATRIX
696             int spos=stream_tell(demuxer->stream);
697             static int cnt=0;
698             static int cnt2=CRACK_MATRIX;
699 #endif
700             if (((sh_audio_t *)ds->sh)->format == mmioFOURCC('M', 'P', '4', 'A')) {
701                 uint16_t sub_packet_lengths[16], sub_packets, i;
702                 int totlen = 0;
703                 /* AAC in Real: several AAC frames in one Real packet. */
704                 /* Second byte, upper four bits: number of AAC frames */
705                 /* next n * 2 bytes: length of the AAC frames in bytes, BE */
706                 if (len < 2)
707                     goto discard;
708                 sub_packets = (stream_read_word(demuxer->stream) & 0xf0) >> 4;
709                 if (len < 2 * sub_packets)
710                     goto discard;
711                 for (i = 0; i < sub_packets; i++)
712                     totlen += sub_packet_lengths[i] = stream_read_word(demuxer->stream);
713                 if (len < totlen )
714                     goto discard;
715                 for (i = 0; i < sub_packets; i++) {
716                     demux_packet_t *dp = new_demux_packet(sub_packet_lengths[i]);
717                     stream_read(demuxer->stream, dp->buffer, sub_packet_lengths[i]);
718                     if (priv->a_pts != timestamp)
719                         dp->pts = timestamp / 1000.0;
720                     priv->a_pts = timestamp;
721                     dp->pos = demuxer->filepos;
722                     ds_add_packet(ds, dp);
723                 }
724                 return 1;
725             }
726         if ((priv->intl_id[stream_id] == mmioFOURCC('I', 'n', 't', '4')) ||
727             (priv->intl_id[stream_id] == mmioFOURCC('g', 'e', 'n', 'r')) ||
728             (priv->intl_id[stream_id] == mmioFOURCC('s', 'i', 'p', 'r'))) {
729             sps = priv->sub_packet_size[stream_id];
730             sph = priv->sub_packet_h[stream_id];
731             cfs = priv->coded_framesize[stream_id];
732             w = priv->audiopk_size[stream_id];
733             spc = priv->sub_packet_cnt;
734             switch (priv->intl_id[stream_id]) {
735                 case mmioFOURCC('I', 'n', 't', '4'):
736                     if (len < cfs * sph/2)
737                         goto discard;
738                     for (x = 0; x < sph / 2; x++)
739                         stream_read(demuxer->stream, priv->audio_buf + x * 2 * w + spc * cfs, cfs);
740                     break;
741                 case mmioFOURCC('g', 'e', 'n', 'r'):
742                     if (len < w)
743                         goto discard;
744                     for (x = 0; x < w / sps; x++)
745                         stream_read(demuxer->stream, priv->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) +
746                                     (spc >> 1)), sps);
747                     break;
748                 case mmioFOURCC('s', 'i', 'p', 'r'):
749                     if (len < w)
750                         goto discard;
751                     stream_read(demuxer->stream, priv->audio_buf + spc * w, w);
752                     if (spc == sph - 1) {
753                         int n;
754                         int bs = sph * w * 2 / 96;  // nibbles per subpacket
755                         // Perform reordering
756                         for(n=0; n < 38; n++) {
757                             int j;
758                             int i = bs * sipr_swaps[n][0];
759                             int o = bs * sipr_swaps[n][1];
760                             // swap nibbles of block 'i' with 'o'      TODO: optimize
761                             for(j = 0;j < bs; j++) {
762                                 int x = (i & 1) ? (priv->audio_buf[i >> 1] >> 4) : (priv->audio_buf[i >> 1] & 0x0F);
763                                 int y = (o & 1) ? (priv->audio_buf[o >> 1] >> 4) : (priv->audio_buf[o >> 1] & 0x0F);
764                                 if(o & 1)
765                                     priv->audio_buf[o >> 1] = (priv->audio_buf[o >> 1] & 0x0F) | (x << 4);
766                                 else
767                                     priv->audio_buf[o >> 1] = (priv->audio_buf[o >> 1] & 0xF0) | x;
768                                 if(i & 1)
769                                     priv->audio_buf[i >> 1] = (priv->audio_buf[i >> 1] & 0x0F) | (y << 4);
770                                 else
771                                     priv->audio_buf[i >> 1] = (priv->audio_buf[i >> 1] & 0xF0) | y;
772                                 ++i; ++o;
773                             }
774                         }
775                     }
776                     break;
777             }
778             priv->audio_need_keyframe = 0;
779             priv->audio_timestamp[priv->sub_packet_cnt] = (priv->a_pts==timestamp) ? MP_NOPTS_VALUE : (timestamp/1000.0);
780             priv->a_pts = timestamp;
781             if (priv->sub_packet_cnt == 0)
782                 priv->audio_filepos = demuxer->filepos;
783             if (++(priv->sub_packet_cnt) < sph)
784                 audioreorder_getnextpk = 1;
785             else {
786                 int apk_usize = ((sh_audio_t*)ds->sh)->wf->nBlockAlign;
787                 audioreorder_getnextpk = 0;
788                 priv->sub_packet_cnt = 0;
789                 // Release all the audio packets
790                 for (x = 0; x < sph*w/apk_usize; x++) {
791                     dp = new_demux_packet(apk_usize);
792                     memcpy(dp->buffer, priv->audio_buf + x * apk_usize, apk_usize);
793                     /* Put timestamp only on packets that correspond to original audio packets in file */
794                     if (x * apk_usize % w == 0)
795                         dp->pts = priv->audio_timestamp[x * apk_usize / w];
796                     dp->pos = priv->audio_filepos; // all equal
797                     dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
798                     ds_add_packet(ds, dp);
799                 }
800             }
801         } else { // No interleaving
802             dp = new_demux_packet(len);
803             stream_read(demuxer->stream, dp->buffer, len);
804
805 #ifdef CRACK_MATRIX
806             mp_msg(MSGT_DEMUX, MSGL_V,"*** audio block len=%d\n",len);
807             { // HACK - used for reverse engineering the descrambling matrix
808                 FILE* f=fopen("test.rm","r+");
809                 fseek(f,spos,SEEK_SET);
810                 ++cnt;
811 //                  for(i=0;i<len;i++) dp->buffer[i]=i/0x12;
812 //                  for(i=0;i<len;i++) dp->buffer[i]=i;
813 //                  for(i=0;i<len;i++) dp->buffer[i]=cnt;
814 //                  for(i=0;i<len;i++) dp->buffer[i]=cnt<<4;
815                     for(i=0;i<len;i++) dp->buffer[i]=(i==cnt2) ? (cnt+16*(8+cnt)) : 0;
816                 if(cnt==6){ cnt=0; ++cnt2; }
817                 fwrite(dp->buffer, len, 1, f);
818                 fclose(f);
819                 if(cnt2>0x150) *((int*)NULL)=1; // sig11 :)
820             }
821 #endif
822 #if 0
823             if( ((sh_audio_t *)ds->sh)->format == 0x2000) {
824                 // if DNET, swap bytes, as DNET is byte-swapped AC3:
825                 char *ptr = dp->buffer;
826                 int i;
827                 for (i = 0; i < len; i += 2)
828                 {
829                     const char tmp = ptr[0];
830                     ptr[0] = ptr[1];
831                     ptr[1] = tmp;
832                     ptr += 2;
833                 }
834             }
835 #endif
836             if (priv->audio_need_keyframe == 1) {
837                 priv->audio_need_keyframe = 0;
838             } else if(priv->a_pts != timestamp)
839                 dp->pts = timestamp/1000.0;
840             priv->a_pts=timestamp;
841             dp->pos = demuxer->filepos;
842             dp->flags = (flags & 0x2) ? 0x10 : 0;
843             ds_add_packet(ds, dp);
844
845         } // codec_id check, codec default case
846         }
847 // we will not use audio index if we use -idx and have a video
848         if(((!demuxer->video->sh && index_mode == 2) || priv->is_multirate) && (unsigned)demuxer->audio->id < MAX_STREAMS) {
849                 while (priv->current_apacket + 1 < priv->index_table_size[demuxer->audio->id] &&
850                        timestamp > priv->index_table[demuxer->audio->id][priv->current_apacket].timestamp) {
851                         priv->current_apacket += 1;
852                         priv->stream_switch = 1;
853                 }
854                 if (priv->stream_switch)
855                         priv->audio_curpos = stream_tell(demuxer->stream);
856         }
857
858     // If we're reordering audio packets and we need more data get it
859     if (audioreorder_getnextpk)
860         continue;
861
862         return 1;
863     }
864
865     if(demuxer->video->id==stream_id){
866 got_video:
867         ds=demuxer->video;
868         mp_dbg(MSGT_DEMUX,MSGL_DBG2, "packet is video (id: %d)\n", stream_id);
869
870         // parse video chunk:
871         {
872             // we need a more complicated, 2nd level demuxing, as the video
873             // frames are stored fragmented in the video chunks :(
874             sh_video_t *sh_video = ds->sh;
875             demux_packet_t *dp;
876             unsigned vpkg_header, vpkg_length, vpkg_offset;
877             int vpkg_seqnum=-1;
878             int vpkg_subseq=0;
879
880             while(len>2){
881                 dp_hdr_t* dp_hdr;
882                 unsigned char* dp_data;
883                 uint8_t* extra;
884
885 //              printf("xxx len=%d  \n",len);
886
887                 // read packet header
888                 // bit 7: 1=last block in block chain
889                 // bit 6: 1=short header (only one block?)
890                 vpkg_header=stream_read_char(demuxer->stream); --len;
891                 mp_dbg(MSGT_DEMUX,MSGL_DBG2, "hdr: %02X (len=%d) ",vpkg_header,len);
892
893                 if (0x40==(vpkg_header&0xc0)) {
894                     // seems to be a very short header
895                     // 2 bytes, purpose of the second byte yet unknown
896                     int bummer;
897                     bummer=stream_read_char(demuxer->stream); --len;
898                     mp_dbg(MSGT_DEMUX,MSGL_DBG2,  "%02X",bummer);
899                     vpkg_offset=0;
900                     vpkg_length=len;
901                 } else {
902
903                     if (0==(vpkg_header&0x40)) {
904                         // sub-seqnum (bits 0-6: number of fragment. bit 7: ???)
905                         vpkg_subseq=stream_read_char(demuxer->stream);
906                         --len;
907                         mp_dbg(MSGT_DEMUX,MSGL_DBG2,  "subseq: %02X ",vpkg_subseq);
908                         vpkg_subseq&=0x7f;
909                     }
910
911                     // size of the complete packet
912                     // bit 14 is always one (same applies to the offset)
913                     vpkg_length=stream_read_word(demuxer->stream);
914                     len-=2;
915                     mp_dbg(MSGT_DEMUX,MSGL_DBG2, "l: %02X %02X ",vpkg_length>>8,vpkg_length&0xff);
916                     if (!(vpkg_length&0xC000)) {
917                         vpkg_length<<=16;
918                         vpkg_length|=(uint16_t)stream_read_word(demuxer->stream);
919                         mp_dbg(MSGT_DEMUX,MSGL_DBG2, "l+: %02X %02X ",(vpkg_length>>8)&0xff,vpkg_length&0xff);
920                         len-=2;
921                     } else
922                     vpkg_length&=0x3fff;
923
924                     // offset of the following data inside the complete packet
925                     // Note: if (hdr&0xC0)==0x80 then offset is relative to the
926                     // _end_ of the packet, so it's equal to fragment size!!!
927                     vpkg_offset=stream_read_word(demuxer->stream);
928                     len-=2;
929                     mp_dbg(MSGT_DEMUX,MSGL_DBG2, "o: %02X %02X ",vpkg_offset>>8,vpkg_offset&0xff);
930                     if (!(vpkg_offset&0xC000)) {
931                         vpkg_offset<<=16;
932                         vpkg_offset|=(uint16_t)stream_read_word(demuxer->stream);
933                         mp_dbg(MSGT_DEMUX,MSGL_DBG2, "o+: %02X %02X ",(vpkg_offset>>8)&0xff,vpkg_offset&0xff);
934                         len-=2;
935                     } else
936                     vpkg_offset&=0x3fff;
937
938                     vpkg_seqnum=stream_read_char(demuxer->stream); --len;
939                     mp_dbg(MSGT_DEMUX,MSGL_DBG2, "seq: %02X ",vpkg_seqnum);
940                 }
941                 mp_dbg(MSGT_DEMUX,MSGL_DBG2, "\n");
942                 mp_dbg(MSGT_DEMUX,MSGL_DBG2, "blklen=%d\n", len);
943                 mp_msg(MSGT_DEMUX,MSGL_DBG2, "block: hdr=0x%0x, len=%d, offset=%d, seqnum=%d\n",
944                     vpkg_header, vpkg_length, vpkg_offset, vpkg_seqnum);
945
946                 if(ds->asf_packet){
947                     dp=ds->asf_packet;
948                     dp_hdr=(dp_hdr_t*)dp->buffer;
949                     dp_data=dp->buffer+sizeof(dp_hdr_t);
950                     extra=dp->buffer+dp_hdr->chunktab;
951                     mp_dbg(MSGT_DEMUX,MSGL_DBG2, "we have an incomplete packet (oldseq=%d new=%d)\n",ds->asf_seq,vpkg_seqnum);
952                     // we have an incomplete packet:
953                     if(ds->asf_seq!=vpkg_seqnum){
954                         // this fragment is for new packet, close the old one
955                         mp_msg(MSGT_DEMUX,MSGL_DBG2, "closing probably incomplete packet, len: %d  \n",dp->len);
956                         queue_video_packet(priv, ds, dp);
957                         ds->asf_packet=NULL;
958                     } else {
959                         // append data to it!
960                         ++dp_hdr->chunks;
961                         mp_msg(MSGT_DEMUX,MSGL_DBG2,"[chunks=%d  subseq=%d]\n",dp_hdr->chunks,vpkg_subseq);
962                         if(dp_hdr->chunktab+8*(1+dp_hdr->chunks)>dp->len){
963                             // increase buffer size, this should not happen!
964                             mp_msg(MSGT_DEMUX,MSGL_WARN, "chunktab buffer too small!!!!!\n");
965                             dp->len=dp_hdr->chunktab+8*(4+dp_hdr->chunks);
966                             dp->buffer=realloc(dp->buffer,dp->len+MP_INPUT_BUFFER_PADDING_SIZE);
967                             memset(dp->buffer + dp->len, 0, MP_INPUT_BUFFER_PADDING_SIZE);
968                             // re-calc pointers:
969                             dp_hdr=(dp_hdr_t*)dp->buffer;
970                             dp_data=dp->buffer+sizeof(dp_hdr_t);
971                             extra=dp->buffer+dp_hdr->chunktab;
972                         }
973                         AV_WL32(extra + 8*dp_hdr->chunks + 0, 1);
974                         AV_WL32(extra + 8*dp_hdr->chunks + 4, dp_hdr->len);
975                         if(0x80==(vpkg_header&0xc0)){
976                             // last fragment!
977                             if(dp_hdr->len!=vpkg_length-vpkg_offset)
978                                 mp_msg(MSGT_DEMUX,MSGL_V,"warning! assembled.len=%d  frag.len=%d  total.len=%d  \n",dp->len,vpkg_offset,vpkg_length-vpkg_offset);
979                             if (vpkg_offset > dp->len - sizeof(dp_hdr_t) - dp_hdr->len) vpkg_offset = dp->len - sizeof(dp_hdr_t) - dp_hdr->len;
980                             stream_read(demuxer->stream, dp_data+dp_hdr->len, vpkg_offset);
981                             if((dp_data[dp_hdr->len]&0x20) && (sh_video->format==0x30335652)) --dp_hdr->chunks; else
982                             dp_hdr->len+=vpkg_offset;
983                             len-=vpkg_offset;
984                             mp_dbg(MSGT_DEMUX,MSGL_DBG2, "fragment (%d bytes) appended, %d bytes left\n",vpkg_offset,len);
985                             // we know that this is the last fragment -> we can close the packet!
986                             queue_video_packet(priv, ds, dp);
987                             ds->asf_packet=NULL;
988                             // continue parsing
989                             continue;
990                         }
991                         // non-last fragment:
992                         if(dp_hdr->len!=vpkg_offset)
993                             mp_msg(MSGT_DEMUX,MSGL_V,"warning! assembled.len=%d  offset=%d  frag.len=%d  total.len=%d  \n",dp->len,vpkg_offset,len,vpkg_length);
994                         if (len > dp->len - sizeof(dp_hdr_t) - dp_hdr->len) len = dp->len - sizeof(dp_hdr_t) - dp_hdr->len;
995                         stream_read(demuxer->stream, dp_data+dp_hdr->len, len);
996                         if((dp_data[dp_hdr->len]&0x20) && (sh_video->format==0x30335652)) --dp_hdr->chunks; else
997                         dp_hdr->len+=len;
998                         len=0;
999                         break; // no more fragments in this chunk!
1000                     }
1001                 }
1002                 // create new packet!
1003                 dp = new_demux_packet(sizeof(dp_hdr_t)+vpkg_length+8*(1+2*(vpkg_header&0x3F)));
1004                 // the timestamp seems to be in milliseconds
1005                 dp->pos = demuxer->filepos;
1006                 dp->flags = (flags & 0x2) ? 0x10 : 0;
1007                 ds->asf_seq = vpkg_seqnum;
1008                 dp_hdr=(dp_hdr_t*)dp->buffer;
1009                 dp_hdr->chunks=0;
1010                 dp_hdr->timestamp=timestamp;
1011                 dp_hdr->chunktab=sizeof(dp_hdr_t)+vpkg_length;
1012                 dp_data=dp->buffer+sizeof(dp_hdr_t);
1013                 extra=dp->buffer+dp_hdr->chunktab;
1014                 AV_WL32(extra, 1); AV_WL32(extra + 4, 0); // offset of the first chunk
1015                 if(0x00==(vpkg_header&0xc0)){
1016                     // first fragment:
1017                     if (len > dp->len - sizeof(dp_hdr_t)) len = dp->len - sizeof(dp_hdr_t);
1018                     dp_hdr->len=len;
1019                     stream_read(demuxer->stream, dp_data, len);
1020                     ds->asf_packet=dp;
1021                     len=0;
1022                     break;
1023                 }
1024                 // whole packet (not fragmented):
1025                 if (vpkg_length > len) {
1026                     mp_msg(MSGT_DEMUX, MSGL_WARN,"\n******** WARNING: vpkg_length=%i > len=%i ********\n", vpkg_length, len);
1027                     /*
1028                      * To keep the video stream rolling, we need to break
1029                      * here. We shouldn't touch len to make sure rest of the
1030                      * broken packet is skipped.
1031                      */
1032                     break;
1033                 }
1034                 dp_hdr->len=vpkg_length; len-=vpkg_length;
1035                 stream_read(demuxer->stream, dp_data, vpkg_length);
1036                 queue_video_packet(priv, ds, dp);
1037
1038             } // while(len>0)
1039
1040             if(len){
1041                 mp_msg(MSGT_DEMUX, MSGL_WARN,"\n******** !!!!!!!! BUG!! len=%d !!!!!!!!!!! ********\n",len);
1042                 if(len>0) stream_skip(demuxer->stream, len);
1043             }
1044         }
1045         if ((unsigned)demuxer->video->id < MAX_STREAMS) {
1046                 while (priv->current_vpacket + 1 < priv->index_table_size[demuxer->video->id] &&
1047                        timestamp > priv->index_table[demuxer->video->id][priv->current_vpacket + 1].timestamp) {
1048                         priv->current_vpacket += 1;
1049                         priv->stream_switch = 1;
1050                 }
1051                 if (priv->stream_switch)
1052                         priv->video_curpos = stream_tell(demuxer->stream);
1053         }
1054
1055         return 1;
1056     }
1057
1058 if((unsigned)stream_id<MAX_STREAMS){
1059
1060     if(demuxer->audio->id==-1 && demuxer->a_streams[stream_id]){
1061         sh_audio_t *sh = demuxer->a_streams[stream_id];
1062         demuxer->audio->id=stream_id;
1063         sh->ds=demuxer->audio;
1064         demuxer->audio->sh=sh;
1065         priv->audio_buf = calloc(priv->sub_packet_h[demuxer->audio->id], priv->audiopk_size[demuxer->audio->id]);
1066         priv->audio_timestamp = calloc(priv->sub_packet_h[demuxer->audio->id], sizeof(double));
1067         mp_msg(MSGT_DEMUX,MSGL_V,"Auto-selected RM audio ID = %d\n",stream_id);
1068         goto got_audio;
1069     }
1070
1071     if(demuxer->video->id==-1 && demuxer->v_streams[stream_id]){
1072         sh_video_t *sh = demuxer->v_streams[stream_id];
1073         demuxer->video->id=stream_id;
1074         sh->ds=demuxer->video;
1075         demuxer->video->sh=sh;
1076         mp_msg(MSGT_DEMUX,MSGL_V,"Auto-selected RM video ID = %d\n",stream_id);
1077         goto got_video;
1078     }
1079
1080 }
1081
1082     mp_msg(MSGT_DEMUX,MSGL_DBG2, "unknown stream id (%d)\n", stream_id);
1083 discard:
1084     stream_skip(demuxer->stream, len);
1085   }//    goto loop;
1086   return 0;
1087 }
1088
1089 static demuxer_t* demux_open_real(demuxer_t* demuxer)
1090 {
1091     real_priv_t* priv = demuxer->priv;
1092     int num_of_headers;
1093     int a_streams=0;
1094     int v_streams=0;
1095     int i;
1096     int header_size;
1097
1098     header_size = stream_read_dword(demuxer->stream); /* header size */
1099     mp_msg(MSGT_DEMUX,MSGL_V, "real: Header size: %d\n", header_size);
1100     i = stream_read_word(demuxer->stream); /* version */
1101     mp_msg(MSGT_DEMUX,MSGL_V, "real: Header object version: %d\n", i);
1102     if (header_size == 0x10)
1103         i = stream_read_word(demuxer->stream);
1104     else /* we should test header_size here too. */
1105         i = stream_read_dword(demuxer->stream);
1106     mp_msg(MSGT_DEMUX,MSGL_V, "real: File version: %d\n", i);
1107     num_of_headers = stream_read_dword(demuxer->stream);
1108
1109     /* parse chunks */
1110     for (i = 1; i <= num_of_headers; i++)
1111 //    for (i = 1; ; i++)
1112     {
1113         int chunk_id, chunk_pos, chunk_size;
1114
1115         chunk_pos = stream_tell(demuxer->stream);
1116         chunk_id = stream_read_dword_le(demuxer->stream);
1117         chunk_size = stream_read_dword(demuxer->stream);
1118
1119         stream_skip(demuxer->stream, 2); /* version */
1120
1121         mp_msg(MSGT_DEMUX,MSGL_V, "Chunk: %.4s (%x) (size: 0x%x, offset: 0x%x)\n",
1122             (char *)&chunk_id, chunk_id, chunk_size, chunk_pos);
1123
1124         if (chunk_id != MKTAG('D', 'A', 'T', 'A') && chunk_size < 10){
1125             mp_msg(MSGT_DEMUX,MSGL_ERR,"demux_real: invalid chunksize! (%d)\n",chunk_size);
1126             break; //return;
1127         }
1128
1129         switch(chunk_id)
1130         {
1131             case MKTAG('P', 'R', 'O', 'P'):
1132                 /* Properties header */
1133
1134                 stream_skip(demuxer->stream, 4); /* max bitrate */
1135                 stream_skip(demuxer->stream, 4); /* avg bitrate */
1136                 stream_skip(demuxer->stream, 4); /* max packet size */
1137                 stream_skip(demuxer->stream, 4); /* avg packet size */
1138                 stream_skip(demuxer->stream, 4); /* nb packets */
1139                 priv->duration = stream_read_dword(demuxer->stream)/1000; /* duration */
1140                 stream_skip(demuxer->stream, 4); /* preroll */
1141                 priv->index_chunk_offset = stream_read_dword(demuxer->stream);
1142                 mp_msg(MSGT_DEMUX,MSGL_V,"First index chunk offset: 0x%x\n", priv->index_chunk_offset);
1143                 priv->data_chunk_offset = stream_read_dword(demuxer->stream)+10;
1144                 mp_msg(MSGT_DEMUX,MSGL_V,"First data chunk offset: 0x%x\n", priv->data_chunk_offset);
1145                 stream_skip(demuxer->stream, 2); /* nb streams */
1146 #if 0
1147                 stream_skip(demuxer->stream, 2); /* flags */
1148 #else
1149                 {
1150                     int flags = stream_read_word(demuxer->stream);
1151
1152                     if (flags)
1153                     {
1154                     mp_msg(MSGT_DEMUX,MSGL_V,"Flags (%x): ", flags);
1155                     if (flags & 0x1)
1156                         mp_msg(MSGT_DEMUX,MSGL_V,"[save allowed] ");
1157                     if (flags & 0x2)
1158                         mp_msg(MSGT_DEMUX,MSGL_V,"[perfect play (more buffers)] ");
1159                     if (flags & 0x4)
1160                         mp_msg(MSGT_DEMUX,MSGL_V,"[live broadcast] ");
1161                     mp_msg(MSGT_DEMUX,MSGL_V,"\n");
1162                     }
1163                 }
1164 #endif
1165                 break;
1166             case MKTAG('C', 'O', 'N', 'T'):
1167             {
1168                 /* Content description header */
1169                 char *buf;
1170                 int len;
1171
1172                 len = stream_read_word(demuxer->stream);
1173                 if (len > 0)
1174                 {
1175                     buf = malloc(len+1);
1176                     stream_read(demuxer->stream, buf, len);
1177                     buf[len] = 0;
1178                     demux_info_add(demuxer, "title", buf);
1179                     free(buf);
1180                 }
1181
1182                 len = stream_read_word(demuxer->stream);
1183                 if (len > 0)
1184                 {
1185                     buf = malloc(len+1);
1186                     stream_read(demuxer->stream, buf, len);
1187                     buf[len] = 0;
1188                     demux_info_add(demuxer, "author", buf);
1189                     free(buf);
1190                 }
1191
1192                 len = stream_read_word(demuxer->stream);
1193                 if (len > 0)
1194                 {
1195                     buf = malloc(len+1);
1196                     stream_read(demuxer->stream, buf, len);
1197                     buf[len] = 0;
1198                     demux_info_add(demuxer, "copyright", buf);
1199                     free(buf);
1200                 }
1201
1202                 len = stream_read_word(demuxer->stream);
1203                 if (len > 0)
1204                 {
1205                     buf = malloc(len+1);
1206                     stream_read(demuxer->stream, buf, len);
1207                     buf[len] = 0;
1208                     demux_info_add(demuxer, "comment", buf);
1209                     free(buf);
1210                 }
1211                 break;
1212             }
1213             case MKTAG('M', 'D', 'P', 'R'):
1214             {
1215                 /* Media properties header */
1216                 int stream_id;
1217                 int bitrate;
1218                 int codec_data_size;
1219                 int codec_pos;
1220                 int tmp;
1221                 int len;
1222                 char *descr, *mimet = NULL;
1223
1224                 stream_id = stream_read_word(demuxer->stream);
1225                 mp_msg(MSGT_DEMUX,MSGL_V,"Found new stream (id: %d)\n", stream_id);
1226
1227                 stream_skip(demuxer->stream, 4); /* max bitrate */
1228                 bitrate = stream_read_dword(demuxer->stream); /* avg bitrate */
1229                 stream_skip(demuxer->stream, 4); /* max packet size */
1230                 stream_skip(demuxer->stream, 4); /* avg packet size */
1231                 stream_skip(demuxer->stream, 4); /* start time */
1232                 stream_skip(demuxer->stream, 4); /* preroll */
1233                 stream_skip(demuxer->stream, 4); /* duration */
1234
1235                 if ((len = stream_read_char(demuxer->stream)) > 0) {
1236                     descr = malloc(len+1);
1237                 stream_read(demuxer->stream, descr, len);
1238                     descr[len] = 0;
1239                     mp_msg(MSGT_DEMUX, MSGL_INFO,"Stream description: %s\n", descr);
1240                     free(descr);
1241                 }
1242                 if ((len = stream_read_char(demuxer->stream)) > 0) {
1243                     mimet = malloc(len+1);
1244                 stream_read(demuxer->stream, mimet, len);
1245                     mimet[len] = 0;
1246                     mp_msg(MSGT_DEMUX, MSGL_INFO,"Stream mimetype: %s\n", mimet);
1247                 }
1248
1249                 /* Type specific header */
1250                 codec_data_size = stream_read_dword(demuxer->stream);
1251                 codec_pos = stream_tell(demuxer->stream);
1252
1253 #ifdef MP_DEBUG
1254 #define stream_skip(st,siz) { int i; for(i=0;i<siz;i++) mp_msg(MSGT_DEMUX,MSGL_V," %02X",stream_read_char(st)); mp_msg(MSGT_DEMUX,MSGL_V,"\n");}
1255 #endif
1256
1257         if (!strncmp(mimet,"audio/",6)) {
1258           if (strstr(mimet,"x-pn-realaudio") || strstr(mimet,"x-pn-multirate-realaudio")) {
1259                 tmp = stream_read_dword(demuxer->stream);
1260                 if (tmp != MKTAG(0xfd, 'a', 'r', '.'))
1261                 {
1262                     mp_msg(MSGT_DEMUX,MSGL_V,"Audio: can't find .ra in codec data\n");
1263                 } else {
1264                     /* audio header */
1265                     sh_audio_t *sh = new_sh_audio(demuxer, stream_id, NULL);
1266                     char buf[128]; /* for codec name */
1267                     int frame_size;
1268                     int sub_packet_size;
1269                     int sub_packet_h;
1270                     int version;
1271                     int flavor;
1272                     int coded_frame_size;
1273                     int codecdata_length;
1274                     int i;
1275                     char *buft;
1276                     int hdr_size;
1277                     mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_AudioID, "real", stream_id);
1278                     mp_msg(MSGT_DEMUX,MSGL_V,"Found audio stream!\n");
1279                     version = stream_read_word(demuxer->stream);
1280                     mp_msg(MSGT_DEMUX,MSGL_V,"version: %d\n", version);
1281                    if (version == 3) {
1282                     stream_skip(demuxer->stream, 2);
1283                     stream_skip(demuxer->stream, 10);
1284                     stream_skip(demuxer->stream, 4);
1285                     // Name, author, (c) are also in CONT tag
1286                     if ((i = stream_read_char(demuxer->stream)) != 0) {
1287                       buft = malloc(i+1);
1288                       stream_read(demuxer->stream, buft, i);
1289                       buft[i] = 0;
1290                       demux_info_add(demuxer, "Name", buft);
1291                       free(buft);
1292                     }
1293                     if ((i = stream_read_char(demuxer->stream)) != 0) {
1294                       buft = malloc(i+1);
1295                       stream_read(demuxer->stream, buft, i);
1296                       buft[i] = 0;
1297                       demux_info_add(demuxer, "Author", buft);
1298                       free(buft);
1299                     }
1300                     if ((i = stream_read_char(demuxer->stream)) != 0) {
1301                       buft = malloc(i+1);
1302                       stream_read(demuxer->stream, buft, i);
1303                       buft[i] = 0;
1304                       demux_info_add(demuxer, "Copyright", buft);
1305                       free(buft);
1306                     }
1307                     if ((i = stream_read_char(demuxer->stream)) != 0)
1308                       mp_msg(MSGT_DEMUX,MSGL_WARN,"Last header byte is not zero!\n");
1309                     stream_skip(demuxer->stream, 1);
1310                     i = stream_read_char(demuxer->stream);
1311                     sh->format = stream_read_dword_le(demuxer->stream);
1312                     if (i != 4) {
1313                       mp_msg(MSGT_DEMUX,MSGL_WARN,"Audio FourCC size is not 4 (%d), please report to "
1314                              "MPlayer developers\n", i);
1315                       stream_skip(demuxer->stream, i - 4);
1316                     }
1317                     if (sh->format != mmioFOURCC('l','p','c','J')) {
1318                       mp_msg(MSGT_DEMUX,MSGL_WARN,"Version 3 audio with FourCC %8x, please report to "
1319                              "MPlayer developers\n", sh->format);
1320                     }
1321                     sh->channels = 1;
1322                     sh->samplesize = 16;
1323                     sh->samplerate = 8000;
1324                     frame_size = 240;
1325                     strcpy(buf, "14_4");
1326                    } else {
1327                     stream_skip(demuxer->stream, 2); // 00 00
1328                     stream_skip(demuxer->stream, 4); /* .ra4 or .ra5 */
1329                     stream_skip(demuxer->stream, 4); // ???
1330                     stream_skip(demuxer->stream, 2); /* version (4 or 5) */
1331                     hdr_size = stream_read_dword(demuxer->stream); // header size
1332                     mp_msg(MSGT_DEMUX,MSGL_V,"header size: %d\n", hdr_size);
1333                     flavor = stream_read_word(demuxer->stream);/* codec flavor id */
1334                     coded_frame_size = stream_read_dword(demuxer->stream);/* needed by codec */
1335                     mp_msg(MSGT_DEMUX,MSGL_V,"coded_frame_size: %d\n", coded_frame_size);
1336                     stream_skip(demuxer->stream, 4); // big number
1337                     stream_skip(demuxer->stream, 4); // bigger number
1338                     stream_skip(demuxer->stream, 4); // 2 || -''-
1339                     sub_packet_h = stream_read_word(demuxer->stream);
1340                     mp_msg(MSGT_DEMUX,MSGL_V,"sub_packet_h: %d\n", sub_packet_h);
1341                     frame_size = stream_read_word(demuxer->stream);
1342                     mp_msg(MSGT_DEMUX,MSGL_V,"frame_size: %d\n", frame_size);
1343                     sub_packet_size = stream_read_word(demuxer->stream);
1344                     mp_msg(MSGT_DEMUX,MSGL_V,"sub_packet_size: %d\n", sub_packet_size);
1345                     stream_skip(demuxer->stream, 2); // 0
1346
1347                     if (version == 5)
1348                         stream_skip(demuxer->stream, 6); //0,srate,0
1349
1350                     sh->samplerate = stream_read_word(demuxer->stream);
1351                     stream_skip(demuxer->stream, 2);  // 0
1352                     sh->samplesize = stream_read_word(demuxer->stream)/8;
1353                     sh->channels = stream_read_word(demuxer->stream);
1354                     mp_msg(MSGT_DEMUX,MSGL_V,"samplerate: %d, channels: %d\n",
1355                         sh->samplerate, sh->channels);
1356
1357                     if (version == 5)
1358                     {
1359                         stream_read(demuxer->stream, buf, 4);  // interleaver id
1360                         priv->intl_id[stream_id] = MKTAG(buf[0], buf[1], buf[2], buf[3]);
1361                         stream_read(demuxer->stream, buf, 4); // fourcc
1362                         buf[4] = 0;
1363                     }
1364                     else
1365                     {
1366                         /* Interleaver id */
1367                         get_str(1, demuxer, buf, sizeof(buf));
1368                         priv->intl_id[stream_id] = MKTAG(buf[0], buf[1], buf[2], buf[3]);
1369                         /* Codec FourCC */
1370                         get_str(1, demuxer, buf, sizeof(buf));
1371                     }
1372                    }
1373
1374                     /* Emulate WAVEFORMATEX struct: */
1375                     sh->wf = calloc(1, sizeof(*sh->wf));
1376                     sh->wf->nChannels = sh->channels;
1377                     sh->wf->wBitsPerSample = sh->samplesize*8;
1378                     sh->wf->nSamplesPerSec = sh->samplerate;
1379                     sh->wf->nAvgBytesPerSec = bitrate/8;
1380                     sh->wf->nBlockAlign = frame_size;
1381                     sh->wf->cbSize = 0;
1382                     sh->format = MKTAG(buf[0], buf[1], buf[2], buf[3]);
1383
1384                     switch (sh->format)
1385                     {
1386                         case MKTAG('d', 'n', 'e', 't'):
1387                             mp_msg(MSGT_DEMUX,MSGL_V,"Audio: DNET -> AC3\n");
1388 //                          sh->format = 0x2000;
1389                             break;
1390                         case MKTAG('1', '4', '_', '4'):
1391                 sh->wf->nBlockAlign = 0x14;
1392                             break;
1393
1394                         case MKTAG('2', '8', '_', '8'):
1395                             sh->wf->nBlockAlign = coded_frame_size;
1396                             break;
1397
1398                         case MKTAG('s', 'i', 'p', 'r'):
1399                         case MKTAG('a', 't', 'r', 'c'):
1400                         case MKTAG('c', 'o', 'o', 'k'):
1401                             // realaudio codec plugins - common:
1402                             stream_skip(demuxer->stream,3);  // Skip 3 unknown bytes
1403                             if (version==5)
1404                               stream_skip(demuxer->stream,1);  // Skip 1 additional unknown byte
1405                             codecdata_length=stream_read_dword(demuxer->stream);
1406                             // Check extradata len, we can't store bigger values in cbSize anyway
1407                             if ((unsigned)codecdata_length > 0xffff) {
1408                                 mp_msg(MSGT_DEMUX,MSGL_ERR,"Extradata too big (%d)\n", codecdata_length);
1409                                 goto skip_this_chunk;
1410                             }
1411                             sh->wf->cbSize = codecdata_length;
1412                             sh->wf = realloc(sh->wf, sizeof(*sh->wf)+sh->wf->cbSize);
1413                             stream_read(demuxer->stream, ((char*)(sh->wf+1)), codecdata_length); // extras
1414                 if (priv->intl_id[stream_id] == MKTAG('g', 'e', 'n', 'r'))
1415                             sh->wf->nBlockAlign = sub_packet_size;
1416                         else
1417                             sh->wf->nBlockAlign = coded_frame_size;
1418
1419                             break;
1420
1421                         case MKTAG('r', 'a', 'a', 'c'):
1422                         case MKTAG('r', 'a', 'c', 'p'):
1423                             /* This is just AAC. The two or five bytes of */
1424                             /* config data needed for libfaad are stored */
1425                             /* after the audio headers. */
1426                             stream_skip(demuxer->stream,3);  // Skip 3 unknown bytes
1427                             if (version==5)
1428                                 stream_skip(demuxer->stream,1);  // Skip 1 additional unknown byte
1429                             codecdata_length=stream_read_dword(demuxer->stream);
1430                             if (codecdata_length>=1) {
1431                                 sh->codecdata_len = codecdata_length - 1;
1432                                 sh->codecdata = calloc(sh->codecdata_len, 1);
1433                                 stream_skip(demuxer->stream, 1);
1434                                 stream_read(demuxer->stream, sh->codecdata, sh->codecdata_len);
1435                             }
1436                             sh->format = mmioFOURCC('M', 'P', '4', 'A');
1437                             break;
1438                         default:
1439                             mp_msg(MSGT_DEMUX,MSGL_V,"Audio: Unknown (%s)\n", buf);
1440                     }
1441
1442                     // Interleaver setup
1443                     priv->sub_packet_size[stream_id] = sub_packet_size;
1444                     priv->sub_packet_h[stream_id] = sub_packet_h;
1445                     priv->coded_framesize[stream_id] = coded_frame_size;
1446                     priv->audiopk_size[stream_id] = frame_size;
1447
1448                     sh->wf->wFormatTag = sh->format;
1449
1450                     mp_msg(MSGT_DEMUX,MSGL_V,"audio fourcc: %.4s (%x)\n", (char *)&sh->format, sh->format);
1451                     if ( mp_msg_test(MSGT_DEMUX,MSGL_V) )
1452                     print_wave_header(sh->wf, MSGL_V);
1453
1454                     /* Select audio stream with highest bitrate if multirate file*/
1455                     if (priv->is_multirate && ((demuxer->audio->id == -1) ||
1456                                                ((demuxer->audio->id >= 0) && priv->a_bitrate && (bitrate > priv->a_bitrate)))) {
1457                             demuxer->audio->id = stream_id;
1458                             priv->a_bitrate = bitrate;
1459                             mp_msg(MSGT_DEMUX,MSGL_DBG2,"Multirate autoselected audio id %d with bitrate %d\n", stream_id, bitrate);
1460                     }
1461
1462                     if(demuxer->audio->id==stream_id){
1463                         sh->ds=demuxer->audio;
1464                         demuxer->audio->sh=sh;
1465                 priv->audio_buf = calloc(priv->sub_packet_h[demuxer->audio->id], priv->audiopk_size[demuxer->audio->id]);
1466                 priv->audio_timestamp = calloc(priv->sub_packet_h[demuxer->audio->id], sizeof(double));
1467                     }
1468
1469                     ++a_streams;
1470
1471 #ifdef stream_skip
1472 #undef stream_skip
1473 #endif
1474                 }
1475           } else if (strstr(mimet,"X-MP3-draft-00")) {
1476                     sh_audio_t *sh = new_sh_audio(demuxer, stream_id, NULL);
1477                     mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_AudioID, "real", stream_id);
1478
1479                     /* Emulate WAVEFORMATEX struct: */
1480                     sh->wf = calloc(1, sizeof(*sh->wf));
1481                     sh->wf->nChannels = 0;//sh->channels;
1482                     sh->wf->wBitsPerSample = 16;
1483                     sh->wf->nSamplesPerSec = 0;//sh->samplerate;
1484                     sh->wf->nAvgBytesPerSec = 0;//bitrate;
1485                     sh->wf->nBlockAlign = 0;//frame_size;
1486                     sh->wf->cbSize = 0;
1487                     sh->wf->wFormatTag = sh->format = mmioFOURCC('a','d','u',0x55);
1488
1489                     if(demuxer->audio->id==stream_id){
1490                             sh->ds=demuxer->audio;
1491                             demuxer->audio->sh=sh;
1492                     }
1493
1494                     ++a_streams;
1495           } else if (strstr(mimet,"x-ralf-mpeg4")) {
1496                  mp_msg(MSGT_DEMUX,MSGL_ERR,"Real lossless audio not supported yet\n");
1497           } else if (strstr(mimet,"x-pn-encrypted-ra")) {
1498                  mp_msg(MSGT_DEMUX,MSGL_ERR,"Encrypted audio is not supported\n");
1499           } else {
1500                  mp_msg(MSGT_DEMUX,MSGL_V,"Unknown audio stream format\n");
1501                 }
1502         } else if (!strncmp(mimet,"video/",6)) {
1503           if (strstr(mimet,"x-pn-realvideo") || strstr(mimet,"x-pn-multirate-realvideo")) {
1504                 stream_skip(demuxer->stream, 4);  // VIDO length, same as codec_data_size
1505                 tmp = stream_read_dword(demuxer->stream);
1506                 if(tmp != MKTAG('O', 'D', 'I', 'V'))
1507                 {
1508                     mp_msg(MSGT_DEMUX,MSGL_V,"Video: can't find VIDO in codec data\n");
1509                 } else {
1510                     /* video header */
1511                     sh_video_t *sh = new_sh_video(demuxer, stream_id);
1512                     mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_VideoID, "real", stream_id);
1513
1514                     sh->format = stream_read_dword_le(demuxer->stream); /* fourcc */
1515                     mp_msg(MSGT_DEMUX,MSGL_V,"video fourcc: %.4s (%x)\n", (char *)&sh->format, sh->format);
1516
1517                     /* emulate BITMAPINFOHEADER */
1518                     sh->bih = calloc(1, sizeof(*sh->bih));
1519                     sh->bih->biSize = sizeof(*sh->bih);
1520                     sh->disp_w = sh->bih->biWidth = stream_read_word(demuxer->stream);
1521                     sh->disp_h = sh->bih->biHeight = stream_read_word(demuxer->stream);
1522                     sh->bih->biPlanes = 1;
1523                     sh->bih->biBitCount = 24;
1524                     sh->bih->biCompression = sh->format;
1525                     sh->bih->biSizeImage= sh->bih->biWidth*sh->bih->biHeight*3;
1526
1527                     sh->fps = (float) stream_read_word(demuxer->stream);
1528                     if (sh->fps<=0) sh->fps=24; // we probably won't even care about fps
1529                     sh->frametime = 1.0f/sh->fps;
1530
1531 #if 1
1532                     stream_skip(demuxer->stream, 4);
1533 #else
1534                     mp_msg(MSGT_DEMUX, MSGL_V,"unknown1: 0x%X  \n",stream_read_dword(demuxer->stream));
1535                     mp_msg(MSGT_DEMUX, MSGL_V,"unknown2: 0x%X  \n",stream_read_word(demuxer->stream));
1536                     mp_msg(MSGT_DEMUX, MSGL_V,"unknown3: 0x%X  \n",stream_read_word(demuxer->stream));
1537 #endif
1538 //                  if(sh->format==0x30335652 || sh->format==0x30325652 )
1539                     if(1)
1540                     {
1541                         int tmp=stream_read_word(demuxer->stream);
1542                         if(tmp>0){
1543                             sh->fps=tmp; sh->frametime = 1.0f/sh->fps;
1544                         }
1545                     } else {
1546                         int fps=stream_read_word(demuxer->stream);
1547                         mp_msg(MSGT_DEMUX, MSGL_WARN,"realvid: ignoring FPS = %d\n",fps);
1548                     }
1549                     stream_skip(demuxer->stream, 2);
1550
1551                     {
1552                             // read and store codec extradata
1553                             unsigned int cnt = codec_data_size - (stream_tell(demuxer->stream) - codec_pos);
1554                             if (cnt > 0x7fffffff - sizeof(*sh->bih)) {
1555                                 mp_msg(MSGT_DEMUX, MSGL_ERR,"Extradata too big (%u)\n", cnt);
1556                             } else  {
1557                                 sh->bih = realloc(sh->bih, sizeof(*sh->bih) + cnt);
1558                                 sh->bih->biSize += cnt;
1559                                 stream_read(demuxer->stream, ((unsigned char*)(sh->bih+1)), cnt);
1560                             }
1561                     }
1562                     if(sh->format == 0x30315652 && ((unsigned char*)(sh->bih+1))[6] == 0x30)
1563                             sh->bih->biCompression = sh->format = mmioFOURCC('R', 'V', '1', '3');
1564
1565                     /* Select video stream with highest bitrate if multirate file*/
1566                     if (priv->is_multirate && ((demuxer->video->id == -1) ||
1567                                                ((demuxer->video->id >= 0) && priv->v_bitrate && (bitrate > priv->v_bitrate)))) {
1568                             demuxer->video->id = stream_id;
1569                             priv->v_bitrate = bitrate;
1570                             mp_msg(MSGT_DEMUX,MSGL_DBG2,"Multirate autoselected video id %d with bitrate %d\n", stream_id, bitrate);
1571                     }
1572
1573                     if(demuxer->video->id==stream_id){
1574                         sh->ds=demuxer->video;
1575                         demuxer->video->sh=sh;
1576                     }
1577
1578                     ++v_streams;
1579
1580                 }
1581           } else {
1582                  mp_msg(MSGT_DEMUX,MSGL_V,"Unknown video stream format\n");
1583           }
1584         } else if (strstr(mimet,"logical-")) {
1585                  if (strstr(mimet,"fileinfo")) {
1586                      mp_msg(MSGT_DEMUX,MSGL_V,"Got a logical-fileinfo chunk\n");
1587                  } else if (strstr(mimet,"-audio") || strstr(mimet,"-video")) {
1588                     int i, stream_cnt;
1589                     int stream_list[MAX_STREAMS];
1590
1591                     priv->is_multirate = 1;
1592                     stream_skip(demuxer->stream, 4); // Length of codec data (repeated)
1593                     stream_cnt = stream_read_dword(demuxer->stream); // Get number of audio or video streams
1594                     if ((unsigned)stream_cnt >= MAX_STREAMS) {
1595                         mp_msg(MSGT_DEMUX,MSGL_ERR,"Too many streams in %s. Big troubles ahead.\n", mimet);
1596                         goto skip_this_chunk;
1597                     }
1598                     for (i = 0; i < stream_cnt; i++)
1599                         stream_list[i] = stream_read_word(demuxer->stream);
1600                     for (i = 0; i < stream_cnt; i++)
1601                         if ((unsigned)stream_list[i] >= MAX_STREAMS) {
1602                             mp_msg(MSGT_DEMUX,MSGL_ERR,"Stream id out of range: %d. Ignored.\n", stream_list[i]);
1603                             stream_skip(demuxer->stream, 4); // Skip DATA offset for broken stream
1604                         } else {
1605                             priv->str_data_offset[stream_list[i]] = stream_read_dword(demuxer->stream);
1606                             mp_msg(MSGT_DEMUX,MSGL_V,"Stream %d with DATA offset 0x%08x\n", stream_list[i], priv->str_data_offset[stream_list[i]]);
1607                         }
1608                     // Skip the rest of this chunk
1609                  } else
1610                      mp_msg(MSGT_DEMUX,MSGL_V,"Unknown logical stream\n");
1611                 }
1612                 else {
1613                     mp_msg(MSGT_DEMUX, MSGL_ERR, "Not audio/video stream or unsupported!\n");
1614                 }
1615 //              break;
1616 //          default:
1617 skip_this_chunk:
1618                 /* skip codec info */
1619                 tmp = stream_tell(demuxer->stream) - codec_pos;
1620                 mp_msg(MSGT_DEMUX,MSGL_V,"### skipping %d bytes of codec info\n", codec_data_size - tmp);
1621 #if 0
1622                 { int i;
1623                   for(i=0;i<codec_data_size - tmp;i++)
1624                       mp_msg(MSGT_DEMUX, MSGL_V," %02X",stream_read_char(demuxer->stream));
1625                   mp_msg(MSGT_DEMUX, MSGL_V,"\n");
1626                 }
1627 #else
1628                 stream_skip(demuxer->stream, codec_data_size - tmp);
1629 #endif
1630                 free (mimet);
1631                 break;
1632 //          }
1633             }
1634             case MKTAG('D', 'A', 'T', 'A'):
1635                 goto header_end;
1636             case MKTAG('I', 'N', 'D', 'X'):
1637             default:
1638                 mp_msg(MSGT_DEMUX,MSGL_V,"Unknown chunk: %x\n", chunk_id);
1639                 stream_skip(demuxer->stream, chunk_size - 10);
1640                 break;
1641         }
1642     }
1643
1644 header_end:
1645     if(priv->is_multirate) {
1646         mp_msg(MSGT_DEMUX,MSGL_V,"Selected video id %d audio id %d\n", demuxer->video->id, demuxer->audio->id);
1647         /* Perform some sanity checks to avoid checking streams id all over the code*/
1648         if (demuxer->audio->id >= MAX_STREAMS) {
1649             mp_msg(MSGT_DEMUX,MSGL_ERR,"Invalid audio stream %d. No sound will be played.\n", demuxer->audio->id);
1650             demuxer->audio->id = -2;
1651         } else if ((demuxer->audio->id >= 0) && (priv->str_data_offset[demuxer->audio->id] == 0)) {
1652             mp_msg(MSGT_DEMUX,MSGL_ERR,"Audio stream %d not found. No sound will be played.\n", demuxer->audio->id);
1653             demuxer->audio->id = -2;
1654         }
1655         if (demuxer->video->id >= MAX_STREAMS) {
1656             mp_msg(MSGT_DEMUX,MSGL_ERR,"Invalid video stream %d. No video will be played.\n", demuxer->video->id);
1657             demuxer->video->id = -2;
1658         } else if ((demuxer->video->id >= 0) && (priv->str_data_offset[demuxer->video->id] == 0)) {
1659             mp_msg(MSGT_DEMUX,MSGL_ERR,"Video stream %d not found. No video will be played.\n", demuxer->video->id);
1660             demuxer->video->id = -2;
1661         }
1662     }
1663
1664     if(priv->is_multirate && ((demuxer->video->id >= 0) || (demuxer->audio->id  >=0))) {
1665         /* If audio or video only, seek to right place and behave like standard file */
1666         if (demuxer->video->id < 0) {
1667             // Stream is audio only, or -novideo
1668             stream_seek(demuxer->stream, priv->data_chunk_offset = priv->str_data_offset[demuxer->audio->id]+10);
1669             priv->is_multirate = 0;
1670         }
1671         if (demuxer->audio->id < 0) {
1672             // Stream is video only, or -nosound
1673             stream_seek(demuxer->stream, priv->data_chunk_offset = priv->str_data_offset[demuxer->video->id]+10);
1674             priv->is_multirate = 0;
1675         }
1676     }
1677
1678   if(!priv->is_multirate) {
1679 //    printf("i=%d num_of_headers=%d   \n",i,num_of_headers);
1680     priv->num_of_packets = stream_read_dword(demuxer->stream);
1681     stream_skip(demuxer->stream, 4); /* next data header */
1682
1683     mp_msg(MSGT_DEMUX,MSGL_V,"Packets in file: %d\n", priv->num_of_packets);
1684
1685     if (priv->num_of_packets == 0)
1686         priv->num_of_packets = -10;
1687   } else {
1688         priv->audio_curpos = priv->str_data_offset[demuxer->audio->id] + 18;
1689         stream_seek(demuxer->stream, priv->str_data_offset[demuxer->audio->id]+10);
1690         priv->a_num_of_packets = stream_read_dword(demuxer->stream);
1691         priv->video_curpos = priv->str_data_offset[demuxer->video->id] + 18;
1692         stream_seek(demuxer->stream, priv->str_data_offset[demuxer->video->id]+10);
1693         priv->v_num_of_packets = stream_read_dword(demuxer->stream);
1694         priv->stream_switch = 1;
1695         /* Index required for multirate playback, force building if it's not there */
1696         /* but respect user request to force index regeneration */
1697         if (index_mode == -1)
1698             index_mode = 1;
1699     }
1700
1701
1702     priv->audio_need_keyframe = 0;
1703     priv->video_after_seek = 0;
1704
1705     switch (index_mode){
1706         case -1: // untouched
1707             if ((demuxer->stream->flags & MP_STREAM_SEEK) == MP_STREAM_SEEK &&
1708                 priv->index_chunk_offset && parse_index_chunk(demuxer))
1709             {
1710                 demuxer->seekable = 1;
1711             }
1712             break;
1713         case 1: // use (generate index)
1714             if (priv->index_chunk_offset && parse_index_chunk(demuxer))
1715             {
1716                 demuxer->seekable = 1;
1717             } else {
1718                 generate_index(demuxer);
1719                 demuxer->seekable = 1;
1720             }
1721             break;
1722         case 2: // force generating index
1723             generate_index(demuxer);
1724             demuxer->seekable = 1;
1725             break;
1726         default: // do nothing
1727             break;
1728     }
1729
1730     // detect streams:
1731     if(demuxer->video->id==-1 && v_streams>0){
1732         // find the valid video stream:
1733         if(!ds_fill_buffer(demuxer->video)){
1734           mp_msg(MSGT_DEMUXER,MSGL_INFO,"RM: " MSGTR_MissingVideoStream);
1735         }
1736     }
1737     if(demuxer->audio->id==-1 && a_streams>0){
1738         // find the valid audio stream:
1739         if(!ds_fill_buffer(demuxer->audio)){
1740           mp_msg(MSGT_DEMUXER,MSGL_INFO,"RM: " MSGTR_MissingAudioStream);
1741         }
1742     }
1743
1744     if(demuxer->video->sh){
1745         sh_video_t *sh=demuxer->video->sh;
1746         mp_msg(MSGT_DEMUX,MSGL_V,"VIDEO:  %.4s [%08X,%08X]  %dx%d  (aspect %4.2f)  %4.2f fps\n",
1747             (char *)&sh->format,((unsigned int*)(sh->bih+1))[1],((unsigned int*)(sh->bih+1))[0],
1748             sh->disp_w,sh->disp_h,sh->aspect,sh->fps);
1749     }
1750
1751     if(demuxer->audio->sh){
1752         sh_audio_t *sh=demuxer->audio->sh;
1753         mp_msg(MSGT_DEMUX,MSGL_V,"AUDIO:  %.4s [%08X]\n",
1754             (char *)&sh->format,sh->format);
1755     }
1756
1757     return demuxer;
1758 }
1759
1760 static void demux_close_real(demuxer_t *demuxer)
1761 {
1762     int i;
1763     real_priv_t* priv = demuxer->priv;
1764
1765     if (priv){
1766         for(i=0; i<MAX_STREAMS; i++)
1767             free(priv->index_table[i]);
1768         free(priv->audio_buf);
1769         free(priv->audio_timestamp);
1770         free(priv);
1771     }
1772
1773     return;
1774 }
1775
1776 /* please upload RV10 samples WITH INDEX CHUNK */
1777 static void demux_seek_real(demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
1778 {
1779     real_priv_t *priv = demuxer->priv;
1780     demux_stream_t *d_audio = demuxer->audio;
1781     demux_stream_t *d_video = demuxer->video;
1782     sh_audio_t *sh_audio = d_audio->sh;
1783     sh_video_t *sh_video = d_video->sh;
1784     int vid = d_video->id, aid = d_audio->id;
1785     int next_offset = 0;
1786     int64_t cur_timestamp = 0;
1787     int streams = 0;
1788     int retried = 0;
1789
1790
1791     if (sh_video && (unsigned)vid < MAX_STREAMS && priv->index_table_size[vid])
1792         streams |= 1;
1793     if (sh_audio && (unsigned)aid < MAX_STREAMS && priv->index_table_size[aid])
1794         streams |= 2;
1795
1796 //    printf("streams: %d\n", streams);
1797
1798     if (!streams)
1799         return;
1800
1801     if (flags & SEEK_ABSOLUTE)
1802         priv->current_apacket = priv->current_vpacket = 0;
1803     if (flags & SEEK_FACTOR)
1804         rel_seek_secs *= priv->duration;
1805
1806     if ((streams & 1) && priv->current_vpacket >= priv->index_table_size[vid])
1807         priv->current_vpacket = priv->index_table_size[vid] - 1;
1808     if ((streams & 2) && priv->current_apacket >= priv->index_table_size[aid])
1809         priv->current_apacket = priv->index_table_size[aid] - 1;
1810
1811 //    if (index_mode == 1 || index_mode == 2) {
1812         if (streams & 1) {// use the video index if we have one
1813             cur_timestamp = priv->index_table[vid][priv->current_vpacket].timestamp;
1814             if (rel_seek_secs > 0)
1815                 while ((priv->index_table[vid][priv->current_vpacket].timestamp - cur_timestamp) < rel_seek_secs * 1000){
1816                         priv->current_vpacket += 1;
1817                         if (priv->current_vpacket >= priv->index_table_size[vid]) {
1818                                 priv->current_vpacket = priv->index_table_size[vid] - 1;
1819                                 if (!retried) {
1820                                         stream_seek(demuxer->stream, priv->index_table[vid][priv->current_vpacket].offset);
1821                                         add_index_segment(demuxer, vid, cur_timestamp + rel_seek_secs * 1000);
1822                                         retried = 1;
1823                                 }
1824                                 else
1825                                         break;
1826                         }
1827                 }
1828             else if (rel_seek_secs < 0) {
1829                 while ((cur_timestamp - priv->index_table[vid][priv->current_vpacket].timestamp) < - rel_seek_secs * 1000){
1830                         priv->current_vpacket -= 1;
1831                         if (priv->current_vpacket < 0) {
1832                                 priv->current_vpacket = 0;
1833                                 break;
1834                         }
1835                 }
1836             }
1837             priv->video_curpos = priv->index_table[vid][priv->current_vpacket].offset;
1838             priv->audio_need_keyframe = !priv->is_multirate;
1839             priv->video_after_seek = 1;
1840         }
1841         if (streams & 2) {
1842             if (!(streams & 1)) {
1843                 cur_timestamp =
1844                     priv->index_table[aid][priv->current_apacket].timestamp;
1845             }
1846             if (rel_seek_secs > 0)
1847                 while ((priv->index_table[aid][priv->current_apacket].timestamp - cur_timestamp) < rel_seek_secs * 1000){
1848                         priv->current_apacket += 1;
1849                         if (priv->current_apacket >= priv->index_table_size[aid]) {
1850                                 priv->current_apacket = priv->index_table_size[aid] - 1;
1851                                 break;
1852                         }
1853                 }
1854             else if (rel_seek_secs < 0)
1855                 while ((cur_timestamp - priv->index_table[aid][priv->current_apacket].timestamp) < - rel_seek_secs * 1000){
1856                         priv->current_apacket -= 1;
1857                         if (priv->current_apacket < 0) {
1858                                 priv->current_apacket = 0;
1859                                 break;
1860                         }
1861                 }
1862             priv->audio_curpos = priv->index_table[aid][priv->current_apacket].offset;
1863         }
1864 //    }
1865     next_offset = streams & 1 ? priv->video_curpos : priv->audio_curpos;
1866 //    printf("seek: pos: %d, current packets: a: %d, v: %d\n",
1867 //      next_offset, priv->current_apacket, priv->current_vpacket);
1868     if (next_offset)
1869         stream_seek(demuxer->stream, next_offset);
1870
1871     demux_real_fill_buffer(demuxer, NULL);
1872 }
1873
1874 static int demux_real_control(demuxer_t *demuxer, int cmd, void *arg)
1875 {
1876     real_priv_t *priv = demuxer->priv;
1877     unsigned int lastpts = priv->v_pts ? priv->v_pts : priv->a_pts;
1878
1879     switch (cmd) {
1880         case DEMUXER_CTRL_GET_TIME_LENGTH:
1881             if (priv->duration == 0)
1882                 return DEMUXER_CTRL_DONTKNOW;
1883
1884             *((double *)arg) = (double)priv->duration;
1885             return DEMUXER_CTRL_OK;
1886
1887         case DEMUXER_CTRL_GET_PERCENT_POS:
1888             if (priv->duration == 0)
1889                 return DEMUXER_CTRL_DONTKNOW;
1890
1891             *((int *)arg) = (int)(100 * lastpts / priv->duration);
1892             return DEMUXER_CTRL_OK;
1893
1894         default:
1895             return DEMUXER_CTRL_NOTIMPL;
1896     }
1897 }
1898
1899
1900 const demuxer_desc_t demuxer_desc_real = {
1901   "Realmedia demuxer",
1902   "real",
1903   "REAL",
1904   "Alex Beregszasi, Florian Schneider, A'rpi, Roberto Togni",
1905   "handles new .RMF files",
1906   DEMUXER_TYPE_REAL,
1907   1, // safe autodetect
1908   real_check_file,
1909   demux_real_fill_buffer,
1910   demux_open_real,
1911   demux_close_real,
1912   demux_seek_real,
1913   demux_real_control
1914 };