Statistics
| Branch: | Revision:

ffmpeg / libavformat / rmdec.c @ 461ef741

History | View | Annotate | Download (31.1 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 AVCodecTag rm_codec_tags[] = {
53
    { CODEC_ID_RV10,   MKTAG('R','V','1','0') },
54
    { CODEC_ID_RV20,   MKTAG('R','V','2','0') },
55
    { CODEC_ID_RV20,   MKTAG('R','V','T','R') },
56
    { CODEC_ID_RV30,   MKTAG('R','V','3','0') },
57
    { CODEC_ID_RV40,   MKTAG('R','V','4','0') },
58
    { CODEC_ID_AC3,    MKTAG('d','n','e','t') },
59
    { CODEC_ID_RA_144, MKTAG('l','p','c','J') },
60
    { CODEC_ID_RA_288, MKTAG('2','8','_','8') },
61
    { CODEC_ID_COOK,   MKTAG('c','o','o','k') },
62
    { CODEC_ID_ATRAC3, MKTAG('a','t','r','c') },
63
    { CODEC_ID_SIPR,   MKTAG('s','i','p','r') },
64
    { CODEC_ID_AAC,    MKTAG('r','a','a','c') },
65
    { CODEC_ID_AAC,    MKTAG('r','a','c','p') },
66
    { 0 },
67
};
68

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

    
82
static const unsigned char sipr_subpk_size[4] = { 29, 19, 37, 20 };
83

    
84
static inline void get_strl(ByteIOContext *pb, char *buf, int buf_size, int len)
85
{
86
    int i;
87
    char *q, r;
88

    
89
    q = buf;
90
    for(i=0;i<len;i++) {
91
        r = get_byte(pb);
92
        if (i < buf_size - 1)
93
            *q++ = r;
94
    }
95
    if (buf_size > 0) *q = '\0';
96
}
97

    
98
static void get_str8(ByteIOContext *pb, char *buf, int buf_size)
99
{
100
    get_strl(pb, buf, buf_size, get_byte(pb));
101
}
102

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

    
114
RMStream *ff_rm_alloc_rmstream (void)
115
{
116
    RMStream *rms = av_mallocz(sizeof(RMStream));
117
    rms->curpic_num = -1;
118
    return rms;
119
}
120

    
121
void ff_rm_free_rmstream (RMStream *rms)
122
{
123
    av_free_packet(&rms->pkt);
124
}
125

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

    
132
    /* ra type header */
133
    version = get_be32(pb); /* version */
134
    if (((version >> 16) & 0xff) == 3) {
135
        int64_t startpos = url_ftell(pb);
136
        url_fskip(pb, 14);
137
        rm_read_metadata(s, 0);
138
        if ((startpos + (version & 0xffff)) >= url_ftell(pb) + 2) {
139
            // fourcc (should always be "lpcJ")
140
            get_byte(pb);
141
            get_str8(pb, buf, sizeof(buf));
142
        }
143
        // Skip extra header crap (this should never happen)
144
        if ((startpos + (version & 0xffff)) > url_ftell(pb))
145
            url_fskip(pb, (version & 0xffff) + startpos - url_ftell(pb));
146
        st->codec->sample_rate = 8000;
147
        st->codec->channels = 1;
148
        st->codec->codec_type = CODEC_TYPE_AUDIO;
149
        st->codec->codec_id = CODEC_ID_RA_144;
150
    } else {
151
        int flavor, sub_packet_h, coded_framesize, sub_packet_size;
152
        int codecdata_length;
153
        /* old version (4) */
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 >> 16) & 0xff) == 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 >> 16) & 0xff) == 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 = CODEC_TYPE_AUDIO;
182
        st->codec->codec_tag  = AV_RL32(buf);
183
        st->codec->codec_id   = ff_codec_get_id(rm_codec_tags, st->codec->codec_tag);
