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 + taglen;
00174 
00175     if (datalen << 4 > size - pos)
00176         return -1;
00177 
00178     av_des_init(&av_des, n_val, 192, 1);
00179     while (datalen-- > 0) {
00180         av_des_crypt(&av_des, oc->r_val, &enc_header[pos], 2, NULL, 1);
00181         kset(s, oc->r_val, NULL, 16);
00182         if (!rprobe(s, enc_header, size, oc->r_val))
00183             return 0;
00184         pos += 16;
00185     }
00186 
00187     return -1;
00188 }
00189 
00190 static int decrypt_init(AVFormatContext *s, ID3v2ExtraMeta *em, uint8_t *header)
00191 {
00192     OMAContext *oc = s->priv_data;
00193     ID3v2ExtraMetaGEOB *geob = NULL;
00194     uint8_t *gdata;
00195 
00196     oc->encrypted = 1;
00197     av_log(s, AV_LOG_INFO, "File is encrypted\n");
00198 
00199     /* find GEOB metadata */
00200     while (em) {
00201         if (!strcmp(em->tag, "GEOB") &&
00202             (geob = em->data) &&
00203             (!strcmp(geob->description, "OMG_LSI") ||
00204              !strcmp(geob->description, "OMG_BKLSI"))) {
00205             break;
00206         }
00207         em = em->next;
00208     }
00209     if (!em) {
00210         av_log(s, AV_LOG_ERROR, "No encryption header found\n");
00211         return -1;
00212     }
00213 
00214     if (geob->datasize < 64) {
00215         av_log(s, AV_LOG_ERROR, "Invalid GEOB data size: %u\n", geob->datasize);
00216         return -1;
00217     }
00218 
00219     gdata = geob->data;
00220 
00221     if (AV_RB16(gdata) != 1)
00222         av_log(s, AV_LOG_WARNING, "Unknown version in encryption header\n");
00223 
00224     oc->k_size = AV_RB16(&gdata[2]);
00225     oc->e_size = AV_RB16(&gdata[4]);
00226     oc->i_size = AV_RB16(&gdata[6]);
00227     oc->s_size = AV_RB16(&gdata[8]);
00228 
00229     if (memcmp(&gdata[OMA_ENC_HEADER_SIZE], "KEYRING     ", 12)) {
00230         av_log(s, AV_LOG_ERROR, "Invalid encryption header\n");
00231         return -1;
00232     }
00233     oc->rid = AV_RB32(&gdata[OMA_ENC_HEADER_SIZE + 28]);
00234     av_log(s, AV_LOG_DEBUG, "RID: %.8x\n", oc->rid);
00235 
00236     memcpy(oc->iv, &header[0x58], 8);
00237     hex_log(s, AV_LOG_DEBUG, "IV", oc->iv, 8);
00238 
00239     hex_log(s, AV_LOG_DEBUG, "CBC-MAC", &gdata[OMA_ENC_HEADER_SIZE+oc->k_size+oc->e_size+oc->i_size], 8);
00240 
00241     if (s->keylen > 0) {
00242         kset(s, s->key, s->key, s->keylen);
00243     }
00244     if (!memcmp(oc->r_val, (const uint8_t[8]){0}, 8) ||
00245         rprobe(s, gdata, geob->datasize, oc->r_val) < 0 &&
00246         nprobe(s, gdata, geob->datasize, oc->n_val) < 0) {
00247         int i;
00248         for (i = 0; i < FF_ARRAY_ELEMS(leaf_table); i += 2) {
00249             uint8_t buf[16];
00250             AV_WL64(buf, leaf_table[i]);
00251             AV_WL64(&buf[8], leaf_table[i+1]);
00252             kset(s, buf, buf, 16);
00253             if (!rprobe(s, gdata, geob->datasize, oc->r_val) ||
00254                 !nprobe(s, gdata, geob->datasize, oc->n_val))
00255                 break;
00256         }
00257         if (i >= sizeof(leaf_table)) {
00258             av_log(s, AV_LOG_ERROR, "Invalid key\n");
00259             return -1;
00260         }
00261     }
00262 
00263     /* e_val */
00264     av_des_init(&oc->av_des, oc->m_val, 64, 0);
00265     av_des_crypt(&oc->av_des, oc->e_val, &gdata[OMA_ENC_HEADER_SIZE + 40], 1, NULL, 0);
00266     hex_log(s, AV_LOG_DEBUG, "EK", oc->e_val, 8);
00267 
00268     /* init e_val */
00269     av_des_init(&oc->av_des, oc->e_val, 64, 1);
00270 
00271     return 0;
00272 }
00273 
00274 static int oma_read_header(AVFormatContext *s,
00275                            AVFormatParameters *ap)
00276 {
00277     int     ret, framesize, jsflag, samplerate;
00278     uint32_t codec_params;
00279     int16_t eid;
00280     uint8_t buf[EA3_HEADER_SIZE];
00281     uint8_t *edata;
00282     AVStream *st;
00283     ID3v2ExtraMeta *extra_meta = NULL;
00284     OMAContext *oc = s->priv_data;
00285 
00286     ff_id3v2_read_all(s, ID3v2_EA3_MAGIC, &extra_meta);
00287     ret = avio_read(s->pb, buf, EA3_HEADER_SIZE);
00288     if (ret < EA3_HEADER_SIZE)
00289         return -1;
00290 
00291     if (memcmp(buf, ((const uint8_t[]){'E', 'A', '3'}),3) || buf[4] != 0 || buf[5] != EA3_HEADER_SIZE) {
00292         av_log(s, AV_LOG_ERROR, "Couldn't find the EA3 header !\n");
00293         return -1;
00294     }
00295 
00296     oc->content_start = avio_tell(s->pb);
00297 
00298     /* encrypted file */
00299     eid = AV_RB16(&buf[6]);
00300     if (eid != -1 && eid != -128 && decrypt_init(s, extra_meta, buf) < 0) {
00301         ff_id3v2_free_extra_meta(&extra_meta);
00302         return -1;
00303     }
00304 
00305     ff_id3v2_free_extra_meta(&extra_meta);
00306 
00307     codec_params = AV_RB24(&buf[33]);
00308 
00309     st = avformat_new_stream(s, NULL);
00310     if (!st)
00311         return AVERROR(ENOMEM);
00312 
00313     st->start_time = 0;
00314     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
00315     st->codec->codec_tag   = buf[32];
00316     st->codec->codec_id    = ff_codec_get_id(ff_oma_codec_tags, st->codec->codec_tag);
00317 
00318     switch (buf[32]) {
00319         case OMA_CODECID_ATRAC3:
00320             samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;
00321             if (!samplerate) {
00322                 av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");
00323                 return AVERROR_INVALIDDATA;
00324             }
00325             if (samplerate != 44100)
00326                 av_log_ask_for_sample(s, "Unsupported sample rate: %d\n",
00327                                       samplerate);
00328 
00329             framesize = (codec_params & 0x3FF) * 8;
00330             jsflag = (codec_params >> 17) & 1; /* get stereo coding mode, 1 for joint-stereo */
00331             st->codec->channels    = 2;
00332             st->codec->sample_rate = samplerate;
00333             st->codec->bit_rate    = st->codec->sample_rate * framesize * 8 / 1024;
00334 
00335             /* fake the atrac3 extradata (wav format, makes stream copy to wav work) */
00336             st->codec->extradata_size = 14;
00337             edata = av_mallocz(14 + FF_INPUT_BUFFER_PADDING_SIZE);
00338             if (!edata)
00339                 return AVERROR(ENOMEM);
00340 
00341             st->codec->extradata = edata;
00342             AV_WL16(&edata[0],  1);             // always 1
00343             AV_WL32(&edata[2],  samplerate);    // samples rate
00344             AV_WL16(&edata[6],  jsflag);        // coding mode
00345             AV_WL16(&edata[8],  jsflag);        // coding mode
00346             AV_WL16(&edata[10], 1);             // always 1
00347             // AV_WL16(&edata[12], 0);          // always 0
00348 
00349             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
00350             break;
00351         case OMA_CODECID_ATRAC3P:
00352             st->codec->channels = (codec_params >> 10) & 7;
00353             framesize = ((codec_params & 0x3FF) * 8) + 8;
00354             samplerate = ff_oma_srate_tab[(codec_params >> 13) & 7] * 100;
00355             if (!samplerate) {
00356                 av_log(s, AV_LOG_ERROR, "Unsupported sample rate\n");
00357                 return AVERROR_INVALIDDATA;
00358             }
00359             st->codec->sample_rate = samplerate;
00360             st->codec->bit_rate    = samplerate * framesize * 8 / 1024;
00361             avpriv_set_pts_info(st, 64, 1, samplerate);
00362             av_log(s, AV_LOG_ERROR, "Unsupported codec ATRAC3+!\n");
00363             break;
00364         case OMA_CODECID_MP3:
00365             st->need_parsing = AVSTREAM_PARSE_FULL;
00366             framesize = 1024;
00367             break;
00368         case OMA_CODECID_LPCM:
00369             /* PCM 44.1 kHz 16 bit stereo big-endian */
00370             st->codec->channels = 2;
00371             st->codec->sample_rate = 44100;
00372             framesize = 1024;
00373             /* bit rate = sample rate x PCM block align (= 4) x 8 */
00374             st->codec->bit_rate = st->codec->sample_rate * 32;
00375             st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);
00376             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
00377             break;
00378         default:
00379             av_log(s, AV_LOG_ERROR, "Unsupported codec %d!\n",buf[32]);
00380             return -1;
00381     }
00382 
00383     st->codec->block_align = framesize;
00384 
00385     return 0;
00386 }
00387 
00388 
00389 static int oma_read_packet(AVFormatContext *s, AVPacket *pkt)
00390 {
00391     OMAContext *oc = s->priv_data;
00392     int packet_size = s->streams[0]->codec->block_align;
00393     int ret = av_get_packet(s->pb, pkt, packet_size);
00394 
00395     if (ret < packet_size)
00396         pkt->flags |= AV_PKT_FLAG_CORRUPT;
00397 
00398     if (ret <= 0)
00399         return AVERROR(EIO);
00400 
00401     pkt->stream_index = 0;
00402 
00403     if (oc->encrypted) {
00404         /* previous unencrypted block saved in IV for
00405          * the next packet (CBC mode) */
00406         if (ret == packet_size)
00407             av_des_crypt(&oc->av_des, pkt->data, pkt->data,
00408                          (packet_size >> 3), oc->iv, 1);
00409         else
00410             memset(oc->iv, 0, 8);
00411     }
00412 
00413     return ret;
00414 }
00415 
00416 static int oma_read_probe(AVProbeData *p)
00417 {
00418     const uint8_t *buf;
00419     unsigned tag_len = 0;
00420 
00421     buf = p->buf;
00422 
00423     if (p->buf_size < ID3v2_HEADER_SIZE ||
00424         !ff_id3v2_match(buf, ID3v2_EA3_MAGIC) ||
00425         buf[3] != 3 || // version must be 3
00426         buf[4]) // flags byte zero
00427         return 0;
00428 
00429     tag_len = ff_id3v2_tag_len(buf);
00430 
00431     /* This check cannot overflow as tag_len has at most 28 bits */
00432     if (p->buf_size < tag_len + 5)
00433         /* EA3 header comes late, might be outside of the probe buffer */
00434         return AVPROBE_SCORE_MAX / 2;
00435 
00436     buf += tag_len;
00437 
00438     if (!memcmp(buf, "EA3", 3) && !buf[4] && buf[5] == EA3_HEADER_SIZE)
00439         return AVPROBE_SCORE_MAX;
00440     else
00441         return 0;
00442 }
00443 
00444 static int oma_read_seek(struct AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
00445 {
00446     OMAContext *oc = s->priv_data;
00447 
00448     int err = pcm_read_seek(s, stream_index, timestamp, flags);
00449 
00450     if (!oc->encrypted)
00451         return err;
00452 
00453     /* readjust IV for CBC */
00454     if (err || avio_tell(s->pb) < oc->content_start)
00455         goto wipe;
00456     if ((err = avio_seek(s->pb, -8, SEEK_CUR)) < 0)
00457         goto wipe;
00458     if ((err = avio_read(s->pb, oc->iv, 8)) < 8) {
00459         if (err >= 0)
00460             err = AVERROR_EOF;
00461         goto wipe;
00462     }
00463 
00464     return 0;
00465 wipe:
00466     memset(oc->iv, 0, 8);
00467     return err;
00468 }
00469 
00470 AVInputFormat ff_oma_demuxer = {
00471     .name           = "oma",
00472     .long_name      = NULL_IF_CONFIG_SMALL("Sony OpenMG audio"),
00473     .priv_data_size = sizeof(OMAContext),
00474     .read_probe     = oma_read_probe,
00475     .read_header    = oma_read_header,
00476     .read_packet    = oma_read_packet,
00477     .read_seek      = oma_read_seek,
00478     .flags          = AVFMT_GENERIC_INDEX,
00479     .extensions     = "oma,omg,aa3",
00480     .codec_tag      = (const AVCodecTag* const []){ff_oma_codec_tags, 0},
00481 };
00482