Skip to content

Commit

Permalink
fix: deprecate render-media (#2180)
Browse files Browse the repository at this point in the history
* fix: deprecate render-media

* chore: update docs
  • Loading branch information
ThaUnknown authored Jun 23, 2022
1 parent 0ab745f commit 8b5ecea
Show file tree
Hide file tree
Showing 7 changed files with 38 additions and 154 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ client.add(magnetURI, function (torrent) {
console.log('Client is downloading:', torrent.infoHash)

torrent.files.forEach(function (file) {
// Display the file by appending it to the DOM. Supports video, audio, images, and
// more. Specify a container element (CSS selector or reference to DOM node).
file.appendTo('body')
document.body.append(file.name)
})
})
```
Expand Down
78 changes: 1 addition & 77 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ client.add(torrentId, function (torrent) {
})

// Display the file by adding it to the DOM. Supports video, audio, image, etc. files
file.appendTo('body')
file.streamTo(document.querySelector('video'))
})
```

Expand Down Expand Up @@ -644,80 +644,6 @@ file.getBuffer(function (err, buffer) {
console.log(buffer) // <Buffer 00 98 00 01 ...>
})
```

## `file.appendTo(rootElem, [opts], [function callback (err, elem) {}])` *(browser only)*

Show the file in a the browser by appending it to the DOM. This is a powerful function
that handles many file types like video (.mp4, .webm, .m4v, etc.), audio (.m4a, .mp3,
.wav, etc.), images (.jpg, .gif, .png, etc.), and other file formats (.pdf, .md, .txt,
etc.).

The file will be fetched from the network with highest priority and streamed into the page
(if it's video or audio). In some cases, video or audio files will not be streamable
because they're not in a format that the browser can stream so the file will be fully
downloaded before being played. For other non-streamable file types like images and PDFs,
the file will be downloaded then displayed.

`rootElem` is a container element (CSS selector or reference to DOM node) that the content
will be shown in. A new DOM node will be created for the content and appended to
`rootElem`.

If provided, `opts` can contain the following options:

- `autoplay`: Autoplay video/audio files (default: `false`)
- `muted`: Mute video/audio files (default: `false`)
- `controls`: Show video/audio player controls (default: `true`)
- `maxBlobLength`: Files above this size will skip the "blob" strategy and fail (default: `200 * 1000 * 1000` bytes)

Note: Modern browsers tend to block media that autoplays with audio (here's the
[Chrome policy](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes)
for instance) so if you set `autoplay` to `true`, it's a good idea to also set
`muted` to `true`.

If provided, `callback` will be called once the file is visible to the user.
`callback` is called with an `Error` (or `null`) and the new DOM node that is
displaying the content.

```js
file.appendTo('#containerElement', function (err, elem) {
if (err) throw err // file failed to download or display in the DOM
console.log('New DOM node with the content', elem)
})
```

Streaming support depends on support for `MediaSource` API in the browser. All
modern browsers have `MediaSource` support.

For video and audio, webtorrent tries multiple methods of playing the file:

- [`videostream`][videostream] -- best option, supports streaming **with seeking**,
but only works with MP4-based files for now (uses `MediaSource` API)
- [`mediasource`][mediasource] -- supports more formats, supports streaming
**without seeking** (uses `MediaSource` API)
- Blob URL -- supports the most formats of all (anything the `<video>` tag supports
from an http url), **with seeking**, but **does not support streaming** (entire
file must be downloaded first)

[videostream]: https://www.npmjs.com/package/videostream
[mediasource]: https://www.npmjs.com/package/mediasource

The Blob URL strategy will not be attempted if the file is over
`opts.maxBlobLength` (200 MB by default) since it requires the entire file to be
downloaded before playback can start which gives the appearance of the `<video>`
tag being stalled. If you increase the size, be sure to indicate loading progress
to the user in the UI somehow.

For other media formats, like images, the file is just added to the DOM.

For text-based formats, like html files, pdfs, etc., the file is added to the DOM
via a sandboxed `<iframe>` tag.

## `file.renderTo(elem, [opts], [function callback (err, elem) {}])` *(browser only)*

Like `file.appendTo` but renders directly into given element (or CSS selector). For
example, to render a video, provide a `<video>` element like
`file.renderTo('video#player')`.

## `file.getBlob(function callback (err, blob) {})` *(browser only)*

Get a W3C `Blob` object which contains the file data.
Expand Down Expand Up @@ -751,8 +677,6 @@ file.getBlobURL(function (err, url) {

Requires `client.loadWorker` to be ran beforehand. Sets the element source to the file's streaming URL. Supports streaming, seeking and all browser codecs and containers.

This method transfers data directly instead of building it into blobs, which means it uses less CPU and RAM than `renderTo`.

Support table:
|Containers|Chromium|Mobile Chromium|Edge Chromium|Firefox|
|-|:-:|:-:|:-:|:-:|
Expand Down
5 changes: 4 additions & 1 deletion docs/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,15 @@ const client = new WebTorrent()

const torrentId = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent'

navigator.serviceWorker.register('sw.min.js')
// see tutorials.md for a full example of streaming media using service workers

client.add(torrentId, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(function (file) {
return file.name.endsWith('.mp4')
})
file.appendTo('body') // append the file to the DOM
file.streamTo(document.querySelector('video')) // append the file to the DOM
})
```

Expand Down
9 changes: 6 additions & 3 deletions docs/get-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ const client = new WebTorrent()
// Sintel, a free, Creative Commons movie
const torrentId = 'magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent'

navigator.serviceWorker.register('sw.min.js')
// see tutorials.md for a full example of streaming media using service workers

client.add(torrentId, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(function (file) {
Expand All @@ -51,7 +54,7 @@ client.add(torrentId, function (torrent) {

// Display the file by adding it to the DOM.
// Supports video, audio, image files, and more!
file.appendTo('body')
file.streamTo(document.querySelector('video'))
})
```

Expand Down Expand Up @@ -183,7 +186,7 @@ downloaded.
// Render all files into to the page
torrent.files.forEach(function (file) {
file.appendTo('.log')
document.querySelector('.log').append(file.name)
log('(Blob URLs only work if the file is loaded from a server. "http//localhost" works. "file://" does not.)')
file.getBlobURL(function (err, url) {
if (err) return log(err.message)
Expand Down Expand Up @@ -328,7 +331,7 @@ or [Instant.io](https://instant.io) to seed torrents to the WebTorrent network.
})
// Stream the file in the browser
file.appendTo('#output')
file.streamTo(document.querySelector('#output'))
// Trigger statistics refresh
torrent.on('done', onDone)
Expand Down
75 changes: 24 additions & 51 deletions docs/tutorials.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,6 @@

WebTorrent can be used to stream videos. WebTorrent can render the incoming video to an HTML `<video>` element. Below are some examples for various video players.

### [Default HTML5 Video Player](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) [legacy]

Code example:

```html
<!DOCTYPE html>
<html>
<head>
<title>Web Torrent Tutorial</title>
<meta charset="UTF-8" />
<script src="//cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>
</head>
<body>
<video id="video-container" controls="true"></video>
<script>
const client = new WebTorrent();
const torrentId =
"magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent";
client.add(torrentId, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(function (file) {
return file.name.endsWith(".mp4");
});
// Render to a <video> element by providing an ID. Alternatively, one can also provide a DOM element.
file.renderTo("#video-container", {}, () => {
console.log("Ready to play!");
});
});
</script>
</body>
</html>

```

### [Service Worker Renderer](https://github.com/webtorrent/webtorrent/blob/master/docs/api.md#clientloadworkercontroller-function-callback-controller---browser-only)

Code example:
Expand Down Expand Up @@ -118,21 +82,30 @@ Code example:
<body>
<video id="video-container" class="video-js" data-setup="{}" controls="true"></video>
<script>
const client = new WebTorrent();
const torrentId =
"magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent";

client.add(torrentId, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(function (file) {
return file.name.endsWith(".mp4");
});

// Render to a <video> element by providing an ID. Alternatively, one can also provide a DOM element.
file.renderTo("video#video-container_html5_api", {}, () => {
console.log("Ready to play!");
});
});
const client = new WebTorrent()
const torrentId = "magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent"
const player = document.querySelector("video#video-container_html5_api")

function download () {
client.add(torrentId, torrent => {
// Torrents can contain many files. Let's use the .mp4 file
const file = torrent.files.find(file => file.name.endsWith('.mp4'))

// Stream to a <video> element by providing an the DOM element
file.streamTo(player, () => {
console.log('Ready to play!')
})
})
}
navigator.serviceWorker.register('sw.min.js', { scope }).then(reg => {
const worker = reg.active || reg.waiting || reg.installing
function checkState (worker) {
return worker.state === 'activated' && client.loadWorker(worker, download)
}
if (!checkState(worker)) {
worker.addEventListener('statechange', ({ target }) => checkState(target))
}
})
</script>
</body>
</html>
Expand Down
20 changes: 2 additions & 18 deletions lib/file.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
const EventEmitter = require('events')
const { PassThrough } = require('stream')
const path = require('path')
const render = require('render-media')
const streamToBlob = require('stream-to-blob')
const streamToBlobURL = require('stream-to-blob-url')
const streamToBuffer = require('stream-with-known-length-to-buffer')
Expand Down Expand Up @@ -123,7 +121,7 @@ class File extends EventEmitter {

getBlob (cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
streamToBlob(this.createReadStream(), this._getMimeType())
streamToBlob(this.createReadStream(), mime.getType(this.name))
.then(
blob => cb(null, blob),
err => cb(err)
Expand All @@ -132,23 +130,13 @@ class File extends EventEmitter {

getBlobURL (cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
streamToBlobURL(this.createReadStream(), this._getMimeType())
streamToBlobURL(this.createReadStream(), mime.getType(this.name))
.then(
blobUrl => cb(null, blobUrl),
err => cb(err)
)
}

appendTo (elem, opts, cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
render.append(this, elem, opts, cb)
}

renderTo (elem, opts, cb) {
if (typeof window === 'undefined') throw new Error('browser-only method')
render.render(this, elem, opts, cb)
}

_serve (req) {
const res = {
status: 200,
Expand Down Expand Up @@ -224,10 +212,6 @@ class File extends EventEmitter {
return this._startPiece <= piece && this._endPiece >= piece
}

_getMimeType () {
return render.mime[path.extname(this.name).toLowerCase()]
}

_destroy () {
this._destroyed = true
this._torrent = null
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@
"random-iterate": "^1.0.1",
"randombytes": "^2.1.0",
"range-parser": "^1.2.1",
"render-media": "^4.1.0",
"run-parallel": "^1.2.0",
"run-parallel-limit": "^1.1.0",
"simple-concat": "^1.0.1",
Expand Down

0 comments on commit 8b5ecea

Please sign in to comment.