Home  >  Article  >  Backend Development  >  golang rtsp to http

golang rtsp to http

WBOY
WBOYOriginal
2023-05-10 17:46:37962browse

With the continuous development of Internet technology and the popularization of network applications, video streaming technology has gradually attracted widespread attention. In video streaming technology, RTSP is a commonly used streaming media transmission protocol, which allows users to transmit and play audio and video data on the network. However, since the RTSP protocol uses the TCP protocol during the transmission process, the transmission speed will be relatively slow and the bandwidth occupied will be relatively high, which will have a certain impact on the user's video viewing experience. In order to solve this problem, we can use the method of converting the RTSP stream into an HTTP stream, which will save bandwidth and increase the transmission speed. This article will introduce how to use golang to implement the process of converting rtsp to http.

1. Use golang to implement RTSP to HTTP conversion

Before implementing RTSP to HTTP, we need to first understand the difference between RTSP and HTTP. The RTSP protocol needs to implement the control part of the streaming media transmission protocol, but the HTTP protocol implements static page transmission and data transmission. Therefore, if you want to convert the RTSP stream into an HTTP stream, you must add an intermediate layer to realize the transmission of the control part and the HTTP static page.

Golang is an efficient, simple, stable and highly concurrent programming language that is very suitable for processing real-time audio and video streaming data. Therefore, we chose to use golang to implement the process of converting RTSP to HTTP.

First of all, we need to use the library in golang to implement the parsing and processing of the RTSP protocol. In golang, there is a third-party library called "gosip", which implements the parsing and processing of the RTSP protocol. We can use this library to implement the process of converting RTSP to HTTP. In addition, we also need to use the HTTP library in golang to implement HTTP protocol transmission.

The specific implementation steps are as follows:

  1. First, use the gosip library to implement the parsing and processing of the RTSP protocol.
import (
    "github.com/gorilla/mux"
    "github.com/nareix/srtcp"
    "github.com/nareix/udp"
    "github.com/nareix/webrtc"
    "github.com/nareix/xtcp"
    "github.com/nareix/joy4/format"
    "github.com/nareix/joy4/format/ts"
    "github.com/nareix/joy4/av"
    "github.com/nareix/joy4/container/rtp"
    "github.com/nareix/joy4/av/pubsub"
    "github.com/nareix/joy4/cgo/ffmpeg"
    "github.com/nareix/joy4/av/pktque"
    "net/http"
    "io"
    "fmt"
    "bytes"
    "strconv"
)

...

