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