forked from Lab-Lab-Lab/CPR-Music
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTakesImportModal.js
More file actions
306 lines (263 loc) Β· 10.7 KB
/
TakesImportModal.js
File metadata and controls
306 lines (263 loc) Β· 10.7 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
// components/audio/DAW/Multitrack/TakesImportModal.js
'use client';
import { useState, useEffect } from 'react';
import { Modal, Button, ListGroup, Form, Badge } from 'react-bootstrap';
import { FaFileAudio, FaClock, FaMusic } from 'react-icons/fa';
import { useMultitrack } from '../../../../contexts/MultitrackContext';
import { getAudioProcessor } from './AudioProcessor';
export default function TakesImportModal({ show, onHide, takes = [] }) {
const { addTrack, updateTrack } = useMultitrack();
const [selectedTake, setSelectedTake] = useState(null);
const [trackName, setTrackName] = useState('');
const [resolvedDurations, setResolvedDurations] = useState({});
// Resolve durations for takes that report 0 when the modal opens
useEffect(() => {
if (!show || takes.length === 0) return;
takes.forEach((take) => {
if (take.duration > 0 || !take.audioURL || resolvedDurations[take.id] != null) return;
const audio = new Audio();
audio.preload = 'metadata';
audio.onloadedmetadata = () => {
if (audio.duration && isFinite(audio.duration)) {
setResolvedDurations((prev) => ({ ...prev, [take.id]: audio.duration }));
}
};
audio.src = take.audioURL;
});
}, [show, takes]);
// Update track name when take is selected
useEffect(() => {
if (selectedTake) {
// Generate default name from take info
const takeName =
selectedTake.name ||
`${selectedTake.partType} - Take ${selectedTake.takeNumber}`;
setTrackName(takeName);
}
}, [selectedTake]);
const handleImport = async () => {
if (!selectedTake || !selectedTake.audioURL) return;
console.log('π₯ TakesImportModal: Importing take:', selectedTake);
try {
let finalURL = selectedTake.audioURL;
// Web Workers can't resolve relative URLs (no page base URL context).
// Convert to absolute so both the AudioProcessor worker and main-thread
// fallback can fetch the resource.
if (finalURL.startsWith('/')) {
finalURL = `${window.location.origin}${finalURL}`;
}
// For blob URLs, we might need to ensure they're still valid
if (selectedTake.audioURL.startsWith('blob:')) {
console.log('π TakesImportModal: Refreshing blob URL for take');
const response = await fetch(selectedTake.audioURL);
if (response.ok) {
const blob = await response.blob();
finalURL = URL.createObjectURL(blob);
console.log('β
TakesImportModal: Blob URL refreshed');
} else {
throw new Error('Blob URL expired');
}
}
// Create immediate placeholder clip
const clipId = `clip-take-${selectedTake.id}-${Date.now()}`;
const placeholderClip = {
id: clipId,
start: 0,
duration: 0, // Will update when processed
color: '#7bafd4',
src: finalURL,
offset: 0,
name: trackName || 'Imported Take',
isLoading: true,
loadingState: 'reading'
};
// Add track immediately with placeholder - UI stays responsive!
// Creates an Audio track (with recording + import capabilities)
const newTrack = addTrack({
type: 'audio', // Explicitly create Audio track (enhanced with recording capabilities)
name: trackName || 'Imported Take',
audioURL: finalURL,
takeId: selectedTake.id,
clips: [placeholderClip],
});
console.log('π΅ TakesImportModal: Track created immediately with ID:', newTrack.id);
// Close modal immediately - track is already visible
setSelectedTake(null);
setTrackName('');
onHide();
// Process in background - Try AudioProcessor first, fallback to old method
console.log('π TakesImportModal: Starting background processing for take');
try {
const audioProcessor = getAudioProcessor();
// Check if AudioProcessor is available and working
if (audioProcessor && typeof audioProcessor.processAudioFile === 'function') {
console.log('π TakesImportModal: Using AudioProcessor for take processing');
const result = await audioProcessor.processAudioFile(
finalURL,
clipId,
(stage, progress) => {
console.log(`π TakesImportModal: Background processing ${stage}: ${progress}%`);
// Update clip loading state in real-time
updateTrack(newTrack.id, (prevTrack) => ({
...prevTrack,
clips: prevTrack.clips.map(clip =>
clip.id === clipId
? { ...clip, loadingState: stage }
: clip
)
}));
}
);
console.log(`β
TakesImportModal: Background processing complete using ${result.method}`);
// Update clip with final data
const finalClip = {
...placeholderClip,
duration: result.duration,
sourceDuration: result.duration, // total buffer length for trim clamping
isLoading: false,
loadingState: 'complete',
processingMethod: result.method
};
updateTrack(newTrack.id, {
clips: [finalClip]
});
console.log(`π TakesImportModal: Take import fully complete - duration: ${result.duration?.toFixed(2)}s`);
} else {
throw new Error('AudioProcessor not available, falling back to legacy method');
}
} catch (bgErr) {
console.warn('π TakesImportModal: AudioProcessor failed, trying fallback method:', bgErr.message);
// Fallback to original decodeAudioFromURL approach
try {
console.log('π TakesImportModal: Using fallback audio processing');
// Import fallback function
const { decodeAudioFromURL } = await import('./AudioEngine');
const audioBuffer = await decodeAudioFromURL(finalURL);
const duration = audioBuffer ? audioBuffer.duration : 0;
// Update clip with final data (fallback version)
const finalClip = {
...placeholderClip,
duration: duration,
sourceDuration: duration, // total buffer length for trim clamping
isLoading: false,
loadingState: 'complete',
processingMethod: 'fallback'
};
updateTrack(newTrack.id, {
clips: [finalClip]
});
console.log(`β
TakesImportModal: Fallback processing complete - duration: ${duration?.toFixed(2)}s`);
} catch (fallbackErr) {
console.error('β TakesImportModal: Both AudioProcessor and fallback failed:', fallbackErr);
// Update clip to show error state
updateTrack(newTrack.id, (prevTrack) => ({
...prevTrack,
clips: prevTrack.clips.map(clip =>
clip.id === clipId
? { ...clip, isLoading: false, loadingState: 'error', hasError: true }
: clip
)
}));
}
}
} catch (err) {
console.error('β TakesImportModal: Take import failed:', err);
alert('Failed to import take: ' + err.message);
}
};
const formatDuration = (seconds) => {
if (!seconds) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
};
const formatDate = (dateString) => {
if (!dateString) return 'Unknown';
const date = new Date(dateString);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};
// Mock data for testing if no takes provided
const displayTakes = takes.length > 0 ? takes : [];
console.log('πΉ TakesImportModal: Received takes:', takes);
console.log('πΉ TakesImportModal: Display takes:', displayTakes);
// Show helpful message if no takes
if (displayTakes.length === 0 && takes.length === 0) {
console.log('No takes available in TakesImportModal');
}
return (
<Modal show={show} onHide={onHide} size="lg" className="takes-import-modal">
<Modal.Header closeButton className="bg-dark text-white">
<Modal.Title>
<FaFileAudio className="me-2" />
Import Take to Multitrack
</Modal.Title>
</Modal.Header>
<Modal.Body className="bg-dark">
{displayTakes.length === 0 ? (
<div className="text-center text-muted py-5">
<p>No takes available. Record some takes first!</p>
</div>
) : (
<>
<h6 className="text-white mb-3">Select a take to import:</h6>
<ListGroup className="mb-3">
{displayTakes.map((take) => (
<ListGroup.Item
key={take.id}
action
active={selectedTake?.id === take.id}
onClick={() => setSelectedTake(take)}
className="d-flex justify-content-between align-items-center"
>
<div>
<div className="fw-bold">
<FaMusic className="me-2" />
{take.name ||
`${take.partType} - Take ${take.takeNumber}`}
</div>
<small className="text-muted">
<FaClock className="me-1" />
{formatDuration(resolvedDurations[take.id] ?? take.duration)} β’{' '}
{formatDate(take.createdAt)}
</small>
</div>
<div>
<Badge
bg={take.partType === 'melody' ? 'primary' : 'secondary'}
>
{take.partType}
</Badge>
</div>
</ListGroup.Item>
))}
</ListGroup>
{selectedTake && (
<Form.Group className="mb-3">
<Form.Label className="text-white">Track Name:</Form.Label>
<Form.Control
type="text"
value={trackName}
onChange={(e) => setTrackName(e.target.value)}
placeholder="Enter track name"
className="bg-dark text-white"
/>
</Form.Group>
)}
</>
)}
</Modal.Body>
<Modal.Footer className="bg-dark">
<Button variant="secondary" onClick={onHide}>
Cancel
</Button>
<Button
variant="primary"
onClick={handleImport}
disabled={!selectedTake}
>
Import Take
</Button>
</Modal.Footer>
</Modal>
);
}