pinterest-dl 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,674 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'json'
5
+ require 'open3'
6
+ require 'tmpdir'
7
+
8
+ module PinterestDL
9
+ module TUI
10
+ class Preview
11
+ MAX_CACHE_ENTRIES = 96
12
+ MAX_DOWNLOAD_BYTES = 6 * 1024 * 1024
13
+ WORKER_COUNT = 3
14
+ BG_RGB = [13, 9, 26].freeze
15
+
16
+ attr_reader :backend, :graphics_protocol
17
+
18
+ def initialize(theme:, icons:, session: nil, external_tools: true,
19
+ graphics_protocol: nil, kitty_graphics: false, on_ready: nil)
20
+ @theme = theme
21
+ @icons = icons
22
+ @session = session
23
+ @external_tools = external_tools
24
+ @graphics_protocol = graphics_protocol || (kitty_graphics ? :kitty : :none)
25
+ @on_ready = on_ready
26
+ @cache = {}
27
+ @files = {}
28
+ @png_files = {}
29
+ @sixel_cache = {}
30
+ @metadata = {}
31
+ @pending = {}
32
+ @failed = {}
33
+ @mutex = Mutex.new
34
+ @job_queue = Queue.new
35
+ @running = true
36
+ @cache_dir = external_tools ? Dir.mktmpdir('pinterest_dl_tui_') : nil
37
+ @backend, @backend_bin = external_tools ? detect_backend : [nil, nil]
38
+ @chafa_bin = external_tools ? find_executable('chafa') : nil
39
+ @sixel_bin = external_tools ? find_executable('img2sixel') : nil
40
+ @ueberzug_bin = external_tools && @graphics_protocol == :none ? detect_ueberzug : nil
41
+ @ueberzug_io = nil
42
+ @ueberzug_ids = []
43
+ @workers = external_tools && @session && decoder_available? ? start_workers : []
44
+ end
45
+
46
+ def decoder_available?
47
+ !@backend.nil? || !@ueberzug_bin.nil? || sixel_ready? || @graphics_protocol == :iterm2
48
+ end
49
+
50
+ def kitty_graphics?
51
+ @graphics_protocol == :kitty && !@backend.nil?
52
+ end
53
+
54
+ def iterm2_graphics?
55
+ @graphics_protocol == :iterm2
56
+ end
57
+
58
+ def sixel_ready?
59
+ @graphics_protocol == :sixel && (!@chafa_bin.nil? || !@sixel_bin.nil?)
60
+ end
61
+
62
+ def ueberzug_available?
63
+ !@ueberzug_bin.nil?
64
+ end
65
+
66
+ def metadata_for(pin)
67
+ return nil unless pin
68
+
69
+ @mutex.synchronize { @metadata[pin[:id].to_s]&.dup }
70
+ end
71
+
72
+ def local_file_for(pin, large: true)
73
+ return nil unless pin
74
+
75
+ key = "#{pin[:id]}_#{large ? 'lg' : 'sm'}"
76
+ path = @mutex.synchronize { @files[key] || @files["#{pin[:id]}_sm"] }
77
+ path && File.exist?(path) ? path : nil
78
+ end
79
+
80
+ def overlay_for(pin, x:, y:, width:, height:, large: false)
81
+ return nil unless pin
82
+
83
+ case @graphics_protocol
84
+ when :kitty then kitty_overlay_for(pin, x: x, y: y, width: width, height: height, large: large)
85
+ when :iterm2 then iterm2_overlay_for(pin, x: x, y: y, width: width, height: height, large: large)
86
+ when :sixel then sixel_overlay_for(pin, x: x, y: y, width: width, height: height, large: large)
87
+ end
88
+ end
89
+
90
+ def kitty_overlay_for(pin, x:, y:, width:, height:, large: false)
91
+ return nil unless kitty_graphics? && pin
92
+
93
+ png_path = @mutex.synchronize { @png_files["#{pin[:id]}_#{large ? 'lg' : 'sm'}"] }
94
+ return nil unless png_path && File.exist?(png_path)
95
+
96
+ draw_w, draw_h, off_x, off_y = fit_cell_box(width, height, metadata_for(pin))
97
+ encoded = [png_path].pack('m0')
98
+ "\e[#{y + off_y};#{x + off_x}H\e_Ga=T,f=100,t=f,c=#{draw_w},r=#{draw_h},q=2;#{encoded}\e\\"
99
+ end
100
+
101
+ def iterm2_overlay_for(pin, x:, y:, width:, height:, large: false)
102
+ return nil unless iterm2_graphics? && pin
103
+
104
+ path = local_file_for(pin, large: large)
105
+ return nil unless path
106
+
107
+ draw_w, draw_h, off_x, off_y = fit_cell_box(width, height, metadata_for(pin))
108
+ data = [File.binread(path)].pack('m0')
109
+ "\e[#{y + off_y};#{x + off_x}H\e]1337;File=inline=1;width=#{draw_w};height=#{draw_h};" \
110
+ "preserveAspectRatio=1:#{data}\a"
111
+ rescue StandardError
112
+ nil
113
+ end
114
+
115
+ def sixel_overlay_for(pin, x:, y:, width:, height:, large: false)
116
+ return nil unless sixel_ready? && pin
117
+
118
+ key = [pin[:id], width, height, large].hash
119
+ sixel = @mutex.synchronize { @sixel_cache[key] }
120
+ return nil unless sixel
121
+
122
+ "\e[#{y};#{x}H#{sixel}"
123
+ end
124
+
125
+ def ueberzug_placement_for(pin, id:, x:, y:, width:, height:, large: false)
126
+ return nil unless ueberzug_available? && pin
127
+
128
+ path = local_file_for(pin, large: large)
129
+ return nil unless path
130
+
131
+ draw_w, draw_h, off_x, off_y = fit_cell_box(width, height, metadata_for(pin))
132
+ {
133
+ action: 'add',
134
+ identifier: id,
135
+ x: [x - 1 + off_x, 0].max,
136
+ y: [y - 1 + off_y, 0].max,
137
+ width: draw_w,
138
+ height: draw_h,
139
+ max_width: draw_w,
140
+ max_height: draw_h,
141
+ scaler: 'fit_contain',
142
+ path: path
143
+ }
144
+ end
145
+
146
+ def sync_ueberzug(placements)
147
+ return unless ueberzug_available?
148
+
149
+ io = ensure_ueberzug_process
150
+ return unless io
151
+
152
+ new_ids = placements.map { |p| p[:identifier] }
153
+ (@ueberzug_ids - new_ids).each do |old_id|
154
+ io.puts({ action: 'remove', identifier: old_id }.to_json)
155
+ end
156
+ placements.each { |pl| io.puts(pl.to_json) }
157
+ io.flush
158
+ @ueberzug_ids = new_ids
159
+ rescue StandardError
160
+ close_ueberzug
161
+ end
162
+
163
+ def clear_ueberzug
164
+ return unless @ueberzug_io && !@ueberzug_ids.empty?
165
+
166
+ @ueberzug_ids.each do |old_id|
167
+ @ueberzug_io.puts({ action: 'remove', identifier: old_id }.to_json)
168
+ end
169
+ @ueberzug_io.flush
170
+ @ueberzug_ids = []
171
+ rescue StandardError
172
+ close_ueberzug
173
+ end
174
+
175
+ def render_pin(pin, width:, height:, large: false)
176
+ w = [width.to_i, 4].max
177
+ h = [height.to_i, 2].max
178
+ return @icons.placeholder_canvas(width: w, height: h, label: 'No pin selected') unless pin
179
+
180
+ is_video = !pin[:video_url].to_s.empty?
181
+ image_url = pin[:image_url].to_s
182
+ if image_url.empty?
183
+ return @icons.placeholder_canvas(width: w, height: h, label: is_video ? 'Video pin' : 'No preview', video: is_video)
184
+ end
185
+
186
+ unless decoder_available? && @session
187
+ label = if @external_tools
188
+ 'Install ueberzugpp/ffmpeg'
189
+ elsif is_video
190
+ 'Video'
191
+ else
192
+ 'Image'
193
+ end
194
+ return @icons.placeholder_canvas(width: w, height: h, label: label, video: is_video)
195
+ end
196
+
197
+ return Array.new(h) { @theme.fit('', w) } if native_overlay_ready?(pin, w, h, large: large)
198
+
199
+ key = [pin[:id], w, h, large].hash
200
+ cached = @mutex.synchronize { @cache[key] }
201
+ return cached if cached
202
+
203
+ failed = @mutex.synchronize { @failed[key] }
204
+ return @icons.placeholder_canvas(width: w, height: h, label: 'Preview error', video: is_video) if failed
205
+
206
+ schedule_render(key, pin, w, h, large: large, video: is_video)
207
+ @icons.placeholder_canvas(width: w, height: h, label: 'Loading...', video: is_video)
208
+ end
209
+
210
+ def clear_cache
211
+ @mutex.synchronize do
212
+ @cache.clear
213
+ @sixel_cache.clear
214
+ @failed.clear
215
+ end
216
+ end
217
+
218
+ def shutdown
219
+ @mutex.synchronize { @running = false }
220
+ @workers.size.times { @job_queue << nil }
221
+ @workers.each { |t| t.join(1.0) }
222
+ close_ueberzug
223
+ FileUtils.rm_rf(@cache_dir) if @cache_dir && Dir.exist?(@cache_dir)
224
+ rescue StandardError
225
+ nil
226
+ end
227
+
228
+ private
229
+
230
+ def native_overlay_ready?(pin, width, height, large:)
231
+ case @graphics_protocol
232
+ when :kitty
233
+ @mutex.synchronize { !@png_files["#{pin[:id]}_#{large ? 'lg' : 'sm'}"].nil? }
234
+ when :iterm2
235
+ !local_file_for(pin, large: large).nil?
236
+ when :sixel
237
+ sixel_ready? && @mutex.synchronize { @sixel_cache.key?([pin[:id], width, height, large].hash) }
238
+ else
239
+ ueberzug_available? && !local_file_for(pin, large: large).nil?
240
+ end
241
+ end
242
+
243
+ def fit_cell_box(box_w, box_h, meta)
244
+ return [box_w, box_h, 0, 0] unless meta && meta[:width].to_i.positive? && meta[:height].to_i.positive?
245
+
246
+ cell_ratio = 2.0
247
+ img_ratio = meta[:width].to_f / meta[:height]
248
+ box_pixel_ratio = box_w.to_f / (box_h * cell_ratio)
249
+ if img_ratio > box_pixel_ratio
250
+ draw_w = box_w
251
+ draw_h = [[(box_w / (img_ratio * cell_ratio)).round, 1].max, box_h].min
252
+ else
253
+ draw_h = box_h
254
+ draw_w = [[(box_h * cell_ratio * img_ratio).round, 1].max, box_w].min
255
+ end
256
+ [draw_w, draw_h, (box_w - draw_w) / 2, (box_h - draw_h) / 2]
257
+ end
258
+
259
+ def ensure_ueberzug_process
260
+ return @ueberzug_io if @ueberzug_io && !@ueberzug_io.closed?
261
+
262
+ args = [@ueberzug_bin, 'layer']
263
+ if File.basename(@ueberzug_bin) == 'ueberzugpp'
264
+ args.concat(['-o', 'x11']) if !ENV['DISPLAY'].to_s.empty? && ENV['WAYLAND_DISPLAY'].to_s.empty?
265
+ else
266
+ args << '--silent'
267
+ end
268
+ @ueberzug_io = IO.popen(args, 'w', err: File::NULL)
269
+ rescue StandardError
270
+ @ueberzug_io = nil
271
+ end
272
+
273
+ def close_ueberzug
274
+ return unless @ueberzug_io
275
+
276
+ clear_ueberzug
277
+ @ueberzug_io.close unless @ueberzug_io.closed?
278
+ rescue StandardError
279
+ nil
280
+ ensure
281
+ @ueberzug_io = nil
282
+ @ueberzug_ids = []
283
+ end
284
+
285
+ def detect_ueberzug
286
+ return nil if ENV['DISPLAY'].to_s.empty? && ENV['WAYLAND_DISPLAY'].to_s.empty?
287
+
288
+ find_executable('ueberzugpp') || find_executable('ueberzug')
289
+ end
290
+
291
+ def start_workers
292
+ Array.new(WORKER_COUNT) do
293
+ Thread.new do
294
+ Thread.current.report_on_exception = false
295
+ while (job = @job_queue.pop)
296
+ break unless running?
297
+
298
+ process_job(job)
299
+ end
300
+ end
301
+ end
302
+ end
303
+
304
+ def running?
305
+ @mutex.synchronize { @running }
306
+ end
307
+
308
+ def schedule_render(key, pin, width, height, large:, video:)
309
+ enqueue = @mutex.synchronize do
310
+ next false if @pending[key] || @cache.key?(key)
311
+
312
+ @pending[key] = true
313
+ true
314
+ end
315
+ return unless enqueue
316
+
317
+ @job_queue << { key: key, pin: pin, width: width, height: height, large: large, video: video }
318
+ end
319
+
320
+ def process_job(job)
321
+ file_path = fetch_image_file(job[:pin], large: job[:large])
322
+ if file_path
323
+ record_metadata(job[:pin], file_path)
324
+ prepare_native_asset(job, file_path)
325
+ end
326
+ lines = build_job_lines(job, file_path)
327
+
328
+ @mutex.synchronize do
329
+ @pending.delete(job[:key])
330
+ if lines
331
+ @cache.shift while @cache.size >= MAX_CACHE_ENTRIES
332
+ @cache[job[:key]] = lines
333
+ @failed.delete(job[:key])
334
+ else
335
+ @failed[job[:key]] = true
336
+ end
337
+ end
338
+ @on_ready&.call
339
+ rescue StandardError
340
+ @mutex.synchronize do
341
+ @pending.delete(job[:key])
342
+ @failed[job[:key]] = true
343
+ end
344
+ @on_ready&.call
345
+ end
346
+
347
+ def prepare_native_asset(job, file_path)
348
+ case @graphics_protocol
349
+ when :kitty then prepare_kitty_png(job[:pin], file_path, large: job[:large])
350
+ when :sixel then prepare_sixel(job, file_path)
351
+ end
352
+ end
353
+
354
+ def build_job_lines(job, file_path)
355
+ return nil unless file_path
356
+ return Array.new(job[:height]) { @theme.fit('', job[:width]) } if ueberzug_available? || @graphics_protocol != :none
357
+
358
+ @backend ? decode_to_lines(file_path, width: job[:width], height: job[:height], video: job[:video]) : nil
359
+ end
360
+
361
+ def prepare_sixel(job, file_path)
362
+ return unless sixel_ready?
363
+
364
+ out = encode_sixel(file_path, width: job[:width], height: job[:height])
365
+ return unless out
366
+
367
+ @mutex.synchronize do
368
+ @sixel_cache.shift while @sixel_cache.size >= MAX_CACHE_ENTRIES
369
+ @sixel_cache[job[:key]] = out
370
+ end
371
+ end
372
+
373
+ def encode_sixel(path, width:, height:)
374
+ if @chafa_bin
375
+ out, status = Open3.capture2(
376
+ @chafa_bin, '--format=sixel', '--bg=#0d091a', "--size=#{width}x#{height}", path
377
+ )
378
+ return out if status.success? && !out.empty?
379
+ end
380
+ if @sixel_bin
381
+ out, status = Open3.capture2(@sixel_bin, '-w', (width * 8).to_s, '-h', (height * 16).to_s, path)
382
+ return out if status.success? && !out.empty?
383
+ end
384
+ nil
385
+ rescue StandardError
386
+ nil
387
+ end
388
+
389
+ def fetch_image_file(pin, large:)
390
+ cache_key = "#{pin[:id]}_#{large ? 'lg' : 'sm'}"
391
+ existing = @mutex.synchronize { @files[cache_key] }
392
+ return existing if existing && File.exist?(existing) && File.size(existing).positive?
393
+
394
+ return nil unless @cache_dir && Dir.exist?(@cache_dir)
395
+
396
+ safe_id = pin[:id].to_s.gsub(/[^A-Za-z0-9_-]/, '')
397
+ safe_id = pin[:image_url].to_s.hash.abs.to_s if safe_id.empty?
398
+ ext = File.extname(pin[:image_url].to_s.split('?').first.to_s)
399
+ ext = '.jpg' unless ext.match?(/\A\.(?:jpg|jpeg|png|webp|gif)\z/i)
400
+ dest = File.join(@cache_dir, "#{safe_id}_#{large ? 'lg' : 'sm'}#{ext.downcase}")
401
+
402
+ candidate_urls(pin[:image_url].to_s, large: large).each do |url|
403
+ next if url.empty?
404
+
405
+ begin
406
+ @session.download(url, path: dest, overwrite: true, resume: false, max_size: MAX_DOWNLOAD_BYTES)
407
+ if File.exist?(dest) && File.size(dest).positive?
408
+ @mutex.synchronize { @files[cache_key] = dest }
409
+ return dest
410
+ end
411
+ rescue StandardError
412
+ next
413
+ end
414
+ end
415
+ nil
416
+ end
417
+
418
+ def prepare_kitty_png(pin, src_path, large:)
419
+ key = "#{pin[:id]}_#{large ? 'lg' : 'sm'}"
420
+ return if @mutex.synchronize { @png_files.key?(key) }
421
+
422
+ png_dest = "#{src_path}.png"
423
+ if convert_to_png(src_path, png_dest)
424
+ @mutex.synchronize { @png_files[key] = png_dest }
425
+ end
426
+ rescue StandardError
427
+ nil
428
+ end
429
+
430
+ def convert_to_png(src_path, dst_path)
431
+ head = File.binread(src_path, 8)
432
+ if head&.start_with?("\x89PNG\r\n\x1A\n".b)
433
+ FileUtils.cp(src_path, dst_path)
434
+ return true
435
+ end
436
+
437
+ case @backend
438
+ when :ffmpeg
439
+ _out, status = Open3.capture2e(@backend_bin, '-v', 'error', '-y', '-i', src_path, '-frames:v', '1', dst_path)
440
+ status.success? && File.exist?(dst_path)
441
+ when :magick
442
+ _out, status = Open3.capture2e(@backend_bin, "#{src_path}[0]", dst_path)
443
+ status.success? && File.exist?(dst_path)
444
+ when :python_pil
445
+ script = 'import sys; from PIL import Image; Image.open(sys.argv[1]).convert("RGBA").save(sys.argv[2], "PNG")'
446
+ _out, status = Open3.capture2e(@backend_bin, '-c', script, src_path, dst_path)
447
+ status.success? && File.exist?(dst_path)
448
+ else
449
+ false
450
+ end
451
+ end
452
+
453
+ def record_metadata(pin, file_path)
454
+ dims = extract_image_dimensions(file_path)
455
+ bytes = File.size(file_path)
456
+ @mutex.synchronize do
457
+ prev = @metadata[pin[:id].to_s] || {}
458
+ w = dims ? dims[0] : prev[:width]
459
+ h = dims ? dims[1] : prev[:height]
460
+ @metadata[pin[:id].to_s] = { width: w, height: h, bytes: bytes }
461
+ end
462
+ rescue StandardError
463
+ nil
464
+ end
465
+
466
+ def extract_image_dimensions(path)
467
+ data = File.binread(path, 65_536)
468
+ return nil if data.nil? || data.bytesize < 24
469
+
470
+ return data.byteslice(16, 8).unpack('NN') if data.start_with?("\x89PNG\r\n\x1A\n".b)
471
+ return extract_jpeg_dimensions(data) if data.getbyte(0) == 0xFF && data.getbyte(1) == 0xD8
472
+
473
+ nil
474
+ rescue StandardError
475
+ nil
476
+ end
477
+
478
+ def extract_jpeg_dimensions(data)
479
+ pos = 2
480
+ while pos + 9 < data.bytesize
481
+ pos += 1 while pos < data.bytesize && data.getbyte(pos) != 0xFF
482
+ pos += 1 while pos < data.bytesize && data.getbyte(pos) == 0xFF
483
+ break if pos + 7 >= data.bytesize
484
+
485
+ marker = data.getbyte(pos)
486
+ pos += 1
487
+ len = data.byteslice(pos, 2).unpack1('n')
488
+ break if len < 2
489
+
490
+ if [0xC0, 0xC1, 0xC2].include?(marker)
491
+ h, w = data.byteslice(pos + 3, 4).unpack('nn')
492
+ return [w, h] if w.positive? && h.positive?
493
+ end
494
+ pos += len
495
+ end
496
+ nil
497
+ end
498
+
499
+ def candidate_urls(url, large:)
500
+ sized = if url.include?('i.pinimg.com/')
501
+ target = large ? '736x' : '474x'
502
+ url.sub(%r{/(?:originals|\d+x)/}, "/#{target}/")
503
+ else
504
+ url
505
+ end
506
+ [sized, url].uniq
507
+ end
508
+
509
+ def decode_to_lines(path, width:, height:, video:)
510
+ case @backend
511
+ when :ffmpeg then render_from_rgb(decode_ffmpeg(path, width, height * 2), width, height, video: video)
512
+ when :magick then render_from_rgb(decode_magick(path, width, height * 2), width, height, video: video)
513
+ when :chafa then decode_chafa(path, width, height)
514
+ when :python_pil then render_from_rgb(decode_python_pil(path, width, height * 2), width, height, video: video)
515
+ when :djpeg then render_from_rgb(decode_djpeg(path, width, height * 2), width, height, video: video)
516
+ end
517
+ rescue StandardError
518
+ nil
519
+ end
520
+
521
+ def decode_ffmpeg(path, px_w, px_h)
522
+ vf = "scale=#{px_w}:#{px_h}:force_original_aspect_ratio=decrease:flags=lanczos," \
523
+ "pad=#{px_w}:#{px_h}:(ow-iw)/2:(oh-ih)/2:color=#0d091a"
524
+ out, status = Open3.capture2(
525
+ @backend_bin, '-v', 'error', '-i', path,
526
+ '-vf', vf, '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-',
527
+ binmode: true
528
+ )
529
+ return nil unless status.success? && out.bytesize >= px_w * px_h * 3
530
+
531
+ out
532
+ end
533
+
534
+ def decode_magick(path, px_w, px_h)
535
+ out, status = Open3.capture2(
536
+ @backend_bin, "#{path}[0]", '-resize', "#{px_w}x#{px_h}",
537
+ '-background', '#0d091a', '-gravity', 'center', '-extent', "#{px_w}x#{px_h}",
538
+ '-colorspace', 'sRGB', '-depth', '8', 'rgb:-',
539
+ binmode: true
540
+ )
541
+ return nil unless status.success? && out.bytesize >= px_w * px_h * 3
542
+
543
+ out
544
+ end
545
+
546
+ def decode_chafa(path, width, height)
547
+ out, status = Open3.capture2(
548
+ @backend_bin, '--format=symbols', '--symbols=half', '--colors=full',
549
+ '--bg=#0d091a', "--size=#{width}x#{height}", path
550
+ )
551
+ return nil unless status.success? && !out.empty?
552
+
553
+ lines = out.lines.map { |l| @theme.fit(l.chomp, width) }.first(height)
554
+ lines << @theme.fit('', width) while lines.size < height
555
+ lines
556
+ end
557
+
558
+ def decode_python_pil(path, px_w, px_h)
559
+ script = 'import sys; from PIL import Image, ImageOps; ' \
560
+ 'im = ImageOps.pad(Image.open(sys.argv[1]).convert("RGB"), ' \
561
+ '(int(sys.argv[2]), int(sys.argv[3])), color=(13, 9, 26)); ' \
562
+ 'sys.stdout.buffer.write(im.tobytes())'
563
+ out, status = Open3.capture2(@backend_bin, '-c', script, path, px_w.to_s, px_h.to_s, binmode: true)
564
+ return nil unless status.success? && out.bytesize >= px_w * px_h * 3
565
+
566
+ out
567
+ end
568
+
569
+ def decode_djpeg(path, px_w, px_h)
570
+ out, status = Open3.capture2(@backend_bin, '-rgb', path, binmode: true)
571
+ return nil unless status.success? && out.start_with?("P6\n")
572
+
573
+ header_match = out.match(/\AP6\s+(?:#[^\n]*\n\s*)*(\d+)\s+(\d+)\s+(\d+)\s/m)
574
+ return nil unless header_match
575
+
576
+ src_w = header_match[1].to_i
577
+ src_h = header_match[2].to_i
578
+ offset = header_match.end(0)
579
+ return nil if src_w <= 0 || src_h <= 0 || out.bytesize < offset + (src_w * src_h * 3)
580
+
581
+ downsample_rgb_aspect(out, offset, src_w, src_h, px_w, px_h)
582
+ end
583
+
584
+ def downsample_rgb_aspect(buf, offset, src_w, src_h, dst_w, dst_h)
585
+ scale = [dst_w.to_f / src_w, dst_h.to_f / src_h].min
586
+ fit_w = [(src_w * scale).round, 1].max
587
+ fit_h = [(src_h * scale).round, 1].max
588
+ pad_x = (dst_w - fit_w) / 2
589
+ pad_y = (dst_h - fit_h) / 2
590
+ bg_pixel = BG_RGB.pack('CCC')
591
+
592
+ result = String.new(encoding: Encoding::BINARY, capacity: dst_w * dst_h * 3)
593
+ dst_h.times do |y|
594
+ dst_w.times do |x|
595
+ if x < pad_x || x >= pad_x + fit_w || y < pad_y || y >= pad_y + fit_h
596
+ result << bg_pixel
597
+ else
598
+ sx = ((x - pad_x) * src_w) / fit_w
599
+ sy = ((y - pad_y) * src_h) / fit_h
600
+ pos = offset + (((sy * src_w) + sx) * 3)
601
+ result << buf.byteslice(pos, 3)
602
+ end
603
+ end
604
+ end
605
+ result
606
+ end
607
+
608
+ def render_from_rgb(rgb, width, height, video:)
609
+ return nil unless rgb && rgb.bytesize >= width * height * 2 * 3
610
+
611
+ stride = width * 3
612
+ Array.new(height) do |row|
613
+ top_off = (row * 2) * stride
614
+ bot_off = ((row * 2) + 1) * stride
615
+ line = +''
616
+
617
+ width.times do |x|
618
+ if video && row.zero? && width >= 6 && x >= width - 3
619
+ ch = x == width - 2 ? '▸' : ' '
620
+ line << @theme.paint(ch, color: :white, background: :pink, bold: true)
621
+ next
622
+ end
623
+
624
+ t_idx = top_off + (x * 3)
625
+ b_idx = bot_off + (x * 3)
626
+ tr = rgb.getbyte(t_idx)
627
+ tg = rgb.getbyte(t_idx + 1)
628
+ tb = rgb.getbyte(t_idx + 2)
629
+ br = rgb.getbyte(b_idx)
630
+ bg = rgb.getbyte(b_idx + 1)
631
+ bb = rgb.getbyte(b_idx + 2)
632
+ line << "\e[38;2;#{tr};#{tg};#{tb};48;2;#{br};#{bg};#{bb}m▀"
633
+ end
634
+ "#{line}\e[0m"
635
+ end
636
+ end
637
+
638
+ def detect_backend
639
+ if (bin = find_executable('ffmpeg'))
640
+ return [:ffmpeg, bin]
641
+ end
642
+ if (bin = find_executable('magick') || find_executable('convert'))
643
+ return [:magick, bin]
644
+ end
645
+ if (bin = find_executable('chafa'))
646
+ return [:chafa, bin]
647
+ end
648
+ if (bin = find_executable('python3')) && python_pil_available?(bin)
649
+ return [:python_pil, bin]
650
+ end
651
+ if (bin = find_executable('djpeg'))
652
+ return [:djpeg, bin]
653
+ end
654
+
655
+ [nil, nil]
656
+ end
657
+
658
+ def python_pil_available?(python_bin)
659
+ _out, status = Open3.capture2e(python_bin, '-c', 'from PIL import Image')
660
+ status.success?
661
+ rescue StandardError
662
+ false
663
+ end
664
+
665
+ def find_executable(name)
666
+ ENV['PATH'].to_s.split(File::PATH_SEPARATOR).each do |dir|
667
+ candidate = File.join(dir, name)
668
+ return candidate if File.executable?(candidate) && !File.directory?(candidate)
669
+ end
670
+ nil
671
+ end
672
+ end
673
+ end
674
+ end