File: ExportMP2.cpp

package info (click to toggle)
audacity 3.7.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 125,252 kB
  • sloc: cpp: 358,238; ansic: 75,458; lisp: 7,761; sh: 3,410; python: 1,503; xml: 1,385; perl: 854; makefile: 122
file content (587 lines) | stat: -rw-r--r-- 17,105 bytes parent folder | download
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
/**********************************************************************

  Audacity: A Digital Audio Editor

  ExportMP2.cpp

  Joshua Haberman
  Markus Meyer

  Copyright 2002, 2003 Joshua Haberman.
  Copyright 2006 Markus Meyer
  Some portions may be Copyright 2003 Paolo Patruno.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*******************************************************************//**

\class MP2Exporter
\brief Class used to export MP2 files

*/


#include <wx/defs.h>
#include <wx/dynlib.h>
#include <wx/log.h>
#include <wx/stream.h>

#include "Export.h"
#include "FileIO.h"
#include "Mix.h"
#include "Tags.h"
#include "Track.h"

#include "ExportPluginHelpers.h"
#include "PlainExportOptionsEditor.h"

#define LIBTWOLAME_STATIC
#include "ExportPluginRegistry.h"
#include "twolame.h"

#ifdef USE_LIBID3TAG
   #include <id3tag.h>
   // DM: the following functions were supposed to have been
   // included in id3tag.h - should be fixed in the next release
   // of mad.
   extern "C" {
      struct id3_frame *id3_frame_new(char const *);
      id3_length_t id3_latin1_length(id3_latin1_t const *);
      void id3_latin1_decode(id3_latin1_t const *, id3_ucs4_t *);
   }
#endif

//----------------------------------------------------------------------------
// ExportMP2Options
//----------------------------------------------------------------------------

namespace {

// i18n-hint kbps abbreviates "thousands of bits per second"
inline TranslatableString n_kbps( int n ) { return XO("%d kbps").Format( n ); }


const TranslatableStrings BitRateMPEG1Names {
   n_kbps(32),
   n_kbps(48),
   n_kbps(56),
   n_kbps(64),
   n_kbps(80),
   n_kbps(96),
   n_kbps(112),
   n_kbps(128),
   n_kbps(160),
   n_kbps(192),//default
   n_kbps(224),
   n_kbps(256),
   n_kbps(320),
   n_kbps(384),
};

const TranslatableStrings BitRateMPEG2Names {
   n_kbps(8),
   n_kbps(16),
   n_kbps(24),
   n_kbps(32),
   n_kbps(40),
   n_kbps(48),
   n_kbps(56),
   n_kbps(64),
   n_kbps(80),
   n_kbps(96),//default
   n_kbps(112),
   n_kbps(128),
   n_kbps(144),
   n_kbps(160)
};

enum : int {
   MP2OptionIDVersion = 0,
   MP2OptionIDBitRateMPEG1 = 1,
   MP2OptionIDBitRateMPEG2 = 2,
};

const std::initializer_list<ExportOption> MP2Options {
   {
      MP2OptionIDVersion, XO("Version"),
      1,
      ExportOption::TypeEnum,
      { 0, 1 },
      { XO("MPEG2"), XO("MPEG1") },

   },
   {
      MP2OptionIDBitRateMPEG1, XO("Bit Rate"),
      192,
      ExportOption::TypeEnum,
      { 32, 48, 56, 64, 80, 96,112,128,160, 192, 224, 256, 320, 384 },
      BitRateMPEG1Names
   },
   {
      MP2OptionIDBitRateMPEG2, XO("Bit Rate"),
      96,
      ExportOption::TypeEnum | ExportOption::Hidden,
      { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 },
      BitRateMPEG2Names,
   }
};

}

