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