#!/usr/bin/perl 
$|=1;
use strict;
use File::Basename;
use Gtk2 '-init';
use Gtk2::SimpleList;
my @open_modules;
my %modules;

##global variables
my $home=$ENV{'HOME'};
my $self=__FILE__;
my $extra='/bin/burn_360';
$self=~s/$extra.*//g;
my $prefix=$self;
my $options_file=$home.'/.burn_360/.burn_360_opts';
my %options=&options_get;
my $pid;
my $dir1=$options{'dir'};
my @pids;
my %files;


sub options_get {
my $optsfile='share/burn_360/opts';
my $optsd="$prefix\/$optsfile";
my %options;
if (! (-e $options_file) or -z $options_file){
open (OPTS,$optsd);
while (my $line=<OPTS>){
chomp $line;
my @key=split /=/,$line;
my @opts;
if ($key[0] ne 'dir' and $key[0] ne 'feedback'){ 
@opts=split /(\t)/, $key[1];
$options{$key[0]}=[@opts];
}

else {
$options{$key[0]}=$key[1] ;
}

}


}

else {
open (OPTS,$options_file) or die "print $!";
while (my $line=<OPTS>){
chomp $line;
my @key=split /=/,$line;
my @opts;

if ($key[0] ne 'dir' and $key[0] ne 'feedback'){ 
@opts=split /(\t)/, $key[1];
$options{$key[0]}=[@opts];
}

else {
$options{$key[0]}=$key[1] ;
}

}


}
return %options;
}

sub save_options {
no strict 'refs';
my $run=&disk_chk($options_file);
my $backsuf=time;
my $backup="$options_file$backsuf";




if (-e $options_file){
rename $options_file, $backup;
}
my $optsdir="$ENV{'HOME'}/.burn_360";
mkdir $optsdir unless -e $optsdir;
open (OPTSAVE,">>",$options_file) or die print $! ;
my @backups=`ls -a $optsdir`;
foreach my $key (@backups){
chomp $key;
my @list= split /(.burn_360_opts)/, $key;
my $time=time;

my $deltime=$time-$list[2] if defined $list[2];
if ($deltime > 2592000){
unlink "$optsdir/$key";
}
unlink "$optsdir/$key" if -z "$optsdir/$key" and "$optsdir/$key" !~/.burn_360_opts/;
}


if ($run ne 0){

foreach my $key (sort keys %options){
if ($key ne 'dir' and $key ne 'feedback'){
print OPTSAVE $key,"=",@{$options{$key}},"\n"
}
else {
print OPTSAVE $key,"=",$options{$key},"\n"
}
}

}
close OPTSAVE;
}

sub disk_chk {
my $options=shift;
my @files_stat= stat $options;
my $part;
my @mounts=`df -m`;
shift @mounts;
my %mount_points;
foreach my $dev1 (@mounts){
my @dev=split /\s+/, $dev1;
my @inode=stat $dev[5];
$mount_points{$dev[5]}=$inode[0];
}

foreach my $keys (keys %mount_points){

$part=$keys if $files_stat[0] eq $mount_points{$keys}
}
my @cap=split /\s+/,`df -m|grep $part`;

if ($cap[4]=~/^100/) {
return 0 ;
}
else {
return 1
}
}

## Menu Setup ##
my @entries = (
#file menus  
[ "FileMenu",undef,"_File"],
[ "Encode Files",    'gtk-open',  "_Encode Files",   "<control>E", "Encode Files",    \&encoder_opts ],
[ "Capture files from VCD/DVD/Capture Device",   'gtk-cdrom', "_Capture - Get files from VCD/DVD/Capture Device",  "<control>R", "Rip from media",       \&capture_opts ],
[ "Create DVD",   'gtk-cdrom', "_Create DVD",  "<control>B", "Create DVD",  \&dvd_opts ],
[ "Close",   'gtk-quit', "_Quit",  "<control>Q", "Quit",sub { foreach my $pid (@pids){kill 15 ,$pid};Gtk2->main_quit;}],
[ "EditMenu",undef,"_Edit"],
[ "Modify Encoding",    'gtk-preferences',  "_Modify Encoding",   "<alt>M", "Modify", sub{&pref_disable}],


[ "HelpMenu",undef,"_Help"],
[ "Help",    'gtk-help',  "_Help",   "<alt>H", "Help", \&help ],
[ "About",    'gtk-about',  "_About",   "<alt>A", "About", \&about ],

);

my $ui_basic = "<ui>
<menubar name='MenuBar'>
    <menu action='FileMenu'> 

    <menuitem action='Capture files from VCD/DVD/Capture Device' position='top'/>
    <separator/>
    <menuitem action='Encode Files' position='2'/>
    <separator/>
    <menuitem action='Create DVD' position='3'/>
 <menuitem action='Close'/>
   </menu>
<menu action='EditMenu'>
<menuitem action='Modify Encoding' position='1'/>
   </menu>
 <menu action='HelpMenu'>
<menuitem action='Help' position='1'/>
<menuitem action='About' position='2'/>
   </menu>
   </menubar>
</ui>";


## GUI Base Setup ##

my $vbox=Gtk2::VBox->new(0,0);
my $blurb_frame=Gtk2::Frame->new;
$blurb_frame->set_shadow_type('out');
my $blurb_box=Gtk2::HBox->new(0,0);
$blurb_box->set_name('blurb_box');
my $blurb_im=Gtk2::Image->new_from_file("$prefix/share/burn_360/icons/burn_360.png");
my $blurb_im1=Gtk2::Image->new_from_file("$prefix/share/burn_360/icons/package_multimedia.png");
my $blurb_lab=Gtk2::Label->new();
$blurb_lab->set_markup("<span size='xx-large'>Combined Multi-media Capture, Encoding\n and media creation tool for Linux</span>");
$blurb_lab->set_justify('center');
$blurb_box->pack_start($blurb_im,1,1,0);
$blurb_box->pack_start($blurb_lab,1,1,0);
$blurb_box->pack_end($blurb_im1,1,1,0);
my $class='normal';
my $border = Gtk2::Gdk::Color->new (62259,62200,20316);
$blurb_frame->add($blurb_box);
$blurb_box->show_all;
my $window=Gtk2::Window->new('toplevel');
$blurb_frame->modify_bg("$class",$border);
$blurb_frame->set_name('blurb_frame');
$window->set_default_size (1200,600);
$window->set_title('Burn 360');
$window->set_default_icon_from_file("$prefix/share/burn_360/icons/burn_360.png");
$window->set_urgency_hint(1);
$window->set_position('center');
$window -> signal_connect ('delete_event' => sub {foreach my $pid (@pids){kill 15,$pid} Gtk2->main_quit;});
my $uimanager = Gtk2::UIManager->new;
my $accelgroup = $uimanager->get_accel_group;
$window->add_accel_group($accelgroup);
my $actions_basic = Gtk2::ActionGroup->new ("actions_basic");
$actions_basic->add_actions (\@entries, undef);
$uimanager->insert_action_group($actions_basic,0);
$uimanager->add_ui_from_string ($ui_basic);
my $menubar = $uimanager->get_widget('/MenuBar');
$vbox->pack_start($menubar,0,0,0);

$vbox->pack_start($blurb_frame,0,0,0);
$vbox->set_name('vbox');
$vbox -> show_all();
my $def=$options{'dir'};

if (! $def){
my $dir_sel=Gtk2::Dialog->new('Please Set Save Directory',$window,'modal');
$dir_sel->set_title('Please Set Save Directory');
$dir_sel->set_position('center');
$dir_sel->set_modal(1);
$dir_sel->set_transient_for($window);
my $dir_vbox=Gtk2::VBox->new(0,0);
my $dir_btn=Gtk2::Button->new('Please select');
my $dir_lab=Gtk2::Label->new("Welcome to Burn 360 - a program to get videos\nfrom any video source(DVD's,VCDs or capture source\nsuch as TV card) and creating DVD's (on DVD,s or CD's).\nIn addition it encodes most video and audio files.\n\nTo Commence using the programme you must \nfirst choose a default directory to save to. \n\nThis should have sufficient space for any \nfiles you wish to create (at least 700MB free)");
$dir_btn->signal_connect('clicked',sub{&selection('Select Default Directory','select-folder');$dir_sel->destroy});
$dir_sel->vbox->pack_start($dir_lab,0,0,5);
$dir_sel->vbox->pack_start($dir_btn,0,0,5);
$dir_sel->show_all();
}

my $prog_hbox1=Gtk2::HBox->new(0,0);
my $prog_vbox1=Gtk2::VBox->new(0,0);
$prog_hbox1->set_name('prog_hbox1');
$prog_vbox1->set_name('prog_vbox1');

sub pref_disable {
my $menu_act='yes';
foreach my $mod (@open_modules){
$menu_act ='no' if $mod eq 'encode'
}
if ($menu_act eq 'yes'){
&mod(undef)
}
else {
my $warn=Gtk2::MessageDialog->new($window,'destroy-with-parent','info','ok',"You have loaded the Encoding module\nPlease change settings by pressing the \"Amend Presets\" button");
$warn->run;
$warn->destroy;

}
}




sub mod {
my ($video_type,$encode)=@_;
my $mod_win=Gtk2::Window->new('toplevel');
$mod_win->set_default_size(400,-1);
my $mod_vbox=Gtk2::VBox->new(0,0);
my $mod_hbox=Gtk2::HBox->new(0,0);
my $mod_label=Gtk2::Label->new();
$mod_label->set_text(&word_wrap("Please see the available programme opts for converting video files - amend as required ",'98'));
my $add_encode_type_btn=Gtk2::Button->new('Add new Category');
my $amend_encode_type_btn=Gtk2::Button->new('Save Changes');
my $delete_encode_type_btn=Gtk2::Button->new('Delete Record');
$mod_win->set_title("Modify Encoding Options");

my $mod_model=Gtk2::SimpleList->new('ID','text'=>'program','text'=>'main_opts','text','extension'=>'text','description'=>'text');
$mod_vbox->pack_start($mod_label,0,1,0);
$mod_vbox->pack_start($mod_model,0,0,0);
$mod_model->set_column_editable(0,1);
$mod_model->set_column_editable(1,1);
$mod_model->set_column_editable(2,1);
$mod_model->set_column_editable(3,1);
$mod_model->set_column_editable(4,1);

$mod_model->set_headers_clickable(1);
my $prog_col=$mod_model->get_column(1);
$prog_col->set_sort_column_id(1);
my $opts_col=$mod_model->get_column(2);
$opts_col->set_sort_column_id(2);
$opts_col->set_resizable(1);
my $id_col=$mod_model->get_column(0);
$id_col->set_sort_column_id(0);
my $ext_col=$mod_model->get_column(3);
$ext_col->set_sort_column_id(3);
my $desc_col=$mod_model->get_column(4);
$desc_col->set_sort_column_id(4);
$desc_col->set_resizable(1);
$desc_col->set_max_width(20);
$mod_model->set_reorderable(1);

no strict 'refs';
foreach my $keys (sort {$a<=>$b} keys %options){
if ($keys ne 'feedback' and $keys ne 'dir'){

my @opts1=($keys,@{$options{$keys}}[0,2,4,6]);
$opts1[2]=&word_wrap($opts1[2],'60');
my $ref=\@opts1;
push (@{$mod_model->{data}},$ref)
}
}

$mod_hbox->pack_start($add_encode_type_btn,0,0,5);
$mod_hbox->pack_start($amend_encode_type_btn,0,0,5);
$mod_hbox->pack_start($delete_encode_type_btn,0,0,5);
$mod_vbox->pack_start($mod_hbox,0,0,0);

$add_encode_type_btn->signal_connect('clicked',sub{push (@{$mod_model->{data}},[undef,undef,undef,undef,undef])});
$delete_encode_type_btn->signal_connect('clicked',sub{my @list=$mod_model->get_selected_indices;splice @{$mod_model->{data}},$list[0],1;});
$amend_encode_type_btn->signal_connect('clicked',sub{%options=&update_opts(@{$mod_model->{data}});&opts($video_type);
if ($encode)
{foreach my $encodes ($encode->get_children){
$encode->remove($encodes) if $encodes->get_name eq 'encode'
}};$mod_win->destroy });
$mod_win->add($mod_vbox);


$mod_win->show_all();
return 1
}

sub update_opts {
my $update=\@_;
my @update;
no strict 'refs';

foreach my $upd (@{$update}){
my @upd;
foreach my $updhash (@{$upd}){
$updhash=~s/\n//g;
push (@upd,$updhash,"\t");
}
$upd=\@upd;
push(@update,$upd);
foreach my $key (keys %options){
if ($key ne 'dir' and $key ne 'feedback'){ 
delete $options{$key} if $key ne ${$upd}[0]
}
}
}

no strict 'refs';
foreach my $upd (@update){


$options{@{$upd}[0]}=[@{$upd}[2..8]] ;
}

&save_options;

return %options;
}

## Create Tool Buttons ##

my $encode_vbox=Gtk2::VBox->new(0,0);
my $encode_btn=Gtk2::Button->new();
my $encode_label=Gtk2::Label->new("Encode");
my $encode_image=Gtk2::Image->new_from_stock('gtk-open','small-toolbar');
$encode_vbox->add($encode_image);
$encode_vbox->add($encode_label);
$encode_btn->add($encode_vbox);
$encode_btn->signal_connect('clicked',sub{&encoder_opts});

