/* Network-Integrated Multimedia Middleware (NMM)
 * http://www.motama.com/nmm.html
 *  
 * Copyright (C) 2006-2007
 * Motama GmbH, Saarbruecken, Germany
 * http://www.motama.com
 *  
 * This file is part of NMM. 
 * 
 * NMM is free software; you can redistribute it and/or modify it    
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; only version 2 of the License.      
 * 
 * NMM is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public 
 * License for more details.  
 * 
 * You should have received a copy of the GNU General Public License 
 * along with NMM; if not, write to the Free Software Foundation,    
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */


#ifndef _NMM_FFMPEGDECODENODE_HPP_
#define _NMM_FFMPEGDECODENODE_HPP_ _NMM_FFMPEGDECODENODE_HPP_

#include "nmm/nmm_prefix.hpp"

#include <sys/time.h>

#include "nmm/multimedia/GenericProcessorNode.cpp"
#include "nmm/utils/time/TimedElement.hpp"
#include "nmm/multimedia/interfaces/ITrackImpl.hpp"
#include "nmm/plugins/interfaces/IVideoDelayImpl.hpp"
#include "nmm/plugins/interfaces/IKeyframeImpl.hpp"

class AVCodec;
class AVCodecContext;
class AVFrame;

namespace NMM {

  /**
   * This class takes encoded YUV-Video-frames and converts
   * them to decoded frames by using the FFMpeg-library from
   * http://ffmpeg.sourceforge.net/
   *
   * This Node has one Input Stream and one Output Stream.
   */
  class FFMpegDecodeNode :
    public GenericProcessorNode,
    public TimedElement,
    public ITrackImpl,
    public IVideoDelayImpl,
    public IKeyframeImpl
  {
  private:
    class FFMpegHandle;

    FFMpegHandle* ffmpeg;    ///< class containing all avcodec relevant stuff
    int ratio_x;             ///< X aspect ratio
    int ratio_y;             ///< Y aspect ratio
    int height;              ///< height of the frames
    int height_half;         ///< height DIV 2
    int width;               ///< width of the frames
    int width_half;          ///< width DIV 2
    float framerate;	     ///< the frame rate of the sequence to be encoded
    const int framerate_base; ///< constant to bring framerates to integer values
    int int_framerate;       ///< the framerate as integer (framerate * framerate_base);
    long bitrate;	     ///< the bitrate of the target encoded stream
    int gop_size;            ///< The size of one Group of Pictures

    int avframe_size;        ///< size of the Y-Plane of an image
    int out_size;            ///< the output size of an encoded frame

    int frame_count;         ///< count of frames that are encoded
    Timestamp timestamp;     ///< The timestamp to put in the next outgoing buffer.
    Timestamp in_buf_ts;

    struct timeval start_time; ///< start time of the stream, 0 in our case.
    struct timeval tv;       ///< remember time to calculate frames per second
    struct timezone tz;      ///< timezone
    int startsec;            ///< the second we started
    int neededsecs;          ///< second since start
    float encfps;            ///< average frames per second

    int got_picture;         ///< >0 if data could be decoded
    Buffer* saved_buffer;    ///< saved incoming buffer
    unsigned char* out_buffer_data1;  ///< pointer to outgoing data
    unsigned char* out_buffer_data2;  ///< pointer to outgoing data
    unsigned char* src1;     ///< pointer to avcodec data
    unsigned char* src2;     ///< pointer to avcodec data
    int out_buffer_size;     ///< precalculated outgoing buffer size
    int line;

    // some wmv stuff
    int video_extradata_size;
    string video_extradata;

    int vid_delay;           ///< video delay

    bool skip_until_keyframe;///< flag to indicat that all non-keyframes until the next kf should be dropped

    typedef std::map<std::string, int> CodecMap;
    typedef CodecMap::iterator CodecIterator;
    typedef CodecMap::const_iterator CodecConstIterator;

    CodecMap codecs;       ///< FourCC codes of all available codecs, mapped to codec IDs.
    std::string default_codec; ///< FourCC code of default codec.

  public:
    FFMpegDecodeNode(const char* name = "FFMpegDecodeNode",
		    StreamQueue::Mode qmode = StreamQueue::MODE_SUSPEND,
		    int qsize = StreamQueue::DEFAULT_SIZE);
    ~FFMpegDecodeNode();

  protected:
    /* GenericNode */
    virtual Result doInit();
    virtual Result doInitOutput();
    virtual Result doDeinitOutput();
    virtual Result doDeactivate();
    virtual Result doFlush();
    virtual Message* processBuffer(Buffer*);

    /* ITrackImpl */
    virtual Result started(const Interval& overall_duration);
    virtual Result startTrack(const string&);
    virtual Result endTrack();
    virtual Result finished();

    /* IVideoDelayImpl */
    virtual Result setVideoDelay(const nmm_int32&);

    /* IKeyframeImpl */
    virtual Result setKeyframe();

  private:
    void detectAllCodecs() throw();
    void addCodec(const std::string& fourcc, int id);
    void updateFormat();
    Result initContext();
    /**
     * struct FFMpegHandle: This is used to handle all ffmpeg relevant stuff
     */
   struct FFMpegHandle {
     AVCodec* ffAVCodec;
     AVCodecContext* ffavcc;
     AVFrame* avframe;
     FFMpegHandle();
   };

  };

}

#include "nmm/nmm_suffix.hpp"

#endif //_NMM_FFMPEGDECODENODE_HPP_
