/* 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.
 *
 */

/*
 * Code based on example (play_title.c, Copyright (C) 2001 Billy Biggs <vektor@dumbterm.net>)
 * of libdvdread package
 */

#ifndef NMM_DVDREADNODE_HPP
#define NMM_DVDREADNODE_HPP NMM_DVDREADNODE_HPP

#if defined(__FreeBSD__)
#define __STDC_LIMIT_MACROS 1	// so that dvdread sees UINT8_MAX
#endif

#include "nmm/nmm_prefix.hpp"

#include "nmm/multimedia/GenericSourceNode.hpp"
#include "nmm/plugins/file/dvd/interfaces/IDVDImpl.hpp"
#include "nmm/plugins/interfaces/IProgressImpl.hpp"

extern "C" {
#include <dvdread/ifo_types.h>
#include <dvdread/nav_types.h>
}

namespace NMM {
  
  /**
   *  @brief DVD Read Node
   *
   *  @bug The format analysis is not complete. Output format is set to unspecified av/mpegps, requiring analyseData in successor node
   *  @bug It is not yet possible to determine the current chapter, let alone to stop at a given chapter
   *  @bug Timestamps seem to be broken around angle blocks
   *
   *  This node is a simple DVD reader node based on libdvdread. It can be used for reading individual
   *  titles and chapters of a DVD, which is suitable for dumping VOB streams and transcoding.
   *  It does not support DVD menu navigation. For this purpose, use a DVDNavReadNode instead.
   */
  class DVDReadNode :
    public GenericSourceNode,
    public IDVDImpl,
    public IProgressImpl
  {
  public:
    /**
     *  @brief Constructor
     */
    DVDReadNode(const char * name = "DVDReadNode",
		StreamQueue::Mode = StreamQueue::MODE_SUSPEND,
		int = StreamQueue::DEFAULT_SIZE);
    
    /**
     *  @name IDevice Interface
     */
    //@{
    /**
     *  @brief Set device
     *  @param device Path to device file
     *
     *  This method sets the device of the DVD drive.
     */
    virtual void setDevice(const string& device)
      throw();
    
    /**
     *  @brief Get device
     *  @return Path to device file
     *
     *  This methos returns the device of the DVD drive.
     */
    virtual string getDevice() const;
    //@}
    
    /**
     *  @name IDVD Interface
     */
    //@{
    /**
     *  @brief Select chapter, title and view angle
     *  @param title Title to play
     *  @param chapter Chapter to play
     *  @param angle View angle to play
     *  @return SUCCESS if the method succeeds, otherwise FAILURE
     *
     *  This method sets the @a title, @a chapter and view @a angle to play. The title must be between 1 and getTitles()
     *  inclusive, the chapter must be between 1 and getChapters(title) inclusive and the view angle must be between
     *  1 and getAngles(title) inclusive. Otherwise the method fails.
     */
    virtual Result select(const nmm_uint32& title, const nmm_uint32& chapter, const nmm_uint32& angle);
    
    /**
     *  @brief Get current title
     *  @return The current title number
     *
     *  This method returns the number of the title currently being played. If no title is being played, or the
     *  current title is invalid, the result is zero.
     */
    virtual nmm_uint32 getCurrentTitle() const;
    
    /**
     *  @brief Get current chapter
     *  @return The current chapternumber
     *
     *  @bug Currently only returns the chapter number set by the last select call, not the current chapter
     *
     *  This method returns the number of the chapter currently being played. If no chapter is being played, or the
     *  current chapter is invalid, the result is zero.
     */
    virtual nmm_uint32 getCurrentChapter() const;
    
    /**
     *  @brief Get number of titles
     *  @return The number of titles on the DVD
     *
     *  This method returns the number of titles on the DVD, which is also the highest possible title number.
     */
    virtual nmm_uint32 getTitles() const;
    
    /**
     *  @brief Get number of chapters in a title
     *  @param title Title number
     *  @return The number of chapters in the title
     *
     *  This method returns the number of chapters in the given @a title, which is also the highest possible chapter
     *  number for that title. The title number must be between 1 and getTitles() inclusive.
     */
    virtual nmm_uint32 getChapters(const nmm_uint32& title) const;

    /**
     *  @brief Get number of view angles in a title
     *  @param title Title number
     *  @return The number of angles in the title
     *
     *  This method returns the number of angles in the given @a title, which is also the highest possible angle
     *  number for that title. The title number must be between 1 and getTitles() inclusive.
     */
    virtual nmm_uint32 getAngles(const nmm_uint32& title) const;
    
    /**
     *  @brief Send a flush event
     *
     *  This method does nothing for this node.
     */
    virtual void sendFlush();
    
    /**
     *  @brief Reset the DVD
     *
     *  Reset the DVD to the beginning. For this node, this is equivalent to calling select(1,1,1).
     */
    virtual void reset();
    //@}
    
    /**
     *  @name IProgress Interface
     */
    //@{
    /**
     *  @brief Enable or disable sending progress information
     *  @param enabled True to enable sending progress information
     *
     *  This method enables or disables sending of progress information. If enables, this node will send progress
     *  events (IProgressListener::setProgress) at regular intervals, defined by the node.
     */
    virtual void sendProgressInformation(const nmm_bool& enabled);
    //@}

    virtual void setProgressInterval(const nmm_int32& buffers);
    
  protected:
    /**
     *  @brief The node's doInit method
     *
     *  This method sets the static properties.
     */
    virtual Result doInit();
    
    /**
     *  @brief The node's doInitOutput method
     *
     *  This method attempts to open the DVD, analyzes its format and sets the working properties.
     */
    virtual Result doInitOutput();

    /**
     *  @brief The node's doDeinitOutput method
     *
     *  This method closes the DVD.
     */
    virtual Result doDeinitOutput();
    
    /**
     *  @brief The node's doActivate method
     *
     *  This method Allocates the read buffer and resets the event state.
     */
    virtual Result doActivate();

    /**
     *  @brief The node's doDeactivate method
     *
     *  This method Deallocates the read buffer.
     */
    virtual Result doDeactivate();
    
    /**
     *  @brief The nodes buffer processing method.
     *
     *  This method reads blocks of data from the DVD and generates buffers. It also handles transitions
     *  between cells on the DVD.
     */
    virtual Message* processBuffer(Buffer*);

  private:
    /**
     *  @brief Open the DVD
     *  @return SUCCESS if the DVD has been successfully opened, otherwise FAILURE
     *
     *  This method opens the DVD, performs CSS authentification if necessary and analyzes the format.
     */
    Result openDVD();
    
    /**
     *  @brief Close the DVD
     *  
     *  This method closes the DVD reader and the associated VMG file.
     */
    void closeDVD();
    
    /**
     *  @brief Open DVD title
     *  @param title Title number
     *  @return SUCCESS if the DVD title has been successfully opened, otherwise FAILURE
     *
     *  This method opens the DVD file for the given title.
     */
    Result openDVDTitle(int title);
    
    /**
     *  @brief Close DVD title
     *
     *  This method closes the current DVD title and the associated VTS file.
     */
    void closeDVDTitle();
    
    /**
     *  @brief Check DVD format
     *  @param pes_stream Returns whether the DVD stream is a packed elementary (PES) stream
     *  @param mpeg_audio Returns whether the DVD stream contains MPEG audio
     *  @param ac3_audio Returns whether the DVD stream contains AC3 audio
     *  @param mpeg2_video Returns whether the DVD stream contains MPEG version 2 video
     *  @param mpeg1_video Returns whether the DVD stream contains MPEG version 1 video
     *  @param width Returns the X-resolution of the video in pixels
     *  @param height Returns the Y-resolution of the video in pixels
     *  @param frame_rate_code Returns the MPEG frame rate code of the video
     *  @param frame_rate Returns the number of frames per second of the video
     *  @param ratio_x Returns the X aspect ratio of the video
     *  @param ratio_y Returns the Y aspect ratio of the video
     *  @return SUCCESS if the format analysis was successfull, otherwise FAILURE
     *
     *  @bug The frame_rate and pes_stream fields are currently hardcoded and not returned correctly
     *
     *  This method analyzes the DVD format based on the information in the video management (VMG) file.
     *  The information is used to determine the output format of the node.
     */
    Result checkFormat(bool&   pes_stream,
		       bool&   mpeg_audio,
		       bool&   ac3_audio,
		       bool&   mpeg2_video,
		       bool&   mpeg1_video,
		       int&    width,
		       int&    height,
		       int&    frame_rate_code,
		       double& frame_rate,
		       int&    ratio_x,
		       int&    ratio_y);
    
    /**
     *  @brief Next cell
     *  @return true, if the next cell is valid, otherwise false
     *
     *  This method computes __next_cell and __current_cell for the next cell.
     *  __next_cell must point to the beginning of a block or a cell outside a block.
     */
    bool nextCell();
    
  private:
    /**
     *  @brief Event states
     *
     *  The event state controls which events are sent by the next processBuffer call
     */
    enum EventState {
      /** Send no events.
       */
      EVENT_NONE = 1,
      
      /** Send ITrack::startTrack event, then go to state EVENT_NONE.
       */
      EVENT_START_TRACK = 2,
      
      /** Send ITrack::endTrack event, then go to state EVENT_START_TRACK.
       */
      EVENT_NEXT_TRACK = 4
    };
    
    /** Path of the DVD device.
     */
    string __device;
    
    /** Current title ID.
     */
    unsigned int __title;
    
    /** Current chapter ID.
     */
    unsigned int __chapter;
    
    /** Current view angle.
     */
    unsigned int __angle;
    
    /** Current program chain ID.
     */
    int __pgc_id;
    
    /** We are at the beginning of a new cell.
     */
    bool __cell_finished;
    
    /** Starting cell of this chapter.
     */
    int __start_cell;
    
    /** Current cell.
     */
    int __current_cell;
    
    /** Next cell to play when __cell_finished.
     */
    int __next_cell;
    
    /** Current sector in current cell.
     */
    unsigned int __current_sector;
    
    /** Internal title number.
     */
    int __ttn;
    
    /** Program number.
     */
    int __pgn;
    
    /** Read buffer.
     */
    vector<unsigned char> __read_buffer;
    
    /** DVD Reader state.
     */
    dvd_reader_t *__dvd_reader;
    
    /** Currently opened DVD file.
     */
    dvd_file_t *__dvd_file;
    
    /** DVD Video management (VMG) file for DVD.
     */
    ifo_handle_t *__vmg_file;
    
    /** Title search pointer table for DVD.
     */
    tt_srpt_t *__tt_srpt;
    
    /** Video title set (VTS) file for current title.
     */
    ifo_handle_t *__vts_file;
    
    /** Search pointer table for current title set.
     */
    vts_ptt_srpt_t *__vts_ptt_srpt;
    
    /** Current program chain.
     */
    pgc_t *__pgc;
    
    /** Mutex for title/chapter/angle changes
     */
    ThreadMutex __select_mutex;
    
    /** Current event state.
     */
    EventState __event_state;
    
    /** Send syncReset event.
     */
    bool __send_sync_reset;
    
    /** Send setProgress event.
     */
    bool __send_progress;
    
    /** Buffer saved across processBuffer calls.
     */
    Buffer* __save_buffer;
    
    /** Number of buffers per progress event.
     */
    unsigned int __buffers_before_progress;
    
    /** Buffers since last progress event.
     */
    unsigned int __buffers_progress;
    
    /** Length of current chapter in sectors.
     */
    unsigned int __title_length;
    
    /** Current position in current chapter in sectors.
     */
    unsigned int __title_position;
  };
  
}

#include "nmm/nmm_suffix.hpp"

#endif //NMM_DVDREADNODE_HPP
