Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(774)

Side by Side Diff: media/audio/audio_device_thread.cc

Issue 1703473002: Make AudioOutputDevice restartable and reinitializable (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@new_mixing
Patch Set: git cl format Created 4 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "media/audio/audio_device_thread.h" 5 #include "media/audio/audio_device_thread.h"
6 6
7 #include <stddef.h> 7 #include <stddef.h>
8 #include <stdint.h> 8 #include <stdint.h>
9 9
10 #include <algorithm> 10 #include <algorithm>
11 #include <limits> 11 #include <limits>
12 12
13 #include "base/bind.h" 13 #include "base/bind.h"
14 #include "base/logging.h" 14 #include "base/logging.h"
15 #include "base/macros.h" 15 #include "base/macros.h"
16 #include "base/memory/aligned_memory.h" 16 #include "base/memory/aligned_memory.h"
17 #include "base/message_loop/message_loop.h" 17 #include "base/message_loop/message_loop.h"
18 #include "base/numerics/safe_conversions.h" 18 #include "base/numerics/safe_conversions.h"
19 #include "base/synchronization/condition_variable.h"
19 #include "base/threading/platform_thread.h" 20 #include "base/threading/platform_thread.h"
20 #include "base/threading/thread_restrictions.h" 21 #include "base/threading/thread_restrictions.h"
21 #include "media/base/audio_bus.h" 22 #include "media/base/audio_bus.h"
22 23
23 using base::PlatformThread; 24 using base::PlatformThread;
24 25
25 namespace media { 26 namespace media {
26 27
27 // The actual worker thread implementation. It's very bare bones and much 28 // The actual worker thread implementation. It's very bare bones and much
28 // simpler than SimpleThread (no synchronization in Start, etc) and supports 29 // simpler than SimpleThread (no synchronization in Start, etc) and supports
29 // joining the thread handle asynchronously via a provided message loop even 30 // joining the thread handle asynchronously via a provided message loop even
30 // after the Thread object itself has been deleted. 31 // after the Thread object itself has been deleted.
31 class AudioDeviceThread::Thread 32 class AudioDeviceThread::Thread
32 : public PlatformThread::Delegate, 33 : public PlatformThread::Delegate,
33 public base::RefCountedThreadSafe<AudioDeviceThread::Thread> { 34 public base::RefCountedThreadSafe<AudioDeviceThread::Thread> {
34 public: 35 public:
35 Thread(AudioDeviceThread::Callback* callback, 36 Thread(const char* thread_name, bool synchronized_buffers);
36 base::SyncSocket::Handle socket,
37 const char* thread_name,
38 bool synchronized_buffers);
39 37
38 // Starts the thread which will wait in ThreadMain(). Resume() must then be
39 // called to actually start running it.
40 void Start(); 40 void Start();
41 41
42 // Stops the thread. If |loop_for_join| is non-NULL, the function posts 42 // Shuts down the thread. If |loop_for_join| is non-NULL, the function posts
43 // a task to join (close) the thread handle later instead of waiting for 43 // a task to join (close) the thread handle later instead of waiting for
44 // the thread. If loop_for_join is NULL, then the function waits 44 // the thread. If loop_for_join is NULL, then the function waits
45 // synchronously for the thread to terminate. 45 // synchronously for the thread to terminate.
46 // Must be called.
46 void Stop(base::MessageLoop* loop_for_join); 47 void Stop(base::MessageLoop* loop_for_join);
47 48
49 // Releases the thread from waiting and starts running it with the given
50 // |callback| and |socket|.
51 void Resume(AudioDeviceThread::Callback* callback,
52 base::SyncSocket::Handle socket);
53
54 // Pauses the thread, it will wait in ThreadMain(). Shuts down the
55 // socket. Resume() can then be called to restart it.
56 void Pause();
57
48 private: 58 private:
59 enum ResumeAction { kActionPause, kActionPlay, kActionStop };
60
49 friend class base::RefCountedThreadSafe<AudioDeviceThread::Thread>; 61 friend class base::RefCountedThreadSafe<AudioDeviceThread::Thread>;
62
50 ~Thread() override; 63 ~Thread() override;
51 64
52 // Overrides from PlatformThread::Delegate. 65 // Overrides from PlatformThread::Delegate.
53 void ThreadMain() override; 66 void ThreadMain() override;
54 67
55 // Runs the loop that reads from the socket. 68 // Runs the loop that reads from the socket, called in ThreadMain(),
56 void Run(); 69 void Run();
57 70
58 private: 71 // Start(), Resume(), Pause() must be serialized; Stop() can be called any
59 base::PlatformThreadHandle thread_; 72 // moment.
60 AudioDeviceThread::Callback* callback_; 73 base::ThreadChecker thread_checker_;
61 base::CancelableSyncSocket socket_; 74
62 base::Lock callback_lock_;
63 const char* thread_name_; 75 const char* thread_name_;
64 const bool synchronized_buffers_; 76 const bool synchronized_buffers_;
65 77
78 // Modified in ThreadMain only, no lock protection needed.
79 AudioDeviceThread::Callback* callback_;
80
81 base::Lock action_lock_; // Protects everything below.
82 base::ConditionVariable action_condition_;
83 ResumeAction action_;
84
85 base::PlatformThreadHandle thread_;
86
87 // Reset on client thread.
88 std::unique_ptr<base::CancelableSyncSocket> socket_;
89
90 // Set on client thead.
91 AudioDeviceThread::Callback* new_callback_;
92 base::SyncSocket::Handle new_socket_handle_;
93
66 DISALLOW_COPY_AND_ASSIGN(Thread); 94 DISALLOW_COPY_AND_ASSIGN(Thread);
67 }; 95 };
68 96
69 // AudioDeviceThread implementation 97 // AudioDeviceThread implementation TODO(olka): get rid of it. It just adds one
o1ka 2016/05/03 15:47:32 You've got a comment on it in the header I think.
Henrik Grunell 2016/05/04 09:05:11 Yes. Removed the whole comment here actually.
98 // extra lock.
70 99
71 AudioDeviceThread::AudioDeviceThread() { 100 AudioDeviceThread::AudioDeviceThread() {}
72 }
73 101
74 AudioDeviceThread::~AudioDeviceThread() { DCHECK(!thread_.get()); } 102 AudioDeviceThread::~AudioDeviceThread() { DCHECK(!thread_.get()); }
75 103
76 void AudioDeviceThread::Start(AudioDeviceThread::Callback* callback, 104 void AudioDeviceThread::Start(const char* thread_name,
77 base::SyncSocket::Handle socket,
78 const char* thread_name,
79 bool synchronized_buffers) { 105 bool synchronized_buffers) {
80 base::AutoLock auto_lock(thread_lock_); 106 base::AutoLock auto_lock(thread_lock_);
81 CHECK(!thread_.get()); 107 CHECK(!thread_.get());
82 thread_ = new AudioDeviceThread::Thread( 108 thread_ = new AudioDeviceThread::Thread(thread_name, synchronized_buffers);
83 callback, socket, thread_name, synchronized_buffers);
84 thread_->Start(); 109 thread_->Start();
85 } 110 }
86 111
87 void AudioDeviceThread::Stop(base::MessageLoop* loop_for_join) { 112 void AudioDeviceThread::Stop(base::MessageLoop* loop_for_join) {
88 base::AutoLock auto_lock(thread_lock_); 113 base::AutoLock auto_lock(thread_lock_);
89 if (thread_.get()) { 114 if (thread_.get()) {
90 thread_->Stop(loop_for_join); 115 thread_->Stop(loop_for_join);
91 thread_ = NULL; 116 thread_ = NULL;
92 } 117 }
93 } 118 }
94 119
120 void AudioDeviceThread::Resume(AudioDeviceThread::Callback* callback,
121 base::SyncSocket::Handle socket) {
122 base::AutoLock auto_lock(thread_lock_);
123 thread_->Resume(callback, socket);
o1ka 2016/05/03 15:47:32 if (thread_.get())?
Henrik Grunell 2016/05/04 09:05:11 Haha, yes, this I commented on in your CL with cha
124 }
125
126 void AudioDeviceThread::Pause() {
127 base::AutoLock auto_lock(thread_lock_);
128 if (thread_.get())
129 thread_->Pause();
130 }
131
95 bool AudioDeviceThread::IsStopped() { 132 bool AudioDeviceThread::IsStopped() {
96 base::AutoLock auto_lock(thread_lock_); 133 base::AutoLock auto_lock(thread_lock_);
97 return !thread_.get(); 134 return !thread_.get();
98 } 135 }
99 136
100 // AudioDeviceThread::Thread implementation 137 // AudioDeviceThread::Thread implementation
101 AudioDeviceThread::Thread::Thread(AudioDeviceThread::Callback* callback, 138 AudioDeviceThread::Thread::Thread(const char* thread_name,
102 base::SyncSocket::Handle socket,
103 const char* thread_name,
104 bool synchronized_buffers) 139 bool synchronized_buffers)
105 : thread_(), 140 : thread_name_(thread_name),
106 callback_(callback), 141 synchronized_buffers_(synchronized_buffers),
107 socket_(socket), 142 callback_(nullptr),
108 thread_name_(thread_name), 143 action_condition_(&action_lock_),
109 synchronized_buffers_(synchronized_buffers) { 144 action_(kActionPause),
145 new_callback_(nullptr),
146 new_socket_handle_(base::CancelableSyncSocket::kInvalidHandle) {
147 thread_checker_.DetachFromThread();
110 } 148 }
111 149
112 AudioDeviceThread::Thread::~Thread() { 150 AudioDeviceThread::Thread::~Thread() {
113 DCHECK(thread_.is_null()); 151 DCHECK(thread_.is_null());
114 } 152 }
115 153
116 void AudioDeviceThread::Thread::Start() { 154 void AudioDeviceThread::Thread::Start() {
117 base::AutoLock auto_lock(callback_lock_); 155 DCHECK(thread_checker_.CalledOnValidThread());
118 DCHECK(thread_.is_null()); 156
157 base::AutoLock auto_lock(action_lock_);
158 DCHECK(thread_.is_null()) << "Calling Start() on a started thread?";
159 if (action_ == kActionStop)
160 return; // Stop has already been executed on another thread.
161
119 // This reference will be released when the thread exists. 162 // This reference will be released when the thread exists.
120 AddRef(); 163 AddRef();
121 164
122 PlatformThread::CreateWithPriority(0, this, &thread_, 165 PlatformThread::CreateWithPriority(0, this, &thread_,
123 base::ThreadPriority::REALTIME_AUDIO); 166 base::ThreadPriority::REALTIME_AUDIO);
124 CHECK(!thread_.is_null()); 167 CHECK(!thread_.is_null());
125 } 168 }
126 169
127 void AudioDeviceThread::Thread::Stop(base::MessageLoop* loop_for_join) { 170 void AudioDeviceThread::Thread::Stop(base::MessageLoop* loop_for_join) {
128 socket_.Shutdown(); 171 // Note: Stop() can be called any time, even before Start(), because it's
172 // allowed to be executed on a different thread.
129 173
130 base::PlatformThreadHandle thread = base::PlatformThreadHandle(); 174 base::PlatformThreadHandle thread = base::PlatformThreadHandle();
175 {
176 base::AutoLock auto_lock(action_lock_);
177 DCHECK(action_ != kActionStop) << "Calling Stop() on a stopped thread?";
131 178
132 { // NOLINT 179 // |socket_| is only set/reset under the |action_lock_|, so it's safe to
133 base::AutoLock auto_lock(callback_lock_); 180 // access under that lock here.
134 callback_ = NULL; 181 // TODO BEFORE COMMIT: Is it safe to shutdown socket twice or shutdown a
182 // socket with an invalid handle? If not, shutdown only if kActionPlay?
183 if (socket_)
184 socket_->Shutdown();
185
186 // Must be done under lock to avoid race wuth Start().
135 std::swap(thread, thread_); 187 std::swap(thread, thread_);
136 } 188
189 action_ = kActionStop;
190 action_condition_.Signal();
191 } // auto_lock(action_lock_)
137 192
138 if (!thread.is_null()) { 193 if (!thread.is_null()) {
139 if (loop_for_join) { 194 if (loop_for_join) {
140 loop_for_join->PostTask(FROM_HERE, 195 loop_for_join->PostTask(FROM_HERE,
141 base::Bind(&base::PlatformThread::Join, thread)); 196 base::Bind(&base::PlatformThread::Join, thread));
142 } else { 197 } else {
143 base::PlatformThread::Join(thread); 198 base::PlatformThread::Join(thread);
144 } 199 }
145 } 200 }
146 } 201 }
147 202
203 void AudioDeviceThread::Thread::Resume(AudioDeviceThread::Callback* callback,
204 base::SyncSocket::Handle socket_handle) {
205 DCHECK(thread_checker_.CalledOnValidThread());
206
207 base::AutoLock auto_lock(action_lock_);
208 if (action_ == kActionStop)
209 return; // Stop is the last operation to be executed.
210
211 DCHECK(action_ != kActionPlay) << "Resume a non-paused thread?";
o1ka 2016/05/03 15:47:32 (action_ == kActionPause) for clarity?
Henrik Grunell 2016/05/04 09:05:11 Done.
212
213 DCHECK_EQ(new_socket_handle_, base::CancelableSyncSocket::kInvalidHandle);
214
215 new_callback_ = callback;
216 new_socket_handle_ = socket_handle;
217
218 action_ = kActionPlay;
219 action_condition_.Signal();
220 }
221
222 void AudioDeviceThread::Thread::Pause() {
223 DCHECK(thread_checker_.CalledOnValidThread());
224
225 base::AutoLock auto_lock(action_lock_);
226 if (action_ == kActionStop)
227 return; // Stop is the last operation to be executed.
228
229 DCHECK(action_ != kActionPause) << "Pause a paused thread?";
o1ka 2016/05/03 15:47:32 (action_ == kActionPlay)?
Henrik Grunell 2016/05/04 09:05:11 Done.
230
231 // |socket_| is only set/reset under the |action_lock_|, so it's safe to
232 // access under that lock here.
233 // TODO BEFORE COMMIT: Is it safe to shutdown socket twice? If not, shutdown
234 // only if kActionPlay?
235 if (socket_)
236 socket_->Shutdown();
237 action_ = kActionPause;
238 }
239
148 void AudioDeviceThread::Thread::ThreadMain() { 240 void AudioDeviceThread::Thread::ThreadMain() {
149 PlatformThread::SetName(thread_name_); 241 PlatformThread::SetName(thread_name_);
150 242
151 // Singleton access is safe from this thread as long as callback is non-NULL. 243 // Singleton access is safe from this thread as long as callback is non-NULL.
152 // The callback is the only point where the thread calls out to 'unknown' code 244 // The callback is the only point where the thread calls out to 'unknown' code
153 // that might touch singletons and the lifetime of the callback is controlled 245 // that might touch singletons and the lifetime of the callback is controlled
154 // by another thread on which singleton access is OK as well. 246 // by another thread on which singleton access is OK as well.
155 base::ThreadRestrictions::SetSingletonAllowed(true); 247 base::ThreadRestrictions::SetSingletonAllowed(true);
156 248
157 { // NOLINT 249 while (true) {
158 base::AutoLock auto_lock(callback_lock_); 250 {
159 if (callback_) 251 base::AutoLock auto_lock(action_lock_);
160 callback_->InitializeOnAudioThread(); 252 while (action_ == kActionPause)
253 action_condition_.Wait();
254
255 if (action_ == kActionStop)
256 break;
257 // else reinitialize and resume.
258
259 socket_.reset(new base::CancelableSyncSocket(new_socket_handle_));
260
261 callback_ = new_callback_;
262 if (callback_)
263 callback_->InitializeOnAudioThread();
264
265 new_callback_ = nullptr;
266 new_socket_handle_ = base::CancelableSyncSocket::kInvalidHandle;
267 } // auto_lock(action_lock_)
268
269 Run();
270
271 // We are here if and only if socket operation failed. The possible reasons
272 // are: (a) Shutdown() has been called on the socket (=Stop() or Pause());
273 // (b) socket failed. In both cases go back and wait for stop or resume
274 // action.
275 callback_ = nullptr;
161 } 276 }
162 277
163 Run();
164
165 // Release the reference for the thread. Note that after this, the Thread 278 // Release the reference for the thread. Note that after this, the Thread
166 // instance will most likely be deleted. 279 // instance will most likely be deleted.
167 Release(); 280 Release();
168 } 281 }
169 282
170 void AudioDeviceThread::Thread::Run() { 283 void AudioDeviceThread::Thread::Run() {
171 uint32_t buffer_index = 0; 284 uint32_t buffer_index = 0;
285
172 while (true) { 286 while (true) {
173 uint32_t pending_data = 0; 287 uint32_t pending_data = 0;
174 size_t bytes_read = socket_.Receive(&pending_data, sizeof(pending_data)); 288 size_t bytes_read = socket_->Receive(&pending_data, sizeof(pending_data));
o1ka 2016/05/03 15:47:32 Add a comment that both socket_ and callback_ are
Henrik Grunell 2016/05/04 09:05:11 Done. I put it before the loop as a general commen
289
175 if (bytes_read != sizeof(pending_data)) 290 if (bytes_read != sizeof(pending_data))
176 break; 291 break;
177 292
178 // std::numeric_limits<uint32_t>::max() is a special signal which is 293 // std::numeric_limits<uint32_t>::max() is a special signal which is
179 // returned after the browser stops the output device in response to a 294 // returned after the browser stops the output device in response to a
180 // renderer side request. 295 // renderer side request.
181 // 296 //
182 // Avoid running Process() for the paused signal, we still need to update 297 // Avoid running Process() for the paused signal, we still need to update
183 // the buffer index if |synchronized_buffers_| is true though. 298 // the buffer index if |synchronized_buffers_| is true though.
184 // 299 //
185 // See comments in AudioOutputController::DoPause() for details on why. 300 // See comments in AudioOutputController::DoPause() for details on why.
186 if (pending_data != std::numeric_limits<uint32_t>::max()) { 301 if (pending_data != std::numeric_limits<uint32_t>::max()) {
187 base::AutoLock auto_lock(callback_lock_);
188 if (callback_) 302 if (callback_)
189 callback_->Process(pending_data); 303 callback_->Process(pending_data);
190 } 304 }
191 305
192 // The usage of |synchronized_buffers_| differs between input and output 306 // The usage of |synchronized_buffers_| differs between input and output
193 // cases. 307 // cases.
194 // Input: 308 // Input:
195 // Let the other end know that we have read data, so that it can verify 309 // Let the other end know that we have read data, so that it can verify
196 // it doesn't overwrite any data before read. The |buffer_index| value is 310 // it doesn't overwrite any data before read. The |buffer_index| value is
197 // not used. For more details, see AudioInputSyncWriter::Write(). 311 // not used. For more details, see AudioInputSyncWriter::Write().
198 // Output: 312 // Output:
199 // Let the other end know which buffer we just filled. The |buffer_index| is 313 // Let the other end know which buffer we just filled. The |buffer_index| is
200 // used to ensure the other end is getting the buffer it expects. For more 314 // used to ensure the other end is getting the buffer it expects. For more
201 // details on how this works see AudioSyncReader::WaitUntilDataIsReady(). 315 // details on how this works see AudioSyncReader::WaitUntilDataIsReady().
202 if (synchronized_buffers_) { 316 if (synchronized_buffers_) {
203 ++buffer_index; 317 ++buffer_index;
204 size_t bytes_sent = socket_.Send(&buffer_index, sizeof(buffer_index)); 318 size_t bytes_sent = socket_->Send(&buffer_index, sizeof(buffer_index));
319
205 if (bytes_sent != sizeof(buffer_index)) 320 if (bytes_sent != sizeof(buffer_index))
206 break; 321 break;
207 } 322 }
208 } 323 } // while
209 } 324 }
210 325
211 // AudioDeviceThread::Callback implementation 326 // AudioDeviceThread::Callback implementation
212 327
213 AudioDeviceThread::Callback::Callback(const AudioParameters& audio_parameters, 328 AudioDeviceThread::Callback::Callback(const AudioParameters& audio_parameters,
214 base::SharedMemoryHandle memory, 329 base::SharedMemoryHandle memory,
215 int memory_length, 330 int memory_length,
216 int total_segments) 331 int total_segments)
217 : audio_parameters_(audio_parameters), 332 : audio_parameters_(audio_parameters),
218 samples_per_ms_(static_cast<double>(audio_parameters.sample_rate()) / 333 samples_per_ms_(static_cast<double>(audio_parameters.sample_rate()) /
(...skipping 14 matching lines...) Expand all
233 } 348 }
234 349
235 AudioDeviceThread::Callback::~Callback() {} 350 AudioDeviceThread::Callback::~Callback() {}
236 351
237 void AudioDeviceThread::Callback::InitializeOnAudioThread() { 352 void AudioDeviceThread::Callback::InitializeOnAudioThread() {
238 MapSharedMemory(); 353 MapSharedMemory();
239 CHECK(shared_memory_.memory()); 354 CHECK(shared_memory_.memory());
240 } 355 }
241 356
242 } // namespace media. 357 } // namespace media.
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698