Documentation
¶
Overview ¶
Package transcode chunk_manager.go:智能分段转码调度器
设计目标:
- 把视频按时间切成多个 chunk(默认每 60 秒一段),每个 chunk 独立用 ffmpeg 转码
- 用户拖动到任意位置时,按需启动对应 chunk 的 ffmpeg,不再线性等待
- 控制单 Job 最多并发 N 个 chunk ffmpeg,超出时 LRU 淘汰最久未访问的 chunk
- 当前 chunk 接近末尾时自动预启动下一个 chunk,保证顺序播放无缝衔接
- chunk 空闲超过阈值时 kill ffmpeg 释放 CPU,但保留已转出的切片文件
与 LocalRunner 的关系:
- LocalRunner.runJob 不再直接启动一个完整的 ffmpeg,而是创建 ChunkSession 并阻塞等待
- ChunkManager 是 ChunkSession 的"大脑",负责调度
- TCSegment 收到切片请求时,调用 ChunkManager.EnsureChunkRunningForSeg(seq) 触发按需调度
Package transcode 实现 OpenList 的 FFmpeg 云端/本地转码功能。 设计目标:
- 总开关默认关,开启后按文件大小、源码率、源编码、文件后缀过滤决定是否转码。
- 协议自研,纯 HTTP/JSON,可挂接本地内置 Worker 或远程 Worker 节点池。
- 切片流式回吐,支持边转边播。
Index ¶
- Constants
- Variables
- func IsEnabled() bool
- func ProtocolWhitelistFor(source string) string
- func ValidProfileName(profile string) bool
- func ValidSourceInput(source string) bool
- func VerifyWorkerSecret(token string) bool
- type Cache
- func (c *Cache) BuildPlaylist(jobID, profile string, segDur int, completed bool, baseURL string, ...) string
- func (c *Cache) Cleanup(jobID string)
- func (c *Cache) EnforceLRU() error
- func (c *Cache) GetSegment(jobID, profile string, seq int) (*SegmentInfo, error)
- func (c *Cache) Init() error
- func (c *Cache) MasterPlaylist(profiles []Profile, baseURL string) string
- func (c *Cache) PutSegment(jobID, profile string, seq int, duration float64, body io.Reader, isFinal bool) (*SegmentInfo, error)
- func (c *Cache) SegmentCount(jobID, profile string) int
- func (c *Cache) WaitForSegment(jobID, profile string, seq int, timeout time.Duration) (*SegmentInfo, error)
- type Chunk
- type ChunkManager
- func (cm *ChunkManager) CancelAllForJob(jobID string)
- func (cm *ChunkManager) CancelSession(jobID, profile string)
- func (cm *ChunkManager) EnsureChunkRunningForSeg(jobID, profile string, seq int) int
- func (cm *ChunkManager) StartSession(job *Job, profile Profile, outDir string) (*ChunkSession, error)
- func (cm *ChunkManager) Stop()
- type ChunkSession
- type ChunkState
- type ClaimRequest
- type ClaimResponse
- type DecideRequest
- type DecideResult
- type ErrorResponse
- type FinishRequest
- type HWAccel
- type HeartbeatRequest
- type HeartbeatResponse
- type Job
- type JobCache
- type JobStats
- type JobStatus
- type LocalRunner
- type Manager
- type OutputFormat
- type OutputSpec
- type Profile
- type RegisterRequest
- type RegisterResponse
- type Scheduler
- func (s *Scheduler) Cancel(jobID string)
- func (s *Scheduler) Capacity(ownerID string) error
- func (s *Scheduler) Claim(workerID string, slots int, wait time.Duration) []*Job
- func (s *Scheduler) FindReusable(ownerID string, path string) (*Job, bool)
- func (s *Scheduler) Finish(req *FinishRequest) error
- func (s *Scheduler) Get(id string) (*Job, bool)
- func (s *Scheduler) ListActiveJobs() []*Job
- func (s *Scheduler) ListJobs() []*Job
- func (s *Scheduler) PopCancellations(workerID string) []string
- func (s *Scheduler) PurgeBefore(t time.Time) []string
- func (s *Scheduler) Reactivate(jobID string) (*Job, error)
- func (s *Scheduler) SetOnCancel(fn func(jobID string))
- func (s *Scheduler) Submit(j *Job) *Job
- func (s *Scheduler) SubmitLimited(j *Job) (*Job, bool, error)
- type SegmentInfo
- type SourceProbe
- type Worker
- type WorkerRegistry
- func (r *WorkerRegistry) Get(id string) (*Worker, bool)
- func (r *WorkerRegistry) HasAvailable() bool
- func (r *WorkerRegistry) Heartbeat(req *HeartbeatRequest) (*Worker, bool)
- func (r *WorkerRegistry) List() []*Worker
- func (r *WorkerRegistry) Register(req *RegisterRequest, local bool) *Worker
- func (r *WorkerRegistry) Sweep() []string
- func (r *WorkerRegistry) Unregister(id string)
Constants ¶
const ( // MaxPendingJobs 全局排队(未被 worker 领取)任务上限 MaxPendingJobs = 200 // MaxActiveJobsPerUser 单用户同时存在的未结束任务上限 MaxActiveJobsPerUser = 3 )
提交配额。转码是 CPU/磁盘密集型操作,必须限制单用户并发与全局排队长度, 否则任何能访问播放接口的用户都能无限堆积任务(每个任务还会触发 30s 的 ffprobe)。
const ( // MaxSegmentBytes 单个切片允许写入的最大字节数,防止 callback_token 持有者打满磁盘 MaxSegmentBytes int64 = 32 << 20 )
const ProtocolVersion = "v1"
协议版本
Variables ¶
var ( // ErrInvalidProfile profile 名称不合法(可能是路径穿越尝试) ErrInvalidProfile = errors.New("invalid profile name") // ErrInvalidJobID job id 不合法 ErrInvalidJobID = errors.New("invalid job id") // ErrInvalidSegment 切片序号越界 ErrInvalidSegment = errors.New("invalid segment seq") // ErrSegmentTooLarge 切片超过大小上限 ErrSegmentTooLarge = errors.New("segment too large") )
Functions ¶
func ProtocolWhitelistFor ¶
ProtocolWhitelistFor 根据输入地址返回应传给 ffmpeg/ffprobe 的 -protocol_whitelist 值。
func ValidProfileName ¶
ValidProfileName 判断 profile 是否为安全的目录名(与 BuildProfile 产出的 source/1080p/720p 对齐)。
func ValidSourceInput ¶
ValidSourceInput 判断输入是否可以安全交给 ffmpeg: 只接受绝对本地路径或 http(s) URL,拒绝 concat:/subfile:/data:/pipe: 等协议前缀, 也拒绝以 - 开头(会被当作 ffmpeg 选项)的值。
func VerifyWorkerSecret ¶
VerifyWorkerSecret 校验远程 worker 注册凭据
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache 全局切片缓存
func (*Cache) BuildPlaylist ¶
func (c *Cache) BuildPlaylist(jobID, profile string, segDur int, completed bool, baseURL string, totalDuration float64) string
BuildPlaylist 生成 HLS playlist (m3u8) 【重要】当 totalDuration > 0 时,会根据总时长预先生成完整切片列表(VOD 模式), 即使切片还未生成,URL 也会出现在 playlist 中。HLS.js 请求未生成切片时 会阻塞等待(见 TCSegment 的 WaitForSegment)。这样可以让 HLS.js 知道 视频总时长,避免:
- 时长显示错误(只显示已转码部分)
- 拖动跳跃(playlist 增长导致切片序号重新对齐)
func (*Cache) EnforceLRU ¶
EnforceLRU 简易 LRU 容量控制:超过 maxBytes 时按目录修改时间从早到晚删除
func (*Cache) GetSegment ¶
func (c *Cache) GetSegment(jobID, profile string, seq int) (*SegmentInfo, error)
GetSegment 读取一个切片(不等待)
func (*Cache) MasterPlaylist ¶
MasterPlaylist 多档位主 m3u8
func (*Cache) PutSegment ¶
func (c *Cache) PutSegment(jobID, profile string, seq int, duration float64, body io.Reader, isFinal bool) (*SegmentInfo, error)
PutSegment 写入一个切片,并通知所有等待者
func (*Cache) SegmentCount ¶
SegmentCount 返回 (jobID, profile) 当前已生成的切片数量。 用于 TCPlaylist 在首次返回前等待至少若干切片就绪,避免 playlist 中只有 seg-0 导致 HLS.js 反复请求填充缓冲。
func (*Cache) WaitForSegment ¶
func (c *Cache) WaitForSegment(jobID, profile string, seq int, timeout time.Duration) (*SegmentInfo, error)
WaitForSegment 等待某个 seq 切片就绪,timeout 后返回 nil
type Chunk ¶
type Chunk struct {
Index int // chunk 序号(0 开始)
StartTime float64 // 起始秒
Duration float64 // 持续时长(最后一个 chunk 可能不足 chunkDur)
StartSeq int // 起始切片序号(包含)
EndSeq int // 结束切片序号(不包含)
State ChunkState
StartedAt time.Time
LastAccess time.Time
Error string
// contains filtered or unexported fields
}
Chunk 表示视频中的一个时间段,对应一段连续的切片序号
type ChunkManager ¶
type ChunkManager struct {
// contains filtered or unexported fields
}
ChunkManager 全局 chunk 管理器(一个 Manager 一个)
func (*ChunkManager) CancelAllForJob ¶
func (cm *ChunkManager) CancelAllForJob(jobID string)
CancelAllForJob 取消该 job 下所有 profile 的 session(CancelJob 时调用)
func (*ChunkManager) CancelSession ¶
func (cm *ChunkManager) CancelSession(jobID, profile string)
CancelSession 外部取消(job 被 cancel 或 idle 超时)
func (*ChunkManager) EnsureChunkRunningForSeg ¶
func (cm *ChunkManager) EnsureChunkRunningForSeg(jobID, profile string, seq int) int
EnsureChunkRunningForSeg 确保覆盖 seq 的 chunk 正在转码(由 TCSegment 触发) 返回所属 chunk index;如果 seq 越界返回 -1
func (*ChunkManager) StartSession ¶
func (cm *ChunkManager) StartSession(job *Job, profile Profile, outDir string) (*ChunkSession, error)
StartSession 创建并启动一个 chunk session(由 LocalRunner.runJob 调用) 返回的 ChunkSession.allDoneCh 在所有切片都转完时关闭
type ChunkSession ¶
type ChunkSession struct {
JobID string
Profile string
Job *Job
ProfDef Profile
// 静态参数
TotalDuration float64 // 视频总时长
SegDur int // 每片时长(秒)
ChunkDur int // 每个 chunk 时长(秒)
MaxConcurrent int // 最大并发 chunk 数
IdleSec int // chunk 空闲多久就 kill
Prefetch bool // 是否启用预读
// outDir / segPattern (供 ffmpeg 使用)
OutDir string
// contains filtered or unexported fields
}
ChunkSession 单个 (jobID, profile) 下的 chunk 调度上下文
func (*ChunkSession) WaitDone ¶
func (s *ChunkSession) WaitDone() <-chan struct{}
WaitDone 阻塞等待所有 chunk 完成(LocalRunner.runJob 用)
type ChunkState ¶
type ChunkState int
ChunkState chunk 当前状态
const ( ChunkIdle ChunkState = iota // 未启动 ChunkRunning // ffmpeg 正在转码 ChunkDone // ffmpeg 自然退出(chunk 内所有切片已转完) ChunkFailed // ffmpeg 异常失败 ChunkKilled // 被 LRU 淘汰或空闲超时 kill )
type ClaimRequest ¶
type ClaimResponse ¶
type ClaimResponse struct {
Jobs []*Job `json:"jobs"`
}
type DecideRequest ¶
type DecideRequest struct {
FileName string
FileSize int64 // 字节
Probe SourceProbe // 可选;为空则只用大小+后缀判断
}
DecideRequest 决策器输入
type DecideResult ¶
DecideResult 决策结果
type ErrorResponse ¶
type FinishRequest ¶
type HeartbeatRequest ¶
type HeartbeatResponse ¶
type Job ¶
type Job struct {
ID string `json:"id"`
Path string `json:"path"` // OpenList 文件路径
SourceURL string `json:"source_url"` // 提供给 Worker 的签名 URL
Probe SourceProbe `json:"probe"`
Profiles []Profile `json:"profiles"`
Output OutputSpec `json:"output"`
CallbackToken string `json:"callback_token"` // Worker 回吐切片用(同时具备写权限,绝不外泄给播放端)
// PlayToken 播放凭据:只用于 master/variant playlist 与切片下发,
// 与 Worker 回写凭据(CallbackToken)分离,避免播放器拿到可写权限。
// json:"-" 保证下发给 Worker 的任务描述里不会包含它。
PlayToken string `json:"-"`
Deadline int64 `json:"deadline"` // unix 秒
// OwnerID 发起转码者的配额键,仅服务端用于去重与配额,不下发给 Worker。
// 用字符串而不是用户 ID:访客共用一个账号,需要按 "guest:<clientIP>" 拆分配额,
// 否则单个匿名访客就能占满所有匿名转码配额。
OwnerID string `json:"-"`
// 运行时
Status JobStatus `json:"status"`
WorkerID string `json:"worker_id"`
CreatedAt time.Time `json:"created_at"`
StartedAt time.Time `json:"started_at"`
FinishedAt time.Time `json:"finished_at"`
LastAccessAt time.Time `json:"last_access_at"` // 播放端最后一次请求 segment/playlist 的时间
Error string `json:"error,omitempty"`
// contains filtered or unexported fields
}
Job 一次转码任务
type JobCache ¶
type JobCache struct {
JobID string
Profile string
BaseDir string
// contains filtered or unexported fields
}
JobCache 单个 Job 的切片缓存
type LocalRunner ¶
type LocalRunner struct {
// contains filtered or unexported fields
}
LocalRunner 本地内置 worker,直接调用本机 ffmpeg
func NewLocalRunner ¶
func NewLocalRunner(mgr *Manager) *LocalRunner
func (*LocalRunner) CancelJob ¶
func (r *LocalRunner) CancelJob(jobID string) bool
CancelJob 外部取消指定 job 的 FFmpeg 进程(由 Scheduler.Cancel / 空闲超时调用)
func (*LocalRunner) RunningJobIDs ¶
func (r *LocalRunner) RunningJobIDs() []string
RunningJobIDs 返回当前正在运行的所有 job ID 列表
func (*LocalRunner) Stop ¶
func (r *LocalRunner) Stop()
type Manager ¶
type Manager struct {
Registry *WorkerRegistry
Scheduler *Scheduler
Cache *Cache
Chunks *ChunkManager // 智能 chunk 调度器(按需启动 ffmpeg,支持随机访问)
// contains filtered or unexported fields
}
Manager 全局转码管理器单例
type OutputFormat ¶
type OutputFormat string
OutputFormat 输出封装格式
const ( FormatHLS OutputFormat = "hls" FormatDASH OutputFormat = "dash" FormatMP4 OutputFormat = "mp4" )
type OutputSpec ¶
type OutputSpec struct {
Format OutputFormat `json:"format"`
SegmentDuration int `json:"segment_duration"` // 秒
}
OutputSpec 输出参数
type Profile ¶
type Profile struct {
Name string `json:"name"` // 例如 1080p
VideoCodec string `json:"video_codec"` // h264 / hevc / av1
VideoBitrate string `json:"video_bitrate"` // 例如 4000k
Scale string `json:"scale"` // 例如 1920:-2
AudioCodec string `json:"audio_codec"` // aac / mp3 / opus / copy
AudioBitrate string `json:"audio_bitrate"` // 例如 160k
HWAccel string `json:"hwaccel"` // worker 端如何选择硬件加速
}
Profile 输出转码档位
type RegisterRequest ¶
type RegisterRequest struct {
Name string `json:"name"`
Version string `json:"version"`
Capacity int `json:"capacity"`
HWAccel []string `json:"hwaccel"`
CodecsDecode []string `json:"codecs_decode"`
CodecsEncode []string `json:"codecs_encode"`
MaxResolution string `json:"max_resolution"`
Tags []string `json:"tags"`
Endpoint string `json:"endpoint,omitempty"`
}
type RegisterResponse ¶
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler 任务调度器:维护 pending 队列并支持 worker pull 领取
func NewScheduler ¶
func NewScheduler(reg *WorkerRegistry) *Scheduler
func (*Scheduler) Capacity ¶
Capacity 只读预检:在启动 ffprobe 这类昂贵操作之前先看配额是否已满。
真正的配额判定仍由 SubmitLimited 在同一把锁内完成;这里的目的有两个:
- 不让用户先等一次最长 30s 的 ffprobe 才收到 429;
- 把「并发请求同时通过配额判定」这个窗口内的探测数量压下来。
func (*Scheduler) FindReusable ¶
FindReusable 查找同一用户对同一路径、仍在进行中的任务,用于去重复用。
func (*Scheduler) Finish ¶
func (s *Scheduler) Finish(req *FinishRequest) error
Finish 由 worker 调用,标记任务完成/失败
func (*Scheduler) ListActiveJobs ¶
ListActiveJobs 列出所有活跃任务(pending/running/ready),用于空闲超时检测
func (*Scheduler) PopCancellations ¶
PopCancellations 取出某个 worker 待处理的取消列表(心跳响应中下发)
func (*Scheduler) PurgeBefore ¶
PurgeBefore 删除 finishedAt 早于某时刻的任务,避免 jobs map 无限增长 返回被清理的 job ID 列表,调用方需联动清理 Cache
func (*Scheduler) Reactivate ¶
Reactivate 把一个已 Cancelled / Failed / Finished 的 job 重新激活回 Pending 状态, 让 worker 能再次领取并跑转码。用于"播放端重新请求时按需重启转码"的场景。
设计点:
- 复用原 jobID 和两套 token(播放用 PlayToken / Worker 回写用 CallbackToken), 前端持有的 master.m3u8 中的 URL 不需要变更
- 重置 readyCh / Status / WorkerID 等运行时字段,但保留 Path / SourceURL / Profiles / Probe
- 重新加入 pending 队列并唤醒等待的 worker
返回被激活的 Job;job 不存在返回 ErrJobNotFound,单用户配额不足返回 ErrUserQuota, 全局排队已满返回 ErrQueueFull。
func (*Scheduler) SetOnCancel ¶
SetOnCancel 注入取消回调(由 Manager 在启动本地 worker 后调用)
type SegmentInfo ¶
type SegmentInfo struct {
Seq int `json:"seq"`
Duration float64 `json:"duration"`
Size int64 `json:"size"`
Path string `json:"-"` // 本地实际文件路径
}
SegmentInfo 单个切片元数据
type SourceProbe ¶
type SourceProbe struct {
Duration float64 `json:"duration"` // 秒
Size int64 `json:"size"` // 字节
VideoCodec string `json:"video_codec"` // h264 / hevc / av1 / vp9 ...
VideoBitrate int64 `json:"video_bitrate"` // bps
Width int `json:"width"`
Height int `json:"height"`
AudioCodec string `json:"audio_codec"`
AudioBitrate int64 `json:"audio_bitrate"`
}
SourceProbe 源文件探测信息(由 ffprobe 得出)
type Worker ¶
type Worker struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version"`
Capacity int `json:"capacity"` // 最大并发任务数
HWAccel []string `json:"hwaccel"` // 支持的硬件加速
CodecsDecode []string `json:"codecs_decode"` // 可解码
CodecsEncode []string `json:"codecs_encode"` // 可编码
MaxResolution string `json:"max_resolution"` // 最大分辨率
Tags []string `json:"tags"`
Endpoint string `json:"endpoint,omitempty"` // 反向连接地址(可选)
// 运行时
Load float64 `json:"load"` // 0~1
Running []string `json:"running"` // 当前 job_ids
FreeSlots int `json:"free_slots"`
LastSeen time.Time `json:"last_seen"`
RegisteredAt time.Time `json:"registered_at"`
Local bool `json:"local"` // 是否本地内置 Worker
}
Worker 节点信息
type WorkerRegistry ¶
type WorkerRegistry struct {
// contains filtered or unexported fields
}
WorkerRegistry 维护当前在线的 Worker 池
func NewWorkerRegistry ¶
func NewWorkerRegistry() *WorkerRegistry
func (*WorkerRegistry) HasAvailable ¶
func (r *WorkerRegistry) HasAvailable() bool
HasAvailable 是否存在有空闲槽位的 worker
func (*WorkerRegistry) Heartbeat ¶
func (r *WorkerRegistry) Heartbeat(req *HeartbeatRequest) (*Worker, bool)
Heartbeat 更新 worker 心跳信息,未注册返回 false
func (*WorkerRegistry) Register ¶
func (r *WorkerRegistry) Register(req *RegisterRequest, local bool) *Worker
Register 注册一个新的 worker,返回分配的 ID
func (*WorkerRegistry) Sweep ¶
func (r *WorkerRegistry) Sweep() []string
Sweep 清理超时未心跳的 worker;返回被移除的 worker_id 列表
func (*WorkerRegistry) Unregister ¶
func (r *WorkerRegistry) Unregister(id string)
Unregister 主动移除 worker