#!avview_shell
#
#


#
# Initialize some global variables
#
foreach {variable value } {
	ffmpeg_max_fifo_size 32
	ffmpeg_recording_chunk_size 2000
	current_video_rate 59.94
	ffmpeg_video_bitrate 300000
	ffmpeg_video_quality 2
	ffmpeg_video_bitrate_control "Fix quality"
	ffmpeg_video_codec "MPEG-1"
	ffmpeg_audio_sample_rate 48000
	ffmpeg_audio_bitrate 64000
	ffmpeg_audio_codec "MPEG-2"
	ffmpeg_file_format "MPEG"
	current_alsa_capture_device "none"
	} {
	global $variable
	set $variable $value
	}


#
#
# Heuristic to figure out a good ffmpeg_max_fifo_size
#
catch { 
	set core_size [file size /proc/kcore]
	set ffmpeg_max_fifo_size [expr $core_size/(2*1024*1024)]
	}

proc generate_capture_window { cw } {
global capture_window
foreach win [grid slaves $cw] { destroy $win }

if { !$capture_window } { 
	grid columnconfigure .controlwin 1 -weight 0
	canvas $cw.f -width 0 -height 0 -background red
	grid $cw.f
	return 
	}
grid columnconfigure .controlwin 1 -weight 1

eval label $cw.title -text "\"Capture (V4L)\"" [get_settings $cw.title Capture V4L]
grid $cw.title - - -sticky news -pady 2 -padx 2
grid columnconfigure $cw 1 -weight 1

eval label $cw.devicel -text "\"V4L device: \"" [get_settings $cw.devicel label Capture V4L]
global v4l_device_menu
set v4l_device_menu [tk_optionMenu $cw.device_optionmenu current_v4l_device none]
eval $cw.device_optionmenu configure [get_settings $cw.device_optionmenu Capture V4L]
eval $v4l_device_menu configure [get_settings $v4l_device_menu Capture V4L menu]

eval button $cw.rescan_button -text "Rescan" -command rescan_v4l_devices [get_settings $cw.rescan_button Capture V4L]
grid $cw.devicel $cw.device_optionmenu $cw.rescan_button -sticky news
grid configure $cw.devicel -sticky nws

if { [alsa_present] } {
	eval label $cw.alsadevicel -text "\"ALSA device: \"" [get_settings $cw.alsadevicel label Capture V4L]
	global v4l_alsadevice_menu current_alsa_capture_device
	set old_value $current_alsa_capture_device
	set v4l_alsadevice_menu [tk_optionMenu $cw.alsadevice_optionmenu current_alsa_capture_device none]
	eval $cw.alsadevice_optionmenu configure [get_settings $cw.alsadevice_optionmenu Capture V4L]
	eval $v4l_alsadevice_menu configure [get_settings $v4l_alsadevice_menu Capture V4L menu]
	eval button $cw.rescan_ad_button -text "Rescan" [get_settings $cw.rescan_button Capture V4L]
	$cw.rescan_ad_button configure -command "rescan_alsa_devices $v4l_alsadevice_menu current_alsa_capture_device"
	grid $cw.alsadevicel $cw.alsadevice_optionmenu $cw.rescan_ad_button -sticky news
	grid configure $cw.alsadevicel -sticky nws
	after idle [subst -nocommands {
		$cw.rescan_ad_button invoke
		global current_alsa_capture_device
		set current_alsa_capture_device "$old_value"
		} ]
	}

eval label $cw.windowl -text "\"Window: \""  [get_settings $cw.windowl label Capture V4L]
eval label $cw.window -text "\"N/A\"" [get_settings $cw.window label Capture V4L]
eval button $cw.window_button -text "Change" -state disabled [get_settings $cw.window_button Capture V4L]
grid $cw.windowl $cw.window $cw.window_button
grid configure $cw.windowl -sticky nws
grid configure $cw.window_button -sticky news


eval label $cw.encoding_themel -text "\"Encoding theme: \"" [get_settings $cw.encoding_themel label Capture V4L]
set menu [tk_optionMenu $cw.encoding_theme_optionmenu ffmpeg_encoding_theme None]
global panel_encoding_theme_menu
set panel_encoding_theme_menu $menu
$menu delete 0 end
global encoding_themes_list
foreach theme $encoding_themes_list {
	$menu add radiobutton -label "$theme" -value "$theme" -variable ffmpeg_encoding_theme
	}
eval $cw.encoding_theme_optionmenu configure [get_settings $cw.encoding_theme_optionmenu Capture V4L]
eval $menu configure [get_settings $menu Capture V4L menu]
eval button $cw.encoding_theme_button -text "Set" -command set_encoding_theme [get_settings $cw.window_button Capture V4L]
grid $cw.encoding_themel $cw.encoding_theme_optionmenu $cw.encoding_theme_button -sticky news
grid configure $cw.encoding_themel $cw.encoding_theme_button -sticky nws

if {[ffmpeg_present] == "yes"} {
#	eval label $cw.rratel -text "\"Recording framerate: \"" [get_settings $cw.rratel Capture V4L]
#	set menu [tk_optionMenu $cw.rrate_optionmenu current_v4l_rrate "as is" "one half" "one quarter"]
#	eval $cw.rrate_optionmenu configure [get_settings $cw.rrate_optionmenu Capture V4L]
#	eval $menu configure [get_settings $menu Capture V4L menu]
#	grid $cw.rratel $cw.rrate_optionmenu - -sticky news
#	grid configure $cw.rratel -sticky nws

	eval label $cw.video_ratel -text "\"V4L device framerate:\"" [get_settings $cw.video_ratel label Capture V4L]
	entry $cw.video_rate_entry -textvariable current_video_rate
	eval $cw.video_rate_entry configure [get_settings $cw.video_rate_entry Capture V4L]
	grid $cw.video_ratel $cw.video_rate_entry
	grid configure $cw.video_ratel -sticky nws
	grid configure $cw.video_rate_entry -sticky news

	eval label $cw.filenamel -text "\"Save to file:\"" [get_settings $cw.filenamel label Capture V4L]
	eval entry $cw.filename_entry -textvariable current_capture_filename [get_settings $cw.filename_entry Capture V4L]
	button $cw.filename_button -text "Change" -command {
		global current_capture_filename; 
		global file_save_path;
		set result [tk_getSaveFile -initialfile "[file tail "$current_capture_filename"]" \
			-parent .controlwin -title "Specify base name of file(s) to hold recorded video"  \
			-filetypes { {"All files" { * } } { "Mpeg streams" { *.mpg *.MPG} } \
				{ "\"AVI streams\"" { *.avi *.AVI} } }\
				-initialdir "$file_save_path" \
			] ; 
#		if { ($result != "") && [file exists $result] } { 
#			set extension [file extension $result]
#			set rootname [file rootname $result]
#			if { [regsub -- "-\[0123456789\]\$" $rootname "" a] } {
#				set rootname "$a"
#				}
#			for { set i 1 } { 1 } { incr i } {
#				if { ![file exists "$rootname-$i$extension"] } {
#					break
#					}
#				}
#			set result "$rootname-$i$extension"
#			}
		if { ($result != "") } {
			set current_capture_filename [file tail $result]
			set file_save_path [file dirname $result]
			}		
		}
	eval $cw.filename_button configure [get_settings $cw.filename_button Capture V4L]
	grid $cw.filenamel $cw.filename_entry $cw.filename_button
	grid configure $cw.filenamel -sticky nws
	grid configure $cw.filename_entry -sticky news
	grid configure $cw.filename_button -sticky news

	button $cw.snapshot_button -text "Snapshot" -command capture_snapshot 
	eval $cw.snapshot_button configure [get_settings $cw.snapshot_button Capture V4L]
#	button $cw.monitor_button -text "Monitor" -command "create_monitor_window $cw"
#	eval $cw.monitor_button configure [get_settings $cw.monitor_button Capture V4L]
	checkbutton $cw.record_button -text "Record" -variable v4l_capture_on \
		-indicatoron false 
	eval $cw.record_button configure [get_settings $cw.record_button Capture V4L]
#	grid $cw.snapshot_button $cw.monitor_button $cw.record_button -sticky ns -padx 5
	grid $cw.snapshot_button $cw.record_button -sticky ns -padx 5

	frame $cw.video_stats 
	eval $cw.video_stats configure [get_settings $cw.video_stats Capture V4L]
	grid $cw.video_stats - - -sticky news

        make_video_stats $cw.video_stats

	} {
	button $cw.snapshot_button -text "Snapshot" -command capture_snapshot 
	eval $cw.snapshot_button configure [get_settings $cw.snapshot_button Capture V4L]
	grid x $cw.snapshot_button
	}
after idle rescan_v4l_devices
}

