ONVIF之播放音视频

2017-10-24  本文已影响0人  ORCLee

前言

前面介绍了设备搜索、获取设备能力信息,在此基础上,本篇博客介绍如何播放音视频(ONVIF协议 + FFmpeg库 + SDL 2.0库)。

编码流程

1.调用 discoveryDevice()接口获取设备服务地址。
2.使用设备服务地址调用 getDeviceCapabilities() 接口获取媒体服务地址。
3.调用 getMediaProfiles()接口获取媒体配置信息(主要是获取Token)。
4.使用Token调用 getStreamUri()接口,获取RTSP地址。
5.使用RTSP地址调用 openRtsp()接口,播放音视频。

FFmpeg库

由于解码用到了FFmpeg库,所以简要介绍一下FFmpeg库的用法。

extern "C"
{
#include "FFmpeg/include/libavcodec/avcodec.h"
#include "FFmpeg/include/libavformat/avformat.h"
#include "FFmpeg/include/libswscale/swscale.h"
#include "FFmpeg/include/libavutil/imgutils.h"
};

SDL 2.0库

由于播放视频用到了SDL库,所以简要介绍一下SDL库的用法。

编码

获取媒体配置信息

/**
* @description: 获取媒体配置信息(主/辅码流配置信息)
*
* @brief getMediaProfiles
* @param[in] mediaXAddrs                媒体服务地址
* @param[in][out] deviceProVec          设备配置信息
* @return bool          返回true表示成功,其余查看soap错误码
*/
bool OnvifFunc::getMediaProfiles(std::string mediaXAddrs, std::vector<DEVICEPROFILE> &deviceProVec)
{
    // 初始化soap
    struct soap soap;
    soap_set_mode(&soap, SOAP_C_UTFSTRING);
    MediaBindingProxy media(&soap);
    // 设置超时(超过指定时间没有数据就退出)
    media.soap->recv_timeout = SOAP_SOCK_TIMEOUT;
    media.soap->send_timeout = SOAP_SOCK_TIMEOUT;
    media.soap->connect_timeout = SOAP_SOCK_TIMEOUT;

    setAuthInfo(media.soap, m_username, m_password);

    _trt__GetProfiles trt__GetProfiles;
    _trt__GetProfilesResponse trt__GetProfilesResponse;
    int iRet = media.GetProfiles(mediaXAddrs.c_str(), NULL, &trt__GetProfiles, trt__GetProfilesResponse);
    if (SOAP_OK == iRet)
    {
        for (std::vector<tt__Profile *>::const_iterator  iter = trt__GetProfilesResponse.Profiles.begin(); 
            iter != trt__GetProfilesResponse.Profiles.end(); ++iter)
        {
            DEVICEPROFILE devicePro;
            tt__Profile *ttProfile = *iter;
            // 配置文件Token
            if (!ttProfile->token.empty())
            {
                devicePro.token = ttProfile->token;
            }   
            // 视频编码器配置信息
            if (NULL != ttProfile->VideoEncoderConfiguration)
            {
                // 视频编码Token
                if (!ttProfile->VideoEncoderConfiguration->token.empty())
                    devicePro.venc.token = ttProfile->VideoEncoderConfiguration->token;
                // 视频编码器分辨率
                if (NULL != ttProfile->VideoEncoderConfiguration->Resolution)
                {
                    devicePro.venc.Height = ttProfile->VideoEncoderConfiguration->Resolution->Height;
                    devicePro.venc.Width = ttProfile->VideoEncoderConfiguration->Resolution->Width;
                }
            }
            deviceProVec.push_back(devicePro);
        }
        // 清理变量
        media.destroy();
        return true;
    }
    // 清理变量
    media.destroy();
    return false;
}

获取设备码流地址(RTSP)

/**
* @description: 获取设备码流地址(RTSP)
*
* @brief getStreamUri
* @param[in] mediaXAddrs            媒体服务地址
* @param[in] profileToken           唯一标识设备配置文件的令牌字符串
* @param[in][out] uri               码流地址
* @return bool          返回true表示成功,其余查看soap错误码
*/
bool OnvifFunc::getStreamUri(std::string mediaXAddrs, std::string profileToken, std::string &uri)
{
    // 初始化soap
    struct soap soap;
    soap_set_mode(&soap, SOAP_C_UTFSTRING);
    MediaBindingProxy media(&soap);
    // 设置超时(超过指定时间没有数据就退出)
    media.soap->recv_timeout = SOAP_SOCK_TIMEOUT;
    media.soap->send_timeout = SOAP_SOCK_TIMEOUT;
    media.soap->connect_timeout = SOAP_SOCK_TIMEOUT;

    _trt__GetStreamUri trt__GetStreamUri;
    _trt__GetStreamUriResponse trt__GetStreamUriResponse;
    tt__StreamSetup ttStreamSetup;
    
    tt__Transport ttTransport;
    ttStreamSetup.Stream = tt__StreamType__RTP_Unicast;
    ttStreamSetup.Transport = &ttTransport;
    ttStreamSetup.Transport->Protocol = tt__TransportProtocol__RTSP;
    ttStreamSetup.Transport->Tunnel = NULL;

    trt__GetStreamUri.StreamSetup = &ttStreamSetup;
    trt__GetStreamUri.ProfileToken = profileToken;
    setAuthInfo(media.soap, m_username, m_password);
    int iRet = media.GetStreamUri(mediaXAddrs.c_str(), NULL, &trt__GetStreamUri, trt__GetStreamUriResponse);
    if (SOAP_OK == iRet)
    {
        if (NULL != trt__GetStreamUriResponse.MediaUri)
        {
            if (!trt__GetStreamUriResponse.MediaUri->Uri.empty())
                uri = trt__GetStreamUriResponse.MediaUri->Uri;
        }
        // 清理变量
        media.destroy();
        return true;
    }
    // 清理变量
    media.destroy();
    return false;
}

