//..............................................................................
//
// USB Monitor session
//

import "doc_Session.jnc"
import "io_usbmon.jncx"
import "ui_BufferPropertySet.jnc"
import "ui_StdSessionInfoSet.jnc"
import "ui_UsbMonUi.jnc"
import "log_ThroughputCalc.jnc"
import "log_ChecksumCalc.jnc"
import "std_Buffer.jnc"

//..............................................................................

class UsbMonSession: doc.Session {
protected:
	enum Defaults {
		ReadBlockSize    = 32 * 1024,
		ReadBufferSize   = 512 * 1024,
		SnapshotSize     = 64 * 1024,
		KernelBufferSize = 1 * 1024 * 1024, // 1 MB
	}

	enum State {
		Closed,
		Opened,
	}

	enum ActionId {
		Refresh,
		Capture,
		_Count,
	}

	enum IconId {
		Refresh,
		Capture,
		StopCapture,
		_Count,
	}

	enum StatusPaneId {
		State,
		_Count,
	}

protected:
	State bindable m_state;
	io.UsbMonitor m_monitor;
	std.Buffer m_readBuffer;
	std.Buffer m_transferBuffer;
	uint8_t m_prevTransferEndpoint;
	uint_t m_syncId;

	// toolbar, status bar & menu

	ui.Action* m_actionTable[ActionId._Count];
	ui.Icon* m_iconTable[IconId._Count];
	ui.StatusPane* m_statusPaneTable[StatusPaneId._Count];
	ui.ComboBox* m_deviceCombo;

	// USB monitor property grid

	ui.EnumProperty* m_deviceProp;
	ui.BufferPropertySet m_bufferPropertySet;
	ui.IntProperty* m_snapshotSizeProp;
	ui.IntProperty* m_kernelBufferSizeProp;

	// information grid

	ui.StdSessionInfoSet m_stdSessionInfoSet;
	ui.ThroughputInfoSet m_throughputInfoSet;
	ui.ChecksumInfoSet m_checksumInfoSet;

	// ui reactor

	reactor m_uiReactor;

public:
	construct(doc.PluginHost* pluginHost);

	bool errorcode capture();
	void close();

	override void load(doc.Storage* storage);
	override void save(doc.Storage* storage);
	override void updateProperties();
	override bool errorcode applyProperties();
	override void restoreDefaultProperties();

protected:
	void onRefresh() {
		ui.refreshUsbMonDeviceListUi(m_deviceCombo, m_deviceProp);
	}

	void onCapture() {
		m_state ? close() : try capture();
	}

	void onMonitorEvent(
		uint_t syncId,
		io.UsbMonEvents triggeredEvents
	);

	void createUi();
	void waitMonitorEvents();

	void processData(
		void const* p,
		size_t size
	);

	void writeTransferError(uint_t status);

	void writeIsoTransferPayload(
		uint64_t recordCode,
		io.UsbMonTransferHdr const* hdr
	);
}

// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

UsbMonSession.construct(doc.PluginHost* pluginHost) {
	basetype.construct(pluginHost);

	createUi();

	pluginHost.m_log.addSelectionProcessor(log.ThroughputCalcRangeProcessor.factory~(m_throughputInfoSet));
	pluginHost.m_log.addSelectionProcessor(log.ChecksumCalcRangeProcessor.factory~(m_checksumInfoSet));
}

