FFmpeg 源码分析:av_seek_frame()

ffmpeg 之 hls 前言 与其他博客不同,本文不是讲解HLS 协议本身,而是讲解在FFMPEG 中是如何解析HLS的,当然FFMPEG 也是按照HLS 协议去封装/解析 HLS 流的,因此读完本文不但能了解HLS 协议本身,还能看到HLS 是如何落地的。 1 综述 HLS(Http Live Streaming )是有苹果公司基于HTTP 传输的协议,目的解决防火墙屏蔽问题,如RTMP 不是走HTTP,容易被防火墙阻难。我们首先来看一个简单的m3u8 文件: #EXTM3U //固定格式,首行开头必须是#E.. 阅读详情

@[TOC](FFmpeg 源码分析:av_seek_frame())

FFmpeg 源码分析:av_seek_frame()

函数原型

av_seek_frame() 是 FFmpeg 中的一个函数,位于 libavformat/avformat.h,用于定位媒体文件中的某一帧。

下面是 av_seek_frame() 的函数定义:

/**
 * Seek to the keyframe at timestamp.
 * 'timestamp' in 'stream_index'.
 *
 * @param s media file handle
 * @param stream_index If stream_index is (-1), a default
 * stream is selected, and timestamp is automatically converted
 * from AV_TIME_BASE units to the stream specific time_base.
 * @param timestamp Timestamp in AVStream.time_base units
 *        or, if no stream is specified, in AV_TIME_BASE units.
 * @param flags flags which select direction and seeking mode
 * @return >= 0 on success
 */
int av_seek_frame(AVFormatContext *s, int stream_index, 
					int64_t timestamp, int flags);

参数说明:

  1. AVFormatContext *s:流媒体打开的上下文结构指针。

  2. stream_index:需要定位的音视频流的索引。一般0为视频流索引,1为音频流索引;-1为默认,说明是所有的媒体流同时跳转。

  3. timestamp:定位的时间戳。在 FFmpeg 中,时间戳(timestamp)的单位是时间基数(time_base),时间戳值乘以时间基,可以得到实际的时刻值(以秒等为单位)。

  4. flags:设置跳转模式。该参数一共有以下四种具体取值:

    #define AVSEEK_FLAG_BACKWARD 1 ///< seek backward
    #define AVSEEK_FLAG_BYTE     2 ///< seeking based on position in bytes
    #define AVSEEK_FLAG_ANY      4 ///< seek to any frame, even non-keyframes
    #define AVSEEK_FLAG_FRAME    8 ///< seeking based on frame number
    

    下面来详细解释一下:

    • AVSEEK_FLAG_BACKWARD:定位到请求的时间戳之前最近的关键帧
    • AVSEEK_FLAG_BYTE:基于字节位置的跳转,当采用这个 flags 时,时间戳要改为 byte 字节计数。
    • AVSEEK_FLAG_ANY:任意定位,跳转到任意帧,不一定是关键帧,因此使用时可能会导致花屏。
    • AVSEEK_FLAG_FRAME:强制定位到最接近的关键帧。

    此外,flags 可以通过或运算组合起来使用。

返回值:返回值大于等于 0,代表打开成功,否则失败。

需要注意的是,使用 av_seek_frame() 函数进行定位时,必须保证输入格式上下文中的流信息已经完全读取,否则可能会出现定位失败的情况。

使用细节

  • seek操作基准:即seek操作当前时间点,因此在进行播放时需要实时记录音视频流的DTS或者PTS。
  • seek时间单位:进行seek操作时,根据流索引,确定其时间单位time_base。
  • seek时间大小:即向前或者向后seek的时间大小,根据此时间大小和当前时间点,可以计算出向前或者向后进行seek操作时的目标时间。
  • seek操作载体:即是按照音频还是视频进行seek操作,只需要按照其中一个流进行seek即可,不需要分别对音视频流进行seek操作。
  • seek操作刷新:在进行seek操作之后,正常播放之前需要将编解码的内部缓冲区进行刷新,同时也要将自行控制的缓冲区内缓存的音视频清零。

实例:循环播放、可快进快退的播放器

参考:https://blog.csdn.net/zhaoyun_zzz/article/details/89406087

unistd.h 导入:https://www.cnblogs.com/lutaishi/p/13436265.html
新建一个 unistd.h,内容如下:

/** This file is part of the Mingw32 package.
 *  unistd.h maps     (roughly) to io.h
 */
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif /* _UNISTD_H */

放到 Visual Studio VC 文件夹的 include 下,我的路径是:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include。

pthread.h 导入:https://blog.csdn.net/Hexa_H/article/details/130691024

// Simplest FFmpeg Seek Player.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#define __STDC_CONSTANT_MACROS

#ifdef __cplusplus
extern "C"
{
#endif
#include <libavutil/time.h>
#include <libavutil/imgutils.h>
#include <libavutil/mathematics.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavdevice/avdevice.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
#include <SDL2/SDL.h>

#include <errno.h>

#include <unistd.h>
#include <assert.h>
#include <pthread.h>
#include <semaphore.h>

#ifdef __cplusplus
};
#endif

// 报错:
// LNK2019 无法解析的外部符号 __imp__fprintf,该符号在函数 _ShowError 中被引用
// LNK2019 无法解析的外部符号 __imp____iob_func,该符号在函数 _ShowError 中被引用

// 解决办法:
// 包含库的编译器版本低于当前编译版本,需要将包含库源码用vs2017重新编译,由于没有包含库的源码,此路不通。
// 然后查到说是stdin, stderr, stdout 这几个函数vs2015和以前的定义得不一样,所以报错。
// 解决方法呢,就是使用{ *stdin,*stdout,*stderr }数组自己定义__iob_func()
#pragma comment(lib,"legacy_stdio_definitions.lib")
extern "C"
{
	FILE __iob_func[3] = { *stdin, *stdout, *stderr };
}

#define MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio

#define PACKET_ARRAY_SIZE			(60)
typedef struct __PacketStruct
{
	AVPacket Packet;
	int64_t dts;
	int64_t pts;
	int state;
}PacketStruct;

typedef struct
{
	unsigned int rIndex;
	unsigned int wIndex;
	PacketStruct PacketArray[PACKET_ARRAY_SIZE];
}PacketArrayStruct;

