基於ffmpeg+SDL的加密視頻播放器的開發(二)

視頻加密器的實現

設計理念:比如我拖一個(或者多個視頻文件)xx.mp4文件到我的 加密器中,自動在同名目錄下生成一個xx.yj(後綴名隨意,只要不與標準的視頻後綴撞車)的視頻加密文件。

首選mfc(基於對話框),因爲方便。

資源視圖:

代碼文件:

自己看吧,當初學習,註釋得很詳盡了。


// EncryptVideoDlg.h : 頭文件
//

#pragma once
#include <vector>
using namespace std;

extern "C"
{
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavutil/avutil.h"
#include "libavutil/mathematics.h"
#include "inttypes.h"
#include "SDL.h"
#include "SDL_thread.h"
};
#include "afxcmn.h"
#include "afxwin.h"
#undef main

#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avcodec.lib")
#pragma comment(lib,"avdevice.lib")
#pragma comment(lib,"avfilter.lib")
#pragma comment(lib,"avutil.lib")
#pragma comment(lib,"postproc.lib")
#pragma comment(lib,"swresample.lib")
#pragma comment(lib,"swscale.lib")
#pragma comment(lib,"SDL.lib")


// CEncryptVideoDlg 對話框
class CEncryptVideoDlg : public CDialogEx
{
// 構造
public:
	CEncryptVideoDlg(CWnd* pParent = NULL);	// 標準構造函數
// 對話框數據
	enum { IDD = IDD_ENCRYPTVIDEO_DIALOG };
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV 支持

// 實現
protected:
	HICON m_hIcon;

	// 生成的消息映射函數
	virtual BOOL OnInitDialog();
	afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
	afx_msg void OnPaint();
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnDropFiles(HDROP hDropInfo);

	afx_msg void OnBnClickedOk();
public:
	CListBox m_ListBox;
	vector<wstring> m_FilePaths;	
	afx_msg void OnBnClickedCancel();
};

// EncryptVideoDlg.cpp : 實現文件
//

#include "stdafx.h"
#include "EncryptVideo.h"
#include "EncryptVideoDlg.h"
#include "afxdialogex.h"
#include <string>
#include <fstream>
using namespace std;


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


/*加密算法(算法有待改進...)*/
void EncryptionAlgorithm(AVPacket& pkt)
{
	for (int i = 0; i < pkt.size; i++)
	{		
		char oribt = pkt.data[i];
		char bt1 = oribt&(0x66);
		bt1 = ~bt1;
		bt1 = bt1&(0x66);
		char bt2 = oribt&(0x99);
		pkt.data[i] = bt2 | bt1;
	}
}

/*WStringToString轉換函數*/
string WStringToString(const wstring& _src)
{
	int nBufSize = WideCharToMultiByte(GetACP(), 0, _src.c_str(), -1, NULL, 0, 0, FALSE);
	char *szBuf = new char[nBufSize];
	WideCharToMultiByte(GetACP(), 0, _src.c_str(), -1, szBuf, nBufSize, 0, FALSE);
	string strRet(szBuf);
	delete[]szBuf;
	szBuf = NULL;
	return strRet;
}

/*分割字符串函數*/
void  SplitString(vector<string>& vecst, const string& str, const string& divdot)
{
	string s = "";
	for (size_t i = 0; i < str.size(); i++)
	{
		if (divdot.find(str[i]) == wstring::npos)
		{
			s += str[i];
		}
		else
		{
			if (s.size() != 0 && s != " ")
			{
				vecst.push_back(s);
				s.clear();
			}
		}
	}
	if (s.size() != 0)
	{
		vecst.push_back(s);
	}
}

/*分割字符串(out_分割好的字符串,in_要分割的字符串,in_分隔符)*/
void SplitWstring(vector<wstring>& wsts, const wstring& data, const wstring& divstr)
{
	wstring temp;
	for (auto i : data)
	{
		if (divstr.find(i) == wstring::npos)//i非分隔符
		{
			temp += i;
		}
		else//i是分隔符
		{
			if (temp.size() != 0)//temp不爲空
			{
				wsts.push_back(temp);//讀取的這一段壓入vector
				temp.clear();//清空temp
			}
		}
	}
	if (temp.size() != 0)//最後可能還有數據
	{
		wsts.push_back(temp);
		temp.clear();//清空temp
	}
}