void UsbMonSession.createUi() {
	// toolbar

	m_iconTable[IconId.Refresh] = new ui.Icon("images/refresh.png");
	m_iconTable[IconId.Capture] = new ui.Icon("images/capture.png");
	m_iconTable[IconId.StopCapture] = new ui.Icon("images/pause.png");

	m_pluginHost.m_toolBar.addLabel("Device:");
	m_deviceCombo = m_pluginHost.m_toolBar.addComboBox(-1);

	m_actionTable[ActionId.Refresh]  = createAction("Re-enumerate devices", m_iconTable[IconId.Refresh]);
	m_actionTable[ActionId.Refresh].m_onTriggered += onRefresh;

	m_actionTable[ActionId.Capture] = createAction("Capture", m_iconTable[IconId.Capture]);
	m_actionTable[ActionId.Capture].m_onTriggered += onCapture;

	// status bar

	m_statusPaneTable[StatusPaneId.State] = m_pluginHost.m_statusBar.addPane(, 80);

	// property grid

	ui.GroupProperty* group = m_pluginHost.m_propertyGrid.createGroupProperty(
		"Connection",
		"USB monitor connection settings"
	);

	m_deviceProp = m_pluginHost.m_propertyGrid.createEnumProperty(
		group,,
		"Device",
		"Target USB device",
		null, 0
	);

	group = m_pluginHost.m_propertyGrid.createGroupProperty(
		"Buffering & compatibility",
		"Advanced options controlling performance, throughtput and compatibility"
	);

	if (sys.g_systemInfo.m_osKind == sys.OsKind.Windows) {
		m_snapshotSizeProp = m_pluginHost.m_propertyGrid.createIntProperty(
			group,,
			"Snapshot size",
			"Specify the USBPcap snapshot size"
		);

		m_snapshotSizeProp.m_minValue = 4 * 1024;
		m_snapshotSizeProp.m_spinBoxStep = 1024;
	}

	m_kernelBufferSizeProp = m_pluginHost.m_propertyGrid.createIntProperty(
		group,,
		"Kernel buffer size",
		"Specify the Pcap kernel buffer size (0 = default)"
	);

	m_kernelBufferSizeProp.m_minValue = 4 * 1024;
	m_kernelBufferSizeProp.m_spinBoxStep = 1024;

	m_bufferPropertySet.m_defaultReadBlockSize = Defaults.ReadBlockSize;
	m_bufferPropertySet.m_defaultReadBufferSize = Defaults.ReadBufferSize;

	m_bufferPropertySet.createProperties(
		m_pluginHost.m_propertyGrid,
		group,,
		ui.BufferPropertySet.PropertyId.ReadBufferSize |
		ui.BufferPropertySet.PropertyId.ReadBlockSize |
		ui.BufferPropertySet.PropertyId.NotifyReadBufferFull
	);

	// information grid

	ui.InformationGroup* infoGroup = m_pluginHost.m_informationGrid.createGroup("Pipe monitor");

	m_stdSessionInfoSet.create(m_pluginHost.m_txRxStats, m_pluginHost.m_informationGrid, infoGroup);
	m_throughputInfoSet.createInformationValuesGrouped(m_pluginHost.m_informationGrid);
	m_checksumInfoSet.createInformationValuesGrouped(m_pluginHost.m_informationGrid);

	m_pluginHost.m_propertyGrid.resizeNameColumnToContents();
	m_pluginHost.m_informationGrid.resizeNameColumnToContents();

	ui.refreshUsbMonDeviceListUi(m_deviceCombo, m_deviceProp);
	m_uiReactor.start();
}

