@kmamal/media-decoders 0.0.0-stage → 0.1.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 (82) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +152 -2
  3. package/binding.gyp +138 -0
  4. package/package.json +61 -4
  5. package/scripts/build-ffmpeg.mjs +35 -0
  6. package/scripts/build.mjs +67 -0
  7. package/scripts/download-ffmpeg.mjs +25 -0
  8. package/scripts/download-release.mjs +20 -0
  9. package/scripts/install.mjs +26 -0
  10. package/scripts/util/common.js +54 -0
  11. package/src/javascript/audio-reader.js +121 -0
  12. package/src/javascript/byte-source.js +144 -0
  13. package/src/javascript/common.js +44 -0
  14. package/src/javascript/decode.js +272 -0
  15. package/src/javascript/events.js +80 -0
  16. package/src/javascript/feed.js +451 -0
  17. package/src/javascript/index.js +23 -0
  18. package/src/javascript/media-file.js +270 -0
  19. package/src/javascript/track-reader.js +45 -0
  20. package/src/javascript/video-reader.js +93 -0
  21. package/src/native/audio-feed-reader-core.cpp +322 -0
  22. package/src/native/audio-feed-reader-core.h +50 -0
  23. package/src/native/audio-feed-reader.cpp +166 -0
  24. package/src/native/audio-feed-reader.h +29 -0
  25. package/src/native/audio-feed-writer.cpp +364 -0
  26. package/src/native/audio-feed-writer.h +63 -0
  27. package/src/native/audio-feed.cpp +44 -0
  28. package/src/native/audio-feed.h +83 -0
  29. package/src/native/audio-pipeline.cpp +141 -0
  30. package/src/native/audio-pipeline.h +52 -0
  31. package/src/native/audio-track.cpp +236 -0
  32. package/src/native/audio-track.h +65 -0
  33. package/src/native/audio-trim.cpp +53 -0
  34. package/src/native/audio-trim.h +26 -0
  35. package/src/native/byte-source-state.h +48 -0
  36. package/src/native/byte-source.cpp +339 -0
  37. package/src/native/byte-source.h +35 -0
  38. package/src/native/codec.cpp +63 -0
  39. package/src/native/codec.h +36 -0
  40. package/src/native/env-registry.h +40 -0
  41. package/src/native/feed-binding.cpp +62 -0
  42. package/src/native/feed-binding.h +14 -0
  43. package/src/native/feed-link.cpp +89 -0
  44. package/src/native/feed-link.h +68 -0
  45. package/src/native/feed-reader-base.h +145 -0
  46. package/src/native/feed-reader-core-base.h +84 -0
  47. package/src/native/feed.cpp +146 -0
  48. package/src/native/feed.h +152 -0
  49. package/src/native/ffmpeg.h +34 -0
  50. package/src/native/file-binding.cpp +265 -0
  51. package/src/native/file-core.cpp +875 -0
  52. package/src/native/file-core.h +219 -0
  53. package/src/native/file-info.cpp +88 -0
  54. package/src/native/file-info.h +47 -0
  55. package/src/native/file.h +40 -0
  56. package/src/native/log-capture.cpp +46 -0
  57. package/src/native/log-capture.h +27 -0
  58. package/src/native/media-input.cpp +116 -0
  59. package/src/native/media-input.h +38 -0
  60. package/src/native/module.cpp +114 -0
  61. package/src/native/packet-decoder.cpp +216 -0
  62. package/src/native/packet-decoder.h +84 -0
  63. package/src/native/resampler.cpp +56 -0
  64. package/src/native/resampler.h +22 -0
  65. package/src/native/silent-track.cpp +23 -0
  66. package/src/native/silent-track.h +33 -0
  67. package/src/native/time-epsilon.h +6 -0
  68. package/src/native/track.cpp +117 -0
  69. package/src/native/track.h +142 -0
  70. package/src/native/video-feed-reader-core.cpp +164 -0
  71. package/src/native/video-feed-reader-core.h +47 -0
  72. package/src/native/video-feed-reader.cpp +132 -0
  73. package/src/native/video-feed-reader.h +33 -0
  74. package/src/native/video-feed-writer.cpp +214 -0
  75. package/src/native/video-feed-writer.h +44 -0
  76. package/src/native/video-feed.cpp +69 -0
  77. package/src/native/video-feed.h +78 -0
  78. package/src/native/video-output.cpp +245 -0
  79. package/src/native/video-output.h +68 -0
  80. package/src/native/video-track.cpp +453 -0
  81. package/src/native/video-track.h +107 -0
  82. package/src/types/index.d.ts +425 -0
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2021 Konstantin M
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,153 @@
1
- # Temporary Holding Version
1
+ # @kmamal/media-decoders
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Audio and video decoding for Node.js via [FFmpeg](https://ffmpeg.org/).
4
+
5
+ Supports these formats (but read also about [patented codecs](#patented-codecs)):
6
+
7
+ - **Containers**: mp4/mov/m4a, webm/mkv, ogg, wav, aiff, mp3, flac, aac (ADTS)
8
+ - **Video**: AV1 (dav1d), VP8, VP9, Theora, H.264, HEVC
9
+ - **Audio**: Opus, Vorbis, FLAC, MP3, AAC, PCM (8 to 64 bit, integer and float, A-law, µ-law)
10
+
11
+ This package officially supports Linux, Mac, and Windows.
12
+ Prebuilt binaries exist for x64 and arm architectures on all supported platforms.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ npm install @kmamal/media-decoders
18
+ ```
19
+
20
+ Future versions of npm will require you to approve scripts before they run. Approve this package's script with:
21
+
22
+ ```bash
23
+ npm install-scripts approve @kmamal/media-decoders
24
+ ```
25
+
26
+ ## Examples
27
+
28
+ ### Audio (using decodeAudio)
29
+
30
+ ```js
31
+ const decoders = require('@kmamal/media-decoders')
32
+
33
+ const clip = await decoders.decodeAudio('song.ogg', { sampleRate: 48000, start: 10, end: 15 })
34
+ console.log(clip.sampleRate, clip.channels.length, clip.channels[0].length)
35
+ // Prints `48000 2 240000`
36
+ // Assumes that `song.ogg` is stereo and at least 15 seconds long.
37
+ ```
38
+
39
+ ### Video (using decodeFrame and decodeVideo)
40
+
41
+ ```js
42
+ const decoders = require('@kmamal/media-decoders')
43
+
44
+ const poster = await decoders.decodeFrame('movie.webm', 0)
45
+ console.log(poster.width, poster.height, poster.timestamp, poster.data.length) // 1280 720 0 3686400
46
+
47
+ for await (const frame of decoders.decodeVideo('movie.webm', { start: 10, end: 15 })) {
48
+ console.log(frame.width, frame.height, frame.timestamp, frame.data.length)
49
+ // Prints `1280 720 10 3686400` for the first frame. 150 frames in total. The next has timestamp 10.0333…
50
+ // Assumes that `movie.webm` is 1280×720, 30 frames per second, and at least 15 seconds long.
51
+ }
52
+ ```
53
+
54
+ ### Audio (using AudioReader)
55
+
56
+ ```js
57
+ const decoders = require('@kmamal/media-decoders')
58
+
59
+ const file = await decoders.open('song.ogg')
60
+ const audio = file.tracks.find((track) => track.type === 'audio')
61
+ const reader = audio.createReader({ sampleRate: 48000 })
62
+
63
+ let block
64
+ while ((block = await reader.readChannels(4096))) {
65
+ console.log(block.timestamp, block.frames, block.channels.length)
66
+ // Prints `0 4096 2` for the first block. The last one may have fewer frames.
67
+ // Assumes that `song.ogg` is stereo, starts at time 0, and is longer than 4096 samples at 48 kHz.
68
+ }
69
+ file.close()
70
+ ```
71
+
72
+ ### Video (using VideoReader)
73
+
74
+ ```js
75
+ const decoders = require('@kmamal/media-decoders')
76
+
77
+ const file = await decoders.open('movie.webm')
78
+ const video = file.tracks.find((track) => track.type === 'video')
79
+ const reader = video.createReader({ format: 'rgba', frames: 4 })
80
+
81
+ let frame
82
+ while ((frame = await reader.read())) {
83
+ console.log(frame.width, frame.height, frame.timestamp, frame.data.length)
84
+ // Prints `1280 720 0 3686400` for the first frame. The next has timestamp 0.0333…
85
+ // Assumes that `movie.webm` is 1280×720, 30 frames per second, and starts at time 0.
86
+ reader.release(frame) // Otherwise the reader stalls once all 4 frames are held
87
+ }
88
+ file.close()
89
+ ```
90
+
91
+ ### Audio and video together (streamed over the network)
92
+
93
+ ```js
94
+ const decoders = require('@kmamal/media-decoders')
95
+
96
+ const response = await fetch('https://example.com/movie.webm')
97
+ const source = decoders.createByteSource()
98
+ const opening = decoders.open(source)
99
+
100
+ const download = async () => {
101
+ let offset = 0
102
+ for await (const chunk of response.body) {
103
+ if (source.closed) { break }
104
+ if (!source.push(offset, chunk)) { await source.drain() }
105
+ offset += chunk.byteLength
106
+ }
107
+ if (!source.closed) { source.end() }
108
+ }
109
+ const downloading = download() // Runs alongside the decoding
110
+
111
+ const file = await opening
112
+ const audio = file.tracks.find((track) => track.type === 'audio').createReader({ sampleRate: 48000 })
113
+ const video = file.tracks.find((track) => track.type === 'video').createReader({ format: 'rgba' })
114
+
115
+ const readAudio = async () => {
116
+ let block
117
+ while ((block = await audio.readChannels(4800))) {
118
+ console.log('audio', block.timestamp, block.frames)
119
+ }
120
+ }
121
+
122
+ const readVideo = async () => {
123
+ let frame
124
+ while ((frame = await video.read())) {
125
+ console.log('video', frame.timestamp, frame.width, frame.height)
126
+ video.release(frame)
127
+ }
128
+ }
129
+
130
+ // Read both tracks together, so that neither holds up the other
131
+ await Promise.all([ downloading, readAudio(), readVideo() ])
132
+ file.close()
133
+ ```
134
+
135
+ ## Documentation
136
+
137
+ The full [API Reference](https://github.com/kmamal/media-decoders/tree/main/docs/api-reference.md) documents every function.
138
+
139
+ ## Patented codecs
140
+
141
+ H.264, HEVC and AAC are covered by patents. They are included in the default installation for convenience.
142
+ If you are building something that you don't plan to share with others then you'll be fine.
143
+ But if you are planning to distribute an application that uses these patented codecs then you will have to license them.
144
+ This is entirely your responsibility and not covered here.
145
+
146
+ If you don't actually need these codecs, and you still want to distribute your software, then you have the option of only bundling the patent-free codecs in your application. This project uses FFMpeg binaries downloaded from the releases of the [build-ffmpeg](https://github.com/kmamal/build-ffmpeg) project. Each release includes two versions of each binary:
147
+
148
+ - The `full` version of the binary includes the patented codecs.
149
+ - The `free` version of the binary doesn't.
150
+
151
+ The `full` binaries are downloaded by default into this package's `dist/` folder. You can replace them with the `free` binaries right before shipping. The best place to do this is as an extra step in you packaging process.
152
+
153
+ Regardless what version of the binaries you download, this package functions the same way. The only observable difference is that the value of `availableCodecs` will be different.
package/binding.gyp ADDED
@@ -0,0 +1,138 @@
1
+ {
2
+ 'variables': {
3
+ 'werror%': 0,
4
+ 'sanitize%': '',
5
+ },
6
+ 'targets': [
7
+ {
8
+ 'target_name': 'media_decoders',
9
+ 'sources': [
10
+ 'src/native/module.cpp',
11
+ 'src/native/byte-source.cpp',
12
+ 'src/native/file-core.cpp',
13
+ 'src/native/file-binding.cpp',
14
+ 'src/native/file-info.cpp',
15
+ 'src/native/log-capture.cpp',
16
+ 'src/native/codec.cpp',
17
+ 'src/native/packet-decoder.cpp',
18
+ 'src/native/track.cpp',
19
+ 'src/native/video-track.cpp',
20
+ 'src/native/audio-track.cpp',
21
+ 'src/native/silent-track.cpp',
22
+ 'src/native/audio-pipeline.cpp',
23
+ 'src/native/video-output.cpp',
24
+ 'src/native/feed-link.cpp',
25
+ 'src/native/audio-feed-writer.cpp',
26
+ 'src/native/feed.cpp',
27
+ 'src/native/feed-binding.cpp',
28
+ 'src/native/audio-feed.cpp',
29
+ 'src/native/audio-feed-reader-core.cpp',
30
+ 'src/native/audio-feed-reader.cpp',
31
+ 'src/native/video-feed.cpp',
32
+ 'src/native/video-feed-writer.cpp',
33
+ 'src/native/video-feed-reader-core.cpp',
34
+ 'src/native/video-feed-reader.cpp',
35
+ 'src/native/media-input.cpp',
36
+ 'src/native/resampler.cpp',
37
+ 'src/native/audio-trim.cpp',
38
+ ],
39
+ 'dependencies': [
40
+ "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
41
+ ],
42
+ 'defines': [
43
+ # Node-API 9, which every supported Node.js (v22.16.0 and later) has
44
+ 'NAPI_VERSION=9',
45
+ 'NODE_ADDON_API_DISABLE_DEPRECATED',
46
+ 'NODE_API_SWALLOW_UNTHROWABLE_EXCEPTIONS',
47
+ ],
48
+ 'cflags': ['-Wall', '-Wextra'],
49
+ 'conditions': [
50
+ [
51
+ 'werror == 1', {
52
+ 'cflags': ['-Werror'],
53
+ 'xcode_settings': {
54
+ 'GCC_TREAT_WARNINGS_AS_ERRORS': 'YES',
55
+ },
56
+ 'msvs_settings': {
57
+ 'VCCLCompilerTool': {
58
+ 'WarnAsError': 'true',
59
+ },
60
+ },
61
+ }
62
+ ],
63
+ [
64
+ 'sanitize != ""', {
65
+ 'cflags': ['-fsanitize=<(sanitize)', '-fno-omit-frame-pointer', '-g'],
66
+ 'ldflags': ['-fsanitize=<(sanitize)'],
67
+ 'xcode_settings': {
68
+ 'OTHER_CFLAGS': ['-fsanitize=<(sanitize)', '-fno-omit-frame-pointer', '-g'],
69
+ 'OTHER_LDFLAGS': ['-fsanitize=<(sanitize)'],
70
+ },
71
+ }
72
+ ],
73
+ [
74
+ 'sanitize == "thread" and OS != "mac" and OS != "win"', {
75
+ 'cflags': ['-Wno-tsan'],
76
+ }
77
+ ],
78
+ [
79
+ 'OS == "linux" or OS == "freebsd" or OS == "openbsd" or OS == "netbsd"', {
80
+ 'cflags_cc': ['-std=c++17'],
81
+ 'include_dirs': ['$(FFMPEG_INC)'],
82
+ 'libraries': [
83
+ '-L$(FFMPEG_LIB)',
84
+ '-lavformat',
85
+ '-lavcodec',
86
+ '-lswscale',
87
+ '-lswresample',
88
+ '-lavutil',
89
+ ],
90
+ 'link_settings': {
91
+ 'libraries': ["-Wl,-rpath,'$$ORIGIN'"],
92
+ },
93
+ }
94
+ ],
95
+ [
96
+ 'OS == "mac"', {
97
+ 'xcode_settings': {
98
+ 'OTHER_CFLAGS': ['-std=c++17'],
99
+ 'WARNING_CFLAGS': ['-Wall', '-Wextra'],
100
+ 'MACOSX_DEPLOYMENT_TARGET': '11.0',
101
+ },
102
+ 'include_dirs': ['$(FFMPEG_INC)'],
103
+ 'libraries': [
104
+ '-L$(FFMPEG_LIB)',
105
+ '-lavformat',
106
+ '-lavcodec',
107
+ '-lswscale',
108
+ '-lswresample',
109
+ '-lavutil',
110
+ ],
111
+ 'link_settings': {
112
+ 'libraries': ['-Wl,-rpath,@loader_path'],
113
+ },
114
+ }
115
+ ],
116
+ [
117
+ 'OS == "win"', {
118
+ 'msvs_settings': {
119
+ 'VCCLCompilerTool': {
120
+ 'AdditionalOptions': ['-std:c++17'],
121
+ 'WarningLevel': '4',
122
+ 'DisableSpecificWarnings': ['4127', '4244'],
123
+ },
124
+ },
125
+ 'include_dirs': ['<!(echo %FFMPEG_INC%)'],
126
+ 'libraries': [
127
+ '-l<!(echo %FFMPEG_LIB%)\\avformat.lib',
128
+ '-l<!(echo %FFMPEG_LIB%)\\avcodec.lib',
129
+ '-l<!(echo %FFMPEG_LIB%)\\swscale.lib',
130
+ '-l<!(echo %FFMPEG_LIB%)\\swresample.lib',
131
+ '-l<!(echo %FFMPEG_LIB%)\\avutil.lib',
132
+ ],
133
+ }
134
+ ],
135
+ ],
136
+ }
137
+ ],
138
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
+ "version": "0.1.1",
2
3
  "name": "@kmamal/media-decoders",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "description": "Audio and video decoding for Node.js through FFmpeg",
5
+ "keywords": [
6
+ "ffmpeg",
7
+ "video",
8
+ "audio",
9
+ "decoder",
10
+ "decoding",
11
+ "media",
12
+ "mp4",
13
+ "webm",
14
+ "av1",
15
+ "vp9",
16
+ "h264",
17
+ "opus"
18
+ ],
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+ssh://git@github.com/kmamal/media-decoders.git"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.16.0"
26
+ },
27
+ "main": "./src/javascript/index.js",
28
+ "types": "./src/types/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./src/types/index.d.ts",
32
+ "default": "./src/javascript/index.js"
33
+ }
34
+ },
35
+ "gypfile": true,
36
+ "scripts": {
37
+ "test": "npx @kmamal/testing",
38
+ "test-native": "cd scripts && node test-native.mjs",
39
+ "install": "cd scripts && node install.mjs",
40
+ "download-release": "cd scripts && node download-release.mjs",
41
+ "download-ffmpeg": "cd scripts && node download-ffmpeg.mjs",
42
+ "build": "cd scripts && node build.mjs",
43
+ "upload-release": "cd scripts && node upload-release.mjs",
44
+ "release": "cd scripts && node release.mjs",
45
+ "clean": "cd scripts && node clean.mjs",
46
+ "generate-fixtures": "cd scripts && node generate-fixtures.mjs"
47
+ },
48
+ "devDependencies": {
49
+ "@kmamal/testing": "0.0.34",
50
+ "node-addon-api": "8.9.2",
51
+ "node-gyp": "13.1.0"
52
+ },
53
+ "config": {
54
+ "ffmpeg": {
55
+ "owner": "kmamal",
56
+ "repo": "build-ffmpeg",
57
+ "version": "9.0.2"
58
+ }
59
+ },
60
+ "dependencies": {
61
+ "modern-tar": "0.8.6"
62
+ }
63
+ }
@@ -0,0 +1,35 @@
1
+ import Fs from 'node:fs'
2
+ import Path from 'node:path'
3
+ import Zlib from 'node:zlib'
4
+ import Stream from 'node:stream'
5
+ import { pathToFileURL } from 'node:url'
6
+ import C from './util/common.js'
7
+ import { unpackTar } from 'modern-tar/fs'
8
+
9
+ const url = `https://github.com/${C.ffmpeg.owner}/${C.ffmpeg.repo}/archive/refs/tags/v${C.ffmpeg.version}.tar.gz`
10
+
11
+ console.log("fetch", url)
12
+ const response = await fetch(url)
13
+ if (!response.ok) { throw new Error(`bad status code ${response.status}`) }
14
+
15
+ console.log("unpack to", C.dir.ffmpeg)
16
+ await Fs.promises.rm(C.dir.ffmpeg, { recursive: true }).catch(() => {})
17
+ await Fs.promises.mkdir(C.dir.ffmpeg, { recursive: true })
18
+ await Stream.promises.pipeline(
19
+ Stream.Readable.fromWeb(response.body),
20
+ Zlib.createGunzip(),
21
+ unpackTar(C.dir.ffmpeg),
22
+ )
23
+
24
+ const ffmpegRoot = Path.join(C.dir.ffmpeg, `${C.ffmpeg.repo}-${C.ffmpeg.version}`)
25
+ await import(pathToFileURL(Path.join(ffmpegRoot, 'scripts/build.mjs')).href)
26
+ await Promise.all(C.ffmpeg.variants.map(async (variant) => {
27
+ await Fs.promises.cp(
28
+ Path.join(ffmpegRoot, 'dist', variant),
29
+ Path.join(C.dir.ffmpeg, variant),
30
+ {
31
+ recursive: true,
32
+ verbatimSymlinks: true,
33
+ },
34
+ )
35
+ }))
@@ -0,0 +1,67 @@
1
+ import Fs from 'node:fs'
2
+ import Path from 'node:path'
3
+ import { execSync } from 'node:child_process'
4
+ import C from './util/common.js'
5
+
6
+ await Promise.all([
7
+ C.dir.build,
8
+ C.dir.dist,
9
+ C.dir.publish,
10
+ ].map(async (dir) => {
11
+ await Fs.promises.rm(dir, { recursive: true }).catch(() => {})
12
+ }))
13
+
14
+ const ffmpegDir = Path.join(C.dir.ffmpeg, 'full')
15
+ const FFMPEG_INC = Path.join(ffmpegDir, 'include')
16
+ const FFMPEG_LIB = Path.join(ffmpegDir, 'lib')
17
+
18
+ console.log("build in", C.dir.build)
19
+
20
+ const werror = C.isSet(process.env.MEDIA_DECODERS_WERROR ?? '1') ? 1 : 0
21
+
22
+ const sanitize = process.env.MEDIA_DECODERS_SANITIZE ?? ''
23
+ if (![ '', 'address', 'thread' ].includes(sanitize)) {
24
+ throw new Error(`MEDIA_DECODERS_SANITIZE must be 'address' or 'thread', not '${sanitize}'`)
25
+ }
26
+
27
+ let archFlag = ''
28
+ if (process.env.CROSS_COMPILE_ARCH) {
29
+ archFlag = `--arch ${process.env.CROSS_COMPILE_ARCH}`
30
+ }
31
+
32
+ process.chdir(C.dir.root)
33
+ execSync(`npx -y node-gyp rebuild ${archFlag} -j max --verbose -- -Dwerror=${werror} -Dsanitize=${sanitize}`, {
34
+ stdio: 'inherit',
35
+ env: {
36
+ ...process.env,
37
+ FFMPEG_INC,
38
+ FFMPEG_LIB,
39
+ },
40
+ })
41
+
42
+ console.log("install to", C.dir.dist)
43
+ await Fs.promises.rm(C.dir.dist, { recursive: true }).catch(() => {})
44
+ await Fs.promises.mkdir(C.dir.dist, { recursive: true })
45
+ await Fs.promises.cp(
46
+ Path.join(C.dir.build, 'Release/media_decoders.node'),
47
+ Path.join(C.dir.dist, 'media_decoders.node'),
48
+ )
49
+
50
+ const copyFfmpeg = async (srcDir) => {
51
+ const names = await Fs.promises.readdir(srcDir)
52
+ await Promise.all(names.map(async (name) => {
53
+ if (!C.isFfmpegFile(name)) { return }
54
+ await Fs.promises.cp(
55
+ Path.join(srcDir, name),
56
+ Path.join(C.dir.dist, name),
57
+ { verbatimSymlinks: true },
58
+ )
59
+ }))
60
+ }
61
+ await copyFfmpeg(ffmpegDir)
62
+ await copyFfmpeg(FFMPEG_LIB)
63
+
64
+ // Strip binaries on linux
65
+ if (C.platform === 'linux' && !sanitize) {
66
+ execSync(`strip -s "${Path.join(C.dir.dist, 'media_decoders.node')}"`)
67
+ }
@@ -0,0 +1,25 @@
1
+ import Fs from 'node:fs'
2
+ import Path from 'node:path'
3
+ import Zlib from 'node:zlib'
4
+ import Stream from 'node:stream'
5
+ import C from './util/common.js'
6
+ import { unpackTar } from 'modern-tar/fs'
7
+
8
+ await Fs.promises.rm(C.dir.ffmpeg, { recursive: true }).catch(() => {})
9
+
10
+ await Promise.all(C.ffmpeg.variants.map(async (variant) => {
11
+ const url = `https://github.com/${C.ffmpeg.owner}/${C.ffmpeg.repo}/releases/download/v${C.ffmpeg.version}/${C.ffmpeg.assetName(variant)}`
12
+
13
+ console.log("fetch", url)
14
+ const response = await fetch(url)
15
+ if (!response.ok) { throw new Error(`bad status code ${response.status}`) }
16
+
17
+ const dirPath = Path.join(C.dir.ffmpeg, variant)
18
+ console.log("unpack to", dirPath)
19
+ await Fs.promises.mkdir(dirPath, { recursive: true })
20
+ await Stream.promises.pipeline(
21
+ Stream.Readable.fromWeb(response.body),
22
+ Zlib.createGunzip(),
23
+ unpackTar(dirPath),
24
+ )
25
+ }))
@@ -0,0 +1,20 @@
1
+ import Fs from 'node:fs'
2
+ import Zlib from 'node:zlib'
3
+ import Stream from 'node:stream'
4
+ import C from './util/common.js'
5
+ import { unpackTar } from 'modern-tar/fs'
6
+
7
+ const url = `https://github.com/${C.owner}/${C.repo}/releases/download/v${C.version}/${C.assetName}`
8
+
9
+ console.log("fetch", url)
10
+ const response = await fetch(url)
11
+ if (!response.ok) { throw new Error(`bad status code ${response.status}`) }
12
+
13
+ console.log("unpack to", C.dir.dist)
14
+ await Fs.promises.rm(C.dir.dist, { recursive: true }).catch(() => {})
15
+ await Fs.promises.mkdir(C.dir.dist, { recursive: true })
16
+ await Stream.promises.pipeline(
17
+ Stream.Readable.fromWeb(response.body),
18
+ Zlib.createGunzip(),
19
+ unpackTar(C.dir.dist),
20
+ )
@@ -0,0 +1,26 @@
1
+ import C from './util/common.js'
2
+
3
+ process.env.MEDIA_DECODERS_WERROR ??= '0'
4
+
5
+ if (!C.fromSource) {
6
+ try {
7
+ await import('./download-release.mjs')
8
+ process.exit(0)
9
+ }
10
+ catch (error) {
11
+ console.log("failed to download release:", error.cause?.message ?? error.message)
12
+ }
13
+ }
14
+ else {
15
+ console.log("skip download and build from source")
16
+ }
17
+
18
+ try {
19
+ await import('./download-ffmpeg.mjs')
20
+ }
21
+ catch (error) {
22
+ console.log("failed to download ffmpeg:", error.cause?.message ?? error.message)
23
+ await import('./build-ffmpeg.mjs')
24
+ }
25
+
26
+ await import('./build.mjs')
@@ -0,0 +1,54 @@
1
+ const Fs = require('node:fs')
2
+ const Path = require('node:path')
3
+
4
+ const dir = {}
5
+ dir.root = Path.join(__dirname, '../..')
6
+ dir.ffmpeg = Path.join(dir.root, 'ffmpeg')
7
+ dir.build = Path.join(dir.root, 'build')
8
+ dir.dist = Path.join(dir.root, 'dist')
9
+ dir.publish = Path.join(dir.root, 'publish')
10
+
11
+ const pkgPath = Path.join(dir.root, 'package.json')
12
+ const pkg = JSON.parse(Fs.readFileSync(pkgPath).toString())
13
+ const version = pkg.version
14
+ const isPrerelease = version.includes('-')
15
+ const [ , owner, repo ] = pkg.repository.url.match(/([^/:]+)\/([^/]+)\.git$/u)
16
+
17
+ const isSet = (value) => ![ undefined, '', '0', 'false' ].includes(value)
18
+ const fromSource = isSet(process.env.MEDIA_DECODERS_FROM_SOURCE)
19
+
20
+ const { platform, arch } = process
21
+ const targetArch = process.env.CROSS_COMPILE_ARCH || arch
22
+ const assetName = `media_decoders.node-v${version}-${platform}-${targetArch}.tar.gz`
23
+ const freeAssetName = `ffmpeg-free-v${version}-${platform}-${targetArch}.tar.gz`
24
+
25
+ const ffmpeg = pkg.config.ffmpeg
26
+ ffmpeg.variants = [ 'full', 'free' ]
27
+ ffmpeg.assetName = (variant) => `FFmpeg-v${ffmpeg.version}-${variant}-${platform}-${targetArch}.tar.gz`
28
+
29
+ const isFfmpegFile = (name) => {
30
+ if (name.endsWith('.md') || name.startsWith('COPYING')) { return true }
31
+ switch (platform) {
32
+ case 'linux': return name.includes('.so')
33
+ case 'darwin': return name.endsWith('.dylib')
34
+ case 'win32': return name.endsWith('.dll')
35
+ default: return false
36
+ }
37
+ }
38
+
39
+ module.exports = {
40
+ dir,
41
+ isSet,
42
+ fromSource,
43
+ version,
44
+ isPrerelease,
45
+ owner,
46
+ repo,
47
+ platform,
48
+ arch,
49
+ targetArch,
50
+ assetName,
51
+ freeAssetName,
52
+ ffmpeg,
53
+ isFfmpegFile,
54
+ }