/***********************************************************************
 * VirtualDub Modification for OGM
 *
 * Copyright (C) 2002 Cyrius
 *
 * This program 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; either version 2 of the License, or
 * (at your option) any later version.
 *   
 * This program 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 this program (see the file COPYING); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * or visit http://www.gnu.org/copyleft/gpl.html
 *
 ***********************************************************************
 *
 *
 *
 */

#ifndef __PACKETIZER_H__
#define __PACKETIZER_H__

/*
 * All this structure was inspired by the OgmTools project
 * Written by Moritz Bunkus <moritz@bunkus.org>
 * Based on Xiph.org's 'oggmerge' found in their CVS repository
 * See http://www.xiph.org
 */
#include "../ogg/ogg.h"

#include "OGMCommon.h"
#include "OGMSerialGenerator.h"
#include "OGMStreams.h"
#include "../error.h"

// Maximum bytes to allocate for "tagging" data (i.e. add the headers)
// Maximum reached for data packets : 1 (header) + 8 (coding the number of samples in data)
#define OVERHEAD        9

// Some types of "frame"
/*#define F_OTHER         -1
#define F_HEADER        1
#define F_COMMENT       2*/
#define F_DATA          3
#define F_VORBIS        4


// Definition of time_stamp type (time unit : 1 ms)
typedef d64 time_stamp;
#define MAX_TIMESTAMP   ((d64)3.40282347e+38F)

/*
 * Structure holding an ogg_page and its timestamp.
 * For an optimal behavior of this struture, please use
 * the new and delete operators. This allow automatic
 * deletion of pointed objects or strutures.
 */
struct muxer_page {
  ogg_page    *page;           // Pointer to the ogg_page
	time_stamp   last_timestamp; // timestamp of the previous frame (coming from the same stream)
  int          priority;       // Priority of the Page

	// What to do when created by new operator
	void *operator new(unsigned int nAlloc) {
		muxer_page* new_mpage = (muxer_page*)malloc(nAlloc);
		if(new_mpage) {
			new_mpage->priority       = 0;
			new_mpage->page           = NULL;
			new_mpage->last_timestamp = 0.;
		}
		return new_mpage;
	}

	// What to do with delete operator
	void operator delete(void* old_mpage) {
		// If page is not NULL, free the memory by deleting it
		ogg_page *old_page = ((muxer_page *)old_mpage)->page;
		if(old_page) {
			if(old_page->header)
				delete old_page->header;
			if(old_page->body)
				delete old_page->body;
			delete old_page;
		}
		free(old_mpage);
	}
};

/*
 * Structure holding a muxer_page and referencing another one (chaining).
 * For an optimal behavior, use the new and delete operators when handling a mpage_mesh.
 * This allow muxer_page deletion (if any) automatically
 */
struct mpage_mesh {
	muxer_page        *m_page;
	struct mpage_mesh *next;

	// What to do when created by new operator
	void* operator new(unsigned int nAlloc) {
		mpage_mesh* new_mesh = (mpage_mesh*)malloc(nAlloc);
		if(new_mesh) {
			new_mesh->m_page    = NULL;
			new_mesh->next      = NULL;
		}
		return new_mesh;
	}

	// What to do with delete operator
	void operator delete(void* old_mesh) {
		// Is there a muxer_page ?
		muxer_page *old_mpage = ((mpage_mesh *)old_mesh)->m_page;
		if(old_mpage)
			// Then delete it;
			delete old_mpage;
		free(old_mesh);
	}
};

/*
 * The Packetizer object
 */
