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