Skip to content

Commit

Permalink
Adding support for FileSystemFileHandle writing
Browse files Browse the repository at this point in the history
Reading is already supported through the File interface with readahead
files. `mkfsfhfile` supports both the synchronous and asynchronous
interface, and uses the synchronous interface preferentially.
  • Loading branch information
Yahweasel committed Sep 25, 2024
1 parent 272ff78 commit 0d12712
Show file tree
Hide file tree
Showing 3 changed files with 239 additions and 2 deletions.
147 changes: 147 additions & 0 deletions demo/fsfh-demo.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<!doctype html>
<!--
* Copyright (C) 2019-2024 Yahweasel and contributors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-->
<html>
<head>
<meta charset="utf-8" />
<title>LibAV.JS FileSystemFileHandle writer demo</title>
</head>
<body>
<script type="text/javascript">(async function() {
try {
const dce = document.createElement.bind(document);
const main = dce("div");
document.body.appendChild(main);

const variant = await new Promise(res => {
const label = dce("label");
label.innerHTML = "Variant:&nbsp;";
label.htmlFor = "variant";
main.appendChild(label);
const vbox = dce("input");
vbox.type = "text";
vbox.id = "variant";
vbox.value = "webm";
main.appendChild(vbox);
const ok = dce("button");
ok.innerHTML = "Load";
main.appendChild(ok);

vbox.focus();
vbox.select();

vbox.onkeypress = ev => {
if (ev.key === "Enter")
res(vbox.value);
};
ok.onclick = ev => {
res(vbox.value);
};
});
main.innerHTML = "Loading...";

// Load libav.js
LibAV = {base: "../dist"};
await new Promise(res => {
const scr = dce("script");
scr.src = `../dist/libav-${variant}.js?${Math.random()}`;
scr.onload = res;
scr.onerror = () => {
alert("Failed to load variant!");
};
document.body.appendChild(scr);
});
const libav = await LibAV.LibAV();

// Load the file
const file = await new Promise(res => {
main.innerHTML = "";
const label = dce("label");
label.innerHTML = "File:&nbsp;";
label.htmlFor = "load-file";
main.appendChild(label);
const picker = dce("input");
picker.type = "file";
picker.id = "load-file";
main.appendChild(picker);

picker.focus();

picker.onchange = () => {
if (picker.files.length > 0)
res(picker.files[0]);
};
});
main.innerHTML = "Loading...";

// Initial read
await libav.mkreadaheadfile("input", file);
const [fmt_ctx, streams] =
await libav.ff_init_demuxer_file("input");

// Create the writer
const fsfh = await showSaveFilePicker({
suggestedName: "out.mkv"
});
await libav.mkfsfhfile("out.mkv", fsfh);

// Get the codec parameters
const ostreams = streams.map(s => [
s.codecpar, s.time_base_num, s.time_base_den
]);

// And the muxer
const [oc, , pb] = await libav.ff_init_muxer({
filename: "out.mkv",
open: true,
codecpars: true
}, ostreams);
await libav.avformat_write_header(oc, 0);

const pkt = await libav.av_packet_alloc();

main.innerHTML = "Remuxing...";

// And read
while (true) {
// Read some packets
const [res, packets] = await libav.ff_read_frame_multi(fmt_ctx, pkt, {
limit: 1024 * 1024,
unify: true
});

// And write them out
if (packets[0])
await libav.ff_write_multi(oc, pkt, packets[0]);

if (res === libav.AVERROR_EOF)
break;
}

await libav.av_write_trailer(oc);
await libav.unlinkfsfhfile("out.mkv");

await libav.ff_free_muxer(oc, pb);
await libav.av_packet_free_js(pkt);
await libav.avformat_close_input_js(fmt_ctx);

main.innerHTML = "Done.";
} catch (ex) {
alert(ex + "");
}
})();
</script>
</body>
</html>
2 changes: 2 additions & 0 deletions funcs.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@
"mkwriterdev",
"mkstreamwriterdev",
"mountwriterfs",
"mkfsfhfile",
"unlinkfsfhfile",
"mkworkerfsfile",
"unlinkworkerfsfile"
],
Expand Down
92 changes: 90 additions & 2 deletions post.in.js
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ var preReadaheadOnBlockRead = null;
function readaheadOnBlockRead(name, position, length) {
if (!(name in readaheads)) {
if (preReadaheadOnBlockRead)
preReadaheadOnBlockRead(name, position, length);
return preReadaheadOnBlockRead(name, position, length);
return;
}

Expand Down Expand Up @@ -438,7 +438,7 @@ Module.unlinkreadaheadfile = function(name) {
* @param mode Unix permissions
*/
/// @types mkwriterdev@sync(name: string, mode?: number): @promise@void@
Module.mkwriterdev = function(loc, mode) {
var mkwriterdev = Module.mkwriterdev = function(loc, mode) {
FS.mkdev(loc, mode?mode:0x1FF, writerDev);
return 0;
};
Expand Down Expand Up @@ -498,6 +498,94 @@ Module.unlinkworkerfsfile = function(name) {
FS.rmdir("/" + name + ".d");
};

// FileSystemFileHandle devices
var fsfhs = {};

// Original onwrite
var preFSFHOnWrite = null;

// Passthru for FSFH writing.
function fsfhOnWrite(name, position, buffer) {
if (!(name in fsfhs)) {
if (preFSFHOnWrite)
return preFSFHOnWrite(name, position, buffer);
return;
}

var h = fsfhs[name];
buffer = buffer.slice(0);

if (h.syncHandle) {
h.syncHandle.write(buffer.buffer, {
at: position
});
return;
}

var p = h.promise.then(function() {
return h.handle.write({
type: "write",
position: position,
data: buffer
});
});

h.promise = p.catch(console.error);
return p;
}

/**
* Make a FileSystemFileHandle device. This writes via a FileSystemFileHandle,
* synchronously if possible. Note that this overrides onwrite, so if you want
* to support both kinds of files, make sure you set onwrite before calling
* this.
* @param name Filename to create.
* @param fsfh FileSystemFileHandle corresponding to this filename.
*/
/// @types mkfsfhfile(name: string, fsfh: FileSystemFileHandle): Promise<void>
Module.mkfsfhfile = function(name, fsfh) {
if (Module.onwrite !== fsfhOnWrite) {
preFSFHOnWrite = Module.onwrite;
Module.onwrite = fsfhOnWrite;
}

mkwriterdev(name);

var h = fsfhs[name] = {
promise: Promise.all([])
};
h.promise = h.promise.then(function() {
return fsfh.createSyncAccessHandle();
}).then(function(syncHandle) {
h.syncHandle = syncHandle;
}).catch(function() {
return fsfh.createWritable();
}).then(function(handle) {
h.handle = handle;
});
return h.promise;
};

/**
* Unlink a FileSystemFileHandle file. Also closes the file handle.
* @param name Filename to unlink.
*/
/// @types unlinkfsfhfile(name: string): Promise<void>
Module.unlinkfsfhfile = function(name) {
FS.unlink(name);
var h = fsfhs[name];
delete fsfhs[name];

if (h.syncHandle) {
h.syncHandle.close();
return Promise.all([]);
}

return h.promise.then(function() {
return h.handle.close();
});
}

/**
* Send some data to a reader device. To indicate EOF, send null. To indicate an
* error, send EOF and include an error code in the options.
Expand Down

0 comments on commit 0d12712

Please sign in to comment.