my $rip_btn=Gtk2::Button->new();
my $rip_vbox=Gtk2::HBox->new(0,0);
my $rip_hbox=Gtk2::VBox->new(0,0);

my $rip_model=Gtk2::TreeStore->new('Glib::String');
my $rip_combo=Gtk2::ComboBox->new_with_model($rip_model);
my @captures=("VCD","DVD","TV\ Card","Screen");
foreach my $cap (@captures){
my $iter=$rip_model->append(undef);
$rip_model->set($iter,0,$cap);
if ($cap eq 'DVD'){
my $iter2=$rip_model->append($iter);
$rip_model->set($iter2,0,'File');
my $iter3=$rip_model->append($iter);
$rip_model->set($iter3,0,'Vobs');
}
}
my $renderer=Gtk2::CellRendererText->new;
$rip_combo->pack_start($renderer,'TRUE');
$rip_combo->add_attribute($renderer, text => 0);

my $rip_label=Gtk2::Label->new("Get Video from\nexternal Source");
my $rip_image1=Gtk2::Image->new_from_stock('gtk-cdrom','small-toolbar');
my $rip_image2=Gtk2::Image->new_from_stock('gtk-go-forward','small-toolbar');
$rip_vbox->pack_start($rip_image1,1,1,0);
$rip_vbox->pack_start($rip_image2,1,1,0);
$rip_hbox->add($rip_vbox);
$rip_hbox->add($rip_label);
$rip_btn->add($rip_hbox);
$rip_combo->signal_connect('changed',sub{my $iter=$rip_combo->get_active_iter;&capture_opts($rip_model->get_value($iter,0))});
$rip_combo->add($rip_btn);
#my $burn_btn=Gtk2::Button->new();
#my $burn_vbox=Gtk2::HBox->new(0,0);
#my $burn_hbox=Gtk2::VBox->new(0,0);

#my $burn_image1=Gtk2::Image->new_from_stock('gtk-cdrom','small-toolbar');
#my $burn_image2=Gtk2::Image->new_from_stock('gtk-go-forward','small-toolbar');
#$burn_vbox->pack_start($burn_image2,1,1,0);
#$burn_vbox->pack_start($burn_image1,1,1,0);
#$burn_hbox->add($burn_vbox);
#$burn_hbox->add($burn_label);
#$burn_btn->add($burn_hbox);
#$burn_btn->signal_connect('clicked',sub{&burner_opts});
my $dvd_btn=Gtk2::Button->new;
my $dvd_combo=Gtk2::ComboBox->new_text();
my $dvd_vbox=Gtk2::HBox->new(0,0);
my $dvd_hbox=Gtk2::VBox->new(0,0);
my $dvd_label=Gtk2::Label->new("Create DVD");
my %dvd_actions=("New DVD from Vobs"=>'dvd_setup',"DVD from existing File System"=>'dvd_from_dir', "DVD from Image"=>'dvd_from_image',"Modify DVD from xml file"=>'dvd_modify');
foreach my $keys (keys %dvd_actions){
$dvd_combo->append_text($keys)
}

my $dvd_image1=Gtk2::Image->new_from_stock('gtk-cdrom','small-toolbar');
my $dvd_image2=Gtk2::Image->new_from_stock('gtk-go-forward','small-toolbar');
$dvd_vbox->pack_start($dvd_image2,1,1,0);
$dvd_vbox->pack_start($dvd_image1,1,1,0);
$dvd_hbox->add($dvd_vbox);
$dvd_hbox->add($dvd_label);
my $dvd_frame=Gtk2::Frame->new;
$dvd_frame->set_shadow_type('out');
$dvd_btn->add($dvd_hbox);
#$dvd_frame->add($dvd_btn);
$dvd_combo->signal_connect('changed',sub{&dvd_opts($dvd_combo->get_active_text,\%dvd_actions)});
$dvd_combo->add($dvd_btn);
my $dir_label=Gtk2::Label->new();
my $dir_save_label=Gtk2::Label->new();
my $dir_save_label_text=&dir_sel;
my $dir_lable_text="Set Directory \nto save work\nCurrent Directory is ";
$dir_label->set_markup("<span weight= 'bold'>$dir_lable_text </span>");
$dir_label->set_text($dir_lable_text);
my $dir_image=Gtk2::HBox->new(0,0);
my $dir_im=Gtk2::Image->new_from_stock('gtk-save','small-toolbar');
my $dir_vbox=Gtk2::VBox->new(0,0);
my $feedback=Gtk2::ComboBox->new_text();

$feedback->append_text("Scrollable Static Log\n and Last Line of\nOutput (Default)");
$feedback->append_text('Scrolling Log');
$feedback->append_text("Select Type\nof Feedback");
$feedback->set_active('2');
$feedback->signal_connect('changed',sub{$options{'feedback'}=$feedback->get_active;&save_options});

$dir_vbox->pack_start($dir_label,0,0,0);
$dir_vbox->pack_start($dir_save_label,0,0,0);
$dir_image->pack_start($dir_im,0,0,0);
$dir_image->pack_start($dir_vbox,0,0,0);
$dir_image->show_all;
my $btn_set = Gtk2::Button->new();
$btn_set->set_focus_on_click(0);
$btn_set->set_relief('half');
$btn_set->add($dir_image);
$btn_set->signal_connect('clicked' ,  sub{selection('Select Directory','select-folder',$dir_save_label)});


## Add small-toolbar (Vertical) ##

my $prog_hbox=Gtk2::HBox->new(0,0);
my $tool_vbox=Gtk2::VBox->new(0,0);
my $prog_vbox=Gtk2::VBox->new(0,0);
$prog_hbox->set_name('prog_hbox');
$prog_vbox->set_name('prog_vbox');
my $scroll_win=Gtk2::ScrolledWindow->new ();



$tool_vbox->pack_start($btn_set,0,0,0);
$tool_vbox->pack_start($feedback,0,0,0);
$tool_vbox->pack_start($rip_combo,0,0,0);
$tool_vbox->pack_start($encode_btn,0,0,0);
#$tool_vbox->pack_start($burn_btn,0,0,0);
$tool_vbox->pack_start($dvd_combo,0,0,0);
$tool_vbox->set_name('tool_vbox');
$prog_hbox1->pack_start($tool_vbox,0,0,5);

## Add Scrolling Programme Window ##


$scroll_win->add_with_viewport ($prog_vbox);
$scroll_win->set_name('scroll_win');
$prog_hbox1->pack_start($scroll_win,1,1,5);
$vbox->pack_start($prog_hbox1,1,1,5);
$window->add($vbox);
$vbox->show_all;
$window->show();
Gtk2->main();
0;

## Help Menu Subs ##

sub help {
my $help_window=Gtk2::Window->new('toplevel');
$help_window->set_title('Help');
$help_window->set_default_size (800,600);
my $help_scroll=Gtk2::ScrolledWindow->new();
my $help_vbox=Gtk2::VBox->new(0,5);
$help_window->add($help_vbox);
open (HELP,"<","$prefix/share/doc/packages/burn_360/README.txt");
my $help_file="$prefix/share/doc/packages/burn_360/README.html";
my @help=<HELP>;
my $help_buff=Gtk2::TextBuffer->new();
$help_buff->create_tag("word_wrap", wrap_mode => 'word');
my $help_view=Gtk2::TextView->new();

foreach my $help (@help){
my $iter = $help_buff->get_iter_at_offset (-1);
$help_buff->insert($iter,$help);

}
$help_buff->apply_tag_by_name("word_wrap",$help_buff->get_bounds);

$help_view->set_buffer($help_buff);

my @html= qw(epiphany konqueror mozilla firefox galeon);
my @path=split /:/,$ENV{'PATH'};
my @brows;
foreach my $path1 (@path){
foreach my $brows (@html){
if (-e "$path1/$brows"){
push (@brows,$brows)
}}
}

my $brows_comb=Gtk2::ComboBox->new_text();
my $desc="To view this in \nhtml formatted version, \nselect your favourite browser";
unshift (@brows,$desc);
foreach my $brows (@brows){
$brows_comb->append_text($brows);
}

$brows_comb->set_active(0);
my $brows_layout=Gtk2::Table->new(1,5,0);
$brows_layout->attach_defaults($brows_comb,2,3,0,1);
$brows_layout->set_col_spacing(0,20);
$brows_layout->set_col_spacing(1,300);
$brows_layout->set_col_spacing(2,300);
$brows_layout->set_col_spacing(3,20);
$brows_comb->signal_connect('changed',sub{&browser($brows_comb,$help_file)});
my $brows_frame=Gtk2::Frame->new();
$brows_frame->add($brows_layout);
$brows_frame->set_name('brows_frame');

#$help_scroll->add($brows_layout);
$help_scroll->add($help_view);
$help_vbox->pack_start($brows_frame,0,1,0);
$help_vbox->pack_start($help_scroll,1,1,0);
$help_window->show_all();
}

sub browser {
my ($brows_comb,$help)=@_;
my $browser=$brows_comb->get_active_text();
system("$browser $help");
}

sub about {
my $about_window=Gtk2::Window->new('toplevel');
$about_window->set_title('About');
my $about_vbox=Gtk2::VBox->new(0,5);
my $about_label1=Gtk2::Label->new("Burn 360 v0.7.2");
my $about_label2=Gtk2::Label->new("Copyright 2006, 2007 and 2008 Mike Martin\nredtux1\@googlemail.com");
my $image=Gtk2::Image->new();
$image->set_from_file("$prefix/share/burn_360/icons/burn_360.png");
$about_vbox->pack_start($about_label1,1,1,5);
$about_vbox->pack_start($image,1,1,5);
$about_vbox->pack_start($about_label2,1,1,5);
$about_window->add($about_vbox);
$about_window->set_default_size (200,300);
$about_window->show_all();
}


## Program Subs ##

sub encoder_opts {
my $subname='encode';

if (! exists $modules{$subname}){
$modules{$subname}=[];
my $btn_encode_open_lab = "Add file to\n be Encoded";
my $btn_encode_title_lab = 'Encoding Selection Actions';
my $subname='encode';
setup_module($btn_encode_open_lab ,  $btn_encode_title_lab,$subname);
}

}


#sub burner_opts {
#my $tag1=grep /create_image/,@open_modules;
#if ($tag1 eq 0){
#push (@open_modules,"create_image");
#my $btn_burn_open_lab="Add file to\nbe Burnt to VCD";
#my $btn_burn_title_lab='Burn VCD Selection Actions';
#my $subname='create_image';
#setup_module($btn_burn_open_lab ,  $btn_burn_title_lab,$subname);
#}
#}

sub capture_opts {
my $sub=shift;
my $tag1=grep /$sub/,@open_modules;
if ($tag1 eq 0){

push (@open_modules,$sub);
my $btn_burn_title_lab="Capture Video from external Source ";
my $subname=['capture',$sub];
setup_module(undef ,  $btn_burn_title_lab,$subname);
}
}

sub dvd_opts {
my ($opt,$subs)=@_;
%options=&options_get;
my $subname=$$subs{$opt};
my $label;

	foreach my $keys (keys %$subs){
	$label = $keys if $$subs{$keys} eq $subname;
	}


if ($subname eq 'dvd_modify'){
if (exists $modules{$subname}){
my $widget=$modules{$subname}->[0][0];
$widget->destroy ;
delete $modules{$subname}
}
}
if (! exists $modules{$subname}){
$modules{$subname}=[];
my $btn_burn_open_lab="Add file to\n be added to DVD";
my $btn_dvd_title_lab=$label;
setup_module($btn_burn_open_lab , $btn_dvd_title_lab,$subname) if defined $subname;
}

}


