snd-sig.c 207 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include "snd.h"
#include "clm2xen.h"
#include "clm-strings.h"

/* collect syncd chans */
typedef struct {
  sync_info *si;
  snd_fd **sfs;
  mus_long_t dur;
} sync_state;


static void free_sync_state(sync_state *sc)
{
  if (sc)
    {
      if (sc->si) 
	sc->si = free_sync_info(sc->si);
      if (sc->sfs) 
	free(sc->sfs);
      free(sc);
    }
}


26
int to_c_edit_position(chan_info *cp, Xen edpos, const char *caller, int arg_pos)
27
{
28
  int pos = AT_CURRENT_EDIT_POSITION;
29 30 31 32 33 34 35
  /* need to allow #f here for optargs */
  /* also remember that there might be no extension language */

#if (!HAVE_EXTENSION_LANGUAGE)
  return(cp->edit_ctr);
#endif

36
  Xen_check_type(!Xen_is_bound(edpos) || Xen_is_integer(edpos) || Xen_is_false(edpos), edpos, arg_pos, caller, "an integer, or " PROC_FALSE);
37

38 39
  if (Xen_is_integer(edpos))
    pos = Xen_integer_to_C_int(edpos);
40

41 42
  if (pos == AT_CURRENT_EDIT_POSITION)
    return(cp->edit_ctr);
43

44 45
  if ((pos < 0) || 
      (pos >= cp->edit_size) ||
46 47
      (!cp->edits[pos]))
    Xen_error(Xen_make_error_type("no-such-edit"),
48 49 50
	      Xen_list_8(C_string_to_Xen_string("~A: no such edpos: ~A (from ~A), sound index: ~A (~S), chan: ~A, current edit: ~A"),
			 C_string_to_Xen_string(caller),
			 C_int_to_Xen_integer(pos),
51
			 edpos,
52 53 54 55
			 C_int_to_Xen_sound(cp->sound->index),
			 C_string_to_Xen_string(cp->sound->short_filename),
			 C_int_to_Xen_integer(cp->chan),
			 C_int_to_Xen_integer(cp->edit_ctr)));
56 57 58 59
  return(pos);
}


60
mus_long_t to_c_edit_samples(chan_info *cp, Xen edpos, const char *caller, int arg_pos)
61 62 63 64 65
{
  return(cp->edits[to_c_edit_position(cp, edpos, caller, arg_pos)]->samples);
}


66
mus_long_t beg_to_sample(Xen beg, const char *caller)
67
{
68 69 70 71 72
  if (Xen_is_integer(beg))
    {
      mus_long_t start;
      start = Xen_llong_to_C_llong(beg);
      if (start < 0) 
73 74
	Xen_error(Xen_make_error_type("no-such-sample"), 
		  Xen_list_3(C_string_to_Xen_string("~A: no such sample: ~A"), C_string_to_Xen_string(caller), beg));
75 76 77 78 79
      if (start > (1LL << 34))
	Xen_out_of_range_error(caller, 1, beg, "too large");
      return(start);
    }
  return(0);
80 81 82
}


83
mus_long_t dur_to_samples(Xen dur, mus_long_t beg, chan_info *cp, int edpos, int argn, const char *caller)
84
{
85 86 87 88 89 90 91 92 93 94 95
  if (Xen_is_integer(dur))
    {
      mus_long_t samps;
      samps = Xen_llong_to_C_llong(dur);
      if (samps < 0)
	Xen_wrong_type_arg_error(caller, argn, dur, "a positive integer");
      if (samps > (1LL << 34))
	Xen_out_of_range_error(caller, argn, dur, "too large");
      return(samps);
    }
  return(cp->edits[edpos]->samples - beg);
96 97 98
}


99
static mus_long_t end_to_sample(Xen end, chan_info *cp, int edpos, const char *caller)
100
{
101 102 103 104 105
  if (Xen_is_integer(end))
    {
      mus_long_t last;
      last = Xen_llong_to_C_llong(end);
      if (last < 0) 
106 107
	Xen_error(Xen_make_error_type("no-such-sample"), 
		  Xen_list_3(C_string_to_Xen_string("~A: no such sample: ~A"), C_string_to_Xen_string(caller), end));
108 109 110 111 112
      if (last > (1LL << 34))
	Xen_out_of_range_error(caller, 2, end, "too large");
      return(last);
    }
  return(cp->edits[edpos]->samples - 1);
113 114 115 116
}


static sync_state *get_sync_state_1(snd_info *sp, chan_info *cp, mus_long_t beg, bool over_selection, 
117
				    read_direction_t forwards, mus_long_t prebeg, Xen edpos, const char *caller, int arg_pos)
118 119 120 121 122 123 124 125 126
{
  /* can return NULL if over_selection and no current selection */
  sync_info *si = NULL;
  snd_fd **sfs = NULL;
  chan_info *ncp;
  int i, pos;
  mus_long_t dur = 0, pbeg;
  sync_state *sc;

127
  if ((!over_selection) && (!sp)) return(NULL);
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

  if ((!over_selection) && (sp->sync != 0))
    {
      si = snd_sync(sp->sync);
      sfs = (snd_fd **)malloc(si->chans * sizeof(snd_fd *));
      for (i = 0; i < si->chans; i++) 
	{
	  ncp = si->cps[i];
	  si->begs[i] = beg;
	  pos = to_c_edit_position(ncp, edpos, caller, arg_pos);
	  if (forwards == READ_FORWARD)
	    sfs[i] = init_sample_read_any(beg, ncp, READ_FORWARD, pos);
	  else sfs[i] = init_sample_read_any(ncp->edits[pos]->samples - 1, ncp, READ_BACKWARD, pos);
	}
    }
  else
    {
      if (over_selection)
	{
	  if (selection_is_active())
	    {
	      si = selection_sync();
	      dur = selection_len();
	      sfs = (snd_fd **)malloc(si->chans * sizeof(snd_fd *));
	      for (i = 0; i < si->chans; i++) 
		{
		  ncp = si->cps[i];
		  pos = to_c_edit_position(ncp, edpos, caller, arg_pos);
		  if (forwards == READ_FORWARD)
		    {
		      pbeg = si->begs[i] - prebeg;
		      if (pbeg < 0) pbeg = 0;
		      sfs[i] = init_sample_read_any(pbeg, ncp, READ_FORWARD, pos);
		    }
		  else sfs[i] = init_sample_read_any(si->begs[i] + dur - 1, ncp, READ_BACKWARD, pos);
		}
	    }
	  else 
	    {
167
	      snd_warning_without_format("no selection");
168 169 170 171
	      return(NULL);
	    }
	}
    }
172
  if (!si) 
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    {
      snd_fd *sf = NULL;
      pos = to_c_edit_position(cp, edpos, caller, arg_pos);
      if (forwards == READ_FORWARD)
	sf = init_sample_read_any(beg, cp, READ_FORWARD, pos);
      else sf = init_sample_read_any(cp->edits[pos]->samples - 1, cp, READ_BACKWARD, pos);
      if (sf)
	{
	  si = make_simple_sync(cp, beg);
	  sfs = (snd_fd **)malloc(sizeof(snd_fd *));
	  sfs[0] = sf;
	}
      else return(NULL);
    }
  sc = (sync_state *)calloc(1, sizeof(sync_state));
  sc->dur = dur;
  sc->sfs = sfs;
  sc->si = si;
  return(sc);
}


static sync_state *get_sync_state(snd_info *sp, chan_info *cp, mus_long_t beg, bool over_selection, 
196
				  read_direction_t forwards, Xen edpos, const char *caller, int arg_pos)
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
{
  return(get_sync_state_1(sp, cp, beg, over_selection, forwards, 0, edpos, caller, arg_pos));
}


static sync_state *get_sync_state_without_snd_fds(snd_info *sp, chan_info *cp, mus_long_t beg, bool over_selection)
{
  sync_info *si = NULL;
  mus_long_t dur = 0;
  sync_state *sc;
  if ((sp->sync != 0) && (!over_selection))
    {
      int i;
      si = snd_sync(sp->sync);
      for (i = 0; i < si->chans; i++) 
	si->begs[i] = beg;
    }
  else
    {
      if (over_selection)
	{
	  if (selection_is_active())
	    {
	      si = selection_sync();
	      dur = selection_len();
	    }
	  else
	    {
225
	      snd_warning_without_format("no selection");
226 227 228 229
	      return(NULL);
	    }
	}
    }
230
  if (!si) 
231 232 233 234 235 236 237 238 239
    si = make_simple_sync(cp, beg);
  sc = (sync_state *)calloc(1, sizeof(sync_state));
  sc->dur = dur;
  sc->si = si;
  sc->sfs = NULL;
  return(sc);
}


