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