FFmpeg中H264 解码 &FFmpeg中H264 编码
步骤:找到解码器 -> 打开解码器-> 解码
- AVCodec 编码器结构体
- AVCodecContext编码器上下文
- AVFrame解码后的帧
av_frame_alloc/av_frame_free() //创建frame /释放frame
avcodec_alloc_context3() //分配编解码器avcodec 上下文
avcodec_free_context3() //释放编解码器avcodec 上下文
avcodec_find_decoder() //查找解码器
avcodec_open2() //打开解码器
avcodec_decoder_video2() //解码(将解码的数据变成未压缩的数据)
avcodec_find_encoder_by_name //查找编码器-通过名字
avcodec_open2() //设置编码参数,并打开编解码器(同解码)
avcodec_encode_video2() //编码
程序内容:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
#include <libavutil/imgutils.h>
int main(int argc, char **argv)
{
const char *filename, *codec_name;
const AVCodec *codec;
AVCodecContext *c= NULL;
int i, ret, x, y, got_output;
FILE *f;
AVFrame *frame;
AVPacket pkt;
/* */
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
if (argc <= 2) {
fprintf(stderr, "Usage: %s <output file> <codec name>\n", argv[0]);
exit(0);
}
filename = argv[1];
codec_name = argv[2];
avcodec_register_all();
/* 通过输入的解码器名字找到对应的code解码器 */
codec = avcodec_find_encoder_by_name(codec_name);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
/*通过codec 创建codec 的上下文*/
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
/* 设置码率 */
c->bit_rate = 400000;
/* 视频宽/高 */
c->width = 352;
c->height = 288;
/* 时间基(1/25) */
c->time_base = (AVRational){1, 25};
/* 帧率(一秒钟25)*/
c->framerate = (AVRational){25, 1};
/* 10帧出现一个关键帧(值越大,码率越小,关键帧丢后需要等待的时间较长)*/
c->gop_size = 10;
/* 设置B帧参数()*/
c->max_b_frames = 1;
/* 设置图像的编码格式YUV420P*/
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec->id == AV_CODEC_ID_H264){
/* 如果编码器是h264--采用压缩速度慢的,视频质量较高*/
av_opt_set(c->priv_data, "preset", "slow", 0);
}
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
/**/
frame->format = c->pix_fmt;
frame->width = c->width;
frame->height = c->height;
ret = av_frame_get_buffer(frame, 32);
if (ret < 0) {
fprintf(stderr, "Could not allocate the video frame data\n");
exit(1);
}
/* 此处人工造了一个一秒的YUV数据 */
for (i = 0; i < 25; i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
/* */
fflush(stdout);
/* make sure the frame data is writable */
ret = av_frame_make_writable(frame);
if (ret < 0)
exit(1);
/* prepare a dummy image */
/* Y */
for (y = 0; y < c->height; y++) {
for (x = 0; x < c->width; x++) {
frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
}
}
/* Cb and Cr */
for (y = 0; y < c->height/2; y++) {
for (x = 0; x < c->width/2; x++) {
frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
}
}
frame->pts = i;
/* encode the image */
ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
/* 如果唯一,则写入文件*/
if (got_output) {
printf("Write frame %3d (size=%5d)\n", i, pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_packet_unref(&pkt);
}
}
/* get the delayed frames */
for (got_output = 1; got_output; i++) {
fflush(stdout);
ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
printf("Write frame %3d (size=%5d)\n", i, pkt.size);
fwrite(pkt.data, 1, pkt.size, f);
av_packet_unref(&pkt);
}
}
/* add sequence end code to have a real MPEG file */
fwrite(endcode, 1, sizeof(endcode), f);
fclose(f);
avcodec_free_context(&c);
av_frame_free(&frame);
return 0;
}
使用命令编译:
clang -g -o encode_video encode_video.c pkg-config --libs libavcodec
运行程序:
./encode_video output1.h264 libx264
ffplay output1.h264
FFmpeg视频转图片实例
程序内容:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
int main (int argc, char *argv[]){
int ret;
const char *filename, *outfilename;
AVFormatContext *fmt_ctx = NULL;
const AVCodec *codec;
AVCodecContext *codec_context = NULL;
AVStream *stream = NULL;
int stream_index;
int frame_count;
AVFrame *frame;
struct SwsContext *img_convert_ctx;
AVPacket *av_pkt;
if (argc <=2 ){
fprintf(stderr,"input less two params");
exit(0);
}
filename = argv[1];
outfilename = argv[2];
av_register_all();
if (avformat_open_input(&fmt_ctx,filename,NULL,NULL)<0){
fprintf(stderr,"could not open file %s",filename);
exit(1);
}
if(avformat_find_stream_info(fmt_ctx,NULL)<0){
fprintf(stderr,"Could not find stream information n");
exit(1);
}
/*打印视频信息*/
av_dump_format(fmt_ctx,0,filename,0);
av_init_packet(&av_pkt);
ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
if (ret<0){
fprintf(stderr,"Could not find %s stream in input file %s",av_get_media_type_string(AVMEDIA_TYPE_VIDEO),filename);
return ret;
}
stream_index = ret;
stream = fmt_ctx->streams[stream_index];
/* codecpar->编解码参数集合*/
codec = avcodec_find_decoder(stream->codecpar->codec_id);
if(!codec){
fprintf(stderr,"Fail to find %s codec\n",av_get_media_type_string(AVDEMID_TYPE_VIDEO));
return AVERROR(EINVAL);
}
codec_context = avcodec_alloc_context3(NULL);
if(!codec_context){
fprintf(stderr,"Cound not allocate video codec context \n");
/* exit(1)表示异常退出,exit(0)表示正常退出*/
exit(1);
}
/*拷贝流的参数到 avcode context */
if((ret = avcodec_parameters_to_context(codec_context,stream->codecpar))<0){
fprintf(stderr,"Failed to copy %s codec parameters to decoder context \n",av_get_media_type_string(AVMEDIA_TYPE_VIDEO));
return ret;
}
if (avcodec_open2(codec_context,codec, NULL)<0){
fprintf(sdderr,"Could not open codec");
exit(1);
}
img_convert_ctx = sws_getContext( codec_context->width,codec_context->height,
codec_context->pix_fmt,
codec_context->width,codec_context->height,
AV_PIX_FMT_RGB24,
SWS_BICUBIC,NULL,NULL,NULL);
if (img_convert_ctx == NULL){
fprintf(stderr,"cannot initialize the conversion context \n");
exit(1);
}
frame = av_frame_alloc();
if(!frame){
fprintf(stderr,"fail allocate video frame \n");
exit(1);
}
while(av_read_frame(fmt_ctx,&av_pkt)>=0){
if(av_pkt.stream_index == stream_index){
if(decode_write_frame(outfilename, codec_context, img_convert_ctx, frame, &frame_count, &av_pkt,0)<0 ){
exit(1);
}
}
av_packet_unref(&av_pkt);
}
return 0;
}
static int decode_write_frame(const char *outfilename, AVCodecContext *avctx, struct SwsContext *img_convert_ctx, AVFrame *frame, int *frame_count, AVPacket *pkt, int last){
int len ,got_frame;
char buf[1024];
len = avcodec_decode_video2(avctx, frame, &got_frame, pkt);
if(len<0){
fprintf(stderr,"error while decoding frame %d \n",*frame_count);
return len;
}
/* 如果got_frame >0 说明解码成功*/
if(got_frame){
fprintf(stderr,"saving %s frame %3d\n",last?"last":"", *frame_count);
/**/
fflush(stdout);
snprintf(buf,sizeof(buf),"%s -%d.bmp",outfilename,*frame_count);
saveBMP(img_convert_ctx,frame,buf);
(*frame_count)++;
}
if(pkt->data) {
pkt->size -= len;
pkt->data += len;
}
return 0;
}
使用命令编译:
运行程序:
FFmpeg中的AAC 编码&FFmpeg中的 AAC 解码
程序内容:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/frame.h>
#include <libavutil/samplefmt.h>
/* check that a given sample format is supported by the encoder */
static int check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt)
{
const enum AVSampleFormat *p = codec->sample_fmts;
while (*p != AV_SAMPLE_FMT_NONE) {
if (*p == sample_fmt)
return 1;
p++;
}
return 0;
}
/* just pick the highest supported samplerate */
static int select_sample_rate(const AVCodec *codec)
{
const int *p;
int best_samplerate = 0;
if (!codec->supported_samplerates)
return 44100;
p = codec->supported_samplerates;
while (*p) {
if (!best_samplerate || abs(44100 - *p) < abs(44100 - best_samplerate))
best_samplerate = *p;
p++;
}
return best_samplerate;
}
/* select layout with the highest channel count */
static int select_channel_layout(const AVCodec *codec)
{
const uint64_t *p;
uint64_t best_ch_layout = 0;
int best_nb_channels = 0;
if (!codec->channel_layouts)
return AV_CH_LAYOUT_STEREO;
p = codec->channel_layouts;
while (*p) {
int nb_channels = av_get_channel_layout_nb_channels(*p);
if (nb_channels > best_nb_channels) {
best_ch_layout = *p;
best_nb_channels = nb_channels;
}
p++;
}
return best_ch_layout;
}
int main(int argc, char **argv)
{
const char *filename;
const AVCodec *codec;
AVCodecContext *c= NULL;
AVFrame *frame;
AVPacket pkt;
int i, j, k, ret, got_output;
FILE *f;
uint16_t *samples;
float t, tincr;
if (argc <= 1) {
fprintf(stderr, "Usage: %s <output file>\n", argv[0]);
return 0;
}
filename = argv[1];
avcodec_register_all();
/* find the MP2 encoder */
codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate audio codec context\n");
exit(1);
}
/* put sample parameters */
c->bit_rate = 64000;
/* check that the encoder supports s16 pcm input */
c->sample_fmt = AV_SAMPLE_FMT_S16;
if (!check_sample_fmt(codec, c->sample_fmt)) {
fprintf(stderr, "Encoder does not support sample format %s",
av_get_sample_fmt_name(c->sample_fmt));
exit(1);
}
/* 设置采样率/声道类型/通道个数 */
c->sample_rate = select_sample_rate(codec);
c->channel_layout = select_channel_layout(codec);
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
/* 打开编码器 */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
/* frame containing input raw audio */
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate audio frame\n");
exit(1);
}
frame->nb_samples = c->frame_size;
frame->format = c->sample_fmt;
frame->channel_layout = c->channel_layout;
/* allocate the data buffers */
ret = av_frame_get_buffer(frame, 0);
if (ret < 0) {
fprintf(stderr, "Could not allocate audio data buffers\n");
exit(1);
}
/* 伪造假数据(实际身影是麦克风采集获取) */
t = 0;
tincr = 2 * M_PI * 440.0 / c->sample_rate;
for (i = 0; i < 200; i++) {
av_init_packet(&pkt);
pkt.data = NULL; // packet data will be allocated by the encoder
pkt.size = 0;
/* make sure the frame is writable -- makes a copy if the encoder
* kept a reference internally */
ret = av_frame_make_writable(frame);
if (ret < 0)
exit(1);
samples = (uint16_t*)frame->data[0];
for (j = 0; j < c->frame_size; j++) {
samples[2*j] = (int)(sin(t) * 10000);
for (k = 1; k < c->channels; k++)
samples[2*j + k] = samples[2*j];
t += tincr;
}
/* encode the samples */
ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding audio frame\n");
exit(1);
}
if (got_output) {
fwrite(pkt.data, 1, pkt.size, f);
av_packet_unref(&pkt);
}
}
/* get the delayed frames */
for (got_output = 1; got_output; i++) {
ret = avcodec_encode_audio2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
/* 有时是多次循环才会生成一个packet,通过got_output 参数获取是否生成了一个包数据(从而写入文件)*/
if (got_output) {
fwrite(pkt.data, 1, pkt.size, f);
av_packet_unref(&pkt);
}
}
fclose(f);
av_frame_free(&frame);
avcodec_free_context(&c);
return 0;
}
使用命令编译:
clang -g -o encode_audio encode_audio.c pkg-config --libs libavcodec
运行程序:
./encode_audio 2.aac
SDL窗口渲染(查看之前笔记)
FFmpeg实现PCM 播放器
前提该要:之前有将mp4 文件提取出pcm 音频数据的命令如下
ffmpeg -i input.mp4 -vn -ar 44100 -ac 2 -f s16le out.pcm
程序内容:
#include <stdio.h>
#include <SDL.h>
/* 4M空间*/
#define BLOCK_SIZE 4096000
static Uint8 *audio_buf = NULL;
static Uint8 *audio_pos = NULL;
static size_t buffer_len = 0;
/*
udata = 需要传回的参数
stream = 需要播放的buffer地址
len = 需要的长度
*/
void read_audio_data(void *udata, Uint8 *stream, int len){
if(buffer_len == 0){
return;
}
/*清除缓冲区数据 设为0*/
SDL_memset(stream, 0, len);
/* 判断缓冲区 buffer_len 和传进来的数据长度len 进行对比,不大于缓冲区长度即可(防止越界) */
len = (len < buffer_len) ? len : buffer_len;
/*
stream =
audio_pos = 数据起始位
len = 数据长度
SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME);
/*audio_pos 位置移动 len 长度(移动播放的数据长度)*/
audio_pos += len;
/*buffer_len 减少 len 长度(消耗掉的数据长度)*/
buffer_len -= len;
}
int main(int argc, char *argv[])
{
int ret = -1;
FILE *audio_fd = NULL;
SDL_AudioSpec spec;
char *path = "./test.pcm";
//SDL initialize
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)){
fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
return ret;
}
//open pcm file
audio_fd = fopen(path, "r");
if(!audio_fd){
fprintf(stderr, "Failed to open pcm file!\n");
goto __FAIL;
}
//alloc memory for audio
audio_buf = (Uint8*)malloc(BLOCK_SIZE);
if(!audio_buf){
goto __FAIL;
}
/*
freq = 采样率
format = 采样格式
channels = 通道数
silence =
samples =
callback = 回调函数
userdata = 回调参数
*/
spec.freq = 44100;;
spec.format = AUDIO_S16SYS;
spec.channels = 2;
spec.silence = 0;
spec.samples = 2048;;
spec.callback = read_audio_data;;
spec.userdata = NULL;
//spec 是常用的音频参数(只有返回0 的时候才表示成功)
if(SDL_OpenAudio(&spec, NULL)){
fprintf(stderr, "Failed to open audio device, %s\n", SDL_GetError());
goto __FAIL;
}
//play audio (0 表示播放、1表示暂停)
SDL_PauseAudio(0);
do{
//read data from pcm file
/* 读取BLOCK_Size大小的数据到audio_buf */
buffer_len = fread(audio_buf, 1, BLOCK_SIZE, audio_fd);
fprintf(stderr, "block size is %zu\n", buffer_len);
audio_pos = audio_buf;
//the main thread wait for a moment
/* 让audio_buf 消耗,消耗完了,从新堵一个BLOCK_SIZE 大小的数据*/
while(audio_pos < (audio_buf + buffer_len)) {
/*延迟执行 1ms */
SDL_Delay(1);
}
}while(buffer_len !=0);
//关闭音频设备
SDL_CloseAudio();
ret = 0;
__FAIL:
//release some resources
if(audio_buf){
free(audio_buf);
}
if(audio_fd){
fclose(audio_fd);
}
//quit SDL
SDL_Quit();
return ret;
}
使用命令编译: clang -g -o pcm_player pcm_player.c `pkg-config --cflags --libs sdl2`
运行程序: ./pcm_player
FFmpeg实现最简单的播放器
程序内容:
#include <SDL.h>
#include <stdio.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
// compatibility with newer API
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif
int main(int argc, char *argv[]) {
int ret = -1;
AVFormatContext *pFormatCtx = NULL; //for opening multi-media file
int i, videoStream;
AVCodecContext *pCodecCtxOrig = NULL; //codec context
AVCodecContext *pCodecCtx = NULL;
/* 图像裁剪的上下文*/
struct SwsContext *sws_ctx = NULL;
AVCodec *pCodec = NULL; // the codecer
AVFrame *pFrame = NULL;
AVPacket packet;
int frameFinished;
float aspect_ratio;
/* 存放YUV数据的AVPicture 结构体*/
AVPicture *pict = NULL;
/*渲染大小*/
SDL_Rect rect;
Uint32 pixformat;
/* 渲染窗口*/
SDL_Window *win = NULL;
SDL_Renderer *renderer = NULL;
SDL_Texture *texture = NULL;
//set defualt size of window
int w_width = 640;
int w_height = 480;
if(argc < 2) {
//fprintf(stderr, "Usage: command <file>\n");
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Usage: command <file>");
return ret;
}
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
//fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not initialize SDL - %s\n", SDL_GetError());
return ret;
}
//Register all formats and codecs
av_register_all();
// Open video file
if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open video file!");
goto __FAIL; // Couldn't open file
}
// Retrieve stream information
if(avformat_find_stream_info(pFormatCtx, NULL)<0){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to find stream infomation!");
goto __FAIL; // Couldn't find stream information
}
// Dump information about file onto standard error
av_dump_format(pFormatCtx, 0, argv[1], 0);
// Find the first video stream
videoStream=-1;
for(i=0; i<pFormatCtx->nb_streams; i++) {
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
videoStream=i;
break;
}
}
if(videoStream==-1){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Din't find a video stream!");
goto __FAIL;// Didn't find a video stream
}
// Get a pointer to the codec context for the video stream
pCodecCtxOrig=pFormatCtx->streams[videoStream]->codec;
// Find the decoder for the video stream
pCodec=avcodec_find_decoder(pCodecCtxOrig->codec_id);
if(pCodec==NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unsupported codec!\n");
goto __FAIL; // Codec not found
}
// Copy context
pCodecCtx = avcodec_alloc_context3(pCodec);
if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't copy codec context");
goto __FAIL;// Error copying codec context
}
// Open codec
if(avcodec_open2(pCodecCtx, pCodec, NULL)<0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to open decoder!\n");
goto __FAIL; // Could not open codec
}
// Allocate video frame
pFrame=av_frame_alloc();
w_width = pCodecCtx->width;
w_height = pCodecCtx->height;
/* 创建SDL窗口
SDL_WINDOW_OPENGL 使用openGL
SDL_WINDOW_RESIZABLE 窗口可大可小
*/
win = SDL_CreateWindow( "Media Player",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
w_width, w_height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
if(!win){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create window by SDL");
goto __FAIL;
}
/* 创建渲染器*/
renderer = SDL_CreateRenderer(win, -1, 0);
if(!renderer){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to create Renderer by SDL");
goto __FAIL;
}
pixformat = SDL_PIXELFORMAT_IYUV;
/*
pixformat = 像素格式
SDL_TEXTUREACCESS_STREAMING = 纹理格式(不断更新的视频流) */
texture = SDL_CreateTexture(renderer,
pixformat,
SDL_TEXTUREACCESS_STREAMING,
w_width,
w_height);
// initialize SWS context for software scaling
/*
对图像进行裁剪(此处没有裁剪)
*/
sws_ctx = sws_getContext(pCodecCtx->width,
pCodecCtx->height,
pCodecCtx->pix_fmt,
pCodecCtx->width,
pCodecCtx->height,
AV_PIX_FMT_YUV420P,
SWS_BILINEAR,
NULL,
NULL,
NULL
);
pict = (AVPicture*)malloc(sizeof(AVPicture));
avpicture_alloc(pict,
AV_PIX_FMT_YUV420P,
pCodecCtx->width,
pCodecCtx->height);
// Read frames and save first five frames to disk
while(av_read_frame(pFormatCtx, &packet)>=0) {
// Is this a packet from the video stream?
if(packet.stream_index==videoStream) {
// Decode video frame
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
// Did we get a video frame?
if(frameFinished) {
// Convert the image into YUV format that SDL uses
sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
pFrame->linesize, 0, pCodecCtx->height,
pict->data, pict->linesize);
//
SDL_UpdateYUVTexture(texture, NULL,
pict->data[0], pict->linesize[0],
pict->data[1], pict->linesize[1],
pict->data[2], pict->linesize[2]);
// Set Size of Window
rect.x = 0;
rect.y = 0;
rect.w = pCodecCtx->width;
rect.h = pCodecCtx->height;
/**/
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, &rect);
SDL_RenderPresent(renderer);
}
}
// Free the packet that was allocated by av_read_frame
av_free_packet(&packet);
/*
SDL_Event event;
SDL_PollEvent(&event);
switch(event.type) {
case SDL_QUIT:
goto __QUIT;
break;
default:
break;
}
*/
}
__QUIT:
ret = 0;
__FAIL:
// Free the YUV frame
if(pFrame){
av_frame_free(&pFrame);
}
// Close the codec
if(pCodecCtx){
avcodec_close(pCodecCtx);
}
if(pCodecCtxOrig){
avcodec_close(pCodecCtxOrig);
}
// Close the video file
if(pFormatCtx){
avformat_close_input(&pFormatCtx);
}
if(pict){
avpicture_free(pict);
free(pict);
}
if(win){
SDL_DestroyWindow(win);
}
if(renderer){
SDL_DestroyRenderer(renderer);
}
if(texture){
SDL_DestroyTexture(texture);
}
SDL_Quit();
return ret;
}
使用命令编译:
clang -g -o player2 player2.c pkg-config --cflags --libs sdl2 libavformat libavutil libswscale
运行程序:
./player2 input.mp4
FFmpeg播放器多线程版
程序内容:
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <SDL.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
// compatibility with newer API
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)
#define av_frame_alloc avcodec_alloc_frame
#define av_frame_free avcodec_free_frame
#endif
#define SDL_AUDIO_BUFFER_SIZE 1024
#define MAX_AUDIO_FRAME_SIZE 192000 //channels(2) * data_size(2) * sample_rate(48000)
#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)
#define AV_SYNC_THRESHOLD 0.01
#define AV_NOSYNC_THRESHOLD 10.0
#define SAMPLE_CORRECTION_PERCENT_MAX 10
#define AUDIO_DIFF_AVG_NB 20
#define FF_REFRESH_EVENT (SDL_USEREVENT)
#define FF_QUIT_EVENT (SDL_USEREVENT + 1)
#define VIDEO_PICTURE_QUEUE_SIZE 1
#define DEFAULT_AV_SYNC_TYPE AV_SYNC_AUDIO_MASTER //AV_SYNC_VIDEO_MASTER
typedef struct PacketQueue {
AVPacketList *first_pkt, *last_pkt;
int nb_packets;
int size;
SDL_mutex *mutex;
SDL_cond *cond;
} PacketQueue;
typedef struct VideoPicture {
AVPicture *bmp;
int width, height; /* source height & width */
int allocated;
double pts;
} VideoPicture;
typedef struct VideoState {
//multi-media file
char filename[1024];
AVFormatContext *pFormatCtx;
int videoStream, audioStream;
//sync
int av_sync_type;
double external_clock; /* external clock base */
int64_t external_clock_time;
double audio_diff_cum; /* used for AV difference average computation */
double audio_diff_avg_coef;
double audio_diff_threshold;
int audio_diff_avg_count;
double audio_clock;
double frame_timer;
double frame_last_pts;
double frame_last_delay;
double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used)
int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts
//audio
AVStream *audio_st;
AVCodecContext *audio_ctx;
PacketQueue audioq;
uint8_t audio_buf[(MAX_AUDIO_FRAME_SIZE * 3) / 2];
unsigned int audio_buf_size;
unsigned int audio_buf_index;
AVFrame audio_frame;
AVPacket audio_pkt;
uint8_t *audio_pkt_data;
int audio_pkt_size;
int audio_hw_buf_size;
//video
AVStream *video_st;
AVCodecContext *video_ctx;
PacketQueue videoq;
struct SwsContext *video_sws_ctx;
struct SwrContext *audio_swr_ctx;
VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE];
int pictq_size, pictq_rindex, pictq_windex;
SDL_mutex *pictq_mutex;
SDL_cond *pictq_cond;
SDL_Thread *parse_tid;
SDL_Thread *video_tid;
int quit;
} VideoState;
SDL_mutex *text_mutex;
SDL_Window *win = NULL;
SDL_Renderer *renderer;
SDL_Texture *texture;
enum {
AV_SYNC_AUDIO_MASTER,
AV_SYNC_VIDEO_MASTER,
AV_SYNC_EXTERNAL_MASTER,
};
FILE *yuvfd = NULL;
FILE *audiofd = NULL;
/* Since we only have one decoding thread, the Big Struct
can be global in case we need it. */
VideoState *global_video_state;
void packet_queue_init(PacketQueue *q) {
memset(q, 0, sizeof(PacketQueue));
q->mutex = SDL_CreateMutex();
q->cond = SDL_CreateCond();
}
int packet_queue_put(PacketQueue *q, AVPacket *pkt) {
AVPacketList *pkt1;
if(av_dup_packet(pkt) < 0) {
return -1;
}
pkt1 = av_malloc(sizeof(AVPacketList));
if (!pkt1)
return -1;
pkt1->pkt = *pkt;
pkt1->next = NULL;
SDL_LockMutex(q->mutex);
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;
}
int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block)
{
AVPacketList *pkt1;
int ret;
SDL_LockMutex(q->mutex);
for(;;) {
if(global_video_state->quit) {
ret = -1;
break;
}
pkt1 = q->first_pkt;
if (pkt1) {
q->first_pkt = pkt1->next;
if (!q->first_pkt)
q->last_pkt = NULL;
q->nb_packets--;
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);
}
}
SDL_UnlockMutex(q->mutex);
return ret;
}
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_ctx->channels * 2;
if(is->audio_st) {
bytes_per_sec = is->audio_ctx->sample_rate * n;
}
if(bytes_per_sec) {
pts -= (double)hw_buf_size / bytes_per_sec;
}
return pts;
}
double get_video_clock(VideoState *is) {
double delta;
delta = (av_gettime() - is->video_current_pts_time) / 1000000.0;
return is->video_current_pts + delta;
}
double get_external_clock(VideoState *is) {
return av_gettime() / 1000000.0;
}
double get_master_clock(VideoState *is) {
if(is->av_sync_type == AV_SYNC_VIDEO_MASTER) {
return get_video_clock(is);
} else if(is->av_sync_type == AV_SYNC_AUDIO_MASTER) {
return get_audio_clock(is);
} else {
return get_external_clock(is);
}
}
/* Add or subtract samples to get a better sync, return new
audio buffer size */
int synchronize_audio(VideoState *is, short *samples,
int samples_size, double pts) {
int n;
double ref_clock;
n = 2 * is->audio_ctx->channels;
if(is->av_sync_type != AV_SYNC_AUDIO_MASTER) {
double diff, avg_diff;
int wanted_size, min_size, max_size /*, nb_samples */;
ref_clock = get_master_clock(is);
diff = get_audio_clock(is) - ref_clock;
if(diff < AV_NOSYNC_THRESHOLD) {
// accumulate the diffs
is->audio_diff_cum = diff + is->audio_diff_avg_coef
* is->audio_diff_cum;
if(is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) {
is->audio_diff_avg_count++;
} else {
avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef);
if(fabs(avg_diff) >= is->audio_diff_threshold) {
wanted_size = samples_size + ((int)(diff * is->audio_ctx->sample_rate) * n);
min_size = samples_size * ((100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100);
max_size = samples_size * ((100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100);
if(wanted_size < min_size) {
wanted_size = min_size;
} else if (wanted_size > max_size) {
wanted_size = max_size;
}
if(wanted_size < samples_size) {
/* remove samples */
samples_size = wanted_size;
} else if(wanted_size > samples_size) {
uint8_t *samples_end, *q;
int nb;
/* add samples by copying final sample*/
nb = (samples_size - wanted_size);
samples_end = (uint8_t *)samples + samples_size - n;
q = samples_end + n;
while(nb > 0) {
memcpy(q, samples_end, n);
q += n;
nb -= n;
}
samples_size = wanted_size;
}
}
}
} else {
/* difference is TOO big; reset diff stuff */
is->audio_diff_avg_count = 0;
is->audio_diff_cum = 0;
}
}
return samples_size;
}
int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) {
int len1, data_size = 0;
AVPacket *pkt = &is->audio_pkt;
double pts;
int n;
for(;;) {
while(is->audio_pkt_size > 0) {
int got_frame = 0;
len1 = avcodec_decode_audio4(is->audio_ctx, &is->audio_frame, &got_frame, pkt);
if(len1 < 0) {
/* if error, skip frame */
is->audio_pkt_size = 0;
break;
}
data_size = 0;
if(got_frame) {
/*
data_size = av_samples_get_buffer_size(NULL,
is->audio_ctx->channels,
is->audio_frame.nb_samples,
is->audio_ctx->sample_fmt,
1);
*/
data_size = 2 * is->audio_frame.nb_samples * 2;
assert(data_size <= buf_size);
swr_convert(is->audio_swr_ctx,
&audio_buf,
MAX_AUDIO_FRAME_SIZE*3/2,
(const uint8_t **)is->audio_frame.data,
is->audio_frame.nb_samples);
fwrite(audio_buf, 1, data_size, audiofd);
//memcpy(audio_buf, is->audio_frame.data[0], data_size);
}
is->audio_pkt_data += len1;
is->audio_pkt_size -= len1;
if(data_size <= 0) {
/* No data yet, get more frames */
continue;
}
pts = is->audio_clock;
*pts_ptr = pts;
n = 2 * is->audio_ctx->channels;
is->audio_clock += (double)data_size /
(double)(n * is->audio_ctx->sample_rate);
/* We have data, return it and come back for more later */
return data_size;
}
if(pkt->data)
av_free_packet(pkt);
if(is->quit) {
return -1;
}
/* next packet */
if(packet_queue_get(&is->audioq, pkt, 1) < 0) {
return -1;
}
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;
}
}
}
void audio_callback(void *userdata, Uint8 *stream, int len) {
VideoState *is = (VideoState *)userdata;
int len1, audio_size;
double pts;
SDL_memset(stream, 0, len);
while(len > 0) {
if(is->audio_buf_index >= is->audio_buf_size) {
/* We have already sent all our data; get more */
audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts);
if(audio_size < 0) {
/* If error, output silence */
is->audio_buf_size = 1024 * 2 * 2;
memset(is->audio_buf, 0, is->audio_buf_size);
} else {
audio_size = synchronize_audio(is, (int16_t *)is->audio_buf,
audio_size, pts);
is->audio_buf_size = audio_size;
}
is->audio_buf_index = 0;
}
len1 = is->audio_buf_size - is->audio_buf_index;
if(len1 > len)
len1 = len;
SDL_MixAudio(stream,(uint8_t *)is->audio_buf + is->audio_buf_index, len1, SDL_MIX_MAXVOLUME);
//memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1);
len -= len1;
stream += len1;
is->audio_buf_index += len1;
}
}
static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) {
SDL_Event event;
event.type = FF_REFRESH_EVENT;
event.user.data1 = opaque;
SDL_PushEvent(&event);
return 0; /* 0 means stop timer */
}
/* schedule a video refresh in 'delay' ms */
static void schedule_refresh(VideoState *is, int delay) {
SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
}
void video_display(VideoState *is) {
SDL_Rect rect;
VideoPicture *vp;
float aspect_ratio;
int w, h, x, y;
int i;
vp = &is->pictq[is->pictq_rindex];
if(vp->bmp) {
SDL_UpdateYUVTexture( texture, NULL,
vp->bmp->data[0], vp->bmp->linesize[0],
vp->bmp->data[1], vp->bmp->linesize[1],
vp->bmp->data[2], vp->bmp->linesize[2]);
rect.x = 0;
rect.y = 0;
rect.w = is->video_ctx->width;
rect.h = is->video_ctx->height;
SDL_LockMutex(text_mutex);
SDL_RenderClear( renderer );
SDL_RenderCopy( renderer, texture, NULL, &rect);
SDL_RenderPresent( renderer );
SDL_UnlockMutex(text_mutex);
}
}
void video_refresh_timer(void *userdata) {
VideoState *is = (VideoState *)userdata;
VideoPicture *vp;
double actual_delay, delay, sync_threshold, ref_clock, diff;
if(is->video_st) {
if(is->pictq_size == 0) {
schedule_refresh(is, 1);
//fprintf(stderr, "no picture in the queue!!!\n");
} else {
//fprintf(stderr, "get picture from queue!!!\n");
vp = &is->pictq[is->pictq_rindex];
is->video_current_pts = vp->pts;
is->video_current_pts_time = av_gettime();
delay = vp->pts - is->frame_last_pts; /* the pts from last time */
if(delay <= 0 || delay >= 1.0) {
/* if incorrect delay, use previous one */
delay = is->frame_last_delay;
}
/* save for next time */
is->frame_last_delay = delay;
is->frame_last_pts = vp->pts;
/* update delay to sync to audio if not master source */
if(is->av_sync_type != AV_SYNC_VIDEO_MASTER) {
ref_clock = get_master_clock(is);
diff = vp->pts - ref_clock;
/* Skip or repeat the frame. Take delay into account
FFPlay still doesn't "know if this is the best guess." */
sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD;
if(fabs(diff) < AV_NOSYNC_THRESHOLD) {
if(diff <= -sync_threshold) {
delay = 0;
} else if(diff >= sync_threshold) {
delay = 2 * delay;
}
}
}
is->frame_timer += delay;
/* computer the REAL delay */
actual_delay = is->frame_timer - (av_gettime() / 1000000.0);
if(actual_delay < 0.010) {
/* Really it should skip the picture instead */
actual_delay = 0.010;
}
schedule_refresh(is, (int)(actual_delay * 1000 + 0.5));
/* show the picture! */
video_display(is);
/* update queue for next picture! */
if(++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) {
is->pictq_rindex = 0;
}
SDL_LockMutex(is->pictq_mutex);
is->pictq_size--;
SDL_CondSignal(is->pictq_cond);
SDL_UnlockMutex(is->pictq_mutex);
}
} else {
schedule_refresh(is, 100);
}
}
void alloc_picture(void *userdata) {
int ret;
VideoState *is = (VideoState *)userdata;
VideoPicture *vp;
vp = &is->pictq[is->pictq_windex];
if(vp->bmp) {
// we already have one make another, bigger/smaller
avpicture_free(vp->bmp);
free(vp->bmp);
vp->bmp = NULL;
}
// Allocate a place to put our YUV image on that screen
SDL_LockMutex(text_mutex);
vp->bmp = (AVPicture*)malloc(sizeof(AVPicture));
ret = avpicture_alloc(vp->bmp, AV_PIX_FMT_YUV420P, is->video_ctx->width, is->video_ctx->height);
if (ret < 0) {
fprintf(stderr, "Could not allocate temporary picture: %s\n", av_err2str(ret));
}
SDL_UnlockMutex(text_mutex);
vp->width = is->video_ctx->width;
vp->height = is->video_ctx->height;
vp->allocated = 1;
}
int queue_picture(VideoState *is, AVFrame *pFrame, double pts) {
VideoPicture *vp;
/* wait until we have space for a new pic */
SDL_LockMutex(is->pictq_mutex);
while(is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&
!is->quit) {
SDL_CondWait(is->pictq_cond, is->pictq_mutex);
}
SDL_UnlockMutex(is->pictq_mutex);
if(is->quit)
return -1;
// windex is set to 0 initially
vp = &is->pictq[is->pictq_windex];
/* allocate or resize the buffer! */
if(!vp->bmp ||
vp->width != is->video_ctx->width ||
vp->height != is->video_ctx->height) {
vp->allocated = 0;
alloc_picture(is);
if(is->quit) {
return -1;
}
}
/* We have a place to put our picture on the queue */
if(vp->bmp) {
vp->pts = pts;
// Convert the image into YUV format that SDL uses
sws_scale(is->video_sws_ctx, (uint8_t const * const *)pFrame->data,
pFrame->linesize, 0, is->video_ctx->height,
vp->bmp->data, vp->bmp->linesize);
/* now we inform our display thread that we have a pic ready */
if(++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) {
is->pictq_windex = 0;
}
SDL_LockMutex(is->pictq_mutex);
is->pictq_size++;
SDL_UnlockMutex(is->pictq_mutex);
}
return 0;
}
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;
}
/* update the video clock */
frame_delay = av_q2d(is->video_ctx->time_base);
/* if we are repeating a frame, adjust clock accordingly */
frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
is->video_clock += frame_delay;
return pts;
}
int decode_video_thread(void *arg) {
VideoState *is = (VideoState *)arg;
AVPacket pkt1, *packet = &pkt1;
int frameFinished;
AVFrame *pFrame;
double pts;
pFrame = av_frame_alloc();
for(;;) {
if(packet_queue_get(&is->videoq, packet, 1) < 0) {
// means we quit getting packets
break;
}
pts = 0;
// Decode video frame
avcodec_decode_video2(is->video_ctx, pFrame, &frameFinished, packet);
if((pts = av_frame_get_best_effort_timestamp(pFrame)) != AV_NOPTS_VALUE) {
} else {
pts = 0;
}
pts *= av_q2d(is->video_st->time_base);
// Did we get a video frame?
if(frameFinished) {
pts = synchronize_video(is, pFrame, pts);
if(queue_picture(is, pFrame, pts) < 0) {
break;
}
}
av_free_packet(packet);
}
av_frame_free(&pFrame);
return 0;
}
int stream_component_open(VideoState *is, int stream_index) {
AVFormatContext *pFormatCtx = is->pFormatCtx;
AVCodecContext *codecCtx = NULL;
AVCodec *codec = NULL;
SDL_AudioSpec wanted_spec, spec;
if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) {
return -1;
}
codecCtx = avcodec_alloc_context3(NULL);
int ret = avcodec_parameters_to_context(codecCtx, pFormatCtx->streams[stream_index]->codecpar);
if (ret < 0)
return -1;
codec = avcodec_find_decoder(codecCtx->codec_id);
if(!codec) {
fprintf(stderr, "Unsupported codec!\n");
return -1;
}
if(codecCtx->codec_type == AVMEDIA_TYPE_AUDIO) {
// Set audio settings from codec info
wanted_spec.freq = codecCtx->sample_rate;
wanted_spec.format = AUDIO_S16SYS;
wanted_spec.channels = 2;//codecCtx->channels;
wanted_spec.silence = 0;
wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
wanted_spec.callback = audio_callback;
wanted_spec.userdata = is;
fprintf(stderr, "wanted spec: channels:%d, sample_fmt:%d, sample_rate:%d \n",
2, AUDIO_S16SYS, codecCtx->sample_rate);
if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
return -1;
}
is->audio_hw_buf_size = spec.size;
}
if(avcodec_open2(codecCtx, codec, NULL) < 0) {
fprintf(stderr, "Unsupported codec!\n");
return -1;
}
switch(codecCtx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
is->audioStream = stream_index;
is->audio_st = pFormatCtx->streams[stream_index];
is->audio_ctx = codecCtx;
is->audio_buf_size = 0;
is->audio_buf_index = 0;
memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
packet_queue_init(&is->audioq);
//Out Audio Param
uint64_t out_channel_layout=AV_CH_LAYOUT_STEREO;
//AAC:1024 MP3:1152
int out_nb_samples= is->audio_ctx->frame_size;
//AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate=is->audio_ctx->sample_rate;
int out_channels=av_get_channel_layout_nb_channels(out_channel_layout);
//Out Buffer Size
/*
int out_buffer_size=av_samples_get_buffer_size(NULL,
out_channels,
out_nb_samples,
AV_SAMPLE_FMT_S16,
1);
*/
//uint8_t *out_buffer=(uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE*2);
int64_t in_channel_layout=av_get_default_channel_layout(is->audio_ctx->channels);
struct SwrContext *audio_convert_ctx;
audio_convert_ctx = swr_alloc();
swr_alloc_set_opts(audio_convert_ctx,
out_channel_layout,
AV_SAMPLE_FMT_S16,
out_sample_rate,
in_channel_layout,
is->audio_ctx->sample_fmt,
is->audio_ctx->sample_rate,
0,
NULL);
fprintf(stderr, "swr opts: out_channel_layout:%lld, out_sample_fmt:%d, out_sample_rate:%d, in_channel_layout:%lld, in_sample_fmt:%d, in_sample_rate:%d",
out_channel_layout, AV_SAMPLE_FMT_S16, out_sample_rate, in_channel_layout, is->audio_ctx->sample_fmt, is->audio_ctx->sample_rate);
swr_init(audio_convert_ctx);
is->audio_swr_ctx = audio_convert_ctx;
SDL_PauseAudio(0);
break;
case AVMEDIA_TYPE_VIDEO:
is->videoStream = stream_index;
is->video_st = pFormatCtx->streams[stream_index];
is->video_ctx = codecCtx;
is->frame_timer = (double)av_gettime() / 1000000.0;
is->frame_last_delay = 40e-3;
is->video_current_pts_time = av_gettime();
packet_queue_init(&is->videoq);
is->video_sws_ctx = sws_getContext(is->video_ctx->width, is->video_ctx->height,
is->video_ctx->pix_fmt, is->video_ctx->width,
is->video_ctx->height, AV_PIX_FMT_YUV420P,
SWS_BILINEAR, NULL, NULL, NULL
);
is->video_tid = SDL_CreateThread(decode_video_thread, "decode_video_thread", is);
break;
default:
break;
}
}
int demux_thread(void *arg) {
int err_code;
char errors[1024] = {0,};
VideoState *is = (VideoState *)arg;
AVFormatContext *pFormatCtx;
AVPacket pkt1, *packet = &pkt1;
int video_index = -1;
int audio_index = -1;
int i;
is->videoStream=-1;
is->audioStream=-1;
global_video_state = is;
/* open input file, and allocate format context */
if ((err_code=avformat_open_input(&pFormatCtx, is->filename, NULL, NULL)) < 0) {
av_strerror(err_code, errors, 1024);
fprintf(stderr, "Could not open source file %s, %d(%s)\n", is->filename, err_code, errors);
return -1;
}
is->pFormatCtx = pFormatCtx;
// Retrieve stream information
if(avformat_find_stream_info(pFormatCtx, NULL)<0)
return -1; // Couldn't find stream information
// Dump information about file onto standard error
av_dump_format(pFormatCtx, 0, is->filename, 0);
// Find the first video stream
for(i=0; i<pFormatCtx->nb_streams; i++) {
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO &&
video_index < 0) {
video_index=i;
}
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO &&
audio_index < 0) {
audio_index=i;
}
}
if(audio_index >= 0) {
stream_component_open(is, audio_index);
}
if(video_index >= 0) {
stream_component_open(is, video_index);
}
if(is->videoStream < 0 || is->audioStream < 0) {
fprintf(stderr, "%s: could not open codecs\n", is->filename);
goto fail;
}
//creat window from SDL
win = SDL_CreateWindow("Media Player",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
is->video_ctx->width, is->video_ctx->height,
SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
if(!win) {
fprintf(stderr, "SDL: could not set video mode - exiting\n");
exit(1);
}
renderer = SDL_CreateRenderer(win, -1, 0);
//IYUV: Y + U + V (3 planes)
//YV12: Y + V + U (3 planes)
Uint32 pixformat= SDL_PIXELFORMAT_IYUV;
//create texture for render
texture = SDL_CreateTexture(renderer,
pixformat,
SDL_TEXTUREACCESS_STREAMING,
is->video_ctx->width,
is->video_ctx->height);
// main decode loop
for(;;) {
if(is->quit) {
break;
}
// seek stuff goes here
if(is->audioq.size > MAX_AUDIOQ_SIZE ||
is->videoq.size > MAX_VIDEOQ_SIZE) {
SDL_Delay(10);
continue;
}
if(av_read_frame(is->pFormatCtx, packet) < 0) {
if(is->pFormatCtx->pb->error == 0) {
SDL_Delay(100); /* no error; wait for user input */
continue;
} else {
break;
}
}
// Is this a packet from the video stream?
if(packet->stream_index == is->videoStream) {
packet_queue_put(&is->videoq, packet);
} else if(packet->stream_index == is->audioStream) {
packet_queue_put(&is->audioq, packet);
} else {
av_free_packet(packet);
}
}
/* all done - wait for it */
while(!is->quit) {
SDL_Delay(100);
}
fail:
if(1){
SDL_Event event;
event.type = FF_QUIT_EVENT;
event.user.data1 = is;
SDL_PushEvent(&event);
}
return 0;
}
int main(int argc, char *argv[]) {
SDL_Event event;
VideoState *is;
is = av_mallocz(sizeof(VideoState));
if(argc < 2) {
fprintf(stderr, "Usage: test <file>\n");
exit(1);
}
yuvfd = fopen("testout.yuv", "wb+");
audiofd = fopen("testout.pcm", "wb+");
// Register all formats and codecs
av_register_all();
if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
exit(1);
}
text_mutex = SDL_CreateMutex();
av_strlcpy(is->filename, argv[1], sizeof(is->filename));
is->pictq_mutex = SDL_CreateMutex();
is->pictq_cond = SDL_CreateCond();
schedule_refresh(is, 40);
is->av_sync_type = DEFAULT_AV_SYNC_TYPE;
is->parse_tid = SDL_CreateThread(demux_thread,"demux_thread", is);
if(!is->parse_tid) {
av_free(is);
return -1;
}
for(;;) {
SDL_WaitEvent(&event);
switch(event.type) {
case FF_QUIT_EVENT:
case SDL_QUIT:
is->quit = 1;
SDL_Quit();
return 0;
break;
case FF_REFRESH_EVENT:
video_refresh_timer(event.user.data1);
break;
default:
break;
}
}
fclose(yuvfd);
fclose(audiofd);
return 0;
}
网友评论