proc rescan_v4l_devices {} {
global v4l_device_menu
global current_v4l_device
set current_v4l_device none
$v4l_device_menu delete 0 end
$v4l_device_menu add radiobutton -label "none"\
				-value "none" -variable current_v4l_device
$v4l_device_menu add radiobutton -label "automatic"\
				-value "automatic" -variable current_v4l_device
for {set i 0 } {$i < 10 } { incr i } {
	set status "[v4l_open_device rescan_handle /dev/video$i]"
	if { "$status" == "" } {
		set type [v4l_device_type rescan_handle]
		if { [lsearch $type capture] >= 0 } {
			$v4l_device_menu add radiobutton -label "/dev/video$i: [v4l_device_name rescan_handle]"\
				-value "/dev/video$i" -variable current_v4l_device
			}
		v4l_close_device rescan_handle
		}
	}
}

proc update_v4l_window_info {cw} {
global current_v4l_device
global current_v4l_mode
if { ! [winfo exists $cw] } {
	return 
	}
if { ! [winfo exists $cw.window] } {
	return
	}
if { "$current_v4l_device" == "none" } { 
	$cw.window configure -text "N/A"
	return 
	}
set window [v4l_get_current_window current_v4l_handle]
switch "$current_v4l_mode" \
	"single-frame" {
		$cw.window configure -text "[lindex $window 2]x[lindex $window 3]+[lindex $window 0]+[lindex $window 1]"
		} \
	"deinterlace-bob" {
		$cw.window configure -text "[lindex $window 2]x[expr [lindex $window 3]*2]+[lindex $window 0]+[expr [lindex $window 1]*2]"
		}\
	"double-interpolate" {
		$cw.window configure -text "[lindex $window 2]x[expr [lindex $window 3]*2]+[lindex $window 0]+[expr [lindex $window 1]*2]"
		}\
	"deinterlace-weave" {
		$cw.window configure -text "[lindex $window 2]x[expr [lindex $window 3]*2]+[lindex $window 0]+[expr [lindex $window 1]*2]"
		}\
	"half-width" {
		$cw.window configure -text "[expr [lindex $window 2]/2]x[lindex $window 3]+[lindex $window 0]+[expr [lindex $window 1]*2]"
		}

}

