1 /*
2  * Copyright (C) 2013 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 GRAPHIC_BUFFER_SOURCE_H_
18 
19 #define GRAPHIC_BUFFER_SOURCE_H_
20 
21 #include <binder/Status.h>
22 #include <utils/RefBase.h>
23 
24 #include <media/hardware/VideoAPI.h>
25 #include <media/stagefright/foundation/ABase.h>
26 #include <media/stagefright/foundation/AHandlerReflector.h>
27 #include <media/stagefright/foundation/ALooper.h>
28 #include <media/stagefright/bqhelper/ComponentWrapper.h>
29 #include <android/hardware/graphics/bufferqueue/1.0/IGraphicBufferProducer.h>
30 #include <android/hardware/graphics/bufferqueue/2.0/IGraphicBufferProducer.h>
31 
32 namespace android {
33 
34 struct FrameDropper;
35 class BufferItem;
36 class IGraphicBufferProducer;
37 class IGraphicBufferConsumer;
38 /*
39  * This class is used to feed codecs from a Surface via BufferQueue or
40  * HW producer.
41  *
42  * Instances of the class don't run on a dedicated thread.  Instead,
43  * various events trigger data movement:
44  *
45  *  - Availability of a new frame of data from the BufferQueue (notified
46  *    via the onFrameAvailable callback).
47  *  - The return of a codec buffer.
48  *  - Application signaling end-of-stream.
49  *  - Transition to or from "executing" state.
50  *
51  * Frames of data (and, perhaps, the end-of-stream indication) can arrive
52  * before the codec is in the "executing" state, so we need to queue
53  * things up until we're ready to go.
54  *
55  * The GraphicBufferSource can be configure dynamically to discard frames
56  * from the source:
57  *
58  * - if their timestamp is less than a start time
59  * - if the source is suspended or stopped and the suspend/stop-time is reached
60  * - if EOS was signaled
61  * - if there is no encoder connected to it
62  *
63  * The source, furthermore, may choose to not encode (drop) frames if:
64  *
65  * - to throttle the frame rate (keep it under a certain limit)
66  *
67  * Finally the source may optionally hold onto the last non-discarded frame
68  * (even if it was dropped) to reencode it after an interval if no further
69  * frames are sent by the producer.
70  */
71 class GraphicBufferSource : public RefBase {
72 public:
73     GraphicBufferSource();
74 
75     virtual ~GraphicBufferSource();
76 
77     // We can't throw an exception if the constructor fails, so we just set
78     // this and require that the caller test the value.
initCheck()79     status_t initCheck() const {
80         return mInitCheck;
81     }
82 
83     // Returns the handle to the producer side of the BufferQueue.  Buffers
84     // queued on this will be received by GraphicBufferSource.
85     sp<IGraphicBufferProducer> getIGraphicBufferProducer() const;
86 
87     // Returns the handle to the bufferqueue HAL (V1_0) producer side of the BufferQueue.
88     // Buffers queued on this will be received by GraphicBufferSource.
89     sp<::android::hardware::graphics::bufferqueue::V1_0::IGraphicBufferProducer>
90         getHGraphicBufferProducer_V1_0() const;
91 
92     // Returns the handle to the bufferqueue HAL producer side of the BufferQueue.
93     // Buffers queued on this will be received by GraphicBufferSource.
94     sp<::android::hardware::graphics::bufferqueue::V2_0::IGraphicBufferProducer>
95         getHGraphicBufferProducer() const;
96 
97     // This is called when component transitions to running state, which means
98     // we can start handing it buffers.  If we already have buffers of data
99     // sitting in the BufferQueue, this will send them to the codec.
100     status_t start();
101 
102     // This is called when component transitions to stopped, indicating that
103     // the codec is meant to return all buffers back to the client for them
104     // to be freed. Do NOT submit any more buffers to the component.
105     status_t stop();
106 
107     // This is called when component transitions to released, indicating that
108     // we are shutting down.
109     status_t release();
110 
111     // A "codec buffer", i.e. a buffer that can be used to pass data into
112     // the encoder, has been allocated.  (This call does not call back into
113     // component.)
114     status_t onInputBufferAdded(int32_t bufferId);
115 
116     // Called when encoder is no longer using the buffer.  If we have a BQ
117     // buffer available, fill it with a new frame of data; otherwise, just mark
118     // it as available.
119     status_t onInputBufferEmptied(int32_t bufferId, int fenceFd);
120 
121     // IGraphicBufferSource interface
122     // ------------------------------
123 
124     // Configure the buffer source to be used with a component with the default
125     // data space.
126     status_t configure(
127         const sp<ComponentWrapper> &component,
128         int32_t dataSpace,
129         int32_t bufferCount,
130         uint32_t frameWidth,
131         uint32_t frameHeight,
132         uint32_t consumerUsage);
133 
134     // This is called after the last input frame has been submitted or buffer
135     // timestamp is greater or equal than stopTimeUs. We need to submit an empty
136     // buffer with the EOS flag set.  If we don't have a codec buffer ready,
137     // we just set the mEndOfStream flag.
138     status_t signalEndOfInputStream();
139 
140     // If suspend is true, all incoming buffers (including those currently
141     // in the BufferQueue) with timestamp larger than timeUs will be discarded
142     // until the suspension is lifted. If suspend is false, all incoming buffers
143     // including those currently in the BufferQueue) with timestamp larger than
144     // timeUs will be processed. timeUs uses SYSTEM_TIME_MONOTONIC time base.
145     status_t setSuspend(bool suspend, int64_t timeUs);
146 
147     // Specifies the interval after which we requeue the buffer previously
148     // queued to the encoder. This is useful in the case of surface flinger
149     // providing the input surface if the resulting encoded stream is to
150     // be displayed "live". If we were not to push through the extra frame
151     // the decoder on the remote end would be unable to decode the latest frame.
152     // This API must be called before transitioning the encoder to "executing"
153     // state and once this behaviour is specified it cannot be reset.
154     status_t setRepeatPreviousFrameDelayUs(int64_t repeatAfterUs);
155 
156     // Sets the input buffer timestamp offset.
157     // When set, the sample's timestamp will be adjusted with the timeOffsetUs.
158     status_t setTimeOffsetUs(int64_t timeOffsetUs);
159 
160     /*
161      * Set the maximum frame rate on the source.
162      *
163      * When maxFps is a positive number, it indicates the maximum rate at which
164      * the buffers from this source will be sent to the encoder. Excessive
165      * frames will be dropped to meet the frame rate requirement.
166      *
167      * When maxFps is a negative number, any frame drop logic will be disabled
168      * and all frames from this source will be sent to the encoder, even when
169      * the timestamp goes backwards. Note that some components may still drop
170      * out-of-order frames silently, so this usually has to be used in
171      * conjunction with OMXNodeInstance::setMaxPtsGapUs() workaround.
172      *
173      * When maxFps is 0, this call will fail with BAD_VALUE.
174      */
175     status_t setMaxFps(float maxFps);
176 
177     // Sets the time lapse (or slow motion) parameters.
178     // When set, the sample's timestamp will be modified to playback framerate,
179     // and capture timestamp will be modified to capture rate.
180     status_t setTimeLapseConfig(double fps, double captureFps);
181 
182     // Sets the start time us (in system time), samples before which should
183     // be dropped and not submitted to encoder
184     status_t setStartTimeUs(int64_t startTimeUs);
185 
186     // Sets the stop time us (in system time), samples after which should be dropped
187     // and not submitted to encoder. timeUs uses SYSTEM_TIME_MONOTONIC time base.
188     status_t setStopTimeUs(int64_t stopTimeUs);
189 
190     // Gets the stop time offset in us. This is the time offset between latest buffer
191     // time and the stopTimeUs. If stop time is not set, INVALID_OPERATION will be returned.
192     // If return is OK, *stopTimeOffsetUs will contain the valid offset. Otherwise,
193     // *stopTimeOffsetUs will not be modified. Positive stopTimeOffsetUs means buffer time
194     // larger than stopTimeUs.
195     status_t getStopTimeOffsetUs(int64_t *stopTimeOffsetUs);
196 
197     // Sets the desired color aspects, e.g. to be used when producer does not specify a dataspace.
198     status_t setColorAspects(int32_t aspectsPacked);
199 
200 protected:
201 
202     // BufferQueue::ConsumerListener interface, called when a new frame of
203     // data is available.  If we're executing and a codec buffer is
204     // available, we acquire the buffer, copy the GraphicBuffer reference
205     // into the codec buffer, and call Empty[This]Buffer.  If we're not yet
206     // executing or there's no codec buffer available, we just increment
207     // mNumFramesAvailable and return.
208     void onFrameAvailable(const BufferItem& item) ;
209 
210     // BufferQueue::ConsumerListener interface, called when the client has
211     // released one or more GraphicBuffers.  We clear out the appropriate
212     // set of mBufferSlot entries.
213     void onBuffersReleased() ;
214 
215     // BufferQueue::ConsumerListener interface, called when the client has
216     // changed the sideband stream. GraphicBufferSource doesn't handle sideband
217     // streams so this is a no-op (and should never be called).
218     void onSidebandStreamChanged() ;
219 
220 private:
221     // BQ::ConsumerListener interface
222     // ------------------------------
223     struct ConsumerProxy;
224     sp<ConsumerProxy> mConsumerProxy;
225 
226     // Lock, covers all member variables.
227     mutable Mutex mMutex;
228 
229     // Used to report constructor failure.
230     status_t mInitCheck;
231 
232     // Graphic buffer reference objects
233     // --------------------------------
234 
235     // These are used to keep a shared reference to GraphicBuffers and gralloc handles owned by the
236     // GraphicBufferSource as well as to manage the cache slots. Separate references are owned by
237     // the buffer cache (controlled by the buffer queue/buffer producer) and the codec.
238 
239     // When we get a buffer from the producer (BQ) it designates them to be cached into specific
240     // slots. Each slot owns a shared reference to the graphic buffer (we track these using
241     // CachedBuffer) that is in that slot, but the producer controls the slots.
242     struct CachedBuffer;
243 
244     // When we acquire a buffer, we must release it back to the producer once we (or the codec)
245     // no longer uses it (as long as the buffer is still in the cache slot). We use shared
246     // AcquiredBuffer instances for this purpose - and we call release buffer when the last
247     // reference is relinquished.
248     struct AcquiredBuffer;
249 
250     // We also need to keep some extra metadata (other than the buffer reference) for acquired
251     // buffers. These are tracked in VideoBuffer struct.
252     struct VideoBuffer {
253         std::shared_ptr<AcquiredBuffer> mBuffer;
254         nsecs_t mTimestampNs;
255         android_dataspace_t mDataspace;
256     };
257 
258     // Cached and aquired buffers
259     // --------------------------------
260 
261     typedef int slot_id;
262 
263     // Maps a slot to the cached buffer in that slot
264     KeyedVector<slot_id, std::shared_ptr<CachedBuffer>> mBufferSlots;
265 
266     // Queue of buffers acquired in chronological order that are not yet submitted to the codec
267     List<VideoBuffer> mAvailableBuffers;
268 
269     // Number of buffers that have been signaled by the producer that they are available, but
270     // we've been unable to acquire them due to our max acquire count
271     int32_t mNumAvailableUnacquiredBuffers;
272 
273     // Number of frames acquired from consumer (debug only)
274     // (as in aquireBuffer called, and release needs to be called)
275     int32_t mNumOutstandingAcquires;
276 
277     // Acquire a buffer from the BQ and store it in |item| if successful
278     // \return OK on success, or error on failure.
279     status_t acquireBuffer_l(VideoBuffer *item);
280 
281     // Called when a buffer was acquired from the producer
282     void onBufferAcquired_l(const VideoBuffer &buffer);
283 
284     // marks the buffer at the slot no longer cached, and accounts for the outstanding
285     // acquire count. Returns true if the slot was populated; otherwise, false.
286     bool discardBufferInSlot_l(slot_id i);
287 
288     // marks the buffer at the slot index no longer cached, and accounts for the outstanding
289     // acquire count
290     void discardBufferAtSlotIndex_l(ssize_t bsi);
291 
292     // release all acquired and unacquired available buffers
293     // This method will return if it fails to acquire an unacquired available buffer, which will
294     // leave mNumAvailableUnacquiredBuffers positive on return.
295     void releaseAllAvailableBuffers_l();
296 
297     // returns whether we have any available buffers (acquired or not-yet-acquired)
haveAvailableBuffers_l()298     bool haveAvailableBuffers_l() const {
299         return !mAvailableBuffers.empty() || mNumAvailableUnacquiredBuffers > 0;
300     }
301 
302     // Codec buffers
303     // -------------
304 
305     // When we queue buffers to the encoder, we must hold the references to the graphic buffers
306     // in those buffers - as the producer may free the slots.
307 
308     typedef int32_t codec_buffer_id;
309 
310     // set of codec buffer ID-s of buffers available to fill
311     List<codec_buffer_id> mFreeCodecBuffers;
312 
313     // maps codec buffer ID-s to buffer info submitted to the codec. Used to keep a reference for
314     // the graphics buffer.
315     KeyedVector<codec_buffer_id, std::shared_ptr<AcquiredBuffer>> mSubmittedCodecBuffers;
316 
317     // Processes the next acquired frame. If there is no available codec buffer, it returns false
318     // without any further action.
319     //
320     // Otherwise, it consumes the next acquired frame and determines if it needs to be discarded or
321     // dropped. If neither are needed, it submits it to the codec. It also saves the latest
322     // non-dropped frame and submits it for repeat encoding (if this is enabled).
323     //
324     // \require there must be an acquired frame (i.e. we're in the onFrameAvailable callback,
325     // or if we're in codecBufferEmptied and mNumFramesAvailable is nonzero).
326     // \require codec must be executing
327     // \returns true if acquired (and handled) the next frame. Otherwise, false.
328     bool fillCodecBuffer_l();
329 
330     // Calculates the media timestamp for |item| and on success it submits the buffer to the codec,
331     // while also keeping a reference for it in mSubmittedCodecBuffers.
332     // Returns UNKNOWN_ERROR if the buffer was not submitted due to buffer timestamp. Otherwise,
333     // it returns any submit success or error value returned by the codec.
334     status_t submitBuffer_l(const VideoBuffer &item);
335 
336     // Submits an empty buffer, with the EOS flag set if there is an available codec buffer and
337     // sets mEndOfStreamSent flag. Does nothing if there is no codec buffer available.
338     void submitEndOfInputStream_l();
339 
340     // Set to true if we want to send end-of-stream after we run out of available frames from the
341     // producer
342     bool mEndOfStream;
343 
344     // Flag that the EOS was submitted to the encoder
345     bool mEndOfStreamSent;
346 
347     // Dataspace for the last frame submitted to the codec
348     android_dataspace mLastDataspace;
349 
350     // Default color aspects for this source
351     int32_t mDefaultColorAspectsPacked;
352 
353     // called when the data space of the input buffer changes
354     void onDataspaceChanged_l(android_dataspace dataspace, android_pixel_format pixelFormat);
355 
356     // Pointer back to the component that created us.  We send buffers here.
357     sp<ComponentWrapper> mComponent;
358 
359     // Set by start() / stop().
360     bool mExecuting;
361 
362     bool mSuspended;
363 
364     // returns true if this source is unconditionally discarding acquired buffers at the moment
365     // regardless of the metadata of those buffers
366     bool areWeDiscardingAvailableBuffers_l();
367 
368     int64_t mLastFrameTimestampUs;
369 
370     // Our BufferQueue interfaces. mProducer is passed to the producer through
371     // getIGraphicBufferProducer, and mConsumer is used internally to retrieve
372     // the buffers queued by the producer.
373     sp<IGraphicBufferProducer> mProducer;
374     sp<IGraphicBufferConsumer> mConsumer;
375 
376     // The time to stop sending buffers.
377     int64_t mStopTimeUs;
378 
379     struct ActionItem {
380         typedef enum {
381             PAUSE,
382             RESUME,
383             STOP
384         } ActionType;
385         ActionType mAction;
386         int64_t mActionTimeUs;
387     };
388 
389     // Maintain last action timestamp to ensure all the action timestamps are
390     // monotonically increasing.
391     int64_t mLastActionTimeUs;
392 
393     // An action queue that queue up all the actions sent to GraphicBufferSource.
394     // STOP action should only show up at the end of the list as all the actions
395     // after a STOP action will be discarded. mActionQueue is protected by mMutex.
396     List<ActionItem> mActionQueue;
397 
398     ////
399     friend struct AHandlerReflector<GraphicBufferSource>;
400 
401     enum {
402         kWhatRepeatLastFrame,   ///< queue last frame for reencoding
403     };
404     enum {
405         kRepeatLastFrameCount = 10,
406     };
407 
408     int64_t mSkipFramesBeforeNs;
409 
410     sp<FrameDropper> mFrameDropper;
411 
412     sp<ALooper> mLooper;
413     sp<AHandlerReflector<GraphicBufferSource> > mReflector;
414 
415     // Repeat last frame feature
416     // -------------------------
417     // configuration parameter: repeat interval for frame repeating (<0 if repeating is disabled)
418     int64_t mFrameRepeatIntervalUs;
419 
420     // current frame repeat generation - used to cancel a pending frame repeat
421     int32_t mRepeatLastFrameGeneration;
422 
423     // number of times to repeat latest frame (0 = none)
424     int32_t mOutstandingFrameRepeatCount;
425 
426     // The previous buffer should've been repeated but
427     // no codec buffer was available at the time.
428     bool mFrameRepeatBlockedOnCodecBuffer;
429 
430     // hold a reference to the last acquired (and not discarded) frame for frame repeating
431     VideoBuffer mLatestBuffer;
432 
433     // queue last frame for reencode after the repeat interval.
434     void queueFrameRepeat_l();
435 
436     // save |item| as the latest buffer and queue it for reencode (repeat)
437     void setLatestBuffer_l(const VideoBuffer &item);
438 
439     // submit last frame to encoder and queue it for reencode
440     // \return true if buffer was submitted, false if it wasn't (e.g. source is suspended, there
441     // is no available codec buffer)
442     bool repeatLatestBuffer_l();
443 
444     // Time lapse / slow motion configuration
445     // --------------------------------------
446 
447     // desired frame rate for encoding - value <= 0 if undefined
448     double mFps;
449 
450     // desired frame rate for capture - value <= 0 if undefined
451     double mCaptureFps;
452 
453     // Time lapse mode is enabled if the capture frame rate is defined and it is
454     // smaller than half the encoding frame rate (if defined). In this mode,
455     // frames that come in between the capture interval (the reciprocal of the
456     // capture frame rate) are dropped and the encoding timestamp is adjusted to
457     // match the desired encoding frame rate.
458     //
459     // Slow motion mode is enabled if both encoding and capture frame rates are
460     // defined and the encoding frame rate is less than half the capture frame
461     // rate. In this mode, the source is expected to produce frames with an even
462     // timestamp interval (after rounding) with the configured capture fps.
463     //
464     // These modes must be configured by calling setTimeLapseConfig() before
465     // using this source.
466     //
467     // Timestamp snapping for slow motion recording
468     // ============================================
469     //
470     // When the slow motion mode is configured with setTimeLapseConfig(), the
471     // property "debug.stagefright.snap_timestamps" will be checked. If the
472     // value of the property is set to any value other than 1, mSnapTimestamps
473     // will be set to false. Otherwise, mSnapTimestamps will be set to true.
474     // (mSnapTimestamps will be false for time lapse recording regardless of the
475     // value of the property.)
476     //
477     // If mSnapTimestamps is true, i.e., timestamp snapping is enabled, the
478     // first source timestamp will be used as the source base time; afterwards,
479     // the timestamp of each source frame will be snapped to the nearest
480     // expected capture timestamp and scaled to match the configured encoding
481     // frame rate.
482     //
483     // If timestamp snapping is disabled, the timestamp of source frames will
484     // be scaled to match the ratio between the configured encoding frame rate
485     // and the configured capture frame rate.
486 
487     // whether timestamps will be snapped
488     bool mSnapTimestamps{true};
489 
490     // adjusted capture timestamp of the base frame
491     int64_t mBaseCaptureUs;
492 
493     // adjusted encoding timestamp of the base frame
494     int64_t mBaseFrameUs;
495 
496     // number of frames from the base time
497     int64_t mFrameCount;
498 
499     // adjusted capture timestamp for previous frame (negative if there were
500     // none)
501     int64_t mPrevCaptureUs;
502 
503     // adjusted media timestamp for previous frame (negative if there were none)
504     int64_t mPrevFrameUs;
505 
506     // desired offset between media time and capture time
507     int64_t mInputBufferTimeOffsetUs;
508 
509     // Calculates and outputs the timestamp to use for a buffer with a specific buffer timestamp
510     // |bufferTimestampNs|. Returns false on failure (buffer too close or timestamp is moving
511     // backwards). Otherwise, stores the media timestamp in |*codecTimeUs| and returns true.
512     //
513     // This method takes into account the start time offset and any time lapse or slow motion time
514     // adjustment requests.
515     bool calculateCodecTimestamp_l(nsecs_t bufferTimeNs, int64_t *codecTimeUs);
516 
517     void onMessageReceived(const sp<AMessage> &msg);
518 
519     DISALLOW_EVIL_CONSTRUCTORS(GraphicBufferSource);
520 };
521 
522 }  // namespace android
523 
524 #endif  // GRAPHIC_BUFFER_SOURCE_H_
525