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

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: Changes from olka@, adding callback lock, removing stopping hack, rebase. 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(). Play() 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 Play(AudioDeviceThread::Callback* callback,
52 base::SyncSocket::Handle socket);
53
54 // Pauses the thread, it will wait in ThreadMain(). Shuts down the
55 // socket. Play() 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(), Play(), 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 threaid.
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
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::Play(AudioDeviceThread::Callback* callback,
121 base::SyncSocket::Handle socket) {
122 base::AutoLock auto_lock(thread_lock_);
123 thread_->Play(callback, socket);
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 // NB: 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 // Is it safe to shutdown socket twice or shutdown a socket with an invalid
133 base::AutoLock auto_lock(callback_lock_); 180 // handle? If not, shutdown only if kActionPlay?
134 callback_ = NULL; 181 socket_->Shutdown();
182
183 // Must be done under lock to avoid race wuth Start().
135 std::swap(thread, thread_); 184 std::swap(thread, thread_);
136 } 185
186 action_ = kActionStop;
187 action_condition_.Signal();
188 } // auto_lock(action_lock_)
137 189
138 if (!thread.is_null()) { 190 if (!thread.is_null()) {
139 if (loop_for_join) { 191 if (loop_for_join) {
140 loop_for_join->PostTask(FROM_HERE, 192 loop_for_join->PostTask(FROM_HERE,
141 base::Bind(&base::PlatformThread::Join, thread)); 193 base::Bind(&base::PlatformThread::Join, thread));
142 } else { 194 } else {
143 base::PlatformThread::Join(thread); 195 base::PlatformThread::Join(thread);
144 } 196 }
145 } 197 }
146 } 198 }
147 199
200 void AudioDeviceThread::Thread::Play(AudioDeviceThread::Callback* callback,
201 base::SyncSocket::Handle socket_handle) {
202 DCHECK(thread_checker_.CalledOnValidThread());
203
204 base::AutoLock auto_lock(action_lock_);
205 if (action_ == kActionStop)
206 return; // Stop is the last operation to be executed.
207
208 DCHECK(action_ != kActionPlay) << "Play a playing thread?";
209
210 DCHECK_EQ(new_socket_handle_, base::CancelableSyncSocket::kInvalidHandle);
211
212 new_callback_ = callback;
213 new_socket_handle_ = socket_handle;
214
215 action_ = kActionPlay;
216 action_condition_.Signal();
217 }
218
219 void AudioDeviceThread::Thread::Pause() {
220 DCHECK(thread_checker_.CalledOnValidThread());
221
222 base::AutoLock auto_lock(action_lock_);
223 if (action_ == kActionStop)
224 return; // Stop is the last operation to be executed.
225
226 DCHECK(action_ != kActionPause) << "Pause a paused thread?";
227
228 // Is it safe to shutdown socket twice? If not, shutdown only if kActionPlay?
229 socket_->Shutdown();
230 action_ = kActionPause;
231 }
232
148 void AudioDeviceThread::Thread::ThreadMain() { 233 void AudioDeviceThread::Thread::ThreadMain() {
149 PlatformThread::SetName(thread_name_); 234 PlatformThread::SetName(thread_name_);
150 235
151 // Singleton access is safe from this thread as long as callback is non-NULL. 236 // 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 237 // 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 238 // that might touch singletons and the lifetime of the callback is controlled
154 // by another thread on which singleton access is OK as well. 239 // by another thread on which singleton access is OK as well.
155 base::ThreadRestrictions::SetSingletonAllowed(true); 240 base::ThreadRestrictions::SetSingletonAllowed(true);
156 241
157 { // NOLINT 242 while (true) {
158 base::AutoLock auto_lock(callback_lock_); 243 {
159 if (callback_) 244 base::AutoLock auto_lock(action_lock_);
160 callback_->InitializeOnAudioThread(); 245 while (action_ == kActionPause)
246 action_condition_.Wait();
247
248 if (action_ == kActionStop)
249 break;
250 // else reinitialize and resume.
251
252 socket_.reset(new base::CancelableSyncSocket(new_socket_handle_));
253
254 callback_ = new_callback_;
255 if (callback_)
256 callback_->InitializeOnAudioThread();
257
258 new_callback_ = nullptr;
259 new_socket_handle_ = base::CancelableSyncSocket::kInvalidHandle;
260 } // auto_lock(action_lock_)
261
262 Run();
263
264 // We are here if and only if socket operation failed. The possible reasons
265 // are: (a) Shutdown() has been called on the socket (=Stop() or Pause());
266 // (b) socket failed. In both cases go back and wait for stop or resume
267 // action.
268 callback_ = nullptr;
161 } 269 }
162 270
163 Run();
164
165 // Release the reference for the thread. Note that after this, the Thread 271 // Release the reference for the thread. Note that after this, the Thread
166 // instance will most likely be deleted. 272 // instance will most likely be deleted.
167 Release(); 273 Release();
168 } 274 }
169 275
170 void AudioDeviceThread::Thread::Run() { 276 void AudioDeviceThread::Thread::Run() {
171 uint32_t buffer_index = 0; 277 uint32_t buffer_index = 0;
278
172 while (true) { 279 while (true) {
173 uint32_t pending_data = 0; 280 uint32_t pending_data = 0;
174 size_t bytes_read = socket_.Receive(&pending_data, sizeof(pending_data)); 281 size_t bytes_read = socket_->Receive(&pending_data, sizeof(pending_data));
282
175 if (bytes_read != sizeof(pending_data)) 283 if (bytes_read != sizeof(pending_data))
176 break; 284 break;
177 285
178 // std::numeric_limits<uint32_t>::max() is a special signal which is 286 // 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 287 // returned after the browser stops the output device in response to a
180 // renderer side request. 288 // renderer side request.
181 // 289 //
182 // Avoid running Process() for the paused signal, we still need to update 290 // Avoid running Process() for the paused signal, we still need to update
183 // the buffer index if |synchronized_buffers_| is true though. 291 // the buffer index if |synchronized_buffers_| is true though.
184 // 292 //
185 // See comments in AudioOutputController::DoPause() for details on why. 293 // See comments in AudioOutputController::DoPause() for details on why.
186 if (pending_data != std::numeric_limits<uint32_t>::max()) { 294 if (pending_data != std::numeric_limits<uint32_t>::max()) {
187 base::AutoLock auto_lock(callback_lock_);
188 if (callback_) 295 if (callback_)
189 callback_->Process(pending_data); 296 callback_->Process(pending_data);
190 } 297 }
191 298
192 // The usage of |synchronized_buffers_| differs between input and output 299 // The usage of |synchronized_buffers_| differs between input and output
193 // cases. 300 // cases.
194 // Input: 301 // Input:
195 // Let the other end know that we have read data, so that it can verify 302 // 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 303 // it doesn't overwrite any data before read. The |buffer_index| value is
197 // not used. For more details, see AudioInputSyncWriter::Write(). 304 // not used. For more details, see AudioInputSyncWriter::Write().
198 // Output: 305 // Output:
199 // Let the other end know which buffer we just filled. The |buffer_index| is 306 // 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 307 // used to ensure the other end is getting the buffer it expects. For more
201 // details on how this works see AudioSyncReader::WaitUntilDataIsReady(). 308 // details on how this works see AudioSyncReader::WaitUntilDataIsReady().
202 if (synchronized_buffers_) { 309 if (synchronized_buffers_) {
203 ++buffer_index; 310 ++buffer_index;
204 size_t bytes_sent = socket_.Send(&buffer_index, sizeof(buffer_index)); 311 size_t bytes_sent = socket_->Send(&buffer_index, sizeof(buffer_index));
312
205 if (bytes_sent != sizeof(buffer_index)) 313 if (bytes_sent != sizeof(buffer_index))
206 break; 314 break;
207 } 315 }
208 } 316 } // while
209 } 317 }
210 318
211 // AudioDeviceThread::Callback implementation 319 // AudioDeviceThread::Callback implementation
212 320
213 AudioDeviceThread::Callback::Callback(const AudioParameters& audio_parameters, 321 AudioDeviceThread::Callback::Callback(const AudioParameters& audio_parameters,
214 base::SharedMemoryHandle memory, 322 base::SharedMemoryHandle memory,
215 int memory_length, 323 int memory_length,
216 int total_segments) 324 int total_segments)
217 : audio_parameters_(audio_parameters), 325 : audio_parameters_(audio_parameters),
218 samples_per_ms_(static_cast<double>(audio_parameters.sample_rate()) / 326 samples_per_ms_(static_cast<double>(audio_parameters.sample_rate()) /
(...skipping 14 matching lines...) Expand all
233 } 341 }
234 342
235 AudioDeviceThread::Callback::~Callback() {} 343 AudioDeviceThread::Callback::~Callback() {}
236 344
237 void AudioDeviceThread::Callback::InitializeOnAudioThread() { 345 void AudioDeviceThread::Callback::InitializeOnAudioThread() {
238 MapSharedMemory(); 346 MapSharedMemory();
239 CHECK(shared_memory_.memory()); 347 CHECK(shared_memory_.memory());
240 } 348 }
241 349
242 } // namespace media. 350 } // namespace media.
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698