// 用於應用程序“關於”菜單項的 CAboutDlg 對話框

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

// 對話框數據
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 實現
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()

CEncryptVideoDlg::CEncryptVideoDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CEncryptVideoDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	
}

void CEncryptVideoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST1, m_ListBox);
	m_ListBox.UpdateData();
}

BEGIN_MESSAGE_MAP(CEncryptVideoDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_DROPFILES()
	ON_BN_CLICKED(IDOK, &CEncryptVideoDlg::OnBnClickedOk)
	ON_BN_CLICKED(IDCANCEL, &CEncryptVideoDlg::OnBnClickedCancel)
END_MESSAGE_MAP()


// CEncryptVideoDlg 消息處理程序

BOOL CEncryptVideoDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 將“關於...”菜單項添加到系統菜單中。

	// IDM_ABOUTBOX 必須在系統命令範圍內。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

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

	// 設置此對話框的圖標。  當應用程序主窗口不是對話框時,框架將自動
	//  執行此操作
	SetIcon(m_hIcon, TRUE);			// 設置大圖標
	SetIcon(m_hIcon, FALSE);		// 設置小圖標

	// TODO:  在此添加額外的初始化代碼
	GetDlgItem(IDC_STATIC)->SetWindowText(L"把要加密的視頻拖拽到窗口中...");

	return TRUE;  // 除非將焦點設置到控件,否則返回 TRUE
}

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

// 如果向對話框添加最小化按鈕,則需要下面的代碼
//  來繪製該圖標。  對於使用文檔/視圖模型的 MFC 應用程序,
//  這將由框架自動完成。

void CEncryptVideoDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用於繪製的設備上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使圖標在工作區矩形中居中
		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;

		// 繪製圖標
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//當用戶拖動最小化窗口時系統調用此函數取得光標
//顯示。
HCURSOR CEncryptVideoDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CEncryptVideoDlg::OnDropFiles(HDROP hDropInfo)
{
	//先做判斷,清空上一次的轉換數據
	m_ListBox.ResetContent();
	m_FilePaths.clear();

	wstring div1 = L"/\\";//以/,\作爲分割符
	int DropCount = DragQueryFile(hDropInfo, -1, NULL, 0);//取得被拖動文件的數目  
	for (int i = 0; i < DropCount; i++)
	{
		WCHAR wcStr[MAX_PATH];
		DragQueryFile(hDropInfo, i, wcStr, MAX_PATH);//獲得拖曳的第i個文件的文件名 
		
		vector<wstring> wsts;
		SplitWstring(wsts, wcStr, div1);
		wstring fileName = wsts[wsts.size() - 1];
		m_ListBox.AddString(fileName.c_str());
		m_FilePaths.push_back(wcStr);//保存要轉換的文件
	}
	DragFinish(hDropInfo);  //拖放結束後,釋放內存  

	CDialog::OnDropFiles(hDropInfo);
}

