本文的示例将实现:读取PC摄像头视频数据并以RTMP协议发送为直播流。示例包含了
1、ffmpeg的libavdevice的使用
2、视频解码、编码、推流的基本流程
具有较强的综合性。
要使用libavdevice的相关函数,首先需要注册相关组件

  1. avdevice_register_all();

接下来我们要列出电脑中可用的dshow设备

  1. AVFormatContext *pFmtCtx = avformat_alloc_context();
  2. AVDeviceInfoList *device_info = NULL;
  3. AVDictionary* options = NULL;
  4. av_dict_set(&options, "list_devices", "true", 0);
  5. AVInputFormat *iformat = av_find_input_format("dshow");
  6. printf("Device Info=============\n");
  7. avformat_open_input(&pFmtCtx, "video=dummy", iformat, &options);
  8. printf("========================\n");

可以看到这里打开设备的步骤基本与打开文件的步骤相同,上面的代码中设置了AVDictionary,这样与在命令行中输入下列命令有相同的效果

  1. ffmpeg -list_devices true -f dshow -i dummy

以上语句得到的结果如下

这里我的电脑上只有一个虚拟摄像头软件虚拟出来的几个dshow设备,没有音频设备,所以有如上的结果。
需要说明的是,avdevice有一个avdevice_list_devices函数可以枚举系统的采集设备,包括设备名和设备描述,非常适合用于让用户选择要使用的设备,但是不支持dshow设备,所以这里没有使用它。
下一步就可以像打开普通文件一样将上面的具体设备名作为输入打开,并进行相应的初始化设置,如下

  1. av_register_all();
  2. //Register Device
  3. avdevice_register_all();
  4. avformat_network_init();
  5. //Show Dshow Device
  6. show_dshow_device();
  7. printf("\nChoose capture device: ");
  8. if (gets(capture_name) == 0)
  9. {
  10. printf("Error in gets()\n");
  11. return -1;
  12. }
  13. sprintf(device_name, "video=%s", capture_name);
  14. ifmt=av_find_input_format("dshow");
  15. //Set own video device's name
  16. if (avformat_open_input(&ifmt_ctx, device_name, ifmt, NULL) != 0){
  17. printf("Couldn't open input stream.(无法打开输入流)\n");
  18. return -1;
  19. }
  20. //input initialize
  21. if (avformat_find_stream_info(ifmt_ctx, NULL)<0)
  22. {
  23. printf("Couldn't find stream information.(无法获取流信息)\n");
  24. return -1;
  25. }
  26. videoindex = -1;
  27. for (i = 0; i<ifmt_ctx->nb_streams; i++)
  28. if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  29. {
  30. videoindex = i;
  31. break;
  32. }
  33. if (videoindex == -1)
  34. {
  35. printf("Couldn't find a video stream.(没有找到视频流)\n");
  36. return -1;
  37. }
  38. if (avcodec_open2(ifmt_ctx->streams[videoindex]->codec, avcodec_find_decoder(ifmt_ctx->streams[videoindex]->codec->codec_id), NULL)<0)
  39. {
  40. printf("Could not open codec.(无法打开解码器)\n");
  41. return -1;
  42. }

