Statistics
| Branch: | Revision:

ffmpeg / libavformat / asf.c @ 1305a9d5

History | View | Annotate | Download (45.5 KB)

1
/*
2
 * ASF compatible encoder and decoder.
3
 * Copyright (c) 2000, 2001 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#include "avformat.h"
20
#include "avi.h"
21
#include "mpegaudio.h"
22

    
23
#undef NDEBUG
24
#include <assert.h>
25

    
26
#define PACKET_SIZE 3200
27
#define PACKET_HEADER_SIZE 12
28
#define FRAME_HEADER_SIZE 17
29

    
30
typedef struct {
31
    int num;
32
    int seq;
33
    /* use for reading */
34
    AVPacket pkt;
35
    int frag_offset;
36
    int timestamp;
37
    int64_t duration;
38

    
39
    int ds_span;                /* descrambling  */
40
    int ds_packet_size;
41
    int ds_chunk_size;
42
    int ds_data_size;
43
    int ds_silence_data;
44
    
45
    int packet_pos;
46

    
47
} ASFStream;
48

    
49
typedef struct {
50
    uint32_t v1;
51
    uint16_t v2;
52
    uint16_t v3;
53
    uint8_t v4[8];
54
} GUID;
55

    
56
typedef struct {
57
    GUID guid;                        // generated by client computer
58
    uint64_t file_size;                // in bytes
59
                                // invalid if broadcasting
60
    uint64_t create_time;        // time of creation, in 100-nanosecond units since 1.1.1601
61
                                // invalid if broadcasting
62
    uint64_t packets_count;        // how many packets are there in the file
63
                                // invalid if broadcasting
64
    uint64_t play_time;                // play time, in 100-nanosecond units
65
                                // invalid if broadcasting
66
    uint64_t send_time;                // time to send file, in 100-nanosecond units
67
                                // invalid if broadcasting (could be ignored)
68
    uint32_t preroll;                // timestamp of the first packet, in milliseconds
69
                                    // if nonzero - substract from time
70
    uint32_t ignore;            // preroll is 64bit - but let's just ignore it
71
    uint32_t flags;                // 0x01 - broadcast
72
                                    // 0x02 - seekable
73
                                // rest is reserved should be 0
74
    uint32_t min_pktsize;        // size of a data packet
75
                                // invalid if broadcasting
76
    uint32_t max_pktsize;        // shall be the same as for min_pktsize
77
                                // invalid if broadcasting
78
    uint32_t max_bitrate;        // bandwith of stream in bps
79
                                    // should be the sum of bitrates of the
80
                                // individual media streams
81
} ASFMainHeader;
82

    
83

    
84
typedef struct {
85
    int seqno;
86
    int packet_size;
87
    int is_streamed;
88
    int asfid2avid[128];        /* conversion table from asf ID 2 AVStream ID */
89
    ASFStream streams[128];        /* it's max number and it's not that big */
90
    /* non streamed additonnal info */
91
    int64_t nb_packets;
92
    int64_t duration; /* in 100ns units */
93
    /* packet filling */
94
    int packet_size_left;
95
    int packet_timestamp_start;
96
    int packet_timestamp_end;
97
    int packet_nb_frames;
98
    uint8_t packet_buf[PACKET_SIZE];
99
    ByteIOContext pb;
100
    /* only for reading */
101
    uint64_t data_offset; /* begining of the first data packet */
102

    
103
    ASFMainHeader hdr;
104

    
105
    int packet_flags;
106
    int packet_property;
107
    int packet_timestamp;
108
    int packet_segsizetype;
109
    int packet_segments;
110
    int packet_seq;
111
    int packet_replic_size;
112
    int packet_key_frame;
113
    int packet_padsize;
114
    int packet_frag_offset;
115
    int packet_frag_size;
116
    int packet_frag_timestamp;
117
    int packet_multi_size;
118
    int packet_obj_size;
119
    int packet_time_delta;
120
    int packet_time_start;
121
    int packet_pos;
122

    
123
    int stream_index;
124
    ASFStream* asf_st; /* currently decoded stream */
125
} ASFContext;
126

    
127
static const GUID asf_header = {
128
    0x75B22630, 0x668E, 0x11CF, { 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C },
129
};
130

    
131
static const GUID file_header = {
132
    0x8CABDCA1, 0xA947, 0x11CF, { 0x8E, 0xE4, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 },
133
};
134

    
135
static const GUID stream_header = {
136
    0xB7DC0791, 0xA9B7, 0x11CF, { 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65 },
137
};
138

    
139
static const GUID audio_stream = {
140
    0xF8699E40, 0x5B4D, 0x11CF, { 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B },
141
};
142

    
143
static const GUID audio_conceal_none = {
144
    // 0x49f1a440, 0x4ece, 0x11d0, { 0xa3, 0xac, 0x00, 0xa0, 0xc9, 0x03, 0x48, 0xf6 },
145
    // New value lifted from avifile
146
    0x20fb5700, 0x5b55, 0x11cf, { 0xa8, 0xfd, 0x00, 0x80, 0x5f, 0x5c, 0x44, 0x2b },
147
};
148

    
149
static const GUID video_stream = {
150
    0xBC19EFC0, 0x5B4D, 0x11CF, { 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B },
151
};
152

    
153
static const GUID video_conceal_none = {
154
    0x20FB5700, 0x5B55, 0x11CF, { 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B },
155
};
156

    
157

    
158
static const GUID comment_header = {
159
    0x75b22633, 0x668e, 0x11cf, { 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c },
160
};
161

    
162
static const GUID codec_comment_header = {
163
    0x86D15240, 0x311D, 0x11D0, { 0xA3, 0xA4, 0x00, 0xA0, 0xC9, 0x03, 0x48, 0xF6 },
164
};
165
static const GUID codec_comment1_header = {
166
    0x86d15241, 0x311d, 0x11d0, { 0xa3, 0xa4, 0x00, 0xa0, 0xc9, 0x03, 0x48, 0xf6 },
167
};
168

    
169
static const GUID data_header = {
170
    0x75b22636, 0x668e, 0x11cf, { 0xa6, 0xd9, 0x00, 0xaa, 0x00, 0x62, 0xce, 0x6c },
171
};
172

    
173
static const GUID index_guid = {
174
    0x33000890, 0xe5b1, 0x11cf, { 0x89, 0xf4, 0x00, 0xa0, 0xc9, 0x03, 0x49, 0xcb },
175
};
176

    
177
static const GUID head1_guid = {
178
    0x5fbf03b5, 0xa92e, 0x11cf, { 0x8e, 0xe3, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65 },
179
};
180

    
181
static const GUID head2_guid = {
182
    0xabd3d211, 0xa9ba, 0x11cf, { 0x8e, 0xe6, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65 },
183
};
184

    
185
static const GUID extended_content_header = {
186
        0xD2D0A440, 0xE307, 0x11D2, { 0x97, 0xF0, 0x00, 0xA0, 0xC9, 0x5E, 0xA8, 0x50 },
187
};
188

    
189
/* I am not a number !!! This GUID is the one found on the PC used to
190
   generate the stream */
191
static const GUID my_guid = {
192
    0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 },