typedef struct __AudioCtrlStruct
{
	AVFormatContext	*pFormatCtx;
	AVStream 		*pStream;
	AVCodec			*pCodec;
	AVCodecContext	*pCodecCtx;
	SwrContext 		*pConvertCtx;

	Uint8  	*audio_chunk;
	Sint32  audio_len;
	Uint8  	*audio_pos;
	int 	AudioIndex;
	int 	AudioCnt;
	uint64_t AudioOutChannelLayout;
	int out_nb_samples;				// nb_samples: AAC-1024 MP3-1152
	AVSampleFormat out_sample_fmt;
	int out_sample_rate;
	int out_channels;
	int out_buffer_size;
	unsigned char* pAudioOutBuffer;

	sem_t frame_put;
	sem_t frame_get;

	PacketArrayStruct 	Audio;
}AudioCtrlStruct;


typedef struct __VideoCtrlStruct
{
	AVFormatContext	*pFormatCtx;
	AVStream 		*pStream;
	AVCodec			*pCodec;
	AVCodecContext	*pCodecCtx;
	SwsContext 		*pConvertCtx;
	AVFrame			*pVideoFrame, *pFrameYUV;
	unsigned char 	*pVideoOutBuffer;
	int 			VideoIndex;
	int 			VideoCnt;
	int 			RefreshTime;
	int screen_w, screen_h;
	SDL_Window *screen;
	SDL_Renderer* sdlRenderer;
	SDL_Texture* sdlTexture;
	SDL_Rect sdlRect;
	SDL_Thread *video_tid;

	sem_t frame_put;
	sem_t video_refresh;
	PacketArrayStruct Video;
}VideoCtrlStruct;


//Refresh Event
#define SFM_REFRESH_VIDEO_EVENT  	(SDL_USEREVENT + 1)
#define SFM_REFRESH_AUDIO_EVENT  	(SDL_USEREVENT + 2)
#define SFM_BREAK_EVENT  			(SDL_USEREVENT + 3)

int thread_exit = 0;
int thread_pause = 0;
int audio_pause = 0;		//音频播放是否暂停,1表示暂停,0表示在播放
int video_pause = 0;		//视频播放是否暂停,1表示暂停,0表示在播放
SDL_Keycode CurKeyCode;		//记录按下的是前进还是后退键,即小键盘的左右方向键,右表示前进,左表示后退
int CurKeyProcess;			//按键seek操作是否已经被处理,0表示未处理,1表示已经处理
int64_t CurVideoDts;	//记录当前播放的视频流Packet的DTS
int64_t CurVideoPts;	//记录当前播放的视频流Packet的DTS

int64_t CurAudioDts;	//记录当前播放的音频流Packet的DTS
int64_t CurAudioPts;	//记录当前播放的音频流Packet的DTS

int64_t DstAudioDts;	//进行seek操作时,计算后的目标音频流的DTS
int64_t DstAudioPts;	//进行seek操作时,计算后的目标音频流的PTS
int64_t DstVideoDts;	//进行seek操作时,计算后的目标视频流的DTS
int64_t DstVideoPts;	//进行seek操作时,计算后的目标视频流的DTS

VideoCtrlStruct VideoCtrl;
AudioCtrlStruct AudioCtrl;
//video time_base.num:1, time_base.den:16, avg_frame_rate.num:8, avg_frame_rate.den:1
//audio time_base.num:1, time_base.den:48000, avg_frame_rate.num:0, avg_frame_rate.den:0
int IsPacketArrayFull(PacketArrayStruct* p)
{
	int i = 0;
	i = p->wIndex % PACKET_ARRAY_SIZE;
	if (p->PacketArray[i].state != 0) return 1;

	return 0;
}

int IsPacketArrayEmpty(PacketArrayStruct* p)
{
	int i = 0;
	i = p->rIndex % PACKET_ARRAY_SIZE;
	if (p->PacketArray[i].state == 0) return 1;

	return 0;
}

int PacketArrayClear(PacketArrayStruct* p)
{
	int i = 0;
	for (i = 0; i < PACKET_ARRAY_SIZE; i++)
	{
		if (p->PacketArray[i].state != 0)
		{
			av_packet_unref(&p->PacketArray[i].Packet);
			p->PacketArray[i].state = 0;
		}
	}
	p->rIndex = 0;
	p->wIndex = 0;

	return 0;
}

int SDL_event_thread(void *opaque)
{
	SDL_Event event;

	while (1)
	{
		SDL_WaitEvent(&event);
		if (event.type == SDL_KEYDOWN)
		{
			//Pause
			if (event.key.keysym.sym == SDLK_SPACE)
			{
				thread_pause = !thread_pause;
				printf("video got pause event!\n");
			}
			if (event.key.keysym.sym == SDLK_RIGHT)
			{
				thread_pause = !thread_pause;
				CurKeyProcess = 0;
				CurKeyCode = SDLK_RIGHT;
				printf("video got right key event!\n");
			}

			if (event.key.keysym.sym == SDLK_LEFT)
			{
				thread_pause = !thread_pause;
				CurKeyProcess = 0;
				CurKeyCode = SDLK_LEFT;
				printf("video got left key event!\n");
			}

		}
		else if (event.type == SDL_QUIT)
		{
			thread_exit = 1;
			printf("------------------------------>video got SDL_QUIT event!\n");
			break;
		}
		else if (event.type == SFM_BREAK_EVENT)
		{
			break;
		}
	}

	printf("---------> SDL_event_thread end !!!! \n");
	return 0;
}

int video_refresh_thread(void *opaque)
{
	while (1)
	{
		if (thread_exit) break;
		if (thread_pause)
		{
			SDL_Delay(40);
			continue;
		}
		//SDL_Delay(40);
		Sleep(VideoCtrl.RefreshTime);
		sem_post(&VideoCtrl.video_refresh);
	}
	printf("---------> video_refresh_thread end !!!! \n");
	return 0;
}

