go常规频道中的同步问题

时间:2019-06-24 08:42:20

标签: go channel goroutine

我正在尝试编写代理服务器,将视频文件转换为实时流。一个vod文件包含多个具有不同比特率的子清单文件。每个子清单由多个ts段组成,每个段4秒。为简单起见,我创建了一个虚拟地图,其中包含2个子清单,每个子清单包含4个ts段。我的任务是在for循环中无限创建一个实时流。所以我在go例程中经过4秒钟后发送了每个ts段,并写入了通道,还有另外一个go例程,我正在从该go例程读取并写入输出字符串。一旦所有细分均结束,我将更新至loopEnd频道并重新开始。每4秒就有2种API用于不同的比特率,从而为我提供了新的提示。

package main

import (
    "fmt"
    "github.com/gin-contrib/gzip"
    "github.com/gin-gonic/gin"
    "sync"
    "time"
)

func main() {
    vodToLiveMap := convertVodToLive()
    engine := gin.Default()
    engine.Use(gzip.Gzip(gzip.DefaultCompression))
    engine.GET("/134200", func(gctx *gin.Context) {
        prepareResponse(gctx, "134200", vodToLiveMap)
    })

    engine.GET("/290400", func(gctx *gin.Context) {
        prepareResponse(gctx, "290400", vodToLiveMap)
    })
    engine.Run() // listen and serve on 0.0.0.0:8080
}

// this represents one ulr for http live stream
type hlsEntry struct {
    timeCode int    // timecode in microseconds
    body     string // string including transport segment URL, timecode
}

type VodToLive struct {
    SequenceNumber int
    Out            chan string
    CurrentStream  string
}

func convertVodToLive() sync.Map {
    var hlsEntriesBitrate1 = []hlsEntry{
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer1_001.ts\n",
        },
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer1_002.ts\n",
        },
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer1_003.ts\n",
        },
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer1_004.ts\n",
        },
    }

    var hlsEntriesBitrate2 = []hlsEntry{
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer2_001.ts\n",
        },
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer2_002.ts\n",
        },
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer2_003.ts\n",
        },
        {
            timeCode: 4000000,
            body:     "#EXTINF:4.00000,\n/master_Layer2_004.ts\n",
        },
    }
    fmt.Println(hlsEntriesBitrate2)
    var hlsEntriesMap = make(map[string][]hlsEntry)
    hlsEntriesMap["134200"] = hlsEntriesBitrate1
    hlsEntriesMap["290400"] = hlsEntriesBitrate2
    outputString := ""
    vodToLiveMap := sync.Map{}
    i := 0
    //Iterate for all child manifest files of different bit rates
    for childURLSlug := range hlsEntriesMap {
        vodToLive := &VodToLive{}
        vodToLive.SequenceNumber = 1
        vodToLive.Out = make(chan string)
        vodToLiveMap.Store(childURLSlug, vodToLive)
        loopEnd := make(chan bool)

        //Writing to vodToLive for a childURLSlug
        go func(childURLSlug string) {
            for {
                for _, entry := range hlsEntriesMap[childURLSlug] {
                    select {
                    case <-time.After(time.Duration(entry.timeCode) * time.Microsecond):
                        vodToLive.SequenceNumber++
                        vodToLive.Out <- entry.body
                    }
                }
                loopEnd <- true
                fmt.Println(childURLSlug)
            }
        }(childURLSlug)

        //Reading from vodToLive's Out channel for a childURLSlug to update CurrentStream
        go func(childURLSlug string) {
            for {
                for {
                    select {
                    //If video reaches end of stream then restart stream from Sequence #1
                    case <-loopEnd:
                        vodToLive.SequenceNumber = 1
                        //time.Sleep(10 * time.Second)
                        vodToLive.CurrentStream = ""
                        break

                    default:
                        outputString = <-vodToLive.Out
                        fmt.Println(outputString)
                        vodToLive.CurrentStream = vodToLive.CurrentStream + outputString

                    }
                }
            }
        }(childURLSlug)
        i++
    }
    return vodToLiveMap
}

func prepareResponse(gctx *gin.Context, childURLSlug string, vodToLiveMap sync.Map) {

    vodToLive, _ := vodToLiveMap.Load(childURLSlug)

    gctx.Header("Content-Type", "application/x-mpegURL")
    response := `#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:` + "1" + "\n" + vodToLive.(*VodToLive).CurrentStream

    size := len(response)
    if size > 0 && response[size-1] == '\n' {
        response = response[:size-1]
    }
    gctx.String(200, response)
}
//curl localhost:8080/134200
//curl localhost:8080/290400

但是这里的问题是我没有在curl请求中获得所有ts段,有时甚至在循环结束后也没有更新ts。我显示了每个调用中的所有4个ts段,但应在每个endLoop之后将其重置。

1 个答案:

答案 0 :(得分:0)

仅通过在频道(vodToLive.Out)上将select替换为default并在case <-loopEnd中添加4秒等待时间即可解决此问题

go func(childURLSlug string) {
    for {
        for {
            select {
            //If video reaches end of stream then restart stream from Sequence #1
            case <-loopEnd:
                vodToLive.SequenceNumber = 1
                // so this will ensure that next stream starts only when first is complete.
                time.Sleep(4 * time.Second) //Usually a ts is 4 seconds length.
                vodToLive.CurrentStream = ""
                break

            case res := <-vodToLive.Out:
                outputString := res
                fmt.Println(outputString)
                vodToLive.CurrentStream = vodToLive.CurrentStream + outputString

            }
        }
    }
}(childURLSlug)