Statistics
| Branch: | Revision:

ffmpeg / libavformat / rmdec.c @ 74e8ccad

History | View | Annotate | Download (30.5 KB)

1
/*
2
 * "Real" 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

    
22
#include "libavutil/avstring.h"
23
#include "libavutil/intreadwrite.h"
24
#include "avformat.h"
25
#include "riff.h"
26
#include "rm.h"
27

    
28
struct RMStream {
29
    AVPacket pkt;      ///< place to store merged video frame / reordered audio data
30
    int videobufsize;  ///< current assembled frame size
31
    int videobufpos;   ///< position for the next slice in the video buffer
32
    int curpic_num;    ///< picture number of current frame
33
    int cur_slice, slices;
34
    int64_t pktpos;    ///< first slice position in file
35
    /// Audio descrambling matrix parameters
36
    int64_t audiotimestamp; ///< Audio packet timestamp
37
    int sub_packet_cnt; // Subpacket counter, used while reading
38
    int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container
39
    int audio_framesize; /// Audio frame size from container
40
    int sub_packet_lengths[16]; /// Length of each subpacket
41
};
42

    
43
typedef struct {
44
    int nb_packets;
45
    int old_format;
46
    int current_stream;
47
    int remaining_len;
48
    int audio_stream_num; ///< Stream number for audio packets
49
    int audio_pkt_cnt; ///< Output packet counter
50
} RMDemuxContext;
51

    
52
static const unsigned char sipr_swaps[38][2] = {
53
    {  0, 63 }, {  1, 22 }, {  2, 44 }, {  3, 90 },
54
    {  5, 81 }, {  7, 31 }, {  8, 86 }, {  9, 58 },
55
    { 10, 36 }, { 12, 68 }, { 13, 39 }, { 14, 73 },
56
    { 15, 53 }, { 16, 69 }, { 17, 57 }, { 19, 88 },
57
    { 20, 34 }, { 21, 71 }, { 24, 46 }, { 25, 94 },
58
    { 26, 54 }, { 28, 75 }, { 29, 50 }, { 32, 70 },
59
    { 33, 92 }, { 35, 74 }, { 38, 85 }, { 40, 56 },
60
    { 42, 87 }, { 43, 65 }, { 45, 59 }, { 48, 79 },
61
    { 49, 93 }, { 51, 89 }, { 55, 95 }, { 61, 76 },
62
    { 67, 83 }, { 77, 80 }
63
};
64

    
65
const unsigned char ff_sipr_subpk_size[4] = { 29, 19, 37, 20 };
66

    
67
static inline void get_strl(ByteIOContext *pb, char *buf, int buf_size, int len)
68
{
69
    int i;
70
    char *q, r;
71

    
72
    q = buf;
73
    for(i=0;i<len;i++) {
74
        r = get_byte(pb);
75
        if (i < buf_size - 1)
76
            *q++ = r;
77
    }
78
    if (buf_size > 0) *q = '\0';
79
}
80

    
81
static void get_str8(ByteIOContext *pb, char *buf, int buf_size)
82
{
83
    get_strl(pb, buf, buf_size, get_byte(pb));
84
}
85

    
86
static int rm_read_extradata(ByteIOContext *pb, AVCodecContext *avctx, unsigned size)
87
{
88
    if (size >= 1<<24)
89
        return -1;
90
    avctx->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
91
    if (!avctx->extradata)
92
        return AVERROR(ENOMEM);
93
    avctx->extradata_size = get_buffer(pb, avctx->extradata, size);
94
    memset(avctx->extradata + avctx->extradata_size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
95
    if (avctx->extradata_size != size)
96
        return AVERROR(EIO);
97
    return 0;
98
}
99

    
100
static void rm_read_metadata(AVFormatContext *s, int wide)
101
{
102
    char buf[1024];
103
    int i;
104
    for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
105
        int len = wide ? get_be16(s->pb) : get_byte(s->pb);
106
        get_strl(s->pb, buf, sizeof(buf), len);
107
        av_metadata_set2(&s->metadata, ff_rm_metadata[i], buf, 0);
108
    }
109
}
110

    
111
RMStream *ff_rm_alloc_rmstream (void)
112
{
113
    RMStream *rms = av_mallocz(sizeof(RMStream));
114
    rms->curpic_num = -1;
115
    return rms;
116
}
117

    
118
void ff_rm_free_rmstream (RMStream *rms)
119
{
120
    av_free_packet(&rms->pkt);
121
}
122

    
123
static int rm_read_audio_stream_info(AVFormatContext *s, ByteIOContext *pb,
124
                                     AVStream *st, RMStream *ast, int read_all)
125
{
126
    char buf[256];
127
    uint32_t version;
128
    int ret;
129

    
130
    /* ra type header */
