forked from Yahweasel/libav.js
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
post.in.js
2814 lines (2520 loc) · 90.6 KB
/
post.in.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.
*/
// A global promise chain for serialization of asyncify components
var serializationPromise = null;
function serially(f) {
var p;
if (serializationPromise) {
p = serializationPromise.catch(function(){}).then(function() {
return f();
});
} else {
p = f();
}
serializationPromise = p = p.finally(function() {
if (serializationPromise === p)
serializationPromise = null;
});
return p;
}
// A global error passed through filesystem operations
Module.fsThrownError = null;
var ERRNO_CODES = {
EPERM: 1,
EIO: 5,
EAGAIN: 6,
ECANCELED: 11,
ESPIPE: 29
};
// Callbacks for stream-based reader
var readerCallbacks = {
open: function(stream) {
if (stream.flags & 3) {
// Opened in write mode, which can't work
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
},
close: function() {},
read: function(stream, buffer, offset, length, position) {
var data = Module.readBuffers[stream.node.name];
if (!data || (data.buf.length === 0 && !data.eof)) {
if (Module.onread) {
try {
var rr = Module.onread(stream.node.name, position, length);
if (rr && rr.then && rr.catch) {
rr.catch(function(ex) {
ff_reader_dev_send(stream.node.name, null, {error: ex});
});
}
} catch (ex) {
ff_reader_dev_send(stream.node.name, null, {error: ex});
}
}
data = Module.readBuffers[stream.node.name];
}
if (!data)
throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
if (data.error) {
Module.fsThrownError = data.error;
throw new FS.ErrnoError(ERRNO_CODES.ECANCELED);
}
if (data.errorCode)
throw new FS.ErrnoError(data.errorCode);
if (data.buf.length === 0) {
if (data.eof) {
return 0;
} else {
data.ready = false;
throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
}
}
var ret;
if (length < data.buf.length) {
// Cut a slice
ret = data.buf.subarray(0, length);
data.buf = data.buf.slice(length);
} else {
// Get the beginning
ret = data.buf;
data.buf = new Uint8Array(0);
}
(new Uint8Array(buffer.buffer)).set(ret, offset);
return ret.length;
},
write: function() {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
},
llseek: function() {
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
}
};
// Callbacks for block-based reader
var blockReaderCallbacks = {
open: function(stream) {
if (stream.flags & 3)
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
},
close: function() {},
read: function(stream, buffer, offset, length, position) {
var data = Module.blockReadBuffers[stream.node.name];
if (!data)
throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
if (data.error) {
Module.fsThrownError = data.error;
throw new FS.ErrnoError(ERRNO_CODES.ECANCELED);
}
if (data.errorCode)
throw new FS.ErrnoError(data.errorCode);
var bufMin = data.position;
var bufMax = data.position + data.buf.length;
if (position < bufMin || position >= bufMax) {
if (position >= stream.node.ff_block_reader_dev_size)
return 0; // EOF
if (!Module.onblockread)
throw new FS.ErrnoError(ERRNO_CODES.EIO);
try {
var brr = Module.onblockread(stream.node.name, position, length);
if (brr && brr.then && brr.catch) {
brr.catch(function(ex) {
ff_block_reader_dev_send(stream.node.name, position, null, {error: ex});
});
}
} catch (ex) {
Module.fsThrownError = ex;
throw new FS.ErrnoError(ERRNO_CODES.ECANCELED);
}
// If it was asynchronous, this won't be ready yet
bufMin = data.position;
bufMax = data.position + data.buf.length;
if (position < bufMin || position >= bufMax) {
data.ready = false;
throw new FS.ErrnoError(ERRNO_CODES.EAGAIN);
}
}
var bufPos = position - bufMin;
var ret;
if (bufPos + length < data.buf.length) {
// Cut a slice
ret = data.buf.subarray(bufPos, bufPos + length);
} else {
// Get the beginning of what was requested
ret = data.buf.subarray(bufPos, data.buf.length);
}
(new Uint8Array(buffer.buffer)).set(ret, offset);
return ret.length;
},
write: function() {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
},
llseek: function(stream, offset, whence) {
if (whence === 2 /* SEEK_END */)
offset = stream.node.size + offset;
else if (whence === 1 /* SEEK_CUR */)
offset += stream.position;
return offset;
}
};
// Callbacks for block-based writer
var writerCallbacks = {
open: function(stream) {
if (!(stream.flags & 1)) {
// Opened in read mode, which can't work
throw new FS.ErrnoError(ERRNO_CODES.EPERM);
}
},
close: function() {},
read: function() {
throw new FS.ErrnoError(ERRNO_CODES.EIO);
},
write: function(stream, buffer, offset, length, position) {
if (!Module.onwrite)
throw new FS.ErrnoError(ERRNO_CODES.EIO);
Module.onwrite(stream.node.name, position, buffer.subarray(offset, offset + length));
return length;
},
llseek: function(stream, offset, whence) {
if (whence === 2)
throw new FS.ErrnoError(ERRNO_CODES.EIO);
else if (whence === 1)
offset += stream.position;
return offset;
}
};
// Callbacks for stream-based writer
var streamWriterCallbacks = Object.create(writerCallbacks);
streamWriterCallbacks.write = function(stream, buffer, offset, length, position) {
if (position != stream.position)
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
return writerCallbacks.write(stream, buffer, offset, length, position);
};
streamWriterCallbacks.llseek = function() {
throw new FS.ErrnoError(ERRNO_CODES.ESPIPE);
};
/* Filesystem for a writer directory. This is done by using MEMFS, but overriding
* the stream operations. */
var streamWriterFS = Object.create(MEMFS);
streamWriterFS.mount = function(mount) {
return streamWriterFS.createNode(null, "/", 0x4000 /* S_IFDIR */ | 0x1FF, 0);
}
streamWriterFS.createNode = function() {
var node = MEMFS.createNode.apply(MEMFS, arguments);
if (FS.isDir(node.mode)) {
if (!streamWriterFS.dir_node_ops) {
streamWriterFS.dir_node_ops = Object.create(node.node_ops);
streamWriterFS.dir_node_ops.mknod = function(parent, name, mode, dev) {
return streamWriterFS.createNode(parent, name, mode, dev);
};
}
node.node_ops = streamWriterFS.dir_node_ops;
} else if (FS.isFile(node.mode)) {
node.stream_ops = writerCallbacks;
}
return node;
};
/* Original versions of all our functions, since the Module version is replaced
* if we're a Worker */
var CAccessors = {};
@FUNCS
// Filesystem
function fsBinding(of) {
Module[of] = function() {
try {
return FS[of].apply(FS, arguments);
} catch (ex) {
if (ex && ex.name === "ErrnoError") {
// Give a more useful error
ex.message = strerror(ex.errno);
if (typeof arguments[0] === "string")
ex.message = arguments[0] + ": " + ex.message;
}
throw ex;
}
};
}
var readerDev = FS.makedev(44, 0);
FS.registerDevice(readerDev, readerCallbacks);
Module.readBuffers = Object.create(null);
Module.blockReadBuffers = Object.create(null);
var writerDev = FS.makedev(44, 1);
FS.registerDevice(writerDev, writerCallbacks);
var streamWriterDev = FS.makedev(44, 2);
FS.registerDevice(streamWriterDev, streamWriterCallbacks);
/**
* Read a complete file from the in-memory filesystem.
* @param name Filename to read
*/
/// @types readFile@sync(name: string): @promise@Uint8Array@
fsBinding("readFile");
/**
* Write a complete file to the in-memory filesystem.
* @param name Filename to write
* @param content Content to write to the file
*/
/// @types writeFile@sync(name: string, content: Uint8Array): @promise@Uint8Array@
fsBinding("writeFile");
/**
* Delete a file in the in-memory filesystem.
* @param name Filename to delete
*/
/// @types unlink@sync(name: string): @promise@void@
fsBinding("unlink");
/**
* Unmount a mounted filesystem.
* @param mountpoint Path where the filesystem is mounted
*/
/// @types unmount@sync(mountpoint: string): @promise@void@
fsBinding("unmount");
fsBinding("mkdev");
/**
* Make a lazy file. Direct link to createLazyFile.
*/
/* @types
* createLazyFile@sync(
* parent: string, name: string, url: string, canRead: boolean,
* canWrite: boolean
* ): @promise@void@
*/
fsBinding("createLazyFile");
/**
* Make a reader device.
* @param name Filename to create.
* @param mode Unix permissions (pointless since this is an in-memory
* filesystem)
*/
/// @types mkreaderdev@sync(name: string, mode?: number): @promise@void@
Module.mkreaderdev = function(loc, mode) {
FS.mkdev(loc, mode?mode:0x1FF, readerDev);
Module.readBuffers[loc] = {
buf: new Uint8Array(0),
eof: false,
errorCode: 0,
error: null
};
return 0;
};
/**
* Make a block reader "device". Technically a file that we then hijack to have
* our behavior.
* @param name Filename to create.
* @param size Size of the device to present.
*/
/// @types mkblockreaderdev@sync(name: string, size: number): @promise@void@
var mkblockreaderdev = Module.mkblockreaderdev = function(name, size) {
FS.writeFile(name, new Uint8Array(0));
var f = FS.open(name, 0);
var super_node_ops = f.node.node_ops;
var node_ops = f.node.node_ops = Object.create(super_node_ops);
node_ops.getattr = function(node) {
var ret = super_node_ops.getattr(node);
ret.size = size;
ret.blksize = 4096;
ret.blocks = Math.ceil(size / 4096);
return ret;
};
f.node.stream_ops = blockReaderCallbacks;
f.node.ff_block_reader_dev_size = size;
Module.blockReadBuffers[name] = {
position: -1,
buf: new Uint8Array(0),
ready: false,
errorCode: 0,
error: null
};
FS.close(f);
};
// Readahead devices
var readaheads = {};
// Original onblockread
var preReadaheadOnBlockRead = null;
// Passthru for readahead.
function readaheadOnBlockRead(name, position, length) {
if (!(name in readaheads)) {
if (preReadaheadOnBlockRead)
return preReadaheadOnBlockRead(name, position, length);
return;
}
var ra = readaheads[name];
function then() {
if (ra.position !== position) {
ra.position = position;
ra.buf = null;
ra.bufPromise = ra.file.slice(position, position + length).arrayBuffer()
.then(function(ret) {
ra.buf = ret;
}).catch(function(ex) {
console.error(ex + "\n" + ex.stack);
ra.buf = new Uint8Array(0);
}).then(then);
return;
}
ff_block_reader_dev_send(name, position, new Uint8Array(ra.buf));
// Attempt to predict the next read
position += length;
ra.position = position;
ra.buf = null;
ra.bufPromise = ra.file.slice(position, position + length).arrayBuffer()
.then(function(ret) {
ra.buf = ret;
}).catch(function(ex) {
console.error(ex + "\n" + ex.stack);
ra.buf = new Uint8Array(0);
});
}
if (!ra.buf && ra.bufPromise)
ra.bufPromise.then(then);
else
then();
}
/**
* Make a readahead device. This reads a File (or other Blob) and attempts to
* read ahead of whatever libav actually asked for. Note that this overrides
* onblockread, so if you want to support both kinds of files, make sure you set
* onblockread before calling this.
* @param name Filename to create.
* @param file Blob or file to read.
*/
/// @types mkreadaheadfile@sync(name: string, file: Blob): @promise@void@
Module.mkreadaheadfile = function(name, file) {
if (Module.onblockread !== readaheadOnBlockRead) {
preReadaheadOnBlockRead = Module.onblockread;
Module.onblockread = readaheadOnBlockRead;
}
mkblockreaderdev(name, file.size);
readaheads[name] = {
file: file,
position: -1,
bufPromise: null,
buf: null
};
};
/**
* Unlink a readahead file. Also gets rid of the File reference.
* @param name Filename to unlink.
*/
/// @types unlinkreadaheadfile@sync(name: string): @promise@void@
Module.unlinkreadaheadfile = function(name) {
FS.unlink(name);
delete readaheads[name];
};
/**
* Make a writer device.
* @param name Filename to create
* @param mode Unix permissions
*/
/// @types mkwriterdev@sync(name: string, mode?: number): @promise@void@
var mkwriterdev = Module.mkwriterdev = function(loc, mode) {
FS.mkdev(loc, mode?mode:0x1FF, writerDev);
return 0;
};
/**
* Make a stream writer device. The same as a writer device but does not allow
* seeking.
* @param name Filename to create
* @param mode Unix permissions
*/
/// @types mkstreamwriterdev@sync(name: string, mode?: number): @promise@void@
Module.mkstreamwriterdev = function(loc, mode) {
FS.mkdev(loc, mode?mode:0x1FF, streamWriterDev);
return 0;
};
/**
* Mount a writer *filesystem*. All files created in this filesystem will be
* redirected as writers. The directory will be created for you if it doesn't
* already exist, but it may already exist.
* @param mountpoint Directory to mount as a writer filesystem
*/
/// @types mountwriterfs@sync(mountpoint: string): @promise@void@
Module.mountwriterfs = function(mountpoint) {
try {
FS.mkdir(mountpoint);
} catch (ex) {}
FS.mount(streamWriterFS, {}, mountpoint);
return 0;
}
// Users waiting to read
Module.ff_reader_dev_waiters = Object.create(null);
/**
* Make a workerfs file. Returns the filename that it's mounted to.
* @param name Filename to use.
* @param blob Blob to load at that file.
*/
/// @types mkworkerfsfile@sync(name: string, blob: Blob): @promise@string@
Module.mkworkerfsfile = function(name, blob) {
FS.mkdir("/" + name + ".d");
FS.mount(WORKERFS, {
blobs: [{name: name, data: blob}]
}, "/" + name + ".d");
return "/" + name + ".d/" + name;
};
/**
* Unmount (unmake) a workerfs file. Give the *original name you provided*, not
* the name mkworkerfsfile returned.
* @param name Filename to unmount.
*/
/// @types unlinkworkerfsfile@sync(name: string): @promise@void@
Module.unlinkworkerfsfile = function(name) {
FS.unmount("/" + name + ".d");
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.
* @param name Filename of the reader device.
* @param data Data to send.
* @param opts Optional send options, such as an error code.
*/
/* @types
* ff_reader_dev_send@sync(
* name: string, data: Uint8Array | null,
* opts?: {
* errorCode?: number,
* error?: any // any other error, used internally
* }
* ): @promise@void@
*/
var ff_reader_dev_send = Module.ff_reader_dev_send = function(name, data, opts) {
opts = opts || {};
var idata = Module.readBuffers[name];
if (data === null) {
// EOF or error
idata.eof = true;
} else {
var newbuf = new Uint8Array(idata.buf.length + data.length);
newbuf.set(idata.buf);
newbuf.set(data, idata.buf.length);
idata.buf = newbuf;
}
idata.ready = true;
idata.errorCode = 0;
if (typeof opts.errorCode === "number")
idata.errorCode = opts.errorCode;
idata.error = null;
if (opts.error)
idata.error = opts.error;
// Wake up waiters
var waiters = Module.ff_reader_dev_waiters[name] || [];
delete Module.ff_reader_dev_waiters[name];
for (var i = 0; i < waiters.length; i++)
waiters[i]();
};
/**
* Send some data to a block reader device. To indicate EOF, send null (but note
* that block read devices have a fixed size, and will automatically send EOF
* for reads outside of that size, so you should not normally need to send EOF).
* To indicate an error, send EOF and include an error code in the options.
* @param name Filename of the reader device.
* @param pos Position of the data in the file.
* @param data Data to send.
* @param opts Optional send options, such as an error code.
*/
/* @types
* ff_block_reader_dev_send@sync(
* name: string, pos: number, data: Uint8Array | null,
* opts?: {
* errorCode?: number,
* error?: any // any other error, used internally
* }
* ): @promise@void@
*/
var ff_block_reader_dev_send = Module.ff_block_reader_dev_send = function(name, pos, data, opts) {
opts = opts || {};
var idata = Module.blockReadBuffers[name];
idata.position = pos;
idata.buf = data;
idata.ready = true;
idata.errorCode = 0;
idata.error = null;
if (data === null)
idata.buf = new Uint8Array(0);
if (typeof opts.errorCode === "number")
idata.errorCode = opts.errorCode;
if (opts.error)
idata.error = opts.error;
// Wake up waiters
var waiters = Module.ff_reader_dev_waiters[name] || [];
delete Module.ff_reader_dev_waiters[name];
for (var i = 0; i < waiters.length; i++)
waiters[i]();
};
/**
* @deprecated
* DEPRECATED. Use the onread callback.
* Metafunction to determine whether any device has any waiters. This can be
* used to determine whether more data needs to be sent before a previous step
* will be fully resolved.
* @param name Optional name of file to check for waiters
*/
/// @types ff_reader_dev_waiting@sync(name?: string): @promise@boolean@
var ff_reader_dev_waiting = Module.ff_reader_dev_waiting = function(name) {
console.log("[libav.js] ff_reader_dev_waiting is deprecated. Use the onread callback.");
return ff_nothing().then(function() {
if (name)
return !!Module.ff_reader_dev_waiters[name];
else
return !!Object.keys(Module.ff_reader_dev_waiters).length;
});
};
/**
* Internal function to determine if this device is ready (to avoid race
* conditions).
*/
Module.readerDevReady = function(fd) {
var stream = FS.streams[fd].node.name;
if (stream in Module.readBuffers)
return Module.readBuffers[stream].ready;
else if (stream in Module.blockReadBuffers)
return Module.blockReadBuffers[stream].ready;
return false;
};
/**
* Internal function to get the name of a file being read by an FD.
*/
Module.fdName = function(fd) {
return FS.streams[fd].node.name;
};
/**
* Metafunction to initialize an encoder with all the bells and whistles.
* Returns [AVCodec, AVCodecContext, AVFrame, AVPacket, frame_size]
* @param name libav name of the codec
* @param opts Encoder options
*/
/* @types
* ff_init_encoder@sync(
* name: string, opts?: {
* ctx?: AVCodecContextProps,
* time_base?: [number, number],
* options?: Record<string, string>
* }
* ): @promise@[number, number, number, number, number]@
*/
var ff_init_encoder = Module.ff_init_encoder = function(name, opts) {
opts = opts || {};
var codec = avcodec_find_encoder_by_name(name);
if (codec === 0)
throw new Error("Codec not found");
var c = avcodec_alloc_context3(codec);
if (c === 0)
throw new Error("Could not allocate audio codec context");
var ctxProps = opts.ctx || {};
for (var prop in ctxProps)
this["AVCodecContext_" + prop + "_s"](c, ctxProps[prop]);
var time_base = opts.time_base || [1, 1000];
AVCodecContext_time_base_s(c, time_base[0], time_base[1]);
var options = 0;
if (opts.options) {
for (var prop in opts.options)
options = av_dict_set_js(options, prop, opts.options[prop], 0);
}
var ret = avcodec_open2_js(c, codec, options);
if (ret < 0)
throw new Error("Could not open codec: " + ff_error(ret));
var frame = av_frame_alloc();
if (frame === 0)
throw new Error("Could not allocate frame");
var pkt = av_packet_alloc();
if (pkt === 0)
throw new Error("Could not allocate packet");
var frame_size = AVCodecContext_frame_size(c);
return [codec, c, frame, pkt, frame_size];
};
/**
* Metafunction to initialize a decoder with all the bells and whistles.
* Similar to ff_init_encoder but doesn't need to initialize the frame.
* Returns [AVCodec, AVCodecContext, AVPacket, AVFrame]
* @param name libav decoder identifier or name
* @param config Decoder configuration. Can just be a number for codec
* parameters, or can be multiple configuration options.
*/
/* @types
* ff_init_decoder@sync(
* name: string | number, config?: number | {
* codecpar?: number | CodecParameters,
* time_base?: [number, number]
* }
* ): @promise@[number, number, number, number]@
*/
var ff_init_decoder = Module.ff_init_decoder = function(name, config) {
if (typeof config === "number") {
config = {codecpar: config};
} else {
config = config || {};
}
var codec, ret;
if (typeof name === "string")
codec = avcodec_find_decoder_by_name(name);
else
codec = avcodec_find_decoder(name);
if (codec === 0)
throw new Error("Codec not found");
var c = avcodec_alloc_context3(codec);
if (c === 0)
throw new Error("Could not allocate audio codec context");
var codecid = AVCodecContext_codec_id(c);
if (config.codecpar) {
var codecparPtr = 0;
var codecpar = config.codecpar;
if (typeof codecpar === "object") {
codecparPtr = avcodec_parameters_alloc();
if (codecparPtr === 0)
throw new Error("Failed to allocate codec parameters");
ff_copyin_codecpar(codecparPtr, codecpar);
codecpar = codecparPtr;
}
ret = avcodec_parameters_to_context(c, codecpar);
if (codecparPtr)
avcodec_parameters_free_js(codecparPtr);
if (ret < 0)
throw new Error("Could not set codec parameters: " + ff_error(ret));
}
// If it is not set, use the copy.
if (AVCodecContext_codec_id(c) === 0) AVCodecContext_codec_id_s(c, codecid);
// Keep the time base
if (config.time_base)
AVCodecContext_time_base_s(c, config.time_base[0], config.time_base[1]);
ret = avcodec_open2(c, codec, 0);
if (ret < 0)
throw new Error("Could not open codec: " + ff_error(ret));
var pkt = av_packet_alloc();
if (pkt === 0)
throw new Error("Could not allocate packet");
var frame = av_frame_alloc();
if (frame === 0)
throw new Error("Could not allocate frame");
return [codec, c, pkt, frame];
};
/**
* Free everything allocated by ff_init_encoder.
* @param c AVCodecContext
* @param frame AVFrame
* @param pkt AVPacket
*/
/* @types
* ff_free_encoder@sync(
* c: number, frame: number, pkt: number
* ): @promise@void@
*/
var ff_free_encoder = Module.ff_free_encoder = function(c, frame, pkt) {
av_frame_free_js(frame);
av_packet_free_js(pkt);
avcodec_free_context_js(c);
};
/**
* Free everything allocated by ff_init_decoder
* @param c AVCodecContext
* @param pkt AVPacket
* @param frame AVFrame
*/
/* @types
* ff_free_decoder@sync(
* c: number, pkt: number, frame: number
* ): @promise@void@
*/
var ff_free_decoder = Module.ff_free_decoder = function(c, pkt, frame) {
ff_free_encoder(c, frame, pkt);
};
/**
* Encode some number of frames at once. Done in one go to avoid excess message
* passing.
* @param ctx AVCodecContext
* @param frame AVFrame
* @param pkt AVPacket
* @param inFrames Array of frames in libav.js format
* @param config Encoding options. May be "true" to indicate end of stream.
*/
/* @types
* ff_encode_multi@sync(
* ctx: number, frame: number, pkt: number, inFrames: (Frame | number)[],
* config?: boolean | {
* fin?: boolean,
* copyoutPacket?: "default"
* }
* ): @promise@Packet[]@
* ff_encode_multi@sync(
* ctx: number, frame: number, pkt: number, inFrames: (Frame | number)[],
* config: {
* fin?: boolean,
* copyoutPacket: "ptr"
* }
* ): @promise@number[]@
*/
var ff_encode_multi = Module.ff_encode_multi = function(ctx, frame, pkt, inFrames, config) {
if (typeof config === "boolean") {
config = {fin: config};
} else {
config = config || {};
}
var outPackets = [];
var tbNum = AVCodecContext_time_base_num(ctx);
var tbDen = AVCodecContext_time_base_den(ctx);
var copyoutPacket = function(ptr) {
var ret = ff_copyout_packet(ptr);
if (!ret.time_base_num) {
ret.time_base_num = tbNum;
ret.time_base_den = tbDen;
}
return ret;
};
if (config.copyoutPacket === "ptr") {
copyoutPacket = function(ptr) {
var ret = ff_copyout_packet_ptr(ptr);
if (!AVPacket_time_base_num(ret))
AVPacket_time_base_s(ret, tbNum, tbDen);
return ret;
};
}
function handleFrame(inFrame) {
if (inFrame !== null) {
ff_copyin_frame(frame, inFrame);
if (tbNum) {
if (typeof inFrame === "number") {
var itbn = AVFrame_time_base_num(frame);
if (itbn) {
ff_frame_rescale_ts_js(
frame,
itbn, AVFrame_time_base_den(frame),
tbNum, tbDen
);
AVFrame_time_base_s(frame, tbNum, tbDen);
}
} else if (inFrame && inFrame.time_base_num) {
ff_frame_rescale_ts_js(
frame,
inFrame.time_base_num, inFrame.time_base_den,
tbNum, tbDen
);
AVFrame_time_base_s(frame, tbNum, tbDen);
}
}
}
var ret = avcodec_send_frame(ctx, inFrame?frame:0);