最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Go語言開發(fā)瀏覽器視頻流rtsp轉(zhuǎn)webrtc播放

 更新時(shí)間:2022年04月28日 16:30:24   作者:xiaoyaoyou.xyz  
這篇文章主要為大家介紹了Go語言開發(fā)瀏覽器視頻流rtsp轉(zhuǎn)webrtc播放的過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

1. 前言

前面我們測(cè)試了rtsp轉(zhuǎn)hls方式,發(fā)現(xiàn)延遲比較大,不太適合我們的使用需求。接下來我們?cè)囈幌聎ebrtc的方式看下使用情況。

綜合考慮下來,我們最好能找到一個(gè)go作為后端,前端兼容性較好的前后端方案來處理webrtc,這樣我們就可以結(jié)合我們之前的cgo+onvif+gSoap實(shí)現(xiàn)方案來獲取rtsp流,并且可以根據(jù)已經(jīng)實(shí)現(xiàn)的ptz、預(yù)置點(diǎn)等功能接口做更多的擴(kuò)展。

2. rtsp轉(zhuǎn)webRTC

如下是找到的一個(gè)比較合適的開源方案,前端使用了jQuery、bootstrap等,后端使用go+gin來實(shí)現(xiàn)并將rtsp流解析轉(zhuǎn)換為webRTC協(xié)議提供http相關(guān)接口給到前端,通過config.json配置rtsp地址和stun地址:

點(diǎn)擊下載

此外,還帶有stun,可以自行配置stun地址,便于進(jìn)行內(nèi)網(wǎng)穿透。

初步測(cè)試幾乎看不出來延遲,符合預(yù)期,使用的jQuery+bootstrap+go+gin做的web,也符合我們的項(xiàng)目使用情況。

3. 初步測(cè)試結(jié)果

結(jié)果如下:

4. 結(jié)合我們之前的onvif+gSoap+cgo的方案做修改

我們?cè)诖隧?xiàng)目的基礎(chǔ)上,結(jié)合我們之前研究的onvif+cgo+gSoap的方案,將onvif獲取到的相關(guān)數(shù)據(jù)提供接口到web端,增加ptz、調(diào)焦、縮放等功能。

我們?cè)趆ttp.go中添加新的post接口:HTTPAPIServerStreamPtz來進(jìn)行ptz和HTTPAPIServerStreamPreset進(jìn)行預(yù)置點(diǎn)相關(guān)操作。

以下是部分代碼,沒有做太多的優(yōu)化,也僅僅實(shí)現(xiàn)了ptz、調(diào)焦和縮放,算是打通了通路,具體項(xiàng)目需要可以再做優(yōu)化。

4.1 go后端修改

增加了新的接口,并將之前cgo+onvif+gSoap的內(nèi)容結(jié)合了進(jìn)來,項(xiàng)目整體沒有做更多的優(yōu)化,只是為了演示,提供一個(gè)思路:

http.go(增加了兩個(gè)post接口ptz和preset,采用cgo方式處理):