proc set_v4l_device {cw name1 name2 op } {
global current_v4l_device
global v4l_capture_on
v4l_close_device current_v4l_handle
if { "$current_v4l_device" == "none" } { 
	set v4l_capture_on false
	catch {
	#	$cw.snapshot_button configure -state disabled
		}
	return 
	}
if { $current_v4l_device == "automatic" } {	
	global primary_v4l_device
	if { ! [info exists primary_v4l_device] } { update_primary_globals }
	if { $primary_v4l_device == "" } { update_primary_globals }
	set v4l_device $primary_v4l_device
	if { $v4l_device != "none" } {
		set status "[v4l_open_device current_v4l_handle $v4l_device]"
		} {
		tk_dialog .controlwin.a "Could not find v4l device" "Could not find device corresponding to the current display. It could be that km is not loaded,\n you need to upgrade to a more recent version of km or avview\n or requred /dev/videoX device does not exist." "" 0 "Acknowledge"
		set current_v4l_device "none"
		return
		}
	} {
	set status "[v4l_open_device current_v4l_handle $current_v4l_device]"
	}
if { "$status" != "" } {
	set current_v4l_device "none"
	}
$cw.snapshot_button configure -state normal
update_v4l_window_info $cw
}

global snp_window_count
set snp_window_count 0

