Load large video file in HTML - javascript

Here is my problem : I want to play a large video file (3.6Gb) stored in a S3 bucket, but it seems the file is too big and the page crash after 30sec of loading.
This is my code to play the video :
var video = document.getElementById("video");
const mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen, { once: true });
function sourceOpen() {
URL.revokeObjectURL(video.src);
const sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.f40028"');
fetch('URL_TO_VIDEO_IN_S3')
.then(response => response.arrayBuffer())
.then(data => {
// Append the data into the new sourceBuffer.
sourceBuffer.appendBuffer(data);
})
.catch(error => {
});
}
I saw that blob URL could be a solution but it didn't work well with my URL.

Take my answer with a grain of salt as I am no expert. However, I am working on something very similar at the moment.
I suspect your issue is that you're attempting to load the entire resource (video file) into the browser at once. An object URL for a file size that exceeds a gigabyte is extremely large.
What you need to do is use the readable stream from the body of your fetch request to process the video file chunk-by-chunk. So as long as you aren't confined to working in the safari browser, you should be to use both the Readable and Writeable Stream classes natively in the browser.
These two classes allow you to form what's called a pipe. In this case, you are "piping" data from the readable stream in your fetch request to a writable stream that you create which is then used as the underlying source of data for your media source extension and it's respective source buffers.
A stream pipe is very special in that it exhibits what's called backpressure. You should definitely look this term up, and read about what it means. In this case, it means the browser will not request more data once it has enough to meet its needs for video playback, the exact amount it can hold at once is specified by you the programmer through something called a "highwater mark" (you should also read about this).
This allows you to control when and how much data the browser is requesting from your (on going) fetch request.
NOTE: When you use .then(response => response.arrayBuffer()) you are telling the browser to wait for the entire resource to come back and then turn the response into an array buffer.

OPTION 1
Use CloudFront to create RTMP distribution to these resources.
It will distribute your video in streaming way.
Create an RTMP distribution to speed up distribution of your streaming media files using Adobe Flash Media Server's RTMP protocol.
Please note that HTML5 does not support RTMP format by default (without flash).
Check here for options
JWPlayer supports RTMP playback using flash. SO Question
---
OPTION 2
Use Elastic Transcoder to create HLS video (.m3u8 format). Again same JWPlayer can handle it in ease.
Also it's mostly supported in native HTML5. Check compatibility with H.264

Related

Receive audio download in chunks and play smoothly with web audio API

I could not really find any way to smoothly get and play audio chunks with Web Audio API. Currently I am simply fetching an audio file from my CDN, but I have tested it on slower internet connections, and as expected it results in a long wait before the audio starts playing.
My code currently is the following:
let context = new AudioContext()
currentsrc = context.createBufferSource()
let audioBuffer = await fetch(songid)
.then(res => res.arrayBuffer())
.then(ArrayBuffer => context.decodeAudioData(ArrayBuffer))
currentsrc.buffer = audioBuffer
currentsrc.connect(context.destination)
currentsrc.start()
This way the script is waiting till the entire audio is downloaded which results in a break that can be long when my connection is not great. Is there any good way to download my audio in chunks and flawlessly play it with Web Audio API.
(I have seen this question and response already, I'm wondering if there's a better/cleaner way of doing this without having to separately schedule the audio chunks)
I later figured out that probably the best way to achieve this is to use the getReader() function of the response body, this way I can read chunks, I also gave more information as to how I finally solved this question here.

Azure Media Service upload file directly from webcam

I have looked at the documentation for Azure Media Services, but I could not find any docs or samples that talk about uploading a video from a browser using the webcam.
I am already using MediaRecorder api in the browser to record the webcam video and then upload... but I was wondering if there was a better alternative than 'MediaRecorder'?
Since Microsoft already provides a media player to play the videos, I was wondering if in a similar way, Microsoft maybe had a js library to do the video recording on the frontend and upload accordingly?
Edit: My intent is not to live stream from the browser, but to upload the file to AMS and play in the Azure media player at a later time.
EDIT:
Originally answered this thinking you meant live... But I see now you meant on-demand recorded files. I will leave the live section below.
On-Demand:
For the on-demand scenario, you should also be able to use the Media Recorder API to save the asset into local storage.
There are some good examples of doing that recording to storage out there, but the main API doc is here and has some guidance on how to save the output. The output could be WebM or MP4 depending on browser capabilities.
https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API
Once you have a local file, the steps to get that into AMS would be:
Create an Asset
Get the container name from the new Asset (we generate one for you, or you can pass the name of the container into the Asset create call)
Use the Azure Blob storage SDK to get a writeable SAS locator to upload the file into the container.
Useful example code:
Example of creating an Asset with a specific Blob container name
Previous Stack thread on uploading from browser to blob storage container
Azure Storage Javascript client samples
// If one file has been selected in the HTML file input element
var file = document.getElementById('fileinput').files[0];
var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512;
blobService.singleBlobPutThresholdInBytes = customBlockSize;
var finishedOrError = false;
var speedSummary = blobService.createBlockBlobFromBrowserFile('mycontainer', file.name, file, {blockSize : customBlockSize}, function(error, result, response) {
finishedOrError = true;
if (error) {
// Upload blob failed
} else {
// Upload successfully
}
});
refreshProgress();
Disclaimer from me...
Have not tried the above scenario at all myself. Just finding the right resources for you to check. Hope that helps!
But, the below scenario I have done for live, and it does work..
Live Scenario:
It's tricky, because Media Services only supports RTMP ingest.
Media Recorder API just records to "slices" of webM or MP4 content in the browser. You have to then push those chunks of media someplace that is capable of sending that content into AMS as RTMP/S. Otherwise, no go.
There is a good example project from Mux up here called Wocket that demonstrates how you could go about building a solution that ingests content from the MediaRecorder API and send it to any RTMP server, but it has to go over a WebSocket connection to a middle tier Docker container that is running FFMPEG. The FFMPEG process receives the webM or MP4 chunks from the Media Recorder and forwards that onto Media Services.
https://github.com/MuxLabs/wocket
I built a demo recently that uses this in Azure, and it surprisingly works... but not really production ready solution - has lots of issues on iOS for example. Also, I had to move the Canvas drawing off the requestAnimationFrame timer and use worker-timers (node.js npm packager) to move the canvas drawing to a web worker. That way I could at least switch focus from different browser tabs or hide the browser without it stopping the webcam. Normally timers like setInterval or setTimeout in the browser will sleep or be throttled in modern browsers to save power and CPU.
Let me know if you want any more details after looking at the Wocket project.

