extensions.rb 58.6 KB
Newer Older
1
# extensions.rb -- various generally useful Snd extensions (see extensions.scm)
2 3

# Translator/Author: Michael Scholz <mi-scholz@users.sourceforge.net>
4 5
# Created: 2004/01/03 17:30:23
# Changed: 2018/04/15 22:50:30
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

# module Compatibility
#  scan_sound_chans(beg, end, snd, edpos) do |y| ... end
#  map_sound_chans(beg, end, edname, snd, edpos) do |y| ... end
#  scan_all_chans(beg, end, edpos) do |y| ... end
#  map_all_chans(beg, end, edname, edpos) do |y| ... end
#  scan_chans(beg, end, edpos) do |y| ... end
#  map_chans(beg, end, edname, edpos) do |y| ... end
#  scan_across_all_chans(beg, end, snd, edpos) do |data, chns| ... end
#  map_across_all_chans(beg, end, edname, snd, edpos) do |data, chns| ... end
#  selection_to_temp(type = Mus_next, format = Mus_out_format)
#  syncd_sounds(val)
#  sound_to_temp(type = Mus_next, format = Mus_out_format, edpos = false)
#  selection_to_temps(type = Mus_next, format = Mus_out_format)
#  sound_to_temps(type = Mus_next, format = Mus_out_format, edpos = false)
#  temp_to_sound(data, filename, origin = false)
#  temps_to_sound(data, filenames, origin = false)
#  temp_to_selection(data, filename, origin = false)
#  temps_to_selection(data, filenames, origin = false)
#  
#  forward_sample(count, snd, chn)
#  backward_sample(count, snd, chn)
#  
#  back_or_forth_graph(count)
#  forward_graph(count)
#  backward_graph(count)
#  back_or_forth_mix(count)
#  forward_mix(count = 1, snd = false, chn = false)
#  backward_mix(count = 1, snd = false, chn = false)
#  back_or_forth_mark(count)
#  forward_mark(count = 1, snd = false, chn = false)
#  backward_mark(count = 1, snd = false, chn = false)
#  vct_convolve!(r1, r2)
#  old_map_channel(beg, dur, snd, chn, edpos, edname, &func)
#  mus_bank(gens, amps, in1, in2)
41
#  old_oscil_bank(amps, gens, in1, in2)
42 43 44 45 46
#  old_formant_bank(amps, gens, in1)
#  vct2samples(samp, samps, data, snd, chn)
#  samples2vct(samp, samps, snd, chn, nv, epos)
#  scale_sound_by(scl, beg, dur, snd, chn, edpos)
#  scale_sound_to(norm, beg, dur, snd, chn)
47 48
#  emacs_style_save_as
#  set_emacs_style_save_as(val)
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
#  make_iir_low_pass_1(fc)
#  make_iir_high_pass_1(fc)
#  sine_bank(amps, phases, size)
#
# module Extensions
#  remove_channel_property(key, snd, chn)
#  remove_sound_property(key, snd)
#
#  channel_sync(snd, chn)
#  set_channel_sync(val, snd, chn)
#
#  set_sound_property_save_state_ignore(key, snd)
#  set_channel_property_save_state_ignore(key, snd, chn)
#  show_sound_properties(snd)
#  show_channel_properties(snd, chn)
#
#  properties2string(snd)
#  save_properties(fname)
#  
#  remember_all_sound_properties(database, tmp_snd_p)
#  remember_properties
#  class Remember_sound_properties
#    initialize(database)
#    inspect
#    with_db do |db| ... end
#    load(snd)
#    save(snd)
#    each do |k, v| ... end
#    delete_if do |k, v| ... end
#    contents
#    help
#  
#  add_comment(samp, comm, snd, chn)
#  remove_comment(comm, snd, chn)
#  show_comments(snd, chn)
#  
#  marks?(more_than_one)
#  all_chans
#  all_chans_zipped
#  normalized_mix(fname, beg, in_chan, snd, chn)
#  enveloped_mix(fname, beg, env, del_tmp)
#  
#  map_sound_files(*args) do |f| ... end
#  for_each_sound_file(*args) do |f| ... end    alias each_sound_file
#  match_sound_files(*args) do |f| ... end
#  
#  selection_members
#  clear_selection
#  make_selection(beg, len, snd, chn)
#  delete_selection_and_smooth()
#
#  mix_channel(fdata, beg, dur, snd, chn, edpos)
#  insert_channel(fdata, beg, dur, snd, chn, edpos)
#  redo_channel(edits, snd, chn)
#  undo_channel(edits, snd, chn)
#  
105
#  any_env_channel(en, b, d, s, c, ep, ori) do |r0, r1, b, d, s, c, e| ... end
106 107 108 109 110 111 112 113 114
#  sine_ramp(rmp0, rmp1, beg, dur, snd, chn, edpos)
#  sine_env_channel(env, beg, dur, snd, chn, edpos)
#  blackman4_ramp(rmp0, rmp1, beg, dur, snd, chn, edpos)
#  blackman4_env_channel(env, beg, dur, snd, chn, edpos)
#  ramp_squared(rmp0, rmp1, symmetric, beg, dur, snd, chn, edpos)
#  env_squared_channel(env, symmetric, beg, dur, snd, chn, edpos)
#  ramp_expt(rmp0, rmp1, exponent, symmetric, beg, dur, snd, chn, edpos)
#  env_expt_channel(env, exponent, symmetric, beg, dur, snd, chn, edpos)
#  offset_channel(amount, beg, dur, snd, chn, edpos)
115 116
#  offset_sound(amount, beg, dur, snd)
#  pad_sound(beg, dur, snd)
117
#  dither_channel(amnt, beg, dur, snd, chn, edpos)
118
#  dither_sound(amnt, beg, dur, snd)
119
#  contrast_channel(index, beg, dur, snd, chn, edpos)
120
#  contrast_sound(index, beg, dur, snd)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
#  channels_eql?(snd1, chn1, snd2, chn2, allowable_difference)
#  channels_equal?(snd1, chn1, snd2, chn2, allowable_difference)
#  mono2stereo(new_name, snd1, chn1, snd2, chn2)
#  mono_files2stereo(new_name, chan1_name, chan2_name)
#  stereo2mono(orig_snd, chan1_name, chan2_name)
#
#  with_reopen_menu
#  with_buffers_menu

# Comments are mostly taken from extensions.scm.

require "hooks"
include Math

module Compatibility
  # 
  # Snd-4 compatibility stuff
  # 
  add_help(:scan_sound_chans,
140 141
           "scan_sound_chans(beg=0, end=flase, snd=false, edpos=false, &proc)  \
Applies scan_chan with PROC to each channel in a sound.")
142 143 144 145
  def scan_sound_chans(beg = 0, fin = false, snd = false, edpos = false, &body)
    # Proc#arity returns -1 instead of 1 on older versions
    if body and body.arity.abs == 1
      val = nil
146 147 148 149
      c = (0...chans(snd)).detect do |chn|
        val = scan_chan(body, beg, fin, snd, chn, edpos)
      end
      if c
150 151 152 153 154
        val += [Snd.snd(snd), c]
      else
        nil
      end
    else
155 156
      Snd.raise(:bad_arity,
                "scan_sound_chans(beg, end, snd, edpos) do |y| ... end")
157 158 159 160
    end
  end

  add_help(:map_sound_chans,
161 162 163 164
           "map_sound_chans(beg=0, end=flase, snd=false, edpos=false, &proc)  \
Applies map_chan with PROC to each channel in a sound.")
  def map_sound_chans(beg = 0, fin = false, edname = false,
                      snd = false, edpos = false, &body)
165
    if body and body.arity.abs == 1
166 167 168
      channels(snd).times do |chn|
        map_chan(body, beg, fin, edname, snd, chn, edpos)
      end
169
    else
170 171
      Snd.raise(:bad_arity,
                "map_sound_chans(beg, end, ename, snd, edpos) do |y| ... end")
172 173 174 175
    end
  end

  add_help(:scan_all_chans,
176 177
           "scan_all_chans(beg=0, end=flase, edpos=false, &proc)  \
Applies scan_chan with PROC to all channels (all sounds).")
178 179 180 181 182 183 184 185 186 187 188 189 190
  def scan_all_chans(beg = 0, fin = false, edpos = false, &body)
    if body and body.arity.abs == 1
      catch(:done) do
        Snd.sounds.each do |snd|
          channels(snd).times do |chn|
            if res = scan_chan(body, beg, fin, snd, chn, edpos)
              throw(:done, res += [snd, chn])
            end
          end
        end
        false
      end
    else
