!7

lib 1400511 // VorbisJava (to unpack ogg file)
lib 1400502 // Concentus 1.0 (to decode OPUS audio in ogg file)

import org.gagravarr.opus.*;
import org.concentus.*;

cm TestConcentus > DynSingleFunctionWithPrintLog {
  S oggSnippetID = #1400517;
  transient L<short[]> samples;
  
  @Override void doIt() ctex {
    OpusDecoder decoder = new(48000, 1); // decode mono
    
    File f = loadLibrary(#1400517);
    temp OpusFile opusFile = new(f);
    
    samples = new L;
    short[] pcm = new[5760]; // max opus frame size (mono)
    
    OpusAudioData data;
    while ((data = opusFile.getNextAudioPacket()) != null) {
      byte[] bytes = data.getData();
      if (empty(bytes)) continue;
      print("Got compressed audio data: " + l(bytes));
      
      int nSamples = decoder.decode(bytes, 0, l(bytes), pcm, 0, l(pcm), false);
      print("Got " + nSamples(nSamples));
      samples.add(cloneSubShortArray(pcm, 0, nSamples));
    }
    print("Done");
    
    File wavFile = programFile("output.wav");
    multiShortArraysToWAVE(samples, wavFile, format := javaSound_opusMono());
    printFileInfo(wavFile);
    
    showGraph();
  }
  
  void showGraph {
    var pcm = random(samples);
    print("Chose PCM: " + l(pcm));
    dm_showImageAs("Decoded Audio Sample", shortArrayToGraph(pcm));
  }
}