bool errorcode UsbMonSession.capture() {
	close();
	startSession();

	io.UsbMonDeviceDesc const* device = m_deviceCombo.m_currentData;
	if (!device) {
		m_logWriter.write(
			UsbLogRecordCode.UsbMonNotDetected,
			&sys.g_systemInfo.m_osKind,
			sizeof(sys.OsKind)
		);

		std.setError("USB capturing service not detected");
		return false;
	}

	size_t snapshotSize = Defaults.SnapshotSize;
	if (m_snapshotSizeProp)
		snapshotSize = m_snapshotSizeProp.m_value;

	m_monitor.m_readBlockSize = m_bufferPropertySet.m_readBlockSizeProp.m_value;
	m_monitor.m_readBufferSize = m_bufferPropertySet.m_readBufferSizeProp.m_value;
	m_monitor.m_kernelBufferSize = m_kernelBufferSizeProp.m_value;
	m_monitor.m_options = io.UsbMonOptions.CompletedTransfersOnly;
	m_monitor.m_addressFilter = device.m_address;
	m_monitor.open(device.m_captureDeviceName, snapshotSize);

	UsbDeviceParams params;
	params.m_osKind = sys.g_systemInfo.m_osKind;
	params.m_captureDeviceId = device.m_captureDeviceId;
	params.m_address = device.m_address;
	params.m_port = device.m_port;
	params.m_vendorId = device.m_vendorId;
	params.m_productId = device.m_productId;
	params.m_speed = device.m_speed;
	params.m_class = device.m_class;

	string_t product = device.m_productDescriptor ? device.m_productDescriptor : device.m_description;
	string_t manufacturer = device.m_manufacturerDescriptor ? device.m_manufacturerDescriptor : device.m_manufacturer;

	std.Buffer buffer;
	buffer.append(params, sizeof(params));
	buffer.append(product);
	buffer.append(0);
	buffer.append(manufacturer);
	buffer.append(0);
	buffer.append(device.m_driver);
	buffer.append(0);

	m_logWriter.write(
		UsbLogRecordCode.CaptureStarted,
		buffer.m_p,
		buffer.m_size
	);

	m_state = State.Opened;
	m_stdSessionInfoSet.startSession(m_pluginHost.m_mainThreadScheduler);
	m_transferBuffer.clear();
	m_prevTransferEndpoint = 0;
	waitMonitorEvents();
	return true;

catch:
	m_logWriter.writeLastError(UsbLogRecordCode.CaptureError);
	m_monitor.close();
	return false;
}

void UsbMonSession.close() {
	if (m_state != State.Opened)
		return;

	m_logWriter.write(UsbLogRecordCode.CaptureStopped);

	m_monitor.close();
	m_state = State.Closed;
	m_stdSessionInfoSet.endSession();
	m_syncId++;
}

void UsbMonSession.onMonitorEvent(
	uint_t syncId,
	io.UsbMonEvents triggeredEvents
) {
	if (syncId != m_syncId)
		return;

	if (triggeredEvents & io.UsbMonEvents.IoError) {
		m_logWriter.write(log.StdRecordCode.Error, m_monitor.m_ioError);
		close();
		return;
	}

	if ((triggeredEvents & io.UsbMonEvents.ReadBufferFull) &&
		m_bufferPropertySet.m_notifyReadBufferFullProp.m_value)
		m_logWriter.write(log.StdRecordCode.RxBufferFull);

	if (triggeredEvents & io.UsbMonEvents.IncomingData) {
		size_t result = m_monitor.read(m_readBuffer.m_p, m_readBuffer.m_size);
		if (result)
			processData(m_readBuffer.m_p, result);
	}

	waitMonitorEvents();

catch:
	m_logWriter.writeLastError(log.StdRecordCode.Error); // broken data from usbpcap/usbmon?
	close();
}

void UsbMonSession.waitMonitorEvents() {
	io.UsbMonEvents eventMask =
		io.UsbMonEvents.IoError |
		io.UsbMonEvents.ReadBufferFull |
		io.UsbMonEvents.IncomingData;

	m_monitor.wait(eventMask, onMonitorEvent~(++m_syncId) @ m_pluginHost.m_mainThreadScheduler);
}

