欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

1. 前言

前面我們測試了rtsp轉hls方式,發(fā)現(xiàn)延遲比較大,不太適合我們的使用需求。接下來我們試一下webrtc的方式看下使用情況。

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

2. rtsp轉webRTC

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

點擊下載

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

初步測試幾乎看不出來延遲,符合預期,使用的jQuery+bootstrap+go+gin做的web,也符合我們的項目使用情況。

3. 初步測試結果

結果如下:

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

我們在此項目的基礎上,結合我們之前研究的onvif+cgo+gSoap的方案,將onvif獲取到的相關數(shù)據(jù)提供接口到web端,增加ptz、調焦、縮放等功能。

我們在http.go中添加新的post接口:HTTPAPIServerStreamPtz來進行ptz和HTTPAPIServerStreamPreset進行預置點相關操作。

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

4.1 go后端修改

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

http.go(增加了兩個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("請輸入數(shù)字進行preset,1-4分別代表查詢、設置、跳轉、刪除預置點;退出輸入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("請輸入要設置的預置點token信息:")
		presentToken := ""
		_, _ = fmt.Scanln(&presentToken)
		fmt.Println("請輸入要設置的預置點name信息長度不超過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("請輸入要跳轉的預置點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("請輸入要刪除的預置點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 前端修改

對于goland我們首先將.tmpl文件通過右鍵標記為html格式,然后再修改時就會有前端語法支持和補全支持,便于修改,否則默認是識別為文本的,之后我們修改player.tmpl和app.js,在player.tmpl中添加一些ptz的按鈕并通過js與前后端進行數(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)">調焦+</button>
                    <button type="button" class="btn btn-default" onclick="funFocusClick(13)">調焦-</button>
                    <button type="button" class="btn btn-default" onclick="funFocusClick(14)">停止調焦</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)
}

主要增加了一個扇形按鈕和兩組按鈕組,然后將按鈕的點擊結合到app.js中進行處理,app.js中則發(fā)送post請求調用go后端接口。

4.3 項目結構和編譯運行

項目結構如下,部分文件做了備份,實際可以不用:

$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

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

編譯運行:

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

記得修改一下go.mod中對go版本的依賴,按照cgo的問題,目前至少需要1.18及以上,否則運行ptz可能出現(xiàn)分割違例問題,到我總結這里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 結果展示

界面效果:

動態(tài)調試ptz:

動態(tài)調試縮放:

動態(tài)調試調焦:

5. 最后

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

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

相關文章

  • golang xorm日志寫入文件中的操作

    golang xorm日志寫入文件中的操作

    這篇文章主要介紹了golang xorm日志寫入文件中的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Golang如何實現(xiàn)任意進制轉換的方法示例

    Golang如何實現(xiàn)任意進制轉換的方法示例

    進制轉換是人們利用符號來計數(shù)的方法,進制轉換由一組數(shù)碼符號和兩個基本因素“基數(shù)”與“位權”構成,這篇文章主要給大家介紹了關于Golang如何實現(xiàn)10進制轉換62進制的方法,文中給出了詳細的示例代碼供大家參考學習學習,下面隨著小編來一起學習學習吧。
    2017-09-09
  • golang簡易令牌桶算法實現(xiàn)代碼

    golang簡易令牌桶算法實現(xiàn)代碼

    這篇文章主要介紹了golang簡易令牌桶算法實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • golang?gin框架實現(xiàn)大文件的流式上傳功能

    golang?gin框架實現(xiàn)大文件的流式上傳功能

    這篇文章主要介紹了golang?gin框架中實現(xiàn)大文件的流式上傳,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • Go map底層實現(xiàn)與擴容規(guī)則和特性分類詳細講解

    Go map底層實現(xiàn)與擴容規(guī)則和特性分類詳細講解

    這篇文章主要介紹了Go map底層實現(xiàn)與擴容規(guī)則和特性,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2023-03-03
  • 詳解Golang中結構體方法的高級應用

    詳解Golang中結構體方法的高級應用

    本文旨在深度剖析Go中結構體方法的高級應用。我們不僅會回顧結構體方法的基本概念和用法,還將探討如何通過高級技巧和最佳實踐,希望對大家有所幫助
    2024-01-01
  • Go語言設計模式之結構型模式

    Go語言設計模式之結構型模式

    本文主要聚焦在結構型模式(Structural Pattern)上,其主要思想是將多個對象組裝成較大的結構,并同時保持結構的靈活和高效,從程序的結構上解決模塊之間的耦合問題
    2021-06-06
  • Golang性能優(yōu)化的技巧分享

    Golang性能優(yōu)化的技巧分享

    性能優(yōu)化的前提是滿足正確可靠、簡潔清晰等質量因素,針對?Go語言特性,本文為大家整理了一些Go語言相關的性能優(yōu)化建議,感興趣的可以了解一下
    2023-07-07
  • sublime text3解決Gosublime無法自動補全代碼的問題

    sublime text3解決Gosublime無法自動補全代碼的問題

    本文主要介紹了sublime text3解決Gosublime無法自動補全代碼的問題,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • PHP和GO對接ChatGPT實現(xiàn)聊天機器人效果實例

    PHP和GO對接ChatGPT實現(xiàn)聊天機器人效果實例

    這篇文章主要為大家介紹了PHP和GO對接ChatGPT實現(xiàn)聊天機器人效果實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01

最新評論