source: extensions/gsdl-video/trunk/perllib/plugins/VideoPlugin.pm@ 18425

Last change on this file since 18425 was 18425, checked in by davidb, 15 years ago

Video extension to Greenstone

File size: 32.1 KB
Line 
1########################################################################
2#
3# VideoPlug.pm -- plugin for processing video largely based on ImagePlug
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 1999 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26package VideoPlugin;
27
28use strict;
29no strict 'refs'; # allow filehandles to be variables and viceversa
30
31use videoconvert;
32use XMLParser;
33use gsprintf;
34
35use BasePlugin;
36
37sub BEGIN {
38 @VideoPlugin::ISA = ('BasePlugin');
39
40 if (!defined $ENV{'GEXTVIDEO'}) {
41 print STDERR "Warning: Greenstone Video extension not detected.\n";
42 }
43
44}
45
46my $arguments =
47 [ { 'name' => "process_exp",
48 'desc' => "{BasePlugin.process_exp}",
49 'type' => "regexp",
50 'deft' => &get_default_process_exp(),
51 'reqd' => "no" },
52 { 'name' => "noscaleup",
53 'desc' => "{VideoPlug.noscaleup}",
54 'type' => "flag",
55 'reqd' => "no" },
56 { 'name' => "use_ascii_only_filenames",
57 'desc' => "{VideoPlug.use_ascii_only_filenames}",
58 'type' => "flag",
59 'reqd' => "no" },
60 { 'name' => "video_excerpt_duration",
61 'desc' => "{VideoPlug.video_excerpt_duration}",
62 'type' => "string",
63 'deft' => "",
64 'reqd' => "no" },
65 { 'name' => "extractthumbnail",
66 'desc' => "{VideoPlug.extractthumbnail}",
67 'type' => "flag",
68 'deft' => "0",
69 'reqd' => "no" },
70 { 'name' => "thumbnailsize",
71 'desc' => "{VideoPlug.thumbnailsize}",
72 'type' => "int",
73 'deft' => "100",
74 'range' => "1,",
75 'reqd' => "no" },
76 { 'name' => "thumbnailtype",
77 'desc' => "{VideoPlug.thumbnailtype}",
78 'type' => "string",
79 'deft' => "jpeg",
80 'reqd' => "no" },
81 { 'name' => "extractscreenview",
82 'desc' => "{VideoPlug.extractscreenview}",
83 'type' => "flag",
84 'deft' => "0",
85 'reqd' => "no" },
86 { 'name' => "screenviewsize",
87 'desc' => "{VideoPlug.screenviewsize}",
88 'type' => "int",
89 'deft' => "0",
90 'range' => "1,",
91 'reqd' => "no" },
92 { 'name' => "screenviewtype",
93 'desc' => "{VideoPlug.screenviewtype}",
94 'type' => "string",
95 'deft' => "jpg",
96 'reqd' => "no" },
97 { 'name' => "converttotype",
98 'desc' => "{VideoPlug.converttotype}",
99 'type' => "string",
100 'deft' => "",
101 'reqd' => "no" },
102 { 'name' => "converttosize",
103 'desc' => "{VideoPlug.converttosize}",
104 'type' => "int",
105 'deft' => "",
106## 'deft' => "352",
107 'reqd' => "no" },
108 { 'name' => "converttobitrate",
109 'desc' => "{VideoPlug.converttobitrate}",
110 'type' => "string",
111 'deft' => "200k",
112 'reqd' => "no" },
113 { 'name' => "extractkeyframes",
114 'desc' => "{VideoPlug.extractkeyframes}",
115 'type' => "flag",
116 'deft' => "0",
117 'reqd' => "no" },
118 { 'name' => "enablestreaming",
119 'desc' => "{VideoPlug.enablestreaming}",
120 'type' => "flag",
121 'deft' => "1",
122 'reqd' => "no" },
123 { 'name' => "streamingsize",
124 'desc' => "{VideoPlug.streamingsize}",
125 'type' => "int",
126 'deft' => "352",
127 'reqd' => "no" },
128 { 'name' => "streamingbitrate",
129 'desc' => "{VideoPlug.streamingbitrate}",
130 'type' => "string",
131 'deft' => "200k",
132 'reqd' => "no" },
133 { 'name' => "minimumsize",
134 'desc' => "{VideoPlug.minimumsize}",
135 'type' => "int",
136 'deft' => "100",
137 'range' => "1,",
138 'reqd' => "no" } ];
139
140my $options = { 'name' => "VideoPlug",
141 'desc' => "{VideoPlug.desc}",
142 'abstract' => "no",
143 'inherits' => "yes",
144 'args' => $arguments };
145
146
147my ($self);
148
149sub new {
150 my ($class) = shift (@_);
151 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
152 push(@$pluginlist, $class);
153
154 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
155 push(@{$hashArgOptLists->{"OptList"}},$options);
156
157 $self = new BasePlugin($pluginlist, $inputargs, $hashArgOptLists);
158
159 # Check that ffmpeg is installed and available on the path (except for Windows 95/98)
160 # This test is "inherited" from ImagePlugin where ImageMagick support
161 # for building cannot be used on these two versions of Windows as they
162 # do not have enough flexablity in the use of stdout and stderr to
163 # support how our code works. It seems reasonable to assume the
164 # same is true for VideoPlugin work using ffmpeg.
165
166 if (($ENV{'GSDLOS'} ne "windows" || Win32::IsWinNT())) {
167
168 my $result = `ffmpeg -h 2>&1`;
169
170 if (!defined $result || $result !~ m/^FFmpeg version/) {
171 $self->{'ffmpeg_not_installed'} = 1;
172 print STDERR $result;
173 }
174 }
175
176
177 # create XML::Parser object for parsing metadata.xml files
178 my $parser;
179 if ($]<5.008) {
180 # Perl 5.6
181 $parser = new XML::Parser('Style' => 'Stream',
182 'Handlers' => {'Char' => \&Char,
183 'Doctype' => \&Doctype
184 });
185 }
186 else {
187 # Perl 5.8
188 $parser = new XML::Parser('Style' => 'Stream',
189 'ProtocolEncoding' => 'ISO-8859-1',
190 'Handlers' => {'Char' => \&Char,
191 'Doctype' => \&Doctype
192 });
193 }
194
195 $self->{'parser'} = $parser;
196
197
198 return bless $self, $class;
199}
200
201
202sub init {
203 my $self = shift (@_);
204 my ($verbosity, $outhandle, $failhandle) = @_;
205
206 $self->SUPER::init(@_);
207 ## $self->ImageConverter::init(); # ****** VideoConverter::init ??
208}
209
210
211sub get_default_process_exp {
212 my $self = shift (@_);
213
214 return q^\.(?i)(mpe?g|flv|qt|vob|avi)$^;
215}
216
217# this makes no sense for image
218sub block_cover_image
219{
220 my $self =shift (@_);
221 my ($filename) = @_;
222
223 return;
224}
225
226
227
228
229# Create the keyframes, thumbnail and screenview images, and discover
230# the Video's size, width, and height using the ffmpeg utility.
231
232sub run_convert {
233 my $self = shift (@_);
234 my $base_dir = shift (@_);
235 my $filename = shift (@_); # filename with full path
236 my $file = shift (@_); # filename without path
237 my $doc_obj = shift (@_);
238
239 my $section = $doc_obj->get_top_section();
240
241 my $verbosity = $self->{'verbosity'};
242 my $outhandle = $self->{'outhandle'};
243
244 # check the filename is okay
245 return 0 if ($file eq "" || $filename eq "");
246
247 my $minimumsize = $self->{'minimumsize'};
248 if (defined $minimumsize && (-s $filename < $minimumsize)) {
249 print $outhandle "VideoPlug: \"$filename\" too small, skipping\n"
250 if ($verbosity > 1);
251 }
252
253 my ($video_type, $video_width, $video_height, $video_duration, $video_size,
254 $vcodec,$vfps,$atype,$afreq,$achan,$arate)
255 = &videoconvert::identify($filename, $outhandle, $verbosity);
256
257 if ($vfps eq "unknown") {
258 print $outhandle "Unknown framerate, defaulting to 25 frames per second.\n";
259 $vfps = 25;
260 }
261
262 my ($dur_hour,$dur_min,$dur_sec)
263 = ($video_duration =~ m/(\d+):(\d+):(\d+\.\d+)/);
264 my $total_dur_secs = $dur_hour*3600 + $dur_min*60 + $dur_sec;
265
266 $self->{'video-fps'} = $vfps;
267 $self->{'num-total-frames'} = $total_dur_secs * $vfps;
268
269 # Convert the video to a new type (if required).
270 my $converttotype = $self->{'converttotype'};
271 my $converttosize = $self->{'converttosize'};
272
273 # shorten duration prcessed for experimentation purposes
274 my $exp_duration = undef;
275
276 my $video_excerpt_duration = $self->{'video_excerpt_duration'};
277
278 if ((defined $video_excerpt_duration) && ($video_excerpt_duration ne "")) {
279 $exp_duration = $video_excerpt_duration;
280 my ($hh,$mm,$ss,$ms) = ($exp_duration =~ m/^(\d\d):(\d\d):(\d\d)\.?(\d\d)?/);
281 my $excerpt_dur_in_secs = $hh * 3600 + $mm * 60 + $ss;
282
283 if ($excerpt_dur_in_secs < $total_dur_secs) {
284 $self->{'num-total-frames'} = $excerpt_dur_in_secs * $vfps; # override calculation for full length duration
285 }
286 else {
287 # clip is already shorter than requested video excerpt duration
288 # set exp_duration back to undefined
289 $exp_duration = undef;
290 }
291 }
292
293
294 if (defined $exp_duration)
295 {
296 print $outhandle "Only encoding first $exp_duration of video.\n";
297 $self->{'exp_duration'} = $exp_duration;
298 }
299
300 my $ascii_only_filenames = $self->{'use_ascii_only_filenames'};
301 my $videoconvert
302 = new videoconvert($base_dir,$filename,$verbosity,$outhandle,$exp_duration,$ascii_only_filenames);
303 $self->{'videoconvert'} = $videoconvert;
304
305 my $originalfilename = undef;
306 my $type = "unknown";
307
308 my $output_dir = $videoconvert->{'cached_dir'};
309 my $ivideo_root = $videoconvert->{'file_root'};
310
311 my $convertto_regenerated = 0;
312 if (($converttotype ne "" && $filename =~ m/$converttotype$/i) ||
313 (($converttosize ne "" && $converttosize ne $video_width) || ($converttosize ne "" && $converttosize ne $video_height))) {
314 if ($converttotype eq "") {
315 # in this block because the video width x height different to original
316 # => set (for this call to run_convert only) converttotype
317 # to input file extension
318 ($converttotype) = ($filename =~ m/\.(.*?)$/);
319 }
320
321 $originalfilename = $filename;
322
323 $file = "$ivideo_root.$converttotype";
324 $filename = &util::filename_cat($output_dir,$file);
325
326 my $s_opt = $videoconvert->optional_frame_scale($converttosize,$video_width,$video_height);
327 my $exp_duration = $self->{'exp_duration'};
328 my $t_opt = (defined $exp_duration) ? "-t $exp_duration" : "";
329
330 my $main_opts = "-y $t_opt $s_opt";
331
332
333 my $convertto_command = "ffmpeg $main_opts -i \"$originalfilename\"";
334 $convertto_command .= " -ar 22050" if ($converttotype eq "flv");
335 $convertto_command .= " -y \"$filename\"";
336
337 my $convertto_result;
338 my $convertto_error;
339
340 my $convertto_options = { @{$videoconvert->{'ffmpeg_monitor'}},
341 'message_prefix' => "Convert to",
342 'message' => "Converting video to $converttotype" };
343
344 ($convertto_regenerated,$convertto_result,$convertto_error)
345 = $videoconvert->run_cached_general_cmd($convertto_command,$filename,$convertto_options);
346
347 $type = $converttotype;
348 }
349
350
351 # Add the video metadata
352
353 my $file_unicode = pack("U0C*", map { ord($_) } split(//,$file)); # force explicitly to unicode
354
355 $file_unicode =~ s/\x{2018}|\x{2019}|\x{201C}|\x{201D}//g; # remove smart quotes as cause problem in URL for video server
356 $file_unicode =~ s/\x{2013}/\-/g; # change en-dash to '-' as again causes problems for video server
357
358## print STDERR "**** file metadata = ", &gsprintf::debug_unicode_string($file_unicode), "\n";
359
360
361 # split filename on char if specified
362 if ($file_unicode =~ m/\-/) {
363
364 my @file_split = split(/\s*\-\s*/,$file_unicode);
365 my $creator = shift @file_split;
366 my $title = shift @file_split;
367
368 $title =~ s/\..*?$//;
369 $title =~ s/^(.)/\u$1/;
370
371 $doc_obj->add_utf8_metadata($section,"Title",$title);
372
373 my @creator_split = split(/\s+and\s+/,$creator);
374 foreach my $c (@creator_split) {
375 $doc_obj->add_utf8_metadata($section,"Creator",$c);
376 }
377 }
378
379 $file = $file_unicode;
380 my $filemeta = $self->filename_to_utf8_metadata($file);
381 my $filemeta_url_safe = $videoconvert->url_safe($filemeta);
382
383 $doc_obj->add_utf8_metadata ($section, "Video", $filemeta_url_safe);
384
385 # Also want to set filename as 'Source' metadata to be
386 # consistent with other plugins
387 $doc_obj->add_utf8_metadata ($section, "Source", $filemeta_url_safe);
388
389
390 if ($video_type ne " ") {
391 $type = $video_type;
392 }
393
394 $doc_obj->add_metadata ($section, "FileFormat", $type);
395 $doc_obj->add_metadata ($section, "FileSize", $video_size);
396
397 $doc_obj->add_metadata ($section, "VideoType", $video_type);
398 $doc_obj->add_metadata ($section, "VideoWidth", $video_width);
399 $doc_obj->add_metadata ($section, "VideoHeight", $video_height);
400 $doc_obj->add_metadata ($section, "VideoDuration", $video_duration);
401 $doc_obj->add_metadata ($section, "VideoSize", $video_size);
402
403 $doc_obj->add_metadata ($section, "VideoCodec", $vcodec);
404 $doc_obj->add_metadata ($section, "VideoFPS", $vfps);
405
406 $doc_obj->add_metadata ($section, "AudioType", $atype);
407 $doc_obj->add_metadata ($section, "AudioFreq", $afreq);
408 $doc_obj->add_metadata ($section, "AudioChannels", $achan);
409 $doc_obj->add_metadata ($section, "AudioRate", $arate);
410
411 $doc_obj->add_utf8_metadata ($section, "srclink",
412 "<a href=\"_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/[Video]\">");
413 $doc_obj->add_utf8_metadata ($section, "/srclink", "</a>");
414 $doc_obj->add_metadata ($section, "srcicon", "[VideoType]");
415
416 # Add the image as an associated file
417 $doc_obj->associate_file($filename,$file,"video/$type",$section);
418
419
420 if ($self->{'extractkeyframes'}) {
421 # Generate the keyframes with ffmpeg and hive
422 my ($keyframe_cmd,$okeyframe_filename) = $videoconvert->keyframe_cmd($originalfilename || $filename);
423
424 my $keyframe_options = { @{$videoconvert->{'ffmpeg_monitor'}},
425 'message_prefix' => "Keyframe",
426 'message' => "Extracting keyframes" };
427
428 $videoconvert->run_cached_general_cmd($keyframe_cmd,$okeyframe_filename,$keyframe_options);
429 $videoconvert->parse_shot_xml($self);
430 $videoconvert->associate_keyframes($doc_obj,$section,$self);
431 }
432
433 my $streamable_regenerated = 0;
434 my $optionally_run_general_cmd
435 = ($convertto_regenerated) ? "regenerate_general_cmd" : "run_cached_general_cmd";
436
437 if ($self->{'enablestreaming'}) {
438 # Generate the Flash FLV format for streaming purposes
439
440 my $streaming_bitrate = $self->{'streamingbitrate'};
441 my $streaming_size = $self->{'streamingsize'};
442
443 my $streaming_quality = "high";
444
445 my ($stream_cmd,$oflash_filename,$oflash_file)
446 = $videoconvert->stream_cmd($originalfilename || $filename,
447 $video_width,$video_height,
448 $streaming_quality,
449 $streaming_bitrate, $streaming_size);
450
451
452 my $streamable_options = { @{$videoconvert->{'ffmpeg_monitor'}},
453 'message_prefix' => "Stream",
454 'message' => "Generating streamable video: $oflash_file" };
455
456 my $streamable_result;
457 my $streamable_had_error;
458 ($streamable_regenerated,$streamable_result,$streamable_had_error)
459 = $videoconvert->$optionally_run_general_cmd($stream_cmd,$oflash_filename,$streamable_options);
460
461 if (!$streamable_had_error) {
462 my ($streamseekable_cmd,$ostreamseekable_filename) = $videoconvert->streamseekable_cmd($oflash_filename);
463
464 my $streamseekable_options = { @{$videoconvert->{'flvtool2_monitor'}},
465 'message_prefix' => "Stream Seekable",
466 'message' => "Reprocessing video stream to be seekable by timeline: $oflash_file" };
467
468 if ($streamable_regenerated) {
469 $videoconvert->run_general_cmd($streamseekable_cmd,$streamseekable_options);
470 }
471
472 my $streamable_url = $oflash_file;
473 ## $streamable_url =~ s/ /%20/g;
474 my $streamable_url_safe = $videoconvert->url_safe($streamable_url);
475
476 $doc_obj->add_utf8_metadata ($section, "streamablevideo", $streamable_url_safe);
477 $doc_obj->associate_file($oflash_filename,$oflash_file,"video/flash",
478 $section);
479 }
480
481 my $video_width = $doc_obj->get_metadata_element($section,"VideoWidth");
482 my $video_height = $doc_obj->get_metadata_element($section,"VideoHeight");
483
484 #
485 # FlowPlayer.swf height+22 pixels
486 # FlowPlayerBlack.swf height+16 pixels
487 # FlowPlayerThermo.swf height+16 pixels
488 # FlowPlayerWhite.swf height+26 pixels
489 my $flashwidth = $video_width;
490 my $flashheight = $video_height + 22;
491 if ($self->{'extractkeyframes'}) {
492 $flashheight += 100;
493 }
494 $doc_obj->add_metadata ($section, "flashwidth", $flashwidth);
495 $doc_obj->add_metadata ($section, "flashheight", $flashheight);
496
497 my $video_server = $ENV{'GEXT_VIDEO_SERVER'};
498 my $video_prefix = $ENV{'GEXT_VIDEO_PREFIX'};
499 my $base_url = "$video_server$video_prefix/collect/[collection]/index/assoc/[assocfilepath]/";
500 my $base_url_safe = $videoconvert->url_safe($base_url);
501 $doc_obj->add_utf8_metadata ($section, "baseurl",$base_url_safe);
502
503 $self->{'oflash_file'} = $oflash_file;
504 $self->{'oflash_filename'} = $oflash_filename;
505 }
506
507
508 # Make the thumbnail image
509 my $thumbnailsize = $self->{'thumbnailsize'} || 100;
510 my $thumbnailtype = $self->{'thumbnailtype'} || 'jpg';
511
512
513 my $thumbnailfile = &util::filename_cat($output_dir,"$ivideo_root.$thumbnailtype");
514
515
516 if ($self->{'extractthumbnail'}) {
517 # Generate the thumbnail with convert, a la ImagePlug
518 my ($thumb_cmd ,$othumb_filename)
519 = $videoconvert->keyframe_thumbnail_cmd($filename,$thumbnailfile,$thumbnailsize);
520
521 my $thumb_options = { 'verbosity' => $verbosity,
522 'outhandle' => $outhandle,
523 'message_prefix' => "Thumbnail",
524 'message' => "Generating thumbnail" };
525
526 my ($thumb_regenerated,$thumb_result,$thumb_had_error)
527 = $videoconvert->$optionally_run_general_cmd($thumb_cmd,$thumbnailfile,$thumb_options);
528
529 # Add the thumbnail as an associated file ...
530 if (-e "$thumbnailfile") {
531 $doc_obj->associate_file("$thumbnailfile", "thumbnail.$thumbnailtype",
532 "image/$thumbnailtype",$section);
533 $doc_obj->add_metadata ($section, "ThumbType", $thumbnailtype);
534 $doc_obj->add_metadata ($section, "Thumb", "thumbnail.$thumbnailtype");
535
536 $doc_obj->add_utf8_metadata ($section, "thumbicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/[Thumb]\" width=[ThumbWidth] height=[ThumbHeight]>");
537### $doc_obj->add_utf8_metadata ($section, "thumbicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/[Thumb]\">");
538 }
539
540 # Extract Thumnail metadata from convert output
541 if ($thumb_result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
542 $doc_obj->add_metadata ($section, "ThumbWidth", $1);
543 $doc_obj->add_metadata ($section, "ThumbHeight", $2);
544 }
545 else {
546 # Two reasons for getting to here:
547 # 1.thumbnail was generated by ffmpeg, not imagemagick convert
548 # 2.thumbnail was cached, so imagemagick convert was not run
549 # Either way, the solution is the same:
550 # => run "identify $thumbnailfile" and parse result
551
552 $thumb_result = `identify \"$thumbnailfile\"`;
553
554 if ($thumb_result =~ m/([0-9]+)x([0-9]+)/) {
555 $doc_obj->add_metadata ($section, "ThumbWidth", $1);
556 $doc_obj->add_metadata ($section, "ThumbHeight", $2);
557 }
558 }
559 }
560
561 if ($self->{'extractkeyframes'}) {
562
563 # Generate the mosaic with 'montage'
564 my $montagefile = &util::filename_cat($output_dir,"$ivideo_root\_montage.$thumbnailtype");
565
566 my ($montage_cmd,$omontage_filename)
567 = $videoconvert->keyframe_montage_cmd($filename,$montagefile);
568
569 my $montage_options = { 'message_prefix' => "Montage",
570 'message' => "Generating montage" };
571
572 my ($montage_result,$montage_had_error)
573 = $videoconvert->run_general_cmd($montage_cmd,$montage_options);
574
575 # Add the montage as an associated file ...
576 if (-e "$montagefile") {
577 $doc_obj->associate_file("$montagefile", "montage.$thumbnailtype",
578 "image/$thumbnailtype",$section);
579 $doc_obj->add_metadata ($section, "MontageType", $thumbnailtype);
580 $doc_obj->add_metadata ($section, "Montage", "montage.$thumbnailtype");
581
582 $doc_obj->add_utf8_metadata ($section, "montageicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/[Montage]\" >");
583 }
584 }
585
586
587
588 # Make a screen-sized version of the picture if requested
589 if ($self->{'extractscreenview'}) {
590
591 # To do: if the actual image smaller than the screenview size,
592 # we should use the original !
593
594 my $screenviewsize = $self->{'screenviewsize'};
595 my $screenviewtype = $self->{'screenviewtype'} || 'jpeg';
596 my $screenviewfilename = &util::filename_cat($output_dir,"$ivideo_root.$screenviewtype");
597
598 # make the screenview image
599
600 my ($screenview_cmd,$oscreenview_filename)
601 = $videoconvert->keyframe_thumbnail_cmd($filename,$screenviewfilename,$screenviewsize);
602
603 my $screenview_options = { 'message_prefix' => "Screenview",
604 'message' => "Generating screenview image" };
605
606 my ($result,$had_error)
607 = $videoconvert->run_general_cmd($screenview_cmd,$screenview_options);
608
609 # get screenview dimensions, size and type
610 if ($result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
611 $doc_obj->add_metadata ($section, "ScreenWidth", $1);
612 $doc_obj->add_metadata ($section, "ScreenHeight", $2);
613 }
614 else {
615 $doc_obj->add_metadata ($section, "ScreenWidth", $video_width);
616 $doc_obj->add_metadata ($section, "ScreenHeight", $video_height);
617 }
618
619 #add the screenview as an associated file ...
620 if (-e "$screenviewfilename") {
621 $doc_obj->associate_file("$screenviewfilename", "screenview.$screenviewtype",
622 "image/$screenviewtype",$section);
623 $doc_obj->add_metadata ($section, "ScreenType", $screenviewtype);
624 $doc_obj->add_metadata ($section, "Screen", "screenview.$screenviewtype");
625
626 $doc_obj->add_utf8_metadata ($section, "screenicon", "<img src=\"_httpprefix_/collect/[collection]/index/assoc/[assocfilepath]/[Screen]\" width=[ScreenWidth] height=[ScreenHeight]>");
627 } else {
628 print $outhandle "VideoPlug: couldn't find \"$screenviewfilename\"\n";
629 }
630 }
631
632 return $type;
633}
634
635
636
637
638
639# The VideoPlug read() function.
640# VideoPlug overrides read() because there is no need to read the actual
641# text of the file in, because the contents of the file is not text...
642#
643# Return number of files processed, undef if can't process
644# Note that $base_dir might be "" and that $file might
645# include directories
646
647sub read {
648 my $self = shift (@_);
649 my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;
650
651 my $outhandle = $self->{'outhandle'};
652
653 #check process and block exps, smart block, etc
654 my ($block_status,$filename) = $self->read_block(@_);
655 return $block_status if ((!defined $block_status) || ($block_status==0));
656
657 print STDERR "<Processing n='$file' p='VideoPlug'>\n" if ($gli);
658 print $outhandle "VideoPlug processing $file\n"
659 if $self->{'verbosity'} > 1;
660
661 # None of this works very well on Windows 95/98...
662 if ($ENV{'GSDLOS'} eq "windows" && !Win32::IsWinNT()) {
663 if ($gli) {
664 print STDERR "<ProcessingError n='$file' r='Windows 95/98 not supported'>\n";
665 }
666 print $outhandle "VideoPlug: Windows 95/98 not supported\n";
667 return -1;
668 }
669
670 # None of this is going to work very well without ffmpeg
671 if ($self->{'ffmpeg_not_installed'}) {
672 if ($gli) {
673 print STDERR "<ProcessingError n='$file' r='ffmpeg not installed'>\n";
674 }
675 print $outhandle "VideoPlug: ffmpeg not installed\n";
676 return -1;
677 }
678
679 #if there's a leading directory name, eat it...
680 $file =~ s/^.*[\/\\]//;
681
682 # create a new document
683 my $doc_obj = new doc ($filename, "indexed_doc");
684
685 $doc_obj->set_OIDtype ($processor->{'OIDtype'}, $processor->{'OIDmetadata'});
686 $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), "Plugin", "$self->{'plugin_type'}");
687
688 #run convert to get the thumbnail and extract size and type info
689 my $result = $self->run_convert($base_dir, $filename, $file, $doc_obj);
690
691 if (!defined $result)
692 {
693 if ($gli) {
694 print STDERR "<ProcessingError n='$file'>\n";
695 }
696 print $outhandle "VideoPlug: couldn't process \"$filename\"\n";
697 return -1; # error during processing
698 }
699
700 #create an empty text string so we don't break downstream plugins
701 my $text = &gsprintf::lookup_string("{BasePlugin.dummy_text}");
702 # include any metadata passed in from previous plugins
703 # note that this metadata is associated with the top level section
704 my $section = $doc_obj->get_top_section();
705 $self->extra_metadata ($doc_obj, $section, $metadata);
706
707 # do plugin specific processing of doc_obj
708 unless (defined ($self->process(\$text, $pluginfo, $base_dir, $file, $metadata, $doc_obj))) {
709 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
710 return -1;
711 }
712
713
714
715 # do any automatic metadata extraction
716 $self->auto_extract_metadata ($doc_obj);
717
718 # if we haven't found any Title so far, assign one
719 # this was shifted to here from inside read()
720 $self->title_fallback($doc_obj,$section,$file);
721
722 # add an OID
723 #
724 # Caveat: Don't want to hash on the source/converted video as typically
725 # prohibitively large => temporarily set source/converted filename
726 # to 'undef' (causes set_OID to hash on metadata and text stored within
727 # $doc_ob) then restore to previous value.
728 #
729 my $stored_gsdlsourcefilename = $doc_obj->get_source_filename();
730 $doc_obj->set_source_filename(undef);
731
732 $self->add_OID($doc_obj);
733
734 $doc_obj->set_source_filename($stored_gsdlsourcefilename);
735
736 $doc_obj->add_text($section, $text);
737
738 # process the document
739 $processor->process($doc_obj);
740
741 if (($self->{'enablestreaming'}) && ($self->{'extractkeyframes'})) {
742 my $oflash_filename = $self->{'oflash_filename'};
743 my $videoconvert = $self->{'videoconvert'};
744 my ($streamkeyframes_cmd,$ostreamkeyframes_filename)
745 = $videoconvert->streamkeyframes_cmd($oflash_filename,$doc_obj,$section);
746
747 my $verbosity = $self->{'verbosity'};
748
749 my $streamkeyframes_options = { @{$videoconvert->{'flvtool2_monitor'}},
750 'message_prefix' => "Stream Keyframes",
751 'message' => "Reprocessing video stream to add keyframes on timeline" };
752#### this used to be commented out!!!
753 $videoconvert->run_general_cmd($streamkeyframes_cmd,$streamkeyframes_options);
754 }
755
756
757 $self->{'num_processed'}++;
758
759 return 1;
760}
761
762# do plugin specific processing of doc_obj
763sub process {
764 my $self = shift (@_);
765 my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj) = @_;
766 my $outhandle = $self->{'outhandle'};
767
768 return 1;
769}
770
771
772
773sub output_distributed_keyframes
774{
775 my ($self) = shift @_;
776 my ($timeline,$num_dist_frames) = @_;
777
778 my $num_total_frames = $self->{'num-total-frames'};
779
780 my $frame_delta = $num_total_frames/$num_dist_frames;
781
782 my $closest_to = $frame_delta;
783 my $prev_t = 0;
784
785# print STDERR "*** num total frames = $num_total_frames\n";
786# print STDERR "*** frame delta = $frame_delta\n";
787
788 foreach my $curr_t (sort { $a <=> $b } keys %$timeline)
789 {
790# print STDERR "*** curr_t = $curr_t\n";
791
792 if ($curr_t>$closest_to) {
793 # decide if previous t (prev_t_ or current t (curr_t) is closest
794
795 my $timeline_rec;
796
797 my $prev_t_dist = $closest_to - $prev_t;
798 my $curr_t_dist = $curr_t - $closest_to;
799
800 if ($curr_t_dist <= $prev_t_dist)
801 {
802 $timeline_rec = $timeline->{$curr_t}
803 }
804 else
805 {
806 $timeline_rec = $timeline->{$prev_t}
807 }
808
809 my $name = $timeline_rec->{'name'};
810 my $timestamp = $timeline_rec->{'timestamp'};
811 my $thumb = $timeline_rec->{'thumb'};
812
813
814 print CUEOUT " <metatag event=\"onCuePoint\" overwrite=\"true\">\n";
815 print CUEOUT " <name>$name</name>\n";
816 print CUEOUT " <timestamp>$timestamp</timestamp>\n";
817 print CUEOUT " <parameters>\n";
818 print CUEOUT " <thumb>$thumb</thumb>\n";
819 print CUEOUT " </parameters>\n";
820 print CUEOUT " <type>navigation</type>\n";
821 print CUEOUT " </metatag>\n";
822
823# my $testtime = $timestamp+1000;
824# print CUEOUT " <metatag event=\"onCuePoint\" overwrite=\"true\">\n";
825# print CUEOUT " <name>Test $name</name>\n";
826# print CUEOUT " <timestamp>$testtime</timestamp>\n";
827# print CUEOUT " <parameters>\n";
828# print CUEOUT " <thumb>$thumb</thumb>\n";
829# print CUEOUT " <secnum>1</secnum>\n";
830# print CUEOUT " <subsecnum>0</subsecnum>\n";
831# print CUEOUT " </parameters>\n";
832# print CUEOUT " <type>event</type>\n";
833# print CUEOUT " </metatag>\n";
834
835 $closest_to += $frame_delta;
836 }
837 $prev_t = $curr_t;
838 }
839}
840
841
842
843sub Doctype {
844 my ($expat, $name, $sysid, $pubid, $internal) = @_;
845
846 # my $root_tag = $self->{'root_tag'};
847
848 if ($name !~ "seg") {
849 die "Root tag $name does not match expected <seg>";
850 }
851}
852
853sub StartTag {
854 my ($expat, $element) = @_;
855
856 my %attr = %_;
857
858 if ($element eq "seg") {
859 $self->{'keyframe_index'} = 0;
860 $self->{'keyframe_fnames'} = [];
861 $self->{'keyframe_timeline'} = {};
862
863 #$self->{'flowplayer_thumblist'} = "thumbs: \\[";
864
865 my $output_dir = $self->{'videoconvert'}->{'cached_dir'};
866 my $cue_filename = &util::filename_cat($output_dir,"on_cue.xml");
867
868 open(CUEOUT,">$cue_filename")
869 || die "Unable to open $cue_filename: $!\n";
870 print CUEOUT "<tags>\n";
871 }
872 elsif ($element eq "trans") {
873 my $trans_type = $attr{'type'};
874 my $pre_frame_num = $attr{'preFNum'};
875 my $post_frame_num = $attr{'postFNum'};
876
877 my $avg_frame_num = int(($pre_frame_num+$post_frame_num)/2.0)+1;
878
879 my $output_dir = $self->{'videoconvert'}->{'cached_dir'};
880 my $ivideo_root = $self->{'videoconvert'}->{'file_root'};
881
882 my $keyframe_index = $self->{'keyframe_index'};
883
884 my $fps = $self->{'video-fps'};
885
886 if ($keyframe_index==0)
887 {
888 # hive actually generates one extra keyframe at the start,
889 # which is half way between frame 0 and the frist pre_frame
890
891 my $thumb_file = sprintf("%s_%04d.jpg",$ivideo_root,$keyframe_index);
892 my $thumb_filename = &util::filename_cat($output_dir,$thumb_file);
893 push(@{$self->{'keyframe_fnames'}},$thumb_file);
894
895 my $half_frame_num = $pre_frame_num/2.0;
896 my $time_msec = ($half_frame_num / $fps) * 1000;
897
898# print CUEOUT " <metatag event=\"onCuePoint\" overwrite=\"true\">\n";
899# print CUEOUT " <name>Keyframe $keyframe_index</name>\n";
900# print CUEOUT " <timestamp>$time_msec</timestamp>\n";
901# print CUEOUT " <parameters>\n";
902# print CUEOUT " <thumb>$thumb_file</thumb>\n";
903# print CUEOUT " </parameters>\n";
904# print CUEOUT " <type>navigation</type>\n";
905# print CUEOUT " </metatag>\n";
906
907
908 my $timeline_rec = { 'name'=> "Keyframe $keyframe_index",
909 'keyframeindex' => $keyframe_index,
910 'timestamp' => $time_msec,
911 'thumb' => $thumb_file };
912
913 $self->{'keyframe_timeline'}->{$half_frame_num}=$timeline_rec;
914
915 }
916
917 $keyframe_index++;
918
919 my $thumb_file = sprintf("%s_%04d.jpg",$ivideo_root,$keyframe_index);
920 my $thumb_filename = &util::filename_cat($output_dir,$thumb_file);
921 push(@{$self->{'keyframe_fnames'}},$thumb_file);
922
923 my $time_msec = (($avg_frame_num) / $fps) * 1000;
924 my $time_sec = (($avg_frame_num)/ $fps);
925
926# print CUEOUT " <metatag event=\"onCuePoint\" overwrite=\"true\">\n";
927# print CUEOUT " <name>Keyframe $keyframe_index</name>\n";
928# print CUEOUT " <timestamp>$time_msec</timestamp>\n";
929# print CUEOUT " <parameters>\n";
930# print CUEOUT " <thumb>$thumb_file</thumb>\n";
931# print CUEOUT " </parameters>\n";
932# print CUEOUT " <type>navigation</type>\n";
933# print CUEOUT " </metatag>\n";
934
935
936 my $timeline_rec = { 'name'=> "Keyframe $keyframe_index",
937 'keyframeindex' => $keyframe_index,
938 'timestamp' => $time_msec,
939 'thumb' => $thumb_file };
940
941 $self->{'keyframe_timeline'}->{$avg_frame_num}=$timeline_rec;
942
943
944 # $self->{'flowplayer_thumblist'} .= "\\{ thumbNail: '$thumb_file', time: $time_sec \\},";
945
946 $self->{'keyframe_index'} = $keyframe_index;
947 }
948}
949
950sub EndTag {
951 my ($expat, $element) = @_;
952
953 if ($element eq "seg") {
954
955 $self->output_distributed_keyframes($self->{'keyframe_timeline'},6);
956
957
958 print CUEOUT "</tags>\n";
959 close(CUEOUT);
960
961 #$self->{'flowplayer_thumblist'} .= "\\]";
962 }
963}
964
965
966sub Text {
967 my $text = $_;
968}
969
970# This Char function overrides the one in XML::Parser::Stream to overcome a
971# problem where $expat->{Text} is treated as the return value, slowing
972# things down significantly in some cases.
973sub Char {
974 $_[0]->{'Text'} .= $_[1];
975 return undef;
976}
977
9781;
979
980
981
982
983
984
985
986
987
988
989
Note: See TracBrowser for help on using the repository browser.