# Media

Pictures (`img`), pictures that are drawn on (`paint`, `canvas layers=`),
codes (`scan`), the camera, video and sound (`vid`, `aud`, `reel`: a film of
tracks, keyframes and grades), speech and microphones (recorded, too), an `audio` or `video` led
from the page, and sounds with no element (`sound`). Drawing with your own code is in [drawing.md](drawing.md).
Back to the [map](README.md).

```mote
// docs: whole
state shot: bytes? = none
state info = ""

action choose
  let file = fs.pick("image/png,image/jpeg")?
  if file == none return
  let im = img.decode(file.data)?
  info = `${im.width} by ${im.height}`
  shot = img.jpeg(img.fit(im, 1600)?, 80)?

column gap=8 padding=16
  button "Choose a picture" press=choose disabled=pending(choose)
  if shot
    image shot.url() max-width=100%
  text info color=dim
  text (failure(choose) ?? "") color=danger
```

## Mental model

Four kinds of value carry media. Each is a plain record, so it can be kept
in state, passed to a fn, and (the first one) stored.

| Type | Is | Made by |
|---|---|---|
| `image` | `{width, height, data}`: RGBA pixels, rows top to bottom, in `bytes`; 8 bits a sample unless it says `depth: 16`. A decoded one may also carry `space` and `profile` ([colour](#colour)) | `img.decode`, `paint.image`, `cam.shot`, `vid.frame`, `draw.read`, `gl.image`, `clipboard.image` |
| `sheet` | `{id, width, height}`: a picture that is drawn on; the pixels stay on the page behind the id | `paint.new`, `paint.from` |
| `video` | `{id, width, height, duration, fps, frames, audio}`: an opened file | `vid.open` |
| `sound` | `{id, duration}`: a decoded sound | `aud.open` |

An `image` holds its pixels, so it is large: 4 bytes a pixel (8 for a deep
one). The other
three are small handles; what stands behind the id lives in the runtime
until it is dropped or closed.

Where the work happens:

- `img` and `scan` are Mote's own codecs, in Rust, compiled to wasm, run
  **in a worker**. Every call waits and can fail. Pixels are moved to the
  worker, not copied, when the page is done with them
  ([reactivity.md](reactivity.md#what-is-copied-and-what-is-moved)).
- `paint` works on canvases **on the page**. None of its calls waits or can
  fail.
- `vid` uses the browser's codecs (WebCodecs) to decode and encode; Mote's
  own wasm reads and writes the MP4 file.

To show an `image`: encode it (`img.png(p)?`, `img.jpeg(p)?`) and show the
bytes (`image shot.url()`, as above), or put it on a sheet and show the
sheet with `canvas layers=`, or draw it on a `surface`. The `image` tag
itself takes an address: handed an `image` value it is refused (`H069`).

An `image` is plain bytes, so a program can make one itself
(`{width: w, height: h, data: bytes.new(w * h * 4)}`, then write the
pixels: [language.md](language.md#bytes)), and run one through a shader
(`gl.filter`: [drawing.md](drawing.md#a-picture-through-a-shader)).

## img

A picture is an `image`. Mote's own codecs, in a worker. The same calls
work in a `server fn` (the same wasm, run in place): a thumbnail can be
made where the file is kept, `server fn thumb(picture: bytes, width:
number): bytes` with `img.decode`, `img.resize`, `img.png`. What the
browser's own codecs read for a page (lossy WebP, AVIF) is not read there.

| Call | Gives |
|---|---|
| `img.decode(b)` | A file's picture, upright (as its Exif orientation says). `b` is its bytes, or a file [picked unread](data.md#files-not-read-yet); so it is for `img.info` and `img.frames`. |
| `img.decode(b, {fit: 2560})` | The same, its long side 2560 pixels at most ([a photo that fits](#a-photo-that-fits)). |
| `img.decode(b, {deep, orient, native, fit})` | The same with choices ([Formats](#formats)). |
| `img.info(b)` | What a file says, without decoding it ([below](#what-a-file-says)). |
| `img.frames(b)` | Every frame of a moving GIF, each a whole picture with `delay` (milliseconds). |
| `img.png(p)` | A PNG file's bytes. |
| `img.jpeg(p, quality)` | A JPEG file's bytes; quality 1 to 100, 85 if left out. |
| `img.tiff(p)` | A TIFF file's bytes, compressed; `img.tiff(p, false)` is not compressed. |
| `img.bmp(p)` | A BMP file's bytes. |
| `img.resize(p, width, height)` | That size. Leave a side out (or give 0) to keep the shape. |
| `img.fit(p, width, height)` | The largest that fits inside, never enlarged. Height may be left out. |
| `img.crop(p, x, y, width, height)` | That part. |
| `img.rotate(p, 90)` | Turned clockwise; a multiple of 90. |
| `img.mirror(p)` · `img.flip(p)` | Left to right · top to bottom. |
| `img.blur(p, radius)` | Blurred. |
| `img.gray(p)` · `img.invert(p)` | |
| `img.adjust(p, {brightness, contrast, saturation})` | Each -1 to 1; any may be left out. |
| `img.fill(p, x, y, "#rrggbb", tolerance)` | The paint bucket: what joins (x, y) and is like it. Tolerance 0 to 255, 0 if left out. |
| `img.depth(p, 16)` · `img.depth(p, 8)` | The same picture at that depth ([Deep pictures](#deep-pictures)). |
| `img.convert(p, "display-p3")` | Its pixels taken to that colour space ([Colour](#colour)). |

Every call can fail and gives a new picture.

```mote
let im = img.decode(file)?
shot = img.jpeg(img.fit(im, 1600)?, 80)?        // both moved
```

The checker corrects habits: `img.grayscale` → `img.gray`, `img.scale` →
`img.resize`, `img.encode` → `img.png`, `img.jpeg`, `img.tiff` or
`img.bmp`, `img.exif` → `img.info`, `img.raw` → `img.decode`. `img.gif`
and `img.webp` do not exist: img writes png, jpeg, tiff and bmp.

```mote
// docs: whole
state said = ""
state frames: bytes[] = []
state out: bytes? = none

action open
  let f = fs.pick("image/*,.tif,.tiff,.dng")?
  if f == none return
  let info = img.info(f.data)?
  said = `${info.format}, ${info.width} by ${info.height}, ${info.depth} bits, ${info.space == "" ? "no space named" : info.space}`
  if info.exif.model != "" said += `, taken with a ${info.exif.model}`
  frames = []
  if info.frames > 1
    for fr in img.frames(f.data)?
      frames.push(img.png(fr)?)
    return
  let p = img.decode(f.data, {deep: true})?
  let wide = img.convert(img.fit(p, 2000)?, "display-p3")?
  out = img.tiff(wide)?
  frames = [img.png(img.depth(wide, 8)?)?]

column gap=8 padding=16
  row gap=8
    button "Open a picture" press=open disabled=pending(open)
    if out
      link "Get it as a TIFF" href=out.url("image/tiff") download="picture.tif"
  text said
  row gap=8 flex-wrap=wrap
    for f in frames
      image f.url("image/png") max-width=240
  text (failure(open) ?? "") color=danger
```

### Formats

| File | Read by | Notes |
|---|---|---|
| PNG, JPEG | Mote | |
| TIFF | Mote | Its first page. |
| GIF | Mote | Its first frame; `img.frames` gives them all. |
| BMP, lossless WebP | Mote | |
| A camera's raw file (DNG, CR2, NEF, ARW, RW2, RAF) | Mote | The JPEG preview the camera put in it: a picture the camera developed. The sensor's data is not read. |
| What else the browser shows (lossy WebP, AVIF; HEIC in Safari) | the browser | As sRGB, 8 bits. |

What Mote reads gives the same pixels in every browser. What it does not
(a CMYK or 12-bit JPEG, a TIFF in CMYK or Lab, a moving WebP) is tried by
the browser, and fails if that cannot read it either.

`img.decode(b, {deep: true, orient: false, native: false, fit: 2560})`:

| Choice | Means |
|---|---|
| `deep: true` | 16 bits are kept where the file has them (PNG, TIFF). Unsaid, every picture is 8 bits. |
| `orient: false` | As stored, not turned upright. |
| `native: false` | Never the browser's decoder: only Mote's own. |
| `fit: 2560` | Its long side is that many pixels at most; a smaller picture is as it is, never enlarged. Below. |

Written: PNG, JPEG, TIFF, BMP. A picture larger than 100 megapixels, or
with a side over 65,535, is refused.

### A photo that fits

A 24-megapixel photo is 96 MB of pixels, before anything is done with it: on
a phone, enough for the browser to close the page. Say how large it is
wanted, and it is never that large:

```mote
action keep(f: picked)
  let im = img.decode(f, {fit: 2560})?
  db.set(f.name, img.jpeg(im, 85)?)?
```

- **The same size as `img.fit` gives**: the long side is `fit` pixels, or
  its own if that is fewer. It is turned upright as ever. 1 or more (`H187`
  for one written below).
- **A JPEG is read at 1/2, 1/4 or 1/8 of its size** (the smallest that is
  still no smaller than `fit`), a row of blocks at a time, shrunk and turned
  as it is read. Measured on a 6000 × 4000 JPEG of 6 MB, to 2560: 24 MB of
  the battery's memory and 0.2 s, where decoding it whole and then shrinking
  it takes 149 MB and 0.9 s; to 1600, 14 MB.
- **Its pixels** are those of decoding it whole and shrinking it but for
  what the eye does not see (over 38 dB). For every other kind of file they
  are the same.
- A PNG and a BMP are shrunk a row at a time too (the PNG's file is in
  memory twice). Read whole first, and only then shrunk: an interlaced PNG,
  a GIF, a TIFF, a lossless WebP; and what the browser reads, by the
  browser.
- A progressive JPEG holds its coefficients until its last scan, the ones
  it needs: 72 MB for 24 megapixels whole, some 39 MB to 2560, 14 MB to
  1500.
- **Not enough memory** fails the call
  (`img: there is not enough memory`, `err.kind` is `"memory"`), and the
  next call works. It is still the browser that decides when a page is too
  large: what is never asked for is the only safe pixel.
- The battery's memory is given up after a large picture. A worker's copy of
  a file goes with the call: hand `img.decode` a file
  [picked unread](data.md#files-not-read-yet) and the page never holds it.

### What a file says

`img.info(b)` reads a file's facts without decoding it:

| Field | Is |
|---|---|
| `format` | `"png"` `"jpeg"` `"tiff"` `"gif"` `"bmp"` `"webp"` `"raw"` `"avif"` `"heic"`. |
| `width`, `height` | Its size, upright. |
| `depth` | Bits a sample: 8 or 16. |
| `alpha` | Whether it has any. |
| `frames` | How many (a moving GIF: more than 1). |
| `space` | Its colour space's name, `""` if the file names none. |
| `orientation` | The Exif orientation, 1 to 8 (1 is upright). |
| `own` | Mote's codec reads it (false: the browser's would). |
| `preview` | It is a raw file's preview that would be read. |
| `exif` | `{make, model, lens, software, artist, copyright, taken, iso, exposure, aperture, focal, focal35, bias, flash, lat, lon, alt}` |

In `exif`, `taken` is as the camera wrote it (`"2024:05:17 14:03:22"`),
`exposure` is seconds, `focal` and `focal35` millimetres. What a file does
not say is `""` or 0; a place (`lat`, `lon`, `alt`) it does not say is
`none`.

### Deep pictures

A picture with `depth: 16` has two bytes a sample in `data`, low byte
first: 8 bytes a pixel.

- `img.decode(b, {deep: true})` keeps 16 bits where a PNG or a TIFF has
  them. `img.depth(p, 16)` and `img.depth(p, 8)` take one to the other.
- `img.png` and `img.tiff` write 16 bits; `img.jpeg` and `img.bmp` write 8.
- `resize` `fit` `crop` `rotate` `mirror` `flip` `gray` `invert` `adjust`
  and `convert` work on it. `blur` and `fill` refuse it:
  `img.depth(p, 8)` first.
- On the page it shows as its high bytes: `draw.image`, `paint.put` and
  `paint.from` take it. Elsewhere give 8 bits (`img.depth(p, 8)?`): a `gl`
  texture, `gl.filter`, `paint.draw`, a brush's `tip`, `clipboard.put`.

### Colour

A decoded picture has `space`, its colour space's name (`"srgb"`
`"display-p3"` `"adobe-rgb"` `"prophoto"`, `"linear-srgb"` …, or what its
profile calls itself), and `profile`, the file's ICC profile as bytes, when
the file gives them (PNG, JPEG, TIFF, WebP).

- Both stay with the picture through every `img` call, and go into the
  PNG, JPEG or TIFF written.
- `img.convert(p, "display-p3")` takes the pixels there through linear
  light (from sRGB if the picture names nothing) and gives it that
  profile. The names: `srgb`, `display-p3`, `adobe-rgb`, `prophoto`, and
  each after `linear-`.
- Only a profile that is a matrix and three curves converts (cameras,
  screens, the named spaces). A printer's or CMYK's table is kept and
  passed on, and `img.convert` of it fails.
- The page itself draws every picture as sRGB: a sheet, a surface and
  `canvas layers=` do not read the profile. A picture put on a sheet and
  taken off again has no `space`.

## paint

Pictures that are drawn on. None of these waits or can fail.

```mote
// docs: whole
state stack: {sheet: sheet, opacity: number?, blend: string?}[] = []
state color = "#1d4ed8"
state picked = ""

action start
  let paper = paint.new(600, 400, "#ffffff")
  let ink = paint.new(600, 400)
  paint.text(paper, "Draw here", 20, 20, {color: "#999999", size: 24})
  stack = [{sheet: paper}, {sheet: ink, opacity: 0.9, blend: "multiply"}]

action stroke(p: {x: number, y: number})
  let top = stack.at(-1)
  if top == none return
  paint.line(top.sheet, p.x, p.y, p.x + 1, p.y + 1, {color, size: 8, soft: 0.4})

action soften
  let top = stack.at(-1)
  if top == none return
  paint.put(top.sheet, img.blur(paint.image(top.sheet), 6)?)

action look(p: {x: number, y: number})
  picked = paint.color(stack, p.x, p.y)

task
  start()

column gap=8 padding=16
  canvas layers=stack width=600 height=400 pointerdown=stroke pointermove=stroke dblclick={soften()} max-width=100%
  row gap=8
    button "Blur the ink" press=soften
    text picked
```

| Call | Does |
|---|---|
| `paint.new(width, height, colour?)` | A `sheet`, clear unless a colour is given. At most 8192 each way. |
| `paint.from(picture)` | A sheet holding an `image`. |
| `paint.line(s, x0, y0, x1, y1, {color, size, soft, tip, spacing, …})` | A stroke: hard, or with `soft` 0 to 1 a run of blurred dabs; with a `tip`, a run of dabs of that shape ([Brushes](#brushes)). |
| `paint.stamp(s, tip, x, y, {size, turn, round, color})` | One dab of a tip, its middle at x, y. |
| `paint.shape(s, "rect" \| "ellipse" \| "line", x0, y0, x1, y1, {color, size, fill, radius})` | Between two corners: an outline `size` thick, or filled (`fill: true`). `radius` rounds a rectangle's corners. |
| `paint.path(s, points, {color, size, fill, closed, rule})` | An outline through points, smooth-edged: points as `draw.path` takes them. A list of such lists is several in one; with `rule: "evenodd"` the inner ones are holes. |
| `paint.gradient(s, x0, y0, x1, y1, "#from", "#to", {opacity})` | One colour at the first point running to the other at the second. |
| `paint.text(s, "words", x, y, {color, size, weight, font, italic, align, baseline, spacing, lineHeight})` | Words, from their top left corner; with `align: "center"` or `"right"`, about or up to x. Lines are split at `"\n"`. |
| `paint.measure("words", {size, weight, font, italic, spacing, lineHeight})` | Their `{width, height, ascent, descent}`. It takes no sheet: it works anywhere. |
| `paint.image(s)` · `paint.image(s, x, y, w, h)` | Its pixels as an `image` (so `img.*` works on it), or a part. |
| `paint.put(s, picture or sheet)` · `paint.put(s, p, x, y)` | Replaces what is on it; with x, y: only where `p` lands. |
| `paint.draw(s, picture or sheet, x, y, {width, height, turn, from, smooth})` · `paint.draw(s, layers)` | Draws it over what is there (`put` replaces), with no pixels read back. A list of layers is drawn as `canvas layers=` would. |
| `paint.clear(s)` · `paint.clear(s, x, y, w, h)` | |
| `paint.copy(s)` · `paint.drop(s)` | A new sheet that looks the same · gives a sheet up. |
| `paint.flat(layers, width, height)` | The layers as one `image`. |
| `paint.color(layers, x, y)` | `"#rrggbb"` there. |

**How a drawing meets what is there.** `line`, `stamp`, `shape`, `path`,
`text` and `draw` take these among their options:

| Option | Means |
|---|---|
| `opacity` | 0 to 1. |
| `erase: true` | Rubs out instead of drawing. |
| `blend` | Any of a canvas's names: `"multiply"`, `"screen"`, `"lighter"`, `"source-atop"` (only where something already is), `"destination-in"` (what is there is kept only where this is) … |
| `clip: {x, y, width, height}` | Draws only inside that rectangle. |

`gradient` takes `opacity` and `clip` only.

- `paint.draw`'s options: `width`, `height` (its own size if unsaid),
  `turn` (degrees, about its middle), `from: {x, y, width, height}` (only
  that part of the picture), `smooth: false` for hard pixels.
- Text is 32 px, weight 600, system-ui unless said; `spacing` is pixels
  between letters; `lineHeight` is in sizes (1.2 unsaid).
- A filter is a round trip through a worker:
  `paint.put(l.sheet, img.blur(paint.image(l.sheet), 6)?)`. Or it stays on
  the graphics card: `paint.put(l.sheet, gl.filter(l.sheet, fs))`
  ([drawing.md](drawing.md#a-picture-through-a-shader)).

### Brushes

```mote
// docs: whole
state ink = paint.new(600, 300)
state mask = paint.new(600, 300)
state tip = paint.new(32, 32)
state stack: {sheet: sheet?, mask: sheet?, blend: string?, filter: string?, clip: bool?}[] = []
state erasing = false
state last: {x: number, y: number}? = none

action start
  let paper = paint.new(600, 300, "#ffffff")
  paint.shape(tip, "ellipse", 4, 10, 28, 22, {color: "#000000", fill: true})
  paint.shape(mask, "rect", 20, 20, 580, 280, {color: "#000000", fill: true, radius: 24})
  paint.path(paper, [[[40, 260], [300, 40], [560, 260]], [[220, 220], [300, 140], [380, 220]]], {color: "#eeeeee", fill: true, rule: "evenodd"})
  let m = paint.measure("Draw here", {size: 28, weight: 700})
  paint.text(paper, "Draw here", 300, 20, {size: 28, weight: 700, align: "center", color: "#999999", spacing: 1})
  paint.shape(paper, "line", 300 - m.width / 2, 24 + m.height, 300 + m.width / 2, 24 + m.height, {color: "#cccccc", size: 2})
  stack = [{sheet: paper}, {sheet: ink, mask, blend: "multiply"}, {filter: "contrast(1.1)"}]

action down(p: {x: number, y: number, width: number})
  last = {x: p.x * 600 / p.width, y: p.y * 600 / p.width}

action stroke(p: {x: number, y: number, width: number, pressure: number})
  let from = last
  if from == none return
  let to = {x: p.x * 600 / p.width, y: p.y * 600 / p.width}
  paint.line(ink, from.x, from.y, to.x, to.y, {tip, color: "#1d4ed8", size: 12 + 20 * p.pressure, spacing: 0.2, follow: true, scatter: 0.1, erase: erasing})
  last = to

action spray(p: {x: number, y: number, width: number})
  paint.stamp(ink, tip, p.x * 600 / p.width, p.y * 600 / p.width, {size: 48, turn: 45, color: "#dc2626", opacity: 0.5})

action copyOut
  let both = paint.new(600, 300)
  paint.draw(both, stack)
  paint.draw(both, ink, 400, 200, {width: 150, height: 75, turn: -8, opacity: 0.8, blend: "multiply"})
  fs.save(img.png(paint.image(both))?, "drawing.png")?
  paint.drop(both)

task
  start()

column gap=8 padding=16
  canvas layers=stack width=600 height=300 pointerdown=down pointermove=stroke pointerup={last = none} dblclick=spray max-width=100%
  row gap=8
    button (erasing ? "Draw" : "Erase") press={erasing = !erasing}
    button "Save" press=copyOut
```

A `paint.line` with a `tip` or a `spacing` is a run of dabs.

| Option | Means |
|---|---|
| `tip` | A sheet or a picture: the dab's shape. Its longer side is `size` long. With `color`, the tip's shape (its alpha) in that colour; without, the tip as it is. |
| `spacing` | Sizes from dab to dab (0.25 unsaid). |
| `turn` | Degrees each dab is turned. |
| `round` | 1 to 0: how far each is flattened (1 is as it is). |
| `follow: true` | Each is turned the way the stroke goes. |
| `scatter` | Sizes each strays from the line (the same strays every time). |

- **A stroke goes on.** A run of dabs that begins where the last stroke on
  that sheet ended carries on its spacing, so a drag made of many short
  `paint.line`s is evenly dabbed.
- With no `tip`, the dabs are round: hard, or `soft`.
- `paint.stamp` is one dab; again and again, it is an airbrush.
- `pressure` from a pointer event (a pen's, 0 to 1) makes a good `size`
  ([events.md](events.md#the-events)).

### Layers

**A layer** is `{sheet}` with, if wanted:

| Field | Means |
|---|---|
| `opacity` | 0 to 1. |
| `blend` | `"multiply"`, `"screen"`, `"overlay"`, … as canvases name them. |
| `hidden` | Not shown. |
| `x`, `y` | Where its corner goes. |
| `scale`, `turn` | Scaled, and turned (degrees), about its middle. |
| `mask` | A sheet: the layer shows only where the mask has something. The mask is placed as the layer is. |
| `clip: true` | It shows only where the layer under it does (several in a row are all kept inside the same one). |
| `filter` | A CSS filter, as text: `"blur(4px)"`, `"drop-shadow(0 2px 4px #0008)"`. |

A layer with a `filter` and **no sheet** is an adjustment: all that is
under it, through the filter, as far as its `opacity`, and only where its
`mask` is if it has one.

### canvas layers=

```mote
canvas layers=stack width=1200 height=800
```

shows the layers, lowest first, and draws again when one (or a mask) is
drawn on, or the list or the size changes. Its `width` and `height` are the
picture's, in pixels; size it on the page with styles (`max-width=100%`).
Pointer events give `{x, y}` in the element's CSS pixels: if the canvas is
shown smaller than its picture, scale them (`p.x * 1200 / p.width`).
`image-rendering=pixelated` shows a small picture enlarged with hard
pixels.

Source: `runtime/page/paint.mote` (part `PA`; `PV` is the canvas).

## scan

`scan.read(picture)` gives the codes in an `image`, as `{format, text}[]`.
Formats: `qr_code` `ean_13` `ean_8` `code_128` `code_39` `itf` (a UPC-A is
an `ean_13` with a 0 in front).

It uses the browser's BarcodeDetector where there is one (Chrome, Android),
and Mote's own wasm reader in a worker everywhere else (iOS Safari, Firefox,
desktop Safari). `scan.read(p, {native: false})` always uses Mote's.

## camera

```mote
// docs: whole
state live = false
state seen = ""

action found(c: {format: string, text: string})
  seen = `${c.format}: ${c.text}`
  live = false

action snap
  let p = cam.shot()?
  let codes = scan.read(p)?
  seen = `${p.width} by ${p.height}, ${codes.length} codes`

column gap=8 padding=16
  camera on=live facing="back" scan=found max-width=100%
  row gap=8
    button (live ? "Stop" : "Start") press={live = !live}
    button "Snap" press=snap
  text seen
  text (cam.error ?? "") color=danger
```

`camera on=live facing="back" scan=found` is the device's camera, shown
while `on` is true.

- `on`: a bool. It is written `false` if the camera is refused or missing;
  `cam.error` (a `string?`) says why.
- `facing`: `"back"` (the default) or `"front"`.
- `scan=handler`: handed each code the camera sees, as `{format, text}`. It
  looks five times a second, and hands a code over when it first sees it,
  or sees it again after three seconds away.
- `cam.shot()` is the frame on show, as an `image`. It can fail (no camera).

Source: `runtime/page/camera.mote`.

## vid, aud and reel

Video. The browser's codecs decode and encode; Mote's own wasm reads and
writes the MP4.

```mote
// docs: whole
state clips: {src: video, from: number, to: number, dissolve: number?}[] = []
state titles: {at: number, len: number, text: string?, size: number?, color: string?}[] = []
state time = 0
state on = false

action open
  let f = fs.pick("video/mp4,video/quicktime")?
  if f == none return
  let v = vid.open(f.data)?
  let half = v.duration / 2
  clips = [{src: v, from: 0, to: half}, {src: v, from: half, to: v.duration, dissolve: 0.5}]
  titles = [{at: 0, len: 2, text: "A film", size: 0.1, color: "#ffffff"}]

action save
  let film = vid.export(clips, {layers: titles, width: 1280, height: 720})?
  fs.save(film, "film.mp4")?

column gap=8 padding=16
  reel clips=clips layers=titles at=time playing=on max-width=100%
  row gap=8
    button "Open" press=open
    button (on ? "Pause" : "Play") press={on = !on}
    button "Export" press=save disabled=pending(save)
  if pending(save)
    progress value=vid.progress max=1
  text `${time.toFixed(1)} s` color=dim
```

### vid

| Call | Gives |
|---|---|
| `vid.open(b)` | An MP4 or MOV as a `video`: `{id, width, height, duration, fps, frames, audio}`. |
| `vid.frame(v, seconds, width?)` | The picture then, an `image`; full size if no width. |
| `vid.strip(v, count, height)` | That many pictures side by side, each the key frame before its even step (quick: one decode each). |
| `vid.wave(v, width, height)` | Its sound, drawn white on clear, an `image`. |
| `vid.export(clips, {layers, sounds, width, height, fps, bitrate})` | The film as an MP4 (H.264, AAC), as bytes. The options may be left out. |
| `vid.progress` | 0 to 1 while an export runs (reactive). |
| `vid.levels` | How loud the second of an export just mixed was (reactive): `{peak, rms}` ([Levels](#levels)). |
| `vid.close(v)` | Gives the video up. |

All but `close` can fail.

### A film: clips, tracks, keys

A film is a list of clips, with layers over them and sounds under them.
`reel` shows it and `vid.export` writes it; both put each frame together
with the same code, so what plays is what is exported.

```mote
// docs: whole
shape Clip
  src: video
  from: number
  to: number
  track: number?
  at: number?
  scale: number?
  x: number?
  y: number?
  opacity: number?
  dissolve: number?
  wipe: string?
  reverse: bool?
  crop: {left: number?, right: number?, top: number?, bottom: number?, round: number?}?
  grade: {gain: number[]?, lift: number[]?, gamma: number[]?}?
  keys: {at: number, x: number?, opacity: number?, ease: string?}[]?
  end: {scale: number?}?

state clips: Clip[] = []
state titles: {at: number, len: number, text: string?, size: number?, italic: bool?, stroke: string?, strokeWidth: number?, y: number?}[] = []
state music: {src: sound, at: number, volume: number?, pan: number?, keys: {at: number, volume: number?}[]?}[] = []
state time = 0
state on = false
state heard = {peak: [0, 0], rms: [0, 0]}

action open
  let f = fs.pick("video/mp4,video/quicktime")?
  if f == none return
  let v = vid.open(f.data)?
  let half = v.duration / 2
  clips = [{src: v, from: 0, to: half, end: {scale: 1.1}}, {src: v, from: half, to: v.duration, dissolve: 0.5, wipe: "iris", grade: {gain: [1.1, 1, 0.9]}}, {src: v, from: 0, to: 2, track: 1, at: 1, scale: 0.3, x: 0.3, y: -0.3, crop: {round: 0.5}, keys: [{at: 0, opacity: 0}, {at: 0.5, opacity: 1}, {at: 1.5, x: 0.3, ease: "hold"}, {at: 2, x: -0.3, ease: "out"}]}]
  titles = [{at: 0, len: 2, text: "A film", size: 0.1, italic: true, stroke: "#000000", strokeWidth: 0.004, y: 0.35}]

action score
  let f = fs.pick("audio/*")?
  if f == none return
  let s = aud.open(f.data)?
  music = [{src: s, at: 0, volume: 0.8, pan: -0.2, keys: [{at: s.duration - 2, volume: 0.8}, {at: s.duration, volume: 0}]}]

action save
  let film = vid.export(clips, {layers: titles, sounds: music, width: 1280, height: 720})?
  fs.save(film, "film.mp4")?

column gap=8 padding=16
  reel clips=clips layers=titles sounds=music at=time playing=on levels=heard frame=({width: 1280, height: 720}) max-width=100%
  row gap=8 align-items=center
    button "Open" press=open
    button "Music" press=score
    button (on ? "Pause" : "Play") press={on = !on}
    button "Export" press=save disabled=pending(save)
    progress value=heard.peak[0] max=1
    progress value=heard.peak[1] max=1
  text `${time.toFixed(1)} s` color=dim
```

**A clip** is `{src: video, from, to}` in seconds of its video. If wanted:

| Field | Means |
|---|---|
| `speed` | Faster or slower (0.05 to 20); the sound keeps its pitch. |
| `pitch` | Semitones up or down; the length stays. |
| `volume`, `pan` | How loud; where between left (-1) and right (1). |
| `fadeIn`, `fadeOut` | Seconds. |
| `reverse: true` | Backwards, sound and all. |
| `hold: true` | The frame at `from`, still and silent, for the clip's length. |
| `filter` | A CSS filter, as text. |
| `grade` | A colour transform ([below](#grades)). |
| `blend` | `"multiply"`, `"screen"`, … over what is under it. |
| `mirror`, `flip` | Left to right · top to bottom. |
| `crop: {left, right, top, bottom, round}` | Parts of the picture cut away from each side (0 to 1); `round` rounds its corners (up to 0.5: a circle of a square). |
| `x`, `y` | Where it sits: parts of the frame, from the middle. |
| `scale`, `rotate`, `opacity` | Its size (1 fits it in the frame), degrees, 0 to 1. |
| `track`, `at` | Its row, and when it starts ([Tracks](#tracks)). |
| `dissolve`, `wipe` | How it comes in over the clip before it ([Tracks](#tracks)). |
| `bus` | A number 1 to 32: its sound is measured on its own as well ([Levels](#levels)). |

#### Moving: end and keys

A clip's own values are what it has as it starts. Two things move it:

- `end: {x, y, scale, rotate, opacity, crop, grade, volume, pan}` is where
  it finishes: it moves there over its length.
- `keys` are points between, in order:
  `keys: [{at: 1.5, opacity: 0, ease: "linear"}]`. `at` is seconds into the
  clip; each key has any of the same values.

`ease` on a key (or on `end`) is how it gets there: smooth if unsaid,
`"linear"`, `"in"`, `"out"`, or `"hold"` (it stays, then is there all at
once). Numbers, a crop's sides and a grade's lists are moved part by part.

#### Tracks

Clips follow one another. Two fields place a clip otherwise:

- `track: 1` puts a clip in a row of its own over track 0 (2 over 1, …).
  Each track is its own row of clips following one another.
- `at: 4` starts a clip at that second of the film, not where the one
  before it on its track ends. So a track may have gaps: what is under
  shows, or black.

**Coming in.** `dissolve` is the seconds a clip takes to come in over the
clip before it on its track: it starts that much sooner, the pictures fade
one into the other and the sounds cross. It is never longer than half of
either clip. With `wipe` it comes in that way instead of fading:

| `wipe` | |
|---|---|
| `"right"` `"left"` `"down"` `"up"` | An edge travels that way, uncovering it. |
| `"iris"` | A circle opens from the middle. |
| `"push"` | It arrives from the right and pushes the other out by the left. |
| `"slide"` | It arrives from the right over the other. |

A track's first clip has no dissolve unless it says `at`.

#### Layers over the clips

**A layer** goes over the clips: `{at, len}` in the film's seconds, with one
of:

- `image`: an `image`.
- `text`, with `size` (a part of the frame's height, 0.08 unsaid), `color`,
  `weight`, `font`, `italic`, `align` (`"left"` or `"right"`; centred
  unsaid), `spacing` (ems between letters), `stroke` with `strokeWidth` (an
  outline; a part of the frame's height), `background` (a box behind the
  words), `shadow: false` (for no soft shadow behind them).
- **neither**: an adjustment layer. Its `filter` and `grade` change what is
  under it, inside its `crop`, as far as its `opacity`. Given a
  `background` as well, it is a sheet of that colour the size of the frame.

A layer takes the same fades, `filter`, placing, `crop`, `blend`, `grade`,
`mirror`, `flip`, `end` and `keys` as a clip (`keys` count from its `at`).
With `track` it is drawn over that track's clips and under the next
track's; with none, over them all.

#### Grades

`grade` is colour, done on the graphics card. Each part may be left out;
they apply in this order, before `filter`:

| Part | Is |
|---|---|
| `lift`, `gamma`, `gain` | Each `[r, g, b]`. 0, 1 and 1 change nothing. |
| `matrix` | 20 numbers: a row each for red, green, blue and alpha out, across `[r, g, b, a, 1]` in. |
| `curve: {all, r, g, b}` | Each a list of outputs for evenly spaced inputs; `[0, 1]` changes nothing. |
| `lut: {size, data}` | `size`³ colours as r, g, b from 0 to 1, red changing fastest (a .cube file's numbers). |

It needs WebGL 2: where there is none, the picture is left as it was.

### aud

| Call | Gives |
|---|---|
| `aud.open(b)` | A sound of its own (music, a voice) as a `sound`: `{id, duration}`. |
| `aud.wave(s, width, height)` | It drawn white on clear, an `image`. |

**A sound** goes under the film as `{src: sound, at}`, `at` in the film's
seconds. If wanted: `from`, `to` (the stretch of it, in its own seconds),
`volume`, `pan`, `fadeIn`, `fadeOut`, `speed` (the pitch stays), `pitch`
(semitones; the length stays), `reverse`, `bus`, and `end` and `keys` for
its `volume` and `pan`, as a clip has.

### Levels

How loud a film is: `{peak, rms}`, each a list of numbers, `[left, right]`,
1 being as loud as a file holds.

- `vid.levels` is how loud the second of an export just mixed was
  (reactive).
- `reel … levels=heard` writes the same to state every frame it plays:
  `state heard = {peak: [0, 0], rms: [0, 0]}`.
- A clip or a sound that says `bus: 2` is measured on its own as well:
  bus n's left and right are at `[2n]` and `[2n + 1]` of each list.

### reel

```mote
reel clips=clips layers=over sounds=music at=time playing=on levels=heard frame=size
```

A canvas showing the film. `clips` is needed (`H049`); the rest are
optional.

- Set `at` and it shows that frame.
- While `playing` it keeps time with the sound and writes `at` back every
  frame, and sets `playing` false at the end. `at` and `playing` are written
  back only when they are state.
- `levels=heard` is written how loud it is, each frame it plays
  ([Levels](#levels)).
- `frame=size` (`{width, height}`) is the film's shape. Unsaid, it is the
  first clip's video's.
- Size it with styles (`max-width=100%`).
- With a `key=`, `focus=` or `blur=` handler it takes the keyboard when
  pressed ([events.md](events.md#the-events)).

Source: `runtime/page/video.mote` (part `VD`), `runtime/page/reel.mote`
(part `RL`), `batteries/mp4`, `batteries/aud`.

## Speech and microphones

(Sound and pictures between people, with their microphones and cameras:
[calls.md](calls.md).)

| Call | Gives |
|---|---|
| `speech.listen("en-US")` | What is said next, as text (the browser's own recogniser). The language may be left out. |
| `speech.say(text)` | Reads it out. |
| `mic.list()` | The microphones, each `{id, label}` (as `json`). It asks leave to use one, or their names are blank. |
| `mic.record({levels: true})` | A recording: the microphone, kept as bytes ([below](#recording-a-microphone)). |
| `mic.meter()` | A meter: how loud the microphone is, nothing kept ([below](#recording-a-microphone)). |

All three wait and can fail. They exist where the browser has them.

Source: `runtime/page/speech.mote`, part `SP`.

### Recording a microphone

```mote
// docs: whole
state rec: recording? = none
state clip: bytes? = none
state bars: number[] = []
state seconds = 0

action start
  rec = mic.record({levels: true})?

action hold
  if rec
    if rec.state == "paused"
      rec.resume()
    else
      rec.pause()

action finish
  if rec
    let got = rec.stop()?
    clip = got.bytes
    bars = got.peaks
    seconds = got.length
    rec = none

action drop
  rec?.cancel()
  rec = none

column gap=8 padding=16
  if rec
    row gap=8 align-items=center
      text `${Math.round(rec.time)} s`
      progress value=rec.level max=1
      button (rec.state == "paused" ? "Go on" : "Pause") press=hold
      button "Done" press=finish
      button "Drop" press=drop
  else
    button "Record" press=start
  if clip
    text `${Math.round(seconds)} s, ${bars.length} bars`
  text (failure(start) ?? "") color=danger
```

`mic.record({levels, mime, mic})` asks for the microphone and begins. It
waits and can fail (`mic: the microphone was not allowed`, `mic: there is no
such microphone`). What it gives is a **recording** (the type `recording`):

| | |
|---|---|
| `rec.state` | `"recording"`, `"paused"` or `"stopped"`. |
| `rec.time` | Seconds recorded so far, in twentieths; a pause is not counted. |
| `rec.level` | How loud it is now, 0 to 1 (measured as a [call's levels](calls.md) are). 0 unless `levels: true` was said, and while paused. |
| `rec.pause()` `rec.resume()` | Neither waits. |
| `rec.stop()` | Waits for `{bytes, type, length, peaks}`: the sound, what kind it is (the recorder's own word, which differs by browser: `"audio/webm;codecs=opus"` in Chrome, an Ogg in Firefox, `"audio/mp4"` in Safari), how many seconds, and how loud each twentieth of a second was (empty without `levels: true`). Asked again, it gives the same. It fails if the recording was let go. |
| `rec.cancel()` | Lets the microphone go and keeps nothing. |

All three of `state`, `time` and `level` are followed: a binding that reads
them is kept current, with no timer. The options: `levels: true` measures
(the meter and the `peaks`); `mime: "audio/mp4"` asks for a kind, and is
ignored where the browser cannot write it (`type` says what was written);
`mic: id` is one of `mic.list()`'s. The microphone stays open, and the
browser shows that it is, until `stop()` or `cancel()`: a page that drops a
recording must call one of them.

To keep a clip in a row, send it under a name that ends as its kind does:
the back end tells what a file is from the end of its name
([models.md](models.md#files)). `files.upload(got.bytes, "note.weba")` for
`audio/webm`, `.ogg` for an Ogg, `.m4a` for `audio/mp4`.

`mic.meter({mic})` listens and keeps nothing: for "is this microphone
working" before a call is joined. It waits and can fail as `mic.record`
does, and gives a **meter** (the type `meter`): `m.level`, followed, and
`m.stop()`, which lets the microphone go. It measures from the moment it is
made until it is stopped; nothing stops it for the page.

```mote
// docs: whole
state ear: meter? = none

action test
  ear = mic.meter()?

action done
  ear?.stop()
  ear = none

column gap=8 padding=16
  if ear
    progress value=ear.level max=1
    button "That works" press=done
  else
    button "Test the microphone" press=test
```

Source: `runtime/page/media.mote`, part `REC`. Recorded in
`tests/expect/real_media_page.txt`.

## audio and video

An `audio` or a `video` is HTML's own element (`src`, `controls`, `loop`,
`muted`, `autoplay`, `poster`, `preload="none"`). Six more attributes lead
it from the page, as a [`reel`](#reel)'s do, so that a player of the
page's own (a waveform, a scrubber) needs neither a timer nor the element:

```mote
// docs: whole
state on = false
state at = 0
state length = 0
state speed = 1

column gap=8 padding=16
  audio src="/file/Clip/7/sound/note.webm" preload="metadata" playing=on at=at rate=speed duration=length ended={at = 0}
  row gap=8 align-items=center
    button (on ? "Pause" : "Play") press={on = !on}
    input type="range" min=0 max=length step=0.01 value=at
    text `${Math.round(at)} / ${Math.round(length)} s`
    button "2x" press={speed = speed == 1 ? 2 : 1}
```

| Attribute | |
|---|---|
| `playing=on` | Whether it plays. Read and, when `on` is state, written back: the browser's own controls, the end of the sound, and a play the browser refused all set it. |
| `at=time` | Where it is, in seconds. While it plays it is written every frame; a value the element did not write itself is a seek. Written back only when it is state. |
| `rate=1.5` | How fast (1 is as it was made). |
| `volume=0.5` | How loud, 0 to 1. |
| `duration=length` | Only written: how long it is, in seconds, once the browser knows. It needs a state (`H049`). |
| `ended=done` | An action, or a `{…}` block, run at its end. |

- **A play nobody pressed for is refused** by the browser, until the page
  has been pressed or typed in ([Sound](#sound) has the rule): `playing`
  is then written back as false.
- **Played from its end, it starts over.**
- **`duration` is 0 for a sound whose length the browser cannot tell.**
  What `mic.record` writes in Chrome is one: keep the `length` that
  `stop()` gave beside the bytes.
- **Seeking needs a source that can be asked for a piece.** A model's
  file ([models.md](models.md#files)) and `b.url()` can; a file in
  `assets/` or `public/` is sent whole by `mote serve` and by the back
  end, and Chrome then seeks to 0.
- **It stops when it leaves the page** (an `if` that turns false, a route
  left).
- `video of=peer` is someone in a call ([calls.md](calls.md)) and takes
  none of these.

Source: `runtime/page/media.mote` (part `MEL`), `compiler/src/view.rs`
(`Gen::media`). Recorded in `tests/expect/real_media_page.txt`.

## Sound

A sound with no element: a notification's ping, a call that rings.

```mote
// docs: whole
state note = ""

action ping
  let r = sound.play("ping", {volume: 0.5})
  note = r.played ? "" : r.why

action ring
  sound.play("ring", {loop: true, id: "call"})

action answer
  sound.stop("call")

column gap=8 padding=16
  if !sound.ready
    text "Press anywhere to turn sound on" color=dim
  row gap=8
    button "Ping" press=ping
    button "Ring" press=ring
    button "Answer" press=answer
  text note
  text (sound.error ?? "") color=danger
```

| | |
|---|---|
| `sound.play(source, {volume, loop, id})` | Plays it, and says whether it does: `{played, why}`. It neither waits nor fails. |
| `sound.stop(id)` · `sound.stop()` | Stops the one played under that id; every one. |
| `sound.ready` | Whether the browser lets this page sound now. Followed. |
| `sound.error` | Why a sound could not be read or fetched (`none` again at the next `play`). Followed. |

- **The source** is bytes (a sound file's: what `mic.record` gave, what
  `net.bytes` fetched), an address (`asset("knock.mp3")`, a row's
  `file.url`), or the name of a tone made in the page: `"ping"`, `"pop"`,
  `"ring"` (two seconds: twice, then quiet; made to loop), `"error"`,
  `"join"`, `"leave"`. A word in quotes that is neither an address nor one
  of these is refused (`H064`).
- **`volume`** is 0 to 1. **`loop: true`** plays it until it is stopped.
  **`id`** names it for `sound.stop`, and a sound played under an id takes
  the place of the one playing under it: a ring asked for twice rings once.
- **The browser's rule.** A page makes no sound until it has been pressed
  or typed in. Before that `sound.play` gives `{played: false, why:
  "gesture"}` and `sound.ready` is false; the first press or key makes it
  true. A sound that was asked to `loop` before then starts by itself at
  that moment (a call that rings as soon as it can); any other is dropped.
  `why` is `"unsupported"` where the browser has no way to play at all,
  and `""` when it plays.
- **`played: true` means it was begun.** Bytes that are no sound, or an
  address with nothing at it, are found out a moment later: `sound.error`
  then says so.
- A sound is read once and kept: playing it again costs nothing.
- (`sound` is also the type of what `aud.open` gives: `fn f(s: sound)`.
  A state or a variable called `sound` hides the calls, as with any of
  the language's names.)

Source: `runtime/page/media.mote`, part `SND`. Recorded in
`tests/expect/real_media_page.txt`.

## Pitfalls

- **An `image` is not shown by itself.** The `image` tag takes an address,
  and an `image` value is pixels: `image p` is refused (`H069`). Encode it
  (`img.png(p)?`) and show the bytes with `.url()`, or use a sheet.
- **A decoded picture is upright.** `img.decode` turns it as its Exif
  orientation says; its width and height are the upright ones. Say
  `{orient: false}` for the pixels as stored.
- **A raw file gives its preview**, which may be smaller than the sensor's
  picture, and is whatever the camera developed.
- **A deep picture is twice the bytes**, and only some calls take it. Ask
  for `{deep: true}` only when the 16 bits are to be kept.
- **Do not keep many `image`s in state.** Twelve megapixels are 48 MB. Keep
  encoded bytes or sheets, and decode when needed.
- **A name that is read again is copied to the worker.** Write a chain, or
  let each `let` be used once, and the pixels are moved instead.
  `mote check --perf` lists what is copied.
- **Sheets and videos are held until dropped.** `paint.drop(s)` and
  `vid.close(v)` give them up.
- **`paint` positions are the picture's pixels; pointer positions are CSS
  pixels.** They differ when the canvas is scaled by styles.
- **A clip's `keys` are in the clip's seconds, a layer's `at` in the
  film's.** `from` and `to` are in the video's own.
- **A shape for clips lists what they say.** State typed `{src: video,
  from: number, to: number}[]` refuses a clip with `track`: declare a
  `shape Clip` with the optional fields the page uses (`track: number?`).
- **WebCodecs and the camera need a secure page** (https or localhost).
  `vid` fails where the browser has no WebCodecs.
- **`cam.shot()` needs a `camera` on the page that is on.**

## Where a new call goes

One `##` heading per namespace or element: `img`, `paint` (with
`canvas layers=`), `scan`, `camera`, `vid, aud and reel`, speech, `audio and video`, `Sound`. What a
clip, a layer or a sound may say goes in its table under `A film`. A new
picture format belongs under `Formats` (and a new encoder row in the `img`
table); a new `paint` call in its table; a new video call under `vid`. A new
media namespace gets its own `##` heading and a line in the
[map](README.md#namespaces).

## In the source

| What | Where |
|---|---|
| Signatures: `image`, `sheet`, `video`, `sound`, clips, layers | `compiler/src/types.rs`: `image`, `sheet`, `ply`, `video`, `clip`, `layer`, `track`, and `Checker::call` |
| `img` | `runtime/page/batteries.mote`: part `IM` (its messages; the browser's fallback, `byBrowser`); `batteries/img/`: `core.rs`, one file per format, `color.rs`, `info.rs` |
| `paint`, `canvas layers=` | `runtime/page/paint.mote`: `stroke` and `dab` (brushes), `drawOn` (`paint.draw`), `drawLayers` (masks, clips, filters) |
| `scan` | `runtime/page/speech.mote`: parts `SN`, `SR`; `batteries/scan/` |
| `camera`, `cam` | `runtime/page/camera.mote` |
| `vid`, `aud` | `runtime/page/video.mote` (its header lists its sections: clips and layers, colour, one frame of a film, the voices of a film, exporting); `batteries/mp4/`, `batteries/aud/` |
| Clips, keys, grades as types | `compiler/src/types.rs`: `clip`, `placing`, `moving`, `grade`, `layer`, `track`, `levels` |
| `reel` | `runtime/page/reel.mote`; `compiler/src/view.rs`: `Gen::reel` |
| `mic.record`, `mic.meter`, `audio` and `video` led from the page, `sound` | `runtime/page/media.mote`: parts `REC`, `MEL`, `SND`; `compiler/src/view.rs`: `Gen::media`; `compiler/src/types.rs`: `recording`, `meter`, `SOUNDS` |
| Recorded behaviour | `tests/pages/darkroom`, `tests/pages/studio`, `tests/paint2`, `tests/formats`, `tests/scan`, `tests/vid`, `tests/film`, `tests/pages/cut`, `tests/media_page` |
