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