240
static char *convolve_with_or_error(char *filename, mus_float_t amp, chan_info *cp, Xen edpos, int arg_pos)
241 242 243 244 245
{
  /* if string returned, needs to be freed */
  /* amp == 0.0 means unnormalized, cp == NULL means current selection */
  sync_state *sc;
  sync_info *si;
246 247 248 249
  snd_info *sp = NULL;
  int ip, stop_point = 0, filter_chans;
  mus_sample_t dataformat;
  mus_long_t filtersize = 0, dataloc;
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  chan_info *ncp, *ucp;
  char *origin;

  if (cp) 
    {
      sp = cp->sound; 
      ncp = cp;
    }
  else
    {
      sp = any_selected_sound();
      if (!sp) return(NULL);
      ncp = any_selected_channel(sp);
    }

  filter_chans = mus_sound_chans(filename);
  if (filter_chans <= 0)
267
    return(mus_format("convolve: impulse response file %s chans: %d", filename, filter_chans));
268 269 270

  filtersize = mus_sound_samples(filename) / filter_chans;
  if (filtersize <= 0) 
271
    return(mus_format("convolve: impulse response file %s is empty", filename));
272 273 274
  /* if impulse response is stereo, we need to use both its channels */

  dataloc = mus_sound_data_location(filename);
275
  dataformat = mus_sound_sample_type(filename);
276

277 278
  sc = get_sync_state_without_snd_fds(sp, ncp, 0, (!cp));
  if (!sc) return(NULL);
279 280 281 282
  si = sc->si;

#if HAVE_FORTH
  origin = mus_format("\"%s\" %.3f %s", 
283
		      filename, amp,  (!cp) ? S_convolve_selection_with : S_convolve_with);
284 285
#else
  origin = mus_format("%s" PROC_OPEN "\"%s\"" PROC_SEP "%.3f", 
286
	       to_proc_name((!cp) ? S_convolve_selection_with : S_convolve_with), 
287 288 289 290
	       filename, amp);
#endif
  if (!(ss->stopped_explicitly))
    {
291 292
      snd_info *gsp = NULL;
      int impulse_chan = 0;
293 294 295 296
      for (ip = 0; ip < si->chans; ip++)
	{
	  char *ofile, *saved_chan_file;
	  io_error_t io_err;
297 298
	  bool ok = false;
	  mus_long_t filesize;
299 300

      	  ucp = si->cps[ip];
301
	  if (!(is_editable(ucp))) continue;
302 303 304 305 306 307 308 309 310 311 312 313 314 315
	  sp = ucp->sound;
	  if (!(sp->active)) continue;
	  if ((ip == 0) || (sp != gsp)) 
	    gsp = ucp->sound; 

	  /* ofile here = new convolved data */
	  ofile = snd_tempnam();

	  saved_chan_file = snd_tempnam();
	  io_err = save_channel_edits(ucp, saved_chan_file, to_c_edit_position(ucp, edpos, S_convolve_with, arg_pos));
	  if (io_err != IO_NO_ERROR)
	    {
	      if (ofile) free(ofile);
	      free_sync_state(sc);
316
	      return(mus_format("convolve: save chan (%s[%d]) in %s hit error: %s\n",
317 318 319 320 321 322 323 324 325 326 327
				sp->short_filename, ucp->chan, 
				saved_chan_file, snd_open_strerror()));
	    }
	  else
	    {
	      int scfd;
	      scfd = mus_file_open_read(saved_chan_file);
	      if (scfd == -1) 
		{
		  if (ofile) free(ofile);
		  free_sync_state(sc);
328
		  return(mus_format("convolve: open saved chan (%s[%d]) file %s hit error: %s\n",
329 330 331 332 333 334 335 336 337 338
				    sp->short_filename, ucp->chan, 
				    saved_chan_file, snd_open_strerror()));
		}
	      else
		{
		  file_info *hdr;
		  int fltfd;
		  hdr = sp->hdr;
		  snd_file_open_descriptors(scfd,
					    saved_chan_file,
339
					    hdr->sample_type,
340 341 342 343 344 345 346
					    hdr->data_location,
					    1, hdr->type); /* ??? */
		  fltfd = mus_file_open_read(filename);
		  if (fltfd == -1) 
		    {
		      if (ofile) free(ofile);
		      free_sync_state(sc);
347
		      return(mus_format("convolve: open filter file %s hit error: %s\n", 
348 349 350 351 352 353 354 355 356 357
					filename, snd_open_strerror()));
		    }
		  else
		    {
		      snd_file_open_descriptors(fltfd,
						filename,
						dataformat,
						dataloc,
						filter_chans,
						mus_sound_header_type(filename));
358
		      if (!cp)
359 360 361 362 363
			filesize = selection_len();
		      else filesize = to_c_edit_samples(ucp, edpos, S_convolve_with, arg_pos);
		      if (filesize > 0)
			{
			  int ipow;
364
			  mus_long_t fftsize;
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
			  ipow = (int)(ceil(log(filtersize + filesize) / log(2.0))) + 1;
			  fftsize = snd_mus_long_t_pow2(ipow);
			  ok = true;
			  c_convolve(ofile, amp, scfd,
				     mus_sound_data_location(saved_chan_file),
				     fltfd, dataloc, filtersize, fftsize, filter_chans, impulse_chan,
				     filtersize + filesize + 1,
				     gsp);
			  impulse_chan++;
			  if (impulse_chan >= filter_chans) 
			    impulse_chan = 0;
			}
		      if (mus_file_close(fltfd) != 0)
			{
			  if (ofile) free(ofile);
			  free_sync_state(sc);
381
			  return(mus_format("convolve: close filter file %s hit error: %s\n", 
382 383 384 385 386 387 388 389
					    filename, snd_io_strerror()));
			}
		    }
		}
	      if (mus_file_close(scfd) != 0)
		{
		  if (ofile) free(ofile);
		  free_sync_state(sc);
390
		  return(mus_format("convolve: close saved chan (%s[%d]) file %s hit error: %s\n",
391 392 393 394 395 396 397 398 399
				    sp->short_filename, ucp->chan, 
				    saved_chan_file, snd_io_strerror()));
		}
	    }
	  snd_remove(saved_chan_file, REMOVE_FROM_CACHE);
	  free(saved_chan_file);

	  if (ok)
	    {
400
	      if (!cp)
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
		{
		  delete_samples(si->begs[ip], sc->dur, ucp, ucp->edit_ctr);
		  if ((filtersize + filesize) > 0)
		    {
		      file_insert_samples(si->begs[ip], filtersize + filesize, ofile, ucp, 0, DELETE_ME, origin, ucp->edit_ctr);
		      reactivate_selection(ucp, si->begs[ip], si->begs[ip] + filtersize + filesize);
		      backup_edit_list(ucp); 
		      ripple_trailing_marks(ucp, si->begs[ip], sc->dur, filtersize + filesize);
		    }
		  else snd_remove(ofile, REMOVE_FROM_CACHE);
		  update_graph(ucp); 
		}
	      else file_override_samples(filtersize + filesize, ofile, ucp, 0, DELETE_ME, origin);
	    }
	  if (ofile) free(ofile);
	  check_for_event();
	  if (ss->stopped_explicitly) 
	    {
	      stop_point = ip;
	      break;
	    }
	}
    }
  if (origin) 
    {
      free(origin); 
      origin = NULL;
    }
  if (ss->stopped_explicitly)
    {
      /* clean up and undo all edits up to stop_point */
      ss->stopped_explicitly = false;
      for (ip = 0; ip <= stop_point; ip++)
	{
	  ucp = si->cps[ip];
	  undo_edit(ucp, 1);
	}
    }
  free_sync_state(sc);
  return(NULL);
}


/* amplitude scaling */

void scale_by(chan_info *cp, mus_float_t *ur_scalers, int len, bool over_selection)
{
  /* if over_selection, sync to current selection, else sync to current sound */
  /* 3-Oct-00: the scale factors are now embedded in the edit fragments  */
  sync_info *si;
  int i, j;

  if (over_selection)
    si = selection_sync();
  else si = sync_to_chan(cp);
456
  if (!si) return;
457 458 459

  for (i = 0, j = 0; i < si->chans; i++)
    {
460
      mus_long_t beg, framples;
461 462 463 464 465
      chan_info *ncp;
      ncp = si->cps[i];
      if (over_selection)
	{
	  beg = selection_beg(ncp);
466
	  framples = selection_end(ncp) - beg + 1;
467 468 469 470
	}
      else
	{
	  beg = 0;
471
	  framples = current_samples(ncp);
472
	}
473
      scale_channel(ncp, ur_scalers[j], beg, framples, ncp->edit_ctr, NOT_IN_AS_ONE_EDIT);
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
      j++;
      if (j >= len) j = 0;
    }
  free_sync_info(si);
}


