1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id:$
 *
 * Copyright (C) 2009 Mohamed Tarek
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <inttypes.h>

#include <codecs/librm/rm.h>
#include "system.h"
#include "metadata.h"
#include "metadata_common.h"
#include "metadata_parsers.h"
#include "logf.h"

//#define DEBUG_RM
#define MAX_STRING 92 /* Size of id3v1 buffers in metadata.h */
#ifndef DEBUG_RM
#undef DEBUGF
#define DEBUGF(...)
#endif

static inline int read_cook_extradata(int fd, RMContext *rmctx) {
    read_uint32be(fd, &rmctx->cook_version);
    read_uint16be(fd, &rmctx->samples_pf_pc);
    read_uint16be(fd, &rmctx->nb_subbands);
    if(rmctx->extradata_size == 16) {
        lseek(fd, sizeof(uint32_t), SEEK_CUR); /* reserved */
        read_uint16be(fd, &rmctx->js_subband_start);
        read_uint16be(fd, &rmctx->js_vlc_bits);
    }
    return rmctx->extradata_size; /* for 'skipped' */
}

static inline void print_cook_extradata(RMContext *rmctx) {

    DEBUGF("            cook_version = 0x%08lx\n", rmctx->cook_version);
    DEBUGF("            samples_per_frame_per_channel = %d\n", rmctx->samples_pf_pc);
    DEBUGF("            number_of_subbands_in_freq_domain = %d\n", rmctx->nb_subbands);
    if(rmctx->extradata_size == 16) {
        DEBUGF("            joint_stereo_subband_start = %d\n",rmctx->js_subband_start);
        DEBUGF("            joint_stereo_vlc_bits = %d\n", rmctx->js_vlc_bits);
    }
} 


struct real_object_t
{
    uint32_t fourcc;
    uint32_t size;
    uint16_t version;
};

#define FOURCC(a,b,c,d) (((a)<<24) | ((b) << 16) | ((c) << 8) | (d))

static int real_read_object_header(int fd, struct real_object_t* obj)
{
    int n;

    if ((n = read_uint32be(fd, &obj->fourcc)) <= 0) return n;
    if ((n = read_uint32be(fd, &obj->size)) <= 0) return n;
    if ((n = read_uint16be(fd, &obj->version)) <= 0) return n;

    return 1;
}

static char* fourcc2str(uint32_t f)
{
    static char res[5];

    res[0] = (f & 0xff000000) >> 24;
    res[1] = (f & 0xff0000) >> 16;
    res[2] = (f & 0xff00) >> 8;
    res[3] = (f & 0xff);
    res[4] = 0;

    return res;
}

static int real_read_audio_stream_info(int fd, RMContext *rmctx)
{
    int skipped = 0;
    uint32_t version;
    struct real_object_t obj;
    memset(&obj,0,sizeof(obj));
    uint32_t header_size;
    uint16_t flavor;
    uint32_t coded_framesize;
    uint8_t  unknown8;
    uint16_t unknown16;
    uint32_t unknown32;
    uint8_t  interleaver_id_length;
    uint32_t interleaver_id;
    uint8_t  fourcc_length;
    uint32_t fourcc = 0;


    read_uint32be(fd, &version);
    skipped += 4;

    DEBUGF("    version=0x%04lx\n",((version >> 16) & 0xff));
    if (((version >> 16) & 0xff) == 3) {
        /* Very old version */
    } else {
       real_read_object_header(fd, &obj);
       skipped += 10;
       read_uint32be(fd, &header_size);
       skipped += 4;
       /* obj.size will be filled with an unknown value, replaced with header_size */
       DEBUGF("    Object: %s, size: %ld bytes, version: 0x%04x\n",fourcc2str(obj.fourcc),header_size,obj.version);

       lseek(fd, 18, SEEK_CUR);
       read_uint16be(fd, &rmctx->sub_packet_h);
       read_uint16be(fd, &rmctx->block_align);
       read_uint16be(fd, &rmctx->sub_packet_size);
       read_uint16be(fd, &unknown16);
       skipped += 26;
       if (((version >> 16) & 0xff) == 5)
       {
           lseek(fd, 6, SEEK_CUR);
           skipped += 6;
       }
       read_uint16be(fd, &rmctx->sample_rate);
       read_uint32be(fd, &unknown32);
       read_uint16be(fd, &rmctx->nb_channels);
       skipped += 8;
       if (((version >> 16) & 0xff) == 4)
       {
           lseek(fd, 10, SEEK_CUR);
           skipped += 10;
       }
       if (((version >> 16) & 0xff) == 5)
       {
           lseek(fd, 8, SEEK_CUR);
           skipped += 8;
       }
       lseek(fd, 3, SEEK_CUR);
       skipped += 3;
       if (((version >> 16) & 0xff) == 5)
       {
           read_uint8(fd, &unknown8);
           skipped += 1;
       }

       read_uint32be(fd, &rmctx->extradata_size);
       skipped += 4;
       if(!strncmp(fourcc2str(fourcc),"cook",4)){
           skipped += read_cook_extradata(fd, rmctx); 
           rmctx->codec_type = cook;
       }


       DEBUGF("        flavor = %d\n",flavor);
       DEBUGF("        coded_frame_size = %ld\n",coded_framesize);
       DEBUGF("        sub_packet_h = %d\n",rmctx->sub_packet_h);
       DEBUGF("        frame_size = %d\n",rmctx->block_align);
       DEBUGF("        sub_packet_size = %d\n",rmctx->sub_packet_size);
       DEBUGF("        sample_rate= %d\n",rmctx->sample_rate);
       DEBUGF("        channels= %d\n",rmctx->nb_channels);
       DEBUGF("        fourcc = %s\n",fourcc2str(fourcc));
       DEBUGF("        codec_extra_data_length = %ld\n",rmctx->extradata_size);
       DEBUGF("        codec_extradata :\n");
       print_cook_extradata(rmctx);

    }

    return skipped;
}

