Minor modifications to handle mms streaming.
[ffmpeg.git] / libavformat / asf.c
1 /*
2  * ASF compatible demuxer
3  * Copyright (c) 2000, 2001 Fabrice Bellard.
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 #include "avformat.h"
22 #include "riff.h"
23 #include "mpegaudio.h"
24 #include "asf.h"
25 #include "common.h"
26
27 #undef NDEBUG
28 #include <assert.h>
29
30 #define FRAME_HEADER_SIZE 17
31 // Fix Me! FRAME_HEADER_SIZE may be different.
32
33 static const GUID index_guid = {
34     0x33000890, 0xe5b1, 0x11cf, { 0x89, 0xf4, 0x00, 0xa0, 0xc9, 0x03, 0x49, 0xcb },
35 };
36
37 /**********************************/
38 /* decoding */
39
40 //#define DEBUG
41
42 #ifdef DEBUG
43 #define PRINT_IF_GUID(g,cmp) \
44 if (!memcmp(g, &cmp, sizeof(GUID))) \
45     printf("(GUID: %s) ", #cmp)
46
47 static void print_guid(const GUID *g)
48 {
49     int i;
50     PRINT_IF_GUID(g, asf_header);
51     else PRINT_IF_GUID(g, file_header);
52     else PRINT_IF_GUID(g, stream_header);
53     else PRINT_IF_GUID(g, audio_stream);
54     else PRINT_IF_GUID(g, audio_conceal_none);
55     else PRINT_IF_GUID(g, video_stream);
56     else PRINT_IF_GUID(g, video_conceal_none);
57     else PRINT_IF_GUID(g, command_stream);
58     else PRINT_IF_GUID(g, comment_header);
59     else PRINT_IF_GUID(g, codec_comment_header);
60     else PRINT_IF_GUID(g, codec_comment1_header);
61     else PRINT_IF_GUID(g, data_header);
62     else PRINT_IF_GUID(g, index_guid);
63     else PRINT_IF_GUID(g, head1_guid);
64     else PRINT_IF_GUID(g, head2_guid);
65     else PRINT_IF_GUID(g, my_guid);
66     else PRINT_IF_GUID(g, ext_stream_header);
67     else PRINT_IF_GUID(g, extended_content_header);
68     else PRINT_IF_GUID(g, ext_stream_embed_stream_header);
69     else PRINT_IF_GUID(g, ext_stream_audio_stream);
70     else
71         printf("(GUID: unknown) ");
72     printf("0x%08x, 0x%04x, 0x%04x, {", g->v1, g->v2, g->v3);
73     for(i=0;i<8;i++)
74         printf(" 0x%02x,", g->v4[i]);
75     printf("}\n");
76 }
77 #undef PRINT_IF_GUID
78 #endif
79
80 static void get_guid(ByteIOContext *s, GUID *g)
81 {
82     int i;
83
84     g->v1 = get_le32(s);
85     g->v2 = get_le16(s);
86     g->v3 = get_le16(s);
87     for(i=0;i<8;i++)
88         g->v4[i] = get_byte(s);
89 }
90
91 #if 0
92 static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
93 {
94     int len, c;
95     char *q;
96
97     len = get_le16(pb);
98     q = buf;
99     while (len > 0) {
100         c = get_le16(pb);
101         if ((q - buf) < buf_size - 1)
102             *q++ = c;
103         len--;
104     }
105     *q = '\0';
106 }
107 #endif
108
109 static void get_str16_nolen(ByteIOContext *pb, int len, char *buf, int buf_size)
110 {
111     char* q = buf;
112     len /= 2;
113     while (len--) {
114         uint8_t tmp;
115         PUT_UTF8(get_le16(pb), tmp, if (q - buf < buf_size - 1) *q++ = tmp;)
116     }
117     *q = '\0';
118 }
119
120 static int asf_probe(AVProbeData *pd)
121 {
122     GUID g;
123     const unsigned char *p;
124     int i;
125
126     /* check file header */
127     if (pd->buf_size <= 32)
128         return 0;
129     p = pd->buf;
130     g.v1 = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
131     p += 4;
132     g.v2 = p[0] | (p[1] << 8);
133     p += 2;
134     g.v3 = p[0] | (p[1] << 8);
135     p += 2;
136     for(i=0;i<8;i++)
137         g.v4[i] = *p++;
138
139     if (!memcmp(&g, &asf_header, sizeof(GUID)))
140         return AVPROBE_SCORE_MAX;
141     else
142         return 0;
143 }
144
145 static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
146 {
147     ASFContext *asf = s->priv_data;
148     GUID g;
149     ByteIOContext *pb = &s->pb;
150     AVStream *st;
151     ASFStream *asf_st;
152     int size, i;
153     int64_t gsize;
154
155     get_guid(pb, &g);
156     if (memcmp(&g, &asf_header, sizeof(GUID)))
157         goto fail;
158     get_le64(pb);
159     get_le32(pb);
160     get_byte(pb);
161     get_byte(pb);
162     memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
163     for(;;) {
164         get_guid(pb, &g);
165         gsize = get_le64(pb);
166 #ifdef DEBUG
167         printf("%08"PRIx64": ", url_ftell(pb) - 24);
168         print_guid(&g);
169         printf("  size=0x%"PRIx64"\n", gsize);
170 #endif
171         if (gsize < 24)
172             goto fail;
173         if (!memcmp(&g, &file_header, sizeof(GUID))) {
174             get_guid(pb, &asf->hdr.guid);
175             asf->hdr.file_size          = get_le64(pb);
176             asf->hdr.create_time        = get_le64(pb);
177             asf->hdr.packets_count      = get_le64(pb);
178             asf->hdr.send_time          = get_le64(pb);
179             asf->hdr.play_time          = get_le64(pb);
180             asf->hdr.preroll            = get_le32(pb);
181             asf->hdr.ignore             = get_le32(pb);
182             asf->hdr.flags              = get_le32(pb);
183             asf->hdr.min_pktsize        = get_le32(pb);
184             asf->hdr.max_pktsize        = get_le32(pb);
185             asf->hdr.max_bitrate        = get_le32(pb);
186             asf->packet_size = asf->hdr.max_pktsize;
187             asf->nb_packets = asf->hdr.packets_count;
188         } else if (!memcmp(&g, &stream_header, sizeof(GUID))) {
189             int type, type_specific_size, sizeX;
190             uint64_t total_size;
191             unsigned int tag1;
192             int64_t pos1, pos2;
193             int test_for_ext_stream_audio;
194
195             pos1 = url_ftell(pb);
196
197             st = av_new_stream(s, 0);
198             if (!st)
199                 goto fail;
200             av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
201             asf_st = av_mallocz(sizeof(ASFStream));
202             if (!asf_st)
203                 goto fail;
204             st->priv_data = asf_st;
205             st->start_time = asf->hdr.preroll;
206             if(!(asf->hdr.flags & 0x01)) { // if we aren't streaming...
207                 st->duration = asf->hdr.send_time /
208                     (10000000 / 1000) - st->start_time;
209             }
210             get_guid(pb, &g);
211
212             test_for_ext_stream_audio = 0;
213             if (!memcmp(&g, &audio_stream, sizeof(GUID))) {
214                 type = CODEC_TYPE_AUDIO;
215             } else if (!memcmp(&g, &video_stream, sizeof(GUID))) {
216                 type = CODEC_TYPE_VIDEO;
217             } else if (!memcmp(&g, &command_stream, sizeof(GUID))) {
218                 type = CODEC_TYPE_UNKNOWN;
219             } else if (!memcmp(&g, &ext_stream_embed_stream_header, sizeof(GUID))) {
220                 test_for_ext_stream_audio = 1;
221                 type = CODEC_TYPE_UNKNOWN;
222             } else {
223                 goto fail;
224             }
225             get_guid(pb, &g);
226             total_size = get_le64(pb);
227             type_specific_size = get_le32(pb);
228             get_le32(pb);
229             st->id = get_le16(pb) & 0x7f; /* stream id */
230             // mapping of asf ID to AV stream ID;
231             asf->asfid2avid[st->id] = s->nb_streams - 1;
232
233             get_le32(pb);
234
235             if (test_for_ext_stream_audio) {
236                 get_guid(pb, &g);
237                 if (!memcmp(&g, &ext_stream_audio_stream, sizeof(GUID))) {
238                     type = CODEC_TYPE_AUDIO;
239                     get_guid(pb, &g);
240                     get_le32(pb);
241                     get_le32(pb);
242                     get_le32(pb);
243                     get_guid(pb, &g);
244                     get_le32(pb);
245                 }
246             }
247
248             st->codec->codec_type = type;
249             if (type == CODEC_TYPE_AUDIO) {
250                 get_wav_header(pb, st->codec, type_specific_size);
251                 st->need_parsing = 1;
252                 /* We have to init the frame size at some point .... */
253                 pos2 = url_ftell(pb);
254                 if (gsize > (pos2 + 8 - pos1 + 24)) {
255                     asf_st->ds_span = get_byte(pb);
256                     asf_st->ds_packet_size = get_le16(pb);
257                     asf_st->ds_chunk_size = get_le16(pb);
258                     asf_st->ds_data_size = get_le16(pb);
259                     asf_st->ds_silence_data = get_byte(pb);
260                 }
261                 //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
262                 //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
263                 //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
264                 if (asf_st->ds_span > 1) {
265                     if (!asf_st->ds_chunk_size
266                         || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1))
267                         asf_st->ds_span = 0; // disable descrambling
268                 }
269                 switch (st->codec->codec_id) {
270                 case CODEC_ID_MP3:
271                     st->codec->frame_size = MPA_FRAME_SIZE;
272                     break;
273                 case CODEC_ID_PCM_S16LE:
274                 case CODEC_ID_PCM_S16BE:
275                 case CODEC_ID_PCM_U16LE:
276                 case CODEC_ID_PCM_U16BE:
277                 case CODEC_ID_PCM_S8:
278                 case CODEC_ID_PCM_U8:
279                 case CODEC_ID_PCM_ALAW:
280                 case CODEC_ID_PCM_MULAW:
281                     st->codec->frame_size = 1;
282                     break;
283                 default:
284                     /* This is probably wrong, but it prevents a crash later */
285                     st->codec->frame_size = 1;
286                     break;
287                 }
288             } else if (type == CODEC_TYPE_VIDEO) {
289                 get_le32(pb);
290                 get_le32(pb);
291                 get_byte(pb);
292                 size = get_le16(pb); /* size */
293                 sizeX= get_le32(pb); /* size */
294                 st->codec->width = get_le32(pb);
295                 st->codec->height = get_le32(pb);
296                 /* not available for asf */
297                 get_le16(pb); /* panes */
298                 st->codec->bits_per_sample = get_le16(pb); /* depth */
299                 tag1 = get_le32(pb);
300                 url_fskip(pb, 20);
301 //                av_log(NULL, AV_LOG_DEBUG, "size:%d tsize:%d sizeX:%d\n", size, total_size, sizeX);
302                 size= sizeX;
303                 if (size > 40) {
304                     st->codec->extradata_size = size - 40;
305                     st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
306                     get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
307                 }
308
309         /* Extract palette from extradata if bpp <= 8 */
310         /* This code assumes that extradata contains only palette */
311         /* This is true for all paletted codecs implemented in ffmpeg */
312         if (st->codec->extradata_size && (st->codec->bits_per_sample <= 8)) {
313             st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
314 #ifdef WORDS_BIGENDIAN
315             for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
316                 st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
317 #else
318             memcpy(st->codec->palctrl->palette, st->codec->extradata,
319                    FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
320 #endif
321             st->codec->palctrl->palette_changed = 1;
322         }
323
324                 st->codec->codec_tag = tag1;
325                 st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
326                 if(tag1 == MKTAG('D', 'V', 'R', ' '))
327                     st->need_parsing = 1;
328             }
329             pos2 = url_ftell(pb);
330             url_fskip(pb, gsize - (pos2 - pos1 + 24));
331         } else if (!memcmp(&g, &data_header, sizeof(GUID))) {
332             asf->data_object_offset = url_ftell(pb);
333             // if not streaming, gsize is not unlimited (how?), and there is enough space in the file..
334             if (!(asf->hdr.flags & 0x01) && gsize != (uint64_t)-1 && gsize >= 24) {
335                 asf->data_object_size = gsize - 24;
336             } else {
337                 asf->data_object_size = (uint64_t)-1;
338             }
339             break;
340         } else if (!memcmp(&g, &comment_header, sizeof(GUID))) {
341             int len1, len2, len3, len4, len5;
342
343             len1 = get_le16(pb);
344             len2 = get_le16(pb);
345             len3 = get_le16(pb);
346             len4 = get_le16(pb);
347             len5 = get_le16(pb);
348             get_str16_nolen(pb, len1, s->title, sizeof(s->title));
349             get_str16_nolen(pb, len2, s->author, sizeof(s->author));
350             get_str16_nolen(pb, len3, s->copyright, sizeof(s->copyright));
351             get_str16_nolen(pb, len4, s->comment, sizeof(s->comment));
352             url_fskip(pb, len5);
353        } else if (!memcmp(&g, &extended_content_header, sizeof(GUID))) {
354                 int desc_count, i;
355
356                 desc_count = get_le16(pb);
357                 for(i=0;i<desc_count;i++)
358                 {
359                         int name_len,value_type,value_len;
360                         uint64_t value_num = 0;
361                         char *name, *value;
362
363                         name_len = get_le16(pb);
364                         name = (char *)av_malloc(name_len * 2);
365                         get_str16_nolen(pb, name_len, name, name_len * 2);
366                         value_type = get_le16(pb);
367                         value_len = get_le16(pb);
368                         if ((value_type == 0) || (value_type == 1)) // unicode or byte
369                         {
370                                 value = (char *)av_malloc(value_len * 2);
371                                 get_str16_nolen(pb, value_len, value,
372                                         value_len * 2);
373                                 if (strcmp(name,"WM/AlbumTitle")==0) { pstrcpy(s->album, sizeof(s->album), value); }
374                                 av_free(value);
375                         }
376                         if ((value_type >= 2) && (value_type <= 5)) // boolean or DWORD or QWORD or WORD
377                         {
378                                 if (value_type==2) value_num = get_le32(pb);
379                                 if (value_type==3) value_num = get_le32(pb);
380                                 if (value_type==4) value_num = get_le64(pb);
381                                 if (value_type==5) value_num = get_le16(pb);
382                                 if (strcmp(name,"WM/Track")==0) s->track = value_num + 1;
383                                 if (strcmp(name,"WM/TrackNumber")==0) s->track = value_num;
384                         }
385                         av_free(name);
386                 }
387         } else if (!memcmp(&g, &ext_stream_header, sizeof(GUID))) {
388             int ext_len, payload_ext_ct, stream_ct;
389             uint32_t ext_d;
390             int64_t pos_ex_st;
391             pos_ex_st = url_ftell(pb);
392
393             get_le64(pb);
394             get_le64(pb);
395             get_le32(pb);
396             get_le32(pb);
397             get_le32(pb);
398             get_le32(pb);
399             get_le32(pb);
400             get_le32(pb);
401             get_le32(pb);
402             get_le32(pb);
403             get_le16(pb);
404             get_le16(pb);
405             get_le64(pb);
406             stream_ct = get_le16(pb);
407             payload_ext_ct = get_le16(pb);
408
409             for (i=0; i<stream_ct; i++){
410                 get_le16(pb);
411                 ext_len = get_le16(pb);
412                 url_fseek(pb, ext_len, SEEK_CUR);
413             }
414
415             for (i=0; i<payload_ext_ct; i++){
416                 get_guid(pb, &g);
417                 ext_d=get_le16(pb);
418                 ext_len=get_le32(pb);
419                 url_fseek(pb, ext_len, SEEK_CUR);
420             }
421
422             // there could be a optional stream properties object to follow
423             // if so the next iteration will pick it up
424         } else if (!memcmp(&g, &head1_guid, sizeof(GUID))) {
425             int v1, v2;
426             get_guid(pb, &g);
427             v1 = get_le32(pb);
428             v2 = get_le16(pb);
429 #if 0
430         } else if (!memcmp(&g, &codec_comment_header, sizeof(GUID))) {
431             int len, v1, n, num;
432             char str[256], *q;
433             char tag[16];
434
435             get_guid(pb, &g);
436             print_guid(&g);
437
438             n = get_le32(pb);
439             for(i=0;i<n;i++) {
440                 num = get_le16(pb); /* stream number */
441                 get_str16(pb, str, sizeof(str));
442                 get_str16(pb, str, sizeof(str));
443                 len = get_le16(pb);
444                 q = tag;
445                 while (len > 0) {
446                     v1 = get_byte(pb);
447                     if ((q - tag) < sizeof(tag) - 1)
448                         *q++ = v1;
449                     len--;
450                 }
451                 *q = '\0';
452             }
453 #endif
454         } else if (url_feof(pb)) {
455             goto fail;
456         } else {
457             url_fseek(pb, gsize - 24, SEEK_CUR);
458         }
459     }
460     get_guid(pb, &g);
461     get_le64(pb);
462     get_byte(pb);
463     get_byte(pb);
464     if (url_feof(pb))
465         goto fail;
466     asf->data_offset = url_ftell(pb);
467     asf->packet_size_left = 0;
468
469     return 0;
470
471  fail:
472      for(i=0;i<s->nb_streams;i++) {
473         AVStream *st = s->streams[i];
474         if (st) {
475             av_free(st->priv_data);
476             av_free(st->codec->extradata);
477         }
478         av_free(st);
479     }
480     return -1;
481 }
482
483 #define DO_2BITS(bits, var, defval) \
484     switch (bits & 3) \
485     { \
486     case 3: var = get_le32(pb); rsize += 4; break; \
487     case 2: var = get_le16(pb); rsize += 2; break; \
488     case 1: var = get_byte(pb); rsize++; break; \
489     default: var = defval; break; \
490     }
491
492 static int asf_get_packet(AVFormatContext *s)
493 {
494     ASFContext *asf = s->priv_data;
495     ByteIOContext *pb = &s->pb;
496     uint32_t packet_length, padsize;
497     int rsize = 9;
498     int c;
499
500     assert((url_ftell(&s->pb) - s->data_offset) % asf->packet_size == 0);
501
502     c = get_byte(pb);
503     if (c != 0x82) {
504         if (!url_feof(pb))
505             av_log(s, AV_LOG_ERROR, "ff asf bad header %x  at:%"PRId64"\n", c, url_ftell(pb));
506     }
507     if ((c & 0x0f) == 2) { // always true for now
508         if (get_le16(pb) != 0) {
509             if (!url_feof(pb))
510                 av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n");
511             return AVERROR_IO;
512         }
513         rsize+=2;
514 /*    }else{
515         if (!url_feof(pb))
516             printf("ff asf bad header %x  at:%"PRId64"\n", c, url_ftell(pb));
517         return AVERROR_IO;*/
518     }
519
520     asf->packet_flags = get_byte(pb);
521     asf->packet_property = get_byte(pb);
522
523     DO_2BITS(asf->packet_flags >> 5, packet_length, asf->packet_size);
524     DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
525     DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
526
527     //the following checks prevent overflows and infinite loops
528     if(packet_length >= (1U<<29)){
529         av_log(s, AV_LOG_ERROR, "invalid packet_length %d at:%"PRId64"\n", packet_length, url_ftell(pb));
530         return 0; // FIXME this should be -1
531     }
532     if(padsize >= (1U<<29)){
533         av_log(s, AV_LOG_ERROR, "invalid padsize %d at:%"PRId64"\n", padsize, url_ftell(pb));
534         return 0; // FIXME this should be -1
535     }
536
537     asf->packet_timestamp = get_le32(pb);
538     get_le16(pb); /* duration */
539     // rsize has at least 11 bytes which have to be present
540
541     if (asf->packet_flags & 0x01) {
542         asf->packet_segsizetype = get_byte(pb); rsize++;
543         asf->packet_segments = asf->packet_segsizetype & 0x3f;
544     } else {
545         asf->packet_segments = 1;
546         asf->packet_segsizetype = 0x80;
547     }
548     asf->packet_size_left = packet_length - padsize - rsize;
549     if (packet_length < asf->hdr.min_pktsize)
550         padsize += asf->hdr.min_pktsize - packet_length;
551     asf->packet_padsize = padsize;
552 #ifdef DEBUG
553     printf("packet: size=%d padsize=%d  left=%d\n", asf->packet_size, asf->packet_padsize, asf->packet_size_left);
554 #endif
555     return 0;
556 }
557
558 static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
559 {
560     ASFContext *asf = s->priv_data;
561     ASFStream *asf_st = 0;
562     ByteIOContext *pb = &s->pb;
563     //static int pc = 0;
564     for (;;) {
565         int rsize = 0;
566         if (asf->packet_size_left < FRAME_HEADER_SIZE
567             || asf->packet_segments < 1) {
568             //asf->packet_size_left <= asf->packet_padsize) {
569             int ret = asf->packet_size_left + asf->packet_padsize;
570             //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));
571             if((url_ftell(&s->pb) + ret - s->data_offset) % asf->packet_size)
572                 ret += asf->packet_size - ((url_ftell(&s->pb) + ret - s->data_offset) % asf->packet_size);
573             assert(ret>=0);
574             /* fail safe */
575             url_fskip(pb, ret);
576             asf->packet_pos= url_ftell(&s->pb);
577             if (asf->data_object_size != (uint64_t)-1 &&
578                 (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))
579                 return AVERROR_IO; /* Do not exceed the size of the data object */
580             ret = asf_get_packet(s);
581             //printf("READ ASF PACKET  %d   r:%d   c:%d\n", ret, asf->packet_size_left, pc++);
582             if (ret < 0 || url_feof(pb))
583                 return AVERROR_IO;
584             asf->packet_time_start = 0;
585             continue;
586         }
587         if (asf->packet_time_start == 0) {
588             /* read frame header */
589             int num = get_byte(pb);
590             asf->packet_segments--;
591             rsize++;
592             asf->packet_key_frame = (num & 0x80) >> 7;
593             asf->stream_index = asf->asfid2avid[num & 0x7f];
594             // sequence should be ignored!
595             DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
596             DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
597             DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
598 //printf("key:%d stream:%d seq:%d offset:%d replic_size:%d\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, //asf->packet_frag_offset, asf->packet_replic_size);
599             if (asf->packet_replic_size > 1) {
600                 assert(asf->packet_replic_size >= 8);
601                 // it should be always at least 8 bytes - FIXME validate
602                 asf->packet_obj_size = get_le32(pb);
603                 asf->packet_frag_timestamp = get_le32(pb); // timestamp
604                 if (asf->packet_replic_size > 8)
605                     url_fskip(pb, asf->packet_replic_size - 8);
606                 rsize += asf->packet_replic_size; // FIXME - check validity
607             } else if (asf->packet_replic_size==1){
608                 // multipacket - frag_offset is begining timestamp
609                 asf->packet_time_start = asf->packet_frag_offset;
610                 asf->packet_frag_offset = 0;
611                 asf->packet_frag_timestamp = asf->packet_timestamp;
612
613                 asf->packet_time_delta = get_byte(pb);
614                 rsize++;
615             }else{
616                 assert(asf->packet_replic_size==0);
617             }
618             if (asf->packet_flags & 0x01) {
619                 DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
620 #undef DO_2BITS
621                 //printf("Fragsize %d\n", asf->packet_frag_size);
622             } else {
623                 asf->packet_frag_size = asf->packet_size_left - rsize;
624                 //printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
625             }
626             if (asf->packet_replic_size == 1) {
627                 asf->packet_multi_size = asf->packet_frag_size;
628                 if (asf->packet_multi_size > asf->packet_size_left) {
629                     asf->packet_segments = 0;
630                     continue;
631                 }
632             }
633             asf->packet_size_left -= rsize;
634             //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
635
636             if (asf->stream_index < 0
637                 || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL
638                 || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)
639                 ) {
640                 asf->packet_time_start = 0;
641                 /* unhandled packet (should not happen) */
642                 url_fskip(pb, asf->packet_frag_size);
643                 asf->packet_size_left -= asf->packet_frag_size;
644                 if(asf->stream_index < 0)
645                     av_log(s, AV_LOG_ERROR, "ff asf skip %d  %d\n", asf->packet_frag_size, num & 0x7f);
646                 continue;
647             }
648             asf->asf_st = s->streams[asf->stream_index]->priv_data;
649         }
650         asf_st = asf->asf_st;
651
652         if ((asf->packet_frag_offset != asf_st->frag_offset
653              || (asf->packet_frag_offset
654                  && asf->packet_seq != asf_st->seq)) // seq should be ignored
655            ) {
656             /* cannot continue current packet: free it */
657             // FIXME better check if packet was already allocated
658             av_log(s, AV_LOG_INFO, "ff asf parser skips: %d - %d     o:%d - %d    %d %d   fl:%d\n",
659                    asf_st->pkt.size,
660                    asf->packet_obj_size,
661                    asf->packet_frag_offset, asf_st->frag_offset,
662                    asf->packet_seq, asf_st->seq, asf->packet_frag_size);
663             if (asf_st->pkt.size)
664                 av_free_packet(&asf_st->pkt);
665             asf_st->frag_offset = 0;
666             if (asf->packet_frag_offset != 0) {
667                 url_fskip(pb, asf->packet_frag_size);
668                 av_log(s, AV_LOG_INFO, "ff asf parser skipping %db\n", asf->packet_frag_size);
669                 asf->packet_size_left -= asf->packet_frag_size;
670                 continue;
671             }
672         }
673         if (asf->packet_replic_size == 1) {
674             // frag_offset is here used as the begining timestamp
675             asf->packet_frag_timestamp = asf->packet_time_start;
676             asf->packet_time_start += asf->packet_time_delta;
677             asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
678             asf->packet_size_left--;
679             asf->packet_multi_size--;
680             if (asf->packet_multi_size < asf->packet_obj_size)
681             {
682                 asf->packet_time_start = 0;
683                 url_fskip(pb, asf->packet_multi_size);
684                 asf->packet_size_left -= asf->packet_multi_size;
685                 continue;
686             }
687             asf->packet_multi_size -= asf->packet_obj_size;
688             //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);
689         }
690         if (asf_st->frag_offset == 0) {
691             /* new packet */
692             av_new_packet(&asf_st->pkt, asf->packet_obj_size);
693             asf_st->seq = asf->packet_seq;
694             asf_st->pkt.pts = asf->packet_frag_timestamp;
695             asf_st->pkt.stream_index = asf->stream_index;
696             asf_st->pkt.pos =
697             asf_st->packet_pos= asf->packet_pos;
698 //printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",
699 //asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,
700 //s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);
701             if (s->streams[asf->stream_index]->codec->codec_type == CODEC_TYPE_AUDIO)
702                 asf->packet_key_frame = 1;
703             if (asf->packet_key_frame)
704                 asf_st->pkt.flags |= PKT_FLAG_KEY;
705         }
706
707         /* read data */
708         //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
709         //       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
710         //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
711         asf->packet_size_left -= asf->packet_frag_size;
712         if (asf->packet_size_left < 0)
713             continue;
714         get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,
715                    asf->packet_frag_size);
716         asf_st->frag_offset += asf->packet_frag_size;
717         /* test if whole packet is read */
718         if (asf_st->frag_offset == asf_st->pkt.size) {
719             /* return packet */
720             if (asf_st->ds_span > 1) {
721                 /* packet descrambling */
722                 uint8_t *newdata = av_malloc(asf_st->pkt.size);
723                 if (newdata) {
724                     int offset = 0;
725                     while (offset < asf_st->pkt.size) {
726                         int off = offset / asf_st->ds_chunk_size;
727                         int row = off / asf_st->ds_span;
728                         int col = off % asf_st->ds_span;
729                         int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
730                         //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
731                         memcpy(newdata + offset,
732                                asf_st->pkt.data + idx * asf_st->ds_chunk_size,
733                                asf_st->ds_chunk_size);
734                         offset += asf_st->ds_chunk_size;
735                     }
736                     av_free(asf_st->pkt.data);
737                     asf_st->pkt.data = newdata;
738                 }
739             }
740             asf_st->frag_offset = 0;
741             memcpy(pkt, &asf_st->pkt, sizeof(AVPacket));
742             //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
743             asf_st->pkt.size = 0;
744             asf_st->pkt.data = 0;
745             break; // packet completed
746         }
747     }
748     return 0;
749 }
750
751 static int asf_read_close(AVFormatContext *s)
752 {
753     int i;
754
755     for(i=0;i<s->nb_streams;i++) {
756         AVStream *st = s->streams[i];
757         av_free(st->priv_data);
758     av_free(st->codec->palctrl);
759     }
760     return 0;
761 }
762
763 // Added to support seeking after packets have been read
764 // If information is not reset, read_packet fails due to
765 // leftover information from previous reads
766 static void asf_reset_header(AVFormatContext *s)
767 {
768     ASFContext *asf = s->priv_data;
769     ASFStream *asf_st;
770     int i;
771
772     asf->packet_nb_frames = 0;
773     asf->packet_timestamp_start = -1;
774     asf->packet_timestamp_end = -1;
775     asf->packet_size_left = 0;
776     asf->packet_segments = 0;
777     asf->packet_flags = 0;
778     asf->packet_property = 0;
779     asf->packet_timestamp = 0;
780     asf->packet_segsizetype = 0;
781     asf->packet_segments = 0;
782     asf->packet_seq = 0;
783     asf->packet_replic_size = 0;
784     asf->packet_key_frame = 0;
785     asf->packet_padsize = 0;
786     asf->packet_frag_offset = 0;
787     asf->packet_frag_size = 0;
788     asf->packet_frag_timestamp = 0;
789     asf->packet_multi_size = 0;
790     asf->packet_obj_size = 0;
791     asf->packet_time_delta = 0;
792     asf->packet_time_start = 0;
793
794     for(i=0; i<s->nb_streams; i++){
795         asf_st= s->streams[i]->priv_data;
796         av_free_packet(&asf_st->pkt);
797         asf_st->frag_offset=0;
798         asf_st->seq=0;
799     }
800     asf->asf_st= NULL;
801 }
802
803 static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit)
804 {
805     ASFContext *asf = s->priv_data;
806     AVPacket pkt1, *pkt = &pkt1;
807     ASFStream *asf_st;
808     int64_t pts;
809     int64_t pos= *ppos;
810     int i;
811     int64_t start_pos[s->nb_streams];
812
813     for(i=0; i<s->nb_streams; i++){
814         start_pos[i]= pos;
815     }
816
817     pos= (pos+asf->packet_size-1-s->data_offset)/asf->packet_size*asf->packet_size+ s->data_offset;
818     *ppos= pos;
819     url_fseek(&s->pb, pos, SEEK_SET);
820
821 //printf("asf_read_pts\n");
822     asf_reset_header(s);
823     for(;;){
824         if (av_read_frame(s, pkt) < 0){
825             av_log(s, AV_LOG_INFO, "seek failed\n");
826             return AV_NOPTS_VALUE;
827         }
828
829         pts= pkt->pts;
830
831         av_free_packet(pkt);
832         if(pkt->flags&PKT_FLAG_KEY){
833             i= pkt->stream_index;
834
835             asf_st= s->streams[i]->priv_data;
836
837             assert((asf_st->packet_pos - s->data_offset) % asf->packet_size == 0);
838             pos= asf_st->packet_pos;
839
840             av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME);
841             start_pos[i]= asf_st->packet_pos + 1;
842
843             if(pkt->stream_index == stream_index)
844                break;
845         }
846     }
847
848     *ppos= pos;
849 //printf("found keyframe at %"PRId64" stream %d stamp:%"PRId64"\n", *ppos, stream_index, pts);
850
851     return pts;
852 }
853
854 static void asf_build_simple_index(AVFormatContext *s, int stream_index)
855 {
856     GUID g;
857     ASFContext *asf = s->priv_data;
858     int64_t gsize, itime;
859     int64_t pos, current_pos, index_pts;
860     int i;
861     int pct,ict;
862
863     current_pos = url_ftell(&s->pb);
864
865     url_fseek(&s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET);
866     get_guid(&s->pb, &g);
867     if (!memcmp(&g, &index_guid, sizeof(GUID))) {
868         gsize = get_le64(&s->pb);
869         get_guid(&s->pb, &g);
870         itime=get_le64(&s->pb);
871         pct=get_le32(&s->pb);
872         ict=get_le32(&s->pb);
873         av_log(NULL, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n",itime,pct,ict);
874
875         for (i=0;i<ict;i++){
876             int pktnum=get_le32(&s->pb);
877             int pktct =get_le16(&s->pb);
878             av_log(NULL, AV_LOG_DEBUG, "pktnum:%d, pktct:%d\n", pktnum, pktct);
879
880             pos=s->data_offset + asf->packet_size*(int64_t)pktnum;
881             index_pts=av_rescale(itime, i, 10000);
882
883             av_add_index_entry(s->streams[stream_index], pos, index_pts, asf->packet_size, 0, AVINDEX_KEYFRAME);
884         }
885         asf->index_read= 1;
886     }
887     url_fseek(&s->pb, current_pos, SEEK_SET);
888 }
889
890 static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags)
891 {
892     ASFContext *asf = s->priv_data;
893     AVStream *st = s->streams[stream_index];
894     int64_t pos;
895     int index;
896
897     if (asf->packet_size <= 0)
898         return -1;
899
900     if (!asf->index_read)
901         asf_build_simple_index(s, stream_index);
902
903     if(!(asf->index_read && st->index_entries)){
904         if(av_seek_frame_binary(s, stream_index, pts, flags)<0)
905             return -1;
906     }else{
907         index= av_index_search_timestamp(st, pts, flags);
908         if(index<0)
909             return -1;
910
911         /* find the position */
912         pos = st->index_entries[index].pos;
913         pts = st->index_entries[index].timestamp;
914
915     // various attempts to find key frame have failed so far
916     //    asf_reset_header(s);
917     //    url_fseek(&s->pb, pos, SEEK_SET);
918     //    key_pos = pos;
919     //     for(i=0;i<16;i++){
920     //         pos = url_ftell(&s->pb);
921     //         if (av_read_frame(s, &pkt) < 0){
922     //             av_log(s, AV_LOG_INFO, "seek failed\n");
923     //             return -1;
924     //         }
925     //         asf_st = s->streams[stream_index]->priv_data;
926     //         pos += st->parser->frame_offset;
927     //
928     //         if (pkt.size > b) {
929     //             b = pkt.size;
930     //             key_pos = pos;
931     //         }
932     //
933     //         av_free_packet(&pkt);
934     //     }
935
936         /* do the seek */
937         av_log(NULL, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos);
938         url_fseek(&s->pb, pos, SEEK_SET);
939     }
940     asf_reset_header(s);
941     return 0;
942 }
943
944 AVInputFormat asf_demuxer = {
945     "asf",
946     "asf format",
947     sizeof(ASFContext),
948     asf_probe,
949     asf_read_header,
950     asf_read_packet,
951     asf_read_close,
952     asf_read_seek,
953     asf_read_pts,
954 };