wav2opus.h 9.34 KB
Newer Older
藤森雅人's avatar
藤森雅人 committed
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
#include <opus_types.h>
#include  <opus.h>
#include <cstring>
#include <memory>

#include <vector>
// https://github.com/mackron/dr_libs/blob/master/dr_wav.h
#define DR_WAV_IMPLEMENTATION

#include "dr_wav.h"

#define FRAME_SIZE 480
#define MAX_FRAME_SIZE (6*FRAME_SIZE)

#define MAX_CHANNELS 1
#define MAX_PACKET_SIZE (3*1276)

#pragma pack(push)
#pragma pack(1)

struct WavInfo {
	uint16_t channels;
	uint32_t sampleRate;
	uint32_t bitsPerSample;
};

#pragma pack(pop)

#ifndef  nullptr
#define  nullptr NULL
#endif

class FileStream {
public:
	FileStream() {
		cur_pos = 0;
	}

	void Append(const char *data, size_t size) {
		if (cur_pos + size > Size()) {
			vec.resize(cur_pos + size);
		}
		memcpy(vec.data() + cur_pos, data, size);
		cur_pos += size;
	}

	void AppendU32(uint32_t val) {
		Append((char *)(&val), sizeof(val));
	}

	char *Data() {
		return vec.data();
	}

	size_t Size() {
		return vec.size();
	}

	size_t Read(void *buff, size_t elemSize, size_t elemCount) {
		size_t readed = min((vec.size() - cur_pos), (elemCount * elemSize)) / elemSize;
		if (readed > 0) {
			memcpy(buff, vec.data() + cur_pos, readed * elemSize);
			cur_pos += readed * elemSize;
		}
		return readed;
	}

	bool SeekCur(int offset) {
		if (cur_pos + offset > vec.size()) {
			cur_pos = !vec.empty() ? (vec.size() - 1) : 0;
			return false;
		}
		else {
			cur_pos += offset;
			return true;
		}
	}

	bool SeekBeg(int offset = 0) {
		cur_pos = 0;
		return SeekCur(offset);
	}

	bool WriteToFile(const char *filename) {
		FILE *fin;
		fopen_s(&fin, filename, "wb");
		if (!fin) {
			return false;
		}
		fseek(fin, 0, SEEK_SET);
		fwrite(vec.data(), sizeof(char), vec.size(), fin);
		fclose(fin);
		return true;
	}

	bool ReadFromFile(const char *filename) {
		FILE *fin;
		fopen_s(&fin, filename, "rb");
		if (!fin) {
			return false;
		}
		fseek(fin, 0, SEEK_END);
		long fileSize = ftell(fin);
		vec.resize(static_cast<unsigned long long int>(fileSize));
		fseek(fin, 0, SEEK_SET);
		fread(vec.data(), sizeof(char), vec.size(), fin);
		fclose(fin);
		return true;
	}

private:
	std::vector<char> vec;
	size_t cur_pos;
};

bool Wav2Opus(FileStream *input, FileStream *output);

bool Opus2Wav(FileStream *input, FileStream *output);

bool wav2stream(char *input, FileStream *output);

bool stream2wav(FileStream *input, char *output);


bool wavWrite_int16(char *filename, int16_t *buffer, int sampleRate, uint32_t totalSampleCount) {
	drwav_data_format format = {};
	format.container = drwav_container_riff;     // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64.
	format.format = DR_WAVE_FORMAT_PCM;          // <-- Any of the DR_WAVE_FORMAT_* codes.
	format.channels = 1;
	format.sampleRate = (drwav_uint32)sampleRate;
	format.bitsPerSample = 16;
	drwav *pWav = drwav_open_file_write(filename, &format);
	if (pWav) {
		drwav_uint64 samplesWritten = drwav_write(pWav, totalSampleCount, buffer);
		drwav_uninit(pWav);
		if (samplesWritten != totalSampleCount) {
			fprintf(stderr, "ERROR\n");
			return false;
		}
		return true;
	}
	return false;
}