191 192
      Snd.raise(:bad_arity,
                "scan_all_chans(beg, end, edpos) do |y| ... end")
193 194 195 196
    end
  end
  
  add_help(:map_all_chans,
197 198
           "map_all_chans(beg=0, end=flase, edpos=false, &proc)  \
Applies map_chan with proc to all channels (all sounds).")
199 200 201 202 203 204 205 206
  def map_all_chans(beg = 0, fin = false, edname = false, edpos = false, &body)
    if body and body.arity.abs == 1
      Snd.sounds.each do |snd|
        channels(snd).times do |chn|
          map_chan(body, beg, fin, edname, snd, chn, edpos)
        end
      end
    else
207 208
      Snd.raise(:bad_arity,
                "map_all_chans(beg, end, ename, edpos) do |y| ... end")
209 210 211 212
    end
  end

  add_help(:scan_chan,
213 214
           "scan_chans(beg=0, end=flase, edpos=false, &proc)  \
Applies scan_chan with PROC to all channels sharing current sound's sync.")
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
  def scan_chans(beg = 0, fin = false, edpos = false, &body)
    if body and body.arity.abs == 1
      current_sync = sync(selected_sound)
      catch(:done) do
        Snd.sounds.each do |snd|
          if sync(snd) == current_sync
            channels(snd).times do |chn|
              if res = scan_chan(body, beg, fin, snd, chn, edpos)
                throw(:done, res += [snd, chn])
              end
            end
          end
        end
        false
      end
    else
231 232
      Snd.raise(:bad_arity,
                "scan_chans(beg, end, edpos) do |y| ... end")
233 234 235 236
    end
  end

  add_help(:map_chan,
237 238
           "map_chans(beg=0, end=false, edpos=false, &proc)  \
Applies map_chan with PROC to all channels sharing current sound's sync.")
239 240 241 242 243 244 245 246 247 248 249
  def map_chans(beg = 0, fin = false, edname = false, edpos = false, &body)
    if body and body.arity.abs == 1
      current_sync = sync(selected_sound)
      Snd.sounds.each do |snd|
        if sync(snd) == current_sync
          channels(snd).times do |chn|
            map_chan(body, beg, fin, edname, snd, chn, edpos)
          end
        end
      end
    else
250 251
      Snd.raise(:bad_arity,
                "map_chans(beg, end, ename, edpos) do |y| ... end")
252 253 254 255
    end
  end

  add_help(:scan_across_all_chans,
256 257 258
           "scan_across_all_chans(beg=0, end=flase, \
snd=false, edpos=false, &proc)  \
Applies map_chan with PROC to all channels in parallel.")
259
  # body.call(data, chan_num)
260 261
  def scan_across_all_chans(beg = 0, fin = false,
                            snd = false, edpos = false, &body)
262 263 264 265 266
    chans = all_chans
    chan_num = chans.first.length
    maxlen = 0
    Snd.sounds.each do |s|
      channels(s).times do |chn|
267
        maxlen = [maxlen, framples(s, chn)].max
268 269 270 271 272 273 274 275 276
      end
    end
    len = integer?(fin) ? ([fin, maxlen].min - beg) : (maxlen - beg)
    data = make_array(chan_num, 0.0)
    fds = make_array(chan_num) do |chn|
      make_sampler(beg, chans[0].shift, chans[1].shift, 1, edpos)
    end
    catch(:done) do
      len.times do |i|
277 278 279
        data.map_with_index! do |d, chn|
          next_sample(fds[chn])
        end
280 281 282 283 284 285 286 287
        if newdata = body.call(data, chan_num)
          throw(:done, [newdata, i + beg])
        end
      end
    end
  end
  
  add_help(:map_across_all_chans,
288 289 290 291 292
           "map_across_all_chans(beg=0, end=flase, edname=false, \
snd=false, edpos=false, &proc)  \
Applies map_chan with PROC to all channels in parallel.")
  def map_across_all_chans(beg = 0, fin = false, edname = false,
                           snd = false, edpos = false, &body)
293 294 295 296 297
    snds, chans = all_chans
    chan_num = snds.length
    maxlen = 0
    Snd.sounds.each do |sd|
      channels(sd).times do |chn|
298
        maxlen = [maxlen, framples(sd, chn)].max
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
      end
    end
    len = integer?(fin) ? ([fin, maxlen].min - beg) : (maxlen - beg)
    data = make_array(chan_num)
    fds = make_array(chan_num) do |chn|
      make_sampler(beg, snds[chn], chans[chn], 1, edpos)
    end
    filenames = make_array(chan_num) do |chn|
      snd_tempnam
    end
    outgs = make_array(chan_num) do |chn|
      make_sample2file(filenames[chn], 1, Mus_out_format, Mus_next)
    end
    outsamp = 0
    len.times do |i|
314 315 316
      data.map_with_index! do |d, chn|
        next_sample(fds[chn])
      end
317
      if (newdata = body.call(data, chan_num))
318 319 320
        newdata.each_with_index do |dat, chn|
          out_any(outsamp, dat, 0, outgs[chn])
        end
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        outsamp += 1
      end
    end
    filenames.each_with_index do |file, chn|
      mus_close(outgs[chn])
      free_sampler(fds[chn])
      if outsamp > 0
        delete_samples(beg, len, snds[chn], chans[chn]) if outsamp != len
        set_samples(beg, outsamp, file, snds[chn], chans[chn], true, edname)
        delete_file(file)
      end
    end
  end

  # 
  # Snd-4 external program support stuff
  # 
  add_help(:selection_to_temp,
339 340
           "selection_to_temp(type=Mus_next, format=Mus_out_format)  \
Writes selection data as (multichannel) file (for external program).")
341 342
  def selection_to_temp(type = Mus_next, format = Mus_out_format)
    data = [snd_tempnam]
343
    save_selection(data.first, 44100, format, type)
344 345 346 347 348 349 350 351 352 353 354 355 356 357
    data
  end

  def syncd_sounds(val)
    ctr = 0
    Snd.sounds.each do |snd|
      if sync(snd) == val
        ctr += 1
      end
    end
    ctr
  end

  add_help(:sound_to_temp,
358 359
           "sound_to_temp(type=Mus_next, format=Mus_out_format, edpos=false)  \
Writes sound data as (multichannel) file (for external program).")
360 361 362 363 364
  def sound_to_temp(type = Mus_next, format = Mus_out_format, edpos = false)
    cursnd = selected_sound
    cursync = sync(cursnd)
    if cursync.zero? or syncd_sounds(cursync) == 1
      data = [snd_tempnam]
365 366 367
      save_sound_as(data.first, selected_sound,
                    :header_type, type,
                    :sample_type, format,
368
                    :edit_position, edpos)
369 370
      data
    else
371 372 373
      Snd.raise(:snd_error,
                "re-implemented sound-to-temp doesn't \
handle sync bit correctly yet.")
374 375 376 377
    end
  end

  add_help(:selection_to_temps,
378 379
           "selection_to_temps(type=Mus_next, format=Mus_out_format)  \
Writes selection data as mono files (for external program).")
380 381 382
  def selection_to_temps(type = Mus_next, format = Mus_out_format)
    data = make_array(selection_chans) do |chn|
      outname = snd_tempnam
383
      save_selection(outname, 44100, format, type, :channel, chn)
384 385 386 387 388 389
      outname
    end
    data
  end

  add_help(:sound_to_temps,
390 391
           "sound_to_temps(type=Mus_next, format=Mus_out_format, edpos=false)  \
Writes sound data as mono files (for external program).")
392 393 394 395 396 397
  def sound_to_temps(type = Mus_next, format = Mus_out_format, edpos = false)
    cursnd = selected_sound
    cursync = sync(cursnd)
    if cursync.zero? or syncd_sounds(cursync) == 1
      make_array(channels(cursnd)) do |chn|
        outname = snd_tempnam
398 399 400 401 402
        save_sound_as(outname, selected_sound,
                      :header_type, type,
                      :sample_type, format,
                      :channel, chn,
                      :edit_position, edpos)
403 404 405
        outname
      end
    else
406 407 408
      Snd.raise(:snd_error,
                "re-implemented sound-to-temps doesn't \
handle sync bit correctly yet.")
409 410 411 412 413 414 415 416
    end
  end

  # filenames: String or Array of Strings
  def delete_temp_data_files(data, filenames)
    case filenames
    when String
      (data or []).each do |temp_file|
417
        if File.exist?(temp_file) and temp_file != filenames
