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