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 #pragma once
18 
19 #include <memory>
20 #include <mutex>
21 #include <thread>
22 #include <vector>
23 
24 #include "host/frontend/webrtc/libdevice/audio_sink.h"
25 #include "host/frontend/webrtc/libcommon/audio_source.h"
26 #include "host/libs/audio_connector/server.h"
27 
28 namespace cuttlefish {
29 class AudioHandler : public AudioServerExecutor {
30   // TODO(jemoreira): This can probably be avoided if playback goes through the
31   // audio device instead.
32   struct HoldingBuffer {
33     std::vector<uint8_t> buffer;
34     size_t count;
35 
36     void Reset(size_t size);
37     size_t Add(const volatile uint8_t* data, size_t max_len);
38     size_t Take(uint8_t* dst, size_t len);
39     bool empty() const;
40     bool full() const;
41     size_t freeCapacity() const;
42     uint8_t* data();
43     uint8_t* end();
44   };
45   struct StreamDesc {
46     std::mutex mtx;
47     int bits_per_sample = -1;
48     int sample_rate = -1;
49     int channels = -1;
50     bool active = false;
51     HoldingBuffer buffer;
52   };
53 
54  public:
55   AudioHandler(std::unique_ptr<AudioServer> audio_server,
56                std::shared_ptr<webrtc_streaming::AudioSink> audio_sink,
57                std::shared_ptr<webrtc_streaming::AudioSource> audio_source);
58   ~AudioHandler() override = default;
59 
60   void Start();
61 
62   // AudioServerExecutor implementation
63   void StreamsInfo(StreamInfoCommand& cmd) override;
64   void SetStreamParameters(StreamSetParamsCommand& cmd) override;
65   void PrepareStream(StreamControlCommand& cmd) override;
66   void ReleaseStream(StreamControlCommand& cmd) override;
67   void StartStream(StreamControlCommand& cmd) override;
68   void StopStream(StreamControlCommand& cmd) override;
69   void ChmapsInfo(ChmapInfoCommand& cmd) override;
70   void JacksInfo(JackInfoCommand& cmd) override;
71 
72   void OnPlaybackBuffer(TxBuffer buffer) override;
73   void OnCaptureBuffer(RxBuffer buffer) override;
74 
75  private:
76   [[noreturn]] void Loop();
77 
78   std::shared_ptr<webrtc_streaming::AudioSink> audio_sink_;
79   std::unique_ptr<AudioServer> audio_server_;
80   std::thread server_thread_;
81   std::vector<StreamDesc> stream_descs_ = {};
82   std::shared_ptr<webrtc_streaming::AudioSource> audio_source_;
83 };
84 }  // namespace cuttlefish
85