193
};
194

    
195
#ifdef CONFIG_ENCODERS
196
static void put_guid(ByteIOContext *s, const GUID *g)
197
{
198
    int i;
199

    
200
    put_le32(s, g->v1);
201
    put_le16(s, g->v2);
202
    put_le16(s, g->v3);
203
    for(i=0;i<8;i++)
204
        put_byte(s, g->v4[i]);
205
}
206

    
207
static void put_str16(ByteIOContext *s, const char *tag)
208
{
209
    int c;
210

    
211
    put_le16(s,strlen(tag) + 1);
212
    for(;;) {
213
        c = (uint8_t)*tag++;
214
        put_le16(s, c);
215
        if (c == '\0')
216
            break;
217
    }
218
}
219

    
220
static void put_str16_nolen(ByteIOContext *s, const char *tag)
221
{
222
    int c;
223

    
224
    for(;;) {
225
        c = (uint8_t)*tag++;
226
        put_le16(s, c);
227
        if (c == '\0')
228
            break;
229
    }
230
}
231

    
232
static int64_t put_header(ByteIOContext *pb, const GUID *g)
233
{
234
    int64_t pos;
235

    
236
    pos = url_ftell(pb);
237
    put_guid(pb, g);
238
    put_le64(pb, 24);
239
    return pos;
240
}
241

    
242
/* update header size */
243
static void end_header(ByteIOContext *pb, int64_t pos)
244
{
245
    int64_t pos1;
246

    
247
    pos1 = url_ftell(pb);
248
    url_fseek(pb, pos + 16, SEEK_SET);
249
    put_le64(pb, pos1 - pos);
250
    url_fseek(pb, pos1, SEEK_SET);
251
}
252

    
253
/* write an asf chunk (only used in streaming case) */
254
static void put_chunk(AVFormatContext *s, int type, int payload_length, int flags)
255
{
256
    ASFContext *asf = s->priv_data;
257
    ByteIOContext *pb = &s->pb;
258
    int length;
259

    
260
    length = payload_length + 8;
261
    put_le16(pb, type);
262
    put_le16(pb, length);
263
    put_le32(pb, asf->seqno);
264
    put_le16(pb, flags); /* unknown bytes */
265
    put_le16(pb, length);
266
    asf->seqno++;
267
}
268

    
269
/* convert from unix to windows time */
270
static int64_t unix_to_file_time(int ti)
271
{
272
    int64_t t;
273

    
274
    t = ti * int64_t_C(10000000);
275
    t += int64_t_C(116444736000000000);
276
    return t;
277
}
278

    
279
/* write the header (used two times if non streamed) */
280
static int asf_write_header1(AVFormatContext *s, int64_t file_size, int64_t data_chunk_size)
281
{
282
    ASFContext *asf = s->priv_data;
283
    ByteIOContext *pb = &s->pb;
284
    int header_size, n, extra_size, extra_size2, wav_extra_size, file_time;
285
    int has_title;
286
    AVCodecContext *enc;
287
    int64_t header_offset, cur_pos, hpos;
288
    int bit_rate;
289

    
290
    has_title = (s->title[0] || s->author[0] || s->copyright[0] || s->comment[0]);
291

    
292
    bit_rate = 0;
293
    for(n=0;n<s->nb_streams;n++) {
294
        enc = &s->streams[n]->codec;
295

    
296
        bit_rate += enc->bit_rate;
297
    }
298

    
299
    if (asf->is_streamed) {
300
        put_chunk(s, 0x4824, 0, 0xc00); /* start of stream (length will be patched later) */
301
    }
302

    
303
    put_guid(pb, &asf_header);
304
    put_le64(pb, -1); /* header length, will be patched after */
305
    put_le32(pb, 3 + has_title + s->nb_streams); /* number of chunks in header */
306
    put_byte(pb, 1); /* ??? */
307
    put_byte(pb, 2); /* ??? */
308

    
309
    /* file header */
310
    header_offset = url_ftell(pb);
311
    hpos = put_header(pb, &file_header);
312
    put_guid(pb, &my_guid);
313
    put_le64(pb, file_size);
314
    file_time = 0;
315
    put_le64(pb, unix_to_file_time(file_time));
316
    put_le64(pb, asf->nb_packets); /* number of packets */
317
    put_le64(pb, asf->duration); /* end time stamp (in 100ns units) */
318
    put_le64(pb, asf->duration); /* duration (in 100ns units) */
319
    put_le32(pb, 0); /* start time stamp */
320
    put_le32(pb, 0); /* ??? */
321
    put_le32(pb, asf->is_streamed ? 1 : 0); /* ??? */
322
    put_le32(pb, asf->packet_size); /* packet size */
323
    put_le32(pb, asf->packet_size); /* packet size */
324
    put_le32(pb, bit_rate); /* Nominal data rate in bps */
325
    end_header(pb, hpos);
326

    
327
    /* unknown headers */
328
    hpos = put_header(pb, &head1_guid);
329
    put_guid(pb, &head2_guid);
330
    put_le32(pb, 6);
331
    put_le16(pb, 0);
332
    end_header(pb, hpos);
333

    
334
    /* title and other infos */
335
    if (has_title) {
336
        hpos = put_header(pb, &comment_header);
337
        put_le16(pb, 2 * (strlen(s->title) + 1));
338
        put_le16(pb, 2 * (strlen(s->author) + 1));
339
        put_le16(pb, 2 * (strlen(s->copyright) + 1));
340
        put_le16(pb, 2 * (strlen(s->comment) + 1));
341
        put_le16(pb, 0);
342
        put_str16_nolen(pb, s->title);
343
        put_str16_nolen(pb, s->author);
344
        put_str16_nolen(pb, s->copyright);
345
        put_str16_nolen(pb, s->comment);
346
        end_header(pb, hpos);
347
    }
348

    
349
    /* stream headers */
350
    for(n=0;n<s->nb_streams;n++) {
351
        int64_t es_pos;
352
        //        ASFStream *stream = &asf->streams[n];
353

    
354
        enc = &s->streams[n]->codec;
355
        asf->streams[n].num = n + 1;
356
        asf->streams[n].seq = 0;
357

    
358
        switch(enc->codec_type) {
359
        case CODEC_TYPE_AUDIO:
360
            wav_extra_size = 0;
361
            extra_size = 18 + wav_extra_size;
362
            extra_size2 = 0;
363
            break;
364
        default:
365
        case CODEC_TYPE_VIDEO:
366
            wav_extra_size = 0;
367
            extra_size = 0x33;
368
            extra_size2 = 0;
369
            break;
370
        }
371

    
372
        hpos = put_header(pb, &stream_header);
373
        if (enc->codec_type == CODEC_TYPE_AUDIO) {
374
            put_guid(pb, &audio_stream);
375
            put_guid(pb, &audio_conceal_none);
376
        } else {
377
            put_guid(pb, &video_stream);
378
            put_guid(pb, &video_conceal_none);
379
        }
380
        put_le64(pb, 0); /* ??? */
381
        es_pos = url_ftell(pb);
382
        put_le32(pb, extra_size); /* wav header len */
383
        put_le32(pb, extra_size2); /* additional data len */
384
        put_le16(pb, n + 1); /* stream number */
385
        put_le32(pb, 0); /* ??? */
386

    
387
        if (enc->codec_type == CODEC_TYPE_AUDIO) {
388
            /* WAVEFORMATEX header */
389
            int wavsize = put_wav_header(pb, enc);
390

    
391
            if (wavsize < 0)
392
                return -1;
393
            if (wavsize != extra_size) {
394
                cur_pos = url_ftell(pb);
395
                url_fseek(pb, es_pos, SEEK_SET);
396
                put_le32(pb, wavsize); /* wav header len */
397
                url_fseek(pb, cur_pos, SEEK_SET);
398
            }
399
        } else {
400
            put_le32(pb, enc->width);
401
            put_le32(pb, enc->height);
402
            put_byte(pb, 2); /* ??? */
403
            put_le16(pb, 40); /* size */
404

    
405
            /* BITMAPINFOHEADER header */
406
            put_bmp_header(pb, enc, codec_bmp_tags, 1);
407
        }
408
        end_header(pb, hpos);
409
    }
410

    
411
    /* media comments */
412

    
413
    hpos = put_header(pb, &codec_comment_header);
414
    put_guid(pb, &codec_comment1_header);
415
    put_le32(pb, s->nb_streams);
416
    for(n=0;n<s->nb_streams;n++) {
417
        AVCodec *p;
418

    
419
        enc = &s->streams[n]->codec;
420
        p = avcodec_find_encoder(enc->codec_id);
421

    
422
        put_le16(pb, asf->streams[n].num);
423
        put_str16(pb, p ? p->name : enc->codec_name);
424
        put_le16(pb, 0); /* no parameters */
425
        
426
        
427
        /* id */
428
        if (enc->codec_type == CODEC_TYPE_AUDIO) {
429
            put_le16(pb, 2);
430
            if(!enc->codec_tag)
431
                enc->codec_tag = codec_get_tag(codec_wav_tags, enc->codec_id);
432
            if(!enc->codec_tag)
433
                return -1;
434
            put_le16(pb, enc->codec_tag);
435
        } else {
436
            put_le16(pb, 4);
437
            if(!enc->codec_tag)
438
                enc->codec_tag = codec_get_tag(codec_bmp_tags, enc->codec_id);
439
            if(!enc->codec_tag)
440
                return -1;
441
            put_le32(pb, enc->codec_tag);
442
        }
443
    }
444
    end_header(pb, hpos);
445

    
446
    /* patch the header size fields */
447

    
448
    cur_pos = url_ftell(pb);
449
    header_size = cur_pos - header_offset;
450
    if (asf->is_streamed) {
451
        header_size += 8 + 30 + 50;
452

    
453
        url_fseek(pb, header_offset - 10 - 30, SEEK_SET);
454
        put_le16(pb, header_size);
455
        url_fseek(pb, header_offset - 2 - 30, SEEK_SET);
456
        put_le16(pb, header_size);
457

    
458
        header_size -= 8 + 30 + 50;
459
    }
460
    header_size += 24 + 6;
461
    url_fseek(pb, header_offset - 14, SEEK_SET);
462
    put_le64(pb, header_size);
463
    url_fseek(pb, cur_pos, SEEK_SET);
464

    
465
    /* movie chunk, followed by packets of packet_size */
466
    asf->data_offset = cur_pos;
467
    put_guid(pb, &data_header);
468
    put_le64(pb, data_chunk_size);
469
    put_guid(pb, &my_guid);
470
    put_le64(pb, asf->nb_packets); /* nb packets */
471
    put_byte(pb, 1); /* ??? */
472
    put_byte(pb, 1); /* ??? */
473
    return 0;
474
}
475

    
476
static int asf_write_header(AVFormatContext *s)
477
{
478
    ASFContext *asf = s->priv_data;
479

    
480
    av_set_pts_info(s, 32, 1, 1000); /* 32 bit pts in ms */
481

    
482
    asf->packet_size = PACKET_SIZE;
483
    asf->nb_packets = 0;
484

    
485
    if (asf_write_header1(s, 0, 50) < 0) {
486
        //av_free(asf);
487
        return -1;
488
    }
489

    
490
    put_flush_packet(&s->pb);
491

    
492
    asf->packet_nb_frames = 0;
493
    asf->packet_timestamp_start = -1;
494
    asf->packet_timestamp_end = -1;
495
    asf->packet_size_left = asf->packet_size - PACKET_HEADER_SIZE;
496
    init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
497
                  NULL, NULL, NULL, NULL);
