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