#------------------------------------------------------------------------
#
# 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 outbssize 65536
set inbp [bitparser_new]
set inbs [bitstream_mmap_read_new $streams]
set outbs [bitstream_new $outbssize]
set file [open $outfile w]
fconfigure $file -translation binary -buffersize 65536
#set len [bitstream_channel_read $bs $file 0]
bitparser_wrap $inbp $inbs
set pkthdr [mpeg_pkt_hdr_new]
set currout 0

while {1} {

#   Find the header.  If not found, we are done.

    set len     [mpeg_pkt_hdr_find $inbp]
    if {$len == -1} {
    	break
    }

#   Parse the header and check for stream id.

    set len     [mpeg_pkt_hdr_parse $inbp $pkthdr]

    set sid      [mpeg_pkt_hdr_get_stream_id $pkthdr]
    if {[expr $sid - 192] != $id} {
    	continue
    }

#   so far so good. this is the stream we want.
#   calculate the length and dump it.

    set pktlen  [mpeg_pkt_hdr_get_length $pkthdr]
    set len     [expr $pktlen + 6 - $len]
    set currin  [bitparser_tell $inbp]

#   if the bitstream is going to be full, flush the bitstream 
#   to the output file  
#   NOTE : instead of flushing, you can do other things here, 
#   e.g. decode the mpeg.

    if {[expr $currout + $len] > $outbssize} {
	bitstream_channel_write_segment $outbs $file 0 $currout
	set currout 0
    }
    bitstream_dump $inbs $currin $outbs $currout $len
    bitparser_seek $inbp [expr $len + $currin]
    set currout [expr $len + $currout]
}

bitstream_channel_write_segment $outbs $file 0 $currout
close $file