view src/libmlk-core-js/core/js-clock.c @ 380:31e2f6d35c34

core: fix sndfile distortion issue
author David Demelier <markand@malikania.fr>
date Fri, 07 Jan 2022 08:20:12 +0100
parents 460c78706989
children
line wrap: on
line source

/*
 * js-clock.c -- core clock binding
 *
 * Copyright (c) 2020-2022 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <assert.h>

#include <core/alloc.h>
#include <core/clock.h>

#include "js-clock.h"

#define SIGNATURE DUK_HIDDEN_SYMBOL("Mlk.Clock")

static inline struct clock *
self(duk_context *ctx)
{
	struct clock *clk;

	duk_push_this(ctx);
	duk_get_prop_string(ctx, -1, SIGNATURE);
	clk = duk_to_pointer(ctx, -1);
	duk_pop_2(ctx);

	if (!clk)
		return (void)duk_error(ctx, DUK_ERR_TYPE_ERROR, "not a Clock object"), NULL;

	return clk;
}

static duk_ret_t
Clock_elapsed(duk_context *ctx)
{
	duk_push_number(ctx, clock_elapsed(self(ctx)));

	return 1;
}

static duk_ret_t
Clock_constructor(duk_context *ctx)
{
	struct clock *clk;

	clk = alloc_new(sizeof (*clk));
	clock_start(clk);

	duk_push_this(ctx);
	duk_push_pointer(ctx, clk);
	duk_put_prop_string(ctx, -2, SIGNATURE);
	duk_push_string(ctx, "elapsed");
	duk_push_c_function(ctx, Clock_elapsed, 0);
	duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_GETTER);
	duk_pop(ctx);

	return 0;
}

static duk_ret_t
Clock_start(duk_context *ctx)
{
	clock_start(self(ctx));

	return 0;
}

static duk_ret_t
Clock_destructor(duk_context *ctx)
{
	duk_get_prop_string(ctx, 0, SIGNATURE);
	free(duk_to_pointer(ctx, -1));
	duk_pop(ctx);
	duk_del_prop_string(ctx, 0, SIGNATURE);

	return 0;
}

static const duk_function_list_entry methods[] = {
	{ "start",      Clock_start,    0 },
	{ NULL,         NULL,           0 }
};

void
js_clock_bind(duk_context *ctx)
{
	assert(ctx);

	duk_push_c_function(ctx, Clock_constructor, 0);
	duk_push_object(ctx);
	duk_put_function_list(ctx, -1, methods);
	duk_push_c_function(ctx, Clock_destructor, 1);
	duk_set_finalizer(ctx, -2);
	duk_put_prop_string(ctx, -2, "prototype");
	duk_put_global_string(ctx, "Clock");
}