498

    
499
    return 0;
500
}
501

    
502
static int asf_write_stream_header(AVFormatContext *s)
503
{
504
    ASFContext *asf = s->priv_data;
505

    
506
    asf->is_streamed = 1;
507

    
508
    return asf_write_header(s);
509
}
510

    
511
/* write a fixed size packet */
512
static int put_packet(AVFormatContext *s,
513
                       unsigned int timestamp, unsigned int duration,
514
                       int nb_frames, int padsize)
515
{
516
    ASFContext *asf = s->priv_data;
517
    ByteIOContext *pb = &s->pb;
518
    int flags;
519

    
520
    if (asf->is_streamed) {
521
        put_chunk(s, 0x4424, asf->packet_size, 0);
522
    }
523

    
524
    put_byte(pb, 0x82);
525
    put_le16(pb, 0);
526

    
527
    flags = 0x01; /* nb segments present */
528
    if (padsize > 0) {
529
        if (padsize < 256)
530
            flags |= 0x08;
531
        else
532
            flags |= 0x10;
533
    }
534
    put_byte(pb, flags); /* flags */
535
    put_byte(pb, 0x5d);
536
    if (flags & 0x10)
537
        put_le16(pb, padsize - 2);
538
    if (flags & 0x08)
539
        put_byte(pb, padsize - 1);
540
    put_le32(pb, timestamp);
541
    put_le16(pb, duration);
542
    put_byte(pb, nb_frames | 0x80);
543

    
544
    return PACKET_HEADER_SIZE + ((flags & 0x18) >> 3);
545
}
546

    
547
static void flush_packet(AVFormatContext *s)
548
{
549
    ASFContext *asf = s->priv_data;
550
    int hdr_size, ptr;
551

    
552
    hdr_size = put_packet(s, asf->packet_timestamp_start,
553
               asf->packet_timestamp_end - asf->packet_timestamp_start,
554
               asf->packet_nb_frames, asf->packet_size_left);
555

    
556
    /* Clear out the padding bytes */
557
    ptr = asf->packet_size - hdr_size - asf->packet_size_left;
558
    memset(asf->packet_buf + ptr, 0, asf->packet_size_left);
559

    
560
    put_buffer(&s->pb, asf->packet_buf, asf->packet_size - hdr_size);
561

    
562
    put_flush_packet(&s->pb);
563
    asf->nb_packets++;
564
    asf->packet_nb_frames = 0;
565
    asf->packet_timestamp_start = -1;
566
    asf->packet_timestamp_end = -1;
567
    asf->packet_size_left = asf->packet_size - PACKET_HEADER_SIZE;
568
    init_put_byte(&asf->pb, asf->packet_buf, asf->packet_size, 1,
569
                  NULL, NULL, NULL, NULL);
570
}
571

    
572
static void put_frame_header(AVFormatContext *s, ASFStream *stream, int timestamp,
573
                             int payload_size, int frag_offset, int frag_len)
574
{
575
    ASFContext *asf = s->priv_data;
576
    ByteIOContext *pb = &asf->pb;
577
    int val;
578

    
579
    val = stream->num;
580
    if (s->streams[val - 1]->codec.coded_frame->key_frame /* && frag_offset == 0 */)
581
        val |= 0x80;
582
    put_byte(pb, val);
583
    put_byte(pb, stream->seq);
584
    put_le32(pb, frag_offset); /* fragment offset */
585
    put_byte(pb, 0x08); /* flags */
586
    put_le32(pb, payload_size);
587
    put_le32(pb, timestamp);
588
    put_le16(pb, frag_len);
589
}
590

    
591

    
592
/* Output a frame. We suppose that payload_size <= PACKET_SIZE.
593

594
   It is there that you understand that the ASF format is really
595
   crap. They have misread the MPEG Systems spec !
596
 */
597
static void put_frame(AVFormatContext *s, ASFStream *stream, int timestamp,
598
                      const uint8_t *buf, int payload_size)
