Load m3u8 video file as Blob with different orign - javascript

I'm attempting to stream video using a Blob URL created from an m3u8 URL.
The m3u8 file contains only relative paths.
E.g.
file1.ts
file2.ts
...
The m3u8 file is stored on a separate host (e.g. the URL is fileserver.com/path/thevideo.m3u8) than the website loading the video (e.g. the URL is website.com).
Therefore, after converting the m3u8 URL to a Blob, the video player subsequently looks for:
website.com/file1.ts
website.com/file2.ts
Whereas, the actual URLs are:
fileserver.com/path/file1.ts
fileserver.com/path/file2.ts
Question is, is there any way to get the video player (I'm using VideoJS) to use the correct URL prefix?
The code I used for Blob URL generation is here: set video objects source file to a blob url
I can confirm that it works if the m3u8 file contains the full *.ts URLs instead of the relative paths, but I want to see if this is possible using only the relative path as that would be more convenient.

You can attach a custom handler for requests made by videojs/http-streaming engine.
player.tech().vhs.xhr.beforeRequest = function(options) {
options.uri = options.uri.replace('example.com', 'foo.com');
return options;
};
Note: You should make a check with safari hls playback if you're using overrideNative option.

Related

How to preview a video upload in react-player?

I have an input of type file which allows my users to upload video files which will be of type File. In my application there also exists the react-player component which takes a URL prop that can be of type array or MediaStream according to its documentation. having done some research I found the following way to convert the File to a URL to be compatible with the react-player however it is depreciated so I do not wish to use it.
URL.createObjectURL(file)
This returns a URL for a blob or file object. I see that this has been replaced with passing a MediaStream to video.srcObject() but I am unaware how to convert a File to type MediaStream and srcObject() seems like a hacky way to access react-player which exposes its URL for the same purpose and also takes a MediaStream. To summarise how do I get a video uploaded with a file type input to be previewed in a react-player component?
Turns out URL.createObjectURL() is only depreciated for MediaStreams and you can therefore go ahead and use it for Blobs and File types.

Javascript function force downloads an MP3 file from URL, once downloaded however MP3 file wont play on my computer only on VLC Player? Why?

I have a Javascript function that basically force downloads a file once provided the URL and name of the file. This function works absolutely fine as intended I call it from a HTML tag/hyperlink. But once the MP3 file from my function downloads it wont play on my computer. I have designed this function for a user to be able to download different MP3 and WAV files upon clicking on the associated link for that file. I can only play the downloaded MP3 file on the media player VLC it won't play on my laptop. Is there something I am doing to the MP3 file in the download process with my function or why will it not play once downloaded?
I have looked into MP3 file variations and encoding but Im not sure what to look for really or what I am doing wrong. When I download MP3 files from other sites they are working fine and play straight away.
Function:
<script>// <![CDATA[
function downloadFile(data, fileName, type="text/plain") {
// Create an invisible A element
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
// Set the HREF to a Blob representation of the data to be downloaded
a.href = window.URL.createObjectURL(
new Blob([data], { type })
);
// Use download attribute to set set desired file name
a.setAttribute("download", fileName);
// Trigger the download by simulating click
a.click();
// Cleanup
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
// ]]></script>
Function Call:
My Download
If you look in the downloaded file, you'll find it contains the text https://cdn.shopify.com/s/files/1/0037/4951/1217/files/ascence-places-like-that-ncs-release.mp3?360 because that's the value you're passing for data and using when creating the blob. Nothing about that code creating a blob downloads the content (and the SOP prevents your code from downloading the content, unless of course the other site overrides it with CORS).
I don't think you can force the link to open the Save dialog. Normally that's triggered by the response to the link from the server (via the Content-Disposition header), which of course you can't control in your scenario. Using the download attribute won't do it, it has no effect cross-origin (other than when the link is a data: or blob: URL, see MDN's description).
You can show them the link so they can right-click and choose "Save target as...", but I know that's going to be a disappointing answer for you.

How to extract all the current video files and its address in the web page with js?

var imgs=document.images.length;
It can extract all the images on the web page.
How extract all the flv files whose suffix is flv such as sample.flv in the web page with js?Not all the flv files on my local directory but web page.
The plugin Video DownloadHelper in firefox can get the current mp4 file.
Why my js code can't do the same task?
var Links = document.querySelectorAll('a[href$=".mp4"]');
console.log(Links);
How to extract the current video files with js such as the plugin Video DownloadHelper in firefox?
Yahoo Movies use blob stream to transfer video data. There are no direct mp4/flv links anywhere, nor can you get such links directly. The src of the <video> tag refers to a blob stream link:
<video class="yvp-html5-video" preload="" id="2413371376" src="blob:https://www.yahoo.com/1dfafd99-a1ff-4cc8-bcff-255e69db9977"></video>
When you hit to download MP4 from Video DownloadHelper, the plugin actually reads the blob stream and writes it to disk in an MP4 file. It doesn’t download a MP4 file. If you try to Copy URL, you’ll get something like this to your clipboard:
https://roarack01.vpg.cdn.yimg.com/yahoomovies/61fb473f-04a2-381e-b2ae-9496dfba5e66_VYtMtix1DscECbXMT9tHT7yf2P9BZF-mRCMjBejFgALFHl7NSm1ZXPOMICAOr949v2xUgEASYLw-_1_0_vtt.m3u8?a=yahoomovies&ib=sapi&m=application%2fvnd.apple.mpegurl&mr=0&ns=c+i+ci+cii&vid=61fb473f-04a2-381e-b2ae-9496dfba5e66&x=1479599999&s=370695a7063b6aae06fb7f537c85773a
You can record a blob stream, but it’s not an easy task.
For more details on video blob stream, check these links:
What is blob in the <video src=blob:url>?
Export HTML5 blob video to MP4
W3C Media Source Extensions
A URL for Blob and File reference
If I'm understanding correctly you want to look for all the links which have an associated .flv.
If you want this, you can use querySelectorAll and select all the links ending in .flv using the css selector $=.
var flvLinks = document.querySelectorAll('a[href$=".flv"]');
to get all flv files of a directory, please try the following code -
var files = fs.readdirSync("YOUR_DIRECTORY");
var path = require('path');
for(var i in files) {
if(path.extname(files[i]) === ".flv") {
//do your desired task here
}
}
Hope it helps..:)
You can inspect all video requests on Chrome -> Networks tab in Media sub tab.

Youtube Blob urls don't work in browsers but in src

I know that there are no blob urls only objects.
I made my own blob object for a video buffer and then I used it in a src of video tag which is something like blob://website.com/blablobbla . I opened this url in the browser it worked
when I opened the url of youtube video src (blob url) into a new tab it did't work but mine video src (blob url) worked
I want to know how can I do the same with my blob urls so that they only work in the src of the html video tag and give error or don't work in the external tab/window of the browsers.I just want to know the technology behind this and blob objects and their url properties.
The question seems somewhat vague to me, so here is what I interpret (also from the code in the fiddle-images in your question):
you receive a Blob (image's binary data) through a XMLHttpRequest() GET-request (responseType = 'blob')
you create a Blob URL with URL.createObjectURL() in the URL Store for XMLHttpRequest() response-object (the Blob holding the binary data)
you set the resulting Blob URL-string as src for a image (and append the image to the document, thereby showing the image you just downloaded)
You "don't want it to work in new tab" ("it" being the Blob URL-string I assume).
In your comments you say:
In fiddle I inspected the image and copied the src and then pasted it in new tab and it worked and showed the image I don't want the image to be shown directly with the blob url.
If you go to youtube and open the src of video in new tab : It will not work,, I want this to happen
It appears to me that you do not want the user to be able to view/download the blob when they copy the Blob URL-string (by examining the live source or simply right-click-on-image>>Copy Imagelocation) and paste it into a new tab/window (for which you give youtube as an example).
But you are also talking about video's.
TL;DR: It seems your question/bounty might be mixing up 2 different types of URL returned by window.URL.createObjectURL();:
Blob URL referencing (objects that represent) 'raw local data' (like (Local-)File, Blob, etc.)
For these you want to automatically (or programmatically) revoke the Blob URL from the browser's URL Store (which you could consider a simplified local webserver inside the browser, only available to that browser).
var myBlobURL=window.URL.createObjectURL(object, flag_oneTimeOnly);
returns a re-usable Blob URL which can be revoked with: window.URL.revokeObjectURL(myBlobURL) (adds the Blob URL string to the Revocation List).
Note: there used to be a second argument flag_oneTimeOnly which used to revoke the Blob URL automatically after it's first use, but that is currently no longer part of the spec! Also this flag often didn't work anyway (at least in firefox).
var myBlobURL=window.URL.createFor(object);
returns a Blob URL that is automatically revoked after it's first use.
Note: quite some browsers were 'late' to implement this one.
MediaSource object URL referencing a special MediaSource Object
These URL's are
only intended to link src of a HTMLMediaElement (think <audo> & <video> elements) to the special MediaSource Object
Note: a new tab/window is not an HTMLMediaElement
already automatically revoked
Note: even though they are created through window.URL.createObjectURL();
Here's what's happening for the fiddle in your question's image and similar code that downloaded a video as Blob (where you downloaded the whole video-file's data/binary on the server using an xhr) or any other 'local' data:
You are essentially using the 'bare' 'un-enhanced' File-API.
The URL Store is only maintained during a session (so it will survive a page-refresh, since it is still the same session) and lost when the document is unloaded.
So, if your fiddle is still open, then fiddle-document (the document that created the Blob URL) is obviously not yet unloaded, and therefore it's Blob URLs are available to the browser (any tab/window) as long as it is not revoked!
This is a relevant feature: you can build/download/modify a Blob in the browser, create a Blob URL and set it as href to a file-download link (which the user can right-click and open in a new tab/window!!)
Close the fiddle or revoke the Blob URL from the URL Store and the Blob URL is no longer accessible (also not in a different tab/window).
Try yourself with your modified fiddle: https://jsfiddle.net/7cyoozwv/
In this fiddle it should now no longer be possible to load your sample image into a different tab/window after you copied the image url (once the image is displayed in your page).
Here I revoked the URL manually (revokeObjectURL()) as it is currently the best cross-browser method (partially due to the api not yet fully being stabilized).
Also note: an element's onload event can be an elegant place to revoke your Blob URL.
Here is what's happening to an <audio> or <video> source linked to an MediaSource Object using an MediaSource object URL returned by window.URL.createObjectURL(MediaSource):
The Media Source Extensions (MSE) also extend the File-API's window.URL.createObjectURL() to accept a MediaSource Object. The (current draft of the) URL Object Extension specifies that:
This algorithm is intended to mirror the behavior of the createObjectURL()[FILE-API] method with autoRevoke set to true.
Note that the current spec of the File API's window.URL.createObjectURL() no longer has an autoRevoke (or flag_oneTimeOnly) boolean flag accessible to the programmer who should be using window.URL.createFor() for this purpose instead. I wonder when the Media-Source spec will mimic that (and for backward compatibility alias their createObjectURL() to a new createFor() extension (seems more appropriate as that is how it seems to be intended to work currently)).
These resulting automatically revoked URL-strings are only intended to link the src of a HTMLMediaElement (think <audo> & <video> elements) to the special MediaSource Object.
I don't think that an empty Document (from a new tab/window) is a <audo> or <video> element.
Perhaps "A quick tutorial on MSE"(source: MSDN) might help clarify the difference and basic use:
To use the MSE API, follow these steps:
Define an HTML5 video element in the HTML section of a page.
Create a MediaSource object in JavaScript.
Create a virtual URL using createObjectURL with the MediaSource object as the source.
Assign the virtual URL to the video element's src property.
Create a SourceBuffer using addSourceBuffer, with the mime type of the video you're adding.
Get the video initialization segment from the media file online and add it to the SourceBuffer with appendBuffer.
Get the segments of video data from the media file, append them to the SourceBuffer with appendBuffer.
Call the play method on the video element.
Repeat step 7 until done.
Clean up.
You (or a big-time player like youtube who will dynamically select supported technologies for playback on the client's platform (so there is no way to tell for sure what kind of youtube video URL's you are talking about)) could be using the new special MediaSource Object to play video's (or audio).
This adds buffer-based source options to HTML5 video for streaming support (compared to to downloading a complete video file before playing or use an add-on like Silverlight or Adobe Flash to stream media).
Hope this is what you were after!
Actually, the URL that you're referring is just a "string" reference to the BLOB itself (which is created using the function window.URL.createObjectURL); So, that you can use it like a normal URL. And, the scope is also only until the document is unloaded.
So, I don't think it is possible for you to open the URL just using browser. And also I tried to re-create what you're saying but with no avail (in my own website, create a blob and put the URL into browser).
Below is the code
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://kurrik.github.io/hackathons/static/img/sample-128.png");
xhr.responseType = "blob";
xhr.onload = function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
console.log(imageUrl);
var imgDOM = document.createElement("img");
imgDOM.src = imageUrl;
document.getElementById("divImage").appendChild(imgDOM);
};
xhr.send();
The fiddle here
Update :
Ok, after I looked at it. seems like youtube is using media-source to stream the video.
I haven't updated the fiddle (cannot found a video that I can use). But, basically, It still using the same function (createObjectURL) to create the blob URL. But, instead of using the source (image, video, etc) to pass to the function. You should pass the MediaSource object into the function.
And then, you use the blob URL and pass it into the video.src. Therefore, when you try to open the blob link. You should not be able to see the video again.

