forked from audacity/audacity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportQT.cpp
More file actions
542 lines (448 loc) · 15.3 KB
/
Copy pathImportQT.cpp
File metadata and controls
542 lines (448 loc) · 15.3 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
/**********************************************************************
Audacity: A Digital Audio Editor
ImportQT.cpp
Joshua Haberman
On OS X, handles import of MPEG-4 audio including AAC and Apple
Lossless, import of audio from MPEG-4 video files, and import of
AIF(F)/AIFC files (AIF(F) might contain content libsndfile can't
handle). Could be modified to support QuickTime import on Windows.
**********************************************************************/
#include "../Audacity.h" // for USE_* macros
#include "Import.h"
#include "ImportPlugin.h"
#include "../widgets/AudacityMessageBox.h"
#include "../widgets/ProgressDialog.h"
#define DESC XO("QuickTime files")
static const auto exts = {
wxT("aif"),
wxT("aifc"),
wxT("aiff"),
wxT("mov"),
wxT("aac"),
wxT("m4a"),
wxT("mp4")
};
#if defined(__WXMAC__)
#undef USE_QUICKTIME
#endif
#ifndef USE_QUICKTIME
// Bug 2068: misleading error message about QuickTime
// In 64 bit versions we cannot compile in (obsolete) QuickTime
// So don't register the QuickTime extensions, so ensuring we never report
// "This version of Audacity was not compiled with QuickTime files support"
// When attempting to import MP4 files.
/*
static Importer::RegisteredUnusableImportPlugin registered{
std::make_unique<UnusableImportPlugin>(DESC,
FileExtensions( exts.begin(), exts.end() ) )
};
*/
#else /* USE_QUICKTIME */
// There's a name collision between our Track and QuickTime's...workaround it
#define Track XTrack
#if defined(__WXMAC__)
// These get used when building under OSX
#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>
#include <wx/osx/core/private.h>
#else
// These get used when building under Windows
#include <ConditionalMacros.h>
#include <Movies.h>
#include <QuickTimeComponents.h>
#include <Sound.h>
#include <Folders.h>
#include <ToolUtils.h>
#include <Gestalt.h>
#include <Navigation.h>
#endif
// There's a name collision between our Track and QuickTime's...workaround it
#undef Track
#include "../Tags.h"
#include "../WaveTrack.h"
#define kQTAudioPropertyID_MaxAudioSampleSize 'mssz'
class QTImportPlugin final : public ImportPlugin
{
public:
QTImportPlugin()
: ImportPlugin( FileExtensions( exts.begin(), exts.end() ) ),
mInitialized(false)
{
OSErr err = noErr;
#if defined(__WXMSW__)
err = ::InitializeQTML(0);
#endif
if (err == noErr) {
err = ::EnterMovies();
if (err == noErr) {
mInitialized = true;
}
else {
#if defined(__WXMSW__)
TerminateQTML();
#endif
}
}
}
~QTImportPlugin()
{
if (mInitialized) {
ExitMovies();
#if defined(__WXMSW__)
TerminateQTML();
#endif
}
mInitialized = false;
}
wxString GetPluginStringID() override { return wxT("quicktime"); }
TranslatableString GetPluginFormatDescription() override;
std::unique_ptr<ImportFileHandle> Open(
const wxString & Filename, AudacityProject*) override;
private:
bool mInitialized;
};
class QTImportFileHandle final : public ImportFileHandle
{
public:
QTImportFileHandle(const wxString & name, Movie movie)
: ImportFileHandle(name)
{
mMovie = movie;
}
virtual ~QTImportFileHandle()
{
if (mMovie) {
DisposeMovie(mMovie);
mMovie = NULL;
}
}
TranslatableString GetFileDescription() override;
ByteCount GetFileUncompressedBytes() override;
wxInt32 GetStreamCount() override
{
return 1;
}
const TranslatableStrings &GetStreamInfo() override
{
static TranslatableStrings empty;
return empty;
}
void SetStreamUsage(wxInt32 StreamID, bool Use) override
{
}
ProgressResult Import(TrackFactory *trackFactory,
TrackHolders &outTracks,
Tags *tags) override;
private:
void AddMetadata(Tags *tags);
Movie mMovie;
};
TranslatableString QTImportPlugin::GetPluginFormatDescription()
{
return DESC;
}
std::unique_ptr<ImportFileHandle> QTImportPlugin::Open(
const wxString & Filename, AudacityProject*)
{
OSErr err;
FSRef inRef;
Movie theMovie = NULL;
Handle dataRef = NULL;
OSType dataRefType = 0;
short resID = 0;
#if defined(__WXMAC__)
err = wxMacPathToFSRef(Filename, &inRef);
#else
// LLL: This will not work for pathnames with Unicode characters...find
// another method.
err = FSPathMakeRef((UInt8 *)OSFILENAME(Filename), &inRef, NULL);
#endif
if (err != noErr) {
return nullptr;
}
err = QTNewDataReferenceFromFSRef(&inRef, 0, &dataRef, &dataRefType);
if (err != noErr) {
return nullptr;
}
// instantiate the movie
err = NewMovieFromDataRef(&theMovie,
newMovieActive | newMovieDontAskUnresolvedDataRefs,
&resID,
dataRef,
dataRefType);
DisposeHandle(dataRef);
if (err != noErr) {
return nullptr;
}
return std::make_unique<QTImportFileHandle>(Filename, theMovie);
}
static Importer::RegisteredImportPlugin registered{ "QT",
std::make_unique< QTImportPlugin >()
};
TranslatableString QTImportFileHandle::GetFileDescription()
{
return DESC;
}
auto QTImportFileHandle::GetFileUncompressedBytes() -> ByteCount
{
return 0;
}
ProgressResult QTImportFileHandle::Import(TrackFactory *trackFactory,
TrackHolders &outTracks,
Tags *tags)
{
outTracks.clear();
OSErr err = noErr;
MovieAudioExtractionRef maer = NULL;
auto updateResult = ProgressResult::Success;
auto totSamples =
(sampleCount) GetMovieDuration(mMovie); // convert from TimeValue
decltype(totSamples) numSamples = 0;
Boolean discrete = true;
UInt32 quality = kQTAudioRenderQuality_Max;
AudioStreamBasicDescription desc;
UInt32 maxSampleSize;
bool res = false;
auto cleanup = finally( [&] {
if (maer) {
MovieAudioExtractionEnd(maer);
}
} );
CreateProgress();
do
{
err = MovieAudioExtractionBegin(mMovie, 0, &maer);
if (err != noErr) {
AudacityMessageBox( XO("Unable to start QuickTime extraction") );
break;
}
err = MovieAudioExtractionSetProperty(maer,
kQTPropertyClass_MovieAudioExtraction_Audio,
kQTMovieAudioExtractionAudioPropertyID_RenderQuality,
sizeof(quality),
&quality);
if (err != noErr) {
AudacityMessageBox( XO("Unable to set QuickTime render quality") );
break;
}
err = MovieAudioExtractionSetProperty(maer,
kQTPropertyClass_MovieAudioExtraction_Movie,
kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
sizeof(discrete),
&discrete);
if (err != noErr) {
AudacityMessageBox( XO(
"Unable to set QuickTime discrete channels property") );
break;
}
err = MovieAudioExtractionGetProperty(maer,
kQTPropertyClass_MovieAudioExtraction_Audio,
kQTAudioPropertyID_MaxAudioSampleSize,
sizeof(maxSampleSize),
&maxSampleSize,
NULL);
if (err != noErr) {
AudacityMessageBox( XO(
"Unable to get QuickTime sample size property") );
break;
}
err = MovieAudioExtractionGetProperty(maer,
kQTPropertyClass_MovieAudioExtraction_Audio,
kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
sizeof(desc),
&desc,
NULL);
if (err != noErr) {
AudacityMessageBox( XO("Unable to retrieve stream description") );
break;
}
auto numchan = desc.mChannelsPerFrame;
const size_t bufsize = 5 * desc.mSampleRate;
// determine sample format
sampleFormat format;
switch (maxSampleSize)
{
case 16:
format = int16Sample;
break;
case 24:
format = int24Sample;
break;
default:
format = floatSample;
break;
}
// Allocate an array of pointers, whose size is not known statically,
// and prefixed with the AudioBufferList structure.
MallocPtr< AudioBufferList > abl{
static_cast< AudioBufferList * >(
calloc( 1, offsetof( AudioBufferList, mBuffers ) +
(sizeof(AudioBuffer) * numchan))) };
abl->mNumberBuffers = numchan;
NewChannelGroup channels{ numchan };
const auto size = sizeof(float) * bufsize;
ArraysOf<unsigned char> holders{ numchan, size };
for (size_t c = 0; c < numchan; c++) {
auto &buffer = abl->mBuffers[c];
auto &holder = holders[c];
auto &channel = channels[c];
buffer.mNumberChannels = 1;
buffer.mDataByteSize = size;
buffer.mData = holder.get();
channel = trackFactory->NewWaveTrack( format );
channel->SetRate( desc.mSampleRate );
}
do {
UInt32 flags = 0;
UInt32 numFrames = bufsize;
err = MovieAudioExtractionFillBuffer(maer,
&numFrames,
abl.get(),
&flags);
if (err != noErr) {
AudacityMessageBox( XO("Unable to get fill buffer") );
break;
}
for (size_t c = 0; c < numchan; c++) {
channels[c]->Append((char *) abl->mBuffers[c].mData, floatSample, numFrames);
}
numSamples += numFrames;
updateResult = mProgress->Update(
numSamples.as_long_long(),
totSamples.as_long_long() );
if (numFrames == 0 || flags & kQTMovieAudioExtractionComplete) {
break;
}
} while (updateResult == ProgressResult::Success);
res = (updateResult == ProgressResult::Success && err == noErr);
if (res) {
for (auto &channel: channels)
channel->Flush();
if (!channels.empty())
outTracks.push_back(std::move(channels));
}
//
// Extract any metadata
//
if (res) {
AddMetadata(tags);
}
} while (false);
// done:
return (res ? ProgressResult::Success : ProgressResult::Failed);
}
static const struct
{
const OSType key;
const wxChar *name;
}
names[] =
{
{ kQTMetaDataCommonKeyAuthor, wxT("Author") },
{ kQTMetaDataCommonKeyComment, TAG_COMMENTS },
{ kQTMetaDataCommonKeyCopyright, TAG_COPYRIGHT },
{ kQTMetaDataCommonKeyDirector, wxT("Director") },
{ kQTMetaDataCommonKeyDisplayName, wxT("Full Name") },
{ kQTMetaDataCommonKeyInformation, wxT("Information") },
{ kQTMetaDataCommonKeyKeywords, wxT("Keywords") },
{ kQTMetaDataCommonKeyProducer, wxT("Producer") },
{ kQTMetaDataCommonKeyAlbum, TAG_ALBUM },
{ kQTMetaDataCommonKeyArtist, TAG_ARTIST },
{ kQTMetaDataCommonKeyChapterName, wxT("Chapter") },
{ kQTMetaDataCommonKeyComposer, wxT("Composer") },
{ kQTMetaDataCommonKeyDescription, wxT("Description") },
{ kQTMetaDataCommonKeyGenre, TAG_GENRE },
{ kQTMetaDataCommonKeyOriginalFormat, wxT("Original Format") },
{ kQTMetaDataCommonKeyOriginalSource, wxT("Original Source") },
{ kQTMetaDataCommonKeyPerformers, wxT("Performers") },
{ kQTMetaDataCommonKeySoftware, TAG_SOFTWARE },
{ kQTMetaDataCommonKeyWriter, wxT("Writer") },
};
void QTImportFileHandle::AddMetadata(Tags *tags)
{
QTMetaDataRef metaDataRef = NULL;
auto cleanup = finally( [&] {
// we are done so release our metadata object
if ( metaDataRef )
QTMetaDataRelease(metaDataRef);
} );
OSErr err;
err = QTCopyMovieMetaData(mMovie, &metaDataRef);
if (err != noErr) {
return;
}
for (int i = 0; i < WXSIZEOF(names); i++) {
QTMetaDataItem item = kQTMetaDataItemUninitialized;
// OSType key = names[i].key;
err = QTMetaDataGetNextItem(metaDataRef,
kQTMetaDataStorageFormatWildcard,
kQTMetaDataItemUninitialized,
kQTMetaDataKeyFormatCommon,
(const UInt8 *) &names[i].key,
sizeof(names[i].key),
&item);
if (err != noErr) {
continue;
}
if (item == kQTMetaDataItemUninitialized) {
continue;
}
QTPropertyValueType outPropType;
::ByteCount outPropValueSize;
::ByteCount outPropValueSizeUsed = 0;
UInt32 outPropFlags;
UInt32 dataType;
// Get data type
err = QTMetaDataGetItemProperty(metaDataRef,
item,
kPropertyClass_MetaDataItem,
kQTMetaDataItemPropertyID_DataType,
sizeof(dataType),
&dataType,
&outPropValueSizeUsed);
if (err != noErr) {
continue;
}
// Get the data length
err = QTMetaDataGetItemPropertyInfo(metaDataRef,
item,
kPropertyClass_MetaDataItem,
kQTMetaDataItemPropertyID_Value,
&outPropType,
&outPropValueSize,
&outPropFlags );
if (err != noErr) {
continue;
}
// Alloc memory for it
ArrayOf<char> outVals{ outPropValueSize };
// Retrieve the data
err = QTMetaDataGetItemProperty(metaDataRef,
item,
kPropertyClass_MetaDataItem,
kQTMetaDataItemPropertyID_Value,
outPropValueSize,
outVals.get(),
&outPropValueSizeUsed);
if (err != noErr)
continue;
wxString v;
switch (dataType)
{
case kQTMetaDataTypeUTF8:
v = wxString(outVals.get(), wxConvUTF8);
break;
case kQTMetaDataTypeUTF16BE:
{
wxMBConvUTF16BE conv;
v = wxString(outVals.get(), conv);
}
break;
}
if (!v.empty()) {
tags->SetTag(names[i].name, v);
}
}
return;
}
#endif