#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if defined(WIN32)
#include <windows.h>
#else
#include <pthread.h>
#endif//WIN32

#include "MRComm.h"
#include "libavserver_v3.h"

static HAVCStream s_hAVClient = NULL;
static FILE *s_fpFile = NULL;
static int live_data_handle(HAVCStream hstream, void *userdata, MRAVFrame *pkt)
{
	if(!s_fpFile)
		s_fpFile = fopen("test.h264", "wb");
	if(s_fpFile && pkt->media_type == AVMEDIA_TYPE_VIDEO)
	{
		fwrite(pkt->data, 1, pkt->size, s_fpFile);
		printf("frame pts=%d, size = %d\n", pkt->pts, pkt->size);
	}
	return 0;
}

static int live_relink_handle(HAVCStream hstream, const char *szName, const char *szIP, short nPort, int nState, void *userdata)
{
	if(nState == LIBMS_CHNSTATE_RECONNT)
	{
		printf("%s shut, re link now\n", szIP);
		return 1;
	}
	else if(nState == LIBMS_CHNSTATE_OK)
	{
		printf("%s re link ok\n", szIP);
		return 1;
	}
	else if(nState == LIBMS_CHNSTATE_EXIT)
	{
		printf("%s exit\n", szIP);
		return 1;
	}
	return 0;
}

int main(int argc, char *argv[])
{
	int iRet;
	LIBMC_REMOINFO_T stRem;
	memset(&stRem, 0, sizeof(stRem));
	stRem.szIP = "192.168.5.163";
	stRem.wPort = 3000;
	stRem.szStreamName = "live/av0";
	stRem.szUserName = "admin";
	stRem.szPassword = "admin";
	stRem.relink_handle=live_relink_handle; 
	stRem.data_handle = live_data_handle;
	stRem.userdata    = NULL;
	iRet = libavmc_stream_live_single(&s_hAVClient, MR_NETSTMPRO_MRMS, &stRem);
	if(!iRet)
	{
		int i, streams;
		MRAVSTREAM_T stStream;
		streams = libavmc_stream_stream_nb(s_hAVClient);
		printf("stream channels = %d\n", streams);
		for(i=0; i<streams; i++)
		{
			libavmc_stream_getstrminfo(s_hAVClient, i, &stStream);
			if(stStream.codec_type == AVMEDIA_TYPE_VIDEO)
			{
				printf("video id = %d, w=%d, h=%d\n", stStream.codec_id, stStream.nWidth, stStream.nHeight);
			}
			else if(stStream.codec_type == AVMEDIA_TYPE_AUDIO)
			{
				printf("audio id = %d, sample rate=%d\n", stStream.codec_id, stStream.nSampleRate);
			}
		}
		libavmc_stream_start(s_hAVClient);
		printf("libavmc_stream_start\n");
	}
	else
	{
		printf("libavmc_stream_live_single ret = %d\n", iRet);
	}
	while(1)
	{
		char cc = getchar();
		if(cc == 'q')
			break;
	}
	if(s_hAVClient)
		libavmc_stream_stop(s_hAVClient);
	s_hAVClient = NULL;
	if(s_fpFile)
		fclose(s_fpFile);
	return 0;
}
