1 /*
2  * Copyright (C) 2012 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 #define LOG_TAG "r_submix"
18 //#define LOG_NDEBUG 0
19 
20 #include <errno.h>
21 #include <pthread.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <sys/param.h>
25 #include <sys/time.h>
26 #include <sys/limits.h>
27 #include <unistd.h>
28 
29 #include <cutils/compiler.h>
30 #include <cutils/properties.h>
31 #include <cutils/str_parms.h>
32 #include <log/log.h>
33 #include <utils/String8.h>
34 
35 #include <hardware/audio.h>
36 #include <hardware/hardware.h>
37 #include <system/audio.h>
38 
39 #include <media/AudioParameter.h>
40 #include <media/AudioBufferProvider.h>
41 #include <media/nbaio/MonoPipe.h>
42 #include <media/nbaio/MonoPipeReader.h>
43 
44 #define LOG_STREAMS_TO_FILES 0
45 #if LOG_STREAMS_TO_FILES
46 #include <fcntl.h>
47 #include <stdio.h>
48 #include <sys/stat.h>
49 #endif // LOG_STREAMS_TO_FILES
50 
51 extern "C" {
52 
53 namespace android {
54 
55 // Uncomment to enable extremely verbose logging in this module.
56 // #define SUBMIX_VERBOSE_LOGGING
57 #if defined(SUBMIX_VERBOSE_LOGGING)
58 #define SUBMIX_ALOGV(...) ALOGV(__VA_ARGS__)
59 #define SUBMIX_ALOGE(...) ALOGE(__VA_ARGS__)
60 #else
61 #define SUBMIX_ALOGV(...)
62 #define SUBMIX_ALOGE(...)
63 #endif // SUBMIX_VERBOSE_LOGGING
64 
65 // NOTE: This value will be rounded up to the nearest power of 2 by MonoPipe().
66 #define DEFAULT_PIPE_SIZE_IN_FRAMES  (1024*4)
67 // Value used to divide the MonoPipe() buffer into segments that are written to the source and
68 // read from the sink.  The maximum latency of the device is the size of the MonoPipe's buffer
69 // the minimum latency is the MonoPipe buffer size divided by this value.
70 #define DEFAULT_PIPE_PERIOD_COUNT    4
71 // The duration of MAX_READ_ATTEMPTS * READ_ATTEMPT_SLEEP_MS must be stricly inferior to
72 //   the duration of a record buffer at the current record sample rate (of the device, not of
73 //   the recording itself). Here we have:
74 //      3 * 5ms = 15ms < 1024 frames * 1000 / 48000 = 21.333ms
75 #define MAX_READ_ATTEMPTS            3
76 #define READ_ATTEMPT_SLEEP_MS        5 // 5ms between two read attempts when pipe is empty
77 #define DEFAULT_SAMPLE_RATE_HZ       48000 // default sample rate
78 // See NBAIO_Format frameworks/av/include/media/nbaio/NBAIO.h.
79 #define DEFAULT_FORMAT               AUDIO_FORMAT_PCM_16_BIT
80 // A legacy user of this device does not close the input stream when it shuts down, which
81 // results in the application opening a new input stream before closing the old input stream
82 // handle it was previously using.  Setting this value to 1 allows multiple clients to open
83 // multiple input streams from this device.  If this option is enabled, each input stream returned
84 // is *the same stream* which means that readers will race to read data from these streams.
85 #define ENABLE_LEGACY_INPUT_OPEN     1
86 // Whether channel conversion (16-bit signed PCM mono->stereo, stereo->mono) is enabled.
87 #define ENABLE_CHANNEL_CONVERSION    1
88 // Whether resampling is enabled.
89 #define ENABLE_RESAMPLING            1
90 #if LOG_STREAMS_TO_FILES
91 // Folder to save stream log files to.
92 #define LOG_STREAM_FOLDER "/data/misc/audioserver"
93 // Log filenames for input and output streams.
94 #define LOG_STREAM_OUT_FILENAME LOG_STREAM_FOLDER "/r_submix_out.raw"
95 #define LOG_STREAM_IN_FILENAME LOG_STREAM_FOLDER "/r_submix_in.raw"
96 // File permissions for stream log files.
97 #define LOG_STREAM_FILE_PERMISSIONS (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
98 #endif // LOG_STREAMS_TO_FILES
99 // limit for number of read error log entries to avoid spamming the logs
100 #define MAX_READ_ERROR_LOGS 5
101 
102 // Common limits macros.
103 #ifndef min
104 #define min(a, b) ((a) < (b) ? (a) : (b))
105 #endif // min
106 #ifndef max
107 #define max(a, b) ((a) > (b) ? (a) : (b))
108 #endif // max
109 
110 // Set *result_variable_ptr to true if value_to_find is present in the array array_to_search,
111 // otherwise set *result_variable_ptr to false.
112 #define SUBMIX_VALUE_IN_SET(value_to_find, array_to_search, result_variable_ptr) \
113     { \
114         size_t i; \
115         *(result_variable_ptr) = false; \
116         for (i = 0; i < sizeof(array_to_search) / sizeof((array_to_search)[0]); i++) { \
117           if ((value_to_find) == (array_to_search)[i]) { \
118                 *(result_variable_ptr) = true; \
119                 break; \
120             } \
121         } \
122     }
123 
124 // Configuration of the submix pipe.
125 struct submix_config {
126     // Channel mask field in this data structure is set to either input_channel_mask or
127     // output_channel_mask depending upon the last stream to be opened on this device.
128     struct audio_config common;
129     // Input stream and output stream channel masks.  This is required since input and output
130     // channel bitfields are not equivalent.
131     audio_channel_mask_t input_channel_mask;
132     audio_channel_mask_t output_channel_mask;
133 #if ENABLE_RESAMPLING
134     // Input stream and output stream sample rates.
135     uint32_t input_sample_rate;
136     uint32_t output_sample_rate;
137 #endif // ENABLE_RESAMPLING
138     size_t pipe_frame_size;  // Number of bytes in each audio frame in the pipe.
139     size_t buffer_size_frames; // Size of the audio pipe in frames.
140     // Maximum number of frames buffered by the input and output streams.
141     size_t buffer_period_size_frames;
142 };
143 
144 #define MAX_ROUTES 10
145 typedef struct route_config {
146     struct submix_config config;
147     char address[AUDIO_DEVICE_MAX_ADDRESS_LEN];
148     // Pipe variables: they handle the ring buffer that "pipes" audio:
149     //  - from the submix virtual audio output == what needs to be played
150     //    remotely, seen as an output for AudioFlinger
151     //  - to the virtual audio source == what is captured by the component
152     //    which "records" the submix / virtual audio source, and handles it as needed.
153     // A usecase example is one where the component capturing the audio is then sending it over
154     // Wifi for presentation on a remote Wifi Display device (e.g. a dongle attached to a TV, or a
155     // TV with Wifi Display capabilities), or to a wireless audio player.
156     sp<MonoPipe> rsxSink;
157     sp<MonoPipeReader> rsxSource;
158     // Pointers to the current input and output stream instances.  rsxSink and rsxSource are
159     // destroyed if both and input and output streams are destroyed.
160     struct submix_stream_out *output;
161     struct submix_stream_in *input;
162 #if ENABLE_RESAMPLING
163     // Buffer used as temporary storage for resampled data prior to returning data to the output
164     // stream.
165     int16_t resampler_buffer[DEFAULT_PIPE_SIZE_IN_FRAMES];
166 #endif // ENABLE_RESAMPLING
167 } route_config_t;
168 
169 struct submix_audio_device {
170     struct audio_hw_device device;
171     route_config_t routes[MAX_ROUTES];
172     // Device lock, also used to protect access to submix_audio_device from the input and output
173     // streams.
174     pthread_mutex_t lock;
175 };
176 
177 struct submix_stream_out {
178     struct audio_stream_out stream;
179     struct submix_audio_device *dev;
180     int route_handle;
181     bool output_standby;
182     uint64_t frames_written;
183     uint64_t frames_written_since_standby;
184 #if LOG_STREAMS_TO_FILES
185     int log_fd;
186 #endif // LOG_STREAMS_TO_FILES
187 };
188 
189 struct submix_stream_in {
190     struct audio_stream_in stream;
191     struct submix_audio_device *dev;
192     int route_handle;
193     bool input_standby;
194     bool output_standby_rec_thr; // output standby state as seen from record thread
195     // wall clock when recording starts
196     struct timespec record_start_time;
197     // how many frames have been requested to be read
198     uint64_t read_counter_frames;
199     uint64_t read_counter_frames_since_standby;
200 
201 #if ENABLE_LEGACY_INPUT_OPEN
202     // Number of references to this input stream.
203     volatile int32_t ref_count;
204 #endif // ENABLE_LEGACY_INPUT_OPEN
205 #if LOG_STREAMS_TO_FILES
206     int log_fd;
207 #endif // LOG_STREAMS_TO_FILES
208 
209     volatile uint16_t read_error_count;
210 };
211 
212 // Determine whether the specified sample rate is supported by the submix module.
sample_rate_supported(const uint32_t sample_rate)213 static bool sample_rate_supported(const uint32_t sample_rate)
214 {
215     // Set of sample rates supported by Format_from_SR_C() frameworks/av/media/libnbaio/NAIO.cpp.
216     static const unsigned int supported_sample_rates[] = {
217         8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000,
218     };
219     bool return_value;
220     SUBMIX_VALUE_IN_SET(sample_rate, supported_sample_rates, &return_value);
221     return return_value;
222 }
223 
224 // Determine whether the specified sample rate is supported, if it is return the specified sample
225 // rate, otherwise return the default sample rate for the submix module.
get_supported_sample_rate(uint32_t sample_rate)226 static uint32_t get_supported_sample_rate(uint32_t sample_rate)
227 {
228   return sample_rate_supported(sample_rate) ? sample_rate : DEFAULT_SAMPLE_RATE_HZ;
229 }
230 
231 // Determine whether the specified channel in mask is supported by the submix module.
channel_in_mask_supported(const audio_channel_mask_t channel_in_mask)232 static bool channel_in_mask_supported(const audio_channel_mask_t channel_in_mask)
233 {
234     // Set of channel in masks supported by Format_from_SR_C()
235     // frameworks/av/media/libnbaio/NAIO.cpp.
236     static const audio_channel_mask_t supported_channel_in_masks[] = {
237         AUDIO_CHANNEL_IN_MONO, AUDIO_CHANNEL_IN_STEREO,
238     };
239     bool return_value;
240     SUBMIX_VALUE_IN_SET(channel_in_mask, supported_channel_in_masks, &return_value);
241     return return_value;
242 }
243 
244 // Determine whether the specified channel in mask is supported, if it is return the specified
245 // channel in mask, otherwise return the default channel in mask for the submix module.
get_supported_channel_in_mask(const audio_channel_mask_t channel_in_mask)246 static audio_channel_mask_t get_supported_channel_in_mask(
247         const audio_channel_mask_t channel_in_mask)
248 {
249     return channel_in_mask_supported(channel_in_mask) ? channel_in_mask :
250             static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_IN_STEREO);
251 }
252 
253 // Determine whether the specified channel out mask is supported by the submix module.
channel_out_mask_supported(const audio_channel_mask_t channel_out_mask)254 static bool channel_out_mask_supported(const audio_channel_mask_t channel_out_mask)
255 {
256     // Set of channel out masks supported by Format_from_SR_C()
257     // frameworks/av/media/libnbaio/NAIO.cpp.
258     static const audio_channel_mask_t supported_channel_out_masks[] = {
259         AUDIO_CHANNEL_OUT_MONO, AUDIO_CHANNEL_OUT_STEREO,
260     };
261     bool return_value;
262     SUBMIX_VALUE_IN_SET(channel_out_mask, supported_channel_out_masks, &return_value);
263     return return_value;
264 }
265 
266 // Determine whether the specified channel out mask is supported, if it is return the specified
267 // channel out mask, otherwise return the default channel out mask for the submix module.
get_supported_channel_out_mask(const audio_channel_mask_t channel_out_mask)268 static audio_channel_mask_t get_supported_channel_out_mask(
269         const audio_channel_mask_t channel_out_mask)
270 {
271     return channel_out_mask_supported(channel_out_mask) ? channel_out_mask :
272         static_cast<audio_channel_mask_t>(AUDIO_CHANNEL_OUT_STEREO);
273 }
274 
275 // Get a pointer to submix_stream_out given an audio_stream_out that is embedded within the
276 // structure.
audio_stream_out_get_submix_stream_out(struct audio_stream_out * const stream)277 static struct submix_stream_out * audio_stream_out_get_submix_stream_out(
278         struct audio_stream_out * const stream)
279 {
280     ALOG_ASSERT(stream);
281     return reinterpret_cast<struct submix_stream_out *>(reinterpret_cast<uint8_t *>(stream) -
282                 offsetof(struct submix_stream_out, stream));
283 }
284 
285 // Get a pointer to submix_stream_out given an audio_stream that is embedded within the structure.
audio_stream_get_submix_stream_out(struct audio_stream * const stream)286 static struct submix_stream_out * audio_stream_get_submix_stream_out(
287         struct audio_stream * const stream)
288 {
289     ALOG_ASSERT(stream);
290     return audio_stream_out_get_submix_stream_out(
291             reinterpret_cast<struct audio_stream_out *>(stream));
292 }
293 
294 // Get a pointer to submix_stream_in given an audio_stream_in that is embedded within the
295 // structure.
audio_stream_in_get_submix_stream_in(struct audio_stream_in * const stream)296 static struct submix_stream_in * audio_stream_in_get_submix_stream_in(
297         struct audio_stream_in * const stream)
298 {
299     ALOG_ASSERT(stream);
300     return reinterpret_cast<struct submix_stream_in *>(reinterpret_cast<uint8_t *>(stream) -
301             offsetof(struct submix_stream_in, stream));
302 }
303 
304 // Get a pointer to submix_stream_in given an audio_stream that is embedded within the structure.
audio_stream_get_submix_stream_in(struct audio_stream * const stream)305 static struct submix_stream_in * audio_stream_get_submix_stream_in(
306         struct audio_stream * const stream)
307 {
308     ALOG_ASSERT(stream);
309     return audio_stream_in_get_submix_stream_in(
310             reinterpret_cast<struct audio_stream_in *>(stream));
311 }
312 
313 // Get a pointer to submix_audio_device given a pointer to an audio_device that is embedded within
314 // the structure.
audio_hw_device_get_submix_audio_device(struct audio_hw_device * device)315 static struct submix_audio_device * audio_hw_device_get_submix_audio_device(
316         struct audio_hw_device *device)
317 {
318     ALOG_ASSERT(device);
319     return reinterpret_cast<struct submix_audio_device *>(reinterpret_cast<uint8_t *>(device) -
320         offsetof(struct submix_audio_device, device));
321 }
322 
323 // Compare an audio_config with input channel mask and an audio_config with output channel mask
324 // returning false if they do *not* match, true otherwise.
audio_config_compare(const audio_config * const input_config,const audio_config * const output_config)325 static bool audio_config_compare(const audio_config * const input_config,
326         const audio_config * const output_config)
327 {
328 #if !ENABLE_CHANNEL_CONVERSION
329     const uint32_t input_channels = audio_channel_count_from_in_mask(input_config->channel_mask);
330     const uint32_t output_channels = audio_channel_count_from_out_mask(output_config->channel_mask);
331     if (input_channels != output_channels) {
332         ALOGE("audio_config_compare() channel count mismatch input=%d vs. output=%d",
333               input_channels, output_channels);
334         return false;
335     }
336 #endif // !ENABLE_CHANNEL_CONVERSION
337 #if ENABLE_RESAMPLING
338     if (input_config->sample_rate != output_config->sample_rate &&
339             audio_channel_count_from_in_mask(input_config->channel_mask) != 1) {
340 #else
341     if (input_config->sample_rate != output_config->sample_rate) {
342 #endif // ENABLE_RESAMPLING
343         ALOGE("audio_config_compare() sample rate mismatch %ul vs. %ul",
344               input_config->sample_rate, output_config->sample_rate);
345         return false;
346     }
347     if (input_config->format != output_config->format) {
348         ALOGE("audio_config_compare() format mismatch %x vs. %x",
349               input_config->format, output_config->format);
350         return false;
351     }
352     // This purposely ignores offload_info as it's not required for the submix device.
353     return true;
354 }
355 
356 // If one doesn't exist, create a pipe for the submix audio device rsxadev of size
357 // buffer_size_frames and optionally associate "in" or "out" with the submix audio device.
358 // Must be called with lock held on the submix_audio_device
359 static void submix_audio_device_create_pipe_l(struct submix_audio_device * const rsxadev,
360                                             const struct audio_config * const config,
361                                             const size_t buffer_size_frames,
362                                             const uint32_t buffer_period_count,
363                                             struct submix_stream_in * const in,
364                                             struct submix_stream_out * const out,
365                                             const char *address,
366                                             int route_idx)
367 {
368     ALOG_ASSERT(in || out);
369     ALOG_ASSERT(route_idx > -1);
370     ALOG_ASSERT(route_idx < MAX_ROUTES);
371     ALOGD("submix_audio_device_create_pipe_l(addr=%s, idx=%d)", address, route_idx);
372 
373     // Save a reference to the specified input or output stream and the associated channel
374     // mask.
375     if (in) {
376         in->route_handle = route_idx;
377         rsxadev->routes[route_idx].input = in;
378         rsxadev->routes[route_idx].config.input_channel_mask = config->channel_mask;
379 #if ENABLE_RESAMPLING
380         rsxadev->routes[route_idx].config.input_sample_rate = config->sample_rate;
381         // If the output isn't configured yet, set the output sample rate to the maximum supported
382         // sample rate such that the smallest possible input buffer is created, and put a default
383         // value for channel count
384         if (!rsxadev->routes[route_idx].output) {
385             rsxadev->routes[route_idx].config.output_sample_rate = 48000;
386             rsxadev->routes[route_idx].config.output_channel_mask = AUDIO_CHANNEL_OUT_STEREO;
387         }
388 #endif // ENABLE_RESAMPLING
389     }
390     if (out) {
391         out->route_handle = route_idx;
392         rsxadev->routes[route_idx].output = out;
393         rsxadev->routes[route_idx].config.output_channel_mask = config->channel_mask;
394 #if ENABLE_RESAMPLING
395         rsxadev->routes[route_idx].config.output_sample_rate = config->sample_rate;
396 #endif // ENABLE_RESAMPLING
397     }
398     // Save the address
399     strncpy(rsxadev->routes[route_idx].address, address, AUDIO_DEVICE_MAX_ADDRESS_LEN);
400     ALOGD("  now using address %s for route %d", rsxadev->routes[route_idx].address, route_idx);
401     // If a pipe isn't associated with the device, create one.
402     if (rsxadev->routes[route_idx].rsxSink == NULL || rsxadev->routes[route_idx].rsxSource == NULL)
403     {
404         struct submix_config * const device_config = &rsxadev->routes[route_idx].config;
405         uint32_t channel_count;
406         if (out)
407             channel_count = audio_channel_count_from_out_mask(config->channel_mask);
408         else
409             channel_count = audio_channel_count_from_in_mask(config->channel_mask);
410 #if ENABLE_CHANNEL_CONVERSION
411         // If channel conversion is enabled, allocate enough space for the maximum number of
412         // possible channels stored in the pipe for the situation when the number of channels in
413         // the output stream don't match the number in the input stream.
414         const uint32_t pipe_channel_count = max(channel_count, 2);
415 #else
416         const uint32_t pipe_channel_count = channel_count;
417 #endif // ENABLE_CHANNEL_CONVERSION
418         const NBAIO_Format format = Format_from_SR_C(config->sample_rate, pipe_channel_count,
419             config->format);
420         const NBAIO_Format offers[1] = {format};
421         size_t numCounterOffers = 0;
422         // Create a MonoPipe with optional blocking set to true.
423         MonoPipe* sink = new MonoPipe(buffer_size_frames, format, true /*writeCanBlock*/);
424         // Negotiation between the source and sink cannot fail as the device open operation
425         // creates both ends of the pipe using the same audio format.
426         ssize_t index = sink->negotiate(offers, 1, NULL, numCounterOffers);
427         ALOG_ASSERT(index == 0);
428         MonoPipeReader* source = new MonoPipeReader(sink);
429         numCounterOffers = 0;
430         index = source->negotiate(offers, 1, NULL, numCounterOffers);
431         ALOG_ASSERT(index == 0);
432         ALOGV("submix_audio_device_create_pipe_l(): created pipe");
433 
434         // Save references to the source and sink.
435         ALOG_ASSERT(rsxadev->routes[route_idx].rsxSink == NULL);
436         ALOG_ASSERT(rsxadev->routes[route_idx].rsxSource == NULL);
437         rsxadev->routes[route_idx].rsxSink = sink;
438         rsxadev->routes[route_idx].rsxSource = source;
439         // Store the sanitized audio format in the device so that it's possible to determine
440         // the format of the pipe source when opening the input device.
441         memcpy(&device_config->common, config, sizeof(device_config->common));
442         device_config->buffer_size_frames = sink->maxFrames();
443         device_config->buffer_period_size_frames = device_config->buffer_size_frames /
444                 buffer_period_count;
445         if (in) device_config->pipe_frame_size = audio_stream_in_frame_size(&in->stream);
446         if (out) device_config->pipe_frame_size = audio_stream_out_frame_size(&out->stream);
447 #if ENABLE_CHANNEL_CONVERSION
448         // Calculate the pipe frame size based upon the number of channels.
449         device_config->pipe_frame_size = (device_config->pipe_frame_size * pipe_channel_count) /
450                 channel_count;
451 #endif // ENABLE_CHANNEL_CONVERSION
452         SUBMIX_ALOGV("submix_audio_device_create_pipe_l(): pipe frame size %zd, pipe size %zd, "
453                      "period size %zd", device_config->pipe_frame_size,
454                      device_config->buffer_size_frames, device_config->buffer_period_size_frames);
455     }
456 }
457 
458 // Release references to the sink and source.  Input and output threads may maintain references
459 // to these objects via StrongPointer (sp<MonoPipe> and sp<MonoPipeReader>) which they can use
460 // before they shutdown.
461 // Must be called with lock held on the submix_audio_device
462 static void submix_audio_device_release_pipe_l(struct submix_audio_device * const rsxadev,
463         int route_idx)
464 {
465     ALOG_ASSERT(route_idx > -1);
466     ALOG_ASSERT(route_idx < MAX_ROUTES);
467     ALOGD("submix_audio_device_release_pipe_l(idx=%d) addr=%s", route_idx,
468             rsxadev->routes[route_idx].address);
469     if (rsxadev->routes[route_idx].rsxSink != 0) {
470         rsxadev->routes[route_idx].rsxSink.clear();
471     }
472     if (rsxadev->routes[route_idx].rsxSource != 0) {
473         rsxadev->routes[route_idx].rsxSource.clear();
474     }
475     memset(rsxadev->routes[route_idx].address, 0, AUDIO_DEVICE_MAX_ADDRESS_LEN);
476 #if ENABLE_RESAMPLING
477     memset(rsxadev->routes[route_idx].resampler_buffer, 0,
478             sizeof(int16_t) * DEFAULT_PIPE_SIZE_IN_FRAMES);
479 #endif
480 }
481 
482 // Remove references to the specified input and output streams.  When the device no longer
483 // references input and output streams destroy the associated pipe.
484 // Must be called with lock held on the submix_audio_device
485 static void submix_audio_device_destroy_pipe_l(struct submix_audio_device * const rsxadev,
486                                              const struct submix_stream_in * const in,
487                                              const struct submix_stream_out * const out)
488 {
489     ALOGV("submix_audio_device_destroy_pipe_l()");
490     int route_idx = -1;
491     if (in != NULL) {
492         bool shut_down = false;
493 #if ENABLE_LEGACY_INPUT_OPEN
494         const_cast<struct submix_stream_in*>(in)->ref_count--;
495         route_idx = in->route_handle;
496         ALOG_ASSERT(rsxadev->routes[route_idx].input == in);
497         if (in->ref_count == 0) {
498             rsxadev->routes[route_idx].input = NULL;
499             shut_down = true;
500         }
501         ALOGV("submix_audio_device_destroy_pipe_l(): input ref_count %d", in->ref_count);
502 #else
503         route_idx = in->route_handle;
504         ALOG_ASSERT(rsxadev->routes[route_idx].input == in);
505         rsxadev->routes[route_idx].input = NULL;
506         shut_down = true;
507 #endif // ENABLE_LEGACY_INPUT_OPEN
508         if (shut_down) {
509             sp <MonoPipe> sink = rsxadev->routes[in->route_handle].rsxSink;
510             if (sink != NULL) {
511               sink->shutdown(true);
512             }
513         }
514     }
515     if (out != NULL) {
516         route_idx = out->route_handle;
517         ALOG_ASSERT(rsxadev->routes[route_idx].output == out);
518         rsxadev->routes[route_idx].output = NULL;
519     }
520     if (route_idx != -1 &&
521             rsxadev->routes[route_idx].input == NULL && rsxadev->routes[route_idx].output == NULL) {
522         submix_audio_device_release_pipe_l(rsxadev, route_idx);
523         ALOGD("submix_audio_device_destroy_pipe_l(): pipe destroyed");
524     }
525 }
526 
527 // Sanitize the user specified audio config for a submix input / output stream.
528 static void submix_sanitize_config(struct audio_config * const config, const bool is_input_format)
529 {
530     config->channel_mask = is_input_format ? get_supported_channel_in_mask(config->channel_mask) :
531             get_supported_channel_out_mask(config->channel_mask);
532     config->sample_rate = get_supported_sample_rate(config->sample_rate);
533     config->format = DEFAULT_FORMAT;
534 }
535 
536 // Verify a submix input or output stream can be opened.
537 // Must be called with lock held on the submix_audio_device
538 static bool submix_open_validate_l(const struct submix_audio_device * const rsxadev,
539                                  int route_idx,
540                                  const struct audio_config * const config,
541                                  const bool opening_input)
542 {
543     bool input_open;
544     bool output_open;
545     audio_config pipe_config;
546 
547     // Query the device for the current audio config and whether input and output streams are open.
548     output_open = rsxadev->routes[route_idx].output != NULL;
549     input_open = rsxadev->routes[route_idx].input != NULL;
550     memcpy(&pipe_config, &rsxadev->routes[route_idx].config.common, sizeof(pipe_config));
551 
552     // If the stream is already open, don't open it again.
553     if (opening_input ? !ENABLE_LEGACY_INPUT_OPEN && input_open : output_open) {
554         ALOGE("submix_open_validate_l(): %s stream already open.", opening_input ? "Input" :
555                 "Output");
556         return false;
557     }
558 
559     SUBMIX_ALOGV("submix_open_validate_l(): sample rate=%d format=%x "
560                  "%s_channel_mask=%x", config->sample_rate, config->format,
561                  opening_input ? "in" : "out", config->channel_mask);
562 
563     // If either stream is open, verify the existing audio config the pipe matches the user
564     // specified config.
565     if (input_open || output_open) {
566         const audio_config * const input_config = opening_input ? config : &pipe_config;
567         const audio_config * const output_config = opening_input ? &pipe_config : config;
568         // Get the channel mask of the open device.
569         pipe_config.channel_mask =
570             opening_input ? rsxadev->routes[route_idx].config.output_channel_mask :
571                 rsxadev->routes[route_idx].config.input_channel_mask;
572         if (!audio_config_compare(input_config, output_config)) {
573             ALOGE("submix_open_validate_l(): Unsupported format.");
574             return false;
575         }
576     }
577     return true;
578 }
579 
580 // Must be called with lock held on the submix_audio_device
581 static status_t submix_get_route_idx_for_address_l(const struct submix_audio_device * const rsxadev,
582                                                  const char* address, /*in*/
583                                                  int *idx /*out*/)
584 {
585     // Do we already have a route for this address
586     int route_idx = -1;
587     int route_empty_idx = -1; // index of an empty route slot that can be used if needed
588     for (int i=0 ; i < MAX_ROUTES ; i++) {
589         if (strcmp(rsxadev->routes[i].address, "") == 0) {
590             route_empty_idx = i;
591         }
592         if (strncmp(rsxadev->routes[i].address, address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
593             route_idx = i;
594             break;
595         }
596     }
597 
598     if ((route_idx == -1) && (route_empty_idx == -1)) {
599         ALOGE("Cannot create new route for address %s, max number of routes reached", address);
600         return -ENOMEM;
601     }
602     if (route_idx == -1) {
603         route_idx = route_empty_idx;
604     }
605     *idx = route_idx;
606     return OK;
607 }
608 
609 
610 // Calculate the maximum size of the pipe buffer in frames for the specified stream.
611 static size_t calculate_stream_pipe_size_in_frames(const struct audio_stream *stream,
612                                                    const struct submix_config *config,
613                                                    const size_t pipe_frames,
614                                                    const size_t stream_frame_size)
615 {
616     const size_t pipe_frame_size = config->pipe_frame_size;
617     const size_t max_frame_size = max(stream_frame_size, pipe_frame_size);
618     return (pipe_frames * config->pipe_frame_size) / max_frame_size;
619 }
620 
621 /* audio HAL functions */
622 
623 static uint32_t out_get_sample_rate(const struct audio_stream *stream)
624 {
625     const struct submix_stream_out * const out = audio_stream_get_submix_stream_out(
626             const_cast<struct audio_stream *>(stream));
627 #if ENABLE_RESAMPLING
628     const uint32_t out_rate = out->dev->routes[out->route_handle].config.output_sample_rate;
629 #else
630     const uint32_t out_rate = out->dev->routes[out->route_handle].config.common.sample_rate;
631 #endif // ENABLE_RESAMPLING
632     SUBMIX_ALOGV("out_get_sample_rate() returns %u for addr %s",
633             out_rate, out->dev->routes[out->route_handle].address);
634     return out_rate;
635 }
636 
637 static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate)
638 {
639     struct submix_stream_out * const out = audio_stream_get_submix_stream_out(stream);
640 #if ENABLE_RESAMPLING
641     // The sample rate of the stream can't be changed once it's set since this would change the
642     // output buffer size and hence break playback to the shared pipe.
643     if (rate != out->dev->routes[out->route_handle].config.output_sample_rate) {
644         ALOGE("out_set_sample_rate() resampling enabled can't change sample rate from "
645               "%u to %u for addr %s",
646               out->dev->routes[out->route_handle].config.output_sample_rate, rate,
647               out->dev->routes[out->route_handle].address);
648         return -ENOSYS;
649     }
650 #endif // ENABLE_RESAMPLING
651     if (!sample_rate_supported(rate)) {
652         ALOGE("out_set_sample_rate(rate=%u) rate unsupported", rate);
653         return -ENOSYS;
654     }
655     SUBMIX_ALOGV("out_set_sample_rate(rate=%u)", rate);
656     out->dev->routes[out->route_handle].config.common.sample_rate = rate;
657     return 0;
658 }
659 
660 static size_t out_get_buffer_size(const struct audio_stream *stream)
661 {
662     const struct submix_stream_out * const out = audio_stream_get_submix_stream_out(
663             const_cast<struct audio_stream *>(stream));
664     const struct submix_config * const config = &out->dev->routes[out->route_handle].config;
665     const size_t stream_frame_size =
666                             audio_stream_out_frame_size((const struct audio_stream_out *)stream);
667     const size_t buffer_size_frames = calculate_stream_pipe_size_in_frames(
668         stream, config, config->buffer_period_size_frames, stream_frame_size);
669     const size_t buffer_size_bytes = buffer_size_frames * stream_frame_size;
670     SUBMIX_ALOGV("out_get_buffer_size() returns %zu bytes, %zu frames",
671                  buffer_size_bytes, buffer_size_frames);
672     return buffer_size_bytes;
673 }
674 
675 static audio_channel_mask_t out_get_channels(const struct audio_stream *stream)
676 {
677     const struct submix_stream_out * const out = audio_stream_get_submix_stream_out(
678             const_cast<struct audio_stream *>(stream));
679     audio_channel_mask_t channel_mask =
680             out->dev->routes[out->route_handle].config.output_channel_mask;
681     SUBMIX_ALOGV("out_get_channels() returns %08x", channel_mask);
682     return channel_mask;
683 }
684 
685 static audio_format_t out_get_format(const struct audio_stream *stream)
686 {
687     const struct submix_stream_out * const out = audio_stream_get_submix_stream_out(
688             const_cast<struct audio_stream *>(stream));
689     const audio_format_t format = out->dev->routes[out->route_handle].config.common.format;
690     SUBMIX_ALOGV("out_get_format() returns %x", format);
691     return format;
692 }
693 
694 static int out_set_format(struct audio_stream *stream, audio_format_t format)
695 {
696     const struct submix_stream_out * const out = audio_stream_get_submix_stream_out(stream);
697     if (format != out->dev->routes[out->route_handle].config.common.format) {
698         ALOGE("out_set_format(format=%x) format unsupported", format);
699         return -ENOSYS;
700     }
701     SUBMIX_ALOGV("out_set_format(format=%x)", format);
702     return 0;
703 }
704 
705 static int out_standby(struct audio_stream *stream)
706 {
707     ALOGI("out_standby()");
708     struct submix_stream_out * const out = audio_stream_get_submix_stream_out(stream);
709     struct submix_audio_device * const rsxadev = out->dev;
710 
711     pthread_mutex_lock(&rsxadev->lock);
712 
713     out->output_standby = true;
714     out->frames_written_since_standby = 0;
715 
716     pthread_mutex_unlock(&rsxadev->lock);
717 
718     return 0;
719 }
720 
721 static int out_dump(const struct audio_stream *stream, int fd)
722 {
723     (void)stream;
724     (void)fd;
725     return 0;
726 }
727 
728 static int out_set_parameters(struct audio_stream *stream, const char *kvpairs)
729 {
730     int exiting = -1;
731     AudioParameter parms = AudioParameter(String8(kvpairs));
732     SUBMIX_ALOGV("out_set_parameters() kvpairs='%s'", kvpairs);
733 
734     // FIXME this is using hard-coded strings but in the future, this functionality will be
735     //       converted to use audio HAL extensions required to support tunneling
736     if ((parms.getInt(String8("exiting"), exiting) == NO_ERROR) && (exiting > 0)) {
737         struct submix_audio_device * const rsxadev =
738                 audio_stream_get_submix_stream_out(stream)->dev;
739         pthread_mutex_lock(&rsxadev->lock);
740         { // using the sink
741             sp<MonoPipe> sink =
742                     rsxadev->routes[audio_stream_get_submix_stream_out(stream)->route_handle]
743                                     .rsxSink;
744             if (sink == NULL) {
745                 pthread_mutex_unlock(&rsxadev->lock);
746                 return 0;
747             }
748 
749             ALOGD("out_set_parameters(): shutting down MonoPipe sink");
750             sink->shutdown(true);
751         } // done using the sink
752         pthread_mutex_unlock(&rsxadev->lock);
753     }
754     return 0;
755 }
756 
757 static char * out_get_parameters(const struct audio_stream *stream, const char *keys)
758 {
759     (void)stream;
760     (void)keys;
761     return strdup("");
762 }
763 
764 static uint32_t out_get_latency(const struct audio_stream_out *stream)
765 {
766     const struct submix_stream_out * const out = audio_stream_out_get_submix_stream_out(
767             const_cast<struct audio_stream_out *>(stream));
768     const struct submix_config * const config = &out->dev->routes[out->route_handle].config;
769     const size_t stream_frame_size =
770                             audio_stream_out_frame_size(stream);
771     const size_t buffer_size_frames = calculate_stream_pipe_size_in_frames(
772             &stream->common, config, config->buffer_size_frames, stream_frame_size);
773     const uint32_t sample_rate = out_get_sample_rate(&stream->common);
774     const uint32_t latency_ms = (buffer_size_frames * 1000) / sample_rate;
775     SUBMIX_ALOGV("out_get_latency() returns %u ms, size in frames %zu, sample rate %u",
776                  latency_ms, buffer_size_frames, sample_rate);
777     return latency_ms;
778 }
779 
780 static int out_set_volume(struct audio_stream_out *stream, float left,
781                           float right)
782 {
783     (void)stream;
784     (void)left;
785     (void)right;
786     return -ENOSYS;
787 }
788 
789 static ssize_t out_write(struct audio_stream_out *stream, const void* buffer,
790                          size_t bytes)
791 {
792     SUBMIX_ALOGV("out_write(bytes=%zd)", bytes);
793     ssize_t written_frames = 0;
794     const size_t frame_size = audio_stream_out_frame_size(stream);
795     struct submix_stream_out * const out = audio_stream_out_get_submix_stream_out(stream);
796     struct submix_audio_device * const rsxadev = out->dev;
797     const size_t frames = bytes / frame_size;
798 
799     pthread_mutex_lock(&rsxadev->lock);
800 
801     out->output_standby = false;
802 
803     sp<MonoPipe> sink = rsxadev->routes[out->route_handle].rsxSink;
804     if (sink != NULL) {
805         if (sink->isShutdown()) {
806             sink.clear();
807             pthread_mutex_unlock(&rsxadev->lock);
808             SUBMIX_ALOGV("out_write(): pipe shutdown, ignoring the write.");
809             // the pipe has already been shutdown, this buffer will be lost but we must
810             //   simulate timing so we don't drain the output faster than realtime
811             usleep(frames * 1000000 / out_get_sample_rate(&stream->common));
812 
813             pthread_mutex_lock(&rsxadev->lock);
814             out->frames_written += frames;
815             out->frames_written_since_standby += frames;
816             pthread_mutex_unlock(&rsxadev->lock);
817             return bytes;
818         }
819     } else {
820         pthread_mutex_unlock(&rsxadev->lock);
821         ALOGE("out_write without a pipe!");
822         ALOG_ASSERT("out_write without a pipe!");
823         return 0;
824     }
825 
826     // If the write to the sink would block, flush enough frames
827     // from the pipe to make space to write the most recent data.
828     // We DO NOT block if:
829     // - no peer input stream is present
830     // - the peer input is in standby AFTER having been active.
831     // We DO block if:
832     // - the input was never activated to avoid discarding first frames
833     // in the pipe in case capture start was delayed
834     {
835         const size_t availableToWrite = sink->availableToWrite();
836         // NOTE: rsxSink has been checked above and sink and source life cycles are synchronized
837         sp<MonoPipeReader> source = rsxadev->routes[out->route_handle].rsxSource;
838         const struct submix_stream_in *in = rsxadev->routes[out->route_handle].input;
839         const bool dont_block = (in == NULL)
840                 || (in->input_standby && (in->read_counter_frames_since_standby != 0));
841         if (dont_block && availableToWrite < frames) {
842             static uint8_t flush_buffer[64];
843             const size_t flushBufferSizeFrames = sizeof(flush_buffer) / frame_size;
844             size_t frames_to_flush_from_source = frames - availableToWrite;
845             SUBMIX_ALOGV("out_write(): flushing %llu frames from the pipe to avoid blocking",
846                     (unsigned long long)frames_to_flush_from_source);
847             while (frames_to_flush_from_source) {
848                 const size_t flush_size = min(frames_to_flush_from_source, flushBufferSizeFrames);
849                 frames_to_flush_from_source -= flush_size;
850                 // read does not block
851                 source->read(flush_buffer, flush_size);
852             }
853         }
854     }
855 
856     pthread_mutex_unlock(&rsxadev->lock);
857 
858     written_frames = sink->write(buffer, frames);
859 
860 #if LOG_STREAMS_TO_FILES
861     if (out->log_fd >= 0) write(out->log_fd, buffer, written_frames * frame_size);
862 #endif // LOG_STREAMS_TO_FILES
863 
864     if (written_frames < 0) {
865         if (written_frames == (ssize_t)NEGOTIATE) {
866             ALOGE("out_write() write to pipe returned NEGOTIATE");
867 
868             pthread_mutex_lock(&rsxadev->lock);
869             sink.clear();
870             pthread_mutex_unlock(&rsxadev->lock);
871 
872             written_frames = 0;
873             return 0;
874         } else {
875             // write() returned UNDERRUN or WOULD_BLOCK, retry
876             ALOGE("out_write() write to pipe returned unexpected %zd", written_frames);
877             written_frames = sink->write(buffer, frames);
878         }
879     }
880 
881     pthread_mutex_lock(&rsxadev->lock);
882     sink.clear();
883     if (written_frames > 0) {
884         out->frames_written_since_standby += written_frames;
885         out->frames_written += written_frames;
886     }
887     pthread_mutex_unlock(&rsxadev->lock);
888 
889     if (written_frames < 0) {
890         ALOGE("out_write() failed writing to pipe with %zd", written_frames);
891         return 0;
892     }
893     const ssize_t written_bytes = written_frames * frame_size;
894     SUBMIX_ALOGV("out_write() wrote %zd bytes %zd frames", written_bytes, written_frames);
895     return written_bytes;
896 }
897 
898 static int out_get_presentation_position(const struct audio_stream_out *stream,
899                                    uint64_t *frames, struct timespec *timestamp)
900 {
901     if (stream == NULL || frames == NULL || timestamp == NULL) {
902         return -EINVAL;
903     }
904 
905     const submix_stream_out *out = audio_stream_out_get_submix_stream_out(
906             const_cast<struct audio_stream_out *>(stream));
907     struct submix_audio_device * const rsxadev = out->dev;
908 
909     int ret = -EWOULDBLOCK;
910     pthread_mutex_lock(&rsxadev->lock);
911     sp<MonoPipeReader> source = rsxadev->routes[out->route_handle].rsxSource;
912     if (source == NULL) {
913         ALOGW("%s called on released output", __FUNCTION__);
914         pthread_mutex_unlock(&rsxadev->lock);
915         return -ENODEV;
916     }
917 
918     const ssize_t frames_in_pipe = source->availableToRead();
919     if (CC_UNLIKELY(frames_in_pipe < 0)) {
920         *frames = out->frames_written;
921         ret = 0;
922     } else if (out->frames_written >= (uint64_t)frames_in_pipe) {
923         *frames = out->frames_written - frames_in_pipe;
924         ret = 0;
925     }
926     pthread_mutex_unlock(&rsxadev->lock);
927 
928     if (ret == 0) {
929         clock_gettime(CLOCK_MONOTONIC, timestamp);
930     }
931 
932     SUBMIX_ALOGV("out_get_presentation_position() got frames=%llu timestamp sec=%llu",
933             frames ? (unsigned long long)*frames : -1ULL,
934             timestamp ? (unsigned long long)timestamp->tv_sec : -1ULL);
935 
936     return ret;
937 }
938 
939 static int out_get_render_position(const struct audio_stream_out *stream,
940                                    uint32_t *dsp_frames)
941 {
942     if (stream == NULL || dsp_frames == NULL) {
943         return -EINVAL;
944     }
945 
946     const submix_stream_out *out = audio_stream_out_get_submix_stream_out(
947             const_cast<struct audio_stream_out *>(stream));
948     struct submix_audio_device * const rsxadev = out->dev;
949 
950     pthread_mutex_lock(&rsxadev->lock);
951     sp<MonoPipeReader> source = rsxadev->routes[out->route_handle].rsxSource;
952     if (source == NULL) {
953         ALOGW("%s called on released output", __FUNCTION__);
954         pthread_mutex_unlock(&rsxadev->lock);
955         return -ENODEV;
956     }
957 
958     const ssize_t frames_in_pipe = source->availableToRead();
959     if (CC_UNLIKELY(frames_in_pipe < 0)) {
960         *dsp_frames = (uint32_t)out->frames_written_since_standby;
961     } else {
962         *dsp_frames = out->frames_written_since_standby > (uint64_t) frames_in_pipe ?
963                 (uint32_t)(out->frames_written_since_standby - frames_in_pipe) : 0;
964     }
965     pthread_mutex_unlock(&rsxadev->lock);
966 
967     return 0;
968 }
969 
970 static int out_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
971 {
972     (void)stream;
973     (void)effect;
974     return 0;
975 }
976 
977 static int out_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
978 {
979     (void)stream;
980     (void)effect;
981     return 0;
982 }
983 
984 static int out_get_next_write_timestamp(const struct audio_stream_out *stream,
985                                         int64_t *timestamp)
986 {
987     (void)stream;
988     (void)timestamp;
989     return -ENOSYS;
990 }
991 
992 /** audio_stream_in implementation **/
993 static uint32_t in_get_sample_rate(const struct audio_stream *stream)
994 {
995     const struct submix_stream_in * const in = audio_stream_get_submix_stream_in(
996         const_cast<struct audio_stream*>(stream));
997 #if ENABLE_RESAMPLING
998     const uint32_t rate = in->dev->routes[in->route_handle].config.input_sample_rate;
999 #else
1000     const uint32_t rate = in->dev->routes[in->route_handle].config.common.sample_rate;
1001 #endif // ENABLE_RESAMPLING
1002     SUBMIX_ALOGV("in_get_sample_rate() returns %u", rate);
1003     return rate;
1004 }
1005 
1006 static int in_set_sample_rate(struct audio_stream *stream, uint32_t rate)
1007 {
1008     const struct submix_stream_in * const in = audio_stream_get_submix_stream_in(stream);
1009 #if ENABLE_RESAMPLING
1010     // The sample rate of the stream can't be changed once it's set since this would change the
1011     // input buffer size and hence break recording from the shared pipe.
1012     if (rate != in->dev->routes[in->route_handle].config.input_sample_rate) {
1013         ALOGE("in_set_sample_rate() resampling enabled can't change sample rate from "
1014               "%u to %u", in->dev->routes[in->route_handle].config.input_sample_rate, rate);
1015         return -ENOSYS;
1016     }
1017 #endif // ENABLE_RESAMPLING
1018     if (!sample_rate_supported(rate)) {
1019         ALOGE("in_set_sample_rate(rate=%u) rate unsupported", rate);
1020         return -ENOSYS;
1021     }
1022     in->dev->routes[in->route_handle].config.common.sample_rate = rate;
1023     SUBMIX_ALOGV("in_set_sample_rate() set %u", rate);
1024     return 0;
1025 }
1026 
1027 static size_t in_get_buffer_size(const struct audio_stream *stream)
1028 {
1029     const struct submix_stream_in * const in = audio_stream_get_submix_stream_in(
1030             const_cast<struct audio_stream*>(stream));
1031     const struct submix_config * const config = &in->dev->routes[in->route_handle].config;
1032     const size_t stream_frame_size =
1033                             audio_stream_in_frame_size((const struct audio_stream_in *)stream);
1034     size_t buffer_size_frames = calculate_stream_pipe_size_in_frames(
1035         stream, config, config->buffer_period_size_frames, stream_frame_size);
1036 #if ENABLE_RESAMPLING
1037     // Scale the size of the buffer based upon the maximum number of frames that could be returned
1038     // given the ratio of output to input sample rate.
1039     buffer_size_frames = (size_t)(((float)buffer_size_frames *
1040                                    (float)config->input_sample_rate) /
1041                                   (float)config->output_sample_rate);
1042 #endif // ENABLE_RESAMPLING
1043     const size_t buffer_size_bytes = buffer_size_frames * stream_frame_size;
1044     SUBMIX_ALOGV("in_get_buffer_size() returns %zu bytes, %zu frames", buffer_size_bytes,
1045                  buffer_size_frames);
1046     return buffer_size_bytes;
1047 }
1048 
1049 static audio_channel_mask_t in_get_channels(const struct audio_stream *stream)
1050 {
1051     const struct submix_stream_in * const in = audio_stream_get_submix_stream_in(
1052             const_cast<struct audio_stream*>(stream));
1053     const audio_channel_mask_t channel_mask =
1054             in->dev->routes[in->route_handle].config.input_channel_mask;
1055     SUBMIX_ALOGV("in_get_channels() returns %x", channel_mask);
1056     return channel_mask;
1057 }
1058 
1059 static audio_format_t in_get_format(const struct audio_stream *stream)
1060 {
1061     const struct submix_stream_in * const in = audio_stream_get_submix_stream_in(
1062             const_cast<struct audio_stream*>(stream));
1063     const audio_format_t format = in->dev->routes[in->route_handle].config.common.format;
1064     SUBMIX_ALOGV("in_get_format() returns %x", format);
1065     return format;
1066 }
1067 
1068 static int in_set_format(struct audio_stream *stream, audio_format_t format)
1069 {
1070     const struct submix_stream_in * const in = audio_stream_get_submix_stream_in(stream);
1071     if (format != in->dev->routes[in->route_handle].config.common.format) {
1072         ALOGE("in_set_format(format=%x) format unsupported", format);
1073         return -ENOSYS;
1074     }
1075     SUBMIX_ALOGV("in_set_format(format=%x)", format);
1076     return 0;
1077 }
1078 
1079 static int in_standby(struct audio_stream *stream)
1080 {
1081     ALOGI("in_standby()");
1082     struct submix_stream_in * const in = audio_stream_get_submix_stream_in(stream);
1083     struct submix_audio_device * const rsxadev = in->dev;
1084 
1085     pthread_mutex_lock(&rsxadev->lock);
1086 
1087     in->input_standby = true;
1088 
1089     pthread_mutex_unlock(&rsxadev->lock);
1090 
1091     return 0;
1092 }
1093 
1094 static int in_dump(const struct audio_stream *stream, int fd)
1095 {
1096     (void)stream;
1097     (void)fd;
1098     return 0;
1099 }
1100 
1101 static int in_set_parameters(struct audio_stream *stream, const char *kvpairs)
1102 {
1103     (void)stream;
1104     (void)kvpairs;
1105     return 0;
1106 }
1107 
1108 static char * in_get_parameters(const struct audio_stream *stream,
1109                                 const char *keys)
1110 {
1111     (void)stream;
1112     (void)keys;
1113     return strdup("");
1114 }
1115 
1116 static int in_set_gain(struct audio_stream_in *stream, float gain)
1117 {
1118     (void)stream;
1119     (void)gain;
1120     return 0;
1121 }
1122 
1123 static ssize_t in_read(struct audio_stream_in *stream, void* buffer,
1124                        size_t bytes)
1125 {
1126     struct submix_stream_in * const in = audio_stream_in_get_submix_stream_in(stream);
1127     struct submix_audio_device * const rsxadev = in->dev;
1128     const size_t frame_size = audio_stream_in_frame_size(stream);
1129     const size_t frames_to_read = bytes / frame_size;
1130 
1131     SUBMIX_ALOGV("in_read bytes=%zu", bytes);
1132     pthread_mutex_lock(&rsxadev->lock);
1133 
1134     const bool output_standby = rsxadev->routes[in->route_handle].output == NULL
1135             ? true : rsxadev->routes[in->route_handle].output->output_standby;
1136     const bool output_standby_transition = (in->output_standby_rec_thr != output_standby);
1137     in->output_standby_rec_thr = output_standby;
1138 
1139     if (in->input_standby || output_standby_transition) {
1140         in->input_standby = false;
1141         // keep track of when we exit input standby (== first read == start "real recording")
1142         // or when we start recording silence, and reset projected time
1143         int rc = clock_gettime(CLOCK_MONOTONIC, &in->record_start_time);
1144         if (rc == 0) {
1145             in->read_counter_frames_since_standby = 0;
1146         }
1147     }
1148 
1149     in->read_counter_frames += frames_to_read;
1150     in->read_counter_frames_since_standby += frames_to_read;
1151     size_t remaining_frames = frames_to_read;
1152 
1153     {
1154         // about to read from audio source
1155         sp<MonoPipeReader> source = rsxadev->routes[in->route_handle].rsxSource;
1156         if (source == NULL) {
1157             in->read_error_count++;// ok if it rolls over
1158             ALOGE_IF(in->read_error_count < MAX_READ_ERROR_LOGS,
1159                     "no audio pipe yet we're trying to read! (not all errors will be logged)");
1160             pthread_mutex_unlock(&rsxadev->lock);
1161             usleep(frames_to_read * 1000000 / in_get_sample_rate(&stream->common));
1162             memset(buffer, 0, bytes);
1163             return bytes;
1164         }
1165 
1166         pthread_mutex_unlock(&rsxadev->lock);
1167 
1168         // read the data from the pipe (it's non blocking)
1169         int attempts = 0;
1170         char* buff = (char*)buffer;
1171 #if ENABLE_CHANNEL_CONVERSION
1172         // Determine whether channel conversion is required.
1173         const uint32_t input_channels = audio_channel_count_from_in_mask(
1174             rsxadev->routes[in->route_handle].config.input_channel_mask);
1175         const uint32_t output_channels = audio_channel_count_from_out_mask(
1176             rsxadev->routes[in->route_handle].config.output_channel_mask);
1177         if (input_channels != output_channels) {
1178             SUBMIX_ALOGV("in_read(): %d output channels will be converted to %d "
1179                          "input channels", output_channels, input_channels);
1180             // Only support 16-bit PCM channel conversion from mono to stereo or stereo to mono.
1181             ALOG_ASSERT(rsxadev->routes[in->route_handle].config.common.format ==
1182                     AUDIO_FORMAT_PCM_16_BIT);
1183             ALOG_ASSERT((input_channels == 1 && output_channels == 2) ||
1184                         (input_channels == 2 && output_channels == 1));
1185         }
1186 #endif // ENABLE_CHANNEL_CONVERSION
1187 
1188 #if ENABLE_RESAMPLING
1189         const uint32_t input_sample_rate = in_get_sample_rate(&stream->common);
1190         const uint32_t output_sample_rate =
1191                 rsxadev->routes[in->route_handle].config.output_sample_rate;
1192         const size_t resampler_buffer_size_frames =
1193             sizeof(rsxadev->routes[in->route_handle].resampler_buffer) /
1194                 sizeof(rsxadev->routes[in->route_handle].resampler_buffer[0]);
1195         float resampler_ratio = 1.0f;
1196         // Determine whether resampling is required.
1197         if (input_sample_rate != output_sample_rate) {
1198             resampler_ratio = (float)output_sample_rate / (float)input_sample_rate;
1199             // Only support 16-bit PCM mono resampling.
1200             // NOTE: Resampling is performed after the channel conversion step.
1201             ALOG_ASSERT(rsxadev->routes[in->route_handle].config.common.format ==
1202                     AUDIO_FORMAT_PCM_16_BIT);
1203             ALOG_ASSERT(audio_channel_count_from_in_mask(
1204                     rsxadev->routes[in->route_handle].config.input_channel_mask) == 1);
1205         }
1206 #endif // ENABLE_RESAMPLING
1207 
1208         while ((remaining_frames > 0) && (attempts < MAX_READ_ATTEMPTS)) {
1209             ssize_t frames_read = -1977;
1210             size_t read_frames = remaining_frames;
1211 #if ENABLE_RESAMPLING
1212             char* const saved_buff = buff;
1213             if (resampler_ratio != 1.0f) {
1214                 // Calculate the number of frames from the pipe that need to be read to generate
1215                 // the data for the input stream read.
1216                 const size_t frames_required_for_resampler = (size_t)(
1217                     (float)read_frames * (float)resampler_ratio);
1218                 read_frames = min(frames_required_for_resampler, resampler_buffer_size_frames);
1219                 // Read into the resampler buffer.
1220                 buff = (char*)rsxadev->routes[in->route_handle].resampler_buffer;
1221             }
1222 #endif // ENABLE_RESAMPLING
1223 #if ENABLE_CHANNEL_CONVERSION
1224             if (output_channels == 1 && input_channels == 2) {
1225                 // Need to read half the requested frames since the converted output
1226                 // data will take twice the space (mono->stereo).
1227                 read_frames /= 2;
1228             }
1229 #endif // ENABLE_CHANNEL_CONVERSION
1230 
1231             SUBMIX_ALOGV("in_read(): frames available to read %zd", source->availableToRead());
1232 
1233             frames_read = source->read(buff, read_frames);
1234 
1235             SUBMIX_ALOGV("in_read(): frames read %zd", frames_read);
1236 
1237 #if ENABLE_CHANNEL_CONVERSION
1238             // Perform in-place channel conversion.
1239             // NOTE: In the following "input stream" refers to the data returned by this function
1240             // and "output stream" refers to the data read from the pipe.
1241             if (input_channels != output_channels && frames_read > 0) {
1242                 int16_t *data = (int16_t*)buff;
1243                 if (output_channels == 2 && input_channels == 1) {
1244                     // Offset into the output stream data in samples.
1245                     ssize_t output_stream_offset = 0;
1246                     for (ssize_t input_stream_frame = 0; input_stream_frame < frames_read;
1247                          input_stream_frame++, output_stream_offset += 2) {
1248                         // Average the content from both channels.
1249                         data[input_stream_frame] = ((int32_t)data[output_stream_offset] +
1250                                                     (int32_t)data[output_stream_offset + 1]) / 2;
1251                     }
1252                 } else if (output_channels == 1 && input_channels == 2) {
1253                     // Offset into the input stream data in samples.
1254                     ssize_t input_stream_offset = (frames_read - 1) * 2;
1255                     for (ssize_t output_stream_frame = frames_read - 1; output_stream_frame >= 0;
1256                          output_stream_frame--, input_stream_offset -= 2) {
1257                         const short sample = data[output_stream_frame];
1258                         data[input_stream_offset] = sample;
1259                         data[input_stream_offset + 1] = sample;
1260                     }
1261                 }
1262             }
1263 #endif // ENABLE_CHANNEL_CONVERSION
1264 
1265 #if ENABLE_RESAMPLING
1266             if (resampler_ratio != 1.0f) {
1267                 SUBMIX_ALOGV("in_read(): resampling %zd frames", frames_read);
1268                 const int16_t * const data = (int16_t*)buff;
1269                 int16_t * const resampled_buffer = (int16_t*)saved_buff;
1270                 // Resample with *no* filtering - if the data from the ouptut stream was really
1271                 // sampled at a different rate this will result in very nasty aliasing.
1272                 const float output_stream_frames = (float)frames_read;
1273                 size_t input_stream_frame = 0;
1274                 for (float output_stream_frame = 0.0f;
1275                      output_stream_frame < output_stream_frames &&
1276                      input_stream_frame < remaining_frames;
1277                      output_stream_frame += resampler_ratio, input_stream_frame++) {
1278                     resampled_buffer[input_stream_frame] = data[(size_t)output_stream_frame];
1279                 }
1280                 ALOG_ASSERT(input_stream_frame <= (ssize_t)resampler_buffer_size_frames);
1281                 SUBMIX_ALOGV("in_read(): resampler produced %zd frames", input_stream_frame);
1282                 frames_read = input_stream_frame;
1283                 buff = saved_buff;
1284             }
1285 #endif // ENABLE_RESAMPLING
1286 
1287             if (frames_read > 0) {
1288 #if LOG_STREAMS_TO_FILES
1289                 if (in->log_fd >= 0) write(in->log_fd, buff, frames_read * frame_size);
1290 #endif // LOG_STREAMS_TO_FILES
1291 
1292                 remaining_frames -= frames_read;
1293                 buff += frames_read * frame_size;
1294                 SUBMIX_ALOGV("  in_read (att=%d) got %zd frames, remaining=%zu",
1295                              attempts, frames_read, remaining_frames);
1296             } else {
1297                 attempts++;
1298                 SUBMIX_ALOGE("  in_read read returned %zd", frames_read);
1299                 usleep(READ_ATTEMPT_SLEEP_MS * 1000);
1300             }
1301         }
1302         // done using the source
1303         pthread_mutex_lock(&rsxadev->lock);
1304         source.clear();
1305         pthread_mutex_unlock(&rsxadev->lock);
1306     }
1307 
1308     if (remaining_frames > 0) {
1309         const size_t remaining_bytes = remaining_frames * frame_size;
1310         SUBMIX_ALOGV("  clearing remaining_frames = %zu", remaining_frames);
1311         memset(((char*)buffer)+ bytes - remaining_bytes, 0, remaining_bytes);
1312     }
1313 
1314     // compute how much we need to sleep after reading the data by comparing the wall clock with
1315     //   the projected time at which we should return.
1316     struct timespec time_after_read;// wall clock after reading from the pipe
1317     struct timespec record_duration;// observed record duration
1318     int rc = clock_gettime(CLOCK_MONOTONIC, &time_after_read);
1319     const uint32_t sample_rate = in_get_sample_rate(&stream->common);
1320     if (rc == 0) {
1321         // for how long have we been recording?
1322         record_duration.tv_sec  = time_after_read.tv_sec - in->record_start_time.tv_sec;
1323         record_duration.tv_nsec = time_after_read.tv_nsec - in->record_start_time.tv_nsec;
1324         if (record_duration.tv_nsec < 0) {
1325             record_duration.tv_sec--;
1326             record_duration.tv_nsec += 1000000000;
1327         }
1328 
1329         // read_counter_frames_since_standby contains the number of frames that have been read since
1330         // the beginning of recording (including this call): it's converted to usec and compared to
1331         // how long we've been recording for, which gives us how long we must wait to sync the
1332         // projected recording time, and the observed recording time.
1333         long projected_vs_observed_offset_us =
1334                 ((int64_t)(in->read_counter_frames_since_standby
1335                             - (record_duration.tv_sec*sample_rate)))
1336                         * 1000000 / sample_rate
1337                 - (record_duration.tv_nsec / 1000);
1338 
1339         SUBMIX_ALOGV("  record duration %5lds %3ldms, will wait: %7ldus",
1340                 record_duration.tv_sec, record_duration.tv_nsec/1000000,
1341                 projected_vs_observed_offset_us);
1342         if (projected_vs_observed_offset_us > 0) {
1343             usleep(projected_vs_observed_offset_us);
1344         }
1345     }
1346 
1347     SUBMIX_ALOGV("in_read returns %zu", bytes);
1348     return bytes;
1349 
1350 }
1351 
1352 static uint32_t in_get_input_frames_lost(struct audio_stream_in *stream)
1353 {
1354     (void)stream;
1355     return 0;
1356 }
1357 
1358 static int in_get_capture_position(const struct audio_stream_in *stream,
1359                                    int64_t *frames, int64_t *time)
1360 {
1361     if (stream == NULL || frames == NULL || time == NULL) {
1362         return -EINVAL;
1363     }
1364 
1365     struct submix_stream_in * const in = audio_stream_in_get_submix_stream_in(
1366             (struct audio_stream_in*)stream);
1367     struct submix_audio_device * const rsxadev = in->dev;
1368 
1369     pthread_mutex_lock(&rsxadev->lock);
1370     sp<MonoPipeReader> source = rsxadev->routes[in->route_handle].rsxSource;
1371     if (source == NULL) {
1372         ALOGW("%s called on released input", __FUNCTION__);
1373         pthread_mutex_unlock(&rsxadev->lock);
1374         return -ENODEV;
1375     }
1376     *frames = in->read_counter_frames;
1377     const ssize_t frames_in_pipe = source->availableToRead();
1378     pthread_mutex_unlock(&rsxadev->lock);
1379     if (frames_in_pipe > 0) {
1380         *frames += frames_in_pipe;
1381     }
1382 
1383     struct timespec timestamp;
1384     clock_gettime(CLOCK_MONOTONIC, &timestamp);
1385     *time = timestamp.tv_sec * 1000000000LL + timestamp.tv_nsec;
1386     return 0;
1387 }
1388 
1389 static int in_add_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1390 {
1391     (void)stream;
1392     (void)effect;
1393     return 0;
1394 }
1395 
1396 static int in_remove_audio_effect(const struct audio_stream *stream, effect_handle_t effect)
1397 {
1398     (void)stream;
1399     (void)effect;
1400     return 0;
1401 }
1402 
1403 static int adev_open_output_stream(struct audio_hw_device *dev,
1404                                    audio_io_handle_t handle,
1405                                    audio_devices_t devices,
1406                                    audio_output_flags_t flags,
1407                                    struct audio_config *config,
1408                                    struct audio_stream_out **stream_out,
1409                                    const char *address)
1410 {
1411     struct submix_audio_device * const rsxadev = audio_hw_device_get_submix_audio_device(dev);
1412     ALOGD("adev_open_output_stream(address=%s)", address);
1413     struct submix_stream_out *out;
1414     bool force_pipe_creation = false;
1415     (void)handle;
1416     (void)devices;
1417     (void)flags;
1418 
1419     *stream_out = NULL;
1420 
1421     // Make sure it's possible to open the device given the current audio config.
1422     submix_sanitize_config(config, false);
1423 
1424     int route_idx = -1;
1425 
1426     pthread_mutex_lock(&rsxadev->lock);
1427 
1428     status_t res = submix_get_route_idx_for_address_l(rsxadev, address, &route_idx);
1429     if (res != OK) {
1430         ALOGE("Error %d looking for address=%s in adev_open_output_stream", res, address);
1431         pthread_mutex_unlock(&rsxadev->lock);
1432         return res;
1433     }
1434 
1435     if (!submix_open_validate_l(rsxadev, route_idx, config, false)) {
1436         ALOGE("adev_open_output_stream(): Unable to open output stream for address %s", address);
1437         pthread_mutex_unlock(&rsxadev->lock);
1438         return -EINVAL;
1439     }
1440 
1441     out = (struct submix_stream_out *)calloc(1, sizeof(struct submix_stream_out));
1442     if (!out) {
1443         pthread_mutex_unlock(&rsxadev->lock);
1444         return -ENOMEM;
1445     }
1446 
1447     // Initialize the function pointer tables (v-tables).
1448     out->stream.common.get_sample_rate = out_get_sample_rate;
1449     out->stream.common.set_sample_rate = out_set_sample_rate;
1450     out->stream.common.get_buffer_size = out_get_buffer_size;
1451     out->stream.common.get_channels = out_get_channels;
1452     out->stream.common.get_format = out_get_format;
1453     out->stream.common.set_format = out_set_format;
1454     out->stream.common.standby = out_standby;
1455     out->stream.common.dump = out_dump;
1456     out->stream.common.set_parameters = out_set_parameters;
1457     out->stream.common.get_parameters = out_get_parameters;
1458     out->stream.common.add_audio_effect = out_add_audio_effect;
1459     out->stream.common.remove_audio_effect = out_remove_audio_effect;
1460     out->stream.get_latency = out_get_latency;
1461     out->stream.set_volume = out_set_volume;
1462     out->stream.write = out_write;
1463     out->stream.get_render_position = out_get_render_position;
1464     out->stream.get_next_write_timestamp = out_get_next_write_timestamp;
1465     out->stream.get_presentation_position = out_get_presentation_position;
1466 
1467 #if ENABLE_RESAMPLING
1468     // Recreate the pipe with the correct sample rate so that MonoPipe.write() rate limits
1469     // writes correctly.
1470     force_pipe_creation = rsxadev->routes[route_idx].config.common.sample_rate
1471             != config->sample_rate;
1472 #endif // ENABLE_RESAMPLING
1473 
1474     // If the sink has been shutdown or pipe recreation is forced (see above), delete the pipe so
1475     // that it's recreated.
1476     if ((rsxadev->routes[route_idx].rsxSink != NULL
1477             && rsxadev->routes[route_idx].rsxSink->isShutdown()) || force_pipe_creation) {
1478         submix_audio_device_release_pipe_l(rsxadev, route_idx);
1479     }
1480 
1481     // Store a pointer to the device from the output stream.
1482     out->dev = rsxadev;
1483     // Initialize the pipe.
1484     ALOGV("adev_open_output_stream(): about to create pipe at index %d", route_idx);
1485     submix_audio_device_create_pipe_l(rsxadev, config, DEFAULT_PIPE_SIZE_IN_FRAMES,
1486             DEFAULT_PIPE_PERIOD_COUNT, NULL, out, address, route_idx);
1487 #if LOG_STREAMS_TO_FILES
1488     out->log_fd = open(LOG_STREAM_OUT_FILENAME, O_CREAT | O_TRUNC | O_WRONLY,
1489                        LOG_STREAM_FILE_PERMISSIONS);
1490     ALOGE_IF(out->log_fd < 0, "adev_open_output_stream(): log file open failed %s",
1491              strerror(errno));
1492     ALOGV("adev_open_output_stream(): log_fd = %d", out->log_fd);
1493 #endif // LOG_STREAMS_TO_FILES
1494     // Return the output stream.
1495     *stream_out = &out->stream;
1496 
1497     pthread_mutex_unlock(&rsxadev->lock);
1498     return 0;
1499 }
1500 
1501 static void adev_close_output_stream(struct audio_hw_device *dev,
1502                                      struct audio_stream_out *stream)
1503 {
1504     struct submix_audio_device * rsxadev = audio_hw_device_get_submix_audio_device(
1505                     const_cast<struct audio_hw_device*>(dev));
1506     struct submix_stream_out * const out = audio_stream_out_get_submix_stream_out(stream);
1507 
1508     pthread_mutex_lock(&rsxadev->lock);
1509     ALOGD("adev_close_output_stream() addr = %s", rsxadev->routes[out->route_handle].address);
1510     submix_audio_device_destroy_pipe_l(audio_hw_device_get_submix_audio_device(dev), NULL, out);
1511 #if LOG_STREAMS_TO_FILES
1512     if (out->log_fd >= 0) close(out->log_fd);
1513 #endif // LOG_STREAMS_TO_FILES
1514 
1515     pthread_mutex_unlock(&rsxadev->lock);
1516     free(out);
1517 }
1518 
1519 static int adev_set_parameters(struct audio_hw_device *dev, const char *kvpairs)
1520 {
1521     (void)dev;
1522     (void)kvpairs;
1523     return -ENOSYS;
1524 }
1525 
1526 static char * adev_get_parameters(const struct audio_hw_device *dev,
1527                                   const char *keys)
1528 {
1529     (void)dev;
1530     (void)keys;
1531     return strdup("");;
1532 }
1533 
1534 static int adev_init_check(const struct audio_hw_device *dev)
1535 {
1536     ALOGI("adev_init_check()");
1537     (void)dev;
1538     return 0;
1539 }
1540 
1541 static int adev_set_voice_volume(struct audio_hw_device *dev, float volume)
1542 {
1543     (void)dev;
1544     (void)volume;
1545     return -ENOSYS;
1546 }
1547 
1548 static int adev_set_master_volume(struct audio_hw_device *dev, float volume)
1549 {
1550     (void)dev;
1551     (void)volume;
1552     return -ENOSYS;
1553 }
1554 
1555 static int adev_get_master_volume(struct audio_hw_device *dev, float *volume)
1556 {
1557     (void)dev;
1558     (void)volume;
1559     return -ENOSYS;
1560 }
1561 
1562 static int adev_set_master_mute(struct audio_hw_device *dev, bool muted)
1563 {
1564     (void)dev;
1565     (void)muted;
1566     return -ENOSYS;
1567 }
1568 
1569 static int adev_get_master_mute(struct audio_hw_device *dev, bool *muted)
1570 {
1571     (void)dev;
1572     (void)muted;
1573     return -ENOSYS;
1574 }
1575 
1576 static int adev_set_mode(struct audio_hw_device *dev, audio_mode_t mode)
1577 {
1578     (void)dev;
1579     (void)mode;
1580     return 0;
1581 }
1582 
1583 static int adev_set_mic_mute(struct audio_hw_device *dev, bool state)
1584 {
1585     (void)dev;
1586     (void)state;
1587     return -ENOSYS;
1588 }
1589 
1590 static int adev_get_mic_mute(const struct audio_hw_device *dev, bool *state)
1591 {
1592     (void)dev;
1593     (void)state;
1594     return -ENOSYS;
1595 }
1596 
1597 static size_t adev_get_input_buffer_size(const struct audio_hw_device *dev,
1598                                          const struct audio_config *config)
1599 {
1600     if (audio_is_linear_pcm(config->format)) {
1601         size_t max_buffer_period_size_frames = 0;
1602         struct submix_audio_device * rsxadev = audio_hw_device_get_submix_audio_device(
1603                 const_cast<struct audio_hw_device*>(dev));
1604         // look for the largest buffer period size
1605         for (int i = 0 ; i < MAX_ROUTES ; i++) {
1606             if (rsxadev->routes[i].config.buffer_period_size_frames > max_buffer_period_size_frames)
1607             {
1608                 max_buffer_period_size_frames = rsxadev->routes[i].config.buffer_period_size_frames;
1609             }
1610         }
1611         const size_t frame_size_in_bytes = audio_channel_count_from_in_mask(config->channel_mask) *
1612                 audio_bytes_per_sample(config->format);
1613         if (max_buffer_period_size_frames == 0) {
1614             max_buffer_period_size_frames = DEFAULT_PIPE_SIZE_IN_FRAMES;
1615         }
1616         const size_t buffer_size = max_buffer_period_size_frames * frame_size_in_bytes;
1617         SUBMIX_ALOGV("adev_get_input_buffer_size() returns %zu bytes, %zu frames",
1618                  buffer_size, max_buffer_period_size_frames);
1619         return buffer_size;
1620     }
1621     return 0;
1622 }
1623 
1624 static int adev_open_input_stream(struct audio_hw_device *dev,
1625                                   audio_io_handle_t handle,
1626                                   audio_devices_t devices,
1627                                   struct audio_config *config,
1628                                   struct audio_stream_in **stream_in,
1629                                   audio_input_flags_t flags __unused,
1630                                   const char *address,
1631                                   audio_source_t source __unused)
1632 {
1633     struct submix_audio_device *rsxadev = audio_hw_device_get_submix_audio_device(dev);
1634     struct submix_stream_in *in;
1635     ALOGD("adev_open_input_stream(addr=%s)", address);
1636     (void)handle;
1637     (void)devices;
1638 
1639     *stream_in = NULL;
1640 
1641     // Do we already have a route for this address
1642     int route_idx = -1;
1643 
1644     pthread_mutex_lock(&rsxadev->lock);
1645 
1646     status_t res = submix_get_route_idx_for_address_l(rsxadev, address, &route_idx);
1647     if (res != OK) {
1648         ALOGE("Error %d looking for address=%s in adev_open_input_stream", res, address);
1649         pthread_mutex_unlock(&rsxadev->lock);
1650         return res;
1651     }
1652 
1653     // Make sure it's possible to open the device given the current audio config.
1654     submix_sanitize_config(config, true);
1655     if (!submix_open_validate_l(rsxadev, route_idx, config, true)) {
1656         ALOGE("adev_open_input_stream(): Unable to open input stream.");
1657         pthread_mutex_unlock(&rsxadev->lock);
1658         return -EINVAL;
1659     }
1660 
1661 #if ENABLE_LEGACY_INPUT_OPEN
1662     in = rsxadev->routes[route_idx].input;
1663     if (in) {
1664         in->ref_count++;
1665         sp<MonoPipe> sink = rsxadev->routes[route_idx].rsxSink;
1666         ALOG_ASSERT(sink != NULL);
1667         // If the sink has been shutdown, delete the pipe.
1668         if (sink != NULL) {
1669             if (sink->isShutdown()) {
1670                 ALOGD(" Non-NULL shut down sink when opening input stream, releasing, refcount=%d",
1671                         in->ref_count);
1672                 submix_audio_device_release_pipe_l(rsxadev, in->route_handle);
1673             } else {
1674                 ALOGD(" Non-NULL sink when opening input stream, refcount=%d", in->ref_count);
1675             }
1676         } else {
1677             ALOGE("NULL sink when opening input stream, refcount=%d", in->ref_count);
1678         }
1679     }
1680 #else
1681     in = NULL;
1682 #endif // ENABLE_LEGACY_INPUT_OPEN
1683 
1684     if (!in) {
1685         in = (struct submix_stream_in *)calloc(1, sizeof(struct submix_stream_in));
1686         if (!in) return -ENOMEM;
1687 #if ENABLE_LEGACY_INPUT_OPEN
1688         in->ref_count = 1;
1689 #endif
1690 
1691         // Initialize the function pointer tables (v-tables).
1692         in->stream.common.get_sample_rate = in_get_sample_rate;
1693         in->stream.common.set_sample_rate = in_set_sample_rate;
1694         in->stream.common.get_buffer_size = in_get_buffer_size;
1695         in->stream.common.get_channels = in_get_channels;
1696         in->stream.common.get_format = in_get_format;
1697         in->stream.common.set_format = in_set_format;
1698         in->stream.common.standby = in_standby;
1699         in->stream.common.dump = in_dump;
1700         in->stream.common.set_parameters = in_set_parameters;
1701         in->stream.common.get_parameters = in_get_parameters;
1702         in->stream.common.add_audio_effect = in_add_audio_effect;
1703         in->stream.common.remove_audio_effect = in_remove_audio_effect;
1704         in->stream.set_gain = in_set_gain;
1705         in->stream.read = in_read;
1706         in->stream.get_input_frames_lost = in_get_input_frames_lost;
1707         in->stream.get_capture_position = in_get_capture_position;
1708 
1709         in->dev = rsxadev;
1710 #if LOG_STREAMS_TO_FILES
1711         in->log_fd = -1;
1712 #endif
1713     }
1714 
1715     // Initialize the input stream.
1716     in->read_counter_frames = 0;
1717     in->read_counter_frames_since_standby = 0;
1718     in->input_standby = true;
1719     if (rsxadev->routes[route_idx].output != NULL) {
1720         in->output_standby_rec_thr = rsxadev->routes[route_idx].output->output_standby;
1721     } else {
1722         in->output_standby_rec_thr = true;
1723     }
1724 
1725     in->read_error_count = 0;
1726     // Initialize the pipe.
1727     ALOGV("adev_open_input_stream(): about to create pipe");
1728     submix_audio_device_create_pipe_l(rsxadev, config, DEFAULT_PIPE_SIZE_IN_FRAMES,
1729                                     DEFAULT_PIPE_PERIOD_COUNT, in, NULL, address, route_idx);
1730 
1731     sp <MonoPipe> sink = rsxadev->routes[route_idx].rsxSink;
1732     if (sink != NULL) {
1733         sink->shutdown(false);
1734     }
1735 
1736 #if LOG_STREAMS_TO_FILES
1737     if (in->log_fd >= 0) close(in->log_fd);
1738     in->log_fd = open(LOG_STREAM_IN_FILENAME, O_CREAT | O_TRUNC | O_WRONLY,
1739                       LOG_STREAM_FILE_PERMISSIONS);
1740     ALOGE_IF(in->log_fd < 0, "adev_open_input_stream(): log file open failed %s",
1741              strerror(errno));
1742     ALOGV("adev_open_input_stream(): log_fd = %d", in->log_fd);
1743 #endif // LOG_STREAMS_TO_FILES
1744     // Return the input stream.
1745     *stream_in = &in->stream;
1746 
1747     pthread_mutex_unlock(&rsxadev->lock);
1748     return 0;
1749 }
1750 
1751 static void adev_close_input_stream(struct audio_hw_device *dev,
1752                                     struct audio_stream_in *stream)
1753 {
1754     struct submix_audio_device * const rsxadev = audio_hw_device_get_submix_audio_device(dev);
1755 
1756     struct submix_stream_in * const in = audio_stream_in_get_submix_stream_in(stream);
1757     ALOGD("adev_close_input_stream()");
1758     pthread_mutex_lock(&rsxadev->lock);
1759     submix_audio_device_destroy_pipe_l(rsxadev, in, NULL);
1760 #if LOG_STREAMS_TO_FILES
1761     if (in->log_fd >= 0) close(in->log_fd);
1762 #endif // LOG_STREAMS_TO_FILES
1763 #if ENABLE_LEGACY_INPUT_OPEN
1764     if (in->ref_count == 0) free(in);
1765 #else
1766     free(in);
1767 #endif // ENABLE_LEGACY_INPUT_OPEN
1768 
1769     pthread_mutex_unlock(&rsxadev->lock);
1770 }
1771 
1772 static int adev_dump(const audio_hw_device_t *device, int fd)
1773 {
1774     const struct submix_audio_device * rsxadev = //audio_hw_device_get_submix_audio_device(device);
1775             reinterpret_cast<const struct submix_audio_device *>(
1776                     reinterpret_cast<const uint8_t *>(device) -
1777                             offsetof(struct submix_audio_device, device));
1778     char msg[100];
1779     int n = snprintf(msg, sizeof(msg), "\nReroute submix audio module:\n");
1780     write(fd, &msg, n);
1781     for (int i=0 ; i < MAX_ROUTES ; i++) {
1782 #if ENABLE_RESAMPLING
1783         n = snprintf(msg, sizeof(msg), " route[%d] rate in=%d out=%d, addr=[%s]\n", i,
1784                 rsxadev->routes[i].config.input_sample_rate,
1785                 rsxadev->routes[i].config.output_sample_rate,
1786                 rsxadev->routes[i].address);
1787 #else
1788         n = snprintf(msg, sizeof(msg), " route[%d], rate=%d addr=[%s]\n", i,
1789                 rsxadev->routes[i].config.common.sample_rate,
1790                 rsxadev->routes[i].address);
1791 #endif
1792         write(fd, &msg, n);
1793     }
1794     return 0;
1795 }
1796 
1797 static int adev_close(hw_device_t *device)
1798 {
1799     ALOGI("adev_close()");
1800     free(device);
1801     return 0;
1802 }
1803 
1804 static int adev_open(const hw_module_t* module, const char* name,
1805                      hw_device_t** device)
1806 {
1807     ALOGI("adev_open(name=%s)", name);
1808     struct submix_audio_device *rsxadev;
1809 
1810     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
1811         return -EINVAL;
1812 
1813     rsxadev = (submix_audio_device*) calloc(1, sizeof(struct submix_audio_device));
1814     if (!rsxadev)
1815         return -ENOMEM;
1816 
1817     rsxadev->device.common.tag = HARDWARE_DEVICE_TAG;
1818     rsxadev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0;
1819     rsxadev->device.common.module = (struct hw_module_t *) module;
1820     rsxadev->device.common.close = adev_close;
1821 
1822     rsxadev->device.init_check = adev_init_check;
1823     rsxadev->device.set_voice_volume = adev_set_voice_volume;
1824     rsxadev->device.set_master_volume = adev_set_master_volume;
1825     rsxadev->device.get_master_volume = adev_get_master_volume;
1826     rsxadev->device.set_master_mute = adev_set_master_mute;
1827     rsxadev->device.get_master_mute = adev_get_master_mute;
1828     rsxadev->device.set_mode = adev_set_mode;
1829     rsxadev->device.set_mic_mute = adev_set_mic_mute;
1830     rsxadev->device.get_mic_mute = adev_get_mic_mute;
1831     rsxadev->device.set_parameters = adev_set_parameters;
1832     rsxadev->device.get_parameters = adev_get_parameters;
1833     rsxadev->device.get_input_buffer_size = adev_get_input_buffer_size;
1834     rsxadev->device.open_output_stream = adev_open_output_stream;
1835     rsxadev->device.close_output_stream = adev_close_output_stream;
1836     rsxadev->device.open_input_stream = adev_open_input_stream;
1837     rsxadev->device.close_input_stream = adev_close_input_stream;
1838     rsxadev->device.dump = adev_dump;
1839 
1840     for (int i=0 ; i < MAX_ROUTES ; i++) {
1841             memset(&rsxadev->routes[i], 0, sizeof(route_config));
1842             strcpy(rsxadev->routes[i].address, "");
1843         }
1844 
1845     *device = &rsxadev->device.common;
1846 
1847     return 0;
1848 }
1849 
1850 static struct hw_module_methods_t hal_module_methods = {
1851     /* open */ adev_open,
1852 };
1853 
1854 struct audio_module HAL_MODULE_INFO_SYM = {
1855     /* common */ {
1856         /* tag */                HARDWARE_MODULE_TAG,
1857         /* module_api_version */ AUDIO_MODULE_API_VERSION_0_1,
1858         /* hal_api_version */    HARDWARE_HAL_API_VERSION,
1859         /* id */                 AUDIO_HARDWARE_MODULE_ID,
1860         /* name */               "Wifi Display audio HAL",
1861         /* author */             "The Android Open Source Project",
1862         /* methods */            &hal_module_methods,
1863         /* dso */                NULL,
1864         /* reserved */           { 0 },
1865     },
1866 };
1867 
1868 } //namespace android
1869 
1870 } //extern "C"
1871