Update broken references to image assets
[chromium-blink-merge.git] / media / audio / audio_input_controller.h
blob6f14394d0b397e4ed3a43df6ec3c5302d92d7964
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef MEDIA_AUDIO_AUDIO_INPUT_CONTROLLER_H_
6 #define MEDIA_AUDIO_AUDIO_INPUT_CONTROLLER_H_
8 #include <string>
9 #include "base/atomicops.h"
10 #include "base/callback.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/synchronization/lock.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/threading/thread.h"
16 #include "base/timer/timer.h"
17 #include "media/audio/audio_io.h"
18 #include "media/audio/audio_manager_base.h"
19 #include "media/audio/audio_parameters.h"
20 #include "media/base/audio_bus.h"
22 // An AudioInputController controls an AudioInputStream and records data
23 // from this input stream. The two main methods are Record() and Close() and
24 // they are both executed on the audio thread which is injected by the two
25 // alternative factory methods, Create() or CreateLowLatency().
27 // All public methods of AudioInputController are non-blocking.
29 // Here is a state diagram for the AudioInputController:
31 // .--> [ Closed / Error ] <--.
32 // | |
33 // | |
34 // [ Created ] ----------> [ Recording ]
35 // ^
36 // |
37 // *[ Empty ]
39 // * Initial state
41 // State sequences (assuming low-latency):
43 // [Creating Thread] [Audio Thread]
45 // User AudioInputController EventHandler
46 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
47 // CrateLowLatency() ==> DoCreate()
48 // AudioManager::MakeAudioInputStream()
49 // AudioInputStream::Open()
50 // .- - - - - - - - - - - - -> OnError()
51 // create the data timer
52 // .-------------------------> OnCreated()
53 // kCreated
54 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
55 // Record() ==> DoRecord()
56 // AudioInputStream::Start()
57 // .-------------------------> OnRecording()
58 // start the data timer
59 // kRecording
60 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
61 // Close() ==> DoClose()
62 // delete the data timer
63 // state_ = kClosed
64 // AudioInputStream::Stop()
65 // AudioInputStream::Close()
66 // SyncWriter::Close()
67 // Closure::Run() <-----------------.
68 // (closure-task)
70 // The audio thread itself is owned by the AudioManager that the
71 // AudioInputController holds a reference to. When performing tasks on the
72 // audio thread, the controller must not add or release references to the
73 // AudioManager or itself (since it in turn holds a reference to the manager).
75 namespace media {
77 // Only do power monitoring for non-mobile platforms to save resources.
78 #if !defined(OS_ANDROID) && !defined(OS_IOS)
79 #define AUDIO_POWER_MONITORING
80 #endif
82 class UserInputMonitor;
84 class MEDIA_EXPORT AudioInputController
85 : public base::RefCountedThreadSafe<AudioInputController>,
86 public AudioInputStream::AudioInputCallback {
87 public:
89 // Error codes to make native loggin more clear. These error codes are added
90 // to generic error strings to provide a higher degree of details.
91 // Changing these values can lead to problems when matching native debug
92 // logs with the actual cause of error.
93 enum ErrorCode {
94 // An unspecified error occured.
95 UNKNOWN_ERROR = 0,
97 // Failed to create an audio input stream.
98 STREAM_CREATE_ERROR, // = 1
100 // Failed to open an audio input stream.
101 STREAM_OPEN_ERROR, // = 2
103 // Native input stream reports an error. Exact reason differs between
104 // platforms.
105 STREAM_ERROR, // = 3
107 // This can happen if a capture device has been removed or disabled.
108 NO_DATA_ERROR, // = 4
111 // An event handler that receives events from the AudioInputController. The
112 // following methods are all called on the audio thread.
113 class MEDIA_EXPORT EventHandler {
114 public:
115 virtual void OnCreated(AudioInputController* controller) = 0;
116 virtual void OnRecording(AudioInputController* controller) = 0;
117 virtual void OnError(AudioInputController* controller,
118 ErrorCode error_code) = 0;
119 virtual void OnData(AudioInputController* controller,
120 const AudioBus* data) = 0;
121 virtual void OnLog(AudioInputController* controller,
122 const std::string& message) = 0;
124 protected:
125 virtual ~EventHandler() {}
128 // A synchronous writer interface used by AudioInputController for
129 // synchronous writing.
130 class SyncWriter {
131 public:
132 virtual ~SyncWriter() {}
134 // Write certain amount of data from |data|.
135 virtual void Write(const AudioBus* data,
136 double volume,
137 bool key_pressed,
138 uint32 hardware_delay_bytes) = 0;
140 // Close this synchronous writer.
141 virtual void Close() = 0;
144 // AudioInputController::Create() can use the currently registered Factory
145 // to create the AudioInputController. Factory is intended for testing only.
146 // |user_input_monitor| is used for typing detection and can be NULL.
147 class Factory {
148 public:
149 virtual AudioInputController* Create(
150 AudioManager* audio_manager,
151 EventHandler* event_handler,
152 AudioParameters params,
153 UserInputMonitor* user_input_monitor) = 0;
155 protected:
156 virtual ~Factory() {}
159 // Factory method for creating an AudioInputController.
160 // The audio device will be created on the audio thread, and when that is
161 // done, the event handler will receive an OnCreated() call from that same
162 // thread. |device_id| is the unique ID of the audio device to be opened.
163 // |user_input_monitor| is used for typing detection and can be NULL.
164 static scoped_refptr<AudioInputController> Create(
165 AudioManager* audio_manager,
166 EventHandler* event_handler,
167 const AudioParameters& params,
168 const std::string& device_id,
169 UserInputMonitor* user_input_monitor);
171 // Sets the factory used by the static method Create(). AudioInputController
172 // does not take ownership of |factory|. A value of NULL results in an
173 // AudioInputController being created directly.
174 static void set_factory_for_testing(Factory* factory) { factory_ = factory; }
175 AudioInputStream* stream_for_testing() { return stream_; }
177 // Factory method for creating an AudioInputController for low-latency mode.
178 // The audio device will be created on the audio thread, and when that is
179 // done, the event handler will receive an OnCreated() call from that same
180 // thread. |user_input_monitor| is used for typing detection and can be NULL.
181 static scoped_refptr<AudioInputController> CreateLowLatency(
182 AudioManager* audio_manager,
183 EventHandler* event_handler,
184 const AudioParameters& params,
185 const std::string& device_id,
186 // External synchronous writer for audio controller.
187 SyncWriter* sync_writer,
188 UserInputMonitor* user_input_monitor,
189 const bool agc_is_enabled);
191 // Factory method for creating an AudioInputController with an existing
192 // |stream| for low-latency mode, taking ownership of |stream|. The stream
193 // will be opened on the audio thread, and when that is done, the event
194 // handler will receive an OnCreated() call from that same thread.
195 // |user_input_monitor| is used for typing detection and can be NULL.
196 static scoped_refptr<AudioInputController> CreateForStream(
197 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
198 EventHandler* event_handler,
199 AudioInputStream* stream,
200 // External synchronous writer for audio controller.
201 SyncWriter* sync_writer,
202 UserInputMonitor* user_input_monitor);
204 // Starts recording using the created audio input stream.
205 // This method is called on the creator thread.
206 virtual void Record();
208 // Closes the audio input stream. The state is changed and the resources
209 // are freed on the audio thread. |closed_task| is then executed on the thread
210 // that called Close().
211 // Callbacks (EventHandler and SyncWriter) must exist until |closed_task|
212 // is called.
213 // It is safe to call this method more than once. Calls after the first one
214 // will have no effect.
215 // This method trampolines to the audio thread.
216 virtual void Close(const base::Closure& closed_task);
218 // Sets the capture volume of the input stream. The value 0.0 corresponds
219 // to muted and 1.0 to maximum volume.
220 virtual void SetVolume(double volume);
222 // AudioInputCallback implementation. Threading details depends on the
223 // device-specific implementation.
224 void OnData(AudioInputStream* stream,
225 const AudioBus* source,
226 uint32 hardware_delay_bytes,
227 double volume) override;
228 void OnError(AudioInputStream* stream) override;
230 bool SharedMemoryAndSyncSocketMode() const { return sync_writer_ != NULL; }
232 protected:
233 friend class base::RefCountedThreadSafe<AudioInputController>;
235 // Internal state of the source.
236 enum State {
237 CREATED,
238 RECORDING,
239 CLOSED
242 #if defined(AUDIO_POWER_MONITORING)
243 // Used to log a silence report (see OnData).
244 // Elements in this enum should not be deleted or rearranged; the only
245 // permitted operation is to add new elements before SILENCE_STATE_MAX and
246 // update SILENCE_STATE_MAX.
247 // Possible silence state transitions:
248 // SILENCE_STATE_AUDIO_AND_SILENCE
249 // ^ ^
250 // SILENCE_STATE_ONLY_AUDIO SILENCE_STATE_ONLY_SILENCE
251 // ^ ^
252 // SILENCE_STATE_NO_MEASUREMENT
253 enum SilenceState {
254 SILENCE_STATE_NO_MEASUREMENT = 0,
255 SILENCE_STATE_ONLY_AUDIO = 1,
256 SILENCE_STATE_ONLY_SILENCE = 2,
257 SILENCE_STATE_AUDIO_AND_SILENCE = 3,
258 SILENCE_STATE_MAX = SILENCE_STATE_AUDIO_AND_SILENCE
260 #endif
262 AudioInputController(EventHandler* handler,
263 SyncWriter* sync_writer,
264 UserInputMonitor* user_input_monitor,
265 const bool agc_is_enabled);
266 ~AudioInputController() override;
268 // Methods called on the audio thread (owned by the AudioManager).
269 void DoCreate(AudioManager* audio_manager,
270 const AudioParameters& params,
271 const std::string& device_id);
272 void DoCreateForLowLatency(AudioManager* audio_manager,
273 const AudioParameters& params,
274 const std::string& device_id);
275 void DoCreateForStream(AudioInputStream* stream_to_control);
276 void DoRecord();
277 void DoClose();
278 void DoReportError();
279 void DoSetVolume(double volume);
280 void DoOnData(scoped_ptr<AudioBus> data);
281 void DoLogAudioLevels(float level_dbfs, int microphone_volume_percent);
283 // Method to check if we get recorded data after a stream was started,
284 // and log the result to UMA.
285 void FirstCheckForNoData();
287 // Method which ensures that OnError() is triggered when data recording
288 // times out. Called on the audio thread.
289 void DoCheckForNoData();
291 // Helper method that stops, closes, and NULL:s |*stream_|.
292 void DoStopCloseAndClearStream();
294 void SetDataIsActive(bool enabled);
295 bool GetDataIsActive();
297 #if defined(AUDIO_POWER_MONITORING)
298 // Updates the silence state, see enum SilenceState above for state
299 // transitions.
300 void UpdateSilenceState(bool silence);
302 // Logs the silence state as UMA stat.
303 void LogSilenceState(SilenceState value);
304 #endif
306 // Gives access to the task runner of the creating thread.
307 scoped_refptr<base::SingleThreadTaskRunner> creator_task_runner_;
309 // The task runner of audio-manager thread that this object runs on.
310 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
312 // Contains the AudioInputController::EventHandler which receives state
313 // notifications from this class.
314 EventHandler* handler_;
316 // Pointer to the audio input stream object.
317 AudioInputStream* stream_;
319 // |no_data_timer_| is used to call OnError() when we stop receiving
320 // OnData() calls. This can occur when an audio input device is unplugged
321 // whilst recording on Windows.
322 // See http://crbug.com/79936 for details.
323 // This member is only touched by the audio thread.
324 scoped_ptr<base::Timer> no_data_timer_;
326 // This flag is used to signal that we are receiving OnData() calls, i.e,
327 // that data is active. It can be touched by the audio thread and by the
328 // low-level audio thread which calls OnData(). E.g. on Windows, the
329 // low-level audio thread is called wasapi_capture_thread.
330 base::subtle::Atomic32 data_is_active_;
332 // |state_| is written on the audio thread and is read on the hardware audio
333 // thread. These operations need to be locked. But lock is not required for
334 // reading on the audio input controller thread.
335 State state_;
337 base::Lock lock_;
339 // SyncWriter is used only in low-latency mode for synchronous writing.
340 SyncWriter* sync_writer_;
342 static Factory* factory_;
344 double max_volume_;
346 UserInputMonitor* user_input_monitor_;
348 const bool agc_is_enabled_;
350 #if defined(AUDIO_POWER_MONITORING)
351 // Enabled in DoCrete() but not in DoCreateForStream().
352 bool power_measurement_is_enabled_;
354 // Updated each time a power measurement is performed.
355 base::TimeTicks last_audio_level_log_time_;
357 // Whether the silence state should sent as UMA stat.
358 bool log_silence_state_;
360 // The silence report sent as UMA stat at the end of a session.
361 SilenceState silence_state_;
362 #endif
364 size_t prev_key_down_count_;
366 // Time when a low-latency stream is created.
367 base::TimeTicks low_latency_create_time_;
369 DISALLOW_COPY_AND_ASSIGN(AudioInputController);
372 } // namespace media
374 #endif // MEDIA_AUDIO_AUDIO_INPUT_CONTROLLER_H_