在选择了输入设备并进行相关初始化之后,需要对输出做相应的初始化。ffmpeg将网络协议和文件同等看待,同时因为使用RTMP协议进行传输,这里我们指定输出为flv格式,编码器使用H.264

  1. //output initialize
  2. avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", out_path);
  3. //output encoder initialize
  4. pCodec = avcodec_find_encoder(AV_CODEC_ID_H264);
  5. if (!pCodec){
  6. printf("Can not find encoder! (没有找到合适的编码器!)\n");
  7. return -1;
  8. }
  9. pCodecCtx=avcodec_alloc_context3(pCodec);
  10. pCodecCtx->pix_fmt = PIX_FMT_YUV420P;
  11. pCodecCtx->width = ifmt_ctx->streams[videoindex]->codec->width;
  12. pCodecCtx->height = ifmt_ctx->streams[videoindex]->codec->height;
  13. pCodecCtx->time_base.num = 1;
  14. pCodecCtx->time_base.den = 25;
  15. pCodecCtx->bit_rate = 400000;
  16. pCodecCtx->gop_size = 250;
  17. /* Some formats,for example,flv, want stream headers to be separate. */
  18. if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
  19. pCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
  20. //H264 codec param
  21. //pCodecCtx->me_range = 16;
  22. //pCodecCtx->max_qdiff = 4;
  23. //pCodecCtx->qcompress = 0.6;
  24. pCodecCtx->qmin = 10;
  25. pCodecCtx->qmax = 51;
  26. //Optional Param
  27. pCodecCtx->max_b_frames = 3;
  28. // Set H264 preset and tune
  29. AVDictionary *param = 0;
  30. av_dict_set(¶m, "preset", "fast", 0);
  31. av_dict_set(¶m, "tune", "zerolatency", 0);
  32. if (avcodec_open2(pCodecCtx, pCodec,¶m) < 0){
  33. printf("Failed to open encoder! (编码器打开失败!)\n");
  34. return -1;
  35. }
  36. //Add a new stream to output,should be called by the user before avformat_write_header() for muxing
  37. video_st = avformat_new_stream(ofmt_ctx, pCodec);
  38. if (video_st == NULL){
  39. return -1;
  40. }
  41. video_st->time_base.num = 1;
  42. video_st->time_base.den = 25;
  43. video_st->codec = pCodecCtx;
  44. //Open output URL,set before avformat_write_header() for muxing
  45. if (avio_open(&ofmt_ctx->pb,out_path, AVIO_FLAG_READ_WRITE) < 0){
  46. printf("Failed to open output file! (输出文件打开失败!)\n");
  47. return -1;
  48. }
  49. //Show some Information
  50. av_dump_format(ofmt_ctx, 0, out_path, 1);
  51. //Write File Header
  52. avformat_write_header(ofmt_ctx,NULL);