599
{
600
    ASFContext *asf = s->priv_data;
601
    int frag_pos, frag_len, frag_len1;
602

    
603
    frag_pos = 0;
604
    while (frag_pos < payload_size) {
605
        frag_len = payload_size - frag_pos;
606
        frag_len1 = asf->packet_size_left - FRAME_HEADER_SIZE;
607
        if (frag_len1 > 0) {
608
            if (frag_len > frag_len1)
609
                frag_len = frag_len1;
610
            put_frame_header(s, stream, timestamp+1, payload_size, frag_pos, frag_len);
611
            put_buffer(&asf->pb, buf, frag_len);
612
            asf->packet_size_left -= (frag_len + FRAME_HEADER_SIZE);
613
            asf->packet_timestamp_end = timestamp;
614
            if (asf->packet_timestamp_start == -1)
615
                asf->packet_timestamp_start = timestamp;
616
            asf->packet_nb_frames++;
617
        } else {
618
            frag_len = 0;
619
        }
620
        frag_pos += frag_len;
621
        buf += frag_len;
622
        /* output the frame if filled */
623
        if (asf->packet_size_left <= FRAME_HEADER_SIZE)
624
            flush_packet(s);
625
    }
626
    stream->seq++;
627
}
628

    
629

    
630
static int asf_write_packet(AVFormatContext *s, int stream_index,
631
                            const uint8_t *buf, int size, int64_t timestamp)
632
{
633
    ASFContext *asf = s->priv_data;
634
    ASFStream *stream;
635
    int64_t duration;
636
    AVCodecContext *codec;
637

    
638
    codec = &s->streams[stream_index]->codec;
639
    stream = &asf->streams[stream_index];
640

    
641
    if (codec->codec_type == CODEC_TYPE_AUDIO) {
642
        duration = (codec->frame_number * codec->frame_size * int64_t_C(10000000)) /
643
            codec->sample_rate;
644
    } else {
645
        duration = av_rescale(codec->frame_number * codec->frame_rate_base, 10000000, codec->frame_rate);
646
    }
647
    if (duration > asf->duration)
648
        asf->duration = duration;
649

    
650
    put_frame(s, stream, timestamp, buf, size);
651
    return 0;
652
}
653

    
654
static int asf_write_trailer(AVFormatContext *s)
655
{
656
    ASFContext *asf = s->priv_data;
657
    int64_t file_size;
658

    
659
    /* flush the current packet */
660
    if (asf->pb.buf_ptr > asf->pb.buffer)
661
        flush_packet(s);
662

    
663
    if (asf->is_streamed) {
664
        put_chunk(s, 0x4524, 0, 0); /* end of stream */
665
    } else {
666
        /* rewrite an updated header */
667
        file_size = url_ftell(&s->pb);
668
        url_fseek(&s->pb, 0, SEEK_SET);
669
        asf_write_header1(s, file_size, file_size - asf->data_offset);
670
    }
671

    
672
    put_flush_packet(&s->pb);
673
    return 0;
674
}
675
#endif //CONFIG_ENCODERS
676

    
677
/**********************************/
678
/* decoding */
679

    
680
//#define DEBUG
681

    
682
#ifdef DEBUG
683
#define PRINT_IF_GUID(g,cmp) \
684
if (!memcmp(g, &cmp, sizeof(GUID))) \
685
    printf("(GUID: %s) ", #cmp)
686

    
687
static void print_guid(const GUID *g)
688
{
689
    int i;
690
    PRINT_IF_GUID(g, asf_header);
691
    else PRINT_IF_GUID(g, file_header);
692
    else PRINT_IF_GUID(g, stream_header);
693
    else PRINT_IF_GUID(g, audio_stream);
694
    else PRINT_IF_GUID(g, audio_conceal_none);
695
    else PRINT_IF_GUID(g, video_stream);
696
    else PRINT_IF_GUID(g, video_conceal_none);
697
    else PRINT_IF_GUID(g, comment_header);
698
    else PRINT_IF_GUID(g, codec_comment_header);
699
    else PRINT_IF_GUID(g, codec_comment1_header);
700
    else PRINT_IF_GUID(g, data_header);
701
    else PRINT_IF_GUID(g, index_guid);
702
    else PRINT_IF_GUID(g, head1_guid);
703
    else PRINT_IF_GUID(g, head2_guid);
704
    else PRINT_IF_GUID(g, my_guid);
705
    else
706
        printf("(GUID: unknown) ");
707
    printf("0x%08x, 0x%04x, 0x%04x, {", g->v1, g->v2, g->v3);
708
    for(i=0;i<8;i++)
709
        printf(" 0x%02x,", g->v4[i]);
710
    printf("}\n");
711
}
712
#undef PRINT_IF_GUID(g,cmp)
713
#endif
714

    
715
static void get_guid(ByteIOContext *s, GUID *g)
716
{
717
    int i;
718

    
719
    g->v1 = get_le32(s);
720
    g->v2 = get_le16(s);
721
    g->v3 = get_le16(s);
722
    for(i=0;i<8;i++)
723
        g->v4[i] = get_byte(s);
724
}
725

    
726
#if 0
727
static void get_str16(ByteIOContext *pb, char *buf, int buf_size)
728
{
729
    int len, c;
730
    char *q;
731

732
    len = get_le16(pb);
733
    q = buf;
734
    while (len > 0) {
735
        c = get_le16(pb);
736
        if ((q - buf) < buf_size - 1)
737
            *q++ = c;
738
        len--;
739
    }
740
    *q = '\0';
741
}
742
#endif
743

    
744
static void get_str16_nolen(ByteIOContext *pb, int len, char *buf, int buf_size)
745
{
746
    int c;
747
    char *q;
748

    
749
    q = buf;
750
    while (len > 0) {
751
        c = get_le16(pb);
752
        if ((q - buf) < buf_size - 1)
753
            *q++ = c;
754
        len-=2;
755
    }
756
    *q = '\0';
757
}
758

    
759
static int asf_probe(AVProbeData *pd)
760
{
761
    GUID g;
762
    const unsigned char *p;
763
    int i;
764

    
765
    /* check file header */
766
    if (pd->buf_size <= 32)
767
        return 0;
768
    p = pd->buf;
769
    g.v1 = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
770
    p += 4;
771
    g.v2 = p[0] | (p[1] << 8);
772
    p += 2;
773
    g.v3 = p[0] | (p[1] << 8);
774
    p += 2;
775
    for(i=0;i<8;i++)
776
        g.v4[i] = *p++;
777

    
778
    if (!memcmp(&g, &asf_header, sizeof(GUID)))
779
        return AVPROBE_SCORE_MAX;
780
    else
781
        return 0;
782
}
783

    
784
static int asf_read_header(AVFormatContext *s, AVFormatParameters *ap)
785
{
786
    ASFContext *asf = s->priv_data;
787
    GUID g;
788
    ByteIOContext *pb = &s->pb;
789
    AVStream *st;
790
    ASFStream *asf_st;
791
    int size, i;
792
    int64_t gsize;
793

    
794
    av_set_pts_info(s, 32, 1, 1000); /* 32 bit pts in ms */
795

    
796
    get_guid(pb, &g);
797
    if (memcmp(&g, &asf_header, sizeof(GUID)))
798
        goto fail;
799
    get_le64(pb);
800
    get_le32(pb);
801
    get_byte(pb);
802
    get_byte(pb);
803
    memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid));
