YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
SoundFileWav.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
8
9#include <yarp/conf/system.h>
10
11#include <yarp/os/NetInt16.h>
12#include <yarp/os/NetInt32.h>
14#include <yarp/os/Vocab.h>
15
16#include <yarp/sig/Sound.h>
17#include <yarp/os/Log.h>
18#include <yarp/os/LogStream.h>
19
20#include <cstdio>
21#include <cstring>
22
23using namespace yarp::os;
24using namespace yarp::sig;
25using namespace yarp::sig::file;
26
27namespace
28{
29 YARP_LOG_COMPONENT(SOUNDFILE_WAV, "yarp.sig.SoundFileWav")
30}
31
63
65{
66 yCTrace(SOUNDFILE_WAV, "bool PcmWavHeader::parse_from_file(FILE *fp)\n");
67
68 size_t ret;
69
70 ret = fread(&wavHeader, sizeof(wavHeader), 1, fp);
71 if (ret != 1) {
72 yCError(SOUNDFILE_WAV, "failed to read .wav file");
73 return false;
74 }
75
76 ret = fread(&wavLength, sizeof(wavLength), 1, fp);
77 if (ret != 1) {
78 yCError(SOUNDFILE_WAV, "failed to read .wav file");
79 return false;
80 }
81
82 ret = fread(&formatHeader1, sizeof(formatHeader1), 1, fp);
83 if (ret != 1) {
84 yCError(SOUNDFILE_WAV, "failed to read .wav file");
85 return false;
86 }
87
88 ret = fread(&formatHeader2, sizeof(formatHeader2), 1, fp);
89 if (ret != 1) {
90 yCError(SOUNDFILE_WAV, "failed to read .wav file");
91 return false;
92 }
93
94 ret = fread(&formatLength, sizeof(formatLength), 1, fp);
95 if (ret != 1) {
96 yCError(SOUNDFILE_WAV, "failed to read .wav file");
97 return false;
98 }
99
100 ret = fread(&pcm.pcmFormatTag, sizeof(pcm.pcmFormatTag), 1, fp);
101 if (ret != 1) {
102 yCError(SOUNDFILE_WAV, "failed to read .wav file");
103 return false;
104 }
105
106 ret = fread(&pcm.pcmChannels, sizeof(pcm.pcmChannels), 1, fp);
107 if (ret != 1) {
108 yCError(SOUNDFILE_WAV, "failed to read .wav file");
109 return false;
110 }
111 if (pcm.pcmChannels <= 0)
112 {
113 yCError(SOUNDFILE_WAV, "pcmChannels <=0, invalid wav file\n");
114 return false;
115 }
116
117 ret = fread(&pcm.pcmSamplesPerSecond, sizeof(pcm.pcmSamplesPerSecond), 1, fp);
118 if (ret != 1) {
119 yCError(SOUNDFILE_WAV, "failed to read .wav file");
120 return false;
121 }
122 if (pcm.pcmSamplesPerSecond <= 0)
123 {
124 yCError(SOUNDFILE_WAV, "pcmSamplesPerSecond <=0, invalid wav file\n");
125 return false;
126 }
127
128 ret = fread(&pcm.pcmBytesPerSecond, sizeof(pcm.pcmBytesPerSecond), 1, fp);
129 if (ret != 1) {
130 yCError(SOUNDFILE_WAV, "failed to read .wav file");
131 return false;
132 }
133 if (pcm.pcmBytesPerSecond <= 0)
134 {
135 yCError(SOUNDFILE_WAV, "pcmBytesPerSecond <=0, invalid wav file\n");
136 return false;
137 }
138
139 ret = fread(&pcm.pcmBlockAlign, sizeof(pcm.pcmBlockAlign), 1, fp);
140 if (ret != 1) {
141 yCError(SOUNDFILE_WAV, "failed to read .wav file");
142 return false;
143 }
144
145 ret = fread(&pcm.pcmBitsPerSample, sizeof(pcm.pcmBitsPerSample), 1, fp);
146 if (ret != 1) {
147 yCError(SOUNDFILE_WAV, "failed to read .wav file");
148 return false;
149 }
150 if (pcm.pcmBitsPerSample != 16)
151 {
152 yCError(SOUNDFILE_WAV, "sorry, lousy .wav read code only does 16-bit ints\n");
153 return false;
154 }
155
156 //extra bytes in pcm chuck
157 int extra_size = formatLength - sizeof(pcm);
158 if (extra_size != 0)
159 {
160 yCError(SOUNDFILE_WAV, "extra_size = %d\n", extra_size);
162 ret = fread(pcmExtraData.get(), extra_size, 1, fp);
163 if (ret != 1) {
164 yCError(SOUNDFILE_WAV, "failed to read .wav file");
165 return false;
166 }
167 }
168
169 //extra chunks
170 ret = fread(&dummyHeader, sizeof(dummyHeader), 1, fp);
171 if (ret != 1) {
172 yCError(SOUNDFILE_WAV, "failed to read .wav file");
173 return false;
174 }
175
176 while (dummyHeader != yarp::os::createVocab32('d', 'a', 't', 'a'))
177 {
178 ret = fread(&dummyLength, sizeof(dummyLength), 1, fp);
179 if (ret != 1) {
180 yCError(SOUNDFILE_WAV, "failed to read .wav file");
181 return false;
182 }
185 ret = fread(dummyData.get(), dummyLength, 1, fp);
186 if (ret != 1) {
187 yCError(SOUNDFILE_WAV, "failed to read .wav file");
188 return false;
189 }
190 ret = fread(&dummyHeader, sizeof(dummyHeader), 1, fp);
191 if (ret != 1) {
192 yCError(SOUNDFILE_WAV, "failed to read .wav file");
193 return false;
194 }
195 }
196
198 ret = fread(&dataLength, sizeof(dataLength), 1, fp);
199 if (ret != 1) {
200 yCError(SOUNDFILE_WAV, "failed to read .wav file");
201 return false;
202 }
203
204 return true;
205}
206
208{
209 int bitsPerSample = 16;
210 size_t channels = src.getChannels();
211 size_t bytes = channels*src.getSamples()*2;
212 int align = channels*((bitsPerSample+7)/8);
213
214 wavHeader = yarp::os::createVocab32('R','I','F','F');
215 wavLength = bytes + sizeof(PcmWavHeader) - 2*sizeof(NetInt32);
216 formatHeader1 = yarp::os::createVocab32('W','A','V','E');
217 formatHeader2 = yarp::os::createVocab32('f','m','t',' ');
218 formatLength = sizeof(pcm);
219
220 pcm.pcmFormatTag = 1; /* PCM! */
221 pcm.pcmChannels = channels;
222 pcm.pcmSamplesPerSecond = (int)src.getFrequency();
223 pcm.pcmBytesPerSecond = align*pcm.pcmSamplesPerSecond;
224 pcm.pcmBlockAlign = align;
225 pcm.pcmBitsPerSample = bitsPerSample;
226
227 dataHeader = yarp::os::createVocab32('d','a','t','a');
228 dataLength = bytes;
229
230
231 fwrite(&wavHeader,sizeof(wavHeader),1,fp);
232 fwrite(&wavLength,sizeof(wavLength),1,fp);
234
237
238 fwrite(&pcm.pcmFormatTag,sizeof(pcm.pcmFormatTag),1,fp);
239 fwrite(&pcm.pcmChannels,sizeof(pcm.pcmChannels),1,fp);
240 fwrite(&pcm.pcmSamplesPerSecond,sizeof(pcm.pcmSamplesPerSecond),1,fp);
241 fwrite(&pcm.pcmBytesPerSecond,sizeof(pcm.pcmBytesPerSecond),1,fp);
242 fwrite(&pcm.pcmBlockAlign,sizeof(pcm.pcmBlockAlign),1,fp);
243 fwrite(&pcm.pcmBitsPerSample,sizeof(pcm.pcmBitsPerSample),1,fp);
244
245 fwrite(&dataHeader,sizeof(dataHeader),1,fp);
246 fwrite(&dataLength,sizeof(dataLength),1,fp);
247
248}
249
251{
252 int bitsPerSample = 16;
253 size_t channels = src.getChannels();
254 size_t bytes = channels*src.getSamples()*2;
255 int align = channels*((bitsPerSample+7)/8);
256
257 // Calculate sizes for marker chunks
258 size_t num_markers = src.getMarkersCount();
259
260 // Size of cue chunk: 4 bytes (chunk ID) + 4 bytes (chunk size) + 4 bytes (num cue points) + 24 bytes per cue point
261 size_t cue_chunk_size = 0;
262 if (num_markers > 0) {
263 cue_chunk_size = 4 + 4 + (4 + num_markers * 24);
264 }
265
266 // Size of LIST/adtl chunk for labels: 4 bytes (LIST) + 4 bytes (size) + 4 bytes (adtl) + labels
267 size_t list_chunk_size = 0;
268 if (num_markers > 0)
269 {
270 list_chunk_size = 4 + 4 + 4; // LIST + size + adtl
271 for (size_t i = 0; i < num_markers; i++)
272 {
274 // Each label chunk: 'labl' (4) + size (4) + cue point ID (4) + null-terminated string
275 size_t label_len = marker.label.length() + 1; // +1 for null terminator
276 if (label_len % 2) label_len++; // Pad to even number
277 list_chunk_size += 4 + 4 + 4 + label_len;
278 }
279 }
280
281 wavHeader = yarp::os::createVocab32('R','I','F','F');
282 wavLength = bytes + sizeof(PcmWavHeader) - 2*sizeof(NetInt32) + cue_chunk_size + list_chunk_size;
283 formatHeader1 = yarp::os::createVocab32('W','A','V','E');
284 formatHeader2 = yarp::os::createVocab32('f','m','t',' ');
285 formatLength = sizeof(pcm);
286
287 pcm.pcmFormatTag = 1; /* PCM! */
288 pcm.pcmChannels = channels;
289 pcm.pcmSamplesPerSecond = (int)src.getFrequency();
290 pcm.pcmBytesPerSecond = align*pcm.pcmSamplesPerSecond;
291 pcm.pcmBlockAlign = align;
292 pcm.pcmBitsPerSample = bitsPerSample;
293
294 dataHeader = yarp::os::createVocab32('d','a','t','a');
295 dataLength = bytes;
296
297 // Write RIFF header
298 fwrite(&wavHeader,sizeof(wavHeader),1,fp);
299 fwrite(&wavLength,sizeof(wavLength),1,fp);
301
302 // Write fmt chunk
305
306 fwrite(&pcm.pcmFormatTag,sizeof(pcm.pcmFormatTag),1,fp);
307 fwrite(&pcm.pcmChannels,sizeof(pcm.pcmChannels),1,fp);
308 fwrite(&pcm.pcmSamplesPerSecond,sizeof(pcm.pcmSamplesPerSecond),1,fp);
309 fwrite(&pcm.pcmBytesPerSecond,sizeof(pcm.pcmBytesPerSecond),1,fp);
310 fwrite(&pcm.pcmBlockAlign,sizeof(pcm.pcmBlockAlign),1,fp);
311 fwrite(&pcm.pcmBitsPerSample,sizeof(pcm.pcmBitsPerSample),1,fp);
312
313 // Write cue chunk if markers exist
314 if (num_markers > 0) {
315 NetInt32 cueHeader = yarp::os::createVocab32('c','u','e',' ');
316 NetInt32 cueChunkSize = 4 + num_markers * 24; // 4 bytes for num cue points + 24 bytes per cue point
318
319 fwrite(&cueHeader, sizeof(cueHeader), 1, fp);
320 fwrite(&cueChunkSize, sizeof(cueChunkSize), 1, fp);
321 fwrite(&numCuePoints, sizeof(numCuePoints), 1, fp);
322
323 // Write each cue point
324 for (size_t i = 0; i < num_markers; i++) {
326
327 NetInt32 cuePointId = i + 1; // Cue point IDs start from 1
328 NetInt32 position = marker.sample_id;
329 NetInt32 dataChunkId = yarp::os::createVocab32('d','a','t','a');
330 NetInt32 chunkStart = 0;
331 NetInt32 blockStart = 0;
332 NetInt32 sampleOffset = position;
333
334 fwrite(&cuePointId, sizeof(cuePointId), 1, fp);
335 fwrite(&position, sizeof(position), 1, fp);
336 fwrite(&dataChunkId, sizeof(dataChunkId), 1, fp);
337 fwrite(&chunkStart, sizeof(chunkStart), 1, fp);
338 fwrite(&blockStart, sizeof(blockStart), 1, fp);
339 fwrite(&sampleOffset, sizeof(sampleOffset), 1, fp);
340 }
341 }
342
343 // Write LIST/adtl chunk with labels if markers exist
344 if (num_markers > 0) {
346 NetInt32 listChunkSize = list_chunk_size - 8; // Total size minus 'LIST' and size fields
348
349 fwrite(&listHeader, sizeof(listHeader), 1, fp);
350 fwrite(&listChunkSize, sizeof(listChunkSize), 1, fp);
351 fwrite(&adtlHeader, sizeof(adtlHeader), 1, fp);
352
353 // Write each label
354 for (size_t i = 0; i < num_markers; i++) {
356
358 NetInt32 cuePointId = i + 1;
359
360 std::string label = marker.label;
361 size_t label_len = label.length() + 1; // +1 for null terminator
362 bool need_pad = (label_len % 2) == 1;
363 if (need_pad) label_len++;
364
365 NetInt32 lablChunkSize = 4 + label_len; // 4 bytes for cue point ID + label string
366
367 fwrite(&lablHeader, sizeof(lablHeader), 1, fp);
368 fwrite(&lablChunkSize, sizeof(lablChunkSize), 1, fp);
369 fwrite(&cuePointId, sizeof(cuePointId), 1, fp);
370 fwrite(label.c_str(), label.length() + 1, 1, fp); // Write null-terminated string
371
372 if (need_pad) {
373 char pad = 0;
374 fwrite(&pad, 1, 1, fp);
375 }
376 }
377 }
378
379 // Write data chunk header
380 fwrite(&dataHeader,sizeof(dataHeader),1,fp);
381 fwrite(&dataLength,sizeof(dataLength),1,fp);
382}
383
384//#######################################################################################################
385
386bool yarp::sig::file::read_wav_file(Sound& sound_data, const char * filename)
387{
388 FILE *fp = fopen(filename, "rb");
389 if (!fp) {
390 yCError(SOUNDFILE_WAV, "cannot open file %s for reading\n", filename);
391 return false;
392 }
393
394 PcmWavHeader header;
395 if (!header.parse_from_file(fp))
396 {
397 yCError(SOUNDFILE_WAV, "error parsing header of file %s\n", filename);
398 fclose(fp);
399 return false;
400 };
401
402
403 int freq = header.pcm.pcmSamplesPerSecond;
404 int channels = header.pcm.pcmChannels;
405 int bits = header.pcm.pcmBitsPerSample;
406 int samples = header.dataLength/(bits/8)/channels;
407 sound_data.resize(samples,channels);
408 sound_data.setFrequency(freq);
409 ManagedBytes bytes(header.dataLength);
410 yCDebug(SOUNDFILE_WAV, "%d channels %d samples %d frequency\n", channels, samples, freq);
411
412 size_t result;
413 result = fread(bytes.get(),bytes.length(),1,fp);
414 YARP_UNUSED(result);
415
416 auto* data = reinterpret_cast<NetInt16*>(bytes.get());
417 int ct = 0;
418 for (int i=0; i<samples; i++) {
419 for (int j=0; j<channels; j++) {
420 sound_data.set(data[ct],i,j);
421 ct++;
422 }
423 }
424
425 fclose(fp);
426 return true;
427}
428
430{
431 yCError(SOUNDFILE_WAV, "read_wav_bytestream() Not yet implemented");
432 return false;
433}
434
436{
437 yCError(SOUNDFILE_WAV, "write_wav_bytestream() Not yet implemented");
438 streamsize = 0;
439 return false;
440}
441
442bool yarp::sig::file::write_wav_file(const Sound& sound_data, const char * filename)
443{
444 FILE *fp = fopen(filename, "wb");
445 if (!fp) {
446 yCError(SOUNDFILE_WAV, "cannot open file %s for writing\n", filename);
447 return false;
448 }
449
450 PcmWavHeader header;
451
452 // Use the new method if markers are present, otherwise use the old method
453 if (sound_data.getMarkersCount() > 0) {
454 header.setup_to_write_with_markers(sound_data, fp);
455 } else {
456 header.setup_to_write(sound_data, fp);
457 }
458
459 ManagedBytes bytes(header.dataLength);
460 auto* data = reinterpret_cast<NetInt16*>(bytes.get());
461 int ct = 0;
462 size_t samples = sound_data.getSamples();
463 size_t channels = sound_data.getChannels();
464 for (size_t i=0; i<samples; i++) {
465 for (size_t j=0; j<channels; j++) {
466 int v = sound_data.get(i,j);
467 data[ct] = v;
468 ct++;
469 }
470 }
471 fwrite(bytes.get(),bytes.length(),1,fp);
472
473 fclose(fp);
474
475 // Write Audacity label file if markers are present
476 if (sound_data.getMarkersCount() > 0)
477 {
478 std::string label_filename(filename);
479 size_t dot_pos = label_filename.find_last_of('.');
480 if (dot_pos != std::string::npos)
481 {
483 }
484 label_filename += ".txt";
485
486 FILE *label_fp = fopen(label_filename.c_str(), "w");
487 if (!label_fp)
488 {
489 yCWarning(SOUNDFILE_WAV, "cannot open file %s for writing Audacity labels\n", label_filename.c_str());
490 }
491 else
492 {
493 double frequency = sound_data.getFrequency();
494 for (size_t i = 0; i < sound_data.getMarkersCount(); i++)
495 {
496 SoundMarker marker = sound_data.getMarker(i);
497 double time_seconds = static_cast<double>(marker.sample_id) / frequency;
498 // Audacity label format: start_time\tend_time\tlabel
499 // For point labels, start and end time are the same
500 fprintf(label_fp, "%.6f\t%.6f\t%s\n", time_seconds, time_seconds, marker.label.c_str());
501 }
503 yCInfo(SOUNDFILE_WAV, "Audacity label file written: %s\n", label_filename.c_str());
504 }
505 }
506
507 return true;
508}
NetInt32 formatLength
NetInt32 pcmSamplesPerSecond
NetInt32 dummyHeader
NetInt32 dummyLength
ManagedBytes pcmExtraData
NetInt32 wavLength
void setup_to_write(const Sound &sound, FILE *fp)
NetInt16 pcmFormatTag
NetInt32 dataHeader
NetInt32 pcmBytesPerSecond
NetInt16 pcmChannels
NetInt32 dataLength
void setup_to_write_with_markers(const Sound &sound, FILE *fp)
NetInt16 pcmBlockAlign
struct PcmWavHeader::@86 pcm
ManagedBytes dummyData
NetInt32 formatHeader2
NetInt32 formatHeader1
NetInt16 pcmBitsPerSample
bool parse_from_file(FILE *fp)
NetInt32 wavHeader
A mini-server for performing network communication in the background.
An abstraction for a block of bytes, with optional responsibility for allocating/destroying that bloc...
void clear()
Disassociate object with any data block (deleting block if appropriate).
void allocate(size_t len)
Makes a data block of the specified length that will be deleted if this object is destroyed.
const char * get() const
Class for storing sounds See Audio in YARP for additional documentation on YARP audio.
Definition Sound.h:39
size_t getMarkersCount() const
Gets the number of markers contained in the sound.
Definition Sound.cpp:794
void setFrequency(int freq)
Set the frequency of the sound (i.e.
Definition Sound.cpp:369
yarp::sig::SoundMarker getMarker(size_t index) const
Get the marker at the specified index.
Definition Sound.cpp:799
size_t getChannels() const
Get the number of channels of the sound.
Definition Sound.cpp:669
void resize(size_t samples, size_t channels=1)
Set the sound size.
Definition Sound.cpp:267
int getFrequency() const
Get the frequency of the sound (i.e.
Definition Sound.cpp:364
audio_sample get(size_t sample, size_t channel=0) const
Definition Sound.cpp:291
void set(audio_sample value, size_t sample, size_t channel=0)
Definition Sound.cpp:342
size_t getSamples() const
Get the number of samples contained in the sound.
Definition Sound.cpp:664
#define yCInfo(component,...)
#define yCError(component,...)
#define yCTrace(component,...)
#define yCWarning(component,...)
#define yCDebug(component,...)
#define YARP_LOG_COMPONENT(name,...)
An interface to the operating system, including Port based communication.
std::int16_t NetInt16
Definition of the NetInt16 type.
Definition NetInt16.h:29
std::int32_t NetInt32
Definition of the NetInt32 type.
Definition NetInt32.h:29
constexpr yarp::conf::vocab32_t createVocab32(char a, char b=0, char c=0, char d=0)
Create a vocab from chars.
Definition Vocab32.h:27
bool read_wav_file(Sound &data, const char *filename)
Read a sound from a .wav audio file.
bool read_wav_bytestream(Sound &data, const char *bytestream, size_t streamsize)
Read a sound from a byte array.
bool write_wav_bytestream(const Sound &data, char *bytestream, size_t &streamsize)
Write a sound to a byte array.
bool write_wav_file(const Sound &data, const char *filename)
Write a sound to a .wav file.
#define YARP_END_PACK
Ends 1 byte packing for structs/classes.
Definition system.h:193
#define YARP_BEGIN_PACK
Starts 1 byte packing for structs/classes.
Definition system.h:192
#define YARP_UNUSED(var)
Definition api.h:162