sub setup_module {
my ($sel_opts_open_lab , $sel_opts_title_lab,$subname) = @_;
my $hbox2=Gtk2::HBox->new(0,0);
my $encode_open_lab1=Gtk2::Label->new($sel_opts_open_lab);
my $image=Gtk2::Image->new_from_stock('gtk-open','small-toolbar');
my $delay=Gtk2::Entry->new;
$delay->set_text(0);
my $delay_label=Gtk2::Label->new("Delay action in Minutes");
my $delay_hbox=Gtk2::HBox->new(0,0);
$delay_hbox->set_name('delbox');
foreach my $w ($delay_label,$delay){
$delay_hbox->pack_start($w,0,0,0);
}
my $btn_open = Gtk2::Button->new();



$hbox2->pack_start($image,0,0,0);
$hbox2->pack_start($encode_open_lab1,0,0,0);
$hbox2->show_all;

my $open1=$hbox2;
my $sel_opts_frame = Gtk2::Frame->new();
$sel_opts_frame->set_shadow_type('etched-out');
my $sel_opts_mod_lab=Gtk2::Label->new($sel_opts_title_lab);
$sel_opts_mod_lab->set_markup("<span weight='600'> $sel_opts_title_lab </span>" );
my $title_frame=Gtk2::Frame->new();
$title_frame->add($sel_opts_mod_lab);
my $sel_opts_hbox = Gtk2::HBox->new(0,0);

$btn_open->set_relief('half');
$btn_open->add($open1);
my $sel_opts_vbox=Gtk2::VBox->new(0,1);
$sel_opts_vbox->set_name('sel_opts_vbox');
my $enc_hbox=Gtk2::HBox->new();
$sel_opts_vbox->pack_start($title_frame,0,0,0);


if ($subname eq 'encode'){
our $encode_vbox=Gtk2::VBox->new();
my $video_hbox=Gtk2::HBox->new();
$video_hbox->set_name('video_hbox');
my $video_type=Gtk2::ComboBox->new_text;
my $open_vbox_container=Gtk2::VBox->new();
my $video_hbox_spacer=Gtk2::HBox->new();
$video_hbox_spacer->set_name('video_hbox_spacer');
$video_type->set_name('video_type');
&opts($video_type);
my $opts_mod=Gtk2::Button->new('Amend Presets');
my $loop_model=Gtk2::ListStore->new('Glib::String');

foreach ('Choose Mode','Sequential','Concurrent'){
$loop_model->set($loop_model->append,0,$_);
}
my $loop_type=Gtk2::ComboBox->new($loop_model);
my $loop_renderer=Gtk2::CellRendererText->new;
$loop_type->pack_start($loop_renderer,1);
$loop_type->add_attribute($loop_renderer,text => 0);
#$loop_type->signal_connect('changed'=>sub{print $loop_type->get_active});
#$loop_type->set_title('Choose Mode');
$opts_mod->signal_connect('clicked'=>sub{&mod($video_type,$encode_vbox);});
$video_type->signal_connect('changed'=>sub{&encode($video_type,$encode_vbox,$sel_opts_vbox,$delay) });
my $action_frame=Gtk2::Frame->new('Encode Files');
$video_hbox->pack_start($video_type,0,0,0);
$video_hbox->pack_start($opts_mod,0,0,0);

#$video_hbox->pack_start($loop_type,0,0,0);
$encode_vbox->pack_start($video_hbox,0,0,0);
$encode_vbox->set_name('encode_vbox');
$encode_vbox->pack_start($delay_hbox,0,0,0);
$action_frame->add($encode_vbox);
$action_frame->set_name('action_frame');
$open_vbox_container->pack_start($btn_open,0,0,6);
$open_vbox_container->pack_start($video_hbox_spacer,0,1,6);
$sel_opts_hbox->pack_start($open_vbox_container,0,0,6);
#$sel_opts_hbox->pack_start($loop_type,0,0,0);
$sel_opts_hbox->set_name('sel_opts_hbox');
$open_vbox_container->set_name('open_vbox_container');
$sel_opts_hbox->pack_start($action_frame,0,0,2);
$video_hbox->set_name('video_hbox');
$prog_vbox -> show_all();
}


#elsif ($subname eq 'create_image'){
#our $vbox2=Gtk2::VBox->new(0,5);
#my $burn_act_btn=Gtk2::Button->new('Create Disk Image');
#my $count = 1;
#$burn_act_btn->signal_connect('clicked'=>sub{$count++ && &create_image($vbox2,$count,#$sel_opts_vbox) });
#my $frame2=Gtk2::Frame->new('Burn Files');
#$vbox2->pack_start($burn_act_btn,0,0,0);
#$frame2->add($vbox2);
#$sel_opts_hbox->pack_start($btn_open,0,0,6);
#$sel_opts_hbox->pack_start($frame2,0,0,6);
#$prog_vbox -> show_all();
#}


elsif ($subname =~/^dvd/){
our $vbox2=Gtk2::VBox->new(0,5);
our $vbox3=Gtk2::VBox->new(0,5);
my $label_text="Update Title Descriptions for DVD";
my $dvd_titles_btn=Gtk2::Button->new_with_label();
my $chap_length_label=Gtk2::Label->new("Chapter Length");
my $chap_length=Gtk2::ComboBox->new_text;
my @chaps=(2,5,7,10,15,20,25,30);
foreach my $chaps (@chaps){
$chap_length->append_text($chaps)
}
$chap_length->set_active(1);
my $chap_hbox=Gtk2::HBox->new(0,0);
$chap_hbox->pack_start($chap_length_label,0,0,10);
$chap_hbox->pack_start($chap_length,0,0,10);
$dvd_titles_btn->set_label($label_text);
my $dvd_title_lable=Gtk2::Label->new("Volume Label for DVD");
my $dvd_title=Gtk2::Entry->new;
my $home_menu_lable=Gtk2::Label->new("Image File for Menu");
my $home_menu=Gtk2::Entry->new;
my $dir=$ENV{'HOME'};
my $default="$dir/menu_dvd.jpeg";
if (!(-e $default)){
my $prefix1=$prefix;
$prefix1=~s/bin\/burn_360//;

}
$home_menu->set_text($default);
my $home_menu_chg=Gtk2::Button->new('Change jpeg for Menu');
$home_menu_chg->signal_connect('clicked' ,  sub{$home_menu->set_text(&selection_menu_jpeg($home_menu))});
my $file_vbox=Gtk2::VBox->new(0,0);
my %files1;
my $list=0;
$btn_open->signal_connect('clicked' =>  sub{$list=0;my $filesex={%files};&dvd_refresh($sel_opts_vbox,$file_vbox,'dvd_setup',$list,$filesex)});

$dvd_title->set_width_chars(32);
my $titles_vbox=Gtk2::VBox->new(0,1);
my %titles;
my %dvd_titles;
my $sub;


if ($subname eq 'dvd_setup' or $subname eq 'dvd_modify'){
$sub = 'dvd_setup';
my $snap=Gtk2::ComboBox->new_text();
$snap->append_text('Choose Type of Title');
$snap->append_text('Titles as Text');
$snap->append_text('Titles as Video');
$snap->set_active(0);
my $sec=Gtk2::Entry->new();
my $sec_label=Gtk2::Label->new('Seconds for Snapshot');
$sec->set_text(15);
my $sec_hbox=Gtk2::HBox->new(0,0);

$vbox2->pack_start($btn_open,0,0,10);
$vbox2->pack_start($dvd_titles_btn,0,0,10);
$vbox2->pack_start($chap_hbox,0,0,10);
$sel_opts_hbox->pack_start($vbox2,0,0,6);
$vbox3->pack_start($dvd_title_lable,0,0,0);
$vbox3->pack_start($dvd_title,0,0,0);
$vbox3->pack_start($home_menu_lable,0,0,0);
$vbox3->pack_start($home_menu,0,0,0);
$vbox3->pack_start($home_menu_chg,0,0,0);
$sec_hbox->pack_start($sec_label,0,0,0);
$sec_hbox->pack_start($sec,0,0,0);
$vbox3->pack_start($sec_hbox,0,0,0);
$vbox3->pack_start($snap,0,0,0);

$sel_opts_hbox->pack_start($vbox3,0,0,100);
$sel_opts_vbox->pack_start($sel_opts_hbox,0,0,0);
my $sep=Gtk2::HSeparator->new;
$sel_opts_vbox->pack_start($sep,0,0,5);
$sel_opts_vbox->pack_start($file_vbox,0,0,0);


if ($subname eq 'dvd_modify'){

foreach my $keys (keys %files){
if (defined $files{$keys}->[5] ) {
no strict 'refs';
delete $files{$keys}
}
}

my %files1=&dvd_modify;

$list=1;
my $count=scalar keys %files ;
foreach my $keys (sort {$files1{$a}->[2] <=> $files1{$b}->[2]} keys %files1){
push (@{$files{$count}},'dvd_setup',undef,$keys,undef,$files1{$keys}->[2],$files1{$keys}->[0],$files1{$keys}->[1],undef,undef);
$count++;
}
dvd_refresh($sel_opts_vbox,$file_vbox,'dvd_setup',$list,undef) ;
no strict 'refs'; &$sub($vbox2,$sel_opts_vbox,$titles_vbox,\%dvd_titles,\%titles,$dvd_title,$home_menu->get_text,$snap,$sec,\%files1,$chap_length);
}


$dvd_titles_btn->signal_connect('clicked'=>sub{no strict 'refs'; &$sub($vbox2,$sel_opts_vbox,$titles_vbox,\%dvd_titles,\%titles,$dvd_title,$home_menu->get_text,$snap,$sec,undef,$chap_length)});
$prog_vbox -> show_all();
}
else {
no strict 'refs';
&$subname($sel_opts_vbox,$dvd_title);
}
}

elsif ($subname->[0] eq 'capture') {
our $device;
my $media;
#my $subname='capture';
my $prog;
my $opts;
our $track;
my $sel_cap_vbox=Gtk2::VBox->new(0,1);
my $sel_cap_hbox=Gtk2::HBox->new(0,1);
my $dir=&dir_sel;
my $source;
my $capture_options;
$sel_cap_hbox->set_name('cap_hbox');
$sel_cap_vbox->set_name('cap_vbox');

$sel_cap_vbox->pack_start($sel_cap_hbox,1,1,0);
$sel_opts_hbox->pack_start($sel_cap_vbox,1,1,0);


&source_search($subname,$sel_cap_hbox,$sel_cap_vbox,$sel_opts_vbox,$delay);

}

if ($subname!~/^dvd/){
$sel_opts_vbox->pack_start($sel_opts_hbox,0,0,0) ;
$btn_open->signal_connect('clicked' ,  sub{&selection('Open file','open',$sel_opts_vbox,$subname)});
}

$btn_open->drag_dest_set(["drop","motion","highlight"],
                         ["copy","private","default","move","link","ask"]);
$btn_open->signal_connect(drag_data_received => \&drop_handler);
  
	  my $target_list = Gtk2::TargetList->new();
	  my $atom = Gtk2::Gdk::Atom->new("text/uri-list");
	  $target_list->add($atom, 0, 0);
	use URI::Escape;
	  $btn_open->drag_dest_set_target_list($target_list);
	  
		  sub drop_handler {
		    my ($treeview, $context, $widget_x, $widget_y, $data, $info, $time) = @_;
		my $uris= $data->data;
		$uris=~s/\n//g;
		my @uris=split /\r/,$uris;
		my @file;
		    foreach my $uri (@uris) {
		$uri=~s/file:\/\///;
		my $file=uri_unescape($uri);
		chomp $file;$uri=~s/\n|\r//g;
		#print $file;
		push @file,$file;
		    }
	&selection('Open file','open',$sel_opts_vbox,$subname,\@file)
	  }

$sel_opts_vbox->pack_start($delay_hbox,0,0,0) ;
$sel_opts_frame->add($sel_opts_vbox);
$sel_opts_frame->set_name('sel_opts_frame');
$prog_vbox->pack_start($sel_opts_frame,1,1,0) ;
push @{$modules{$subname}},[$sel_opts_frame];

$prog_vbox -> show_all();
return
}


## File Operations ##

sub selection {
%options=&options_get;
my ($heading,$type,$sel_opts_vbox,$subname,$file) = @_;
print "file",$file,"file","\n";
my @filenames;
my $key;
unless ($file){
my ($filter,$filterall,$filterdvd,$dir_label);
my $file_chooser =Gtk2::FileChooserDialog->new (
$heading,undef,$type,'gtk-cancel' => 'cancel','gtk-ok' => 'ok'
);


if (exists $modules{'dvd_modify'}){
$dvd_combo->append_text('');
$dvd_combo->set_active(5);
$dvd_combo->remove_text(5);
}


$file_chooser->set_select_multiple('TRUE') if $subname ne 'dvd_burn';
$file_chooser->set_current_folder($options{'dir'});
$filter=Gtk2::FileFilter->new();
$filterall=Gtk2::FileFilter->new();
$filterdvd=Gtk2::FileFilter->new();
$filter->set_name("Movies") ;
$filterdvd->set_name("DVD XML files") ;
$filterall->set_name("All Files") ;
my @types;
if ($subname eq 'encode'){
@types=("video/mpeg","video/x-msvideo","video/x-divx","video/x-xvid","video/x-ms-asf","image/*","audio/*","application/ogg","application/x-extension-vob","application/x-flash-video");
foreach my $mimes (@types){$filter->add_mime_type($mimes);}
(defined $filter)&&($file_chooser->add_filter($filter)) ;
}
elsif ($subname=~/^dvd_setup/){
@types=('*.vob');
foreach my $mimes (@types){$filter->add_pattern($mimes);}
(defined $filter)&&($file_chooser->add_filter($filter)) ;
}
elsif ($subname eq 'create_image'){
@types=("video/mpeg");
foreach my $mimes (@types){$filter->add_mime_type($mimes);}
(defined $filter)&&($file_chooser->add_filter($filter)) ;
}

elsif ($heading=~/xml/){@types=('dvd*.xml');
foreach my $mimes (@types){$filterdvd->add_pattern($mimes);}
(defined $filterdvd)&&($file_chooser->add_filter($filterdvd)) ;
}



$filterall->add_pattern('*');

if ($subname=~/^dvd_from/){
(defined $filterall)&&($file_chooser->add_filter($filterall)) ;

}

$file_chooser->add_filter($filterall);


if ('ok' eq $file_chooser->run){@filenames = $file_chooser-> get_filenames};
$file_chooser->destroy;
}
else {
foreach my $file (@{$file}){
push @filenames,$file ;
}
}
my %actions=(encode=>['encode_gui_add','$subname,$file_vbox2,$filename,$file_start,$file_time,$video_track,$audio_track,$quality,$sync',1],
dvd_setup=>['dvd_gui','$subname,undef,$filename,undef,undef,1,undef,undef,undef',1],
'dvd_from_image'=>['none','',0],
'dvd_modify'=>['none','',0],
'dvd_burn'=>['none','',0]
);





if ($type eq 'select-folder'){
	&dir_sel($filenames[0]);
	return 1;
	}
$key=scalar keys %files;
foreach my $filename (@filenames){

$key++;

my $chk='0';


foreach my $keys (keys %files){if ($files{$keys}->[2] eq $filename ){$chk='1' and $files{$keys}->[0] eq $subname}}
no strict 'refs';
my @sub_vars=$actions{$subname}->[0]->($sel_opts_vbox,$subname,$filename);
push (@{$files{$key}},@sub_vars) if $chk eq '0';


}
#print $actions{$subname}->[1];
return $filenames[0];# if $actions{$subname}->[1] == 0;
1
}