184
        switch (st->codec->codec_id) {
185
        case CODEC_ID_AC3:
186
            st->need_parsing = AVSTREAM_PARSE_FULL;
187
            break;
188
        case CODEC_ID_RA_288:
189
            st->codec->extradata_size= 0;
190
            ast->audio_framesize = st->codec->block_align;
191
            st->codec->block_align = coded_framesize;
192

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

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

    
212
            if (!strcmp(buf, "cook")) st->codec->codec_id = CODEC_ID_COOK;
213
            else if (!strcmp(buf, "sipr")) st->codec->codec_id = CODEC_ID_SIPR;
214
            else st->codec->codec_id = CODEC_ID_ATRAC3;
215

    
216
            ast->audio_framesize = st->codec->block_align;
217
            if (st->codec->codec_id == CODEC_ID_SIPR) {
218
                if (flavor > 3) {
219
                    av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",
220
                           flavor);
221
                    return -1;
222
                }
223
                st->codec->block_align = sipr_subpk_size[flavor];
224
            } else {
225
                if(sub_packet_size <= 0){
226
                    av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");
227
                    return -1;
228
                }
229
                st->codec->block_align = ast->sub_packet_size;
230
            }
231
            st->codec->extradata_size= codecdata_length;
232
            st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
233
            get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
234

    
235
            if(ast->audio_framesize >= UINT_MAX / sub_packet_h){
236
                av_log(s, AV_LOG_ERROR, "rm->audio_framesize * sub_packet_h too large\n");
237
                return -1;
238
            }
239

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

    
272
int
273
ff_rm_read_mdpr_codecdata (AVFormatContext *s, ByteIOContext *pb,
274
                           AVStream *st, RMStream *rst, int codec_data_size)
275
{
276
    unsigned int v;
277
    int size;
278
    int64_t codec_pos;
279

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

    
308
        st->codec->extradata_size= codec_data_size - (url_ftell(pb) - codec_pos);
309

    
310
        if(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE <= (unsigned)st->codec->extradata_size){
311
            //check is redundant as get_buffer() will catch this
312
            av_log(s, AV_LOG_ERROR, "st->codec->extradata_size too large\n");
313
            return -1;
314
        }
315
        st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
316
        if (!st->codec->extradata)
317
            return AVERROR(ENOMEM);
318
        get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
319

    
320
//        av_log(s, AV_LOG_DEBUG, "fps= %d fps2= %d\n", fps, fps2);
321
        st->codec->time_base.den = fps * st->codec->time_base.num;
322
        //XXX: do we really need that?
323
        switch(((uint8_t*)st->codec->extradata)[4]>>4){
324
        case 1: st->codec->codec_id = CODEC_ID_RV10; break;
325
        case 2: st->codec->codec_id = CODEC_ID_RV20; break;
326
        case 3: st->codec->codec_id = CODEC_ID_RV30; break;
327
        case 4: st->codec->codec_id = CODEC_ID_RV40; break;
328
        default: goto fail1;
329
        }
330
    }
331

    
332
skip:
333
    /* skip codec info */
334
    size = url_ftell(pb) - codec_pos;
335
    url_fskip(pb, codec_data_size - size);
336

    
337
    return 0;
338
}
339

    
340
/** this function assumes that the demuxer has already seeked to the start
341
 * of the INDX chunk, and will bail out if not. */
342
static int rm_read_index(AVFormatContext *s)
343
{
344
    ByteIOContext *pb = s->pb;
345
    unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
346
    AVStream *st;
347

    
348
    do {
349
        if (get_le32(pb) != MKTAG('I','N','D','X'))
350
            return -1;
351
        size     = get_be32(pb);
352
        if (size < 20)
353
            return -1;
354
        url_fskip(pb, 2);
355
        n_pkts   = get_be32(pb);
356
        str_id   = get_be16(pb);
357
        next_off = get_be32(pb);
358
        for (n = 0; n < s->nb_streams; n++)
359
            if (s->streams[n]->id == str_id) {
360
                st = s->streams[n];
361
                break;
362
            }
363
        if (n == s->nb_streams)
364
            goto skip;
365

    
366
        for (n = 0; n < n_pkts; n++) {
367
            url_fskip(pb, 2);
368
            pts = get_be32(pb);
369
            pos = get_be32(pb);
370
            url_fskip(pb, 4); /* packet no. */
371

    
372
            av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
373
        }
374

    
375
skip:
376
        if (next_off && url_ftell(pb) != next_off &&
377
            url_fseek(pb, next_off, SEEK_SET) < 0)
378
            return -1;
379
    } while (next_off);
380

    
381
    return 0;
382
}
383

    
384
static int rm_read_header_old(AVFormatContext *s, AVFormatParameters *ap)
385
{
386
    RMDemuxContext *rm = s->priv_data;
387
    AVStream *st;
388

    
389
    rm->old_format = 1;
390
    st = av_new_stream(s, 0);
391
    if (!st)
392
        return -1;
393
    st->priv_data = ff_rm_alloc_rmstream();
394
    return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1);
