stagefright.cpp revision 36e3ee0094e845ed9d2a1c755addecfde9db3a68
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#include <sys/time.h>
18
19#include <stdlib.h>
20#include <string.h>
21#include <unistd.h>
22
23#include <binder/IServiceManager.h>
24#include <binder/ProcessState.h>
25#include <media/IMediaPlayerService.h>
26#include <media/stagefright/CachingDataSource.h>
27#include <media/stagefright/FileSource.h>
28#include <media/stagefright/HTTPDataSource.h>
29#include <media/stagefright/JPEGSource.h>
30#include <media/stagefright/MediaDebug.h>
31#include <media/stagefright/MediaDefs.h>
32#include <media/stagefright/MediaExtractor.h>
33#include <media/stagefright/MediaSource.h>
34#include <media/stagefright/MetaData.h>
35#include <media/stagefright/OMXClient.h>
36#include <media/stagefright/OMXCodec.h>
37#include <media/mediametadataretriever.h>
38
39using namespace android;
40
41static long gNumRepetitions;
42static long gMaxNumFrames;  // 0 means decode all available.
43static long gReproduceBug;  // if not -1.
44static bool gPreferSoftwareCodec;
45
46static int64_t getNowUs() {
47    struct timeval tv;
48    gettimeofday(&tv, NULL);
49
50    return (int64_t)tv.tv_usec + tv.tv_sec * 1000000;
51}
52
53static void playSource(OMXClient *client, const sp<MediaSource> &source) {
54    sp<MetaData> meta = source->getFormat();
55
56    const char *mime;
57    CHECK(meta->findCString(kKeyMIMEType, &mime));
58
59    sp<MediaSource> rawSource;
60    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) {
61        rawSource = source;
62    } else {
63        rawSource = OMXCodec::Create(
64            client->interface(), meta, false /* createEncoder */, source,
65            NULL /* matchComponentName */,
66            gPreferSoftwareCodec ? OMXCodec::kPreferSoftwareCodecs : 0);
67
68        if (rawSource == NULL) {
69            fprintf(stderr, "Failed to instantiate decoder for '%s'.\n", mime);
70            return;
71        }
72    }
73
74    rawSource->start();
75
76    if (gReproduceBug >= 3 && gReproduceBug <= 5) {
77        int64_t durationUs;
78        CHECK(meta->findInt64(kKeyDuration, &durationUs));
79
80        status_t err;
81        MediaBuffer *buffer;
82        MediaSource::ReadOptions options;
83        int64_t seekTimeUs = -1;
84        for (;;) {
85            err = rawSource->read(&buffer, &options);
86            options.clearSeekTo();
87
88            bool shouldSeek = false;
89            if (err == INFO_FORMAT_CHANGED) {
90                CHECK_EQ(buffer, NULL);
91
92                printf("format changed.\n");
93                continue;
94            } else if (err != OK) {
95                printf("reached EOF.\n");
96
97                shouldSeek = true;
98            } else {
99                int64_t timestampUs;
100                CHECK(buffer->meta_data()->findInt64(kKeyTime, &timestampUs));
101
102                bool failed = false;
103
104                if (seekTimeUs >= 0) {
105                    int64_t diff = timestampUs - seekTimeUs;
106
107                    if (diff < 0) {
108                        diff = -diff;
109                    }
110
111                    if ((gReproduceBug == 4 && diff > 500000)
112                        || (gReproduceBug == 5 && timestampUs < 0)) {
113                        printf("wanted: %.2f secs, got: %.2f secs\n",
114                               seekTimeUs / 1E6, timestampUs / 1E6);
115
116                        printf("ERROR: ");
117                        failed = true;
118                    }
119                }
120
121                printf("buffer has timestamp %lld us (%.2f secs)\n",
122                       timestampUs, timestampUs / 1E6);
123
124                buffer->release();
125                buffer = NULL;
126
127                if (failed) {
128                    break;
129                }
130
131                shouldSeek = ((double)rand() / RAND_MAX) < 0.1;
132
133                if (gReproduceBug == 3) {
134                    shouldSeek = false;
135                }
136            }
137
138            seekTimeUs = -1;
139
140            if (shouldSeek) {
141                seekTimeUs = (rand() * (float)durationUs) / RAND_MAX;
142                options.setSeekTo(seekTimeUs);
143
144                printf("seeking to %lld us (%.2f secs)\n",
145                       seekTimeUs, seekTimeUs / 1E6);
146            }
147        }
148
149        rawSource->stop();
150
151        return;
152    }
153
154    int n = 0;
155    int64_t startTime = getNowUs();
156
157    long numIterationsLeft = gNumRepetitions;
158    MediaSource::ReadOptions options;
159
160    int64_t sumDecodeUs = 0;
161
162    while (numIterationsLeft-- > 0) {
163        long numFrames = 0;
164
165        MediaBuffer *buffer;
166
167        for (;;) {
168            int64_t startDecodeUs = getNowUs();
169            status_t err = rawSource->read(&buffer, &options);
170            int64_t delayDecodeUs = getNowUs() - startDecodeUs;
171
172            options.clearSeekTo();
173
174            if (err != OK) {
175                CHECK_EQ(buffer, NULL);
176
177                if (err == INFO_FORMAT_CHANGED) {
178                    printf("format changed.\n");
179                    continue;
180                }
181
182                break;
183            }
184
185            if (buffer->range_length() > 0 && (n++ % 16) == 0) {
186                printf(".");
187                fflush(stdout);
188            }
189
190            sumDecodeUs += delayDecodeUs;
191
192            buffer->release();
193            buffer = NULL;
194
195            ++numFrames;
196            if (gMaxNumFrames > 0 && numFrames == gMaxNumFrames) {
197                break;
198            }
199
200            if (gReproduceBug == 1 && numFrames == 40) {
201                printf("seeking past the end now.");
202                options.setSeekTo(0x7fffffffL);
203            } else if (gReproduceBug == 2 && numFrames == 40) {
204                printf("seeking to 5 secs.");
205                options.setSeekTo(5000000);
206            }
207        }
208
209        printf("$");
210        fflush(stdout);
211
212        options.setSeekTo(0);
213    }
214
215    rawSource->stop();
216    printf("\n");
217
218    int64_t delay = getNowUs() - startTime;
219    printf("avg. %.2f fps\n", n * 1E6 / delay);
220    printf("avg. time to decode one buffer %.2f usecs\n",
221           (double)sumDecodeUs / n);
222
223    printf("decoded a total of %d frame(s).\n", n);
224}
225
226static void usage(const char *me) {
227    fprintf(stderr, "usage: %s\n", me);
228    fprintf(stderr, "       -h(elp)\n");
229    fprintf(stderr, "       -a(udio)\n");
230    fprintf(stderr, "       -n repetitions\n");
231    fprintf(stderr, "       -l(ist) components\n");
232    fprintf(stderr, "       -m max-number-of-frames-to-decode in each pass\n");
233    fprintf(stderr, "       -b bug to reproduce\n");
234    fprintf(stderr, "       -p(rofiles) dump decoder profiles supported\n");
235    fprintf(stderr, "       -t(humbnail) extract video thumbnail\n");
236    fprintf(stderr, "       -s(oftware) prefer software codec\n");
237}
238
239int main(int argc, char **argv) {
240    android::ProcessState::self()->startThreadPool();
241
242    bool audioOnly = false;
243    bool listComponents = false;
244    bool dumpProfiles = false;
245    bool extractThumbnail = false;
246    gNumRepetitions = 1;
247    gMaxNumFrames = 0;
248    gReproduceBug = -1;
249    gPreferSoftwareCodec = false;
250
251    int res;
252    while ((res = getopt(argc, argv, "han:lm:b:pts")) >= 0) {
253        switch (res) {
254            case 'a':
255            {
256                audioOnly = true;
257                break;
258            }
259
260            case 'l':
261            {
262                listComponents = true;
263                break;
264            }
265
266            case 'm':
267            case 'n':
268            case 'b':
269            {
270                char *end;
271                long x = strtol(optarg, &end, 10);
272
273                if (*end != '\0' || end == optarg || x <= 0) {
274                    x = 1;
275                }
276
277                if (res == 'n') {
278                    gNumRepetitions = x;
279                } else if (res == 'm') {
280                    gMaxNumFrames = x;
281                } else {
282                    CHECK_EQ(res, 'b');
283                    gReproduceBug = x;
284                }
285                break;
286            }
287
288            case 'p':
289            {
290                dumpProfiles = true;
291                break;
292            }
293
294            case 't':
295            {
296                extractThumbnail = true;
297                break;
298            }
299
300            case 's':
301            {
302                gPreferSoftwareCodec = true;
303                break;
304            }
305
306            case '?':
307            case 'h':
308            default:
309            {
310                usage(argv[0]);
311                exit(1);
312                break;
313            }
314        }
315    }
316
317    argc -= optind;
318    argv += optind;
319
320    if (extractThumbnail) {
321        sp<IServiceManager> sm = defaultServiceManager();
322        sp<IBinder> binder = sm->getService(String16("media.player"));
323        sp<IMediaPlayerService> service =
324            interface_cast<IMediaPlayerService>(binder);
325
326        CHECK(service.get() != NULL);
327
328        sp<IMediaMetadataRetriever> retriever =
329            service->createMetadataRetriever(getpid());
330
331        CHECK(retriever != NULL);
332
333        for (int k = 0; k < argc; ++k) {
334            const char *filename = argv[k];
335
336            CHECK_EQ(retriever->setDataSource(filename), OK);
337            CHECK_EQ(retriever->setMode(METADATA_MODE_FRAME_CAPTURE_ONLY), OK);
338
339            sp<IMemory> mem = retriever->captureFrame();
340
341            printf("captureFrame(%s) => %s\n",
342                   filename, mem != NULL ? "OK" : "FAILED");
343        }
344
345        return 0;
346    }
347
348    if (dumpProfiles) {
349        sp<IServiceManager> sm = defaultServiceManager();
350        sp<IBinder> binder = sm->getService(String16("media.player"));
351        sp<IMediaPlayerService> service =
352            interface_cast<IMediaPlayerService>(binder);
353
354        CHECK(service.get() != NULL);
355
356        sp<IOMX> omx = service->getOMX();
357        CHECK(omx.get() != NULL);
358
359        const char *kMimeTypes[] = {
360            MEDIA_MIMETYPE_VIDEO_AVC, MEDIA_MIMETYPE_VIDEO_MPEG4,
361            MEDIA_MIMETYPE_VIDEO_H263
362        };
363
364        for (size_t k = 0; k < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]);
365             ++k) {
366            printf("type '%s':\n", kMimeTypes[k]);
367
368            Vector<CodecCapabilities> results;
369            CHECK_EQ(QueryCodecs(omx, kMimeTypes[k],
370                                 true, // queryDecoders
371                                 &results), OK);
372
373            for (size_t i = 0; i < results.size(); ++i) {
374                printf("  decoder '%s' supports ",
375                       results[i].mComponentName.string());
376
377                if (results[i].mProfileLevels.size() == 0) {
378                    printf("NOTHING.\n");
379                    continue;
380                }
381
382                for (size_t j = 0; j < results[i].mProfileLevels.size(); ++j) {
383                    const CodecProfileLevel &profileLevel =
384                        results[i].mProfileLevels[j];
385
386                    printf("%s%ld/%ld", j > 0 ? ", " : "",
387                           profileLevel.mProfile, profileLevel.mLevel);
388                }
389
390                printf("\n");
391            }
392        }
393    }
394
395    if (listComponents) {
396        sp<IServiceManager> sm = defaultServiceManager();
397        sp<IBinder> binder = sm->getService(String16("media.player"));
398        sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
399
400        CHECK(service.get() != NULL);
401
402        sp<IOMX> omx = service->getOMX();
403        CHECK(omx.get() != NULL);
404
405        List<IOMX::ComponentInfo> list;
406        omx->listNodes(&list);
407
408        for (List<IOMX::ComponentInfo>::iterator it = list.begin();
409             it != list.end(); ++it) {
410            printf("%s\n", (*it).mName.string());
411        }
412    }
413
414    DataSource::RegisterDefaultSniffers();
415
416    OMXClient client;
417    status_t err = client.connect();
418
419    for (int k = 0; k < argc; ++k) {
420        const char *filename = argv[k];
421
422        sp<DataSource> dataSource;
423        if (!strncasecmp("http://", filename, 7)) {
424            dataSource = new HTTPDataSource(filename);
425            dataSource = new CachingDataSource(dataSource, 64 * 1024, 10);
426        } else {
427            dataSource = new FileSource(filename);
428        }
429
430        bool isJPEG = false;
431
432        size_t len = strlen(filename);
433        if (len >= 4 && !strcasecmp(filename + len - 4, ".jpg")) {
434            isJPEG = true;
435        }
436
437        sp<MediaSource> mediaSource;
438
439        if (isJPEG) {
440            mediaSource = new JPEGSource(dataSource);
441        } else {
442            sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
443            if (extractor == NULL) {
444                fprintf(stderr, "could not create data source\n");
445                return -1;
446            }
447
448            size_t numTracks = extractor->countTracks();
449
450            sp<MetaData> meta;
451            size_t i;
452            for (i = 0; i < numTracks; ++i) {
453                meta = extractor->getTrackMetaData(
454                        i, MediaExtractor::kIncludeExtensiveMetaData);
455
456                const char *mime;
457                meta->findCString(kKeyMIMEType, &mime);
458
459                if (audioOnly && !strncasecmp(mime, "audio/", 6)) {
460                    break;
461                }
462
463                if (!audioOnly && !strncasecmp(mime, "video/", 6)) {
464                    break;
465                }
466            }
467
468            int64_t thumbTimeUs;
469            if (meta->findInt64(kKeyThumbnailTime, &thumbTimeUs)) {
470                printf("thumbnailTime: %lld us (%.2f secs)\n",
471                       thumbTimeUs, thumbTimeUs / 1E6);
472            }
473
474            mediaSource = extractor->getTrack(i);
475        }
476
477        playSource(&client, mediaSource);
478    }
479
480    client.disconnect();
481
482    return 0;
483}
484