mcicda: Exclude unused headers.
[wine] / dlls / 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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_hWakeEvent;
48 static    CRITICAL_SECTION      TIME_cbcrst;
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("%04x:CallBack => lpFunc=%p wTimerID=%04X dwUser=%08X dwTriggerTime %d(delta %d)\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     LeaveCriticalSection(&iData->cs);
204
205     EnterCriticalSection(&TIME_cbcrst);
206     while (idx > 0) TIME_TriggerCallBack(&lpTimers[--idx]);
207     LeaveCriticalSection(&TIME_cbcrst);
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 %d(%d) 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         InitializeCriticalSection(&TIME_cbcrst);
270         TIME_cbcrst.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": WINMM.TIME_cbcrst");
271     }
272 }
273
274 /**************************************************************************
275  *                              TIME_MMTimeStop
276  */
277 void    TIME_MMTimeStop(void)
278 {
279     if (TIME_hMMTimer) {
280
281         TIME_TimeToDie = TRUE;
282         SetEvent(TIME_hWakeEvent);
283
284         /* FIXME: in the worst case, we're going to wait 65 seconds here :-( */
285         WaitForSingleObject(TIME_hMMTimer, INFINITE);
286
287         CloseHandle(TIME_hMMTimer);
288         CloseHandle(TIME_hWakeEvent);
289         TIME_hMMTimer = 0;
290         TIME_cbcrst.DebugInfo->Spare[0] = 0;
291         DeleteCriticalSection(&TIME_cbcrst);
292         TIME_TimersList = NULL;
293     }
294 }
295
296 /**************************************************************************
297  *                              timeGetSystemTime       [WINMM.@]
298  */
299 MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
300 {
301
302     if (wSize >= sizeof(*lpTime)) {
303         lpTime->wType = TIME_MS;
304         lpTime->u.ms = GetTickCount();
305
306     }
307
308     return 0;
309 }
310
311 /**************************************************************************
312  *                              TIME_SetEventInternal   [internal]
313  */
314 WORD    TIME_SetEventInternal(UINT wDelay, UINT wResol,
315                               LPTIMECALLBACK lpFunc, DWORD dwUser, UINT wFlags)
316 {
317     WORD                wNewID = 0;
318     LPWINE_TIMERENTRY   lpNewTimer;
319     LPWINE_TIMERENTRY   lpTimer;
320
321     TRACE("(%u, %u, %p, %08X, %04X);\n", wDelay, wResol, lpFunc, dwUser, wFlags);
322
323     if (wDelay < MMSYSTIME_MININTERVAL || wDelay > MMSYSTIME_MAXINTERVAL)
324         return 0;
325
326     lpNewTimer = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
327     if (lpNewTimer == NULL)
328         return 0;
329
330     TIME_MMTimeStart();
331
332     lpNewTimer->wDelay = wDelay;
333     lpNewTimer->dwTriggerTime = GetTickCount() + wDelay;
334
335     /* FIXME - wResol is not respected, although it is not clear
336                that we could change our precision meaningfully  */
337     lpNewTimer->wResol = wResol;
338     lpNewTimer->lpFunc = lpFunc;
339     lpNewTimer->dwUser = dwUser;
340     lpNewTimer->wFlags = wFlags;
341
342     EnterCriticalSection(&WINMM_IData.cs);
343
344     for (lpTimer = TIME_TimersList; lpTimer != NULL; lpTimer = lpTimer->lpNext) {
345         wNewID = max(wNewID, lpTimer->wTimerID);
346     }
347
348     lpNewTimer->lpNext = TIME_TimersList;
349     TIME_TimersList = lpNewTimer;
350     lpNewTimer->wTimerID = wNewID + 1;
351
352     LeaveCriticalSection(&WINMM_IData.cs);
353
354     /* Wake the service thread in case there is work to be done */
355     SetEvent(TIME_hWakeEvent);
356
357     TRACE("=> %u\n", wNewID + 1);
358
359     return wNewID + 1;
360 }
361
362 /**************************************************************************
363  *                              timeSetEvent            [WINMM.@]
364  */
365 MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
366                             DWORD_PTR dwUser, UINT wFlags)
367 {
368     if (wFlags & WINE_TIMER_IS32)
369         WARN("Unknown windows flag... wine internally used.. ooch\n");
370
371     return TIME_SetEventInternal(wDelay, wResol, lpFunc,
372                                  dwUser, wFlags|WINE_TIMER_IS32);
373 }
374
375 /**************************************************************************
376  *                              timeKillEvent           [WINMM.@]
377  */
378 MMRESULT WINAPI timeKillEvent(UINT wID)
379 {
380     LPWINE_TIMERENTRY   lpSelf = NULL, *lpTimer;
381
382     TRACE("(%u)\n", wID);
383     EnterCriticalSection(&WINMM_IData.cs);
384     /* remove WINE_TIMERENTRY from list */
385     for (lpTimer = &TIME_TimersList; *lpTimer; lpTimer = &(*lpTimer)->lpNext) {
386         if (wID == (*lpTimer)->wTimerID) {
387             lpSelf = *lpTimer;
388             /* unlink timer of id 'wID' */
389             *lpTimer = (*lpTimer)->lpNext;
390             break;
391         }
392     }
393     LeaveCriticalSection(&WINMM_IData.cs);
394
395     if (!lpSelf)
396     {
397         WARN("wID=%u is not a valid timer ID\n", wID);
398         return MMSYSERR_INVALPARAM;
399     }
400     if (lpSelf->wFlags & TIME_KILL_SYNCHRONOUS)
401         EnterCriticalSection(&TIME_cbcrst);
402     HeapFree(GetProcessHeap(), 0, lpSelf);
403     if (lpSelf->wFlags & TIME_KILL_SYNCHRONOUS)
404         LeaveCriticalSection(&TIME_cbcrst);
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 mciavi32.dll run correctly
472      */
473     if (pFnReleaseThunkLock) pFnReleaseThunkLock(&count);
474     if (pFnRestoreThunkLock) pFnRestoreThunkLock(count);
475 #endif
476
477     return GetTickCount();
478 }