Class: AudioMonster::Monster

Inherits:
Object
  • Object
show all
Includes:
Configuration, NuWav
Defined in:
lib/audio_monster/monster.rb

Constant Summary collapse

COMMON_EXTENSIONS =

when we want to be sure a format string is chosen esp. when mimemagic has multiple options

{
  'application/xml' => 'xml',
  'audio/mpeg' => 'mp3',
  'audio/flac' => 'flac',
  'audio/mp4'  => 'm4a',
  'audio/ogg'  => 'ogg',
  'image/jpeg' => 'jpg',
  'text/plain' => 'txt'
}
MAX_FILENAME_LENGTH =
160
MAX_EXTENSION_LENGTH =
6

Constants included from Configuration

Configuration::AES46_2002_DATE_FORMAT, Configuration::AES46_2002_TIME_FORMAT, Configuration::BINARIES_KEYS, Configuration::FILE_SUCCESS, Configuration::LAME_ERROR_RE, Configuration::LAME_MODES, Configuration::LAME_SUCCESS_RE, Configuration::MP2_BITRATES, Configuration::MP2_SAMPLE_RATES, Configuration::MP3VAL_ERROR_RE, Configuration::MP3VAL_IGNORE_RE, Configuration::MP3VAL_WARNING_RE, Configuration::MP3_BITRATES, Configuration::MP3_SAMPLE_RATES, Configuration::PRSS_DATE_FORMAT, Configuration::SOX_ERROR_RE, Configuration::TWOLAME_MODES, Configuration::TWOLAME_SUCCESS_RE, Configuration::VALID_OPTIONS_KEYS

Instance Method Summary collapse

Methods included from Configuration

#apply_configuration, #bin, #check_binaries, #configure, #current_options, #current_options=, extended, #find_executable, included, #options, #reset!

Constructor Details

#initialize(options = {}) ⇒ Monster

Returns a new instance of Monster.



34
35
36
37
# File 'lib/audio_monster/monster.rb', line 34

def initialize(options={})
  apply_configuration(options)
  check_binaries if ENV['AUDIO_MONSTER_DEBUG']
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (protected)



945
946
947
948
949
950
951
952
953
# File 'lib/audio_monster/monster.rb', line 945

def method_missing(name, *args, &block)
  if name.to_s.starts_with?('encode_wav_pcm_from_')
    decode_audio(*args)
  elsif name.to_s.starts_with?('info_for_')
    info_for(*args)
  else
    super
  end
end

Instance Method Details

#add_cart_chunk_to_wav(wave_path, result_path, options = {}) ⇒ Object



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
# File 'lib/audio_monster/monster.rb', line 601

def add_cart_chunk_to_wav(wave_path, result_path, options={})
  wave = NuWav::WaveFile.parse(wave_path)
  unless wave.chunks[:cart]
    cart = CartChunk.new
    now = Time.now
    today = Date.today
    later = today << 12

    cart.title                = options[:title] || File.basename(wave_path)
    cart.artist               = options[:artist]
    cart.cut_id               = options[:cut_id]

    cart.version              = options[:version] || '0101'
    cart.producer_app_id      = options[:producer_app_id] || 'ContentDepot'
    cart.producer_app_version = options[:producer_app_version] || '1.0'
    cart.level_reference      = options[:level_reference] || 0
    cart.tag_text             = options[:tag_text] || "\r\n"
    cart.start_date           = (options[:start_at] || today).strftime(PRSS_DATE_FORMAT)
    cart.start_time           = (options[:start_at] || now).strftime(AES46_2002_TIME_FORMAT)
    cart.end_date             = (options[:end_at] || later).strftime(PRSS_DATE_FORMAT)
    cart.end_time             = (options[:end_at] || now).strftime(AES46_2002_TIME_FORMAT)

    wave.chunks[:cart] = cart
  end

  wave.to_file(result_path)

  check_local_file(result_path)

  return true
end

#append_wav_to_wav(wav_path, append_wav_path, out_path, add_length, fade_length = 5) ⇒ Object



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
# File 'lib/audio_monster/monster.rb', line 705

