#------------------------------------------------------------------------
#
# 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 DvmMpeg

if {$argc < 3} {
    puts "enter MPEG system streams input file :"
    set streams [gets stdin]
    puts "enter stream id you want to extract :"
    set id [gets stdin]
    puts "enter output filename :"
    set outfile [gets stdin]
} else {
    set streams [lindex $argv 0]
    set id [lindex $argv 1]
    set outfile [lindex $argv 2]
}

#----------------------------------------------------------------
# open file, create new bitparser, new bitstream, read first 
# 65535 bytes from file into bitstream and attached the bitparser
# to the bitstream
#----------------------------------------------------------------
set bp   [bitparser_new]
set bs   [bitstream_new 65535]
set file [open $streams r]
fconfigure $file -translation binary -buffersize 65535
set len [bitstream_channel_read $bs $file 0]
bitparser_wrap $bp $bs

#----------------------------------------------------------------
# build the system toc
#----------------------------------------------------------------
set toc [mpeg_sys_toc_new]
set off 0
mpeg_sys_toc_add $bp $toc $off
while {![eof $file]} {
    set pos [bitparser_tell $bp]
    set bytesInBuf [expr 65535-$pos]
    bitstream_shift $bs $pos
    set off [expr $off + $pos]
    bitstream_channel_read $bs $file $bytesInBuf
    bitparser_seek $bp 0
    mpeg_sys_toc_add $bp $toc $off
}


#----------------------------------------------------------------
# use the toc to demux the video stream
#----------------------------------------------------------------
seek $file 0
set outfile [open $outfile w]
fconfigure $outfile -translation binary -buffersize 65535
set index [ mpeg_sys_toc_get_filter $toc $id]
set len [ bitstream_channel_filter_in $bs $file 0 $index ]
while {$len == 65535} {
    bitstream_channel_write_segment $bs $outfile 0 $len
    set len [bitstream_channel_filter_in $bs $file 0 $index]
}
bitstream_channel_write_segment $bs $outfile 0 $len
mpeg_sys_toc_free $toc
bitstream_free $bs