
/*
 * Copyright 2011-2022 Cuberite Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// SleepResolutionBooster.h

// Increases the accuracy of Sleep on Windows (GH #5140).

// This file MUST NOT be included from anywhere other than main.cpp.





#ifdef _WIN32

#include <timeapi.h>





static TIMECAPS g_Resolution;





namespace SleepResolutionBooster
{
	static void Register()
	{
		// Default sleep resolution on Windows isn't accurate enough (GH #5140) so try to boost it:
		if (
			(timeGetDevCaps(&g_Resolution, sizeof(g_Resolution)) == MMSYSERR_NOERROR) &&
			(timeBeginPeriod(g_Resolution.wPeriodMin) == MMSYSERR_NOERROR)
		)
		{
			return;
		}

		// Max < Min sentinel for failure, to prevent bogus timeEndPeriod calls:
		g_Resolution.wPeriodMax = 0;
		g_Resolution.wPeriodMin = 1;
	}

	static void Unregister()
	{
		if (g_Resolution.wPeriodMax >= g_Resolution.wPeriodMin)
		{
			timeEndPeriod(g_Resolution.wPeriodMin);
		}
	}
};

#else

namespace SleepResolutionBooster
{
	static void Register()
	{
	}

	static void Unregister()
	{
	}
};

#endif
