设计理念:比如我拖一个(或者多个视频文件)xx.mp4文件到我的 加密器中,自动在同名目录下生成一个xx.yj(后缀名随意,只要不与标准的视频后缀撞车)的视频加密文件。
首选mfc(基于对话框),因为方便。
资源视图:
代码文件:
自己看吧,当初学习,注释得很详尽了。
// EncryptVideoDlg.h : 头文件
//
#pragma once
#include
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 m_FilePaths;
afx_msg void OnBnClickedCancel();
};
// EncryptVideoDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "EncryptVideo.h"
#include "EncryptVideoDlg.h"
#include "afxdialogex.h"
#include
#include
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& 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& 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(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(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 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 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();
}
等我哪天想说话的时候,再作进一步的分析。
至此,视频加密工具已经做好了。
工程文件整理后再上传。
链接:预留