proc capture_snapshot {} {
global current_v4l_device
global snp_window_count
global current_v4l_mode
if { "$current_v4l_device" == "none" } {
	set current_v4l_device "automatic"
	}
if { "$current_v4l_device" == "none" } {
	return
	}
incr snp_window_count
image create photo .snapshot$snp_window_count.image
v4l_capture_snapshot current_v4l_handle .snapshot$snp_window_count.image $current_v4l_mode {
	global snp_window_count
	create_snapshot_window .snapshot$snp_window_count.image
	} {
	global snp_window_count
	puts "Error capturing image $snp_window_count" 
	}
}

proc create_snapshot_window {image} {
global control_screen
global snp_window_count
set sw .snapshot$snp_window_count
if { "$control_screen" != "" } {
	toplevel $sw -screen "$control_screen"
	} {
	toplevel $sw
	}
wm title $sw "Snapshot $snp_window_count"
eval frame $sw.f [get_settings $sw.f Capture V4L]
grid $sw.f - -sticky news
canvas $sw.c -xscrollcommand "$sw.hscroll set" \
	-yscrollcommand "$sw.vscroll set" -relief sunken -bd 2
scrollbar $sw.vscroll -command "$sw.c yview"
scrollbar $sw.hscroll -command "$sw.c xview" -orient horiz
grid $sw.c $sw.vscroll 
grid $sw.hscroll x
grid configure $sw.c -sticky news
grid configure $sw.vscroll -sticky ns
grid configure $sw.hscroll -sticky ew
grid rowconfig $sw 1 -weight 1
grid columnconfig $sw 0 -weight 1
$sw.c create image 0 0 -anchor nw -image $image
# size the canvas
set screenheight [expr [winfo screenheight $sw.c] - 40]
set screenwidth [expr [winfo screenwidth $sw.c] - 20]
set width [image width $image]
set height [image height $image]

# scrollregion
$sw.c configure -scrollregion "-10 -10 $width $height"

# size - truncate to fit screen
if { $width > $screenwidth } { set width $screenwidth }
if { $height > $screenheight } { set height $screenheight}

$sw.c configure -width $width -height $height

#
# Now populate control frame
#

button $sw.f.sab -text "Save as" -command "save_image_as $sw $image"
eval $sw.f.sab configure [get_settings $sw.f.sab button Capture V4L]

set menu [tk_optionMenu $sw.f.type save_type Postscript PPM]
eval $sw.f.type configure [get_settings $sw.f.type optionmenu menu Capture V4L]
eval $menu configure [get_settings $menu menu Capture V4L]

grid $sw.f.sab $sw.f.type -padx 5
eval $cw.c configure [get_settings $cw.c canvas Capture V4L]
eval $sw.vscroll configure [get_settings $sw.vscroll Capture V4L]
eval $sw.hscroll configure [get_settings $sw.hscroll Capture V4L]
}

proc save_image_as { sw image } {
global save_type
switch "$save_type" \
	"Postscript" {
		set file [tk_getSaveFile -defaultextension .eps \
			-filetypes {{"Postscript" {.eps .ps}} {"All files" {.*}}} -parent $sw]
		if { "$file" != "" } {
			$sw.c postscript -file "$file"
			}
		} \
	"PPM" {
		set file [tk_getSaveFile -defaultextension .ppm \
			-filetypes {{"PPM" {.ppm}} {"All files" {.*}}} -parent $sw]
		if { "$file" != "" } {
			$image write "$file" -format ppm
			}
		}
}

