| 429 | } |
| 430 | |
| 431 | bool AudioClip::WriteBuffer(int32 chunkIndex) |
| 432 | { |
| 433 | // Ensure audio backend exists |
| 434 | if (AudioBackend::Instance == nullptr) |
| 435 | return true; |
| 436 | PROFILE_CPU(); |
| 437 | PROFILE_MEM(Audio); |
| 438 | |
| 439 | const auto chunk = GetChunk(chunkIndex); |
| 440 | if (chunk == nullptr || chunk->IsMissing()) |
| 441 | { |
| 442 | LOG(Warning, "Missing audio data."); |
| 443 | return true; |
| 444 | } |
| 445 | Span<byte> data; |
| 446 | Array<byte> tmp1, tmp2; |
| 447 | AudioDataInfo info = AudioHeader.Info; |
| 448 | const uint32 bytesPerSample = info.BitDepth / 8; |
| 449 | ZoneValue(chunk->Size() / 1024); // Audio data size (in kB) |
| 450 | |
| 451 | // Get raw data or decompress it |
| 452 | switch (Format()) |
| 453 | { |
| 454 | case AudioFormat::Vorbis: |
| 455 | { |
| 456 | #if COMPILE_WITH_OGG_VORBIS |
| 457 | PROFILE_CPU_NAMED("OggVorbisDecode"); |
| 458 | OggVorbisDecoder decoder; |
| 459 | MemoryReadStream stream(chunk->Get(), chunk->Size()); |
| 460 | AudioDataInfo tmpInfo; |
| 461 | if (decoder.Convert(&stream, tmpInfo, tmp1)) |
| 462 | { |
| 463 | LOG(Warning, "Audio data decode failed (OggVorbisDecoder)."); |
| 464 | return true; |
| 465 | } |
| 466 | // TODO: validate decompressed data header info? |
| 467 | data = Span<byte>(tmp1.Get(), tmp1.Count()); |
| 468 | #else |
| 469 | LOG(Warning, "OggVorbisDecoder is disabled."); |
| 470 | return true; |
| 471 | #endif |
| 472 | } |
| 473 | break; |
| 474 | case AudioFormat::Raw: |
| 475 | data = Span<byte>(chunk->Get(), chunk->Size()); |
| 476 | break; |
| 477 | default: |
| 478 | return true; |
| 479 | } |
| 480 | info.NumSamples = Math::AlignDown(data.Length() / bytesPerSample, info.NumChannels * bytesPerSample); |
| 481 | |
| 482 | #if COMPILE_WITH_AUDIO_TOOL |
| 483 | // Convert to Mono if used as 3D source and backend doesn't support it |
| 484 | if (Is3D() && info.NumChannels > 1 && EnumHasNoneFlags(AudioBackend::Features(), AudioBackend::FeatureFlags::SpatialMultiChannel)) |
| 485 | { |
| 486 | const uint32 samplesPerChannel = info.NumSamples / info.NumChannels; |
| 487 | const uint32 monoBufferSize = samplesPerChannel * bytesPerSample; |
| 488 | tmp2.Resize(monoBufferSize); |