| 1 | // clips.go is how a clip's video gets into a deck and back out of it |
| 2 | // (scenes and clips spec §2, §4; §8 call 8). |
| 3 | // |
| 4 | // A video is an asset like a picture: the same sign, PUT and register |
| 5 | // (assets.go), the same verification row, the same register_asset op |
| 6 | // the browser applies, the same GET under each surface's capability. |
| 7 | // What differs is here: |
| 8 | // |
| 9 | // - its kind is video/mp4 or video/webm, read from the bytes (an MP4's |
| 10 | // ftyp box, a WebM's EBML header naming the webm DocType), and it |
| 11 | // may be 50 MiB; |
| 12 | // - it is registered with a poster: the ref of a PNG or WebP picture |
| 13 | // of its first frame, which the uploader's browser drew and |
| 14 | // registered for this deck just before, and its length in whole |
| 15 | // milliseconds. The record names both, and register_asset carries |
| 16 | // them into the deck, which is how every surface that can't play |
| 17 | // the video (scripts off, a thumbnail, the PDF, the presenter's |
| 18 | // Next, the remote) draws the poster instead; |
| 19 | // - it is served in ranges (http.ServeContent), so a browser can seek; |
| 20 | // - while it is staged, its bytes go back to whoever staged them |
| 21 | // (GET /d/{sqid}/uploads/{ref}), because the poster is drawn from |
| 22 | // them: the page's policy loads media from this origin alone, so the |
| 23 | // browser cannot play the file it picked from a blob: URL. |
| 24 | // |
| 25 | // Refusals are a code and a developer's sentence, as a scene bundle's |
| 26 | // are (scenes.go's sceneFail); the editor words them from the catalog |
| 27 | // (slides.refused.clip, slides.refused.clip.big). |
| 28 | package slides |
| 29 | |
| 30 | import ( |
| 31 | "bytes" |
| 32 | "context" |
| 33 | "encoding/binary" |
| 34 | "errors" |
| 35 | "io" |
| 36 | "net/http" |
| 37 | "slices" |
| 38 | "strings" |
| 39 | "time" |
| 40 | |
| 41 | "github.com/go-chi/chi/v5" |
| 42 | "gorm.io/gorm" |
| 43 | "gorm.io/gorm/clause" |
| 44 | |
| 45 | "amadan.net/rastrillo/rastrillo/blobs" |
| 46 | ) |
| 47 | |
| 48 | // maxVideoBytes is a clip's ceiling (scenes and clips spec §9): 50 MiB, |
| 49 | // held where pictures' 20 MiB is held (sign, the development PUT, and |
| 50 | // registration). |
| 51 | const maxVideoBytes = 50 << 20 |
| 52 | |
| 53 | // videoTypes is what a clip may be, as a file picker names it. |
| 54 | var videoTypes = map[string]string{ |
| 55 | "video/mp4": ".mp4", |
| 56 | "video/webm": ".webm", |
| 57 | } |
| 58 | |
| 59 | // clipTypes is videoTypes as the clip picker's accept attribute, sorted. |
| 60 | func clipTypes() string { |
| 61 | out := make([]string, 0, len(videoTypes)) |
| 62 | for kind := range videoTypes { |
| 63 | out = append(out, kind) |
| 64 | } |
| 65 | slices.Sort(out) |
| 66 | return strings.Join(out, ",") |
| 67 | } |
| 68 | |
| 69 | // maxVideoDuration bounds the length a client reports, which its own |
| 70 | // decode measured: advisory, like a picture's size, so a number outside |
| 71 | // this is dropped rather than refused. |
| 72 | const maxVideoDuration = 24 * 60 * 60 * 1000 |
| 73 | |
| 74 | // isVideo is whether an upload signed as kind is a clip's video. |
| 75 | func isVideo(kind string) bool { |
| 76 | _, ok := videoTypes[kind] |
| 77 | return ok |
| 78 | } |
| 79 | |
| 80 | // stillBrands are the ISO BMFF brands of pictures that share an MP4's |
| 81 | // ftyp box (AVIF and HEIF), which are not clips. |
| 82 | var stillBrands = map[string]bool{ |
| 83 | "avif": true, "avis": true, "heic": true, "heix": true, "heim": true, "heis": true, |
| 84 | "hevc": true, "hevx": true, "mif1": true, "msf1": true, |
| 85 | } |
| 86 | |
| 87 | // sniffVideo reads the bytes themselves and returns video/mp4, |
| 88 | // video/webm or the empty string. |
| 89 | func sniffVideo(raw []byte) string { |
| 90 | if len(raw) >= 12 && bytes.Equal(raw[4:8], []byte("ftyp")) { |
| 91 | // The box holds a major brand, a version and the brands it is |
| 92 | // compatible with: a few dozen bytes, in fours. |
| 93 | size := binary.BigEndian.Uint32(raw[:4]) |
| 94 | if size >= 16 && size <= 1024 && size%4 == 0 && !stillBrands[string(raw[8:12])] { |
| 95 | return "video/mp4" |
| 96 | } |
| 97 | return "" |
| 98 | } |
| 99 | if docType(raw) == "webm" { |
| 100 | return "video/webm" |
| 101 | } |
| 102 | return "" |
| 103 | } |
| 104 | |
| 105 | // docType is the DocType of an EBML header at the start of raw, or "". |
| 106 | func docType(raw []byte) string { |
| 107 | if !bytes.HasPrefix(raw, []byte{0x1a, 0x45, 0xdf, 0xa3}) { |
| 108 | return "" |
| 109 | } |
| 110 | size, n := ebmlSize(raw[4:]) |
| 111 | if n == 0 { |
| 112 | return "" |
| 113 | } |
| 114 | body := raw[4+n:] |
| 115 | if size < uint64(len(body)) { |
| 116 | body = body[:size] |
| 117 | } |
| 118 | for len(body) > 0 { |
| 119 | id, idLen := ebmlID(body) |
| 120 | if idLen == 0 { |
| 121 | return "" |
| 122 | } |
| 123 | size, sizeLen := ebmlSize(body[idLen:]) |
| 124 | if sizeLen == 0 || uint64(len(body)-idLen-sizeLen) < size { |
| 125 | return "" |
| 126 | } |
| 127 | value := body[idLen+sizeLen : idLen+sizeLen+int(size)] |
| 128 | if id == 0x4282 { |
| 129 | return string(value) |
| 130 | } |
| 131 | body = body[idLen+sizeLen+int(size):] |
| 132 | } |
| 133 | return "" |
| 134 | } |
| 135 | |
| 136 | // ebmlID reads an element ID (its length marker kept), and its length. |
| 137 | func ebmlID(b []byte) (uint32, int) { |
| 138 | if len(b) == 0 || b[0] == 0 { |
| 139 | return 0, 0 |
| 140 | } |
| 141 | n := 1 |
| 142 | for mask := byte(0x80); b[0]&mask == 0; mask >>= 1 { |
| 143 | n++ |
| 144 | } |
| 145 | if n > 4 || len(b) < n { |
| 146 | return 0, 0 |
| 147 | } |
| 148 | var id uint32 |
| 149 | for _, c := range b[:n] { |
| 150 | id = id<<8 | uint32(c) |
| 151 | } |
| 152 | return id, n |
| 153 | } |
| 154 | |
| 155 | // ebmlSize reads a variable-length size, its marker taken off. |
| 156 | func ebmlSize(b []byte) (uint64, int) { |
| 157 | if len(b) == 0 || b[0] == 0 { |
| 158 | return 0, 0 |
| 159 | } |
| 160 | n := 1 |
| 161 | mask := byte(0x80) |
| 162 | for ; b[0]&mask == 0; mask >>= 1 { |
| 163 | n++ |
| 164 | } |
| 165 | if len(b) < n { |
| 166 | return 0, 0 |
| 167 | } |
| 168 | v := uint64(b[0] & (mask - 1)) |
| 169 | for _, c := range b[1:n] { |
| 170 | v = v<<8 | uint64(c) |
| 171 | } |
| 172 | return v, n |
| 173 | } |
| 174 | |
| 175 | // videoFail is a refusal of a clip: a code for the editor, which words |
| 176 | // it from the catalog, and a developer's sentence. |
| 177 | func videoFail(w http.ResponseWriter, status int, code string) { |
| 178 | writeAssetJSON(w, status, map[string]string{"error": code, "message": videoFailures[code]}) |
| 179 | } |
| 180 | |
| 181 | var videoFailures = map[string]string{ |
| 182 | "too_large": "A clip may be at most 50 MiB.", |
| 183 | "not_a_video": "A clip must be an MP4 or a WebM video.", |
| 184 | "poster_required": "A clip is registered with a poster: the ref of a PNG or WebP picture registered for this deck.", |
| 185 | "poster_too_large": "A clip's poster may be at most 4 MiB.", |
| 186 | "not_found": "No upload staged by you for this deck has that ref, or its bytes never arrived.", |
| 187 | "hash_mismatch": "The bytes that arrived do not have the hash the upload declared.", |
| 188 | "already_verified": "That upload address is already in use.", |
| 189 | "internal": "The clip could not be stored. Try again.", |
| 190 | } |
| 191 | |
| 192 | // registerVideo is registerAsset for a receipt staged as a video: check |
| 193 | // the poster, read the bytes back, refuse anything but an MP4 or a WebM |
| 194 | // of at most 50 MiB, put them back under their own hash, record the |
| 195 | // verification, and answer the record the browser registers. |
| 196 | func (a *app) registerVideo(w http.ResponseWriter, r *http.Request, u User, d Deck, store blobs.Store, up AssetUpload, name, alt, poster string, width, height int, duration int64) { |
| 197 | object := up.ObjectKey |
| 198 | if object == "" { |
| 199 | videoFail(w, http.StatusNotFound, "not_found") |
| 200 | return |
| 201 | } |
| 202 | refused, err := a.posterFor(r.Context(), store, d, poster) |
| 203 | if err != nil { |
| 204 | a.logger.Error("slides: check a clip's poster", "deck", d.Sqid, "err", err) |
| 205 | videoFail(w, http.StatusInternalServerError, "internal") |
| 206 | return |
| 207 | } |
| 208 | if refused != "" { |
| 209 | videoFail(w, http.StatusUnprocessableEntity, refused) |
| 210 | return |
| 211 | } |
| 212 | raw, err := a.readObject(r.Context(), store, object, maxVideoBytes) |
| 213 | if err != nil { |
| 214 | switch { |
| 215 | case errors.Is(err, blobs.ErrNotFound): |
| 216 | videoFail(w, http.StatusNotFound, "not_found") |
| 217 | case errors.Is(err, errAssetTooLarge): |
| 218 | videoFail(w, http.StatusRequestEntityTooLarge, "too_large") |
| 219 | default: |
| 220 | a.logger.Error("slides: read an uploaded clip", "deck", d.Sqid, "err", err) |
| 221 | videoFail(w, http.StatusInternalServerError, "internal") |
| 222 | } |
| 223 | return |
| 224 | } |
| 225 | kind := sniffVideo(raw) |
| 226 | if kind == "" { |
| 227 | videoFail(w, http.StatusUnprocessableEntity, "not_a_video") |
| 228 | return |
| 229 | } |
| 230 | stored, err := store.Put(r.Context(), bytes.NewReader(raw), kind) |
| 231 | if err != nil { |
| 232 | a.logger.Error("slides: promote a staged clip", "deck", d.Sqid, "err", err) |
| 233 | videoFail(w, http.StatusInternalServerError, "internal") |
| 234 | return |
| 235 | } |
| 236 | ref := stored.Hash |
| 237 | if err := a.guarded(r.Context(), a.deckGuard(r.Context(), u, d), func(db *gorm.DB) error { |
| 238 | return db.Clauses(clause.OnConflict{DoNothing: true}). |
| 239 | Create(&DeckAsset{DeckID: d.ID, Ref: ref, CreatedAt: time.Now().UTC()}).Error |
| 240 | }); err != nil { |
| 241 | if a.guardRefused(w, r, err) { |
| 242 | return |
| 243 | } |
| 244 | a.fail(w, r, "record a verified clip", err) |
| 245 | return |
| 246 | } |
| 247 | a.spendUpload(r, d, up, object, ref) |
| 248 | id, err := newID() |
| 249 | if err != nil { |
| 250 | a.fail(w, r, "mint an asset id", err) |
| 251 | return |
| 252 | } |
| 253 | if duration <= 0 || duration > maxVideoDuration { |
| 254 | duration = 0 |
| 255 | } |
| 256 | writeAssetJSON(w, http.StatusOK, map[string]any{ |
| 257 | "id": id, |
| 258 | "ref": ref, |
| 259 | "name": trimTo(name, maxAssetName), |
| 260 | "width": boundDimension(width), |
| 261 | "height": boundDimension(height), |
| 262 | "alt": trimTo(alt, maxAssetAlt), |
| 263 | "poster": poster, |
| 264 | "duration": duration, |
| 265 | }) |
| 266 | } |
| 267 | |
| 268 | // posterFor checks a clip's poster: a picture this deck verified (its |
| 269 | // deck_assets row, as serveAsset requires), a PNG or WebP, the two a |
| 270 | // canvas draws a frame as, and at most a still's 4 MiB. It answers the |
| 271 | // refusal's code, or "" for a poster that will do. |
| 272 | func (a *app) posterFor(ctx context.Context, store blobs.Store, d Deck, ref string) (string, error) { |
| 273 | if !assetRefPattern.MatchString(ref) { |
| 274 | return "poster_required", nil |
| 275 | } |
| 276 | var verified int64 |
| 277 | if err := a.db.G.WithContext(ctx).Model(&DeckAsset{}). |
| 278 | Where("deck_id = ? AND ref = ?", d.ID, ref).Count(&verified).Error; err != nil { |
| 279 | return "", err |
| 280 | } |
| 281 | if verified == 0 { |
| 282 | return "poster_required", nil |
| 283 | } |
| 284 | raw, err := a.readObject(ctx, store, ref, maxStillBytes) |
| 285 | switch { |
| 286 | case errors.Is(err, errAssetTooLarge): |
| 287 | return "poster_too_large", nil |
| 288 | case errors.Is(err, blobs.ErrNotFound): |
| 289 | return "poster_required", nil |
| 290 | case err != nil: |
| 291 | return "", err |
| 292 | } |
| 293 | if kind := sniffImage(raw); kind != "image/png" && kind != "image/webp" { |
| 294 | return "poster_required", nil |
| 295 | } |
| 296 | return "", nil |
| 297 | } |
| 298 | |
| 299 | // errNotVideo is an object that does not open as a clip's video does. |
| 300 | var errNotVideo = errors.New("slides: this object is not a video") |
| 301 | |
| 302 | // videoLoad is the clip cache's load for object: the store read once, |
| 303 | // its head sniffed (anything but an MP4 or WebM is errNotVideo), and the |
| 304 | // whole of it handed on as one stream. |
| 305 | func videoLoad(ctx context.Context, store blobs.Store, object string) func() (string, io.Reader, func(), error) { |
| 306 | return func() (string, io.Reader, func(), error) { |
| 307 | rc, err := store.Get(ctx, object) |
| 308 | if err != nil { |
| 309 | return "", nil, nil, err |
| 310 | } |
| 311 | return sniffedVideo(rc) |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | // sniffedVideo reads rc's head, and answers its kind and rc again, |
| 316 | // whole: rc itself, rewound, when it seeks, else (it cannot, or the |
| 317 | // rewind fails) the head and the rest. |
| 318 | func sniffedVideo(rc io.ReadCloser) (string, io.Reader, func(), error) { |
| 319 | head := make([]byte, 1024) |
| 320 | n, err := io.ReadFull(rc, head) |
| 321 | if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) && !errors.Is(err, io.EOF) { |
| 322 | rc.Close() |
| 323 | return "", nil, nil, err |
| 324 | } |
| 325 | kind := sniffVideo(head[:n]) |
| 326 | if kind == "" { |
| 327 | rc.Close() |
| 328 | return "", nil, nil, errNotVideo |
| 329 | } |
| 330 | release := func() { rc.Close() } |
| 331 | if rs, ok := rc.(io.ReadSeeker); ok { |
| 332 | if _, err := rs.Seek(0, io.SeekStart); err == nil { |
| 333 | return kind, rs, release, nil |
| 334 | } |
| 335 | } |
| 336 | return kind, io.MultiReader(bytes.NewReader(head[:n]), rc), release, nil |
| 337 | } |
| 338 | |
| 339 | // serveCachedVideo serves ref's video from the clip cache, filled by |
| 340 | // load when it is not there yet. |
| 341 | func (a *app) serveCachedVideo(w http.ResponseWriter, r *http.Request, cache *clipCache, ref string, load func() (string, io.Reader, func(), error)) { |
| 342 | body, kind, done, err := cache.get(ref, true, load) |
| 343 | if err != nil { |
| 344 | if errors.Is(err, blobs.ErrNotFound) || errors.Is(err, errNotVideo) { |
| 345 | a.notFound(w, r) |
| 346 | return |
| 347 | } |
| 348 | a.fail(w, r, "serve a clip", err) |
| 349 | return |
| 350 | } |
| 351 | defer done() |
| 352 | serveVideo(w, r, kind, body) |
| 353 | } |
| 354 | |
| 355 | // serveVideo hands over a clip's bytes in whatever ranges were asked |
| 356 | // for. ServeContent answers Range, If-Range and If-None-Match against |
| 357 | // the ETag already set; a modification time it has no use for. |
| 358 | func serveVideo(w http.ResponseWriter, r *http.Request, kind string, body io.ReadSeeker) { |
| 359 | assetHeaders(w, kind) |
| 360 | http.ServeContent(w, r, "", time.Time{}, body) |
| 361 | } |
| 362 | |
| 363 | // --- GET /d/{sqid}/uploads/{ref} --- |
| 364 | |
| 365 | // stagedVideo answers a staged clip's bytes to the person who staged |
| 366 | // it, for this deck, while the receipt is unspent and fresh: the same |
| 367 | // receipt putUpload and registerAsset resolve, so nobody else's staged |
| 368 | // bytes, and nothing that is not a video, ever comes back. Not cached: |
| 369 | // the address is a staging key, gone once the clip is registered. |
| 370 | func (a *app) stagedVideo(w http.ResponseWriter, r *http.Request) { |
| 371 | u, ok := a.viewer(w, r) |
| 372 | if !ok { |
| 373 | return |
| 374 | } |
| 375 | d, ok := a.deckFor(w, r, u) |
| 376 | if !ok { |
| 377 | return |
| 378 | } |
| 379 | store := a.cfg.Blobs |
| 380 | key := chi.URLParam(r, "ref") |
| 381 | if store == nil || !assetRefPattern.MatchString(key) { |
| 382 | a.notFound(w, r) |
| 383 | return |
| 384 | } |
| 385 | up, staged, err := a.stagedUpload(r.Context(), d, actorFor(u), key) |
| 386 | if err != nil { |
| 387 | a.fail(w, r, "resolve a staged clip", err) |
| 388 | return |
| 389 | } |
| 390 | if !staged || !isVideo(up.ContentType) || up.ObjectKey == "" { |
| 391 | a.notFound(w, r) |
| 392 | return |
| 393 | } |
| 394 | // A staging key names an upload, not its bytes: cached apart from |
| 395 | // any registered clip, unchecked against its name, and read from the |
| 396 | // store once however many ranges the poster's drawing asks for. |
| 397 | body, kind, done, err := a.clipCacheFor().get("staged-"+key, false, videoLoad(r.Context(), store, up.ObjectKey)) |
| 398 | if err != nil { |
| 399 | if errors.Is(err, blobs.ErrNotFound) || errors.Is(err, errNotVideo) { |
| 400 | a.notFound(w, r) |
| 401 | return |
| 402 | } |
| 403 | a.fail(w, r, "read a staged clip", err) |
| 404 | return |
| 405 | } |
| 406 | defer done() |
| 407 | w.Header().Set("Cache-Control", "no-store") |
| 408 | serveVideo(w, r, kind, body) |
| 409 | } |
| 410 | |