804
    for(;;) {
805
        get_guid(pb, &g);
806
        gsize = get_le64(pb);
807
#ifdef DEBUG
808
        printf("%08Lx: ", url_ftell(pb) - 24);
809
        print_guid(&g);
810
        printf("  size=0x%Lx\n", gsize);
811
#endif
812
        if (gsize < 24)
813
            goto fail;
814
        if (!memcmp(&g, &file_header, sizeof(GUID))) {
815
            get_guid(pb, &asf->hdr.guid);
816
            asf->hdr.file_size                = get_le64(pb);
817
            asf->hdr.create_time        = get_le64(pb);
818
            asf->hdr.packets_count        = get_le64(pb);
819
            asf->hdr.play_time                = get_le64(pb);
820
            asf->hdr.send_time                = get_le64(pb);
821
            asf->hdr.preroll                = get_le32(pb);
822
            asf->hdr.ignore                = get_le32(pb);
823
            asf->hdr.flags                = get_le32(pb);
824
            asf->hdr.min_pktsize        = get_le32(pb);
825
            asf->hdr.max_pktsize        = get_le32(pb);
826
            asf->hdr.max_bitrate        = get_le32(pb);
827
            asf->packet_size = asf->hdr.max_pktsize;
828
            asf->nb_packets = asf->hdr.packets_count;
829
        } else if (!memcmp(&g, &stream_header, sizeof(GUID))) {
830
            int type, total_size, type_specific_size;
831
            unsigned int tag1;
832
            int64_t pos1, pos2;
833

    
834
            pos1 = url_ftell(pb);
835

    
836
            st = av_new_stream(s, 0);
837
            if (!st)
838
                goto fail;
839
            asf_st = av_mallocz(sizeof(ASFStream));
840
            if (!asf_st)
841
                goto fail;
842
            st->priv_data = asf_st;
843
            st->start_time = asf->hdr.preroll / (10000000 / AV_TIME_BASE);
844
            st->duration = (asf->hdr.send_time - asf->hdr.preroll) / 
845
                (10000000 / AV_TIME_BASE);
846
            get_guid(pb, &g);
847
            if (!memcmp(&g, &audio_stream, sizeof(GUID))) {
848
                type = CODEC_TYPE_AUDIO;
849
            } else if (!memcmp(&g, &video_stream, sizeof(GUID))) {
850
                type = CODEC_TYPE_VIDEO;
851
            } else {
852
                goto fail;
853
            }
854
            get_guid(pb, &g);
855
            total_size = get_le64(pb);
856
            type_specific_size = get_le32(pb);
857
            get_le32(pb);
858
            st->id = get_le16(pb) & 0x7f; /* stream id */
859
            // mapping of asf ID to AV stream ID;
860
            asf->asfid2avid[st->id] = s->nb_streams - 1;
861

    
862
            get_le32(pb);
863
            st->codec.codec_type = type;
864
            /* 1 fps default (XXX: put 0 fps instead) */
865
            st->codec.frame_rate = 1; 
866
            st->codec.frame_rate_base = 1;
867
            if (type == CODEC_TYPE_AUDIO) {
868
                get_wav_header(pb, &st->codec, type_specific_size);
869
                st->need_parsing = 1;
870
                /* We have to init the frame size at some point .... */
871
                pos2 = url_ftell(pb);
872
                if (gsize > (pos2 + 8 - pos1 + 24)) {
873
                    asf_st->ds_span = get_byte(pb);
874
                    asf_st->ds_packet_size = get_le16(pb);
875
                    asf_st->ds_chunk_size = get_le16(pb);
876
                    asf_st->ds_data_size = get_le16(pb);
877
                    asf_st->ds_silence_data = get_byte(pb);
878
                }
879
                //printf("Descrambling: ps:%d cs:%d ds:%d s:%d  sd:%d\n",
880
                //       asf_st->ds_packet_size, asf_st->ds_chunk_size,
881
                //       asf_st->ds_data_size, asf_st->ds_span, asf_st->ds_silence_data);
882
                if (asf_st->ds_span > 1) {
883
                    if (!asf_st->ds_chunk_size
884
                        || (asf_st->ds_packet_size/asf_st->ds_chunk_size <= 1))
885
                        asf_st->ds_span = 0; // disable descrambling
886
                }
887
                switch (st->codec.codec_id) {
888
                case CODEC_ID_MP3:
889
                    st->codec.frame_size = MPA_FRAME_SIZE;
890
                    break;
891
                case CODEC_ID_PCM_S16LE:
892
                case CODEC_ID_PCM_S16BE:
893
                case CODEC_ID_PCM_U16LE:
894
                case CODEC_ID_PCM_U16BE:
895
                case CODEC_ID_PCM_S8:
896
                case CODEC_ID_PCM_U8:
897
                case CODEC_ID_PCM_ALAW:
898
                case CODEC_ID_PCM_MULAW:
899
                    st->codec.frame_size = 1;
900
                    break;
901
                default:
902
                    /* This is probably wrong, but it prevents a crash later */
903
                    st->codec.frame_size = 1;
904
                    break;
905
                }
906
            } else {
907
                get_le32(pb);
908
                get_le32(pb);
909
                get_byte(pb);
910
                size = get_le16(pb); /* size */
911
                get_le32(pb); /* size */
912
                st->codec.width = get_le32(pb);
913
                st->codec.height = get_le32(pb);
914
                /* not available for asf */
915
                get_le16(pb); /* panes */
916
                st->codec.bits_per_sample = get_le16(pb); /* depth */
917
                tag1 = get_le32(pb);
918
                url_fskip(pb, 20);
919
                if (size > 40) {
920
                    st->codec.extradata_size = size - 40;
921
                    st->codec.extradata = av_mallocz(st->codec.extradata_size);
922
                    get_buffer(pb, st->codec.extradata, st->codec.extradata_size);
923
                }
924

    
925
        /* Extract palette from extradata if bpp <= 8 */
926
        /* This code assumes that extradata contains only palette */
927
        /* This is true for all paletted codecs implemented in ffmpeg */
928
        if (st->codec.extradata_size && (st->codec.bits_per_sample <= 8)) {
929
            st->codec.palctrl = av_mallocz(sizeof(AVPaletteControl));
930
#ifdef WORDS_BIGENDIAN
931
            for (i = 0; i < FFMIN(st->codec.extradata_size, AVPALETTE_SIZE)/4; i++)
932
                st->codec.palctrl->palette[i] = bswap_32(((uint32_t*)st->codec.extradata)[i]);
933
#else
934
            memcpy(st->codec.palctrl->palette, st->codec.extradata,
935
                   FFMIN(st->codec.extradata_size, AVPALETTE_SIZE));
936
#endif
937
            st->codec.palctrl->palette_changed = 1;
938
        }
939

    
940
                st->codec.codec_tag = tag1;
941
                st->codec.codec_id = codec_get_id(codec_bmp_tags, tag1);
942
            }
943
            pos2 = url_ftell(pb);
944
            url_fskip(pb, gsize - (pos2 - pos1 + 24));
945
        } else if (!memcmp(&g, &data_header, sizeof(GUID))) {
946
            break;
947
        } else if (!memcmp(&g, &comment_header, sizeof(GUID))) {
948
            int len1, len2, len3, len4, len5;
949

    
950
            len1 = get_le16(pb);
951
            len2 = get_le16(pb);
952
            len3 = get_le16(pb);
953
            len4 = get_le16(pb);
954
            len5 = get_le16(pb);
955
            get_str16_nolen(pb, len1, s->title, sizeof(s->title));
956
            get_str16_nolen(pb, len2, s->author, sizeof(s->author));
957
            get_str16_nolen(pb, len3, s->copyright, sizeof(s->copyright));
958
            get_str16_nolen(pb, len4, s->comment, sizeof(s->comment));
959
            url_fskip(pb, len5);
960
       } else if (!memcmp(&g, &extended_content_header, sizeof(GUID))) {
961
                int desc_count, i;
962

    
963
                desc_count = get_le16(pb);
964
                for(i=0;i<desc_count;i++)
965
                {
966
                        int name_len,value_type,value_len,value_num = 0;
967
                        char *name, *value;
968

    
969
                        name_len = get_le16(pb);
970
                        name = (char *)av_mallocz(name_len);
971
                        get_str16_nolen(pb, name_len, name, name_len);
972
                        value_type = get_le16(pb);
973
                        value_len = get_le16(pb);
974
                        if ((value_type == 0) || (value_type == 1)) // unicode or byte
975
                        {
976
                                value = (char *)av_mallocz(value_len);
977
                                get_str16_nolen(pb, value_len, value, value_len);
978
                                if (strcmp(name,"WM/AlbumTitle")==0) { strcpy(s->album, value); }
979
                                av_free(value);
980
                        }
981
                        if ((value_type >= 2) || (value_type <= 5)) // boolean or DWORD or QWORD or WORD
982
                        {
983
                                if (value_type==2) value_num = get_le32(pb);
984
                                if (value_type==3) value_num = get_le32(pb);
985
                                if (value_type==4) value_num = get_le64(pb);
986
                                if (value_type==5) value_num = get_le16(pb);
987
                                if (strcmp(name,"WM/Track")==0) s->track = value_num + 1;
988
                                if (strcmp(name,"WM/TrackNumber")==0) s->track = value_num;
989
                        }
990
                        av_free(name);
991
                }
992
#if 0
993
        } else if (!memcmp(&g, &head1_guid, sizeof(GUID))) {
994
            int v1, v2;
995
            get_guid(pb, &g);
996
            v1 = get_le32(pb);
997
            v2 = get_le16(pb);
998
        } else if (!memcmp(&g, &codec_comment_header, sizeof(GUID))) {
999
            int len, v1, n, num;
1000
            char str[256], *q;
1001
            char tag[16];
1002

1003
            get_guid(pb, &g);
1004
            print_guid(&g);
1005

1006
            n = get_le32(pb);
1007
            for(i=0;i<n;i++) {
1008
                num = get_le16(pb); /* stream number */
1009
                get_str16(pb, str, sizeof(str));
1010
                get_str16(pb, str, sizeof(str));
1011
                len = get_le16(pb);
1012
                q = tag;
1013
                while (len > 0) {
1014
                    v1 = get_byte(pb);
1015
                    if ((q - tag) < sizeof(tag) - 1)
1016
                        *q++ = v1;
1017
                    len--;
1018
                }
1019
                *q = '\0';
1020
            }
1021
#endif
1022
        } else if (url_feof(pb)) {
1023
            goto fail;
1024
        } else {
1025
            url_fseek(pb, gsize - 24, SEEK_CUR);
1026
        }
1027
    }
