Separate Simple Backend creation from initialization.
[chromium-blink-merge.git] / media / audio / audio_input_controller.h
blob21eb704ad499d8e35381235d83787f80207f6955
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.h"
17 #include "media/audio/audio_io.h"
18 #include "media/audio/audio_manager_base.h"
20 // An AudioInputController controls an AudioInputStream and records data
21 // from this input stream. The two main methods are Record() and Close() and
22 // they are both executed on the audio thread which is injected by the two
23 // alternative factory methods, Create() or CreateLowLatency().
25 // All public methods of AudioInputController are non-blocking.
27 // Here is a state diagram for the AudioInputController:
29 // .--> [ Closed / Error ] <--.
30 // | |
31 // | |
32 // [ Created ] ----------> [ Recording ]
33 // ^
34 // |
35 // *[ Empty ]
37 // * Initial state
39 // State sequences (assuming low-latency):
41 // [Creating Thread] [Audio Thread]
43 // User AudioInputController EventHandler
44 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
45 // CrateLowLatency() ==> DoCreate()
46 // AudioManager::MakeAudioInputStream()
47 // AudioInputStream::Open()
48 // .- - - - - - - - - - - - -> OnError()
49 // create the data timer
50 // .-------------------------> OnCreated()
51 // kCreated
52 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
53 // Record() ==> DoRecord()
54 // AudioInputStream::Start()
55 // .-------------------------> OnRecording()
56 // start the data timer
57 // kRecording
58 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
59 // Close() ==> DoClose()
60 // delete the data timer
61 // state_ = kClosed
62 // AudioInputStream::Stop()
63 // AudioInputStream::Close()
64 // SyncWriter::Close()
65 // Closure::Run() <-----------------.
66 // (closure-task)
68 // The audio thread itself is owned by the AudioManager that the
69 // AudioInputController holds a reference to. When performing tasks on the
70 // audio thread, the controller must not add or release references to the
71 // AudioManager or itself (since it in turn holds a reference to the manager).
73 namespace media {
75 class MEDIA_EXPORT AudioInputController
76 : public base::RefCountedThreadSafe<AudioInputController>,
77 public AudioInputStream::AudioInputCallback {
78 public:
79 // An event handler that receives events from the AudioInputController. The
80 // following methods are all called on the audio thread.
81 class MEDIA_EXPORT EventHandler {
82 public:
83 virtual void OnCreated(AudioInputController* controller) = 0;
84 virtual void OnRecording(AudioInputController* controller) = 0;
85 virtual void OnError(AudioInputController* controller) = 0;
86 virtual void OnData(AudioInputController* controller, const uint8* data,
87 uint32 size) = 0;
89 protected:
90 virtual ~EventHandler() {}
93 // A synchronous writer interface used by AudioInputController for
94 // synchronous writing.
95 class SyncWriter {
96 public:
97 virtual ~SyncWriter() {}
99 // Notify the synchronous writer about the number of bytes in the
100 // soundcard which has been recorded.
101 virtual void UpdateRecordedBytes(uint32 bytes) = 0;
103 // Write certain amount of data from |data|. This method returns
104 // number of written bytes.
105 virtual uint32 Write(const void* data, uint32 size, double volume) = 0;
107 // Close this synchronous writer.
108 virtual void Close() = 0;
111 // AudioInputController::Create() can use the currently registered Factory
112 // to create the AudioInputController. Factory is intended for testing only.
113 class Factory {
114 public:
115 virtual AudioInputController* Create(AudioManager* audio_manager,
116 EventHandler* event_handler,
117 AudioParameters params) = 0;
118 protected:
119 virtual ~Factory() {}
122 // Factory method for creating an AudioInputController.
123 // The audio device will be created on the audio thread, and when that is
124 // done, the event handler will receive an OnCreated() call from that same
125 // thread.
126 static scoped_refptr<AudioInputController> Create(
127 AudioManager* audio_manager,
128 EventHandler* event_handler,
129 const AudioParameters& params);
131 // Sets the factory used by the static method Create(). AudioInputController
132 // does not take ownership of |factory|. A value of NULL results in an
133 // AudioInputController being created directly.
134 static void set_factory_for_testing(Factory* factory) { factory_ = factory; }
135 AudioInputStream* stream_for_testing() { return stream_; }
137 // Factory method for creating an AudioInputController for low-latency mode.
138 // The audio device will be created on the audio thread, and when that is
139 // done, the event handler will receive an OnCreated() call from that same
140 // thread.
141 static scoped_refptr<AudioInputController> CreateLowLatency(
142 AudioManager* audio_manager,
143 EventHandler* event_handler,
144 const AudioParameters& params,
145 const std::string& device_id,
146 // External synchronous writer for audio controller.
147 SyncWriter* sync_writer);
149 // Factory method for creating an AudioInputController for low-latency mode,
150 // taking ownership of |stream|. The stream will be opened on the audio
151 // thread, and when that is done, the event handler will receive an
152 // OnCreated() call from that same thread.
153 static scoped_refptr<AudioInputController> CreateForStream(
154 AudioManager* audio_manager,
155 EventHandler* event_handler,
156 AudioInputStream* stream,
157 // External synchronous writer for audio controller.
158 SyncWriter* sync_writer);
160 // Starts recording using the created audio input stream.
161 // This method is called on the creator thread.
162 virtual void Record();
164 // Closes the audio input stream. The state is changed and the resources
165 // are freed on the audio thread. |closed_task| is then executed on the thread
166 // that called Close().
167 // Callbacks (EventHandler and SyncWriter) must exist until |closed_task|
168 // is called.
169 // It is safe to call this method more than once. Calls after the first one
170 // will have no effect.
171 // This method trampolines to the audio thread.
172 virtual void Close(const base::Closure& closed_task);
174 // Sets the capture volume of the input stream. The value 0.0 corresponds
175 // to muted and 1.0 to maximum volume.
176 virtual void SetVolume(double volume);
178 // Sets the Automatic Gain Control (AGC) state of the input stream.
179 // Changing the AGC state is not supported while recording is active.
180 virtual void SetAutomaticGainControl(bool enabled);
182 // AudioInputCallback implementation. Threading details depends on the
183 // device-specific implementation.
184 virtual void OnData(AudioInputStream* stream, const uint8* src, uint32 size,
185 uint32 hardware_delay_bytes, double volume) OVERRIDE;
186 virtual void OnClose(AudioInputStream* stream) OVERRIDE;
187 virtual void OnError(AudioInputStream* stream) OVERRIDE;
189 bool LowLatencyMode() const { return sync_writer_ != NULL; }
191 protected:
192 friend class base::RefCountedThreadSafe<AudioInputController>;
194 // Internal state of the source.
195 enum State {
196 kEmpty,
197 kCreated,
198 kRecording,
199 kClosed,
200 kError
203 AudioInputController(EventHandler* handler, SyncWriter* sync_writer);
204 virtual ~AudioInputController();
206 // Methods called on the audio thread (owned by the AudioManager).
207 void DoCreate(AudioManager* audio_manager, const AudioParameters& params,
208 const std::string& device_id);
209 void DoCreateForStream(AudioInputStream* stream_to_control);
210 void DoRecord();
211 void DoClose();
212 void DoReportError();
213 void DoSetVolume(double volume);
214 void DoSetAutomaticGainControl(bool enabled);
216 // Method which ensures that OnError() is triggered when data recording
217 // times out. Called on the audio thread.
218 void DoCheckForNoData();
220 // Helper method that stops, closes, and NULL:s |*stream_|.
221 // Signals event when done if the event is not NULL.
222 void DoStopCloseAndClearStream(base::WaitableEvent* done);
224 void SetDataIsActive(bool enabled);
225 bool GetDataIsActive();
227 // Gives access to the message loop of the creating thread.
228 scoped_refptr<base::MessageLoopProxy> creator_loop_;
230 // The message loop of audio-manager thread that this object runs on.
231 scoped_refptr<base::MessageLoopProxy> message_loop_;
233 // Contains the AudioInputController::EventHandler which receives state
234 // notifications from this class.
235 EventHandler* handler_;
237 // Pointer to the audio input stream object.
238 AudioInputStream* stream_;
240 // |no_data_timer_| is used to call OnError() when we stop receiving
241 // OnData() calls without an OnClose() call. This can occur
242 // when an audio input device is unplugged whilst recording on Windows.
243 // See http://crbug.com/79936 for details.
244 // This member is only touched by the audio thread.
245 scoped_ptr<base::Timer> no_data_timer_;
247 // This flag is used to signal that we are receiving OnData() calls, i.e,
248 // that data is active. It can be touched by the audio thread and by the
249 // low-level audio thread which calls OnData(). E.g. on Windows, the
250 // low-level audio thread is called wasapi_capture_thread.
251 base::subtle::Atomic32 data_is_active_;
253 // |state_| is written on the audio thread and is read on the hardware audio
254 // thread. These operations need to be locked. But lock is not required for
255 // reading on the audio input controller thread.
256 State state_;
258 base::Lock lock_;
260 // SyncWriter is used only in low-latency mode for synchronous writing.
261 SyncWriter* sync_writer_;
263 static Factory* factory_;
265 double max_volume_;
267 DISALLOW_COPY_AND_ASSIGN(AudioInputController);
270 } // namespace media
272 #endif // MEDIA_AUDIO_AUDIO_INPUT_CONTROLLER_H_