Azure Media Service upload file directly from webcam - javascript

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.

Related

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.

Load large video file in HTML

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

Play local video file in electron html5 video player using node.js fs.readStream()

I am developing a video player application, which plays video videos (.mp4) from the local filesystem using node.js and electron (therefore I am using chromium's html5 video player).
Playing video videos larger than 2GB seems to be a problem with my current approach.
I used to read the local video files using fs.readFileSync and pass that Blob to the video player, like in this code:
this.videoNode = document.querySelector('video');
const file: Buffer = fs.readFileSync(video.previewFilePath);
this.fileURL = URL.createObjectURL(new Blob([file]));
this.videoNode.src = this.fileURL;
This does work for video files smaller that 2GB. Files larger than 2GB trigger the following error:
ERROR RangeError [ERR_FS_FILE_TOO_LARGE]: File size (2164262704) is greater than possible Buffer: 2147483647 bytes
at tryCreateBuffer (fs.js:328)
at Object.readFileSync (fs.js:364)
at Object.fs.readFileSync (electron/js2c/asar.js:597)
I believe the solution is to pass a ReadStream to the html5 video player using fs.readStream(). Unfortunately I cannot find any documentation on how to pass this stream to the video player.
As the topic says you are using electron and from the above comments it is clear that you are avoiding a server. It seems that if you are just creating an offline video player then you are just making things complex. Why are you creating a buffer and then creating a new url? You can achieve this by simply getting the video path and using it as src attribute of video object.
Your code should look like this-
var path="path/to/video.mp4"; //you can get it by simple input tag with type=file or using electron dialogs
this.videoNode = document.querySelector('video');//it should be a video element in your html
this.videoNode.src=path;
this.videoNode.oncanplay=()=>{
//do something...
}
This will handle complete file and you dont need to disable webPreference given that videoNode is the video element in html file.
You can take a look at this open source media player project made using electron-
https://github.com/HemantKumar01/ElectronMediaPlayer
Disclaimer: i am the owner of the above project and everyone is invited to contribute to it

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.

flash voice recording, then upload to server

I'm looking for a flash widget that allows users to record their audio and then send it to the server.
There are a few similar questions:
Record Audio and Upload as Wav or MP3 to server
They advocate using Red5 or flash media server.
Shouldn't it be possible to record locally on the user's client using the codecs that the user already has and then upload the resulting file to the server, rather than say, process the and record the stream on the server itself.
Thanks.
According to the the Capturing Sound Input Article if you are running Flash Player 10.1 you can save the microphone data to a ByteArray. The Capturing microphone sound data section gives the following example on how to do it:
var mic:Microphone = Microphone.getMicrophone();
mic.setSilenceLevel(0, DELAY_LENGTH);
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, micSampleDataHandler);
function micSampleDataHandler(event:SampleDataEvent):void {
while(event.data.bytesAvailable) {
var sample:Number = event.data.readFloat();
soundBytes.writeFloat(sample);
}
}
Once you have the ByteArray you can of course do whatever you want with it.
Once you have the ByteArray you can pass it in with NetStream.appendBytes()

Categories