1 /*
2  * Copyright (C) 2020 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 ANDROID_MEDIA_SAMPLE_QUEUE_H
18 #define ANDROID_MEDIA_SAMPLE_QUEUE_H
19 
20 #include <media/MediaSample.h>
21 #include <utils/Mutex.h>
22 
23 #include <memory>
24 #include <mutex>
25 #include <queue>
26 
27 namespace android {
28 
29 /**
30  * MediaSampleQueue asynchronously connects a producer and a consumer of media samples.
31  * Media samples flows through the queue in FIFO order. If the queue is empty the consumer will be
32  * blocked until a new media sample is added or until the producer aborts the queue operation.
33  */
34 class MediaSampleQueue {
35 public:
36     /**
37      * Enqueues a media sample at the end of the queue and notifies potentially waiting consumers.
38      * If the queue has previously been aborted this method does nothing.
39      * @param sample The media sample to enqueue.
40      * @return True if the queue has been aborted.
41      */
42     bool enqueue(const std::shared_ptr<MediaSample>& sample);
43 
44     /**
45      * Removes the next media sample from the queue and returns it. If the queue has previously been
46      * aborted this method returns null. Note that this method will block while the queue is empty.
47      * @param[out] sample The next media sample in the queue.
48      * @return True if the queue has been aborted.
49      */
50     bool dequeue(std::shared_ptr<MediaSample>* sample /* nonnull */);
51 
52     /**
53      * Checks if the queue currently holds any media samples.
54      * @return True if the queue is empty or has been aborted. False otherwise.
55      */
56     bool isEmpty();
57 
58     /**
59      * Aborts the queue operation. This clears the queue and notifies waiting consumers. After the
60      * has been aborted it is not possible to enqueue more samples, and dequeue will return null.
61      */
62     void abort();
63 
64 private:
65     std::queue<std::shared_ptr<MediaSample>> mSampleQueue GUARDED_BY(mMutex);
66     std::mutex mMutex;
67     std::condition_variable mCondition;
68     bool mAborted GUARDED_BY(mMutex) = false;
69 };
70 
71 }  // namespace android
72 #endif  // ANDROID_MEDIA_SAMPLE_QUEUE_H
73