sub none {}

sub dvd_refresh {
my ($sel_opts_vbox,$vid_box,$subname,$list,$filesentered)=@_;
&selection('Add Movie to DVD','open',$sel_opts_vbox,'dvd_setup') if $list ne '1';
foreach my $keys (sort keys %files){
print @{$files{$keys}},"\n"
}
my %order;
use File::Basename;
foreach my $order (sort {$files{$a}->[5] <=> $files{$b}->[5]||uc(basename($files{$a}->[2])) cmp uc(basename($files{$b}->[2]))} keys %files){
push @{$order{$files{$order}->[5]}},$order;
}
my %title_order;
foreach my $keys (sort  keys %order){
my $count=1;
foreach my $keys2 (@{$order{$keys}}){
$title_order{$keys2}=$count;
$count++
}
}
foreach my $keys (sort {$files{$a}->[5] <=> $files{$b}->[5]||$a <=> $b} keys %files){ 
$files{$keys}->[4]=$title_order{$keys};
}
foreach my $keys (sort {$files{$a}->[5] <=> $files{$b}->[5]||$files{$a}->[4] <=> $files{$b}->[4]} keys %files) 
{
print $keys,"\t",$files{$keys}->[5],"\t",$files{$keys}->[4],"\t",$files{$keys}->[2],"\n";
if ($files{$keys}->[0] eq 'dvd_setup'){
my $exists=0;
foreach my $oldfiles (keys %$filesentered){
$exists = 1 if $$filesentered{$oldfiles}->[2] eq $files{$keys}->[2];
}

if ($exists eq 0){
my $fc_file=&word_wrap($files{$keys}->[2],'40');
my $fc_label=Gtk2::Label->new($fc_file);
$fc_label->set_alignment(0,0);
my $fc_frame=Gtk2::Frame->new;
my $btn_remove=Gtk2::Button->new('Remove');
$fc_frame->add($fc_label);
my $vid_vbox=Gtk2::VBox->new(0,1);
my $title_label=Gtk2::Label->new('Allocate Title');
$title_label->set_width_chars(25);
my $vid_hbox=Gtk2::HBox->new(0,0);
my $title_frame=Gtk2::Frame->new;
my @tracks=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
my $video_track=Gtk2::ComboBox->new_text;
my $order=Gtk2::ComboBox->new_text();
my $order_label=Gtk2::Label->new('Position');
foreach my $tracks (@tracks){
$video_track->append_text($tracks) unless $tracks>=8;
$order->append_text($tracks)
}

$video_track->set_active($files{$keys}->[5]-1);
$vid_hbox->pack_start($title_label,1,0,3);
$vid_hbox->pack_start($video_track,1,1,3);
$vid_hbox->pack_start($order_label,1,0,3); 
$vid_hbox->pack_start($order,1,0,3); 
$vid_hbox->pack_start($btn_remove,1,0,3); 
$title_frame->add($vid_hbox);
$vid_vbox->pack_start($fc_frame,1,0,3);
$vid_vbox->pack_start($title_frame,1,0,3);
$vid_box->pack_start($vid_vbox,1,0,3);
$order->set_active($title_order{$keys}-1);
$video_track->signal_connect('changed',sub{$files{$keys}->[5]=$video_track->get_active_text});
$btn_remove->signal_connect('clicked' => sub{remove_file($files{$keys}->[2],$sel_opts_vbox,$vid_vbox,$subname);});
$order->signal_connect('changed',sub{$files{$keys}->[4]=$order->get_active});
}

}
}
$sel_opts_vbox->show_all;
}



sub dvd_gui {
my ($sel_opts_vbox,$subname,$filename)=@_;
#print $filename,$subname;
return $subname,undef,$filename,,undef,undef,'1'
}

sub dvd_image_gui {
my ($sel_opts_vbox,$subname,$filename)=@_;

my $file_vbox2=Gtk2::VBox->new(0,0);
my $file_hbox = Gtk2::HBox->new(0,1);
my $fc_file_frame=Gtk2::Frame->new();
my $file=Gtk2::Label->new($filename);
$file->set_alignment(0,0);
$file_vbox2->pack_start($file,0,0,0);
$fc_file_frame->add($file_vbox2);
$sel_opts_vbox->pack_start($fc_file_frame,0,0,0) ;
$prog_vbox->show_all();

return $subname,$file_vbox2,$filename
}


sub encode_gui_add {
my ($sel_opts_vbox,$subname,$filename)=@_;
my $file_vbox2=Gtk2::VBox->new(0,0);
my $file_hbox = Gtk2::HBox->new(0,1);
my $file_vbox = Gtk2::VBox->new(0,1);
my $file_hbox_position = Gtk2::HBox->new(0,1);
my $fc_label_col=Gtk2::EventBox->new();
my $fc_label_frame=Gtk2::Frame->new();
my $fc_file_frame=Gtk2::Frame->new();

my $layout_entry=Gtk2::EventBox->new();
my $file_col=Gtk2::Gdk::Color->new(58853,57825,57825);
$layout_entry->modify_bg('normal',$file_col);
my $fc_label=Gtk2::Label->new();
my $fc_file=&word_wrap($filename,'40');
$fc_label->set_text($fc_file);
$fc_label->set_selectable(1);
$fc_label->set_text($fc_file);
$fc_label->set_alignment(0,1);
my $time_label=Gtk2::VBox->new(0,1);
my $file_start=Gtk2::ComboBoxEntry->new_text;
my $file_time=Gtk2::ComboBoxEntry->new_text;
my $file_start_label=Gtk2::Label->new('Start');
my $file_time_label=Gtk2::Label->new('Time');
my $video_track=Gtk2::ComboBox->new_text;
my $audio_track=Gtk2::ComboBox->new_text;
my $quality=Gtk2::ComboBoxEntry->new_text;
$quality->set_size_request(55);
my $sync=Gtk2::ComboBoxEntry->new_text;
my @times=("00:30:00","01:00:00","01:30:00","02:00:00","02:30:00","03:00:00","03:30:00","04:00:00","04:30:00","05:00:00");

	foreach my $times (@times){
	$file_start->append_text($times);
	$file_time->append_text($times);
	}

my $times=Gtk2::VBox->new(0,1);
$times->set_name('times');

$time_label->pack_start($file_start_label,0,0,3);
$time_label->pack_start($file_time_label,0,0,3);
$times->pack_start($file_start,0,0,3);
$times->pack_start($file_time,0,0,3);
my ($vid_frame,$aud_frame,$qual_frame,$sync_frame)=(Gtk2::Frame->new(),Gtk2::Frame->new(),Gtk2::Frame->new(),Gtk2::Frame->new());
my @sync=("-50","-40","-30","-20","-10","0","10","20","30","40","50");

	foreach my $synct (@sync){$sync->append_text($synct)}

my $vid_label=Gtk2::Label->new("Video\nTrack");
my $aud_label=Gtk2::Label->new("Audio\nTrack");
my $qual_label=Gtk2::Label->new('Quality');
my $sync_label=Gtk2::Label->new("Fix sync (in seconds -\nminus to delay audio)");
my %pack_frame=(1=>[$vid_frame,$vid_label],
2=>[$aud_frame,$aud_label],
3=>[$qual_frame,$qual_label],
4=>[$sync_frame,$sync_label]);

	foreach my $keys (keys %pack_frame){
	no strict 'refs';
	${$pack_frame{$keys}}[0]->add(${$pack_frame{$keys}}[1])
	}

my $vid_box=Gtk2::VBox->new(0,1);
$vid_box->set_name('vt');
my $aud_box=Gtk2::VBox->new(0,1);
$aud_box->set_name('at');
my $qual_box=Gtk2::VBox->new(0,1);
$qual_box->set_name('qual');
my $sync_box=Gtk2::VBox->new(0,1);
$sync_box->set_name('sync');
$vid_box->pack_start($vid_frame,1,1,3);
$aud_box->pack_start($aud_frame,1,1,3);
$qual_box->pack_start($qual_frame,1,1,3);
$sync_box->pack_start($sync_frame,1,1,1);
$sync_box->pack_start($sync,0,0,1);

my @tracks=('',0,1,2,3,4,5,6,7,8,9);

	foreach my $tracks (@tracks){
	$video_track->append_text($tracks);
	$audio_track->append_text($tracks);
	$quality->append_text($tracks);
	}

$vid_box->pack_end($video_track,0,0,3);
$aud_box->pack_end($audio_track,0,0,3);
$qual_box->pack_end($quality,0,0,3);
$file_hbox->pack_start($time_label,0,0,3);
$file_hbox->pack_start($times,0,0,3);
$file_hbox->pack_start($vid_box,0,0,3);
$file_hbox->pack_start($aud_box,0,0,3);
$file_hbox->pack_start($qual_box,0,0,3);
$file_hbox->pack_start($sync_box,0,0,3);
$file_hbox->pack_start($file_vbox,0,0,6);


$file_hbox->set_name('filebox');
my $file_hbox_frame=Gtk2::Frame->new();
$fc_file_frame->set_name('filesel');
$file_hbox_frame->add($file_hbox);
my $fc_btn=Gtk2::Button->new_from_stock('gtk-remove');
$fc_btn->signal_connect('clicked'=>sub{&remove_file($filename,$sel_opts_vbox,$fc_file_frame,$subname)});
$fc_label_frame->add($fc_label);
$file_hbox->pack_end($fc_btn,0,0,3);
$fc_label_col->add($fc_label_frame);
$file_vbox2->pack_start($fc_label_col,0,0,3);
$file_vbox2->pack_start($file_hbox_frame,0,0,3);
$layout_entry->add($file_vbox2);
$fc_file_frame->add($layout_entry);
$file_vbox2->set_name($filename);
$sel_opts_vbox->pack_start($fc_file_frame,1,1,2) ;


$prog_vbox->show_all();

return $subname,$file_vbox2,$filename,$file_start,$file_time,$video_track,$audio_track,$quality,$sync
}

sub file_remove {
my ($file_hbox,$fc_label_col,$fc_label,$fc_btn,$file_vbox,$fc_file_frame,$sel_opts_vbox,$layout_entry,$key)=@_;
my $del=$fc_label->get_text;
$del=~s/\n//g;
my $files1;
$file_hbox->remove($file_vbox);
$file_hbox->remove($fc_btn);
$fc_file_frame->remove($layout_entry);
$sel_opts_vbox->remove($fc_file_frame);
delete $files{$key};
foreach my $pids (@pids){
kill ('15',$pids);
}
return 
}

sub dir_sel {

my $dir=shift;

my $color1='blue';
if ($dir) {
$options{'dir'}=$dir;
$color1='red';
}

no strict 'refs';
my $dirww=&word_wrap($options{'dir'},'20');
$dir_save_label->set_markup("<span color= \"$color1\" >$dirww </span>");
&save_options;
return \$dir1;
}

sub remove_file {
my ($file,$sel_opts_vbox,$fc_file_frame,$subname)=@_;
my $key;

foreach my $keys (keys %files){
$key = $keys if $file eq $files{$keys}->[2] and $files{$keys}->[0] eq $subname;
}

delete $files{$key};
$fc_file_frame->destroy;


}

## Action Subs - What we are doing to files etc ##

sub encode {
my ($video_type,$vbox2,$sel_opts_vbox,$delay)=@_;
my $encode_type=$video_type->get_active();
my $enc='enc-act';
my $btn_encode = Gtk2::Button->new_from_stock('encode');
$btn_encode->set_relief('half');
$btn_encode->set_name('encode');
our $opts;
our $prog;
our $ext;

no strict 'refs';
foreach my $enc (keys %options){

if ($video_type->get_active_text eq ${$options{$enc}}[6]){
$opts=$options{$enc}[2];
$prog=$options{$enc}[0];
$ext=$options{$enc}[4];
}
}

$btn_encode->signal_connect('clicked' ,  sub{&encode_loop($opts,$prog,$ext,$sel_opts_vbox,$delay)});
my $butchk= \$vbox2->get_children ();
if ((grep /Button/,$$butchk) eq 0){
$vbox2->pack_start($btn_encode,1,1,0);
}

$vbox2->show_all;
}