bool scale_to(snd_info *sp, chan_info *cp, mus_float_t *ur_scalers, int len, bool over_selection)
{
  /* essentially the same as scale-by, but first take into account current maxamps */
  /* here it matters if more than one arg is given -- if one, get overall maxamp */
  /*   if more than one, get successive maxamps */
  bool scaled = false;
  int i, chans, nlen, datum_size;
  sync_info *si = NULL;
  chan_info *ncp;
490
  mus_float_t maxamp = -1.0, val;
491 492
  mus_float_t *scalers;

493
  if ((!over_selection) && (!cp)) return(false);
494 495 496 497 498 499 500 501 502
  if (over_selection) 
    {
      if (!(selection_is_active())) 
	return(false);
      si = selection_sync();
      sp = si->cps[0]->sound;
    }
  else si = sync_to_chan(cp);

503
  datum_size = mus_bytes_per_sample((sp->hdr)->sample_type);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  chans = si->chans;
  scalers = (mus_float_t *)calloc(chans, sizeof(mus_float_t));
  if (chans < len)
    nlen = chans; 
  else nlen = len;
  for (i = 0; i < nlen; i++) 
    scalers[i] = ur_scalers[i];
  if (chans > len)
    for (i = len; i < chans; i++) 
      scalers[i] = ur_scalers[len - 1];

  /* now find maxamps (special if len==1) and fixup the scalers */
  if (len == 1)
    {
      if (scalers[0] != 0.0)
	{
	  for (i = 0; i < chans; i++)
	    {
	      ncp = si->cps[i];
	      if (over_selection)
		val = selection_maxamp(ncp);
	      else val = channel_maxamp(ncp, AT_CURRENT_EDIT_POSITION);
	      if (val > maxamp) maxamp = val;
	    }
	  if ((!(clipping(ss))) && 
	      (scalers[0] == 1.0) &&
	      (datum_size <= 2))
	    {
	      if (datum_size == 2)
		scalers[0] = 32767.0 / 32768.0;
	      else scalers[0] = 127.0 / 128.0;
	    }
	  if (maxamp != 0.0)
	    val = scalers[0] / maxamp;
	  else val = 0.0;
	}
      else val = 0.0;
      for (i = 0; i < chans; i++) 
	scalers[i] = val;
    }
  else
    {
      for (i = 0; i < chans; i++)
	{
	  ncp = si->cps[i];
	  if (scalers[i] != 0.0)
	    {
	      if (over_selection)
		val = selection_maxamp(ncp);
	      else val = channel_maxamp(ncp, AT_CURRENT_EDIT_POSITION);
	      if (val > maxamp) maxamp = val;
	      if (val != 0.0)
		{
		  if ((!(clipping(ss))) && 
		      (scalers[i] == 1.0) && 
		      (datum_size <= 2))
		    {
		      if (datum_size == 2)
562 563
			scalers[i] = 32767.0 / 32768.0;
		      else scalers[i] = 127.0 / 128.0;
564 565 566 567 568 569 570 571 572 573 574 575 576
		    }
		  scalers[i] /= val;
		}
	      else scalers[i] = 0.0;
	    }
	  else maxamp = 1.0; /* turn off the maxamp check */
	}
    }

  if (maxamp != 0.0)
    {
      for (i = 0; i < si->chans; i++)
	{
577 578 579
	  mus_long_t beg, framples;
	  char *origin = NULL;
	  mus_float_t norm = 1.0;
580 581 582 583 584
	  ncp = si->cps[i];
	  if (nlen > i) norm = ur_scalers[i]; else norm = ur_scalers[0];
	  if (over_selection)
	    {
	      beg = selection_beg(ncp);
585
	      framples = selection_end(ncp) - beg + 1;
586
#if HAVE_FORTH
587
	      origin = mus_format("%.3f" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long " %s", norm, beg, framples, S_normalize_channel);
588
#else
589
	      origin = mus_format("%s" PROC_OPEN "%.3f" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long, to_proc_name(S_normalize_channel), norm, beg, framples);
590 591 592 593 594
#endif
	    }
	  else
	    {
	      beg = 0;
595
	      framples = current_samples(ncp);
596 597 598
#if HAVE_FORTH
	      origin = mus_format("%.3f 0 " PROC_FALSE " %s", norm, S_normalize_channel);
#else
599
	      origin = mus_format("%s" PROC_OPEN "%.3f" PROC_SEP "0" PROC_SEP PROC_FALSE, to_proc_name(S_normalize_channel), norm);
600 601
#endif
	    }
602
	  scale_channel_with_origin(ncp, scalers[i], beg, framples, ncp->edit_ctr, NOT_IN_AS_ONE_EDIT, origin);
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
	  if (origin) free(origin);
	  origin = NULL;
	}
      scaled = true;
    }

  free(scalers);
  free_sync_info(si);
  return(scaled);
}


static void swap_channels(chan_info *cp0, chan_info *cp1, mus_long_t beg, mus_long_t dur, int pos0, int pos1)
{
  snd_fd *c0, *c1;
  snd_info *sp0;
  file_info *hdr0 = NULL, *hdr1 = NULL;
620
  int ofd0 = 0, ofd1 = 0, datumb = 0;
621
  bool temp_file;
622 623 624
  mus_long_t alloc_len;
  mus_float_t **data0, **data1;
  mus_float_t *idata0, *idata1;
625 626 627 628 629
  bool reporting = false;
  char *ofile0 = NULL, *ofile1 = NULL;
  io_error_t io_err = IO_NO_ERROR;

  if (dur <= 0) return;
630
  if ((!(is_editable(cp0))) || (!(is_editable(cp1)))) return;
631 632 633 634
  sp0 = cp0->sound;
  reporting = ((sp0) && (dur > REPORTING_SIZE) && (!(cp0->squelch_update)));
  if (reporting) start_progress_report(cp0);

635
  if (dur > REPORTING_SIZE)
636
    {
637
      alloc_len = REPORTING_SIZE;
638 639
      temp_file = true; 
      ofile0 = snd_tempnam();
640
      hdr0 = make_temp_header(ofile0, snd_srate(sp0), 1, dur, (char *)S_swap_channels);
641 642 643 644
      ofd0 = open_temp_file(ofile0, 1, hdr0, &io_err);
      if (ofd0 == -1)
	{
	  free_file_info(hdr0);
645
	  snd_error("%s " S_swap_channels " temp file %s: %s\n", 
646 647 648 649 650
		    (io_err != IO_NO_ERROR) ? io_error_name(io_err) : "can't open",
		    ofile0, 
		    snd_open_strerror());
	  return;
	}
651
      datumb = mus_bytes_per_sample(hdr0->sample_type);
652
      ofile1 = snd_tempnam();
653
      hdr1 = make_temp_header(ofile1, snd_srate(sp0), 1, dur, (char *)S_swap_channels);
654 655 656 657 658 659 660
      ofd1 = open_temp_file(ofile1, 1, hdr1, &io_err);
      if (ofd1 == -1)
	{
	  close_temp_file(ofile0, ofd0, hdr0->type, 0);
	  free_file_info(hdr0);
	  free_file_info(hdr1);
	  if (ofile0) free(ofile0);
661
	  snd_error("%s " S_swap_channels " temp file %s: %s\n", 
662 663 664 665 666 667
		    (io_err != IO_NO_ERROR) ? io_error_name(io_err) : "can't open",
		    ofile1, 
		    snd_open_strerror());
	  return;
	}
    }
668 669 670 671 672
  else 
    {
      temp_file = false;
      alloc_len = dur;
    }
673

674 675 676 677
  data0 = (mus_float_t **)malloc(sizeof(mus_float_t *));
  data0[0] = (mus_float_t *)calloc(alloc_len, sizeof(mus_float_t)); 
  data1 = (mus_float_t **)malloc(sizeof(mus_float_t *));
  data1[0] = (mus_float_t *)calloc(alloc_len, sizeof(mus_float_t)); 
678 679
  idata0 = data0[0];
  idata1 = data1[0];
680 681
  c0 = init_sample_read_any_with_bufsize(beg, cp0, READ_FORWARD, pos0, alloc_len);
  c1 = init_sample_read_any_with_bufsize(beg, cp1, READ_FORWARD, pos1, alloc_len);
682 683 684

  if (temp_file)
    {
685
      mus_long_t k;
686
      ss->stopped_explicitly = false;
687 688 689
      sampler_set_safe(c0, dur);
      sampler_set_safe(c1, dur);
      for (k = 0; k < dur; k += alloc_len)
690
	{
691 692 693 694 695
	  int j, n, err;
	  j = dur - k;
	  if (j > alloc_len) j = alloc_len;

	  for (n = 0; n < j; n++)
696
	    {
697 698
	      idata0[j] = read_sample(c1);
	      idata1[j] = read_sample(c0);
699
	    }
700 701 702 703 704
	  mus_file_write(ofd0, 0, j - 1, 1, data0);
	  err = mus_file_write(ofd1, 0, j - 1, 1, data1);

	  if (err != MUS_NO_ERROR) break;
	  if (reporting) 
705
	    {
706 707 708 709 710 711 712 713
	      progress_report(cp0, (mus_float_t)((double)k / (double)dur));
	      if (ss->stopped_explicitly) break;
	      if ((cp0->active < CHANNEL_HAS_EDIT_LIST) || 
		  (cp1->active < CHANNEL_HAS_EDIT_LIST))
		{
		  ss->stopped_explicitly = true;
		  break;
		}
714 715 716 717 718 719 720 721 722 723 724 725 726
	    }
	}
      close_temp_file(ofile0, ofd0, hdr0->type, dur * datumb);
      close_temp_file(ofile1, ofd1, hdr1->type, dur * datumb);
      free_file_info(hdr0);
      free_file_info(hdr1);
      if (!(ss->stopped_explicitly))
	{
	  file_change_samples(beg, dur, ofile0, cp0, 0, DELETE_ME, S_swap_channels, cp0->edit_ctr);
	  file_change_samples(beg, dur, ofile1, cp1, 0, DELETE_ME, S_swap_channels, cp1->edit_ctr);
	}
      else
	{
727
	  set_status(sp0, "swap interrupted", false);
728 729 730 731 732 733 734 735
	  ss->stopped_explicitly = false;
	}
      if (ofile0) {free(ofile0); ofile0 = NULL;}
      if (ofile1) {free(ofile1); ofile1 = NULL;}
      if (reporting) finish_progress_report(cp0);
    }
  else 
    {
736 737 738 739 740
      samples_to_vct_with_reader(dur, idata0, c1);
      samples_to_vct_with_reader(dur, idata1, c0);

      change_samples(beg, dur, data0[0], cp0, S_swap_channels, cp0->edit_ctr, -1.0);
      change_samples(beg, dur, data1[0], cp1, S_swap_channels, cp1->edit_ctr, -1.0);
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    }
  swap_marks(cp0, cp1);
  update_graph(cp0);
  update_graph(cp1);
  if (ofile0) free(ofile0);
  if (ofile1) free(ofile1);
  free(data0[0]);
  free(data0);
  free(data1[0]);
  free(data1);
  free_snd_fd(c0);
  free_snd_fd(c1);
}


