forked from wolfgangw/backports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dcp_inspect
executable file
·4669 lines (4179 loc) · 181 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-2023 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.2024.01.01'
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 and
# composition summaries
#
# Usage:
#
# dcp_inspect --help
# dcp_inspect /path/to/dir
#
# 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 information
#
# - 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).
#
# - 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 (gem install nokogiri)
# - dcp_inspect requires xsd/ next to it.
#
# Run
# $ git pull
# in backports to keep up-to-date.
#
#
# 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.
# Thanks to Terrence Meiczinger.
#
# ruby version and platform
RubyVersionPlatform = [ RUBY_ENGINE, RUBY_VERSION, RUBY_PLATFORM ].join( ' ' )
# 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
LIB_LOAD_ERROR = 23
RUBY_NAME_ERROR = 24
RUBY_ARGUMENT_ERROR = 25
# Constants
PictureBitrateMaxDCI = 250.0 # Mb/s
PictureBitrateMaxDCISafetyMargin = 2.0 # percent
PictureBitrateMaxDCISafe = ( PictureBitrateMaxDCI / 100 * ( 100 - PictureBitrateMaxDCISafetyMargin ) ).round( 2 )
PictureBitrateMaxHFR = 400.0 # Mb/s
# Required libs
required_libs = [
'optparse',
'ostruct',
'pathname',
'shellwords',
'openssl',
'stringio',
'fileutils',
'open3',
]
if RUBY_VERSION < '3.4'
required_libs << 'base64'
end
missing_libs = []
required_libs.each do |lib|
begin
require lib
rescue LoadError => e
puts e.inspect
missing_libs << lib
end
end
if missing_libs.any?
puts "Ruby installation (#{ RubyVersionPlatform }) is missing required libraries (#{ missing_libs.join( ', ' ) })"
exit LIB_LOAD_ERROR
end
# Required gems
required_gems = [
'nokogiri',
'ttfunk',
]
if RUBY_VERSION >= '3.4'
required_gems << 'base64'
end
missing_gems = []
required_gems.each do |gem|
begin
require gem
rescue LoadError => e
puts e.inspect
missing_gems << gem
end
end
if missing_gems.any?
puts "Please run 'gem install #{ missing_gems.join( ' ' ) }' (without the quotes) and try again"
exit GEM_LOAD_ERROR
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 = nil
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] <path>
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 @is_quiet = true; break
when 'debug' then @dev, @errors, @hints, @info, @debug, @cr, @cpl = [ false, true, true, true, true, true, true ]; @is_quiet = false; break
when 'dev' then @dev, @errors, @hints, @info, @debug, @cr, @cpl = [ true, true, true, true, true, true, true ]; @is_quiet = false; break
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 ]; @is_quiet = 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 err =~ /EditRate and SampleRate do not match/ and err =~ /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 # MxfTools
include MxfTools
class Pipe
def initialize
@pipename = "#{ AppName }_#{ rand( 2 ** 32 ).to_s( 16 ) }"
@pipe = nil
result = make_pipe
end
def remove
out, err, status = Open3.capture3( "rm #{ self.path }" )
end
def path
"/tmp/#{ @pipename }"
end
private
def make_pipe
out, err, status = Open3.capture3( "mkfifo #{ self.path }" )
@pipe = self.path
end
end # Pipe
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 audio_characteristics( pipe, asset_file, channel_count, entry_point, duration, key = nil )
unwrap_call = "asdcp-unwrap -f #{ entry_point } -d #{ duration } #{ key ? '-k ' + key : '' } #{ Shellwords.escape asset_file } #{ pipe.path } 2>/dev/null"
pid = Process.spawn( unwrap_call )
Process.detach pid
system( 'sleep 0.1' )
sox_call = "sox -t wavpcm #{ pipe.path } -n stats"
out, err, status = Open3.capture3( sox_call )
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', 'http://www.smpte-ra.org/schemas/429-16/2014/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'
}
# 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 }
#
# 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
#
class String
def black; "\e[30m#{self}\e[0m" end
def red; "\e[31m#{self}\e[0m" end
def green; "\e[32m#{self}\e[0m" end
def brown; "\e[33m#{self}\e[0m" end
def blue; "\e[34m#{self}\e[0m" end
def magenta; "\e[35m#{self}\e[0m" end
def cyan; "\e[36m#{self}\e[0m" end
def gray; "\e[37m#{self}\e[0m" end
def bg_black; "\e[40m#{self}\e[0m" end
def bg_red; "\e[41m#{self}\e[0m" end
def bg_green; "\e[42m#{self}\e[0m" end
def bg_brown; "\e[43m#{self}\e[0m" end
def bg_blue; "\e[44m#{self}\e[0m" end
def bg_magenta; "\e[45m#{self}\e[0m" end
def bg_cyan; "\e[46m#{self}\e[0m" end
def bg_gray; "\e[47m#{self}\e[0m" end
def bold; "\e[1m#{self}\e[22m" end
def italic; "\e[3m#{self}\e[23m" end
def underline; "\e[4m#{self}\e[24m" end
def blink; "\e[5m#{self}\e[25m" end # temptingudontknowhow
def invert; "\e[7m#{self}\e[27m" end
end
# 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.integer?
"#{ 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.integer?
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 )
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.
#
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
end
# Initialize a Timecode object at this specfic timecode
def at(hrs, mins, secs, frames, with_fps = DEFAULT_FPS)
validate_atoms!(hrs, mins, secs, frames, with_fps)
total = (hrs*(60*60*with_fps) + mins*(60*with_fps) + secs*with_fps + frames).round
new(total, with_fps)
end
# Validate the passed atoms for the concrete framerate
def validate_atoms!(hrs, mins, secs, frames, with_fps)
case true
when hrs > 999
raise RangeError, "There can be no more than 999 hours, got #{hrs}"
when mins > 59
raise RangeError, "There can be no more than 59 minutes, got #{mins}"
when secs > 59
raise RangeError, "There can be no more than 59 seconds, got #{secs}"
when frames > (with_fps - 1)
raise RangeError, "There can be no more than #{with_fps - 1} frames @#{with_fps}, got #{frames}"
end
end
# Parse a timecode with fractional seconds instead of frames. This is how ffmpeg reports
# a timecode
def parse_with_fractional_seconds(tc_with_fractions_of_second, fps = DEFAULT_FPS)
fraction_expr = /\.(\d+)$/
fraction_part = ('.' + tc_with_fractions_of_second.scan(fraction_expr)[0][0]).to_f
seconds_per_frame = 1.0 / fps.to_f
frame_idx = (fraction_part / seconds_per_frame).floor
tc_with_frameno = tc_with_fractions_of_second.gsub(fraction_expr, ":%02d" % frame_idx)
parse(tc_with_frameno, fps)
end
# Parse a timecode with ticks of a second instead of frames. A 'tick' is defined as
# 4 msec and has a range of 0 to 249. This format can show up in subtitle files for digital cinema
def parse_with_ticks(tc_with_ticks, fps = DEFAULT_FPS)
ticks_expr = /(\d{3})$/
ticks_part = (tc_with_ticks.scan(ticks_expr)[0][0]).to_i
seconds_per_frame = 1.0 / fps
frame_idx = ((ticks_part * 0.004) / seconds_per_frame ).floor
tc_with_frameno = tc_with_ticks.gsub(ticks_expr, "%02d" % frame_idx)
parse(tc_with_frameno, fps)
end
# create a timecode from the number of seconds. This is how current time is supplied by
# QuickTime and other systems which have non-frame-based timescales
def from_seconds(seconds_float, the_fps = DEFAULT_FPS)
total_frames = (seconds_float.to_f * the_fps.to_f).to_i
new(total_frames, the_fps)
end
# Some systems (like SGIs) and DPX format store timecode as unsigned integer, bit-packed. This method
# unpacks such an integer into a timecode.
def from_uint(uint, fps = DEFAULT_FPS)
tc_elements = (0..7).to_a.reverse.map do | multiplier |
((uint >> (multiplier * 4)) & 0x0F)
end.join.scan(/(\d{2})/).flatten.map{|e| e.to_i}
tc_elements << fps
at(*tc_elements)
end
end
def coerce(to)
me = case to
when String
to_s
when Integer
to_i
when Float
to_f
else
self