1 // Copyright (C) 2021 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <aidl/device/google/atv/audio_proxy/IStreamProvider.h>
18 #include <android-base/thread_annotations.h>
19 #include <utils/RefBase.h>
20 
21 #include <mutex>
22 #include <vector>
23 
24 #include "AidlTypes.h"
25 #include "StreamOutImpl.h"
26 
27 namespace audio_proxy::service {
28 
29 using aidl::device::google::atv::audio_proxy::IStreamProvider;
30 using android::wp;
31 
32 class BusOutputStream;
33 
34 // Class to provider BusOutputStream to clients (StreamOutImpl). The public
35 // functions will be called from either the AIDL thread pool or HIDL thread
36 // pool. So the public functions are thread safe.
37 class BusStreamProvider {
38  public:
39   // Set/unset remote IStreamProvider. It will notify the opened StreamOut in
40   // mStreamOutList as well.
41   void setStreamProvider(std::shared_ptr<IStreamProvider> streamProvider);
42 
43   std::shared_ptr<IStreamProvider> getStreamProvider();
44 
45   // Add stream to the list so that they can be notified when the client becomes
46   // available.
47   void onStreamOutCreated(wp<StreamOutImpl> stream);
48 
49   // Returns different BusOutputStream depends on the current status:
50   // 1. If mStreamProvider is available and mStreamProvider::openOutputStream
51   //    returns valid IOutputStream, returns RemoteBusOutputStream.
52   // 2. Returns DummyBusOutputStream otherwise.
53   // This function always return a non null BusOutputStream.
54   std::shared_ptr<BusOutputStream> openOutputStream(
55       const std::string& address, const AidlAudioConfig& config, int32_t flags,
56       int64_t bufferSizeBytes, int32_t latencyMs);
57 
58   // Clear closed StreamOut and return number of opened StreamOut.
59   size_t cleanAndCountStreamOuts();
60 
61  private:
62   std::shared_ptr<BusOutputStream> openOutputStream_Locked(
63       const std::string& address, const AidlAudioConfig& config, int32_t flags,
64       int64_t bufferSizeBytes, int32_t latencyMs) REQUIRES(mLock);
65 
66   // Remove the dead dead from mStreamOutList.
67   void cleanStreamOutList_Locked() REQUIRES(mLock);
68 
69   std::mutex mLock;
70   std::shared_ptr<IStreamProvider> mStreamProvider GUARDED_BY(mLock);
71   std::vector<wp<StreamOutImpl>> mStreamOutList GUARDED_BY(mLock);
72 };
73 
74 }  // namespace audio_proxy::service