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
116int check_sample_fmt(const AVCodec * codec, enum AVSampleFormat sample_fmt)
117{
118 const enum AVSampleFormat* p = codec->sample_fmts;
119
120 while (*p != AV_SAMPLE_FMT_NONE)
121 {
122 if (*p == sample_fmt) {
123 return 1;
124 }
125 p++;
126 }
127 return 0;
128}
129
130int select_sample_rate(const AVCodec* codec, int desired_rate)
131{
132 const int* p;
133 int best_samplerate = 0;
134
135 if (!codec->supported_samplerates) {
136 return desired_rate; // Use the desired rate if codec doesn't specify
137 }
138
139 p = codec->supported_samplerates;
140 while (*p)
141 {
142 // Find the closest supported rate to the desired rate
143 if (!best_samplerate || abs(desired_rate - *p) < abs(desired_rate - best_samplerate)) {
144 best_samplerate = *p;
145 }
146 p++;
147 }
148 return best_samplerate;
149}
150
151bool encode(AVCodecContext* ctx, AVFrame* frame, AVPacket* pkt, std::fstream& os)
152{
153 int ret;
154
155 // send the frame for encoding
156 ret = avcodec_send_frame(ctx, frame);
157 if (ret < 0)
158 {
159 yCError(SOUNDFILE_MP3, "Error sending the frame to the encoder\n");
160 return false;
161 }
162
163 // read all the available output packets (in general there may be any
164 // number of them
165 while (ret >= 0)
166 {
168 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
169 {
170 return true;
171 }
172 else if (ret < 0)
173 {
174 yCError(SOUNDFILE_MP3, "Error encoding audio frame\n");
175 return false;
176 }
177 os.write((const char*)(pkt->data), pkt->size);
179 }
180 return true;
181}
182
183#if LIBAVCODEC_VERSION_MAJOR >= 61
184// Taken from https://github.com/FFmpeg/FFmpeg/blob/f5ef91e02080316f50d606f5b0b03333bb627ed7/doc/examples/encode_audio.c#L72C1-L92C2
185/* select layout with the highest channel count */
186static int select_channel_layout(const AVCodec *codec, AVChannelLayout *dst)
187{
188 const AVChannelLayout *p, *best_ch_layout=nullptr;
189 int best_nb_channels = 0;
190
191 if (!codec->ch_layouts)
192 {
195 }
196
197 p = codec->ch_layouts;
198 while (p->nb_channels)
199 {
200 int nb_channels = p->nb_channels;
201
203 {
204 best_ch_layout = p;
206 }
207 p++;
208 }
209
210 if (!best_ch_layout)
211 {
212 return -1;
213 }
214
216}
217#else
218// Taken from https://github.com/FFmpeg/FFmpeg/blob/50e9e11316064ecdee889b18a0b6681a248edcf4/doc/examples/encode_audio.c#L72C1-L93C2
219/* select layout with the highest channel count */
220int select_channel_layout(const AVCodec * codec)
221{
222 const uint64_t * p;
224 int best_nb_channels = 0;
225
226 if (!codec->channel_layouts) {
227 return AV_CH_LAYOUT_STEREO;
228 }
229
230 p = codec->channel_layouts;
231 while (*p)
232 {
234
236 {
237 best_ch_layout = *p;
239 }
240 p++;
241 }
242 return best_ch_layout;
243}
244#endif /* LIBAVCODEC_VERSION_MAJOR >= 61 */
245#endif /* defined (YARP_HAS_FFMPEG) */
246
247//#######################################################################################################
248bool yarp::sig::file::write_mp3_file(const Sound& sound_data, const char* filename, size_t bitrate)
249{
250#if !defined (YARP_HAS_FFMPEG)
251
252 yCError(SOUNDFILE_MP3) << "write_mp3_file() not supported: lib ffmpeg not found";
253 return false;
254#else
255 const AVCodec * codec = nullptr;
256 AVCodecContext * c = nullptr;
257 AVFrame * frame = nullptr;
258 AVPacket * pkt = nullptr;
259 int ret;
260 std::fstream fos;
261 uint16_t * samples = nullptr;
262
263#if LIBAVCODEC_VERSION_MAJOR < 58
264 //register all the codecs, deprecated and useless in libffmpeg4.0
266#endif
267
268 // find the MP3 encoder
270 if (!codec)
271 {
272 yCError(SOUNDFILE_MP3, "Codec not found");
273 return false;
274 }
275
276 c = avcodec_alloc_context3(codec);
277 if (!c)
278 {
279 yCError(SOUNDFILE_MP3, "Could not allocate audio codec context");
280 return false;
281 }
282
283 // the compressed output bitrate
284 c->bit_rate = bitrate;
285
286 // check that the encoder supports s16 pcm input
287 c->sample_fmt = AV_SAMPLE_FMT_S16;
288 if (!check_sample_fmt(codec, c->sample_fmt))
289 {
290 yCError(SOUNDFILE_MP3, "Encoder does not support sample format %s",
291 av_get_sample_fmt_name(c->sample_fmt));
292 return false;
293 }
294
295 // select other audio parameters supported by the encoder
296 c->sample_rate = select_sample_rate(codec, sound_data.getFrequency());
297#if LIBAVCODEC_VERSION_MAJOR >= 61
298 // from https://github.com/FFmpeg/FFmpeg/commit/f5ef91e02080316f50d606f5b0b03333bb627ed7#diff-85abeaf18e8c74a972fa1f5ab3c2fdfa7ddc818f9048196c6bd5f63a837b076aL167
299 ret = select_channel_layout(codec, &c->ch_layout);
300 if (ret < 0)
301 {
302 yCError(SOUNDFILE_MP3, "Could not select_channel_layout");
303 return false;
304 }
305#else
306 c->channel_layout = select_channel_layout(codec);
307 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
308#endif
309
310 // open it
311 if (avcodec_open2(c, codec, NULL) < 0)
312 {
313 yCError(SOUNDFILE_MP3, "Could not open codec");
314 return false;
315 }
316
317 fos.open(filename, std::fstream::out | std::fstream::binary);
318 if (fos.is_open()==false)
319 {
320 yCError(SOUNDFILE_MP3, "Cannot open %s for writing", filename);
321 return false;
322 }
323
324 // packet for holding encoded output
326 if (!pkt)
327 {
328 yCError(SOUNDFILE_MP3, "could not allocate the packet");
329 fos.close();
330 return false;
331 }
332
333 // frame containing input raw audio
334 frame = av_frame_alloc();
335 if (!frame)
336 {
337 yCError(SOUNDFILE_MP3, "Could not allocate audio frame");
338 fos.close();
339 return false;
340 }
341
342 frame->nb_samples = c->frame_size;
343 frame->format = c->sample_fmt;
344
345#if LIBAVCODEC_VERSION_MAJOR >= 61
346 // See https://github.com/FFmpeg/FFmpeg/commit/f5ef91e02080316f50d606f5b0b03333bb627ed7#diff-85abeaf18e8c74a972fa1f5ab3c2fdfa7ddc818f9048196c6bd5f63a837b076aL198
347 ret = av_channel_layout_copy(&frame->ch_layout, &c->ch_layout);
348 if (ret < 0)
349 {
350 yCError(SOUNDFILE_MP3, "Could not copy channel layout");
351 fos.close();
352 return false;
353 }
354#else
355 frame->channel_layout = c->channel_layout;
356#endif
357
358 // allocate the data buffers
359 ret = av_frame_get_buffer(frame, 0);
360 if (ret < 0)
361 {
362 yCError(SOUNDFILE_MP3, "Could not allocate audio data buffers");
363 fos.close();
364 return false;
365 }
366
367 // encode
368 size_t soundsize = sound_data.getSamples();
369 size_t nframes = soundsize / c->frame_size;
370 size_t rem_lastframe = soundsize % c->frame_size;
371
372 // Encode full frames
373 for (size_t i = 0; i < nframes; i++)
374 {
375 ret = av_frame_make_writable(frame);
376 if (ret < 0) {
377 av_frame_free(&frame);
380 fos.close();
381 return false;
382 }
383
384#if LIBAVCODEC_VERSION_MAJOR >= 61
385 int ch_layout_nb_channels = c->ch_layout.nb_channels;
386#else
387 int ch_layout_nb_channels = c->channels;
388#endif
389
390 samples = (uint16_t*)frame->data[0];
391 for (int j = 0; j < c->frame_size; j++)
392 {
393 for (int k = 0; k < ch_layout_nb_channels; k++) {
394 samples[j * ch_layout_nb_channels + k] = sound_data.get(j + i * c->frame_size, k);
395 }
396 }
397 if (encode(c, frame, pkt, fos) == false)
398 {
399 yCError(SOUNDFILE_MP3, "Encode failed, memory could be corrupted, should I exit?");
400 }
401 }
402
403 // Encode remaining samples (partial frame) with zero padding
404 if (rem_lastframe > 0)
405 {
406 ret = av_frame_make_writable(frame);
407 if (ret < 0) {
408 av_frame_free(&frame);
411 fos.close();
412 return false;
413 }
414
415#if LIBAVCODEC_VERSION_MAJOR >= 61
416 int ch_layout_nb_channels = c->ch_layout.nb_channels;
417#else
418 int ch_layout_nb_channels = c->channels;
419#endif
420
421 samples = (uint16_t*)frame->data[0];
422
423 // Copy remaining samples
424 for (size_t j = 0; j < rem_lastframe; j++)
425 {
426 for (int k = 0; k < ch_layout_nb_channels; k++) {
427 samples[j * ch_layout_nb_channels + k] = sound_data.get(j + nframes * c->frame_size, k);
428 }
429 }
430
431 // Zero-pad the rest of the frame
432 for (size_t j = rem_lastframe; j < static_cast<size_t>(c->frame_size); j++)
433 {
434 for (int k = 0; k < ch_layout_nb_channels; k++) {
435 samples[j * ch_layout_nb_channels + k] = 0;
436 }
437 }
438
439 if (encode(c, frame, pkt, fos) == false)
440 {
441 yCError(SOUNDFILE_MP3, "Encode failed on partial frame");
442 }
443 }
444
445 // flush the encoder
446 if (encode(c, NULL, pkt, fos) == false)
447 {
448 yCError(SOUNDFILE_MP3, "Encode failed, memory could be corrupted, should I exit?");
449 }
450
451 fos.close();
452
453 av_frame_free(&frame);
456
457 return true;
458#endif
459}
460
461bool read_mp3_istream(Sound& sound_data, std::istream& istream)
462{
463#if !defined (YARP_HAS_FFMPEG)
464 yCError(SOUNDFILE_MP3) << "read_mp3_istream() not supported: lib ffmpeg not found";
465 return false;
466#else
467 // Try to read metadata header (12 bytes) - only present in bytestream format
471
472 // Save current position
473 std::streampos start_pos = istream.tellg();
474
475 // Try to read metadata
476 istream.read((char*)&original_samples, sizeof(uint32_t));
477 istream.read((char*)&original_frequency, sizeof(uint32_t));
478 istream.read((char*)&original_channels, sizeof(uint32_t));
479
480 bool has_metadata = false;
481 if (istream.good())
482 {
483 // Validate metadata - check if values are reasonable
484 // MP3 frequency range: 8000-48000 Hz, channels: 1-2, samples: reasonable range
485 if (original_frequency >= 8000 && original_frequency <= 48000 &&
487 original_samples > 0 && original_samples < 100000000) // max ~30 minutes at 48kHz
488 {
489 has_metadata = true;
490 yCDebug(SOUNDFILE_MP3, "Found metadata: samples=%u, frequency=%u, channels=%u",
492 }
493 else
494 {
495 yCDebug(SOUNDFILE_MP3, "No valid metadata found, seeking back to start");
496 // Reset to start - this is a standard MP3 file without metadata
497 istream.clear();
498 istream.seekg(start_pos);
499 }
500 }
501 else
502 {
503 yCDebug(SOUNDFILE_MP3, "Failed to read metadata, seeking back to start");
504 // Reset to start - this is a standard MP3 file without metadata
505 istream.clear();
506 istream.seekg(start_pos);
507 }
508
509 const AVCodec* codec = nullptr;
510 AVCodecContext* context = nullptr;
511 AVCodecParserContext* parser = nullptr;
512 int len, ret;
514 uint8_t* data = nullptr;
515 size_t data_size;
516 AVPacket* pkt = nullptr;
517 AVFrame* decoded_frame = nullptr;
518
520
521#if LIBAVCODEC_VERSION_MAJOR < 58
522 //register all the codecs, deprecated and useless in libffmpeg4.0
524#endif
525
526 // find the MPEG audio decoder
528 if (!codec)
529 {
530 yCError(SOUNDFILE_MP3, "Codec not found");
531 return false;
532 }
533 parser = av_parser_init(codec->id);
534 if (!parser)
535 {
536 yCError(SOUNDFILE_MP3, "Parser not found");
537 return false;
538 }
539 context = avcodec_alloc_context3(codec);
540 if (!context)
541 {
542 yCError(SOUNDFILE_MP3, "Could not allocate audio codec context");
543 return false;
544 }
545 //open the codec
546 if (avcodec_open2(context, codec, NULL) < 0)
547 {
548 yCError(SOUNDFILE_MP3, "Could not open codec");
549 return false;
550 }
551
552 // decode until eof
553 data = inbuf;
554 istream.read((char*)(inbuf), AUDIO_INBUF_SIZE);
555 data_size = istream.gcount();
556 if (data_size == 0)
557 {
558 yCError(SOUNDFILE_MP3, "Cannot process invalid (empty) stream");
559 return false;
560 }
561
562 // temporary storage of sound frames
563 std::vector<yarp::sig::Sound> vector_of_sound_frames;
564
565 // process the sequence of frames
566 while (data_size > 0)
567 {
568 // add a new empty element to the vector
569 vector_of_sound_frames.emplace_back();
570
571 if (!decoded_frame)
572 {
573 if (!(decoded_frame = av_frame_alloc()))
574 {
575 yCError(SOUNDFILE_MP3, "Could not allocate audio frame");
576 return false;
577 }
578 }
579 ret = av_parser_parse2(parser, context, &pkt->data, &pkt->size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
580 if (ret < 0)
581 {
582 yCError(SOUNDFILE_MP3, "Error while parsing");
583 return false;
584 }
585 data += ret;
586 data_size -= ret;
587 if (pkt->size) {
588 decode(context, pkt, decoded_frame, vector_of_sound_frames.back());
589 }
591 {
592 memmove(inbuf, data, data_size);
593 data = inbuf;
594 istream.read((char*)(data + data_size), AUDIO_INBUF_SIZE - data_size);
595 len = istream.gcount();
596 if (len > 0) {
597 data_size += len;
598 }
599 }
600 }
601
602 // flush the decoder
603 pkt->data = NULL;
604 pkt->size = 0;
605 vector_of_sound_frames.emplace_back(); // the last element
606 decode(context, pkt, decoded_frame, vector_of_sound_frames.back());
607
608 // reconstruct the full sound_data from the vector of frames
609 size_t tot_num_of_samples = 0;
610 for (auto it = vector_of_sound_frames.begin(); it != vector_of_sound_frames.end(); it++)
611 {
612 tot_num_of_samples += it->getSamples();
613 }
614
615 yCDebug(SOUNDFILE_MP3, "Decoded %zu samples total", tot_num_of_samples);
616
617 sound_data.resize(tot_num_of_samples, vector_of_sound_frames[0].getChannels());
618 size_t offset = 0;
619 for (auto it = vector_of_sound_frames.begin(); it != vector_of_sound_frames.end(); it++)
620 {
621 sound_data.overwrite(*it, offset, it->getSamples());
622 offset += it->getSamples();
623 }
624
625 // Use metadata if available, otherwise use decoded values
626 if (has_metadata)
627 {
628 // Trim to original sample count using metadata
630 {
631 yCDebug(SOUNDFILE_MP3, "Trimming from %zu to %u samples using metadata", tot_num_of_samples, original_samples);
633 }
635 }
636 else
637 {
638 // Use frequency from decoder
639 sound_data.setFrequency(context->sample_rate);
640 yCDebug(SOUNDFILE_MP3, "Using decoder frequency: %d Hz", context->sample_rate);
641 }
642
643 yCDebug(SOUNDFILE_MP3, "Final sound: %zu samples, %d Hz, %zu channels",
644 sound_data.getSamples(), sound_data.getFrequency(), sound_data.getChannels());
645
646 //cleanup
647 avcodec_free_context(&context);
648 av_parser_close(parser);
651 return true;
652#endif
653}
654
655bool yarp::sig::file::read_mp3_file(Sound& sound_data, const char* filename)
656{
657 std::fstream fis;
658 fis.open(filename, std::fstream::in | std::fstream::binary);
659 if (fis.is_open() == false)
660 {
661 yCError(SOUNDFILE_MP3, "Cannot open %s for reading", filename);
662 return false;
663 }
664
665 bool b = read_mp3_istream(sound_data, fis);
666 fis.close();
667 return b;
668}
669
671{
672 std::istringstream iss(std::string(bytestream, streamsize));
673 return read_mp3_istream(data, iss);
674}
675
677{
678#if !defined (YARP_HAS_FFMPEG)
679 yCError(SOUNDFILE_MP3) << "write_mp3_bytestream() not supported: lib ffmpeg not found";
680 return false;
681#else
682 const AVCodec * codec = nullptr;
683 AVCodecContext * c = nullptr;
684 AVFrame * frame = nullptr;
685 AVPacket * pkt = nullptr;
686 int ret;
687 std::ostringstream oss(std::ios::binary);
688 uint16_t * samples = nullptr;
689
690#if LIBAVCODEC_VERSION_MAJOR < 58
692#endif
693
694 // find the MP3 encoder
696 if (!codec)
697 {
698 yCError(SOUNDFILE_MP3, "Codec not found");
699 return false;
700 }
701
702 c = avcodec_alloc_context3(codec);
703 if (!c)
704 {
705 yCError(SOUNDFILE_MP3, "Could not allocate audio codec context");
706 return false;
707 }
708
709 // the compressed output bitrate
710 c->bit_rate = 64000;
711
712 // check that the encoder supports s16 pcm input
713 c->sample_fmt = AV_SAMPLE_FMT_S16;
714 if (!check_sample_fmt(codec, c->sample_fmt))
715 {
716 yCError(SOUNDFILE_MP3, "Encoder does not support sample format %s",
717 av_get_sample_fmt_name(c->sample_fmt));
719 return false;
720 }
721
722 // select other audio parameters supported by the encoder
723 c->sample_rate = select_sample_rate(codec, data.getFrequency());
724#if LIBAVCODEC_VERSION_MAJOR >= 61
725 ret = select_channel_layout(codec, &c->ch_layout);
726 if (ret < 0)
727 {
728 yCError(SOUNDFILE_MP3, "Could not select_channel_layout");
730 return false;
731 }
732#else
733 c->channel_layout = select_channel_layout(codec);
734 c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
735#endif
736
737 // open it
738 if (avcodec_open2(c, codec, NULL) < 0)
739 {
740 yCError(SOUNDFILE_MP3, "Could not open codec");
742 return false;
743 }
744
745 // Write metadata header BEFORE MP3 data
746 uint32_t original_samples = static_cast<uint32_t>(data.getSamples());
747 uint32_t original_frequency = static_cast<uint32_t>(data.getFrequency());
748 uint32_t original_channels = static_cast<uint32_t>(data.getChannels());
749 oss.write((const char*)&original_samples, sizeof(uint32_t));
750 oss.write((const char*)&original_frequency, sizeof(uint32_t));
751 oss.write((const char*)&original_channels, sizeof(uint32_t));
752
753 // packet for holding encoded output
755 if (!pkt)
756 {
757 yCError(SOUNDFILE_MP3, "could not allocate the packet");
759 return false;
760 }
761
762 // frame containing input raw audio
763 frame = av_frame_alloc();
764 if (!frame)
765 {
766 yCError(SOUNDFILE_MP3, "Could not allocate audio frame");
769 return false;
770 }
771
772 frame->nb_samples = c->frame_size;
773 frame->format = c->sample_fmt;
774
775#if LIBAVCODEC_VERSION_MAJOR >= 61
776 ret = av_channel_layout_copy(&frame->ch_layout, &c->ch_layout);
777 if (ret < 0)
778 {
779 yCError(SOUNDFILE_MP3, "Could not copy channel layout");
780 av_frame_free(&frame);
783 return false;
784 }
785#else
786 frame->channel_layout = c->channel_layout;
787#endif
788
789 // allocate the data buffers
790 ret = av_frame_get_buffer(frame, 0);
791 if (ret < 0)
792 {
793 yCError(SOUNDFILE_MP3, "Could not allocate audio data buffers");
794 av_frame_free(&frame);
797 return false;
798 }
799
800 // Helper lambda to write packet data to ostringstream
801 auto encode_to_stream = [&](AVCodecContext* ctx, AVFrame* frm, AVPacket* p, std::ostringstream& os) -> bool {
802 int r;
804 if (r < 0)
805 {
806 yCError(SOUNDFILE_MP3, "Error sending the frame to the encoder\n");
807 return false;
808 }
809
810 while (r >= 0)
811 {
813 if (r == AVERROR(EAGAIN) || r == AVERROR_EOF)
814 {
815 return true;
816 }
817 else if (r < 0)
818 {
819 yCError(SOUNDFILE_MP3, "Error encoding audio frame\n");
820 return false;
821 }
822 os.write((const char*)(p->data), p->size);
824 }
825 return true;
826 };
827
828 // encode
829 size_t soundsize = data.getSamples();
830 size_t nframes = soundsize / c->frame_size;
831 size_t rem_lastframe = soundsize % c->frame_size;
832
833 // Encode full frames
834 for (size_t i = 0; i < nframes; i++)
835 {
836 ret = av_frame_make_writable(frame);
837 if (ret < 0) {
838 av_frame_free(&frame);
841 return false;
842 }
843
844#if LIBAVCODEC_VERSION_MAJOR >= 61
845 int ch_layout_nb_channels = c->ch_layout.nb_channels;
846#else
847 int ch_layout_nb_channels = c->channels;
848#endif
849
850 samples = (uint16_t*)frame->data[0];
851 for (int j = 0; j < c->frame_size; j++)
852 {
853 for (int k = 0; k < ch_layout_nb_channels; k++) {
854 samples[j * ch_layout_nb_channels + k] = data.get(j + i * c->frame_size, k);
855 }
856 }
857 if (!encode_to_stream(c, frame, pkt, oss))
858 {
859 yCError(SOUNDFILE_MP3, "Encode failed, memory could be corrupted");
860 av_frame_free(&frame);
863 return false;
864 }
865 }
866
867 // Encode remaining samples (partial frame) with zero padding
868 if (rem_lastframe > 0)
869 {
870 ret = av_frame_make_writable(frame);
871 if (ret < 0) {
872 av_frame_free(&frame);
875 return false;
876 }
877
878#if LIBAVCODEC_VERSION_MAJOR >= 61
879 int ch_layout_nb_channels = c->ch_layout.nb_channels;
880#else
881 int ch_layout_nb_channels = c->channels;
882#endif
883
884 samples = (uint16_t*)frame->data[0];
885
886 // Copy remaining samples
887 for (size_t j = 0; j < rem_lastframe; j++)
888 {
889 for (int k = 0; k < ch_layout_nb_channels; k++) {
890 samples[j * ch_layout_nb_channels + k] = data.get(j + nframes * c->frame_size, k);
891 }
892 }
893
894 // Zero-pad the rest of the frame
895 for (size_t j = rem_lastframe; j < static_cast<size_t>(c->frame_size); j++)
896 {
897 for (int k = 0; k < ch_layout_nb_channels; k++) {
898 samples[j * ch_layout_nb_channels + k] = 0;
899 }
900 }
901
902 if (!encode_to_stream(c, frame, pkt, oss))
903 {
904 yCError(SOUNDFILE_MP3, "Encode failed on partial frame");
905 av_frame_free(&frame);
908 return false;
909 }
910 }
911
912 // flush the encoder
913 if (!encode_to_stream(c, NULL, pkt, oss))
914 {
915 yCError(SOUNDFILE_MP3, "Encode failed during flush");
916 av_frame_free(&frame);
919 return false;
920 }
921
922 // Get the encoded data from the ostringstream
923 std::string encoded_data = oss.str();
924 size_t encoded_size = encoded_data.size();
925
926 // FIX: Handle buffer size query separately from error condition
927 if (bytestream == nullptr)
928 {
929 // Caller is querying required buffer size - this is SUCCESS
930 // Add 12 bytes for the metadata header
932 av_frame_free(&frame);
935 return true;
936 }
937
938 // Check if the provided buffer is large enough
940 {
941 // Buffer too small - this is an ERROR
942 yCError(SOUNDFILE_MP3, "Buffer too small: provided %zu bytes, need %zu bytes", streamsize, encoded_size);
944 av_frame_free(&frame);
947 return false;
948 }
949
950 // Copy the encoded data to the output buffer
953
954 // Cleanup
955 av_frame_free(&frame);
958
959 return true;
960#endif
961}
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:42
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.
Definition OSTestMsg.cpp:13
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.