 (ns sormilla.video
   (:import [com.twilight.h264.decoder AVFrame AVPacket H264Decoder MpegEncContext]
            [com.twilight.h264.player FrameUtils]
+           [org.opencv.core CvType Mat MatOfByte]
+           [org.opencv.highgui Highgui]
            [java.util Arrays]
-           [java.awt.image BufferedImage]))
+           [java.awt RenderingHints]
+           [java.awt.image BufferedImage]
+           [java.net Socket]
+           [javax.imageio ImageIO]
+           [java.io FileOutputStream DataOutputStream File ByteArrayInputStream]
+           [javax.swing JFrame JPanel]
+           [java.awt FlowLayout])
+  (:require [sormilla.bin :as bin]))
 
 (def INBUF_SIZE 65535)
 (def inbuf-int (int-array (+ INBUF_SIZE MpegEncContext/FF_INPUT_BUFFER_PADDING_SIZE)))
-(def avpkt (AVPacket.))
-(.av_init_packet avpkt)
-
+(def avpkt (doto (AVPacket.) (.av_init_packet)))
 (def codec (H264Decoder.))
-(if (nil? codec) (println "Codec not found"))
 (def c (MpegEncContext/avcodec_alloc_context))
 (def picture (AVFrame/avcodec_alloc_frame))
 
 (if-not (zero? (bit-and (.capabilities codec) H264Decoder/CODEC_CAP_TRUNCATED))
-  (println "need to configure CODEC_FLAG_TRUNCATED"))
-
+  (throw (Exception. "need to configure CODEC_FLAG_TRUNCATED")))
 (if (< (.avcodec_open c codec) 0)
-  (println "Could not open codec"))
+  (throw (Exception. "Could not open codec")))
 
 (defn to-ba-int [b]
   (doall (for [i (range 0 (count b))]

      (swap! frame-number inc)
      (future (update-image (process-and-return-image buff-img))))
    (catch Exception e (println (str "Error displaying frame - skipping " e)))))

(defn read-frame [host out]
  (try

(defn read-signature [in]
  (String. (byte-array (map #(nth in %1) [0 1 2 3]))))

(defn get-header [in]
  {:version              (bin/get-byte in 4)
   :codec                (bin/get-byte in 5)
   :header-size          (bin/get-short in 6)
   :payload-size         (bin/get-int in 8)
   :encoded-width        (bin/get-short in 12)
   :encoded-height       (bin/get-short in 14)
   :display-width        (bin/get-short in 16)
   :display-height       (bin/get-short in 18)
   :frame-number         (bin/get-int in 20)
   :timestamp            (bin/get-int in 24)
   :total-chunks         (bin/get-byte in 28)
   :chunk-index          (bin/get-byte in 29)
   :frame-type           (bin/get-byte in 30)
   :control              (bin/get-byte in 31)
   :stream-byte-pos-lw   (bin/get-int in 32)
   :stream-bypte-pos-uw  (bin/get-int in 36)
   :stream-id            (bin/get-short in 40)
   :total-slices         (bin/get-byte in 42)
   :slice-index          (bin/get-byte in 43)
   :header1-size         (bin/get-byte in 44)
   :header2-size         (bin/get-byte in 45)
   :advertised-size      (bin/get-int in 48)})

(defn payload-size [in]
  (:payload-size (get-header in)))
