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#ifndef IMEDIA_SOURCE_BASE_H_
18
19#define IMEDIA_SOURCE_BASE_H_
20
21#include <map>
22
23#include <binder/IInterface.h>
24#include <binder/IMemory.h>
25#include <media/stagefright/MediaBuffer.h>
26#include <media/stagefright/MediaErrors.h>
27
28namespace android {
29
30struct MediaSource;
31class MetaData;
32class MediaBufferGroup;
33
34class IMediaSource : public IInterface {
35public:
36    DECLARE_META_INTERFACE(MediaSource);
37
38    enum {
39        // Maximum number of buffers would be read in readMultiple.
40        kMaxNumReadMultiple = 128,
41    };
42
43    // To be called before any other methods on this object, except
44    // getFormat().
45    virtual status_t start(MetaData *params = NULL) = 0;
46
47    // Any blocking read call returns immediately with a result of NO_INIT.
48    // It is an error to call any methods other than start after this call
49    // returns. Any buffers the object may be holding onto at the time of
50    // the stop() call are released.
51    // Also, it is imperative that any buffers output by this object and
52    // held onto by callers be released before a call to stop() !!!
53    virtual status_t stop() = 0;
54
55    // Returns the format of the data output by this media source.
56    virtual sp<MetaData> getFormat() = 0;
57
58    // Options that modify read() behaviour. The default is to
59    // a) not request a seek
60    // b) not be late, i.e. lateness_us = 0
61    struct ReadOptions {
62        enum SeekMode : int32_t {
63            SEEK_PREVIOUS_SYNC,
64            SEEK_NEXT_SYNC,
65            SEEK_CLOSEST_SYNC,
66            SEEK_CLOSEST,
67        };
68
69        ReadOptions();
70
71        // Reset everything back to defaults.
72        void reset();
73
74        void setSeekTo(int64_t time_us, SeekMode mode = SEEK_CLOSEST_SYNC);
75        void clearSeekTo();
76        bool getSeekTo(int64_t *time_us, SeekMode *mode) const;
77
78        // TODO: remove this if unused.
79        void setLateBy(int64_t lateness_us);
80        int64_t getLateBy() const;
81
82        void setNonBlocking();
83        void clearNonBlocking();
84        bool getNonBlocking() const;
85
86        // Used to clear all non-persistent options for multiple buffer reads.
87        void clearNonPersistent() {
88            clearSeekTo();
89        }
90
91    private:
92        enum Options {
93            kSeekTo_Option      = 1,
94        };
95
96        uint32_t mOptions;
97        int64_t mSeekTimeUs;
98        SeekMode mSeekMode;
99        int64_t mLatenessUs;
100        bool mNonBlocking;
101    } __attribute__((packed)); // sent through Binder
102
103    // Returns a new buffer of data. Call blocks until a
104    // buffer is available, an error is encountered or the end of the stream
105    // is reached.
106    // End of stream is signalled by a result of ERROR_END_OF_STREAM.
107    // A result of INFO_FORMAT_CHANGED indicates that the format of this
108    // MediaSource has changed mid-stream, the client can continue reading
109    // but should be prepared for buffers of the new configuration.
110    //
111    // TODO: consider removing read() in favor of readMultiple().
112    virtual status_t read(
113            MediaBuffer **buffer, const ReadOptions *options = NULL) = 0;
114
115    // Returns a vector of new buffers of data, where the new buffers are added
116    // to the end of the vector.
117    // Call blocks until an error is encountered, or the end of the stream is
118    // reached, or format change is hit, or |kMaxNumReadMultiple| buffers have
119    // been read.
120    // End of stream is signaled by a result of ERROR_END_OF_STREAM.
121    // A result of INFO_FORMAT_CHANGED indicates that the format of this
122    // MediaSource has changed mid-stream, the client can continue reading
123    // but should be prepared for buffers of the new configuration.
124    //
125    // ReadOptions may be specified. Persistent options apply to all reads;
126    // non-persistent options (e.g. seek) apply only to the first read.
127    virtual status_t readMultiple(
128            Vector<MediaBuffer *> *buffers, uint32_t maxNumBuffers = 1,
129            const ReadOptions *options = nullptr) = 0;
130
131    // Returns true if |readMultiple| is supported, otherwise false.
132    virtual bool supportReadMultiple() = 0;
133
134    // Returns true if |read| supports nonblocking option, otherwise false.
135    // |readMultiple| if supported, always allows the nonblocking option.
136    virtual bool supportNonblockingRead() = 0;
137
138    // Causes this source to suspend pulling data from its upstream source
139    // until a subsequent read-with-seek. Currently only supported by
140    // OMXCodec.
141    virtual status_t pause()  = 0;
142
143    // The consumer of this media source requests that the given buffers
144    // are to be returned exclusively in response to read calls.
145    // This will be called after a successful start() and before the
146    // first read() call.
147    // Callee assumes ownership of the buffers if no error is returned.
148    virtual status_t setBuffers(const Vector<MediaBuffer *> & /* buffers */) = 0;
149
150};
151
152class BnMediaSource: public BnInterface<IMediaSource>
153{
154public:
155    BnMediaSource();
156
157    virtual status_t    onTransact(uint32_t code, const Parcel& data, Parcel* reply,
158                                uint32_t flags = 0);
159
160    virtual status_t pause() {
161        return ERROR_UNSUPPORTED;
162    }
163
164    virtual status_t setBuffers(const Vector<MediaBuffer *> & /* buffers */) {
165        return ERROR_UNSUPPORTED;
166    }
167
168    // TODO: Implement this for local media sources.
169    virtual status_t readMultiple(
170            Vector<MediaBuffer *> * /* buffers */, uint32_t /* maxNumBuffers = 1 */,
171            const ReadOptions * /* options = nullptr */) {
172        return ERROR_UNSUPPORTED;
173    }
174
175    virtual bool supportReadMultiple() {
176        return false;
177    }
178
179    // Override in source if nonblocking reads are supported.
180    virtual bool supportNonblockingRead() {
181        return false;
182    }
183
184    static const size_t kBinderMediaBuffers = 4; // buffers managed by BnMediaSource
185    static const size_t kTransferSharedAsSharedThreshold = 4 * 1024;  // if >= shared, else inline
186    static const size_t kTransferInlineAsSharedThreshold = 64 * 1024; // if >= shared, else inline
187    static const size_t kInlineMaxTransfer = 256 * 1024; // Binder size limited to BINDER_VM_SIZE.
188
189protected:
190    virtual ~BnMediaSource();
191
192private:
193    uint32_t mBuffersSinceStop; // Buffer tracking variable
194
195    std::unique_ptr<MediaBufferGroup> mGroup;
196
197    // To prevent marshalling IMemory with each read transaction, we cache the IMemory pointer
198    // into a map.
199    //
200    // This is converted into an index, which is used to identify the associated memory
201    // on the receiving side.  We hold a reference to the IMemory here to ensure it doesn't
202    // change underneath us.
203
204    struct IndexCache {
205        IndexCache() : mIndex(0) { }
206
207        // Returns the index of the IMemory stored in cache or 0 if not found.
208        uint64_t lookup(const sp<IMemory> &mem) {
209            auto p = mMemoryToIndex.find(mem.get());
210            if (p == mMemoryToIndex.end()) {
211                return 0;
212            }
213            if (MediaBuffer::isDeadObject(p->second.first)) {
214                // this object's dead
215                ALOGW("Attempting to lookup a dead IMemory");
216                (void)mMemoryToIndex.erase(p);
217                return 0;
218            }
219            ALOGW_IF(p->second.first.get() != mem.get(), "Mismatched buffers without reset");
220            return p->second.second;
221        }
222
223        // Returns the index of the IMemory stored in the index cache.
224        uint64_t insert(const sp<IMemory> &mem) {
225            auto p = mMemoryToIndex.find(mem.get());
226            if (p == mMemoryToIndex.end()) {
227                if (mIndex == UINT64_MAX) {
228                    ALOGE("Index overflow");
229                    mIndex = 1; // skip overflow condition and hope for the best
230                } else {
231                    ++mIndex;
232                }
233                (void)mMemoryToIndex.emplace(// C++11 mem.get(), std::make_pair(mem, mIndex))
234                        std::piecewise_construct,
235                        std::forward_as_tuple(mem.get()), std::forward_as_tuple(mem, mIndex));
236                return mIndex;
237            }
238            ALOGW("IMemory already inserted into cache");
239            return p->second.second;
240        }
241
242        void reset() {
243            mMemoryToIndex.clear();
244            mIndex = 0;
245        }
246
247        void gc() {
248            for (auto it = mMemoryToIndex.begin(); it != mMemoryToIndex.end(); ) {
249                if (MediaBuffer::isDeadObject(it->second.first)) {
250                    it = mMemoryToIndex.erase(it);
251                } else {
252                    ++it;
253                }
254            }
255        }
256
257    private:
258        uint64_t mIndex;
259        // C++14 unordered_map erase on iterator is stable; C++11 has no guarantee.
260        // Could key on uintptr_t instead of IMemory *
261        std::map<IMemory *, std::pair<sp<IMemory>, uint64_t>> mMemoryToIndex;
262    } mIndexCache;
263};
264
265}  // namespace android
266
267#endif  // IMEDIA_SOURCE_BASE_H_
268