| 54 | } |
| 55 | |
| 56 | void Abyss::Streams::AudioStream::update() { |
| 57 | if (_avFormatContext == nullptr) |
| 58 | return; |
| 59 | |
| 60 | const std::unique_ptr<AVPacket, void (*)(AVPacket *)> packet(av_packet_alloc(), [](AVPacket *p) { av_packet_free(&p); }); |
| 61 | |
| 62 | if (av_read_frame(_avFormatContext, packet.get()) < 0) { |
| 63 | if (_loop) { |
| 64 | av_seek_frame(_avFormatContext, _audioStreamIdx, 0, AVSEEK_FLAG_FRAME); |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | av_seek_frame(_avFormatContext, _audioStreamIdx, 0, AVSEEK_FLAG_FRAME); |
| 69 | _isPlaying = false; |
| 70 | return; |
| 71 | } |
| 72 | |
| 73 | if (packet->stream_index != _audioStreamIdx) |
| 74 | return; |
| 75 | |
| 76 | if (avcodec_send_packet(_audioCodecContext, packet.get()) < 0) { |
| 77 | avcodec_flush_buffers(_audioCodecContext); |
| 78 | avformat_flush(_avFormatContext); |
| 79 | av_seek_frame(_avFormatContext, _audioStreamIdx, 0, AVSEEK_FLAG_FRAME); |
| 80 | |
| 81 | if (!_loop) |
| 82 | _isPlaying = false; |
| 83 | |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | while (true) { |
| 88 | if (int avError; (avError = avcodec_receive_frame(_audioCodecContext, _avFrame)) < 0) { |
| 89 | if (avError == AVERROR(EAGAIN) || avError == AVERROR_EOF) |
| 90 | return; |
| 91 | |
| 92 | throw std::runtime_error(absl::StrCat("Failed to receive frame: ", AvErrorCodeToString(avError))); |
| 93 | } |
| 94 | |
| 95 | int _lineSize; |
| 96 | const auto outSamples = swr_get_out_samples(_resampleContext, _avFrame->nb_samples); |
| 97 | const auto audioOutSize = av_samples_get_buffer_size(&_lineSize, 2, outSamples, AV_SAMPLE_FMT_S16, 0); |
| 98 | uint8_t *ptr[1] = {_audioOutBuffer}; |
| 99 | const auto result = swr_convert(_resampleContext, ptr, audioOutSize, const_cast<const uint8_t **>(_avFrame->data), _avFrame->nb_samples); |
| 100 | _ringBuffer.pushData(std::span(_audioOutBuffer, result * 4)); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | Abyss::Streams::AudioStream::AudioStream(FileSystem::InputStream stream) : _stream(std::move(stream)), _ringBuffer(1024 * 1024) { |
| 105 | const auto streamSize = _stream.size(); |