void CEncryptVideoDlg::OnBnClickedOk()
{
	wstring div2 = L".";//以.作爲分割符
	for (int n = 0; n < m_FilePaths.size(); n++)
	{
		wstring file = m_FilePaths[n];

		CString cstr;
		cstr.Format(L"正在處理第%d/%d個文件,請稍等...", n + 1, m_FilePaths.size());
		GetDlgItem(IDC_STATIC)->SetWindowText(cstr);

		/*---------------------------------視頻與音樂的融合(in_filename_v = in_filename_a的時候,原視頻)---------------------------------------------*/
		AVOutputFormat *	ofmt = NULL;		//輸出格式
		AVFormatContext*	ifmt_ctx_v = NULL;	//輸入: 畫面 上下文
		AVFormatContext*	ifmt_ctx_a = NULL;	//輸入: 音頻 上下文
		AVFormatContext*	ofmt_ctx = NULL;	//輸出: 上下文
		AVPacket pkt;
		AVCodec *dec;
		int ret, i;
		int videoindex_v = -1, videoindex_out = -1;
		int audioindex_a = -1, audioindex_out = -1;
		int frame_index = 0;
		int64_t cur_pts_v = 0, cur_pts_a = 0;

		string in_filename_v = WStringToString(file);
		string in_filename_a = in_filename_v;
		vector<wstring> wsts;
		SplitWstring(wsts, file, div2);
		wstring myPath = wsts[0] + L".yj";
		string out_filename = WStringToString(myPath);

		//FFmpeg開始工作:註冊所有可能用到的東西
		avcodec_register_all();
		av_register_all();

		//打開音頻文件:
		if ((ret = avformat_open_input(&ifmt_ctx_a, in_filename_a.c_str(), NULL, NULL)) < 0)
			goto end;//無法打開音頻文件
		if ((ret = avformat_find_stream_info(ifmt_ctx_a, 0)) < 0)
			goto end;//讀取音頻文件信息失敗

		//打開視頻文件:
		if ((ret = avformat_open_input(&ifmt_ctx_v, in_filename_v.c_str(), NULL, NULL)) < 0)
			goto end;//無法打開畫面文件
		if ((ret = avformat_find_stream_info(ifmt_ctx_v, 0)) < 0) 		
			goto end;//無法找到畫面流信息
		//輸入文件的信息
		av_dump_format(ifmt_ctx_v, 0, in_filename_v.c_str(), 0);
		av_dump_format(ifmt_ctx_a, 0, in_filename_a.c_str(), 0);

		//輸出文件:
		avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, in_filename_v.c_str());//輸出文件的格式以輸入的視頻格式
		if (!ofmt_ctx)
		{
			ret = AVERROR_UNKNOWN;//無法創建輸出上下文
			goto end;
		}
		ofmt = ofmt_ctx->oformat;
		for (i = 0; i < ifmt_ctx_v->nb_streams; i++)
		{
			//根據輸入的AVStream創建輸出AVStream(畫面)
			if (ifmt_ctx_v->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
			{
				AVStream *in_stream = ifmt_ctx_v->streams[i];
				AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
				videoindex_v = i;
				if (!out_stream)
				{
					ret = AVERROR_UNKNOWN;//分配輸出AVStream空間失敗
					goto end;
				}
				videoindex_out = out_stream->index;
				//複製AVCodecContext的環境設置(畫面)
				ret = av_dict_set(&out_stream->metadata, "rotate", "90", 0); //設置旋轉角度//ret>=0則成功
				if (avcodec_copy_context(out_stream->codec, in_stream->codec) < 0)
					goto end;//從輸入流加解碼上下文複製到輸出流加解碼,失敗
				out_stream->codec->codec_tag = 0;
				if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
					out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
				break;
			}
		}

		for (i = 0; i < ifmt_ctx_a->nb_streams; i++)
		{
			//根據輸入的AVStream創建輸出AVStream(音頻)
			if (ifmt_ctx_a->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
			{
				AVStream *in_stream = ifmt_ctx_a->streams[i];
				AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
				audioindex_a = i;
				if (!out_stream)
				{
					ret = AVERROR_UNKNOWN;//分配輸出AVStream空間失敗
					goto end;
				}
				audioindex_out = out_stream->index;
				//複製AVCodecContext的環境設置(音頻)
				if (avcodec_copy_context(out_stream->codec, in_stream->codec) < 0)							
					goto end;//從輸入流加解碼上下文複製到輸出流加解碼,失敗				
				out_stream->codec->codec_tag = 0;
				if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
					out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
				break;
			}
		}

		//輸出信息
		av_dump_format(ofmt_ctx, 0, out_filename.c_str(), 1);

		//打開輸出文件
		if (!(ofmt->flags & AVFMT_NOFILE))
		{
			if (avio_open(&ofmt_ctx->pb, out_filename.c_str(), AVIO_FLAG_WRITE) < 0)
				goto end;//無法打開輸出文件
		}

		//寫入文件頭
		if (avformat_write_header(ofmt_ctx, NULL) < 0) 
			goto end;//寫入文件頭失敗
		
		while (1) 
		{
			AVFormatContext *ifmt_ctx;
			int stream_index = 0;
			AVStream *in_stream, *out_stream;

			//獲取一個AVPacket
			if (av_compare_ts(cur_pts_v, ifmt_ctx_v->streams[videoindex_v]->time_base, cur_pts_a, ifmt_ctx_a->streams[audioindex_a]->time_base) <= 0)
			{
				ifmt_ctx = ifmt_ctx_v;
				stream_index = videoindex_out;
				if (av_read_frame(ifmt_ctx, &pkt) >= 0){
					do{
						//視頻加密操作
						EncryptionAlgorithm(pkt);

						//寫入文件
						in_stream = ifmt_ctx->streams[pkt.stream_index];
						out_stream = ofmt_ctx->streams[stream_index];
						if (pkt.stream_index == videoindex_v)
						{

							//簡單地寫入 PTS
							if (pkt.pts == AV_NOPTS_VALUE){

								//Write PTS
								AVRational time_base1 = in_stream->time_base;
								//Duration between 2 frames (us)
								int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(in_stream->r_frame_rate);
								//Parameters
								pkt.pts = (double)(frame_index*calc_duration) / (double)(av_q2d(time_base1)*AV_TIME_BASE);
								pkt.dts = pkt.pts;
								pkt.duration = (double)calc_duration / (double)(av_q2d(time_base1)*AV_TIME_BASE);
								frame_index++;
							}
							cur_pts_v = pkt.pts;
							break;
						}
					} 
					while (av_read_frame(ifmt_ctx, &pkt) >= 0);
				}
				else
				{
					break;
				}
			}
			else
			{
				ifmt_ctx = ifmt_ctx_a;
				stream_index = audioindex_out;
				if (av_read_frame(ifmt_ctx, &pkt) >= 0)
				{
					do{
						//音頻加密操作
						EncryptionAlgorithm(pkt);

						//寫入文件
						in_stream = ifmt_ctx->streams[pkt.stream_index];
						out_stream = ofmt_ctx->streams[stream_index];
						if (pkt.stream_index == audioindex_a){
							//Simple Write PTS
							if (pkt.pts == AV_NOPTS_VALUE){
								//Write PTS
								AVRational time_base1 = in_stream->time_base;
								//Duration between 2 frames (us)
								int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(in_stream->r_frame_rate);
								//Parameters
								pkt.pts = (double)(frame_index*calc_duration) / (double)(av_q2d(time_base1)*AV_TIME_BASE);
								pkt.dts = pkt.pts;
								pkt.duration = (double)calc_duration / (double)(av_q2d(time_base1)*AV_TIME_BASE);
								frame_index++;
							}
							cur_pts_a = pkt.pts;
							break;
						}
					} 
					while (av_read_frame(ifmt_ctx, &pkt) >= 0);
				}
				else
				{
					break;
				}
			}

			//Convert PTS/DTS
			pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
			pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
			pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
			pkt.pos = -1;
			pkt.stream_index = stream_index;

			//Write
			if (av_interleaved_write_frame(ofmt_ctx, &pkt) < 0) 
			
				break;//音視混合失敗			
			av_free_packet(&pkt);
		}

		//寫入文件尾
		av_write_trailer(ofmt_ctx);

	end:
		avformat_close_input(&ifmt_ctx_v);
		avformat_close_input(&ifmt_ctx_a);
		/*關閉輸出*/
		if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
			avio_close(ofmt_ctx->pb);
		avformat_free_context(ofmt_ctx);
		if (ret < 0 && ret != AVERROR_EOF) 
			return;//發生錯誤		
	}

	GetDlgItem(IDC_STATIC)->SetWindowText(L"視頻加密處理完成!!!");

	//CDialogEx::OnOK();
}




void CEncryptVideoDlg::OnBnClickedCancel()
{
	CDialogEx::OnCancel();
}

等我哪天想說話的時候,再作進一步的分析。

至此,視頻加密工具已經做好了。

工程文件整理後再上傳。

鏈接:預留

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章