MediaPlayer2: remove MediaPlayer2Engine

Test: MediaPlayer2 plays
Bug: 63934228
Change-Id: I2459082bf6bbe2384ed94901b1f8f28559345888
diff --git a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2AudioOutput.h b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2AudioOutput.h
new file mode 100644
index 0000000..ad4937a
--- /dev/null
+++ b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2AudioOutput.h
@@ -0,0 +1,192 @@
+/*
+**
+** Copyright 2018, The Android Open Source Project
+**
+** Licensed under the Apache License, Version 2.0 (the "License");
+** you may not use this file except in compliance with the License.
+** You may obtain a copy of the License at
+**
+**     http://www.apache.org/licenses/LICENSE-2.0
+**
+** Unless required by applicable law or agreed to in writing, software
+** distributed under the License is distributed on an "AS IS" BASIS,
+** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+** See the License for the specific language governing permissions and
+** limitations under the License.
+*/
+
+#ifndef ANDROID_MEDIAPLAYER2AUDIOOUTPUT_H
+#define ANDROID_MEDIAPLAYER2AUDIOOUTPUT_H
+
+#include <mediaplayer2/MediaPlayer2Interface.h>
+
+#include <utils/String16.h>
+#include <utils/Vector.h>
+
+namespace android {
+
+class AudioTrack;
+
+class MediaPlayer2AudioOutput : public MediaPlayer2Interface::AudioSink
+{
+    class CallbackData;
+
+public:
+    MediaPlayer2AudioOutput(audio_session_t sessionId,
+                            uid_t uid,
+                            int pid,
+                            const audio_attributes_t * attr,
+                            const sp<AudioSystem::AudioDeviceCallback>& deviceCallback);
+    virtual ~MediaPlayer2AudioOutput();
+
+    virtual bool ready() const {
+        return mTrack != 0;
+    }
+    virtual ssize_t bufferSize() const;
+    virtual ssize_t frameCount() const;
+    virtual ssize_t channelCount() const;
+    virtual ssize_t frameSize() const;
+    virtual uint32_t latency() const;
+    virtual float msecsPerFrame() const;
+    virtual status_t getPosition(uint32_t *position) const;
+    virtual status_t getTimestamp(AudioTimestamp &ts) const;
+    virtual int64_t getPlayedOutDurationUs(int64_t nowUs) const;
+    virtual status_t getFramesWritten(uint32_t *frameswritten) const;
+    virtual audio_session_t getSessionId() const;
+    virtual uint32_t getSampleRate() const;
+    virtual int64_t getBufferDurationInUs() const;
+
+    virtual status_t open(
+            uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
+            audio_format_t format, int bufferCount,
+            AudioCallback cb, void *cookie,
+            audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
+            const audio_offload_info_t *offloadInfo = NULL,
+            bool doNotReconnect = false,
+            uint32_t suggestedFrameCount = 0);
+
+    virtual status_t start();
+    virtual ssize_t write(const void* buffer, size_t size, bool blocking = true);
+    virtual void stop();
+    virtual void flush();
+    virtual void pause();
+    virtual void close();
+    void setAudioStreamType(audio_stream_type_t streamType);
+    virtual audio_stream_type_t getAudioStreamType() const {
+        return mStreamType;
+    }
+    void setAudioAttributes(const audio_attributes_t * attributes);
+
+    void setVolume(float left, float right);
+    virtual status_t setPlaybackRate(const AudioPlaybackRate& rate);
+    virtual status_t getPlaybackRate(AudioPlaybackRate* rate /* nonnull */);
+
+    status_t setAuxEffectSendLevel(float level);
+    status_t attachAuxEffect(int effectId);
+    virtual status_t dump(int fd, const Vector<String16>& args) const;
+
+    static bool isOnEmulator();
+    static int getMinBufferCount();
+    void setNextOutput(const sp<MediaPlayer2AudioOutput>& nextOutput);
+    virtual bool needsTrailingPadding() {
+        return true;
+        // TODO: return correct value.
+        //return mNextOutput == NULL;
+    }
+    virtual status_t setParameters(const String8& keyValuePairs);
+    virtual String8 getParameters(const String8& keys);
+
+    // AudioRouting
+    virtual status_t setOutputDevice(audio_port_handle_t deviceId);
+    virtual status_t getRoutedDeviceId(audio_port_handle_t* deviceId);
+    virtual status_t enableAudioDeviceCallback(bool enabled);
+
+private:
+    static void setMinBufferCount();
+    static void CallbackWrapper(int event, void *me, void *info);
+    void deleteRecycledTrack_l();
+    void close_l();
+    status_t updateTrack_l();
+
+    sp<AudioTrack>          mTrack;
+    AudioCallback           mCallback;
+    void *                  mCallbackCookie;
+    CallbackData *          mCallbackData;
+    audio_stream_type_t     mStreamType;
+    audio_attributes_t *    mAttributes;
+    float                   mLeftVolume;
+    float                   mRightVolume;
+    AudioPlaybackRate       mPlaybackRate;
+    uint32_t                mSampleRateHz; // sample rate of the content, as set in open()
+    float                   mMsecsPerFrame;
+    size_t                  mFrameSize;
+    audio_session_t         mSessionId;
+    uid_t                   mUid;
+    int                     mPid;
+    float                   mSendLevel;
+    int                     mAuxEffectId;
+    audio_output_flags_t    mFlags;
+    audio_port_handle_t     mSelectedDeviceId;
+    audio_port_handle_t     mRoutedDeviceId;
+    bool                    mDeviceCallbackEnabled;
+    wp<AudioSystem::AudioDeviceCallback>        mDeviceCallback;
+    mutable Mutex           mLock;
+
+    // static variables below not protected by mutex
+    static bool             mIsOnEmulator;
+    static int              mMinBufferCount;  // 12 for emulator; otherwise 4
+
+    // CallbackData is what is passed to the AudioTrack as the "user" data.
+    // We need to be able to target this to a different Output on the fly,
+    // so we can't use the Output itself for this.
+    class CallbackData {
+        friend MediaPlayer2AudioOutput;
+    public:
+        explicit CallbackData(MediaPlayer2AudioOutput *cookie) {
+            mData = cookie;
+            mSwitching = false;
+        }
+        MediaPlayer2AudioOutput *getOutput() const {
+            return mData;
+        }
+        void setOutput(MediaPlayer2AudioOutput* newcookie) {
+            mData = newcookie;
+        }
+        // lock/unlock are used by the callback before accessing the payload of this object
+        void lock() const {
+            mLock.lock();
+        }
+        void unlock() const {
+            mLock.unlock();
+        }
+
+        // tryBeginTrackSwitch/endTrackSwitch are used when the CallbackData is handed over
+        // to the next sink.
+
+        // tryBeginTrackSwitch() returns true only if it obtains the lock.
+        bool tryBeginTrackSwitch() {
+            LOG_ALWAYS_FATAL_IF(mSwitching, "tryBeginTrackSwitch() already called");
+            if (mLock.tryLock() != OK) {
+                return false;
+            }
+            mSwitching = true;
+            return true;
+        }
+        void endTrackSwitch() {
+            if (mSwitching) {
+                mLock.unlock();
+            }
+            mSwitching = false;
+        }
+
+    private:
+        MediaPlayer2AudioOutput *mData;
+        mutable Mutex mLock; // a recursive mutex might make this unnecessary.
+        bool mSwitching;
+        DISALLOW_EVIL_CONSTRUCTORS(CallbackData);
+    };
+};
+
+}; // namespace android
+
+#endif // ANDROID_MEDIAPLAYER2AUDIOOUTPUT_H
diff --git a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Engine.h b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Engine.h
deleted file mode 100644
index 749d83c..0000000
--- a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Engine.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_MEDIAPLAYER2ENGINE_H
-#define ANDROID_MEDIAPLAYER2ENGINE_H
-
-#include <utils/RefBase.h>
-#include <binder/Parcel.h>
-#include <utils/KeyedVector.h>
-#include <system/audio.h>
-
-#include <media/MediaSource.h>
-
-// Fwd decl to make sure everyone agrees that the scope of struct sockaddr_in is
-// global, and not in android::
-struct sockaddr_in;
-
-namespace android {
-
-struct ANativeWindowWrapper;
-struct AVSyncSettings;
-struct AudioPlaybackRate;
-struct BufferingSettings;
-class DataSource;
-struct DataSourceDesc;
-struct IStreamSource;
-struct MediaHTTPService;
-class Parcel;
-
-typedef MediaSource::ReadOptions::SeekMode MediaPlayer2SeekMode;
-
-class MediaPlayer2Engine: public RefBase
-{
-public:
-    virtual void            disconnect() = 0;
-
-    virtual status_t        setDataSource(const sp<DataSourceDesc>& source) = 0;
-    virtual status_t        prepareNextDataSource(const sp<DataSourceDesc>& source) = 0;
-    virtual status_t        playNextDataSource(int64_t srcId) = 0;
-    virtual status_t        setVideoSurfaceTexture(const sp<ANativeWindowWrapper>& nww) = 0;
-    virtual status_t        getBufferingSettings(
-                                    BufferingSettings* buffering /* nonnull */) = 0;
-    virtual status_t        setBufferingSettings(const BufferingSettings& buffering) = 0;
-    virtual status_t        prepareAsync() = 0;
-    virtual status_t        start() = 0;
-    virtual status_t        stop() = 0;
-    virtual status_t        pause() = 0;
-    virtual status_t        isPlaying(bool* state) = 0;
-    virtual status_t        setPlaybackSettings(const AudioPlaybackRate& rate) = 0;
-    virtual status_t        getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */) = 0;
-    virtual status_t        setSyncSettings(const AVSyncSettings& sync, float videoFpsHint) = 0;
-    virtual status_t        getSyncSettings(AVSyncSettings* sync /* nonnull */,
-                                            float* videoFps /* nonnull */) = 0;
-    virtual status_t        seekTo(
-            int msec,
-            MediaPlayer2SeekMode mode = MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC) = 0;
-    virtual status_t        getCurrentPosition(int* msec) = 0;
-    virtual status_t        getDuration(int* msec) = 0;
-    virtual status_t        notifyAt(int64_t mediaTimeUs) = 0;
-    virtual status_t        reset() = 0;
-    virtual status_t        setAudioStreamType(audio_stream_type_t type) = 0;
-    virtual status_t        setLooping(int loop) = 0;
-    virtual status_t        setVolume(float leftVolume, float rightVolume) = 0;
-    virtual status_t        setAuxEffectSendLevel(float level) = 0;
-    virtual status_t        attachAuxEffect(int effectId) = 0;
-    virtual status_t        setParameter(int key, const Parcel& request) = 0;
-    virtual status_t        getParameter(int key, Parcel* reply) = 0;
-    virtual status_t        setNextPlayer(const sp<MediaPlayer2Engine>& next) = 0;
-
-    // Modular DRM
-    virtual status_t        prepareDrm(const uint8_t uuid[16],
-                                    const Vector<uint8_t>& drmSessionId) = 0;
-    virtual status_t        releaseDrm() = 0;
-
-    // Invoke a generic method on the player by using opaque parcels
-    // for the request and reply.
-    // @param request Parcel that must start with the media player
-    // interface token.
-    // @param[out] reply Parcel to hold the reply data. Cannot be null.
-    // @return OK if the invocation was made successfully.
-    virtual status_t        invoke(const Parcel& request, Parcel *reply) = 0;
-
-    // Set a new metadata filter.
-    // @param filter A set of allow and drop rules serialized in a Parcel.
-    // @return OK if the invocation was made successfully.
-    virtual status_t        setMetadataFilter(const Parcel& filter) = 0;
-
-    // Retrieve a set of metadata.
-    // @param update_only Include only the metadata that have changed
-    //                    since the last invocation of getMetadata.
-    //                    The set is built using the unfiltered
-    //                    notifications the native player sent to the
-    //                    MediaPlayer2Manager during that period of
-    //                    time. If false, all the metadatas are considered.
-    // @param apply_filter If true, once the metadata set has been built based
-    //                     on the value update_only, the current filter is
-    //                     applied.
-    // @param[out] metadata On exit contains a set (possibly empty) of metadata.
-    //                      Valid only if the call returned OK.
-    // @return OK if the invocation was made successfully.
-    virtual status_t        getMetadata(bool update_only,
-                                        bool apply_filter,
-                                        Parcel *metadata) = 0;
-
-    // AudioRouting
-    virtual status_t        setOutputDevice(audio_port_handle_t deviceId) = 0;
-    virtual status_t        getRoutedDeviceId(audio_port_handle_t *deviceId) = 0;
-    virtual status_t        enableAudioDeviceCallback(bool enabled) = 0;
-};
-
-}; // namespace android
-
-#endif // ANDROID_MEDIAPLAYER2ENGINE_H
diff --git a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2EngineClient.h b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2EngineClient.h
deleted file mode 100644
index 0b066aa..0000000
--- a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2EngineClient.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_MEDIAPLAYER2ENGINECLIENT_H
-#define ANDROID_MEDIAPLAYER2ENGINECLIENT_H
-
-#include <utils/RefBase.h>
-#include <binder/Parcel.h>
-
-namespace android {
-
-class MediaPlayer2EngineClient: public RefBase
-{
-public:
-    virtual void notify(int64_t srcId, int msg, int ext1, int ext2, const Parcel *obj) = 0;
-};
-
-}; // namespace android
-
-#endif // ANDROID_MEDIAPLAYER2ENGINECLIENT_H
diff --git a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Interface.h b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Interface.h
index c0c490b..96aea7f 100644
--- a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Interface.h
+++ b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Interface.h
@@ -21,18 +21,17 @@
 
 #include <sys/types.h>
 #include <utils/Errors.h>