class MP2ExportOptionsEditor final : public ExportOptionsEditor
{
   std::vector<ExportOption> mOptions {MP2Options };
   std::unordered_map<ExportOptionID, ExportValue> mValues;
   Listener* mListener{};
public:
   MP2ExportOptionsEditor(Listener* listener)
      : mListener(listener)
   {
      for(auto& option : mOptions)
         mValues[option.id] = option.defaultValue;
   }

   int GetOptionsCount() const override
   {
      return static_cast<int>(mOptions.size());
   }
   bool GetOption(int index, ExportOption& option) const override
   {
      if(index >= 0 && index < mOptions.size())
      {
         option = mOptions[index];
         return true;
      }
      return false;
   }
   bool GetValue(ExportOptionID id, ExportValue& value) const override
   {
      const auto it = mValues.find(id);
      if(it != mValues.end())
      {
         value = it->second;
         return true;
      }
      return false;
   }
   bool SetValue(ExportOptionID id, const ExportValue& value) override
   {
      auto it = mValues.find(id);
      if(it == mValues.end() || it->second.index() != value.index())
         return false;

      it->second = value;

      if(id == MP2OptionIDVersion)
      {
         OnVersionChanged();

         if(mListener != nullptr)
         {
            mListener->OnExportOptionChangeBegin();
            mListener->OnExportOptionChange(mOptions[MP2OptionIDBitRateMPEG1]);
            mListener->OnExportOptionChange(mOptions[MP2OptionIDBitRateMPEG2]);
            mListener->OnExportOptionChangeEnd();

            mListener->OnSampleRateListChange();
         }
      }
      return true;
   }
   SampleRateList GetSampleRateList() const override
   {
      auto it = mValues.find(MP2OptionIDVersion);
      if(*std::get_if<int>(&it->second) == TWOLAME_MPEG1)
         return { 32000, 44100, 48000 };
      return {16000, 22050, 24000 };
   }
   void Store(audacity::BasicSettings& config) const override
   {
      auto it = mValues.find(MP2OptionIDVersion);
      config.Write(wxT("/FileFormats/MP2Version"), *std::get_if<int>(&it->second));
      it = mValues.find(MP2OptionIDBitRateMPEG1);
      config.Write(wxT("/FileFormats/MP2BitrateMPEG1"), *std::get_if<int>(&it->second));
      it = mValues.find(MP2OptionIDBitRateMPEG2);
      config.Write(wxT("/FileFormats/MP2BitrateMPEG2"), *std::get_if<int>(&it->second));
   }

   void Load(const audacity::BasicSettings& config) override
   {
      config.Read(wxT("/FileFormats/MP2Version"), std::get_if<int>(&mValues[MP2OptionIDVersion]));
      config.Read(wxT("/FileFormats/MP2BitrateMPEG1"), std::get_if<int>(&mValues[MP2OptionIDBitRateMPEG1]));
      config.Read(wxT("/FileFormats/MP2BitrateMPEG2"), std::get_if<int>(&mValues[MP2OptionIDBitRateMPEG2]));
      OnVersionChanged();
   }

   void OnVersionChanged()
   {
      if(*std::get_if<int>(&mValues[MP2OptionIDVersion]) == TWOLAME_MPEG1)
      {
         mOptions[MP2OptionIDBitRateMPEG2].flags |= ExportOption::Hidden;
         mOptions[MP2OptionIDBitRateMPEG1].flags &= ~ExportOption::Hidden;
      }
      else
      {
         mOptions[MP2OptionIDBitRateMPEG2].flags &= ~ExportOption::Hidden;
         mOptions[MP2OptionIDBitRateMPEG1].flags |= ExportOption::Hidden;
      }
   }
};

class MP2ExportProcessor final : public ExportProcessor
{
   // Values taken from the twolame simple encoder sample
   constexpr static size_t pcmBufferSize = 9216 / 2; // number of samples
   constexpr static size_t mp2BufferSize = 16384u; // bytes