static void *thread_audio(void *arg)
{
	AVCodecContext	*pAudioCodecCtx;
	AVFrame			*pAudioFrame;
	unsigned char 	*pAudioOutBuffer;
	AVPacket 		*Packet;
	int 			i, ret, GotAudioPicture;

	struct SwrContext *AudioConvertCtx;

	AudioCtrlStruct* AudioCtrl = (AudioCtrlStruct*)arg;

	pAudioCodecCtx = AudioCtrl->pCodecCtx;
	pAudioOutBuffer = AudioCtrl->pAudioOutBuffer;
	AudioConvertCtx = AudioCtrl->pConvertCtx;
	printf("---------> thread_audio start !!!! \n");
	pAudioFrame = av_frame_alloc();
	while (1)
	{
		if (thread_exit) break;
		if (thread_pause)
		{
			Sleep(10000);
			audio_pause = 1;
			continue;
		}

		if (IsPacketArrayEmpty(&AudioCtrl->Audio))
		{
			SDL_Delay(1);
			printf("---------> thread_audio empty !!!! \n");
			continue;
		}
		audio_pause = 0;
		i = AudioCtrl->Audio.rIndex;
		Packet = &AudioCtrl->Audio.PacketArray[i].Packet;
		CurAudioDts = AudioCtrl->Audio.PacketArray[i].dts;
		CurAudioPts = AudioCtrl->Audio.PacketArray[i].pts;
		if (Packet->stream_index == AudioCtrl->AudioIndex)
		{
			// ret = avcodec_decode_audio4(pAudioCodecCtx, pAudioFrame, &GotAudioPicture, Packet);
			ret = avcodec_send_packet(pAudioCodecCtx, Packet);
			if (ret < 0)
			{
				printf("Error in decoding audio frame.\n");
				return 0;
			}
			while (avcodec_receive_frame(pAudioCodecCtx, pAudioFrame) == 0)
			{
				swr_convert(AudioConvertCtx, &pAudioOutBuffer, MAX_AUDIO_FRAME_SIZE,
					(const uint8_t **)pAudioFrame->data, pAudioFrame->nb_samples);
				printf("Auduo index:%5d\t pts:%ld\t packet size:%d, pFrame->nb_samples:%d\n",
					AudioCtrl->AudioCnt, Packet->pts, Packet->size, pAudioFrame->nb_samples);

				AudioCtrl->AudioCnt++;
			}

			while (AudioCtrl->audio_len > 0)//Wait until finish
				SDL_Delay(1);

			//Set audio buffer (PCM data)
			AudioCtrl->audio_chunk = (Uint8 *)pAudioOutBuffer;
			AudioCtrl->audio_pos = AudioCtrl->audio_chunk;
			AudioCtrl->audio_len = AudioCtrl->out_buffer_size;

			av_packet_unref(Packet);

			AudioCtrl->Audio.PacketArray[i].state = 0;
			i++;
			if (i >= PACKET_ARRAY_SIZE) i = 0;
			AudioCtrl->Audio.rIndex = i;
		}
	}

	printf("---------> thread_audio end !!!! \n");
	return 0;
}

static void *thread_video(void *arg)
{
	//AVFormatContext	*pFormatCtx;
	AVCodecContext	*pVideoCodecCtx;
	//AVCodec			*pVideoCodec;
	AVFrame			*pVideoFrame, *pFrameYUV;
	//unsigned char 	*pVideoOutBuffer;
	AVPacket 		*Packet;
	int 			i, ret, GotPicture;
	struct SwsContext *VideoConvertCtx;

	VideoCtrlStruct* VideoCtrl = (VideoCtrlStruct*)arg;

	pVideoCodecCtx = VideoCtrl->pCodecCtx;
	//pVideoOutBuffer = VideoCtrl->pVideoOutBuffer;
	VideoConvertCtx = VideoCtrl->pConvertCtx;
	pVideoFrame = VideoCtrl->pVideoFrame;
	pFrameYUV = VideoCtrl->pFrameYUV;
	printf("---------> thread_video start !!!! \n");
	while (1)
	{
		if (thread_exit) break;
		if (thread_pause)
		{
			Sleep(10000);
			video_pause = 1;
			continue;
		}

		if (IsPacketArrayEmpty(&VideoCtrl->Video))
		{
			SDL_Delay(1);
			continue;
		}
		video_pause = 0;
		i = VideoCtrl->Video.rIndex;
		Packet = &VideoCtrl->Video.PacketArray[i].Packet;
		CurVideoDts = VideoCtrl->Video.PacketArray[i].dts;
		CurVideoPts = VideoCtrl->Video.PacketArray[i].pts;
		if (Packet->stream_index == VideoCtrl->VideoIndex)
		{
			// ret = avcodec_decode_video2(pVideoCodecCtx, pVideoFrame, &GotPicture, Packet);
			ret = avcodec_send_packet(pVideoCodecCtx, Packet);
			if (ret != 0)
			{
				printf("Video Decode Error.\n");
				return 0;
			}
			GotPicture = avcodec_receive_frame(pVideoCodecCtx, pVideoFrame);
			printf("Video index:%5d\t dts:%ld\t, pts:%ld\t packet size:%d, GotVideoPicture:%d\n",
				VideoCtrl->VideoCnt, Packet->dts, Packet->pts, Packet->size, GotPicture);
			//			printf("Video index:%5d\t pFrame->pkt_dts:%ld, pFrame->pkt_pts:%ld, pFrame->pts:%ld, pFrame->pict_type:%d, "
			//					"pFrame->best_effort_timestamp:%ld, pFrame->pkt_pos:%ld, pVideoFrame->pkt_duration:%ld\n",
			//					VideoCtrl->VideoCnt, pVideoFrame->pkt_dts, pVideoFrame->pkt_pts, pVideoFrame->pts,
			//					pVideoFrame->pict_type, pVideoFrame->best_effort_timestamp,
			//					pVideoFrame->pkt_pos, pVideoFrame->pkt_duration);
			VideoCtrl->VideoCnt++;
			if (GotPicture == 0)
			{
				sws_scale(VideoConvertCtx, (const unsigned char* const*)pVideoFrame->data,
					pVideoFrame->linesize, 0, pVideoCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);

				sem_wait(&VideoCtrl->video_refresh);
				//SDL---------------------------
				SDL_UpdateTexture(VideoCtrl->sdlTexture, NULL, pFrameYUV->data[0], pFrameYUV->linesize[0]);
				SDL_RenderClear(VideoCtrl->sdlRenderer);
				//SDL_RenderCopy( sdlRenderer, sdlTexture, &sdlRect, &sdlRect );
				SDL_RenderCopy(VideoCtrl->sdlRenderer, VideoCtrl->sdlTexture, NULL, NULL);
				SDL_RenderPresent(VideoCtrl->sdlRenderer);
				//SDL End-----------------------
			}

			av_packet_unref(Packet);
			VideoCtrl->Video.PacketArray[i].state = 0;
			i++;
			if (i >= PACKET_ARRAY_SIZE) i = 0;
			VideoCtrl->Video.rIndex = i;
		}
	}
	printf("---------> thread_video end !!!! \n");
	return 0;
}

