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