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