////////////////////////////////////////////////////////////////////////////////
// StreamRecorder.h
// Mario Chirinos
// 2014-02-12
//------------------------------------------------------------------------------
// Notes:
//	Streaming recorder with GStreamer
//
////////////////////////////////////////////////////////////////////////////////

#ifndef STREAMRECORDER_H
#define STREAMRECORDER_H

//------------------------------------------------------------------------------

/** Your public header include */

#include <gst/gst.h>
#include <jmorecfg.h>

//------------------------------------------------------------------------------

#define STREAMRECORDER_SAMPLERATE 44100
#define READSIZE 1152 //For MPEG1, frame_size = 1152 samples/frame
#define STREAMRECORDER_BYTESPERSAMPLE 2
#define NCHANNELS    1

#define DST_URI_SIZE 80
#define RECONNECTION_DELAY 1

#define STREAM_ENOUGH_DATA_ERROR 4

//------------------------------------------------------------------------------

/** Class declaration */

class StreamRecorder
{
	private:
    
        unsigned char* audioBuffer;
        unsigned char* audioBufferPosition;
    
        char pluginUri[DST_URI_SIZE];

        unsigned int nBytes;
        unsigned int bufferSize;

        int recordTime;
        int audioFileDuration;
            
        /** Audio filename */
        long int timestamp = 0;
    
        bool isDisconnected = false;
    
        //char* sourceName;
        //GstElement* audioResample;
        //GstElement* tempBin;
        //GstElement* audioSink;
        GstElement* streamSrc;
        GstElement* audioConvert;
        GstElement* filterCaps;
        GstElement* queue0;
        GstElement* queue1;
        GstElement* filter;
        GstElement* fakeSink;
        GstElement* mainPipeline;
        
        int createMainPipeline();
        int connect();
        int disconnect();
            
        /** add data to buffer */
        int addToBuffer(unsigned char* data, int length);
        int compressBuffer();
                
        /** plugin's callbacks */
        static void srcNewPad_callback(GstElement *element, GstPad *pad, void *data);
        static int bus_callback(GstBus *bus, GstMessage *message, void *data);
        static int filter_handoff_callback(GstElement *filter, GstBuffer* buffer, void* user_data);
                
        /** Save audio*/
        void saveBuffer();
                
        /** Restart the pipeline */
        static gboolean reconnectURIStream(void* data);
    
    public:
    
        StreamRecorder(const char* source, int time);
};
//------------------------------------------------------------------------------
#endif