   struct
   {
      TranslatableString status;
      double t0;
      double t1;
      wxFileNameWrapper fName;
      std::unique_ptr<Mixer> mixer;
      ArrayOf<char> id3buffer;
      int id3len;
      twolame_options* encodeOptions{};
      std::unique_ptr<FileIO> outFile;
   } context;

public:

   ~MP2ExportProcessor() override;

   bool Initialize(AudacityProject& project,
      const Parameters& parameters,
      const wxFileNameWrapper& filename,
      double t0, double t1, bool selectedOnly,
      double sampleRate, unsigned channels,
      MixerOptions::Downmix* mixerSpec,
      const Tags* tags) override;

   ExportResult Process(ExportProcessorDelegate& delegate) override;

private:
   static int AddTags(ArrayOf<char> &buffer, bool *endOfFile, const Tags *tags);
#ifdef USE_LIBID3TAG
   static void AddFrame(struct id3_tag *tp, const wxString & n, const wxString & v, const char *name);
#endif

};

class ExportMP2 final : public ExportPlugin
{
public:

   ExportMP2();

   int GetFormatCount() const override;
   FormatInfo GetFormatInfo(int) const override;

   // Required

   std::unique_ptr<ExportOptionsEditor>
   CreateOptionsEditor(int, ExportOptionsEditor::Listener*) const override;

   std::unique_ptr<ExportProcessor> CreateProcessor(int) const override;
};

ExportMP2::ExportMP2() = default;

int ExportMP2::GetFormatCount() const
{
   return 1;
}

FormatInfo ExportMP2::GetFormatInfo(int) const
{
   return {
      wxT("MP2"), XO("MP2 Files"), { wxT("mp2") }, 2, true
   };
}

std::unique_ptr<ExportOptionsEditor>
ExportMP2::CreateOptionsEditor(int, ExportOptionsEditor::Listener* listener) const
{
   return std::make_unique<MP2ExportOptionsEditor>(listener);
}

std::unique_ptr<ExportProcessor> ExportMP2::CreateProcessor(int) const
{
   return std::make_unique<MP2ExportProcessor>();
}

MP2ExportProcessor::~MP2ExportProcessor()
{
   if(context.encodeOptions)
      twolame_close(&context.encodeOptions);
}


bool MP2ExportProcessor::Initialize(AudacityProject& project,
   const Parameters& parameters,
   const wxFileNameWrapper& fName,
   double t0, double t1, bool selectionOnly,
   double sampleRate, unsigned channels,
   MixerOptions::Downmix* mixerSpec,
   const Tags* metadata)
{
   context.t0 = t0;
   context.t1 = t1;
   context.fName = fName;

   bool stereo = (channels == 2);
   const auto version = static_cast<TWOLAME_MPEG_version>(
      ExportPluginHelpers::GetParameterValue(parameters,
         MP2OptionIDVersion, 1));

   const auto bitrate = version == TWOLAME_MPEG1
      ? ExportPluginHelpers::GetParameterValue(
         parameters,
         MP2OptionIDBitRateMPEG1, 192)
      : ExportPluginHelpers::GetParameterValue(
         parameters,
         MP2OptionIDBitRateMPEG2, 96);

   wxLogNull logNo;             /* temporarily disable wxWidgets error messages */

   twolame_options *&encodeOptions = context.encodeOptions;
   encodeOptions = twolame_init();

   twolame_set_version(encodeOptions, version);
   twolame_set_in_samplerate(encodeOptions, static_cast<int>(sampleRate));
   twolame_set_out_samplerate(encodeOptions, static_cast<int>(sampleRate));
   twolame_set_bitrate(encodeOptions, bitrate);
   twolame_set_num_channels(encodeOptions, stereo ? 2 : 1);

   if (twolame_init_params(encodeOptions) != 0)
   {
      throw ExportException(_("Cannot export MP2 with this sample rate and bit rate"));
   }

   // Put ID3 tags at beginning of file
   if (metadata == NULL)
      metadata = &Tags::Get( project );

   context.outFile = std::make_unique<FileIO>(fName, FileIO::Output);
   if (!context.outFile->IsOpened()) {
      throw ExportException(_("Unable to open target file for writing"));
   }

   bool endOfFile;
   context.id3len = AddTags(context.id3buffer, &endOfFile, metadata);
   if (context.id3len && !endOfFile) {
      if ( context.outFile->Write(context.id3buffer.get(), context.id3len).GetLastError() ) {
         // TODO: more precise message
         throw ExportErrorException("MP2:292");
      }
      context.id3len = 0;
      context.id3buffer.reset();
   }

   context.status = selectionOnly
      ? XO("Exporting selected audio at %ld kbps")
           .Format( bitrate )
      : XO("Exporting the audio at %ld kbps")
           .Format( bitrate );

   context.mixer = ExportPluginHelpers::CreateMixer(
      project, selectionOnly, t0, t1, stereo ? 2 : 1, pcmBufferSize, true,
      sampleRate, int16Sample, mixerSpec);

   return true;
}