proc verify_v4l_stream_parameters {} {
global v4l_capture_on ffmpeg_video_codec ffmpeg_audio_codec ffmpeg_file_format \
	 current_v4l_mode current_v4l_rrate current_capture_filename current_v4l_device \
	 current_alsa_capture_device file_save_path

if { ("$ffmpeg_file_format" == "none") &&
	("$current_v4l_device" != "none") &&
	("$current_alsa_capture_device" != "none") } {
	tk_dialog .controlwin.capture.wrong_parameters "Incompatible capture parameters" \
		"If you want to record both audio and video the file format must not be \"none\"" ""\
		0 "OK"
	return 0
	}

if { ("$ffmpeg_file_format" == "AVI") } {
	tk_dialog .controlwin.capture.wrong_parameters "Warning" \
		"AVI files are internally limited to 1Gb size\nBe sure to end the capture before this limit is reached" ""\
		0 "OK"
	return 1
	}

if { ("$ffmpeg_file_format" == "MPEG") &&
	( ("$current_v4l_device" != "none" ) && ("$ffmpeg_video_codec" != "MPEG-1") )
	} {
	set ans [tk_dialog .controlwin.capture.wrong_parameters "Incompatible capture parameters" \
		"At the moment mpeg format is not compatible with video formats except mpeg-1.\n Do you want to proceed anyway ?" ""\
		1 "Yes" "No" ]
	if { "$ans" == 0 } { return 1 }
	return 0
	}

return 1
}

proc on_v4l_capture_set {cw name1 name2 w } {
global v4l_capture_on \
 ffmpeg_video_codec ffmpeg_audio_codec \
 ffmpeg_file_format ffmpeg_audio_sample_rate ffmpeg_audio_bitrate \
 ffmpeg_video_bitrate ffmpeg_video_quality ffmpeg_video_bitrate_control \
 current_v4l_mode current_v4l_rrate current_capture_filename \
 current_alsa_capture_device file_save_path \
 current_video_rate current_v4l_device 
if { $v4l_capture_on } {
	if { ! [verify_v4l_stream_parameters] } {
		set v4l_capture_on 0
		after idle "$cw.record_button deselect"
		return
		}
	if { $current_v4l_device == "none" } {
		set current_v4l_device "automatic"
		}
	if { $current_v4l_device == "none" } {
		bell
		set v4l_capture_on 0
		after idle "$cw.record_button deselect"
		return
		}
	set alsa_device $current_alsa_capture_device
	if { $alsa_device != "none" } {
		alsa_hctl_open $alsa_device
		}
	set status [ffmpeg_encode_v4l_stream -v4l_handle current_v4l_handle \
				-video_codec $ffmpeg_video_codec \
				-audio_codec $ffmpeg_audio_codec \
				-deinterlace_mode $current_v4l_mode \
				-step_frames $current_v4l_rrate \
				-av_format $ffmpeg_file_format \
				-audio_device $alsa_device \
				-audio_rate "$ffmpeg_audio_sample_rate" \
				-audio_bitrate "$ffmpeg_audio_bitrate" \
				-v4l_rate "$current_video_rate" \
				-video_bitrate "$ffmpeg_video_bitrate" \
				-video_quality "$ffmpeg_video_quality" \
				-video_bitrate_control "$ffmpeg_video_bitrate_control" \
				-filename "$file_save_path/$current_capture_filename"]
	if { $alsa_device != "none" } {
		# we are not really closing it - just decrementing the use count
		# it will stay up as long as alsa_reader_thread is active
		alsa_hctl_close $alsa_device
		}
	if { "$status" == "" } { 
		after cancel "check_fifo $cw"
		after 800 "check_fifo $cw"
		} {
		tk_messageBox -default ok -icon info -message "Could not start recording:\n$status" \
			-title "Could not start recording" -parent .controlwin -type ok
		set v4l_capture_on false
		}
	puts "status=$status"
	} {
	if { [ffmpeg_present] == "yes" } {
		ffmpeg_stop_encoding
		}
	}
}