构造带有认证信息的URI地址(有的IPC要求认证)

/**
* @description: 构造带有认证信息的URI地址
*
* @brief makeUriWithauth
* @param[in][out] uri           码流地址
* @param[in] username           用户名
* @param[in] password           密码
* @return bool          返回true表示成功,其余查看soap错误码
*/
bool OnvifFunc::makeUriWithauth(std::string &uri, std::string username, std::string password)
{
    assert(!uri.empty());
    assert(!username.empty());
    assert(!password.empty());

    std::string str = username + ":" + password + "@";
    size_t pos = uri.find("//");
    uri.insert(pos + 2, str);
    
    return true;
}

播放RTSP流

/**
* @description: 播放RTSP流
*
* @brief openRtsp
* @param[in] rtsp               码流地址(带认证)
* @param[in] hwnd               窗口句柄
* @param[in] width              窗口的宽度
* @param[in] height             窗口的高度
* @return bool          返回true表示成功,返回false表示失败
*/
bool OnvifFunc::openRtsp(std::string rtsp, HWND hwnd, int width, int height)
{
    AVFormatContext *pFormatCtx;
    int i, videoindex = -1;
    AVCodecContext  *pCodecCtx;
    AVCodec *pCodec;
    AVFrame *pFrame, *pFrameYUV;
    uint8_t *out_buffer;
    AVPacket *packet;
    int ret;
    struct SwsContext *img_convert_ctx;

    // SDL
    int screen_w, screen_h;
    SDL_Window *screen;
    SDL_Renderer* sdlRenderer;
    SDL_Texture* sdlTexture;
    SDL_Rect sdlRect;
    SDL_Thread *videoTid;
    SDL_Event event;

    av_register_all();
    avformat_network_init();
    pFormatCtx = avformat_alloc_context();
    pCodecCtx = avcodec_alloc_context3(NULL);

    if (avformat_open_input(&pFormatCtx, rtsp.c_str(), NULL, NULL) != 0)
        return false;
    if (avformat_find_stream_info(pFormatCtx, NULL) < 0)
        return false;
    for (i = 0; i < pFormatCtx->nb_streams; i++)
        if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            videoindex = i;
            break;
        }
    if (-1 == videoindex) {
        return false;
    }

    ret = avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[videoindex]->codecpar);
    if (ret < 0)
        return false;
    pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
    if (NULL == pCodec)
        return false;
    if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0)
        return false;

    pFrame = av_frame_alloc();
    pFrameYUV = av_frame_alloc();
    out_buffer = (uint8_t *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1));
    av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
    packet = (AVPacket *)av_malloc(sizeof(AVPacket));
    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
        width, height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER))
        return false;

    screen_w = width;
    screen_h = height;

    screen = SDL_CreateWindowFrom(static_cast<void *>(hwnd));
    if (!screen)
        return false;

    sdlRenderer = SDL_CreateRenderer(screen, -1, 0);
    //IYUV: Y + U + V  (3 planes)
    //YV12: Y + V + U  (3 planes)
    sdlTexture = SDL_CreateTexture(sdlRenderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, width, height);

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

    videoTid = SDL_CreateThread(sfp_refresh_thread, NULL, NULL);

    for (;;)
    {
        // 等待事件
        SDL_WaitEvent(&event);
        if (SFM_REFRESH_EVENT == event.type)
        {
            if (0 == av_read_frame(pFormatCtx, packet)) {
                if (packet->stream_index == videoindex) {
                    ret = avcodec_send_packet(pCodecCtx, packet);
                    if (ret != 0)
                        return false;
                    ret = avcodec_receive_frame(pCodecCtx, pFrame);
                    if (ret != 0)
                        return false;
                    sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
                        pFrameYUV->data, pFrameYUV->linesize);

                    SDL_UpdateYUVTexture(sdlTexture, &sdlRect,
                        pFrameYUV->data[0], pFrameYUV->linesize[0],
                        pFrameYUV->data[1], pFrameYUV->linesize[1],
                        pFrameYUV->data[2], pFrameYUV->linesize[2]);
                    SDL_RenderClear(sdlRenderer);
                    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, &sdlRect);
                    SDL_RenderPresent(sdlRenderer);
                }
                av_packet_unref(packet);
            }
            else
            {
                // 退出线程
                g_global.m_threadExit = 1;
                break;
            }
        }
        else if (SFM_BREAK_EVENT == event.type)
            break;
    }
    sws_freeContext(img_convert_ctx);

    SDL_Quit();

    av_frame_free(&pFrameYUV);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);
    avcodec_free_context(&pCodecCtx);

    return true;
}

上述代码均为核心代码。

参考

上一篇 下一篇

猜你喜欢

热点阅读