forked from wolfgangw/digital_cinema_tools_distribution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dcp_inspect
executable file
·4782 lines (4281 loc) · 183 KB
/
dcp_inspect
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
# encoding: utf-8
#
# dcp_inspect checks and validates DCPs (Digital Cinema Packages)
#
# 2011-2014 Wolfgang Woehl
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
AppName = File.basename( $0 )
AppVersion = 'v1.2014.12.22'
AppStartSeconds = Time.now
#
# dcp_inspect is a tool for deep inspection and validation of digital
# cinema packages (DCP). This includes integrity checks, asset inspection,
# schema validation, signature and certificate verification, composition
# summaries and naming convention checks.
#
#
# Usage:
#
# dcp_inspect --help
# dcp_inspect /path/to/dir
# dcp_inspect /path/to/dir --no-hash
#
#
# Installation:
#
# See https://github.com/wolfgangw/digital_cinema_tools_distribution/wiki
# for an easy-to-use setup script. This will install everything required.
#
#
# Features:
#
# - Will find and check all DCPs in a filesystem tree
#
# - Runs schema validation on all infrastructure files and DCSubtitle.
# Validation errors will be reported but dcp_inspect will still try to
# inspect the contents of non-valid files.
#
# - Checks and verifies signatures
#
# - Reports detailed composition overviews
#
# - Deep-inspects compositions. This includes composition type consistency
# and completeness checks. dcp_inspect goes through some lengths to determine
# a composition's type (SMPTE/Interop).
#
# - Hints at deviations from the Digital Cinema Naming Convention.
# See http://digitalcinemanamingconvention.com for the proper nomenclature
#
# - Checks presence and sanity of DCSubtitle resources
#
# - Reports in detail all errors encountered
#
# See [Examples](https://github.com/wolfgangw/backports/wiki/Example-output-from-dcp_inspect).
#
#
# Manual installation / Requirements:
#
# If you prefer manual installation you will need the following:
#
# - $ git clone git://github.com/wolfgangw/backports.git
# - asdcplib and its cli tools (http://www.cinecert.com/asdcplib/)
# - Nokogiri, a ruby wrapper for libxml2
# (http://nokogiri.org/tutorials/installing_nokogiri.html)
# For signature verification dcp_inspect requires a recent
# (post 2012.01.11) Nokogiri version with C14N support.
# - dcp_inspect requires xsd/ next to it.
# Clone the whole repository to put everything in place:
# $ git clone git://github.com/wolfgangw/backports.git
#
# Run
# $ git pull
# in backports to keep up-to-date.
#
#
# And then what?
#
# - If you get errors go bug someone:
#
# Either me (https://github.com/wolfgangw/backports/issues) if you
# suspect dcp_inspect to report a false positive or negative
#
# or the author/vendor of the DCP's authoring app.
#
# We all write bugs all the time and your feedback is much appreciated.
#
# - If you get hints think about bugging someone. Try and make an informed
# decision whether the issues hinted at might lead to trouble in the field.
# Some hints will recommend fixing the issue (e.g. empty Text or Image
# elements in DCSubtitle). Other hints will be purely informational
#
# - If all you get is info and 0 errors:
#
# Either your package is perfectly ok
#
# or you might still run into issues on a system in the field
#
# or you ran into a dcp_inspect bug :) Again, get in touch if you suspect
# the latter (https://github.com/wolfgangw/backports/issues).
#
#
# Thanks to the Nokogiri team. You're a wicked crew.
# Thanks to Julik for his Timecode library
# https://github.com/guerilla-di/timecode
# Thanks to Mattias Mattsson for DCSubtitle.v1.mattsson.xsd and
# great feedback from Göteborg International Film Festival.
# Thanks to Mike Radford and Tammo Buhren for test materials.
# Thanks to Alexis Michaltsis for interesting test cases and feedback.
# Thanks to Lilian Lefranc for constant feedback and a donation
# which clearly exceeded what can safely be called a gesture.
# Appreciated and you rock.
# Thanks to Adrianne Jorge for a great user report from Sundance and Sarasota.
#
# Tested on linux and Mac OS boxes. Thanks to Terrence Meiczinger for trying
# on a Windows system (it executed but the libxml infrastructure required for
# schema validation did not work. Wip)
#
# Exit codes
DCP_OK = 0
DCP_ERROR = 1
NO_ARG = 2
TOO_MANY_ARGS = 3
ARG_NOT_A_DIR = 4
XML_CATALOG_NOT_FOUND = 5
XSD_STORE_NOT_FOUND = 6
BAD_HASH_LIMIT_ARG = 7
LOGFILE_WRITE_ERROR = 8
FILE_ACCESS_ERROR = 9
LOGFILE_EXISTS_ERROR = 10
GEM_LOAD_ERROR = 11
REQUIRED_COMMAND_NOT_FOUND = 12
ENV_DCP_INSPECT_DIR_NOT_SET = 13
DCP_INSPECT_DIR_NOT_WRITABLE = 14
AUTOLOGFILE_WRITE_ERROR = 15
MKFIFO_FAIL = 16
RMFIFO_FAIL = 17
USER_INTERRUPT = 18
RUBY_VERSION_NOT_SUPPORTED = 19
RUBY_TYPE_ERROR = 20
RUBY_EXCEPTION = 21
GRACEFUL_SHUTDOWN = 22
# Constants
PictureBitrateMaxLegacy = 250.0 # Mb/s
PictureBitrateMaxLegacySafetyMargin = 2.0 # percent
PictureBitrateMaxLegacySafe = ( PictureBitrateMaxLegacy / 100 * ( 100 - PictureBitrateMaxLegacySafetyMargin ) ).round( 2 )
PictureBitrateMax2ndGen = 500.0 # Mb/s
# Required gems
if RUBY_VERSION <= '1.9'
begin
require 'rubygems'
rescue LoadError
end
end
[
'nokogiri',
'ttfunk',
'optparse',
'ostruct',
'pathname',
'shellwords',
'openssl',
'base64',
'stringio',
'fileutils',
'open3'
].each do |gem|
begin
require gem
rescue LoadError => e
puts e.message
puts "Please run 'gem install #{ gem }' (without the quotes) and try again"
exit GEM_LOAD_ERROR
end
end
# lib/options.rb
class Options
def self.parse( args )
# defaults
options = OpenStruct.new
options.check_hashes = TRUE
options.check_hashes_limit = :no_limit
options.image_analysis = FALSE # not yet implemented
options.audio_analysis = TRUE
options.validate = TRUE
options.as_asset_store = FALSE
options.verbosity = [ 'debug', 'dev' ]
options.logfile = NIL
options.logfile_append = NIL
options.logfile_autolog = FALSE
options.overwrite_logfile = FALSE
options.verbosity_choices = [ 'quiet', 'dev', 'errors', 'hints', 'info', 'cpl', 'debug', 'trace_func' ]
opts = OptionParser.new do |opts|
opts.banner = <<BANNER
#{ AppName } #{ AppVersion }
Usage: #{ AppName } [options] <location>
BANNER
opts.on( '--nh', '--no-hash', 'No asset hash checks' ) do
options.check_hashes = FALSE
end
opts.on( '--hl', '--hash-limit limit', String, 'Limit asset hash checks to assets smaller than limit. E.g. 700KB, 50MB or 1GB (Default: No limit)' ) do |p|
options.check_hashes_limit = p.downcase
end
opts.on( '--ni', '--no-image-analysis', 'No image analysis (Image analysis not yet implemented)' ) do
options.image_analysis = FALSE
end
opts.on( '--na', '--no-audio-analysis', 'No audio analysis' ) do
options.audio_analysis = FALSE
end
opts.on( '--no-schema', 'Skip schema checks' ) do
options.validate = FALSE
end
opts.on( '-s', '--as-asset-store', 'Simulate asset store by merging all collected AM dictionaries' ) do
options.as_asset_store = TRUE
end
opts.on( '-l', '--logfile path', String, 'Write full report to logfile at path' ) do |p|
options.logfile = p
end
opts.on( '--la', '--logfile-append path', String, 'Append full report to logfile at path' ) do |p|
options.logfile_append = p
end
opts.on( '--autolog', "Write full report to $DCP_INSPECT_DIR. (Default: Don't)" ) do
options.logfile_autolog = TRUE
end
opts.on( '-L', '--overwrite-logfile', 'Overwrite logfile (Default: Do not overwrite if logfile exists)' ) do
options.overwrite_logfile = TRUE
end
opts.on( '-v', '--verbosity cutout', Array, "Use quiet, errors, hints, info, debug or cpl. Specify multiple cutouts like '-v errors,info' (Default: debug)" ) do |p|
options.verbosity = [] # option was given so reset
p.each do |e|
if options.verbosity_choices.include?( e )
options.verbosity << e
end
end
if options.verbosity.empty?
options.verbosity = [ 'debug' ]
end
end
opts.on_tail( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
begin
opts.parse!( args )
rescue Exception => e
exit if e.class == SystemExit
puts "Options error: #{ e.message }"
exit
end
options
end # parse
end # Options
# * lib/logger.rb
class DLogger
attr_reader :is_quiet, :prints_dev, :prints_errors, :prints_hints, :prints_info, :prints_debug, :prints_cr, :prints_cpl, :writes_logfile, :logfile, :writes_autolog
def initialize( prefix, options )
@prefix = prefix
@full_log = ( options.logfile || options.logfile_autolog || options.logfile_append ? Array.new : NIL )
@dev, @errors, @hints, @info, @debug, @cr, @cpl = [ FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE ]
options.verbosity.each do |cutout|
case cutout
when 'quiet' then @errors, @hints, @info, @debug, @cr, @cpl = [ FALSE, FALSE, FALSE, FALSE, FALSE, FALSE ]; @is_quiet = TRUE; break
when 'debug' then @dev, @errors, @hints, @info, @debug, @cr, @cpl = [ TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE ]; @is_quiet = FALSE; break
when 'dev' then @dev = TRUE
when 'errors' then @errors = TRUE
when 'hints' then @hints = TRUE
when 'info' then @info = TRUE
when 'cpl' then @cpl = TRUE
when 'trace_func'
@dev, @errors, @hints, @info, @debug, @cr, @cpl = [ TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE ]
set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}
end
end
@writes_logfile = TRUE if options.logfile
@writes_autolog = TRUE if options.logfile_autolog
@logfile = options.logfile
@prints_dev, @prints_errors, @prints_hints, @prints_info, @prints_debug, @prints_cr, @prints_cpl = @dev, @errors, @hints, @info, @debug, @cr, @cpl
@color = Hash.new
@color[ :dev ] = '32' # green
end
def dev( text )
if @dev then outbound_colored( text, @color[ :dev ] ) end
end
def errors( text )
if @errors then outbound( text ) end
end
def hints( text )
if @hints then outbound( text ) end
end
def info( text )
if @info then outbound( text ) end
end
def debug( text )
if @debug then outbound( text ) end
end
def cpl( text )
if @cpl then outbound( text ) end
end
def cr( text )
# don't go to @full_log here
carriage_return( text ) if @cr
end
def outbound( text )
printf "%s %s\n", @prefix, text
@full_log << text if @full_log
end
def outbound_colored( text, color )
printf "%s %s\n", @prefix, colored( text, color )
end
def colored( text, color )
"\033[#{ color }m#{ text }\033[0m"
end
def to_console( text ) printf "%s %s\n", @prefix, text end
def carriage_return( text ) printf "%s %s\r", @prefix, text end
def full_log_blob
@full_log.join( "\n" ) + "\n"
end
end
# Workaround Nokogiri::XML::Document#collect_namespaces peculiarity
# (see https://github.com/sparklemotion/nokogiri/issues/885 for details)
#
# collect_all_namespaces_href_keys will return
#
# {
# "http://www.w3.org/XML/1998/namespace" => ["xml"],
# "http://www.smpte-ra.org/schemas/429-7/2006/CPL" => [nil],
# "http://isdcf.com/schemas/draft/2011/cpl-metadata" => ["meta"],
# "http://www.w3.org/2000/09/xmldsig#" => [nil]
# }
#
# where nil implies xmlns.
# This is an example where multiple default namespace definitions exist
# and are used in different document fragments.
#
# collect_all_namespaces_prefix_keys will return
#
# {
# "xml" => ["http://www.w3.org/XML/1998/namespace"],
# "nil" => ["http://www.smpte-ra.org/schemas/429-7/2006/CPL", "http://www.w3.org/2000/09/xmldsig#"],
# "meta" => ["http://isdcf.com/schemas/draft/2011/cpl-metadata"]
# }
#
class Nokogiri::XML::Document
def collect_all_namespaces_href_keys
xpath( "//namespace::*" ).inject( {} ) do |hash, ns|
( hash[ ns.href ] ||= [] ) << ns.prefix unless ( hash[ ns.href ] and hash[ ns.href ].include? ns.prefix )
hash
end
end
def collect_all_namespaces_prefix_keys
xpath( "//namespace::*" ).inject( {} ) do |hash, ns|
( hash[ ns.prefix ] ||= [] ) << ns.href unless ( hash[ ns.prefix ] and hash[ ns.prefix ].include? ns.href )
hash
end
end
end
# lib/mxf.rb
module MxfTools
def asdcplib_version
out, err, status = Open3.capture3( 'asdcp-unwrap -V' )
major, minor, patchlevel = out.scan( /(\d)\.(\d+)\.(\d+)/ )[0].map { |e| e.to_i }
end
def asdcplib_version_supported?
major, minor, patchlevel = asdcplib_version
case major
when 1
TRUE
else
FALSE
end
end
def mxf_inspect( filename )
errors_present = FALSE
out, err, status = Shell.asdcp_mxf_info( filename )
if out =~ /EditRate and SampleRate do not match/ and out =~ /File may contain JPEG Interop stereoscopic images/
# With 1.12.58 this is not required anymore. Keep it for backwards compat
out, err, status = Shell.asdcp_mxf_interop_stereoscopic_info( filename )
end
if out.empty?
return nil
elsif err =~ /Program stopped on error/
if err =~ /SeekToRIP failed/
return nil
elsif err =~ /File open failure/
return nil
elsif out =~ /essence type is/
# See e.g. Fox Format Test 2D-2k-50 (scope v1.0) (CPL 3452c9ed, MXF 20f97e4e)
errors_present = TRUE
end
end
out = out.split( /\n\s*/ ).collect { |line| line.split( ': ' ) }
et = [ 'EssenceType',
case out.first.to_s
when /#{ MStr::Stereoscopic_pictures }/
MStr::Stereoscopic_pictures
when /#{ MStr::Pictures }/
MStr::Pictures
when /#{ MStr::Mpeg2 }/
MStr::Mpeg2
when /#{ MStr::Audio }/
MStr::Audio
when /#{ MStr::Atmos }/
MStr::Atmos
when /#{ MStr::Timed_text }/i
MStr::Timed_text
else
nil
end
]
return Hash[ out << et ]
end
end
include MxfTools
class Ramdisk
attr_reader :device
def initialize( diskname, size )
@diskname = diskname
@size = size
@device = NIL
result = make_ramdisk
end
def eject
case RUBY_PLATFORM
when /darwin/
out, err, status = Open3.capture3( "hdiutil eject #{ self.path }" )
else
out, err, status = Open3.capture3( "rm -rf #{ self.path }" )
end
end
def path
case RUBY_PLATFORM
when /darwin/
"/Volumes/#{ @diskname }"
else
"/dev/shm/#{ @diskname }"
end
end
private
def make_ramdisk
case RUBY_PLATFORM
when /darwin/
out, err, status = Open3.capture3( "hdiutil attach -nomount ram://#{ @size }" )
@device = out.chomp
out, err, status = Open3.capture3( "diskutil erasevolume HFS+ '#{ @diskname }' #{ @device }" )
TRUE
when /linux/
out, err, status = Open3.capture3( "mkdir #{ self.path }" )
@device = self.path
TRUE
else
FALSE
end
end
end
def bars( list )
level = '█▇▆▅▄▃▂▁'
'|' + list.inject( [] ) do |ary, value|
case value
when '-inf'
ary << '.'
else
case value.to_f.abs
when 0.0
level_index = level[ 0 ]
else
level_index = [ 0, ( Math.log2 value.to_f.abs ).to_i.abs, level.size - 1 ].sort[ 1 ] # clamp between 0 and level.size - 1
end
ary << level[ level_index ]
end
ary
end.join('|') + '|'
end
def parse_sox_stats( stats_str )
begin
[ 'DC offset', 'Min level', 'Max level', 'Pk lev dB', 'RMS lev dB', 'RMS Pk dB', 'RMS Tr dB', 'Crest factor', 'Flat factor', 'Pk count', 'Bit-depth', 'Num samples', 'Length s', 'Scale max', 'Window s' ].inject( {} ) do |hash, item|
values = stats_str.match( /^#{ item }.+$/ )[ 0 ].split( /\s+/ ).reject { |e| item =~ /#{ e }/ }
key = item.downcase.gsub( /\W/, '_' ).to_sym
hash[ key ] = { :overall => values[ 0 ], :channels => values[ 1 .. -1 ] }
hash
end
rescue Exception => e
@logger.info e.message
return {}
end
end
def mkfifo( ramdisk, fifo_name )
begin
system( "mkfifo #{ fifo_name }" )
rescue Exception => e
@logger.info ''
@logger.info e.inspect
@logger.info "Removing #{ ramdisk.path } ..."
ramdisk.eject
exit MKFIFO_FAIL
end
end
def rmfifo( fifo_name )
begin
system( "rm #{ fifo_name }" )
rescue Exception => e
@logger.info ''
@logger.info e.inspect
exit RMFIFO_FAIL
end
end
def audio_characteristics( ramdisk, asset_file, channel_count, entry_point, duration, key = NIL )
fifo_tokens = Array.new
asdcp_prefix_token = File.join( ramdisk.path, 'asdcp-temp-audio' )
( 1 .. channel_count ).each do |ch|
fifo_tokens << "#{ asdcp_prefix_token }_#{ ch }.wav"
end
fifo_zombies = Dir.glob( "#{ asdcp_prefix_token }*" )
fifo_zombies.each do |fz|
rmfifo( fz )
end
fifo_tokens.each do |fifo|
mkfifo( ramdisk, fifo )
end
pid = Process.spawn( "asdcp-unwrap -1 -f #{ entry_point } -d #{ duration } #{ key ? '-k ' + key : '' } #{ Shellwords.escape asset_file } #{ asdcp_prefix_token } 2>/dev/null" )
Process.detach pid
system( 'sleep 0.1' )
out, err, status = Open3.capture3( "sox -t wavpcm -M #{ fifo_tokens.join( ' ' ) } -n stats" )
fifo_tokens.each do |fifo|
rmfifo( fifo )
end
parse_sox_stats( err )
end
# lib/magic_strings.rb
module MStr
Smpte_am = 'http://www.smpte-ra.org/schemas/429-9/2007/AM'
Smpte_pkl = 'http://www.smpte-ra.org/schemas/429-8/2007/PKL'
Smpte_cpl = 'http://www.smpte-ra.org/schemas/429-7/2006/CPL'
Interop_am = 'http://www.digicine.com/PROTO-ASDCP-AM-20040311#'
Interop_pkl = 'http://www.digicine.com/PROTO-ASDCP-PKL-20040311#'
Interop_cpl = 'http://www.digicine.com/PROTO-ASDCP-CPL-20040511#'
Composition_metadata_href = 'http://isdcf.com/schemas/draft/2011/cpl-metadata'
Ns_Xmldsig = 'http://www.w3.org/2000/09/xmldsig#'
Schemas = {
Smpte_am => 'SMPTE-429-9-2007-AM.xsd',
Smpte_pkl => 'SMPTE-429-8-2006-PKL.xsd',
Smpte_cpl => 'SMPTE-429-7-2006-CPL.xsd',
Interop_am => 'PROTO-ASDCP-AM-20040311.xsd',
Interop_pkl => 'PROTO-ASDCP-PKL-20040311.xsd',
Interop_cpl => 'PROTO-ASDCP-CPL-20040511.xsd'
}
# Digital Cinema Naming Convention V.3.9 (superseded by V.8.3 2013)
# http://digitalcinemanamingconvention.com
Naming_convention_v_3_9 = {
:film_title => { :re => /^[-A-Z0-9]{1,14}$/, :field_re => /^[-a-zA-Z0-9]+$/ },
:content_kind => { :re => /^(FTR|FTR-\d|TST|TST-\d|TLR|TLR-\d|TLR\d-2D|TLR\d-3D|RTG-F|RTG-T|TSR|TSR-\d|POL|PSA|ADV|ADV-\d|SHR|SHR-\d|XSN)$/,
:field_re => /^(FTR\d|TST\d|TLR\d|TSR\d|ADV\d|SHR\d)$/},
:aspect_ratio => { :re => /^(F|S|C)$/ },
:language => { :re => /^[A-Z]{2,3}-[A-Z]{2,3}$/, :field_re => /^[a-zA-Z]{2,3}-[a-zA-Z]{2,3}$/ },
:territory_rating => { :re => /^([A-Z]{2}-[+A-Z]{1,3}|INT-TD|INT-TL)$/, :field_re => /^([A-Z]{2}-[+A-Z]{1,3}|INT|INT-|INT-XX|ITL-TD|ITL-TL)$/ },
:audio_type => { :re => /^((10|20|51|61|71)(-[A-Z]{2})?|51-HI-VI|51-HI|51-VI)$/ },
:resolution => { :re => /^2K|4K|48$/ },
:studio => { :re => /^[A-Z]{2,4}$/, :field_re => /^[A-Z]+$/ },
:date => { :re => /^\d{8}$/, :field_re => /^\d{6}$/ },
:facility => { :re => /^[A-Z0-9]{2,3}$/ },
:i3d_specs => { :re => /^(i3D|i3D-gb|i3D-ngb)$/ },
:package_type => { :re => /^(OV|VF(-\d)?)$/, :field_re => /^VF(\d)?$/ }
}
Naming_convention = Naming_convention_v_3_9
# asdcp-info answers include
Stereoscopic_pictures = 'stereoscopic pictures'
Pictures = 'pictures'
Mpeg2 = 'MPEG2 video'
Audio = 'audio'
Atmos = 'Dolby ATMOS'
Timed_text = 'timed text'
Tkr_attr = 'x-TKR'
AssetTypeInterop = 'Interop'
AssetTypeSmpte = 'SMPTE'
AssetTypeUnknown = 'Unknown'
AssetTypeMixed = 'Mixed'
AssetTypeUndetermined = 'Undetermined'
TTF = 'Font TrueType'
OTF = 'Font CFF-based'
Cpl_content_kind_default_scope = 'http://www.smpte-ra.org/schemas/429-7/2006/CPL#standard-content'
Cpl_standard_content = [ 'feature', 'trailer', 'test', 'teaser', 'rating', 'advertisement', 'short', 'transitional', 'psa', 'policy' ]
Cpl_standard_content_moniker_map = { :ftr => :feature, :tlr => :trailer, :tst => :test, :tsr => :teaser, :rtg => :rating, :pol => :policy, :adv => :advertisement, :shr => :short, :xsn => :transitional, :psa => :psa, :pol => :policy }
#
# RFC-4122:
# The hexadecimal values "a" through "f" are output as
# lower case characters and are case insensitive on input.
#
Uuid_rfc4122_re = /^[0-9a-f]{8}-[0-9a-f]{4}-([1-5])[0-9a-f]{3}-[8-9a-b][0-9a-f]{3}-[0-9a-f]{12}$/i
Uuid_re = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
Uuid_particle_re = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i # used for filename component
end # module MStr
# lib/shell_tools.rb
module Shell
class << self
def uuid_new
`kmuuidgen -n`
end
def asdcp_mxf_info( filename )
out, err, status = Open3.capture3( "asdcp-info -v -i -d -r #{ Shellwords.shellescape filename }" )
out = out.chomp
return out, err, status
end
def asdcp_mxf_interop_stereoscopic_info( filename )
out, err, status = Open3.capture3( "asdcp-info -3 -v -i -d -r #{ Shellwords.shellescape filename }" )
out = out.chomp
return out, err, status
end
end
end
class Numeric
TERA = 1099511627776.0
GIGA = 1073741824.0
MEGA = 1048576.0
KILO = 1024.0
def to_k
case
when self == 1 then '1 Byte'
when self < KILO then "%d Bytes" % self
when self < MEGA then "%.1f KB" % ( self / KILO )
when self < GIGA then "%.1f MB" % ( self / MEGA )
when self < TERA then "%.1f GB" % ( self / GIGA )
else "%.1f TB" % ( self / TERA )
end
end
end
# Glyph availability
module TTFunk
class File
def provides_glyphs_for?( unicode_string )
unicode_string.unpack("U*").all? { |c| cmap.unicode.first[c] > 0 }
end
end
end
# Signature counters
@signed_cpls_count = 0
@signed_cpls_verified_count = 0
@signed_pkls_count = 0
@signed_pkls_verified_count = 0
# Plaintext/Encrypted compositions counter
@encrypted_compositions = 0
# lib/tools.rb
# date helpers
require 'date'
def time_to_datetime( time ) # OpenSSL's ruby bindings return Time objects for certificate validity info
DateTime.parse( time.to_s )
end
def datetime_friendly( dt ) # return something in the form of "Tuesday Nov 30 2010 (18:56)"
"#{ DateTime::DAYNAMES[ dt.wday ] } #{ DateTime::ABBR_MONTHNAMES[ dt.month ] } #{ dt.day.to_s } #{ dt.year.to_s } #{ '%02d' % dt.hour.to_s }:#{ '%02d' % dt.min.to_s }"
end
RunDatetime = time_to_datetime AppStartSeconds
RunDatetime_friendly = datetime_friendly RunDatetime
def yyyymmdd( datetime ) # used in KDM filenames. See http://www.kdmnamingconvention.com/
datetime.to_s.split( 'T' ).first.gsub( /-/,'' )
end
def hours_minutes_seconds_verbose( seconds )
t = seconds
hrs = ( ( t / 3600 ) ).to_i
min = ( ( t / 60 ) % 60 ).to_i
sec = t % 60
return [
hrs > 0 ? hrs.to_s + " hour#{ 's' * ( hrs > 1 ? 1 : 0 ) }" : nil ,
min > 0 ? min.to_s + " minute#{ 's' * ( min > 1 ? 1 : 0 ) }" : nil ,
sec == 1 ? sec.to_i.to_s + ' second' : sec != 0 ? sec.to_s + ' seconds' : nil ,
t > 60 ? "(#{ t } seconds)" : nil
].compact.join( ' ' )
end
def hms_from_seconds( seconds )
hours = ( seconds / 3600.0 ).to_i
minutes = ( ( seconds / 60.0 ) % 60 ).to_i
secs = seconds % 60
return [ hours, minutes, secs ].join( ':' )
end
def seconds_from_hms( timestring ) # hh:mm:ss.fraction
a = timestring.split( ':' )
hours = a[ 0 ].to_i
minutes = a[ 1 ].to_i
secs = a[ 2 ].to_f
return ( hours * 3600 + minutes * 60 + secs )
end
def time_string( t )
return "--:--:--" if t.nil?
t = t.to_i; s = t % 60; m = ( t / 60 ) % 60; h = t / 3600
"%02d:%02d:%02d" % [ h, m, s ]
end
# Adapted from actionpack-3.2.11/lib/action_view/helpers/date_helper.rb
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1
return distance_in_minutes == 0 ?
"less than 1 minute" :
"#{ amount 'minute', distance_in_minutes }" unless include_seconds
case distance_in_seconds
when 0..59 then "less than 1 minute"
else "1 minute"
end
when 2..44 then "#{ amount 'minute', distance_in_minutes }"
when 45..89 then "about 1 hour"
when 90..1439 then "about #{ amount 'hour', (distance_in_minutes.to_f / 60.0).round }"
when 1440..2519 then "1 day"
when 2520..43199 then "#{ amount 'day', (distance_in_minutes.to_f / 1440.0).round }"
when 43200..86399 then "about 1 month"
when 86400..525599 then "#{ amount 'month', (distance_in_minutes.to_f / 43200.0).round }"
else
fyear = from_time.year
fyear += 1 if from_time.month >= 3
tyear = to_time.year
tyear -= 1 if to_time.month < 3
leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
minute_offset_for_leap_year = leap_years * 1440
minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
remainder = (minutes_with_offset % 525600)
distance_in_years = (minutes_with_offset / 525600)
if remainder < 131400
"about #{ amount 'year', distance_in_years }"
elsif remainder < 394200
"over #{ amount 'year', distance_in_years }"
else
"almost #{ amount 'year', distance_in_years + 1 }"
end
end
end
# misc helpers
#
# turn items like '100KB' or '1.5 GB' to bytes
def bytes_from_nice_bytes( nice_bytes )
parts = nice_bytes.downcase.split( /(kb|mb|gb)/ )
n = Float( parts.first )
if parts[ 1 ]
case parts[ 1 ]
when 'kb'
n * Numeric::KILO.to_i
when 'mb'
n * Numeric::MEGA.to_i
when 'gb'
n * Numeric::GIGA.to_i
end
else
n
end
end
# plural helper english
def amount( item, count )
if count.is_a? Array or count.is_a? Hash
"#{ count.size } #{ item }#{ pl count }"
elsif count.is_a? Fixnum
"#{ count } #{ item }#{ pl count }"
end
end
def plural( item, count )
"#{ item }#{ pl count }"
end
def pl( count )
if count.is_a? Array or count.is_a? Hash
count.size != 1 ? 's' : ''
elsif count.is_a? Fixnum
count != 1 ? 's' : ''
end
end
# Thanks to Rein Henrichs
def truncate( text, num_words = 6, truncate_string = " [...]" )
if text.nil? then return end
arr = text.split( ' ' )
arr.length > num_words ? arr[ 0...num_words ].join( ' ' ) + truncate_string : text
end
# package path helper
def package( relative_path )
File.join( @package_dir, relative_path )
end
def print_inspection_messages( inspection )
inspection[ :errors ].map { |e| @logger.errors [ 'Error', e ].join( ': ' ) }
inspection[ :hints ].map { |e| @logger.hints [ 'Hint', e ].join( ': ' ) }
inspection[ :info ].map { |e| @logger.info [ 'Info', e ].join( ': ' ) }
end
# lib/timecode-ticks_tc.rb (Julik's timecode -- https://github.com/guerilla-di/timecode + parse_with_ticks)
# Timecode is a convenience object for calculating SMPTE timecode natively.
# The promise is that you only have to store two values to know the timecode - the amount
# of frames and the framerate. An additional perk might be to save the dropframeness,
# but we avoid that at this point.
#
# You can calculate in timecode objects as well as with conventional integers and floats.
# Timecode is immutable and can be used as a value object. Timecode objects are sortable.
#
# Here's how to use it with ActiveRecord (your column names will be source_tc_frames_total and tape_fps)
#
# composed_of :source_tc, :class_name => 'Timecode',
# :mapping => [%w(source_tc_frames total), %w(tape_fps fps)]
class Timecode
VERSION = '1.0.0'
include Comparable
DEFAULT_FPS = 25.0
#:stopdoc:
NTSC_FPS = (30.0 * 1000 / 1001).freeze
FILMSYNC_FPS = (24.0 * 1000 / 1001).freeze
ALLOWED_FPS_DELTA = (0.001).freeze
COMPLETE_TC_RE = /^(\d{2}):(\d{2}):(\d{2}):(\d{2})$/
COMPLETE_TC_RE_24 = /^(\d{2}):(\d{2}):(\d{2})\+(\d{2})$/
DF_TC_RE = /^(\d{1,2}):(\d{1,2}):(\d{1,2});(\d{2})$/
FRACTIONAL_TC_RE = /^(\d{2}):(\d{2}):(\d{2})\.(\d{1,8})$/
TICKS_TC_RE = /^(\d{2}):(\d{2}):(\d{2}):(\d{3})$/
WITH_FRACTIONS_OF_SECOND = "%02d:%02d:%02d.%02d"
WITH_FRAMES = "%02d:%02d:%02d:%02d"
WITH_FRAMES_24 = "%02d:%02d:%02d+%02d"
#:startdoc:
# All Timecode lib errors inherit from this
class Error < RuntimeError; end
# Gets raised if timecode is out of range (like 100 hours long)
class RangeError < Error; end
# Gets raised when a timecode cannot be parsed
class CannotParse < Error; end
# Gets raised when you try to compute two timecodes with different framerates together
class WrongFramerate < ArgumentError; end
# Initialize a new Timecode object with a certain amount of frames and a framerate
# will be interpreted as the total number of frames
def initialize(total = 0, fps = DEFAULT_FPS)
raise WrongFramerate, "FPS cannot be zero" if fps.zero?
# If total is a string, use parse
raise RangeError, "Timecode cannot be negative" if total.to_i < 0
# Always cast framerate to float, and num of rames to integer
@total, @fps = total.to_i, fps.to_f
@value = validate!
freeze
end
def inspect # :nodoc:
"#<Timecode:%s (%dF@%.2f)>" % [to_s, total, fps]
end
class << self
# Use initialize for integers and parsing for strings
def new(from, fps = DEFAULT_FPS)
from.is_a?(String) ? parse(from, fps) : super(from, fps)
end
# Parse timecode and return zero if none matched
def soft_parse(input, with_fps = DEFAULT_FPS)
parse(input) rescue new(0, with_fps)
end
# Parse timecode entered by the user. Will raise if the string cannot be parsed.
# The following formats are supported:
# * 10h 20m 10s 1f (or any combination thereof) - will be disassembled to hours, frames, seconds and so on automatically
# * 123 - will be parsed as 00:00:01:23
# * 00:00:00:00 - will be parsed as zero TC
def parse(input, with_fps = DEFAULT_FPS)
# Drop frame goodbye
if (input =~ DF_TC_RE)
raise Error, "We do not support drop-frame TC"
# 00:00:00:00
elsif (input =~ COMPLETE_TC_RE)
atoms_and_fps = input.scan(COMPLETE_TC_RE).to_a.flatten.map{|e| e.to_i} + [with_fps]
return at(*atoms_and_fps)
# 00:00:00+00
elsif (input =~ COMPLETE_TC_RE_24)
atoms_and_fps = input.scan(COMPLETE_TC_RE_24).to_a.flatten.map{|e| e.to_i} + [24]
return at(*atoms_and_fps)
# 00:00:00.0
elsif input =~ FRACTIONAL_TC_RE
parse_with_fractional_seconds(input, with_fps)
# 00:00:00:000
elsif input =~ TICKS_TC_RE
parse_with_ticks(input, with_fps)
# 10h 20m 10s 1f 00:00:00:01 - space separated is a sum of parts
elsif input =~ /\s/
parts = input.gsub(/\s/, ' ').split.reject{|e| e.strip.empty? }
raise CannotParse, "No atoms" if parts.empty?
parts.map{|part| parse(part, with_fps) }.inject{|sum, p| sum + p.total }
# 10s
elsif input =~ /^(\d+)s$/
return new(input.to_i * with_fps, with_fps)
# 10h
elsif input =~ /^(\d+)h$/i
return new(input.to_i * 60 * 60 * with_fps, with_fps)
# 20m
elsif input =~ /^(\d+)m$/i
return new(input.to_i * 60 * with_fps, with_fps)
# 60f - 60 frames, or 2 seconds and 10 frames
elsif input =~ /^(\d+)f$/i
return new(input.to_i, with_fps)
# Only a bunch of digits, treat 12345 as 00:01:23:45
elsif (input =~ /^(\d+)$/)
atoms_len = 2 * 4
# left-pad input AND truncate if needed
padded = input[0..atoms_len].rjust(8, "0")
atoms = padded.scan(/(\d{2})/).flatten.map{|e| e.to_i } + [with_fps]
return at(*atoms)
else
raise CannotParse, "Cannot parse #{input} into timecode, unknown format"
end