package main
/*
#cgo CFLAGS: -I ./ -I /usr/local/
#cgo LDFLAGS: -L ./build -lc_onvif_static -lpthread -ldl -lssl -lcrypto
#include "client.h"
#include "malloc.h"
*/
import "C"
import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "os"
    "sort"
    "strconv"
    "time"
    "unsafe"
    "github.com/deepch/vdk/av"
    webrtc "github.com/deepch/vdk/format/webrtcv3"
    "github.com/gin-gonic/gin"
)
type JCodec struct {
    Type string
}
func serveHTTP() {
    gin.SetMode(gin.ReleaseMode)
    router := gin.Default()
    router.Use(CORSMiddleware())
    if _, err := os.Stat("./web"); !os.IsNotExist(err) {
        router.LoadHTMLGlob("web/templates/*")
        router.GET("/", HTTPAPIServerIndex)
        router.GET("/stream/player/:uuid", HTTPAPIServerStreamPlayer)
    }
    router.POST("/stream/receiver/:uuid", HTTPAPIServerStreamWebRTC)
    //增加新的post接口
    router.POST("/stream/ptz/", HTTPAPIServerStreamPtz)
    router.POST("/stream/preset/", HTTPAPIServerStreamPreset)
    router.GET("/stream/codec/:uuid", HTTPAPIServerStreamCodec)
    router.POST("/stream", HTTPAPIServerStreamWebRTC2)
    router.StaticFS("/static", http.Dir("web/static"))
    err := router.Run(Config.Server.HTTPPort)
    if err != nil {
        log.Fatalln("Start HTTP Server error", err)
    }
}
//HTTPAPIServerIndex  index
func HTTPAPIServerIndex(c *gin.Context) {
    _, all := Config.list()
    if len(all) > 0 {
        c.Header("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store")
        c.Header("Access-Control-Allow-Origin", "*")
        c.Redirect(http.StatusMovedPermanently, "stream/player/"+all[0])
    } else {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "port":    Config.Server.HTTPPort,
            "version": time.Now().String(),
        })
    }
}
//HTTPAPIServerStreamPlayer stream player
func HTTPAPIServerStreamPlayer(c *gin.Context) {
    _, all := Config.list()
    sort.Strings(all)
    c.HTML(http.StatusOK, "player.tmpl", gin.H{
        "port":     Config.Server.HTTPPort,
        "suuid":    c.Param("uuid"),
        "suuidMap": all,
        "version":  time.Now().String(),
    })
}
//HTTPAPIServerStreamCodec stream codec
func HTTPAPIServerStreamCodec(c *gin.Context) {
    if Config.ext(c.Param("uuid")) {
        Config.RunIFNotRun(c.Param("uuid"))
        codecs := Config.coGe(c.Param("uuid"))
        if codecs == nil {
            return
        }
        var tmpCodec []JCodec
        for _, codec := range codecs {
            if codec.Type() != av.H264 && codec.Type() != av.PCM_ALAW && codec.Type() != av.PCM_MULAW && codec.Type() != av.OPUS {
                log.Println("Codec Not Supported WebRTC ignore this track", codec.Type())
                continue
            }
            if codec.Type().IsVideo() {
                tmpCodec = append(tmpCodec, JCodec{Type: "video"})
            } else {
                tmpCodec = append(tmpCodec, JCodec{Type: "audio"})
            }
        }
        b, err := json.Marshal(tmpCodec)
        if err == nil {
			_, err = c.Writer.Write(b)
			if err != nil {
				log.Println("Write Codec Info error", err)
				return
			}
		}
	}
}
//HTTPAPIServerStreamWebRTC stream video over WebRTC
func HTTPAPIServerStreamWebRTC(c *gin.Context) {
	if !Config.ext(c.PostForm("suuid")) {
		log.Println("Stream Not Found")
		return
	}
	Config.RunIFNotRun(c.PostForm("suuid"))
	codecs := Config.coGe(c.PostForm("suuid"))
	if codecs == nil {
		log.Println("Stream Codec Not Found")
		return
	}
	var AudioOnly bool
	if len(codecs) == 1 && codecs[0].Type().IsAudio() {
		AudioOnly = true
	}
	muxerWebRTC := webrtc.NewMuxer(webrtc.Options{ICEServers: Config.GetICEServers(), ICEUsername: Config.GetICEUsername(), ICECredential: Config.GetICECredential(), PortMin: Config.GetWebRTCPortMin(), PortMax: Config.GetWebRTCPortMax()})
	answer, err := muxerWebRTC.WriteHeader(codecs, c.PostForm("data"))
	if err != nil {
		log.Println("WriteHeader", err)
		return
	}
	_, err = c.Writer.Write([]byte(answer))
	if err != nil {
		log.Println("Write", err)
		return
	}
	go func() {
		cid, ch := Config.clAd(c.PostForm("suuid"))
		defer Config.clDe(c.PostForm("suuid"), cid)
		defer muxerWebRTC.Close()
		var videoStart bool
		noVideo := time.NewTimer(10 * time.Second)
		for {
			select {
			case <-noVideo.C:
				log.Println("noVideo")
				return
			case pck := <-ch:
				if pck.IsKeyFrame || AudioOnly {
					noVideo.Reset(10 * time.Second)
					videoStart = true
				}
				if !videoStart && !AudioOnly {
					continue
				}
				err = muxerWebRTC.WritePacket(pck)
				if err != nil {
					log.Println("WritePacket", err)
					return
				}
			}
		}
	}()
}
func HTTPAPIServerStreamPtz(c *gin.Context) {
	action := c.PostForm("action")
	direction, err := strconv.Atoi(action)
	if err != nil {
		log.Println(err)
		return
	}
	var soap C.P_Soap
	soap = C.new_soap(soap)
	username := C.CString("admin")
	password := C.CString("admin")
	serviceAddr := C.CString("http://40.40.40.101:80/onvif/device_service")
	C.get_device_info(soap, username, password, serviceAddr)
	mediaAddr := [200]C.char{}
	C.get_capabilities(soap, username, password, serviceAddr, &mediaAddr[0])
	profileToken := [200]C.char{}
	C.get_profiles(soap, username, password, &profileToken[0], &mediaAddr[0])
	videoSourceToken := [200]C.char{}
	C.get_video_source(soap, username, password, &videoSourceToken[0], &mediaAddr[0])
	switch direction {
	case 0:
		break
	case 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11:
		C.ptz(soap, username, password, C.int(direction), C.float(0.5), &profileToken[0], &mediaAddr[0])
	case 12, 13, 14:
		C.focus(soap, username, password, C.int(direction), C.float(0.5), &videoSourceToken[0], &mediaAddr[0])
	default:
		fmt.Println("Unknown direction.")
	}
	C.del_soap(soap)
	C.free(unsafe.Pointer(username))
	C.free(unsafe.Pointer(password))
	C.free(unsafe.Pointer(serviceAddr))
	c.JSON(http.StatusOK, gin.H{"message":"success"})
}
func HTTPAPIServerStreamPreset(c *gin.Context) {
	var soap C.P_Soap
	soap = C.new_soap(soap)
	username := C.CString("admin")
	password := C.CString("admin")
	serviceAddr := C.CString("http://40.40.40.101:80/onvif/device_service")
	C.get_device_info(soap, username, password, serviceAddr)
	mediaAddr := [200]C.char{}
	C.get_capabilities(soap, username, password, serviceAddr, &mediaAddr[0])
	profileToken := [200]C.char{}
	C.get_profiles(soap, username, password, &profileToken[0], &mediaAddr[0])
	videoSourceToken := [200]C.char{}
	C.get_video_source(soap, username, password, &videoSourceToken[0], &mediaAddr[0])
	action := c.PostForm("action")
	presetAction, err := strconv.Atoi(action)
	if err != nil {
		log.Println(err)
		return
	}
	fmt.Println("請(qǐng)輸入數(shù)字進(jìn)行preset,1-4分別代表查詢、設(shè)置、跳轉(zhuǎn)、刪除預(yù)置點(diǎn);退出輸入0:")
	switch presetAction {
	case 0:
		break
	case 1:
		C.preset(soap, username, password, C.int(presetAction), nil, nil, &profileToken[0], &mediaAddr[0])
	case 2:
		fmt.Println("請(qǐng)輸入要設(shè)置的預(yù)置點(diǎn)token信息:")
		presentToken := ""
		_, _ = fmt.Scanln(&presentToken)
		fmt.Println("請(qǐng)輸入要設(shè)置的預(yù)置點(diǎn)name信息長(zhǎng)度不超過200:")
		presentName := ""
		_, _ = fmt.Scanln(&presentName)
		C.preset(soap, username, password, C.int(presetAction), C.CString(presentToken), C.CString(presentName), &profileToken[0], &mediaAddr[0])
	case 3:
		fmt.Println("請(qǐng)輸入要跳轉(zhuǎn)的預(yù)置點(diǎn)token信息:")
		presentToken := ""
		_, _ = fmt.Scanln(&presentToken)
		C.preset(soap, username, password, C.int(presetAction), C.CString(presentToken), nil, &profileToken[0], &mediaAddr[0])
	case 4:
		fmt.Println("請(qǐng)輸入要?jiǎng)h除的預(yù)置點(diǎn)token信息:")
		presentToken := ""
		_, _ = fmt.Scanln(&presentToken)
		C.preset(soap, username, password, C.int(presetAction), C.CString(presentToken), nil, &profileToken[0], &mediaAddr[0])
	default:
		fmt.Println("unknown present action.")
		break
	}
	C.del_soap(soap)
	C.free(unsafe.Pointer(username))
	C.free(unsafe.Pointer(password))
	C.free(unsafe.Pointer(serviceAddr))
	c.JSON(http.StatusOK, gin.H{"message":"success"})
}
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, x-access-token")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
		c.Header("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.Next()
	}
}
type Response struct {
	Tracks []string `json:"tracks"`
	Sdp64  string   `json:"sdp64"`
}
type ResponseError struct {
	Error string `json:"error"`
}
func HTTPAPIServerStreamWebRTC2(c *gin.Context) {
	url := c.PostForm("url")
	if _, ok := Config.Streams[url]; !ok {
		Config.Streams[url] = StreamST{
			URL:      url,
			OnDemand: true,
			Cl:       make(map[string]viewer),
		}
	}
	Config.RunIFNotRun(url)
	codecs := Config.coGe(url)
	if codecs == nil {
		log.Println("Stream Codec Not Found")
		c.JSON(500, ResponseError{Error: Config.LastError.Error()})
		return
	}
	muxerWebRTC := webrtc.NewMuxer(
		webrtc.Options{
			ICEServers: Config.GetICEServers(),
			PortMin:    Config.GetWebRTCPortMin(),
			PortMax:    Config.GetWebRTCPortMax(),
		},
	)
	sdp64 := c.PostForm("sdp64")
	answer, err := muxerWebRTC.WriteHeader(codecs, sdp64)
	if err != nil {
		log.Println("Muxer WriteHeader", err)
		c.JSON(500, ResponseError{Error: err.Error()})
		return
	}
	response := Response{
		Sdp64: answer,
	}
	for _, codec := range codecs {
		if codec.Type() != av.H264 &&
			codec.Type() != av.PCM_ALAW &&
			codec.Type() != av.PCM_MULAW &&
			codec.Type() != av.OPUS {
			log.Println("Codec Not Supported WebRTC ignore this track", codec.Type())
			continue
		}
		if codec.Type().IsVideo() {
			response.Tracks = append(response.Tracks, "video")
		} else {
			response.Tracks = append(response.Tracks, "audio")
		}
	}
	c.JSON(200, response)
	AudioOnly := len(codecs) == 1 && codecs[0].Type().IsAudio()
	go func() {
		cid, ch := Config.clAd(url)
		defer Config.clDe(url, cid)
		defer muxerWebRTC.Close()
		var videoStart bool
		noVideo := time.NewTimer(10 * time.Second)
		for {
			select {
			case <-noVideo.C:
				log.Println("noVideo")
				return
			case pck := <-ch:
				if pck.IsKeyFrame || AudioOnly {
					noVideo.Reset(10 * time.Second)
					videoStart = true
				}
				if !videoStart && !AudioOnly {
					continue
				}
				err = muxerWebRTC.WritePacket(pck)
				if err != nil {
					log.Println("WritePacket", err)
					return
				}
			}
		}
	}()
}