-#include <utils/KeyedVector.h>
 #include <utils/String8.h>
 #include <utils/RefBase.h>
 
+#include <media/AVSyncSettings.h>
 #include <media/AudioResamplerPublic.h>
 #include <media/AudioSystem.h>
 #include <media/AudioTimestamp.h>
-#include <media/AVSyncSettings.h>
 #include <media/BufferingSettings.h>
 #include <media/Metadata.h>
 #include <media/stagefright/foundation/AHandler.h>
-#include <mediaplayer2/mediaplayer2.h>
+#include <mediaplayer2/MediaPlayer2Types.h>
 
 // Fwd decl to make sure everyone agrees that the scope of struct sockaddr_in is
 // global, and not in android::
@@ -40,14 +39,10 @@
 
 namespace android {
 
-class DataSource;
 struct DataSourceDesc;
-struct MediaHTTPService;
 class Parcel;
 struct ANativeWindowWrapper;
 
-template<typename T> class SortedVector;
-
 #define DEFAULT_AUDIOSINK_BUFFERCOUNT 4
 #define DEFAULT_AUDIOSINK_BUFFERSIZE 1200
 #define DEFAULT_AUDIOSINK_SAMPLERATE 44100
@@ -58,14 +53,14 @@
 // duration below which we do not allow deep audio buffering
 #define AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US 5000000
 
-// abstract base class - use MediaPlayer2Interface
-class MediaPlayer2Interface : public AHandler
+class MediaPlayer2InterfaceListener: public RefBase
 {
 public:
-    // callback mechanism for passing messages to MediaPlayer2 object
-    typedef void (*NotifyCallback)(const wp<MediaPlayer2Engine> &listener,
-            int64_t srcId, int msg, int ext1, int ext2, const Parcel *obj);
+    virtual void notify(int64_t srcId, int msg, int ext1, int ext2, const Parcel *obj) = 0;
+};
 
+class MediaPlayer2Interface : public AHandler {
+public:
     // AudioSink: abstraction layer for audio output
     class AudioSink : public RefBase {
     public:
@@ -79,29 +74,28 @@
 
         // Callback returns the number of bytes actually written to the buffer.
         typedef size_t (*AudioCallback)(
-                AudioSink *audioSink, void *buffer, size_t size, void *cookie,
-                        cb_event_t event);
+                AudioSink *audioSink, void *buffer, size_t size, void *cookie, cb_event_t event);
 
-        virtual             ~AudioSink() {}
-        virtual bool        ready() const = 0; // audio output is open and ready
-        virtual ssize_t     bufferSize() const = 0;
-        virtual ssize_t     frameCount() const = 0;
-        virtual ssize_t     channelCount() const = 0;
-        virtual ssize_t     frameSize() const = 0;
-        virtual uint32_t    latency() const = 0;
-        virtual float       msecsPerFrame() const = 0;
-        virtual status_t    getPosition(uint32_t *position) const = 0;
-        virtual status_t    getTimestamp(AudioTimestamp &ts) const = 0;
-        virtual int64_t     getPlayedOutDurationUs(int64_t nowUs) const = 0;
-        virtual status_t    getFramesWritten(uint32_t *frameswritten) const = 0;
+        virtual ~AudioSink() {}
+        virtual bool ready() const = 0; // audio output is open and ready
+        virtual ssize_t bufferSize() const = 0;
+        virtual ssize_t frameCount() const = 0;
+        virtual ssize_t channelCount() const = 0;
+        virtual ssize_t frameSize() const = 0;
+        virtual uint32_t latency() const = 0;
+        virtual float msecsPerFrame() const = 0;
+        virtual status_t getPosition(uint32_t *position) const = 0;
+        virtual status_t getTimestamp(AudioTimestamp &ts) const = 0;
+        virtual int64_t getPlayedOutDurationUs(int64_t nowUs) const = 0;
+        virtual status_t getFramesWritten(uint32_t *frameswritten) const = 0;
         virtual audio_session_t getSessionId() const = 0;
         virtual audio_stream_type_t getAudioStreamType() const = 0;
-        virtual uint32_t    getSampleRate() const = 0;
-        virtual int64_t     getBufferDurationInUs() const = 0;
+        virtual uint32_t getSampleRate() const = 0;
+        virtual int64_t getBufferDurationInUs() const = 0;
 
         // If no callback is specified, use the "write" API below to submit
         // audio data.
-        virtual status_t    open(
+        virtual status_t open(
                 uint32_t sampleRate, int channelCount, audio_channel_mask_t channelMask,
                 audio_format_t format=AUDIO_FORMAT_PCM_16_BIT,
                 int bufferCount=DEFAULT_AUDIOSINK_BUFFERCOUNT,
@@ -112,7 +106,7 @@
                 bool doNotReconnect = false,
                 uint32_t suggestedFrameCount = 0) = 0;
 
-        virtual status_t    start() = 0;
+        virtual status_t start() = 0;
 
         /* Input parameter |size| is in byte units stored in |buffer|.
          * Data is copied over and actual number of bytes written (>= 0)
@@ -124,19 +118,25 @@
          * buffer, unless an error occurs or the copy operation is
          * prematurely stopped.
          */
-        virtual ssize_t     write(const void* buffer, size_t size, bool blocking = true) = 0;
+        virtual ssize_t write(const void* buffer, size_t size, bool blocking = true) = 0;
 
-        virtual void        stop() = 0;
-        virtual void        flush() = 0;
-        virtual void        pause() = 0;
-        virtual void        close() = 0;
+        virtual void stop() = 0;
+        virtual void flush() = 0;
+        virtual void pause() = 0;
+        virtual void close() = 0;
 
-        virtual status_t    setPlaybackRate(const AudioPlaybackRate& rate) = 0;
-        virtual status_t    getPlaybackRate(AudioPlaybackRate* rate /* nonnull */) = 0;
-        virtual bool        needsTrailingPadding() { return true; }
+        virtual status_t setPlaybackRate(const AudioPlaybackRate& rate) = 0;
+        virtual status_t getPlaybackRate(AudioPlaybackRate* rate /* nonnull */) = 0;
+        virtual bool needsTrailingPadding() {
+            return true;
+        }
 
-        virtual status_t    setParameters(const String8& /* keyValuePairs */) { return NO_ERROR; }
-        virtual String8     getParameters(const String8& /* keys */) { return String8::empty(); }
+        virtual status_t setParameters(const String8& /* keyValuePairs */) {
+            return NO_ERROR;
+        }
+        virtual String8 getParameters(const String8& /* keys */) {
+            return String8::empty();
+        }
 
         // AudioRouting
         virtual status_t    setOutputDevice(audio_port_handle_t deviceId);
@@ -144,47 +144,48 @@
         virtual status_t    enableAudioDeviceCallback(bool enabled);
     };
 
-                        MediaPlayer2Interface() : mClient(0), mNotify(0) { }
-    virtual             ~MediaPlayer2Interface() { }
-    virtual status_t    initCheck() = 0;
+    MediaPlayer2Interface() : mListener(NULL) { }
+    virtual ~MediaPlayer2Interface() { }
+    virtual status_t initCheck() = 0;
 
-    virtual void        setAudioSink(const sp<AudioSink>& audioSink) { mAudioSink = audioSink; }
+    virtual void setAudioSink(const sp<AudioSink>& audioSink) {
+        mAudioSink = audioSink;
+    }
 
-    virtual status_t    setDataSource(const sp<DataSourceDesc> &dsd) = 0;
+    virtual status_t setDataSource(const sp<DataSourceDesc> &dsd) = 0;
 
-    virtual status_t    prepareNextDataSource(const sp<DataSourceDesc> &dsd) = 0;
+    virtual status_t prepareNextDataSource(const sp<DataSourceDesc> &dsd) = 0;
 
-    virtual status_t    playNextDataSource(int64_t srcId) = 0;
+    virtual status_t playNextDataSource(int64_t srcId) = 0;
 
     // pass the buffered native window to the media player service
-    virtual status_t    setVideoSurfaceTexture(const sp<ANativeWindowWrapper>& nww) = 0;
+    virtual status_t setVideoSurfaceTexture(const sp<ANativeWindowWrapper>& nww) = 0;
 
-    virtual status_t    getBufferingSettings(
-                                BufferingSettings* buffering /* nonnull */) {
+    virtual status_t getBufferingSettings(BufferingSettings* buffering /* nonnull */) {
         *buffering = BufferingSettings();
         return OK;
     }
-    virtual status_t    setBufferingSettings(const BufferingSettings& /* buffering */) {
+    virtual status_t setBufferingSettings(const BufferingSettings& /* buffering */) {
         return OK;
     }
 
-    virtual status_t    prepareAsync() = 0;
-    virtual status_t    start() = 0;
-    virtual status_t    stop() = 0;
-    virtual status_t    pause() = 0;
-    virtual bool        isPlaying() = 0;
-    virtual status_t    setPlaybackSettings(const AudioPlaybackRate& rate) {
+    virtual status_t prepareAsync() = 0;
+    virtual status_t start() = 0;
+    virtual status_t stop() = 0;
+    virtual status_t pause() = 0;
+    virtual bool isPlaying() = 0;
+    virtual status_t setPlaybackSettings(const AudioPlaybackRate& rate) {
         // by default, players only support setting rate to the default
         if (!isAudioPlaybackRateEqual(rate, AUDIO_PLAYBACK_RATE_DEFAULT)) {
             return BAD_VALUE;
         }
         return OK;
     }
-    virtual status_t    getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */) {
+    virtual status_t getPlaybackSettings(AudioPlaybackRate* rate /* nonnull */) {
         *rate = AUDIO_PLAYBACK_RATE_DEFAULT;
         return OK;
     }
-    virtual status_t    setSyncSettings(const AVSyncSettings& sync, float /* videoFps */) {
+    virtual status_t setSyncSettings(const AVSyncSettings& sync, float /* videoFps */) {
         // By default, players only support setting sync source to default; all other sync
         // settings are ignored. There is no requirement for getters to return set values.
         if (sync.mSource != AVSYNC_SOURCE_DEFAULT) {
@@ -192,27 +193,23 @@
         }
         return OK;
     }
-    virtual status_t    getSyncSettings(
-                                AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */) {
+    virtual status_t getSyncSettings(
+            AVSyncSettings* sync /* nonnull */, float* videoFps /* nonnull */) {
         *sync = AVSyncSettings();
         *videoFps = -1.f;
         return OK;
     }
-    virtual status_t    seekTo(
+    virtual status_t seekTo(
             int msec, MediaPlayer2SeekMode mode = MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC) = 0;
-    virtual status_t    getCurrentPosition(int *msec) = 0;
-    virtual status_t    getDuration(int *msec) = 0;
-    virtual status_t    reset() = 0;
-    virtual status_t    notifyAt(int64_t /* mediaTimeUs */) {
+    virtual status_t getCurrentPosition(int *msec) = 0;
+    virtual status_t getDuration(int *msec) = 0;
+    virtual status_t reset() = 0;
+    virtual status_t notifyAt(int64_t /* mediaTimeUs */) {
         return INVALID_OPERATION;
     }
-    virtual status_t    setLooping(int loop) = 0;
-    virtual status_t    setParameter(int key, const Parcel &request) = 0;
-    virtual status_t    getParameter(int key, Parcel *reply) = 0;
-
-    virtual status_t setNextPlayer(const sp<MediaPlayer2Interface>& /* next */) {
-        return OK;
-    }
+    virtual status_t setLooping(int loop) = 0;
+    virtual status_t setParameter(int key, const Parcel &request) = 0;
+    virtual status_t getParameter(int key, Parcel *reply) = 0;
 
     // Invoke a generic method on the player by using opaque parcels
     // for the request and reply.
@@ -221,7 +218,7 @@
     //                data sent by the java layer.
     // @param[out] reply Parcel to hold the reply data. Cannot be null.
     // @return OK if the call was successful.
-    virtual status_t    invoke(const Parcel& request, Parcel *reply) = 0;
+    virtual status_t invoke(const Parcel& request, Parcel *reply) = 0;
 
     // The Client in the MetadataPlayerService calls this method on
     // the native player to retrieve all or a subset of metadata.
@@ -230,28 +227,26 @@
     //            the known metadata should be returned.
     // @param[inout] records Parcel where the player appends its metadata.
     // @return OK if the call was successful.
-    virtual status_t    getMetadata(const media::Metadata::Filter& /* ids */,
-                                    Parcel* /* records */) {
+    virtual status_t getMetadata(const media::Metadata::Filter& /* ids */,
+                                 Parcel* /* records */) {
         return INVALID_OPERATION;
     };
 
-    void        setNotifyCallback(
-            const wp<MediaPlayer2Engine> &client, NotifyCallback notifyFunc) {
-        Mutex::Autolock autoLock(mNotifyLock);
-        mClient = client; mNotify = notifyFunc;
+    void setListener(const sp<MediaPlayer2InterfaceListener> &listener) {
+        Mutex::Autolock autoLock(mListenerLock);
+        mListener = listener;
     }
 
-    void        sendEvent(int64_t srcId, int msg, int ext1=0, int ext2=0,
-                          const Parcel *obj=NULL) {
-        NotifyCallback notifyCB;
-        wp<MediaPlayer2Engine> client;
+    void sendEvent(int64_t srcId, int msg, int ext1=0, int ext2=0, const Parcel *obj=NULL) {
+        sp<MediaPlayer2InterfaceListener> listener;
         {
-            Mutex::Autolock autoLock(mNotifyLock);
-            notifyCB = mNotify;
-            client = mClient;
+            Mutex::Autolock autoLock(mListenerLock);
+            listener = mListener;
         }
 
-        if (notifyCB) notifyCB(client, srcId, msg, ext1, ext2, obj);
+        if (listener) {
+            listener->notify(srcId, msg, ext1, ext2, obj);
+        }
     }
 
     virtual status_t dump(int /* fd */, const Vector<String16>& /* args */) const {
@@ -261,7 +256,8 @@
     virtual void onMessageReceived(const sp<AMessage> & /* msg */) override { }
 
     // Modular DRM
-    virtual status_t prepareDrm(const uint8_t /* uuid */[16], const Vector<uint8_t>& /* drmSessionId */) {
+    virtual status_t prepareDrm(const uint8_t /* uuid */[16],
+                                const Vector<uint8_t>& /* drmSessionId */) {
         return INVALID_OPERATION;
     }
     virtual status_t releaseDrm() {
@@ -269,14 +265,11 @@
     }
 
 protected:
-    sp<AudioSink>       mAudioSink;
+    sp<AudioSink> mAudioSink;
 
 private:
-    friend class MediaPlayer2Manager;
-
-    Mutex                  mNotifyLock;
-    wp<MediaPlayer2Engine> mClient;
-    NotifyCallback         mNotify;
+    Mutex mListenerLock;
+    sp<MediaPlayer2InterfaceListener> mListener;
 };
 
 }; // namespace android
diff --git a/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Types.h b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Types.h
new file mode 100644
index 0000000..260c7ed
--- /dev/null
+++ b/media/libmediaplayer2/include/mediaplayer2/MediaPlayer2Types.h
@@ -0,0 +1,195 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_MEDIAPLAYER2_TYPES_H
+#define ANDROID_MEDIAPLAYER2_TYPES_H
+
+#include <media/mediaplayer_common.h>
+
+#include <media/MediaSource.h>
+
+namespace android {
+
+typedef MediaSource::ReadOptions::SeekMode MediaPlayer2SeekMode;
+
+enum media2_event_type {
+    MEDIA2_NOP               = 0, // interface test message
+    MEDIA2_PREPARED          = 1,
+    MEDIA2_PLAYBACK_COMPLETE = 2,
+    MEDIA2_BUFFERING_UPDATE  = 3,
+    MEDIA2_SEEK_COMPLETE     = 4,
+    MEDIA2_SET_VIDEO_SIZE    = 5,
+    MEDIA2_STARTED           = 6,
+    MEDIA2_PAUSED            = 7,
+    MEDIA2_STOPPED           = 8,
+    MEDIA2_SKIPPED           = 9,
+    MEDIA2_NOTIFY_TIME       = 98,
+    MEDIA2_TIMED_TEXT        = 99,
+    MEDIA2_ERROR             = 100,
+    MEDIA2_INFO              = 200,
+    MEDIA2_SUBTITLE_DATA     = 201,
+    MEDIA2_META_DATA         = 202,
+    MEDIA2_DRM_INFO          = 210,
+    MEDIA2_AUDIO_ROUTING_CHANGED = 10000,
+};
+
+// Generic error codes for the media player framework.  Errors are fatal, the
+// playback must abort.
+//
+// Errors are communicated back to the client using the
+// MediaPlayer2Listener::notify method defined below.
+// In this situation, 'notify' is invoked with the following:
+//   'msg' is set to MEDIA_ERROR.
+//   'ext1' should be a value from the enum media2_error_type.
+//   'ext2' contains an implementation dependant error code to provide
+//          more details. Should default to 0 when not used.
+//
+// The codes are distributed as follow:
+//   0xx: Reserved
+//   1xx: Android Player errors. Something went wrong inside the MediaPlayer2.
+//   2xx: Media errors (e.g Codec not supported). There is a problem with the
+//        media itself.
+//   3xx: Runtime errors. Some extraordinary condition arose making the playback
+//        impossible.
+//
+enum media2_error_type {
+    // 0xx
+    MEDIA2_ERROR_UNKNOWN = 1,
+    // 1xx
+    // MEDIA2_ERROR_SERVER_DIED = 100,
+    // 2xx
+    MEDIA2_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200,
+    // 3xx
+    MEDIA2_ERROR_FAILED_TO_SET_DATA_SOURCE = 300,
+};
+
+
+// Info and warning codes for the media player framework.  These are non fatal,
+// the playback is going on but there might be some user visible issues.
+//
+// Info and warning messages are communicated back to the client using the
+// MediaPlayer2Listener::notify method defined below.  In this situation,
+// 'notify' is invoked with the following:
+//   'msg' is set to MEDIA_INFO.
+//   'ext1' should be a value from the enum media2_info_type.
+//   'ext2' contains an implementation dependant info code to provide
+//          more details. Should default to 0 when not used.
+//
+// The codes are distributed as follow:
+//   0xx: Reserved
+//   7xx: Android Player info/warning (e.g player lagging behind.)
+//   8xx: Media info/warning (e.g media badly interleaved.)
+//
+enum media2_info_type {
+    // 0xx
+    MEDIA2_INFO_UNKNOWN = 1,
+    // The player was started because it was used as the next player for another
+    // player, which just completed playback
+    MEDIA2_INFO_STARTED_AS_NEXT = 2,
+    // The player just pushed the very first video frame for rendering
+    MEDIA2_INFO_VIDEO_RENDERING_START = 3,
+    // The player just pushed the very first audio frame for rendering
+    MEDIA2_INFO_AUDIO_RENDERING_START = 4,
+    // The player just completed the playback of this data source
+    MEDIA2_INFO_PLAYBACK_COMPLETE = 5,
+    // The player just completed the playback of the full play list
+    MEDIA2_INFO_PLAYLIST_END = 6,
+
+    //1xx
+    // The player just prepared a data source.
+    MEDIA2_INFO_PREPARED = 100,
+    // The player just completed a call play().
+    MEDIA2_INFO_COMPLETE_CALL_PLAY = 101,
+    // The player just completed a call pause().
+    MEDIA2_INFO_COMPLETE_CALL_PAUSE = 102,
+    // The player just completed a call seekTo.
+    MEDIA2_INFO_COMPLETE_CALL_SEEK = 103,
+
+    // 7xx
+    // The video is too complex for the decoder: it can't decode frames fast
+    // enough. Possibly only the audio plays fine at this stage.
+    MEDIA2_INFO_VIDEO_TRACK_LAGGING = 700,
+    // MediaPlayer2 is temporarily pausing playback internally in order to
+    // buffer more data.
+    MEDIA2_INFO_BUFFERING_START = 701,
+    // MediaPlayer2 is resuming playback after filling buffers.
+    MEDIA2_INFO_BUFFERING_END = 702,
+    // Bandwidth in recent past
+    MEDIA2_INFO_NETWORK_BANDWIDTH = 703,
+
+    // 8xx
+    // Bad interleaving means that a media has been improperly interleaved or not
+    // interleaved at all, e.g has all the video samples first then all the audio
+    // ones. Video is playing but a lot of disk seek may be happening.
+    MEDIA2_INFO_BAD_INTERLEAVING = 800,
+    // The media is not seekable (e.g live stream).
+    MEDIA2_INFO_NOT_SEEKABLE = 801,
+    // New media metadata is available.
+    MEDIA2_INFO_METADATA_UPDATE = 802,
+    // Audio can not be played.
+    MEDIA2_INFO_PLAY_AUDIO_ERROR = 804,
+    // Video can not be played.
+    MEDIA2_INFO_PLAY_VIDEO_ERROR = 805,
+
+    //9xx
+    MEDIA2_INFO_TIMED_TEXT_ERROR = 900,
+};
+
+enum media_player2_states {
+    MEDIA_PLAYER2_STATE_ERROR        = 0,
+    MEDIA_PLAYER2_IDLE               = 1 << 0,
+    MEDIA_PLAYER2_INITIALIZED        = 1 << 1,
+    MEDIA_PLAYER2_PREPARING          = 1 << 2,
+    MEDIA_PLAYER2_PREPARED           = 1 << 3,
+    MEDIA_PLAYER2_STARTED            = 1 << 4,
+    MEDIA_PLAYER2_PAUSED             = 1 << 5,
+    MEDIA_PLAYER2_STOPPED            = 1 << 6,
+    MEDIA_PLAYER2_PLAYBACK_COMPLETE  = 1 << 7
+};
+
+// Keep KEY_PARAMETER_* in sync with MediaPlayer2.java.
+// The same enum space is used for both set and get, in case there are future keys that
+// can be both set and get.  But as of now, all parameters are either set only or get only.
+enum media2_parameter_keys {
+    // Streaming/buffering parameters
+    MEDIA2_KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS = 1100,            // set only
+
+    // Return a Parcel containing a single int, which is the channel count of the
+    // audio track, or zero for error (e.g. no audio track) or unknown.
+    MEDIA2_KEY_PARAMETER_AUDIO_CHANNEL_COUNT = 1200,                   // get only
+
+    // Playback rate expressed in permille (1000 is normal speed), saved as int32_t, with negative
+    // values used for rewinding or reverse playback.
+    MEDIA2_KEY_PARAMETER_PLAYBACK_RATE_PERMILLE = 1300,                // set only
+
+    // Set a Parcel containing the value of a parcelled Java AudioAttribute instance
+    MEDIA2_KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400                       // set only
+};
+
+// Keep INVOKE_ID_* in sync with MediaPlayer2.java.
+enum media_player2_invoke_ids {
+    MEDIA_PLAYER2_INVOKE_ID_GET_TRACK_INFO = 1,
+    MEDIA_PLAYER2_INVOKE_ID_ADD_EXTERNAL_SOURCE = 2,
+    MEDIA_PLAYER2_INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3,
+    MEDIA_PLAYER2_INVOKE_ID_SELECT_TRACK = 4,
+    MEDIA_PLAYER2_INVOKE_ID_UNSELECT_TRACK = 5,
+    MEDIA_PLAYER2_INVOKE_ID_SET_VIDEO_SCALING_MODE = 6,
+    MEDIA_PLAYER2_INVOKE_ID_GET_SELECTED_TRACK = 7
+};
+
+}; // namespace android
+
+#endif // ANDROID_MEDIAPLAYER2_TYPES_H
diff --git a/media/libmediaplayer2/include/mediaplayer2/mediaplayer2.h b/media/libmediaplayer2/include/mediaplayer2/mediaplayer2.h
index 0afef1e..11e4f42 100644
--- a/media/libmediaplayer2/include/mediaplayer2/mediaplayer2.h
+++ b/media/libmediaplayer2/include/mediaplayer2/mediaplayer2.h
@@ -17,196 +17,27 @@
 #ifndef ANDROID_MEDIAPLAYER2_H
 #define ANDROID_MEDIAPLAYER2_H
 
-#include <media/mediaplayer_common.h>
-
-#include <arpa/inet.h>
-
+#include <media/AVSyncSettings.h>
 #include <media/AudioResamplerPublic.h>
 #include <media/BufferingSettings.h>
-#include <mediaplayer2/MediaPlayer2EngineClient.h>
-#include <mediaplayer2/MediaPlayer2Engine.h>
+#include <media/Metadata.h>
+#include <media/mediaplayer_common.h>
+#include <mediaplayer2/MediaPlayer2Interface.h>
+#include <mediaplayer2/MediaPlayer2Types.h>
 
-#include <utils/Condition.h>
-#include <utils/KeyedVector.h>
-#include <utils/String8.h>
-#include <utils/ThreadDefs.h>
+#include <utils/Errors.h>
+#include <utils/Mutex.h>
+#include <utils/RefBase.h>
+#include <utils/String16.h>
+#include <utils/Vector.h>
+#include <system/audio-base.h>
 
 namespace android {
 
-struct AVSyncSettings;
 struct ANativeWindowWrapper;
-class DataSource;
 struct DataSourceDesc;
-struct MediaHTTPService;
+class MediaPlayer2AudioOutput;
 
-enum media2_event_type {
-    MEDIA2_NOP               = 0, // interface test message
-    MEDIA2_PREPARED          = 1,
-    MEDIA2_PLAYBACK_COMPLETE = 2,
-    MEDIA2_BUFFERING_UPDATE  = 3,
-    MEDIA2_SEEK_COMPLETE     = 4,
-    MEDIA2_SET_VIDEO_SIZE    = 5,
-    MEDIA2_STARTED           = 6,
-    MEDIA2_PAUSED            = 7,
-    MEDIA2_STOPPED           = 8,
-    MEDIA2_SKIPPED           = 9,
-    MEDIA2_NOTIFY_TIME       = 98,
-    MEDIA2_TIMED_TEXT        = 99,
-    MEDIA2_ERROR             = 100,
-    MEDIA2_INFO              = 200,
-    MEDIA2_SUBTITLE_DATA     = 201,
-    MEDIA2_META_DATA         = 202,
-    MEDIA2_DRM_INFO          = 210,
-    MEDIA2_AUDIO_ROUTING_CHANGED = 10000,
-};
-
-// Generic error codes for the media player framework.  Errors are fatal, the
-// playback must abort.
-//
-// Errors are communicated back to the client using the
-// MediaPlayer2Listener::notify method defined below.
-// In this situation, 'notify' is invoked with the following:
-//   'msg' is set to MEDIA_ERROR.
-//   'ext1' should be a value from the enum media2_error_type.
-//   'ext2' contains an implementation dependant error code to provide
-//          more details. Should default to 0 when not used.
-//
-// The codes are distributed as follow:
-//   0xx: Reserved
-//   1xx: Android Player errors. Something went wrong inside the MediaPlayer2.
-//   2xx: Media errors (e.g Codec not supported). There is a problem with the
-//        media itself.
-//   3xx: Runtime errors. Some extraordinary condition arose making the playback
-//        impossible.
-//
-enum media2_error_type {
-    // 0xx
-    MEDIA2_ERROR_UNKNOWN = 1,
-    // 1xx
-    // MEDIA2_ERROR_SERVER_DIED = 100,
-    // 2xx
-    MEDIA2_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200,
-    // 3xx
-    MEDIA2_ERROR_FAILED_TO_SET_DATA_SOURCE = 300,
-};
-
-
-// Info and warning codes for the media player framework.  These are non fatal,
-// the playback is going on but there might be some user visible issues.
-//
-// Info and warning messages are communicated back to the client using the
-// MediaPlayer2Listener::notify method defined below.  In this situation,
-// 'notify' is invoked with the following:
-//   'msg' is set to MEDIA_INFO.
-//   'ext1' should be a value from the enum media2_info_type.
-//   'ext2' contains an implementation dependant info code to provide
-//          more details. Should default to 0 when not used.
-//
-// The codes are distributed as follow:
-//   0xx: Reserved
-//   7xx: Android Player info/warning (e.g player lagging behind.)
-//   8xx: Media info/warning (e.g media badly interleaved.)
-//
-enum media2_info_type {
-    // 0xx
-    MEDIA2_INFO_UNKNOWN = 1,
-    // The player was started because it was used as the next player for another
-    // player, which just completed playback
-    MEDIA2_INFO_STARTED_AS_NEXT = 2,
-    // The player just pushed the very first video frame for rendering
-    MEDIA2_INFO_VIDEO_RENDERING_START = 3,
-    // The player just pushed the very first audio frame for rendering
-    MEDIA2_INFO_AUDIO_RENDERING_START = 4,
-    // The player just completed the playback of this data source
-    MEDIA2_INFO_PLAYBACK_COMPLETE = 5,
-    // The player just completed the playback of the full play list
-    MEDIA2_INFO_PLAYLIST_END = 6,
-
-    //1xx
-    // The player just prepared a data source.
-    MEDIA2_INFO_PREPARED = 100,
-    // The player just completed a call play().
-    MEDIA2_INFO_COMPLETE_CALL_PLAY = 101,
-    // The player just completed a call pause().
-    MEDIA2_INFO_COMPLETE_CALL_PAUSE = 102,
-    // The player just completed a call seekTo.
-    MEDIA2_INFO_COMPLETE_CALL_SEEK = 103,
-
-    // 7xx
-    // The video is too complex for the decoder: it can't decode frames fast
-    // enough. Possibly only the audio plays fine at this stage.
-    MEDIA2_INFO_VIDEO_TRACK_LAGGING = 700,
-    // MediaPlayer2 is temporarily pausing playback internally in order to
-    // buffer more data.
-    MEDIA2_INFO_BUFFERING_START = 701,
-    // MediaPlayer2 is resuming playback after filling buffers.
-    MEDIA2_INFO_BUFFERING_END = 702,
-    // Bandwidth in recent past
-    MEDIA2_INFO_NETWORK_BANDWIDTH = 703,
-
-    // 8xx
-    // Bad interleaving means that a media has been improperly interleaved or not
-    // interleaved at all, e.g has all the video samples first then all the audio
-    // ones. Video is playing but a lot of disk seek may be happening.
-    MEDIA2_INFO_BAD_INTERLEAVING = 800,
-    // The media is not seekable (e.g live stream).
-    MEDIA2_INFO_NOT_SEEKABLE = 801,
-    // New media metadata is available.
-    MEDIA2_INFO_METADATA_UPDATE = 802,
-    // Audio can not be played.
-    MEDIA2_INFO_PLAY_AUDIO_ERROR = 804,
-    // Video can not be played.
-    MEDIA2_INFO_PLAY_VIDEO_ERROR = 805,
-
-    //9xx
-    MEDIA2_INFO_TIMED_TEXT_ERROR = 900,
-};
-
-
-
-enum media_player2_states {
-    MEDIA_PLAYER2_STATE_ERROR        = 0,
-    MEDIA_PLAYER2_IDLE               = 1 << 0,
-    MEDIA_PLAYER2_INITIALIZED        = 1 << 1,
-    MEDIA_PLAYER2_PREPARING          = 1 << 2,
-    MEDIA_PLAYER2_PREPARED           = 1 << 3,
-    MEDIA_PLAYER2_STARTED            = 1 << 4,
-    MEDIA_PLAYER2_PAUSED             = 1 << 5,
-    MEDIA_PLAYER2_STOPPED            = 1 << 6,
-    MEDIA_PLAYER2_PLAYBACK_COMPLETE  = 1 << 7
-};
-
-// Keep KEY_PARAMETER_* in sync with MediaPlayer2.java.
-// The same enum space is used for both set and get, in case there are future keys that
-// can be both set and get.  But as of now, all parameters are either set only or get only.
-enum media2_parameter_keys {
-    // Streaming/buffering parameters
-    MEDIA2_KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS = 1100,            // set only
-
-    // Return a Parcel containing a single int, which is the channel count of the
-    // audio track, or zero for error (e.g. no audio track) or unknown.
-    MEDIA2_KEY_PARAMETER_AUDIO_CHANNEL_COUNT = 1200,                   // get only
-
-    // Playback rate expressed in permille (1000 is normal speed), saved as int32_t, with negative
-    // values used for rewinding or reverse playback.
-    MEDIA2_KEY_PARAMETER_PLAYBACK_RATE_PERMILLE = 1300,                // set only
-
-    // Set a Parcel containing the value of a parcelled Java AudioAttribute instance
-    MEDIA2_KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400                       // set only
-};
-
-// Keep INVOKE_ID_* in sync with MediaPlayer2.java.
-enum media_player2_invoke_ids {
-    MEDIA_PLAYER2_INVOKE_ID_GET_TRACK_INFO = 1,
-    MEDIA_PLAYER2_INVOKE_ID_ADD_EXTERNAL_SOURCE = 2,
-    MEDIA_PLAYER2_INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3,
-    MEDIA_PLAYER2_INVOKE_ID_SELECT_TRACK = 4,
-    MEDIA_PLAYER2_INVOKE_ID_UNSELECT_TRACK = 5,
-    MEDIA_PLAYER2_INVOKE_ID_SET_VIDEO_SCALING_MODE = 6,
-    MEDIA_PLAYER2_INVOKE_ID_GET_SELECTED_TRACK = 7
-};
-
-// ----------------------------------------------------------------------------
 // ref-counted object for callbacks
 class MediaPlayer2Listener: virtual public RefBase
 {
@@ -214,11 +45,14 @@
     virtual void notify(int64_t srcId, int msg, int ext1, int ext2, const Parcel *obj) = 0;
 };
 
-class MediaPlayer2 : public MediaPlayer2EngineClient
+class MediaPlayer2 : public MediaPlayer2InterfaceListener
 {
 public:
-    MediaPlayer2();
     ~MediaPlayer2();
+
+    static sp<MediaPlayer2> Create();
+    static status_t DumpAll(int fd, const Vector<String16>& args);
+
             void            disconnect();
 
             status_t        getSrcId(int64_t *srcId);
@@ -275,22 +109,43 @@
             audio_port_handle_t getRoutedDeviceId();
             status_t        enableAudioDeviceCallback(bool enabled);
 
-private:
-            void            clear_l();
-            status_t        seekTo_l(int msec, MediaPlayer2SeekMode mode);
-            status_t        prepareAsync_l();
-            status_t        getDuration_l(int *msec);
-            status_t        attachNewPlayer(const sp<MediaPlayer2Engine>& player, long srcId);
-            status_t        reset_l();
-            status_t        checkStateForKeySet_l(int key);
+            status_t        dump(int fd, const Vector<String16>& args);
 
-    sp<MediaPlayer2Engine>      mPlayer;
+private:
+    MediaPlayer2();
+    bool init();
+
+    // @param type Of the metadata to be tested.
+    // @return true if the metadata should be dropped according to
+    //              the filters.
+    bool shouldDropMetadata(media::Metadata::Type type) const;
+
+    // Add a new element to the set of metadata updated. Noop if
+    // the element exists already.
+    // @param type Of the metadata to be recorded.
+    void addNewMetadataUpdate(media::Metadata::Type type);
+
+    // Disconnect from the currently connected ANativeWindow.
+    void disconnectNativeWindow_l();
+
+    status_t setAudioAttributes_l(const Parcel &request);
+
+    void clear_l();
+    status_t seekTo_l(int msec, MediaPlayer2SeekMode mode);
+    status_t prepareAsync_l();
+    status_t getDuration_l(int *msec);
+    status_t reset_l();
+    status_t checkStateForKeySet_l(int key);
+
+    pid_t                       mPid;
+    uid_t                       mUid;
+    sp<MediaPlayer2Interface>   mPlayer;
+    sp<MediaPlayer2AudioOutput> mAudioOutput;
     int64_t                     mSrcId;
     thread_id_t                 mLockThreadId;
-    Mutex                       mLock;
+    mutable Mutex               mLock;
     Mutex                       mNotifyLock;
     sp<MediaPlayer2Listener>    mListener;
-    void*                       mCookie;
     media_player2_states        mCurrentState;
     int                         mCurrentPosition;
     MediaPlayer2SeekMode        mCurrentSeekMode;
@@ -304,7 +159,20 @@
     int                         mVideoWidth;
     int                         mVideoHeight;
     audio_session_t             mAudioSessionId;
+    audio_attributes_t *        mAudioAttributes;
     float                       mSendLevel;
+
+    sp<ANativeWindowWrapper>    mConnectedWindow;
+
+    // Metadata filters.
+    media::Metadata::Filter mMetadataAllow;  // protected by mLock
+    media::Metadata::Filter mMetadataDrop;  // protected by mLock
+
+    // Metadata updated. For each MEDIA_INFO_METADATA_UPDATE
+    // notification we try to update mMetadataUpdated which is a
+    // set: no duplicate.
+    // getMetadata clears this set.
+    media::Metadata::Filter mMetadataUpdated;  // protected by mLock
 };
 
 }; // namespace android