npm.io
1.0.0 • Published 16h ago

m3u8stream

Licence
MIT
Version
1.0.0
Deps
2
Size
172 kB
Vulns
0
Weekly
0
Stars
231

node-m3u8stream

Reads segments from a m3u8 playlist or DASH MPD file into a consumable stream.

npm Node.js CI codecov

Usage

const fs = require('fs');
const m3u8stream = require('m3u8stream');

m3u8stream('http://somesite.com/link/to/the/playlist.m3u8').pipe(
  fs.createWriteStream('videofile.mp4'),
);

Tested streams

Compatibility is checked against these public streams. They are third-party resources and may change or disappear. Run npm run test:smoke to verify them; the smoke suite requires network access and is not part of the default test run.

Type Covers Stream Notes
HLS VOD (TS) Multi-variant master playlist, TS segments, muxed audio/video Mux Big Buck Bunny
HLS VOD (TS) Advanced master with EXT-X-MEDIA renditions Apple TS example Audio may be a separate rendition
HLS VOD (fMP4) EXT-X-MAP initialization, fragmented MP4 Apple fMP4 example Audio may be a separate rendition
HLS VOD (fMP4) Initialization and muxed audio/video Unified Streaming HLS
HLS encrypted EXT-X-KEY, AES-128 key fetch and decryption JW Player oceans AES AES-128 only; SAMPLE-AES is not supported
DASH VOD Duration-based SegmentTemplate, initialization segment DASH-IF Big Buck Bunny
DASH VOD Multiple representations and adaptation sets Envivio
DASH VOD Text-first and audio-first adaptation sets Shaka Angel One Default selection skips text and prefers video; use select for a specific quality
DASH VOD (fMP4) Initialization and fragmented MP4 segments Unified Streaming DASH
DASH on-demand single-file BaseURL-only single-file representation Sony test vector Valid MP4, but FFmpeg-based players may reject its sidx reference_type 1
DASH live Dynamic MPD, minimumUpdatePeriod, timeShiftBufferDepth, clock sync DASH-IF livesim Live content; availability varies
DASH live Newer livesim endpoint DASH-IF livesim2 Live content; availability varies
DASH live (timeline) SegmentTimeline, $Time$, repeated entries DASH-IF SegmentTimeline Live content; availability varies
DASH live (multi-period) Period transitions, live edge, segment deduplication DASH-IF multi-period Live content; availability varies

Some HLS masters expose separate audio and video renditions. The library selects one playlist or rendition and exposes alternate renditions through the media event; it does not mux multiple renditions.

API

m3u8stream(url, [options])

Creates a readable stream of binary media data. options can have the following

  • begin - Where to begin playing the video. Accepts an absolute unix timestamp or date, a relative time in the formats 1:23:45.123 and 1m2s, or "live" to begin at the live edge.
  • end - Where to stop downloading the video. Accepts an absolute unix timestamp or date and a relative time in the formats 1:23:45.123 and 1m2s. Cannot be used together with duration.
  • duration - How much of the video to download from begin. Accepts a duration in milliseconds or human-readable format like 1m30s. Cannot be used together with end.
  • liveBuffer - How much buffer in milliseconds to have for live streams. Default is 20000.
  • chunkReadahead - How many chunks to preload ahead. Default is 3.
  • highWaterMark - How much of the download to buffer into the stream. See node's docs for more.
  • requestOptions - Any options you want to pass to miniget, such as headers.
  • parser - Override parser detection with "m3u8" or "dash-mpd". Otherwise detection uses the playlist content, Content-Type, and URL extension.
  • select - For playlists containing multiple media options (HLS master playlists and DASH MPD manifests). If not given, the first video stream is picked when available, otherwise the first stream. Can be:
    • Quality keywords: 'highest' / 'best' or 'lowest' / 'worst' (bandwidth-based).
    • Resolution shorthand: e.g. '1080p', '720p', '1920x1080'.
    • Specific identifier: DASH representation id, playlist URL or filename, or 0-based index.
    • An HLS alternate rendition from EXT-X-MEDIA, by NAME, GROUP-ID, URI, or language.
    • A Variant or Media object returned by m3u8stream.inspect().
    • A callback receiving { variants, media } that returns one of the above. Return null or undefined to end without downloading anything, or throw to emit an error. The callback runs once, before segments are requested.

m3u8stream.inspect(url, [options])

Fetches and parses a master playlist without requesting any media segments. Returns a promise for the available stream choices:

const { variants, media } = await m3u8stream.inspect(url);

variants contains HLS variants or DASH representations. media contains HLS EXT-X-MEDIA alternate renditions; it is empty for DASH. Relative URLs are resolved against the final playlist URL.

Variant fields where available: id, url (HLS), index, bandwidth, resolution, width, height, codecs, frameRate, contentType.

Media fields where available: type, groupId, name, uri, language, default, autoselect, forced, channels, characteristics.

Options:

  • requestOptions - Any options you want to pass to miniget, such as headers.
  • parser - Override parser detection with "m3u8" or "dash-mpd".

The returned objects can be passed back through select:

const { variants } = await m3u8stream.inspect(url);
const stream = m3u8stream(url, { select: variants[0] });

Or choose during the first fetch:

const stream = m3u8stream(url, {
  select: ({ variants, media }) =>
    media.find((m) => m.language === 'en') ?? variants[0],
});

Returning null or undefined ends the stream without downloading media. Throwing emits an error.

Stream#end()

If called, stops the stream.

Event: progress

Emitted after each segment is downloaded.

  • Object - Progress details:
    • number - segmentNum
    • number - totalSegments
    • number - downloadedBytes
Event: segment

Emitted after each segment is downloaded, with metadata about it.

  • Object - Current segment with the following fields:
    • number - num
    • number - size
    • number - duration
    • string - url
    • boolean - [discontinuity]
    • number - [discontinuitySequence]
Event: variants

Emitted once when a master playlist is parsed. Receives an array of HLS variants or DASH representations. URLs are resolved against the final playlist URL. Not emitted for media playlists.

  • Object[] - Variant details:
    • number - index
    • string - [id]
    • string - [name]
    • string - [url]
    • number - [bandwidth]
    • string - [resolution]
    • number - [width]
    • number - [height]
    • string - [codecs]
    • number - [frameRate]
    • string - [contentType]
    • string - [audio]
    • string - [video]
    • string - [subtitles]
    • string - [closedCaptions]
Event: media

Emitted once when an HLS master playlist is parsed. Receives an array of alternate renditions; the array is empty when none are declared. Not emitted for DASH or media playlists.

  • Object[] - Rendition details:
    • string - type
    • string - groupId
    • string - name
    • string - [uri]
    • string - [language]
    • boolean - [default]
    • boolean - [autoselect]
    • boolean - [forced]
    • string - [channels]
    • string - [characteristics]
miniget events

All miniget events are forwarded and can be listened to from the returned stream.

m3u8stream.parseTimestamp(time)

Converts human friendly time to milliseconds. Supports the format
0000.000 for hours, minutes, seconds, and milliseconds respectively.
And 0ms, 0s, 0m, 0h, and together 1m1s.

  • time - A string (or number) giving the user-readable input data

Install

npm install m3u8stream

Tests

Tests are written with mocha

npm test

Keywords