MediaPlayerService.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. **
  3. ** Copyright 2008, 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. #ifndef ANDROID_MEDIAPLAYERSERVICE_H
  18. #define ANDROID_MEDIAPLAYERSERVICE_H
  19. #include <arpa/inet.h>
  20. #include <utils/threads.h>
  21. #include <utils/Errors.h>
  22. #include <utils/KeyedVector.h>
  23. #include <utils/String8.h>
  24. #include <utils/Vector.h>
  25. #include <media/MediaPlayerInterface.h>
  26. #include <media/Metadata.h>
  27. #include <media/stagefright/foundation/ABase.h>
  28. #include <system/audio.h>
  29. namespace android {
  30. struct AudioPlaybackRate;
  31. class AudioTrack;
  32. struct AVSyncSettings;
  33. class DeathNotifier;
  34. class IDataSource;
  35. class IMediaRecorder;
  36. class IMediaMetadataRetriever;
  37. class IRemoteDisplay;
  38. class IRemoteDisplayClient;
  39. class MediaRecorderClient;
  40. #define CALLBACK_ANTAGONIZER 0
  41. #if CALLBACK_ANTAGONIZER
  42. class Antagonizer {
  43. public:
  44. Antagonizer(const sp<MediaPlayerBase::Listener> &listener);
  45. void start() { mActive = true; }
  46. void stop() { mActive = false; }
  47. void kill();
  48. private:
  49. static const int interval;
  50. Antagonizer();
  51. static int callbackThread(void* cookie);
  52. Mutex mLock;
  53. Condition mCondition;
  54. bool mExit;
  55. bool mActive;
  56. sp<MediaPlayerBase::Listener> mListener;
  57. };
  58. #endif
  59. class MediaPlayerService : public BnMediaPlayerService
  60. {
  61. class Client;
  62. class AudioOutput : public MediaPlayerBase::AudioSink
  63. {
  64. class CallbackData;
  65. public:
  66. AudioOutput(
  67. audio_session_t sessionId,
  68. uid_t uid,
  69. int pid,
  70. const audio_attributes_t * attr,
  71. const sp<AudioSystem::AudioDeviceCallback>& deviceCallback);
  72. virtual ~AudioOutput();
  73. virtual bool ready() const { return mTrack != 0; }
  74. virtual ssize_t bufferSize() const;
  75. virtual ssize_t frameCount() const;
  76. virtual ssize_t channelCount() const;
  77. virtual ssize_t frameSize() const;
  78. virtual uint32_t latency() const;
  79. virtual float msecsPerFrame() const;
  80. virtual status_t getPosition(uint32_t *position) const;
  81. virtual status_t getTimestamp(AudioTimestamp &ts) const;
  82. virtual int64_t getPlayedOutDurationUs(int64_t nowUs) const;
  83. virtual status_t getFramesWritten(uint32_t *frameswritten) const;
  84. virtual audio_session_t getSessionId() const;
  85. virtual uint32_t getSampleRate() const;
  86. virtual int64_t getBufferDurationInUs() const;
  87. virtual status_t open(
  88. uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
  89. audio_format_t format, int bufferCount,
  90. AudioCallback cb, void *cookie,
  91. audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
  92. const audio_offload_info_t *offloadInfo = NULL,
  93. bool doNotReconnect = false,
  94. uint32_t suggestedFrameCount = 0);
  95. virtual status_t start();
  96. virtual ssize_t write(const void* buffer, size_t size, bool blocking = true);
  97. virtual void stop();
  98. virtual void flush();
  99. virtual void pause();
  100. virtual void close();
  101. void setAudioStreamType(audio_stream_type_t streamType);
  102. virtual audio_stream_type_t getAudioStreamType() const { return mStreamType; }
  103. void setAudioAttributes(const audio_attributes_t * attributes);
  104. void setVolume(float left, float right);
  105. virtual status_t setPlaybackRate(const AudioPlaybackRate& rate);
  106. virtual status_t getPlaybackRate(AudioPlaybackRate* rate /* nonnull */);
  107. status_t setAuxEffectSendLevel(float level);
  108. status_t attachAuxEffect(int effectId);
  109. virtual status_t dump(int fd, const Vector<String16>& args) const;
  110. static bool isOnEmulator();
  111. static int getMinBufferCount();
  112. void setNextOutput(const sp<AudioOutput>& nextOutput);
  113. void switchToNextOutput();
  114. virtual bool needsTrailingPadding() { return mNextOutput == NULL; }
  115. virtual status_t setParameters(const String8& keyValuePairs);
  116. virtual String8 getParameters(const String8& keys);
  117. virtual media::VolumeShaper::Status applyVolumeShaper(
  118. const sp<media::VolumeShaper::Configuration>& configuration,
  119. const sp<media::VolumeShaper::Operation>& operation) override;
  120. virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
  121. // AudioRouting
  122. virtual status_t setOutputDevice(audio_port_handle_t deviceId);
  123. virtual status_t getRoutedDeviceId(audio_port_handle_t* deviceId);
  124. virtual status_t enableAudioDeviceCallback(bool enabled);
  125. private:
  126. static void setMinBufferCount();
  127. static void CallbackWrapper(
  128. int event, void *me, void *info);
  129. void deleteRecycledTrack_l();
  130. void close_l();
  131. status_t updateTrack();
  132. sp<AudioTrack> mTrack;
  133. sp<AudioTrack> mRecycledTrack;
  134. sp<AudioOutput> mNextOutput;
  135. AudioCallback mCallback;
  136. void * mCallbackCookie;
  137. CallbackData * mCallbackData;
  138. audio_stream_type_t mStreamType;
  139. audio_attributes_t * mAttributes;
  140. float mLeftVolume;
  141. float mRightVolume;
  142. AudioPlaybackRate mPlaybackRate;
  143. uint32_t mSampleRateHz; // sample rate of the content, as set in open()
  144. float mMsecsPerFrame;
  145. size_t mFrameSize;
  146. audio_session_t mSessionId;
  147. uid_t mUid;
  148. int mPid;
  149. float mSendLevel;
  150. int mAuxEffectId;
  151. audio_output_flags_t mFlags;
  152. sp<media::VolumeHandler> mVolumeHandler;
  153. audio_port_handle_t mSelectedDeviceId;
  154. audio_port_handle_t mRoutedDeviceId;
  155. bool mDeviceCallbackEnabled;
  156. wp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
  157. mutable Mutex mLock;
  158. // static variables below not protected by mutex
  159. static bool mIsOnEmulator;
  160. static int mMinBufferCount; // 12 for emulator; otherwise 4
  161. // CallbackData is what is passed to the AudioTrack as the "user" data.
  162. // We need to be able to target this to a different Output on the fly,
  163. // so we can't use the Output itself for this.
  164. class CallbackData {
  165. friend AudioOutput;
  166. public:
  167. explicit CallbackData(AudioOutput *cookie) {
  168. mData = cookie;
  169. mSwitching = false;
  170. }
  171. AudioOutput * getOutput() const { return mData; }
  172. void setOutput(AudioOutput* newcookie) { mData = newcookie; }
  173. // lock/unlock are used by the callback before accessing the payload of this object
  174. void lock() const { mLock.lock(); }
  175. void unlock() const { mLock.unlock(); }
  176. // tryBeginTrackSwitch/endTrackSwitch are used when the CallbackData is handed over
  177. // to the next sink.
  178. // tryBeginTrackSwitch() returns true only if it obtains the lock.
  179. bool tryBeginTrackSwitch() {
  180. LOG_ALWAYS_FATAL_IF(mSwitching, "tryBeginTrackSwitch() already called");
  181. if (mLock.tryLock() != OK) {
  182. return false;
  183. }
  184. mSwitching = true;
  185. return true;
  186. }
  187. void endTrackSwitch() {
  188. if (mSwitching) {
  189. mLock.unlock();
  190. }
  191. mSwitching = false;
  192. }
  193. private:
  194. AudioOutput * mData;
  195. mutable Mutex mLock; // a recursive mutex might make this unnecessary.
  196. bool mSwitching;
  197. DISALLOW_EVIL_CONSTRUCTORS(CallbackData);
  198. };
  199. }; // AudioOutput
  200. public:
  201. static void instantiate();
  202. // IMediaPlayerService interface
  203. virtual sp<IMediaRecorder> createMediaRecorder(const String16 &opPackageName);
  204. void removeMediaRecorderClient(const wp<MediaRecorderClient>& client);
  205. virtual sp<IMediaMetadataRetriever> createMetadataRetriever();
  206. virtual sp<IMediaPlayer> create(const sp<IMediaPlayerClient>& client,
  207. audio_session_t audioSessionId);
  208. virtual sp<IMediaCodecList> getCodecList() const;
  209. virtual sp<IRemoteDisplay> listenForRemoteDisplay(const String16 &opPackageName,
  210. const sp<IRemoteDisplayClient>& client, const String8& iface);
  211. virtual status_t dump(int fd, const Vector<String16>& args);
  212. void removeClient(const wp<Client>& client);
  213. bool hasClient(wp<Client> client);
  214. enum {
  215. MEDIASERVER_PROCESS_DEATH = 0,
  216. MEDIAEXTRACTOR_PROCESS_DEATH = 1,
  217. MEDIACODEC_PROCESS_DEATH = 2,
  218. AUDIO_PROCESS_DEATH = 3, // currently no need to track this
  219. CAMERA_PROCESS_DEATH = 4
  220. };
  221. // Collect info of the codec usage from media player and media recorder
  222. virtual void addBatteryData(uint32_t params);
  223. // API for the Battery app to pull the data of codecs usage
  224. virtual status_t pullBatteryData(Parcel* reply);
  225. private:
  226. struct BatteryTracker {
  227. BatteryTracker();
  228. // Collect info of the codec usage from media player and media recorder
  229. void addBatteryData(uint32_t params);
  230. // API for the Battery app to pull the data of codecs usage
  231. status_t pullBatteryData(Parcel* reply);
  232. private:
  233. // For battery usage tracking purpose
  234. struct BatteryUsageInfo {
  235. // how many streams are being played by one UID
  236. int refCount;
  237. // a temp variable to store the duration(ms) of audio codecs
  238. // when we start a audio codec, we minus the system time from audioLastTime
  239. // when we pause it, we add the system time back to the audioLastTime
  240. // so after the pause, audioLastTime = pause time - start time
  241. // if multiple audio streams are played (or recorded), then audioLastTime
  242. // = the total playing time of all the streams
  243. int32_t audioLastTime;
  244. // when all the audio streams are being paused, we assign audioLastTime to
  245. // this variable, so this value could be provided to the battery app
  246. // in the next pullBatteryData call
  247. int32_t audioTotalTime;
  248. int32_t videoLastTime;
  249. int32_t videoTotalTime;
  250. };
  251. KeyedVector<int, BatteryUsageInfo> mBatteryData;
  252. enum {
  253. SPEAKER,
  254. OTHER_AUDIO_DEVICE,
  255. SPEAKER_AND_OTHER,
  256. NUM_AUDIO_DEVICES
  257. };
  258. struct BatteryAudioFlingerUsageInfo {
  259. int refCount; // how many audio streams are being played
  260. int deviceOn[NUM_AUDIO_DEVICES]; // whether the device is currently used
  261. int32_t lastTime[NUM_AUDIO_DEVICES]; // in ms
  262. // totalTime[]: total time of audio output devices usage
  263. int32_t totalTime[NUM_AUDIO_DEVICES]; // in ms
  264. };
  265. // This varialble is used to record the usage of audio output device
  266. // for battery app
  267. BatteryAudioFlingerUsageInfo mBatteryAudio;
  268. mutable Mutex mLock;
  269. };
  270. BatteryTracker mBatteryTracker;
  271. class Client : public BnMediaPlayer {
  272. // IMediaPlayer interface
  273. virtual void disconnect();
  274. virtual status_t setVideoSurfaceTexture(
  275. const sp<IGraphicBufferProducer>& bufferProducer);
  276. virtual status_t setBufferingSettings(const BufferingSettings& buffering) override;
  277. virtual status_t getBufferingSettings(
  278. BufferingSettings* buffering /* nonnull */) override;
  279. virtual status_t prepareAsync();
  280. virtual status_t start();
  281. virtual status_t stop();
  282. virtual status_t pause();
  283. virtual status_t isPlaying(bool* state);
  284. virtual status_t setPlaybackSettings(const AudioPlaybackRate& rate);
  285. virtual status_t getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */);
  286. virtual status_t setSyncSettings(const AVSyncSettings& rate, float videoFpsHint);
  287. virtual status_t getSyncSettings(AVSyncSettings* rate /* nonnull */,
  288. float* videoFps /* nonnull */);
  289. virtual status_t seekTo(
  290. int msec,
  291. MediaPlayerSeekMode mode = MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC);
  292. virtual status_t getCurrentPosition(int* msec);
  293. virtual status_t getDuration(int* msec);
  294. virtual status_t reset();
  295. virtual status_t notifyAt(int64_t mediaTimeUs);
  296. virtual status_t setAudioStreamType(audio_stream_type_t type);
  297. virtual status_t setLooping(int loop);
  298. virtual status_t setVolume(float leftVolume, float rightVolume);
  299. virtual status_t invoke(const Parcel& request, Parcel *reply);
  300. virtual status_t setMetadataFilter(const Parcel& filter);
  301. virtual status_t getMetadata(bool update_only,
  302. bool apply_filter,
  303. Parcel *reply);
  304. virtual status_t setAuxEffectSendLevel(float level);
  305. virtual status_t attachAuxEffect(int effectId);
  306. virtual status_t setParameter(int key, const Parcel &request);
  307. virtual status_t getParameter(int key, Parcel *reply);
  308. virtual status_t setRetransmitEndpoint(const struct sockaddr_in* endpoint);
  309. virtual status_t getRetransmitEndpoint(struct sockaddr_in* endpoint);
  310. virtual status_t setNextPlayer(const sp<IMediaPlayer>& player);
  311. virtual media::VolumeShaper::Status applyVolumeShaper(
  312. const sp<media::VolumeShaper::Configuration>& configuration,
  313. const sp<media::VolumeShaper::Operation>& operation) override;
  314. virtual sp<media::VolumeShaper::State> getVolumeShaperState(int id) override;
  315. sp<MediaPlayerBase> createPlayer(player_type playerType);
  316. virtual status_t setDataSource(
  317. const sp<IMediaHTTPService> &httpService,
  318. const char *url,
  319. const KeyedVector<String8, String8> *headers);
  320. virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
  321. virtual status_t setDataSource(const sp<IStreamSource> &source);
  322. virtual status_t setDataSource(const sp<IDataSource> &source);
  323. sp<MediaPlayerBase> setDataSource_pre(player_type playerType);
  324. status_t setDataSource_post(const sp<MediaPlayerBase>& p,
  325. status_t status);
  326. void notify(int msg, int ext1, int ext2, const Parcel *obj);
  327. pid_t pid() const { return mPid; }
  328. virtual status_t dump(int fd, const Vector<String16>& args);
  329. audio_session_t getAudioSessionId() { return mAudioSessionId; }
  330. // Modular DRM
  331. virtual status_t prepareDrm(const uint8_t uuid[16], const Vector<uint8_t>& drmSessionId);
  332. virtual status_t releaseDrm();
  333. // AudioRouting
  334. virtual status_t setOutputDevice(audio_port_handle_t deviceId);
  335. virtual status_t getRoutedDeviceId(audio_port_handle_t* deviceId);
  336. virtual status_t enableAudioDeviceCallback(bool enabled);
  337. private:
  338. class AudioDeviceUpdatedNotifier: public AudioSystem::AudioDeviceCallback
  339. {
  340. public:
  341. AudioDeviceUpdatedNotifier(const sp<MediaPlayerBase>& listener) {
  342. mListener = listener;
  343. }
  344. ~AudioDeviceUpdatedNotifier() {}
  345. virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
  346. audio_port_handle_t deviceId);
  347. private:
  348. wp<MediaPlayerBase> mListener;
  349. };
  350. friend class MediaPlayerService;
  351. Client( const sp<MediaPlayerService>& service,
  352. pid_t pid,
  353. int32_t connId,
  354. const sp<IMediaPlayerClient>& client,
  355. audio_session_t audioSessionId,
  356. uid_t uid);
  357. Client();
  358. virtual ~Client();
  359. void deletePlayer();
  360. sp<MediaPlayerBase> getPlayer() const { Mutex::Autolock lock(mLock); return mPlayer; }
  361. // @param type Of the metadata to be tested.
  362. // @return true if the metadata should be dropped according to
  363. // the filters.
  364. bool shouldDropMetadata(media::Metadata::Type type) const;
  365. // Add a new element to the set of metadata updated. Noop if
  366. // the element exists already.
  367. // @param type Of the metadata to be recorded.
  368. void addNewMetadataUpdate(media::Metadata::Type type);
  369. // Disconnect from the currently connected ANativeWindow.
  370. void disconnectNativeWindow_l();
  371. status_t setAudioAttributes_l(const Parcel &request);
  372. class Listener : public MediaPlayerBase::Listener {
  373. public:
  374. Listener(const wp<Client> &client) : mClient(client) {}
  375. virtual ~Listener() {}
  376. virtual void notify(int msg, int ext1, int ext2, const Parcel *obj) {
  377. sp<Client> client = mClient.promote();
  378. if (client != NULL) {
  379. client->notify(msg, ext1, ext2, obj);
  380. }
  381. }
  382. private:
  383. wp<Client> mClient;
  384. };
  385. mutable Mutex mLock;
  386. sp<MediaPlayerBase> mPlayer;
  387. sp<MediaPlayerService> mService;
  388. sp<IMediaPlayerClient> mClient;
  389. sp<AudioOutput> mAudioOutput;
  390. pid_t mPid;
  391. status_t mStatus;
  392. bool mLoop;
  393. int32_t mConnId;
  394. audio_session_t mAudioSessionId;
  395. audio_attributes_t * mAudioAttributes;
  396. uid_t mUid;
  397. sp<ANativeWindow> mConnectedWindow;
  398. sp<IBinder> mConnectedWindowBinder;
  399. struct sockaddr_in mRetransmitEndpoint;
  400. bool mRetransmitEndpointValid;
  401. sp<Client> mNextClient;
  402. sp<MediaPlayerBase::Listener> mListener;
  403. // Metadata filters.
  404. media::Metadata::Filter mMetadataAllow; // protected by mLock
  405. media::Metadata::Filter mMetadataDrop; // protected by mLock
  406. // Metadata updated. For each MEDIA_INFO_METADATA_UPDATE
  407. // notification we try to update mMetadataUpdated which is a
  408. // set: no duplicate.
  409. // getMetadata clears this set.
  410. media::Metadata::Filter mMetadataUpdated; // protected by mLock
  411. std::vector<DeathNotifier> mDeathNotifiers;
  412. sp<AudioDeviceUpdatedNotifier> mAudioDeviceUpdatedListener;
  413. #if CALLBACK_ANTAGONIZER
  414. Antagonizer* mAntagonizer;
  415. #endif
  416. }; // Client
  417. // ----------------------------------------------------------------------------
  418. MediaPlayerService();
  419. virtual ~MediaPlayerService();
  420. mutable Mutex mLock;
  421. SortedVector< wp<Client> > mClients;
  422. SortedVector< wp<MediaRecorderClient> > mMediaRecorderClients;
  423. int32_t mNextConnId;
  424. };
  425. // ----------------------------------------------------------------------------
  426. }; // namespace android
  427. #endif // ANDROID_MEDIAPLAYERSERVICE_H