pwebm 0.0.1-alpha.1 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +118 -5
  2. package/TODO.md +7 -36
  3. package/package.json +1 -1
  4. package/src/ffmpeg.ts +22 -10
package/README.md CHANGED
@@ -1,15 +1,128 @@
1
1
  # pwebm
2
2
 
3
- To install dependencies:
3
+ Utility to encode size restricted webm files with ffmpeg.
4
+
5
+ When executed multiple times, the additional encoding requests will be put inside a queue that will be handled in the first instance that was executed.
6
+
7
+ When not specified, the output file name will be the current unix timestamp (with 13 digits plus 3 random additional ones, e.g.: `1741140729397902.webm`), and saved in `~/Movies/pwebm/` (macOs) or `~/Videos/pwebm/` (all others).
8
+
9
+ # Installation
10
+
11
+ This is a CLI that makes use of [Bun](https://bun.sh/) APIs internally, so having bun installed in your system for it to work is a requirement.
12
+
13
+ The package is available in the official npm registry, so you can install it globally with:
4
14
 
5
15
  ```bash
6
- bun install
16
+ bun i -g pwebm
7
17
  ```
8
18
 
9
- To run:
19
+ Or if you prefer installing the repo directly from GitHub (with the latest commits):
10
20
 
11
21
  ```bash
12
- bun run index.ts
22
+ bun i -g git+https://github.com/4ndrs/pwebm.git
13
23
  ```
14
24
 
15
- This project was created using `bun init` in bun v1.0.0. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
25
+ >[!NOTE]
26
+ >There is no build step for this script; the source code is used and executed as is. You can check, and follow its [entry point](./pwebm) to see how it works.
27
+
28
+ ## Historical Background & Purpose
29
+
30
+ In 2022, I wrote a script for the mpv media player called [PureMPV](https://github.com/4ndrs/PureMPV) that would help extracting the currently watched video's information, like the timestamps at certain points, and the the cropping coordinates, which would then later be used for encoding videos with ffmpeg with specific parameters.
31
+
32
+ Up to that point, I mostly spent the time encoding short webm files to keep and share on some imageboards, as well as encoding some mkv files with streams and attachments copied, so I wanted to integrate this functionality in some way with PureMPV. I didn't like the idea of having PureMPV to do the encoding itself, I wanted a seperate process to handle this independently, so I could stop or start another mpv window without affecting the encoding process. I wrote down some of the initial requirements at the time, which were the following:
33
+
34
+ - Encoding webm files with size limits (first crf mode, then bitrate mode on retries)
35
+ - Having a queue for handling multiple encodings
36
+ - Log file tracking everything that is happening (I'm a sucker for these)
37
+ - Generated file names with unix timestamps
38
+
39
+ The encoding with first crf mode, and then bitrate (when failing) was my way of encoding webms, and I wanted to automate this very same process. Having a queue was essential to keep selecting multiple segments to encode without waiting for the previous one to end, this meant I could keep using mpv and then later check at the end the resulting webms. I also loved the idea of having a log file that I could track with `tail -f`. Personally, I have been using tail/multitail on my Linux boxes to track logs for the longest time, so this was hugely inspired by this. When uploading files on some imageboards, the file name generated on the server uses the unix timestamp, so I wanted to keep the same format. I use the same naming format for my screenshots as well.
40
+
41
+ Following these requirements, I wrote an early version of the script in Python named [PureWebM](https://github.com/4ndrs/PureWebM), which was a simple script that would encode size limited webm files, and would retry encoding with a lower bitrate if the limit was reached. It would also handle multiple encoding requests in a queue, and log everything that was happening in a file.
42
+
43
+ The script worked fine for me for 2 years, but maintenance and installation on new machines became a painful experience with Python. The codebase was hard to look at (it was written in my early days with python), and I strongly wanted to improve it using a more modern approach, so I decided to rewrite it from scratch in TypeScript, and this is the result.
44
+
45
+ This new version is a lot more organized, and was written with cross-platform compatibility in mind, like using named pipes on Windows instead of unix sockets, and properly handling paths with `path.join()` instead of using hard coded paths. Unfortunately at the time of writing I haven't been able to test it on Windows yet, but the foundation is there for anyone who wants to try it out.
46
+
47
+ The script was mainly written to use with [PureMPV](https://github.com/4ndrs/PureMPV) and [pwebm-helper](https://github.com/4ndrs/pwebm-helper), but it can be used independently as well, if you are comfortable with the command line.
48
+
49
+ ## Usage
50
+
51
+ [Usage Preview](https://github.com/user-attachments/assets/1800f80c-db37-4fd4-9652-3e68aeb645d5)
52
+
53
+ The script has different arguments that can be used to customize the encoding process. They are similar to ffmpeg's arguments, meaning we have `-i` for selecting inputs, `-c:v` for selecting the video codec, `-ss` for the start time, `-to` for the end time, and so on. The script supports both output seeking and input seeking with multiple inputs if needed. Here is an exhaustive list of the currently available arguments:
54
+
55
+ |Argument|Details|
56
+ |----------|------|
57
+ |-h, --help| Show help message and exit|
58
+ |-v, --version| Show version and exit|
59
+ |-kill| Terminate the running pwebm instance, if there is any|
60
+ |-status| Show the current status of the encoding process|
61
+ |-i| The input file to encode|
62
+ |-ss| The start time of the segment to encode|
63
+ |-to| The end time of the segment to encode|
64
+ |-c:v| The video codec to use. Default is **libvpx-vp9**|
65
+ |-crf| The Constant Rate Factor to use. Default is **24**|
66
+ |-lavfi| The set of filters to pass to ffmpeg|
67
+ |-deadline| The deadline passed to ffmpeg for libvpx-vp9. Default is **good**|
68
+ |-cpu-used|The cpu-used passed to ffmpeg for libvpx-vp9. Default is **0**|
69
+ |-subs| Burn the subtitles|
70
+ |-sl, --size-limit| The size limit in MiB. Default is **4**|
71
+ |--video-path| The path to save the video files. Default is **~/Movies/pwebm/** on macOs, and **~/Videos/pwebm/** on everything else|
72
+ |-ep, --extra-params| Extra parameters to pass to ffmpeg|
73
+
74
+ If the codec option `c:v` is set to `libvpx` for v8 webms, or `libvpx-vp9` for vp9 webms, the script will generate a webm with the choosen options and size limit in MiB. If the codec is set to anything else, the script will generate an mkv file with all streams copied, including the attachments, and reencode the video stream with the choosen crf; no size limitations will be applied here.
75
+
76
+ The `subs` option will only trigger on webms, burning the subtitles onto the video stream. The internal implementation of this option is just picking the first input file's subtitles, and applying the subtitle filter to the resulting output. If you need to pick subtitles in a different file, you can use the `-lavfi` option to pass the subtitles filter manually for now.
77
+
78
+ >[!NOTE]
79
+ >The `subs` option doesn't work with input seeking. If you need to seek, make sure you are using output seeking, otherwise the resulting webm will have the subtitles burned at the wrong time.
80
+
81
+ The `size-limit` option sets the limit in MiB for the resulting webm file. If the file exceeds this limit, the script will retry encoding with a lower bitrate, and will keep retrying until the limit is met. The script will also keep track of the amount of retries, and will log this information in the log file. You can use `0` to disable the limit.
82
+
83
+ The `extra-params` option is a way to pass additional parameters to ffmpeg. This is an escape hatch, and can be used to replace internal defaults. Everything is passed as is, and there is no validation by the script, so make sure you are passing valid parameters.
84
+
85
+ ### Examples
86
+ ```bash
87
+ # Encode a webm without audio, with a size limit of 4 MiB, and save it in the default video path with a random file name
88
+ pwebm -i /tmp/Videos/nijinosaki.mkv
89
+
90
+ # Encode a webm with a specific file name
91
+ pwebm -i /tmp/Videos/nijinosaki.mkv /tmp/Videos/CUTE.webm
92
+
93
+ # Encode a segment with input seeking
94
+ pwebm -ss 00:00:02.268 -to 00:00:10.310 -i /tmp/Videos/nijinosaki.mkv
95
+
96
+ # Encode a segment with output seeking and burnt subtitles
97
+ pwebm -i /tmp/Videos/nijinosaki.mkv -ss 00:00:02.268 -to 00:00:10.310 -subs
98
+
99
+ # Encode a webm with size limit of 6 MiB and audio
100
+ pwebm -i /tmp/Videos/nijinosaki.mkv --size-limit 6 --extra-params -c:a libopus -b:a 128k
101
+
102
+ # Encode an h264 mkv with crf 24 and other streams copied
103
+ pwebm -ss 00:00:02.268 -to 00:00:10.310 -i /tmp/Videos/nijinosaki.mkv -c:v libx264
104
+ ```
105
+
106
+ The script logs everything it does inside a log file located in `~/.config/pwebm/pwebm.log`, so you can check this file to see what params are used when executing ffmpeg. This file isn't currently rotated automatically in the script, so you might want to setup rotation with `logrotate` or similar.
107
+
108
+ ## Configuration File
109
+
110
+ The defaults in the script can be configured with a configuration file located in `~/.config/pwebm/config.toml`. The file is a simple TOML file with the following options:
111
+
112
+ |Key|Equivalent|
113
+ |----------|------|
114
+ |encoder| -c:v|
115
+ |crf| -crf|
116
+ |deadline| -deadline|
117
+ |cpuUsed| -cpu-used|
118
+ |subs|-subs|
119
+ |sizeLimit| --size-limit|
120
+ |videoPath| --video-path|
121
+
122
+ Example:
123
+ ```toml
124
+ crf = 28
125
+ subs = true
126
+ sizeLimit = 3
127
+ videoPath = "~/Videos/PureWebM"
128
+ ```
package/TODO.md CHANGED
@@ -1,28 +1,3 @@
1
- config, log -> there has to be a way to retrieve the config dir with env variable or some api
2
- (socket) similar to purewebm; have to be in ~/.config/pwebm/config, ~/.config/pwebm/log
3
- the socket file (if there is any) goes to /tmp
4
-
5
- videos dir -> use ~/Videos/pwebm for consistency as default, but make it changeable through
6
- the config file ASAP, way to many webms in PureWebM to move to another dir
7
-
8
- filename -> use the unix timestamp with 16 digits (performance.now() + performance.timeOrigin)
9
- the --name_type flag won't be ported
10
-
11
- flags -> -v/--version, -h/--help, --status, --kill, -i, -subs, -c:v, -ss, -to, -lavfi,
12
- --size_limit/-sl, -crf, -cpu-used, -deadline, --extra_params/-ep
13
-
14
-
15
- some considerations:
16
- - not being v1.0 permits for some leeway with breaking changes
17
- - default size limit will be increased from 3 to 4
18
- - if --status or --kill are used other flags will be ignored, consider maybe direct commands?
19
- - current purewebm needs the start/end times in the metadata of the file to work no matter what
20
- need to find a different way to get these, or at least not rely on them when they are set
21
- manually
22
- - it has to work with PureMPV (through pwebm-helper), tail log is nice but would be also nice
23
- to have some kind of keybinding on the helper to show the status of the encoding on the mpv
24
- window
25
-
26
1
  ## Stuff
27
2
 
28
3
  - [x] argument parser
@@ -43,17 +18,13 @@ some considerations:
43
18
  - [x] if input is missing after some other arg, the default parse error is shown
44
19
  - [x] warn color is messed up for the message shown when the file limit is reached because of default warn color
45
20
  - [x] implement better cleaning process before exit
46
- - [ ] add automatic releases with github actions (edge + tagged)
47
- - [ ] add bun bundled executable package releases to the automatic releases
48
- - [ ] update readme
49
- - [ ] add subs flag warning to the readme (how it works, output seeking needed, etc)
50
- - [ ] release tagged versions in npm
51
- - [ ] it's not part of this repo, but don't forget to improve the helper script for PureMPV (pwebm-helper), it has a missing readme
21
+ - [x] release tagged versions in npm
22
+ - [x] it's not part of this repo, but don't forget to improve the helper script for PureMPV (pwebm-helper), it has a missing readme
23
+ - [x] update readme
24
+ - [x] add subs flag warning to the readme (how it works, output seeking needed, etc)
52
25
 
53
- ### the following is just extra not implemented on purewebm but was its initial vision (can skip)
54
- - [ ] implement conversion logger view (save previous conversions to db with last bitrate info)
55
- - [ ] redo conversions in logger view
26
+ ### Might be nice to have
56
27
  - [ ] add limit for the amount of tries to redo a conversion
57
28
  - [ ] percentage bitrate offset when retrying a conversion with new calcs
58
-
59
- ## 2025-03-03
29
+ - [ ] handle no duration case, maybe adding an additional crf mode instead of bitrate calcs
30
+ - [ ] (helper script) add a keybinding to show the status of the encoding on the mpv window
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pwebm",
3
- "version": "0.0.1-alpha.1",
3
+ "version": "0.0.1",
4
4
  "author": "4ndrs <andres.degozaru@gmail.com>",
5
5
  "repository": {
6
6
  "type": "git",
package/src/ffmpeg.ts CHANGED
@@ -14,7 +14,7 @@ import path from "path";
14
14
 
15
15
  type Subprocess = _Subprocess<"ignore", "pipe", "pipe">;
16
16
 
17
- let stderr = "";
17
+ let stderr: string;
18
18
  let forceKilled = false;
19
19
  let passLogFile: string | undefined;
20
20
  let ffmpegProcess: Subprocess | undefined;
@@ -116,6 +116,8 @@ const encode = async (args: ArgsSchema) => {
116
116
 
117
117
  logger.info("Executing: " + cmd.join(" "));
118
118
 
119
+ stderr = "";
120
+
119
121
  const singlePassProcess = Bun.spawn({ cmd, stderr: "pipe" });
120
122
 
121
123
  ffmpegProcess = singlePassProcess;
@@ -153,13 +155,14 @@ const encode = async (args: ArgsSchema) => {
153
155
  await singlePassProcess.exited;
154
156
 
155
157
  if (ffmpegProcess.exitCode !== 0 && !forceKilled) {
158
+ logger.error("\n" + stderr);
159
+
156
160
  logger.error(
157
161
  "Error processing the single pass, ffmpeg exited with code: " +
158
162
  ffmpegProcess.exitCode,
159
163
  );
160
- logger.error(stderr);
161
164
 
162
- cleanExit(1);
165
+ await cleanExit(1);
163
166
  }
164
167
 
165
168
  if (forceKilled) {
@@ -296,6 +299,8 @@ const encode = async (args: ArgsSchema) => {
296
299
 
297
300
  logger.info("Executing: " + firstPassCmd.join(" "));
298
301
 
302
+ stderr = "";
303
+
299
304
  const firstPassProcess = Bun.spawn({ cmd: firstPassCmd, stderr: "pipe" });
300
305
 
301
306
  ffmpegProcess = firstPassProcess;
@@ -305,11 +310,16 @@ const encode = async (args: ArgsSchema) => {
305
310
  await firstPassProcess.exited;
306
311
 
307
312
  if (firstPassProcess.exitCode !== 0 && !forceKilled) {
308
- logger.error("Couldn't process first pass");
313
+ logger.error("\n" + stderr);
314
+
315
+ logger.error(
316
+ "Error processing the single pass, ffmpeg exited with code: " +
317
+ ffmpegProcess.exitCode,
318
+ );
309
319
 
310
320
  removePassLogFile();
311
321
 
312
- cleanExit(1);
322
+ await cleanExit(1);
313
323
  }
314
324
 
315
325
  if (forceKilled) {
@@ -332,6 +342,8 @@ const encode = async (args: ArgsSchema) => {
332
342
 
333
343
  logger.info("Executing: " + secondPassCmd.join(" "));
334
344
 
345
+ stderr = "";
346
+
335
347
  const secondPassProcess = Bun.spawn({ cmd: secondPassCmd, stderr: "pipe" });
336
348
 
337
349
  ffmpegProcess = secondPassProcess;
@@ -425,14 +437,14 @@ const encode = async (args: ArgsSchema) => {
425
437
  } while (failed);
426
438
 
427
439
  if (ffmpegProcess.exitCode !== 0 && !forceKilled) {
440
+ logger.error("\n" + stderr);
441
+
428
442
  logger.error(
429
443
  "Error processing the second pass, ffmpeg exited with code: " +
430
444
  ffmpegProcess.exitCode,
431
445
  );
432
446
 
433
- logger.error(stderr);
434
-
435
- cleanExit(1);
447
+ await cleanExit(1);
436
448
  }
437
449
 
438
450
  if (forceKilled) {
@@ -452,11 +464,11 @@ const encode = async (args: ArgsSchema) => {
452
464
 
453
465
  status.updateSecondPass(100);
454
466
 
455
- removePassLogFile();
456
-
457
467
  if (queueIsDone) {
458
468
  logger.info("All encodings done");
459
469
  }
470
+
471
+ removePassLogFile();
460
472
  };
461
473
 
462
474
  const processStderr = async (process: Subprocess) => {