global-timer.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * This tool is used by the utimer test, and it allows us to
  4. * count the ticks of a global timer in a certain time frame
  5. * (which is set by `timeout` parameter).
  6. *
  7. * Author: Ivan Orlov <ivan.orlov0322@gmail.com>
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <alsa/asoundlib.h>
  12. #include <time.h>
  13. static int ticked;
  14. static void async_callback(snd_async_handler_t *ahandler)
  15. {
  16. ticked++;
  17. }
  18. static char timer_name[64];
  19. static void bind_to_timer(int device, int subdevice, int timeout)
  20. {
  21. snd_timer_t *handle;
  22. snd_timer_params_t *params;
  23. snd_async_handler_t *ahandler;
  24. time_t end;
  25. sprintf(timer_name, "hw:CLASS=%d,SCLASS=%d,DEV=%d,SUBDEV=%d",
  26. SND_TIMER_CLASS_GLOBAL, SND_TIMER_SCLASS_NONE,
  27. device, subdevice);
  28. snd_timer_params_alloca(&params);
  29. if (snd_timer_open(&handle, timer_name, SND_TIMER_OPEN_NONBLOCK) < 0) {
  30. perror("Can't open the timer");
  31. exit(EXIT_FAILURE);
  32. }
  33. snd_timer_params_set_auto_start(params, 1);
  34. snd_timer_params_set_ticks(params, 1);
  35. if (snd_timer_params(handle, params) < 0) {
  36. perror("Can't set timer params");
  37. exit(EXIT_FAILURE);
  38. }
  39. if (snd_async_add_timer_handler(&ahandler, handle, async_callback, NULL) < 0) {
  40. perror("Can't create a handler");
  41. exit(EXIT_FAILURE);
  42. }
  43. end = time(NULL) + timeout;
  44. if (snd_timer_start(handle) < 0) {
  45. perror("Failed to start the timer");
  46. exit(EXIT_FAILURE);
  47. }
  48. printf("Timer has started\n");
  49. while (time(NULL) <= end) {
  50. /*
  51. * Waiting for the timeout to elapse. Can't use sleep here, as it gets
  52. * constantly interrupted by the signal from the timer (SIGIO)
  53. */
  54. }
  55. snd_timer_stop(handle);
  56. snd_timer_close(handle);
  57. }
  58. int main(int argc, char *argv[])
  59. {
  60. int device, subdevice, timeout;
  61. if (argc < 4) {
  62. perror("Usage: %s <device> <subdevice> <timeout>");
  63. return EXIT_FAILURE;
  64. }
  65. setlinebuf(stdout);
  66. device = atoi(argv[1]);
  67. subdevice = atoi(argv[2]);
  68. timeout = atoi(argv[3]);
  69. bind_to_timer(device, subdevice, timeout);
  70. printf("Total ticks count: %d\n", ticked);
  71. return EXIT_SUCCESS;
  72. }