| 6 | extern "C" { |
| 7 | #include <libavutil/timestamp.h> |
| 8 | #include <libavformat/avformat.h> |
| 9 | #include <libavcodec/avcodec.h> |
| 10 | } |
| 11 |
| 12 | #include <string> |
| 13 | #include <set> |
| 14 | #include <map> |
| 15 |
| 16 | namespace tgcalls { |
| 17 |
| 18 | namespace { |
| 19 |
| 20 | static absl::optional<uint32_t> readInt32(std::string const &data, int &offset) { |
| 21 | if (offset + 4 > data.length()) { |
| 22 | return absl::nullopt; |
| 23 | } |
| 24 |
| 25 | int32_t value = 0; |
| 26 | memcpy(&value, data.data() + offset, 4); |
| 27 | offset += 4; |
| 28 |
| 29 | return value; |
| 30 | } |
| 31 |
| 32 | struct ChannelUpdate { |
| 33 | int frameIndex = 0; |
| 34 | int id = 0; |
| 35 | uint32_t ssrc = 0; |
| 36 | }; |
| 37 |
| 38 | static std::vector<ChannelUpdate> parseChannelUpdates(std::string const &data, int &offset) { |
| 39 | std::vector<ChannelUpdate> result; |
| 40 |
| 41 | auto channels = readInt32(data, offset); |
| 42 | if (!channels) { |
| 43 | return {}; |
| 44 | } |
| 45 |
| 46 | auto count = readInt32(data, offset); |
| 47 | if (!count) { |
| 48 | return {}; |
| 49 | } |
| 50 |
| 51 | for (int i = 0; i < count.value(); i++) { |
| 52 | auto frameIndex = readInt32(data, offset); |
| 53 | if (!frameIndex) { |
| 54 | return {}; |
| 55 | } |
| 56 |
| 57 | auto channelId = readInt32(data, offset); |
| 58 | if (!channelId) { |
| 59 | return {}; |
| 60 | } |
| 61 |
| 62 | auto ssrc = readInt32(data, offset); |
| 63 | if (!ssrc) { |
| 64 | return {}; |
| 65 | } |
| 66 |
| 67 | ChannelUpdate update; |
| 68 | update.frameIndex = frameIndex.value(); |
| 69 | update.id = channelId.value(); |
| 70 | update.ssrc = ssrc.value(); |
| 71 |
| 72 | result.push_back(update); |
| 73 | } |
| 74 |
| 75 | return result; |
| 76 | } |
| 77 |
| 78 | class AVIOContextImpl { |
| 79 | public: |
| 80 | AVIOContextImpl(std::vector<uint8_t> &&fileData) : |
| 81 | _fileData(std::move(fileData)) { |
| 82 | _buffer.resize(4 * 1024); |
| 83 | _context = avio_alloc_context(_buffer.data(), (int)_buffer.size(), 0, this, &AVIOContextImpl::read, NULL, &AVIOContextImpl::seek); |
| 84 | } |
| 85 |
| 86 | ~AVIOContextImpl() { |
| 87 | av_free(_context); |
| 88 | } |
| 89 |
| 90 | static int read(void *opaque, unsigned char *buffer, int bufferSize) { |
| 91 | AVIOContextImpl *instance = static_cast<AVIOContextImpl *>(opaque); |
| 92 |
| 93 | int bytesToRead = std::min(bufferSize, ((int)instance->_fileData.size()) - instance->_fileReadPosition); |
| 94 | if (bytesToRead < 0) { |
| 95 | bytesToRead = 0; |
| 96 | } |
| 97 |
| 98 | if (bytesToRead > 0) { |
| 99 | memcpy(buffer, instance->_fileData.data() + instance->_fileReadPosition, bytesToRead); |
| 100 | instance->_fileReadPosition += bytesToRead; |
| 101 |
| 102 | return bytesToRead; |
| 103 | } else { |
| 104 | return AVERROR_EOF; |
| 105 | } |
| 106 | } |
| 107 |
| 108 | static int64_t seek(void *opaque, int64_t offset, int whence) { |
| 109 | AVIOContextImpl *instance = static_cast<AVIOContextImpl *>(opaque); |
| 110 |
| 111 | if (whence == 0x10000) { |
| 112 | return (int64_t)instance->_fileData.size(); |
| 113 | } else { |
| 114 | int64_t seekOffset = std::min(offset, (int64_t)instance->_fileData.size()); |
| 115 | if (seekOffset < 0) { |
| 116 | seekOffset = 0; |
| 117 | } |
| 118 | instance->_fileReadPosition = (int)seekOffset; |
| 119 | return seekOffset; |
| 120 | } |
| 121 | } |
| 122 |
| 123 | AVIOContext *getContext() { |
| 124 | return _context; |
| 125 | } |
| 126 |
| 127 | private: |
| 128 | std::vector<uint8_t> _fileData; |
| 129 | int _fileReadPosition = 0; |
| 130 |
| 131 | std::vector<uint8_t> _buffer; |
| 132 | AVIOContext *_context = nullptr; |
| 133 | }; |
| 134 |
| 135 | } |
| 136 |
| 137 | struct ReadPcmResult { |
| 138 | int numSamples = 0; |
| 139 | int numChannels = 0; |
| 140 | }; |
| 141 |
| 142 | class StreamingPartInternal { |
| 143 | public: |
| 144 | StreamingPartInternal(std::vector<uint8_t> &&fileData) : |
| 145 | _avIoContext(std::move(fileData)) { |
| 146 | int ret = 0; |
| 147 |
| 148 | _frame = av_frame_alloc(); |
| 149 |
| 150 | AVInputFormat *inputFormat = av_find_input_format("ogg"); |
| 151 | if (!inputFormat) { |
| 152 | _didReadToEnd = true; |
| 153 | return; |
| 154 | } |
| 155 |
| 156 | _inputFormatContext = avformat_alloc_context(); |
| 157 | if (!_inputFormatContext) { |
| 158 | _didReadToEnd = true; |
| 159 | return; |
| 160 | } |
| 161 |
| 162 | _inputFormatContext->pb = _avIoContext.getContext(); |
| 163 |
| 164 | if ((ret = avformat_open_input(&_inputFormatContext, "", inputFormat, nullptr)) < 0) { |
| 165 | _didReadToEnd = true; |
| 166 | return; |
| 167 | } |
| 168 |
| 169 | if ((ret = avformat_find_stream_info(_inputFormatContext, nullptr)) < 0) { |
| 170 | _didReadToEnd = true; |
| 171 |
| 172 | avformat_close_input(&_inputFormatContext); |
| 173 | _inputFormatContext = nullptr; |
| 174 | return; |
| 175 | } |
| 176 |
| 177 | AVCodecParameters *audioCodecParameters = nullptr; |
| 178 | AVStream *audioStream = nullptr; |
| 179 | for (int i = 0; i < _inputFormatContext->nb_streams; i++) { |
| 180 | AVStream *inStream = _inputFormatContext->streams[i]; |
| 181 |
| 182 | AVCodecParameters *inCodecpar = inStream->codecpar; |
| 183 | if (inCodecpar->codec_type != AVMEDIA_TYPE_AUDIO) { |
| 184 | continue; |
| 185 | } |
| 186 | audioCodecParameters = inCodecpar; |
| 187 | audioStream = inStream; |
| 188 |
| 189 | _durationInMilliseconds = (int)((inStream->duration + inStream->first_dts) * 1000 / 48000); |
| 190 |
| 191 | if (inStream->metadata) { |
| 192 | AVDictionaryEntry *entry = av_dict_get(inStream->metadata, "TG_META", nullptr, 0); |
| 193 | if (entry && entry->value) { |
| 194 | std::string result; |
| 195 | size_t data_used = 0; |
| 196 | std::string sourceBase64 = (const char *)entry->value; |
| 197 | rtc::Base64::Decode(sourceBase64, rtc::Base64::DO_LAX, &result, &data_used); |
| 198 |
| 199 | if (result.size() != 0) { |
| 200 | int offset = 0; |
| 201 | _channelUpdates = parseChannelUpdates(result, offset); |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 |
| 206 | break; |
| 207 | } |
| 208 |
| 209 | if (audioCodecParameters && audioStream) { |
| 210 | AVCodec *codec = avcodec_find_decoder(audioCodecParameters->codec_id); |
| 211 | if (codec) { |
| 212 | _codecContext = avcodec_alloc_context3(codec); |
| 213 | ret = avcodec_parameters_to_context(_codecContext, audioCodecParameters); |
| 214 | if (ret < 0) { |
| 215 | _didReadToEnd = true; |
| 216 |
| 217 | avcodec_free_context(&_codecContext); |
| 218 | _codecContext = nullptr; |
| 219 | } else { |
| 220 | _codecContext->pkt_timebase = audioStream->time_base; |
| 221 |
| 222 | _channelCount = _codecContext->channels; |
| 223 |
| 224 | ret = avcodec_open2(_codecContext, codec, nullptr); |
| 225 | if (ret < 0) { |
| 226 | _didReadToEnd = true; |
| 227 |
| 228 | avcodec_free_context(&_codecContext); |
| 229 | _codecContext = nullptr; |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 |
| 236 | ~StreamingPartInternal() { |
| 237 | if (_frame) { |
| 238 | av_frame_unref(_frame); |
| 239 | } |
| 240 | if (_codecContext) { |
| 241 | avcodec_close(_codecContext); |
| 242 | avcodec_free_context(&_codecContext); |
| 243 | } |
| 244 | if (_inputFormatContext) { |
| 245 | avformat_close_input(&_inputFormatContext); |
| 246 | } |
| 247 | } |
| 248 |
| 249 | ReadPcmResult readPcm(std::vector<int16_t> &outPcm) { |
| 250 | int outPcmSampleOffset = 0; |
| 251 | ReadPcmResult result; |
| 252 |
| 253 | int readSamples = (int)outPcm.size() / _channelCount; |
| 254 |
| 255 | result.numChannels = _channelCount; |
| 256 |
| 257 | while (outPcmSampleOffset < readSamples) { |
| 258 | if (_pcmBufferSampleOffset >= _pcmBufferSampleSize) { |
| 259 | fillPcmBuffer(); |
| 260 |
| 261 | if (_pcmBufferSampleOffset >= _pcmBufferSampleSize) { |
| 262 | break; |
| 263 | } |
| 264 | } |
| 265 |
| 266 | int readFromPcmBufferSamples = std::min(_pcmBufferSampleSize - _pcmBufferSampleOffset, readSamples - outPcmSampleOffset); |
| 267 | if (readFromPcmBufferSamples != 0) { |
| 268 | std::copy(_pcmBuffer.begin() + _pcmBufferSampleOffset * _channelCount, _pcmBuffer.begin() + _pcmBufferSampleOffset * _channelCount + readFromPcmBufferSamples * _channelCount, outPcm.begin() + outPcmSampleOffset * _channelCount); |
| 269 | _pcmBufferSampleOffset += readFromPcmBufferSamples; |
| 270 | outPcmSampleOffset += readFromPcmBufferSamples; |
| 271 | result.numSamples += readFromPcmBufferSamples; |
| 272 | } |
| 273 | } |
| 274 |
| 275 | return result; |
| 276 | } |
| 277 |
| 278 | int getDurationInMilliseconds() { |
| 279 | return _durationInMilliseconds; |
| 280 | } |
| 281 |
| 282 | int getChannelCount() { |
| 283 | return _channelCount; |
| 284 | } |
| 285 |
| 286 | std::vector<ChannelUpdate> const &getChannelUpdates() { |
| 287 | return _channelUpdates; |
| 288 | } |
| 289 |
| 290 | private: |
| 291 | void fillPcmBuffer() { |
| 292 | _pcmBufferSampleSize = 0; |
| 293 | _pcmBufferSampleOffset = 0; |
| 294 |
| 295 | if (_didReadToEnd) { |
| 296 | return; |
| 297 | } |
| 298 | if (!_inputFormatContext) { |
| 299 | _didReadToEnd = true; |
| 300 | return; |
| 301 | } |
| 302 | if (!_codecContext) { |
| 303 | _didReadToEnd = true; |
| 304 | return; |
| 305 | } |
| 306 |
| 307 | int ret = 0; |
| 308 |
| 309 | ret = av_read_frame(_inputFormatContext, &_packet); |
| 310 | if (ret < 0) { |
| 311 | _didReadToEnd = true; |
| 312 | return; |
| 313 | } |
| 314 |
| 315 | ret = avcodec_send_packet(_codecContext, &_packet); |
| 316 | if (ret < 0) { |
| 317 | _didReadToEnd = true; |
| 318 | return; |
| 319 | } |
| 320 |
| 321 | int bytesPerSample = av_get_bytes_per_sample(_codecContext->sample_fmt); |
| 322 | if (bytesPerSample != 2 && bytesPerSample != 4) { |
| 323 | _didReadToEnd = true; |
| 324 | return; |
| 325 | } |
| 326 |
| 327 | ret = avcodec_receive_frame(_codecContext, _frame); |
| 328 | if (ret != 0) { |
| 329 | _didReadToEnd = true; |
| 330 | return; |
| 331 | } |
| 332 | if (_frame->channels != _channelCount || _frame->channels > 8) { |
| 333 | _didReadToEnd = true; |
| 334 | return; |
| 335 | } |
| 336 |
| 337 | if (_pcmBuffer.size() < _frame->nb_samples * _frame->channels) { |
| 338 | _pcmBuffer.resize(_frame->nb_samples * _frame->channels); |
| 339 | } |
| 340 |
| 341 | switch (_codecContext->sample_fmt) { |
| 342 | case AV_SAMPLE_FMT_S16: { |
| 343 | memcpy(_pcmBuffer.data(), _frame->data[0], _frame->nb_samples * 2 * _frame->channels); |
| 344 | } break; |
| 345 |
| 346 | case AV_SAMPLE_FMT_S16P: { |
| 347 | int16_t *to = _pcmBuffer.data(); |
| 348 | for (int sample = 0; sample < _frame->nb_samples; ++sample) { |
| 349 | for (int channel = 0; channel < _frame->channels; ++channel) { |
| 350 | int16_t *shortChannel = (int16_t*)_frame->data[channel]; |
| 351 | *to++ = shortChannel[sample]; |
| 352 | } |
| 353 | } |
| 354 | } break; |
| 355 |
| 356 | case AV_SAMPLE_FMT_FLT: { |
| 357 | float *floatData = (float *)&_frame->data[0]; |
| 358 | for (int i = 0; i < _frame->nb_samples * _frame->channels; i++) { |
| 359 | _pcmBuffer[i] = (int16_t)(floatData[i] * INT16_MAX); |
| 360 | } |
| 361 | } break; |
| 362 |
| 363 | case AV_SAMPLE_FMT_FLTP: { |
| 364 | int16_t *to = _pcmBuffer.data(); |
| 365 | for (int sample = 0; sample < _frame->nb_samples; ++sample) { |
| 366 | for (int channel = 0; channel < _frame->channels; ++channel) { |
| 367 | float *floatChannel = (float*)_frame->data[channel]; |
| 368 | *to++ = (int16_t)(floatChannel[sample] * INT16_MAX); |
| 369 | } |
| 370 | } |
| 371 | } break; |
| 372 |
| 373 | default: { |
| 374 | //RTC_FATAL() << "Unexpected sample_fmt"; |
| 375 | } break; |
| 376 | } |
| 377 |
| 378 | _pcmBufferSampleSize = _frame->nb_samples; |
| 379 | _pcmBufferSampleOffset = 0; |
| 380 | } |
| 381 |
| 382 | private: |
| 383 | AVIOContextImpl _avIoContext; |
| 384 |
| 385 | AVFormatContext *_inputFormatContext = nullptr; |
| 386 | AVPacket _packet; |
| 387 | AVCodecContext *_codecContext = nullptr; |
| 388 | AVFrame *_frame = nullptr; |
| 389 |
| 390 | bool _didReadToEnd = false; |
| 391 |
| 392 | int _durationInMilliseconds = 0; |
| 393 | int _channelCount = 0; |
| 394 |
| 395 | std::vector<ChannelUpdate> _channelUpdates; |
| 396 |
| 397 | std::vector<int16_t> _pcmBuffer; |
| 398 | int _pcmBufferSampleOffset = 0; |
| 399 | int _pcmBufferSampleSize = 0; |
| 400 | }; |
| 401 |
| 402 | class StreamingPartState { |
| 403 | struct ChannelMapping { |
| 404 | uint32_t ssrc = 0; |
| 405 | int channelIndex = 0; |
| 406 |
| 407 | ChannelMapping(uint32_t ssrc_, int channelIndex_) : |
| 408 | ssrc(ssrc_), channelIndex(channelIndex_) { |
| 409 | } |
| 410 | }; |
| 411 |
| 412 | public: |
| 413 | StreamingPartState(std::vector<uint8_t> &&data) : |
| 414 | _parsedPart(std::move(data)) { |
| 415 | if (_parsedPart.getChannelUpdates().size() == 0) { |
| 416 | _didReadToEnd = true; |
| 417 | return; |
| 418 | } |
| 419 |
| 420 | _remainingMilliseconds = _parsedPart.getDurationInMilliseconds(); |
| 421 | _pcm10ms.resize(480 * _parsedPart.getChannelCount()); |
| 422 |
| 423 | for (const auto &it : _parsedPart.getChannelUpdates()) { |
| 424 | _allSsrcs.insert(it.ssrc); |
| 425 | } |
| 426 | } |
| 427 |
| 428 | ~StreamingPartState() { |
| 429 | } |
| 430 |
| 431 | int getRemainingMilliseconds() const { |
| 432 | return _remainingMilliseconds; |
| 433 | } |
| 434 |
| 435 | std::vector<StreamingPart::StreamingPartChannel> get10msPerChannel() { |
| 436 | if (_didReadToEnd) { |
| 437 | return {}; |
| 438 | } |
| 439 |
| 440 | for (const auto &update : _parsedPart.getChannelUpdates()) { |
| 441 | if (update.frameIndex == _frameIndex) { |
| 442 | updateCurrentMapping(update.ssrc, update.id); |
| 443 | } |
| 444 | } |
| 445 |
| 446 | auto readResult = _parsedPart.readPcm(_pcm10ms); |
| 447 | if (readResult.numSamples <= 0) { |
| 448 | _didReadToEnd = true; |
| 449 | return {}; |
| 450 | } |
| 451 |
| 452 | std::vector<StreamingPart::StreamingPartChannel> resultChannels; |
| 453 | for (const auto ssrc : _allSsrcs) { |
| 454 | StreamingPart::StreamingPartChannel emptyPart; |
| 455 | emptyPart.ssrc = ssrc; |
| 456 | resultChannels.push_back(emptyPart); |
| 457 | } |
| 458 |
| 459 | for (auto &channel : resultChannels) { |
| 460 | auto mappedChannelIndex = getCurrentMappedChannelIndex(channel.ssrc); |
| 461 |
| 462 | if (mappedChannelIndex) { |
| 463 | int sourceChannelIndex = mappedChannelIndex.value(); |
| 464 | for (int j = 0; j < readResult.numSamples; j++) { |
| 465 | channel.pcmData.push_back(_pcm10ms[sourceChannelIndex + j * readResult.numChannels]); |
| 466 | } |
| 467 | } else { |
| 468 | for (int j = 0; j < readResult.numSamples; j++) { |
| 469 | channel.pcmData.push_back(0); |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 |
| 474 | _remainingMilliseconds -= 10; |
| 475 | if (_remainingMilliseconds < 0) { |
| 476 | _remainingMilliseconds = 0; |
| 477 | } |
| 478 | _frameIndex++; |
| 479 |
| 480 | return resultChannels; |
| 481 | } |
| 482 |
| 483 | private: |
| 484 | absl::optional<int> getCurrentMappedChannelIndex(uint32_t ssrc) { |
| 485 | for (const auto &it : _currentChannelMapping) { |
| 486 | if (it.ssrc == ssrc) { |
| 487 | return it.channelIndex; |
| 488 | } |
| 489 | } |
| 490 | return absl::nullopt; |
| 491 | } |
| 492 |
| 493 | void updateCurrentMapping(uint32_t ssrc, int channelIndex) { |
| 494 | for (int i = (int)_currentChannelMapping.size() - 1; i >= 0; i--) { |
| 495 | const auto &entry = _currentChannelMapping[i]; |
| 496 | if (entry.ssrc == ssrc && entry.channelIndex == channelIndex) { |
| 497 | return; |
| 498 | } else if (entry.ssrc == ssrc || entry.channelIndex == channelIndex) { |
| 499 | _currentChannelMapping.erase(_currentChannelMapping.begin() + i); |
| 500 | } |
| 501 | } |
| 502 | _currentChannelMapping.emplace_back(ssrc, channelIndex); |
| 503 | } |
| 504 |
| 505 | private: |
| 506 | StreamingPartInternal _parsedPart; |
| 507 | std::set<uint32_t> _allSsrcs; |
| 508 |
| 509 | std::vector<int16_t> _pcm10ms; |
| 510 | std::vector<ChannelMapping> _currentChannelMapping; |
| 511 | int _frameIndex = 0; |
| 512 | int _remainingMilliseconds = 0; |
| 513 |
| 514 | bool _didReadToEnd = false; |
| 515 | }; |
| 516 |
| 517 | StreamingPart::StreamingPart(std::vector<uint8_t> &&data) { |
| 518 | if (!data.empty()) { |
| 519 | _state = new StreamingPartState(std::move(data)); |
| 520 | } |
| 521 | } |
| 522 |
| 523 | StreamingPart::~StreamingPart() { |
| 524 | if (_state) { |
| 525 | delete _state; |
| 526 | } |
| 527 | } |
| 528 |
| 529 | int StreamingPart::getRemainingMilliseconds() const { |
| 530 | return _state ? _state->getRemainingMilliseconds() : 0; |
| 531 | } |
| 532 |
| 533 | std::vector<StreamingPart::StreamingPartChannel> StreamingPart::get10msPerChannel() { |
| 534 | return _state |
| 535 | ? _state->get10msPerChannel() |
| 536 | : std::vector<StreamingPart::StreamingPartChannel>(); |
| 537 | } |
| 538 |
| 539 | } |
| 540 |