#------------------------------------------------------------------------
#
# Copyright (c) 1997-1998 by Cornell University.
# 
# See the file "license.txt" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
#------------------------------------------------------------------------
package require DvmBasic
package require DvmAvi
package require DvmPnm

#---------------------------------------------------------------
# This script decodes an avi video stream into a series of ppms
#---------------------------------------------------------------

#---------------------------------------------------------------
# This procedure encode 3 byte image into a bitstream bs,
# using bitparser bp, and output it to a tcl channel called
# name.  Assumes that the header is already encoded in the 
# bitstream.  (This is an improvement over the routines in pnmlib.tcl
# since it reuse the same header and bitstream)
#---------------------------------------------------------------
proc write_ppm {r g b bs bp name} {
    set chan [open $name w]
    fconfigure $chan -translation binary -buffersize 65536
    set curr [bitparser_tell $bp]
    ppm_encode $r $g $b $bp
    bitstream_channel_write $bs $chan 0
    bitparser_seek $bp $curr
    close $chan
}


if {$argc != 1} {
    puts "enter input mpeg file :"
    set inname [gets stdin]
} else {
    set inname [lindex $argv 0]
}

set hdr [avi_file_open "$inname"]
set shdr [avi_stream_open $hdr 0]

set w [avi_stream_get_width $shdr]
set h [avi_stream_get_height $shdr]
set ln [avi_stream_get_length $shdr]

set r [byte_new $w $h]
set g [byte_new $w $h]
set b [byte_new $w $h]

#----------------------------------------------------------------
# initialize stuff for ppm file output
# we only need to write the header once.
#----------------------------------------------------------------
set pnmhdr  [pnm_hdr_new]
pnm_hdr_set_type   $pnmhdr "ppm-bin"
pnm_hdr_set_width  $pnmhdr $w 
pnm_hdr_set_height $pnmhdr $h
pnm_hdr_set_maxval $pnmhdr 255
set outbs   [bitstream_new [expr 3*$w*$h + 20]]
set outbp   [bitparser_new]
bitparser_wrap $outbp $outbs
pnm_hdr_encode $pnmhdr $outbp
pnm_hdr_free $pnmhdr

#----------------------------------------------------------------
# Now do the decode
#----------------------------------------------------------------
avi_stream_start_decode $shdr

for {set i 0} {$i < $ln} {incr i} {
    avi_video_frame_read $shdr $r $g $b	
    write_ppm $r $g $b $outbs $outbp [format "%03di.ppm" $i] 
    puts -nonewline " $i"
    flush stdout
}

puts ""
byte_free $r
byte_free $g
byte_free $b
avi_stream_close $shdr
avi_file_close $hdr