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