131
    version = get_be16(pb); /* version */
132
    if (version == 3) {
133
        int header_size = get_be16(pb);
134
        int64_t startpos = url_ftell(pb);
135
        url_fskip(pb, 14);
136
        rm_read_metadata(s, 0);
137
        if ((startpos + header_size) >= url_ftell(pb) + 2) {
138
            // fourcc (should always be "lpcJ")
139
            get_byte(pb);
140
            get_str8(pb, buf, sizeof(buf));
141
        }
142
        // Skip extra header crap (this should never happen)
143
        if ((startpos + header_size) > url_ftell(pb))
144
            url_fskip(pb, header_size + startpos - url_ftell(pb));
145
        st->codec->sample_rate = 8000;
146
        st->codec->channels = 1;
147
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
148
        st->codec->codec_id = CODEC_ID_RA_144;
149
    } else {
150
        int flavor, sub_packet_h, coded_framesize, sub_packet_size;
151
        int codecdata_length;
152
        /* old version (4) */
153
        url_fskip(pb, 2); /* unused */
154
        get_be32(pb); /* .ra4 */
155
        get_be32(pb); /* data size */
156
        get_be16(pb); /* version2 */
157
        get_be32(pb); /* header size */
158
        flavor= get_be16(pb); /* add codec info / flavor */
159
        ast->coded_framesize = coded_framesize = get_be32(pb); /* coded frame size */
160
        get_be32(pb); /* ??? */
161
        get_be32(pb); /* ??? */
162
        get_be32(pb); /* ??? */
163
        ast->sub_packet_h = sub_packet_h = get_be16(pb); /* 1 */
164
        st->codec->block_align= get_be16(pb); /* frame size */
165
        ast->sub_packet_size = sub_packet_size = get_be16(pb); /* sub packet size */
166
        get_be16(pb); /* ??? */
167
        if (version == 5) {
168
            get_be16(pb); get_be16(pb); get_be16(pb);
169
        }
170
        st->codec->sample_rate = get_be16(pb);
171
        get_be32(pb);
172
        st->codec->channels = get_be16(pb);
173
        if (version == 5) {
174
            get_be32(pb);
175
            get_buffer(pb, buf, 4);
176
            buf[4] = 0;
177
        } else {
178
            get_str8(pb, buf, sizeof(buf)); /* desc */
179
            get_str8(pb, buf, sizeof(buf)); /* desc */
180
        }
181
        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
182
        st->codec->codec_tag  = AV_RL32(buf);
183
        st->codec->codec_id   = ff_codec_get_id(ff_rm_codec_tags,
184
                                                st->codec->codec_tag);
185
        switch (st->codec->codec_id) {
186
        case CODEC_ID_AC3:
187
            st->need_parsing = AVSTREAM_PARSE_FULL;
188
            break;
189
        case CODEC_ID_RA_288:
190
            st->codec->extradata_size= 0;
191
            ast->audio_framesize = st->codec->block_align;
192
            st->codec->block_align = coded_framesize;
193

    
194
            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
195
                av_log(s, AV_LOG_ERROR, "ast->audio_framesize * sub_packet_h too large\n");
196
                return -1;
197
            }
198

    
199
            av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);
200
            break;
201
        case CODEC_ID_COOK:
202
        case CODEC_ID_ATRAC3:
203
        case CODEC_ID_SIPR:
204
            get_be16(pb); get_byte(pb);
205
            if (version == 5)
206
                get_byte(pb);
207
            codecdata_length = get_be32(pb);
208
            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
209
                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
210
                return -1;
211
            }
212

    
213
            ast->audio_framesize = st->codec->block_align;
214
            if (st->codec->codec_id == CODEC_ID_SIPR) {
215
                if (flavor > 3) {
216
                    av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",
217
                           flavor);
218
                    return -1;
219
                }
220
                st->codec->block_align = ff_sipr_subpk_size[flavor];
221
            } else {
222
                if(sub_packet_size <= 0){
223
                    av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");
224
                    return -1;
225
                }
226
                st->codec->block_align = ast->sub_packet_size;
227
            }
228
            if ((ret = rm_read_extradata(pb, st->codec, codecdata_length)) < 0)