395
}
396

    
397
static int rm_read_header(AVFormatContext *s, AVFormatParameters *ap)
398
{
399
    RMDemuxContext *rm = s->priv_data;
400
    AVStream *st;
401
    ByteIOContext *pb = s->pb;
402
    unsigned int tag;
403
    int tag_size;
404
    unsigned int start_time, duration;
405
    unsigned int data_off = 0, indx_off = 0;
406
    char buf[128];
407
    int flags = 0;
408

    
409
    tag = get_le32(pb);
410
    if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
411
        /* very old .ra format */
412
        return rm_read_header_old(s, ap);
413
    } else if (tag != MKTAG('.', 'R', 'M', 'F')) {
414
        return AVERROR(EIO);
415
    }
416

    
417
    get_be32(pb); /* header size */
418
    get_be16(pb);
419
    get_be32(pb);
420
    get_be32(pb); /* number of headers */
421

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

    
493
    if (!data_off)
494
        data_off = url_ftell(pb) - 18;
495
    if (indx_off && url_fseek(pb, indx_off, SEEK_SET) >= 0) {
496
        rm_read_index(s);
497
        url_fseek(pb, data_off + 18, SEEK_SET);
498
    }
499

    
500
    return 0;
501
}
502

    
503
static int get_num(ByteIOContext *pb, int *len)
504
{
505
    int n, n1;
506

    
507
    n = get_be16(pb);
508
    (*len)-=2;
509
    n &= 0x7FFF;
510
    if (n >= 0x4000) {
511
        return n - 0x4000;
512
    } else {
513
        n1 = get_be16(pb);
514
        (*len)-=2;
515
        return (n << 16) | n1;
516
    }
517
}
518

    
519
/* multiple of 20 bytes for ra144 (ugly) */
520
#define RAW_PACKET_SIZE 1000
521

    
522
static int sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
523
    RMDemuxContext *rm = s->priv_data;
524
    ByteIOContext *pb = s->pb;
525
    AVStream *st;
526
    uint32_t state=0xFFFFFFFF;
527

    
528
    while(!url_feof(pb)){
529
        int len, num, res, i;
530
        *pos= url_ftell(pb) - 3;
531
        if(rm->remaining_len > 0){
532
            num= rm->current_stream;
533
            len= rm->remaining_len;
534
            *timestamp = AV_NOPTS_VALUE;
535
            *flags= 0;
536
        }else{
537
            state= (state<<8) + get_byte(pb);
538

    
539
            if(state == MKBETAG('I', 'N', 'D', 'X')){
540
                int n_pkts, expected_len;
541
                len = get_be32(pb);
542
                url_fskip(pb, 2);
543
                n_pkts = get_be32(pb);
544
                expected_len = 20 + n_pkts * 14;
545
                if (len == 20)
546
                    /* some files don't add index entries to chunk size... */
547
                    len = expected_len;
548
                else if (len != expected_len)
549
                    av_log(s, AV_LOG_WARNING,
550
                           "Index size %d (%d pkts) is wrong, should be %d.\n",
551
                           len, n_pkts, expected_len);
552
                len -= 14; // we already read part of the index header
553
                if(len<0)
554
                    continue;
555
                goto skip;
556
            }
557

    
558
            if(state > (unsigned)0xFFFF || state <= 12)
559
                continue;
560
            len=state - 12;
561
            state= 0xFFFFFFFF;
562

    
563
            num = get_be16(pb);
564
            *timestamp = get_be32(pb);
565
            res= get_byte(pb); /* reserved */
566
            *flags = get_byte(pb); /* flags */
567
        }
568
        for(i=0;i<s->nb_streams;i++) {
569
            st = s->streams[i];
570
            if (num == st->id)
571
                break;
572
        }
573
        if (i == s->nb_streams) {
574
skip:
575
            /* skip packet if unknown number */
576
            url_fskip(pb, len);
577
            rm->remaining_len = 0;
578
            continue;
579
        }
580
        *stream_index= i;
581

    
582
        return len;
583
    }
584
    return -1;
585
}
586

    
587
static int rm_assemble_video_frame(AVFormatContext *s, ByteIOContext *pb,
588
                                   RMDemuxContext *rm, RMStream *vst,
589
                                   AVPacket *pkt, int len, int *pseq)
