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