blob: 51881f01567ace66ef94a75042914d7ad05af1c6 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.h
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#ifndef ANDROID_AUDIO_FLINGER_H
19#define ANDROID_AUDIO_FLINGER_H
20
21#include <stdint.h>
22#include <sys/types.h>
23#include <limits.h>
24
25#include <media/IAudioFlinger.h>
26#include <media/IAudioFlingerClient.h>
27#include <media/IAudioTrack.h>
28#include <media/IAudioRecord.h>
29#include <media/AudioTrack.h>
30
31#include <utils/Atomic.h>
32#include <utils/Errors.h>
33#include <utils/threads.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <utils/SortedVector.h>
35#include <utils/Vector.h>
36
Mathias Agopian5462fc92010-07-14 18:41:18 -070037#include <binder/BinderService.h>
38#include <binder/MemoryDealer.h>
39
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <hardware_legacy/AudioHardwareInterface.h>
41
42#include "AudioBufferProvider.h"
43
44namespace android {
45
46class audio_track_cblk_t;
47class effect_param_cblk_t;
48class AudioMixer;
49class AudioBuffer;
50class AudioResampler;
51
52
53// ----------------------------------------------------------------------------
54
55#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
56#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
57
58
59// ----------------------------------------------------------------------------
60
61static const nsecs_t kStandbyTimeInNsecs = seconds(3);
62
Mathias Agopian5462fc92010-07-14 18:41:18 -070063class AudioFlinger :
64 public BinderService<AudioFlinger>,
65 public BnAudioFlinger
Mathias Agopian65ab4712010-07-14 17:59:35 -070066{
Mathias Agopian5462fc92010-07-14 18:41:18 -070067 friend class BinderService<AudioFlinger>;
Mathias Agopian65ab4712010-07-14 17:59:35 -070068public:
Mathias Agopian5462fc92010-07-14 18:41:18 -070069 static char const* getServiceName() { return "media.audio_flinger"; }
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71 virtual status_t dump(int fd, const Vector<String16>& args);
72
73 // IAudioFlinger interface
74 virtual sp<IAudioTrack> createTrack(
75 pid_t pid,
76 int streamType,
77 uint32_t sampleRate,
78 int format,
79 int channelCount,
80 int frameCount,
81 uint32_t flags,
82 const sp<IMemory>& sharedBuffer,
83 int output,
84 int *sessionId,
85 status_t *status);
86
87 virtual uint32_t sampleRate(int output) const;
88 virtual int channelCount(int output) const;
89 virtual int format(int output) const;
90 virtual size_t frameCount(int output) const;
91 virtual uint32_t latency(int output) const;
92
93 virtual status_t setMasterVolume(float value);
94 virtual status_t setMasterMute(bool muted);
95
96 virtual float masterVolume() const;
97 virtual bool masterMute() const;
98
99 virtual status_t setStreamVolume(int stream, float value, int output);
100 virtual status_t setStreamMute(int stream, bool muted);
101
102 virtual float streamVolume(int stream, int output) const;
103 virtual bool streamMute(int stream) const;
104
105 virtual status_t setMode(int mode);
106
107 virtual status_t setMicMute(bool state);
108 virtual bool getMicMute() const;
109
110 virtual bool isStreamActive(int stream) const;
111
112 virtual status_t setParameters(int ioHandle, const String8& keyValuePairs);
113 virtual String8 getParameters(int ioHandle, const String8& keys);
114
115 virtual void registerClient(const sp<IAudioFlingerClient>& client);
116
117 virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount);
118 virtual unsigned int getInputFramesLost(int ioHandle);
119
120 virtual int openOutput(uint32_t *pDevices,
121 uint32_t *pSamplingRate,
122 uint32_t *pFormat,
123 uint32_t *pChannels,
124 uint32_t *pLatencyMs,
125 uint32_t flags);
126
127 virtual int openDuplicateOutput(int output1, int output2);
128
129 virtual status_t closeOutput(int output);
130
131 virtual status_t suspendOutput(int output);
132
133 virtual status_t restoreOutput(int output);
134
135 virtual int openInput(uint32_t *pDevices,
136 uint32_t *pSamplingRate,
137 uint32_t *pFormat,
138 uint32_t *pChannels,
139 uint32_t acoustics);
140
141 virtual status_t closeInput(int input);
142
143 virtual status_t setStreamOutput(uint32_t stream, int output);
144
145 virtual status_t setVoiceVolume(float volume);
146
147 virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output);
148
149 virtual int newAudioSessionId();
150
151 virtual status_t loadEffectLibrary(const char *libPath, int *handle);
152
153 virtual status_t unloadEffectLibrary(int handle);
154
155 virtual status_t queryNumberEffects(uint32_t *numEffects);
156
157 virtual status_t queryEffect(uint32_t index, effect_descriptor_t *descriptor);
158
159 virtual status_t getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor);
160
161 virtual sp<IEffect> createEffect(pid_t pid,
162 effect_descriptor_t *pDesc,
163 const sp<IEffectClient>& effectClient,
164 int32_t priority,
165 int output,
166 int sessionId,
167 status_t *status,
168 int *id,
169 int *enabled);
170
Eric Laurentde070132010-07-13 04:45:46 -0700171 virtual status_t moveEffects(int session, int srcOutput, int dstOutput);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700172
173 enum hardware_call_state {
174 AUDIO_HW_IDLE = 0,
175 AUDIO_HW_INIT,
176 AUDIO_HW_OUTPUT_OPEN,
177 AUDIO_HW_OUTPUT_CLOSE,
178 AUDIO_HW_INPUT_OPEN,
179 AUDIO_HW_INPUT_CLOSE,
180 AUDIO_HW_STANDBY,
181 AUDIO_HW_SET_MASTER_VOLUME,
182 AUDIO_HW_GET_ROUTING,
183 AUDIO_HW_SET_ROUTING,
184 AUDIO_HW_GET_MODE,
185 AUDIO_HW_SET_MODE,
186 AUDIO_HW_GET_MIC_MUTE,
187 AUDIO_HW_SET_MIC_MUTE,
188 AUDIO_SET_VOICE_VOLUME,
189 AUDIO_SET_PARAMETER,
190 };
191
192 // record interface
193 virtual sp<IAudioRecord> openRecord(
194 pid_t pid,
195 int input,
196 uint32_t sampleRate,
197 int format,
198 int channelCount,
199 int frameCount,
200 uint32_t flags,
201 int *sessionId,
202 status_t *status);
203
204 virtual status_t onTransact(
205 uint32_t code,
206 const Parcel& data,
207 Parcel* reply,
208 uint32_t flags);
209
210 uint32_t getMode() { return mMode; }
211
212private:
213 AudioFlinger();
214 virtual ~AudioFlinger();
215
216
217 // Internal dump utilites.
218 status_t dumpPermissionDenial(int fd, const Vector<String16>& args);
219 status_t dumpClients(int fd, const Vector<String16>& args);
220 status_t dumpInternals(int fd, const Vector<String16>& args);
221
222 // --- Client ---
223 class Client : public RefBase {
224 public:
225 Client(const sp<AudioFlinger>& audioFlinger, pid_t pid);
226 virtual ~Client();
227 const sp<MemoryDealer>& heap() const;
228 pid_t pid() const { return mPid; }
229 sp<AudioFlinger> audioFlinger() { return mAudioFlinger; }
230
231 private:
232 Client(const Client&);
233 Client& operator = (const Client&);
234 sp<AudioFlinger> mAudioFlinger;
235 sp<MemoryDealer> mMemoryDealer;
236 pid_t mPid;
237 };
238
239 // --- Notification Client ---
240 class NotificationClient : public IBinder::DeathRecipient {
241 public:
242 NotificationClient(const sp<AudioFlinger>& audioFlinger,
243 const sp<IAudioFlingerClient>& client,
244 pid_t pid);
245 virtual ~NotificationClient();
246
247 sp<IAudioFlingerClient> client() { return mClient; }
248
249 // IBinder::DeathRecipient
250 virtual void binderDied(const wp<IBinder>& who);
251
252 private:
253 NotificationClient(const NotificationClient&);
254 NotificationClient& operator = (const NotificationClient&);
255
256 sp<AudioFlinger> mAudioFlinger;
257 pid_t mPid;
258 sp<IAudioFlingerClient> mClient;
259 };
260
261 class TrackHandle;
262 class RecordHandle;
263 class RecordThread;
264 class PlaybackThread;
265 class MixerThread;
266 class DirectOutputThread;
267 class DuplicatingThread;
268 class Track;
269 class RecordTrack;
270 class EffectModule;
271 class EffectHandle;
272 class EffectChain;
273
274 class ThreadBase : public Thread {
275 public:
276 ThreadBase (const sp<AudioFlinger>& audioFlinger, int id);
277 virtual ~ThreadBase();
278
279 status_t dumpBase(int fd, const Vector<String16>& args);
280
281 // base for record and playback
282 class TrackBase : public AudioBufferProvider, public RefBase {
283
284 public:
285 enum track_state {
286 IDLE,
287 TERMINATED,
288 STOPPED,
289 RESUMING,
290 ACTIVE,
291 PAUSING,
292 PAUSED
293 };
294
295 enum track_flags {
296 STEPSERVER_FAILED = 0x01, // StepServer could not acquire cblk->lock mutex
297 SYSTEM_FLAGS_MASK = 0x0000ffffUL,
298 // The upper 16 bits are used for track-specific flags.
299 };
300
301 TrackBase(const wp<ThreadBase>& thread,
302 const sp<Client>& client,
303 uint32_t sampleRate,
304 int format,
305 int channelCount,
306 int frameCount,
307 uint32_t flags,
308 const sp<IMemory>& sharedBuffer,
309 int sessionId);
310 ~TrackBase();
311
312 virtual status_t start() = 0;
313 virtual void stop() = 0;
314 sp<IMemory> getCblk() const;
315 audio_track_cblk_t* cblk() const { return mCblk; }
316 int sessionId() { return mSessionId; }
317
318 protected:
319 friend class ThreadBase;
320 friend class RecordHandle;
321 friend class PlaybackThread;
322 friend class RecordThread;
323 friend class MixerThread;
324 friend class DirectOutputThread;
325
326 TrackBase(const TrackBase&);
327 TrackBase& operator = (const TrackBase&);
328
329 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer) = 0;
330 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
331
332 int format() const {
333 return mFormat;
334 }
335
336 int channelCount() const ;
337
338 int sampleRate() const;
339
340 void* getBuffer(uint32_t offset, uint32_t frames) const;
341
342 bool isStopped() const {
343 return mState == STOPPED;
344 }
345
346 bool isTerminated() const {
347 return mState == TERMINATED;
348 }
349
350 bool step();
351 void reset();
352
353 wp<ThreadBase> mThread;
354 sp<Client> mClient;
355 sp<IMemory> mCblkMemory;
356 audio_track_cblk_t* mCblk;
357 void* mBuffer;
358 void* mBufferEnd;
359 uint32_t mFrameCount;
360 // we don't really need a lock for these
361 int mState;
362 int mClientTid;
363 uint8_t mFormat;
364 uint32_t mFlags;
365 int mSessionId;
366 };
367
368 class ConfigEvent {
369 public:
370 ConfigEvent() : mEvent(0), mParam(0) {}
371
372 int mEvent;
373 int mParam;
374 };
375
376 uint32_t sampleRate() const;
377 int channelCount() const;
378 int format() const;
379 size_t frameCount() const;
380 void wakeUp() { mWaitWorkCV.broadcast(); }
381 void exit();
382 virtual bool checkForNewParameters_l() = 0;
383 virtual status_t setParameters(const String8& keyValuePairs);
384 virtual String8 getParameters(const String8& keys) = 0;
385 virtual void audioConfigChanged_l(int event, int param = 0) = 0;
386 void sendConfigEvent(int event, int param = 0);
387 void sendConfigEvent_l(int event, int param = 0);
388 void processConfigEvents();
389 int id() const { return mId;}
390 bool standby() { return mStandby; }
391
392 mutable Mutex mLock;
393
394 protected:
395
396 friend class Track;
397 friend class TrackBase;
398 friend class PlaybackThread;
399 friend class MixerThread;
400 friend class DirectOutputThread;
401 friend class DuplicatingThread;
402 friend class RecordThread;
403 friend class RecordTrack;
404
405 Condition mWaitWorkCV;
406 sp<AudioFlinger> mAudioFlinger;
407 uint32_t mSampleRate;
408 size_t mFrameCount;
409 uint32_t mChannels;
410 uint16_t mChannelCount;
411 uint16_t mFrameSize;
412 int mFormat;
413 Condition mParamCond;
414 Vector<String8> mNewParameters;
415 status_t mParamStatus;
416 Vector<ConfigEvent *> mConfigEvents;
417 bool mStandby;
418 int mId;
419 bool mExiting;
420 };
421
422 // --- PlaybackThread ---
423 class PlaybackThread : public ThreadBase {
424 public:
425
426 enum type {
427 MIXER,
428 DIRECT,
429 DUPLICATING
430 };
431
432 enum mixer_state {
433 MIXER_IDLE,
434 MIXER_TRACKS_ENABLED,
435 MIXER_TRACKS_READY
436 };
437
438 // playback track
439 class Track : public TrackBase {
440 public:
441 Track( const wp<ThreadBase>& thread,
442 const sp<Client>& client,
443 int streamType,
444 uint32_t sampleRate,
445 int format,
446 int channelCount,
447 int frameCount,
448 const sp<IMemory>& sharedBuffer,
449 int sessionId);
450 ~Track();
451
452 void dump(char* buffer, size_t size);
453 virtual status_t start();
454 virtual void stop();
455 void pause();
456
457 void flush();
458 void destroy();
459 void mute(bool);
460 void setVolume(float left, float right);
461 int name() const {
462 return mName;
463 }
464
465 int type() const {
466 return mStreamType;
467 }
468 status_t attachAuxEffect(int EffectId);
469 void setAuxBuffer(int EffectId, int32_t *buffer);
470 int32_t *auxBuffer() { return mAuxBuffer; }
471 void setMainBuffer(int16_t *buffer) { mMainBuffer = buffer; }
472 int16_t *mainBuffer() { return mMainBuffer; }
473 int auxEffectId() { return mAuxEffectId; }
474
475
476 protected:
477 friend class ThreadBase;
478 friend class AudioFlinger;
479 friend class TrackHandle;
480 friend class PlaybackThread;
481 friend class MixerThread;
482 friend class DirectOutputThread;
483
484 Track(const Track&);
485 Track& operator = (const Track&);
486
487 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
488 bool isMuted() { return mMute; }
489 bool isPausing() const {
490 return mState == PAUSING;
491 }
492 bool isPaused() const {
493 return mState == PAUSED;
494 }
495 bool isReady() const;
496 void setPaused() { mState = PAUSED; }
497 void reset();
498
499 bool isOutputTrack() const {
500 return (mStreamType == AudioSystem::NUM_STREAM_TYPES);
501 }
502
503 // we don't really need a lock for these
504 float mVolume[2];
505 volatile bool mMute;
506 // FILLED state is used for suppressing volume ramp at begin of playing
507 enum {FS_FILLING, FS_FILLED, FS_ACTIVE};
508 mutable uint8_t mFillingUpStatus;
509 int8_t mRetryCount;
510 sp<IMemory> mSharedBuffer;
511 bool mResetDone;
512 int mStreamType;
513 int mName;
514 int16_t *mMainBuffer;
515 int32_t *mAuxBuffer;
516 int mAuxEffectId;
517 }; // end of Track
518
519
520 // playback track
521 class OutputTrack : public Track {
522 public:
523
524 class Buffer: public AudioBufferProvider::Buffer {
525 public:
526 int16_t *mBuffer;
527 };
528
529 OutputTrack( const wp<ThreadBase>& thread,
530 DuplicatingThread *sourceThread,
531 uint32_t sampleRate,
532 int format,
533 int channelCount,
534 int frameCount);
535 ~OutputTrack();
536
537 virtual status_t start();
538 virtual void stop();
539 bool write(int16_t* data, uint32_t frames);
540 bool bufferQueueEmpty() { return (mBufferQueue.size() == 0) ? true : false; }
541 bool isActive() { return mActive; }
542 wp<ThreadBase>& thread() { return mThread; }
543
544 private:
545
546 status_t obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs);
547 void clearBufferQueue();
548
549 // Maximum number of pending buffers allocated by OutputTrack::write()
550 static const uint8_t kMaxOverFlowBuffers = 10;
551
552 Vector < Buffer* > mBufferQueue;
553 AudioBufferProvider::Buffer mOutBuffer;
554 bool mActive;
555 DuplicatingThread* mSourceThread;
556 }; // end of OutputTrack
557
558 PlaybackThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device);
559 virtual ~PlaybackThread();
560
561 virtual status_t dump(int fd, const Vector<String16>& args);
562
563 // Thread virtuals
564 virtual status_t readyToRun();
565 virtual void onFirstRef();
566
567 virtual uint32_t latency() const;
568
569 virtual status_t setMasterVolume(float value);
570 virtual status_t setMasterMute(bool muted);
571
572 virtual float masterVolume() const;
573 virtual bool masterMute() const;
574
575 virtual status_t setStreamVolume(int stream, float value);
576 virtual status_t setStreamMute(int stream, bool muted);
577
578 virtual float streamVolume(int stream) const;
579 virtual bool streamMute(int stream) const;
580
581 bool isStreamActive(int stream) const;
582
583 sp<Track> createTrack_l(
584 const sp<AudioFlinger::Client>& client,
585 int streamType,
586 uint32_t sampleRate,
587 int format,
588 int channelCount,
589 int frameCount,
590 const sp<IMemory>& sharedBuffer,
591 int sessionId,
592 status_t *status);
593
594 AudioStreamOut* getOutput() { return mOutput; }
595
596 virtual int type() const { return mType; }
597 void suspend() { mSuspended++; }
598 void restore() { if (mSuspended) mSuspended--; }
599 bool isSuspended() { return (mSuspended != 0); }
600 virtual String8 getParameters(const String8& keys);
601 virtual void audioConfigChanged_l(int event, int param = 0);
602 virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames);
603 int16_t *mixBuffer() { return mMixBuffer; };
604
605 sp<EffectHandle> createEffect_l(
606 const sp<AudioFlinger::Client>& client,
607 const sp<IEffectClient>& effectClient,
608 int32_t priority,
609 int sessionId,
610 effect_descriptor_t *desc,
611 int *enabled,
612 status_t *status);
613 void disconnectEffect(const sp< EffectModule>& effect,
614 const wp<EffectHandle>& handle);
615
Eric Laurent39e94f82010-07-28 01:32:47 -0700616 // return values for hasAudioSession (bit field)
617 enum effect_state {
618 EFFECT_SESSION = 0x1, // the audio session corresponds to at least one
619 // effect
620 TRACK_SESSION = 0x2 // the audio session corresponds to at least one
621 // track
622 };
623
624 uint32_t hasAudioSession(int sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 sp<EffectChain> getEffectChain(int sessionId);
626 sp<EffectChain> getEffectChain_l(int sessionId);
627 status_t addEffectChain_l(const sp<EffectChain>& chain);
628 size_t removeEffectChain_l(const sp<EffectChain>& chain);
Eric Laurentde070132010-07-13 04:45:46 -0700629 void lockEffectChains_l(Vector<sp <EffectChain> >& effectChains);
630 void unlockEffectChains(Vector<sp <EffectChain> >& effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700631
632 sp<AudioFlinger::EffectModule> getEffect_l(int sessionId, int effectId);
633 void detachAuxEffect_l(int effectId);
Eric Laurentde070132010-07-13 04:45:46 -0700634 status_t attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track,
635 int EffectId);
636 status_t attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track,
637 int EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 void setMode(uint32_t mode);
639
Eric Laurentde070132010-07-13 04:45:46 -0700640 status_t addEffect_l(const sp< EffectModule>& effect);
641 void removeEffect_l(const sp< EffectModule>& effect);
642
643 uint32_t getStrategyForSession_l(int sessionId);
644
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 struct stream_type_t {
646 stream_type_t()
647 : volume(1.0f),
648 mute(false)
649 {
650 }
651 float volume;
652 bool mute;
653 };
654
655 protected:
656 int mType;
657 int16_t* mMixBuffer;
658 int mSuspended;
659 int mBytesWritten;
660 bool mMasterMute;
661 SortedVector< wp<Track> > mActiveTracks;
662
663 virtual int getTrackName_l() = 0;
664 virtual void deleteTrackName_l(int name) = 0;
665 virtual uint32_t activeSleepTimeUs() = 0;
666 virtual uint32_t idleSleepTimeUs() = 0;
Eric Laurent25cbe0e2010-08-18 18:13:17 -0700667 virtual uint32_t suspendSleepTimeUs() = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668
669 private:
670
671 friend class AudioFlinger;
672 friend class OutputTrack;
673 friend class Track;
674 friend class TrackBase;
675 friend class MixerThread;
676 friend class DirectOutputThread;
677 friend class DuplicatingThread;
678
679 PlaybackThread(const Client&);
680 PlaybackThread& operator = (const PlaybackThread&);
681
682 status_t addTrack_l(const sp<Track>& track);
683 void destroyTrack_l(const sp<Track>& track);
684
685 void readOutputParameters();
686
687 uint32_t device() { return mDevice; }
688
689 virtual status_t dumpInternals(int fd, const Vector<String16>& args);
690 status_t dumpTracks(int fd, const Vector<String16>& args);
691 status_t dumpEffectChains(int fd, const Vector<String16>& args);
692
693 SortedVector< sp<Track> > mTracks;
694 // mStreamTypes[] uses 1 additionnal stream type internally for the OutputTrack used by DuplicatingThread
695 stream_type_t mStreamTypes[AudioSystem::NUM_STREAM_TYPES + 1];
696 AudioStreamOut* mOutput;
697 float mMasterVolume;
698 nsecs_t mLastWriteTime;
699 int mNumWrites;
700 int mNumDelayedWrites;
701 bool mInWrite;
702 Vector< sp<EffectChain> > mEffectChains;
703 uint32_t mDevice;
704 };
705
706 class MixerThread : public PlaybackThread {
707 public:
Eric Laurentde070132010-07-13 04:45:46 -0700708 MixerThread (const sp<AudioFlinger>& audioFlinger,
709 AudioStreamOut* output,
710 int id,
711 uint32_t device);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700712 virtual ~MixerThread();
713
714 // Thread virtuals
715 virtual bool threadLoop();
716
717 void invalidateTracks(int streamType);
718 virtual bool checkForNewParameters_l();
719 virtual status_t dumpInternals(int fd, const Vector<String16>& args);
720
721 protected:
Eric Laurentde070132010-07-13 04:45:46 -0700722 uint32_t prepareTracks_l(const SortedVector< wp<Track> >& activeTracks,
723 Vector< sp<Track> > *tracksToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 virtual int getTrackName_l();
725 virtual void deleteTrackName_l(int name);
726 virtual uint32_t activeSleepTimeUs();
727 virtual uint32_t idleSleepTimeUs();
Eric Laurent25cbe0e2010-08-18 18:13:17 -0700728 virtual uint32_t suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729
730 AudioMixer* mAudioMixer;
731 };
732
733 class DirectOutputThread : public PlaybackThread {
734 public:
735
736 DirectOutputThread (const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device);
737 ~DirectOutputThread();
738
739 // Thread virtuals
740 virtual bool threadLoop();
741
742 virtual bool checkForNewParameters_l();
743
744 protected:
745 virtual int getTrackName_l();
746 virtual void deleteTrackName_l(int name);
747 virtual uint32_t activeSleepTimeUs();
748 virtual uint32_t idleSleepTimeUs();
Eric Laurent25cbe0e2010-08-18 18:13:17 -0700749 virtual uint32_t suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750
751 private:
752 void applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp);
753
754 float mLeftVolFloat;
755 float mRightVolFloat;
756 uint16_t mLeftVolShort;
757 uint16_t mRightVolShort;
758 };
759
760 class DuplicatingThread : public MixerThread {
761 public:
762 DuplicatingThread (const sp<AudioFlinger>& audioFlinger, MixerThread* mainThread, int id);
763 ~DuplicatingThread();
764
765 // Thread virtuals
766 virtual bool threadLoop();
767 void addOutputTrack(MixerThread* thread);
768 void removeOutputTrack(MixerThread* thread);
769 uint32_t waitTimeMs() { return mWaitTimeMs; }
770 protected:
771 virtual uint32_t activeSleepTimeUs();
772
773 private:
774 bool outputsReady(SortedVector< sp<OutputTrack> > &outputTracks);
775 void updateWaitTime();
776
777 SortedVector < sp<OutputTrack> > mOutputTracks;
778 uint32_t mWaitTimeMs;
779 };
780
781 PlaybackThread *checkPlaybackThread_l(int output) const;
782 MixerThread *checkMixerThread_l(int output) const;
783 RecordThread *checkRecordThread_l(int input) const;
784 float streamVolumeInternal(int stream) const { return mStreamTypes[stream].volume; }
785 void audioConfigChanged_l(int event, int ioHandle, void *param2);
786
787 int nextUniqueId();
Eric Laurentde070132010-07-13 04:45:46 -0700788 status_t moveEffectChain_l(int session,
789 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -0700790 AudioFlinger::PlaybackThread *dstThread,
791 bool reRegister);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792
793 friend class AudioBuffer;
794
795 class TrackHandle : public android::BnAudioTrack {
796 public:
797 TrackHandle(const sp<PlaybackThread::Track>& track);
798 virtual ~TrackHandle();
799 virtual status_t start();
800 virtual void stop();
801 virtual void flush();
802 virtual void mute(bool);
803 virtual void pause();
804 virtual void setVolume(float left, float right);
805 virtual sp<IMemory> getCblk() const;
806 virtual status_t attachAuxEffect(int effectId);
807 virtual status_t onTransact(
808 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
809 private:
810 sp<PlaybackThread::Track> mTrack;
811 };
812
813 friend class Client;
814 friend class PlaybackThread::Track;
815
816
817 void removeClient_l(pid_t pid);
818 void removeNotificationClient(pid_t pid);
819
820
821 // record thread
822 class RecordThread : public ThreadBase, public AudioBufferProvider
823 {
824 public:
825
826 // record track
827 class RecordTrack : public TrackBase {
828 public:
829 RecordTrack(const wp<ThreadBase>& thread,
830 const sp<Client>& client,
831 uint32_t sampleRate,
832 int format,
833 int channelCount,
834 int frameCount,
835 uint32_t flags,
836 int sessionId);
837 ~RecordTrack();
838
839 virtual status_t start();
840 virtual void stop();
841
842 bool overflow() { bool tmp = mOverflow; mOverflow = false; return tmp; }
843 bool setOverflow() { bool tmp = mOverflow; mOverflow = true; return tmp; }
844
845 void dump(char* buffer, size_t size);
846 private:
847 friend class AudioFlinger;
848 friend class RecordThread;
849
850 RecordTrack(const RecordTrack&);
851 RecordTrack& operator = (const RecordTrack&);
852
853 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
854
855 bool mOverflow;
856 };
857
858
859 RecordThread(const sp<AudioFlinger>& audioFlinger,
860 AudioStreamIn *input,
861 uint32_t sampleRate,
862 uint32_t channels,
863 int id);
864 ~RecordThread();
865
866 virtual bool threadLoop();
867 virtual status_t readyToRun() { return NO_ERROR; }
868 virtual void onFirstRef();
869
870 status_t start(RecordTrack* recordTrack);
871 void stop(RecordTrack* recordTrack);
872 status_t dump(int fd, const Vector<String16>& args);
873 AudioStreamIn* getInput() { return mInput; }
874
875 virtual status_t getNextBuffer(AudioBufferProvider::Buffer* buffer);
876 virtual void releaseBuffer(AudioBufferProvider::Buffer* buffer);
877 virtual bool checkForNewParameters_l();
878 virtual String8 getParameters(const String8& keys);
879 virtual void audioConfigChanged_l(int event, int param = 0);
880 void readInputParameters();
881 virtual unsigned int getInputFramesLost();
882
883 private:
884 RecordThread();
885 AudioStreamIn *mInput;
886 sp<RecordTrack> mActiveTrack;
887 Condition mStartStopCond;
888 AudioResampler *mResampler;
889 int32_t *mRsmpOutBuffer;
890 int16_t *mRsmpInBuffer;
891 size_t mRsmpInIndex;
892 size_t mInputBytes;
893 int mReqChannelCount;
894 uint32_t mReqSampleRate;
895 ssize_t mBytesRead;
896 };
897
898 class RecordHandle : public android::BnAudioRecord {
899 public:
900 RecordHandle(const sp<RecordThread::RecordTrack>& recordTrack);
901 virtual ~RecordHandle();
902 virtual status_t start();
903 virtual void stop();
904 virtual sp<IMemory> getCblk() const;
905 virtual status_t onTransact(
906 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
907 private:
908 sp<RecordThread::RecordTrack> mRecordTrack;
909 };
910
911 //--- Audio Effect Management
912
913 // EffectModule and EffectChain classes both have their own mutex to protect
914 // state changes or resource modifications. Always respect the following order
915 // if multiple mutexes must be acquired to avoid cross deadlock:
916 // AudioFlinger -> ThreadBase -> EffectChain -> EffectModule
917
918 // The EffectModule class is a wrapper object controlling the effect engine implementation
919 // in the effect library. It prevents concurrent calls to process() and command() functions
920 // from different client threads. It keeps a list of EffectHandle objects corresponding
921 // to all client applications using this effect and notifies applications of effect state,
922 // control or parameter changes. It manages the activation state machine to send appropriate
923 // reset, enable, disable commands to effect engine and provide volume
924 // ramping when effects are activated/deactivated.
925 // When controlling an auxiliary effect, the EffectModule also provides an input buffer used by
926 // the attached track(s) to accumulate their auxiliary channel.
927 class EffectModule: public RefBase {
928 public:
929 EffectModule(const wp<ThreadBase>& wThread,
930 const wp<AudioFlinger::EffectChain>& chain,
931 effect_descriptor_t *desc,
932 int id,
933 int sessionId);
934 ~EffectModule();
935
936 enum effect_state {
937 IDLE,
938 RESTART,
939 STARTING,
940 ACTIVE,
941 STOPPING,
942 STOPPED
943 };
944
945 int id() { return mId; }
946 void process();
947 void updateState();
Eric Laurent25f43952010-07-28 05:40:18 -0700948 status_t command(uint32_t cmdCode,
949 uint32_t cmdSize,
950 void *pCmdData,
951 uint32_t *replySize,
952 void *pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700953
954 void reset_l();
955 status_t configure();
956 status_t init();
957 uint32_t state() {
958 return mState;
959 }
960 uint32_t status() {
961 return mStatus;
962 }
Eric Laurentde070132010-07-13 04:45:46 -0700963 int sessionId() {
964 return mSessionId;
965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966 status_t setEnabled(bool enabled);
967 bool isEnabled();
968
969 void setInBuffer(int16_t *buffer) { mConfig.inputCfg.buffer.s16 = buffer; }
970 int16_t *inBuffer() { return mConfig.inputCfg.buffer.s16; }
971 void setOutBuffer(int16_t *buffer) { mConfig.outputCfg.buffer.s16 = buffer; }
972 int16_t *outBuffer() { return mConfig.outputCfg.buffer.s16; }
Eric Laurentde070132010-07-13 04:45:46 -0700973 void setChain(const wp<EffectChain>& chain) { mChain = chain; }
974 void setThread(const wp<ThreadBase>& thread) { mThread = thread; }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975
976 status_t addHandle(sp<EffectHandle>& handle);
977 void disconnect(const wp<EffectHandle>& handle);
978 size_t removeHandle (const wp<EffectHandle>& handle);
979
980 effect_descriptor_t& desc() { return mDescriptor; }
981 wp<EffectChain>& chain() { return mChain; }
982
983 status_t setDevice(uint32_t device);
984 status_t setVolume(uint32_t *left, uint32_t *right, bool controller);
985 status_t setMode(uint32_t mode);
986
987 status_t dump(int fd, const Vector<String16>& args);
988
989 protected:
990
991 // Maximum time allocated to effect engines to complete the turn off sequence
992 static const uint32_t MAX_DISABLE_TIME_MS = 10000;
993
994 EffectModule(const EffectModule&);
995 EffectModule& operator = (const EffectModule&);
996
997 status_t start_l();
998 status_t stop_l();
999
1000 // update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
1001 static const uint32_t sDeviceConvTable[];
1002 static uint32_t deviceAudioSystemToEffectApi(uint32_t device);
1003
1004 // update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
1005 static const uint32_t sModeConvTable[];
1006 static int modeAudioSystemToEffectApi(uint32_t mode);
1007
1008 Mutex mLock; // mutex for process, commands and handles list protection
1009 wp<ThreadBase> mThread; // parent thread
1010 wp<EffectChain> mChain; // parent effect chain
1011 int mId; // this instance unique ID
1012 int mSessionId; // audio session ID
1013 effect_descriptor_t mDescriptor;// effect descriptor received from effect engine
1014 effect_config_t mConfig; // input and output audio configuration
1015 effect_interface_t mEffectInterface; // Effect module C API
1016 status_t mStatus; // initialization status
1017 uint32_t mState; // current activation state (effect_state)
1018 Vector< wp<EffectHandle> > mHandles; // list of client handles
1019 uint32_t mMaxDisableWaitCnt; // maximum grace period before forcing an effect off after
1020 // sending disable command.
1021 uint32_t mDisableWaitCnt; // current process() calls count during disable period.
1022 };
1023
1024 // The EffectHandle class implements the IEffect interface. It provides resources
1025 // to receive parameter updates, keeps track of effect control
1026 // ownership and state and has a pointer to the EffectModule object it is controlling.
1027 // There is one EffectHandle object for each application controlling (or using)
1028 // an effect module.
1029 // The EffectHandle is obtained by calling AudioFlinger::createEffect().
1030 class EffectHandle: public android::BnEffect {
1031 public:
1032
1033 EffectHandle(const sp<EffectModule>& effect,
1034 const sp<AudioFlinger::Client>& client,
1035 const sp<IEffectClient>& effectClient,
1036 int32_t priority);
1037 virtual ~EffectHandle();
1038
1039 // IEffect
1040 virtual status_t enable();
1041 virtual status_t disable();
Eric Laurent25f43952010-07-28 05:40:18 -07001042 virtual status_t command(uint32_t cmdCode,
1043 uint32_t cmdSize,
1044 void *pCmdData,
1045 uint32_t *replySize,
1046 void *pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 virtual void disconnect();
1048 virtual sp<IMemory> getCblk() const;
1049 virtual status_t onTransact(uint32_t code, const Parcel& data,
1050 Parcel* reply, uint32_t flags);
1051
1052
1053 // Give or take control of effect module
1054 void setControl(bool hasControl, bool signal);
Eric Laurent25f43952010-07-28 05:40:18 -07001055 void commandExecuted(uint32_t cmdCode,
1056 uint32_t cmdSize,
1057 void *pCmdData,
1058 uint32_t replySize,
1059 void *pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 void setEnabled(bool enabled);
1061
1062 // Getters
1063 int id() { return mEffect->id(); }
1064 int priority() { return mPriority; }
1065 bool hasControl() { return mHasControl; }
1066 sp<EffectModule> effect() { return mEffect; }
1067
1068 void dump(char* buffer, size_t size);
1069
1070 protected:
1071
1072 EffectHandle(const EffectHandle&);
1073 EffectHandle& operator =(const EffectHandle&);
1074
1075 sp<EffectModule> mEffect; // pointer to controlled EffectModule
1076 sp<IEffectClient> mEffectClient; // callback interface for client notifications
1077 sp<Client> mClient; // client for shared memory allocation
1078 sp<IMemory> mCblkMemory; // shared memory for control block
1079 effect_param_cblk_t* mCblk; // control block for deferred parameter setting via shared memory
1080 uint8_t* mBuffer; // pointer to parameter area in shared memory
1081 int mPriority; // client application priority to control the effect
1082 bool mHasControl; // true if this handle is controlling the effect
1083 };
1084
1085 // the EffectChain class represents a group of effects associated to one audio session.
1086 // There can be any number of EffectChain objects per output mixer thread (PlaybackThread).
1087 // The EffecChain with session ID 0 contains global effects applied to the output mix.
1088 // Effects in this chain can be insert or auxiliary. Effects in other chains (attached to tracks)
1089 // are insert only. The EffectChain maintains an ordered list of effect module, the order corresponding
1090 // in the effect process order. When attached to a track (session ID != 0), it also provide it's own
1091 // input buffer used by the track as accumulation buffer.
1092 class EffectChain: public RefBase {
1093 public:
1094 EffectChain(const wp<ThreadBase>& wThread, int sessionId);
1095 ~EffectChain();
1096
1097 void process_l();
1098
1099 void lock() {
1100 mLock.lock();
1101 }
1102 void unlock() {
1103 mLock.unlock();
1104 }
1105
Eric Laurentde070132010-07-13 04:45:46 -07001106 status_t addEffect_l(const sp<EffectModule>& handle);
Eric Laurentcab11242010-07-15 12:50:15 -07001107 size_t removeEffect_l(const sp<EffectModule>& handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108
1109 int sessionId() {
1110 return mSessionId;
1111 }
Eric Laurentde070132010-07-13 04:45:46 -07001112
Eric Laurentcab11242010-07-15 12:50:15 -07001113 sp<EffectModule> getEffectFromDesc_l(effect_descriptor_t *descriptor);
1114 sp<EffectModule> getEffectFromId_l(int id);
1115 bool setVolume_l(uint32_t *left, uint32_t *right);
1116 void setDevice_l(uint32_t device);
1117 void setMode_l(uint32_t mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001118
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 void setInBuffer(int16_t *buffer, bool ownsBuffer = false) {
1120 mInBuffer = buffer;
1121 mOwnInBuffer = ownsBuffer;
1122 }
1123 int16_t *inBuffer() {
1124 return mInBuffer;
1125 }
1126 void setOutBuffer(int16_t *buffer) {
1127 mOutBuffer = buffer;
1128 }
1129 int16_t *outBuffer() {
1130 return mOutBuffer;
1131 }
1132
1133 void startTrack() {mActiveTrackCnt++;}
1134 void stopTrack() {mActiveTrackCnt--;}
1135 int activeTracks() { return mActiveTrackCnt;}
1136
Eric Laurentde070132010-07-13 04:45:46 -07001137 uint32_t strategy() { return mStrategy; }
1138 void setStrategy(uint32_t strategy)
1139 { mStrategy = strategy; }
1140
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 status_t dump(int fd, const Vector<String16>& args);
1142
1143 protected:
1144
1145 EffectChain(const EffectChain&);
1146 EffectChain& operator =(const EffectChain&);
1147
1148 wp<ThreadBase> mThread; // parent mixer thread
1149 Mutex mLock; // mutex protecting effect list
1150 Vector<sp<EffectModule> > mEffects; // list of effect modules
1151 int mSessionId; // audio session ID
1152 int16_t *mInBuffer; // chain input buffer
1153 int16_t *mOutBuffer; // chain output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 int mActiveTrackCnt; // number of active tracks connected
1155 bool mOwnInBuffer; // true if the chain owns its input buffer
Eric Laurentcab11242010-07-15 12:50:15 -07001156 int mVolumeCtrlIdx; // index of insert effect having control over volume
1157 uint32_t mLeftVolume; // previous volume on left channel
1158 uint32_t mRightVolume; // previous volume on right channel
Eric Laurentf997cab2010-07-19 06:24:46 -07001159 uint32_t mNewLeftVolume; // new volume on left channel
1160 uint32_t mNewRightVolume; // new volume on right channel
Eric Laurentde070132010-07-13 04:45:46 -07001161 uint32_t mStrategy; // strategy for this effect chain
Mathias Agopian65ab4712010-07-14 17:59:35 -07001162 };
1163
1164 friend class RecordThread;
1165 friend class PlaybackThread;
1166
1167
1168 mutable Mutex mLock;
1169
1170 DefaultKeyedVector< pid_t, wp<Client> > mClients;
1171
1172 mutable Mutex mHardwareLock;
1173 AudioHardwareInterface* mAudioHardware;
1174 mutable int mHardwareStatus;
1175
1176
1177 DefaultKeyedVector< int, sp<PlaybackThread> > mPlaybackThreads;
1178 PlaybackThread::stream_type_t mStreamTypes[AudioSystem::NUM_STREAM_TYPES];
1179 float mMasterVolume;
1180 bool mMasterMute;
1181
1182 DefaultKeyedVector< int, sp<RecordThread> > mRecordThreads;
1183
1184 DefaultKeyedVector< pid_t, sp<NotificationClient> > mNotificationClients;
1185 volatile int32_t mNextUniqueId;
1186#ifdef LVMX
1187 int mLifeVibesClientPid;
1188#endif
1189 uint32_t mMode;
1190
Mathias Agopian65ab4712010-07-14 17:59:35 -07001191};
1192
1193// ----------------------------------------------------------------------------
1194
1195}; // namespace android
1196
1197#endif // ANDROID_AUDIO_FLINGER_H