/* The audio function callback takes the following parameters:
* stream: A pointer to the audio buffer to be filled
* len: The length (in bytes) of the audio buffer
*/
void fill_audio(void *udata, Uint8 *stream, int len)
{
	AudioCtrlStruct* AudioCtrl = (AudioCtrlStruct*)udata;
	//SDL 2.0
	SDL_memset(stream, 0, len);
	if (AudioCtrl->audio_len == 0) return;

	len = (len > AudioCtrl->audio_len ? AudioCtrl->audio_len : len);	/*  Mix  as  much  data  as  possible  */

	SDL_MixAudio(stream, AudioCtrl->audio_pos, len, SDL_MIX_MAXVOLUME);
	AudioCtrl->audio_pos += len;
	AudioCtrl->audio_len -= len;
}

AVFormatContext	*pFormatCtx;
AVCodecContext	*pVideoCodecCtx, *pAudioCodecCtx;
AVCodec			*pVideoCodec, *pAudioCodec;
AVCodecParameters *pVideoCodecParameters, *pAudioCodecParameters;
AVPacket		*Packet;
unsigned char 	*pVideoOutBuffer, *pAudioOutBuffer;

int 			ret;
unsigned int    i;
pthread_t 		audio_tid, video_tid;

uint64_t AudioOutChannelLayout;
//nb_samples: AAC-1024 MP3-1152
int out_nb_samples;
AVSampleFormat out_sample_fmt;
int out_sample_rate;
int out_channels;
//Out Buffer Size
int out_buffer_size;

//------------SDL----------------

struct SwsContext *VideoConvertCtx;
struct SwrContext *AudioConvertCtx;
int VideoIndex, VideoCnt;
int AudioIndex, AudioCnt;