4.2 前端修改

對(duì)于goland我們首先將.tmpl文件通過右鍵標(biāo)記為html格式,然后再修改時(shí)就會(huì)有前端語法支持和補(bǔ)全支持,便于修改,否則默認(rèn)是識(shí)別為文本的,之后我們修改player.tmpl和app.js,在player.tmpl中添加一些ptz的按鈕并通過js與前后端進(jìn)行數(shù)據(jù)交互:

player.tmpl:

<html>
<meta http-equiv="Expires" content="0">
<meta http-equiv="Last-Modified" content="0">
<meta http-equiv="Cache-Control" content="no-cache, mustrevalidate">
<meta http-equiv="Pragma" content="no-cache">
<link rel="stylesheet" href="../../static/css/bootstrap.min.css" rel="external nofollow" >
<link rel="stylesheet" href="../../static/css/shanxing.css" rel="external nofollow" >
<script type="text/javascript" src="../../static/js/jquery-3.4.1.min.js"></script>
<script src="../../static/js/bootstrap.min.js"></script>
<script src="../../static/js/adapter-latest.js"></script>
<h2 align=center>
    Play Stream {{ .suuid }}<br>
</h2>
<div class="container">
    <div class="row">
        <div class="col-3">
            <div class="list-group">
                {{ range .suuidMap }}
                <a href="{{ . }}" rel="external nofollow"  id="{{ . }}" name="{{ . }}" class="list-group-item list-group-item-action">{{ . }}</a>
                {{ end }}
                </br>
                <div class="sector">
                    <div class="box s1" id="top" onclick="funTopClick()">
                    </div>
                    <div class="box s2" id="right" onclick="funRightClick()">
                    </div>
                    <div class="box s3" id="down" onclick="funDownClick()">
                    </div>
                    <div class="box s4" id="left" onclick="funLeftClick()">
                    </div>
                    <div class="center" id="stop" onclick="funStopClick()">
                    </div>
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-default" onclick="funZoomClick(10)">縮放+</button>
                    <button type="button" class="btn btn-default" onclick="funZoomClick(11)">縮放-</button>
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-default" onclick="funFocusClick(12)">調(diào)焦+</button>
                    <button type="button" class="btn btn-default" onclick="funFocusClick(13)">調(diào)焦-</button>
                    <button type="button" class="btn btn-default" onclick="funFocusClick(14)">停止調(diào)焦</button>
                </div>
            </div>
        </div>
        <div class="col">
            <input type="hidden" name="suuid" id="suuid" value="{{ .suuid }}">
            <input type="hidden" name="port" id="port" value="{{ .port }}">
            <input type="hidden" id="localSessionDescription" readonly="true">
            <input type="hidden" id="remoteSessionDescription">
            <div id="remoteVideos">
                <video style="width:600px" id="videoElem" autoplay muted controls></video>
            </div>
            <div id="div"></div>
        </div>
    </div>
