/*
 * libusb example program to measure isochronous performance
 * Copyright (C) 2012 Harald Welte <laforge@gnumonks.org>
 * Copyright (C) 2022 Tormod Volden
 *
 * Based on sam3u_benchmark.c
 * Copied with the author's permission under LGPL-2.1 from
 * http://git.gnumonks.org/cgi-bin/gitweb.cgi?p=sam3u-tests.git;a=blob;f=usb-benchmark-project/host/benchmark.c;h=74959f7ee88f1597286cd435f312a8ff52c56b7e
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <config.h>

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include <time.h>

#include "libusb.h"

#define VID 0x0483
#define PID 0x5730
#define IFACE 1
#define ALTS 1
#define EP_ISO_IN  0x82
#define EP_ISO_OUT 0x01
#define PACKET_LEN 22

static int verbose = 0;
static volatile sig_atomic_t do_exit = 0;
static struct libusb_device_handle *devh = NULL;

static unsigned long num_bytes = 0, num_xfer = 0;
static struct timeval tv_start;

static void get_timestamp(struct timeval *tv)
{
#if defined(PLATFORM_WINDOWS)
	static LARGE_INTEGER frequency;
	LARGE_INTEGER counter;

	if (!frequency.QuadPart)
		QueryPerformanceFrequency(&frequency);

	QueryPerformanceCounter(&counter);
	counter.QuadPart *= 1000000;
	counter.QuadPart /= frequency.QuadPart;

	tv->tv_sec = (long)(counter.QuadPart / 1000000ULL);
	tv->tv_usec = (long)(counter.QuadPart % 1000000ULL);
#elif defined(HAVE_CLOCK_GETTIME)
	struct timespec ts;

	(void)clock_gettime(CLOCK_MONOTONIC, &ts);
	tv->tv_sec = ts.tv_sec;
	tv->tv_usec = (int)(ts.tv_nsec / 1000L);
#else
	gettimeofday(tv, NULL);
#endif
}

static void LIBUSB_CALL cb_xfr(struct libusb_transfer *xfr)
{
	int i;
	unsigned int packet_length_sum = 0;

	if (xfr->status != LIBUSB_TRANSFER_COMPLETED) {
		fprintf(stderr, "transfer status %d\n", xfr->status);
		//libusb_free_transfer(xfr);
		//exit(3);
		goto resubmit;
	}

	if (xfr->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) {
		for (i = 0; i < xfr->num_iso_packets; i++) {
			struct libusb_iso_packet_descriptor *pack = &xfr->iso_packet_desc[i];

			if (pack->status != LIBUSB_TRANSFER_COMPLETED) {
				fprintf(stderr, "Error: pack %d endpoint %02x status %d (%s)\n", i, pack->status, xfr->endpoint, libusb_error_name(pack->status));
				//exit(5);
				goto resubmit;
			}

			if (pack->length != pack->actual_length)
				printf("pack %d endpoint:%02x length:%u, actual_length:%u\n", i, xfr->endpoint, pack->length, pack->actual_length);
			packet_length_sum += pack->actual_length;
		}
	}

	printf("request endpoint:%02x length:%u, xfr length (bulk):%u, total (isoch):%u\n", xfr->endpoint, xfr->length, xfr->actual_length, packet_length_sum);

	/* transfer actual_length not valid for isochronous transfers */
	if (xfr->endpoint == EP_ISO_IN || xfr->endpoint == EP_ISO_OUT)
		xfr->actual_length = packet_length_sum;

	if (verbose && (xfr->endpoint & 0x80)) { /* IN */
		for (i = 0; i < xfr->actual_length; i++) {
			printf(" %02x", xfr->buffer[i]);
			if (i % 16 == 15)
				printf("\n");
			else if (i % 8 == 7)
				printf(" ");
		}
		if (i % 16 != 0)
			printf("\n");
	}
	num_bytes += xfr->actual_length;
	num_xfer++;

resubmit:
	if (libusb_submit_transfer(xfr) < 0) {
		fprintf(stderr, "error re-submitting URB\n");
		exit(1);
	}
}

