My First Lisp Program
I wrote a simple timecode generator for testing of the
Video Annotation and Reference System in
Groovy. The program listens for requests on a UDP port and responds with a String formated as a timecode. For grins, I converted the program to
Clojure
Groovy
#!/usr/bin/env groovy
/**
* Script for simulation of a udp VCR
*/
def port = (args.size() > 0) ? Integer.valueOf(args[0]) : 9000
println("Localtime timecode generator attached to port ${port}")
def socket = new DatagramSocket(port)
def buffer = (' ' * 4096) as byte[]
while(true) {
def incoming = new DatagramPacket(buffer, buffer.length)
socket.receive(incoming)
def c = new GregorianCalendar()
def f = c.get(Calendar.MILLISECOND) / 1000.0 * 29.97;
String reply = String.format('%tT:%02d', c, Math.round(f))
outgoing = new DatagramPacket(reply.bytes, reply.size(),
incoming.address, incoming.port);
socket.send(outgoing)
}
Clojure
(import
'(java.net DatagramPacket DatagramSocket)
'(java.util GregorianCalendar Calendar))
(defn fmt-time
"Format a java Calendar as a timecode"
[cal]
(let [frames (* (/ (. cal get (Calendar/MILLISECOND)) 1000) 29.97)]
(format "%tT:%02d" cal (Math/round frames))))
(defn run-generator
"Function for simulation of a udp VCR"
[port]
(println (str "Localtime timecode generator attached to port " port))
(let [socket (new DatagramSocket port)
buffer (make-array (Byte/TYPE) 4096)]
(while true
(let [incoming (new DatagramPacket buffer 4096)
reply (fmt-time (new GregorianCalendar))]
(. socket receive incoming)
(let [outgoing (new DatagramPacket (. reply getBytes) (. reply length) (. incoming getAddress) (. incoming getPort))]
(. socket send outgoing))))))
(run-generator (Integer/parseInt (first *command-line-args*)))
0 comments:
Post a Comment