byte-range.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Reads a `Range` request header against a file of a known size.
  3. *
  4. * A video player does not download a clip and then play it. It asks for the
  5. * first two bytes to learn whether the server can seek, then for the pieces
  6. * it needs, and iOS refuses to play at all from a server that answers a
  7. * range request with the whole file.
  8. *
  9. * Returns the inclusive byte span to send, `'unsatisfiable'` when the span
  10. * starts past the end of the file, and null when there is no range to honour:
  11. * no header, a unit other than bytes, a malformed value, or several ranges at
  12. * once, which nothing here asks for and which is answered with the whole file.
  13. */
  14. export function parseByteRange(
  15. header: string | null,
  16. size: number
  17. ): { start: number; end: number } | 'unsatisfiable' | null {
  18. if (!header) return null
  19. const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim())
  20. if (!match) return null
  21. const [, from, to] = match
  22. if (from === '' && to === '') return null
  23. // `bytes=-500` is the last 500 bytes, not a span starting at zero.
  24. if (from === '') {
  25. const length = Number(to)
  26. if (length === 0 || size === 0) return 'unsatisfiable'
  27. return { start: Math.max(size - length, 0), end: size - 1 }
  28. }
  29. const start = Number(from)
  30. if (start >= size) return 'unsatisfiable'
  31. const end = to === '' ? size - 1 : Math.min(Number(to), size - 1)
  32. if (end < start) return null
  33. return { start, end }
  34. }