int main(int argc, char* argv[])
{
	char *filepath = "cuc_ieschool.mp4";
	memset(&AudioCtrl, 0, sizeof(AudioCtrlStruct));
	memset(&VideoCtrl, 0, sizeof(VideoCtrlStruct));

	sem_init(&VideoCtrl.video_refresh, 0, 0);
	sem_init(&VideoCtrl.frame_put, 0, 0);
	sem_init(&AudioCtrl.frame_put, 0, 0);
	thread_exit = 0;
	thread_pause = 0;
	CurKeyProcess = 1;
	CurKeyCode = 0;
	// av_register_all();
	avformat_network_init();
	pFormatCtx = avformat_alloc_context();

	if (avformat_open_input(&pFormatCtx, filepath, NULL, NULL) != 0)
	{
		printf("Couldn't open input stream.\n");
		return -1;
	}
	if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
	{
		printf("Couldn't find stream information.\n");
		return -1;
	}

	VideoIndex = -1;
	AudioIndex = -1;
	for (i = 0; i < pFormatCtx->nb_streams; i++)
	{
		if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
		{
			VideoIndex = i;
			//打印输出视频流的信息
			printf("video time_base.num:%d, time_base.den:%d, avg_frame_rate.num:%d, avg_frame_rate.den:%d\n",
				pFormatCtx->streams[VideoIndex]->time_base.num,
				pFormatCtx->streams[VideoIndex]->time_base.den,
				pFormatCtx->streams[VideoIndex]->avg_frame_rate.num,
				pFormatCtx->streams[VideoIndex]->avg_frame_rate.den);
		}

		if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
		{
			AudioIndex = i;
			//打印输出音频流的信息
			//pFormatCtx->streams[AudioIndex]->time_base.den <<= 1;
			printf("audio time_base.num:%d, time_base.den:%d, avg_frame_rate.num:%d, avg_frame_rate.den:%d\n",
				pFormatCtx->streams[AudioIndex]->time_base.num,
				pFormatCtx->streams[AudioIndex]->time_base.den,
				pFormatCtx->streams[AudioIndex]->avg_frame_rate.num,
				pFormatCtx->streams[AudioIndex]->avg_frame_rate.den);
		}
	}

	if (VideoIndex != -1)
	{	
		// 准备视频的解码操作上下文数据结构
		pVideoCodec = avcodec_find_decoder(pFormatCtx->streams[VideoIndex]->codecpar->codec_id);
		pVideoCodecCtx = avcodec_alloc_context3(pVideoCodec);
		pVideoCodecParameters = pFormatCtx->streams[VideoIndex]->codecpar;
		avcodec_parameters_to_context(pVideoCodecCtx, pVideoCodecParameters);
		if (pVideoCodec == NULL)
		{
			printf("Video Codec not found.\n");
			return -1;
		}
		if (avcodec_open2(pVideoCodecCtx, pVideoCodec, NULL) < 0)
		{
			printf("Could not open video codec.\n");
			return -1;
		}

		// prepare video
		VideoCtrl.pVideoFrame = av_frame_alloc();
		VideoCtrl.pFrameYUV = av_frame_alloc();

		ret = av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pVideoCodecCtx->width, pVideoCodecCtx->height, 1);
		pVideoOutBuffer = (unsigned char *)av_malloc(ret);
		av_image_fill_arrays(VideoCtrl.pFrameYUV->data, VideoCtrl.pFrameYUV->linesize, pVideoOutBuffer,
			AV_PIX_FMT_YUV420P, pVideoCodecCtx->width, pVideoCodecCtx->height, 1);

		VideoConvertCtx = sws_getContext(pVideoCodecCtx->width, pVideoCodecCtx->height, pVideoCodecCtx->pix_fmt,
			pVideoCodecCtx->width, pVideoCodecCtx->height,
			AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);

		VideoCtrl.pFormatCtx = pFormatCtx;
		VideoCtrl.pStream = pFormatCtx->streams[VideoIndex];
		VideoCtrl.pCodec = pVideoCodec;
		// VideoCtrl.pCodecCtx = pFormatCtx->streams[VideoIndex]->codec;
		pVideoCodecParameters = pFormatCtx->streams[VideoIndex]->codecpar;
		AVCodecContext *pVideoCodecContext = avcodec_alloc_context3(NULL);
		avcodec_parameters_to_context(pVideoCodecContext, pVideoCodecParameters);
		VideoCtrl.pCodecCtx = pVideoCodecContext;
		VideoCtrl.pConvertCtx = VideoConvertCtx;
		VideoCtrl.pVideoOutBuffer = pVideoOutBuffer;
		VideoCtrl.VideoIndex = VideoIndex;

		if (pFormatCtx->streams[VideoIndex]->avg_frame_rate.num == 0 ||
			pFormatCtx->streams[VideoIndex]->avg_frame_rate.den == 0)
		{
			VideoCtrl.RefreshTime = 40000;
		}
		else
		{
			VideoCtrl.RefreshTime = 1000000 * pFormatCtx->streams[VideoIndex]->avg_frame_rate.den;
			VideoCtrl.RefreshTime /= pFormatCtx->streams[VideoIndex]->avg_frame_rate.num;
		}
		printf("VideoCtrl.RefreshTime:%d\n", VideoCtrl.RefreshTime);
	}
	else
	{
		printf("Didn't find a video stream.\n");
	}

	if (AudioIndex != -1)
	{	//准备音频的解码操作上下文数据结构,
		// pAudioCodecCtx = pFormatCtx->streams[AudioIndex]->codec;	
		pAudioCodec = avcodec_find_decoder(pFormatCtx->streams[AudioIndex]->codecpar->codec_id);
		pAudioCodecCtx = avcodec_alloc_context3(pAudioCodec);
		pAudioCodecParameters = pFormatCtx->streams[AudioIndex]->codecpar;
		avcodec_parameters_to_context(pAudioCodecCtx, pAudioCodecParameters);
		if (pAudioCodec == NULL)
		{
			printf("Audio Codec not found.\n");
			return -1;
		}
		if (avcodec_open2(pAudioCodecCtx, pAudioCodec, NULL) < 0)
		{
			printf("Could not open audio codec.\n");
			return -1;
		}
		// prepare Out Audio Param
		AudioOutChannelLayout = AV_CH_LAYOUT_STEREO;
		out_nb_samples = pAudioCodecCtx->frame_size * 2;	//nb_samples: AAC-1024 MP3-1152
		out_sample_fmt = AV_SAMPLE_FMT_S16;
		out_sample_rate = pAudioCodecCtx->sample_rate * 2;
		// 此处一定使用pAudioCodecCtx->sample_rate这个变量赋值,否则使用不一样的值会造成音频少采样或者过采样,导致音频播放出现杂音
		out_channels = av_get_channel_layout_nb_channels(AudioOutChannelLayout);
		out_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1);

		//mp3:out_nb_samples:1152, out_channels:2, out_buffer_size:4608, pCodecCtx->channels:2
		//aac:out_nb_samples:1024, out_channels:2, out_buffer_size:4096, pCodecCtx->channels:2
		printf("out_nb_samples:%d, out_channels:%d, out_buffer_size:%d, pCodecCtx->channels:%d\n",
			out_nb_samples, out_channels, out_buffer_size, pAudioCodecCtx->channels);
		pAudioOutBuffer = (uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE * 2);

		//FIX:Some Codec's Context Information is missing
		int64_t in_channel_layout = av_get_default_channel_layout(pAudioCodecCtx->channels);
		//Swr
		AudioConvertCtx = swr_alloc();
		AudioConvertCtx = swr_alloc_set_opts(AudioConvertCtx, AudioOutChannelLayout,
			out_sample_fmt, out_sample_rate,
			in_channel_layout, pAudioCodecCtx->sample_fmt,
			pAudioCodecCtx->sample_rate, 0, NULL);
		swr_init(AudioConvertCtx);

		AudioCtrl.pFormatCtx = pFormatCtx;
		AudioCtrl.pStream = pFormatCtx->streams[AudioIndex];
		AudioCtrl.pCodec = pAudioCodec;
		// AudioCtrl.pCodecCtx = pFormatCtx->streams[AudioIndex]->codec;
		pAudioCodecParameters = pFormatCtx->streams[AudioIndex]->codecpar;
		AVCodecContext *pAudioCodecContext = avcodec_alloc_context3(NULL);
		avcodec_parameters_to_context(pAudioCodecContext, pAudioCodecParameters);
		AudioCtrl.pCodecCtx = pAudioCodecContext;
		AudioCtrl.pConvertCtx = AudioConvertCtx;

		AudioCtrl.AudioOutChannelLayout = AudioOutChannelLayout;
		AudioCtrl.out_nb_samples = out_nb_samples;
		AudioCtrl.out_sample_fmt = out_sample_fmt;
		AudioCtrl.out_sample_rate = out_sample_rate;
		AudioCtrl.out_channels = out_channels;
		AudioCtrl.out_buffer_size = out_buffer_size;
		AudioCtrl.pAudioOutBuffer = pAudioOutBuffer;
		AudioCtrl.AudioIndex = AudioIndex;
	}
	else
	{
		printf("Didn't find a audio stream.\n");
	}

	//Output Info-----------------------------
	printf("---------------- File Information ---------------\n");
	av_dump_format(pFormatCtx, 0, filepath, 0);
	printf("-------------- File Information end -------------\n");

	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER))
	{
		printf("Could not initialize SDL - %s\n", SDL_GetError());
		return -1;
	}

	if (VideoIndex != -1)
	{
		//SDL 2.0 Support for multiple windows
		//SDL_VideoSpec
		VideoCtrl.screen_w = pVideoCodecCtx->width;
		VideoCtrl.screen_h = pVideoCodecCtx->height;
		VideoCtrl.screen = SDL_CreateWindow("Simplest ffmpeg player's Window", SDL_WINDOWPOS_UNDEFINED,
			SDL_WINDOWPOS_UNDEFINED, VideoCtrl.screen_w, VideoCtrl.screen_h, SDL_WINDOW_OPENGL);

		if (!VideoCtrl.screen)
		{
			printf("SDL: could not create window - exiting:%s\n", SDL_GetError());
			return -1;
		}
		VideoCtrl.sdlRenderer = SDL_CreateRenderer(VideoCtrl.screen, -1, 0);
		//IYUV: Y + U + V  (3 planes)
		//YV12: Y + V + U  (3 planes)
		VideoCtrl.sdlTexture = SDL_CreateTexture(VideoCtrl.sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING,
			pVideoCodecCtx->width, pVideoCodecCtx->height);

		VideoCtrl.sdlRect.x = 0;
		VideoCtrl.sdlRect.y = 0;
		VideoCtrl.sdlRect.w = VideoCtrl.screen_w;
		VideoCtrl.sdlRect.h = VideoCtrl.screen_h;

		VideoCtrl.video_tid = SDL_CreateThread(video_refresh_thread, NULL, NULL);
		ret = pthread_create(&video_tid, NULL, thread_video, &VideoCtrl);
		if (ret)
		{
			printf("create thr_rvs video thread failed, error = %d \n", ret);
			return -1;
		}
	}

	if (AudioIndex != -1)
	{
		//SDL_AudioSpec
		SDL_AudioSpec AudioSpec;
		AudioSpec.freq = out_sample_rate;
		AudioSpec.format = AUDIO_S16SYS;
		AudioSpec.channels = out_channels;
		AudioSpec.silence = 0;
		AudioSpec.samples = out_nb_samples;
		AudioSpec.callback = fill_audio;
		AudioSpec.userdata = (void*)&AudioCtrl;

		if (SDL_OpenAudio(&AudioSpec, NULL) < 0)
		{
			printf("can't open audio.\n");
			return -1;
		}

		ret = pthread_create(&audio_tid, NULL, thread_audio, &AudioCtrl);
		if (ret)
		{
			printf("create thr_rvs video thread failed, error = %d \n", ret);
			return -1;
		}
		SDL_PauseAudio(0);
	}

	SDL_Thread *event_tid;
	event_tid = SDL_CreateThread(SDL_event_thread, NULL, NULL);

	VideoCnt = 0;
	AudioCnt = 0;
	Packet = (AVPacket *)av_malloc(sizeof(AVPacket));
	av_init_packet(Packet);

	while (1)
	{
		if (thread_pause)
		{
			if ((CurKeyProcess == 0) && video_pause && audio_pause)
			{
				switch (CurKeyCode)
				{
				case SDLK_RIGHT:
					//DstAudioDts = CurAudioDts + (int64_t) (3 / av_q2d(AudioCtrl.pStream->time_base));
					//因为time_base分数结构中,num基本都为1,因此为了减少浮点数乘除法,可以直接乘以time_base的分母
					DstAudioDts = CurAudioDts + 3 * AudioCtrl.pStream->time_base.den;
					DstVideoDts = CurVideoDts + 3 * VideoCtrl.pStream->time_base.den;
					ret = av_seek_frame(pFormatCtx, AudioIndex, DstAudioDts, AVSEEK_FLAG_FRAME);
					//ret = av_seek_frame(pFormatCtx, VideoIndex, DstVideoDts, AVSEEK_FLAG_FRAME);
					printf("SDLK_RIGHT av_seek_frame ret = %d, CurAudioDts:%ld, CurVideoDts:%ld, DstVideoDts:%ld, DstAudioDts:%ld\n",
						ret, CurAudioDts, CurVideoDts, DstVideoDts, DstAudioDts);
					avcodec_flush_buffers(AudioCtrl.pCodecCtx);
					avcodec_flush_buffers(VideoCtrl.pCodecCtx);
					PacketArrayClear(&VideoCtrl.Video);
					PacketArrayClear(&AudioCtrl.Audio);
					break;
				case SDLK_LEFT:
					DstAudioDts = CurAudioDts - 3 * AudioCtrl.pStream->time_base.den;
					DstVideoDts = CurVideoDts - 3 * VideoCtrl.pStream->time_base.den;
					if (DstAudioDts < 0) DstAudioDts = 0;
					if (DstVideoDts < 0) DstVideoDts = 0;
					ret = av_seek_frame(pFormatCtx, AudioIndex, DstAudioDts, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME);
					//ret = av_seek_frame(pFormatCtx, VideoIndex, DstVideoDts, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME);
					printf("SDLK_LEFT av_seek_frame ret = %d, CurAudioDts:%ld, CurVideoDts:%ld, DstVideoDts:%ld, DstAudioDts:%ld\n",
						ret, CurAudioDts, CurVideoDts, DstVideoDts, DstAudioDts);
					avcodec_flush_buffers(AudioCtrl.pCodecCtx);
					avcodec_flush_buffers(VideoCtrl.pCodecCtx);
					PacketArrayClear(&VideoCtrl.Video);
					PacketArrayClear(&AudioCtrl.Audio);
					break;
				default:
					break;
				}
				CurKeyProcess = 1;
				thread_pause = !thread_pause;
			}
			Sleep(10000);
			continue;
		}
		if (av_read_frame(pFormatCtx, Packet) < 0)
		{
			//			thread_exit = 1;
			//			SDL_Event event;
			//			event.type = SFM_BREAK_EVENT;
			//			SDL_PushEvent(&event);
			//			printf("---------> av_read_frame < 0, thread_exit = 1  !!!\n");
			//			break;
			av_seek_frame(pFormatCtx, AudioIndex, 0, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_FRAME);
			continue;
		}
		if (Packet->stream_index == VideoIndex)
		{
			if (VideoCtrl.Video.wIndex >= PACKET_ARRAY_SIZE)
			{
				VideoCtrl.Video.wIndex = 0;
			}
			while (IsPacketArrayFull(&VideoCtrl.Video))
			{
				Sleep(5000);
				//printf("---------> VideoCtrl.Video.PacketArray FULL !!!\n");
			}
			i = VideoCtrl.Video.wIndex;
			VideoCtrl.Video.PacketArray[i].Packet = *Packet;
			VideoCtrl.Video.PacketArray[i].dts = Packet->dts;
			VideoCtrl.Video.PacketArray[i].pts = Packet->pts;
			VideoCtrl.Video.PacketArray[i].state = 1;
			VideoCtrl.Video.wIndex++;
			//printf("VideoCtrl packet put,dts:%ld, pts:%ld, VideoCnt:%d\n", Packet->dts, Packet->pts, VideoCnt++);
		}

		if (Packet->stream_index == AudioIndex)
		{
			if (AudioCtrl.Audio.wIndex >= PACKET_ARRAY_SIZE)
			{
				AudioCtrl.Audio.wIndex = 0;
			}
			while (IsPacketArrayFull(&AudioCtrl.Audio))
			{
				Sleep(5000);
				//printf("---------> AudioCtrl.Audio.PacketArray FULL !!!\n");
			}
			i = AudioCtrl.Audio.wIndex;
			AudioCtrl.Audio.PacketArray[i].Packet = *Packet;
			AudioCtrl.Audio.PacketArray[i].dts = Packet->dts;
			AudioCtrl.Audio.PacketArray[i].pts = Packet->pts;
			AudioCtrl.Audio.PacketArray[i].state = 1;
			AudioCtrl.Audio.wIndex++;
			//printf("AudioCtrl.frame_put, AudioCnt:%d\n", AudioCnt++);
		}

		if (thread_exit) break;
	}

	SDL_WaitThread(event_tid, NULL);
	SDL_WaitThread(VideoCtrl.video_tid, NULL);
	pthread_join(audio_tid, NULL);

	pthread_join(video_tid, NULL);
	SDL_CloseAudio();//Close SDL
	SDL_Quit();
	swr_free(&AudioConvertCtx);
	sws_freeContext(VideoConvertCtx);
	av_free(pVideoOutBuffer);
	avcodec_close(pVideoCodecCtx);
	av_free(pAudioOutBuffer);
	avcodec_close(pAudioCodecCtx);
	avformat_close_input(&pFormatCtx);

	return 0;
}

