storyboard.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package transcoder
  2. /*
  3. Storyboard.go
  4. Generates "storyboard" sprite sheets for video scrub-bar previews: a single
  5. tiled JPEG holding one downscaled frame every N seconds. The player loads one
  6. image into memory and slices it with CSS, so hovering the timeline never has
  7. to hit ffmpeg — which matters because seeking a software-decoded H.265 source
  8. per hover would be far too slow to feel interactive.
  9. */
  10. import (
  11. "bytes"
  12. "context"
  13. "errors"
  14. "fmt"
  15. "image"
  16. _ "image/jpeg" // registers the JPEG decoder used by image.DecodeConfig
  17. "math"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "strings"
  22. "time"
  23. )
  24. // StoryboardCacheFolder returns the folder holding the storyboard sheet for a
  25. // given video file.
  26. //
  27. // Sheets live beside the media they describe, following the same ".metadata"
  28. // convention the thumbnail cache uses, so a storyboard travels with its video
  29. // across the file system abstraction and disappears with the folder it belongs
  30. // to. The trailing separator matches how the metadata package builds its own
  31. // cache paths, so callers can concatenate a filename directly.
  32. func StoryboardCacheFolder(videoRealPath string) string {
  33. return filepath.ToSlash(
  34. filepath.Join(filepath.Clean(filepath.Dir(videoRealPath)), "/.metadata/.storyboard/")) + "/"
  35. }
  36. const (
  37. // Tile width in pixels; height follows the source aspect ratio.
  38. storyboardTileWidth = 160
  39. // Tiles per row in the generated sheet.
  40. storyboardCols = 10
  41. // Frame budget: how many tiles we aim for regardless of clip length.
  42. storyboardTargetTiles = 120
  43. // Hard ceiling so a very long film cannot produce an enormous sheet.
  44. storyboardMaxTiles = 240
  45. // Sampling interval bounds, in seconds.
  46. storyboardMinInterval = 2.0
  47. storyboardMaxInterval = 60.0
  48. // Generation is capped so a pathological input cannot pin a core forever.
  49. storyboardTimeout = 5 * time.Minute
  50. )
  51. // StoryboardLayout describes the geometry of a generated sheet. The player needs
  52. // every field to map a hovered timestamp onto the right tile.
  53. type StoryboardLayout struct {
  54. Interval float64 `json:"interval"` // seconds represented by each tile
  55. Count int `json:"count"` // tiles that carry a real frame
  56. Cols int `json:"cols"` // tiles per row
  57. Rows int `json:"rows"` // rows in the sheet
  58. TileWidth int `json:"tileWidth"` // pixel width of one tile
  59. TileHeight int `json:"tileHeight"` // pixel height of one tile
  60. Duration float64 `json:"duration"` // source duration in seconds
  61. }
  62. // PlanStoryboard picks the sampling interval and grid for a clip of the given
  63. // duration.
  64. //
  65. // The interval scales with length so short clips get fine-grained previews and
  66. // long ones stay within a sane sheet size: roughly storyboardTargetTiles frames,
  67. // clamped to [storyboardMinInterval, storyboardMaxInterval], then widened again
  68. // if the tile count would exceed storyboardMaxTiles.
  69. //
  70. // Kept free of ffmpeg so the sizing rules can be unit-tested directly.
  71. func PlanStoryboard(duration float64) (StoryboardLayout, error) {
  72. if duration <= 0 || math.IsNaN(duration) || math.IsInf(duration, 0) {
  73. return StoryboardLayout{}, errors.New("invalid duration")
  74. }
  75. interval := duration / storyboardTargetTiles
  76. if interval < storyboardMinInterval {
  77. interval = storyboardMinInterval
  78. }
  79. if interval > storyboardMaxInterval {
  80. interval = storyboardMaxInterval
  81. }
  82. count := int(math.Ceil(duration / interval))
  83. if count > storyboardMaxTiles {
  84. count = storyboardMaxTiles
  85. interval = duration / float64(count)
  86. }
  87. if count < 1 {
  88. count = 1
  89. }
  90. cols := storyboardCols
  91. if count < cols {
  92. cols = count
  93. }
  94. rows := int(math.Ceil(float64(count) / float64(cols)))
  95. return StoryboardLayout{
  96. Interval: interval,
  97. Count: count,
  98. Cols: cols,
  99. Rows: rows,
  100. TileWidth: storyboardTileWidth,
  101. Duration: duration,
  102. }, nil
  103. }
  104. // GenerateStoryboard renders the sprite sheet for inputFile and returns the
  105. // encoded JPEG together with the layout describing it.
  106. //
  107. // The sheet is deliberately returned as bytes rather than written to a path:
  108. // ffmpeg can only write to a native filesystem path, but the caller may be
  109. // serving a video that lives behind an arozfs abstraction (S3, remote mounts,
  110. // …). Rendering into scratch space under workDir and handing the bytes back
  111. // lets the caller store the result through whichever file system actually owns
  112. // the video, instead of stranding it on local disk.
  113. //
  114. // Decoding is restricted to keyframes (-skip_frame nokey), which is what makes
  115. // this affordable: a full decode of a two-hour software-decoded H.265 file would
  116. // take many minutes, while a keyframe-only pass runs an order of magnitude
  117. // faster and is more than accurate enough for thumbnails.
  118. func GenerateStoryboard(inputFile string, workDir string, duration float64) ([]byte, StoryboardLayout, error) {
  119. layout, err := PlanStoryboard(duration)
  120. if err != nil {
  121. return nil, StoryboardLayout{}, err
  122. }
  123. if strings.TrimSpace(workDir) == "" {
  124. workDir = os.TempDir()
  125. }
  126. if err := os.MkdirAll(workDir, 0775); err != nil {
  127. return nil, StoryboardLayout{}, fmt.Errorf("scratch directory unavailable: %w", err)
  128. }
  129. // The .jpg suffix matters: ffmpeg picks its muxer from the output extension.
  130. scratch, err := os.CreateTemp(workDir, "storyboard-*.jpg")
  131. if err != nil {
  132. return nil, StoryboardLayout{}, fmt.Errorf("could not create scratch file: %w", err)
  133. }
  134. scratchPath := scratch.Name()
  135. scratch.Close()
  136. defer os.Remove(scratchPath)
  137. vf := fmt.Sprintf("fps=1/%.6f,scale=%d:-2,tile=%dx%d",
  138. layout.Interval, storyboardTileWidth, layout.Cols, layout.Rows)
  139. ctx, cancel := context.WithTimeout(context.Background(), storyboardTimeout)
  140. defer cancel()
  141. cmd := exec.CommandContext(ctx, "ffmpeg",
  142. "-y",
  143. "-skip_frame", "nokey", // decode keyframes only
  144. "-i", inputFile,
  145. "-an", "-sn", // no audio or subtitle streams
  146. "-vf", vf,
  147. "-frames:v", "1", // a single tiled sheet
  148. "-q:v", "5",
  149. scratchPath,
  150. )
  151. if out, err := cmd.CombinedOutput(); err != nil {
  152. if ctx.Err() == context.DeadlineExceeded {
  153. return nil, StoryboardLayout{}, errors.New("storyboard generation timed out")
  154. }
  155. return nil, StoryboardLayout{}, fmt.Errorf("ffmpeg failed: %w (%s)", err, lastLines(string(out), 2))
  156. }
  157. sheet, err := os.ReadFile(scratchPath)
  158. if err != nil {
  159. return nil, StoryboardLayout{}, fmt.Errorf("storyboard not written: %w", err)
  160. }
  161. if len(sheet) == 0 {
  162. return nil, StoryboardLayout{}, errors.New("storyboard came out empty")
  163. }
  164. // Read the real tile height back from the sheet: it depends on the source
  165. // aspect ratio, which we do not know until ffmpeg has scaled a frame.
  166. cfg, _, err := image.DecodeConfig(bytes.NewReader(sheet))
  167. if err != nil {
  168. return nil, StoryboardLayout{}, fmt.Errorf("unreadable storyboard: %w", err)
  169. }
  170. if cfg.Width <= 0 || cfg.Height <= 0 || layout.Cols <= 0 || layout.Rows <= 0 {
  171. return nil, StoryboardLayout{}, errors.New("unexpected storyboard dimensions")
  172. }
  173. layout.TileWidth = cfg.Width / layout.Cols
  174. layout.TileHeight = cfg.Height / layout.Rows
  175. if layout.TileWidth <= 0 || layout.TileHeight <= 0 {
  176. return nil, StoryboardLayout{}, errors.New("unexpected storyboard tile size")
  177. }
  178. return sheet, layout, nil
  179. }
  180. // lastLines trims ffmpeg's very verbose output down to the tail, which is where
  181. // the actual failure reason lives.
  182. func lastLines(s string, n int) string {
  183. if s == "" {
  184. return ""
  185. }
  186. lines := []string{}
  187. start := 0
  188. for i := 0; i < len(s); i++ {
  189. if s[i] == '\n' {
  190. if i > start {
  191. lines = append(lines, s[start:i])
  192. }
  193. start = i + 1
  194. }
  195. }
  196. if start < len(s) {
  197. lines = append(lines, s[start:])
  198. }
  199. if len(lines) > n {
  200. lines = lines[len(lines)-n:]
  201. }
  202. out := ""
  203. for i, l := range lines {
  204. if i > 0 {
  205. out += " | "
  206. }
  207. out += l
  208. }
  209. return out
  210. }