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