forked from audacity/audacity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExportFFmpeg.cpp
More file actions
1260 lines (1079 loc) · 42.6 KB
/
Copy pathExportFFmpeg.cpp
File metadata and controls
1260 lines (1079 loc) · 42.6 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
/**********************************************************************
Audacity: A Digital Audio Editor
ExportFFmpeg.cpp
Audacity(R) is copyright (c) 1999-2009 Audacity Team.
License: GPL v2. See License.txt.
LRN
******************************************************************//**
\class ExportFFmpeg
\brief Controlling class for FFmpeg exporting. Creates the options
dialog of the appropriate type, adds tags and invokes the export
function.
*//*******************************************************************/
#include "../Audacity.h" // keep ffmpeg before wx because they interact // for USE_* macros
#include "../FFmpeg.h" // and Audacity.h before FFmpeg for config*.h
#include <wx/choice.h>
#include <wx/intl.h>
#include <wx/timer.h>
#include <wx/string.h>
#include <wx/textctrl.h>
#include <wx/listbox.h>
#include <wx/window.h>
#include <wx/spinctrl.h>
#include <wx/combobox.h>
#include "../Mix.h"
#include "../ProjectSettings.h"
#include "../Tags.h"
#include "../Track.h"
#include "../widgets/AudacityMessageBox.h"
#include "../widgets/ErrorDialog.h"
#include "../widgets/ProgressDialog.h"
#include "../wxFileNameWrapper.h"
#include "Export.h"
#include "ExportFFmpegDialogs.h"
#if defined(WIN32) && _MSC_VER < 1900
#define snprintf _snprintf
#endif
#if defined(USE_FFMPEG)
// Define this to automatically resample audio to the nearest supported sample rate
#define FFMPEG_AUTO_RESAMPLE 1
static bool CheckFFmpegPresence(bool quiet = false)
{
bool result = true;
PickFFmpegLibs();
if (!FFmpegLibsInst()->ValidLibsLoaded())
{
if (!quiet)
{
AudacityMessageBox(XO(
"Properly configured FFmpeg is required to proceed.\nYou can configure it at Preferences > Libraries."));
}
result = false;
}
DropFFmpegLibs();
return result;
}
static int AdjustFormatIndex(int format)
{
int subFormat = -1;
for (int i = 0; i <= FMT_OTHER; i++)
{
if (ExportFFmpegOptions::fmts[i].compiledIn) subFormat++;
if (subFormat == format || i == FMT_OTHER)
{
subFormat = i;
break;
}
}
return subFormat;
}
//----------------------------------------------------------------------------
// ExportFFmpeg
//----------------------------------------------------------------------------
class ExportFFmpeg final : public ExportPlugin
{
public:
ExportFFmpeg();
~ExportFFmpeg() override;
/// Callback, called from GetFilename
bool CheckFileName(wxFileName &filename, int format = 0) override;
/// Format initialization
bool Init(const char *shortname, AudacityProject *project, const Tags *metadata, int subformat);
/// Codec initialization
bool InitCodecs(AudacityProject *project);
/// Writes metadata
bool AddTags(const Tags *metadata);
/// Sets individual metadata values
void SetMetadata(const Tags *tags, const char *name, const wxChar *tag);
/// Encodes audio
bool EncodeAudioFrame(int16_t *pFrame, size_t frameSize);
/// Flushes audio encoder
bool Finalize();
void FreeResources();
/// Creates options panel
///\param format - index of export type
void OptionsCreate(ShuttleGui &S, int format) override;
/// Check whether or not current project sample rate is compatible with the export codec
bool CheckSampleRate(int rate, int lowrate, int highrate, const int *sampRates);
/// Asks user to resample the project or cancel the export procedure
int AskResample(int bitrate, int rate, int lowrate, int highrate, const int *sampRates);
/// Exports audio
///\param project Audacity project
///\param fName output file name
///\param selectedOnly true if exporting only selected audio
///\param t0 audio start time
///\param t1 audio end time
///\param mixerSpec mixer
///\param metadata tags to write into file
///\param subformat index of export type
///\return true if export succeeded
ProgressResult Export(AudacityProject *project,
std::unique_ptr<ProgressDialog> &pDialog,
unsigned channels,
const wxFileNameWrapper &fName,
bool selectedOnly,
double t0,
double t1,
MixerSpec *mixerSpec = NULL,
const Tags *metadata = NULL,
int subformat = 0) override;
private:
AVOutputFormat * mEncFormatDesc{}; // describes our output file to libavformat
int default_frame_size{};
AVStream * mEncAudioStream{}; // the output audio stream (may remain NULL)
int mEncAudioFifoOutBufSiz{};
wxFileNameWrapper mName;
int mSubFormat{};
int mBitRate{};
int mSampleRate{};
unsigned mChannels{};
bool mSupportsUTF8{};
// Smart pointer fields, their order is the reverse in which they are reset in FreeResources():
AVFifoBufferHolder mEncAudioFifo; // FIFO to write incoming audio samples into
AVMallocHolder<int16_t> mEncAudioFifoOutBuf; // buffer to read _out_ of the FIFO into
AVFormatContextHolder mEncFormatCtx; // libavformat's context for our output file
UFileHolder mUfileCloser;
AVCodecContextHolder mEncAudioCodecCtx; // the encoder for the output audio stream
};
ExportFFmpeg::ExportFFmpeg()
: ExportPlugin()
{
mEncFormatDesc = NULL; // describes our output file to libavformat
mEncAudioStream = NULL; // the output audio stream (may remain NULL)
#define MAX_AUDIO_PACKET_SIZE (128 * 1024)
mEncAudioFifoOutBufSiz = 0;
mSampleRate = 0;
mSupportsUTF8 = true;
PickFFmpegLibs(); // DropFFmpegLibs() call is in ExportFFmpeg destructor
int avfver = FFmpegLibsInst()->ValidLibsLoaded() ? avformat_version() : 0;
int newfmt;
// Adds export types from the export type list
for (newfmt = 0; newfmt < FMT_LAST; newfmt++)
{
wxString shortname(ExportFFmpegOptions::fmts[newfmt].shortname);
//Don't hide export types when there's no av-libs, and don't hide FMT_OTHER
if (newfmt < FMT_OTHER && FFmpegLibsInst()->ValidLibsLoaded())
{
// Format/Codec support is compiled in?
AVOutputFormat *avoformat = av_guess_format(shortname.mb_str(), NULL, NULL);
AVCodec *avcodec = avcodec_find_encoder(ExportFFmpegOptions::fmts[newfmt].codecid);
if (avoformat == NULL || avcodec == NULL)
{
ExportFFmpegOptions::fmts[newfmt].compiledIn = false;
continue;
}
}
int fmtindex = AddFormat() - 1;
SetFormat(ExportFFmpegOptions::fmts[newfmt].name,fmtindex);
AddExtension(ExportFFmpegOptions::fmts[newfmt].extension,fmtindex);
// For some types add other extensions
switch(newfmt)
{
case FMT_M4A:
AddExtension(wxT("3gp"),fmtindex);
AddExtension(wxT("m4r"),fmtindex);
AddExtension(wxT("mp4"),fmtindex);
break;
case FMT_WMA2:
AddExtension(wxT("asf"),fmtindex);
AddExtension(wxT("wmv"),fmtindex);
break;
default:
break;
}
SetMaxChannels(ExportFFmpegOptions::fmts[newfmt].maxchannels,fmtindex);
SetDescription(ExportFFmpegOptions::fmts[newfmt].description, fmtindex);
int canmeta = ExportFFmpegOptions::fmts[newfmt].canmetadata;
if (canmeta && (canmeta == AV_CANMETA || canmeta <= avfver))
{
SetCanMetaData(true,fmtindex);
}
else
{
SetCanMetaData(false,fmtindex);
}
}
}
ExportFFmpeg::~ExportFFmpeg()
{
DropFFmpegLibs();
}
bool ExportFFmpeg::CheckFileName(wxFileName & WXUNUSED(filename), int WXUNUSED(format))
{
bool result = true;
// Show "Locate FFmpeg" dialog
if (!CheckFFmpegPresence(true))
{
FFmpegLibsInst()->FindLibs(NULL);
FFmpegLibsInst()->FreeLibs();
return LoadFFmpeg(true);
}
return result;
}
bool ExportFFmpeg::Init(const char *shortname, AudacityProject *project, const Tags *metadata, int subformat)
{
// This will undo the acquisition of resources along any early exit path:
auto deleter = [](ExportFFmpeg *This) {
if (This)
This->FreeResources();
};
std::unique_ptr<ExportFFmpeg, decltype(deleter)> cleanup{ this, deleter };
int err;
//FFmpegLibsInst()->LoadLibs(NULL,true); //Loaded at startup or from Prefs now
if (!FFmpegLibsInst()->ValidLibsLoaded())
return false;
av_log_set_callback(av_log_wx_callback);
// See if libavformat has modules that can write our output format. If so, mEncFormatDesc
// will describe the functions used to write the format (used internally by libavformat)
// and the default video/audio codecs that the format uses.
const auto path = mName.GetFullPath();
if ((mEncFormatDesc = av_guess_format(shortname, OSINPUT(path), NULL)) == NULL)
{
AudacityMessageBox(
XO(
"FFmpeg : ERROR - Can't determine format description for file \"%s\".")
.Format( path ),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION );
return false;
}
// mEncFormatCtx is used by libavformat to carry around context data re our output file.
mEncFormatCtx.reset(avformat_alloc_context());
if (!mEncFormatCtx)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Can't allocate output format context."),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION);
return false;
}
// Initialise the output format context.
mEncFormatCtx->oformat = mEncFormatDesc;
memcpy(mEncFormatCtx->filename, OSINPUT(path), strlen(OSINPUT(path))+1);
// At the moment Audacity can export only one audio stream
if ((mEncAudioStream = avformat_new_stream(mEncFormatCtx.get(), NULL)) == NULL)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Can't add audio stream to output file \"%s\".")
.Format( path ),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION);
return false;
}
// Documentation for avformat_new_stream says
// "User is required to call avcodec_close() and avformat_free_context() to clean
// up the allocation by avformat_new_stream()."
// We use smart pointers that ensure these cleanups either in their destructors or
// sooner if they are reset. These are std::unique_ptr with nondefault deleter
// template parameters.
// mEncFormatCtx takes care of avformat_free_context(), so
// mEncAudioStream can be a plain pointer.
// mEncAudioCodecCtx now becomes responsible for closing the codec:
mEncAudioCodecCtx.reset(mEncAudioStream->codec);
mEncAudioStream->id = 0;
// Open the output file.
if (!(mEncFormatDesc->flags & AVFMT_NOFILE))
{
if ((err = ufile_fopen(&mEncFormatCtx->pb, path, AVIO_FLAG_WRITE)) < 0)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Can't open output file \"%s\" to write. Error code is %d.")
.Format( path, err ),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION);
return false;
}
// Give mUfileCloser responsibility
mUfileCloser.reset(mEncFormatCtx->pb);
}
// Open the audio stream's codec and initialise any stream related data.
if (!InitCodecs(project))
return false;
if (metadata == NULL)
metadata = &Tags::Get( *project );
// Add metadata BEFORE writing the header.
// At the moment that works with ffmpeg-git and ffmpeg-0.5 for MP4.
if (GetCanMetaData(subformat))
{
mSupportsUTF8 = ExportFFmpegOptions::fmts[mSubFormat].canutf8;
AddTags(metadata);
}
// Write headers to the output file.
if ((err = avformat_write_header(mEncFormatCtx.get(), NULL)) < 0)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Can't write headers to output file \"%s\". Error code is %d.")
.Format( path, err ),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION);
return false;
}
// Only now, we can keep all the resources until after Finalize().
// Cancel the local cleanup.
cleanup.release();
return true;
}
bool ExportFFmpeg::CheckSampleRate(int rate, int lowrate, int highrate, const int *sampRates)
{
if (lowrate && highrate)
{
if (rate < lowrate || rate > highrate)
{
return false;
}
}
if (sampRates)
{
for (int i = 0; sampRates[i] > 0; i++)
{
if (rate == sampRates[i])
{
return true;
}
}
}
return false;
}
static int set_dict_int(AVDictionary **dict, const char *key, int val)
{
char val_str[256];
snprintf(val_str, sizeof(val_str), "%d", val);
return av_dict_set(dict, key, val_str, 0);
}
bool ExportFFmpeg::InitCodecs(AudacityProject *project)
{
const auto &settings = ProjectSettings::Get( *project );
AVCodec *codec = NULL;
AVDictionary *options = NULL;
AVDictionaryCleanup cleanup{ &options };
// Get the sample rate from the passed settings if we haven't set it before.
// Doing this only when not set allows us to carry the sample rate from one
// iteration of ExportMultiple to the next. This prevents multiple resampling
// dialogs in the event the codec can't support the specified rate.
if (!mSampleRate)
{
mSampleRate = (int)settings.GetRate();
}
// Configure the audio stream's codec context.
mEncAudioCodecCtx->codec_id = ExportFFmpegOptions::fmts[mSubFormat].codecid;
mEncAudioCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
mEncAudioCodecCtx->codec_tag = av_codec_get_tag(mEncFormatCtx->oformat->codec_tag,mEncAudioCodecCtx->codec_id);
mEncAudioCodecCtx->global_quality = -99999; //quality mode is off by default;
// Each export type has its own settings
switch (mSubFormat)
{
case FMT_M4A:
{
int q = gPrefs->Read(wxT("/FileFormats/AACQuality"),-99999);
mEncAudioCodecCtx->global_quality = q;
q = wxClip( q, 98 * mChannels, 160 * mChannels);
// Set bit rate to between 98 kbps and 320 kbps (if two channels)
mEncAudioCodecCtx->bit_rate = q * 1000;
mEncAudioCodecCtx->profile = FF_PROFILE_AAC_LOW;
mEncAudioCodecCtx->cutoff = 0;
break;
}
case FMT_AC3:
mEncAudioCodecCtx->bit_rate = gPrefs->Read(wxT("/FileFormats/AC3BitRate"), 192000);
if (!CheckSampleRate(mSampleRate,ExportFFmpegAC3Options::iAC3SampleRates[0], ExportFFmpegAC3Options::iAC3SampleRates[2], &ExportFFmpegAC3Options::iAC3SampleRates[0]))
mSampleRate = AskResample(mEncAudioCodecCtx->bit_rate,mSampleRate, ExportFFmpegAC3Options::iAC3SampleRates[0], ExportFFmpegAC3Options::iAC3SampleRates[2], &ExportFFmpegAC3Options::iAC3SampleRates[0]);
break;
case FMT_AMRNB:
mSampleRate = 8000;
mEncAudioCodecCtx->bit_rate = gPrefs->Read(wxT("/FileFormats/AMRNBBitRate"), 12200);
break;
case FMT_OPUS:
av_dict_set(&options, "b", gPrefs->Read(wxT("/FileFormats/OPUSBitRate"), wxT("128000")).ToUTF8(), 0);
av_dict_set(&options, "vbr", gPrefs->Read(wxT("/FileFormats/OPUSVbrMode"), wxT("on")).ToUTF8(), 0);
av_dict_set(&options, "compression_level", gPrefs->Read(wxT("/FileFormats/OPUSCompression"), wxT("10")).ToUTF8(), 0);
av_dict_set(&options, "frame_duration", gPrefs->Read(wxT("/FileFormats/OPUSFrameDuration"), wxT("20")).ToUTF8(), 0);
av_dict_set(&options, "application", gPrefs->Read(wxT("/FileFormats/OPUSApplication"), wxT("audio")).ToUTF8(), 0);
av_dict_set(&options, "cutoff", gPrefs->Read(wxT("/FileFormats/OPUSCutoff"), wxT("0")).ToUTF8(), 0);
av_dict_set(&options, "mapping_family", mChannels <= 2 ? "0" : "255", 0);
break;
case FMT_WMA2:
mEncAudioCodecCtx->bit_rate = gPrefs->Read(wxT("/FileFormats/WMABitRate"), 198000);
if (!CheckSampleRate(mSampleRate,ExportFFmpegWMAOptions::iWMASampleRates[0], ExportFFmpegWMAOptions::iWMASampleRates[4], &ExportFFmpegWMAOptions::iWMASampleRates[0]))
mSampleRate = AskResample(mEncAudioCodecCtx->bit_rate,mSampleRate, ExportFFmpegWMAOptions::iWMASampleRates[0], ExportFFmpegWMAOptions::iWMASampleRates[4], &ExportFFmpegWMAOptions::iWMASampleRates[0]);
break;
case FMT_OTHER:
av_dict_set(&mEncAudioStream->metadata, "language", gPrefs->Read(wxT("/FileFormats/FFmpegLanguage"),wxT("")).ToUTF8(), 0);
mEncAudioCodecCtx->sample_rate = gPrefs->Read(wxT("/FileFormats/FFmpegSampleRate"),(long)0);
if (mEncAudioCodecCtx->sample_rate != 0) mSampleRate = mEncAudioCodecCtx->sample_rate;
mEncAudioCodecCtx->bit_rate = gPrefs->Read(wxT("/FileFormats/FFmpegBitRate"), (long)0);
strncpy((char *)&mEncAudioCodecCtx->codec_tag,gPrefs->Read(wxT("/FileFormats/FFmpegTag"),wxT("")).mb_str(wxConvUTF8),4);
mEncAudioCodecCtx->global_quality = gPrefs->Read(wxT("/FileFormats/FFmpegQuality"),(long)-99999);
mEncAudioCodecCtx->cutoff = gPrefs->Read(wxT("/FileFormats/FFmpegCutOff"),(long)0);
mEncAudioCodecCtx->flags2 = 0;
if (gPrefs->Read(wxT("/FileFormats/FFmpegBitReservoir"),true))
av_dict_set(&options, "reservoir", "1", 0);
if (gPrefs->Read(wxT("/FileFormats/FFmpegVariableBlockLen"),true)) mEncAudioCodecCtx->flags2 |= 0x0004; //WMA only?
mEncAudioCodecCtx->compression_level = gPrefs->Read(wxT("/FileFormats/FFmpegCompLevel"),-1);
mEncAudioCodecCtx->frame_size = gPrefs->Read(wxT("/FileFormats/FFmpegFrameSize"),(long)0);
//FIXME The list of supported options for the selected encoder should be extracted instead of a few hardcoded
set_dict_int(&options, "lpc_coeff_precision", gPrefs->Read(wxT("/FileFormats/FFmpegLPCCoefPrec"),(long)0));
set_dict_int(&options, "min_prediction_order", gPrefs->Read(wxT("/FileFormats/FFmpegMinPredOrder"),(long)-1));
set_dict_int(&options, "max_prediction_order", gPrefs->Read(wxT("/FileFormats/FFmpegMaxPredOrder"),(long)-1));
set_dict_int(&options, "min_partition_order", gPrefs->Read(wxT("/FileFormats/FFmpegMinPartOrder"),(long)-1));
set_dict_int(&options, "max_partition_order", gPrefs->Read(wxT("/FileFormats/FFmpegMaxPartOrder"),(long)-1));
set_dict_int(&options, "prediction_order_method", gPrefs->Read(wxT("/FileFormats/FFmpegPredOrderMethod"),(long)0));
set_dict_int(&options, "muxrate", gPrefs->Read(wxT("/FileFormats/FFmpegMuxRate"),(long)0));
mEncFormatCtx->packet_size = gPrefs->Read(wxT("/FileFormats/FFmpegPacketSize"),(long)0);
codec = avcodec_find_encoder_by_name(gPrefs->Read(wxT("/FileFormats/FFmpegCodec")).ToUTF8());
if (!codec)
mEncAudioCodecCtx->codec_id = mEncFormatDesc->audio_codec;
break;
default:
return false;
}
// This happens if user refused to resample the project
if (mSampleRate == 0) return false;
if (mEncAudioCodecCtx->global_quality >= 0)
{
mEncAudioCodecCtx->flags |= AV_CODEC_FLAG_QSCALE;
}
else mEncAudioCodecCtx->global_quality = 0;
mEncAudioCodecCtx->global_quality = mEncAudioCodecCtx->global_quality * FF_QP2LAMBDA;
mEncAudioCodecCtx->sample_rate = mSampleRate;
mEncAudioCodecCtx->channels = mChannels;
mEncAudioCodecCtx->channel_layout = av_get_default_channel_layout(mChannels);
mEncAudioCodecCtx->time_base.num = 1;
mEncAudioCodecCtx->time_base.den = mEncAudioCodecCtx->sample_rate;
mEncAudioCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
mEncAudioCodecCtx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
if (mEncAudioCodecCtx->codec_id == AV_CODEC_ID_AC3)
{
// As of Jan 4, 2011, the default AC3 encoder only accept SAMPLE_FMT_FLT samples.
// But, currently, Audacity only supports SAMPLE_FMT_S16. So, for now, look for the
// "older" AC3 codec. this is not a proper solution, but will suffice until other
// encoders no longer support SAMPLE_FMT_S16.
codec = avcodec_find_encoder_by_name("ac3_fixed");
}
if (!codec)
{
codec = avcodec_find_encoder(mEncAudioCodecCtx->codec_id);
}
// Is the required audio codec compiled into libavcodec?
if (codec == NULL)
{
AudacityMessageBox(
XO(
/* i18n-hint: "codec" is short for a "coder-decoder" algorithm */
"FFmpeg cannot find audio codec 0x%x.\nSupport for this codec is probably not compiled in.")
.Format( (unsigned int) mEncAudioCodecCtx->codec_id ),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION);
return false;
}
if (codec->sample_fmts) {
for (int i=0; codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
enum AVSampleFormat fmt = codec->sample_fmts[i];
if ( fmt == AV_SAMPLE_FMT_U8
|| fmt == AV_SAMPLE_FMT_U8P
|| fmt == AV_SAMPLE_FMT_S16
|| fmt == AV_SAMPLE_FMT_S16P
|| fmt == AV_SAMPLE_FMT_S32
|| fmt == AV_SAMPLE_FMT_S32P
|| fmt == AV_SAMPLE_FMT_FLT
|| fmt == AV_SAMPLE_FMT_FLTP) {
mEncAudioCodecCtx->sample_fmt = fmt;
}
if ( fmt == AV_SAMPLE_FMT_S16
|| fmt == AV_SAMPLE_FMT_S16P)
break;
}
}
if (codec->supported_samplerates)
{
// Workaround for crash in bug #2378. Proper fix is to get a newer version of FFmpeg.
if (codec->id == AV_CODEC_ID_AAC)
{
std::vector<int> rates;
int i = 0;
while (codec->supported_samplerates[i] && codec->supported_samplerates[i] != 7350)
{
rates.push_back(codec->supported_samplerates[i++]);
}
rates.push_back(0);
if (!CheckSampleRate(mSampleRate, 0, 0, rates.data()))
{
mEncAudioCodecCtx->sample_rate = mSampleRate = AskResample(0, mSampleRate, 0, 0, rates.data());
}
}
else
{
if (!CheckSampleRate(mSampleRate, 0, 0, codec->supported_samplerates))
{
mEncAudioCodecCtx->sample_rate = mSampleRate = AskResample(0, mSampleRate, 0, 0, codec->supported_samplerates);
}
}
// This happens if user refused to resample the project
if (mSampleRate == 0)
{
return false;
}
}
if (mEncFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
{
mEncAudioCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
mEncFormatCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
// Open the codec.
int rc = avcodec_open2(mEncAudioCodecCtx.get(), codec, &options);
if (rc < 0)
{
TranslatableString errmsg;
switch (rc)
{
case -EPERM:
errmsg = XO("The codec reported a generic error (EPERM)");
break;
case -EINVAL:
errmsg = XO("The codec reported an invalid parameter (EINVAL)");
break;
default:
char buf[AV_ERROR_MAX_STRING_SIZE];
av_strerror(rc, buf, sizeof(buf));
errmsg = Verbatim(buf);
}
AudacityMessageBox(
/* i18n-hint: "codec" is short for a "coder-decoder" algorithm */
XO("Can't open audio codec \"%s\" (0x%x)\n\n%s")
.Format(codec->name, mEncAudioCodecCtx->codec_id, errmsg),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION);
return false;
}
default_frame_size = mEncAudioCodecCtx->frame_size;
if (default_frame_size == 0)
default_frame_size = 1024; // arbitrary non zero value;
wxLogDebug(wxT("FFmpeg : Audio Output Codec Frame Size: %d samples."), mEncAudioCodecCtx->frame_size);
// The encoder may require a minimum number of raw audio samples for each encoding but we can't
// guarantee we'll get this minimum each time an audio frame is decoded from the input file so
// we use a FIFO to store up incoming raw samples until we have enough for one call to the codec.
mEncAudioFifo.reset(av_fifo_alloc(1024));
mEncAudioFifoOutBufSiz = 2*MAX_AUDIO_PACKET_SIZE;
// Allocate a buffer to read OUT of the FIFO into. The FIFO maintains its own buffer internally.
mEncAudioFifoOutBuf.reset(static_cast<int16_t*>(av_malloc(mEncAudioFifoOutBufSiz)));
if (!mEncAudioFifoOutBuf)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Can't allocate buffer to read into from audio FIFO."),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return false;
}
return true;
}
// Returns 0 if no more output, 1 if more output, negative if error
static int encode_audio(AVCodecContext *avctx, AVPacket *pkt, int16_t *audio_samples, int nb_samples)
{
// Assume *pkt is already initialized.
int i, ch, buffer_size, ret, got_output = 0;
AVMallocHolder<uint8_t> samples;
AVFrameHolder frame;
if (audio_samples) {
frame.reset(av_frame_alloc());
if (!frame)
return AVERROR(ENOMEM);
frame->nb_samples = nb_samples;
frame->format = avctx->sample_fmt;
#if !defined(DISABLE_DYNAMIC_LOADING_FFMPEG) || (LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(54, 13, 0))
frame->channel_layout = avctx->channel_layout;
#endif
buffer_size = av_samples_get_buffer_size(NULL, avctx->channels, frame->nb_samples,
avctx->sample_fmt, 0);
if (buffer_size < 0) {
AudacityMessageBox(
XO("FFmpeg : ERROR - Could not get sample buffer size"),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return buffer_size;
}
samples.reset(static_cast<uint8_t*>(av_malloc(buffer_size)));
if (!samples) {
AudacityMessageBox(
XO("FFmpeg : ERROR - Could not allocate bytes for samples buffer"),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return AVERROR(ENOMEM);
}
/* setup the data pointers in the AVFrame */
ret = avcodec_fill_audio_frame(frame.get(), avctx->channels, avctx->sample_fmt,
samples.get(), buffer_size, 0);
if (ret < 0) {
AudacityMessageBox(
XO("FFmpeg : ERROR - Could not setup audio frame"),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return ret;
}
for (ch = 0; ch < avctx->channels; ch++) {
for (i = 0; i < frame->nb_samples; i++) {
switch(avctx->sample_fmt) {
case AV_SAMPLE_FMT_U8:
((uint8_t*)(frame->data[0]))[ch + i*avctx->channels] = audio_samples[ch + i*avctx->channels]/258 + 128;
break;
case AV_SAMPLE_FMT_U8P:
((uint8_t*)(frame->data[ch]))[i] = audio_samples[ch + i*avctx->channels]/258 + 128;
break;
case AV_SAMPLE_FMT_S16:
((int16_t*)(frame->data[0]))[ch + i*avctx->channels] = audio_samples[ch + i*avctx->channels];
break;
case AV_SAMPLE_FMT_S16P:
((int16_t*)(frame->data[ch]))[i] = audio_samples[ch + i*avctx->channels];
break;
case AV_SAMPLE_FMT_S32:
((int32_t*)(frame->data[0]))[ch + i*avctx->channels] = audio_samples[ch + i*avctx->channels]<<16;
break;
case AV_SAMPLE_FMT_S32P:
((int32_t*)(frame->data[ch]))[i] = audio_samples[ch + i*avctx->channels]<<16;
break;
case AV_SAMPLE_FMT_FLT:
((float*)(frame->data[0]))[ch + i*avctx->channels] = audio_samples[ch + i*avctx->channels] / 32767.0;
break;
case AV_SAMPLE_FMT_FLTP:
((float*)(frame->data[ch]))[i] = audio_samples[ch + i*avctx->channels] / 32767.;
break;
case AV_SAMPLE_FMT_NONE:
case AV_SAMPLE_FMT_DBL:
case AV_SAMPLE_FMT_DBLP:
case AV_SAMPLE_FMT_NB:
wxASSERT(false);
break;
}
}
}
}
pkt->data = NULL; // packet data will be allocated by the encoder
pkt->size = 0;
ret = avcodec_encode_audio2(avctx, pkt, frame.get(), &got_output);
if (ret < 0) {
AudacityMessageBox(
XO("FFmpeg : ERROR - encoding frame failed"),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return ret;
}
pkt->dts = pkt->pts = AV_NOPTS_VALUE; // we dont set frame.pts thus dont trust the AVPacket ts
return got_output;
}
bool ExportFFmpeg::Finalize()
{
// Flush the audio FIFO and encoder.
for (;;)
{
AVPacketEx pkt;
const int nFifoBytes = av_fifo_size(mEncAudioFifo.get()); // any bytes left in audio FIFO?
int encodeResult = 0;
// Flush the audio FIFO first if necessary. It won't contain a _full_ audio frame because
// if it did we'd have pulled it from the FIFO during the last encodeAudioFrame() call
if (nFifoBytes > 0)
{
const int nAudioFrameSizeOut = default_frame_size * mEncAudioCodecCtx->channels * sizeof(int16_t);
if (nAudioFrameSizeOut > mEncAudioFifoOutBufSiz || nFifoBytes > mEncAudioFifoOutBufSiz) {
AudacityMessageBox(
XO("FFmpeg : ERROR - Too much remaining data."),
XO("FFmpeg Error"),
wxOK | wxCENTER | wxICON_EXCLAMATION
);
return false;
}
// We have an incomplete buffer of samples left, encode it.
// If codec supports CODEC_CAP_SMALL_LAST_FRAME, we can feed it with smaller frame
// Or if frame_size is 1, then it's some kind of PCM codec, they don't have frames and will be fine with the samples
// Otherwise we'll send a full frame of audio + silence padding to ensure all audio is encoded
int frame_size = default_frame_size;
if (mEncAudioCodecCtx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME ||
frame_size == 1)
frame_size = nFifoBytes / (mEncAudioCodecCtx->channels * sizeof(int16_t));
wxLogDebug(wxT("FFmpeg : Audio FIFO still contains %d bytes, writing %d sample frame ..."),
nFifoBytes, frame_size);
// Fill audio buffer with zeroes. If codec tries to read the whole buffer,
// it will just read silence. If not - who cares?
memset(mEncAudioFifoOutBuf.get(), 0, mEncAudioFifoOutBufSiz);
//const AVCodec *codec = mEncAudioCodecCtx->codec;
// Pull the bytes out from the FIFO and feed them to the encoder.
if (av_fifo_generic_read(mEncAudioFifo.get(), mEncAudioFifoOutBuf.get(), nFifoBytes, NULL) == 0)
{
encodeResult = encode_audio(mEncAudioCodecCtx.get(), &pkt, mEncAudioFifoOutBuf.get(), frame_size);
}
else
{
wxLogDebug(wxT("FFmpeg : Reading from Audio FIFO failed, aborting"));
// TODO: more precise message
ShowExportErrorDialog("FFmpeg:825");
return false;
}
}
else
{
// Fifo is empty, flush encoder. May be called multiple times.
encodeResult = encode_audio(mEncAudioCodecCtx.get(), &pkt, NULL, 0);
}
if (encodeResult < 0) {
// TODO: more precise message
ShowExportErrorDialog("FFmpeg:837");
return false;
}
else if (encodeResult == 0)
break;
// We have a packet, send to the muxer
pkt.stream_index = mEncAudioStream->index;
// Set presentation time of frame (currently in the codec's timebase) in the stream timebase.
if (pkt.pts != int64_t(AV_NOPTS_VALUE))
pkt.pts = av_rescale_q(pkt.pts, mEncAudioCodecCtx->time_base, mEncAudioStream->time_base);
if (pkt.dts != int64_t(AV_NOPTS_VALUE))
pkt.dts = av_rescale_q(pkt.dts, mEncAudioCodecCtx->time_base, mEncAudioStream->time_base);
if (pkt.duration)
pkt.duration = av_rescale_q(pkt.duration, mEncAudioCodecCtx->time_base, mEncAudioStream->time_base);
if (av_interleaved_write_frame(mEncFormatCtx.get(), &pkt) != 0)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Couldn't write last audio frame to output file."),
XO("FFmpeg Error"),
wxOK | wxCENTER | wxICON_EXCLAMATION
);
return false;
}
}
// Write any file trailers.
if (av_write_trailer(mEncFormatCtx.get()) != 0) {
// TODO: more precise message
ShowExportErrorDialog("FFmpeg:868");
return false;
}
return true;
}
void ExportFFmpeg::FreeResources()
{
// Close the codecs.
mEncAudioCodecCtx.reset();
// Close the output file if we created it.
mUfileCloser.reset();
// Free any buffers or structures we allocated.
mEncFormatCtx.reset();
mEncAudioFifoOutBuf.reset();
mEncAudioFifoOutBufSiz = 0;
mEncAudioFifo.reset();
av_log_set_callback(av_log_default_callback);
}
// All paths in this that fail must report their error to the user.
bool ExportFFmpeg::EncodeAudioFrame(int16_t *pFrame, size_t frameSize)
{
int nBytesToWrite = 0;
uint8_t *pRawSamples = NULL;
int nAudioFrameSizeOut = default_frame_size * mEncAudioCodecCtx->channels * sizeof(int16_t);
int ret;
nBytesToWrite = frameSize;
pRawSamples = (uint8_t*)pFrame;
if (av_fifo_realloc2(mEncAudioFifo.get(), av_fifo_size(mEncAudioFifo.get()) + frameSize) < 0) {
ShowExportErrorDialog("FFmpeg:905");
return false;
}
// Put the raw audio samples into the FIFO.
ret = av_fifo_generic_write(mEncAudioFifo.get(), pRawSamples, nBytesToWrite,NULL);
if (ret != nBytesToWrite) {
ShowExportErrorDialog("FFmpeg:913");
return false;
}
if (nAudioFrameSizeOut > mEncAudioFifoOutBufSiz) {
AudacityMessageBox(
XO("FFmpeg : ERROR - nAudioFrameSizeOut too large."),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return false;
}
// Read raw audio samples out of the FIFO in nAudioFrameSizeOut byte-sized groups to encode.
while ( av_fifo_size(mEncAudioFifo.get()) >= nAudioFrameSizeOut)
{
ret = av_fifo_generic_read(mEncAudioFifo.get(), mEncAudioFifoOutBuf.get(), nAudioFrameSizeOut, NULL);
AVPacketEx pkt;
ret= encode_audio(mEncAudioCodecCtx.get(),
&pkt, // out
mEncAudioFifoOutBuf.get(), // in
default_frame_size);
if (ret < 0)
{
AudacityMessageBox(
XO("FFmpeg : ERROR - Can't encode audio frame."),
XO("FFmpeg Error"),
wxOK|wxCENTER|wxICON_EXCLAMATION
);
return false;
}
if (ret == 0)
continue;
// Rescale from the codec time_base to the AVStream time_base.
if (pkt.pts != int64_t(AV_NOPTS_VALUE))
pkt.pts = av_rescale_q(pkt.pts, mEncAudioCodecCtx->time_base, mEncAudioStream->time_base);
if (pkt.dts != int64_t(AV_NOPTS_VALUE))
pkt.dts = av_rescale_q(pkt.dts, mEncAudioCodecCtx->time_base, mEncAudioStream->time_base);
//wxLogDebug(wxT("FFmpeg : (%d) Writing audio frame with PTS: %lld."), mEncAudioCodecCtx->frame_number, (long long) pkt.pts);
pkt.stream_index = mEncAudioStream->index;
// Write the encoded audio frame to the output file.
if ((ret = av_interleaved_write_frame(mEncFormatCtx.get(), &pkt)) < 0)
{
ShowDiskFullExportErrorDialog(mName);
return false;
}
}
return true;
}
ProgressResult ExportFFmpeg::Export(AudacityProject *project,
std::unique_ptr<ProgressDialog> &pDialog,
unsigned channels, const wxFileNameWrapper &fName,
bool selectionOnly, double t0, double t1,
MixerSpec *mixerSpec, const Tags *metadata, int subformat)
{
if (!CheckFFmpegPresence())
return ProgressResult::Cancelled;
mChannels = channels;
// subformat index may not correspond directly to fmts[] index, convert it
mSubFormat = AdjustFormatIndex(subformat);
if (channels > ExportFFmpegOptions::fmts[mSubFormat].maxchannels)
{
AudacityMessageBox(
XO(
"Attempted to export %d channels, but maximum number of channels for selected output format is %d")
.Format(
channels,
ExportFFmpegOptions::fmts[mSubFormat].maxchannels ),
XO("Error"));
return ProgressResult::Cancelled;
}
mName = fName;
const auto &tracks = TrackList::Get( *project );
bool ret = true;
if (mSubFormat >= FMT_LAST) {
// TODO: more precise message
ShowExportErrorDialog("FFmpeg:996");
return ProgressResult::Cancelled;
}