完成输入和输出的初始化之后,就可以正式开始解码和编码并推流的流程了,这里要注意,摄像头数据往往是RGB格式的,需要将其转换为YUV420P格式,所以要先做如下的准备工作

  1. //prepare before decode and encode
  2. dec_pkt = (AVPacket *)av_malloc(sizeof(AVPacket));
  3. //enc_pkt = (AVPacket *)av_malloc(sizeof(AVPacket));
  4. //camera data has a pix fmt of RGB,convert it to YUV420
  5. img_convert_ctx = sws_getContext(ifmt_ctx->streams[videoindex]->codec->width, ifmt_ctx->streams[videoindex]->codec->height,
  6. ifmt_ctx->streams[videoindex]->codec->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  7. pFrameYUV = avcodec_alloc_frame();
  8. uint8_t *out_buffer = (uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
  9. avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);

下面就可以正式开始解码、编码和推流了

  1. //start decode and encode
  2. int64_t start_time=av_gettime();
  3. while (av_read_frame(ifmt_ctx, dec_pkt) >= 0){
  4. if (exit_thread)
  5. break;
  6. av_log(NULL, AV_LOG_DEBUG, "Going to reencode the frame\n");
  7. pframe = av_frame_alloc();
  8. if (!pframe) {
  9. ret = AVERROR(ENOMEM);
  10. return -1;
  11. }
  12. //av_packet_rescale_ts(dec_pkt, ifmt_ctx->streams[dec_pkt->stream_index]->time_base,
  13. //  ifmt_ctx->streams[dec_pkt->stream_index]->codec->time_base);
  14. ret = avcodec_decode_video2(ifmt_ctx->streams[dec_pkt->stream_index]->codec, pframe,
  15. &dec_got_frame, dec_pkt);
  16. if (ret < 0) {
  17. av_frame_free(&pframe);
  18. av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
  19. break;
  20. }
  21. if (dec_got_frame){
  22. sws_scale(img_convert_ctx, (const uint8_t* const*)pframe->data, pframe->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
  23. enc_pkt.data = NULL;
  24. enc_pkt.size = 0;
  25. av_init_packet(&enc_pkt);
  26. ret = avcodec_encode_video2(pCodecCtx, &enc_pkt, pFrameYUV, &enc_got_frame);
  27. av_frame_free(&pframe);
  28. if (enc_got_frame == 1){
  29. //printf("Succeed to encode frame: %5d\tsize:%5d\n", framecnt, enc_pkt.size);
  30. framecnt++;
  31. enc_pkt.stream_index = video_st->index;
  32. //Write PTS
  33. AVRational time_base = ofmt_ctx->streams[videoindex]->time_base;//{ 1, 1000 };
  34. AVRational r_framerate1 = ifmt_ctx->streams[videoindex]->r_frame_rate;// { 50, 2 };
  35. AVRational time_base_q = { 1, AV_TIME_BASE };
  36. //Duration between 2 frames (us)
  37. int64_t calc_duration = (double)(AV_TIME_BASE)*(1 / av_q2d(r_framerate1));  //内部时间戳
  38. //Parameters
  39. //enc_pkt.pts = (double)(framecnt*calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base));
  40. enc_pkt.pts = av_rescale_q(framecnt*calc_duration, time_base_q, time_base);
  41. enc_pkt.dts = enc_pkt.pts;
  42. enc_pkt.duration = av_rescale_q(calc_duration, time_base_q, time_base); //(double)(calc_duration)*(double)(av_q2d(time_base_q)) / (double)(av_q2d(time_base));
  43. enc_pkt.pos = -1;
  44. //Delay
  45. int64_t pts_time = av_rescale_q(enc_pkt.dts, time_base, time_base_q);
  46. int64_t now_time = av_gettime() - start_time;
  47. if (pts_time > now_time)
  48. av_usleep(pts_time - now_time);
  49. ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
  50. av_free_packet(&enc_pkt);
  51. }
  52. }
  53. else {
  54. av_frame_free(&pframe);
  55. }
  56. av_free_packet(dec_pkt);
  57. }

解码部分比较简单,编码部分需要自己计算PTS、DTS,比较复杂。这里通过帧率计算PTS和DTS
首先通过帧率计算每两帧之间的时间间隔,但是要换算

ffmpeg超详细综合教程——摄像头直播的更多相关文章

  1. [转载] ffmpeg超详细综合教程——摄像头直播

    本文的示例将实现:读取PC摄像头视频数据并以RTMP协议发送为直播流.示例包含了 1.ffmpeg的libavdevice的使用 2.视频解码.编码.推流的基本流程 具有较强的综合性. 要使用liba ...

  2. VMware虚拟机下安装CentOS7.0超详细图文教程

    1.本文说明: 官方的第一个文本档案.也就是0_README.txt,大概意思是这样(渣翻译,但是大概意思还是有的). CentOS-7.0-1406-x86_64-DVD.iso:这个镜像(DVD ...

  3. MySql5.6 Window超详细安装教程

    林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 目录 一.安装包准备二.开始安装三.验证安装四.客户端工具 一.安装包准备 1.下载MySql ...

  4. MySql5.6Window超详细安装教程(msi 格式的安装)

    转自:红黑联盟  http://www.2cto.com/database/201506/409821.html 一.安装包准备 1.下载MySql5.6 http://www.mysql.com/ ...

  5. 在Ubuntu下进行XMR Monero(门罗币)挖矿的超详细图文教程

    大家都知道,最近挖矿什么的非常流行,于是我也在网上看了一些大神写的教程,以及跟一些大神请教过如何挖矿,但是网上的教程都感觉写得不够详细,于是今天我这里整理一个教程,希望能够帮到想要挖矿的朋友. 首先, ...

  6. 超详细实战教程丨多场景解析如何迁移Rancher Server

    本文转自Rancher Labs 作者介绍 王海龙,Rancher中国社区技术经理,负责Rancher中国技术社区的维护和运营.拥有6年的云计算领域经验,经历了OpenStack到Kubernetes ...

  7. 【建议收藏】Redis超详细入门教程大杂烩

    写在前边 Redis入门的整合篇.本篇也算是把2021年redis留下来的坑填上去,重新整合了一翻,点击这里,回顾我的2020与2021~一名大二后台练习生 NoSQL NoSQL(NoSQL = N ...

  8. 最新MATLAB R2021b超详细安装教程(附完整安装文件)

    摘要:本文详细介绍Matlab R2021b的安装步骤,为方便安装这里提供了完整安装文件的百度网盘下载链接供大家使用.从文件下载到证书安装本文都给出了每个步骤的截图,按照图示进行即可轻松完成安装使用. ...

  9. 最新MATLAB R2020b超详细安装教程(附完整安装文件)

    摘要:本文详细介绍Matlab R2020b的安装步骤,为方便安装这里提供了完整安装文件的百度网盘下载链接供大家使用.从文件下载到证书安装本文都给出了每个步骤的截图,按照图示进行即可轻松完成安装使用. ...

随机推荐

  1. PHP 开发环境搭建

    1. PHP (1) download PHP and extra the zip file to the folder “C:\tools\php” (2) add the path “;C:\to ...

  2. JSP数据交互(一)

    1.JSP内置对象 请求对象:request 输出对象:out 响应对象:response 应用程序对象:application 会话对象:session 页面上下文对象:pageContext 页面 ...

  3. jmeter-执行多个sql查询语句

    1.添加jdbc connection(注意标红部分) 2.添加jdbc request 3.查看结果树

  4. yii2:frontend/frontactoin curl生成

    yii2:frontend/frontactoin curl生成 想要覆写已存在文件,选中 “overwrite” 下的复选框然后点击 “Generator”.如果是新文件,只点击 “Generato ...

  5. 用fail2ban阻止ssh暴力破解root密码

    安装fail2ban工具来实现防暴力破解,防止恶意攻击,锁定恶意攻击IP. 1.如果是centos系统,先yum安装fail2ban [root@VM_152_184_centos /]# yum - ...

  6. CSS如何设置字体的类型、大小、颜色

    设计网页时,一般设置body的字体,让其他标签继承body的字体,这样设置特别方便,但是标题标签h1到h6和表单标签(input类型)是没有继承body的字体属性的,它们的字体需要单独设置. < ...

  7. Java8_00_资源帖

    一.官方资料 Java Platform Standard Edition 8 Documentation The Java™ Tutorials Java 8 API 二.精选资料 三.参考资料

  8. [JS学习笔记]Javascript事件阶段:捕获、目标、冒泡

    当你在浏览器上点击一个按钮时,点击的事件不仅仅发生在按钮上,同时点击的还有这个按钮的容器元素,甚至也点击了整个页面. 事件流 事件流描述了从页面接收事件的顺序,但在浏览器发展到第四代时,浏览器开发团队 ...

  9. h5启动原生APP总结

    许久没有写博客了,最近有个H5启动APP原生页面的需求,中间遇上一些坑,看了些网上的实现方案,特意来总结下 一.需要判断客户端的平台以及是否在微信浏览器中访问 1.客户端判断 在启动APP时,Andr ...

  10. Android onTouchEvent和setOnTouchListener中onTouch的区别

    OnTouchEvent()方法 是获取的对屏幕的各种操作,比如向左向右滑动,点击返回按钮等等. 属于一个宏观的屏幕触摸监控. OnTouchListener()方法 是获取某一个控件某一个View的 ...