@hiroosy/baileys-lite 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.
- package/README.md +25 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +115856 -0
- package/engine-requirements.js +11 -0
- package/package.json +27 -0
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +649 -0
- package/src/constants.js +143 -0
- package/src/defaults.js +102 -0
- package/src/foundation/audio-duration.js +530 -0
- package/src/foundation/audio-samples.js +268 -0
- package/src/foundation/boom.js +46 -0
- package/src/foundation/cache.js +142 -0
- package/src/foundation/concurrency.js +87 -0
- package/src/foundation/curve25519.js +221 -0
- package/src/foundation/link-preview.js +320 -0
- package/src/foundation/logger.js +69 -0
- package/src/foundation/long.js +140 -0
- package/src/foundation/protobuf-minimal.js +619 -0
- package/src/foundation/wa-crypto.js +76 -0
- package/src/foundation/zip.js +124 -0
- package/src/index.js +48 -0
- package/src/signal/libsignal.js +1051 -0
- package/src/signal/signal-group.js +487 -0
- package/src/signal/signal-repository.js +646 -0
- package/src/socket/business-communities.js +830 -0
- package/src/socket/chats.js +674 -0
- package/src/socket/groups-newsletter.js +342 -0
- package/src/socket/messages-recv.js +1835 -0
- package/src/socket/messages-send.js +1202 -0
- package/src/socket/socket-core.js +833 -0
- package/src/socket/usync.js +291 -0
- package/src/socket-client/websocket-client.js +124 -0
- package/src/utils/auth-state-core.js +764 -0
- package/src/utils/auth-state-storage.js +316 -0
- package/src/utils/chat-sync.js +1045 -0
- package/src/utils/media.js +841 -0
- package/src/utils/message-compose.js +1609 -0
- package/src/utils/message-processing.js +958 -0
- package/src/utils/wa-protocol-core.js +1283 -0
- package/src/vendor/jpeg-js/LICENSE +25 -0
- package/src/vendor/jpeg-js/decoder.js +1152 -0
- package/src/vendor/jpeg-js/encoder.js +824 -0
- package/src/vendor/pngjs/LICENSE +20 -0
- package/src/vendor/pngjs/bitmapper.js +273 -0
- package/src/vendor/pngjs/bitpacker.js +167 -0
- package/src/vendor/pngjs/constants.js +38 -0
- package/src/vendor/pngjs/crc.js +47 -0
- package/src/vendor/pngjs/filter-pack.js +179 -0
- package/src/vendor/pngjs/filter-parse-sync.js +27 -0
- package/src/vendor/pngjs/filter-parse.js +185 -0
- package/src/vendor/pngjs/format-normaliser.js +101 -0
- package/src/vendor/pngjs/interlace.js +101 -0
- package/src/vendor/pngjs/packer-sync.js +65 -0
- package/src/vendor/pngjs/packer.js +138 -0
- package/src/vendor/pngjs/paeth-predictor.js +22 -0
- package/src/vendor/pngjs/parser-sync.js +121 -0
- package/src/vendor/pngjs/parser.js +299 -0
- package/src/vendor/pngjs/png-sync.js +19 -0
- package/src/vendor/pngjs/sync-inflate.js +174 -0
- package/src/vendor/pngjs/sync-reader.js +54 -0
- package/src/wam/wam-constants.js +22853 -0
- package/src/wam/wam.js +151 -0
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Native audio duration reader (seconds) — replaces `music-metadata` for the one thing lite used it for:
|
|
3
|
+
* `metadata.format.duration`.
|
|
4
|
+
*
|
|
5
|
+
* Supported containers (formulas mirror music-metadata 11.x):
|
|
6
|
+
* Ogg Opus (granule(last page) - preSkip) / 48000
|
|
7
|
+
* Ogg Vorbis granule(last page) / sampleRate
|
|
8
|
+
* WAV (fact.dwSampleLength | dataSize/blockAlign) / sampleRate (data chunk clamped to file size)
|
|
9
|
+
* FLAC STREAMINFO.totalSamples / sampleRate
|
|
10
|
+
* MP4/M4A first audio track mdhd.duration / mdhd.timeScale (+ fragmented mp4, mvhd not used)
|
|
11
|
+
* MP3 / ADTS Xing/Info frame count, CBR from file size, or full frame scan
|
|
12
|
+
* AIFF / AIFF-C COMM.numSampleFrames / sampleRate (80-bit float)
|
|
13
|
+
* Matroska / WebM Segment > Info > Duration x TimecodeScale
|
|
14
|
+
* AMR-NB / AMR-WB frame count x 20 ms
|
|
15
|
+
*
|
|
16
|
+
* Returns `undefined` when the duration cannot be determined with confidence (unknown container, truncated
|
|
17
|
+
* header, ...) — callers may then fall back to something else. It never guesses.
|
|
18
|
+
*/
|
|
19
|
+
import { createReadStream } from 'node:fs'
|
|
20
|
+
import { open, stat } from 'node:fs/promises'
|
|
21
|
+
|
|
22
|
+
/* ------------------------------ helpers ------------------------------ */
|
|
23
|
+
|
|
24
|
+
const u32be = (b, o) => b.readUInt32BE(o)
|
|
25
|
+
const u64be = (b, o) => Number(b.readBigUInt64BE(o))
|
|
26
|
+
const ascii = (b, o, n) => b.toString('latin1', o, o + n)
|
|
27
|
+
|
|
28
|
+
/* ------------------------------ Ogg ------------------------------ */
|
|
29
|
+
|
|
30
|
+
const oggDuration = buf => {
|
|
31
|
+
// Mirrors music-metadata's OggParser: pages are read in order; a stream's `lastPageHeader` is recorded when
|
|
32
|
+
// its page header is parsed (BEFORE the page body is read), so a file cut inside a page body still records
|
|
33
|
+
// that page's granule. `endOfStream` is true only when reading threw EndOfStream (file cut mid-header/body).
|
|
34
|
+
const streams = new Map()
|
|
35
|
+
let pos = 0
|
|
36
|
+
let endOfStream = false
|
|
37
|
+
while (true) {
|
|
38
|
+
if (pos + 27 > buf.length) {
|
|
39
|
+
// PageHeader needs 27 bytes; if there is nothing left at all this is a clean end, otherwise a cut header
|
|
40
|
+
if (pos < buf.length) endOfStream = true
|
|
41
|
+
else endOfStream = true // readToken at EOF also throws EndOfStream in music-metadata
|
|
42
|
+
break
|
|
43
|
+
}
|
|
44
|
+
if (ascii(buf, pos, 4) !== 'OggS') break // OggContentError -> warning; not an end-of-stream
|
|
45
|
+
const headerType = buf[pos + 5]
|
|
46
|
+
const granule = buf.readBigInt64LE(pos + 6)
|
|
47
|
+
const serial = buf.readUInt32LE(pos + 14)
|
|
48
|
+
const nseg = buf[pos + 26]
|
|
49
|
+
let s = streams.get(serial)
|
|
50
|
+
if (!s) {
|
|
51
|
+
s = { codec: undefined, sampleRate: undefined, preSkip: 0, last: undefined, closed: false, pageNumber: 0, fullPages: 0, pageCount: 0 }
|
|
52
|
+
streams.set(serial, s)
|
|
53
|
+
}
|
|
54
|
+
s.pageNumber = buf.readUInt32LE(pos + 18)
|
|
55
|
+
if (pos + 27 + nseg > buf.length) {
|
|
56
|
+
endOfStream = true // SegmentTable read hits EOF; lastPageHeader is NOT yet updated for this page
|
|
57
|
+
break
|
|
58
|
+
}
|
|
59
|
+
let dataLen = 0
|
|
60
|
+
for (let i = 0; i < nseg; i++) dataLen += buf[pos + 27 + i]
|
|
61
|
+
const dataStart = pos + 27 + nseg
|
|
62
|
+
if (dataStart + dataLen > buf.length) {
|
|
63
|
+
endOfStream = true // page body cut short: music-metadata throws before parsePage of the consumer runs
|
|
64
|
+
break
|
|
65
|
+
}
|
|
66
|
+
if (headerType & 0x02) {
|
|
67
|
+
const idText = [...buf.subarray(dataStart, dataStart + 7)].filter(b => b >= 32 && b <= 126).map(b => String.fromCharCode(b)).join('')
|
|
68
|
+
if (idText === 'OpusHea') {
|
|
69
|
+
s.codec = 'opus'
|
|
70
|
+
s.preSkip = buf.readUInt16LE(dataStart + 10)
|
|
71
|
+
s.sampleRate = buf.readUInt32LE(dataStart + 12)
|
|
72
|
+
} else if (idText === 'vorbis') {
|
|
73
|
+
s.codec = 'vorbis'
|
|
74
|
+
s.sampleRate = buf.readUInt32LE(dataStart + 12)
|
|
75
|
+
} else {
|
|
76
|
+
s.codec = 'other'
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (headerType & 0x04) s.closed = true
|
|
80
|
+
else if (!(headerType & 0x02)) s.fullPages++ // a complete page that is neither first nor last
|
|
81
|
+
s.pageCount++
|
|
82
|
+
s.last = { granule, lastPage: !!(headerType & 0x04) }
|
|
83
|
+
pos = dataStart + dataLen
|
|
84
|
+
// music-metadata stops early after page 12 unless a consumer wants the last page (Opus/Vorbis do) — so it keeps going
|
|
85
|
+
if ([...streams.values()].every(x => x.closed)) break
|
|
86
|
+
}
|
|
87
|
+
for (const s of streams.values()) {
|
|
88
|
+
if (!s.last || !s.sampleRate) continue
|
|
89
|
+
if (!(endOfStream || s.last.lastPage)) continue
|
|
90
|
+
if (s.last.granule < 0n) continue
|
|
91
|
+
// music-metadata (Vorbis only): on a truncated file it calls flush() -> parseFullPage() on the pages queued so
|
|
92
|
+
// far; with nothing queued (file ends after the identification page, before the comment page completes) that
|
|
93
|
+
// reads an empty array and THROWS RangeError. A throw leaves the caller's `seconds` unset, so the faithful
|
|
94
|
+
// equivalent is `undefined` — never a fabricated 0. (Measured: cut in bytes 58..3997 of a Vorbis file.)
|
|
95
|
+
if (s.codec === 'vorbis' && endOfStream && !s.last.lastPage && s.fullPages === 0 && s.pageCount > 0) return undefined
|
|
96
|
+
const g = Number(s.last.granule)
|
|
97
|
+
if (s.codec === 'opus') return (g - s.preSkip) / 48000
|
|
98
|
+
if (s.codec === 'vorbis') return g / s.sampleRate
|
|
99
|
+
}
|
|
100
|
+
return undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/* ------------------------------ WAV ------------------------------ */
|
|
104
|
+
|
|
105
|
+
const wavDuration = buf => {
|
|
106
|
+
if (ascii(buf, 0, 4) !== 'RIFF' || ascii(buf, 8, 4) !== 'WAVE') return undefined
|
|
107
|
+
let pos = 12
|
|
108
|
+
let sampleRate
|
|
109
|
+
let blockAlign = 0
|
|
110
|
+
let fact
|
|
111
|
+
while (pos + 8 <= buf.length) {
|
|
112
|
+
const id = ascii(buf, pos, 4)
|
|
113
|
+
const size = buf.readUInt32LE(pos + 4)
|
|
114
|
+
const body = pos + 8
|
|
115
|
+
if (id === 'fmt ') {
|
|
116
|
+
sampleRate = buf.readUInt32LE(body + 4)
|
|
117
|
+
blockAlign = buf.readUInt16LE(body + 12)
|
|
118
|
+
} else if (id === 'fact') {
|
|
119
|
+
fact = buf.readUInt32LE(body)
|
|
120
|
+
} else if (id === 'data') {
|
|
121
|
+
let chunkSize = size
|
|
122
|
+
const remaining = buf.length - body
|
|
123
|
+
if (remaining < chunkSize) chunkSize = remaining // "data chunk length exceeding file length"
|
|
124
|
+
const samples = fact !== undefined ? fact : chunkSize === 0xffffffff ? undefined : chunkSize / blockAlign
|
|
125
|
+
if (samples && sampleRate) return samples / sampleRate
|
|
126
|
+
return undefined
|
|
127
|
+
}
|
|
128
|
+
pos = body + size + (size % 2) // chunks are word aligned
|
|
129
|
+
}
|
|
130
|
+
return undefined
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/* ------------------------------ FLAC ------------------------------ */
|
|
134
|
+
|
|
135
|
+
const flacDuration = buf => {
|
|
136
|
+
if (ascii(buf, 0, 4) !== 'fLaC') return undefined
|
|
137
|
+
let pos = 4
|
|
138
|
+
while (pos + 4 <= buf.length) {
|
|
139
|
+
const h = buf[pos]
|
|
140
|
+
const type = h & 0x7f
|
|
141
|
+
const len = (buf[pos + 1] << 16) | (buf[pos + 2] << 8) | buf[pos + 3]
|
|
142
|
+
if (type === 0) {
|
|
143
|
+
// STREAMINFO (34 bytes): ... sampleRate(20) channels(3) bps(5) totalSamples(36)
|
|
144
|
+
if (len !== 34) return undefined
|
|
145
|
+
// music-metadata only reports once the whole 34-byte STREAMINFO block is present (a cut inside it is not trusted)
|
|
146
|
+
if (pos + 4 + 34 > buf.length) return undefined
|
|
147
|
+
const o = pos + 4
|
|
148
|
+
const sampleRate = ((buf[o + 10] << 16) | (buf[o + 11] << 8) | buf[o + 12]) >> 4
|
|
149
|
+
const totalSamples = (buf[o + 13] & 0x0f) * 2 ** 32 + buf.readUInt32BE(o + 14)
|
|
150
|
+
return totalSamples > 0 && sampleRate ? totalSamples / sampleRate : undefined
|
|
151
|
+
}
|
|
152
|
+
if (h & 0x80) break // last metadata block, no STREAMINFO seen
|
|
153
|
+
pos += 4 + len
|
|
154
|
+
}
|
|
155
|
+
return undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/* ------------------------------ MP4 / M4A ------------------------------ */
|
|
159
|
+
|
|
160
|
+
const CONTAINERS = new Set(['moov', 'trak', 'mdia', 'minf', 'stbl', 'moof', 'traf', 'mvex'])
|
|
161
|
+
|
|
162
|
+
const mp4Duration = buf => {
|
|
163
|
+
const tracks = [] // { handler, timeScale, duration, fragSamples }
|
|
164
|
+
const walk = (start, end, cur) => {
|
|
165
|
+
let pos = start
|
|
166
|
+
while (pos + 8 <= end) {
|
|
167
|
+
let size = u32be(buf, pos)
|
|
168
|
+
const type = ascii(buf, pos + 4, 4)
|
|
169
|
+
let hdr = 8
|
|
170
|
+
if (size === 1) {
|
|
171
|
+
size = u64be(buf, pos + 8)
|
|
172
|
+
hdr = 16
|
|
173
|
+
} else if (size === 0) size = end - pos
|
|
174
|
+
// A box that claims more bytes than the file holds means the file is truncated. music-metadata reads
|
|
175
|
+
// boxes through a tokenizer and throws EndOfStreamError there; the faithful equivalent is "no duration".
|
|
176
|
+
if (size >= hdr && pos + size > end) {
|
|
177
|
+
if (type === 'moov') truncated = true // header atom incomplete -> unreliable
|
|
178
|
+
size = end - pos
|
|
179
|
+
} else if (size < hdr) size = Math.min(Math.max(size, hdr), end - pos)
|
|
180
|
+
const body = pos + hdr
|
|
181
|
+
const bodyEnd = pos + size
|
|
182
|
+
if (type === 'trak') {
|
|
183
|
+
const t = { handler: undefined, timeScale: 0, duration: 0, hasMdhd: false }
|
|
184
|
+
tracks.push(t)
|
|
185
|
+
walk(body, bodyEnd, t)
|
|
186
|
+
} else if (CONTAINERS.has(type)) {
|
|
187
|
+
walk(body, bodyEnd, cur)
|
|
188
|
+
} else if (cur && type === 'hdlr') {
|
|
189
|
+
cur.handler = ascii(buf, body + 8, 4)
|
|
190
|
+
} else if (cur && type === 'mdhd') {
|
|
191
|
+
const v = buf[body]
|
|
192
|
+
cur.hasMdhd = true
|
|
193
|
+
if (v === 1) {
|
|
194
|
+
cur.timeScale = u32be(buf, body + 20)
|
|
195
|
+
cur.duration = u64be(buf, body + 24)
|
|
196
|
+
} else {
|
|
197
|
+
cur.timeScale = u32be(buf, body + 12)
|
|
198
|
+
cur.duration = u32be(buf, body + 16)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
pos += size
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
let truncated = false
|
|
205
|
+
walk(0, buf.length, undefined)
|
|
206
|
+
if (truncated) return undefined
|
|
207
|
+
const audio = tracks.find(t => t.handler === 'soun' || t.handler === 'audi')
|
|
208
|
+
if (audio && audio.timeScale > 0 && audio.duration > 0) return audio.duration / audio.timeScale
|
|
209
|
+
return undefined // fragmented-only / timeScale 0 cases are not reproduced (caller falls back)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/* ------------------------------ MP3 / ADTS ------------------------------ */
|
|
213
|
+
|
|
214
|
+
const MPEG_BITRATES = {
|
|
215
|
+
// [version][layer] kbps by index 1..14; version: 1 = MPEG1, 2 = MPEG2/2.5
|
|
216
|
+
'1-1': [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448],
|
|
217
|
+
'1-2': [32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384],
|
|
218
|
+
'1-3': [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
|
|
219
|
+
'2-1': [32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256],
|
|
220
|
+
'2-2': [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
|
|
221
|
+
'2-3': [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]
|
|
222
|
+
}
|
|
223
|
+
const MPEG_SAMPLE_RATES = { 3: [44100, 48000, 32000], 2: [22050, 24000, 16000], 0: [11025, 12000, 8000] } // keyed by version bits
|
|
224
|
+
|
|
225
|
+
/** Parses a 4-byte MPEG audio frame header at `o`. Returns null when it is not a valid frame header. */
|
|
226
|
+
const mpegHeader = (buf, o) => {
|
|
227
|
+
if (o + 4 > buf.length || buf[o] !== 0xff || (buf[o + 1] & 0xe0) !== 0xe0) return null
|
|
228
|
+
const versionBits = (buf[o + 1] >> 3) & 3 // 3=MPEG1 2=MPEG2 0=MPEG2.5 1=reserved
|
|
229
|
+
const layerBits = (buf[o + 1] >> 1) & 3 // 1=III 2=II 3=I 0=reserved (ADTS uses 0)
|
|
230
|
+
const bitrateIdx = buf[o + 2] >> 4
|
|
231
|
+
const srIdx = (buf[o + 2] >> 2) & 3
|
|
232
|
+
const padding = (buf[o + 2] >> 1) & 1
|
|
233
|
+
if (versionBits === 1 || layerBits === 0 || srIdx === 3) return null
|
|
234
|
+
const layer = 4 - layerBits // 1,2,3
|
|
235
|
+
const verKey = versionBits === 3 ? 1 : 2
|
|
236
|
+
if (bitrateIdx === 0 || bitrateIdx === 15) return null
|
|
237
|
+
const bitrate = MPEG_BITRATES[`${verKey}-${layer}`][bitrateIdx - 1] * 1000
|
|
238
|
+
const sampleRate = MPEG_SAMPLE_RATES[versionBits][srIdx]
|
|
239
|
+
const samplesPerFrame = layer === 1 ? 384 : layer === 2 ? 1152 : versionBits === 3 ? 1152 : 576
|
|
240
|
+
const slot = layer === 1 ? 4 : 1
|
|
241
|
+
const frameSize = layer === 1 ? Math.floor(((12 * bitrate) / sampleRate + padding) * 4) : Math.floor((samplesPerFrame / 8) * bitrate / sampleRate + (padding ? slot : 0))
|
|
242
|
+
const mono = (buf[o + 3] >> 6) === 3
|
|
243
|
+
return { versionBits, layer, bitrate, sampleRate, samplesPerFrame, frameSize, padding, crc: (buf[o + 1] & 1) === 0, mono }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const id3v2Size = buf => {
|
|
247
|
+
if (buf.length >= 10 && ascii(buf, 0, 3) === 'ID3') {
|
|
248
|
+
const size = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f)
|
|
249
|
+
return 10 + size + (buf[5] & 0x10 ? 10 : 0)
|
|
250
|
+
}
|
|
251
|
+
return 0
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const mp3Duration = buf => {
|
|
255
|
+
let pos = id3v2Size(buf)
|
|
256
|
+
// find first valid frame header
|
|
257
|
+
let first
|
|
258
|
+
while (pos + 4 <= buf.length) {
|
|
259
|
+
const h = mpegHeader(buf, pos)
|
|
260
|
+
if (h && h.frameSize > 0 && (pos + h.frameSize === buf.length || mpegHeader(buf, pos + h.frameSize) || pos + h.frameSize > buf.length)) {
|
|
261
|
+
first = { ...h, pos }
|
|
262
|
+
break
|
|
263
|
+
}
|
|
264
|
+
pos++
|
|
265
|
+
}
|
|
266
|
+
if (!first) return undefined
|
|
267
|
+
const hasId3v1 = buf.length >= 128 && ascii(buf, buf.length - 128, 3) === 'TAG'
|
|
268
|
+
|
|
269
|
+
// Xing / Info tag lives after the side info of the first frame
|
|
270
|
+
const sideInfo = first.versionBits === 3 ? (first.mono ? 17 : 32) : first.mono ? 9 : 17
|
|
271
|
+
const tagOff = first.pos + 4 + (first.crc ? 2 : 0) + sideInfo
|
|
272
|
+
const tag = tagOff + 4 <= buf.length ? ascii(buf, tagOff, 4) : ''
|
|
273
|
+
if (tag === 'Xing' || tag === 'Info') {
|
|
274
|
+
const flags = u32be(buf, tagOff + 4)
|
|
275
|
+
let o = tagOff + 8
|
|
276
|
+
let numFrames = null
|
|
277
|
+
let streamSize = null
|
|
278
|
+
if (flags & 1) {
|
|
279
|
+
numFrames = u32be(buf, o)
|
|
280
|
+
o += 4
|
|
281
|
+
}
|
|
282
|
+
if (flags & 2) {
|
|
283
|
+
streamSize = u32be(buf, o)
|
|
284
|
+
o += 4
|
|
285
|
+
}
|
|
286
|
+
if (flags & 4) o += 100
|
|
287
|
+
if (flags & 8) o += 4
|
|
288
|
+
let lameMusicLength
|
|
289
|
+
if (o + 4 <= buf.length && ascii(buf, o, 4) === 'LAME') {
|
|
290
|
+
const ver = ascii(buf, o + 4, 5)
|
|
291
|
+
const m = ver.match(/\d+.\d+/g)
|
|
292
|
+
if (m) {
|
|
293
|
+
const [maj, min] = m[0].split('.').map(n => parseInt(n, 10))
|
|
294
|
+
if (maj >= 3 && min >= 90) lameMusicLength = buf.readUInt32BE(o + 9 + 0x14) // ExtendedLameHeader.music_length
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// music-metadata: LAME music_length/1000 first, then overwritten by the frame-count formula if streamSize present
|
|
298
|
+
if (streamSize && numFrames !== null) return (numFrames * first.samplesPerFrame) / first.sampleRate
|
|
299
|
+
if (lameMusicLength !== undefined && lameMusicLength > 0) return lameMusicLength / 1000
|
|
300
|
+
// 'Info' tag = CBR marker, fall through to CBR-by-size below
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Scan up to 4 frames to detect CBR (all equal bitrates), like music-metadata
|
|
304
|
+
const bitrates = []
|
|
305
|
+
let p = first.pos
|
|
306
|
+
let last
|
|
307
|
+
for (let i = 0; i < 4 && p + 4 <= buf.length; i++) {
|
|
308
|
+
const h = mpegHeader(buf, p)
|
|
309
|
+
if (!h) break
|
|
310
|
+
bitrates.push(h.bitrate)
|
|
311
|
+
last = h
|
|
312
|
+
p += h.frameSize
|
|
313
|
+
}
|
|
314
|
+
if (bitrates.length === 4 && bitrates.every(b => b === bitrates[0])) {
|
|
315
|
+
// CBR: numberOfSamples = round(mpegSize / frame_size) * samplesPerFrame
|
|
316
|
+
const mpegSize = buf.length - first.pos - (hasId3v1 ? 128 : 0)
|
|
317
|
+
return (Math.round(mpegSize / last.frameSize) * first.samplesPerFrame) / first.sampleRate
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// VBR without Xing: full frame walk
|
|
321
|
+
let frames = 0
|
|
322
|
+
p = first.pos
|
|
323
|
+
while (p + 4 <= buf.length) {
|
|
324
|
+
const h = mpegHeader(buf, p)
|
|
325
|
+
if (!h) {
|
|
326
|
+
// resync: advance byte-wise to next plausible header
|
|
327
|
+
p++
|
|
328
|
+
continue
|
|
329
|
+
}
|
|
330
|
+
frames++
|
|
331
|
+
p += h.frameSize
|
|
332
|
+
}
|
|
333
|
+
return frames ? (frames * first.samplesPerFrame) / first.sampleRate : undefined
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/* ------------------------------ ADTS (raw AAC) ------------------------------ */
|
|
337
|
+
|
|
338
|
+
const ADTS_SAMPLE_RATES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Raw ADTS AAC (`.aac`): every frame carries 1024 samples; duration = frames * 1024 / sampleRate.
|
|
342
|
+
* Walks frame by frame using the 13-bit frame length in each header. Like music-metadata the sample rate
|
|
343
|
+
* comes from the first frame header.
|
|
344
|
+
*/
|
|
345
|
+
const adtsDuration = buf => {
|
|
346
|
+
let pos = id3v2Size(buf)
|
|
347
|
+
let frames = 0
|
|
348
|
+
let sampleRate
|
|
349
|
+
while (pos + 7 <= buf.length) {
|
|
350
|
+
// syncword 0xFFF, layer bits == 00 (this is what distinguishes ADTS from MPEG audio layers)
|
|
351
|
+
if (buf[pos] !== 0xff || (buf[pos + 1] & 0xf6) !== 0xf0) {
|
|
352
|
+
if (frames === 0) {
|
|
353
|
+
pos++ // still hunting for the first sync
|
|
354
|
+
continue
|
|
355
|
+
}
|
|
356
|
+
break // garbage after the stream: stop like a decoder would
|
|
357
|
+
}
|
|
358
|
+
const sfi = (buf[pos + 2] >> 2) & 0x0f
|
|
359
|
+
const frameLength = ((buf[pos + 3] & 0x03) << 11) | (buf[pos + 4] << 3) | (buf[pos + 5] >> 5)
|
|
360
|
+
if (sfi > 12 || frameLength < 7) {
|
|
361
|
+
if (frames === 0) {
|
|
362
|
+
pos++
|
|
363
|
+
continue
|
|
364
|
+
}
|
|
365
|
+
break
|
|
366
|
+
}
|
|
367
|
+
if (sampleRate === undefined) sampleRate = ADTS_SAMPLE_RATES[sfi]
|
|
368
|
+
frames++
|
|
369
|
+
pos += frameLength
|
|
370
|
+
}
|
|
371
|
+
return frames && sampleRate ? (frames * 1024) / sampleRate : undefined
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/* ------------------------------ AIFF / AIFF-C ------------------------------ */
|
|
375
|
+
|
|
376
|
+
const aiffDuration = buf => {
|
|
377
|
+
if (ascii(buf, 0, 4) !== 'FORM') return undefined
|
|
378
|
+
const kind = ascii(buf, 8, 4)
|
|
379
|
+
if (kind !== 'AIFF' && kind !== 'AIFC') return undefined
|
|
380
|
+
let pos = 12
|
|
381
|
+
while (pos + 8 <= buf.length) {
|
|
382
|
+
const id = ascii(buf, pos, 4)
|
|
383
|
+
const size = u32be(buf, pos + 4)
|
|
384
|
+
const body = pos + 8
|
|
385
|
+
if (id === 'COMM') {
|
|
386
|
+
if (size < 18 || body + size > buf.length) return undefined // the whole COMM chunk (incl. AIFF-C extras) must be present
|
|
387
|
+
const frames = u32be(buf, body + 2)
|
|
388
|
+
// 80-bit IEEE extended sample rate: 1 sign + 15 exponent bits, 64-bit mantissa (explicit integer bit)
|
|
389
|
+
const exp = buf.readUInt16BE(body + 8) & 0x7fff
|
|
390
|
+
const mantissa = buf.readBigUInt64BE(body + 10)
|
|
391
|
+
const sampleRate = Number(mantissa) * 2 ** (exp - 16383 - 63)
|
|
392
|
+
return sampleRate > 0 ? frames / sampleRate : undefined
|
|
393
|
+
}
|
|
394
|
+
pos = body + size + (size & 1)
|
|
395
|
+
}
|
|
396
|
+
return undefined
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/* ------------------------------ Matroska / WebM ------------------------------ */
|
|
400
|
+
|
|
401
|
+
/** EBML variable-length integer at `pos`. `keepMarker` = element IDs keep the length-marker bit, sizes drop it. */
|
|
402
|
+
const ebmlVint = (buf, pos, keepMarker) => {
|
|
403
|
+
if (pos >= buf.length) return undefined
|
|
404
|
+
const first = buf[pos]
|
|
405
|
+
if (first === 0) return undefined
|
|
406
|
+
const len = Math.clz32(first) - 23 // 1..8
|
|
407
|
+
if (pos + len > buf.length) return undefined
|
|
408
|
+
let value = keepMarker ? first : first & (0xff >> len)
|
|
409
|
+
let allOnes = (first & (0xff >> len)) === 0xff >> len
|
|
410
|
+
for (let i = 1; i < len; i++) {
|
|
411
|
+
value = value * 256 + buf[pos + i]
|
|
412
|
+
if (buf[pos + i] !== 0xff) allOnes = false
|
|
413
|
+
}
|
|
414
|
+
return { value, length: len, unknown: !keepMarker && allOnes }
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const matroskaDuration = buf => {
|
|
418
|
+
const info = { timecodeScale: undefined, duration: undefined }
|
|
419
|
+
const readUInt = (o, n) => {
|
|
420
|
+
let v = 0
|
|
421
|
+
for (let i = 0; i < n; i++) v = v * 256 + buf[o + i]
|
|
422
|
+
return v
|
|
423
|
+
}
|
|
424
|
+
// walk `[start, end)` looking for the Segment > Info element; returns true once Info has been fully read
|
|
425
|
+
const walk = (start, end, depth) => {
|
|
426
|
+
let pos = start
|
|
427
|
+
while (pos < end) {
|
|
428
|
+
const id = ebmlVint(buf, pos, true)
|
|
429
|
+
if (!id) return false
|
|
430
|
+
const size = ebmlVint(buf, pos + id.length, false)
|
|
431
|
+
if (!size) return false
|
|
432
|
+
const body = pos + id.length + size.length
|
|
433
|
+
const bodyEnd = size.unknown ? end : Math.min(end, body + size.value)
|
|
434
|
+
if (id.value === 0x18538067 && depth === 0) {
|
|
435
|
+
if (walk(body, bodyEnd, 1)) return true // Segment
|
|
436
|
+
} else if (id.value === 0x1549a966 && depth === 1) {
|
|
437
|
+
// Info: TimecodeScale (uint) and Duration (float)
|
|
438
|
+
let q = body
|
|
439
|
+
while (q < bodyEnd) {
|
|
440
|
+
const cid = ebmlVint(buf, q, true)
|
|
441
|
+
const csz = cid && ebmlVint(buf, q + cid.length, false)
|
|
442
|
+
if (!csz) break
|
|
443
|
+
const cb = q + cid.length + csz.length
|
|
444
|
+
if (cb + csz.value > buf.length) break
|
|
445
|
+
if (cid.value === 0x2ad7b1) info.timecodeScale = readUInt(cb, csz.value)
|
|
446
|
+
else if (cid.value === 0x4489) info.duration = csz.value === 4 ? buf.readFloatBE(cb) : csz.value === 8 ? buf.readDoubleBE(cb) : undefined
|
|
447
|
+
q = cb + csz.value
|
|
448
|
+
}
|
|
449
|
+
return true
|
|
450
|
+
}
|
|
451
|
+
if (size.unknown) return false // cannot skip an unknown-size element that is not the Segment
|
|
452
|
+
pos = body + size.value
|
|
453
|
+
}
|
|
454
|
+
return false
|
|
455
|
+
}
|
|
456
|
+
walk(0, buf.length, 0)
|
|
457
|
+
if (typeof info.duration !== 'number' || !Number.isFinite(info.duration)) return undefined
|
|
458
|
+
return (info.duration * (info.timecodeScale || 1000000)) / 1e9
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/* ------------------------------ AMR (NB and WB) ------------------------------ */
|
|
462
|
+
|
|
463
|
+
// total bytes per frame (1 header byte + payload), indexed by frame type; 0 = invalid frame type
|
|
464
|
+
const AMR_NB_FRAME_BYTES = [13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1]
|
|
465
|
+
const AMR_WB_FRAME_BYTES = [18, 24, 33, 37, 41, 47, 51, 59, 61, 6, 0, 0, 0, 0, 1, 1]
|
|
466
|
+
|
|
467
|
+
/** Every AMR frame (any mode, incl. SID and "no data") covers 20 ms. */
|
|
468
|
+
const amrDuration = buf => {
|
|
469
|
+
const wb = ascii(buf, 0, 9) === '#!AMR-WB\n'
|
|
470
|
+
if (!wb && ascii(buf, 0, 6) !== '#!AMR\n') return undefined
|
|
471
|
+
const table = wb ? AMR_WB_FRAME_BYTES : AMR_NB_FRAME_BYTES
|
|
472
|
+
let pos = wb ? 9 : 6
|
|
473
|
+
let frames = 0
|
|
474
|
+
while (pos < buf.length) {
|
|
475
|
+
const size = table[(buf[pos] >> 3) & 0x0f]
|
|
476
|
+
if (!size) break // reserved frame type: not a valid stream from here on
|
|
477
|
+
if (pos + size > buf.length) break // partial last frame is not counted
|
|
478
|
+
frames++
|
|
479
|
+
pos += size
|
|
480
|
+
}
|
|
481
|
+
return frames ? frames * 0.02 : undefined
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/* ------------------------------ dispatch ------------------------------ */
|
|
485
|
+
|
|
486
|
+
/** @param {Buffer} buf @returns {number|undefined} duration in seconds */
|
|
487
|
+
export const durationFromBuffer = buf => {
|
|
488
|
+
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
|
|
489
|
+
if (buf.length < 12) return undefined
|
|
490
|
+
try {
|
|
491
|
+
const magic = ascii(buf, 0, 4)
|
|
492
|
+
if (magic === 'OggS') return oggDuration(buf)
|
|
493
|
+
if (magic === 'RIFF') return wavDuration(buf)
|
|
494
|
+
if (magic === 'fLaC') return flacDuration(buf)
|
|
495
|
+
if (ascii(buf, 4, 4) === 'ftyp') return mp4Duration(buf)
|
|
496
|
+
if (magic === 'FORM') return aiffDuration(buf)
|
|
497
|
+
if (buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3) return matroskaDuration(buf)
|
|
498
|
+
if (magic === '#!AM') return amrDuration(buf)
|
|
499
|
+
if (buf[0] === 0xff && (buf[1] & 0xf6) === 0xf0) return adtsDuration(buf) // sync + layer 00 = ADTS
|
|
500
|
+
if (magic.startsWith('ID3') || (buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0)) return mp3Duration(buf)
|
|
501
|
+
} catch {
|
|
502
|
+
return undefined
|
|
503
|
+
}
|
|
504
|
+
return undefined
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Accepts a Buffer, a file path, or a Readable stream (same inputs as the old `getAudioDuration`). */
|
|
508
|
+
export const audioDuration = async input => {
|
|
509
|
+
if (Buffer.isBuffer(input)) return durationFromBuffer(input)
|
|
510
|
+
if (typeof input === 'string') {
|
|
511
|
+
const { size } = await stat(input)
|
|
512
|
+
if (size > 64 * 1024 * 1024) {
|
|
513
|
+
// avoid loading huge files fully: header-only containers only need a prefix, Ogg needs the tail
|
|
514
|
+
const fh = await open(input, 'r')
|
|
515
|
+
try {
|
|
516
|
+
const head = Buffer.alloc(Math.min(size, 4 * 1024 * 1024))
|
|
517
|
+
await fh.read(head, 0, head.length, 0)
|
|
518
|
+
return durationFromBuffer(head)
|
|
519
|
+
} finally {
|
|
520
|
+
await fh.close()
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const chunks = []
|
|
524
|
+
for await (const c of createReadStream(input)) chunks.push(c)
|
|
525
|
+
return durationFromBuffer(Buffer.concat(chunks))
|
|
526
|
+
}
|
|
527
|
+
const chunks = []
|
|
528
|
+
for await (const c of input) chunks.push(c)
|
|
529
|
+
return durationFromBuffer(Buffer.concat(chunks))
|
|
530
|
+
}
|