590
{
591
    int hdr, seq, pic_num, len2, pos;
592
    int type;
593

    
594
    hdr = get_byte(pb); len--;
595
    type = hdr >> 6;
596

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

    
624
    *pseq = seq;
625
    if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
626
        vst->slices = ((hdr & 0x3F) << 1) + 1;
627
        vst->videobufsize = len2 + 8*vst->slices + 1;
628
        av_free_packet(&vst->pkt); //FIXME this should be output.
629
        if(av_new_packet(&vst->pkt, vst->videobufsize) < 0)
630
            return AVERROR(ENOMEM);
631
        vst->videobufpos = 8*vst->slices + 1;
632
        vst->cur_slice = 0;
633
        vst->curpic_num = pic_num;
634
        vst->pktpos = url_ftell(pb);
635
    }
636
    if(type == 2)
637
        len = FFMIN(len, pos);
638

    
639
    if(++vst->cur_slice > vst->slices)
640
        return 1;
641
    AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
642
    AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
643
    if(vst->videobufpos + len > vst->videobufsize)
644
        return 1;
645
    if (get_buffer(pb, vst->pkt.data + vst->videobufpos, len) != len)
646
        return AVERROR(EIO);
647
    vst->videobufpos += len;
648
    rm->remaining_len-= len;
649

    
650
    if(type == 2 || (vst->videobufpos) == vst->videobufsize){
651
        vst->pkt.data[0] = vst->cur_slice-1;
652
        *pkt= vst->pkt;
653
        vst->pkt.data= NULL;
654
        vst->pkt.size= 0;
655
        if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
656
            memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
657
                vst->videobufpos - 1 - 8*vst->slices);
658
        pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices);
659
        pkt->pts = AV_NOPTS_VALUE;
660
        pkt->pos = vst->pktpos;
661
        vst->slices = 0;
662
        return 0;
663
    }
664

    
665
    return 1;
666
}
667

    
668
static inline void
669
rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt)
670
{
671
    uint8_t *ptr;
672
    int j;
673

    
674
    if (st->codec->codec_id == CODEC_ID_AC3) {
675
        ptr = pkt->data;
676
        for (j=0;j<pkt->size;j+=2) {
677
            FFSWAP(int, ptr[0], ptr[1]);
678
            ptr += 2;
679
        }
680
    }
681
}
682

    
683
/**
684
 * Perform 4-bit block reordering for SIPR data.
685
 * @todo This can be optimized, e.g. use memcpy() if data blocks are aligned
686
 */
687
static void
688
rm_reorder_sipr_data (RMStream *ast)
689
{
690
    int n, bs = ast->sub_packet_h * ast->audio_framesize * 2 / 96; // nibbles per subpacket
691

    
692
    for (n = 0; n < 38; n++) {
693
        int j;
694
        int i = bs * sipr_swaps[n][0];
695
        int o = bs * sipr_swaps[n][1];
696
        uint8_t *buf = ast->pkt.data;
697

    
698
        /* swap 4bit-nibbles of block 'i' with 'o' */
699
        for (j = 0; j < bs; j++, i++, o++) {
700
            int x = (buf[i >> 1] >> (4 * (i & 1))) & 0xF,
701
                y = (buf[o >> 1] >> (4 * (o & 1))) & 0xF;
702

    
703
            buf[o >> 1] = (x << (4 * (o & 1))) |
704
                (buf[o >> 1] & (0xF << (4 * !(o & 1))));
705
            buf[i >> 1] = (y << (4 * (i & 1))) |
706
                (buf[i >> 1] & (0xF << (4 * !(i & 1))));
707
        }
708
    }
709
}
710

    
711
int
712
ff_rm_parse_packet (AVFormatContext *s, ByteIOContext *pb,
713
                    AVStream *st, RMStream *ast, int len, AVPacket *pkt,
714
                    int *seq, int flags, int64_t timestamp)
715
{
716
    RMDemuxContext *rm = s->priv_data;
717

    
718
    if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
719
        rm->current_stream= st->id;
720
        if(rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq))
721
            return -1; //got partial frame