static int rm_parse_header(int fd, RMContext *rmctx, struct mp3entry *id3)
{
    struct real_object_t obj;
    memset(&obj,0,sizeof(obj));
    int res;
    int skipped;
    off_t curpos;
    uint8_t len; /* Holds a string_length, which is then passed to read_string() */

    //uint32_t unknown32;

    uint32_t max_bitrate;
    uint32_t avg_bitrate = 0;
    uint32_t max_packet_size;
    uint32_t avg_packet_size;
    uint32_t packet_count;
    uint32_t duration;
    uint32_t preroll;
    uint32_t index_offset;
    uint16_t num_streams;

    uint16_t stream_id;
    uint32_t start_time;
    uint32_t codec_data_size;
    uint32_t v;

    uint32_t next_data_off;
    uint8_t  header_end;

    curpos = lseek(fd, 0, SEEK_SET);    
    res = real_read_object_header(fd, &obj);

    if (obj.fourcc == FOURCC('.','r','a',0xfd))
    {
        /* Very old .ra format - not yet supported */
        return -1;
    } 
    else if (obj.fourcc != FOURCC('.','R','M','F'))
    {
        return -1;
    }

    /* Skip 2 dword unknowns */
    lseek(fd, 2*sizeof(uint32_t), SEEK_CUR);

    DEBUGF("Object: %s, size: %d bytes, version: 0x%04x, pos: %d\n",fourcc2str(obj.fourcc),(int)obj.size,obj.version,(int)curpos);

    res = real_read_object_header(fd, &obj);
    header_end = 0;
    while(res)
    {
        DEBUGF("Object: %s, size: %d bytes, version: 0x%04x, pos: %d\n",fourcc2str(obj.fourcc),(int)obj.size,obj.version,(int)curpos);
        skipped = 10;
        if(obj.fourcc == FOURCC('I','N','D','X'))
                break;
        switch (obj.fourcc)
        {
            case FOURCC('P','R','O','P'): /* File properties */
                read_uint32be(fd, &max_bitrate);
                read_uint32be(fd, &rmctx->bit_rate); /*avg bitrate*/
                lseek(fd, 12, SEEK_CUR);
                read_uint32be(fd, &rmctx->duration);
                lseek(fd, 8, SEEK_CUR);
                read_uint32be(fd, &rmctx->data_offset);
                read_uint16be(fd, &num_streams);
                read_uint16be(fd, &rmctx->flags);
                skipped += 40;

                DEBUGF("    max_bitrate = %ld\n",max_bitrate);
                DEBUGF("    avg_bitrate = %ld\n",avg_bitrate);
                DEBUGF("    max_packet_size = %ld\n",max_packet_size);
                DEBUGF("    avg_packet_size = %ld\n",avg_packet_size);
                DEBUGF("    packet_count = %ld\n",packet_count);
                DEBUGF("    duration = %ld\n",rmctx->duration);
                DEBUGF("    preroll = %ld\n",preroll);
                DEBUGF("    index_offset = %ld\n",index_offset);
                DEBUGF("    data_offset = %ld\n",rmctx->data_offset);
                DEBUGF("    num_streams = %d\n",num_streams);
                DEBUGF("    flags=0x%04x\n",rmctx->flags);
                break;

            case FOURCC('C','O','N','T'):
                /* Four strings - Title, Author, Copyright, Comment */
                read_uint8(fd,&len);
                skipped += (int)read_string(fd, id3->id3v1buf[0], MAX_STRING, '\0', len);
                read_uint8(fd,&len);
                skipped += (int)read_string(fd, id3->id3v1buf[1], MAX_STRING, '\0', len);
                read_uint8(fd,&len);
                skipped += (int)read_string(fd, id3->id3v1buf[2], MAX_STRING, '\0', len);
                read_uint8(fd,&len);
                skipped += (int)read_string(fd, id3->id3v1buf[3], MAX_STRING, '\0', len);
                skipped += 4;

                DEBUGF("    title=\"%s\"\n",id3->id3v1buf[0]);
                DEBUGF("    author=\"%s\"\n",id3->id3v1buf[1]);
                DEBUGF("    copyright=\"%s\"\n",id3->id3v1buf[2]);
                DEBUGF("    comment=\"%s\"\n",id3->id3v1buf[3]);
                break;

            case FOURCC('M','D','P','R'): /* Media properties */
                lseek(fd, 30, SEEK_CUR);
                skipped += 30;
                read_uint8(fd,&len);
                skipped += 1;
                lseek(fd, len, SEEK_CUR); /* desc */
                skipped += len;
                read_uint8(fd,&len);
                skipped += 1;
                lseek(fd, len + 4, SEEK_CUR); /* mimetype */
                skipped += len + 4;
                //From ffmpeg: codec_pos = url_ftell(pb);
                //read_uint32be(fd,&v);

                DEBUGF("    stream_id = 0x%04x\n",stream_id);
                DEBUGF("    max_bitrate = %ld\n",max_bitrate);
                DEBUGF("    avg_bitrate = %ld\n",avg_bitrate);
                DEBUGF("    max_packet_size = %ld\n",max_packet_size);
                DEBUGF("    avg_packet_size = %ld\n",avg_packet_size);
                DEBUGF("    start_time = %ld\n",start_time);
                DEBUGF("    preroll = %ld\n",preroll);
                DEBUGF("    duration = %ld\n",duration);
                DEBUGF("    codec_data_size = %ld\n",codec_data_size);
                DEBUGF("    v=\"%s\"\n", fourcc2str(v));

                if (v == FOURCC('.','r','a',0xfd))
                {
                    skipped += real_read_audio_stream_info(fd, rmctx);
                }

                break;

            case FOURCC('D','A','T','A'):             
                read_uint32be(fd,&rmctx->nb_packets);
                skipped += 4;
                read_uint32be(fd,&next_data_off);
                skipped += 4;		

              /***
               * nb_packets correction :
               *   in some samples, number of packets may not exactly form
               *   an integer number of scrambling units. This is corrected
               *   by constructing a partially filled unit out of the few 
               *   remaining samples at the end of decoding.
               ***/
                if(rmctx->nb_packets % rmctx->sub_packet_h)
                    rmctx->nb_packets += rmctx->sub_packet_h - (rmctx->nb_packets % rmctx->sub_packet_h);

                DEBUGF("    data_nb_packets = %ld\n",rmctx->nb_packets);
                DEBUGF("    next DATA offset = %ld\n",next_data_off);
                header_end = 1;
                break; 
        }
        if(header_end) break;
        curpos = lseek(fd, obj.size - skipped, SEEK_CUR);
        res = real_read_object_header(fd, &obj);
    }


    return 0;
}

static void copy_metadata(struct mp3entry *id3, RMContext *rmctx)
{
    /* Copy tags */
    id3->title = id3->id3v1buf[0];
    id3->artist = id3->id3v1buf[1];
    id3->comment = id3->id3v1buf[3];

    /* Copy stream parameters */
    id3->bitrate = rmctx->bit_rate / 1000;
    id3->frequency = rmctx->sample_rate;
    id3->length = rmctx->duration;
    switch(rmctx->codec_type)
    {
        case cook:
            id3->codectype = AFMT_COOK;
            break;
    }
    memcpy(id3->id3v2buf, rmctx, sizeof(RMContext));

}

bool get_rm_metadata(int fd, struct mp3entry* id3)
{
    RMContext rmctx;
    memset(&rmctx,0,sizeof(RMContext));
    rm_parse_header(fd, &rmctx, id3);
    copy_metadata(id3, &rmctx);
    id3->filesize = filesize(fd);
    return true;
}