gstlal_itacac.c 66.6 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 26 27 28 29 30 31 32 33 34 35
/*
 * An inspiral trigger, autocorrelation chisq, and coincidence (itacac) element
 *
 * Copyright (C) 2011 Chad Hanna, Kipp Cannon, 2018 Cody Messick, Alex Pace
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */


/*
 * ========================================================================
 *
 *                                  Preamble
 *
 * ========================================================================
 */


/*
 * stuff from C library, glib/gstreamer
 */


36
#include <complex.h>
37
#include <glib.h>
38
#include <gmodule.h>
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
#include <gst/gst.h>
#include <gst/base/gstaggregator.h>
#include <gst/controller/controller.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>

/*
 * our own stuff
 */

#include <gstlal/gstlal.h>
#include <gstlal/gstlal_debug.h>
#include <gstlal_itacac.h>
#include <gstlal/gstlal_peakfinder.h>
#include <gstlal/gstaudioadapter.h>
#include <gstlal/gstlal_tags.h>
#include <gstlal/gstlal_autocorrelation_chi2.h>
#include <gstlal_snglinspiral.h>

/*
 * ============================================================================
 *
 *                           GStreamer Boiler Plate
 *
 * ============================================================================
 */


#define GST_CAT_DEFAULT gstlal_itacac_debug
GST_DEBUG_CATEGORY_STATIC(GST_CAT_DEFAULT);

G_DEFINE_TYPE(
	GSTLALItacacPad,
	gstlal_itacac_pad,
	GST_TYPE_AGGREGATOR_PAD
);

G_DEFINE_TYPE_WITH_CODE(
	GSTLALItacac,
	gstlal_itacac,
	GST_TYPE_AGGREGATOR,
	GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, "lal_itacac", 0, "lal_itacac debug category")
);

/* 
 * Static pad templates, needed to make instances of GstAggregatorPad
 */

#define CAPS \
	"audio/x-raw, " \
	"format = (string) { " GST_AUDIO_NE(Z64) ", " GST_AUDIO_NE(Z128) ", " GST_AUDIO_NE(F64) "}, "\
	"rate = " GST_AUDIO_RATE_RANGE ", " \
	"channels = " GST_AUDIO_CHANNELS_RANGE ", " \
	"layout = (string) interleaved, " \
	"channel-mask = (bitmask) 0"

static GstStaticPadTemplate src_templ = GST_STATIC_PAD_TEMPLATE(
	"src",
	GST_PAD_SRC,
	GST_PAD_ALWAYS,
	GST_STATIC_CAPS("application/x-lal-snglinspiral")
);

static GstStaticPadTemplate sink_templ = GST_STATIC_PAD_TEMPLATE(
	"sink%d",
	GST_PAD_SINK,
	GST_PAD_REQUEST,
	GST_STATIC_CAPS(CAPS)
);

#define DEFAULT_SNR_THRESH 5.5
112
#define DEFAULT_COINC_THRESH 5
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

/*
 * ========================================================================
 *
 *                             Utility Functions
 *
 * ========================================================================
 */

static unsigned autocorrelation_channels(const GSTLALItacacPad *itacacpad) {
	return gstlal_autocorrelation_chi2_autocorrelation_channels(itacacpad->autocorrelation_matrix);
}

static unsigned autocorrelation_length(GSTLALItacacPad *itacacpad) {
	// The autocorrelation length should be the same for all of the detectors, so we can just use the first
	return gstlal_autocorrelation_chi2_autocorrelation_length(itacacpad->autocorrelation_matrix);
}

static guint64 output_num_samps(GSTLALItacacPad *itacacpad) {
	return (guint64) itacacpad->n;
}

static guint64 output_num_bytes(GSTLALItacacPad *itacacpad) {
	return (guint64) output_num_samps(itacacpad) * itacacpad->adapter->unit_size;
}

static int reset_time_and_offset(GSTLALItacac *itacac) {
140 141
	// NOTE This should only get called when itacac is first starting up,
	// there is an assert that guarantees this
142
	itacac->next_output_offset = 0;
143 144 145 146 147 148 149 150 151 152 153 154 155
	itacac->next_output_timestamp = GST_CLOCK_TIME_NONE;
        return 0;
}

static guint gst_audioadapter_available_samples(GstAudioAdapter *adapter) {
        guint size;
        g_object_get(adapter, "size", &size, NULL);
        return size;
}

static void free_bank(GSTLALItacacPad *itacacpad) {
	g_free(itacacpad->bank_filename);
	itacacpad->bank_filename = NULL;
156
	gstlal_snglinspiral_array_free(itacacpad->bankarray);
157 158 159 160 161
	itacacpad->bankarray = NULL;
}

static void update_peak_info_from_autocorrelation_properties(GSTLALItacacPad *itacacpad) {
	// FIXME Need to make sure that itacac can run without autocorrelation matrix
162
	if(itacacpad->maxdata && itacacpad->tmp_maxdata && itacacpad->autocorrelation_matrix) {
163
		itacacpad->maxdata->pad = itacacpad->tmp_maxdata->pad = autocorrelation_length(itacacpad) / 2;
164 165
		free(itacacpad->snr_mat);
		free(itacacpad->tmp_snr_mat);
166 167 168 169 170 171 172 173 174 175 176

		itacacpad->snr_mat = calloc(autocorrelation_channels(itacacpad) * autocorrelation_length(itacacpad), itacacpad->maxdata->unit);
		itacacpad->tmp_snr_mat = calloc(autocorrelation_channels(itacacpad) * autocorrelation_length(itacacpad), itacacpad->tmp_maxdata->unit);

		//
		// Each row is one sample point of the snr time series with N
		// columns for N channels. Assumes proper packing to go from real to complex.
		// FIXME assumes single precision
		//
		itacacpad->snr_matrix_view = gsl_matrix_complex_float_view_array((float *) itacacpad->snr_mat, autocorrelation_length(itacacpad), autocorrelation_channels(itacacpad));
		itacacpad->tmp_snr_matrix_view = gsl_matrix_complex_float_view_array((float *) itacacpad->tmp_snr_mat, autocorrelation_length(itacacpad), autocorrelation_channels(itacacpad));
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        }
}

/*
 * ============================================================================
 *
 *                                 Events
 *
 * ============================================================================
 */

static gboolean taglist_extract_string(GstObject *object, GstTagList *taglist, const char *tagname, gchar **dest)
{
	if(!gst_tag_list_get_string(taglist, tagname, dest)) {
		GST_WARNING_OBJECT(object, "unable to parse \"%s\" from %" GST_PTR_FORMAT, tagname, taglist);
		return FALSE;
	}
        return TRUE;
}

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
static gboolean get_instrument_pad_pointer(GSTLALItacac *itacac, GSTLALItacacPad *itacacpad)
{
	gboolean result = TRUE;
	if(strcmp(itacacpad->instrument, "H1") == 0)
		itacac->H1_itacacpad = itacacpad;
	else if(strcmp(itacacpad->instrument, "K1") == 0)
		itacac->K1_itacacpad = itacacpad;
	else if(strcmp(itacacpad->instrument, "L1") == 0)
		itacac->L1_itacacpad = itacacpad;
	else if(strcmp(itacacpad->instrument, "V1") == 0)
		itacac->V1_itacacpad = itacacpad;
	else {
		GST_ERROR_OBJECT(itacacpad, "pad has unknown detector, %s", itacacpad->instrument);
		result = FALSE;
	}
	return result;
}
214 215 216 217 218

static gboolean setcaps(GstAggregator *agg, GstAggregatorPad *aggpad, GstEvent *event) {
	GSTLALItacac *itacac = GSTLAL_ITACAC(agg);
	GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(aggpad);
	GstCaps *caps;
219 220 221
	guint width = 0;
	gstlal_peak_type_specifier peak_type = 0;
	gint rate;
222 223 224 225 226 227 228

	//
	// Update element metadata
	//
	gst_event_parse_caps(event, &caps);
	GstStructure *str = gst_caps_get_structure(caps, 0);
	const gchar *format = gst_structure_get_string(str, "format");
229
	gst_structure_get_int(str, "rate", &rate);
230 231 232

	if(!strcmp(format, GST_AUDIO_NE(Z64))) {
		width = sizeof(float complex);
233
		peak_type = GSTLAL_PEAK_COMPLEX;
234 235
	} else if(!strcmp(format, GST_AUDIO_NE(Z128))) {
		width = sizeof(double complex);
236
		peak_type = GSTLAL_PEAK_DOUBLE_COMPLEX;
237 238 239
	} else
		GST_ERROR_OBJECT(itacac, "unsupported format %s", format);

240 241 242 243 244 245 246 247 248 249 250 251 252
	g_mutex_lock(&itacac->caps_lock);
	if(itacac->rate == 0) {
		itacac->rate = (guint) rate;
		itacac->peak_type = peak_type;
	} else {
		g_assert(itacac->rate == (guint) rate);
		g_assert(itacac->peak_type == peak_type);
	}
	g_mutex_unlock(&itacac->caps_lock);

	g_object_set(itacacpad->adapter, "unit-size", itacac->channels * width, NULL);
	itacacpad->chi2 = calloc(itacac->channels, width);
	itacacpad->tmp_chi2 = calloc(itacac->channels, width);
253

254
	if(itacacpad->maxdata)
255 256
		gstlal_peak_state_free(itacacpad->maxdata);
	
257
	if(itacacpad->tmp_maxdata)
258 259
		gstlal_peak_state_free(itacacpad->tmp_maxdata);

260 261
	itacacpad->maxdata = gstlal_peak_state_new(itacac->channels, itacac->peak_type);
	itacacpad->tmp_maxdata = gstlal_peak_state_new(itacac->channels, itacac->peak_type);
262 263 264 265

	// This should be called any time the autocorrelation property is updated 
	update_peak_info_from_autocorrelation_properties(itacacpad);

266 267 268 269 270 271 272 273 274
	// Set up data_container struct
	// FIXME Can simplify this process by reworking audioadapter to provide
	// the information currently contained duration_..._matrix
	itacacpad->data->data = g_malloc(output_num_bytes(itacacpad) + itacacpad->adapter->unit_size * (2 * itacacpad->maxdata->pad));
	// The largest number of disjoint sets of non-gap-samples (large enough
	// to produce a trigger) that we could have in a given trigger window
	guint max_number_disjoint_sets_in_trigger_window = itacac->rate / (2 * itacacpad->maxdata->pad) + 1;
	itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix = gsl_matrix_calloc(max_number_disjoint_sets_in_trigger_window, 4);

275 276 277 278 279 280 281 282
	return GST_AGGREGATOR_CLASS(gstlal_itacac_parent_class)->sink_event(agg, aggpad, event);
}

