⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverh264dlg.cpp

📁 dianzi shuju ,tai badao le ,my tian li a a
💻 CPP
字号:
// ServerH264Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "ServerH264.h"
#include "ServerH264Dlg.h"

#include "common.h"
#include <afxtempl.h>
#include <malloc.h>
#include <winsock.h>
#include <sys/stat.h>
#define SERVER_SOCKET_ERROR 1
#define SOCKET_OK 0
#pragma comment(lib, "wsock32.lib")

int nSending = 1; //indicate data is sending
char *h264buf = 0;
CList<char *, char *> snippets; //split video stream into several snippets
unsigned long nData = 0; //data received in current tick
unsigned long nLastData = 0; //data received in last tick
unsigned long nTicks = 0; //counting ticks
#define SPEED_REFRESH 1001 //refreshing timer
UINT H264SendingThread(LPVOID param); //thread that sends video stream data

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerH264Dlg dialog

CServerH264Dlg::CServerH264Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CServerH264Dlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CServerH264Dlg)
	m_strH264FileName = _T("xxx.264");
	m_strAveSpeed = _T("平均速度:");
	m_strSendSpeed = _T("发送速度:");
	m_strTimer = _T("计时时间:");
	m_strTotalSend = _T("累计发送:");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CServerH264Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CServerH264Dlg)
	DDX_Control(pDX, IDC_SLIDER_SENDING_SPEED, m_ctrlSlider);
	DDX_Text(pDX, IDC_EDIT_H264_FILE, m_strH264FileName);
	DDX_Text(pDX, IDC_STATIC_AVE_SPEED, m_strAveSpeed);
	DDX_Text(pDX, IDC_STATIC_SEND_SPEED, m_strSendSpeed);
	DDX_Text(pDX, IDC_STATIC_TIMER, m_strTimer);
	DDX_Text(pDX, IDC_STATIC_TOTAL_SEND, m_strTotalSend);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CServerH264Dlg, CDialog)
	//{{AFX_MSG_MAP(CServerH264Dlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_BROWSE, OnButtonBrowse)
	ON_BN_CLICKED(IDC_BUTTON_START, OnButtonStart)
	ON_WM_CLOSE()
	ON_WM_DESTROY()
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CServerH264Dlg message handlers

BOOL CServerH264Dlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_ctrlSlider.SetRange(0, 10);
	m_ctrlSlider.SetPos(8);
	SetTimer(SPEED_REFRESH, 1000, NULL);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CServerH264Dlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CServerH264Dlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CServerH264Dlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CServerH264Dlg::OnButtonBrowse() 
{
	// TODO: Add your control notification handler code here
	OPENFILENAME ofn;
	char szFile[256];

	ZeroMemory(&ofn, sizeof(ofn));
	ZeroMemory(szFile, sizeof(szFile));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = this->m_hWnd;
	ofn.lpstrFilter = "h264码流文件(Annox B bit stream, *.264)\0*.264\0所有文件(*.*)\0*.*";
	ofn.lpstrFile = szFile; //(LPTSTR)(LPCTSTR)m_strMediaFileName
	ofn.nMaxFile = 255;
	ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
	ofn.lpstrDefExt = "H264";

	if (GetOpenFileName(&ofn) != 0)
	{
		m_strH264FileName = szFile;
		UpdateData(FALSE);
	}
	
}

void socketError(char* str)
{
	MessageBox(NULL, str, "SERVER SOCKET ERROR", MB_OK);
}