ExportResult MP2ExportProcessor::Process(ExportProcessorDelegate& delegate)
{
   delegate.SetStatusString(context.status);
   // We allocate a buffer which is twice as big as the
   // input buffer, which should always be enough.
   // We have to multiply by 4 because one sample is 2 bytes wide!
   ArrayOf<unsigned char> mp2Buffer{ mp2BufferSize };

   auto exportResult = ExportResult::Success;

   {
      while (exportResult == ExportResult::Success) {
         auto pcmNumSamples = context.mixer->Process();
         if (pcmNumSamples == 0)
            break;

         short *pcmBuffer = (short *)context.mixer->GetBuffer();

         int mp2BufferNumBytes = twolame_encode_buffer_interleaved(
            context.encodeOptions,
            pcmBuffer,
            pcmNumSamples,
            mp2Buffer.get(),
            mp2BufferSize);

         if (mp2BufferNumBytes < 0) {
            // TODO: more precise message
            throw ExportErrorException("MP2:339");
         }

         if ( context.outFile->Write(mp2Buffer.get(), mp2BufferNumBytes).GetLastError() ) {
            // TODO: more precise message
            throw ExportDiskFullError(context.fName);
         }
         exportResult = ExportPluginHelpers::UpdateProgress(
            delegate, *context.mixer, context.t0, context.t1);
      }
   }

   int mp2BufferNumBytes = twolame_encode_flush(
      context.encodeOptions,
      mp2Buffer.get(),
      mp2BufferSize);

   if (mp2BufferNumBytes > 0)
      if ( context.outFile->Write(mp2Buffer.get(), mp2BufferNumBytes).GetLastError() ) {
         // TODO: more precise message
         throw ExportErrorException("MP2:362");
      }

   /* Write ID3 tag if it was supposed to be at the end of the file */

   if (context.id3len)
      if ( context.outFile->Write(context.id3buffer.get(), context.id3len).GetLastError() ) {
         // TODO: more precise message
         throw ExportErrorException("MP2:371");
      }

   if ( !context.outFile->Close() ) {
      // TODO: more precise message
      throw ExportErrorException("MP2:377");
   }
   return exportResult;
}


#ifdef USE_LIBID3TAG
struct id3_tag_deleter {
   void operator () (id3_tag *p) const { if (p) id3_tag_delete(p); }
};
using id3_tag_holder = std::unique_ptr<id3_tag, id3_tag_deleter>;
#endif