static gboolean sink_event(GstAggregator *agg, GstAggregatorPad *aggpad, GstEvent *event)
{
	GSTLALItacac *itacac = GSTLAL_ITACAC(agg);
	GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(aggpad);
	gboolean result = TRUE;
283
	GList *padlist;
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

	GST_DEBUG_OBJECT(aggpad, "Got %s event on sink pad", GST_EVENT_TYPE_NAME (event));

	switch (GST_EVENT_TYPE(event)) {
		case GST_EVENT_CAPS:
		{
			return setcaps(agg, aggpad, event);
		}
		case GST_EVENT_TAG:
		{
			GstTagList *taglist;
			gchar *instrument, *channel_name;
			gst_event_parse_tag(event, &taglist);
			result = taglist_extract_string(GST_OBJECT(aggpad), taglist, GSTLAL_TAG_INSTRUMENT, &instrument);
			result &= taglist_extract_string(GST_OBJECT(aggpad), taglist, GSTLAL_TAG_CHANNEL_NAME, &channel_name);
			if(result) {
				GST_DEBUG_OBJECT(aggpad, "found tags \"%s\"=\"%s\", \"%s\"=\"%s\"", GSTLAL_TAG_INSTRUMENT, instrument, GSTLAL_TAG_CHANNEL_NAME, channel_name);
				g_free(itacacpad->instrument);
				itacacpad->instrument = instrument;
				g_free(itacacpad->channel_name);
				itacacpad->channel_name = channel_name;
				g_mutex_lock(&itacacpad->bank_lock);
306 307
				gstlal_set_channel_in_snglinspiral_array(itacacpad->bankarray, (int) itacac->channels, itacacpad->channel_name);
				gstlal_set_instrument_in_snglinspiral_array(itacacpad->bankarray, (int) itacac->channels, itacacpad->instrument);
308
				g_mutex_unlock(&itacacpad->bank_lock);
309
				result &= get_instrument_pad_pointer(itacac, itacacpad);
310 311 312 313 314 315
			}
                        break;

		}
		case GST_EVENT_EOS:
		{
316
			itacacpad->EOS = TRUE;
317
			itacac->EOS = TRUE;
318 319
			for(padlist = GST_ELEMENT(agg)->sinkpads; padlist != NULL; padlist = padlist->next)
				itacac->EOS = GSTLAL_ITACAC_PAD(padlist->data)->EOS && itacac->EOS;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
			break;
		}
		default:
			break;
	}
	if(!result) {
		gst_event_unref(event);
	} else {
		result = GST_AGGREGATOR_CLASS(gstlal_itacac_parent_class)->sink_event(agg, aggpad, event);
	}
	return result;
}

/*
 * ============================================================================
 *
336
 *                           Properties and Meta
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
 *
 * ============================================================================
 */

enum padproperty {
	ARG_N = 1,
	ARG_SNR_THRESH,
	ARG_BANK_FILENAME,
	ARG_SIGMASQ,
	ARG_AUTOCORRELATION_MATRIX,
	ARG_AUTOCORRELATION_MASK
};

static void gstlal_itacac_pad_set_property(GObject *object, enum padproperty id, const GValue *value, GParamSpec *pspec)
{
352
	GSTLALItacac *itacac = GSTLAL_ITACAC(gst_pad_get_parent(GST_PAD(object)));
353
	GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(object);
354 355
	guint channels;
	GstClockTimeDiff difftime;
356 357 358 359 360 361 362 363 364 365 366 367 368 369

	GST_OBJECT_LOCK(itacacpad);

	switch(id) {
	case ARG_N:
		itacacpad->n = g_value_get_uint(value);
		break;

	case ARG_SNR_THRESH:
		itacacpad->snr_thresh = g_value_get_double(value);
		break;

	case ARG_BANK_FILENAME:
		g_mutex_lock(&itacacpad->bank_lock);
370
		free_bank(itacacpad);
371
		itacacpad->bank_filename = g_value_dup_string(value);
372 373
		channels = gstlal_snglinspiral_array_from_file(itacacpad->bank_filename, &(itacacpad->bankarray));
		gstlal_set_min_offset_in_snglinspiral_array(itacacpad->bankarray, (gint) channels, &difftime);
374
		if(itacacpad->instrument && itacacpad->channel_name) {
375 376
			gstlal_set_instrument_in_snglinspiral_array(itacacpad->bankarray, (gint) channels, itacacpad->instrument);
			gstlal_set_channel_in_snglinspiral_array(itacacpad->bankarray, (gint) channels, itacacpad->channel_name);
377 378
		}
		g_mutex_unlock(&itacacpad->bank_lock);
379 380 381 382 383 384 385 386 387 388 389

		g_assert(itacac != NULL);
		g_mutex_lock(&itacac->caps_lock);
		if(itacac->channels == 0) {
			itacac->channels = channels;
			itacac->difftime = difftime;
		} else {
			g_assert(itacac->channels == channels);
			g_assert(itacac->difftime == difftime);
		}
		g_mutex_unlock(&itacac->caps_lock);
390 391 392 393
		break;

	case ARG_SIGMASQ:
		g_mutex_lock(&itacacpad->bank_lock);
394
		if(itacacpad->bankarray) {
395
			g_assert(itacac != NULL);
396 397
			gint length;
			double *sigmasq = gstlal_doubles_from_g_value_array(g_value_get_boxed(value), NULL, &length);
398 399
			if((gint) itacac->channels != length)
				GST_ERROR_OBJECT(itacacpad, "vector length (%d) does not match number of templates (%u)", length, itacac->channels);
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
			else
				gstlal_set_sigmasq_in_snglinspiral_array(itacacpad->bankarray, length, sigmasq);
			g_free(sigmasq);
		} else
			GST_WARNING_OBJECT(itacacpad, "must set template bank before setting sigmasq");
		g_mutex_unlock(&itacacpad->bank_lock);
		break;


	case ARG_AUTOCORRELATION_MATRIX:
		g_mutex_lock(&itacacpad->bank_lock);

		if(itacacpad->autocorrelation_matrix)
			gsl_matrix_complex_free(itacacpad->autocorrelation_matrix);

		itacacpad->autocorrelation_matrix = gstlal_gsl_matrix_complex_from_g_value_array(g_value_get_boxed(value)); 

		// This should be called any time caps change too
		update_peak_info_from_autocorrelation_properties(itacacpad);

		//
		// induce norms to be recomputed
		//

		if(itacacpad->autocorrelation_norm) {
			gsl_vector_free(itacacpad->autocorrelation_norm);
			itacacpad->autocorrelation_norm = NULL;
		}

		g_mutex_unlock(&itacacpad->bank_lock);
		break;

        case ARG_AUTOCORRELATION_MASK: 
		g_mutex_lock(&itacacpad->bank_lock);

		if(itacacpad->autocorrelation_mask)
			gsl_matrix_int_free(itacacpad->autocorrelation_mask);

		itacacpad->autocorrelation_mask = gstlal_gsl_matrix_int_from_g_value_array(g_value_get_boxed(value));

		g_mutex_unlock(&itacacpad->bank_lock);
		break;

	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, id, pspec);
		break;
	}

	GST_OBJECT_UNLOCK(itacacpad);
449 450
	if(itacac != NULL)
		gst_object_unref(GST_OBJECT(itacac));
451 452 453 454
}

