forked from esaruoho/paketti
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPakettiAmigoInspect.lua
More file actions
2105 lines (1797 loc) · 78.8 KB
/
PakettiAmigoInspect.lua
File metadata and controls
2105 lines (1797 loc) · 78.8 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
--[[============================================================================
PakettiAmigoInspect.lua
Decode, Export, Import, and Modify Active Plugin Wavefile Pathname within ParameterChunk
This Renoise tool extends the original "Decode Active Plugin ParameterChunk" script
with functions to:
• extract (export) the embedded WAV file from an Amigo preset
• import a new WAV back into the active preset data
• read and display the embedded pathname
• override that pathname with a new one on disk
Uses macOS `plutil` and a local base64.lua module.
Prerequisites:
• base64.lua in the same folder
• macOS `plutil` on your PATH
After installation, restart Renoise and use under the Tools menu:
• Decode Active Plugin ParameterChunk
• Export Active Plugin Wavefile
• Import Active Plugin Wavefile
• Set Active Plugin Pathname
============================================================================]]--
-- Ensure bit32 is nil so base64 module uses its Lua 5.1 fallback
_G.bit32 = nil
-- Load base64 module
local ok64, base64 = pcall(require, "base64")
if not ok64 then
renoise.app():show_status("Error loading base64 module: " .. tostring(base64))
print("Error loading base64 module: " .. tostring(base64))
return
end
-- Debug-print helper - prints to both console and status bar
function pakettiAmigoDebug(msg, show_in_status)
print(msg)
if show_in_status then
renoise.app():show_status(msg)
end
end
-- Verify JUCE header structure
function pakettiAmigoVerifyJuceHeader(data)
-- Check minimum size
if #data < 8 then
return false, "Data too small for JUCE header"
end
-- Check magic
local magic = data:sub(1, 6)
if magic ~= "PARAMS" then
return false, string.format("Invalid magic: %q (expected 'PARAMS')", magic)
end
-- Check version in little-endian format
local version_lo = data:byte(7) -- First byte is low byte
local version_hi = data:byte(8) -- Second byte is high byte
local version = version_lo + version_hi * 256
pakettiAmigoDebug("\nVerifying JUCE header:")
pakettiAmigoDebug(string.format(" Magic: %s", magic))
pakettiAmigoDebug(string.format(" Version bytes: 0x%02X 0x%02X", version_lo, version_hi))
pakettiAmigoDebug(string.format(" Calculated version: %d", version))
-- If version bytes are reversed, swap them and recalculate
if version ~= 1 and version_hi == 1 and version_lo == 0 then
pakettiAmigoDebug(" Warning: Version bytes appear to be reversed")
version = 1 -- Force to version 1 since we know that's what it should be
end
if version ~= 1 then
return false, string.format("Unexpected version: %d (bytes: 0x%02X 0x%02X, expected 0x01 0x00)",
version, version_lo, version_hi)
end
-- Verify basic structure by looking for known entries
local found_entries = {}
local offset = 9
while offset < #data do
if offset + 8 > #data then break end
local id = data:sub(offset, offset + 7)
local clean_id = id:match("([%w]+)") -- Extract printable part
if clean_id then
table.insert(found_entries, clean_id)
end
offset = offset + 8
end
return true, {
magic = magic,
version = version,
entries = found_entries
}
end
-- Write raw data to a file
function pakettiAmigoWriteFile(path, data)
pakettiAmigoDebug("Writing file: " .. path .. " (" .. tostring(#data) .. " bytes)")
local f, err = io.open(path, "wb")
if not f then error("Cannot write file '" .. tostring(path) .. "': " .. tostring(err)) end
f:write(data)
f:close()
end
-- Convert binary plist to XML via plutil
function pakettiAmigoPlistToXml(bin_data)
pakettiAmigoDebug("Converting binary plist to XML")
local tmpbin = pakettiGetTempFilePath(".tmp")
local f = io.open(tmpbin, "wb")
if not f then error("Failed to open temp file") end
f:write(bin_data)
f:close()
local tmpxml = tmpbin .. ".xml"
local ok = os.execute(('plutil -convert xml1 -o "%s" "%s"'):format(tmpxml, tmpbin))
if ok ~= 0 then
os.remove(tmpbin)
error("plutil conversion failed")
end
local xf = io.open(tmpxml, "rb")
local xml = xf:read("*a")
xf:close()
os.remove(tmpbin)
os.remove(tmpxml)
pakettiAmigoDebug(" XML plist length: " .. tostring(#xml))
return xml
end
-- Extract and decode jucePluginState blob
function pakettiAmigoExtractJuceState(xml_plist)
pakettiAmigoDebug("Extracting jucePluginState data")
local pattern = "<key>%s*jucePluginState%s*</key>%s*<data>(.-)</data>"
local b64 = xml_plist:match(pattern)
if not b64 then error("jucePluginState <data> not found") end
pakettiAmigoDebug(" Base64 size: " .. tostring(#b64))
local state = base64.decode(b64)
pakettiAmigoDebug(" Decoded state size: " .. tostring(#state))
return state
end
-- Extract WAV data from state blob
function pakettiAmigoExtractWavFromState(state_blob)
pakettiAmigoDebug("Locating EMBEDDED_FILE marker")
local marker = "EMBEDDED_FILE"
local s, e = state_blob:find(marker, 1, true)
if not s then
error("NO_EMBEDDED_SAMPLE") -- Special error code we'll handle in the main function
end
pakettiAmigoDebug(" Marker at bytes " .. s .. "–" .. e)
local valid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
-- skip to first Base64 char after marker
local pos = e + 1
while pos <= #state_blob and not valid:find(state_blob:sub(pos,pos),1,true) do
pos = pos + 1
end
if pos > #state_blob then error("No Base64 payload after marker") end
local start_b64 = pos
while pos <= #state_blob and valid:find(state_blob:sub(pos,pos),1,true) do
pos = pos + 1
end
local wav_b64 = state_blob:sub(start_b64, pos-1)
pakettiAmigoDebug(" WAV Base64 length: " .. tostring(#wav_b64))
if #wav_b64 == 0 then error("Empty WAV payload") end
pakettiAmigoDebug(" Decoding WAV payload")
local wav_data = base64.decode(wav_b64)
pakettiAmigoDebug(" Decoded WAV size: " .. tostring(#wav_data))
return wav_data
end
-- Utility: hex dump a portion of data with ASCII representation
function pakettiAmigoHexDump(data, start, length)
local result = ""
local ascii = ""
for i = start, math.min(start + length - 1, #data) do
local byte = data:byte(i)
result = result .. string.format("%02X ", byte)
if byte >= 32 and byte <= 126 then
ascii = ascii .. string.char(byte)
else
ascii = ascii .. "."
end
if (i - start + 1) % 16 == 0 then
result = result .. " | " .. ascii .. "\n"
ascii = ""
end
end
if ascii ~= "" then
while #ascii < 16 do
result = result .. " "
ascii = ascii .. " "
end
result = result .. " | " .. ascii .. "\n"
end
return result
end
-- Utility: convert bytes to ASCII string if printable
function pakettiAmigoBytesToAscii(data, start, length)
local result = ""
for i = start, math.min(start + length - 1, #data) do
local byte = data:byte(i)
if byte >= 32 and byte <= 126 then
result = result .. string.char(byte)
else
result = result .. string.format("\\x%02X", byte)
end
end
return result
end
-- Read a little-endian integer from data
function pakettiAmigoReadLeInt(data, offset, size)
local val = 0
for i = 0, size - 1 do
val = val + data:byte(offset + i) * (256 ^ i) -- Little-endian: lowest byte first
end
pakettiAmigoDebug(string.format("Reading %d-byte LE int at offset %d:", size, offset))
for i = 0, size - 1 do
pakettiAmigoDebug(string.format(" Byte %d: 0x%02X", i, data:byte(offset + i)))
end
pakettiAmigoDebug(string.format(" Value: %d (0x%X)", val, val))
return val
end
-- Parse JUCE parameter chunk header and content
function pakettiAmigoParseJuceParams(chunk)
if not chunk or #chunk < 8 then return nil, "Chunk too small" end
local working_chunk = chunk
-- First convert binary plist to XML if needed
if working_chunk:sub(1,6) == "bplist" then
print("Debug: Converting binary plist to XML first...")
local tmpbin = pakettiGetTempFilePath(".tmp")
local tmpxml = tmpbin .. ".xml"
local ok, err = pcall(function()
-- Write binary file
local f = io.open(tmpbin, "wb")
if not f then error("Failed to create temporary binary file") end
f:write(working_chunk)
f:close()
-- Convert to XML
local plutil_result = os.execute(('plutil -convert xml1 -o "%s" "%s"'):format(tmpxml, tmpbin))
if plutil_result ~= 0 then
error("plutil conversion failed with code: " .. tostring(plutil_result))
end
-- Read XML file
local xf = io.open(tmpxml, "r")
if not xf then error("Failed to open converted XML file") end
local xmlc = xf:read("*a")
xf:close()
-- Clean up temp files
os.remove(tmpxml)
os.remove(tmpbin)
-- Look for JUCE state in plist
local juce_b64 = xmlc:match('<key>jucePluginState</key>%s*<data><!%[CDATA%[(.-)%]%]></data>') or
xmlc:match('<key>jucePluginState</key>%s*<data>(.-)</data>') or
xmlc:match('<key>data</key>%s*<data><!%[CDATA%[(.-)%]%]></data>') or
xmlc:match('<key>data</key>%s*<data>(.-)</data>')
if not juce_b64 then
print("Debug: XML content:")
print(xmlc:sub(1, 500)) -- Print first 500 chars to help diagnose
error("No JUCE plugin state found in plist")
end
-- Decode JUCE state
working_chunk = base64.decode(juce_b64)
if not working_chunk then
error("Failed to decode JUCE plugin state")
end
-- Verify we got JUCE data
if working_chunk:sub(1,6) ~= "PARAMS" then
print("Debug: First 64 bytes of decoded data:")
print(pakettiAmigoHexDump(working_chunk, 1, 64))
error("Invalid JUCE data (no PARAMS header)")
end
pakettiAmigoDebug(string.format("Successfully converted binary plist to JUCE data (%d bytes)", #working_chunk))
end)
-- Clean up in case of error
if not ok then
if tmpbin then os.remove(tmpbin) end
if tmpxml then os.remove(tmpxml) end
return nil, "Binary plist conversion failed: " .. tostring(err)
end
end
local info = {
magic = working_chunk:sub(1, 6), -- Should be "PARAMS"
version = working_chunk:byte(7) + working_chunk:byte(8) * 256, -- Version in little-endian
entries = {}
}
if info.magic ~= "PARAMS" then
return nil, "Not a JUCE parameter chunk (invalid magic)"
end
pakettiAmigoDebug("JUCE Parameter chunk:")
pakettiAmigoDebug(string.format(" Magic: %s", info.magic))
pakettiAmigoDebug(string.format(" Version bytes: 0x%02X 0x%02X", working_chunk:byte(7), working_chunk:byte(8)))
pakettiAmigoDebug(string.format(" Version: %d", info.version))
-- First scan for metadata to build path lookup table
local path_lookup = {}
local offset = 9
while offset < #working_chunk do
if offset + 8 > #working_chunk then break end
local id = working_chunk:sub(offset, offset + 7)
local clean_id = id:match("metadata")
if clean_id then
offset = offset + 8
if offset + 4 > #working_chunk then break end
local version = pakettiAmigoReadLeInt(working_chunk, offset, 2)
offset = offset + 2
if offset + 2 > #working_chunk then break end
local length = pakettiAmigoReadLeInt(working_chunk, offset, 2)
offset = offset + 2
if offset + length > #working_chunk then break end
local data = working_chunk:sub(offset, offset + length - 1)
pakettiAmigoDebug("\nFound metadata entry:")
pakettiAmigoDebug(" First 128 bytes of metadata:")
pakettiAmigoDebug(pakettiAmigoHexDump(data, 1, 128))
-- Look for paths in metadata
local pos = 1
while pos <= #data do
local null_pos = data:find("\0", pos)
if not null_pos then break end
local str = data:sub(pos, null_pos - 1)
if str:match("%.wav$") or str:match("%.WAV$") then
table.insert(path_lookup, str)
pakettiAmigoDebug(string.format(" Found path in metadata: %q", str))
end
pos = null_pos + 1
end
offset = offset + length
else
offset = offset + 8
end
end
pakettiAmigoDebug("\nFound paths in lookup table:")
for i, path in ipairs(path_lookup) do
pakettiAmigoDebug(string.format(" [%d] %q", i, path))
end
-- Now parse the actual entries
offset = 9
while offset < #working_chunk do
if offset + 8 > #working_chunk then break end
-- Try to read the ID, handling potential binary data
local raw_id = working_chunk:sub(offset, offset + 7)
local id = raw_id:match("pathnam?e?") or raw_id:match("jucedata") or raw_id:match("metadata")
if id then
offset = offset + 8
local entry = { id = id, offset = offset - 8 }
table.insert(info.entries, entry)
if id:match("pathnam?e?") then
-- version (2 bytes), length (1), flag (1), then path string
if offset + 4 > #working_chunk then break end
entry.version = pakettiAmigoReadLeInt(working_chunk, offset, 2)
offset = offset + 2
entry.length = working_chunk:byte(offset)
offset = offset + 1
entry.flag = working_chunk:byte(offset)
offset = offset + 1
-- Enhanced path extraction with detailed debugging
pakettiAmigoDebug(string.format("\nPathname entry details at offset %d:", entry.offset))
pakettiAmigoDebug(string.format(" Raw ID bytes: %s", pakettiAmigoHexDump(raw_id, 1, 8):match("(.-)\n")))
pakettiAmigoDebug(string.format(" Version: %d (0x%04X)", entry.version, entry.version))
pakettiAmigoDebug(string.format(" Length: %d bytes", entry.length))
pakettiAmigoDebug(string.format(" Flag: %d (0x%02X)", entry.flag, entry.flag))
if offset + entry.length > #working_chunk then break end
-- Show raw path bytes before extraction
local raw_path_bytes = working_chunk:sub(offset, offset + entry.length - 1)
pakettiAmigoDebug(" Raw path bytes:")
pakettiAmigoDebug(pakettiAmigoHexDump(raw_path_bytes, 1, entry.length))
-- Handle special flag values
if entry.flag == 0x19 then
-- This is a special flag indicating a path index followed by the actual path
local path_index = working_chunk:byte(offset)
pakettiAmigoDebug(string.format(" Special path index: %d", path_index))
-- Look for the actual path after the index
-- Find the next null-terminated string
local path_start = offset + 1
local path_end = working_chunk:find("\0", path_start) or #working_chunk
local full_path = working_chunk:sub(path_start, path_end - 1)
pakettiAmigoDebug(string.format(" Found path after index: %q", full_path))
-- Extract just the filename
local filename = full_path:match("[^/\\]+$") or full_path
pakettiAmigoDebug(string.format(" Extracted filename: %q", filename))
entry.path = filename
entry.full_path = full_path
entry.path_index = path_index
-- Update offset to skip both the index and the path
offset = path_end + 1
elseif entry.flag == 0x3C then
-- This is another special flag indicating a path index that needs lookup
local path_index = working_chunk:byte(offset)
pakettiAmigoDebug(string.format(" Special path index: %d", path_index))
-- Look up the path in our collected paths
if path_lookup[path_index] then
local full_path = path_lookup[path_index]
local filename = full_path:match("[^/\\]+$") or full_path
entry.path = filename
entry.full_path = full_path
pakettiAmigoDebug(string.format(" Found path in lookup table: %q", full_path))
pakettiAmigoDebug(string.format(" Extracted filename: %q", filename))
else
-- Try to find the path before EMBEDDED_FILE marker
local marker = "EMBEDDED_FILE"
local s, e = working_chunk:find(marker, 1, true)
if s then
pakettiAmigoDebug(string.format("\nFound EMBEDDED_FILE marker at offset %d", s))
pakettiAmigoDebug("Context around marker:")
pakettiAmigoDebug(pakettiAmigoHexDump(working_chunk, math.max(1, s - 64), 128))
-- Look backwards from EMBEDDED_FILE for the path
local before = working_chunk:sub(1, s-1)
-- Find the last null byte before EMBEDDED_FILE
local last_null = before:reverse():find("\0")
if last_null then
-- Now look for the path - it starts with a slash
local path_start = before:find("/[^%z]*%.%w+%z$")
if path_start then
local full_path = before:sub(path_start, #before - 1) -- -1 to remove trailing null
pakettiAmigoDebug(string.format(" Found complete path: %q", full_path))
-- Extract just the filename
local filename = full_path:match("[^/]+$")
pakettiAmigoDebug(string.format(" Extracted filename: %q", filename))
entry.path = filename
entry.full_path = full_path
end
end
end
if not entry.path or entry.path == "" then
pakettiAmigoDebug(" Warning: Could not find path for index " .. path_index)
entry.path = string.format("<unknown_path_%d>", path_index)
end
end
entry.path_index = path_index
offset = offset + entry.length
else
-- Normal path string extraction
local path_chars = {}
for i = 1, entry.length do
local byte = working_chunk:byte(offset + i - 1)
if byte >= 32 and byte <= 126 then -- Printable ASCII
table.insert(path_chars, string.char(byte))
else
-- For non-printable characters, use hex representation
table.insert(path_chars, string.format("\\x%02X", byte))
end
end
entry.path = table.concat(path_chars)
offset = offset + entry.length
end
pakettiAmigoDebug(string.format(" Final path value: %q", entry.path))
elseif id == "jucedata" or id == "metadata" then
-- both store: version (2), length (2), then data
if offset + 4 > #working_chunk then break end
entry.version = pakettiAmigoReadLeInt(working_chunk, offset, 2)
offset = offset + 2
entry.length = pakettiAmigoReadLeInt(working_chunk, offset, 2)
offset = offset + 2
if offset + entry.length > #working_chunk then break end
entry.data = working_chunk:sub(offset, offset + entry.length - 1)
offset = offset + entry.length
end
else
-- Try to resync by looking for next known pattern
local found = false
for i = offset + 1, math.min(offset + 32, #working_chunk - 8) do
local next_bytes = working_chunk:sub(i, i + 7)
if next_bytes:match("pathnam?e?") or next_bytes:match("jucedata") or next_bytes:match("metadata") then
offset = i
found = true
break
end
end
if not found then offset = offset + 8 end
end
end
return info
end
-- Inspect chunk entries
function pakettiAmigoInspectChunkEntries(chunk)
local offset = 9 -- Start after PARAMS header
local entries = {}
while offset < #chunk do
if offset + 8 > #chunk then break end
-- Get the raw ID bytes and try to interpret them
local raw_id = chunk:sub(offset, offset + 7)
pakettiAmigoDebug("\nFound entry at offset " .. offset)
pakettiAmigoDebug("Raw ID bytes: " .. pakettiAmigoHexDump(raw_id, 1, 8))
-- Try to read version and length
if offset + 12 <= #chunk then
local version = chunk:byte(offset + 8) * 256 + chunk:byte(offset + 9)
local length = chunk:byte(offset + 10) * 256 + chunk:byte(offset + 11)
pakettiAmigoDebug(string.format("Version: %d (0x%04X)", version, version))
pakettiAmigoDebug(string.format("Length: %d bytes", length))
-- Show some data bytes
if offset + 12 + length <= #chunk then
local data = chunk:sub(offset + 12, offset + 12 + math.min(32, length) - 1)
pakettiAmigoDebug("First bytes of data:")
pakettiAmigoDebug(pakettiAmigoHexDump(data, 1, #data))
end
table.insert(entries, {
offset = offset,
raw_id = raw_id,
version = version,
length = length
})
offset = offset + 12 + length
else
offset = offset + 8
end
end
return entries
end
-- Parse WAV header info from a given position
function pakettiAmigoParseWavHeader(chunk, pos)
if #chunk < pos + 44 then return nil, "Insufficient data for WAV header" end
local function read_le(offset, size)
local v = 0
for i = 0, size - 1 do
v = v + chunk:byte(pos + offset + i) * (256 ^ i)
end
return v
end
return {
chunk_id = chunk:sub(pos, pos + 3),
chunk_size = read_le(4, 4),
format = chunk:sub(pos + 8, pos + 11),
fmt_chunk_id = chunk:sub(pos + 12, pos + 15),
fmt_chunk_size = read_le(16, 4),
audio_format = read_le(20, 2),
num_channels = read_le(22, 2),
sample_rate = read_le(24, 4),
byte_rate = read_le(28, 4),
block_align = read_le(32, 2),
bits_per_sample= read_le(34, 2),
}
end
-- Extract the raw binary plist from the active preset data
function pakettiAmigoGetRawPlist()
local song = renoise.song()
local dev = song.selected_instrument.plugin_properties.plugin_device
local xml = dev.active_preset_data
if not xml or xml == "" then
return nil, "No active preset data found."
end
local b64 = xml:match('<ParameterChunk><!%[CDATA%[(.-)%]%]></ParameterChunk>')
if not b64 then
return nil, "<ParameterChunk> not found in preset data."
end
return base64.decode(b64)
end
-- Main functions
function pakettiAmigoDecodeActiveParameterChunk()
local raw, err = pakettiAmigoGetRawPlist()
if not raw then
renoise.app():show_status(err)
print(err)
return
end
-- Convert raw plist to XML for inspection
local tmpbin = pakettiGetTempFilePath(".tmp")
do local f = io.open(tmpbin, "wb") f:write(raw) f:close() end
local tmpxml = tmpbin .. ".xml"
if os.execute(('plutil -convert xml1 -o "%s" "%s"'):format(tmpxml, tmpbin)) ~= 0 then
renoise.app():show_status("Failed converting plist to XML.")
print("Failed converting plist to XML.")
os.remove(tmpbin)
return
end
local xmlc = io.open(tmpxml, "r"):read("*a")
os.remove(tmpxml) os.remove(tmpbin)
-- Known keys to search
local keys = { "AudioFileData", "attachment", "jucePluginState" }
local foundAny = false
for _, key in ipairs(keys) do
local data_b64 = xmlc:match('<key>' .. key .. '</key>%s*<data>(.-)</data>')
if data_b64 then
foundAny = true
local chunk = base64.decode(data_b64)
print(string.format("\nAnalyzing chunk '%s', size: %d bytes", key, #chunk))
print("First 64 bytes:") print(pakettiAmigoHexDump(chunk, 1, 64))
if key == "jucePluginState" then
local info, perr = pakettiAmigoParseJuceParams(chunk)
if not info then
print("Error parsing JUCE parameters: " .. tostring(perr))
else
print("\nJUCE Parameter Chunk Analysis:")
print(string.format(" Magic: %s", info.magic))
print(string.format(" Version: %d", info.version))
print("\nEntries found:")
for i, entry in ipairs(info.entries) do
print(string.format("\nEntry %d: '%s' at offset %d", i, entry.id, entry.offset))
if entry.length then
print(string.format(" Length: %d bytes", entry.length))
end
if entry.path then
print(string.format(" Path: %s", entry.path))
renoise.app():show_status("Found pathname: " .. entry.path)
print("Found pathname: " .. entry.path)
end
if entry.preview then
print(" Preview of data:")
print(pakettiAmigoHexDump(entry.preview, 1, #entry.preview))
end
end
-- Scan for RIFF/WAV blocks
local pos = 1
while true do
pos = chunk:find("RIFF", pos, true)
if not pos then break end
print(string.format("\nFound RIFF at offset %d", pos - 1))
print("Context:") print(pakettiAmigoHexDump(chunk, math.max(1, pos - 16), 64))
local winfo, werr = pakettiAmigoParseWavHeader(chunk, pos)
if winfo then
print("\nWAV Header:")
print(string.format(" Sample Rate: %d Hz", winfo.sample_rate))
-- Extract WAV
local endpos = pos + 8 + winfo.chunk_size - 1
local wavseg = chunk:sub(pos, math.min(endpos, #chunk))
local wavfile = pakettiGetTempFilePath(".wav")
local wf = io.open(wavfile, "wb"); wf:write(wavseg); wf:close()
print("Extracted WAV to: " .. wavfile)
else
print("Error parsing WAV header: " .. tostring(werr))
end
pos = pos + 1
end
end
end
end
end
if not foundAny then
renoise.app():show_status("No known data chunks found.")
print("No known data chunks found.")
end
end
-- Helper function to check if Amigo is available and loaded
function pakettiAmigoIsAvailable()
local song = renoise.song()
local inst = song.selected_instrument
-- First check: Is there even a plugin loaded?
if not inst.plugin_properties or not inst.plugin_properties.plugin_loaded then
renoise.app():show_status("There is no Amigo available in the current Instrument, doing nothing.")
return false
end
local device = inst.plugin_properties.plugin_device
-- Debug output to help diagnose any issues
print("Found plugin device:")
print(" Short name: " .. tostring(device.short_name))
print(" Name: " .. tostring(device.name))
-- Most reliable check: short_name should be "Amigo" for both AU and VST3
if device.short_name ~= "Amigo" then
renoise.app():show_status("There is no Amigo available in the current Instrument, doing nothing.")
return false
end
return true, device
end
-- Load embedded WAV into a new sample slot
function pakettiAmigoLoadIntoSample()
print ("--------------------------------")
local ok, err = pcall(function()
-- Check if Amigo is available
local is_available, device = pakettiAmigoIsAvailable()
if not is_available then return end
-- If we get here, we definitely have Amigo loaded
print("Confirmed Amigo plugin detected, proceeding with sample extraction...")
-- unpack
local raw_plist = pakettiAmigoGetRawPlist()
if not raw_plist then error("Failed to get raw plist") end
local xml_plist = pakettiAmigoPlistToXml(raw_plist)
local juce_bin = pakettiAmigoExtractJuceState(xml_plist)
local wav_data = pakettiAmigoExtractWavFromState(juce_bin)
-- Extract filename from preset data
pakettiAmigoDebug("Step 5: Extracting filename from preset data")
local info = pakettiAmigoParseJuceParams(juce_bin)
local filename = "Amigo Sample Export" -- Better default name
if info then
-- Look for pathname entry
for _, entry in ipairs(info.entries) do
if entry.id:match("pathnam?e?") then
pakettiAmigoDebug("\nFound pathname entry:")
pakettiAmigoDebug(string.format(" ID: %s", entry.id))
pakettiAmigoDebug(string.format(" Flag: 0x%02X", entry.flag))
pakettiAmigoDebug(string.format(" Path: %q", entry.path))
if entry.path and entry.path ~= "" and entry.path ~= "\\x05" then
-- Use the full filename including extension
filename = entry.path
pakettiAmigoDebug(string.format(" Using filename: %q", filename))
else
pakettiAmigoDebug(string.format(" Invalid filename detected, using default: %q", filename))
end
break
end
end
end
-- write to temp
pakettiAmigoDebug("Step 6: Writing temp WAV file")
local tmp_path = pakettiGetTempFilePath(".wav")
pakettiAmigoWriteFile(tmp_path, wav_data)
-- lookup the selected sample in the selected instrument
pakettiAmigoDebug("Step 7: Loading into selected sample")
-- Inject default XRNI settings before loading the sample
renoise.song():insert_instrument_at(renoise.song().selected_instrument_index+1)
renoise.song().selected_instrument_index = renoise.song().selected_instrument_index+1
pakettiPreferencesDefaultInstrumentLoader()
local song=renoise.song()
local inst_index = song.selected_instrument_index
local inst = song.instruments[inst_index]
-- Insert new sample at index 1
inst:insert_sample_at(1)
song.selected_sample_index = 1
local samp_index = song.selected_sample_index
local samp = inst.samples[samp_index]
if not samp then
error(("No sample %d in instrument %d"):format(samp_index, inst_index))
end
-- Set names from extracted filename
inst.name = filename
samp.name = filename
-- load into the sample buffer
local success, msg = samp.sample_buffer:load_from(tmp_path)
if not success then
error("Sample load failed: " .. tostring(msg))
end
local num_samples = #inst.samples
if num_samples > 0 and inst.samples[num_samples].name == "Placeholder sample" then
inst:delete_sample_at(num_samples)
end
pakettiAmigoDebug("Sample loaded successfully from: " .. tmp_path)
pakettiAmigoDebug(string.format("Named instrument and sample: %q", filename))
end)
if not ok then
if type(err) == "string" then
if err:find("NO_EMBEDDED_SAMPLE") then
renoise.app():show_status("This instance of Amigo does not have an Embedded Sample - Please click on Embed in the Amigo interface and then try to export the Sample again.")
else
renoise.app():show_status(err)
end
else
renoise.app():show_status("An error occurred while processing")
end
print("Error: " .. tostring(err))
end
end
-- Helper function to find full path in JUCE data
function pakettiAmigoFindFullPath(chunk)
print("\nSearching for full path in JUCE data...")
-- First check if we have valid JUCE data
if #chunk < 8 or chunk:sub(1, 6) ~= "PARAMS" then
print("Not valid JUCE data (no PARAMS header)")
return nil
end
-- Look for path patterns in the first 1024 bytes (where header info usually is)
local search_area = chunk:sub(1, math.min(1024, #chunk))
print("Searching first 1024 bytes for path pattern")
print("First 64 bytes of search area:")
print(pakettiAmigoHexDump(search_area, 1, 64))
-- Look for /Users/ path pattern
local path_start = search_area:find("/Users/[^%z]+%.wav", 1, false)
if path_start then
-- Find the end of the path (null terminator or .wav extension)
local path_end = search_area:find("%.wav", path_start) + 4
local full_path = search_area:sub(path_start, path_end)
print("Found path:", full_path)
return full_path
end
-- If not found in header, look near EMBEDDED_FILE marker
local marker = "EMBEDDED_FILE"
local marker_pos = chunk:find(marker, 1, true)
if marker_pos then
print("Found EMBEDDED_FILE marker at position", marker_pos)
-- Look in 512 bytes before the marker
local before_marker = chunk:sub(math.max(1, marker_pos - 512), marker_pos - 1)
-- Look for the last path-like string before the marker
local last_path
local pos = 1
while true do
local next_path = before_marker:match("/[^%z]+%.wav", pos)
if not next_path then break end
last_path = next_path
pos = before_marker:find(next_path, pos) + 1
end
if last_path then
print("Found path before marker:", last_path)
return last_path
end
end
print("No path found using direct search methods")
-- Last resort: try to find any path-like pattern in the whole chunk
local paths = {}
local pos = 1
while pos < #chunk do
local path = chunk:match("/[^%z]+%.wav", pos)
if not path then break end
table.insert(paths, path)
pos = chunk:find(path, pos) + 1
end
if #paths > 0 then
print("Found", #paths, "potential paths:")
for i, path in ipairs(paths) do
print(i .. ":", path)
end
-- Return the most likely path (usually the first one in the JUCE data)
return paths[1]
end
print("No paths found in JUCE data")
return nil
end
-- Open the folder containing the sample file from the active preset
function pakettiAmigoOpenSamplePath()
print ("--------------------------------")
print("Starting pakettiAmigoOpenSamplePath...")
local ok, err = pcall(function()
-- Check if Amigo is available
local is_available, device = pakettiAmigoIsAvailable()
if not is_available then return end
print("\nDevice info:")
print(" Name:", device.name)
print(" Short name:", device.short_name)
-- Get the raw plist data
print("\nGetting raw plist data...")
local raw_plist = pakettiAmigoGetRawPlist()
if not raw_plist then
print("Failed to get raw plist")
error("Failed to get raw plist")
end
print("Raw plist size:", #raw_plist, "bytes")
print("First 64 bytes of raw plist:")
print(pakettiAmigoHexDump(raw_plist, 1, 64))
print("\nConverting plist to XML...")
local xml_plist = pakettiAmigoPlistToXml(raw_plist)
print("XML plist size:", #xml_plist, "bytes")
print("\nExtracting JUCE state...")
local juce_bin = pakettiAmigoExtractJuceState(xml_plist)
print("JUCE binary size:", #juce_bin, "bytes")
print("First 64 bytes of JUCE data:")
print(pakettiAmigoHexDump(juce_bin, 1, 64))
-- Try to find the full path using our new function
local full_path = pakettiAmigoFindFullPath(juce_bin)
if full_path then
-- Extract the directory path
local dir_path = full_path:match("(.+)[/\\][^/\\]+$")
if dir_path then
print("\nOpening folder:", dir_path)
renoise.app():open_path(dir_path)
else
print("Could not extract directory path from:", full_path)
error("Could not extract directory path from: " .. full_path)
end
else
print("\nNo valid path found in preset data")
error("NO_PATH_FOUND")
end
end)
if not ok then
if type(err) == "string" then
if err:find("NO_PATH_FOUND") then
print("Error: No sample path found in the current Amigo preset")
renoise.app():show_status("No sample path found in the current Amigo preset.")
else
print("Error:", err)
renoise.app():show_status(err)
end
else
print("Error:", tostring(err))
renoise.app():show_status("There is no Amigo available in the current Instrument, doing nothing.")
end
end
end
-- Export the selected sample into Amigo as its embedded WAV
function pakettiAmigoExportSampleToAmigo()
print ("--------------------------------")
local ok, err = pcall(function()
-- Check if Amigo is available
local is_available, device = pakettiAmigoIsAvailable()
if not is_available then return end
local song = renoise.song()
local sample = song.selected_sample
if not sample then
error("No sample selected")
end
if not sample.sample_buffer.has_sample_data then
error("Selected sample has no audio data")
end
-- Print original sample details
local original_frames = sample.sample_buffer.number_of_frames
local original_channels = sample.sample_buffer.number_of_channels
local original_bits = sample.sample_buffer.bit_depth
local original_rate = sample.sample_buffer.sample_rate
pakettiAmigoDebug("Original Renoise sample details:", true)
pakettiAmigoDebug(string.format(" Name: %s", sample.name), true)
pakettiAmigoDebug(string.format(" Frames: %d", original_frames), true)
pakettiAmigoDebug(string.format(" Channels: %d", original_channels), true)
pakettiAmigoDebug(string.format(" Bit depth: %d", original_bits), true)
pakettiAmigoDebug(string.format(" Sample rate: %d", original_rate), true)
-- Save to temporary WAV
local tmp_path = pakettiGetTempFilePath(".wav")
pakettiAmigoDebug(string.format("\nSaving temporary WAV to: %s", tmp_path), true)