// 使用gosip库解析RTSP请求
func processRTSP(rtspRequest io.ReadWriteCloser, pubsub1 *pubsub.PubSub, aacWrite io.WriteCloser, h264Write io.WriteCloser) {
    sessionHandle := func(s *rtsp.Session) {
        p, err := s.Streams()
        checkError(err)

        var vtrack av.CodecData
        var atracks []av.CodecData
        for _, vi := range p {
            switch vi.Type().(type) {
            case av.H264CodecData:
                vtrack = vi.(av.H264CodecData)
                break
            case av.AACCodecData:
                atracks = append(atracks, vi.(av.AACCodecData))
                break
            }
        }

        var streamDialers []av.MuxCloser
        var streamWriters []av.MuxCloser

        // 创建H264的PubSub并添加到H264 Pub集
        H264Pub := pubsub.NewSimpleMuxer(100)
        streamDialers = append(streamDialers, H264Pub)
        go func() {
            H264Out := <-H264Pub.Out
            H264Outs, err := rtp.Encode(H264Out, vtrack.(av.VideoCodecData).Sdp())
            checkError(err)
            defer H264Outs.Close()
            n, err := s.WriteInterleaved(H264Outs)
            checkError(err)
            fmt.Println("Sent", n, "bytes. H264")
        }()

        // 创建AAC的PubSub并添加到AAC Pub集
        AACPubs := make([]*pubsub.PubSub, len(atracks))
        for i, atrack := range atracks {
            AACPubs[i] = pubsub.NewSimpleMuxer(100)
            streamDialers = append(streamDialers, AACPubs[i])
            go func(atrack av.CodecData, AACPubs1 *pubsub.PubSub) {
                out := <-AACPubs1.Out
                aacOut, _ := atrack.NewMuxer(out)
                defer aacOut.Close()

                outs, err := rtp.Encode(aacOut, atrack.(av.AudioCodecData).Sdp())
                checkError(err)
                defer outs.Close()
                n, err := s.WriteInterleaved(outs)
                checkError(err)
                fmt.Println("Sent", n, "bytes. Audio")
            }(atrack, AACPubs[i])
        }

        // 打开相应的转换器
        if aacWrite != nil {
            streamWriters = append(streamWriters, aacWrite)
            pubAACOut := make(chan []byte)
            AACPubs[0].Out <- pubAACOut
            go func() { // 把音频包推送到channel,再写到文件 
                for {
                    samples := <-pubAACOut
                    _, err := aacWrite.Write(samples)
                    checkError(err)
                }
            }()
        }
        if h264Write != nil {
            streamWriters = append(streamWriters, h264Write)
            H264Pub.Out <- h264Write
        }

        // 等待停止
        <-s.Done()
        for _, dialer := range streamDialers {
            fmt.Println("Closing dialer")
            dialer.Close()
        }
        for _, writer := range streamWriters {
            fmt.Println("Closing writer")
            writer.Close()
        }
    }

    for {
        req, err := rtsp.NewRequest()
        checkError(err)
        s, err := rtsp.NewSession(req, rtspRequest)
        if err != nil {
            fmt.Println(err)
            break
        }
        sessionHandle(s)
    }
}
  1. Use the HTTP library to implement and transmit the HTTP protocol.
...

// 使用HTTP协议请求推送的HLS流
func processHTTP(w http.ResponseWriter, r *http.Request) {
    ctx := &av.Context{Logger: logger}

    fmt.Println("New connection")
    defer fmt.Println("Closing write")

    v := mux.Vars(r)
    streamName := v["name"]

    if r.Method == "GET" {
        fmt.Println("HTTP GET request received...")

        segSeq := 0
        for {
            writer := NewHTTPStreamer(streamName, segSeq, w)
            segSeq++
            pubsub1 := pubsub.NewSimpleMuxer(100)

            // 创建http请求推送流着音视频流
            go func() {
                defer writer.Close()

                fmt.Println("Connected HTTP Writer. Waiting for output.")

                for {
                    Out := <-pubsub1.Out
                    fmt.Println("Received output")
                    ctx := &av.Context{Logger: logger, Write: writer}
                    fmt.Println(ctx)
                    defer ctx.Flush()
                    stream := Out[0]
                    fmt.Println(stream)
                    _ = avutil.CopyPackets(ctx, stream)
                }
            }()
            aacWrite, h264Write := getHLS(path.Join(videoTempDir, streamName), segSeq)
            processRTSP(NewRTSPReader(streamName), pubsub1, aacWrite, h264Write)
        }
    }
}

// 实现HTTP音视频流
func NewHTTPStreamer(base string, sn int, w http.ResponseWriter) *HTTPStreamer {
    str := fmt.Sprintf("%v/%v-%d.ts", videoTempDir, base, sn)
    f, _ := os.Create(str)
    return &HTTPStreamer{Writer: f, ResponseWriter: w}
}

...
  1. Finally, we connect the RTSP request with the HTTP response to realize the process of converting RTSP to HTTP.
...

// 连接RTSP请求和HTTP响应
func streamInvoke(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL.Path)
    if strings.HasPrefix(r.URL.Path, "/stream/") {
        processHTTP(w, r)
    } else if strings.HasPrefix(r.URL.Path, "/hls/") {
        processHLS(w, r)
    } else {
        fmt.Println(r.URL.Path)
        w.WriteHeader(404)
    }
}

...

The above is the specific implementation method of realizing the process of converting RTSP to HTTP through golang. By converting the RTSP stream into an HTTP stream, the transmission of video media can be made faster and more efficient, improving the user's viewing experience.

The above is the detailed content of golang rtsp to http. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn