| 52 | } |
| 53 | |
| 54 | bool OpusAudioEncoder::Encode(const AudioChunk& chunk, EncodedAudioFrame* output, std::string* error) { |
| 55 | if (!impl_ || !impl_->encoder) { |
| 56 | if (error) *error = "Opus encoder is not open"; |
| 57 | return false; |
| 58 | } |
| 59 | if (chunk.sample_rate != impl_->sample_rate || chunk.channels != impl_->channels || chunk.channels == 0) { |
| 60 | if (error) *error = "Opus encoder audio format changed"; |
| 61 | return false; |
| 62 | } |
| 63 | const int frame_size = static_cast<int>(chunk.samples.size() / chunk.channels); |
| 64 | if (frame_size <= 0) return false; |
| 65 | |
| 66 | const int bytes = opus_encode( |
| 67 | impl_->encoder, |
| 68 | reinterpret_cast<const opus_int16*>(chunk.samples.data()), |
| 69 | frame_size, |
| 70 | encoded_.data(), |
| 71 | static_cast<opus_int32>(encoded_.size())); |
| 72 | if (bytes < 0) { |
| 73 | if (error) *error = opus_strerror(bytes); |
| 74 | return false; |
| 75 | } |
| 76 | |
| 77 | if (output) { |
| 78 | output->codec = "opus"; |
| 79 | output->data = std::span<const uint8_t>(encoded_.data(), static_cast<size_t>(bytes)); |
| 80 | output->pts_us = chunk.pts_us; |
| 81 | } |
| 82 | return bytes > 0; |
| 83 | } |
| 84 | |
| 85 | void OpusAudioEncoder::Close() { |
| 86 | if (impl_ && impl_->encoder) { |
no test coverage detected