1028
    get_guid(pb, &g);
1029
    get_le64(pb);
1030
    get_byte(pb);
1031
    get_byte(pb);
1032
    if (url_feof(pb))
1033
        goto fail;
1034
    asf->data_offset = url_ftell(pb);
1035
    asf->packet_size_left = 0;
1036

    
1037
    return 0;
1038

    
1039
 fail:
1040
     for(i=0;i<s->nb_streams;i++) {
1041
        AVStream *st = s->streams[i];
1042
        if (st) {
1043
            av_free(st->priv_data);
1044
            av_free(st->codec.extradata);
1045
        }
1046
        av_free(st);
1047
    }
1048
    return -1;
1049
}
1050

    
1051
#define DO_2BITS(bits, var, defval) \
1052
    switch (bits & 3) \
1053
    { \
1054
    case 3: var = get_le32(pb); rsize += 4; break; \
1055
    case 2: var = get_le16(pb); rsize += 2; break; \
1056
    case 1: var = get_byte(pb); rsize++; break; \
1057
    default: var = defval; break; \
1058
    }
1059

    
1060
static int asf_get_packet(AVFormatContext *s)
1061
{
1062
    ASFContext *asf = s->priv_data;
1063
    ByteIOContext *pb = &s->pb;
1064
    uint32_t packet_length, padsize;
1065
    int rsize = 11;
1066
    int c = get_byte(pb);
1067
    if (c != 0x82) {
1068
        if (!url_feof(pb))
1069
            printf("ff asf bad header %x  at:%lld\n", c, url_ftell(pb));
1070
        return -EIO;
1071
    }
1072
    if ((c & 0x0f) == 2) { // always true for now
1073
        if (get_le16(pb) != 0) {
1074
            if (!url_feof(pb))
1075
                printf("ff asf bad non zero\n");
1076
            return -EIO;
1077
        }
1078
    }
1079

    
1080
    asf->packet_flags = get_byte(pb);
1081
    asf->packet_property = get_byte(pb);
1082

    
1083
    DO_2BITS(asf->packet_flags >> 5, packet_length, asf->packet_size);
1084
    DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored
1085
    DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length
1086

    
1087
    asf->packet_timestamp = get_le32(pb);
1088
    get_le16(pb); /* duration */
1089
    // rsize has at least 11 bytes which have to be present
1090

    
1091
    if (asf->packet_flags & 0x01) {
1092
        asf->packet_segsizetype = get_byte(pb); rsize++;
1093
        asf->packet_segments = asf->packet_segsizetype & 0x3f;
1094
    } else {
1095
        asf->packet_segments = 1;
1096
        asf->packet_segsizetype = 0x80;
1097
    }
1098
    asf->packet_size_left = packet_length - padsize - rsize;
1099
    if (packet_length < asf->hdr.min_pktsize)
1100
        padsize += asf->hdr.min_pktsize - packet_length;
1101
    asf->packet_padsize = padsize;
1102
#ifdef DEBUG
1103
    printf("packet: size=%d padsize=%d  left=%d\n", asf->packet_size, asf->packet_padsize, asf->packet_size_left);
1104
#endif
1105
    return 0;
1106
}
1107

    
1108
static int asf_read_packet(AVFormatContext *s, AVPacket *pkt)
1109
{
1110
    ASFContext *asf = s->priv_data;
1111
    ASFStream *asf_st = 0;
1112
    ByteIOContext *pb = &s->pb;
1113
    //static int pc = 0;
1114
    for (;;) {
1115
        int rsize = 0;
1116
        if (asf->packet_size_left < FRAME_HEADER_SIZE
1117
            || asf->packet_segments < 1) {
1118
            //asf->packet_size_left <= asf->packet_padsize) {
1119
            int ret = asf->packet_size_left + asf->packet_padsize;
1120
            //printf("PacketLeftSize:%d  Pad:%d Pos:%Ld\n", asf->packet_size_left, asf->packet_padsize, url_ftell(pb));
1121
            /* fail safe */
1122
            url_fskip(pb, ret);
1123
            asf->packet_pos= url_ftell(&s->pb);
1124
            ret = asf_get_packet(s);
1125
            //printf("READ ASF PACKET  %d   r:%d   c:%d\n", ret, asf->packet_size_left, pc++);
1126
            if (ret < 0 || url_feof(pb))
1127
                return -EIO;
1128
            asf->packet_time_start = 0;
1129
            continue;
1130
        }
1131
        if (asf->packet_time_start == 0) {
1132
            /* read frame header */
1133
            int num = get_byte(pb);
1134
            asf->packet_segments--;
1135
            rsize++;
1136
            asf->packet_key_frame = (num & 0x80) >> 7;
1137
            asf->stream_index = asf->asfid2avid[num & 0x7f];
1138
            // sequence should be ignored!
1139
            DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0);
1140
            DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0);
1141
            DO_2BITS(asf->packet_property, asf->packet_replic_size, 0);
1142
//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);
1143
            if (asf->packet_replic_size > 1) {
1144
                assert(asf->packet_replic_size >= 8);
1145
                // it should be always at least 8 bytes - FIXME validate
1146
                asf->packet_obj_size = get_le32(pb);
1147
                asf->packet_frag_timestamp = get_le32(pb); // timestamp
1148
                if (asf->packet_replic_size > 8)
1149
                    url_fskip(pb, asf->packet_replic_size - 8);
1150
                rsize += asf->packet_replic_size; // FIXME - check validity
1151
            } else if (asf->packet_replic_size==1){
1152
                // multipacket - frag_offset is begining timestamp
1153
                asf->packet_time_start = asf->packet_frag_offset;
1154
                asf->packet_frag_offset = 0;
1155
                asf->packet_frag_timestamp = asf->packet_timestamp;
1156

    
1157
                asf->packet_time_delta = get_byte(pb);
1158
                rsize++;
1159
            }else{
1160
                assert(asf->packet_replic_size==0);
1161
            }
1162
            if (asf->packet_flags & 0x01) {
1163
                DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal
1164
#undef DO_2BITS
1165
                //printf("Fragsize %d\n", asf->packet_frag_size);
1166
            } else {
1167
                asf->packet_frag_size = asf->packet_size_left - rsize;
1168
                //printf("Using rest  %d %d %d\n", asf->packet_frag_size, asf->packet_size_left, rsize);
1169
            }
1170
            if (asf->packet_replic_size == 1) {
1171
                asf->packet_multi_size = asf->packet_frag_size;
1172
                if (asf->packet_multi_size > asf->packet_size_left) {
1173
                    asf->packet_segments = 0;
1174
                    continue;
1175
                }
1176
            }
1177
            asf->packet_size_left -= rsize;
1178
            //printf("___objsize____  %d   %d    rs:%d\n", asf->packet_obj_size, asf->packet_frag_offset, rsize);
1179

    
1180
            if (asf->stream_index < 0) {
1181
                asf->packet_time_start = 0;
1182
                /* unhandled packet (should not happen) */
1183
                url_fskip(pb, asf->packet_frag_size);
1184
                asf->packet_size_left -= asf->packet_frag_size;
1185
                printf("ff asf skip %d  %d\n", asf->packet_frag_size, num & 0x7f);
1186
                continue;
1187
            }
1188
            asf->asf_st = s->streams[asf->stream_index]->priv_data;
1189
        }