229
                return ret;
230

    
231
            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
232
                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
233
                return -1;
234
            }
235

    
236
            av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h);
237
            break;
238
        case CODEC_ID_AAC:
239
            get_be16(pb); get_byte(pb);
240
            if (version == 5)
241
                get_byte(pb);
242
            codecdata_length = get_be32(pb);
243
            if(codecdata_length + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
244
                av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
245
                return -1;
246
            }
247
            if (codecdata_length >= 1) {
248
                get_byte(pb);
249
                if ((ret = rm_read_extradata(pb, st->codec, codecdata_length - 1)) < 0)
250
                    return ret;
251
            }
252
            break;
253
        default:
254
            av_strlcpy(st->codec->codec_name, buf, sizeof(st->codec->codec_name));
255
        }
256
        if (read_all) {
257
            get_byte(pb);
258
            get_byte(pb);
259
            get_byte(pb);
260
            rm_read_metadata(s, 0);
261
        }
262
    }
263
    return 0;
264
}
265

    
266
int
267
ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
268
                           AVStream *st, RMStream *rst, int codec_data_size)
269
{
270
    unsigned int v;
271
    int size;
272
    int64_t codec_pos;
273
    int ret;
274

    
275
    av_set_pts_info(st, 64, 1, 1000);
276
    codec_pos = url_ftell(pb);
277
    v = get_be32(pb);
278
    if (v == MKTAG(0xfd, 'a', 'r', '.')) {
279
        /* ra type header */
280
        if (rm_read_audio_stream_info(s, pb, st, rst, 0))
281
            return -1;
282
    } else {
283
        int fps, fps2;
284
        if (get_le32(pb) != MKTAG('V', 'I', 'D', 'O')) {
285
        fail1:
286
            av_log(st->codec, AV_LOG_ERROR, "Unsupported video codec\n");
287
            goto skip;
288
        }
289
        st->codec->codec_tag = get_le32(pb);
290
        st->codec->codec_id  = ff_codec_get_id(ff_rm_codec_tags,
291
                                               st->codec->codec_tag);
292
//        av_log(s, AV_LOG_DEBUG, "%X %X\n", st->codec->codec_tag, MKTAG('R', 'V', '2', '0'));
293
        if (st->codec->codec_id == CODEC_ID_NONE)
294
            goto fail1;
295
        st->codec->width = get_be16(pb);
296
        st->codec->height = get_be16(pb);
297
        st->codec->time_base.num= 1;
298
        fps= get_be16(pb);
299
        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
300
        get_be32(pb);
301
        fps2= get_be16(pb);
302
        get_be16(pb);
303

    
304
        if ((ret = rm_read_extradata(pb, st->codec, codec_data_size - (url_ftell(pb) - codec_pos))) < 0)
305
            return ret;
306

    
307
//        av_log(s, AV_LOG_DEBUG, "fps= %d fps2= %d\n", fps, fps2);
308
        st->codec->time_base.den = fps * st->codec->time_base.num;
309
        //XXX: do we really need that?
310
        switch(st->codec->extradata[4]>>4){
311
        case 1: st->codec->codec_id = CODEC_ID_RV10; break;
312
        case 2: st->codec->codec_id = CODEC_ID_RV20; break;
313
        case 3: st->codec->codec_id = CODEC_ID_RV30; break;
314
        case 4: st->codec->codec_id = CODEC_ID_RV40; break;
315
        default:
316
            av_log(st->codec, AV_LOG_ERROR, "extra:%02X %02X %02X %02X %02X\n", st->codec->extradata[0], st->codec->extradata[1], st->codec->extradata[2], st->codec->extradata[3], st->codec->extradata[4]);
317
            goto fail1;
318
        }
319
    }
320

    
321
skip:
322
    /* skip codec info */
323
    size = url_ftell(pb) - codec_pos;
324
    url_fskip(pb, codec_data_size - size);
325

    
326
    return 0;
327
}
328

    
329
/** this function assumes that the demuxer has already seeked to the start
330
 * of the INDX chunk, and will bail out if not. */
