Skip to main content

usbdac_core/
dac.rs

1//! The DAC handle.
2
3use crate::capabilities::{Capabilities, DeviceInfo};
4use crate::config::{CloseVolume, DacConfig, HandBack};
5use crate::error::{Error, Result};
6use crate::events::{DacListener, EventHub, EventSink};
7use crate::format::{StreamFormat, StreamRequest};
8use crate::settings::{self, Settings};
9use crate::stream::{DacStream, StreamInner};
10use crate::transport;
11use crate::volume::VolumeControl;
12use parking_lot::Mutex;
13use std::os::fd::RawFd;
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::sync::{Arc, Weak};
16use std::time::Duration;
17
18/// How long `close` waits for the output thread to finish.
19const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);
20
21/// Serializes `Dac::open`, so two concurrent opens cannot disturb each other's
22/// settings.
23static OPEN_GUARD: Mutex<()> = Mutex::new(());
24
25/// State shared by the `Dac`, its streams and its volume handle.
26pub(crate) struct DacShared {
27    pub(crate) events: EventSink,
28    pub(crate) info: DeviceInfo,
29    pub(crate) config: DacConfig,
30    closed: AtomicBool,
31    pub(crate) stream: Mutex<Option<Weak<StreamInner>>>,
32    last_feedback_stream: Mutex<Option<(StreamFormat, Arc<transport::RuntimeStats>)>>,
33}
34
35impl DacShared {
36    pub(crate) fn ensure_open(&self) -> Result<()> {
37        if self.closed.load(Ordering::Acquire) {
38            Err(Error::InvalidState("the DAC is closed".to_string()))
39        } else {
40            Ok(())
41        }
42    }
43
44    /// The stream that is open now, if any.
45    fn active_stream(&self) -> Option<Arc<StreamInner>> {
46        self.stream
47            .lock()
48            .as_ref()
49            .and_then(Weak::upgrade)
50            .filter(|stream| !stream.is_closed())
51    }
52
53    /// Closes with what the configuration says about the original volume
54    /// (`None`) or with what the host decided at close.
55    fn shutdown(&self, volume: Option<CloseVolume>) -> Result<()> {
56        if self.closed.swap(true, Ordering::AcqRel) {
57            return Ok(());
58        }
59        if let Some(stream) = self.active_stream() {
60            let _ = stream.close();
61        }
62        // A DAC that has gone cannot be written to, and what was recorded for
63        // it must not survive into a later attachment: forget it, whatever was
64        // asked for.
65        let action = if self.events.device_lost() {
66            transport::api::ORIGINAL_VOLUME_ACTION_FORGET
67        } else {
68            match volume {
69                Some(CloseVolume::Restore) => transport::api::ORIGINAL_VOLUME_ACTION_RESTORE,
70                Some(CloseVolume::Keep) => transport::api::ORIGINAL_VOLUME_ACTION_KEEP,
71                Some(CloseVolume::Forget) => transport::api::ORIGINAL_VOLUME_ACTION_FORGET,
72                None => match self.config.hand_back {
73                    HandBack::RestoreOriginal => transport::api::ORIGINAL_VOLUME_ACTION_RESTORE,
74                    HandBack::Keep => transport::api::ORIGINAL_VOLUME_ACTION_KEEP,
75                },
76            }
77        };
78        let stopped = transport::api::close_device(action, CLOSE_TIMEOUT);
79        self.events.shutdown();
80        if stopped {
81            Ok(())
82        } else {
83            Err(Error::Transfer(
84                "the USB output thread did not stop in time; the DAC stays busy until it does"
85                    .to_string(),
86            ))
87        }
88    }
89}
90
91/// An open USB DAC.
92///
93/// v0.1 supports one open `Dac` per process; a second [`Dac::open`] returns
94/// [`Error::Busy`] until the first is closed or dropped. The host keeps its
95/// `UsbDeviceConnection` open until then.
96pub struct Dac {
97    shared: Arc<DacShared>,
98}
99
100impl std::fmt::Debug for Dac {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        f.debug_struct("Dac")
103            .field("info", &self.shared.info)
104            .finish_non_exhaustive()
105    }
106}
107
108impl Dac {
109    /// Wait until USB activity has retired before releasing the host's claimed interfaces and FD.
110    ///
111    /// After [`Dac::close`] returns a transfer timeout, retain all host ownership
112    /// and call this until it returns `true`. This does not require a live `Dac` handle.
113    pub fn await_usb_retirement(timeout: Duration) -> bool {
114        transport::api::await_usb_retirement(timeout)
115    }
116
117    /// Identify optional capture interfaces after the host claims the base audio interfaces.
118    /// Returns the active configuration ID and source interface numbers without starting audio.
119    pub fn feedback_preflight(fd: RawFd, info: &DeviceInfo) -> Result<(u8, Vec<u8>)> {
120        let _guard = OPEN_GUARD.lock();
121        if transport::session::session_registered() {
122            return Err(Error::Busy);
123        }
124        transport::api::feedback_preflight(fd, info)
125    }
126
127    /// Opens the DAC behind `fd`.
128    ///
129    /// `fd` is the usbfs file descriptor of the device (on Android
130    /// `UsbDeviceConnection.getFileDescriptor()`); the library duplicates it, so
131    /// the host keeps ownership of its own. `info.claimed_interfaces` must be
132    /// the AudioControl and playback AudioStreaming interfaces plus any
133    /// optional capture sources identified by [`Dac::feedback_preflight`].
134    ///
135    /// Opening scans the descriptors, finds the hardware volume control, records
136    /// the DAC's current level and, with the default
137    /// [`StartupVolume::Attenuate`](crate::StartupVolume::Attenuate), lowers every
138    /// channel to at most -40 dB and verifies it, so that no stream can start
139    /// at the DAC's own (often full-scale) level. It does not touch the clock or
140    /// start any audio. [`VolumeControl::startup`](crate::VolumeControl::startup)
141    /// says what it did.
142    pub fn open(fd: RawFd, info: DeviceInfo, config: DacConfig) -> Result<Dac> {
143        config.validate()?;
144        let _guard = OPEN_GUARD.lock();
145        if transport::session::session_registered() {
146            return Err(Error::Busy);
147        }
148        settings::install(Settings::for_device(config.clone(), &info));
149        if let Err(error) = transport::api::open_device(fd, &info) {
150            settings::reset();
151            return Err(error);
152        }
153        let events = EventHub::start();
154        // The start-up step lowered the level before this handle existed: tell
155        // the first listener, as a change made through the library.
156        if let Some(state) = transport::volume_hw::startup_lowered_volume() {
157            events.emit_dac_or_hold(crate::events::DacEvent::VolumeChanged(state));
158        }
159        Ok(Dac {
160            shared: Arc::new(DacShared {
161                events,
162                info,
163                config,
164                closed: AtomicBool::new(false),
165                stream: Mutex::new(None),
166                last_feedback_stream: Mutex::new(None),
167            }),
168        })
169    }
170
171    /// The identity the host gave at open.
172    pub fn info(&self) -> &DeviceInfo {
173        &self.shared.info
174    }
175
176    /// Export the last stream's opt-in support capture, even after the stream
177    /// has closed. A new successfully opened stream replaces it.
178    pub fn feedback_trace(&self) -> Option<crate::FeedbackTrace> {
179        let (format, stats) = self.shared.last_feedback_stream.lock().clone()?;
180        let explicit = *stats.explicit_feedback_diagnostics.lock();
181        Some(stats.feedback_trace.as_ref()?.snapshot(format, explicit))
182    }
183
184    /// What the DAC offers, from the descriptors scanned at open.
185    pub fn capabilities(&self) -> Result<Capabilities> {
186        self.shared.ensure_open()?;
187        transport::api::capabilities()
188    }
189
190    /// Settles the wire format for `request`.
191    ///
192    /// This programs the DAC's sampling frequency and reads it back (it is the
193    /// step that can fail with [`Error::ClockUnverified`] later), so it takes
194    /// 100 ms or more. It fails with [`Error::InvalidState`] while a stream is
195    /// open. Nothing is resampled: with [`RatePolicy::Exact`] a rate the DAC
196    /// cannot run is [`Error::Unsupported`]; with `NearestSupported` the
197    /// returned format carries the rate the DAC will run.
198    ///
199    /// [`RatePolicy::Exact`]: crate::RatePolicy::Exact
200    pub fn negotiate(&self, request: &StreamRequest) -> Result<StreamFormat> {
201        self.shared.ensure_open()?;
202        transport::api::negotiate(request)
203    }
204
205    /// Opens the output stream for a negotiated format and starts the output
206    /// thread. The stream plays as soon as the ring holds the start threshold
207    /// ([`DacConfig::start_threshold_ms`]) of audio. Only one stream can be open
208    /// at a time.
209    ///
210    /// Fails with [`Error::VolumeUnavailable`] when the stream's own route has
211    /// no usable hardware volume control and
212    /// [`DacConfig::require_hardware_volume`] is on; nothing is programmed and
213    /// no output thread starts.
214    ///
215    /// `listener` receives the stream's events; see [`DacListener`].
216    pub fn open_stream(
217        &self,
218        format: &StreamFormat,
219        listener: Arc<dyn DacListener>,
220    ) -> Result<DacStream> {
221        self.shared.ensure_open()?;
222        let mut slot = self.shared.stream.lock();
223        if slot
224            .as_ref()
225            .and_then(Weak::upgrade)
226            .is_some_and(|stream| !stream.is_closed())
227        {
228            return Err(Error::InvalidState("a stream is already open".to_string()));
229        }
230        self.shared.events.set_stream_listener(Some(listener));
231        let handle = match transport::api::open_stream(format, self.shared.events.clone()) {
232            Ok(handle) => handle,
233            Err(error) => {
234                self.shared.events.set_stream_listener(None);
235                return Err(error);
236            }
237        };
238        let inner = StreamInner::new(Arc::clone(&self.shared), handle, format.clone());
239        if inner.shared.stats.feedback_trace.is_some() {
240            *self.shared.last_feedback_stream.lock() =
241                Some((format.clone(), Arc::clone(&inner.shared.stats)));
242        }
243        *slot = Some(Arc::downgrade(&inner));
244        drop(slot);
245        inner.start_events();
246        Ok(DacStream::from_inner(inner))
247    }
248
249    /// The hardware volume control, if the DAC has a writable one.
250    pub fn volume(&self) -> Option<VolumeControl> {
251        if self.shared.ensure_open().is_err() || !transport::volume_hw::has_hardware_volume() {
252            return None;
253        }
254        Some(VolumeControl::new(Arc::clone(&self.shared)))
255    }
256
257    /// Sets the listener for events about the device itself (volume changes,
258    /// device loss) while no stream is open. While a stream is open its
259    /// listener gets those events too.
260    pub fn set_listener(&self, listener: Option<Arc<dyn DacListener>>) {
261        self.shared.events.set_dac_listener(listener);
262    }
263
264    /// Closes the DAC: stops the stream if one is open, hands the volume back
265    /// as [`DacConfig::hand_back`] says, and releases the session so another
266    /// [`Dac::open`] can succeed. The host may then release its interfaces and
267    /// close its connection after success. If closing times out, keep all host
268    /// claims and the connection until [`Dac::await_usb_retirement`] returns
269    /// `true`. Dropping the `Dac` initiates the same cleanup, but cannot report
270    /// a timeout; hosts must still wait for retirement before releasing claims.
271    pub fn close(self) -> Result<()> {
272        self.shared.shutdown(None)
273    }
274
275    /// Like [`close`](Self::close), but the host says what becomes of the level
276    /// the DAC had before the library first changed it, instead of
277    /// [`DacConfig::hand_back`] deciding at open: write it back (another driver
278    /// gets the DAC), keep the record (the host holds on to the DAC or takes it
279    /// straight back) or forget it (the DAC was unplugged).
280    ///
281    /// A DAC the library saw disappear is always forgotten: nothing can be
282    /// written to it and a later attachment must start fresh.
283    pub fn close_with(self, volume: CloseVolume) -> Result<()> {
284        self.shared.shutdown(Some(volume))
285    }
286
287    /// Changes the native DSD overrides of the open DAC ([`DacConfig::dsd_big_endian`]
288    /// and [`DacConfig::dsd_subslot`]), for a host whose user can change them
289    /// while the DAC stays open. `None` goes back to the device quirk.
290    ///
291    /// They are read when a format is negotiated and when a stream is opened: a
292    /// stream that is already open keeps what it started with, and
293    /// [`capabilities`](Self::capabilities) reflects a new subslot size after the
294    /// next [`negotiate`](Self::negotiate). `subslot` must be 1, 2 or 4.
295    pub fn set_dsd_overrides(&self, big_endian: Option<bool>, subslot: Option<u8>) -> Result<()> {
296        self.shared.ensure_open()?;
297        if subslot.is_some_and(|size| !matches!(size, 1 | 2 | 4)) {
298            return Err(Error::InvalidArgument(
299                "dsd_subslot must be 1, 2 or 4".to_string(),
300            ));
301        }
302        settings::update(|config| {
303            config.dsd_big_endian = big_endian;
304            config.dsd_subslot = subslot;
305        });
306        Ok(())
307    }
308}
309
310impl Drop for Dac {
311    fn drop(&mut self) {
312        if let Err(error) = self.shared.shutdown(None) {
313            log::warn!("closing the DAC: {error}");
314        }
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::capabilities::DeviceInfo;
322
323    use crate::transport::session::PAYLOAD_LATCH_TEST_LOCK as SESSION_TEST_LOCK;
324
325    #[test]
326    fn a_second_open_while_one_is_registered_is_busy() {
327        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
328        let _registered = transport::session::TestSession::install();
329        let info = DeviceInfo::new(1, 2, "Fake DAC");
330        let error = Dac::open(-1, info, DacConfig::default()).unwrap_err();
331        assert_eq!(error, Error::Busy);
332        assert_eq!(error.code(), "busy");
333    }
334
335    #[test]
336    fn a_failed_open_leaves_nothing_registered() {
337        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
338        let info = DeviceInfo::new(1, 2, "Fake DAC");
339        let error = Dac::open(-1, info, DacConfig::default()).unwrap_err();
340        // No usbfs here (or an invalid descriptor): not Busy, and the slot is free.
341        assert!(
342            matches!(error, Error::PlatformUnsupported | Error::Claim(_)),
343            "{error:?}"
344        );
345        assert!(!transport::session::session_registered());
346    }
347
348    #[test]
349    fn an_invalid_config_is_rejected_before_anything_is_touched() {
350        let _serial = SESSION_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
351        let config = DacConfig {
352            buffer_target_ms: 900,
353            ..DacConfig::default()
354        };
355        let error = Dac::open(-1, DeviceInfo::new(1, 2, "x"), config).unwrap_err();
356        assert!(matches!(error, Error::InvalidArgument(_)));
357    }
358
359    /// A `Dac` over the fake registered session.
360    fn fake_dac_handle(config: DacConfig) -> Dac {
361        Dac {
362            shared: Arc::new(DacShared {
363                events: EventHub::start(),
364                info: DeviceInfo::new(0x1234, 0x5678, "test DAC"),
365                config,
366                closed: AtomicBool::new(false),
367                stream: Mutex::new(None),
368                last_feedback_stream: Mutex::new(None),
369            }),
370        }
371    }
372
373    /// A DAC whose level the library lowered, with the true original on record.
374    fn lowered_with_a_record() -> crate::transport::fake_dac::Registered {
375        use crate::transport::fake_dac::{Registered, ORIGINAL_RAW};
376        let fake = Registered::new(false, true);
377        fake.set_levels(ORIGINAL_RAW, ORIGINAL_RAW);
378        fake.record_original();
379        crate::transport::volume_hw::write_volume_db(-40.0).unwrap();
380        assert_ne!(fake.raw(), vec![ORIGINAL_RAW; 2]);
381        fake
382    }
383
384    #[test]
385    fn close_with_restore_writes_the_original_back_and_ends_the_record() {
386        use crate::transport::fake_dac::ORIGINAL_RAW;
387        let fake = lowered_with_a_record();
388        // The configuration says keep: the host's decision at close wins.
389        let dac = fake_dac_handle(DacConfig {
390            hand_back: HandBack::Keep,
391            ..DacConfig::default()
392        });
393        dac.close_with(CloseVolume::Restore).unwrap();
394        assert_eq!(fake.raw(), vec![ORIGINAL_RAW; 2]);
395        assert!(!fake.original_recorded());
396        assert!(!transport::session::session_registered());
397    }
398
399    #[test]
400    fn close_with_keep_leaves_the_level_and_the_record() {
401        use crate::transport::fake_dac::ORIGINAL_RAW;
402        let fake = lowered_with_a_record();
403        let lowered = fake.raw();
404        // The configuration says restore: again the host's decision wins.
405        let dac = fake_dac_handle(DacConfig::default());
406        dac.close_with(CloseVolume::Keep).unwrap();
407        assert_eq!(fake.raw(), lowered, "the level was not touched");
408        assert_ne!(lowered, vec![ORIGINAL_RAW; 2]);
409        assert!(
410            fake.original_recorded(),
411            "a later open still knows the true original"
412        );
413        assert!(!transport::session::session_registered());
414    }
415
416    #[test]
417    fn close_with_forget_ends_the_record_without_writing() {
418        let fake = lowered_with_a_record();
419        let lowered = fake.raw();
420        let writes = fake.dac.lock().unwrap().volume_writes.len();
421        let dac = fake_dac_handle(DacConfig::default());
422        dac.close_with(CloseVolume::Forget).unwrap();
423        assert_eq!(fake.raw(), lowered);
424        assert_eq!(
425            fake.dac.lock().unwrap().volume_writes.len(),
426            writes,
427            "nothing was written"
428        );
429        assert!(!fake.original_recorded());
430    }
431
432    #[test]
433    fn a_dac_the_library_saw_disappear_is_forgotten_whatever_close_asked_for() {
434        let fake = lowered_with_a_record();
435        let lowered = fake.raw();
436        let dac = fake_dac_handle(DacConfig::default());
437        dac.shared
438            .events
439            .emit_dac(crate::events::DacEvent::DeviceLost);
440        dac.close_with(CloseVolume::Restore).unwrap();
441        assert_eq!(fake.raw(), lowered, "no write to a DAC that is gone");
442        assert!(!fake.original_recorded());
443    }
444
445    #[test]
446    fn a_plain_close_still_follows_the_configuration() {
447        use crate::transport::fake_dac::ORIGINAL_RAW;
448        let fake = lowered_with_a_record();
449        fake_dac_handle(DacConfig::default()).close().unwrap();
450        assert_eq!(
451            fake.raw(),
452            vec![ORIGINAL_RAW; 2],
453            "the default is to restore"
454        );
455        drop(fake);
456
457        let fake = lowered_with_a_record();
458        let lowered = fake.raw();
459        fake_dac_handle(DacConfig {
460            hand_back: HandBack::Keep,
461            ..DacConfig::default()
462        })
463        .close()
464        .unwrap();
465        assert_eq!(fake.raw(), lowered);
466        assert!(fake.original_recorded());
467    }
468
469    #[test]
470    fn dsd_overrides_change_the_settings_of_the_open_dac_and_are_validated() {
471        let fake = crate::transport::fake_dac::Registered::new(false, false);
472        fake.configure(DacConfig::default());
473        let dac = fake_dac_handle(DacConfig::default());
474        assert!(!settings::settings().dsd_big_endian());
475        assert_eq!(settings::settings().dsd_subslot_override(), None);
476
477        dac.set_dsd_overrides(Some(true), Some(2)).unwrap();
478        assert!(settings::settings().dsd_big_endian());
479        assert_eq!(settings::settings().dsd_subslot_override(), Some(2));
480
481        assert!(matches!(
482            dac.set_dsd_overrides(None, Some(3)),
483            Err(Error::InvalidArgument(_))
484        ));
485        assert_eq!(
486            settings::settings().dsd_subslot_override(),
487            Some(2),
488            "a refused call changes nothing"
489        );
490
491        dac.set_dsd_overrides(None, None).unwrap();
492        assert!(!settings::settings().dsd_big_endian());
493        assert_eq!(settings::settings().dsd_subslot_override(), None);
494        dac.close().unwrap();
495        drop(fake);
496    }
497
498    #[test]
499    fn dsd_overrides_keep_the_quirks_resolved_for_the_device() {
500        let fake = crate::transport::fake_dac::Registered::new(false, false);
501        fake.configure(DacConfig {
502            quirks: vec![crate::config::QuirkOverride {
503                vendor_id: 0x1234,
504                product_id: 0x5678,
505                name_contains: None,
506                quirks: vec![
507                    crate::quirk::Quirk::SettleDelayMs(80),
508                    crate::quirk::Quirk::DsdBigEndian,
509                ],
510            }],
511            ..DacConfig::default()
512        });
513        let dac = fake_dac_handle(DacConfig::default());
514        // The quirk gives big-endian; an override of "little-endian" wins over it.
515        assert!(settings::settings().dsd_big_endian());
516        dac.set_dsd_overrides(Some(false), None).unwrap();
517        assert!(!settings::settings().dsd_big_endian());
518        assert_eq!(
519            settings::settings().settle_delay_ms(),
520            80,
521            "the device quirk is still there"
522        );
523        // `None` goes back to the quirk.
524        dac.set_dsd_overrides(None, None).unwrap();
525        assert!(settings::settings().dsd_big_endian());
526        dac.close().unwrap();
527        drop(fake);
528    }
529
530    #[test]
531    fn the_volume_handle_works_without_a_stream_and_reports_changes() {
532        use crate::events::DacEvent;
533        use crate::transport::fake_dac::Registered;
534        use crate::volume::VolumeControl;
535
536        struct Seen(Mutex<Vec<DacEvent>>);
537        impl DacListener for Seen {
538            fn on_event(&self, event: DacEvent) {
539                self.0.lock().push(event);
540            }
541        }
542
543        // Holds the process-wide test lock for the whole test.
544        let fake = Registered::new(false, true);
545        let events = EventHub::start();
546        let seen = Arc::new(Seen(Mutex::new(Vec::new())));
547        events.set_dac_listener(Some(seen.clone()));
548        let shared = Arc::new(DacShared {
549            events: events.clone(),
550            info: DeviceInfo::new(0x1234, 0x5678, "test DAC"),
551            config: DacConfig::default(),
552            closed: AtomicBool::new(false),
553            stream: Mutex::new(None),
554            last_feedback_stream: Mutex::new(None),
555        });
556        let volume = VolumeControl::new(shared.clone());
557
558        let range = volume.range().unwrap();
559        assert_eq!(
560            (range.min_db, range.max_db, range.res_db),
561            (-80.0, 0.0, 1.0)
562        );
563        let initial = volume.get().unwrap();
564        assert_eq!(initial.db, -64.0);
565        assert_eq!(initial.muted, Some(false));
566
567        let set = volume.set_db(-30.0).unwrap();
568        assert_eq!(set.db, -30.0);
569        assert_eq!(fake.raw(), vec![-30 * 256, -30 * 256]);
570        let up = volume.step(1, 0).unwrap();
571        assert!(up.db > -30.0, "{up:?}");
572        let half = volume.set_fraction(0.5).unwrap();
573        assert!((half.fraction - 0.5).abs() < 0.01, "{half:?}");
574        assert_eq!(volume.set_mute(true).unwrap().muted, Some(true));
575        assert_eq!(
576            volume.original_db(),
577            None,
578            "nothing was recorded by the fake"
579        );
580
581        // An unreachable DAC fails the call; the handle stays usable.
582        fake.dac.lock().unwrap().unreachable = true;
583        assert!(volume.get().is_err());
584        fake.dac.lock().unwrap().unreachable = false;
585
586        for _ in 0..200 {
587            if seen.0.lock().len() >= 4 {
588                break;
589            }
590            std::thread::sleep(Duration::from_millis(5));
591        }
592        events.shutdown();
593        let changes: Vec<f64> = seen
594            .0
595            .lock()
596            .iter()
597            .filter_map(|event| match event {
598                DacEvent::VolumeChanged(state) => Some(state.db),
599                _ => None,
600            })
601            .collect();
602        assert_eq!(
603            changes.len(),
604            4,
605            "set_db, step, set_fraction, set_mute: {changes:?}"
606        );
607        assert_eq!(changes[0], -30.0);
608
609        shared.closed.store(true, Ordering::Release);
610        assert!(matches!(volume.get(), Err(Error::InvalidState(_))));
611    }
612}