使用SDL 2.0.20 Simple DirectMedia Layer - SDL version 2.0.20 (stable)https://www.libsdl.org/release/SDL2-devel-2.0.20-VC.zip
参考文章:
ffmpeg tutorial
学习文章的同时基于ffmpeg 4.4 和 sdl 2.0 做同样功能的mfc demo。
可以先参考:CSDN
在制作播放器时,我们将使用 SDL 来输出媒体文件的音频和视频。 SDL 是一个出色的跨平台多媒体库,可用于 MPEG 播放软件、模拟器和许多视频游戏。您需要为您的系统下载并安装 SDL 开发库,以便编译本教程中的程序。
所以我们目前的计划是替换教程 1 中的 Saveframe() 函数,而是将我们的帧输出到屏幕上。但首先我们必须先了解如何使用 SDL 库。首先,我们必须包含库并初始化 SDL:
参考SDL2源代码分析1:初始化(SDL_Init())_雷霄骅(leixiaohua1020)的专栏-CSDN博客_sdl_init
使用SDL 播放一个视频代码流程大体如下:
初始化:
1. SDL_Init() 初始化SDL
2. SDL_CreateWindow(): 创建窗口
3. SDL_CreateRenderer() 基于窗口创建渲染器
4. SDL_CreateTexture() 创建纹理
循环渲染数据
SDL_UpdateTexture 设置纹理的数据
SDL_RenderCopy 纹理复制给渲染器
SDL_RenderPresent 显示
// MFCAudioResampleDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "MFCAudioResample.h" #include "MFCAudioResampleDlg.h" #include "afxdialogex.h" #include#include //Refresh Event #define REFRESH_EVENT (SDL_USEREVENT + 1) #define BREAK_EVENT (SDL_USEREVENT + 2) std::string GetFFmpegErorString(int errnum) { static CHAR g_av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 }; return std::string(av_make_error_string(g_av_error, AV_ERROR_MAX_STRING_SIZE, errnum)); } void msgBoxFFmpegError(int errnum) { ::MessageBoxA(0, 0, GetFFmpegErorString(errnum).c_str(), 0); } std::wstring GetoneFile(BOOL bOpen = TRUE) { CString FilePathName; CFileDialog dlg(bOpen, NULL, NULL, NULL, NULL);//TRUE为OPEN对话框,FALSE为SAVE AS对话框 if (dlg.DoModal() == IDOK) { //清空 FilePathName = dlg.GetPathName(); } return std::wstring(FilePathName.GetBuffer()); } #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CaboutDlg 对话框 class CaboutDlg : public CDialogEx { public: CaboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_aboutBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CaboutDlg::CaboutDlg() : CDialogEx(IDD_aboutBOX) { } void CaboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CaboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCAudioResampleDlg 对话框 CMFCAudioResampleDlg::CMFCAudioResampleDlg(CWnd* pParent ) : CDialogEx(IDD_MFCAUDIORESAMPLE_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINframe); } void CMFCAudioResampleDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT_INPUT_FILE, m_targetFilePath); } BEGIN_MESSAGE_MAP(CMFCAudioResampleDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_CHOOSE_FILE, &CMFCAudioResampleDlg::OnBnClickedButtonChooseFile) END_MESSAGE_MAP() // CMFCAudioResampleDlg 消息处理程序 BOOL CMFCAudioResampleDlg::onInitDialog() { CDialogEx::onInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_aboutBOX 必须在系统命令范围内。 ASSERT((IDM_aboutBOX & 0xFFF0) == IDM_aboutBOX); ASSERT(IDM_aboutBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { 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: 在此添加额外的初始化代码 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMFCAudioResampleDlg::onSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_aboutBOX) { CaboutDlg dlgabout; dlgabout.DoModal(); } else { CDialogEx::onSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMFCAudioResampleDlg::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 CMFCAudioResampleDlg::onQueryDragIcon() { return static_cast (m_hIcon); } void CMFCAudioResampleDlg::Saveframe(AVframe* pframe, int width, int height, int iframe) { m_frame = pframe; SDL_Event event; event.type = REFRESH_EVENT; SDL_PushEvent(&event); } void CMFCAudioResampleDlg::onBnClickedButtonChooseFile() { if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER)) { assert(false); } // TODO: 在此添加控件通知处理程序代码 auto target = GetoneFile(); m_targetFilePath.SetWindowTextW(target.c_str()); UpdateData(TRUE); CString strTargetWindowText; m_targetFilePath.GetWindowTextW(strTargetWindowText); AVFormatContext* avFormatContext = avformat_alloc_context(); USES_CONVERSION; if (!PathFileExists(strTargetWindowText.GetBuffer())) { return; } auto result = avformat_open_input(&avFormatContext, W2A((strTargetWindowText.GetBuffer())), nullptr, nullptr); if (result < 0) { assert(false); } result = avformat_find_stream_info(avFormatContext, NULL); if (result < 0) { assert(false); } av_dump_format(avFormatContext, 0, NULL, 0); // Find the first video stream int videoStream = -1; for (int i = 0; i < avFormatContext->nb_streams; i++) if (avFormatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { videoStream = i; break; } if (videoStream == -1) return ; // Didn't find a video stream AVCodecContext* avCodecContext = avcodec_alloc_context3(NULL); result = avcodec_parameters_to_context(avCodecContext, avFormatContext->streams[videoStream]->codecpar); if (result < 0) { assert(false); } avCodecContext->pkt_timebase = avFormatContext->streams[videoStream]->time_base; AVCodec* codec = avcodec_find_decoder(avCodecContext->codec_id); avCodecContext->codec_id = codec->id; result = avcodec_open2(avCodecContext, codec, nullptr); if (result < 0) { msgBoxFFmpegError(result); assert(false); } m_sdlThread = std::move(std::thread([this, avCodecContext]() { m_sdlWindow = SDL_CreateWindow("sdl display", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, avCodecContext->width, avCodecContext->height, SDL_WINDOW_OPENGL); assert(m_sdlWindow); m_sdlRender = SDL_CreateRenderer(m_sdlWindow, -1, 0); assert(m_sdlRender); m_sdlTexture = SDL_CreateTexture(m_sdlRender, SDL_PixelFormatEnum::SDL_PIXELFORMAT_RGB24, SDL_TextureAccess::SDL_TEXTUREACCESS_STREAMING, avCodecContext->width, avCodecContext->height); assert(m_sdlTexture); SDL_Event event; while (1) { SDL_WaitEvent(&event); if (event.type == REFRESH_EVENT) { SDL_UpdateTexture(m_sdlTexture, nullptr, m_frame->data[0], avCodecContext->width * 3); SDL_Rect sdlRect = {}; sdlRect.x = 0; sdlRect.y = 0; sdlRect.h = avCodecContext->height; sdlRect.w = avCodecContext->width; SDL_RenderClear(m_sdlRender); SDL_RenderCopy(m_sdlRender, m_sdlTexture, nullptr, &sdlRect); SDL_RenderPresent(m_sdlRender); } else if (event.type == SDL_WINDOWEVENT) { } else if (event.type == SDL_QUIT) { } else if (event.type == BREAK_EVENT) { break; } } })); AVframe* pframe = nullptr; pframe = av_frame_alloc(); // 我们最终的目的是将原始视频帧存储为24-bit RGB 视频。 AVframe* pframeRGB24 = av_frame_alloc(); uint8_t* bufferRawRGB24 = nullptr; const int numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGB24, avCodecContext->width, avCodecContext->height, 1); bufferRawRGB24 = (uint8_t*)av_malloc(numBytes * sizeof(uint8_t)); av_image_fill_arrays(pframeRGB24->data, pframeRGB24->linesize, bufferRawRGB24, AV_PIX_FMT_RGB24, avCodecContext->width, avCodecContext->height, 1); // 读取数据 // sws_ctx 定义了从pix_fmt 到 AV_PIX_FMT_RGB24的转换 struct SwsContext* sws_ctx = NULL; int frameFinished; // initialize SWS context for software scaling sws_ctx = sws_getContext(avCodecContext->width, avCodecContext->height, avCodecContext->pix_fmt, avCodecContext->width, avCodecContext->height, AV_PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL ); int i = 0; AVPacket packet; bool bReadEof = false; while (true) { Sleep(33); int readResult = -1; if (!bReadEof) { readResult = av_read_frame(avFormatContext, &packet); if (readResult < 0) { ::MessageBoxA(0, 0, GetFFmpegErorString(readResult).c_str(), 0); bReadEof = true; } else if (readResult == 0) { static int iCnt = 0; if (packet.stream_index == videoStream) { ++iCnt; } CString str; str.Format(L"cunt[%d]rn", iCnt); OutputDebugStringW(str.GetBuffer()); } } if (bReadEof) { // 需要给刷空 avcodec_send_packet(avCodecContext, NULL); } else { // Is this a packet from the video stream? if (packet.stream_index == videoStream) { // Decode video frame avcodec_send_packet(avCodecContext, &packet); } } int receiveResult = avcodec_receive_frame(avCodecContext, pframe); // Did we get a video frame? if (receiveResult == 0) { // Convert the image from its native format to RGB sws_scale(sws_ctx, (uint8_t const* const*)pframe->data, pframe->linesize, 0, avCodecContext->height, pframeRGB24->data, pframeRGB24->linesize); ++i; Saveframe(pframeRGB24, avCodecContext->width, avCodecContext->height, i); } else if (receiveResult == AVERROR_EOF) { ::MessageBoxA(0, 0, "read eof", 0); SDL_Event event; event.type = BREAK_EVENT; SDL_PushEvent(&event); break; } else if(receiveResult == AVERROR(EAGAIN)){ if (bReadEof) { break; } else { } } else { msgBoxFFmpegError(receiveResult); } // Free the packet that was allocated by av_read_frame if(readResult == 0) av_packet_unref(&packet); } SDL_Quit(); av_frame_free(&pframe); av_frame_free(&pframeRGB24); av_free(bufferRawRGB24); avcodec_close(avCodecContext); avformat_close_input(&avFormatContext); }
完整项目ffmpegsdl2.0rgb24player-互联网文档类资源-CSDN下载



