#!/usr/bin/env scalas

// https://github.com/sannies/mp4parser

/***

scalaVersion := "2.11.5"

libraryDependencies ++= Seq(
  "com.googlecode.mp4parser" % "isoparser" % "1.1.7")

*/

import com.coremedia.iso.IsoTypeReader
import com.googlecode.mp4parser.DataSource
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.util.Arrays
import java.util.List

val containers = Seq(
  "moov",
  "trak",
  "mdia",
  "minf",
  "udta",
  "stbl")

val file = new File(args(0))
val fileChannel = new FileInputStream(file).getChannel

val fsize = fileChannel.size()
val megabytes = fsize / (math.pow(1024, 2))
println(s"File: $file ($fsize bytes, $megabytes MB)")
printAtom(fileChannel, 0, 0, 0)



def printAtom(fc: FileChannel, level: Int, start: Long, _end: Long): Unit = {
  fc.position(start)
  val end = if (_end <= 0) start + fc.size else _end
  if (end != _end) println(s"Setting END to $end")

  while (end - fc.position() > 8) {
    val begin = fc.position()
    val bb = ByteBuffer.allocate(8)
    fc.read(bb)
    bb.rewind()
    val size = IsoTypeReader.readUInt32(bb);
    val _type = IsoTypeReader.read4cc(bb);
    val fin = begin + size
    val prefix = " " * level // Indent by required number of spaces
    println(s"${prefix}- Atom: ${_type} @ ${begin} ($size bytes)")
    if (containers.contains(_type)) {
        printAtom(fc, level + 1, begin + 8, fin)
        if (fc.position() != fin) {
          println(s"End of container contents at ${fc.position()}")
          println(s"  FIN = $fin")
        }
    }
    fc.position(fin)
  }
}

