草庐IT

RTSP视频推流方法汇总

红色石榴 2023-08-29 原文

1  基于rtsp-simple-server的视频推流

rtsp-simple-server是一个rtsp推流服务器,可以与gstreamer或ffmpeg结合进行推流。下载对应平台版本,直接运行即可。

1.1  使用gstreamer命令推流

1.1.1  RTSP视频推流:Camera

/usr/bin/gst-launch-1.0 v4l2src device=/dev/video0 ! videoconvert ! video/x-raw,width=640,height=480,framerate=30/1 ! timeoverlay ! videoconvert ! x264enc ! rtspclientsink location=rtsp://localhost:8554/mystream

1.1.2  RTSP视频推流:Camera简化

/usr/bin/gst-launch-1.0 v4l2src device=/dev/video0 ! timeoverlay ! videoconvert ! x264enc ! rtspclientsink location=rtsp://localhost:8554/mystream

1.1.3  RTSP视频推流:videotestsrc

/usr/bin/gst-launch-1.0 videotestsrc ! video/x-raw,width=1920,height=1080,framerate=30/1 ! timeoverlay ! videoconvert ! x264enc ! rtspclientsink location=rtsp://localhost:8554/mystream

1.2  使用opencv和ffmpeg推流(cuvid硬件编码)

    std::string rtsp_server_url = "rtsp://localhost:8554/live/test_green";

    std::stringstream command;

    command << "ffmpeg ";

    // infile options

    command << "-y "  // overwrite output files

            << "-an " // disable audio

            << "-hwaccel cuvid "

            << "-f rawvideo " // force format to rawvideo

            << "-vcodec rawvideo "  // force video rawvideo ('copy' to copy stream)

            << "-pix_fmt bgr24 "  // set pixel format to bgr24

            << "-s 1920x1080 "  // set frame size (WxH or abbreviation)

            << "-r 30 "; // set frame rate (Hz value, fraction or abbreviation)

    command << "-i - ";

    // outfile options

    command << "-c:v h264_nvenc "  // nvenc Video encoder

            << "-pix_fmt yuv420p "  // set pixel format to yuv420p

            << "-tune:v zerolatency "

            << "-preset fast " // set the h264_nvenc encoding preset to fast

            << "-f rtsp " // force format to flv for rtmp, rtsp for rtsp

            << rtsp_server_url;

    cv::Mat frame;

    // 在子进程中调用 ffmpeg 进行推流

    FILE *fp = nullptr;

    fp = popen(command.str().c_str(), "w");

    int id = 0;

    // 将 cv 读到的每一帧传入子进程

    if (fp != nullptr)

    {

        while (1)

        {

            frame = cv::imread("./2016-04-14-09-25-42.jpg");

            cv::String strFrameId;

            id = (++id) % 10000;

            QString idStr = QString("%1").arg(id);

            strFrameId = idStr.toStdString();

            cv::putText(frame, strFrameId, cv::Point(960,500), cv::HersheyFonts::FONT_ITALIC, 10, cv::Scalar(0,255,0), 3);

            if(frame.empty())

            {

                continue;

            }

            std::cout << frame.size() << std::endl;

            fwrite(frame.data, sizeof(char), frame.total() * frame.elemSize(), fp);

        }

        pclose(fp);

        return EXIT_SUCCESS;

    }

    else

    {

        return EXIT_FAILURE;

    }