418 419 420 421 422
          File.unlink(temp_file)
        end
      end
    when Array
      (data or []).each_with_index do |temp_file, i|
423
        if File.exist?(temp_file) and temp_file != filenames[i]
424 425 426 427 428 429 430
          File.unlink(temp_file)
        end
      end
    end
  end
  
  add_help(:temp_to_sound,
431 432
           "temp_to_sound(data, filename, origin=false)  \
Reads (multichannel) file as new sound data (from external program).")
433 434 435 436
  def temp_to_sound(data, filename, origin = false)
    cursnd = selected_sound
    delete_temp_data_files(data, filename)
    channels(cursnd).times do |chn|
437 438
      set_samples(0, mus_sound_framples(filename), filename,
                  cursnd, chn, true, origin, chn)
439 440 441 442
    end
  end

  add_help(:temps_to_sound,
443 444
           "temps_to_sound(data, filenames, origin=false)  \
Reads mono files as new sound data (from external program).")
445 446 447 448
  def temps_to_sound(data, filenames, origin = false)
    cursnd = selected_sound
    delete_temp_data_files(data, filenames)
    channels(cursnd).times do |chn|
449
      len = mus_sound_framples(filenames[chn])
450 451 452 453 454
      set_samples(0, len, filenames[chn], cursnd, chn, true, origin, chn)
    end
  end

  add_help(:temp_to_selection,
455 456
           "temp_to_selection(data, filename, origin=false)  \
Sets selection from (multichannel) file (from external program).")
457 458 459
  def temp_to_selection(data, filename, origin = false)
    delete_temp_data_files(data, filename)
    chan = 0
460
    len = mus_sound_framples(filename)
461 462 463
    Snd.sounds.each do |snd|
      channels(snd).times do |chn|
        if selection_member?(snd, chn)
464 465
          set_samples(selection_position(snd, chn), len, filename,
                      snd, chn, true, origin, chan)
466 467 468 469 470 471 472
          chan += 1
        end
      end
    end
  end

  add_help(:temps_to_selection,
473 474
           "temps_to_selection(data, filenames, origin=false)  \
Sets selection from mono files (from external program).")
475 476 477 478 479 480
  def temps_to_selection(data, filenames, origin = false)
    delete_temp_data_files(data, filenames)
    chan = 0
    Snd.sounds.each do |snd|
      channels(snd).times do |chn|
        if selection_member?(snd, chn)
481 482 483
          len = mus_sound_framples(filenames[chan])
          set_samples(selection_position(snd, chn), len, filenames[chan],
                      snd, chn, true, origin)
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
          chan += 1
        end
      end
    end
  end
  # 
  # Snd-5 compatibility stuff
  # 
  def forward_sample(count = 1, snd = false, chn = false)
    set_cursor(cursor(snd, chn) + count, snd, chn)
  end
  
  def backward_sample(count = 1, snd = false, chn = false)
    set_cursor(cursor(snd, chn) - count, snd, chn)
  end

  # 
  # Snd-7 compatibility stuff
  # 
  def back_or_forth_graph(count)
    if sounds
      cursnd = selected_sound or Snd.sounds.first
      curchn = selected_channel or 0
      curpos = 0
      pos = 0
      sndlst = []
      chnlst = []
      Snd.sounds.each do |snd|
        channels(snd).times do |chn|
          if cursnd.eql?(snd) and curchn == chn
            curpos = pos
          end
          pos += 1
          sndlst.push(snd)
          chnlst.push(chn)
        end
      end
      newpos = (curpos + count) % sndlst.length
      set_selected_sound(sndlst[newpos])
      set_selected_channel(chnlst[newpos])
      [selected_sound, selected_channel]
    end
  end
  
  def forward_graph(count = 1)
    back_or_forth_graph(count)
  end
  
  def backward_graph(count = 1)
    back_or_forth_graph(-count)
  end

  def back_or_forth_mix(count, snd, chn)
    if count.nonzero? and (mx = mixes(snd, chn))
      if mx.length == 1
        set_cursor(mix_position(mx.first), snd, chn)
        mx.first
      else
542 543 544
        sorted_mx = mx.sort do |a, b|
          mix_position(a) <=> mix_position(b)
        end
545 546 547 548
        pos = cursor(snd, chn)
        curpos = count > 0 ? -1 : 0
        if pos >= mix_position(sorted_mx.first)
          sorted_mx.each do |m|
549 550 551
            if (count > 0 and 
               pos < mix_position(m)) or 
               (count < 0 and pos <= mix_position(m))
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
              break
            else
              curpos += 1
            end
          end
        end
        curmx = sorted_mx[(curpos + count) % mx.length]
        set_cursor(mix_position(curmx), snd, chn)
        curmx
      end
    else
      false
    end
  end
  
  def forward_mix(count = 1, snd = false, chn = false)
    back_or_forth_mix(count, Snd.snd(snd), Snd.chn(chn))
  end

  def backward_mix(count = 1, snd = false, chn = false)
    back_or_forth_mix(-count, Snd.snd(snd), Snd.chn(chn))
  end

  def back_or_forth_mark(count, snd, chn)
    mk = Snd.marks(snd, chn)
    if count.nonzero? and (not mk.empty?)
      if mk.length == 1
        set_cursor(mark_sample(mk.first), snd, chn)
        mk.first
      else
582 583 584
        sorted_mk = mk.sort do |a, b|
          mark_sample(a) <=> mark_sample(b)
        end
585 586 587 588
        pos = cursor(snd, chn)
        curpos = count > 0 ? -1 : 0
        if pos >= mark_sample(sorted_mk.first)
          sorted_mk.each do |m|
589 590 591
            if (count > 0 and
               pos < mark_sample(m)) or
               (count < 0 and pos <= mark_sample(m))
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
              break
            else
              curpos += 1
            end
          end
        end
        curmk = sorted_mk[(curpos + count) % mk.length]
        set_cursor(mark_sample(curmk), snd, chn)
        curmk
      end
    else
      false
    end
  end

  def forward_mark(count = 1, snd = false, chn = false)
    back_or_forth_mark(count, Snd.snd(snd), Snd.chn(chn))
  end

  def backward_mark(count = 1, snd = false, chn = false)
    back_or_forth_mark(-count, Snd.snd(snd), Snd.chn(chn))
  end

  def vct_convolve!(r1, r2)
    convolution(r1, r2, r1.length)
  end

  def old_map_channel(beg = 0, dur = false,
620 621 622
                      snd = false, chn = false,
                      edpos = false, edname = false, &func)
    map_channel(lambda do |y|
623 624 625 626 627
                  if array?(val = func.call(y))
                    vector2vct(val)
                  else
                    val
                  end
628
                end, beg, dur, snd, chn, edpos, edname)
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
  end
  
  def mus_bank(gens, amps, in1 = false, in2 = false)
    amps = case amps
           when Array
             amps.to_vct
           when Vct
             amps
           else
             Vct.new(gens.length, 1.0)
           end
    inp1 = case in1
           when Array
             in1.to_vct
           when Vct
             in1
           else
             Vct.new(gens.length, 0.0)
           end
    inp2 = case in2
           when Array
             in2.to_vct
           when Vct
             in2
           else
             Vct.new(gens.length, 0.0)
           end
    sum = 0.0
657 658 659
    gens.each_with_index do |gen, i|
      sum = sum + amps[i] * mus_run(gen, inp1[i], inp2[i])
    end
660 661 662
    sum
  end

663
  def old_oscil_bank(amps, gens, in1 = false, in2 = false)
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
    amps = case amps
           when Array
             amps.to_vct
           when Vct
             amps
           else
             Vct.new(gens.length, 1.0)
           end
    inp1 = case in1
           when Array
             in1.to_vct
           when Vct
             in1
           else
             Vct.new(gens.length, 0.0)
           end
    inp2 = case in2
           when Array
             in2.to_vct
           when Vct
             in2
           else
             Vct.new(gens.length, 0.0)
           end
    sum = 0.0
689 690 691
    gens.each_with_index do |gen, i|
      sum = sum + amps[i] * oscil(gen, inp1[i], inp2[i])
    end
692 693 694 695 696 697 698 699 700 701 702
    sum
  end

  def old_formant_bank(amps, gens, in1 = 0.0)
    formant_bank(array?(amps) ? amps.to_vct : amps, gens, in1)
  end
  
  def vct2samples(samp, samps, data, snd = false, chn = false)
    vct2channel(data, samp, samps, snd, chn)
  end
  
703 704
  def samples2vct(samp, samps, snd = false, chn = false,
                  nv = false, epos = false)