</div>
<script type="text/javascript" src="../../static/js/app.js?ver={{ .version }}"></script>
</html>

app.js:

let stream = new MediaStream();
let suuid = $('#suuid').val();
let config = {
  iceServers: [{
    urls: ["stun:stun.l.google.com:19302"]
  }]
};
const pc = new RTCPeerConnection(config);
pc.onnegotiationneeded = handleNegotiationNeededEvent;
let log = msg => {
  document.getElementById('div').innerHTML += msg + '<br>'
}
pc.ontrack = function(event) {
  stream.addTrack(event.track);
  videoElem.srcObject = stream;
  log(event.streams.length + ' track is delivered')
}
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
async function handleNegotiationNeededEvent() {
  let offer = await pc.createOffer();
  await pc.setLocalDescription(offer);
  getRemoteSdp();
}
$(document).ready(function() {
  $('#' + suuid).addClass('active');
  getCodecInfo();
});
function getCodecInfo() {
  $.get("../codec/" + suuid, function(data) {
    try {
      data = JSON.parse(data);
    } catch (e) {
      console.log(e);
    } finally {
      $.each(data,function(index,value){
        pc.addTransceiver(value.Type, {
          'direction': 'sendrecv'
        })
      })
    }
  });
}
let sendChannel = null;
function getRemoteSdp() {
  $.post("../receiver/"+ suuid, {
    suuid: suuid,
    data: btoa(pc.localDescription.sdp)
  }, function(data) {
    try {
      pc.setRemoteDescription(new RTCSessionDescription({
        type: 'answer',
        sdp: atob(data)
      }))
    } catch (e) {
      console.warn(e);
    }
  });
}
function ptz(direction) {
  $.post("../ptz/", direction, function(data, status){
    console.debug("Data: " + data + "nStatus: " + status);
  });
}
function funTopClick() {
  console.debug("top click");
  ptz("action=1")
}
function funDownClick() {
  console.debug("down click");
  ptz("action=2")
}
function funLeftClick() {
  console.debug("left click");
  ptz("action=3")
}
function funRightClick() {
  console.debug("right click");
  ptz("action=4")
}
function funStopClick() {
  console.debug("stop click");
  ptz("action=9")
}
function funZoomClick(direction) {
  console.debug("zoom click"+direction);
  ptz("action="+direction)
}
function funFocusClick(direction) {
  console.debug("focus click"+direction);
  ptz("action="+direction)
}