参考

  1. https://blog.csdn.net/zhaoyun_zzz/article/details/89406087
  2. https://blog.csdn.net/logani/article/details/128378138
  3. https://www.cnblogs.com/yongdaimi/p/15796060.html
  4. https://wenku.csdn.net/answer/4cb7a683e83842d292ba68e38e62a748
  5. https://blog.csdn.net/u011686167/article/details/123029573
  6. https://blog.csdn.net/bolitongyue/article/details/130806031
  7. https://blog.csdn.net/e891377/article/details/126705854
FFmpeg源码分析:av_seek_frame()与avformat_seek_file() 在播放视频过程中,想要跳过中间直接看精彩片段怎么办呢?或者看到精彩片段,想回到某个位置重新观看又该怎么办呢?所以播放器得提供seek操作实现快进快退功能,FFmpeg在libavformat模块提供此功能的API,av_seek_frame()属于旧版API,而avformat_seek_file()属于新版API并且兼容旧版本。 阅读详情

相关推荐

ffmpeg新手成长之路——使用av_seek_frame做seek定位

ts一般使用AVSEEK_FLAG_BYTE,mp4一般使用AVSEEK_FLAG_ANY、AVSEEK_FLAG_BACKWARD(seek到对应时间戳之前的最后一个关键帧)timestamp:定位的时间戳,单位以流的time_base为单位,并非毫秒单位的时间戳,因此如果seek,需要结合具体的流的time_base计算对应单位的时间戳。具体的值有如下几个,可以通过运算符来进行组合。stream_index:用于seek的流索引,-1为默认,一般0为视频流索引,1为音频流索引。