void UsbMonSession.processData(
	void const* p,
	size_t size
) {
	int i = 0;
	while (size) {
		if (m_transferBuffer.m_size < sizeof(io.UsbMonTransferHdr)) {
			size_t leftoverSize = sizeof(io.UsbMonTransferHdr) - m_transferBuffer.m_size;
			if (size < leftoverSize) {
				m_transferBuffer.append(p, size);
				break;
			}

			m_transferBuffer.append(p, leftoverSize);
			p += leftoverSize;
			size -= leftoverSize;
		}

		io.UsbMonTransferHdr const* hdr = (io.UsbMonTransferHdr const*)m_transferBuffer.m_p;
		size_t transferSize = sizeof(io.UsbMonTransferHdr) + hdr.m_capturedDataSize;
		if (hdr.m_transferType == io.UsbTransferType.Isochronous) {
			// for iso transfers we need to buffer the whole transfer --
			// including the iso packet array and the payload -- before writing to log

			transferSize += hdr.m_isoHdr.m_packetCount * sizeof(io.UsbIsoPacket);
			size_t leftoverSize = transferSize - m_transferBuffer.m_size;
			if (size < leftoverSize) {
				m_transferBuffer.append(p, size);
				break;
			}

			m_transferBuffer.append(p, leftoverSize);
			hdr = (io.UsbMonTransferHdr const*)m_transferBuffer.m_p; // update hdr after append
			p += leftoverSize;
			size -= leftoverSize;
		}

		size_t leftoverSize = transferSize - m_transferBuffer.m_size;
		if (size < leftoverSize) {
			m_transferBuffer.append(p, size);
			break;
		}

		if (hdr.m_transferType == -1) { // ignore non-transfer URBs
			m_transferBuffer.clear();
			p += leftoverSize;
			size -= leftoverSize;
			continue;
		}

		switch (hdr.m_transferType) {
		case io.UsbTransferType.Control:
			m_logWriter.write(
				UsbLogRecordCode.ControlTransfer,
				&hdr.m_controlSetup,
				sizeof(hdr.m_controlSetup)
			);

			break;

		case io.UsbTransferType.Isochronous:
			if (m_prevTransferEndpoint != hdr.m_endpoint) // otherwise, simply append the payload
				m_logWriter.write(UsbLogRecordCode.IsochronousTransfer, &hdr.m_endpoint, sizeof(uint8_t));
			break;

		case io.UsbTransferType.Bulk:
			if (m_prevTransferEndpoint != hdr.m_endpoint) // otherwise, simply append the payload
				m_logWriter.write(UsbLogRecordCode.BulkTransfer, &hdr.m_endpoint, sizeof(uint8_t));
			break;

		case io.UsbTransferType.Interrupt:
			if (m_prevTransferEndpoint != hdr.m_endpoint) // otherwise, simply append the payload
				m_logWriter.write(UsbLogRecordCode.InterruptTransfer, &hdr.m_endpoint, sizeof(uint8_t));
			break;
		}

		if (hdr.m_transferType != -1) { // not a real transfer (could be USBPcap meta-information)
			if (hdr.m_status != 0)
				writeTransferError(hdr.m_status);
			else if (hdr.m_capturedDataSize) {
				uint64_t recordCode = (hdr.m_endpoint & 0x80) ?
					log.StdRecordCode.Rx :
					log.StdRecordCode.Tx;

				if (hdr.m_transferType == io.UsbTransferType.Isochronous)
					writeIsoTransferPayload(recordCode, hdr);
				else
					m_logWriter.write(
						recordCode,
						hdr + 1,
						m_transferBuffer.m_size - sizeof(io.UsbMonTransferHdr),
						p,
						leftoverSize
					);
			}

			if (hdr.m_capturedDataSize < hdr.m_originalDataSize) {
				uint32_t truncated = hdr.m_originalDataSize - hdr.m_capturedDataSize;
				m_logWriter.write(UsbLogRecordCode.TruncatedCapture, &truncated, sizeof(truncated));
			}
		}

		m_prevTransferEndpoint = hdr.m_endpoint;
		m_transferBuffer.clear();
		p += leftoverSize;
		size -= leftoverSize;
	}
}

void UsbMonSession.writeTransferError(uint_t status) {
	UsbTransferErrorParams params;
	params.m_osKind = sys.g_systemInfo.m_osKind;
	params.m_status = status;
	m_logWriter.write(UsbLogRecordCode.TransferError, &params, sizeof(params));
}

void UsbMonSession.writeIsoTransferPayload(
	uint64_t recordCode,
	io.UsbMonTransferHdr const* hdr
) {
	io.UsbIsoPacket const* packet = (io.UsbIsoPacket const*)(hdr + 1);
	io.UsbIsoPacket const* end = packet + hdr.m_isoHdr.m_packetCount;
	void const* p = end;
	uint64_t capturedDataSize64 = hdr.m_capturedDataSize;

	while (packet < end) {
		if (packet.m_status != 0)
			writeTransferError(packet.m_status);
		else if ((uint64_t)packet.m_offset + packet.m_length <= capturedDataSize64)
			m_logWriter.write(recordCode, p + packet.m_offset, packet.m_length);

		packet++;
	}
}

