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