more work on preroll, time_pos now updates $pos
[HTML5TV.git] / bin / mplayer.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use IPC::Open3 qw(open3);
7 use IO::Select;
8 use Data::Dump qw(dump);
9 use File::Slurp;
10 use YAML;
11 use JSON;
12 use HTML::TreeBuilder;
13 use Graphics::Magick;
14 use Time::HiRes qw(time);
15 use File::Path qw(rmtree);
16
17 use lib 'lib';
18 use HTML5TV::Slides;
19
20 my $debug = $ENV{DEBUG} || 0;
21
22 my $movie = shift @ARGV;
23
24 sub base_dir  { $1 if $_[0] =~ m{^(.+)/[^/]+$} }
25 sub base_name { $1 if $_[0] =~ m{^.+/([^/]+)$} }
26
27 if ( ! $movie && -e 'media/_editing' ) {
28         $movie = 'media/' . readlink('media/_editing') . '/video.ogv';
29         warn "using media/_editing -> $movie\n";
30 } elsif ( -d $movie && $movie =~ m{media/} ) {
31         $movie .= '/video.ogv';
32 } elsif ( -f $movie && $movie !~ m{video\.ogv} ) {
33         my $movie_master = $movie;
34         $movie = base_dir($movie) . '/video.ogv';
35         if ( ! -e $movie ) {
36                 symlink base_name($movie_master), $movie;
37                 warn "symlink video.ogv -> $movie_master";
38         } else {
39                 warn "using symlink video.ogv -> ", readlink $movie;
40         }
41 } elsif ( -f $movie ) {
42         warn "using video $movie";
43 } else {
44         die "Usage: $0 media/conference-Title_of_talk[/video.ogv'\n";
45 }
46
47 my $media_part = my $media_dir = base_dir($movie);
48 $media_part =~ s{media/}{};
49 $media_part =~ s{/$}{};
50
51 unlink 'media/_editing';
52 symlink $media_part, 'media/_editing';
53
54 warn "# media_part $media_part\n";
55
56 my $edl = "/dev/shm/edl";
57 my $subtitles = $movie;
58 $subtitles =~ s{\.\w+$}{.srt};
59
60 my $preroll = 3;
61
62 my $slide_factor = 4; # 1/4 size of video
63
64 my $min_slide_height = 480;
65
66 our $to_mplayer;
67 our $from_mplayer;
68 our $err_mplayer;
69 our $prop = {};
70
71 my $pid = open3( $to_mplayer, $from_mplayer, $err_mplayer,
72          'mplayer',
73                 '-slave', '-idle',
74 #               '-quiet',
75 #               '-msglevel', 'demux=9', '-msgmodule',
76                 '-edlout', $edl,
77                 '-osdlevel', 3,
78                 '-vf' => 'screenshot',
79 );
80
81 my $select = IO::Select->new();
82 #$select->add( \*STDIN );
83 $select->add( $from_mplayer );
84 #$select->add( $err_mplayer );
85
86 sub load_subtitles;
87
88 sub load_movie {
89         warn "$movie ", -s $movie, " bytes $edl\n";
90         print $to_mplayer qq|loadfile "$movie"\n|;
91         load_subtitles;
92 }
93
94
95 my $term_id = `xdotool getwindowfocus`;
96 our $mplayer_id;
97
98
99 sub focus_mplayer {
100         $mplayer_id ||= `xdotool search mplayer`;
101         warn "focus_mplayer $mplayer_id\n";
102         system "xdotool windowactivate $mplayer_id"
103 }
104
105 sub focus_term {
106         warn "focus_term $term_id\n";
107         system "xdotool windowactivate $term_id";
108 }
109
110 our $pos;
111
112 sub preroll {
113         my ( $to, $osd ) = @_;
114         $osd =~ s{\W+}{ }gs;
115         my $preroll_to = $to - $preroll;
116         $preroll_to = 0 if $preroll_to < 0;
117         print $to_mplayer "set_property time_pos $preroll_to\n";
118         my $osd_ms = ( $to - time_pos() ) * 1000;
119         print $to_mplayer "get_property time_pos\n";
120         print $to_mplayer "osd_show_text \"PREROLL $osd\"\n"; # $osd_ms\n";
121         warn "PREROLL $to -> $pos [$osd_ms] $osd\n";
122         print $to_mplayer "play\n";
123 }
124
125
126 $|=1;
127
128 my $line;
129 my $repl;
130
131 sub repl {
132         print "> ";
133         my $cmd = <STDIN>;
134         warn ">>> $cmd\n";
135         print $to_mplayer $cmd;
136 }
137
138
139 our @subtitles;
140
141 sub slide_jpg {
142         sprintf "%s/s/%d/%03d.jpg", $media_dir, @_;
143 }
144
145 sub oggThumb {
146         my $video = shift;
147         my $file  = shift;
148         my $t = join(',', @_);
149         system "oggThumb -t $t -o jpg -n $file $video";
150 }
151
152 sub fmt_mmss {
153         my $t = shift;
154         return sprintf('%02d:%02d', int($t/60), int($t%60));
155 }
156
157 sub html5tv {
158
159         if ( ! $prop->{width} || ! $prop->{height} ) {
160                 warn "SKIP no size yet\n";
161                 return;
162         }
163
164         if ( ! @subtitles ) {
165                 warn "SKIP no subtitles yet\n";
166                 return;
167         }
168
169         warn "html5tv";
170
171         my $sync;
172
173         my @slide_t;
174
175         my @videos;
176         my @frames;
177
178         foreach my $s ( @subtitles ) {
179                 push @{ $sync->{htmlEvents}->{'#subtitle'} }, {
180                         startTime => $s->[0],
181                         endTime   => $s->[1],
182                         html      => $s->[2],
183                 };
184
185                 if ( $s->[2] =~ m{video:(.+)} ) {
186                         my $video = $1;
187                         my $path = "$media_dir/$video";
188                         if ( ! -e $path ) {
189                                 warn "MISSING $path: $!\n";
190                         } else {
191                                 my $frame_dir = "$media_dir/s/$video";
192                                 system "mplayer -vo jpeg:outdir=$frame_dir,quality=95 -frames 1 -ss 0 -ao null -really-quiet $media_dir/$video"
193                                         if ! -e $frame_dir;
194                                 push @videos, [ @$s, $video ];
195                         }
196                 } elsif ( $s->[2] =~ m{slide:(\d+)\s+shot:(\d+\.\d+)} ) {
197                         push @frames, [ $2, $1 ];
198                         next;
199                 }
200
201                 next unless $s->[2] =~ m{\[(\d+)\]};
202
203
204                 push @{ $sync->{customEvents} }, {
205                         startTime => $s->[0],
206                         endTime   => $s->[1],
207                         action    => 'chapterChange',
208                         args => {
209                                 carousel => 'theCarousel',
210                                 id => "chapter$1",
211                                 title => $s->[2],
212                                 description => $s->[2],
213                                 src => slide_jpg( 4 => $1 ),
214                                 href => '',
215                         },
216                 };
217
218                 push @slide_t, $s->[0];
219         }
220
221         if ( @frames ) {
222                 rmdir $_ foreach glob "$media_dir/s/[124]";
223                 my $hires = "$media_dir/s/hires";
224                 mkdir $hires unless -e $hires;
225
226                 oggThumb $movie, "$hires/.f%.jpg", map { $_->[0] } @frames;
227
228                 foreach my $i ( 0 .. $#frames ) {
229                         my $from = "$hires/.f$i.jpg";
230                         my $to   = "$hires/f" . $frames[$i]->[1] . '.jpg';
231                         rename $from, $to || warn "can't rename $from -> $to: $!";
232                 }
233
234         }
235
236         foreach ( 0 .. $#slide_t ) {
237                 my $slide_nr = $_ + 1;
238                 push @{ $sync->{htmlEvents}->{'#slide'} }, {
239                         startTime => $slide_t[$_],
240                         endTime   => $slide_t[$_ + 1] || $prop->{length},
241                         html      => '<img src=' . slide_jpg( 1 => $slide_nr ) . '>',
242                 };
243         }
244
245         my @slides_hires = glob "$media_dir/s/hires/*";
246
247         my $path = "$media_dir/s";
248
249         if ( ! -d $path ) {
250                 warn "create slides images in $path";
251                 mkdir $path;
252         }
253
254         foreach my $hires ( @slides_hires ) {
255
256                 my ($slide_width, $slide_height) = Graphics::Magick->new->Ping( $hires );
257                 my $slide_aspect = $slide_width / $slide_height;
258
259                 my $nr = $1 if $hires =~ m{(\d+)\.\w+$} || warn "can't find number in $hires";
260                 next unless $nr;
261
262                 my $im;
263
264                 foreach my $factor ( 1, 2, 4 ) {
265
266                         mkdir "$path/$factor" unless -e "$path/$factor";
267
268                         my $file = slide_jpg( $factor => $nr );
269                         next if -e $file;
270
271                         $min_slide_height = $prop->{height} if $prop->{height} > $min_slide_height;
272
273                         my $w = $min_slide_height / $factor * $slide_aspect;
274                         my $h = $min_slide_height / $factor;
275
276                         warn "slide [$nr] $hires -> ${w}x${h} $file\n";
277
278                         if ( ! $im ) {
279                                 warn "loading $hires ", -s $hires, " bytes\n";
280                                 $im = Graphics::Magick->new;
281                                 $im->ReadImage( $hires );
282                         }
283                         $im->Resize( width => $w, height => $h, filter => 13, blur => 0.9 );
284
285                         my $c = 1; # $h / 10;
286                         my %info = (
287                                 font => 'Sans', pointsize => $h / 10,
288                                 #text => "$factor = $w*$h",
289                                 text => " $nr ",
290                                 y => $c,
291                                 x => $c,
292                         );
293                         #warn "# info ", dump %info;
294                         #warn dump $im->QueryFontMetrics( %info );
295                         my ($x_ppem, $y_ppem, $ascender, $descender, $width, $height, $max_advance) = $im->QueryFontMetrics( %info );
296                         my $background = Graphics::Magick->new( size => $width . 'x' . $height );
297                         $background->ReadImage( 'xc:black' );
298                         $im->Composite( image => $background, compose => 'Over', x => $c, y => $c, opacity => 75 );
299                         $info{y} += $ascender;
300                         $im->Annotate( fill => 'yellow', %info );
301                         $im->Write( filename => $file );
302                 }
303
304         }
305
306         my ($slide_width, $slide_height, $size, $format) = Graphics::Magick->new->Ping( slide_jpg( $slide_factor => 1 ) );
307
308         my $html5tv = {
309                 sync => $sync,
310                 video => $prop,
311                 slide => {
312                         width => $slide_width,
313                         height => $slide_height,
314                 },
315         };
316
317         $html5tv->{html}->{video_tags} =
318                 join("\n",
319                         map {
320                                 my $s = $_;
321                                 my $id = $s->[3];
322                                 $id =~ s{\W+}{_}g;
323
324                                 push @{ $html5tv->{sync}->{customEvents} }, {
325                                         startTime => $s->[0],
326                                         endTime   => $s->[1],
327                                         action    => 'additional_video',
328                                         args => {
329                                                 id => $id,
330                                                 title => $s->[2],
331                                                 description => $s->[2],
332                                                 src => "$media_dir/s/1/00000001.jpg",
333                                                 href => '',
334                                         },
335                                 };
336
337                                 qq|
338                                         <video id="$id" style="display: none" controls="controls" width="$html5tv->{video}->{width}px" height="$html5tv->{video}->{height}px">
339                                         <source src="$media_dir/$_->[3]" />
340                                         </video>
341                                 |
342                         } @videos
343                 )
344         ;
345
346         my @customEvents_sorted;
347
348         if ( ref $html5tv->{sync}->{customEvents} ne 'ARRAY' ) {
349                 my $max = 
350                 warn "ERROR: no slide markers [1] .. [", scalar @slides_hires, "] in subtitles\n";
351                 return;
352         } else {
353                 @customEvents_sorted =
354                 sort { $a->{startTime} <=> $b->{startTime} }
355                 @{ $html5tv->{sync}->{customEvents} }
356                 ;
357         }
358
359         my $index = 1;
360
361         $_->{args}->{index} = $index++ foreach @customEvents_sorted;
362
363         warn "last customEvent $index\n";
364
365         $html5tv->{html}->{subtitles_table}
366                 = qq|<table id="subtitles">|
367                 . join("\n",
368                         map {
369                                 my $s = fmt_mmss( $_->{startTime} );
370                                 my $e = fmt_mmss( $_->{endTime} );
371                                 qq|
372                                 <tr id="sub_$_->{index}">
373                                         <td class="seek_video"><a href="#$_->{startTime}">$s</a></td>
374                                         <td class="seek_video"><a href="#$_->{endTime}">$e</a></td>
375                                         <td>$_->{args}->{title}</td>
376                                 </tr>
377                                 |
378                         }
379                         @customEvents_sorted
380                 )
381                 . qq|</table><a href="$media_dir/video.srt">download subtitles</a>|
382                 ;
383
384         my $hCalendar = '<div style="color: red">Create <tt>hCalendar.html</tt> to fill this space</div>';
385         my $hcal_path = "$media_dir/hCalendar.html";
386         if ( -e $hcal_path ) {
387                 $html5tv->{hCalendar} = read_file $hcal_path;
388                 my $tree = HTML::TreeBuilder->new;
389                 $tree->parse_file($hcal_path);
390                 if ( my $vevent = $tree->look_down( class => 'vevent' ) ) {
391                         $html5tv->{title} = $vevent->look_down( class=> 'summary' )->as_trimmed_text;
392                 }
393         }
394
395         warn "# html5tv ", dump $html5tv if $debug;
396
397         my $sync_path = "$media_dir/video.js";
398         write_file $sync_path, "var html5tv = " . to_json($html5tv) . " ;\n";
399         warn "sync $sync_path ", -s $sync_path, " bytes\n";
400
401         my $html = read_file 'www/tv.html';
402         $html =~ s|{([^}]+)}|my $n = $1; $n =~ s(\.)(}->{)g; eval "\$html5tv->{$n}"|egs ||
403                 warn "no interpolation in template!";
404
405         write_file "www/_editing.html", $html;
406         $html =~ s{media/_editing}{media/$media_part}gs;
407         write_file "www/$media_part.html", $html;
408
409         my $carousel_width = $prop->{width} + $slide_width - 80;
410         $carousel_width -= $carousel_width % ( $slide_width + 6 ); # round to full slide
411         my $carousel_height =   $slide_height + 2;
412
413         write_file "$media_dir/video.css", qq|
414
415 .jcarousel-skin-ie7 .jcarousel-container-horizontal,
416 .jcarousel-skin-ie7 .jcarousel-clip-horizontal {
417         width: ${carousel_width}px;
418         height: ${carousel_height}px;
419 }
420
421 .jcarousel-skin-ie7 .jcarousel-item {
422         width: ${slide_width}px;
423         height: ${slide_height}px;
424         margin: 0 2px 0 2px;
425 }
426
427 .active {
428         background-color: #ffc;
429 }
430
431 div#videoContainer {
432         width: $prop->{width}px;
433         height: $prop->{height}px;
434         font-family: Arial, Helvetica, sans-serif;
435         margin: 0 10px 0px 0;
436         position: relative;
437         display: inline;
438 }
439
440
441 div#subtitle {
442         bottom: 24px;
443         color: white;
444         font-size: 100%;
445         font-weight: bold;
446         height: 22px;
447         line-height: 1em;
448         margin: 0  0 0 0;
449         padding: 1px 10px 5px 10px ;
450         position: absolute;
451         text-align: center;
452         width: $html5tv->{video}->{width}px;
453 }
454
455
456
457 .jcarousel-skin-ie7 .jcarousel-item img:hover {
458 //      border-color: #555 !important;
459 }
460
461 .jcarousel-skin-ie7 .jcarousel-item:hover div.thumbnailOverlay {
462         visibility: visible !important;
463 }
464
465 .jcarousel-skin-ie7 .jcarousel-item div.thumbnailOverlay {
466         background: black;
467         bottom: 1px;
468         color: #00EEFF;
469         visibility: hidden;
470         font-size: 10px;
471         font-family: Arial, Verdana;
472         font-weight: bold;
473         line-height: 0.9em;
474         opacity: 0.5;
475         position: absolute;
476         text-align: center;
477         z-index: 10;
478         padding: 2px 0 2px 0;
479         width: ${slide_width}px;
480 }
481
482 .seek_video {
483         text-align: right;
484         font-family: monospace;
485 }
486
487         |;
488
489         return 1;
490 }
491
492
493 sub t_srt {
494         my $t = shift;
495         my $hh = int( $t / 3600 );
496         $t -= $hh * 3600;
497         my $mm = int( $t / 60 );
498         $t -= $mm * 60;
499         my $srt = sprintf "%02d:%02d:%04.1f", $hh, $mm, $t;
500         $srt =~ s{\.}{,};
501         return $srt;
502 }
503
504 my @to_mplayer;
505
506 sub save_subtitles {
507
508         html5tv || return;
509
510         my $nr = 0;
511         my $srt = "\n";
512         foreach my $s ( @subtitles ) {
513                 $srt .= $nr++ . "\n"
514                         . t_srt( $s->[0] ) . " --> " . t_srt( $s->[1] ) . "\n"
515                         . $s->[2] . "\n\n"
516                         ;
517         }
518         warn $srt;
519
520         write_file $subtitles, $srt;
521         YAML::DumpFile "$subtitles.yaml", sort { $a->[0] <=> $b->[0] } @subtitles;
522
523         push @to_mplayer
524                 , "sub_remove\n"
525                 , qq|sub_load "$subtitles"\n|
526                 , "sub_select 1\n"
527                 ;
528 }
529
530 sub load_subtitles {
531         if ( ! -e "$subtitles.yaml" ) {
532                 warn "no subtitles $subtitles to load\n";
533                 return;
534         }
535         @subtitles = YAML::LoadFile "$subtitles.yaml";
536         warn "subtitles ", dump @subtitles;
537         save_subtitles;
538 }
539
540 sub edit_subtitles {
541         print $to_mplayer qq|pause\n|;
542         focus_term;
543         system( qq|vi "$subtitles.yaml"| ) == 0 and load_subtitles;
544         focus_mplayer;
545 }
546
547 sub add_subtitle {
548         print $to_mplayer qq|pause\n|;
549
550         focus_term;
551
552         warn "subtitles ", dump( @subtitles );
553         print "## ";
554         my $line = <STDIN>;
555         $subtitles[ $#subtitles ]->[2] = $line if defined $line;
556
557         save_subtitles;
558
559         focus_mplayer;
560
561         preroll $subtitles[ $#subtitles ]->[0], $line;
562 }
563
564 sub time_pos {
565         print $to_mplayer qq|get_property time_pos\n|;
566         my $line = <$from_mplayer>;
567         if ( $line =~ m{^ANS_time_pos=(\d+\.\d+)} ) {
568                 warn "# time_pos $1\n";
569                 $pos = $1;
570                 return $1;
571         }
572 }
573
574 sub sub_fmt {
575         my $s = shift;
576         sprintf "%1.5f - %1.5f %s %s\n", @$s, join(' | ',@_);
577 }
578
579 sub prev_subtitle {
580         my $s = ( grep { $_->[0] < $pos } @subtitles )[-1] || return;
581         warn "<<<< subtitle ", sub_fmt $s;
582         preroll $s->[0], $s->[2];
583 #       print $to_mplayer "set_property time_pos $s->[0]\n";
584 }
585
586 sub next_subtitle {
587         my $s = ( grep { $_->[0] > $pos } @subtitles )[0] || return;
588         warn ">>>> subtitle ", sub_fmt $s;
589         preroll $s->[0], $s->[2];
590 #       print $to_mplayer "set_property time_pos $s->[0]\n";
591 }
592
593 sub current_subtitle {
594         my $callback = shift;
595         my $visible;
596         foreach my $nr ( 0 .. $#subtitles ) {
597                 my $s = $subtitles[$nr];
598                 if ( $s->[0] <= $pos && $s->[1] >= $pos ) {
599                         warn sub_fmt $s, $pos;
600                         $visible = $nr;
601                         $callback->( $visible, $pos ) if $callback;
602                         return ( $visible, $pos );
603                 }
604         }
605         warn "# $pos no visible subtitle\n";
606 }
607
608 sub move_subtitle {
609         my $offset = shift;
610         current_subtitle( sub {
611                 my ( $nr, $pos ) = @_;
612                 my $new_start = $subtitles[$nr]->[0] += $offset;
613                 warn "subtitle $nr $pos $offset $new_start\n";
614                 save_subtitles;
615                 preroll $new_start, "$pos $offset $new_start";
616         } );
617 }
618
619
620
621 # XXX main epool loop
622
623 load_movie;
624
625 my $slides = HTML5TV::Slides->new(
626         sub {
627                 my $t = shift;
628                 my $nr = 0;
629                 foreach my $s ( @subtitles ) {
630                         $nr = $1 if $s->[2] =~ m{\[(\d+)\]} && $s->[0] < $t;
631                 }
632                 return $nr;
633         }
634 );
635
636
637 sub from_mplayer {
638         my $line = shift;
639
640         if ( $line =~ m{V:\s+(\d+\.\d+)\s+} ) {
641                 $pos = $1;
642                 print "$pos\r";
643 #               $pos = $1 if $1 > 0.2; # mplayer demuxer report fake position while seeking
644         } elsif ( $line =~ m{Exiting} ) {
645                 exit;
646         } elsif ( $line =~ m{ANS_(\w+)=(\S+)} ) {
647                 $prop->{$1} = $2;
648                 warn "prop $1 = $2\n";
649         } elsif ( $line =~ m{No bind found for key '(.+)'} ) {
650
651                 # XXX keyboard shortcuts
652
653                   $1 eq 'c'  ? repl
654                 : $1 eq ','  ? add_subtitle
655                 : $1 eq 'F1' ? prev_subtitle
656                 : $1 eq 'F2' ? move_subtitle( -0.3 )
657                 : $1 eq 'F3' ? move_subtitle( +0.3 )
658                 : $1 eq 'F4' ? next_subtitle
659                 : $1 eq 'F5' ? save_subtitles
660                 : $1 eq 'F9' ? add_subtitle
661                 : $1 eq 'F12' ? edit_subtitles
662                 : warn "CUSTOM $1\n"
663                 ;
664
665         } elsif ( $line =~ m{EDL}i ) {
666
667                 print $to_mplayer qq|osd_show_text "$line"\n|;
668
669                 if ( $line =~ m{start}i ) {
670                         push @subtitles, [ $pos, $pos, '-' ];
671                 } else {
672                         $subtitles[ $#subtitles ]->[1] = $pos;
673                 }
674         } elsif ( $line =~ m{(shot\d+.png)} ) {
675                 my $shot = $1;
676                 warn "shot $pos $shot\n";
677
678                 my @existing_slides = glob("$media_dir/s/hires/*");
679                 my $nr = $#existing_slides + 2;
680
681                 push @subtitles, [ $pos, $pos, "slide:$nr shot:$pos" ];
682
683                 warn "slide $nr from video $pos file $shot\n";
684                 save_subtitles;
685         } else {
686                 warn "IGNORE $line";
687         }
688
689 }
690
691 push @to_mplayer, "get_property $_\n" foreach grep { ! $prop->{$_} } ( qw/metadata video_codec video_bitrate width height fps length/ );
692
693 my $t = time;
694 my $line;
695
696 while ( 1 ) {
697
698         my $dt = time - $t;
699         if ( abs($dt) > 0.7 ) {
700 warn "dt $dt\n";
701                 $slides->show( $pos );
702                 $t = time;
703         }
704
705         foreach my $fd ( $select->can_read(0.1) ) {
706                 if ( $fd == $from_mplayer ) {
707                         my $ch;
708                         sysread $from_mplayer, $ch, 1;
709                         if ( $ch =~ m{[\n\r]} ) {
710                                 from_mplayer $line;
711                                 $line = '';
712                         } else {
713                                 $line .= $ch;
714                         }
715                 } else {
716                         warn "unknown fd $fd";
717                 }
718         }
719
720         if ( my $cmd = shift @to_mplayer ) {
721                 warn ">>>> $cmd\n";
722                 print $to_mplayer $cmd;
723         }
724
725 }
726