class Packetizer {
	private:
		int                      _state;
		int                      pages;
		ogg_int64_t              packets;
		//bool                     pending_mheader;
    static ogg_page         *copy_page(ogg_page *src_page);
    static void              copy_packet(ogg_packet *src_packet, ogg_packet *dest_packet);
		mpage_mesh              *mpage_queue;
		mpage_mesh              *last_mesh;
		time_stamp               timestamp;
		time_stamp               t_delay;
		ogg_int64_t              granulepos_delay;
	  void                     process_buffer_packet(void);
		ogg_packet               buffer_packet;
		bool                     packet_in_buffer;
		bool                     granulepos_is_end;
		ogg_int64_t              start_granulepos;
		SerialGenerator         *s_generator;
		int                      nb_headers;
		int                      priority_set;
		bool                     priority_headers;
		bool                     group_headers;
		int                      header_pages;
		double                   samples_per_second;
	protected:
		stream_header            sh;
		int                      serialno;
		ogg_int32_t              standard_buffersize;
		ogg_int32_t              real_buffersize;
		unsigned char           *buffer;
		ogg_stream_state         oss;
		ogg_int64_t              packetno;
		ogg_int64_t              last_granulepos;
    void                     add_page(ogg_page *new_page);
	public:
		Packetizer(int serial
			         , SerialGenerator *generator
			         , stream_header sheader
							 , time_stamp delay_ms=0
							 , bool use_header=true
							 , bool pos_is_end=true
							 , ogg_int64_t start_granulepos=1
							 , int nb_headers=1
							 , bool priority_headers=false
							 , bool group_headers=false);
		virtual ~Packetizer(void);
		int                      state(void) { return _state; };
		mpage_mesh              *pending_mpage(void) { return mpage_queue; };
		void                     produce_header_packet(void);
		void                     produce_comment_packet(comment_list *comments, bool flush);
		bool                     need_data_for_headers(void) { return (nb_headers>0); };
		bool                     pending_header(void) { return (header_pages>0); };
		void                     process_packet(ogg_packet *new_packet, bool flush=false);
		/*void                     process_frame(unsigned char *frame
		                                       , int frame_type
		                                       , long frame_size
		                                       , ogg_int64_t n_samples
		  				        										 , bool is_key_frame
								        									 , bool is_last_frame);*/
		void                     process_frame(unsigned char *frame
                                           , int frame_type
		                                       , long frame_size
		                                       , ogg_int64_t n_samples
		  				        										 , bool is_key_frame
								        									 , bool is_last_frame
																					 , bool flush=false);
		//void                     process_null_frame(ogg_int64_t nSamples) {last_granulepos += nSamples;};
		void                     update_granulepos(ogg_int64_t diff) {last_granulepos += diff;};
		void                     update_granulepos(time_stamp diff_ms);
		muxer_page              *get_header(void);
		muxer_page              *get_mpage(void);
		time_stamp               make_timestamp(ogg_int64_t granulepos);
		//time_stamp               get_smallest_timestamp(void);
		time_stamp               get_smallest_last_timestamp(void);
		void                     produce_eos_packet(void);
		bool                     eos(void) { return (_state == STATE_EOS); };
    void                     flush_pages(void);
    void                     queue_pages(void);
    void                     flush_header_pages(void);
    void                     queue_header_pages(void);
		void                     set_mpage_priority(void);
};

/*
 * To chain packetizers (used in the Reader object)
 * For anoptimal behavior, please use the new and delete operators
 */
struct packetizer_mesh {
	int              num_stream;      // identification number of the stream (regarding the input file)
	void            *extra;           // pointer to optional extra data
	Packetizer      *packetizer;      // pointer to the packetizer
	bool             has_few_packets; // help preventing Reader's prepare_mpages() to queue a lot of Packets in other Packetizers
	packetizer_mesh *next;            // pointer to the next packetizer_mesh (chaining)

	// What to do when created by new operator
	void* operator new(unsigned int nAlloc) {
		packetizer_mesh* new_mesh = (packetizer_mesh*)malloc(nAlloc);
		if(new_mesh) {
			new_mesh->num_stream      = -1;
			new_mesh->extra           = NULL;
			new_mesh->packetizer      = NULL;
			new_mesh->has_few_packets = false;
			new_mesh->next            = NULL;
		}
		return new_mesh;
	}

	// What to do with delete operator
	void operator delete(void* old_mesh) {
		if(((packetizer_mesh*)old_mesh)->packetizer)
			delete ((packetizer_mesh*)old_mesh)->packetizer;
		if(((packetizer_mesh*)old_mesh)->extra)
			delete ((packetizer_mesh*)old_mesh)->extra;
		free(old_mesh);
	}
};

#endif /*  __PACKETIZER_H__ */