int16_t *wavRead_int16(char *filename, uint32_t *sampleRate, uint64_t *totalSampleCount) {
	unsigned int channels;
	int16_t *buffer = drwav_open_and_read_file_s16(filename, &channels, sampleRate, totalSampleCount);
	if (buffer == nullptr) {
		ods("[wavRead_int16() buffer==nullptr]\n");
		fprintf(stderr, "ERROR\n");
		return nullptr;
	}
	if (channels != 1) {
		ods("[wavRead_int16() channels!=1]\n");
		drwav_free(buffer);
		buffer = nullptr;
		*sampleRate = 0;
		*totalSampleCount = 0;
	}
	return buffer;
}

bool wav2stream(char *input, FileStream *output) {
	uint32_t sampleRate = 0;
	uint64_t totalSampleCount = 0;
	int16_t *wavBuffer = wavRead_int16(input, &sampleRate, &totalSampleCount);
	if (wavBuffer == nullptr)
	{
		return false;
	}
	WavInfo info = {};
	info.bitsPerSample = 16;
	info.sampleRate = sampleRate;
	info.channels = 1;
	output->SeekBeg();
	output->Append((char *)&info, sizeof(info));
	output->Append((char *)wavBuffer, (size_t)(totalSampleCount * sizeof(int16_t)));
	free(wavBuffer);
	return true;
}

bool stream2wav(FileStream *input, char *output) {
	WavInfo info = {};
	input->SeekBeg();
	size_t read = input->Read(&info, sizeof(info), 1);
	if (read != 1) {
		return false;
	}
	size_t totalSampleCount = (input->Size() - sizeof(info)) / 2;
	return wavWrite_int16(output, (int16_t *)(input->Data() + sizeof(info)), info.sampleRate,
		static_cast<uint32_t>(totalSampleCount));
}

bool Wav2Opus(FileStream *input, FileStream *output) {
	WavInfo in_info = {};
	input->SeekBeg();
	size_t read = input->Read(&in_info, sizeof(in_info), 1);
	if (read != 1) {
		return false;
	}
	uint32_t bitsPerSample = in_info.bitsPerSample;
	uint32_t sampleRate = in_info.sampleRate;
	uint16_t channels = in_info.channels;
	int err = 0;
	if (channels > MAX_CHANNELS) {
		return false;
	}
	OpusEncoder *encoder = opus_encoder_create(sampleRate, channels, OPUS_APPLICATION_AUDIO, &err);
	if (!encoder || err < 0) {
		fprintf(stderr, "failed to create an encoder: %s\n", opus_strerror(err));
		if (!encoder) {
			opus_encoder_destroy(encoder);
		}
		return false;
	}
	const uint16_t *data = (uint16_t *)(input->Data() + sizeof(in_info));
	size_t size = (input->Size() - sizeof(in_info)) / 2;
	opus_int16 pcm_bytes[FRAME_SIZE * MAX_CHANNELS];
	size_t index = 0;
	size_t step = static_cast<size_t>(FRAME_SIZE * channels);
	FileStream encodedData;
	unsigned char cbits[MAX_PACKET_SIZE];
	size_t frameCount = 0;
	size_t readCount = 0;
	while (index < size) {
		memset(&pcm_bytes, 0, sizeof(pcm_bytes));
		if (index + step <= size) {
			memcpy(pcm_bytes, data + index, step * sizeof(uint16_t));
			index += step;
		}
		else {
			readCount = size - index;
			memcpy(pcm_bytes, data + index, (readCount) * sizeof(uint16_t));
			index += readCount;
		}
		int nbBytes = opus_encode(encoder, pcm_bytes, channels * FRAME_SIZE, cbits, MAX_PACKET_SIZE);
		if (nbBytes < 0) {
			fprintf(stderr, "encode failed: %s\n", opus_strerror(nbBytes));
			break;
		}
		++frameCount;
		encodedData.AppendU32(static_cast<uint32_t>(nbBytes));
		encodedData.Append((char *)cbits, static_cast<size_t>(nbBytes));
	}
	WavInfo info = {};
	info.bitsPerSample = bitsPerSample;
	info.sampleRate = sampleRate;
	info.channels = channels;
	output->SeekBeg();
	output->Append((char *)&info, sizeof(info));
	output->Append(encodedData.Data(), encodedData.Size());
	opus_encoder_destroy(encoder);
	return true;
}