void UsbMonSession.load(doc.Storage* storage) {
	uint_t vid = storage.readInt("deviceVid");
	uint_t pid = storage.readInt("devicePid");
	uint_t captureDeviceId = storage.readInt("captureDeviceId");
	uint_t address = storage.readInt("deviceAddress");

	size_t index = ui.findUsbMonDeviceComboIndex(m_deviceCombo, vid, pid, captureDeviceId, address);
	if (index != -1)
		m_deviceCombo.m_currentIndex = index;

	if (m_snapshotSizeProp)
		m_snapshotSizeProp.m_value = storage.readInt("snapshotSize", Defaults.SnapshotSize);

	m_kernelBufferSizeProp.m_value = storage.readInt("kernelBufferSize", Defaults.KernelBufferSize);
	m_bufferPropertySet.load(storage);
	m_readBuffer.setSize(m_bufferPropertySet.m_readBufferSizeProp.m_value);
}

void UsbMonSession.save(doc.Storage* storage) {
	io.UsbMonDeviceDesc const* deviceDesc = m_deviceCombo.m_currentData;
	if (deviceDesc) {
		storage.writeInt("deviceVid", deviceDesc.m_vendorId);
		storage.writeInt("devicePid", deviceDesc.m_productId);
		storage.writeInt("captureDeviceId", deviceDesc.m_captureDeviceId);
		storage.writeInt("deviceAddress", deviceDesc.m_address);
	}

	if (m_snapshotSizeProp)
		storage.writeInt("snapshotSize", m_snapshotSizeProp.m_value);

	storage.writeInt("kernelBufferSize", m_kernelBufferSizeProp.m_value);
	m_bufferPropertySet.save(storage);
}

void UsbMonSession.updateProperties() {
	m_deviceProp.m_currentIndex = m_deviceCombo.m_currentIndex;
}

bool errorcode UsbMonSession.applyProperties() {
	m_deviceCombo.m_currentIndex = m_deviceProp.m_currentIndex;
	m_readBuffer.setSize(m_bufferPropertySet.m_readBufferSizeProp.m_value);

	if (m_state != State.Opened)
		return true;

	if (sys.g_systemInfo.m_osKind != sys.OsKind.Windows) // USBPcap can BSOD on kernel buffer size change
		m_monitor.m_kernelBufferSize = m_kernelBufferSizeProp.m_value;

	m_monitor.m_readBlockSize = m_bufferPropertySet.m_readBlockSizeProp.m_value;
	m_monitor.m_readBufferSize = m_bufferPropertySet.m_readBufferSizeProp.m_value;
	return true;
}

void UsbMonSession.restoreDefaultProperties() {
	if (m_snapshotSizeProp)
		m_snapshotSizeProp.m_value = Defaults.SnapshotSize;

	m_kernelBufferSizeProp.m_value = Defaults.KernelBufferSize;
	m_bufferPropertySet.restoreDefaults();
}

reactor UsbMonSession.m_uiReactor {
	m_title = $"USB $(m_deviceCombo.m_currentText)";
	m_actionTable[ActionId.Capture].m_text = m_state ? "Stop Capture" : "Capture";
	m_actionTable[ActionId.Capture].m_icon = m_iconTable[m_state ? IconId.StopCapture : IconId.Capture];
	m_statusPaneTable[StatusPaneId.State].m_text = m_state ? "Capturing" : "Closed";

	if (m_snapshotSizeProp)
		m_snapshotSizeProp.m_isEnabled = !m_state;

	m_kernelBufferSizeProp.m_isEnabled = !m_state || sys.g_systemInfo.m_osKind != sys.OsKind.Windows;
}

//..............................................................................
