-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathaudioConverter.js
More file actions
218 lines (192 loc) · 6.42 KB
/
audioConverter.js
File metadata and controls
218 lines (192 loc) · 6.42 KB
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
const { spawn } = require('child_process');
const { appLogger } = require('./logger');
const fs = require('fs');
const path = require('path');
const os = require('os');
const logger = appLogger('audioConverter');
/**
* Audio Converter - Converts audio files to WhatsApp-compatible OGG/Opus format
* Uses ffmpeg to ensure proper encoding
*/
class AudioConverter {
constructor() {
this.ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg';
}
/**
* Check if ffmpeg is available
* @returns {Promise<boolean>}
*/
async checkFfmpegAvailable() {
return new Promise((resolve) => {
const ffmpeg = spawn(this.ffmpegPath, ['-version']);
ffmpeg.on('error', () => {
resolve(false);
});
ffmpeg.on('close', (code) => {
resolve(code === 0);
});
});
}
/**
* Convert audio buffer to OGG/Opus format for WhatsApp
* @param {Buffer} inputBuffer - Input audio buffer
* @param {string} originalMimetype - Original audio mimetype
* @param {boolean} isPtt - Is this a voice message (PTT) vs regular audio
* @returns {Promise<Buffer>} - Converted audio buffer
*/
async convertToOggOpus(inputBuffer, originalMimetype = '', isPtt = false) {
const available = await this.checkFfmpegAvailable();
if (!available) {
logger.warn('ffmpeg not available, sending audio without conversion');
return inputBuffer;
}
// If already OGG with opus codec, skip conversion
if (originalMimetype === 'audio/ogg; codecs=opus' || originalMimetype === 'audio/ogg') {
logger.info('Audio already in OGG format, checking codec');
// We could add codec verification here, but for now trust the mimetype
return inputBuffer;
}
return new Promise((resolve, reject) => {
const tempDir = os.tmpdir();
const inputPath = path.join(tempDir, `input_${Date.now()}.${this._getExtension(originalMimetype)}`);
const outputPath = path.join(tempDir, `output_${Date.now()}.ogg`);
logger.info('Converting audio to OGG/Opus', {
originalMimetype,
inputSize: inputBuffer.length,
});
// Write input buffer to temp file
fs.writeFileSync(inputPath, inputBuffer);
// Convert using ffmpeg - STRIP EVERYTHING except audio stream
// -vn: disable video (removes album art/thumbnails)
// -sn: disable subtitles
// -dn: disable data streams
// -map_metadata -1: strip ALL metadata
// -fflags +bitexact: ensure deterministic output
// -ar 16000: 16kHz sample rate (WhatsApp voice message standard)
// -avoid_negative_ts make_zero: fixes timestamp issues
// -ac 1: mono channel (required by WhatsApp)
// -codec:a libopus: use Opus codec
// -b:a: bitrate (24k for voice, 64k for music)
// -application voip: optimize for voice (only for PTT)
const ffmpegArgs = [
'-i', inputPath,
'-vn', // No video stream
'-sn', // No subtitle stream
'-dn', // No data stream
'-map_metadata', '-1', // Strip all metadata (title, artist, album, etc.)
'-fflags', '+bitexact', // Deterministic output
'-map', '0:a:0', // Only map first audio stream
'-ar', '16000', // 16kHz sample rate like real WhatsApp messages
'-avoid_negative_ts', 'make_zero',
'-ac', '1', // Mono
];
// Add codec and application-specific settings
if (isPtt) {
// Voice message settings (PTT - Push To Talk)
ffmpegArgs.push(
'-codec:a', 'libopus',
'-application', 'voip', // Optimize for voice
'-b:a', '24k', // Lower bitrate for voice
);
} else {
// Regular audio/music settings
ffmpegArgs.push(
'-codec:a', 'libopus',
'-b:a', '64k', // Higher bitrate for music quality
);
}
ffmpegArgs.push(
'-f', 'ogg',
'-y', // Overwrite output file
outputPath,
);
const ffmpeg = spawn(this.ffmpegPath, ffmpegArgs);
let stderrData = '';
ffmpeg.stderr.on('data', (data) => {
stderrData += data.toString();
});
ffmpeg.on('error', (err) => {
logger.error('ffmpeg spawn error', { error: err.message });
this._cleanup([inputPath, outputPath]);
reject(new Error(`ffmpeg process error: ${err.message}`));
});
ffmpeg.on('close', (code) => {
if (code !== 0) {
logger.error('ffmpeg conversion failed', {
code,
stderr: stderrData.substring(0, 500),
});
this._cleanup([inputPath, outputPath]);
reject(new Error(`ffmpeg exited with code ${code}`));
return;
}
try {
// Read converted file
const convertedBuffer = fs.readFileSync(outputPath);
logger.info('Audio converted successfully', {
originalSize: inputBuffer.length,
convertedSize: convertedBuffer.length,
});
// Cleanup temp files
this._cleanup([inputPath, outputPath]);
resolve(convertedBuffer);
} catch (err) {
logger.error('Error reading converted file', { error: err.message });
this._cleanup([inputPath, outputPath]);
reject(err);
}
});
});
}
/**
* Get file extension from mimetype
* @private
*/
_getExtension(mimetype) {
const map = {
'audio/mpeg': 'mp3',
'audio/mp3': 'mp3',
'audio/mp4': 'm4a',
'audio/m4a': 'm4a',
'audio/x-m4a': 'm4a',
'audio/wav': 'wav',
'audio/wave': 'wav',
'audio/x-wav': 'wav',
'audio/ogg': 'ogg',
'audio/webm': 'webm',
'audio/flac': 'flac',
'audio/aac': 'aac',
'audio/3gpp': '3gp',
'audio/amr': 'amr',
};
return map[mimetype] || 'audio';
}
/**
* Cleanup temporary files
* @private
*/
_cleanup(files) {
files.forEach(file => {
try {
if (fs.existsSync(file)) {
fs.unlinkSync(file);
}
} catch (err) {
logger.warn('Failed to cleanup temp file', { file, error: err.message });
}
});
}
/**
* Check if mimetype needs conversion
* @param {string} mimetype - Audio mimetype
* @returns {boolean}
*/
needsConversion(mimetype) {
// Skip conversion for OGG
if (mimetype === 'audio/ogg' || mimetype === 'audio/ogg; codecs=opus') {
return false;
}
return true;
}
}
module.exports = new AudioConverter();