libavformat/omadec.c
Go to the documentation of this file.
00001 /*
00002  * Sony OpenMG (OMA) demuxer
00003  *
00004  * Copyright (c) 2008 Maxim Poliakovski
00005  *               2008 Benjamin Larsson
00006  *               2011 David Goldwich
00007  *
00008  * This file is part of Libav.
00009  *
00010  * Libav is free software; you can redistribute it and/or
00011  * modify it under the terms of the GNU Lesser General Public
00012  * License as published by the Free Software Foundation; either
00013  * version 2.1 of the License, or (at your option) any later version.
00014  *
00015  * Libav is distributed in the hope that it will be useful,
00016  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00017  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00018  * Lesser General Public License for more details.
00019  *
00020  * You should have received a copy of the GNU Lesser General Public
00021  * License along with Libav; if not, write to the Free Software
00022  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00023  */
00024 
00043 #include "avformat.h"
00044 #include "internal.h"
00045 #include "libavutil/intreadwrite.h"
00046 #include "libavutil/des.h"
00047 #include "oma.h"
00048 #include "pcm.h"
00049 #include "riff.h"
00050 #include "id3v2.h"
00051 
00052 
00053 static const uint64_t leaf_table[] = {
00054     0xd79e8283acea4620, 0x7a9762f445afd0d8,
00055     0x354d60a60b8c79f1, 0x584e1cde00b07aee,
00056     0x1573cd93da7df623, 0x47f98d79620dd535
00057 };
00058 
00059 typedef struct OMAContext {
00060     uint64_t content_start;
00061     int encrypted;
00062     uint16_t k_size;
00063     uint16_t e_size;
00064     uint16_t i_size;
00065     uint16_t s_size;
00066     uint32_t rid;
00067     uint8_t r_val[24];
00068     uint8_t n_val[24];
00069     uint8_t m_val[8];
00070     uint8_t s_val[8];
00071     uint8_t sm_val[8];
00072     uint8_t e_val[8];
00073     uint8_t iv[8];
00074     struct AVDES av_des;
00075 } OMAContext;
00076 
00077 static void hex_log(AVFormatContext *s, int level, const char *name, const uint8_t *value, int len)
00078 {
00079     char buf[33];
00080     len = FFMIN(len, 16);
00081     if (av_log_get_level() < level)
00082         return;
00083     ff_data_to_hex(buf, value, len, 1);
00084     buf[len<<1] = '\0';
00085     av_log(s, level, "%s: %s\n", name, buf);
00086 }
00087 
00088 static int kset(AVFormatContext *s, const uint8_t *r_val, const uint8_t *n_val, int len)
00089 {
00090     OMAContext *oc = s->priv_data;
00091 
00092     if (!r_val && !n_val)
00093         return -1;
00094 
00095     len = FFMIN(len, 16);
00096 
00097     /* use first 64 bits in the third round again */
00098     if (r_val) {
00099         if (r_val != oc->r_val) {
00100             memset(oc->r_val, 0, 24);
00101             memcpy(oc->r_val, r_val, len);
00102         }
00103         memcpy(&oc->r_val[16], r_val, 8);
00104     }
00105     if (n_val) {
00106         if (n_val != oc->n_val) {
00107             memset(oc->n_val, 0, 24);
00108             memcpy(oc->n_val, n_val, len);
00109         }
00110         memcpy(&oc->n_val[16], n_val, 8);
00111     }
00112 
00113     return 0;
00114 }
00115 
00116 #define OMA_RPROBE_M_VAL 48 + 1
00117 
00118 static int rprobe(AVFormatContext *s, uint8_t *enc_header, unsigned size,
00119                   const uint8_t *r_val)
00120 {
00121     OMAContext *oc = s->priv_data;
00122     unsigned int pos;
00123     struct AVDES av_des;
00124 
00125     if (!enc_header || !r_val ||
00126         size < OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size + oc->i_size ||
00127         size < OMA_RPROBE_M_VAL)
00128         return -1;
00129 
00130     /* m_val */
00131     av_des_init(&av_des, r_val, 192, 1);
00132     av_des_crypt(&av_des, oc->m_val, &enc_header[48], 1, NULL, 1);
00133 
00134     /* s_val */
00135     av_des_init(&av_des, oc->m_val, 64, 0);
00136     av_des_crypt(&av_des, oc->s_val, NULL, 1, NULL, 0);
00137 
00138     /* sm_val */
00139     pos = OMA_ENC_HEADER_SIZE + oc->k_size + oc->e_size;
00140     av_des_init(&av_des, oc->s_val, 64, 0);
00141     av_des_mac(&av_des, oc->sm_val, &enc_header[pos], (oc->i_size >> 3));
00142 
00143     pos += oc->i_size;
00144 
00145     return memcmp(&enc_header[pos], oc->sm_val, 8) ? -1 : 0;
00146 }
00147 
00148 static int nprobe(AVFormatContext *s, uint8_t *enc_header, unsigned size,
00149                   const uint8_t *n_val)
00150 {
00151     OMAContext *oc = s->priv_data;
00152     uint64_t pos;
00153     uint32_t taglen, datalen;
00154     struct AVDES av_des;
00155 
00156     if (!enc_header || !n_val ||
00157         size < OMA_ENC_HEADER_SIZE + oc->k_size + 4)
00158         return -1;
00159 
00160     pos = OMA_ENC_HEADER_SIZE + oc->k_size;
00161     if (!memcmp(&enc_header[pos], "EKB ", 4))
00162         pos += 32;
00163 
00164     if (size < pos + 44)
00165         return -1;
00166 
00167     if (AV_RB32(&enc_header[pos]) != oc->rid)
00168         av_log(s, AV_LOG_DEBUG, "Mismatching RID\n");
00169 
00170     taglen = AV_RB32(&enc_header[pos+32]);
00171     datalen = AV_RB32(&enc_header[pos+36]) >> 4;
00172 
00173     pos += 44;
00174     if (size - pos < taglen)
00175         return -1;
00176 
00177     pos += taglen;
00178 
00179     if (datalen << 4 > size - pos)
00180         return -1;
00181 
00182     av_des_init(&av_des, n_val, 192, 1);
00183     while (datalen-- > 0) {
00184         av_des_crypt(&av_des, oc->r_val, &enc_header[pos], 2, NULL, 1);
00185         kset(s, oc->r_val, NULL, 16);
00186         if (!rprobe(s, enc_header, size, oc->r_val))
00187             return 0;
00188         pos += 16;
00189     }
00190 
00191     return -1;
00192 }
00193 
00194 static int decrypt_init(AVFormatContext *s, ID3v2ExtraMeta *em, uint8_t *header)
00195 {
00196     OMAContext *oc = s->priv_data;
00197     ID3v2ExtraMetaGEOB *geob = NULL;
00198     uint8_t *gdata;
00199 
00200     oc->encrypted = 1;
00201     av_log(s, AV_LOG_INFO, "File is encrypted\n");
00202 
00203     /* find GEOB metadata */
00204     while (em) {
00205         if (!strcmp(em->tag, "GEOB") &&
00206             (geob = em->data) &&
00207             (!strcmp(geob->description, "OMG_LSI") ||
00208              !strcmp(geob->description, "OMG_BKLSI"))) {
00209             break;
00210         }
00211         em = em->next;
00212     }
00213     if (!em) {
00214         av_log(s, AV_LOG_ERROR, "No encryption header found\n");
00215         return -1;
00216     }
00217 
00218     if (geob->datasize < 64) {
00219         av_log(s, AV_LOG_ERROR, "Invalid GEOB data size: %u\n", geob->datasize);
00220         return -1;
00221     }
00222 
00223     gdata = geob->data;
00224 
00225     if (AV_RB16(gdata) != 1)
00226         av_log(s, AV_LOG_WARNING, "Unknown version in encryption header\n");
00227 
00228     oc->k_size = AV_RB16(&gdata[2]);
00229     oc->e_size = AV_RB16(&gdata[4]);
00230     oc->i_size = AV_RB16(&gdata[6]);
00231     oc->s_size = AV_RB16(&gdata[8]);
00232 
00233     if (memcmp(&gdata[OMA_ENC_HEADER_SIZE], "KEYRING     ", 12)) {
00234         av_log(s, AV_LOG_ERROR, "Invalid encryption header\n");
00235         return -1;
00236     }
00237     oc->rid = AV_RB32(&gdata[OMA_ENC_HEADER_SIZE + 28]);
00238     av_log(s, AV_LOG_DEBUG, "RID: %.8x\n", oc->rid);
00239 
00240     memcpy(oc->iv, &header[0x58], 8);
00241     hex_log(s, AV_LOG_DEBUG, "IV", oc->iv, 8);
00242 
00243     hex_log(s, AV_LOG_DEBUG, "CBC-MAC", &gdata[OMA_ENC_HEADER_SIZE+oc->k_size+oc->e_size+oc->i_size], 8);
00244 
00245     if (s->keylen > 0) {
00246         kset(s, s->key, s->key, s->keylen);
00247     }
00248     if (!memcmp(oc->r_val, (const uint8_t[8]){0}, 8) ||
00249         rprobe(s, gdata, geob->datasize, oc->r_val) < 0 &&
00250         nprobe(s, gdata, geob->datasize, oc->n_val) < 0) {
00251         int i;
00252         for (i = 0; i < FF_ARRAY_ELEMS(leaf_table); i += 2) {
00253             uint8_t buf[16];
00254             AV_WL64(buf, leaf_table[i]);
00255             AV_WL64(&buf[8], leaf_table[i+1]);
00256             kset(s, buf, buf, 16);
00257             if (!rprobe(s, gdata, geob->datasize, oc->r_val) ||
00258                 !nprobe(s, gdata, geob->datasize, oc->n_val))
00259                 break;
00260         }
00261         if (i >= sizeof(leaf_table)) {
00262             av_log(s, AV_LOG_ERROR, "Invalid key\n");
00263             return -1;
00264         }
00265     }
00266 
00267     /* e_val */
00268     av_des_init(&oc->av_des, oc->m_val, 64, 0);
00269     av_des_crypt(&oc->av_des, oc->e_val, &gdata[OMA_ENC_HEADER_SIZE + 40], 1, NULL, 0);
00270     hex_log(s, AV_LOG_DEBUG, "EK", oc->e_val, 8);
00271 
00272     /* init e_val */
00273     av_des_init(&oc->av_des, oc->e_val, 64, 1);
00274 
00275     return 0;
00276 }
00277 
00278 static int oma_read_header(AVFormatContext *s,
00279                            AVFormatParameters *ap)
00280 {
00281     int     ret, framesize, jsflag, samplerate;
00282     uint32_t codec_params;
00283     int16_t eid;
00284     uint8_t buf[EA3_HEADER_SIZE];
00285     uint8_t *edata;
00286     AVStream *st;
00287     ID3v2ExtraMeta *extra_meta = NULL;
00288     OMAContext *oc = s->priv_data;
00289 
00290     ff_id3v2_read_all(s, ID3v2_EA3_MAGIC, &extra_meta);
00291     ret = avio_read(s->pb, buf, EA3_HEADER_SIZE);
00292     if (ret < EA3_HEADER_SIZE)
00293         return -1;
00294 
00295     if (memcmp(buf, ((const uint8_t[]){'E', 'A', '3'}),3) || buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {
00296         av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");
00297         return -1;
00298     }
00299 
00300     oc->content_start = avio_tell(s->pb);
00301 
00302     /* encrypted file */
00303     eid = AV_RB16(&buf[6]);
00304     if (eid != -1 && eid != -128 && decrypt_init(s, extra_meta, buf) < 0) {
00305         ff_id3v2_free_extra_meta(&extra_meta);
00306         return -1;
00307     }
00308 
00309     ff_id3v2_free_extra_meta(&extra_meta);
00310 
00311     codec_params = AV_RB24(&buf[33]);
00312 
00313     st = avformat_new_stream(s, NULL);
00314     if (!st)
00315         return AVERROR(ENOMEM);
00316 
00317     st->start_time = 0;
00318     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
00319     st->codec->codec_tag   = buf[32];
00320     st->codec->codec_id    = ff_codec_get_id(ff_oma_codec_tags, st->codec->codec_tag);
00321 
00322     switch (buf[32]) {
00323         case OMA_CODECID_ATRAC3:
00324             samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;
00325             if (!samplerate) {
00326                 av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");
00327                 return AVERROR_INVALIDDATA;
00328             }
00329             if (samplerate != 44100)
00330                 av_log_ask_for_sample(s, "Unsupported sample rate: %d\n",
00331                                       samplerate);
00332 
00333             framesize = (codec_params & 0x3FF) * 8;
00334             jsflag = (codec_params >> 17) & 1; /* get stereo coding mode, 1 for joint-stereo */
00335             st->codec->channels    = 2;
00336             st->codec->sample_rate = samplerate;
00337             st->codec->bit_rate    = st->codec->sample_rate * framesize * 8 / 1024;
00338 
00339             /* fake the atrac3 extradata (wav format, makes stream copy to wav work) */
00340             st->codec->extradata_size = 14;
00341             edata = av_mallocz(14 + FF_INPUT_BUFFER_PADDING_SIZE);
00342             if (!edata)
00343                 return AVERROR(ENOMEM);
00344 
00345             st->codec->extradata = edata;
00346             AV_WL16(&edata[0],  1);             // always 1
00347             AV_WL32(&edata[2],  samplerate);    // samples rate
00348             AV_WL16(&edata[6],  jsflag);        // coding mode
00349             AV_WL16(&edata[8],  jsflag);        // coding mode
00350             AV_WL16(&edata[10], 1);             // always 1
00351             // AV_WL16(&edata[12], 0);          // always 0
00352 
00353             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
00354             break;
00355         case OMA_CODECID_ATRAC3P:
00356             st->codec->channels = (codec_params >> 10) & 7;
00357             framesize = ((codec_params & 0x3FF) * 8) + 8;
00358             samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;
00359             if (!samplerate) {
00360                 av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");
00361                 return AVERROR_INVALIDDATA;
00362             }
00363             st->codec->sample_rate = samplerate;
00364             st->codec->bit_rate    = samplerate * framesize * 8 / 1024;
00365             avpriv_set_pts_info(st, 64, 1, samplerate);
00366             av_log(s, AV_LOG_ERROR, "Unsupported codec ATRAC3+!\n");
00367             break;
00368         case OMA_CODECID_MP3:
00369             st->need_parsing = AVSTREAM_PARSE_FULL;
00370             framesize = 1024;
00371             break;
00372         case OMA_CODECID_LPCM:
00373             /* PCM 44.1 kHz 16 bit stereo big-endian */
00374             st->codec->channels = 2;
00375             st->codec->sample_rate = 44100;
00376             framesize = 1024;
00377             /* bit rate = sample rate x PCM block align (= 4) x 8 */
00378             st->codec->bit_rate = st->codec->sample_rate * 32;
00379             st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);
00380             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
00381             break;
00382         default:
00383             av_log(s, AV_LOG_ERROR, "Unsupported codec %d!\n",buf[32]);
00384             return -1;
00385     }
00386 
00387     st->codec->block_align = framesize;
00388 
00389     return 0;
00390 }
00391 
00392 
00393 static int oma_read_packet(AVFormatContext *s, AVPacket *pkt)
00394 {
00395     OMAContext *oc = s->priv_data;
00396     int packet_size = s->streams[0]->codec->block_align;
00397     int ret = av_get_packet(s->pb, pkt, packet_size);
00398 
00399     if (ret < packet_size)
00400         pkt->flags |= AV_PKT_FLAG_CORRUPT;
00401 
00402     if (ret <= 0)
00403         return AVERROR(EIO);
00404 
00405     pkt->stream_index = 0;
00406 
00407     if (oc->encrypted) {
00408         /* previous unencrypted block saved in IV for
00409          * the next packet (CBC mode) */
00410         if (ret == packet_size)
00411             av_des_crypt(&oc->av_des, pkt->data, pkt->data,
00412                          (packet_size >> 3), oc->iv, 1);
00413         else
00414             memset(oc->iv, 0, 8);
00415     }
00416 
00417     return ret;
00418 }
00419 
00420 static int oma_read_probe(AVProbeData *p)
00421 {
00422     const uint8_t *buf;
00423     unsigned tag_len = 0;
00424 
00425     buf = p->buf;
00426 
00427     if (p->buf_size < ID3v2_HEADER_SIZE ||
00428         !ff_id3v2_match(buf, ID3v2_EA3_MAGIC) ||
00429         buf[3] != 3 || // version must be 3
00430         buf[4]) // flags byte zero
00431         return 0;
00432 
00433     tag_len = ff_id3v2_tag_len(buf);
00434 
00435     /* This check cannot overflow as tag_len has at most 28 bits */
00436     if (p->buf_size < tag_len + 5)
00437         /* EA3 header comes late, might be outside of the probe buffer */
00438         return AVPROBE_SCORE_MAX / 2;
00439 
00440     buf += tag_len;
00441 
00442     if (!memcmp(buf, "EA3", 3) && !buf[4] && buf[5] == EA3_HEADER_SIZE)
00443         return AVPROBE_SCORE_MAX;
00444     else
00445         return 0;
00446 }
00447 
00448 static int oma_read_seek(struct AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
00449 {
00450     OMAContext *oc = s->priv_data;
00451 
00452     int err = pcm_read_seek(s, stream_index, timestamp, flags);
00453 
00454     if (!oc->encrypted)
00455         return err;
00456 
00457     /* readjust IV for CBC */
00458     if (err || avio_tell(s->pb) < oc->content_start)
00459         goto wipe;
00460     if ((err = avio_seek(s->pb, -8, SEEK_CUR)) < 0)
00461         goto wipe;
00462     if ((err = avio_read(s->pb, oc->iv, 8)) < 8) {
00463         if (err >= 0)
00464             err = AVERROR_EOF;
00465         goto wipe;
00466     }
00467 
00468     return 0;
00469 wipe:
00470     memset(oc->iv, 0, 8);
00471     return err;
00472 }
00473 
00474 AVInputFormat ff_oma_demuxer = {
00475     .name           = "oma",
00476     .long_name      = NULL_IF_CONFIG_SMALL("Sony OpenMG audio"),
00477     .priv_data_size = sizeof(OMAContext),
00478     .read_probe     = oma_read_probe,
00479     .read_header    = oma_read_header,
00480     .read_packet    = oma_read_packet,
00481     .read_seek      = oma_read_seek,
00482     .flags          = AVFMT_GENERIC_INDEX,
00483     .extensions     = "oma,omg,aa3",
00484     .codec_tag      = (const AVCodecTag* const []){ff_oma_codec_tags, 0},
00485 };
00486