YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
SoundFileMp3.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2026-2026 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
7
8#include <yarp/conf/system.h>
9
10#include <yarp/os/NetInt16.h>
11#include <yarp/os/NetInt32.h>
13#include <yarp/os/Vocab.h>
14
15#include <yarp/sig/Sound.h>
16#include <yarp/os/Log.h>
17#include <yarp/os/LogStream.h>
18
19#include <cstdio>
20#include <cstring>
21#include <fstream>
22
23#if defined (YARP_HAS_FFMPEG)
24extern "C"
25{
26 #include <libavutil/opt.h>
27 #include <libavcodec/avcodec.h>
28 #include <libavcodec/version.h>
29 #include <libavutil/channel_layout.h>
30 #include <libavutil/common.h>
31 #include <libavutil/imgutils.h>
32 #include <libavutil/mathematics.h>
33 #include <libavutil/samplefmt.h>
34}
35#endif
36
37using namespace yarp::os;
38using namespace yarp::sig;
39using namespace yarp::sig::file;
40
41namespace
42{
43 YARP_LOG_COMPONENT(SOUNDFILE_MP3, "yarp.sig.SoundFileMp3")
44}
45
46//#######################################################################################################
47#if defined (YARP_HAS_FFMPEG)
48#define AUDIO_INBUF_SIZE 20480
49#define AUDIO_REFILL_THRESH 4096
50#endif
51
52//#######################################################################################################
53#if defined (YARP_HAS_FFMPEG)
55{
56 int i;
57 size_t ch;
58 int ret, data_size;
59 /* send the packet with the compressed data to the decoder */
61 if (ret < 0)
62 {
63 yCError(SOUNDFILE_MP3, "Error submitting the packet to the decoder");
64 return false;
65 }
66
67 /* Get the number of channels */
68#if LIBAVCODEC_VERSION_MAJOR >= 61
69 size_t num_channels = dec_ctx->ch_layout.nb_channels;
70#else
71 size_t num_channels = dec_ctx->channels;
72#endif
73 // sound_block is a newly created sound, that will be filled later.
74
75 sound_block.resize(0, num_channels);
76
77 /* read all the output frames (in general there may be any number of them */
78 while (ret >= 0)
79 {
80 ret = avcodec_receive_frame(dec_ctx, frame);
81 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
82 {
83 // all frames have been decoded
84 break;
85 }
86 else if (ret < 0)
87 {
88 yCError(SOUNDFILE_MP3, "Error during decoding");
89 return false;
90 }
91 //this seems to be 2: S16P
93 if (data_size < 0)
94 {
95 /* This should not occur, checking just for paranoia */
96 yCError(SOUNDFILE_MP3, "Failed to calculate data size\n");
97 return false;
98 }
99
101 frame_sound.resize(frame->nb_samples, num_channels);
102
103 for (i = 0; i < frame->nb_samples; i++) //1152
104 {
105 for (ch = 0; ch < num_channels; ch++) //2
106 {
107 short int val = *((short int*)frame->data[ch] + i);
108 frame_sound.set(val,i,ch);
109 }
110 }
112 }
113 return true;
114}
115
116// FFmpeg >= 7.1 (libavcodec 61.13.100) provides avcodec_get_supported_config(),
117// and FFmpeg 8 (libavcodec 62) removed the AVCodec::sample_fmts,
118// AVCodec::supported_samplerates and AVCodec::ch_layouts fields.
119// These helpers return the same terminated lists (or nullptr if unknown/any).
120#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(61, 13, 100)
121#define YARP_FFMPEG_HAS_GET_SUPPORTED_CONFIG
122template <typename T>
123static const T* get_supported_config(const AVCodec* codec, enum AVCodecConfig config)
124{
125 const void* out = nullptr;
126 if (avcodec_get_supported_config(nullptr, codec, config, 0, &out, nullptr) < 0) {
127 return nullptr;
128 }
129 return static_cast<const T*>(out);
130}
131#endif
132
133static const enum AVSampleFormat* codec_sample_fmts(const AVCodec* codec)
134{
135#ifdef YARP_FFMPEG_HAS_GET_SUPPORTED_CONFIG
137#else
138 return codec->sample_fmts;
139#endif
140}
141
142static const int* codec_supported_samplerates(const AVCodec* codec)
143{
144#ifdef YARP_FFMPEG_HAS_GET_SUPPORTED_CONFIG
146#else
147 return codec->supported_samplerates;
148#endif
149}
150
151int check_sample_fmt(const AVCodec * codec, enum AVSampleFormat sample_fmt)
152{
153 const enum AVSampleFormat* p = codec_sample_fmts(codec);
154 if (!p) {
155 return 1; // all sample formats are supported (or unknown)
156 }
157
158 while (*p != AV_SAMPLE_FMT_NONE)
159 {
160 if (*p == sample_fmt) {
161 return 1;
162 }
163 p++;
164 }
165 return 0;
166}
167
168int select_sample_rate(const AVCodec* codec, int desired_rate)
169{
170 const int* p;
171 int best_samplerate = 0;
172
174 if (!p) {
175 return desired_rate; // Use the desired rate if codec doesn't specify
176 }
177
178 while (*p)
179 {
180 // Find the closest supported rate to the desired rate
181 if (!best_samplerate || abs(desired_rate - *p) < abs(desired_rate - best_samplerate)) {
182 best_samplerate = *p;
183 }
184 p++;
185 }
186 return best_samplerate;
187}
188
189bool encode(AVCodecContext* ctx, AVFrame* frame, AVPacket* pkt, std::fstream& os)
190{
191 int ret;
192
193 // send the frame for encoding
194 ret = avcodec_send_frame(ctx, frame);
195 if (ret < 0)
196 {
197 yCError(SOUNDFILE_MP3, "Error sending the frame to the encoder\n");
198 return false;
199 }
200
201 // read all the available output packets (in general there may be any
202 // number of them
203 while (ret >= 0)
204 {
206 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
207 {
208 return true;
209 }
210 else if (ret < 0)
211 {
212 yCError(SOUNDFILE_MP3, "Error encoding audio frame\n");
213 return false;
214 }
215 os.write((const char*)(pkt->data), pkt->size);
217 }
218 return true;
219}
220
221#if LIBAVCODEC_VERSION_MAJOR >= 61
222// Taken from https://github.com/FFmpeg/FFmpeg/blob/f5ef91e02080316f50d606f5b0b03333bb627ed7/doc/examples/encode_audio.c#L72C1-L92C2
223/* select layout with the highest channel count */
224static int select_channel_layout(const AVCodec *codec, AVChannelLayout *dst)
225{
226 const AVChannelLayout *p, *best_ch_layout=nullptr;
227 int best_nb_channels = 0;
228
229#ifdef YARP_FFMPEG_HAS_GET_SUPPORTED_CONFIG
231#else
232 p = codec->ch_layouts;
233#endif
234 if (!p)
235 {
238 }
239
240 while (p->nb_channels)
241 {
242 int nb_channels = p->nb_channels;
243
245 {
246 best_ch_layout = p;
248 }
249 p++;
250 }
251
252 if (!best_ch_layout)
253 {
254 return -1;
255 }
256
258}
259#else
260// Taken from https://github.com/FFmpeg/FFmpeg/blob/50e9e11316064ecdee889b18a0b6681a248edcf4/doc/examples/encode_audio.c#L72C1-L93C2
261/* select layout with the highest channel count */
262int select_channel_layout(const AVCodec * codec)
263{
264 const uint64_t * p;
266 int best_nb_channels = 0;
267
268 if (!codec->channel_layouts) {
269 return AV_CH_LAYOUT_STEREO;
270 }
271
272 p = codec->channel_layouts;
273 while (*p)
274 {
276
278 {
279 best_ch_layout = *p;
281 }
282 p++;
283 }
284 return best_ch_layout;
285}
286#endif /* LIBAVCODEC_VERSION_MAJOR >= 61 */
287#endif /* defined (YARP_HAS_FFMPEG) */
288
289//#######################################################################################################
290bool yarp::sig::file::write_mp3_file(const Sound& sound_data, const char* filename, size_t bitrate)
291{
292#if !defined (YARP_HAS_FFMPEG)
293
294 yCError(SOUNDFILE_MP3) << "write_mp3_file() not supported: lib ffmpeg not found";
295 return false;
296#else
297 const AVCodec * codec = nullptr;
298 AVCodecContext * c = nullptr;
299 AVFrame * frame = nullptr;
300 AVPacket * pkt = nullptr;
301 int ret;
302 std::fstream fos;
303 uint16_t * samples = nullptr;
304
305#if LIBAVCODEC_VERSION_MAJOR < 58
306 //register all the codecs, deprecated and useless in libffmpeg4.0
308#endif
309
310 // find the MP3 encoder
312 if (!codec)
313 {
314 yCError(SOUNDFILE_MP3, "Codec not found");
315 return false;
316 }
317
318 c = avcodec_alloc_context3(codec);
319 if (!c)
320 {
321 yCError(SOUNDFILE_MP3, "Could not allocate audio codec context");
322 return false;
323 }
324
325 // the compressed output bitrate
326 c->bit_rate = bitrate;
327
328 // check that the encoder supports s16 pcm input
329 c->sample_fmt = AV_SAMPLE_FMT_S16;
330 if (!check_sample_fmt(codec, c->sample_fmt))
331 {
332 yCError(SOUNDFILE_MP3, "Encoder does not support sample format %s",
333 av_get_sample_fmt_name(c->sample_fmt));
334 return false;
335 }
336
337 // select other audio parameters supported by the encoder
338 c->sample_rate = select_sample_rate(codec, sound_data.getFrequency());
339#if LIBAVCODEC_VERSION_MAJOR >= 61
340 // from https://github.com/FFmpeg/FFmpeg/commit/f5ef91e02080316f50d606f5b0b03333bb627ed7#diff-85abeaf18e8c74a972fa1f5ab3c2fdfa7ddc818f9048196c6bd5f63a837b076aL167
341 ret = select_channel_layout(codec, &c->ch_layout);
342 if (ret < 0)
343 {
344 yCError(SOUNDFILE_MP3, "Could not select_channel_layout");
345 return false;
346 }
347#else
348 c->channel_layout = select_channel_layout(codec);
349 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
350#endif
351
352 // open it
353 if (avcodec_open2(c, codec, NULL) < 0)
354 {
355 yCError(SOUNDFILE_MP3, "Could not open codec");
356 return false;
357 }
358
359 fos.open(filename, std::fstream::out | std::fstream::binary);
360 if (fos.is_open()==false)
361 {
362 yCError(SOUNDFILE_MP3, "Cannot open %s for writing", filename);
363 return false;
364 }
365
366 // packet for holding encoded output
368 if (!pkt)
369 {
370 yCError(SOUNDFILE_MP3, "could not allocate the packet");
371 fos.close();
372 return false;
373 }
374
375 // frame containing input raw audio
376 frame = av_frame_alloc();
377 if (!frame)
378 {
379 yCError(SOUNDFILE_MP3, "Could not allocate audio frame");
380 fos.close();
381 return false;
382 }
383
384 frame->nb_samples = c->frame_size;
385 frame->format = c->sample_fmt;
386
387#if LIBAVCODEC_VERSION_MAJOR >= 61
388 // See https://github.com/FFmpeg/FFmpeg/commit/f5ef91e02080316f50d606f5b0b03333bb627ed7#diff-85abeaf18e8c74a972fa1f5ab3c2fdfa7ddc818f9048196c6bd5f63a837b076aL198
389 ret = av_channel_layout_copy(&frame->ch_layout, &c->ch_layout);
390 if (ret < 0)
391 {
392 yCError(SOUNDFILE_MP3, "Could not copy channel layout");
393 fos.close();
394 return false;
395 }
396#else
397 frame->channel_layout = c->channel_layout;
398#endif
399
400 // allocate the data buffers
401 ret = av_frame_get_buffer(frame, 0);
402 if (ret < 0)
403 {
404 yCError(SOUNDFILE_MP3, "Could not allocate audio data buffers");
405 fos.close();
406 return false;
407 }
408
409 // encode
410 size_t soundsize = sound_data.getSamples();
411 size_t nframes = soundsize / c->frame_size;
412 size_t rem_lastframe = soundsize % c->frame_size;
413
414 // Encode full frames
415 for (size_t i = 0; i < nframes; i++)
416 {
417 ret = av_frame_make_writable(frame);
418 if (ret < 0) {
419 av_frame_free(&frame);
422 fos.close();
423 return false;
424 }
425
426#if LIBAVCODEC_VERSION_MAJOR >= 61
427 int ch_layout_nb_channels = c->ch_layout.nb_channels;
428#else
429 int ch_layout_nb_channels = c->channels;
430#endif
431
432 samples = (uint16_t*)frame->data[0];
433 for (int j = 0; j < c->frame_size; j++)
434 {
435 for (int k = 0; k < ch_layout_nb_channels; k++) {
436 samples[j * ch_layout_nb_channels + k] = sound_data.get(j + i * c->frame_size, k);
437 }
438 }
439 if (encode(c, frame, pkt, fos) == false)
440 {
441 yCError(SOUNDFILE_MP3, "Encode failed, memory could be corrupted, should I exit?");
442 }
443 }
444
445 // Encode remaining samples (partial frame) with zero padding
446 if (rem_lastframe > 0)
447 {
448 ret = av_frame_make_writable(frame);
449 if (ret < 0) {
450 av_frame_free(&frame);
453 fos.close();
454 return false;
455 }
456
457#if LIBAVCODEC_VERSION_MAJOR >= 61
458 int ch_layout_nb_channels = c->ch_layout.nb_channels;
459#else
460 int ch_layout_nb_channels = c->channels;
461#endif
462
463 samples = (uint16_t*)frame->data[0];
464
465 // Copy remaining samples
466 for (size_t j = 0; j < rem_lastframe; j++)
467 {
468 for (int k = 0; k < ch_layout_nb_channels; k++) {
469 samples[j * ch_layout_nb_channels + k] = sound_data.get(j + nframes * c->frame_size, k);
470 }
471 }
472
473 // Zero-pad the rest of the frame
474 for (size_t j = rem_lastframe; j < static_cast<size_t>(c->frame_size); j++)
475 {
476 for (int k = 0; k < ch_layout_nb_channels; k++) {
477 samples[j * ch_layout_nb_channels + k] = 0;
478 }
479 }
480
481 if (encode(c, frame, pkt, fos) == false)
482 {
483 yCError(SOUNDFILE_MP3, "Encode failed on partial frame");
484 }
485 }
486
487 // flush the encoder
488 if (encode(c, NULL, pkt, fos) == false)
489 {
490 yCError(SOUNDFILE_MP3, "Encode failed, memory could be corrupted, should I exit?");
491 }
492
493 fos.close();
494
495 av_frame_free(&frame);
498
499 return true;
500#endif
501}
502
503bool read_mp3_istream(Sound& sound_data, std::istream& istream)
504{
505#if !defined (YARP_HAS_FFMPEG)
506 yCError(SOUNDFILE_MP3) << "read_mp3_istream() not supported: lib ffmpeg not found";
507 return false;
508#else
509 // Try to read metadata header (12 bytes) - only present in bytestream format
513
514 // Save current position
515 std::streampos start_pos = istream.tellg();
516
517 // Try to read metadata
518 istream.read((char*)&original_samples, sizeof(uint32_t));
519 istream.read((char*)&original_frequency, sizeof(uint32_t));
520 istream.read((char*)&original_channels, sizeof(uint32_t));
521
522 bool has_metadata = false;
523 if (istream.good())
524 {
525 // Validate metadata - check if values are reasonable
526 // MP3 frequency range: 8000-48000 Hz, channels: 1-2, samples: reasonable range
527 if (original_frequency >= 8000 && original_frequency <= 48000 &&
529 original_samples > 0 && original_samples < 100000000) // max ~30 minutes at 48kHz
530 {
531 has_metadata = true;
532 yCDebug(SOUNDFILE_MP3, "Found metadata: samples=%u, frequency=%u, channels=%u",
534 }
535 else
536 {
537 yCDebug(SOUNDFILE_MP3, "No valid metadata found, seeking back to start");
538 // Reset to start - this is a standard MP3 file without metadata
539 istream.clear();
540 istream.seekg(start_pos);
541 }
542 }
543 else
544 {
545 yCDebug(SOUNDFILE_MP3, "Failed to read metadata, seeking back to start");
546 // Reset to start - this is a standard MP3 file without metadata
547 istream.clear();
548 istream.seekg(start_pos);
549 }
550
551 const AVCodec* codec = nullptr;
552 AVCodecContext* context = nullptr;
553 AVCodecParserContext* parser = nullptr;
554 int len, ret;
556 uint8_t* data = nullptr;
557 size_t data_size;
558 AVPacket* pkt = nullptr;
559 AVFrame* decoded_frame = nullptr;
560
562
563#if LIBAVCODEC_VERSION_MAJOR < 58
564 //register all the codecs, deprecated and useless in libffmpeg4.0
566#endif
567
568 // find the MPEG audio decoder
570 if (!codec)
571 {
572 yCError(SOUNDFILE_MP3, "Codec not found");
573 return false;
574 }
575 parser = av_parser_init(codec->id);
576 if (!parser)
577 {
578 yCError(SOUNDFILE_MP3, "Parser not found");
579 return false;
580 }
581 context = avcodec_alloc_context3(codec);
582 if (!context)
583 {
584 yCError(SOUNDFILE_MP3, "Could not allocate audio codec context");
585 return false;
586 }
587 //open the codec
588 if (avcodec_open2(context, codec, NULL) < 0)
589 {
590 yCError(SOUNDFILE_MP3, "Could not open codec");
591 return false;
592 }
593
594 // decode until eof
595 data = inbuf;
596 istream.read((char*)(inbuf), AUDIO_INBUF_SIZE);
597 data_size = istream.gcount();
598 if (data_size == 0)
599 {
600 yCError(SOUNDFILE_MP3, "Cannot process invalid (empty) stream");
601 return false;
602 }
603
604 // temporary storage of sound frames
605 std::vector<yarp::sig::Sound> vector_of_sound_frames;
606
607 // process the sequence of frames
608 while (data_size > 0)
609 {
610 // add a new empty element to the vector
611 vector_of_sound_frames.emplace_back();
612
613 if (!decoded_frame)
614 {
615 if (!(decoded_frame = av_frame_alloc()))
616 {
617 yCError(SOUNDFILE_MP3, "Could not allocate audio frame");
618 return false;
619 }
620 }
621 ret = av_parser_parse2(parser, context, &pkt->data, &pkt->size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
622 if (ret < 0)
623 {
624 yCError(SOUNDFILE_MP3, "Error while parsing");
625 return false;
626 }
627 data += ret;
628 data_size -= ret;
629 if (pkt->size) {
630 decode(context, pkt, decoded_frame, vector_of_sound_frames.back());
631 }
633 {
634 memmove(inbuf, data, data_size);
635 data = inbuf;
636 istream.read((char*)(data + data_size), AUDIO_INBUF_SIZE - data_size);
637 len = istream.gcount();
638 if (len > 0) {
639 data_size += len;
640 }
641 }
642 }
643
644 // flush the decoder
645 pkt->data = NULL;
646 pkt->size = 0;
647 vector_of_sound_frames.emplace_back(); // the last element
648 decode(context, pkt, decoded_frame, vector_of_sound_frames.back());
649
650 // reconstruct the full sound_data from the vector of frames
651 size_t tot_num_of_samples = 0;
652 for (auto it = vector_of_sound_frames.begin(); it != vector_of_sound_frames.end(); it++)
653 {
654 tot_num_of_samples += it->getSamples();
655 }
656
657 yCDebug(SOUNDFILE_MP3, "Decoded %zu samples total", tot_num_of_samples);
658
659 sound_data.resize(tot_num_of_samples, vector_of_sound_frames[0].getChannels());
660 size_t offset = 0;
661 for (auto it = vector_of_sound_frames.begin(); it != vector_of_sound_frames.end(); it++)
662 {
663 sound_data.overwrite(*it, offset, it->getSamples());
664 offset += it->getSamples();
665 }
666
667 // Use metadata if available, otherwise use decoded values
668 if (has_metadata)
669 {
670 // Trim to original sample count using metadata
672 {
673 yCDebug(SOUNDFILE_MP3, "Trimming from %zu to %u samples using metadata", tot_num_of_samples, original_samples);
675 }
677 }
678 else
679 {
680 // Use frequency from decoder
681 sound_data.setFrequency(context->sample_rate);
682 yCDebug(SOUNDFILE_MP3, "Using decoder frequency: %d Hz", context->sample_rate);
683 }
684
685 yCDebug(SOUNDFILE_MP3, "Final sound: %zu samples, %d Hz, %zu channels",
686 sound_data.getSamples(), sound_data.getFrequency(), sound_data.getChannels());
687
688 //cleanup
689 avcodec_free_context(&context);
690 av_parser_close(parser);
693 return true;
694#endif
695}
696
697bool yarp::sig::file::read_mp3_file(Sound& sound_data, const char* filename)
698{
699 std::fstream fis;
700 fis.open(filename, std::fstream::in | std::fstream::binary);
701 if (fis.is_open() == false)
702 {
703 yCError(SOUNDFILE_MP3, "Cannot open %s for reading", filename);
704 return false;
705 }
706
707 bool b = read_mp3_istream(sound_data, fis);
708 fis.close();
709 return b;
710}
711
713{
714 std::istringstream iss(std::string(bytestream, streamsize));
715 return read_mp3_istream(data, iss);
716}
717
719{
720#if !defined (YARP_HAS_FFMPEG)
721 yCError(SOUNDFILE_MP3) << "write_mp3_bytestream() not supported: lib ffmpeg not found";
722 return false;
723#else
724 const AVCodec * codec = nullptr;
725 AVCodecContext * c = nullptr;
726 AVFrame * frame = nullptr;
727 AVPacket * pkt = nullptr;
728 int ret;
729 std::ostringstream oss(std::ios::binary);
730 uint16_t * samples = nullptr;
731
732#if LIBAVCODEC_VERSION_MAJOR < 58
734#endif
735
736 // find the MP3 encoder
738 if (!codec)
739 {
740 yCError(SOUNDFILE_MP3, "Codec not found");
741 return false;
742 }
743
744 c = avcodec_alloc_context3(codec);
745 if (!c)
746 {
747 yCError(SOUNDFILE_MP3, "Could not allocate audio codec context");
748 return false;
749 }
750
751 // the compressed output bitrate
752 c->bit_rate = 64000;
753
754 // check that the encoder supports s16 pcm input
755 c->sample_fmt = AV_SAMPLE_FMT_S16;
756 if (!check_sample_fmt(codec, c->sample_fmt))
757 {
758 yCError(SOUNDFILE_MP3, "Encoder does not support sample format %s",
759 av_get_sample_fmt_name(c->sample_fmt));
761 return false;
762 }
763
764 // select other audio parameters supported by the encoder
765 c->sample_rate = select_sample_rate(codec, data.getFrequency());
766#if LIBAVCODEC_VERSION_MAJOR >= 61
767 ret = select_channel_layout(codec, &c->ch_layout);
768 if (ret < 0)
769 {
770 yCError(SOUNDFILE_MP3, "Could not select_channel_layout");
772 return false;
773 }
774#else
775 c->channel_layout = select_channel_layout(codec);
776 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
777#endif
778
779 // open it
780 if (avcodec_open2(c, codec, NULL) < 0)
781 {
782 yCError(SOUNDFILE_MP3, "Could not open codec");
784 return false;
785 }
786
787 // Write metadata header BEFORE MP3 data
788 uint32_t original_samples = static_cast<uint32_t>(data.getSamples());
789 uint32_t original_frequency = static_cast<uint32_t>(data.getFrequency());
790 uint32_t original_channels = static_cast<uint32_t>(data.getChannels());
791 oss.write((const char*)&original_samples, sizeof(uint32_t));
792 oss.write((const char*)&original_frequency, sizeof(uint32_t));
793 oss.write((const char*)&original_channels, sizeof(uint32_t));
794
795 // packet for holding encoded output
797 if (!pkt)
798 {
799 yCError(SOUNDFILE_MP3, "could not allocate the packet");
801 return false;
802 }
803
804 // frame containing input raw audio
805 frame = av_frame_alloc();
806 if (!frame)
807 {
808 yCError(SOUNDFILE_MP3, "Could not allocate audio frame");
811 return false;
812 }
813
814 frame->nb_samples = c->frame_size;
815 frame->format = c->sample_fmt;
816
817#if LIBAVCODEC_VERSION_MAJOR >= 61
818 ret = av_channel_layout_copy(&frame->ch_layout, &c->ch_layout);
819 if (ret < 0)
820 {
821 yCError(SOUNDFILE_MP3, "Could not copy channel layout");
822 av_frame_free(&frame);
825 return false;
826 }
827#else
828 frame->channel_layout = c->channel_layout;
829#endif
830
831 // allocate the data buffers
832 ret = av_frame_get_buffer(frame, 0);
833 if (ret < 0)
834 {
835 yCError(SOUNDFILE_MP3, "Could not allocate audio data buffers");
836 av_frame_free(&frame);
839 return false;
840 }
841
842 // Helper lambda to write packet data to ostringstream
843 auto encode_to_stream = [&](AVCodecContext* ctx, AVFrame* frm, AVPacket* p, std::ostringstream& os) -> bool {
844 int r;
846 if (r < 0)
847 {
848 yCError(SOUNDFILE_MP3, "Error sending the frame to the encoder\n");
849 return false;
850 }
851
852 while (r >= 0)
853 {
855 if (r == AVERROR(EAGAIN) || r == AVERROR_EOF)
856 {
857 return true;
858 }
859 else if (r < 0)
860 {
861 yCError(SOUNDFILE_MP3, "Error encoding audio frame\n");
862 return false;
863 }
864 os.write((const char*)(p->data), p->size);
866 }
867 return true;
868 };
869
870 // encode
871 size_t soundsize = data.getSamples();
872 size_t nframes = soundsize / c->frame_size;
873 size_t rem_lastframe = soundsize % c->frame_size;
874
875 // Encode full frames
876 for (size_t i = 0; i < nframes; i++)
877 {
878 ret = av_frame_make_writable(frame);
879 if (ret < 0) {
880 av_frame_free(&frame);
883 return false;
884 }
885
886#if LIBAVCODEC_VERSION_MAJOR >= 61
887 int ch_layout_nb_channels = c->ch_layout.nb_channels;
888#else
889 int ch_layout_nb_channels = c->channels;
890#endif
891
892 samples = (uint16_t*)frame->data[0];
893 for (int j = 0; j < c->frame_size; j++)
894 {
895 for (int k = 0; k < ch_layout_nb_channels; k++) {
896 samples[j * ch_layout_nb_channels + k] = data.get(j + i * c->frame_size, k);
897 }
898 }
899 if (!encode_to_stream(c, frame, pkt, oss))
900 {
901 yCError(SOUNDFILE_MP3, "Encode failed, memory could be corrupted");
902 av_frame_free(&frame);
905 return false;
906 }
907 }
908
909 // Encode remaining samples (partial frame) with zero padding
910 if (rem_lastframe > 0)
911 {
912 ret = av_frame_make_writable(frame);
913 if (ret < 0) {
914 av_frame_free(&frame);
917 return false;
918 }
919
920#if LIBAVCODEC_VERSION_MAJOR >= 61
921 int ch_layout_nb_channels = c->ch_layout.nb_channels;
922#else
923 int ch_layout_nb_channels = c->channels;
924#endif
925
926 samples = (uint16_t*)frame->data[0];
927
928 // Copy remaining samples
929 for (size_t j = 0; j < rem_lastframe; j++)
930 {
931 for (int k = 0; k < ch_layout_nb_channels; k++) {
932 samples[j * ch_layout_nb_channels + k] = data.get(j + nframes * c->frame_size, k);
933 }
934 }
935
936 // Zero-pad the rest of the frame
937 for (size_t j = rem_lastframe; j < static_cast<size_t>(c->frame_size); j++)
938 {
939 for (int k = 0; k < ch_layout_nb_channels; k++) {
940 samples[j * ch_layout_nb_channels + k] = 0;
941 }
942 }
943
944 if (!encode_to_stream(c, frame, pkt, oss))
945 {
946 yCError(SOUNDFILE_MP3, "Encode failed on partial frame");
947 av_frame_free(&frame);
950 return false;
951 }
952 }
953
954 // flush the encoder
955 if (!encode_to_stream(c, NULL, pkt, oss))
956 {
957 yCError(SOUNDFILE_MP3, "Encode failed during flush");
958 av_frame_free(&frame);
961 return false;
962 }
963
964 // Get the encoded data from the ostringstream
965 std::string encoded_data = oss.str();
966 size_t encoded_size = encoded_data.size();
967
968 // FIX: Handle buffer size query separately from error condition
969 if (bytestream == nullptr)
970 {
971 // Caller is querying required buffer size - this is SUCCESS
972 // Add 12 bytes for the metadata header
974 av_frame_free(&frame);
977 return true;
978 }
979
980 // Check if the provided buffer is large enough
982 {
983 // Buffer too small - this is an ERROR
984 yCError(SOUNDFILE_MP3, "Buffer too small: provided %zu bytes, need %zu bytes", streamsize, encoded_size);
986 av_frame_free(&frame);
989 return false;
990 }
991
992 // Copy the encoded data to the output buffer
995
996 // Cleanup
997 av_frame_free(&frame);
1000
1001 return true;
1002#endif
1003}
bool read_mp3_istream(Sound &sound_data, std::istream &istream)
A mini-server for performing network communication in the background.
void close() override
Stop port activity.
bool open(const std::string &name) override
Start port operation, with a specific name, with automatically-chosen network parameters.
T * read(bool shouldWait=true) override
Read an available object from the port.
void write(bool forceStrict=false)
Write the current object being returned by BufferedPort::prepare.
Class for storing sounds See Audio in YARP for additional documentation on YARP audio.
Definition Sound.h:39
void setFrequency(int freq)
Set the frequency of the sound (i.e.
Definition Sound.cpp:369
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
void overwrite(const Sound &alt, size_t offset=0, size_t len=0)
It overwrites the sound with another sound, starting from a specified offset.
Definition Sound.cpp:83
audio_sample get(size_t sample, size_t channel=0) const
Definition Sound.cpp:291
size_t getSamples() const
Get the number of samples contained in the sound.
Definition Sound.cpp:664
#define yCError(component,...)
#define yCDebug(component,...)
#define YARP_LOG_COMPONENT(name,...)
NetInt32 encode(const std::string &str)
Convert a string into a vocabulary identifier.
Definition Vocab32.cpp:11
std::string decode(NetInt32 code)
Convert a vocabulary identifier into a string.
Definition Vocab32.cpp:33
An interface to the operating system, including Port based communication.
bool write_mp3_file(const Sound &data, const char *filename, size_t bitrate=64000)
Write a sound to a mp3 file.
bool write_mp3_bytestream(const Sound &data, char *bytestream, size_t &streamsize)
write a sound from a byte array.
bool read_mp3_file(Sound &data, const char *filename)
Read a sound from a .mp3 audio file.
bool read_mp3_bytestream(Sound &data, const char *bytestream, size_t streamsize)
Read a sound from a byte array.