音视频(二)之使用FFMpegSDK在C++代码中进行推流

前言

  • 上一篇文章我们介绍了如何使用FFMpeg工具进行推流。但如果要在我们的代码工程中,实现推流。就要下载FFMpegSDK包,调用相关API,在我们自己的程序中实现推流。

FFMpegSDK下载

  • 下载动态库文件
    在这里插入图片描述
  • 选择这个下载
    在这里插入图片描述

使用FFMpegSDK推流

  • 下载FFMpegSDK后,拷贝到我们的工程下
  • 目录结构如下
  •   ├─ bin
      ├─ doc
      ├─ include
      		├─ libavcodec
      		├─ libavdevice
      		├─ libavfilter
      		├─ libavformat
      		├─ libavutil
      		├─ libpostproc
      		├─ libswresample
      		└─ libswscale
      ├─ lib
      		└─pkgconfig
      ├─ src
      		└─ main.cpp
      ├─ build_x64
      └─ CMakeLists.txt
    
  • bin,doc,include,lib目录都是FFMpegSDK包中的内容,直接拷贝过来
  • src 在这个目录下创建一个源文件 main.cpp,在代码中调用FFMpeg提供的API,实现推流,内容如下
  •   extern "C"{
      #include "libavformat/avformat.h"
      #include "libavcodec/avcodec.h"
      #include "libavutil/time.h"
      };
      #include <iostream>
      
      
      void printErr(int errNum);
      
      static double r2d(AVRational r){
          return (r.num == 0 || r.den == 0) ? 0.0 : (double)r.num / (double)r.den;
      }
      
      int main(){
          //初始化网络库以及网络加密协议相关的库
          avformat_network_init();
      
          //打开文件, 解封文件头
          AVFormatContext *inContext = NULL;
          char *inFile = "001.mp4";
          int ret = avformat_open_input(&inContext, inFile, 0, 0);
          if(ret != 0){
              printErr(ret);
              return -1;
          }
      
          std::cout<<"avformat_open_input success"<<std::endl;
      
          //获取音视频流信息
          ret = avformat_find_stream_info(inContext, 0);
          if(ret != 0){
              printErr(ret);
              return -1;
          }
      
          std::cout<<"avformat_find_stream_info success"<<std::endl;
      
          //打印信息
          av_dump_format(inContext, 0, inFile, 0);
      
          //输出流
          AVFormatContext *outContext;
          char *outFile = "rtmp://192.168.206.131:10088/live";
          ret = avformat_alloc_output_context2(&outContext, 0, "flv", outFile);
          if(outContext == 0){
              printErr(ret);
              return -1;
          }
      
          std::cout<<"avformat_alloc_output_context2 success"<<std::endl;
      
          //配置输出流
          //遍历输入的AVStream
          for(int i = 0; i < inContext->nb_streams; i++){
              AVStream *outStream = avformat_new_stream(outContext, NULL);
              if(outStream == NULL){
                  printErr(-1);
                  return -1;
              }
      
              //复制配置信息
              ret = avcodec_parameters_copy(outStream->codecpar, inContext->streams[i]->codecpar);
              if(ret < 0){
                  printErr(ret);
                  return -1;
              }
      
              outStream->codecpar->codec_tag = 0;
          }
      
          //输出
          av_dump_format(outContext, 0, outFile, 1);
      
          //rtmp推流
          
          //打开io
          ret = avio_open(&outContext->pb, outFile, AVIO_FLAG_WRITE);
          if(ret != 0){
              printErr(ret);
              return -1;
          }
          std::cout<<"avio_open success"<<std::endl;
      
          //写入头信息
          ret = avformat_write_header(outContext, NULL);
          if(ret < 0){
              printErr(ret);
              return -1;
          }
          std::cout<<"avformat_write_header success"<<std::endl;
      
          //推流帧数据
          AVPacket avpkt;
          long long startTime = av_gettime();
          while(1){
              //读帧数据
              ret = av_read_frame(inContext, &avpkt);
              if(ret != 0){
                  break;
              }
      
              std::cout << avpkt.pts << std::endl;
      
              //计算转换pts dts
              AVRational inTime = inContext->streams[avpkt.stream_index]->time_base;
              AVRational outTime = outContext->streams[avpkt.stream_index]->time_base;
              avpkt.pts = av_rescale_q_rnd(avpkt.pts, inTime, outTime, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
              avpkt.dts = av_rescale_q_rnd(avpkt.dts, inTime, outTime, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
              avpkt.duration = av_rescale_q_rnd(avpkt.duration, inTime, outTime, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
              avpkt.pos = -1;
      
               //处理视频帧,控制推流速度
              if(inContext->streams[avpkt.stream_index]->codecpar->codec_type = AVMEDIA_TYPE_VIDEO){
                  //时间基数
                  AVRational tb = inContext->streams[avpkt.stream_index]->time_base;
                  
                  long long nowTime = av_gettime() - startTime;
                  long long dtsTime = avpkt.dts * (1000 * 1000 * r2d(tb));
                  if(dtsTime > nowTime){
                      av_usleep(dtsTime - nowTime);
                  }
                  
              }
      
      
              //发送数据
              ret = av_interleaved_write_frame(outContext, &avpkt);
              if(ret < 0){
                  printErr(ret);
                  return -1;
              }
      
              //释放
              av_packet_unref(&avpkt);
          }
      
          system("pause");
          return 0;
      }
      
      void printErr(int errNum){
          char errBuf[1024] = {0};
          av_strerror(errNum, errBuf, sizeof(errBuf));
          system("pause");
      }
    
  • CMakeLists.txt文件,实现编译,内容如下
  •   cmake_minimum_required (VERSION 3.5)
      project (FFmpegSDK)
      
      MESSAGE(STATUS "PROJECT_SOURCE_DIR" ${PROJECT_SOURCE_DIR})
      SET(SRC_LISTS ${PROJECT_SOURCE_DIR}/src/main.cpp)
         
      
      # 配置工程需要的头文件目录 
      include_directories(${PROJECT_SOURCE_DIR}/include)
      
      
      IF(WIN32)
      	set(CMAKE_C_FLAGS_RELEASE "/MD /MP /Od /Zi /EHsc")
      ENDIF()
      
      
      set(PRO_AVCODEC_LIB ${PROJECT_SOURCE_DIR}/lib/avcodec.lib)
      set(PRO_AVFORMAT_LIB ${PROJECT_SOURCE_DIR}/lib/avformat.lib)
      set(PRO_AVUTIL_LIB ${PROJECT_SOURCE_DIR}/lib/avutil.lib)
      
      
      ADD_EXECUTABLE(FFmpegSDK ${SRC_LISTS})
      TARGET_LINK_LIBRARIES(FFmpegSDK ${PRO_AVCODEC_LIB} ${PRO_AVFORMAT_LIB} ${PRO_AVUTIL_LIB})
    
  • 在build_x64目录下执行以下编译命令
    • cmake -G “Visual Studio 14 2015 Win64” …
    • cmake --build ./ --config Release
  • 编译成功后,在build_x86\Release目录下就会生成可执行程序FFmpegSDK.exe
  • 再把对应的库avcodec-60.dll、avformat-60.dll、avutil-58.dll、swresample-4.dll和要推送的视频文件001.mp4拷贝到build_x86\Release下。运行FFmpegSDK.exe就可以实现推流
  • 可以使用VLC工具来播放推送流
    在这里插入图片描述
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是使用FFmpeg实现RTSP推流C++代码示例: ```c++ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <errno.h> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> const char* RTSP_URL = "rtsp://192.168.1.1:8554/test"; // 要推流RTSP地址 const int FRAME_RATE = 25; // 视频帧率 const int VIDEO_WIDTH = 640; // 视频宽度 const int VIDEO_HEIGHT = 480; // 视频高度 int64_t start_time = 0; int interrupt_cb(void* ctx) { int timeout = 10; if (av_gettime_relative() - start_time > timeout * 1000 * 1000) { return 1; } return 0; } void* push_thread(void* arg) { AVFormatContext* fmt_ctx = NULL; AVStream* video_stream = NULL; AVCodecContext* codec_ctx = NULL; AVCodec* codec = NULL; AVFrame* frame = NULL; AVPacket pkt; int ret = 0; avformat_network_init(); // 打开输出RTSP流的上下文 avformat_alloc_output_context2(&fmt_ctx, NULL, "rtsp", RTSP_URL); if (!fmt_ctx) { printf("avformat_alloc_output_context2 failed\n"); goto end; } // 找到h.264编码器 codec = avcodec_find_encoder_by_name("libx264"); if (!codec) { printf("avcodec_find_encoder_by_name failed\n"); goto end; } // 创建视频流 video_stream = avformat_new_stream(fmt_ctx, codec); if (!video_stream) { printf("avformat_new_stream failed\n"); goto end; } video_stream->codecpar->codec_id = codec->id; video_stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; video_stream->codecpar->width = VIDEO_WIDTH; video_stream->codecpar->height = VIDEO_HEIGHT; video_stream->codecpar->format = AV_PIX_FMT_YUV420P; video_stream->codecpar->bit_rate = 500000; video_stream->codecpar->fps_num = FRAME_RATE; video_stream->codecpar->fps_den = 1; // 打开编码器 codec_ctx = avcodec_alloc_context3(codec); if (!codec_ctx) { printf("avcodec_alloc_context3 failed\n"); goto end; } avcodec_parameters_to_context(codec_ctx, video_stream->codecpar); if (avcodec_open2(codec_ctx, codec, NULL) < 0) { printf("avcodec_open2 failed\n"); goto end; } // 创建帧 frame = av_frame_alloc(); if (!frame) { printf("av_frame_alloc failed\n"); goto end; } frame->format = codec_ctx->pix_fmt; frame->width = VIDEO_WIDTH; frame->height = VIDEO_HEIGHT; if (av_frame_get_buffer(frame, 32) < 0) { printf("av_frame_get_buffer failed\n"); goto end; } // 打开输出流 if (avio_open(&fmt_ctx->pb, RTSP_URL, AVIO_FLAG_WRITE) < 0) { printf("avio_open failed\n"); goto end; } // 写输出流头部 avformat_write_header(fmt_ctx, NULL); // 推流 while (1) { // 生成测试图像 uint8_t* data[1]; int linesize[1]; int y_size = VIDEO_WIDTH * VIDEO_HEIGHT; data[0] = (uint8_t*)malloc(y_size * 3 / 2); memset(data[0], 0, y_size * 3 / 2); for (int i = 0; i < VIDEO_HEIGHT; i++) { memset(data[0] + i * VIDEO_WIDTH, i * 255 / (VIDEO_HEIGHT - 1), VIDEO_WIDTH); } for (int i = 0; i < VIDEO_HEIGHT / 2; i++) { memset(data[0] + y_size + i * VIDEO_WIDTH / 2, 128 + i * 127 / (VIDEO_HEIGHT / 2 - 1), VIDEO_WIDTH / 2); } // 将测试图像转换为AVFrame av_image_fill_arrays(frame->data, frame->linesize, data[0], codec_ctx->pix_fmt, VIDEO_WIDTH, VIDEO_HEIGHT, 32); frame->pts = av_rescale_q(av_gettime_relative() - start_time, (AVRational){1, AV_TIME_BASE}, video_stream->time_base); ret = avcodec_send_frame(codec_ctx, frame); if (ret < 0) { printf("avcodec_send_frame failed\n"); goto end; } while (ret >= 0) { ret = avcodec_receive_packet(codec_ctx, &pkt); if (ret < 0) { break; } av_packet_rescale_ts(&pkt, codec_ctx->time_base, video_stream->time_base); pkt.stream_index = video_stream->index; av_interleaved_write_frame(fmt_ctx, &pkt); av_packet_unref(&pkt); } free(data[0]); if (av_gettime_relative() - start_time > 30 * 1000 * 1000) { // 推流30秒后退出 break; } } // 写输出流尾部 av_write_trailer(fmt_ctx); end: if (frame) { av_frame_free(&frame); } if (codec_ctx) { avcodec_free_context(&codec_ctx); } if (fmt_ctx) { avio_close(fmt_ctx->pb); avformat_free_context(fmt_ctx); } return NULL; } int main(int argc, char* argv[]) { pthread_t pid; int ret = 0; // 初始化FFmpeg库 av_register_all(); avformat_network_init(); avcodec_register_all(); start_time = av_gettime_relative(); // 创建推流线程 ret = pthread_create(&pid, NULL, push_thread, NULL); if (ret != 0) { printf("pthread_create failed\n"); return -1; } // 等待推流线程退出 pthread_join(pid, NULL); return 0; } ``` 上述代码使用libx264编码器,生成测试图像并将其推流RTSP服务器。可以根据实际需要修改RTSP_URL、FRAME_RATE、VIDEO_WIDTH和VIDEO_HEIGHT等参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值