Visual C++ backend for rbuild (for now just a hacked mingw backend) and related compi...
[reactos.git] / dll / win32 / winmm / time.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2
3 /*
4 * MMSYSTEM time functions
5 *
6 * Copyright 1993 Martin Ayotte
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <time.h>
28 #ifdef HAVE_SYS_TIME_H
29 # include <sys/time.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "mmsystem.h"
38
39 #include "winemm.h"
40
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(mmtime);
44
45 static HANDLE TIME_hMMTimer;
46 static LPWINE_TIMERENTRY TIME_TimersList;
47 static HANDLE TIME_hKillEvent;
48 static HANDLE TIME_hWakeEvent;
49 static BOOL TIME_TimeToDie = TRUE;
50
51 /*
52 * Some observations on the behavior of winmm on Windows.
53 * First, the call to timeBeginPeriod(xx) can never be used
54 * to raise the timer resolution, only lower it.
55 *
56 * Second, a brief survey of a variety of Win 2k and Win X
57 * machines showed that a 'standard' (aka default) timer
58 * resolution was 1 ms (Win9x is documented as being 1). However, one
59 * machine had a standard timer resolution of 10 ms.
60 *
61 * Further, if we set our default resolution to 1,
62 * the implementation of timeGetTime becomes GetTickCount(),
63 * and we can optimize the code to reduce overhead.
64 *
65 * Additionally, a survey of Event behaviors shows that
66 * if we request a Periodic event every 50 ms, then Windows
67 * makes sure to trigger that event 20 times in the next
68 * second. If delays prevent that from happening on exact
69 * schedule, Windows will trigger the events as close
70 * to the original schedule as is possible, and will eventually
71 * bring the event triggers back onto a schedule that is
72 * consistent with what would have happened if there were
73 * no delays.
74 *
75 * Jeremy White, October 2004
76 */
77 #define MMSYSTIME_MININTERVAL (1)
78 #define MMSYSTIME_MAXINTERVAL (65535)
79
80
81 static void TIME_TriggerCallBack(LPWINE_TIMERENTRY lpTimer)
82 {
83 TRACE("%04lx:CallBack => lpFunc=%p wTimerID=%04X dwUser=%08lX dwTriggerTime %ld(delta %ld)\n",
84 GetCurrentThreadId(), lpTimer->lpFunc, lpTimer->wTimerID, lpTimer->dwUser,
85 lpTimer->dwTriggerTime, GetTickCount() - lpTimer->dwTriggerTime);
86
87 /* - TimeProc callback that is called here is something strange, under Windows 3.1x it is called
88 * during interrupt time, is allowed to execute very limited number of API calls (like
89 * PostMessage), and must reside in DLL (therefore uses stack of active application). So I
90 * guess current implementation via SetTimer has to be improved upon.
91 */
92 switch (lpTimer->wFlags & 0x30) {
93 case TIME_CALLBACK_FUNCTION:
94 if (lpTimer->wFlags & WINE_TIMER_IS32)
95 (lpTimer->lpFunc)(lpTimer->wTimerID, 0, lpTimer->dwUser, 0, 0);
96 else if (pFnCallMMDrvFunc16)
97 pFnCallMMDrvFunc16((DWORD)lpTimer->lpFunc, lpTimer->wTimerID, 0,
98 lpTimer->dwUser, 0, 0);
99 break;
100 case TIME_CALLBACK_EVENT_SET:
101 SetEvent((HANDLE)lpTimer->lpFunc);
102 break;
103 case TIME_CALLBACK_EVENT_PULSE:
104 PulseEvent((HANDLE)lpTimer->lpFunc);
105 break;
106 default:
107 FIXME("Unknown callback type 0x%04x for mmtime callback (%p), ignored.\n",
108 lpTimer->wFlags, lpTimer->lpFunc);
109 break;
110 }
111 }
112
113 /**************************************************************************
114 * TIME_MMSysTimeCallback
115 */
116 static DWORD CALLBACK TIME_MMSysTimeCallback(LPWINE_MM_IDATA iData)
117 {
118 static int nSizeLpTimers;
119 static LPWINE_TIMERENTRY lpTimers;
120
121 LPWINE_TIMERENTRY timer, *ptimer, *next_ptimer;
122 int idx;
123 DWORD cur_time;
124 DWORD delta_time;
125 DWORD ret_time = INFINITE;
126 DWORD adjust_time;
127
128
129 /* optimize for the most frequent case - no events */
130 if (! TIME_TimersList)
131 return(ret_time);
132
133 /* since timeSetEvent() and timeKillEvent() can be called
134 * from 16 bit code, there are cases where win16 lock is
135 * locked upon entering timeSetEvent(), and then the mm timer
136 * critical section is locked. This function cannot call the
137 * timer callback with the crit sect locked (because callback
138 * may need to acquire Win16 lock, thus providing a deadlock
139 * situation).
140 * To cope with that, we just copy the WINE_TIMERENTRY struct
141 * that need to trigger the callback, and call it without the
142 * mm timer crit sect locked.
143 * the hKillTimeEvent is used to mark the section where we
144 * handle the callbacks so we can do synchronous kills.
145 * EPP 99/07/13, updated 04/01/10
146 */
147 idx = 0;
148 cur_time = GetTickCount();
149
150 EnterCriticalSection(&iData->cs);
151 for (ptimer = &TIME_TimersList; *ptimer != NULL; ) {
152 timer = *ptimer;
153 next_ptimer = &timer->lpNext;
154 if (cur_time >= timer->dwTriggerTime)
155 {
156 if (timer->lpFunc) {
157 if (idx == nSizeLpTimers) {
158 if (lpTimers)
159 lpTimers = (LPWINE_TIMERENTRY)
160 HeapReAlloc(GetProcessHeap(), 0, lpTimers,
161 ++nSizeLpTimers * sizeof(WINE_TIMERENTRY));
162 else
163 lpTimers = (LPWINE_TIMERENTRY)
164 HeapAlloc(GetProcessHeap(), 0,
165 ++nSizeLpTimers * sizeof(WINE_TIMERENTRY));
166 }
167 lpTimers[idx++] = *timer;
168
169 }
170
171 /* Update the time after we make the copy to preserve
172 the original trigger time */
173 timer->dwTriggerTime += timer->wDelay;
174
175 /* TIME_ONESHOT is defined as 0 */
176 if (!(timer->wFlags & TIME_PERIODIC))
177 {
178 /* unlink timer from timers list */
179 *ptimer = *next_ptimer;
180 HeapFree(GetProcessHeap(), 0, timer);
181
182 /* We don't need to trigger oneshots again */
183 delta_time = INFINITE;
184 }
185 else
186 {
187 /* Compute when this event needs this function
188 to be called again */
189 if (timer->dwTriggerTime <= cur_time)
190 delta_time = 0;
191 else
192 delta_time = timer->dwTriggerTime - cur_time;
193 }
194 }
195 else
196 delta_time = timer->dwTriggerTime - cur_time;
197
198 /* Determine when we need to return to this function */
199 ret_time = min(ret_time, delta_time);
200
201 ptimer = next_ptimer;
202 }
203 if (TIME_hKillEvent) ResetEvent(TIME_hKillEvent);
204 LeaveCriticalSection(&iData->cs);
205
206 while (idx > 0) TIME_TriggerCallBack(&lpTimers[--idx]);
207 if (TIME_hKillEvent) SetEvent(TIME_hKillEvent);
208
209 /* Finally, adjust the recommended wait time downward
210 by the amount of time the processing routines
211 actually took */
212 adjust_time = GetTickCount() - cur_time;
213 if (adjust_time > ret_time)
214 ret_time = 0;
215 else
216 ret_time -= adjust_time;
217
218 /* We return the amount of time our caller should sleep
219 before needing to check in on us again */
220 return(ret_time);
221 }
222
223 /**************************************************************************
224 * TIME_MMSysTimeThread
225 */
226 static DWORD CALLBACK TIME_MMSysTimeThread(LPVOID arg)
227 {
228 LPWINE_MM_IDATA iData = (LPWINE_MM_IDATA)arg;
229 DWORD sleep_time;
230 DWORD rc;
231
232 TRACE("Starting main winmm thread\n");
233
234 /* FIXME: As an optimization, we could have
235 this thread die when there are no more requests
236 pending, and then get recreated on the first
237 new event; it's not clear if that would be worth
238 it or not. */
239
240 while (! TIME_TimeToDie)
241 {
242 sleep_time = TIME_MMSysTimeCallback(iData);
243
244 if (sleep_time == 0)
245 continue;
246
247 rc = WaitForSingleObject(TIME_hWakeEvent, sleep_time);
248 if (rc != WAIT_TIMEOUT && rc != WAIT_OBJECT_0)
249 {
250 FIXME("Unexpected error %ld(%ld) in timer thread\n", rc, GetLastError());
251 break;
252 }
253 }
254 TRACE("Exiting main winmm thread\n");
255 return 0;
256 }
257
258 /**************************************************************************
259 * TIME_MMTimeStart
260 */
261 void TIME_MMTimeStart(void)
262 {
263 if (!TIME_hMMTimer) {
264 TIME_TimersList = NULL;
265 TIME_hWakeEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
266 TIME_TimeToDie = FALSE;
267 TIME_hMMTimer = CreateThread(NULL, 0, TIME_MMSysTimeThread, &WINMM_IData, 0, NULL);
268 SetThreadPriority(TIME_hMMTimer, THREAD_PRIORITY_TIME_CRITICAL);
269 }
270 }
271
272 /**************************************************************************
273 * TIME_MMTimeStop
274 */
275 void TIME_MMTimeStop(void)
276 {
277 if (TIME_hMMTimer) {
278
279 TIME_TimeToDie = TRUE;
280 SetEvent(TIME_hWakeEvent);
281
282 /* FIXME: in the worst case, we're going to wait 65 seconds here :-( */
283 WaitForSingleObject(TIME_hMMTimer, INFINITE);
284
285 CloseHandle(TIME_hMMTimer);
286 CloseHandle(TIME_hWakeEvent);
287 TIME_hMMTimer = 0;
288 TIME_TimersList = NULL;
289 }
290 }
291
292 /**************************************************************************
293 * timeGetSystemTime [WINMM.@]
294 */
295 MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
296 {
297
298 if (wSize >= sizeof(*lpTime)) {
299 lpTime->wType = TIME_MS;
300 lpTime->u.ms = GetTickCount();
301
302 }
303
304 return 0;
305 }
306
307 /**************************************************************************
308 * TIME_SetEventInternal [internal]
309 */
310 WORD TIME_SetEventInternal(UINT wDelay, UINT wResol,
311 LPTIMECALLBACK lpFunc, DWORD dwUser, UINT wFlags)
312 {
313 WORD wNewID = 0;
314 LPWINE_TIMERENTRY lpNewTimer;
315 LPWINE_TIMERENTRY lpTimer;
316
317 TRACE("(%u, %u, %p, %08lX, %04X);\n", wDelay, wResol, lpFunc, dwUser, wFlags);
318
319 if (wDelay < MMSYSTIME_MININTERVAL || wDelay > MMSYSTIME_MAXINTERVAL)
320 return 0;
321
322 lpNewTimer = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
323 if (lpNewTimer == NULL)
324 return 0;
325
326 TIME_MMTimeStart();
327
328 lpNewTimer->wDelay = wDelay;
329 lpNewTimer->dwTriggerTime = GetTickCount() + wDelay;
330
331 /* FIXME - wResol is not respected, although it is not clear
332 that we could change our precision meaningfully */
333 lpNewTimer->wResol = wResol;
334 lpNewTimer->lpFunc = lpFunc;
335 lpNewTimer->dwUser = dwUser;
336 lpNewTimer->wFlags = wFlags;
337
338 EnterCriticalSection(&WINMM_IData.cs);
339
340 if ((wFlags & TIME_KILL_SYNCHRONOUS) && !TIME_hKillEvent)
341 TIME_hKillEvent = CreateEventW(NULL, TRUE, TRUE, NULL);
342
343 for (lpTimer = TIME_TimersList; lpTimer != NULL; lpTimer = lpTimer->lpNext) {
344 wNewID = max(wNewID, lpTimer->wTimerID);
345 }
346
347 lpNewTimer->lpNext = TIME_TimersList;
348 TIME_TimersList = lpNewTimer;
349 lpNewTimer->wTimerID = wNewID + 1;
350
351 LeaveCriticalSection(&WINMM_IData.cs);
352
353 /* Wake the service thread in case there is work to be done */
354 SetEvent(TIME_hWakeEvent);
355
356 TRACE("=> %u\n", wNewID + 1);
357
358 return wNewID + 1;
359 }
360
361 /**************************************************************************
362 * timeSetEvent [WINMM.@]
363 */
364 MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
365 DWORD_PTR dwUser, UINT wFlags)
366 {
367 if (wFlags & WINE_TIMER_IS32)
368 WARN("Unknown windows flag... wine internally used.. ooch\n");
369
370 return TIME_SetEventInternal(wDelay, wResol, lpFunc,
371 dwUser, wFlags|WINE_TIMER_IS32);
372 }
373
374 /**************************************************************************
375 * timeKillEvent [WINMM.@]
376 */
377 MMRESULT WINAPI timeKillEvent(UINT wID)
378 {
379 LPWINE_TIMERENTRY lpSelf = NULL, *lpTimer;
380
381 TRACE("(%u)\n", wID);
382 EnterCriticalSection(&WINMM_IData.cs);
383 /* remove WINE_TIMERENTRY from list */
384 for (lpTimer = &TIME_TimersList; *lpTimer; lpTimer = &(*lpTimer)->lpNext) {
385 if (wID == (*lpTimer)->wTimerID) {
386 lpSelf = *lpTimer;
387 /* unlink timer of id 'wID' */
388 *lpTimer = (*lpTimer)->lpNext;
389 break;
390 }
391 }
392 LeaveCriticalSection(&WINMM_IData.cs);
393
394 if (!lpSelf)
395 {
396 WARN("wID=%u is not a valid timer ID\n", wID);
397 return MMSYSERR_INVALPARAM;
398 }
399 if (lpSelf->wFlags & TIME_KILL_SYNCHRONOUS)
400 WaitForSingleObject(TIME_hKillEvent, INFINITE);
401 HeapFree(GetProcessHeap(), 0, lpSelf);
402 return TIMERR_NOERROR;
403 }
404
405 /**************************************************************************
406 * timeGetDevCaps [WINMM.@]
407 */
408 MMRESULT WINAPI timeGetDevCaps(LPTIMECAPS lpCaps, UINT wSize)
409 {
410 TRACE("(%p, %u)\n", lpCaps, wSize);
411
412 if (lpCaps == 0) {
413 WARN("invalid lpCaps\n");
414 return TIMERR_NOCANDO;
415 }
416
417 if (wSize < sizeof(TIMECAPS)) {
418 WARN("invalid wSize\n");
419 return TIMERR_NOCANDO;
420 }
421
422 lpCaps->wPeriodMin = MMSYSTIME_MININTERVAL;
423 lpCaps->wPeriodMax = MMSYSTIME_MAXINTERVAL;
424 return TIMERR_NOERROR;
425 }
426
427 /**************************************************************************
428 * timeBeginPeriod [WINMM.@]
429 */
430 MMRESULT WINAPI timeBeginPeriod(UINT wPeriod)
431 {
432 if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
433 return TIMERR_NOCANDO;
434
435 if (wPeriod > MMSYSTIME_MININTERVAL)
436 {
437 WARN("Stub; we set our timer resolution at minimum\n");
438 }
439
440 return 0;
441 }
442
443 /**************************************************************************
444 * timeEndPeriod [WINMM.@]
445 */
446 MMRESULT WINAPI timeEndPeriod(UINT wPeriod)
447 {
448 if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
449 return TIMERR_NOCANDO;
450
451 if (wPeriod > MMSYSTIME_MININTERVAL)
452 {
453 WARN("Stub; we set our timer resolution at minimum\n");
454 }
455 return 0;
456 }
457
458 /**************************************************************************
459 * timeGetTime [MMSYSTEM.607]
460 * timeGetTime [WINMM.@]
461 */
462 DWORD WINAPI timeGetTime(void)
463 {
464 #if defined(COMMENTOUTPRIORTODELETING)
465 DWORD count;
466
467 /* FIXME: releasing the win16 lock here is a temporary hack (I hope)
468 * that lets mciavi.drv run correctly
469 */
470 if (pFnReleaseThunkLock) pFnReleaseThunkLock(&count);
471 if (pFnRestoreThunkLock) pFnRestoreThunkLock(count);
472 #endif
473
474 return GetTickCount();
475 }