| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | // webmHead is the EBML header a WebM opens with: the header element |
| 9 | // (1A 45 DF A3), its size, and inside it the version fields and the |
| 10 | // DocType, here docType. |
| 11 | func webmHead(docType string) []byte { |
| 12 | body := []byte{ |
| 13 | 0x42, 0x86, 0x81, 0x01, // EBMLVersion 1 |
| 14 | 0x42, 0xf7, 0x81, 0x01, // EBMLReadVersion 1 |
| 15 | 0x42, 0xf2, 0x81, 0x04, // EBMLMaxIDLength 4 |
| 16 | 0x42, 0xf3, 0x81, 0x08, // EBMLMaxSizeLength 8 |
| 17 | 0x42, 0x82, 0x80 | byte(len(docType)), |
| 18 | } |
| 19 | body = append(body, docType...) |
| 20 | body = append(body, 0x42, 0x87, 0x81, 0x04, 0x42, 0x85, 0x81, 0x02) |
| 21 | out := append([]byte{0x1a, 0x45, 0xdf, 0xa3, 0x80 | byte(len(body))}, body...) |
| 22 | return append(out, 0x18, 0x53, 0x80, 0x67, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff) |
| 23 | } |
| 24 | |
| 25 | // mp4Head is an ISO BMFF file's first box, ftyp, with major brand. |
| 26 | func mp4Head(brand string) []byte { |
| 27 | box := []byte{0, 0, 0, 0x18, 'f', 't', 'y', 'p'} |
| 28 | box = append(box, brand...) |
| 29 | box = append(box, 0, 0, 0, 0) |
| 30 | box = append(box, brand...) |
| 31 | box = append(box, "mp41"...) |
| 32 | return append(box, 0, 0, 0, 8, 'f', 'r', 'e', 'e') |
| 33 | } |
| 34 | |
| 35 | // TestSniffVideo: a clip is an MP4 (an ftyp box first, and not one of |
| 36 | // the still-picture brands that share the box) or a WebM (an EBML |
| 37 | // header whose DocType is webm), read from the bytes, never a header. |
| 38 | func TestSniffVideo(t *testing.T) { |
| 39 | for _, c := range []struct { |
| 40 | name string |
| 41 | raw []byte |
| 42 | want string |
| 43 | }{ |
| 44 | {"a WebM", webmHead("webm"), "video/webm"}, |
| 45 | {"an MP4", mp4Head("isom"), "video/mp4"}, |
| 46 | {"an MP4 of another brand", mp4Head("mp42"), "video/mp4"}, |
| 47 | {"a Matroska file", webmHead("matroska"), ""}, |
| 48 | {"an AVIF picture", mp4Head("avif"), ""}, |
| 49 | {"a HEIC picture", mp4Head("heic"), ""}, |
| 50 | {"a PNG", []byte("\x89PNG\r\n\x1a\n...."), ""}, |
| 51 | {"nothing", nil, ""}, |
| 52 | {"an EBML header cut short", webmHead("webm")[:12], ""}, |
| 53 | {"text that says ftyp", []byte("hi! ftypisom and more"), ""}, |
| 54 | } { |
| 55 | if got := sniffVideo(c.raw); got != c.want { |
| 56 | t.Errorf("%s: sniffVideo = %q, want %q", c.name, got, c.want) |
| 57 | } |
| 58 | } |
| 59 | // A picture is never taken for a video, nor a video for a picture. |
| 60 | if k := sniffImage(webmHead("webm")); k != "" { |
| 61 | t.Errorf("a WebM sniffs as the picture %q", k) |
| 62 | } |
| 63 | if !bytes.HasPrefix(mp4Head("isom")[4:], []byte("ftyp")) { |
| 64 | t.Fatal("the MP4 head is wrong") |
| 65 | } |
| 66 | } |
| 67 | |