主要增加了一個(gè)扇形按鈕和兩組按鈕組,然后將按鈕的點(diǎn)擊結(jié)合到app.js中進(jìn)行處理,app.js中則發(fā)送post請(qǐng)求調(diào)用go后端接口。

4.3 項(xiàng)目結(jié)構(gòu)和編譯運(yùn)行

項(xiàng)目結(jié)構(gòu)如下,部分文件做了備份,實(shí)際可以不用:

$tree -a -I ".github|.idea|
build"
.
├── .gitignore
├── CMakeLists.txt
├── Dockerfile
├── LICENSE
├── README.md
├── build.cmd
├── client.c
├── client.h
├── config.go
├── config.json
├── config.json.bak
├── doc
│   ├── demo2.png
│   ├── demo3.png
│   └── demo4.png
├── go.mod
├── go.sum
├── http.go
├── main.go
├── main.go.bak
├── renovate.json
├── soap
│   ├── DeviceBinding.nsmap
│   ├── ImagingBinding.nsmap
│   ├── MediaBinding.nsmap
│   ├── PTZBinding.nsmap
│   ├── PullPointSubscriptionBinding.nsmap
│   ├── RemoteDiscoveryBinding.nsmap
│   ├── custom
│   │   ├── README.txt
│   │   ├── chrono_duration.cpp
│   │   ├── chrono_duration.h
│   │   ├── chrono_time_point.cpp
│   │   ├── chrono_time_point.h
│   │   ├── duration.c
│   │   ├── duration.h
│   │   ├── float128.c
│   │   ├── float128.h
│   │   ├── int128.c
│   │   ├── int128.h
│   │   ├── long_double.c
│   │   ├── long_double.h
│   │   ├── long_time.c
│   │   ├── long_time.h
│   │   ├── qbytearray_base64.cpp
│   │   ├── qbytearray_base64.h
│   │   ├── qbytearray_hex.cpp
│   │   ├── qbytearray_hex.h
│   │   ├── qdate.cpp
│   │   ├── qdate.h
│   │   ├── qdatetime.cpp
│   │   ├── qdatetime.h
│   │   ├── qstring.cpp
│   │   ├── qstring.h
│   │   ├── qtime.cpp
│   │   ├── qtime.h
│   │   ├── struct_timeval.c
│   │   ├── struct_timeval.h
│   │   ├── struct_tm.c
│   │   ├── struct_tm.h
│   │   ├── struct_tm_date.c
│   │   └── struct_tm_date.h
│   ├── dom.c
│   ├── dom.h
│   ├── duration.c
│   ├── duration.h
│   ├── mecevp.c
│   ├── mecevp.h
│   ├── onvif.h
│   ├── smdevp.c
│   ├── smdevp.h
│   ├── soapC.c
│   ├── soapClient.c
│   ├── soapH.h
│   ├── soapStub.h
│   ├── stdsoap2.h
│   ├── stdsoap2_ssl.c
│   ├── struct_timeval.c
│   ├── struct_timeval.h
│   ├── threads.c
│   ├── threads.h
│   ├── typemap.dat
│   ├── wsaapi.c
│   ├── wsaapi.h
│   ├── wsdd.nsmap
│   ├── wsseapi.c
│   └── wsseapi.h
├── stream.go
└── web
    ├── static
    │   ├── css
    │   │   ├── bootstrap-grid.css
    │   │   ├── bootstrap-grid.css.map
    │   │   ├── bootstrap-grid.min.css
    │   │   ├── bootstrap-grid.min.css.map
    │   │   ├── bootstrap-reboot.css
    │   │   ├── bootstrap-reboot.css.map
    │   │   ├── bootstrap-reboot.min.css
    │   │   ├── bootstrap-reboot.min.css.map
    │   │   ├── bootstrap.css
    │   │   ├── bootstrap.css.map
    │   │   ├── bootstrap.min.css
    │   │   ├── bootstrap.min.css.map
    │   │   └── shanxing.css
    │   └── js
    │       ├── adapter-latest.js
    │       ├── app.js
    │       ├── bootstrap.bundle.js
    │       ├── bootstrap.bundle.js.map
    │       ├── bootstrap.bundle.min.js
    │       ├── bootstrap.bundle.min.js.map
    │       ├── bootstrap.js
    │       ├── bootstrap.js.map
    │       ├── bootstrap.min.js
    │       ├── bootstrap.min.js.map
    │       └── jquery-3.4.1.min.js
    └── templates
        ├── index.tmpl
        └── player.tmpl