722
    } else if (st->codec->codec_type == CODEC_TYPE_AUDIO) {
723
        if ((st->codec->codec_id == CODEC_ID_RA_288) ||
724
            (st->codec->codec_id == CODEC_ID_COOK) ||
725
            (st->codec->codec_id == CODEC_ID_ATRAC3) ||
726
            (st->codec->codec_id == CODEC_ID_SIPR)) {
727
            int x;
728
            int sps = ast->sub_packet_size;
729
            int cfs = ast->coded_framesize;
730
            int h = ast->sub_packet_h;
731
            int y = ast->sub_packet_cnt;
732
            int w = ast->audio_framesize;
733

    
734
            if (flags & 2)
735
                y = ast->sub_packet_cnt = 0;
736
            if (!y)
737
                ast->audiotimestamp = timestamp;
738

    
739
            switch(st->codec->codec_id) {
740
                case CODEC_ID_RA_288:
741
                    for (x = 0; x < h/2; x++)
742
                        get_buffer(pb, ast->pkt.data+x*2*w+y*cfs, cfs);
743
                    break;
744
                case CODEC_ID_ATRAC3:
745
                case CODEC_ID_COOK:
746
                    for (x = 0; x < w/sps; x++)
747
                        get_buffer(pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
748
                    break;
749
                case CODEC_ID_SIPR:
750
                    get_buffer(pb, ast->pkt.data + y * w, w);
751
                    break;
752
            }
753

    
754
            if (++(ast->sub_packet_cnt) < h)
755
                return -1;
756
            if (st->codec->codec_id == CODEC_ID_SIPR)
757
                rm_reorder_sipr_data(ast);
758

    
759
             ast->sub_packet_cnt = 0;
760
             rm->audio_stream_num = st->index;
761
             rm->audio_pkt_cnt = h * w / st->codec->block_align;
762
        } else if (st->codec->codec_id == CODEC_ID_AAC) {
763
            int x;
764
            rm->audio_stream_num = st->index;
765
            ast->sub_packet_cnt = (get_be16(pb) & 0xf0) >> 4;
766
            if (ast->sub_packet_cnt) {
767
                for (x = 0; x < ast->sub_packet_cnt; x++)
768
                    ast->sub_packet_lengths[x] = get_be16(pb);
769
                rm->audio_pkt_cnt = ast->sub_packet_cnt;
770
                ast->audiotimestamp = timestamp;
771
            } else
772
                return -1;
773
        } else {
774
            av_get_packet(pb, pkt, len);
775
            rm_ac3_swap_bytes(st, pkt);
776
        }
777
    } else
778
        av_get_packet(pb, pkt, len);
779

    
780
    pkt->stream_index = st->index;
781

    
782
#if 0
783
    if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
784
        if(st->codec->codec_id == CODEC_ID_RV20){
785
            int seq= 128*(pkt->data[2]&0x7F) + (pkt->data[3]>>1);
786
            av_log(s, AV_LOG_DEBUG, "%d %"PRId64" %d\n", *timestamp, *timestamp*512LL/25, seq);
787

788
            seq |= (timestamp&~0x3FFF);
789
            if(seq - timestamp >  0x2000) seq -= 0x4000;
790
            if(seq - timestamp < -0x2000) seq += 0x4000;
791
        }
792
    }
793
#endif
794

    
795
    pkt->pts= timestamp;
796
    if (flags & 2)
797
        pkt->flags |= PKT_FLAG_KEY;
798

    
799
    return st->codec->codec_type == CODEC_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;
800
}
801

    
802
int
803
ff_rm_retrieve_cache (AVFormatContext *s, ByteIOContext *pb,
804
                      AVStream *st, RMStream *ast, AVPacket *pkt)
805
{
806
    RMDemuxContext *rm = s->priv_data;
807

    
808
    assert (rm->audio_pkt_cnt > 0);
809

    
810
    if (st->codec->codec_id == CODEC_ID_AAC)
811
        av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);
812
    else {
813
        av_new_packet(pkt, st->codec->block_align);
814
        memcpy(pkt->data, ast->pkt.data + st->codec->block_align * //FIXME avoid this
815
               (ast->sub_packet_h * ast->audio_framesize / st->codec->block_align - rm->audio_pkt_cnt),
816
               st->codec->block_align);
817
    }
818
    rm->audio_pkt_cnt--;
819
    if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {
820
        ast->audiotimestamp = AV_NOPTS_VALUE;
821
        pkt->flags = PKT_FLAG_KEY;
822
    } else
823
        pkt->flags = 0;
824
    pkt->stream_index = st->index;
825

    
826
    return rm->audio_pkt_cnt;
