Home | History | Annotate | Download | only in libstagefright
      1 /*
      2  * Copyright (C) 2009 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 //#define LOG_NDEBUG 0
     18 #define LOG_TAG "Utils"
     19 #include <utils/Log.h>
     20 #include <ctype.h>
     21 
     22 #include "include/ESDS.h"
     23 
     24 #include <arpa/inet.h>
     25 #include <cutils/properties.h>
     26 #include <media/openmax/OMX_Audio.h>
     27 #include <media/stagefright/foundation/ABuffer.h>
     28 #include <media/stagefright/foundation/ADebug.h>
     29 #include <media/stagefright/foundation/AMessage.h>
     30 #include <media/stagefright/MetaData.h>
     31 #include <media/stagefright/MediaDefs.h>
     32 #include <media/AudioSystem.h>
     33 #include <media/MediaPlayerInterface.h>
     34 #include <hardware/audio.h>
     35 #include <media/stagefright/Utils.h>
     36 #include <media/AudioParameter.h>
     37 
     38 namespace android {
     39 
     40 uint16_t U16_AT(const uint8_t *ptr) {
     41     return ptr[0] << 8 | ptr[1];
     42 }
     43 
     44 uint32_t U32_AT(const uint8_t *ptr) {
     45     return ptr[0] << 24 | ptr[1] << 16 | ptr[2] << 8 | ptr[3];
     46 }
     47 
     48 uint64_t U64_AT(const uint8_t *ptr) {
     49     return ((uint64_t)U32_AT(ptr)) << 32 | U32_AT(ptr + 4);
     50 }
     51 
     52 uint16_t U16LE_AT(const uint8_t *ptr) {
     53     return ptr[0] | (ptr[1] << 8);
     54 }
     55 
     56 uint32_t U32LE_AT(const uint8_t *ptr) {
     57     return ptr[3] << 24 | ptr[2] << 16 | ptr[1] << 8 | ptr[0];
     58 }
     59 
     60 uint64_t U64LE_AT(const uint8_t *ptr) {
     61     return ((uint64_t)U32LE_AT(ptr + 4)) << 32 | U32LE_AT(ptr);
     62 }
     63 
     64 // XXX warning: these won't work on big-endian host.
     65 uint64_t ntoh64(uint64_t x) {
     66     return ((uint64_t)ntohl(x & 0xffffffff) << 32) | ntohl(x >> 32);
     67 }
     68 
     69 uint64_t hton64(uint64_t x) {
     70     return ((uint64_t)htonl(x & 0xffffffff) << 32) | htonl(x >> 32);
     71 }
     72 
     73 status_t convertMetaDataToMessage(
     74         const sp<MetaData> &meta, sp<AMessage> *format) {
     75     format->clear();
     76 
     77     const char *mime;
     78     CHECK(meta->findCString(kKeyMIMEType, &mime));
     79 
     80     sp<AMessage> msg = new AMessage;
     81     msg->setString("mime", mime);
     82 
     83     int64_t durationUs;
     84     if (meta->findInt64(kKeyDuration, &durationUs)) {
     85         msg->setInt64("durationUs", durationUs);
     86     }
     87 
     88     int avgBitRate;
     89     if (meta->findInt32(kKeyBitRate, &avgBitRate)) {
     90         msg->setInt32("bit-rate", avgBitRate);
     91     }
     92 
     93     int32_t isSync;
     94     if (meta->findInt32(kKeyIsSyncFrame, &isSync) && isSync != 0) {
     95         msg->setInt32("is-sync-frame", 1);
     96     }
     97 
     98     if (!strncasecmp("video/", mime, 6)) {
     99         int32_t width, height;
    100         CHECK(meta->findInt32(kKeyWidth, &width));
    101         CHECK(meta->findInt32(kKeyHeight, &height));
    102 
    103         msg->setInt32("width", width);
    104         msg->setInt32("height", height);
    105 
    106         int32_t sarWidth, sarHeight;
    107         if (meta->findInt32(kKeySARWidth, &sarWidth)
    108                 && meta->findInt32(kKeySARHeight, &sarHeight)) {
    109             msg->setInt32("sar-width", sarWidth);
    110             msg->setInt32("sar-height", sarHeight);
    111         }
    112 
    113         int32_t colorFormat;
    114         if (meta->findInt32(kKeyColorFormat, &colorFormat)) {
    115             msg->setInt32("color-format", colorFormat);
    116         }
    117 
    118         int32_t cropLeft, cropTop, cropRight, cropBottom;
    119         if (meta->findRect(kKeyCropRect,
    120                            &cropLeft,
    121                            &cropTop,
    122                            &cropRight,
    123                            &cropBottom)) {
    124             msg->setRect("crop", cropLeft, cropTop, cropRight, cropBottom);
    125         }
    126 
    127         int32_t rotationDegrees;
    128         if (meta->findInt32(kKeyRotation, &rotationDegrees)) {
    129             msg->setInt32("rotation-degrees", rotationDegrees);
    130         }
    131     } else if (!strncasecmp("audio/", mime, 6)) {
    132         int32_t numChannels, sampleRate;
    133         CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
    134         CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
    135 
    136         msg->setInt32("channel-count", numChannels);
    137         msg->setInt32("sample-rate", sampleRate);
    138 
    139         int32_t channelMask;
    140         if (meta->findInt32(kKeyChannelMask, &channelMask)) {
    141             msg->setInt32("channel-mask", channelMask);
    142         }
    143 
    144         int32_t delay = 0;
    145         if (meta->findInt32(kKeyEncoderDelay, &delay)) {
    146             msg->setInt32("encoder-delay", delay);
    147         }
    148         int32_t padding = 0;
    149         if (meta->findInt32(kKeyEncoderPadding, &padding)) {
    150             msg->setInt32("encoder-padding", padding);
    151         }
    152 
    153         int32_t isADTS;
    154         if (meta->findInt32(kKeyIsADTS, &isADTS)) {
    155             msg->setInt32("is-adts", true);
    156         }
    157 
    158         int32_t aacProfile = -1;
    159         if (meta->findInt32(kKeyAACAOT, &aacProfile)) {
    160             msg->setInt32("aac-profile", aacProfile);
    161         }
    162     }
    163 
    164     int32_t maxInputSize;
    165     if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
    166         msg->setInt32("max-input-size", maxInputSize);
    167     }
    168 
    169     int32_t rotationDegrees;
    170     if (meta->findInt32(kKeyRotation, &rotationDegrees)) {
    171         msg->setInt32("rotation-degrees", rotationDegrees);
    172     }
    173 
    174     uint32_t type;
    175     const void *data;
    176     size_t size;
    177     if (meta->findData(kKeyAVCC, &type, &data, &size)) {
    178         // Parse the AVCDecoderConfigurationRecord
    179 
    180         const uint8_t *ptr = (const uint8_t *)data;
    181 
    182         CHECK(size >= 7);
    183         CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
    184         uint8_t profile = ptr[1];
    185         uint8_t level = ptr[3];
    186 
    187         // There is decodable content out there that fails the following
    188         // assertion, let's be lenient for now...
    189         // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
    190 
    191         size_t lengthSize = 1 + (ptr[4] & 3);
    192 
    193         // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
    194         // violates it...
    195         // CHECK((ptr[5] >> 5) == 7);  // reserved
    196 
    197         size_t numSeqParameterSets = ptr[5] & 31;
    198 
    199         ptr += 6;
    200         size -= 6;
    201 
    202         sp<ABuffer> buffer = new ABuffer(1024);
    203         buffer->setRange(0, 0);
    204 
    205         for (size_t i = 0; i < numSeqParameterSets; ++i) {
    206             CHECK(size >= 2);
    207             size_t length = U16_AT(ptr);
    208 
    209             ptr += 2;
    210             size -= 2;
    211 
    212             CHECK(size >= length);
    213 
    214             memcpy(buffer->data() + buffer->size(), "\x00\x00\x00\x01", 4);
    215             memcpy(buffer->data() + buffer->size() + 4, ptr, length);
    216             buffer->setRange(0, buffer->size() + 4 + length);
    217 
    218             ptr += length;
    219             size -= length;
    220         }
    221 
    222         buffer->meta()->setInt32("csd", true);
    223         buffer->meta()->setInt64("timeUs", 0);
    224 
    225         msg->setBuffer("csd-0", buffer);
    226 
    227         buffer = new ABuffer(1024);
    228         buffer->setRange(0, 0);
    229 
    230         CHECK(size >= 1);
    231         size_t numPictureParameterSets = *ptr;
    232         ++ptr;
    233         --size;
    234 
    235         for (size_t i = 0; i < numPictureParameterSets; ++i) {
    236             CHECK(size >= 2);
    237             size_t length = U16_AT(ptr);
    238 
    239             ptr += 2;
    240             size -= 2;
    241 
    242             CHECK(size >= length);
    243 
    244             memcpy(buffer->data() + buffer->size(), "\x00\x00\x00\x01", 4);
    245             memcpy(buffer->data() + buffer->size() + 4, ptr, length);
    246             buffer->setRange(0, buffer->size() + 4 + length);
    247 
    248             ptr += length;
    249             size -= length;
    250         }
    251 
    252         buffer->meta()->setInt32("csd", true);
    253         buffer->meta()->setInt64("timeUs", 0);
    254         msg->setBuffer("csd-1", buffer);
    255     } else if (meta->findData(kKeyHVCC, &type, &data, &size)) {
    256         const uint8_t *ptr = (const uint8_t *)data;
    257 
    258         CHECK(size >= 7);
    259         CHECK_EQ((unsigned)ptr[0], 1u);  // configurationVersion == 1
    260         uint8_t profile = ptr[1] & 31;
    261         uint8_t level = ptr[12];
    262         ptr += 22;
    263         size -= 22;
    264 
    265 
    266         size_t numofArrays = (char)ptr[0];
    267         ptr += 1;
    268         size -= 1;
    269         size_t j = 0, i = 0;
    270 
    271         sp<ABuffer> buffer = new ABuffer(1024);
    272         buffer->setRange(0, 0);
    273 
    274         for (i = 0; i < numofArrays; i++) {
    275             ptr += 1;
    276             size -= 1;
    277 
    278             //Num of nals
    279             size_t numofNals = U16_AT(ptr);
    280 
    281             ptr += 2;
    282             size -= 2;
    283 
    284             for (j = 0; j < numofNals; j++) {
    285                 CHECK(size >= 2);
    286                 size_t length = U16_AT(ptr);
    287 
    288                 ptr += 2;
    289                 size -= 2;
    290 
    291                 CHECK(size >= length);
    292 
    293                 memcpy(buffer->data() + buffer->size(), "\x00\x00\x00\x01", 4);
    294                 memcpy(buffer->data() + buffer->size() + 4, ptr, length);
    295                 buffer->setRange(0, buffer->size() + 4 + length);
    296 
    297                 ptr += length;
    298                 size -= length;
    299             }
    300         }
    301         buffer->meta()->setInt32("csd", true);
    302         buffer->meta()->setInt64("timeUs", 0);
    303         msg->setBuffer("csd-0", buffer);
    304 
    305     } else if (meta->findData(kKeyESDS, &type, &data, &size)) {
    306         ESDS esds((const char *)data, size);
    307         CHECK_EQ(esds.InitCheck(), (status_t)OK);
    308 
    309         const void *codec_specific_data;
    310         size_t codec_specific_data_size;
    311         esds.getCodecSpecificInfo(
    312                 &codec_specific_data, &codec_specific_data_size);
    313 
    314         sp<ABuffer> buffer = new ABuffer(codec_specific_data_size);
    315 
    316         memcpy(buffer->data(), codec_specific_data,
    317                codec_specific_data_size);
    318 
    319         buffer->meta()->setInt32("csd", true);
    320         buffer->meta()->setInt64("timeUs", 0);
    321         msg->setBuffer("csd-0", buffer);
    322     } else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
    323         sp<ABuffer> buffer = new ABuffer(size);
    324         memcpy(buffer->data(), data, size);
    325 
    326         buffer->meta()->setInt32("csd", true);
    327         buffer->meta()->setInt64("timeUs", 0);
    328         msg->setBuffer("csd-0", buffer);
    329 
    330         if (!meta->findData(kKeyVorbisBooks, &type, &data, &size)) {
    331             return -EINVAL;
    332         }
    333 
    334         buffer = new ABuffer(size);
    335         memcpy(buffer->data(), data, size);
    336 
    337         buffer->meta()->setInt32("csd", true);
    338         buffer->meta()->setInt64("timeUs", 0);
    339         msg->setBuffer("csd-1", buffer);
    340     } else if (meta->findData(kKeyOpusHeader, &type, &data, &size)) {
    341         sp<ABuffer> buffer = new ABuffer(size);
    342         memcpy(buffer->data(), data, size);
    343 
    344         buffer->meta()->setInt32("csd", true);
    345         buffer->meta()->setInt64("timeUs", 0);
    346         msg->setBuffer("csd-0", buffer);
    347     }
    348 
    349     *format = msg;
    350 
    351     return OK;
    352 }
    353 
    354 static size_t reassembleAVCC(const sp<ABuffer> &csd0, const sp<ABuffer> csd1, char *avcc) {
    355 
    356     avcc[0] = 1;        // version
    357     avcc[1] = 0x64;     // profile
    358     avcc[2] = 0;        // unused (?)
    359     avcc[3] = 0xd;      // level
    360     avcc[4] = 0xff;     // reserved+size
    361 
    362     size_t i = 0;
    363     int numparams = 0;
    364     int lastparamoffset = 0;
    365     int avccidx = 6;
    366     do {
    367         if (i >= csd0->size() - 4 ||
    368                 memcmp(csd0->data() + i, "\x00\x00\x00\x01", 4) == 0) {
    369             if (i >= csd0->size() - 4) {
    370                 // there can't be another param here, so use all the rest
    371                 i = csd0->size();
    372             }
    373             ALOGV("block at %zu, last was %d", i, lastparamoffset);
    374             if (lastparamoffset > 0) {
    375                 int size = i - lastparamoffset;
    376                 avcc[avccidx++] = size >> 8;
    377                 avcc[avccidx++] = size & 0xff;
    378                 memcpy(avcc+avccidx, csd0->data() + lastparamoffset, size);
    379                 avccidx += size;
    380                 numparams++;
    381             }
    382             i += 4;
    383             lastparamoffset = i;
    384         } else {
    385             i++;
    386         }
    387     } while(i < csd0->size());
    388     ALOGV("csd0 contains %d params", numparams);
    389 
    390     avcc[5] = 0xe0 | numparams;
    391     //and now csd-1
    392     i = 0;
    393     numparams = 0;
    394     lastparamoffset = 0;
    395     int numpicparamsoffset = avccidx;
    396     avccidx++;
    397     do {
    398         if (i >= csd1->size() - 4 ||
    399                 memcmp(csd1->data() + i, "\x00\x00\x00\x01", 4) == 0) {
    400             if (i >= csd1->size() - 4) {
    401                 // there can't be another param here, so use all the rest
    402                 i = csd1->size();
    403             }
    404             ALOGV("block at %zu, last was %d", i, lastparamoffset);
    405             if (lastparamoffset > 0) {
    406                 int size = i - lastparamoffset;
    407                 avcc[avccidx++] = size >> 8;
    408                 avcc[avccidx++] = size & 0xff;
    409                 memcpy(avcc+avccidx, csd1->data() + lastparamoffset, size);
    410                 avccidx += size;
    411                 numparams++;
    412             }
    413             i += 4;
    414             lastparamoffset = i;
    415         } else {
    416             i++;
    417         }
    418     } while(i < csd1->size());
    419     avcc[numpicparamsoffset] = numparams;
    420     return avccidx;
    421 }
    422 
    423 static void reassembleESDS(const sp<ABuffer> &csd0, char *esds) {
    424     int csd0size = csd0->size();
    425     esds[0] = 3; // kTag_ESDescriptor;
    426     int esdescriptorsize = 26 + csd0size;
    427     CHECK(esdescriptorsize < 268435456); // 7 bits per byte, so max is 2^28-1
    428     esds[1] = 0x80 | (esdescriptorsize >> 21);
    429     esds[2] = 0x80 | ((esdescriptorsize >> 14) & 0x7f);
    430     esds[3] = 0x80 | ((esdescriptorsize >> 7) & 0x7f);
    431     esds[4] = (esdescriptorsize & 0x7f);
    432     esds[5] = esds[6] = 0; // es id
    433     esds[7] = 0; // flags
    434     esds[8] = 4; // kTag_DecoderConfigDescriptor
    435     int configdescriptorsize = 18 + csd0size;
    436     esds[9] = 0x80 | (configdescriptorsize >> 21);
    437     esds[10] = 0x80 | ((configdescriptorsize >> 14) & 0x7f);
    438     esds[11] = 0x80 | ((configdescriptorsize >> 7) & 0x7f);
    439     esds[12] = (configdescriptorsize & 0x7f);
    440     esds[13] = 0x40; // objectTypeIndication
    441     esds[14] = 0x15; // not sure what 14-25 mean, they are ignored by ESDS.cpp,
    442     esds[15] = 0x00; // but the actual values here were taken from a real file.
    443     esds[16] = 0x18;
    444     esds[17] = 0x00;
    445     esds[18] = 0x00;
    446     esds[19] = 0x00;
    447     esds[20] = 0xfa;
    448     esds[21] = 0x00;
    449     esds[22] = 0x00;
    450     esds[23] = 0x00;
    451     esds[24] = 0xfa;
    452     esds[25] = 0x00;
    453     esds[26] = 5; // kTag_DecoderSpecificInfo;
    454     esds[27] = 0x80 | (csd0size >> 21);
    455     esds[28] = 0x80 | ((csd0size >> 14) & 0x7f);
    456     esds[29] = 0x80 | ((csd0size >> 7) & 0x7f);
    457     esds[30] = (csd0size & 0x7f);
    458     memcpy((void*)&esds[31], csd0->data(), csd0size);
    459     // data following this is ignored, so don't bother appending it
    460 
    461 }
    462 
    463 void convertMessageToMetaData(const sp<AMessage> &msg, sp<MetaData> &meta) {
    464     AString mime;
    465     if (msg->findString("mime", &mime)) {
    466         meta->setCString(kKeyMIMEType, mime.c_str());
    467     } else {
    468         ALOGW("did not find mime type");
    469     }
    470 
    471     int64_t durationUs;
    472     if (msg->findInt64("durationUs", &durationUs)) {
    473         meta->setInt64(kKeyDuration, durationUs);
    474     }
    475 
    476     int32_t isSync;
    477     if (msg->findInt32("is-sync-frame", &isSync) && isSync != 0) {
    478         meta->setInt32(kKeyIsSyncFrame, 1);
    479     }
    480 
    481     if (mime.startsWith("video/")) {
    482         int32_t width;
    483         int32_t height;
    484         if (msg->findInt32("width", &width) && msg->findInt32("height", &height)) {
    485             meta->setInt32(kKeyWidth, width);
    486             meta->setInt32(kKeyHeight, height);
    487         } else {
    488             ALOGW("did not find width and/or height");
    489         }
    490 
    491         int32_t sarWidth, sarHeight;
    492         if (msg->findInt32("sar-width", &sarWidth)
    493                 && msg->findInt32("sar-height", &sarHeight)) {
    494             meta->setInt32(kKeySARWidth, sarWidth);
    495             meta->setInt32(kKeySARHeight, sarHeight);
    496         }
    497 
    498         int32_t colorFormat;
    499         if (msg->findInt32("color-format", &colorFormat)) {
    500             meta->setInt32(kKeyColorFormat, colorFormat);
    501         }
    502 
    503         int32_t cropLeft, cropTop, cropRight, cropBottom;
    504         if (msg->findRect("crop",
    505                           &cropLeft,
    506                           &cropTop,
    507                           &cropRight,
    508                           &cropBottom)) {
    509             meta->setRect(kKeyCropRect, cropLeft, cropTop, cropRight, cropBottom);
    510         }
    511 
    512         int32_t rotationDegrees;
    513         if (msg->findInt32("rotation-degrees", &rotationDegrees)) {
    514             meta->setInt32(kKeyRotation, rotationDegrees);
    515         }
    516     } else if (mime.startsWith("audio/")) {
    517         int32_t numChannels;
    518         if (msg->findInt32("channel-count", &numChannels)) {
    519             meta->setInt32(kKeyChannelCount, numChannels);
    520         }
    521         int32_t sampleRate;
    522         if (msg->findInt32("sample-rate", &sampleRate)) {
    523             meta->setInt32(kKeySampleRate, sampleRate);
    524         }
    525         int32_t channelMask;
    526         if (msg->findInt32("channel-mask", &channelMask)) {
    527             meta->setInt32(kKeyChannelMask, channelMask);
    528         }
    529         int32_t delay = 0;
    530         if (msg->findInt32("encoder-delay", &delay)) {
    531             meta->setInt32(kKeyEncoderDelay, delay);
    532         }
    533         int32_t padding = 0;
    534         if (msg->findInt32("encoder-padding", &padding)) {
    535             meta->setInt32(kKeyEncoderPadding, padding);
    536         }
    537 
    538         int32_t isADTS;
    539         if (msg->findInt32("is-adts", &isADTS)) {
    540             meta->setInt32(kKeyIsADTS, isADTS);
    541         }
    542     }
    543 
    544     int32_t maxInputSize;
    545     if (msg->findInt32("max-input-size", &maxInputSize)) {
    546         meta->setInt32(kKeyMaxInputSize, maxInputSize);
    547     }
    548 
    549     // reassemble the csd data into its original form
    550     sp<ABuffer> csd0;
    551     if (msg->findBuffer("csd-0", &csd0)) {
    552         if (mime.startsWith("video/")) { // do we need to be stricter than this?
    553             sp<ABuffer> csd1;
    554             if (msg->findBuffer("csd-1", &csd1)) {
    555                 char avcc[1024]; // that oughta be enough, right?
    556                 size_t outsize = reassembleAVCC(csd0, csd1, avcc);
    557                 meta->setData(kKeyAVCC, kKeyAVCC, avcc, outsize);
    558             }
    559         } else if (mime.startsWith("audio/")) {
    560             int csd0size = csd0->size();
    561             char esds[csd0size + 31];
    562             reassembleESDS(csd0, esds);
    563             meta->setData(kKeyESDS, kKeyESDS, esds, sizeof(esds));
    564         }
    565     }
    566 
    567     int32_t timeScale;
    568     if (msg->findInt32("time-scale", &timeScale)) {
    569         meta->setInt32(kKeyTimeScale, timeScale);
    570     }
    571 
    572     // XXX TODO add whatever other keys there are
    573 
    574 #if 0
    575     ALOGI("converted %s to:", msg->debugString(0).c_str());
    576     meta->dumpToLog();
    577 #endif
    578 }
    579 
    580 AString MakeUserAgent() {
    581     AString ua;
    582     ua.append("stagefright/1.2 (Linux;Android ");
    583 
    584 #if (PROPERTY_VALUE_MAX < 8)
    585 #error "PROPERTY_VALUE_MAX must be at least 8"
    586 #endif
    587 
    588     char value[PROPERTY_VALUE_MAX];
    589     property_get("ro.build.version.release", value, "Unknown");
    590     ua.append(value);
    591     ua.append(")");
    592 
    593     return ua;
    594 }
    595 
    596 status_t sendMetaDataToHal(sp<MediaPlayerBase::AudioSink>& sink,
    597                            const sp<MetaData>& meta)
    598 {
    599     int32_t sampleRate = 0;
    600     int32_t bitRate = 0;
    601     int32_t channelMask = 0;
    602     int32_t delaySamples = 0;
    603     int32_t paddingSamples = 0;
    604 
    605     AudioParameter param = AudioParameter();
    606 
    607     if (meta->findInt32(kKeySampleRate, &sampleRate)) {
    608         param.addInt(String8(AUDIO_OFFLOAD_CODEC_SAMPLE_RATE), sampleRate);
    609     }
    610     if (meta->findInt32(kKeyChannelMask, &channelMask)) {
    611         param.addInt(String8(AUDIO_OFFLOAD_CODEC_NUM_CHANNEL), channelMask);
    612     }
    613     if (meta->findInt32(kKeyBitRate, &bitRate)) {
    614         param.addInt(String8(AUDIO_OFFLOAD_CODEC_AVG_BIT_RATE), bitRate);
    615     }
    616     if (meta->findInt32(kKeyEncoderDelay, &delaySamples)) {
    617         param.addInt(String8(AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES), delaySamples);
    618     }
    619     if (meta->findInt32(kKeyEncoderPadding, &paddingSamples)) {
    620         param.addInt(String8(AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES), paddingSamples);
    621     }
    622 
    623     ALOGV("sendMetaDataToHal: bitRate %d, sampleRate %d, chanMask %d,"
    624           "delaySample %d, paddingSample %d", bitRate, sampleRate,
    625           channelMask, delaySamples, paddingSamples);
    626 
    627     sink->setParameters(param.toString());
    628     return OK;
    629 }
    630 
    631 struct mime_conv_t {
    632     const char* mime;
    633     audio_format_t format;
    634 };
    635 
    636 static const struct mime_conv_t mimeLookup[] = {
    637     { MEDIA_MIMETYPE_AUDIO_MPEG,        AUDIO_FORMAT_MP3 },
    638     { MEDIA_MIMETYPE_AUDIO_RAW,         AUDIO_FORMAT_PCM_16_BIT },
    639     { MEDIA_MIMETYPE_AUDIO_AMR_NB,      AUDIO_FORMAT_AMR_NB },
    640     { MEDIA_MIMETYPE_AUDIO_AMR_WB,      AUDIO_FORMAT_AMR_WB },
    641     { MEDIA_MIMETYPE_AUDIO_AAC,         AUDIO_FORMAT_AAC },
    642     { MEDIA_MIMETYPE_AUDIO_VORBIS,      AUDIO_FORMAT_VORBIS },
    643     { MEDIA_MIMETYPE_AUDIO_OPUS,        AUDIO_FORMAT_OPUS},
    644     { 0, AUDIO_FORMAT_INVALID }
    645 };
    646 
    647 status_t mapMimeToAudioFormat( audio_format_t& format, const char* mime )
    648 {
    649 const struct mime_conv_t* p = &mimeLookup[0];
    650     while (p->mime != NULL) {
    651         if (0 == strcasecmp(mime, p->mime)) {
    652             format = p->format;
    653             return OK;
    654         }
    655         ++p;
    656     }
    657 
    658     return BAD_VALUE;
    659 }
    660 
    661 struct aac_format_conv_t {
    662     OMX_AUDIO_AACPROFILETYPE eAacProfileType;
    663     audio_format_t format;
    664 };
    665 
    666 static const struct aac_format_conv_t profileLookup[] = {
    667     { OMX_AUDIO_AACObjectMain,        AUDIO_FORMAT_AAC_MAIN},
    668     { OMX_AUDIO_AACObjectLC,          AUDIO_FORMAT_AAC_LC},
    669     { OMX_AUDIO_AACObjectSSR,         AUDIO_FORMAT_AAC_SSR},
    670     { OMX_AUDIO_AACObjectLTP,         AUDIO_FORMAT_AAC_LTP},
    671     { OMX_AUDIO_AACObjectHE,          AUDIO_FORMAT_AAC_HE_V1},
    672     { OMX_AUDIO_AACObjectScalable,    AUDIO_FORMAT_AAC_SCALABLE},
    673     { OMX_AUDIO_AACObjectERLC,        AUDIO_FORMAT_AAC_ERLC},
    674     { OMX_AUDIO_AACObjectLD,          AUDIO_FORMAT_AAC_LD},
    675     { OMX_AUDIO_AACObjectHE_PS,       AUDIO_FORMAT_AAC_HE_V2},
    676     { OMX_AUDIO_AACObjectELD,         AUDIO_FORMAT_AAC_ELD},
    677     { OMX_AUDIO_AACObjectNull,        AUDIO_FORMAT_AAC},
    678 };
    679 
    680 void mapAACProfileToAudioFormat( audio_format_t& format, uint64_t eAacProfile)
    681 {
    682 const struct aac_format_conv_t* p = &profileLookup[0];
    683     while (p->eAacProfileType != OMX_AUDIO_AACObjectNull) {
    684         if (eAacProfile == p->eAacProfileType) {
    685             format = p->format;
    686             return;
    687         }
    688         ++p;
    689     }
    690     format = AUDIO_FORMAT_AAC;
    691     return;
    692 }
    693 
    694 bool canOffloadStream(const sp<MetaData>& meta, bool hasVideo,
    695                       bool isStreaming, audio_stream_type_t streamType)
    696 {
    697     const char *mime;
    698     if (meta == NULL) {
    699         return false;
    700     }
    701     CHECK(meta->findCString(kKeyMIMEType, &mime));
    702 
    703     audio_offload_info_t info = AUDIO_INFO_INITIALIZER;
    704 
    705     info.format = AUDIO_FORMAT_INVALID;
    706     if (mapMimeToAudioFormat(info.format, mime) != OK) {
    707         ALOGE(" Couldn't map mime type \"%s\" to a valid AudioSystem::audio_format !", mime);
    708         return false;
    709     } else {
    710         ALOGV("Mime type \"%s\" mapped to audio_format %d", mime, info.format);
    711     }
    712 
    713     if (AUDIO_FORMAT_INVALID == info.format) {
    714         // can't offload if we don't know what the source format is
    715         ALOGE("mime type \"%s\" not a known audio format", mime);
    716         return false;
    717     }
    718 
    719     // Redefine aac format according to its profile
    720     // Offloading depends on audio DSP capabilities.
    721     int32_t aacaot = -1;
    722     if (meta->findInt32(kKeyAACAOT, &aacaot)) {
    723         mapAACProfileToAudioFormat(info.format,(OMX_AUDIO_AACPROFILETYPE) aacaot);
    724     }
    725 
    726     int32_t srate = -1;
    727     if (!meta->findInt32(kKeySampleRate, &srate)) {
    728         ALOGV("track of type '%s' does not publish sample rate", mime);
    729     }
    730     info.sample_rate = srate;
    731 
    732     int32_t cmask = 0;
    733     if (!meta->findInt32(kKeyChannelMask, &cmask)) {
    734         ALOGV("track of type '%s' does not publish channel mask", mime);
    735 
    736         // Try a channel count instead
    737         int32_t channelCount;
    738         if (!meta->findInt32(kKeyChannelCount, &channelCount)) {
    739             ALOGV("track of type '%s' does not publish channel count", mime);
    740         } else {
    741             cmask = audio_channel_out_mask_from_count(channelCount);
    742         }
    743     }
    744     info.channel_mask = cmask;
    745 
    746     int64_t duration = 0;
    747     if (!meta->findInt64(kKeyDuration, &duration)) {
    748         ALOGV("track of type '%s' does not publish duration", mime);
    749     }
    750     info.duration_us = duration;
    751 
    752     int32_t brate = -1;
    753     if (!meta->findInt32(kKeyBitRate, &brate)) {
    754         ALOGV("track of type '%s' does not publish bitrate", mime);
    755      }
    756     info.bit_rate = brate;
    757 
    758 
    759     info.stream_type = streamType;
    760     info.has_video = hasVideo;
    761     info.is_streaming = isStreaming;
    762 
    763     // Check if offload is possible for given format, stream type, sample rate,
    764     // bit rate, duration, video and streaming
    765     return AudioSystem::isOffloadSupported(info);
    766 }
    767 
    768 AString uriDebugString(const AString &uri, bool incognito) {
    769     if (incognito) {
    770         return AString("<URI suppressed>");
    771     }
    772 
    773     char prop[PROPERTY_VALUE_MAX];
    774     if (property_get("media.stagefright.log-uri", prop, "false") &&
    775         (!strcmp(prop, "1") || !strcmp(prop, "true"))) {
    776         return uri;
    777     }
    778 
    779     // find scheme
    780     AString scheme;
    781     const char *chars = uri.c_str();
    782     for (size_t i = 0; i < uri.size(); i++) {
    783         const char c = chars[i];
    784         if (!isascii(c)) {
    785             break;
    786         } else if (isalpha(c)) {
    787             continue;
    788         } else if (i == 0) {
    789             // first character must be a letter
    790             break;
    791         } else if (isdigit(c) || c == '+' || c == '.' || c =='-') {
    792             continue;
    793         } else if (c != ':') {
    794             break;
    795         }
    796         scheme = AString(uri, 0, i);
    797         scheme.append("://<suppressed>");
    798         return scheme;
    799     }
    800     return AString("<no-scheme URI suppressed>");
    801 }
    802 
    803 }  // namespace android
    804 
    805