Home | History | Annotate | Download | only in tests
      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 "OMXHarness"
     19 #include <inttypes.h>
     20 #include <utils/Log.h>
     21 
     22 #include "OMXHarness.h"
     23 
     24 #include <sys/time.h>
     25 
     26 #include <binder/ProcessState.h>
     27 #include <binder/IServiceManager.h>
     28 #include <binder/MemoryDealer.h>
     29 #include <media/IMediaHTTPService.h>
     30 #include <media/IMediaCodecService.h>
     31 #include <media/stagefright/foundation/ADebug.h>
     32 #include <media/stagefright/foundation/ALooper.h>
     33 #include <media/stagefright/DataSource.h>
     34 #include <media/stagefright/MediaBuffer.h>
     35 #include <media/stagefright/MediaDefs.h>
     36 #include <media/stagefright/MediaErrors.h>
     37 #include <media/stagefright/MediaExtractor.h>
     38 #include <media/stagefright/MediaSource.h>
     39 #include <media/stagefright/MetaData.h>
     40 #include <media/stagefright/SimpleDecodingSource.h>
     41 
     42 #define DEFAULT_TIMEOUT         500000
     43 
     44 namespace android {
     45 
     46 Harness::Harness()
     47     : mInitCheck(NO_INIT) {
     48     mInitCheck = initOMX();
     49 }
     50 
     51 Harness::~Harness() {
     52 }
     53 
     54 status_t Harness::initCheck() const {
     55     return mInitCheck;
     56 }
     57 
     58 status_t Harness::initOMX() {
     59     sp<IServiceManager> sm = defaultServiceManager();
     60     sp<IBinder> binder = sm->getService(String16("media.codec"));
     61     sp<IMediaCodecService> service = interface_cast<IMediaCodecService>(binder);
     62     mOMX = service->getOMX();
     63 
     64     return mOMX != 0 ? OK : NO_INIT;
     65 }
     66 
     67 void Harness::onMessages(const std::list<omx_message> &messages) {
     68     Mutex::Autolock autoLock(mLock);
     69     for (std::list<omx_message>::const_iterator it = messages.cbegin(); it != messages.cend(); ) {
     70         mMessageQueue.push_back(*it++);
     71     }
     72     mMessageAddedCondition.signal();
     73 }
     74 
     75 status_t Harness::dequeueMessageForNode(
     76         IOMX::node_id node, omx_message *msg, int64_t timeoutUs) {
     77     return dequeueMessageForNodeIgnoringBuffers(
     78             node, NULL, NULL, msg, timeoutUs);
     79 }
     80 
     81 // static
     82 bool Harness::handleBufferMessage(
     83         const omx_message &msg,
     84         Vector<Buffer> *inputBuffers,
     85         Vector<Buffer> *outputBuffers) {
     86     switch (msg.type) {
     87         case omx_message::EMPTY_BUFFER_DONE:
     88         {
     89             if (inputBuffers) {
     90                 for (size_t i = 0; i < inputBuffers->size(); ++i) {
     91                     if ((*inputBuffers)[i].mID == msg.u.buffer_data.buffer) {
     92                         inputBuffers->editItemAt(i).mFlags &= ~kBufferBusy;
     93                         return true;
     94                     }
     95                 }
     96                 CHECK(!"should not be here");
     97             }
     98             break;
     99         }
    100 
    101         case omx_message::FILL_BUFFER_DONE:
    102         {
    103             if (outputBuffers) {
    104                 for (size_t i = 0; i < outputBuffers->size(); ++i) {
    105                     if ((*outputBuffers)[i].mID == msg.u.buffer_data.buffer) {
    106                         outputBuffers->editItemAt(i).mFlags &= ~kBufferBusy;
    107                         return true;
    108                     }
    109                 }
    110                 CHECK(!"should not be here");
    111             }
    112             break;
    113         }
    114 
    115         default:
    116             break;
    117     }
    118 
    119     return false;
    120 }
    121 
    122 status_t Harness::dequeueMessageForNodeIgnoringBuffers(
    123         IOMX::node_id node,
    124         Vector<Buffer> *inputBuffers,
    125         Vector<Buffer> *outputBuffers,
    126         omx_message *msg, int64_t timeoutUs) {
    127     int64_t finishBy = ALooper::GetNowUs() + timeoutUs;
    128 
    129     for (;;) {
    130         Mutex::Autolock autoLock(mLock);
    131         List<omx_message>::iterator it = mMessageQueue.begin();
    132         while (it != mMessageQueue.end()) {
    133             if ((*it).node == node) {
    134                 if (handleBufferMessage(*it, inputBuffers, outputBuffers)) {
    135                     it = mMessageQueue.erase(it);
    136                     continue;
    137                 }
    138 
    139                 *msg = *it;
    140                 mMessageQueue.erase(it);
    141 
    142                 return OK;
    143             }
    144 
    145             ++it;
    146         }
    147 
    148         status_t err = (timeoutUs < 0)
    149             ? mMessageAddedCondition.wait(mLock)
    150             : mMessageAddedCondition.waitRelative(
    151                     mLock, (finishBy - ALooper::GetNowUs()) * 1000);
    152 
    153         if (err == TIMED_OUT) {
    154             return err;
    155         }
    156         CHECK_EQ(err, (status_t)OK);
    157     }
    158 }
    159 
    160 status_t Harness::getPortDefinition(
    161         IOMX::node_id node, OMX_U32 portIndex,
    162         OMX_PARAM_PORTDEFINITIONTYPE *def) {
    163     def->nSize = sizeof(*def);
    164     def->nVersion.s.nVersionMajor = 1;
    165     def->nVersion.s.nVersionMinor = 0;
    166     def->nVersion.s.nRevision = 0;
    167     def->nVersion.s.nStep = 0;
    168     def->nPortIndex = portIndex;
    169     return mOMX->getParameter(
    170             node, OMX_IndexParamPortDefinition, def, sizeof(*def));
    171 }
    172 
    173 #define EXPECT(condition, info) \
    174     if (!(condition)) {         \
    175         ALOGE(info); printf("\n  * " info "\n"); return UNKNOWN_ERROR; \
    176     }
    177 
    178 #define EXPECT_SUCCESS(err, info) \
    179     EXPECT((err) == OK, info " failed")
    180 
    181 status_t Harness::allocatePortBuffers(
    182         const sp<MemoryDealer> &dealer,
    183         IOMX::node_id node, OMX_U32 portIndex,
    184         Vector<Buffer> *buffers) {
    185     buffers->clear();
    186 
    187     OMX_PARAM_PORTDEFINITIONTYPE def;
    188     status_t err = getPortDefinition(node, portIndex, &def);
    189     EXPECT_SUCCESS(err, "getPortDefinition");
    190 
    191     for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
    192         Buffer buffer;
    193         buffer.mMemory = dealer->allocate(def.nBufferSize);
    194         buffer.mFlags = 0;
    195         CHECK(buffer.mMemory != NULL);
    196 
    197         err = mOMX->allocateBufferWithBackup(
    198                 node, portIndex, buffer.mMemory, &buffer.mID, buffer.mMemory->size());
    199         EXPECT_SUCCESS(err, "allocateBuffer");
    200 
    201         buffers->push(buffer);
    202     }
    203 
    204     return OK;
    205 }
    206 
    207 status_t Harness::setRole(IOMX::node_id node, const char *role) {
    208     OMX_PARAM_COMPONENTROLETYPE params;
    209     params.nSize = sizeof(params);
    210     params.nVersion.s.nVersionMajor = 1;
    211     params.nVersion.s.nVersionMinor = 0;
    212     params.nVersion.s.nRevision = 0;
    213     params.nVersion.s.nStep = 0;
    214     strncpy((char *)params.cRole, role, OMX_MAX_STRINGNAME_SIZE - 1);
    215     params.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
    216 
    217     return mOMX->setParameter(
    218             node, OMX_IndexParamStandardComponentRole,
    219             &params, sizeof(params));
    220 }
    221 
    222 struct NodeReaper {
    223     NodeReaper(const sp<Harness> &harness, IOMX::node_id node)
    224         : mHarness(harness),
    225           mNode(node) {
    226     }
    227 
    228     ~NodeReaper() {
    229         if (mNode != 0) {
    230             mHarness->mOMX->freeNode(mNode);
    231             mNode = 0;
    232         }
    233     }
    234 
    235     void disarm() {
    236         mNode = 0;
    237     }
    238 
    239 private:
    240     sp<Harness> mHarness;
    241     IOMX::node_id mNode;
    242 
    243     NodeReaper(const NodeReaper &);
    244     NodeReaper &operator=(const NodeReaper &);
    245 };
    246 
    247 static sp<IMediaExtractor> CreateExtractorFromURI(const char *uri) {
    248     sp<DataSource> source =
    249         DataSource::CreateFromURI(NULL /* httpService */, uri);
    250 
    251     if (source == NULL) {
    252         return NULL;
    253     }
    254 
    255     return MediaExtractor::Create(source);
    256 }
    257 
    258 status_t Harness::testStateTransitions(
    259         const char *componentName, const char *componentRole) {
    260     if (strncmp(componentName, "OMX.", 4)) {
    261         // Non-OMX components, i.e. software decoders won't execute this
    262         // test.
    263         return OK;
    264     }
    265 
    266     sp<MemoryDealer> dealer = new MemoryDealer(16 * 1024 * 1024, "OMXHarness");
    267     IOMX::node_id node;
    268 
    269     status_t err =
    270         mOMX->allocateNode(componentName, this, NULL, &node);
    271     EXPECT_SUCCESS(err, "allocateNode");
    272 
    273     NodeReaper reaper(this, node);
    274 
    275     err = setRole(node, componentRole);
    276     EXPECT_SUCCESS(err, "setRole");
    277 
    278     // Initiate transition Loaded->Idle
    279     err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateIdle);
    280     EXPECT_SUCCESS(err, "sendCommand(go-to-Idle)");
    281 
    282     omx_message msg;
    283     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    284     // Make sure node doesn't just transition to idle before we are done
    285     // allocating all input and output buffers.
    286     EXPECT(err == TIMED_OUT,
    287             "Component must not transition from loaded to idle before "
    288             "all input and output buffers are allocated.");
    289 
    290     // Now allocate buffers.
    291     Vector<Buffer> inputBuffers;
    292     err = allocatePortBuffers(dealer, node, 0, &inputBuffers);
    293     EXPECT_SUCCESS(err, "allocatePortBuffers(input)");
    294 
    295     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    296     CHECK_EQ(err, (status_t)TIMED_OUT);
    297 
    298     Vector<Buffer> outputBuffers;
    299     err = allocatePortBuffers(dealer, node, 1, &outputBuffers);
    300     EXPECT_SUCCESS(err, "allocatePortBuffers(output)");
    301 
    302     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    303     EXPECT(err == OK
    304             && msg.type == omx_message::EVENT
    305             && msg.u.event_data.event == OMX_EventCmdComplete
    306             && msg.u.event_data.data1 == OMX_CommandStateSet
    307             && msg.u.event_data.data2 == OMX_StateIdle,
    308            "Component did not properly transition to idle state "
    309            "after all input and output buffers were allocated.");
    310 
    311     // Initiate transition Idle->Executing
    312     err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateExecuting);
    313     EXPECT_SUCCESS(err, "sendCommand(go-to-Executing)");
    314 
    315     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    316     EXPECT(err == OK
    317             && msg.type == omx_message::EVENT
    318             && msg.u.event_data.event == OMX_EventCmdComplete
    319             && msg.u.event_data.data1 == OMX_CommandStateSet
    320             && msg.u.event_data.data2 == OMX_StateExecuting,
    321            "Component did not properly transition from idle to "
    322            "executing state.");
    323 
    324     for (size_t i = 0; i < outputBuffers.size(); ++i) {
    325         err = mOMX->fillBuffer(node, outputBuffers[i].mID);
    326         EXPECT_SUCCESS(err, "fillBuffer");
    327 
    328         outputBuffers.editItemAt(i).mFlags |= kBufferBusy;
    329     }
    330 
    331     err = mOMX->sendCommand(node, OMX_CommandFlush, 1);
    332     EXPECT_SUCCESS(err, "sendCommand(flush-output-port)");
    333 
    334     err = dequeueMessageForNodeIgnoringBuffers(
    335             node, &inputBuffers, &outputBuffers, &msg, DEFAULT_TIMEOUT);
    336     EXPECT(err == OK
    337             && msg.type == omx_message::EVENT
    338             && msg.u.event_data.event == OMX_EventCmdComplete
    339             && msg.u.event_data.data1 == OMX_CommandFlush
    340             && msg.u.event_data.data2 == 1,
    341            "Component did not properly acknowledge flushing the output port.");
    342 
    343     for (size_t i = 0; i < outputBuffers.size(); ++i) {
    344         EXPECT((outputBuffers[i].mFlags & kBufferBusy) == 0,
    345                "Not all output buffers have been returned to us by the time "
    346                "we received the flush-complete notification.");
    347     }
    348 
    349     for (size_t i = 0; i < outputBuffers.size(); ++i) {
    350         err = mOMX->fillBuffer(node, outputBuffers[i].mID);
    351         EXPECT_SUCCESS(err, "fillBuffer");
    352 
    353         outputBuffers.editItemAt(i).mFlags |= kBufferBusy;
    354     }
    355 
    356     // Initiate transition Executing->Idle
    357     err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateIdle);
    358     EXPECT_SUCCESS(err, "sendCommand(go-to-Idle)");
    359 
    360     err = dequeueMessageForNodeIgnoringBuffers(
    361             node, &inputBuffers, &outputBuffers, &msg, DEFAULT_TIMEOUT);
    362     EXPECT(err == OK
    363             && msg.type == omx_message::EVENT
    364             && msg.u.event_data.event == OMX_EventCmdComplete
    365             && msg.u.event_data.data1 == OMX_CommandStateSet
    366             && msg.u.event_data.data2 == OMX_StateIdle,
    367            "Component did not properly transition to from executing to "
    368            "idle state.");
    369 
    370     for (size_t i = 0; i < inputBuffers.size(); ++i) {
    371         EXPECT((inputBuffers[i].mFlags & kBufferBusy) == 0,
    372                 "Not all input buffers have been returned to us by the "
    373                 "time we received the transition-to-idle complete "
    374                 "notification.");
    375     }
    376 
    377     for (size_t i = 0; i < outputBuffers.size(); ++i) {
    378         EXPECT((outputBuffers[i].mFlags & kBufferBusy) == 0,
    379                 "Not all output buffers have been returned to us by the "
    380                 "time we received the transition-to-idle complete "
    381                 "notification.");
    382     }
    383 
    384     // Initiate transition Idle->Loaded
    385     err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateLoaded);
    386     EXPECT_SUCCESS(err, "sendCommand(go-to-Loaded)");
    387 
    388     // Make sure node doesn't just transition to loaded before we are done
    389     // freeing all input and output buffers.
    390     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    391     CHECK_EQ(err, (status_t)TIMED_OUT);
    392 
    393     for (size_t i = 0; i < inputBuffers.size(); ++i) {
    394         err = mOMX->freeBuffer(node, 0, inputBuffers[i].mID);
    395         EXPECT_SUCCESS(err, "freeBuffer");
    396     }
    397 
    398     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    399     CHECK_EQ(err, (status_t)TIMED_OUT);
    400 
    401     for (size_t i = 0; i < outputBuffers.size(); ++i) {
    402         err = mOMX->freeBuffer(node, 1, outputBuffers[i].mID);
    403         EXPECT_SUCCESS(err, "freeBuffer");
    404     }
    405 
    406     err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
    407     EXPECT(err == OK
    408             && msg.type == omx_message::EVENT
    409             && msg.u.event_data.event == OMX_EventCmdComplete
    410             && msg.u.event_data.data1 == OMX_CommandStateSet
    411             && msg.u.event_data.data2 == OMX_StateLoaded,
    412            "Component did not properly transition to from idle to "
    413            "loaded state after freeing all input and output buffers.");
    414 
    415     err = mOMX->freeNode(node);
    416     EXPECT_SUCCESS(err, "freeNode");
    417 
    418     reaper.disarm();
    419 
    420     node = 0;
    421 
    422     return OK;
    423 }
    424 
    425 static const char *GetMimeFromComponentRole(const char *componentRole) {
    426     struct RoleToMime {
    427         const char *mRole;
    428         const char *mMime;
    429     };
    430     const RoleToMime kRoleToMime[] = {
    431         { "video_decoder.avc", "video/avc" },
    432         { "video_decoder.mpeg4", "video/mp4v-es" },
    433         { "video_decoder.h263", "video/3gpp" },
    434         { "video_decoder.vp8", "video/x-vnd.on2.vp8" },
    435         { "video_decoder.vp9", "video/x-vnd.on2.vp9" },
    436 
    437         // we appear to use this as a synonym to amrnb.
    438         { "audio_decoder.amr", "audio/3gpp" },
    439 
    440         { "audio_decoder.amrnb", "audio/3gpp" },
    441         { "audio_decoder.amrwb", "audio/amr-wb" },
    442         { "audio_decoder.aac", "audio/mp4a-latm" },
    443         { "audio_decoder.mp3", "audio/mpeg" },
    444         { "audio_decoder.vorbis", "audio/vorbis" },
    445         { "audio_decoder.opus", "audio/opus" },
    446         { "audio_decoder.g711alaw", MEDIA_MIMETYPE_AUDIO_G711_ALAW },
    447         { "audio_decoder.g711mlaw", MEDIA_MIMETYPE_AUDIO_G711_MLAW },
    448     };
    449 
    450     for (size_t i = 0; i < sizeof(kRoleToMime) / sizeof(kRoleToMime[0]); ++i) {
    451         if (!strcmp(componentRole, kRoleToMime[i].mRole)) {
    452             return kRoleToMime[i].mMime;
    453         }
    454     }
    455 
    456     return NULL;
    457 }
    458 
    459 static const char *GetURLForMime(const char *mime) {
    460     struct MimeToURL {
    461         const char *mMime;
    462         const char *mURL;
    463     };
    464     static const MimeToURL kMimeToURL[] = {
    465         { "video/avc",
    466           "file:///sdcard/media_api/video/H264_500_AAC_128.3gp" },
    467         { "video/mp4v-es", "file:///sdcard/media_api/video/MPEG4_320_AAC_64.mp4" },
    468         { "video/3gpp",
    469           "file:///sdcard/media_api/video/H263_500_AMRNB_12.3gp" },
    470         { "audio/3gpp",
    471           "file:///sdcard/media_api/video/H263_500_AMRNB_12.3gp" },
    472         { "audio/amr-wb", NULL },
    473         { "audio/mp4a-latm",
    474           "file:///sdcard/media_api/video/H263_56_AAC_24.3gp" },
    475         { "audio/mpeg",
    476           "file:///sdcard/media_api/music/MP3_48KHz_128kbps_s_1_17_CBR.mp3" },
    477         { "audio/vorbis", NULL },
    478         { "audio/opus", NULL },
    479         { "video/x-vnd.on2.vp8",
    480           "file:///sdcard/media_api/video/big-buck-bunny_trailer.webm" },
    481         { MEDIA_MIMETYPE_AUDIO_G711_ALAW, "file:///sdcard/M1F1-Alaw-AFsp.wav" },
    482         { MEDIA_MIMETYPE_AUDIO_G711_MLAW,
    483           "file:///sdcard/M1F1-mulaw-AFsp.wav" },
    484     };
    485 
    486     for (size_t i = 0; i < sizeof(kMimeToURL) / sizeof(kMimeToURL[0]); ++i) {
    487         if (!strcasecmp(kMimeToURL[i].mMime, mime)) {
    488             return kMimeToURL[i].mURL;
    489         }
    490     }
    491 
    492     return NULL;
    493 }
    494 
    495 static sp<IMediaSource> CreateSourceForMime(const char *mime) {
    496     const char *url = GetURLForMime(mime);
    497 
    498     if (url == NULL) {
    499         return NULL;
    500     }
    501 
    502     sp<IMediaExtractor> extractor = CreateExtractorFromURI(url);
    503 
    504     if (extractor == NULL) {
    505         return NULL;
    506     }
    507 
    508     for (size_t i = 0; i < extractor->countTracks(); ++i) {
    509         sp<MetaData> meta = extractor->getTrackMetaData(i);
    510         CHECK(meta != NULL);
    511 
    512         const char *trackMime;
    513         CHECK(meta->findCString(kKeyMIMEType, &trackMime));
    514 
    515         if (!strcasecmp(mime, trackMime)) {
    516             return extractor->getTrack(i);
    517         }
    518     }
    519 
    520     return NULL;
    521 }
    522 
    523 static double uniform_rand() {
    524     return (double)rand() / RAND_MAX;
    525 }
    526 
    527 static bool CloseEnough(int64_t time1Us, int64_t time2Us) {
    528 #if 0
    529     int64_t diff = time1Us - time2Us;
    530     if (diff < 0) {
    531         diff = -diff;
    532     }
    533 
    534     return diff <= 50000;
    535 #else
    536     return time1Us == time2Us;
    537 #endif
    538 }
    539 
    540 status_t Harness::testSeek(
    541         const char *componentName, const char *componentRole) {
    542     bool isEncoder =
    543         !strncmp(componentRole, "audio_encoder.", 14)
    544         || !strncmp(componentRole, "video_encoder.", 14);
    545 
    546     if (isEncoder) {
    547         // Not testing seek behaviour for encoders.
    548 
    549         printf("  * Not testing seek functionality for encoders.\n");
    550         return OK;
    551     }
    552 
    553     const char *mime = GetMimeFromComponentRole(componentRole);
    554 
    555     if (!mime) {
    556         printf("  * Cannot perform seek test with this componentRole (%s)\n",
    557                componentRole);
    558 
    559         return OK;
    560     }
    561 
    562     sp<IMediaSource> source = CreateSourceForMime(mime);
    563 
    564     if (source == NULL) {
    565         printf("  * Unable to open test content for type '%s', "
    566                "skipping test of componentRole %s\n",
    567                mime, componentRole);
    568 
    569         return OK;
    570     }
    571 
    572     sp<IMediaSource> seekSource = CreateSourceForMime(mime);
    573     if (source == NULL || seekSource == NULL) {
    574         return UNKNOWN_ERROR;
    575     }
    576 
    577     CHECK_EQ(seekSource->start(), (status_t)OK);
    578 
    579     sp<IMediaSource> codec = SimpleDecodingSource::Create(
    580             source, 0 /* flags */, NULL /* nativeWindow */, componentName);
    581 
    582     CHECK(codec != NULL);
    583 
    584     CHECK_EQ(codec->start(), (status_t)OK);
    585 
    586     int64_t durationUs;
    587     CHECK(source->getFormat()->findInt64(kKeyDuration, &durationUs));
    588 
    589     ALOGI("stream duration is %lld us (%.2f secs)",
    590          durationUs, durationUs / 1E6);
    591 
    592     static const int32_t kNumIterations = 5000;
    593 
    594     // We are always going to seek beyond EOS in the first iteration (i == 0)
    595     // followed by a linear read for the second iteration (i == 1).
    596     // After that it's all random.
    597     for (int32_t i = 0; i < kNumIterations; ++i) {
    598         int64_t requestedSeekTimeUs;
    599         int64_t actualSeekTimeUs;
    600         MediaSource::ReadOptions options;
    601 
    602         double r = uniform_rand();
    603 
    604         if ((i == 1) || (i > 0 && r < 0.5)) {
    605             // 50% chance of just continuing to decode from last position.
    606 
    607             requestedSeekTimeUs = -1;
    608 
    609             ALOGI("requesting linear read");
    610         } else {
    611             if (i == 0 || r < 0.55) {
    612                 // 5% chance of seeking beyond end of stream.
    613 
    614                 requestedSeekTimeUs = durationUs;
    615 
    616                 ALOGI("requesting seek beyond EOF");
    617             } else {
    618                 requestedSeekTimeUs =
    619                     (int64_t)(uniform_rand() * durationUs);
    620 
    621                 ALOGI("requesting seek to %lld us (%.2f secs)",
    622                      requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
    623             }
    624 
    625             MediaBuffer *buffer = NULL;
    626             options.setSeekTo(
    627                     requestedSeekTimeUs, MediaSource::ReadOptions::SEEK_NEXT_SYNC);
    628 
    629             if (seekSource->read(&buffer, &options) != OK) {
    630                 CHECK(buffer == NULL);
    631                 actualSeekTimeUs = -1;
    632             } else {
    633                 CHECK(buffer != NULL);
    634                 CHECK(buffer->meta_data()->findInt64(kKeyTime, &actualSeekTimeUs));
    635                 CHECK(actualSeekTimeUs >= 0);
    636 
    637                 buffer->release();
    638                 buffer = NULL;
    639             }
    640 
    641             ALOGI("nearest keyframe is at %lld us (%.2f secs)",
    642                  actualSeekTimeUs, actualSeekTimeUs / 1E6);
    643         }
    644 
    645         status_t err;
    646         MediaBuffer *buffer;
    647         for (;;) {
    648             err = codec->read(&buffer, &options);
    649             options.clearSeekTo();
    650             if (err == INFO_FORMAT_CHANGED) {
    651                 CHECK(buffer == NULL);
    652                 continue;
    653             }
    654             if (err == OK) {
    655                 CHECK(buffer != NULL);
    656                 if (buffer->range_length() == 0) {
    657                     buffer->release();
    658                     buffer = NULL;
    659                     continue;
    660                 }
    661             } else {
    662                 CHECK(buffer == NULL);
    663             }
    664 
    665             break;
    666         }
    667 
    668         if (requestedSeekTimeUs < 0) {
    669             // Linear read.
    670             if (err != OK) {
    671                 CHECK(buffer == NULL);
    672             } else {
    673                 CHECK(buffer != NULL);
    674                 buffer->release();
    675                 buffer = NULL;
    676             }
    677         } else if (actualSeekTimeUs < 0) {
    678             EXPECT(err != OK,
    679                    "We attempted to seek beyond EOS and expected "
    680                    "ERROR_END_OF_STREAM to be returned, but instead "
    681                    "we got a valid buffer.");
    682             EXPECT(err == ERROR_END_OF_STREAM,
    683                    "We attempted to seek beyond EOS and expected "
    684                    "ERROR_END_OF_STREAM to be returned, but instead "
    685                    "we found some other error.");
    686             CHECK_EQ(err, (status_t)ERROR_END_OF_STREAM);
    687             CHECK(buffer == NULL);
    688         } else {
    689             EXPECT(err == OK,
    690                    "Expected a valid buffer to be returned from "
    691                    "OMXCodec::read.");
    692             CHECK(buffer != NULL);
    693 
    694             int64_t bufferTimeUs;
    695             CHECK(buffer->meta_data()->findInt64(kKeyTime, &bufferTimeUs));
    696             if (!CloseEnough(bufferTimeUs, actualSeekTimeUs)) {
    697                 printf("\n  * Attempted seeking to %" PRId64 " us (%.2f secs)",
    698                        requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
    699                 printf("\n  * Nearest keyframe is at %" PRId64 " us (%.2f secs)",
    700                        actualSeekTimeUs, actualSeekTimeUs / 1E6);
    701                 printf("\n  * Returned buffer was at %" PRId64 " us (%.2f secs)\n\n",
    702                        bufferTimeUs, bufferTimeUs / 1E6);
    703 
    704                 buffer->release();
    705                 buffer = NULL;
    706 
    707                 CHECK_EQ(codec->stop(), (status_t)OK);
    708 
    709                 return UNKNOWN_ERROR;
    710             }
    711 
    712             buffer->release();
    713             buffer = NULL;
    714         }
    715     }
    716 
    717     CHECK_EQ(codec->stop(), (status_t)OK);
    718 
    719     return OK;
    720 }
    721 
    722 status_t Harness::test(
    723         const char *componentName, const char *componentRole) {
    724     printf("testing %s [%s] ... ", componentName, componentRole);
    725     ALOGI("testing %s [%s].", componentName, componentRole);
    726 
    727     status_t err1 = testStateTransitions(componentName, componentRole);
    728     status_t err2 = testSeek(componentName, componentRole);
    729 
    730     if (err1 != OK) {
    731         return err1;
    732     }
    733 
    734     return err2;
    735 }
    736 
    737 status_t Harness::testAll() {
    738     List<IOMX::ComponentInfo> componentInfos;
    739     status_t err = mOMX->listNodes(&componentInfos);
    740     EXPECT_SUCCESS(err, "listNodes");
    741 
    742     for (List<IOMX::ComponentInfo>::iterator it = componentInfos.begin();
    743          it != componentInfos.end(); ++it) {
    744         const IOMX::ComponentInfo &info = *it;
    745         const char *componentName = info.mName.string();
    746 
    747         if (strncmp(componentName, "OMX.google.", 11)) {
    748             continue;
    749         }
    750 
    751         for (List<String8>::const_iterator role_it = info.mRoles.begin();
    752              role_it != info.mRoles.end(); ++role_it) {
    753             const char *componentRole = (*role_it).string();
    754 
    755             err = test(componentName, componentRole);
    756 
    757             if (err == OK) {
    758                 printf("OK\n");
    759             }
    760         }
    761     }
    762 
    763     return OK;
    764 }
    765 
    766 }  // namespace android
    767 
    768 static void usage(const char *me) {
    769     fprintf(stderr, "usage: %s\n"
    770                     "  -h(elp)  Show this information\n"
    771                     "  -s(eed)  Set the random seed\n"
    772                     "    [ component role ]\n\n"
    773                     "When launched without specifying a specific component "
    774                     "and role, tool will test all available OMX components "
    775                     "in all their supported roles. To determine available "
    776                     "component names, use \"stagefright -l\"\n"
    777                     "It's also a good idea to run a separate \"adb logcat\""
    778                     " for additional debug and progress information.", me);
    779 
    780     exit(0);
    781 }
    782 
    783 int main(int argc, char **argv) {
    784     using namespace android;
    785 
    786     android::ProcessState::self()->startThreadPool();
    787     DataSource::RegisterDefaultSniffers();
    788 
    789     const char *me = argv[0];
    790 
    791     unsigned long seed = 0xdeadbeef;
    792 
    793     int res;
    794     while ((res = getopt(argc, argv, "hs:")) >= 0) {
    795         switch (res) {
    796             case 's':
    797             {
    798                 char *end;
    799                 unsigned long x = strtoul(optarg, &end, 10);
    800 
    801                 if (*end != '\0' || end == optarg) {
    802                     fprintf(stderr, "Malformed seed.\n");
    803                     return 1;
    804                 }
    805 
    806                 seed = x;
    807                 break;
    808             }
    809 
    810             case '?':
    811                 fprintf(stderr, "\n");
    812                 // fall through
    813 
    814             case 'h':
    815             default:
    816             {
    817                 usage(me);
    818                 exit(1);
    819                 break;
    820             }
    821         }
    822     }
    823 
    824     argc -= optind;
    825     argv += optind;
    826 
    827     printf("To reproduce the conditions for this test, launch "
    828            "with \"%s -s %lu\"\n", me, seed);
    829 
    830     srand(seed);
    831 
    832     sp<Harness> h = new Harness;
    833     CHECK_EQ(h->initCheck(), (status_t)OK);
    834 
    835     if (argc == 0) {
    836         h->testAll();
    837     } else if (argc == 2) {
    838         if (h->test(argv[0], argv[1]) == OK) {
    839             printf("OK\n");
    840         }
    841     }
    842 
    843     return 0;
    844 }
    845