827
}
828

    
829
static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
830
{
831
    RMDemuxContext *rm = s->priv_data;
832
    AVStream *st;
833
    int i, len, res, seq = 1;
834
    int64_t timestamp, pos;
835
    int flags;
836

    
837
    for (;;) {
838
        if (rm->audio_pkt_cnt) {
839
            // If there are queued audio packet return them first
840
            st = s->streams[rm->audio_stream_num];
841
            ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
842
        } else {
843
            if (rm->old_format) {
844
                RMStream *ast;
845

    
846
                st = s->streams[0];
847
                ast = st->priv_data;
848
                timestamp = AV_NOPTS_VALUE;
849
                len = !ast->audio_framesize ? RAW_PACKET_SIZE :
850
                    ast->coded_framesize * ast->sub_packet_h / 2;
851
                flags = (seq++ == 1) ? 2 : 0;
852
            } else {
853
                len=sync(s, &timestamp, &flags, &i, &pos);
854
                if (len > 0)
855
                    st = s->streams[i];
856
            }
857

    
858
            if(len<0 || url_feof(s->pb))
859
                return AVERROR(EIO);
860

    
861
            res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
862
                                      &seq, flags, timestamp);
863
            if((flags&2) && (seq&0x7F) == 1)
864
                av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
865
            if (res)
866
                continue;
867
        }
868

    
869
        if(  (st->discard >= AVDISCARD_NONKEY && !(flags&2))
870
           || st->discard >= AVDISCARD_ALL){
871
            av_free_packet(pkt);
872
        } else
873
            break;
874
    }
875

    
876
    return 0;
877
}
878

    
879
static int rm_read_close(AVFormatContext *s)
880
{
881
    int i;
882

    
883
    for (i=0;i<s->nb_streams;i++)
884
        ff_rm_free_rmstream(s->streams[i]->priv_data);
885

    
886
    return 0;
887
}
888

    
889
static int rm_probe(AVProbeData *p)
890
{
891
    /* check file header */
892
    if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
893
         p->buf[2] == 'M' && p->buf[3] == 'F' &&
894
         p->buf[4] == 0 && p->buf[5] == 0) ||
895
        (p->buf[0] == '.' && p->buf[1] == 'r' &&
896
         p->buf[2] == 'a' && p->buf[3] == 0xfd))
897
        return AVPROBE_SCORE_MAX;
898
    else
899
        return 0;
900
}
901

    
902
static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
903
                               int64_t *ppos, int64_t pos_limit)
904
{
905
    RMDemuxContext *rm = s->priv_data;
906
    int64_t pos, dts;
907
    int stream_index2, flags, len, h;
908

    
909
    pos = *ppos;
910

    
911
    if(rm->old_format)
912
        return AV_NOPTS_VALUE;
913

    
914
    url_fseek(s->pb, pos, SEEK_SET);
915
    rm->remaining_len=0;
916
    for(;;){
917
        int seq=1;
918
        AVStream *st;
919

    
920
        len=sync(s, &dts, &flags, &stream_index2, &pos);
921
        if(len<0)
922
            return AV_NOPTS_VALUE;
923

    
924
        st = s->streams[stream_index2];
925
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
926
            h= get_byte(s->pb); len--;
927
            if(!(h & 0x40)){
928
                seq = get_byte(s->pb); len--;
929
            }
930
        }
931

    
932
        if((flags&2) && (seq&0x7F) == 1){
933
//            av_log(s, AV_LOG_DEBUG, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq);
934
            av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
935
            if(stream_index2 == stream_index)
936
                break;
937
        }
938

    
939
        url_fskip(s->pb, len);
940
    }
941
    *ppos = pos;
942
    return dts;
943
}
944

    
945
AVInputFormat rm_demuxer = {
946
    "rm",
947
    NULL_IF_CONFIG_SMALL("RealMedia format"),
948
    sizeof(RMDemuxContext),
949
    rm_probe,
950
    rm_read_header,
951
    rm_read_packet,
952
    rm_read_close,
953
    NULL,
954
    rm_read_dts,
955
};
956

    
957
AVInputFormat rdt_demuxer = {
958
    "rdt",
959
    NULL_IF_CONFIG_SMALL("RDT demuxer"),
960
    sizeof(RMDemuxContext),
961
    NULL,
962
    NULL,
963
    NULL,
964
    rm_read_close,
965
};