make snapshots from mplayer partially work
[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 @slides_hires = glob 'www/media/s/hires/p*.jpg';
168         @slides_hires    = glob 'shot*.png' unless @slides_hires;
169         my $factor_s_path;
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                 $factor_s_path->{$factor} = $path;
177
178                 if ( ! -d $path ) {
179                         mkdir $path;
180                         warn "created $path\n";
181
182                         foreach my $hires ( @slides_hires ) {
183
184                                 my $file = $hires;
185                                 $file =~ s{^.+/(p\d+\.\w)}{$path/$1};
186
187                                 my $im = Imager->new( file => $hires );
188                                 $im->scale( xpixels => $w, ypixels => $h, type => 'min' )->write( file => $file );
189                                 warn "resized $file ", -s $file, " bytes\n";
190                         }
191                 }
192
193         }
194
195         my ( $slide_width, $slide_height );
196
197         my $im = Imager->new( file => $factor_s_path->{ 1 } . '/p001.jpg"')
198                         || Imager->new( file => "shot0001.png" ) # from mplayer [s]
199                         ;
200
201         if ( $im ) {
202                 $slide_width  = $im->getwidth  / $slide_factor;
203                 $slide_height = $im->getheight / $slide_factor;
204         } else {
205                 warn "can't find first slide default to 1/$slide_factor of video size\n";
206                 $slide_width  = $prop->{width}  / $slide_factor;
207                 $slide_height = $prop->{height} / $slide_factor;
208         }
209
210         my $html5tv = {
211                 sync => $sync,
212                 video => $prop,
213                 slide => {
214                         width => $slide_width,
215                         height => $slide_height,
216                 },
217         };
218
219         $html5tv->{video_tags} =
220                 join("\n",
221                         map {
222                                 my $s = $_;
223                                 my $id = $s->[3];
224                                 $id =~ s{\W+}{_}g;
225
226                                 push @{ $html5tv->{sync}->{customEvents} }, {
227                                         startTime => $s->[0],
228                                         endTime   => $s->[1],
229                                         action    => 'additional_video',
230                                         args => {
231                                                 id => $id,
232                                                 title => $s->[2],
233                                                 description => $s->[2],
234                                                 src => "media/s/$s->[3]/00000001.jpg",
235                                                 href => '',
236                                         },
237                                 };
238
239                                 qq|
240                                         <video id="$id" style="display: none" controls="controls" width="$html5tv->{video}->{width}px" height="$html5tv->{video}->{height}px">
241                                         <source src="media/$_->[3]" />
242                                         </video>
243                                 |
244                         } @videos
245                 )
246         ;
247
248         sub customEvents_sorted {
249
250                 if ( ref $html5tv->{sync}->{customEvents} ne 'ARRAY' ) {
251                         my $max = 
252                         warn "ERROR: no slide markers [1] .. [", scalar @slides_hires, "] in subtitles\n";
253                         return;
254                 }
255
256                 sort { $a->{startTime} <=> $b->{startTime} }
257                 @{ $html5tv->{sync}->{customEvents} }
258         }
259
260         my $index = 1;
261
262         $_->{args}->{index} = $index++ foreach customEvents_sorted;
263
264         warn "last customEvent $index\n";
265
266         $html5tv->{subtitles_table}
267                 = qq|<table id="subtitles">|
268                 . join("\n",
269                         map { qq|
270                                 <tr id="sub_$_->{index}">
271                                         <td class="seek_video">$_->{startTime}</td>
272                                         <td class="seek_video">$_->{endTime}</td>
273                                         <td>$_->{args}->{title}</td>
274                                 </tr>
275                         | }
276                         customEvents_sorted
277                 )
278                 . qq|</table><a href="media/video.srt">download subtitles</a>|
279                 ;
280
281         my $hcalendar = '<div style="color: red">Create <tt>hcalendar.html</tt> to fill this space</div>';
282         my $hcal_path = 'www/media/hcalendar.html';
283         if ( -e $hcal_path ) {
284                 $html5tv->{hcalendar} = read_file $hcal_path;
285                 my $tree = HTML::TreeBuilder->new;
286                 $tree->parse_file($hcal_path);
287                 if ( my $vevent = $tree->look_down( class => 'vevent' ) ) {
288                         $html5tv->{title} = $vevent->look_down( class=> 'summary' )->as_trimmed_text;
289                 }
290         }
291
292         warn "# html5tv ", dump $html5tv;
293
294         my $sync_path = 'www/media/video.js';
295         write_file $sync_path, "var html5tv = " . to_json($html5tv) . " ;\n";
296         warn "sync $sync_path ", -s $sync_path, " bytes\n";
297
298         my $html = read_file 'www/tv.html';
299         $html =~ s|{([^}]+)}|my $n = $1; $n =~ s(\.)(}->{)g; eval "\$html5tv->{$n}"|egs ||
300                 warn "no interpolation in template!";
301
302         write_file 'www/media.html', $html;
303
304         my $carousel_width = $prop->{width} + $slide_width - 80;
305         $carousel_width -= $carousel_width % ( $slide_width + 6 ); # round to full slide
306         my $carousel_height =   $slide_height + 2;
307
308         write_file 'www/media/video.css', qq|
309
310 .jcarousel-skin-ie7 .jcarousel-container-horizontal,
311 .jcarousel-skin-ie7 .jcarousel-clip-horizontal {
312         width: ${carousel_width}px;
313         height: ${carousel_height}px;
314 }
315
316 .jcarousel-skin-ie7 .jcarousel-item {
317         width: ${slide_width}px;
318         height: ${slide_height}px;
319         margin: 0 2px 0 2px;
320 }
321
322 .active {
323         background-color: #ffc;
324 }
325
326 div#videoContainer {
327         width: $prop->{width}px;
328         height: $prop->{height}px;
329         font-family: Arial, Helvetica, sans-serif;
330         margin: 0 10px 0px 0;
331         position: relative;
332         display: inline;
333 }
334
335
336 div#subtitle {
337         bottom: 24px;
338         color: white;
339         font-size: 100%;
340         font-weight: bold;
341         height: 22px;
342         line-height: 1em;
343         margin: 0  0 0 0;
344         padding: 1px 10px 5px 10px ;
345         position: absolute;
346         text-align: center;
347         width: $html5tv->{video}->{width}px;
348 }
349
350
351
352 .jcarousel-skin-ie7 .jcarousel-item img:hover {
353 //      border-color: #555 !important;
354 }
355
356 .jcarousel-skin-ie7 .jcarousel-item:hover div.thumbnailOverlay {
357         visibility: visible !important;
358 }
359
360 .jcarousel-skin-ie7 .jcarousel-item div.thumbnailOverlay {
361         background: black;
362         bottom: 1px;
363         color: #00EEFF;
364         visibility: hidden;
365         font-size: 10px;
366         font-family: Arial, Verdana;
367         font-weight: bold;
368         line-height: 0.9em;
369         opacity: 0.5;
370         position: absolute;
371         text-align: center;
372         z-index: 10;
373         padding: 2px 0 2px 0;
374         width: ${slide_width}px;
375 }
376
377 .seek_video {
378         text-align: right;
379         font-family: monospace;
380 }
381
382         |;
383
384         return 1;
385 }
386
387
388 sub t_srt {
389         my $t = shift;
390         my $hh = int( $t / 3600 );
391         $t -= $hh * 3600;
392         my $mm = int( $t / 60 );
393         $t -= $mm * 60;
394         my $srt = sprintf "%02d:%02d:%04.1f", $hh, $mm, $t;
395         $srt =~ s{\.}{,};
396         return $srt;
397 }
398
399 sub save_subtitles {
400
401         html5tv || return;
402
403         my $nr = 0;
404         my $srt = "\n";
405         foreach my $s ( @subtitles ) {
406                 $srt .= $nr++ . "\n"
407                         . t_srt( $s->[0] ) . " --> " . t_srt( $s->[1] ) . "\n"
408                         . $s->[2] . "\n\n"
409                         ;
410         }
411         warn $srt;
412
413         write_file $subtitles, $srt;
414         YAML::DumpFile "$subtitles.yaml", sort { $a->[0] <=> $b->[0] } @subtitles;
415
416         print $to_mplayer "sub_remove\n";
417         print $to_mplayer qq|sub_load "$subtitles"\n|;
418         print $to_mplayer "sub_select 1\n";
419 }
420
421 sub load_subtitles {
422         @subtitles = YAML::LoadFile "$subtitles.yaml";
423         warn "subtitles ", dump @subtitles;
424         save_subtitles;
425 }
426
427 load_subtitles if -e "$subtitles.yaml";
428
429 sub edit_subtitles {
430         print $to_mplayer qq|pause\n|;
431         focus_term;
432         system( qq|vi "$subtitles.yaml"| ) == 0 and load_subtitles;
433         focus_mplayer;
434 }
435
436 sub add_subtitle {
437         print $to_mplayer qq|pause\n|;
438
439         focus_term;
440
441         warn "subtitles ", dump( @subtitles );
442         print "## ";
443         my $line = <STDIN>;
444         $subtitles[ $#subtitles ]->[2] = $line if defined $line;
445
446         save_subtitles;
447
448         focus_mplayer;
449
450         preroll $subtitles[ $#subtitles ]->[0], $line;
451 }
452
453 sub time_pos {
454         print $to_mplayer qq|get_property time_pos\n|;
455         my $pos = <$from_mplayer>;
456         if ( $pos =~ m{^ANS_time_pos=(\d+\.\d+)} ) {
457                 warn "# time_pos $1\n";
458                 return $1;
459         }
460 }
461
462 sub sub_fmt {
463         my $s = shift;
464         sprintf "%1.5f - %1.5f %s %s\n", @$s, join(' | ',@_);
465 }
466
467 sub prev_subtitle {
468         my $pos = time_pos;
469         my $s = ( grep { $_->[0] < $pos } @subtitles )[0];
470         warn "<<<< subtitle ", sub_fmt $s;
471         preroll $s->[0], $s->[2];
472 #       print $to_mplayer "set_property time_pos $s->[0]\n";
473 }
474
475 sub next_subtitle {
476         my $pos = time_pos + $preroll;
477         my $s = ( grep { $_->[0] > $pos } @subtitles )[0];
478         warn ">>>> subtitle ", sub_fmt $s;
479         preroll $s->[0], $s->[2];
480 #       print $to_mplayer "set_property time_pos $s->[0]\n";
481 }
482
483 sub current_subtitle {
484         my $callback = shift;
485         my $pos = time_pos;
486         my $visible;
487         foreach my $nr ( 0 .. $#subtitles ) {
488                 my $s = $subtitles[$nr];
489                 if ( $s->[0] <= $pos && $s->[1] >= $pos ) {
490                         warn sub_fmt $s, $pos;
491                         $visible = $nr;
492                         $callback->( $visible, $pos ) if $callback;
493                         return ( $visible, $pos );
494                 }
495         }
496         warn "# $pos no visible subtitle\n";
497 }
498
499 sub move_subtitle {
500         my $offset = shift;
501         current_subtitle( sub {
502                 my ( $nr, $pos ) = @_;
503                 my $new_start = $subtitles[$nr]->[0] += $offset;
504                 warn "subtitle $nr $pos $offset $new_start\n";
505                 save_subtitles;
506                 preroll $new_start, "$pos $offset $new_start";
507         } );
508 }
509
510
511
512 # XXX main epool loop
513
514 load_movie;
515
516 while ( my $events = epoll_wait($epfd, 10, 1000) ) { # Max 10 events returned, 1s timeout
517
518         warn "no events" unless $events;
519
520         foreach my $e ( @$events ) {
521 #               warn "# event: ", dump($e), $/;
522
523                 my $fileno = $e->[0];
524
525                 if ( $fileno == fileno STDIN ) {
526                         my $chr;
527                         sysread STDIN, $chr, 1;
528                         print $chr;
529                 } elsif ( $fileno == fileno $from_mplayer ) {
530                         my $chr;
531                         sysread $from_mplayer, $chr, 1;
532                         print $chr;
533
534                         if ( $chr =~ m{[\n\r]} ) {
535
536                                 exit if $line =~ m{Exiting};
537
538                                 if ( $line =~ m{ANS_(\w+)=(\S+)} ) {
539                                         $prop->{$1} = $2;
540                                         warn "prop $1 = $2\n";
541                                 } elsif ( $line =~ m{No bind found for key '(.+)'} ) {
542
543                                         # XXX keyboard shortcuts
544
545                                           $1 eq 'c'  ? repl
546                                         : $1 eq ','  ? add_subtitle
547                                         : $1 eq 'F1' ? prev_subtitle
548                                         : $1 eq 'F2' ? move_subtitle( -0.3 )
549                                         : $1 eq 'F3' ? move_subtitle( +0.3 )
550                                         : $1 eq 'F4' ? next_subtitle
551                                         : $1 eq 'F5' ? save_subtitles
552                                         : $1 eq 'F9' ? add_subtitle
553                                         : $1 eq 'F12' ? edit_subtitles
554                                         : warn "CUSTOM $1\n"
555                                         ;
556
557                                 } elsif ( $line =~ m{EDL}i ) {
558
559                                         print $to_mplayer qq|osd_show_text "$line"\n|;
560
561                                         if ( my $pos = time_pos ) {
562                                                 if ( $line =~ m{start}i ) {
563                                                         push @subtitles, [ $pos, $pos, '-' ];
564                                                 } else {
565                                                         $subtitles[ $#subtitles ]->[1] = $pos;
566                                                 }
567                                         }
568                                 }
569
570                                 $line = '';
571                         } else {
572                                 $line .= $chr;
573                         }
574
575
576                 } elsif ( $fileno == fileno $to_mplayer ) {
577 #                       warn "command";
578                 } else {
579                         die "invalid fileno $fileno";
580                 }
581         }
582
583 }
584