bool Opus2Wav(FileStream *input, FileStream *output) {
	WavInfo info = {};
	input->SeekBeg();
	size_t read = input->Read(&info, sizeof(info), 1);
	if (read != 1) {
		return false;
	}
	int channels = info.channels;
	if (channels > MAX_CHANNELS) {
		return false;
	}
	output->SeekBeg();
	output->Append((char *)&info, sizeof(info));
	int err = 0;
	OpusDecoder *decoder = opus_decoder_create(info.sampleRate, channels, &err);
	if (!decoder || err < 0) {
		fprintf(stderr, "failed to create decoder: %s\n", opus_strerror(err));
		if (!decoder) {
			opus_decoder_destroy(decoder);
		}
		return false;
	}
	unsigned char cbits[MAX_PACKET_SIZE];
	opus_int16 out[MAX_FRAME_SIZE * MAX_CHANNELS];
	int frameCount = 0;
	while (true) {
		uint32_t nbBytes;
		size_t readed = input->Read(&nbBytes, sizeof(uint32_t), 1);
		if (readed == 0) {
			break;
		}

		if (nbBytes > sizeof(cbits)) {
			fprintf(stderr, "nbBytes > sizeof(cbits)\n");
			break;
		}
		readed = input->Read(cbits, sizeof(char), nbBytes);
		if (readed != nbBytes) {
			fprintf(stderr, "readed != nbBytes\n");
			break;
		}
		int frame_size = opus_decode(decoder, cbits, nbBytes, out, MAX_FRAME_SIZE, 0);
		if (frame_size < 0) {
			fprintf(stderr, "decoder failed: %s\n", opus_strerror(frame_size));
			break;
		}
		++frameCount;
		output->Append((char *)out, channels * frame_size * sizeof(out[0]));
	}
	opus_decoder_destroy(decoder);
	return true;
}

void splitpath(const char *path, char *drv, char *dir, char *name, char *ext) {
	const char *end;
	const char *p;
	const char *s;
	if (path[0] && path[1] == ':') {
		if (drv) {
			*drv++ = *path++;
			*drv++ = *path++;
			*drv = '\0';
		}
	}
	else if (drv)
		*drv = '\0';
	for (end = path; *end && *end != ':';)
		end++;
	for (p = end; p > path && *--p != '\\' && *p != '/';)
		if (*p == '.') {
			end = p;
			break;
		}
	if (ext)
		for (s = end; (*ext = *s++);)
			ext++;
	for (p = end; p > path;)
		if (*--p == '\\' || *p == '/') {
			p++;
			break;
		}
	if (name) {
		for (s = p; s < end;)
			*name++ = *s++;
		*name = '\0';
	}
	if (dir) {
		for (s = path; s < p;)
			*dir++ = *s++;
		*dir = '\0';
	}
}

void opus2wav(const char *in_file, char *out_file) {
	FileStream input;
	FileStream output;
	input.ReadFromFile(in_file);
	Opus2Wav(&input, &output);
	stream2wav(&output, out_file);
}

void wav2opus(char *in_file, char *out_file) {
	FileStream input;
	FileStream output;
	if (wav2stream(in_file, &input))
	{
		ods("[wav2stream] OK\n");
	}
	else
	{
		ods("[wav2stream] NG\n");
	}
	if (Wav2Opus(&input, &output))
	{
		ods("[Wav2Opus] OK\n");
	}
	else
	{
		ods("[Wav2Opus] NG\n");
	}
	output.WriteToFile(out_file);
}

#if 0
int convert(char *path) {
	char *in_file = path;
	char drive[3];
	char dir[256];
	char fname[256];
	char ext[256];
	char out_file[1024];
	splitpath(in_file, drive, dir, fname, ext);
	if (memcmp(".wav", ext, strlen(ext)) == 0) {
		sprintf_s(out_file, "%s%s%s.opus", drive, dir, fname);
		wav2opus(in_file, out_file);
	}
	else if (memcmp(".opus", ext, strlen(ext)) == 0) {
		sprintf_s(out_file, "%s%s%s_opus.wav", drive, dir, fname);
		opus2wav(in_file, out_file);
	}
	return 0;
}
#endif