8 directories, 111 files

關(guān)于cgo和onvif、gSoap部分這里就不多說了,不清楚的可以看前面的總結(jié),gin、bootstramp、jQuery這些也需要一定的前后端概念學(xué)習(xí)和儲(chǔ)備,在其它的分類總結(jié)中也零星分布了,不清楚的可以看一下,這里就不再多說了。

編譯運(yùn)行:

GOOS=linux GOARCH=amd64 CGO_ENABLE=1 GO111MODULE=on go run *.go

記得修改一下go.mod中對(duì)go版本的依賴,按照cgo的問題,目前至少需要1.18及以上,否則運(yùn)行ptz可能出現(xiàn)分割違例問題,到我總結(jié)這里1.18已經(jīng)發(fā)了正式版本了。

module github.com/deepch/RTSPtoWebRTC
go 1.18
require (
	github.com/deepch/vdk v0.0.0-20220309163430-c6529706436c
	github.com/gin-gonic/gin v1.7.7
)

4.4 結(jié)果展示

界面效果:

動(dòng)態(tài)調(diào)試ptz:

動(dòng)態(tài)調(diào)試縮放:

動(dòng)態(tài)調(diào)試調(diào)焦:

5. 最后

webRTC使用起來幾乎感覺不到延遲,但是受制于stun的udp打洞的穩(wěn)定性,可能會(huì)出現(xiàn)卡頓掉線等情況,所以還牽扯到p2p的問題,需要注意這一點(diǎn),當(dāng)然,這是遠(yuǎn)程推流都繞不開的一點(diǎn),也不算是獨(dú)有的問題。