756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
/* -------- reverse-channel -------- */

mus_float_t previous_sample_value_unscaled_and_unchecked(snd_fd *sf);
mus_float_t previous_sample_value_unscaled(snd_fd *sf);
mus_float_t previous_sample_value_unchecked(snd_fd *sf);

static char *reverse_channel(chan_info *cp, snd_fd *sf, mus_long_t beg, mus_long_t dur, Xen edp, const char *caller, int arg_pos)
{
  snd_info *sp;
  peak_env_info *ep = NULL;
  file_info *hdr = NULL;
  int ofd = 0, datumb = 0, edpos = 0;
  bool section = false, temp_file;
  mus_long_t k, alloc_len;
  char *origin = NULL;
  mus_float_t **data;
  mus_float_t *idata;
  char *ofile = NULL;
  io_error_t io_err = IO_NO_ERROR;

  if ((beg < 0) || (dur <= 0)) return(NULL);
  if (!(is_editable(cp))) return(NULL);
  /* if last was reverse and start/end match, we could just copy preceding edlist entry, or undo/redo etc --
   *   how to tell that this is happening?
   */
  sp = cp->sound;
  edpos = to_c_edit_position(cp, edp, caller, arg_pos);

  if (dur > cp->edits[edpos]->samples) dur = cp->edits[edpos]->samples;
  if (dur > REPORTING_SIZE)
    {
      temp_file = true; 
      alloc_len = REPORTING_SIZE;
      ofile = snd_tempnam();
      hdr = make_temp_header(ofile, snd_srate(sp), 1, dur, caller);
      ofd = open_temp_file(ofile, 1, hdr, &io_err);
      if (ofd == -1)
	{
	  char *str;
	  str = mus_format("%s %s temp file %s: %s\n", 
			    (io_err != IO_NO_ERROR) ? io_error_name(io_err) : "can't open",
			    caller, ofile, 
			    snd_open_strerror());
	  if (ofile) free(ofile);
	  return(str);
	}
      datumb = mus_bytes_per_sample(hdr->sample_type);
    }
  else 
    {
      temp_file = false;
      alloc_len = dur;
    }

  if ((beg == 0) && (dur == cp->edits[edpos]->samples))
    ep = peak_env_copy(cp, true, edpos); /* true -> reversed */
  else 
    {
      ep = peak_env_copy(cp, false, edpos);
      if (ep) 
	{
	  int i, j, sbin, ebin;
	  /* now reverse the selection */
	  sbin = (int)ceil(beg / ep->samps_per_bin);
	  ebin = (int)floor((beg + dur) / ep->samps_per_bin);
	  if (ebin > ep->peak_env_size) ebin = ep->peak_env_size;
	  for (i = sbin, j = ebin - 1; i < j; i++, j--)
	    {
	      mus_float_t min1, max1;
	      min1 = ep->data_min[i];
	      max1 = ep->data_max[i];
	      ep->data_min[i] = ep->data_min[j];
	      ep->data_max[i] = ep->data_max[j];
	      ep->data_min[j] = min1;
	      ep->data_max[j] = max1;
	    }
	  if (sbin > 0) pick_one_bin(ep, sbin - 1, ep->samps_per_bin * (sbin - 1), cp, edpos);
	  if (ebin < ep->peak_env_size) pick_one_bin(ep, ebin, ep->samps_per_bin * ebin, cp, edpos);
	}
      section = true; /* only for reverse_marks below */
    }

  sampler_set_safe(sf, dur);
  data = (mus_float_t **)malloc(sizeof(mus_float_t *));
  data[0] = (mus_float_t *)malloc(alloc_len * sizeof(mus_float_t)); 
  idata = data[0];

#if HAVE_FORTH
  if (dur == cp->edits[edpos]->samples)
845 846
    origin = mus_format("%" print_mus_long PROC_SEP PROC_FALSE " %s", beg, S_reverse_channel);
  else origin = mus_format("%" print_mus_long PROC_SEP "%" print_mus_long " %s", beg, dur, S_reverse_channel);
847 848
#else
  if (dur == cp->edits[edpos]->samples)
849 850
    origin = mus_format("%s" PROC_OPEN "%" print_mus_long PROC_SEP PROC_FALSE, to_proc_name(S_reverse_channel), beg);
  else origin = mus_format("%s" PROC_OPEN "%" print_mus_long PROC_SEP "%" print_mus_long, to_proc_name(S_reverse_channel), beg, dur);
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
#endif

  if (temp_file)
    {
      for (k = 0; k < dur; k += alloc_len)
	{ 
	  int err;
	  mus_long_t kp, kdur;
	  kdur = dur - k;
	  if (kdur > alloc_len) kdur = alloc_len;
	  for (kp = 0; kp < kdur; kp++)
	    idata[kp] = read_sample(sf);
	  err = mus_file_write(ofd, 0, kdur - 1, 1, data);
	  if (err != MUS_NO_ERROR) break;
	}
      close_temp_file(ofile, ofd, hdr->type, dur * datumb);
867
      free_file_info(hdr);
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
      file_change_samples(beg, dur, ofile, cp, 0, DELETE_ME, origin, edpos);
      if (ofile) 
	{
	  free(ofile); 
	  ofile = NULL;
	}
    }
  else 
    {
      mus_long_t n;
      if ((sf->runf == previous_sample_value_unscaled_and_unchecked) ||
	  ((sf->runf == previous_sample_value_unscaled) &&
	   (sf->loc - sf->first >= (dur - 1))))
	{
	  for (n = sf->loc, k = 0; k < dur; k++, n--)
	    idata[k] = sf->data[n];
	}
      else
	{
	  if (sf->runf == previous_sample_value_unchecked)
	    {
	      for (n = sf->loc, k = 0; k < dur; k++, n--)
		idata[k] = sf->data[n] * sf->fscaler;
	    }
	  else
	    {
	      /* beg is begin time of the edit, not where the reverse read starts */
	      /* independent of sf, if edpos is 0, and saved_data is available, and beg+dur < saved_data length, just use it.
	       */
	      mus_float_t **d;
	      if ((sf->runf == previous_sample_value_unscaled) &&
		  (edpos == 0) &&
		  (beg + dur <= cp->edits[0]->samples) &&
		  (d = mus_sound_saved_data(sp->filename)))
		{
		  mus_long_t d2;
		  mus_float_t *dc;

		  dc = d[cp->chan];
		  if (dur & 1) d2 = dur - 1; else d2 = dur;
		  for (n = beg + dur, k = 0; k < d2; )
		    {
		      idata[k++] = dc[n--];
		      idata[k++] = dc[n--];
		    }
		  if (k < dur) idata[k] = dc[n];
		}
	      else
		{
		  for (k = 0; k < dur; k++)
		    idata[k] = read_sample(sf);
		}
	    }
	}
      change_samples(beg, dur, idata, cp, origin, edpos, -1.0);
    }
  if (ep) cp->edits[cp->edit_ctr]->peak_env = ep;
  reverse_marks(cp, (section) ? beg : -1, dur);
  update_graph(cp); 
  free(data[0]);
  free(data);
  if (origin) free(origin);
  return(NULL);
}