sub encode_loop {
my ($opts,$prog,$ext,$sel_opts_vbox,$delay)=@_;
my $subname='encode';

my $timedel= $delay->get_text * 60;
print $timedel;

sleep $timedel;
foreach my $files1 (keys %files){
no strict 'refs';
if (${$files{$files1}}[0] eq $subname){
 {
my $prog=&run_cmd($files1,$opts,$prog,$ext,$subname,$sel_opts_vbox) ;


}
}
}
}




sub opts {
my ($video_type,$enc)=@_;

if (defined($video_type)){
my $model= $video_type->get_model ;
$model->clear ;

my $title='Select Encoding Type';
$video_type->append_text("$title");
my @opts;
foreach my $type (keys %options){
no strict 'refs';
if ($type ne  'dir' and $type ne 'feedback'){
push (@opts, $options{$type}[6]);
}
}

foreach my $opt (sort {uc($a) cmp uc($b)} @opts){
$video_type->append_text($opt);
}


$video_type->set_active(0);
}

}



## This is the programme that does the work ##

sub run_cmd {
my ($arr1,$opts,$prog,$ext,$subname,$run_hbox,$ext_opts,$append)=@_;
my $cmd_hbox;
my $scroll; 
my $textview;
my $buffer;
my $cmd_vbox;
my $gtkend;
my $log_frame;
my $shell_frame;
my $cancel_frame;
my $btn_cancel;
my $output_label;
my $last_label;
my $cancel_vbox;

### If display is to added to gets widgets from previous run ###
if ($append == 1){

foreach my $keys ($run_hbox->get_children){
print "\n",$keys->get_name,"\n";
$cmd_hbox=$keys if $keys->get_name eq 'cmd_hbox';
if ($keys->get_name ne 'delbox'){
unless ($keys->get_name eq 'GtkHSeparator' ) {
foreach my $keys1 ($keys->get_children){ 

print $keys1->get_name;# if $keys1->get_name eq 'GtkHBox';
$cmd_vbox=$keys1 if $keys1->get_name eq 'cmd_vbox'; 
$cancel_vbox=$keys1 if $keys1->get_name eq 'cancel_vbox';

if ($keys1->get_name ne 'GtkLabel'){
foreach my $keys2 ($keys1->get_children){print $keys2->get_name;
$gtkend=$keys2 if $keys2->get_name eq 'gtkend';
$log_frame=$keys2 if $keys2->get_name eq 'log_frame';
$shell_frame=$keys2 if $keys2->get_name eq 'shell_frame';
$cancel_frame=$keys2 if $keys2->get_name eq 'cancel_frame';
$scroll=$keys2 if $keys2->get_name eq 'scroll';
if ($keys2->get_name=~/scroll/){
foreach my $keys3 ($keys2->get_children){
$textview=$keys3 if $keys3->get_name eq 'textview';
}
}
}
}
}
}
}
}
}

if ($append != 1){
$cmd_hbox=Gtk2::HBox->new(0,0);
$scroll = Gtk2::ScrolledWindow->new(undef,undef);

$textview = Gtk2::TextView->new();
$buffer = $textview->get_buffer;
$cmd_vbox=Gtk2::VBox->new(0,1);
$scroll->add ($textview);
$gtkend=Gtk2::Entry->new();
$log_frame=Gtk2::Frame->new();
$shell_frame=Gtk2::Frame->new();
$cancel_frame=Gtk2::Frame->new();
$btn_cancel = Gtk2::Button->new_from_stock('gtk-stop'); 

$btn_cancel->set_relief('half');
$cancel_frame->add($btn_cancel);
$output_label=Gtk2::Label->new('log');
$last_label=Gtk2::Label->new('Shell Output');
$log_frame->add($output_label);
$shell_frame->add($last_label);
$cancel_vbox=Gtk2::VBox->new(0,0);
$cmd_hbox->set_name('cmd_hbox');
$scroll->set_name('scroll');
$textview->set_name('textview');
$cmd_vbox->set_name('cmd_vbox');
$gtkend->set_name('gtkend');
$log_frame->set_name('log_frame');
$shell_frame->set_name('shell_frame');
$cancel_frame->set_name('cancel_frame');
$btn_cancel->set_name('btn_cancel');
$output_label->set_name('output_label');
$last_label->set_name('last_label');
$cancel_vbox->set_name('cancel_vbox');


$cmd_vbox->pack_start($log_frame,0,0,0);
$cmd_vbox->pack_start($scroll,1,1,0);
$cmd_vbox->pack_start($shell_frame,0,0,0);

$cmd_vbox->set_size_request(450,250) ;
$cmd_vbox->pack_start($gtkend,0,0,0) if $options{'feedback'} eq '0';

$cancel_vbox->pack_start($cancel_frame,0,0,0);
$cmd_hbox->pack_start($cmd_vbox,1,1,0);
$cmd_hbox->pack_start($cancel_vbox,0,0,0);
}
if ($subname ne 'encode'){
$run_hbox->pack_start($cmd_hbox,1,1,0) if $append != 1;
}
else {
${$files{$arr1}}[1]->pack_start($cmd_hbox,1,1,5);
}
$prog_vbox->show_all;
my @opts;
my @ext;
if ($subname eq 'encode'){
@opts=split /\s+/,$opts;
@ext;
foreach my $ext (@{$files{$arr1}}[3..8]){
push (@ext,$ext->get_active_text);
}

if ($ext[0] ne ''){
push (@opts," -ss $ext[0]")
}
if ($ext[1] ne ''){
push (@opts," -t $ext[1] ")
}
if ($ext[2] ne ''){
push (@opts," -map 0.$ext[2] ")
}
if ($ext[3] ne ''){
if ($ext[2] eq ''){
push (@opts," -map 0.0 ")
}
push (@opts," -map 0.$ext[3] ")
}



my $index='-1';
if ($ext[4] ne ''){
my $qual;
foreach my $main (@opts){
$index++;
if ($main eq '-qscale'){
$qual='1';
$opts[$index+1]=$ext[4];
}
}

push (@opts,"-qscale $ext[4]") if $qual ne '1';
}
my $ffmpeg=&version;
if ($ffmpeg > 8243){
my $arr=-1;
foreach my $opts1 (@opts){
$arr++;
my $len=length($opts[$arr+1]);
$opts[$arr+1]="$opts[$arr+1]k" if substr($opts[$arr+1],$len) ne 'k' and $opts1 eq '-ab';
}
}
}

no strict 'refs';
my ($inp,$dir);
($inp,$dir)=fileparse(${$files{$arr1}}[2]) if defined(${$files{$arr1}}[2]);
my $quote='"';
my $save_dir=$options{'dir'};
my @out;
my $inp1;
my $out1;
if ($inp=~/\./){
@out=split /\./,$inp if $subname ne 'dvd_burn';
pop @out ;

$out1=join('',@out);
}
else {$out1=$inp};
if ($subname eq 'encode'){

if ($ext[5] ne ''){
unshift (@opts,"-itsoffset $ext[5] -i $quote$dir$inp$quote");
push (@opts,"-map 1:0 -map 0:1")
}
$opts=join(' ',@opts);
}
print $opts,"\n";
my $file;
my $pid;
my %cmd=(
         'encode'=>"$prog $quote$dir$inp$quote $opts $quote$save_dir/$out1$ext$quote",
         'capture'=>"$prog $opts",
         'dvd_setup'=>"$prog $opts ",
         'dvd_burn'=>"$prog $opts",
#         'create_image'=>"$prog -c $save_dir/videocd.cue -b $save_dir/videocd.bin $arr1",
	'spumux'=>"$prog",
        'gd'=>"$prog"
);


my $pid1;

$pid=open($file, "-|","$cmd{$subname} 2>&1") or die $! if $subname ne 'gd';
$pid1=$pid+1;
push (@pids,$pid1);
my $cmd_label=Gtk2::Label->new();	
$cmd_label->set_selectable(1);
$cmd_label->set_alignment(0,0);
my $cmd_text=word_wrap($cmd{$subname},120);
$cmd_label->set_markup("<span background='yellow' foreground='red' size='small'><i>$cmd_text</i></span>");
$cmd_label->set_max_width_chars('50');
my $cmd_label_frame1=Gtk2::Frame->new('Command Used');
$cmd_label_frame1->add($cmd_label);
$cmd_vbox->pack_end($cmd_label_frame1,0,0,0) if $append != 1;
$cmd_vbox->show_all if $append != 1;

my $end_mark;
my $feedback_type=$options{'feedback'};

if ($feedback_type eq '1'){$end_mark=$buffer->create_mark('end',$buffer->get_end_iter,0);
$buffer->signal_connect(insert_text=>sub{
$textview->scroll_to_mark($end_mark,0.0,1,0.0,1.0);});
};


if ($subname ne 'gd'){
our $tag=  Glib::IO->add_watch ( fileno($file), ['in', 'hup'], sub {
my ($fileno, $condition,$tag) = @_;

if ($condition eq 'hup') {
close $file;
Gtk2->main_quit();
return 0;
}
my $line ;

sysread $file, $line, 256;

if ($feedback_type eq '0'){
$buffer->insert($buffer->get_end_iter,$line) if $subname ne 'gd';
$gtkend->set_text($line)
}

else {
$buffer->insert($buffer->get_end_iter, $line);
}
return 1;
}
);

$btn_cancel->signal_connect('clicked', sub { kill (15,$pid1,$pid) });
if ($feedback_type eq '1'){
$buffer->signal_connect(insert_text=>sub{
$textview->scroll_to_mark($end_mark,0.0,1,0.0,1.0);});
};
}

else {

my $buffer = $textview->get_buffer;
my $line;
if ($cmd{'gd'} == 1 ){
$line="Frames are being created for DVD Menu\n\nFrame $cmd{'gd'} has been created\n"
}
else {
$line="Frame $cmd{'gd'} has been created\n";
}
$buffer->insert($buffer->get_end_iter, $line);
$gtkend->set_text($line);


return 1

}
;

Gtk2->main();

return 1
}

# Utility Functions
sub version {
my $version=`ffmpeg -version 2>&1`;
my $ffmpeg= substr((split /,/, $version)[0],index((split /,/,$version)[0],"SVN-r")+5);
}

sub word_wrap {
my ($string,$wrap)=@_;
my @wwl;
my $count=0;
my $string1=$string;
my $str_length=length($string1);

while ($count < $str_length){

{
my $len2;
my $line1=substr($string1,$count,$wrap);
if ((length($line1)+$count)<$str_length){
if (rindex($line1,' ') ne -1){
$len2=rindex($line1,' ');
}
else {$len2=$wrap}
}
else {$len2=$wrap}
my $strin2=substr($string1,$count,$len2);
push (@wwl,$strin2);
$count=$count+$len2;

}


}

$string=join("\n",@wwl);
return $string
}



# DVD Creation

sub selection_menu_jpeg {
my ($filename) = shift;
my ($filter);

my $file_chooser =Gtk2::FileChooserDialog->new (
'open file',undef,'open','gtk-cancel' => 'cancel','gtk-ok' => 'ok'
);
$file_chooser->set_select_multiple('FALSE');
$filter=Gtk2::FileFilter->new();
$filter->set_name("jpegs");

$filter->add_mime_type('image/jpeg');


(defined $filter)&&($file_chooser->add_filter($filter));


if ('ok' eq $file_chooser->run){$filename = $file_chooser-> get_filename};

$file_chooser->destroy;
return $filename
}

