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