void reverse_sound(chan_info *ncp, bool over_selection, Xen edpos, int arg_pos)
{
  sync_state *sc;
  sync_info *si;
  int i, stop_point = 0;
  snd_fd **sfs;
  char *caller;
  snd_info *sp;
  chan_info *cp;

  sp = ncp->sound;
  caller = (char *)((over_selection) ? S_reverse_selection : S_reverse_sound);
  sc = get_sync_state(sp, ncp, 0, over_selection, READ_BACKWARD, edpos, (const char *)caller, arg_pos);
947
  if (!sc) return;
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
  si = sc->si;
  sfs = sc->sfs;

  if (!(ss->stopped_explicitly))
    {
      for (i = 0; i < si->chans; i++)
	{
	  char *errmsg = NULL;
	  mus_long_t dur;
	  cp = si->cps[i];
	  sp = cp->sound;
	  if (over_selection)
	    dur = sc->dur;
	  else dur = to_c_edit_samples(cp, edpos, caller, arg_pos);
	  if (dur == 0) 
	    {
	      sfs[i] = free_snd_fd(sfs[i]); 
	      continue;
	    }
	  
	  errmsg = reverse_channel(cp, sfs[i], si->begs[i], dur, edpos, caller, arg_pos);

	  sfs[i] = free_snd_fd(sfs[i]);
	  if (errmsg)
	    {
	      snd_error_without_format(errmsg);
	      free(errmsg);
	      break;
	    }
	  if (ss->stopped_explicitly) 
	    {
	      stop_point = i;
	      break;
	    }
	}
    }

  if (ss->stopped_explicitly)
    {
      set_status(sp, "reverse stopped", false);
      ss->stopped_explicitly = false;
      for (i = 0; i <= stop_point; i++)
	{
	  cp = si->cps[i];
	  undo_edit(cp, 1);
	}
    }
  free_sync_state(sc);
}




1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
/* -------- src -------- */

typedef struct {
  mus_any *gen;
  snd_fd *sf;
  mus_long_t sample;
  int dir;
} src_state;

static mus_float_t src_input_as_needed(void *arg, int direction) 
{
  src_state *sr = (src_state *)arg;
  snd_fd *sf;
  sf = sr->sf;
  sr->sample++;
  if (direction != sr->dir)
    {
      read_sample_change_direction(sf, (direction == 1) ? READ_FORWARD : READ_BACKWARD);
      sr->dir = direction;
    }
  return(read_sample(sf));
}


1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
static mus_float_t src_input_as_needed_unchanged(void *arg, int direction) 
{
  src_state *sr = (src_state *)arg;
  sr->sample++;
  return(read_sample(sr->sf));
}


static mus_float_t read_sample_input(void *arg, int direction) 
{
  src_state *sr = (src_state *)arg;
  return(read_sample(sr->sf));
}


static src_state *make_src(mus_float_t srate, snd_fd *sf, bool src_change)
1041 1042 1043 1044 1045 1046 1047 1048 1049
{
  src_state *sr;
  if ((sinc_width(ss) > MUS_MAX_CLM_SINC_WIDTH) ||
      (sinc_width(ss) < 0) ||
      (fabs(srate) > MUS_MAX_CLM_SRC))
    return(NULL);
  sr = (src_state *)calloc(1, sizeof(src_state));
  sr->sf = sf;
  if (srate >= 0.0) sr->dir = 1; else sr->dir = -1;          /* if env on src, this will be 0.0 even if env vals are < 0.0 */
1050 1051 1052
  if (src_change)
    sr->gen = mus_make_src(&src_input_as_needed, srate, sinc_width(ss), (void *)sr);
  else sr->gen = mus_make_src(&src_input_as_needed_unchanged, srate, sinc_width(ss), (void *)sr);
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  mus_set_increment(sr->gen, srate);
  sr->sample = 0;
  return(sr);
}


static src_state *free_src(src_state *sr)
{
  mus_free(sr->gen);
  free(sr);
  return(NULL);
}


static int mus_long_t_compare(const void *a, const void *b)
{
  mus_long_t *m1, *m2;
  m1 = (mus_long_t *)a;
  m2 = (mus_long_t *)b;
  if (*m1 < *m2) return(-1);
  if (*m1 == *m2) return(0);
  return(1);
}


1078
mus_float_t next_sample_value_unscaled_and_unchecked(snd_fd *sf);
1079 1080 1081 1082 1083 1084 1085 1086

