;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;

;; Buffered Video

;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; define global canvas

(define *canvas* (gfx:make-canvas 640 480))


;; start live video feed

(gfx:start-live-video)


;; define 4 empty video buffers using a vector

;; vectors are another scheme data type similar to standard arrays

;; we define *vid-buffers* to be a vector of 4 empty lists

(define *vid-buffers* (vector (list) (list) (list) (list)))


;; define function to recursively record a list (lst) of video

;;

;; duration = is the time we want to record for

;; buffer = the index number into *vid-buffers* (i.e. which list to record into)

;; lst = is a list we build and then set to *vid-buffers* index

(define vid-record

   (lambda (duration buffer lst) 

      (if (> duration 0)

          (callback (+ (now) 4000) vid-record 

                    (- duration 4000)

                    buffer

                    (cons (gfx:convert-image (gfx:get-live-frame)) lst))

          (vector-set! *vid-buffers* buffer (reverse lst)))))


;; playback randomly choosing one of the 4 video buffers contained in *vid-buffers*

;; lst = the list of images we playback using.  whenever lst runs out we randomly 

;; eset it to be one of the four lists contained in the vector *vid-buffers*

;;

;; Note that our playback rate is twice the speed of our record rate

;; (i.e. it will playback at double speed)

(define playback

   (lambda (lst)

      (if (null? lst)

          (set! lst (vector-ref *vid-buffers* (random 0 4))))

      (gfx:draw-image (now) *canvas* (car lst) 1.0)

      (callback (+ (now) 2000) 'playback (cdr lst))))


;; record into buffer one for .5 of a second

(vid-record (* 0.5 *second*) 0 (list))


;; record into buffer two for 1 second

(vid-record (* 1.0 *second*) 1 (list))


;; record into buffer three for 2 seconds

(vid-record (* 2.0 *second*) 2 (list))


;; record into buffer four for 4 seconds

(vid-record (* 4.0 *second*) 3 (list))


;; start playback

;; after playback is started you can re-record any buffer at any time

(callback (+ (now) (* 5 *second*)) 'playback (list))