A modded EditSaber for making beat saber maps.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

288 lines
8.8 KiB

  1. // Fill out your copyright notice in the Description page of Project Settings.
  2. #include "RenderWaveform.h"
  3. // KISS Headers, that we need for the decompression part
  4. #include "ThirdParty/Kiss_FFT/kiss_fft129/kiss_fft.h"
  5. #include "ThirdParty/Kiss_FFT/kiss_fft129/tools/kiss_fftnd.h"
  6. bool bNormalizeOutputToDb = false;
  7. bool bShowLogDebug = false;
  8. bool bShowWarningDebug = false;
  9. bool bShowErrorDebug = false;
  10. // Log Category
  11. DECLARE_LOG_CATEGORY_EXTERN(LogRenderWave, Log, All);
  12. // Short Defines to faster debug
  13. #define PrintLog(TextToLog) if(bShowLogDebug) UE_LOG(LogRenderWave, Log, TextToLog)
  14. #define PrintWarning(TextToLog) if(bShowWarningDebug) UE_LOG(LogRenderWave, Warning, TextToLog)
  15. #define PrintError(TextToLog) if(bShowErrorDebug) UE_LOG(LogRenderWave, Error, TextToLog)
  16. #include "Sound/SoundWave.h"
  17. #include "AudioDevice.h"
  18. #include "Runtime/Engine/Public/VorbisAudioInfo.h"
  19. #include "Developer/TargetPlatform/Public/Interfaces/IAudioFormat.h"
  20. DEFINE_LOG_CATEGORY(LogRenderWave);
  21. float GetFFTInValue(const int16 InSampleValue, const int16 InSampleIndex, const int16 InSampleCount)
  22. {
  23. float FFTValue = InSampleValue;
  24. // Apply the Hann window
  25. FFTValue *= 0.5f * (1 - FMath::Cos(2 * PI * InSampleIndex / (InSampleCount - 1)));
  26. return FFTValue;
  27. }
  28. void CalculateFrequencySpectrum(USoundWave* InSoundWaveRef, const float InStartTime, const float InDuration, TArray<float>& OutFrequencies)
  29. {
  30. // Clear the Array before continuing
  31. OutFrequencies.Empty();
  32. const int32 NumChannels = InSoundWaveRef->NumChannels;
  33. const int32 SampleRate = InSoundWaveRef->SampleRate;
  34. // Make sure the Number of Channels is correct
  35. if (NumChannels > 0 && NumChannels <= 2)
  36. {
  37. // Check if we actually have a Buffer to work with
  38. if (InSoundWaveRef->CachedRealtimeFirstBuffer)
  39. {
  40. // The first sample is just the StartTime * SampleRate
  41. int32 FirstSample = SampleRate * InStartTime;
  42. // The last sample is the SampleRate times (StartTime plus the Duration)
  43. int32 LastSample = SampleRate * (InStartTime + InDuration);
  44. // Get Maximum amount of samples in this Sound
  45. const int32 SampleCount = InSoundWaveRef->RawPCMDataSize / (2 * NumChannels);
  46. // An early check if we can create a Sample window
  47. FirstSample = FMath::Min(SampleCount, FirstSample);
  48. LastSample = FMath::Min(SampleCount, LastSample);
  49. // Actual amount of samples we gonna read
  50. int32 SamplesToRead = LastSample - FirstSample;
  51. if (SamplesToRead < 0) {
  52. PrintError(TEXT("Number of SamplesToRead is < 0!"));
  53. return;
  54. }
  55. // Shift the window enough so that we get a PowerOfTwo. FFT works better with that
  56. int32 PoT = 2;
  57. while (SamplesToRead > PoT) {
  58. PoT *= 2;
  59. }
  60. // Now we have a good PowerOfTwo to work with
  61. SamplesToRead = PoT;
  62. // Create two 2-dim Arrays for complex numbers | Buffer and Output
  63. kiss_fft_cpx* Buffer[2] = {0};
  64. kiss_fft_cpx* Output[2] = {0};
  65. // Create 1-dim Array with one slot for SamplesToRead
  66. int32 Dims[1] = {SamplesToRead};
  67. // alloc once and forget, should probably move to a init/deinit func
  68. static kiss_fftnd_cfg STF = kiss_fftnd_alloc(Dims, 1, 0, nullptr, nullptr);
  69. int16* SamplePtr = reinterpret_cast<int16*>(InSoundWaveRef->CachedRealtimeFirstBuffer);
  70. // Allocate space in the Buffer and Output Arrays for all the data that FFT returns
  71. for (int32 ChannelIndex = 0; ChannelIndex < NumChannels; ChannelIndex++)
  72. {
  73. Buffer[ChannelIndex] = (kiss_fft_cpx*)KISS_FFT_MALLOC(sizeof(kiss_fft_cpx) * SamplesToRead);
  74. Output[ChannelIndex] = (kiss_fft_cpx*)KISS_FFT_MALLOC(sizeof(kiss_fft_cpx) * SamplesToRead);
  75. }
  76. // Shift our SamplePointer to the Current "FirstSample"
  77. SamplePtr += FirstSample * NumChannels;
  78. float precomputeMultiplier = 2.f * PI / (SamplesToRead - 1);
  79. for (int32 SampleIndex = 0; SampleIndex < SamplesToRead; SampleIndex++)
  80. {
  81. float rMult = 0.f;
  82. if (SamplePtr != NULL && (SampleIndex + FirstSample < SampleCount))
  83. {
  84. rMult = 0.5f * (1.f - FMath::Cos(precomputeMultiplier * SampleIndex));
  85. }
  86. for (int32 ChannelIndex = 0; ChannelIndex < NumChannels; ChannelIndex++)
  87. {
  88. // Make sure the Point is Valid and we don't go out of bounds
  89. if (SamplePtr != NULL && (SampleIndex + FirstSample < SampleCount))
  90. {
  91. // Use Window function to get a better result for the Data (Hann Window)
  92. Buffer[ChannelIndex][SampleIndex].r = rMult * (*SamplePtr);
  93. }
  94. else
  95. {
  96. Buffer[ChannelIndex][SampleIndex].r = 0.f;
  97. }
  98. Buffer[ChannelIndex][SampleIndex].i = 0.f;
  99. // Take the next Sample
  100. SamplePtr++;
  101. }
  102. }
  103. // Now that the Buffer is filled, use the FFT
  104. for (int32 ChannelIndex = 0; ChannelIndex < NumChannels; ChannelIndex++)
  105. {
  106. if (Buffer[ChannelIndex])
  107. {
  108. kiss_fftnd(STF, Buffer[ChannelIndex], Output[ChannelIndex]);
  109. }
  110. }
  111. OutFrequencies.AddZeroed(SamplesToRead);
  112. for (int32 SampleIndex = 0; SampleIndex < SamplesToRead; ++SampleIndex)
  113. {
  114. float ChannelSum = 0.0f;
  115. for (int32 ChannelIndex = 0; ChannelIndex < NumChannels; ++ChannelIndex)
  116. {
  117. if (Output[ChannelIndex])
  118. {
  119. // With this we get the actual Frequency value for the frequencies from 0hz to ~22000hz
  120. ChannelSum += FMath::Sqrt(FMath::Square(Output[ChannelIndex][SampleIndex].r) + FMath::Square(Output[ChannelIndex][SampleIndex].i));
  121. }
  122. }
  123. if (bNormalizeOutputToDb)
  124. {
  125. OutFrequencies[SampleIndex] = FMath::LogX(10, ChannelSum / NumChannels) * 10;
  126. } else
  127. {
  128. OutFrequencies[SampleIndex] = ChannelSum / NumChannels;
  129. }
  130. }
  131. // Make sure to free up the FFT stuff
  132. // KISS_FFT_FREE(STF);
  133. for (int32 ChannelIndex = 0; ChannelIndex < NumChannels; ++ChannelIndex)
  134. {
  135. KISS_FFT_FREE(Buffer[ChannelIndex]);
  136. KISS_FFT_FREE(Output[ChannelIndex]);
  137. }
  138. } else {
  139. PrintError(TEXT("InSoundVisData.PCMData is a nullptr!"));
  140. }
  141. } else {
  142. PrintError(TEXT("Number of Channels is < 0!"));
  143. }
  144. }
  145. void URenderWaveform::BP_RenderWaveform(USoundWave* InSoundWaveRef, UProceduralMeshComponent* Mesh, float InSongPosition, int SizeX){
  146. if (!IsValid(InSoundWaveRef)){
  147. return;
  148. }
  149. if (!IsValid(Mesh)){
  150. return;
  151. }
  152. int nbVert = Mesh->GetProcMeshSection(0)->ProcVertexBuffer.Num();
  153. bool valid;
  154. TArray<FVector> Vertices;
  155. TArray<FVector> Normals;
  156. TArray<FVector2D> UV0;
  157. TArray<FLinearColor> VertexColors;
  158. TArray<FProcMeshTangent> Tangents;
  159. Vertices.AddDefaulted(nbVert);
  160. Normals.Init(FVector(0.0f, 0.0f, 1.0f), nbVert);
  161. UV0.AddDefaulted(nbVert);
  162. VertexColors.AddDefaulted(nbVert);
  163. Tangents.Init(FProcMeshTangent(1.0f, 0.0f, 0.0f), nbVert);
  164. for (size_t i = 0; i < 160; ++i){
  165. float duration = (1 / 64.f);
  166. float startTime = duration * i + InSongPosition;
  167. valid = true;
  168. if (startTime < 0.0f || startTime >= InSoundWaveRef->Duration || startTime + duration >= InSoundWaveRef->Duration) {
  169. valid = false;
  170. }
  171. TArray<float> results;
  172. if (valid) CalculateFrequencySpectrum(InSoundWaveRef, startTime, duration, results);
  173. for (size_t j = 0; j < 64; ++j){
  174. float height;
  175. if (valid) height = results[j * 8.f] / 50000.f;
  176. else height = 0;
  177. Vertices[To1D(i, j, SizeX)] = FVector(i, j, height);
  178. VertexColors[To1D(i, j, SizeX)] = FLinearColor(height, 0.0f, 0.0f);
  179. }
  180. }
  181. Mesh->UpdateMeshSection_LinearColor(0, Vertices, Normals, UV0, VertexColors, Tangents);
  182. return;
  183. }
  184. void URenderWaveform::BP_GenerateSpectrogramMesh(UProceduralMeshComponent* Mesh, int SizeX, int SizeY)
  185. {
  186. if (!IsValid(Mesh) || SizeX <= 0 || SizeY <= 0) {
  187. return;
  188. }
  189. TArray<FVector> Vertices;
  190. TArray<int> Faces;
  191. TArray<FVector> Normals;
  192. TArray<FVector2D> UV0;
  193. TArray<FLinearColor> VertexColors;
  194. TArray<FProcMeshTangent> Tangents;
  195. Vertices.AddDefaulted(SizeX * SizeY);
  196. Normals.AddDefaulted(SizeX * SizeY);
  197. UV0.AddDefaulted(SizeX * SizeY);
  198. VertexColors.AddDefaulted(SizeX * SizeY);
  199. Tangents.AddDefaulted(SizeX * SizeY);
  200. Faces.AddZeroed((SizeX - 1) * (SizeY - 1) * 6);
  201. for (int j = 0; j < SizeY; ++j)
  202. {
  203. for (int i = 0; i < SizeX; ++i)
  204. {
  205. Vertices[To1D(i, j, SizeX)] = FVector(i,j, 0.0f);
  206. Normals[To1D(i, j, SizeX)] = FVector(0.0f, 0.0f, 1.0f);
  207. UV0[To1D(i, j, SizeX)] = FVector2D(0.0f, 0.0f);
  208. VertexColors[To1D(i, j, SizeX)] = FLinearColor(0.0f, 0.0f, 0.0f);
  209. Tangents[To1D(i, j, SizeX)] = FProcMeshTangent(1.0f, 0.0f, 0.0f);
  210. }
  211. }
  212. for (int j = 0; j < SizeY - 1; ++j)
  213. {
  214. for (int i = 0; i < SizeX - 1; ++i)
  215. {
  216. Faces[To1D(i, j, SizeX - 1) * 6] = To1D(i, j, SizeX);
  217. Faces[To1D(i, j, SizeX - 1) * 6 + 1] = To1D(i, j + 1, SizeX);
  218. Faces[To1D(i, j, SizeX - 1) * 6 + 2] = To1D(i + 1, j, SizeX);
  219. Faces[To1D(i, j, SizeX - 1) * 6 + 3] = To1D(i + 1, j, SizeX);
  220. Faces[To1D(i, j, SizeX - 1) * 6 + 4] = To1D(i, j + 1, SizeX);
  221. Faces[To1D(i, j, SizeX - 1) * 6 + 5] = To1D(i + 1, j + 1, SizeX);
  222. }
  223. }
  224. Mesh->CreateMeshSection_LinearColor(0, Vertices, Faces, Normals, UV0, VertexColors, Tangents, false);
  225. }
  226. int URenderWaveform::To1D(int x, int y, int sizeX)
  227. {
  228. return (sizeX * y) + x;
  229. }