1.3  使用opencv和ffmpeg推流(x264软件解码)

    std::string rtsp_server_url = "rtsp://localhost:8554/live/test_green";

    std::stringstream command;

    command << "ffmpeg ";

    // infile options

    command << "-y "  // overwrite output files

            << "-an " // disable audio

            << "-f rawvideo " // force format to rawvideo

            << "-vcodec rawvideo "  // force video rawvideo ('copy' to copy stream)

            << "-pix_fmt bgr24 "  // set pixel format to bgr24

            << "-s 1920x1080 "  // set frame size (WxH or abbreviation)

            << "-r 30 "; // set frame rate (Hz value, fraction or abbreviation)

    command << "-i - ";

    // outfile options

    command << "-c:v libx264 "  // Hyper fast Audio and Video encoder

      << "-pix_fmt yuv420p "  // set pixel format to yuv420p

      << "-tune:v zerolatency "

      << "-preset ultrafast " // set the libx264 encoding preset to ultrafast

      << "-f rtsp " // force format to flv for rtmp, rtsp for rtsp

      << rtsp_server_url;

    cv::Mat frame;

    // 在子进程中调用 ffmpeg 进行推流

    FILE *fp = nullptr;

    fp = popen(command.str().c_str(), "w");

    int id = 0;

    // 将 cv 读到的每一帧传入子进程

    if (fp != nullptr)

    {

        while (1)

        {

            frame = cv::imread("./2016-04-14-09-25-42.jpg");

            cv::String strFrameId;

            id = (++id) % 10000;

            QString idStr = QString("%1").arg(id);

            strFrameId = idStr.toStdString();

            cv::putText(frame, strFrameId, cv::Point(960,500), cv::HersheyFonts::FONT_ITALIC, 10, cv::Scalar(0,255,0), 3);

            if(frame.empty())

            {

                continue;

            }

            std::cout << frame.size() << std::endl;

            fwrite(frame.data, sizeof(char), frame.total() * frame.elemSize(), fp);

        }

        pclose(fp);

        return EXIT_SUCCESS;

    }

    else

    {

        return EXIT_FAILURE;

}

1.4  使用opencv和gstreamer推流

    cv::Mat frame;

    cv::String gst_str = "appsrc ! videoconvert ! x264enc ! rtspclientsink location=rtsp://localhost:8554/live/test_red";

    //cv::String gst_str = "appsrc ! videoconvert ! omxh264enc ! rtspclientsink location=rtsp://localhost:8554/live/test_red";//PC上没有omxh264enc插件,嵌入式平台有

    cv::VideoWriter video_writer(gst_str,cv::CAP_GSTREAMER, 0, 30, cv::Size(1920,1080));

    int id = 0;

    // 将 cv 读到的每一帧传入子进程

    while (1)

    {

        frame = cv::imread("./2016-04-14-09-25-42.jpg");

        cv::String strFrameId;

        id = (++id) % 10000;

        QString idStr = QString("%1").arg(id);

        strFrameId = idStr.toStdString();

        cv::putText(frame, strFrameId, cv::Point(960,500), cv::HersheyFonts::FONT_ITALIC, 10, cv::Scalar(0,255,0), 3);

        if(frame.empty())

        {

            continue;

        }

        std::cout << frame.size() << std::endl;

        //

        video_writer.write(frame);

    }

    return EXIT_SUCCESS;

2  opencv,x264,live555推流

2.1  原理

opencv将视频帧传递给x264进行编码,将输出的264数据流写入管道文件,管道文件放在live555的推流可执行文件live555MediaServer统一目录下。

管道文件为FIFO,写入(推流)和读出(拉流)需要同时进行,否则会阻塞。

