source: gs2-extensions/video-and-audio/trunk/src/perllib/plugins/SimpleVideoPlugin.pm@ 25842

Last change on this file since 25842 was 25842, checked in by jmt12, 12 years ago

Adding in more timing information and allowing for clusters to copy files to a local filespace (/tmp) before processing, so we can separate the timing for IO

File size: 12.8 KB
Line 
1###########################################################################
2#
3# SimpleVideoPlugin.pm -- Plugin for multimedia with some simple video
4# processing
5#
6# A component of the Greenstone digital library software from the New
7# Zealand Digital Library Project at the University of Waikato, New
8# Zealand.
9#
10# Copyright (C) 2012 New Zealand Digital Library Project
11#
12# This program is free software; you can redistribute it and/or modify
13# it under the terms of the GNU General Public License as published by
14# the Free Software Foundation; either version 2 of the License, or
15# (at your option) any later version.
16#
17# This program is distributed in the hope that it will be useful, but
18# WITHOUT ANY WARRANTY; without even the implied warranty of
19# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20# General Public License for more details.
21#
22# You should have received a copy of the GNU General Public License
23# along with this program; if not, write to the Free Software
24# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25#
26###########################################################################
27
28package SimpleVideoPlugin;
29
30use File::Temp qw/ tempdir /;
31
32use BasePlugin;
33use MetadataRead;
34use util;
35
36use strict;
37use warnings;
38no strict 'refs'; # allow filehandles to be variables and viceversa
39
40sub BEGIN
41{
42 @SimpleVideoPlugin::ISA = ('MetadataRead', 'BasePlugin');
43}
44
45my $arguments = [ { 'name' => "process_exp",
46 'desc' => "{BasePlugin.process_exp}",
47 'type' => "regexp",
48 'reqd' => "no",
49 'deft' => &get_default_process_exp() },
50 { 'name' => "streamingHQsize",
51 'desc' => "{VideoPlugin.streamingsize}",
52 'type' => "int",
53 'deft' => "720",
54 'reqd' => "no" },
55 { 'name' => "streamingHQVideoBitrate",
56 'desc' => "{VideoPlugin.streamingbitrate}",
57 'type' => "int",
58 'deft' => "496",
59 'reqd' => "no" },
60 { 'name' => "streamingHQAudioBitrate",
61 'desc' => "{VideoPlugin.streamingbitrate}",
62 'type' => "int",
63 'deft' => "80",
64 'reqd' => "no" },
65 { 'name' => "videoDeinterlacingFilter",
66 'desc' => "Activate a deinterlacing filter to increase the quality of TV footage",
67 'type' => "enum",
68 'list' => [{'name' => "true", 'desc' => "{common.true}"},
69 {'name' => "false", 'desc' => "{common.false}"}],
70 'deft' => "false",
71 'reqd' => "no" },
72 { 'name' => "isParallel",
73 'desc' => "Will the import use parallel processing? (maybe this should be set by parallel-import.pl somehow)",
74 'type' => "enum",
75 'list' => [{'name' => "true", 'desc' => "{common.true}"},
76 {'name' => "false", 'desc' => "{common.false}"}],
77 'deft' => "true",
78 'reqd' => "no" },
79 { 'name' => "isCluster",
80 'desc' => "Will the import be run on a cluster (multiple computers) or not (single computer - possibly multiple processors)",
81 'type' => "enum",
82 'list' => [{'name' => "true", 'desc' => "{common.true}"},
83 {'name' => "false", 'desc' => "{common.false}"}],
84 'deft' => "false",
85 'reqd' => "no" },
86 { 'name' => "separateIO",
87 'desc' => "copy and process the file locally (good for segregating IO cost)",
88 'type' => "enum",
89 'list' => [{'name' => "true", 'desc' => "{common.true}"},
90 {'name' => "false", 'desc' => "{common.false}"}],
91 'deft' => "false",
92 'reqd' => "no" }
93 ];
94
95my $options = { 'name' => "BasicVideoPlugin",
96 'desc' => "",
97 'abstract' => "no",
98 'inherits' => "yes",
99 'args' => $arguments };
100
101sub new
102{
103 my ($class) = shift (@_);
104 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
105 push(@$pluginlist, $class);
106
107 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
108 push(@{$hashArgOptLists->{"OptList"}},$options);
109 my $self = new BasePlugin($pluginlist, $inputargs, $hashArgOptLists);
110 return bless $self, $class;
111}
112
113sub get_default_process_exp
114{
115 return '(?i)\.ts$';
116}
117
118sub get_oid_hash_type
119{
120 my $self = shift (@_);
121 return "hash_on_ga_xml";
122}
123
124sub process
125{
126 my $self = shift (@_);
127 my ($pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
128
129 print STDERR "[A:" . time() . "] SimpleVideoPlugin processing: " . $file . "\n";
130
131 # - I have to add some text (yay, back to needing dummy text) otherwise the
132 # DocumentText formatting is ignored (?!?)
133 my $topsection = $doc_obj->get_top_section();
134 $doc_obj->add_utf8_text($topsection, "This is dummy text");
135
136
137 $file =~ /[\/]?(.+)\.(?:ts)$/;
138 my $filename = $1;
139
140
141 # Optional date metadata (available on raw ReplayMe recordings)
142 if ($filename =~ /(\d\d\d\d)-(\d\d)-(\d\d)/)
143 {
144 my $date = $1 . $2 . $3;
145 $filename =~ s/[^a-z0-9]+/_/ig;
146 $filename =~ s/^_+|_+$//g;
147 $doc_obj->add_utf8_metadata($topsection,"Date",$date);
148 }
149
150 my $process_dir = $ENV{'GSDLCOLLECTDIR'};
151 # If we are in a cluster, then we don't want to be writing all the logs
152 # etc to the shared file system. Instead, we write to the tmp drive
153 my $separate_io = $self->{'separateIO'};
154 if ($separate_io)
155 {
156 $process_dir = &util::filename_cat('/tmp', 'gsimport-' . $filename);
157 if (!-d $process_dir)
158 {
159 mkdir($process_dir, 0775);
160 }
161 }
162 my $logs_dir = &util::filename_cat($process_dir, "logs");
163 if (!-d $logs_dir)
164 {
165 mkdir($logs_dir, 0775);
166 }
167 my $convert_log_path = &util::filename_cat($logs_dir, 'convert-' . $filename . '.log');
168 my $pass_log_path = &util::filename_cat($logs_dir, 'convert-' . $filename . '-pass');
169 my $tmp_dir = &util::filename_cat($process_dir, "cached");
170 if (!-d $tmp_dir)
171 {
172 mkdir($tmp_dir, 0775);
173 }
174 $tmp_dir = &util::filename_cat($tmp_dir, $filename);
175 if (!-d $tmp_dir)
176 {
177 mkdir($tmp_dir, 0775);
178 }
179
180 # If we are separating IO, then we also start by copying the file to
181 # the process directory (local tmp) as well
182 my $ivideo_path = &util::filename_cat($base_dir, $file);
183 if ($separate_io)
184 {
185 print STDERR "[B1:" . time() . "] Creating local copy of file\n";
186 my $local_ivideo_path = &util::filename_cat($process_dir, $file);
187 my $copy_cmd = 'cp "' . $ivideo_path . '" "' . $local_ivideo_path . '"';
188 `$copy_cmd`;
189 $ivideo_path = $local_ivideo_path;
190 print STDERR "[B2:" . time() . "] Complete\n";
191 }
192
193 # 1. Use MediaInfo to extract important metadata
194 print STDERR "[C1:" . time() . "] Extracting metadata\n";
195 print " - Extracting metadata using MediaInfo\n";
196 my $mi_metadata = $self->getMetadata($ivideo_path);
197 $doc_obj->add_utf8_metadata($topsection,"Format", 'multimedia (' . $mi_metadata->{'General'}->{'Format'} . ')');
198 $doc_obj->set_metadata_element($topsection,"FileSize",$mi_metadata->{'General'}->{'File_size'});
199 $doc_obj->add_utf8_metadata($topsection,"Duration",$mi_metadata->{'General'}->{'Duration'});
200 if (defined $mi_metadata->{'Video'}->{'Format_Info'} && defined $mi_metadata->{'Video'}->{'Format'})
201 {
202 $doc_obj->add_utf8_metadata($topsection,"VideoFormat",$mi_metadata->{'Video'}->{'Format_Info'} . ' (' . $mi_metadata->{'Video'}->{'Format'} . ')');
203 }
204 if (defined $mi_metadata->{'Audio'}->{'Format_Info'} && defined $mi_metadata->{'Audio'}->{'Format'})
205 {
206 $doc_obj->add_utf8_metadata($topsection,"AudioFormat",$mi_metadata->{'Audio'}->{'Format_Info'} . ' (' . $mi_metadata->{'Audio'}->{'Format'} . ')');
207 }
208 $doc_obj->add_utf8_metadata($topsection,"Width",$mi_metadata->{'Video'}->{'Width'});
209 $doc_obj->add_utf8_metadata($topsection,"Height",$mi_metadata->{'Video'}->{'Height'});
210 print STDERR "[C2:" . time() . "] Complete\n";
211
212 # 2. Convert into FLV, reprocess to make seekable, and associate
213 # - generate a path for our temporary converted video file
214 print STDERR "[D1:" . time() . "] Converting video to streamble format\n";
215 my $ovideo_path = &util::filename_cat($tmp_dir, 'gsv.mp4');
216 if (-f $ovideo_path)
217 {
218 print " - Found existing converted video in cache\n";
219 }
220 else
221 {
222 # - first conversion pass
223 print " - Convert using Handbrake\n";
224 my $streaming_HQ_size = $self->{'streamingHQsize'};
225 my $streaming_HQ_VideoBitrate = $self->{'streamingHQVideoBitrate'};
226 my $streaming_HQ_AudioBitrate = $self->{'streamingHQAudioBitrate'};
227 my $deinterlace = $self->{'videoDeinterlacingFilter'};
228 my $video_processing_parameters;
229 if (!$streaming_HQ_size || $streaming_HQ_size eq "fullsize")
230 {
231 $video_processing_parameters = "--strict-anamorphic";
232 }
233 else
234 {
235 $video_processing_parameters = "-w $streaming_HQ_size --loose-anamorphic";
236 }
237 if ($deinterlace eq "true")
238 {
239 $video_processing_parameters .= " --decomb";
240 }
241 # Default MenCoder options for x264
242 my $mencoder_options = 'ref=2:bframes=2:subq=6:mixed-refs=0:weightb=0:8x8dct=0:trellis=0';
243 my $is_cluster = $self->{'isCluster'};
244 my $is_parallel = $self->{'isParallel'};
245 # If we are parallel processing on a single (presumably) multicore computer
246 # then we need to limit the number of threads (and hence CPUs) HandBrake
247 # will utilize in order to emulate true parallel processing (otherwise the
248 # first thread to get to HandBrake conversion will take up most the CPUs
249 # causing all other threads to wait anyway). It will interesting to test
250 # whether parallel processing or serial processing (with HandBrake parallel
251 # processing) is faster.
252 if ($is_parallel && !$is_cluster)
253 {
254 $mencoder_options .= ':threads=1';
255 }
256 my $cmd = 'HandBrakeCLI -i "' . $ivideo_path . '" -t 1 -c 1 -f mp4 -O -o "' . $ovideo_path . '" ' . $video_processing_parameters . ' -e x264 -b ' . $streaming_HQ_VideoBitrate . ' -a 1 -E faac -6 dpl2 -R Auto -B ' . $streaming_HQ_AudioBitrate . ' -D 0.0 -x ' . $mencoder_options . ' > "' . $convert_log_path . '" 2>&1';
257 print "[DEBUG: " . $cmd . "]\n";
258 `$cmd`;
259 }
260 if (!-f $ovideo_path)
261 {
262 die("Fatal Error! Failed to convert video: " . $ovideo_path . "\nReason:" . $! . "\n");
263 }
264 print STDERR "[D2:" . time() . "] Complete\n";
265
266 # 3. Extract keyframes using hive
267 print STDERR "[E1:" . time() . "] Extract keyframes\n";
268 my $oshots_path = &util::filename_cat($tmp_dir, 'shots.xml');
269 if (-f $oshots_path)
270 {
271 print " - Found existing keyframe images in cache\n";
272 }
273 else
274 {
275 print " - Generating keyframe images using Hive2\n";
276 my $cmd = 'hive2_ffmpegsvn -o "' . $oshots_path . '" -k "' . $tmp_dir . '" "' . $ovideo_path . '" >> "' . $convert_log_path . '" 2>&1';
277 ###print "[cmd: " . $cmd . "]\n";
278 `$cmd`;
279 }
280 if (!-f $oshots_path)
281 {
282 die("Fatal Error! Failed to extract keyframe images: " . $oshots_path . "\nReason:" . $! . "\n");
283 }
284 print STDERR "[E2:" . time() . "] Complete\n";
285
286
287 # 4. Associate files (copies back to shared space if IO separated)
288 print STDERR "[F1:" . time() . "] Associate derived files to doc_obj\n";
289 # - associate streamable video
290 $doc_obj->associate_file($ovideo_path,'gsv.mp4','video/mp4',$topsection);
291 # - associate all of the JPGs found in the temp directory
292 opendir(my $dh, $tmp_dir);
293 my @shots = readdir($dh);
294 closedir($dh);
295 my $thumbnail = 0;
296 foreach my $shot (sort @shots)
297 {
298 my $shot_path = &util::filename_cat($tmp_dir, $shot);
299 if ($shot =~ /.jpg$/)
300 {
301 if (!$thumbnail)
302 {
303 $doc_obj->add_utf8_metadata($topsection,"Thumbnail",$shot);
304 $thumbnail = 1;
305 }
306 $doc_obj->add_utf8_metadata($topsection,"Keyframe",$shot);
307 $doc_obj->associate_file($shot_path,$shot,"image/jpeg",$topsection);
308 }
309 }
310 print STDERR "[F2:" . time() . "] Complete\n";
311
312 # 5. Done! Cleanup.
313 print STDERR "[G:" . time() . "] SimpleVideoPlugin: Complete!\n";
314 return 1;
315}
316
317sub getMetadata
318{
319 my ($self, $ivideo_path) = @_;
320 my $cmd = 'mediainfo --Output=XML "' . $ivideo_path . '" 2>&1';
321 ###print "Cmd: " . $cmd . "\n";
322 my $metadata_xml = `$cmd`;
323 my @lines = split(/\r?\n/, $metadata_xml);
324 my $metadata = {'Unknown'=>{}};
325 my $metadata_type = 'Unknown';
326 foreach my $line (@lines)
327 {
328 if ($line =~ /<track type="(.+)">/)
329 {
330 $metadata_type = $1;
331 if (!defined $metadata->{$metadata_type})
332 {
333 $metadata->{$metadata_type} = {};
334 }
335 }
336 elsif ($line =~ /<([^>]+)>(.+)<\/[^>]+>/)
337 {
338 my $field = $1;
339 my $value = $2;
340 $metadata->{$metadata_type}->{$field} = $value;
341 }
342 }
343 return $metadata;
344}
345
3461;
347
348
349
350
351
352
353
354
355
356
357
Note: See TracBrowser for help on using the repository browser.