Share local blob data between two client-only JS applications deployed on different domains

I have two client-only (backend is static file server) applications written in JS. One is a recorder that records videos (e.g. the webcam) via the MediaRecorder API (this results in a Blob object). The other application is a video editor (don't mind how that one is implemented).
The two applications are deployed on different domains (e.g. foo-recorder.com and foo-editor.com). My goal is to make editing your recordings as easy as possible. I would like the recorder to have a button "edit recording in editor" that opens the editor with the recording already loaded.
A naive solution would be to URL.createObjectUrl(blob) in the recorder, URL-encode that URL and pass it as query parameter to the editor. E.g. https://foo-editor.com?video=blob://.... However, as far as I can tell, browsers do not allow sites to access blob URLs from another domain. (That's probably for good privacy reasons.)
I also thought about:
Storing the blob as a file on the user's device and pass the path to the other site. But we can't just willy nilly write files with JS.
Storing the blob in local storage: local storage usually is limited to a few MB and can't be access cross-domain either.
Passing the whole video base64 encoded as query parameter: that's ridiculous. No.
So I can't come up with a working solution. And I wouldn't be surprised if it doesn't work at all because it's probably very tricky privacy and security wise.
Does anyone have an idea how I could pass this blob from one app to the other? Obviously, the blob should not be uploaded.
Thanks to Musa's hint, I found a solution: postMessage allows me to pass the Blob to the editor, even if it's deployed on another domain. The recorder has to open a new browsing contect with the editor loaded. This can be:
windows.open to open a popup window
An <iframe> with the editor as src. Acquire the context via iframeDomNode.contentWindow.
It's now possible to use postMessage to send a message to that context:
const iframe = document.getElementById('editor-iframe');
iframe.contentWindow.postMessage(videoBlob, "*");
// ^ TODO: change "*" to the specific target origin in production code!!!
On the editor side, I can receive that message via:
window.addEventListener("message", event => {
// TODO: in real code, you should check `event.origin` here!
const v = document.getElementById("a-video-element");
v.src = URL.createObjectURL(event.data);
}, false);
Note: if you generate the blob URL on the recorder side, pass that to the editor, the editor still cannot access that. So you need to pass the blob directly.
Also note that sending a Blob via postMessage is not expensive and does not copy the Blob data.

Receive chunks of video and play them in browser

Base idea: I am creating an app. In which user chooses local file(mp4) in input field(type="file") and then streams the video to other user.
I am thinking to manipulate the file in javascript. And send it chunk by chunk to another user via(datachannels webRTC) then just play it on the other side chunk by chunk.
I understand that i can "assemble" the chunks using - MediaSource API
Questions: How can i split the video in chunks using javascript? I have been googling for a while i can't seem to find a library( maybe i am googling wrong keywords? ).
Thanks!
Use blob#slice to split the video
// simulate a file
blob = new Blob(['ab'])
chunk1 = blob.slice(0, 1)
chunk2 = blob.slice(1, 2)
console.log(blob.size)
console.log(chunk1.size)
console.log(chunk2.size)
Another thing i might think you are interested in is File streaming...
To get a ReadableStream from a blob you could use the hackish why of doing
stream = new Response(blob).body
reader = stream.getReader()
reader.read().then(chunk => spread(chunk))
Another cool library otherwise you can use to stream the blob Is by using Screw-FileReader
What wouldn't be more awesome then using WebTorrent to share the video got everything you need... uses WebRTC...

Dynamically create video (stream) with createObjectURL

I wonder if it is possible to create a html5 video on the fly. Some of you may noticed the new webrtc and its behavior with the video tag.
navigator.webkitGetUserMedia('video', gotStream, noStream);
function gotStream(stream) {
video.src = webkitURL.createObjectURL(stream);
}
what exactly is that "stream" in gotStream(stream) what is that "interface" looks like so i can generate one of my own? May it be by computing things or by just receiving data from server to display the video. Secound how do i get the data out of this "stream"? So i can read it from one users webcam to send it to my server and let it pass through the receiving user. Binary data transmission is no topic of my question, i already have this working.
I just need the data from the "stream" from one user and reconstruct that "stream" on the target user who wanna see user ones webcam.
Any further information on "where to get these infos by my self" (API Docu sort of) would be also very helpful, cuz i cant find any.
I am aware of the PeerConnection stuff, so no need to mention it here. Cuz beside that webcam stuff i would love to pipe dynamically generated videos from my server to the client or make some sort of video transmitting over dynamic changeable bandwidth with ffmpeg etc. but for this i need to pipe that data to that video element
You may want to look at Whammy: http://antimatter15.com/wp/2012/08/whammy-a-real-time-javascript-webm-encoder/.
For now, you can periodically copy a video element screen to a canvas, then save that canvas to build a video. Whammy ties together webp images generated from a canvas into a webm file, taking advantage of the similarities of the webp (image) and webm (video) format.
You could generate other images and stitch them together in the same manner. Note that this does not support audio.

Categories