// socket listening thread
UINT ConnectionThread(LPVOID param)
{
	WORD sockVersion;
	WSADATA wsaData;
	int rVal;

	sockVersion = MAKEWORD(1,1);
	//start winsock dll
	WSAStartup(sockVersion, &wsaData);

	//create socket
	SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

	if(s == INVALID_SOCKET)
	{
		socketError("Failed socket()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	//fill in sockaddr_in struct 
	SOCKADDR_IN sin;
	sin.sin_family = PF_INET;
	sin.sin_port = htons(9999);
	sin.sin_addr.s_addr = INADDR_ANY;

	//bind the socket
	rVal = bind(s, (LPSOCKADDR)&sin, sizeof(sin));
	if(rVal == SOCKET_ERROR)
	{
		socketError("Failed bind()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	//get socket to listen 
	rVal = listen(s, 2);
	if(rVal == SOCKET_ERROR)
	{
		socketError("Failed listen()");
		WSACleanup();
		return SERVER_SOCKET_ERROR;
	}

	while (nSending)
	{
		//wait for a client
		SOCKET server = accept(s, NULL, NULL);

		//newclient found
		if(server == INVALID_SOCKET)
		{
			socketError("Failed accept()");
			WSACleanup();
			return SERVER_SOCKET_ERROR;
		}

		nData = nLastData = 0;
		nTicks = 0;
		//start a new thread to process data sending
		AfxBeginThread(H264SendingThread, (LPVOID)&server, 0, 0, NULL);
	}

	closesocket(s);

	WSACleanup();

	//PostMessage(AfxGetApp()->m_pMainWnd->m_hWnd, WM_DESTROY, 0, 0);
	return SOCKET_OK;
	//return 0;
}

// video data sending thread
UINT H264SendingThread(LPVOID param)
{
	SOCKET server = *(SOCKET *)param;
	POSITION begin = snippets.GetHeadPosition();
	POSITION pos = begin;
	char *buf;

	CServerH264Dlg *dlg = (CServerH264Dlg *)AfxGetApp()->m_pMainWnd;
	CSliderCtrl *slider = (CSliderCtrl *) dlg->GetDlgItem(IDC_SLIDER_SENDING_SPEED);

	while (nSending)
	{
		if (pos == NULL)
		{
			pos = begin;
			//if (begin == NULL)  continue;
			//break;
		}

		buf = snippets.GetNext(pos);

		int rVal = send(server, buf, _msize(buf), 0);  //MUST not use sizeof(...)

		if(rVal == SOCKET_ERROR)
		{
			//close process
			closesocket(server);
			return SERVER_SOCKET_ERROR;
		}

		nData += rVal;
		if (nData < nLastData)
		{
			nData = rVal;//restart a new statistic
			nLastData = 0;
			nTicks = 0;
		}

		//if (slider->GetPos() < 10)
			//Sleep(slider->GetRangeMax() - slider->GetPos());
		Sleep(60 - 5 * slider->GetPos());
	}

	//AfxMessageBox("file sending finished.");
	closesocket(server);

	nData = 0;
	nTicks = 0;

	//PostMessage(AfxGetApp()->m_pMainWnd->m_hWnd, WM_DESTROY, 0, 0);
	return SOCKET_OK;
}

//getting size of video file
long get_file_size(char * filename)
{
    struct _stat f_stat;

    if( _stat( filename, &f_stat ) == -1 ){
        return -1;
    }

    return (long)f_stat.st_size;
}

void CServerH264Dlg::OnButtonStart() 
{
	// TODO: Add your control notification handler code here
	FILE *fp;

	fp = fopen(m_strH264FileName, "rb");
    if (!fp) {
        AfxMessageBox("could not open .264 file");
        return;
    }

    fseek(fp, 0, SEEK_END);  
    int length = ftell(fp);
	if (length < 0)
	{
        AfxMessageBox("open .264 file error");
        return;
	}

	h264buf = (char *) malloc(length);
    fseek(fp, 0, SEEK_SET);
	int size = fread(h264buf, sizeof(char), length, fp);
	if (length != size)
	{
        AfxMessageBox("open .264 file error");
        return;
	}
    fclose(fp);

	//split h264 code into snippits with 1024 bytes
	char *buf;
	for (int i=0; i<length/1024; i++)
	{
		buf = (char *)malloc(1024);
		memcpy(buf, h264buf+i*1024, 1024);
		snippets.AddTail(buf);
	}

	if (length % 1024 != 0)
	{
		buf = (char *)malloc(length % 1024);
		memcpy(buf, h264buf+i*1024, length % 1024);
		snippets.AddTail(buf);
	}


	GetDlgItem(IDC_BUTTON_START)->EnableWindow(FALSE);

	AfxBeginThread(ConnectionThread, (LPVOID)NULL, 0, 0, NULL);
}

void CServerH264Dlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	KillTimer(SPEED_REFRESH);
	WSACleanup();
	nSending = 0;
	Sleep(2000);//waiting for two seconds
	
	CDialog::OnClose();
}

void CServerH264Dlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
	// TODO: Add your message handler code here
	if (!h264buf)
	{
		free(h264buf);

		while (! snippets.IsEmpty())
		{
			char *buf = snippets.RemoveHead();
			free(buf);
		}
	}
}

void CServerH264Dlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	switch (nIDEvent)
	{
	case SPEED_REFRESH:
		{
			if (nData == 0)//has no data sended
				return;

			nTicks ++;

			m_strTimer.Format("计时时间: %d s", nTicks);
			m_strTotalSend.Format("累计发送: %.1f KB", nData/1024.0);
			m_strAveSpeed.Format("平均速度: %.1f kbps", nData*8/(1024.0 * nTicks));
			m_strSendSpeed.Format("发送速度: %.1f kbps", (nData-nLastData)*8/1024.0);
			UpdateData(FALSE);//refresh the speed information in dialog

			SetWindowText(m_strSendSpeed);

			nLastData = nData;

			break;
		}
	default:
		break;
	}
	
	CDialog::OnTimer(nIDEvent);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -