我们在开发中可能会用到一些播放器,但有时现有的播放器并不能满足我们自定义的需求,这时候需要我们自己来写播放器,这会用到FFmpeg和SDL。FFmpeg是对文件进行解码的工具,SDL可以将解码后的数据转化图像,声音播放。
FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。能够满足我们编解码的需求。它提供了录制、转换以及流化音视频的完整解决方案,FFmpeg有着非常强大的功能。
SDL提供了数种控制图像、声音、输出入的函数,让开发者只要用相同或是相似的代码就可以开发出跨多个平台(Linux、Windows、Mac OS X等)的应用软件 。
在学习ffmpeg之前需要了解一些相关内容,可以看一下师兄之前写的文章,也可以下载雷霄骅大神的视频学习。
然后再来学习FFmpeg的数据结构,如下图:
AVFormatContext 是存储音视频封装格式中包含的信息的结构体。如:视频时长duration,音视频流个数nb_streams, 音视频的文件名filename[], 以及最主要的音视频流streams。
AVInputFormat: 输入数据的封装格式(mp4,avi等格式)。
AVStream 是存储每一个音频/视频流信息的结构体,判断是哪种流的方法是获取其中的 AVCodecContext, AVCodecContext包含的codec_type是流的类型。
AVCodecContext 存储在AVSream内部的codec参数,是一个描述编解码器上下文的结构体,包含了众多编解码器需要的参数信息。
AVCodeC是存储编码器信息的结构体。通过获取编码器函数avcodec_find_decoder(id)获取,id是存在AVCodecContext 结构体内的参数codec_id中。
AVPacket 是存储压缩编码数据相关信息的结构体,是通过调用av_read_frame获得的。
AVFrame 是由AVPacket解码后获得的数据,该结构体一般用于存储原始数据(即非压缩数据,例如对视频来说是 YUV,RGB,对音频来说是 PCM),此外还包含了一些相关的信息。
详细的内容可以看雷霄骅大神关于结构体的文章
了解完结构体后,再学习如何进行解码,视频解码步骤如下:
1. 调用ffmpeg注册复用器,编码器等的函数av_register_all()。该函数在所有基于ffmpeg的应用程序中几乎都是第一个被调用的。只有调用了该函数,才能使用复用器,编码器等。
2. avformat_open_input()。该函数用于打开多媒体数据并且获得一些相关的信息 。
3. avformat_find_stream_info()。该函数可以读取一部分视音频数据并且获得一些相关的信息。
4. avcodec_find_decoder()用于查找FFmpeg的解码器。
5. avcodec_open2()用于打开解码器。
6. 进入循环,循环调用av_read_frame(),av_read_frame()的作用是读取码流中的音频若干帧或者视频一帧。
7. 对读取的音频或视频帧进行解码。 avcodec_decode_video2()的作用是解码一帧视频数据。
8. 所有帧读取完成,退出循环。
下面说一下关于代码中的音视频同步功能:
DTS: packet 解码的时间。
PTS: packet 解码后数据的显示时间 。
time_base :是 PTS 和 DTS 的时间单位,也称时间基,相乘得到时间。
提到time_base就要说一下 储存数据结构AVRational,内部储存了分子和分母,AVRational{1,100}表示1/100 秒。
代码解析:
本文的关键类VideoPlayer_Thread,是一个线程类,下面的内容都是对该类中的内容进行的说明。
VideoState是一个贯彻全文的结构体,该结构体用于在各函数之间使用,包含了媒体播放的状态,数据,标志等内容,由于内容过多,之后提到函数时会对用到的内容说明。
typedef struct VideoState {
AVFormatContext *ic;
int videoStream, audioStream;
AVFrame *audio_frame;// 解码音频过程中的使用缓存
PacketQueue audioq;
AVStream *audio_st; //音频流
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVPacket audio_pkt;//音频包(未解码)
uint8_t *audio_pkt_data;
int audio_pkt_size;
uint8_t *audio_buf;//音频缓存
DECLARE_ALIGNED(16,uint8_t,audio_buf2) [AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
enum AVSampleFormat audio_src_fmt;//输入采用格式
enum AVSampleFormat audio_tgt_fmt;//输出采样格式
int audio_src_channels;//输入通道
int audio_tgt_channels;//输出通道
int64_t audio_src_channel_layout;//通道布局
int64_t audio_tgt_channel_layout;
int audio_src_freq;//输入采样率
int audio_tgt_freq;//输出采样率
struct SwrContext *swr_ctx; //用于解码后的音频格式转换
int audio_hw_buf_size;
double audio_clock; ///音频时钟
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
AVStream *video_st;
PacketQueue videoq;
/// 跳转相关的变量
int seek_req; //跳转标志
int64_t seek_pos; //跳转的位置 -- 微秒
int seek_flag_audio;//跳转标志 -- 用于音频线程中
int seek_flag_video;//跳转标志 -- 用于视频线程中
double seek_time; //跳转的时间(秒) 值和seek_pos是一样的
///播放控制相关
bool isNeedPause; //暂停后跳转先标记此变量
bool isPause; //暂停标志
bool quit; //停止
bool readFinished; //文件读取完毕
bool readThreadFinished;
bool videoThreadFinished;
SDL_Thread *video_tid; //视频线程id
VideoPlayer_Thread *player; //记录下这个类的指针 主要用于在线程里面调用激发信号的函数
bool isMute; //静音标识
float mVolume; //0~1 超过1 表示放大倍数
} VideoState;
线程的启动:
外部调用setFileName设置播放文件,对mVideoState初始化,启动线程
//设置播放文件,启动线程
bool VideoPlayer_Thread::setFileName(QString path)
{
if (mPlayerState != Stop)
{
return false;
}
mFileName = path;
memset(&mVideoState,0,sizeof(VideoState)); //为了安全起见 先将结构体的数据初始化成0了
this->start(); //启动线程
return true;
}
线程的run函数:
1. 先进行一些结构体和变量的声明,赋值,然后打开多媒体,获取流信息,循环查找音频流和视频流的下标,保存到VideoState结构体中,emit通知界面显示视频的长度。
2. 调用audio_stream_component_open(&mVideoState, audioStream)函数完成对音频流的设置,之后调用avcodec_find_decoder查找解码器,avcodec_open2打开解码器
3.同样的方法找到视频流的解码器并打开。
4. 初始化队列。队列是用来存取之后的循环读取到的AVPacket数据。
5. 创建一个解码视频(不解码音频)的线程。
6. 改变状态为播放状态,emit提示播放状态改变。打开SDL,由openSDL函数完成,调用函数SDL_PauseAudioDevice(0)进行播放,参数为1是暂停。SDL_LockAudioDevice和SDL_UnLockAudioDevice是因为SDL回调函数在一个独立的线程中,这样可以保护资源。
7. 进入while循环,先判断是否停止,再判断跳转标记,跳转的实现主要通过av_seek_frame函数,可以跳转到流的指定帧。之后再把队列清理(不清理跳转会有延迟),再加入跳转的标记数据,之后设置跳转时间和跳转标记(音频和视频解码函数会用到)。
8. 当队列里面的数据超过某个大小的时候就暂停读取,避免占用空间过多,如果是暂停状态也是相同操作。
9. 调用av_read_frame读取帧,将帧入队。
10. 循环结束后,进行一些销毁工作
void VideoPlayer_Thread::run()
{
char file_path[1280] = {0};
strcpy(file_path,mFileName.toUtf8().data());
//设置静音
mVideoState.isMute = mIsMute;
//音量
mVideoState.mVolume = mVolume;
VideoState *is = &mVideoState;
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVCodecContext *aCodecCtx;
AVCodec *aCodec;
int audioStream ,videoStream, i;
//分配内存
pFormatCtx = avformat_alloc_context();
//打开多媒体
if (avformat_open_input(&pFormatCtx, file_path, NULL, NULL) != 0) {
printf("can't open the file. \n");
return;
}
//获取流信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
printf("Could't find stream infomation.\n");
return;
}
videoStream = -1;
audioStream = -1;
//循环查找视频中包含的流信息,音频流和视频流
for (i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoStream = i;
}
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO && audioStream < 0)
{
audioStream = i;
}
}
//如果videoStream为-1 说明没有找到视频流
if (videoStream == -1) {
printf("Didn't find a video stream.\n");
return;
}
//audioStream为-1 说明没有找到音频流
if (audioStream == -1) {
printf("Didn't find a audio stream.\n");
return;
}
is->ic = pFormatCtx;
is->videoStream = videoStream;
is->audioStream = audioStream;
emit sig_TotalTimeChanged(getTotalTime());
if (audioStream >= 0) {
/* 所有设置SDL音频流信息的步骤都在这个函数里完成 */
audio_stream_component_open(&mVideoState, audioStream);
}
///查找音频解码器
aCodecCtx = pFormatCtx->streams[audioStream]->codec;
aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
if (aCodec == NULL) {
printf("ACodec not found.\n");
return;
}
///打开音频解码器
if (avcodec_open2(aCodecCtx, aCodec, NULL) < 0) {
printf("Could not open audio codec.\n");
return;
}
is->audio_st = pFormatCtx->streams[audioStream];
///查找视频解码器
pCodecCtx = pFormatCtx->streams[videoStream]->codec;
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
printf("PCodec not found.\n");
return;
}
///打开视频解码器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
printf("Could not open video codec.\n");
return;
}
is->video_st = pFormatCtx->streams[videoStream];
//初始化队列
packet_queue_init(&mVideoState.audioq);
packet_queue_init(&mVideoState.videoq);
///创建一个线程专门用来解码视频
is->video_tid = SDL_CreateThread(video_thread, "video_thread", &mVideoState);
is->player = this;
AVPacket *packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet 用来存放读取的视频
qDebug()<<__FUNCTION__<<is->quit;
mPlayerState = Playing;
emit sig_StateChanged(Playing);
//打开SDL
openSDL();
SDL_LockAudioDevice(mAudioID);
//0播放,1暂停
SDL_PauseAudioDevice(mAudioID,0);
SDL_UnlockAudioDevice(mAudioID);
while (1)
{
if (is->quit)
{
//停止播放了
break;
}
//跳转标志
if (is->seek_req)
{
int stream_index = -1;
int64_t seek_target = is->seek_pos;
if (is->videoStream >= 0)
stream_index = is->videoStream;
else if (is->audioStream >= 0)
stream_index = is->audioStream;
AVRational aVRational = {1, AV_TIME_BASE};
if (stream_index >= 0) {
seek_target = av_rescale_q(seek_target, aVRational,
pFormatCtx->streams[stream_index]->time_base);
}
//跳转函数
//stream_index:基本流索引,表示当前的seek是针对哪个基本流,比如视频或者音频等等。
//timestamp:要seek的时间点,以time_base或者AV_TIME_BASE为单位。
if (av_seek_frame(is->ic, stream_index, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
fprintf(stderr, "%s: error while seeking\n",is->ic->filename);
} else {
if (is->audioStream >= 0) {
AVPacket *packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet
av_new_packet(packet, 10);
strcpy((char*)packet->data,FLUSH_DATA);
packet_queue_flush(&is->audioq); //清除队列
packet_queue_put(&is->audioq, packet); //往队列中存入用来清除的包
}
if (is->videoStream >= 0) {
AVPacket *packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet
av_new_packet(packet, 10);
strcpy((char*)packet->data,FLUSH_DATA);
packet_queue_flush(&is->videoq); //清除队列
packet_queue_put(&is->videoq, packet); //往队列中存入用来清除的包
is->video_clock = 0;
}
}
is->seek_req = 0;
is->seek_time = is->seek_pos / 1000000.0;
is->seek_flag_audio = 1;
is->seek_flag_video = 1;
if (is->isPause)
{
is->isNeedPause = true;
is->isPause = false;
}
}
//这里做了个限制 当队列里面的数据超过某个大小的时候 就暂停读取 防止一下子就把视频读完了,导致的空间分配不足
/* 这里audioq.size是指队列中的所有数据包带的音频数据的总量或者视频数据总量,并不是包的数量 */
//这个值可以稍微写大一些
// qDebug()<<__FUNCTION__<<is->audioq.size<<MAX_AUDIO_SIZE<<is->videoq.size<<MAX_VIDEO_SIZE;
if (is->audioq.size > MAX_AUDIO_SIZE || is->videoq.size > MAX_VIDEO_SIZE) {
SDL_Delay(10);
continue;
}
if (is->isPause == true)
{
SDL_Delay(10);
continue;
}
//读取数据到packet
if (av_read_frame(pFormatCtx, packet) < 0)
{
is->readFinished = true;
if (is->quit)
{
break; //解码线程也执行完了 可以退出了
}
SDL_Delay(10);
continue;
}
//入栈
if (packet->stream_index == videoStream)
{
packet_queue_put(&is->videoq, packet);
//这里我们将数据存入队列 因此不调用 av_free_packet 释放
}
else if( packet->stream_index == audioStream )
{
packet_queue_put(&is->audioq, packet);
//这里我们将数据存入队列 因此不调用 av_free_packet 释放
}
else
{
// Free the packet that was allocated by av_read_frame
av_free_packet(packet);
}
}
///文件读取结束 跳出循环的情况
///等待播放完毕
while (!is->quit) {
SDL_Delay(100);
}
if (mPlayerState != Stop) //不是外部调用的stop 是正常播放结束
{
stop();
}
//下面是一些收尾工作
SDL_LockAudioDevice(mAudioID);
SDL_PauseAudioDevice(mAudioID,1);
SDL_UnlockAudioDevice(mAudioID);
closeSDL();
qDebug()<<__FUNCTION__<<"444";
while(!mVideoState.videoThreadFinished)
{
// qDebug()<<__FUNCTION__<<"videoThreadFinished"<<mVideoState.videoThreadFinished;
msleep(10);
} //确保视频线程结束后 再销毁队列
qDebug()<<__FUNCTION__<<"555";
avcodec_close(aCodecCtx);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
free(packet);
packet_queue_deinit(&mVideoState.videoq);
packet_queue_deinit(&mVideoState.audioq);
is->readThreadFinished = true;
emit sig_StateChanged(Stop);
qDebug()<<__FUNCTION__<<"finished!";
// SDL_Quit();
}
解码视频的video_thread函数:
我们在run函数中创建了一个video_thread函数的线程,下面对这个函数进行说明。
1. 首先也是声明一些变量和结构体,并进行内存分配。
2. 调用sws_getContext函数将解码后的数据转化为RGB格式,然后申请空间,关联内存。
3. 进入while循环,调用packet_queue_get()从队列中获取一帧数据,判断是否跳转,跳转的话就清理解码器的数据。
4. 调用avcodec_decode_video2函数进行解码,获取PTS,AV_NOPTS_VALUE是枚举类型,表示没有PTS。然后用video_pts*time_base得到时间,av_q2d返回的是AVRational结构
5. 调用synchronize_video函数更新同步。判断跳转,true则跳过,直到跳转位置。之后再进行同步的判断:如果视频超前音频,则不进行播放,以等待音频;如果视频落后音频,则丢弃当前帧直接播放下一帧,以追赶音频。
6. 调用 sws_freeContext 函数用来做视频像素格式和分辨率的转换,之前的 sws_getContext 相当于初始化函数, sws_freeContext 相当于销毁函数。
7. 用QImage来加载RGB数据,调用disPlayVideo函数通知界面加载图片(代码中没有用SDL的视频播放,用的自己定义的容器,该函数会emit容器刷新,达到播放效果)。
8. 循环结束后释放内存,销毁操作,设置标记videoThreadFinished为true。
//解码视频
int video_thread(void *arg)
{
VideoState *is = (VideoState *) arg;
AVPacket pkt1, *packet = &pkt1;
int ret, got_picture, numBytes;
double video_pts = 0; //当前视频的pts
double audio_pts = 0; //音频pts
///解码视频相关
AVFrame *pFrame, *pFrameRGB;
uint8_t *out_buffer_rgb; //解码后的rgb数据
struct SwsContext *img_convert_ctx; //用于解码后的视频格式转换
AVCodecContext *pCodecCtx = is->video_st->codec; //视频解码器
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
///这里我们改成了 将解码后的YUV数据转换成RGB32
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,
pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height,
PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
//计算这个格式的图片,需要多少字节来存储
numBytes = avpicture_get_size(PIX_FMT_RGB32, pCodecCtx->width,pCodecCtx->height);
//申请空间
out_buffer_rgb = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
//前面的av_frame_alloc函数,只是为这个AVFrame结构体分配了内存,
//这里把av_malloc得到的内存和AVFrame关联起来。
//当然,其还会设置AVFrame的其他成员
avpicture_fill((AVPicture *) pFrameRGB, out_buffer_rgb, PIX_FMT_RGB32,
pCodecCtx->width, pCodecCtx->height);
while(1)
{
if (is->quit)
{qDebug()<<__FUNCTION__<<"quit!";
packet_queue_flush(&is->videoq); //清空队列
break;
}
if (is->isPause == true) //判断暂停
{
SDL_Delay(10);
continue;
}
//获取一帧
if (packet_queue_get(&is->videoq, packet, 0) <= 0)
{
if (is->readFinished)
{//队列里面没有数据了且读取完毕了
break;
}
else
{
SDL_Delay(1); //队列只是暂时没有数据而已
continue;
}
}
//收到这个数据 说明刚刚执行过跳转 现在需要把解码器的数据 清除一下
if(strcmp((char*)packet->data,FLUSH_DATA) == 0)
{
avcodec_flush_buffers(is->video_st->codec);
av_free_packet(packet);
continue;
}
//packet解码到frame
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture,packet);
if (ret < 0) {
qDebug()<<"decode error.\n";
av_free_packet(packet);
continue;
}
//获取pts
if (packet->dts == AV_NOPTS_VALUE && pFrame->opaque&& *(uint64_t*) pFrame->opaque != AV_NOPTS_VALUE)
{
video_pts = *(uint64_t *) pFrame->opaque;
}
else if (packet->dts != AV_NOPTS_VALUE)
{
video_pts = packet->dts;
}
else
{
video_pts = 0;
}
//pts*time_base得到时间
video_pts *= av_q2d(is->video_st->time_base);
//更新同步
video_pts = synchronize_video(is, pFrame, video_pts);
if (is->seek_flag_video)
{
//发生了跳转 则跳过关键帧到目的时间的这几帧
if (video_pts < is->seek_time)
{
av_free_packet(packet);
continue;
}
else
{
is->seek_flag_video = 0;
}
}
//循环判断是否满足同步
while(1)
{
if (is->quit)
{
break;
}
if (is->readFinished && is->audioq.size == 0)
{//读取完了 且音频数据也播放完了 就剩下视频数据了 直接显示出来了 不用同步了
break;
}
audio_pts = is->audio_clock;
//主要是 跳转的时候 我们把video_clock设置成0了
//因此这里需要更新video_pts
//否则当从后面跳转到前面的时候 会卡在这里
video_pts = is->video_clock;
//满足同步
if (video_pts <= audio_pts) break;
//不满足,等待音频
int delayTime = (video_pts - audio_pts) * 1000;
delayTime = delayTime > 5 ? 5:delayTime;
if (!is->isNeedPause)
SDL_Delay(delayTime);
}
if (got_picture) {
sws_scale(img_convert_ctx,
(uint8_t const * const *) pFrame->data,
pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data,
pFrameRGB->linesize);
//把这个RGB数据 用QImage加载
QImage tmpImg((uchar *)out_buffer_rgb,pCodecCtx->width,pCodecCtx->height,QImage::Format_RGB32);
QImage image = tmpImg.convertToFormat(QImage::Format_RGB888,Qt::NoAlpha); //去掉透明的部分 有些奇葩的视频会透明
//播放视频
is->player->disPlayVideo(image); //调用激发信号的函数
if (is->isNeedPause)
{
is->isPause = true;
is->isNeedPause = false;
}
}
av_free_packet(packet);
}
//收尾工作
av_free(pFrame);
av_free(pFrameRGB);
av_free(out_buffer_rgb);
sws_freeContext(img_convert_ctx);
if (!is->quit)
{
is->quit = true;
}
is->videoThreadFinished = true;
qDebug()<<__FUNCTION__<<"finished!";
return 0;
}
说明一下上面用到的更新同步函数:synchronize_video(VideoState *is, AVFrame *src_frame, double pts),其作用是更新PTS到VideoState结构体,包含了帧延迟的处理。
//用于更新需要同步的视频帧的 PTS
static double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) {
double frame_delay;
if (pts != 0) {
/* if we have pts, set video clock to it */
is->video_clock = pts;
} else {
/* if we aren't given a pts, set it to the clock */
pts = is->video_clock;
}
/* 首行是按照time_base计算出相应帧率下帧之间的间隔。此为一般情况下的帧延迟。
而第二行加上了它的附加延迟。FFmpeg给出了公式:extra_delay = repeat_pict / (2*fps)。
相加即为其的总延迟。 */
frame_delay = av_q2d(is->video_st->codec->time_base);
frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
is->video_clock += frame_delay;
return pts;
}
以上是关于视频解码的函数说明,下面是关于音频解码的相关函数说明。
设置音频流信息函数audio_stream_component_open(&mVideoState, audioStream):
1. 设置通道数量和通道布局,通道布局的获取可以通过av_get_default_channel_layout(int)函数获取,参数为通道数量,然后把参数保存到VideoState结构体中。
2. 获取解码器,然后打开解码器
3. 初始化VideoState结构体中音频相关的参数。
//设置音频流,初始化
int audio_stream_component_open(VideoState *is, int stream_index)
{
AVFormatContext *ic = is->ic;
AVCodecContext *codecCtx;
AVCodec *codec;
//0表示通道未知
int64_t wanted_channel_layout = 0;
int wanted_nb_channels;
if (stream_index < 0 || stream_index >= ic->nb_streams) {
return -1;
}
codecCtx = ic->streams[stream_index]->codec;
//通道数量number of audio channels
wanted_nb_channels = codecCtx->channels;
//在编码的时候有可能丢失通道数量或者channel layout ,这里根据获取的参数设置其默认值
//av_get_channel_layout_nb_channels表示根据通道布局获取其默认的channel数量
//av_get_default_channel_layout表示通过通道数量获取通道布局
if (!wanted_channel_layout
|| wanted_nb_channels
!= av_get_channel_layout_nb_channels(
wanted_channel_layout)) {
wanted_channel_layout = av_get_default_channel_layout(
wanted_nb_channels);
//&操作符,结果为两者共有的声道(缩混立体声)
wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
}
/* 把设置好的参数保存到大结构中 */
is->audio_src_fmt = is->audio_tgt_fmt = AV_SAMPLE_FMT_S16;
is->audio_src_freq = is->audio_tgt_freq = 44100;
is->audio_src_channel_layout = is->audio_tgt_channel_layout =
wanted_channel_layout;
is->audio_src_channels = is->audio_tgt_channels = 2;
//获取解码器
codec = avcodec_find_decoder(codecCtx->codec_id);
//打开解码器
if (!codec || (avcodec_open2(codecCtx, codec, NULL) < 0)) {
fprintf(stderr,"Unsupported codec!\n");
return -1;
}
//设置丢弃 avi 中的无效数据(如:size == 0)
ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
//如果是音频流格式的数据,对大结构体音频相关的一些数据初始化
switch (codecCtx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
is->audio_st = ic->streams[stream_index];
is->audio_buf_size = 0;
is->audio_buf_index = 0;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
break;
default:
break;
}
return 0;
}
SDL初始化,打开设备函数openSDL():
该函数主要用到了SDL_AudioSpec结构体,如下:
typedef struct SDL_AudioSpec {
int freq; /**< DSP frequency -- samples per second */
Uint16 format; /**< Audio data format */
Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */
Uint8 silence; /**< Audio buffer silence value (calculated) */
Uint16 samples; /**< Audio buffer size in samples (power of 2) */
Uint16 padding; /**< Necessary for some compile environments */
Uint32 size; /**< Audio buffer size in bytes (calculated) */
void (SDLCALL *callback)(void *userdata, Uint8 *stream, int len);
void *userdata;
} SDL_AudioSpec;
freq: 指定了每秒向音频设备发送的sample数。常用的值为:11025,22050,44100。值越高质量越好。
format: 指定了每个sample元素的大小和类型。
channels: 指定了声音的通道数:1(单声道)2(立体声)。
samples: 这个值表示音频缓存区的大小(以sample计)。一个sample是一段大小为 format * channels的音频数据。
size: 这个值表示音频缓存区的大小(以byte计)。
silence: 设置静音的值。
padding: 考虑到兼容性的一个参数。
callback: 是获取音频数据后的回调函数,可以作解码获取的音频码流及输出到设备的操作。
openSDL()函数就是对该结构体进行赋值,之后调用SDL_OpenAudioDevice将结构体传入,打开音频设备。
//打开SDL
int VideoPlayer_Thread::openSDL()
{
VideoState *is = &mVideoState;
SDL_AudioSpec wanted_spec, spec;
int64_t wanted_channel_layout = 0;
int wanted_nb_channels = 2;
//采样率
int samplerate = 44100;
/* SDL支持的声道数为 1, 2, 4, 6 */
// /* 后面我们会使用这个数组来纠正不支持的声道数目 */
// const int next_nb_channels[] = { 0, 0, 1, 6, 2, 6, 4, 6 };
if (!wanted_channel_layout
|| wanted_nb_channels
!= av_get_channel_layout_nb_channels(
wanted_channel_layout)) {
wanted_channel_layout = av_get_default_channel_layout(
wanted_nb_channels);
wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
}
wanted_spec.channels = av_get_channel_layout_nb_channels(
wanted_channel_layout);
//采样率
wanted_spec.freq = samplerate;
if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
//fprintf(stderr,"Invalid sample rate or channel count!\n");
return -1;
}
wanted_spec.format = AUDIO_S16SYS; // 音频数据的格式
wanted_spec.silence = 0; // 0指示静音
wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE; // 自定义SDL缓冲区大小
//我们开始播放音频时,SDL将不断调用这个回调函数,并要求它填充一定数量的字节的音频缓冲区
wanted_spec.callback = audio_callback;
wanted_spec.userdata = is; // 传给上面回调函数的外带数据
int num = SDL_GetNumAudioDevices(0);
for (int i=0;i<num;i++)
{
//打开音频
mAudioID = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(i,0), false, &wanted_spec, &spec,0);
if (mAudioID > 0)
{
break;
}
}
/* 检查实际使用的配置(保存在spec,由SDL_OpenAudio()填充) */
if (spec.format != AUDIO_S16SYS) {
qDebug()<<"SDL advised audio format %d is not supported!"<<spec.format;
return -1;
}
if (spec.channels != wanted_spec.channels) {
wanted_channel_layout = av_get_default_channel_layout(spec.channels);
if (!wanted_channel_layout) {
fprintf(stderr,"SDL advised channel count %d is not supported!\n",spec.channels);
return -1;
}
}
is->audio_hw_buf_size = spec.size;
/* 把设置好的参数保存到大结构中 */
is->audio_src_fmt = is->audio_tgt_fmt = AV_SAMPLE_FMT_S16;
is->audio_src_freq = is->audio_tgt_freq = spec.freq;
is->audio_src_channel_layout = is->audio_tgt_channel_layout =
wanted_channel_layout;
is->audio_src_channels = is->audio_tgt_channels = spec.channels;
is->audio_buf_size = 0;
is->audio_buf_index = 0;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
return 0;
}
回调函数audio_callback(void *userdata, Uint8 *stream, int len):
userdata是我们给SDL的指针( VideoState结构体is ),stream是我们将要写入音频数据的缓冲区,len是该缓冲区的大小。该函数作用是在SDL播放过程中,向SDL缓存区填充数据,这个是由SDL自动调用的。
1. 声明一些结构体和变量,len1为本次提供给SDL的数据量,audio_data_size为解码出来的数据量。
2. 进入循环,先判断结构体中音频缓存是否为空,为空的话说明没有数据可以提供给SDL缓存,这时需要调用audio_decode_frame来解码出更多数据。
3. 判断VideoState结构体中的缓存是否大于SDL缓存,大于就提供len大小的数据给SDL,小于就提供全部缓存。
4. 调用memcpy函数将数据copy到SDL缓存,修改相关数据。
static void audio_callback(void *userdata, Uint8 *stream, int len) {
VideoState *is = (VideoState *) userdata;
//len1 本次提供给SDL的数据量
//audio_data_size 解码出来的数据量
int len1, audio_data_size;
//显示时间戳
double pts;
/* len是由SDL传入的SDL缓冲区的大小,如果这个缓冲未满,我们就一直往里填充数据 */
while (len > 0) {
/* audio_buf_index 和 audio_buf_size 标示我们自己用来放置解码出来的数据的缓冲区,*/
/* 这些数据待copy到SDL缓冲区, 当audio_buf_index >= audio_buf_size的时候意味着我*/
/* 们的缓冲为空,没有数据可供copy,这时候需要调用audio_decode_frame来解码出更
/* 多的桢数据 */
// qDebug()<<__FUNCTION__<<is->audio_buf_index<<is->audio_buf_size;
if (is->audio_buf_index >= is->audio_buf_size) {
/////解码音频
audio_data_size = audio_decode_frame(is, &pts);
/* audio_data_size < 0 标示没能解码出数据,我们默认播放静音 */
if (audio_data_size < 0) {
/* silence */
is->audio_buf_size = 1024;
/* 清零,静音 */
if (is->audio_buf == NULL) return;
memset(is->audio_buf, 0, is->audio_buf_size);
} else {
is->audio_buf_size = audio_data_size;
}
//音频缓存下标重置
is->audio_buf_index = 0;
}
/* 查看stream可用空间,决定一次copy多少数据,剩下的下次继续copy */
len1 = is->audio_buf_size - is->audio_buf_index;
if (len1 > len) {
len1 = len;
}
if (is->audio_buf == NULL) return;
if (is->isMute || is->isNeedPause) //静音 或者 是在暂停的时候跳转了
{
memset(is->audio_buf + is->audio_buf_index, 0, len1);
}
else
{
RaiseVolume((char*)is->audio_buf + is->audio_buf_index, len1, 1, is->mVolume);
}
//缓存copy到SDL缓存流中
memcpy(stream, (uint8_t *) is->audio_buf + is->audio_buf_index, len1);
//SDL缓存-获得的数据
len -= len1;
//stream数据增加len1
stream += len1;
//音频缓存下标增加len1
is->audio_buf_index += len1;
}
}
音频解码函数audio_decode_frame(VideoState *is, double *pts_ptr):
1. 声明变量和结构体
2. 进入for循环,packet大于0,进入while循环,进入循环后进行一些判断(暂停,空值等),调用avcodec_decode_audio4解码函数,该函数返回结果为0表示成功解码,传递的参数
成功解码一个frame后传入的参数got_frame变为1。
3. 计算解码出来的桢需要的缓冲大小和声道设置。
4. 重采样判断(当前帧的数据和结构体的数据不一样),调用swr_alloc_set_opts函数,分配SwrContext并设置/重置常用的参数。
什么是重采样?重采样即改变文件原有的采样率。
为什么进行重采样?音频系统中可能存在多个音轨,而每个音轨的原始采样率可能是不一致的。比如播放音乐时收到了信息提示音,就需要把音乐和提示音都混合到codec输出,音乐的原始采样率和提示音的原始采样率可能是不一致的。我们可以设置一个采样率,将两者都重采样到这个采样率。
5. 判断重采样上下文结构体是否为空,设置输入缓冲和输出缓冲,判断是否进行了重采样,true则激活重采样补偿。之后进行音频转换,调用swr_convert函数。
6. 设置pts,对音频时钟更新。
7. 之后进行的跳转等操作和视频解码类似。
//解码音频
static int audio_decode_frame(VideoState *is, double *pts_ptr)
{
int len1, len2, decoded_data_size;
AVPacket *pkt = &is->audio_pkt;
int got_frame = 0;
int64_t dec_channel_layout;
//nb_samples:音频的一个AVFrame中可能包含多个音频帧,在此标记包含了几个
int wanted_nb_samples, resampled_data_size, n;
double pts;
for (;;) {
while (is->audio_pkt_size > 0) {
if (is->isPause == true) //判断暂停
{
return -1;
SDL_Delay(10);
continue;
}
if (!is->audio_frame) {
if (!(is->audio_frame = avcodec_alloc_frame())) {
return AVERROR(ENOMEM);
}
} else// 将给定AVFrame的字段设置为默认值
avcodec_get_frame_defaults(is->audio_frame);
//音频解码
//建议使用avcodec_send_packet和avcodec_receive_frame获取解码后的原始数据
len1 = avcodec_decode_audio4(is->audio_st->codec, is->audio_frame,
&got_frame, pkt);
//解码失败
if (len1 < 0) {
// error, skip the frame
is->audio_pkt_size = 0;
break;
}
//已解码数据大小
is->audio_pkt_data += len1;
//未解码数据大小
is->audio_pkt_size -= len1;
if (!got_frame)
continue;
/* 计算解码出来的桢需要的缓冲大小 */
decoded_data_size = av_samples_get_buffer_size(NULL,
is->audio_frame->channels, is->audio_frame->nb_samples,
(AVSampleFormat)is->audio_frame->format, 1);
//声道设置
dec_channel_layout =
(is->audio_frame->channel_layout
&& is->audio_frame->channels
== av_get_channel_layout_nb_channels(is->audio_frame->channel_layout)) ?
is->audio_frame->channel_layout :
av_get_default_channel_layout(is->audio_frame->channels);
//一个Frame可能有多个音频帧,指音频帧数
wanted_nb_samples = is->audio_frame->nb_samples;
//format:(解码后原始数据类型(YUV420,YUV422,RGB24, PCM...)
//sample_rate:音频采样率
//结构体中的数据和当前帧的数据不一致,重采样
if (is->audio_frame->format != is->audio_src_fmt
|| dec_channel_layout != is->audio_src_channel_layout
|| is->audio_frame->sample_rate != is->audio_src_freq
|| (wanted_nb_samples != is->audio_frame->nb_samples
&& !is->swr_ctx))
{
if (is->swr_ctx)
swr_free(&is->swr_ctx);
//分配SwrContext并设置/重置常用的参数
/**
参数1:重采样上下文
参数2:输出的layout, 如:5.1声道…
参数3:输出的样本格式。Float, S16, S24
参数4:输出的样本率。可以不变。
参数5:输入的layout。
参数6:输入的样本格式。
参数7:输入的样本率。
参数8,参数9,日志,不用管,可直接传0
**/
is->swr_ctx = swr_alloc_set_opts(NULL,
is->audio_tgt_channel_layout, (AVSampleFormat)is->audio_tgt_fmt,
is->audio_tgt_freq, dec_channel_layout,
(AVSampleFormat)is->audio_frame->format, is->audio_frame->sample_rate,
0, NULL);
//swr_init
if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
//fprintf(stderr,"swr_init() failed\n");
break;
}
is->audio_src_channel_layout = dec_channel_layout;
is->audio_src_channels = is->audio_st->codec->channels;
is->audio_src_freq = is->audio_st->codec->sample_rate;
is->audio_src_fmt = is->audio_st->codec->sample_fmt;
}
/* 这里我们可以对采样数进行调整,增加或者减少,一般可以用来做声画同步 */
if (is->swr_ctx) {
const uint8_t **in =
(const uint8_t **) is->audio_frame->extended_data;
uint8_t *out[] = { is->audio_buf2 };
// qDebug()<<wanted_nb_samples<<"...."<<is->audio_frame->nb_samples;
//一般情况下两个参数是相等的
//不一样说明进行了重采样
if (wanted_nb_samples != is->audio_frame->nb_samples) {
//激活重采样补偿
/**
s:分配Swr上下文。 如果未初始化,或未设置SWR_FLAG_RESAMPLE,则会使用标志集调用swr_init()。
sample_delta:每个样本PTS的delta
compensation_distance:要补偿的样品数量
**/
if (swr_set_compensation(is->swr_ctx,
(wanted_nb_samples - is->audio_frame->nb_samples)
* is->audio_tgt_freq
/ is->audio_frame->sample_rate,
wanted_nb_samples * is->audio_tgt_freq
/ is->audio_frame->sample_rate) < 0) {
break;
}
}
//转换音频
/**参数:s:分配Swr上下文,并设置参数
out:输出缓冲区,只有在打包音频的情况下才需要设置第一个
out_count:每个通道样品中可用于输出的空间量
in:输入缓冲区,只有在打包音频的情况下才需要设置第一个
in_count:在一个通道中可用的输入样本数
返回:每个通道的采样数量,误差的负值
**/
len2 = swr_convert(is->swr_ctx, out,
sizeof(is->audio_buf2) / is->audio_tgt_channels
/ av_get_bytes_per_sample(is->audio_tgt_fmt),
in, is->audio_frame->nb_samples);
if (len2 < 0) {
//fprintf(stderr,"swr_convert() failed\n");
break;
}
if (len2
== sizeof(is->audio_buf2) / is->audio_tgt_channels
/ av_get_bytes_per_sample(is->audio_tgt_fmt)) {
//fprintf(stderr,"warning: audio buffer is probably too small\n");
swr_init(is->swr_ctx);
}
//音频数据
is->audio_buf = is->audio_buf2;
//采样数据大小
resampled_data_size = len2 * is->audio_tgt_channels
* av_get_bytes_per_sample(is->audio_tgt_fmt);
} else {
resampled_data_size = decoded_data_size;
is->audio_buf = is->audio_frame->data[0];
}
//设置pts
pts = is->audio_clock;
*pts_ptr = pts;
n = 2 * is->audio_st->codec->channels;
//下一个时钟
is->audio_clock += (double) resampled_data_size
/ (double) (n * is->audio_st->codec->sample_rate);
if (is->seek_flag_audio)
{
//发生了跳转 则跳过关键帧到目的时间的这几帧
if (is->audio_clock < is->seek_time)
{
break;
}
else
{
is->seek_flag_audio = 0;
}
}
// We have data, return it and come back for more later
return resampled_data_size;
}
if (pkt->data)
av_free_packet(pkt);
memset(pkt, 0, sizeof(*pkt));
if (is->quit)
{
packet_queue_flush(&is->audioq);
return -1;
}
if (is->isPause == true) //判断暂停
{
return -1;
}
//出队,获取packet
if (packet_queue_get(&is->audioq, pkt, 0) <= 0)
{
return -1;
}
//收到这个数据 说明刚刚执行过跳转 现在需要把解码器的数据 清除一下
if(strcmp((char*)pkt->data,FLUSH_DATA) == 0)
{
avcodec_flush_buffers(is->audio_st->codec);
av_free_packet(pkt);
continue;
}
is->audio_pkt_data = pkt->data;
is->audio_pkt_size = pkt->size;
/* if update, update the audio clock w/pts */
if (pkt->pts != AV_NOPTS_VALUE) {
is->audio_clock = av_q2d(is->audio_st->time_base) * pkt->pts;
}
}
return 0;
}
通过上述的代码说明,能够发现,视频和音频始终都是在上面提到的解码的顺序结构进行的,只不过是在过程中添加了一些其他的处理。
完整代码:
videoplayer_thread.h
#ifndef VIDEOPLAYER_THREAD_H
#define VIDEOPLAYER_THREAD_H
#include <QThread>
#include <QImage>
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include <libavutil/time.h>
#include "libavutil/pixfmt.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
#include <SDL.h>
#include <SDL_audio.h>
#include <SDL_types.h>
#include <SDL_name.h>
#include <SDL_main.h>
#include <SDL_config.h>
}
#include "videoplayer/videoplayer_showvideowidget.h"
typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutex;
SDL_cond *cond;
} PacketQueue;
#define VIDEO_PICTURE_QUEUE_SIZE 1
#define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
#define MAX_AUDIO_SIZE (25 * 16 * 1024)
#define MAX_VIDEO_SIZE (25 * 256 * 1024)
class VideoPlayer_Thread; //前置声明
typedef struct VideoState {
AVFormatContext *ic;
int videoStream, audioStream;
AVFrame *audio_frame;// 解码音频过程中的使用缓存
PacketQueue audioq;//音频队列
AVStream *audio_st; //音频流
unsigned int audio_buf_size;//音频缓存大小
unsigned int audio_buf_index;//音频缓存下标
AVPacket audio_pkt;//音频包(未解码)
uint8_t *audio_pkt_data;
int audio_pkt_size;
uint8_t *audio_buf;//音频缓存
DECLARE_ALIGNED(16,uint8_t,audio_buf2) [AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
enum AVSampleFormat audio_src_fmt;//输入采用格式
enum AVSampleFormat audio_tgt_fmt;//输出采样格式
int audio_src_channels;//输入通道
int audio_tgt_channels;//输出通道
int64_t audio_src_channel_layout;//通道布局
int64_t audio_tgt_channel_layout;
int audio_src_freq;//输入采样率
int audio_tgt_freq;//输出采样率
struct SwrContext *swr_ctx; //用于解码后的音频格式转换
int audio_hw_buf_size;//SDL缓存大小
double audio_clock; ///音频时钟
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
AVStream *video_st;
PacketQueue videoq;
/// 跳转相关的变量
int seek_req; //跳转标志
int64_t seek_pos; //跳转的位置 -- 微秒
int seek_flag_audio;//跳转标志 -- 用于音频线程中
int seek_flag_video;//跳转标志 -- 用于视频线程中
double seek_time; //跳转的时间(秒) 值和seek_pos是一样的
///播放控制相关
bool isNeedPause; //暂停后跳转先标记此变量
bool isPause; //暂停标志
bool quit; //停止
bool readFinished; //文件读取完毕
bool readThreadFinished;
bool videoThreadFinished;
SDL_Thread *video_tid; //视频线程id
VideoPlayer_Thread *player; //记录下这个类的指针 主要用于在线程里面调用激发信号的函数
bool isMute; //静音标识
float mVolume; //0~1 超过1 表示放大倍数
} VideoState;
class VideoPlayer_Thread : public QThread
{
Q_OBJECT
public:
enum PlayerState
{
Playing,
Pause,
Stop
};
explicit VideoPlayer_Thread();
~VideoPlayer_Thread();
bool setFileName(QString path);
bool replay(); //重新播放
bool play();
bool pause();
bool stop(bool isWait = false); //参数表示是否等待所有的线程执行完毕再返回
void seek(int64_t pos); //单位是微秒
void setMute(bool isMute){mIsMute = isMute;}
void setVolume(float value);
int64_t getTotalTime(); //单位微秒
double getCurrentTime(); //单位秒
void disPlayVideo(QImage img);
void setVideoWidget(VideoPlayer_ShowVideoWidget*widget);
QWidget *getVideoWidget(){return mVideoWidget;}
signals:
void sig_GetOneFrame(QImage); //每获取到一帧图像 就发送此信号
void sig_StateChanged(VideoPlayer_Thread::PlayerState state);
void sig_TotalTimeChanged(qint64 uSec); //获取到视频时长的时候激发此信号
protected:
void run();
private:
QString mFileName;
VideoState mVideoState;
PlayerState mPlayerState; //播放状态
///用自己的控件替代SLD 是因为SDL会导致QSS样式失效
VideoPlayer_ShowVideoWidget *mVideoWidget; //显示视频用的控件
bool mIsMute;
float mVolume; //0~1 超过1 表示放大倍数
SDL_AudioDeviceID mAudioID;
int openSDL();
void closeSDL();
void deInit();
};
#endif // VIDEOPLAYER_THREAD_H
videoplayer_thread.cpp
#include "videoplayer_thread.h"
#include <stdio.h>
#include <QDebug>
#define SDL_AUDIO_BUFFER_SIZE 1024
#define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio
//跳转时会将队列清空,加入FLUSH_DATA
#define FLUSH_DATA "FLUSH"
//清空队列
static void packet_queue_flush(PacketQueue *q)
{
AVPacketList *pkt, *pkt1;
//互斥锁加锁
SDL_LockMutex(q->mutex);
for(pkt = q->first_pkt; pkt != NULL; pkt = pkt1)
{
pkt1 = pkt->next;
if(pkt1->pkt.data != (uint8_t *)"FLUSH")
{
}
//将packet指向的数据域的引用技术减1
av_free_packet(&pkt->pkt);
//释放内存
av_freep(&pkt);
}
q->last_pkt = NULL;
q->first_pkt = NULL;
q->nb_packets = 0;
q->size = 0;
//互斥锁解锁
SDL_UnlockMutex(q->mutex);
}
//队列销毁
static void packet_queue_deinit(PacketQueue *q) {
packet_queue_flush(q);
SDL_DestroyMutex(q->mutex);
SDL_DestroyCond(q->cond);
}
//初始化队列
void packet_queue_init(PacketQueue *q) {
//初始化内存单元
memset(q, 0, sizeof(PacketQueue));
//创建Mutex和Cond
q->mutex = SDL_CreateMutex();
q->cond = SDL_CreateCond();
//初始化其他
q->size = 0;
q->nb_packets = 0;
q->first_pkt = NULL;
q->last_pkt = NULL;
}
//队列添加内容
int packet_queue_put(PacketQueue *q, AVPacket *pkt) {
AVPacketList *pkt1;
if (av_dup_packet(pkt) < 0) {
return -1;
}
pkt1 = (AVPacketList*)av_malloc(sizeof(AVPacketList));
if (!pkt1)
return -1;
pkt1->pkt = *pkt;
pkt1->next = NULL;
//加锁
SDL_LockMutex(q->mutex);
//队列操作:如果last_pkt为空,说明队列是空的,新增节点为队头;否则,队列有数据,则让原队尾的next为新增节点,最后将队尾指向新增节点
if (!q->last_pkt)
q->first_pkt = pkt1;
else
q->last_pkt->next = pkt1;
q->last_pkt = pkt1;
q->nb_packets++;
q->size += pkt1->pkt.size;
//通知
SDL_CondSignal(q->cond);
//解锁
SDL_UnlockMutex(q->mutex);
return 0;
}
//出队
static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) {
AVPacketList *pkt1;
int ret;
SDL_LockMutex(q->mutex);
for (;;) {
pkt1 = q->first_pkt;
if (pkt1) {//队列中有数据
q->first_pkt = pkt1->next;//队头移到第二个节点
if (!q->first_pkt)
q->last_pkt = NULL;
q->nb_packets--;//节点数减1
q->size -= pkt1->pkt.size;
*pkt = pkt1->pkt;
av_free(pkt1);//释放节点内存
ret = 1;
break;
} else if (!block) {//队列中没有数据,且非阻塞调用
ret = 0;
break;
} else {//队列中没有数据,且阻塞调用
SDL_CondWait(q->cond, q->mutex);//这里没有break。for循环的另一个作用是在条件变量满足后重复上述代码取出节点
}
}
SDL_UnlockMutex(q->mutex);
return ret;
}
//解码音频
static int audio_decode_frame(VideoState *is, double *pts_ptr)
{
int len1, len2, decoded_data_size;
AVPacket *pkt = &is->audio_pkt;
int got_frame = 0;
int64_t dec_channel_layout;
//nb_samples:音频的一个AVFrame中可能包含多个音频帧,在此标记包含了几个
int wanted_nb_samples, resampled_data_size, n;
double pts;
for (;;) {
while (is->audio_pkt_size > 0) {
if (is->isPause == true) //判断暂停
{
return -1;
SDL_Delay(10);
continue;
}
if (!is->audio_frame) {
if (!(is->audio_frame = avcodec_alloc_frame())) {
return AVERROR(ENOMEM);
}
} else// 将给定AVFrame的字段设置为默认值
avcodec_get_frame_defaults(is->audio_frame);
//音频解码
//建议使用avcodec_send_packet和avcodec_receive_frame获取解码后的原始数据
len1 = avcodec_decode_audio4(is->audio_st->codec, is->audio_frame,
&got_frame, pkt);
//解码失败
if (len1 < 0) {
// error, skip the frame
is->audio_pkt_size = 0;
break;
}
is->audio_pkt_data += len1;
is->audio_pkt_size -= len1;
if (!got_frame)
continue;
/* 计算解码出来的桢需要的缓冲大小 */
decoded_data_size = av_samples_get_buffer_size(NULL,
is->audio_frame->channels, is->audio_frame->nb_samples,
(AVSampleFormat)is->audio_frame->format, 1);
//声道设置
dec_channel_layout =
(is->audio_frame->channel_layout
&& is->audio_frame->channels
== av_get_channel_layout_nb_channels(is->audio_frame->channel_layout)) ?
is->audio_frame->channel_layout :
av_get_default_channel_layout(is->audio_frame->channels);
//音频采样数
wanted_nb_samples = is->audio_frame->nb_samples;
//format:(解码后原始数据类型(YUV420,YUV422,RGB24, PCM...)
//sample_rate:音频采样率
if (is->audio_frame->format != is->audio_src_fmt
|| dec_channel_layout != is->audio_src_channel_layout
|| is->audio_frame->sample_rate != is->audio_src_freq
|| (wanted_nb_samples != is->audio_frame->nb_samples
&& !is->swr_ctx))
{
//重采样
if (is->swr_ctx)
swr_free(&is->swr_ctx);
//分配SwrContext并设置/重置常用的参数
is->swr_ctx = swr_alloc_set_opts(NULL,
is->audio_tgt_channel_layout, (AVSampleFormat)is->audio_tgt_fmt,
is->audio_tgt_freq, dec_channel_layout,
(AVSampleFormat)is->audio_frame->format, is->audio_frame->sample_rate,
0, NULL);
//swr_init
if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
//fprintf(stderr,"swr_init() failed\n");
break;
}
is->audio_src_channel_layout = dec_channel_layout;
is->audio_src_channels = is->audio_st->codec->channels;
is->audio_src_freq = is->audio_st->codec->sample_rate;
is->audio_src_fmt = is->audio_st->codec->sample_fmt;
}
/* 这里我们可以对采样数进行调整,增加或者减少,一般可以用来做声画同步 */
if (is->swr_ctx) {
const uint8_t **in =
(const uint8_t **) is->audio_frame->extended_data;
uint8_t *out[] = { is->audio_buf2 };
if (wanted_nb_samples != is->audio_frame->nb_samples) {
//低级选项设置函数
/**
s:分配Swr上下文。 如果未初始化,或未设置SWR_FLAG_RESAMPLE,则会使用标志集调用swr_init()。
sample_delta:每个样本PTS的delta
compensation_distance:要补偿的样品数量
**/
if (swr_set_compensation(is->swr_ctx,
(wanted_nb_samples - is->audio_frame->nb_samples)
* is->audio_tgt_freq
/ is->audio_frame->sample_rate,
wanted_nb_samples * is->audio_tgt_freq
/ is->audio_frame->sample_rate) < 0) {
break;
}
}
//转换音频
/**参数:s:分配Swr上下文,并设置参数
out:输出缓冲区,只有在打包音频的情况下才需要设置第一个
out_count:每个通道样品中可用于输出的空间量
in:输入缓冲区,只有在打包音频的情况下才需要设置第一个
in_count:在一个通道中可用的输入样本数
返回:每个通道的采样数量,误差的负值
**/
len2 = swr_convert(is->swr_ctx, out,
sizeof(is->audio_buf2) / is->audio_tgt_channels
/ av_get_bytes_per_sample(is->audio_tgt_fmt),
in, is->audio_frame->nb_samples);
if (len2 < 0) {
//fprintf(stderr,"swr_convert() failed\n");
break;
}
if (len2
== sizeof(is->audio_buf2) / is->audio_tgt_channels
/ av_get_bytes_per_sample(is->audio_tgt_fmt)) {
//fprintf(stderr,"warning: audio buffer is probably too small\n");
swr_init(is->swr_ctx);
}
//音频数据
is->audio_buf = is->audio_buf2;
//采样数据大小
resampled_data_size = len2 * is->audio_tgt_channels
* av_get_bytes_per_sample(is->audio_tgt_fmt);
} else {
resampled_data_size = decoded_data_size;
is->audio_buf = is->audio_frame->data[0];
}
//设置pts
pts = is->audio_clock;
*pts_ptr = pts;
n = 2 * is->audio_st->codec->channels;
//下一个时钟
is->audio_clock += (double) resampled_data_size
/ (double) (n * is->audio_st->codec->sample_rate);
if (is->seek_flag_audio)
{
//发生了跳转 则跳过关键帧到目的时间的这几帧
if (is->audio_clock < is->seek_time)
{
break;
}
else
{
is->seek_flag_audio = 0;
}
}
// We have data, return it and come back for more later
return resampled_data_size;
}
if (pkt->data)
av_free_packet(pkt);
memset(pkt, 0, sizeof(*pkt));
if (is->quit)
{
packet_queue_flush(&is->audioq);
return -1;
}
if (is->isPause == true) //判断暂停
{
return -1;
}
if (packet_queue_get(&is->audioq, pkt, 0) <= 0)
{
return -1;
}
//收到这个数据 说明刚刚执行过跳转 现在需要把解码器的数据 清除一下
if(strcmp((char*)pkt->data,FLUSH_DATA) == 0)
{
avcodec_flush_buffers(is->audio_st->codec);
av_free_packet(pkt);
continue;
}
is->audio_pkt_data = pkt->data;
is->audio_pkt_size = pkt->size;
/* if update, update the audio clock w/pts */
if (pkt->pts != AV_NOPTS_VALUE) {
is->audio_clock = av_q2d(is->audio_st->time_base) * pkt->pts;
}
}
return 0;
}
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long DWORD;
typedef int BOOL;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef float FLOAT;
typedef FLOAT *PFLOAT;
typedef int INT;
typedef unsigned int UINT;
typedef unsigned int *PUINT;
typedef unsigned long ULONG_PTR, *PULONG_PTR;
typedef ULONG_PTR DWORD_PTR, *PDWORD_PTR;
#define MAKEWORD(a, b) ((WORD)(((BYTE)(((DWORD_PTR)(a)) & 0xff)) | ((WORD)((BYTE)(((DWORD_PTR)(b)) & 0xff))) << 8))
#define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
#define LOWORD(l) ((WORD)(((DWORD_PTR)(l)) & 0xffff))
#define HIWORD(l) ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff))
#define LOBYTE(w) ((BYTE)(((DWORD_PTR)(w)) & 0xff))
#define HIBYTE(w) ((BYTE)((((DWORD_PTR)(w)) >> 8) & 0xff))
//buf为需要调节音量的音频数据块首地址指针,size为长度,uRepeat为重复次数,通常设为1,vol为增益倍数,可以小于1
void RaiseVolume(char* buf, int size, int uRepeat, double vol)
{
if (!size)
{
return;
}
for (int i = 0; i < size; i += 2)
{
short wData;
wData = MAKEWORD(buf[i], buf[i + 1]);
long dwData = wData;
for (int j = 0; j < uRepeat; j++)
{
dwData = dwData * vol;
if (dwData < -0x8000)
{
dwData = -0x8000;
}
else if (dwData > 0x7FFF)
{
dwData = 0x7FFF;
}
}
wData = LOWORD(dwData);
buf[i] = LOBYTE(wData);
buf[i + 1] = HIBYTE(wData);
}
}
//buffer中的数据来源
//其中userdata是我们给SDL的指针,stream是我们将要写入音频数据的缓冲区,len是该缓冲区的大小
static void audio_callback(void *userdata, Uint8 *stream, int len) {
VideoState *is = (VideoState *) userdata;
//len1 本次提供给SDL的数据量
//audio_data_size 解码出来的数据量
int len1, audio_data_size;
//显示时间戳
double pts;
/* len是由SDL传入的SDL缓冲区的大小,如果这个缓冲未满,我们就一直往里填充数据 */
while (len > 0) {
/* audio_buf_index 和 audio_buf_size 标示我们自己用来放置解码出来的数据的缓冲区,*/
/* 这些数据待copy到SDL缓冲区, 当audio_buf_index >= audio_buf_size的时候意味着我*/
/* 们的缓冲为空,没有数据可供copy,这时候需要调用audio_decode_frame来解码出更
/* 多的桢数据 */
// qDebug()<<__FUNCTION__<<is->audio_buf_index<<is->audio_buf_size;
if (is->audio_buf_index >= is->audio_buf_size) {
/////解码音频
audio_data_size = audio_decode_frame(is, &pts);
/* audio_data_size < 0 标示没能解码出数据,我们默认播放静音 */
if (audio_data_size < 0) {
/* silence */
is->audio_buf_size = 1024;
/* 清零,静音 */
if (is->audio_buf == NULL) return;
memset(is->audio_buf, 0, is->audio_buf_size);
} else {
is->audio_buf_size = audio_data_size;
}
//音频缓存下标重置
is->audio_buf_index = 0;
}
/* 查看stream可用空间,决定一次copy多少数据,剩下的下次继续copy */
len1 = is->audio_buf_size - is->audio_buf_index;
if (len1 > len) {
len1 = len;
}
if (is->audio_buf == NULL) return;
if (is->isMute || is->isNeedPause) //静音 或者 是在暂停的时候跳转了
{
memset(is->audio_buf + is->audio_buf_index, 0, len1);
}
else
{
RaiseVolume((char*)is->audio_buf + is->audio_buf_index, len1, 1, is->mVolume);
}
//缓存copy到SDL缓存流中
memcpy(stream, (uint8_t *) is->audio_buf + is->audio_buf_index, len1);
//SDL缓存-获得的数据
len -= len1;
//stream数据增加len1
stream += len1;
//音频缓存下标增加len1
is->audio_buf_index += len1;
}
}
static double get_audio_clock(VideoState *is)
{
double pts;
int hw_buf_size, bytes_per_sec, n;
pts = is->audio_clock; /* maintained in the audio thread */
hw_buf_size = is->audio_buf_size - is->audio_buf_index;
bytes_per_sec = 0;
n = is->audio_st->codec->channels * 2;
if(is->audio_st)
{
bytes_per_sec = is->audio_st->codec->sample_rate * n;
}
if(bytes_per_sec)
{
pts -= (double)hw_buf_size / bytes_per_sec;
}
return pts;
}
//用于更新需要同步的视频帧的 PTS
static double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) {
double frame_delay;
if (pts != 0) {
/* if we have pts, set video clock to it */
is->video_clock = pts;
} else {
/* if we aren't given a pts, set it to the clock */
pts = is->video_clock;
}
/* 首行是按照time_base计算出相应帧率下帧之间的间隔。此为一般情况下的帧延迟。
而第二行加上了它的附加延迟。FFmpeg给出了公式:extra_delay = repeat_pict / (2*fps)。
相加即为其的总延迟。 */
frame_delay = av_q2d(is->video_st->codec->time_base);
frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
is->video_clock += frame_delay;
return pts;
}
//设置音频流
int audio_stream_component_open(VideoState *is, int stream_index)
{
AVFormatContext *ic = is->ic;
AVCodecContext *codecCtx;
AVCodec *codec;
//0表示通道未知
int64_t wanted_channel_layout = 0;
int wanted_nb_channels;
if (stream_index < 0 || stream_index >= ic->nb_streams) {
return -1;
}
codecCtx = ic->streams[stream_index]->codec;
//通道数量number of audio channels
wanted_nb_channels = codecCtx->channels;
//在编码的时候有可能丢失通道数量或者channel layout ,这里根据获取的参数设置其默认值
//av_get_channel_layout_nb_channels表示根据通道布局获取其默认的channel数量
//av_get_default_channel_layout表示通过通道数量获取通道布局
if (!wanted_channel_layout
|| wanted_nb_channels
!= av_get_channel_layout_nb_channels(
wanted_channel_layout)) {
wanted_channel_layout = av_get_default_channel_layout(
wanted_nb_channels);
//&操作符,结果为两者共有的声道(缩混立体声)
wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
}
/* 把设置好的参数保存到大结构中 */
is->audio_src_fmt = is->audio_tgt_fmt = AV_SAMPLE_FMT_S16;
is->audio_src_freq = is->audio_tgt_freq = 44100;
is->audio_src_channel_layout = is->audio_tgt_channel_layout =
wanted_channel_layout;
is->audio_src_channels = is->audio_tgt_channels = 2;
//获取解码器
codec = avcodec_find_decoder(codecCtx->codec_id);
//打开解码器
if (!codec || (avcodec_open2(codecCtx, codec, NULL) < 0)) {
fprintf(stderr,"Unsupported codec!\n");
return -1;
}
//设置丢弃 avi 中的无效数据(如:size == 0)
ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
//如果是音频流格式的数据,对大结构体音频相关的一些数据初始化
switch (codecCtx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
is->audio_st = ic->streams[stream_index];
is->audio_buf_size = 0;
is->audio_buf_index = 0;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
break;
default:
break;
}
return 0;
}
//解码视频
int video_thread(void *arg)
{
VideoState *is = (VideoState *) arg;
AVPacket pkt1, *packet = &pkt1;
int ret, got_picture, numBytes;
double video_pts = 0; //当前视频的pts
double audio_pts = 0; //音频pts
///解码视频相关
AVFrame *pFrame, *pFrameRGB;
uint8_t *out_buffer_rgb; //解码后的rgb数据
struct SwsContext *img_convert_ctx; //用于解码后的视频格式转换
AVCodecContext *pCodecCtx = is->video_st->codec; //视频解码器
pFrame = av_frame_alloc();
pFrameRGB = av_frame_alloc();
///这里我们改成了 将解码后的YUV数据转换成RGB32
img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,
pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height,
PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL);
//计算这个格式的图片,需要多少字节来存储
numBytes = avpicture_get_size(PIX_FMT_RGB32, pCodecCtx->width,pCodecCtx->height);
//申请空间
out_buffer_rgb = (uint8_t *) av_malloc(numBytes * sizeof(uint8_t));
//前面的av_frame_alloc函数,只是为这个AVFrame结构体分配了内存,
//这里把av_malloc得到的内存和AVFrame关联起来。
//当然,其还会设置AVFrame的其他成员
avpicture_fill((AVPicture *) pFrameRGB, out_buffer_rgb, PIX_FMT_RGB32,
pCodecCtx->width, pCodecCtx->height);
while(1)
{
if (is->quit)
{qDebug()<<__FUNCTION__<<"quit!";
packet_queue_flush(&is->videoq); //清空队列
break;
}
if (is->isPause == true) //判断暂停
{
SDL_Delay(10);
continue;
}
//获取一帧
if (packet_queue_get(&is->videoq, packet, 0) <= 0)
{
if (is->readFinished)
{//队列里面没有数据了且读取完毕了
break;
}
else
{
SDL_Delay(1); //队列只是暂时没有数据而已
continue;
}
}
//收到这个数据 说明刚刚执行过跳转 现在需要把解码器的数据 清除一下
if(strcmp((char*)packet->data,FLUSH_DATA) == 0)
{
avcodec_flush_buffers(is->video_st->codec);
av_free_packet(packet);
continue;
}
//packet解码到frame
ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture,packet);
if (ret < 0) {
qDebug()<<"decode error.\n";
av_free_packet(packet);
continue;
}
//获取pts
if (packet->dts == AV_NOPTS_VALUE && pFrame->opaque&& *(uint64_t*) pFrame->opaque != AV_NOPTS_VALUE)
{
video_pts = *(uint64_t *) pFrame->opaque;
}
else if (packet->dts != AV_NOPTS_VALUE)
{
video_pts = packet->dts;
}
else
{
video_pts = 0;
}
//pts*time_base得到时间
video_pts *= av_q2d(is->video_st->time_base);
//同步音频
video_pts = synchronize_video(is, pFrame, video_pts);
if (is->seek_flag_video)
{
//发生了跳转 则跳过关键帧到目的时间的这几帧
if (video_pts < is->seek_time)
{
av_free_packet(packet);
continue;
}
else
{
is->seek_flag_video = 0;
}
}
//循环判断是否满足同步
while(1)
{
if (is->quit)
{
break;
}
if (is->readFinished && is->audioq.size == 0)
{//读取完了 且音频数据也播放完了 就剩下视频数据了 直接显示出来了 不用同步了
break;
}
audio_pts = is->audio_clock;
//主要是 跳转的时候 我们把video_clock设置成0了
//因此这里需要更新video_pts
//否则当从后面跳转到前面的时候 会卡在这里
video_pts = is->video_clock;
//满足同步
if (video_pts <= audio_pts) break;
//不满足,等待音频
int delayTime = (video_pts - audio_pts) * 1000;
delayTime = delayTime > 5 ? 5:delayTime;
if (!is->isNeedPause)
SDL_Delay(delayTime);
}
if (got_picture) {
sws_scale(img_convert_ctx,
(uint8_t const * const *) pFrame->data,
pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data,
pFrameRGB->linesize);
//把这个RGB数据 用QImage加载
QImage tmpImg((uchar *)out_buffer_rgb,pCodecCtx->width,pCodecCtx->height,QImage::Format_RGB32);
QImage image = tmpImg.convertToFormat(QImage::Format_RGB888,Qt::NoAlpha); //去掉透明的部分 有些奇葩的视频会透明
//播放视频
is->player->disPlayVideo(image); //调用激发信号的函数
if (is->isNeedPause)
{
is->isPause = true;
is->isNeedPause = false;
}
}
av_free_packet(packet);
}
//收尾工作
av_free(pFrame);
av_free(pFrameRGB);
av_free(out_buffer_rgb);
sws_freeContext(img_convert_ctx);
if (!is->quit)
{
is->quit = true;
}
is->videoThreadFinished = true;
qDebug()<<__FUNCTION__<<"finished!";
return 0;
}
//构造方法
VideoPlayer_Thread::VideoPlayer_Thread()
{
// mVideoState.readThreadFinished = true;
// mVideoState.videoThreadFinished = true;
memset(&mVideoState,0,sizeof(VideoState)); //为了安全起见 先将结构体的数据初始化成0了
mVideoWidget = NULL;
mPlayerState = Stop;
mAudioID = 0;
mIsMute = false;
mVolume = 1;
}
VideoPlayer_Thread::~VideoPlayer_Thread()
{
///关闭SDL音频播放设备
qDebug()<<__FUNCTION__<<"111...";
if (mAudioID != 0)
{
SDL_LockAudioDevice(mAudioID);
SDL_CloseAudioDevice(mAudioID);
SDL_UnlockAudioDevice(mAudioID);
mAudioID = 0;
}
deInit();
qDebug()<<__FUNCTION__<<"222...";
}
void VideoPlayer_Thread::deInit()
{
if (mVideoState.swr_ctx != NULL)
{
swr_free(&mVideoState.swr_ctx);
mVideoState.swr_ctx = NULL;
}
if (mVideoState.audio_frame!= NULL) {
avcodec_free_frame(&mVideoState.audio_frame);
mVideoState.audio_frame = NULL;
}
}
//设置播放文件,启动线程
bool VideoPlayer_Thread::setFileName(QString path)
{
if (mPlayerState != Stop)
{
return false;
}
mFileName = path;
memset(&mVideoState,0,sizeof(VideoState)); //为了安全起见 先将结构体的数据初始化成0了
this->start(); //启动线程
return true;
}
bool VideoPlayer_Thread::replay()
{
while (this->isRunning())
{
SDL_Delay(5);
}
if (mPlayerState != Stop)
{
return false;
}
// memset(&mVideoState,0,sizeof(VideoState)); //为了安全起见 先将结构体的数据初始化成0了
this->start(); //启动线程
return true;
}
bool VideoPlayer_Thread::play()
{
mVideoState.isNeedPause = false;
mVideoState.isPause = false;
if (mPlayerState != Pause)
{
return false;
}
mPlayerState = Playing;
emit sig_StateChanged(Playing);
return true;
}
bool VideoPlayer_Thread::pause()
{
mVideoState.isPause = true;
if (mPlayerState != Playing)
{
return false;
}
mPlayerState = Pause;
emit sig_StateChanged(Pause);
return true;
}
bool VideoPlayer_Thread::stop(bool isWait)
{
if (mPlayerState == Stop)
{
return false;
}
mPlayerState = Stop;
mVideoState.quit = true;
if (isWait)
{
while(!mVideoState.readThreadFinished)
{
SDL_Delay(3);
}
}
return true;
}
//跳转
void VideoPlayer_Thread::seek(int64_t pos)
{
if(!mVideoState.seek_req)
{
mVideoState.seek_pos = pos;
//跳转标志(0或1)
mVideoState.seek_req = 1;
}
}
//设置音量
void VideoPlayer_Thread::setVolume(float value)
{
mVolume = value;
mVideoState.mVolume = value;
}
double VideoPlayer_Thread::getCurrentTime()
{
return mVideoState.audio_clock;
}
int64_t VideoPlayer_Thread::getTotalTime()
{
return mVideoState.ic->duration;
}
void VideoPlayer_Thread::disPlayVideo(QImage img)
{
emit sig_GetOneFrame(img); //发送信号
}
//设置容器和信号
void VideoPlayer_Thread::setVideoWidget(VideoPlayer_ShowVideoWidget*widget)
{
mVideoWidget = widget;
connect(this,SIGNAL(sig_GetOneFrame(QImage)),mVideoWidget,SLOT(slotGetOneFrame(QImage)));
}
//打开SDL
int VideoPlayer_Thread::openSDL()
{
VideoState *is = &mVideoState;
SDL_AudioSpec wanted_spec, spec;
int64_t wanted_channel_layout = 0;
int wanted_nb_channels = 2;
//采样率
int samplerate = 44100;
/* SDL支持的声道数为 1, 2, 4, 6 */
// /* 后面我们会使用这个数组来纠正不支持的声道数目 */
// const int next_nb_channels[] = { 0, 0, 1, 6, 2, 6, 4, 6 };
if (!wanted_channel_layout
|| wanted_nb_channels
!= av_get_channel_layout_nb_channels(
wanted_channel_layout)) {
wanted_channel_layout = av_get_default_channel_layout(
wanted_nb_channels);
wanted_channel_layout &= ~AV_CH_LAYOUT_STEREO_DOWNMIX;
}
wanted_spec.channels = av_get_channel_layout_nb_channels(
wanted_channel_layout);
//采样率
wanted_spec.freq = samplerate;
if (wanted_spec.freq <= 0 || wanted_spec.channels <= 0) {
//fprintf(stderr,"Invalid sample rate or channel count!\n");
return -1;
}
wanted_spec.format = AUDIO_S16SYS; // 音频数据的格式
wanted_spec.silence = 0; // 0指示静音
wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE; // 自定义SDL缓冲区大小
//我们开始播放音频时,SDL将不断调用这个回调函数,并要求它填充一定数量的字节的音频缓冲区
wanted_spec.callback = audio_callback;
wanted_spec.userdata = is; // 传给上面回调函数的外带数据
int num = SDL_GetNumAudioDevices(0);
for (int i=0;i<num;i++)
{
//打开音频
mAudioID = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(i,0), false, &wanted_spec, &spec,0);
if (mAudioID > 0)
{
break;
}
}
/* 检查实际使用的配置(保存在spec,由SDL_OpenAudio()填充) */
if (spec.format != AUDIO_S16SYS) {
qDebug()<<"SDL advised audio format %d is not supported!"<<spec.format;
return -1;
}
if (spec.channels != wanted_spec.channels) {
wanted_channel_layout = av_get_default_channel_layout(spec.channels);
if (!wanted_channel_layout) {
fprintf(stderr,"SDL advised channel count %d is not supported!\n",spec.channels);
return -1;
}
}
is->audio_hw_buf_size = spec.size;
/* 把设置好的参数保存到大结构中 */
is->audio_src_fmt = is->audio_tgt_fmt = AV_SAMPLE_FMT_S16;
is->audio_src_freq = is->audio_tgt_freq = spec.freq;
is->audio_src_channel_layout = is->audio_tgt_channel_layout =
wanted_channel_layout;
is->audio_src_channels = is->audio_tgt_channels = spec.channels;
is->audio_buf_size = 0;
is->audio_buf_index = 0;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
return 0;
}
void VideoPlayer_Thread::closeSDL()
{
if (mAudioID > 0)
{
SDL_CloseAudioDevice(mAudioID);
}
mAudioID = -1;
}
void VideoPlayer_Thread::run()
{
char file_path[1280] = {0};
strcpy(file_path,mFileName.toUtf8().data());
memset(&mVideoState,0,sizeof(VideoState)); //为了安全起见 先将结构体的数据初始化成0了
//设置静音
mVideoState.isMute = mIsMute;
//音量
mVideoState.mVolume = mVolume;
VideoState *is = &mVideoState;
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
AVCodecContext *aCodecCtx;
AVCodec *aCodec;
int audioStream ,videoStream, i;
//Allocate an AVFormatContext.
pFormatCtx = avformat_alloc_context();
if (avformat_open_input(&pFormatCtx, file_path, NULL, NULL) != 0) {
printf("can't open the file. \n");
return;
}
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
printf("Could't find stream infomation.\n");
return;
}
videoStream = -1;
audioStream = -1;
//循环查找视频中包含的流信息,音频流和视频流
for (i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoStream = i;
}
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO && audioStream < 0)
{
audioStream = i;
}
}
//如果videoStream为-1 说明没有找到视频流
if (videoStream == -1) {
printf("Didn't find a video stream.\n");
return;
}
//audioStream为-1 说明没有找到音频流
if (audioStream == -1) {
printf("Didn't find a audio stream.\n");
return;
}
is->ic = pFormatCtx;
is->videoStream = videoStream;
is->audioStream = audioStream;
emit sig_TotalTimeChanged(getTotalTime());
if (audioStream >= 0) {
/* 所有设置SDL音频流信息的步骤都在这个函数里完成 */
audio_stream_component_open(&mVideoState, audioStream);
}
///查找音频解码器
aCodecCtx = pFormatCtx->streams[audioStream]->codec;
aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
if (aCodec == NULL) {
printf("ACodec not found.\n");
return;
}
///打开音频解码器
if (avcodec_open2(aCodecCtx, aCodec, NULL) < 0) {
printf("Could not open audio codec.\n");
return;
}
is->audio_st = pFormatCtx->streams[audioStream];
///查找视频解码器
pCodecCtx = pFormatCtx->streams[videoStream]->codec;
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
printf("PCodec not found.\n");
return;
}
///打开视频解码器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
printf("Could not open video codec.\n");
return;
}
is->video_st = pFormatCtx->streams[videoStream];
//初始化队列
packet_queue_init(&mVideoState.audioq);
packet_queue_init(&mVideoState.videoq);
///创建一个线程专门用来解码视频
is->video_tid = SDL_CreateThread(video_thread, "video_thread", &mVideoState);
is->player = this;
AVPacket *packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet 用来存放读取的视频
qDebug()<<__FUNCTION__<<is->quit;
mPlayerState = Playing;
emit sig_StateChanged(Playing);
//打开SDL
openSDL();
SDL_LockAudioDevice(mAudioID);
//0播放,1暂停
SDL_PauseAudioDevice(mAudioID,0);
SDL_UnlockAudioDevice(mAudioID);
while (1)
{
if (is->quit)
{
//停止播放了
break;
}
//跳转标志
if (is->seek_req)
{
int stream_index = -1;
int64_t seek_target = is->seek_pos;
if (is->videoStream >= 0)
stream_index = is->videoStream;
else if (is->audioStream >= 0)
stream_index = is->audioStream;
AVRational aVRational = {1, AV_TIME_BASE};
if (stream_index >= 0) {
seek_target = av_rescale_q(seek_target, aVRational,
pFormatCtx->streams[stream_index]->time_base);
}
//跳转函数
//stream_index:基本流索引,表示当前的seek是针对哪个基本流,比如视频或者音频等等。
//timestamp:要seek的时间点,以time_base或者AV_TIME_BASE为单位。
if (av_seek_frame(is->ic, stream_index, seek_target, AVSEEK_FLAG_BACKWARD) < 0) {
fprintf(stderr, "%s: error while seeking\n",is->ic->filename);
} else {
if (is->audioStream >= 0) {
AVPacket *packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet
av_new_packet(packet, 10);
strcpy((char*)packet->data,FLUSH_DATA);
packet_queue_flush(&is->audioq); //清除队列
packet_queue_put(&is->audioq, packet); //往队列中存入用来清除的包
}
if (is->videoStream >= 0) {
AVPacket *packet = (AVPacket *) malloc(sizeof(AVPacket)); //分配一个packet
av_new_packet(packet, 10);
strcpy((char*)packet->data,FLUSH_DATA);
packet_queue_flush(&is->videoq); //清除队列
packet_queue_put(&is->videoq, packet); //往队列中存入用来清除的包
is->video_clock = 0;
}
}
is->seek_req = 0;
is->seek_time = is->seek_pos / 1000000.0;
is->seek_flag_audio = 1;
is->seek_flag_video = 1;
if (is->isPause)
{
is->isNeedPause = true;
is->isPause = false;
}
}
//这里做了个限制 当队列里面的数据超过某个大小的时候 就暂停读取 防止一下子就把视频读完了,导致的空间分配不足
/* 这里audioq.size是指队列中的所有数据包带的音频数据的总量或者视频数据总量,并不是包的数量 */
//这个值可以稍微写大一些
// qDebug()<<__FUNCTION__<<is->audioq.size<<MAX_AUDIO_SIZE<<is->videoq.size<<MAX_VIDEO_SIZE;
if (is->audioq.size > MAX_AUDIO_SIZE || is->videoq.size > MAX_VIDEO_SIZE) {
SDL_Delay(10);
continue;
}
if (is->isPause == true)
{
SDL_Delay(10);
continue;
}
//读取数据到packet
if (av_read_frame(pFormatCtx, packet) < 0)
{
is->readFinished = true;
if (is->quit)
{
break; //解码线程也执行完了 可以退出了
}
SDL_Delay(10);
continue;
}
//入队
if (packet->stream_index == videoStream)
{
packet_queue_put(&is->videoq, packet);
//这里我们将数据存入队列 因此不调用 av_free_packet 释放
}
else if( packet->stream_index == audioStream )
{
packet_queue_put(&is->audioq, packet);
//这里我们将数据存入队列 因此不调用 av_free_packet 释放
}
else
{
// Free the packet that was allocated by av_read_frame
av_free_packet(packet);
}
}
///文件读取结束 跳出循环的情况
///等待播放完毕
while (!is->quit) {
SDL_Delay(100);
}
if (mPlayerState != Stop) //不是外部调用的stop 是正常播放结束
{
stop();
}
//下面是一些收尾工作
SDL_LockAudioDevice(mAudioID);
SDL_PauseAudioDevice(mAudioID,1);
SDL_UnlockAudioDevice(mAudioID);
closeSDL();
qDebug()<<__FUNCTION__<<"444";
while(!mVideoState.videoThreadFinished)
{
// qDebug()<<__FUNCTION__<<"videoThreadFinished"<<mVideoState.videoThreadFinished;
msleep(10);
} //确保视频线程结束后 再销毁队列
qDebug()<<__FUNCTION__<<"555";
avcodec_close(aCodecCtx);
avcodec_close(pCodecCtx);
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
free(packet);
packet_queue_deinit(&mVideoState.videoq);
packet_queue_deinit(&mVideoState.audioq);
is->readThreadFinished = true;
emit sig_StateChanged(Stop);
qDebug()<<__FUNCTION__<<"finished!";
// SDL_Quit();
}
{{ cmt.username }}
{{ cmt.content }}
{{ cmt.commentDate | formatDate('YYYY.MM.DD hh:mm') }}