-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathct.rb
More file actions
1851 lines (1579 loc) · 61 KB
/
Copy pathct.rb
File metadata and controls
1851 lines (1579 loc) · 61 KB
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
# You need the xml-simple gem to run this script
# [sudo] gem install xml-simple
# Ruby standard modules
require 'fileutils'
require 'open-uri'
require 'set'
require 'thread'
# Local modules
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)))
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__)) + "/ctlib")
require 'backports'
require 'image_size'
require 'json'
require 'tile'
require 'tileset'
require 'xmlsimple'
$ajax_includes = {}
def include_ajax(filename, contents)
$ajax_includes[filename] = contents
end
def include_ajax_file(filename)
include_ajax filename, Filesystem.read_file("#{$explorer_source_dir}/#{filename}")
end
def javascript_quote x
# JSON.generate works for arrays and maps, but not strings or numbers. So wrap in an array
# before generating, and then take the square brackets off
JSON.generate([x])[1...-1]
end
def ajax_includes_to_javascript
statements = ["cached_ajax={};"]
$ajax_includes.keys.sort.each do |filename|
statements << "cached_ajax['#{filename}']=#{javascript_quote($ajax_includes[filename])};"
end
statements.join "\n\n"
end
#profile = "ct.profile.13n.txt"
profile = false
debug = false
$check_mem = false
class Partial
def initialize(n, total)
@n = n
@total = total
end
def self.none
Partial.new(0,1)
end
def self.all
Partial.new(1,1)
end
def none?
@n == 0
end
def all?
@total == 1 && !none?
end
def apply(seq)
none? and return []
seq = seq.map
len = seq.size
start = len * (@n - 1) / @total
finish = len * @n / @total
start...finish
end
def to_s
if none?
"Skip all"
elsif all?
"All"
else
"Part #{@n} of #{@total}"
end
end
end
$compute_tilestacks = Partial.all
$compute_videos = Partial.all
$preserve_source_tiles = false
if profile
require 'rubygems'
require 'ruby-prof'
# RubyProf.measure_mode = RubyProf::MEMORY
RubyProf.start
end
if $check_mem
require 'check-mem'
end
start_time = Time.new
if debug
require 'ruby-debug'
end
$run_remotely = nil
$run_remotely_json = false
$run_remotely_json_dir = nil
$cache_folder = nil
$dry_run = false
if RUBY_VERSION < '1.8.5' || RUBY_VERSION > '1.9.'
raise "Ruby version is #{RUBY_VERSION}, but must be >= 1.8.6, and must be < 1.9 because of threading bugs in 1.9"
end
if `echo %PATH%`.chomp != '%PATH%'
$os = 'windows'
elsif File.exists?('/proc')
$os = 'linux'
else
$os = 'osx'
end
if $os == 'windows'
require 'win32/registry'
require File.join(File.dirname(__FILE__), 'shortcut')
end
def temp_file_unique_fragment
"tmp-#{Process.pid}-#{Thread.current.object_id}-#{Time.new.to_i}"
end
def self_test(stitch = true)
success = true
STDERR.puts "Testing tilestacktool...\n"
status = Kernel.system(*(tilestacktool_cmd + ['--selftest']))
if status
STDERR.puts "tilestacktool: succeeded\n"
else
STDERR.puts "tilestacktool: FAILED\n"
success = false
end
if stitch
STDERR.puts "Testing stitch..."
status = Kernel.system($stitch, '--batch-mode', '--version')
if status
STDERR.puts "stitch: succeeded"
else
STDERR.puts "stitch: FAILED"
success = false
end
end
if $explorer_source_dir
STDERR.puts "Explorer source dir: succeeded"
else
STDERR.puts "Explorer source dir not found: FAILED"
end
STDERR.puts "ct.rb self-test #{success ? 'succeeded' : 'FAILED'}."
return success
end
def read_from_registry(hkey,subkey)
begin
reg_type = Win32::Registry::Constants::KEY_READ | KEY_WOW64_64KEY
reg = Win32::Registry.open(hkey,subkey,reg_type)
return reg
rescue Win32::Registry::Error
# If we fail to read the key (e.g. it does not exist, we end up here)
return nil
end
end
$tilestacktool_args = []
def tilestacktool_cmd
[$tilestacktool] + $tilestacktool_args
end
def stitch_cmd
cmd = [$stitch]
cmd << '--batch-mode'
cmd << '--nolog'
$os == 'linux' and $run_remotely and cmd << '--xvfb'
cmd
end
$sourcetypes = {}
class Filesystem
def self.mkdir_p(path)
FileUtils.mkdir_p path
end
def self.read_file(path)
open(path, 'r') { |fh| fh.read }
end
def self.write_file(path, data)
open(path, 'w') { |fh| fh.write data }
end
def self.cache_directory(root)
end
def self.exists?(path)
File.exists? path
end
def self.cached_exists?(path)
File.exists? path
end
def self.cp_r(src, dest)
FileUtils.cp_r src, dest
end
def self.cp(src, dest)
FileUtils.cp src, dest
end
def self.mv(src, dest)
FileUtils.mv src, dest
end
def self.rm(path)
FileUtils.rm_rf Dir.glob("#{path}")
end
end
def write_json_and_js(path, prefix, obj)
Filesystem.mkdir_p File.dirname(path)
js_path = path + '.js'
Filesystem.write_file(js_path, prefix + '(' + JSON.pretty_generate(obj) + ')')
STDERR.puts("Wrote #{js_path}")
# Deprecated. TODO(RS): Remove this soon
write_json_path = true
if write_json_path
json_path = path + '.json'
Filesystem.write_file(json_path, JSON.pretty_generate(obj))
STDERR.puts("Wrote #{json_path}")
end
end
Dir.glob(File.dirname(__FILE__) + "/*_source.rb").each do |file|
STDERR.puts "Loading #{File.basename(file)}..."
require file
end
$verbose = false
@@global_parent = nil
#
# DOCUMENTATION IS IN README_CT.TXT
#
def date
Time.now.strftime("%Y-%m-%d %H:%M:%S")
end
def usage(msg=nil)
msg and STDERR.puts msg
STDERR.puts "usage:"
STDERR.puts "ct.rb [flags] input.tmc output.timemachine"
STDERR.puts "Flags:"
STDERR.puts "-j N: number of parallel jobs to run (default 1)"
STDERR.puts "-r N: max number of rules per job (default 1)"
STDERR.puts "-v: verbose"
STDERR.puts "--remote [script]: Use script to submit remote jobs"
STDERR.puts "--remote_json [script]: Use script to submit remote jobs"
STDERR.puts "--tilestacktool path: full path of tilestacktool"
STDERR.puts "--cache_folder path: Path of cache folder. Usefull in cluster mode"
exit 1
end
def without_extension(filename)
filename[0..-File.extname(filename).size-1]
end
class TemporalFragment
attr_reader :start_frame, :end_frame, :fragment_seq
# start_frame and end_frame are both INCLUSIVE
def initialize(start_frame, end_frame, fragment_seq = nil)
@start_frame = start_frame
@end_frame = end_frame
@fragment_seq = fragment_seq
end
end
class VideoTile
attr_reader :c, :r, :level, :x, :y, :subsample, :fragment
def initialize(c, r, level, x, y, subsample, fragment)
@c = c
@r = r
@level = level
@x = x
@y = y
@subsample = subsample
@fragment = fragment
end
def path
ret = "#{@level}/#{@r}/#{@c}"
@fragment.fragment_seq and ret += "_#{@fragment.fragment_seq}"
ret
end
def to_s
"#<VideoTile path='#{path}' r=#{@r} c=#{@c} level=#{@level} x=#{@x} y=#{@y} subsample=#{@subsample}>"
end
def source_bounds(vid_width, vid_height)
{'xmin' => @x, 'ymin' => @y, 'width' => vid_width * @subsample, 'height' => vid_height * @subsample}
end
def frames
{'start' => @fragment.start_frame, 'end' => @fragment.end_frame}
end
end
class Rule
attr_reader :targets, :dependencies, :commands, :local
@@all = []
@@all_targets = Set.new
@@n = 0
def self.clear_all
@@all = []
end
def self.all
@@all
end
def self.has_target?(target)
@@all_targets.member? target
end
def array_of_strings?(a)
a.class == Array && a.all? {|e| e.class == String}
end
def initialize(targets, dependencies, commands, options={})
if $check_mem
@@n += 1
if @@n % 10000 == 0
CheckMem.logvm("Created #{@@n} rules")
end
end
if targets.class == String
targets = [targets]
end
commands = commands.map {|cmd| cmd.map {|x| x.class == Hash ? JSON.generate(x) : x.to_s} }
array_of_strings?(targets) or raise "targets must be an array of pathnames"
array_of_strings?(dependencies) or raise "dependencies must be an array of pathnames"
@targets = targets
@dependencies = dependencies
@commands = commands
@@all << self
targets.each { |target| @@all_targets << target }
end
def self.add(targets, dependencies, commands, options={})
Rule.new(targets, dependencies, commands, options).targets
end
def self.touch(target, dependencies)
Rule.add(target, dependencies, [tilestacktool_cmd + ['--createfile', target]], {:local => true})
end
def to_make
ret = "#{@targets.join(" ")}: #{@dependencies.join(" ")}\n"
if @commands.size
ret += "\t@$(SS) '#{@commands.join(" && ")}'"
end
ret
end
def to_s
"[Rule: #{targets.join(" ")}]"
end
end
class VideosetCompiler
attr_reader :videotype, :vid_width, :vid_height, :overlap_x, :overlap_y, :compression, :label, :fps, :show_frameno, :parent
attr_reader :id
# DEPRECATED
# We now allow users to pass in an array containing a desired width and height
@@sizes={
"large"=>{:vid_size=>[1088,624], :overlap=>[1088/4, 624/4]},
"small"=>{:vid_size=>[768,432], :overlap=>[768/3, 432/3]}
}
@@videotypes={
"h.264"=>{}
}
def initialize(parent, settings)
@parent = parent
@@global_parent = parent
@label = settings["label"] || raise("Video settings must include label")
@videotype = settings["type"] || raise("Video settings must include type")
size = settings["size"] || raise("Video settings must include size")
if size.kind_of?(Array)
overlap = settings["overlap"] || 0.25
(@vid_width, @vid_height) = [(size[0] / (1-overlap)).ceil, (size[1] / (1-overlap)).ceil]
# Ensure that the width and height are multiples of 2 for ffmpeg
@vid_width = ((@vid_width - 1) / 2 + 1) * 2
@vid_height = ((@vid_height - 1) / 2 + 1) * 2
(@overlap_x, @overlap_y) = [@vid_width - size[0], @vid_height - size[1]]
else # Backwards compatibility
@@sizes.member?(size) || raise("Video size must be one of [#{@@sizes.keys.join(", ")}]. WARNING: This way of declaring sizes is deprecated.")
(@vid_width, @vid_height) = @@sizes[size][:vid_size]
(@overlap_x, @overlap_y) = @@sizes[size][:overlap]
end
(@compression = settings["compression"] || settings["quality"]) or raise "Video settings must include compression"
@compression = @compression.to_i
@compression > 0 || raise("Video compression must be > 0")
@fps = settings["fps"] || raise("Video settings must include fps")
@fps = @fps.to_f
@fps > 0 || raise("Video fps must be > 0")
@show_frameno = settings["show_frameno"]
@frames_per_fragment = settings["frames_per_fragment"]
@leader = @frames_per_fragment ? 0 : compute_leader_length
initialize_videotiles
initialize_id
end
def compute_leader_length
leader_bytes_per_pixel={
30 => 2701656.0 / (@vid_width * @vid_height * 90),
28 => 2738868.0 / (@vid_width * @vid_height * 80),
26 => 2676000.0 / (@vid_width * @vid_height * 70),
24 => 2556606.0 / (@vid_width * @vid_height * 60)
}
if not leader_bytes_per_pixel.member?(@compression)
raise "Video compression must be one of [#{leader_bytes_per_pixel.keys.join(", ")}]"
end
bytes_per_frame = @vid_width * @vid_height * leader_bytes_per_pixel[@compression]
leader_threshold = 1200000
estimated_video_size = bytes_per_frame * nframes
if estimated_video_size < leader_threshold
# No leader needed
return 0
end
minimum_leader_length = 2500000
leader_nframes = minimum_leader_length / bytes_per_frame
# Round up to nearest multiple of frames per keyframe
frames_per_keyframe = 10
leader_nframes = (leader_nframes / frames_per_keyframe).ceil * frames_per_keyframe
return leader_nframes
end
def initialize_id
tokens = ["crf#{@compression}", "#{@fps.round}fps"]
(@leader > 0) && tokens << "l#{@leader}"
tokens << "#{@vid_width}x#{@vid_height}"
@id = tokens.join('-')
end
def nframes
@parent.source.framenames.size
end
def initialize_videotiles
$compute_videos or return
# Compute levels
levels = []
@levelinfo = []
subsample = 1
while true do
input_width = @vid_width * subsample
input_height = @vid_height * subsample
levels << {:subsample => subsample, :input_width => input_width, :input_height => input_height}
if input_width >= @parent.source.width and input_height >= @parent.source.height
break
end
subsample *= 2
end
levels.reverse!
for level in 0...levels.size do
levels[level][:level] = level
end
if @frames_per_fragment
@temporal_fragments = (nframes / @frames_per_fragment).floor.times.map do |i|
TemporalFragment.new(i * @frames_per_fragment,
[(i + 1) * @frames_per_fragment, nframes].min - 1,
i)
end
else
@temporal_fragments = [TemporalFragment.new(0, nframes - 1)]
end
@videotiles = []
levels.each do |level|
level_rows = 1+((@parent.source.height - level[:input_height]).to_f / (@overlap_y * level[:subsample])).ceil
level_rows = [1,level_rows].max
level_cols = 1+((@parent.source.width - level[:input_width]).to_f / (@overlap_x * level[:subsample])).ceil
level_cols = [1,level_cols].max
@levelinfo << {"rows" => level_rows, "cols" => level_cols}
#puts "** level=#{level[:level]} subsample=#{level[:subsample]} #{level_cols}x#{level_rows}=#{level_cols*level_rows} videos input_width=#{level[:input_width]} input_height=#{level[:input_height]}"
rows_to_compute = $compute_videos.apply(0...level_rows)
rows_to_compute.each do |r|
y = r * @overlap_y * level[:subsample]
level_cols.times do |c|
x = c * @overlap_x * level[:subsample]
@temporal_fragments.each do |fragment|
@videotiles << VideoTile.new(c, r, level[:level], x, y, level[:subsample], fragment)
end
end
end
end
end
def rules(dependencies)
if not $compute_videos
STDERR.puts "#{id}: skipping video creation"
dependencies
else
STDERR.puts "#{id}: #{@videotiles.size} videos (#{$compute_videos})"
@videotiles.flat_map do |vt|
target = "#{@parent.videosets_dir}/#{id}/#{vt.path}.mp4"
cmd = tilestacktool_cmd
cmd << "--create-parent-directories"
cmd << '--path2stack'
cmd += [@vid_width, @vid_height]
frames = {'frames' => vt.frames,
'bounds' => vt.source_bounds(@vid_width, @vid_height)};
cmd << JSON.generate(frames)
cmd << @parent.tilestack_dir
cmd += @parent.video_filter || []
@leader > 0 and cmd += ["--prependleader", @leader]
cmd += ["--blackstack",
10, # number of frames
@vid_width,
@vid_height,
3, # bands per pixel
8 # bits per band
];
cmd << "--cat";
cmd += ['--writevideo', target, @fps, @compression]
Rule.add(target, dependencies, [cmd])
end
end
end
def info
ret = {
"level_info" => @levelinfo,
"nlevels" => @levelinfo.size,
"level_scale" => 2,
"frames" => nframes,
"fps" => @fps,
"leader" => @leader,
"tile_width" => @overlap_x,
"tile_height" => @overlap_y,
"video_width" => @vid_width,
"video_height" => @vid_height,
"width" => parent.source.width,
"height" => parent.source.height
}
@frames_per_fragment and ret['frames_per_fragment']=@frames_per_fragment
ret
end
def write_json
write_json_and_js("#{@parent.videosets_dir}/#{id}/r", 'org.cmucreatelab.loadVideoset', info)
include_ajax "./#{id}/r.json", info
end
end
# Looks for images in one or two levels below dir, and sorts them alphabetically
# Supports Windows shortcuts
def find_images_in_directory(dir)
valid_image_extensions = Set.new [".jpg",".jpeg",".png",".tif",".tiff", ".raw", ".kro", ".lnk"]
images = []
(Dir.glob("#{dir}/*.*")+Dir.glob("#{dir}/*/*.*")).sort.each do |image|
next unless valid_image_extensions.include? File.extname(image).downcase
if $os == 'windows' && File.extname(image) == ".lnk"
images << Win32::Shortcut.open(image).path
else
images << image
end
end
images
end
class ImagesSource
attr_reader :ids, :width, :height, :tilesize, :tileformat, :subsample, :raw_width, :raw_height
attr_reader :capture_times, :capture_time_parser, :capture_time_parser_inputs, :framenames
def initialize(parent, settings)
@parent = parent
@@global_parent = parent
@image_dir="#{@parent.store}/0100-original-images"
@raw_width = settings["width"]
@raw_height = settings["height"]
@subsample = settings["subsample"] || 1
@images = settings["images"] ? settings["images"].flatten : nil
@capture_times = settings["capture_times"] ? settings["capture_times"].flatten : nil
@capture_time_parser = settings["capture_time_parser"] || "/bin/extract_exif_capturetimes.rb"
@capture_time_parser_inputs = settings["capture_time_parser_inputs"] || "#{@parent.store}/0100-unstitched/"
initialize_images
initialize_framenames
@tilesize = settings["tilesize"] || ideal_tilesize(@framenames.size)
@tileformat = settings["tileformat"] || "kro"
end
def ideal_tilesize(nframes)
# Aim for less than half a gigabyte, but no more than 512
tilesize = 512
while tilesize * tilesize * nframes * 3 > 0.5e9
tilesize /= 2
end
tilesize
end
def initialize_images
@images ||= find_images_in_directory(@image_dir)
@images.empty? and usage "No images specified, and none found in #{@image_dir}"
@images.map! {|image| File.expand_path(image, @parent.store)}
@raw = (File.extname(@images[0]).downcase == ".raw")
initialize_size
end
def initialize_size
if @raw
@raw_width and @raw_height or usage("Must specify width and height for .raw image source")
@width = @raw_width
@height = @raw_height
else
open(@images[0], "rb") do |fh|
(@width, @height)=ImageSize.new(fh).get_size
end
end
@width /= @subsample
@height /= @subsample
end
def initialize_framenames
frames = @images.map {|filename| File.expand_path(without_extension(filename)).split('/')}
# Remove common prefixes
while frames[0].length > 1 && frames.map {|x|x[0]}.uniq.length == 1
frames = frames.map {|x| x[1..-1]}
end
@framenames = frames.map {|frame| frame.join('@')}
@image_framenames = {}
@framenames.size.times {|i| @image_framenames[@images[i]] = @framenames[i]}
end
def image_to_tiles_rule(image)
fn = @image_framenames[image]
target = "#{@parent.tiles_dir}/#{fn}.data/tiles"
cmd = tilestacktool_cmd + ['--tilesize', @tilesize, '--image2tiles', target, @tileformat, image]
Rule.add(target, [image], [cmd])
end
def tiles_rules
@images.flat_map {|image| image_to_tiles_rule(image)}
end
end
$sourcetypes['images'] = ImagesSource;
class GigapanOrgSource
attr_reader :ids, :width, :height, :tilesize, :tileformat, :framenames, :subsample
attr_reader :capture_time_parser, :capture_time_parser_inputs
def initialize(parent, settings)
@parent = parent
@@global_parent = parent
@urls = settings["urls"]
@ids = @urls.map{|url| id_from_url(url)}
@subsample = settings["subsample"] || 1
@capture_time_parser = "/bin/extract_gigapan_capturetimes.rb"
@capture_time_parser_inputs = "#{@parent.store}/0200-tiles"
@tileformat = "jpg"
initialize_dimensions
end
def initialize_dimensions
@tilesize = 256
id = @ids[0]
api_url = "http://api.gigapan.org/beta/gigapans/#{id}.json"
gigapan = open(api_url) { |fh| JSON.load(fh) }
@width = gigapan["width"] or raise "Gigapan #{id} has no width"
@width = @width.to_i / @subsample
@height = gigapan["height"] or raise "Gigapan #{id} has no height"
@height = @height.to_i / @subsample
@framenames = (0...@ids.size).map {|i| framename(i)}
end
def framename(i)
"#{"%06d"%i}-#{@ids[i]}"
end
def tiles_rules
@ids.size.times.flat_map do |i|
target = "#{@parent.tiles_dir}/#{framename(i)}.data/tiles"
Rule.add(target, [], [['mirror-gigapan.rb', @ids[i], target]])
end
end
def id_from_url(url)
url.match(/(\d+)/) {|id| return id[0]}
raise "Can't find ID in url #{url}"
end
end
$sourcetypes['gigapan.org'] = GigapanOrgSource;
class PrestitchedSource
attr_reader :ids, :width, :height, :tilesize, :tileformat, :framenames, :subsample
attr_reader :capture_time_parser, :capture_time_parser_inputs
def initialize(parent, settings)
@parent = parent
@@global_parent = parent
@subsample = settings["subsample"] || 1
@capture_time_parser = "/bin/extract_gigapan_capturetimes.rb"
@capture_time_parser_inputs = "#{@parent.store}/0200-tiles"
initialize_frames
end
def initialize_frames
@framenames = Dir.glob("#{@parent.store}/0200-tiles/*.data").map {|dir| File.basename(without_extension(dir))}.sort
data = XmlSimple.xml_in("#{@parent.store}/0200-tiles/#{framenames[0]}.data/tiles/r.info")
@width =
data["bounding_box"][0]["bbox"][0]["max"][0]["vector"][0]["elt"][0].to_i -
data["bounding_box"][0]["bbox"][0]["min"][0]["vector"][0]["elt"][0].to_i
@height =
data["bounding_box"][0]["bbox"][0]["max"][0]["vector"][0]["elt"][1].to_i -
data["bounding_box"][0]["bbox"][0]["min"][0]["vector"][0]["elt"][1].to_i
@tilesize = data["tile_size"][0].to_i
@tileformat = "jpg"
@width /= @subsample
@height /= @subsample
end
def tiles_rules
[]
end
end
$sourcetypes['prestitched'] = PrestitchedSource;
class StitchSource
attr_reader :ids, :width, :height, :tilesize, :tileformat, :framenames, :subsample
attr_reader :align_to, :stitcher_args, :camera_response_curve, :cols, :rows, :rowfirst
attr_reader :directory_per_position, :capture_times, :capture_time_parser, :capture_time_parser_inputs
def initialize(parent, settings)
@parent = parent
@@global_parent = parent
@subsample = settings["subsample"] || 1
@width = settings["width"] || 1
@height = settings["height"] || 1
@align_to = settings["align_to"] or raise "Must include align-to"
settings["align_to_comment"] or raise "Must include align-to-comment"
@stitcher_args = settings["stitcher_args"] || ""
@camera_response_curve = settings["camera_response_curve"]
if !@camera_response_curve
response_curve_path = [File.expand_path("#{File.dirname(__FILE__)}/g10.response"),
File.expand_path("#{File.dirname(__FILE__)}/ctlib/g10.response")]
@camera_response_curve = response_curve_path.find {|file| File.exists? file}
if !@camera_response_curve
raise "Can't find camera response curve in search path #{response_curve_path.join(':')}"
end
end
if !File.exists?(@camera_response_curve)
raise "Camera response curve set to #{@camera_response_curve} but the file doesn't exist"
end
@cols = settings["cols"] or raise "Must include cols"
@rows = settings["rows"] or raise "Must include rows"
@rowfirst = settings["rowfirst"] || false
@images = settings["images"]
@directory_per_position = settings["directory_per_position"] || false
@capture_times = settings["capture_times"] ? settings["capture_times"].flatten : nil
@capture_time_parser = "/bin/extract_gigapan_capturetimes.rb"
@capture_time_parser_inputs = "#{@parent.store}/0200-tiles"
initialize_frames
end
def find_directories
Filesystem.cached_exists?("#{@parent.store}/0100-unstitched") or raise "Could not find #{@parent.store}/0100-unstitched"
dirs = Dir.glob("#{@parent.store}/0100-unstitched/*").sort.select {|dir| File.directory? dir}
dirs.empty? and raise 'Found no directories in 0100-unstitched'
dirs
end
def find_images_dpp
directories = find_directories
if @cols * @rows != directories.size
raise "Found #{directories.size} directories in #{@parent.store}/0100-unstitched, but expected #{@cols}x#{@rows}=#{@cols*@rows}"
end
dpp_images = []
directories.each do |dir|
dpp_images << find_images_in_directory(dir)
if dpp_images[0].size != dpp_images[-1].size
raise "Directory #{directories[0]} has #{dpp_images[0].size} images, but directory #{dir} has #{dpp_images[-1].size} images"
end
end
dpp_images[0].size.times.map do |i|
dpp_images.map {|images| images[i]}
end
end
def find_images
directories = find_directories
@framenames = directories.map {|dir| File.basename(dir)}
directories.map do |dir|
images = find_images_in_directory(dir)
images.size == @rows * @cols or raise "Directory #{dir} has #{images.size} images, but expected #{@cols}x#{@rows}=#{@cols*@rows}"
images
end
end
def initialize_frames
if @images
@images.size > 0 or raise "'images' is an empty list"
elsif @directory_per_position
@images = find_images_dpp
else
@images = find_images
end
@images.each_with_index do |frame, i|
if @cols * @rows != frame.size
raise "Found #{frame.size} images in 'images' index #{i}, but expected #{@cols}x#{@rows}=#{@cols*@rows}"
end
end
@images.map! {|frame| frame.map! {|image| File.expand_path(image, @parent.store)} }
@framenames ||= @images.size.times.map {|i| '%06d' % i}
@tilesize = 256
@tileformat = "jpg"
# Read in .gigapan if it exists and we actually need the dimensions from it
# 1x1 are the dummy dimensions we feed the json file
first_gigapan = "#{@parent.store}/0200-tiles/#{framenames[0]}.gigapan"
if @width == 1 && @height == 1 && File.exist?(first_gigapan)
data = XmlSimple.xml_in(first_gigapan)
if data
notes = data["notes"]
if notes
dimensions = notes[0].scan(/\d* x \d*/)
if dimensions
dimensions_array = dimensions[0].split(" x ")
if dimensions_array.size == 2
@width = dimensions_array[0].to_i
@height = dimensions_array[1].to_i
end
end
end
end
end
@width /= @subsample
@height /= @subsample
end
class Copy
attr_reader :target
def initialize(target)
@target = target
end
end
def copy(x)
return Copy.new(x)
end
def tiles_rules
targetsets = []
@framenames.size.times do |i|
framename = @framenames[i]
align_to = []
copy_master_geometry_exactly = false
align_to_eval = eval(@align_to)
if align_to_eval.class == Copy
if align_to_eval.target != i
align_to += targetsets[align_to_eval.target]
copy_master_geometry_exactly = true
end
else
align_to_eval.each do |align_to_index|
if align_to_index >= i
raise "align_to for index #{i} yields #{align_to_index}, which >= #{i}"
end
if align_to_index >= 0
align_to += targetsets[align_to_index]
end
end
if align_to == [] && i > 0
raise "align_to is empty for index #{i} but can only be empty for index 0"
end
end
target_prefix = "#{@parent.store}/0200-tiles/#{framename}"
if $cache_folder
cache_prefix = "#{$cache_folder}/#{framename}"
end
cmd = stitch_cmd
cmd += @rowfirst ? ["--rowfirst", "--ncols", @cols] : ["--nrows", @rows]
# Stitch 1.x:
# stitch_cmd << "--license-key AATG-F89N-XPW4-TUBU"
# Stitch 2.x:
cmd += ['--license-key', 'ACTG-F8P9-AJY3-6733']
cmd += @stitcher_args.split
if @camera_response_curve
cmd += ["--load-camera-response-curve", @camera_response_curve]
end
suffix = "tmp-#{temp_file_unique_fragment}"
if $cache_folder
cmd += ["--save-as", "#{cache_prefix}-#{suffix}.gigapan"]
else
cmd += ["--save-as", "#{target_prefix}-#{suffix}.gigapan"]
end
# Only get files with extensions. Organizer creates a subdir called "cache",
# which this pattern will ignore
images = @images[i]
cached_images = []
cache_cmd = ["sed"] + ["-i"]
if $cache_folder
cp_cmd = ["cp"]
images.each do |orig_image|
temp_string = "#{cache_prefix}-photos/"+File.basename(orig_image)
cached_images << temp_string
cp_cmd += ["#{orig_image}"]
cache_cmd += ["-e"] + ["'s/#{temp_string.gsub('/','\/')}/#{orig_image.gsub('/','\/')}/g'"]
end
cache_cmd += ["#{cache_prefix}-#{suffix}.gigapan"]
cp_cmd += ["#{cache_prefix}-photos"]
end
if images.size != @rows * @cols
raise "There should be #{@rows}x#{@cols}=#{@rows*@cols} images for frame #{i}, but in fact there are #{images.size}"
end
if $cache_folder