blob: eff4bb7bc46931674c916cd37b3e79ee37df9444 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
Alok Kediya601e9b52013-09-27 11:55:10 +05302** Copyright (c) 2013, The Linux Foundation. All rights reserved.
3** Not a Contribution.
Eric Laurent81784c32012-11-19 14:55:58 -08004** Copyright 2012, The Android Open Source Project
5**
6** Licensed under the Apache License, Version 2.0 (the "License");
7** you may not use this file except in compliance with the License.
8** You may obtain a copy of the License at
9**
10** http://www.apache.org/licenses/LICENSE-2.0
11**
12** Unless required by applicable law or agreed to in writing, software
13** distributed under the License is distributed on an "AS IS" BASIS,
14** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15** See the License for the specific language governing permissions and
16** limitations under the License.
17*/
18
19#ifndef INCLUDING_FROM_AUDIOFLINGER_H
20 #error This header file should only be included from AudioFlinger.h
21#endif
22
23class ThreadBase : public Thread {
24public:
25
26#include "TrackBase.h"
27
28 enum type_t {
29 MIXER, // Thread class is MixerThread
30 DIRECT, // Thread class is DirectOutputThread
31 DUPLICATING, // Thread class is DuplicatingThread
Eric Laurentbfb1b832013-01-07 09:53:42 -080032 RECORD, // Thread class is RecordThread
33 OFFLOAD // Thread class is OffloadThread
Eric Laurent81784c32012-11-19 14:55:58 -080034 };
35
36 ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
37 audio_devices_t outDevice, audio_devices_t inDevice, type_t type);
38 virtual ~ThreadBase();
39
40 void dumpBase(int fd, const Vector<String16>& args);
41 void dumpEffectChains(int fd, const Vector<String16>& args);
42
43 void clearPowerManager();
44
45 // base for record and playback
46 enum {
47 CFG_EVENT_IO,
48 CFG_EVENT_PRIO
49 };
50
51 class ConfigEvent {
52 public:
53 ConfigEvent(int type) : mType(type) {}
54 virtual ~ConfigEvent() {}
55
56 int type() const { return mType; }
57
58 virtual void dump(char *buffer, size_t size) = 0;
59
60 private:
61 const int mType;
62 };
63
64 class IoConfigEvent : public ConfigEvent {
65 public:
66 IoConfigEvent(int event, int param) :
67 ConfigEvent(CFG_EVENT_IO), mEvent(event), mParam(event) {}
68 virtual ~IoConfigEvent() {}
69
70 int event() const { return mEvent; }
71 int param() const { return mParam; }
72
73 virtual void dump(char *buffer, size_t size) {
74 snprintf(buffer, size, "IO event: event %d, param %d\n", mEvent, mParam);
75 }
76
77 private:
78 const int mEvent;
79 const int mParam;
80 };
81
82 class PrioConfigEvent : public ConfigEvent {
83 public:
84 PrioConfigEvent(pid_t pid, pid_t tid, int32_t prio) :
85 ConfigEvent(CFG_EVENT_PRIO), mPid(pid), mTid(tid), mPrio(prio) {}
86 virtual ~PrioConfigEvent() {}
87
88 pid_t pid() const { return mPid; }
89 pid_t tid() const { return mTid; }
90 int32_t prio() const { return mPrio; }
91
92 virtual void dump(char *buffer, size_t size) {
93 snprintf(buffer, size, "Prio event: pid %d, tid %d, prio %d\n", mPid, mTid, mPrio);
94 }
95
96 private:
97 const pid_t mPid;
98 const pid_t mTid;
99 const int32_t mPrio;
100 };
101
102
103 class PMDeathRecipient : public IBinder::DeathRecipient {
104 public:
105 PMDeathRecipient(const wp<ThreadBase>& thread) : mThread(thread) {}
106 virtual ~PMDeathRecipient() {}
107
108 // IBinder::DeathRecipient
109 virtual void binderDied(const wp<IBinder>& who);
110
111 private:
112 PMDeathRecipient(const PMDeathRecipient&);
113 PMDeathRecipient& operator = (const PMDeathRecipient&);
114
115 wp<ThreadBase> mThread;
116 };
117
118 virtual status_t initCheck() const = 0;
119
120 // static externally-visible
121 type_t type() const { return mType; }
122 audio_io_handle_t id() const { return mId;}
123
124 // dynamic externally-visible
125 uint32_t sampleRate() const { return mSampleRate; }
126 uint32_t channelCount() const { return mChannelCount; }
127 audio_channel_mask_t channelMask() const { return mChannelMask; }
128 audio_format_t format() const { return mFormat; }
129 // Called by AudioFlinger::frameCount(audio_io_handle_t output) and effects,
Glenn Kasten9b58f632013-07-16 11:37:48 -0700130 // and returns the [normal mix] buffer's frame count.
131 virtual size_t frameCount() const = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800132 size_t frameSize() const { return mFrameSize; }
Eric Laurent81784c32012-11-19 14:55:58 -0800133
134 // Should be "virtual status_t requestExitAndWait()" and override same
135 // method in Thread, but Thread::requestExitAndWait() is not yet virtual.
136 void exit();
137 virtual bool checkForNewParameters_l() = 0;
138 virtual status_t setParameters(const String8& keyValuePairs);
139 virtual String8 getParameters(const String8& keys) = 0;
140 virtual void audioConfigChanged_l(int event, int param = 0) = 0;
Alok Kediya601e9b52013-09-27 11:55:10 +0530141 void effectConfigChanged();
Eric Laurent81784c32012-11-19 14:55:58 -0800142 void sendIoConfigEvent(int event, int param = 0);
143 void sendIoConfigEvent_l(int event, int param = 0);
144 void sendPrioConfigEvent_l(pid_t pid, pid_t tid, int32_t prio);
145 void processConfigEvents();
146
147 // see note at declaration of mStandby, mOutDevice and mInDevice
148 bool standby() const { return mStandby; }
149 audio_devices_t outDevice() const { return mOutDevice; }
150 audio_devices_t inDevice() const { return mInDevice; }
151
152 virtual audio_stream_t* stream() const = 0;
153
154 sp<EffectHandle> createEffect_l(
155 const sp<AudioFlinger::Client>& client,
156 const sp<IEffectClient>& effectClient,
157 int32_t priority,
158 int sessionId,
159 effect_descriptor_t *desc,
160 int *enabled,
161 status_t *status);
162 void disconnectEffect(const sp< EffectModule>& effect,
163 EffectHandle *handle,
164 bool unpinIfLast);
165
166 // return values for hasAudioSession (bit field)
167 enum effect_state {
168 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
169 // effect
170 TRACK_SESSION = 0x2 // the audio session corresponds to at least one
171 // track
172 };
173
174 // get effect chain corresponding to session Id.
175 sp<EffectChain> getEffectChain(int sessionId);
176 // same as getEffectChain() but must be called with ThreadBase mutex locked
177 sp<EffectChain> getEffectChain_l(int sessionId) const;
178 // add an effect chain to the chain list (mEffectChains)
179 virtual status_t addEffectChain_l(const sp<EffectChain>& chain) = 0;
180 // remove an effect chain from the chain list (mEffectChains)
181 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain) = 0;
182 // lock all effect chains Mutexes. Must be called before releasing the
183 // ThreadBase mutex before processing the mixer and effects. This guarantees the
184 // integrity of the chains during the process.
185 // Also sets the parameter 'effectChains' to current value of mEffectChains.
186 void lockEffectChains_l(Vector< sp<EffectChain> >& effectChains);
187 // unlock effect chains after process
188 void unlockEffectChains(const Vector< sp<EffectChain> >& effectChains);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800189 // get a copy of mEffectChains vector
190 Vector< sp<EffectChain> > getEffectChains_l() const { return mEffectChains; };
Eric Laurent81784c32012-11-19 14:55:58 -0800191 // set audio mode to all effect chains
192 void setMode(audio_mode_t mode);
193 // get effect module with corresponding ID on specified audio session
194 sp<AudioFlinger::EffectModule> getEffect(int sessionId, int effectId);
195 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
196 // add and effect module. Also creates the effect chain is none exists for
197 // the effects audio session
198 status_t addEffect_l(const sp< EffectModule>& effect);
199 // remove and effect module. Also removes the effect chain is this was the last
200 // effect
201 void removeEffect_l(const sp< EffectModule>& effect);
202 // detach all tracks connected to an auxiliary effect
203 virtual void detachAuxEffect_l(int effectId) {}
204 // returns either EFFECT_SESSION if effects on this audio session exist in one
205 // chain, or TRACK_SESSION if tracks on this audio session exist, or both
206 virtual uint32_t hasAudioSession(int sessionId) const = 0;
207 // the value returned by default implementation is not important as the
208 // strategy is only meaningful for PlaybackThread which implements this method
209 virtual uint32_t getStrategyForSession_l(int sessionId) { return 0; }
210
211 // suspend or restore effect according to the type of effect passed. a NULL
212 // type pointer means suspend all effects in the session
213 void setEffectSuspended(const effect_uuid_t *type,
214 bool suspend,
215 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
216 // check if some effects must be suspended/restored when an effect is enabled
217 // or disabled
218 void checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
219 bool enabled,
220 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
221 void checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
222 bool enabled,
223 int sessionId = AUDIO_SESSION_OUTPUT_MIX);
224
225 virtual status_t setSyncEvent(const sp<SyncEvent>& event) = 0;
226 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const = 0;
227
228
229 mutable Mutex mLock;
230
231protected:
232
233 // entry describing an effect being suspended in mSuspendedSessions keyed vector
234 class SuspendedSessionDesc : public RefBase {
235 public:
236 SuspendedSessionDesc() : mRefCount(0) {}
237
238 int mRefCount; // number of active suspend requests
239 effect_uuid_t mType; // effect type UUID
240 };
241
Marco Nelissene14a5d62013-10-03 08:51:24 -0700242 void acquireWakeLock(int uid = -1);
243 void acquireWakeLock_l(int uid = -1);
Eric Laurent81784c32012-11-19 14:55:58 -0800244 void releaseWakeLock();
245 void releaseWakeLock_l();
246 void setEffectSuspended_l(const effect_uuid_t *type,
247 bool suspend,
248 int sessionId);
249 // updated mSuspendedSessions when an effect suspended or restored
250 void updateSuspendedSessions_l(const effect_uuid_t *type,
251 bool suspend,
252 int sessionId);
253 // check if some effects must be suspended when an effect chain is added
254 void checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain);
255
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100256 String16 getWakeLockTag();
257
Eric Laurent81784c32012-11-19 14:55:58 -0800258 virtual void preExit() { }
259
260 friend class AudioFlinger; // for mEffectChains
261
262 const type_t mType;
263
264 // Used by parameters, config events, addTrack_l, exit
265 Condition mWaitWorkCV;
266
267 const sp<AudioFlinger> mAudioFlinger;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700268
269 // updated by PlaybackThread::readOutputParameters() or
270 // RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800271 uint32_t mSampleRate;
272 size_t mFrameCount; // output HAL, direct output, record
Eric Laurent81784c32012-11-19 14:55:58 -0800273 audio_channel_mask_t mChannelMask;
Glenn Kastenf6ed4232013-07-16 11:16:27 -0700274 uint32_t mChannelCount;
Eric Laurent81784c32012-11-19 14:55:58 -0800275 size_t mFrameSize;
276 audio_format_t mFormat;
277
278 // Parameter sequence by client: binder thread calling setParameters():
279 // 1. Lock mLock
280 // 2. Append to mNewParameters
281 // 3. mWaitWorkCV.signal
282 // 4. mParamCond.waitRelative with timeout
283 // 5. read mParamStatus
284 // 6. mWaitWorkCV.signal
285 // 7. Unlock
286 //
287 // Parameter sequence by server: threadLoop calling checkForNewParameters_l():
288 // 1. Lock mLock
289 // 2. If there is an entry in mNewParameters proceed ...
290 // 2. Read first entry in mNewParameters
291 // 3. Process
292 // 4. Remove first entry from mNewParameters
293 // 5. Set mParamStatus
294 // 6. mParamCond.signal
295 // 7. mWaitWorkCV.wait with timeout (this is to avoid overwriting mParamStatus)
296 // 8. Unlock
297 Condition mParamCond;
298 Vector<String8> mNewParameters;
299 status_t mParamStatus;
300
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700301 // vector owns each ConfigEvent *, so must delete after removing
Eric Laurent81784c32012-11-19 14:55:58 -0800302 Vector<ConfigEvent *> mConfigEvents;
303
304 // These fields are written and read by thread itself without lock or barrier,
305 // and read by other threads without lock or barrier via standby() , outDevice()
306 // and inDevice().
307 // Because of the absence of a lock or barrier, any other thread that reads
308 // these fields must use the information in isolation, or be prepared to deal
309 // with possibility that it might be inconsistent with other information.
310 bool mStandby; // Whether thread is currently in standby.
311 audio_devices_t mOutDevice; // output device
312 audio_devices_t mInDevice; // input device
313 audio_source_t mAudioSource; // (see audio.h, audio_source_t)
314
315 const audio_io_handle_t mId;
316 Vector< sp<EffectChain> > mEffectChains;
317
318 static const int kNameLength = 16; // prctl(PR_SET_NAME) limit
319 char mName[kNameLength];
320 sp<IPowerManager> mPowerManager;
321 sp<IBinder> mWakeLockToken;
322 const sp<PMDeathRecipient> mDeathRecipient;
323 // list of suspended effects per session and per type. The first vector is
324 // keyed by session ID, the second by type UUID timeLow field
325 KeyedVector< int, KeyedVector< int, sp<SuspendedSessionDesc> > >
326 mSuspendedSessions;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800327 static const size_t kLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800328 sp<NBLog::Writer> mNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800329};
330
331// --- PlaybackThread ---
332class PlaybackThread : public ThreadBase {
333public:
334
335#include "PlaybackTracks.h"
336
337 enum mixer_state {
338 MIXER_IDLE, // no active tracks
339 MIXER_TRACKS_ENABLED, // at least one active track, but no track has any data ready
Eric Laurentbfb1b832013-01-07 09:53:42 -0800340 MIXER_TRACKS_READY, // at least one active track, and at least one track has data
341 MIXER_DRAIN_TRACK, // drain currently playing track
342 MIXER_DRAIN_ALL, // fully drain the hardware
Eric Laurent81784c32012-11-19 14:55:58 -0800343 // standby mode does not have an enum value
344 // suspend by audio policy manager is orthogonal to mixer state
345 };
346
Eric Laurentbfb1b832013-01-07 09:53:42 -0800347 // retry count before removing active track in case of underrun on offloaded thread:
348 // we need to make sure that AudioTrack client has enough time to send large buffers
349//FIXME may be more appropriate if expressed in time units. Need to revise how underrun is handled
350 // for offloaded tracks
351 static const int8_t kMaxTrackRetriesOffload = 20;
352
Eric Laurent81784c32012-11-19 14:55:58 -0800353 PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
354 audio_io_handle_t id, audio_devices_t device, type_t type);
355 virtual ~PlaybackThread();
356
357 void dump(int fd, const Vector<String16>& args);
358
359 // Thread virtuals
360 virtual status_t readyToRun();
361 virtual bool threadLoop();
362
363 // RefBase
364 virtual void onFirstRef();
365
366protected:
367 // Code snippets that were lifted up out of threadLoop()
368 virtual void threadLoop_mix() = 0;
369 virtual void threadLoop_sleepTime() = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800370 virtual ssize_t threadLoop_write();
371 virtual void threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -0800372 virtual void threadLoop_standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800373 virtual void threadLoop_exit();
Eric Laurent81784c32012-11-19 14:55:58 -0800374 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
375
376 // prepareTracks_l reads and writes mActiveTracks, and returns
377 // the pending set of tracks to remove via Vector 'tracksToRemove'. The caller
378 // is responsible for clearing or destroying this Vector later on, when it
379 // is safe to do so. That will drop the final ref count and destroy the tracks.
380 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove) = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800381 void removeTracks_l(const Vector< sp<Track> >& tracksToRemove);
382
383 void writeCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700384 void resetWriteBlocked(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800385 void drainCallback();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700386 void resetDraining(uint32_t sequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800387
388 static int asyncCallback(stream_callback_event_t event, void *param, void *cookie);
389
390 virtual bool waitingAsyncCallback();
391 virtual bool waitingAsyncCallback_l();
392 virtual bool shouldStandby_l();
393
Eric Laurent81784c32012-11-19 14:55:58 -0800394
395 // ThreadBase virtuals
396 virtual void preExit();
397
398public:
399
400 virtual status_t initCheck() const { return (mOutput == NULL) ? NO_INIT : NO_ERROR; }
401
402 // return estimated latency in milliseconds, as reported by HAL
403 uint32_t latency() const;
404 // same, but lock must already be held
405 uint32_t latency_l() const;
406
407 void setMasterVolume(float value);
408 void setMasterMute(bool muted);
409
410 void setStreamVolume(audio_stream_type_t stream, float value);
411 void setStreamMute(audio_stream_type_t stream, bool muted);
412
413 float streamVolume(audio_stream_type_t stream) const;
414
415 sp<Track> createTrack_l(
416 const sp<AudioFlinger::Client>& client,
417 audio_stream_type_t streamType,
418 uint32_t sampleRate,
419 audio_format_t format,
420 audio_channel_mask_t channelMask,
421 size_t frameCount,
422 const sp<IMemory>& sharedBuffer,
423 int sessionId,
424 IAudioFlinger::track_flags_t *flags,
425 pid_t tid,
426 status_t *status);
427
428 AudioStreamOut* getOutput() const;
429 AudioStreamOut* clearOutput();
430 virtual audio_stream_t* stream() const;
431
432 // a very large number of suspend() will eventually wraparound, but unlikely
433 void suspend() { (void) android_atomic_inc(&mSuspended); }
434 void restore()
435 {
436 // if restore() is done without suspend(), get back into
437 // range so that the next suspend() will operate correctly
438 if (android_atomic_dec(&mSuspended) <= 0) {
439 android_atomic_release_store(0, &mSuspended);
440 }
441 }
442 bool isSuspended() const
443 { return android_atomic_acquire_load(&mSuspended) > 0; }
444
445 virtual String8 getParameters(const String8& keys);
446 virtual void audioConfigChanged_l(int event, int param = 0);
447 status_t getRenderPosition(size_t *halFrames, size_t *dspFrames);
448 int16_t *mixBuffer() const { return mMixBuffer; };
449
450 virtual void detachAuxEffect_l(int effectId);
451 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
452 int EffectId);
453 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
454 int EffectId);
455
456 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
457 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
458 virtual uint32_t hasAudioSession(int sessionId) const;
459 virtual uint32_t getStrategyForSession_l(int sessionId);
460
461
462 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
463 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
Glenn Kastenfb1fdc92013-07-10 17:03:19 -0700464
465 // called with AudioFlinger lock held
Eric Laurent81784c32012-11-19 14:55:58 -0800466 void invalidateTracks(audio_stream_type_t streamType);
467
Glenn Kasten9b58f632013-07-16 11:37:48 -0700468 virtual size_t frameCount() const { return mNormalFrameCount; }
469
470 // Return's the HAL's frame count i.e. fast mixer buffer size.
471 size_t frameCountHAL() const { return mFrameCount; }
Eric Laurent81784c32012-11-19 14:55:58 -0800472
Eric Laurentaccc1472013-09-20 09:36:34 -0700473 status_t getTimestamp_l(AudioTimestamp& timestamp);
474
Eric Laurent81784c32012-11-19 14:55:58 -0800475protected:
Glenn Kasten9b58f632013-07-16 11:37:48 -0700476 // updated by readOutputParameters()
477 size_t mNormalFrameCount; // normal mixer and effects
478
Eric Laurentbfb1b832013-01-07 09:53:42 -0800479 int16_t* mMixBuffer; // frame size aligned mix buffer
480 int8_t* mAllocMixBuffer; // mixer buffer allocation address
Eric Laurent81784c32012-11-19 14:55:58 -0800481
482 // suspend count, > 0 means suspended. While suspended, the thread continues to pull from
483 // tracks and mix, but doesn't write to HAL. A2DP and SCO HAL implementations can't handle
484 // concurrent use of both of them, so Audio Policy Service suspends one of the threads to
485 // workaround that restriction.
486 // 'volatile' means accessed via atomic operations and no lock.
487 volatile int32_t mSuspended;
488
489 // FIXME overflows every 6+ hours at 44.1 kHz stereo 16-bit samples
490 // mFramesWritten would be better, or 64-bit even better
491 size_t mBytesWritten;
492private:
493 // mMasterMute is in both PlaybackThread and in AudioFlinger. When a
494 // PlaybackThread needs to find out if master-muted, it checks it's local
495 // copy rather than the one in AudioFlinger. This optimization saves a lock.
496 bool mMasterMute;
497 void setMasterMute_l(bool muted) { mMasterMute = muted; }
498protected:
499 SortedVector< wp<Track> > mActiveTracks; // FIXME check if this could be sp<>
500
501 // Allocate a track name for a given channel mask.
502 // Returns name >= 0 if successful, -1 on failure.
503 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId) = 0;
504 virtual void deleteTrackName_l(int name) = 0;
505
506 // Time to sleep between cycles when:
507 virtual uint32_t activeSleepTimeUs() const; // mixer state MIXER_TRACKS_ENABLED
508 virtual uint32_t idleSleepTimeUs() const = 0; // mixer state MIXER_IDLE
509 virtual uint32_t suspendSleepTimeUs() const = 0; // audio policy manager suspended us
510 // No sleep when mixer state == MIXER_TRACKS_READY; relies on audio HAL stream->write()
511 // No sleep in standby mode; waits on a condition
512
513 // Code snippets that are temporarily lifted up out of threadLoop() until the merge
514 void checkSilentMode_l();
515
516 // Non-trivial for DUPLICATING only
517 virtual void saveOutputTracks() { }
518 virtual void clearOutputTracks() { }
519
520 // Cache various calculated values, at threadLoop() entry and after a parameter change
521 virtual void cacheParameters_l();
522
523 virtual uint32_t correctLatency_l(uint32_t latency) const;
524
525private:
526
527 friend class AudioFlinger; // for numerous
528
529 PlaybackThread(const Client&);
530 PlaybackThread& operator = (const PlaybackThread&);
531
532 status_t addTrack_l(const sp<Track>& track);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800533 bool destroyTrack_l(const sp<Track>& track);
Eric Laurent81784c32012-11-19 14:55:58 -0800534 void removeTrack_l(const sp<Track>& track);
Eric Laurentede6c3b2013-09-19 14:37:46 -0700535 void broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800536
537 void readOutputParameters();
538
539 virtual void dumpInternals(int fd, const Vector<String16>& args);
540 void dumpTracks(int fd, const Vector<String16>& args);
541
542 SortedVector< sp<Track> > mTracks;
543 // mStreamTypes[] uses 1 additional stream type internally for the OutputTrack used by
544 // DuplicatingThread
545 stream_type_t mStreamTypes[AUDIO_STREAM_CNT + 1];
546 AudioStreamOut *mOutput;
547
548 float mMasterVolume;
549 nsecs_t mLastWriteTime;
550 int mNumWrites;
551 int mNumDelayedWrites;
552 bool mInWrite;
553
554 // FIXME rename these former local variables of threadLoop to standard "m" names
555 nsecs_t standbyTime;
556 size_t mixBufferSize;
557
558 // cached copies of activeSleepTimeUs() and idleSleepTimeUs() made by cacheParameters_l()
559 uint32_t activeSleepTime;
560 uint32_t idleSleepTime;
561
562 uint32_t sleepTime;
563
564 // mixer status returned by prepareTracks_l()
565 mixer_state mMixerStatus; // current cycle
566 // previous cycle when in prepareTracks_l()
567 mixer_state mMixerStatusIgnoringFastTracks;
568 // FIXME or a separate ready state per track
569
570 // FIXME move these declarations into the specific sub-class that needs them
571 // MIXER only
572 uint32_t sleepTimeShift;
573
574 // same as AudioFlinger::mStandbyTimeInNsecs except for DIRECT which uses a shorter value
575 nsecs_t standbyDelay;
576
577 // MIXER only
578 nsecs_t maxPeriod;
579
580 // DUPLICATING only
581 uint32_t writeFrames;
582
Eric Laurentbfb1b832013-01-07 09:53:42 -0800583 size_t mBytesRemaining;
584 size_t mCurrentWriteLength;
585 bool mUseAsyncWrite;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700586 // mWriteAckSequence contains current write sequence on bits 31-1. The write sequence is
587 // incremented each time a write(), a flush() or a standby() occurs.
588 // Bit 0 is set when a write blocks and indicates a callback is expected.
589 // Bit 0 is reset by the async callback thread calling resetWriteBlocked(). Out of sequence
590 // callbacks are ignored.
591 uint32_t mWriteAckSequence;
592 // mDrainSequence contains current drain sequence on bits 31-1. The drain sequence is
593 // incremented each time a drain is requested or a flush() or standby() occurs.
594 // Bit 0 is set when the drain() command is called at the HAL and indicates a callback is
595 // expected.
596 // Bit 0 is reset by the async callback thread calling resetDraining(). Out of sequence
597 // callbacks are ignored.
598 uint32_t mDrainSequence;
Eric Laurentede6c3b2013-09-19 14:37:46 -0700599 // A condition that must be evaluated by prepareTrack_l() has changed and we must not wait
600 // for async write callback in the thread loop before evaluating it
Eric Laurentbfb1b832013-01-07 09:53:42 -0800601 bool mSignalPending;
602 sp<AsyncCallbackThread> mCallbackThread;
603
Eric Laurent81784c32012-11-19 14:55:58 -0800604private:
605 // The HAL output sink is treated as non-blocking, but current implementation is blocking
606 sp<NBAIO_Sink> mOutputSink;
607 // If a fast mixer is present, the blocking pipe sink, otherwise clear
608 sp<NBAIO_Sink> mPipeSink;
609 // The current sink for the normal mixer to write it's (sub)mix, mOutputSink or mPipeSink
610 sp<NBAIO_Sink> mNormalSink;
Glenn Kasten46909e72013-02-26 09:20:22 -0800611#ifdef TEE_SINK
Eric Laurent81784c32012-11-19 14:55:58 -0800612 // For dumpsys
613 sp<NBAIO_Sink> mTeeSink;
614 sp<NBAIO_Source> mTeeSource;
Glenn Kasten46909e72013-02-26 09:20:22 -0800615#endif
Eric Laurent81784c32012-11-19 14:55:58 -0800616 uint32_t mScreenState; // cached copy of gScreenState
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800617 static const size_t kFastMixerLogSize = 4 * 1024;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800618 sp<NBLog::Writer> mFastMixerNBLogWriter;
Eric Laurent81784c32012-11-19 14:55:58 -0800619public:
620 virtual bool hasFastMixer() const = 0;
621 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const
622 { FastTrackUnderruns dummy; return dummy; }
623
624protected:
625 // accessed by both binder threads and within threadLoop(), lock on mutex needed
626 unsigned mFastTrackAvailMask; // bit i set if fast track [i] is available
Eric Laurentbfb1b832013-01-07 09:53:42 -0800627 virtual void flushOutput_l();
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700628
629private:
630 // timestamp latch:
631 // D input is written by threadLoop_write while mutex is unlocked, and read while locked
632 // Q output is written while locked, and read while locked
633 struct {
634 AudioTimestamp mTimestamp;
635 uint32_t mUnpresentedFrames;
636 } mLatchD, mLatchQ;
637 bool mLatchDValid; // true means mLatchD is valid, and clock it into latch at next opportunity
638 bool mLatchQValid; // true means mLatchQ is valid
Eric Laurent81784c32012-11-19 14:55:58 -0800639};
640
641class MixerThread : public PlaybackThread {
642public:
643 MixerThread(const sp<AudioFlinger>& audioFlinger,
644 AudioStreamOut* output,
645 audio_io_handle_t id,
646 audio_devices_t device,
647 type_t type = MIXER);
648 virtual ~MixerThread();
649
650 // Thread virtuals
651
652 virtual bool checkForNewParameters_l();
653 virtual void dumpInternals(int fd, const Vector<String16>& args);
654
655protected:
656 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
657 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
658 virtual void deleteTrackName_l(int name);
659 virtual uint32_t idleSleepTimeUs() const;
660 virtual uint32_t suspendSleepTimeUs() const;
661 virtual void cacheParameters_l();
662
663 // threadLoop snippets
Eric Laurentbfb1b832013-01-07 09:53:42 -0800664 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800665 virtual void threadLoop_standby();
666 virtual void threadLoop_mix();
667 virtual void threadLoop_sleepTime();
668 virtual void threadLoop_removeTracks(const Vector< sp<Track> >& tracksToRemove);
669 virtual uint32_t correctLatency_l(uint32_t latency) const;
670
671 AudioMixer* mAudioMixer; // normal mixer
672private:
673 // one-time initialization, no locks required
674 FastMixer* mFastMixer; // non-NULL if there is also a fast mixer
675 sp<AudioWatchdog> mAudioWatchdog; // non-0 if there is an audio watchdog thread
676
677 // contents are not guaranteed to be consistent, no locks required
678 FastMixerDumpState mFastMixerDumpState;
679#ifdef STATE_QUEUE_DUMP
680 StateQueueObserverDump mStateQueueObserverDump;
681 StateQueueMutatorDump mStateQueueMutatorDump;
682#endif
683 AudioWatchdogDump mAudioWatchdogDump;
684
685 // accessible only within the threadLoop(), no locks required
686 // mFastMixer->sq() // for mutating and pushing state
687 int32_t mFastMixerFutex; // for cold idle
688
689public:
690 virtual bool hasFastMixer() const { return mFastMixer != NULL; }
691 virtual FastTrackUnderruns getFastTrackUnderruns(size_t fastIndex) const {
692 ALOG_ASSERT(fastIndex < FastMixerState::kMaxFastTracks);
693 return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
694 }
695};
696
697class DirectOutputThread : public PlaybackThread {
698public:
699
700 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
701 audio_io_handle_t id, audio_devices_t device);
702 virtual ~DirectOutputThread();
703
704 // Thread virtuals
705
706 virtual bool checkForNewParameters_l();
707
708protected:
709 virtual int getTrackName_l(audio_channel_mask_t channelMask, int sessionId);
710 virtual void deleteTrackName_l(int name);
711 virtual uint32_t activeSleepTimeUs() const;
712 virtual uint32_t idleSleepTimeUs() const;
713 virtual uint32_t suspendSleepTimeUs() const;
714 virtual void cacheParameters_l();
715
716 // threadLoop snippets
717 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
718 virtual void threadLoop_mix();
719 virtual void threadLoop_sleepTime();
720
Eric Laurent81784c32012-11-19 14:55:58 -0800721 // volumes last sent to audio HAL with stream->set_volume()
722 float mLeftVolFloat;
723 float mRightVolFloat;
724
Eric Laurentbfb1b832013-01-07 09:53:42 -0800725 DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
726 audio_io_handle_t id, uint32_t device, ThreadBase::type_t type);
727 void processVolume_l(Track *track, bool lastTrack);
728
Eric Laurent81784c32012-11-19 14:55:58 -0800729 // prepareTracks_l() tells threadLoop_mix() the name of the single active track
730 sp<Track> mActiveTrack;
731public:
732 virtual bool hasFastMixer() const { return false; }
733};
734
Eric Laurentbfb1b832013-01-07 09:53:42 -0800735class OffloadThread : public DirectOutputThread {
736public:
737
738 OffloadThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
739 audio_io_handle_t id, uint32_t device);
Eric Laurent6a99d202013-10-17 18:59:26 -0700740 virtual ~OffloadThread() {};
Eric Laurentbfb1b832013-01-07 09:53:42 -0800741
742protected:
743 // threadLoop snippets
744 virtual mixer_state prepareTracks_l(Vector< sp<Track> > *tracksToRemove);
745 virtual void threadLoop_exit();
746 virtual void flushOutput_l();
747
748 virtual bool waitingAsyncCallback();
749 virtual bool waitingAsyncCallback_l();
750 virtual bool shouldStandby_l();
751
752private:
753 void flushHw_l();
754
755private:
756 bool mHwPaused;
757 bool mFlushPending;
758 size_t mPausedWriteLength; // length in bytes of write interrupted by pause
759 size_t mPausedBytesRemaining; // bytes still waiting in mixbuffer after resume
Eric Laurent6a99d202013-10-17 18:59:26 -0700760 Track *mPreviousTrack; // used to detect track switch
Eric Laurentbfb1b832013-01-07 09:53:42 -0800761};
762
763class AsyncCallbackThread : public Thread {
764public:
765
Eric Laurent4de95592013-09-26 15:28:21 -0700766 AsyncCallbackThread(const wp<PlaybackThread>& playbackThread);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800767
768 virtual ~AsyncCallbackThread();
769
770 // Thread virtuals
771 virtual bool threadLoop();
772
773 // RefBase
774 virtual void onFirstRef();
775
776 void exit();
Eric Laurent3b4529e2013-09-05 18:09:19 -0700777 void setWriteBlocked(uint32_t sequence);
778 void resetWriteBlocked();
779 void setDraining(uint32_t sequence);
780 void resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800781
782private:
Eric Laurent4de95592013-09-26 15:28:21 -0700783 const wp<PlaybackThread> mPlaybackThread;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700784 // mWriteAckSequence corresponds to the last write sequence passed by the offload thread via
785 // setWriteBlocked(). The sequence is shifted one bit to the left and the lsb is used
786 // to indicate that the callback has been received via resetWriteBlocked()
Eric Laurent4de95592013-09-26 15:28:21 -0700787 uint32_t mWriteAckSequence;
Eric Laurent3b4529e2013-09-05 18:09:19 -0700788 // mDrainSequence corresponds to the last drain sequence passed by the offload thread via
789 // setDraining(). The sequence is shifted one bit to the left and the lsb is used
790 // to indicate that the callback has been received via resetDraining()
Eric Laurent4de95592013-09-26 15:28:21 -0700791 uint32_t mDrainSequence;
792 Condition mWaitWorkCV;
793 Mutex mLock;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800794};
795
Eric Laurent81784c32012-11-19 14:55:58 -0800796class DuplicatingThread : public MixerThread {
797public:
798 DuplicatingThread(const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread,
799 audio_io_handle_t id);
800 virtual ~DuplicatingThread();
801
802 // Thread virtuals
803 void addOutputTrack(MixerThread* thread);
804 void removeOutputTrack(MixerThread* thread);
805 uint32_t waitTimeMs() const { return mWaitTimeMs; }
806protected:
807 virtual uint32_t activeSleepTimeUs() const;
808
809private:
810 bool outputsReady(const SortedVector< sp<OutputTrack> > &outputTracks);
811protected:
812 // threadLoop snippets
813 virtual void threadLoop_mix();
814 virtual void threadLoop_sleepTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -0800815 virtual ssize_t threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -0800816 virtual void threadLoop_standby();
817 virtual void cacheParameters_l();
818
819private:
820 // called from threadLoop, addOutputTrack, removeOutputTrack
821 virtual void updateWaitTime_l();
822protected:
823 virtual void saveOutputTracks();
824 virtual void clearOutputTracks();
825private:
826
827 uint32_t mWaitTimeMs;
828 SortedVector < sp<OutputTrack> > outputTracks;
829 SortedVector < sp<OutputTrack> > mOutputTracks;
830public:
831 virtual bool hasFastMixer() const { return false; }
832};
833
834
835// record thread
836class RecordThread : public ThreadBase, public AudioBufferProvider
837 // derives from AudioBufferProvider interface for use by resampler
838{
839public:
840
841#include "RecordTracks.h"
842
843 RecordThread(const sp<AudioFlinger>& audioFlinger,
844 AudioStreamIn *input,
845 uint32_t sampleRate,
846 audio_channel_mask_t channelMask,
847 audio_io_handle_t id,
Eric Laurentd3922f72013-02-01 17:57:04 -0800848 audio_devices_t outDevice,
Glenn Kasten46909e72013-02-26 09:20:22 -0800849 audio_devices_t inDevice
850#ifdef TEE_SINK
851 , const sp<NBAIO_Sink>& teeSink
852#endif
853 );
Eric Laurent81784c32012-11-19 14:55:58 -0800854 virtual ~RecordThread();
855
856 // no addTrack_l ?
857 void destroyTrack_l(const sp<RecordTrack>& track);
858 void removeTrack_l(const sp<RecordTrack>& track);
859
860 void dumpInternals(int fd, const Vector<String16>& args);
861 void dumpTracks(int fd, const Vector<String16>& args);
862
863 // Thread virtuals
864 virtual bool threadLoop();
865 virtual status_t readyToRun();
866
867 // RefBase
868 virtual void onFirstRef();
869
870 virtual status_t initCheck() const { return (mInput == NULL) ? NO_INIT : NO_ERROR; }
871 sp<AudioFlinger::RecordThread::RecordTrack> createRecordTrack_l(
872 const sp<AudioFlinger::Client>& client,
873 uint32_t sampleRate,
874 audio_format_t format,
875 audio_channel_mask_t channelMask,
876 size_t frameCount,
877 int sessionId,
Glenn Kastenddb0ccf2013-07-31 16:14:50 -0700878 IAudioFlinger::track_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -0800879 pid_t tid,
880 status_t *status);
881
882 status_t start(RecordTrack* recordTrack,
883 AudioSystem::sync_event_t event,
884 int triggerSession);
885
886 // ask the thread to stop the specified track, and
887 // return true if the caller should then do it's part of the stopping process
Glenn Kastena8356f62013-07-25 14:37:52 -0700888 bool stop(RecordTrack* recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -0800889
890 void dump(int fd, const Vector<String16>& args);
891 AudioStreamIn* clearInput();
892 virtual audio_stream_t* stream() const;
893
894 // AudioBufferProvider interface
895 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts);
896 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
897
898 virtual bool checkForNewParameters_l();
899 virtual String8 getParameters(const String8& keys);
900 virtual void audioConfigChanged_l(int event, int param = 0);
901 void readInputParameters();
902 virtual unsigned int getInputFramesLost();
903
904 virtual status_t addEffectChain_l(const sp<EffectChain>& chain);
905 virtual size_t removeEffectChain_l(const sp<EffectChain>& chain);
906 virtual uint32_t hasAudioSession(int sessionId) const;
907
908 // Return the set of unique session IDs across all tracks.
909 // The keys are the session IDs, and the associated values are meaningless.
910 // FIXME replace by Set [and implement Bag/Multiset for other uses].
911 KeyedVector<int, bool> sessionIds() const;
912
913 virtual status_t setSyncEvent(const sp<SyncEvent>& event);
914 virtual bool isValidSyncEvent(const sp<SyncEvent>& event) const;
915
916 static void syncStartEventCallback(const wp<SyncEvent>& event);
917 void handleSyncStartEvent(const sp<SyncEvent>& event);
918
Glenn Kasten9b58f632013-07-16 11:37:48 -0700919 virtual size_t frameCount() const { return mFrameCount; }
Glenn Kasten90e58b12013-07-31 16:16:02 -0700920 bool hasFastRecorder() const { return false; }
Glenn Kasten9b58f632013-07-16 11:37:48 -0700921
Eric Laurent81784c32012-11-19 14:55:58 -0800922private:
923 void clearSyncStartEvent();
924
925 // Enter standby if not already in standby, and set mStandby flag
926 void standby();
927
928 // Call the HAL standby method unconditionally, and don't change mStandby flag
929 void inputStandBy();
930
931 AudioStreamIn *mInput;
932 SortedVector < sp<RecordTrack> > mTracks;
933 // mActiveTrack has dual roles: it indicates the current active track, and
934 // is used together with mStartStopCond to indicate start()/stop() progress
935 sp<RecordTrack> mActiveTrack;
936 Condition mStartStopCond;
Glenn Kasten9b58f632013-07-16 11:37:48 -0700937
938 // updated by RecordThread::readInputParameters()
Eric Laurent81784c32012-11-19 14:55:58 -0800939 AudioResampler *mResampler;
Glenn Kasten34af0262013-07-30 11:52:39 -0700940 // interleaved stereo pairs of fixed-point signed Q19.12
Eric Laurent81784c32012-11-19 14:55:58 -0800941 int32_t *mRsmpOutBuffer;
Glenn Kasten34af0262013-07-30 11:52:39 -0700942 int16_t *mRsmpInBuffer; // [mFrameCount * mChannelCount]
Eric Laurent81784c32012-11-19 14:55:58 -0800943 size_t mRsmpInIndex;
Glenn Kasten548efc92012-11-29 08:48:51 -0800944 size_t mBufferSize; // stream buffer size for read()
Eric Laurent81784c32012-11-19 14:55:58 -0800945 const uint32_t mReqChannelCount;
946 const uint32_t mReqSampleRate;
947 ssize_t mBytesRead;
948 // sync event triggering actual audio capture. Frames read before this event will
949 // be dropped and therefore not read by the application.
950 sp<SyncEvent> mSyncStartEvent;
951 // number of captured frames to drop after the start sync event has been received.
952 // when < 0, maximum frames to drop before starting capture even if sync event is
953 // not received
954 ssize_t mFramestoDrop;
955
956 // For dumpsys
957 const sp<NBAIO_Sink> mTeeSink;
Marco Nelissene14a5d62013-10-03 08:51:24 -0700958 int mClientUid;
Eric Laurent81784c32012-11-19 14:55:58 -0800959};