proc check_fifo { cw } {
global ffmpeg_max_fifo_size
global ffmpeg_recording_chunk_size
global v4l_capture_on
global file_save_path
global current_capture_filename
if { [ffmpeg_present] == "no" } { return }
catch {
	set status [ffmpeg_encoding_status]
	if { "$status" == "" } {
		reset_video_stats $cw.video_stats
		return
		}
	set size [get_value $status "-total_fifo"]
	if { $v4l_capture_on && ("$size" != "") && ($size > [expr $ffmpeg_max_fifo_size*1024*1024]) } {
		set v4l_capture_on false
		$cw.record_button flash
		tk_dialog .controlwin.limit_reached "Fifo limit reached" "Fifo limit has been reached.\nCapture stopped." "" 0 "OK"
		}
	set length [get_value $status "-encoded_stream_size"]
#	if { $ffmpeg_recording_chunk_size > 2000 } {
#		set ffmpeg_recording_chunk_size 2000
#		}
#	if { $ffmpeg_recording_chunk_size < 10 } {
#		set ffmpeg_recording_chunk_size 10 
#		}
#	if { $ffmpeg_recording_chunk_size < $length } {
#			set result "$file_save_path/$current_capture_filename"
#			set extension [file extension "$result"]
#			set rootname [file rootname "$result"]
#			if { [regsub -- "-\[0123456789\]\$" "$rootname" "" a] } {
#				set rootname "$a"
#				}
#			for { set i 1 } { 1 } { incr i } {
#				if { ![file exists "$rootname-$i$extension"] } {
#					break
#					}
#				}
#			set result "$rootname-$i$extension"
#			set current_capture_filename [file tail "$result"]
#			set file_save_path [file dirname "$result"]
#			ffmpeg_switch_file "$result"
#		}
	update_video_stats $cw.video_stats $status
	}
after 800 "check_fifo $cw"
}

proc make_video_stats { widget } {
label $widget.total_stream_length -text "Total stream length:"
label $widget.total_stream_length_value -text "0 Mb"
eval $widget.total_stream_length configure [get_settings $widget.total_stream_length label Capture V4L]
eval $widget.total_stream_length_value configure [get_settings $widget.total_stream_length_value label value Capture V4L]
grid $widget.total_stream_length $widget.total_stream_length_value -sticky nws -padx 10

label $widget.frames_encoded -text "Video frames encoded:"
label $widget.frames_encoded_value -text "0"
eval $widget.frames_encoded configure [get_settings $widget.frames_encoded label Capture V4L]
eval $widget.frames_encoded_value configure [get_settings $widget.frames_encoded_value label value Capture V4L]
grid $widget.frames_encoded $widget.frames_encoded_value -sticky nws -padx 10

label $widget.fifo_label -text "Fifo size: "
label $widget.fifo_value_label -text "0 Mb"
eval $widget.fifo_label configure [get_settings $widget.fifo_label Capture V4L]
eval $widget.fifo_value_label configure [get_settings $widget.fifo_value_label Capture V4L]
grid $widget.fifo_label $widget.fifo_value_label -sticky nws -padx 10

frame $widget.f
eval $widget.f configure [get_settings $widget.f Capture V4L]
grid $widget.f - - - -sticky news	
grid columnconfig $widget 3 -weight 1
	
label $widget.f.audio_levels_label -text "Audio levels"
eval $widget.f.audio_levels_label configure [get_settings $widget.f.audio_levels_label Capture V4L]

label $widget.f.video_hist_label -text "Luminosity histogram"
eval $widget.f.video_hist_label configure [get_settings $widget.f.video_hist_label Capture V4L]
grid $widget.f.audio_levels_label - $widget.f.video_hist_label
	
canvas $widget.f.left_audio_level  -height 80 -width 20 -relief sunken -borderwidth 1
eval $widget.f.left_audio_level configure [get_settings $widget.f.left_audio_level Capture V4L]
$widget.f.left_audio_level create polygon 1 79 19 79 19 79 1 79 -fill green -tags avg_volume 
$widget.f.left_audio_level create polygon 1 79 19 79 19 79 1 79 -fill yellow -tags top_volume 
$widget.f.left_audio_level create line 1 79 19 79 -fill red -tags top_volume_line 

canvas $widget.f.right_audio_level  -height 80 -width 20 -relief sunken -borderwidth 1
eval $widget.f.right_audio_level configure [get_settings $widget.f.right_audio_level Capture V4L]
$widget.f.right_audio_level create polygon 1 79 19 79 19 79 1 79 -fill green -tags avg_volume 
$widget.f.right_audio_level create polygon 1 79 19 79 19 79 1 79 -fill yellow -tags top_volume 
$widget.f.right_audio_level create line 1 79 19 79 -fill red -tags top_volume_line 

canvas $widget.f.video_hist  -height 80 -width 160 -relief sunken -borderwidth 1
eval $widget.f.video_hist configure [get_settings $widget.f.video_hist Capture V4L]
for {set i 0 } { $i < 31 } { incr i } {
	$widget.f.video_hist create line [expr $i*10] 79 [expr ($i+1)*10] 79 -fill red \
			-tags luma_hist$i
	}

grid $widget.f.left_audio_level $widget.f.right_audio_level $widget.f.video_hist  -padx 5
}