331
static int rm_read_index(AVFormatContext *s)
332
{
333
    ByteIOContext *pb = s->pb;
334
    unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
335
    AVStream *st;
336

    
337
    do {
338
        if (get_le32(pb) != MKTAG('I','N','D','X'))
339
            return -1;
340
        size     = get_be32(pb);
341
        if (size < 20)
342
            return -1;
343
        url_fskip(pb, 2);
344
        n_pkts   = get_be32(pb);
345
        str_id   = get_be16(pb);
346
        next_off = get_be32(pb);
347
        for (n = 0; n < s->nb_streams; n++)
348
            if (s->streams[n]->id == str_id) {
349
                st = s->streams[n];
350
                break;
351
            }
352
        if (n == s->nb_streams)
353
            goto skip;
354

    
355
        for (n = 0; n < n_pkts; n++) {
356
            url_fskip(pb, 2);
357
            pts = get_be32(pb);
358
            pos = get_be32(pb);
359
            url_fskip(pb, 4); /* packet no. */
360

    
361
            av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
362
        }
363

    
364
skip:
365
        if (next_off && url_ftell(pb) != next_off &&
366
            url_fseek(pb, next_off, SEEK_SET) < 0)
367
            return -1;
368
    } while (next_off);
369

    
370
    return 0;
371
}
372

    
373
static int rm_read_header_old(AVFormatContext *s, AVFormatParameters *ap)
374
{
375
    RMDemuxContext *rm = s->priv_data;
376
    AVStream *st;
377

    
378
    rm->old_format = 1;
379
    st = av_new_stream(s, 0);
380
    if (!st)
381
        return -1;
382
    st->priv_data = ff_rm_alloc_rmstream();
383
    return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1);
384
}
385

    
386
static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
387
{
388
    RMDemuxContext *rm = s->priv_data;
389
    AVStream *st;
390
    ByteIOContext *pb = s->pb;
391
    unsigned int tag;
392
    int tag_size;
393
    unsigned int start_time, duration;
394
    unsigned int data_off = 0, indx_off = 0;
395
    char buf[128];
396
    int flags = 0;
397

    
398
    tag = get_le32(pb);
399
    if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
400
        /* very old .ra format */
401
        return rm_read_header_old(s, ap);
402
    } else if (tag != MKTAG('.', 'R', 'M', 'F')) {
403
        return AVERROR(EIO);
404
    }
405

    
406
    get_be32(pb); /* header size */
407
    get_be16(pb);
408
    get_be32(pb);
409
    get_be32(pb); /* number of headers */
410

    
411
    for(;;) {
412
        if (url_feof(pb))
413
            return -1;
414
        tag = get_le32(pb);
415
        tag_size = get_be32(pb);
416
        get_be16(pb);
417
#if 0
418
        printf("tag=%c%c%c%c (%08x) size=%d\n",
419
               (tag) & 0xff,
420
               (tag >> 8) & 0xff,
421
               (tag >> 16) & 0xff,
422
               (tag >> 24) & 0xff,
423
               tag,
424
               tag_size);
425
#endif
426
        if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A'))
427
            return -1;
428
        switch(tag) {
429
        case MKTAG('P', 'R', 'O', 'P'):
430
            /* file header */
431
            get_be32(pb); /* max bit rate */
432
            get_be32(pb); /* avg bit rate */
433
            get_be32(pb); /* max packet size */
434
            get_be32(pb); /* avg packet size */
435
            get_be32(pb); /* nb packets */
436
            get_be32(pb); /* duration */
437
            get_be32(pb); /* preroll */
438
            indx_off = get_be32(pb); /* index offset */
439
            data_off = get_be32(pb); /* data offset */
440
            get_be16(pb); /* nb streams */
441
            flags = get_be16(pb); /* flags */
442
            break;
443
        case MKTAG('C', 'O', 'N', 'T'):
444
            rm_read_metadata(s, 1);
445
            break;
446
        case MKTAG('M', 'D', 'P', 'R'):
447
            st = av_new_stream(s, 0);
448
            if (!st)
449
                return AVERROR(ENOMEM);
450
            st->id = get_be16(pb);
451
            get_be32(pb); /* max bit rate */
452
            st->codec->bit_rate = get_be32(pb); /* bit rate */
453
            get_be32(pb); /* max packet size */
454
            get_be32(pb); /* avg packet size */
455
            start_time = get_be32(pb); /* start time */
456
            get_be32(pb); /* preroll */
457
            duration = get_be32(pb); /* duration */
458
            st->start_time = start_time;
459
            st->duration = duration;
460
            get_str8(pb, buf, sizeof(buf)); /* desc */
461
            get_str8(pb, buf, sizeof(buf)); /* mimetype */
462
            st->codec->codec_type = AVMEDIA_TYPE_DATA;
463
            st->priv_data = ff_rm_alloc_rmstream();
464
            if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data,
465
                                          get_be32(pb)) < 0)
