/*
 * Copyright (C) 2013 Google 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.
 */

#ifndef SourceBuffer_h
#define SourceBuffer_h

#if ENABLE(MEDIA_SOURCE)

#include "ActiveDOMObject.h"
#include "EventTarget.h"
#include "ExceptionCode.h"
#include "GenericEventQueue.h"
#include "ScriptWrappable.h"
#include "SourceBufferAppendMode.h"
#include "SourceBufferPrivateClient.h"
#include "Timer.h"
#include <runtime/ArrayBufferView.h>
#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

class MediaSource;
class SourceBufferPrivate;
class TimeRanges;

class SourceBuffer : public RefCounted<SourceBuffer>, public ActiveDOMObject, public EventTarget, public SourceBufferPrivateClient {
public:
    static PassRefPtr<SourceBuffer> create(PassRefPtr<SourceBufferPrivate>, MediaSource*);

    virtual ~SourceBuffer();

    void rangeRemoval(const MediaTime& start, const MediaTime& end);

    // SourceBuffer.idl methods
    bool updating() const { return m_updating; }
    PassRefPtr<TimeRanges> buffered(ExceptionCode&) const;
    double timestampOffset() const;
    void setTimestampOffset(double, ExceptionCode&);

    double appendWindowStart() const;
    void setAppendWindowStart(double, ExceptionCode&);
    double appendWindowEnd() const;
    void setAppendWindowEnd(double, ExceptionCode&);

    void append(PassRefPtr<ArrayBuffer> data, ExceptionCode&);
    void append(PassRefPtr<ArrayBufferView> data, ExceptionCode&);
    void appendBuffer(PassRefPtr<ArrayBuffer> data, ExceptionCode& ec) { append(data, ec); }
    void appendBuffer(PassRefPtr<ArrayBufferView> data, ExceptionCode& ec) { append(data, ec); }
    void abort(ExceptionCode&);
    void remove(double start, double end, ExceptionCode&);

    void abortIfUpdating();
    void removedFromMediaSource();

    // ActiveDOMObject interface
    virtual bool hasPendingActivity() const OVERRIDE;
    virtual void stop() OVERRIDE;

    // EventTarget interface
    virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
    virtual EventTargetInterface eventTargetInterface() const OVERRIDE;

    using RefCounted<SourceBuffer>::ref;
    using RefCounted<SourceBuffer>::deref;

    SourceBufferAppendMode mode() const { return m_mode; }
    void setMode(Optional<SourceBufferAppendMode>, ExceptionCode&);

    bool shouldGenerateTimestamps() const { return m_shouldGenerateTimestamps; }
    void setShouldGenerateTimestamps(bool flag) { m_shouldGenerateTimestamps = flag; }

    DEFINE_ATTRIBUTE_EVENT_LISTENER(updatestart);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(update);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(updateend);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);

protected:
    // EventTarget interface
    virtual EventTargetData* eventTargetData() OVERRIDE;
    virtual EventTargetData* ensureEventTargetData() OVERRIDE;
    virtual void refEventTarget() OVERRIDE { ref(); }
    virtual void derefEventTarget() OVERRIDE { deref(); }

private:
    SourceBuffer(PassRefPtr<SourceBufferPrivate>, MediaSource*);

    virtual const char* activeDOMObjectName() const OVERRIDE { return "SourceBuffer"; }

    // SourceBufferPrivateClient
    virtual void sourceBufferPrivateDidEndStream(SourceBufferPrivate*, const WTF::AtomicString&);
    virtual void sourceBufferPrivateDidReceiveInitializationSegment(SourceBufferPrivate*, const InitializationSegment&) OVERRIDE;
    virtual void sourceBufferPrivateDidReceiveSample(SourceBufferPrivate*, PassRefPtr<MediaSample>) OVERRIDE;
    virtual bool sourceBufferPrivateHasAudio(const SourceBufferPrivate*) const OVERRIDE;
    virtual bool sourceBufferPrivateHasVideo(const SourceBufferPrivate*) const OVERRIDE;

    static const WTF::AtomicString& decodeError();
    static const WTF::AtomicString& networkError();

    bool isRemoved() const;
    void scheduleEvent(const AtomicString& eventName);

    void appendBufferInternal(const unsigned char*, unsigned, ExceptionCode&);
    void appendBufferTimerFired(Timer<SourceBuffer>*);

    void didDropSample();

    void removeTimerFired(Timer<SourceBuffer>*);
    void removeCodedFrames(const MediaTime& start, const MediaTime& end);

    size_t extraMemoryCost() const;
    void reportExtraMemoryAllocated();

    void appendData(const unsigned char* data, unsigned length);

    RefPtr<SourceBufferPrivate> m_private;
    MediaSource* m_source;
    GenericEventQueue m_asyncEventQueue;
    EventTargetData m_eventTargetData;
    SourceBufferAppendMode m_mode;

    bool m_updating;
    MediaTime m_timestampOffset;
    MediaTime m_appendWindowStart;
    MediaTime m_appendWindowEnd;

    MediaTime m_groupStartTimestamp;
    MediaTime m_groupEndTimestamp;

    Vector<unsigned char> m_pendingAppendData;
    Timer<SourceBuffer> m_appendBufferTimer;

    size_t m_reportedExtraMemoryCost;

    MediaTime m_pendingRemoveStart;
    MediaTime m_pendingRemoveEnd;
    Timer<SourceBuffer> m_removeTimer;

    bool m_shouldGenerateTimestamps;
};

} // namespace WebCore

#endif

#endif