sub dvd_setup {
my ($vbox2,$sel_opts_vbox,$titles_vbox,$dvd_titles,$titles,$dvd_title,$menu_file,$snap,$sec,$files1,$chap)=@_;
print "sec",$sec->get_text,"sec";
my $subname='dvd_setup';
my $chapter_length=$chap->get_active_text;

my ($dvd,$spu)=($options{'dir'}.'/dvd.xml',$options{'dir'}.'/spu.xml');
foreach my $titles (sort keys %files){
no strict 'refs';

if (${$files{$titles}}[0] eq $subname){
my $key=$files{$titles}->[5];
my $file;
$file=$titles;
unless (exists($dvd_titles->{$key})){
$dvd_titles->{$key};
};
undef @{$dvd_titles->{$key}};
}
}

if (defined $files1){print"\n",1,"\n"};


foreach my $titles (sort {$files{$a}->[5] <=> $files{$b}->[5]||$files{$a}->[4] <=> $files{$b}->[4]} keys %files){
if (${$files{$titles}}[0] eq $subname){
my $chk=0;
my $key=$files{$titles}->[5];
foreach my $uniq (sort @{$dvd_titles->{$key}}){
$chk=1 if $uniq eq $files{$titles}->[2];

}

push (@{$dvd_titles->{$key}},${$files{$titles}}[2]) if $chk==0;
}
}

foreach my $keys (sort {$a<=>$b} keys %{$dvd_titles}){
my $title_hbox=Gtk2::HBox->new(0,1);
my $title=Gtk2::Label->new("title$keys");
my $title_desc=Gtk2::Entry->new();
$title_desc->set_width_chars(30);
$title_desc->set_max_length(30);
my $deltag=1;
foreach my $del (keys %files){
if ($subname eq $files{$del}->[0]){
$deltag=0 if $files{$del}->[5] eq $keys;
}
}
delete $$dvd_titles{$keys} if $deltag == 1;
if (exists $$titles{$keys}){

foreach my $files (keys %files){
$files{$files}->[6] = $$titles{$keys}->[0]->get_text if $files{$files}->[5] eq $keys;
}
}
unless (exists $$titles{$keys}){
my $file_title;
foreach my $files (sort {$files{$a}->[5] <=> $files{$b}->[5]} keys %files){

$file_title=$files{$files}->[6] if $files{$files}->[5] eq $keys;
}
if (defined ($file_title)){
$title_desc->set_text($file_title);
}
else {
my @list;

foreach my $tit (@{$dvd_titles->{$keys}}){
push @list,substr(basename($tit),0,10)
}

my $desc= join "/",@list;
$desc=~s/\/$//;
$title_desc->set_text($desc);
}
}
$title_desc->signal_connect('changed'=>sub{$$titles{$keys}[0]->set_text($title_desc->get_text)});

$title_desc->set_text($$titles{$keys}[0]->get_text) if defined  $$titles{$keys}[0];
$title_desc->set_text($title->get_text) if $title_desc eq '';
$title_hbox->pack_start($title,0,0,0);
$title_hbox->pack_start($title_desc,0,0,0);
$title_hbox->set_name($keys);
my $ref=substr($title->get_text,5);
$titles->{$ref}=[$title_desc];
push (@{$titles->{$ref}},$title_hbox);
}

$titles_vbox->set_name('titles');
no strict 'refs';
my $buttons=scalar keys %{$dvd_titles};

foreach my $file (sort keys %{$titles}){
no strict 'refs';
my $hbox=$titles->{$file}[1]->get_name;
my $ex=0;
delete $$titles{$file} unless exists $$dvd_titles{$file};
foreach my $box ($titles_vbox->get_children){

if ($box->get_name eq $hbox){
$box->destroy  unless exists $$titles{$file};
$ex = 1;
}
}

$titles_vbox->pack_start($titles->{$file}[1],0,0,0) if $ex==0;
}

my $create_dvd_button;
my $dvd_button=0;

foreach my $button ($sel_opts_vbox->get_children){
if ($button->get_name eq 'dvd_file_system'){
$dvd_button = 1
}
}

foreach my $butt ($sel_opts_vbox->get_children){
if ($butt->get_name eq 'dvd_file_system'){$sel_opts_vbox->remove($butt);
$dvd_button =0
} 
}

$create_dvd_button=Gtk2::Button->new('Create DVD File System');
$create_dvd_button->set_name('dvd_file_system');
$sel_opts_vbox->pack_start($titles_vbox,0,0,1) if $dvd_button == 0;
$sel_opts_vbox->pack_start($create_dvd_button,0,0,0) if $dvd_button == 0 and ! defined $files1;;
$sel_opts_vbox->show_all;

$create_dvd_button->signal_connect('clicked'=>sub{
my %menu_mov=(
1=>[[80,140,$titles->{1}]],
2=>[[210,140,$titles->{'1'}],[210,350,$titles->{'2'}]],
3=>[[70,140,$titles->{'1'}],[390,140,$titles->{'2'}],[230,360,$titles->{'3'}]],
4=>[[70,140,$titles->{'1'}],[390,140,$titles->{'2'}],[70,360,$titles->{'3'}],[390,360,$titles->{'4'}]],
5=>[[30,140,$titles->{'1'}],[265,140,$titles->{'2'}],[500,140,$titles->{'3'}],[130,340,$titles->{'4'}],[370,340,$titles->{'5'}]],
6=>[[30,140,$titles->{'1'}],[265,140,$titles->{'2'}],[500,140,$titles->{'3'}],[30,340,$titles->{'4'}],[265,340,$titles->{'5'}],[500,340,$titles->{'6'}]],

7=>[[25,130,$titles->{'1'}],[265,130,$titles->{'2'}],[500,130,$titles->{'3'}],[25,280,$titles->{'4'}],[265,280,$titles->{'5'}],[500,280,$titles->{'6'}],[265,430,$titles->{'7'}]],

8=>[[25,130,$titles->{'1'}],[265,130,$titles->{'2'}],[500,130,$titles->{'3'}],[25,280,$titles->{'4'}],[265,280,$titles->{'5'}],[500,280,$titles->{'6'}],[135,430,$titles->{'7'}],[370,430,$titles->{'8'}]]
);
my %size=(1=>[580,400,"1.6",18],2=>[350,200,"1.6",14],3=>[260,210,"1.333",14],4=>[260,210,"1.333",14],5=>[204,170,"1.333",12],6=>[204,170,"1.333",12],7=>[200,140,"1.6",10],8=>[200,140,"1.6",10]);

use GD::Simple;

my $img1=GD::Simple->new(720,576);
my $green="0,255,0";
my $blue= "0,0,255";
my $red= "255,0,0";
my $white= "255,210,255";
my $black= "0,0,0";
my $menu;

unless (-e $menu_file ){
$menu=GD::Simple->new(720,576);
my $title="DVD Menu";
my @fore=split /,/,$red;
my @back=split /,/,$black;
my $fore=$menu->colorAllocate(@fore);
my $back=$menu->colorAllocate(@back);
$menu->fgcolor(($back));
$menu->bgcolor($back);
$menu->font("Verdana",32);
$menu->rectangle(0,0,720,576);
$menu->moveTo('240','100');
$menu->interlaced;
$menu->fgcolor(($fore));
my $string=$menu->string($title);

my $home_menu;
$menu_file='menu_dvd.jpeg';
open (MENU,">",$menu_file);
print MENU $menu->jpeg;
close MENU;
}
my %menu_jpegs;
my $seconds=$sec->get_text ;
for (1 .. ($seconds * 25)+1){
$menu_jpegs{$_}=undef
}
my $type = ($snap->get_active==1) ? 1:0;
my %menu_files=(
'image'=>[$blue,$black],
'highlight'=>[$green,$blue],
'select'=>[$red,$white]
);

my ($text,$size,$width,$height);
$height=$size{$buttons}->[1] ;
$width=int($height * $size{$buttons}->[2]* 0.9);
(($width/2) =~/\./) ? $width++:$width;
(($height/2) =~/\./) ? $height++:$height;
$size=$width.'x'.$height;

foreach my $files (keys %menu_files){
my $ext='.png';
my $menu="$options{'dir'}/$files$ext";
open (GDP,">",$menu) ;
my $img=GD::Simple->new(720,576);
$img->transparent;

my $title_ind=1;
foreach my $keys (@{$menu_mov{$buttons}}){

my @fore=split /,/,$menu_files{$files}[1];
my @back=split /,/,$menu_files{$files}[0];
my $fore=$img->colorAllocate(@fore);
my $back=$img->colorAllocate(@back);
my %snap=(

0=>[
1],

1=>[
2]
);

no strict 'refs';
my @rect=($keys->[0],$keys->[1],$keys->[0]+$width,$keys->[1]+$size{$buttons}->[1]);

($type == 1) ? $img->fgcolor($back):$img->fgcolor($fore);
($type == 1) ? $img->bgcolor($back):$img->bgcolor(undef);

my $fontsize=$size{$buttons}->[3] * $snap{$type}->[0];
$img->font("Verdana",$fontsize);
use Text::Wrap ;
my $bound = $width-6;
my $textwidth=$img->stringWidth($keys->[2][0]->get_text);
my $col= int($bound/$textwidth * length($keys->[2][0]->get_text));

$Text::Wrap::columns=$col;

my $text=wrap('','',$keys->[2][0]->get_text);
my @str_size=$img->stringBounds($text);
($type==0)? $img->penSize(5):$img->penSize(1);
$img->rectangle(@rect);
my $gapx=int(($width-$str_size[0])/2);
my $gapy=int(($height-$str_size[1])/2);
$img->moveTo($keys->[0]+$gapx,$keys->[1]+($gapy));
($type == 1) ? $img->fgcolor(-($fore)):$img->fgcolor(undef);
my $string=$img->string($text) if $type == 1;
}
print GDP $img->png;

}
{
my $count=1;
foreach my $keys (@{$menu_mov{$buttons}}){
foreach my $keys1 (sort keys %menu_jpegs){

no strict 'refs';
$height=$size{$buttons}->[1] * 0.9;

			if (($height / 2) =~/\./){
			$height++
			}

			my $text=$keys->[2][0]->get_text;
			my @arr=($count,$count.'-'.$keys1.'.png',$width,$height,$text,$size);

			push @{$menu_jpegs{$keys1}->[0]},[@arr];

}
$count++;
}
}


my @arr_pic;
my @arr_out;
my $size=$menu_jpegs{$buttons}->[0]->[0]->[5];
foreach my $keys (sort {$a <=> $b} keys %{$dvd_titles}){
push @arr_pic, " -i ","\"", $$dvd_titles{$keys}[0],"\"";
push @arr_out," ",$options{'dir'}.'/'.$keys.'-%d.png';

}
my $listin= join "",@arr_pic;
my $out= join ' ',@arr_out;

my $prog="ffmpeg $listin -f image2 -s $size  -t $seconds  -y $out";
&run_cmd(undef,undef,$prog,undef,'spumux',$sel_opts_vbox,undef) if $type != 1;
print $type,$seconds;
if ($type != 1){
if ($seconds < .05){
delete $menu_jpegs{2}
}
foreach my $keys1 (sort {$a <=> $b} keys %menu_jpegs){
&gd_frame($keys1,$sel_opts_vbox,$menu_file,\%size,\%menu_jpegs,\%menu_mov);
Gtk2->main_iteration while (Gtk2->events_pending)
}

}

my $input=$options{'dir'}.'/dvdjpeg%d.jpeg' ;
my $output=$options{'dir'}.'/menudvd.mpg';
my $time;
if ($seconds <1){$time='5 -loop_input'} else {$time=$seconds}
my $prog;
if ($type != 1){
$prog="ffmpeg  -i $input  -f s16le -i /dev/zero  -target pal-dvd -s 720x576 -t $time -shortest -acodec mp2 -ab 64k -ar 48000 -ac 2 -aspect 4:3 -y $output";
}
else {
$prog="ffmpeg -loop_input -s 720x576 -i $menu_file -t 5 -f s16le -i /dev/zero  -target pal-dvd -s 720x576 -acodec mp2 -ab 64k -ar 48000 -ac 2 -aspect 4:3 -y $options{'dir'}/menudvd.mpg ";
}

&run_cmd(undef,undef,$prog,undef,'spumux',$sel_opts_vbox,undef,undef) ;

if ($type != 1){
foreach my $list (sort {$a <=> $b} keys %menu_jpegs){
unlink $options{'dir'}.'/dvdjpeg'.$list.'.jpeg' or print $!;
	foreach my $list2 (sort {$a <=> $b} @{$menu_jpegs{$list}->[0]}){
	unlink "$options{'dir'}/$list2->[1]" ;
	}
}
}
my $menu_file_fin="menu1.mpg";
my $output=$options{'dir'}.'/menudvd.mpg';
open (SPU,">",$spu);
print SPU "<subpictures>
<stream>
<spu start=\"00:00:00.00\" ";

print SPU "image=\"$options{'dir'}/image.png\" select=\"$options{'dir'}/select.png\" highlight=\"$options{'dir'}/highlight.png\"";


print SPU " force=\"yes\" 
autooutline=\"infer\"  outlinewidth=\"2\" 
autoorder=\"rows\" > ";
foreach my $keys (sort {$a <=> $b} keys %{$titles}){
my $but_text=$titles->{$keys}[0]->get_text;
print SPU "<button name=\"$but_text\" />";
}
print SPU "</spu>
</stream>
</subpictures>";
my $spumux=$options{'dir'}.'/spu.xml';
my $sputemp="$options{'dir'}/sputemp";
`spumux -m dvd $spumux <$output> \"$options{'dir'}/menu.mpg\" 2>$sputemp`;
my $prog="cat $sputemp";
&run_cmd(undef,undef,$prog,undef,'spumux',$sel_opts_vbox);
unlink $sputemp;

my $DVD='DVD';
my $dir2=$options{'dir'};
my $dir="$dir2/$DVD";
my $dir1="$dir/VIDEO_TS";

if (-e $dir1){
opendir DIR,$dir1;
my @DIR=readdir DIR;
foreach my $files (@DIR){
unlink "$dir1/$files" if substr($files,0,1) ne '.'}
}

foreach my $lines (sort {$files{$a}->[5]<=>$files{$b}->[5]||$files{$a}->[4]<=>$files{$b}->[4]} keys %files){
print $lines,"\t",join "\t",$files{$lines}->[2],$files{$lines}->[5],$files{$lines}->[4],"\n"
}



my $dvdfile=$dvd;
unlink $dvdfile;
open (DVD,">>", $dvdfile) or die "$!:";
print DVD "<dvdauthor dest=\"$dir\">
<vmgm>
<menus>
<pgc>
<post> jump titleset 1 menu;<\/post>
<\/pgc>
<\/menus>
<\/vmgm>
<titleset>
<menus>
<video format=\"pal\" aspect=\"4:3\"/>
<pgc entry=\"root\">
<pre> button=1024; </pre>\n";
if ($type != 1){
print DVD "<post> jump titleset 1 menu  ; </post>\n" 
}
print DVD "<vob file=\"$dir2/menu.mpg\" \/>";
foreach my $keys (sort {$a <=> $b} keys %{$dvd_titles}){

my $but_text=$titles->{$keys}[0]->get_text;
print DVD "<button name=\"$but_text\">jump title $keys;<\/button>","\n";
}



print DVD "<\/pgc>
<\/menus>";
print DVD "<titles>
<video format=\"pal\" resolution=\"352x288\"\ aspect=\"4:3\"/>";

foreach my $keys (sort {$a<=>$b} keys %{$dvd_titles}){

print DVD "<pgc>\n";
foreach my $files (@{$dvd_titles->{$keys}}){
print $files,"\t",$files{$files}->[5],"\n";
my $chapters=&duration($files,$chapter_length);
print DVD "<vob file=\"$files\" chapters =$chapters\/>\n";

}
if ($keys++ < (scalar keys  %{$dvd_titles})){
my $next =$keys;
print DVD "<post>jump title $next;<\/post>";
}
else {
print DVD "<post>call vmgm menu;<\/post>";
}
print DVD "<\/pgc>\n";
}
print DVD "
<\/titles>
<\/titleset>
<\/dvdauthor>";
close DVD;
my $prog='dvdauthor';
my $opts=" -x $dvdfile";
&run_cmd(undef,$opts,$prog,undef,$subname,$sel_opts_vbox)&& &dvd_burn($sel_opts_vbox,$dvd_title);
$create_dvd_button->destroy;
}
);

$sel_opts_vbox->show_all;
}