466
                return -1;
467
            break;
468
        case MKTAG('D', 'A', 'T', 'A'):
469
            goto header_end;
470
        default:
471
            /* unknown tag: skip it */
472
            url_fskip(pb, tag_size - 10);
473
            break;
474
        }
475
    }
476
 header_end:
477
    rm->nb_packets = get_be32(pb); /* number of packets */
478
    if (!rm->nb_packets && (flags & 4))
479
        rm->nb_packets = 3600 * 25;
480
    get_be32(pb); /* next data header */
481

    
482
    if (!data_off)
483
        data_off = url_ftell(pb) - 18;
484
    if (indx_off && url_fseek(pb, indx_off, SEEK_SET) >= 0) {
485
        rm_read_index(s);
486
        url_fseek(pb, data_off + 18, SEEK_SET);
487
    }
488

    
489
    return 0;
490
}
491

    
492
static int get_num(ByteIOContext *pb, int *len)
493
{
494
    int n, n1;
495

    
496
    n = get_be16(pb);
497
    (*len)-=2;
498
    n &= 0x7FFF;
499
    if (n >= 0x4000) {
500
        return n - 0x4000;
501
    } else {
502
        n1 = get_be16(pb);
503
        (*len)-=2;
504
        return (n << 16) | n1;
505
    }
506
}
507

    
508
/* multiple of 20 bytes for ra144 (ugly) */
509
#define RAW_PACKET_SIZE 1000
510

    
511
static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
512
    RMDemuxContext *rm = s->priv_data;
513
    ByteIOContext *pb = s->pb;
514
    AVStream *st;
515
    uint32_t state=0xFFFFFFFF;
516

    
517
    while(!url_feof(pb)){
518
        int len, num, i;
519
        *pos= url_ftell(pb) - 3;
520
        if(rm->remaining_len > 0){
521
            num= rm->current_stream;
522
            len= rm->remaining_len;
523
            *timestamp = AV_NOPTS_VALUE;
524
            *flags= 0;
525
        }else{
526
            state= (state<<8) + get_byte(pb);
527

    
528
            if(state == MKBETAG('I', 'N', 'D', 'X')){
529
                int n_pkts, expected_len;
530
                len = get_be32(pb);
531
                url_fskip(pb, 2);
532
                n_pkts = get_be32(pb);
533
                expected_len = 20 + n_pkts * 14;
534
                if (len == 20)
535
                    /* some files don't add index entries to chunk size... */
536
                    len = expected_len;
537
                else if (len != expected_len)
538
                    av_log(s, AV_LOG_WARNING,
539
                           "Index size %d (%d pkts) is wrong, should be %d.\n",
540
                           len, n_pkts, expected_len);
541
                len -= 14; // we already read part of the index header
542
                if(len<0)
543
                    continue;
544
                goto skip;
545
            } else if (state == MKBETAG('D','A','T','A')) {
546
                av_log(s, AV_LOG_WARNING,
547
                       "DATA tag in middle of chunk, file may be broken.\n");
548
            }
549

    
550
            if(state > (unsigned)0xFFFF || state <= 12)
551
                continue;
552
            len=state - 12;
553
            state= 0xFFFFFFFF;
554

    
555
            num = get_be16(pb);
556
            *timestamp = get_be32(pb);
557
            get_byte(pb); /* reserved */
558
            *flags = get_byte(pb); /* flags */
559
        }
560
        for(i=0;i<s->nb_streams;i++) {
561
            st = s->streams[i];
562
            if (num == st->id)
563
                break;
564
        }
565
        if (i == s->nb_streams) {
566
skip:
567
            /* skip packet if unknown number */
568
            url_fskip(pb, len);
569
            rm->remaining_len = 0;
570
            continue;
571
        }
572
        *stream_index= i;
573

    
574
        return len;
575
    }
576
    return -1;
577
}
578

    
579
static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
580
                                   RMDemuxContext *rm, RMStream *vst,
581
                                   AVPacket *pkt, int len, int *pseq)