static char *src_channel_with_error(chan_info *cp, snd_fd *sf, mus_long_t beg, mus_long_t dur, mus_float_t ratio, mus_any *egen, 
				    const char *origin, bool over_selection,
				    bool *clm_err)
{
  snd_info *sp = NULL;
  bool reporting = false;
  bool full_chan;
1087
  mus_float_t **data;
1088 1089 1090
  file_info *hdr = NULL;
  int j, ofd = 0, datumb = 0, err = 0;
  mus_long_t *old_marks = NULL, *new_marks = NULL;
1091
  int cur_marks = 0;
1092 1093
  mus_long_t k;
  char *ofile = NULL;
1094
  mus_float_t *idata;
1095 1096 1097
  io_error_t io_err = IO_NO_ERROR;
  src_state *sr;

1098
  /* fprintf(stderr, "src: %" print_mus_long " %f %s\n", dur, ratio, origin); */
1099

1100
  if ((!egen) && (sf->edit_ctr == cp->edit_ctr))
1101 1102 1103 1104
    {
      if (ratio == 1.0) 
	return(NULL);
      if (ratio == -1.0)
1105
	return(reverse_channel(cp, sf, beg, dur, C_int_to_Xen_integer(sf->edit_ctr), origin, 0));
1106 1107 1108
    }

  sp = cp->sound;
1109
  if (!(is_editable(cp))) return(NULL); /* edit hook result perhaps */
1110

1111
  sr = make_src(ratio, sf, egen);  /* ratio is 0.0 if egen because the envelope is the srate, but it's passed as the "sr-change" arg */
1112
  if (!sr) 
1113 1114 1115 1116
    {
      (*clm_err) = true;
      return(mus_format("invalid src ratio: %f\n", ratio));
    }
1117 1118 1119
  if ((egen) &&
      (mus_phase(egen) < 0.0))
    sr->dir = -1;
1120

1121
  full_chan = ((beg == 0) && (dur == cp->edits[sf->edit_ctr]->samples)); /* not current_samples here! */
1122 1123 1124 1125 1126

  reporting = ((sp) && (dur > REPORTING_SIZE) && (!(cp->squelch_update)));
  if (reporting) start_progress_report(cp);

  ofile = snd_tempnam();
1127
  hdr = make_temp_header(ofile, snd_srate(sp), 1, dur, (char *)origin);
1128 1129 1130
  ofd = open_temp_file(ofile, 1, hdr, &io_err);
  if (ofd == -1)
    {
1131
      return(mus_format("%s %s temp file %s: %s\n", 
1132 1133 1134 1135 1136
			(io_err != IO_NO_ERROR) ? io_error_name(io_err) : "can't open",
			origin, ofile, 
			snd_open_strerror()));
    }

1137 1138 1139
  data = (mus_float_t **)malloc(sizeof(mus_float_t *));
  datumb = mus_bytes_per_sample(hdr->sample_type);

1140 1141 1142
  j = 0;
  ss->stopped_explicitly = false;

1143
  if (!egen)
1144
    {
1145
      if ((ratio == 0.5) && (dur < (1 << 22)))
1146
	{
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	  mus_long_t in_dur, swid2;
	  mus_float_t *in_data;

	  swid2 = 2 * sinc_width(ss);
	  in_dur = dur + 4 + swid2;
	  in_data = (mus_float_t *)calloc(in_dur, sizeof(mus_float_t));
	  samples_to_vct_with_reader(in_dur - swid2, (mus_float_t *)(in_data + swid2), sf);
	  data[0] = mus_src_05(sr->gen, in_data, dur);
	  k = dur * 2 + 1;
	  j = k;
	  free(in_data);
	}
      else
	{
	  if ((ratio == 2.0) && (dur < (1 << 23)))
1162
	    {
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
	      /* make and fill input data, make output data, pass mus_src_20 the input data array, new dur, and sr->gen
	       */
	      mus_long_t in_dur, swid2;
	      mus_float_t *in_data;

	      swid2 = 2 * sinc_width(ss);
	      in_dur = dur + 4 + swid2;
	      in_data = (mus_float_t *)calloc(in_dur, sizeof(mus_float_t));
	      samples_to_vct_with_reader(in_dur - swid2, (mus_float_t *)(in_data + swid2), sf);
	      data[0] = mus_src_20(sr->gen, in_data, dur);
	      k = dur / 2 + 1;
	      if ((dur & 1) != 0) k++; /* ?? */
	      j = k;
	      free(in_data);
1177
	    }
1178
	  else
1179
	    {
1180 1181 1182 1183 1184 1185 1186
	      mus_long_t out_dur;

	      data[0] = (mus_float_t *)malloc(MAX_BUFFER_SIZE * sizeof(mus_float_t)); 
	      idata = data[0];
	      out_dur = ceil(dur / fabs(ratio)) + 1;

	      for (k = 0; k < out_dur; k += MAX_BUFFER_SIZE)
1187
		{
1188 1189 1190 1191 1192 1193 1194
		  mus_long_t kdur;
		  kdur = out_dur - k;
		  if (kdur > MAX_BUFFER_SIZE) kdur = MAX_BUFFER_SIZE;
		  mus_src_to_buffer(sr->gen, &read_sample_input, idata, kdur);

		  err = mus_file_write(ofd, 0, kdur - 1, 1, data);
		  if (err != MUS_NO_ERROR) break;
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
		  if (reporting) 
		    {
		      progress_report(cp, (mus_float_t)((double)(sr->sample) / (double)dur));
		      if (ss->stopped_explicitly) break;
		      if (!(sp->active))
			{
			  ss->stopped_explicitly = true;
			  break;
			}
		    }
		}
1206 1207
	      j = 0;
	      k = out_dur;
1208 1209 1210 1211 1212 1213
	    }
	}
    }
  else
    {
      mus_long_t next_pass;
1214
      mus_long_t cur_mark_sample;
1215 1216 1217
      int cur_mark = 0, cur_new_mark = 0;
      mus_float_t env_val;

1218 1219 1220
      data[0] = (mus_float_t *)malloc(MAX_BUFFER_SIZE * sizeof(mus_float_t)); 
      idata = data[0];

1221 1222 1223 1224 1225 1226 1227
      cur_mark_sample = -1;
      env_val = mus_env(egen); 
      /* envelope case -- have to go by sr->sample, not output sample counter, also check marks */

      if ((cp->edits[cp->edit_ctr]->marks) && 
	  (cp->edits[cp->edit_ctr]->mark_ctr >= 0))
	{
1228
	  int m;
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	  mark **mps;
	  mps = cp->edits[cp->edit_ctr]->marks;
	  cur_marks = cp->edits[cp->edit_ctr]->mark_ctr + 1;
	  new_marks = (mus_long_t *)malloc(cur_marks * sizeof(mus_long_t));
	  old_marks = (mus_long_t *)malloc(cur_marks * sizeof(mus_long_t));
	  for (m = 0; m < cur_marks; m++)
	    {
	      mus_long_t pos;
	      pos = mark_sample(mps[m]);
	      new_marks[m] = -1;
	      if ((env_val >= 0.0) ||
		  (pos < beg) ||
		  (pos > (beg + dur)))
		old_marks[m] = pos;
	      else 
		{
		  old_marks[m] = (dur - pos - 1) + beg; /* moving backwards, so flip marks */
		  cur_new_mark = m;
		}
	    }
	  if ((env_val < 0.0) && (cur_marks > 1))
	    qsort((void *)old_marks, cur_marks, sizeof(mus_long_t), mus_long_t_compare);
	  for (m = 0; m < cur_marks; m++)
	    if (old_marks[m] > beg)
	      {
		cur_mark_sample = old_marks[m];
		cur_mark = m;
		if ((env_val >= 0.0) || (cur_marks <= 1))
		  cur_new_mark = m;
		break;
	      }
	}
      next_pass = sr->sample;
      for (k = 0; sr->sample < dur; k++)
	{
1264
	  idata[j] = ((mus_src(sr->gen, env_val, &src_input_as_needed)));
1265 1266 1267 1268 1269
	  j++;
	  if (j == MAX_BUFFER_SIZE)
	    {
	      err = mus_file_write(ofd, 0, j - 1, 1, data);
	      j = 0;
1270
	      if (err != MUS_NO_ERROR) break;
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
	      if (reporting) 
		{
		  progress_report(cp, (mus_float_t)((double)(sr->sample) / (double)dur));
		  if (ss->stopped_explicitly) break;
		  if (!(sp->active))
		    {
		      ss->stopped_explicitly = true;
		      break;
		    }
		}
	    }
	  if (next_pass != sr->sample)             /* tick env forward dependent on sr->sample */
	    {
	      mus_long_t jj, idiff;
	      idiff = sr->sample - next_pass;
	      next_pass = sr->sample;
	      if ((new_marks) && 
		  (cur_mark_sample != -1) && 
		  (next_pass >= (cur_mark_sample - beg))) 
		{
		  /* not '==' because sr->sample can be incremented by more than 1 */
		  new_marks[cur_new_mark] = k + beg;
		  cur_mark++;
		  if (env_val >= 0.0) cur_new_mark++; else cur_new_mark--;
		  if (cur_mark < cur_marks)
		    cur_mark_sample = old_marks[cur_mark];
		  else cur_mark_sample = -1;
		}
1299 1300
	      env_val = mus_env(egen);
	      for (jj = 1; jj < idiff; jj++) 
1301 1302 1303 1304 1305 1306
		env_val = mus_env(egen);
	    }
	}
    }

  if (reporting) finish_progress_report(cp);
1307
  free_src(sr);
1308 1309
  if ((!(ss->stopped_explicitly)) && (j > 0)) 
    mus_file_write(ofd, 0, j - 1, 1, data);
1310

1311
  close_temp_file(ofile, ofd, hdr->type, k * datumb);
1312
  free_file_info(hdr);
1313 1314 1315 1316 1317

  if (!(ss->stopped_explicitly))
    {
      char *new_origin = NULL;
      /* egen null -> use ratio, else env, if dur=samples #f */
1318
      if (!egen)
1319 1320 1321 1322
	{

#if HAVE_FORTH
	  if (dur == cp->edits[sf->edit_ctr]->samples)
1323 1324
	    new_origin = mus_format("%.4f" PROC_SEP "%" print_mus_long PROC_SEP PROC_FALSE " %s", ratio, beg, S_src_channel);
	  else new_origin = mus_format("%.4f" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long " %s", ratio, beg, dur, S_src_channel);
1325 1326
#else
	  if (dur == cp->edits[sf->edit_ctr]->samples)
1327 1328
	    new_origin = mus_format("%s" PROC_OPEN "%.4f" PROC_SEP "%" print_mus_long PROC_SEP PROC_FALSE, to_proc_name(S_src_channel), ratio, beg);
	  else new_origin = mus_format("%s" PROC_OPEN "%.4f" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long, to_proc_name(S_src_channel), ratio, beg, dur);
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
#endif
	}
      else
	{
	  mus_float_t base;
	  char *envstr;
	  env *newe;
	  base = mus_increment(egen);
	  newe = make_envelope_with_offset_and_scaler(mus_data(egen), mus_env_breakpoints(egen) * 2, mus_offset(egen), mus_scaler(egen));
	  envstr = env_to_string(newe);

#if HAVE_FORTH
	  if (base == 1.0)
	    {
	      if (dur == cp->edits[sf->edit_ctr]->samples)
1344 1345
		new_origin = mus_format("%s" PROC_SEP "%" print_mus_long PROC_SEP PROC_FALSE " %s", envstr, beg, S_src_channel);
	      else new_origin = mus_format("%s" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long " %s", envstr, beg, dur, S_src_channel);
1346
	    }
1347
	  else new_origin = mus_format("%s :base %.4f :end %" print_mus_long " %s %" print_mus_long PROC_SEP "%" print_mus_long " %s", envstr, base, dur, S_make_env, beg, dur, S_src_channel);
1348 1349 1350 1351
#else
	  if (base == 1.0)
	    {
	      if (dur == cp->edits[sf->edit_ctr]->samples)
1352 1353
		new_origin = mus_format("%s" PROC_OPEN "%s" PROC_SEP "%" print_mus_long PROC_SEP PROC_FALSE, to_proc_name(S_src_channel), envstr, beg);
	      else new_origin = mus_format("%s" PROC_OPEN "%s" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long, to_proc_name(S_src_channel), envstr, beg, dur);
1354
	    }
1355
	  else new_origin = mus_format("%s" PROC_OPEN BPAREN "%s" PROC_OPEN "%s" PROC_SEP ":base" PROC_SEP "%.4f" PROC_SEP ":end" PROC_SEP "%" print_mus_long ")" PROC_SEP "%" print_mus_long PROC_SEP "%" print_mus_long, 
1356
				       to_proc_name(S_make_env), to_proc_name(S_src_channel), envstr, base, dur, beg, dur);
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
#endif
	  if (envstr) free(envstr);
	  free_env(newe);
	}

      if (!full_chan)
	{
	  /* here we need delete followed by insert since dur is probably different */
	  if (k == dur)
	    file_change_samples(beg, dur, ofile, cp, 0, DELETE_ME, new_origin, sf->edit_ctr);
	  else
	    {
	      delete_samples(beg, dur, cp, sf->edit_ctr);
	      file_insert_samples(beg, k, ofile, cp, 0, DELETE_ME, new_origin, cp->edit_ctr);
	      if (over_selection)
		reactivate_selection(cp, beg, beg + k); /* backwards compatibility */
	      backup_edit_list(cp);
	      ripple_marks(cp, 0, 0);
	    }
	  update_graph(cp);
	}
      else file_override_samples(k, ofile, cp, 0, DELETE_ME, new_origin);

      if (new_origin) free(new_origin);

      /* not file_change_samples because that would not necessarily change the current file length */
      if (cp->edits[cp->edit_ctr]->marks)
	{
1385
	  if (!egen)
1386 1387 1388 1389 1390 1391 1392 1393 1394
	    src_marks(cp, ratio, dur, k, beg, full_chan);
	  else
	    {
	      if (new_marks) 
		reset_marks(cp, cur_marks, new_marks, beg + dur, (k - dur), full_chan);
	    }
	}

      /* if possible, copy the previous amp env and change the samps_per_bin to reflect ratio */
1395
      if ((full_chan) && (!egen) &&          /* just ratio -- egen is freed by caller */
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
	  (!(cp->edits[cp->edit_ctr]->peak_env)))   /* can this happen? */
	{
	  peak_env_info *ep;
	  ep = cp->edits[sf->edit_ctr]->peak_env; /* previous peak env (sf is freed by caller) */
	  if (ep)
	    {
	      mus_float_t bratio;
	      int iratio;
	      bratio = ep->samps_per_bin / fabs(ratio);
	      iratio = (int)bratio;
	      if ((bratio - iratio) < .001)
		{
		  peak_env_info *new_ep;
		  new_ep = copy_peak_env_info(ep, (ratio < 0.0)); /* might return NULL if ep but not ep->completed */
		  if (new_ep)
		    {
		      new_ep->samps_per_bin = iratio;
		      cp->edits[cp->edit_ctr]->peak_env = new_ep;
		    }
		}
	    }
	}

      update_graph(cp);
    }
  else
    {
1423
      set_status(sp, "src interrupted", false);
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
      /* should we remove the temp file here? */
      ss->stopped_explicitly = false;
    }

  if (old_marks) free(old_marks);
  old_marks = NULL;
  if (new_marks) free(new_marks);
  new_marks = NULL;
  free(ofile); 
  ofile = NULL;
  free(data[0]);
  free(data);
  return(NULL);
}