sub gd_frame {
my ($keys1,$sel_opts_vbox,$menu_file,$size,$menu_jpegs,$menu_mov)=@_;
	my $gd_sum=scalar keys %{$menu_jpegs};
	my $frame=GD::Simple->newFromJpeg($menu_file,1);
		foreach my $keys2 (@{$$menu_jpegs{$keys1}}){

		my $count=0;
		my $pos_key= scalar @{$keys2};
			foreach my $keys3 (@{$keys2}){
			my $file=$options{'dir'}.'/'.$keys3->[1];
			my $inset=GD::Image->newFromPng($file);
			my $title_x1=$$menu_mov{$pos_key}->[$count]->[0] ;
			my $title_x2=$$menu_mov{$pos_key}->[$count]->[0] + $keys3->[2]					;
			my $title_y1=$$menu_mov{$pos_key}->[$count]->[1] ;
			my $title_y2=int($$menu_mov{$pos_key}->[$count]->[1] + ($keys3->[3] *.1));
			my $rect_x2=$title_x1 + $keys3->[2];
			my $pos=$keys3->[3] * 1.1111;
			my $destx=$$menu_mov{$pos_key}->[$count]->[0];
			my $desty=$$menu_mov{$pos_key}->[$count]->[1]+($keys3->[3]*.1);
			$frame->copy($inset,$$menu_mov{$pos_key}->[$count]->[0],$$menu_mov{$pos_key}->[$count]->[1]+($keys3->[3]*.1),0,0,$keys3->[2],$keys3->[3]);
			my @rect_movie=($title_x1,$title_y1,$title_x2,$title_y2);
			$frame->font("Verdana",$$size{$pos_key}->[3]);
			$frame->bgcolor('blue');
			$frame->fgcolor('blue');
			$frame->rectangle(@rect_movie);
			$frame->fgcolor('white');
			$frame->moveTo($title_x1+10,$title_y2);
			$frame->string($keys3->[4]);

			$count++;
			}

		}

my $frame_new=$options{'dir'}.'/dvdjpeg'.$keys1.'.jpeg';
open (FRAME,">",$frame_new);
print FRAME $frame->jpeg;

my $append;
	if ($keys1==1){
	$append=0
	}
	else {
	$append=1
	}

&run_cmd(undef,undef,"$keys1 of $gd_sum",undef,'gd',$sel_opts_vbox,undef,$append);

return 1
}


sub dvd_burn {

my ($sel_opts_vbox,$dvd_title,$filename)=@_;

my $dir="$options{'dir'}/DVD";
my $dvd_drive=Gtk2::ComboBox->new_text;
my $DVD_speed=Gtk2::ComboBox->new_text;

$DVD_speed->set_active(0);
my %drivesd=&drive_seek('dvd_burn');
my (undef,undef,undef,$day,$month,$year)= localtime;
$year=$year+1900;
$month=$month+1;


$dvd_title->set_text("DVD-$day-$month-$year") if $dvd_title->get_text eq '';
my $volid= $dvd_title->get_text;
$dvd_title->signal_connect('changed'=>sub{$volid=$dvd_title->get_text;});

$dvd_drive->append_text("Select Drive/Filename");
foreach my $drives1 (keys %drivesd){
$dvd_drive->append_text($drives1);
}
$dvd_drive->append_text('file');
$dvd_drive->set_active(0);

my $subname='dvd_burn';
my @drives;
my $drives;
my $burn_hbox=Gtk2::HBox->new(0,1);
$burn_hbox->set_name('burn');
my $dvd_burn_btn=Gtk2::Button->new_with_label('Burn DVD');
foreach my $key ($sel_opts_vbox->get_children){$key->destroy if $key->get_name eq 'burn'};
$burn_hbox->pack_start($dvd_drive,0,0,0);
$burn_hbox->pack_start($DVD_speed,0,0,0);
$burn_hbox->pack_start($dvd_burn_btn,0,0,0);
my $filename;
$drives=$dvd_drive->signal_connect('changed'=>sub{
my $iso_file=Gtk2::Label->new;
if ($dvd_drive->get_active_text eq 'file'){
$filename=selection('Choose iso file to save','save',undef,'dvd_burn');$iso_file->set_text($filename);$drivesd{'file'}=$filename;
my $label_iso_file=Gtk2::Label->new('Iso file to save to');

my $iso_frame=Gtk2::Frame->new;
my $iso_label_frame=Gtk2::Frame->new;
$iso_frame->add($iso_file);
$iso_label_frame->add($label_iso_file);
$burn_hbox->pack_start($iso_label_frame,0,3,20);
$burn_hbox->pack_end($iso_frame,0,3,50);
$burn_hbox->show_all;
}


$drives=$drivesd{$dvd_drive->get_active_text}->[0];
$drives=~s/'//g;
$drives=~s/\s+//g;
my @speed;
if ($drivesd{$dvd_drive->get_active_text}->[1] eq 'cdr'){
@speed=(0,4,8,12,16,20,24,28,32,36,40,44,48,52)
}
else {
@speed=(1,2,3,4,5,6)
}
$DVD_speed->get_model->clear;

foreach my $speed (@speed){
$DVD_speed->append_text($speed)
}


}
);

$dvd_burn_btn->signal_connect('clicked'=>sub{
my ($opts,$prog);

if ($dvd_drive->get_active_text !~/file/ ) 
{
$prog='growisofs';
my $speed=$DVD_speed->get_active_text;
$opts="-dvd-compat -speed=$speed -Z $drives -dvd-video -V $volid $dir";
}
else {
$prog='genisoimage';
$opts=" -dvd-video -V $volid -o  $filename $dir"
}

&run_cmd(undef,$opts,$prog,undef,$subname,$sel_opts_vbox)
});

my $burn_chk=0;
if ($sel_opts_vbox->get_children eq 'burn') {
$burn_chk=1
}

$sel_opts_vbox->pack_start($burn_hbox,0,0,0) if $burn_chk ==0;
$sel_opts_vbox->show_all;
}



sub dvd_from_dir {
my ($sel_opts_vbox,$dvd_title)=@_;
my $name_hbox=Gtk2::HBox->new(0,0);
my $name_label=Gtk2::Label->new('Title for DVD');
$name_hbox->pack_start($name_label,0,0,0);
$dvd_title->signal_connect('changed'=>sub{ foreach my $key ($sel_opts_vbox->get_children){$key->destroy if $key->get_name eq 'burn'};&dvd_burn($sel_opts_vbox,$dvd_title)});
$name_hbox->pack_start($dvd_title,0,0,0);
$sel_opts_vbox->pack_start($name_hbox,0,0,0);
}

sub dvd_from_image {
my ($sel_opts_vbox,$dvd_title)=@_;
my $name_hbox=Gtk2::HBox->new(0,0);
my $filesel=Gtk2::Button->new_with_label('Choose Image File');
my $filename;
$filesel->signal_connect('clicked',sub{$filename=selection('Choose Image File','open',undef,'dvd_from_image');$filesel->set_label($filename);&dvd_burn($sel_opts_vbox,$dvd_title,$filename)});
$name_hbox->pack_start($filesel,0,0,20);
$sel_opts_vbox->pack_start($name_hbox,0,0,0);

}

sub dvd_modify {
use XML::Simple;
use strict;

%options=&options_get;
my $dvdfile=$options{'dir'}.'/dvd.xml';  
use Data::Dumper;


my %titles;
unless (-e $dvdfile){$dvdfile=selection('Select dvd.xml file','open',undef,'dvd_modify');};
my $dir = dirname ($dvdfile);
&dir_sel($dir);
my $config=XMLin($dvdfile,ForceArray=>1);
#print Dumper($config);
my $count=1;
my %files_list;

my @array;
my $count1=1;
no strict 'refs';
foreach my $keys (keys %{$config}){ 
if ($keys eq 'titleset'){
foreach my $keys2 (@{$config->{$keys}}){
foreach my $buttons (keys %{$keys2->{'menus'}[0]->{'pgc'}[0]->{'button'}}){
my $indexbut=  $keys2->{'menus'}[0]->{'pgc'}[0]->{'button'}->{$buttons}->{'content'};
$indexbut=~s/Jump Title //i;
$indexbut=~s/;//;
$titles{$indexbut}=$buttons;
}
foreach my $keys3 (@{$keys2->{'titles'}}){
foreach my $keys4 (@{$keys3->{'pgc'}}){
my $index=0;
foreach my $keys5 (@{$keys4->{'vob'}}){
$files_list{$keys5->{'file'}}=[$count1,$titles{$count1},$index];
$index++;
}
$count1++
}
}

}
}
}

return %files_list;

#}
}

# Hardware Detection

sub drive_seek {
my $sub=shift;
my %type=(dvd_burn=>{com=>'hal-find-by-capability',val=>'--capability storage.cdrom'},VCD=>{com=>'hal-find-by-property',val=>' --key volume.disc.type --string cd_rom'},DVD=>{com=>'hal-find-by-property',val=>' --key volume.fstype --string udf'});


my @drives=`$type{$sub}->{'com'} $type{$sub}->{'val'}`;
my %drivesi;
my %halh;
my %diskschk;
my @halmedia=`hal-device|grep empty|grep info.udi `;
foreach my $halmedia (@halmedia){
$halmedia=~s/\(string\)//;
my @disk=split /=/,$halmedia;
chomp $disk[1];
$diskschk{`hal-get-property --udi $disk[1] --key info.parent`}=$disk[1];
}

foreach my $drive (@drives){
my @hal=`hal-device $drive`;
my $del=0;
foreach my $hal (@hal){
if ($hal=~/dvdr.+true|cdr.+true/){
$del=1 
}
chomp $hal;
my @hal2=split /=/,$hal;
$hal2[0]=~s/\s+//g;
$hal2[1]=~s/\(string\)//g;
$halh{$hal2[0]}=$hal2[1]
}
my $type;

if ($diskschk{$drive}=~/cd_r/){
$type='cdr'
}
else {
$type='dvd'
}

$drivesi{$drive}=[{%halh},$type];
delete $drivesi{$drive} if $del != 1 and $sub eq 'dvd_burn';
}

my %drives;
foreach my $keys (keys %drivesi){

$drives{$drivesi{$keys}->[0]->{'info.product'}}=[$drivesi{$keys}->[0]->{'block.device'},$drivesi{$keys}->[1]]
}

return %drives
}

#sub cdw_search {
#my @list=`cdrdao scanbus 2>&1`;
#my @list1=grep /0,0/,@list;
#our @cdw;
#foreach my $list2 (@list1){
#chomp $list2;
#my @list2=split (/\s+/,$list2,2);
#my $jn="\t";
#my $dev=$list2[0].$jn.$list2[1];
#push (@cdw,$dev);
#}
#return @cdw;
#}


#sub device {
#our ($device,$vcd_combo)=@_;
#$device=$vcd_combo->get_active_text;
#return $device;
#}

sub track {
our ($track,$tracks_combo,)=@_;
$track=$tracks_combo->get_active_text;
return $track
}