Convert blob URL to normal URL

My page generates a URL like this: "blob:http%3A//localhost%3A8383/568233a1-8b13-48b3-84d5-cca045ae384f" How can I convert it to a normal address?
I'm using it as an <img>'s src attribute.
A URL that was created from a JavaScript Blob can not be converted to a "normal" URL.
A blob: URL does not refer to data the exists on the server, it refers to data that your browser currently has in memory, for the current page. It will not be available on other pages, it will not be available in other browsers, and it will not be available from other computers.
Therefore it does not make sense, in general, to convert a Blob URL to a "normal" URL. If you wanted an ordinary URL, you would have to send the data from the browser to a server and have the server make it available like an ordinary file.
It is possible convert a blob: URL into a data: URL, at least in Chrome. You can use an AJAX request to "fetch" the data from the blob: URL (even though it's really just pulling it out of your browser's memory, not making an HTTP request).
Here's an example:
var blob = new Blob(["Hello, world!"], { type: 'text/plain' });
var blobUrl = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
var blobAsDataUrl = reader.result;
window.location = blobAsDataUrl;
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', blobUrl);
xhr.send();
data: URLs are probably not what you mean by "normal" and can be problematically large. However they do work like normal URLs in that they can be shared; they're not specific to the current browser or session.
another way to create a data url from blob url may be using canvas.
var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)
as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)
For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.
Another guide shows you how to save a stream with the VLC Player.
UPDATE:
An alternative way of downloading the videos from a blob url is by using the mass downloader and joining the files together.
Download Videos Part
Open network tab in chrome dev tools
Reload the webpage
Filter .m3u8 files
Look through all filtered files and find the playlist of the '.ts' files. It should look something like this:
You need to extract those links somehow. Either download and edit the file manually OR use any other method you like. As you can see, those links are very similar, the only thing that differs is the serial number of the video: 's-0-v1-a1.ts', 's-1-v1-a1.ts' etc.
https://some-website.net/del/8cf.m3u8/s-0-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-1-v1-a1.ts
https://some-website.net/del/8cf.m3u8/s-2-v1-a1.ts
and so on up to the last link in the .m3u8 playlist file. These .ts files are actually your video. You need to download all of them.
For bulk downloading I prefer using the Simple Mass Downloader extension for Chrome (https://chrome.google.com/webstore/detail/simple-mass-downloader/abdkkegmcbiomijcbdaodaflgehfffed)
If you opt in for the Simple Mass Downloader, you need to:
a. Select a Pattern URL
b. Enter your link in the address field with only one modification: that part of the link that is changing for each next video needs to be replaced with the pattern in square brackets [0:400] where 0 is the first file name and 400 is the last one. So your link should look something like this https://some-website.net/del/8cf.m3u8/s-[0:400]-v1-a1.ts.
Afterwards hit the Import button to add these links into the Download List of Mass Downloader.
c. The next action may ask you for the destination folder for EACH video you download. So it is highly recommended to specify the default download folder in Chrome Settings and disable the Select Destination option in Chrome Settings as well. This will save you a lot of time! Additionally you may want you specify the folder where these files will go to:
c1. Click on Select All checkbox to select all files from the Download List.
c2. Click on the Download button in the bottom right corner of the SMD extension window. It will take you to next tab to start downloading
c3. Hit Start selected. This will download all vids automatically into the download folder.
That is it! Simply wait till all files are downloaded and you can watch them via the VLC Player or any other player that supports the .ts format. However, if you want to have one video instead of those you have downloaded, you need to join all these mini-videos together
Joining Videos Part
Since I am working on Mac, I am not aware of how you would do this on Windows. If you are the Windows user and you want to merge the videos, feel free to google for the windows solution. The next steps are applicable for Mac only.
Open Terminal in the folder you want the new video to be saved in
Type: cat and hit space
Open the folder where you downloaded your .ts video. Select all .ts videos that you want to join (use your mouse or cmd+A)
Drag and drop them into the terminal
Hit space
Hit >
Hit Space
Type the name of the new video, e.g. my_new_video.ts. Please note that the format has to be the same as in the original videos, otherwise it will take long time to convert and even may fail!
Hit Enter. Wait for the terminal to finish the joining process and enjoy watching your video!
Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:
function blobToDataURL(blob, callback) {
var fileReader = new FileReader();
fileReader.onload = function(e) {callback(e.target.result);}
fileReader.readAsDataURL(blob);
}
I'm very late to the party.
If you want to download the content you can simply use fetch now
fetch(blobURL)
.then(res => res.blob())
.then(blob => /*do what you want with the blob here*/)
Here the solution:
let blob = new Blob(chunks, { 'type' : 'video/mp4;' });
let videoURL = window.URL.createObjectURL(blob);
const blobF = await fetch(videoURL).then(res => res.blob())
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.

Categories

Resources