以上就是Go語言開發(fā)瀏覽器視頻流rtsp轉(zhuǎn)webrtc播放的詳細(xì)內(nèi)容,更多關(guān)于Go語言視頻流rtsp轉(zhuǎn)webrtc的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Go語言學(xué)習(xí)教程之goroutine和通道的示例詳解

    Go語言學(xué)習(xí)教程之goroutine和通道的示例詳解

    這篇文章主要通過A?Tour?of?Go中的例子進(jìn)行學(xué)習(xí),以此了解Go語言中的goroutine和通道,文中的示例代碼講解詳細(xì),感興趣的可以了解一下
    2022-09-09
  • Go語言中init函數(shù)和defer延遲調(diào)用關(guān)鍵詞詳解

    Go語言中init函數(shù)和defer延遲調(diào)用關(guān)鍵詞詳解

    這篇文章主要介紹了Go語言中init函數(shù)和defer延遲調(diào)用關(guān)鍵詞,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03
  • 教你一分鐘配置好Go語言開發(fā)環(huán)境(多種操作系統(tǒng))

    教你一分鐘配置好Go語言開發(fā)環(huán)境(多種操作系統(tǒng))

    在這篇文章中,我們從頭到尾一步步指導(dǎo)你配置Golang開發(fā)環(huán)境,并編寫你的第一個(gè)"Hello,?World!"程序,我們?cè)敿?xì)解釋了在多種操作系統(tǒng)(包括Windows、Linux和macOS)下的安裝過程、環(huán)境變量設(shè)置以及如何驗(yàn)證安裝是否成功
    2023-09-09
  • Go語言開源庫(kù)實(shí)現(xiàn)Onvif協(xié)議客戶端設(shè)備搜索

    Go語言開源庫(kù)實(shí)現(xiàn)Onvif協(xié)議客戶端設(shè)備搜索

    這篇文章主要為大家介紹了Go語言O(shè)nvif協(xié)議客戶端設(shè)備搜索示例實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-04-04
  • Go泛型實(shí)戰(zhàn)教程之如何在結(jié)構(gòu)體中使用泛型

    Go泛型實(shí)戰(zhàn)教程之如何在結(jié)構(gòu)體中使用泛型

    這篇文章主要介紹了Go泛型實(shí)戰(zhàn)教程之如何在結(jié)構(gòu)體中使用泛型,根據(jù)Go泛型使用的三步曲提到的:類型參數(shù)化、定義類型約束、類型實(shí)例化我們一步步來定義我們的緩存結(jié)構(gòu)體,需要的朋友可以參考下
    2022-07-07
  • 一文帶你了解Go語言中鎖特性和實(shí)現(xiàn)

    一文帶你了解Go語言中鎖特性和實(shí)現(xiàn)

    Go語言中的sync包主要提供的對(duì)并發(fā)操作的支持,標(biāo)志性的工具有cond(條件變量)?once?(原子性)?還有?鎖,本文會(huì)主要向大家介紹Go語言中鎖的特性和實(shí)現(xiàn),感興趣的可以了解下
    2024-03-03
  • GoLang并發(fā)編程中條件變量sync.Cond的使用

    GoLang并發(fā)編程中條件變量sync.Cond的使用

    Go標(biāo)準(zhǔn)庫(kù)提供Cond原語的目的是,為等待/通知場(chǎng)景下的并發(fā)問題提供支持,本文主要介紹了Go并發(fā)編程sync.Cond的具體使用,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-01-01
  • golang?Strings包使用總結(jié)

    golang?Strings包使用總結(jié)

    Go語言在處理字符串時(shí),strings包提供了豐富的函數(shù),如常用的strings.Contains檢查是否包含子串,strings.Join拼接字符串?dāng)?shù)組,strings.Split切割字符串等,熟悉這些函數(shù)能有效提高編程效率,尤其是在算法競(jìng)賽或筆試題中
    2021-03-03
  • 聊聊go xorm生成mysql的結(jié)構(gòu)體問題

    聊聊go xorm生成mysql的結(jié)構(gòu)體問題

    這篇文章主要介紹了go xorm生成mysql的結(jié)構(gòu)體問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2022-03-03
  • Go語言學(xué)習(xí)之指針的用法詳解

    Go語言學(xué)習(xí)之指針的用法詳解

    這篇文章主要為大家詳細(xì)介紹了Go語言中指針的用法,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Go語言有一定的幫助,需要的可以參考一下
    2022-04-04

最新評(píng)論

揭阳市| 海南省| 武安市| 民和| 新余市| 汉源县| 文安县| 缙云县| 扎赉特旗| 将乐县| 麦盖提县| 龙川县| 锡林郭勒盟| 托里县| 大足县| 北碚区| 肇东市| 香格里拉县| 开封市| 通海县| 定州市| 永嘉县| 邹平县| 龙海市| 清新县| 定远县| 龙泉市| 孟村| 丹巴县| 夹江县| 蒙山县| 个旧市| 林州市| 兰溪市| 大邑县| 平陆县| 吐鲁番市| 达日县| 福贡县| 武川县| 苍梧县|