1190
        asf_st = asf->asf_st;
1191

    
1192
        if ((asf->packet_frag_offset != asf_st->frag_offset
1193
             || (asf->packet_frag_offset
1194
                 && asf->packet_seq != asf_st->seq)) // seq should be ignored
1195
           ) {
1196
            /* cannot continue current packet: free it */
1197
            // FIXME better check if packet was already allocated
1198
            printf("ff asf parser skips: %d - %d     o:%d - %d    %d %d   fl:%d\n",
1199
                   asf_st->pkt.size,
1200
                   asf->packet_obj_size,
1201
                   asf->packet_frag_offset, asf_st->frag_offset,
1202
                   asf->packet_seq, asf_st->seq, asf->packet_frag_size);
1203
            if (asf_st->pkt.size)
1204
                av_free_packet(&asf_st->pkt);
1205
            asf_st->frag_offset = 0;
1206
            if (asf->packet_frag_offset != 0) {
1207
                url_fskip(pb, asf->packet_frag_size);
1208
                printf("ff asf parser skiping %db\n", asf->packet_frag_size);
1209
                asf->packet_size_left -= asf->packet_frag_size;
1210
                continue;
1211
            }
1212
        }
1213
        if (asf->packet_replic_size == 1) {
1214
            // frag_offset is here used as the begining timestamp
1215
            asf->packet_frag_timestamp = asf->packet_time_start;
1216
            asf->packet_time_start += asf->packet_time_delta;
1217
            asf->packet_obj_size = asf->packet_frag_size = get_byte(pb);
1218
            asf->packet_size_left--;
1219
            asf->packet_multi_size--;
1220
            if (asf->packet_multi_size < asf->packet_obj_size)
1221
            {
1222
                asf->packet_time_start = 0;
1223
                url_fskip(pb, asf->packet_multi_size);
1224
                asf->packet_size_left -= asf->packet_multi_size;
1225
                continue;
1226
            }
1227
            asf->packet_multi_size -= asf->packet_obj_size;
1228
            //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);
1229
        }
1230
        if (asf_st->frag_offset == 0) {
1231
            /* new packet */
1232
            av_new_packet(&asf_st->pkt, asf->packet_obj_size);
1233
            asf_st->seq = asf->packet_seq;
1234
            asf_st->pkt.pts = asf->packet_frag_timestamp - asf->hdr.preroll;
1235
            asf_st->pkt.stream_index = asf->stream_index;
1236
            asf_st->packet_pos= asf->packet_pos;            
1237
//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n", 
1238
//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & PKT_FLAG_KEY,
1239
//s->streams[asf->stream_index]->codec.codec_type == CODEC_TYPE_AUDIO, asf->packet_obj_size);
1240
            if (s->streams[asf->stream_index]->codec.codec_type == CODEC_TYPE_AUDIO) 
1241
                asf->packet_key_frame = 1;
1242
            if (asf->packet_key_frame)
1243
                asf_st->pkt.flags |= PKT_FLAG_KEY;
1244
        }
1245

    
1246
        /* read data */
1247
        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",
1248
        //       asf->packet_size, asf_st->pkt.size, asf->packet_frag_offset,
1249
        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);
1250
        asf->packet_size_left -= asf->packet_frag_size;
1251
        if (asf->packet_size_left < 0)
1252
            continue;
1253
        get_buffer(pb, asf_st->pkt.data + asf->packet_frag_offset,
1254
                   asf->packet_frag_size);
1255
        asf_st->frag_offset += asf->packet_frag_size;
1256
        /* test if whole packet is read */
1257
        if (asf_st->frag_offset == asf_st->pkt.size) {
1258
            /* return packet */
1259
            if (asf_st->ds_span > 1) {
1260
                /* packet descrambling */
1261
                char* newdata = av_malloc(asf_st->pkt.size);
1262
                if (newdata) {
1263
                    int offset = 0;
1264
                    while (offset < asf_st->pkt.size) {
1265
                        int off = offset / asf_st->ds_chunk_size;
1266
                        int row = off / asf_st->ds_span;
1267
                        int col = off % asf_st->ds_span;
1268
                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;
1269
                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);
1270
                        memcpy(newdata + offset,
1271
                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,
1272
                               asf_st->ds_chunk_size);
1273
                        offset += asf_st->ds_chunk_size;
1274
                    }
1275
                    av_free(asf_st->pkt.data);
1276
                    asf_st->pkt.data = newdata;
1277
                }
1278
            }
1279
            asf_st->frag_offset = 0;
1280
            memcpy(pkt, &asf_st->pkt, sizeof(AVPacket));
1281
            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);
1282
            asf_st->pkt.size = 0;
1283
            asf_st->pkt.data = 0;
1284
            break; // packet completed
1285
        }
1286
    }
1287
    return 0;