582
{
583
    int hdr, seq, pic_num, len2, pos;
584
    int type;
585

    
586
    hdr = get_byte(pb); len--;
587
    type = hdr >> 6;
588

    
589
    if(type != 3){  // not frame as a part of packet
590
        seq = get_byte(pb); len--;
591
    }
592
    if(type != 1){  // not whole frame
593
        len2 = get_num(pb, &len);
594
        pos  = get_num(pb, &len);
595
        pic_num = get_byte(pb); len--;
596
    }
597
    if(len<0)
598
        return -1;
599
    rm->remaining_len = len;
600
    if(type&1){     // frame, not slice
601
        if(type == 3)  // frame as a part of packet
602
            len= len2;
603
        if(rm->remaining_len < len)
604
            return -1;
605
        rm->remaining_len -= len;
606
        if(av_new_packet(pkt, len + 9) < 0)
607
            return AVERROR(EIO);
608
        pkt->data[0] = 0;
609
        AV_WL32(pkt->data + 1, 1);
610
        AV_WL32(pkt->data + 5, 0);
611
        get_buffer(pb, pkt->data + 9, len);
612
        return 0;
613
    }
614
    //now we have to deal with single slice
615

    
616
    *pseq = seq;
617
    if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
618
        vst->slices = ((hdr & 0x3F) << 1) + 1;
619
        vst->videobufsize = len2 + 8*vst->slices + 1;
620
        av_free_packet(&vst->pkt); //FIXME this should be output.
621
        if(av_new_packet(&vst->pkt, vst->videobufsize) < 0)
622
            return AVERROR(ENOMEM);
623
        vst->videobufpos = 8*vst->slices + 1;
624
        vst->cur_slice = 0;
625
        vst->curpic_num = pic_num;
626
        vst->pktpos = url_ftell(pb);
627
    }
628
    if(type == 2)
629
        len = FFMIN(len, pos);
630

    
631
    if(++vst->cur_slice > vst->slices)
632
        return 1;
633
    AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
634
    AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
635
    if(vst->videobufpos + len > vst->videobufsize)
636
        return 1;
637
    if (get_buffer(pb, vst->pkt.data + vst->videobufpos, len) != len)
638
        return AVERROR(EIO);
639
    vst->videobufpos += len;
640
    rm->remaining_len-= len;
641

    
642
    if(type == 2 || (vst->videobufpos) == vst->videobufsize){
643
        vst->pkt.data[0] = vst->cur_slice-1;
644
        *pkt= vst->pkt;
645
        vst->pkt.data= NULL;
646
        vst->pkt.size= 0;
647
        if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
648
            memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
649
                vst->videobufpos - 1 - 8*vst->slices);
650
        pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices);
651
        pkt->pts = AV_NOPTS_VALUE;
652
        pkt->pos = vst->pktpos;
653
        vst->slices = 0;
654
        return 0;
655
    }
656

    
657
    return 1;
658
}
659

    
660
static inline void
661
rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt)
662
{
663
    uint8_t *ptr;
664
    int j;
665

    
666
    if (st->codec->codec_id == CODEC_ID_AC3) {
667
        ptr = pkt->data;
668
        for (j=0;j<pkt->size;j+=2) {
669
            FFSWAP(int, ptr[0], ptr[1]);
670
            ptr += 2;
671
        }
672
    }
673
}
674

    
675
/**
676
 * Perform 4-bit block reordering for SIPR data.
677
 * @todo This can be optimized, e.g. use memcpy() if data blocks are aligned
678
 */
679
void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize)
680
{
681
    int n, bs = sub_packet_h * framesize * 2 / 96; // nibbles per subpacket
682

    
683
    for (n = 0; n < 38; n++) {
684
        int j;
685
        int i = bs * sipr_swaps[n][0];
686
        int o = bs * sipr_swaps[n][1];
687

    
688
        /* swap 4bit-nibbles of block 'i' with 'o' */
689
        for (j = 0; j < bs; j++, i++, o++) {
690
            int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
691
                y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
692

    
693
            buf[o >> 1] = (x << (4 * (o & 1))) |
694
                (buf[o >> 1] & (0xF << (4 * !(o & 1))));
695
            buf[i >> 1] = (y << (4 * (i & 1))) |
696
                (buf[i >> 1] & (0xF << (4 * !(i & 1))));
697
        }
698
    }
699
}
700

    
701
int
702
ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
703
                    AVStream *st, RMStream *ast, int len, AVPacket *pkt,
704
                    int *seq, int flags, int64_t timestamp)
705
{
706
    RMDemuxContext *rm = s->priv_data;
707

    
708
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
709
        rm->current_stream= st->id;
710
        if(rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq))
711
            return -1; //got partial frame
712
    } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
