utils.cpp 17.3 KB
Newer Older
moto's avatar
moto committed
1
2
#include <c10/core/ScalarType.h>
#include <sox.h>
3
#include <torchaudio/csrc/sox/types.h>
moto's avatar
moto committed
4
#include <torchaudio/csrc/sox/utils.h>
moto's avatar
moto committed
5
6
7
8

namespace torchaudio {
namespace sox_utils {

moto's avatar
moto committed
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
void set_seed(const int64_t seed) {
  sox_get_globals()->ranqd1 = static_cast<sox_int32_t>(seed);
}

void set_verbosity(const int64_t verbosity) {
  sox_get_globals()->verbosity = static_cast<unsigned>(verbosity);
}

void set_use_threads(const bool use_threads) {
  sox_get_globals()->use_threads = static_cast<sox_bool>(use_threads);
}

void set_buffer_size(const int64_t buffer_size) {
  sox_get_globals()->bufsiz = static_cast<size_t>(buffer_size);
}

std::vector<std::vector<std::string>> list_effects() {
  std::vector<std::vector<std::string>> effects;
  for (const sox_effect_fn_t* fns = sox_get_effect_fns(); *fns; ++fns) {
    const sox_effect_handler_t* handler = (*fns)();
    if (handler && handler->name) {
      if (UNSUPPORTED_EFFECTS.find(handler->name) ==
          UNSUPPORTED_EFFECTS.end()) {
        effects.emplace_back(std::vector<std::string>{
            handler->name,
            handler->usage ? std::string(handler->usage) : std::string("")});
      }
    }
  }
  return effects;
}

41
std::vector<std::string> list_write_formats() {
moto's avatar
moto committed
42
43
  std::vector<std::string> formats;
  for (const sox_format_tab_t* fns = sox_get_format_fns(); fns->fn; ++fns) {
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    const sox_format_handler_t* handler = fns->fn();
    for (const char* const* names = handler->names; *names; ++names) {
      if (!strchr(*names, '/') && handler->write)
        formats.emplace_back(*names);
    }
  }
  return formats;
}

std::vector<std::string> list_read_formats() {
  std::vector<std::string> formats;
  for (const sox_format_tab_t* fns = sox_get_format_fns(); fns->fn; ++fns) {
    const sox_format_handler_t* handler = fns->fn();
    for (const char* const* names = handler->names; *names; ++names) {
      if (!strchr(*names, '/') && handler->read)
moto's avatar
moto committed
59
60
61
62
63
64
        formats.emplace_back(*names);
    }
  }
  return formats;
}

moto's avatar
moto committed
65
SoxFormat::SoxFormat(sox_format_t* fd) noexcept : fd_(fd) {}
moto's avatar
moto committed
66
67
68
SoxFormat::~SoxFormat() {
  close();
}
69

moto's avatar
moto committed
70
71
72
sox_format_t* SoxFormat::operator->() const noexcept {
  return fd_;
}
73
SoxFormat::operator sox_format_t*() const noexcept {
moto's avatar
moto committed
74
75
76
  return fd_;
}

77
78
79
80
81
82
83
void SoxFormat::close() {
  if (fd_ != nullptr) {
    sox_close(fd_);
    fd_ = nullptr;
  }
}

84
void validate_input_file(const SoxFormat& sf, bool check_length) {
85
  if (static_cast<sox_format_t*>(sf) == nullptr) {
moto's avatar
moto committed
86
87
88
89
90
    throw std::runtime_error("Error loading audio file: failed to open file.");
  }
  if (sf->encoding.encoding == SOX_ENCODING_UNKNOWN) {
    throw std::runtime_error("Error loading audio file: unknown encoding.");
  }
91
92
  if (check_length && sf->signal.length == 0) {
    throw std::runtime_error("Error reading audio file: unknown length.");
moto's avatar
moto committed
93
94
95
  }
}

96
97
98
99
100
101
102
103
104
void validate_input_tensor(const torch::Tensor tensor) {
  if (!tensor.device().is_cpu()) {
    throw std::runtime_error("Input tensor has to be on CPU.");
  }

  if (tensor.ndimension() != 2) {
    throw std::runtime_error("Input tensor has to be 2D.");
  }

105
106
107
108
109
110
111
112
113
  switch (tensor.dtype().toScalarType()) {
    case c10::ScalarType::Byte:
    case c10::ScalarType::Short:
    case c10::ScalarType::Int:
    case c10::ScalarType::Float:
      break;
    default:
      throw std::runtime_error(
          "Input tensor has to be one of float32, int32, int16 or uint8 type.");
114
115
116
  }
}

moto's avatar
moto committed
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
caffe2::TypeMeta get_dtype(
    const sox_encoding_t encoding,
    const unsigned precision) {
  const auto dtype = [&]() {
    switch (encoding) {
      case SOX_ENCODING_UNSIGNED: // 8-bit PCM WAV
        return torch::kUInt8;
      case SOX_ENCODING_SIGN2: // 16-bit or 32-bit PCM WAV
        switch (precision) {
          case 16:
            return torch::kInt16;
          case 32:
            return torch::kInt32;
          default:
            throw std::runtime_error(
                "Only 16 and 32 bits are supported for signed PCM.");
        }
      default:
        // default to float32 for the other formats, including
        // 32-bit flaoting-point WAV,
        // MP3,
        // FLAC,
        // VORBIS etc...
        return torch::kFloat32;
    }
  }();
  return c10::scalarTypeToTypeMeta(dtype);
}
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

caffe2::TypeMeta get_dtype_from_str(const std::string dtype) {
  const auto tgt_dtype = [&]() {
    if (dtype == "uint8")
      return torch::kUInt8;
    else if (dtype == "int16")
      return torch::kInt16;
    else if (dtype == "int32")
      return torch::kInt32;
    else if (dtype == "float32")
      return torch::kFloat32;
    else if (dtype == "float64")
      return torch::kFloat64;
    else
      throw std::runtime_error("Unsupported dtype");
  }();
  return c10::scalarTypeToTypeMeta(tgt_dtype);
}
moto's avatar
moto committed
163
164
165
166
167
168
169
170

torch::Tensor convert_to_tensor(
    sox_sample_t* buffer,
    const int32_t num_samples,
    const int32_t num_channels,
    const caffe2::TypeMeta dtype,
    const bool normalize,
    const bool channels_first) {
171
172
173
  torch::Tensor t;
  uint64_t dummy;
  SOX_SAMPLE_LOCALS;
moto's avatar
moto committed
174
  if (normalize || dtype == torch::kFloat32) {
175
176
177
178
179
180
    t = torch::empty(
        {num_samples / num_channels, num_channels}, torch::kFloat32);
    auto ptr = t.data_ptr<float_t>();
    for (int32_t i = 0; i < num_samples; ++i) {
      ptr[i] = SOX_SAMPLE_TO_FLOAT_32BIT(buffer[i], dummy);
    }
moto's avatar
moto committed
181
  } else if (dtype == torch::kInt32) {
182
183
184
    t = torch::from_blob(
            buffer, {num_samples / num_channels, num_channels}, torch::kInt32)
            .clone();
moto's avatar
moto committed
185
  } else if (dtype == torch::kInt16) {
186
187
188
189
190
    t = torch::empty({num_samples / num_channels, num_channels}, torch::kInt16);
    auto ptr = t.data_ptr<int16_t>();
    for (int32_t i = 0; i < num_samples; ++i) {
      ptr[i] = SOX_SAMPLE_TO_SIGNED_16BIT(buffer[i], dummy);
    }
moto's avatar
moto committed
191
  } else if (dtype == torch::kUInt8) {
192
193
194
195
196
    t = torch::empty({num_samples / num_channels, num_channels}, torch::kUInt8);
    auto ptr = t.data_ptr<uint8_t>();
    for (int32_t i = 0; i < num_samples; ++i) {
      ptr[i] = SOX_SAMPLE_TO_UNSIGNED_8BIT(buffer[i], dummy);
    }
moto's avatar
moto committed
197
198
199
200
201
202
203
204
205
  } else {
    throw std::runtime_error("Unsupported dtype.");
  }
  if (channels_first) {
    t = t.transpose(1, 0);
  }
  return t.contiguous();
}

206
207
208
209
210
211
const std::string get_filetype(const std::string path) {
  std::string ext = path.substr(path.find_last_of(".") + 1);
  std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  return ext;
}

212
213
214
215
namespace {

std::tuple<sox_encoding_t, unsigned> get_save_encoding_for_wav(
    const std::string format,
216
    caffe2::TypeMeta dtype,
217
218
219
220
221
222
    const Encoding& encoding,
    const BitDepth& bits_per_sample) {
  switch (encoding) {
    case Encoding::NOT_PROVIDED:
      switch (bits_per_sample) {
        case BitDepth::NOT_PROVIDED:
223
224
225
226
227
228
229
230
231
232
233
234
          switch (dtype.toScalarType()) {
            case c10::ScalarType::Float:
              return std::make_tuple<>(SOX_ENCODING_FLOAT, 32);
            case c10::ScalarType::Int:
              return std::make_tuple<>(SOX_ENCODING_SIGN2, 32);
            case c10::ScalarType::Short:
              return std::make_tuple<>(SOX_ENCODING_SIGN2, 16);
            case c10::ScalarType::Byte:
              return std::make_tuple<>(SOX_ENCODING_UNSIGNED, 8);
            default:
              throw std::runtime_error("Internal Error: Unexpected dtype.");
          }
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
        case BitDepth::B8:
          return std::make_tuple<>(SOX_ENCODING_UNSIGNED, 8);
        default:
          return std::make_tuple<>(
              SOX_ENCODING_SIGN2, static_cast<unsigned>(bits_per_sample));
      }
    case Encoding::PCM_SIGNED:
      switch (bits_per_sample) {
        case BitDepth::NOT_PROVIDED:
          return std::make_tuple<>(SOX_ENCODING_SIGN2, 32);
        case BitDepth::B8:
          throw std::runtime_error(
              format + " does not support 8-bit signed PCM encoding.");
        default:
          return std::make_tuple<>(
              SOX_ENCODING_SIGN2, static_cast<unsigned>(bits_per_sample));
      }
    case Encoding::PCM_UNSIGNED:
      switch (bits_per_sample) {
        case BitDepth::NOT_PROVIDED:
        case BitDepth::B8:
          return std::make_tuple<>(SOX_ENCODING_UNSIGNED, 8);
        default:
          throw std::runtime_error(
              format + " only supports 8-bit for unsigned PCM encoding.");
      }
    case Encoding::PCM_FLOAT:
      switch (bits_per_sample) {
        case BitDepth::NOT_PROVIDED:
        case BitDepth::B32:
          return std::make_tuple<>(SOX_ENCODING_FLOAT, 32);
        case BitDepth::B64:
          return std::make_tuple<>(SOX_ENCODING_FLOAT, 64);
        default:
          throw std::runtime_error(
              format +
              " only supports 32-bit or 64-bit for floating-point PCM encoding.");
      }
    case Encoding::ULAW:
      switch (bits_per_sample) {
        case BitDepth::NOT_PROVIDED:
        case BitDepth::B8:
          return std::make_tuple<>(SOX_ENCODING_ULAW, 8);
        default:
          throw std::runtime_error(
              format + " only supports 8-bit for mu-law encoding.");
      }
    case Encoding::ALAW:
      switch (bits_per_sample) {
        case BitDepth::NOT_PROVIDED:
        case BitDepth::B8:
          return std::make_tuple<>(SOX_ENCODING_ALAW, 8);
        default:
          throw std::runtime_error(
              format + " only supports 8-bit for a-law encoding.");
      }
    default:
      throw std::runtime_error(
          format + " does not support encoding: " + to_string(encoding));
  }
}

std::tuple<sox_encoding_t, unsigned> get_save_encoding(
    const std::string& format,
    const caffe2::TypeMeta dtype,
    const c10::optional<std::string>& encoding,
    const c10::optional<int64_t>& bits_per_sample) {
  const Format fmt = get_format_from_string(format);
  const Encoding enc = get_encoding_from_option(encoding);
  const BitDepth bps = get_bit_depth_from_option(bits_per_sample);

  switch (fmt) {
    case Format::WAV:
    case Format::AMB:
      return get_save_encoding_for_wav(format, dtype, enc, bps);
    case Format::MP3:
      if (enc != Encoding::NOT_PROVIDED)
        throw std::runtime_error("mp3 does not support `encoding` option.");
      if (bps != BitDepth::NOT_PROVIDED)
        throw std::runtime_error(
            "mp3 does not support `bits_per_sample` option.");
      return std::make_tuple<>(SOX_ENCODING_MP3, 16);
    case Format::VORBIS:
      if (enc != Encoding::NOT_PROVIDED)
        throw std::runtime_error("vorbis does not support `encoding` option.");
      if (bps != BitDepth::NOT_PROVIDED)
        throw std::runtime_error(
            "vorbis does not support `bits_per_sample` option.");
      return std::make_tuple<>(SOX_ENCODING_VORBIS, 16);
    case Format::AMR_NB:
      if (enc != Encoding::NOT_PROVIDED)
        throw std::runtime_error("amr-nb does not support `encoding` option.");
      if (bps != BitDepth::NOT_PROVIDED)
        throw std::runtime_error(
            "amr-nb does not support `bits_per_sample` option.");
      return std::make_tuple<>(SOX_ENCODING_AMR_NB, 16);
    case Format::FLAC:
      if (enc != Encoding::NOT_PROVIDED)
        throw std::runtime_error("flac does not support `encoding` option.");
      switch (bps) {
        case BitDepth::B32:
        case BitDepth::B64:
          throw std::runtime_error(
              "flac does not support `bits_per_sample` larger than 24.");
        default:
          return std::make_tuple<>(
              SOX_ENCODING_FLAC, static_cast<unsigned>(bps));
      }
    case Format::SPHERE:
      switch (enc) {
        case Encoding::NOT_PROVIDED:
        case Encoding::PCM_SIGNED:
          switch (bps) {
            case BitDepth::NOT_PROVIDED:
              return std::make_tuple<>(SOX_ENCODING_SIGN2, 32);
            default:
              return std::make_tuple<>(
                  SOX_ENCODING_SIGN2, static_cast<unsigned>(bps));
          }
        case Encoding::PCM_UNSIGNED:
          throw std::runtime_error(
              "sph does not support unsigned integer PCM.");
        case Encoding::PCM_FLOAT:
          throw std::runtime_error("sph does not support floating point PCM.");
        case Encoding::ULAW:
          switch (bps) {
            case BitDepth::NOT_PROVIDED:
            case BitDepth::B8:
              return std::make_tuple<>(SOX_ENCODING_ULAW, 8);
            default:
              throw std::runtime_error(
                  "sph only supports 8-bit for mu-law encoding.");
          }
        case Encoding::ALAW:
          switch (bps) {
            case BitDepth::NOT_PROVIDED:
            case BitDepth::B8:
              return std::make_tuple<>(SOX_ENCODING_ALAW, 8);
            default:
              return std::make_tuple<>(
                  SOX_ENCODING_ALAW, static_cast<unsigned>(bps));
          }
        default:
          throw std::runtime_error(
              "sph does not support encoding: " + encoding.value());
      }
    default:
      throw std::runtime_error("Unsupported format: " + format);
383
384
385
  }
}

386
unsigned get_precision(const std::string filetype, caffe2::TypeMeta dtype) {
387
388
389
390
391
392
  if (filetype == "mp3")
    return SOX_UNSPEC;
  if (filetype == "flac")
    return 24;
  if (filetype == "ogg" || filetype == "vorbis")
    return SOX_UNSPEC;
393
  if (filetype == "wav" || filetype == "amb") {
394
395
396
397
398
399
400
401
402
403
404
405
    switch (dtype.toScalarType()) {
      case c10::ScalarType::Byte:
        return 8;
      case c10::ScalarType::Short:
        return 16;
      case c10::ScalarType::Int:
        return 32;
      case c10::ScalarType::Float:
        return 32;
      default:
        throw std::runtime_error("Unsupported dtype.");
    }
406
  }
moto's avatar
moto committed
407
408
  if (filetype == "sph")
    return 32;
409
410
411
412
  if (filetype == "amr-nb") {
    return 16;
  }
  throw std::runtime_error("Unsupported file type: " + filetype);
413
414
}

415
416
} // namespace

417
sox_signalinfo_t get_signalinfo(
418
419
420
421
    const torch::Tensor* waveform,
    const int64_t sample_rate,
    const std::string filetype,
    const bool channels_first) {
422
  return sox_signalinfo_t{
423
      /*rate=*/static_cast<sox_rate_t>(sample_rate),
moto's avatar
moto committed
424
      /*channels=*/
425
426
427
      static_cast<unsigned>(waveform->size(channels_first ? 0 : 1)),
      /*precision=*/get_precision(filetype, waveform->dtype()),
      /*length=*/static_cast<uint64_t>(waveform->numel())};
428
429
}

430
sox_encodinginfo_t get_tensor_encodinginfo(caffe2::TypeMeta dtype) {
431
  sox_encoding_t encoding = [&]() {
432
433
434
435
436
437
438
439
440
441
442
443
    switch (dtype.toScalarType()) {
      case c10::ScalarType::Byte:
        return SOX_ENCODING_UNSIGNED;
      case c10::ScalarType::Short:
        return SOX_ENCODING_SIGN2;
      case c10::ScalarType::Int:
        return SOX_ENCODING_SIGN2;
      case c10::ScalarType::Float:
        return SOX_ENCODING_FLOAT;
      default:
        throw std::runtime_error("Unsupported dtype.");
    }
444
445
  }();
  unsigned bits_per_sample = [&]() {
446
447
448
449
450
451
452
453
454
455
456
457
    switch (dtype.toScalarType()) {
      case c10::ScalarType::Byte:
        return 8;
      case c10::ScalarType::Short:
        return 16;
      case c10::ScalarType::Int:
        return 32;
      case c10::ScalarType::Float:
        return 32;
      default:
        throw std::runtime_error("Unsupported dtype.");
    }
458
  }();
moto's avatar
moto committed
459
  return sox_encodinginfo_t{
460
461
      /*encoding=*/encoding,
      /*bits_per_sample=*/bits_per_sample,
moto's avatar
moto committed
462
463
464
465
466
      /*compression=*/HUGE_VAL,
      /*reverse_bytes=*/sox_option_default,
      /*reverse_nibbles=*/sox_option_default,
      /*reverse_bits=*/sox_option_default,
      /*opposite_endian=*/sox_false};
467
}
468

469
sox_encodinginfo_t get_encodinginfo_for_save(
470
    const std::string& format,
471
    const caffe2::TypeMeta dtype,
472
473
474
475
    const c10::optional<double>& compression,
    const c10::optional<std::string>& encoding,
    const c10::optional<int64_t>& bits_per_sample) {
  auto enc = get_save_encoding(format, dtype, encoding, bits_per_sample);
moto's avatar
moto committed
476
  return sox_encodinginfo_t{
477
478
      /*encoding=*/std::get<0>(enc),
      /*bits_per_sample=*/std::get<1>(enc),
moto's avatar
moto committed
479
480
481
482
483
      /*compression=*/compression.value_or(HUGE_VAL),
      /*reverse_bytes=*/sox_option_default,
      /*reverse_nibbles=*/sox_option_default,
      /*reverse_bits=*/sox_option_default,
      /*opposite_endian=*/sox_false};
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
#ifdef TORCH_API_INCLUDE_EXTENSION_H

uint64_t read_fileobj(py::object* fileobj, const uint64_t size, char* buffer) {
  uint64_t num_read = 0;
  while (num_read < size) {
    auto request = size - num_read;
    auto chunk = static_cast<std::string>(
        static_cast<py::bytes>(fileobj->attr("read")(request)));
    auto chunk_len = chunk.length();
    if (chunk_len == 0) {
      break;
    }
    if (chunk_len > request) {
      std::ostringstream message;
      message
          << "Requested up to " << request << " bytes but, "
          << "received " << chunk_len << " bytes. "
          << "The given object does not confirm to read protocol of file object.";
      throw std::runtime_error(message.str());
    }
    memcpy(buffer, chunk.data(), chunk_len);
    buffer += chunk_len;
    num_read += chunk_len;
  }
  return num_read;
}

#endif // TORCH_API_INCLUDE_EXTENSION_H

515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
TORCH_LIBRARY_FRAGMENT(torchaudio, m) {
  m.def("torchaudio::sox_utils_set_seed", &torchaudio::sox_utils::set_seed);
  m.def(
      "torchaudio::sox_utils_set_verbosity",
      &torchaudio::sox_utils::set_verbosity);
  m.def(
      "torchaudio::sox_utils_set_use_threads",
      &torchaudio::sox_utils::set_use_threads);
  m.def(
      "torchaudio::sox_utils_set_buffer_size",
      &torchaudio::sox_utils::set_buffer_size);
  m.def(
      "torchaudio::sox_utils_list_effects",
      &torchaudio::sox_utils::list_effects);
  m.def(
      "torchaudio::sox_utils_list_read_formats",
      &torchaudio::sox_utils::list_read_formats);
  m.def(
      "torchaudio::sox_utils_list_write_formats",
      &torchaudio::sox_utils::list_write_formats);
}

moto's avatar
moto committed
537
538
} // namespace sox_utils
} // namespace torchaudio