OSDN Git Service

* [BugFix] Replace usleep() func to My MicroSleep() Func. ( for usleep() func precis...
[playumidi/playumidi.git] / src / micro_sleep.c
diff --git a/src/micro_sleep.c b/src/micro_sleep.c
new file mode 100644 (file)
index 0000000..a381ddc
--- /dev/null
@@ -0,0 +1,79 @@
+
+#define        PLAYUMIDI_SRC_MSLEEP
+
+#include<stdio.h>
+#include<unistd.h>
+#include<sys/time.h>
+#include"playumidi.h"
+
+
+long   gl_min_usleep   = DEFAULT_MIN_SLEEP;
+
+
+/* ===================================================================*/
+EXTERN_FUNC_MSLEEP
+long   MSleep_Ajust(
+                       void )          {
+
+       int                                     i_cnt;
+       long                            l_times;
+       long                            l_value;
+       struct  timeval         tv_start;
+       struct  timeval         tv_end;
+
+       l_times         = 0;
+       for( i_cnt = 0; i_cnt < MSLEEP_AJUST_COUNT; i_cnt++ )   {
+
+               gettimeofday( &tv_start, NULL );
+               usleep( MSLEEP_USLEEP_TIME );
+               gettimeofday( &tv_end, NULL );
+
+               if( tv_start.tv_sec == tv_end.tv_sec )  {
+                       l_value = tv_end.tv_usec - tv_start.tv_usec;
+               } else  {
+                       l_value = (tv_end.tv_sec - tv_start.tv_sec) * 1000000;
+                       l_value += (tv_end.tv_usec + (1000000 - tv_start.tv_usec));
+               }
+
+               l_times         += l_value;
+       }
+       
+       l_times         /= MSLEEP_AJUST_COUNT; 
+       
+       gl_min_usleep   = l_times + (l_times / 12); 
+
+       return gl_min_usleep;
+}
+
+
+/* ===================================================================*/
+EXTERN_FUNC_MSLEEP
+int            MSleep_MicroSleep(
+                       long    l_usleep )      {
+       
+       long    l_diff;
+       struct  timeval         tv_start;
+       struct  timeval         tv_end;
+
+       gettimeofday( &tv_start, NULL );
+       l_diff  = 0;
+       do      {
+               if( gl_min_usleep < (l_usleep-l_diff) )
+                       { usleep( MSLEEP_USLEEP_TIME ); }
+
+               gettimeofday( &tv_end, NULL );
+
+               if( tv_start.tv_sec == tv_end.tv_sec )  {
+                       l_diff  = tv_end.tv_usec - tv_start.tv_usec;
+               } else if( tv_start.tv_sec + 1 == tv_end.tv_sec )       {
+                       l_diff  = (tv_end.tv_usec + (1000000 - tv_start.tv_usec));
+               } else  {
+                       l_diff  = (tv_end.tv_sec - tv_start.tv_sec) * 1000000;
+                       l_diff  += (tv_end.tv_usec + (1000000 - tv_start.tv_usec));
+               }
+
+       }while( l_usleep > l_diff );
+
+       return 0x00;
+}
+