713
        if ((st->codec->codec_id == CODEC_ID_RA_288) ||
714
            (st->codec->codec_id == CODEC_ID_COOK) ||
715
            (st->codec->codec_id == CODEC_ID_ATRAC3) ||
716
            (st->codec->codec_id == CODEC_ID_SIPR)) {
717
            int x;
718
            int sps = ast->sub_packet_size;
719
            int cfs = ast->coded_framesize;
720
            int h = ast->sub_packet_h;
721
            int y = ast->sub_packet_cnt;
722
            int w = ast->audio_framesize;
723

    
724
            if (flags & 2)
725
                y = ast->sub_packet_cnt = 0;
726
            if (!y)
727
                ast->audiotimestamp = timestamp;
728

    
729
            switch(st->codec->codec_id) {
730
                case CODEC_ID_RA_288:
731
                    for (x = 0; x < h/2; x++)
732
                        get_buffer(pb, ast->pkt.data+x*2*w+y*cfs, cfs);
733
                    break;
734
                case CODEC_ID_ATRAC3:
735
                case CODEC_ID_COOK:
736
                    for (x = 0; x < w/sps; x++)
737
                        get_buffer(pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
738
                    break;
739
                case CODEC_ID_SIPR:
740
                    get_buffer(pb, ast->pkt.data + y * w, w);
741
                    break;
742
            }
743

    
744
            if (++(ast->sub_packet_cnt) < h)
745
                return -1;
746
            if (st->codec->codec_id == CODEC_ID_SIPR)
747
                ff_rm_reorder_sipr_data(ast->pkt.data, h, w);
748

    
749
             ast->sub_packet_cnt = 0;
750
             rm->audio_stream_num = st->index;
751
             rm->audio_pkt_cnt = h * w / st->codec->block_align;
752
        } else if (st->codec->codec_id == CODEC_ID_AAC) {
753
            int x;
754
            rm->audio_stream_num = st->index;
755
            ast->sub_packet_cnt = (get_be16(pb) & 0xf0) >> 4;
756
            if (ast->sub_packet_cnt) {
757
                for (x = 0; x < ast->sub_packet_cnt; x++)
758
                    ast->sub_packet_lengths[x] = get_be16(pb);
759
                rm->audio_pkt_cnt = ast->sub_packet_cnt;
760
                ast->audiotimestamp = timestamp;
761
            } else
762
                return -1;
763
        } else {
764
            av_get_packet(pb, pkt, len);
765
            rm_ac3_swap_bytes(st, pkt);
766
        }
767
    } else
768
        av_get_packet(pb, pkt, len);
769

    
770
    pkt->stream_index = st->index;
771

    
772
#if 0
773
    if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
774
        if(st->codec->codec_id == CODEC_ID_RV20){
775
            int seq= 128*(pkt->data[2]&0x7F) + (pkt->data[3]>>1);
776
            av_log(s, AV_LOG_DEBUG, "%d %"PRId64" %d\n", *timestamp, *timestamp*512LL/25, seq);
777

778
            seq |= (timestamp&~0x3FFF);
779
            if(seq - timestamp >  0x2000) seq -= 0x4000;
780
            if(seq - timestamp < -0x2000) seq += 0x4000;
781
        }
782
    }
783
#endif
784

    
785
    pkt->pts= timestamp;
786
    if (flags & 2)
787
        pkt->flags |= AV_PKT_FLAG_KEY;
788

    
789
    return st->codec->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;
790
}
791

    
792
int
793
ff_rm_retrieve_cache (AVFormatContext *s, ByteIOContext *pb,
794
                      AVStream *st, RMStream *ast, AVPacket *pkt)
795
{
796
    RMDemuxContext *rm = s->priv_data;
797

    
798
    assert (rm->audio_pkt_cnt > 0);
799

    
800
    if (st->codec->codec_id == CODEC_ID_AAC)
801
        av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);
802
    else {
803
        av_new_packet(pkt, st->codec->block_align);
804
        memcpy(pkt->data, ast->pkt.data + st->codec->block_align * //FIXME avoid this
805
               (ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),
806
               st->codec->block_align);
807
    }
808
    rm->audio_pkt_cnt--;
809
    if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {
810
        ast->audiotimestamp = AV_NOPTS_VALUE;
811
        pkt->flags = AV_PKT_FLAG_KEY;
812
    } else
813
        pkt->flags = 0;
814
    pkt->stream_index = st->index;
815

    
816
    return rm->audio_pkt_cnt;