bolitongyue的博客 1168

FFmpeg之音视频截取关键函数av_seek_frame

无

qq_44632658的博客 2707

av_seek_frame获取当前Frame

av_seek_frame对视频进行跳转,但该方法使用还是有些坑说明如下。 I/P/B帧 I frame:自身可以通过视频解压算法解压成一张单独的完整的图片。 P frame:需要参考其前面的一个I/P/B来生成一张完整的图片。 B frame:则要参考其前一个I或者P帧及其后面的一个P帧来生成一张完整的图片。 两个I frame之间形成一个GOP。 flag参数 #define AVSEEK_FLAG_BACKWARD 1 ///< seek backward,若你设置seek时

quietbxj的博客 1021

基于NDK、C++、FFmpeg的android视频播放器开发实战

课程包含了对流媒体(拉流)的播放,演示了播放rtmp的香港卫视,支持rtsp摄像头和http网络视频的播放,支持访问本地的视频文件,并精确显示和控制播放进度:1讲解如何编译Android平台的ffmpeg库,使其支持neon技术和硬解码,并测试性能2使用opengles的NDK shader高效播放yuv视频,不耗费cpu性能更优(GPU)3代码支持硬解码(省电不耗cpu)和多线程解码(高性能每秒解码240帧1080p)4支持网络流媒体(rtmp,rtsp,http)可直接拉流播放电视并支持rtsp摄像头访问5课程将设计模式应用到实践 - 观察者,构建者,门面,代理,适配器,单件模式

ffplay源码分析2-数据结构

本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10301253.html ffplay是FFmpeg工程自带的简单播放器,使用FFmpeg提供的解码器和SDL库进行视频播放。本文基于FFmpeg工程4.1版本进行分析,其中ffplay源码清单如下: https://github.com/FFmpeg/FFmpeg/blob/n4.1/f...

叶余的博客 585

FFmpeg常用API总结

常用 API 分析 通用 API av_register_all 编译配置(--enable、--disable) FFmpeg 的时候,会生成两个文件:config.mk、config.h。config.mk 会实际上就是 makefile 文件需要包含进去的子模块,会作用在编译阶段,帮助开发者便宜出正确的库;而 config.h 是作用在运行阶段,这一阶段将确保需要注册哪些容器以...

程序猿老樊的博客 1022

ffmpeg ffplay.c 源码分析二:数据读取线程

一 准备⼯作本章主要是分析 数据读取线程read_thread 中的工作。如上图红色框框的部分从ffplay框架分析我们可以看到,ffplay有专⻔的线程read_thread()读取数据,且在调⽤av_read_frame 读取数据包之前需要做:1.例如打开⽂件,2.查找配置解码器,3.初始化⾳视频输出等准备阶段,主要包括三⼤步骤:准备⼯作For循环读取数据退出线程处理一 准备⼯作准备⼯作主要包括以下步骤:1.avformat_alloc_context 创建上下⽂2.

hunandede的博客 1354

告别环境配置焦虑:在Win10的Ubuntu子系统里搞定CSAPP实验环境(附32/64位库编译指南)

本文详细介绍了如何在Win10的Ubuntu子系统中搭建CSAPP实验环境,包括WSL 2的安装与配置、32/64位库的编译指南以及高效开发工具链的设置。通过优化WSL性能和使用实用技巧,开发者可以轻松应对CSAPP实验中的环境配置问题,提升学习效率。

weixin_30443813的博客 302

FFmpeg源码分析: AVStream码流

在AVCodecContext结构体存储有AVStream数组,包含所有视频流、音频流、字幕流的信息。每个码流包含有时间基、时长、索引数组、编解码器参数、dts、元数据。其中,索引数组用于保存每帧数据包offset、size、duration、flag,用于seek定位某个时间戳对应的帧。

徐福记456 2万+

Type-C快充移动电源芯片避坑指南:IP5356配置全流程(支持PD3.0)

本文详细解析了英集芯IP5356芯片在Type-C快充移动电源中的应用,提供了从芯片选型、原理图设计、PCB布局到PD协议调试的全流程实战指南。文章重点剖析了如何避免散热、EMI及协议握手等常见设计陷阱,并分享了量产前的关键测试验证方法,旨在帮助硬件开发者高效打造稳定可靠的快充产品。

weixin_29235525的博客 885

《探秘 BME680温度湿度气压气体传感器模块:环境感知的卓越之选》:此文为AI自动生成

