/*
 * Copyright (C) 2011, 2015 Ericsson AB. All rights reserved.
 * Copyright (C) 2013 Google Inc. All rights reserved.
 * Copyright (C) 2015 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "MediaStreamPrivate.h"

#if ENABLE(MEDIA_STREAM)

#include "GraphicsContext.h"
#include "IntRect.h"
#include <wtf/MainThread.h>
#include <wtf/RefCounted.h>
#include <wtf/Vector.h>

namespace WebCore {

Ref<MediaStreamPrivate> MediaStreamPrivate::create(const Vector<RefPtr<RealtimeMediaSource>>& audioSources, const Vector<RefPtr<RealtimeMediaSource>>& videoSources)
{
    MediaStreamTrackPrivateVector tracks;
    tracks.reserveCapacity(audioSources.size() + videoSources.size());

    for(int i = 0; i < audioSources.size(); ++i)
        tracks.append(MediaStreamTrackPrivate::create(audioSources[i]));

    for(int i = 0; i < videoSources.size(); ++i)
        tracks.append(MediaStreamTrackPrivate::create(videoSources[i]));

    return MediaStreamPrivate::create(tracks);
}

MediaStreamPrivate::MediaStreamPrivate(const MediaStreamTrackPrivateVector& tracks, String&& id)
    : m_id(WTFMove(id))
	, m_activeVideoTrack(0)
    , m_isActive(false)
{
    ASSERT(!m_id.isEmpty());

    for(int i = 0; i < tracks.size(); ++i) {
    	const RefPtr<MediaStreamTrackPrivate>& track = tracks[i];
        track->addObserver(*this);
        m_trackSet.add(track->id(), track);
    }

    updateActiveState(NotifyClientOption::DontNotify);
}

MediaStreamPrivate::~MediaStreamPrivate()
{
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it)
        it->second->removeObserver(*this);
}

void MediaStreamPrivate::addObserver(MediaStreamPrivate::Observer& observer)
{
    m_observers.append(&observer);
}

void MediaStreamPrivate::removeObserver(MediaStreamPrivate::Observer& observer)
{
    size_t pos = m_observers.find(&observer);
    if (pos != notFound)
        m_observers.remove(pos);
}

MediaStreamTrackPrivateVector MediaStreamPrivate::tracks() const
{
    MediaStreamTrackPrivateVector tracks;
    tracks.reserveCapacity(m_trackSet.size());
    copyValuesToVector(m_trackSet, tracks);

    return tracks;
}

void MediaStreamPrivate::updateActiveState(NotifyClientOption notifyClientOption)
{
    bool newActiveState = false;
    for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it) {
    	auto& track = it->second;
        if (!track->ended()) {
            newActiveState = true;
			break;
        }
    }

    updateActiveVideoTrack();

    // A stream is active if it has at least one un-ended track.
    if (newActiveState == m_isActive)
        return;

    m_isActive = newActiveState;

    if (notifyClientOption == NotifyClientOption::Notify) {
    	for(int i = 0; i < m_observers.size(); ++i)
    		m_observers[i]->activeStatusChanged();
    }
}

void MediaStreamPrivate::addTrack(PassRefPtr<MediaStreamTrackPrivate> track, NotifyClientOption notifyClientOption)
{
    if (m_trackSet.contains(track->id()))
        return;

    track->addObserver(*this);
    m_trackSet.add(track->id(), track);

    if (notifyClientOption == NotifyClientOption::Notify) {
    	for(int i = 0; i < m_observers.size(); ++i)
			m_observers[i]->didAddTrack(*track.get());
    }

    updateActiveState(notifyClientOption);
}

void MediaStreamPrivate::removeTrack(MediaStreamTrackPrivate& track, NotifyClientOption notifyClientOption)
{
    if (!m_trackSet.remove(track.id()))
        return;

    track.removeObserver(*this);

    if (notifyClientOption == NotifyClientOption::Notify) {
    	for(int i = 0; i < m_observers.size(); ++i)
			m_observers[i]->didRemoveTrack(track);
    }

    updateActiveState(notifyClientOption);
}

void MediaStreamPrivate::startProducingData()
{
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it)
		it->second->startProducingData();
}

void MediaStreamPrivate::stopProducingData()
{
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it)
		it->second->stopProducingData();
}

bool MediaStreamPrivate::isProducingData() const
{
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it) {
		auto& track = it->second;
        if (track->isProducingData())
            return true;
    }
    return false;
}

bool MediaStreamPrivate::hasVideo()
{
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it) {
		auto& track = it->second;
        if (track->type() == RealtimeMediaSource::Type::Video && track->enabled() && !track->ended())
            return true;
    }
    return false;
}

bool MediaStreamPrivate::hasAudio()
{
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it) {
		auto& track = it->second;
		if (track->type() == RealtimeMediaSource::Type::Audio && track->enabled() && !track->ended())
            return true;
    }
    return false;
}

FloatSize MediaStreamPrivate::intrinsicSize() const
{
    FloatSize size;

    if (m_activeVideoTrack) {
        const RealtimeMediaSourceSettings& setting = m_activeVideoTrack->settings();
        size.setWidth(setting.width());
        size.setHeight(setting.height());
    }

    return size;
}

#if USE(ACCELERATED_COMPOSITING)
PlatformLayer* MediaStreamPrivate::platformLayer() const
{
    if (!m_activeVideoTrack)
        return 0;

    return m_activeVideoTrack->source()->platformLayer();
}
#endif

void MediaStreamPrivate::paintCurrentFrameInContext(GraphicsContext& context, const FloatRect& rect)
{
    if (context.paintingDisabled())
        return;

    if (active() && m_activeVideoTrack)
        m_activeVideoTrack->paintCurrentFrameInContext(context, rect);
    else {
        GraphicsContextStateSaver stateSaver(context);
        context.translate(rect.x(), rect.y() + rect.height());
        context.scale(FloatSize(1, -1));
        IntRect paintRect(IntPoint(0, 0), IntSize(rect.width(), rect.height()));
        context.fillRect(paintRect, Color::black);
    }
}

RefPtr<Image> MediaStreamPrivate::currentFrameImage()
{
    if (!active() || !m_activeVideoTrack)
        return nullptr;

    return m_activeVideoTrack->source()->currentFrameImage();
}

void MediaStreamPrivate::updateActiveVideoTrack()
{
    m_activeVideoTrack = 0;
	for(auto it = m_trackSet.begin(); it != m_trackSet.end(); ++it) {
		auto& track = it->second;
        if (!track->ended() && track->type() == RealtimeMediaSource::Type::Video) {
            m_activeVideoTrack = track.get();
            break;
        }
    }
}

void MediaStreamPrivate::characteristicsChanged()
{
	for(int i = 0; i < m_observers.size(); ++i)
		m_observers[i]->characteristicsChanged();
}

namespace {
struct MutedContext {
    WTF_MAKE_NONCOPYABLE(MutedContext); WTF_MAKE_FAST_ALLOCATED;
public:
    MutedContext(MediaStreamPrivate& mediaStreamPrivate)
		: weakThis(makeWeakPtr(mediaStreamPrivate))
    {
    }

    static void didReceiveTask(void* untypedContext)
    {
        ASSERT(isMainThread());

        OwnPtr<MutedContext> context = adoptPtr(static_cast<MutedContext*>(untypedContext));
        ASSERT(context);
        if (!context->weakThis)
    		return;

        context->weakThis->characteristicsChanged();
    }

    WeakPtr<MediaStreamPrivate> weakThis;
};

}

void MediaStreamPrivate::trackMutedChanged(MediaStreamTrackPrivate&)
{
    callOnMainThread(MutedContext::didReceiveTask, new MutedContext(*this));
}

void MediaStreamPrivate::trackSettingsChanged(MediaStreamTrackPrivate&)
{
    characteristicsChanged();
}

namespace {
struct EnabledChangedContext {
    WTF_MAKE_NONCOPYABLE(EnabledChangedContext); WTF_MAKE_FAST_ALLOCATED;
public:
    EnabledChangedContext(MediaStreamPrivate& mediaStreamPrivate)
		: weakThis(makeWeakPtr(mediaStreamPrivate))
    {
    }

    static void didReceiveTask(void* untypedContext)
    {
        ASSERT(isMainThread());

        OwnPtr<EnabledChangedContext> context = adoptPtr(static_cast<EnabledChangedContext*>(untypedContext));
        ASSERT(context);
        if (!context->weakThis)
    		return;

        context->weakThis->characteristicsChanged();
    }

    WeakPtr<MediaStreamPrivate> weakThis;
};

}

void MediaStreamPrivate::trackEnabledChanged(MediaStreamTrackPrivate&)
{
    updateActiveVideoTrack();

    callOnMainThread(EnabledChangedContext::didReceiveTask, new EnabledChangedContext(*this));
}

namespace {
struct EndedContext {
    WTF_MAKE_NONCOPYABLE(EndedContext); WTF_MAKE_FAST_ALLOCATED;
public:
    EndedContext(MediaStreamPrivate& mediaStreamPrivate)
		: weakThis(makeWeakPtr(mediaStreamPrivate))
    {
    }

    static void didReceiveTask(void* untypedContext)
    {
        ASSERT(isMainThread());

        OwnPtr<EndedContext> context = adoptPtr(static_cast<EndedContext*>(untypedContext));
        ASSERT(context);
        if (!context->weakThis)
    		return;

        RefPtr<MediaStreamPrivate> protectedThis(context->weakThis.get());
        context->weakThis->updateActiveState(MediaStreamPrivate::NotifyClientOption::Notify);
        context->weakThis->characteristicsChanged();
    }

    WeakPtr<MediaStreamPrivate> weakThis;
};

}

void MediaStreamPrivate::trackEnded(MediaStreamTrackPrivate&)
{
    callOnMainThread(EndedContext::didReceiveTask, new EndedContext(*this));
}

#if 0
void MediaStreamPrivate::scheduleDeferredTask(std::function<void()> function)
{
    ASSERT(function);
    auto weakThis = createWeakPtr();
    callOnMainThread([weakThis, function] {
        if (!weakThis)
            return;

        function();
    });
}
#endif

} // namespace WebCore

#endif // ENABLE(MEDIA_STREAM)