sub source_search {
my ($source,$sel_cap_hbox,$sel_cap_vbox,$sel_opts_vbox,$delay)=@_;
my @dvds;
my @cd;
my $track;
my $device;

# Clear Widgets when Function is loaded

foreach my $box ($sel_cap_hbox->get_children){if ($box->get_name ne 'media'){
$box->destroy
}
}
foreach my $box ($sel_cap_vbox->get_children){if ($box->get_name ne 'cap_hbox'){
$box->destroy
}
}

# Setup hardware lookups

my $media=$source->[1];

my @video=`v4l-info |grep v4l2|cut -d \" \" -f 5` if $media eq "TV\ Card";
my $media1=$media;
($media=~/File|Vobs/) ? $media1 = 'DVD' : "";


my %cds=&drive_seek($media1);
my $media_count=scalar keys %cds;
my %opticals=(0=>"No $media1 found" ,2=>"Select Drive\nWith $media1" );
delete $cds{''};
@cd=$opticals{$media_count};
shift @cd if $cd[0] eq '';

@dvds =$opticals{$media_count} unless $media_count == 1;
my %disks;
foreach my $dvd (keys %cds){
no strict 'refs';
$disks{$dvd}=$cds{$dvd}->[0];
push (@dvds,$dvd);
}
print @dvds;
foreach my $cds (keys %cds){
push (@cd,$cds);
}

my @source1;
@source1="Select Video Device" if scalar @source1 > 0;

foreach my $videos (@video){
$videos=~s/\[//g;
$videos=~s/\]//g;
push(@source1,$videos);
}

my @screen;

if ($media eq "Screen"){
my $width=Gtk2::Gdk::Screen->get_default->get_width;
my $height=Gtk2::Gdk::Screen->get_default->get_height;

my $sizec=join('',$width,"x",$height);
@screen=("Select Screen Size",$sizec,"1280x1024","1024x768","800x600","640x480","320x240");
{my $count = 0;
foreach my $screen (@screen[2..7]){
$count++;
if ($screen eq $sizec){
splice @screen,$count,1
}
}
pop @screen;
}
}

my $bitrate;
my $standard="pal";
my $channel=0;
my %input;
my @standard;
my @input;
my %standard;

if ($media eq "TV\ Card") {

my $standards=`v4l-info|grep std`;
my $inds=rindex($standards,"[");
my $indl=rindex($standards,"]");
my $len=$indl-$inds;
my $standard1=substr($standards,$inds+1,$len-1);
@standard=split /,/,$standard1;
foreach my $line (@standard){
$line=~s/CAM_/CAM /g;
$line=~s/_/-/;

}
foreach my $line (@standard){
my $key;
if ($line=~/PAL/){
$key='pal'
}
elsif ($line=~/NTSC/){
$key='ntsc'
}
elsif ($line=~/SECAM/){
$key='secam'
}
else {$key='pal'}
$standard{$line}=$key

}


my $channels=`v4lctl list|grep input`;
my $indsc=rindex($channels,"|");
$standard1=substr($channels,$indsc+1);
my @channels=split /\s+/,$standard1;
my $count=-1;

foreach my $line (@channels){
$input{$line}=$count;
$count++;
}
delete $input{''};
foreach my $keys (sort keys %input){
push (@input,$keys)
}

}

my %quality =("High Quality"=>["0","0"],
"Good Quality"=>["1","0"],"Average Quality"=>["2","1"],"Poor Quality"=>["2","0"]
);
my %bitrate=("Select Encoding Quality" => "-qscale 3","Copy Input" => "-sameq" ,"High Bitrate" => "-qscale 3","Medium Bitrate" => "-qscale 4","Medium low bitrate" => "-qscale 5", "Low Bitrate" => "-qscale 6","very Low Bitrate" => "-qscale 7" , "poor quaity tape " => "-qscale 9");

my %actions=('GtkComboBox'=>['set_active','get_active_text','append_text'],'GtkComboBoxEntry'=>['set_active','get_active_text','append_text'],'GtkButton'=>['set_label',undef,undef],'GtkEntry'=>['set_text','get_text',undef]);

## Hash of arrays defining Widget placement and actions
#array[0] defines widgets and asssociated actions
# array[0][0] is a one element array defining program to run
# array[0][1] defines widgets at top of screen (horizontal) - widget type,widget data,,appropriate action for widget, switch for option, default value for option (index for combo boxes - ie: most),switches for order control
# array[0][2] defines widgets below (vertical)

no strict 'refs';

my %capture=('VCD'=>[
[
["vcdxrip"],

[Gtk2::ComboBox->new_text,[@cd],""," -C",1,\%disks],
[Gtk2::ComboBox->new_text,["Select Single \nTrack to Rip",'1','2','3','4','5','6','7'],"","-t",'0',undef],
[Gtk2::Button->new('Capture'),['Capture'],undef,undef,undef,undef]
],
[undef ],
[undef," -p"],
],

'File'=>[
[
["vobcopy"],

[Gtk2::ComboBox->new_text,[@dvds],""," -i ",'0',\%disks],
[Gtk2::ComboBox->new_text,["Select Title \n to Rip",'1','2','3','4','5','6','7'],""," -n ",'0',undef],
[Gtk2::Button->new,['Capture'],undef,undef,undef]
],

[undef],

[undef," -l  -o "],

],
'Vobs'=>[
[
["dvdunauthor"],

[Gtk2::ComboBox->new_text,[@dvds],"","  ",'0',\%disks],
[Gtk2::Button->new,['Capture'],undef,undef,undef]
],

[undef],

[undef,undef],

],



"TV\ Card"=>[
[
["ffmpeg"],
[Gtk2::ComboBox->new_text,[@source1],""," -croptop 8 -cropbottom 8 -cropleft 8 -cropright 8 -r 25 -tvstd $standard -f video4linux2 -i ",0,undef],
[Gtk2::ComboBox->new_text,["Select Quality","High Quality","Good Quality","Average Quality","Poor Quality"],"",undef,undef,3],
#[Gtk2::ComboBox->new_text,["Select Encoding Quality","Copy Input","High Bitrate","Medium Bitrate","Medium low bitrate", "Low Bitrate"],"",undef,1,\%bitrate],
[Gtk2::ComboBox->new_text,[keys %bitrate],"",undef,1,\%bitrate],

[Gtk2::Button->new,['Capture'],undef,undef,undef,undef],

],

[
undef,
[Gtk2::ComboBoxEntry->new_text,["720x576","640x480","352x288"],Gtk2::Label->new("Size"), "-s",'1',undef,2],
[Gtk2::ComboBoxEntry->new_text,["24","12"],Gtk2::Label->new("Async")," -async",'0',undef,1],
[Gtk2::ComboBoxEntry->new_text,["00:30:00", "01:00:00", "01:30:00", "02:00:00", "02:30:00", "03:00:00", "03:30:00", "04:00:00","04:30:00", "05:00:00","05:30:00", "06:00:00"],Gtk2::Label->new("Time")," -t",'0',undef,0],
[Gtk2::ComboBoxEntry->new_text,[@input],Gtk2::Label->new("Input (for tv Card)")," -vc ",'0',\%input,1],
[Gtk2::ComboBoxEntry->new_text,[@standard],Gtk2::Label->new("Video Standard"),' -tvstd ',undef,\%standard,0],
[Gtk2::ComboBoxEntry->new_text,["1","2"],Gtk2::Label->new("Audio Channels")," -ac ",'1',undef,0],

[Gtk2::Entry->new,[""],Gtk2::Label->new("File Name"),undef,'test.avi',undef,3]

],

[undef, " -f oss -i /dev/dsp -f avi  -r 25 -v 2  -aspect 4:3 -acodec mp2  -ab 224k -vol 512 -ar 48000 -y "],

],

'Screen'=>[
[
["ffmpeg"],
[Gtk2::ComboBoxEntry->new_text,[@screen],""," -s",0,undef],
[Gtk2::Button->new,['Capture'],"",undef,undef,undef,undef]
],

[
undef,
[Gtk2::ComboBoxEntry->new_text,["00:30:00", "01:00:00", "01:30:00", "02:00:00", "02:30:00", "03:00:00", "03:30:00", "04:00:00","04:30:00", "05:00:00","05:30:00", "06:00:00"],Gtk2::Label->new("Time")," -t",0,undef],
[Gtk2::ComboBoxEntry->new_text,["2","3","4","5","6","7","8","9","10","11","12","13","14","15"],Gtk2::Label->new("Quality")," -qscale ",0,undef],
[Gtk2::Entry->new,[],Gtk2::Label->new("File Name"),undef,undef,undef,3]
],
[undef," -r 12 -f x11grab -i :0.0 -an -r 12 -y "]
]
);



my $ffmpeg=&version;

if ($ffmpeg < 7983){
no strict 'refs';
$capture{"TV\ Card"}->[0][1][4]=" -vd ";
$capture{"TV\ Card"}->[2]=~s/-f audio_device -i / -ad /g;
$capture{"Screen"}->[2]=~s/-f x11grab -i :0.0/ -vd x11:0.0 /g;
}
elsif ($ffmpeg >10428){
$capture{"TV\ Card"}->[2]=~s/-f audio_device -i / -f oss /g;
}

my $end=scalar @{$capture{$media}->[0]} - 1;

foreach my $widget (@{$capture{$media}->[0]}[1 .. $end]){
my $box=$widget->[0];

foreach my $data (@{$widget->[1]})
{
	if (defined $actions{$box->get_name}->[2]){
	my $action=$actions{$box->get_name}->[2] ;
	$box->$action($data)
	}
}

my $set=$actions{$box->get_name}->[0];
$box->$set($widget->[3]);
$sel_cap_hbox->pack_start($widget->[0],0,0,0)
}

$capture{$media}->[0]->[-1]->[0]->set_label('Capture');

$sel_cap_hbox->show_all;

my $end_vbox=scalar @{$capture{$media}->[1]} -1;

foreach my $widget (@{$capture{$media}->[1]}[1 .. $end_vbox]){
my $box=$widget->[0];
my $action=$actions{$box->get_name}->[2];

foreach my $data (@{$widget->[1]}){
if (defined $actions{$box->get_name}->[2]){
my $action=$actions{$box->get_name}->[2];
$box->$action($data)
}
}
my $hbox=Gtk2::HBox->new(0,0);
$widget->[2]->set_alignment(0,0) ;
$widget->[2]->set_width_chars(25) ;
$widget->[0]->set_size_request(225);

my $action2=$actions{$box->get_name}->[0] ;
$box->$action2($widget->[4]) if defined $widget->[4];
$hbox->pack_start($widget->[2],0,0,0);
$hbox->pack_start($widget->[0],0,0,0);
$sel_cap_vbox->pack_start($hbox,0,0,0)
}
$sel_cap_vbox->show_all;
my @opts;

if ($media eq "TV\ Card"){
$capture{$media}->[0][2][0]->signal_connect('changed' =>sub{
my $key=$quality{$capture{$media}->[0][2][0]->get_active_text};
$capture{$media}->[1][1][0]->set_active($key->[0]);
$capture{$media}->[1][2][0]->set_active($key->[1]);
}
);
}

$capture{$media}->[0][-1][0]->signal_connect('clicked' =>sub{

@opts='';
foreach my $opts (@{$capture{$media}->[0]}[1 .. $end-1]){
my $action=$actions{$opts->[0]->get_name}->[1] ;

my $opt;

if (defined $opts->[5]){
my $hash=$opts->[5];
$opt=$opts->[3].' '.$hash->{$opts->[0]->$action};
}
else {
$opt=$opts->[3].' '.$opts->[0]->$action ;
}

$opt=~s/\n//g;
push (@opts,$opt) if $opt!~/Select/;
}

foreach my $opts (@{$capture{$media}->[1]}[1 .. $end_vbox]){
my $action=$actions{$opts->[0]->get_name}->[1] ;
my $opt;
if (defined $opts->[5]){
my $hash=$opts->[5];
$opt=$opts->[3].' '.$hash->{$opts->[0]->$action};

}
else {
$opt=$opts->[3].' '.$opts->[0]->$action if defined $opts->[4];
}

if ($opts->[6] == 2){
unshift (@opts, $opt);
push (@opts, $opt);
}
elsif ($opts->[6] == 1){
unshift (@opts, $opt);
}
else  {
push(@opts, $opt) unless $opts->[6] == 3
}
}

push (@opts,$capture{$media}->[2]->[1]);
my $output;
if (defined $capture{$media}->[1]->[-1]->[0]){
my $file=$capture{$media}->[1]->[-1]->[0]->get_text;
$output=$options{'dir'}.'/'.$file;
}
else {
$output=$options{'dir'};
}

if ($media=~/VCD|Vobs/){
my $subdir=$capture{$media}->[0]->[1]->[0]->get_active_text;
$subdir=~s/\'//g;
$subdir=~s/^\s+//g;
$subdir=~s/\s+$//g;
my $outputdir=$output.'/'.$subdir.'/';
mkdir $outputdir;
chdir $outputdir
}
else {
push (@opts,$output);
}
my $opts=join(" ",@opts);
if ($delay->get_text ne 0){
my $del=$delay->get_text * 60;
sleep $del;
}
&run_cmd(undef,$opts,$capture{$media}->[0][0][0],undef,'capture',$sel_opts_vbox,undef)
}); 

}

sub duration {
my ($file,$chap)=@_;
my $arr=`ffmpeg -i \"$file\" 2>&1`;
my @arr=split /\n/,$arr;
my $dur;
foreach my $out (@arr){
$dur=$out if $out=~/Duration/
}
$dur=~s/\s+//g;
$dur=~s/,.+//g;
$dur=~s/Duration://g;
my @sec=split /:/,$dur;
my $length= (($sec[0] * 3600) + ($sec[1] * 60) + $sec[2]);
my $chk=30;
$chap=$chap * 60;
my @chapters;
until ($chk>=$length){
my ($sec,$min,$hr)= localtime($chk);
$hr=$hr-1;
$hr="0$hr";
(length($min) == 1)? $min="0$min":$min;
my $chapter=$hr.':'.$min.':00';
push @chapters, $chapter;
$chk=$chk + $chap;
}
my $chapters='"'. (join ',',@chapters). '"';

return $chapters
}