static void gstlal_itacac_pad_get_property(GObject *object, enum padproperty id, GValue *value, GParamSpec *pspec)
{
455
	GSTLALItacac *itacac = GSTLAL_ITACAC(gst_pad_get_parent(GST_PAD(object)));
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
	GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(object);

	GST_OBJECT_LOCK(itacacpad);

	switch(id) {
	case ARG_N:
		g_value_set_uint(value, itacacpad->n);
		break;

	case ARG_SNR_THRESH:
		g_value_set_double(value, itacacpad->snr_thresh);
		break;

	case ARG_BANK_FILENAME:
		g_mutex_lock(&itacacpad->bank_lock);
		g_value_set_string(value, itacacpad->bank_filename);
		g_mutex_unlock(&itacacpad->bank_lock);
		break;

        case ARG_SIGMASQ:
		g_mutex_lock(&itacacpad->bank_lock);
		if(itacacpad->bankarray) {
478 479
			g_assert(itacac != NULL);
			double sigmasq[itacac->channels];
480
			gint i;
481
			for(i = 0; i < (gint) itacac->channels; i++)
482
				sigmasq[i] = itacacpad->bankarray[i].sigmasq;
483
			g_value_take_boxed(value, gstlal_g_value_array_from_doubles(sigmasq, (gint) itacac->channels));
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
		} else {
			GST_WARNING_OBJECT(itacacpad, "no template bank");
			g_value_take_boxed(value, g_array_sized_new(TRUE, TRUE, sizeof(double), 0));
		}
		g_mutex_unlock(&itacacpad->bank_lock);
		break;

	case ARG_AUTOCORRELATION_MATRIX:
		g_mutex_lock(&itacacpad->bank_lock);
		if(itacacpad->autocorrelation_matrix)
                        g_value_take_boxed(value, gstlal_g_value_array_from_gsl_matrix_complex(itacacpad->autocorrelation_matrix));
                else {
                        GST_WARNING_OBJECT(itacacpad, "no autocorrelation matrix");
			g_value_take_boxed(value, g_array_sized_new(TRUE, TRUE, sizeof(double), 0));
                        }
                g_mutex_unlock(&itacacpad->bank_lock);
                break;

	case ARG_AUTOCORRELATION_MASK:
		g_mutex_lock(&itacacpad->bank_lock);
		if(itacacpad->autocorrelation_mask)
			g_value_take_boxed(value, gstlal_g_value_array_from_gsl_matrix_int(itacacpad->autocorrelation_mask));
		else {
			GST_WARNING_OBJECT(itacacpad, "no autocorrelation mask");
			g_value_take_boxed(value, g_array_sized_new(TRUE, TRUE, sizeof(double), 0));
		}
		g_mutex_unlock(&itacacpad->bank_lock);
		break;

	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID(object, id, pspec);
		break;
	}

	GST_OBJECT_UNLOCK(itacacpad);
519 520
	if(itacac != NULL)
		gst_object_unref(GST_OBJECT(itacac));
521
}
522

523 524 525 526 527 528 529 530 531 532
/*
 * aggregate()
*/ 

static void update_state(GSTLALItacac *itacac, GstBuffer *srcbuf) {
	itacac->next_output_offset = GST_BUFFER_OFFSET_END(srcbuf);
	itacac->next_output_timestamp = GST_BUFFER_PTS(srcbuf) - itacac->difftime;
	itacac->next_output_timestamp += GST_BUFFER_DURATION(srcbuf);
}

533
static GstFlowReturn push_buffer(GstAggregator *agg, GstBuffer *srcbuf) {
534
	GSTLALItacac *itacac = GSTLAL_ITACAC(agg);
535 536 537
	update_state(itacac, srcbuf);

	GST_DEBUG_OBJECT(itacac, "pushing %" GST_BUFFER_BOUNDARIES_FORMAT, GST_BUFFER_BOUNDARIES_ARGS(srcbuf));
538
	return GST_AGGREGATOR_CLASS(gstlal_itacac_parent_class)->finish_buffer(agg, srcbuf);
539 540 541 542 543 544 545 546 547
}

static GstFlowReturn push_gap(GSTLALItacac *itacac, guint samps) {
	GstBuffer *srcbuf = gst_buffer_new();
	GST_BUFFER_FLAG_SET(srcbuf, GST_BUFFER_FLAG_GAP);

	GST_BUFFER_OFFSET(srcbuf) = itacac->next_output_offset;
	GST_BUFFER_OFFSET_END(srcbuf) = itacac->next_output_offset + samps;
	GST_BUFFER_PTS(srcbuf) = itacac->next_output_timestamp + itacac->difftime;
548
	GST_BUFFER_DURATION(srcbuf) = (GstClockTime) gst_util_uint64_scale_int_round(GST_SECOND, samps, (gint) itacac->rate);
549

550
	return gst_aggregator_finish_buffer(GST_AGGREGATOR(itacac), srcbuf);
551 552 553

}

554
static void copy_nongapsamps(GSTLALItacac *itacac, GSTLALItacacPad *itacacpad, guint copysamps, guint peak_finding_length, gint offset_from_trigwindow) {
555 556
	guint data_container_index = 0;
	guint offset_from_copied_data = 0;
557
	guint duration = (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, 0, 0);
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

	//
	// Description of duration_dataoffset_trigwindowoffset_peakfindinglength_matrix
	// First column is duration, or number of samples that we've copied
	// Second column is data offset, so the number of samples that come before the data that was just copied
	// Third column is trigger window offset, the distance in samples from the beginning of the data to the beginning of the trigger window. This number can be negative
	// Fourth column is the peak finding length used by the peakfinder
	//

	// set the columns of the matrix described above
	while(duration != 0) {
		offset_from_copied_data += duration;
		duration = gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, ++data_container_index, 0);
	}
	gsl_matrix_set(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 0, (double) copysamps);
	gsl_matrix_set(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 1, (double) offset_from_copied_data);
	gsl_matrix_set(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 2, (double) offset_from_trigwindow);
	gsl_matrix_set(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 3, (double) peak_finding_length);

	// copy the samples that we will call the peak finding library on (if no events are found the result will be a GAP)
578
        if(itacac->peak_type == GSTLAL_PEAK_COMPLEX)
579
		gst_audioadapter_copy_samples(itacacpad->adapter, (float complex *) itacacpad->data->data + offset_from_copied_data * itacacpad->maxdata->channels, copysamps, NULL, NULL);
580
        else if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX)
581
		gst_audioadapter_copy_samples(itacacpad->adapter, (double complex *) itacacpad->data->data + offset_from_copied_data * itacacpad->maxdata->channels, copysamps, NULL, NULL);
582 583
}

584
static void generate_triggers(GSTLALItacac *itacac, GSTLALItacacPad *itacacpad, void *data, guint peak_finding_start, guint peak_finding_length, guint samples_previously_searched, gboolean numerous_peaks_in_window) {
585 586 587 588 589
	gsl_error_handler_t *old_gsl_error_handler;

	struct gstlal_peak_state *this_maxdata;
	void *this_snr_mat;
	void *this_chi2;
590
	guint channel;
591 592 593

	// Need to use our tmp_chi2 and tmp_maxdata struct and its corresponding snr_mat if we've already found a peak in this window
	if(numerous_peaks_in_window) {
594 595 596
		this_maxdata = itacacpad->tmp_maxdata;
		this_snr_mat = itacacpad->tmp_snr_mat;
		this_chi2 = itacacpad->tmp_chi2;
597 598 599 600
		// FIXME At the moment, empty triggers are added to inform the
		// "how many instruments were on test", the correct thing to do
		// is probably to add metadata to the buffer containing
		// information about which instruments were on
601
		this_maxdata->no_peaks_past_threshold = itacacpad->maxdata->no_peaks_past_threshold;
602
	} else {
603 604 605
		this_maxdata = itacacpad->maxdata;
		this_snr_mat = itacacpad->snr_mat;
		this_chi2 = itacacpad->chi2;
606 607 608 609 610
		// This boolean will be set to false if we find any peaks above threshold
		// FIXME At the moment, empty triggers are added to inform the
		// "how many instruments were on test", the correct thing to do
		// is probably to add metadata to the buffer containing
		// information about which instruments were on
611
		this_maxdata->no_peaks_past_threshold = TRUE;
612 613 614
	}

	// Update the snr threshold
615
	this_maxdata->thresh = itacacpad->snr_thresh;
616 617 618 619

	// AEP- 180417 Turning XLAL Errors off
	old_gsl_error_handler=gsl_set_error_handler_off();

620
        if(itacac->peak_type == GSTLAL_PEAK_COMPLEX) {
621 622
                // Find the peak, making sure to put the data pointer at the start of the interval we care about
                gstlal_float_complex_peak_over_window_interp(this_maxdata, (float complex *) itacacpad->data->data + peak_finding_start * this_maxdata->channels, peak_finding_length);
623 624 625 626
		//FIXME At the moment, empty triggers are added to inform the
		//"how many instruments were on test", the correct thing to do
		//is probably to add metadata to the buffer containing
		//information about which instruments were on
627 628
		if(this_maxdata->no_peaks_past_threshold) {
			for(channel = 0; channel < this_maxdata->channels; channel++) {
629
				if(cabs((double complex) (this_maxdata->interpvalues).as_float_complex[channel]) > 0) {
630
					this_maxdata->no_peaks_past_threshold = FALSE;
631 632 633 634 635
					break;
				}
			}
		}
	}
636
        else if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX) {
637 638
                // Find the peak, making sure to put the data pointer at the start of the interval we care about
                gstlal_double_complex_peak_over_window_interp(this_maxdata, (double complex *) itacacpad->data->data + peak_finding_start * this_maxdata->channels, peak_finding_length);
639 640 641 642
		//FIXME At the moment, empty triggers are added to inform the
		//"how many instruments were on test", the correct thing to do
		//is probably to add metadata to the buffer containing
		//information about which instruments were on
643 644
		if(this_maxdata->no_peaks_past_threshold) {
			for(channel = 0; channel < this_maxdata->channels; channel++) {
645
				if(cabs((this_maxdata->interpvalues).as_double_complex[channel]) > 0) {
646
					this_maxdata->no_peaks_past_threshold = FALSE;
647 648 649 650 651
					break;
				}
			}
		}
	}