1288
}
1289

    
1290
static int asf_read_close(AVFormatContext *s)
1291
{
1292
    int i;
1293

    
1294
    for(i=0;i<s->nb_streams;i++) {
1295
        AVStream *st = s->streams[i];
1296
        av_free(st->priv_data);
1297
        av_free(st->codec.extradata);
1298
    av_free(st->codec.palctrl);
1299
    }
1300
    return 0;
1301
}
1302

    
1303
// Added to support seeking after packets have been read
1304
// If information is not reset, read_packet fails due to
1305
// leftover information from previous reads
1306
static void asf_reset_header(AVFormatContext *s)
1307
{
1308
    ASFContext *asf = s->priv_data;
1309
    ASFStream *asf_st;
1310
    int i;
1311

    
1312
    asf->packet_nb_frames = 0;
1313
    asf->packet_timestamp_start = -1;
1314
    asf->packet_timestamp_end = -1;
1315
    asf->packet_size_left = 0;
1316
    asf->packet_segments = 0;
1317
    asf->packet_flags = 0;
1318
    asf->packet_property = 0;
1319
    asf->packet_timestamp = 0;
1320
    asf->packet_segsizetype = 0;
1321
    asf->packet_segments = 0;
1322
    asf->packet_seq = 0;
1323
    asf->packet_replic_size = 0;
1324
    asf->packet_key_frame = 0;
1325
    asf->packet_padsize = 0;
1326
    asf->packet_frag_offset = 0;
1327
    asf->packet_frag_size = 0;
1328
    asf->packet_frag_timestamp = 0;
1329
    asf->packet_multi_size = 0;
1330
    asf->packet_obj_size = 0;
1331
    asf->packet_time_delta = 0;
1332
    asf->packet_time_start = 0;
1333
    
1334
    for(i=0; i<s->nb_streams; i++){
1335
        asf_st= s->streams[i]->priv_data;
1336
        av_free_packet(&asf_st->pkt);
1337
        asf_st->frag_offset=0;
1338
        asf_st->seq=0;
1339
    }
1340
    asf->asf_st= NULL;
1341
}
1342

    
1343
static int64_t asf_read_pts(AVFormatContext *s, int64_t *ppos, int stream_index)
1344
{
1345
    ASFContext *asf = s->priv_data;
1346
    AVPacket pkt1, *pkt = &pkt1;
1347
    ASFStream *asf_st;
1348
    int64_t pts;
1349
    int64_t pos= *ppos;
1350

    
1351
//printf("asf_read_pts\n");
1352
    url_fseek(&s->pb, pos*asf->packet_size + s->data_offset, SEEK_SET);
1353
    asf_reset_header(s);
1354
    do{
1355
        if (av_read_frame(s, pkt) < 0){
1356
            printf("seek failed\n");
1357
                return AV_NOPTS_VALUE;
1358
        }
1359
        pts= pkt->pts;
1360

    
1361
        av_free_packet(pkt);
1362
    }while(pkt->stream_index != stream_index || !(pkt->flags&PKT_FLAG_KEY));
1363
    asf_st= s->streams[stream_index]->priv_data;
1364

    
1365
    assert((asf_st->packet_pos - s->data_offset) % asf->packet_size == 0);
1366
    *ppos= (asf_st->packet_pos - s->data_offset) / asf->packet_size;
1367
//printf("found keyframe at %Ld stream %d stamp:%Ld\n", *ppos, stream_index, pts);
1368

    
1369
    return pts;
1370
}
1371

    
1372
static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts)
1373
{
1374
    ASFContext *asf = s->priv_data;
1375
    int64_t pos;
1376
    int64_t pos_min, pos_max, pts_min, pts_max, cur_pts, pos_limit;
1377

    
1378
    if (stream_index == -1)
1379
        stream_index= av_find_default_stream_index(s);
1380
    
1381
    if (asf->packet_size <= 0)
1382
        return -1;
1383

    
1384
    pos_min = 0;
1385
    pts_min = asf_read_pts(s, &pos_min, stream_index);
1386
    if (pts_min == AV_NOPTS_VALUE) return -1;
1387
   
1388
    pos_max = (url_filesize(url_fileno(&s->pb)) - 1 - s->data_offset) / asf->packet_size; //FIXME wrong
1389
    pts_max = pts_min + s->duration;
1390
    pos_limit= pos_max;
1391

    
1392
    while (pos_min < pos_limit) {
1393
        int64_t start_pos;
1394

    
1395
        assert(pos_limit <= pos_max);
1396

    
1397
        // interpolate position (better than dichotomy)
1398
        pos = (int64_t)((double)(pos_limit - pos_min) *
1399
                        (double)(pts - pts_min) /
1400
                        (double)(pts_max - pts_min)) + pos_min;
1401
        pos/= asf->packet_size;
1402
        if(pos <= pos_min)
1403
            pos= pos_min + 1;
1404
        else if(pos > pos_limit)
1405
            pos= pos_limit;
1406
        start_pos= pos;
1407

    
1408
        // read the next timestamp 
1409
            cur_pts = asf_read_pts(s, &pos, stream_index);    
1410

    
1411
        if (cur_pts == AV_NOPTS_VALUE) {
1412
            return -1;
1413
        } else if (pts < cur_pts) {
1414
            pos_limit = start_pos - 1;
1415
            pos_max = pos;
1416
            pts_max = cur_pts;
1417
        } else {
1418
            pos_min = pos;
1419
            pts_min = cur_pts;
1420
            /* check if we are lucky */
1421
            if (pts == cur_pts)
1422
                break;
1423
        }
1424
    }
1425
    pos = pos_min;
1426
    url_fseek(&s->pb, pos*asf->packet_size + s->data_offset, SEEK_SET);
1427
    asf_reset_header(s);
1428
    return 0;
1429
}
1430

    
1431
static AVInputFormat asf_iformat = {
1432
    "asf",
1433
    "asf format",
1434
    sizeof(ASFContext),
1435
    asf_probe,
1436
    asf_read_header,
1437
    asf_read_packet,
1438
    asf_read_close,
1439
    asf_read_seek,
1440
};
1441

    
1442
#ifdef CONFIG_ENCODERS
1443
static AVOutputFormat asf_oformat = {
1444
    "asf",
1445
    "asf format",
1446
    "video/x-ms-asf",
1447
    "asf,wmv",
1448
    sizeof(ASFContext),
1449
#ifdef CONFIG_MP3LAME
1450
    CODEC_ID_MP3,
1451
#else
1452
    CODEC_ID_MP2,
1453
#endif
1454
    CODEC_ID_MSMPEG4V3,
1455
    asf_write_header,
1456
    asf_write_packet,
1457
    asf_write_trailer,
1458
};
1459

    
1460
static AVOutputFormat asf_stream_oformat = {
1461
    "asf_stream",
1462
    "asf format",
1463
    "video/x-ms-asf",
1464
    "asf,wmv",
1465
    sizeof(ASFContext),
1466
#ifdef CONFIG_MP3LAME
1467
    CODEC_ID_MP3,
1468
#else
1469
    CODEC_ID_MP2,
1470
#endif
1471
    CODEC_ID_MSMPEG4V3,
1472
    asf_write_stream_header,
1473
    asf_write_packet,
1474
    asf_write_trailer,
1475
};
1476
#endif //CONFIG_ENCODERS
1477

    
1478
int asf_init(void)
1479
{
1480
    av_register_input_format(&asf_iformat);
1481
#ifdef CONFIG_ENCODERS
1482
    av_register_output_format(&asf_oformat);
1483
    av_register_output_format(&asf_stream_oformat);
1484
#endif //CONFIG_ENCODERS
1485
    return 0;
1486
}