817
}
818

    
819
static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
820
{
821
    RMDemuxContext *rm = s->priv_data;
822
    AVStream *st;
823
    int i, len, res, seq = 1;
824
    int64_t timestamp, pos;
825
    int flags;
826

    
827
    for (;;) {
828
        if (rm->audio_pkt_cnt) {
829
            // If there are queued audio packet return them first
830
            st = s->streams[rm->audio_stream_num];
831
            ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
832
            flags = 0;
833
        } else {
834
            if (rm->old_format) {
835
                RMStream *ast;
836

    
837
                st = s->streams[0];
838
                ast = st->priv_data;
839
                timestamp = AV_NOPTS_VALUE;
840
                len = !ast->audio_framesize ? RAW_PACKET_SIZE :
841
                    ast->coded_framesize * ast->sub_packet_h / 2;
842
                flags = (seq++ == 1) ? 2 : 0;
843
                pos = url_ftell(s->pb);
844
            } else {
845
                len=sync(s, &timestamp, &flags, &i, &pos);
846
                if (len > 0)
847
                    st = s->streams[i];
848
            }
849

    
850
            if(len<0 || url_feof(s->pb))
851
                return AVERROR(EIO);
852

    
853
            res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
854
                                      &seq, flags, timestamp);
855
            if((flags&2) && (seq&0x7F) == 1)
856
                av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
857
            if (res)
858
                continue;
859
        }
860

    
861
        if(  (st->discard >= AVDISCARD_NONKEY && !(flags&2))
862
           || st->discard >= AVDISCARD_ALL){
863
            av_free_packet(pkt);
864
        } else
865
            break;
866
    }
867

    
868
    return 0;
869
}
870

    
871
static int rm_read_close(AVFormatContext *s)
872
{
873
    int i;
874

    
875
    for (i=0;i<s->nb_streams;i++)
876
        ff_rm_free_rmstream(s->streams[i]->priv_data);
877

    
878
    return 0;
879
}
880

    
881
static int rm_probe(AVProbeData *p)
882
{
883
    /* check file header */
884
    if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
885
         p->buf[2] == 'M' && p->buf[3] == 'F' &&
886
         p->buf[4] == 0 && p->buf[5] == 0) ||
887
        (p->buf[0] == '.' && p->buf[1] == 'r' &&
888
         p->buf[2] == 'a' && p->buf[3] == 0xfd))
889
        return AVPROBE_SCORE_MAX;
890
    else
891
        return 0;
892
}
893

    
894
static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
895
                               int64_t *ppos, int64_t pos_limit)
896
{
897
    RMDemuxContext *rm = s->priv_data;
898
    int64_t pos, dts;
899
    int stream_index2, flags, len, h;
900

    
901
    pos = *ppos;
902

    
903
    if(rm->old_format)
904
        return AV_NOPTS_VALUE;
905

    
906
    url_fseek(s->pb, pos, SEEK_SET);
907
    rm->remaining_len=0;
908
    for(;;){
909
        int seq=1;
910
        AVStream *st;
911

    
912
        len=sync(s, &dts, &flags, &stream_index2, &pos);
913
        if(len<0)
914
            return AV_NOPTS_VALUE;
915

    
916
        st = s->streams[stream_index2];
917
        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
918
            h= get_byte(s->pb); len--;
919
            if(!(h & 0x40)){
920
                seq = get_byte(s->pb); len--;
921
            }
922
        }
923

    
924
        if((flags&2) && (seq&0x7F) == 1){
925
//            av_log(s, AV_LOG_DEBUG, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq);
926
            av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
927
            if(stream_index2 == stream_index)
928
                break;
929
        }
930

    
931
        url_fskip(s->pb, len);
932
    }
933
    *ppos = pos;
934
    return dts;
935
}
936

    
937
AVInputFormat rm_demuxer = {
938
    "rm",
939
    NULL_IF_CONFIG_SMALL("RealMedia format"),
940
    sizeof(RMDemuxContext),
941
    rm_probe,
942
    rm_read_header,
943
    rm_read_packet,
944
    rm_read_close,
945
    NULL,
946
    rm_read_dts,
947
};
948

    
949
AVInputFormat rdt_demuxer = {
950
    "rdt",
951
    NULL_IF_CONFIG_SMALL("RDT demuxer"),
952
    sizeof(RMDemuxContext),
953
    NULL,
954
    NULL,
955
    NULL,
956
    rm_read_close,
957
};