/
gpac.html
2276 lines (2134 loc) · 85.8 KB
/
gpac.html
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
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>GPAC WASM</title>
<style>
body {
font-family: arial;
margin: 0;
padding: none;
}
.gpac { padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
div.gpac { text-align: center; }
canvas.gpac { border: 0px none; background-color: black; }
#status {
display: inline-block;
vertical-align: top;
margin-top: 30px;
margin-left: 20px;
font-weight: bold;
color: rgb(120, 120, 120);
}
.controls {
display: none;
float: left;
vertical-align: top;
margin-top: 10px;
margin-left: 10px;
}
#output {
width: 99%;
height: 60vh;
margin: 0 auto;
margin-top: 10px;
border-left: 0px;
border-right: 0px;
padding-left: 0px;
padding-right: 0px;
display: block;
background-color: black;
color: white;
font-family: 'Lucida Console', Monaco, monospace;
outline: none;
resize: vertical;
border: 1px solid #ccc;
overflow-y: scroll;
}
#logo { transform-origin: center; }
#cmd {
background-color: black;
width: 99%;
color: white;
font-family: 'Lucida Console', Monaco, monospace;
outline: none;
margin: 0 auto;
margin-top: 0px;
border-left: 0px;
border-right: 0px;
padding-left: 0px;
padding-right: 0px;
display: block;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div style="width: 100%">
<span style="float: left"><a href="https://gpac.io">Home</a> <a href="https://wiki.gpac.io">Wiki</a></span>
<span style="text-align: center; margin: 0 0 0 20%">GPAC@WASM - Run MP4Box and gpac in your browser !</span>
<span id="header" style="float: right"></span>
</div>
<svg viewBox="0 0 20.773 20.773" xml:space="preserve" width="80" height="80">
<radialGradient id="gradR" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" style="stop-color:rgb(0,0,0); stop-opacity:0" />
<stop offset="80%" style="stop-color:rgb(128,0,0); stop-opacity:1" />
<stop offset="90%" style="stop-color:rgb(255,0,0); stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(128,0,0);stop-opacity:1" />
</radialGradient>
<radialGradient id="gradB" cx="50%" cy="50%" r="50%" fx="45%" fy="55%">
<stop offset="0%" style="stop-color:rgb(140,140,140); stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(0,0,0);stop-opacity:1" />
</radialGradient>
<g id="logo">
<path fill="url(#gradB)" d="M 10.5, 13.6 m -5.5, 0 a 5.5,5.5 0 1,0 11,0 a 5.5,5.5 0 1,0 -11,0 M 10.5, 8.1 L 14.5, 1.6 L 6.5, 1.6 L 10.5, 8.1"/>
<animateTransform id="logo_anim" attributeName="transform" attributeType="XML" type="scale" values="1 1; -1 1; 1 1" keyTimes="0; 0.5; 1" dur="1s" repeatCount="indefinite"/>
</g>
<path fill="url(#gradR)" d="M 10.331,0 C 4.595,0.031 -0.031,4.706 0,10.443 0.03,16.179 4.708,20.804 10.442,20.774 16.181,20.743 20.804,16.068 20.773,10.332 20.742,4.594 16.07,-0.03 10.331,0 z m 0.103,19.082 C 5.632,19.106 1.723,15.236 1.696,10.434 1.671,5.633 5.538,1.718 10.34,1.692 c 4.802,-0.026 8.716,3.848 8.743,8.647 0.025,4.803 -3.848,8.716 -8.649,8.743"/>
<g transform="translate(5.6 15)">
<text id="progress" stroke="black" stroke-width="0.1" fill="white" font-size="3.5" font-weight="bold"> </text>
</g>
</svg>
<div class="gpac" id="status">Downloading...</div>
<script>
var console_bck = '';
var cmd_history = [];
var cmd_idx = -1;
var statusElement = document.getElementById('status');
var progressTxt = document.getElementById('progress').childNodes[0];
var animElement = document.getElementById('logo_anim');
var ctrl_down=false;
var opt_down=false;
let use_idbfs = false;
let edit_name = null;
let is_eval = false;
let is_bsize = false;
let is_custfs = false;
var fsess=null;
let prev_filter=null;
let defer_mode=false;
let suspend_sess=false;
let fs_steps=20;
var FS = null;
var element = document.getElementById('output');
if (element) element.value = '/ %';
const run_session = () => {
let i=fs_steps;
while (i) {
let e = LIBGPAC.fs_run(fsess);
if (e) break;
i--;
}
if (suspend_sess || LIBGPAC.fs_last_task(fsess)) {
animElement.stop();
if (!suspend_sess) set_status('Session done');
suspend_sess=false;
} else {
setTimeout(run_session, 0);
}
}
//start anim on logo
animElement.start = function() {
if (! this.started) {
this.setAttribute('dur', '2s');
this.beginElement();
this.started=true;
}
};
//stop anim on logo
animElement.stop = function() {
this.endElementAt(0);
this.setAttribute('dur', 'indefinite');
this.started=false;
};
//create missing dirs in an output path
function check_file_dir(fname, is_directory) {
let paths = fname.split('/');
let path ='/';
while (paths.length) {
if (!paths[0].length) {
paths.shift();
continue;
}
path += paths[0];
if ((paths.length==1) && !is_directory) break;
if (paths.length>1) path+='/';
try {
FS.mkdir(path);
} catch(e) {
}
paths.shift();
}
}
//set status
function set_status(str)
{
statusElement.innerHTML = str;
}
function do_log(str) {
LIBGPAC.print(str);
}
function do_log_err(str) {
LIBGPAC.printErr(str);
}
//load command history from /idbfs/.gpac/history.txt
function load_history() {
let s = FS.analyzePath('/idbfs', true);
if (s.error) {
set_status('IDBFS not mounted');
return;
}
use_idbfs = true;
s = FS.analyzePath('/idbfs/.gpac', true);
if (s.error) FS.mkdir('/idbfs/.gpac');
s = FS.analyzePath('/idbfs/.gpac/history.txt', true);
if (s.error) return;
let strs = FS.readFile('/idbfs/.gpac/history.txt', { encoding: "utf8"}).split('\n');
strs.forEach(s => { if (s.length) cmd_history.push(s); });
}
//save command history to /idbfs/.gpac/history.txt
function save_history() {
if (!use_idbfs) {
return;
}
let txt='';
cmd_history.forEach( c => { txt += c + '\n';});
FS.writeFile('/idbfs/.gpac/history.txt', txt);
FS.syncfs(false, () => {
if (arguments.length) {
err('Failed to sync IDBFS: ' + arguments[0]);
}
});
}
//runs a given script
function run_script(cmd) {
var element = document.getElementById('output');
if (!element) return;
var js_txt = element.innerText;
element.removeAttribute('contenteditable');
element.innerText = '';
is_eval = false;
set_status('');
err = '';
console.log('text is ' + js_txt);
if (!cmd.length || (cmd=='go')) {
var fun = Function(js_txt);
try {
//eval(js_txt);
fun();
} catch (e) {
err = e.message;
}
}
let runElement = document.getElementById('run_script');
runElement.hidden = true;
var cmdDiv = document.getElementById('cmd_div');
cmdDiv.hidden = false;
return com_exit(err);
}
function set_text(txt)
{
var element = document.getElementById('output');
if (txt.length) element.innerText += txt;
else element.innerText = '';
}
//utility to log command error and append '/cwd/ %' at end of textArea
function com_exit() {
if (arguments.length && arguments[0].length) {
do_log('Error: ' + arguments[0]);
}
var d = FS.cwd().split('/');
var n = d.length ? d[d.length-1] : '/';
if (!n.length) n= '/';
do_log(n+ ' %');
GPAC.no_log = true;
}
//our basic terminal emulation
function process_command() {
var cmdElement = document.getElementById('cmd');
var cmd = cmdElement.value;
set_status('cmd is '+cmdElement.value);
cmdElement.value = '';
GPAC.no_log = false;
args = cmd.split(' ');
//evaluates a script - turns textArea in write mode and wait for go/cancel
if (args[0]=='eval') {
var element = document.getElementById('output');
if (element) {
element.setAttribute('contenteditable', true);
element.innerText = '';
set_status('Edit your JS and click run to evaluate, cancel to abort');
}
is_eval = true;
let runElement = document.getElementById('run_script');
runElement.hidden = false;
var cmdDiv = document.getElementById('cmd_div');
cmdDiv.hidden = true;
return;
}
//in eval mode, run
if (is_eval) {
run_script(cmd);
return;
}
if (is_custfs) {
run_prompt(cmd);
return;
}
if (is_bsize) {
let s = parseInt(cmd);
is_bsize = false;
set_status('');
if (s != s) return com_exit('Inavlid value ' + cmd);
GPAC.read_block_size = s;
return com_exit();
}
//nothing to do
if (!cmd.length) {
return com_exit();
}
//in edit mode, save/discard content
if (edit_name != null) {
let do_save = false;
if (args[0]=='save') {
do_save = true;
} else if (args[0] != 'close') {
set_status('Use save or close to exit editor, not ' + args[0]);
return;
}
var element = document.getElementById('output');
if (element) {
element.removeAttribute('contenteditable');
if (do_save) {
FS.writeFile(edit_name, element.innerText);
}
element.innerHTML = '';
}
edit_name = null;
return com_exit();
}
//save history
cmd_history.push(cmd);
save_history();
cmd_idx = -1;
//webpage help
if ((args[0]=="help") || (args[0]=="h")) {
let text = "GPAC WASM demo - " + LIBGPAC.copyright() + "\n";
text+="Use the command line input to run gpac, MP4Box or perform simple filesystem manipulations\n";
text+="If program name is not given, 'gpac' is assumed\n";
text+="\n";
text+="Command line helpers\n";
text+="ls [N]: list files in N or in current directory if N not set or print file N info - use 'ls -l N' for details.\n";
text+="imp [-d] [N]: imports files or directory (-d) to local filesystem file.\n";
text+=" 'imp' : imports single file to current dir using its native name\n";
text+=" 'imp foo' : imports single file as foo\n";
text+=" 'imp foo/' : imports one or more files in foo using their native name\n";
text+=" 'imp -d' : imports a directory to current dir\n";
text+=" 'imp -d foo' : imports a directory as foo\n";
text+="exp NAME: exports given file NAME\n";
text+="cd [NAME]: changes current working directory, use Emscripten home if NAME not provided\n";
text+="cwd: prints current working directory\n";
text+="clear: clears console output\n";
text+="mkdir NAME: creates directory NAME\n";
text+="rm NAME: removes file or empty directory NAME\n";
text+="mv N1 N2: moves file N1 to N2\n";
text+="cp N1 N2: copies file N1 to N2 (no recursive copy support)\n";
text+="show NAME: shows content of file NAME\n";
text+="edit NAME: edits content of file NAME, use 'save' to save and close, 'close' to discard and close\n";
if (LIBGPAC.has_threads) {
text+="worker toggles worker mode on or off (" + (GPAC.worker ? "on" : "off") + ")\n";
text+="threads views number of pre-allocated workers\n";
}
text+="stack prints available size in stack\n";
text+="clearh [N] clears command history. If N is set, only keeps last N items, otherwise clears everything\n";
text+="fetch toggles fetch support in libgpac\n";
text+="bsize sets block size used to read from local disk (default " + GPAC.read_block_size + ")\n";
text+="eval evaluates JS code\n";
text+="fs interactive graph builder\n";
text+="\n";
text+="Up and Down arrows can be used for command history\n";
text+="\n";
text+="The variable $(NAME) can be used to design a file not on Emscripten's file system.\n"
text+="The file will be handled as a stream (not copied). This is the recommended methods for handling large files.\n";
text+="If NAME is an absolute URL other than 'file://' scheme:\n"
text+="- if used for an input, it will be pulled progressively using Fetch API\n"
text+="- if used for an output, it will be pushed progressively using Fetch API. If writable streams fail, the file will be stored in memory until final PUT or canceled.\n"
text+="Otherwise, NAME designs a file to be picked on the user's file system\n"
text+="- if used for an input, a file picker will be shown and status text will indicate the corresponding NAME\n"
text+="- if used for an output, a file saver will be shown with the given NAME. If writable stream failure, the file will be stored in memory until final write or canceled.\n"
text+="\n";
text+="For output files, the extension will be used to derive the output format, e.g. '($file.ts)' will use MPEG-2 TS.\n"
text+="Use '$(file):ext=ts' to override format if desired.\n"
text+="\n";
text+="This syntax CANNOT work when editing files (MP4Box, dasher context, etc...).\n"
text+="\n";
text+="IndexedDB is used for persistent storage, mounted at /idbfs. Typing any command will synchronize the file system.\n";
text+="\n";
text+="The default behaviour for gpac app is to run on the browser/worker main loop in non-blocking mode, running the session at most 100 times before returning control.\n";
text+="This can be configured (see gpac -hx), for example:\n";
text+="\t-step=-1 will block the main browser/worker thread (WILL DEADLOCK if some filters use JS promises or other async tools)\n";
text+="\t-step=0 will use browser defaults for requestAnimationFrame frequency\n";
text+="\t-step=100 will request callback every 10 ms\n";
text+="\t-step=100:1000 will request callback every 10 ms, calling at most 1000 times the session\n";
if (LIBGPAC.has_threads) {
text+="\n";
text+="When running without worker, internal threading of filters (e.g. ffmpeg & co) will be disabled if the session runs only on the main thread.\n"
text+="Use -threads=N with N>0 (typically -threads=1) to enable threading in these filters.\n";
}
do_log(text);
return com_exit();
}
//file or directory import
if (args[0]=='imp') {
let is_dir = false;
let is_mdir = false;
args.shift();
if (args.length && (args[0]=='-d')) {
is_mdir = true;
args.shift();
}
let file_name = null;
if (args.length) file_name = args[0];
if (file_name && (file_name.charAt(file_name.length-1) == '/'))
is_dir = true;
if (file_name && !is_dir && is_mdir) {
file_name += '/';
}
if (is_mdir) is_dir=true;
if (file_name)
check_file_dir(file_name, is_dir);
let input = document.createElement('input');
input['type'] = 'file';
if (!is_mdir) {
input.multiple = is_dir;
} else {
input.directory = true;
input.mozDirectory = true;
input.webkitdirectory = true;
}
input.click();
input.onchange = function() {
for (const file of event.target.files) {
if (file.name.charAt(0) == '.') continue;
let read = new FileReader();
let fname = file_name; //can be null
if (is_dir) {
if (is_mdir) {
if (fname) {
//strip dir name
let name = file.webkitRelativePath.substring(file.webkitRelativePath.indexOf("/") + 1);
fname += name;
} else {
//copy as is
fname = file.webkitRelativePath;
}
} else {
fname += file.name;
}
}
if (!fname) fname = file.name;
read.addEventListener('loadend', (e) => {
const uint8_view = new Uint8Array(read.result);
if (is_mdir) check_file_dir(fname, false);
FS.writeFile(fname, uint8_view);
});
read.readAsArrayBuffer(file);
}
}
return com_exit();
}
//file or directory listing
if (args[0]=='ls') {
let list=0;
if ((args.length>1) && (args[1]=='-l')) {
list=1;
args.splice(1, 1);
}
else if ((args.length>1) && (args[1]=='-la')) {
list=2;
args.splice(1, 1);
}
var d = ((args.length>1) && args[1].length) ? args[1] : FS.cwd();
try {
let stats = FS.stat(d);
if (FS.isDir(stats.mode)) {
var children = FS.readdir(d, { parent: false });
//do_log('Contents of ' + d + ':');
children.forEach(i => {
let text;
if ((i=='.') || (i=='..')) return;
text=i;
if (list) {
stats = FS.stat(d+'/'+i);
if (list==1) {
if (FS.isDir(stats.mode)) text += ' directory';
else text += ' size ' + stats.size;
text += ' modified ' + stats.mtime.toUTCString();
} else {
text = JSON.stringify(stats);
}
}
do_log(text);
});
} else {
let text;
if (list==2) text = JSON.stringify(stats);
else {
text = '' + stats.size + ' modified ' + stats.mtime;
}
do_log(text);
}
return com_exit();
} catch (e) {
return com_exit('No such file');
}
}
//get current working directory
if (args[0]=='cwd') {
do_log(FS.cwd());
return com_exit();
}
//change directory
if (args[0]=='cd') {
var d = (args.length>1) ? args[1] : '/home/web_user';
FS.chdir(d);
return com_exit();
}
//creates directory
if (args[0]=='mkdir') {
if (args.length>1)
FS.mkdir(args[1]);
return com_exit();
}
//remove file
if (args[0]=='rm') {
if (args.length<2) return com_exit('Missing name');
let stats = FS.stat(args[1]);
if (FS.isDir(stats.mode)) FS.rmdir(args[1]);
else FS.unlink(args[1]);
return com_exit();
}
//rename file
if (args[0]=='mv') {
if (args.length<3) return com_exit('Missing file names');
let stats = FS.stat(args[1]);
if (FS.isDir(stats.mode)) return com_exit(args[1] + ' is a directory');
FS.rename(args[1], args[2]);
return com_exit();
}
//copy file
if (args[0]=='cp') {
if (args.length<3) return com_exit('Missing file names');
let stats = FS.stat(args[1]);
if (FS.isDir(stats.mode)) return com_exit(args[1] + ' is a directory');
FS.writeFile(args[2], FS.readFile(args[1], {encoding: "binary"}));
return com_exit();
}
//export file to user file system
if (args[0]=='exp') {
if (args.length<2) return com_exit('Missing file name');
let stats = FS.stat(args[1]);
if (FS.isDir(stats.mode)) return com_exit(args[1] + ' is a directory');
var blob = new Blob([FS.readFile(args[1], {encoding: "binary"})], {type: "application/octet-stream"});
var a = document.createElement("a");
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = args[1];
a.click();
window.URL.revokeObjectURL(url);
return com_exit();
}
//show file
if (args[0]=='show') {
if (args.length<2) return com_exit('Missing file name');
let stats = FS.stat(args[1]);
if (FS.isDir(stats.mode)) return com_exit(args[1] + ' is a directory');
let str = FS.readFile(args[1], { encoding: "utf8"});
do_log(str);
return com_exit();
}
//edit file
if (args[0]=='edit') {
if (args.length<2) return com_exit('Missing file name');;
let stats = FS.stat(args[1]);
if (FS.isDir(stats.mode)) return com_exit(args[1] + ' is a directory');
let str = FS.readFile(args[1], { encoding: "utf8"});
edit_name = args[1];
var element = document.getElementById('output');
if (element) {
element.setAttribute('contenteditable', true);
element.innerText = str;
}
return;
}
//worker tag set
if (args[0]=='worker') {
if (!LIBGPAC.has_threads) {
LIBGPAC.gpac_worker=false;
return com_exit('GPAC compiled without threads');
}
LIBGPAC.gpac_worker = !LIBGPAC.gpac_worker;
do_log('Worker Thread for main: ' + (LIBGPAC.gpac_worker ? 'on' : 'off') );
return com_exit();
}
//print stack free size
if (args[0]=='stack') {
const get_stack_free = LIBGPAC.cwrap('emscripten_stack_get_free', 'number', [])
do_log('Free stack: ' + get_stack_free() + ' bytes');
return com_exit();
}
//clear console
if (args[0]=='clear') {
var element = document.getElementById('output');
if (element) element.innerText = '';
return com_exit();
}
//clear history
if (args[0]=='clearh') {
if (args.length>1)
cmd_history = cmd_history.slice(- parseInt(args[1]) );
else
cmd_history=[];
save_history();
return com_exit();
}
//show allocated threads - usefull to check how many threads were indeed created by the previous run
if (args[0]=='threads') {
if (LIBGPAC.has_threads) {
do_log('Threads Pool Size: ' + LIBGPAC['PThread'].unusedWorkers.length);
return com_exit();
}
return com_exit('GPAC compiled without threads');
}
//worker tag set
if (args[0]=='fetch') {
LIBGPAC.gpac_fetch = !LIBGPAC.gpac_fetch;
do_log('libgpac fetch() ' + (LIBGPAC.gpac_fetch ? 'on' : 'off') );
return com_exit();
}
if (args[0]=='fs') {
set_status('Starting interactive graph builder');
set_text('');
defer_mode=true;
fs_steps=20;
is_custfs = true;
return;
}
if (args[0]=='bsize') {
set_status('Enter new block size to use (current ' + GPAC.read_block_size + ')');
is_bsize = true;
return;
}
//set logs at runtime (doesn't work when video output is used, text input is always directed to SDL in this case...)
if (args[0]=='logs') {
if (!GPAC.running) {
do_log('GPAC not running');
return;
}
if (args.length>1) {
LIBGPAC.log_set_tools_levels(args[1], 1);
}
return;
}
//
//end of commands
//
//run gpac or mp4box
if (GPAC.running) {
set_status('Already running, ignoring command');
return;
}
cmdElement.readonly = true;
let will_block=false;
let is_mp4box=false;
if (args[0].toLowerCase()=='gpac') {
args.shift();
}
else if (args[0].toLowerCase()=='mp4box') {
args.shift();
is_mp4box = true;
if (LIBGPAC.gpac_worker==false) will_block=true;
}
//when using vout or compositor in standalone mode, don't use a worker thread since we run through emscripten_main_loop
let use_video=false;
let has_report = false;
for (let i=0; i<args.length; i++) {
a = args[i];
if (a.includes('vout') || a.includes('-play') || a.includes('-gui')) {
use_video=true;
} else if (a.includes('compositor')) {
if (a.includes('base') || a.includes('gui')) use_video=true;
} else if ((LIBGPAC.gpac_worker==false) && (a.startsWith('-step='))) {
var val = parseInt(a.substring(6));
if (val<0) will_block = true;
}
else if (a.startsWith('-r')) {
has_report = true;
}
//input file io
else if (a=='-ib') {
args[i] = '-i';
let f = args[i+1];
let fio = GFIO.create(f, 1);
let wrap_url = fio.gfio_url();
args[i+1] = wrap_url;
i++;
}
//output file io
else if (a=='-ob') {
args[i] = '-o';
let f = args[i+1];
let fio = GFIO.create(f, 2);
let wrap_url = fio.gfio_url();
args[i+1] = wrap_url;
i++;
}
//look for automated wrappers $(NAME), create fileIOs and replace names
else {
let select_start = a.indexOf('$(');
let select_end = (select_start>=0) ? a.indexOf(')') : 0;
if (select_end) {
let hint = a.substring(select_start, select_end+1);
let fio = GFIO.create(hint, 0); //can only use this for read mode at the time being
let wrap_url = fio.gfio_url();
args[i] = a.replace(hint, wrap_url);
}
}
}
function run_prompt(cmd) {
let args = cmd.split(' ');
if (!args.length) return;
if (args[0]=='q') {
is_custfs=false;
if (fsess) {
LIBGPAC.fs_del(fsess);
fsess=null;
LIBGPAC.uninit();
set_status("leaving interactive mode");
}
return;
}
if (args[0]=='d') {
if (!fsess) {
defer_mode = !defer_mode;
set_status("will use defer linking mode: " + (defer_mode ? "yes" : "no"));
}
return;
}
if (args[0]=='s') {
if (args.length>1) {
fs_steps = parseInt(args[1]);
if (fs_steps<=0) fs_steps=1;
set_status("will use " + fs_steps + " steps per callback");
}
return;
}
if (args[0]=='a') {
if (args.length<2) return set_status('Invalid add command');
if (!fsess) {
let flag = 1<<2; //always run async
if (defer_mode) flag |= (1<<13);
LIBGPAC.init(0, null);
fsess = LIBGPAC.fs_new_defaults(flag);
set_status("Creating filter session in non-blocking mode" + (defer_mode ? ' - deferred linking' : '') );
}
if (prev_filter && defer_mode) {
LIBGPAC.filter_reconnect_output(prev_filter, null);
prev_filter=null;
}
let fdesc = args[1];
let select_start = fdesc.indexOf('$(');
let select_end = (select_start>=0) ? fdesc.indexOf(')') : 0;
if (select_end) {
let hint = fdesc.substring(select_start, select_end+1);
let fio = GFIO.create(hint, 0); //can only use this for read mode at the time being
let wrap_url = fio.gfio_url();
fdesc = fdesc.replace(hint, wrap_url);
}
const e = LIBGPAC._malloc(LIBGPAC.HEAP32.BYTES_PER_ELEMENT);
LIBGPAC.HEAP32.set([0], e/LIBGPAC.HEAP32.BYTES_PER_ELEMENT);
let f;
if (fdesc.startsWith('src=')) {
fdesc = fdesc.substring(4);
f = LIBGPAC.fs_load_source(fsess, fdesc, null, null, e);
} else if (fdesc.startsWith('dst=')) {
fdesc = fdesc.substring(4);
f = LIBGPAC.fs_load_destination(fsess, fdesc, null, null, e);
} else {
f = LIBGPAC.fs_load_filter(fsess, fdesc, e);
}
prev_filter = f;
let res = LIBGPAC.getValue(e, 'i32');
LIBGPAC._free(e);
set_status("added filter "+args[1]+ " returned " + res);
return;
}
if (args[0]=='r') {
if (!fsess) return set_status('No valid session, add a filter first');
animElement.start();
run_session();
return;
}
if (args[0]=='c') {
if (fsess) {
suspend_sess = true;
set_status("Suspending session");
}
return;
}
if (args[0]=='p') {
let idx=0;
let n;
if (!fsess) return set_status('No valid session, add a filter first');
if (!prev_filter) return set_status('No filter loaded, cannot probe');
if (args.length<2) return set_status('No name provided');
if (args.length>2) {
idx=parseInt(args[1]);
n=args[2];
} else {
n=args[1];
}
var p_str = LIBGPAC._malloc(LIBGPAC.HEAP32.BYTES_PER_ELEMENT);
var res = LIBGPAC.filter_probe_link(prev_filter, idx, n, p_str);
if (!res) {
var c_str = LIBGPAC.getValue(p_str, "i32");
var chain = LIBGPAC.UTF8ToString(c_str);
LIBGPAC.free(c_str);
set_text('resolved chain from ' + LIBGPAC.filter_get_name(prev_filter) + ' to ' + n + ' is: ' + chain);
}
LIBGPAC._free(p_str);
return set_status(res ? ('Failed'+res) : 'OK');
}
if (args[0]=='l') {
let idx=-1;
let n;
if (!fsess) return set_status('No valid session, add a filter first');
if (!prev_filter) return set_status('No filter loaded, cannot check destinations');
if (args.length>1) {
idx=parseInt(args[1]);
}
var p_str = LIBGPAC._malloc(LIBGPAC.HEAP32.BYTES_PER_ELEMENT);
var res = LIBGPAC.filter_get_destinations(prev_filter, idx, p_str);
if (!res) {
var c_str = LIBGPAC.getValue(p_str, "i32");
var chain = LIBGPAC.UTF8ToString(c_str);
LIBGPAC.free(c_str);
set_text('possible destinations for ' + LIBGPAC.filter_get_name(prev_filter) +': ' + chain);
}
LIBGPAC._free(p_str);
return set_status(res ? ('Failed'+res) : 'OK');
}
if (args[0]=='v') {
if (!fsess) return set_status('No valid session, add a filter first');
LIBGPAC.fs_print_stats(fsess);
LIBGPAC.fs_print_connections(fsess);
return;
}
if (args[0]=='i') {
if (!prev_filter) return set_status('No current fiter, add a filter first');
txt='Filter ' + LIBGPAC.filter_get_name(prev_filter) + ' PID info:\n';
let c_i = LIBGPAC.filter_get_ipid_count(prev_filter);
if (c_i) {
for (let idx=0; idx<c_i; idx++) {
let pid = LIBGPAC.filter_get_ipid(prev_filter, idx);
txt+='Input PID ' + (idx+1) + ' Properties:\n';
let props = LIBGPAC.filter_pid_get_props(pid);
txt+=JSON.stringify(props);
txt+='\n\n';
}
}
let c_o = LIBGPAC.filter_get_opid_count(prev_filter);
if (c_o) {
for (let idx=0; idx<c_o; idx++) {
let pid = LIBGPAC.filter_get_opid(prev_filter, idx);
txt+='Output PID ' + (idx+1) + ' Properties:\n';
let props = LIBGPAC.filter_pid_get_props(pid);
txt+=JSON.stringify(props);
txt+='\n\n';
}
}
if (!c_i && !c_o) txt+='No PIDs - run session';
set_text(txt);
return;
}
set_status("Unknown command "+cmd);
let help="Possible commands:\n";
help+= "- d: set defer linking mode (default: "+ defer_mode + ")\n";
help+= "- s: set number of steps before returning control to JS (default: "+ fs_steps + ")\n";
help+= "- a DESC: add filter, use src=URL for source, dst=URL for sinks. $(name) replacement rules are allowed\n";
help+= "- r: run or resume session\n";
help+= "- c: suspend session while running\n";
help+= "- v: view connections and stats\n";
help+= "\nThe following only apply to the last added filter:\n";
help+= "- i: print pid properties\n";
help+= "- p [pid_idx=0] DESC: probe resolution from pid with index pid_idx of last added filter to filter description DESC\n";
help+= "- l [pid_idx=-1]: list possible destinations for pid of index pid_idx (-1 for all pids) of last added filter\n";
help+= "\n";
set_text(help);
}
let controlElement = document.getElementById('controls');
//controlElement.hidden = is_mp4box ? true : false;
controlElement.style.display = is_mp4box ? 'none' : 'inline-block';
let abortElement = document.getElementById('abort');
abortElement.selectedIndex = 0;
let reportElement = document.getElementById('reports');
reportElement.checked = has_report;
let fsElement = document.getElementById('fullscreen');
fsElement.hidden = use_video ? false : true;
GPAC.running = true;
set_status('Running ' + (is_mp4box ? "MP4Box " : "gpac ") + cmd);
animElement.start();
if (use_video && LIBGPAC.gpac_worker) {
LIBGPAC.gpac_worker = false;
GPAC.restore_worker = true;
//cannot run SDL + main_loop in thread unless for offscreen canvas
do_log('Main video output used, disabling worker mode for this run');
}
//our own version of callMain to deal with:
//- stack save/restore missing in emscripten callMain
//- even if it where there, we may exit aynchronously and can only restore stack on main thread in gpac.on_done
function call_gpac() {
GPAC.stack = LIBGPAC.stackSave();
args.unshift(is_mp4box ? "MP4Box" : "gpac");
var argc = args.length;
var argv = LIBGPAC.stackAlloc((argc + 1) * 4);
var argv_ptr = argv >> 2;
args.forEach(arg => {
LIBGPAC.HEAP32[argv_ptr++] = LIBGPAC.allocateUTF8OnStack(arg);
});
LIBGPAC.HEAP32[argv_ptr] = 0;
try {
LIBGPAC["_main"](argc, argv);
} catch (e) {
//unwind thrown by emscripten main
if (e != 'unwind') {
GPAC.on_done();
return com_exit('Exception while running - ' + e);
}
}
};
if (will_block) {
let warn='Worker for main disabled - web page will be blocked!';
do_log(warn);
set_status(warn);
//use setTimeout to have time to display above warning...
setTimeout(call_gpac, 1);
} else {
call_gpac();
}
}
//end of command line processing
// Include ANSI escape codes convert
// @link: https://www.npmjs.com/package/ansi-html
// Reference to https://github.com/sindresorhus/ansi-regex
var _regANSI = /(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/
var _defColors = {
reset: ['fff', '000'], // [FOREGROUD_COLOR, BACKGROUND_COLOR]
black: '000',
red: 'ff0000',
green: '209805',
yellow: 'e8bf03',
blue: '0000ff',
magenta: 'ff00ff',
cyan: '00ffee',
lightgrey: 'f0f0f0',
darkgrey: '888'
}
var _styles = {
30: 'black',
31: 'red',
32: 'green',
33: 'yellow',
34: 'blue',
35: 'magenta',
36: 'cyan',
37: 'lightgrey'