开发订阅者插件
所谓订阅者就是用来从流媒体服务器接收音视频流的程序,例如RTMP协议执行play命令后、http-flv请求响应程序、websocket响应程序。内置插件中录制flv程序也是一个特殊的订阅者。下面是http-flv插件的源码,供参考
package HDL
import (
. "github.com/langhuihui/monibuca/monica"
"github.com/langhuihui/monibuca/monica/avformat"
"github.com/langhuihui/monibuca/monica/pool"
"log"
"net/http"
"strings"
)
var config = new(ListenerConfig)
func init() {
InstallPlugin(&PluginConfig{
Name: "HDL",
Type: PLUGIN_SUBSCRIBER,
Config: config,
Run: run,
})
}
func run() {
log.Printf("HDL start at %s", config.ListenAddr)
log.Fatal(http.ListenAndServe(config.ListenAddr, http.HandlerFunc(HDLHandler)))
}
func HDLHandler(w http.ResponseWriter, r *http.Request) {
sign := r.URL.Query().Get("sign")
if err := AuthHooks.Trigger(sign); err != nil {
w.WriteHeader(403)
return
}
stringPath := strings.TrimLeft(r.RequestURI, "/")
if strings.HasSuffix(stringPath, ".flv") {
stringPath = strings.TrimRight(stringPath, ".flv")
}
if _, ok := AllRoom.Load(stringPath); ok {
//atomic.AddInt32(&hdlId, 1)
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", "video/x-flv")
w.Write(avformat.FLVHeader)
p := OutputStream{
Sign: sign,
SendHandler: func(packet *pool.SendPacket) error {
return avformat.WriteFLVTag(w, packet)
},
SubscriberInfo: SubscriberInfo{
ID: r.RemoteAddr, Type: "FLV",
},
}
p.Play(stringPath)
} else {
w.WriteHeader(404)
}
}
其中,核心逻辑就是创建OutputStream对象,每一个订阅者需要提供SendHandler函数,用来接收来自发布者广播出来的音视频数据。最后调用该对象的Play函数进行播放。请注意:Play函数会阻塞当前goroutine。