// returns buffer len; caller frees
int MP2ExportProcessor::AddTags(ArrayOf< char > &buffer,
   bool *endOfFile, const Tags *tags)
{
#ifdef USE_LIBID3TAG
   id3_tag_holder tp { id3_tag_new() };

   for (const auto &pair : tags->GetRange()) {
      const auto &n = pair.first;
      const auto &v = pair.second;
      const char *name = "TXXX";

      if (n.CmpNoCase(TAG_TITLE) == 0) {
         name = ID3_FRAME_TITLE;
      }
      else if (n.CmpNoCase(TAG_ARTIST) == 0) {
         name = ID3_FRAME_ARTIST;
      }
      else if (n.CmpNoCase(TAG_ALBUM) == 0) {
         name = ID3_FRAME_ALBUM;
      }
      else if (n.CmpNoCase(TAG_YEAR) == 0) {
         // LLL:  Some apps do not like the newer frame ID (ID3_FRAME_YEAR),
         //       so we add old one as well.
         AddFrame(tp.get(), n, v, "TYER");
         name = ID3_FRAME_YEAR;
      }
      else if (n.CmpNoCase(TAG_GENRE) == 0) {
         name = ID3_FRAME_GENRE;
      }
      else if (n.CmpNoCase(TAG_COMMENTS) == 0) {
         name = ID3_FRAME_COMMENT;
      }
      else if (n.CmpNoCase(TAG_TRACK) == 0) {
         name = ID3_FRAME_TRACK;
      }

      AddFrame(tp.get(), n, v, name);
   }

   tp->options &= (~ID3_TAG_OPTION_COMPRESSION); // No compression

   // If this version of libid3tag supports it, use v2.3 ID3
   // tags instead of the newer, but less well supported, v2.4
   // that libid3tag uses by default.
   #ifdef ID3_TAG_HAS_TAG_OPTION_ID3V2_3
   tp->options |= ID3_TAG_OPTION_ID3V2_3;
   #endif

   *endOfFile = false;

   id3_length_t len;

   len = id3_tag_render(tp.get(), 0);
   buffer.reinit(len);
   len = id3_tag_render(tp.get(), (id3_byte_t *)buffer.get());


   return len;
#else //ifdef USE_LIBID3TAG
   return 0;
#endif
}

#ifdef USE_LIBID3TAG
void MP2ExportProcessor::AddFrame(struct id3_tag *tp, const wxString & n, const wxString & v, const char *name)
{
   struct id3_frame *frame = id3_frame_new(name);

   if (!n.IsAscii() || !v.IsAscii()) {
      id3_field_settextencoding(id3_frame_field(frame, 0), ID3_FIELD_TEXTENCODING_UTF_16);
   }
   else {
      id3_field_settextencoding(id3_frame_field(frame, 0), ID3_FIELD_TEXTENCODING_ISO_8859_1);
   }

   MallocString<id3_ucs4_t> ucs4 {
      id3_utf8_ucs4duplicate((id3_utf8_t *) (const char *) v.mb_str(wxConvUTF8)) };

   if (strcmp(name, ID3_FRAME_COMMENT) == 0) {
      // A hack to get around iTunes not recognizing the comment.  The
      // language defaults to XXX and, since it's not a valid language,
      // iTunes just ignores the tag.  So, either set it to a valid language
      // (which one???) or just clear it.  Unfortunately, there's no supported
      // way of clearing the field, so do it directly.
      id3_field *f = id3_frame_field(frame, 1);
      memset(f->immediate.value, 0, sizeof(f->immediate.value));
      id3_field_setfullstring(id3_frame_field(frame, 3), ucs4.get());
   }
   else if (strcmp(name, "TXXX") == 0) {
      id3_field_setstring(id3_frame_field(frame, 2), ucs4.get());

      ucs4.reset(id3_utf8_ucs4duplicate((id3_utf8_t *) (const char *) n.mb_str(wxConvUTF8)));

      id3_field_setstring(id3_frame_field(frame, 1), ucs4.get());
   }
   else {
      auto addr = ucs4.get();
      id3_field_setstrings(id3_frame_field(frame, 1), 1, &addr);
   }

   id3_tag_attachframe(tp, frame);
}
#endif

static ExportPluginRegistry::RegisteredPlugin sRegisteredPlugin{ "MP2",
   []{ return std::make_unique< ExportMP2 >(); }
};