BME680 是一款由博世公司推出的集成环境传感器模块,在环境监测和物联网等领域中发挥着重要作用。它能够同时测量温度、湿度、气压和气体浓度等多个环境参数,为各种应用提供准确可靠的环境数据。该模块采用小巧的封装形式,便于集成到各种设备中,无论是智能家居、可穿戴设备还是工业监测系统,都能轻松适配。例如,在智能家居系统中,BME680 模块可以监测室内环境参数,如温度、湿度、气压和空气质量等。通过与智能家居控制器或智能手机应用程序的连接,用户可以实时了解室内环境状况,并根据需要进行调整。

zheng_ruiguo的专栏 1881

ffplay源码分析7-播放控制

本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10316225.html ffplay是FFmpeg工程自带的简单播放器,使用FFmpeg提供的解码器和SDL库进行视频播放。本文基于FFmpeg工程4.1版本进行分析,其中ffplay源码清单如下: https://github.com/FFmpeg/FFmpeg/blob/n4.1/f...

weixin_34419321的博客 173

fatal: unable to access ‘https://github.com/‘: Recv failure: Connection was reset 解决方案

本文主要介绍了fatal: unable to access ‘https://github.com/’: Recv failure: Connection was reset 解决方案,希望能对使用github的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 2万+

ffmpeg源码分析 (五)

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33709364的博客 384

05、CAN 总线拓扑结构详解,线型拓扑搭建要点

CAN总线拓扑与信号完整性优化 本文通过工程实践经验,深入剖析了CAN总线系统中信号完整性的关键要素。主要内容包括: 终端电阻的核心作用:必须严格在总线两端配置120Ω电阻,形成60Ω等效阻抗以匹配双绞线特性阻抗,避免信号反射导致的波形畸变。 阻抗匹配原理:解释了信号能量管理机制,指出阻抗不连续会导致信号反射,并通过示波器波形特征(如振铃现象)判断阻抗失配问题。 信号完整性多维要求:强调信号质量不仅涉及波形存在与否,还包括边沿斜率、共模电压范围等关键参数,这些直接影响通信可靠性。 工程实践建议:提供了终端电

2401_88858637的博客 191

点云结构面智能识别与裂隙网络分析系统

点云结构面智能识别系统摘要 本系统采用深度学习与传统几何算法融合的方法,实现岩石结构面的智能识别与分析。系统包含7个核心模块:点云预处理、结构面识别、分组分割、参数计算、粗糙度分析、裂隙网络生成和可视化。技术路线结合PointNet++深度学习架构与RANSAC、区域生长等传统算法,通过预处理→深度学习识别→几何精修→参数计算→网络构建的流程实现高精度分析。预处理模块实现点云降噪、下采样和法向量估计,深度学习模块基于改进的PointNet++架构进行特征提取和分类。系统支持多种点云格式输入,提供完整的结构面

huanghm88的专栏 355

ffplay.c源码分析【1】

ffplay.c源码分析【1】

m0_60259116的博客 590

​​手把手教你学PCIE--ATU 的 Bar 匹配模式与地址匹配模式详解​

摘要: ATU(地址转换单元)提供两种地址匹配模式:Bar匹配模式基于PCI设备的BAR寄存器自动映射虚拟地址(只需配置物理基址),适用于标准PCI设备DMA;地址匹配模式需显式配置虚拟与物理地址范围,适合自定义映射场景。核心区别在于匹配依据(BAR自动推导vs人工定义),Bar模式简化配置,地址模式更灵活。

MHD0815的博客 385

jikplayer源码线程分析-解封装线程

ijkplayer源码线程分析

WenYangFF的博客 607

物联网通信中NB-IoT、Cat.1、LTE-M该如何选择?

首先我们要确定我们产品的关键需求,例如:我们的设备是否对数据传输速率有较高的要求,有较高要求我们就需要选择较高传输速率的Cat.1来开发我们的产品。同时关于产品性能方面,我们对功耗、延迟、可靠性也会有所要求,例如我们的产品为移动端产品,不方便布线以及安装电源,那我们就会采用电池供电的方式,所以在选择时可以优先考虑低功耗产品,最终结合其他需求选择出合适的协议。首先,我们需求的产品是不同的,我们需要根据产品需求或项目需求来进行选择,NB-IoT、Cat.1、Cat.M都有属于自己的优势。

a1809032425的博客 1220

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

带着问题,再读ijkplayer源码

问题主流程上的区别缓冲区的设计内存管理的逻辑音视频播放方式音视频同步seek的问题:缓冲区flush、播放时间显示、k帧间距大时定位不准问题…stop时怎么释放资源,是否...

欢迎关注公众号:【码农突围】,回复9999,可以获取一份LeetCode刷题笔记 1738

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

解密FFmpeg播放track mode控制

上一篇文章(http://my.oschina.net/u/2336532/blog/400790)我们解决了在FFmpeg下如何处理H264和AAC的扩展数据,根据解出的NALU长度恢复了H264的起始码和AAC的ADTS头,这样一般来说播放是没有问题。本篇文章来谈谈如何实现基于FFmpeg的track mode控制,也就是如何用FFmpeg提供的功能来实现基本的seek、快进、快退。好了,废话...

weixin_34087301的博客 516

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

FFmpeg 4.3 音视频基础到工程应用

课程介绍1课程面向音视频行业的入门者,没有太多音视频基础或者是音视频零基础的同学2课程通过概念分析、代码试验、项目实战的方式当你真正理解音视频3提供直播答疑和学员作业代码评审,提升学员的代码能力4包含视频封装、编解码(H264、 H265、 硬件加速)、像素格式转换、视频渲染5实现接入多路RTSP网络摄像头,预览多路视频并完成硬盘录像机自动录制功能   

ffmpeg av_seek_frame

转载于:https://blog.csdn.net/xujaiwei/article/details/77651562 av_seek_frame使用时需要使用四个参数 av_seek_frame(fmt_ctx, -1 , 20 * AV_TIME_BASE, AVSEEK_FLAG_ANY); 参数一: fmt_ctx为容器内容; 参数二: 流索引, stream_index 参数三...

junlon2006的博客 1315

ffmpeg协议之接口篇之快进快退(av_seek_frame)

ffmpeg协议

qq_39466755的博客 2286
上一篇: 指针和引用的区别
下一篇: Leetcode 第 393 场周赛题解
UestcXiye
博客等级 码龄8年 9044粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址