652 653 654
        else
                g_assert_not_reached();

655 656 657
	// AEP- 180417 Turning XLAL Errors back on
	gsl_set_error_handler(old_gsl_error_handler);

658 659

	// Compute \chi^2 values if we can
660
	if(itacacpad->autocorrelation_matrix && !this_maxdata->no_peaks_past_threshold) {
661 662 663 664 665 666 667 668
		// Compute the chisq norm if it doesn't exist
		if(!itacacpad->autocorrelation_norm)
			itacacpad->autocorrelation_norm = gstlal_autocorrelation_chi2_compute_norms(itacacpad->autocorrelation_matrix, NULL);

		g_assert(autocorrelation_length(itacacpad) & 1);  // must be odd 

		if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX) {
			/* extract data around peak for chisq calculation */
669
			gstlal_double_complex_series_around_peak(this_maxdata, (double complex *) itacacpad->data->data + peak_finding_start * this_maxdata->channels, (double complex *) this_snr_mat, this_maxdata->pad);
670
			gstlal_autocorrelation_chi2((double *) this_chi2, (double complex *) this_snr_mat, autocorrelation_length(itacacpad), -((int) autocorrelation_length(itacacpad)) / 2, itacacpad->snr_thresh, itacacpad->autocorrelation_matrix, itacacpad->autocorrelation_mask, itacacpad->autocorrelation_norm);
671

672
		} else if(itacac->peak_type == GSTLAL_PEAK_COMPLEX) {
673
			/* extract data around peak for chisq calculation */
674
			gstlal_float_complex_series_around_peak(this_maxdata, (float complex *) itacacpad->data->data + peak_finding_start * this_maxdata->channels, (float complex *) this_snr_mat, this_maxdata->pad);
675
			gstlal_autocorrelation_chi2_float((float *) this_chi2, (float complex *) this_snr_mat, autocorrelation_length(itacacpad), -((int) autocorrelation_length(itacacpad)) / 2, itacacpad->snr_thresh, itacacpad->autocorrelation_matrix, itacacpad->autocorrelation_mask, itacacpad->autocorrelation_norm);
676 677 678 679 680
		} else
			g_assert_not_reached();
	} 

	// Adjust the location of the peak by the number of samples processed in this window before this function call
681
	if(samples_previously_searched > 0 && !this_maxdata->no_peaks_past_threshold) {
682
		if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX) {
683 684
			for(channel=0; channel < this_maxdata->channels; channel++) {
				if(cabs( (double complex) (this_maxdata->values).as_double_complex[channel]) > 0) {
685 686
					this_maxdata->samples[channel] += samples_previously_searched;
					this_maxdata->interpsamples[channel] += (double) samples_previously_searched;
687 688 689
				}
			}
		} else {
690 691
			for(channel=0; channel < this_maxdata->channels; channel++) {
				if(cabs( (double complex) (this_maxdata->values).as_float_complex[channel]) > 0) {
692 693
					this_maxdata->samples[channel] += samples_previously_searched;
					this_maxdata->interpsamples[channel] += (double) samples_previously_searched;
694 695 696 697 698 699
				}
			}
		}
	}

	// Combine with previous peaks found if any
700
	if(numerous_peaks_in_window && !this_maxdata->no_peaks_past_threshold) {
701
		// replace an original peak with a second peak, we need to...
702 703
		// Replace maxdata->interpvalues.as_float_complex, maxdata->interpvalues.as_double_complex etc with whichever of the two is larger
		// // Do same as above, but with maxdata->values instead of maxdata->interpvalues
704 705 706
		// // Make sure to replace samples and interpsamples too
		double old_snr, new_snr;
		if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX) {
707 708 709
			double *old_chi2 = (double *) itacacpad->chi2;
			double *new_chi2 = (double *) itacacpad->tmp_chi2;
			for(channel=0; channel < this_maxdata->channels; channel++) {
710 711 712 713 714
				// Possible cases
				// itacacpad->maxdata has a peak but itacacpad->tmp_maxdata does not <--No change required
				// itacacpad->tmp_maxdata has a peak but itacacpad->maxdata does not <--Swap out peaks
				// Both have peaks and itacacpad->maxdata's is higher <--No change required
				// Both have peaks and itacacpad->tmp_maxdata's is higher <--Swap out peaks
715
				old_snr = cabs( (double complex) (itacacpad->maxdata->interpvalues).as_double_complex[channel]);
716
				new_snr = cabs( (double complex) (itacacpad->tmp_maxdata->interpvalues).as_double_complex[channel]);
717 718 719 720 721

				if(new_snr > old_snr) {
					// The previous peak found was larger than the current peak. If there was a peak before but not now, increment itacacpad->maxdata's num_events
					if(old_snr == 0)
						// FIXME confirm that this isnt affected by floating point error
722
						itacacpad->maxdata->num_events++;
723

724 725 726 727
					(itacacpad->maxdata->values).as_double_complex[channel] = (itacacpad->tmp_maxdata->values).as_double_complex[channel];
					(itacacpad->maxdata->interpvalues).as_double_complex[channel] = (itacacpad->tmp_maxdata->interpvalues).as_double_complex[channel];
					itacacpad->maxdata->samples[channel] = itacacpad->tmp_maxdata->samples[channel];
					itacacpad->maxdata->interpsamples[channel] = itacacpad->tmp_maxdata->interpsamples[channel];
728 729 730 731
					old_chi2[channel] = new_chi2[channel];

					if(itacacpad->autocorrelation_matrix) {
						// Replace the snr time series around the peak with the new one
732 733
						gsl_vector_complex_float_view old_snr_vector_view = gsl_matrix_complex_float_column(&(itacacpad->snr_matrix_view.matrix), channel);
						gsl_vector_complex_float_view new_snr_vector_view = gsl_matrix_complex_float_column(&(itacacpad->tmp_snr_matrix_view.matrix), channel);
734 735 736 737 738
						old_snr_vector_view.vector = new_snr_vector_view.vector;
					}
				}
			}
		} else {
739 740 741
			float *old_chi2 = (float *) itacacpad->chi2;
			float *new_chi2 = (float *) itacacpad->tmp_chi2;
			for(channel=0; channel < itacacpad->maxdata->channels; channel++) {
742 743 744 745 746
				// Possible cases
				// itacacpad->maxdata has a peak but itacacpad->tmp_maxdata does not <--No change required
				// itacacpad->tmp_maxdata has a peak but itacacpad->maxdata does not <--Swap out peaks
				// Both have peaks and itacacpad->maxdata's is higher <--No change required 
				// Both have peaks and itacacpad->tmp_maxdata's is higher <--Swap out peaks
747
				old_snr = cabs( (double complex) (itacacpad->maxdata->interpvalues).as_float_complex[channel]);
748
				new_snr = cabs( (double complex) (itacacpad->tmp_maxdata->interpvalues).as_float_complex[channel]);
749
				if(new_snr > old_snr) {
750
					// The new peak found is larger than the previous peak. If there was a peak before but not now, increment itacacpad->maxdata's num_events
751 752
					if(old_snr == 0)
						// FIXME confirm that this isnt affected by floating point error
753
						itacacpad->maxdata->num_events++;
754

755 756 757 758
					(itacacpad->maxdata->values).as_float_complex[channel] = (itacacpad->tmp_maxdata->values).as_float_complex[channel];
					(itacacpad->maxdata->interpvalues).as_float_complex[channel] = (itacacpad->tmp_maxdata->interpvalues).as_float_complex[channel];
					itacacpad->maxdata->samples[channel] = itacacpad->tmp_maxdata->samples[channel];
					itacacpad->maxdata->interpsamples[channel] = itacacpad->tmp_maxdata->interpsamples[channel];
759 760 761 762
					old_chi2[channel] = new_chi2[channel];

					if(itacacpad->autocorrelation_matrix) {
						// Replace the snr time series around the peak with the new one
763 764
						gsl_vector_complex_float_view old_snr_vector_view = gsl_matrix_complex_float_column(&(itacacpad->snr_matrix_view.matrix), channel);
						gsl_vector_complex_float_view new_snr_vector_view = gsl_matrix_complex_float_column(&(itacacpad->tmp_snr_matrix_view.matrix), channel);
765 766 767 768 769
						old_snr_vector_view.vector = new_snr_vector_view.vector;
					}
				}
			}
		}