proc update_video_stats { widget status} {
foreach { var value } $status {
	set $var $value
	}
set cheight [$widget.f.video_hist cget -height]
set cwidth [$widget.f.video_hist cget -width]
$widget.fifo_value_label configure -text "[expr $total_fifo/(1024*1024)] Mb"
$widget.total_stream_length_value configure -text "$encoded_stream_size Mb"
$widget.frames_encoded_value configure -text "$frames_encoded"
$widget.f.video_hist configure -scrollregion [list 1 1 [expr $cwidth -1] [expr $cheight-1]]
if { $luma_top_hist == 0 } { set luma_top_hist 1 }
for {set i 0 } { $i < 31 } { incr i } {
	set left_luma [lindex $luma_hist $i]
	set right_luma [lindex $luma_hist [expr $i+1]]
	$widget.f.video_hist coords luma_hist$i [expr 1+($i*($cwidth-2))/31] [expr $cheight-1-(($cheight-2)*$left_luma)/$luma_top_hist] \
		[expr 1+(($i+1)*($cwidth-2))/31] [expr $cheight-1-(($cheight-2)*$right_luma)/$luma_top_hist]
	}
set avg_left_coord [expr 79-($avg_left_level*78)/1000]
$widget.f.left_audio_level coords avg_volume 1 79 20 79 20 $avg_left_coord 1 $avg_left_coord
set top_left_coord [expr 79-($top_left_level*78)/1000]
$widget.f.left_audio_level coords top_volume 1 $avg_left_coord 20 $avg_left_coord 20 $top_left_coord 1 $top_left_coord
$widget.f.left_audio_level coords top_volume_line 1 $top_left_coord 20 $top_left_coord

set avg_right_coord [expr 79-($avg_right_level*78)/1000]
$widget.f.right_audio_level coords avg_volume 1 79 20 79 20 $avg_right_coord 1 $avg_right_coord
set top_right_coord [expr 79-($top_right_level*78)/1000]
$widget.f.right_audio_level coords top_volume 1 $avg_right_coord 20 $avg_right_coord 20 $top_right_coord 1 $top_right_coord
$widget.f.right_audio_level coords top_volume_line 1 $top_right_coord 20 $top_right_coord
}

proc reset_video_stats { widget} {
set cheight [$widget.f.video_hist cget -height]
set cwidth [$widget.f.video_hist cget -width]
$widget.fifo_value_label configure -text "0 Mb"
$widget.total_stream_length_value configure -text "0 Mb"
$widget.frames_encoded_value configure -text "0"
$widget.f.video_hist configure -scrollregion [list 1 1 [expr $cwidth -1] [expr $cheight-1]]
set luma_top_hist 1
for {set i 0 } { $i < 31 } { incr i } {
	set left_luma 0
	set right_luma 0
	$widget.f.video_hist coords luma_hist$i [expr 1+($i*($cwidth-2))/31] [expr $cheight-1-(($cheight-2)*$left_luma)/$luma_top_hist] \
		[expr 1+(($i+1)*($cwidth-2))/31] [expr $cheight-1-(($cheight-2)*$right_luma)/$luma_top_hist]
	}
set avg_left_coord 79
$widget.f.left_audio_level coords avg_volume 1 79 20 79 20 $avg_left_coord 1 $avg_left_coord
set top_left_coord 79
$widget.f.left_audio_level coords top_volume 1 $avg_left_coord 20 $avg_left_coord 20 $top_left_coord 1 $top_left_coord
$widget.f.left_audio_level coords top_volume_line 1 $top_left_coord 20 $top_left_coord

set avg_right_coord 79
$widget.f.right_audio_level coords avg_volume 1 79 20 79 20 $avg_right_coord 1 $avg_right_coord
set top_right_coord 79
$widget.f.right_audio_level coords top_volume 1 $avg_right_coord 20 $avg_right_coord 20 $top_right_coord 1 $top_right_coord
$widget.f.right_audio_level coords top_volume_line 1 $top_right_coord 20 $top_right_coord
}