705 706 707 708 709 710 711
    if nv
      vct_subseq(channel2vct(samp, samps, snd, chn, epos), 0, samps, nv)
    else
      channel2vct(samp, samps, snd, chn, epos)
    end
  end

712 713
  def scale_sound_by(scl, beg = false, dur = false,
                     snd = false, chn = false, edpos = false)
714 715 716
    if integer?(chn)
      scale_channel(scl, beg, dur, snd, chn, edpos)
    else
717 718 719
      channels(snd).times do |c|
        scale_channel(scl, beg, dur, snd, c)
      end
720 721 722 723 724 725 726 727 728 729 730 731
    end
  end

  def scale_sound_to(norm, beg = false, dur = false, snd = false, chn = false)
    if integer?(chn)
      mx = maxamp(snd, chn)
      if mx.nonzero? and mx != norm
        scale_channel(norm / mx, beg, dur, snd, chn)
      end
    else
      mx = maxamp(snd, true).max
      if mx.nonzero? and mx != norm
732 733 734
        channels(snd).times do |c|
          scale_channel(norm / mx, beg, dur, snd, c)
        end
735 736 737
      end
    end
  end
738
  Emacs_hookname = "after-save-as-hook-replace-sound"
739
  def emacs_style_save_as
740
    $after_save_as_hook.member?(Emacs_hookname)
741 742 743 744
  end

  def set_emacs_style_save_as(val = true)
    if val and (not emacs_style_save_as())
745
      $after_save_as_hook.add_hook!(Emacs_hookname) do |snd, fname, from_dialog|
746 747 748 749 750 751 752
        if from_dialog
          revert_sound(snd)
          close_sound(snd)
          open_sound(fname)
        end
      end
    else
753
      $after_save_as_hook.remove_hook!(Emacs_hookname)
754 755 756
    end
  end
  
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
  alias mus_error_to_string mus_error_type2string

  def make_iir_low_pass_1(fc)
    fc = fc.to_f
    theta = (2 * PI * fc) / mus_srate()
    gamma = cos(theta) / (1.0 + sin(theta))
    xc = (1.0 - gamma) / 2.0
    make_filter(2, vct(xc, xc), vct(0.0, -gamma))
  end

  def make_iir_high_pass_1(fc)
    fc = fc.to_f
    theta = (2 * PI * fc) / mus_srate()
    gamma = cos(theta) / (1.0 + sin(theta))
    xc = (1.0 + gamma) / 2.0
    make_filter(2, vct(xc, -xc), vct(0.0, -gamma))
  end

  # 
  # Snd-9 compatibility stuff
  # 
  def sine_bank(amps, phases, size = nil)
    len = (size or amps.length)
    sum = 0.0
781 782 783
    len.times do |i|
      sum = sum + amps[i] * sin(phases[i])
    end
784 785 786 787 788 789 790
    sum
  end
end

include Compatibility

module Extensions
791 792 793
  add_help(:remove_channel_property,
           "remove_channel_property(key, snd)  \
Deletes key-value pair.")
794 795 796 797 798 799
  def remove_channel_property(key, snd = false, chn = false)
    array?(props = channel_properties(snd, chn)) and
      array?(item = props.assoc(key)) and
      props.delete(item)
  end

800 801 802
  add_help(:remove_sound_property,
           "remove_sound_property(key, snd)  \
Deletes key-value pair.")
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
  def remove_sound_property(key, snd = false)
    array?(props = sound_properties(snd)) and
      array?(item = props.assoc(key)) and
      props.delete(item)
  end
  
  def channel_sync(snd = false, chn = false)
    channel_property(:sync, snd, chn)
  end
  
  def set_channel_sync(val, snd = false, chn = false)
    set_channel_property(:sync, val, snd, chn)
  end

  def set_sound_property_save_state_ignore(key, snd = false)
    set_sound_property(:save_state_ignore,
                       (sound_property(:save_state_ignore, snd) or
                          [:save_state_ignore]) + [key],
                       snd)
  end

  def set_channel_property_save_state_ignore(key, snd = false, chn = false)
    set_channel_property(:save_state_ignore,
                         (channel_property(:save_state_ignore, snd, chn) or
                            [:save_state_ignore]) + [key],
                         snd, chn)
  end
  
  def show_sound_properties(snd = false)
    if props = sound_properties(snd)
      Snd.display("sound-properties of %s", file_name(snd).inspect)
      props.each do |k, v|
        Snd.display("%s --> %s", k, v.inspect)
      end
    else
      Snd.display("%s has no sound-properties", file_name(snd).inspect)
    end
    nil
  end

  def show_channel_properties(snd = false, chn = false)
    Snd.display("channel-properties of %s", file_name(snd).inspect)
    if integer?(chn)
      if props = channel_properties(snd, chn)
        Snd.display("==> channel %d <==", chn)
        props.each do |k, v|
          Snd.display("%s --> %s", k, v.inspect)
        end
      else
        Snd.display("==> channel %d has no channel-properties <==", chn)
      end
    else
      channels(snd).times do |cn|
        if props = channel_properties(snd, cn)
          Snd.display("==> channel %d <==", cn)
          props.each do |k, v|
            Snd.display("%s --> %s", k, v.inspect)
          end
        else
          Snd.display("==> channel %d has no channel-properties <==", cn)
        end
      end
    end
    nil
  end
868 869

  # Used in remember_all_sound_properties and remember_sound_state
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
  $sound_funcs = [:sync, :with_tracking_cursor, :selected_channel,
    :show_controls, :read_only, :contrast_control?, :expand_control?,
    :reverb_control?, :filter_control?, :amp_control, :amp_control_bounds,
    :contrast_control, :contrast_control_amp, :contrast_control_bounds,
    :expand_control, :expand_control_bounds, :expand_control_hop,
    :expand_control_jitter, :expand_control_length, :expand_control_ramp,
    :filter_control_envelope, :filter_control_in_dB, :filter_control_in_hz,
    :filter_control_order, :reverb_control_decay, :reverb_control_feedback,
    :reverb_control_length, :reverb_control_length_bounds,
    :reverb_control_lowpass, :reverb_control_scale,
    :reverb_control_scale_bounds, :speed_control, :speed_control_bounds,
    :speed_control_style, :speed_control_tones]
  # transform_type: #<transform Xxx> transform2integer -->
  #   save/load --> integer2transform
  $channel_funcs = [:time_graph?, :transform_graph?, :lisp_graph?, :x_bounds,
    :y_bounds, :cursor, :cursor_size, :cursor_style, :show_marks, :show_y_zero,
    :show_grid, :wavo_hop, :wavo_trace, :max_transform_peaks,
    :show_transform_peaks, :fft_log_frequency, :fft_log_magnitude,
    :with_verbose_cursor, :zero_pad, :wavelet_type, :min_dB, :transform_size,
    :transform_graph_type, :time_graph_type, :fft_window, :transform_type,
    :transform_normalization, :time_graph_style, :show_mix_waveforms,
    :dot_size, :x_axis_style, :show_axes, :graphs_horizontal,
    :lisp_graph_style, :transform_graph_style, :grid_density,
    :tracking_cursor_style]
894
  
895
  # [ms] Based on the idea of remember_sound_state() below, here is
896 897 898 899
  # another approach, using a database file.
  #
  # remember_all_sound_properties() in ~/.snd-ruby.rb installs the hooks
  # default database is ~/.snd-properties.db
900 901
  # default tmp_snd_p is false
  #   (discarding `.*0000_00.snd' and `.*.rev.*' filenames)
902

