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