xref: /openbmc/qemu/audio/audio.c (revision 919a0423d8cbdb99e31a9a9d5c49e6e364ddf160)
1  /*
2   * QEMU Audio subsystem
3   *
4   * Copyright (c) 2003-2005 Vassili Karpov (malc)
5   *
6   * Permission is hereby granted, free of charge, to any person obtaining a copy
7   * of this software and associated documentation files (the "Software"), to deal
8   * in the Software without restriction, including without limitation the rights
9   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10   * copies of the Software, and to permit persons to whom the Software is
11   * furnished to do so, subject to the following conditions:
12   *
13   * The above copyright notice and this permission notice shall be included in
14   * all copies or substantial portions of the Software.
15   *
16   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19   * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22   * THE SOFTWARE.
23   */
24  
25  #include "qemu/osdep.h"
26  #include "audio.h"
27  #include "migration/vmstate.h"
28  #include "monitor/monitor.h"
29  #include "qemu/timer.h"
30  #include "qapi/error.h"
31  #include "qapi/clone-visitor.h"
32  #include "qapi/qobject-input-visitor.h"
33  #include "qapi/qapi-visit-audio.h"
34  #include "qapi/qapi-commands-audio.h"
35  #include "qemu/cutils.h"
36  #include "qemu/module.h"
37  #include "qemu/help_option.h"
38  #include "sysemu/sysemu.h"
39  #include "sysemu/replay.h"
40  #include "sysemu/runstate.h"
41  #include "ui/qemu-spice.h"
42  #include "trace.h"
43  
44  #define AUDIO_CAP "audio"
45  #include "audio_int.h"
46  
47  /* #define DEBUG_LIVE */
48  /* #define DEBUG_OUT */
49  /* #define DEBUG_CAPTURE */
50  /* #define DEBUG_POLL */
51  
52  #define SW_NAME(sw) (sw)->name ? (sw)->name : "unknown"
53  
54  
55  /* Order of CONFIG_AUDIO_DRIVERS is import.
56     The 1st one is the one used by default, that is the reason
57      that we generate the list.
58  */
59  const char *audio_prio_list[] = {
60      "spice",
61      CONFIG_AUDIO_DRIVERS
62      "none",
63      "wav",
64      NULL
65  };
66  
67  static QLIST_HEAD(, audio_driver) audio_drivers;
68  static AudiodevListHead audiodevs = QSIMPLEQ_HEAD_INITIALIZER(audiodevs);
69  
70  void audio_driver_register(audio_driver *drv)
71  {
72      QLIST_INSERT_HEAD(&audio_drivers, drv, next);
73  }
74  
75  audio_driver *audio_driver_lookup(const char *name)
76  {
77      struct audio_driver *d;
78      Error *local_err = NULL;
79      int rv;
80  
81      QLIST_FOREACH(d, &audio_drivers, next) {
82          if (strcmp(name, d->name) == 0) {
83              return d;
84          }
85      }
86      rv = audio_module_load(name, &local_err);
87      if (rv > 0) {
88          QLIST_FOREACH(d, &audio_drivers, next) {
89              if (strcmp(name, d->name) == 0) {
90                  return d;
91              }
92          }
93      } else if (rv < 0) {
94          error_report_err(local_err);
95      }
96      return NULL;
97  }
98  
99  static QTAILQ_HEAD(AudioStateHead, AudioState) audio_states =
100      QTAILQ_HEAD_INITIALIZER(audio_states);
101  
102  const struct mixeng_volume nominal_volume = {
103      .mute = 0,
104  #ifdef FLOAT_MIXENG
105      .r = 1.0,
106      .l = 1.0,
107  #else
108      .r = 1ULL << 32,
109      .l = 1ULL << 32,
110  #endif
111  };
112  
113  static bool legacy_config = true;
114  
115  int audio_bug (const char *funcname, int cond)
116  {
117      if (cond) {
118          static int shown;
119  
120          AUD_log (NULL, "A bug was just triggered in %s\n", funcname);
121          if (!shown) {
122              shown = 1;
123              AUD_log (NULL, "Save all your work and restart without audio\n");
124              AUD_log (NULL, "I am sorry\n");
125          }
126          AUD_log (NULL, "Context:\n");
127      }
128  
129      return cond;
130  }
131  
132  static inline int audio_bits_to_index (int bits)
133  {
134      switch (bits) {
135      case 8:
136          return 0;
137  
138      case 16:
139          return 1;
140  
141      case 32:
142          return 2;
143  
144      default:
145          audio_bug ("bits_to_index", 1);
146          AUD_log (NULL, "invalid bits %d\n", bits);
147          return 0;
148      }
149  }
150  
151  void *audio_calloc (const char *funcname, int nmemb, size_t size)
152  {
153      int cond;
154      size_t len;
155  
156      len = nmemb * size;
157      cond = !nmemb || !size;
158      cond |= nmemb < 0;
159      cond |= len < size;
160  
161      if (audio_bug ("audio_calloc", cond)) {
162          AUD_log (NULL, "%s passed invalid arguments to audio_calloc\n",
163                   funcname);
164          AUD_log (NULL, "nmemb=%d size=%zu (len=%zu)\n", nmemb, size, len);
165          return NULL;
166      }
167  
168      return g_malloc0 (len);
169  }
170  
171  void AUD_vlog (const char *cap, const char *fmt, va_list ap)
172  {
173      if (cap) {
174          fprintf(stderr, "%s: ", cap);
175      }
176  
177      vfprintf(stderr, fmt, ap);
178  }
179  
180  void AUD_log (const char *cap, const char *fmt, ...)
181  {
182      va_list ap;
183  
184      va_start (ap, fmt);
185      AUD_vlog (cap, fmt, ap);
186      va_end (ap);
187  }
188  
189  static void audio_print_settings (struct audsettings *as)
190  {
191      dolog ("frequency=%d nchannels=%d fmt=", as->freq, as->nchannels);
192  
193      switch (as->fmt) {
194      case AUDIO_FORMAT_S8:
195          AUD_log (NULL, "S8");
196          break;
197      case AUDIO_FORMAT_U8:
198          AUD_log (NULL, "U8");
199          break;
200      case AUDIO_FORMAT_S16:
201          AUD_log (NULL, "S16");
202          break;
203      case AUDIO_FORMAT_U16:
204          AUD_log (NULL, "U16");
205          break;
206      case AUDIO_FORMAT_S32:
207          AUD_log (NULL, "S32");
208          break;
209      case AUDIO_FORMAT_U32:
210          AUD_log (NULL, "U32");
211          break;
212      case AUDIO_FORMAT_F32:
213          AUD_log (NULL, "F32");
214          break;
215      default:
216          AUD_log (NULL, "invalid(%d)", as->fmt);
217          break;
218      }
219  
220      AUD_log (NULL, " endianness=");
221      switch (as->endianness) {
222      case 0:
223          AUD_log (NULL, "little");
224          break;
225      case 1:
226          AUD_log (NULL, "big");
227          break;
228      default:
229          AUD_log (NULL, "invalid");
230          break;
231      }
232      AUD_log (NULL, "\n");
233  }
234  
235  static int audio_validate_settings (struct audsettings *as)
236  {
237      int invalid;
238  
239      invalid = as->nchannels < 1;
240      invalid |= as->endianness != 0 && as->endianness != 1;
241  
242      switch (as->fmt) {
243      case AUDIO_FORMAT_S8:
244      case AUDIO_FORMAT_U8:
245      case AUDIO_FORMAT_S16:
246      case AUDIO_FORMAT_U16:
247      case AUDIO_FORMAT_S32:
248      case AUDIO_FORMAT_U32:
249      case AUDIO_FORMAT_F32:
250          break;
251      default:
252          invalid = 1;
253          break;
254      }
255  
256      invalid |= as->freq <= 0;
257      return invalid ? -1 : 0;
258  }
259  
260  static int audio_pcm_info_eq (struct audio_pcm_info *info, struct audsettings *as)
261  {
262      int bits = 8;
263      bool is_signed = false, is_float = false;
264  
265      switch (as->fmt) {
266      case AUDIO_FORMAT_S8:
267          is_signed = true;
268          /* fall through */
269      case AUDIO_FORMAT_U8:
270          break;
271  
272      case AUDIO_FORMAT_S16:
273          is_signed = true;
274          /* fall through */
275      case AUDIO_FORMAT_U16:
276          bits = 16;
277          break;
278  
279      case AUDIO_FORMAT_F32:
280          is_float = true;
281          /* fall through */
282      case AUDIO_FORMAT_S32:
283          is_signed = true;
284          /* fall through */
285      case AUDIO_FORMAT_U32:
286          bits = 32;
287          break;
288  
289      default:
290          abort();
291      }
292      return info->freq == as->freq
293          && info->nchannels == as->nchannels
294          && info->is_signed == is_signed
295          && info->is_float == is_float
296          && info->bits == bits
297          && info->swap_endianness == (as->endianness != AUDIO_HOST_ENDIANNESS);
298  }
299  
300  void audio_pcm_init_info (struct audio_pcm_info *info, struct audsettings *as)
301  {
302      int bits = 8, mul;
303      bool is_signed = false, is_float = false;
304  
305      switch (as->fmt) {
306      case AUDIO_FORMAT_S8:
307          is_signed = true;
308          /* fall through */
309      case AUDIO_FORMAT_U8:
310          mul = 1;
311          break;
312  
313      case AUDIO_FORMAT_S16:
314          is_signed = true;
315          /* fall through */
316      case AUDIO_FORMAT_U16:
317          bits = 16;
318          mul = 2;
319          break;
320  
321      case AUDIO_FORMAT_F32:
322          is_float = true;
323          /* fall through */
324      case AUDIO_FORMAT_S32:
325          is_signed = true;
326          /* fall through */
327      case AUDIO_FORMAT_U32:
328          bits = 32;
329          mul = 4;
330          break;
331  
332      default:
333          abort();
334      }
335  
336      info->freq = as->freq;
337      info->bits = bits;
338      info->is_signed = is_signed;
339      info->is_float = is_float;
340      info->nchannels = as->nchannels;
341      info->bytes_per_frame = as->nchannels * mul;
342      info->bytes_per_second = info->freq * info->bytes_per_frame;
343      info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);
344  }
345  
346  void audio_pcm_info_clear_buf (struct audio_pcm_info *info, void *buf, int len)
347  {
348      if (!len) {
349          return;
350      }
351  
352      if (info->is_signed || info->is_float) {
353          memset(buf, 0x00, len * info->bytes_per_frame);
354      } else {
355          switch (info->bits) {
356          case 8:
357              memset(buf, 0x80, len * info->bytes_per_frame);
358              break;
359  
360          case 16:
361              {
362                  int i;
363                  uint16_t *p = buf;
364                  short s = INT16_MAX;
365  
366                  if (info->swap_endianness) {
367                      s = bswap16 (s);
368                  }
369  
370                  for (i = 0; i < len * info->nchannels; i++) {
371                      p[i] = s;
372                  }
373              }
374              break;
375  
376          case 32:
377              {
378                  int i;
379                  uint32_t *p = buf;
380                  int32_t s = INT32_MAX;
381  
382                  if (info->swap_endianness) {
383                      s = bswap32 (s);
384                  }
385  
386                  for (i = 0; i < len * info->nchannels; i++) {
387                      p[i] = s;
388                  }
389              }
390              break;
391  
392          default:
393              AUD_log (NULL, "audio_pcm_info_clear_buf: invalid bits %d\n",
394                       info->bits);
395              break;
396          }
397      }
398  }
399  
400  /*
401   * Capture
402   */
403  static void noop_conv (struct st_sample *dst, const void *src, int samples)
404  {
405      (void) src;
406      (void) dst;
407      (void) samples;
408  }
409  
410  static CaptureVoiceOut *audio_pcm_capture_find_specific(AudioState *s,
411                                                          struct audsettings *as)
412  {
413      CaptureVoiceOut *cap;
414  
415      for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
416          if (audio_pcm_info_eq (&cap->hw.info, as)) {
417              return cap;
418          }
419      }
420      return NULL;
421  }
422  
423  static void audio_notify_capture (CaptureVoiceOut *cap, audcnotification_e cmd)
424  {
425      struct capture_callback *cb;
426  
427  #ifdef DEBUG_CAPTURE
428      dolog ("notification %d sent\n", cmd);
429  #endif
430      for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
431          cb->ops.notify (cb->opaque, cmd);
432      }
433  }
434  
435  static void audio_capture_maybe_changed (CaptureVoiceOut *cap, int enabled)
436  {
437      if (cap->hw.enabled != enabled) {
438          audcnotification_e cmd;
439          cap->hw.enabled = enabled;
440          cmd = enabled ? AUD_CNOTIFY_ENABLE : AUD_CNOTIFY_DISABLE;
441          audio_notify_capture (cap, cmd);
442      }
443  }
444  
445  static void audio_recalc_and_notify_capture (CaptureVoiceOut *cap)
446  {
447      HWVoiceOut *hw = &cap->hw;
448      SWVoiceOut *sw;
449      int enabled = 0;
450  
451      for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
452          if (sw->active) {
453              enabled = 1;
454              break;
455          }
456      }
457      audio_capture_maybe_changed (cap, enabled);
458  }
459  
460  static void audio_detach_capture (HWVoiceOut *hw)
461  {
462      SWVoiceCap *sc = hw->cap_head.lh_first;
463  
464      while (sc) {
465          SWVoiceCap *sc1 = sc->entries.le_next;
466          SWVoiceOut *sw = &sc->sw;
467          CaptureVoiceOut *cap = sc->cap;
468          int was_active = sw->active;
469  
470          if (sw->rate) {
471              st_rate_stop (sw->rate);
472              sw->rate = NULL;
473          }
474  
475          QLIST_REMOVE (sw, entries);
476          QLIST_REMOVE (sc, entries);
477          g_free (sc);
478          if (was_active) {
479              /* We have removed soft voice from the capture:
480                 this might have changed the overall status of the capture
481                 since this might have been the only active voice */
482              audio_recalc_and_notify_capture (cap);
483          }
484          sc = sc1;
485      }
486  }
487  
488  static int audio_attach_capture (HWVoiceOut *hw)
489  {
490      AudioState *s = hw->s;
491      CaptureVoiceOut *cap;
492  
493      audio_detach_capture (hw);
494      for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
495          SWVoiceCap *sc;
496          SWVoiceOut *sw;
497          HWVoiceOut *hw_cap = &cap->hw;
498  
499          sc = g_malloc0(sizeof(*sc));
500  
501          sc->cap = cap;
502          sw = &sc->sw;
503          sw->hw = hw_cap;
504          sw->info = hw->info;
505          sw->empty = 1;
506          sw->active = hw->enabled;
507          sw->conv = noop_conv;
508          sw->ratio = ((int64_t) hw_cap->info.freq << 32) / sw->info.freq;
509          sw->vol = nominal_volume;
510          sw->rate = st_rate_start (sw->info.freq, hw_cap->info.freq);
511          if (!sw->rate) {
512              dolog ("Could not start rate conversion for `%s'\n", SW_NAME (sw));
513              g_free (sw);
514              return -1;
515          }
516          QLIST_INSERT_HEAD (&hw_cap->sw_head, sw, entries);
517          QLIST_INSERT_HEAD (&hw->cap_head, sc, entries);
518  #ifdef DEBUG_CAPTURE
519          sw->name = g_strdup_printf ("for %p %d,%d,%d",
520                                      hw, sw->info.freq, sw->info.bits,
521                                      sw->info.nchannels);
522          dolog ("Added %s active = %d\n", sw->name, sw->active);
523  #endif
524          if (sw->active) {
525              audio_capture_maybe_changed (cap, 1);
526          }
527      }
528      return 0;
529  }
530  
531  /*
532   * Hard voice (capture)
533   */
534  static size_t audio_pcm_hw_find_min_in (HWVoiceIn *hw)
535  {
536      SWVoiceIn *sw;
537      size_t m = hw->total_samples_captured;
538  
539      for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
540          if (sw->active) {
541              m = MIN (m, sw->total_hw_samples_acquired);
542          }
543      }
544      return m;
545  }
546  
547  static size_t audio_pcm_hw_get_live_in(HWVoiceIn *hw)
548  {
549      size_t live = hw->total_samples_captured - audio_pcm_hw_find_min_in (hw);
550      if (audio_bug(__func__, live > hw->conv_buf->size)) {
551          dolog("live=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
552          return 0;
553      }
554      return live;
555  }
556  
557  static size_t audio_pcm_hw_conv_in(HWVoiceIn *hw, void *pcm_buf, size_t samples)
558  {
559      size_t conv = 0;
560      STSampleBuffer *conv_buf = hw->conv_buf;
561  
562      while (samples) {
563          uint8_t *src = advance(pcm_buf, conv * hw->info.bytes_per_frame);
564          size_t proc = MIN(samples, conv_buf->size - conv_buf->pos);
565  
566          hw->conv(conv_buf->samples + conv_buf->pos, src, proc);
567          conv_buf->pos = (conv_buf->pos + proc) % conv_buf->size;
568          samples -= proc;
569          conv += proc;
570      }
571  
572      return conv;
573  }
574  
575  /*
576   * Soft voice (capture)
577   */
578  static size_t audio_pcm_sw_read(SWVoiceIn *sw, void *buf, size_t size)
579  {
580      HWVoiceIn *hw = sw->hw;
581      size_t samples, live, ret = 0, swlim, isamp, osamp, rpos, total = 0;
582      struct st_sample *src, *dst = sw->buf;
583  
584      live = hw->total_samples_captured - sw->total_hw_samples_acquired;
585      if (!live) {
586          return 0;
587      }
588      if (audio_bug(__func__, live > hw->conv_buf->size)) {
589          dolog("live_in=%zu hw->conv_buf->size=%zu\n", live, hw->conv_buf->size);
590          return 0;
591      }
592  
593      rpos = audio_ring_posb(hw->conv_buf->pos, live, hw->conv_buf->size);
594  
595      samples = size / sw->info.bytes_per_frame;
596  
597      swlim = (live * sw->ratio) >> 32;
598      swlim = MIN (swlim, samples);
599  
600      while (swlim) {
601          src = hw->conv_buf->samples + rpos;
602          if (hw->conv_buf->pos > rpos) {
603              isamp = hw->conv_buf->pos - rpos;
604          } else {
605              isamp = hw->conv_buf->size - rpos;
606          }
607  
608          if (!isamp) {
609              break;
610          }
611          osamp = swlim;
612  
613          st_rate_flow (sw->rate, src, dst, &isamp, &osamp);
614          swlim -= osamp;
615          rpos = (rpos + isamp) % hw->conv_buf->size;
616          dst += osamp;
617          ret += osamp;
618          total += isamp;
619      }
620  
621      if (!hw->pcm_ops->volume_in) {
622          mixeng_volume (sw->buf, ret, &sw->vol);
623      }
624  
625      sw->clip (buf, sw->buf, ret);
626      sw->total_hw_samples_acquired += total;
627      return ret * sw->info.bytes_per_frame;
628  }
629  
630  /*
631   * Hard voice (playback)
632   */
633  static size_t audio_pcm_hw_find_min_out (HWVoiceOut *hw, int *nb_livep)
634  {
635      SWVoiceOut *sw;
636      size_t m = SIZE_MAX;
637      int nb_live = 0;
638  
639      for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
640          if (sw->active || !sw->empty) {
641              m = MIN (m, sw->total_hw_samples_mixed);
642              nb_live += 1;
643          }
644      }
645  
646      *nb_livep = nb_live;
647      return m;
648  }
649  
650  static size_t audio_pcm_hw_get_live_out (HWVoiceOut *hw, int *nb_live)
651  {
652      size_t smin;
653      int nb_live1;
654  
655      smin = audio_pcm_hw_find_min_out (hw, &nb_live1);
656      if (nb_live) {
657          *nb_live = nb_live1;
658      }
659  
660      if (nb_live1) {
661          size_t live = smin;
662  
663          if (audio_bug(__func__, live > hw->mix_buf->size)) {
664              dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
665              return 0;
666          }
667          return live;
668      }
669      return 0;
670  }
671  
672  static size_t audio_pcm_hw_get_free(HWVoiceOut *hw)
673  {
674      return (hw->pcm_ops->buffer_get_free ? hw->pcm_ops->buffer_get_free(hw) :
675              INT_MAX) / hw->info.bytes_per_frame;
676  }
677  
678  static void audio_pcm_hw_clip_out(HWVoiceOut *hw, void *pcm_buf, size_t len)
679  {
680      size_t clipped = 0;
681      size_t pos = hw->mix_buf->pos;
682  
683      while (len) {
684          st_sample *src = hw->mix_buf->samples + pos;
685          uint8_t *dst = advance(pcm_buf, clipped * hw->info.bytes_per_frame);
686          size_t samples_till_end_of_buf = hw->mix_buf->size - pos;
687          size_t samples_to_clip = MIN(len, samples_till_end_of_buf);
688  
689          hw->clip(dst, src, samples_to_clip);
690  
691          pos = (pos + samples_to_clip) % hw->mix_buf->size;
692          len -= samples_to_clip;
693          clipped += samples_to_clip;
694      }
695  }
696  
697  /*
698   * Soft voice (playback)
699   */
700  static size_t audio_pcm_sw_write(SWVoiceOut *sw, void *buf, size_t size)
701  {
702      size_t hwsamples, samples, isamp, osamp, wpos, live, dead, left, blck;
703      size_t hw_free;
704      size_t ret = 0, pos = 0, total = 0;
705  
706      if (!sw) {
707          return size;
708      }
709  
710      hwsamples = sw->hw->mix_buf->size;
711  
712      live = sw->total_hw_samples_mixed;
713      if (audio_bug(__func__, live > hwsamples)) {
714          dolog("live=%zu hw->mix_buf->size=%zu\n", live, hwsamples);
715          return 0;
716      }
717  
718      if (live == hwsamples) {
719  #ifdef DEBUG_OUT
720          dolog ("%s is full %zu\n", sw->name, live);
721  #endif
722          return 0;
723      }
724  
725      wpos = (sw->hw->mix_buf->pos + live) % hwsamples;
726  
727      dead = hwsamples - live;
728      hw_free = audio_pcm_hw_get_free(sw->hw);
729      hw_free = hw_free > live ? hw_free - live : 0;
730      samples = ((int64_t)MIN(dead, hw_free) << 32) / sw->ratio;
731      samples = MIN(samples, size / sw->info.bytes_per_frame);
732      if (samples) {
733          sw->conv(sw->buf, buf, samples);
734  
735          if (!sw->hw->pcm_ops->volume_out) {
736              mixeng_volume(sw->buf, samples, &sw->vol);
737          }
738      }
739  
740      while (samples) {
741          dead = hwsamples - live;
742          left = hwsamples - wpos;
743          blck = MIN (dead, left);
744          if (!blck) {
745              break;
746          }
747          isamp = samples;
748          osamp = blck;
749          st_rate_flow_mix (
750              sw->rate,
751              sw->buf + pos,
752              sw->hw->mix_buf->samples + wpos,
753              &isamp,
754              &osamp
755              );
756          ret += isamp;
757          samples -= isamp;
758          pos += isamp;
759          live += osamp;
760          wpos = (wpos + osamp) % hwsamples;
761          total += osamp;
762      }
763  
764      sw->total_hw_samples_mixed += total;
765      sw->empty = sw->total_hw_samples_mixed == 0;
766  
767  #ifdef DEBUG_OUT
768      dolog (
769          "%s: write size %zu ret %zu total sw %zu\n",
770          SW_NAME (sw),
771          size / sw->info.bytes_per_frame,
772          ret,
773          sw->total_hw_samples_mixed
774          );
775  #endif
776  
777      return ret * sw->info.bytes_per_frame;
778  }
779  
780  #ifdef DEBUG_AUDIO
781  static void audio_pcm_print_info (const char *cap, struct audio_pcm_info *info)
782  {
783      dolog("%s: bits %d, sign %d, float %d, freq %d, nchan %d\n",
784            cap, info->bits, info->is_signed, info->is_float, info->freq,
785            info->nchannels);
786  }
787  #endif
788  
789  #define DAC
790  #include "audio_template.h"
791  #undef DAC
792  #include "audio_template.h"
793  
794  /*
795   * Timer
796   */
797  static int audio_is_timer_needed(AudioState *s)
798  {
799      HWVoiceIn *hwi = NULL;
800      HWVoiceOut *hwo = NULL;
801  
802      while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
803          if (!hwo->poll_mode) {
804              return 1;
805          }
806      }
807      while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
808          if (!hwi->poll_mode) {
809              return 1;
810          }
811      }
812      return 0;
813  }
814  
815  static void audio_reset_timer (AudioState *s)
816  {
817      if (audio_is_timer_needed(s)) {
818          timer_mod_anticipate_ns(s->ts,
819              qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->period_ticks);
820          if (!s->timer_running) {
821              s->timer_running = true;
822              s->timer_last = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
823              trace_audio_timer_start(s->period_ticks / SCALE_MS);
824          }
825      } else {
826          timer_del(s->ts);
827          if (s->timer_running) {
828              s->timer_running = false;
829              trace_audio_timer_stop();
830          }
831      }
832  }
833  
834  static void audio_timer (void *opaque)
835  {
836      int64_t now, diff;
837      AudioState *s = opaque;
838  
839      now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
840      diff = now - s->timer_last;
841      if (diff > s->period_ticks * 3 / 2) {
842          trace_audio_timer_delayed(diff / SCALE_MS);
843      }
844      s->timer_last = now;
845  
846      audio_run(s, "timer");
847      audio_reset_timer(s);
848  }
849  
850  /*
851   * Public API
852   */
853  size_t AUD_write(SWVoiceOut *sw, void *buf, size_t size)
854  {
855      HWVoiceOut *hw;
856  
857      if (!sw) {
858          /* XXX: Consider options */
859          return size;
860      }
861      hw = sw->hw;
862  
863      if (!hw->enabled) {
864          dolog ("Writing to disabled voice %s\n", SW_NAME (sw));
865          return 0;
866      }
867  
868      if (audio_get_pdo_out(hw->s->dev)->mixing_engine) {
869          return audio_pcm_sw_write(sw, buf, size);
870      } else {
871          return hw->pcm_ops->write(hw, buf, size);
872      }
873  }
874  
875  size_t AUD_read(SWVoiceIn *sw, void *buf, size_t size)
876  {
877      HWVoiceIn *hw;
878  
879      if (!sw) {
880          /* XXX: Consider options */
881          return size;
882      }
883      hw = sw->hw;
884  
885      if (!hw->enabled) {
886          dolog ("Reading from disabled voice %s\n", SW_NAME (sw));
887          return 0;
888      }
889  
890      if (audio_get_pdo_in(hw->s->dev)->mixing_engine) {
891          return audio_pcm_sw_read(sw, buf, size);
892      } else {
893          return hw->pcm_ops->read(hw, buf, size);
894      }
895  }
896  
897  int AUD_get_buffer_size_out(SWVoiceOut *sw)
898  {
899      return sw->hw->samples * sw->hw->info.bytes_per_frame;
900  }
901  
902  void AUD_set_active_out (SWVoiceOut *sw, int on)
903  {
904      HWVoiceOut *hw;
905  
906      if (!sw) {
907          return;
908      }
909  
910      hw = sw->hw;
911      if (sw->active != on) {
912          AudioState *s = sw->s;
913          SWVoiceOut *temp_sw;
914          SWVoiceCap *sc;
915  
916          if (on) {
917              hw->pending_disable = 0;
918              if (!hw->enabled) {
919                  hw->enabled = 1;
920                  if (s->vm_running) {
921                      if (hw->pcm_ops->enable_out) {
922                          hw->pcm_ops->enable_out(hw, true);
923                      }
924                      audio_reset_timer (s);
925                  }
926              }
927          } else {
928              if (hw->enabled) {
929                  int nb_active = 0;
930  
931                  for (temp_sw = hw->sw_head.lh_first; temp_sw;
932                       temp_sw = temp_sw->entries.le_next) {
933                      nb_active += temp_sw->active != 0;
934                  }
935  
936                  hw->pending_disable = nb_active == 1;
937              }
938          }
939  
940          for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
941              sc->sw.active = hw->enabled;
942              if (hw->enabled) {
943                  audio_capture_maybe_changed (sc->cap, 1);
944              }
945          }
946          sw->active = on;
947      }
948  }
949  
950  void AUD_set_active_in (SWVoiceIn *sw, int on)
951  {
952      HWVoiceIn *hw;
953  
954      if (!sw) {
955          return;
956      }
957  
958      hw = sw->hw;
959      if (sw->active != on) {
960          AudioState *s = sw->s;
961          SWVoiceIn *temp_sw;
962  
963          if (on) {
964              if (!hw->enabled) {
965                  hw->enabled = 1;
966                  if (s->vm_running) {
967                      if (hw->pcm_ops->enable_in) {
968                          hw->pcm_ops->enable_in(hw, true);
969                      }
970                      audio_reset_timer (s);
971                  }
972              }
973              sw->total_hw_samples_acquired = hw->total_samples_captured;
974          } else {
975              if (hw->enabled) {
976                  int nb_active = 0;
977  
978                  for (temp_sw = hw->sw_head.lh_first; temp_sw;
979                       temp_sw = temp_sw->entries.le_next) {
980                      nb_active += temp_sw->active != 0;
981                  }
982  
983                  if (nb_active == 1) {
984                      hw->enabled = 0;
985                      if (hw->pcm_ops->enable_in) {
986                          hw->pcm_ops->enable_in(hw, false);
987                      }
988                  }
989              }
990          }
991          sw->active = on;
992      }
993  }
994  
995  /**
996   * audio_frontend_frames_in() - returns the number of frames the resampling
997   * code generates from frames_in frames
998   *
999   * @sw: audio recording frontend
1000   * @frames_in: number of frames
1001   */
1002  static size_t audio_frontend_frames_in(SWVoiceIn *sw, size_t frames_in)
1003  {
1004      return (int64_t)frames_in * sw->ratio >> 32;
1005  }
1006  
1007  static size_t audio_get_avail (SWVoiceIn *sw)
1008  {
1009      size_t live;
1010  
1011      if (!sw) {
1012          return 0;
1013      }
1014  
1015      live = sw->hw->total_samples_captured - sw->total_hw_samples_acquired;
1016      if (audio_bug(__func__, live > sw->hw->conv_buf->size)) {
1017          dolog("live=%zu sw->hw->conv_buf->size=%zu\n", live,
1018                sw->hw->conv_buf->size);
1019          return 0;
1020      }
1021  
1022      ldebug (
1023          "%s: get_avail live %zu frontend frames %zu\n",
1024          SW_NAME (sw),
1025          live, audio_frontend_frames_in(sw, live)
1026          );
1027  
1028      return live;
1029  }
1030  
1031  /**
1032   * audio_frontend_frames_out() - returns the number of frames needed to
1033   * get frames_out frames after resampling
1034   *
1035   * @sw: audio playback frontend
1036   * @frames_out: number of frames
1037   */
1038  static size_t audio_frontend_frames_out(SWVoiceOut *sw, size_t frames_out)
1039  {
1040      return ((int64_t)frames_out << 32) / sw->ratio;
1041  }
1042  
1043  static size_t audio_get_free(SWVoiceOut *sw)
1044  {
1045      size_t live, dead;
1046  
1047      if (!sw) {
1048          return 0;
1049      }
1050  
1051      live = sw->total_hw_samples_mixed;
1052  
1053      if (audio_bug(__func__, live > sw->hw->mix_buf->size)) {
1054          dolog("live=%zu sw->hw->mix_buf->size=%zu\n", live,
1055                sw->hw->mix_buf->size);
1056          return 0;
1057      }
1058  
1059      dead = sw->hw->mix_buf->size - live;
1060  
1061  #ifdef DEBUG_OUT
1062      dolog("%s: get_free live %zu dead %zu frontend frames %zu\n",
1063            SW_NAME(sw), live, dead, audio_frontend_frames_out(sw, dead));
1064  #endif
1065  
1066      return dead;
1067  }
1068  
1069  static void audio_capture_mix_and_clear(HWVoiceOut *hw, size_t rpos,
1070                                          size_t samples)
1071  {
1072      size_t n;
1073  
1074      if (hw->enabled) {
1075          SWVoiceCap *sc;
1076  
1077          for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1078              SWVoiceOut *sw = &sc->sw;
1079              int rpos2 = rpos;
1080  
1081              n = samples;
1082              while (n) {
1083                  size_t till_end_of_hw = hw->mix_buf->size - rpos2;
1084                  size_t to_write = MIN(till_end_of_hw, n);
1085                  size_t bytes = to_write * hw->info.bytes_per_frame;
1086                  size_t written;
1087  
1088                  sw->buf = hw->mix_buf->samples + rpos2;
1089                  written = audio_pcm_sw_write (sw, NULL, bytes);
1090                  if (written - bytes) {
1091                      dolog("Could not mix %zu bytes into a capture "
1092                            "buffer, mixed %zu\n",
1093                            bytes, written);
1094                      break;
1095                  }
1096                  n -= to_write;
1097                  rpos2 = (rpos2 + to_write) % hw->mix_buf->size;
1098              }
1099          }
1100      }
1101  
1102      n = MIN(samples, hw->mix_buf->size - rpos);
1103      mixeng_clear(hw->mix_buf->samples + rpos, n);
1104      mixeng_clear(hw->mix_buf->samples, samples - n);
1105  }
1106  
1107  static size_t audio_pcm_hw_run_out(HWVoiceOut *hw, size_t live)
1108  {
1109      size_t clipped = 0;
1110  
1111      while (live) {
1112          size_t size = live * hw->info.bytes_per_frame;
1113          size_t decr, proc;
1114          void *buf = hw->pcm_ops->get_buffer_out(hw, &size);
1115  
1116          if (size == 0) {
1117              break;
1118          }
1119  
1120          decr = MIN(size / hw->info.bytes_per_frame, live);
1121          if (buf) {
1122              audio_pcm_hw_clip_out(hw, buf, decr);
1123          }
1124          proc = hw->pcm_ops->put_buffer_out(hw, buf,
1125                                             decr * hw->info.bytes_per_frame) /
1126              hw->info.bytes_per_frame;
1127  
1128          live -= proc;
1129          clipped += proc;
1130          hw->mix_buf->pos = (hw->mix_buf->pos + proc) % hw->mix_buf->size;
1131  
1132          if (proc == 0 || proc < decr) {
1133              break;
1134          }
1135      }
1136  
1137      if (hw->pcm_ops->run_buffer_out) {
1138          hw->pcm_ops->run_buffer_out(hw);
1139      }
1140  
1141      return clipped;
1142  }
1143  
1144  static void audio_run_out (AudioState *s)
1145  {
1146      HWVoiceOut *hw = NULL;
1147      SWVoiceOut *sw;
1148  
1149      while ((hw = audio_pcm_hw_find_any_enabled_out(s, hw))) {
1150          size_t played, live, prev_rpos;
1151          size_t hw_free = audio_pcm_hw_get_free(hw);
1152          int nb_live;
1153  
1154          if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1155              /* there is exactly 1 sw for each hw with no mixeng */
1156              sw = hw->sw_head.lh_first;
1157  
1158              if (hw->pending_disable) {
1159                  hw->enabled = 0;
1160                  hw->pending_disable = 0;
1161                  if (hw->pcm_ops->enable_out) {
1162                      hw->pcm_ops->enable_out(hw, false);
1163                  }
1164              }
1165  
1166              if (sw->active) {
1167                  sw->callback.fn(sw->callback.opaque,
1168                                  hw_free * sw->info.bytes_per_frame);
1169              }
1170  
1171              if (hw->pcm_ops->run_buffer_out) {
1172                  hw->pcm_ops->run_buffer_out(hw);
1173              }
1174  
1175              continue;
1176          }
1177  
1178          for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1179              if (sw->active) {
1180                  size_t sw_free = audio_get_free(sw);
1181                  size_t free;
1182  
1183                  if (hw_free > sw->total_hw_samples_mixed) {
1184                      free = audio_frontend_frames_out(sw,
1185                          MIN(sw_free, hw_free - sw->total_hw_samples_mixed));
1186                  } else {
1187                      free = 0;
1188                  }
1189                  if (free > 0) {
1190                      sw->callback.fn(sw->callback.opaque,
1191                                      free * sw->info.bytes_per_frame);
1192                  }
1193              }
1194          }
1195  
1196          live = audio_pcm_hw_get_live_out (hw, &nb_live);
1197          if (!nb_live) {
1198              live = 0;
1199          }
1200  
1201          if (audio_bug(__func__, live > hw->mix_buf->size)) {
1202              dolog("live=%zu hw->mix_buf->size=%zu\n", live, hw->mix_buf->size);
1203              continue;
1204          }
1205  
1206          if (hw->pending_disable && !nb_live) {
1207              SWVoiceCap *sc;
1208  #ifdef DEBUG_OUT
1209              dolog ("Disabling voice\n");
1210  #endif
1211              hw->enabled = 0;
1212              hw->pending_disable = 0;
1213              if (hw->pcm_ops->enable_out) {
1214                  hw->pcm_ops->enable_out(hw, false);
1215              }
1216              for (sc = hw->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1217                  sc->sw.active = 0;
1218                  audio_recalc_and_notify_capture (sc->cap);
1219              }
1220              continue;
1221          }
1222  
1223          if (!live) {
1224              if (hw->pcm_ops->run_buffer_out) {
1225                  hw->pcm_ops->run_buffer_out(hw);
1226              }
1227              continue;
1228          }
1229  
1230          prev_rpos = hw->mix_buf->pos;
1231          played = audio_pcm_hw_run_out(hw, live);
1232          replay_audio_out(&played);
1233          if (audio_bug(__func__, hw->mix_buf->pos >= hw->mix_buf->size)) {
1234              dolog("hw->mix_buf->pos=%zu hw->mix_buf->size=%zu played=%zu\n",
1235                    hw->mix_buf->pos, hw->mix_buf->size, played);
1236              hw->mix_buf->pos = 0;
1237          }
1238  
1239  #ifdef DEBUG_OUT
1240          dolog("played=%zu\n", played);
1241  #endif
1242  
1243          if (played) {
1244              hw->ts_helper += played;
1245              audio_capture_mix_and_clear (hw, prev_rpos, played);
1246          }
1247  
1248          for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1249              if (!sw->active && sw->empty) {
1250                  continue;
1251              }
1252  
1253              if (audio_bug(__func__, played > sw->total_hw_samples_mixed)) {
1254                  dolog("played=%zu sw->total_hw_samples_mixed=%zu\n",
1255                        played, sw->total_hw_samples_mixed);
1256                  played = sw->total_hw_samples_mixed;
1257              }
1258  
1259              sw->total_hw_samples_mixed -= played;
1260  
1261              if (!sw->total_hw_samples_mixed) {
1262                  sw->empty = 1;
1263              }
1264          }
1265      }
1266  }
1267  
1268  static size_t audio_pcm_hw_run_in(HWVoiceIn *hw, size_t samples)
1269  {
1270      size_t conv = 0;
1271  
1272      if (hw->pcm_ops->run_buffer_in) {
1273          hw->pcm_ops->run_buffer_in(hw);
1274      }
1275  
1276      while (samples) {
1277          size_t proc;
1278          size_t size = samples * hw->info.bytes_per_frame;
1279          void *buf = hw->pcm_ops->get_buffer_in(hw, &size);
1280  
1281          assert(size % hw->info.bytes_per_frame == 0);
1282          if (size == 0) {
1283              break;
1284          }
1285  
1286          proc = audio_pcm_hw_conv_in(hw, buf, size / hw->info.bytes_per_frame);
1287  
1288          samples -= proc;
1289          conv += proc;
1290          hw->pcm_ops->put_buffer_in(hw, buf, proc * hw->info.bytes_per_frame);
1291      }
1292  
1293      return conv;
1294  }
1295  
1296  static void audio_run_in (AudioState *s)
1297  {
1298      HWVoiceIn *hw = NULL;
1299  
1300      if (!audio_get_pdo_in(s->dev)->mixing_engine) {
1301          while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1302              /* there is exactly 1 sw for each hw with no mixeng */
1303              SWVoiceIn *sw = hw->sw_head.lh_first;
1304              if (sw->active) {
1305                  sw->callback.fn(sw->callback.opaque, INT_MAX);
1306              }
1307          }
1308          return;
1309      }
1310  
1311      while ((hw = audio_pcm_hw_find_any_enabled_in(s, hw))) {
1312          SWVoiceIn *sw;
1313          size_t captured = 0, min;
1314  
1315          if (replay_mode != REPLAY_MODE_PLAY) {
1316              captured = audio_pcm_hw_run_in(
1317                  hw, hw->conv_buf->size - audio_pcm_hw_get_live_in(hw));
1318          }
1319          replay_audio_in(&captured, hw->conv_buf->samples, &hw->conv_buf->pos,
1320                          hw->conv_buf->size);
1321  
1322          min = audio_pcm_hw_find_min_in (hw);
1323          hw->total_samples_captured += captured - min;
1324          hw->ts_helper += captured;
1325  
1326          for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1327              sw->total_hw_samples_acquired -= min;
1328  
1329              if (sw->active) {
1330                  size_t sw_avail = audio_get_avail(sw);
1331                  size_t avail;
1332  
1333                  avail = audio_frontend_frames_in(sw, sw_avail);
1334                  if (avail > 0) {
1335                      sw->callback.fn(sw->callback.opaque,
1336                                      avail * sw->info.bytes_per_frame);
1337                  }
1338              }
1339          }
1340      }
1341  }
1342  
1343  static void audio_run_capture (AudioState *s)
1344  {
1345      CaptureVoiceOut *cap;
1346  
1347      for (cap = s->cap_head.lh_first; cap; cap = cap->entries.le_next) {
1348          size_t live, rpos, captured;
1349          HWVoiceOut *hw = &cap->hw;
1350          SWVoiceOut *sw;
1351  
1352          captured = live = audio_pcm_hw_get_live_out (hw, NULL);
1353          rpos = hw->mix_buf->pos;
1354          while (live) {
1355              size_t left = hw->mix_buf->size - rpos;
1356              size_t to_capture = MIN(live, left);
1357              struct st_sample *src;
1358              struct capture_callback *cb;
1359  
1360              src = hw->mix_buf->samples + rpos;
1361              hw->clip (cap->buf, src, to_capture);
1362              mixeng_clear (src, to_capture);
1363  
1364              for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1365                  cb->ops.capture (cb->opaque, cap->buf,
1366                                   to_capture * hw->info.bytes_per_frame);
1367              }
1368              rpos = (rpos + to_capture) % hw->mix_buf->size;
1369              live -= to_capture;
1370          }
1371          hw->mix_buf->pos = rpos;
1372  
1373          for (sw = hw->sw_head.lh_first; sw; sw = sw->entries.le_next) {
1374              if (!sw->active && sw->empty) {
1375                  continue;
1376              }
1377  
1378              if (audio_bug(__func__, captured > sw->total_hw_samples_mixed)) {
1379                  dolog("captured=%zu sw->total_hw_samples_mixed=%zu\n",
1380                        captured, sw->total_hw_samples_mixed);
1381                  captured = sw->total_hw_samples_mixed;
1382              }
1383  
1384              sw->total_hw_samples_mixed -= captured;
1385              sw->empty = sw->total_hw_samples_mixed == 0;
1386          }
1387      }
1388  }
1389  
1390  void audio_run(AudioState *s, const char *msg)
1391  {
1392      audio_run_out(s);
1393      audio_run_in(s);
1394      audio_run_capture(s);
1395  
1396  #ifdef DEBUG_POLL
1397      {
1398          static double prevtime;
1399          double currtime;
1400          struct timeval tv;
1401  
1402          if (gettimeofday (&tv, NULL)) {
1403              perror ("audio_run: gettimeofday");
1404              return;
1405          }
1406  
1407          currtime = tv.tv_sec + tv.tv_usec * 1e-6;
1408          dolog ("Elapsed since last %s: %f\n", msg, currtime - prevtime);
1409          prevtime = currtime;
1410      }
1411  #endif
1412  }
1413  
1414  void audio_generic_run_buffer_in(HWVoiceIn *hw)
1415  {
1416      if (unlikely(!hw->buf_emul)) {
1417          hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1418          hw->buf_emul = g_malloc(hw->size_emul);
1419          hw->pos_emul = hw->pending_emul = 0;
1420      }
1421  
1422      while (hw->pending_emul < hw->size_emul) {
1423          size_t read_len = MIN(hw->size_emul - hw->pos_emul,
1424                                hw->size_emul - hw->pending_emul);
1425          size_t read = hw->pcm_ops->read(hw, hw->buf_emul + hw->pos_emul,
1426                                          read_len);
1427          hw->pending_emul += read;
1428          hw->pos_emul = (hw->pos_emul + read) % hw->size_emul;
1429          if (read < read_len) {
1430              break;
1431          }
1432      }
1433  }
1434  
1435  void *audio_generic_get_buffer_in(HWVoiceIn *hw, size_t *size)
1436  {
1437      size_t start;
1438  
1439      start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1440      assert(start < hw->size_emul);
1441  
1442      *size = MIN(*size, hw->pending_emul);
1443      *size = MIN(*size, hw->size_emul - start);
1444      return hw->buf_emul + start;
1445  }
1446  
1447  void audio_generic_put_buffer_in(HWVoiceIn *hw, void *buf, size_t size)
1448  {
1449      assert(size <= hw->pending_emul);
1450      hw->pending_emul -= size;
1451  }
1452  
1453  size_t audio_generic_buffer_get_free(HWVoiceOut *hw)
1454  {
1455      if (hw->buf_emul) {
1456          return hw->size_emul - hw->pending_emul;
1457      } else {
1458          return hw->samples * hw->info.bytes_per_frame;
1459      }
1460  }
1461  
1462  void audio_generic_run_buffer_out(HWVoiceOut *hw)
1463  {
1464      while (hw->pending_emul) {
1465          size_t write_len, written, start;
1466  
1467          start = audio_ring_posb(hw->pos_emul, hw->pending_emul, hw->size_emul);
1468          assert(start < hw->size_emul);
1469  
1470          write_len = MIN(hw->pending_emul, hw->size_emul - start);
1471  
1472          written = hw->pcm_ops->write(hw, hw->buf_emul + start, write_len);
1473          hw->pending_emul -= written;
1474  
1475          if (written < write_len) {
1476              break;
1477          }
1478      }
1479  }
1480  
1481  void *audio_generic_get_buffer_out(HWVoiceOut *hw, size_t *size)
1482  {
1483      if (unlikely(!hw->buf_emul)) {
1484          hw->size_emul = hw->samples * hw->info.bytes_per_frame;
1485          hw->buf_emul = g_malloc(hw->size_emul);
1486          hw->pos_emul = hw->pending_emul = 0;
1487      }
1488  
1489      *size = MIN(hw->size_emul - hw->pending_emul,
1490                  hw->size_emul - hw->pos_emul);
1491      return hw->buf_emul + hw->pos_emul;
1492  }
1493  
1494  size_t audio_generic_put_buffer_out(HWVoiceOut *hw, void *buf, size_t size)
1495  {
1496      assert(buf == hw->buf_emul + hw->pos_emul &&
1497             size + hw->pending_emul <= hw->size_emul);
1498  
1499      hw->pending_emul += size;
1500      hw->pos_emul = (hw->pos_emul + size) % hw->size_emul;
1501  
1502      return size;
1503  }
1504  
1505  size_t audio_generic_write(HWVoiceOut *hw, void *buf, size_t size)
1506  {
1507      size_t total = 0;
1508  
1509      if (hw->pcm_ops->buffer_get_free) {
1510          size_t free = hw->pcm_ops->buffer_get_free(hw);
1511  
1512          size = MIN(size, free);
1513      }
1514  
1515      while (total < size) {
1516          size_t dst_size = size - total;
1517          size_t copy_size, proc;
1518          void *dst = hw->pcm_ops->get_buffer_out(hw, &dst_size);
1519  
1520          if (dst_size == 0) {
1521              break;
1522          }
1523  
1524          copy_size = MIN(size - total, dst_size);
1525          if (dst) {
1526              memcpy(dst, (char *)buf + total, copy_size);
1527          }
1528          proc = hw->pcm_ops->put_buffer_out(hw, dst, copy_size);
1529          total += proc;
1530  
1531          if (proc == 0 || proc < copy_size) {
1532              break;
1533          }
1534      }
1535  
1536      return total;
1537  }
1538  
1539  size_t audio_generic_read(HWVoiceIn *hw, void *buf, size_t size)
1540  {
1541      size_t total = 0;
1542  
1543      if (hw->pcm_ops->run_buffer_in) {
1544          hw->pcm_ops->run_buffer_in(hw);
1545      }
1546  
1547      while (total < size) {
1548          size_t src_size = size - total;
1549          void *src = hw->pcm_ops->get_buffer_in(hw, &src_size);
1550  
1551          if (src_size == 0) {
1552              break;
1553          }
1554  
1555          memcpy((char *)buf + total, src, src_size);
1556          hw->pcm_ops->put_buffer_in(hw, src, src_size);
1557          total += src_size;
1558      }
1559  
1560      return total;
1561  }
1562  
1563  static int audio_driver_init(AudioState *s, struct audio_driver *drv,
1564                               bool msg, Audiodev *dev)
1565  {
1566      s->drv_opaque = drv->init(dev);
1567  
1568      if (s->drv_opaque) {
1569          if (!drv->pcm_ops->get_buffer_in) {
1570              drv->pcm_ops->get_buffer_in = audio_generic_get_buffer_in;
1571              drv->pcm_ops->put_buffer_in = audio_generic_put_buffer_in;
1572          }
1573          if (!drv->pcm_ops->get_buffer_out) {
1574              drv->pcm_ops->get_buffer_out = audio_generic_get_buffer_out;
1575              drv->pcm_ops->put_buffer_out = audio_generic_put_buffer_out;
1576          }
1577  
1578          audio_init_nb_voices_out(s, drv);
1579          audio_init_nb_voices_in(s, drv);
1580          s->drv = drv;
1581          return 0;
1582      } else {
1583          if (msg) {
1584              dolog("Could not init `%s' audio driver\n", drv->name);
1585          }
1586          return -1;
1587      }
1588  }
1589  
1590  static void audio_vm_change_state_handler (void *opaque, bool running,
1591                                             RunState state)
1592  {
1593      AudioState *s = opaque;
1594      HWVoiceOut *hwo = NULL;
1595      HWVoiceIn *hwi = NULL;
1596  
1597      s->vm_running = running;
1598      while ((hwo = audio_pcm_hw_find_any_enabled_out(s, hwo))) {
1599          if (hwo->pcm_ops->enable_out) {
1600              hwo->pcm_ops->enable_out(hwo, running);
1601          }
1602      }
1603  
1604      while ((hwi = audio_pcm_hw_find_any_enabled_in(s, hwi))) {
1605          if (hwi->pcm_ops->enable_in) {
1606              hwi->pcm_ops->enable_in(hwi, running);
1607          }
1608      }
1609      audio_reset_timer (s);
1610  }
1611  
1612  static void free_audio_state(AudioState *s)
1613  {
1614      HWVoiceOut *hwo, *hwon;
1615      HWVoiceIn *hwi, *hwin;
1616  
1617      QLIST_FOREACH_SAFE(hwo, &s->hw_head_out, entries, hwon) {
1618          SWVoiceCap *sc;
1619  
1620          if (hwo->enabled && hwo->pcm_ops->enable_out) {
1621              hwo->pcm_ops->enable_out(hwo, false);
1622          }
1623          hwo->pcm_ops->fini_out (hwo);
1624  
1625          for (sc = hwo->cap_head.lh_first; sc; sc = sc->entries.le_next) {
1626              CaptureVoiceOut *cap = sc->cap;
1627              struct capture_callback *cb;
1628  
1629              for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1630                  cb->ops.destroy (cb->opaque);
1631              }
1632          }
1633          QLIST_REMOVE(hwo, entries);
1634      }
1635  
1636      QLIST_FOREACH_SAFE(hwi, &s->hw_head_in, entries, hwin) {
1637          if (hwi->enabled && hwi->pcm_ops->enable_in) {
1638              hwi->pcm_ops->enable_in(hwi, false);
1639          }
1640          hwi->pcm_ops->fini_in (hwi);
1641          QLIST_REMOVE(hwi, entries);
1642      }
1643  
1644      if (s->drv) {
1645          s->drv->fini (s->drv_opaque);
1646          s->drv = NULL;
1647      }
1648  
1649      if (s->dev) {
1650          qapi_free_Audiodev(s->dev);
1651          s->dev = NULL;
1652      }
1653  
1654      if (s->ts) {
1655          timer_free(s->ts);
1656          s->ts = NULL;
1657      }
1658  
1659      g_free(s);
1660  }
1661  
1662  void audio_cleanup(void)
1663  {
1664      while (!QTAILQ_EMPTY(&audio_states)) {
1665          AudioState *s = QTAILQ_FIRST(&audio_states);
1666          QTAILQ_REMOVE(&audio_states, s, list);
1667          free_audio_state(s);
1668      }
1669  }
1670  
1671  static bool vmstate_audio_needed(void *opaque)
1672  {
1673      /*
1674       * Never needed, this vmstate only exists in case
1675       * an old qemu sends it to us.
1676       */
1677      return false;
1678  }
1679  
1680  static const VMStateDescription vmstate_audio = {
1681      .name = "audio",
1682      .version_id = 1,
1683      .minimum_version_id = 1,
1684      .needed = vmstate_audio_needed,
1685      .fields = (VMStateField[]) {
1686          VMSTATE_END_OF_LIST()
1687      }
1688  };
1689  
1690  static void audio_validate_opts(Audiodev *dev, Error **errp);
1691  
1692  static AudiodevListEntry *audiodev_find(
1693      AudiodevListHead *head, const char *drvname)
1694  {
1695      AudiodevListEntry *e;
1696      QSIMPLEQ_FOREACH(e, head, next) {
1697          if (strcmp(AudiodevDriver_str(e->dev->driver), drvname) == 0) {
1698              return e;
1699          }
1700      }
1701  
1702      return NULL;
1703  }
1704  
1705  /*
1706   * if we have dev, this function was called because of an -audiodev argument =>
1707   *   initialize a new state with it
1708   * if dev == NULL => legacy implicit initialization, return the already created
1709   *   state or create a new one
1710   */
1711  static AudioState *audio_init(Audiodev *dev, const char *name)
1712  {
1713      static bool atexit_registered;
1714      size_t i;
1715      int done = 0;
1716      const char *drvname = NULL;
1717      VMChangeStateEntry *e;
1718      AudioState *s;
1719      struct audio_driver *driver;
1720      /* silence gcc warning about uninitialized variable */
1721      AudiodevListHead head = QSIMPLEQ_HEAD_INITIALIZER(head);
1722  
1723      if (using_spice) {
1724          /*
1725           * When using spice allow the spice audio driver being picked
1726           * as default.
1727           *
1728           * Temporary hack.  Using audio devices without explicit
1729           * audiodev= property is already deprecated.  Same goes for
1730           * the -soundhw switch.  Once this support gets finally
1731           * removed we can also drop the concept of a default audio
1732           * backend and this can go away.
1733           */
1734          driver = audio_driver_lookup("spice");
1735          if (driver) {
1736              driver->can_be_default = 1;
1737          }
1738      }
1739  
1740      if (dev) {
1741          /* -audiodev option */
1742          legacy_config = false;
1743          drvname = AudiodevDriver_str(dev->driver);
1744      } else if (!QTAILQ_EMPTY(&audio_states)) {
1745          if (!legacy_config) {
1746              dolog("Device %s: audiodev default parameter is deprecated, please "
1747                    "specify audiodev=%s\n", name,
1748                    QTAILQ_FIRST(&audio_states)->dev->id);
1749          }
1750          return QTAILQ_FIRST(&audio_states);
1751      } else {
1752          /* legacy implicit initialization */
1753          head = audio_handle_legacy_opts();
1754          /*
1755           * In case of legacy initialization, all Audiodevs in the list will have
1756           * the same configuration (except the driver), so it doesn't matter which
1757           * one we chose.  We need an Audiodev to set up AudioState before we can
1758           * init a driver.  Also note that dev at this point is still in the
1759           * list.
1760           */
1761          dev = QSIMPLEQ_FIRST(&head)->dev;
1762          audio_validate_opts(dev, &error_abort);
1763      }
1764  
1765      s = g_new0(AudioState, 1);
1766      s->dev = dev;
1767  
1768      QLIST_INIT (&s->hw_head_out);
1769      QLIST_INIT (&s->hw_head_in);
1770      QLIST_INIT (&s->cap_head);
1771      if (!atexit_registered) {
1772          atexit(audio_cleanup);
1773          atexit_registered = true;
1774      }
1775  
1776      s->ts = timer_new_ns(QEMU_CLOCK_VIRTUAL, audio_timer, s);
1777  
1778      s->nb_hw_voices_out = audio_get_pdo_out(dev)->voices;
1779      s->nb_hw_voices_in = audio_get_pdo_in(dev)->voices;
1780  
1781      if (s->nb_hw_voices_out < 1) {
1782          dolog ("Bogus number of playback voices %d, setting to 1\n",
1783                 s->nb_hw_voices_out);
1784          s->nb_hw_voices_out = 1;
1785      }
1786  
1787      if (s->nb_hw_voices_in < 0) {
1788          dolog ("Bogus number of capture voices %d, setting to 0\n",
1789                 s->nb_hw_voices_in);
1790          s->nb_hw_voices_in = 0;
1791      }
1792  
1793      if (drvname) {
1794          driver = audio_driver_lookup(drvname);
1795          if (driver) {
1796              done = !audio_driver_init(s, driver, true, dev);
1797          } else {
1798              dolog ("Unknown audio driver `%s'\n", drvname);
1799          }
1800          if (!done) {
1801              free_audio_state(s);
1802              return NULL;
1803          }
1804      } else {
1805          for (i = 0; audio_prio_list[i]; i++) {
1806              AudiodevListEntry *e = audiodev_find(&head, audio_prio_list[i]);
1807              driver = audio_driver_lookup(audio_prio_list[i]);
1808  
1809              if (e && driver) {
1810                  s->dev = dev = e->dev;
1811                  audio_validate_opts(dev, &error_abort);
1812                  done = !audio_driver_init(s, driver, false, dev);
1813                  if (done) {
1814                      e->dev = NULL;
1815                      break;
1816                  }
1817              }
1818          }
1819      }
1820      audio_free_audiodev_list(&head);
1821  
1822      if (!done) {
1823          driver = audio_driver_lookup("none");
1824          done = !audio_driver_init(s, driver, false, dev);
1825          assert(done);
1826          dolog("warning: Using timer based audio emulation\n");
1827      }
1828  
1829      if (dev->timer_period <= 0) {
1830          s->period_ticks = 1;
1831      } else {
1832          s->period_ticks = dev->timer_period * (int64_t)SCALE_US;
1833      }
1834  
1835      e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);
1836      if (!e) {
1837          dolog ("warning: Could not register change state handler\n"
1838                 "(Audio can continue looping even after stopping the VM)\n");
1839      }
1840  
1841      QTAILQ_INSERT_TAIL(&audio_states, s, list);
1842      QLIST_INIT (&s->card_head);
1843      vmstate_register (NULL, 0, &vmstate_audio, s);
1844      return s;
1845  }
1846  
1847  void audio_free_audiodev_list(AudiodevListHead *head)
1848  {
1849      AudiodevListEntry *e;
1850      while ((e = QSIMPLEQ_FIRST(head))) {
1851          QSIMPLEQ_REMOVE_HEAD(head, next);
1852          qapi_free_Audiodev(e->dev);
1853          g_free(e);
1854      }
1855  }
1856  
1857  void AUD_register_card (const char *name, QEMUSoundCard *card)
1858  {
1859      if (!card->state) {
1860          card->state = audio_init(NULL, name);
1861      }
1862  
1863      card->name = g_strdup (name);
1864      memset (&card->entries, 0, sizeof (card->entries));
1865      QLIST_INSERT_HEAD(&card->state->card_head, card, entries);
1866  }
1867  
1868  void AUD_remove_card (QEMUSoundCard *card)
1869  {
1870      QLIST_REMOVE (card, entries);
1871      g_free (card->name);
1872  }
1873  
1874  static struct audio_pcm_ops capture_pcm_ops;
1875  
1876  CaptureVoiceOut *AUD_add_capture(
1877      AudioState *s,
1878      struct audsettings *as,
1879      struct audio_capture_ops *ops,
1880      void *cb_opaque
1881      )
1882  {
1883      CaptureVoiceOut *cap;
1884      struct capture_callback *cb;
1885  
1886      if (!s) {
1887          if (!legacy_config) {
1888              dolog("Capturing without setting an audiodev is deprecated\n");
1889          }
1890          s = audio_init(NULL, NULL);
1891      }
1892  
1893      if (!audio_get_pdo_out(s->dev)->mixing_engine) {
1894          dolog("Can't capture with mixeng disabled\n");
1895          return NULL;
1896      }
1897  
1898      if (audio_validate_settings (as)) {
1899          dolog ("Invalid settings were passed when trying to add capture\n");
1900          audio_print_settings (as);
1901          return NULL;
1902      }
1903  
1904      cb = g_malloc0(sizeof(*cb));
1905      cb->ops = *ops;
1906      cb->opaque = cb_opaque;
1907  
1908      cap = audio_pcm_capture_find_specific(s, as);
1909      if (cap) {
1910          QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1911          return cap;
1912      } else {
1913          HWVoiceOut *hw;
1914          CaptureVoiceOut *cap;
1915  
1916          cap = g_malloc0(sizeof(*cap));
1917  
1918          hw = &cap->hw;
1919          hw->s = s;
1920          hw->pcm_ops = &capture_pcm_ops;
1921          QLIST_INIT (&hw->sw_head);
1922          QLIST_INIT (&cap->cb_head);
1923  
1924          /* XXX find a more elegant way */
1925          hw->samples = 4096 * 4;
1926          audio_pcm_hw_alloc_resources_out(hw);
1927  
1928          audio_pcm_init_info (&hw->info, as);
1929  
1930          cap->buf = g_malloc0_n(hw->mix_buf->size, hw->info.bytes_per_frame);
1931  
1932          if (hw->info.is_float) {
1933              hw->clip = mixeng_clip_float[hw->info.nchannels == 2];
1934          } else {
1935              hw->clip = mixeng_clip
1936                  [hw->info.nchannels == 2]
1937                  [hw->info.is_signed]
1938                  [hw->info.swap_endianness]
1939                  [audio_bits_to_index(hw->info.bits)];
1940          }
1941  
1942          QLIST_INSERT_HEAD (&s->cap_head, cap, entries);
1943          QLIST_INSERT_HEAD (&cap->cb_head, cb, entries);
1944  
1945          QLIST_FOREACH(hw, &s->hw_head_out, entries) {
1946              audio_attach_capture (hw);
1947          }
1948          return cap;
1949      }
1950  }
1951  
1952  void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)
1953  {
1954      struct capture_callback *cb;
1955  
1956      for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {
1957          if (cb->opaque == cb_opaque) {
1958              cb->ops.destroy (cb_opaque);
1959              QLIST_REMOVE (cb, entries);
1960              g_free (cb);
1961  
1962              if (!cap->cb_head.lh_first) {
1963                  SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;
1964  
1965                  while (sw) {
1966                      SWVoiceCap *sc = (SWVoiceCap *) sw;
1967  #ifdef DEBUG_CAPTURE
1968                      dolog ("freeing %s\n", sw->name);
1969  #endif
1970  
1971                      sw1 = sw->entries.le_next;
1972                      if (sw->rate) {
1973                          st_rate_stop (sw->rate);
1974                          sw->rate = NULL;
1975                      }
1976                      QLIST_REMOVE (sw, entries);
1977                      QLIST_REMOVE (sc, entries);
1978                      g_free (sc);
1979                      sw = sw1;
1980                  }
1981                  QLIST_REMOVE (cap, entries);
1982                  g_free (cap->hw.mix_buf);
1983                  g_free (cap->buf);
1984                  g_free (cap);
1985              }
1986              return;
1987          }
1988      }
1989  }
1990  
1991  void AUD_set_volume_out (SWVoiceOut *sw, int mute, uint8_t lvol, uint8_t rvol)
1992  {
1993      Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
1994      audio_set_volume_out(sw, &vol);
1995  }
1996  
1997  void audio_set_volume_out(SWVoiceOut *sw, Volume *vol)
1998  {
1999      if (sw) {
2000          HWVoiceOut *hw = sw->hw;
2001  
2002          sw->vol.mute = vol->mute;
2003          sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2004          sw->vol.r = nominal_volume.l * vol->vol[vol->channels > 1 ? 1 : 0] /
2005              255;
2006  
2007          if (hw->pcm_ops->volume_out) {
2008              hw->pcm_ops->volume_out(hw, vol);
2009          }
2010      }
2011  }
2012  
2013  void AUD_set_volume_in (SWVoiceIn *sw, int mute, uint8_t lvol, uint8_t rvol)
2014  {
2015      Volume vol = { .mute = mute, .channels = 2, .vol = { lvol, rvol } };
2016      audio_set_volume_in(sw, &vol);
2017  }
2018  
2019  void audio_set_volume_in(SWVoiceIn *sw, Volume *vol)
2020  {
2021      if (sw) {
2022          HWVoiceIn *hw = sw->hw;
2023  
2024          sw->vol.mute = vol->mute;
2025          sw->vol.l = nominal_volume.l * vol->vol[0] / 255;
2026          sw->vol.r = nominal_volume.r * vol->vol[vol->channels > 1 ? 1 : 0] /
2027              255;
2028  
2029          if (hw->pcm_ops->volume_in) {
2030              hw->pcm_ops->volume_in(hw, vol);
2031          }
2032      }
2033  }
2034  
2035  void audio_create_pdos(Audiodev *dev)
2036  {
2037      switch (dev->driver) {
2038  #define CASE(DRIVER, driver, pdo_name)                              \
2039      case AUDIODEV_DRIVER_##DRIVER:                                  \
2040          if (!dev->u.driver.in) {                                    \
2041              dev->u.driver.in = g_malloc0(                           \
2042                  sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
2043          }                                                           \
2044          if (!dev->u.driver.out) {                                   \
2045              dev->u.driver.out = g_malloc0(                          \
2046                  sizeof(Audiodev##pdo_name##PerDirectionOptions));   \
2047          }                                                           \
2048          break
2049  
2050          CASE(NONE, none, );
2051  #ifdef CONFIG_AUDIO_ALSA
2052          CASE(ALSA, alsa, Alsa);
2053  #endif
2054  #ifdef CONFIG_AUDIO_COREAUDIO
2055          CASE(COREAUDIO, coreaudio, Coreaudio);
2056  #endif
2057  #ifdef CONFIG_DBUS_DISPLAY
2058          CASE(DBUS, dbus, );
2059  #endif
2060  #ifdef CONFIG_AUDIO_DSOUND
2061          CASE(DSOUND, dsound, );
2062  #endif
2063  #ifdef CONFIG_AUDIO_JACK
2064          CASE(JACK, jack, Jack);
2065  #endif
2066  #ifdef CONFIG_AUDIO_OSS
2067          CASE(OSS, oss, Oss);
2068  #endif
2069  #ifdef CONFIG_AUDIO_PA
2070          CASE(PA, pa, Pa);
2071  #endif
2072  #ifdef CONFIG_AUDIO_SDL
2073          CASE(SDL, sdl, Sdl);
2074  #endif
2075  #ifdef CONFIG_AUDIO_SNDIO
2076          CASE(SNDIO, sndio, );
2077  #endif
2078  #ifdef CONFIG_SPICE
2079          CASE(SPICE, spice, );
2080  #endif
2081          CASE(WAV, wav, );
2082  
2083      case AUDIODEV_DRIVER__MAX:
2084          abort();
2085      };
2086  }
2087  
2088  static void audio_validate_per_direction_opts(
2089      AudiodevPerDirectionOptions *pdo, Error **errp)
2090  {
2091      if (!pdo->has_mixing_engine) {
2092          pdo->has_mixing_engine = true;
2093          pdo->mixing_engine = true;
2094      }
2095      if (!pdo->has_fixed_settings) {
2096          pdo->has_fixed_settings = true;
2097          pdo->fixed_settings = pdo->mixing_engine;
2098      }
2099      if (!pdo->fixed_settings &&
2100          (pdo->has_frequency || pdo->has_channels || pdo->has_format)) {
2101          error_setg(errp,
2102                     "You can't use frequency, channels or format with fixed-settings=off");
2103          return;
2104      }
2105      if (!pdo->mixing_engine && pdo->fixed_settings) {
2106          error_setg(errp, "You can't use fixed-settings without mixeng");
2107          return;
2108      }
2109  
2110      if (!pdo->has_frequency) {
2111          pdo->has_frequency = true;
2112          pdo->frequency = 44100;
2113      }
2114      if (!pdo->has_channels) {
2115          pdo->has_channels = true;
2116          pdo->channels = 2;
2117      }
2118      if (!pdo->has_voices) {
2119          pdo->has_voices = true;
2120          pdo->voices = pdo->mixing_engine ? 1 : INT_MAX;
2121      }
2122      if (!pdo->has_format) {
2123          pdo->has_format = true;
2124          pdo->format = AUDIO_FORMAT_S16;
2125      }
2126  }
2127  
2128  static void audio_validate_opts(Audiodev *dev, Error **errp)
2129  {
2130      Error *err = NULL;
2131  
2132      audio_create_pdos(dev);
2133  
2134      audio_validate_per_direction_opts(audio_get_pdo_in(dev), &err);
2135      if (err) {
2136          error_propagate(errp, err);
2137          return;
2138      }
2139  
2140      audio_validate_per_direction_opts(audio_get_pdo_out(dev), &err);
2141      if (err) {
2142          error_propagate(errp, err);
2143          return;
2144      }
2145  
2146      if (!dev->has_timer_period) {
2147          dev->has_timer_period = true;
2148          dev->timer_period = 10000; /* 100Hz -> 10ms */
2149      }
2150  }
2151  
2152  void audio_help(void)
2153  {
2154      int i;
2155  
2156      printf("Available audio drivers:\n");
2157  
2158      for (i = 0; i < AUDIODEV_DRIVER__MAX; i++) {
2159          audio_driver *driver = audio_driver_lookup(AudiodevDriver_str(i));
2160          if (driver) {
2161              printf("%s\n", driver->name);
2162          }
2163      }
2164  }
2165  
2166  void audio_parse_option(const char *opt)
2167  {
2168      Audiodev *dev = NULL;
2169  
2170      if (is_help_option(opt)) {
2171          audio_help();
2172          exit(EXIT_SUCCESS);
2173      }
2174      Visitor *v = qobject_input_visitor_new_str(opt, "driver", &error_fatal);
2175      visit_type_Audiodev(v, NULL, &dev, &error_fatal);
2176      visit_free(v);
2177  
2178      audio_define(dev);
2179  }
2180  
2181  void audio_define(Audiodev *dev)
2182  {
2183      AudiodevListEntry *e;
2184  
2185      audio_validate_opts(dev, &error_fatal);
2186  
2187      e = g_new0(AudiodevListEntry, 1);
2188      e->dev = dev;
2189      QSIMPLEQ_INSERT_TAIL(&audiodevs, e, next);
2190  }
2191  
2192  bool audio_init_audiodevs(void)
2193  {
2194      AudiodevListEntry *e;
2195  
2196      QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2197          if (!audio_init(e->dev, NULL)) {
2198              return false;
2199          }
2200      }
2201  
2202      return true;
2203  }
2204  
2205  audsettings audiodev_to_audsettings(AudiodevPerDirectionOptions *pdo)
2206  {
2207      return (audsettings) {
2208          .freq = pdo->frequency,
2209          .nchannels = pdo->channels,
2210          .fmt = pdo->format,
2211          .endianness = AUDIO_HOST_ENDIANNESS,
2212      };
2213  }
2214  
2215  int audioformat_bytes_per_sample(AudioFormat fmt)
2216  {
2217      switch (fmt) {
2218      case AUDIO_FORMAT_U8:
2219      case AUDIO_FORMAT_S8:
2220          return 1;
2221  
2222      case AUDIO_FORMAT_U16:
2223      case AUDIO_FORMAT_S16:
2224          return 2;
2225  
2226      case AUDIO_FORMAT_U32:
2227      case AUDIO_FORMAT_S32:
2228      case AUDIO_FORMAT_F32:
2229          return 4;
2230  
2231      case AUDIO_FORMAT__MAX:
2232          ;
2233      }
2234      abort();
2235  }
2236  
2237  
2238  /* frames = freq * usec / 1e6 */
2239  int audio_buffer_frames(AudiodevPerDirectionOptions *pdo,
2240                          audsettings *as, int def_usecs)
2241  {
2242      uint64_t usecs = pdo->has_buffer_length ? pdo->buffer_length : def_usecs;
2243      return (as->freq * usecs + 500000) / 1000000;
2244  }
2245  
2246  /* samples = channels * frames = channels * freq * usec / 1e6 */
2247  int audio_buffer_samples(AudiodevPerDirectionOptions *pdo,
2248                           audsettings *as, int def_usecs)
2249  {
2250      return as->nchannels * audio_buffer_frames(pdo, as, def_usecs);
2251  }
2252  
2253  /*
2254   * bytes = bytes_per_sample * samples =
2255   *     bytes_per_sample * channels * freq * usec / 1e6
2256   */
2257  int audio_buffer_bytes(AudiodevPerDirectionOptions *pdo,
2258                         audsettings *as, int def_usecs)
2259  {
2260      return audio_buffer_samples(pdo, as, def_usecs) *
2261          audioformat_bytes_per_sample(as->fmt);
2262  }
2263  
2264  AudioState *audio_state_by_name(const char *name)
2265  {
2266      AudioState *s;
2267      QTAILQ_FOREACH(s, &audio_states, list) {
2268          assert(s->dev);
2269          if (strcmp(name, s->dev->id) == 0) {
2270              return s;
2271          }
2272      }
2273      return NULL;
2274  }
2275  
2276  const char *audio_get_id(QEMUSoundCard *card)
2277  {
2278      if (card->state) {
2279          assert(card->state->dev);
2280          return card->state->dev->id;
2281      } else {
2282          return "";
2283      }
2284  }
2285  
2286  const char *audio_application_name(void)
2287  {
2288      const char *vm_name;
2289  
2290      vm_name = qemu_get_vm_name();
2291      return vm_name ? vm_name : "qemu";
2292  }
2293  
2294  void audio_rate_start(RateCtl *rate)
2295  {
2296      memset(rate, 0, sizeof(RateCtl));
2297      rate->start_ticks = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2298  }
2299  
2300  size_t audio_rate_peek_bytes(RateCtl *rate, struct audio_pcm_info *info)
2301  {
2302      int64_t now;
2303      int64_t ticks;
2304      int64_t bytes;
2305      int64_t frames;
2306  
2307      now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
2308      ticks = now - rate->start_ticks;
2309      bytes = muldiv64(ticks, info->bytes_per_second, NANOSECONDS_PER_SECOND);
2310      frames = (bytes - rate->bytes_sent) / info->bytes_per_frame;
2311      if (frames < 0 || frames > 65536) {
2312          AUD_log(NULL, "Resetting rate control (%" PRId64 " frames)\n", frames);
2313          audio_rate_start(rate);
2314          frames = 0;
2315      }
2316  
2317      return frames * info->bytes_per_frame;
2318  }
2319  
2320  void audio_rate_add_bytes(RateCtl *rate, size_t bytes_used)
2321  {
2322      rate->bytes_sent += bytes_used;
2323  }
2324  
2325  size_t audio_rate_get_bytes(RateCtl *rate, struct audio_pcm_info *info,
2326                              size_t bytes_avail)
2327  {
2328      size_t bytes;
2329  
2330      bytes = audio_rate_peek_bytes(rate, info);
2331      bytes = MIN(bytes, bytes_avail);
2332      audio_rate_add_bytes(rate, bytes);
2333  
2334      return bytes;
2335  }
2336  
2337  AudiodevList *qmp_query_audiodevs(Error **errp)
2338  {
2339      AudiodevList *ret = NULL;
2340      AudiodevListEntry *e;
2341      QSIMPLEQ_FOREACH(e, &audiodevs, next) {
2342          QAPI_LIST_PREPEND(ret, QAPI_CLONE(Audiodev, e->dev));
2343      }
2344      return ret;
2345  }
2346