void src_env_or_num(chan_info *cp, env *e, mus_float_t ratio, bool just_num, 
1441
		    const char *origin, bool over_selection, mus_any *gen, Xen edpos, int arg_pos)
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
{
  snd_info *sp = NULL;
  sync_state *sc;
  sync_info *si;
  snd_fd **sfs;
  int i;
  mus_long_t scdur;
  int stop_point = 0;
  char *errmsg = NULL;

1452
  if ((!just_num) && (!e) && (!gen)) return;
1453 1454 1455 1456 1457 1458 1459 1460 1461
  if ((just_num) && (ratio == 0.0)) return;

  /* get envelope or src ratio */
  sp = cp->sound;
  /* get current syncd chans */
  sc = get_sync_state(sp, cp, 0, over_selection, 
		      (ratio < 0.0) ? READ_BACKWARD : READ_FORWARD, /* 0->beg, 0->over_selection (ratio = 0.0 if from enved) */ 
		      edpos,
		      origin, arg_pos);      
1462
  if (!sc) return;
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
  si = sc->si;
  sfs = sc->sfs;
  scdur = sc->dur;

  if (!(ss->stopped_explicitly))
    {
      for (i = 0; i < si->chans; i++)
	{
	  mus_long_t dur;
	  mus_any *egen = NULL;
	  bool clm_err = false;
	  cp = si->cps[i];
	  if (scdur == 0) 
	    dur = to_c_edit_samples(cp, edpos, origin, arg_pos); 
	  else dur = scdur;
	  if (dur == 0) 
	    {
	      sfs[i] = free_snd_fd(sfs[i]); 
	      continue;
	    }
	  if (!just_num)
	    {
	      if (e)
1486
		egen = mus_make_env(e->data, e->pts, 1.0, 0.0, e->base, 0.0, dur - 1, NULL);
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
	      else egen = gen;
	      if (egen) ratio = 0.0;            /* added 14-Mar-01 otherwise the envelope is an offset? */
	    }
	  errmsg = src_channel_with_error(cp, sfs[i], si->begs[i], dur, ratio, egen, origin, over_selection, &clm_err);
	  if (egen)
	    {
	      if (e) 
		mus_free(egen);
	      else mus_reset(gen);
	    }
	  if (errmsg) break;
	  if (ss->stopped_explicitly) 
	    {
	      stop_point = i;
	      break;
	    }
	}
    }
  if (ss->stopped_explicitly)
    {
      /* clean up and undo all edits up to stop_point */
      ss->stopped_explicitly = false;
      for (i = 0; i <= stop_point; i++)
	{
	  cp = si->cps[i];
	  undo_edit(cp, 1);
	}
    }
  for (i = 0; i < si->chans; i++) 
    free_snd_fd(sfs[i]);
  free_sync_state(sc);
  if (errmsg)
    snd_error_without_format(errmsg);
}


1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
static mus_float_t input_as_needed(void *arg, int dir) 
{
  return(mus_readin((mus_any *)arg));
}


void src_file(const char *file, double ratio)
{
  mus_any **rds, **srcs;
  char *temp_out;
  const char *comment;
1534 1535 1536
  int k, chan, chans, width, out_fd, buffer_size;
  mus_sample_t sample_type;
  mus_header_t header_type;
1537 1538
  mus_long_t samp, old_samps, new_samps;
  mus_float_t old_srate, new_srate;
1539
  mus_float_t **obufs;
1540 1541 1542 1543 1544 1545

  old_srate = mus_srate();
  new_srate = mus_sound_srate(file); /* need have no connection with previous CLM srate setting */
  mus_set_srate(new_srate);

  chans = mus_sound_chans(file);
1546
  sample_type = mus_sound_sample_type(file);
1547 1548 1549
  header_type = mus_sound_header_type(file);
  comment = mus_sound_comment(file);
  buffer_size = mus_file_buffer_size();
1550
  old_samps = mus_sound_framples(file);
1551 1552 1553 1554 1555 1556
  new_samps = old_samps / ratio;  /* old-srate/new-srate in-coming */

  width = sinc_width(ss);
  if (width < 32) width = 32;

  temp_out = snd_tempnam();
1557
  out_fd = mus_sound_open_output(temp_out, new_srate, chans, sample_type, header_type, comment);
1558 1559 1560

  srcs = (mus_any **)malloc(chans * sizeof(mus_any *));
  rds = (mus_any **)malloc(chans * sizeof(mus_any *));
1561
  obufs = (mus_float_t **)malloc(chans * sizeof(mus_float_t *));
1562 1563 1564 1565 1566

  for (chan = 0; chan < chans; chan++)
    {
      rds[chan] = mus_make_readin(file, chan, 0, 1);
      srcs[chan] = mus_make_src(NULL, ratio, width, (void *)rds[chan]);
1567
      obufs[chan] = (mus_float_t *)malloc(buffer_size * sizeof(mus_float_t));
1568 1569 1570 1571 1572
    }

  for (k = 0, samp = 0; samp < new_samps; samp++)
    {
      for (chan = 0; chan < chans; chan++)
1573
	obufs[chan][k] = (mus_src(srcs[chan], 0.0, &input_as_needed));
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
      k++;
      if (k == buffer_size)
	{
	  mus_sound_write(out_fd, 0, buffer_size - 1, chans, obufs);
	  k = 0;
	}
    }
  if (k > 0) 
    mus_sound_write(out_fd, 0, k - 1, chans, obufs);

1584
  mus_sound_close_output(out_fd, new_samps * chans * mus_bytes_per_sample(sample_type));
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
  mus_sound_forget(file);

  for (chan = 0; chan < chans; chan++)
    {
      free(obufs[chan]);
      mus_free(srcs[chan]);
      mus_free(rds[chan]);
    }
  free(obufs);
  free(srcs);
  free(rds);

  move_file(temp_out, file);
  free(temp_out);
  mus_set_srate(old_srate);
}