770 771 772 773

		itacacpad->maxdata->no_peaks_past_threshold = itacacpad->tmp_maxdata->no_peaks_past_threshold;
		gstlal_peak_state_clear(itacacpad->tmp_maxdata);
		itacacpad->tmp_maxdata->no_peaks_past_threshold = TRUE;
774 775 776
	}
}

777 778
static void get_snr_series(GSTLALItacac *itacac, GSTLALItacacPad *itacacpad, guint channel, guint peak_sample) {
	guint data_container_index, nongapsamps_duration, data_start_in_trigwindow, data_index, snr_index, series_start;
779 780 781
	gint trig_window_offset;
	double complex *tmp_snr_mat_doubleptr;
	float complex *tmp_snr_mat_floatptr;
782

783 784
	for(data_container_index = 0; data_container_index < itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix->size1; data_container_index++) {
		nongapsamps_duration = (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 0);
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
		// Check if we've looked at all of the available nongaps
		if(nongapsamps_duration == 0)
			break;

		// Get the start and stop sample indices for this set of nongaps
		// data_index describes where to start in the block of nongaps we have
		// data_start_in_trigwindow is how many samples came before the beginning of the data we care about in the current trigger window
		// notice that data_index and data_start_in_trigwindow give locations of the *same* sample point, just using different metrics
		// Thus if you subtract data_start_in_trigwindow from peak_sample, then add that to data_index, you'll find the location of your peak
		data_index = (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 1);
		trig_window_offset = (gint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 2);

		data_index += itacacpad->maxdata->pad;

		if(trig_window_offset < 0)
			data_start_in_trigwindow = itacacpad->maxdata->pad - (guint) abs(trig_window_offset);
		 else
			data_start_in_trigwindow = (guint) trig_window_offset + itacacpad->maxdata->pad;

		// Check if the samples we care about are in this set of nongaps
		// FIXME Can get time series out more often if we zero pad whatever existing time series when its not long enough
		if(peak_sample < data_start_in_trigwindow)
			break;
		if(peak_sample >= data_start_in_trigwindow + (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 3))
810
			continue;
811 812 813 814 815 816 817

		// notice that data_index and data_start_in_trigwindow give locations of the *same* sample point, just using different metrics
		// Thus if you subtract data_start_in_trigwindow from peak_sample, then add that to data_index, you'll find the location of your peak
		series_start = data_index + (peak_sample - data_start_in_trigwindow) - itacacpad->maxdata->pad;

		// find snr time series
		// FIXME Should the gstlal*series_around_peak functions be generalized so that they can do this?
818
		if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX) {
819
			tmp_snr_mat_doubleptr = (double complex *) itacacpad->tmp_snr_mat;
820
		} else if(itacac->peak_type == GSTLAL_PEAK_COMPLEX) {
821 822 823 824 825
			tmp_snr_mat_floatptr = (float complex *) itacacpad->tmp_snr_mat;
		}

		for(snr_index = 0; snr_index < 2*itacacpad->maxdata->pad + 1; snr_index++) {

826
			if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX)
827 828
				tmp_snr_mat_doubleptr[snr_index * itacacpad->maxdata->channels + channel] = *(((double complex *) itacacpad->data->data) + (series_start + snr_index) * itacacpad->maxdata->channels + channel);

829
			else if(itacac->peak_type == GSTLAL_PEAK_COMPLEX)
830 831 832 833 834
				tmp_snr_mat_floatptr[snr_index * itacacpad->maxdata->channels + channel] = *(((float complex *) itacacpad->data->data) + (series_start + snr_index) * itacacpad->maxdata->channels + channel);
		}

		// If we reached this point, we have what we need
		break;
835
	}
836 837 838 839 840 841 842 843 844 845 846 847 848 849
}