2.2  示例代码

    cv::Mat BasePic = cv::imread("./2016-04-14-09-25-42.jpg");

    cv::Mat inputPic;

    cv::resize(BasePic, BasePic, cv::Size(1920, 1080));

    //使用YUV420编码

    cv::cvtColor(BasePic, BasePic, cv::COLOR_BGR2YUV_I420);

    //创建fifo

    ::unlink("/media/user/DATA/zhangchen/live555/live555-latest/live/mediaServer/demo.264");

    ::mkfifo("/media/user/DATA/zhangchen/live555/live555-latest/live/mediaServer/demo.264", O_CREAT | O_EXCL | 660);

    //打开fifo

    int fp_dst = ::open("/media/user/DATA/zhangchen/live555/live555-latest/live/mediaServer/demo.264", O_WRONLY);

    if(fp_dst == NULL)

    {

        ::close(fp_dst);

        return;

    }

    //H264编码设置

    int video_width = 1920;

    int video_height = 1080;

    int res = 0;

    //压缩编码前的图像

    x264_picture_t pic;

    x264_picture_t pic_out;

    //

    x264_t *h;

    int i_frame = 0;

    int i_frame_size = 0;

    //压缩编码后的码流数据

    x264_nal_t *nal;

    int i_nal;

    x264_param_t param;

    res = x264_param_default_preset(¶m, "veryfast", NULL);

    param.i_bitdepth = 8;//编码位数

    param.i_csp = X264_CSP_I420;//编码制式

    param.rc.i_qp_min = 36;//编码质量:越小,视频质量损失越小

    param.rc.i_qp_max = 40;

    param.rc.i_qp_step = 2;

    param.i_width = video_width;//分辨率

    param.i_height = video_height;

    param.i_fps_den = 1;//帧率

    param.i_fps_num = 30;

    param.i_keyint_max = 4;//设置IDR关键帧间隔

    param.i_keyint_min = 1;

    param.b_vfr_input = 0;//固定帧率

    param.b_repeat_headers = 1;//在每个关键帧前放置SPS/PPS

    param.b_annexb = 1;//在NAL单元前放置起始码

    res = x264_param_apply_profile(¶m, "baseline");

    res = x264_picture_alloc(&pic, param.i_csp, param.i_width, param.i_height);

    //打开编码器

    h = x264_encoder_open(¶m);

    if(h == 0)

    {

        return;

    }

    //输出头信息

/*

    i_frame_size = x264_encoder_headers(h, &nal, &i_nal);

    if(i_frame_size < 0)

    {

        return;

    }

    else if(i_frame_size)

    {

        if(!::write(fp_dst, nal->p_payload, i_frame_size))

        {

            return;

        }

    }

*/

    //对视频帧进行编码

    unsigned int luma_size = video_width * video_height;

    unsigned int chroma_size = luma_size / 4;

    for(;;i_frame++)

    {

        //读取输入帧YUV420

        inputPic = BasePic.clone();

        //绘制帧号

        int id = i_frame / 15;

        cv::String strFrameId;

        QString idStr = QString("%1").arg(id);

        strFrameId = idStr.toStdString();

        cv::putText(inputPic, strFrameId, cv::Point(960,500), cv::HersheyFonts::FONT_ITALIC, 10, cv::Scalar(255,0,0), 3);

        //

        memcpy(pic.img.plane[0], inputPic.data, luma_size);

        memcpy(pic.img.plane[1], inputPic.data + luma_size, chroma_size);

        memcpy(pic.img.plane[2], inputPic.data + luma_size + chroma_size, chroma_size);

        //

        pic.i_pts = i_frame;

        i_frame_size = x264_encoder_encode(h, &nal, &i_nal, &pic, &pic_out);

        if(i_frame_size < 0)

        {

            break;

        }

        else if(i_frame_size)

        {

            if(!::write(fp_dst, nal->p_payload, i_frame_size))

            {

                break;

            }

        }

        if(i_frame == (30 * 600))

        {

            break;

        }

    }

/*

    //Flush delayed frames

    while(x264_encoder_delayed_frames(h))

    {

        i_frame_size = x264_encoder_encode(h, &nal, &i_nal, NULL, &pic_out);

        if(i_frame_size < 0)

        {

            break;

        }

        else if(i_frame_size)

        {

            if(!::write(fp_dst, nal->p_payload, i_frame_size))

            {

                break;

            }

        }

    }

*/

    //关闭编码器

    x264_encoder_close(h);

    x264_picture_clean(&pic);

    ::close(fp_dst);

有关RTSP视频推流方法汇总的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  8. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  9. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  10. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

随机推荐