1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
/* FIR filtering */

static mus_float_t *get_filter_coeffs(int order, env *e)
{
  /* interpret e as frequency response */
  mus_float_t *a = NULL, *fdata;
  if (!e) return(NULL);

  /* get the frequency envelope and design the FIR filter */
  fdata = sample_linear_env(e, order);
  if (!fdata) return(NULL);
1614
  a = (mus_float_t *)calloc(order + 1, sizeof(mus_float_t));
1615 1616 1617 1618 1619 1620 1621 1622

  mus_make_fir_coeffs(order, fdata, a);

  free(fdata);
  return(a);
}


1623
void display_frequency_response(env *e, axis_info *ap, graphics_context *gax, int order, bool dBing)
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
{
  /* not cp->min_dB here -- this is sound panel related which refers to ss->min_dB */
  mus_float_t *coeffs = NULL;
  int height, width, i, pts, x1, y1;
  mus_float_t samps_per_pixel, invpts, resp, pix;
  int fsize, j;
  mus_float_t step, fx;
  mus_float_t *rl, *im;

  if (order & 1) order++;

  height = (ap->y_axis_y1 - ap->y_axis_y0);
  width = (ap->x_axis_x1 - ap->x_axis_x0);
  pts = order * 4;
  if (pts > width) pts = width;
  if (pts <= 0) pts = 1;
  invpts = 1.0 / (mus_float_t)pts;
  samps_per_pixel = (mus_float_t)(ap->x_axis_x1 - ap->x_axis_x0) * invpts;

  coeffs = get_filter_coeffs(order, e);
  if (!coeffs) return;
1645

1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
  fsize = 2 * snd_to_int_pow2((pts > order) ? pts : order); /* *2 for 1/2 frqs */
  rl = (mus_float_t *)calloc(fsize, sizeof(mus_float_t));
  im = (mus_float_t *)calloc(fsize, sizeof(mus_float_t));
  for (i = 0, j = order - 1; i < order / 2; i++, j -= 2) rl[j] = coeffs[i]; /* by 2 from 1 for 1/2 bins */

  mus_fft(rl, im, fsize, -1);

  resp = 2 * rl[0];
  if (dBing)
    y1 = (int)(ap->y_axis_y0 + (min_dB(ss) - in_dB(min_dB(ss), ss->lin_dB, resp)) * height / min_dB(ss));
  else y1 = (int)(ap->y_axis_y0 + resp * height);
  x1 = ap->x_axis_x0;
  step = (mus_float_t)(fsize - 1) / (4 * (mus_float_t)pts); /* fsize-1 since we got 1 already, *4 due to double size fft */
  for (i = 1, pix = x1, fx = step; 
       i < pts; 
       i++, pix += samps_per_pixel, fx += step)
    {
      int fxi, x0, y0;
      x0 = x1;
      y0 = y1;
      x1 = (int)(pix);
      fxi = (int)fx;
      resp = 2 * (rl[fxi] + (fx - fxi) * (rl[fxi + 1] - rl[fxi]));
      if (resp < 0.0) resp = -resp;
      if (dBing)
	y1 = (int)(ap->y_axis_y0 + (min_dB(ss) - in_dB(min_dB(ss), ss->lin_dB, resp)) * height / min_dB(ss));
      else y1 = (int)(ap->y_axis_y0 + resp * height);
      draw_line(gax, x0, y0, x1, y1);
    }

  free(rl);
  free(im);
  free(coeffs);
}


static char *clm_channel(chan_info *cp, mus_any *gen, mus_long_t beg, mus_long_t dur, int edpos, mus_long_t overlap, const char *origin)
{
  /* calls gen over cp[beg for dur] data, replacing. */
  snd_info *sp;
  file_info *hdr = NULL;
1687
  int j = 0, ofd = 0, datumb = 0;
1688
  bool temp_file;
1689 1690 1691
  mus_long_t k, alloc_len;
  mus_float_t **data;
  mus_float_t *idata;
1692 1693
  char *ofile = NULL;
  snd_fd *sf;
1694
  mus_float_t (*runf)(mus_any *gen, mus_float_t arg1, mus_float_t arg2);
1695 1696 1697

  if ((beg < 0) || ((dur + overlap) <= 0)) return(NULL);
  sp = cp->sound;
1698
  if (!(is_editable(cp))) return(NULL);
1699 1700

  sf = init_sample_read_any(beg, cp, READ_FORWARD, edpos);
1701
  if (!sf)
1702
    return(mus_format("%s can't read %s[%d] channel data!", S_clm_channel, sp->short_filename, cp->chan));
1703
  runf = mus_run_function(gen);
1704

1705
  if ((dur + overlap) > REPORTING_SIZE)
1706 1707
    {
      io_error_t io_err = IO_NO_ERROR;
1708
      alloc_len = REPORTING_SIZE;
1709 1710
      temp_file = true; 
      ofile = snd_tempnam();
1711
      hdr = make_temp_header(ofile, snd_srate(sp), 1, dur + overlap, S_clm_channel);
1712 1713 1714 1715
      ofd = open_temp_file(ofile, 1, hdr, &io_err);
      if (ofd == -1)
	{
	  free_snd_fd(sf); 
1716
	  return(mus_format("%s %s temp file %s: %s\n", 
1717 1718 1719 1720
			    (io_err != IO_NO_ERROR) ? io_error_name(io_err) : "can't open",
			    S_clm_channel, ofile, 
			    snd_open_strerror()));
	}
1721
      datumb = mus_bytes_per_sample(hdr->sample_type);
1722
    }
1723 1724 1725 1726 1727 1728 1729 1730
  else 
    {
      temp_file = false;
      alloc_len = dur + overlap;
    }

  data = (mus_float_t **)malloc(sizeof(mus_float_t *));
  data[0] = (mus_float_t *)calloc(alloc_len, sizeof(mus_float_t)); 
1731
  idata = data[0];
1732

1733 1734
  if (temp_file)
    {
1735 1736
      sampler_set_safe(sf, dur);
      for (k = 0; k < dur; k += alloc_len)
1737
	{
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
	  int n, err;
	  j = dur - k;
	  if (j > alloc_len) j = alloc_len;

	  for (n = 0; n < j; n++)
	    idata[n] = runf(gen, read_sample(sf), 0.0);

	  err = mus_file_write(ofd, 0, j - 1, 1, data);
	  j = 0;
	  if (err != MUS_NO_ERROR) break;
1748 1749 1750 1751
	}
    }
  else
    {
1752
      mus_float_t (*runf1)(mus_any *gen, mus_float_t arg);
1753
      samples_to_vct_with_reader(dur, idata, sf);
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765

      runf1 = mus_run1_function(gen);
      if (runf1)
	{
	  for (k = 0; k < dur; k++)
	    idata[k] = runf1(gen, idata[k]);
	}
      else
	{
	  for (k = 0; k < dur; k++)
	    idata[k] = runf(gen, idata[k], 0.0);
	}
1766 1767
      j = (int)dur;
    }
1768 1769

  if (overlap > 0)
1770
    {
1771 1772 1773 1774 1775 1776
      snd_fd *fd;
      fd = init_sample_read_any_with_bufsize(beg + dur, cp, READ_FORWARD, edpos, overlap);
      for (k = 0; k < overlap; k++)