static void populate_snr_in_other_detectors(GSTLALItacac *itacac, GSTLALItacacPad *itacacpad) {
	guint channel, peak_sample;

	// First zero the tmp_snr_mat objects in the other pads
	if(strcmp(itacacpad->instrument, "H1") != 0 && itacac->H1_itacacpad != NULL && !itacac->H1_itacacpad->waiting)
		memset(itacac->H1_itacacpad->tmp_snr_mat, 0, autocorrelation_channels(itacacpad) * autocorrelation_length(itacacpad) * itacacpad->maxdata->unit);
	if(strcmp(itacacpad->instrument, "K1") != 0 && itacac->K1_itacacpad != NULL && !itacac->K1_itacacpad->waiting)
		memset(itacac->K1_itacacpad->tmp_snr_mat, 0, autocorrelation_channels(itacacpad) * autocorrelation_length(itacacpad) * itacacpad->maxdata->unit);
	if(strcmp(itacacpad->instrument, "L1") != 0 && itacac->L1_itacacpad != NULL && !itacac->L1_itacacpad->waiting)
		memset(itacac->L1_itacacpad->tmp_snr_mat, 0, autocorrelation_channels(itacacpad) * autocorrelation_length(itacacpad) * itacacpad->maxdata->unit);
	if(strcmp(itacacpad->instrument, "V1") != 0 && itacac->V1_itacacpad != NULL && !itacac->V1_itacacpad->waiting)
		memset(itacac->V1_itacacpad->tmp_snr_mat, 0, autocorrelation_channels(itacacpad) * autocorrelation_length(itacacpad) * itacacpad->maxdata->unit);
850 851 852 853 854

	for(channel = 0; channel < itacacpad->maxdata->channels; channel++) {
		// Identify which sample was the peak
		// See if we that have that sample in the other ifos
		// zeropad other ifos if we need to
855
		if(itacac->peak_type == GSTLAL_PEAK_DOUBLE_COMPLEX) {
856 857 858
			// First check if there's a trigger
			if(!itacacpad->maxdata->values.as_double_complex[channel])
				continue;
859
		} else if(itacac->peak_type == GSTLAL_PEAK_COMPLEX) {
860 861 862 863
			// First check if there's a trigger
			if(!itacacpad->maxdata->values.as_float_complex[channel])
				continue;
		}
864

865
		peak_sample = itacacpad->maxdata->samples[channel];
866 867 868 869 870 871 872 873
		if(strcmp(itacacpad->instrument, "H1") != 0 && itacac->H1_itacacpad != NULL && !itacac->H1_itacacpad->waiting)
			get_snr_series(itacac, itacac->H1_itacacpad, channel, peak_sample);
		if(strcmp(itacacpad->instrument, "K1") != 0 && itacac->K1_itacacpad != NULL && !itacac->K1_itacacpad->waiting)
			get_snr_series(itacac, itacac->K1_itacacpad, channel, peak_sample);
		if(strcmp(itacacpad->instrument, "L1") != 0 && itacac->L1_itacacpad != NULL && !itacac->L1_itacacpad->waiting)
			get_snr_series(itacac, itacac->L1_itacacpad, channel, peak_sample);
		if(strcmp(itacacpad->instrument, "V1") != 0 && itacac->V1_itacacpad != NULL && !itacac->V1_itacacpad->waiting)
			get_snr_series(itacac, itacac->V1_itacacpad, channel, peak_sample);
874

875 876 877
	}
}

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
static GstBuffer* assemble_srcbuf(GSTLALItacac *itacac, GSTLALItacacPad *itacacpad, GstBuffer *srcbuf) {
	if(strcmp(itacacpad->instrument, "H1") == 0) {
		if(srcbuf == NULL)
			srcbuf = gstlal_snglinspiral_new_buffer_from_peak(itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, &(itacac->H1_itacacpad->snr_matrix_view), itacac->K1_itacacpad != NULL ? &(itacac->K1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->L1_itacacpad != NULL ? &(itacac->L1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->V1_itacacpad != NULL ? &(itacac->V1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->difftime);
		else
			gstlal_snglinspiral_append_peak_to_buffer(srcbuf, itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, &(itacac->H1_itacacpad->snr_matrix_view), itacac->K1_itacacpad != NULL ? &(itacac->K1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->L1_itacacpad != NULL ? &(itacac->L1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->V1_itacacpad != NULL ? &(itacac->V1_itacacpad->tmp_snr_matrix_view) : NULL);
	} else if(strcmp(itacacpad->instrument, "K1") == 0) {
		if(srcbuf == NULL)
			srcbuf = gstlal_snglinspiral_new_buffer_from_peak(itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, itacac->H1_itacacpad != NULL ? &(itacac->H1_itacacpad->tmp_snr_matrix_view) : NULL, &(itacac->K1_itacacpad->snr_matrix_view), itacac->L1_itacacpad != NULL ? &(itacac->L1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->V1_itacacpad != NULL ? &(itacac->V1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->difftime);
		else
			gstlal_snglinspiral_append_peak_to_buffer(srcbuf, itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, itacac->H1_itacacpad != NULL ? &(itacac->H1_itacacpad->tmp_snr_matrix_view) : NULL, &(itacac->K1_itacacpad->snr_matrix_view), itacac->L1_itacacpad != NULL ? &(itacac->L1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->V1_itacacpad != NULL ? &(itacac->V1_itacacpad->tmp_snr_matrix_view) : NULL);
	} else if(strcmp(itacacpad->instrument, "L1") == 0) {
		if(srcbuf == NULL)
			srcbuf = gstlal_snglinspiral_new_buffer_from_peak(itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, itacac->H1_itacacpad != NULL ? &(itacac->H1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->K1_itacacpad != NULL ? &(itacac->K1_itacacpad->tmp_snr_matrix_view) : NULL, &(itacac->L1_itacacpad->snr_matrix_view), itacac->V1_itacacpad != NULL ? &(itacac->V1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->difftime);
		else
			gstlal_snglinspiral_append_peak_to_buffer(srcbuf, itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, itacac->H1_itacacpad != NULL ? &(itacac->H1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->K1_itacacpad != NULL ? &(itacac->K1_itacacpad->tmp_snr_matrix_view) : NULL, &(itacac->L1_itacacpad->snr_matrix_view), itacac->V1_itacacpad != NULL ? &(itacac->V1_itacacpad->tmp_snr_matrix_view) : NULL);
894
	} else if(strcmp(itacacpad->instrument, "V1") == 0) {
895
		if(srcbuf == NULL)
896
			srcbuf = gstlal_snglinspiral_new_buffer_from_peak(itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, itacac->H1_itacacpad != NULL ? &(itacac->H1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->K1_itacacpad != NULL ? &(itacac->K1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->L1_itacacpad != NULL ? &(itacac->L1_itacacpad->tmp_snr_matrix_view) : NULL, &(itacac->V1_itacacpad->snr_matrix_view), itacac->difftime);
897
		else
898
			gstlal_snglinspiral_append_peak_to_buffer(srcbuf, itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, itacac->H1_itacacpad != NULL ? &(itacac->H1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->K1_itacacpad != NULL ? &(itacac->K1_itacacpad->tmp_snr_matrix_view) : NULL, itacac->L1_itacacpad != NULL ? &(itacac->L1_itacacpad->tmp_snr_matrix_view) : NULL, &(itacac->V1_itacacpad->snr_matrix_view) );
899 900 901 902
	}
	return srcbuf;
}

903 904 905
static GstFlowReturn process(GSTLALItacac *itacac) {
	// Iterate through audioadapters and generate triggers
	GstElement *element = GST_ELEMENT(itacac);
906
	guint outsamps, nongapsamps, copysamps, samples_left_in_window;
907 908 909
	guint gapsamps = 0;
	GstFlowReturn result = GST_FLOW_OK;
	GList *padlist;
910
	//GSTLALItacacPad *itacacpad;
911 912 913
	GstBuffer *srcbuf = NULL;
	guint availablesamps;

914 915 916
        // Make sure we have enough samples to produce a trigger
        // FIXME Currently assumes every pad has the same n
	for(padlist = element->sinkpads; padlist != NULL; padlist = padlist->next) {
917 918
		GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
		if(gst_audioadapter_available_samples( itacacpad->adapter ) <= itacacpad->n + 2*itacacpad->maxdata->pad && !itacacpad->EOS && !itacacpad->waiting) {
919
			return result;
920
		}
921
	}
922 923 924


	for(padlist = element->sinkpads; padlist != NULL; padlist = padlist->next) {
925
		GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
926 927
		if(itacacpad->waiting)
			continue;
928 929 930

		samples_left_in_window = itacacpad->n;

931

932
		// FIXME Currently assumes n is the same for all detectors
933
		while( samples_left_in_window > 0 && gst_audioadapter_available_samples(itacacpad->adapter) ) {
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950

			// Check how many gap samples there are until a nongap
			// or vice versa, depending on which comes first
			gapsamps = gst_audioadapter_head_gap_length(itacacpad->adapter);
			nongapsamps = gst_audioadapter_head_nongap_length(itacacpad->adapter);
			availablesamps = gst_audioadapter_available_samples(itacacpad->adapter);

			// NOTE Remember that if you didnt just come off a gap, you should always have a pad worth of nongap samples that have been processed already

			// Check if the samples are gap, and flush up to samples_left_in_window of them if so
			if(gapsamps > 0) {
				outsamps = gapsamps > samples_left_in_window ? samples_left_in_window : gapsamps;
				gst_audioadapter_flush_samples(itacacpad->adapter, outsamps);
				samples_left_in_window -= outsamps;
			}
			// Check if we have enough nongap samples to compute chisq for a potential trigger, and if not, check if we should flush the samples or 
			// if theres a possibility we could get more nongapsamples in the future
951
			else if(nongapsamps <= 2 * itacacpad->maxdata->pad) {
952 953
				if(nongapsamps == availablesamps && !itacacpad->EOS) {
					// We have reached the end of available samples, thus there could still be enough nongaps in the next window for triggers
954
					// Assertion logic: we're guarenteed at least one more sample than a trigger window and 2 pad's worth of samples, thus if
955 956 957 958 959 960 961 962
					// all of the available samples are nongapsamps and we have 2 pad worth of non gap samples samples or less, our nongapsamps
					// must go into the next window and we must have just come off a gap, meaning we dont have any samples already available for
					// padding
					g_assert(nongapsamps > samples_left_in_window);
					g_assert(itacacpad->samples_available_for_padding == 0);
					itacacpad->samples_available_for_padding = samples_left_in_window;
					samples_left_in_window = 0;
				} else {
963
					// We are guaranteed to have at least one sample more than a pad worth of samples past the end of the 
964 965
					// trigger window, thus we know there must be a gap sample after these, and can ditch them, though we 
					// need to make sure we aren't flushing any samples from the next trigger window
966
					g_assert(availablesamps > nongapsamps || itacacpad->EOS);
967
					g_assert(itacacpad->samples_available_for_padding == 0);
968 969
					outsamps = nongapsamps > samples_left_in_window ? samples_left_in_window : nongapsamps;
					gst_audioadapter_flush_samples(itacacpad->adapter, outsamps);
970
					samples_left_in_window -= outsamps;
971

972
				}
973 974
			}
			// Not enough samples left in the window to produce a trigger or possibly even fill up a pad for a trigger in the next window
975
			else if(samples_left_in_window <= itacacpad->maxdata->pad) {
976
				itacacpad->samples_available_for_padding = samples_left_in_window;
977 978
				samples_left_in_window = 0;
			}
979 980 981 982 983 984 985 986 987
			// Have a pad worth of samples after this window and possibly some (up to a pad) before
			// want to copy samples_left_in_window + pad + samples from previous window if any
			// Want to flush up to a pad worth of samples before the next window
			// Want peak finding length to go from first sample after pad to last sample of window
			// samples_left_in_window will be zero after this
			else if(nongapsamps >= samples_left_in_window + itacacpad->maxdata->pad + itacacpad->samples_available_for_padding) {
				copysamps = samples_left_in_window + itacacpad->maxdata->pad + itacacpad->samples_available_for_padding;
				outsamps = samples_left_in_window + itacacpad->samples_available_for_padding - itacacpad->maxdata->pad;
				copy_nongapsamps(itacac, itacacpad, copysamps, outsamps, (gint) itacacpad->n - 1 * (gint) samples_left_in_window - 1 * (gint) itacacpad->samples_available_for_padding);
988
				gst_audioadapter_flush_samples(itacacpad->adapter, outsamps);
989 990
				samples_left_in_window = 0;
				itacacpad->samples_available_for_padding = itacacpad->maxdata->pad;
991
			}
992
			// There is a gap coming up in the next window
993
			else {
994 995 996 997
				g_assert(availablesamps > nongapsamps || itacacpad->EOS);
				copysamps = nongapsamps;
				outsamps = nongapsamps >= samples_left_in_window + itacacpad->samples_available_for_padding ? samples_left_in_window + itacacpad->samples_available_for_padding : nongapsamps;
				copy_nongapsamps(itacac, itacacpad, copysamps, copysamps - 2*itacacpad->maxdata->pad, (gint) itacacpad->n - 1*(gint) samples_left_in_window - 1 * (gint) itacacpad->samples_available_for_padding);
998
				gst_audioadapter_flush_samples(itacacpad->adapter, outsamps);
999 1000 1001
				samples_left_in_window = nongapsamps >= samples_left_in_window + itacacpad->samples_available_for_padding ? 0 : samples_left_in_window + itacacpad->samples_available_for_padding - nongapsamps;
				itacacpad->samples_available_for_padding = 0;
				//samples_left_in_window + itacacpad->maxdata->pad + itacacpad->samples_available_for_padding;
1002
			}
1003

1004
		}
1005
	}
1006

1007 1008 1009 1010 1011 1012 1013
	guint data_container_index;
	guint peak_finding_start;
	guint duration;
	guint samples_searched_in_window;
	gint trig_offset;

	for(padlist = element->sinkpads; padlist != NULL; padlist = padlist->next) {
1014
		GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
1015 1016
		if(itacacpad->waiting)
			continue;
1017
		data_container_index = 0;
1018
		duration = (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, 0, 0);
1019

1020
		gboolean triggers_generated = FALSE;
1021
		while(duration != 0) {
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
			peak_finding_start = (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 1);
			trig_offset = (gint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 2);

			peak_finding_start += itacacpad->maxdata->pad;
			if(trig_offset < 0) {
				// We need to use the first pad worth of samples to compute chisq for potential triggers
				samples_searched_in_window = itacacpad->maxdata->pad - (guint) abs(trig_offset);
			} else 
				samples_searched_in_window = (guint) trig_offset + itacacpad->maxdata->pad;

1032 1033
			// Sanity check

1034
			g_assert(samples_searched_in_window < itacacpad->n);
1035 1036


1037
			//raise(SIGINT);
1038 1039 1040 1041 1042 1043 1044 1045 1046
			generate_triggers(
				itacac, 
				itacacpad, 
				itacacpad->data->data, 
				peak_finding_start,
				(guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, data_container_index, 3),
				samples_searched_in_window,
				triggers_generated
			);
1047
			//raise(SIGINT);
1048 1049

			triggers_generated = TRUE;
1050
			duration = (guint) gsl_matrix_get(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, ++data_container_index, 0);
1051 1052
		}

1053 1054 1055 1056 1057 1058
		// FIXME Could check for coincidence and only add extra snr
		// time series for a detector if it doesnt have a coincident
		// trigger. This could also be where an early version of the
		// network snr cut is imposed
		if(triggers_generated && !itacacpad->maxdata->no_peaks_past_threshold) {
			populate_snr_in_other_detectors(itacac, itacacpad);
1059 1060
		}

1061
		if(triggers_generated && itacacpad->autocorrelation_matrix) {
1062
			srcbuf = assemble_srcbuf(itacac, itacacpad, srcbuf);
1063
		} else if(triggers_generated) {
1064
			if(srcbuf == NULL) {
1065
				srcbuf = gstlal_snglinspiral_new_buffer_from_peak(itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, NULL, NULL, NULL, NULL, itacac->difftime);
1066
			} else {
1067
				gstlal_snglinspiral_append_peak_to_buffer(srcbuf, itacacpad->maxdata, itacacpad->bankarray, GST_PAD((itacac->aggregator).srcpad), itacac->next_output_offset, itacacpad->n, itacac->next_output_timestamp, itacac->rate, itacacpad->chi2, NULL, NULL, NULL, NULL);
1068 1069 1070 1071 1072
			}
		}

	}

1073
	// clear the matrix that tracks information about our saved data
1074 1075 1076 1077 1078 1079
	for(padlist = element->sinkpads; padlist != NULL; padlist = padlist->next) {
		GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
		if(itacacpad->waiting)
			continue;
		gsl_matrix_scale(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix, 0);
	}
1080 1081

	if(!itacac->EOS) {
1082 1083
		if(srcbuf != NULL)
			result = gst_aggregator_finish_buffer(GST_AGGREGATOR(itacac), srcbuf);
1084
		else 
1085 1086
			// FIXME Assumes n is same for all ifos
			result = push_gap(itacac, GSTLAL_ITACAC_PAD(element->sinkpads->data)->n);
1087 1088 1089 1090
	} else {
		guint max_num_samps_left_in_any_pad = 0;
		guint available_samps;
		for(padlist=element->sinkpads; padlist != NULL; padlist = padlist->next) {
1091
			GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
1092 1093 1094 1095 1096
			available_samps = gst_audioadapter_available_samples(itacacpad->adapter);
			max_num_samps_left_in_any_pad = available_samps > max_num_samps_left_in_any_pad ? available_samps : max_num_samps_left_in_any_pad;
		}

		// If there aren't any samples left to process, then we're ready to return GST_FLOW_EOS
1097
		if(max_num_samps_left_in_any_pad > 0) {
1098
			if(srcbuf != NULL)
1099
				gst_aggregator_finish_buffer(GST_AGGREGATOR(itacac), srcbuf);
1100
			else
1101
				push_gap(itacac, GSTLAL_ITACAC_PAD(element->sinkpads->data)->n);
1102

1103
			result = process(itacac);
1104 1105 1106 1107
		} else {
			if(srcbuf != NULL) {
				gst_aggregator_finish_buffer(GST_AGGREGATOR(itacac), srcbuf);
			}
1108
			result = GST_FLOW_EOS;
1109
		}
1110 1111 1112 1113 1114 1115 1116 1117 1118
	}

	return result;
}

static GstFlowReturn aggregate(GstAggregator *aggregator, gboolean timeout)
{
	GSTLALItacac *itacac = GSTLAL_ITACAC(aggregator);
	GList *padlist;
1119
	GstFlowReturn result = GST_FLOW_OK;
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

	if(itacac->EOS) {
		result = process(itacac);
		return result;
	}

	// FIXME need to confirm the aggregator does enough checks that the
	// checks itac does are unncessary
	for(padlist = GST_ELEMENT(aggregator)->sinkpads; padlist != NULL; padlist = padlist->next) {
		// Get the buffer from the pad we're looking at and assert it
		// has a valid timestamp
1131
		GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
1132
		//raise(SIGINT);
1133
		//sinkbuf = gst_aggregator_pad_pop_buffer(GST_AGGREGATOR_PAD(itacacpad));
1134 1135 1136 1137 1138
		// We don't need to worry about this if this pad is waiting
		//if(!itacac->waiting && itacacpad->waiting)
		if(itacacpad->waiting && gst_audioadapter_available_samples(itacacpad->adapter) != 0)
			continue;

1139 1140 1141 1142 1143
		GstBuffer *sinkbuf = gst_aggregator_pad_peek_buffer(GST_AGGREGATOR_PAD(itacacpad));
		if(sinkbuf == NULL) {
			GST_DEBUG_OBJECT(itacac, "%s sinkbuf is NULL", itacacpad->instrument);
			continue;
		}
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
		g_assert(GST_BUFFER_PTS_IS_VALID(sinkbuf));

		// FIXME Is this necessary/did I understand what this does correctly?
		// Sync up the properties that may have changed, do this before
		// accessing any of the pad's properties
		gst_object_sync_values(GST_OBJECT(itacacpad), GST_BUFFER_PTS(sinkbuf));

		if(!GST_BUFFER_PTS_IS_VALID(sinkbuf) || !GST_BUFFER_DURATION_IS_VALID(sinkbuf) || !GST_BUFFER_OFFSET_IS_VALID(sinkbuf) || !GST_BUFFER_OFFSET_END_IS_VALID(sinkbuf)) {
			gst_buffer_unref(sinkbuf);
			GST_ERROR_OBJECT(GST_ELEMENT(aggregator), "error in input stream: buffer has invalid timestamp and/or offset");
			result = GST_FLOW_ERROR;
			return result;
1156
		}
1157 1158 1159

		// Check for instrument and channel name tags
		if(!itacacpad->instrument || !itacacpad->channel_name) {
1160
			gst_buffer_unref(sinkbuf);
1161 1162 1163 1164 1165 1166
			GST_ELEMENT_ERROR(itacacpad, STREAM, FAILED, ("missing or invalid tags"), ("instrument and/or channel name not known (stream's tags must provide this information)"));
			result = GST_FLOW_ERROR;
			return result;
		}

		if(!itacacpad->bankarray) {
1167
			gst_buffer_unref(sinkbuf);
1168 1169 1170 1171 1172
			GST_ELEMENT_ERROR(itacacpad, STREAM, FAILED, ("missing bank file"), ("must have a valid template bank to create events"));
			result = GST_FLOW_ERROR;
			return result;
		}

1173

1174 1175
		// FIXME if we were more careful we wouldn't lose so much data around disconts
		// FIXME I don't think this logic works for itacac, it came from itac, need to think carefully about what to do around disconts
1176
		if(GST_BUFFER_FLAG_IS_SET(sinkbuf, GST_BUFFER_FLAG_DISCONT)) {
1177
			// FIXME For now, this should ensure we only see disconts at start up
1178
			g_assert(gst_audioadapter_available_samples(itacacpad->adapter) == 0);
1179 1180
			itacacpad->initial_timestamp = GST_CLOCK_TIME_NONE;
			gst_audioadapter_clear(itacacpad->adapter);
1181 1182 1183
			if(!itacacpad->waiting) { 
				reset_time_and_offset(itacac);
			}
1184 1185
		}

1186 1187 1188 1189
		// If the adapter has too many samples stored in memory, just
		// ignore this buffer for now. We need n + 2*maxdata->pad for a
		// trigger, so adapter should never need to hold more than 2*(2
		// + 2*maxdata->pad).
1190
		if(gst_audioadapter_available_samples(itacacpad->adapter) > 2*(itacacpad->n + 2*itacacpad->maxdata->pad)) {
1191 1192
			gst_buffer_unref(sinkbuf);
			continue;
1193 1194
		}

1195 1196 1197 1198 1199
		// Grab timestamp for this pad if we dont have it already
		if(itacacpad->initial_timestamp == GST_CLOCK_TIME_NONE) {
			g_assert(gst_audioadapter_available_samples(itacacpad->adapter) == 0);
			itacacpad->initial_timestamp = GST_BUFFER_PTS(sinkbuf);
		}
1200

1201 1202 1203
		// Push buf to gstaudioadapter
		gst_audioadapter_push(itacacpad->adapter, sinkbuf);
		gst_aggregator_pad_drop_buffer(GST_AGGREGATOR_PAD(itacacpad));
1204 1205


1206
	}
1207
	//raise(SIGINT);
1208

1209
	//raise(SIGINT);
1210 1211 1212 1213 1214 1215 1216
	if(itacac->waiting) {
		// Check if timestamps of all sinkpads are the same, if not,
		// take the earliest timestamp as the next output timestamp and
		// start processing samples from sinkpads that have that
		// timestamp
		for(padlist = GST_ELEMENT(aggregator)->sinkpads; padlist != NULL; padlist = padlist->next) {
			GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
1217 1218 1219
			if(gst_audioadapter_available_samples(itacacpad->adapter) == 0)
				continue;

1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
			if(padlist == GST_ELEMENT(aggregator)->sinkpads)
				itacac->next_output_timestamp = itacacpad->initial_timestamp;
			else
				itacac->next_output_timestamp = itacac->next_output_timestamp <= itacacpad->initial_timestamp ? itacac->next_output_timestamp : itacacpad->initial_timestamp;
		}

		if(itacac->next_output_timestamp != GST_CLOCK_TIME_NONE) {
			for(padlist = GST_ELEMENT(aggregator)->sinkpads; padlist != NULL; padlist = padlist->next) {
				GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
				if(itacacpad->initial_timestamp == itacac->next_output_timestamp && gst_audioadapter_available_samples(itacacpad->adapter) > 0) {
					itacacpad->waiting = FALSE;
1231
					if(itacac->waiting)
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
						itacac->waiting = FALSE;
				}
			}
			if(!itacac->waiting)
				result = process(itacac);
		}

	} else {
		if(itacac->next_output_timestamp == GST_CLOCK_TIME_NONE) {
			for(padlist = GST_ELEMENT(aggregator)->sinkpads; padlist != NULL; padlist = padlist->next) {
				GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
				if(padlist == GST_ELEMENT(aggregator)->sinkpads)
					itacac->next_output_timestamp = itacacpad->initial_timestamp;
				else
					itacac->next_output_timestamp = itacac->next_output_timestamp <= itacacpad->initial_timestamp ? itacac->next_output_timestamp : itacacpad->initial_timestamp;
			}
		}
		// Figure out if we can start taking data from each pad that is still waiting
		for(padlist = GST_ELEMENT(aggregator)->sinkpads; padlist != NULL; padlist = padlist->next) {
			GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(padlist->data);
			if(!itacacpad->waiting || itacacpad->initial_timestamp > itacac->next_output_timestamp)
				continue;

			// FIXME Assumes n is the same for all detectors
1256
			guint num_samples_behind = (guint) ((itacac->next_output_timestamp - itacacpad->initial_timestamp) / (1000000000 / itacac->rate));
1257
			if(num_samples_behind > itacacpad->maxdata->pad)
1258
				gst_audioadapter_flush_samples(itacacpad->adapter, MIN(num_samples_behind - itacacpad->maxdata->pad, gst_audioadapter_available_samples(itacacpad->adapter)));
1259
			itacacpad->samples_available_for_padding = num_samples_behind > itacacpad->maxdata->pad ? itacacpad->maxdata->pad : num_samples_behind;
1260 1261

			itacacpad->waiting = FALSE;
1262
		}
1263

1264
		result = process(itacac);
1265 1266
	}

1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
	return result;
}

/*
 * ============================================================================
 *
 *                                Type Support FIXME Is this appropriately named?
 *
 * ============================================================================
 */


/*
 * Instance finalize function.  See ???
 */

static void gstlal_itacac_pad_dispose(GObject *object)
{
1285
	GST_DEBUG_OBJECT(GST_AGGREGATOR_PAD(object), "in pad_dispose");
1286 1287
	GSTLALItacacPad *itacacpad = GSTLAL_ITACAC_PAD(object);

1288
	gst_audioadapter_clear(itacacpad->adapter);
1289
	g_object_unref(itacacpad->adapter);
1290
	itacacpad->adapter = NULL;
1291

1292
	free_bank(itacacpad);
1293

1294 1295
	free(itacacpad->instrument);
	itacacpad->instrument = NULL;
1296

1297 1298
	free(itacacpad->channel_name);
	itacacpad->channel_name = NULL;
1299

1300 1301 1302 1303 1304 1305 1306 1307
	if(itacacpad->maxdata) {
		gstlal_peak_state_free(itacacpad->maxdata);
		itacacpad->maxdata = NULL;
	}

	if(itacacpad->tmp_maxdata) {
		gstlal_peak_state_free(itacacpad->tmp_maxdata);
		itacacpad->tmp_maxdata = NULL;
1308 1309
	}

1310
	if(itacacpad->data) {
1311 1312
		free(itacacpad->data->data);
		itacacpad->data->data = NULL;
1313

1314 1315 1316 1317
		if(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix) {
			gsl_matrix_free(itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix);
			itacacpad->data->duration_dataoffset_trigwindowoffset_peakfindinglength_matrix = NULL;
		}
1318

1319 1320
		free(itacacpad->data);
		itacacpad->data = NULL;
1321 1322
	}

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
	free(itacacpad->snr_mat);
	free(itacacpad->tmp_snr_mat);
	free(itacacpad->autocorrelation_matrix);
	free(itacacpad->autocorrelation_mask);
	free(itacacpad->autocorrelation_norm);
	free(itacacpad->chi2);
	free(itacacpad->tmp_chi2);
	itacacpad->snr_mat = NULL;
	itacacpad->tmp_snr_mat = NULL;
	itacacpad->autocorrelation_matrix = NULL;
	itacacpad->autocorrelation_mask = NULL;
	itacacpad->autocorrelation_norm = NULL;
	itacacpad->chi2 = NULL;
	itacacpad->tmp_chi2 = NULL;
1337

1338 1339 1340
	G_OBJECT_CLASS(gstlal_itacac_pad_parent_class)->dispose(object);
}

1341 1342
static void gstlal_itacac_finalize(GObject *object)
{
1343
	//GSTLALItacac *itacac = GSTLAL_ITACAC(object);
1344 1345
	G_OBJECT_CLASS(gstlal_itacac_parent_class)->finalize(object);
}
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

/*
 * Class init function.  See
 *
 * http://developer.gnome.org/doc/API/2.0/gobject/gobject-Type-Information.html#GClassInitFunc
 */

static void gstlal_itacac_pad_class_init(GSTLALItacacPadClass *klass)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS(klass);

	gobject_class->set_property = GST_DEBUG_FUNCPTR(gstlal_itacac_pad_set_property);
	gobject_class->get_property = GST_DEBUG_FUNCPTR(gstlal_itacac_pad_get_property);
	// Right now no memory is allocated in the class instance structure for GSTLALItacacPads, so we dont need a custom finalize function
	// If anything is added to the class structure, we will need a custom finalize function that chains up to the AggregatorPad's finalize function
	gobject_class->dispose = GST_DEBUG_FUNCPTR(gstlal_itacac_pad_dispose);

	//
	// Properties
	//

        g_object_class_install_property(
		gobject_class,
		ARG_N,
		g_param_spec_uint(
			"n",
			"n",
			"number of samples over which to identify itacs",
			0, G_MAXUINT, 0,
1375
			(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT)
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
		)
	);

	g_object_class_install_property(
		gobject_class,
		ARG_BANK_FILENAME,
		g_param_spec_string(
			"bank-filename",
			"Bank file name",
			"Path to XML file used to generate the template bank.  Setting this property resets sigmasq to a vector of 0s.",
			NULL,
1387
			(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
		)
	);

	g_object_class_install_property(
		gobject_class,
		ARG_SNR_THRESH,
		g_param_spec_double(
			"snr-thresh",
			"SNR Threshold",
			"SNR Threshold that determines a trigger.",
			0, G_MAXDOUBLE, DEFAULT_SNR_THRESH,
1399
			(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
		)
	);

	g_object_class_install_property(
		gobject_class,
		ARG_SIGMASQ,
		g_param_spec_value_array(
			"sigmasq",
			"\\sigma^{2} factors",
			"Vector of \\sigma^{2} factors.  The effective distance of a trigger is \\sqrt{sigma^{2}} / SNR.",
			g_param_spec_double(
				"sigmasq",
				"\\sigma^{2}",
				"\\sigma^{2} factor",
				-G_MAXDOUBLE, G_MAXDOUBLE, 0.0,
1415
				(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
1416
			),
1417
			(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_CONTROLLABLE)
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
		)
	);


	g_object_class_install_property(
		gobject_class,
		ARG_AUTOCORRELATION_MATRIX,
		g_param_spec_value_array(
			"autocorrelation-matrix",
			"Autocorrelation Matrix",
			"Array of complex autocorrelation vectors.  Number of vectors (rows) in matrix sets number of channels.  All vectors must have the same length.",
			g_param_spec_value_array(
				"autocorrelation",
				"Autocorrelation",
				"Array of autocorrelation samples.",
				/* FIXME:  should be complex */
				g_param_spec_double(
					"sample",
					"Sample",
					"Autocorrelation sample",
					-G_MAXDOUBLE, G_MAXDOUBLE, 0.0,
1439
					(GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
Cody Messick's avatar