]> git.sesse.net Git - ffmpeg/blob - libavformat/omadec.c
oma: K&R formatting cosmetics
[ffmpeg] / libavformat / omadec.c
1 /*
2  * Sony OpenMG (OMA) demuxer
3  *
4  * Copyright (c) 2008 Maxim Poliakovski
5  *               2008 Benjamin Larsson
6  *               2011 David Goldwich
7  *
8  * This file is part of Libav.
9  *
10  * Libav is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * Libav is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with Libav; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 /**
26  * @file
27  * This is a demuxer for Sony OpenMG Music files
28  *
29  * Known file extensions: ".oma", "aa3"
30  * The format of such files consists of three parts:
31  * - "ea3" header carrying overall info and metadata. Except for starting with
32  *   "ea" instead of "ID", it's an ID3v2 header.
33  * - "EA3" header is a Sony-specific header containing information about
34  *   the OpenMG file: codec type (usually ATRAC, can also be MP3 or WMA),
35  *   codec specific info (packet size, sample rate, channels and so on)
36  *   and DRM related info (file encryption, content id).
37  * - Sound data organized in packets follow the EA3 header
38  *   (can be encrypted using the Sony DRM!).
39  *
40  * CODEC SUPPORT: Only ATRAC3 codec is currently supported!
41  */
42
43 #include "libavutil/channel_layout.h"
44 #include "avformat.h"
45 #include "internal.h"
46 #include "libavutil/intreadwrite.h"
47 #include "libavutil/des.h"
48 #include "oma.h"
49 #include "pcm.h"
50 #include "id3v2.h"
51
52
53 static const uint64_t leaf_table[] = {
54     0xd79e8283acea4620, 0x7a9762f445afd0d8,
55     0x354d60a60b8c79f1, 0x584e1cde00b07aee,
56     0x1573cd93da7df623, 0x47f98d79620dd535
57 };
58
59 typedef struct OMAContext {
60     uint64_t content_start;
61     int encrypted;
62     uint16_t k_size;
63     uint16_t e_size;
64     uint16_t i_size;
65     uint16_t s_size;
66     uint32_t rid;
67     uint8_t r_val[24];
68     uint8_t n_val[24];
69     uint8_t m_val[8];
70     uint8_t s_val[8];
71     uint8_t sm_val[8];
72     uint8_t e_val[8];
73     uint8_t iv[8];
74     struct AVDES av_des;
75 } OMAContext;
76
77 static void hex_log(AVFormatContext *s, int level,
78                     const char *name, const uint8_t *value, int len)
79 {
80     char buf[33];
81     len = FFMIN(len, 16);
82     if (av_log_get_level() < level)
83         return;
84     ff_data_to_hex(buf, value, len, 1);
85     buf[len << 1] = '\0';
86     av_log(s, level, "%s: %s\n", name, buf);
87 }
88
89 static int kset(AVFormatContext *s, const uint8_t *r_val, const uint8_t *n_val,
90                 int len)
91 {
92     OMAContext *oc = s->priv_data;
93
94     if (!r_val && !n_val)
95         return -1;
96
97     len = FFMIN(len, 16);
98
99     /* use first 64 bits in the third round again */
100     if (r_val) {
101         if (r_val != oc->r_val) {
102             memset(oc->r_val, 0, 24);
103             memcpy(oc->r_val, r_val, len);
104         }
105         memcpy(&oc->r_val[16], r_val, 8);
106     }
107     if (n_val) {
108         if (n_val != oc->n_val) {
109             memset(oc->n_val, 0, 24);
110             memcpy(oc->n_val, n_val, len);
111         }
112         memcpy(&oc->n_val[16], n_val, 8);
113     }
114
115     return 0;
116 }
117
118 static int rprobe(AVFormatContext *s, uint8_t *enc_header, const uint8_t *r_val)
119 {
120     OMAContext *oc = s->priv_data;
121     unsigned int pos;
122     struct AVDES av_des;
123
124     if (!enc_header || !r_val)
125         return -1;
126
127     /* m_val */
128     av_des_init(&av_des, r_val, 192, 1);
129     av_des_crypt(&av_des, oc->m_val, &enc_header[48], 1, NULL, 1);
130
131     /* s_val */
132     av_des_init(&av_des, oc->m_val, 64, 0);
133     av_des_crypt(&av_des, oc->s_val, NULL, 1, NULL, 0);
134
135     /* sm_val */
136     pos = OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size;
137     av_des_init(&av_des, oc->s_val, 64, 0);
138     av_des_mac(&av_des, oc->sm_val, &enc_header[pos], (oc->i_size >> 3));
139
140     pos += oc->i_size;
141
142     return memcmp(&enc_header[pos], oc->sm_val, 8) ? -1 : 0;
143 }
144
145 static int nprobe(AVFormatContext *s, uint8_t *enc_header, int size,
146                   const uint8_t *n_val)
147 {
148     OMAContext *oc = s->priv_data;
149     uint32_t pos, taglen, datalen;
150     struct AVDES av_des;
151
152     if (!enc_header || !n_val)
153         return -1;
154
155     pos = OMA_ENC_HEADER_SIZE + oc->k_size;
156     if (!memcmp(&enc_header[pos], "EKB ", 4))
157         pos += 32;
158
159     if (AV_RB32(&enc_header[pos]) != oc->rid)
160         av_log(s, AV_LOG_DEBUG, "Mismatching RID\n");
161
162     taglen  = AV_RB32(&enc_header[pos + 32]);
163     datalen = AV_RB32(&enc_header[pos + 36]) >> 4;
164
165     if (taglen + (((uint64_t)datalen) << 4) + 44 > size)
166         return -1;
167
168     pos += 44 + taglen;
169
170     av_des_init(&av_des, n_val, 192, 1);
171     while (datalen-- > 0) {
172         av_des_crypt(&av_des, oc->r_val, &enc_header[pos], 2, NULL, 1);
173         kset(s, oc->r_val, NULL, 16);
174         if (!rprobe(s, enc_header, oc->r_val))
175             return 0;
176         pos += 16;
177     }
178
179     return -1;
180 }
181
182 static int decrypt_init(AVFormatContext *s, ID3v2ExtraMeta *em, uint8_t *header)
183 {
184     OMAContext *oc = s->priv_data;
185     ID3v2ExtraMetaGEOB *geob = NULL;
186     uint8_t *gdata;
187
188     oc->encrypted = 1;
189     av_log(s, AV_LOG_INFO, "File is encrypted\n");
190
191     /* find GEOB metadata */
192     while (em) {
193         if (!strcmp(em->tag, "GEOB") &&
194             (geob = em->data) &&
195             (!strcmp(geob->description, "OMG_LSI") ||
196              !strcmp(geob->description, "OMG_BKLSI"))) {
197             break;
198         }
199         em = em->next;
200     }
201     if (!em) {
202         av_log(s, AV_LOG_ERROR, "No encryption header found\n");
203         return -1;
204     }
205
206     if (geob->datasize < 64) {
207         av_log(s, AV_LOG_ERROR,
208                "Invalid GEOB data size: %u\n", geob->datasize);
209         return -1;
210     }
211
212     gdata = geob->data;
213
214     if (AV_RB16(gdata) != 1)
215         av_log(s, AV_LOG_WARNING, "Unknown version in encryption header\n");
216
217     oc->k_size = AV_RB16(&gdata[2]);
218     oc->e_size = AV_RB16(&gdata[4]);
219     oc->i_size = AV_RB16(&gdata[6]);
220     oc->s_size = AV_RB16(&gdata[8]);
221
222     if (memcmp(&gdata[OMA_ENC_HEADER_SIZE], "KEYRING     ", 12)) {
223         av_log(s, AV_LOG_ERROR, "Invalid encryption header\n");
224         return -1;
225     }
226     oc->rid = AV_RB32(&gdata[OMA_ENC_HEADER_SIZE + 28]);
227     av_log(s, AV_LOG_DEBUG, "RID: %.8x\n", oc->rid);
228
229     memcpy(oc->iv, &header[0x58], 8);
230     hex_log(s, AV_LOG_DEBUG, "IV", oc->iv, 8);
231
232     hex_log(s, AV_LOG_DEBUG, "CBC-MAC",
233             &gdata[OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size + oc->i_size],
234             8);
235
236     if (s->keylen > 0) {
237         kset(s, s->key, s->key, s->keylen);
238     }
239     if (!memcmp(oc->r_val, (const uint8_t[8]){0}, 8) ||
240         rprobe(s, gdata, oc->r_val) < 0 &&
241         nprobe(s, gdata, geob->datasize, oc->n_val) < 0) {
242         int i;
243         for (i = 0; i < FF_ARRAY_ELEMS(leaf_table); i += 2) {
244             uint8_t buf[16];
245             AV_WL64(buf,     leaf_table[i]);
246             AV_WL64(&buf[8], leaf_table[i + 1]);
247             kset(s, buf, buf, 16);
248             if (!rprobe(s, gdata, oc->r_val) ||
249                 !nprobe(s, gdata, geob->datasize, oc->n_val))
250                 break;
251         }
252         if (i >= sizeof(leaf_table)) {
253             av_log(s, AV_LOG_ERROR, "Invalid key\n");
254             return -1;
255         }
256     }
257
258     /* e_val */
259     av_des_init(&oc->av_des, oc->m_val, 64, 0);
260     av_des_crypt(&oc->av_des, oc->e_val,
261                  &gdata[OMA_ENC_HEADER_SIZE + 40], 1, NULL, 0);
262     hex_log(s, AV_LOG_DEBUG, "EK", oc->e_val, 8);
263
264     /* init e_val */
265     av_des_init(&oc->av_des, oc->e_val, 64, 1);
266
267     return 0;
268 }
269
270 static int oma_read_header(AVFormatContext *s)
271 {
272     int     ret, framesize, jsflag, samplerate;
273     uint32_t codec_params;
274     int16_t eid;
275     uint8_t buf[EA3_HEADER_SIZE];
276     uint8_t *edata;
277     AVStream *st;
278     ID3v2ExtraMeta *extra_meta = NULL;
279     OMAContext *oc = s->priv_data;
280
281     ff_id3v2_read(s, ID3v2_EA3_MAGIC, &extra_meta);
282     ret = avio_read(s->pb, buf, EA3_HEADER_SIZE);
283     if (ret < EA3_HEADER_SIZE)
284         return -1;
285
286     if (memcmp(buf, ((const uint8_t[]){'E', 'A', '3'}), 3) ||
287         buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {
288         av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");
289         return -1;
290     }
291
292     oc->content_start = avio_tell(s->pb);
293
294     /* encrypted file */
295     eid = AV_RB16(&buf[6]);
296     if (eid != -1 && eid != -128 && decrypt_init(s, extra_meta, buf) < 0) {
297         ff_id3v2_free_extra_meta(&extra_meta);
298         return -1;
299     }
300
301     ff_id3v2_free_extra_meta(&extra_meta);
302
303     codec_params = AV_RB24(&buf[33]);
304
305     st = avformat_new_stream(s, NULL);
306     if (!st)
307         return AVERROR(ENOMEM);
308
309     st->start_time = 0;
310     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
311     st->codec->codec_tag  = buf[32];
312     st->codec->codec_id   = ff_codec_get_id(ff_oma_codec_tags,
313                                             st->codec->codec_tag);
314
315     switch (buf[32]) {
316     case OMA_CODECID_ATRAC3:
317         samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;
318         if (!samplerate) {
319             av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");
320             return AVERROR_INVALIDDATA;
321         }
322         if (samplerate != 44100)
323             avpriv_request_sample(s, "Sample rate %d", samplerate);
324
325         framesize = (codec_params & 0x3FF) * 8;
326
327         /* get stereo coding mode, 1 for joint-stereo */
328         jsflag = (codec_params >> 17) & 1;
329
330         st->codec->channels    = 2;
331         st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
332         st->codec->sample_rate = samplerate;
333         st->codec->bit_rate    = st->codec->sample_rate * framesize * 8 / 1024;
334
335         /* fake the atrac3 extradata
336          * (wav format, makes stream copy to wav work) */
337         st->codec->extradata_size = 14;
338         edata = av_mallocz(14 + FF_INPUT_BUFFER_PADDING_SIZE);
339         if (!edata)
340             return AVERROR(ENOMEM);
341
342         st->codec->extradata = edata;
343         AV_WL16(&edata[0],  1);             // always 1
344         AV_WL32(&edata[2],  samplerate);    // samples rate
345         AV_WL16(&edata[6],  jsflag);        // coding mode
346         AV_WL16(&edata[8],  jsflag);        // coding mode
347         AV_WL16(&edata[10], 1);             // always 1
348         // AV_WL16(&edata[12], 0);          // always 0
349
350         avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
351         break;
352     case OMA_CODECID_ATRAC3P:
353         st->codec->channels = (codec_params >> 10) & 7;
354         framesize = ((codec_params & 0x3FF) * 8) + 8;
355         samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;
356         if (!samplerate) {
357             av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");
358             return AVERROR_INVALIDDATA;
359         }
360         st->codec->sample_rate = samplerate;
361         st->codec->bit_rate    = samplerate * framesize * 8 / 1024;
362         avpriv_set_pts_info(st, 64, 1, samplerate);
363         av_log(s, AV_LOG_ERROR, "Unsupported codec ATRAC3+!\n");
364         break;
365     case OMA_CODECID_MP3:
366         st->need_parsing = AVSTREAM_PARSE_FULL;
367         framesize = 1024;
368         break;
369     case OMA_CODECID_LPCM:
370         /* PCM 44.1 kHz 16 bit stereo big-endian */
371         st->codec->channels = 2;
372         st->codec->channel_layout = AV_CH_LAYOUT_STEREO;
373         st->codec->sample_rate = 44100;
374         framesize = 1024;
375         /* bit rate = sample rate x PCM block align (= 4) x 8 */
376         st->codec->bit_rate = st->codec->sample_rate * 32;
377         st->codec->bits_per_coded_sample =
378             av_get_bits_per_sample(st->codec->codec_id);
379         avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
380         break;
381     default:
382         av_log(s, AV_LOG_ERROR, "Unsupported codec %d!\n", buf[32]);
383         return -1;
384     }
385
386     st->codec->block_align = framesize;
387
388     return 0;
389 }
390
391
392 static int oma_read_packet(AVFormatContext *s, AVPacket *pkt)
393 {
394     OMAContext *oc = s->priv_data;
395     int packet_size = s->streams[0]->codec->block_align;
396     int ret = av_get_packet(s->pb, pkt, packet_size);
397
398     if (ret <= 0)
399         return AVERROR(EIO);
400
401     pkt->stream_index = 0;
402
403     if (oc->encrypted) {
404         /* previous unencrypted block saved in IV for
405          * the next packet (CBC mode) */
406         av_des_crypt(&oc->av_des, pkt->data, pkt->data,
407                      (packet_size >> 3), oc->iv, 1);
408     }
409
410     return ret;
411 }
412
413 static int oma_read_probe(AVProbeData *p)
414 {
415     const uint8_t *buf;
416     unsigned tag_len = 0;
417
418     buf = p->buf;
419
420     if (p->buf_size < ID3v2_HEADER_SIZE ||
421         !ff_id3v2_match(buf, ID3v2_EA3_MAGIC) ||
422         buf[3] != 3 || // version must be 3
423         buf[4]) // flags byte zero
424         return 0;
425
426     tag_len = ff_id3v2_tag_len(buf);
427
428     /* This check cannot overflow as tag_len has at most 28 bits */
429     if (p->buf_size < tag_len + 5)
430         /* EA3 header comes late, might be outside of the probe buffer */
431         return AVPROBE_SCORE_MAX / 2;
432
433     buf += tag_len;
434
435     if (!memcmp(buf, "EA3", 3) && !buf[4] && buf[5] == EA3_HEADER_SIZE)
436         return AVPROBE_SCORE_MAX;
437     else
438         return 0;
439 }
440
441 static int oma_read_seek(struct AVFormatContext *s,
442                          int stream_index, int64_t timestamp, int flags)
443 {
444     OMAContext *oc = s->priv_data;
445
446     ff_pcm_read_seek(s, stream_index, timestamp, flags);
447
448     if (oc->encrypted) {
449         /* readjust IV for CBC */
450         int64_t pos = avio_tell(s->pb);
451         if (pos < oc->content_start)
452             memset(oc->iv, 0, 8);
453         else {
454             if (avio_seek(s->pb, -8, SEEK_CUR) < 0 ||
455                 avio_read(s->pb, oc->iv, 8) < 8) {
456                 memset(oc->iv, 0, 8);
457                 return -1;
458             }
459         }
460     }
461
462     return 0;
463 }
464
465 AVInputFormat ff_oma_demuxer = {
466     .name           = "oma",
467     .long_name      = NULL_IF_CONFIG_SMALL("Sony OpenMG audio"),
468     .priv_data_size = sizeof(OMAContext),
469     .read_probe     = oma_read_probe,
470     .read_header    = oma_read_header,
471     .read_packet    = oma_read_packet,
472     .read_seek      = oma_read_seek,
473     .flags          = AVFMT_GENERIC_INDEX,
474     .extensions     = "oma,omg,aa3",
475     .codec_tag      = (const AVCodecTag* const []){ff_oma_codec_tags, 0},
476 };