903 904
  def remember_all_sound_properties(database = ENV['HOME'] + "/.snd-properties",
                                    tmp_snd_p = false)
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
    rsp = Remember_sound_properties.new(database)
    unless $after_open_hook.member?("save-property-hook")
      $after_open_hook.add_hook!("save-property-hook") do |snd|
        rsp.load(snd)
      end
      $close_hook.add_hook!("save-property-hook") do |snd|
        if tmp_snd_p or (not file_name(snd) =~ /(.+\d+_\d+\.snd$)|(.*\.rev.*$)/)
          rsp.save(snd)
        end
      end
    end
    set_property(:remember_properties, :object, rsp)
    rsp
  end

  # Returns the local object created by remember_all_sound_properties
  # to manipulate the database with methods mentioned below; it saves
  # a global variable.
  def remember_properties
    property(:remember_properties, :object)
  end

  class Remember_sound_properties
    add_help(:remember_sound_properties, "\
# class Remember_sound_properties
#   initialize(database)
#
# getter:
#   database
#
# methods:
#   inspect
#   with_db do ... end
#   load(snd)
#   save(snd)
#   each do |file, value| ... end
#   delete_if do |file, value| ... end
#   contents
#   help           (alias info and description)
#
# Usage:
#
# rsp = Remember_sound_properties.new(database)
# unless $after_open_hook.member?(\"save-property-hook\")
#   $after_open_hook.add_hook!(\"save-property-hook\") do |snd|
#     rsp.load(snd)
#   end
#   $close_hook.add_hook!(\"save-property-hook\") do |snd|
#     # discarding `.*0000_00.snd' and `.*.rev.*' filenames
954 955
#     if tmp_snd_p or
#        (not file_name(snd) =~ /(.+\\d+_\\d+\\.snd$)|(.*\\.rev.*$)/)
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
#       rsp.save(snd)
#     end
#   end
# end
#
# rsp.delete_if do |file, value|
#   file =~ /test/
# end                        # deletes all files containing the string \"test\"
# rsp.contents               # prints all filenames in database
# rsp.each do |file, value|
#   Snd.display(file)
# end                        # the same as rsp.contents")

    include Enumerable
    include Info
    with_silence do
      unless defined? DBM.open
        require "dbm"
      end
    end
    
    def initialize(database)
978 979 980
      @database      = database
      @sound_funcs   = $sound_funcs
      @channel_funcs = $channel_funcs
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
      set_help
    end
    attr_reader :database
    alias help description
    
    def inspect
      format("#<%s: database: %s>", self.class, @database.inspect)
    end

    def with_db
      db = DBM.open(@database)
      ret = yield(db)
      db.close
      ret
    end
    
    def load(snd)
      snd_name = file_name(snd)
      with_db do |db|
1000 1001 1002
        Snd.catch do
          eval((db[snd_name] or ""))
        end
1003 1004 1005 1006
      end
      if file_write_date(snd_name) == sound_property(:current_file_time, snd)
        @sound_funcs.each do |prop|
          if (val = sound_property(prop, snd))
1007 1008 1009 1010 1011
            if prop == :selected_channel # arguments swapped!
              Kernel.set_snd_func(prop, snd, val)
            else
              Kernel.set_snd_func(prop, val, snd)
            end
1012 1013 1014 1015 1016 1017
          end
        end
        channels(snd).times do |chn|
          set_squelch_update(true, snd, chn)
          @channel_funcs.each do |prop|
            if (val = channel_property(prop, snd, chn))
1018 1019 1020 1021 1022
              if prop == :transform_type
                Kernel.set_snd_func(prop, integer2transform(val), snd, chn)
              else
                Kernel.set_snd_func(prop, val, snd, chn)
              end
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
            end
          end
          set_squelch_update(false, snd, chn)
        end
      end
    end
    
    # the resulting string looks like
    # let(find_sound("snd_name")) do |snd|
    #   set_sound_properties([...], snd)
    #   if channels(snd) > 0
    #     set_channel_properties([...], snd, 0)
    #   end
    #   if channels(snd) > 1
    #     set_channel_properties([...], snd, 1)
    #   end
    #   ...
    # end
    # self.load evals this string
    def save(snd)
      snd_name = file_name(snd)
      set_sound_property(:current_file_time, file_write_date(snd_name), snd)
      @sound_funcs.each do |prop|
        set_sound_property(prop, snd_func(prop, snd), snd)
      end
      props = (sound_properties(snd) or [])
      if reject = sound_property(:save_state_ignore, snd)
1050 1051 1052
        props.reject! do |k, v|
          reject.member?(k)
        end
1053 1054 1055 1056 1057
      end
      res = format("let(find_sound(%s)) do |snd_s|\n", snd_name.inspect)
      res += format("  set_sound_properties(%s, snd_s)\n", props.inspect)
      channels(snd).times do |chn|
        @channel_funcs.each do |prop|
1058
          if prop == :transform_type
1059 1060 1061
            set_channel_property(prop,
                                 transform2integer(snd_func(prop, snd, chn)),
                                 snd, chn)
1062 1063 1064
          else
            set_channel_property(prop, snd_func(prop, snd, chn), snd, chn)
          end
1065 1066 1067
        end
        props = (channel_properties(snd, chn) or [])
        if reject = channel_property(:save_state_ignore, snd, chn)
1068 1069 1070
          props.reject! do |k, v|
            reject.member?(k)
          end
1071 1072
        end
        res += format("  if channels(snd_s) > %d\n", chn)
1073 1074
        res += format("    set_channel_properties(%s, snd_s, %d)\n",
                      props.inspect, chn)
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
        res += "  end\n"
      end
      res += "end\n"
      res += marks2string(snd)
      with_db do |db|
        db[snd_name] = res
      end
    end

    def each
      with_db do |db|
        db.each do |key, value|
          yield(key, value)
        end
      end
    end
    
   def delete_if(&body)
     with_db do |db|
       db.delete_if(&body)
     end
   end

    def contents
      Snd.display("contents of %s", @database.inspect)
      with_db do |db|
        db.each do |file, value|
          Snd.display(file)
        end
      end
      nil
    end
  
    private
    def set_help
      self.description = get_help(:remember_sound_properties)
    end
  end

  # add channel comments (see extsnd.html->Graphics->draw-string)
  def add_comment(samp, comm, snd = selected_sound(), chn = selected_channel())
    if array?(comments = channel_property(:comments, snd, chn))
      comments.push([samp, comm])
    else
      set_channel_property(:comments, [[samp, comm]], snd, chn)
    end
  end

  def remove_comment(comm, snd = selected_sound(), chn = selected_channel())
1124 1125 1126
    (channel_property(:comments, snd, chn) or []).delete_if do |samp, text|
      text == comm
    end
1127 1128 1129 1130 1131 1132 1133 1134
  end

  def show_comments(snd, chn)
    (channel_property(:comments, snd, chn) or []).each do |samp, text|
      width = 6 * text.length
      if samp.between?(left_sample(snd, chn), right_sample(snd, chn))
        xpos = x2position(samp / srate(snd).to_f, snd, chn)
        ypos = y2position(sample(samp), snd, chn)
1135
        cr = channel_widgets(snd, chn)[17]
1136 1137
        draw_line(xpos, 35, xpos, ypos - 4, snd, chn, Copy_context, cr)
        draw_string(text, xpos - width / 2, 18, snd, chn, Copy_context, cr)
1138 1139 1140
      end
    end
  end
1141 1142 1143
  # $after_graph_hook.add_hook!("show-comments") do |snd, chn|
  #   show_comments(snd, chn)
  # end
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
  
  # Have we marks?  Similar to selections?().
  def marks?(more_than_one = true)
    if (m = marks(selected_sound(), selected_channel())).nil?
      false
    else
      if more_than_one
        m.length > 1
      else
        true
      end
    end
  end
  
  add_help(:all_chans,
1159 1160 1161 1162 1163 1164
           "all_chans()  \
Returns two parallel lists, the first snd indices, \
the second channel numbers.  \
If we have two sounds open (indices 0 and 1 for example), \
and the second has two channels, \
all_chans returns [[0, 1, 1], [0, 0, 1]].")
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  def all_chans
    sndlist = []
    chnlist = []
    Snd.sounds.each do |snd|
      channels(snd).times do |chn|
        sndlist << snd
        chnlist << chn
      end
    end
    [sndlist, chnlist]
  end

  # all_chans:        [[0, 1, 1], [0, 0, 1]]
  # all_chans_zipped: [[0, 0], [1, 0], [1, 1]]
  # fits with each or map
  # all_chans_zipped.each do |snd, chn| ... end
  def all_chans_zipped
    new_list = []
    Snd.sounds.each do |snd|
      channels(snd).times do |chn|
        new_list.push([snd, chn])
      end
    end
    new_list
  end
  
  add_help(:normalized_mix,
1192 1193 1194
           "normalized_mix(filename, beg, in_chan, snd, chn)  \
Is like mix but the mix result has same peak amp \
as unmixed snd/chn (returns scaler).")
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
  def normalized_mix(fname, beg = 0, in_chan = 0, snd = false, chn = false)
    orig_maxamp = maxamp(snd, chn)
    mix(fname, beg, in_chan, snd, chn)
    new_maxamp = maxamp(snd, chn)
    if orig_maxamp == new_maxamp
      1.0
    else
      scl = orig_maxamp / new_maxamp
      old_sync = sync(snd)
      set_sync(false, snd)
      scale_by(scl, snd, chn)
      set_sync(old_sync, snd)
      scl
    end
  end

  add_help(:enveloped_mix,
1212 1213
           "enveloped_mix(filename, beg, env)  \
Mixes FILENAME starting at BEG with amplitude envelope ENV: \
1214 1215
enveloped_mix(\"pistol.snd\", 0, [0, 0, 1, 1, 2, 0])")
  def enveloped_mix(fname, beg, env, del_tmp = true)
1216 1217 1218 1219 1220 1221
    len = framples(fname)
    amp_env = make_env(env, :length, len)
    rd = make_readin(fname)
    map_channel(lambda do |y|
                  y + env(amp_env) * readin(rd)
                end, beg, len)
1222 1223 1224 1225 1226
  end
  # enveloped_mix("pistol.snd", 0, [0, 0, 1, 1, 2, 0])

  add_help(:for_each_sound_file,
           "for_each_sound_file(*dir_args) do |file| ... end  \
1227
Applies body to each sound file in dir.")
1228 1229
  add_help(:map_sound_files,
           "map_sound_files(*dir_array) do |file| ... end  \
1230
Applies body to each sound file in dir.")
1231 1232
  add_help(:each_sound_file,
           "each_sound_file(*dir_args) do |file| ... end  \
1233
Applies body to each sound file in dir.")
1234
  def each_sound_file(*args, &func)
1235 1236 1237
    if args.empty?
      args.push(Dir.pwd)
    end
1238
    args.map do |dir|
1239 1240 1241 1242
      if File.exist?(dir)
        sound_files_in_directory(dir).each do |f|
          func.call(dir + "/" + f)
        end
1243 1244 1245 1246 1247
      end
    end
  end
  alias for_each_sound_file each_sound_file
  alias map_sound_files each_sound_file
1248 1249 1250
  # each_sound_file(".", "/usr/opt/sound/SFiles") do |f|
  #   play(f, :wait, true)
  # end
1251 1252 1253

  add_help(:match_sound_files,
           "match_sound_files(*dir_args) do |file| ... end  \
1254 1255
Applies func to each sound file in dir and returns a list of files \
for which body does not return false.")
1256 1257
  def match_sound_files(*args, &func)
    res = []
1258 1259 1260
    each_sound_file(*args) do |f|
      func.call(f) and res.push(f)
    end
1261 1262 1263 1264 1265
    res
  end
  # match_sound_files() do |f| f =~ /\.(wav|snd)$/ end
  
  add_help(:selection_members,
1266 1267 1268
           "selection_members()  \
Returns list of lists of [snd, chn] indicating the channels \
participating in the current selection.")
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
  def selection_members
    sndlist = []
    if selection?
      Snd.sounds.each do |snd|
        channels(snd).times do |chn|
          sndlist.push([snd, chn]) if selection_member?(snd, chn)
        end
      end
    end
    sndlist
  end

1281 1282 1283
  add_help(:clear_selection,
           "clear_selection()  \
Unselects any currently selected samples.")
1284 1285 1286 1287 1288 1289
  def clear_selection()
    if selection?
      Snd.sounds.each do |snd|
        channels(snd).times do |chn|
          need_update = selection_member?(snd, chn)
          set_selection_member?(false, snd, chn)
1290 1291 1292
          if need_update
            update_time_graph(snd, chn)
          end
1293 1294 1295 1296 1297 1298
        end
      end
    end
  end
  
  add_help(:make_selection,
1299 1300 1301 1302 1303 1304
           "make_selection(beg=0, end=false, snd=false, chn=false)  \
Makes a selection like make-region but without creating a region.  \
make_selection follows SND's sync field, \
and applies to all SND's channels if CHN is not specified.  \
END defaults to end of channel, BEG defaults to 0, \
SND defaults to the currently selected sound.")
1305 1306
  def make_selection(beg = 0, len = false, snd = false, chn = false)
    add_chan_to_selection = lambda do |s0, s1, s, c|
1307 1308 1309
      unless s0 
        s0 = 0
      end
1310 1311 1312 1313 1314
      set_selection_member?(true, s, c)
      set_selection_position(s0, s, c)
      val = if number?(s1)
              s1 + 1
            else
1315
              framples(s, c)
1316
            end
1317
      set_selection_framples(val - s0, s, c)
1318 1319
    end
    current_sound = (snd or selected_sound() or Snd.sounds[0])
1320 1321 1322
    unless sound?(current_sound)
      Snd.raise(:no_such_sound, beg, len, snd, chn)
    end
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    current_sync = sync(current_sound)
    clear_selection()
    if number?(chn)
      add_chan_to_selection.call(beg, len, snd, chn)
    else
      Snd.sounds.each do |s|
        if snd == true or
            s.eql?(current_sound) or
            (current_sync.nonzero? and current_sync == sync(s))
          channels(s).times do |i|
            add_chan_to_selection.call(beg, len, s, i)
          end
        end
      end
    end
  end
  
  add_help(:mix_channel,
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
           "mix_channel(file, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Mixes in FILE.  \
FILE can be the file name or a list [file_name, beg = 0, chn = 0].")
  def mix_channel(fdata, beg = 0, dur = false,
                  snd = false, chn = false, edpos = false)
    assert_type((string?(fdata) or array?(fdata)), fdata, 0,
                "a string or an array")
    unless number?(beg) 
      beg = 0
    end
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
    fname = string?(fdata) ? fdata : fdata.first
    fbeg = if string?(fdata) or fdata.length < 2
             0
           else
             fdata[1]
           end
    fchan = if string?(fdata) or fdata.length < 3
              0
            else
              fdata[2]
            end
1363
    len = (dur or (mus_sound_framples(fname) - fbeg))
1364 1365 1366 1367 1368 1369
    Snd.raise(:no_such_sample) if beg < 0
    if len > 0
      reader = make_sampler(fbeg, fname, fchan)
      map_channel(lambda do |val|
                    val + next_sample(reader)
                  end, beg, len, snd, chn, edpos,
1370
                  format("%s(%p, %s, %s", get_func_name, fdata, beg, dur))
1371 1372 1373 1374
    end
  end
  
  add_help(:insert_channel,
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
           "insert_channel(file, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Inserts the FILE.  \
FILE can be the file name or a list [file_name, beg = 0, chn = 0].")
  def insert_channel(fdata, beg = 0, dur = false,
                     snd = false, chn = false, edpos = false)
    assert_type((string?(fdata) or array?(fdata)), fdata, 0,
                "a string or an array")
    unless number?(beg)
      beg = 0
    end
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    fname = string?(fdata) ? fdata : fdata.first
    fbeg = if string?(fdata) or fdata.length < 2
             0
           else
             fdata[1]
           end
    fchan = if string?(fdata) or fdata.length < 3
              0
            else
              fdata[2]
            end
1397
    len = (dur or (mus_sound_framples(fname) - fbeg))
1398 1399 1400
    Snd.raise(:no_such_sample) if beg < 0
    if len > 0
      reader = make_sampler(fbeg, fname, fchan)
1401 1402 1403 1404 1405
      insert_samples(beg, len,
                     Vct.new(len) do |i|
                       next_sample(reader)
                     end, snd, chn, edpos, false,
                     format("%s(%p, %s, %s", get_func_name, fdata, beg, dur))
1406 1407 1408 1409
    end
  end
  
  add_help(:redo_channel,
1410 1411
           "redo_channel(edits=1, snd=false, chn=false)  \
Is the regularized version of redo.")
1412 1413 1414 1415 1416 1417 1418 1419 1420
  def redo_channel(edits = 1, snd = false, chn = false)
    if snd and sync(snd).nonzero? and chn
      set_edit_position(edit_position(snd, chn) + edits, snd, chn)
    else
      redo_edit(edits, snd)
    end
  end
  
  add_help(:undo_channel,
1421 1422
           "undo_channel(edits=1, snd=false, chn=false)  \
Is the regularized version of undo.")
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
  def undo_channel(edits = 1, snd = false, chn = false)
    if snd and sync(snd).nonzero? and chn
      set_edit_position([edit_position(snd, chn) - edits, 0].max, snd, chn)
    else
      undo_edit(edits, snd)
    end
  end
  
  # Take breakpoints in ENV, connect with FUNC, apply as envelope to
  # channel handled as a sequence of funcs and scales.
  def any_env_channel(env, beg = 0, dur = false, snd = false, chn = false,
                      edpos = false, origin = false, &func)
    if array?(env) and (not env.empty?)
      pts = env.length / 2
      if pts == 1
        scale_channel(env[0], beg, dur, snd, chn, edpos)
      else
        x0 = y0 = 0
        x1, y1 = env[0], env[1]
        xrange = (env[-2] - env[0]).to_f
        ramp_beg = beg
1444 1445 1446
        unless number?(dur)
          dur = framples(snd, chn)
        end
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
        as_one_edit_rb(origin) do | |
          2.step(env.length - 1, 2) do |i|
            x0, y0, x1, y1 = x1, y1, env[i], env[i + 1]
            ramp_dur = (dur * ((x1 - x0) / xrange)).round
            if y0 == y1
              scale_channel(y0, ramp_beg, ramp_dur, snd, chn, edpos)
            else
              func.call(y0, y1, ramp_beg, ramp_dur, snd, chn, edpos)
            end
            ramp_beg += ramp_dur
          end
        end
      end
    end
  end
  
  add_help(:sine_ramp,
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
           "sine_ramp(rmp0, rmp1, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Produces a sinsusoidal connection from RMP0 to RMP1.")
  def sine_ramp(rmp0, rmp1, beg = 0, dur = false,
                snd = false, chn = false, edpos = false)
    angle = -PI
    len = if number?(dur)
            dur
          else
            framples(snd, chn) - beg
          end
    incr = PI / len
    map_channel(lambda do |y|
                  result = y * (rmp0 + (rmp1 - rmp0) * (0.5 + 0.5 * cos(angle)))
                  angle += incr
                  result
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s, %s",
                get_func_name, rmp0, rmp1, beg, dur))
1483 1484 1485
  end

  add_help(:sine_env_channel,
1486 1487 1488 1489 1490
           "sine_env_channel(env, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Connects ENV's dots with sinusoids.")
  def sine_env_channel(env, beg = 0, dur = false,
                       snd = false, chn = false, edpos = false)
1491
    any_env_channel(env, beg, dur, snd, chn, edpos,
1492 1493 1494
                    format("%s(%p, %s, %s",
                           get_func_name,
                           env, beg, dur)) do |r0, r1, b, d, s, c, e|
1495 1496 1497 1498 1499 1500 1501 1502 1503
      sine_ramp(r0, r1, b, d, s, c, e)
    end
  end
  # sine_env_channel([0, 0, 1, 1, 2, -0.5, 3, 1])
  
  # An obvious extension of this idea is to use the blackman fft window
  # formulas to get sharper sinusoids (i.e. use the sum of n cosines,
  # rather than just 1).
  
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
  def blackman4_ramp(rmp0, rmp1, beg = 0, dur = false,
                     snd = false, chn = false, edpos = false)
    angle = 0.0
    len = if number?(dur)
            dur
          else
            framples(snd, chn) - beg
          end
    incr = PI / len
    map_channel(lambda do |y|
                  cx = cos(angle)
                  result = y * (rmp0 + (rmp1 - rmp0) *
                            (0.084037 + cx *
                              (-0.29145 + cx *
                                (0.375696 + cx *
                                  (-0.20762 + cx * 0.041194)))))
                  angle += incr
                  result
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s, %s",
                       get_func_name, rmp0, rmp1, beg, dur))
1525 1526
  end
  
1527 1528
  def blackman4_env_channel(env, beg = 0, dur = false,
                            snd = false, chn = false, edpos = false)
1529
    any_env_channel(env, beg, dur, snd, chn, edpos,
1530 1531 1532
                    format("%s(%p, %s, %s",
                           get_func_name, env,
                           beg, dur)) do |r0, r1, b, d, s, c, e|
1533 1534 1535 1536 1537
      blackman4_ramp(r0, r1, b, d, s, c, e)
    end
  end
  
  add_help(:ramp_squared,
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
           "ramp_squared(rmp0, rmp1, symmetric=true, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Connects RMP0 and RMP1 with an x^2 curve.")
  def ramp_squared(rmp0, rmp1, symmetric = true, beg = 0, dur = false,
                   snd = false, chn = false, edpos = false)
    angle = 0.0
    len = if number?(dur)
            dur
          else
            framples(snd, chn) - beg
          end
    incr = 1.0 / len
    map_channel(lambda do |y|
                  result = y * (rmp0 + angle * angle * (rmp1 - rmp0))
                  angle += incr
                  result
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s, %s, %s", get_func_name, rmp0, rmp1,
                       symmetric, beg, dur))
1557 1558 1559
  end

  add_help(:env_squared_channel,
1560 1561 1562 1563 1564
           "env_squared_channel(env, symmetric=true, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Connects ENV's dots with x^2 curves.")
  def env_squared_channel(env, symmetric = true, beg = 0, dur = false,
                          snd = false, chn = false, edpos = false)
1565
    any_env_channel(env, beg, dur, snd, chn, edpos,
1566
                    format("%s(%p, %s, %s, %s",
1567
                           get_func_name,
1568
                           env, symmetric, beg, dur)) do |r0, r1, b, d, s, c, e|
1569 1570 1571 1572 1573 1574
      ramp_squared(r0, r1, symmetric, b, d, s, c, e)
    end
  end
  # env_squared_channel([0, 0, 1, 1, 2, -0.5, 3, 1])
  
  add_help(:ramp_expt,
1575 1576 1577
           "ramp_expt(rmp0, rmp1, exponent, symmetric=true, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Connects RMP0 and RMP1 with an x^exponent curve.")
1578 1579
  def ramp_expt(rmp0, rmp1, exponent, symmetric = true,
                beg = 0, dur = false, snd = false, chn = false, edpos = false)
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
    angle = 0.0
    len = if number?(dur)
            dur
          else
            framples(snd, chn) - beg
          end
    incr = 1.0 / len
    map_channel(lambda do |y|
                  begin
                    result = y *
                      (rmp0 + exp(log(angle) * exponent) * (rmp1 - rmp0))
                  rescue
                    result = 0.0
                  end
                  angle += incr
                  result
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s, %s, %s, %s",
                       get_func_name, rmp0, rmp1,
                       exponent, symmetric, beg, dur))
1600 1601 1602
  end

  add_help(:env_expt_channel,
1603 1604 1605 1606 1607
           "env_expt_channel(env, exponent, symmetric=true, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Connects ENV's dots with x^exponent curves.")
  def env_expt_channel(env, exponent, symmetric = true, beg = 0, dur = false,
                       snd = false, chn = false, edpos = false)
1608 1609 1610 1611
    if exponent == 1.0
      env_channel(env, beg, dur, snd, chn, edpos)
    else
      any_env_channel(env, beg, dur, snd, chn, edpos,
1612
                      format("%s(%p, %s, %s, %s, %s",
1613
                             get_func_name,
1614 1615
                             env, exponent, symmetric,
                             beg, dur)) do |r0, r1, b, d, s, c, e|
1616 1617 1618 1619 1620 1621
        ramp_expt(r0, r1, exponent, symmetric, b, d, s, c, e)
      end
    end
  end
  
  add_help(:offset_channel,
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
           "offset_channel(amount, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Adds AMOUNT to each sample.")
  def offset_channel(amount, beg = 0, dur = false,
                     snd = false, chn = false, edpos = false)
    map_channel(lambda do |y|
                  y + amount
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s", get_func_name, amount, beg, dur))
  end

  add_help(:offset_sound,
           "offset_sound(off, beg=0, dur=false, snd=false)  \
Adds OFF to every sample in SND.")
  def offset_sound(off, beg = 0, dur = false, snd = false)
    snd = Snd.snd(snd)
    if sound?(snd)
      channels(snd).times do |chn|
        offset_channel(off, beg, dur, snd, chn)
      end
    else
      Snd.raise(:no_such_sound, snd)
    end
  end

  add_help(:pad_sound,
           "pad_sound(beg, dur, snd=false)  \
Places a block of DUR zeros in every channel of SND starting at BEG.")
  def pad_sound(beg, dur, snd = false)
    snd = Snd.snd(snd)
    if sound?(snd)
      channels(snd).times do |chn|
        pad_channel(beg, dur, snd, chn)
      end
    else
      Snd.raise(:no_such_sound, snd)
    end
1659 1660 1661
  end

  add_help(:dither_channel,
1662 1663 1664 1665 1666
           "dither_channel(amount=0.00006, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Adds AMOUNT dither to each sample.")
  def dither_channel(amnt = 0.00006, beg = 0, dur = false,
                     snd = false, chn = false, edpos = false)
1667
    dither = 0.5 * amnt
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    map_channel(lambda do |y|
                  mus_random(dither) + mus_random(dither) + y
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s", get_func_name, amnt, beg, dur))
  end

  add_help(:dither_sound,
           "dither_sound(amount=0.00006, beg=0, dur=false, snd=false)  \
Adds dithering to every channel of SND.")
  def dither_sound(amnt = 0.00006, beg = 0, dur = false, snd = false)
    snd = Snd.snd(snd)
    if sound?(snd)
      channels(snd).times do |chn|
        dither_channel(amnt, beg, dur, snd, chn)
      end
    else
      Snd.raise(:no_such_sound, snd)
    end
1686 1687 1688
  end

  add_help(:contrast_channel,
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711
           "contrast_channel(index, beg=0, dur=false, \
snd=false, chn=false, edpos=false)  \
Applies contrast-enhancement to the sound.")
  def contrast_channel(index, beg = 0, dur = false,
                       snd = false, chn = false, edpos = false)
    map_channel(lambda do |y|
                  sin(y * HALF_PI + index * sin(y * TWO_PI))
                end, beg, dur, snd, chn, edpos,
                format("%s(%s, %s, %s", get_func_name, index, beg, dur))
  end

  add_help(:contrast_sound,
           "contrast_sound(index, beg=0, dur=false, snd=false)  \
Applies contrast-enhancement to every channel of SND.")
  def contrast_sound(index, beg = 0, dur = false, snd = false)
    snd = Snd.snd(snd)
    if sound?(snd)
      channels(snd).times do |chn|
        contrast_channel(index, beg, dur, snd, chn)
      end
    else
      Snd.raise(:no_such_sound, snd)
    end
1712 1713 1714 1715
  end

  # channels-equal
  add_help(:channels_eql?,
1716 1717 1718
           "channels_eql?(s1, c1, s2, c2, diff=0.0)  \
Returns true if the two channels \
are the same (within diff) modulo trailing 0's.")
1719 1720 1721 1722 1723 1724 1725 1726 1727
  def channels_eql?(snd1, chn1, snd2, chn2, allowable_difference = 0.0)
    if snd1.eql?(snd2) and chn1 == chn2
      true
    else
      mx1 = maxamp(snd1, chn1)
      mx2 = maxamp(snd2, chn2)
      if (mx1 - mx2).abs > allowable_difference
        false
      else
1728 1729
        len1 = framples(snd1, chn1)
        len2 = framples(snd2, chn2)
1730 1731 1732 1733 1734 1735 1736
        first_longer = (len1 >= len2)
        len = first_longer ? len1 : len2
        s1 = first_longer ? snd1 : snd2
        s2 = first_longer ? snd2 : snd1
        c1 = first_longer ? chn1 : chn2
        c2 = first_longer ? chn2 : chn1
        read2 = make_sampler(0, s2, c2)
1737
        (not scan_channel(lambda do |y|
1738 1739
                            val = read_sample(read2)
                            (val - y).abs > allowable_difference
1740
                          end, 0, len, s1, c1))
1741 1742 1743 1744 1745
      end
    end
  end

  add_help(:channels_equal?,
1746 1747
           "channels_equal?(s1, c1, s2, c2, diff=0.0)  \
Returns true if the two channels are the same (within diff).")
1748
  def channels_equal?(snd1, chn1, snd2, chn2, allowable_difference = 0.0)
1749 1750
    len1 = framples(snd1, chn1)
    len2 = framples(snd2, chn2)
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
    if len1 == len2
      channels_eql?(snd1, chn1, snd2, chn2, allowable_difference)
    else
      false
    end
  end

  # mono->stereo, mono-files->stereo
  def mono2stereo(new_name, snd1, chn1, snd2, chn2)
    old_ed1 = edit_position(snd1, chn1)
    old_ed2 = edit_position(snd2, chn2)
    ind = new_sound(new_name, :channels, 2, :srate, srate(snd1))
    swap_channels(ind, 0, snd1, chn1)
    swap_channels(ind, 1, snd2, chn2)
    set_edit_position(old_ed1, snd1, chn1)
    set_edit_position(old_ed2, snd2, chn2)
    ind
  end
  # mono2stereo("test.snd", 0, 0, 1, 0)

  def mono_files2stereo(new_name, chan1_name, chan2_name)
    ind1 = open_sound(chan1_name)
    ind2 = open_sound(chan2_name)
    ind3 = mono2stereo(new_name, ind1, 0, ind2, 0)
    close_sound(ind1)
    close_sound(ind2)
    ind3
  end
  # mono_files2stereo("test.snd", "oboe.snd", "pistol.snd")

  def stereo2mono(orig_snd, chan1_name, chan2_name)
    old_ed0 = edit_position(orig_snd, 0)
    old_ed1 = edit_position(orig_snd, 1)
    chan1 = new_sound(chan1_name, :srate, srate(orig_snd))
    chan2 = new_sound(chan2_name, :srate, srate(orig_snd))
    swap_channels(orig_snd, 0, chan1, 0)
    swap_channels(orig_snd, 1, chan2, 0)
    set_edit_position(old_ed0, orig_snd, 0)
    set_edit_position(old_ed1, orig_snd, 1)
    [chan1, chan2]
  end
  # stereo2mono(0, "hi1.snd", "hi2.snd")

  # 
  # === PREFERENCES-DIALOG ===
  # 

  # reopen menu

  $including_reopen_menu = false # for prefs

  def with_reopen_menu
    unless $including_reopen_menu
      menu = Reopen_menu.new("Reopen")
      $including_reopen_menu = true
1806 1807 1808 1809 1810 1811
      $close_hook.add_hook!("prefs-add-to-reopen-menu") do |snd|
        menu.add_to_reopen_menu(snd)
      end
      $open_hook.add_hook!("prefs-check-reopen-menu") do |file|
        menu.check_reopen_menu(file)
      end
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
    end
  end

  class Reopen_menu
    def initialize(name)
      @menu_name = name
      @reopen_menu = add_to_main_menu(name, lambda do | | end)
      @reopen_names = []
      @reopen_max_length = 16
      @reopen_empty = "empty"
    end

    def add_to_reopen_menu(snd)
      brief_name = short_file_name(snd)
      long_name = file_name(snd)
      unless(@reopen_names.member?(brief_name))
        if @reopen_names.member?(@reopen_empty)
          remove_from_menu(@reopen_menu, @reopen_empty)
          @reopen_names = []
        end
1832
        add_to_menu(@reopen_menu, brief_name,
1833 1834
                    lambda do | |
                      remove_from_menu(@reopen_menu, brief_name)
1835 1836 1837 1838
                      if File.exist?(long_name)
                        open_sound(long_name)
                      end
                    end, 0)
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
        @reopen_names.push(brief_name)
        if @reopen_names.length > @reopen_max_length
          remove_from_menu(@reopen_menu, @reopen_names.shift)
        end
      end
      false
    end

    def check_reopen_menu(file)
      brief_name = File.basename(file)
      if @reopen_names.member?(brief_name)
        remove_from_menu(@reopen_menu, brief_name)
        @reopen_names.delete(brief_name)
      end
      if @reopen_names.empty?
        add_to_menu(@reopen_menu, @reopen_empty, lambda do | | end, 0)
        @reopen_names.push(@reopen_empty)
      end
    end
  end

  # buffers menu

  $include_buffers_menu = false # for prefs

  def with_buffers_menu
    unless $include_buffers_menu
      menu = Buffers_menu.new("Buffers")
      $include_buffers_menu = true
1868 1869 1870 1871 1872 1873
      $open_hook.add_hook!("prefs-open-buffer") do |file|
        menu.open_buffer(file)
      end
      $close_hook.add_hook!("prefs-close-buffer") do |file|
        menu.close_buffer(file)
      end
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
    end
  end
  
  class Buffers_menu
    def initialize(name)
      @menu_name = name
      @buffer_menu = add_to_main_menu(name, lambda do | | end)
      @buffer_names = []
      @buffer_empty = "empty"
    end

    def open_buffer(file)
      if @buffer_names.member?(@buffer_empty)
        remove_from_menu(@buffer_menu, @buffer_empty)
        @buffer_names = []
      end
1890
      add_to_menu(@buffer_menu, file,
1891
                  lambda do | |
1892 1893 1894 1895
                    if sound?(ind = find_sound(file))
                      select_sound(ind)
                    end
                  end, -1)
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
      @buffer_names.push(file)
    end

    def close_buffer(snd)
      remove_from_menu(@buffer_menu, file_name(snd))
      @buffer_names.delete(file_name(snd))
      if @buffer_names.empty?
        add_to_menu(@buffer_menu, @buffer_empty, lambda do | | end, 0)
        @buffer_names.push(@buffer_empty)
      end
      false
    end
  end
end

include Extensions

# extensions.rb ends here