static int benchmark_iso(uint8_t ep, uint8_t *buf, size_t length, int packet_size)
{
	static struct libusb_transfer *xfr;
	int num_iso_pack = 0;
	unsigned int i;

	/* prefill OUT buffer with sawtooth signal */
	if (!(ep & 0x80))
		for (i = 0; i < length; i++)
			buf[i] = i & 0xff;

	if (ep == EP_ISO_IN || ep == EP_ISO_OUT) {
		num_iso_pack = length / packet_size + (length % packet_size != 0);
		if (verbose)
			printf("num_iso_pack = %d\n", num_iso_pack);
	}

	xfr = libusb_alloc_transfer(num_iso_pack);
	if (!xfr) {
		errno = ENOMEM;
		return -1;
	}

	if (ep == EP_ISO_IN || ep == EP_ISO_OUT) {
		libusb_fill_iso_transfer(xfr, devh, ep, buf,
				length, num_iso_pack, cb_xfr, NULL, 1000);
		libusb_set_iso_packet_lengths(xfr, packet_size);
		//if (length % packet_size) // partial 
		//	xfr->iso_packet_desc[num_iso_pack - 1].length = length % packet_size;
	} else /* assume BULK endpoint */
		libusb_fill_bulk_transfer(xfr, devh, ep, buf,
				length, cb_xfr, NULL, 0);

	get_timestamp(&tv_start);

	/* NOTE: To reach maximum possible performance the program must
	 * submit *multiple* transfers here, not just one.
	 *
	 * When only one transfer is submitted there is a gap in the bus
	 * schedule from when the transfer completes until a new transfer
	 * is submitted by the callback. This causes some jitter for
	 * isochronous transfers and loss of throughput for bulk transfers.
	 *
	 * This is avoided by queueing multiple transfers in advance, so
	 * that the host controller is always kept busy, and will schedule
	 * more transfers on the bus while the callback is running for
	 * transfers which have completed on the bus.
	 */

	return libusb_submit_transfer(xfr);
}

static void measure(void)
{
	struct timeval tv_stop;
	unsigned long diff_msec;

	get_timestamp(&tv_stop);

	diff_msec = (tv_stop.tv_sec - tv_start.tv_sec) * 1000L;
	diff_msec += (tv_stop.tv_usec - tv_start.tv_usec) / 1000L;

	printf("%lu transfers (total %lu bytes) in %lu milliseconds => %lu bytes/sec\n",
		num_xfer, num_bytes, diff_msec, (num_bytes * 1000L) / diff_msec);
}

static void sig_hdlr(int signum)
{
	(void)signum;

	measure();
	do_exit = 1;
}

int main(int argc, const char **argv)
{
	int rc;
	int opt;
	int dir_out = 0;
	uint8_t *buf;
	unsigned int xfr_size = PACKET_LEN; /* default one packet */

#if defined(PLATFORM_POSIX)
	struct sigaction sigact;

	sigact.sa_handler = sig_hdlr;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = 0;
	(void)sigaction(SIGINT, &sigact, NULL);
#else
	(void)signal(SIGINT, sig_hdlr);
#endif

	for (opt = 1; opt < argc; opt++) {
		if (argv[opt][0] != '-')
			continue;
		else if (argv[opt][1] == 'v')
			verbose = 1;
		else if (argv[opt][1] == 'o')
			dir_out = 1;
		else if (argv[opt][1] == 'n')
			xfr_size = (unsigned int) strtoul(&argv[opt][2], NULL, 0);
		else
			fprintf(stderr, "Unknown option: %s\n", argv[opt]);
	}

	rc = libusb_init(NULL);
	if (rc < 0) {
		fprintf(stderr, "Error initializing libusb: %s\n", libusb_error_name(rc));
		exit(1);
	}

	devh = libusb_open_device_with_vid_pid(NULL, VID, PID);
	if (!devh) {
		fprintf(stderr, "Error finding USB device\n");
		goto out;
	}

	rc = libusb_claim_interface(devh, IFACE);
	if (rc < 0) {
		fprintf(stderr, "Error claiming interface: %s\n", libusb_error_name(rc));
		goto out;
	}

	rc = libusb_set_interface_alt_setting(devh, IFACE, ALTS);
	if (rc < 0) {
		fprintf(stderr, "Error setting alternate interface: %s\n", libusb_error_name(rc));
		goto out;
	}

	buf = malloc(xfr_size); // + PACKET_LEN for good measure?

	if (dir_out)
		benchmark_iso(EP_ISO_OUT, buf, xfr_size, PACKET_LEN);
	else
		benchmark_iso(EP_ISO_IN, buf, xfr_size, PACKET_LEN);

	while (!do_exit) {
		rc = libusb_handle_events(NULL);
		if (rc != LIBUSB_SUCCESS)
			break;
	}

	free(buf);

	/* Measurement has already been done by the signal handler. */

	libusb_release_interface(devh, IFACE);
out:
	if (devh)
		libusb_close(devh);
	libusb_exit(NULL);
	return rc;
}