package ocelot.desktop.audio

import de.jarnbjo.ogg.{BasicStream, EndOfOggStreamException, LogicalOggStream}
import de.jarnbjo.vorbis.VorbisStream

import java.io.{ByteArrayOutputStream, InputStream}
import java.nio.ByteBuffer

object OggDecoder {
  def decode(input: InputStream): SoundSamples = {
    val stream =
      new VorbisStream(new BasicStream(input).getLogicalStreams.iterator().next().asInstanceOf[LogicalOggStream])

    val rate = stream.getIdentificationHeader.getSampleRate
    val channels = stream.getIdentificationHeader.getChannels

    val buffer = new Array[Byte](8192)
    val dataOut = new ByteArrayOutputStream()

    try {
      while (true) {
        val read = stream.readPcm(buffer, 0, buffer.length)
        var i = 0
        while (i < read) {
          val tB = buffer(i)
          buffer(i) = buffer(i + 1)
          buffer(i + 1) = tB
          i += 2
        }
        dataOut.write(buffer, 0, read)
      }
    } catch {
      case _: EndOfOggStreamException =>
    }

    val data = ByteBuffer.allocateDirect(dataOut.size())
    data.put(dataOut.toByteArray)
    data.rewind()

    val format = channels match {
      case 1 => SoundSamples.Format.Mono16
      case 2 => SoundSamples.Format.Stereo16
    }

    SoundSamples(data, rate, format)
  }
}
