-
Notifications
You must be signed in to change notification settings - Fork 43
/
main.cpp
1409 lines (1306 loc) · 49.8 KB
/
main.cpp
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
#include <clocale>
#include <numeric>
#include <regex>
#include "win32util.h"
#include "options.h"
#include "InputFactory.h"
#include "sink.h"
#include "WaveSink.h"
#include "CAFSink.h"
#include "WaveOutSink.h"
#include "PeakSink.h"
#include "cuesheet.h"
#include "CompositeSource.h"
#include "NullSource.h"
#include "SoxrResampler.h"
#include "SoxLowpassFilter.h"
#include "Normalizer.h"
#include "MatrixMixer.h"
#include "Quantizer.h"
#include "Scaler.h"
#include "Limiter.h"
#include "PipedReader.h"
#include "TrimmedSource.h"
#include "chanmap.h"
#include "ChannelMapper.h"
#include "logging.h"
#include "Compressor.h"
#include "metadata.h"
#include "wicimage.h"
#include "FLACModule.h"
#include "LibSndfileSource.h"
#include "TakSource.h"
#include "WavpackSource.h"
#include "AvisynthSource.h"
#include "OpusPacketDecoder.h"
#ifdef REFALAC
#include "ALACEncoderX.h"
#endif
#ifdef QAAC
#include <delayimp.h>
#include "AudioCodecX.h"
#include "CoreAudioEncoder.h"
#include "CoreAudioPaddedEncoder.h"
#include "CoreAudioResampler.h"
#endif
#include <crtdbg.h>
#ifdef REFALAC
#define PROGNAME "refalac"
#elif defined QAAC
#define PROGNAME "qaac"
#endif
static volatile bool g_interrupted = false;
static
BOOL WINAPI console_interrupt_handler(DWORD type)
{
g_interrupted = true;
return TRUE;
}
inline
std::wstring errormsg(const std::exception &ex)
{
return strutil::us2w(ex.what());
}
class PeriodicDisplay {
uint32_t m_interval;
uint32_t m_last_tick_title;
uint32_t m_last_tick_stderr;
std::wstring m_message;
bool m_verbose;
bool m_console_visible;
public:
PeriodicDisplay(uint32_t interval, bool verbose=true)
: m_interval(interval),
m_verbose(verbose)
{
m_console_visible = IsWindowVisible(GetConsoleWindow());
m_last_tick_title = m_last_tick_stderr = GetTickCount();
}
void put(const std::wstring &message) {
m_message = message;
uint32_t tick = GetTickCount();
if (tick - m_last_tick_stderr > m_interval) {
m_last_tick_stderr = tick;
flush();
}
}
void flush() {
if (m_verbose) std::fputws(m_message.c_str(), stderr);
if (m_verbose && m_console_visible &&
m_last_tick_stderr - m_last_tick_title > m_interval * 4)
{
std::vector<wchar_t> s(m_message.size() + 1);
std::wcscpy(&s[0], m_message.c_str());
strutil::squeeze(&s[0], L"\r");
std::wstring msg = strutil::format(L"%hs %s", PROGNAME, &s[0]);
SetConsoleTitleW(msg.c_str());
m_last_tick_title = m_last_tick_stderr;
}
}
};
class Progress {
PeriodicDisplay m_disp;
bool m_verbose;
uint64_t m_total;
uint32_t m_rate;
std::wstring m_tstamp;
win32::Timer m_timer;
bool m_console_visible;
DWORD m_stderr_type;
public:
Progress(bool verbosity, uint64_t total, uint32_t rate)
: m_disp(100, verbosity), m_verbose(verbosity),
m_total(total), m_rate(rate)
{
m_stderr_type = GetFileType(win32::get_handle(_fileno(stderr)));
m_console_visible = IsWindowVisible(GetConsoleWindow());
if (total != ~0ULL)
m_tstamp = util::format_seconds(static_cast<double>(total) / rate);
}
void update(uint64_t current)
{
if ((!m_verbose || !m_stderr_type) && !m_console_visible) return;
double fcurrent = current;
double percent = 100.0 * fcurrent / m_total;
double seconds = fcurrent / m_rate;
double ellapsed = m_timer.ellapsed();
double eta = ellapsed * (m_total / fcurrent - 1);
double speed = ellapsed ? seconds/ellapsed : 0.0;
if (m_total == ~0ULL)
m_disp.put(strutil::format(L"\r%s (%.1fx) ",
util::format_seconds(seconds).c_str(), speed));
else {
std::wstring msg =
strutil::format(L"\r[%.1f%%] %s/%s (%.1fx), ETA %s ",
percent, util::format_seconds(seconds).c_str(),
m_tstamp.c_str(), speed,
util::format_seconds(eta).c_str());
m_disp.put(msg);
}
}
void finish(uint64_t current)
{
m_disp.flush();
if (m_verbose) fputwc('\n', stderr);
double ellapsed = m_timer.ellapsed();
LOG(L"%lld/%lld samples processed in %s\n",
current, m_total, util::format_seconds(ellapsed).c_str());
}
};
static
AudioStreamBasicDescription get_encoding_ASBD(const ISource *src,
uint32_t codecid)
{
AudioStreamBasicDescription iasbd = src->getSampleFormat();
AudioStreamBasicDescription oasbd = { 0 };
oasbd.mFormatID = codecid;
oasbd.mChannelsPerFrame = iasbd.mChannelsPerFrame;
oasbd.mSampleRate = iasbd.mSampleRate;
if (codecid == 'aac ')
oasbd.mFramesPerPacket = 1024;
else if (codecid == 'aach')
oasbd.mFramesPerPacket = 2048;
else if (codecid == 'alac')
oasbd.mFramesPerPacket = 4096;
if (codecid == 'alac') {
if (!(iasbd.mFormatFlags & kAudioFormatFlagIsSignedInteger))
throw std::runtime_error(
"floating point PCM is not supported for ALAC");
switch (iasbd.mBitsPerChannel) {
case 16:
oasbd.mFormatFlags = 1; break;
case 20:
oasbd.mFormatFlags = 2; break;
case 24:
oasbd.mFormatFlags = 3; break;
case 32:
oasbd.mFormatFlags = 4; break;
default:
throw std::runtime_error("Not supported bit depth for ALAC");
}
}
return oasbd;
}
static
uint32_t get_encoding_channel_layout(ISource *src, const Options &opts,
uint32_t *bitmap)
{
AudioStreamBasicDescription asbd = src->getSampleFormat();
const std::vector<uint32_t> *cs = src->getChannels();
uint32_t chanmask;
if (cs) chanmask = chanmap::getChannelMask(*cs);
else chanmask = chanmap::defaultChannelMask(asbd.mChannelsPerFrame);
uint32_t tag = chanmap::AACLayoutFromBitmap(chanmask);
#ifdef QAAC
auto codec = std::make_shared<AudioCodecX>(opts.output_format);
if (tag == kAudioChannelLayoutTag_AAC_7_1_B) {
if (opts.isALAC())
throw std::runtime_error("Channel layout not supported");
} else if (!codec->isAvailableOutputChannelLayout(tag)) {
throw std::runtime_error("Channel layout not supported");
}
#endif
#ifdef REFALAC
if (!ALACEncoderX::isAvailableOutputChannelLayout(tag))
throw std::runtime_error("Not supported channel layout for ALAC");
#endif
if (bitmap) *bitmap = chanmask;
return tag;
}
double target_sample_rate(const Options &opts, ISource *src)
{
AudioStreamBasicDescription iasbd = src->getSampleFormat();
double candidate = opts.rate > 0 ? opts.rate : iasbd.mSampleRate;
#ifdef QAAC
if (!opts.isAAC())
return candidate;
else if (opts.rate != 0) {
auto codec = std::make_shared<AudioCodecX>(opts.output_format);
return codec->getClosestAvailableOutputSampleRate(candidate);
} else {
uint32_t tag = get_encoding_channel_layout(src, opts, nullptr);
AudioChannelLayout acl = { 0 };
acl.mChannelLayoutTag = tag;
AudioStreamBasicDescription oasbd = { 0 };
oasbd.mFormatID = opts.output_format;
oasbd.mChannelsPerFrame = iasbd.mChannelsPerFrame;
AudioConverterXX converter(iasbd, oasbd);
converter.setInputChannelLayout(acl);
converter.setOutputChannelLayout(acl);
int32_t quality = (opts.quality + 1) << 5;
converter.configAACCodec(opts.method, opts.bitrate, quality);
return converter.getOutputStreamDescription().mSampleRate;
}
#else
return candidate;
#endif
}
static
void manipulate_channels(std::vector<std::shared_ptr<ISource> > &chain,
const Options &opts)
{
// normalize to Microsoft channel layout
{
const std::vector<uint32_t> *cs = chain.back()->getChannels();
if (cs) {
if (opts.verbose > 1) {
LOG(L"Input layout: %hs\n",
chanmap::getChannelNames(*cs).c_str());
}
auto ccs = chanmap::convertFromAppleLayout(*cs);
auto map = chanmap::getMappingToUSBOrder(ccs);
if (ccs != *cs || !util::is_increasing(map.begin(), map.end()))
{
std::shared_ptr<ISource>
mapper(new ChannelMapper(chain.back(), map,
chanmap::getChannelMask(ccs)));
chain.push_back(mapper);
}
}
}
// remix
if (opts.remix_preset || opts.remix_file) {
if (!SoXConvolverModule::instance().loaded())
LOG(L"WARNING: mixer requires libsoxconvolver. Mixing disabled\n");
else {
std::vector<std::vector<misc::complex_t> > matrix;
if (opts.remix_file)
matrix = misc::loadRemixerMatrixFromFile(opts.remix_file);
else
matrix = misc::loadRemixerMatrixFromPreset(opts.remix_preset);
if (opts.verbose > 1 || opts.logfilename) {
LOG(L"Matrix mixer: %uch -> %uch\n",
static_cast<uint32_t>(matrix[0].size()),
static_cast<uint32_t>(matrix.size()));
}
std::shared_ptr<ISource>
mixer(new MatrixMixer(chain.back(),
matrix, !opts.no_matrix_normalize));
chain.push_back(mixer);
}
}
uint32_t nchannels = chain.back()->getSampleFormat().mChannelsPerFrame;
// --chanmap
if (opts.chanmap.size()) {
if (opts.chanmap.size() != nchannels)
throw std::runtime_error(
"nchannels of input and --chanmap spec unmatch");
std::shared_ptr<ISource>
mapper(new ChannelMapper(chain.back(), opts.chanmap));
chain.push_back(mapper);
}
// --chanmask
if (opts.chanmask > 0)
{
if (util::bitcount(opts.chanmask) != nchannels)
throw std::runtime_error("unmatch --chanmask with input");
std::vector<uint32_t> map(nchannels);
std::iota(map.begin(), map.end(), 1);
std::shared_ptr<ISource>
mapper(new ChannelMapper(chain.back(), map, opts.chanmask));
chain.push_back(mapper);
}
}
std::string pcm_format_str(AudioStreamBasicDescription &asbd)
{
const char *stype[] = { "int", "float" };
unsigned itype = !!(asbd.mFormatFlags & kAudioFormatFlagIsFloat);
return strutil::format("%s%d", stype[itype], asbd.mBitsPerChannel);
}
static double do_normalize(std::vector<std::shared_ptr<ISource> > &chain,
const Options &opts, bool seekable)
{
std::shared_ptr<ISource> src = chain.back();
Normalizer *normalizer = new Normalizer(src, seekable);
chain.push_back(std::shared_ptr<ISource>(normalizer));
LOG(L"Scanning maximum peak...\n");
uint64_t n = 0, rc;
Progress progress(opts.verbose, src->length(),
src->getSampleFormat().mSampleRate);
while (!g_interrupted && (rc = normalizer->process(4096)) > 0) {
n += rc;
progress.update(src->getPosition());
}
progress.finish(src->getPosition());
LOG(L"Peak: %g (%gdB)\n", normalizer->getPeak(), util::scale_to_dB(normalizer->getPeak()));
return normalizer->getPeak();
}
void build_filter_chain_sub(std::shared_ptr<ISeekableSource> src,
std::vector<std::shared_ptr<ISource> > &chain,
const Options &opts, bool normalize_pass=false)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
bool threading = opts.threading && si.dwNumberOfProcessors > 1;
AudioStreamBasicDescription sasbd = src->getSampleFormat();
manipulate_channels(chain, opts);
// check if channel layout is available for codec
if (opts.isAAC() || opts.isALAC())
get_encoding_channel_layout(chain.back().get(), opts, nullptr);
if (opts.lowpass > 0) {
if (!SoXConvolverModule::instance().loaded())
LOG(L"WARNING: --lowpass requires libsoxconvolver. LPF disabled\n");
else {
if (opts.verbose > 1 || opts.logfilename)
LOG(L"Applying LPF: %dHz\n", opts.lowpass);
std::shared_ptr<SoxLowpassFilter>
f(new SoxLowpassFilter(chain.back(), opts.lowpass));
chain.push_back(f);
}
}
{
double irate = chain.back()->getSampleFormat().mSampleRate;
double orate = target_sample_rate(opts, chain.back().get());
if (orate != irate) {
if (!opts.native_resampler && SOXRModule::instance().loaded()) {
LOG(L"%gHz -> %gHz\n", irate, orate);
std::shared_ptr<SoxrResampler>
resampler(new SoxrResampler(chain.back(), orate));
if (opts.verbose > 1 || opts.logfilename)
LOG(L"Using libsoxr SRC: %hs\n", resampler->engine());
chain.push_back(resampler);
} else {
#ifndef QAAC
LOG(L"WARNING: --rate requires libsoxr, resampling disabled\n");
#else
LOG(L"%gHz -> %gHz\n", irate, orate);
AudioStreamBasicDescription sf
= chain.back()->getSampleFormat();
if ((sf.mFormatFlags & kAudioFormatFlagIsFloat)
&& sf.mBitsPerChannel < 32)
{
std::shared_ptr<ISource>
f(new Quantizer(chain.back(), 32, false, true));
chain.push_back(f);
}
uint32_t complexity = opts.native_resampler_complexity;
int quality = std::min(opts.native_resampler_quality,
(int)kAudioConverterQuality_Max);
if (quality < 0) quality = 0;
if (!complexity) complexity = 'bats';
std::shared_ptr<ISource>
resampler(new CoreAudioResampler(chain.back(), orate,
quality, complexity));
chain.push_back(resampler);
if (opts.verbose > 1 || opts.logfilename) {
CoreAudioResampler *p =
dynamic_cast<CoreAudioResampler*>(chain.back().get());
LOG(L"Using CoreAudio SRC: complexity %hs quality %u\n",
util::fourcc(p->getComplexity()).svalue,
p->getQuality());
}
#endif
}
}
}
for (size_t i = 0; i < opts.drc_params.size(); ++i) {
const DRCParams &p = opts.drc_params[i];
if (opts.verbose > 1 || opts.logfilename)
LOG(L"DRC: Threshold %gdB Ratio %g Knee width %gdB\n"
L" Attack %gms Release %gms\n",
p.m_threshold, p.m_ratio, p.m_knee_width,
p.m_attack, p.m_release);
std::shared_ptr<FILE> stat_file;
if (p.m_stat_file) {
FILE *fp = win32::wfopenx(p.m_stat_file, L"wb");
stat_file = std::shared_ptr<FILE>(fp, std::fclose);
}
std::shared_ptr<ISource>
compressor(new Compressor(chain.back(),
p.m_threshold,
p.m_ratio,
p.m_knee_width,
p.m_attack,
p.m_release,
stat_file));
chain.push_back(compressor);
}
if (normalize_pass) {
do_normalize(chain, opts, src->isSeekable());
if (src->isSeekable())
return;
}
if (opts.gain) {
double scale = util::dB_to_scale(opts.gain);
if (opts.verbose > 1 || opts.logfilename)
LOG(L"Gain adjustment: %gdB, scale factor %g\n",
opts.gain, scale);
std::shared_ptr<ISource> scaler(new Scaler(chain.back(), scale));
chain.push_back(scaler);
}
if (opts.limiter) {
if (opts.verbose > 1 || opts.logfilename)
LOG(L"Limiter on\n");
std::shared_ptr<ISource> limiter(new Limiter(chain.back()));
chain.push_back(limiter);
}
if (opts.bits_per_sample) {
bool is_float = (opts.bits_per_sample == 32 && !opts.isALAC());
unsigned sbits = chain.back()->getSampleFormat().mBitsPerChannel;
bool sflags = chain.back()->getSampleFormat().mFormatFlags;
if (opts.isAAC())
LOG(L"WARNING: --bits-per-sample has no effect for AAC\n");
else if (sbits != opts.bits_per_sample ||
!!(sflags & kAudioFormatFlagIsFloat) != is_float) {
std::shared_ptr<ISource>
isrc(new Quantizer(chain.back(), opts.bits_per_sample,
opts.no_dither, is_float));
chain.push_back(isrc);
if (opts.verbose > 1 || opts.logfilename)
LOG(L"Convert to %d bit\n", opts.bits_per_sample);
}
}
if (opts.isAAC()) {
AudioStreamBasicDescription sfmt = chain.back()->getSampleFormat();
if (!(sfmt.mFormatFlags & kAudioFormatFlagIsFloat) ||
sfmt.mBitsPerChannel != 32)
chain.push_back(std::make_shared<Quantizer>(chain.back(), 32,
false, true));
}
if (threading && (opts.isAAC() || opts.isALAC())) {
PipedReader *reader = new PipedReader(chain.back());
reader->start();
chain.push_back(std::shared_ptr<ISource>(reader));
if (opts.verbose > 1 || opts.logfilename)
LOG(L"Enable threading\n");
}
if (opts.verbose > 1) {
auto asbd = chain.back()->getSampleFormat();
LOG(L"Format: %hs -> %hs\n",
pcm_format_str(sasbd).c_str(), pcm_format_str(asbd).c_str());
}
}
void build_filter_chain(std::shared_ptr<ISeekableSource> src,
std::vector<std::shared_ptr<ISource> > &chain,
const Options &opts)
{
chain.push_back(src);
build_filter_chain_sub(src, chain, opts, opts.normalize);
if (opts.normalize && src->isSeekable()) {
src->seekTo(0);
Normalizer *normalizer = dynamic_cast<Normalizer*>(chain.back().get());
double peak = normalizer->getPeak();
chain.clear();
chain.push_back(src);
if (peak > FLT_MIN)
chain.push_back(std::make_shared<Scaler>(src, 1.0/peak));
build_filter_chain_sub(src, chain, opts, false);
}
}
static
bool accept_tag(const std::string &name)
{
/*
* We don't want to copy these tags from the source.
* XXX: should we use white list instead?
*/
static std::regex black_list[] = {
std::regex("accuraterip.*"),
std::regex("compatiblebrands"), /* XXX: ffmpeg metadata for mp4 */
std::regex("ctdb.*confidence"),
std::regex("cuesheet"),
std::regex("cuetrack.*"),
std::regex("encodedby"),
std::regex("encodingapplication"),
std::regex("itunnorm"),
std::regex("itunpgap"),
std::regex("itunsmpb"),
std::regex("log"),
std::regex("majorbrand"), /* XXX: ffmpeg metadata for mp4 */
std::regex("minorversion"), /* XXX: ffmpeg metadata for mp4 */
std::regex("replaygain.*"),
};
std::string ss;
for (const char *s = name.c_str(); *s; ++s)
if (!std::strchr(" -_", *s))
ss.push_back(tolower(static_cast<unsigned char>(*s)));
size_t i = 0, end = util::sizeof_array(black_list);
for (i = 0; i < end; ++i)
if (std::regex_match(ss, black_list[i]))
break;
return i == end;
}
static
void set_tags(ISource *src, ISink *sink, const Options &opts,
const std::wstring encoder_config)
{
ITagStore *tagstore = dynamic_cast<ITagStore*>(sink);
if (!tagstore)
return;
MP4SinkBase *mp4sink = dynamic_cast<MP4SinkBase*>(tagstore);
ITagParser *parser = dynamic_cast<ITagParser*>(src);
if (parser) {
const std::map<std::string, std::string> &tags = parser->getTags();
std::map<std::string, std::string>::const_iterator ssi;
for (ssi = tags.begin(); ssi != tags.end(); ++ssi) {
if (!strcasecmp(ssi->first.c_str(), "cover art")) {
if (mp4sink && opts.copy_artwork && !opts.artworks.size()) {
std::vector<char> vec(ssi->second.begin(),
ssi->second.end());
if (opts.artwork_size)
WICConvertArtwork(vec.data(), vec.size(),
opts.artwork_size, &vec);
mp4sink->addArtwork(vec);
}
} else if (accept_tag(ssi->first))
tagstore->setTag(ssi->first, ssi->second);
}
if (mp4sink) {
IChapterParser *cp = dynamic_cast<IChapterParser*>(src);
if (cp) {
auto &chapters = cp->getChapters();
if (chapters.size())
mp4sink->setChapters(chapters.begin(), chapters.end());
}
}
}
tagstore->setTag("encoding application",
strutil::w2us(opts.encoder_name + L", " + encoder_config));
for (auto uwi = opts.tagopts.begin(); uwi != opts.tagopts.end(); ++uwi) {
const char *name = M4A::getTagNameFromFourCC(uwi->first);
if (name)
tagstore->setTag(name, uwi->second);
}
for (auto swi = opts.longtags.begin(); swi != opts.longtags.end(); ++swi)
tagstore->setTag(swi->first, swi->second);
if (mp4sink) {
for (size_t i = 0; i < opts.artworks.size(); ++i)
mp4sink->addArtwork(opts.artworks[i]);
}
}
static
void decode_file(const std::vector<std::shared_ptr<ISource> > &chain,
const std::wstring &ofilename, const Options &opts)
{
std::shared_ptr<ISink> sink;
uint32_t chanmask = 0;
CAFSink *cafsink = 0;
const std::shared_ptr<ISource> src = chain.back();
const AudioStreamBasicDescription &sf = src->getSampleFormat();
const std::vector<uint32_t> *channels = src->getChannels();
if (channels) {
chanmask = chanmap::getChannelMask(*channels);
if (opts.verbose > 1) {
LOG(L"Output layout: %hs\n",
chanmap::getChannelNames(*channels).c_str());
}
}
if (opts.isLPCM()) {
auto fileptr = win32::fopen(ofilename, L"wb");
if (!opts.is_caf) {
sink = std::make_shared<WaveSink>(fileptr, src->length(),
sf, chanmask);
} else {
sink = std::make_shared<CAFSink>(fileptr, sf, chanmask,
std::vector<uint8_t>());
cafsink = dynamic_cast<CAFSink*>(sink.get());
set_tags(chain[0].get(), cafsink, opts, L"");
cafsink->beginWrite();
}
} else if (opts.isWaveOut()) {
if (!chanmask)
chanmask = chanmap::defaultChannelMask(sf.mChannelsPerFrame);
sink = std::make_shared<WaveOutSink>(sf, chanmask);
} else if (opts.isPeak())
sink = std::make_shared<PeakSink>(sf);
Progress progress(opts.verbose, src->length(), sf.mSampleRate);
uint32_t bpf = sf.mBytesPerFrame;
std::vector<uint8_t> buffer(4096 * bpf);
try {
size_t nread;
while (!g_interrupted &&
(nread = src->readSamples(&buffer[0], 4096)) > 0) {
progress.update(src->getPosition());
sink->writeSamples(&buffer[0], nread * bpf, nread);
}
progress.finish(src->getPosition());
} catch (const std::exception &e) {
LOG(L"\nERROR: %s\n", errormsg(e).c_str());
}
if (opts.isLPCM()) {
WaveSink *wavsink = dynamic_cast<WaveSink *>(sink.get());
if (wavsink)
wavsink->finishWrite();
else if (cafsink)
cafsink->finishWrite(AudioFilePacketTableInfo());
} else if (opts.isPeak()) {
PeakSink *p = dynamic_cast<PeakSink *>(sink.get());
LOG(L"Peak: %g (%gdB)\n", p->peak(), util::scale_to_dB(p->peak()));
}
}
static
uint32_t map_to_aac_channels(std::vector<std::shared_ptr<ISource> > &chain,
const Options &opts)
{
uint32_t chanmask;
uint32_t tag = get_encoding_channel_layout(chain.back().get(), opts,
&chanmask);
auto map = chanmap::getMappingToAAC(chanmask);
std::shared_ptr<ISource>
mapper(new ChannelMapper(chain.back(), map, 0, tag));
chain.push_back(mapper);
if (opts.verbose > 1) {
AudioChannelLayout acl = { 0 };
acl.mChannelLayoutTag = tag;
auto vec = chanmap::getChannels(&acl);
LOG(L"Output layout: %hs\n", chanmap::getChannelNames(vec).c_str());
}
return tag;
}
static
void do_encode(IEncoder *encoder, const std::wstring &ofilename,
const Options &opts)
{
typedef std::shared_ptr<std::FILE> file_t;
file_t statPtr;
if (opts.save_stat) {
std::wstring statname =
win32::PathReplaceExtension(ofilename, L".stat.txt");
statPtr = win32::fopen(statname, L"w");
}
IEncoderStat *stat = dynamic_cast<IEncoderStat*>(encoder);
ISource *src = encoder->src();
Progress progress(opts.verbose, src->length(),
src->getSampleFormat().mSampleRate);
try {
FILE *statfp = statPtr.get();
while (!g_interrupted && encoder->encodeChunk(1)) {
progress.update(src->getPosition());
if (statfp && stat->framesWritten())
std::fwprintf(statfp, L"%g\n", stat->currentBitrate());
}
progress.finish(src->getPosition());
} catch (...) {
LOG(L"\n");
throw;
}
}
static void do_optimize(MP4FileX *file, const std::wstring &dst, bool verbose)
{
try {
file->FinishWriteX();
MP4FileCopy optimizer(file);
optimizer.start(strutil::w2us(dst).c_str());
uint64_t total = optimizer.getTotalChunks();
PeriodicDisplay disp(100, verbose);
for (uint64_t i = 1; optimizer.copyNextChunk(); ++i) {
int percent = 100.0 * i / total + .5;
disp.put(strutil::format(L"\rOptimizing...%d%%",
percent).c_str());
}
disp.put(L"\rOptimizing...done\n");
disp.flush();
} catch (mp4v2::impl::Exception *e) {
handle_mp4error(e);
}
}
static
void finalize_m4a(MP4SinkBase *sink, IEncoder *encoder,
const std::wstring &ofilename, const Options &opts)
{
IEncoderStat *stat = dynamic_cast<IEncoderStat *>(encoder);
if (opts.chapter_file) {
try {
double duration = stat->samplesRead() /
encoder->getInputDescription().mSampleRate;
auto xs = misc::convertChaptersToQT(opts.chapters, duration);
sink->setChapters(xs.begin(), xs.end());
} catch (const std::runtime_error &e) {
LOG(L"WARNING: %s\n", errormsg(e).c_str());
}
}
sink->writeTags();
sink->writeBitrates(stat->overallBitrate() * 1000.0 + .5);
if (!opts.no_optimize)
do_optimize(sink->getFile(), ofilename, opts.verbose);
sink->close();
}
#ifdef QAAC
static
std::shared_ptr<ISink> open_sink(const std::wstring &ofilename,
const Options &opts,
const AudioStreamBasicDescription &asbd,
uint32_t channel_layout,
const std::vector<uint8_t> &cookie)
{
std::vector<uint8_t> asc;
if (opts.isAAC())
asc = cautil::parseMagicCookieAAC(cookie);
win32::MakeSureDirectoryPathExistsX(ofilename);
if (opts.isMP4()) {
std::shared_ptr<FILE> _ = win32::fopen(ofilename, L"wb");
}
if (opts.is_adts)
return std::make_shared<ADTSSink>(ofilename, asc, false);
else if (opts.is_caf)
return std::make_shared<CAFSink>(ofilename, asbd, channel_layout,
cookie);
else if (opts.isALAC())
return std::make_shared<ALACSink>(ofilename, cookie, !opts.no_optimize);
else if (opts.isAAC())
return std::make_shared<MP4Sink>(ofilename, asc, !opts.no_optimize);
throw std::runtime_error("XXX");
}
static
void show_available_codec_setttings(UInt32 fmt)
{
AudioCodecX codec(fmt);
auto srates = codec.getAvailableOutputSampleRates();
auto tags = codec.getAvailableOutputChannelLayoutTags();
for (size_t i = 0; i < srates.size(); ++i) {
if (srates[i].mMinimum == 0) continue;
for (size_t j = 0; j < tags.size(); ++j) {
if (tags[j] == 0) continue;
AudioChannelLayout acl = { 0 };
acl.mChannelLayoutTag = tags[j];
auto channels = chanmap::getChannels(&acl);
std::string name = chanmap::getChannelNames(channels);
AudioStreamBasicDescription iasbd =
cautil::buildASBDForPCM(srates[i].mMinimum,
channels.size(),
32, kAudioFormatFlagIsFloat);
AudioStreamBasicDescription oasbd = { 0 };
oasbd.mFormatID = fmt;
oasbd.mSampleRate = iasbd.mSampleRate;
oasbd.mChannelsPerFrame = iasbd.mChannelsPerFrame;
AudioConverterXX converter(iasbd, oasbd);
converter.setInputChannelLayout(acl);
converter.setOutputChannelLayout(acl);
converter.setBitRateControlMode(
kAudioCodecBitRateControlMode_Constant);
auto bits = converter.getApplicableEncodeBitRates();
std::wprintf(L"%hs %gHz %hs --",
fmt == 'aac ' ? "LC" : "HE",
srates[i].mMinimum, name.c_str());
for (size_t k = 0; k < bits.size(); ++k) {
if (!bits[k].mMinimum) continue;
int delim = k == 0 ? L' ' : L',';
std::wprintf(L"%c%d", delim, lrint(bits[k].mMinimum / 1000.0));
}
std::putwchar(L'\n');
}
}
}
static
void show_available_aac_settings()
{
show_available_codec_setttings('aac ');
show_available_codec_setttings('aach');
}
static
void setup_aach_codec(HMODULE hDll)
{
CFPlugInFactoryFunction aachFactory =
AutoCast(GetProcAddress(hDll, "ACMP4AACHighEfficiencyEncoderFactory"));
if (aachFactory) {
AudioComponentDescription desc = { 'aenc', 'aach', 0 };
AudioComponentRegister(&desc,
CFSTR("MPEG4 High Efficiency AAC Encoder"),
0, aachFactory);
}
}
/*
static
FARPROC WINAPI DllImportHook(unsigned notify, PDelayLoadInfo pdli)
{
win32::throw_error(pdli->szDll, pdli->dwLastError);
return 0;
}
*/
static
void set_dll_directories(int verbose)
{
SetDllDirectoryW(L"");
DWORD sz = GetEnvironmentVariableW(L"PATH", 0, 0);
std::vector<wchar_t> vec(sz);
sz = GetEnvironmentVariableW(L"PATH", &vec[0], sz);
std::wstring searchPaths(&vec[0], &vec[sz]);
try {
HKEY hKey;
const wchar_t *subkey[] = {
L"SOFTWARE\\Apple Inc.\\Apple Application Support",
L"SOFTWARE\\Apple Computer, Inc.\\iTunes",
};
for (int i = 0; i < 2; ++i) {
if (!RegOpenKeyExW(HKEY_LOCAL_MACHINE, subkey[i], 0, KEY_READ, &hKey)) {
std::shared_ptr<HKEY__> hKeyPtr(hKey, RegCloseKey);
DWORD size;
if (!RegQueryValueExW(hKey, L"InstallDir", 0, 0, 0, &size)) {
std::vector<wchar_t> vec(size/sizeof(wchar_t));
RegQueryValueExW(hKey, L"InstallDir", 0, 0,
reinterpret_cast<LPBYTE>(&vec[0]), &size);
searchPaths = strutil::format(L"%s;%s", &vec[0], searchPaths.c_str());
}
}
}
} catch (const std::exception &) {}
std::wstring dir = win32::get_module_directory() + L"QTfiles";
#ifdef _WIN64
dir += L"64";
#endif
searchPaths = strutil::format(L"%s;%s", dir.c_str(), searchPaths.c_str());
SetEnvironmentVariableW(L"PATH", searchPaths.c_str());
}
static
void encode_file(const std::shared_ptr<ISeekableSource> &src,
const std::wstring &ofilename, const Options &opts)
{
std::vector<std::shared_ptr<ISource> > chain;
build_filter_chain(src, chain, opts);
if (opts.isLPCM() || opts.isWaveOut() || opts.isPeak()) {
decode_file(chain, ofilename, opts);
return;
}
uint32_t channel_layout = map_to_aac_channels(chain, opts);
AudioStreamBasicDescription iasbd = chain.back()->getSampleFormat();
AudioStreamBasicDescription oasbd =
get_encoding_ASBD(chain.back().get(), opts.output_format);
AudioConverterXX converter(iasbd, oasbd);
AudioChannelLayout acl = { 0 };
acl.mChannelLayoutTag = channel_layout;
converter.setInputChannelLayout(acl);
converter.setOutputChannelLayout(acl);
if (opts.isAAC()) {
int32_t quality = (opts.quality + 1) << 5;
converter.configAACCodec(opts.method, opts.bitrate, quality);
}
std::wstring encoder_config = strutil::us2w(converter.getConfigAsString());
LOG(L"%s\n", encoder_config.c_str());
auto cookie = converter.getCompressionMagicCookie();
std::shared_ptr<CoreAudioEncoder> encoder;
if (opts.isAAC()) {
if (opts.no_smart_padding)
encoder = std::make_shared<CoreAudioEncoder>(converter);
else
encoder = std::make_shared<CoreAudioPaddedEncoder>(
converter, opts.num_priming);
} else
encoder = std::make_shared<CoreAudioEncoder>(converter);
encoder->setSource(chain.back());
std::shared_ptr<ISink> sink;
sink = open_sink(ofilename, opts, oasbd, channel_layout, cookie);
encoder->setSink(sink);
if (opts.isAAC()) {
MP4Sink *mp4sink = dynamic_cast<MP4Sink*>(sink.get());
if (mp4sink) {
std::string params = converter.getEncodingParamsTag();
mp4sink->setTag("Encoding Params", params);
}
}
set_tags(src.get(), sink.get(), opts, encoder_config);
CAFSink *cafsink = dynamic_cast<CAFSink*>(sink.get());
if (cafsink)
cafsink->beginWrite();
do_encode(encoder.get(), ofilename, opts);
LOG(L"Overall bitrate: %gkbps\n", encoder->overallBitrate());
AudioFilePacketTableInfo pti = { 0 };
if (opts.isAAC()) {
pti = encoder->getGaplessInfo();
MP4Sink *mp4sink = dynamic_cast<MP4Sink*>(sink.get());
if (mp4sink) {
mp4sink->setGaplessMode(opts.gapless_mode + 1);
mp4sink->setGaplessInfo(pti);
}
}
MP4SinkBase *mp4sinkbase = dynamic_cast<MP4SinkBase*>(sink.get());
if (mp4sinkbase)
finalize_m4a(mp4sinkbase, encoder.get(), ofilename, opts);
else if (cafsink)
cafsink->finishWrite(pti);
}
#endif // QAAC
#ifdef REFALAC
static
void encode_file(const std::shared_ptr<ISeekableSource> &src,
const std::wstring &ofilename, const Options &opts)
{
std::vector<std::shared_ptr<ISource> > chain;
build_filter_chain(src, chain, opts);
if (opts.isLPCM() || opts.isWaveOut() || opts.isPeak()) {
decode_file(chain, ofilename, opts);
return;
}
uint32_t channel_layout = map_to_aac_channels(chain, opts);
AudioStreamBasicDescription iasbd = chain.back()->getSampleFormat();
AudioStreamBasicDescription oasbd =
get_encoding_ASBD(chain.back().get(), opts.output_format);
ALACEncoderX encoder(iasbd);
encoder.setFastMode(opts.alac_fast);
auto cookie = encoder.getMagicCookie();
win32::MakeSureDirectoryPathExistsX(ofilename);
std::shared_ptr<ISink> sink;
if (opts.is_caf)
sink = std::make_shared<CAFSink>(ofilename, oasbd,
channel_layout, cookie);
else
sink = std::make_shared<ALACSink>(ofilename, cookie, !opts.no_optimize);
encoder.setSource(chain.back());
encoder.setSink(sink);