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