proc save_v4l_capture { fileid } {

puts $fileid "#\n# V4L and capture settings\n#"

set ffmpeg_vars { 
	ffmpeg_file_format 
	ffmpeg_audio_codec ffmpeg_audio_sample_rate ffmpeg_audio_bitrate 
	ffmpeg_video_codec ffmpeg_video_bitrate ffmpeg_video_quality
	ffmpeg_video_bitrate_control
	ffmpeg_max_fifo_size ffmpeg_recording_chunk_size 
	}

foreach variable [concat [list current_v4l_mode current_v4l_rrate current_alsa_capture_device] $ffmpeg_vars ] {
	catch {
		global $variable
		puts $fileid "\nglobal $variable"
		puts $fileid "set $variable \"[set $variable]\""
		}
	}

puts $fileid "#\n# End of V4L and capture settings\n#"
}

proc recompute_video_bitrate {} {
global current_v4l_rrate
global current_v4l_mode
global current_video_rate
global ffmpeg_video_bitrate
set ffmpeg_video_bitrate 600000
catch {
	switch "$current_v4l_mode" {
		"half-width"  { set ffmpeg_video_bitrate [ expr $ffmpeg_video_bitrate/2] }
		}
	switch "$current_v4l_rrate" {
		"as is" { set ffmpeg_video_bitrate [expr $ffmpeg_video_bitrate * 2] }
		"one quarter" { set ffmpeg_video_bitrate [expr $ffmpeg_video_bitrate / 2] }
		}
	}
}

proc create_monitor_window {cw} {
set mw $cw.monitor
global current_v4l_device
if { $current_v4l_device == "none" } {
	set current_v4l_device "automatic"
	}
if { [winfo exists $mw] } {
	raise $mw
	return
	}
toplevel $mw
canvas $mw.canvas
grid $mw.canvas -sticky news
puts "starting monitor ---"
set status [start_monitor current_v4l_handle $mw.canvas]
puts "status=$status"
}

trace variable ffmpeg_video_quality w {
	catch {
		global ffmpeg_video_quality
		if { $ffmpeg_video_quality < 6 } {
			.controlwin.capture.video_quality_value_label configure -text "$ffmpeg_video_quality (very high)"
			return
			} 
		if { $ffmpeg_video_quality < 11 } {
			.controlwin.capture.video_quality_value_label configure -text "$ffmpeg_video_quality (high)"
			return
			} 
		if { $ffmpeg_video_quality < 17 } {
			.controlwin.capture.video_quality_value_label configure -text "$ffmpeg_video_quality (medium)"
			return
			} 
		if { $ffmpeg_video_quality < 23 } {
			.controlwin.capture.video_quality_value_label configure -text "$ffmpeg_video_quality (low)"
			return
			} 
		.controlwin.capture.video_quality_value_label configure -text "$ffmpeg_video_quality (very low)"
		}
	skip_args3}

global current_file_extension
trace variable current_file_extension w {
	global current_capture_filename current_file_extension
	if { [regexp {^(.*)\.([^.]*)$} $current_capture_filename {} base ext] } {
		set current_capture_filename "$base.$current_file_extension"
		}
	skip_args3 }