def append_wav_to_wav(wav_path, append_wav_path, out_path, add_length, fade_length=5)
  append_wav_info = info_for_wav(append_wav_path)
  raise "append wav is not sufficiently long enough (#{append_wav_info[:length]}) to add length (#{add_length})" if append_wav_info[:length].to_i < add_length

  append_length = [append_wav_info[:length].to_i, (add_length - 1)].min

  append_fade_length = [append_wav_info[:length].to_i, fade_length].min

  # find out if the wav file is stereo or mono as this needs to match the starting wav
  wav_info = info_for_wav(wav_path)
  channels = wav_info[:channel_mode] == 'Mono' ? 1 : 2
  sample_rate = wav_info[:sample_rate]
  append_file = nil

  begin
    append_file = create_temp_file(append_wav_path)
    append_file.close

    # create the wav to append
    command = "#{bin(:sox)} -t wav '#{append_wav_path}' -t raw -s -b 16 -c #{channels} - trim 0 #{append_length} | #{bin(:sox)} -t raw -r #{sample_rate} -s -b 16 -c #{channels} - -t raw - fade h 0 #{append_length} #{append_fade_length} | #{bin(:sox)} -t raw -r #{sample_rate} -s -b 16 -c #{channels} - -t wav '#{append_file.path}' pad 1 0"
    out, err = run_command(command)
    response = out + err
    response.split("\n").each{ |out| raise("append_wav_to_wav: create append file error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }

    # append the files to out_file
    command = "#{bin(:sox)} -t wav '#{wav_path}' -t wav '#{append_file.path}' -t wav '#{out_path}'"
    out, err = run_command(command)
    response = out + err
    response.split("\n").each{ |out| raise("append_wav_to_wav: create append file error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }
  ensure
    append_file.close rescue nil
    append_file.unlink rescue nil
  end

  return true
end

#audio_file_bit_rate(path, info = nil) ⇒ Object



293
294
295
296
297
298
299
# File 'lib/audio_monster/monster.rb', line 293

def audio_file_bit_rate(path, info = nil)
  # audio_file_info_soxi(path, 'B').to_i
  info ||= audio_file_info_ffprobe(path)
  stream = info['streams'].detect { |s| s['codec_type'] == 'audio' }
  bit_rate = stream['bit_rate'] || info['format']['bit_rate']
  (BigDecimal.new(bit_rate) / 1000).round
end

#audio_file_channels(path, info = nil) ⇒ Object



279
280
281
282
283
284
# File 'lib/audio_monster/monster.rb', line 279

def audio_file_channels(path, info = nil)
  # audio_file_info_soxi(path, 'c').to_i
  info ||= audio_file_info_ffprobe(path)
  stream = info['streams'].detect { |s| s['codec_type'] == 'audio' }
  stream['channels'].to_i
end

#audio_file_duration(path, info = nil) ⇒ Object



273
274
275
276
277
# File 'lib/audio_monster/monster.rb', line 273

def audio_file_duration(path, info = nil)
  # audio_file_info_soxi(path, 'D').to_f
  info ||= audio_file_info_ffprobe(path)
  info['format']['duration'].to_f
end

#audio_file_format(path, info = nil) ⇒ Object



263
264
265
266
267
268
269
270
271
# File 'lib/audio_monster/monster.rb', line 263

def audio_file_format(path, info = nil)
  info ||= audio_file_info_ffprobe(path)
  f = info['format']['format_name']
  if f == 'mp3'
    stream = info['streams'].detect { |s| s['codec_type'] == 'audio' }
    f = stream['codec_name']
  end
  f.downcase
end

#audio_file_info_ffprobe(path) ⇒ Object Also known as: audio_file_info



307
308
309
310
311
312
313
314
315
# File 'lib/audio_monster/monster.rb', line 307

def audio_file_info_ffprobe(path)
  check_local_file(path)
  cmd = bin(:ffprobe) +
    " -v quiet -print_format json -show_format -show_streams" +
    " '#{path}'"
  out, err = run_command(cmd, nice: 'n', echo_return: false)
  json = out.chomp
  JSON.parse(json)
end

#audio_file_info_soxi(path, flag) ⇒ Object



301
302
303
304
305
# File 'lib/audio_monster/monster.rb', line 301

def audio_file_info_soxi(path, flag)
  check_local_file(path)
  out, err = run_command("#{bin(:soxi)} -V0 -#{flag} '#{path}'", nice: 'n', echo_return: false)
  out.chomp
end

#audio_file_sample_rate(path, info = nil) ⇒ Object



286
287
288
289
290
291
# File 'lib/audio_monster/monster.rb', line 286

def audio_file_sample_rate(path, info = nil)
  # audio_file_info_soxi(path, 'r').to_i
  info ||= audio_file_info_ffprobe(path)
  stream = info['streams'].detect { |s| s['codec_type'] == 'audio' }
  stream['sample_rate'].to_i
end

#basic_info_for_file(path) ⇒ Object



207
208
209
210
211
212
213
214
215
# File 'lib/audio_monster/monster.rb', line 207

def basic_info_for_file(path)
  ct = content_type(path)
  mm = MimeMagic.new(ct)
  {
    size: File.size(path),
    content_type: ct,
    format: common_extensions(ct) || mm.extensions.first
  }
end

#common_extensions(content_type) ⇒ Object



217
218
219
# File 'lib/audio_monster/monster.rb', line 217

def common_extensions(content_type)
  COMMON_EXTENSIONS[content_type]
end

#concat_wavs(in_paths, out_path) ⇒ Object



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
# File 'lib/audio_monster/monster.rb', line 667

def concat_wavs(in_paths, out_path)
  first_wav_info = info_for_wav(in_paths.first)
  channels = first_wav_info[:channel_mode] == 'Mono' ? 1 : 2
  sample_rate = first_wav_info[:sample_rate]
  tmp_files = []

  concat_paths = in_paths.inject("") {|cmd, path|
    concat_path = path
    wav_info = info_for_wav(concat_path)
    current_channels = wav_info[:channel_mode] == 'Mono' ? 1 : 2
    current_sample_rate = wav_info[:sample_rate]
    if current_channels != channels || current_sample_rate != sample_rate

      concat_file = create_temp_file(path)
      concat_file.close

      concat_path = concat_file.path
      command = "#{bin(:sox)} -t wav #{path} -t wav -c #{channels} -r #{sample_rate} '#{concat_path}'"
      out, err = run_command(command)
      response = out + err
      response.split("\n").each{ |out| raise("concat_wavs: create temp file error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }
      tmp_files << concat_file
    end
    cmd << "-t wav '#{concat_path}' "
  }
  command = "#{bin(:sox)} #{concat_paths} -t wav '#{out_path}'"
  out, err = run_command(command)

  response = out + err
  response.split("\n").each{ |out| raise("concat_wavs: concat files error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }
ensure
  tmp_files.each do |tf|
    tf.close rescue nil
    tf.unlink rescue nil
  end
  tmp_files = nil
end

#content_type(path) ⇒ Object



247
248
249
250
251
# File 'lib/audio_monster/monster.rb', line 247

def content_type(path)
  ct = mime_magic_content_type(path)
  ct = file_content_type(path) if (ct.nil? || ct.length == 0)
  ct
end

#create_temp_file(base_file_name = nil, bin_mode = true) ⇒ Object



769
770
771
772
773
774
775
776
777
778
# File 'lib/audio_monster/monster.rb', line 769

def create_temp_file(base_file_name=nil, bin_mode=true)
  file_name = File.basename(base_file_name)
  file_name = Digest::SHA256.hexdigest(base_file_name) if file_name.length > MAX_FILENAME_LENGTH
  file_ext = File.extname(base_file_name)[0, MAX_EXTENSION_LENGTH]

  FileUtils.mkdir_p(tmp_dir) unless File.exists?(tmp_dir)
  tmp = Tempfile.new([file_name, file_ext], tmp_dir)
  tmp.binmode if bin_mode
  tmp
end

#create_wav_wrapped_mpeg(mpeg_path, result_path, options = {}) ⇒ Object Also known as: create_wav_wrapped_mp2, create_wav_wrapped_mp3

need start_at, ends_on



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
# File 'lib/audio_monster/monster.rb', line 566

def create_wav_wrapped_mpeg(mpeg_path, result_path, options={})
  options.to_options!

  start_at = get_datetime_for_option(options[:start_at])
  end_at = get_datetime_for_option(options[:end_at])

  wav_wrapped_mpeg = NuWav::WaveFile.from_mpeg(mpeg_path)
  cart = wav_wrapped_mpeg.chunks[:cart]
  cart.title = options[:title] || File.basename(mpeg_path)
  cart.artist = options[:artist]
  cart.cut_id = options[:cut_id]
  cart.producer_app_id = options[:producer_app_id] if options[:producer_app_id]
  cart.start_date = start_at.strftime(PRSS_DATE_FORMAT)
  cart.start_time = start_at.strftime(AES46_2002_TIME_FORMAT)
  cart.end_date = end_at.strftime(PRSS_DATE_FORMAT)
  cart.end_time = end_at.strftime(AES46_2002_TIME_FORMAT)

  # pass in the options used by NuWav -
  # :no_pad_byte - when true, will not add the pad byte to the data chunk
  nu_wav_options = options.slice(:no_pad_byte)
  wav_wrapped_mpeg.to_file(result_path, nu_wav_options)

  check_local_file(result_path)

  return true
end

#cut_wav(wav_path, out_path, length, fade = 5) ⇒ Object



648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'lib/audio_monster/monster.rb', line 648

def cut_wav(wav_path, out_path, length, fade=5)
  logger.info "cut_wav: wav_path:#{wav_path}, length:#{length}, fade:#{fade}"

  wav_info = info_for_wav(wav_path)
  logger.debug "cut_wav: wav_info:#{wav_info.inspect}"

  new_length = [wav_info[:length].to_f, length.to_f].min
  fade_length = [wav_info[:length].to_f, fade.to_f].min

  # find out if the wav file is stereo or mono as this needs to match the starting wav
  channels = wav_info[:channel_mode] == 'Mono' ? 1 : 2
  sample_rate = wav_info[:sample_rate]

  command = "#{bin(:sox)} -t wav '#{wav_path}' -t raw -s -b 16 -c #{channels} - trim 0 #{new_length} | #{bin(:sox)} -t raw -r #{sample_rate} -s -b 16 -c #{channels} - -t wav '#{out_path}' fade h 0 #{new_length} #{fade_length}"
  out, err = run_command(command)
  response = out + err
  response.split("\n").each{ |out| raise("cut_wav: cut file error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }
end

#decode_audio(original_path, wav_path, options = {}) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/audio_monster/monster.rb', line 174

def decode_audio(original_path, wav_path, options={})
  # check to see if there is an original
  logger.info "decode_audio: #{original_path}, #{wav_path}, #{options.inspect}"
  check_local_file(original_path)

  # if the file extension is banged up, try to get from options, or guess at 'mov'
  input_format = ''
  if options[:source_format] || (File.extname(original_path).length != 4)
    input_format = options[:source_format] ? "-f #{options[:source_format]}" : '-f mov'
  end

  channels = options[:channels] ? options[:channels].to_i : 2
  sample_rate = options[:sample_rate] ? options[:sample_rate].to_i : 44100
  logger.debug "decode_audio: start"
  command = "#{bin(:ffmpeg)} -nostats -loglevel warning -vn -i '#{original_path}' -acodec pcm_s16le -ac #{channels} -ar #{sample_rate} -y -f wav '#{wav_path}'"

  out, err = run_command(command)

  # check to see if there is a file created, or don't go on.
  check_local_file(wav_path)
  return [out, err]
end

#encode_mp2_from_wav(original_path, mp2_path, options = {}) ⇒ Object

valid options :sample_rate :bit_rate :per_channel_bit_rate :channel_mode :protect :copyright :original :emphasis



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
# File 'lib/audio_monster/monster.rb', line 328

def encode_mp2_from_wav(original_path, mp2_path, options={})
  check_local_file(original_path)

  options.to_options!
  # parse the wave to see what values to use if not overridden by the options
  wf = WaveFile.parse(original_path)
  fmt = wf.chunks[:fmt]

  wav_sample_size = fmt.sample_bits

  # twolame can only handle up to 16 for floating point (seems to convert to 16 internaly anyway)
  # "Note: the 32-bit samples are currently scaled down to 16-bit samples internally."
  # libtwolame.h  twolame_encode_buffer_float32 http://www.twolame.org/doc/twolame_8h.html#8e77eb0f22479f8ec1bd4f1b042f9cd9
  if (fmt.compression_code.to_i == PCM_FLOATING_COMPRESSION && fmt.sample_bits > 32)
    wav_sample_size = 16
  end

  # input options
  prefix_command = ''
  raw_input      = ''
  sample_rate    = "--samplerate #{fmt.sample_rate}"
  sample_bits    = "--samplesize #{wav_sample_size}"
  channels       = "--channels #{fmt.number_of_channels}"
  input_path     = "'#{original_path}'"

  # output options
  mp2_sample_rate = if MP2_SAMPLE_RATES.include?(options[:sample_rate].to_s)
    options[:sample_rate]
  elsif MP2_SAMPLE_RATES.include?(fmt.sample_rate.to_s)
    fmt.sample_rate.to_s
  else
    '44100'
  end

  if mp2_sample_rate.to_i != fmt.sample_rate.to_i
    prefix_command = "#{bin(:sox)} '#{original_path}' -t raw -r #{mp2_sample_rate} - | "
    input_path = '-'
    raw_input = '--raw-input'
  end

  mode = if TWOLAME_MODES.include?(options[:channel_mode])
    options[:channel_mode] #use the channel mode from the options if specified
  elsif fmt.number_of_channels <= 1
    'm' # default to monoaural for 1 channel input
  else
    's' # default to joint stereo for 2 channel input
  end
  channel_mode = "--mode #{mode}"

  kbps = if options[:per_channel_bit_rate]
    options[:per_channel_bit_rate].to_i * ((mode == 'm') ? 1 : 2)
  elsif options[:bit_rate]
    options[:bit_rate].to_i
  else
    0
  end

  kbps = if MP2_BITRATES.include?(kbps)
    kbps
  elsif mode == 'm' || (mode =='a' && fmt.number_of_channels <= 1)
    128 # default for monoaural is 128 kbps
  else
    256 # default for stereo/dual channel is 256 kbps
  end
  bit_rate = "--bitrate #{kbps}"

  downmix = (mode == 'm' && fmt.number_of_channels > 1) ? '--downmix' : ''

  # default these headers when options not present
  protect = (options.key?(:protect) && !options[:protect] ) ? '' : '--protect'
  copyright = (options.key?(:copyright) && !options[:copyright] ) ? '' : '--copyright'
  original = (options.key?(:original) && !options[:original] ) ? '--non-original' : '--original'
  emphasis = (options.key?(:emphasis)) ? "--deemphasis #{options[:emphasis]}" : '--deemphasis n'

  ##
  # execute the command
  ##
  input_options = "#{raw_input} #{sample_rate} #{sample_bits} #{channels}"
  output_options = "#{channel_mode} #{bit_rate} #{downmix} #{protect} #{copyright} #{original} #{emphasis}"

  command = "#{prefix_command} #{bin(:twolame)} -t 0 #{input_options} #{output_options} #{input_path} '#{mp2_path}'"
  out, err = run_command(command)
  unless out.split("\n").last =~ TWOLAME_SUCCESS_RE
    raise "encode_mp2_from_wav - twolame response on transcoding was not recognized as a success, #{out}, #{err}"
  end

  # make sure there is a file at the end of this
  check_local_file(mp2_path)

  true
end

#encode_mp3_from_wav(original_path, mp3_path, options = {}) ⇒ Object

valid options :sample_rate :bit_rate :channel_mode



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
# File 'lib/audio_monster/monster.rb', line 424

def encode_mp3_from_wav(original_path, mp3_path, options={})
  logger.info "encode_mp3_from_wav: #{original_path}, #{mp3_path}, #{options.inspect}"

  check_local_file(original_path)

  options.to_options!
  # parse the wave to see what values to use if not overridden by the options
  wf = WaveFile.parse(original_path)
  fmt = wf.chunks[:fmt]

  input_path = '-'

  mp3_sample_rate = if MP3_SAMPLE_RATES.include?(options[:sample_rate].to_s)
    options[:sample_rate].to_s
  elsif MP3_SAMPLE_RATES.include?(fmt.sample_rate.to_s)
    logger.debug "sample_rate:  fmt.sample_rate = #{fmt.sample_rate}"
    fmt.sample_rate.to_s
  else
    '44100'
  end
  logger.debug "mp3_sample_rate: #{options[:sample_rate]}, #{fmt.sample_rate}"

  mode = if LAME_MODES.include?(options[:channel_mode])
    options[:channel_mode] #use the channel mode from the options if specified
  elsif fmt.number_of_channels <= 1
    'm' # default to monoaural for 1 channel input
  else
    'j' # default to joint stereo for 2 channel input
  end
  channel_mode = "-m #{mode}"

  # if mono selected, but input is in stereo, need to specify downmix to 1 channel for sox
  downmix = (mode == 'm' && fmt.number_of_channels > 1) ? '-c 1' : ''

  # if sample rate different, change that as well in sox before piping to lame
  resample = (mp3_sample_rate.to_i != fmt.sample_rate.to_i) ? "-r #{mp3_sample_rate} " : ''
  logger.debug "resample: #{resample} from comparing #{mp3_sample_rate} #{fmt.sample_rate}"

  # output to wav (-t wav) has a warning
  # '/usr/local/bin/sox wav: Length in output .wav header will be wrong since can't seek to fix it'
  # that messsage can safely be ignored, wa output is easier/safer for lame to recognize, so worth ignoring this message
  prefix_command = "#{bin(:sox)} '#{original_path}' -t wav #{resample} #{downmix} - | "

  kbps = if options[:per_channel_bit_rate]
    options[:per_channel_bit_rate].to_i * ((mode == 'm') ? 1 : 2)
  elsif options[:bit_rate]
    options[:bit_rate].to_i
  else
    0
  end

  kbps = if MP3_BITRATES.include?(kbps)
    kbps
  elsif mode == 'm'
    128 # default for monoaural is 128 kbps
  else
    256 # default for stereo/dual channel is 256 kbps
  end
  bit_rate = "--cbr -b #{kbps}"

  ##
  # execute the command
  ##
  output_options = "#{channel_mode} #{bit_rate}"

  command = "#{prefix_command} #{bin(:lame)} -S #{output_options} #{input_path} '#{mp3_path}'"

  out, err = run_command(command)

  unless out.split("\n")[-1] =~ LAME_SUCCESS_RE
    raise "encode_mp3_from_wav - lame completion unsuccessful: #{out}"
  end

  err.split("\n").each do |l|
    if l =~ LAME_ERROR_RE
      raise "encode_mp3_from_wav - lame response had fatal error: #{l}"
    end
  end
  logger.debug "encode_mp3_from_wav: end!"

  check_local_file(mp3_path)

  true
end

#encode_ogg_from_wav(original_path, result_path, options = {}) ⇒ Object



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
# File 'lib/audio_monster/monster.rb', line 509

def encode_ogg_from_wav(original_path, result_path, options={})
  logger.info("encode_ogg_from_wav: original_path: #{original_path}, result_path: #{result_path}, options: #{options.inspect}")

  check_local_file(original_path)

  options.to_options!
  # parse the wave to see what values to use if not overridden by the options
  wf = WaveFile.parse(original_path)
  fmt = wf.chunks[:fmt]

  sample_rate = if MP3_SAMPLE_RATES.include?(options[:sample_rate].to_s)
    options[:sample_rate].to_s
  elsif MP3_SAMPLE_RATES.include?(fmt.sample_rate.to_s)
    logger.debug "sample_rate:  fmt.sample_rate = #{fmt.sample_rate}"
    fmt.sample_rate.to_s
  else
    '44100'
  end
  logger.debug "sample_rate: #{options[:sample_rate]}, #{fmt.sample_rate}"

  mode = if LAME_MODES.include?(options[:channel_mode])
    options[:channel_mode] #use the channel mode from the options if specified
  elsif fmt.number_of_channels <= 1
    'm' # default to monoaural for 1 channel input
  else
    'j' # default to joint stereo for 2 channel input
  end

  # can directly set # of channels, 16 or less
  # otherwise fallback on the mode, like mpegs
  # or 2 if all else fails
  channels = if (options[:channels].to_i > 0 )
    [options[:channels].to_i, 16].min
  else
    (mode && (mode == 'm')) ? 1 : 2
  end

  kbps = if options[:per_channel_bit_rate]
    options[:per_channel_bit_rate].to_i * channels
  elsif options[:bit_rate]
    options[:bit_rate].to_i
  else
    0
  end

  bit_rate = (MP3_BITRATES.include?(kbps) ? kbps : 96).to_s + "k"

  command = "#{bin(:ffmpeg)} -nostats -loglevel warning -vn -i '#{original_path}' -acodec libvorbis -ac #{channels} -ar #{sample_rate} -ab #{bit_rate} -y -f ogg '#{result_path}'"

  out, err = run_command(command)

  check_local_file(result_path)

  return true
end

#file_content_type(path) ⇒ Object



257
258
259
260
261
# File 'lib/audio_monster/monster.rb', line 257

def file_content_type(path)
  check_local_file(path)
  out, err = run_command("#{bin(:file)} --brief --mime-type '#{path}'", nice: 'n', echo_return: false)
  out.chomp
end

#get_datetime_for_option(d) ⇒ Object



593
594
595
596
# File 'lib/audio_monster/monster.rb', line 593

def get_datetime_for_option(d)
  return DateTime.now unless d
  d.respond_to?(:strftime) ? d : DateTime.parse(d.to_s)
end

#info_for(path) ⇒ Object



197
198
199
200
201
202
203
204
205
# File 'lib/audio_monster/monster.rb', line 197

def info_for(path)
  ct = content_type(path)
  mm = MimeMagic.new(ct)
  if respond_to?("info_for_#{mm.mediatype}")
    send("info_for_#{mm.mediatype}", path)
  else
    basic_info_for_file(path)
  end
end

#info_for_audio(path) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/audio_monster/monster.rb', line 221

def info_for_audio(path)
  info = audio_file_info_ffprobe(path)
  audio_info = {
    format:       audio_file_format(path, info),
    channel_mode: audio_file_channels(path, info) <= 1 ? 'Mono' : 'Stereo',
    channels:     audio_file_channels(path, info),
    bit_rate:     audio_file_bit_rate(path, info),
    length:       audio_file_duration(path, info),
    sample_rate:  audio_file_sample_rate(path, info)
  }
  basic_info_for_file(path).merge(audio_info)
end

#info_for_mpeg(path, info = nil) ⇒ Object Also known as: info_for_mp2, info_for_mp3



234
235
236
237
238
239
240
241
242
# File 'lib/audio_monster/monster.rb', line 234

def info_for_mpeg(path, info = nil)
  info = info_for_audio(path)
  mp3_info ||= Mp3Info.new(path)
  info[:channel_mode] = mp3_info.channel_mode
  info[:version]      = mp3_info.mpeg_version
  info[:layer]        = mp3_info.layer
  info[:padding]      = mp3_info.header[:padding]
  info
end

#loudness_info(path) ⇒ Object

True peak:

Peak:       -2.1 dBFS


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/audio_monster/monster.rb', line 51

def loudness_info(path)
  command = "#{bin(:ffmpeg)} -nostats -vn -i '#{path}' -y -filter_complex ebur128=peak=true -f null - 2>&1 | tail -12"
  out, err = run_command(command, echo_return: false)

  lines = out.split("\n").map(&:strip).compact.map { |o| o.split(":").map(&:strip) }
  group = nil
  info = {}
  lines.each do |i|
    if i.length == 1 && i[0].length > 0
      group = i[0].downcase.gsub(' ', '_').to_sym
      info[group] ||= {}
    elsif i.length == 2
      key = i[0].downcase.gsub(' ', '_').to_sym
      info[group][key] = i[1].to_f
    end
  end
  info
end

#mime_magic_content_type(path) ⇒ Object



253
254
255
# File 'lib/audio_monster/monster.rb', line 253

def mime_magic_content_type(path)
  (MimeMagic.by_path(path) || MimeMagic.by_magic(path)).to_s
end

#normalize_wav(wav_path, out_path, level = -9)) ⇒ Object



742
743
744
745
746
747
748
# File 'lib/audio_monster/monster.rb', line 742

def normalize_wav(wav_path, out_path, level=-9)
  logger.info "normalize_wav: wav_path:#{wav_path}, level:#{level}"
  command = "#{bin(:sox)} -t wav '#{wav_path}' -t wav '#{out_path}' gain -n #{level.to_i}"
  out, err = run_command(command)
  response = out + err
  response.split("\n").each{ |out| raise("normalize_wav: normalize audio file error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }
end

#silence_detect(path, threshold = 0.001, min_time = 2.0) ⇒ Object



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
# File 'lib/audio_monster/monster.rb', line 122

def silence_detect(path, threshold=0.001, min_time=2.0)
  ranges = []
  # puts "\n#{Time.now} tone_detect(path, tone): #{path}, #{tone}\n"

  threshold = threshold.to_f
  min_time  = min_time.to_f
  normalized_wav_dat = nil

  begin

    normalized_wav_dat = create_temp_file(path + '.dat')
    normalized_wav_dat.close

    command = "#{bin(:sox)} '#{path}' '#{normalized_wav_dat.path}' channels 1 rate 1000 norm"
    out, err = run_command(command)

    current_range = nil

    File.foreach(normalized_wav_dat.path) do |row|
      next if row[0] == ';'

      data = row.split.map(&:to_f)
      time = data[0]
      energy = data[1].abs()

      if energy < threshold
        if !current_range
          current_range = {start: time, finish: time, min: energy, max: energy}
        else
          current_range[:finish] = time
          current_range[:min] = [current_range[:min], energy].min
          current_range[:max] = [current_range[:max], energy].max
        end
      else
        next unless current_range
        ranges << current_range if ((current_range[:finish] - current_range[:start]) > min_time.to_f)
        current_range = nil
      end
    end

    if current_range && ((current_range[:finish] - current_range[:start]) > min_time.to_f)
      ranges << current_range
    end

  ensure
    normalized_wav_dat.close rescue nil
    normalized_wav_dat.unlink rescue nil
  end

  ranges
end

#slice_wav(wav_path, out_path, start, length) ⇒ Object



633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/audio_monster/monster.rb', line 633

def slice_wav(wav_path, out_path, start, length)
  check_local_file(wav_path)

  wav_info = info_for_wav(wav_path)
  logger.debug "slice_wav: wav_info:#{wav_info.inspect}"

  command = "#{bin(:sox)} -t wav '#{wav_path}' -t wav '#{out_path}' trim #{start} #{length}"
  out, err = run_command(command)
  response = out + err
  response.split("\n").each{ |out| raise("slice_wav: cut file error: '#{response}' on:\n #{command}") if out =~ SOX_ERROR_RE }

  check_local_file(out_path)
  out_path
end

#tone_detect(path, tone, threshold = 0.05, min_time = 0.5) ⇒ Object



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
# File 'lib/audio_monster/monster.rb', line 70

def tone_detect(path, tone, threshold=0.05, min_time=0.5)
  ranges = []

  tone      = tone.to_i
  threshold = threshold.to_f
  min_time  = min_time.to_f
  normalized_wav_dat = nil

  begin

    normalized_wav_dat = create_temp_file(path + '.dat')
    normalized_wav_dat.close

    command = "#{bin(:sox)} '#{path}' '#{normalized_wav_dat.path}' channels 1 rate 200 bandpass #{tone} 3 gain 6"
    out, err = run_command(command)
    current_range = nil

    File.foreach(normalized_wav_dat.path) do |row|
      next if row[0] == ';'

      data = row.split.map(&:to_f)
      time = data[0]
      energy = data[1].abs()

      if energy >= threshold
        if !current_range
          current_range = {start: time, finish: time, min: energy, max: energy}
        else
          current_range[:finish] = time
          current_range[:min] = [current_range[:min], energy].min
          current_range[:max] = [current_range[:max], energy].max
        end
      else
        if current_range && ((current_range[:finish] + min_time.to_f) < time)
          ranges << current_range
          current_range = nil
        end
      end
    end

    if current_range
      ranges << current_range
    end

  ensure
    normalized_wav_dat.close rescue nil
    normalized_wav_dat.unlink rescue nil
  end

  ranges
end

#validate_mpeg(audio_file_path, options) ⇒ Object Also known as: validate_mp2, validate_mp3



750
751
752
753
754
755
756
757
758
759
760
761
# File 'lib/audio_monster/monster.rb', line 750

def validate_mpeg(audio_file_path, options)
  @errors = {}

  options = HashWithIndifferentAccess.new(options)

  info = mp3info_validation(audio_file_path, options)

  # if the format seems legit, check the audio itself
  mp3val_validation(audio_file_path, options)

  return @errors, info
end