summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndrew Walbran <qwandor@google.com>2021-08-03 14:20:19 +0000
committerAndrew Walbran <qwandor@google.com>2021-08-03 14:20:19 +0000
commit8dce65084f73d40bb081312769a24b4bd533f667 (patch)
treee2118ad5dbee0370c6ab114bb3974cd9f09a2251
parentbcf1f249f11b6865cff3f0d3f0ae5801e67e0e7e (diff)
downloadadhd-android-t-preview-1.tar.gz
This repository will be removed from the manifest change, but Treehugger seems unable to test the manifest change, so this change first removes all files so we can test that instead. Bug: 190503456 Test: m crosvm Change-Id: I133ef3bd8b39035a68113c4da8fe4c637a40daac
-rw-r--r--Android.bp52
-rw-r--r--LICENSE.SUPERFASTHASH27
-rw-r--r--LICENSE.UTLIST22
-rw-r--r--LICENSE.WEBKIT27
-rw-r--r--METADATA3
-rw-r--r--MODULE_LICENSE_BSD0
-rw-r--r--Makefile94
-rw-r--r--NOTICE76
-rw-r--r--OWNERS.fuzz5
-rw-r--r--PRESUBMIT.cfg19
-rw-r--r--audio_streams/.gitignore2
-rw-r--r--audio_streams/Android.bp61
-rw-r--r--audio_streams/Cargo.toml12
-rw-r--r--audio_streams/README.md6
-rw-r--r--audio_streams/src/audio_streams.rs471
-rw-r--r--audio_streams/src/capture.rs250
-rw-r--r--audio_streams/src/shm_streams.rs568
-rw-r--r--cras-config/device_blocklist2
-rw-r--r--cras-config/dsp.ini.sample104
-rw-r--r--cras-config/for_all_boards/Chat 150 C4
-rw-r--r--cras-config/for_all_boards/Jabra SPEAK 8104
-rw-r--r--cras-config/for_all_boards/Logitech MeetUp Speakerphone103
-rw-r--r--cras/.gitignore45
-rw-r--r--cras/Makefile.am14
-rw-r--r--cras/README.dbus-api238
-rw-r--r--cras/README.md222
-rw-r--r--cras/client/cras-sys/.gitignore2
-rw-r--r--cras/client/cras-sys/.rustfmt.toml2
-rw-r--r--cras/client/cras-sys/Android.bp62
-rw-r--r--cras/client/cras-sys/Cargo.toml8
-rw-r--r--cras/client/cras-sys/generator/.gitignore2
-rw-r--r--cras/client/cras-sys/generator/Cargo.toml7
-rw-r--r--cras/client/cras-sys/generator/README.md3
-rw-r--r--cras/client/cras-sys/generator/src/main.rs159
-rw-r--r--cras/client/cras-sys/src/gen.rs5004
-rw-r--r--cras/client/cras-sys/src/lib.rs657
-rw-r--r--cras/client/cras_tests/.gitignore2
-rw-r--r--cras/client/cras_tests/.rustfmt.toml2
-rw-r--r--cras/client/cras_tests/Cargo.toml17
-rw-r--r--cras/client/cras_tests/src/arguments.rs462
-rw-r--r--cras/client/cras_tests/src/audio.rs414
-rw-r--r--cras/client/cras_tests/src/control.rs106
-rw-r--r--cras/client/cras_tests/src/main.rs58
-rw-r--r--cras/client/libcras/.gitignore2
-rw-r--r--cras/client/libcras/.rustfmt.toml2
-rw-r--r--cras/client/libcras/Android.bp69
-rw-r--r--cras/client/libcras/Cargo.toml15
-rw-r--r--cras/client/libcras/src/audio_socket.rs316
-rw-r--r--cras/client/libcras/src/cras_client_message.rs200
-rw-r--r--cras/client/libcras/src/cras_server_socket.rs124
-rw-r--r--cras/client/libcras/src/cras_shm.rs1308
-rw-r--r--cras/client/libcras/src/cras_shm_stream.rs191
-rw-r--r--cras/client/libcras/src/cras_stream.rs224
-rw-r--r--cras/client/libcras/src/libcras.rs699
-rw-r--r--cras/configure.ac206
-rw-r--r--cras/cras.mk32
-rw-r--r--cras/examples/Makefile5
-rw-r--r--cras/examples/cplay.c100
-rw-r--r--cras/examples/cplay_buffer.c77
-rwxr-xr-xcras/git_prepare.sh5
-rwxr-xr-xcras/install_deps.sh51
-rw-r--r--cras/libcras.pc.in11
-rw-r--r--cras/src/Android.bp44
-rw-r--r--cras/src/Makefile.am1078
-rw-r--r--cras/src/alsa_plugin/ctl_cras.c280
-rw-r--r--cras/src/alsa_plugin/pcm_cras.c405
-rw-r--r--cras/src/common/a2dp-codecs.h139
-rw-r--r--cras/src/common/array.h117
-rw-r--r--cras/src/common/bluetooth.h84
-rw-r--r--cras/src/common/byte_buffer.h137
-rw-r--r--cras/src/common/cras_audio_codec.h28
-rw-r--r--cras/src/common/cras_audio_format.c171
-rw-r--r--cras/src/common/cras_audio_format.h176
-rw-r--r--cras/src/common/cras_checksum.c79
-rw-r--r--cras/src/common/cras_checksum.h21
-rw-r--r--cras/src/common/cras_config.c61
-rw-r--r--cras/src/common/cras_config.h49
-rw-r--r--cras/src/common/cras_file_wait.c319
-rw-r--r--cras/src/common/cras_file_wait.h128
-rw-r--r--cras/src/common/cras_iodev_info.h79
-rw-r--r--cras/src/common/cras_messages.h756
-rw-r--r--cras/src/common/cras_metrics.c58
-rw-r--r--cras/src/common/cras_metrics.h19
-rw-r--r--cras/src/common/cras_observer_ops.h65
-rw-r--r--cras/src/common/cras_sbc_codec.c201
-rw-r--r--cras/src/common/cras_sbc_codec.h44
-rw-r--r--cras/src/common/cras_selinux_helper.c12
-rw-r--r--cras/src/common/cras_shm.c309
-rw-r--r--cras/src/common/cras_shm.h659
-rw-r--r--cras/src/common/cras_types.h723
-rw-r--r--cras/src/common/cras_util.c264
-rw-r--r--cras/src/common/cras_util.h254
-rw-r--r--cras/src/common/dumper.c159
-rw-r--r--cras/src/common/dumper.h49
-rw-r--r--cras/src/common/edid_utils.c833
-rw-r--r--cras/src/common/edid_utils.h204
-rw-r--r--cras/src/common/packet_status_logger.c35
-rw-r--r--cras/src/common/packet_status_logger.h127
-rw-r--r--cras/src/common/rtp.h76
-rw-r--r--cras/src/common/sfh.c92
-rw-r--r--cras/src/common/sfh.h16
-rw-r--r--cras/src/common/utlist.h231
-rw-r--r--cras/src/dsp/biquad.c381
-rw-r--r--cras/src/dsp/biquad.h57
-rw-r--r--cras/src/dsp/crossover.c188
-rw-r--r--cras/src/dsp/crossover.h70
-rw-r--r--cras/src/dsp/crossover2.c689
-rw-r--r--cras/src/dsp/crossover2.h75
-rw-r--r--cras/src/dsp/dcblock.c68
-rw-r--r--cras/src/dsp/dcblock.h42
-rw-r--r--cras/src/dsp/drc.c396
-rw-r--r--cras/src/dsp/drc.h183
-rw-r--r--cras/src/dsp/drc_kernel.c1060
-rw-r--r--cras/src/dsp/drc_kernel.h109
-rw-r--r--cras/src/dsp/drc_math.c14
-rw-r--r--cras/src/dsp/drc_math.h217
-rw-r--r--cras/src/dsp/dsp_util.c611
-rw-r--r--cras/src/dsp/dsp_util.h55
-rw-r--r--cras/src/dsp/eq.c148
-rw-r--r--cras/src/dsp/eq.h67
-rw-r--r--cras/src/dsp/eq2.c343
-rw-r--r--cras/src/dsp/eq2.h71
-rw-r--r--cras/src/dsp/tests/cmpraw.c58
-rw-r--r--cras/src/dsp/tests/crossover2_test.c89
-rw-r--r--cras/src/dsp/tests/crossover_test.c93
-rw-r--r--cras/src/dsp/tests/dcblock_test.c79
-rw-r--r--cras/src/dsp/tests/drc_test.c100
-rw-r--r--cras/src/dsp/tests/dsp_test_util.c37
-rw-r--r--cras/src/dsp/tests/dsp_test_util.h27
-rw-r--r--cras/src/dsp/tests/dsp_util_test.c389
-rw-r--r--cras/src/dsp/tests/eq2_test.c95
-rw-r--r--cras/src/dsp/tests/eq_test.c140
-rw-r--r--cras/src/dsp/tests/plot_fftl.m40
-rw-r--r--cras/src/dsp/tests/raw.c93
-rw-r--r--cras/src/dsp/tests/raw.h46
-rw-r--r--cras/src/fuzz/.clang-format1
-rw-r--r--cras/src/fuzz/Dockerfile13
-rw-r--r--cras/src/fuzz/README.md44
-rwxr-xr-xcras/src/fuzz/build.sh24
-rw-r--r--cras/src/fuzz/corpus/06051efd871be7eb2b4baed61c3ba53fe0b27833bin8 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/06e2b48cb549540ab62c0a62a1480f3de7807896bin63 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/1cea528aa30177cb48d9b279b7d1f115b5a60c01bin12 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/348b671615268f526f174ed2f89d887a26ee8b7abin63 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/756692a278ad08a8f3a9e198b1436620c53247e9bin12 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/90c740f0e2e83b050ba7ccc2b963f2cb6bf23bc1bin20 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/9448261a4711bdb5e62490e57f78a9a8d99cfd90bin20 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/b148b3ca1a089964a122b42170eb39e41461e8debin8 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/c66fae687ac462af608f9f22ea1b9493b66fe844bin63 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/da39a3ee5e6b4b0d3255bfef95601890afd807090
-rw-r--r--cras/src/fuzz/corpus/da6b17d11511d4c4eb14933aa404715e753e2c02bin20 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/e578774a32e52e17461c30848f554f78c3ffda66bin12 -> 0 bytes
-rw-r--r--cras/src/fuzz/corpus/e85fb46a837d5a798d371573b41fd60e1e1486edbin20 -> 0 bytes
-rw-r--r--cras/src/fuzz/cras_hfp_slc.cc66
-rw-r--r--cras/src/fuzz/cras_hfp_slc.dict23
-rw-r--r--cras/src/fuzz/rclient_message.cc68
-rw-r--r--cras/src/libcras/cras_client.c4249
-rw-r--r--cras/src/libcras/cras_client.h2008
-rw-r--r--cras/src/libcras/cras_helpers.c159
-rw-r--r--cras/src/libcras/cras_helpers.h95
-rw-r--r--cras/src/plc/cras_plc.c285
-rw-r--r--cras/src/plc/cras_plc.h54
-rw-r--r--cras/src/plc/cras_plc_test.c223
-rwxr-xr-xcras/src/plc/parse_sco.py107
-rw-r--r--cras/src/server/audio_thread.c1314
-rw-r--r--cras/src/server/audio_thread.h222
-rw-r--r--cras/src/server/audio_thread_log.h93
-rw-r--r--cras/src/server/buffer_share.c171
-rw-r--r--cras/src/server/buffer_share.h61
-rw-r--r--cras/src/server/config/cras_board_config.c97
-rw-r--r--cras/src/server/config/cras_board_config.h29
-rw-r--r--cras/src/server/config/cras_card_config.c110
-rw-r--r--cras/src/server/config/cras_card_config.h37
-rw-r--r--cras/src/server/config/cras_device_blocklist.c56
-rw-r--r--cras/src/server/config/cras_device_blocklist.h48
-rw-r--r--cras/src/server/cras.c146
-rw-r--r--cras/src/server/cras_a2dp_endpoint.c226
-rw-r--r--cras/src/server/cras_a2dp_endpoint.h26
-rw-r--r--cras/src/server/cras_a2dp_info.c187
-rw-r--r--cras/src/server/cras_a2dp_info.h89
-rw-r--r--cras/src/server/cras_a2dp_iodev.c709
-rw-r--r--cras/src/server/cras_a2dp_iodev.h25
-rw-r--r--cras/src/server/cras_alert.c184
-rw-r--r--cras/src/server/cras_alert.h129
-rw-r--r--cras/src/server/cras_alsa_card.c641
-rw-r--r--cras/src/server/cras_alsa_card.h51
-rw-r--r--cras/src/server/cras_alsa_helpers.c799
-rw-r--r--cras/src/server/cras_alsa_helpers.h227
-rw-r--r--cras/src/server/cras_alsa_io.c2473
-rw-r--r--cras/src/server/cras_alsa_io.h88
-rw-r--r--cras/src/server/cras_alsa_jack.c1243
-rw-r--r--cras/src/server/cras_alsa_jack.h155
-rw-r--r--cras/src/server/cras_alsa_mixer.c1174
-rw-r--r--cras/src/server/cras_alsa_mixer.h235
-rw-r--r--cras/src/server/cras_alsa_mixer_name.c131
-rw-r--r--cras/src/server/cras_alsa_mixer_name.h102
-rw-r--r--cras/src/server/cras_alsa_plugin_io.c265
-rw-r--r--cras/src/server/cras_alsa_plugin_io.h20
-rw-r--r--cras/src/server/cras_alsa_ucm.c1237
-rw-r--r--cras/src/server/cras_alsa_ucm.h512
-rw-r--r--cras/src/server/cras_alsa_ucm_section.c129
-rw-r--r--cras/src/server/cras_alsa_ucm_section.h117
-rw-r--r--cras/src/server/cras_apm_list.c730
-rw-r--r--cras/src/server/cras_apm_list.h248
-rw-r--r--cras/src/server/cras_audio_area.c105
-rw-r--r--cras/src/server/cras_audio_area.h99
-rw-r--r--cras/src/server/cras_audio_thread_monitor.c139
-rw-r--r--cras/src/server/cras_audio_thread_monitor.h54
-rw-r--r--cras/src/server/cras_bt_adapter.c383
-rw-r--r--cras/src/server/cras_bt_adapter.h50
-rw-r--r--cras/src/server/cras_bt_battery_provider.c371
-rw-r--r--cras/src/server/cras_bt_battery_provider.h47
-rw-r--r--cras/src/server/cras_bt_constants.h71
-rw-r--r--cras/src/server/cras_bt_device.c1409
-rw-r--r--cras/src/server/cras_bt_device.h230
-rw-r--r--cras/src/server/cras_bt_endpoint.c583
-rw-r--r--cras/src/server/cras_bt_endpoint.h59
-rw-r--r--cras/src/server/cras_bt_io.c721
-rw-r--r--cras/src/server/cras_bt_io.h54
-rw-r--r--cras/src/server/cras_bt_log.h56
-rw-r--r--cras/src/server/cras_bt_manager.c619
-rw-r--r--cras/src/server/cras_bt_manager.h14
-rw-r--r--cras/src/server/cras_bt_player.c486
-rw-r--r--cras/src/server/cras_bt_player.h95
-rw-r--r--cras/src/server/cras_bt_profile.c479
-rw-r--r--cras/src/server/cras_bt_profile.h91
-rw-r--r--cras/src/server/cras_bt_transport.c634
-rw-r--r--cras/src/server/cras_bt_transport.h87
-rw-r--r--cras/src/server/cras_capture_rclient.c35
-rw-r--r--cras/src/server/cras_capture_rclient.h20
-rw-r--r--cras/src/server/cras_control_rclient.c572
-rw-r--r--cras/src/server/cras_control_rclient.h20
-rw-r--r--cras/src/server/cras_dbus.c184
-rw-r--r--cras/src/server/cras_dbus.h28
-rw-r--r--cras/src/server/cras_dbus_control.c1532
-rw-r--r--cras/src/server/cras_dbus_control.h15
-rw-r--r--cras/src/server/cras_dbus_util.c29
-rw-r--r--cras/src/server/cras_dbus_util.h18
-rw-r--r--cras/src/server/cras_device_monitor.c119
-rw-r--r--cras/src/server/cras_device_monitor.h22
-rw-r--r--cras/src/server/cras_dsp.c265
-rw-r--r--cras/src/server/cras_dsp.h89
-rw-r--r--cras/src/server/cras_dsp_ini.c492
-rw-r--r--cras/src/server/cras_dsp_ini.h102
-rw-r--r--cras/src/server/cras_dsp_mod_builtin.c631
-rw-r--r--cras/src/server/cras_dsp_mod_ladspa.c217
-rw-r--r--cras/src/server/cras_dsp_module.h118
-rw-r--r--cras/src/server/cras_dsp_pipeline.c1007
-rw-r--r--cras/src/server/cras_dsp_pipeline.h159
-rw-r--r--cras/src/server/cras_empty_iodev.c254
-rw-r--r--cras/src/server/cras_empty_iodev.h28
-rw-r--r--cras/src/server/cras_expr.c653
-rw-r--r--cras/src/server/cras_expr.h108
-rw-r--r--cras/src/server/cras_fmt_conv.c847
-rw-r--r--cras/src/server/cras_fmt_conv.h105
-rw-r--r--cras/src/server/cras_fmt_conv_ops.c503
-rw-r--r--cras/src/server/cras_fmt_conv_ops.h109
-rw-r--r--cras/src/server/cras_gpio_jack.c100
-rw-r--r--cras/src/server/cras_gpio_jack.h47
-rw-r--r--cras/src/server/cras_hfp_ag_profile.c466
-rw-r--r--cras/src/server/cras_hfp_ag_profile.h59
-rw-r--r--cras/src/server/cras_hfp_alsa_iodev.c336
-rw-r--r--cras/src/server/cras_hfp_alsa_iodev.h30
-rw-r--r--cras/src/server/cras_hfp_info.c868
-rw-r--r--cras/src/server/cras_hfp_info.h127
-rw-r--r--cras/src/server/cras_hfp_iodev.c371
-rw-r--r--cras/src/server/cras_hfp_iodev.h33
-rw-r--r--cras/src/server/cras_hfp_slc.c1400
-rw-r--r--cras/src/server/cras_hfp_slc.h156
-rw-r--r--cras/src/server/cras_hotword_handler.c64
-rw-r--r--cras/src/server/cras_hotword_handler.h24
-rw-r--r--cras/src/server/cras_iodev.c1719
-rw-r--r--cras/src/server/cras_iodev.h850
-rw-r--r--cras/src/server/cras_iodev_list.c1920
-rw-r--r--cras/src/server/cras_iodev_list.h285
-rw-r--r--cras/src/server/cras_loopback_iodev.c362
-rw-r--r--cras/src/server/cras_loopback_iodev.h21
-rw-r--r--cras/src/server/cras_main_message.c117
-rw-r--r--cras/src/server/cras_main_message.h49
-rw-r--r--cras/src/server/cras_main_thread_log.h64
-rw-r--r--cras/src/server/cras_mix.c78
-rw-r--r--cras/src/server/cras_mix.h83
-rw-r--r--cras/src/server/cras_mix_ops.c850
-rw-r--r--cras/src/server/cras_mix_ops.h47
-rw-r--r--cras/src/server/cras_non_empty_audio_handler.c61
-rw-r--r--cras/src/server/cras_non_empty_audio_handler.h25
-rw-r--r--cras/src/server/cras_observer.c634
-rw-r--r--cras/src/server/cras_observer.h109
-rw-r--r--cras/src/server/cras_playback_rclient.c35
-rw-r--r--cras/src/server/cras_playback_rclient.h20
-rw-r--r--cras/src/server/cras_ramp.c136
-rw-r--r--cras/src/server/cras_ramp.h91
-rw-r--r--cras/src/server/cras_rclient.c101
-rw-r--r--cras/src/server/cras_rclient.h98
-rw-r--r--cras/src/server/cras_rclient_util.c316
-rw-r--r--cras/src/server/cras_rclient_util.h125
-rw-r--r--cras/src/server/cras_rstream.c560
-rw-r--r--cras/src/server/cras_rstream.h325
-rw-r--r--cras/src/server/cras_rstream_config.c77
-rw-r--r--cras/src/server/cras_rstream_config.h101
-rw-r--r--cras/src/server/cras_server.c720
-rw-r--r--cras/src/server/cras_server.h38
-rw-r--r--cras/src/server/cras_server_metrics.c1326
-rw-r--r--cras/src/server/cras_server_metrics.h88
-rw-r--r--cras/src/server/cras_system_state.c714
-rw-r--r--cras/src/server/cras_system_state.h365
-rw-r--r--cras/src/server/cras_telephony.c455
-rw-r--r--cras/src/server/cras_telephony.h54
-rw-r--r--cras/src/server/cras_tm.c149
-rw-r--r--cras/src/server/cras_tm.h54
-rw-r--r--cras/src/server/cras_udev.c426
-rw-r--r--cras/src/server/cras_udev.h12
-rw-r--r--cras/src/server/cras_unified_rclient.c37
-rw-r--r--cras/src/server/cras_unified_rclient.h21
-rw-r--r--cras/src/server/cras_utf8.c182
-rw-r--r--cras/src/server/cras_utf8.h36
-rw-r--r--cras/src/server/cras_volume_curve.c80
-rw-r--r--cras/src/server/cras_volume_curve.h57
-rw-r--r--cras/src/server/dev_io.c1583
-rw-r--r--cras/src/server/dev_io.h113
-rw-r--r--cras/src/server/dev_stream.c782
-rw-r--r--cras/src/server/dev_stream.h234
-rw-r--r--cras/src/server/ewma_power.c81
-rw-r--r--cras/src/server/ewma_power.h65
-rw-r--r--cras/src/server/float_buffer.h126
-rw-r--r--cras/src/server/iniparser_wrapper.h30
-rw-r--r--cras/src/server/input_data.c210
-rw-r--r--cras/src/server/input_data.h95
-rw-r--r--cras/src/server/linear_resampler.c171
-rw-r--r--cras/src/server/linear_resampler.h57
-rw-r--r--cras/src/server/polled_interval_checker.c53
-rw-r--r--cras/src/server/polled_interval_checker.h49
-rw-r--r--cras/src/server/rust/.gitignore1
-rw-r--r--cras/src/server/rust/Cargo.toml17
-rw-r--r--cras/src/server/rust/binding_generator/Cargo.toml8
-rw-r--r--cras/src/server/rust/binding_generator/src/main.rs27
-rw-r--r--cras/src/server/rust/src/headers/rate_estimator.h85
-rw-r--r--cras/src/server/rust/src/rate_estimator.rs188
-rw-r--r--cras/src/server/rust/src/rate_estimator_bindings.rs110
-rw-r--r--cras/src/server/server_stream.c87
-rw-r--r--cras/src/server/server_stream.h29
-rw-r--r--cras/src/server/softvol_curve.c62
-rw-r--r--cras/src/server/softvol_curve.h32
-rw-r--r--cras/src/server/stream_list.c188
-rw-r--r--cras/src/server/stream_list.h68
-rw-r--r--cras/src/server/test_iodev.c267
-rw-r--r--cras/src/server/test_iodev.h32
-rw-r--r--cras/src/tests/.clang-format14
-rw-r--r--cras/src/tests/a2dp_info_unittest.cc133
-rw-r--r--cras/src/tests/a2dp_iodev_unittest.cc962
-rw-r--r--cras/src/tests/alert_unittest.cc227
-rw-r--r--cras/src/tests/alsa_card_unittest.cc1289
-rw-r--r--cras/src/tests/alsa_helpers_unittest.cc293
-rw-r--r--cras/src/tests/alsa_io_unittest.cc3045
-rw-r--r--cras/src/tests/alsa_jack_unittest.cc1104
-rw-r--r--cras/src/tests/alsa_mixer_unittest.cc1645
-rw-r--r--cras/src/tests/alsa_ucm_unittest.cc1564
-rw-r--r--cras/src/tests/apm_list_unittest.cc444
-rw-r--r--cras/src/tests/array_unittest.cc116
-rw-r--r--cras/src/tests/audio_area_unittest.cc340
-rw-r--r--cras/src/tests/audio_format_unittest.cc102
-rw-r--r--cras/src/tests/audio_test_gui.py266
-rw-r--r--cras/src/tests/audio_thread_monitor_unittest.cc131
-rw-r--r--cras/src/tests/audio_thread_unittest.cc1475
-rw-r--r--cras/src/tests/audio_thread_unittest_obsolete.cc2191
-rw-r--r--cras/src/tests/biquad_unittest.cc216
-rw-r--r--cras/src/tests/bt_device_unittest.cc781
-rw-r--r--cras/src/tests/bt_io_unittest.cc493
-rw-r--r--cras/src/tests/bt_profile_unittest.cc182
-rw-r--r--cras/src/tests/buffer_share_unittest.cc114
-rw-r--r--cras/src/tests/byte_buffer_unittest.cc103
-rw-r--r--cras/src/tests/capture_rclient_unittest.cc278
-rw-r--r--cras/src/tests/card_config_unittest.cc283
-rw-r--r--cras/src/tests/checksum_unittest.cc37
-rw-r--r--cras/src/tests/control_rclient_unittest.cc977
-rw-r--r--cras/src/tests/cras_abi_unittest.cc139
-rw-r--r--cras/src/tests/cras_client_unittest.cc432
-rw-r--r--cras/src/tests/cras_dsp_pipeline_unittest.cc518
-rw-r--r--cras/src/tests/cras_selinux_helper_unittest.c10
-rw-r--r--cras/src/tests/cras_tm_unittest.cc198
-rw-r--r--cras/src/tests/dbus_test.cc734
-rw-r--r--cras/src/tests/dbus_test.h325
-rw-r--r--cras/src/tests/dev_io_stubs.cc169
-rw-r--r--cras/src/tests/dev_io_stubs.h81
-rw-r--r--cras/src/tests/dev_io_unittest.cc468
-rw-r--r--cras/src/tests/dev_stream_unittest.cc1336
-rw-r--r--cras/src/tests/device_blocklist_unittest.cc88
-rw-r--r--cras/src/tests/device_monitor_unittest.cc150
-rw-r--r--cras/src/tests/dsp_core_unittest.cc433
-rw-r--r--cras/src/tests/dsp_ini_unittest.cc308
-rw-r--r--cras/src/tests/dsp_unittest.cc155
-rw-r--r--cras/src/tests/dumper_unittest.cc61
-rw-r--r--cras/src/tests/edid_utils_unittest.cc274
-rw-r--r--cras/src/tests/empty_audio_stub.cc24
-rw-r--r--cras/src/tests/empty_iodev_unittest.cc100
-rw-r--r--cras/src/tests/ewma_power_unittest.cc129
-rw-r--r--cras/src/tests/expr_unittest.cc248
-rw-r--r--cras/src/tests/file_wait_unittest.cc277
-rw-r--r--cras/src/tests/float_buffer_unittest.cc53
-rw-r--r--cras/src/tests/fmt_conv_ops_unittest.cc855
-rw-r--r--cras/src/tests/fmt_conv_unittest.cc1781
-rw-r--r--cras/src/tests/hfp_ag_profile_unittest.cc310
-rw-r--r--cras/src/tests/hfp_alsa_iodev_unittest.cc543
-rw-r--r--cras/src/tests/hfp_info_unittest.cc586
-rw-r--r--cras/src/tests/hfp_iodev_unittest.cc409
-rw-r--r--cras/src/tests/hfp_slc_unittest.cc457
-rw-r--r--cras/src/tests/input_data_unittest.cc148
-rw-r--r--cras/src/tests/iodev_list_unittest.cc2362
-rw-r--r--cras/src/tests/iodev_stub.cc225
-rw-r--r--cras/src/tests/iodev_stub.h25
-rw-r--r--cras/src/tests/iodev_unittest.cc2801
-rw-r--r--cras/src/tests/linear_resampler_unittest.cc220
-rw-r--r--cras/src/tests/loopback_iodev_unittest.cc297
-rw-r--r--cras/src/tests/metrics_stub.cc66
-rw-r--r--cras/src/tests/metrics_stub.h9
-rw-r--r--cras/src/tests/mix_unittest.cc1271
-rw-r--r--cras/src/tests/observer_unittest.cc726
-rw-r--r--cras/src/tests/playback_rclient_unittest.cc308
-rw-r--r--cras/src/tests/polled_interval_checker_unittest.cc155
-rw-r--r--cras/src/tests/ramp_unittest.cc513
-rw-r--r--cras/src/tests/rate_estimator_unittest.cc182
-rw-r--r--cras/src/tests/rstream_stub.cc120
-rw-r--r--cras/src/tests/rstream_stub.h20
-rw-r--r--cras/src/tests/rstream_unittest.cc437
-rw-r--r--cras/src/tests/sbc_codec_stub.cc174
-rw-r--r--cras/src/tests/sbc_codec_stub.h39
-rw-r--r--cras/src/tests/server_metrics_unittest.cc403
-rw-r--r--cras/src/tests/shm_unittest.cc572
-rw-r--r--cras/src/tests/softvol_curve_unittest.cc36
-rw-r--r--cras/src/tests/stream_list_unittest.cc216
-rw-r--r--cras/src/tests/system_state_unittest.cc576
-rw-r--r--cras/src/tests/timing_unittest.cc1246
-rw-r--r--cras/src/tests/utf8_unittest.cc159
-rw-r--r--cras/src/tests/util_unittest.cc330
-rw-r--r--cras/src/tests/volume_curve_unittest.cc54
-rw-r--r--cras/src/tools/cras_monitor/cras_monitor.c309
-rw-r--r--cras/src/tools/cras_router/cras_router.c241
-rw-r--r--cras/src/tools/cras_test_client/cras_test_client.c2426
-rwxr-xr-xcras/tools/create_volume_curve.py72
-rw-r--r--cros_alsa/.gitignore3
-rw-r--r--cros_alsa/.rustfmt.toml2
-rw-r--r--cros_alsa/Cargo.toml15
-rw-r--r--cros_alsa/cros_alsa_derive/Cargo.toml14
-rw-r--r--cros_alsa/cros_alsa_derive/src/common.rs77
-rw-r--r--cros_alsa/cros_alsa_derive/src/control.rs40
-rw-r--r--cros_alsa/cros_alsa_derive/src/lib.rs26
-rw-r--r--cros_alsa/src/card.rs117
-rw-r--r--cros_alsa/src/control.rs297
-rw-r--r--cros_alsa/src/control_primitive.rs406
-rw-r--r--cros_alsa/src/control_tlv.rs313
-rw-r--r--cros_alsa/src/elem.rs204
-rw-r--r--cros_alsa/src/lib.rs61
-rw-r--r--dbus-config/org.chromium.cras.conf13
-rw-r--r--defs/c.mk117
-rw-r--r--defs/definitions.mk7
-rw-r--r--defs/make.mk70
-rw-r--r--defs/utilities.mk18
-rw-r--r--init/cras-directories.conf1
-rw-r--r--init/cras.conf42
-rw-r--r--init/cras.service14
-rw-r--r--init/cras.sh64
-rwxr-xr-xscripts/asoc_dapm_graph95
-rwxr-xr-xscripts/audio_diagnostics129
-rw-r--r--scripts/audio_thread_log_viewer/README.md45
-rw-r--r--scripts/audio_thread_log_viewer/example.html783
-rw-r--r--scripts/audio_thread_log_viewer/log.test6151
-rwxr-xr-xscripts/audio_thread_log_viewer/viewer_c3.py604
-rwxr-xr-xscripts/audio_tuning/conf2ini2.py166
-rw-r--r--scripts/audio_tuning/frontend/LICENSE27
-rw-r--r--scripts/audio_tuning/frontend/app.yaml30
-rw-r--r--scripts/audio_tuning/frontend/audio.css88
-rw-r--r--scripts/audio_tuning/frontend/audio.html54
-rw-r--r--scripts/audio_tuning/frontend/audio.js1994
-rw-r--r--scripts/audio_tuning/frontend/google_drive_picker.js83
-rw-r--r--scripts/audio_tuning/frontend/setup_credential.js11
-rwxr-xr-xscripts/ini_editor.py628
-rwxr-xr-xscripts/ini_editor_unittest.py145
-rw-r--r--scripts/mic_testing/frontend/LICENSE27
-rw-r--r--scripts/mic_testing/frontend/analysis.js485
-rw-r--r--scripts/mic_testing/frontend/app.yaml30
-rw-r--r--scripts/mic_testing/frontend/audio.css107
-rw-r--r--scripts/mic_testing/frontend/audio.html184
-rw-r--r--scripts/mic_testing/frontend/audio.js363
-rw-r--r--scripts/mic_testing/frontend/recorder.js366
-rw-r--r--scripts/mic_testing/frontend/source.js227
-rw-r--r--scripts/volume_tuning/LICENSE27
-rw-r--r--scripts/volume_tuning/app.yaml30
-rw-r--r--scripts/volume_tuning/volume.css30
-rw-r--r--scripts/volume_tuning/volume.html24
-rw-r--r--scripts/volume_tuning/volume.js315
-rw-r--r--seccomp/cras-seccomp-amd64.policy95
-rw-r--r--seccomp/cras-seccomp-arm.policy104
-rw-r--r--seccomp/cras-seccomp-arm64.policy90
-rw-r--r--sof_sys/.gitignore2
-rw-r--r--sof_sys/.rustfmt.toml2
-rw-r--r--sof_sys/Cargo.toml4
-rw-r--r--sof_sys/generator/.gitignore1
-rw-r--r--sof_sys/generator/Cargo.toml6
-rw-r--r--sof_sys/generator/README.md1
-rw-r--r--sof_sys/generator/src/main.rs42
-rw-r--r--sof_sys/generator/wrapper.h5
-rw-r--r--sof_sys/src/bindings.rs154
-rw-r--r--sof_sys/src/lib.rs12
-rw-r--r--sound_card_init/.gitignore6
-rw-r--r--sound_card_init/99-sound_card_init.rules13
-rw-r--r--sound_card_init/Cargo.lock286
-rw-r--r--sound_card_init/Cargo.toml33
-rw-r--r--sound_card_init/amp/Cargo.lock254
-rw-r--r--sound_card_init/amp/Cargo.toml16
-rw-r--r--sound_card_init/amp/src/lib.rs58
-rw-r--r--sound_card_init/amp/src/max98373d/dsm_param.rs211
-rw-r--r--sound_card_init/amp/src/max98373d/mod.rs274
-rw-r--r--sound_card_init/amp/src/max98373d/settings.rs41
-rw-r--r--sound_card_init/amp/src/max98390d/mod.rs213
-rw-r--r--sound_card_init/amp/src/max98390d/settings.rs51
-rw-r--r--sound_card_init/dsm/Cargo.lock229
-rw-r--r--sound_card_init/dsm/Cargo.toml15
-rw-r--r--sound_card_init/dsm/src/datastore.rs72
-rw-r--r--sound_card_init/dsm/src/error.rs128
-rw-r--r--sound_card_init/dsm/src/lib.rs335
-rw-r--r--sound_card_init/dsm/src/utils.rs82
-rw-r--r--sound_card_init/dsm/src/vpd.rs41
-rw-r--r--sound_card_init/dsm/src/zero_player.rs209
-rw-r--r--sound_card_init/seccomp/sound_card_init-seccomp-amd64.policy82
-rw-r--r--sound_card_init/sound_card_init.conf80
-rw-r--r--sound_card_init/src/main.rs131
-rw-r--r--ubsan_blocklist.txt5
-rw-r--r--ucm-config/for_all_boards/C505 HD Webcam/C505 HD Webcam.conf6
-rw-r--r--ucm-config/for_all_boards/C505 HD Webcam/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/Chat 150 C/Chat 150 C.conf6
-rw-r--r--ucm-config/for_all_boards/Chat 150 C/HiFi.conf19
-rw-r--r--ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/DELL PROFESSIONAL SOUND BAR AE5.conf6
-rw-r--r--ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/HiFi.conf27
-rw-r--r--ucm-config/for_all_boards/Dell AC511 USB SoundBar/Dell AC511 USB SoundBar.conf6
-rw-r--r--ucm-config/for_all_boards/Dell AC511 USB SoundBar/HiFi.conf30
-rw-r--r--ucm-config/for_all_boards/Dell-WD15-Dock/Dell-WD15-Dock.conf5
-rw-r--r--ucm-config/for_all_boards/Dell-WD15-Dock/HiFi.conf40
-rw-r--r--ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HUAWEI USB-C HEADSET.conf6
-rw-r--r--ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/Hangouts Meet speakermic/Hangouts Meet speakermic.conf6
-rw-r--r--ucm-config/for_all_boards/Hangouts Meet speakermic/HiFi.conf8
-rw-r--r--ucm-config/for_all_boards/ICUSBAUDIO7D/HiFi.conf132
-rw-r--r--ucm-config/for_all_boards/ICUSBAUDIO7D/ICUSBAUDIO7D.conf6
-rw-r--r--ucm-config/for_all_boards/Jabra SPEAK 810/HiFi.conf19
-rw-r--r--ucm-config/for_all_boards/Jabra SPEAK 810/Jabra SPEAK 810.conf6
-rw-r--r--ucm-config/for_all_boards/Logitech BRIO/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/Logitech BRIO/Logitech BRIO.conf6
-rw-r--r--ucm-config/for_all_boards/Logitech Webcam C930e/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/Logitech Webcam C930e/Logitech Webcam C930e.conf6
-rw-r--r--ucm-config/for_all_boards/Loopback/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/Loopback/Loopback.conf6
-rw-r--r--ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/Mi Dual Driver Earphones Type-C.conf6
-rw-r--r--ucm-config/for_all_boards/PCP-USB/HiFi.conf20
-rw-r--r--ucm-config/for_all_boards/PCP-USB/PCP-USB.conf6
-rw-r--r--ucm-config/for_all_boards/Pixel USB-C earbuds/HiFi.conf24
-rw-r--r--ucm-config/for_all_boards/Pixel USB-C earbuds/Pixel USB-C earbuds.conf6
-rw-r--r--ucm-config/for_all_boards/Plantronics DA70/HiFi.conf28
-rw-r--r--ucm-config/for_all_boards/Plantronics DA70/Plantronics DA70.conf6
-rw-r--r--ucm-config/for_all_boards/Scarlett 2i2 USB/HiFi.conf27
-rw-r--r--ucm-config/for_all_boards/Scarlett 2i2 USB/Scarlett 2i2 USB.conf5
-rw-r--r--ucm-config/for_all_boards/Scarlett 2i4 USB/HiFi.conf27
-rw-r--r--ucm-config/for_all_boards/Scarlett 2i4 USB/Scarlett 2i4 USB.conf5
-rw-r--r--ucm-config/for_all_boards/USB 2.0 Camera/HiFi.conf25
-rw-r--r--ucm-config/for_all_boards/USB 2.0 Camera/USB 2.0 Camera6
l---------ucm-config/for_all_boards/WD15 Dock1
l---------ucm-config/for_all_boards/WD19 Dock1
-rw-r--r--unblocked_terms.txt10
567 files changed, 0 insertions, 154367 deletions
diff --git a/Android.bp b/Android.bp
deleted file mode 100644
index 4cb9810f..00000000
--- a/Android.bp
+++ /dev/null
@@ -1,52 +0,0 @@
-//
-// Copyright (C) 2021 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package {
- default_applicable_licenses: ["external_adhd_license"],
-}
-
-// Added automatically by a large-scale-change that took the approach of
-// 'apply every license found to every target'. While this makes sure we respect
-// every license restriction, it may not be entirely correct.
-//
-// e.g. GPL in an MIT project might only apply to the contrib/ directory.
-//
-// Please consider splitting the single license below into multiple licenses,
-// taking care not to lose any license_kind information, and overriding the
-// default license using the 'licenses: [...]' property on targets as needed.
-//
-// For unused files, consider creating a 'fileGroup' with "//visibility:private"
-// to attach the license to, and including a comment whether the files may be
-// used in the current project.
-//
-// large-scale-change included anything that looked like it might be a license
-// text as a license_text. e.g. LICENSE, NOTICE, COPYING etc.
-//
-// Please consider removing redundant or irrelevant files from 'license_text:'.
-// See: http://go/android-license-faq
-license {
- name: "external_adhd_license",
- visibility: [":__subpackages__"],
- license_kinds: [
- "SPDX-license-identifier-BSD",
- "SPDX-license-identifier-LGPL",
- ],
- license_text: [
- "LICENSE.SUPERFASTHASH",
- "LICENSE.UTLIST",
- "LICENSE.WEBKIT",
- "NOTICE",
- ],
-}
diff --git a/LICENSE.SUPERFASTHASH b/LICENSE.SUPERFASTHASH
deleted file mode 100644
index 3c40a3ec..00000000
--- a/LICENSE.SUPERFASTHASH
+++ /dev/null
@@ -1,27 +0,0 @@
-Paul Hsieh OLD BSD license
-
-Copyright (c) 2010, Paul Hsieh
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-* Redistributions in binary form must reproduce the above copyright notice, this
- list of conditions and the following disclaimer in the documentation and/or
- other materials provided with the distribution.
-* Neither my name, Paul Hsieh, nor the names of any other contributors to the
- code use may not be used to endorse or promote products derived from this
- software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/LICENSE.UTLIST b/LICENSE.UTLIST
deleted file mode 100644
index fbc90b18..00000000
--- a/LICENSE.UTLIST
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
-Copyright (c) 2007-2011, Troy D. Hanson http://uthash.sourceforge.net
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
diff --git a/LICENSE.WEBKIT b/LICENSE.WEBKIT
deleted file mode 100644
index 2f69d9f0..00000000
--- a/LICENSE.WEBKIT
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
diff --git a/METADATA b/METADATA
deleted file mode 100644
index 6d8601bb..00000000
--- a/METADATA
+++ /dev/null
@@ -1,3 +0,0 @@
-third_party {
- license_type: RESTRICTED
-}
diff --git a/MODULE_LICENSE_BSD b/MODULE_LICENSE_BSD
deleted file mode 100644
index e69de29b..00000000
--- a/MODULE_LICENSE_BSD
+++ /dev/null
diff --git a/Makefile b/Makefile
deleted file mode 100644
index 9693cabb..00000000
--- a/Makefile
+++ /dev/null
@@ -1,94 +0,0 @@
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-export ADHD_DIR = $(shell pwd)
-include $(ADHD_DIR)/defs/definitions.mk
-
-all: cras
-
-cras:
- @$(call remake,Building,$@,cras.mk,$@)
-
-cras_install:
- @$(call remake,Building,cras,cras.mk,$@)
-
-cras-scripts:
- $(ECHO) "Installing cras scripts"
- $(INSTALL) --mode 755 -d $(DESTDIR)/usr/bin/
- $(INSTALL) --mode 755 -D $(ADHD_DIR)/scripts/audio_diagnostics \
- $(DESTDIR)/usr/bin/
- $(INSTALL) --mode 755 -D $(ADHD_DIR)/scripts/asoc_dapm_graph \
- $(DESTDIR)/usr/bin/
-
-cras_init_upstart: $(ADHD_DIR)/init/cras.conf
- $(ECHO) "Installing upstart file"
- $(INSTALL) --mode 644 -D $< $(DESTDIR)/etc/init/cras.conf
-
-cras_init_scripts: $(ADHD_DIR)/init/cras.sh
- $(INSTALL) --mode 644 -D $< $(DESTDIR)/usr/share/cros/init/cras.sh
-
-SYSTEMD_UNIT_DIR := /usr/lib/systemd/system/
-SYSTEMD_TMPFILESD_DIR := /usr/lib/tmpfiles.d/
-
-cras_init_systemd: $(ADHD_DIR)/init/cras.service \
- $(ADHD_DIR)/init/cras-directories.conf
- $(ECHO) "Installing systemd files"
- $(INSTALL) --mode 644 -D $(ADHD_DIR)/init/cras.service \
- $(DESTDIR)/$(SYSTEMD_UNIT_DIR)/cras.service
- $(INSTALL) --mode 755 -d $(DESTDIR)/$(SYSTEMD_UNIT_DIR)/system-services.target.wants
- $(LINK) -s ../cras.service \
- $(DESTDIR)/$(SYSTEMD_UNIT_DIR)/system-services.target.wants/cras.service
- $(INSTALL) --mode 644 -D $(ADHD_DIR)/init/cras-directories.conf \
- $(DESTDIR)/$(SYSTEMD_TMPFILESD_DIR)/cras-directories.conf
-
-ifeq ($(strip $(SYSTEMD)), yes)
-
-cras_init: cras_init_systemd cras_init_scripts
-
-else
-
-cras_init: cras_init_upstart cras_init_scripts
-
-endif
-
-$(DESTDIR)/etc/cras/device_blocklist: $(ADHD_DIR)/cras-config/device_blocklist
- $(ECHO) "Installing '$<' to '$@'"
- $(INSTALL) --mode 644 -D $< $@
-
-# Note: $(BOARD) usage is deprecated. Configs should be added in board overlays
-# or via cros_config data for newer unibuild systems.
-
-optional_alsa_conf := $(wildcard $(ADHD_DIR)/alsa-module-config/alsa-$(BOARD).conf)
-
-ifneq ($(strip $(optional_alsa_conf)),)
-
-$(DESTDIR)/etc/modprobe.d/alsa-$(BOARD).conf: $(optional_alsa_conf)
- $(ECHO) "Installing '$<' to '$@'"
- $(INSTALL) --mode 644 -D $< $@
-
-install: $(DESTDIR)/etc/modprobe.d/alsa-$(BOARD).conf
-
-endif
-
-optional_alsa_patch := $(wildcard $(ADHD_DIR)/alsa-module-config/$(BOARD)_alsa.fw)
-
-ifneq ($(strip $(optional_alsa_patch)),)
-
-$(DESTDIR)/lib/firmware/$(BOARD)_alsa.fw: $(optional_alsa_patch)
- $(ECHO) "Installing '$<' to '$@'"
- $(INSTALL) --mode 644 -D $< $@
-
-install: $(DESTDIR)/lib/firmware/$(BOARD)_alsa.fw
-
-endif
-
-install: $(DESTDIR)/etc/cras/device_blocklist \
- cras-scripts \
- cras_install \
- cras_init
-
-clean:
- @rm -rf $(ADHD_BUILD_DIR)
-
-.PHONY: clean cras cras_install cras-script
diff --git a/NOTICE b/NOTICE
deleted file mode 100644
index a7f0a02b..00000000
--- a/NOTICE
+++ /dev/null
@@ -1,76 +0,0 @@
-Paul Hsieh OLD BSD license
-
-Copyright (c) 2010, Paul Hsieh
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-* Redistributions in binary form must reproduce the above copyright notice, this
- list of conditions and the following disclaimer in the documentation and/or
- other materials provided with the distribution.
-* Neither my name, Paul Hsieh, nor the names of any other contributors to the
- code use may not be used to endorse or promote products derived from this
- software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-/*
-Copyright (c) 2007-2011, Troy D. Hanson http://uthash.sourceforge.net
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
diff --git a/OWNERS.fuzz b/OWNERS.fuzz
deleted file mode 100644
index 8c7567ff..00000000
--- a/OWNERS.fuzz
+++ /dev/null
@@ -1,5 +0,0 @@
-cychiang@chromium.org
-dgreid@chromium.org
-enshuo@chromium.org
-paulhsia@chromium.org
-chromeos-audio-bugs@google.com
diff --git a/PRESUBMIT.cfg b/PRESUBMIT.cfg
deleted file mode 100644
index e85e5dc2..00000000
--- a/PRESUBMIT.cfg
+++ /dev/null
@@ -1,19 +0,0 @@
-[Hook Overrides]
-tab_check: false
-clang_format_check: true
-cargo_clippy_check: true
-
-# On by default, but required for options below.
-cros_license_check: true
-
-[Hook Overrides Options]
-# Ignore HiFi file
-cros_license_check: --exclude_regex=HiFi\.conf$
-clang_format_check:
- cras/
-cargo_clippy_check:
- --project=audio_streams
- --project=cras/client/cras-sys
- --project=cras/client/cras_tests
- --project=cras/client/libcras
- --project=cras/src/server/rust
diff --git a/audio_streams/.gitignore b/audio_streams/.gitignore
deleted file mode 100644
index fa8d85ac..00000000
--- a/audio_streams/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Cargo.lock
-target
diff --git a/audio_streams/Android.bp b/audio_streams/Android.bp
deleted file mode 100644
index 2909b544..00000000
--- a/audio_streams/Android.bp
+++ /dev/null
@@ -1,61 +0,0 @@
-// This file is generated by cargo2android.py --run --device --test --global_defaults=crosvm_defaults --dependencies.
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "external_adhd_license"
- // to get the below license kinds:
- // SPDX-license-identifier-BSD
- default_applicable_licenses: ["external_adhd_license"],
-}
-
-rust_defaults {
- name: "audio_streams_defaults",
- defaults: ["crosvm_defaults"],
- crate_name: "audio_streams",
- srcs: ["src/audio_streams.rs"],
- test_suites: ["general-tests"],
- auto_gen_config: true,
- edition: "2018",
- rustlibs: [
- "libsync_rust",
- "libsys_util",
- ],
-}
-
-rust_test_host {
- name: "audio_streams_host_test_src_audio_streams",
- defaults: ["audio_streams_defaults"],
-}
-
-rust_test {
- name: "audio_streams_device_test_src_audio_streams",
- defaults: ["audio_streams_defaults"],
-}
-
-rust_library {
- name: "libaudio_streams",
- defaults: ["crosvm_defaults"],
- host_supported: true,
- crate_name: "audio_streams",
- srcs: ["src/audio_streams.rs"],
- edition: "2018",
- rustlibs: [
- "libsync_rust",
- "libsys_util",
- ],
-}
-
-// dependent_library ["feature_list"]
-// ../../crosvm/assertions/src/lib.rs
-// ../../crosvm/data_model/src/lib.rs
-// ../../crosvm/sync/src/lib.rs
-// ../../crosvm/sys_util/poll_token_derive/poll_token_derive.rs
-// ../../crosvm/sys_util/src/lib.rs
-// ../../crosvm/syscall_defines/src/lib.rs
-// ../../crosvm/tempfile/src/lib.rs
-// libc-0.2.76 "default,std"
-// proc-macro2-1.0.19 "default,proc-macro"
-// quote-1.0.7 "default,proc-macro"
-// syn-1.0.39 "clone-impls,default,derive,parsing,printing,proc-macro,quote"
-// unicode-xid-0.2.1 "default"
diff --git a/audio_streams/Cargo.toml b/audio_streams/Cargo.toml
deleted file mode 100644
index dd169c7f..00000000
--- a/audio_streams/Cargo.toml
+++ /dev/null
@@ -1,12 +0,0 @@
-[package]
-name = "audio_streams"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-
-[lib]
-path = "src/audio_streams.rs"
-
-[dependencies]
-sync = { path = "../../crosvm/sync" } # provided by ebuild
-sys_util = { path = "../../crosvm/sys_util" } # provided by ebuild
diff --git a/audio_streams/README.md b/audio_streams/README.md
deleted file mode 100644
index d3a02e8f..00000000
--- a/audio_streams/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-# Audio Server and Stream interfaces
-
-The `audio_streams` crate provides a basic interface for playing audio.
-This will be used to enable playback to various audio subsystems such as
-Alsa and cras. To start, an empty playback example `NoopStreamSource`
-is provided.
diff --git a/audio_streams/src/audio_streams.rs b/audio_streams/src/audio_streams.rs
deleted file mode 100644
index e5fc83cb..00000000
--- a/audio_streams/src/audio_streams.rs
+++ /dev/null
@@ -1,471 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! Provides an interface for playing and recording audio.
-//!
-//! When implementing an audio playback system, the `StreamSource` trait is implemented.
-//! Implementors of this trait allow creation of `PlaybackBufferStream` objects. The
-//! `PlaybackBufferStream` provides the actual audio buffers to be filled with audio samples. These
-//! buffers are obtained by calling `next_playback_buffer`.
-//!
-//! Users playing audio fill the provided buffers with audio. When a `PlaybackBuffer` is dropped,
-//! the samples written to it are committed to the `PlaybackBufferStream` it came from.
-//!
-//! ```
-//! use audio_streams::{BoxError, SampleFormat, StreamSource, NoopStreamSource};
-//! use std::io::Write;
-//!
-//! const buffer_size: usize = 120;
-//! const num_channels: usize = 2;
-//!
-//! # fn main() -> std::result::Result<(), BoxError> {
-//! let mut stream_source = NoopStreamSource::new();
-//! let sample_format = SampleFormat::S16LE;
-//! let frame_size = num_channels * sample_format.sample_bytes();
-//!
-//! let (_, mut stream) = stream_source
-//! .new_playback_stream(num_channels, sample_format, 48000, buffer_size)?;
-//! // Play 10 buffers of DC.
-//! let mut buf = Vec::new();
-//! buf.resize(buffer_size * frame_size, 0xa5u8);
-//! for _ in 0..10 {
-//! let mut stream_buffer = stream.next_playback_buffer()?;
-//! assert_eq!(stream_buffer.write(&buf)?, buffer_size * frame_size);
-//! }
-//! # Ok (())
-//! # }
-//! ```
-
-use std::cmp::min;
-use std::error;
-use std::fmt::{self, Display};
-use std::io::{self, Write};
-use std::os::unix::io::RawFd;
-use std::result::Result;
-use std::str::FromStr;
-use std::time::{Duration, Instant};
-
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum SampleFormat {
- U8,
- S16LE,
- S24LE,
- S32LE,
-}
-
-impl SampleFormat {
- pub fn sample_bytes(self) -> usize {
- use SampleFormat::*;
- match self {
- U8 => 1,
- S16LE => 2,
- S24LE => 4, // Not a typo, S24_LE samples are stored in 4 byte chunks.
- S32LE => 4,
- }
- }
-}
-
-impl Display for SampleFormat {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use SampleFormat::*;
- match self {
- U8 => write!(f, "Unsigned 8 bit"),
- S16LE => write!(f, "Signed 16 bit Little Endian"),
- S24LE => write!(f, "Signed 24 bit Little Endian"),
- S32LE => write!(f, "Signed 32 bit Little Endian"),
- }
- }
-}
-
-/// Valid directions of an audio stream.
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum StreamDirection {
- Playback,
- Capture,
-}
-
-/// Valid effects for an audio stream.
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum StreamEffect {
- NoEffect,
- EchoCancellation,
-}
-
-pub mod capture;
-pub mod shm_streams;
-
-impl Default for StreamEffect {
- fn default() -> Self {
- StreamEffect::NoEffect
- }
-}
-
-/// Errors that can pass across threads.
-pub type BoxError = Box<dyn error::Error + Send + Sync>;
-
-/// Errors that are possible from a `StreamEffect`.
-#[derive(Debug)]
-pub enum StreamEffectError {
- InvalidEffect,
-}
-
-impl error::Error for StreamEffectError {}
-
-impl Display for StreamEffectError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- StreamEffectError::InvalidEffect => write!(f, "Must be in [EchoCancellation, aec]"),
- }
- }
-}
-
-impl FromStr for StreamEffect {
- type Err = StreamEffectError;
- fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
- match s {
- "EchoCancellation" | "aec" => Ok(StreamEffect::EchoCancellation),
- _ => Err(StreamEffectError::InvalidEffect),
- }
- }
-}
-
-/// `StreamSource` creates streams for playback or capture of audio.
-pub trait StreamSource: Send {
- /// Returns a stream control and buffer generator object. These are separate as the buffer
- /// generator might want to be passed to the audio stream.
- #[allow(clippy::type_complexity)]
- fn new_playback_stream(
- &mut self,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> Result<(Box<dyn StreamControl>, Box<dyn PlaybackBufferStream>), BoxError>;
-
- /// Returns a stream control and buffer generator object. These are separate as the buffer
- /// generator might want to be passed to the audio stream.
- /// Default implementation returns `NoopStreamControl` and `NoopCaptureStream`.
- #[allow(clippy::type_complexity)]
- fn new_capture_stream(
- &mut self,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> Result<
- (
- Box<dyn StreamControl>,
- Box<dyn capture::CaptureBufferStream>,
- ),
- BoxError,
- > {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(capture::NoopCaptureStream::new(
- num_channels,
- format,
- frame_rate,
- buffer_size,
- )),
- ))
- }
-
- /// Returns any open file descriptors needed by the implementor. The FD list helps users of the
- /// StreamSource enter Linux jails making sure not to close needed FDs.
- fn keep_fds(&self) -> Option<Vec<RawFd>> {
- None
- }
-}
-
-/// `PlaybackBufferStream` provides `PlaybackBuffer`s to fill with audio samples for playback.
-pub trait PlaybackBufferStream: Send {
- fn next_playback_buffer(&mut self) -> Result<PlaybackBuffer, BoxError>;
-}
-
-/// `StreamControl` provides a way to set the volume and mute states of a stream. `StreamControl`
-/// is separate from the stream so it can be owned by a different thread if needed.
-pub trait StreamControl: Send + Sync {
- fn set_volume(&mut self, _scaler: f64) {}
- fn set_mute(&mut self, _mute: bool) {}
-}
-
-/// `BufferDrop` is used as a callback mechanism for `PlaybackBuffer` objects. It is meant to be
-/// implemented by the audio stream, allowing arbitrary code to be run after a buffer is filled or
-/// read by the user.
-pub trait BufferDrop {
- /// Called when an audio buffer is dropped. `nframes` indicates the number of audio frames that
- /// were read or written to the device.
- fn trigger(&mut self, nframes: usize);
-}
-
-/// Errors that are possible from a `PlaybackBuffer`.
-#[derive(Debug)]
-pub enum PlaybackBufferError {
- InvalidLength,
-}
-
-impl error::Error for PlaybackBufferError {}
-
-impl Display for PlaybackBufferError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- PlaybackBufferError::InvalidLength => write!(f, "Invalid buffer length"),
- }
- }
-}
-
-/// `AudioBuffer` is one buffer that holds buffer_size audio frames and its drop function.
-/// It is the inner data of `PlaybackBuffer` and `CaptureBuffer`.
-struct AudioBuffer<'a> {
- buffer: &'a mut [u8],
- offset: usize, // Read or Write offset in frames.
- frame_size: usize, // Size of a frame in bytes.
- drop: &'a mut dyn BufferDrop,
-}
-
-/// `PlaybackBuffer` is one buffer that holds buffer_size audio frames. It is used to temporarily
-/// allow access to an audio buffer and notifes the owning stream of write completion when dropped.
-pub struct PlaybackBuffer<'a> {
- buffer: AudioBuffer<'a>,
-}
-
-impl<'a> PlaybackBuffer<'a> {
- /// Creates a new `PlaybackBuffer` that holds a reference to the backing memory specified in
- /// `buffer`.
- pub fn new<F>(
- frame_size: usize,
- buffer: &'a mut [u8],
- drop: &'a mut F,
- ) -> Result<Self, PlaybackBufferError>
- where
- F: BufferDrop,
- {
- if buffer.len() % frame_size != 0 {
- return Err(PlaybackBufferError::InvalidLength);
- }
-
- Ok(PlaybackBuffer {
- buffer: AudioBuffer {
- buffer,
- offset: 0,
- frame_size,
- drop,
- },
- })
- }
-
- /// Returns the number of audio frames that fit in the buffer.
- pub fn frame_capacity(&self) -> usize {
- self.buffer.buffer.len() / self.buffer.frame_size
- }
-
- /// Writes up to `size` bytes directly to this buffer inside of the given callback function.
- pub fn copy_cb<F: FnOnce(&mut [u8])>(&mut self, size: usize, cb: F) {
- // only write complete frames.
- let len = min(
- size / self.buffer.frame_size * self.buffer.frame_size,
- self.buffer.buffer.len() - self.buffer.offset,
- );
- cb(&mut self.buffer.buffer[self.buffer.offset..(self.buffer.offset + len)]);
- self.buffer.offset += len;
- }
-}
-
-impl<'a> Write for PlaybackBuffer<'a> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- // only write complete frames.
- let len = buf.len() / self.buffer.frame_size * self.buffer.frame_size;
- let written = (&mut self.buffer.buffer[self.buffer.offset..]).write(&buf[..len])?;
- self.buffer.offset += written;
- Ok(written)
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-
-impl<'a> Drop for PlaybackBuffer<'a> {
- fn drop(&mut self) {
- self.buffer
- .drop
- .trigger(self.buffer.offset / self.buffer.frame_size);
- }
-}
-
-/// Stream that accepts playback samples but drops them.
-pub struct NoopStream {
- buffer: Vec<u8>,
- frame_size: usize,
- interval: Duration,
- next_frame: Duration,
- start_time: Option<Instant>,
- buffer_drop: NoopBufferDrop,
-}
-
-/// NoopStream data that is needed from the buffer complete callback.
-struct NoopBufferDrop {
- which_buffer: bool,
-}
-
-impl BufferDrop for NoopBufferDrop {
- fn trigger(&mut self, _nwritten: usize) {
- // When a buffer completes, switch to the other one.
- self.which_buffer ^= true;
- }
-}
-
-impl NoopStream {
- pub fn new(
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> Self {
- let frame_size = format.sample_bytes() * num_channels;
- let interval = Duration::from_millis(buffer_size as u64 * 1000 / frame_rate as u64);
- NoopStream {
- buffer: vec![0; buffer_size * frame_size],
- frame_size,
- interval,
- next_frame: interval,
- start_time: None,
- buffer_drop: NoopBufferDrop {
- which_buffer: false,
- },
- }
- }
-}
-
-impl PlaybackBufferStream for NoopStream {
- fn next_playback_buffer(&mut self) -> Result<PlaybackBuffer, BoxError> {
- if let Some(start_time) = self.start_time {
- let elapsed = start_time.elapsed();
- if elapsed < self.next_frame {
- std::thread::sleep(self.next_frame - elapsed);
- }
- self.next_frame += self.interval;
- } else {
- self.start_time = Some(Instant::now());
- self.next_frame = self.interval;
- }
- Ok(PlaybackBuffer::new(
- self.frame_size,
- &mut self.buffer,
- &mut self.buffer_drop,
- )?)
- }
-}
-
-/// No-op control for `NoopStream`s.
-#[derive(Default)]
-pub struct NoopStreamControl;
-
-impl NoopStreamControl {
- pub fn new() -> Self {
- NoopStreamControl {}
- }
-}
-
-impl StreamControl for NoopStreamControl {}
-
-/// Source of `NoopStream` and `NoopStreamControl` objects.
-#[derive(Default)]
-pub struct NoopStreamSource;
-
-impl NoopStreamSource {
- pub fn new() -> Self {
- NoopStreamSource {}
- }
-}
-
-impl StreamSource for NoopStreamSource {
- #[allow(clippy::type_complexity)]
- fn new_playback_stream(
- &mut self,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> Result<(Box<dyn StreamControl>, Box<dyn PlaybackBufferStream>), BoxError> {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(NoopStream::new(
- num_channels,
- format,
- frame_rate,
- buffer_size,
- )),
- ))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn invalid_buffer_length() {
- // Playback buffers can't be created with a size that isn't divisible by the frame size.
- let mut pb_buf = [0xa5u8; 480 * 2 * 2 + 1];
- let mut buffer_drop = NoopBufferDrop {
- which_buffer: false,
- };
- assert!(PlaybackBuffer::new(2, &mut pb_buf, &mut buffer_drop).is_err());
- }
-
- #[test]
- fn trigger() {
- struct TestDrop {
- frame_count: usize,
- };
- impl BufferDrop for TestDrop {
- fn trigger(&mut self, nwritten: usize) {
- self.frame_count += nwritten;
- }
- }
- let mut test_drop = TestDrop { frame_count: 0 };
- {
- const FRAME_SIZE: usize = 4;
- let mut buf = [0u8; 480 * FRAME_SIZE];
- let mut pb_buf = PlaybackBuffer::new(FRAME_SIZE, &mut buf, &mut test_drop).unwrap();
- pb_buf.write_all(&[0xa5u8; 480 * FRAME_SIZE]).unwrap();
- }
- assert_eq!(test_drop.frame_count, 480);
- }
-
- #[test]
- fn sixteen_bit_stereo() {
- let mut server = NoopStreamSource::new();
- let (_, mut stream) = server
- .new_playback_stream(2, SampleFormat::S16LE, 48000, 480)
- .unwrap();
- let mut stream_buffer = stream.next_playback_buffer().unwrap();
- assert_eq!(stream_buffer.frame_capacity(), 480);
- let pb_buf = [0xa5u8; 480 * 2 * 2];
- assert_eq!(stream_buffer.write(&pb_buf).unwrap(), 480 * 2 * 2);
- }
-
- #[test]
- fn consumption_rate() {
- let mut server = NoopStreamSource::new();
- let (_, mut stream) = server
- .new_playback_stream(2, SampleFormat::S16LE, 48000, 480)
- .unwrap();
- let start = Instant::now();
- {
- let mut stream_buffer = stream.next_playback_buffer().unwrap();
- let pb_buf = [0xa5u8; 480 * 2 * 2];
- assert_eq!(stream_buffer.write(&pb_buf).unwrap(), 480 * 2 * 2);
- }
- // The second call should block until the first buffer is consumed.
- let _stream_buffer = stream.next_playback_buffer().unwrap();
- let elapsed = start.elapsed();
- assert!(
- elapsed > Duration::from_millis(10),
- "next_playback_buffer didn't block long enough {}",
- elapsed.subsec_millis()
- );
- }
-}
diff --git a/audio_streams/src/capture.rs b/audio_streams/src/capture.rs
deleted file mode 100644
index 6a32cf1a..00000000
--- a/audio_streams/src/capture.rs
+++ /dev/null
@@ -1,250 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! ```
-//! use audio_streams::{BoxError, SampleFormat, StreamSource, NoopStreamSource};
-//! use std::io::Read;
-//!
-//! const buffer_size: usize = 120;
-//! const num_channels: usize = 2;
-//!
-//! # fn main() -> std::result::Result<(),BoxError> {
-//! let mut stream_source = NoopStreamSource::new();
-//! let sample_format = SampleFormat::S16LE;
-//! let frame_size = num_channels * sample_format.sample_bytes();
-//!
-//! let (_, mut stream) = stream_source
-//! .new_capture_stream(num_channels, sample_format, 48000, buffer_size)?;
-//! // Capture 10 buffers of zeros.
-//! let mut buf = Vec::new();
-//! buf.resize(buffer_size * frame_size, 0xa5u8);
-//! for _ in 0..10 {
-//! let mut stream_buffer = stream.next_capture_buffer()?;
-//! assert_eq!(stream_buffer.read(&mut buf)?, buffer_size * frame_size);
-//! }
-//! # Ok (())
-//! # }
-//! ```
-
-use std::{
- cmp::min,
- error,
- fmt::{self, Display},
- io::{self, Read, Write},
- time::{Duration, Instant},
-};
-
-use super::{AudioBuffer, BoxError, BufferDrop, NoopBufferDrop, SampleFormat};
-
-/// `CaptureBufferStream` provides `CaptureBuffer`s to read with audio samples from capture.
-pub trait CaptureBufferStream: Send {
- fn next_capture_buffer(&mut self) -> Result<CaptureBuffer, BoxError>;
-}
-
-/// `CaptureBuffer` contains a block of audio samples got from capture stream. It provides
-/// temporary view to those samples and will notifies capture stream when dropped.
-/// Note that it'll always send `buffer.len() / frame_size` to drop function when it got destroyed
-/// since `CaptureBufferStream` assumes that users get all the samples from the buffer.
-pub struct CaptureBuffer<'a> {
- buffer: AudioBuffer<'a>,
-}
-
-/// Errors that are possible from a `CaptureBuffer`.
-#[derive(Debug)]
-pub enum CaptureBufferError {
- InvalidLength,
-}
-
-impl error::Error for CaptureBufferError {}
-
-impl Display for CaptureBufferError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- CaptureBufferError::InvalidLength => write!(f, "Invalid buffer length"),
- }
- }
-}
-
-impl<'a> CaptureBuffer<'a> {
- /// Creates a new `CaptureBuffer` that holds a reference to the backing memory specified in
- /// `buffer`.
- pub fn new<F>(
- frame_size: usize,
- buffer: &'a mut [u8],
- drop: &'a mut F,
- ) -> Result<Self, CaptureBufferError>
- where
- F: BufferDrop,
- {
- if buffer.len() % frame_size != 0 {
- return Err(CaptureBufferError::InvalidLength);
- }
-
- Ok(CaptureBuffer {
- buffer: AudioBuffer {
- buffer,
- frame_size,
- offset: 0,
- drop,
- },
- })
- }
-
- /// Returns the number of audio frames that fit in the buffer.
- pub fn frame_capacity(&self) -> usize {
- self.buffer.buffer.len() / self.buffer.frame_size
- }
-
- /// Reads up to `size` bytes directly from this buffer inside of the given callback function.
- pub fn copy_cb<F: FnOnce(&[u8])>(&mut self, size: usize, cb: F) {
- let len = min(
- size / self.buffer.frame_size * self.buffer.frame_size,
- self.buffer.buffer.len() - self.buffer.offset,
- );
- cb(&self.buffer.buffer[self.buffer.offset..(self.buffer.offset + len)]);
- self.buffer.offset += len;
- }
-}
-
-impl<'a> Read for CaptureBuffer<'a> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- let len = buf.len() / self.buffer.frame_size * self.buffer.frame_size;
- let written = (&mut buf[..len]).write(&self.buffer.buffer[self.buffer.offset..])?;
- self.buffer.offset += written;
- Ok(written)
- }
-}
-
-/// Always sends `frame_capacity` when it drops.
-impl<'a> Drop for CaptureBuffer<'a> {
- fn drop(&mut self) {
- self.buffer.drop.trigger(self.frame_capacity());
- }
-}
-
-/// Stream that provides null capture samples.
-pub struct NoopCaptureStream {
- buffer: Vec<u8>,
- frame_size: usize,
- interval: Duration,
- next_frame: Duration,
- start_time: Option<Instant>,
- buffer_drop: NoopBufferDrop,
-}
-
-impl NoopCaptureStream {
- pub fn new(
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> Self {
- let frame_size = format.sample_bytes() * num_channels;
- let interval = Duration::from_millis(buffer_size as u64 * 1000 / frame_rate as u64);
- NoopCaptureStream {
- buffer: vec![0; buffer_size * frame_size],
- frame_size,
- interval,
- next_frame: interval,
- start_time: None,
- buffer_drop: NoopBufferDrop {
- which_buffer: false,
- },
- }
- }
-}
-
-impl CaptureBufferStream for NoopCaptureStream {
- fn next_capture_buffer(&mut self) -> Result<CaptureBuffer, BoxError> {
- if let Some(start_time) = self.start_time {
- let elapsed = start_time.elapsed();
- if elapsed < self.next_frame {
- std::thread::sleep(self.next_frame - elapsed);
- }
- self.next_frame += self.interval;
- } else {
- self.start_time = Some(Instant::now());
- self.next_frame = self.interval;
- }
- Ok(CaptureBuffer::new(
- self.frame_size,
- &mut self.buffer,
- &mut self.buffer_drop,
- )?)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::super::*;
- use super::*;
-
- #[test]
- fn invalid_buffer_length() {
- // Capture buffers can't be created with a size that isn't divisible by the frame size.
- let mut cp_buf = [0xa5u8; 480 * 2 * 2 + 1];
- let mut buffer_drop = NoopBufferDrop {
- which_buffer: false,
- };
- assert!(CaptureBuffer::new(2, &mut cp_buf, &mut buffer_drop).is_err());
- }
-
- #[test]
- fn trigger() {
- struct TestDrop {
- frame_count: usize,
- };
- impl BufferDrop for TestDrop {
- fn trigger(&mut self, nwritten: usize) {
- self.frame_count += nwritten;
- }
- }
- let mut test_drop = TestDrop { frame_count: 0 };
- {
- const FRAME_SIZE: usize = 4;
- let mut buf = [0u8; 480 * FRAME_SIZE];
- let mut cp_buf = CaptureBuffer::new(FRAME_SIZE, &mut buf, &mut test_drop).unwrap();
- let mut local_buf = [0u8; 240 * FRAME_SIZE];
- assert_eq!(cp_buf.read(&mut local_buf).unwrap(), 240 * FRAME_SIZE);
- }
- // This should be 480 no matter how many samples are read.
- assert_eq!(test_drop.frame_count, 480);
- }
-
- #[test]
- fn sixteen_bit_stereo() {
- let mut server = NoopStreamSource::new();
- let (_, mut stream) = server
- .new_capture_stream(2, SampleFormat::S16LE, 48000, 480)
- .unwrap();
- let mut stream_buffer = stream.next_capture_buffer().unwrap();
- assert_eq!(stream_buffer.frame_capacity(), 480);
- let mut pb_buf = [0xa5u8; 480 * 2 * 2];
- assert_eq!(stream_buffer.read(&mut pb_buf).unwrap(), 480 * 2 * 2);
- }
-
- #[test]
- fn consumption_rate() {
- let mut server = NoopStreamSource::new();
- let (_, mut stream) = server
- .new_capture_stream(2, SampleFormat::S16LE, 48000, 480)
- .unwrap();
- let start = Instant::now();
- {
- let mut stream_buffer = stream.next_capture_buffer().unwrap();
- let mut cp_buf = [0xa5u8; 480 * 2 * 2];
- assert_eq!(stream_buffer.read(&mut cp_buf).unwrap(), 480 * 2 * 2);
- for buf in cp_buf.iter() {
- assert_eq!(*buf, 0, "Read samples should all be zeros.");
- }
- }
- // The second call should block until the first buffer is consumed.
- let _stream_buffer = stream.next_capture_buffer().unwrap();
- let elapsed = start.elapsed();
- assert!(
- elapsed > Duration::from_millis(10),
- "next_capture_buffer didn't block long enough {}",
- elapsed.subsec_millis()
- );
- }
-}
diff --git a/audio_streams/src/shm_streams.rs b/audio_streams/src/shm_streams.rs
deleted file mode 100644
index b11626fd..00000000
--- a/audio_streams/src/shm_streams.rs
+++ /dev/null
@@ -1,568 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::error;
-use std::fmt;
-use std::os::unix::io::RawFd;
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-
-use sync::{Condvar, Mutex};
-use sys_util::SharedMemory;
-
-use crate::{BoxError, SampleFormat, StreamDirection, StreamEffect};
-
-type GenericResult<T> = std::result::Result<T, BoxError>;
-
-/// `BufferSet` is used as a callback mechanism for `ServerRequest` objects.
-/// It is meant to be implemented by the audio stream, allowing arbitrary code
-/// to be run after a buffer offset and length is set.
-pub trait BufferSet {
- /// Called when the client sets a buffer offset and length.
- ///
- /// `offset` is the offset within shared memory of the buffer and `frames`
- /// indicates the number of audio frames that can be read from or written to
- /// the buffer.
- fn callback(&mut self, offset: usize, frames: usize) -> GenericResult<()>;
-
- /// Called when the client ignores a request from the server.
- fn ignore(&mut self) -> GenericResult<()>;
-}
-
-#[derive(Debug)]
-pub enum Error {
- TooManyFrames(usize, usize),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Error::TooManyFrames(provided, requested) => write!(
- f,
- "Provided number of frames {} exceeds requested number of frames {}",
- provided, requested
- ),
- }
- }
-}
-
-/// `ServerRequest` represents an active request from the server for the client
-/// to provide a buffer in shared memory to playback from or capture to.
-pub struct ServerRequest<'a> {
- requested_frames: usize,
- buffer_set: &'a mut dyn BufferSet,
-}
-
-impl<'a> ServerRequest<'a> {
- /// Create a new ServerRequest object
- ///
- /// Create a ServerRequest object representing a request from the server
- /// for a buffer `requested_frames` in size.
- ///
- /// When the client responds to this request by calling
- /// [`set_buffer_offset_and_frames`](ServerRequest::set_buffer_offset_and_frames),
- /// BufferSet::callback will be called on `buffer_set`.
- ///
- /// # Arguments
- /// * `requested_frames` - The requested buffer size in frames.
- /// * `buffer_set` - The object implementing the callback for when a buffer is provided.
- pub fn new<D: BufferSet>(requested_frames: usize, buffer_set: &'a mut D) -> Self {
- Self {
- requested_frames,
- buffer_set,
- }
- }
-
- /// Get the number of frames of audio data requested by the server.
- ///
- /// The returned value should never be greater than the `buffer_size`
- /// given in [`new_stream`](ShmStreamSource::new_stream).
- pub fn requested_frames(&self) -> usize {
- self.requested_frames
- }
-
- /// Sets the buffer offset and length for the requested buffer.
- ///
- /// Sets the buffer offset and length of the buffer that fulfills this
- /// server request to `offset` and `length`, respectively. This means that
- /// `length` bytes of audio samples may be read from/written to that
- /// location in `client_shm` for a playback/capture stream, respectively.
- /// This function may only be called once for a `ServerRequest`, at which
- /// point the ServerRequest is dropped and no further calls are possible.
- ///
- /// # Arguments
- ///
- /// * `offset` - The value to use as the new buffer offset for the next buffer.
- /// * `frames` - The length of the next buffer in frames.
- ///
- /// # Errors
- ///
- /// * If `frames` is greater than `requested_frames`.
- pub fn set_buffer_offset_and_frames(self, offset: usize, frames: usize) -> GenericResult<()> {
- if frames > self.requested_frames {
- return Err(Box::new(Error::TooManyFrames(
- frames,
- self.requested_frames,
- )));
- }
-
- self.buffer_set.callback(offset, frames)
- }
-
- /// Ignore this request
- ///
- /// If the client does not intend to respond to this ServerRequest with a
- /// buffer, they should call this function. The stream will be notified that
- /// the request has been ignored and will handle it properly.
- pub fn ignore_request(self) -> GenericResult<()> {
- self.buffer_set.ignore()
- }
-}
-
-/// `ShmStream` allows a client to interact with an active CRAS stream.
-pub trait ShmStream: Send {
- /// Get the size of a frame of audio data for this stream.
- fn frame_size(&self) -> usize;
-
- /// Get the number of channels of audio data for this stream.
- fn num_channels(&self) -> usize;
-
- /// Get the frame rate of audio data for this stream.
- fn frame_rate(&self) -> u32;
-
- /// Waits until the next server message indicating action is required.
- ///
- /// For playback streams, this will be `AUDIO_MESSAGE_REQUEST_DATA`, meaning
- /// that we must set the buffer offset to the next location where playback
- /// data can be found.
- /// For capture streams, this will be `AUDIO_MESSAGE_DATA_READY`, meaning
- /// that we must set the buffer offset to the next location where captured
- /// data can be written to.
- /// Will return early if `timeout` elapses before a message is received.
- ///
- /// # Arguments
- ///
- /// * `timeout` - The amount of time to wait until a message is received.
- ///
- /// # Return value
- ///
- /// Returns `Some(request)` where `request` is an object that implements the
- /// [`ServerRequest`](ServerRequest) trait and which can be used to get the
- /// number of bytes requested for playback streams or that have already been
- /// written to shm for capture streams.
- ///
- /// If the timeout occurs before a message is received, returns `None`.
- ///
- /// # Errors
- ///
- /// * If an invalid message type is received for the stream.
- fn wait_for_next_action_with_timeout(
- &mut self,
- timeout: Duration,
- ) -> GenericResult<Option<ServerRequest>>;
-}
-
-/// `ShmStreamSource` creates streams for playback or capture of audio.
-pub trait ShmStreamSource: Send {
- /// Creates a new [`ShmStream`](ShmStream)
- ///
- /// Creates a new `ShmStream` object, which allows:
- /// * Waiting until the server has communicated that data is ready or
- /// requested that we make more data available.
- /// * Setting the location and length of buffers for reading/writing audio data.
- ///
- /// # Arguments
- ///
- /// * `direction` - The direction of the stream, either `Playback` or `Capture`.
- /// * `num_channels` - The number of audio channels for the stream.
- /// * `format` - The audio format to use for audio samples.
- /// * `frame_rate` - The stream's frame rate in Hz.
- /// * `buffer_size` - The maximum size of an audio buffer. This will be the
- /// size used for transfers of audio data between client
- /// and server.
- /// * `effects` - Audio effects to use for the stream, such as echo-cancellation.
- /// * `client_shm` - The shared memory area that will contain samples.
- /// * `buffer_offsets` - The two initial values to use as buffer offsets
- /// for streams. This way, the server will not write
- /// audio data to an arbitrary offset in `client_shm`
- /// if the client fails to update offsets in time.
- ///
- /// # Errors
- ///
- /// * If sending the connect stream message to the server fails.
- #[allow(clippy::too_many_arguments)]
- fn new_stream(
- &mut self,
- direction: StreamDirection,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- effects: &[StreamEffect],
- client_shm: &SharedMemory,
- buffer_offsets: [u64; 2],
- ) -> GenericResult<Box<dyn ShmStream>>;
-
- /// Get a list of file descriptors used by the implementation.
- ///
- /// Returns any open file descriptors needed by the implementation.
- /// This list helps users of the ShmStreamSource enter Linux jails without
- /// closing needed file descriptors.
- fn keep_fds(&self) -> Vec<RawFd> {
- Vec::new()
- }
-}
-
-/// Class that implements ShmStream trait but does nothing with the samples
-pub struct NullShmStream {
- num_channels: usize,
- frame_rate: u32,
- buffer_size: usize,
- frame_size: usize,
- interval: Duration,
- next_frame: Duration,
- start_time: Instant,
-}
-
-impl NullShmStream {
- /// Attempt to create a new NullShmStream with the given number of channels,
- /// format, frame_rate, and buffer_size.
- pub fn new(
- buffer_size: usize,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- ) -> Self {
- let interval = Duration::from_millis(buffer_size as u64 * 1000 / frame_rate as u64);
- Self {
- num_channels,
- frame_rate,
- buffer_size,
- frame_size: format.sample_bytes() * num_channels,
- interval,
- next_frame: interval,
- start_time: Instant::now(),
- }
- }
-}
-
-impl BufferSet for NullShmStream {
- fn callback(&mut self, _offset: usize, _frames: usize) -> GenericResult<()> {
- Ok(())
- }
-
- fn ignore(&mut self) -> GenericResult<()> {
- Ok(())
- }
-}
-
-impl ShmStream for NullShmStream {
- fn frame_size(&self) -> usize {
- self.frame_size
- }
-
- fn num_channels(&self) -> usize {
- self.num_channels
- }
-
- fn frame_rate(&self) -> u32 {
- self.frame_rate
- }
-
- fn wait_for_next_action_with_timeout(
- &mut self,
- timeout: Duration,
- ) -> GenericResult<Option<ServerRequest>> {
- let elapsed = self.start_time.elapsed();
- if elapsed < self.next_frame {
- if timeout < self.next_frame - elapsed {
- std::thread::sleep(timeout);
- return Ok(None);
- } else {
- std::thread::sleep(self.next_frame - elapsed);
- }
- }
- self.next_frame += self.interval;
- Ok(Some(ServerRequest::new(self.buffer_size, self)))
- }
-}
-
-/// Source of `NullShmStream` objects.
-#[derive(Default)]
-pub struct NullShmStreamSource;
-
-impl NullShmStreamSource {
- pub fn new() -> Self {
- Self::default()
- }
-}
-
-impl ShmStreamSource for NullShmStreamSource {
- fn new_stream(
- &mut self,
- _direction: StreamDirection,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- _effects: &[StreamEffect],
- _client_shm: &SharedMemory,
- _buffer_offsets: [u64; 2],
- ) -> GenericResult<Box<dyn ShmStream>> {
- let new_stream = NullShmStream::new(buffer_size, num_channels, format, frame_rate);
- Ok(Box::new(new_stream))
- }
-}
-
-#[derive(Clone)]
-pub struct MockShmStream {
- num_channels: usize,
- frame_rate: u32,
- request_size: usize,
- frame_size: usize,
- request_notifier: Arc<(Mutex<bool>, Condvar)>,
-}
-
-impl MockShmStream {
- /// Attempt to create a new MockShmStream with the given number of
- /// channels, frame_rate, format, and buffer_size.
- pub fn new(
- num_channels: usize,
- frame_rate: u32,
- format: SampleFormat,
- buffer_size: usize,
- ) -> Self {
- Self {
- num_channels,
- frame_rate,
- request_size: buffer_size,
- frame_size: format.sample_bytes() * num_channels,
- request_notifier: Arc::new((Mutex::new(false), Condvar::new())),
- }
- }
-
- /// Call to request data from the stream, causing it to return from
- /// `wait_for_next_action_with_timeout`. Will block until
- /// `set_buffer_offset_and_frames` is called on the ServerRequest returned
- /// from `wait_for_next_action_with_timeout`, or until `timeout` elapses.
- /// Returns true if a response was successfully received.
- pub fn trigger_callback_with_timeout(&mut self, timeout: Duration) -> bool {
- let &(ref lock, ref cvar) = &*self.request_notifier;
- let mut requested = lock.lock();
- *requested = true;
- cvar.notify_one();
- let start_time = Instant::now();
- while *requested {
- requested = cvar.wait_timeout(requested, timeout).0;
- if start_time.elapsed() > timeout {
- // We failed to get a callback in time, mark this as false.
- *requested = false;
- return false;
- }
- }
-
- true
- }
-
- fn notify_request(&mut self) {
- let &(ref lock, ref cvar) = &*self.request_notifier;
- let mut requested = lock.lock();
- *requested = false;
- cvar.notify_one();
- }
-}
-
-impl BufferSet for MockShmStream {
- fn callback(&mut self, _offset: usize, _frames: usize) -> GenericResult<()> {
- self.notify_request();
- Ok(())
- }
-
- fn ignore(&mut self) -> GenericResult<()> {
- self.notify_request();
- Ok(())
- }
-}
-
-impl ShmStream for MockShmStream {
- fn frame_size(&self) -> usize {
- self.frame_size
- }
-
- fn num_channels(&self) -> usize {
- self.num_channels
- }
-
- fn frame_rate(&self) -> u32 {
- self.frame_rate
- }
-
- fn wait_for_next_action_with_timeout(
- &mut self,
- timeout: Duration,
- ) -> GenericResult<Option<ServerRequest>> {
- {
- let start_time = Instant::now();
- let &(ref lock, ref cvar) = &*self.request_notifier;
- let mut requested = lock.lock();
- while !*requested {
- requested = cvar.wait_timeout(requested, timeout).0;
- if start_time.elapsed() > timeout {
- return Ok(None);
- }
- }
- }
-
- Ok(Some(ServerRequest::new(self.request_size, self)))
- }
-}
-
-/// Source of `MockShmStream` objects.
-#[derive(Clone, Default)]
-pub struct MockShmStreamSource {
- last_stream: Arc<(Mutex<Option<MockShmStream>>, Condvar)>,
-}
-
-impl MockShmStreamSource {
- pub fn new() -> Self {
- Default::default()
- }
-
- /// Get the last stream that has been created from this source. If no stream
- /// has been created, block until one has.
- pub fn get_last_stream(&self) -> MockShmStream {
- let &(ref last_stream, ref cvar) = &*self.last_stream;
- let mut stream = last_stream.lock();
- loop {
- match &*stream {
- None => stream = cvar.wait(stream),
- Some(ref s) => return s.clone(),
- };
- }
- }
-}
-
-impl ShmStreamSource for MockShmStreamSource {
- fn new_stream(
- &mut self,
- _direction: StreamDirection,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- _effects: &[StreamEffect],
- _client_shm: &SharedMemory,
- _buffer_offsets: [u64; 2],
- ) -> GenericResult<Box<dyn ShmStream>> {
- let &(ref last_stream, ref cvar) = &*self.last_stream;
- let mut stream = last_stream.lock();
-
- let new_stream = MockShmStream::new(num_channels, frame_rate, format, buffer_size);
- *stream = Some(new_stream.clone());
- cvar.notify_one();
- Ok(Box::new(new_stream))
- }
-}
-
-#[cfg(test)]
-pub mod tests {
- use super::*;
-
- #[test]
- fn mock_trigger_callback() {
- let stream_source = MockShmStreamSource::new();
- let mut thread_stream_source = stream_source.clone();
-
- let buffer_size = 480;
- let num_channels = 2;
- let format = SampleFormat::S24LE;
- let shm = SharedMemory::anon().expect("Failed to create shm");
-
- let handle = std::thread::spawn(move || {
- let mut stream = thread_stream_source
- .new_stream(
- StreamDirection::Playback,
- num_channels,
- format,
- 44100,
- buffer_size,
- &[],
- &shm,
- [400, 8000],
- )
- .expect("Failed to create stream");
-
- let request = stream
- .wait_for_next_action_with_timeout(Duration::from_secs(5))
- .expect("Failed to wait for next action");
- match request {
- Some(r) => {
- let requested = r.requested_frames();
- r.set_buffer_offset_and_frames(872, requested)
- .expect("Failed to set buffer offset and frames");
- requested
- }
- None => 0,
- }
- });
-
- let mut stream = stream_source.get_last_stream();
- assert!(stream.trigger_callback_with_timeout(Duration::from_secs(1)));
-
- let requested_frames = handle.join().expect("Failed to join thread");
- assert_eq!(requested_frames, buffer_size);
- }
-
- #[test]
- fn null_consumption_rate() {
- let frame_rate = 44100;
- let buffer_size = 480;
- let interval = Duration::from_millis(buffer_size as u64 * 1000 / frame_rate as u64);
-
- let shm = SharedMemory::anon().expect("Failed to create shm");
-
- let start = Instant::now();
-
- let mut stream_source = NullShmStreamSource::new();
- let mut stream = stream_source
- .new_stream(
- StreamDirection::Playback,
- 2,
- SampleFormat::S24LE,
- frame_rate,
- buffer_size,
- &[],
- &shm,
- [400, 8000],
- )
- .expect("Failed to create stream");
-
- let timeout = Duration::from_secs(5);
- let request = stream
- .wait_for_next_action_with_timeout(timeout)
- .expect("Failed to wait for first request")
- .expect("First request should not have timed out");
- request
- .set_buffer_offset_and_frames(276, 480)
- .expect("Failed to set buffer offset and length");
-
- // The second call should block until the first buffer is consumed.
- let _request = stream
- .wait_for_next_action_with_timeout(timeout)
- .expect("Failed to wait for second request");
- let elapsed = start.elapsed();
- assert!(
- elapsed > interval,
- "wait_for_next_action_with_timeout didn't block long enough: {:?}",
- elapsed
- );
-
- assert!(
- elapsed < timeout,
- "wait_for_next_action_with_timeout blocked for too long: {:?}",
- elapsed
- );
- }
-}
diff --git a/cras-config/device_blocklist b/cras-config/device_blocklist
deleted file mode 100644
index 19a9b033..00000000
--- a/cras-config/device_blocklist
+++ /dev/null
@@ -1,2 +0,0 @@
-[USB_Outputs]
- 0d8c_0008_3cd197dd_0 = 1 ; CAD-u1 mic crosbug.com/32278
diff --git a/cras-config/dsp.ini.sample b/cras-config/dsp.ini.sample
deleted file mode 100644
index c3ca1275..00000000
--- a/cras-config/dsp.ini.sample
+++ /dev/null
@@ -1,104 +0,0 @@
-[output_source]
-library=builtin
-label=source
-purpose=playback
-disable=(equal? output_jack "HDMI")
-output_0={src:0}
-output_1={src:1}
-
-[output_sink]
-library=builtin
-label=sink
-purpose=playback
-disable=(equal? output_jack "HDMI")
-input_0={dst:0}
-input_1={dst:1}
-
-[drc]
-library=builtin
-label=drc
-input_0={src:0}
-input_1={src:1}
-output_2={intermediate:0}
-output_3={intermediate:1}
-input_4=0 ; emphasis_disabled
-input_5=0 ; f
-input_6=0 ; enable
-input_7=-29 ; threshold
-input_8=3 ; knee
-input_9=6.677 ; ratio
-input_10=0.02 ; attack
-input_11=0.2 ; release
-input_12=-7 ; boost
-input_13=200 ; f
-input_14=1 ; enable
-input_15=-32 ; threshold
-input_16=23 ; knee
-input_17=12 ; ratio
-input_18=0.02 ; attack
-input_19=0.2 ; release
-input_20=0.7 ; boost
-input_21=1200 ; f
-input_22=1 ; enable
-input_23=-24 ; threshold
-input_24=30 ; knee
-input_25=1 ; ratio
-input_26=0.001 ; attack
-input_27=1 ; release
-input_28=0 ; boost
-
-[eq2]
-library=builtin
-label=eq2
-input_0={intermediate:0}
-input_1={intermediate:1}
-output_2={dst:0}
-output_3={dst:1}
-input_4=6 ; peaking
-input_5=380 ; freq
-input_6=3 ; Q
-input_7=-10 ; gain
-input_8=6 ; peaking
-input_9=450 ; freq
-input_10=3 ; Q
-input_11=-12 ; gain
-input_12=6 ; peaking
-input_13=720 ; freq
-input_14=3 ; Q
-input_15=-12 ; gain
-input_16=6 ; peaking
-input_17=721 ; freq
-input_18=3 ; Q
-input_19=-12 ; gain
-input_20=6 ; peaking
-input_21=1705 ; freq
-input_22=3 ; Q
-input_23=-8 ; gain
-input_24=6 ; peaking
-input_25=1800 ; freq
-input_26=8 ; Q
-input_27=-10.2 ; gain
-input_28=2 ; highpass
-input_29=218 ; freq
-input_30=0.7 ; Q
-input_31=-10.2 ; gain
-input_32=6 ; peaking
-input_33=580 ; freq
-input_34=6 ; Q
-input_35=-8 ; gain
-input_36=6 ; peaking
-input_37=580 ; freq
-input_38=6 ; Q
-input_39=-8 ; gain
-input_40=2 ; highpass
-input_41=250 ; freq
-input_42=0.6578 ; Q
-input_43=0 ; gain
-input_44=5 ; highshelf
-input_45=8000 ; freq
-input_46=3 ; Q
-input_47=2 ; gain
-input_48=5 ; highshelf
-input_49=8000 ; freq
-input_50=0 ; Q
-input_51=2 ; gain
diff --git a/cras-config/for_all_boards/Chat 150 C b/cras-config/for_all_boards/Chat 150 C
deleted file mode 100644
index 047ab29b..00000000
--- a/cras-config/for_all_boards/Chat 150 C
+++ /dev/null
@@ -1,4 +0,0 @@
-[Default]
- volume_curve = simple_step
- volume_step = 25
- max_volume = 0
diff --git a/cras-config/for_all_boards/Jabra SPEAK 810 b/cras-config/for_all_boards/Jabra SPEAK 810
deleted file mode 100644
index 5117dd20..00000000
--- a/cras-config/for_all_boards/Jabra SPEAK 810
+++ /dev/null
@@ -1,4 +0,0 @@
-[Default]
- volume_curve = simple_step
- volume_step = 30
- max_volume = 0
diff --git a/cras-config/for_all_boards/Logitech MeetUp Speakerphone b/cras-config/for_all_boards/Logitech MeetUp Speakerphone
deleted file mode 100644
index 429835fe..00000000
--- a/cras-config/for_all_boards/Logitech MeetUp Speakerphone
+++ /dev/null
@@ -1,103 +0,0 @@
-[Default]
- volume_curve = explicit
- db_at_100 = 0
- db_at_99 = -30
- db_at_98 = -60
- db_at_97 = -90
- db_at_96 = -120
- db_at_95 = -150
- db_at_94 = -180
- db_at_93 = -210
- db_at_92 = -240
- db_at_91 = -270
- db_at_90 = -300
- db_at_89 = -330
- db_at_88 = -360
- db_at_87 = -390
- db_at_86 = -420
- db_at_85 = -450
- db_at_84 = -480
- db_at_83 = -510
- db_at_82 = -540
- db_at_81 = -570
- db_at_80 = -600
- db_at_79 = -630
- db_at_78 = -660
- db_at_77 = -690
- db_at_76 = -720
- db_at_75 = -750
- db_at_74 = -780
- db_at_73 = -810
- db_at_72 = -840
- db_at_71 = -870
- db_at_70 = -900
- db_at_69 = -930
- db_at_68 = -960
- db_at_67 = -990
- db_at_66 = -1020
- db_at_65 = -1050
- db_at_64 = -1080
- db_at_63 = -1110
- db_at_62 = -1140
- db_at_61 = -1170
- db_at_60 = -1200
- db_at_59 = -1230
- db_at_58 = -1260
- db_at_57 = -1290
- db_at_56 = -1320
- db_at_55 = -1350
- db_at_54 = -1380
- db_at_53 = -1410
- db_at_52 = -1440
- db_at_51 = -1470
- db_at_50 = -1500
- db_at_49 = -1560
- db_at_48 = -1620
- db_at_47 = -1680
- db_at_46 = -1740
- db_at_45 = -1800
- db_at_44 = -1860
- db_at_43 = -1920
- db_at_42 = -1980
- db_at_41 = -2040
- db_at_40 = -2100
- db_at_39 = -2160
- db_at_38 = -2220
- db_at_37 = -2280
- db_at_36 = -2340
- db_at_35 = -2400
- db_at_34 = -2460
- db_at_33 = -2520
- db_at_32 = -2580
- db_at_31 = -2640
- db_at_30 = -2700
- db_at_29 = -2760
- db_at_28 = -2820
- db_at_27 = -2880
- db_at_26 = -2940
- db_at_25 = -3000
- db_at_24 = -3060
- db_at_23 = -3120
- db_at_22 = -3180
- db_at_21 = -3240
- db_at_20 = -3300
- db_at_19 = -3360
- db_at_18 = -3420
- db_at_17 = -3480
- db_at_16 = -3540
- db_at_15 = -3600
- db_at_14 = -3660
- db_at_13 = -3720
- db_at_12 = -3780
- db_at_11 = -3840
- db_at_10 = -3900
- db_at_9 = -3960
- db_at_8 = -4020
- db_at_7 = -4080
- db_at_6 = -4140
- db_at_5 = -4200
- db_at_4 = -4260
- db_at_3 = -4320
- db_at_2 = -4380
- db_at_1 = -4440
- db_at_0 = -4500
diff --git a/cras/.gitignore b/cras/.gitignore
deleted file mode 100644
index dcbb1808..00000000
--- a/cras/.gitignore
+++ /dev/null
@@ -1,45 +0,0 @@
-*.o
-*.la
-*.lo
-*.a
-*.so*
-*.log
-*.d
-*.swp
-*.trs
-.deps
-.dirstamp
-.libs
-
-/.__autoconf_trace_data
-/.elibtoolized
-/aclocal.m4
-/ar-lib
-/autom4te.cache/
-/compile
-/config.cache
-/config.guess
-/config.log
-/config.status
-/config.sub
-/configure
-/depcomp
-/install-sh
-/libtool
-/ltmain.sh
-/missing
-/test-driver
-Makefile.in
-
-tags
-/Makefile
-/libcras.pc
-/src/Makefile
-/src/*_unittest
-/src/*_test
-/src/cmpraw
-/src/cras
-/src/cras_monitor
-/src/cras_router
-/src/cras_test_client
-/src/common/cras_version.h
diff --git a/cras/Makefile.am b/cras/Makefile.am
deleted file mode 100644
index 6c89bdcb..00000000
--- a/cras/Makefile.am
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-AUTOMAKE_OPTIONS = foreign
-SUBDIRS = src
-pkgconfigdir = $(libdir)/pkgconfig
-pkgconfig_DATA = libcras.pc
-
-compile_commands.json:
- which bear || (echo "Please install 'bear' first." && exit 1)
- bear make check -j$(nproc)
-
-clean-local:
- rm -f compile_commands.json
diff --git a/cras/README.dbus-api b/cras/README.dbus-api
deleted file mode 100644
index f347358e..00000000
--- a/cras/README.dbus-api
+++ /dev/null
@@ -1,238 +0,0 @@
-CRAS dbus methods and signals.
-==============================
-
-Service org.chromium.cras
-Interface org.chromium.cras.Control
-Object Path /org/chromium/cras
-
-Methods void SetOutputVolume(int32 volume)
-
- Sets the volume of the system. Volume ranges from
- 0 to 100, and will be translated to dB based on the
- output-specific volume curve.
-
- void SetOutputNodeVolume(uint64 node_id, int32 volume)
-
- Sets the volume of the given node. Volume ranges from
- 0 to 100, and will be translated to dB based on the
- output-specific volume curve.
-
- void SwapLeftRight(uint64 node_id, boolean swap)
-
- Swap the left and right channel of the given node.
- Message will be dropped if this feature is not supported.
-
- void SetOutputMute(boolean mute_on)
-
- Sets the system output mute.
-
- void SetOutputUserMute(boolean mute_on)
-
- Sets the system output mute from user action.
-
- void SetInputNodeGain(uint64 node_id, int32 gain)
-
- Sets the capture gain of the node. gain is a 0-100
- integer which linearly maps [0, 50] to range [-40dB, 0dB]
- and [50, 100] to [0dB, 20dB],
- Default gain value is 50, which is 0dB.
-
- void SetInputMute(boolean mute_on)
-
- Sets the capture mute state of the system. Recordings
- will be muted when this is set.
-
- void GetVolumeState()
-
- Returns the volume and capture gain as follows:
- int32 output_volume (0-100)
- boolean output_mute
- int32 input_gain (in dBFS * 100)
- boolean input_mute
- boolean output_user_mute
-
- void GetDefaultOutputBufferSize()
-
- Returns the default output buffer size in frames.
-
- {dict},{dict},... GetNodes()
-
- Returns information about nodes. A node can be either
- output or input but not both. An output node is
- something like a speaker or a headphone, and an input
- node is like a microphone. The return value is a
- sequence of dicts mapping from strings to variants
- (e.g. signature "a{sv}a{sv}" for two nodes). Each dict
- contains information about a node.
-
- Each dict contains the following properties:
- boolean IsInput
- false for output nodes, true for input
- nodes.
- uint64 Id
- The id of this node. It is unique among
- all nodes including both output and
- input nodes.
- string Type
- The type of this node. It can be one of
- following values:
- /* for output nodes. */
- "INTERNAL_SPEAKER","HEADPHONE", "HDMI",
- /* for input nodes. */
- "INTERNAL_MIC", "MIC",
- /* for both output and input nodes. */
- "USB", "BLUETOOTH", "UNKNOWN",
- string Name
- The name of this node. For example,
- "Speaker" or "Internal Mic".
- string DeviceName
- The name of the device that this node
- belongs to. For example,
- "HDA Intel PCH: CA0132 Analog:0,0" or
- "Creative SB Arena Headset".
- uint64 StableDeviceId
- The stable ID does not change due to
- device plug/unplug or reboot.
- uint64 StableDeviceIdNew
- The new stable ID. Keeping both stable
- ID and stable ID new is for backward
- compatibility.
- boolean Active
- Whether this node is currently used
- for output/input. There is one active
- node for output and one active node for
- input.
- uint64 PluggedTime
- The time that this device was plugged
- in. This value is in microseconds.
- unit64 NodeVolume
- The node volume indexed from 0 to 100.
- unit64 NodeCaptureGain
- The capture gain of node in dBFS * 100.
- string HotwordModels
- A string of comma-separated hotword
- language model locales supported by this
- node. e.g. "en_au,en_gb,en_us"
- The string is empty if the node type is
- not HOTWORD.
-
- void GetSystemAecSupported();
-
- Returns 1 if system echo cancellation is supported,
- otherwise return 0.
-
- void SetActiveOutputNode(uint64 node_id);
-
- Requests the specified node to be used for
- output. If node_id is 0 (which is not a valid
- node id), cras will choose the active node
- automatically.
-
- void SetActiveInputNode(uint64 node_id);
-
- Requests the specified node to be used for
- input. If node_id is 0 (which is not a valid
- node id), cras will choose the active node
- automatically.
-
- int32 GetNumberOfActiveStreams()
-
- Returns the number of streams currently being
- played or recorded.
-
- int32 GetNumberOfActiveInputStreams()
-
- Returns the number of streams currently using input hardware.
-
- int32 GetNumberOfActiveOutputStreams()
-
- Returns the number of streams currently using output hardware.
-
- int32 IsAudioOutputActive()
-
- Returns 1 if there are currently any active output streams,
- excluding 'fake' streams that are not actually outputting any
- audio. Returns 0 if there are no active streams, or all active
- streams are 'fake' streams.
-
- void SetGlobalOutputChannelRemix(int32 num_channels,
- array:double coefficient)
-
- Sets the conversion matrix for global output channel
- remixing. The coefficient array represents an N * N
- conversion matrix M, where N is num_channels, with
- M[i][j] = coefficient[i * N + j].
- The remix is done by multiplying the conversion matrix
- to each N-channel PCM data, i.e M * [L, R] = [L', R']
- For example, coefficient [0.1, 0.9, 0.4, 0.6] will
- result in:
- L' = 0.1 * L + 0.9 * R
- R' = 0.4 * L + 0.6 * R
-
- int32 SetHotwordModel(uint64_t node_id, string model_name)
-
- Set the hotword language model on the specified node.
- The node must have type HOTWORD and the model_name must
- be one of the supported locales returned by
- GetNodes() HotwordModels string.
- Returns 0 on success, or a negative errno on failure.
-
-Signals OutputVolumeChanged(int32 volume)
-
- Indicates that the output volume level has changed.
-
- OutputMuteChanged(boolean muted, boolean user_muted)
-
- Indicates that the output mute state has changed. muted
- is true if the system is muted by a system process, such
- as suspend or device switch. user_muted is set if the
- system has been muted by user action such as the mute
- key.
-
- InputGainChanged(int32 gain)
-
- Indicates what the system capture gain is now. gain
- expressed in dBFS*100.
-
- InputMuteChanged(boolean muted)
-
- Indicates that the input mute state has changed.
-
- NodesChanged()
-
- Indicates that nodes are added/removed.
-
- ActiveOutputNodeChanged(uint64 node_id)
-
- Indicates that the active output node has changed.
-
- ActiveInputNodeChanged(uint64 node_id)
-
- Indicates that the active input node has changed.
-
- OutputNodeVolumeChanged(uint64 node_id, int32 volume)
-
- Indicates the volume of the given node.
-
- NodeLeftRightSwappedChanged(uint64 node_id, boolean swapped)
-
- Indicates the left and right channel swapping state of the
- given node.
-
- InputNodeGainChanged(uint64 node_id, int32 gain)
-
- Indicates that the capture gain for the node is now gain
- expressed in dBFS*100.
-
- NumberOfActiveStreamsChanged(int32 num_active_streams)
-
- Indicates the number of active streams has changed.
-
- AudioOutputActiveStateChanged(boolean active)
-
- Indicates active output state has changed.
- See IsAudioOutputActive for details.
-
- HotwordTriggered(int64 tv_sec, int64 tv_nsec)
-
- Indicates that hotword was triggered at the given timestamp.
diff --git a/cras/README.md b/cras/README.md
deleted file mode 100644
index e0ef0ec5..00000000
--- a/cras/README.md
+++ /dev/null
@@ -1,222 +0,0 @@
-CRAS = ChromeOS Audio Server
-===
-
-# Directories
-- [src/server](src/server) - the source for the sound server
-- [src/libcras](src/libcras) - client library for interacting with cras
-- [src/common](src/common) - files common to both the server and library
-- [src/tests](src/tests) - tests for cras and libcras
-- [src/fuzz](src/fuzz) - source code and build scripts for coverage-guided
- fuzzers for CRAS
-
-# Building from source:
-```
-# Generate install-sh
-./git_prepare.sh
-
-# Configure
-CC=clang \
-CXX=clang++ \
-CXXFLAGS="-g -O2 -std=gnu++11 -Wall" \
-CFLAGS="-g -O2 -Wall" \
-./configure --disable-alsa-plugin
-
-# Compile
-make -j$(nproc)
-
-# Compile with unit tests
-make -j$(nproc) check
-
-# Install binaries to /usr/bin
-sudo make install
-```
-
-## Code complete for for editors
-You need to install [bear] first and generate [compile commands] for
-[language server plugins in editors] by
-```
-make clean && make compile_commands.json
-```
-Then you'll get `compile_commands.json` for editor.
-Import the JSON file to your editor and you'll get useful code complete
-features for CRAS and its unit tests.
-
-# Configuration:
-
-## Device Blocklisting:
-
-Blocklist of certain USB output device(s) is possible by modifying the config
-file `/etc/cras/device_blocklist`.
-
-The format of this file is as follows:
-```
-[USB_Outputs]
- <vendor_id>_<product_id>_<checksum>_<device_index> = 1
-```
-Where vendor_id and product id are the USB identifiers for the card to
-blocklist. The checksum is the output of "cksum" command applied to the
-sysfs "descriptors" file of the device. The device index specifies the
-index of the output device in the card to blocklist. This is a bool
-parameter, so '= 1' enables the option.
-
-Example, blocklisting the non-functional output device reported by the C-Media
-based CAD-u1 mic:
-```
-[USB_Outputs]
- 0d8c_0008_00000000_0 = 1
-```
-
-## Card Configuration:
-
-There can be a config file for each sound alsa card on the system. This file
-lives in `/etc/cras/`. The file should be named with the card name returned by
-ALSA, the string in the second set of '[]' in the aplay -l output. The ini file
-has the following format.
-
-```
-[<output-node-name>] ; Name of the mixer control for this output.
- <config-option> = <config-value>
-```
-output-node-name can be speficied in a few ways to link with the real node:
-- UCM device name - The name string following the SectionDevice label in UCM
- config, i.e. HiFi.conf
-- Jack name - Name of the mixer control for mixer jack, or the gpio jack name
- listed by 'evtest' command.
-- Mixer control name - e.g. "Headphone" or "Speaker", listed by
- 'amixer scontrols' command.
-
-Note that an output node matches to the output-node-name label in card config by
-priorty ordered above. For example if a node has UCM device, it will first
-search the config file for the UCM device name. When not found, jack name will
-be used for searching, and lastly the mixer output control name.
-
-config-option can be the following:
-- volume_curve - The type of volume curve, "simple_step" or "explicit".
-- Options valid and mandatory when volume_curve = simple_step:
- - max_volume - The maximum volume for this output specified in dBFS * 100.
- - volume_step - Number of dB per volume 'tick' specified in dBFS * 100.
-- Options valid and mandatory when volume_curve = explicit:
- - dB_at_N - The value in dB*100 that should be used for the volume at step
- "N". There must be one of these for each setting from N=0 to 100
- inclusive.
-
-
-Example:
-This example configures the Headphones to have a max volume of -3dBFS with a
-step size of 0.75dBFS and the Speaker to have the curve specified by the steps
-given, which is a 1dBFS per step curve from max = +0.5dBFS to min = -99.5dBFS
-(volume step 10 is -89.5dBFS).
-
-```
-[Headphone]
- volume_curve = simple_step
- volume_step = 75
- max_volume = -300
-[Speaker]
- volume_curve = explicit
- dB_at_0 = -9950
- dB_at_1 = -9850
- dB_at_2 = -9750
- dB_at_3 = -9650
- dB_at_4 = -9550
- dB_at_5 = -9450
- dB_at_6 = -9350
- dB_at_7 = -9250
- dB_at_8 = -9150
- dB_at_9 = -9050
- dB_at_10 = -8950
- dB_at_11 = -8850
- dB_at_12 = -8750
- dB_at_13 = -8650
- dB_at_14 = -8550
- dB_at_15 = -8450
- dB_at_16 = -8350
- dB_at_17 = -8250
- dB_at_18 = -8150
- dB_at_19 = -8050
- dB_at_20 = -7950
- dB_at_21 = -7850
- dB_at_22 = -7750
- dB_at_23 = -7650
- dB_at_24 = -7550
- dB_at_25 = -7450
- dB_at_26 = -7350
- dB_at_27 = -7250
- dB_at_28 = -7150
- dB_at_29 = -7050
- dB_at_30 = -6950
- dB_at_31 = -6850
- dB_at_32 = -6750
- dB_at_33 = -6650
- dB_at_34 = -6550
- dB_at_35 = -6450
- dB_at_36 = -6350
- dB_at_37 = -6250
- dB_at_38 = -6150
- dB_at_39 = -6050
- dB_at_40 = -5950
- dB_at_41 = -5850
- dB_at_42 = -5750
- dB_at_43 = -5650
- dB_at_44 = -5550
- dB_at_45 = -5450
- dB_at_46 = -5350
- dB_at_47 = -5250
- dB_at_48 = -5150
- dB_at_49 = -5050
- dB_at_50 = -4950
- dB_at_51 = -4850
- dB_at_52 = -4750
- dB_at_53 = -4650
- dB_at_54 = -4550
- dB_at_55 = -4450
- dB_at_56 = -4350
- dB_at_57 = -4250
- dB_at_58 = -4150
- dB_at_59 = -4050
- dB_at_60 = -3950
- dB_at_61 = -3850
- dB_at_62 = -3750
- dB_at_63 = -3650
- dB_at_64 = -3550
- dB_at_65 = -3450
- dB_at_66 = -3350
- dB_at_67 = -3250
- dB_at_68 = -3150
- dB_at_69 = -3050
- dB_at_70 = -2950
- dB_at_71 = -2850
- dB_at_72 = -2750
- dB_at_73 = -2650
- dB_at_74 = -2550
- dB_at_75 = -2450
- dB_at_76 = -2350
- dB_at_77 = -2250
- dB_at_78 = -2150
- dB_at_79 = -2050
- dB_at_80 = -1950
- dB_at_81 = -1850
- dB_at_82 = -1750
- dB_at_83 = -1650
- dB_at_84 = -1550
- dB_at_85 = -1450
- dB_at_86 = -1350
- dB_at_87 = -1250
- dB_at_88 = -1150
- dB_at_89 = -1050
- dB_at_90 = -950
- dB_at_91 = -850
- dB_at_92 = -750
- dB_at_93 = -650
- dB_at_94 = -550
- dB_at_95 = -450
- dB_at_96 = -350
- dB_at_97 = -250
- dB_at_98 = -150
- dB_at_99 = -50
- dB_at_100 = 50
-```
-
-[bear]: https://github.com/rizsotto/Bear
-[compile commands]: https://clang.llvm.org/extra/clangd/Installation.html#compile-commands-json
-[language server plugins in editors]: https://clang.llvm.org/extra/clangd/Installation.html#editor-plugins
diff --git a/cras/client/cras-sys/.gitignore b/cras/client/cras-sys/.gitignore
deleted file mode 100644
index fa8d85ac..00000000
--- a/cras/client/cras-sys/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Cargo.lock
-target
diff --git a/cras/client/cras-sys/.rustfmt.toml b/cras/client/cras-sys/.rustfmt.toml
deleted file mode 100644
index a2db3012..00000000
--- a/cras/client/cras-sys/.rustfmt.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-use_field_init_shorthand = true
-use_try_shorthand = true
diff --git a/cras/client/cras-sys/Android.bp b/cras/client/cras-sys/Android.bp
deleted file mode 100644
index d6482b2e..00000000
--- a/cras/client/cras-sys/Android.bp
+++ /dev/null
@@ -1,62 +0,0 @@
-// This file is generated by cargo2android.py --run --device --test --global_defaults=crosvm_defaults --dependencies.
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "external_adhd_license"
- // to get the below license kinds:
- // SPDX-license-identifier-BSD
- default_applicable_licenses: ["external_adhd_license"],
-}
-
-rust_defaults {
- name: "cras-sys_defaults",
- defaults: ["crosvm_defaults"],
- crate_name: "cras_sys",
- srcs: ["src/lib.rs"],
- test_suites: ["general-tests"],
- auto_gen_config: true,
- edition: "2015",
- rustlibs: [
- "libaudio_streams",
- "libdata_model",
- ],
-}
-
-rust_test_host {
- name: "cras-sys_host_test_src_lib",
- defaults: ["cras-sys_defaults"],
-}
-
-rust_test {
- name: "cras-sys_device_test_src_lib",
- defaults: ["cras-sys_defaults"],
-}
-
-rust_library {
- name: "libcras_sys",
- defaults: ["crosvm_defaults"],
- host_supported: true,
- crate_name: "cras_sys",
- srcs: ["src/lib.rs"],
- edition: "2015",
- rustlibs: [
- "libaudio_streams",
- "libdata_model",
- ],
-}
-
-// dependent_library ["feature_list"]
-// ../../../../crosvm/assertions/src/lib.rs
-// ../../../../crosvm/data_model/src/lib.rs
-// ../../../../crosvm/sync/src/lib.rs
-// ../../../../crosvm/sys_util/poll_token_derive/poll_token_derive.rs
-// ../../../../crosvm/sys_util/src/lib.rs
-// ../../../../crosvm/syscall_defines/src/lib.rs
-// ../../../../crosvm/tempfile/src/lib.rs
-// ../../../audio_streams/src/audio_streams.rs
-// libc-0.2.76 "default,std"
-// proc-macro2-1.0.19 "default,proc-macro"
-// quote-1.0.7 "default,proc-macro"
-// syn-1.0.39 "clone-impls,default,derive,parsing,printing,proc-macro,quote"
-// unicode-xid-0.2.1 "default"
diff --git a/cras/client/cras-sys/Cargo.toml b/cras/client/cras-sys/Cargo.toml
deleted file mode 100644
index 1ac1857a..00000000
--- a/cras/client/cras-sys/Cargo.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-[package]
-name = "cras-sys"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-
-[dependencies]
-audio_streams = { path = "../../../audio_streams" } # provided by ebuild
-data_model = { path = "../../../../crosvm/data_model" } # provided by ebuild
diff --git a/cras/client/cras-sys/generator/.gitignore b/cras/client/cras-sys/generator/.gitignore
deleted file mode 100644
index 0e8b881c..00000000
--- a/cras/client/cras-sys/generator/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.h
-Cargo.lock
diff --git a/cras/client/cras-sys/generator/Cargo.toml b/cras/client/cras-sys/generator/Cargo.toml
deleted file mode 100644
index 87c826e2..00000000
--- a/cras/client/cras-sys/generator/Cargo.toml
+++ /dev/null
@@ -1,7 +0,0 @@
-[package]
-name = "generator"
-version = "0.1.0"
-authors = ["paulhsia <paulhsia@chromium.org>"]
-
-[dependencies]
-bindgen = "0.43.0"
diff --git a/cras/client/cras-sys/generator/README.md b/cras/client/cras-sys/generator/README.md
deleted file mode 100644
index 0ca99062..00000000
--- a/cras/client/cras-sys/generator/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-1. Use `cargo run` to generate rust bindings at `lib_gen.rs`
-
-2. Copy `lib_gen.rs` to `cras-sys/src/gen.rs
diff --git a/cras/client/cras-sys/generator/src/main.rs b/cras/client/cras-sys/generator/src/main.rs
deleted file mode 100644
index e562691d..00000000
--- a/cras/client/cras-sys/generator/src/main.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-extern crate bindgen;
-
-use bindgen::builder;
-
-use std::fs::{self, File};
-use std::io::Write;
-use std::path::Path;
-use std::str;
-
-fn copy_headers(src_dir: &Path, dst_dir: &Path) -> Result<(), String> {
- if dst_dir.is_file() {
- fs::remove_file(&dst_dir).or_else(|e| {
- Err(format!(
- "failed to remove existing file at {:?}: {}",
- dst_dir, e
- ))
- })?;
- }
-
- if !dst_dir.is_dir() {
- fs::create_dir(&dst_dir).or_else(|e| {
- Err(format!(
- "failed to create destination directory: {:?}: {}",
- dst_dir, e
- ))
- })?;
- }
-
- let header_files = vec![
- "cras_audio_format.h",
- "cras_iodev_info.h",
- "cras_messages.h",
- "cras_shm.h",
- "cras_types.h",
- "cras_util.h",
- "packet_status_logger.h",
- ];
-
- for header in &header_files {
- let src = src_dir.join(&header);
- let dst = dst_dir.join(&header);
- fs::copy(&src, &dst).or_else(|e| {
- Err(format!(
- "failed to copy header file {:?} to {:?}: {}",
- src, dst, e
- ))
- })?;
- }
- Ok(())
-}
-
-/*
- * If we use both `packed` and `align(4)` for a struct, bindgen will generate
- * it as an opaque struct.
- *
- * `cras_server_state` is created from C with `packed` and `aligned(4)` and
- * shared through a shared memory area.
- *
- * Structs with `packed` and `align(4)` have the same memory layout as those
- * with `packed` except for some extra alignment bytes at the end.
- *
- * Therefore, using only `packed` for `cras_server_state` from Rust side is safe.
- *
- * This function modifies `cras_server_state` from
- * `__attribute__ ((packed, aligned(4)))` to `__attribute__ ((packed))`
- */
-fn modify_server_state_attributes(dir: &Path) -> Result<(), String> {
- let cras_types_path = dir.join("cras_types.h");
- let bytes = fs::read(&cras_types_path)
- .or_else(|e| Err(format!("failed to read {:?}: {}", cras_types_path, e)))?;
-
- let old = str::from_utf8(&bytes).or_else(|e| {
- Err(format!(
- "failed to parse {:?} as utf8: {}",
- cras_types_path, e
- ))
- })?;
-
- let new = old.replacen(
- "struct __attribute__((packed, aligned(4))) cras_server_state {",
- "struct __attribute__((packed)) cras_server_state {",
- 1,
- );
-
- if new.len() >= old.len() {
- return Err("failed to remove 'aligned(4)' from cras_server_state".to_string());
- }
-
- fs::write(&cras_types_path, new).or_else(|e| {
- Err(format!(
- "failed to write updated contents to {:?}: {}",
- cras_types_path, e
- ))
- })?;
-
- Ok(())
-}
-
-fn gen() -> String {
- let name = "cras_gen";
- let bindings = builder()
- .header("c_headers/cras_messages.h")
- .header("c_headers/cras_types.h")
- .header("c_headers/cras_audio_format.h")
- .header("c_headers/cras_shm.h")
- .whitelist_type("cras_.*")
- .whitelist_var("cras_.*")
- .whitelist_type("CRAS_.*")
- .whitelist_var("CRAS_.*")
- .whitelist_type("audio_message")
- .whitelist_var("MAX_DEBUG_.*")
- .rustified_enum("CRAS_.*")
- .rustified_enum("_snd_pcm_.*")
- .bitfield_enum("CRAS_STREAM_EFFECT")
- .generate()
- .expect(format!("Unable to generate {} code", name).as_str());
-
- bindings.to_string()
-}
-
-fn write_output(output_path: &Path, output: String) -> std::io::Result<()> {
- let header = b"// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/*
- * generated from files in cras/src/common in adhd:
- * cras_audio_format.h
- * cras_iodev_info.h
- * cras_messages.h
- * cras_shm.h
- * cras_types.h
- * cras_util.h
- * packet_status_logger.h
- */
-
-#![allow(clippy::unreadable_literal)]
-#![allow(clippy::cognitive_complexity)]
-";
-
- let mut output_file = File::create(output_path)?;
- output_file.write_all(header)?;
- output_file.write_all(output.as_bytes())?;
- Ok(())
-}
-
-fn main() {
- let src_header_dir = Path::new("../../../src/common");
- let dst_header_dir = Path::new("./c_headers");
-
- copy_headers(src_header_dir, dst_header_dir).expect("failed to copy C headers");
- modify_server_state_attributes(dst_header_dir)
- .expect("failed to modify cras_server_state's attributes");
- let generated_code = gen();
- write_output(Path::new("lib_gen.rs"), generated_code).expect("failed to write generated code");
-}
diff --git a/cras/client/cras-sys/src/gen.rs b/cras/client/cras-sys/src/gen.rs
deleted file mode 100644
index 6fb4cdf8..00000000
--- a/cras/client/cras-sys/src/gen.rs
+++ /dev/null
@@ -1,5004 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-/*
- * generated from files in cras/src/common in adhd:
- * cras_audio_format.h
- * cras_iodev_info.h
- * cras_messages.h
- * cras_shm.h
- * cras_types.h
- * cras_util.h
- * packet_status_logger.h
- */
-
-#![allow(clippy::unreadable_literal)]
-#![allow(clippy::cognitive_complexity)]
-/* automatically generated by rust-bindgen */
-
-pub const CRAS_IODEV_NAME_BUFFER_SIZE: u32 = 64;
-pub const CRAS_NODE_TYPE_BUFFER_SIZE: u32 = 32;
-pub const CRAS_NODE_MIC_POS_BUFFER_SIZE: u32 = 128;
-pub const CRAS_NODE_NAME_BUFFER_SIZE: u32 = 64;
-pub const CRAS_NODE_HOTWORD_MODEL_BUFFER_SIZE: u32 = 16;
-pub const CRAS_MAX_IODEVS: u32 = 20;
-pub const CRAS_MAX_IONODES: u32 = 20;
-pub const CRAS_MAX_ATTACHED_CLIENTS: u32 = 20;
-pub const CRAS_MAX_AUDIO_THREAD_SNAPSHOTS: u32 = 10;
-pub const CRAS_MAX_HOTWORD_MODEL_NAME_SIZE: u32 = 12;
-pub const MAX_DEBUG_DEVS: u32 = 4;
-pub const MAX_DEBUG_STREAMS: u32 = 8;
-pub const CRAS_BT_EVENT_LOG_SIZE: u32 = 1024;
-pub const CRAS_SERVER_STATE_VERSION: u32 = 2;
-pub const CRAS_PROTO_VER: u32 = 7;
-pub const CRAS_SERV_MAX_MSG_SIZE: u32 = 256;
-pub const CRAS_CLIENT_MAX_MSG_SIZE: u32 = 256;
-pub const CRAS_MAX_HOTWORD_MODELS: u32 = 243;
-pub const CRAS_MAX_REMIX_CHANNELS: u32 = 8;
-pub const CRAS_MAX_TEST_DATA_LEN: u32 = 224;
-pub const CRAS_AEC_DUMP_FILE_NAME_LEN: u32 = 128;
-pub const CRAS_NUM_SHM_BUFFERS: u32 = 2;
-pub const CRAS_SHM_BUFFERS_MASK: u32 = 1;
-pub type __int8_t = ::std::os::raw::c_schar;
-pub type __uint8_t = ::std::os::raw::c_uchar;
-pub type __int32_t = ::std::os::raw::c_int;
-pub type __uint32_t = ::std::os::raw::c_uint;
-pub type __int64_t = ::std::os::raw::c_long;
-pub type __uint64_t = ::std::os::raw::c_ulong;
-pub type __time_t = ::std::os::raw::c_long;
-pub type __syscall_slong_t = ::std::os::raw::c_long;
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_iodev_info {
- pub idx: u32,
- pub name: [::std::os::raw::c_char; 64usize],
- pub stable_id: u32,
- pub max_supported_channels: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_iodev_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_iodev_info>(),
- 76usize,
- concat!("Size of: ", stringify!(cras_iodev_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_iodev_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_iodev_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_iodev_info>())).idx as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_iodev_info),
- "::",
- stringify!(idx)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_iodev_info>())).name as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_iodev_info),
- "::",
- stringify!(name)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_iodev_info>())).stable_id as *const _ as usize },
- 68usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_iodev_info),
- "::",
- stringify!(stable_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_iodev_info>())).max_supported_channels as *const _ as usize
- },
- 72usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_iodev_info),
- "::",
- stringify!(max_supported_channels)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_ionode_info {
- pub iodev_idx: u32,
- pub ionode_idx: u32,
- pub plugged: i32,
- pub active: i32,
- pub plugged_time: cras_ionode_info__bindgen_ty_1,
- pub volume: u32,
- pub capture_gain: i32,
- pub ui_gain_scaler: f32,
- pub left_right_swapped: i32,
- pub type_enum: u32,
- pub stable_id: u32,
- pub type_: [::std::os::raw::c_char; 32usize],
- pub name: [::std::os::raw::c_char; 64usize],
- pub active_hotword_model: [::std::os::raw::c_char; 16usize],
-}
-#[repr(C)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_ionode_info__bindgen_ty_1 {
- pub tv_sec: i64,
- pub tv_usec: i64,
-}
-#[test]
-fn bindgen_test_layout_cras_ionode_info__bindgen_ty_1() {
- assert_eq!(
- ::std::mem::size_of::<cras_ionode_info__bindgen_ty_1>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_ionode_info__bindgen_ty_1))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_ionode_info__bindgen_ty_1>(),
- 8usize,
- concat!("Alignment of ", stringify!(cras_ionode_info__bindgen_ty_1))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_ionode_info__bindgen_ty_1>())).tv_sec as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info__bindgen_ty_1),
- "::",
- stringify!(tv_sec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_ionode_info__bindgen_ty_1>())).tv_usec as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info__bindgen_ty_1),
- "::",
- stringify!(tv_usec)
- )
- );
-}
-#[test]
-fn bindgen_test_layout_cras_ionode_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_ionode_info>(),
- 168usize,
- concat!("Size of: ", stringify!(cras_ionode_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_ionode_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_ionode_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).iodev_idx as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(iodev_idx)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).ionode_idx as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(ionode_idx)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).plugged as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(plugged)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).active as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(active)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).plugged_time as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(plugged_time)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).volume as *const _ as usize },
- 32usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(volume)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).capture_gain as *const _ as usize },
- 36usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(capture_gain)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).ui_gain_scaler as *const _ as usize },
- 40usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(ui_gain_scaler)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_ionode_info>())).left_right_swapped as *const _ as usize
- },
- 44usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(left_right_swapped)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).type_enum as *const _ as usize },
- 48usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(type_enum)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).stable_id as *const _ as usize },
- 52usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(stable_id)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).type_ as *const _ as usize },
- 56usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(type_)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_ionode_info>())).name as *const _ as usize },
- 88usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(name)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_ionode_info>())).active_hotword_model as *const _ as usize
- },
- 152usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_ionode_info),
- "::",
- stringify!(active_hotword_model)
- )
- );
-}
-pub const ionode_attr_IONODE_ATTR_PLUGGED: ionode_attr = 0;
-pub const ionode_attr_IONODE_ATTR_VOLUME: ionode_attr = 1;
-pub const ionode_attr_IONODE_ATTR_CAPTURE_GAIN: ionode_attr = 2;
-pub const ionode_attr_IONODE_ATTR_SWAP_LEFT_RIGHT: ionode_attr = 3;
-pub type ionode_attr = u32;
-#[repr(C)]
-#[derive(Debug, Copy, Clone)]
-pub struct timespec {
- pub tv_sec: __time_t,
- pub tv_nsec: __syscall_slong_t,
-}
-#[test]
-fn bindgen_test_layout_timespec() {
- assert_eq!(
- ::std::mem::size_of::<timespec>(),
- 16usize,
- concat!("Size of: ", stringify!(timespec))
- );
- assert_eq!(
- ::std::mem::align_of::<timespec>(),
- 8usize,
- concat!("Alignment of ", stringify!(timespec))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<timespec>())).tv_sec as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(timespec),
- "::",
- stringify!(tv_sec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<timespec>())).tv_nsec as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(timespec),
- "::",
- stringify!(tv_nsec)
- )
- );
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_LAST: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_DSD_U32_BE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_S16: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_S16_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_U16: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_U16_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_S24: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_S24_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_U24: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_U24_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_S32: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_S32_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_U32: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_U32_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_FLOAT: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_FLOAT_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_FLOAT64: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_FLOAT64_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_IEC958_SUBFRAME: _snd_pcm_format =
- _snd_pcm_format::SND_PCM_FORMAT_IEC958_SUBFRAME_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_S20: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_S20_LE;
-}
-impl _snd_pcm_format {
- pub const SND_PCM_FORMAT_U20: _snd_pcm_format = _snd_pcm_format::SND_PCM_FORMAT_U20_LE;
-}
-#[repr(i32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum _snd_pcm_format {
- SND_PCM_FORMAT_UNKNOWN = -1,
- SND_PCM_FORMAT_S8 = 0,
- SND_PCM_FORMAT_U8 = 1,
- SND_PCM_FORMAT_S16_LE = 2,
- SND_PCM_FORMAT_S16_BE = 3,
- SND_PCM_FORMAT_U16_LE = 4,
- SND_PCM_FORMAT_U16_BE = 5,
- SND_PCM_FORMAT_S24_LE = 6,
- SND_PCM_FORMAT_S24_BE = 7,
- SND_PCM_FORMAT_U24_LE = 8,
- SND_PCM_FORMAT_U24_BE = 9,
- SND_PCM_FORMAT_S32_LE = 10,
- SND_PCM_FORMAT_S32_BE = 11,
- SND_PCM_FORMAT_U32_LE = 12,
- SND_PCM_FORMAT_U32_BE = 13,
- SND_PCM_FORMAT_FLOAT_LE = 14,
- SND_PCM_FORMAT_FLOAT_BE = 15,
- SND_PCM_FORMAT_FLOAT64_LE = 16,
- SND_PCM_FORMAT_FLOAT64_BE = 17,
- SND_PCM_FORMAT_IEC958_SUBFRAME_LE = 18,
- SND_PCM_FORMAT_IEC958_SUBFRAME_BE = 19,
- SND_PCM_FORMAT_MU_LAW = 20,
- SND_PCM_FORMAT_A_LAW = 21,
- SND_PCM_FORMAT_IMA_ADPCM = 22,
- SND_PCM_FORMAT_MPEG = 23,
- SND_PCM_FORMAT_GSM = 24,
- SND_PCM_FORMAT_S20_LE = 25,
- SND_PCM_FORMAT_S20_BE = 26,
- SND_PCM_FORMAT_U20_LE = 27,
- SND_PCM_FORMAT_U20_BE = 28,
- SND_PCM_FORMAT_SPECIAL = 31,
- SND_PCM_FORMAT_S24_3LE = 32,
- SND_PCM_FORMAT_S24_3BE = 33,
- SND_PCM_FORMAT_U24_3LE = 34,
- SND_PCM_FORMAT_U24_3BE = 35,
- SND_PCM_FORMAT_S20_3LE = 36,
- SND_PCM_FORMAT_S20_3BE = 37,
- SND_PCM_FORMAT_U20_3LE = 38,
- SND_PCM_FORMAT_U20_3BE = 39,
- SND_PCM_FORMAT_S18_3LE = 40,
- SND_PCM_FORMAT_S18_3BE = 41,
- SND_PCM_FORMAT_U18_3LE = 42,
- SND_PCM_FORMAT_U18_3BE = 43,
- SND_PCM_FORMAT_G723_24 = 44,
- SND_PCM_FORMAT_G723_24_1B = 45,
- SND_PCM_FORMAT_G723_40 = 46,
- SND_PCM_FORMAT_G723_40_1B = 47,
- SND_PCM_FORMAT_DSD_U8 = 48,
- SND_PCM_FORMAT_DSD_U16_LE = 49,
- SND_PCM_FORMAT_DSD_U32_LE = 50,
- SND_PCM_FORMAT_DSD_U16_BE = 51,
- SND_PCM_FORMAT_DSD_U32_BE = 52,
-}
-pub use self::_snd_pcm_format as snd_pcm_format_t;
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_CHANNEL {
- CRAS_CH_FL = 0,
- CRAS_CH_FR = 1,
- CRAS_CH_RL = 2,
- CRAS_CH_RR = 3,
- CRAS_CH_FC = 4,
- CRAS_CH_LFE = 5,
- CRAS_CH_SL = 6,
- CRAS_CH_SR = 7,
- CRAS_CH_RC = 8,
- CRAS_CH_FLC = 9,
- CRAS_CH_FRC = 10,
- CRAS_CH_MAX = 11,
-}
-#[repr(C)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_audio_format {
- pub format: snd_pcm_format_t,
- pub frame_rate: usize,
- pub num_channels: usize,
- pub channel_layout: [i8; 11usize],
-}
-#[test]
-fn bindgen_test_layout_cras_audio_format() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_format>(),
- 40usize,
- concat!("Size of: ", stringify!(cras_audio_format))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_format>(),
- 8usize,
- concat!("Alignment of ", stringify!(cras_audio_format))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_format>())).format as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format),
- "::",
- stringify!(format)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_format>())).frame_rate as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format),
- "::",
- stringify!(frame_rate)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_format>())).num_channels as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format),
- "::",
- stringify!(num_channels)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_format>())).channel_layout as *const _ as usize
- },
- 24usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format),
- "::",
- stringify!(channel_layout)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_audio_format_packed {
- pub format: i32,
- pub frame_rate: u32,
- pub num_channels: u32,
- pub channel_layout: [i8; 11usize],
-}
-#[test]
-fn bindgen_test_layout_cras_audio_format_packed() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_format_packed>(),
- 23usize,
- concat!("Size of: ", stringify!(cras_audio_format_packed))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_format_packed>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_audio_format_packed))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_format_packed>())).format as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format_packed),
- "::",
- stringify!(format)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_format_packed>())).frame_rate as *const _ as usize
- },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format_packed),
- "::",
- stringify!(frame_rate)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_format_packed>())).num_channels as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format_packed),
- "::",
- stringify!(num_channels)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_format_packed>())).channel_layout as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_format_packed),
- "::",
- stringify!(channel_layout)
- )
- );
-}
-#[repr(C)]
-#[derive(Copy, Clone)]
-pub struct packet_status_logger {
- pub data: [u8; 64usize],
- pub size: ::std::os::raw::c_int,
- pub wp: ::std::os::raw::c_int,
- pub num_wraps: ::std::os::raw::c_int,
- pub ts: timespec,
-}
-#[test]
-fn bindgen_test_layout_packet_status_logger() {
- assert_eq!(
- ::std::mem::size_of::<packet_status_logger>(),
- 96usize,
- concat!("Size of: ", stringify!(packet_status_logger))
- );
- assert_eq!(
- ::std::mem::align_of::<packet_status_logger>(),
- 8usize,
- concat!("Alignment of ", stringify!(packet_status_logger))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<packet_status_logger>())).data as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(packet_status_logger),
- "::",
- stringify!(data)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<packet_status_logger>())).size as *const _ as usize },
- 64usize,
- concat!(
- "Offset of field: ",
- stringify!(packet_status_logger),
- "::",
- stringify!(size)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<packet_status_logger>())).wp as *const _ as usize },
- 68usize,
- concat!(
- "Offset of field: ",
- stringify!(packet_status_logger),
- "::",
- stringify!(wp)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<packet_status_logger>())).num_wraps as *const _ as usize },
- 72usize,
- concat!(
- "Offset of field: ",
- stringify!(packet_status_logger),
- "::",
- stringify!(num_wraps)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<packet_status_logger>())).ts as *const _ as usize },
- 80usize,
- concat!(
- "Offset of field: ",
- stringify!(packet_status_logger),
- "::",
- stringify!(ts)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_timespec {
- pub tv_sec: i64,
- pub tv_nsec: i64,
-}
-#[test]
-fn bindgen_test_layout_cras_timespec() {
- assert_eq!(
- ::std::mem::size_of::<cras_timespec>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_timespec))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_timespec>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_timespec))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_timespec>())).tv_sec as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_timespec),
- "::",
- stringify!(tv_sec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_timespec>())).tv_nsec as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_timespec),
- "::",
- stringify!(tv_nsec)
- )
- );
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_SPECIAL_DEVICE {
- NO_DEVICE = 0,
- SILENT_RECORD_DEVICE = 1,
- SILENT_PLAYBACK_DEVICE = 2,
- SILENT_HOTWORD_DEVICE = 3,
- MAX_SPECIAL_DEVICE_IDX = 4,
-}
-pub const TEST_IODEV_TYPE_TEST_IODEV_HOTWORD: TEST_IODEV_TYPE = 0;
-pub type TEST_IODEV_TYPE = u32;
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_TEST_IODEV_CMD {
- TEST_IODEV_CMD_HOTWORD_TRIGGER = 0,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_CONNECTION_TYPE {
- CRAS_CONTROL = 0,
- CRAS_PLAYBACK = 1,
- CRAS_CAPTURE = 2,
- CRAS_VMS_LEGACY = 3,
- CRAS_VMS_UNIFIED = 4,
- CRAS_PLUGIN_PLAYBACK = 5,
- CRAS_PLUGIN_UNIFIED = 6,
- CRAS_NUM_CONN_TYPE = 7,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_STREAM_DIRECTION {
- CRAS_STREAM_OUTPUT = 0,
- CRAS_STREAM_INPUT = 1,
- CRAS_STREAM_UNDEFINED = 2,
- CRAS_STREAM_POST_MIX_PRE_DSP = 3,
- CRAS_NUM_DIRECTIONS = 4,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_INPUT_STREAM_FLAG {
- BULK_AUDIO_OK = 1,
- USE_DEV_TIMING = 2,
- HOTWORD_STREAM = 3,
- TRIGGER_ONLY = 4,
- SERVER_ONLY = 8,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_LOOPBACK_TYPE {
- LOOPBACK_POST_MIX_PRE_DSP = 0,
- LOOPBACK_POST_DSP = 1,
- LOOPBACK_NUM_TYPES = 2,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_STREAM_TYPE {
- CRAS_STREAM_TYPE_DEFAULT = 0,
- CRAS_STREAM_TYPE_MULTIMEDIA = 1,
- CRAS_STREAM_TYPE_VOICE_COMMUNICATION = 2,
- CRAS_STREAM_TYPE_SPEECH_RECOGNITION = 3,
- CRAS_STREAM_TYPE_PRO_AUDIO = 4,
- CRAS_STREAM_TYPE_ACCESSIBILITY = 5,
- CRAS_STREAM_NUM_TYPES = 6,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_CLIENT_TYPE {
- CRAS_CLIENT_TYPE_UNKNOWN = 0,
- CRAS_CLIENT_TYPE_LEGACY = 1,
- CRAS_CLIENT_TYPE_TEST = 2,
- CRAS_CLIENT_TYPE_PCM = 3,
- CRAS_CLIENT_TYPE_CHROME = 4,
- CRAS_CLIENT_TYPE_ARC = 5,
- CRAS_CLIENT_TYPE_CROSVM = 6,
- CRAS_CLIENT_TYPE_SERVER_STREAM = 7,
- CRAS_CLIENT_TYPE_LACROS = 8,
- CRAS_CLIENT_TYPE_PLUGIN = 9,
- CRAS_CLIENT_TYPE_ARCVM = 10,
- CRAS_NUM_CLIENT_TYPE = 11,
-}
-impl CRAS_STREAM_EFFECT {
- pub const APM_ECHO_CANCELLATION: CRAS_STREAM_EFFECT = CRAS_STREAM_EFFECT(1);
-}
-impl CRAS_STREAM_EFFECT {
- pub const APM_NOISE_SUPRESSION: CRAS_STREAM_EFFECT = CRAS_STREAM_EFFECT(2);
-}
-impl CRAS_STREAM_EFFECT {
- pub const APM_GAIN_CONTROL: CRAS_STREAM_EFFECT = CRAS_STREAM_EFFECT(4);
-}
-impl CRAS_STREAM_EFFECT {
- pub const APM_VOICE_DETECTION: CRAS_STREAM_EFFECT = CRAS_STREAM_EFFECT(8);
-}
-impl ::std::ops::BitOr<CRAS_STREAM_EFFECT> for CRAS_STREAM_EFFECT {
- type Output = Self;
- #[inline]
- fn bitor(self, other: Self) -> Self {
- CRAS_STREAM_EFFECT(self.0 | other.0)
- }
-}
-impl ::std::ops::BitOrAssign for CRAS_STREAM_EFFECT {
- #[inline]
- fn bitor_assign(&mut self, rhs: CRAS_STREAM_EFFECT) {
- self.0 |= rhs.0;
- }
-}
-impl ::std::ops::BitAnd<CRAS_STREAM_EFFECT> for CRAS_STREAM_EFFECT {
- type Output = Self;
- #[inline]
- fn bitand(self, other: Self) -> Self {
- CRAS_STREAM_EFFECT(self.0 & other.0)
- }
-}
-impl ::std::ops::BitAndAssign for CRAS_STREAM_EFFECT {
- #[inline]
- fn bitand_assign(&mut self, rhs: CRAS_STREAM_EFFECT) {
- self.0 &= rhs.0;
- }
-}
-#[repr(C)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub struct CRAS_STREAM_EFFECT(pub u32);
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_attached_client_info {
- pub id: u32,
- pub pid: i32,
- pub uid: u32,
- pub gid: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_attached_client_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_attached_client_info>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_attached_client_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_attached_client_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_attached_client_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_attached_client_info>())).id as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_attached_client_info),
- "::",
- stringify!(id)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_attached_client_info>())).pid as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_attached_client_info),
- "::",
- stringify!(pid)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_attached_client_info>())).uid as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_attached_client_info),
- "::",
- stringify!(uid)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_attached_client_info>())).gid as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_attached_client_info),
- "::",
- stringify!(gid)
- )
- );
-}
-pub type cras_node_id_t = u64;
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_BT_LOG_EVENTS {
- BT_ADAPTER_ADDED = 0,
- BT_ADAPTER_REMOVED = 1,
- BT_AUDIO_GATEWAY_INIT = 2,
- BT_AUDIO_GATEWAY_START = 3,
- BT_AVAILABLE_CODECS = 4,
- BT_A2DP_CONFIGURED = 5,
- BT_A2DP_START = 6,
- BT_A2DP_SUSPENDED = 7,
- BT_CODEC_SELECTION = 8,
- BT_DEV_CONNECTED = 9,
- BT_DEV_DISCONNECTED = 10,
- BT_DEV_CONN_WATCH_CB = 11,
- BT_DEV_SUSPEND_CB = 12,
- BT_HFP_NEW_CONNECTION = 13,
- BT_HFP_REQUEST_DISCONNECT = 14,
- BT_HFP_SUPPORTED_FEATURES = 15,
- BT_HFP_HF_INDICATOR = 16,
- BT_HFP_SET_SPEAKER_GAIN = 17,
- BT_HFP_UPDATE_SPEAKER_GAIN = 18,
- BT_HSP_NEW_CONNECTION = 19,
- BT_HSP_REQUEST_DISCONNECT = 20,
- BT_NEW_AUDIO_PROFILE_AFTER_CONNECT = 21,
- BT_RESET = 22,
- BT_SCO_CONNECT = 23,
- BT_TRANSPORT_ACQUIRE = 24,
- BT_TRANSPORT_RELEASE = 25,
- BT_TRANSPORT_SET_VOLUME = 26,
- BT_TRANSPORT_UPDATE_VOLUME = 27,
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct audio_thread_event {
- pub tag_sec: u32,
- pub nsec: u32,
- pub data1: u32,
- pub data2: u32,
- pub data3: u32,
-}
-#[test]
-fn bindgen_test_layout_audio_thread_event() {
- assert_eq!(
- ::std::mem::size_of::<audio_thread_event>(),
- 20usize,
- concat!("Size of: ", stringify!(audio_thread_event))
- );
- assert_eq!(
- ::std::mem::align_of::<audio_thread_event>(),
- 1usize,
- concat!("Alignment of ", stringify!(audio_thread_event))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event>())).tag_sec as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event),
- "::",
- stringify!(tag_sec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event>())).nsec as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event),
- "::",
- stringify!(nsec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event>())).data1 as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event),
- "::",
- stringify!(data1)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event>())).data2 as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event),
- "::",
- stringify!(data2)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event>())).data3 as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event),
- "::",
- stringify!(data3)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct audio_thread_event_log {
- pub write_pos: u64,
- pub sync_write_pos: u64,
- pub len: u32,
- pub log: [audio_thread_event; 6144usize],
-}
-#[test]
-fn bindgen_test_layout_audio_thread_event_log() {
- assert_eq!(
- ::std::mem::size_of::<audio_thread_event_log>(),
- 122900usize,
- concat!("Size of: ", stringify!(audio_thread_event_log))
- );
- assert_eq!(
- ::std::mem::align_of::<audio_thread_event_log>(),
- 1usize,
- concat!("Alignment of ", stringify!(audio_thread_event_log))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_thread_event_log>())).write_pos as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event_log),
- "::",
- stringify!(write_pos)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_thread_event_log>())).sync_write_pos as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event_log),
- "::",
- stringify!(sync_write_pos)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event_log>())).len as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event_log),
- "::",
- stringify!(len)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_thread_event_log>())).log as *const _ as usize },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_thread_event_log),
- "::",
- stringify!(log)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct audio_dev_debug_info {
- pub dev_name: [::std::os::raw::c_char; 64usize],
- pub buffer_size: u32,
- pub min_buffer_level: u32,
- pub min_cb_level: u32,
- pub max_cb_level: u32,
- pub frame_rate: u32,
- pub num_channels: u32,
- pub est_rate_ratio: f64,
- pub direction: u8,
- pub num_underruns: u32,
- pub num_severe_underruns: u32,
- pub highest_hw_level: u32,
- pub runtime_sec: u32,
- pub runtime_nsec: u32,
- pub longest_wake_sec: u32,
- pub longest_wake_nsec: u32,
- pub software_gain_scaler: f64,
-}
-#[test]
-fn bindgen_test_layout_audio_dev_debug_info() {
- assert_eq!(
- ::std::mem::size_of::<audio_dev_debug_info>(),
- 133usize,
- concat!("Size of: ", stringify!(audio_dev_debug_info))
- );
- assert_eq!(
- ::std::mem::align_of::<audio_dev_debug_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(audio_dev_debug_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_dev_debug_info>())).dev_name as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(dev_name)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).buffer_size as *const _ as usize
- },
- 64usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(buffer_size)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).min_buffer_level as *const _ as usize
- },
- 68usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(min_buffer_level)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).min_cb_level as *const _ as usize
- },
- 72usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(min_cb_level)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).max_cb_level as *const _ as usize
- },
- 76usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(max_cb_level)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_dev_debug_info>())).frame_rate as *const _ as usize },
- 80usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(frame_rate)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).num_channels as *const _ as usize
- },
- 84usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(num_channels)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).est_rate_ratio as *const _ as usize
- },
- 88usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(est_rate_ratio)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_dev_debug_info>())).direction as *const _ as usize },
- 96usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).num_underruns as *const _ as usize
- },
- 97usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(num_underruns)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).num_severe_underruns as *const _
- as usize
- },
- 101usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(num_severe_underruns)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).highest_hw_level as *const _ as usize
- },
- 105usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(highest_hw_level)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).runtime_sec as *const _ as usize
- },
- 109usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(runtime_sec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).runtime_nsec as *const _ as usize
- },
- 113usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(runtime_nsec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).longest_wake_sec as *const _ as usize
- },
- 117usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(longest_wake_sec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).longest_wake_nsec as *const _ as usize
- },
- 121usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(longest_wake_nsec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_dev_debug_info>())).software_gain_scaler as *const _
- as usize
- },
- 125usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_dev_debug_info),
- "::",
- stringify!(software_gain_scaler)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct audio_stream_debug_info {
- pub stream_id: u64,
- pub dev_idx: u32,
- pub direction: u32,
- pub stream_type: u32,
- pub client_type: u32,
- pub buffer_frames: u32,
- pub cb_threshold: u32,
- pub effects: u64,
- pub flags: u32,
- pub frame_rate: u32,
- pub num_channels: u32,
- pub longest_fetch_sec: u32,
- pub longest_fetch_nsec: u32,
- pub num_missed_cb: u32,
- pub num_overruns: u32,
- pub is_pinned: u32,
- pub pinned_dev_idx: u32,
- pub runtime_sec: u32,
- pub runtime_nsec: u32,
- pub stream_volume: f64,
- pub channel_layout: [i8; 11usize],
-}
-#[test]
-fn bindgen_test_layout_audio_stream_debug_info() {
- assert_eq!(
- ::std::mem::size_of::<audio_stream_debug_info>(),
- 103usize,
- concat!("Size of: ", stringify!(audio_stream_debug_info))
- );
- assert_eq!(
- ::std::mem::align_of::<audio_stream_debug_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(audio_stream_debug_info))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).stream_id as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(stream_id)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_stream_debug_info>())).dev_idx as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(dev_idx)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).direction as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).stream_type as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(stream_type)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).client_type as *const _ as usize
- },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(client_type)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).buffer_frames as *const _ as usize
- },
- 24usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(buffer_frames)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).cb_threshold as *const _ as usize
- },
- 28usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(cb_threshold)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_stream_debug_info>())).effects as *const _ as usize },
- 32usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(effects)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_stream_debug_info>())).flags as *const _ as usize },
- 40usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(flags)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).frame_rate as *const _ as usize
- },
- 44usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(frame_rate)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).num_channels as *const _ as usize
- },
- 48usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(num_channels)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).longest_fetch_sec as *const _
- as usize
- },
- 52usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(longest_fetch_sec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).longest_fetch_nsec as *const _
- as usize
- },
- 56usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(longest_fetch_nsec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).num_missed_cb as *const _ as usize
- },
- 60usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(num_missed_cb)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).num_overruns as *const _ as usize
- },
- 64usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(num_overruns)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).is_pinned as *const _ as usize
- },
- 68usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(is_pinned)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).pinned_dev_idx as *const _ as usize
- },
- 72usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(pinned_dev_idx)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).runtime_sec as *const _ as usize
- },
- 76usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(runtime_sec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).runtime_nsec as *const _ as usize
- },
- 80usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(runtime_nsec)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).stream_volume as *const _ as usize
- },
- 84usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(stream_volume)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<audio_stream_debug_info>())).channel_layout as *const _ as usize
- },
- 92usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_stream_debug_info),
- "::",
- stringify!(channel_layout)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct audio_debug_info {
- pub num_streams: u32,
- pub num_devs: u32,
- pub devs: [audio_dev_debug_info; 4usize],
- pub streams: [audio_stream_debug_info; 8usize],
- pub log: audio_thread_event_log,
-}
-#[test]
-fn bindgen_test_layout_audio_debug_info() {
- assert_eq!(
- ::std::mem::size_of::<audio_debug_info>(),
- 124264usize,
- concat!("Size of: ", stringify!(audio_debug_info))
- );
- assert_eq!(
- ::std::mem::align_of::<audio_debug_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(audio_debug_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_debug_info>())).num_streams as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_debug_info),
- "::",
- stringify!(num_streams)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_debug_info>())).num_devs as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_debug_info),
- "::",
- stringify!(num_devs)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_debug_info>())).devs as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_debug_info),
- "::",
- stringify!(devs)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_debug_info>())).streams as *const _ as usize },
- 540usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_debug_info),
- "::",
- stringify!(streams)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_debug_info>())).log as *const _ as usize },
- 1364usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_debug_info),
- "::",
- stringify!(log)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct main_thread_event {
- pub tag_sec: u32,
- pub nsec: u32,
- pub data1: u32,
- pub data2: u32,
- pub data3: u32,
-}
-#[test]
-fn bindgen_test_layout_main_thread_event() {
- assert_eq!(
- ::std::mem::size_of::<main_thread_event>(),
- 20usize,
- concat!("Size of: ", stringify!(main_thread_event))
- );
- assert_eq!(
- ::std::mem::align_of::<main_thread_event>(),
- 1usize,
- concat!("Alignment of ", stringify!(main_thread_event))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event>())).tag_sec as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event),
- "::",
- stringify!(tag_sec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event>())).nsec as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event),
- "::",
- stringify!(nsec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event>())).data1 as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event),
- "::",
- stringify!(data1)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event>())).data2 as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event),
- "::",
- stringify!(data2)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event>())).data3 as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event),
- "::",
- stringify!(data3)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct main_thread_event_log {
- pub write_pos: u32,
- pub len: u32,
- pub log: [main_thread_event; 1024usize],
-}
-#[test]
-fn bindgen_test_layout_main_thread_event_log() {
- assert_eq!(
- ::std::mem::size_of::<main_thread_event_log>(),
- 20488usize,
- concat!("Size of: ", stringify!(main_thread_event_log))
- );
- assert_eq!(
- ::std::mem::align_of::<main_thread_event_log>(),
- 1usize,
- concat!("Alignment of ", stringify!(main_thread_event_log))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event_log>())).write_pos as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event_log),
- "::",
- stringify!(write_pos)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event_log>())).len as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event_log),
- "::",
- stringify!(len)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_event_log>())).log as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_event_log),
- "::",
- stringify!(log)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct main_thread_debug_info {
- pub main_log: main_thread_event_log,
-}
-#[test]
-fn bindgen_test_layout_main_thread_debug_info() {
- assert_eq!(
- ::std::mem::size_of::<main_thread_debug_info>(),
- 20488usize,
- concat!("Size of: ", stringify!(main_thread_debug_info))
- );
- assert_eq!(
- ::std::mem::align_of::<main_thread_debug_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(main_thread_debug_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<main_thread_debug_info>())).main_log as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(main_thread_debug_info),
- "::",
- stringify!(main_log)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_bt_event {
- pub tag_sec: u32,
- pub nsec: u32,
- pub data1: u32,
- pub data2: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_bt_event() {
- assert_eq!(
- ::std::mem::size_of::<cras_bt_event>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_bt_event))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_bt_event>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_bt_event))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event>())).tag_sec as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event),
- "::",
- stringify!(tag_sec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event>())).nsec as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event),
- "::",
- stringify!(nsec)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event>())).data1 as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event),
- "::",
- stringify!(data1)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event>())).data2 as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event),
- "::",
- stringify!(data2)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_bt_event_log {
- pub write_pos: u32,
- pub len: u32,
- pub log: [cras_bt_event; 1024usize],
-}
-#[test]
-fn bindgen_test_layout_cras_bt_event_log() {
- assert_eq!(
- ::std::mem::size_of::<cras_bt_event_log>(),
- 16392usize,
- concat!("Size of: ", stringify!(cras_bt_event_log))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_bt_event_log>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_bt_event_log))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event_log>())).write_pos as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event_log),
- "::",
- stringify!(write_pos)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event_log>())).len as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event_log),
- "::",
- stringify!(len)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_event_log>())).log as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_event_log),
- "::",
- stringify!(log)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_bt_debug_info {
- pub bt_log: cras_bt_event_log,
- pub wbs_logger: packet_status_logger,
-}
-#[test]
-fn bindgen_test_layout_cras_bt_debug_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_bt_debug_info>(),
- 16488usize,
- concat!("Size of: ", stringify!(cras_bt_debug_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_bt_debug_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_bt_debug_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_debug_info>())).bt_log as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_debug_info),
- "::",
- stringify!(bt_log)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_bt_debug_info>())).wbs_logger as *const _ as usize },
- 16392usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_bt_debug_info),
- "::",
- stringify!(wbs_logger)
- )
- );
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_AUDIO_THREAD_EVENT_TYPE {
- AUDIO_THREAD_EVENT_A2DP_OVERRUN = 0,
- AUDIO_THREAD_EVENT_A2DP_THROTTLE = 1,
- AUDIO_THREAD_EVENT_BUSYLOOP = 2,
- AUDIO_THREAD_EVENT_DEBUG = 3,
- AUDIO_THREAD_EVENT_SEVERE_UNDERRUN = 4,
- AUDIO_THREAD_EVENT_UNDERRUN = 5,
- AUDIO_THREAD_EVENT_DROP_SAMPLES = 6,
- AUDIO_THREAD_EVENT_DEV_OVERRUN = 7,
- AUDIO_THREAD_EVENT_TYPE_COUNT = 8,
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_audio_thread_snapshot {
- pub timestamp: timespec,
- pub event_type: CRAS_AUDIO_THREAD_EVENT_TYPE,
- pub audio_debug_info: audio_debug_info,
-}
-#[test]
-fn bindgen_test_layout_cras_audio_thread_snapshot() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_thread_snapshot>(),
- 124284usize,
- concat!("Size of: ", stringify!(cras_audio_thread_snapshot))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_thread_snapshot>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_audio_thread_snapshot))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_thread_snapshot>())).timestamp as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_thread_snapshot),
- "::",
- stringify!(timestamp)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_thread_snapshot>())).event_type as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_thread_snapshot),
- "::",
- stringify!(event_type)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_thread_snapshot>())).audio_debug_info as *const _
- as usize
- },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_thread_snapshot),
- "::",
- stringify!(audio_debug_info)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_audio_thread_snapshot_buffer {
- pub snapshots: [cras_audio_thread_snapshot; 10usize],
- pub pos: ::std::os::raw::c_int,
-}
-#[test]
-fn bindgen_test_layout_cras_audio_thread_snapshot_buffer() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_thread_snapshot_buffer>(),
- 1242844usize,
- concat!("Size of: ", stringify!(cras_audio_thread_snapshot_buffer))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_thread_snapshot_buffer>(),
- 1usize,
- concat!(
- "Alignment of ",
- stringify!(cras_audio_thread_snapshot_buffer)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_thread_snapshot_buffer>())).snapshots as *const _
- as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_thread_snapshot_buffer),
- "::",
- stringify!(snapshots)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_thread_snapshot_buffer>())).pos as *const _ as usize
- },
- 1242840usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_thread_snapshot_buffer),
- "::",
- stringify!(pos)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_server_state {
- pub state_version: u32,
- pub volume: u32,
- pub min_volume_dBFS: i32,
- pub max_volume_dBFS: i32,
- pub mute: i32,
- pub user_mute: i32,
- pub mute_locked: i32,
- pub suspended: i32,
- pub capture_gain: i32,
- pub capture_mute: i32,
- pub capture_mute_locked: i32,
- pub num_streams_attached: u32,
- pub num_output_devs: u32,
- pub num_input_devs: u32,
- pub output_devs: [cras_iodev_info; 20usize],
- pub input_devs: [cras_iodev_info; 20usize],
- pub num_output_nodes: u32,
- pub num_input_nodes: u32,
- pub output_nodes: [cras_ionode_info; 20usize],
- pub input_nodes: [cras_ionode_info; 20usize],
- pub num_attached_clients: u32,
- pub client_info: [cras_attached_client_info; 20usize],
- pub update_count: u32,
- pub num_active_streams: [u32; 4usize],
- pub last_active_stream_time: cras_timespec,
- pub audio_debug_info: audio_debug_info,
- pub default_output_buffer_size: i32,
- pub non_empty_status: i32,
- pub aec_supported: i32,
- pub aec_group_id: i32,
- pub snapshot_buffer: cras_audio_thread_snapshot_buffer,
- pub bt_debug_info: cras_bt_debug_info,
- pub bt_wbs_enabled: i32,
- pub deprioritize_bt_wbs_mic: i32,
- pub main_thread_debug_info: main_thread_debug_info,
- pub num_input_streams_with_permission: [u32; 11usize],
- pub noise_cancellation_enabled: i32,
- pub hotword_pause_at_suspend: i32,
-}
-#[test]
-fn bindgen_test_layout_cras_server_state() {
- assert_eq!(
- ::std::mem::size_of::<cras_server_state>(),
- 1414344usize,
- concat!("Size of: ", stringify!(cras_server_state))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_server_state>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_server_state))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).state_version as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(state_version)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).volume as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(volume)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).min_volume_dBFS as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(min_volume_dBFS)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).max_volume_dBFS as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(max_volume_dBFS)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).mute as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(mute)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).user_mute as *const _ as usize },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(user_mute)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).mute_locked as *const _ as usize },
- 24usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(mute_locked)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).suspended as *const _ as usize },
- 28usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(suspended)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).capture_gain as *const _ as usize },
- 32usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(capture_gain)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).capture_mute as *const _ as usize },
- 36usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(capture_mute)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).capture_mute_locked as *const _ as usize
- },
- 40usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(capture_mute_locked)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_streams_attached as *const _ as usize
- },
- 44usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_streams_attached)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_output_devs as *const _ as usize
- },
- 48usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_output_devs)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_input_devs as *const _ as usize
- },
- 52usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_input_devs)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).output_devs as *const _ as usize },
- 56usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(output_devs)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).input_devs as *const _ as usize },
- 1576usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(input_devs)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_output_nodes as *const _ as usize
- },
- 3096usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_output_nodes)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_input_nodes as *const _ as usize
- },
- 3100usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_input_nodes)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).output_nodes as *const _ as usize },
- 3104usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(output_nodes)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).input_nodes as *const _ as usize },
- 6464usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(input_nodes)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_attached_clients as *const _ as usize
- },
- 9824usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_attached_clients)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).client_info as *const _ as usize },
- 9828usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(client_info)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).update_count as *const _ as usize },
- 10148usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(update_count)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_active_streams as *const _ as usize
- },
- 10152usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_active_streams)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).last_active_stream_time as *const _
- as usize
- },
- 10168usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(last_active_stream_time)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).audio_debug_info as *const _ as usize
- },
- 10184usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(audio_debug_info)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).default_output_buffer_size as *const _
- as usize
- },
- 134448usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(default_output_buffer_size)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).non_empty_status as *const _ as usize
- },
- 134452usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(non_empty_status)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).aec_supported as *const _ as usize },
- 134456usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(aec_supported)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).aec_group_id as *const _ as usize },
- 134460usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(aec_group_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).snapshot_buffer as *const _ as usize
- },
- 134464usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(snapshot_buffer)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_state>())).bt_debug_info as *const _ as usize },
- 1377308usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(bt_debug_info)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).bt_wbs_enabled as *const _ as usize
- },
- 1393796usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(bt_wbs_enabled)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).deprioritize_bt_wbs_mic as *const _
- as usize
- },
- 1393800usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(deprioritize_bt_wbs_mic)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).main_thread_debug_info as *const _
- as usize
- },
- 1393804usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(main_thread_debug_info)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).num_input_streams_with_permission
- as *const _ as usize
- },
- 1414292usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(num_input_streams_with_permission)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).noise_cancellation_enabled as *const _
- as usize
- },
- 1414336usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(noise_cancellation_enabled)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_server_state>())).hotword_pause_at_suspend as *const _
- as usize
- },
- 1414340usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_state),
- "::",
- stringify!(hotword_pause_at_suspend)
- )
- );
-}
-pub const cras_notify_device_action_CRAS_DEVICE_ACTION_ADD: cras_notify_device_action = 0;
-pub const cras_notify_device_action_CRAS_DEVICE_ACTION_REMOVE: cras_notify_device_action = 1;
-pub const cras_notify_device_action_CRAS_DEVICE_ACTION_CHANGE: cras_notify_device_action = 2;
-pub type cras_notify_device_action = u32;
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_ALSA_CARD_TYPE {
- ALSA_CARD_TYPE_INTERNAL = 0,
- ALSA_CARD_TYPE_USB = 1,
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_alsa_card_info {
- pub card_type: CRAS_ALSA_CARD_TYPE,
- pub card_index: u32,
- pub usb_vendor_id: u32,
- pub usb_product_id: u32,
- pub usb_serial_number: [::std::os::raw::c_char; 64usize],
- pub usb_desc_checksum: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_alsa_card_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_alsa_card_info>(),
- 84usize,
- concat!("Size of: ", stringify!(cras_alsa_card_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_alsa_card_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_alsa_card_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_alsa_card_info>())).card_type as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_alsa_card_info),
- "::",
- stringify!(card_type)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_alsa_card_info>())).card_index as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_alsa_card_info),
- "::",
- stringify!(card_index)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_alsa_card_info>())).usb_vendor_id as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_alsa_card_info),
- "::",
- stringify!(usb_vendor_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_alsa_card_info>())).usb_product_id as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_alsa_card_info),
- "::",
- stringify!(usb_product_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_alsa_card_info>())).usb_serial_number as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_alsa_card_info),
- "::",
- stringify!(usb_serial_number)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_alsa_card_info>())).usb_desc_checksum as *const _ as usize
- },
- 80usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_alsa_card_info),
- "::",
- stringify!(usb_desc_checksum)
- )
- );
-}
-pub type cras_stream_id_t = u32;
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_NODE_TYPE {
- CRAS_NODE_TYPE_INTERNAL_SPEAKER = 0,
- CRAS_NODE_TYPE_HEADPHONE = 1,
- CRAS_NODE_TYPE_HDMI = 2,
- CRAS_NODE_TYPE_HAPTIC = 3,
- CRAS_NODE_TYPE_LINEOUT = 4,
- CRAS_NODE_TYPE_MIC = 5,
- CRAS_NODE_TYPE_HOTWORD = 6,
- CRAS_NODE_TYPE_POST_MIX_PRE_DSP = 7,
- CRAS_NODE_TYPE_POST_DSP = 8,
- CRAS_NODE_TYPE_BLUETOOTH_NB_MIC = 9,
- CRAS_NODE_TYPE_USB = 10,
- CRAS_NODE_TYPE_BLUETOOTH = 11,
- CRAS_NODE_TYPE_FALLBACK_NORMAL = 12,
- CRAS_NODE_TYPE_FALLBACK_ABNORMAL = 13,
- CRAS_NODE_TYPE_UNKNOWN = 14,
- CRAS_NODE_TYPE_ECHO_REFERENCE = 15,
- CRAS_NODE_TYPE_ALSA_LOOPBACK = 16,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_NODE_POSITION {
- NODE_POSITION_EXTERNAL = 0,
- NODE_POSITION_INTERNAL = 1,
- NODE_POSITION_FRONT = 2,
- NODE_POSITION_REAR = 3,
- NODE_POSITION_KEYBOARD = 4,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_SERVER_MESSAGE_ID {
- CRAS_SERVER_CONNECT_STREAM = 0,
- CRAS_SERVER_DISCONNECT_STREAM = 1,
- CRAS_SERVER_SWITCH_STREAM_TYPE_IODEV = 2,
- CRAS_SERVER_SET_SYSTEM_VOLUME = 3,
- CRAS_SERVER_SET_SYSTEM_MUTE = 4,
- CRAS_SERVER_SET_USER_MUTE = 5,
- CRAS_SERVER_SET_SYSTEM_MUTE_LOCKED = 6,
- CRAS_SERVER_SET_SYSTEM_CAPTURE_GAIN = 7,
- CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE = 8,
- CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE_LOCKED = 9,
- CRAS_SERVER_SET_NODE_ATTR = 10,
- CRAS_SERVER_SELECT_NODE = 11,
- CRAS_SERVER_RELOAD_DSP = 12,
- CRAS_SERVER_DUMP_DSP_INFO = 13,
- CRAS_SERVER_DUMP_AUDIO_THREAD = 14,
- CRAS_SERVER_DUMP_SNAPSHOTS = 15,
- CRAS_SERVER_ADD_ACTIVE_NODE = 16,
- CRAS_SERVER_RM_ACTIVE_NODE = 17,
- CRAS_SERVER_ADD_TEST_DEV = 18,
- CRAS_SERVER_TEST_DEV_COMMAND = 19,
- CRAS_SERVER_SUSPEND = 20,
- CRAS_SERVER_RESUME = 21,
- CRAS_CONFIG_GLOBAL_REMIX = 22,
- CRAS_SERVER_GET_HOTWORD_MODELS = 23,
- CRAS_SERVER_SET_HOTWORD_MODEL = 24,
- CRAS_SERVER_REGISTER_NOTIFICATION = 25,
- CRAS_SERVER_SET_AEC_DUMP = 26,
- CRAS_SERVER_RELOAD_AEC_CONFIG = 27,
- CRAS_SERVER_DUMP_BT = 28,
- CRAS_SERVER_SET_BT_WBS_ENABLED = 29,
- CRAS_SERVER_GET_ATLOG_FD = 30,
- CRAS_SERVER_DUMP_MAIN = 31,
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_CLIENT_MESSAGE_ID {
- CRAS_CLIENT_CONNECTED = 0,
- CRAS_CLIENT_STREAM_CONNECTED = 1,
- CRAS_CLIENT_AUDIO_DEBUG_INFO_READY = 2,
- CRAS_CLIENT_GET_HOTWORD_MODELS_READY = 3,
- CRAS_CLIENT_OUTPUT_VOLUME_CHANGED = 4,
- CRAS_CLIENT_OUTPUT_MUTE_CHANGED = 5,
- CRAS_CLIENT_CAPTURE_GAIN_CHANGED = 6,
- CRAS_CLIENT_CAPTURE_MUTE_CHANGED = 7,
- CRAS_CLIENT_NODES_CHANGED = 8,
- CRAS_CLIENT_ACTIVE_NODE_CHANGED = 9,
- CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED = 10,
- CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED = 11,
- CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED = 12,
- CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED = 13,
- CRAS_CLIENT_ATLOG_FD_READY = 14,
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_server_message {
- pub length: u32,
- pub id: CRAS_SERVER_MESSAGE_ID,
-}
-#[test]
-fn bindgen_test_layout_cras_server_message() {
- assert_eq!(
- ::std::mem::size_of::<cras_server_message>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_server_message))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_server_message>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_server_message))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_message>())).length as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_message),
- "::",
- stringify!(length)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_server_message>())).id as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_server_message),
- "::",
- stringify!(id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_message {
- pub length: u32,
- pub id: CRAS_CLIENT_MESSAGE_ID,
-}
-#[test]
-fn bindgen_test_layout_cras_client_message() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_message>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_client_message))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_message>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_message))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_client_message>())).length as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_message),
- "::",
- stringify!(length)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_client_message>())).id as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_message),
- "::",
- stringify!(id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_connect_message {
- pub header: cras_server_message,
- pub proto_version: u32,
- pub direction: CRAS_STREAM_DIRECTION,
- pub stream_id: cras_stream_id_t,
- pub stream_type: CRAS_STREAM_TYPE,
- pub buffer_frames: u32,
- pub cb_threshold: u32,
- pub flags: u32,
- pub format: cras_audio_format_packed,
- pub dev_idx: u32,
- pub effects: u64,
- pub client_type: CRAS_CLIENT_TYPE,
- pub client_shm_size: u64,
- pub buffer_offsets: [u64; 2usize],
-}
-#[test]
-fn bindgen_test_layout_cras_connect_message() {
- assert_eq!(
- ::std::mem::size_of::<cras_connect_message>(),
- 99usize,
- concat!("Size of: ", stringify!(cras_connect_message))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_connect_message>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_connect_message))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).proto_version as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(proto_version)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).direction as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).stream_id as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(stream_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).stream_type as *const _ as usize
- },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(stream_type)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).buffer_frames as *const _ as usize
- },
- 24usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(buffer_frames)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).cb_threshold as *const _ as usize
- },
- 28usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(cb_threshold)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).flags as *const _ as usize },
- 32usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(flags)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).format as *const _ as usize },
- 36usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(format)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).dev_idx as *const _ as usize },
- 59usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(dev_idx)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_connect_message>())).effects as *const _ as usize },
- 63usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(effects)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).client_type as *const _ as usize
- },
- 71usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(client_type)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).client_shm_size as *const _ as usize
- },
- 75usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(client_shm_size)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_connect_message>())).buffer_offsets as *const _ as usize
- },
- 83usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_connect_message),
- "::",
- stringify!(buffer_offsets)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_disconnect_stream_message {
- pub header: cras_server_message,
- pub stream_id: cras_stream_id_t,
-}
-#[test]
-fn bindgen_test_layout_cras_disconnect_stream_message() {
- assert_eq!(
- ::std::mem::size_of::<cras_disconnect_stream_message>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_disconnect_stream_message))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_disconnect_stream_message>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_disconnect_stream_message))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_disconnect_stream_message>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_disconnect_stream_message),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_disconnect_stream_message>())).stream_id as *const _
- as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_disconnect_stream_message),
- "::",
- stringify!(stream_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_switch_stream_type_iodev {
- pub header: cras_server_message,
- pub stream_type: CRAS_STREAM_TYPE,
- pub iodev_idx: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_switch_stream_type_iodev() {
- assert_eq!(
- ::std::mem::size_of::<cras_switch_stream_type_iodev>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_switch_stream_type_iodev))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_switch_stream_type_iodev>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_switch_stream_type_iodev))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_switch_stream_type_iodev>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_switch_stream_type_iodev),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_switch_stream_type_iodev>())).stream_type as *const _
- as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_switch_stream_type_iodev),
- "::",
- stringify!(stream_type)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_switch_stream_type_iodev>())).iodev_idx as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_switch_stream_type_iodev),
- "::",
- stringify!(iodev_idx)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_set_system_volume {
- pub header: cras_server_message,
- pub volume: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_set_system_volume() {
- assert_eq!(
- ::std::mem::size_of::<cras_set_system_volume>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_set_system_volume))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_set_system_volume>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_set_system_volume))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_system_volume>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_system_volume),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_system_volume>())).volume as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_system_volume),
- "::",
- stringify!(volume)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_set_system_mute {
- pub header: cras_server_message,
- pub mute: i32,
-}
-#[test]
-fn bindgen_test_layout_cras_set_system_mute() {
- assert_eq!(
- ::std::mem::size_of::<cras_set_system_mute>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_set_system_mute))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_set_system_mute>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_set_system_mute))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_system_mute>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_system_mute),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_system_mute>())).mute as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_system_mute),
- "::",
- stringify!(mute)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_set_node_attr {
- pub header: cras_server_message,
- pub node_id: cras_node_id_t,
- pub attr: ionode_attr,
- pub value: i32,
-}
-#[test]
-fn bindgen_test_layout_cras_set_node_attr() {
- assert_eq!(
- ::std::mem::size_of::<cras_set_node_attr>(),
- 24usize,
- concat!("Size of: ", stringify!(cras_set_node_attr))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_set_node_attr>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_set_node_attr))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_node_attr>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_node_attr),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_node_attr>())).node_id as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_node_attr),
- "::",
- stringify!(node_id)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_node_attr>())).attr as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_node_attr),
- "::",
- stringify!(attr)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_node_attr>())).value as *const _ as usize },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_node_attr),
- "::",
- stringify!(value)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_select_node {
- pub header: cras_server_message,
- pub direction: CRAS_STREAM_DIRECTION,
- pub node_id: cras_node_id_t,
-}
-#[test]
-fn bindgen_test_layout_cras_select_node() {
- assert_eq!(
- ::std::mem::size_of::<cras_select_node>(),
- 20usize,
- concat!("Size of: ", stringify!(cras_select_node))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_select_node>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_select_node))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_select_node>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_select_node),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_select_node>())).direction as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_select_node),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_select_node>())).node_id as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_select_node),
- "::",
- stringify!(node_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_add_active_node {
- pub header: cras_server_message,
- pub direction: CRAS_STREAM_DIRECTION,
- pub node_id: cras_node_id_t,
-}
-#[test]
-fn bindgen_test_layout_cras_add_active_node() {
- assert_eq!(
- ::std::mem::size_of::<cras_add_active_node>(),
- 20usize,
- concat!("Size of: ", stringify!(cras_add_active_node))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_add_active_node>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_add_active_node))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_add_active_node>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_add_active_node),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_add_active_node>())).direction as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_add_active_node),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_add_active_node>())).node_id as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_add_active_node),
- "::",
- stringify!(node_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_rm_active_node {
- pub header: cras_server_message,
- pub direction: CRAS_STREAM_DIRECTION,
- pub node_id: cras_node_id_t,
-}
-#[test]
-fn bindgen_test_layout_cras_rm_active_node() {
- assert_eq!(
- ::std::mem::size_of::<cras_rm_active_node>(),
- 20usize,
- concat!("Size of: ", stringify!(cras_rm_active_node))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_rm_active_node>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_rm_active_node))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_rm_active_node>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_rm_active_node),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_rm_active_node>())).direction as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_rm_active_node),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_rm_active_node>())).node_id as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_rm_active_node),
- "::",
- stringify!(node_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_reload_dsp {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_reload_dsp() {
- assert_eq!(
- ::std::mem::size_of::<cras_reload_dsp>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_reload_dsp))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_reload_dsp>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_reload_dsp))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_reload_dsp>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_reload_dsp),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_dump_dsp_info {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_dump_dsp_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_dump_dsp_info>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_dump_dsp_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_dump_dsp_info>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_dump_dsp_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_dump_dsp_info>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_dump_dsp_info),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_dump_audio_thread {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_dump_audio_thread() {
- assert_eq!(
- ::std::mem::size_of::<cras_dump_audio_thread>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_dump_audio_thread))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_dump_audio_thread>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_dump_audio_thread))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_dump_audio_thread>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_dump_audio_thread),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_get_atlog_fd {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_get_atlog_fd() {
- assert_eq!(
- ::std::mem::size_of::<cras_get_atlog_fd>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_get_atlog_fd))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_get_atlog_fd>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_get_atlog_fd))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_get_atlog_fd>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_get_atlog_fd),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_dump_main {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_dump_main() {
- assert_eq!(
- ::std::mem::size_of::<cras_dump_main>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_dump_main))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_dump_main>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_dump_main))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_dump_main>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_dump_main),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_dump_bt {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_dump_bt() {
- assert_eq!(
- ::std::mem::size_of::<cras_dump_bt>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_dump_bt))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_dump_bt>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_dump_bt))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_dump_bt>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_dump_bt),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_dump_snapshots {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_dump_snapshots() {
- assert_eq!(
- ::std::mem::size_of::<cras_dump_snapshots>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_dump_snapshots))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_dump_snapshots>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_dump_snapshots))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_dump_snapshots>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_dump_snapshots),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_add_test_dev {
- pub header: cras_server_message,
- pub type_: TEST_IODEV_TYPE,
-}
-#[test]
-fn bindgen_test_layout_cras_add_test_dev() {
- assert_eq!(
- ::std::mem::size_of::<cras_add_test_dev>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_add_test_dev))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_add_test_dev>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_add_test_dev))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_add_test_dev>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_add_test_dev),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_add_test_dev>())).type_ as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_add_test_dev),
- "::",
- stringify!(type_)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_test_dev_command {
- pub header: cras_server_message,
- pub command: ::std::os::raw::c_uint,
- pub iodev_idx: ::std::os::raw::c_uint,
- pub data_len: ::std::os::raw::c_uint,
- pub data: [u8; 224usize],
-}
-#[test]
-fn bindgen_test_layout_cras_test_dev_command() {
- assert_eq!(
- ::std::mem::size_of::<cras_test_dev_command>(),
- 244usize,
- concat!("Size of: ", stringify!(cras_test_dev_command))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_test_dev_command>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_test_dev_command))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_test_dev_command>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_test_dev_command),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_test_dev_command>())).command as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_test_dev_command),
- "::",
- stringify!(command)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_test_dev_command>())).iodev_idx as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_test_dev_command),
- "::",
- stringify!(iodev_idx)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_test_dev_command>())).data_len as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_test_dev_command),
- "::",
- stringify!(data_len)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_test_dev_command>())).data as *const _ as usize },
- 20usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_test_dev_command),
- "::",
- stringify!(data)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_config_global_remix {
- pub header: cras_server_message,
- pub num_channels: ::std::os::raw::c_uint,
- pub coefficient: [f32; 64usize],
-}
-#[test]
-fn bindgen_test_layout_cras_config_global_remix() {
- assert_eq!(
- ::std::mem::size_of::<cras_config_global_remix>(),
- 268usize,
- concat!("Size of: ", stringify!(cras_config_global_remix))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_config_global_remix>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_config_global_remix))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_config_global_remix>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_config_global_remix),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_config_global_remix>())).num_channels as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_config_global_remix),
- "::",
- stringify!(num_channels)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_config_global_remix>())).coefficient as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_config_global_remix),
- "::",
- stringify!(coefficient)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_get_hotword_models {
- pub header: cras_server_message,
- pub node_id: cras_node_id_t,
-}
-#[test]
-fn bindgen_test_layout_cras_get_hotword_models() {
- assert_eq!(
- ::std::mem::size_of::<cras_get_hotword_models>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_get_hotword_models))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_get_hotword_models>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_get_hotword_models))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_get_hotword_models>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_get_hotword_models),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_get_hotword_models>())).node_id as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_get_hotword_models),
- "::",
- stringify!(node_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_set_hotword_model {
- pub header: cras_server_message,
- pub node_id: cras_node_id_t,
- pub model_name: [::std::os::raw::c_char; 12usize],
-}
-#[test]
-fn bindgen_test_layout_cras_set_hotword_model() {
- assert_eq!(
- ::std::mem::size_of::<cras_set_hotword_model>(),
- 28usize,
- concat!("Size of: ", stringify!(cras_set_hotword_model))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_set_hotword_model>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_set_hotword_model))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_hotword_model>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_hotword_model),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_hotword_model>())).node_id as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_hotword_model),
- "::",
- stringify!(node_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_set_hotword_model>())).model_name as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_hotword_model),
- "::",
- stringify!(model_name)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_set_aec_dump {
- pub header: cras_server_message,
- pub stream_id: cras_stream_id_t,
- pub start: ::std::os::raw::c_uint,
-}
-#[test]
-fn bindgen_test_layout_cras_set_aec_dump() {
- assert_eq!(
- ::std::mem::size_of::<cras_set_aec_dump>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_set_aec_dump))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_set_aec_dump>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_set_aec_dump))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_aec_dump>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_aec_dump),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_aec_dump>())).stream_id as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_aec_dump),
- "::",
- stringify!(stream_id)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_aec_dump>())).start as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_aec_dump),
- "::",
- stringify!(start)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_reload_aec_config {
- pub header: cras_server_message,
-}
-#[test]
-fn bindgen_test_layout_cras_reload_aec_config() {
- assert_eq!(
- ::std::mem::size_of::<cras_reload_aec_config>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_reload_aec_config))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_reload_aec_config>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_reload_aec_config))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_reload_aec_config>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_reload_aec_config),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_set_bt_wbs_enabled {
- pub header: cras_server_message,
- pub enabled: ::std::os::raw::c_uint,
-}
-#[test]
-fn bindgen_test_layout_cras_set_bt_wbs_enabled() {
- assert_eq!(
- ::std::mem::size_of::<cras_set_bt_wbs_enabled>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_set_bt_wbs_enabled))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_set_bt_wbs_enabled>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_set_bt_wbs_enabled))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_bt_wbs_enabled>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_bt_wbs_enabled),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_set_bt_wbs_enabled>())).enabled as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_set_bt_wbs_enabled),
- "::",
- stringify!(enabled)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_register_notification {
- pub header: cras_server_message,
- pub msg_id: u32,
- pub do_register: ::std::os::raw::c_int,
-}
-#[test]
-fn bindgen_test_layout_cras_register_notification() {
- assert_eq!(
- ::std::mem::size_of::<cras_register_notification>(),
- 16usize,
- concat!("Size of: ", stringify!(cras_register_notification))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_register_notification>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_register_notification))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_register_notification>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_register_notification),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_register_notification>())).msg_id as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_register_notification),
- "::",
- stringify!(msg_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_register_notification>())).do_register as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_register_notification),
- "::",
- stringify!(do_register)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_connected {
- pub header: cras_client_message,
- pub client_id: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_client_connected() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_connected>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_client_connected))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_connected>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_connected))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_client_connected>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_connected),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_client_connected>())).client_id as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_connected),
- "::",
- stringify!(client_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_stream_connected {
- pub header: cras_client_message,
- pub err: i32,
- pub stream_id: cras_stream_id_t,
- pub format: cras_audio_format_packed,
- pub samples_shm_size: u32,
- pub effects: u64,
-}
-#[test]
-fn bindgen_test_layout_cras_client_stream_connected() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_stream_connected>(),
- 51usize,
- concat!("Size of: ", stringify!(cras_client_stream_connected))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_stream_connected>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_stream_connected))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_stream_connected>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_stream_connected),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_stream_connected>())).err as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_stream_connected),
- "::",
- stringify!(err)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_stream_connected>())).stream_id as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_stream_connected),
- "::",
- stringify!(stream_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_stream_connected>())).format as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_stream_connected),
- "::",
- stringify!(format)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_stream_connected>())).samples_shm_size as *const _
- as usize
- },
- 39usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_stream_connected),
- "::",
- stringify!(samples_shm_size)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_stream_connected>())).effects as *const _ as usize
- },
- 43usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_stream_connected),
- "::",
- stringify!(effects)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_audio_debug_info_ready {
- pub header: cras_client_message,
-}
-#[test]
-fn bindgen_test_layout_cras_client_audio_debug_info_ready() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_audio_debug_info_ready>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_client_audio_debug_info_ready))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_audio_debug_info_ready>(),
- 1usize,
- concat!(
- "Alignment of ",
- stringify!(cras_client_audio_debug_info_ready)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_audio_debug_info_ready>())).header as *const _
- as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_audio_debug_info_ready),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_atlog_fd_ready {
- pub header: cras_client_message,
-}
-#[test]
-fn bindgen_test_layout_cras_client_atlog_fd_ready() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_atlog_fd_ready>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_client_atlog_fd_ready))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_atlog_fd_ready>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_atlog_fd_ready))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_atlog_fd_ready>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_atlog_fd_ready),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Copy, Clone)]
-pub struct cras_client_get_hotword_models_ready {
- pub header: cras_client_message,
- pub hotword_models_size: i32,
- pub hotword_models: [u8; 244usize],
-}
-#[test]
-fn bindgen_test_layout_cras_client_get_hotword_models_ready() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_get_hotword_models_ready>(),
- 256usize,
- concat!(
- "Size of: ",
- stringify!(cras_client_get_hotword_models_ready)
- )
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_get_hotword_models_ready>(),
- 1usize,
- concat!(
- "Alignment of ",
- stringify!(cras_client_get_hotword_models_ready)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_get_hotword_models_ready>())).header as *const _
- as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_get_hotword_models_ready),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_get_hotword_models_ready>())).hotword_models_size
- as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_get_hotword_models_ready),
- "::",
- stringify!(hotword_models_size)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_get_hotword_models_ready>())).hotword_models
- as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_get_hotword_models_ready),
- "::",
- stringify!(hotword_models)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_volume_changed {
- pub header: cras_client_message,
- pub volume: i32,
-}
-#[test]
-fn bindgen_test_layout_cras_client_volume_changed() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_volume_changed>(),
- 12usize,
- concat!("Size of: ", stringify!(cras_client_volume_changed))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_volume_changed>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_volume_changed))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_volume_changed>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_volume_changed),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_volume_changed>())).volume as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_volume_changed),
- "::",
- stringify!(volume)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_mute_changed {
- pub header: cras_client_message,
- pub muted: i32,
- pub user_muted: i32,
- pub mute_locked: i32,
-}
-#[test]
-fn bindgen_test_layout_cras_client_mute_changed() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_mute_changed>(),
- 20usize,
- concat!("Size of: ", stringify!(cras_client_mute_changed))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_mute_changed>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_mute_changed))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_client_mute_changed>())).header as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_mute_changed),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_client_mute_changed>())).muted as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_mute_changed),
- "::",
- stringify!(muted)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_mute_changed>())).user_muted as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_mute_changed),
- "::",
- stringify!(user_muted)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_mute_changed>())).mute_locked as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_mute_changed),
- "::",
- stringify!(mute_locked)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_nodes_changed {
- pub header: cras_client_message,
-}
-#[test]
-fn bindgen_test_layout_cras_client_nodes_changed() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_nodes_changed>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_client_nodes_changed))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_nodes_changed>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_nodes_changed))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_nodes_changed>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_nodes_changed),
- "::",
- stringify!(header)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_active_node_changed {
- pub header: cras_client_message,
- pub direction: u32,
- pub node_id: cras_node_id_t,
-}
-#[test]
-fn bindgen_test_layout_cras_client_active_node_changed() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_active_node_changed>(),
- 20usize,
- concat!("Size of: ", stringify!(cras_client_active_node_changed))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_active_node_changed>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_active_node_changed))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_active_node_changed>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_active_node_changed),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_active_node_changed>())).direction as *const _
- as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_active_node_changed),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_active_node_changed>())).node_id as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_active_node_changed),
- "::",
- stringify!(node_id)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_node_value_changed {
- pub header: cras_client_message,
- pub node_id: cras_node_id_t,
- pub value: i32,
-}
-#[test]
-fn bindgen_test_layout_cras_client_node_value_changed() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_node_value_changed>(),
- 20usize,
- concat!("Size of: ", stringify!(cras_client_node_value_changed))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_node_value_changed>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_client_node_value_changed))
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_node_value_changed>())).header as *const _ as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_node_value_changed),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_node_value_changed>())).node_id as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_node_value_changed),
- "::",
- stringify!(node_id)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_node_value_changed>())).value as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_node_value_changed),
- "::",
- stringify!(value)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_client_num_active_streams_changed {
- pub header: cras_client_message,
- pub direction: u32,
- pub num_active_streams: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_client_num_active_streams_changed() {
- assert_eq!(
- ::std::mem::size_of::<cras_client_num_active_streams_changed>(),
- 16usize,
- concat!(
- "Size of: ",
- stringify!(cras_client_num_active_streams_changed)
- )
- );
- assert_eq!(
- ::std::mem::align_of::<cras_client_num_active_streams_changed>(),
- 1usize,
- concat!(
- "Alignment of ",
- stringify!(cras_client_num_active_streams_changed)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_num_active_streams_changed>())).header as *const _
- as usize
- },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_num_active_streams_changed),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_num_active_streams_changed>())).direction as *const _
- as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_num_active_streams_changed),
- "::",
- stringify!(direction)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_client_num_active_streams_changed>())).num_active_streams
- as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_client_num_active_streams_changed),
- "::",
- stringify!(num_active_streams)
- )
- );
-}
-#[repr(u32)]
-#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-pub enum CRAS_AUDIO_MESSAGE_ID {
- AUDIO_MESSAGE_REQUEST_DATA = 0,
- AUDIO_MESSAGE_DATA_READY = 1,
- AUDIO_MESSAGE_DATA_CAPTURED = 2,
- NUM_AUDIO_MESSAGES = 3,
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct audio_message {
- pub id: CRAS_AUDIO_MESSAGE_ID,
- pub error: i32,
- pub frames: u32,
-}
-#[test]
-fn bindgen_test_layout_audio_message() {
- assert_eq!(
- ::std::mem::size_of::<audio_message>(),
- 12usize,
- concat!("Size of: ", stringify!(audio_message))
- );
- assert_eq!(
- ::std::mem::align_of::<audio_message>(),
- 1usize,
- concat!("Alignment of ", stringify!(audio_message))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_message>())).id as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_message),
- "::",
- stringify!(id)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_message>())).error as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_message),
- "::",
- stringify!(error)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<audio_message>())).frames as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(audio_message),
- "::",
- stringify!(frames)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_audio_shm_config {
- pub used_size: u32,
- pub frame_bytes: u32,
-}
-#[test]
-fn bindgen_test_layout_cras_audio_shm_config() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_shm_config>(),
- 8usize,
- concat!("Size of: ", stringify!(cras_audio_shm_config))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_shm_config>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_audio_shm_config))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm_config>())).used_size as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_config),
- "::",
- stringify!(used_size)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_config>())).frame_bytes as *const _ as usize
- },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_config),
- "::",
- stringify!(frame_bytes)
- )
- );
-}
-#[repr(C, packed)]
-#[derive(Debug, Copy, Clone)]
-pub struct cras_audio_shm_header {
- pub config: cras_audio_shm_config,
- pub read_buf_idx: u32,
- pub write_buf_idx: u32,
- pub read_offset: [u32; 2usize],
- pub write_offset: [u32; 2usize],
- pub write_in_progress: [i32; 2usize],
- pub volume_scaler: f32,
- pub mute: i32,
- pub callback_pending: i32,
- pub num_overruns: u32,
- pub ts: cras_timespec,
- pub buffer_offset: [u64; 2usize],
-}
-#[test]
-fn bindgen_test_layout_cras_audio_shm_header() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_shm_header>(),
- 88usize,
- concat!("Size of: ", stringify!(cras_audio_shm_header))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_shm_header>(),
- 1usize,
- concat!("Alignment of ", stringify!(cras_audio_shm_header))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm_header>())).config as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(config)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).read_buf_idx as *const _ as usize
- },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(read_buf_idx)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).write_buf_idx as *const _ as usize
- },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(write_buf_idx)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).read_offset as *const _ as usize
- },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(read_offset)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).write_offset as *const _ as usize
- },
- 24usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(write_offset)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).write_in_progress as *const _ as usize
- },
- 32usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(write_in_progress)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).volume_scaler as *const _ as usize
- },
- 40usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(volume_scaler)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm_header>())).mute as *const _ as usize },
- 44usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(mute)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).callback_pending as *const _ as usize
- },
- 48usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(callback_pending)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).num_overruns as *const _ as usize
- },
- 52usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(num_overruns)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm_header>())).ts as *const _ as usize },
- 56usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(ts)
- )
- );
- assert_eq!(
- unsafe {
- &(*(::std::ptr::null::<cras_audio_shm_header>())).buffer_offset as *const _ as usize
- },
- 72usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm_header),
- "::",
- stringify!(buffer_offset)
- )
- );
-}
-#[repr(C)]
-#[derive(Copy, Clone)]
-pub struct cras_shm_info {
- pub fd: ::std::os::raw::c_int,
- pub name: [::std::os::raw::c_char; 255usize],
- pub length: usize,
-}
-#[test]
-fn bindgen_test_layout_cras_shm_info() {
- assert_eq!(
- ::std::mem::size_of::<cras_shm_info>(),
- 272usize,
- concat!("Size of: ", stringify!(cras_shm_info))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_shm_info>(),
- 8usize,
- concat!("Alignment of ", stringify!(cras_shm_info))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_shm_info>())).fd as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_shm_info),
- "::",
- stringify!(fd)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_shm_info>())).name as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_shm_info),
- "::",
- stringify!(name)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_shm_info>())).length as *const _ as usize },
- 264usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_shm_info),
- "::",
- stringify!(length)
- )
- );
-}
-#[repr(C)]
-#[derive(Copy, Clone)]
-pub struct cras_audio_shm {
- pub config: cras_audio_shm_config,
- pub header_info: cras_shm_info,
- pub header: *mut cras_audio_shm_header,
- pub samples_info: cras_shm_info,
- pub samples: *mut u8,
-}
-#[test]
-fn bindgen_test_layout_cras_audio_shm() {
- assert_eq!(
- ::std::mem::size_of::<cras_audio_shm>(),
- 568usize,
- concat!("Size of: ", stringify!(cras_audio_shm))
- );
- assert_eq!(
- ::std::mem::align_of::<cras_audio_shm>(),
- 8usize,
- concat!("Alignment of ", stringify!(cras_audio_shm))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm>())).config as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm),
- "::",
- stringify!(config)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm>())).header_info as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm),
- "::",
- stringify!(header_info)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm>())).header as *const _ as usize },
- 280usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm),
- "::",
- stringify!(header)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm>())).samples_info as *const _ as usize },
- 288usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm),
- "::",
- stringify!(samples_info)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<cras_audio_shm>())).samples as *const _ as usize },
- 560usize,
- concat!(
- "Offset of field: ",
- stringify!(cras_audio_shm),
- "::",
- stringify!(samples)
- )
- );
-}
diff --git a/cras/client/cras-sys/src/lib.rs b/cras/client/cras-sys/src/lib.rs
deleted file mode 100644
index 2b3d21e0..00000000
--- a/cras/client/cras-sys/src/lib.rs
+++ /dev/null
@@ -1,657 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-extern crate audio_streams;
-extern crate data_model;
-
-use std::cmp::min;
-use std::convert::{TryFrom, TryInto};
-use std::error;
-use std::fmt;
-use std::iter::FromIterator;
-use std::os::raw::c_char;
-use std::str::FromStr;
-use std::time::Duration;
-
-#[allow(dead_code)]
-#[allow(non_upper_case_globals)]
-#[allow(non_camel_case_types)]
-#[allow(non_snake_case)]
-pub mod gen;
-use gen::{
- _snd_pcm_format, audio_dev_debug_info, audio_message, audio_stream_debug_info,
- cras_audio_format_packed, cras_iodev_info, cras_ionode_info, cras_ionode_info__bindgen_ty_1,
- cras_timespec, snd_pcm_format_t, CRAS_AUDIO_MESSAGE_ID, CRAS_CHANNEL, CRAS_CLIENT_TYPE,
- CRAS_NODE_TYPE, CRAS_STREAM_DIRECTION, CRAS_STREAM_EFFECT, CRAS_STREAM_TYPE,
-};
-
-use audio_streams::{SampleFormat, StreamDirection, StreamEffect};
-
-unsafe impl data_model::DataInit for gen::audio_message {}
-unsafe impl data_model::DataInit for gen::audio_debug_info {}
-unsafe impl data_model::DataInit for gen::audio_dev_debug_info {}
-unsafe impl data_model::DataInit for gen::audio_stream_debug_info {}
-unsafe impl data_model::DataInit for gen::cras_client_connected {}
-unsafe impl data_model::DataInit for gen::cras_client_stream_connected {}
-unsafe impl data_model::DataInit for gen::cras_connect_message {}
-unsafe impl data_model::DataInit for gen::cras_disconnect_stream_message {}
-unsafe impl data_model::DataInit for gen::cras_dump_audio_thread {}
-unsafe impl data_model::DataInit for gen::cras_iodev_info {}
-unsafe impl data_model::DataInit for gen::cras_ionode_info {}
-unsafe impl data_model::DataInit for gen::cras_server_state {}
-unsafe impl data_model::DataInit for gen::cras_set_system_mute {}
-unsafe impl data_model::DataInit for gen::cras_set_system_volume {}
-
-/// An enumeration of errors that can occur when converting the packed C
-/// structs into Rust-style structs.
-#[derive(Debug)]
-pub enum Error {
- InvalidChannel(i8),
- InvalidClientType(u32),
- InvalidClientTypeStr,
- InvalidStreamType(u32),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- InvalidChannel(c) => write!(
- f,
- "Channel value {} is not within valid range [0, {})",
- c,
- CRAS_CHANNEL::CRAS_CH_MAX as u32
- ),
- InvalidClientType(t) => write!(
- f,
- "Client type {} is not within valid range [0, {})",
- t,
- CRAS_CLIENT_TYPE::CRAS_CLIENT_TYPE_SERVER_STREAM as u32 + 1
- ),
- InvalidClientTypeStr => write!(f, "Invalid client type string"),
- InvalidStreamType(t) => write!(
- f,
- "Stream type {} is not within valid range [0, {})",
- t,
- CRAS_STREAM_TYPE::CRAS_STREAM_NUM_TYPES as u32
- ),
- }
- }
-}
-
-impl cras_audio_format_packed {
- /// Initializes `cras_audio_format_packed` from input parameters.
- /// Field `channel_layout` will be assigned with default channel layout defined in
- /// `Self::default_channel_layout`.
- ///
- /// # Arguments
- /// * `format` - Format in used.
- /// * `rate` - Rate in used.
- /// * `num_channels` - Number of channels in used.
- /// * `direction` - Stream direction enumeration.
- ///
- /// # Returns
- /// Structure `cras_audio_format_packed`
- pub fn new(
- format: _snd_pcm_format,
- rate: u32,
- num_channels: usize,
- direction: CRAS_STREAM_DIRECTION,
- ) -> Self {
- Self {
- format: format as i32,
- frame_rate: rate,
- num_channels: num_channels as u32,
- channel_layout: Self::default_channel_layout(num_channels, direction),
- }
- }
-
- /// Generates default channel layout by given number of channels and stream direction.
- /// ```
- /// use cras_sys::gen::{
- /// _snd_pcm_format,
- /// cras_audio_format_packed,
- /// CRAS_STREAM_DIRECTION::*
- /// };
- /// let test_one = | num_channels, direction, expected_results | {
- /// let default_channel_fmt = cras_audio_format_packed::new(
- /// _snd_pcm_format::SND_PCM_FORMAT_S16,
- /// 48000,
- /// num_channels,
- /// direction
- /// );
- /// assert_eq!(default_channel_fmt.channel_layout, expected_results);
- /// };
- /// test_one(2, CRAS_STREAM_OUTPUT, [0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1]);
- /// test_one(4, CRAS_STREAM_OUTPUT, [0, 1, 2, 3, -1, -1, -1, -1, -1, -1, -1]);
- /// test_one(6, CRAS_STREAM_OUTPUT, [0, 1, 4, 5, 2, 3, -1, -1, -1, -1, -1]);
- /// test_one(2, CRAS_STREAM_INPUT, [0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1]);
- /// test_one(4, CRAS_STREAM_INPUT, [0, 1, 2, 3, -1, -1, -1, -1, -1, -1, -1]);
- /// test_one(6, CRAS_STREAM_INPUT, [0, 1, 2, 3, 4, 5, -1, -1, -1, -1, -1]);
- /// ```
- fn default_channel_layout(
- num_channels: usize,
- direction: CRAS_STREAM_DIRECTION,
- ) -> [i8; CRAS_CHANNEL::CRAS_CH_MAX as usize] {
- use {CRAS_CHANNEL::*, CRAS_STREAM_DIRECTION::*};
-
- let mut channel_layout = [-1; CRAS_CH_MAX as usize];
- match (num_channels, direction) {
- (6, CRAS_STREAM_OUTPUT) => {
- [
- CRAS_CH_FL,
- CRAS_CH_FR,
- CRAS_CH_FC,
- CRAS_CH_LFE,
- CRAS_CH_RL,
- CRAS_CH_RR,
- ]
- .iter()
- .enumerate()
- .for_each(|(idx, &channel)| channel_layout[channel as usize] = idx as i8);
- }
- _ => {
- for (i, channel) in channel_layout
- .iter_mut()
- .enumerate()
- .take(min(num_channels, CRAS_CH_MAX as usize))
- {
- *channel = i as i8;
- }
- }
- }
- channel_layout
- }
-}
-
-impl Default for audio_message {
- fn default() -> Self {
- Self {
- error: 0,
- frames: 0,
- id: CRAS_AUDIO_MESSAGE_ID::NUM_AUDIO_MESSAGES,
- }
- }
-}
-
-impl Default for cras_iodev_info {
- fn default() -> Self {
- Self {
- idx: 0,
- name: [0; 64usize],
- stable_id: 0,
- max_supported_channels: 0,
- }
- }
-}
-
-#[derive(Debug)]
-pub struct CrasIodevInfo {
- pub index: u32,
- pub name: String,
-}
-
-fn cstring_to_string(cstring: &[c_char]) -> String {
- let null_idx = match cstring.iter().enumerate().find(|(_, &c)| c == 0) {
- Some((i, _)) => i,
- None => return "".to_owned(),
- };
-
- let ptr = cstring.as_ptr() as *const u8;
- let slice = unsafe { core::slice::from_raw_parts(ptr, null_idx) };
- String::from_utf8_lossy(slice).to_string()
-}
-
-impl From<cras_iodev_info> for CrasIodevInfo {
- fn from(info: cras_iodev_info) -> Self {
- Self {
- index: info.idx,
- name: cstring_to_string(&info.name),
- }
- }
-}
-
-impl Default for cras_ionode_info {
- fn default() -> Self {
- Self {
- iodev_idx: 0,
- ionode_idx: 0,
- plugged: 0,
- active: 0,
- plugged_time: cras_ionode_info__bindgen_ty_1 {
- tv_sec: 0,
- tv_usec: 0,
- },
- volume: 0,
- ui_gain_scaler: 0.0,
- capture_gain: 0,
- left_right_swapped: 0,
- type_enum: 0,
- stable_id: 0,
- type_: [0; 32usize],
- name: [0; 64usize],
- active_hotword_model: [0; 16usize],
- }
- }
-}
-
-impl From<u32> for CRAS_NODE_TYPE {
- fn from(node_type: u32) -> CRAS_NODE_TYPE {
- use CRAS_NODE_TYPE::*;
- match node_type {
- 0 => CRAS_NODE_TYPE_INTERNAL_SPEAKER,
- 1 => CRAS_NODE_TYPE_HEADPHONE,
- 2 => CRAS_NODE_TYPE_HDMI,
- 3 => CRAS_NODE_TYPE_HAPTIC,
- 4 => CRAS_NODE_TYPE_LINEOUT,
- 5 => CRAS_NODE_TYPE_MIC,
- 6 => CRAS_NODE_TYPE_HOTWORD,
- 7 => CRAS_NODE_TYPE_POST_MIX_PRE_DSP,
- 8 => CRAS_NODE_TYPE_POST_DSP,
- 9 => CRAS_NODE_TYPE_USB,
- 10 => CRAS_NODE_TYPE_BLUETOOTH,
- _ => CRAS_NODE_TYPE_UNKNOWN,
- }
- }
-}
-
-#[derive(Debug)]
-pub struct CrasIonodeInfo {
- pub name: String,
- pub iodev_index: u32,
- pub ionode_index: u32,
- pub stable_id: u32,
- pub plugged: bool,
- pub active: bool,
- pub node_type: CRAS_NODE_TYPE,
- pub type_name: String,
- pub volume: u32,
- pub capture_gain: i32,
- pub plugged_time: cras_timespec,
-}
-
-impl From<cras_ionode_info> for CrasIonodeInfo {
- fn from(info: cras_ionode_info) -> Self {
- Self {
- name: cstring_to_string(&info.name),
- iodev_index: info.iodev_idx,
- ionode_index: info.ionode_idx,
- stable_id: info.stable_id,
- plugged: info.plugged != 0,
- active: info.active != 0,
- node_type: CRAS_NODE_TYPE::from(info.type_enum),
- type_name: cstring_to_string(&info.type_),
- volume: info.volume,
- capture_gain: info.capture_gain,
- plugged_time: cras_timespec {
- tv_sec: info.plugged_time.tv_sec,
- tv_nsec: info.plugged_time.tv_usec * 1000,
- },
- }
- }
-}
-
-impl From<u32> for CRAS_STREAM_DIRECTION {
- fn from(node_type: u32) -> CRAS_STREAM_DIRECTION {
- use CRAS_STREAM_DIRECTION::*;
- match node_type {
- 0 => CRAS_STREAM_OUTPUT,
- 1 => CRAS_STREAM_INPUT,
- 2 => CRAS_STREAM_UNDEFINED,
- 3 => CRAS_STREAM_POST_MIX_PRE_DSP,
- _ => CRAS_STREAM_UNDEFINED,
- }
- }
-}
-
-impl Default for audio_dev_debug_info {
- fn default() -> Self {
- Self {
- dev_name: [0; 64],
- buffer_size: 0,
- min_buffer_level: 0,
- min_cb_level: 0,
- max_cb_level: 0,
- frame_rate: 0,
- num_channels: 0,
- est_rate_ratio: 0.0,
- direction: 0,
- num_underruns: 0,
- num_severe_underruns: 0,
- highest_hw_level: 0,
- runtime_sec: 0,
- runtime_nsec: 0,
- longest_wake_sec: 0,
- longest_wake_nsec: 0,
- software_gain_scaler: 0.0,
- }
- }
-}
-
-/// A rust-style representation of the server's packed audio_dev_debug_info
-/// struct.
-#[derive(Debug)]
-pub struct AudioDevDebugInfo {
- pub dev_name: String,
- pub buffer_size: u32,
- pub min_buffer_level: u32,
- pub min_cb_level: u32,
- pub max_cb_level: u32,
- pub frame_rate: u32,
- pub num_channels: u32,
- pub est_rate_ratio: f64,
- pub direction: CRAS_STREAM_DIRECTION,
- pub num_underruns: u32,
- pub num_severe_underruns: u32,
- pub highest_hw_level: u32,
- pub runtime: Duration,
- pub longest_wake: Duration,
- pub software_gain_scaler: f64,
-}
-
-impl From<audio_dev_debug_info> for AudioDevDebugInfo {
- fn from(info: audio_dev_debug_info) -> Self {
- Self {
- dev_name: cstring_to_string(&info.dev_name),
- buffer_size: info.buffer_size,
- min_buffer_level: info.min_buffer_level,
- min_cb_level: info.min_cb_level,
- max_cb_level: info.max_cb_level,
- frame_rate: info.frame_rate,
- num_channels: info.num_channels,
- est_rate_ratio: info.est_rate_ratio,
- direction: CRAS_STREAM_DIRECTION::from(u32::from(info.direction)),
- num_underruns: info.num_underruns,
- num_severe_underruns: info.num_severe_underruns,
- highest_hw_level: info.highest_hw_level,
- runtime: Duration::new(info.runtime_sec.into(), info.runtime_nsec),
- longest_wake: Duration::new(info.longest_wake_sec.into(), info.longest_wake_nsec),
- software_gain_scaler: info.software_gain_scaler,
- }
- }
-}
-
-impl fmt::Display for AudioDevDebugInfo {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- writeln!(f, "Device: {}", self.dev_name)?;
- writeln!(f, " Direction: {:?}", self.direction)?;
- writeln!(f, " Buffer size: {}", self.buffer_size)?;
- writeln!(f, " Minimum buffer level: {}", self.min_buffer_level)?;
- writeln!(f, " Minimum callback level: {}", self.min_cb_level)?;
- writeln!(f, " Max callback level: {}", self.max_cb_level)?;
- writeln!(f, " Frame rate: {}", self.frame_rate)?;
- writeln!(f, " Number of channels: {}", self.num_channels)?;
- writeln!(f, " Estimated rate ratio: {:.2}", self.est_rate_ratio)?;
- writeln!(f, " Underrun count: {}", self.num_underruns)?;
- writeln!(f, " Severe underrun count: {}", self.num_severe_underruns)?;
- writeln!(f, " Highest hardware level: {}", self.highest_hw_level)?;
- writeln!(f, " Runtime: {:?}", self.runtime)?;
- writeln!(f, " Longest wake: {:?}", self.longest_wake)?;
- writeln!(f, " Software gain scaler: {}", self.software_gain_scaler)?;
- Ok(())
- }
-}
-
-impl TryFrom<u32> for CRAS_STREAM_TYPE {
- type Error = Error;
- fn try_from(stream_type: u32) -> Result<Self, Self::Error> {
- use CRAS_STREAM_TYPE::*;
- match stream_type {
- 0 => Ok(CRAS_STREAM_TYPE_DEFAULT),
- 1 => Ok(CRAS_STREAM_TYPE_MULTIMEDIA),
- 2 => Ok(CRAS_STREAM_TYPE_VOICE_COMMUNICATION),
- 3 => Ok(CRAS_STREAM_TYPE_SPEECH_RECOGNITION),
- 4 => Ok(CRAS_STREAM_TYPE_PRO_AUDIO),
- 5 => Ok(CRAS_STREAM_TYPE_ACCESSIBILITY),
- _ => Err(Error::InvalidStreamType(stream_type)),
- }
- }
-}
-
-impl TryFrom<u32> for CRAS_CLIENT_TYPE {
- type Error = Error;
- fn try_from(client_type: u32) -> Result<Self, Self::Error> {
- use CRAS_CLIENT_TYPE::*;
- match client_type {
- 0 => Ok(CRAS_CLIENT_TYPE_UNKNOWN),
- 1 => Ok(CRAS_CLIENT_TYPE_LEGACY),
- 2 => Ok(CRAS_CLIENT_TYPE_TEST),
- 3 => Ok(CRAS_CLIENT_TYPE_PCM),
- 4 => Ok(CRAS_CLIENT_TYPE_CHROME),
- 5 => Ok(CRAS_CLIENT_TYPE_ARC),
- 6 => Ok(CRAS_CLIENT_TYPE_CROSVM),
- 7 => Ok(CRAS_CLIENT_TYPE_SERVER_STREAM),
- 8 => Ok(CRAS_CLIENT_TYPE_LACROS),
- _ => Err(Error::InvalidClientType(client_type)),
- }
- }
-}
-
-impl FromStr for CRAS_CLIENT_TYPE {
- type Err = Error;
- fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
- use CRAS_CLIENT_TYPE::*;
- match s {
- "crosvm" => Ok(CRAS_CLIENT_TYPE_CROSVM),
- "arcvm" => Ok(CRAS_CLIENT_TYPE_ARCVM),
- _ => Err(Error::InvalidClientTypeStr),
- }
- }
-}
-
-impl Default for audio_stream_debug_info {
- fn default() -> Self {
- Self {
- stream_id: 0,
- dev_idx: 0,
- direction: 0,
- stream_type: 0,
- client_type: 0,
- buffer_frames: 0,
- cb_threshold: 0,
- effects: 0,
- flags: 0,
- frame_rate: 0,
- num_channels: 0,
- longest_fetch_sec: 0,
- longest_fetch_nsec: 0,
- num_missed_cb: 0,
- num_overruns: 0,
- is_pinned: 0,
- pinned_dev_idx: 0,
- runtime_sec: 0,
- runtime_nsec: 0,
- stream_volume: 0.0,
- channel_layout: [0; 11],
- }
- }
-}
-
-impl TryFrom<i8> for CRAS_CHANNEL {
- type Error = Error;
- fn try_from(channel: i8) -> Result<Self, Self::Error> {
- use CRAS_CHANNEL::*;
- match channel {
- 0 => Ok(CRAS_CH_FL),
- 1 => Ok(CRAS_CH_FR),
- 2 => Ok(CRAS_CH_RL),
- 3 => Ok(CRAS_CH_RR),
- 4 => Ok(CRAS_CH_FC),
- 5 => Ok(CRAS_CH_LFE),
- 6 => Ok(CRAS_CH_SL),
- 7 => Ok(CRAS_CH_SR),
- 8 => Ok(CRAS_CH_RC),
- 9 => Ok(CRAS_CH_FLC),
- 10 => Ok(CRAS_CH_FRC),
- _ => Err(Error::InvalidChannel(channel)),
- }
- }
-}
-
-/// A rust-style representation of the server's packed audio_stream_debug_info
-/// struct.
-#[derive(Debug)]
-pub struct AudioStreamDebugInfo {
- pub stream_id: u64,
- pub dev_idx: u32,
- pub direction: CRAS_STREAM_DIRECTION,
- pub stream_type: CRAS_STREAM_TYPE,
- pub client_type: CRAS_CLIENT_TYPE,
- pub buffer_frames: u32,
- pub cb_threshold: u32,
- pub effects: u64,
- pub flags: u32,
- pub frame_rate: u32,
- pub num_channels: u32,
- pub longest_fetch: Duration,
- pub num_missed_cb: u32,
- pub num_overruns: u32,
- pub is_pinned: bool,
- pub pinned_dev_idx: u32,
- pub runtime: Duration,
- pub stream_volume: f64,
- pub channel_layout: Vec<CRAS_CHANNEL>,
-}
-
-impl TryFrom<audio_stream_debug_info> for AudioStreamDebugInfo {
- type Error = Error;
- fn try_from(info: audio_stream_debug_info) -> Result<Self, Self::Error> {
- let channel_layout = info
- .channel_layout
- .iter()
- .cloned()
- .take_while(|&c| c != -1)
- .map(TryInto::try_into)
- .collect::<Result<Vec<_>, _>>()?;
- Ok(Self {
- stream_id: info.stream_id,
- dev_idx: info.dev_idx,
- direction: info.direction.into(),
- stream_type: info.stream_type.try_into()?,
- client_type: info.client_type.try_into()?,
- buffer_frames: info.buffer_frames,
- cb_threshold: info.cb_threshold,
- effects: info.effects,
- flags: info.flags,
- frame_rate: info.frame_rate,
- num_channels: info.num_channels,
- longest_fetch: Duration::new(info.longest_fetch_sec.into(), info.longest_fetch_nsec),
- num_missed_cb: info.num_missed_cb,
- num_overruns: info.num_overruns,
- is_pinned: info.is_pinned != 0,
- pinned_dev_idx: info.pinned_dev_idx,
- runtime: Duration::new(info.runtime_sec.into(), info.runtime_nsec),
- stream_volume: info.stream_volume,
- channel_layout,
- })
- }
-}
-
-impl fmt::Display for AudioStreamDebugInfo {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- writeln!(
- f,
- "Stream: {}, Device index: {}",
- self.stream_id, self.dev_idx
- )?;
- writeln!(f, " Direction: {:?}", self.direction)?;
- writeln!(f, " Stream type: {:?}", self.stream_type)?;
- writeln!(f, " Client type: {:?}", self.client_type)?;
- writeln!(f, " Buffer frames: {}", self.buffer_frames)?;
- writeln!(f, " Callback threshold: {}", self.cb_threshold)?;
- writeln!(f, " Effects: {:#x}", self.effects)?;
- writeln!(f, " Frame rate: {}", self.frame_rate)?;
- writeln!(f, " Number of channels: {}", self.num_channels)?;
- writeln!(f, " Longest fetch: {:?}", self.longest_fetch)?;
- writeln!(f, " Overrun count: {}", self.num_overruns)?;
- writeln!(f, " Pinned: {}", self.is_pinned)?;
- writeln!(f, " Pinned device index: {}", self.pinned_dev_idx)?;
- writeln!(f, " Missed callbacks: {}", self.num_missed_cb)?;
- match self.direction {
- CRAS_STREAM_DIRECTION::CRAS_STREAM_OUTPUT => {
- writeln!(f, " Volume: {:.2}", self.stream_volume)?
- }
- CRAS_STREAM_DIRECTION::CRAS_STREAM_INPUT => {
- writeln!(f, " Gain: {:.2}", self.stream_volume)?
- }
- _ => (),
- };
- writeln!(f, " Runtime: {:?}", self.runtime)?;
- write!(f, " Channel map:")?;
- for channel in &self.channel_layout {
- write!(f, " {:?}", channel)?;
- }
- writeln!(f)?;
- Ok(())
- }
-}
-
-/// A rust-style representation of the server's audio debug info.
-pub struct AudioDebugInfo {
- pub devices: Vec<AudioDevDebugInfo>,
- pub streams: Vec<AudioStreamDebugInfo>,
-}
-
-impl AudioDebugInfo {
- pub fn new(devices: Vec<AudioDevDebugInfo>, streams: Vec<AudioStreamDebugInfo>) -> Self {
- Self { devices, streams }
- }
-}
-
-impl Into<u64> for CRAS_STREAM_EFFECT {
- fn into(self) -> u64 {
- u64::from(self.0)
- }
-}
-
-impl CRAS_STREAM_EFFECT {
- pub fn empty() -> Self {
- CRAS_STREAM_EFFECT(0)
- }
-}
-
-impl From<StreamDirection> for CRAS_STREAM_DIRECTION {
- /// Convert an audio_streams StreamDirection into the corresponding CRAS_STREAM_DIRECTION.
- fn from(direction: StreamDirection) -> Self {
- match direction {
- StreamDirection::Playback => CRAS_STREAM_DIRECTION::CRAS_STREAM_OUTPUT,
- StreamDirection::Capture => CRAS_STREAM_DIRECTION::CRAS_STREAM_INPUT,
- }
- }
-}
-
-impl From<StreamEffect> for CRAS_STREAM_EFFECT {
- /// Convert an audio_streams StreamEffect into the corresponding CRAS_STREAM_EFFECT.
- fn from(effect: StreamEffect) -> Self {
- match effect {
- StreamEffect::NoEffect => CRAS_STREAM_EFFECT::empty(),
- StreamEffect::EchoCancellation => CRAS_STREAM_EFFECT::APM_ECHO_CANCELLATION,
- }
- }
-}
-
-impl<'a> FromIterator<&'a StreamEffect> for CRAS_STREAM_EFFECT {
- fn from_iter<I>(iter: I) -> Self
- where
- I: IntoIterator<Item = &'a StreamEffect>,
- {
- iter.into_iter().fold(
- CRAS_STREAM_EFFECT::empty(),
- |cras_effect, &stream_effect| cras_effect | stream_effect.into(),
- )
- }
-}
-
-/// Convert an audio_streams SampleFormat into the corresponding pcm_format.
-impl From<SampleFormat> for snd_pcm_format_t {
- fn from(format: SampleFormat) -> Self {
- match format {
- SampleFormat::U8 => snd_pcm_format_t::SND_PCM_FORMAT_U8,
- SampleFormat::S16LE => snd_pcm_format_t::SND_PCM_FORMAT_S16_LE,
- SampleFormat::S24LE => snd_pcm_format_t::SND_PCM_FORMAT_S24_LE,
- SampleFormat::S32LE => snd_pcm_format_t::SND_PCM_FORMAT_S32_LE,
- }
- }
-}
diff --git a/cras/client/cras_tests/.gitignore b/cras/client/cras_tests/.gitignore
deleted file mode 100644
index 302b31de..00000000
--- a/cras/client/cras_tests/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-target/
-.*.rustfmt
diff --git a/cras/client/cras_tests/.rustfmt.toml b/cras/client/cras_tests/.rustfmt.toml
deleted file mode 100644
index a2db3012..00000000
--- a/cras/client/cras_tests/.rustfmt.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-use_field_init_shorthand = true
-use_try_shorthand = true
diff --git a/cras/client/cras_tests/Cargo.toml b/cras/client/cras_tests/Cargo.toml
deleted file mode 100644
index 108fe6c4..00000000
--- a/cras/client/cras_tests/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "cras_tests"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-
-[dependencies]
-audio_streams = { path = "../../../audio_streams" } # provided by ebuild
-getopts = "0.2.18"
-hound = "3.4.0"
-libcras = { path = "../libcras" } # provided by ebuild
-sys_util = { path = "../../../../crosvm/sys_util" } # provided by ebuild
-
-[profile.release]
-lto = true
-panic = 'abort'
-overflow-checks = true
diff --git a/cras/client/cras_tests/src/arguments.rs b/cras/client/cras_tests/src/arguments.rs
deleted file mode 100644
index 59e9ec26..00000000
--- a/cras/client/cras_tests/src/arguments.rs
+++ /dev/null
@@ -1,462 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::error;
-use std::fmt;
-use std::path::PathBuf;
-
-use audio_streams::SampleFormat;
-use getopts::{self, Matches, Options};
-
-#[derive(Debug)]
-pub enum Error {
- GetOpts(getopts::Fail),
- InvalidArgument(String, String, String),
- InvalidFiletype(String),
- MissingArgument(String),
- MissingCommand,
- MissingFilename,
- UnknownCommand(String),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- GetOpts(e) => write!(f, "Getopts Error: {}", e),
- InvalidArgument(flag, value, error_msg) => {
- write!(f, "Invalid {} argument '{}': {}", flag, value, error_msg)
- }
- InvalidFiletype(extension) => write!(
- f,
- "Invalid file extension '{}'. Supported types are 'wav' and 'raw'",
- extension
- ),
- MissingArgument(subcommand) => write!(f, "Missing argument for {}", subcommand),
- MissingCommand => write!(f, "A command must be provided"),
- MissingFilename => write!(f, "A file name must be provided"),
- UnknownCommand(s) => write!(f, "Unknown command '{}'", s),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-/// The different types of commands that can be given to cras_tests.
-/// Any options for those commands are passed as parameters to the enum values.
-#[derive(Debug, PartialEq)]
-pub enum Command {
- Capture(AudioOptions),
- Playback(AudioOptions),
- Control(ControlCommand),
-}
-
-impl Command {
- pub fn parse<T: AsRef<str>>(args: &[T]) -> Result<Option<Self>> {
- let program_name = args.get(0).map(|s| s.as_ref()).unwrap_or("cras_tests");
- let remaining_args = args.get(2..).unwrap_or(&[]);
- match args.get(1).map(|s| s.as_ref()) {
- None => {
- show_usage(program_name);
- Err(Error::MissingCommand)
- }
- Some("help") => {
- show_usage(program_name);
- Ok(None)
- }
- Some("capture") => Ok(
- AudioOptions::parse(program_name, "capture", remaining_args)?.map(Command::Capture),
- ),
- Some("playback") => Ok(
- AudioOptions::parse(program_name, "playback", remaining_args)?
- .map(Command::Playback),
- ),
- Some("control") => {
- Ok(ControlCommand::parse(program_name, remaining_args)?.map(Command::Control))
- }
- Some(s) => {
- show_usage(program_name);
- Err(Error::UnknownCommand(s.to_string()))
- }
- }
- }
-}
-
-#[derive(Debug, PartialEq)]
-pub enum FileType {
- Raw,
- Wav,
-}
-
-impl fmt::Display for FileType {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- FileType::Raw => write!(f, "raw data"),
- FileType::Wav => write!(f, "WAVE"),
- }
- }
-}
-
-fn show_usage(program_name: &str) {
- eprintln!("Usage: {} [command] <command args>", program_name);
- eprintln!("\nCommands:\n");
- eprintln!("capture - Capture to a file from CRAS");
- eprintln!("playback - Playback to CRAS from a file");
- eprintln!("control - Get and set server settings");
- eprintln!("\nhelp - Print help message");
-}
-
-fn show_audio_command_usage(program_name: &str, command: &str, opts: &Options) {
- let brief = format!("Usage: {} {} [options] [filename]", program_name, command);
- eprint!("{}", opts.usage(&brief));
-}
-
-/// The possible command line options that can be passed to the 'playback' and
-/// 'capture' commands. Optional values will be `Some(_)` only if a value was
-/// explicitly provided by the user.
-///
-/// This struct will be passed to `playback()` and `capture()`.
-#[derive(Debug, PartialEq)]
-pub enum LoopbackType {
- PreDsp,
- PostDsp,
-}
-
-#[derive(Debug, PartialEq)]
-pub struct AudioOptions {
- pub file_name: PathBuf,
- pub loopback_type: Option<LoopbackType>,
- pub file_type: FileType,
- pub buffer_size: Option<usize>,
- pub num_channels: Option<usize>,
- pub format: Option<SampleFormat>,
- pub frame_rate: Option<u32>,
-}
-
-fn get_u32_param(matches: &Matches, option_name: &str) -> Result<Option<u32>> {
- matches.opt_get::<u32>(option_name).map_err(|e| {
- let argument = matches.opt_str(option_name).unwrap_or_default();
- Error::InvalidArgument(option_name.to_string(), argument, e.to_string())
- })
-}
-
-fn get_usize_param(matches: &Matches, option_name: &str) -> Result<Option<usize>> {
- matches.opt_get::<usize>(option_name).map_err(|e| {
- let argument = matches.opt_str(option_name).unwrap_or_default();
- Error::InvalidArgument(option_name.to_string(), argument, e.to_string())
- })
-}
-
-impl AudioOptions {
- fn parse<T: AsRef<str>>(
- program_name: &str,
- command_name: &str,
- args: &[T],
- ) -> Result<Option<Self>> {
- let mut opts = Options::new();
- opts.optopt("b", "buffer_size", "Buffer size in frames", "SIZE")
- .optopt("c", "channels", "Number of channels", "NUM")
- .optopt(
- "f",
- "format",
- "Sample format (U8, S16_LE, S24_LE, or S32_LE)",
- "FORMAT",
- )
- .optopt("r", "rate", "Audio frame rate (Hz)", "RATE")
- .optflag("h", "help", "Print help message");
-
- if command_name == "capture" {
- opts.optopt(
- "",
- "loopback",
- "Capture from loopback device ('pre_dsp' or 'post_dsp')",
- "DEVICE",
- );
- }
-
- let args = args.iter().map(|s| s.as_ref());
- let matches = match opts.parse(args) {
- Ok(m) => m,
- Err(e) => {
- show_audio_command_usage(program_name, command_name, &opts);
- return Err(Error::GetOpts(e));
- }
- };
- if matches.opt_present("h") {
- show_audio_command_usage(program_name, command_name, &opts);
- return Ok(None);
- }
-
- let loopback_type = if matches.opt_defined("loopback") {
- match matches.opt_str("loopback").as_deref() {
- Some("pre_dsp") => Some(LoopbackType::PreDsp),
- Some("post_dsp") => Some(LoopbackType::PostDsp),
- Some(s) => {
- return Err(Error::InvalidArgument(
- "loopback".to_string(),
- s.to_string(),
- "Loopback type must be 'pre_dsp' or 'post_dsp'".to_string(),
- ))
- }
- None => None,
- }
- } else {
- None
- };
-
- let file_name = match matches.free.get(0) {
- None => {
- show_audio_command_usage(program_name, command_name, &opts);
- return Err(Error::MissingFilename);
- }
- Some(file_name) => PathBuf::from(file_name),
- };
-
- let extension = file_name
- .extension()
- .map(|s| s.to_string_lossy().into_owned());
- let file_type = match extension.as_deref() {
- Some("wav") | Some("wave") => FileType::Wav,
- Some("raw") | None => FileType::Raw,
- Some(extension) => return Err(Error::InvalidFiletype(extension.to_string())),
- };
-
- let buffer_size = get_usize_param(&matches, "buffer_size")?;
- let num_channels = get_usize_param(&matches, "channels")?;
- let frame_rate = get_u32_param(&matches, "rate")?;
- let format = match matches.opt_str("format").as_deref() {
- Some("U8") => Some(SampleFormat::U8),
- Some("S16_LE") => Some(SampleFormat::S16LE),
- Some("S24_LE") => Some(SampleFormat::S24LE),
- Some("S32_LE") => Some(SampleFormat::S32LE),
- Some(s) => {
- show_audio_command_usage(program_name, command_name, &opts);
- return Err(Error::InvalidArgument(
- "format".to_string(),
- s.to_string(),
- "Format must be 'U8', 'S16_LE', 'S24_LE', or 'S32_LE'".to_string(),
- ));
- }
- None => None,
- };
-
- Ok(Some(AudioOptions {
- loopback_type,
- file_name,
- file_type,
- buffer_size,
- num_channels,
- format,
- frame_rate,
- }))
- }
-}
-
-fn show_control_command_usage(program_name: &str) {
- eprintln!("Usage: {} control [command] <command args>", program_name);
- eprintln!("");
- eprintln!("Commands:");
- let commands = [
- ("help", "", "Print help message"),
- ("", "", ""),
- ("get_volume", "", "Get the system volume (0 - 100)"),
- (
- "set_volume",
- "VOLUME",
- "Set the system volume to VOLUME (0 - 100)",
- ),
- ("get_mute", "", "Get the system mute state (true or false)"),
- (
- "set_mute",
- "MUTE",
- "Set the system mute state to MUTE (true or false)",
- ),
- ("", "", ""),
- ("list_output_devices", "", "Print list of output devices"),
- ("list_input_devices", "", "Print list of input devices"),
- ("list_output_nodes", "", "Print list of output nodes"),
- ("list_input_nodes", "", "Print list of input nodes"),
- (
- "dump_audio_debug_info",
- "",
- "Print stream info, device info, and audio thread log.",
- ),
- ];
- for command in &commands {
- let command_string = format!("{} {}", command.0, command.1);
- eprintln!("\t{: <23} {}", command_string, command.2);
- }
-}
-
-#[derive(Debug, PartialEq)]
-pub enum ControlCommand {
- GetSystemVolume,
- SetSystemVolume(u32),
- GetSystemMute,
- SetSystemMute(bool),
- ListOutputDevices,
- ListInputDevices,
- ListOutputNodes,
- ListInputNodes,
- DumpAudioDebugInfo,
-}
-
-impl ControlCommand {
- fn parse<T: AsRef<str>>(program_name: &str, args: &[T]) -> Result<Option<Self>> {
- let mut args = args.iter().map(|s| s.as_ref());
- match args.next() {
- Some("help") => {
- show_control_command_usage(program_name);
- Ok(None)
- }
- Some("get_volume") => Ok(Some(ControlCommand::GetSystemVolume)),
- Some("set_volume") => {
- let volume_str = args
- .next()
- .ok_or_else(|| Error::MissingArgument("set_volume".to_string()))?;
-
- let volume = volume_str.parse::<u32>().map_err(|e| {
- Error::InvalidArgument(
- "set_volume".to_string(),
- volume_str.to_string(),
- e.to_string(),
- )
- })?;
-
- Ok(Some(ControlCommand::SetSystemVolume(volume)))
- }
- Some("get_mute") => Ok(Some(ControlCommand::GetSystemMute)),
- Some("set_mute") => {
- let mute_str = args
- .next()
- .ok_or_else(|| Error::MissingArgument("set_mute".to_string()))?;
-
- let mute = mute_str.parse::<bool>().map_err(|e| {
- Error::InvalidArgument(
- "set_mute".to_string(),
- mute_str.to_string(),
- e.to_string(),
- )
- })?;
- Ok(Some(ControlCommand::SetSystemMute(mute)))
- }
- Some("list_output_devices") => Ok(Some(ControlCommand::ListOutputDevices)),
- Some("list_input_devices") => Ok(Some(ControlCommand::ListInputDevices)),
- Some("list_output_nodes") => Ok(Some(ControlCommand::ListOutputNodes)),
- Some("list_input_nodes") => Ok(Some(ControlCommand::ListInputNodes)),
- Some("dump_audio_debug_info") => Ok(Some(ControlCommand::DumpAudioDebugInfo)),
- Some(s) => {
- show_control_command_usage(program_name);
- Err(Error::UnknownCommand(s.to_string()))
- }
- None => {
- show_control_command_usage(program_name);
- Err(Error::MissingCommand)
- }
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn parse_command() {
- let command = Command::parse(&["cras_tests", "playback", "output.wav"])
- .unwrap()
- .unwrap();
- assert_eq!(
- command,
- Command::Playback(AudioOptions {
- file_name: PathBuf::from("output.wav"),
- loopback_type: None,
- file_type: FileType::Wav,
- frame_rate: None,
- num_channels: None,
- format: None,
- buffer_size: None,
- })
- );
- let command = Command::parse(&["cras_tests", "capture", "input.raw"])
- .unwrap()
- .unwrap();
- assert_eq!(
- command,
- Command::Capture(AudioOptions {
- file_name: PathBuf::from("input.raw"),
- loopback_type: None,
- file_type: FileType::Raw,
- frame_rate: None,
- num_channels: None,
- format: None,
- buffer_size: None,
- })
- );
-
- let command = Command::parse(&[
- "cras_tests",
- "playback",
- "-r",
- "44100",
- "output.wave",
- "-c",
- "2",
- ])
- .unwrap()
- .unwrap();
- assert_eq!(
- command,
- Command::Playback(AudioOptions {
- file_name: PathBuf::from("output.wave"),
- loopback_type: None,
- file_type: FileType::Wav,
- frame_rate: Some(44100),
- num_channels: Some(2),
- format: None,
- buffer_size: None,
- })
- );
-
- let command =
- Command::parse(&["cras_tests", "playback", "-r", "44100", "output", "-c", "2"])
- .unwrap()
- .unwrap();
- assert_eq!(
- command,
- Command::Playback(AudioOptions {
- file_name: PathBuf::from("output"),
- loopback_type: None,
- file_type: FileType::Raw,
- frame_rate: Some(44100),
- num_channels: Some(2),
- format: None,
- buffer_size: None,
- })
- );
-
- assert!(Command::parse(&["cras_tests"]).is_err());
- assert!(Command::parse(&["cras_tests", "capture"]).is_err());
- assert!(Command::parse(&["cras_tests", "capture", "input.mp3"]).is_err());
- assert!(Command::parse(&["cras_tests", "capture", "input.ogg"]).is_err());
- assert!(Command::parse(&["cras_tests", "capture", "input.flac"]).is_err());
- assert!(Command::parse(&["cras_tests", "playback"]).is_err());
- assert!(Command::parse(&["cras_tests", "loopback"]).is_err());
- assert!(Command::parse(&["cras_tests", "loopback", "file.ogg"]).is_err());
- assert!(Command::parse(&["cras_tests", "filename.wav"]).is_err());
- assert!(Command::parse(&["cras_tests", "filename.wav", "capture"]).is_err());
- assert!(Command::parse(&["cras_tests", "help"]).is_ok());
- assert!(Command::parse(&[
- "cras_tests",
- "-c",
- "2",
- "playback",
- "output.wav",
- "-r",
- "44100"
- ])
- .is_err());
- }
-}
diff --git a/cras/client/cras_tests/src/audio.rs b/cras/client/cras_tests/src/audio.rs
deleted file mode 100644
index 23018fd7..00000000
--- a/cras/client/cras_tests/src/audio.rs
+++ /dev/null
@@ -1,414 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-use std::error;
-use std::fmt;
-use std::fs::File;
-use std::io::{self, BufReader, BufWriter, Read, Write};
-use std::os::raw::c_int;
-use std::path::Path;
-use std::sync::atomic::{AtomicBool, Ordering};
-
-use audio_streams::{SampleFormat, StreamSource};
-use hound::{WavReader, WavSpec, WavWriter};
-use libcras::{BoxError, CrasClient, CrasNodeType};
-use sys_util::{register_signal_handler, set_rt_prio_limit, set_rt_round_robin};
-
-use crate::arguments::{AudioOptions, FileType, LoopbackType};
-
-#[derive(Debug)]
-pub enum Error {
- CreateStream(BoxError),
- FetchStream(BoxError),
- FloatingPointSamples,
- InvalidWavFile(hound::Error),
- Io(io::Error),
- Libcras(libcras::Error),
- NoLoopbackNode(CrasNodeType),
- OpenFile(hound::Error),
- SampleBits(u16),
- SysUtil(sys_util::Error),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- CreateStream(e) => write!(f, "Failed to create stream: {}", e),
- FetchStream(e) => write!(f, "Failed to fetch buffer from stream: {}", e),
- FloatingPointSamples => write!(f, "Floating point audio samples are not supported"),
- InvalidWavFile(e) => write!(f, "Could not open file as WAV file: {}", e),
- Io(e) => write!(f, "IO Error: {}", e),
- Libcras(e) => write!(f, "Libcras Error: {}", e),
- NoLoopbackNode(typ) => write!(f, "No loopback node found with type {:?}", typ),
- OpenFile(e) => write!(f, "Could not open WAV file for writing: {}", e),
- SampleBits(bits) => write!(
- f,
- "Sample size {} is not supported, only 8, 16, 24, and 32 bit samples are supported",
- bits
- ),
- SysUtil(e) => write!(f, "SysUtil Error: {}", e),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-static INTERRUPTED: AtomicBool = AtomicBool::new(false);
-
-extern "C" fn sigint_handler(_: c_int) {
- // Check if we've already received one SIGINT. If we have, the program may
- // be misbehaving and not terminating, so to be safe we'll forcefully exit.
- if INTERRUPTED.load(Ordering::Acquire) {
- std::process::exit(1);
- }
- INTERRUPTED.store(true, Ordering::Release);
-}
-
-fn add_sigint_handler() -> Result<()> {
- const SIGINT: c_int = 2;
- let result = unsafe { register_signal_handler(SIGINT, sigint_handler) };
- result.map_err(Error::SysUtil)
-}
-
-fn set_priority_to_realtime() {
- const AUDIO_THREAD_RTPRIO: u16 = 10;
- if set_rt_prio_limit(AUDIO_THREAD_RTPRIO as u64).is_err()
- || set_rt_round_robin(AUDIO_THREAD_RTPRIO as i32).is_err()
- {
- println!("Attempt to use real-time priority failed, running with default scheduler.");
- }
-}
-
-fn channel_string(num_channels: usize) -> String {
- match num_channels {
- 1 => "Mono".to_string(),
- 2 => "Stereo".to_string(),
- _ => format!("{} Channels", num_channels),
- }
-}
-
-struct WavSource {
- wav_reader: WavReader<BufReader<File>>,
- format: SampleFormat,
- num_channels: usize,
- frame_rate: u32,
-}
-
-impl WavSource {
- fn try_new(opts: &AudioOptions) -> Result<Self> {
- let wav_reader = WavReader::open(&opts.file_name).map_err(Error::InvalidWavFile)?;
- let spec = wav_reader.spec();
- if spec.sample_format == hound::SampleFormat::Float {
- return Err(Error::FloatingPointSamples);
- }
-
- let format = match spec.bits_per_sample {
- 8 => SampleFormat::U8,
- 16 => SampleFormat::S16LE,
- 24 => SampleFormat::S24LE,
- 32 => SampleFormat::S32LE,
- s => return Err(Error::SampleBits(s)),
- };
- if opts.format.is_some() && Some(format) != opts.format {
- eprintln!("Warning: format changed to {:?}", format);
- }
-
- let num_channels = spec.channels as usize;
- if opts.num_channels.is_some() && Some(num_channels) != opts.num_channels {
- eprintln!("Warning: number of channels changed to {}", num_channels);
- }
-
- let frame_rate = spec.sample_rate;
- if opts.frame_rate.is_some() && Some(frame_rate) != opts.frame_rate {
- eprintln!("Warning: frame rate changed to {}", frame_rate);
- }
-
- Ok(Self {
- wav_reader,
- format,
- num_channels,
- frame_rate,
- })
- }
-
- fn format(&self) -> SampleFormat {
- self.format
- }
-
- fn num_channels(&self) -> usize {
- self.num_channels
- }
-
- fn frame_rate(&self) -> u32 {
- self.frame_rate
- }
-}
-
-impl Read for WavSource {
- fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
- let frame_size = self.format.sample_bytes() * self.num_channels;
- let read_len = buf.len() - buf.len() % frame_size;
- let num_samples = read_len / self.format.sample_bytes();
- let samples = self.wav_reader.samples::<i32>();
- let mut read = 0;
- for s in samples.take(num_samples) {
- match s {
- Ok(sample) => {
- let result = match self.format {
- SampleFormat::U8 => buf.write_all(&((sample + 128) as u8).to_le_bytes()),
- SampleFormat::S16LE => buf.write_all(&(sample as i16).to_le_bytes()),
- SampleFormat::S24LE | SampleFormat::S32LE => {
- buf.write_all(&sample.to_le_bytes())
- }
- };
-
- match result {
- Ok(()) => read += self.format.sample_bytes(),
- Err(_) => return Ok(read),
- };
- }
- Err(_) => return Ok(read),
- };
- }
- Ok(read)
- }
-}
-
-pub fn playback(opts: AudioOptions) -> Result<()> {
- let num_channels;
- let frame_rate;
- let format;
- let mut sample_source: Box<dyn Read> = match opts.file_type {
- FileType::Wav => {
- let wav_source = WavSource::try_new(&opts)?;
- num_channels = wav_source.num_channels();
- frame_rate = wav_source.frame_rate();
- format = wav_source.format();
- Box::new(wav_source)
- }
- FileType::Raw => {
- num_channels = opts.num_channels.unwrap_or(2);
- frame_rate = opts.frame_rate.unwrap_or(48000);
- format = opts.format.unwrap_or(SampleFormat::S16LE);
- Box::new(BufReader::new(
- File::open(&opts.file_name).map_err(Error::Io)?,
- ))
- }
- };
-
- println!(
- "Playing {} '{}' : {}, Rate {} Hz, {}",
- opts.file_type,
- opts.file_name.display(),
- format,
- frame_rate,
- channel_string(num_channels)
- );
-
- let mut cras_client = CrasClient::new().map_err(Error::Libcras)?;
- let (_control, mut stream) = cras_client
- .new_playback_stream(
- num_channels,
- format,
- frame_rate,
- opts.buffer_size.unwrap_or(256),
- )
- .map_err(Error::CreateStream)?;
- set_priority_to_realtime();
-
- add_sigint_handler()?;
- while !INTERRUPTED.load(Ordering::Acquire) {
- let mut buffer = stream.next_playback_buffer().map_err(Error::FetchStream)?;
-
- let frame_size = num_channels * format.sample_bytes();
- let frames = buffer.frame_capacity();
-
- let mut chunk = (&mut sample_source).take((frames * frame_size) as u64);
- let transferred = io::copy(&mut chunk, &mut buffer).map_err(Error::Io)?;
- if transferred == 0 {
- break;
- }
- }
- // Stream and client should gracefully be closed out of this scope
-
- Ok(())
-}
-
-struct WavSink {
- wav_writer: WavWriter<BufWriter<File>>,
- format: SampleFormat,
-}
-
-impl WavSink {
- fn try_new<P: AsRef<Path>>(
- path: P,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- ) -> Result<Self> {
- let spec = WavSpec {
- channels: num_channels as u16,
- sample_rate: frame_rate,
- bits_per_sample: (format.sample_bytes() * 8) as u16,
- sample_format: hound::SampleFormat::Int,
- };
- let wav_writer = WavWriter::create(path, spec).map_err(Error::OpenFile)?;
- Ok(Self { wav_writer, format })
- }
-}
-
-impl Write for WavSink {
- fn write(&mut self, samples: &[u8]) -> io::Result<usize> {
- let sample_bytes = self.format.sample_bytes();
- if samples.len() % sample_bytes != 0 {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- format!(
- "u8 samples vector of length {} cannot be interpreted as {:?} samples",
- samples.len(),
- self.format
- ),
- ));
- }
- let num_samples = samples.len() / sample_bytes;
- match self.format {
- SampleFormat::U8 => {
- for sample in samples {
- self.wav_writer.write_sample(*sample as i8).map_err(|e| {
- io::Error::new(
- io::ErrorKind::Other,
- format!("Failed to write sample: {}", e),
- )
- })?;
- }
- }
- SampleFormat::S16LE => {
- // hound offers an optimized i16 writer, so special case here.
- let mut writer = self.wav_writer.get_i16_writer(num_samples as u32);
- for i in 0..num_samples {
- let sample = i16::from_le_bytes([
- samples[sample_bytes * i],
- samples[sample_bytes * i + 1],
- ]);
- writer.write_sample(sample);
- }
- // I16Writer buffers internally and must be explicitly flushed to write
- // samples to the backing writer. Flush is not called automatically
- // on drop.
- // The flush method only writes data from the i16_writer to the underlying
- // WavWriter, it does not actually guarantee a flush to disk.
- writer.flush().map_err(|e| {
- io::Error::new(
- io::ErrorKind::Other,
- format!("Failed to flush SampleWriter: {}", e),
- )
- })?;
- }
- SampleFormat::S24LE | SampleFormat::S32LE => {
- for i in 0..num_samples {
- let mut sample = i32::from_le_bytes([
- samples[sample_bytes * i],
- samples[sample_bytes * i + 1],
- samples[sample_bytes * i + 2],
- samples[sample_bytes * i + 3],
- ]);
-
- // Upsample to 32 bit since CRAS doesn't support S24_3LE.
- // Our wav encoder/decoder, hound, does have support for
- // S24_LE, but it hasn't released a new version since the
- // support was added. If getting that support is an issue,
- // push upstream to cut a new a release.
- if self.format == SampleFormat::S24LE {
- sample <<= 8;
- }
-
- self.wav_writer.write_sample(sample).map_err(|e| {
- io::Error::new(
- io::ErrorKind::Other,
- format!("Failed to write sample: {}", e),
- )
- })?;
- }
- }
- }
-
- Ok(samples.len())
- }
-
- fn flush(&mut self) -> io::Result<()> {
- self.wav_writer.flush().map_err(|e| {
- io::Error::new(
- io::ErrorKind::Other,
- format!("Failed to flush WavWriter: {}", e),
- )
- })
- }
-}
-
-pub fn capture(opts: AudioOptions) -> Result<()> {
- let num_channels = opts.num_channels.unwrap_or(2);
- let format = opts.format.unwrap_or(SampleFormat::S16LE);
- let frame_rate = opts.frame_rate.unwrap_or(48000);
- let buffer_size = opts.buffer_size.unwrap_or(256);
-
- let mut sample_sink: Box<dyn Write> = match opts.file_type {
- FileType::Raw => Box::new(BufWriter::new(
- File::create(&opts.file_name).map_err(Error::Io)?,
- )),
- FileType::Wav => Box::new(WavSink::try_new(
- &opts.file_name,
- num_channels,
- format,
- frame_rate,
- )?),
- };
-
- println!(
- "Recording {} '{}' : {}, Rate {} Hz, {}",
- opts.file_type,
- opts.file_name.display(),
- format,
- frame_rate,
- channel_string(num_channels)
- );
-
- let mut cras_client = CrasClient::new().map_err(Error::Libcras)?;
- cras_client.enable_cras_capture();
- let (_control, mut stream) = match opts.loopback_type {
- Some(loopback_type) => {
- let node_type = match loopback_type {
- LoopbackType::PreDsp => CrasNodeType::CRAS_NODE_TYPE_POST_MIX_PRE_DSP,
- LoopbackType::PostDsp => CrasNodeType::CRAS_NODE_TYPE_POST_DSP,
- };
-
- let loopback_node = cras_client
- .input_nodes()
- .find(|node| node.node_type == node_type)
- .ok_or(Error::NoLoopbackNode(node_type))?;
-
- cras_client
- .new_pinned_capture_stream(
- loopback_node.iodev_index,
- num_channels,
- format,
- frame_rate,
- buffer_size,
- )
- .map_err(Error::CreateStream)?
- }
- None => cras_client
- .new_capture_stream(num_channels, format, frame_rate, buffer_size)
- .map_err(Error::CreateStream)?,
- };
- set_priority_to_realtime();
- add_sigint_handler()?;
- while !INTERRUPTED.load(Ordering::Acquire) {
- let mut buf = stream.next_capture_buffer().map_err(Error::FetchStream)?;
- io::copy(&mut buf, &mut sample_sink).map_err(Error::Io)?;
- }
- Ok(())
-}
diff --git a/cras/client/cras_tests/src/control.rs b/cras/client/cras_tests/src/control.rs
deleted file mode 100644
index 3a98ec98..00000000
--- a/cras/client/cras_tests/src/control.rs
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-use std::error;
-use std::fmt;
-
-use libcras::{AudioDebugInfo, CrasClient, CrasIonodeInfo};
-
-use crate::arguments::ControlCommand;
-
-/// An enumeration of errors that can occur when running `ControlCommand` using
-/// the `control()` function.
-#[derive(Debug)]
-pub enum Error {
- Libcras(libcras::Error),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- Libcras(e) => write!(f, "Libcras Error: {}", e),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-fn print_nodes(nodes: impl Iterator<Item = CrasIonodeInfo>) {
- println!(
- "{: <13}{: <7}{: <6}{: <10}{: <13}{: <20} {: <10}",
- "Stable ID", "ID", "Vol", "Plugged", "Time", "Type", "Name"
- );
- for node in nodes {
- let id = format!("{}:{}", node.iodev_index, node.ionode_index);
- let stable_id = format!("({:08x})", node.stable_id);
- let plugged_time = node.plugged_time.tv_sec;
- let active = if node.active { "*" } else { " " };
- println!(
- "{: <13}{: <7}{: <6}{: <10}{: <13}{: <20}{}{: <10}",
- stable_id,
- id,
- node.volume,
- node.plugged,
- plugged_time,
- node.type_name,
- active,
- node.name
- );
- }
-}
-
-fn print_audio_debug_info(info: &AudioDebugInfo) {
- println!("Audio Debug Stats:");
- println!("-------------devices------------");
- for device in &info.devices {
- println!("{}", device);
- println!();
- }
-
- println!("-------------stream_dump------------");
- for stream in &info.streams {
- println!("{}", stream);
- println!();
- }
-}
-
-/// Connect to CRAS and run the given `ControlCommand`.
-pub fn control(command: ControlCommand) -> Result<()> {
- use ControlCommand::*;
- let mut cras_client = CrasClient::new().map_err(Error::Libcras)?;
- match command {
- GetSystemVolume => println!("{}", cras_client.get_system_volume()),
- SetSystemVolume(volume) => {
- cras_client
- .set_system_volume(volume)
- .map_err(Error::Libcras)?;
- }
- GetSystemMute => println!("{}", cras_client.get_system_mute()),
- SetSystemMute(mute) => {
- cras_client.set_system_mute(mute).map_err(Error::Libcras)?;
- }
- ListOutputDevices => {
- println!("{: <5}{: <10}", "ID", "Name");
- for dev in cras_client.output_devices() {
- println!("{: <5}{: <10}", dev.index, dev.name);
- }
- }
- ListInputDevices => {
- println!("{: <5}{: <10}", "ID", "Name");
- for dev in cras_client.input_devices() {
- println!("{: <5}{: <10}", dev.index, dev.name);
- }
- }
- ListOutputNodes => print_nodes(cras_client.output_nodes()),
- ListInputNodes => print_nodes(cras_client.input_nodes()),
- DumpAudioDebugInfo => {
- let debug_info = cras_client.get_audio_debug_info().map_err(Error::Libcras)?;
- print_audio_debug_info(&debug_info);
- }
- };
- Ok(())
-}
diff --git a/cras/client/cras_tests/src/main.rs b/cras/client/cras_tests/src/main.rs
deleted file mode 100644
index 50ffd090..00000000
--- a/cras/client/cras_tests/src/main.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-mod arguments;
-mod audio;
-mod control;
-
-use std::error;
-use std::fmt;
-
-use crate::arguments::Command;
-use crate::audio::{capture, playback};
-use crate::control::control;
-
-#[derive(Debug)]
-pub enum Error {
- Audio(audio::Error),
- ParseArgs(arguments::Error),
- Control(control::Error),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- Audio(e) => e.fmt(f),
- ParseArgs(e) => write!(f, "Failed to parse arguments: {}", e),
- Control(e) => e.fmt(f),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-fn run() -> Result<()> {
- let args: Vec<String> = std::env::args().collect();
- let command = match Command::parse(&args).map_err(Error::ParseArgs)? {
- None => return Ok(()),
- Some(v) => v,
- };
-
- match command {
- Command::Capture(audio_opts) => capture(audio_opts).map_err(Error::Audio),
- Command::Control(command) => control(command).map_err(Error::Control),
- Command::Playback(audio_opts) => playback(audio_opts).map_err(Error::Audio),
- }
-}
-
-fn main() {
- // Use run() instead of returning a Result from main() so that we can print
- // errors using Display instead of Debug.
- if let Err(e) = run() {
- eprintln!("{}", e);
- }
-}
diff --git a/cras/client/libcras/.gitignore b/cras/client/libcras/.gitignore
deleted file mode 100644
index fa8d85ac..00000000
--- a/cras/client/libcras/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Cargo.lock
-target
diff --git a/cras/client/libcras/.rustfmt.toml b/cras/client/libcras/.rustfmt.toml
deleted file mode 100644
index a2db3012..00000000
--- a/cras/client/libcras/.rustfmt.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-use_field_init_shorthand = true
-use_try_shorthand = true
diff --git a/cras/client/libcras/Android.bp b/cras/client/libcras/Android.bp
deleted file mode 100644
index aecb27a2..00000000
--- a/cras/client/libcras/Android.bp
+++ /dev/null
@@ -1,69 +0,0 @@
-// This file is generated by cargo2android.py --run --device --test --global_defaults=crosvm_defaults --dependencies.
-
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "external_adhd_license"
- // to get the below license kinds:
- // SPDX-license-identifier-BSD
- default_applicable_licenses: ["external_adhd_license"],
-}
-
-rust_defaults {
- name: "libcras_defaults",
- defaults: ["crosvm_defaults"],
- crate_name: "libcras",
- srcs: ["src/libcras.rs"],
- test_suites: ["general-tests"],
- auto_gen_config: true,
- edition: "2018",
- rustlibs: [
- "libaudio_streams",
- "libcras_sys",
- "libdata_model",
- "liblibc",
- "libsys_util",
- ],
-}
-
-rust_test_host {
- name: "libcras_host_test_src_libcras",
- defaults: ["libcras_defaults"],
-}
-
-rust_test {
- name: "libcras_device_test_src_libcras",
- defaults: ["libcras_defaults"],
-}
-
-rust_library {
- name: "liblibcras",
- defaults: ["crosvm_defaults"],
- host_supported: true,
- crate_name: "libcras",
- srcs: ["src/libcras.rs"],
- edition: "2018",
- rustlibs: [
- "libaudio_streams",
- "libcras_sys",
- "libdata_model",
- "liblibc",
- "libsys_util",
- ],
-}
-
-// dependent_library ["feature_list"]
-// ../../../../crosvm/assertions/src/lib.rs
-// ../../../../crosvm/data_model/src/lib.rs
-// ../../../../crosvm/sync/src/lib.rs
-// ../../../../crosvm/sys_util/poll_token_derive/poll_token_derive.rs
-// ../../../../crosvm/sys_util/src/lib.rs
-// ../../../../crosvm/syscall_defines/src/lib.rs
-// ../../../../crosvm/tempfile/src/lib.rs
-// ../../../audio_streams/src/audio_streams.rs
-// ../cras-sys/src/lib.rs
-// libc-0.2.76 "default,std"
-// proc-macro2-1.0.19 "default,proc-macro"
-// quote-1.0.7 "default,proc-macro"
-// syn-1.0.39 "clone-impls,default,derive,parsing,printing,proc-macro,quote"
-// unicode-xid-0.2.1 "default"
diff --git a/cras/client/libcras/Cargo.toml b/cras/client/libcras/Cargo.toml
deleted file mode 100644
index b52a2612..00000000
--- a/cras/client/libcras/Cargo.toml
+++ /dev/null
@@ -1,15 +0,0 @@
-[package]
-name = "libcras"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-
-[lib]
-path = "src/libcras.rs"
-
-[dependencies]
-audio_streams = { path = "../../../audio_streams" } # provided by ebuild
-libc = "*"
-cras-sys = { path = "../cras-sys" } # provided by ebuild
-data_model = { path = "../../../../crosvm/data_model" } # provided by ebuild
-sys_util = { path = "../../../../crosvm/sys_util" } # provided by ebuild
diff --git a/cras/client/libcras/src/audio_socket.rs b/cras/client/libcras/src/audio_socket.rs
deleted file mode 100644
index ac56144c..00000000
--- a/cras/client/libcras/src/audio_socket.rs
+++ /dev/null
@@ -1,316 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::io;
-use std::io::{Read, Write};
-use std::mem;
-use std::os::unix::{
- io::{AsRawFd, RawFd},
- net::UnixStream,
-};
-use std::time::Duration;
-
-use cras_sys::gen::{audio_message, CRAS_AUDIO_MESSAGE_ID};
-use data_model::DataInit;
-use sys_util::{PollContext, PollToken};
-
-/// A structure for interacting with the CRAS server audio thread through a `UnixStream::pair`.
-pub struct AudioSocket {
- socket: UnixStream,
-}
-
-/// Audio message results which are exchanged by `CrasStream` and CRAS audio server.
-/// through an audio socket.
-#[allow(dead_code)]
-#[derive(Debug)]
-pub enum AudioMessage {
- /// * `id` - Audio message id, which is a `enum CRAS_AUDIO_MESSAGE_ID`.
- /// * `frames` - A `u32` indicating the read or written frame count.
- Success {
- id: CRAS_AUDIO_MESSAGE_ID,
- frames: u32,
- },
- /// * `error` - Error code when a error occurs.
- Error(i32),
-}
-
-/// Converts AudioMessage to raw audio_message for CRAS audio server.
-impl Into<audio_message> for AudioMessage {
- fn into(self) -> audio_message {
- match self {
- AudioMessage::Success { id, frames } => audio_message {
- id,
- error: 0,
- frames,
- },
- AudioMessage::Error(error) => audio_message {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_REQUEST_DATA,
- error,
- frames: 0,
- },
- }
- }
-}
-
-/// Converts AudioMessage from raw audio_message from CRAS audio server.
-impl From<audio_message> for AudioMessage {
- fn from(message: audio_message) -> Self {
- match message.error {
- 0 => AudioMessage::Success {
- id: message.id as CRAS_AUDIO_MESSAGE_ID,
- frames: message.frames,
- },
- error => AudioMessage::Error(error),
- }
- }
-}
-
-impl AudioSocket {
- /// Creates `AudioSocket` from a `UnixStream`.
- ///
- /// # Arguments
- /// `socket` - A `UnixStream`.
- pub fn new(socket: UnixStream) -> Self {
- AudioSocket { socket }
- }
-
- fn read_from_socket<T>(&mut self) -> io::Result<T>
- where
- T: Sized + DataInit + Default,
- {
- let mut message: T = Default::default();
- let rc = self.socket.read(message.as_mut_slice())?;
- if rc == mem::size_of::<T>() {
- Ok(message)
- } else {
- Err(io::Error::new(io::ErrorKind::Other, "Read truncated data."))
- }
- }
-
- /// Blocks reading an `audio message`.
- ///
- /// # Returns
- /// `AudioMessage` - AudioMessage enum.
- ///
- /// # Errors
- /// Returns io::Error if error occurs.
- pub fn read_audio_message(&mut self) -> io::Result<AudioMessage> {
- match self.read_audio_message_with_timeout(None)? {
- None => Err(io::Error::new(io::ErrorKind::Other, "Unexpected exit")),
- Some(message) => Ok(message),
- }
- }
-
- /// Blocks waiting for an `audio message` until `timeout` occurs. If `timeout`
- /// is None, blocks indefinitely.
- ///
- /// # Returns
- /// Some(AudioMessage) - AudioMessage enum if we receive a message before timeout.
- /// None - If the timeout expires.
- ///
- /// # Errors
- /// Returns io::Error if error occurs.
- pub fn read_audio_message_with_timeout(
- &mut self,
- timeout: Option<Duration>,
- ) -> io::Result<Option<AudioMessage>> {
- #[derive(PollToken)]
- enum Token {
- AudioMsg,
- }
- let poll_ctx: PollContext<Token> =
- match PollContext::new().and_then(|pc| pc.add(self, Token::AudioMsg).and(Ok(pc))) {
- Ok(pc) => pc,
- Err(e) => {
- return Err(io::Error::new(
- io::ErrorKind::Other,
- format!("Failed to create PollContext: {}", e),
- ));
- }
- };
- let events = {
- let result = match timeout {
- None => poll_ctx.wait(),
- Some(duration) => poll_ctx.wait_timeout(duration),
- };
- match result {
- Ok(v) => v,
- Err(e) => {
- return Err(io::Error::new(
- io::ErrorKind::Other,
- format!("Failed to poll: {:?}", e),
- ));
- }
- }
- };
-
- // Check the first readable message
- let tokens: Vec<Token> = events.iter_readable().map(|e| e.token()).collect();
- match tokens.get(0) {
- None => Ok(None),
- Some(&Token::AudioMsg) => {
- let raw_msg: audio_message = self.read_from_socket()?;
- Ok(Some(AudioMessage::from(raw_msg)))
- }
- }
- }
-
- /// Sends raw audio message with given AudioMessage enum.
- ///
- /// # Arguments
- /// * `msg` - enum AudioMessage, which could be `Success` with message id
- /// and frames or `Error` with error code.
- ///
- /// # Errors
- /// Returns error if `libc::write` fails.
- fn send_audio_message(&mut self, msg: AudioMessage) -> io::Result<()> {
- let msg: audio_message = msg.into();
- let rc = self.socket.write(msg.as_slice())?;
- if rc < mem::size_of::<audio_message>() {
- Err(io::Error::new(io::ErrorKind::Other, "Sent truncated data."))
- } else {
- Ok(())
- }
- }
-
- /// Sends the data ready message with written frame count.
- ///
- /// # Arguments
- /// * `frames` - An `u32` indicating the written frame count.
- pub fn data_ready(&mut self, frames: u32) -> io::Result<()> {
- self.send_audio_message(AudioMessage::Success {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_DATA_READY,
- frames,
- })
- }
-
- /// Sends the capture ready message with read frame count.
- ///
- /// # Arguments
- ///
- /// * `frames` - An `u32` indicating the number of read frames.
- pub fn capture_ready(&mut self, frames: u32) -> io::Result<()> {
- self.send_audio_message(AudioMessage::Success {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_DATA_CAPTURED,
- frames,
- })
- }
-}
-
-impl AsRawFd for AudioSocket {
- fn as_raw_fd(&self) -> RawFd {
- self.socket.as_raw_fd()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- // PartialEq for comparing AudioMessage in tests
- impl PartialEq for AudioMessage {
- fn eq(&self, other: &Self) -> bool {
- match (self, other) {
- (
- AudioMessage::Success { id, frames },
- AudioMessage::Success {
- id: other_id,
- frames: other_frames,
- },
- ) => id == other_id && frames == other_frames,
- (AudioMessage::Error(err), AudioMessage::Error(other_err)) => err == other_err,
- _ => false,
- }
- }
- }
-
- fn init_audio_socket_pair() -> (AudioSocket, AudioSocket) {
- let (sock1, sock2) = UnixStream::pair().unwrap();
- let sender = AudioSocket::new(sock1);
- let receiver = AudioSocket::new(sock2);
- (sender, receiver)
- }
-
- #[test]
- fn audio_socket_send_and_recv_audio_message() {
- let (mut sender, mut receiver) = init_audio_socket_pair();
- let message_succ = AudioMessage::Success {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_REQUEST_DATA,
- frames: 0,
- };
- sender.send_audio_message(message_succ).unwrap();
- let res = receiver.read_audio_message().unwrap();
- assert_eq!(
- res,
- AudioMessage::Success {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_REQUEST_DATA,
- frames: 0
- }
- );
-
- let message_err = AudioMessage::Error(123);
- sender.send_audio_message(message_err).unwrap();
- let res = receiver.read_audio_message().unwrap();
- assert_eq!(res, AudioMessage::Error(123));
- }
-
- #[test]
- fn audio_socket_data_ready_send_and_recv() {
- let (sock1, sock2) = UnixStream::pair().unwrap();
- let mut audio_socket_send = AudioSocket::new(sock1);
- let mut audio_socket_recv = AudioSocket::new(sock2);
- audio_socket_send.data_ready(256).unwrap();
-
- // Test receiving by using raw audio_message since CRAS audio server use this.
- let audio_msg: audio_message = audio_socket_recv.read_from_socket().unwrap();
- let ref_audio_msg = audio_message {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_DATA_READY,
- error: 0,
- frames: 256,
- };
- // Use brace to copy unaligned data locally
- assert_eq!({ audio_msg.id }, { ref_audio_msg.id });
- assert_eq!({ audio_msg.error }, { ref_audio_msg.error });
- assert_eq!({ audio_msg.frames }, { ref_audio_msg.frames });
- }
-
- #[test]
- fn audio_socket_capture_ready() {
- let (sock1, sock2) = UnixStream::pair().unwrap();
- let mut audio_socket_send = AudioSocket::new(sock1);
- let mut audio_socket_recv = AudioSocket::new(sock2);
- audio_socket_send
- .capture_ready(256)
- .expect("Failed to send capture ready message.");
-
- // Test receiving by using raw audio_message since CRAS audio server use this.
- let audio_msg: audio_message = audio_socket_recv
- .read_from_socket()
- .expect("Failed to read audio message from AudioSocket.");
- let ref_audio_msg = audio_message {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_DATA_CAPTURED,
- error: 0,
- frames: 256,
- };
- // Use brace to copy unaligned data locally
- assert_eq!({ audio_msg.id }, { ref_audio_msg.id });
- assert_eq!({ audio_msg.error }, { ref_audio_msg.error });
- assert_eq!({ audio_msg.frames }, { ref_audio_msg.frames });
- }
-
- #[test]
- fn audio_socket_send_when_broken_pipe() {
- let sock1 = {
- let (sock1, _) = UnixStream::pair().unwrap();
- sock1
- };
- let mut audio_socket = AudioSocket::new(sock1);
- let res = audio_socket.data_ready(256);
- //Broken pipe
- assert_eq!(
- res.expect_err("Result should be an error.").kind(),
- io::Error::from_raw_os_error(32).kind(),
- "Error should be broken pipe.",
- );
- }
-}
diff --git a/cras/client/libcras/src/cras_client_message.rs b/cras/client/libcras/src/cras_client_message.rs
deleted file mode 100644
index c1c5ec5c..00000000
--- a/cras/client/libcras/src/cras_client_message.rs
+++ /dev/null
@@ -1,200 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::{array::TryFromSliceError, convert::TryInto, error, fmt, io, mem, os::unix::io::RawFd};
-
-use cras_sys::gen::{
- cras_client_connected, cras_client_message, cras_client_stream_connected,
- CRAS_CLIENT_MAX_MSG_SIZE,
- CRAS_CLIENT_MESSAGE_ID::{self, *},
-};
-use data_model::DataInit;
-use sys_util::ScmSocket;
-
-use crate::cras_server_socket::CrasServerSocket;
-use crate::cras_shm::*;
-use crate::cras_stream;
-
-#[derive(Debug)]
-pub enum Error {
- IoError(io::Error),
- SysUtilError(sys_util::Error),
- CrasStreamError(cras_stream::Error),
- ArrayTryFromSliceError(TryFromSliceError),
- InvalidSize,
- MessageTypeError,
- MessageNumFdError,
- MessageTruncated,
- MessageIdError,
- MessageFromSliceError,
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Error::IoError(ref err) => err.fmt(f),
- Error::SysUtilError(ref err) => err.fmt(f),
- Error::MessageTypeError => write!(f, "Message type error"),
- Error::CrasStreamError(ref err) => err.fmt(f),
- Error::ArrayTryFromSliceError(ref err) => err.fmt(f),
- Error::MessageNumFdError => write!(f, "Message the number of fds is not matched"),
- Error::MessageTruncated => write!(f, "Read truncated message"),
- Error::MessageIdError => write!(f, "No such id"),
- Error::MessageFromSliceError => write!(f, "Message from slice error"),
- Error::InvalidSize => write!(f, "Invalid data size"),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-impl From<io::Error> for Error {
- fn from(io_err: io::Error) -> Self {
- Error::IoError(io_err)
- }
-}
-
-impl From<sys_util::Error> for Error {
- fn from(sys_util_err: sys_util::Error) -> Self {
- Error::SysUtilError(sys_util_err)
- }
-}
-
-impl From<cras_stream::Error> for Error {
- fn from(err: cras_stream::Error) -> Self {
- Error::CrasStreamError(err)
- }
-}
-
-impl From<TryFromSliceError> for Error {
- fn from(err: TryFromSliceError) -> Self {
- Error::ArrayTryFromSliceError(err)
- }
-}
-
-/// A handled server result from one message sent from CRAS server.
-pub enum ServerResult {
- /// client_id, CrasServerStateShmFd
- Connected(u32, CrasServerStateShmFd),
- /// stream_id, header_fd, samples_fd
- StreamConnected(u32, CrasAudioShmHeaderFd, CrasShmFd),
- DebugInfoReady,
-}
-
-impl ServerResult {
- /// Reads and handles one server message and converts `CrasClientMessage` into `ServerResult`
- /// with error handling.
- ///
- /// # Arguments
- /// * `server_socket`: A reference to `CrasServerSocket`.
- pub fn handle_server_message(server_socket: &CrasServerSocket) -> Result<ServerResult> {
- let message = CrasClientMessage::try_new(&server_socket)?;
- match message.get_id()? {
- CRAS_CLIENT_MESSAGE_ID::CRAS_CLIENT_CONNECTED => {
- let cmsg: &cras_client_connected = message.get_message()?;
- // CRAS server should return a shared memory area which contains
- // `cras_server_state`.
- let server_state_fd = unsafe { CrasServerStateShmFd::new(message.fds[0]) };
- Ok(ServerResult::Connected(cmsg.client_id, server_state_fd))
- }
- CRAS_CLIENT_MESSAGE_ID::CRAS_CLIENT_STREAM_CONNECTED => {
- let cmsg: &cras_client_stream_connected = message.get_message()?;
- // CRAS should return two shared memory areas the first which has
- // mem::size_of::<cras_audio_shm_header>() bytes, and the second which has
- // `samples_shm_size` bytes.
- Ok(ServerResult::StreamConnected(
- cmsg.stream_id,
- // Safe because CRAS ensures that the first fd contains a cras_audio_shm_header
- unsafe { CrasAudioShmHeaderFd::new(message.fds[0]) },
- // Safe because CRAS ensures that the second fd has length 'samples_shm_size'
- unsafe { CrasShmFd::new(message.fds[1], cmsg.samples_shm_size as usize) },
- ))
- }
- CRAS_CLIENT_MESSAGE_ID::CRAS_CLIENT_AUDIO_DEBUG_INFO_READY => {
- Ok(ServerResult::DebugInfoReady)
- }
- _ => Err(Error::MessageTypeError),
- }
- }
-}
-
-// A structure for raw message with fds from CRAS server.
-struct CrasClientMessage {
- fds: [RawFd; 2],
- data: [u8; CRAS_CLIENT_MAX_MSG_SIZE as usize],
- len: usize,
-}
-
-/// The default constructor won't be used outside of this file and it's an optimization to prevent
-/// having to copy the message data from a temp buffer.
-impl Default for CrasClientMessage {
- // Initializes fields with default values.
- fn default() -> Self {
- Self {
- fds: [-1; 2],
- data: [0; CRAS_CLIENT_MAX_MSG_SIZE as usize],
- len: 0,
- }
- }
-}
-
-impl CrasClientMessage {
- // Reads a message from server_socket and checks validity of the read result
- fn try_new(server_socket: &CrasServerSocket) -> Result<CrasClientMessage> {
- let mut message: Self = Default::default();
- let (len, fd_nums) = server_socket.recv_with_fds(&mut message.data, &mut message.fds)?;
-
- if len < mem::size_of::<cras_client_message>() {
- Err(Error::MessageTruncated)
- } else {
- message.len = len;
- message.check_fd_nums(fd_nums)?;
- Ok(message)
- }
- }
-
- // Check if `fd nums` of a read result is valid
- fn check_fd_nums(&self, fd_nums: usize) -> Result<()> {
- match self.get_id()? {
- CRAS_CLIENT_CONNECTED => match fd_nums {
- 1 => Ok(()),
- _ => Err(Error::MessageNumFdError),
- },
- CRAS_CLIENT_STREAM_CONNECTED => match fd_nums {
- // CRAS should return two shared memory areas the first which has
- // mem::size_of::<cras_audio_shm_header>() bytes, and the second which has
- // `samples_shm_size` bytes.
- 2 => Ok(()),
- _ => Err(Error::MessageNumFdError),
- },
- CRAS_CLIENT_AUDIO_DEBUG_INFO_READY => match fd_nums {
- 0 => Ok(()),
- _ => Err(Error::MessageNumFdError),
- },
- _ => Err(Error::MessageTypeError),
- }
- }
-
- // Gets the message id
- fn get_id(&self) -> Result<CRAS_CLIENT_MESSAGE_ID> {
- let offset = mem::size_of::<u32>();
- match u32::from_le_bytes(self.data[offset..offset + 4].try_into()?) {
- id if id == (CRAS_CLIENT_CONNECTED as u32) => Ok(CRAS_CLIENT_CONNECTED),
- id if id == (CRAS_CLIENT_STREAM_CONNECTED as u32) => Ok(CRAS_CLIENT_STREAM_CONNECTED),
- id if id == (CRAS_CLIENT_AUDIO_DEBUG_INFO_READY as u32) => {
- Ok(CRAS_CLIENT_AUDIO_DEBUG_INFO_READY)
- }
- _ => Err(Error::MessageIdError),
- }
- }
-
- // Gets a reference to the message content
- fn get_message<T: DataInit>(&self) -> Result<&T> {
- if self.len != mem::size_of::<T>() {
- return Err(Error::InvalidSize);
- }
- T::from_slice(&self.data[..mem::size_of::<T>()]).ok_or(Error::MessageFromSliceError)
- }
-}
diff --git a/cras/client/libcras/src/cras_server_socket.rs b/cras/client/libcras/src/cras_server_socket.rs
deleted file mode 100644
index 4a7d9151..00000000
--- a/cras/client/libcras/src/cras_server_socket.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::os::unix::io::{AsRawFd, RawFd};
-use std::{io, mem};
-
-use cras_sys::gen::{cras_disconnect_stream_message, cras_server_message, CRAS_SERVER_MESSAGE_ID};
-use sys_util::{net::UnixSeqpacket, ScmSocket};
-
-use data_model::DataInit;
-
-/// Server socket type to connect.
-pub enum CrasSocketType {
- /// A server socket type supports only playback function.
- Legacy,
- /// A server socket type supports both playback and capture functions.
- Unified,
-}
-
-impl CrasSocketType {
- fn sock_path(&self) -> &str {
- match self {
- Self::Legacy => "/run/cras/.cras_socket",
- Self::Unified => "/run/cras/.cras_unified",
- }
- }
-}
-
-/// A socket connecting to the CRAS audio server.
-pub struct CrasServerSocket {
- socket: UnixSeqpacket,
-}
-
-impl CrasServerSocket {
- pub fn new() -> io::Result<CrasServerSocket> {
- Self::with_type(CrasSocketType::Legacy)
- }
-
- /// Creates a `CrasServerSocket` with given `CrasSocketType`.
- ///
- /// # Errors
- ///
- /// Returns the `io::Error` generated when connecting to the socket on failure.
- pub fn with_type(socket_type: CrasSocketType) -> io::Result<CrasServerSocket> {
- Ok(CrasServerSocket {
- socket: UnixSeqpacket::connect(socket_type.sock_path())?,
- })
- }
-
- /// Sends a sized and packed server messge to the server socket. The message
- /// must implement `Sized` and `DataInit`.
- /// # Arguments
- /// * `message` - A sized and packed message.
- /// * `fds` - A slice of fds to send.
- ///
- /// # Returns
- /// * Length of written bytes in `usize`.
- ///
- /// # Errors
- /// Return error if the socket fails to write message to server.
- pub fn send_server_message_with_fds<M: Sized + DataInit>(
- &self,
- message: &M,
- fds: &[RawFd],
- ) -> io::Result<usize> {
- match fds.len() {
- 0 => self.socket.send(message.as_slice()),
- _ => {
- let ioslice = io::IoSlice::new(message.as_slice());
- match self.send_with_fds(&[ioslice], fds) {
- Ok(len) => Ok(len),
- Err(err) => Err(io::Error::new(io::ErrorKind::Other, format!("{}", err))),
- }
- }
- }
- }
-
- /// Creates a clone of the underlying socket. The returned clone can also be
- /// used to communicate with the cras server.
- pub fn try_clone(&self) -> io::Result<CrasServerSocket> {
- let new_sock = self.socket.try_clone()?;
- Ok(CrasServerSocket { socket: new_sock })
- }
-
- /// Send a message to request disconnection of the given stream.
- ///
- /// Builds a `cras_disconnect_stream_message` containing `stream_id` and
- /// sends it to the server.
- /// No response is expected.
- ///
- /// # Arguments
- ///
- /// * `stream_id` - The id of the stream that should be disconnected.
- ///
- /// # Errors
- ///
- /// * If the message was not written to the server socket successfully.
- pub fn disconnect_stream(&self, stream_id: u32) -> io::Result<()> {
- let msg_header = cras_server_message {
- length: mem::size_of::<cras_disconnect_stream_message>() as u32,
- id: CRAS_SERVER_MESSAGE_ID::CRAS_SERVER_DISCONNECT_STREAM,
- };
- let server_cmsg = cras_disconnect_stream_message {
- header: msg_header,
- stream_id,
- };
- self.send_server_message_with_fds(&server_cmsg, &[])
- .map(|_| ())
- }
-}
-
-// For using `recv_with_fds` and `send_with_fds`.
-impl ScmSocket for CrasServerSocket {
- fn socket_fd(&self) -> RawFd {
- self.socket.as_raw_fd()
- }
-}
-
-// For using `PollContex`.
-impl AsRawFd for CrasServerSocket {
- fn as_raw_fd(&self) -> RawFd {
- self.socket.as_raw_fd()
- }
-}
diff --git a/cras/client/libcras/src/cras_shm.rs b/cras/client/libcras/src/cras_shm.rs
deleted file mode 100644
index 05533753..00000000
--- a/cras/client/libcras/src/cras_shm.rs
+++ /dev/null
@@ -1,1308 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::convert::TryFrom;
-use std::io;
-use std::mem;
-use std::os::unix::io::{AsRawFd, RawFd};
-use std::ptr;
-use std::ptr::NonNull;
-use std::slice;
-use std::sync::atomic::{self, Ordering};
-use std::thread;
-
-use cras_sys::gen::{
- audio_dev_debug_info, audio_stream_debug_info, cras_audio_shm_header, cras_iodev_info,
- cras_ionode_info, cras_server_state, CRAS_MAX_IODEVS, CRAS_MAX_IONODES, CRAS_NUM_SHM_BUFFERS,
- CRAS_SERVER_STATE_VERSION, CRAS_SHM_BUFFERS_MASK, MAX_DEBUG_DEVS, MAX_DEBUG_STREAMS,
-};
-use cras_sys::{
- AudioDebugInfo, AudioDevDebugInfo, AudioStreamDebugInfo, CrasIodevInfo, CrasIonodeInfo,
-};
-use data_model::{VolatileRef, VolatileSlice};
-use sys_util::warn;
-
-/// A structure wrapping a fd which contains a shared `cras_audio_shm_header`.
-/// * `shm_fd` - A shared memory fd contains a `cras_audio_shm_header`
-pub struct CrasAudioShmHeaderFd {
- fd: CrasShmFd,
-}
-
-impl CrasAudioShmHeaderFd {
- /// Creates a `CrasAudioShmHeaderFd` by shared memory fd
- /// # Arguments
- /// * `fd` - A shared memory file descriptor, which will be owned by the resulting structure and
- /// the fd will be closed on drop.
- ///
- /// # Returns
- /// A structure wrapping a `CrasShmFd` with the input fd and `size` which equals to
- /// the size of `cras_audio_shm_header`.
- ///
- /// To use this function safely, we need to make sure
- /// - The input fd is a valid shared memory fd.
- /// - The input shared memory fd won't be used by others.
- /// - The shared memory area in the input fd contains a `cras_audio_shm_header`.
- pub unsafe fn new(fd: libc::c_int) -> Self {
- Self {
- fd: CrasShmFd::new(fd, mem::size_of::<cras_audio_shm_header>()),
- }
- }
-}
-
-/// A wrapper for the raw structure `cras_audio_shm_header` with
-/// size information for the separate audio samples shm area and several
-/// `VolatileRef` to sub fields for safe access to the header.
-pub struct CrasAudioHeader<'a> {
- addr: *mut libc::c_void,
- /// Size of the buffer for samples in CrasAudioBuffer
- samples_len: usize,
- used_size: VolatileRef<'a, u32>,
- frame_size: VolatileRef<'a, u32>,
- read_buf_idx: VolatileRef<'a, u32>,
- write_buf_idx: VolatileRef<'a, u32>,
- read_offset: [VolatileRef<'a, u32>; CRAS_NUM_SHM_BUFFERS as usize],
- write_offset: [VolatileRef<'a, u32>; CRAS_NUM_SHM_BUFFERS as usize],
- buffer_offset: [VolatileRef<'a, u64>; CRAS_NUM_SHM_BUFFERS as usize],
-}
-
-// It is safe to send audio buffers between threads as this struct has exclusive ownership of the
-// pointers contained in it.
-unsafe impl<'a> Send for CrasAudioHeader<'a> {}
-
-/// An unsafe macro for getting `VolatileRef` for a field from a given NonNull pointer.
-/// It Supports
-/// - Nested sub-field
-/// - Element of an array field
-///
-/// To use this macro safely, we need to
-/// - Make sure the pointer address is readable and writable for its structure.
-/// - Make sure all `VolatileRef`s generated from this macro have exclusive ownership for the same
-/// pointer.
-#[macro_export]
-macro_rules! vref_from_addr {
- ($addr:ident, $($field:ident).*) => {
- VolatileRef::new(&mut $addr.as_mut().$($field).* as *mut _)
- };
-
- ($addr:ident, $field:ident[$idx:tt]) => {
- VolatileRef::new(&mut $addr.as_mut().$field[$idx] as *mut _)
- };
-}
-
-// Generates error when an index is out of range.
-fn index_out_of_range() -> io::Error {
- io::Error::new(io::ErrorKind::InvalidInput, "Index out of range.")
-}
-
-impl<'a> CrasAudioHeader<'a> {
- // Creates a `CrasAudioHeader` with given `CrasAudioShmHeaderFd` and `samples_len`
- fn new(header_fd: CrasAudioShmHeaderFd, samples_len: usize) -> io::Result<Self> {
- // Safe because the creator of CrasAudioShmHeaderFd already
- // ensured that header_fd contains a cras_audio_shm_header.
- let mmap_addr = unsafe {
- cras_mmap(
- header_fd.fd.size,
- libc::PROT_READ | libc::PROT_WRITE,
- header_fd.fd.as_raw_fd(),
- )?
- };
-
- let mut addr = NonNull::new(mmap_addr as *mut cras_audio_shm_header)
- .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "Failed to create header."))?;
-
- // Safe because we know that mmap_addr (contained in addr) contains a
- // cras_audio_shm_header, and the mapped area will be exclusively
- // owned by this struct.
- unsafe {
- Ok(CrasAudioHeader {
- addr: addr.as_ptr() as *mut libc::c_void,
- samples_len,
- used_size: vref_from_addr!(addr, config.used_size),
- frame_size: vref_from_addr!(addr, config.frame_bytes),
- read_buf_idx: vref_from_addr!(addr, read_buf_idx),
- write_buf_idx: vref_from_addr!(addr, write_buf_idx),
- read_offset: [
- vref_from_addr!(addr, read_offset[0]),
- vref_from_addr!(addr, read_offset[1]),
- ],
- write_offset: [
- vref_from_addr!(addr, write_offset[0]),
- vref_from_addr!(addr, write_offset[1]),
- ],
- buffer_offset: [
- vref_from_addr!(addr, buffer_offset[0]),
- vref_from_addr!(addr, buffer_offset[1]),
- ],
- })
- }
- }
-
- /// Calculates the length of a buffer with the given offset. This length will
- /// be `used_size`, unless the offset is closer than `used_size` to the end
- /// of samples, in which case the length will be as long as possible.
- ///
- /// If that buffer length is invalid (too small to hold a frame of audio data),
- /// then returns an error.
- /// The returned buffer length will be rounded down to a multiple of `frame_size`.
- fn buffer_len_from_offset(&self, offset: usize) -> io::Result<usize> {
- if offset > self.samples_len {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- format!(
- "Buffer offset {} exceeds the length of samples area ({}).",
- offset, self.samples_len
- ),
- ));
- }
-
- let used_size = self.get_used_size();
- let frame_size = self.get_frame_size();
-
- // We explicitly allow a buffer shorter than used_size, but only
- // at the end of the samples area.
- // This is useful if we're playing a file where the number of samples is
- // not a multiple of used_size (meaning the length of the samples area
- // won't be either). Then, the last buffer played will be smaller than
- // used_size.
- let mut buffer_length = used_size.min(self.samples_len - offset);
- if buffer_length < frame_size {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- format!(
- "Buffer offset {} gives buffer length {} smaller than frame size {}.",
- offset, buffer_length, frame_size
- ),
- ));
- }
-
- // Round buffer_length down to a multiple of frame size
- buffer_length = buffer_length / frame_size * frame_size;
- Ok(buffer_length)
- }
-
- /// Gets the base of the write buffer and the writable length (rounded to `frame_size`).
- /// Does not take into account the write offset.
- ///
- /// # Returns
- ///
- /// * (`usize`, `usize`) - write buffer base as an offset from the start of
- /// the samples area and buffer length in bytes.
- pub fn get_write_offset_and_len(&self) -> io::Result<(usize, usize)> {
- let idx = self.get_write_buf_idx() as usize;
- let offset = self.get_buffer_offset(idx)?;
- let len = self.buffer_len_from_offset(offset)?;
-
- Ok((offset, len))
- }
-
- /// Gets the buffer offset of the read buffer.
- ///
- /// # Returns
- ///
- /// * `usize` - read offset in bytes
- pub fn get_read_buffer_offset(&self) -> io::Result<usize> {
- let idx = self.get_read_buf_idx() as usize;
- self.get_buffer_offset(idx)
- }
-
- /// Gets the offset of a buffer from the start of samples.
- ///
- /// # Arguments
- /// `index` - 0 <= `index` < `CRAS_NUM_SHM_BUFFERS`. The index of the buffer
- /// for which we want the `buffer_offset`.
- ///
- /// # Returns
- /// * `usize` - buffer offset in bytes
- fn get_buffer_offset(&self, idx: usize) -> io::Result<usize> {
- let buffer_offset = self
- .buffer_offset
- .get(idx)
- .ok_or_else(index_out_of_range)?
- .load() as usize;
- self.check_buffer_offset(idx, buffer_offset)?;
- Ok(buffer_offset)
- }
-
- /// Gets the number of bytes per frame from the shared memory structure.
- ///
- /// # Returns
- ///
- /// * `usize` - Number of bytes per frame
- pub fn get_frame_size(&self) -> usize {
- self.frame_size.load() as usize
- }
-
- /// Gets the max size in bytes of each shared memory buffer within
- /// the samples area.
- ///
- /// # Returns
- ///
- /// * `usize` - Value of `used_size` fetched from the shared memory header.
- pub fn get_used_size(&self) -> usize {
- self.used_size.load() as usize
- }
-
- /// Gets the index of the current written buffer.
- ///
- /// # Returns
- /// `u32` - the returned index is less than `CRAS_NUM_SHM_BUFFERS`.
- fn get_write_buf_idx(&self) -> u32 {
- self.write_buf_idx.load() & CRAS_SHM_BUFFERS_MASK
- }
-
- fn get_read_buf_idx(&self) -> u32 {
- self.read_buf_idx.load() & CRAS_SHM_BUFFERS_MASK
- }
-
- /// Switches the written buffer.
- fn switch_write_buf_idx(&mut self) {
- self.write_buf_idx
- .store(self.get_write_buf_idx() as u32 ^ 1u32)
- }
-
- /// Switches the buffer to read.
- fn switch_read_buf_idx(&mut self) {
- self.read_buf_idx
- .store(self.get_read_buf_idx() as u32 ^ 1u32)
- }
-
- /// Checks if the offset value for setting write_offset or read_offset is
- /// out of range or not.
- ///
- /// # Arguments
- /// `idx` - The index of the buffer for which we're checking the offset.
- /// `offset` - 0 <= `offset` <= `used_size` && `buffer_offset[idx]` + `offset` <=
- /// `samples_len`. Writable or readable size equals to 0 when offset equals
- /// to `used_size`.
- ///
- /// # Errors
- /// Returns an error if `offset` is out of range or if idx is not a valid
- /// buffer idx.
- fn check_rw_offset(&self, idx: usize, offset: u32) -> io::Result<()> {
- let buffer_len = self.buffer_len_from_offset(self.get_buffer_offset(idx)?)?;
- if offset as usize > buffer_len {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- format!(
- "Offset {} is larger than buffer size {}.",
- offset, buffer_len
- ),
- ));
- }
-
- Ok(())
- }
-
- /// Sets `write_offset[idx]` to the count of written bytes.
- ///
- /// # Arguments
- /// `idx` - 0 <= `idx` < `CRAS_NUM_SHM_BUFFERS`
- /// `offset` - 0 <= `offset` <= `used_size` && `offset` + `used_size` <=
- /// `samples_len`. Writable size equals to 0 when offset equals to
- /// `used_size`.
- ///
- /// # Errors
- /// Returns an error if `offset` is out of range.
- fn set_write_offset(&mut self, idx: usize, offset: u32) -> io::Result<()> {
- self.check_rw_offset(idx, offset)?;
- let write_offset = self.write_offset.get(idx).ok_or_else(index_out_of_range)?;
- write_offset.store(offset);
- Ok(())
- }
-
- /// Sets `read_offset[idx]` to count of written bytes.
- ///
- /// # Arguments
- /// `idx` - 0 <= `idx` < `CRAS_NUM_SHM_BUFFERS`
- /// `offset` - 0 <= `offset` <= `used_size` && `offset` + `used_size` <=
- /// `samples_len`. Readable size equals to 0 when offset equals to
- /// `used_size`.
- ///
- /// # Errors
- /// Returns error if index out of range.
- fn set_read_offset(&mut self, idx: usize, offset: u32) -> io::Result<()> {
- self.check_rw_offset(idx, offset)?;
- let read_offset = self.read_offset.get(idx).ok_or_else(index_out_of_range)?;
- read_offset.store(offset);
- Ok(())
- }
-
- /// Check that `offset` is a valid buffer offset for the buffer at `idx`
- /// An offset is not valid if it is
- /// * outside of the samples area
- /// * overlaps some other buffer `[other_offset, other_offset + used_size)`
- /// * is close enough to the end of the samples area that the buffer would
- /// be shorter than `frame_size`.
- fn check_buffer_offset(&self, idx: usize, offset: usize) -> io::Result<()> {
- let start = offset;
- let end = start + self.buffer_len_from_offset(start)?;
-
- let other_idx = (idx ^ 1) as usize;
- let other_start = self
- .buffer_offset
- .get(other_idx)
- .ok_or_else(index_out_of_range)?
- .load() as usize;
- let other_end = other_start + self.buffer_len_from_offset(other_start)?;
- if start < other_end && other_start < end {
- // Special case: occasionally we get the same buffer offset twice
- // from the intel8x0 kernel driver in crosvm's AC97 device, and we
- // don't want to crash in that case.
- if start == other_start && end == other_end {
- warn!(
- "Setting buffer {} to same index/offset as buffer {}, [{}, {})",
- idx, other_idx, other_start, other_end
- );
- } else {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- format!(
- "Setting buffer {} to [{}, {}) overlaps buffer {} at [{}, {})",
- idx, start, end, other_idx, other_start, other_end,
- ),
- ));
- }
- }
- Ok(())
- }
-
- /// Sets the location of the audio buffer `idx` within the samples area to
- /// `offset`, so that CRAS will read/write samples for that buffer from that
- /// offset.
- ///
- /// # Arguments
- /// `idx` - 0 <= `idx` < `CRAS_NUM_SHM_BUFFERS`
- /// `offset` - 0 <= `offset` && `offset` + `frame_size` <= `samples_len`
- ///
- /// # Errors
- /// If `idx` is out of range
- /// If the offset is invalid, which can happen if `offset` is
- /// * outside of the samples area
- /// * overlaps some other buffer `[other_offset, other_offset + used_size)`
- /// * is close enough to the end of the samples area that the buffer would
- /// be shorter than `frame_size`.
- pub fn set_buffer_offset(&mut self, idx: usize, offset: usize) -> io::Result<()> {
- self.check_buffer_offset(idx, offset)?;
-
- let buffer_offset = self.buffer_offset.get(idx).ok_or_else(index_out_of_range)?;
- buffer_offset.store(offset as u64);
- Ok(())
- }
-
- /// Commits written frames by switching the current buffer to the other one
- /// after samples are ready and indexes of current buffer are all set.
- /// - Sets `write_offset` of current buffer to `frame_count * frame_size`
- /// - Sets `read_offset` of current buffer to `0`.
- ///
- /// # Arguments
- ///
- /// * `frame_count` - Number of frames written to the current buffer
- ///
- /// # Errors
- ///
- /// * Returns error if `frame_count` is larger than buffer size
- ///
- /// This function is safe because we switch `write_buf_idx` after letting
- /// `write_offset` and `read_offset` ready and we read / write shared memory
- /// variables with volatile operations.
- pub fn commit_written_frames(&mut self, frame_count: u32) -> io::Result<()> {
- // Uses `u64` to prevent possible overflow
- let byte_count = frame_count as u64 * self.get_frame_size() as u64;
- if byte_count > self.get_used_size() as u64 {
- Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- "frame_count * frame_size is larger than used_size",
- ))
- } else {
- let idx = self.get_write_buf_idx() as usize;
- // Sets `write_offset` of current buffer to frame_count * frame_size
- self.set_write_offset(idx, byte_count as u32)?;
- // Sets `read_offset` of current buffer to `0`.
- self.set_read_offset(idx, 0)?;
- // Switch to the other buffer
- self.switch_write_buf_idx();
- Ok(())
- }
- }
-
- /// Get readable frames in current buffer.
- ///
- /// # Returns
- ///
- /// * `usize` - number of readable frames.
- ///
- /// # Errors
- ///
- /// Returns error if index out of range.
- pub fn get_readable_frames(&self) -> io::Result<usize> {
- let idx = self.get_read_buf_idx() as usize;
- let read_offset = self.read_offset.get(idx).ok_or_else(index_out_of_range)?;
- let write_offset = self.write_offset.get(idx).ok_or_else(index_out_of_range)?;
- let nframes =
- (write_offset.load() as i32 - read_offset.load() as i32) / self.get_frame_size() as i32;
- if nframes < 0 {
- Ok(0)
- } else {
- Ok(nframes as usize)
- }
- }
-
- /// Commit read frames from reader, .
- /// - Sets `read_offset` of current buffer to `read_offset + frame_count * frame_size`.
- /// If `read_offset` is larger than or equal to `write_offset`, then
- /// - Sets `read_offset` and `write_offset` to `0` and switch `read_buf_idx`.
- ///
- /// # Arguments
- ///
- /// * `frame_count` - Read frames in current read buffer.
- ///
- /// # Errors
- ///
- /// Returns error if index out of range.
- pub fn commit_read_frames(&mut self, frame_count: u32) -> io::Result<()> {
- let idx = self.get_read_buf_idx() as usize;
- let read_offset = self.read_offset.get(idx).ok_or_else(index_out_of_range)?;
- let write_offset = self.write_offset.get(idx).ok_or_else(index_out_of_range)?;
- read_offset.store(read_offset.load() + frame_count * self.get_frame_size() as u32);
- if read_offset.load() >= write_offset.load() {
- read_offset.store(0);
- write_offset.store(0);
- self.switch_read_buf_idx();
- }
- Ok(())
- }
-}
-
-impl<'a> Drop for CrasAudioHeader<'a> {
- fn drop(&mut self) {
- // Safe because all references must be gone by the time drop is called.
- unsafe {
- libc::munmap(self.addr as *mut _, mem::size_of::<cras_audio_shm_header>());
- }
- }
-}
-
-// To use this safely, we need to make sure
-// - The given fd contains valid space which is larger than `len` + `offset`
-unsafe fn cras_mmap_offset(
- len: usize,
- prot: libc::c_int,
- fd: libc::c_int,
- offset: usize,
-) -> io::Result<*mut libc::c_void> {
- if offset > libc::off_t::max_value() as usize {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput,
- "Requested offset is out of range of `libc::off_t`.",
- ));
- }
- // It's safe because we handle its returned results.
- match libc::mmap(
- ptr::null_mut(),
- len,
- prot,
- libc::MAP_SHARED,
- fd,
- offset as libc::off_t,
- ) {
- libc::MAP_FAILED => Err(io::Error::last_os_error()),
- shm_ptr => Ok(shm_ptr),
- }
-}
-
-// To use this safely, we need to make sure
-// - The given fd contains valid space which is larger than `len`
-unsafe fn cras_mmap(
- len: usize,
- prot: libc::c_int,
- fd: libc::c_int,
-) -> io::Result<*mut libc::c_void> {
- cras_mmap_offset(len, prot, fd, 0)
-}
-
-/// An unsafe macro for getting a `VolatileSlice` representing an entire array
-/// field from a given NonNull pointer.
-///
-/// To use this macro safely, we need to
-/// - Make sure the pointer address is readable and writeable for its struct.
-/// - Make sure all `VolatileSlice`s generated from this macro have exclusive ownership for the same
-/// pointer.
-/// - Make sure the length of the array field is non-zero.
-#[macro_export]
-macro_rules! vslice_from_addr {
- ($addr:ident, $($field:ident).*) => {{
- let ptr = &mut $addr.as_mut().$($field).* as *mut _ as *mut u8;
- let size = std::mem::size_of_val(&$addr.as_mut().$($field).*);
- VolatileSlice::from_raw_parts(ptr, size)
- }};
-}
-
-/// A structure that points to RO shared memory area - `cras_server_state`
-/// The structure is created from a shared memory fd which contains the structure.
-#[derive(Debug)]
-pub struct CrasServerState<'a> {
- addr: *mut libc::c_void,
- volume: VolatileRef<'a, u32>,
- mute: VolatileRef<'a, i32>,
- num_output_devs: VolatileRef<'a, u32>,
- output_devs: VolatileSlice<'a>,
- num_input_devs: VolatileRef<'a, u32>,
- input_devs: VolatileSlice<'a>,
- num_output_nodes: VolatileRef<'a, u32>,
- num_input_nodes: VolatileRef<'a, u32>,
- output_nodes: VolatileSlice<'a>,
- input_nodes: VolatileSlice<'a>,
- update_count: VolatileRef<'a, u32>,
- debug_info_num_devs: VolatileRef<'a, u32>,
- debug_info_devs: VolatileSlice<'a>,
- debug_info_num_streams: VolatileRef<'a, u32>,
- debug_info_streams: VolatileSlice<'a>,
-}
-
-// It is safe to send server_state between threads as this struct has exclusive
-// ownership of the shared memory area contained in it.
-unsafe impl<'a> Send for CrasServerState<'a> {}
-
-impl<'a> CrasServerState<'a> {
- /// Create a CrasServerState
- pub fn try_new(state_fd: CrasServerStateShmFd) -> io::Result<Self> {
- // Safe because the creator of CrasServerStateShmFd already
- // ensured that state_fd contains a cras_server_state.
- let mmap_addr =
- unsafe { cras_mmap(state_fd.fd.size, libc::PROT_READ, state_fd.fd.as_raw_fd())? };
-
- let mut addr = NonNull::new(mmap_addr as *mut cras_server_state).ok_or_else(|| {
- io::Error::new(io::ErrorKind::Other, "Failed to create CrasServerState.")
- })?;
-
- // Safe because we know that addr is a non-null pointer to cras_server_state.
- let state_version = unsafe { vref_from_addr!(addr, state_version) };
- if state_version.load() != CRAS_SERVER_STATE_VERSION {
- return Err(io::Error::new(
- io::ErrorKind::Other,
- format!(
- "CrasServerState version {} does not match expected version {}",
- state_version.load(),
- CRAS_SERVER_STATE_VERSION
- ),
- ));
- }
-
- // Safe because we know that mmap_addr (contained in addr) contains a
- // cras_server_state, and the mapped area will be exclusively
- // owned by this struct.
- unsafe {
- Ok(CrasServerState {
- addr: addr.as_ptr() as *mut libc::c_void,
- volume: vref_from_addr!(addr, volume),
- mute: vref_from_addr!(addr, mute),
- num_output_devs: vref_from_addr!(addr, num_output_devs),
- num_input_devs: vref_from_addr!(addr, num_input_devs),
- output_devs: vslice_from_addr!(addr, output_devs),
- input_devs: vslice_from_addr!(addr, input_devs),
- num_output_nodes: vref_from_addr!(addr, num_output_nodes),
- num_input_nodes: vref_from_addr!(addr, num_input_nodes),
- output_nodes: vslice_from_addr!(addr, output_nodes),
- input_nodes: vslice_from_addr!(addr, input_nodes),
- update_count: vref_from_addr!(addr, update_count),
- debug_info_num_devs: vref_from_addr!(addr, audio_debug_info.num_devs),
- debug_info_devs: vslice_from_addr!(addr, audio_debug_info.devs),
- debug_info_num_streams: vref_from_addr!(addr, audio_debug_info.num_streams),
- debug_info_streams: vslice_from_addr!(addr, audio_debug_info.streams),
- })
- }
- }
-
- /// Gets the system volume.
- ///
- /// Read the current value for system volume from shared memory.
- pub fn get_system_volume(&self) -> u32 {
- self.volume.load()
- }
-
- /// Gets the system mute.
- ///
- /// Read the current value for system mute from shared memory.
- pub fn get_system_mute(&self) -> bool {
- self.mute.load() != 0
- }
-
- /// Runs a closure safely such that it can be sure that the server state
- /// was not updated during the read.
- /// This can be used for an "atomic" read of non-atomic data from the
- /// state shared memory.
- fn synchronized_state_read<F, T>(&self, mut func: F) -> T
- where
- F: FnMut() -> T,
- {
- // Waits until the server has completed a state update before returning
- // the current update count.
- let begin_server_state_read = || -> u32 {
- loop {
- let update_count = self.update_count.load();
- if update_count % 2 == 0 {
- atomic::fence(Ordering::Acquire);
- return update_count;
- } else {
- thread::yield_now();
- }
- }
- };
-
- // Checks that the update count has not changed since the start
- // of the server state read.
- let end_server_state_read = |count: u32| -> bool {
- let result = count == self.update_count.load();
- atomic::fence(Ordering::Release);
- result
- };
-
- // Get the state's update count and run the provided closure.
- // If the update count has not changed once the closure is finished,
- // return the result, otherwise repeat the process.
- loop {
- let update_count = begin_server_state_read();
- let result = func();
- if end_server_state_read(update_count) {
- return result;
- }
- }
- }
-
- /// Gets a list of output devices
- ///
- /// Read a list of the currently attached output devices from shared memory.
- pub fn output_devices(&self) -> impl Iterator<Item = CrasIodevInfo> {
- let mut devs: Vec<cras_iodev_info> = vec![Default::default(); CRAS_MAX_IODEVS as usize];
- let num_devs = self.synchronized_state_read(|| {
- self.output_devs.copy_to(&mut devs);
- self.num_output_devs.load()
- });
- devs.into_iter()
- .take(num_devs as usize)
- .map(CrasIodevInfo::from)
- }
-
- /// Gets a list of input devices
- ///
- /// Read a list of the currently attached input devices from shared memory.
- pub fn input_devices(&self) -> impl Iterator<Item = CrasIodevInfo> {
- let mut devs: Vec<cras_iodev_info> = vec![Default::default(); CRAS_MAX_IODEVS as usize];
- let num_devs = self.synchronized_state_read(|| {
- self.input_devs.copy_to(&mut devs);
- self.num_input_devs.load()
- });
- devs.into_iter()
- .take(num_devs as usize)
- .map(CrasIodevInfo::from)
- }
-
- /// Gets a list of output nodes
- ///
- /// Read a list of the currently attached output nodes from shared memory.
- pub fn output_nodes(&self) -> impl Iterator<Item = CrasIonodeInfo> {
- let mut nodes: Vec<cras_ionode_info> = vec![Default::default(); CRAS_MAX_IONODES as usize];
- let num_nodes = self.synchronized_state_read(|| {
- self.output_nodes.copy_to(&mut nodes);
- self.num_output_nodes.load()
- });
- nodes
- .into_iter()
- .take(num_nodes as usize)
- .map(CrasIonodeInfo::from)
- }
-
- /// Gets a list of input nodes
- ///
- /// Read a list of the currently attached input nodes from shared memory.
- pub fn input_nodes(&self) -> impl Iterator<Item = CrasIonodeInfo> {
- let mut nodes: Vec<cras_ionode_info> = vec![Default::default(); CRAS_MAX_IONODES as usize];
- let num_nodes = self.synchronized_state_read(|| {
- self.input_nodes.copy_to(&mut nodes);
- self.num_input_nodes.load()
- });
- nodes
- .into_iter()
- .take(num_nodes as usize)
- .map(CrasIonodeInfo::from)
- }
-
- /// Get audio debug info
- ///
- /// Loads the server's audio_debug_info struct and converts it into an
- /// idiomatic rust representation.
- ///
- /// # Errors
- /// * If any of the stream debug information structs are invalid.
- pub fn get_audio_debug_info(&self) -> Result<AudioDebugInfo, cras_sys::Error> {
- let mut devs: Vec<audio_dev_debug_info> = vec![Default::default(); MAX_DEBUG_DEVS as usize];
- let mut streams: Vec<audio_stream_debug_info> =
- vec![Default::default(); MAX_DEBUG_STREAMS as usize];
- let (num_devs, num_streams) = self.synchronized_state_read(|| {
- self.debug_info_devs.copy_to(&mut devs);
- self.debug_info_streams.copy_to(&mut streams);
- (
- self.debug_info_num_devs.load(),
- self.debug_info_num_streams.load(),
- )
- });
- let dev_info = devs
- .into_iter()
- .take(num_devs as usize)
- .map(AudioDevDebugInfo::from)
- .collect();
- let stream_info = streams
- .into_iter()
- .take(num_streams as usize)
- .map(AudioStreamDebugInfo::try_from)
- .collect::<Result<Vec<_>, _>>()?;
- Ok(AudioDebugInfo::new(dev_info, stream_info))
- }
-}
-
-impl<'a> Drop for CrasServerState<'a> {
- /// Call `munmap` for `addr`.
- fn drop(&mut self) {
- unsafe {
- // Safe because all references must be gone by the time drop is called.
- libc::munmap(self.addr, mem::size_of::<cras_server_state>());
- }
- }
-}
-
-/// A structure holding the mapped shared memory area used to exchange
-/// samples with CRAS. The shared memory is owned exclusively by this structure,
-/// and will be cleaned up on drop.
-/// * `addr` - The address of the mapped shared memory.
-/// * `len` - Length of the mapped shared memory in bytes.
-pub struct CrasAudioBuffer {
- addr: *mut u8,
- len: usize,
-}
-
-// It is safe to send audio buffers between threads as this struct has exclusive ownership of the
-// shared memory area contained in it.
-unsafe impl Send for CrasAudioBuffer {}
-
-impl CrasAudioBuffer {
- fn new(samples_fd: CrasShmFd) -> io::Result<Self> {
- // This is safe because we checked that the size of the shm in samples_fd
- // was at least samples_fd.size when it was created.
- let addr = unsafe {
- cras_mmap(
- samples_fd.size,
- libc::PROT_READ | libc::PROT_WRITE,
- samples_fd.as_raw_fd(),
- )? as *mut u8
- };
- Ok(Self {
- addr,
- len: samples_fd.size,
- })
- }
-
- /// Provides a mutable slice to be filled with audio samples.
- pub fn get_buffer(&mut self) -> &mut [u8] {
- // This is safe because it takes a mutable reference to self, and there can only be one
- // taken at a time. Although this is shared memory, the reader side must have it mapped as
- // read only.
- unsafe { slice::from_raw_parts_mut(self.addr, self.len) }
- }
-}
-
-impl Drop for CrasAudioBuffer {
- fn drop(&mut self) {
- // Safe because all references must be gone by the time drop is called.
- unsafe {
- libc::munmap(self.addr as *mut _, self.len);
- }
- }
-}
-
-/// Creates header and buffer from given shared memory fds.
-pub fn create_header_and_buffers<'a>(
- header_fd: CrasAudioShmHeaderFd,
- samples_fd: CrasShmFd,
-) -> io::Result<(CrasAudioHeader<'a>, CrasAudioBuffer)> {
- let header = CrasAudioHeader::new(header_fd, samples_fd.size)?;
- let buffer = CrasAudioBuffer::new(samples_fd)?;
-
- Ok((header, buffer))
-}
-
-/// Creates header from header shared memory fds. Use this function
-/// when mapping the samples shm is not necessary, for instance with a
-/// client-provided shm stream.
-pub fn create_header<'a>(
- header_fd: CrasAudioShmHeaderFd,
- samples_len: usize,
-) -> io::Result<CrasAudioHeader<'a>> {
- Ok(CrasAudioHeader::new(header_fd, samples_len)?)
-}
-
-/// A structure wrapping a fd which contains a shared memory area and its size.
-/// * `fd` - The shared memory file descriptor, a `libc::c_int`.
-/// * `size` - Size of the shared memory area.
-pub struct CrasShmFd {
- fd: libc::c_int,
- size: usize,
-}
-
-impl CrasShmFd {
- /// Creates a `CrasShmFd` by shared memory fd and size
- /// # Arguments
- /// * `fd` - A shared memory file descriptor, which will be owned by the resulting structure and
- /// the fd will be closed on drop.
- /// * `size` - Size of the shared memory.
- ///
- /// # Returns
- /// * `CrasShmFd` - Wrap the input arguments without doing anything.
- ///
- /// To use this function safely, we need to make sure
- /// - The input fd is a valid shared memory fd.
- /// - The input shared memory fd won't be used by others.
- /// - The input fd contains memory size larger than `size`.
- pub unsafe fn new(fd: libc::c_int, size: usize) -> CrasShmFd {
- CrasShmFd { fd, size }
- }
-}
-
-impl AsRawFd for CrasShmFd {
- fn as_raw_fd(&self) -> RawFd {
- self.fd
- }
-}
-
-impl Drop for CrasShmFd {
- fn drop(&mut self) {
- // It's safe here if we make sure
- // - the input fd is valid and
- // - `CrasShmFd` is the only owner
- // in `new` function
- unsafe {
- libc::close(self.fd);
- }
- }
-}
-
-/// A structure wrapping a fd which contains a shared `cras_server_state`.
-/// * `shm_fd` - A shared memory fd contains a `cras_server_state`
-pub struct CrasServerStateShmFd {
- fd: CrasShmFd,
-}
-
-impl CrasServerStateShmFd {
- /// Creates a `CrasServerStateShmFd` by shared memory fd
- /// # Arguments
- /// * `fd` - A shared memory file descriptor, which will be owned by the resulting structure and
- /// the fd will be closed on drop.
- ///
- /// # Returns
- /// A structure wrapping a `CrasShmFd` with the input fd and `size` which equals to
- /// the size of `cras_server_sate`.
- ///
- /// To use this function safely, we need to make sure
- /// - The input fd is a valid shared memory fd.
- /// - The input shared memory fd won't be used by others.
- /// - The shared memory area in the input fd contains a `cras_server_state`.
- pub unsafe fn new(fd: libc::c_int) -> Self {
- Self {
- fd: CrasShmFd::new(fd, mem::size_of::<cras_server_state>()),
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use std::fs::File;
- use std::os::unix::io::IntoRawFd;
- use std::sync::{Arc, Mutex};
- use std::thread;
- use sys_util::{kernel_has_memfd, SharedMemory};
-
- #[test]
- fn cras_audio_header_switch_test() {
- if !kernel_has_memfd() {
- return;
- }
- let mut header = create_cras_audio_header(20);
- assert_eq!(0, header.get_write_buf_idx());
- header.switch_write_buf_idx();
- assert_eq!(1, header.get_write_buf_idx());
- }
-
- #[test]
- fn cras_audio_header_write_offset_test() {
- if !kernel_has_memfd() {
- return;
- }
- let mut header = create_cras_audio_header(20);
- header.frame_size.store(2);
- header.used_size.store(5);
- header.set_buffer_offset(0, 12).unwrap();
-
- assert_eq!(0, header.write_offset[0].load());
- // Index out of bound
- assert!(header.set_write_offset(2, 5).is_err());
- // Offset out of bound
- // Buffer length is 4, since that's the largest multiple of frame_size
- // less than used_size.
- assert!(header.set_write_offset(0, 6).is_err());
- assert_eq!(0, header.write_offset[0].load());
- assert!(header.set_write_offset(0, 5).is_err());
- assert_eq!(0, header.write_offset[0].load());
- assert!(header.set_write_offset(0, 4).is_ok());
- assert_eq!(4, header.write_offset[0].load());
- }
-
- #[test]
- fn cras_audio_header_read_offset_test() {
- if !kernel_has_memfd() {
- return;
- }
- let mut header = create_cras_audio_header(20);
- header.frame_size.store(2);
- header.used_size.store(5);
- header.set_buffer_offset(0, 12).unwrap();
-
- assert_eq!(0, header.read_offset[0].load());
- // Index out of bound
- assert!(header.set_read_offset(2, 5).is_err());
- // Offset out of bound
- // Buffer length is 4, since that's the largest multiple of frame_size
- // less than used_size.
- assert!(header.set_read_offset(0, 6).is_err());
- assert_eq!(0, header.read_offset[0].load());
- assert!(header.set_read_offset(0, 5).is_err());
- assert_eq!(0, header.read_offset[0].load());
- assert!(header.set_read_offset(0, 4).is_ok());
- assert_eq!(4, header.read_offset[0].load());
- }
-
- #[test]
- fn cras_audio_header_commit_written_frame_test() {
- if !kernel_has_memfd() {
- return;
- }
- let mut header = create_cras_audio_header(20);
- header.frame_size.store(2);
- header.used_size.store(10);
- header.read_offset[0].store(10);
- header.set_buffer_offset(0, 10).unwrap();
-
- assert!(header.commit_written_frames(5).is_ok());
- assert_eq!(header.write_offset[0].load(), 10);
- assert_eq!(header.read_offset[0].load(), 0);
- assert_eq!(header.write_buf_idx.load(), 1);
- }
-
- #[test]
- fn cras_audio_header_get_readable_frames_test() {
- if !kernel_has_memfd() {
- return;
- }
- let header = create_cras_audio_header(20);
- header.frame_size.store(2);
- header.used_size.store(10);
- header.read_offset[0].store(2);
- header.write_offset[0].store(10);
- let frames = header
- .get_readable_frames()
- .expect("Failed to get readable frames.");
- assert_eq!(frames, 4);
- }
-
- #[test]
- fn cras_audio_header_commit_read_frames_test() {
- if !kernel_has_memfd() {
- return;
- }
- let mut header = create_cras_audio_header(20);
- header.frame_size.store(2);
- header.used_size.store(10);
- header.read_offset[0].store(2);
- header.write_offset[0].store(10);
- header
- .commit_read_frames(3)
- .expect("Failed to commit read frames.");
- assert_eq!(header.get_read_buf_idx(), 0);
- assert_eq!(header.read_offset[0].load(), 8);
-
- header
- .commit_read_frames(1)
- .expect("Failed to commit read frames.");
- // Read buffer should be switched
- assert_eq!(header.get_read_buf_idx(), 1);
- assert_eq!(header.read_offset[0].load(), 0);
- assert_eq!(header.read_offset[0].load(), 0);
- }
-
- #[test]
- fn cras_audio_header_get_write_offset_and_len() {
- if !kernel_has_memfd() {
- return;
- }
- let header = create_cras_audio_header(30);
- header.frame_size.store(2);
- header.used_size.store(10);
- header.write_buf_idx.store(0);
- header.read_offset[0].store(0);
- header.write_offset[0].store(0);
- header.buffer_offset[0].store(0);
-
- header.read_buf_idx.store(1);
- header.read_offset[1].store(0);
- header.write_offset[1].store(0);
- header.buffer_offset[1].store(10);
-
- // standard offsets and lens
- let (offset, len) = header.get_write_offset_and_len().unwrap();
- assert_eq!(offset, 0);
- assert_eq!(len, 10);
-
- header.write_buf_idx.store(1);
- header.read_buf_idx.store(0);
- let (offset, len) = header.get_write_offset_and_len().unwrap();
- assert_eq!(offset, 10);
- assert_eq!(len, 10);
-
- // relocate buffer offsets
- header.buffer_offset[1].store(16);
- let (offset, len) = header.get_write_offset_and_len().unwrap();
- assert_eq!(offset, 16);
- assert_eq!(len, 10);
-
- header.buffer_offset[0].store(5);
- header.write_buf_idx.store(0);
- let (offset, len) = header.get_write_offset_and_len().unwrap();
- assert_eq!(offset, 5);
- assert_eq!(len, 10);
-
- header.write_buf_idx.store(0);
- header.buffer_offset[0].store(2);
- header.read_buf_idx.store(1);
- header.buffer_offset[1].store(10);
- let result = header.get_write_offset_and_len();
- // Should be an error as write buffer would overrun into other buffer.
- assert!(result.is_err());
-
- header.buffer_offset[0].store(24);
- header.buffer_offset[1].store(10);
- let (offset, len) = header.get_write_offset_and_len().unwrap();
- // Should be ok since we're only running up against the end of samples.
- assert_eq!(offset, 24);
- assert_eq!(len, 6);
-
- header.buffer_offset[0].store(25);
- let (offset, len) = header.get_write_offset_and_len().unwrap();
- // Should be ok, but we'll truncate len to frame_size.
- assert_eq!(offset, 25);
- assert_eq!(len, 4);
-
- header.buffer_offset[0].store(29);
- let result = header.get_write_offset_and_len();
- // Should be an error as buffer is smaller than frame_size.
- assert!(result.is_err());
- }
-
- #[test]
- fn cras_audio_header_set_buffer_offset() {
- if !kernel_has_memfd() {
- return;
- }
- let mut header = create_cras_audio_header(30);
- header.frame_size.store(2);
- header.used_size.store(10);
- header.write_buf_idx.store(0);
- header.read_offset[0].store(0);
- header.write_offset[0].store(0);
- header.buffer_offset[0].store(0);
-
- header.read_buf_idx.store(1);
- header.read_offset[1].store(0);
- header.write_offset[1].store(0);
- header.buffer_offset[1].store(10);
-
- // Setting buffer_offset to exactly overlap with other buffer is okay
- assert!(header.set_buffer_offset(0, 10).is_ok());
-
- // Setting buffer_offset to partially overlap other buffer is not okay
- assert!(header.set_buffer_offset(0, 9).is_err());
-
- header.buffer_offset[0].store(0);
- header.write_offset[1].store(8);
- // With samples, it's still an error.
- assert!(header.set_buffer_offset(0, 9).is_err());
-
- // Setting the offset past the end of the other buffer is okay
- assert!(header.set_buffer_offset(0, 20).is_ok());
-
- // Setting buffer offset such that buffer length is less than used_size
- // is okay, but only at the end of the samples area.
- assert!(header.set_buffer_offset(0, 21).is_ok());
- assert!(header.set_buffer_offset(0, 27).is_ok());
-
- // It's not okay if we get a buffer with length less than frame_size.
- assert!(header.set_buffer_offset(0, 29).is_err());
- assert!(header.set_buffer_offset(0, 30).is_err());
-
- // If we try to overlap another buffer with that other buffer at the end,
- // it's not okay, unless it's the exact same index.
- assert!(header.set_buffer_offset(1, 25).is_err());
- assert!(header.set_buffer_offset(1, 27).is_ok());
- assert!(header.set_buffer_offset(1, 28).is_err());
-
- // Setting buffer offset past the end of samples is an error.
- assert!(header.set_buffer_offset(0, 33).is_err());
- }
-
- #[test]
- fn create_header_and_buffers_test() {
- if !kernel_has_memfd() {
- return;
- }
- let header_fd = cras_audio_header_fd();
- let samples_fd = cras_audio_samples_fd(20);
- let res = create_header_and_buffers(header_fd, samples_fd);
- res.expect("Failed to create header and buffer.");
- }
-
- fn create_shm(size: usize) -> File {
- let mut shm = SharedMemory::new(None).expect("failed to create shm");
- shm.set_size(size as u64).expect("failed to set shm size");
- shm.into()
- }
-
- fn create_cras_audio_header<'a>(samples_len: usize) -> CrasAudioHeader<'a> {
- CrasAudioHeader::new(cras_audio_header_fd(), samples_len).unwrap()
- }
-
- fn cras_audio_header_fd() -> CrasAudioShmHeaderFd {
- let size = mem::size_of::<cras_audio_shm_header>();
- let shm = create_shm(size);
- unsafe { CrasAudioShmHeaderFd::new(shm.into_raw_fd()) }
- }
-
- fn cras_audio_samples_fd(size: usize) -> CrasShmFd {
- let shm = create_shm(size);
- unsafe { CrasShmFd::new(shm.into_raw_fd(), size) }
- }
-
- #[test]
- fn cras_mmap_pass() {
- if !kernel_has_memfd() {
- return;
- }
- let shm = create_shm(100);
- let rc = unsafe { cras_mmap(10, libc::PROT_READ, shm.as_raw_fd()) };
- assert!(rc.is_ok());
- unsafe { libc::munmap(rc.unwrap(), 10) };
- }
-
- #[test]
- fn cras_mmap_failed() {
- if !kernel_has_memfd() {
- return;
- }
- let rc = unsafe { cras_mmap(10, libc::PROT_READ, -1) };
- assert!(rc.is_err());
- }
-
- #[test]
- fn cras_server_state() {
- let size = mem::size_of::<cras_server_state>();
- let shm = create_shm(size);
- unsafe {
- let addr = cras_mmap(size, libc::PROT_WRITE, shm.as_raw_fd())
- .expect("failed to mmap state shm");
- {
- let state: &mut cras_server_state = &mut *(addr as *mut cras_server_state);
- state.state_version = CRAS_SERVER_STATE_VERSION;
- state.volume = 47;
- state.mute = 1;
- }
- libc::munmap(addr, size);
- };
- let state_fd = unsafe { CrasServerStateShmFd::new(shm.into_raw_fd()) };
- let state =
- CrasServerState::try_new(state_fd).expect("try_new failed for valid server_state fd");
- assert_eq!(state.get_system_volume(), 47);
- assert_eq!(state.get_system_mute(), true);
- }
-
- #[test]
- fn cras_server_state_old_version() {
- let size = mem::size_of::<cras_server_state>();
- let shm = create_shm(size);
- unsafe {
- let addr = cras_mmap(size, libc::PROT_WRITE, shm.as_raw_fd())
- .expect("failed to mmap state shm");
- {
- let state: &mut cras_server_state = &mut *(addr as *mut cras_server_state);
- state.state_version = CRAS_SERVER_STATE_VERSION - 1;
- state.volume = 29;
- state.mute = 0;
- }
- libc::munmap(addr, size);
- };
- let state_fd = unsafe { CrasServerStateShmFd::new(shm.into_raw_fd()) };
- CrasServerState::try_new(state_fd)
- .expect_err("try_new succeeded for invalid state version");
- }
-
- #[test]
- fn cras_server_sync_state_read() {
- let size = mem::size_of::<cras_server_state>();
- let shm = create_shm(size);
- let addr = unsafe { cras_mmap(size, libc::PROT_WRITE, shm.as_raw_fd()).unwrap() };
- let state: &mut cras_server_state = unsafe { &mut *(addr as *mut cras_server_state) };
- state.state_version = CRAS_SERVER_STATE_VERSION;
- state.update_count = 14;
- state.volume = 12;
-
- let state_fd = unsafe { CrasServerStateShmFd::new(shm.into_raw_fd()) };
- let state_struct = CrasServerState::try_new(state_fd).unwrap();
-
- // Create a lock so that we can block the reader while we change the
- // update_count;
- let lock = Arc::new(Mutex::new(()));
- let thread_lock = lock.clone();
- let reader_thread = {
- let _guard = lock.lock().unwrap();
-
- // Create reader thread that will get the value of volume. Since we
- // hold the lock currently, this will block until we release the lock.
- let reader_thread = thread::spawn(move || {
- state_struct.synchronized_state_read(|| {
- let _guard = thread_lock.lock().unwrap();
- state_struct.volume.load()
- })
- });
-
- // Update volume and change update count so that the synchronized read
- // will not return (odd update count means update in progress).
- state.volume = 27;
- state.update_count = 15;
-
- reader_thread
- };
-
- // The lock has been released, but the reader thread should still not
- // terminate, because of the update in progress.
-
- // Yield thread to give reader_thread a chance to get scheduled.
- thread::yield_now();
- {
- let _guard = lock.lock().unwrap();
-
- // Update volume and change update count to indicate the write has
- // finished.
- state.volume = 42;
- state.update_count = 16;
- }
-
- let read_value = reader_thread.join().unwrap();
- assert_eq!(read_value, 42);
- }
-}
diff --git a/cras/client/libcras/src/cras_shm_stream.rs b/cras/client/libcras/src/cras_shm_stream.rs
deleted file mode 100644
index f72cc07c..00000000
--- a/cras/client/libcras/src/cras_shm_stream.rs
+++ /dev/null
@@ -1,191 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::time::Duration;
-use std::{error, fmt};
-
-use audio_streams::{
- shm_streams::{BufferSet, ServerRequest, ShmStream},
- BoxError, SampleFormat, StreamDirection,
-};
-use cras_sys::gen::CRAS_AUDIO_MESSAGE_ID;
-use sys_util::error;
-
-use crate::audio_socket::{AudioMessage, AudioSocket};
-use crate::cras_server_socket::CrasServerSocket;
-use crate::cras_shm::{self, CrasAudioHeader, CrasAudioShmHeaderFd};
-
-#[derive(Debug)]
-pub enum Error {
- MessageTypeError,
- CaptureBufferTooSmall,
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Error::MessageTypeError => write!(f, "Message type error"),
- Error::CaptureBufferTooSmall => write!(
- f,
- "Capture buffer too small, must have size at least 'used_size'."
- ),
- }
- }
-}
-
-/// An object that handles interactions with CRAS for a shm stream.
-/// The object implements `ShmStream` and so can be used to wait for
-/// `ServerRequest` and `BufferComplete` messages.
-pub struct CrasShmStream<'a> {
- stream_id: u32,
- server_socket: CrasServerSocket,
- audio_socket: AudioSocket,
- direction: StreamDirection,
- header: CrasAudioHeader<'a>,
- frame_size: usize,
- num_channels: usize,
- frame_rate: u32,
- // The index of the next buffer within SHM to set the buffer offset for.
- next_buffer_idx: usize,
-}
-
-impl<'a> CrasShmStream<'a> {
- /// Attempt to creates a CrasShmStream with the given arguments.
- ///
- /// # Arguments
- ///
- /// * `stream_id` - The server's ID for the stream.
- /// * `server_socket` - The socket that is connected to the server.
- /// * `audio_socket` - The socket for audio request and audio available messages.
- /// * `direction` - The direction of the stream, `Playback` or `Capture`.
- /// * `num_channels` - The number of audio channels for the stream.
- /// * `format` - The format to use for the stream's samples.
- /// * `header_fd` - The file descriptor for the audio header shm area.
- /// * `samples_len` - The size of the audio samples shm area.
- ///
- /// # Returns
- ///
- /// `CrasShmStream` - CRAS client stream.
- ///
- /// # Errors
- ///
- /// * If `header_fd` could not be successfully mmapped.
- #[allow(clippy::too_many_arguments)]
- pub fn try_new(
- stream_id: u32,
- server_socket: CrasServerSocket,
- audio_socket: AudioSocket,
- direction: StreamDirection,
- num_channels: usize,
- frame_rate: u32,
- format: SampleFormat,
- header_fd: CrasAudioShmHeaderFd,
- samples_len: usize,
- ) -> Result<Self, BoxError> {
- let header = cras_shm::create_header(header_fd, samples_len)?;
- Ok(Self {
- stream_id,
- server_socket,
- audio_socket,
- direction,
- header,
- frame_size: format.sample_bytes() * num_channels,
- num_channels,
- frame_rate,
- // We have either sent zero or two offsets to the server, so we will
- // need to update index 0 next.
- next_buffer_idx: 0,
- })
- }
-}
-
-impl<'a> Drop for CrasShmStream<'a> {
- /// Send the disconnect stream message and log an error if sending fails.
- fn drop(&mut self) {
- if let Err(e) = self.server_socket.disconnect_stream(self.stream_id) {
- error!("CrasShmStream::drop error: {}", e);
- }
- }
-}
-
-impl<'a> ShmStream for CrasShmStream<'a> {
- fn frame_size(&self) -> usize {
- self.frame_size
- }
-
- fn num_channels(&self) -> usize {
- self.num_channels
- }
-
- fn frame_rate(&self) -> u32 {
- self.frame_rate
- }
-
- fn wait_for_next_action_with_timeout(
- &mut self,
- timeout: Duration,
- ) -> Result<Option<ServerRequest>, BoxError> {
- let expected_id = match self.direction {
- StreamDirection::Playback => CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_REQUEST_DATA,
- StreamDirection::Capture => CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_DATA_READY,
- };
-
- match self
- .audio_socket
- .read_audio_message_with_timeout(Some(timeout))?
- {
- Some(AudioMessage::Success { id, frames }) if id == expected_id => {
- Ok(Some(ServerRequest::new(frames as usize, self)))
- }
- None => Ok(None),
- _ => Err(Box::new(Error::MessageTypeError)),
- }
- }
-}
-
-impl BufferSet for CrasShmStream<'_> {
- fn callback(&mut self, offset: usize, frames: usize) -> Result<(), BoxError> {
- self.header
- .set_buffer_offset(self.next_buffer_idx, offset)?;
- self.next_buffer_idx ^= 1;
- let frames = frames as u32;
-
- match self.direction {
- StreamDirection::Playback => {
- self.header.commit_written_frames(frames)?;
-
- // Notify CRAS that we've made playback data available.
- self.audio_socket.data_ready(frames)?
- }
- StreamDirection::Capture => {
- let used_size = self.header.get_used_size();
- // Because CRAS doesn't know how long our buffer in shm is, we
- // must make sure that there are always at least buffer_size
- // frames available so that it doesn't write outside the buffer.
- if frames < (used_size / self.frame_size) as u32 {
- return Err(Box::new(Error::CaptureBufferTooSmall));
- }
-
- self.header.commit_read_frames(frames)?;
- self.audio_socket.capture_ready(frames)?;
- }
- }
-
- Ok(())
- }
-
- fn ignore(&mut self) -> Result<(), BoxError> {
- // We send an empty buffer for an ignored playback request since the
- // server will not read from a 0-length buffer. We don't do anything for
- // an ignored capture request, since we don't have a way to communicate
- // buffer length to the server, and we don't want the server writing
- // data to offsets within the SHM area that aren't audio buffers.
- if self.direction == StreamDirection::Playback {
- self.callback(0, 0)?;
- }
-
- Ok(())
- }
-}
diff --git a/cras/client/libcras/src/cras_stream.rs b/cras/client/libcras/src/cras_stream.rs
deleted file mode 100644
index f6004802..00000000
--- a/cras/client/libcras/src/cras_stream.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::cmp::min;
-use std::io;
-use std::marker::PhantomData;
-use std::{error, fmt};
-
-use audio_streams::{
- capture::{CaptureBuffer, CaptureBufferStream},
- BoxError, BufferDrop, PlaybackBuffer, PlaybackBufferStream,
-};
-use cras_sys::gen::{snd_pcm_format_t, CRAS_AUDIO_MESSAGE_ID, CRAS_STREAM_DIRECTION};
-use sys_util::error;
-
-use crate::audio_socket::{AudioMessage, AudioSocket};
-use crate::cras_server_socket::CrasServerSocket;
-use crate::cras_shm::*;
-
-#[derive(Debug)]
-pub enum Error {
- IoError(io::Error),
- MessageTypeError,
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Error::IoError(ref err) => err.fmt(f),
- Error::MessageTypeError => write!(f, "Message type error"),
- }
- }
-}
-
-impl From<io::Error> for Error {
- fn from(io_err: io::Error) -> Error {
- Error::IoError(io_err)
- }
-}
-
-/// A trait controls the state of `CrasAudioHeader` and
-/// interacts with server's audio thread through `AudioSocket`.
-pub trait CrasStreamData<'a>: Send {
- // Creates `CrasStreamData` with only `AudioSocket`.
- fn new(audio_sock: AudioSocket, header: CrasAudioHeader<'a>) -> Self;
- fn header_mut(&mut self) -> &mut CrasAudioHeader<'a>;
- fn audio_sock_mut(&mut self) -> &mut AudioSocket;
-}
-
-/// `CrasStreamData` implementation for `PlaybackBufferStream`.
-pub struct CrasPlaybackData<'a> {
- audio_sock: AudioSocket,
- header: CrasAudioHeader<'a>,
-}
-
-impl<'a> CrasStreamData<'a> for CrasPlaybackData<'a> {
- fn new(audio_sock: AudioSocket, header: CrasAudioHeader<'a>) -> Self {
- Self { audio_sock, header }
- }
-
- fn header_mut(&mut self) -> &mut CrasAudioHeader<'a> {
- &mut self.header
- }
-
- fn audio_sock_mut(&mut self) -> &mut AudioSocket {
- &mut self.audio_sock
- }
-}
-
-impl<'a> BufferDrop for CrasPlaybackData<'a> {
- fn trigger(&mut self, nframes: usize) {
- let log_err = |e| error!("BufferDrop error: {}", e);
- if let Err(e) = self.header.commit_written_frames(nframes as u32) {
- log_err(e);
- }
- if let Err(e) = self.audio_sock.data_ready(nframes as u32) {
- log_err(e);
- }
- }
-}
-
-/// `CrasStreamData` implementation for `CaptureBufferStream`.
-pub struct CrasCaptureData<'a> {
- audio_sock: AudioSocket,
- header: CrasAudioHeader<'a>,
-}
-
-impl<'a> CrasStreamData<'a> for CrasCaptureData<'a> {
- fn new(audio_sock: AudioSocket, header: CrasAudioHeader<'a>) -> Self {
- Self { audio_sock, header }
- }
-
- fn header_mut(&mut self) -> &mut CrasAudioHeader<'a> {
- &mut self.header
- }
-
- fn audio_sock_mut(&mut self) -> &mut AudioSocket {
- &mut self.audio_sock
- }
-}
-
-impl<'a> BufferDrop for CrasCaptureData<'a> {
- fn trigger(&mut self, nframes: usize) {
- let log_err = |e| error!("BufferDrop error: {}", e);
- if let Err(e) = self.header.commit_read_frames(nframes as u32) {
- log_err(e);
- }
- if let Err(e) = self.audio_sock.capture_ready(nframes as u32) {
- log_err(e);
- }
- }
-}
-
-#[allow(dead_code)]
-pub struct CrasStream<'a, T: CrasStreamData<'a> + BufferDrop> {
- stream_id: u32,
- server_socket: CrasServerSocket,
- block_size: u32,
- direction: CRAS_STREAM_DIRECTION,
- rate: u32,
- num_channels: usize,
- format: snd_pcm_format_t,
- /// A structure for stream to interact with server audio thread.
- controls: T,
- /// The `PhantomData` is used by `controls: T`
- phantom: PhantomData<CrasAudioHeader<'a>>,
- audio_buffer: CrasAudioBuffer,
-}
-
-impl<'a, T: CrasStreamData<'a> + BufferDrop> CrasStream<'a, T> {
- /// Creates a CrasStream by given arguments.
- ///
- /// # Returns
- /// `CrasStream` - CRAS client stream.
- #[allow(clippy::too_many_arguments)]
- pub fn try_new(
- stream_id: u32,
- server_socket: CrasServerSocket,
- block_size: u32,
- direction: CRAS_STREAM_DIRECTION,
- rate: u32,
- num_channels: usize,
- format: snd_pcm_format_t,
- audio_sock: AudioSocket,
- header_fd: CrasAudioShmHeaderFd,
- samples_fd: CrasShmFd,
- ) -> Result<Self, Error> {
- let (header, audio_buffer) = create_header_and_buffers(header_fd, samples_fd)?;
-
- Ok(Self {
- stream_id,
- server_socket,
- block_size,
- direction,
- rate,
- num_channels,
- format,
- controls: T::new(audio_sock, header),
- phantom: PhantomData,
- audio_buffer,
- })
- }
-
- fn wait_request_data(&mut self) -> Result<(), Error> {
- match self.controls.audio_sock_mut().read_audio_message()? {
- AudioMessage::Success {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_REQUEST_DATA,
- ..
- } => Ok(()),
- _ => Err(Error::MessageTypeError),
- }
- }
-
- fn wait_data_ready(&mut self) -> Result<u32, Error> {
- match self.controls.audio_sock_mut().read_audio_message()? {
- AudioMessage::Success {
- id: CRAS_AUDIO_MESSAGE_ID::AUDIO_MESSAGE_DATA_READY,
- frames,
- } => Ok(frames),
- _ => Err(Error::MessageTypeError),
- }
- }
-}
-
-impl<'a, T: CrasStreamData<'a> + BufferDrop> Drop for CrasStream<'a, T> {
- /// A blocking drop function, sends the disconnect message to `CrasClient` and waits for
- /// the return message.
- /// Logs an error message to stderr if the method fails.
- fn drop(&mut self) {
- if let Err(e) = self.server_socket.disconnect_stream(self.stream_id) {
- error!("CrasStream::Drop error: {}", e);
- }
- }
-}
-
-impl<'a, T: CrasStreamData<'a> + BufferDrop> PlaybackBufferStream for CrasStream<'a, T> {
- fn next_playback_buffer(&mut self) -> Result<PlaybackBuffer, BoxError> {
- // Wait for request audio message
- self.wait_request_data()?;
- let header = self.controls.header_mut();
- let frame_size = header.get_frame_size();
- let (offset, len) = header.get_write_offset_and_len()?;
- let buf = &mut self.audio_buffer.get_buffer()[offset..offset + len];
-
- PlaybackBuffer::new(frame_size, buf, &mut self.controls).map_err(Box::from)
- }
-}
-
-impl<'a, T: CrasStreamData<'a> + BufferDrop> CaptureBufferStream for CrasStream<'a, T> {
- fn next_capture_buffer(&mut self) -> Result<CaptureBuffer, BoxError> {
- // Wait for data ready message
- let frames = self.wait_data_ready()?;
- let header = self.controls.header_mut();
- let frame_size = header.get_frame_size();
- let shm_frames = header.get_readable_frames()?;
- let len = min(shm_frames, frames as usize) * frame_size;
- let offset = header.get_read_buffer_offset()?;
- let buf = &mut self.audio_buffer.get_buffer()[offset..offset + len];
-
- CaptureBuffer::new(frame_size, buf, &mut self.controls).map_err(Box::from)
- }
-}
diff --git a/cras/client/libcras/src/libcras.rs b/cras/client/libcras/src/libcras.rs
deleted file mode 100644
index 402a4a27..00000000
--- a/cras/client/libcras/src/libcras.rs
+++ /dev/null
@@ -1,699 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! Provides an interface for playing and recording audio through CRAS server.
-//!
-//! `CrasClient` implements `StreamSource` trait and it can create playback or capture
-//! stream - `CrasStream` which can be a
-//! - `PlaybackBufferStream` for audio playback or
-//! - `CaptureBufferStream` for audio capture.
-//!
-//! # Example of file audio playback
-//!
-//! `PlaybackBuffer`s to be filled with audio samples are obtained by calling
-//! `next_playback_buffer` from `CrasStream`.
-//!
-//! Users playing audio fill the provided buffers with audio. When a `PlaybackBuffer` is dropped,
-//! the samples written to it are committed to the `CrasStream` it came from.
-//!
-//!
-//! ```
-//! // An example of playing raw audio data from a given file
-//! use std::env;
-//! use std::fs::File;
-//! use std::io::{Read, Write};
-//! use std::thread::{spawn, JoinHandle};
-//! type Result<T> = std::result::Result<T, BoxError>;
-//!
-//! use libcras::{BoxError, CrasClient, CrasClientType};
-//! use audio_streams::{SampleFormat, StreamSource};
-//!
-//! const BUFFER_SIZE: usize = 256;
-//! const FRAME_RATE: u32 = 44100;
-//! const NUM_CHANNELS: usize = 2;
-//! const FORMAT: SampleFormat = SampleFormat::S16LE;
-//!
-//! # fn main() -> Result<()> {
-//! # let args: Vec<String> = env::args().collect();
-//! # match args.len() {
-//! # 2 => {
-//! let mut cras_client = CrasClient::new()?;
-//! cras_client.set_client_type(CrasClientType::CRAS_CLIENT_TYPE_TEST);
-//! let (_control, mut stream) = cras_client
-//! .new_playback_stream(NUM_CHANNELS, FORMAT, FRAME_RATE, BUFFER_SIZE)?;
-//!
-//! // Plays 1000 * BUFFER_SIZE samples from the given file
-//! let mut file = File::open(&args[1])?;
-//! let mut local_buffer = [0u8; BUFFER_SIZE * NUM_CHANNELS * 2];
-//! for _i in 0..1000 {
-//! // Reads data to local buffer
-//! let _read_count = file.read(&mut local_buffer)?;
-//!
-//! // Gets writable buffer from stream and
-//! let mut buffer = stream.next_playback_buffer()?;
-//! // Writes data to stream buffer
-//! let _write_frames = buffer.write(&local_buffer)?;
-//! }
-//! // Stream and client should gracefully be closed out of this scope
-//! # }
-//! # _ => {
-//! # println!("{} /path/to/playback_file.raw", args[0]);
-//! # }
-//! # };
-//! # Ok(())
-//! # }
-//! ```
-//!
-//! # Example of file audio capture
-//!
-//! `CaptureBuffer`s which contain audio samples are obtained by calling
-//! `next_capture_buffer` from `CrasStream`.
-//!
-//! Users get captured audio samples from the provided buffers. When a `CaptureBuffer` is dropped,
-//! the number of read samples will be committed to the `CrasStream` it came from.
-//! ```
-//! use std::env;
-//! use std::fs::File;
-//! use std::io::{Read, Write};
-//! use std::thread::{spawn, JoinHandle};
-//! type Result<T> = std::result::Result<T, BoxError>;
-//!
-//! use libcras::{BoxError, CrasClient, CrasClientType};
-//! use audio_streams::{SampleFormat, StreamSource};
-//!
-//! const BUFFER_SIZE: usize = 256;
-//! const FRAME_RATE: u32 = 44100;
-//! const NUM_CHANNELS: usize = 2;
-//! const FORMAT: SampleFormat = SampleFormat::S16LE;
-//!
-//! # fn main() -> Result<()> {
-//! # let args: Vec<String> = env::args().collect();
-//! # match args.len() {
-//! # 2 => {
-//! let mut cras_client = CrasClient::new()?;
-//! cras_client.set_client_type(CrasClientType::CRAS_CLIENT_TYPE_TEST);
-//! let (_control, mut stream) = cras_client
-//! .new_capture_stream(NUM_CHANNELS, FORMAT, FRAME_RATE, BUFFER_SIZE)?;
-//!
-//! // Capture 1000 * BUFFER_SIZE samples to the given file
-//! let mut file = File::create(&args[1])?;
-//! let mut local_buffer = [0u8; BUFFER_SIZE * NUM_CHANNELS * 2];
-//! for _i in 0..1000 {
-//!
-//! // Gets readable buffer from stream and
-//! let mut buffer = stream.next_capture_buffer()?;
-//! // Reads data to local buffer
-//! let read_count = buffer.read(&mut local_buffer)?;
-//! // Writes data to file
-//! let _read_frames = file.write(&local_buffer[..read_count])?;
-//! }
-//! // Stream and client should gracefully be closed out of this scope
-//! # }
-//! # _ => {
-//! # println!("{} /path/to/capture_file.raw", args[0]);
-//! # }
-//! # };
-//! # Ok(())
-//! # }
-//! ```
-use std::io;
-use std::mem;
-use std::os::unix::{
- io::{AsRawFd, RawFd},
- net::UnixStream,
-};
-use std::{error, fmt};
-
-pub use audio_streams::BoxError;
-use audio_streams::{
- capture::{CaptureBufferStream, NoopCaptureStream},
- shm_streams::{NullShmStream, ShmStream, ShmStreamSource},
- BufferDrop, NoopStreamControl, PlaybackBufferStream, SampleFormat, StreamControl,
- StreamDirection, StreamEffect, StreamSource,
-};
-use cras_sys::gen::*;
-pub use cras_sys::gen::{
- CRAS_CLIENT_TYPE as CrasClientType, CRAS_NODE_TYPE as CrasNodeType,
- CRAS_STREAM_EFFECT as CrasStreamEffect,
-};
-pub use cras_sys::{AudioDebugInfo, CrasIodevInfo, CrasIonodeInfo, Error as CrasSysError};
-use sys_util::{PollContext, PollToken, SharedMemory};
-
-mod audio_socket;
-use crate::audio_socket::AudioSocket;
-mod cras_server_socket;
-use crate::cras_server_socket::CrasServerSocket;
-pub use crate::cras_server_socket::CrasSocketType;
-mod cras_shm;
-use crate::cras_shm::CrasServerState;
-pub mod cras_shm_stream;
-use crate::cras_shm_stream::CrasShmStream;
-mod cras_stream;
-use crate::cras_stream::{CrasCaptureData, CrasPlaybackData, CrasStream, CrasStreamData};
-mod cras_client_message;
-use crate::cras_client_message::*;
-
-#[derive(Debug)]
-pub enum Error {
- CrasClientMessageError(cras_client_message::Error),
- CrasStreamError(cras_stream::Error),
- CrasSysError(cras_sys::Error),
- IoError(io::Error),
- SysUtilError(sys_util::Error),
- MessageTypeError,
- UnexpectedExit,
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self {
- Error::CrasClientMessageError(ref err) => err.fmt(f),
- Error::CrasStreamError(ref err) => err.fmt(f),
- Error::CrasSysError(ref err) => err.fmt(f),
- Error::IoError(ref err) => err.fmt(f),
- Error::SysUtilError(ref err) => err.fmt(f),
- Error::MessageTypeError => write!(f, "Message type error"),
- Error::UnexpectedExit => write!(f, "Unexpected exit"),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-impl From<io::Error> for Error {
- fn from(io_err: io::Error) -> Self {
- Error::IoError(io_err)
- }
-}
-
-impl From<sys_util::Error> for Error {
- fn from(sys_util_err: sys_util::Error) -> Self {
- Error::SysUtilError(sys_util_err)
- }
-}
-
-impl From<cras_stream::Error> for Error {
- fn from(err: cras_stream::Error) -> Self {
- Error::CrasStreamError(err)
- }
-}
-
-impl From<cras_client_message::Error> for Error {
- fn from(err: cras_client_message::Error) -> Self {
- Error::CrasClientMessageError(err)
- }
-}
-
-/// A CRAS server client, which implements StreamSource and ShmStreamSource.
-/// It can create audio streams connecting to CRAS server.
-pub struct CrasClient<'a> {
- server_socket: CrasServerSocket,
- server_state: CrasServerState<'a>,
- client_id: u32,
- next_stream_id: u32,
- cras_capture: bool,
- client_type: CRAS_CLIENT_TYPE,
-}
-
-impl<'a> CrasClient<'a> {
- /// Blocks creating a `CrasClient` with registered `client_id`
- ///
- /// # Results
- ///
- /// * `CrasClient` - A client to interact with CRAS server
- ///
- /// # Errors
- ///
- /// Returns error if error occurs while handling server message or message
- /// type is incorrect
- pub fn new() -> Result<Self> {
- Self::with_type(CrasSocketType::Legacy)
- }
-
- /// Tries to create a `CrasClient` with a given `CrasSocketType`.
- ///
- /// # Errors
- ///
- /// Returns error if error occurs while handling server message or message
- /// type is incorrect.
- pub fn with_type(socket_type: CrasSocketType) -> Result<Self> {
- // Create a connection to the server.
- let mut server_socket = CrasServerSocket::with_type(socket_type)?;
- // Gets client ID and server state fd from server
- if let ServerResult::Connected(client_id, server_state_fd) =
- CrasClient::wait_for_message(&mut server_socket)?
- {
- Ok(Self {
- server_socket,
- server_state: CrasServerState::try_new(server_state_fd)?,
- client_id,
- next_stream_id: 0,
- cras_capture: false,
- client_type: CRAS_CLIENT_TYPE::CRAS_CLIENT_TYPE_UNKNOWN,
- })
- } else {
- Err(Error::MessageTypeError)
- }
- }
-
- /// Enables capturing audio through CRAS server.
- pub fn enable_cras_capture(&mut self) {
- self.cras_capture = true;
- }
-
- /// Set the type of this client to report to CRAS when connecting streams.
- pub fn set_client_type(&mut self, client_type: CRAS_CLIENT_TYPE) {
- self.client_type = client_type;
- }
-
- /// Sets the system volume to `volume`.
- ///
- /// Send a message to the server to request setting the system volume
- /// to `volume`. No response is returned from the server.
- ///
- /// # Errors
- ///
- /// If writing the message to the server socket failed.
- pub fn set_system_volume(&mut self, volume: u32) -> Result<()> {
- let header = cras_server_message {
- length: mem::size_of::<cras_set_system_volume>() as u32,
- id: CRAS_SERVER_MESSAGE_ID::CRAS_SERVER_SET_SYSTEM_VOLUME,
- };
- let msg = cras_set_system_volume { header, volume };
-
- self.server_socket.send_server_message_with_fds(&msg, &[])?;
- Ok(())
- }
-
- /// Sets the system mute status to `mute`.
- ///
- /// Send a message to the server to request setting the system mute
- /// to `mute`. No response is returned from the server.
- ///
- /// # Errors
- ///
- /// If writing the message to the server socket failed.
- pub fn set_system_mute(&mut self, mute: bool) -> Result<()> {
- let header = cras_server_message {
- length: mem::size_of::<cras_set_system_mute>() as u32,
- id: CRAS_SERVER_MESSAGE_ID::CRAS_SERVER_SET_SYSTEM_MUTE,
- };
- let msg = cras_set_system_mute {
- header,
- mute: mute as i32,
- };
-
- self.server_socket.send_server_message_with_fds(&msg, &[])?;
- Ok(())
- }
-
- /// Gets the system volume.
- ///
- /// Read the current value for system volume from the server shared memory.
- pub fn get_system_volume(&self) -> u32 {
- self.server_state.get_system_volume()
- }
-
- /// Gets the system mute.
- ///
- /// Read the current value for system mute from the server shared memory.
- pub fn get_system_mute(&self) -> bool {
- self.server_state.get_system_mute()
- }
-
- /// Gets a list of output devices
- ///
- /// Read a list of the currently attached output devices from the server shared memory.
- pub fn output_devices(&self) -> impl Iterator<Item = CrasIodevInfo> {
- self.server_state.output_devices()
- }
-
- /// Gets a list of input devices
- ///
- /// Read a list of the currently attached input devices from the server shared memory.
- pub fn input_devices(&self) -> impl Iterator<Item = CrasIodevInfo> {
- self.server_state.input_devices()
- }
-
- /// Gets a list of output nodes
- ///
- /// Read a list of the currently attached output nodes from the server shared memory.
- pub fn output_nodes(&self) -> impl Iterator<Item = CrasIonodeInfo> {
- self.server_state.output_nodes()
- }
-
- /// Gets a list of input nodes
- ///
- /// Read a list of the currently attached input nodes from the server shared memory.
- pub fn input_nodes(&self) -> impl Iterator<Item = CrasIonodeInfo> {
- self.server_state.input_nodes()
- }
-
- /// Gets the server's audio debug info.
- ///
- /// Sends a message to the server requesting an update of audio debug info,
- /// waits for the response, and then reads the info from the server state.
- ///
- /// # Errors
- ///
- /// * If sending the message to the server failed.
- /// * If an unexpected response message is received.
- pub fn get_audio_debug_info(&mut self) -> Result<AudioDebugInfo> {
- let header = cras_server_message {
- length: mem::size_of::<cras_dump_audio_thread>() as u32,
- id: CRAS_SERVER_MESSAGE_ID::CRAS_SERVER_DUMP_AUDIO_THREAD,
- };
- let msg = cras_dump_audio_thread { header };
-
- self.server_socket.send_server_message_with_fds(&msg, &[])?;
-
- match CrasClient::wait_for_message(&mut self.server_socket)? {
- ServerResult::DebugInfoReady => Ok(self
- .server_state
- .get_audio_debug_info()
- .map_err(Error::CrasSysError)?),
- _ => Err(Error::MessageTypeError),
- }
- }
-
- // Gets next server_stream_id from client and increment stream_id counter.
- fn next_server_stream_id(&mut self) -> u32 {
- let res = self.next_stream_id;
- self.next_stream_id += 1;
- self.server_stream_id(res)
- }
-
- // Gets server_stream_id from given stream_id
- fn server_stream_id(&self, stream_id: u32) -> u32 {
- (self.client_id << 16) | stream_id
- }
-
- // Creates general stream with given parameters
- fn create_stream<'b, T: BufferDrop + CrasStreamData<'b>>(
- &mut self,
- device_index: Option<u32>,
- block_size: u32,
- direction: CRAS_STREAM_DIRECTION,
- rate: u32,
- channel_num: usize,
- format: SampleFormat,
- ) -> Result<CrasStream<'b, T>> {
- let stream_id = self.next_server_stream_id();
-
- // Prepares server message
- let audio_format =
- cras_audio_format_packed::new(format.into(), rate, channel_num, direction);
- let msg_header = cras_server_message {
- length: mem::size_of::<cras_connect_message>() as u32,
- id: CRAS_SERVER_MESSAGE_ID::CRAS_SERVER_CONNECT_STREAM,
- };
- let server_cmsg = cras_connect_message {
- header: msg_header,
- proto_version: CRAS_PROTO_VER,
- direction,
- stream_id,
- stream_type: CRAS_STREAM_TYPE::CRAS_STREAM_TYPE_DEFAULT,
- buffer_frames: block_size,
- cb_threshold: block_size,
- flags: 0,
- format: audio_format,
- dev_idx: device_index.unwrap_or(CRAS_SPECIAL_DEVICE::NO_DEVICE as u32),
- effects: 0,
- client_type: self.client_type,
- client_shm_size: 0,
- buffer_offsets: [0, 0],
- };
-
- // Creates AudioSocket pair
- let (sock1, sock2) = UnixStream::pair()?;
-
- // Sends `CRAS_SERVER_CONNECT_STREAM` message
- let socks = [sock2.as_raw_fd()];
- self.server_socket
- .send_server_message_with_fds(&server_cmsg, &socks)?;
-
- let audio_socket = AudioSocket::new(sock1);
- loop {
- let result = CrasClient::wait_for_message(&mut self.server_socket)?;
- if let ServerResult::StreamConnected(_stream_id, header_fd, samples_fd) = result {
- return CrasStream::try_new(
- stream_id,
- self.server_socket.try_clone()?,
- block_size,
- direction,
- rate,
- channel_num,
- format.into(),
- audio_socket,
- header_fd,
- samples_fd,
- )
- .map_err(Error::CrasStreamError);
- }
- }
- }
-
- /// Creates a new playback stream pinned to the device at `device_index`.
- ///
- /// # Arguments
- ///
- /// * `device_index` - The device to which the stream will be attached.
- /// * `num_channels` - The count of audio channels for the stream.
- /// * `format` - The format to use for stream audio samples.
- /// * `frame_rate` - The sample rate of the stream.
- /// * `buffer_size` - The transfer size granularity in frames.
- #[allow(clippy::type_complexity)]
- pub fn new_pinned_playback_stream(
- &mut self,
- device_index: u32,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> std::result::Result<(Box<dyn StreamControl>, Box<dyn PlaybackBufferStream>), BoxError>
- {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(self.create_stream::<CrasPlaybackData>(
- Some(device_index),
- buffer_size as u32,
- CRAS_STREAM_DIRECTION::CRAS_STREAM_OUTPUT,
- frame_rate,
- num_channels,
- format,
- )?),
- ))
- }
-
- /// Creates a new capture stream pinned to the device at `device_index`.
- ///
- /// This is useful for, among other things, capturing from a loopback
- /// device.
- ///
- /// # Arguments
- ///
- /// * `device_index` - The device to which the stream will be attached.
- /// * `num_channels` - The count of audio channels for the stream.
- /// * `format` - The format to use for stream audio samples.
- /// * `frame_rate` - The sample rate of the stream.
- /// * `buffer_size` - The transfer size granularity in frames.
- #[allow(clippy::type_complexity)]
- pub fn new_pinned_capture_stream(
- &mut self,
- device_index: u32,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> std::result::Result<(Box<dyn StreamControl>, Box<dyn CaptureBufferStream>), BoxError> {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(self.create_stream::<CrasCaptureData>(
- Some(device_index),
- buffer_size as u32,
- CRAS_STREAM_DIRECTION::CRAS_STREAM_INPUT,
- frame_rate,
- num_channels,
- format,
- )?),
- ))
- }
-
- // Blocks handling the first server message received from `socket`.
- fn wait_for_message(socket: &mut CrasServerSocket) -> Result<ServerResult> {
- #[derive(PollToken)]
- enum Token {
- ServerMsg,
- }
- let poll_ctx: PollContext<Token> =
- PollContext::new().and_then(|pc| pc.add(socket, Token::ServerMsg).and(Ok(pc)))?;
-
- let events = poll_ctx.wait()?;
- // Check the first readable message
- let tokens: Vec<Token> = events.iter_readable().map(|e| e.token()).collect();
- tokens
- .get(0)
- .ok_or(Error::UnexpectedExit)
- .and_then(|ref token| {
- match token {
- Token::ServerMsg => ServerResult::handle_server_message(socket),
- }
- .map_err(Into::into)
- })
- }
-
- /// Returns any open file descriptors needed by CrasClient.
- /// This function is shared between StreamSource and ShmStreamSource.
- fn keep_fds(&self) -> Vec<RawFd> {
- vec![self.server_socket.as_raw_fd()]
- }
-}
-
-impl<'a> StreamSource for CrasClient<'a> {
- #[allow(clippy::type_complexity)]
- fn new_playback_stream(
- &mut self,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> std::result::Result<(Box<dyn StreamControl>, Box<dyn PlaybackBufferStream>), BoxError>
- {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(self.create_stream::<CrasPlaybackData>(
- None,
- buffer_size as u32,
- CRAS_STREAM_DIRECTION::CRAS_STREAM_OUTPUT,
- frame_rate,
- num_channels,
- format,
- )?),
- ))
- }
-
- #[allow(clippy::type_complexity)]
- fn new_capture_stream(
- &mut self,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- ) -> std::result::Result<(Box<dyn StreamControl>, Box<dyn CaptureBufferStream>), BoxError> {
- if self.cras_capture {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(self.create_stream::<CrasCaptureData>(
- None,
- buffer_size as u32,
- CRAS_STREAM_DIRECTION::CRAS_STREAM_INPUT,
- frame_rate,
- num_channels,
- format,
- )?),
- ))
- } else {
- Ok((
- Box::new(NoopStreamControl::new()),
- Box::new(NoopCaptureStream::new(
- num_channels,
- format,
- frame_rate,
- buffer_size,
- )),
- ))
- }
- }
-
- fn keep_fds(&self) -> Option<Vec<RawFd>> {
- Some(CrasClient::keep_fds(self))
- }
-}
-
-impl<'a> ShmStreamSource for CrasClient<'a> {
- fn new_stream(
- &mut self,
- direction: StreamDirection,
- num_channels: usize,
- format: SampleFormat,
- frame_rate: u32,
- buffer_size: usize,
- effects: &[StreamEffect],
- client_shm: &SharedMemory,
- buffer_offsets: [u64; 2],
- ) -> std::result::Result<Box<dyn ShmStream>, BoxError> {
- if direction == StreamDirection::Capture && !self.cras_capture {
- return Ok(Box::new(NullShmStream::new(
- buffer_size,
- num_channels,
- format,
- frame_rate,
- )));
- }
-
- let buffer_size = buffer_size as u32;
-
- // Prepares server message
- let stream_id = self.next_server_stream_id();
- let audio_format = cras_audio_format_packed::new(
- format.into(),
- frame_rate,
- num_channels,
- direction.into(),
- );
- let msg_header = cras_server_message {
- length: mem::size_of::<cras_connect_message>() as u32,
- id: CRAS_SERVER_MESSAGE_ID::CRAS_SERVER_CONNECT_STREAM,
- };
-
- let server_cmsg = cras_connect_message {
- header: msg_header,
- proto_version: CRAS_PROTO_VER,
- direction: direction.into(),
- stream_id,
- stream_type: CRAS_STREAM_TYPE::CRAS_STREAM_TYPE_DEFAULT,
- buffer_frames: buffer_size,
- cb_threshold: buffer_size,
- flags: 0,
- format: audio_format,
- dev_idx: CRAS_SPECIAL_DEVICE::NO_DEVICE as u32,
- effects: effects.iter().collect::<CrasStreamEffect>().into(),
- client_type: self.client_type,
- client_shm_size: client_shm.size(),
- buffer_offsets,
- };
-
- // Creates AudioSocket pair
- let (sock1, sock2) = UnixStream::pair()?;
-
- // Sends `CRAS_SERVER_CONNECT_STREAM` message
- let fds = [sock2.as_raw_fd(), client_shm.as_raw_fd()];
- self.server_socket
- .send_server_message_with_fds(&server_cmsg, &fds)?;
-
- loop {
- let result = CrasClient::wait_for_message(&mut self.server_socket)?;
- if let ServerResult::StreamConnected(_stream_id, header_fd, _samples_fd) = result {
- let audio_socket = AudioSocket::new(sock1);
- let stream = CrasShmStream::try_new(
- stream_id,
- self.server_socket.try_clone()?,
- audio_socket,
- direction,
- num_channels,
- frame_rate,
- format,
- header_fd,
- client_shm.size() as usize,
- )?;
- return Ok(Box::new(stream));
- }
- }
- }
-
- fn keep_fds(&self) -> Vec<RawFd> {
- CrasClient::keep_fds(self)
- }
-}
diff --git a/cras/configure.ac b/cras/configure.ac
deleted file mode 100644
index f39a14a6..00000000
--- a/cras/configure.ac
+++ /dev/null
@@ -1,206 +0,0 @@
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-AC_INIT([cras], [0.1], [dgreid@chromium.org],
- [cras], [http://www.chromium.org/])
-AC_PREREQ([2.59])
-
-AC_CANONICAL_HOST
-
-AM_INIT_AUTOMAKE([1.10 -Wall no-define])
-#AC_CONFIG_HEADERS([config.h])
-
-# To compile with full logs, use V=1 with make instead.
-AM_SILENT_RULES([yes])
-
-m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
-AC_PROG_LIBTOOL
-AC_PROG_CC
-# c++ unit test (gtest).
-AC_PROG_CXX
-AC_LANG_C
-AM_PROG_CC_C_O
-PKG_PROG_PKG_CONFIG
-AC_CONFIG_FILES([Makefile src/Makefile libcras.pc])
-
-PKG_CHECK_MODULES([LIBSPEEX], [ speexdsp >= 1.2 ])
-PKG_CHECK_MODULES([ASOUNDLIB], [ alsa >= 1.1.0 ])
-
-AC_CHECK_HEADERS([iniparser/iniparser.h])
-
-AC_ARG_ENABLE([dbus], AS_HELP_STRING([--disable-dbus], [Disable all DBUS uses]), have_dbus=$enableval, have_dbus=yes)
-AM_CONDITIONAL(HAVE_DBUS, test "$have_dbus" = "yes")
-if test "$have_dbus" = "yes"; then
- PKG_CHECK_MODULES([DBUS], [ dbus-1 >= 1.4.12 ])
- AS_VAR_APPEND([DBUS_CFLAGS], [" -DCRAS_DBUS"])
-else
- DBUS_CFLAGS=
- DBUS_LIBS=
-fi
-AC_SUBST(DBUS_LIBS)
-AC_SUBST(DBUS_CFLAGS)
-
-AC_ARG_ENABLE([selinux], AS_HELP_STRING([--enable-selinux], [Enable SELinux calls]), have_selinux=$enableval, have_selinux=no)
-AM_CONDITIONAL(HAVE_SELINUX, test "$have_selinux" = "yes")
-if test "$have_selinux" = "yes"; then
- PKG_CHECK_MODULES([SELINUX], [ libselinux ])
- AS_VAR_APPEND([SELINUX_CFLAGS], [" -DCRAS_SELINUX"])
-else
- SELINUX_CFLAGS=
- SELINUX_LIBS=
-fi
-AC_SUBST(SELINUX_CFLAGS)
-AC_SUBST(SELINUX_LIBS)
-
-# WEBRTC APM support
-AC_ARG_ENABLE([webrtc-apm], AS_HELP_STRING([--enable-webrtc-apm], [Enable webrtc-apm uses]), have_webrtc_apm=$enableval, have_webrtc_apm=no)
-AM_CONDITIONAL(HAVE_WEBRTC_APM, test "$have_webrtc_apm" = "yes")
-if test "$have_webrtc_apm" = "yes"; then
- PKG_CHECK_MODULES([WEBRTC_APM], [ libwebrtc_apm ])
- AC_DEFINE(HAVE_WEBRTC_APM, 1, [Define to use webrtc-apm.])
-else
- WEBRTC_APM_LIBS=
-fi
-AC_SUBST(WEBRTC_APM_LIBS)
-
-# Build fuzzer binaries
-AC_ARG_ENABLE([fuzzer], AS_HELP_STRING([--enable-fuzzer], [Enable fuzzer build]), have_fuzzer=$enableval, have_fuzzer=no)
-AM_CONDITIONAL(HAVE_FUZZER, test "$have_fuzzer" = "yes")
-if test "$have_fuzzer" = "yes"; then
- AC_DEFINE(HAVE_FUZZER, 1, [Define to build fuzzers.])
-fi
-
-PKG_CHECK_MODULES([SBC], [ sbc >= 1.0 ])
-AC_CHECK_HEADERS([iniparser/iniparser.h iniparser.h], [FOUND_INIPARSER=1;break])
-test [$FOUND_INIPARSER] || AC_MSG_ERROR([Missing iniparser, please install.])
-AC_SEARCH_LIBS([LADSPA], [ladspa-sdk], [], [
- AC_CHECK_HEADERS([ladspa.h], [], [
- AC_MSG_ERROR([Missing ladspa-sdk, please install.])
- ])
-])
-PKG_CHECK_MODULES([UDEV], [ libudev >= 1.0 ])
-PKG_CHECK_MODULES([GTEST], [ gtest >= 1.0 ])
-AC_CHECK_LIB(asound, snd_pcm_ioplug_create,,
- AC_ERROR([*** libasound has no external plugin SDK]), -ldl)
-
-AC_ARG_ENABLE([alsa-plugin], AS_HELP_STRING([--disable-alsa-plugin],
- [Disable building of ALSA plugin]))
-
-AC_ARG_ENABLE([metrics], AS_HELP_STRING([--enable-metrics], [Enable metrics uses]), have_metrics=$enableval, have_metrics=no)
-if test "$have_metrics" = "yes"; then
- AC_DEFINE(HAVE_LIB_METRICS, 1, [Define to use libmetrics])
- METRICS_LIBS=-lmetrics
-else
- METRICS_LIBS=
-fi
-AC_SUBST(METRICS_LIBS)
-
-# Check if the system copy of the cras rust library should be used. If not, make sure cargo and rustc are present to build it.
-AC_ARG_WITH([system-cras-rust],
- AS_HELP_STRING([--with-system-cras-rust], [Use the system provided cras_rust library]),
- with_system_rust=$enableval,
- with_system_rust=no)
-AM_CONDITIONAL(WITH_SYSTEM_RUST, test "$with_system_rust" = "yes")
-if test "$with_system_rust" = "no"; then
- AC_CHECK_PROG(CARGO, [cargo], [yes], [no])
- AS_IF(test x$CARGO = xno,
- AC_MSG_ERROR([cargo is required to build cras rust lib.])
- )
- AC_CHECK_PROG(RUSTC, [rustc], [yes], [no])
- AS_IF(test x$RUSTC = xno,
- AC_MSG_ERROR([rustc is required to build cras rust lib.])
- )
-fi
-
-# Determine ALSA plugin directory.
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-test "x$exec_prefix" = xNONE && exec_prefix=$prefix
-
-AC_ARG_WITH(plugindir,
- AS_HELP_STRING([--with-plugindir=dir],
- [path where ALSA plugin files are stored]),
- plugindir="$withval", plugindir="")
-if test -z "$plugindir"; then
- eval dir="$libdir"
- case "$dir" in
- /*) ;;
- *) dir="$dir"
- esac
- plugindir="$dir/alsa-lib"
-fi
-AC_DEFINE_UNQUOTED(ALSA_PLUGIN_DIR, "$plugindir",
- [directory containing ALSA add-on modules])
-ALSA_PLUGIN_DIR="$plugindir"
-AC_SUBST(ALSA_PLUGIN_DIR)
-
-# Determine CRAS configuration directory.
-eval cras_config_file_dir="$sysconfdir/cras"
-AC_DEFINE_UNQUOTED(CRAS_CONFIG_FILE_DIR, "$cras_config_file_dir",
- [directory containing CRAS configuration])
-
-# CRAS socket dir
-AC_ARG_WITH(socketdir,
- AS_HELP_STRING([--with-socketdir=dir],
- [path where CRAS stores its sockets]),
- socketdir="$withval",
- socketdir="/run/cras")
-AC_DEFINE_UNQUOTED(CRAS_SOCKET_FILE_DIR, "$socketdir",
- [directory containing CRAS socket files])
-
-# SSE4_2 support
-AC_ARG_ENABLE(sse42, [AS_HELP_STRING([--enable-sse42],[enable SSE42 optimizations])], have_sse42=$enableval, have_sse42=yes)
-if test "x$host_cpu" != xx86_64; then
- have_sse42=no
-fi
-if test "$have_sse42" = "yes"; then
- AC_DEFINE(HAVE_SSE42,1,[Define to enable SSE42 optimizations.])
- SSE42_CFLAGS="-DOPS_SSE42 -msse4.2 -ffast-math"
-fi
-AM_CONDITIONAL(HAVE_SSE42, test "$have_sse42" = "yes")
-AC_SUBST(SSE42_CFLAGS)
-
-# AVX support
-AC_ARG_ENABLE(avx, [AS_HELP_STRING([--enable-avx],[enable AVX optimizations])], have_avx=$enableval, have_avx=yes)
-if test "x$host_cpu" != xx86_64; then
- have_avx=no
-fi
-if test "$have_avx" = "yes"; then
- AC_DEFINE(HAVE_AVX,1,[Define to enable AVX optimizations.])
- AVX_CFLAGS="-DOPS_AVX -mavx -ffast-math"
-fi
-AM_CONDITIONAL(HAVE_AVX, test "$have_avx" = "yes")
-AC_SUBST(AVX_CFLAGS)
-
-# AVX2 support
-AC_ARG_ENABLE(avx2, [AS_HELP_STRING([--enable-avx2],[enable AVX2 optimizations])], have_avx2=$enableval, have_avx2=yes)
-if test "x$host_cpu" != xx86_64; then
- have_avx2=no
-fi
-if test "$have_avx2" = "yes"; then
- AC_DEFINE(HAVE_AVX2,1,[Define to enable AVX2 optimizations.])
- AVX2_CFLAGS="-DOPS_AVX2 -mavx2 -ffast-math"
-fi
-AM_CONDITIONAL(HAVE_AVX2, test "$have_avx2" = "yes")
-AC_SUBST(AVX2_CFLAGS)
-
-# FMA support
-AC_ARG_ENABLE(fma, [AS_HELP_STRING([--enable-fma],[enable FMA optimizations])], have_fma=$enableval, have_fma=yes)
-if test "x$host_cpu" != xx86_64; then
- have_fma=no
-fi
-if test "$have_fma" = "yes"; then
- AC_DEFINE(HAVE_FMA,1,[Define to enable FMA optimizations.])
- FMA_CFLAGS="-DOPS_FMA -mavx2 -mfma -ffast-math"
-fi
-AM_CONDITIONAL(HAVE_FMA, test "$have_fma" = "yes")
-AC_SUBST(FMA_CFLAGS)
-
-AC_OUTPUT
-
-AC_MSG_NOTICE([
-
-Enable SSE42: ${have_sse42}
-Enable AVX: ${have_avx}
-Enable AVX2: ${have_avx2}
-Enable FMA: ${have_fma}
-])
diff --git a/cras/cras.mk b/cras/cras.mk
deleted file mode 100644
index 8ad715e4..00000000
--- a/cras/cras.mk
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#include $(ADHD_DIR)/defs/definitions.mk
-CWARN=
-CFLAGS=
-
-$(ADHD_DIR)/cras/configure: $(ADHD_DIR)/cras/configure.ac \
- $(ADHD_DIR)/cras/Makefile.am
- (cd $(ADHD_DIR)/cras && \
- $(ADHD_DIR)/cras/git_prepare.sh)
-
-$(ADHD_DIR)/cras/Makefile: $(ADHD_DIR)/cras/configure
- (cd $(ADHD_DIR)/cras && \
- $(ADHD_DIR)/cras/configure \
- --build=$(CBUILD) \
- --host=$(CHOST) \
- --prefix=/usr \
- --mandir=/usr/share/man \
- --infodir=/usr/share/info \
- --datadir=/usr/share \
- --sysconfdir=/etc \
- --localstatedir=/var/lib)
-
-cras: $(ADHD_DIR)/cras/Makefile
- (cd $(ADHD_DIR)/cras && \
- $(MAKE) -f $(ADHD_DIR)/cras/Makefile)
-
-cras_install:
- (cd $(ADHD_DIR)/cras && \
- $(MAKE) -f $(ADHD_DIR)/cras/Makefile install)
-
diff --git a/cras/examples/Makefile b/cras/examples/Makefile
deleted file mode 100644
index 2e236929..00000000
--- a/cras/examples/Makefile
+++ /dev/null
@@ -1,5 +0,0 @@
-cplay: cplay.c
- gcc -o cplay cplay.c -lcras
-
-cplay_buffer: cplay_buffer.c
- gcc -o cplay_buffer cplay_buffer.c -lcras
diff --git a/cras/examples/cplay.c b/cras/examples/cplay.c
deleted file mode 100644
index eb6d8e6c..00000000
--- a/cras/examples/cplay.c
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Copyright (c) 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * This example plays a file. The filename is the only argument. The file is
- * assumed to contain raw stereo 16-bit PCM data to be played at 48kHz.
- * usage: cplay <filename>
- */
-
-#include <cras_client.h>
-#include <cras_helpers.h>
-#include <stdio.h>
-#include <stdint.h>
-
-/* Used as a cookie for the playing stream. */
-struct stream_data {
- int fd;
- unsigned int frame_bytes;
-};
-
-/* Run from callback thread. */
-static int put_samples(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- struct stream_data *data = (struct stream_data *)user_arg;
- int nread;
-
- nread = read(data->fd, playback_samples, frames * data->frame_bytes);
- if (nread <= 0)
- return EOF;
-
- return nread / data->frame_bytes;
-}
-
-/* Run from callback thread. */
-static int stream_error(struct cras_client *client, cras_stream_id_t stream_id,
- int err, void *arg)
-{
- printf("Stream error %d\n", err);
- exit(err);
- return 0;
-}
-
-int main(int argc, char **argv)
-{
- struct cras_client *client;
- cras_stream_id_t stream_id;
- struct stream_data *data;
- int rc = 0;
- int fd;
- const unsigned int block_size = 4800;
- const unsigned int num_channels = 2;
- const unsigned int rate = 48000;
- const unsigned int flags = 0;
-
- if (argc < 2)
- printf("Usage: %s filename\n", argv[0]);
-
- fd = open(argv[1], O_RDONLY);
- if (fd < 0) {
- perror("failed to open file");
- return -errno;
- }
-
- rc = cras_helper_create_connect(&client);
- if (rc < 0) {
- fprintf(stderr, "Couldn't create client.\n");
- close(fd);
- return rc;
- }
-
- data = malloc(sizeof(*data));
- data->fd = fd;
- data->frame_bytes = 4;
-
- rc = cras_helper_add_stream_simple(client, CRAS_STREAM_OUTPUT, data,
- put_samples, stream_error,
- SND_PCM_FORMAT_S16_LE, rate,
- num_channels, NO_DEVICE, &stream_id);
- if (rc < 0) {
- fprintf(stderr, "adding a stream %d\n", rc);
- goto destroy_exit;
- }
-
- /* At this point the stream has been added and audio callbacks will
- * start to fire. This app can now go off and do other things, but this
- * example just loops forever. */
- while (1) {
- sleep(1);
- }
-
-destroy_exit:
- cras_client_destroy(client);
- close(fd);
- free(data);
- return rc;
-}
diff --git a/cras/examples/cplay_buffer.c b/cras/examples/cplay_buffer.c
deleted file mode 100644
index 07e5d0f8..00000000
--- a/cras/examples/cplay_buffer.c
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Copyright (c) 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * This example plays a file. The filename is the only argument. The file is
- * assumed to contain raw stereo 16-bit PCM data to be played at 48kHz.
- * usage: cplay <filename>
- */
-
-#include <cras_client.h>
-#include <cras_helpers.h>
-#include <sys/param.h>
-#include <stdio.h>
-#include <stdint.h>
-
-int main(int argc, char **argv)
-{
- struct cras_client *client;
- cras_stream_id_t stream_id;
- int rc = 0;
- int fd;
- const unsigned int num_channels = 2;
- const unsigned int rate = 48000;
- const unsigned int flags = 0;
- uint8_t *buffer;
- int nread;
-
- if (argc < 2)
- printf("Usage: %s filename\n", argv[0]);
-
- fd = open(argv[1], O_RDONLY);
- if (fd < 0) {
- perror("failed to open file");
- return -errno;
- }
-
- buffer = malloc(48000 * 4 * 5);
-
- nread = read(fd, buffer, 48000 * 4 * 5);
- if (nread <= 0) {
- free(buffer);
- close(fd);
- return nread;
- }
-
- rc = cras_helper_create_connect(&client);
- if (rc < 0) {
- fprintf(stderr, "Couldn't create client.\n");
- free(buffer);
- close(fd);
- return rc;
- }
-
- rc = cras_helper_play_buffer(client, buffer, nread / 4,
- SND_PCM_FORMAT_S16_LE, rate, num_channels,
- cras_client_get_first_dev_type_idx(
- client,
- CRAS_NODE_TYPE_INTERNAL_SPEAKER,
- CRAS_STREAM_OUTPUT));
- if (rc < 0) {
- fprintf(stderr, "playing a buffer %d\n", rc);
- goto destroy_exit;
- }
-
- /* At this point the stream has been added and audio callbacks will
- * start to fire. This app can now go off and do other things, but this
- * example just loops forever. */
- while (1) {
- sleep(1);
- }
-
-destroy_exit:
- cras_client_destroy(client);
- free(buffer);
- close(fd);
- return rc;
-}
diff --git a/cras/git_prepare.sh b/cras/git_prepare.sh
deleted file mode 100755
index d53eb064..00000000
--- a/cras/git_prepare.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#!/bin/sh
-libtoolize && aclocal && autoconf && automake --add-missing
diff --git a/cras/install_deps.sh b/cras/install_deps.sh
deleted file mode 100755
index 6eac01a6..00000000
--- a/cras/install_deps.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/sh
-apt-get install -y \
- automake \
- build-essential \
- cmake \
- g++ \
- gdb \
- git \
- ladspa-sdk \
- libasound-dev \
- libdbus-1-dev \
- libncurses5-dev \
- libsbc-dev \
- libsndfile-dev \
- libspeexdsp-dev \
- libtool \
- libudev-dev \
- wget \
- zip
-cd /tmp
-git clone https://github.com/ndevilla/iniparser.git
-cd iniparser
-make
-cp libiniparser.* /usr/local/lib
-cp src/dictionary.h src/iniparser.h /usr/local/include
-chmod 644 /usr/local/include/dictionary.h /usr/local/include/iniparser.h
-chmod 644 /usr/local/lib/libiniparser.a
-chmod 755 /usr/local/lib/libiniparser.so.*
-
-cd /tmp
-git clone https://github.com/google/googletest.git -b v1.8.x
-cd googletest
-mkdir build
-cd build
-cmake .. -DBUILD_SHARED_LIBS=ON \
- -DINSTALL_GTEST=ON \
- -DCMAKE_INSTALL_PREFIX:PATH=/usr
-make
-make install
-
-# Need to build and install alsa so there is a static lib.
-mkdir -p /tmp/alsa-build &&
- cd /tmp/alsa-build && \
- wget ftp://ftp.alsa-project.org/pub/lib/alsa-lib-1.1.4.1.tar.bz2 && \
- bzip2 -f -d alsa-lib-* && \
- tar xf alsa-lib-* && \
- cd alsa-lib-* && \
- ./configure --enable-static --disable-shared && \
- make clean && \
- make -j$(nproc) all && \
- make install
diff --git a/cras/libcras.pc.in b/cras/libcras.pc.in
deleted file mode 100644
index 06375228..00000000
--- a/cras/libcras.pc.in
+++ /dev/null
@@ -1,11 +0,0 @@
-prefix=@prefix@
-exec_prefix=@exec_prefix@
-libdir=@libdir@
-includedir=@includedir@
-modlibexecdir=@modlibexecdir@
-
-Name: libcras
-Description: ChromeOS Audio Server Interface
-Version: @PACKAGE_VERSION@
-Libs: -L${libdir} -lcras
-Cflags: -I${includedir}
diff --git a/cras/src/Android.bp b/cras/src/Android.bp
deleted file mode 100644
index 17b9919a..00000000
--- a/cras/src/Android.bp
+++ /dev/null
@@ -1,44 +0,0 @@
-package {
- // See: http://go/android-license-faq
- // A large-scale-change added 'default_applicable_licenses' to import
- // all of the 'license_kinds' from "external_adhd_license"
- // to get the below license kinds:
- // SPDX-license-identifier-BSD
- // SPDX-license-identifier-LGPL
- default_applicable_licenses: ["external_adhd_license"],
-}
-
-cc_library_static {
- name: "libcras",
-
- srcs: [
- "common/cras_audio_format.c",
- "common/cras_config.c",
- "common/cras_file_wait.c",
- "common/cras_shm.c",
- "common/cras_util.c",
- "common/edid_utils.c",
- "libcras/cras_client.c",
- "libcras/cras_helpers.c",
- ],
-
- shared_libs: [
- "libcutils",
- "libtinyalsa",
- ],
-
- export_include_dirs: [
- "common",
- "libcras",
- ],
-
- cflags: [
- "-DCRAS_SOCKET_FILE_DIR=\"/var/run/cras\"",
- "-Wall",
- "-Werror",
- "-Wno-error=missing-field-initializers",
- "-Wno-sign-compare",
- "-Wno-unused-function",
- "-Wno-unused-parameter",
- ],
-}
diff --git a/cras/src/Makefile.am b/cras/src/Makefile.am
deleted file mode 100644
index 1e89f811..00000000
--- a/cras/src/Makefile.am
+++ /dev/null
@@ -1,1078 +0,0 @@
-# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-AUTOMAKE_OPTIONS = subdir-objects
-ACLOCAL_AMFLAGS = ${ACLOCAL_FLAGS}
-
-if HAVE_SSE42
-CRAS_SSE4_2 = libcrasmix_sse42.la
-else
-CRAS_SSE4_2 =
-endif
-
-if HAVE_AVX
-CRAS_AVX = libcrasmix_avx.la
-else
-CRAS_AVX =
-endif
-
-if HAVE_AVX2
-CRAS_AVX2 = libcrasmix_avx2.la
-else
-CRAS_AVX2 =
-endif
-
-if HAVE_FMA
-CRAS_FMA = libcrasmix_fma.la
-else
-CRAS_FMA =
-endif
-
-if HAVE_WEBRTC_APM
-CRAS_WEBRTC_APM_SOURCES = \
- server/cras_apm_list.c
-else
-CRAS_WEBRTC_APM_SOURCES =
-endif
-
-CRAS_UT_TMPDIR_CFLAGS=-DCRAS_UT_TMPDIR=\"/tmp\"
-COMMON_CPPFLAGS = -O2 -Wall -Werror -Wno-error=cpp
-COMMON_SIMD_CPPFLAGS = -O3 -Wall -Werror -Wno-error=cpp
-
-bin_PROGRAMS = cras cras_test_client cras_monitor cras_router
-noinst_PROGRAMS =
-
-if HAVE_DBUS
-CRAS_DBUS_SOURCES = \
- common/cras_sbc_codec.c \
- common/packet_status_logger.c \
- server/cras_bt_manager.c \
- server/cras_bt_adapter.c \
- server/cras_bt_device.c \
- server/cras_bt_transport.c \
- server/cras_bt_endpoint.c \
- server/cras_bt_player.c \
- server/cras_bt_io.c \
- server/cras_bt_profile.c \
- server/cras_bt_battery_provider.c \
- server/cras_dbus.c \
- server/cras_dbus_util.c \
- server/cras_dbus_control.c \
- server/cras_hfp_ag_profile.c \
- server/cras_hfp_iodev.c \
- server/cras_hfp_alsa_iodev.c \
- server/cras_hfp_info.c \
- server/cras_hfp_slc.c \
- server/cras_a2dp_endpoint.c \
- server/cras_a2dp_info.c \
- server/cras_a2dp_iodev.c \
- server/cras_telephony.c \
- server/cras_utf8.c
-else
-CRAS_DBUS_SOURCES =
-endif
-
-if HAVE_SELINUX
-CRAS_SELINUX_SOURCES = common/cras_selinux_helper.c
-CRAS_SELINUX_UNITTEST_SOURCES = tests/cras_selinux_helper_unittest.c
-else
-CRAS_SELINUX_SOURCES =
-CRAS_SELINUX_UNITTEST_SOURCES =
-endif
-
-cras_server_SOURCES = \
- $(CRAS_DBUS_SOURCES) \
- $(CRAS_SELINUX_SOURCES) \
- $(CRAS_WEBRTC_APM_SOURCES) \
- common/cras_audio_format.c \
- common/cras_checksum.c \
- common/cras_config.c \
- common/cras_metrics.c \
- common/cras_shm.c \
- common/cras_util.c \
- common/dumper.c \
- common/edid_utils.c \
- common/sfh.c \
- dsp/biquad.c \
- dsp/crossover.c \
- dsp/crossover2.c \
- dsp/dcblock.c \
- dsp/drc.c \
- dsp/drc_kernel.c \
- dsp/drc_math.c \
- dsp/dsp_util.c \
- dsp/eq.c \
- dsp/eq2.c \
- plc/cras_plc.c\
- server/audio_thread.c \
- server/buffer_share.c \
- server/config/cras_board_config.c \
- server/config/cras_card_config.c \
- server/config/cras_device_blocklist.c \
- server/cras_alert.c \
- server/cras_alsa_card.c \
- server/cras_alsa_helpers.c \
- server/cras_alsa_io.c \
- server/cras_alsa_jack.c \
- server/cras_alsa_mixer.c \
- server/cras_alsa_mixer_name.c \
- server/cras_alsa_plugin_io.c \
- server/cras_alsa_ucm.c \
- server/cras_alsa_ucm_section.c \
- server/cras_audio_area.c \
- server/cras_audio_thread_monitor.c \
- server/cras_device_monitor.c \
- server/cras_dsp.c \
- server/cras_dsp_ini.c \
- server/cras_dsp_mod_builtin.c \
- server/cras_dsp_mod_ladspa.c \
- server/cras_dsp_pipeline.c \
- server/cras_empty_iodev.c \
- server/cras_expr.c \
- server/cras_fmt_conv.c \
- server/cras_fmt_conv_ops.c \
- server/cras_gpio_jack.c \
- server/cras_hotword_handler.c \
- server/cras_iodev.c \
- server/cras_iodev_list.c \
- server/cras_loopback_iodev.c \
- server/cras_main_message.c \
- server/cras_mix.c \
- server/cras_non_empty_audio_handler.c \
- server/cras_observer.c \
- server/cras_ramp.c \
- server/cras_rclient.c \
- server/cras_rclient_util.c \
- server/cras_control_rclient.c \
- server/cras_playback_rclient.c \
- server/cras_capture_rclient.c \
- server/cras_unified_rclient.c \
- server/cras_rstream.c \
- server/cras_rstream_config.c \
- server/cras_server_metrics.c \
- server/cras_system_state.c \
- server/cras_tm.c \
- server/cras_udev.c \
- server/cras_volume_curve.c \
- server/dev_io.c \
- server/dev_stream.c \
- server/ewma_power.c \
- server/input_data.c \
- server/linear_resampler.c \
- server/polled_interval_checker.c \
- server/server_stream.c \
- server/stream_list.c \
- server/test_iodev.c \
- server/softvol_curve.c
-
-SERVER_RUST_SRCDIR = $(top_srcdir)/src/server/rust
-
-libcrasserver_la_SOURCES = \
- $(cras_server_SOURCES)
-libcrasserver_la_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- -I$(SERVER_RUST_SRCDIR)/src/headers \
- $(DBUS_CFLAGS) $(SBC_CFLAGS) $(SELINUX_CFLAGS)
-libcrasserver_la_LIBADD = \
- $(CRAS_RUST) \
- libcrasmix.la \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- -lpthread -lasound -lrt -liniparser -ludev -ldl -lm -lspeexdsp \
- $(SBC_LIBS) \
- $(DBUS_LIBS) \
- $(SELINUX_LIBS)
-
-cras_SOURCES = \
- server/cras.c \
- server/cras_server.c
-
-cras_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(SBC_CFLAGS)
-
-cras_LDADD = \
- libcrasmix.la \
- libcrasserver.la \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- $(CRAS_RUST) \
- -lpthread -lasound -lrt -liniparser -ludev -ldl -lm -lspeexdsp \
- $(METRICS_LIBS) \
- $(SBC_LIBS) \
- $(DBUS_LIBS) \
- $(WEBRTC_APM_LIBS)
-
-noinst_LTLIBRARIES = \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- libcrasmix.la \
- libcrasserver.la
-
-libcrasmix_la_SOURCES = \
- server/cras_mix_ops.c
-
-libcrasmix_la_CFLAGS = \
- $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(SBC_CFLAGS)
-
-libcrasmix_sse42_la_SOURCES = \
- server/cras_mix_ops.c
-
-libcrasmix_sse42_la_CFLAGS = \
- $(COMMON_SIMD_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(SSE42_CFLAGS)
-
-libcrasmix_avx_la_SOURCES = \
- server/cras_mix_ops.c
-
-libcrasmix_avx_la_CFLAGS = \
- $(COMMON_SIMD_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(AVX_CFLAGS)
-
-libcrasmix_avx2_la_SOURCES = \
- server/cras_mix_ops.c
-
-libcrasmix_avx2_la_CFLAGS = \
- $(COMMON_SIMD_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(AVX2_CFLAGS)
-
-libcrasmix_fma_la_SOURCES = \
- server/cras_mix_ops.c
-
-libcrasmix_fma_la_CFLAGS = \
- $(COMMON_SIMD_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(FMA_CFLAGS)
-
-lib_LTLIBRARIES = libcras.la
-libcras_la_SOURCES = \
- common/cras_audio_format.c \
- common/cras_config.c \
- common/cras_file_wait.c \
- common/cras_shm.c \
- common/cras_util.c \
- common/edid_utils.c \
- libcras/cras_client.c \
- libcras/cras_helpers.c
-
-include_HEADERS = \
- common/cras_audio_format.h \
- common/cras_config.h \
- common/cras_iodev_info.h \
- common/cras_messages.h \
- common/cras_shm.h \
- common/cras_types.h \
- common/cras_util.h \
- common/edid_utils.h \
- common/packet_status_logger.h \
- common/utlist.h \
- libcras/cras_client.h \
- libcras/cras_helpers.h
-
-libcras_la_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/libcras
-libcras_la_LIBADD = -lpthread -lasound -lrt
-libcras_la_LDFLAGS = -version-info 0:0:0
-
-asound_module_pcm_cras_LTLIBRARIES = libasound_module_pcm_cras.la
-asound_module_ctl_cras_LTLIBRARIES = libasound_module_ctl_cras.la
-asound_module_pcm_crasdir = @ALSA_PLUGIN_DIR@
-asound_module_ctl_crasdir = @ALSA_PLUGIN_DIR@
-libasound_module_pcm_cras_la_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/libcras
-libasound_module_pcm_cras_la_LDFLAGS = -module -avoid-version -export-dynamic -no-undefined \
- $(LDFLAGS_NOUNDEFINED)
-libasound_module_ctl_cras_la_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/libcras
-libasound_module_ctl_cras_la_LDFLAGS = -module -avoid-version -export-dynamic -no-undefined \
- $(LDFLAGS_NOUNDEFINED)
-libasound_module_pcm_cras_la_SOURCES = alsa_plugin/pcm_cras.c
-libasound_module_pcm_cras_la_LIBADD = -lasound libcras.la
-libasound_module_ctl_cras_la_SOURCES = alsa_plugin/ctl_cras.c
-libasound_module_ctl_cras_la_LIBADD = -lasound libcras.la
-
-if !WITH_SYSTEM_RUST
-RUST_FILES = \
- $(SERVER_RUST_SRCDIR)/Cargo.toml \
- $(SERVER_RUST_SRCDIR)/src/rate_estimator_bindings.rs \
- $(SERVER_RUST_SRCDIR)/src/rate_estimator.rs
-
-CRAS_RUST_TARGET_DIR = $(top_builddir)/src/server/rust/target
-CRAS_RUST = $(CRAS_RUST_TARGET_DIR)/release/libcras_rust.a
-$(CRAS_RUST): $(RUST_FILES)
- cargo build --release \
- --manifest-path $(SERVER_RUST_SRCDIR)/Cargo.toml \
- --target-dir $(CRAS_RUST_TARGET_DIR)
-
-clean-local:
- cargo clean --release \
- --manifest-path $(SERVER_RUST_SRCDIR)/Cargo.toml \
- --target-dir $(CRAS_RUST_TARGET_DIR)
-
-else
-CRAS_RUST = -lcras_rust
-endif
-
-# Inject a dependency between the installation rules of libcras and its modules.
-# This avoids a race when the modules are relinked before libcras is actually
-# installed.
-#
-# Automake will refuse to generate a rule that collides with a user-specified
-# one. The hide_install variable prevents automake from noticing these rules,
-# so everything else will behave as usual.
-hide_install=install
-$(hide_install)-asound_module_pcm_crasLTLIBRARIES: install-libLTLIBRARIES
-$(hide_install)-asound_module_ctl_crasLTLIBRARIES: install-libLTLIBRARIES
-
-# ==== Fuzzer section
-if HAVE_FUZZER
-FUZZERS = \
- cras_rclient_message_fuzzer \
- cras_hfp_slc_fuzzer
-
-noinst_PROGRAMS += $(FUZZERS)
-
-FUZZER_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config -I$(top_srcdir)/src/plc \
- $(DBUS_CFLAGS) $(SBC_CFLAGS)
-
-FUZZER_LDADD = \
- libcrasmix.la \
- libcrasserver.la \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- $(CRAS_RUST) \
- -lpthread -lasound -lrt -liniparser -ludev -ldl -lm -lspeexdsp \
- $(METRICS_LIBS) \
- $(SBC_LIBS) \
- $(DBUS_LIBS) \
- $(WEBRTC_APM_LIBS)
-
-cras_rclient_message_fuzzer_SOURCES = \
- fuzz/rclient_message.cc
-
-cras_rclient_message_fuzzer_CPPFLAGS = $(FUZZER_CPPFLAGS)
-cras_rclient_message_fuzzer_LDFLAGS = $(FUZZER_LDFLAGS)
-cras_rclient_message_fuzzer_LDADD = $(FUZZER_LDADD)
-
-cras_hfp_slc_fuzzer_SOURCES = \
- fuzz/cras_hfp_slc.cc
-
-cras_hfp_slc_fuzzer_CPPFLAGS = $(FUZZER_CPPFLAGS)
-cras_hfp_slc_fuzzer_LDFLAGS = $(FUZZER_LDFLAGS)
-cras_hfp_slc_fuzzer_LDADD = $(FUZZER_LDADD)
-endif
-
-# ==== Tests section
-if HAVE_DBUS
-DBUS_TESTS = \
- a2dp_info_unittest \
- a2dp_iodev_unittest \
- alsa_io_unittest \
- bt_device_unittest \
- bt_io_unittest \
- hfp_iodev_unittest \
- hfp_alsa_iodev_unittest \
- hfp_ag_profile_unittest \
- hfp_slc_unittest
-else
-DBUS_TESTS =
-endif
-
-if HAVE_WEBRTC_APM
-CRAS_WEBRTC_APM_TESTS = \
- apm_list_unittest
-else
-CRAS_WEBRTC_APM_TESTS =
-endif
-
-TESTS = \
- $(DBUS_TESTS) \
- $(CRAS_WEBRTC_APM_TESTS) \
- audio_area_unittest \
- audio_format_unittest \
- audio_thread_unittest \
- audio_thread_monitor_unittest \
- alert_unittest \
- alsa_card_unittest \
- alsa_helpers_unittest \
- alsa_jack_unittest \
- alsa_mixer_unittest \
- alsa_ucm_unittest \
- array_unittest \
- biquad_unittest \
- byte_buffer_unittest \
- card_config_unittest \
- checksum_unittest \
- cras_abi_unittest \
- cras_client_unittest \
- cras_tm_unittest \
- device_monitor_unittest \
- dev_io_unittest \
- dev_stream_unittest \
- device_blocklist_unittest \
- dsp_core_unittest \
- dsp_ini_unittest \
- dsp_pipeline_unittest \
- dsp_unittest \
- dumper_unittest \
- edid_utils_unittest \
- empty_iodev_unittest \
- expr_unittest \
- ewma_power_unittest \
- file_wait_unittest \
- float_buffer_unittest \
- fmt_conv_unittest \
- fmt_conv_ops_unittest \
- hfp_info_unittest \
- buffer_share_unittest \
- input_data_unittest \
- iodev_list_unittest \
- iodev_unittest \
- loopback_iodev_unittest \
- mix_unittest \
- linear_resampler_unittest \
- observer_unittest \
- polled_interval_checker_unittest \
- ramp_unittest \
- rate_estimator_unittest \
- control_rclient_unittest \
- playback_rclient_unittest \
- capture_rclient_unittest \
- rstream_unittest \
- shm_unittest \
- server_metrics_unittest \
- softvol_curve_unittest \
- stream_list_unittest \
- system_state_unittest \
- timing_unittest \
- utf8_unittest \
- util_unittest \
- volume_curve_unittest
-
-check_PROGRAMS = $(TESTS)
-
-cras_test_client_SOURCES = tools/cras_test_client/cras_test_client.c
-cras_test_client_LDADD = -lm libcras.la
-cras_test_client_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/libcras \
- -I$(top_srcdir)/src/common -I$(top_builddir)/src/common
-
-tools/cras_test_client/cras_test_client.c: common/cras_version.h
-
-cras_monitor_SOURCES = tools/cras_monitor/cras_monitor.c
-cras_monitor_LDADD = -lm libcras.la
-cras_monitor_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/libcras \
- -I$(top_srcdir)/src/common -I$(top_builddir)/src/common
-
-tools/cras_monitor/cras_monitor.c: common/cras_version.h
-
-cras_router_SOURCES = tools/cras_router/cras_router.c
-cras_router_LDADD = -lm libcras.la
-cras_router_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/libcras \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/dsp \
- -I$(top_srcdir)/src/server -I$(top_builddir)/src/common
-
-tools/cras_router/cras_router.c: common/cras_version.h
-
-CLEANFILES = common/cras_version.h
-.PHONY: common/cras_version.h
-common/cras_version.h:
- if echo "$(CPPFLAGS)" | grep -q -- '-DVCSID='; then \
- echo > $@.tmp; \
- else \
- commit="outoftree-$$(git rev-parse HEAD)"; \
- if [ -n "$$(git diff-index --name-only HEAD)" ]; then \
- commit="$${commit}-dirty"; \
- fi; \
- echo "#define VCSID \"$$commit\"" > $@.tmp; \
- fi
- diff $@.tmp $@ && rm -f $@.tmp || mv $@.tmp $@
-
-# dsp test programs (not run automatically)
-check_PROGRAMS += \
- crossover_test \
- crossover2_test \
- dcblock_test \
- drc_test \
- dsp_util_test \
- eq_test \
- eq2_test \
- cmpraw
-
-DSP_INCLUDE_PATHS = -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/common
-
-crossover_test_SOURCES = dsp/crossover.c dsp/biquad.c dsp/dsp_util.c \
- dsp/tests/crossover_test.c dsp/tests/dsp_test_util.c dsp/tests/raw.c
-crossover_test_LDADD = -lrt -lm
-crossover_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-crossover2_test_SOURCES = dsp/crossover2.c dsp/biquad.c dsp/dsp_util.c \
- dsp/tests/crossover2_test.c dsp/tests/dsp_test_util.c dsp/tests/raw.c
-crossover2_test_LDADD = -lrt -lm
-crossover2_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-dcblock_test_SOURCES = dsp/dcblock.c dsp/dsp_util.c dsp/tests/dcblock_test.c \
- dsp/tests/dsp_test_util.c dsp/tests/raw.c
-dcblock_test_LDADD = -lrt -lm
-dcblock_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-drc_test_SOURCES = dsp/drc.c dsp/drc_kernel.c dsp/drc_math.c \
- dsp/crossover2.c dsp/eq2.c dsp/biquad.c dsp/dsp_util.c \
- dsp/tests/drc_test.c dsp/tests/dsp_test_util.c dsp/tests/raw.c
-drc_test_LDADD = -lrt -lm
-drc_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-dsp_util_test_SOURCES = dsp/tests/dsp_util_test.c dsp/dsp_util.c
-dsp_util_test_LDADD = -lm
-dsp_util_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS) -Wno-error=strict-aliasing
-
-eq_test_SOURCES = dsp/biquad.c dsp/eq.c dsp/dsp_util.c dsp/tests/eq_test.c \
- dsp/tests/dsp_test_util.c dsp/tests/raw.c
-eq_test_LDADD = -lrt -lm
-eq_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-eq2_test_SOURCES = dsp/biquad.c dsp/eq2.c dsp/dsp_util.c dsp/tests/eq2_test.c \
- dsp/tests/dsp_test_util.c dsp/tests/raw.c
-eq2_test_LDADD = -lrt -lm
-eq2_test_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-cmpraw_SOURCES = dsp/tests/cmpraw.c dsp/tests/raw.c
-cmpraw_LDADD = -lm
-cmpraw_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-
-cras_plc_test_SOURCES = plc/cras_plc_test.c plc/cras_plc.c \
- common/cras_sbc_codec.c
-cras_plc_test_LDADD = -lrt -lm $(SBC_LIBS)
-cras_plc_test_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/plc \
- -I$(top_srcdir)/src/common \
- $(SBC_CFLAGS)
-check_PROGRAMS += cras_plc_test
-
-# unit tests
-alert_unittest_SOURCES = tests/alert_unittest.cc \
- server/cras_alert.c
-alert_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-alert_unittest_LDADD = -lgtest -lpthread
-
-alsa_card_unittest_SOURCES = tests/alsa_card_unittest.cc \
- server/cras_alsa_card.c server/cras_alsa_mixer_name.c \
- server/cras_alsa_ucm_section.c
-alsa_card_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config
-alsa_card_unittest_LDADD = -lgtest -lpthread
-
-alsa_helpers_unittest_SOURCES = tests/alsa_helpers_unittest.cc \
- common/cras_audio_format.c
-alsa_helpers_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-alsa_helpers_unittest_LDADD = -lgtest -lpthread
-
-audio_area_unittest_SOURCES = tests/audio_area_unittest.cc \
- server/cras_audio_area.c
-audio_area_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common
-audio_area_unittest_LDADD = -lgtest -lpthread
-
-audio_format_unittest_SOURCES = tests/audio_format_unittest.cc
-audio_format_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common
-audio_format_unittest_LDADD = -lgtest -lpthread
-
-if HAVE_DBUS
-a2dp_info_unittest_SOURCES = \
- server/cras_a2dp_info.c \
- tests/a2dp_info_unittest.cc \
- tests/sbc_codec_stub.cc
-a2dp_info_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common
-a2dp_info_unittest_LDADD = -lgtest -lpthread
-
-a2dp_iodev_unittest_SOURCES = tests/a2dp_iodev_unittest.cc
-a2dp_iodev_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common $(DBUS_CFLAGS)
-a2dp_iodev_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-endif
-
-alsa_io_unittest_SOURCES = tests/alsa_io_unittest.cc server/softvol_curve.c \
- common/sfh.c \
- server/cras_alsa_ucm_section.c \
- server/cras_alsa_mixer_name.c
-alsa_io_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) $(DBUS_CFLAGS) \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server/config
-alsa_io_unittest_LDADD = -lgtest -lpthread
-
-alsa_jack_unittest_SOURCES = tests/alsa_jack_unittest.cc \
- server/cras_alsa_jack.c \
- server/cras_alsa_ucm_section.c \
- server/cras_alsa_mixer_name.c
-alsa_jack_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-alsa_jack_unittest_LDADD = -lgtest -lpthread
-
-alsa_mixer_unittest_SOURCES = tests/alsa_mixer_unittest.cc \
- server/cras_alsa_mixer_name.c \
- server/cras_alsa_ucm_section.c
-alsa_mixer_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config
-alsa_mixer_unittest_LDADD = -lgtest -lpthread
-
-alsa_ucm_unittest_SOURCES = tests/alsa_ucm_unittest.cc \
- server/cras_alsa_mixer_name.c \
- server/cras_alsa_ucm_section.c
-alsa_ucm_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config
-alsa_ucm_unittest_LDADD = -lgtest -lpthread
-
-if HAVE_WEBRTC_APM
-apm_list_unittest_SOURCES = tests/apm_list_unittest.cc \
- server/cras_apm_list.c
-apm_list_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- $(DSP_INCLUDE_PATHS) \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config \
- $(WEBRTC_APM_CFLAGS)
-apm_list_unittest_LDADD = -lgtest -liniparser
-endif
-
-array_unittest_SOURCES = tests/array_unittest.cc
-array_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-array_unittest_LDADD = -lgtest -lpthread
-
-audio_thread_unittest_SOURCES = tests/audio_thread_unittest.cc \
- server/dev_io.c tests/empty_audio_stub.cc tests/metrics_stub.cc \
- common/cras_shm.c
-audio_thread_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server \
- -I$(SERVER_RUST_SRCDIR)/src/headers
-audio_thread_unittest_LDADD = -lgtest -lpthread -lrt
-
-audio_thread_monitor_unittest_SOURCES = tests/audio_thread_monitor_unittest.cc
-audio_thread_monitor_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server
-audio_thread_monitor_unittest_LDADD = -lgtest -lpthread -lrt
-
-if HAVE_DBUS
-bt_device_unittest_SOURCES = tests/bt_device_unittest.cc \
- server/cras_bt_device.c \
- tests/metrics_stub.cc common/sfh.c
-bt_device_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common $(DBUS_CFLAGS)
-bt_device_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-
-bt_io_unittest_SOURCES = tests/bt_io_unittest.cc common/sfh.c
-bt_io_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/common $(DBUS_CFLAGS)
-bt_io_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-endif
-
-biquad_unittest_SOURCES = tests/biquad_unittest.cc \
- dsp/biquad.c
-biquad_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS) \
- -I$(top_srcdir)/src/server
-biquad_unittest_LDADD = -lgtest -lpthread -lm
-
-byte_buffer_unittest_SOURCES = tests/byte_buffer_unittest.cc
-byte_buffer_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-byte_buffer_unittest_LDADD = -lgtest -lpthread
-
-card_config_unittest_SOURCES = tests/card_config_unittest.cc \
- server/config/cras_card_config.c
-card_config_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config $(CRAS_UT_TMPDIR_CFLAGS)
-card_config_unittest_LDADD = -lgtest -liniparser -lpthread
-
-checksum_unittest_SOURCES = tests/checksum_unittest.cc common/cras_checksum.c
-checksum_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-checksum_unittest_LDADD = -lgtest -lpthread
-
-cras_abi_unittest_SOURCES = tests/cras_abi_unittest.cc \
- common/cras_config.c common/cras_shm.c common/cras_util.c \
- common/cras_file_wait.c common/cras_audio_format.c
-cras_abi_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/libcras
-cras_abi_unittest_LDADD = -lgtest -lpthread -lrt -lspeexdsp
-
-cras_client_unittest_SOURCES = tests/cras_client_unittest.cc \
- common/cras_config.c common/cras_shm.c common/cras_util.c \
- common/cras_file_wait.c
-cras_client_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/libcras
-cras_client_unittest_LDADD = -lgtest -lpthread -lrt -lspeexdsp
-
-cras_tm_unittest_SOURCES = tests/cras_tm_unittest.cc server/cras_tm.c
-cras_tm_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-cras_tm_unittest_LDADD = -lgtest -lpthread
-
-dev_io_unittest_SOURCES = \
- $(CRAS_SELINUX_UNITTEST_SOURCES) \
- common/cras_audio_format.c \
- server/dev_io.c \
- tests/dev_io_stubs.cc \
- tests/iodev_stub.cc \
- tests/empty_audio_stub.cc \
- tests/metrics_stub.cc \
- tests/rstream_stub.cc \
- tests/dev_io_unittest.cc
-dev_io_unittest_CXXFLAGS = \
- -std=c++11 -Wno-noexcept-type
-dev_io_unittest_CPPFLAGS = \
- $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config \
- -I$(SERVER_RUST_SRCDIR)/src/headers \
- $(SELINUX_CFLAGS)
-dev_io_unittest_LDADD = \
- libcrasmix.la \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- $(SELINUX_LIBS) \
- -lgtest -lrt -lpthread -ldl -lm -lspeexdsp
-
-dev_stream_unittest_SOURCES = tests/dev_stream_unittest.cc \
- server/dev_stream.c common/cras_shm.c
-dev_stream_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server
-dev_stream_unittest_LDADD = -lgtest -liniparser -lpthread -lrt
-
-device_blocklist_unittest_SOURCES = tests/device_blocklist_unittest.cc \
- server/config/cras_device_blocklist.c
-device_blocklist_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config $(CRAS_UT_TMPDIR_CFLAGS)
-device_blocklist_unittest_LDADD = -lgtest -liniparser -lpthread
-
-device_monitor_unittest_SOURCES = tests/device_monitor_unittest.cc
-device_monitor_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-device_monitor_unittest_LDADD = -lgtest -lpthread
-
-dsp_core_unittest_SOURCES = tests/dsp_core_unittest.cc dsp/eq.c dsp/eq2.c \
- dsp/biquad.c dsp/dsp_util.c dsp/crossover.c dsp/crossover2.c dsp/drc.c \
- dsp/drc_kernel.c dsp/drc_math.c
-dsp_core_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) $(DSP_INCLUDE_PATHS)
-dsp_core_unittest_LDADD = -lgtest -lpthread
-
-dsp_ini_unittest_SOURCES = tests/dsp_ini_unittest.cc \
- server/cras_dsp_ini.c server/cras_expr.c common/dumper.c
-dsp_ini_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-dsp_ini_unittest_LDADD = -lgtest -liniparser -lpthread
-
-dsp_pipeline_unittest_SOURCES = tests/cras_dsp_pipeline_unittest.cc \
- server/cras_dsp_ini.c server/cras_expr.c server/cras_dsp_pipeline.c \
- common/dumper.c dsp/dsp_util.c
-dsp_pipeline_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/server $(DSP_INCLUDE_PATHS)
-dsp_pipeline_unittest_LDADD = -lgtest -lrt -liniparser -lpthread
-
-dsp_unittest_SOURCES = tests/dsp_unittest.cc \
- server/cras_dsp.c server/cras_dsp_ini.c server/cras_dsp_pipeline.c \
- server/cras_expr.c common/dumper.c dsp/dsp_util.c \
- dsp/tests/dsp_test_util.c
-dsp_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/server $(DSP_INCLUDE_PATHS)
-dsp_unittest_LDADD = -lgtest -lrt -liniparser -lpthread
-
-dumper_unittest_SOURCES = tests/dumper_unittest.cc common/dumper.c
-dumper_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-dumper_unittest_LDADD = -lgtest -lpthread
-
-edid_utils_unittest_SOURCES = tests/edid_utils_unittest.cc common/edid_utils.c
-edid_utils_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-edid_utils_unittest_LDADD = -lgtest -lpthread
-
-empty_iodev_unittest_SOURCES = tests/empty_iodev_unittest.cc \
- server/cras_empty_iodev.c
-empty_iodev_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-empty_iodev_unittest_LDADD = -lgtest -lpthread
-
-expr_unittest_SOURCES = tests/expr_unittest.cc server/cras_expr.c common/dumper.c
-expr_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-expr_unittest_LDADD = -lgtest -lpthread
-
-file_wait_unittest_SOURCES = tests/file_wait_unittest.cc \
- common/cras_file_wait.c common/cras_util.c
-file_wait_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- $(CRAS_UT_TMPDIR_CFLAGS)
-file_wait_unittest_LDADD = -lgtest -lpthread
-
-
-float_buffer_unittest_SOURCES = tests/float_buffer_unittest.cc
-float_buffer_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-float_buffer_unittest_LDADD = -lgtest -lpthread
-
-fmt_conv_unittest_SOURCES = tests/fmt_conv_unittest.cc server/cras_fmt_conv.c \
- server/cras_fmt_conv_ops.c
-fmt_conv_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-fmt_conv_unittest_LDADD = -lasound -lspeexdsp -lgtest -lpthread
-
-fmt_conv_ops_unittest_SOURCES = tests/fmt_conv_ops_unittest.cc \
- server/cras_fmt_conv_ops.c
-fmt_conv_ops_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-fmt_conv_ops_unittest_LDADD = -lasound -lspeexdsp -lgtest -lpthread
-
-hfp_info_unittest_SOURCES = tests/hfp_info_unittest.cc \
- tests/metrics_stub.cc tests/sbc_codec_stub.cc
-hfp_info_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server -I$(top_srcdir)/src/plc
-hfp_info_unittest_LDADD = -lgtest -lpthread
-
-if HAVE_DBUS
-hfp_iodev_unittest_SOURCES = tests/hfp_iodev_unittest.cc \
- server/cras_hfp_iodev.c
-hfp_iodev_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server $(DBUS_CFLAGS)
-hfp_iodev_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-
-hfp_alsa_iodev_unittest_SOURCES = tests/hfp_alsa_iodev_unittest.cc \
- server/cras_hfp_alsa_iodev.c
-hfp_alsa_iodev_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server $(DBUS_CFLAGS)
-hfp_alsa_iodev_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-
-hfp_ag_profile_unittest_SOURCES = tests/hfp_ag_profile_unittest.cc \
- server/cras_hfp_ag_profile.c common/sfh.c tests/metrics_stub.cc
-hfp_ag_profile_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server $(DBUS_CFLAGS)
-hfp_ag_profile_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-
-hfp_slc_unittest_SOURCES = tests/hfp_slc_unittest.cc \
- server/cras_hfp_slc.c tests/metrics_stub.cc
-hfp_slc_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server $(DBUS_CFLAGS)
-hfp_slc_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-endif
-
-buffer_share_unittest_SOURCES = tests/buffer_share_unittest.cc \
- server/buffer_share.c
-buffer_share_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server
-buffer_share_unittest_LDADD = -lgtest -liniparser -lpthread
-
-ewma_power_unittest_SOURCES = tests/ewma_power_unittest.cc \
- common/cras_audio_format.c server/cras_audio_area.c \
- server/ewma_power.c
-
-ewma_power_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server
-ewma_power_unittest_LDADD = -lgtest
-
-iodev_list_unittest_SOURCES = tests/iodev_list_unittest.cc \
- server/cras_iodev_list.c
-iodev_list_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-iodev_list_unittest_LDADD = -lgtest -lpthread
-
-loopback_iodev_unittest_SOURCES = tests/loopback_iodev_unittest.cc \
- server/cras_loopback_iodev.c common/cras_shm.c common/sfh.c
-loopback_iodev_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-loopback_iodev_unittest_LDADD = -lgtest -lpthread -lrt
-
-input_data_unittest_SOURCES = tests/input_data_unittest.cc \
- server/input_data.c
-input_data_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/dsp -I$(top_srcdir)/src/server
-input_data_unittest_LDADD = -lgtest -lpthread
-
-iodev_unittest_SOURCES = tests/iodev_unittest.cc \
- server/cras_iodev.c common/cras_shm.c
-iodev_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(SERVER_RUST_SRCDIR)/src/headers
-iodev_unittest_LDADD = -lgtest -lpthread -lrt
-
-mix_unittest_SOURCES = tests/mix_unittest.cc server/cras_mix.c
-mix_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-mix_unittest_LDADD = libcrasmix.la \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- -lgtest \
- -lpthread
-
-linear_resampler_unittest_SOURCES = tests/linear_resampler_unittest.cc \
- server/linear_resampler.c server/cras_audio_area.c
-linear_resampler_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-linear_resampler_unittest_LDADD = -lgtest -lpthread
-
-observer_unittest_SOURCES = tests/observer_unittest.cc
-observer_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-observer_unittest_LDADD = -lgtest -lpthread
-
-polled_interval_checker_unittest_SOURCES = tests/polled_interval_checker_unittest.cc \
- server/polled_interval_checker.c
-polled_interval_checker_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-polled_interval_checker_unittest_LDADD = -lgtest -lpthread
-
-ramp_unittest_SOURCES = tests/ramp_unittest.cc
-ramp_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-ramp_unittest_LDADD = -lgtest -lpthread
-
-rate_estimator_unittest_SOURCES = tests/rate_estimator_unittest.cc
-rate_estimator_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(SERVER_RUST_SRCDIR)/src/headers
-rate_estimator_unittest_LDADD = $(CRAS_RUST) -lgtest -ldl -lpthread
-
-control_rclient_unittest_SOURCES = tests/control_rclient_unittest.cc \
- server/cras_rstream_config.c
-control_rclient_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server $(CRAS_UT_TMPDIR_CFLAGS) \
- $(DBUS_CFLAGS)
-control_rclient_unittest_LDADD = -lgtest -lpthread $(DBUS_LIBS)
-
-playback_rclient_unittest_SOURCES = tests/playback_rclient_unittest.cc \
- server/cras_rstream_config.c
-playback_rclient_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server $(CRAS_UT_TMPDIR_CFLAGS)
-playback_rclient_unittest_LDADD = -lgtest -lpthread
-
-capture_rclient_unittest_SOURCES = tests/capture_rclient_unittest.cc \
- server/cras_rstream_config.c
-capture_rclient_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server $(CRAS_UT_TMPDIR_CFLAGS)
-capture_rclient_unittest_LDADD = -lgtest -lpthread
-
-rstream_unittest_SOURCES = tests/rstream_unittest.cc server/cras_rstream.c \
- common/cras_shm.c tests/metrics_stub.cc \
- server/cras_rstream_config.c $(CRAS_SELINUX_UNITTEST_SOURCES)
-rstream_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server $(SELINUX_CFLAGS)
-rstream_unittest_LDADD = $(SELINUX_LIBS) \
- -lasound -lgtest -lpthread -lrt
-
-server_metrics_unittest_SOURCES = tests/server_metrics_unittest.cc
-server_metrics_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-server_metrics_unittest_LDADD = -lgtest -lpthread
-
-shm_unittest_SOURCES = tests/shm_unittest.cc
-shm_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-shm_unittest_LDADD = -lgtest -lpthread
-
-softvol_curve_unittest_SOURCES = tests/softvol_curve_unittest.cc server/softvol_curve.c
-softvol_curve_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-softvol_curve_unittest_LDADD = -lgtest -lpthread
-
-stream_list_unittest_SOURCES = tests/stream_list_unittest.cc \
- server/stream_list.c
-stream_list_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-stream_list_unittest_LDADD = -lgtest -lpthread
-
-system_state_unittest_SOURCES = tests/system_state_unittest.cc \
- server/cras_system_state.c common/cras_shm.c \
- $(CRAS_SELINUX_UNITTEST_SOURCES)
-system_state_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config $(SELINUX_CFLAGS)
-system_state_unittest_LDADD = $(SELINUX_LIBS) \
- -lgtest -liniparser -lpthread -lrt
-
-timing_unittest_SOURCES = \
- $(CRAS_SELINUX_UNITTEST_SOURCES) \
- common/cras_audio_format.c \
- common/cras_shm.c \
- server/cras_audio_area.c \
- server/cras_fmt_conv.c \
- server/cras_fmt_conv_ops.c \
- server/cras_mix.c \
- server/cras_mix_ops.c \
- server/dev_io.c \
- server/dev_stream.c \
- server/linear_resampler.c \
- tests/dev_io_stubs.cc \
- tests/iodev_stub.cc \
- tests/empty_audio_stub.cc \
- tests/metrics_stub.cc \
- tests/rstream_stub.cc \
- tests/timing_unittest.cc
-timing_unittest_CXXFLAGS = \
- -std=c++11 -Wno-noexcept-type
-timing_unittest_CPPFLAGS = \
- $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server \
- -I$(top_srcdir)/src/server/config \
- -I$(SERVER_RUST_SRCDIR)/src/headers \
- $(SELINUX_CFLAGS)
-timing_unittest_LDADD = \
- libcrasmix.la \
- $(CRAS_SSE4_2) \
- $(CRAS_AVX) \
- $(CRAS_AVX2) \
- $(CRAS_FMA) \
- $(SELINUX_LIBS) \
- -lgtest -lrt -lpthread -ldl -lm -lspeexdsp
-
-utf8_unittest_SOURCES = tests/utf8_unittest.cc server/cras_utf8.c
-utf8_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common \
- -I$(top_srcdir)/src/server
-utf8_unittest_LDADD = -lgtest -lpthread
-
-util_unittest_SOURCES = tests/util_unittest.cc common/cras_util.c \
- common/cras_config.c
-util_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) -I$(top_srcdir)/src/common
-util_unittest_LDADD = -lgtest -lpthread
-
-volume_curve_unittest_SOURCES = tests/volume_curve_unittest.cc \
- server/cras_volume_curve.c
-volume_curve_unittest_CPPFLAGS = $(COMMON_CPPFLAGS) \
- -I$(top_srcdir)/src/common -I$(top_srcdir)/src/server
-volume_curve_unittest_LDADD = -lgtest -lpthread
diff --git a/cras/src/alsa_plugin/ctl_cras.c b/cras/src/alsa_plugin/ctl_cras.c
deleted file mode 100644
index 76b0c039..00000000
--- a/cras/src/alsa_plugin/ctl_cras.c
+++ /dev/null
@@ -1,280 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <alsa/control_external.h>
-#include <cras_client.h>
-
-static const size_t MAX_IODEVS = 10; /* Max devices to print out. */
-static const size_t MAX_IONODES = 20; /* Max ionodes to print out. */
-
-/* Support basic input/output volume/mute only. */
-enum CTL_CRAS_MIXER_CONTROLS {
- CTL_CRAS_MIXER_PLAYBACK_SWITCH,
- CTL_CRAS_MIXER_PLAYBACK_VOLUME,
- NUM_CTL_CRAS_MIXER_ELEMS
-};
-
-/* Hold info specific to each control. */
-struct cras_mixer_control {
- const char *name;
- int type;
- unsigned int access;
- unsigned int count;
-};
-
-/* CRAS mixer elements. */
-static const struct cras_mixer_control cras_elems[NUM_CTL_CRAS_MIXER_ELEMS] = {
- { "Master Playback Switch", SND_CTL_ELEM_TYPE_BOOLEAN,
- SND_CTL_EXT_ACCESS_READWRITE, 1 },
- { "Master Playback Volume", SND_CTL_ELEM_TYPE_INTEGER,
- SND_CTL_EXT_ACCESS_READWRITE, 1 },
-};
-
-/* Holds the client and ctl plugin pointers. */
-struct ctl_cras {
- snd_ctl_ext_t ext_ctl;
- struct cras_client *client;
-};
-
-/* Frees resources when the plugin is closed. */
-static void ctl_cras_close(snd_ctl_ext_t *ext_ctl)
-{
- struct ctl_cras *cras = (struct ctl_cras *)ext_ctl->private_data;
-
- if (cras) {
- cras_client_stop(cras->client);
- cras_client_destroy(cras->client);
- }
- free(cras);
-}
-
-/* Lists available controls. */
-static int ctl_cras_elem_list(snd_ctl_ext_t *ext_ctl, unsigned int offset,
- snd_ctl_elem_id_t *id)
-{
- snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER);
- if (offset >= NUM_CTL_CRAS_MIXER_ELEMS)
- return -EINVAL;
- snd_ctl_elem_id_set_name(id, cras_elems[offset].name);
- return 0;
-}
-
-/* Returns the number of available controls. */
-static int ctl_cras_elem_count(snd_ctl_ext_t *ext_ctl)
-{
- return NUM_CTL_CRAS_MIXER_ELEMS;
-}
-
-/* Gets a control key from a search id. */
-static snd_ctl_ext_key_t ctl_cras_find_elem(snd_ctl_ext_t *ext_ctl,
- const snd_ctl_elem_id_t *id)
-{
- const char *name;
- unsigned int numid;
-
- numid = snd_ctl_elem_id_get_numid(id);
- if (numid - 1 < NUM_CTL_CRAS_MIXER_ELEMS)
- return numid - 1;
-
- name = snd_ctl_elem_id_get_name(id);
-
- for (numid = 0; numid < NUM_CTL_CRAS_MIXER_ELEMS; numid++)
- if (strcmp(cras_elems[numid].name, name) == 0)
- return numid;
-
- return SND_CTL_EXT_KEY_NOT_FOUND;
-}
-
-/* Fills accessibility, type and count based on the specified control. */
-static int ctl_cras_get_attribute(snd_ctl_ext_t *ext_ctl, snd_ctl_ext_key_t key,
- int *type, unsigned int *acc,
- unsigned int *count)
-{
- if (key >= NUM_CTL_CRAS_MIXER_ELEMS)
- return -EINVAL;
- *type = cras_elems[key].type;
- *acc = cras_elems[key].access;
- *count = cras_elems[key].count;
- return 0;
-}
-
-/* Returns the range of the specified control. The volume sliders always run
- * from 0 to 100 for CRAS. */
-static int ctl_cras_get_integer_info(snd_ctl_ext_t *ext_ctl,
- snd_ctl_ext_key_t key, long *imin,
- long *imax, long *istep)
-{
- *istep = 0;
- *imin = 0;
- *imax = 100;
- return 0;
-}
-
-static int get_nodes(struct cras_client *client, enum CRAS_STREAM_DIRECTION dir,
- struct cras_ionode_info *nodes, size_t num_nodes)
-{
- struct cras_iodev_info devs[MAX_IODEVS];
- size_t num_devs;
- int rc;
-
- if (dir == CRAS_STREAM_OUTPUT)
- rc = cras_client_get_output_devices(client, devs, nodes,
- &num_devs, &num_nodes);
- else
- rc = cras_client_get_input_devices(client, devs, nodes,
- &num_devs, &num_nodes);
- if (rc < 0)
- return 0;
- return num_nodes;
-}
-
-/* Gets the value of the given control from CRAS and puts it in value. */
-static int ctl_cras_read_integer(snd_ctl_ext_t *ext_ctl, snd_ctl_ext_key_t key,
- long *value)
-{
- struct ctl_cras *cras = (struct ctl_cras *)ext_ctl->private_data;
- struct cras_ionode_info nodes[MAX_IONODES];
- int num_nodes, i;
-
- switch (key) {
- case CTL_CRAS_MIXER_PLAYBACK_SWITCH:
- *value = !cras_client_get_user_muted(cras->client);
- break;
- case CTL_CRAS_MIXER_PLAYBACK_VOLUME:
- num_nodes = get_nodes(cras->client, CRAS_STREAM_OUTPUT, nodes,
- MAX_IONODES);
- for (i = 0; i < num_nodes; i++) {
- if (!nodes[i].active)
- continue;
- *value = nodes[i].volume;
- break;
- }
- break;
- default:
- return -EINVAL;
- }
-
- return 0;
-}
-
-/* Writes the given values to CRAS. */
-static int ctl_cras_write_integer(snd_ctl_ext_t *ext_ctl, snd_ctl_ext_key_t key,
- long *value)
-{
- struct ctl_cras *cras = (struct ctl_cras *)ext_ctl->private_data;
- struct cras_ionode_info nodes[MAX_IONODES];
- int num_nodes, i;
-
- switch (key) {
- case CTL_CRAS_MIXER_PLAYBACK_SWITCH:
- cras_client_set_user_mute(cras->client, !(*value));
- break;
- case CTL_CRAS_MIXER_PLAYBACK_VOLUME:
- num_nodes = get_nodes(cras->client, CRAS_STREAM_OUTPUT, nodes,
- MAX_IONODES);
- for (i = 0; i < num_nodes; i++) {
- if (!nodes[i].active)
- continue;
- cras_client_set_node_volume(
- cras->client,
- cras_make_node_id(nodes[i].iodev_idx,
- nodes[i].ionode_idx),
- *value);
- }
- break;
- default:
- return -EINVAL;
- }
-
- return 0;
-}
-
-static const snd_ctl_ext_callback_t ctl_cras_ext_callback = {
- .close = ctl_cras_close,
- .elem_count = ctl_cras_elem_count,
- .elem_list = ctl_cras_elem_list,
- .find_elem = ctl_cras_find_elem,
- .get_attribute = ctl_cras_get_attribute,
- .get_integer_info = ctl_cras_get_integer_info,
- .read_integer = ctl_cras_read_integer,
- .write_integer = ctl_cras_write_integer,
-};
-
-SND_CTL_PLUGIN_DEFINE_FUNC(cras)
-{
- struct ctl_cras *cras;
- int rc;
-
- cras = malloc(sizeof(*cras));
- if (cras == NULL)
- return -ENOMEM;
-
- rc = cras_client_create(&cras->client);
- if (rc != 0 || cras->client == NULL) {
- fprintf(stderr, "Couldn't create CRAS client\n");
- free(cras);
- return rc;
- }
-
- rc = cras_client_connect(cras->client);
- if (rc < 0) {
- fprintf(stderr, "Couldn't connect to cras.\n");
- cras_client_destroy(cras->client);
- free(cras);
- return rc;
- }
-
- rc = cras_client_run_thread(cras->client);
- if (rc < 0) {
- fprintf(stderr, "Couldn't start client thread.\n");
- cras_client_stop(cras->client);
- cras_client_destroy(cras->client);
- free(cras);
- return rc;
- }
-
- rc = cras_client_connected_wait(cras->client);
- if (rc < 0) {
- fprintf(stderr, "CRAS client wouldn't connect.\n");
- cras_client_stop(cras->client);
- cras_client_destroy(cras->client);
- free(cras);
- return rc;
- }
-
- cras->ext_ctl.version = SND_CTL_EXT_VERSION;
- cras->ext_ctl.card_idx = 0;
- strncpy(cras->ext_ctl.id, "cras", sizeof(cras->ext_ctl.id) - 1);
- cras->ext_ctl.id[sizeof(cras->ext_ctl.id) - 1] = '\0';
- strncpy(cras->ext_ctl.driver, "CRAS plugin",
- sizeof(cras->ext_ctl.driver) - 1);
- cras->ext_ctl.driver[sizeof(cras->ext_ctl.driver) - 1] = '\0';
- strncpy(cras->ext_ctl.name, "CRAS", sizeof(cras->ext_ctl.name) - 1);
- cras->ext_ctl.name[sizeof(cras->ext_ctl.name) - 1] = '\0';
- strncpy(cras->ext_ctl.longname, "CRAS",
- sizeof(cras->ext_ctl.longname) - 1);
- cras->ext_ctl.longname[sizeof(cras->ext_ctl.longname) - 1] = '\0';
- strncpy(cras->ext_ctl.mixername, "CRAS",
- sizeof(cras->ext_ctl.mixername) - 1);
- cras->ext_ctl.mixername[sizeof(cras->ext_ctl.mixername) - 1] = '\0';
- cras->ext_ctl.poll_fd = -1;
-
- cras->ext_ctl.callback = &ctl_cras_ext_callback;
- cras->ext_ctl.private_data = cras;
-
- rc = snd_ctl_ext_create(&cras->ext_ctl, name, mode);
- if (rc < 0) {
- cras_client_stop(cras->client);
- cras_client_destroy(cras->client);
- free(cras);
- return rc;
- }
-
- *handlep = cras->ext_ctl.handle;
- return 0;
-}
-
-SND_CTL_PLUGIN_SYMBOL(cras);
diff --git a/cras/src/alsa_plugin/pcm_cras.c b/cras/src/alsa_plugin/pcm_cras.c
deleted file mode 100644
index 7bc960bc..00000000
--- a/cras/src/alsa_plugin/pcm_cras.c
+++ /dev/null
@@ -1,405 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <alsa/pcm_external.h>
-#include <cras_client.h>
-#include <sys/socket.h>
-
-/* Holds configuration for the alsa plugin.
- * io - ALSA ioplug object.
- * fd - Wakes users with polled io.
- * stream_playing - Indicates if the stream is playing/capturing.
- * hw_ptr - Current read or write position.
- * channels - Number of channels.
- * stream_id - CRAS ID of the playing/capturing stream.
- * bytes_per_frame - number of bytes in an audio frame.
- * direction - input or output.
- * areas - ALSA areas used to read from/write to.
- * client - CRAS client object.
- * capture_sample_index - The sample tracked for capture latency calculation.
- * playback_sample_index - The sample tracked for playback latency calculation.
- * capture_sample_time - The time when capture_sample_index was captured.
- * playback_sample_time - The time when playback_sample_index was captured.
- */
-struct snd_pcm_cras {
- snd_pcm_ioplug_t io;
- int fd;
- int stream_playing;
- unsigned int hw_ptr;
- unsigned int channels;
- cras_stream_id_t stream_id;
- size_t bytes_per_frame;
- enum CRAS_STREAM_DIRECTION direction;
- snd_pcm_channel_area_t *areas;
- struct cras_client *client;
- int capture_sample_index;
- int playback_sample_index;
- struct timespec capture_sample_time;
- struct timespec playback_sample_time;
-};
-
-/* Frees all resources allocated during use. */
-static void snd_pcm_cras_free(struct snd_pcm_cras *pcm_cras)
-{
- if (pcm_cras == NULL)
- return;
- assert(!pcm_cras->stream_playing);
- if (pcm_cras->fd >= 0)
- close(pcm_cras->fd);
- if (pcm_cras->io.poll_fd >= 0)
- close(pcm_cras->io.poll_fd);
- cras_client_destroy(pcm_cras->client);
- free(pcm_cras->areas);
- free(pcm_cras);
-}
-
-/* Stops a playing or capturing CRAS plugin. */
-static int snd_pcm_cras_stop(snd_pcm_ioplug_t *io)
-{
- struct snd_pcm_cras *pcm_cras = io->private_data;
-
- if (pcm_cras->stream_playing) {
- cras_client_rm_stream(pcm_cras->client, pcm_cras->stream_id);
- cras_client_stop(pcm_cras->client);
- pcm_cras->stream_playing = 0;
- }
- return 0;
-}
-
-/* Close a CRAS plugin opened with snd_pcm_cras_open. */
-static int snd_pcm_cras_close(snd_pcm_ioplug_t *io)
-{
- struct snd_pcm_cras *pcm_cras = io->private_data;
-
- if (pcm_cras->stream_playing)
- snd_pcm_cras_stop(io);
- snd_pcm_cras_free(pcm_cras);
- return 0;
-}
-
-/* Poll callback used to wait for data ready (playback) or space available
- * (capture). */
-static int snd_pcm_cras_poll_revents(snd_pcm_ioplug_t *io, struct pollfd *pfds,
- unsigned int nfds, unsigned short *revents)
-{
- static char buf[1];
- int rc;
-
- if (pfds == NULL || nfds != 1 || revents == NULL)
- return -EINVAL;
- rc = read(pfds[0].fd, buf, 1);
- if (rc < 0 && errno != EWOULDBLOCK && errno != EAGAIN) {
- fprintf(stderr, "%s read failed %d\n", __func__, errno);
- return errno;
- }
- *revents = pfds[0].revents & ~(POLLIN | POLLOUT);
- if (pfds[0].revents & POLLIN)
- *revents |= (io->stream == SND_PCM_STREAM_PLAYBACK) ? POLLOUT :
- POLLIN;
- return 0;
-}
-
-/* Callback to return the location of the write (playback) or read (capture)
- * pointer. */
-static snd_pcm_sframes_t snd_pcm_cras_pointer(snd_pcm_ioplug_t *io)
-{
- struct snd_pcm_cras *pcm_cras = io->private_data;
- return pcm_cras->hw_ptr;
-}
-
-/* Main callback for processing audio. This is called by CRAS when more samples
- * are needed (playback) or ready (capture). Copies bytes between ALSA and CRAS
- * buffers. */
-static int pcm_cras_process_cb(struct cras_client *client,
- cras_stream_id_t stream_id,
- uint8_t *capture_samples,
- uint8_t *playback_samples, unsigned int nframes,
- const struct timespec *capture_ts,
- const struct timespec *playback_ts, void *arg)
-{
- snd_pcm_ioplug_t *io;
- struct snd_pcm_cras *pcm_cras;
- const snd_pcm_channel_area_t *areas;
- snd_pcm_uframes_t copied_frames;
- char empty_byte;
- size_t chan, frame_bytes, sample_bytes;
- int rc;
- uint8_t *samples;
- const struct timespec *sample_time;
-
- samples = capture_samples ?: playback_samples;
- sample_time = capture_ts ?: playback_ts;
-
- io = (snd_pcm_ioplug_t *)arg;
- pcm_cras = (struct snd_pcm_cras *)io->private_data;
- frame_bytes = pcm_cras->bytes_per_frame;
- sample_bytes = snd_pcm_format_physical_width(io->format) / 8;
-
- if (io->stream == SND_PCM_STREAM_PLAYBACK) {
- if (io->state != SND_PCM_STATE_RUNNING &&
- io->state != SND_PCM_STATE_DRAINING) {
- memset(samples, 0, nframes * frame_bytes);
- return nframes;
- }
- /* Only take one period of data at a time. */
- if (nframes > io->period_size)
- nframes = io->period_size;
-
- /* Keep track of the first transmitted sample index and the time
- * it will be played. */
- pcm_cras->playback_sample_index = io->hw_ptr;
- pcm_cras->playback_sample_time = *sample_time;
- } else {
- /* Keep track of the first read sample index and the time it
- * was captured. */
- pcm_cras->capture_sample_index = io->hw_ptr;
- pcm_cras->capture_sample_time = *sample_time;
- }
-
- /* CRAS always takes interleaved samples. */
- for (chan = 0; chan < io->channels; chan++) {
- pcm_cras->areas[chan].addr = samples + chan * sample_bytes;
- pcm_cras->areas[chan].first = 0;
- pcm_cras->areas[chan].step =
- snd_pcm_format_physical_width(io->format) *
- io->channels;
- }
-
- areas = snd_pcm_ioplug_mmap_areas(io);
-
- copied_frames = 0;
- while (copied_frames < nframes) {
- snd_pcm_uframes_t frames = nframes - copied_frames;
- snd_pcm_uframes_t remain = io->buffer_size - pcm_cras->hw_ptr;
-
- if (frames > remain)
- frames = remain;
-
- for (chan = 0; chan < io->channels; chan++)
- if (io->stream == SND_PCM_STREAM_PLAYBACK)
- snd_pcm_area_copy(&pcm_cras->areas[chan],
- copied_frames, &areas[chan],
- pcm_cras->hw_ptr, frames,
- io->format);
- else
- snd_pcm_area_copy(&areas[chan],
- pcm_cras->hw_ptr,
- &pcm_cras->areas[chan],
- copied_frames, frames,
- io->format);
-
- pcm_cras->hw_ptr += frames;
- pcm_cras->hw_ptr %= io->buffer_size;
- copied_frames += frames;
- }
-
- rc = write(pcm_cras->fd, &empty_byte, 1); /* Wake up polling clients. */
- if (rc < 0 && errno != EWOULDBLOCK && errno != EAGAIN)
- fprintf(stderr, "%s write failed %d\n", __func__, errno);
-
- return nframes;
-}
-
-/* Callback from CRAS for stream errors. */
-static int pcm_cras_error_cb(struct cras_client *client,
- cras_stream_id_t stream_id, int err, void *arg)
-{
- fprintf(stderr, "Stream error %d\n", err);
- return 0;
-}
-
-/* ALSA calls this automatically when the stream enters the
- * SND_PCM_STATE_PREPARED state. */
-static int snd_pcm_cras_prepare(snd_pcm_ioplug_t *io)
-{
- struct snd_pcm_cras *pcm_cras = io->private_data;
-
- return cras_client_connect(pcm_cras->client);
-}
-
-/* Called when an ALSA stream is started. */
-static int snd_pcm_cras_start(snd_pcm_ioplug_t *io)
-{
- struct snd_pcm_cras *pcm_cras = io->private_data;
- struct cras_stream_params *params;
- struct cras_audio_format *audio_format;
- int rc;
-
- audio_format =
- cras_audio_format_create(io->format, io->rate, io->channels);
- if (audio_format == NULL)
- return -ENOMEM;
-
- params = cras_client_unified_params_create(
- pcm_cras->direction, io->period_size, 0, 0, io,
- pcm_cras_process_cb, pcm_cras_error_cb, audio_format);
- if (params == NULL) {
- rc = -ENOMEM;
- goto error_out;
- }
-
- cras_client_stream_params_set_client_type(params, CRAS_CLIENT_TYPE_PCM);
-
- rc = cras_client_run_thread(pcm_cras->client);
- if (rc < 0)
- goto error_out;
-
- pcm_cras->bytes_per_frame =
- cras_client_format_bytes_per_frame(audio_format);
-
- rc = cras_client_add_stream(pcm_cras->client, &pcm_cras->stream_id,
- params);
- if (rc < 0) {
- fprintf(stderr, "CRAS add failed\n");
- goto error_out;
- }
- pcm_cras->stream_playing = 1;
-
-error_out:
- cras_audio_format_destroy(audio_format);
- cras_client_stream_params_destroy(params);
- return rc;
-}
-
-static snd_pcm_ioplug_callback_t cras_pcm_callback = {
- .close = snd_pcm_cras_close,
- .start = snd_pcm_cras_start,
- .stop = snd_pcm_cras_stop,
- .pointer = snd_pcm_cras_pointer,
- .prepare = snd_pcm_cras_prepare,
- .poll_revents = snd_pcm_cras_poll_revents,
-};
-
-/* Set constraints for hw_params. This lists the handled formats, sample rates,
- * access patters, and buffer/period sizes. These are enforce in
- * snd_pcm_set_params(). */
-static int set_hw_constraints(struct snd_pcm_cras *pcm_cras)
-{
- // clang-format off
- static const unsigned int access_list[] = {
- SND_PCM_ACCESS_MMAP_INTERLEAVED,
- SND_PCM_ACCESS_MMAP_NONINTERLEAVED,
- SND_PCM_ACCESS_RW_INTERLEAVED,
- SND_PCM_ACCESS_RW_NONINTERLEAVED
- };
- static const unsigned int format_list[] = {
- SND_PCM_FORMAT_U8,
- SND_PCM_FORMAT_S16_LE,
- SND_PCM_FORMAT_S24_LE,
- SND_PCM_FORMAT_S32_LE,
- SND_PCM_FORMAT_S24_3LE,
- };
- // clang-format on
- int rc;
-
- rc = snd_pcm_ioplug_set_param_list(&pcm_cras->io,
- SND_PCM_IOPLUG_HW_ACCESS,
- ARRAY_SIZE(access_list),
- access_list);
- if (rc < 0)
- return rc;
- rc = snd_pcm_ioplug_set_param_list(&pcm_cras->io,
- SND_PCM_IOPLUG_HW_FORMAT,
- ARRAY_SIZE(format_list),
- format_list);
- if (rc < 0)
- return rc;
- rc = snd_pcm_ioplug_set_param_minmax(&pcm_cras->io,
- SND_PCM_IOPLUG_HW_CHANNELS, 1,
- pcm_cras->channels);
- if (rc < 0)
- return rc;
- rc = snd_pcm_ioplug_set_param_minmax(
- &pcm_cras->io, SND_PCM_IOPLUG_HW_RATE, 8000, 48000);
- if (rc < 0)
- return rc;
- rc = snd_pcm_ioplug_set_param_minmax(&pcm_cras->io,
- SND_PCM_IOPLUG_HW_BUFFER_BYTES, 64,
- 2 * 1024 * 1024);
- if (rc < 0)
- return rc;
- rc = snd_pcm_ioplug_set_param_minmax(&pcm_cras->io,
- SND_PCM_IOPLUG_HW_PERIOD_BYTES, 64,
- 2 * 1024 * 1024);
- if (rc < 0)
- return rc;
- rc = snd_pcm_ioplug_set_param_minmax(
- &pcm_cras->io, SND_PCM_IOPLUG_HW_PERIODS, 1, 2048);
- return rc;
-}
-
-/* Called by snd_pcm_open(). Creates a CRAS client and an ioplug plugin. */
-static int snd_pcm_cras_open(snd_pcm_t **pcmp, const char *name,
- snd_pcm_stream_t stream, int mode)
-{
- struct snd_pcm_cras *pcm_cras;
- int rc;
- int fd[2];
-
- assert(pcmp);
- pcm_cras = calloc(1, sizeof(*pcm_cras));
- if (!pcm_cras)
- return -ENOMEM;
-
- pcm_cras->fd = -1;
- pcm_cras->io.poll_fd = -1;
- pcm_cras->channels = 2;
- pcm_cras->direction = (stream == SND_PCM_STREAM_PLAYBACK) ?
- CRAS_STREAM_OUTPUT :
- CRAS_STREAM_INPUT;
-
- rc = cras_client_create(&pcm_cras->client);
- if (rc != 0 || pcm_cras->client == NULL) {
- fprintf(stderr, "Couldn't create CRAS client\n");
- free(pcm_cras);
- return rc;
- }
-
- pcm_cras->areas =
- calloc(pcm_cras->channels, sizeof(snd_pcm_channel_area_t));
- if (pcm_cras->areas == NULL) {
- snd_pcm_cras_free(pcm_cras);
- return -ENOMEM;
- }
-
- socketpair(AF_LOCAL, SOCK_STREAM, 0, fd);
-
- cras_make_fd_nonblocking(fd[0]);
- cras_make_fd_nonblocking(fd[1]);
-
- pcm_cras->fd = fd[0];
-
- pcm_cras->io.version = SND_PCM_IOPLUG_VERSION;
- pcm_cras->io.name = "ALSA to CRAS Plugin";
- pcm_cras->io.callback = &cras_pcm_callback;
- pcm_cras->io.private_data = pcm_cras;
- pcm_cras->io.poll_fd = fd[1];
- pcm_cras->io.poll_events = POLLIN;
- pcm_cras->io.mmap_rw = 1;
-
- rc = snd_pcm_ioplug_create(&pcm_cras->io, name, stream, mode);
- if (rc < 0) {
- snd_pcm_cras_free(pcm_cras);
- return rc;
- }
-
- rc = set_hw_constraints(pcm_cras);
- if (rc < 0) {
- snd_pcm_ioplug_delete(&pcm_cras->io);
- return rc;
- }
-
- *pcmp = pcm_cras->io.pcm;
-
- return 0;
-}
-
-SND_PCM_PLUGIN_DEFINE_FUNC(cras)
-{
- return snd_pcm_cras_open(pcmp, name, stream, mode);
-}
-
-SND_PCM_PLUGIN_SYMBOL(cras);
diff --git a/cras/src/common/a2dp-codecs.h b/cras/src/common/a2dp-codecs.h
deleted file mode 100644
index 006d9fe4..00000000
--- a/cras/src/common/a2dp-codecs.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- *
- * BlueZ - Bluetooth protocol stack for Linux
- *
- * Copyright (C) 2006-2010 Nokia Corporation
- * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org>
- *
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
- *
- */
-
-#define A2DP_CODEC_SBC 0x00
-#define A2DP_CODEC_MPEG12 0x01
-#define A2DP_CODEC_MPEG24 0x02
-#define A2DP_CODEC_ATRAC 0x03
-#define A2DP_CODEC_VENDOR 0xFF
-
-#define SBC_SAMPLING_FREQ_16000 (1 << 3)
-#define SBC_SAMPLING_FREQ_32000 (1 << 2)
-#define SBC_SAMPLING_FREQ_44100 (1 << 1)
-#define SBC_SAMPLING_FREQ_48000 1
-
-#define SBC_CHANNEL_MODE_MONO (1 << 3)
-#define SBC_CHANNEL_MODE_DUAL_CHANNEL (1 << 2)
-#define SBC_CHANNEL_MODE_STEREO (1 << 1)
-#define SBC_CHANNEL_MODE_JOINT_STEREO 1
-
-#define SBC_BLOCK_LENGTH_4 (1 << 3)
-#define SBC_BLOCK_LENGTH_8 (1 << 2)
-#define SBC_BLOCK_LENGTH_12 (1 << 1)
-#define SBC_BLOCK_LENGTH_16 1
-
-#define SBC_SUBBANDS_4 (1 << 1)
-#define SBC_SUBBANDS_8 1
-
-#define SBC_ALLOCATION_SNR (1 << 1)
-#define SBC_ALLOCATION_LOUDNESS 1
-
-#define MAX_BITPOOL 64
-#define MIN_BITPOOL 2
-
-#define MPEG_CHANNEL_MODE_MONO (1 << 3)
-#define MPEG_CHANNEL_MODE_DUAL_CHANNEL (1 << 2)
-#define MPEG_CHANNEL_MODE_STEREO (1 << 1)
-#define MPEG_CHANNEL_MODE_JOINT_STEREO 1
-
-#define MPEG_LAYER_MP1 (1 << 2)
-#define MPEG_LAYER_MP2 (1 << 1)
-#define MPEG_LAYER_MP3 1
-
-#define MPEG_SAMPLING_FREQ_16000 (1 << 5)
-#define MPEG_SAMPLING_FREQ_22050 (1 << 4)
-#define MPEG_SAMPLING_FREQ_24000 (1 << 3)
-#define MPEG_SAMPLING_FREQ_32000 (1 << 2)
-#define MPEG_SAMPLING_FREQ_44100 (1 << 1)
-#define MPEG_SAMPLING_FREQ_48000 1
-
-#define MPEG_BIT_RATE_VBR 0x8000
-#define MPEG_BIT_RATE_320000 0x4000
-#define MPEG_BIT_RATE_256000 0x2000
-#define MPEG_BIT_RATE_224000 0x1000
-#define MPEG_BIT_RATE_192000 0x0800
-#define MPEG_BIT_RATE_160000 0x0400
-#define MPEG_BIT_RATE_128000 0x0200
-#define MPEG_BIT_RATE_112000 0x0100
-#define MPEG_BIT_RATE_96000 0x0080
-#define MPEG_BIT_RATE_80000 0x0040
-#define MPEG_BIT_RATE_64000 0x0020
-#define MPEG_BIT_RATE_56000 0x0010
-#define MPEG_BIT_RATE_48000 0x0008
-#define MPEG_BIT_RATE_40000 0x0004
-#define MPEG_BIT_RATE_32000 0x0002
-#define MPEG_BIT_RATE_FREE 0x0001
-
-#if __BYTE_ORDER == __LITTLE_ENDIAN
-
-typedef struct {
- uint8_t channel_mode : 4;
- uint8_t frequency : 4;
- uint8_t allocation_method : 2;
- uint8_t subbands : 2;
- uint8_t block_length : 4;
- uint8_t min_bitpool;
- uint8_t max_bitpool;
-} __attribute__((packed)) a2dp_sbc_t;
-
-typedef struct {
- uint8_t channel_mode : 4;
- uint8_t crc : 1;
- uint8_t layer : 3;
- uint8_t frequency : 6;
- uint8_t mpf : 1;
- uint8_t rfa : 1;
- uint16_t bitrate;
-} __attribute__((packed)) a2dp_mpeg_t;
-
-#elif __BYTE_ORDER == __BIG_ENDIAN
-
-typedef struct {
- uint8_t frequency : 4;
- uint8_t channel_mode : 4;
- uint8_t block_length : 4;
- uint8_t subbands : 2;
- uint8_t allocation_method : 2;
- uint8_t min_bitpool;
- uint8_t max_bitpool;
-} __attribute__((packed)) a2dp_sbc_t;
-
-typedef struct {
- uint8_t layer : 3;
- uint8_t crc : 1;
- uint8_t channel_mode : 4;
- uint8_t rfa : 1;
- uint8_t mpf : 1;
- uint8_t frequency : 6;
- uint16_t bitrate;
-} __attribute__((packed)) a2dp_mpeg_t;
-
-#else
-#error "Unknown byte order"
-#endif
-
-typedef struct {
- uint8_t vendor_id[4];
- uint8_t codec_id[2];
-} __attribute__((packed)) a2dp_vendor_codec_t;
diff --git a/cras/src/common/array.h b/cras/src/common/array.h
deleted file mode 100644
index b21987e9..00000000
--- a/cras/src/common/array.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_ARRAY_H_
-#define CRAS_ARRAY_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <string.h>
-
-/*
-
-Sample usage:
-
-DECLARE_ARRAY_TYPE(double, double_array);
-
-void f()
-{
- int i;
- double *p;
- double_array a = ARRAY_INIT;
-
- ARRAY_APPEND(&a, 1.0);
- *ARRAY_APPEND_ZERO(&a) = 2.0;
-
- ARRAY_ELEMENT_FOREACH(&a, i, p) {
- printf("%f\n", *p); // prints 1.0 2.0
- }
-
- ARRAY_FREE(&a);
-}
-
-*/
-
-/* Define a type for the array given the element type */
-#define DECLARE_ARRAY_TYPE(element_type, array_type) \
- typedef struct { \
- int count; \
- int size; \
- element_type *element; \
- } array_type;
-
-/* The initializer for an empty array is the zero value. */
-#define ARRAY_INIT \
- { \
- }
-
-#define _ARRAY_EXTEND(a) \
- ({ \
- if ((a)->count >= (a)->size) { \
- if ((a)->size == 0) \
- (a)->size = 4; \
- else \
- (a)->size *= 2; \
- (a)->element = (__typeof((a)->element))realloc( \
- (a)->element, \
- (a)->size * sizeof((a)->element[0])); \
- } \
- &(a)->element[((a)->count)++]; \
- })
-
-/* Append an element with the given value to the array a */
-#define ARRAY_APPEND(a, value) \
- do { \
- *_ARRAY_EXTEND(a) = (value); \
- } while (0)
-
-/* Append a zero element to the array a and return the pointer to the element */
-#define ARRAY_APPEND_ZERO(a) \
- ({ \
- typeof((a)->element) _tmp_ptr = _ARRAY_EXTEND(a); \
- memset(_tmp_ptr, 0, sizeof(*_tmp_ptr)); \
- _tmp_ptr; \
- })
-
-/* Return the number of elements in the array a */
-#define ARRAY_COUNT(a) ((a)->count)
-
-/* Return a pointer to the i-th element in the array a */
-#define ARRAY_ELEMENT(a, i) ((a)->element + (i))
-
-/* Return the index of the element pointed by p in the array a */
-#define ARRAY_INDEX(a, p) ((p) - (a)->element)
-
-/* Go through each element in the array a and assign index and pointer
- to the element to the variable i and ptr */
-#define ARRAY_ELEMENT_FOREACH(a, i, ptr) \
- for ((i) = 0, (ptr) = (a)->element; (i) < (a)->count; (i)++, (ptr)++)
-
-/* Free the memory used by the array a. The array becomes an empty array. */
-#define ARRAY_FREE(a) \
- do { \
- free((a)->element); \
- (a)->element = NULL; \
- (a)->size = 0; \
- (a)->count = 0; \
- } while (0)
-
-/* Return the index of the element with the value x. -1 if not found */
-#define ARRAY_FIND(a, x) \
- ({ \
- typeof((a)->element) _bptr = (a)->element; \
- typeof((a)->element) _eptr = (a)->element + (a)->count; \
- for (; _bptr != _eptr && *_bptr != x; _bptr++) \
- ; \
- (_bptr == _eptr) ? -1 : (_bptr - (a)->element); \
- })
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_ARRAY_H_ */
diff --git a/cras/src/common/bluetooth.h b/cras/src/common/bluetooth.h
deleted file mode 100644
index 66beadad..00000000
--- a/cras/src/common/bluetooth.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/* Copyright (c) 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Definitions from Linux bluetooth directory that are useful for
- * bluetotoh audio.
- * TODO(hychao): Remove this file when there is bluetooth user
- * space header provided.
- */
-
-#include <unistd.h>
-
-#define HCI_VIRTUAL 0
-#define HCI_USB 1
-#define HCI_PCCARD 2
-#define HCI_UART 3
-#define HCI_RS232 4
-#define HCI_PCI 5
-#define HCI_SDIO 6
-#define HCI_BUS_MAX 7
-
-#define BTPROTO_HCI 1
-#define BTPROTO_SCO 2
-
-#define SCO_OPTIONS 0x01
-#define SOL_SCO 17
-
-#define HCIGETDEVINFO _IOR('H', 211, int)
-
-typedef struct {
- uint8_t b[6];
-} __attribute__((packed)) bdaddr_t;
-
-struct hci_dev_stats {
- uint32_t err_rx;
- uint32_t err_tx;
- uint32_t cmd_tx;
- uint32_t evt_rx;
- uint32_t acl_tx;
- uint32_t acl_rx;
- uint32_t sco_tx;
- uint32_t sco_rx;
- uint32_t byte_rx;
- uint32_t byte_tx;
-};
-
-struct hci_dev_info {
- uint16_t dev_id;
- char name[8];
- bdaddr_t bdaddr;
- uint32_t flags;
- uint8_t type;
- uint8_t features[8];
- uint32_t pkt_type;
- uint32_t link_policy;
- uint32_t link_mode;
- uint16_t acl_mtu;
- uint16_t acl_pkts;
- uint16_t sco_mtu;
- uint16_t sco_pkts;
- struct hci_dev_stats stat;
-};
-
-struct sco_options {
- uint16_t mtu;
-};
-
-#define SOL_BLUETOOTH 274
-
-#define BT_VOICE 11
-struct bt_voice {
- uint16_t setting;
-};
-
-#define BT_VOICE_TRANSPARENT 0x0003
-
-#define BT_SNDMTU 12
-
-#define BT_RCVMTU 13
-
-#define BT_PKT_STATUS 16
-
-#define BT_SCM_PKT_STATUS 0x03
diff --git a/cras/src/common/byte_buffer.h b/cras/src/common/byte_buffer.h
deleted file mode 100644
index dd9cb2d0..00000000
--- a/cras/src/common/byte_buffer.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef BYTE_BUFFER_H_
-#define BYTE_BUFFER_H_
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <sys/param.h>
-
-struct byte_buffer {
- unsigned int write_idx;
- unsigned int read_idx;
- unsigned int level;
- unsigned int max_size;
- unsigned int used_size;
- uint8_t bytes[];
-};
-
-/* Create a byte buffer to hold buffer_size_bytes worth of data. */
-static inline struct byte_buffer *byte_buffer_create(size_t buffer_size_bytes)
-{
- struct byte_buffer *buf;
- buf = (struct byte_buffer *)calloc(1, sizeof(struct byte_buffer) +
- buffer_size_bytes);
- if (!buf)
- return buf;
- buf->max_size = buffer_size_bytes;
- buf->used_size = buffer_size_bytes;
- return buf;
-}
-
-static inline void byte_buffer_set_used_size(struct byte_buffer *buf,
- size_t used_size)
-{
- buf->used_size = MIN(used_size, buf->max_size);
-}
-
-/* Destory a byte_buffer created with byte_buffer_create. */
-static inline void byte_buffer_destroy(struct byte_buffer **buf)
-{
- free(*buf);
- *buf = NULL;
-}
-
-static inline unsigned int buf_writable(struct byte_buffer *buf)
-{
- if (buf->level >= buf->used_size)
- return 0;
- if (buf->write_idx < buf->read_idx)
- return buf->read_idx - buf->write_idx;
-
- return buf->used_size - buf->write_idx;
-}
-
-static inline unsigned int buf_readable(struct byte_buffer *buf)
-{
- if (buf->level == 0)
- return 0;
-
- if (buf->read_idx < buf->write_idx)
- return buf->write_idx - buf->read_idx;
-
- return buf->used_size - buf->read_idx;
-}
-
-/* Adjust readable size to given value. Use with caution. */
-static inline unsigned int buf_adjust_readable(struct byte_buffer *buf,
- size_t readable)
-{
- buf->level = MIN(readable, buf->used_size);
- buf->write_idx = (buf->read_idx + buf->level) % buf->used_size;
- return 0;
-}
-
-static inline unsigned int buf_queued(struct byte_buffer *buf)
-{
- return buf->level;
-}
-
-static inline unsigned int buf_available(const struct byte_buffer *buf)
-{
- return buf->used_size - buf->level;
-}
-
-static inline uint8_t *buf_read_pointer(struct byte_buffer *buf)
-{
- return &buf->bytes[buf->read_idx];
-}
-
-static inline uint8_t *buf_read_pointer_size(struct byte_buffer *buf,
- unsigned int *readable)
-{
- *readable = buf_readable(buf);
- return buf_read_pointer(buf);
-}
-
-static inline void buf_increment_read(struct byte_buffer *buf, size_t inc)
-{
- inc = MIN(inc, buf->level);
- buf->read_idx += inc;
- buf->read_idx %= buf->used_size;
- buf->level -= inc;
-}
-
-static inline uint8_t *buf_write_pointer(struct byte_buffer *buf)
-{
- return &buf->bytes[buf->write_idx];
-}
-
-static inline uint8_t *buf_write_pointer_size(struct byte_buffer *buf,
- unsigned int *writeable)
-{
- *writeable = buf_writable(buf);
- return buf_write_pointer(buf);
-}
-
-static inline void buf_increment_write(struct byte_buffer *buf, size_t inc)
-{
- buf->write_idx += inc;
- buf->write_idx %= buf->used_size;
- if (buf->level + inc < buf->used_size)
- buf->level += inc;
- else
- buf->level = buf->used_size;
-}
-
-static inline void buf_reset(struct byte_buffer *buf)
-{
- buf->write_idx = 0;
- buf->read_idx = 0;
- buf->level = 0;
-}
-
-#endif /* BYTE_BUFFER_H_ */
diff --git a/cras/src/common/cras_audio_codec.h b/cras/src/common/cras_audio_codec.h
deleted file mode 100644
index 01277ea0..00000000
--- a/cras/src/common/cras_audio_codec.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef COMMON_CRAS_AUDIO_CODEC_H_
-#define COMMON_CRAS_AUDIO_CODEC_H_
-
-/* A audio codec that transforms audio between different formats.
- * decode - Function to decode audio samples. Returns the number of decoded
- * bytes of input buffer, number of decoded bytes of output buffer
- * will be filled in count.
- * encode - Function to encode audio samples. Returns the number of encoded
- * bytes of input buffer, number of encoded bytes of output buffer
- * will be filled in count.
- * priv_data - Private data for specific use.
- */
-struct cras_audio_codec {
- int (*decode)(struct cras_audio_codec *codec, const void *input,
- size_t input_len, void *output, size_t output_len,
- size_t *count);
- int (*encode)(struct cras_audio_codec *codec, const void *input,
- size_t intput_len, void *output, size_t output_len,
- size_t *count);
- void *priv_data;
-};
-
-#endif /* COMMON_CRAS_AUDIO_CODEC_H_ */
diff --git a/cras/src/common/cras_audio_format.c b/cras/src/common/cras_audio_format.c
deleted file mode 100644
index 8bd48656..00000000
--- a/cras/src/common/cras_audio_format.c
+++ /dev/null
@@ -1,171 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include "cras_audio_format.h"
-
-/* Table for allowed alternatives when doing channel re-mapping.
- * When channel_alt[X][Y] is non-zero, it's allowed to map channel
- * from X to Y. */
-static const int channel_alt[CRAS_CH_MAX][CRAS_CH_MAX] = {
- /*FL FR RL RR FC LFE SL SR RC FLC FRC */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* FL */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* FR */
- { 0, 0, 0, 0, 0, 0, +1, 0, 0, 0, +0 }, /* RL */
- { 0, 0, 0, 0, 0, 0, +0, 1, 0, 0, +0 }, /* RR */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* FC */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* LFE */
- { 0, 0, 1, 0, 0, 0, +0, 0, 0, 0, +0 }, /* SL */
- { 0, 0, 0, 1, 0, 0, +0, 0, 0, 0, +0 }, /* SR */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* RC */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* FLC */
- { 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, +0 }, /* FRC */
-};
-
-/* Create an audio format structure. */
-struct cras_audio_format *cras_audio_format_create(snd_pcm_format_t format,
- size_t frame_rate,
- size_t num_channels)
-{
- struct cras_audio_format *fmt;
- unsigned i;
-
- fmt = (struct cras_audio_format *)calloc(1, sizeof(*fmt));
- if (fmt == NULL)
- return fmt;
-
- fmt->format = format;
- fmt->frame_rate = frame_rate;
- fmt->num_channels = num_channels;
-
- /* Set a default working channel layout according to num_channels.
- * Initialize all other channel position to -1(not set)
- */
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt->channel_layout[i] = (i < num_channels) ? i : -1;
-
- return fmt;
-}
-
-int cras_audio_format_set_channel_layout(struct cras_audio_format *format,
- const int8_t layout[CRAS_CH_MAX])
-{
- int i;
-
- /* Check that the max channel index should not exceed the
- * channel count set in format.
- */
- for (i = 0; i < CRAS_CH_MAX; i++)
- if (layout[i] < -1 || layout[i] >= (int)format->num_channels)
- return -EINVAL;
-
- for (i = 0; i < CRAS_CH_MAX; i++)
- format->channel_layout[i] = layout[i];
-
- return 0;
-}
-
-/* Verifies if all channel_layout[i] are in [-1, fmt->num_channels). */
-bool cras_audio_format_valid(const struct cras_audio_format *fmt)
-{
- int i;
- for (i = 0; i < CRAS_CH_MAX; i++) {
- if (fmt->channel_layout[i] < -1 ||
- fmt->channel_layout[i] >= (int)fmt->num_channels) {
- return false;
- }
- }
- return true;
-}
-
-/* Destroy an audio format struct created with cras_audio_format_crate. */
-void cras_audio_format_destroy(struct cras_audio_format *fmt)
-{
- free(fmt);
-}
-
-float **cras_channel_conv_matrix_alloc(size_t in_ch, size_t out_ch)
-{
- size_t i;
- float **p;
- p = (float **)calloc(out_ch, sizeof(*p));
- if (p == NULL)
- return NULL;
- for (i = 0; i < out_ch; i++) {
- p[i] = (float *)calloc(in_ch, sizeof(*p[i]));
- if (p[i] == NULL)
- goto alloc_err;
- }
- return p;
-
-alloc_err:
- if (p)
- cras_channel_conv_matrix_destroy(p, out_ch);
- return NULL;
-}
-
-void cras_channel_conv_matrix_destroy(float **p, size_t out_ch)
-{
- size_t i;
- for (i = 0; i < out_ch; i++)
- free(p[i]);
- free(p);
-}
-
-float **cras_channel_conv_matrix_create(const struct cras_audio_format *in,
- const struct cras_audio_format *out)
-{
- int i;
- float **mtx;
-
- for (i = 0; i < CRAS_CH_MAX; i++) {
- if (in->channel_layout[i] >= (int)in->num_channels ||
- out->channel_layout[i] >= (int)out->num_channels) {
- syslog(LOG_ERR, "Fail to create conversion matrix "
- "due to invalid channel layout");
- return NULL;
- }
- }
-
- mtx = cras_channel_conv_matrix_alloc(in->num_channels,
- out->num_channels);
-
- /* For the in/out format pair which has the same set of channels
- * in use, create a permutation matrix for them.
- */
- for (i = 0; i < CRAS_CH_MAX; i++) {
- if (in->channel_layout[i] == -1 && out->channel_layout[i] == -1)
- continue;
- if (in->channel_layout[i] != -1 && out->channel_layout[i] != -1)
- mtx[out->channel_layout[i]][in->channel_layout[i]] = 1;
- else if (in->channel_layout[i] != -1) {
- /* When the same channel does not appear at output
- * channel layout. Look up for allowed channel
- * alternatives.
- */
- int alt;
- for (alt = 0; alt <= CRAS_CH_MAX; alt++) {
- if (alt == CRAS_CH_MAX)
- goto fail;
- if (channel_alt[i][alt] &&
- in->channel_layout[alt] == -1 &&
- out->channel_layout[alt] != -1) {
- mtx[out->channel_layout[alt]]
- [in->channel_layout[i]] = 1;
- break;
- }
- }
- }
- }
-
- return mtx;
-fail:
- cras_channel_conv_matrix_destroy(mtx, out->num_channels);
- return NULL;
-}
diff --git a/cras/src/common/cras_audio_format.h b/cras/src/common/cras_audio_format.h
deleted file mode 100644
index f0cc94f4..00000000
--- a/cras/src/common/cras_audio_format.h
+++ /dev/null
@@ -1,176 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_AUDIO_FORMAT_H_
-#define CRAS_AUDIO_FORMAT_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <string.h>
-
-#ifdef __ANDROID__
-#include <hardware/audio.h>
-#include <tinyalsa/asoundlib.h>
-#define PCM_FORMAT_WIDTH(format) pcm_format_to_bits(format)
-typedef enum pcm_format snd_pcm_format_t;
-
-/* libasound audio formats. */
-#define SND_PCM_FORMAT_UNKNOWN -1
-#define SND_PCM_FORMAT_U8 1
-#define SND_PCM_FORMAT_S16_LE 2
-#define SND_PCM_FORMAT_S24_LE 6
-#define SND_PCM_FORMAT_S32_LE 10
-
-static inline int audio_format_to_cras_format(audio_format_t audio_format)
-{
- switch (audio_format) {
- case AUDIO_FORMAT_PCM_16_BIT:
- return SND_PCM_FORMAT_S16_LE;
- case AUDIO_FORMAT_PCM_8_BIT:
- return SND_PCM_FORMAT_U8;
- case AUDIO_FORMAT_PCM_32_BIT:
- return SND_PCM_FORMAT_S32_LE;
- case AUDIO_FORMAT_PCM_8_24_BIT:
- return SND_PCM_FORMAT_S24_LE;
- default:
- return SND_PCM_FORMAT_UNKNOWN;
- }
-}
-#else
-#include <alsa/asoundlib.h>
-#define PCM_FORMAT_WIDTH(format) snd_pcm_format_physical_width(format)
-#endif
-
-/* Identifiers for each channel in audio stream. */
-enum CRAS_CHANNEL {
- /* First nine channels matches the
- * snd_mixer_selem_channel_id_t values.
- */
- CRAS_CH_FL,
- CRAS_CH_FR,
- CRAS_CH_RL,
- CRAS_CH_RR,
- CRAS_CH_FC,
- CRAS_CH_LFE,
- CRAS_CH_SL,
- CRAS_CH_SR,
- CRAS_CH_RC,
- /* Channels defined both in channel_layout.h and
- * alsa channel mapping API. */
- CRAS_CH_FLC,
- CRAS_CH_FRC,
- /* Must be the last one */
- CRAS_CH_MAX,
-};
-
-/* Audio format. */
-struct cras_audio_format {
- snd_pcm_format_t format;
- size_t frame_rate; /* Hz */
-
- // TODO(hychao): use channel_layout to replace num_channels
- size_t num_channels;
-
- /* Channel layout whose value represents the index of each
- * CRAS_CHANNEL in the layout. Value -1 means the channel is
- * not used. For example: 0,1,2,3,4,5,-1,-1,-1,-1,-1 means the
- * channel order is FL,FR,RL,RR,FC.
- */
- int8_t channel_layout[CRAS_CH_MAX];
-};
-
-/* Packed version of audio format, for use in messages. We cannot modify
- * the above structure to keep binary compatibility with Chromium.
- * If cras_audio_format ever changes, merge the 2 structures.
- */
-struct __attribute__((__packed__)) cras_audio_format_packed {
- int32_t format;
- uint32_t frame_rate;
- uint32_t num_channels;
- int8_t channel_layout[CRAS_CH_MAX];
-};
-
-static inline void pack_cras_audio_format(struct cras_audio_format_packed *dest,
- const struct cras_audio_format *src)
-{
- dest->format = src->format;
- dest->frame_rate = src->frame_rate;
- dest->num_channels = src->num_channels;
- memcpy(dest->channel_layout, src->channel_layout,
- sizeof(src->channel_layout));
-}
-
-static inline struct cras_audio_format
-unpack_cras_audio_format(const struct cras_audio_format_packed *src)
-{
- struct cras_audio_format dest;
- dest.format = (snd_pcm_format_t)src->format;
- dest.frame_rate = src->frame_rate;
- dest.num_channels = src->num_channels;
- memcpy(dest.channel_layout, src->channel_layout,
- sizeof(src->channel_layout));
- return dest;
-}
-
-/* Returns the number of bytes per sample.
- * This is bits per smaple / 8 * num_channels.
- */
-static inline size_t cras_get_format_bytes(const struct cras_audio_format *fmt)
-{
- const int bytes = PCM_FORMAT_WIDTH(fmt->format) / 8;
- return (size_t)bytes * fmt->num_channels;
-}
-
-/* Sets channel layout to a default value where channels [0, num_channels] are
- * placed to the same position of its channel index, otherwise set to -1. */
-static inline void
-cras_audio_format_set_default_channel_layout(struct cras_audio_format *format)
-{
- unsigned int i;
- for (i = 0; i < CRAS_CH_MAX; i++)
- format->channel_layout[i] = i < format->num_channels ? i : -1;
-}
-
-/* Create an audio format structure. */
-struct cras_audio_format *cras_audio_format_create(snd_pcm_format_t format,
- size_t frame_rate,
- size_t num_channels);
-
-/* Destroy an audio format struct created with cras_audio_format_crate. */
-void cras_audio_format_destroy(struct cras_audio_format *fmt);
-
-/* Returns true if the audio format is valid */
-bool cras_audio_format_valid(const struct cras_audio_format *fmt);
-
-/* Sets the channel layout for given format.
- * format - The format structure to carry channel layout info
- * layout - An integer array representing the position of each
- * channel in enum CRAS_CHANNEL
- */
-int cras_audio_format_set_channel_layout(struct cras_audio_format *format,
- const int8_t layout[CRAS_CH_MAX]);
-
-/* Allocates an empty channel conversion matrix of given size. */
-float **cras_channel_conv_matrix_alloc(size_t in_ch, size_t out_ch);
-
-/* Destroys the channel conversion matrix. */
-void cras_channel_conv_matrix_destroy(float **mtx, size_t out_ch);
-
-/* Creates channel conversion matrix for given input and output format.
- * Returns NULL if the conversion is not supported between the channel
- * layouts specified in input/ouput formats.
- */
-float **cras_channel_conv_matrix_create(const struct cras_audio_format *in,
- const struct cras_audio_format *out);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CRAS_AUDIO_FORMAT_H_ */
diff --git a/cras/src/common/cras_checksum.c b/cras/src/common/cras_checksum.c
deleted file mode 100644
index 33e9f603..00000000
--- a/cras/src/common/cras_checksum.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* The table and the algorithm are taken from
- * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cksum.html
- *
- * The output of this function is the same as the output of the "cksum"
- * command.
- */
-
-#include "cras_checksum.h"
-
-static const uint32_t crctab[] = {
- 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
- 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
- 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7,
- 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
- 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3,
- 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
- 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef,
- 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
- 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb,
- 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
- 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
- 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
- 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4,
- 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
- 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08,
- 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
- 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc,
- 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
- 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050,
- 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
- 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
- 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
- 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1,
- 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
- 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5,
- 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
- 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9,
- 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
- 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd,
- 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
- 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
- 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
- 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2,
- 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
- 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e,
- 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
- 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a,
- 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
- 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676,
- 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
- 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
- 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
- 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
-};
-
-uint32_t crc32_checksum(const unsigned char *input, size_t n)
-{
- size_t i;
- uint32_t s = 0, c;
-
- for (i = 0; i < n; i++) {
- c = *input++;
- s = (s << 8) ^ crctab[(s >> 24) ^ c];
- }
-
- /* Extend with the length of the string. */
- while (n != 0) {
- c = n & 0xff;
- n >>= 8;
- s = (s << 8) ^ crctab[(s >> 24) ^ c];
- }
-
- return ~s;
-}
diff --git a/cras/src/common/cras_checksum.h b/cras/src/common/cras_checksum.h
deleted file mode 100644
index d995d667..00000000
--- a/cras/src/common/cras_checksum.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_CHECKSUM_H_
-#define CRAS_CHECKSUM_H_
-
-#include "cras_types.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-uint32_t crc32_checksum(const unsigned char *input, size_t n);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_CHECKSUM_H_ */
diff --git a/cras/src/common/cras_config.c b/cras/src/common/cras_config.c
deleted file mode 100644
index 75fa24e7..00000000
--- a/cras/src/common/cras_config.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <pwd.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "cras_config.h"
-
-const char *cras_config_get_system_socket_file_dir()
-{
- /* This directory is created by the upstart script, eventually it would
- * be nice to make this more dynamic, but it isn't needed right now for
- * Chrome OS. */
- return CRAS_SOCKET_FILE_DIR;
-}
-
-int cras_fill_socket_path(enum CRAS_CONNECTION_TYPE conn_type, char *sock_path)
-{
- const char *sock_file;
- const char *sock_dir;
-
- sock_dir = cras_config_get_system_socket_file_dir();
- if (sock_dir == NULL) {
- return -ENOTDIR;
- }
-
- switch (conn_type) {
- case CRAS_CONTROL:
- sock_file = CRAS_SOCKET_FILE;
- break;
- case CRAS_PLAYBACK:
- sock_file = CRAS_PLAYBACK_SOCKET_FILE;
- break;
- case CRAS_CAPTURE:
- sock_file = CRAS_CAPTURE_SOCKET_FILE;
- break;
- case CRAS_VMS_LEGACY:
- sock_file = CRAS_VMS_LEGACY_SOCKET_FILE;
- break;
- case CRAS_VMS_UNIFIED:
- sock_file = CRAS_VMS_UNIFIED_SOCKET_FILE;
- break;
- case CRAS_PLUGIN_PLAYBACK:
- sock_file = CRAS_PLUGIN_PLAYBACK_SOCKET_FILE;
- break;
- case CRAS_PLUGIN_UNIFIED:
- sock_file = CRAS_PLUGIN_UNIFIED_SOCKET_FILE;
- break;
- default:
- return -EINVAL;
- }
-
- snprintf(sock_path, CRAS_MAX_SOCKET_PATH_SIZE, "%s/%s", sock_dir,
- sock_file);
-
- return 0;
-}
diff --git a/cras/src/common/cras_config.h b/cras/src/common/cras_config.h
deleted file mode 100644
index 1c8e55fa..00000000
--- a/cras/src/common/cras_config.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_CONFIG_H_
-#define CRAS_CONFIG_H_
-
-#include "cras_types.h"
-
-#define CRAS_MIN_BUFFER_TIME_IN_US 1000 /* 1 milliseconds */
-#define CRAS_MAX_BUFFER_TIME_IN_S 10 /* 10 seconds */
-
-#define CRAS_SERVER_RT_THREAD_PRIORITY 12
-#define CRAS_CLIENT_RT_THREAD_PRIORITY 10
-#define CRAS_CLIENT_NICENESS_LEVEL -10
-#define CRAS_SOCKET_FILE ".cras_socket"
-#define CRAS_PLAYBACK_SOCKET_FILE ".cras_playback"
-#define CRAS_CAPTURE_SOCKET_FILE ".cras_capture"
-/* Socket file paths for VMs. */
-#define CRAS_VMS_LEGACY_SOCKET_FILE "vms/.cras_socket"
-#define CRAS_VMS_UNIFIED_SOCKET_FILE "vms/.cras_unified"
-/* Socket file paths for pluginVM. */
-#define CRAS_PLUGIN_PLAYBACK_SOCKET_FILE "vms/plugin/playback/.cras_socket"
-#define CRAS_PLUGIN_UNIFIED_SOCKET_FILE "vms/plugin/unified/.cras_socket"
-
-/* Maximum socket_path size, which is equals to sizeof(sun_path) in sockaddr_un
- * structure.
- */
-#define CRAS_MAX_SOCKET_PATH_SIZE 108
-
-/* CRAS_CONFIG_FILE_DIR is defined as $sysconfdir/cras by the configure
- script. */
-
-/* Gets the path to save UDS socket files. */
-const char *cras_config_get_system_socket_file_dir();
-
-/* Fills sock_path by given connection type.
- *
- * Args:
- * conn_type - server socket connection type.
- * sock_path - socket path to be filled.
- *
- * Returns:
- * 0 for success, positive error code on error.
- */
-int cras_fill_socket_path(enum CRAS_CONNECTION_TYPE conn_type, char *sock_path);
-
-#endif /* CRAS_CONFIG_H_ */
diff --git a/cras/src/common/cras_file_wait.c b/cras/src/common/cras_file_wait.c
deleted file mode 100644
index 190a5e10..00000000
--- a/cras/src/common/cras_file_wait.c
+++ /dev/null
@@ -1,319 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-#include <sys/inotify.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "cras_file_wait.h"
-
-#define CRAS_FILE_WAIT_EVENT_MIN_SIZE sizeof(struct inotify_event)
-#define CRAS_FILE_WAIT_EVENT_SIZE (CRAS_FILE_WAIT_EVENT_MIN_SIZE + NAME_MAX + 1)
-#define CRAS_FILE_WAIT_FLAG_MOCK_RACE (1u << 31)
-
-struct cras_file_wait {
- cras_file_wait_callback_t callback;
- void *callback_context;
- const char *file_path;
- size_t file_path_len;
- char *watch_path;
- char *watch_dir;
- char *watch_file_name;
- size_t watch_file_name_len;
- int inotify_fd;
- int watch_id;
- char event_buf[CRAS_FILE_WAIT_EVENT_SIZE];
- cras_file_wait_flag_t flags;
-};
-
-int cras_file_wait_get_fd(struct cras_file_wait *file_wait)
-{
- if (!file_wait)
- return -EINVAL;
- if (file_wait->inotify_fd < 0)
- return -EINVAL;
- return file_wait->inotify_fd;
-}
-
-/* Defined for the unittest. */
-void cras_file_wait_mock_race_condition(struct cras_file_wait *file_wait);
-void cras_file_wait_mock_race_condition(struct cras_file_wait *file_wait)
-{
- if (file_wait)
- file_wait->flags |= CRAS_FILE_WAIT_FLAG_MOCK_RACE;
-}
-
-void cras_file_wait_destroy(struct cras_file_wait *file_wait)
-{
- if (!file_wait)
- return;
- if (file_wait->inotify_fd >= 0)
- close(file_wait->inotify_fd);
- free(file_wait);
-}
-
-static int cras_file_wait_rm_watch(struct cras_file_wait *file_wait)
-{
- int rc;
-
- file_wait->watch_path[0] = 0;
- file_wait->watch_dir[0] = 0;
- file_wait->watch_file_name[0] = 0;
- file_wait->watch_file_name_len = 0;
- if (file_wait->inotify_fd >= 0 && file_wait->watch_id >= 0) {
- rc = inotify_rm_watch(file_wait->inotify_fd,
- file_wait->watch_id);
- file_wait->watch_id = -1;
- if (rc < 0)
- return -errno;
- }
- return 0;
-}
-
-int cras_file_wait_process_event(struct cras_file_wait *file_wait,
- struct inotify_event *event)
-{
- cras_file_wait_event_t file_wait_event;
-
- syslog(LOG_DEBUG,
- "file_wait->watch_id: %d, event->wd: %d"
- ", event->mask: %x, event->name: %s",
- file_wait->watch_id, event->wd, event->mask,
- event->len ? event->name : "");
-
- if (event->wd != file_wait->watch_id)
- return 0;
-
- if (event->mask & IN_IGNORED) {
- /* The watch has been removed. */
- file_wait->watch_id = -1;
- return cras_file_wait_rm_watch(file_wait);
- }
-
- if (event->len == 0 ||
- memcmp(event->name, file_wait->watch_file_name,
- file_wait->watch_file_name_len + 1) != 0) {
- /* Some file we don't care about. */
- return 0;
- }
-
- if ((event->mask & (IN_CREATE | IN_MOVED_TO)) != 0)
- file_wait_event = CRAS_FILE_WAIT_EVENT_CREATED;
- else if ((event->mask & (IN_DELETE | IN_MOVED_FROM)) != 0)
- file_wait_event = CRAS_FILE_WAIT_EVENT_DELETED;
- else
- return 0;
-
- /* Found the file! */
- if (strcmp(file_wait->watch_path, file_wait->file_path) == 0) {
- /* Tell the caller about this creation or deletion. */
- file_wait->callback(file_wait->callback_context,
- file_wait_event, event->name);
- } else {
- /* Remove the watch for this file, move on. */
- return cras_file_wait_rm_watch(file_wait);
- }
- return 0;
-}
-
-int cras_file_wait_dispatch(struct cras_file_wait *file_wait)
-{
- struct inotify_event *event;
- char *watch_dir_end;
- size_t watch_dir_len;
- char *watch_file_start;
- size_t watch_path_len;
- int rc = 0;
- int flags;
- ssize_t read_rc;
- ssize_t read_offset;
-
- if (!file_wait)
- return -EINVAL;
-
- /* If we have a file-descriptor, then read it and see what's up. */
- if (file_wait->inotify_fd >= 0) {
- read_offset = 0;
- read_rc = read(file_wait->inotify_fd, file_wait->event_buf,
- CRAS_FILE_WAIT_EVENT_SIZE);
- if (read_rc < 0) {
- rc = -errno;
- if ((rc == -EAGAIN || rc == -EWOULDBLOCK) &&
- file_wait->watch_id < 0) {
- /* Really nothing to read yet: we need to
- * setup a watch. */
- rc = 0;
- }
- } else if (read_rc < CRAS_FILE_WAIT_EVENT_MIN_SIZE) {
- rc = -EIO;
- } else if (file_wait->watch_id < 0) {
- /* Processing messages related to old watches. */
- rc = 0;
- } else
- while (rc == 0 && read_offset < read_rc) {
- event = (struct inotify_event
- *)(file_wait->event_buf +
- read_offset);
- read_offset += sizeof(*event) + event->len;
- rc = cras_file_wait_process_event(file_wait,
- event);
- }
- }
-
- /* Report errors from above here. */
- if (rc < 0)
- return rc;
-
- if (file_wait->watch_id >= 0) {
- /* Assume that the watch that we have is the right one. */
- return 0;
- }
-
- /* Initialize inotify if we haven't already. */
- if (file_wait->inotify_fd < 0) {
- file_wait->inotify_fd = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
- if (file_wait->inotify_fd < 0)
- return -errno;
- }
-
- /* Figure out what we need to watch next. */
- rc = -ENOENT;
- strcpy(file_wait->watch_dir, file_wait->file_path);
- watch_dir_len = file_wait->file_path_len;
-
- while (rc == -ENOENT || rc == -EACCES) {
- strcpy(file_wait->watch_path, file_wait->watch_dir);
- watch_path_len = watch_dir_len;
-
- /* Find the end of the parent directory. */
- watch_dir_end = file_wait->watch_dir + watch_dir_len - 1;
- while (watch_dir_end > file_wait->watch_dir &&
- *watch_dir_end != '/')
- watch_dir_end--;
- watch_file_start = watch_dir_end + 1;
- /* Treat consecutive '/' characters as one. */
- while (watch_dir_end > file_wait->watch_dir &&
- *(watch_dir_end - 1) == '/')
- watch_dir_end--;
- watch_dir_len = watch_dir_end - file_wait->watch_dir;
-
- if (watch_dir_len == 0) {
- /* We're looking for a file in the current directory. */
- strcpy(file_wait->watch_file_name,
- file_wait->watch_path);
- file_wait->watch_file_name_len = watch_path_len;
- strcpy(file_wait->watch_dir, ".");
- watch_dir_len = 1;
- } else {
- /* Copy out the file name that we're looking for, and
- * mark the end of the directory path. */
- strcpy(file_wait->watch_file_name, watch_file_start);
- file_wait->watch_file_name_len =
- watch_path_len -
- (watch_file_start - file_wait->watch_dir);
- *watch_dir_end = 0;
- }
-
- if (file_wait->flags & CRAS_FILE_WAIT_FLAG_MOCK_RACE) {
- /* For testing only. */
- mknod(file_wait->watch_path, S_IFREG | 0600, 0);
- file_wait->flags &= ~CRAS_FILE_WAIT_FLAG_MOCK_RACE;
- }
-
- flags = IN_CREATE | IN_MOVED_TO | IN_DELETE | IN_MOVED_FROM;
- file_wait->watch_id = inotify_add_watch(
- file_wait->inotify_fd, file_wait->watch_dir, flags);
- if (file_wait->watch_id < 0) {
- rc = -errno;
- continue;
- }
-
- /* Satisfy the race condition between existence of the
- * file and creation of the watch. */
- rc = access(file_wait->watch_path, F_OK);
- if (rc < 0) {
- rc = -errno;
- if (rc == -ENOENT) {
- /* As expected, the file still doesn't exist. */
- rc = 0;
- }
- continue;
- }
-
- /* The file we're looking for exists. */
- if (strcmp(file_wait->watch_path, file_wait->file_path) == 0) {
- file_wait->callback(file_wait->callback_context,
- CRAS_FILE_WAIT_EVENT_CREATED,
- file_wait->watch_file_name);
- return 0;
- }
-
- /* Start over again. */
- rc = cras_file_wait_rm_watch(file_wait);
- if (rc < 0)
- return rc;
- rc = -ENOENT;
- strcpy(file_wait->watch_dir, file_wait->file_path);
- watch_dir_len = file_wait->file_path_len;
- }
-
- /* Get out for permissions problems for example. */
- return rc;
-}
-
-int cras_file_wait_create(const char *file_path, cras_file_wait_flag_t flags,
- cras_file_wait_callback_t callback,
- void *callback_context,
- struct cras_file_wait **file_wait_out)
-{
- struct cras_file_wait *file_wait;
- size_t file_path_len;
- int rc;
-
- if (!file_path || !*file_path || !callback || !file_wait_out)
- return -EINVAL;
- *file_wait_out = NULL;
-
- /* Create a struct cras_file_wait to track waiting for this file. */
- file_path_len = strlen(file_path);
- file_wait = (struct cras_file_wait *)calloc(
- 1, sizeof(*file_wait) + ((file_path_len + 1) * 5));
- if (!file_wait)
- return -ENOMEM;
- file_wait->callback = callback;
- file_wait->callback_context = callback_context;
- file_wait->inotify_fd = -1;
- file_wait->watch_id = -1;
- file_wait->file_path_len = file_path_len;
- file_wait->flags = flags;
-
- /* We've allocated memory such that the file_path, watch_path,
- * watch_dir, and watch_file_name data are appended to the end of
- * our cras_file_wait structure. */
- file_wait->file_path = (const char *)file_wait + sizeof(*file_wait);
- file_wait->watch_path =
- (char *)file_wait->file_path + file_path_len + 1;
- file_wait->watch_dir = file_wait->watch_path + file_path_len + 1;
- file_wait->watch_file_name = file_wait->watch_dir + file_path_len + 1;
- memcpy((void *)file_wait->file_path, file_path, file_path_len + 1);
-
- /* Setup the first watch. If that fails unexpectedly, then we destroy
- * the file wait structure immediately. */
- rc = cras_file_wait_dispatch(file_wait);
- if (rc < 0) {
- cras_file_wait_destroy(file_wait);
- return rc;
- }
-
- *file_wait_out = file_wait;
- return 0;
-}
diff --git a/cras/src/common/cras_file_wait.h b/cras/src/common/cras_file_wait.h
deleted file mode 100644
index e9ec3ad8..00000000
--- a/cras/src/common/cras_file_wait.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_FILE_WAIT_H_
-#define CRAS_FILE_WAIT_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Structure used to track the current progress of a file wait. */
-struct cras_file_wait;
-
-/* Flags type for file wait. */
-typedef unsigned int cras_file_wait_flag_t;
-
-/* No flags. */
-#define CRAS_FILE_WAIT_FLAG_NONE ((cras_file_wait_flag_t)0)
-
-/* File wait events. */
-typedef enum cras_file_wait_event {
- CRAS_FILE_WAIT_EVENT_NONE,
- CRAS_FILE_WAIT_EVENT_CREATED,
- CRAS_FILE_WAIT_EVENT_DELETED,
-} cras_file_wait_event_t;
-
-/*
- * File wait callback function.
- *
- * Called for cras_file_wait events. Do not call cras_file_wait_destroy()
- * from this function.
- *
- * Args:
- * context - Context pointer passed to cras_file_wait_start().
- * event - Event that has occurred related to this file wait.
- * filename - Filename associated with the event.
- */
-typedef void (*cras_file_wait_callback_t)(void *context,
- cras_file_wait_event_t event,
- const char *filename);
-
-/*
- * Wait for the existence of a file.
- *
- * Setup a watch with the aim of determining if the given file path exists. If
- * any parent directory is missing, then the appropriate watch is created to
- * watch for the parent (or it's parent). Watches are created or renewed while
- * this file wait structure exists.
- *
- * The callback function will be called with event CRAS_FILE_WAIT_EVENT_CREATED
- * when the file is created, moved into the directory, or if it already exists
- * when this function is called.
- *
- * After the file is found future deletion and creation events for the file can
- * be observed using the same file_wait structure and callback. When the file
- * is deleted or moved out of it's parent, the callback is called with event
- * CRAS_FILE_WAIT_EVENT_DELETED.
- *
- * Call cras_file_wait_destroy() to cancel the wait anytime and cleanup
- * resources.
- *
- * Args:
- * file_path - Path of the file or directory that must exist.
- * flags - CRAS_FILE_WAIT_FLAG_* values bit-wise orred together. Set to
- * CRAS_FILE_WAIT_FLAG_NONE for now.
- * callback - Callback function to execute to notify of file existence.
- * callback_context - Context pointer passed to the callback function.
- * file_wait_out - Pointer to file wait structure that is initialized.
- *
- * Returns:
- * - 0 for success, or negative on error.
- * - On error cras_file_wait_destroy() need not be called.
- */
-int cras_file_wait_create(const char *file_path, cras_file_wait_flag_t flags,
- cras_file_wait_callback_t callback,
- void *callback_context,
- struct cras_file_wait **file_wait_out);
-
-/* Returns the file-descriptor to poll for a file wait.
- *
- * Poll for POLLIN on this file decriptor. When there is data available, call
- * cras_file_wait_continue() on the associated file_wait structure.
- *
- * Args:
- * file_wait - The associated cras_file_wait structure initialized by
- * cras_file_wait_start().
- *
- * Returns:
- * Non-negative file descriptor number, or -EINVAL if the file_wait
- * structure is NULL or otherwise invalid.
- */
-int cras_file_wait_get_fd(struct cras_file_wait *file_wait);
-
-/* Dispatch a file wait event.
- *
- * Call this function when the file descriptor from cras_file_wait_fd() has
- * data ready (POLLIN). This function will call the callback provided to
- * cras_file_wait_start when there is a relevant event.
- *
- * Args:
- * file_wait - The associated cras_file_wait structure initialized by
- * cras_file_wait_start().
- *
- * Returns:
- * - 0 for success, negative on error.
- * - -EAGAIN or -EWOULDBLOCK when this function would have blocked.
- */
-int cras_file_wait_dispatch(struct cras_file_wait *file_wait);
-
-/* Destroy a file wait structure.
- *
- * This function can be called to cleanup a cras_file_wait structure, and it
- * will interrupt any wait that is in progress; the pointer is subsequently
- * invalid.
- *
- * Args:
- * file_wait - The cras_file_wait structure initialized by
- * cras_file_wait_start();
- */
-void cras_file_wait_destroy(struct cras_file_wait *file_wait);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_FILE_WAIT_H_ */
diff --git a/cras/src/common/cras_iodev_info.h b/cras/src/common/cras_iodev_info.h
deleted file mode 100644
index 85d20f90..00000000
--- a/cras/src/common/cras_iodev_info.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_IODEV_INFO_H_
-#define CRAS_IODEV_INFO_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#define CRAS_IODEV_NAME_BUFFER_SIZE 64
-#define CRAS_NODE_TYPE_BUFFER_SIZE 32
-#define CRAS_NODE_MIC_POS_BUFFER_SIZE 128
-#define CRAS_NODE_NAME_BUFFER_SIZE 64
-#define CRAS_NODE_HOTWORD_MODEL_BUFFER_SIZE 16
-
-/* Identifying information about an IO device.
- * idx - iodev index.
- * name - Name displayed to the user.
- * stable_id - ID that does not change due to device plug/unplug or reboot.
- * max_supported_channels - Max supported channel count of this device.
- */
-struct __attribute__((__packed__)) cras_iodev_info {
- uint32_t idx;
- char name[CRAS_IODEV_NAME_BUFFER_SIZE];
- uint32_t stable_id;
- uint32_t max_supported_channels;
-};
-
-/* Identifying information about an ionode on an iodev.
- * iodev_idx - Index of the device this node belongs.
- * ionode_idx - Index of this node on the device.
- * plugged - Set true if this node is known to be plugged in.
- * plugged_time - If plugged is true, this is the time it was attached.
- * active - If this is the node currently being used.
- * volume - per-node volume (0-100)
- * capture_gain - per-node capture gain/attenuation (in 100*dBFS)
- * ui_gain_scaler - Adjustable gain scaler set by Chrome.
- * left_right_swapped - Set true if left and right channels are swapped.
- * stable_id - ID that does not change due to device plug/unplug or reboot.
- * type - Type displayed to the user.
- * name - Name displayed to the user.
- * active_hotword_model - name of the currently selected hotword model.
- */
-struct __attribute__((__packed__)) cras_ionode_info {
- uint32_t iodev_idx;
- uint32_t ionode_idx;
- int32_t plugged;
- int32_t active;
- struct {
- int64_t tv_sec;
- int64_t tv_usec;
- } plugged_time;
- uint32_t volume;
- int32_t capture_gain;
- float ui_gain_scaler;
- int32_t left_right_swapped;
- uint32_t type_enum;
- uint32_t stable_id;
- char type[CRAS_NODE_TYPE_BUFFER_SIZE];
- char name[CRAS_NODE_NAME_BUFFER_SIZE];
- char active_hotword_model[CRAS_NODE_HOTWORD_MODEL_BUFFER_SIZE];
-};
-
-/* This is used in the cras_client_set_node_attr API.
- * IONODE_ATTR_PLUGGED - set the node as plugged/unplugged.
- * IONODE_ATTR_VOLUME - set the node's output volume.
- * IONODE_ATTR_CAPTURE_GAIN - set the node's capture gain.
- * IONODE_ATTR_SWAP_LEFT_RIGHT - Swap the node's left and right channel.
- */
-enum ionode_attr {
- IONODE_ATTR_PLUGGED,
- IONODE_ATTR_VOLUME,
- IONODE_ATTR_CAPTURE_GAIN,
- IONODE_ATTR_SWAP_LEFT_RIGHT
-};
-
-#endif /* CRAS_IODEV_INFO_H_ */
diff --git a/cras/src/common/cras_messages.h b/cras/src/common/cras_messages.h
deleted file mode 100644
index 50cbe7cd..00000000
--- a/cras/src/common/cras_messages.h
+++ /dev/null
@@ -1,756 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Messages sent between the server and clients.
- */
-#ifndef CRAS_MESSAGES_H_
-#define CRAS_MESSAGES_H_
-
-#include <stdint.h>
-
-#include "cras_iodev_info.h"
-#include "cras_types.h"
-
-/* Rev when message format changes. If new messages are added, or message ID
- * values change. */
-#define CRAS_PROTO_VER 7
-#define CRAS_SERV_MAX_MSG_SIZE 256
-#define CRAS_CLIENT_MAX_MSG_SIZE 256
-#define CRAS_MAX_HOTWORD_MODELS 243
-#define CRAS_MAX_REMIX_CHANNELS 8
-#define CRAS_MAX_TEST_DATA_LEN 224
-#define CRAS_AEC_DUMP_FILE_NAME_LEN 128
-
-/* Message IDs. */
-enum CRAS_SERVER_MESSAGE_ID {
- /* Client -> Server*/
- CRAS_SERVER_CONNECT_STREAM,
- CRAS_SERVER_DISCONNECT_STREAM,
- CRAS_SERVER_SWITCH_STREAM_TYPE_IODEV, /* Unused */
- CRAS_SERVER_SET_SYSTEM_VOLUME,
- CRAS_SERVER_SET_SYSTEM_MUTE,
- CRAS_SERVER_SET_USER_MUTE,
- CRAS_SERVER_SET_SYSTEM_MUTE_LOCKED,
- CRAS_SERVER_SET_SYSTEM_CAPTURE_GAIN, /* Deprecated */
- CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE,
- CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE_LOCKED,
- CRAS_SERVER_SET_NODE_ATTR,
- CRAS_SERVER_SELECT_NODE,
- CRAS_SERVER_RELOAD_DSP,
- CRAS_SERVER_DUMP_DSP_INFO,
- CRAS_SERVER_DUMP_AUDIO_THREAD,
- CRAS_SERVER_DUMP_SNAPSHOTS,
- CRAS_SERVER_ADD_ACTIVE_NODE,
- CRAS_SERVER_RM_ACTIVE_NODE,
- CRAS_SERVER_ADD_TEST_DEV,
- CRAS_SERVER_TEST_DEV_COMMAND,
- CRAS_SERVER_SUSPEND,
- CRAS_SERVER_RESUME,
- CRAS_CONFIG_GLOBAL_REMIX,
- CRAS_SERVER_GET_HOTWORD_MODELS,
- CRAS_SERVER_SET_HOTWORD_MODEL,
- CRAS_SERVER_REGISTER_NOTIFICATION,
- CRAS_SERVER_SET_AEC_DUMP,
- CRAS_SERVER_RELOAD_AEC_CONFIG,
- CRAS_SERVER_DUMP_BT,
- CRAS_SERVER_SET_BT_WBS_ENABLED,
- CRAS_SERVER_GET_ATLOG_FD,
- CRAS_SERVER_DUMP_MAIN,
-};
-
-enum CRAS_CLIENT_MESSAGE_ID {
- /* Server -> Client */
- CRAS_CLIENT_CONNECTED,
- CRAS_CLIENT_STREAM_CONNECTED,
- CRAS_CLIENT_AUDIO_DEBUG_INFO_READY,
- CRAS_CLIENT_GET_HOTWORD_MODELS_READY,
- /* System status messages */
- CRAS_CLIENT_OUTPUT_VOLUME_CHANGED,
- CRAS_CLIENT_OUTPUT_MUTE_CHANGED,
- CRAS_CLIENT_CAPTURE_GAIN_CHANGED,
- CRAS_CLIENT_CAPTURE_MUTE_CHANGED,
- CRAS_CLIENT_NODES_CHANGED,
- CRAS_CLIENT_ACTIVE_NODE_CHANGED,
- CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED,
- CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED,
- CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED,
- CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED,
- /* Server -> Client */
- CRAS_CLIENT_ATLOG_FD_READY,
-};
-
-/* Messages that control the server. These are sent from the client to affect
- * and action on the server. */
-struct __attribute__((__packed__)) cras_server_message {
- uint32_t length;
- enum CRAS_SERVER_MESSAGE_ID id;
-};
-
-/* Messages that control the client. These are sent from the server to affect
- * and action on the client. */
-struct __attribute__((__packed__)) cras_client_message {
- uint32_t length;
- enum CRAS_CLIENT_MESSAGE_ID id;
-};
-
-/*
- * Messages from client to server.
- */
-
-/* Sent by a client to connect a stream to the server. */
-struct __attribute__((__packed__)) cras_connect_message {
- struct cras_server_message header;
- uint32_t proto_version;
- enum CRAS_STREAM_DIRECTION direction; /* input/output/loopback */
- cras_stream_id_t stream_id; /* unique id for this stream */
- enum CRAS_STREAM_TYPE stream_type; /* media, or call, etc. */
- uint32_t buffer_frames; /* Buffer size in frames. */
- uint32_t cb_threshold; /* callback client when this much is left */
- uint32_t flags;
- struct cras_audio_format_packed format; /* rate, channel, sample size */
- uint32_t dev_idx; /* device to attach stream, 0 if none */
- uint64_t effects; /* Bit map of requested effects. */
- enum CRAS_CLIENT_TYPE client_type; /* chrome, or arc, etc. */
- uint64_t client_shm_size; /* Size of client-provided samples shm, if any */
- /* Initial values for shm samples buffer offsets. These will be 0 for
- * streams that do not use client-provided shm */
- uint64_t buffer_offsets[2];
-};
-
-static inline void cras_fill_connect_message(
- struct cras_connect_message *m, enum CRAS_STREAM_DIRECTION direction,
- cras_stream_id_t stream_id, enum CRAS_STREAM_TYPE stream_type,
- enum CRAS_CLIENT_TYPE client_type, size_t buffer_frames,
- size_t cb_threshold, uint32_t flags, uint64_t effects,
- struct cras_audio_format format, uint32_t dev_idx)
-{
- m->proto_version = CRAS_PROTO_VER;
- m->direction = direction;
- m->stream_id = stream_id;
- m->stream_type = stream_type;
- m->buffer_frames = buffer_frames;
- m->cb_threshold = cb_threshold;
- m->flags = flags;
- m->effects = effects;
- pack_cras_audio_format(&m->format, &format);
- m->dev_idx = dev_idx;
- m->client_type = client_type;
- m->client_shm_size = 0;
- m->buffer_offsets[0] = 0;
- m->buffer_offsets[1] = 0;
- m->header.id = CRAS_SERVER_CONNECT_STREAM;
- m->header.length = sizeof(struct cras_connect_message);
-}
-
-/* Sent by a client to remove a stream from the server. */
-struct __attribute__((__packed__)) cras_disconnect_stream_message {
- struct cras_server_message header;
- cras_stream_id_t stream_id;
-};
-static inline void
-cras_fill_disconnect_stream_message(struct cras_disconnect_stream_message *m,
- cras_stream_id_t stream_id)
-{
- m->stream_id = stream_id;
- m->header.id = CRAS_SERVER_DISCONNECT_STREAM;
- m->header.length = sizeof(struct cras_disconnect_stream_message);
-}
-
-/* Move streams of "type" to the iodev at "iodev_idx". */
-struct __attribute__((__packed__)) cras_switch_stream_type_iodev {
- struct cras_server_message header;
- enum CRAS_STREAM_TYPE stream_type;
- uint32_t iodev_idx;
-};
-
-/* Set the system volume. */
-struct __attribute__((__packed__)) cras_set_system_volume {
- struct cras_server_message header;
- uint32_t volume;
-};
-static inline void cras_fill_set_system_volume(struct cras_set_system_volume *m,
- size_t volume)
-{
- m->volume = volume;
- m->header.id = CRAS_SERVER_SET_SYSTEM_VOLUME;
- m->header.length = sizeof(*m);
-}
-
-/* Set the system mute state. */
-struct __attribute__((__packed__)) cras_set_system_mute {
- struct cras_server_message header;
- int32_t mute; /* 0 = un-mute, 1 = mute. */
-};
-static inline void cras_fill_set_system_mute(struct cras_set_system_mute *m,
- int mute)
-{
- m->mute = mute;
- m->header.id = CRAS_SERVER_SET_SYSTEM_MUTE;
- m->header.length = sizeof(*m);
-}
-static inline void cras_fill_set_user_mute(struct cras_set_system_mute *m,
- int mute)
-{
- m->mute = mute;
- m->header.id = CRAS_SERVER_SET_USER_MUTE;
- m->header.length = sizeof(*m);
-}
-static inline void
-cras_fill_set_system_mute_locked(struct cras_set_system_mute *m, int locked)
-{
- m->mute = locked;
- m->header.id = CRAS_SERVER_SET_SYSTEM_MUTE_LOCKED;
- m->header.length = sizeof(*m);
-}
-static inline void
-cras_fill_set_system_capture_mute(struct cras_set_system_mute *m, int mute)
-{
- m->mute = mute;
- m->header.id = CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE;
- m->header.length = sizeof(*m);
-}
-static inline void
-cras_fill_set_system_capture_mute_locked(struct cras_set_system_mute *m,
- int locked)
-{
- m->mute = locked;
- m->header.id = CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE_LOCKED;
- m->header.length = sizeof(*m);
-}
-
-/* Set an attribute of an ionode. */
-struct __attribute__((__packed__)) cras_set_node_attr {
- struct cras_server_message header;
- cras_node_id_t node_id;
- enum ionode_attr attr;
- int32_t value;
-};
-static inline void cras_fill_set_node_attr(struct cras_set_node_attr *m,
- cras_node_id_t node_id,
- enum ionode_attr attr, int value)
-{
- m->header.id = CRAS_SERVER_SET_NODE_ATTR;
- m->node_id = node_id;
- m->attr = attr;
- m->value = value;
- m->header.length = sizeof(*m);
-}
-
-/* Set an attribute of an ionode. */
-struct __attribute__((__packed__)) cras_select_node {
- struct cras_server_message header;
- enum CRAS_STREAM_DIRECTION direction;
- cras_node_id_t node_id;
-};
-static inline void cras_fill_select_node(struct cras_select_node *m,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- m->header.id = CRAS_SERVER_SELECT_NODE;
- m->direction = direction;
- m->node_id = node_id;
- m->header.length = sizeof(*m);
-}
-
-/* Add an active ionode. */
-struct __attribute__((__packed__)) cras_add_active_node {
- struct cras_server_message header;
- enum CRAS_STREAM_DIRECTION direction;
- cras_node_id_t node_id;
-};
-static inline void
-cras_fill_add_active_node(struct cras_add_active_node *m,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- m->header.id = CRAS_SERVER_ADD_ACTIVE_NODE;
- m->direction = direction;
- m->node_id = node_id;
- m->header.length = sizeof(*m);
-}
-
-/* Remove an active ionode. */
-struct __attribute__((__packed__)) cras_rm_active_node {
- struct cras_server_message header;
- enum CRAS_STREAM_DIRECTION direction;
- cras_node_id_t node_id;
-};
-static inline void
-cras_fill_rm_active_node(struct cras_rm_active_node *m,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- m->header.id = CRAS_SERVER_RM_ACTIVE_NODE;
- m->direction = direction;
- m->node_id = node_id;
- m->header.length = sizeof(*m);
-}
-
-/* Reload the dsp configuration. */
-struct __attribute__((__packed__)) cras_reload_dsp {
- struct cras_server_message header;
-};
-static inline void cras_fill_reload_dsp(struct cras_reload_dsp *m)
-{
- m->header.id = CRAS_SERVER_RELOAD_DSP;
- m->header.length = sizeof(*m);
-}
-
-/* Dump current dsp information to syslog. */
-struct __attribute__((__packed__)) cras_dump_dsp_info {
- struct cras_server_message header;
-};
-
-static inline void cras_fill_dump_dsp_info(struct cras_dump_dsp_info *m)
-{
- m->header.id = CRAS_SERVER_DUMP_DSP_INFO;
- m->header.length = sizeof(*m);
-}
-
-/* Dump current audio thread information to syslog. */
-struct __attribute__((__packed__)) cras_dump_audio_thread {
- struct cras_server_message header;
-};
-
-static inline void cras_fill_dump_audio_thread(struct cras_dump_audio_thread *m)
-{
- m->header.id = CRAS_SERVER_DUMP_AUDIO_THREAD;
- m->header.length = sizeof(*m);
-}
-
-struct __attribute__((__packed__)) cras_get_atlog_fd {
- struct cras_server_message header;
-};
-
-static inline void cras_fill_get_atlog_fd(struct cras_get_atlog_fd *m)
-{
- m->header.id = CRAS_SERVER_GET_ATLOG_FD;
- m->header.length = sizeof(*m);
-}
-
-/* Dump events in CRAS main thread. */
-struct __attribute__((__packed__)) cras_dump_main {
- struct cras_server_message header;
-};
-
-static inline void cras_fill_dump_main(struct cras_dump_main *m)
-{
- m->header.id = CRAS_SERVER_DUMP_MAIN;
- m->header.length = sizeof(*m);
-}
-
-/* Dump bluetooth events and state changes. */
-struct __attribute__((__packed__)) cras_dump_bt {
- struct cras_server_message header;
-};
-
-static inline void cras_fill_dump_bt(struct cras_dump_bt *m)
-{
- m->header.id = CRAS_SERVER_DUMP_BT;
- m->header.length = sizeof(*m);
-}
-
-/* Dump current audio thread snapshots to shard memory with the client. */
-struct __attribute__((__packed__)) cras_dump_snapshots {
- struct cras_server_message header;
-};
-
-static inline void cras_fill_dump_snapshots(struct cras_dump_snapshots *m)
-{
- m->header.id = CRAS_SERVER_DUMP_SNAPSHOTS;
- m->header.length = sizeof(*m);
-}
-
-/* Add a test device. */
-struct __attribute__((__packed__)) cras_add_test_dev {
- struct cras_server_message header;
- enum TEST_IODEV_TYPE type;
-};
-
-static inline void cras_fill_add_test_dev(struct cras_add_test_dev *m,
- enum TEST_IODEV_TYPE type)
-{
- m->header.id = CRAS_SERVER_ADD_TEST_DEV;
- m->header.length = sizeof(*m);
- m->type = type;
-}
-
-/* Command a test device. */
-struct __attribute__((__packed__)) cras_test_dev_command {
- struct cras_server_message header;
- unsigned int command;
- unsigned int iodev_idx;
- unsigned int data_len;
- uint8_t data[CRAS_MAX_TEST_DATA_LEN];
-};
-
-static inline void cras_fill_test_dev_command(struct cras_test_dev_command *m,
- unsigned int iodev_idx,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len,
- const uint8_t *data)
-{
- m->header.id = CRAS_SERVER_TEST_DEV_COMMAND;
- m->header.length = sizeof(*m) + data_len;
- m->iodev_idx = iodev_idx;
- m->command = command;
- m->data_len = data_len;
- memcpy(m->data, data, data_len);
-}
-
-static inline void cras_fill_suspend_message(struct cras_server_message *m,
- int is_suspend)
-{
- m->id = is_suspend ? CRAS_SERVER_SUSPEND : CRAS_SERVER_RESUME;
- m->length = sizeof(*m);
-}
-
-/*
- * Configures the global remix converter.
- * `num_channels` must be less than `CRAS_MAX_REMIX_CHANNELS`.
- */
-struct __attribute__((__packed__)) cras_config_global_remix {
- struct cras_server_message header;
- unsigned int num_channels;
- float coefficient[CRAS_MAX_REMIX_CHANNELS * CRAS_MAX_REMIX_CHANNELS];
-};
-
-static inline void
-cras_fill_config_global_remix_command(struct cras_config_global_remix *m,
- unsigned int num_channels, float *coeff,
- unsigned int count)
-{
- m->header.id = CRAS_CONFIG_GLOBAL_REMIX;
- m->header.length = sizeof(*m) + count * sizeof(*coeff);
- m->num_channels = num_channels;
- memcpy(m->coefficient, coeff, count * sizeof(*coeff));
-}
-
-/* Get supported hotword models. */
-struct __attribute__((__packed__)) cras_get_hotword_models {
- struct cras_server_message header;
- cras_node_id_t node_id;
-};
-
-static inline void
-cras_fill_get_hotword_models_message(struct cras_get_hotword_models *m,
- cras_node_id_t node_id)
-{
- m->header.id = CRAS_SERVER_GET_HOTWORD_MODELS;
- m->header.length = sizeof(*m);
- m->node_id = node_id;
-}
-
-/* Set desired hotword model. */
-struct __attribute__((__packed__)) cras_set_hotword_model {
- struct cras_server_message header;
- cras_node_id_t node_id;
- char model_name[CRAS_MAX_HOTWORD_MODEL_NAME_SIZE];
-};
-
-static inline void
-cras_fill_set_hotword_model_message(struct cras_set_hotword_model *m,
- cras_node_id_t node_id,
- const char *model_name)
-{
- m->header.id = CRAS_SERVER_SET_HOTWORD_MODEL;
- m->header.length = sizeof(*m);
- m->node_id = node_id;
- memcpy(m->model_name, model_name, CRAS_MAX_HOTWORD_MODEL_NAME_SIZE);
-}
-
-/* Set aec dump to start or stop. */
-struct __attribute__((__packed__)) cras_set_aec_dump {
- struct cras_server_message header;
- cras_stream_id_t stream_id;
- unsigned int start;
-};
-
-static inline void cras_fill_set_aec_dump_message(struct cras_set_aec_dump *m,
- cras_stream_id_t stream_id,
- unsigned int start)
-{
- m->header.id = CRAS_SERVER_SET_AEC_DUMP;
- m->header.length = sizeof(*m);
- m->stream_id = stream_id;
- m->start = start;
-}
-
-/* Reload the aec configuration. */
-struct __attribute__((__packed__)) cras_reload_aec_config {
- struct cras_server_message header;
-};
-static inline void cras_fill_reload_aec_config(struct cras_reload_aec_config *m)
-{
- m->header.id = CRAS_SERVER_RELOAD_AEC_CONFIG;
- m->header.length = sizeof(*m);
-}
-
-/* Sets the flag to enable or disable bluetooth wideband speech feature. */
-struct __attribute__((__packed__)) cras_set_bt_wbs_enabled {
- struct cras_server_message header;
- unsigned int enabled;
-};
-static inline void
-cras_fill_set_bt_wbs_enabled(struct cras_set_bt_wbs_enabled *m,
- unsigned int enabled)
-{
- m->header.id = CRAS_SERVER_SET_BT_WBS_ENABLED;
- m->header.length = sizeof(*m);
- m->enabled = enabled;
-}
-
-struct __attribute__((__packed__)) cras_register_notification {
- struct cras_server_message header;
- uint32_t msg_id;
- int do_register;
-};
-static inline void
-cras_fill_register_notification_message(struct cras_register_notification *m,
- enum CRAS_CLIENT_MESSAGE_ID msg_id,
- int do_register)
-{
- m->header.id = CRAS_SERVER_REGISTER_NOTIFICATION;
- m->header.length = sizeof(*m);
- m->msg_id = msg_id;
- m->do_register = do_register;
-}
-
-/*
- * Messages sent from server to client.
- */
-
-/* Reply from the server indicating that the client has connected. */
-struct __attribute__((__packed__)) cras_client_connected {
- struct cras_client_message header;
- uint32_t client_id;
-};
-static inline void cras_fill_client_connected(struct cras_client_connected *m,
- size_t client_id)
-{
- m->client_id = client_id;
- m->header.id = CRAS_CLIENT_CONNECTED;
- m->header.length = sizeof(struct cras_client_connected);
-}
-
-/*
- * Reply from server that a stream has been successfully added.
- * Two file descriptors are added, input shm followed by out shm.
- *
- * |samples_shm_size| is valid for normal streams, not client-provided
- * shm streams.
- */
-struct __attribute__((__packed__)) cras_client_stream_connected {
- struct cras_client_message header;
- int32_t err;
- cras_stream_id_t stream_id;
- struct cras_audio_format_packed format;
- uint32_t samples_shm_size;
- uint64_t effects;
-};
-
-static inline void
-cras_fill_client_stream_connected(struct cras_client_stream_connected *m,
- int err, cras_stream_id_t stream_id,
- struct cras_audio_format *format,
- size_t samples_shm_size, uint64_t effects)
-{
- m->err = err;
- m->stream_id = stream_id;
- pack_cras_audio_format(&m->format, format);
- if (samples_shm_size > UINT32_MAX) {
- samples_shm_size = UINT32_MAX;
- }
- m->samples_shm_size = samples_shm_size;
- m->effects = effects;
- m->header.id = CRAS_CLIENT_STREAM_CONNECTED;
- m->header.length = sizeof(struct cras_client_stream_connected);
-}
-
-/* Sent from server to client when audio debug information is requested. */
-struct __attribute__((__packed__)) cras_client_audio_debug_info_ready {
- struct cras_client_message header;
-};
-static inline void cras_fill_client_audio_debug_info_ready(
- struct cras_client_audio_debug_info_ready *m)
-{
- m->header.id = CRAS_CLIENT_AUDIO_DEBUG_INFO_READY;
- m->header.length = sizeof(*m);
-}
-
-struct __attribute__((__packed__)) cras_client_atlog_fd_ready {
- struct cras_client_message header;
-};
-
-static inline void
-cras_fill_client_atlog_fd_ready(struct cras_client_atlog_fd_ready *m)
-{
- m->header.id = CRAS_CLIENT_ATLOG_FD_READY;
- m->header.length = sizeof(*m);
-}
-
-/* Sent from server to client when hotword models info is ready. */
-struct __attribute__((__packed__)) cras_client_get_hotword_models_ready {
- struct cras_client_message header;
- int32_t hotword_models_size;
- uint8_t hotword_models[CRAS_MAX_HOTWORD_MODELS + 1];
-};
-static inline void cras_fill_client_get_hotword_models_ready(
- struct cras_client_get_hotword_models_ready *m,
- const char *hotword_models, size_t hotword_models_size)
-{
- m->header.id = CRAS_CLIENT_GET_HOTWORD_MODELS_READY;
- m->header.length = sizeof(*m);
- m->hotword_models_size = hotword_models_size;
- /* Copy string data with terminator. */
- if (hotword_models) {
- strncpy((char *)m->hotword_models, hotword_models,
- CRAS_MAX_HOTWORD_MODELS);
- m->hotword_models[CRAS_MAX_HOTWORD_MODELS] = '\0';
- }
-}
-
-/* System status messages sent from server to client when state changes. */
-struct __attribute__((__packed__)) cras_client_volume_changed {
- struct cras_client_message header;
- int32_t volume;
-};
-static inline void
-cras_fill_client_output_volume_changed(struct cras_client_volume_changed *m,
- int32_t volume)
-{
- m->header.id = CRAS_CLIENT_OUTPUT_VOLUME_CHANGED;
- m->header.length = sizeof(*m);
- m->volume = volume;
-}
-static inline void
-cras_fill_client_capture_gain_changed(struct cras_client_volume_changed *m,
- int32_t gain)
-{
- m->header.id = CRAS_CLIENT_CAPTURE_GAIN_CHANGED;
- m->header.length = sizeof(*m);
- m->volume = gain;
-}
-
-struct __attribute__((__packed__)) cras_client_mute_changed {
- struct cras_client_message header;
- int32_t muted;
- int32_t user_muted;
- int32_t mute_locked;
-};
-static inline void
-cras_fill_client_output_mute_changed(struct cras_client_mute_changed *m,
- int32_t muted, int32_t user_muted,
- int32_t mute_locked)
-{
- m->header.id = CRAS_CLIENT_OUTPUT_MUTE_CHANGED;
- m->header.length = sizeof(*m);
- m->muted = muted;
- m->user_muted = user_muted;
- m->mute_locked = mute_locked;
-}
-static inline void
-cras_fill_client_capture_mute_changed(struct cras_client_mute_changed *m,
- int32_t muted, int32_t mute_locked)
-{
- m->header.id = CRAS_CLIENT_CAPTURE_MUTE_CHANGED;
- m->header.length = sizeof(*m);
- m->muted = muted;
- m->user_muted = 0;
- m->mute_locked = mute_locked;
-}
-
-struct __attribute__((__packed__)) cras_client_nodes_changed {
- struct cras_client_message header;
-};
-static inline void
-cras_fill_client_nodes_changed(struct cras_client_nodes_changed *m)
-{
- m->header.id = CRAS_CLIENT_NODES_CHANGED;
- m->header.length = sizeof(*m);
-}
-
-struct __attribute__((__packed__)) cras_client_active_node_changed {
- struct cras_client_message header;
- uint32_t direction;
- cras_node_id_t node_id;
-};
-static inline void
-cras_fill_client_active_node_changed(struct cras_client_active_node_changed *m,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- m->header.id = CRAS_CLIENT_ACTIVE_NODE_CHANGED;
- m->header.length = sizeof(*m);
- m->direction = direction;
- m->node_id = node_id;
-};
-
-struct __attribute__((__packed__)) cras_client_node_value_changed {
- struct cras_client_message header;
- cras_node_id_t node_id;
- int32_t value;
-};
-static inline void cras_fill_client_output_node_volume_changed(
- struct cras_client_node_value_changed *m, cras_node_id_t node_id,
- int32_t volume)
-{
- m->header.id = CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED;
- m->header.length = sizeof(*m);
- m->node_id = node_id;
- m->value = volume;
-};
-static inline void cras_fill_client_node_left_right_swapped_changed(
- struct cras_client_node_value_changed *m, cras_node_id_t node_id,
- int swapped)
-{
- m->header.id = CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED;
- m->header.length = sizeof(*m);
- m->node_id = node_id;
- m->value = swapped;
-};
-static inline void cras_fill_client_input_node_gain_changed(
- struct cras_client_node_value_changed *m, cras_node_id_t node_id,
- int32_t gain)
-{
- m->header.id = CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED;
- m->header.length = sizeof(*m);
- m->node_id = node_id;
- m->value = gain;
-};
-
-struct __attribute__((__packed__)) cras_client_num_active_streams_changed {
- struct cras_client_message header;
- uint32_t direction;
- uint32_t num_active_streams;
-};
-static inline void cras_fill_client_num_active_streams_changed(
- struct cras_client_num_active_streams_changed *m,
- enum CRAS_STREAM_DIRECTION direction, uint32_t num_active_streams)
-{
- m->header.id = CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED;
- m->header.length = sizeof(*m);
- m->direction = direction;
- m->num_active_streams = num_active_streams;
-};
-
-/*
- * Messages specific to passing audio between client and server
- */
-enum CRAS_AUDIO_MESSAGE_ID {
- AUDIO_MESSAGE_REQUEST_DATA,
- AUDIO_MESSAGE_DATA_READY,
- AUDIO_MESSAGE_DATA_CAPTURED,
- NUM_AUDIO_MESSAGES
-};
-
-struct __attribute__((__packed__)) audio_message {
- enum CRAS_AUDIO_MESSAGE_ID id;
- int32_t error;
- uint32_t frames; /* number of samples per channel */
-};
-
-#endif /* CRAS_MESSAGES_H_ */
diff --git a/cras/src/common/cras_metrics.c b/cras/src/common/cras_metrics.c
deleted file mode 100644
index b318fb44..00000000
--- a/cras/src/common/cras_metrics.c
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <syslog.h>
-#include <unistd.h>
-
-#ifdef HAVE_LIB_METRICS
-#include <metrics/c_metrics_library.h>
-
-void cras_metrics_log_event(const char *event)
-{
- CMetricsLibrary handle;
-
- syslog(LOG_DEBUG, "UMA event: %s", event);
- handle = CMetricsLibraryNew();
- CMetricsLibrarySendCrosEventToUMA(handle, event);
- CMetricsLibraryDelete(handle);
-}
-
-void cras_metrics_log_histogram(const char *name, int sample, int min, int max,
- int nbuckets)
-{
- CMetricsLibrary handle;
-
- syslog(LOG_DEBUG, "UMA name: %s", name);
- handle = CMetricsLibraryNew();
- CMetricsLibrarySendToUMA(handle, name, sample, min, max, nbuckets);
- CMetricsLibraryDelete(handle);
-}
-
-void cras_metrics_log_sparse_histogram(const char *name, int sample)
-{
- CMetricsLibrary handle;
-
- syslog(LOG_DEBUG, "UMA name: %s", name);
- handle = CMetricsLibraryNew();
- CMetricsLibrarySendSparseToUMA(handle, name, sample);
- CMetricsLibraryDelete(handle);
-}
-
-#else
-void cras_metrics_log_event(const char *event)
-{
-}
-void cras_metrics_log_histogram(const char *name, int sample, int min, int max,
- int nbuckets)
-{
-}
-void cras_metrics_log_enum_histogram(const char *name, int sample, int max)
-{
-}
-void cras_metrics_log_sparse_histogram(const char *name, int sample)
-{
-}
-#endif
diff --git a/cras/src/common/cras_metrics.h b/cras/src/common/cras_metrics.h
deleted file mode 100644
index 814b3dde..00000000
--- a/cras/src/common/cras_metrics.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_METRICS_H_
-#define CRAS_METRICS_H_
-
-/* Logs the specified event. */
-void cras_metrics_log_event(const char *event);
-
-/* Sends histogram data. */
-void cras_metrics_log_histogram(const char *name, int sample, int min, int max,
- int nbuckets);
-
-/* Sends sparse histogram data. */
-void cras_metrics_log_sparse_histogram(const char *name, int sample);
-
-#endif /* CRAS_METRICS_H_ */
diff --git a/cras/src/common/cras_observer_ops.h b/cras/src/common/cras_observer_ops.h
deleted file mode 100644
index e73845c9..00000000
--- a/cras/src/common/cras_observer_ops.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_OBSERVER_OPS_H
-#define CRAS_OBSERVER_OPS_H
-
-#include "cras_types.h"
-
-/* Observation of CRAS state.
- * Unless otherwise specified, all notifications only contain the data value
- * reflecting the current state: it is possible that multiple notifications
- * are queued within CRAS before being sent to the client.
- */
-struct cras_observer_ops {
- /* System output volume changed. */
- void (*output_volume_changed)(void *context, int32_t volume);
- /* System output mute changed. */
- void (*output_mute_changed)(void *context, int muted, int user_muted,
- int mute_locked);
- /* System input/capture gain changed. */
- void (*capture_gain_changed)(void *context, int32_t gain);
- /* System input/capture mute changed. */
- void (*capture_mute_changed)(void *context, int muted, int mute_locked);
- /* Device or node topology changed. */
- void (*nodes_changed)(void *context);
- /* Active node changed. A notification is sent for every change.
- * When there is no active node, node_id is 0. */
- void (*active_node_changed)(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id);
- /* Output node volume changed. */
- void (*output_node_volume_changed)(void *context,
- cras_node_id_t node_id,
- int32_t volume);
- /* Node left/right swapped state change. */
- void (*node_left_right_swapped_changed)(void *context,
- cras_node_id_t node_id,
- int swapped);
- /* Input gain changed. */
- void (*input_node_gain_changed)(void *context, cras_node_id_t node_id,
- int32_t gain);
- /* Suspend state changed. */
- void (*suspend_changed)(void *context, int suspended);
- /* Number of active streams changed. */
- void (*num_active_streams_changed)(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams);
- /* Number of input streams with permission changed. */
- void (*num_input_streams_with_permission_changed)(
- void *context,
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE]);
- /* Hotword triggered. */
- void (*hotword_triggered)(void *context, int64_t tv_sec,
- int64_t tv_nsec);
- /* State regarding whether non-empty audio is being played/captured has
- * changed. */
- void (*non_empty_audio_state_changed)(void *context, int non_empty);
- /* Bluetooth headset battery level changed. */
- void (*bt_battery_changed)(void *context, const char *address,
- uint32_t level);
-};
-
-#endif /* CRAS_OBSERVER_OPS_H */
diff --git a/cras/src/common/cras_sbc_codec.c b/cras/src/common/cras_sbc_codec.c
deleted file mode 100644
index df02b3eb..00000000
--- a/cras/src/common/cras_sbc_codec.c
+++ /dev/null
@@ -1,201 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <sbc/sbc.h>
-#include <stdlib.h>
-
-#include "cras_sbc_codec.h"
-
-/* SBC library encodes one PCM input block to one SBC output block. This
- * structure holds related info about the SBC codec.
- * Members:
- * sbc - The main structure for SBC codec.
- * codesize - The size of one PCM input block in bytes.
- * frame_length - The size of one SBC output block in bytes.
- */
-struct cras_sbc_data {
- sbc_t sbc;
- unsigned int codesize;
- unsigned int frame_length;
-};
-
-int cras_msbc_decode(struct cras_audio_codec *codec, const void *input,
- size_t input_len, void *output, size_t output_len,
- size_t *count)
-{
- struct cras_sbc_data *data = (struct cras_sbc_data *)codec->priv_data;
- size_t written = 0;
- ssize_t decoded;
-
- /*
- * Proceed decode when there is buffer left in input and room in
- * output.
- */
- decoded = sbc_decode(&data->sbc, input, input_len, output, output_len,
- &written);
-
- *count = written;
- return decoded;
-}
-
-int cras_msbc_encode(struct cras_audio_codec *codec, const void *input,
- size_t input_len, void *output, size_t output_len,
- size_t *count)
-{
- struct cras_sbc_data *data = (struct cras_sbc_data *)codec->priv_data;
- ssize_t written = 0;
- ssize_t encoded;
-
- /*
- * Proceed encode when input buffer has at least one input block and
- * there is still room in output buffer.
- */
- if (input_len < data->codesize)
- return -EINVAL;
-
- encoded = sbc_encode(&data->sbc, input, data->codesize, output,
- output_len, &written);
-
- *count = written;
- return encoded;
-}
-
-int cras_sbc_decode(struct cras_audio_codec *codec, const void *input,
- size_t input_len, void *output, size_t output_len,
- size_t *count)
-{
- struct cras_sbc_data *data = (struct cras_sbc_data *)codec->priv_data;
- size_t written;
- ssize_t decoded;
- int processed = 0;
- int result = 0;
-
- /* Proceed decode when there is buffer left in input and room in
- * output.
- */
- while (input_len > processed && output_len > result) {
- decoded = sbc_decode(&data->sbc, input + processed,
- input_len - processed, output + result,
- output_len - result, &written);
- if (decoded <= 0)
- break;
-
- processed += decoded;
- result += written;
- }
- *count = result;
- return processed;
-}
-
-int cras_sbc_encode(struct cras_audio_codec *codec, const void *input,
- size_t input_len, void *output, size_t output_len,
- size_t *count)
-{
- struct cras_sbc_data *data = (struct cras_sbc_data *)codec->priv_data;
- ssize_t written, encoded;
- int processed = 0, result = 0;
-
- /* Proceed encode when input buffer has at least one input block and
- * there is still room in output buffer.
- */
- while (input_len - processed >= data->codesize &&
- output_len >= result) {
- encoded = sbc_encode(&data->sbc, input + processed,
- data->codesize, output + result,
- output_len - result, &written);
- if (encoded == -ENOSPC)
- break;
- else if (encoded < 0)
- return encoded;
-
- processed += encoded;
- result += written;
- }
- *count = result;
- return processed;
-}
-
-int cras_sbc_get_codesize(struct cras_audio_codec *codec)
-{
- struct cras_sbc_data *data = (struct cras_sbc_data *)codec->priv_data;
- return data->codesize;
-}
-
-int cras_sbc_get_frame_length(struct cras_audio_codec *codec)
-{
- struct cras_sbc_data *data = (struct cras_sbc_data *)codec->priv_data;
- return data->frame_length;
-}
-
-struct cras_audio_codec *cras_msbc_codec_create()
-{
- struct cras_audio_codec *codec;
- struct cras_sbc_data *data;
-
- codec = (struct cras_audio_codec *)calloc(1, sizeof(*codec));
- if (!codec)
- return NULL;
-
- codec->priv_data =
- (struct cras_sbc_data *)calloc(1, sizeof(struct cras_sbc_data));
- if (!codec->priv_data) {
- free(codec);
- return NULL;
- }
-
- data = (struct cras_sbc_data *)codec->priv_data;
- sbc_init_msbc(&data->sbc, 0L);
- data->codesize = sbc_get_codesize(&data->sbc);
- data->frame_length = sbc_get_frame_length(&data->sbc);
-
- codec->decode = cras_msbc_decode;
- codec->encode = cras_msbc_encode;
- return codec;
-}
-
-struct cras_audio_codec *cras_sbc_codec_create(uint8_t freq, uint8_t mode,
- uint8_t subbands, uint8_t alloc,
- uint8_t blocks, uint8_t bitpool)
-{
- struct cras_audio_codec *codec;
- struct cras_sbc_data *data;
-
- codec = (struct cras_audio_codec *)calloc(1, sizeof(*codec));
- if (!codec)
- return NULL;
-
- codec->priv_data =
- (struct cras_sbc_data *)calloc(1, sizeof(struct cras_sbc_data));
- if (!codec->priv_data)
- goto create_error;
-
- data = (struct cras_sbc_data *)codec->priv_data;
- sbc_init(&data->sbc, 0L);
- data->sbc.endian = SBC_LE;
- data->sbc.frequency = freq;
- data->sbc.mode = mode;
- data->sbc.subbands = subbands;
- data->sbc.allocation = alloc;
- data->sbc.blocks = blocks;
- data->sbc.bitpool = bitpool;
- data->codesize = sbc_get_codesize(&data->sbc);
- data->frame_length = sbc_get_frame_length(&data->sbc);
-
- codec->decode = cras_sbc_decode;
- codec->encode = cras_sbc_encode;
- return codec;
-
-create_error:
- free(codec);
- return NULL;
-}
-
-void cras_sbc_codec_destroy(struct cras_audio_codec *codec)
-{
- sbc_finish(&((struct cras_sbc_data *)codec->priv_data)->sbc);
- free(codec->priv_data);
- free(codec);
-}
diff --git a/cras/src/common/cras_sbc_codec.h b/cras/src/common/cras_sbc_codec.h
deleted file mode 100644
index 322c45b6..00000000
--- a/cras/src/common/cras_sbc_codec.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef COMMON_CRAS_SBC_CODEC_H_
-#define COMMON_CRAS_SBC_CODEC_H_
-
-#include <sbc/sbc.h>
-
-#include "cras_audio_codec.h"
-
-/* Creates an sbc codec.
- * Args:
- * freq: frequency for sbc encoder settings.
- * mode: mode for sbc encoder settings.
- * subbands: subbands for sbc encoder settings.
- * alloc: allocation method for sbc encoder settings.
- * blocks: blocks for sbc encoder settings.
- * bitpool: bitpool for sbc encoder settings.
- */
-struct cras_audio_codec *cras_sbc_codec_create(uint8_t freq, uint8_t mode,
- uint8_t subbands, uint8_t alloc,
- uint8_t blocks, uint8_t bitpool);
-
-/* Creates an mSBC codec, which is a version of SBC codec used for
- * wideband speech mode of HFP. */
-struct cras_audio_codec *cras_msbc_codec_create();
-
-/* Destroys an sbc codec.
- * Args:
- * codec: the codec to destroy.
- */
-void cras_sbc_codec_destroy(struct cras_audio_codec *codec);
-
-/* Gets codesize, the input block size of sbc codec in bytes.
- */
-int cras_sbc_get_codesize(struct cras_audio_codec *codec);
-
-/* Gets frame_length, the output block size of sbc codec in bytes.
- */
-int cras_sbc_get_frame_length(struct cras_audio_codec *codec);
-
-#endif /* COMMON_CRAS_SBC_CODEC_H_ */
diff --git a/cras/src/common/cras_selinux_helper.c b/cras/src/common/cras_selinux_helper.c
deleted file mode 100644
index ddacc6a8..00000000
--- a/cras/src/common/cras_selinux_helper.c
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2018 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <selinux/restorecon.h>
-
-#include "cras_shm.h"
-
-int cras_selinux_restorecon(const char *pathname)
-{
- return selinux_restorecon(pathname, 0);
-}
diff --git a/cras/src/common/cras_shm.c b/cras/src/common/cras_shm.c
deleted file mode 100644
index ecb6169c..00000000
--- a/cras/src/common/cras_shm.c
+++ /dev/null
@@ -1,309 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <sys/cdefs.h>
-#include <sys/mman.h>
-#ifdef __BIONIC__
-#include <cutils/ashmem.h>
-#else
-#include <sys/shm.h>
-#endif
-#include <errno.h>
-#include <syslog.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "cras_shm.h"
-
-int cras_shm_info_init(const char *stream_name, uint32_t length,
- struct cras_shm_info *info_out)
-{
- struct cras_shm_info info;
-
- if (!info_out)
- return -EINVAL;
-
- strncpy(info.name, stream_name, sizeof(info.name) - 1);
- info.name[sizeof(info.name) - 1] = '\0';
- info.length = length;
- info.fd = cras_shm_open_rw(info.name, info.length);
- if (info.fd < 0)
- return info.fd;
-
- *info_out = info;
-
- return 0;
-}
-
-int cras_shm_info_init_with_fd(int fd, size_t length,
- struct cras_shm_info *info_out)
-{
- struct cras_shm_info info;
-
- if (!info_out)
- return -EINVAL;
-
- info.name[0] = '\0';
- info.length = length;
- info.fd = dup(fd);
- if (info.fd < 0)
- return info.fd;
-
- *info_out = info;
-
- return 0;
-}
-
-/* Move the resources from the cras_shm_info 'from' into the cras_shm_info 'to'.
- * The owner of 'to' will be responsible for cleaning up those resources with
- * cras_shm_info_cleanup.
- */
-static int cras_shm_info_move(struct cras_shm_info *from,
- struct cras_shm_info *to)
-{
- if (!from || !to)
- return -EINVAL;
-
- *to = *from;
- from->fd = -1;
- from->name[0] = '\0';
- return 0;
-}
-
-void cras_shm_info_cleanup(struct cras_shm_info *info)
-{
- if (!info)
- return;
-
- if (info->name[0] != '\0')
- cras_shm_close_unlink(info->name, info->fd);
- else
- close(info->fd);
-
- info->fd = -1;
- info->name[0] = '\0';
-}
-
-int cras_audio_shm_create(struct cras_shm_info *header_info,
- struct cras_shm_info *samples_info, int samples_prot,
- struct cras_audio_shm **shm_out)
-{
- struct cras_audio_shm *shm;
- int ret;
-
- if (!header_info || !samples_info || !shm_out) {
- ret = -EINVAL;
- goto cleanup_info;
- }
-
- if (samples_prot != PROT_READ && samples_prot != PROT_WRITE) {
- ret = -EINVAL;
- syslog(LOG_ERR,
- "cras_shm: samples must be mapped read or write only");
- goto cleanup_info;
- }
-
- shm = calloc(1, sizeof(*shm));
- if (!shm) {
- ret = -ENOMEM;
- goto cleanup_info;
- }
-
- /* Move the cras_shm_info params into the new cras_audio_shm object.
- * The parameters are cleared, and the owner of cras_audio_shm is now
- * responsible for closing the fds and unlinking any associated shm
- * files using cras_audio_shm_destroy.
- */
- ret = cras_shm_info_move(header_info, &shm->header_info);
- if (ret)
- goto free_shm;
-
- ret = cras_shm_info_move(samples_info, &shm->samples_info);
- if (ret)
- goto free_shm;
-
- shm->header =
- mmap(NULL, shm->header_info.length, PROT_READ | PROT_WRITE,
- MAP_SHARED, shm->header_info.fd, 0);
- if (shm->header == (struct cras_audio_shm_header *)-1) {
- ret = -errno;
- syslog(LOG_ERR, "cras_shm: mmap failed to map shm for header.");
- goto free_shm;
- }
-
- shm->samples = mmap(NULL, shm->samples_info.length, samples_prot,
- MAP_SHARED, shm->samples_info.fd, 0);
- if (shm->samples == (uint8_t *)-1) {
- ret = -errno;
- syslog(LOG_ERR,
- "cras_shm: mmap failed to map shm for samples.");
- goto free_shm;
- }
-
- cras_shm_set_volume_scaler(shm, 1.0);
-
- *shm_out = shm;
- return 0;
-
-free_shm:
- cras_audio_shm_destroy(shm);
-cleanup_info:
- cras_shm_info_cleanup(samples_info);
- cras_shm_info_cleanup(header_info);
- return ret;
-}
-
-void cras_audio_shm_destroy(struct cras_audio_shm *shm)
-{
- if (!shm)
- return;
-
- if (shm->samples != NULL && shm->samples != (uint8_t *)-1)
- munmap(shm->samples, shm->samples_info.length);
- cras_shm_info_cleanup(&shm->samples_info);
- if (shm->header != NULL &&
- shm->header != (struct cras_audio_shm_header *)-1)
- munmap(shm->header, shm->header_info.length);
- cras_shm_info_cleanup(&shm->header_info);
- free(shm);
-}
-
-/* Set the correct SELinux label for SHM fds. */
-static void cras_shm_restorecon(int fd)
-{
-#ifdef CRAS_SELINUX
- char fd_proc_path[64];
-
- if (snprintf(fd_proc_path, sizeof(fd_proc_path), "/proc/self/fd/%d",
- fd) < 0) {
- syslog(LOG_WARNING,
- "Couldn't construct proc symlink path of fd: %d", fd);
- return;
- }
-
- /* Get the actual file-path for this fd. */
- char *path = realpath(fd_proc_path, NULL);
- if (path == NULL) {
- syslog(LOG_WARNING, "Couldn't run realpath() for %s: %s",
- fd_proc_path, strerror(errno));
- return;
- }
-
- if (cras_selinux_restorecon(path) < 0) {
- syslog(LOG_WARNING, "Restorecon on %s failed: %s", fd_proc_path,
- strerror(errno));
- }
-
- free(path);
-#endif
-}
-
-#ifdef __BIONIC__
-
-int cras_shm_open_rw(const char *name, size_t size)
-{
- int fd;
-
- /* Eliminate the / in the shm_name. */
- if (name[0] == '/')
- name++;
- fd = ashmem_create_region(name, size);
- if (fd < 0) {
- fd = -errno;
- syslog(LOG_ERR, "failed to ashmem_create_region %s: %s\n", name,
- strerror(-fd));
- }
- return fd;
-}
-
-int cras_shm_reopen_ro(const char *name, int fd)
-{
- /* After mmaping the ashmem read/write, change it's protection
- bits to disallow further write access. */
- if (ashmem_set_prot_region(fd, PROT_READ) != 0) {
- fd = -errno;
- syslog(LOG_ERR, "failed to ashmem_set_prot_region %s: %s\n",
- name, strerror(-fd));
- }
- return fd;
-}
-
-void cras_shm_close_unlink(const char *name, int fd)
-{
- close(fd);
-}
-
-#else
-
-int cras_shm_open_rw(const char *name, size_t size)
-{
- int fd;
- int rc;
-
- fd = shm_open(name, O_CREAT | O_EXCL | O_RDWR, 0600);
- if (fd < 0) {
- fd = -errno;
- syslog(LOG_ERR, "failed to shm_open %s: %s\n", name,
- strerror(-fd));
- return fd;
- }
- rc = posix_fallocate(fd, 0, size);
- if (rc) {
- rc = -errno;
- syslog(LOG_ERR, "failed to set size of shm %s: %s\n", name,
- strerror(-rc));
- return rc;
- }
-
- cras_shm_restorecon(fd);
-
- return fd;
-}
-
-int cras_shm_reopen_ro(const char *name, int fd)
-{
- /* Open a read-only copy to dup and pass to clients. */
- fd = shm_open(name, O_RDONLY, 0);
- if (fd < 0) {
- fd = -errno;
- syslog(LOG_ERR,
- "Failed to re-open shared memory '%s' read-only: %s",
- name, strerror(-fd));
- }
- return fd;
-}
-
-void cras_shm_close_unlink(const char *name, int fd)
-{
- shm_unlink(name);
- close(fd);
-}
-
-#endif
-
-void *cras_shm_setup(const char *name, size_t mmap_size, int *rw_fd_out,
- int *ro_fd_out)
-{
- int rw_shm_fd = cras_shm_open_rw(name, mmap_size);
- if (rw_shm_fd < 0)
- return NULL;
-
- /* mmap shm. */
- void *exp_state = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE,
- MAP_SHARED, rw_shm_fd, 0);
- if (exp_state == (void *)-1)
- return NULL;
-
- /* Open a read-only copy to dup and pass to clients. */
- int ro_shm_fd = cras_shm_reopen_ro(name, rw_shm_fd);
- if (ro_shm_fd < 0)
- return NULL;
-
- *rw_fd_out = rw_shm_fd;
- *ro_fd_out = ro_shm_fd;
-
- return exp_state;
-}
diff --git a/cras/src/common/cras_shm.h b/cras/src/common/cras_shm.h
deleted file mode 100644
index 47786c3b..00000000
--- a/cras/src/common/cras_shm.h
+++ /dev/null
@@ -1,659 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_SHM_H_
-#define CRAS_SHM_H_
-
-#include <assert.h>
-#include <stdint.h>
-#include <sys/mman.h>
-#include <sys/param.h>
-
-#include "cras_types.h"
-#include "cras_util.h"
-
-#define CRAS_NUM_SHM_BUFFERS 2U /* double buffer */
-#define CRAS_SHM_BUFFERS_MASK (CRAS_NUM_SHM_BUFFERS - 1)
-
-/* Configuration of the shm area.
- *
- * used_size - The size in bytes of the sample area being actively used.
- * frame_bytes - The size of each frame in bytes.
- */
-struct __attribute__((__packed__)) cras_audio_shm_config {
- uint32_t used_size;
- uint32_t frame_bytes;
-};
-
-/* Structure containing stream metadata shared between client and server.
- *
- * config - Size config data. A copy of the config shared with clients.
- * read_buf_idx - index of the current buffer to read from (0 or 1 if double
- * buffered).
- * write_buf_idx - index of the current buffer to write to (0 or 1 if double
- * buffered).
- * read_offset - offset of the next sample to read (one per buffer).
- * write_offset - offset of the next sample to write (one per buffer).
- * write_in_progress - non-zero when a write is in progress.
- * volume_scaler - volume scaling factor (0.0-1.0).
- * muted - bool, true if stream should be muted.
- * num_overruns - Starting at 0 this is incremented very time data is over
- * written because too much accumulated before a read.
- * ts - For capture, the time stamp of the next sample at read_index. For
- * playback, this is the time that the next sample written will be played.
- * This is only valid in audio callbacks.
- * buffer_offset - Offset of each buffer from start of samples area.
- * Valid range: 0 <= buffer_offset <= shm->samples_info.length
- */
-struct __attribute__((__packed__)) cras_audio_shm_header {
- struct cras_audio_shm_config config;
- uint32_t read_buf_idx; /* use buffer A or B */
- uint32_t write_buf_idx;
- uint32_t read_offset[CRAS_NUM_SHM_BUFFERS];
- uint32_t write_offset[CRAS_NUM_SHM_BUFFERS];
- int32_t write_in_progress[CRAS_NUM_SHM_BUFFERS];
- float volume_scaler;
- int32_t mute;
- int32_t callback_pending;
- uint32_t num_overruns;
- struct cras_timespec ts;
- uint64_t buffer_offset[CRAS_NUM_SHM_BUFFERS];
-};
-
-/* Returns the number of bytes needed to hold a cras_audio_shm_header. */
-static inline uint32_t cras_shm_header_size()
-{
- return sizeof(struct cras_audio_shm_header);
-}
-
-/* Returns the number of bytes needed to hold the samples area for an audio
- * shm with the given used_size */
-static inline uint32_t cras_shm_calculate_samples_size(uint32_t used_size)
-{
- return used_size * CRAS_NUM_SHM_BUFFERS;
-}
-
-/* Holds identifiers for a shm segment. All valid cras_shm_info objects will
- * have an fd and a length, and they may have the name of the shm file as well.
- *
- * fd - File descriptor to access shm (shared between client/server).
- * name - Name of the shm area. May be empty.
- * length - Size of the shm region.
- */
-struct cras_shm_info {
- int fd;
- char name[NAME_MAX];
- size_t length;
-};
-
-/* Initializes a cras_shm_info to be used as the backing shared memory for a
- * cras_audio_shm.
- *
- * shm_name - the name of the shm area to create.
- * length - the length of the shm area to create.
- * info_out - pointer where the created cras_shm_info will be stored.
- */
-int cras_shm_info_init(const char *shm_name, uint32_t length,
- struct cras_shm_info *info_out);
-
-/* Initializes a cras_shm_info to be used as the backing shared memory for a
- * cras_audio_shm.
- *
- * fd - file descriptor for the shm to be used. fd must be closed after
- * calling this function.
- * length - the size of the shm referenced by fd.
- * info_out - pointer where the created cras_shm_info will be stored.
- */
-int cras_shm_info_init_with_fd(int fd, size_t length,
- struct cras_shm_info *info_out);
-
-/* Cleans up the resources for a cras_shm_info returned from cras_shm_info_init.
- *
- * info - the cras_shm_info to cleanup.
- */
-void cras_shm_info_cleanup(struct cras_shm_info *info);
-
-/* Structure that holds the config for and a pointer to the audio shm header and
- * samples area.
- *
- * config - Size config data, kept separate so it can be checked.
- * header_info - fd, name, and length of shm containing header.
- * header - Shm region containing audio metadata
- * samples_info - fd, name, and length of shm containing samples.
- * samples - Shm region containing audio data.
- */
-struct cras_audio_shm {
- struct cras_audio_shm_config config;
- struct cras_shm_info header_info;
- struct cras_audio_shm_header *header;
- struct cras_shm_info samples_info;
- uint8_t *samples;
-};
-
-/* Sets up a cras_audio_shm given info about the shared memory to use
- *
- * header_info - the underlying shm area to use for the header. The shm
- * will be managed by the created cras_audio_shm object.
- * The header_info parameter will be returned to an uninitialized
- * state, and the client need not call cras_shm_info_destroy.
- * samples_info - the underlying shm area to use for the samples. The shm
- * will be managed by the created cras_audio_shm object.
- * The samples_info parameter will be returned to an
- * uninitialized state, and the client need not call
- * cras_shm_info_destroy.
- * samples_prot - the mapping protections to use when mapping samples. Allowed
- * values are PROT_READ or PROT_WRITE.
- * shm_out - pointer where the created cras_audio_shm will be stored.
- *
- * Returns 0 on success or a negative error code on failure.
- */
-int cras_audio_shm_create(struct cras_shm_info *header_info,
- struct cras_shm_info *samples_info, int samples_prot,
- struct cras_audio_shm **shm_out);
-
-/* Destroys a cras_audio_shm returned from cras_audio_shm_create.
- *
- * shm - the cras_audio_shm to destroy.
- */
-void cras_audio_shm_destroy(struct cras_audio_shm *shm);
-
-/* Limit a buffer offset to within the samples area size. */
-static inline unsigned
-cras_shm_get_checked_buffer_offset(const struct cras_audio_shm *shm,
- uint32_t buf_idx)
-{
- unsigned buffer_offset = shm->header->buffer_offset[buf_idx];
-
- /* Cap buffer_offset at the length of the samples area */
- return MIN(buffer_offset, shm->samples_info.length);
-}
-
-/* Get a pointer to the buffer at idx. */
-static inline uint8_t *cras_shm_buff_for_idx(const struct cras_audio_shm *shm,
- size_t idx)
-{
- assert_on_compile_is_power_of_2(CRAS_NUM_SHM_BUFFERS);
- idx = idx & CRAS_SHM_BUFFERS_MASK;
-
- return shm->samples + cras_shm_get_checked_buffer_offset(shm, idx);
-}
-
-/* Limit a read offset to within the buffer size. */
-static inline unsigned
-cras_shm_get_checked_read_offset(const struct cras_audio_shm *shm,
- uint32_t buf_idx)
-{
- unsigned buffer_offset =
- cras_shm_get_checked_buffer_offset(shm, buf_idx);
- unsigned read_offset = shm->header->read_offset[buf_idx];
-
- /* The read_offset is allowed to be the total size, indicating that the
- * buffer is full. If read pointer is invalid assume it is at the
- * beginning. */
- if (read_offset > shm->config.used_size)
- return 0;
- if (buffer_offset + read_offset > shm->samples_info.length)
- return 0;
- return read_offset;
-}
-
-/* Limit a write offset to within the buffer size. */
-static inline unsigned
-cras_shm_get_checked_write_offset(const struct cras_audio_shm *shm,
- uint32_t buf_idx)
-{
- unsigned write_offset = shm->header->write_offset[buf_idx];
- unsigned buffer_offset =
- cras_shm_get_checked_buffer_offset(shm, buf_idx);
-
- /* The write_offset is allowed to be the total size, indicating that the
- * buffer is full. If write pointer is past used size, assume it is at
- * used size. */
- write_offset = MIN(write_offset, shm->config.used_size);
-
- /* If the buffer offset plus the write offset overruns the samples area,
- * return the longest valid write_offset */
- if (buffer_offset + write_offset > shm->samples_info.length)
- return shm->samples_info.length - buffer_offset;
- return write_offset;
-}
-
-/* Get the number of frames readable in current read buffer */
-static inline unsigned
-cras_shm_get_curr_read_frames(const struct cras_audio_shm *shm)
-{
- unsigned buf_idx = shm->header->read_buf_idx & CRAS_SHM_BUFFERS_MASK;
- unsigned read_offset, write_offset;
-
- read_offset = cras_shm_get_checked_read_offset(shm, buf_idx);
- write_offset = cras_shm_get_checked_write_offset(shm, buf_idx);
-
- if (read_offset > write_offset)
- return 0;
- else
- return (write_offset - read_offset) / shm->config.frame_bytes;
-}
-
-/* Get the base of the current read buffer. */
-static inline uint8_t *
-cras_shm_get_read_buffer_base(const struct cras_audio_shm *shm)
-{
- unsigned i = shm->header->read_buf_idx & CRAS_SHM_BUFFERS_MASK;
- return cras_shm_buff_for_idx(shm, i);
-}
-
-/* Get the base of the current write buffer. */
-static inline uint8_t *
-cras_shm_get_write_buffer_base(const struct cras_audio_shm *shm)
-{
- unsigned i = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- return cras_shm_buff_for_idx(shm, i);
-}
-
-/* Get a pointer to the next buffer to write */
-static inline uint8_t *
-cras_shm_get_writeable_frames(const struct cras_audio_shm *shm,
- unsigned limit_frames, unsigned *frames)
-{
- unsigned buf_idx = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
- unsigned write_offset;
- const unsigned frame_bytes = shm->config.frame_bytes;
- unsigned written;
-
- write_offset = cras_shm_get_checked_write_offset(shm, buf_idx);
- written = write_offset / frame_bytes;
- if (frames) {
- if (limit_frames >= written)
- *frames = limit_frames - written;
- else
- *frames = 0;
- }
-
- return cras_shm_buff_for_idx(shm, buf_idx) + write_offset;
-}
-
-/* Get a pointer to the current read buffer plus an offset. The offset might be
- * in the next buffer. 'frames' is filled with the number of frames that can be
- * copied from the returned buffer.
- */
-static inline uint8_t *
-cras_shm_get_readable_frames(const struct cras_audio_shm *shm, size_t offset,
- size_t *frames)
-{
- unsigned buf_idx = shm->header->read_buf_idx & CRAS_SHM_BUFFERS_MASK;
- unsigned read_offset, write_offset, final_offset;
-
- assert(frames != NULL);
-
- read_offset = cras_shm_get_checked_read_offset(shm, buf_idx);
- write_offset = cras_shm_get_checked_write_offset(shm, buf_idx);
- final_offset = read_offset + offset * shm->config.frame_bytes;
- if (final_offset >= write_offset) {
- final_offset -= write_offset;
- assert_on_compile_is_power_of_2(CRAS_NUM_SHM_BUFFERS);
- buf_idx = (buf_idx + 1) & CRAS_SHM_BUFFERS_MASK;
- write_offset = cras_shm_get_checked_write_offset(shm, buf_idx);
- }
- if (final_offset >= write_offset) {
- /* Past end of samples. */
- *frames = 0;
- return NULL;
- }
- *frames = (write_offset - final_offset) / shm->config.frame_bytes;
- return cras_shm_buff_for_idx(shm, buf_idx) + final_offset;
-}
-
-/* How many bytes are queued? */
-static inline size_t cras_shm_get_bytes_queued(const struct cras_audio_shm *shm)
-{
- size_t total, i;
- const unsigned used_size = shm->config.used_size;
-
- total = 0;
- for (i = 0; i < CRAS_NUM_SHM_BUFFERS; i++) {
- unsigned read_offset, write_offset;
-
- read_offset = MIN(shm->header->read_offset[i], used_size);
- write_offset = MIN(shm->header->write_offset[i], used_size);
-
- if (write_offset > read_offset)
- total += write_offset - read_offset;
- }
- return total;
-}
-
-/* How many frames are queued? */
-static inline int cras_shm_get_frames(const struct cras_audio_shm *shm)
-{
- size_t bytes;
-
- bytes = cras_shm_get_bytes_queued(shm);
- if (bytes % shm->config.frame_bytes != 0)
- return -EIO;
- return bytes / shm->config.frame_bytes;
-}
-
-/* How many frames in the current buffer? */
-static inline size_t
-cras_shm_get_frames_in_curr_buffer(const struct cras_audio_shm *shm)
-{
- size_t buf_idx = shm->header->read_buf_idx & CRAS_SHM_BUFFERS_MASK;
- unsigned read_offset, write_offset;
- const unsigned used_size = shm->config.used_size;
-
- read_offset = MIN(shm->header->read_offset[buf_idx], used_size);
- write_offset = MIN(shm->header->write_offset[buf_idx], used_size);
-
- if (write_offset <= read_offset)
- return 0;
-
- return (write_offset - read_offset) / shm->config.frame_bytes;
-}
-
-/* Return 1 if there is an empty buffer in the list. */
-static inline int cras_shm_is_buffer_available(const struct cras_audio_shm *shm)
-{
- size_t buf_idx = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- return (shm->header->write_offset[buf_idx] == 0);
-}
-
-/* How many are available to be written? */
-static inline size_t
-cras_shm_get_num_writeable(const struct cras_audio_shm *shm)
-{
- /* Not allowed to write to a buffer twice. */
- if (!cras_shm_is_buffer_available(shm))
- return 0;
-
- return shm->config.used_size / shm->config.frame_bytes;
-}
-
-/* Flags an overrun if writing would cause one and reset the write offset.
- * Return 1 if overrun happens, otherwise return 0. */
-static inline int cras_shm_check_write_overrun(struct cras_audio_shm *shm)
-{
- int ret = 0;
- size_t write_buf_idx =
- shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- if (!shm->header->write_in_progress[write_buf_idx]) {
- unsigned int used_size = shm->config.used_size;
-
- if (shm->header->write_offset[write_buf_idx]) {
- shm->header->num_overruns++; /* Will over-write unread */
- ret = 1;
- }
-
- memset(cras_shm_buff_for_idx(shm, write_buf_idx), 0, used_size);
-
- shm->header->write_in_progress[write_buf_idx] = 1;
- shm->header->write_offset[write_buf_idx] = 0;
- }
- return ret;
-}
-
-/* Increment the write pointer for the current buffer. */
-static inline void cras_shm_buffer_written(struct cras_audio_shm *shm,
- size_t frames)
-{
- size_t buf_idx = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- if (frames == 0)
- return;
-
- shm->header->write_offset[buf_idx] += frames * shm->config.frame_bytes;
- shm->header->read_offset[buf_idx] = 0;
-}
-
-/* Returns the number of frames that have been written to the current buffer. */
-static inline unsigned int
-cras_shm_frames_written(const struct cras_audio_shm *shm)
-{
- size_t buf_idx = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- return shm->header->write_offset[buf_idx] / shm->config.frame_bytes;
-}
-
-/* Signals the writing to this buffer is complete and moves to the next one. */
-static inline void cras_shm_buffer_write_complete(struct cras_audio_shm *shm)
-{
- size_t buf_idx = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- shm->header->write_in_progress[buf_idx] = 0;
-
- assert_on_compile_is_power_of_2(CRAS_NUM_SHM_BUFFERS);
- buf_idx = (buf_idx + 1) & CRAS_SHM_BUFFERS_MASK;
- shm->header->write_buf_idx = buf_idx;
-}
-
-/* Set the write pointer for the current buffer and complete the write. */
-static inline void cras_shm_buffer_written_start(struct cras_audio_shm *shm,
- size_t frames)
-{
- size_t buf_idx = shm->header->write_buf_idx & CRAS_SHM_BUFFERS_MASK;
-
- shm->header->write_offset[buf_idx] = frames * shm->config.frame_bytes;
- shm->header->read_offset[buf_idx] = 0;
- cras_shm_buffer_write_complete(shm);
-}
-
-/* Increment the read pointer. If it goes past the write pointer for this
- * buffer, move to the next buffer. */
-static inline void cras_shm_buffer_read(struct cras_audio_shm *shm,
- size_t frames)
-{
- size_t buf_idx = shm->header->read_buf_idx & CRAS_SHM_BUFFERS_MASK;
- size_t remainder;
- struct cras_audio_shm_header *header = shm->header;
- struct cras_audio_shm_config *config = &shm->config;
-
- if (frames == 0)
- return;
-
- header->read_offset[buf_idx] += frames * config->frame_bytes;
- if (header->read_offset[buf_idx] >= header->write_offset[buf_idx]) {
- remainder = header->read_offset[buf_idx] -
- header->write_offset[buf_idx];
- header->read_offset[buf_idx] = 0;
- header->write_offset[buf_idx] = 0;
- assert_on_compile_is_power_of_2(CRAS_NUM_SHM_BUFFERS);
- buf_idx = (buf_idx + 1) & CRAS_SHM_BUFFERS_MASK;
- if (remainder < header->write_offset[buf_idx]) {
- header->read_offset[buf_idx] = remainder;
- } else if (remainder) {
- /* Read all of this buffer too. */
- header->write_offset[buf_idx] = 0;
- buf_idx = (buf_idx + 1) & CRAS_SHM_BUFFERS_MASK;
- }
- header->read_buf_idx = buf_idx;
- }
-}
-
-/* Read from the current buffer. This is similar to cras_shm_buffer_read(), but
- * it doesn't check for the case we may read from two buffers. */
-static inline void cras_shm_buffer_read_current(struct cras_audio_shm *shm,
- size_t frames)
-{
- size_t buf_idx = shm->header->read_buf_idx & CRAS_SHM_BUFFERS_MASK;
- struct cras_audio_shm_header *header = shm->header;
- struct cras_audio_shm_config *config = &shm->config;
-
- header->read_offset[buf_idx] += frames * config->frame_bytes;
- if (header->read_offset[buf_idx] >= header->write_offset[buf_idx]) {
- header->read_offset[buf_idx] = 0;
- header->write_offset[buf_idx] = 0;
- buf_idx = (buf_idx + 1) & CRAS_SHM_BUFFERS_MASK;
- header->read_buf_idx = buf_idx;
- }
-}
-
-/* Sets the volume for the stream. The volume level is a scaling factor that
- * will be applied to the stream before mixing. */
-static inline void cras_shm_set_volume_scaler(struct cras_audio_shm *shm,
- float volume_scaler)
-{
- volume_scaler = MAX(volume_scaler, 0.0);
- shm->header->volume_scaler = MIN(volume_scaler, 1.0);
-}
-
-/* Returns the volume of the stream(0.0-1.0). */
-static inline float cras_shm_get_volume_scaler(const struct cras_audio_shm *shm)
-{
- return shm->header->volume_scaler;
-}
-
-/* Indicates that the stream should be muted/unmuted */
-static inline void cras_shm_set_mute(struct cras_audio_shm *shm, size_t mute)
-{
- shm->header->mute = !!mute;
-}
-
-/* Returns the mute state of the stream. 0 if not muted, non-zero if muted. */
-static inline size_t cras_shm_get_mute(const struct cras_audio_shm *shm)
-{
- return shm->header->mute;
-}
-
-/* Sets the size of a frame in bytes. */
-static inline void cras_shm_set_frame_bytes(struct cras_audio_shm *shm,
- unsigned frame_bytes)
-{
- shm->config.frame_bytes = frame_bytes;
- if (shm->header)
- shm->header->config.frame_bytes = frame_bytes;
-}
-
-/* Returns the size of a frame in bytes. */
-static inline unsigned cras_shm_frame_bytes(const struct cras_audio_shm *shm)
-{
- return shm->config.frame_bytes;
-}
-
-/* Sets if a callback is pending with the client. */
-static inline void cras_shm_set_callback_pending(struct cras_audio_shm *shm,
- int pending)
-{
- shm->header->callback_pending = !!pending;
-}
-
-/* Returns non-zero if a callback is pending for this shm region. */
-static inline int cras_shm_callback_pending(const struct cras_audio_shm *shm)
-{
- return shm->header->callback_pending;
-}
-
-/* Sets the starting offset of a buffer */
-static inline void cras_shm_set_buffer_offset(struct cras_audio_shm *shm,
- uint32_t buf_idx, uint32_t offset)
-{
- shm->header->buffer_offset[buf_idx] = offset;
-}
-
-/* Sets the used_size of the shm region. This is the maximum number of bytes
- * that is exchanged each time a buffer is passed from client to server.
- *
- * Also sets the buffer_offsets to default values based on the used size.
- */
-static inline void cras_shm_set_used_size(struct cras_audio_shm *shm,
- unsigned used_size)
-{
- uint32_t i;
-
- shm->config.used_size = used_size;
- if (shm->header) {
- shm->header->config.used_size = used_size;
-
- for (i = 0; i < CRAS_NUM_SHM_BUFFERS; i++)
- cras_shm_set_buffer_offset(shm, i, i * used_size);
- }
-}
-
-/* Returns the used size of the shm region in bytes. */
-static inline unsigned cras_shm_used_size(const struct cras_audio_shm *shm)
-{
- return shm->config.used_size;
-}
-
-/* Returns the used size of the shm region in frames. */
-static inline unsigned cras_shm_used_frames(const struct cras_audio_shm *shm)
-{
- return shm->config.used_size / shm->config.frame_bytes;
-}
-
-/* Returns the size of the samples shm region. */
-static inline uint64_t cras_shm_samples_size(const struct cras_audio_shm *shm)
-{
- return shm->samples_info.length;
-}
-
-/* Gets the counter of over-runs. */
-static inline unsigned cras_shm_num_overruns(const struct cras_audio_shm *shm)
-{
- return shm->header->num_overruns;
-}
-
-/* Copy the config from the shm region to the local config. Used by clients
- * when initially setting up the region.
- */
-static inline void cras_shm_copy_shared_config(struct cras_audio_shm *shm)
-{
- memcpy(&shm->config, &shm->header->config, sizeof(shm->config));
-}
-
-/* Open a read/write shared memory area with the given name.
- * Args:
- * name - Name of the shared-memory area.
- * size - Size of the shared-memory area.
- * Returns:
- * >= 0 file descriptor value, or negative errno value on error.
- */
-int cras_shm_open_rw(const char *name, size_t size);
-
-/* Reopen an existing shared memory area read-only.
- * Args:
- * name - Name of the shared-memory area.
- * fd - Existing file descriptor.
- * Returns:
- * >= 0 new file descriptor value, or negative errno value on error.
- */
-int cras_shm_reopen_ro(const char *name, int fd);
-
-/* Close and delete a shared memory area.
- * Args:
- * name - Name of the shared-memory area.
- * fd - Existing file descriptor.
- * Returns:
- * >= 0 new file descriptor value, or negative errno value on error.
- */
-void cras_shm_close_unlink(const char *name, int fd);
-
-/*
- * Configure shared memory for the system state.
- * Args:
- * name - Name of the shared-memory area.
- * mmap_size - Amount of shared memor to map.
- * rw_fd_out - Filled with the RW fd for the shm region.
- * ro_fd_out - Filled with the RO fd for the shm region.
- * Returns a pointer to the new shared memory region. Or NULL on error.
- */
-void *cras_shm_setup(const char *name, size_t mmap_size, int *rw_fd_out,
- int *ro_fd_out);
-
-#ifdef CRAS_SELINUX
-/*
- * Wrapper around selinux_restorecon(). This is helpful in unit tests because
- * we can mock out the selinux_restorecon() behaviour there. That is required
- * because selinux_restorecon() would fail in the unit tests, since there
- * is no file_contexts file.
- * Args:
- * pathname - Name of the file on which to run restorecon
- * Returns 0 on success, otherwise -1 and errno is set appropriately.
- */
-int cras_selinux_restorecon(const char *pathname);
-#endif
-
-#endif /* CRAS_SHM_H_ */
diff --git a/cras/src/common/cras_types.h b/cras/src/common/cras_types.h
deleted file mode 100644
index 544ba02c..00000000
--- a/cras/src/common/cras_types.h
+++ /dev/null
@@ -1,723 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Types commonly used in the client and server are defined here.
- */
-#ifndef CRAS_TYPES_H_
-#define CRAS_TYPES_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#include "cras_audio_format.h"
-#include "cras_iodev_info.h"
-#include "packet_status_logger.h"
-
-/* Architecture independent timespec */
-struct __attribute__((__packed__)) cras_timespec {
- int64_t tv_sec;
- int64_t tv_nsec;
-};
-
-/* Some special device index values. */
-enum CRAS_SPECIAL_DEVICE {
- NO_DEVICE,
- SILENT_RECORD_DEVICE,
- SILENT_PLAYBACK_DEVICE,
- SILENT_HOTWORD_DEVICE,
- MAX_SPECIAL_DEVICE_IDX
-};
-
-/*
- * Types of test iodevs supported.
- */
-enum TEST_IODEV_TYPE {
- TEST_IODEV_HOTWORD,
-};
-
-/* Commands for test iodevs. */
-enum CRAS_TEST_IODEV_CMD {
- TEST_IODEV_CMD_HOTWORD_TRIGGER,
-};
-
-/* CRAS client connection types. */
-enum CRAS_CONNECTION_TYPE {
- CRAS_CONTROL, // For legacy client.
- CRAS_PLAYBACK, // For playback client.
- CRAS_CAPTURE, // For capture client.
- CRAS_VMS_LEGACY, // For legacy client in vms.
- CRAS_VMS_UNIFIED, // For unified client in vms.
- CRAS_PLUGIN_PLAYBACK, // For playback client in vms/plugin.
- CRAS_PLUGIN_UNIFIED, // For unified client in vms/plugin.
- CRAS_NUM_CONN_TYPE,
-};
-
-static inline bool
-cras_validate_connection_type(enum CRAS_CONNECTION_TYPE conn_type)
-{
- return 0 <= conn_type && conn_type < CRAS_NUM_CONN_TYPE;
-}
-
-/* Directions of audio streams.
- * Input, Output, or loopback.
- *
- * Note that we use enum CRAS_STREAM_DIRECTION to access the elements in
- * num_active_streams in cras_server_state. For example,
- * num_active_streams[CRAS_STREAM_OUTPUT] is the number of active
- * streams with direction CRAS_STREAM_OUTPUT.
- */
-enum CRAS_STREAM_DIRECTION {
- CRAS_STREAM_OUTPUT,
- CRAS_STREAM_INPUT,
- CRAS_STREAM_UNDEFINED,
- CRAS_STREAM_POST_MIX_PRE_DSP,
- CRAS_NUM_DIRECTIONS
-};
-
-/* Bitmask for supporting all CRAS_STREAM_DIRECTION. */
-#define CRAS_STREAM_ALL_DIRECTION ((1 << CRAS_NUM_DIRECTIONS) - 1)
-
-/* Converts CRAS_STREAM_DIRECTION to bitmask.
- * Args:
- * dir - An enum CRAS_STREAM_DIRECTION.
- *
- * Returns:
- * bitmask for the given direction on success, negative on failure.
- */
-static inline int
-cras_stream_direction_mask(const enum CRAS_STREAM_DIRECTION dir)
-{
- if (0 <= dir && dir < CRAS_NUM_DIRECTIONS)
- return (1 << dir);
- return -EINVAL;
-}
-
-/*
- * Flags for stream types.
- * BULK_AUDIO_OK - This stream is OK with receiving up to a full shm of samples
- * in a single callback.
- * USE_DEV_TIMING - Don't wake up based on stream timing. Only wake when the
- * device is ready. Input streams only.
- * HOTWORD_STREAM - This stream is used only to listen for hotwords such as "OK
- * Google". Hardware will wake the device when this phrase is heard.
- * TRIGGER_ONLY - This stream only wants to receive when the data is available
- * and does not want to receive data. Used with HOTWORD_STREAM.
- * SERVER_ONLY - This stream doesn't associate to a client. It's used mainly
- * for audio data to flow from hardware through iodev's dsp pipeline.
- */
-enum CRAS_INPUT_STREAM_FLAG {
- BULK_AUDIO_OK = 0x01,
- USE_DEV_TIMING = 0x02,
- HOTWORD_STREAM = BULK_AUDIO_OK | USE_DEV_TIMING,
- TRIGGER_ONLY = 0x04,
- SERVER_ONLY = 0x08,
-};
-
-/*
- * Types of Loopback stream.
- */
-enum CRAS_LOOPBACK_TYPE {
- LOOPBACK_POST_MIX_PRE_DSP,
- LOOPBACK_POST_DSP,
- LOOPBACK_NUM_TYPES,
-};
-
-static inline int cras_stream_uses_output_hw(enum CRAS_STREAM_DIRECTION dir)
-{
- return dir == CRAS_STREAM_OUTPUT;
-}
-
-static inline int cras_stream_uses_input_hw(enum CRAS_STREAM_DIRECTION dir)
-{
- return dir == CRAS_STREAM_INPUT;
-}
-
-static inline int cras_stream_has_input(enum CRAS_STREAM_DIRECTION dir)
-{
- return dir != CRAS_STREAM_OUTPUT;
-}
-
-static inline int cras_stream_is_loopback(enum CRAS_STREAM_DIRECTION dir)
-{
- return dir == CRAS_STREAM_POST_MIX_PRE_DSP;
-}
-
-/* Types of audio streams. */
-enum CRAS_STREAM_TYPE {
- CRAS_STREAM_TYPE_DEFAULT,
- CRAS_STREAM_TYPE_MULTIMEDIA,
- CRAS_STREAM_TYPE_VOICE_COMMUNICATION,
- CRAS_STREAM_TYPE_SPEECH_RECOGNITION,
- CRAS_STREAM_TYPE_PRO_AUDIO,
- CRAS_STREAM_TYPE_ACCESSIBILITY,
- CRAS_STREAM_NUM_TYPES,
-};
-
-/* Types of audio clients. */
-enum CRAS_CLIENT_TYPE {
- CRAS_CLIENT_TYPE_UNKNOWN, /* Unknown client */
- CRAS_CLIENT_TYPE_LEGACY, /* A client with old craslib (CRAS_PROTO_VER = 3) */
- CRAS_CLIENT_TYPE_TEST, /* cras_test_client */
- CRAS_CLIENT_TYPE_PCM, /* A client using CRAS via pcm, like aplay */
- CRAS_CLIENT_TYPE_CHROME, /* Chrome, UI */
- CRAS_CLIENT_TYPE_ARC, /* ARC++ */
- CRAS_CLIENT_TYPE_CROSVM, /* CROSVM */
- CRAS_CLIENT_TYPE_SERVER_STREAM, /* Server stream */
- CRAS_CLIENT_TYPE_LACROS, /* LaCrOS */
- CRAS_CLIENT_TYPE_PLUGIN, /* PluginVM */
- CRAS_CLIENT_TYPE_ARCVM, /* ARCVM */
- CRAS_NUM_CLIENT_TYPE, /* numbers of CRAS_CLIENT_TYPE */
-};
-
-static inline bool cras_validate_client_type(enum CRAS_CLIENT_TYPE client_type)
-{
- return 0 <= client_type && client_type < CRAS_NUM_CLIENT_TYPE;
-}
-
-#define ENUM_STR(x) \
- case x: \
- return #x;
-
-static inline const char *
-cras_stream_type_str(enum CRAS_STREAM_TYPE stream_type)
-{
- // clang-format off
- switch (stream_type) {
- ENUM_STR(CRAS_STREAM_TYPE_DEFAULT)
- ENUM_STR(CRAS_STREAM_TYPE_MULTIMEDIA)
- ENUM_STR(CRAS_STREAM_TYPE_VOICE_COMMUNICATION)
- ENUM_STR(CRAS_STREAM_TYPE_SPEECH_RECOGNITION)
- ENUM_STR(CRAS_STREAM_TYPE_PRO_AUDIO)
- ENUM_STR(CRAS_STREAM_TYPE_ACCESSIBILITY)
- default:
- return "INVALID_STREAM_TYPE";
- }
- // clang-format on
-}
-
-static inline const char *
-cras_client_type_str(enum CRAS_CLIENT_TYPE client_type)
-{
- // clang-format off
- switch (client_type) {
- ENUM_STR(CRAS_CLIENT_TYPE_UNKNOWN)
- ENUM_STR(CRAS_CLIENT_TYPE_LEGACY)
- ENUM_STR(CRAS_CLIENT_TYPE_TEST)
- ENUM_STR(CRAS_CLIENT_TYPE_PCM)
- ENUM_STR(CRAS_CLIENT_TYPE_CHROME)
- ENUM_STR(CRAS_CLIENT_TYPE_ARC)
- ENUM_STR(CRAS_CLIENT_TYPE_CROSVM)
- ENUM_STR(CRAS_CLIENT_TYPE_SERVER_STREAM)
- ENUM_STR(CRAS_CLIENT_TYPE_LACROS)
- ENUM_STR(CRAS_CLIENT_TYPE_PLUGIN)
- ENUM_STR(CRAS_CLIENT_TYPE_ARCVM)
- default:
- return "INVALID_CLIENT_TYPE";
- }
- // clang-format on
-}
-
-/* Effects that can be enabled for a CRAS stream. */
-enum CRAS_STREAM_EFFECT {
- APM_ECHO_CANCELLATION = (1 << 0),
- APM_NOISE_SUPRESSION = (1 << 1),
- APM_GAIN_CONTROL = (1 << 2),
- APM_VOICE_DETECTION = (1 << 3),
-};
-
-/* Information about a client attached to the server. */
-struct __attribute__((__packed__)) cras_attached_client_info {
- uint32_t id;
- int32_t pid;
- uint32_t uid;
- uint32_t gid;
-};
-
-/* Each ionode has a unique id. The top 32 bits are the device index, lower 32
- * are the node index. */
-typedef uint64_t cras_node_id_t;
-
-static inline cras_node_id_t cras_make_node_id(uint32_t dev_index,
- uint32_t node_index)
-{
- cras_node_id_t id = dev_index;
- return (id << 32) | node_index;
-}
-
-static inline uint32_t dev_index_of(cras_node_id_t id)
-{
- return (uint32_t)(id >> 32);
-}
-
-static inline uint32_t node_index_of(cras_node_id_t id)
-{
- return (uint32_t)id;
-}
-
-#define CRAS_MAX_IODEVS 20
-#define CRAS_MAX_IONODES 20
-#define CRAS_MAX_ATTACHED_CLIENTS 20
-#define CRAS_MAX_AUDIO_THREAD_SNAPSHOTS 10
-#define CRAS_MAX_HOTWORD_MODEL_NAME_SIZE 12
-#define MAX_DEBUG_DEVS 4
-#define MAX_DEBUG_STREAMS 8
-#define AUDIO_THREAD_EVENT_LOG_SIZE (1024 * 6)
-#define CRAS_BT_EVENT_LOG_SIZE 1024
-#define MAIN_THREAD_EVENT_LOG_SIZE 1024
-
-/* There are 8 bits of space for events. */
-enum AUDIO_THREAD_LOG_EVENTS {
- AUDIO_THREAD_WAKE,
- AUDIO_THREAD_SLEEP,
- AUDIO_THREAD_READ_AUDIO,
- AUDIO_THREAD_READ_AUDIO_TSTAMP,
- AUDIO_THREAD_READ_AUDIO_DONE,
- AUDIO_THREAD_READ_OVERRUN,
- AUDIO_THREAD_FILL_AUDIO,
- AUDIO_THREAD_FILL_AUDIO_TSTAMP,
- AUDIO_THREAD_FILL_AUDIO_DONE,
- AUDIO_THREAD_WRITE_STREAMS_WAIT,
- AUDIO_THREAD_WRITE_STREAMS_WAIT_TO,
- AUDIO_THREAD_WRITE_STREAMS_MIX,
- AUDIO_THREAD_WRITE_STREAMS_MIXED,
- AUDIO_THREAD_WRITE_STREAMS_STREAM,
- AUDIO_THREAD_FETCH_STREAM,
- AUDIO_THREAD_STREAM_ADDED,
- AUDIO_THREAD_STREAM_REMOVED,
- AUDIO_THREAD_A2DP_FLUSH,
- AUDIO_THREAD_A2DP_THROTTLE_TIME,
- AUDIO_THREAD_A2DP_WRITE,
- AUDIO_THREAD_DEV_STREAM_MIX,
- AUDIO_THREAD_CAPTURE_POST,
- AUDIO_THREAD_CAPTURE_WRITE,
- AUDIO_THREAD_CONV_COPY,
- AUDIO_THREAD_STREAM_FETCH_PENDING,
- AUDIO_THREAD_STREAM_RESCHEDULE,
- AUDIO_THREAD_STREAM_SLEEP_TIME,
- AUDIO_THREAD_STREAM_SLEEP_ADJUST,
- AUDIO_THREAD_STREAM_SKIP_CB,
- AUDIO_THREAD_DEV_SLEEP_TIME,
- AUDIO_THREAD_SET_DEV_WAKE,
- AUDIO_THREAD_DEV_ADDED,
- AUDIO_THREAD_DEV_REMOVED,
- AUDIO_THREAD_IODEV_CB,
- AUDIO_THREAD_PB_MSG,
- AUDIO_THREAD_ODEV_NO_STREAMS,
- AUDIO_THREAD_ODEV_START,
- AUDIO_THREAD_ODEV_LEAVE_NO_STREAMS,
- AUDIO_THREAD_ODEV_DEFAULT_NO_STREAMS,
- AUDIO_THREAD_FILL_ODEV_ZEROS,
- AUDIO_THREAD_UNDERRUN,
- AUDIO_THREAD_SEVERE_UNDERRUN,
- AUDIO_THREAD_CAPTURE_DROP_TIME,
- AUDIO_THREAD_DEV_DROP_FRAMES,
- AUDIO_THREAD_LOOPBACK_PUT,
- AUDIO_THREAD_LOOPBACK_GET,
- AUDIO_THREAD_LOOPBACK_SAMPLE_HOOK,
- AUDIO_THREAD_DEV_OVERRUN,
-};
-
-/* Important events in main thread.
- * MAIN_THREAD_DEV_CLOSE - When an iodev closes at stream removal.
- * MAIN_THREAD_DEV_DISABLE - When an iodev is removed from active dev list.
- * MAIN_THREAD_DEV_INIT - When an iodev opens when stream attachs.
- * MAIN_THREAD_DEV_REOPEN - When an iodev reopens for format change.
- * MAIN_THREAD_ADD_ACTIVE_NODE - When an iodev is set as an additional
- * active device.
- * MAIN_THREAD_SELECT_NODE - When UI selects an iodev as active.
- * MAIN_THREAD_NODE_PLUGGED - When a jack of iodev is plugged/unplugged.
- * MAIN_THREAD_ADD_TO_DEV_LIST - When iodev is added to list.
- * MAIN_THREAD_INPUT_NODE_GAIN - When input node gain changes.
- * MAIN_THREAD_OUTPUT_NODE_VOLUME - When output node volume changes.
- * MAIN_THREAD_SET_OUTPUT_USER_MUTE - When output mute state is set.
- * MAIN_THREAD_RESUME_DEVS - When system resumes and notifies CRAS.
- * MAIN_THREAD_SUSPEND_DEVS - When system suspends and notifies CRAS.
- * MAIN_THREAD_STREAM_ADDED - When an audio stream is added.
- * MAIN_THREAD_STREAM_REMOVED - When an audio stream is removed.
- */
-enum MAIN_THREAD_LOG_EVENTS {
- /* iodev related */
- MAIN_THREAD_DEV_CLOSE,
- MAIN_THREAD_DEV_DISABLE,
- MAIN_THREAD_DEV_INIT,
- MAIN_THREAD_DEV_REOPEN,
- MAIN_THREAD_ADD_ACTIVE_NODE,
- MAIN_THREAD_SELECT_NODE,
- MAIN_THREAD_NODE_PLUGGED,
- MAIN_THREAD_ADD_TO_DEV_LIST,
- MAIN_THREAD_INPUT_NODE_GAIN,
- MAIN_THREAD_OUTPUT_NODE_VOLUME,
- MAIN_THREAD_SET_OUTPUT_USER_MUTE,
- MAIN_THREAD_RESUME_DEVS,
- MAIN_THREAD_SUSPEND_DEVS,
- /* stream related */
- MAIN_THREAD_STREAM_ADDED,
- MAIN_THREAD_STREAM_REMOVED,
-};
-
-/* There are 8 bits of space for events. */
-enum CRAS_BT_LOG_EVENTS {
- BT_ADAPTER_ADDED,
- BT_ADAPTER_REMOVED,
- BT_AUDIO_GATEWAY_INIT,
- BT_AUDIO_GATEWAY_START,
- BT_AVAILABLE_CODECS,
- BT_A2DP_CONFIGURED,
- BT_A2DP_START,
- BT_A2DP_SUSPENDED,
- BT_CODEC_SELECTION,
- BT_DEV_CONNECTED,
- BT_DEV_DISCONNECTED,
- BT_DEV_CONN_WATCH_CB,
- BT_DEV_SUSPEND_CB,
- BT_HFP_NEW_CONNECTION,
- BT_HFP_REQUEST_DISCONNECT,
- BT_HFP_SUPPORTED_FEATURES,
- BT_HFP_HF_INDICATOR,
- BT_HFP_SET_SPEAKER_GAIN,
- BT_HFP_UPDATE_SPEAKER_GAIN,
- BT_HSP_NEW_CONNECTION,
- BT_HSP_REQUEST_DISCONNECT,
- BT_NEW_AUDIO_PROFILE_AFTER_CONNECT,
- BT_RESET,
- BT_SCO_CONNECT,
- BT_TRANSPORT_ACQUIRE,
- BT_TRANSPORT_RELEASE,
- BT_TRANSPORT_SET_VOLUME,
- BT_TRANSPORT_UPDATE_VOLUME,
-};
-
-struct __attribute__((__packed__)) audio_thread_event {
- uint32_t tag_sec;
- uint32_t nsec;
- uint32_t data1;
- uint32_t data2;
- uint32_t data3;
-};
-
-/* Ring buffer of log events from the audio thread. */
-struct __attribute__((__packed__)) audio_thread_event_log {
- uint64_t write_pos;
- uint64_t sync_write_pos;
- uint32_t len;
- struct audio_thread_event log[AUDIO_THREAD_EVENT_LOG_SIZE];
-};
-
-struct __attribute__((__packed__)) audio_dev_debug_info {
- char dev_name[CRAS_NODE_NAME_BUFFER_SIZE];
- uint32_t buffer_size;
- uint32_t min_buffer_level;
- uint32_t min_cb_level;
- uint32_t max_cb_level;
- uint32_t frame_rate;
- uint32_t num_channels;
- double est_rate_ratio;
- uint8_t direction;
- uint32_t num_underruns;
- uint32_t num_severe_underruns;
- uint32_t highest_hw_level;
- uint32_t runtime_sec;
- uint32_t runtime_nsec;
- uint32_t longest_wake_sec;
- uint32_t longest_wake_nsec;
- double software_gain_scaler;
-};
-
-struct __attribute__((__packed__)) audio_stream_debug_info {
- uint64_t stream_id;
- uint32_t dev_idx;
- uint32_t direction;
- uint32_t stream_type;
- uint32_t client_type;
- uint32_t buffer_frames;
- uint32_t cb_threshold;
- uint64_t effects;
- uint32_t flags;
- uint32_t frame_rate;
- uint32_t num_channels;
- uint32_t longest_fetch_sec;
- uint32_t longest_fetch_nsec;
- uint32_t num_missed_cb;
- uint32_t num_overruns;
- uint32_t is_pinned;
- uint32_t pinned_dev_idx;
- uint32_t runtime_sec;
- uint32_t runtime_nsec;
- double stream_volume;
- int8_t channel_layout[CRAS_CH_MAX];
-};
-
-/* Debug info shared from server to client. */
-struct __attribute__((__packed__)) audio_debug_info {
- uint32_t num_streams;
- uint32_t num_devs;
- struct audio_dev_debug_info devs[MAX_DEBUG_DEVS];
- struct audio_stream_debug_info streams[MAX_DEBUG_STREAMS];
- struct audio_thread_event_log log;
-};
-
-struct __attribute__((__packed__)) main_thread_event {
- uint32_t tag_sec;
- uint32_t nsec;
- uint32_t data1;
- uint32_t data2;
- uint32_t data3;
-};
-
-struct __attribute__((__packed__)) main_thread_event_log {
- uint32_t write_pos;
- uint32_t len;
- struct main_thread_event log[MAIN_THREAD_EVENT_LOG_SIZE];
-};
-
-struct __attribute__((__packed__)) main_thread_debug_info {
- struct main_thread_event_log main_log;
-};
-
-struct __attribute__((__packed__)) cras_bt_event {
- uint32_t tag_sec;
- uint32_t nsec;
- uint32_t data1;
- uint32_t data2;
-};
-
-struct __attribute__((__packed__)) cras_bt_event_log {
- uint32_t write_pos;
- uint32_t len;
- struct cras_bt_event log[CRAS_BT_EVENT_LOG_SIZE];
-};
-
-struct __attribute__((__packed__)) cras_bt_debug_info {
- struct cras_bt_event_log bt_log;
- struct packet_status_logger wbs_logger;
-};
-
-/*
- * All event enums should be less then AUDIO_THREAD_EVENT_TYPE_COUNT,
- * or they will be ignored by the handler.
- */
-enum CRAS_AUDIO_THREAD_EVENT_TYPE {
- AUDIO_THREAD_EVENT_A2DP_OVERRUN,
- AUDIO_THREAD_EVENT_A2DP_THROTTLE,
- AUDIO_THREAD_EVENT_BUSYLOOP,
- AUDIO_THREAD_EVENT_DEBUG,
- AUDIO_THREAD_EVENT_SEVERE_UNDERRUN,
- AUDIO_THREAD_EVENT_UNDERRUN,
- AUDIO_THREAD_EVENT_DROP_SAMPLES,
- AUDIO_THREAD_EVENT_DEV_OVERRUN,
- AUDIO_THREAD_EVENT_TYPE_COUNT,
-};
-
-/*
- * Structure of snapshot for audio thread.
- */
-struct __attribute__((__packed__)) cras_audio_thread_snapshot {
- struct timespec timestamp;
- enum CRAS_AUDIO_THREAD_EVENT_TYPE event_type;
- struct audio_debug_info audio_debug_info;
-};
-
-/*
- * Ring buffer for storing snapshots.
- */
-struct __attribute__((__packed__)) cras_audio_thread_snapshot_buffer {
- struct cras_audio_thread_snapshot
- snapshots[CRAS_MAX_AUDIO_THREAD_SNAPSHOTS];
- int pos;
-};
-
-/* The server state that is shared with clients.
- * state_version - Version of this structure.
- * volume - index from 0-100.
- * min_volume_dBFS - volume in dB * 100 when volume = 1.
- * max_volume_dBFS - volume in dB * 100 when volume = max.
- * mute - 0 = unmuted, 1 = muted by system (device switch, suspend, etc).
- * user_mute - 0 = unmuted, 1 = muted by user.
- * mute_locked - 0 = unlocked, 1 = locked.
- * suspended - 1 = suspended, 0 = resumed.
- * capture_gain - Capture gain in dBFS * 100.
- * capture_mute - 0 = unmuted, 1 = muted.
- * capture_mute_locked - 0 = unlocked, 1 = locked.
- * num_streams_attached - Total number of streams since server started.
- * num_output_devs - Number of available output devices.
- * num_input_devs - Number of available input devices.
- * output_devs - Output audio devices currently attached.
- * input_devs - Input audio devices currently attached.
- * num_output_nodes - Number of available output nodes.
- * num_input_nodes - Number of available input nodes.
- * output_nodes - Output nodes currently attached.
- * input_nodes - Input nodes currently attached.
- * num_attached_clients - Number of clients attached to server.
- * client_info - List of first 20 attached clients.
- * update_count - Incremented twice each time the struct is updated. Odd
- * during updates.
- * num_active_streams - An array containing numbers or active
- * streams of different directions.
- * last_active_stream_time - Time the last stream was removed. Can be used
- * to determine how long audio has been idle.
- * audio_debug_info - Debug data filled in when a client requests it. This
- * isn't protected against concurrent updating, only one client should
- * use it.
- * default_output_buffer_size - Default output buffer size in frames.
- * non_empty_status - Whether any non-empty audio is being
- * played/captured.
- * aec_supported - Flag to indicate if system aec is supported.
- * aec_group_id - Group ID for the system aec to use for separating aec
- * tunings.
- * snapshot_buffer - ring buffer for storing audio thread snapshots.
- * bt_debug_info - ring buffer for storing bluetooth event logs.
- * bt_wbs_enabled - Whether or not bluetooth wideband speech is enabled.
- * deprioritize_bt_wbs_mic - Whether Bluetooth wideband speech mic
- * should be deprioritized for selecting as default audio input.
- * main_thread_debug_info - ring buffer for storing main thread event logs.
- * num_input_streams_with_permission - An array containing numbers of input
- * streams with permission in each client type.
- * noise_cancellation_enabled - Whether or not Noise Cancellation is enabled.
- * hotword_pause_at_suspend - 1 = Pause hotword detection when the system
- * suspends. Hotword detection is resumed after system resumes.
- * 0 - Hotword detection is allowed to continue running after system
- * suspends, so a detected hotword can wake up the device.
- *
- */
-#define CRAS_SERVER_STATE_VERSION 2
-struct __attribute__((packed, aligned(4))) cras_server_state {
- uint32_t state_version;
- uint32_t volume;
- int32_t min_volume_dBFS;
- int32_t max_volume_dBFS;
- int32_t mute;
- int32_t user_mute;
- int32_t mute_locked;
- int32_t suspended;
- int32_t capture_gain;
- int32_t capture_mute;
- int32_t capture_mute_locked;
- uint32_t num_streams_attached;
- uint32_t num_output_devs;
- uint32_t num_input_devs;
- struct cras_iodev_info output_devs[CRAS_MAX_IODEVS];
- struct cras_iodev_info input_devs[CRAS_MAX_IODEVS];
- uint32_t num_output_nodes;
- uint32_t num_input_nodes;
- struct cras_ionode_info output_nodes[CRAS_MAX_IONODES];
- struct cras_ionode_info input_nodes[CRAS_MAX_IONODES];
- uint32_t num_attached_clients;
- struct cras_attached_client_info client_info[CRAS_MAX_ATTACHED_CLIENTS];
- uint32_t update_count;
- uint32_t num_active_streams[CRAS_NUM_DIRECTIONS];
- struct cras_timespec last_active_stream_time;
- struct audio_debug_info audio_debug_info;
- int32_t default_output_buffer_size;
- int32_t non_empty_status;
- int32_t aec_supported;
- int32_t aec_group_id;
- struct cras_audio_thread_snapshot_buffer snapshot_buffer;
- struct cras_bt_debug_info bt_debug_info;
- int32_t bt_wbs_enabled;
- int32_t deprioritize_bt_wbs_mic;
- struct main_thread_debug_info main_thread_debug_info;
- uint32_t num_input_streams_with_permission[CRAS_NUM_CLIENT_TYPE];
- int32_t noise_cancellation_enabled;
- int32_t hotword_pause_at_suspend;
-};
-
-/* Actions for card add/remove/change. */
-enum cras_notify_device_action {
- /* Must match gavd action definitions. */
- CRAS_DEVICE_ACTION_ADD = 0,
- CRAS_DEVICE_ACTION_REMOVE = 1,
- CRAS_DEVICE_ACTION_CHANGE = 2,
-};
-
-/* Information about an ALSA card to be added to the system.
- * card_type - Either internal card or a USB sound card.
- * card_index - Index ALSA uses to refer to the card. The X in "hw:X".
- * priority - Base priority to give devices found on this card. Zero is the
- * lowest priority. Non-primary devices on the card will be given a
- * lowered priority.
- * usb_vendor_id - vendor ID if the device is on the USB bus.
- * usb_product_id - product ID if the device is on the USB bus.
- * usb_serial_number - serial number if the device is on the USB bus.
- * usb_desc_checksum - the checksum of the USB descriptors if the device
- * is on the USB bus.
- */
-enum CRAS_ALSA_CARD_TYPE {
- ALSA_CARD_TYPE_INTERNAL,
- ALSA_CARD_TYPE_USB,
-};
-#define USB_SERIAL_NUMBER_BUFFER_SIZE 64
-struct __attribute__((__packed__)) cras_alsa_card_info {
- enum CRAS_ALSA_CARD_TYPE card_type;
- uint32_t card_index;
- uint32_t usb_vendor_id;
- uint32_t usb_product_id;
- char usb_serial_number[USB_SERIAL_NUMBER_BUFFER_SIZE];
- uint32_t usb_desc_checksum;
-};
-
-/* Unique identifier for each active stream.
- * The top 16 bits are the client number, lower 16 are the stream number.
- */
-typedef uint32_t cras_stream_id_t;
-/* Generates a stream id for client stream. */
-static inline cras_stream_id_t cras_get_stream_id(uint16_t client_id,
- uint16_t stream_id)
-{
- return (cras_stream_id_t)(((client_id & 0x0000ffff) << 16) |
- (stream_id & 0x0000ffff));
-}
-/* Verify if the stream_id fits the given client_id */
-static inline bool cras_valid_stream_id(cras_stream_id_t stream_id,
- uint16_t client_id)
-{
- return ((stream_id >> 16) ^ client_id) == 0;
-}
-
-enum CRAS_NODE_TYPE {
- /* These value can be used for output nodes. */
- CRAS_NODE_TYPE_INTERNAL_SPEAKER,
- CRAS_NODE_TYPE_HEADPHONE,
- CRAS_NODE_TYPE_HDMI,
- CRAS_NODE_TYPE_HAPTIC,
- CRAS_NODE_TYPE_LINEOUT,
- /* These value can be used for input nodes. */
- CRAS_NODE_TYPE_MIC,
- CRAS_NODE_TYPE_HOTWORD,
- CRAS_NODE_TYPE_POST_MIX_PRE_DSP,
- CRAS_NODE_TYPE_POST_DSP,
- /* Type for the legacy BT narrow band mic .*/
- CRAS_NODE_TYPE_BLUETOOTH_NB_MIC,
- /* These value can be used for both output and input nodes. */
- CRAS_NODE_TYPE_USB,
- CRAS_NODE_TYPE_BLUETOOTH,
- CRAS_NODE_TYPE_FALLBACK_NORMAL,
- CRAS_NODE_TYPE_FALLBACK_ABNORMAL,
- CRAS_NODE_TYPE_UNKNOWN,
- CRAS_NODE_TYPE_ECHO_REFERENCE,
- CRAS_NODE_TYPE_ALSA_LOOPBACK,
-};
-
-/* Position values to described where a node locates on the system.
- * NODE_POSITION_EXTERNAL - The node works only when peripheral
- * is plugged.
- * NODE_POSITION_INTERNAL - The node lives on the system and doesn't
- * have specific direction.
- * NODE_POSITION_FRONT - The node locates on the side of system that
- * faces user.
- * NODE_POSITION_REAR - The node locates on the opposite side of
- * the system that faces user.
- * NODE_POSITION_KEYBOARD - The node locates under the keyboard.
- */
-enum CRAS_NODE_POSITION {
- NODE_POSITION_EXTERNAL,
- NODE_POSITION_INTERNAL,
- NODE_POSITION_FRONT,
- NODE_POSITION_REAR,
- NODE_POSITION_KEYBOARD,
-};
-
-#endif /* CRAS_TYPES_H_ */
diff --git a/cras/src/common/cras_util.c b/cras/src/common/cras_util.c
deleted file mode 100644
index 28570bf9..00000000
--- a/cras/src/common/cras_util.c
+++ /dev/null
@@ -1,264 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#define _GNU_SOURCE /* For ppoll() */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <poll.h>
-#include <sched.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-#include <sys/param.h>
-#include <sys/resource.h>
-#include <sys/socket.h>
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "cras_util.h"
-
-int cras_set_rt_scheduling(int rt_lim)
-{
- struct rlimit rl;
-
- rl.rlim_cur = rl.rlim_max = rt_lim;
-
- if (setrlimit(RLIMIT_RTPRIO, &rl) < 0) {
- syslog(LOG_WARNING, "setrlimit %u failed: %d\n",
- (unsigned)rt_lim, errno);
- return -EACCES;
- }
- return 0;
-}
-
-int cras_set_thread_priority(int priority)
-{
- struct sched_param sched_param;
- int err;
-
- memset(&sched_param, 0, sizeof(sched_param));
- sched_param.sched_priority = priority;
-
- err = pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
- if (err)
- syslog(LOG_WARNING,
- "Failed to set thread sched params to priority %d"
- ", rc: %d\n",
- priority, err);
-
- return err;
-}
-
-int cras_set_nice_level(int nice)
-{
- int rc;
-
- /* Linux isn't posix compliant with setpriority(2), it will set a thread
- * priority if it is passed a tid, not affecting the rest of the threads
- * in the process. Setting this priority will only succeed if the user
- * has been granted permission to adjust nice values on the system.
- */
- rc = setpriority(PRIO_PROCESS, syscall(__NR_gettid), nice);
- if (rc)
- syslog(LOG_WARNING, "Failed to set nice to %d, rc: %d", nice,
- rc);
-
- return rc;
-}
-
-int cras_make_fd_nonblocking(int fd)
-{
- int fl;
-
- fl = fcntl(fd, F_GETFL);
- if (fl < 0)
- return fl;
- if (fl & O_NONBLOCK)
- return 0;
- return fcntl(fd, F_SETFL, fl | O_NONBLOCK);
-}
-
-int cras_make_fd_blocking(int fd)
-{
- int fl;
-
- fl = fcntl(fd, F_GETFL);
- if (fl < 0)
- return fl;
- if ((~fl) & O_NONBLOCK)
- return 0;
- return fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
-}
-
-int cras_send_with_fds(int sockfd, const void *buf, size_t len, int *fd,
- unsigned int num_fds)
-{
- struct msghdr msg = { 0 };
- struct iovec iov;
- struct cmsghdr *cmsg;
- char *control;
- const unsigned int control_size = CMSG_SPACE(sizeof(*fd) * num_fds);
- int rc;
-
- control = calloc(control_size, 1);
-
- msg.msg_iov = &iov;
- msg.msg_iovlen = 1;
- iov.iov_base = (void *)buf;
- iov.iov_len = len;
-
- msg.msg_control = control;
- msg.msg_controllen = control_size;
-
- cmsg = CMSG_FIRSTHDR(&msg);
- cmsg->cmsg_level = SOL_SOCKET;
- cmsg->cmsg_type = SCM_RIGHTS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(*fd) * num_fds);
- memcpy(CMSG_DATA(cmsg), fd, sizeof(*fd) * num_fds);
-
- rc = sendmsg(sockfd, &msg, 0);
- if (rc == -1)
- rc = -errno;
- free(control);
- return rc;
-}
-
-int cras_recv_with_fds(int sockfd, void *buf, size_t len, int *fd,
- unsigned int *num_fds)
-{
- struct msghdr msg = { 0 };
- struct iovec iov;
- struct cmsghdr *cmsg;
- char *control;
- const unsigned int control_size = CMSG_SPACE(sizeof(*fd) * *num_fds);
- int rc;
- int i;
-
- control = calloc(control_size, 1);
-
- for (i = 0; i < *num_fds; i++)
- fd[i] = -1;
-
- msg.msg_iov = &iov;
- msg.msg_iovlen = 1;
- iov.iov_base = buf;
- iov.iov_len = len;
- msg.msg_control = control;
- msg.msg_controllen = control_size;
-
- rc = recvmsg(sockfd, &msg, 0);
- if (rc < 0) {
- rc = -errno;
- goto exit;
- }
-
- for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
- cmsg = CMSG_NXTHDR(&msg, cmsg)) {
- if (cmsg->cmsg_level == SOL_SOCKET &&
- cmsg->cmsg_type == SCM_RIGHTS) {
- size_t fd_size = cmsg->cmsg_len - sizeof(*cmsg);
- *num_fds = MIN(*num_fds, fd_size / sizeof(*fd));
- memcpy(fd, CMSG_DATA(cmsg), *num_fds * sizeof(*fd));
- goto exit;
- }
- }
-
- // If we reach here, we did not find any file descriptors.
- *num_fds = 0;
-exit:
- free(control);
- return rc;
-}
-
-int cras_poll(struct pollfd *fds, nfds_t nfds, struct timespec *timeout,
- const sigset_t *sigmask)
-{
- struct timespec now;
- struct timespec future;
- struct pollfd *fd = fds;
- nfds_t i;
- int rc = 0;
-
- if (timeout) {
- /* Treat a negative timeout as valid (but timed-out) since
- * this function could update timeout to have negative tv_sec
- * or tv_nsec. */
- if (timeout->tv_sec < 0 || timeout->tv_nsec < 0)
- return -ETIMEDOUT;
- rc = clock_gettime(CLOCK_MONOTONIC_RAW, &future);
- if (rc < 0)
- return -errno;
- add_timespecs(&future, timeout);
- }
-
- for (i = 0; i < nfds; i++) {
- fd->revents = 0;
- fd++;
- }
-
- rc = ppoll(fds, nfds, timeout, sigmask);
- if (rc == 0 && timeout) {
- rc = -ETIMEDOUT;
- } else if (rc < 0) {
- rc = -errno;
- }
-
- if (timeout) {
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&future, &now, timeout);
- }
-
- return rc;
-}
-
-int wait_for_dev_input_access()
-{
- /* Wait for /dev/input/event* files to become accessible by
- * having group 'input'. Setting these files to have 'rw'
- * access to group 'input' is done through a udev rule
- * installed by adhd into /lib/udev/rules.d.
- *
- * Wait for up to 2 seconds for the /dev/input/event* files to be
- * readable by gavd.
- *
- * TODO(thutt): This could also be done with a udev enumerate
- * and then a udev monitor.
- */
- const unsigned max_iterations = 4;
- unsigned i = 0;
-
- while (i < max_iterations) {
- int readable;
- struct timeval timeout;
- const char *const pathname = "/dev/input/event0";
-
- timeout.tv_sec = 0;
- timeout.tv_usec = 500000; /* 1/2 second. */
- readable = access(pathname, R_OK);
-
- /* If the file could be opened, then the udev rule has been
- * applied and gavd can read the event files. If there are no
- * event files, then we don't need to wait.
- *
- * If access does not become available, then headphone &
- * microphone jack autoswitching will not function properly.
- */
- if (readable == 0 || (readable == -1 && errno == ENOENT)) {
- /* Access allowed, or file does not exist. */
- break;
- }
- if (readable != -1 || errno != EACCES) {
- syslog(LOG_ERR, "Bad access for input devs.");
- return errno;
- }
- select(1, NULL, NULL, NULL, &timeout);
- ++i;
- }
-
- return 0;
-}
diff --git a/cras/src/common/cras_util.h b/cras/src/common/cras_util.h
deleted file mode 100644
index 96985ab2..00000000
--- a/cras/src/common/cras_util.h
+++ /dev/null
@@ -1,254 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_UTIL_H_
-#define CRAS_UTIL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <poll.h>
-#include <time.h>
-
-#include "cras_types.h"
-
-#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
-
-#define assert_on_compile(e) ((void)sizeof(char[1 - 2 * !(e)]))
-#define assert_on_compile_is_power_of_2(n) \
- assert_on_compile((n) != 0 && (((n) & ((n)-1)) == 0))
-
-/* Enables real time scheduling. */
-int cras_set_rt_scheduling(int rt_lim);
-/* Sets the priority. */
-int cras_set_thread_priority(int priority);
-/* Sets the niceness level of the current thread. */
-int cras_set_nice_level(int nice);
-
-/* Converts a buffer level from one sample rate to another. */
-static inline size_t cras_frames_at_rate(size_t orig_rate, size_t orig_frames,
- size_t act_rate)
-{
- return (orig_frames * act_rate + orig_rate - 1) / orig_rate;
-}
-
-/* Converts a number of frames to a time in a timespec. */
-static inline void cras_frames_to_time(unsigned int frames, unsigned int rate,
- struct timespec *t)
-{
- t->tv_sec = frames / rate;
- frames = frames % rate;
- t->tv_nsec = (uint64_t)frames * 1000000000 / rate;
-}
-
-/* Converts a number of frames to a time in a timespec. */
-static inline void cras_frames_to_time_precise(unsigned int frames, double rate,
- struct timespec *t)
-{
- double seconds = frames / rate;
- t->tv_sec = (unsigned int)seconds;
- seconds -= t->tv_sec;
- t->tv_nsec = (unsigned int)(seconds * 1000000000);
-}
-
-/* Converts a timespec duration to a frame count. */
-static inline uint64_t cras_time_to_frames(const struct timespec *t,
- unsigned int rate)
-{
- return t->tv_nsec * (uint64_t)rate / 1000000000 + rate * t->tv_sec;
-}
-
-/* Converts a number of frames to a duration in ms. */
-static inline unsigned int cras_frames_to_ms(unsigned int frames,
- unsigned int rate)
-{
- return 1000 * frames / rate;
-}
-
-/* Makes a file descriptor non blocking. */
-int cras_make_fd_nonblocking(int fd);
-
-/* Makes a file descriptor blocking. */
-int cras_make_fd_blocking(int fd);
-
-/* Send data in buf to the socket attach the fds. */
-int cras_send_with_fds(int sockfd, const void *buf, size_t len, int *fd,
- unsigned int num_fds);
-
-/* Receive data in buf from the socket. If file descriptors are received, put
- * them in *fd, otherwise set *fd to -1. */
-int cras_recv_with_fds(int sockfd, void *buf, size_t len, int *fd,
- unsigned int *num_fds);
-
-/* This must be written a million times... */
-static inline void subtract_timespecs(const struct timespec *end,
- const struct timespec *beg,
- struct timespec *diff)
-{
- diff->tv_sec = end->tv_sec - beg->tv_sec;
- diff->tv_nsec = end->tv_nsec - beg->tv_nsec;
-
- /* Adjust tv_sec and tv_nsec to the same sign. */
- if (diff->tv_sec > 0 && diff->tv_nsec < 0) {
- diff->tv_sec--;
- diff->tv_nsec += 1000000000L;
- } else if (diff->tv_sec < 0 && diff->tv_nsec > 0) {
- diff->tv_sec++;
- diff->tv_nsec -= 1000000000L;
- }
-}
-
-static inline void add_timespecs(struct timespec *a, const struct timespec *b)
-{
- a->tv_sec += b->tv_sec;
- a->tv_nsec += b->tv_nsec;
-
- while (a->tv_nsec >= 1000000000L) {
- a->tv_sec++;
- a->tv_nsec -= 1000000000L;
- }
-}
-
-/* Converts a fixed-size cras_timespec to a native timespec */
-static inline void cras_timespec_to_timespec(struct timespec *dest,
- const struct cras_timespec *src)
-{
- dest->tv_sec = src->tv_sec;
- dest->tv_nsec = src->tv_nsec;
-}
-
-/* Fills a fixed-size cras_timespec with the current system time */
-static inline int cras_clock_gettime(clockid_t clk_id,
- struct cras_timespec *ctp)
-{
- struct timespec tp;
- int ret = clock_gettime(clk_id, &tp);
- ctp->tv_sec = tp.tv_sec;
- ctp->tv_nsec = tp.tv_nsec;
- return ret;
-}
-
-/* Returns true if timeval a is after timeval b */
-static inline int timeval_after(const struct timeval *a,
- const struct timeval *b)
-{
- return (a->tv_sec > b->tv_sec) ||
- (a->tv_sec == b->tv_sec && a->tv_usec > b->tv_usec);
-}
-
-/* Returns true if timespec a is after timespec b */
-static inline int timespec_after(const struct timespec *a,
- const struct timespec *b)
-{
- return (a->tv_sec > b->tv_sec) ||
- (a->tv_sec == b->tv_sec && a->tv_nsec > b->tv_nsec);
-}
-
-/* Retruns the equivalent number of milliseconds for a given timespec.
- * The result is rounded up to the next millisecond. */
-static inline unsigned int timespec_to_ms(const struct timespec *ts)
-{
- return ts->tv_sec * 1000 + (ts->tv_nsec + 999999) / 1000000;
-}
-
-/* Convert milliseconds to timespec. */
-static inline void ms_to_timespec(time_t milliseconds, struct timespec *ts)
-{
- ts->tv_sec = milliseconds / 1000;
- ts->tv_nsec = (milliseconds % 1000) * 1000000;
-}
-
-/* Returns true if the given timespec is zero. */
-static inline int timespec_is_zero(const struct timespec *ts)
-{
- return ts && ts->tv_sec == 0 && ts->tv_nsec == 0;
-}
-
-/* Returns non-zero if the given timespec is non-zero. */
-static inline int timespec_is_nonzero(const struct timespec *ts)
-{
- return ts && (ts->tv_sec != 0 || (ts->tv_sec == 0 && ts->tv_nsec != 0));
-}
-
-/* Calculates frames since time beg. */
-static inline uint64_t cras_frames_since_time(const struct timespec *beg,
- unsigned int rate)
-{
- struct timespec now, time_since;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- if (!timespec_after(&now, beg))
- return 0;
-
- subtract_timespecs(&now, beg, &time_since);
- return cras_time_to_frames(&time_since, rate);
-}
-
-/* Calculates frames until time end. */
-static inline uint64_t cras_frames_until_time(const struct timespec *end,
- unsigned int rate)
-{
- struct timespec now, time_until;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- if (!timespec_after(end, &now))
- return 0;
-
- subtract_timespecs(end, &now, &time_until);
- return cras_time_to_frames(&time_until, rate);
-}
-
-/* Returns true if the difference between a and b is shorter than t. */
-static inline bool timespec_diff_shorter_than(const struct timespec *a,
- const struct timespec *b,
- const struct timespec *t)
-{
- struct timespec diff;
- if (timespec_after(a, b))
- subtract_timespecs(a, b, &diff);
- else
- subtract_timespecs(b, a, &diff);
- return timespec_after(t, &diff);
-}
-
-/* Poll on the given file descriptors.
- *
- * See ppoll(). This implementation changes the value of timeout to the
- * remaining time, and returns negative error codes on error.
- *
- * Args:
- * fds - Array of pollfd structures.
- * nfds - Number of pollfd structures.
- * timeout - Timeout time updated upon return with remaining time. The
- * timeout value may be updated to become invalid (negative
- * tv_nsec or negative tv_sec). In that case, -tv_nsec is the
- * number of nanoseconds by which the polling exceeded the
- * supplied timeout. The function immediately returns with
- * -ETIMEOUT if tv_nsec is negative, simplifying loops that
- * rely on the returned remaining timeout.
- * sigmask - Signal mask while in the poll.
- *
- * Returns:
- * Positive when file decriptors are ready.
- * Zero if no file descriptors are ready and timeout is NULL.
- * -ETIMEDOUT when no file descriptors are ready and a timeout specified.
- * Other negative error codes specified in the ppoll() man page.
- */
-int cras_poll(struct pollfd *fds, nfds_t nfds, struct timespec *timeout,
- const sigset_t *sigmask);
-
-/* Wait for /dev/input/event* files to become accessible.
- *
- * Returns:
- * Zero on success. Otherwise a negative error code.
- */
-int wait_for_dev_input_access();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_UTIL_H_ */
diff --git a/cras/src/common/dumper.c b/cras/src/common/dumper.c
deleted file mode 100644
index 5da16df8..00000000
--- a/cras/src/common/dumper.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdarg.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "dumper.h"
-
-void dumpf(struct dumper *dumper, const char *format, ...)
-{
- va_list ap;
- va_start(ap, format);
- dumper->vprintf(dumper, format, ap);
- va_end(ap);
-}
-
-/* dumper which outputs to syslog */
-
-struct syslog_data {
- int priority;
- struct dumper *mem_dumper;
-};
-
-static void syslog_vprintf(struct dumper *dumper, const char *fmt, va_list ap)
-{
- char *buf;
- int size, i;
- struct syslog_data *data = (struct syslog_data *)dumper->data;
- struct dumper *mem_dumper = data->mem_dumper;
-
- /* We cannot use syslog() directly each time we are called,
- * because syslog() will always append a newline to the
- * output, so the user will not be able to construct a line
- * incrementally using multiple calls. What we do here is to
- * collect the output in a buffer until a newline is given by
- * the user. */
-
- mem_dumper->vprintf(mem_dumper, fmt, ap);
-again:
- mem_dumper_get(mem_dumper, &buf, &size);
- for (i = 0; i < size; i++) {
- if (buf[i] == '\n') {
- syslog(data->priority, "%.*s", i + 1, buf);
- mem_dumper_consume(mem_dumper, i + 1);
- goto again;
- }
- }
-}
-
-struct dumper *syslog_dumper_create(int priority)
-{
- struct dumper *dumper = calloc(1, sizeof(struct dumper));
- struct syslog_data *data = calloc(1, sizeof(struct syslog_data));
- data->priority = priority;
- data->mem_dumper = mem_dumper_create();
- dumper->data = data;
- dumper->vprintf = &syslog_vprintf;
- return dumper;
-}
-
-void syslog_dumper_free(struct dumper *dumper)
-{
- mem_dumper_free(((struct syslog_data *)dumper->data)->mem_dumper);
- free(dumper->data);
- free(dumper);
-}
-
-/* dumper which outputs to a memory buffer */
-
-struct mem_data {
- char *buf;
- int size;
- int capacity;
-};
-
-static void mem_vprintf(struct dumper *dumper, const char *format, va_list ap)
-{
- int n;
- char *tmp;
- struct mem_data *data = (struct mem_data *)dumper->data;
-
- while (1) {
- /* try to use the remaining space */
- int remaining = data->capacity - data->size;
- n = vsnprintf(data->buf + data->size, remaining, format, ap);
-
- /* enough space? */
- if (n > -1 && n < remaining) {
- data->size += n;
- return;
- }
-
- /* allocate more space and try again */
- tmp = realloc(data->buf, data->capacity * 2);
- if (tmp == NULL)
- return;
- data->buf = tmp;
- data->capacity *= 2;
- }
-}
-
-struct dumper *mem_dumper_create()
-{
- struct dumper *dumper = calloc(1, sizeof(struct dumper));
- struct mem_data *data = calloc(1, sizeof(struct mem_data));
- if (!dumper || !data)
- goto error;
- data->size = 0;
- data->capacity = 80;
- data->buf = malloc(data->capacity);
- if (!data->buf)
- goto error;
- data->buf[0] = '\0';
- dumper->data = data;
- dumper->vprintf = &mem_vprintf;
- return dumper;
-
-error:
- if (dumper)
- free(dumper);
- if (data)
- free(data);
- return NULL;
-}
-
-void mem_dumper_free(struct dumper *dumper)
-{
- struct mem_data *data = (struct mem_data *)dumper->data;
- free(data->buf);
- free(data);
- free(dumper);
-}
-
-void mem_dumper_clear(struct dumper *dumper)
-{
- struct mem_data *data = (struct mem_data *)dumper->data;
- data->buf[0] = '\0';
- data->size = 0;
-}
-
-void mem_dumper_consume(struct dumper *dumper, int n)
-{
- struct mem_data *data = (struct mem_data *)dumper->data;
- if (n > data->size)
- n = data->size;
- memmove(data->buf, data->buf + n, data->size - n + 1);
- data->size -= n;
-}
-
-void mem_dumper_get(struct dumper *dumper, char **buf, int *size)
-{
- struct mem_data *data = (struct mem_data *)dumper->data;
- *buf = data->buf;
- *size = data->size;
-}
diff --git a/cras/src/common/dumper.h b/cras/src/common/dumper.h
deleted file mode 100644
index a6a32276..00000000
--- a/cras/src/common/dumper.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DUMPER_H_
-#define CRAS_DUMPER_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdio.h>
-
-/* dumper is an interface to output some human-readable information */
-struct dumper {
- void (*vprintf)(struct dumper *dumper, const char *format, va_list ap);
- void *data; /* private to each dumper */
-};
-
-/* a convenience function outputs to a dumper */
-void dumpf(struct dumper *dumper, const char *format, ...);
-
-/*
- * a dumper outputs to syslog with the given priority
- */
-struct dumper *syslog_dumper_create(int priority);
-void syslog_dumper_free(struct dumper *dumper);
-
-/*
- * a dumper saves the output in a memory buffer
- */
-struct dumper *mem_dumper_create();
-void mem_dumper_free(struct dumper *dumper);
-
-/* get the memory buffer of the output */
-void mem_dumper_get(struct dumper *dumper, char **buf, int *size);
-
-/* clear the memory buffer */
-void mem_dumper_clear(struct dumper *dumper);
-
-/* delete the first n characters in the memory buffer */
-void mem_dumper_consume(struct dumper *dumper, int n);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_DUMPER_H_ */
diff --git a/cras/src/common/edid_utils.c b/cras/src/common/edid_utils.c
deleted file mode 100644
index d9361f08..00000000
--- a/cras/src/common/edid_utils.c
+++ /dev/null
@@ -1,833 +0,0 @@
-// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "edid_utils.h"
-
-/* Dump out an EDID block in a simple format */
-void show_edid_data(FILE *outfile, unsigned char *edid_data, int items,
- int base)
-{
- int item = 0;
-
- while (item < items) {
- int i;
- fprintf(outfile, " 0x%04x: ", item + base);
- for (i = 0; i < 16; i++) {
- fprintf(outfile, "%02x ", edid_data[item++]);
- if (item >= items)
- break;
- }
- fprintf(outfile, "\n");
- }
-}
-
-unsigned char test_edid1[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x06, 0xaf, 0x5c, 0x20,
- 0x00, 0x00, 0x00, 0x00, 0x01, 0x12, 0x01, 0x03, 0x80, 0x1a, 0x0e, 0x78,
- 0x0a, 0x99, 0x85, 0x95, 0x55, 0x56, 0x92, 0x28, 0x22, 0x50, 0x54, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x96, 0x19, 0x56, 0x28, 0x50, 0x00,
- 0x08, 0x30, 0x18, 0x10, 0x24, 0x00, 0x00, 0x90, 0x10, 0x00, 0x00, 0x18,
- 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x41,
- 0x55, 0x4f, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfe, 0x00, 0x42, 0x31, 0x31, 0x36, 0x58, 0x57, 0x30,
- 0x32, 0x20, 0x56, 0x30, 0x20, 0x0a, 0x00, 0xf8
-};
-
-unsigned char test_edid2[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0xe4, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x01, 0x03, 0x80, 0x1a, 0x0e, 0x78,
- 0x0a, 0xbf, 0x45, 0x95, 0x58, 0x52, 0x8a, 0x28, 0x25, 0x50, 0x54, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x84, 0x1c, 0x56, 0xa8, 0x50, 0x00,
- 0x19, 0x30, 0x30, 0x20, 0x35, 0x00, 0x00, 0x90, 0x10, 0x00, 0x00, 0x1b,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x4c,
- 0x47, 0x20, 0x44, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x0a, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x50, 0x31, 0x31, 0x36, 0x57, 0x48,
- 0x31, 0x2d, 0x54, 0x4c, 0x4e, 0x31, 0x00, 0x4e
-};
-
-unsigned char test_edid3[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x4d, 0xd9, 0x02, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x01, 0x03, 0x80, 0x00, 0x00, 0x78,
- 0x0a, 0x0d, 0xc9, 0xa0, 0x57, 0x47, 0x98, 0x27, 0x12, 0x48, 0x4c, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x80, 0xd0, 0x72, 0x1c,
- 0x16, 0x20, 0x10, 0x2c, 0x25, 0x80, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e,
- 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00,
- 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x48,
- 0x44, 0x4d, 0x49, 0x20, 0x4c, 0x4c, 0x43, 0x0a, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x0f, 0x2d, 0x08, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0xc0, 0x02, 0x03, 0x1e, 0x47,
- 0x4f, 0x94, 0x13, 0x05, 0x03, 0x04, 0x02, 0x01, 0x16, 0x15, 0x07, 0x06,
- 0x11, 0x10, 0x12, 0x1f, 0x23, 0x09, 0x07, 0x01, 0x65, 0x03, 0x0c, 0x00,
- 0x10, 0x00, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40,
- 0x55, 0x00, 0x13, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0xbc,
- 0x52, 0xd0, 0x1e, 0x20, 0xb8, 0x28, 0x55, 0x40, 0xc4, 0x8e, 0x21, 0x00,
- 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72,
- 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xc4, 0x8e, 0x21, 0x00,
- 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0x13, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xfb
-};
-
-unsigned char test_edid4[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x4c, 0x2d, 0x10, 0x02,
- 0x00, 0x00, 0x00, 0x00, 0x31, 0x0f, 0x01, 0x03, 0x80, 0x10, 0x09, 0x8c,
- 0x0a, 0xe2, 0xbd, 0xa1, 0x5b, 0x4a, 0x98, 0x24, 0x15, 0x47, 0x4a, 0x20,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0,
- 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x1e,
- 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00,
- 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b,
- 0x3d, 0x1e, 0x2e, 0x08, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfc, 0x00, 0x53, 0x41, 0x4d, 0x53, 0x55, 0x4e, 0x47,
- 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x8d, 0x02, 0x03, 0x16, 0x71,
- 0x43, 0x84, 0x05, 0x03, 0x23, 0x09, 0x07, 0x07, 0x83, 0x01, 0x00, 0x00,
- 0x65, 0x03, 0x0c, 0x00, 0x20, 0x00, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0,
- 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x18,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x30
-};
-
-unsigned char test_edid5[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x3d, 0xcb, 0x61, 0x07,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x01, 0x03, 0x80, 0x00, 0x00, 0x78,
- 0x0a, 0x0d, 0xc9, 0xa0, 0x57, 0x47, 0x98, 0x27, 0x12, 0x48, 0x4c, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c,
- 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e,
- 0x01, 0x1d, 0x80, 0xd0, 0x72, 0x1c, 0x16, 0x20, 0x10, 0x2c, 0x25, 0x80,
- 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x54,
- 0x58, 0x2d, 0x53, 0x52, 0x36, 0x30, 0x35, 0x0a, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x17, 0xf0, 0x0f, 0x7e, 0x11, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x93, 0x02, 0x03, 0x3b, 0x72,
- 0x55, 0x85, 0x04, 0x03, 0x02, 0x0e, 0x0f, 0x07, 0x23, 0x24, 0x10, 0x94,
- 0x13, 0x12, 0x11, 0x1d, 0x1e, 0x16, 0x25, 0x26, 0x01, 0x1f, 0x35, 0x09,
- 0x7f, 0x07, 0x0f, 0x7f, 0x07, 0x17, 0x07, 0x50, 0x3f, 0x06, 0xc0, 0x57,
- 0x06, 0x00, 0x5f, 0x7e, 0x01, 0x67, 0x5e, 0x00, 0x83, 0x4f, 0x00, 0x00,
- 0x66, 0x03, 0x0c, 0x00, 0x20, 0x00, 0x80, 0x8c, 0x0a, 0xd0, 0x8a, 0x20,
- 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00,
- 0x18, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40, 0x55,
- 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72, 0x51,
- 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00,
- 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xdd
-};
-
-/* Has DTD that is too wide */
-unsigned char test_edid6[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x10, 0xac, 0x63, 0x40,
- 0x4c, 0x35, 0x31, 0x33, 0x0c, 0x15, 0x01, 0x03, 0x80, 0x40, 0x28, 0x78,
- 0xea, 0x8d, 0x85, 0xad, 0x4f, 0x35, 0xb1, 0x25, 0x0e, 0x50, 0x54, 0xa5,
- 0x4b, 0x00, 0x71, 0x4f, 0x81, 0x00, 0x81, 0x80, 0xa9, 0x40, 0xd1, 0x00,
- 0xd1, 0x40, 0x01, 0x01, 0x01, 0x01, 0xe2, 0x68, 0x00, 0xa0, 0xa0, 0x40,
- 0x2e, 0x60, 0x30, 0x20, 0x36, 0x00, 0x81, 0x91, 0x21, 0x00, 0x00, 0x1a,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x50, 0x48, 0x35, 0x4e, 0x59, 0x31, 0x33,
- 0x4d, 0x33, 0x31, 0x35, 0x4c, 0x0a, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x44,
- 0x45, 0x4c, 0x4c, 0x20, 0x55, 0x33, 0x30, 0x31, 0x31, 0x0a, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x31, 0x56, 0x1d, 0x71, 0x1c, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0xb0
-};
-
-static unsigned char *test_edids[N_TEST_EDIDS] = { test_edid1, test_edid2,
- test_edid3, test_edid4,
- test_edid5, test_edid6 };
-
-int get_test_edid(int n, unsigned char *dst)
-{
- if ((n < 1) || (n > N_TEST_EDIDS))
- return -1;
- memcpy(dst, test_edids[n - 1], 256);
- return 0;
-}
-
-int show_test_edid(FILE *outfile, int n)
-{
- if ((n < 1) || (n > N_TEST_EDIDS))
- return -1;
- fprintf(outfile, "Test EDID %d\n", n);
- show_edid(outfile, test_edids[n - 1], 1);
- return 0;
-}
-
-static void get_dtd_string(const char *str, char *buf, int buf_size)
-{
- int stp;
- int len = buf_size < 14 ? buf_size : 14;
-
- strncpy(buf, str, len - 1);
- for (stp = 0; stp < len - 1; stp++)
- if (buf[stp] == 0x0a)
- buf[stp] = 0;
- buf[stp] = 0;
-}
-
-/* Print an edid descriptor block (standard case is at 54 + 18 * i) */
-void show_edid_dtd(FILE *outfile, unsigned char *base)
-{
- int pelclk = base[DTD_PCLK_LO] + (base[DTD_PCLK_HI] << 8);
- char monstr[DTD_SIZE];
-
- if (pelclk != 0) {
- int hres = base[DTD_HA_LO] + ((base[DTD_HABL_HI] & 0xf0) << 4);
- int hbl = base[DTD_HBL_LO] + ((base[DTD_HABL_HI] & 0x0f) << 8);
- int vres = base[DTD_VA_LO] + ((base[DTD_VABL_HI] & 0xf0) << 4);
- int vbl = base[DTD_VBL_LO] + ((base[DTD_VABL_HI] & 0x0f) << 8);
- int hso = base[DTD_HSO_LO] + ((base[DTD_HVSX_HI] & 0xc0) << 2);
- int hsw = base[DTD_HSW_LO] + ((base[DTD_HVSX_HI] & 0x30) << 4);
- int vso = (base[DTD_VSX_LO] >> 4) +
- ((base[DTD_HVSX_HI] & 0x0c) << 2);
- int vsw = (base[DTD_VSX_LO] & 0xf) +
- ((base[DTD_HVSX_HI] & 0x03) << 4);
- int hsiz = base[DTD_HSIZE_LO] +
- ((base[DTD_HVSIZE_HI] & 0xf0) << 4);
- int vsiz = base[DTD_VSIZE_LO] +
- ((base[DTD_HVSIZE_HI] & 0x0f) << 8);
- int hbdr = base[DTD_HBORDER];
- int vbdr = base[DTD_VBORDER];
- int mdflg = base[DTD_FLAGS];
-
- int refr = (pelclk * 10000) / ((hres + hbl) * (vres + vbl));
- int refm = (pelclk * 10000) % ((hres + hbl) * (vres + vbl));
- int refd = (refm * 100) / ((hres + hbl) * (vres + vbl));
-
- fprintf(outfile,
- "%dx%d%c@%d.%02d, dot clock %d %cHsync %cVsync\n",
- hres, vres, (mdflg & 0x80) ? 'i' : 'p', refr, refd,
- pelclk * 10000, (mdflg & 0x2) ? '+' : '-',
- (mdflg & 0x4) ? '+' : '-');
- fprintf(outfile, "H: start %d, end %d, total %d\n", hres + hso,
- hres + hso + hsw, hres + hbl);
- fprintf(outfile, "V: start %d, end %d, total %d\n", vres + vso,
- vres + vso + vsw, vres + vbl);
- fprintf(outfile, "Size %dx%dmm, Border %dx%d pixels\n", hsiz,
- vsiz, hbdr, vbdr);
- return;
- }
-
- switch (base[DTD_TYPETAG]) {
- case DTDTYPE_SERIAL:
- case DTDTYPE_STRING:
- case DTDTYPE_NAME:
- get_dtd_string((const char *)base + DTD_STRING, monstr,
- DTD_SIZE);
-
- if (base[3] != DTDTYPE_STRING)
- fprintf(outfile, "%s: %s\n",
- (base[3] == DTDTYPE_NAME) ? "Name" : "Serial",
- monstr);
- else
- fprintf(outfile, "%s\n", monstr);
- break;
-
- case DTDTYPE_LIMITS:
- fprintf(outfile, "V %d - %d Hz, H %d - %d kHz, Pel <= %d MHz\n",
- base[DTD_MINV_HZ], base[DTD_MAXV_HZ],
- base[DTD_MINH_kHZ], base[DTD_MAXH_kHZ],
- base[DTD_MAXCLK_100kHZ] * 10);
- break;
-
- default:
- fprintf(outfile, "Undecoded descriptor block type 0x%x\n",
- base[DTD_TYPETAG]);
- break;
- }
-}
-
-char *sad_audio_type[16] = {
- "Reserved",
- "LPCM",
- "AC-3",
- "MPEG1 (Layer 1 and 2)",
- "MP3",
- "MPEG2",
- "AAC",
- "DTS",
- "ATRAC",
- "SACD",
- "DD+",
- "DTS-HD",
- "MLP/Dolby TrueHD",
- "DST Audio",
- "WMA Pro",
- "Reserved",
-};
-
-char *uscanstr[4] = {
- "not supported",
- "always overscan",
- "always underscan",
- "supports both over- and underscan",
-};
-
-static inline void show_audio_dbc(FILE *outfile, const unsigned char *edid_ext,
- int dbc)
-{
- int dbp = dbc + 1;
- int db_len = edid_ext[dbc + DBC_TAG_LENGTH] & DBC_LEN_MASK;
-
- while (dbp < (dbc + db_len + 1)) {
- int atype = (edid_ext[dbp + DBCA_FORMAT] >> 3) & 0xf;
- unsigned char dbca_rate = edid_ext[dbp + DBCA_RATE];
-
- fprintf(outfile, "Audio: %d channels %s: ",
- (edid_ext[dbp + DBCA_FORMAT] & 0x7) + 1,
- sad_audio_type[atype]);
-
- if (dbca_rate & 0x40)
- fprintf(outfile, "192k ");
- if (dbca_rate & 0x20)
- fprintf(outfile, "176k ");
- if (dbca_rate & 0x10)
- fprintf(outfile, "96k ");
- if (dbca_rate & 0x08)
- fprintf(outfile, "88k ");
- if (dbca_rate & 0x04)
- fprintf(outfile, "48k ");
- if (dbca_rate & 0x02)
- fprintf(outfile, "44k ");
- if (dbca_rate & 0x01)
- fprintf(outfile, "32k ");
-
- if (atype == 1) {
- unsigned char dbca_info = edid_ext[dbp + DBCA_INFO];
- fprintf(outfile, "%s%s%s\n",
- (dbca_info & 0x4) ? "24-bit " : "",
- (dbca_info & 0x2) ? "20-bit " : "",
- (dbca_info & 0x1) ? "16-bit" : "");
- } else if ((atype >= 2) && (atype <= 8)) {
- fprintf(outfile, "Max %dkHz\n",
- edid_ext[dbp + DBCA_INFO] * 8);
- } else {
- fprintf(outfile, "Codec vendor flags 0x%02x\n",
- edid_ext[dbp + DBCA_INFO]);
- }
-
- dbp += DBCA_SIZE;
- }
-}
-
-static inline void show_vendor_dbc(FILE *outfile, const unsigned char *edid_ext,
- int dbp)
-{
- if ((edid_ext[dbp + DBCVND_IEEE_LO] != 0x03) ||
- (edid_ext[dbp + DBCVND_IEEE_MID] != 0x0C) ||
- (edid_ext[dbp + DBCVND_IEEE_HI] != 0x00)) {
- fprintf(outfile, "Vendor block for %02x-%02x-%02x",
- edid_ext[dbp + DBCVND_IEEE_LO],
- edid_ext[dbp + DBCVND_IEEE_MID],
- edid_ext[dbp + DBCVND_IEEE_HI]);
- return;
- }
-
- fprintf(outfile,
- "HDMI Vendor block (CEC @0x%04x):\n"
- "Support: %s%s%s%s%s%s\n",
- edid_ext[dbp + DBCVHDMI_CEC_LO] +
- (edid_ext[dbp + DBCVHDMI_CEC_HI] << 8),
- (edid_ext[dbp + DBCVHDMI_SUPPORT] & 0x80) ? "AI " : "",
- (edid_ext[dbp + DBCVHDMI_SUPPORT] & 0x40) ? "DC_48bit " : "",
- (edid_ext[dbp + DBCVHDMI_SUPPORT] & 0x20) ? "DC_36bit " : "",
- (edid_ext[dbp + DBCVHDMI_SUPPORT] & 0x10) ? "DC_30bit " : "",
- (edid_ext[dbp + DBCVHDMI_SUPPORT] & 0x08) ? "DC_Y444 " : "",
- (edid_ext[dbp + DBCVHDMI_SUPPORT] & 0x01) ? "DVI_Dual" : "");
-
- if (edid_ext[dbp + DBCVHDMI_MAXTMDS_5MHz] > 0)
- fprintf(outfile, "Max TMDS Frequency %dMHz\n",
- edid_ext[dbp + DBCVHDMI_MAXTMDS_5MHz] * 5);
-
- if (edid_ext[dbp + DBCVHDMI_LATFLAGS] & 0x80)
- fprintf(outfile, "Video latency %dms, audio latency %dms\n",
- 2 * (edid_ext[dbp + DBCVHDMI_VLAT] - 1),
- 2 * (edid_ext[dbp + DBCVHDMI_ALAT] - 1));
-
- if (edid_ext[dbp + 7] & 0x40)
- fprintf(outfile,
- "Interlaced Video latency %dms, audio latency %dms\n",
- 2 * (edid_ext[dbp + DBCVHDMI_IVLAT] - 1),
- 2 * (edid_ext[dbp + DBCVHDMI_IALAT] - 1));
-}
-
-static void show_extended_dbc(FILE *outfile, const unsigned char *edid_ext,
- int dbc)
-{
- int dbp = dbc + 1;
- int db_len = edid_ext[dbc + DBC_TAG_LENGTH] & DBC_LEN_MASK;
-
- switch (edid_ext[dbp + DBC_ETAG]) {
- case DBC_ETAG_VCDB: {
- unsigned char vcdb_flags;
-
- fprintf(outfile, "Video Capabilities:\n");
- fprintf(outfile, " Quantization range selectable: %s\n",
- (edid_ext[dbp + VCDB_FLAGS] & 0x40) ? "unknown" :
- "via AVI Q");
-
- /* PT field zero implies no data, just use IT
- * and CE fields
- */
- vcdb_flags = edid_ext[dbp + VCDB_FLAGS];
- if (VCDB_S_PT(vcdb_flags))
- fprintf(outfile, " Preferred mode %s\n",
- uscanstr[VCDB_S_PT(vcdb_flags)]);
- fprintf(outfile, " IT modes %s\n",
- uscanstr[VCDB_S_IT(vcdb_flags)]);
- fprintf(outfile, " CE modes %s\n",
- uscanstr[VCDB_S_CE(vcdb_flags)]);
- break;
- }
-
- case DBC_ETAG_COL:
- fprintf(outfile, "Colorimetry supports %s%s metadata 0x%x\n",
- (edid_ext[dbp + COL_FLAGS] & 0x02) ? "HD(YCC709) " : "",
- (edid_ext[dbp + COL_FLAGS] & 0x01) ? "SD(YCC601) " : "",
- (edid_ext[dbp + COL_META] & 0x07));
- break;
-
- default:
- fprintf(outfile,
- "Unknown extended tag data block 0x%x, length 0x%x\n",
- edid_ext[dbc + DBC_ETAG], db_len);
- }
-}
-
-void show_cea_timing(FILE *outfile, unsigned char *edid_ext)
-{
- int i, dbc;
- int off_dtd = edid_ext[CEA_DTD_OFFSET];
- int n_dtd;
- fprintf(outfile, "Found CEA EDID Timing Extension rev 3\n");
-
- if (off_dtd < CEA_DBC_START) {
- fprintf(outfile, "Block is empty (off_dtd = %d)\n", off_dtd);
- return;
- }
- /* Ends with 0 and a checksum, have at least one pad byte */
- n_dtd = (CEA_LAST_PAD - off_dtd) / DTD_SIZE;
- fprintf(outfile,
- "Block has DTDs starting at offset %d (%d bytes of DBCs)\n",
- off_dtd, off_dtd - CEA_DBC_START);
- fprintf(outfile, "There is space for %d DTDs in extension\n", n_dtd);
- fprintf(outfile,
- "There are %d native DTDs (between regular and extensions)\n",
- edid_ext[CEA_NATIVE_DTDS] & 0xf);
- fprintf(outfile, "IT formats %sdefault to underscan\n",
- (edid_ext[CEA_SUPPORT] & 0x80) ? "" : "do not ");
- fprintf(outfile,
- "Support: %sbasic audio, %sYCrCb 4:4:4, %sYCrCb 4:2:2\n",
- (edid_ext[CEA_SUPPORT] & 0x40) ? "" : "no ",
- (edid_ext[CEA_SUPPORT] & 0x20) ? "" : "no ",
- (edid_ext[CEA_SUPPORT] & 0x10) ? "" : "no ");
-
- /* Between offset 4 and off_dtd is the Data Block Collection */
- /* There may be none, in which case off_dtd == 4 */
- dbc = CEA_DBC_START;
- while (dbc < off_dtd) {
- int db_len = edid_ext[dbc + DBC_TAG_LENGTH] & DBC_LEN_MASK;
- int dbp = dbc + 1;
-
- switch (edid_ext[dbc + DBC_TAG_LENGTH] >> DBC_TAG_SHIFT) {
- case DBC_TAG_AUDIO:
- /* Audio Data Block */
- show_audio_dbc(outfile, edid_ext, dbc);
- break;
-
- case DBC_TAG_VIDEO:
- /* Vidio Data Block */
- while (dbp < (dbc + db_len + 1)) {
- int vtype = edid_ext[dbp + DBCV_CODE] & 0x7f;
- fprintf(outfile, "Video: Code %d %s\n", vtype,
- (edid_ext[dbp + DBCV_CODE] & 0x80) ?
- "(native)" :
- "");
- dbp += DBCV_SIZE;
- }
- break;
-
- case DBC_TAG_VENDOR:
- /* Vendor Data Block */
- show_vendor_dbc(outfile, edid_ext, dbc + 1);
- break;
-
- case DBC_TAG_SPEAKER: {
- /* Speaker allocation Block */
- unsigned char dbcsp_alloc = edid_ext[dbp + DBCSP_ALLOC];
-
- fprintf(outfile, "Speakers: %s%s%s%s%s%s%s\n",
- (dbcsp_alloc & 0x40) ? "RearCenter L/R " : "",
- (dbcsp_alloc & 0x20) ? "FrontCenter L/R " : "",
- (dbcsp_alloc & 0x10) ? "Rear Center" : "",
- (dbcsp_alloc & 0x08) ? "Rear L/R " : "",
- (dbcsp_alloc & 0x04) ? "Front Center " : "",
- (dbcsp_alloc & 0x02) ? "LFE " : "",
- (dbcsp_alloc & 0x01) ? "Front L/R " : "");
- break;
- }
-
- case DBC_TAG_EXTENDED:
- show_extended_dbc(outfile, edid_ext, dbc);
- break;
-
- default:
- fprintf(outfile,
- "Unknown Data Block type tag 0x%x, len 0x%x\n",
- edid_ext[dbc + DBC_TAG_LENGTH] >> DBC_TAG_SHIFT,
- db_len);
- break;
- }
-
- dbc += db_len + 1;
- }
- for (i = 0; i < n_dtd; i++) {
- /* Find 0,0 when we hit padding */
- if ((edid_ext[off_dtd + DTD_SIZE * i + DTD_PCLK_LO] == 0) &&
- (edid_ext[off_dtd + DTD_SIZE * i + DTD_PCLK_HI] == 0)) {
- fprintf(outfile, "End of DTD padding after %d DTDs\n",
- i);
- break;
- }
- show_edid_dtd(outfile, edid_ext + (off_dtd + DTD_SIZE * i));
- }
-}
-
-int edid_valid(const unsigned char *edid_data)
-{
- return ((edid_data[EDID_HDR + 0] == 0x00) &&
- (edid_data[EDID_HDR + 1] == 0xff) &&
- (edid_data[EDID_HDR + 2] == 0xff) &&
- (edid_data[EDID_HDR + 3] == 0xff) &&
- (edid_data[EDID_HDR + 4] == 0xff) &&
- (edid_data[EDID_HDR + 5] == 0xff) &&
- (edid_data[EDID_HDR + 6] == 0xff) &&
- (edid_data[EDID_HDR + 7] == 0x00));
-}
-
-int edid_lpcm_support(const unsigned char *edid_data, int ext)
-{
- const unsigned char *edid_ext = edid_data + EDID_SIZE;
- int dbc;
- int off_dtd = edid_ext[CEA_DTD_OFFSET];
-
- /* No if no extension, which can happen for two reasons */
- /* a) ext < 1 indicates no data was read into the extension area */
- /* b) edid_data[126] < 1 indicates EDID does not use extension area */
- if ((ext < 1) || (edid_data[EDID_EXT_FLAG] < 1))
- return 0;
-
- /* No if extension is not CEA rev 3 */
- if (!((edid_ext[EEXT_TAG] == 0x02) && (edid_ext[EEXT_REV] == 0x03)))
- return 0;
-
- /* If DBC block is not empty look for audio info */
- if (off_dtd <= CEA_DBC_START)
- goto done_dtd;
-
- /* Between offset 4 and off_dtd is the Data Block Collection */
- /* There may be none, in which case off_dtd == 4 */
- dbc = CEA_DBC_START;
- while (dbc < off_dtd) {
- int db_len = edid_ext[dbc + DBC_TAG_LENGTH] & DBC_LEN_MASK;
- int dbp = dbc + 1;
- unsigned char dbc_type;
-
- /* Audio Data Block, type LPCM, return bitmap of frequencies */
- dbc_type = edid_ext[dbc + DBC_TAG_LENGTH] >> DBC_TAG_SHIFT;
- if ((dbc_type == DBC_TAG_AUDIO) &&
- (((edid_ext[dbp + DBCA_FORMAT] >> 3) & 0xF) ==
- DBCA_FMT_LPCM))
- return edid_ext[dbp + DBCA_RATE];
-
- dbc += db_len + 1;
- }
- /* Get here if failed to find LPCM info in DBC block */
-
-done_dtd:
- /* Last chance is to look for Basic Audio support. Return bitmap for 32,
- * 44.1, 48 */
- if (edid_ext[CEA_SUPPORT] & 0x40)
- return 0x7;
-
- return 0;
-}
-
-int edid_has_hdmi_info(const unsigned char *edid_data, int ext)
-{
- const unsigned char *edid_ext = edid_data + EDID_SIZE;
- int dbc;
- int off_dtd = edid_ext[CEA_DTD_OFFSET];
-
- /* No if no extension, which can happen for two reasons */
- /* a) ext < 1 indicates no data was read into the extension area */
- /* b) edid_data[126] < 1 indicates EDID does not use extension area */
- if ((ext < 1) || (edid_data[EDID_EXT_FLAG] < 1))
- return 0;
-
- /* No if extension is not CEA rev 3 */
- if (!((edid_ext[EEXT_TAG] == 0x02) && (edid_ext[EEXT_REV] == 0x03)))
- return 0;
-
- /* No if block is empty */
- if (off_dtd < CEA_DBC_START)
- return 0;
-
- /* Between offset 4 and off_dtd is the Data Block Collection */
- /* There may be none, in which case off_dtd == 4 */
- dbc = CEA_DBC_START;
- while (dbc < off_dtd) {
- int db_len = edid_ext[dbc + DBC_TAG_LENGTH] & DBC_LEN_MASK;
- int dbp = dbc + 1;
- unsigned char dbc_type;
-
- dbc_type = edid_ext[dbc + DBC_TAG_LENGTH] >> DBC_TAG_SHIFT;
- if (dbc_type == DBC_TAG_VENDOR) {
- /* Vendor Data Block */
- if ((edid_ext[dbp + DBCVND_IEEE_LO] == 0x03) &&
- (edid_ext[dbp + DBCVND_IEEE_MID] == 0x0C) &&
- (edid_ext[dbp + DBCVND_IEEE_HI] == 0x00))
- return 1;
- }
- dbc += db_len + 1;
- }
- return 0;
-}
-
-/* Print out an EDID */
-void show_edid(FILE *outfile, unsigned char *edid_data, int ext)
-{
- int i;
- int edidver = edid_data[EDID_VERSION];
- int edidrev = edid_data[EDID_REVISION];
- unsigned char *edid_ext;
- unsigned char edid_features;
-
- if (!edid_valid(edid_data)) {
- fprintf(outfile, "Block does not contain EDID header\n");
- return;
- }
- /* unsigned edid_data so the right shifts pull in zeros */
- fprintf(outfile, "Manufacturer ID %c%c%c, product ID 0x%x\n",
- '@' + (edid_data[EDID_MFG_EID] >> 2),
- '@' + (((edid_data[EDID_MFG_EID] & 3) << 3) +
- (edid_data[EDID_MFG_EID + 1] >> 5)),
- '@' + (edid_data[EDID_MFG_EID + 1] & 0x1f),
- edid_data[EDID_MFG_PROD_LO] +
- (edid_data[EDID_MFG_PROD_HI] << 8));
- fprintf(outfile, "Manufactured wk %d of %d. Edid version %d.%d\n",
- edid_data[EDID_MFG_WEEK], 1990 + edid_data[EDID_MFG_YEAR],
- edidver, edidrev);
- fprintf(outfile,
- "Input: %s, vid level %d, %s, %s %s %s %s sync, %dx%dcm, Gamma %f\n",
- (edid_data[EDID_VIDEO_IN] & 0x80) ? "digital" : "analog",
- (edid_data[EDID_VIDEO_IN] >> 5) & 3,
- (edid_data[EDID_VIDEO_IN] & 0x10) ? "Blank to black" : "",
- (edid_data[EDID_VIDEO_IN] & 0x08) ? "Separate" : "",
- (edid_data[EDID_VIDEO_IN] & 0x04) ? "Composite" : "",
- (edid_data[EDID_VIDEO_IN] & 0x02) ? "On-green" : "",
- (edid_data[EDID_VIDEO_IN] & 0x01) ? "Serration V" : "",
- edid_data[EDID_MAX_HSIZE], edid_data[EDID_MAX_VSIZE],
- 1.0 + ((float)edid_data[EDID_GAMMA] / 100.0));
-
- edid_features = edid_data[EDID_FEATURES];
- fprintf(outfile, "Features: %s %s %s %s %s %s %s\n",
- (edid_features & 0x80) ? "standby" : "",
- (edid_features & 0x40) ? "suspend" : "",
- (edid_features & 0x20) ? "active-off" : "",
- (edid_features & 0x18) ? "colour" : "monochrome",
- (edid_features & 0x04) ? "std-cspace" : "non-std-cspace",
- (edid_features & 0x02) ? "preferred-timing" : "",
- (edid_features & 0x01) ? "default-GTF" : "");
-
- fprintf(outfile, "Established Timing:\n");
- if (edid_data[EDID_ESTTIME1] & 0x80)
- fprintf(outfile, "720x400@70\n");
- if (edid_data[EDID_ESTTIME1] & 0x40)
- fprintf(outfile, "720x400@88\n");
- if (edid_data[EDID_ESTTIME1] & 0x20)
- fprintf(outfile, "640x480@60\n");
- if (edid_data[EDID_ESTTIME1] & 0x10)
- fprintf(outfile, "640x480@67\n");
- if (edid_data[EDID_ESTTIME1] & 0x08)
- fprintf(outfile, "640x480@72\n");
- if (edid_data[EDID_ESTTIME1] & 0x04)
- fprintf(outfile, "640x480@75\n");
- if (edid_data[EDID_ESTTIME1] & 0x02)
- fprintf(outfile, "800x600@56\n");
- if (edid_data[EDID_ESTTIME1] & 0x01)
- fprintf(outfile, "800x600@60\n");
- if (edid_data[EDID_ESTTIME2] & 0x80)
- fprintf(outfile, "800x600@72\n");
- if (edid_data[EDID_ESTTIME2] & 0x40)
- fprintf(outfile, "800x600@75\n");
- if (edid_data[EDID_ESTTIME2] & 0x20)
- fprintf(outfile, "832x624@75\n");
- if (edid_data[EDID_ESTTIME2] & 0x10)
- fprintf(outfile, "1024x768i@87\n");
- if (edid_data[EDID_ESTTIME2] & 0x08)
- fprintf(outfile, "1024x768@60\n");
- if (edid_data[EDID_ESTTIME2] & 0x04)
- fprintf(outfile, "1024x768@70\n");
- if (edid_data[EDID_ESTTIME2] & 0x02)
- fprintf(outfile, "1024x768@75\n");
- if (edid_data[EDID_ESTTIME2] & 0x01)
- fprintf(outfile, "1280x1024@75\n");
- if (edid_data[EDID_MFGTIME] & 0x80)
- fprintf(outfile, "1152x870@75\n");
-
- fprintf(outfile, "Standard timing:\n");
- for (i = 0; i < EDID_N_STDTIME; i++) {
- int hinfo = edid_data[EDID_STDTIMEH + 2 * i];
- int vinfo = edid_data[EDID_STDTIMEV + 2 * i];
- int hres, vres;
-
- /* 01 01 is pad by spec, but 00 00 and 20 20 are see in wild */
- if (((hinfo == 0x01) && (vinfo == 0x01)) ||
- ((hinfo == 0x00) && (vinfo == 0x00)) ||
- ((hinfo == 0x20) && (vinfo == 0x20)))
- continue;
- hres = (hinfo * 8) + 248;
- switch (vinfo >> 6) {
- case ASPECT_16_10:
- vres = (hres * 10) / 16;
- break;
- case ASPECT_4_3:
- vres = (hres * 3) / 4;
- break;
- case ASPECT_5_4:
- vres = (hres * 4) / 5;
- break;
- case ASPECT_16_9:
- vres = (hres * 9) / 16;
- break;
- /* Default only hit if compiler broken */
- default:
- vres = 0;
- }
- fprintf(outfile, "%d: %dx%d@%d\n", i, hres, vres,
- 60 + (vinfo & 0x3f));
- }
-
- fprintf(outfile, "Descriptor blocks:\n");
- for (i = 0; i < EDID_N_DTDS; i++)
- show_edid_dtd(outfile,
- edid_data + (EDID_DTD_BASE + i * DTD_SIZE));
- fprintf(outfile, "EDID contains %d extensions\n",
- edid_data[EDID_EXT_FLAG]);
-
- edid_ext = edid_data + EDID_SIZE;
-
- if ((ext >= 1) && (edid_data[EDID_EXT_FLAG] >= 1)) {
- unsigned char eext_tag = edid_ext[EEXT_TAG];
- if ((eext_tag == 0x02) && (edid_ext[EEXT_REV] == 0x03)) {
- show_cea_timing(outfile, edid_ext);
- } else {
- char *tagtype;
- switch (eext_tag) {
- case 0x01:
- tagtype = "LCD Timings";
- break;
- case 0x02:
- tagtype = "CEA";
- break;
- case 0x20:
- tagtype = "EDID 2.0";
- break;
- case 0x30:
- tagtype = "Color Information";
- break;
- case 0x40:
- tagtype = "DVI Feature";
- break;
- case 0x50:
- tagtype = "Touch Screen Map";
- break;
- case 0xF0:
- tagtype = "Block Map";
- break;
- case 0xFF:
- tagtype = "Manufacturer";
- break;
- default:
- tagtype = "Unknown";
- }
- fprintf(outfile,
- "EDID %s ext tag 0x%02x rev 0x%02x skipped\n",
- tagtype, edid_ext[EEXT_TAG],
- edid_ext[EEXT_REV]);
- }
- }
-}
-
-/* Pixel counts normally round to 8 */
-#define CLOSE_ENOUGH(a, b) (abs((a) - (b)) < 16)
-
-/* These match order of defines ASPECT_x_y in edid_utils.h */
-char *aspect_to_str[] = { "16:10", "4:3", "5:4", "16:9" };
-
-int find_aspect(int h, int v)
-{
- if (CLOSE_ENOUGH((h * 3), (v * 4)))
- return ASPECT_4_3;
- if (CLOSE_ENOUGH((h * 4), (v * 5)))
- return ASPECT_5_4;
- if (CLOSE_ENOUGH((h * 9), (v * 16)))
- return ASPECT_16_9;
- if (CLOSE_ENOUGH((h * 10), (v * 16)))
- return ASPECT_16_10;
-
- return -1;
-}
-
-int find_aspect_fromisize(unsigned char *edid_data)
-{
- int hsiz = edid_data[EDID_MAX_HSIZE];
- int vsiz = edid_data[EDID_MAX_VSIZE];
- int res;
-
- /* Zero size for projector */
- /* Only use this code if there was no preferred resolution */
- /* So assume it is an older 4:3 projector not a video one */
- if ((hsiz == 0) && (vsiz == 0))
- return ASPECT_4_3;
-
- res = find_aspect(hsiz, vsiz);
-
- /* If things didn't work out, assume the old 4:3 case */
- if (res < 0)
- return ASPECT_4_3;
- else
- return res;
-}
-
-int edid_get_monitor_name(const unsigned char *edid_data, char *buf,
- unsigned int buf_size)
-{
- int i;
- const unsigned char *dtd;
-
- for (i = 0; i < EDID_N_DTDS; i++) {
- dtd = edid_data + (EDID_DTD_BASE + i * DTD_SIZE);
- if (dtd[DTD_PCLK_LO] == 0x00 && dtd[DTD_PCLK_HI] == 0x00 &&
- dtd[DTD_TYPETAG] == DTDTYPE_NAME) {
- get_dtd_string((const char *)dtd + DTD_STRING, buf,
- buf_size);
- return 0;
- }
- }
-
- return -1;
-}
diff --git a/cras/src/common/edid_utils.h b/cras/src/common/edid_utils.h
deleted file mode 100644
index b43a6bc8..00000000
--- a/cras/src/common/edid_utils.h
+++ /dev/null
@@ -1,204 +0,0 @@
-// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef __EDID_UTILS_H__
-#define __EDID_UTILS_H__
-
-#include "stdio.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* These match the EDID encoding for Standard Timing block */
-#define ASPECT_16_10 0
-#define ASPECT_4_3 1
-#define ASPECT_5_4 2
-#define ASPECT_16_9 3
-#define N_ASPECTS 4
-
-/* Defines based on EDID and CEA-861D descriptions */
-#define EDID_HDR 0
-#define EDID_MFG_EID 0x8
-#define EDID_MFG_PROD_LO 0x0A
-#define EDID_MFG_PROD_HI 0x0B
-#define EDID_MFG_SERIAL 0x0C
-#define EDID_MFG_WEEK 0x10
-#define EDID_MFG_YEAR 0x11
-#define EDID_VERSION 0x12
-#define EDID_REVISION 0x13
-#define EDID_VIDEO_IN 0x14
-#define EDID_MAX_HSIZE 0x15
-#define EDID_MAX_VSIZE 0x16
-#define EDID_GAMMA 0x17
-#define EDID_FEATURES 0x18
-
-#define EDID_ESTTIME1 0x23
-#define EDID_ESTTIME2 0x24
-#define EDID_MFGTIME 0x25
-/* Next two repeat 8 times for standard timings 1-8 */
-#define EDID_STDTIMEH 0x26
-#define EDID_STDTIMEV 0x27
-#define EDID_N_STDTIME 8
-
-/* There are 4 DTD blocks in the EDID */
-#define EDID_DTD_BASE 0x36
-#define EDID_N_DTDS 4
-
-#define EDID_EXT_FLAG 0x7E
-#define EDID_CSUM 0x7F
-#define EDID_SIZE 0x80
-
-#define EEXT_TAG 0
-#define EEXT_REV 1
-#define EEXT_SIZE 0x80
-
-#define EEDID_SIZE (EDID_SIZE + EEXT_SIZE)
-
-/* 2 byte standard timing structure */
-#define STDTIME_HBASE 248
-#define STDTIME_HMULT 8
-#define STDTIME_VASPECT_SHIFT 6
-#define STDTIME_VREFMINUS60_MASK 0x3f
-#define STDTIME_SIZE 2
-
-/* 18 byte DTD structure */
-#define DTD_PCLK_LO 0
-#define DTD_PCLK_HI 1
-#define DTD_HA_LO 2
-#define DTD_HBL_LO 3
-#define DTD_HABL_HI 4
-#define DTD_VA_LO 5
-#define DTD_VBL_LO 6
-#define DTD_VABL_HI 7
-#define DTD_HSO_LO 8
-#define DTD_HSW_LO 9
-#define DTD_VSX_LO 10
-#define DTD_HVSX_HI 11
-#define DTD_HSIZE_LO 12
-#define DTD_VSIZE_LO 13
-#define DTD_HVSIZE_HI 14
-#define DTD_HBORDER 15
-#define DTD_VBORDER 16
-#define DTD_FLAGS 17
-#define DTD_SIZE 18
-
-/* These apply when PCLK is zero */
-#define DTD_TYPETAG 3
-#define DTD_STRING 5
-#define DTD_MINV_HZ 5
-#define DTD_MAXV_HZ 6
-#define DTD_MINH_kHZ 7
-#define DTD_MAXH_kHZ 8
-#define DTD_MAXCLK_100kHZ 9
-
-/* Types in the TYPETAG field */
-#define DTDTYPE_MANUF 0x0f
-#define DTDTYPE_STDTIME 0xfa
-#define DTDTYPE_COLPOINT 0xfb
-#define DTDTYPE_NAME 0xfc
-#define DTDTYPE_LIMITS 0xfd
-#define DTDTYPE_STRING 0xfe
-#define DTDTYPE_SERIAL 0xff
-
-/* This is the CEA extension version 3 */
-#define CEA_TAG 0
-#define CEA_REV 1
-#define CEA_DTD_OFFSET 2
-/* Next two are low nibble, high nibble of same byte */
-#define CEA_NATIVE_DTDS 3
-#define CEA_SUPPORT 3
-#define CEA_DBC_START 4
-/* Last DBC is at [CEA_DTD_OFFSET]-1, first DTD is at [CEA_DTD_OFFSET] */
-/* Padding needs min of two (gives PCLK=00 in DTD) */
-#define CEA_LAST_PAD 125
-#define CEA_END_PAD 126
-#define CEA_CHECKSUM 127
-
-/* Data Block Collections */
-/* Same byte: upper 3 bits tag, low five length */
-#define DBC_TAG_LENGTH 0
-#define DBC_LEN_MASK 0x1f
-#define DBC_TAG_SHIFT 5
-#define DBC_ETAG 1
-
-#define DBCA_FORMAT 0
-#define DBCA_RATE 1
-#define DBCA_INFO 2
-#define DBCA_SIZE 3
-
-#define DBCA_FMT_LPCM 1
-
-#define DBCV_CODE 0
-#define DBCV_SIZE 1
-
-#define DBCVND_IEEE_LO 0
-#define DBCVND_IEEE_MID 1
-#define DBCVND_IEEE_HI 2
-
-#define DBCVHDMI_CEC_LO 3
-#define DBCVHDMI_CEC_HI 4
-#define DBCVHDMI_SUPPORT 5
-#define DBCVHDMI_MAXTMDS_5MHz 6
-#define DBCVHDMI_LATFLAGS 7
-#define DBCVHDMI_VLAT 8
-#define DBCVHDMI_ALAT 9
-#define DBCVHDMI_IVLAT 10
-#define DBCVHDMI_IALAT 11
-
-#define DBCSP_ALLOC 0
-#define DBCSP_SIZE 3
-
-#define DBC_TAG_AUDIO 1
-#define DBC_TAG_VIDEO 2
-#define DBC_TAG_VENDOR 3
-#define DBC_TAG_SPEAKER 4
-#define DBC_TAG_VESA 5
-#define DBC_TAG_EXTENDED 7
-
-#define DBC_ETAG_VCDB 0
-#define DBC_ETAG_VENDOR_VDB 1
-#define DBC_ETAG_COL 5
-
-#define VCDB_TAG 0
-#define VCDB_ETAG 1
-#define VCDB_FLAGS 2
-#define VCDB_S_PT(x) (((x)&0x30) >> 4)
-#define VCDB_S_IT(x) (((x)&0x0C) >> 2)
-#define VCDB_S_CE(x) (((x)&0x03))
-
-#define COL_TAG 0
-#define COL_ETAG 1
-#define COL_FLAGS 2
-#define COL_META 3
-
-/* Number of test EDID arrays available to get/show_test_edid */
-#define N_TEST_EDIDS 6
-
-int edid_valid(const unsigned char *edid_data);
-int edid_has_hdmi_info(const unsigned char *edid_data, int ext);
-int edid_lpcm_support(const unsigned char *edid_data, int ext);
-void show_edid_data(FILE *outfile, unsigned char *edid_data, int items,
- int base);
-void show_edid(FILE *outfile, unsigned char *edid_data, int ext);
-int find_aspect(int h, int v);
-int find_aspect_fromisize(unsigned char *edid_data);
-extern char *aspect_to_str[];
-int get_test_edid(int n, unsigned char *dst);
-int show_test_edid(FILE *outfile, int n);
-
-/* Gets monitor name from EDID.
- * Args:
- * edid_data - EDID data.
- * buf - buffer to store monitor name.
- * buf_size - buffer size.
- */
-int edid_get_monitor_name(const unsigned char *edid_data, char *buf,
- unsigned int buf_size);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif
diff --git a/cras/src/common/packet_status_logger.c b/cras/src/common/packet_status_logger.c
deleted file mode 100644
index f1be6965..00000000
--- a/cras/src/common/packet_status_logger.c
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <string.h>
-#include <time.h>
-
-#include "cras_util.h"
-#include "packet_status_logger.h"
-
-void packet_status_logger_init(struct packet_status_logger *logger)
-{
- memset(logger->data, 0, PACKET_STATUS_LEN_BYTES);
- logger->size = PACKET_STATUS_LEN_BYTES * 8;
- logger->wp = 0;
- logger->num_wraps = 0;
- clock_gettime(CLOCK_MONOTONIC_RAW, &logger->ts);
-}
-
-void packet_status_logger_update(struct packet_status_logger *logger, bool val)
-{
- if (val) {
- logger->data[logger->wp / 8] |= 1UL << (logger->wp % 8);
- } else {
- logger->data[logger->wp / 8] &= ~(1UL << (logger->wp % 8));
- }
- logger->wp++;
- if (logger->wp >= logger->size) {
- logger->wp %= logger->size;
- logger->num_wraps += 1;
- }
- if (logger->wp == 0 || (logger->num_wraps == 0 && logger->wp == 1))
- clock_gettime(CLOCK_MONOTONIC_RAW, &logger->ts);
-}
diff --git a/cras/src/common/packet_status_logger.h b/cras/src/common/packet_status_logger.h
deleted file mode 100644
index 3bc90041..00000000
--- a/cras/src/common/packet_status_logger.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef PACKET_STATUS_LOGGER_
-#define PACKET_STATUS_LOGGER_
-
-#include <stdint.h>
-#include <stdbool.h>
-
-#define PACKET_STATUS_LEN_BYTES 64
-#define WBS_FRAME_NS 7500000
-
-/* Avoid 32, 40, 64 consecutive hex characters so CrOS feedback redact
- * tool doesn't trim our dump. */
-#define PACKET_STATUS_LOG_LINE_WRAP 50
-
-/*
- * Object to log consecutive packets' status.
- * Members:
- * data - Bytes to store packets' status.
- * size - Total number of bits in |data|.
- * wp - Position of the next bit to log packet status.
- * num_wraps - Number of times the ring buffer has wrapped.
- * ts - The timestamp of the last time when the first bit of |data| updated.
- */
-struct packet_status_logger {
- uint8_t data[PACKET_STATUS_LEN_BYTES];
- int size;
- int wp;
- int num_wraps;
- struct timespec ts;
-};
-
-/* Initializes the packet status logger. */
-void packet_status_logger_init(struct packet_status_logger *logger);
-
-/* Updates the next packet status to logger. */
-void packet_status_logger_update(struct packet_status_logger *logger, bool val);
-
-/* Rewinds logger's time stamp to calculate the beginning.
- * If logger's ring buffer hasn't wrapped, simply return logger_ts.
- * Otherwise beginning_ts = logger_ts - WBS_FRAME_NS * (size - wp)
- */
-static inline void
-packet_status_logger_begin_ts(const struct packet_status_logger *logger,
- struct timespec *ts)
-{
- long nsec = WBS_FRAME_NS * (logger->size - logger->wp);
-
- *ts = logger->ts;
- if (logger->num_wraps == 0)
- return;
- while (nsec > 1000000000L) {
- ts->tv_sec--;
- nsec -= 1000000000L;
- }
- ts->tv_nsec -= nsec;
- if (ts->tv_nsec < 0) {
- ts->tv_sec--;
- ts->tv_nsec += 1000000000L;
- }
-}
-
-/* Fast-forwards the logger's time stamp to calculate the end.
- * In other words, end_ts = logger_ts + WBS_FRAME_NS * wp
- */
-static inline void
-packet_status_logger_end_ts(const struct packet_status_logger *logger,
- struct timespec *ts)
-{
- *ts = logger->ts;
- ts->tv_nsec += WBS_FRAME_NS * logger->wp;
- while (ts->tv_nsec > 1000000000L) {
- ts->tv_sec++;
- ts->tv_nsec -= 1000000000L;
- }
-}
-
-/* Prints the logger data in hex format */
-static inline void
-packet_status_logger_dump_hex(const struct packet_status_logger *logger)
-{
- int i = logger->wp / 8;
-
- /* Print the bits after wp only if buffer has wrapped. */
- if (logger->num_wraps) {
- if (logger->wp % 8)
- printf("%.2x",
- logger->data[i] & (0xff << (logger->wp % 8)));
- for (; i < PACKET_STATUS_LEN_BYTES; i++)
- printf("%.2x", logger->data[i]);
- }
- for (i = 0; i < logger->wp / 8; i++)
- printf("%.2x", logger->data[i]);
- if (logger->wp % 8)
- printf("%.2x", logger->data[i] & (~(0xff << (logger->wp % 8))));
- printf("\n");
-}
-
-/* Prints the logger data in binary format */
-static inline void
-packet_status_logger_dump_binary(const struct packet_status_logger *logger)
-{
- /* Don't print the bits after wp if buffer hasn't wrapped. */
- int head = logger->num_wraps ? logger->wp : 0;
- int len = logger->num_wraps ? logger->size : logger->wp;
- int i, j;
-
- for (i = 0; i < len; ++i) {
- j = (head + i) % logger->size;
- printf("%d", (logger->data[j / 8] >> (j % 8)) & 1U);
- if ((i + 1) % PACKET_STATUS_LOG_LINE_WRAP == 0)
- printf("\n");
- }
- /* Fill indicator digit 'D' until the last line wraps. */
- if (len % PACKET_STATUS_LOG_LINE_WRAP) {
- while (len % PACKET_STATUS_LOG_LINE_WRAP) {
- printf("D");
- ++len;
- }
- printf("\n");
- }
-}
-
-#endif /* PACKET_STATUS_LOGGER_ */
diff --git a/cras/src/common/rtp.h b/cras/src/common/rtp.h
deleted file mode 100644
index d0fb14af..00000000
--- a/cras/src/common/rtp.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- *
- * BlueZ - Bluetooth protocol stack for Linux
- *
- * Copyright (C) 2004-2010 Marcel Holtmann <marcel@holtmann.org>
- *
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
- *
- */
-
-#if __BYTE_ORDER == __LITTLE_ENDIAN
-
-struct rtp_header {
- unsigned cc : 4;
- unsigned x : 1;
- unsigned p : 1;
- unsigned v : 2;
-
- unsigned pt : 7;
- unsigned m : 1;
-
- uint16_t sequence_number;
- uint32_t timestamp;
- uint32_t ssrc;
- uint32_t csrc[0];
-} __attribute__((packed));
-
-struct rtp_payload {
- unsigned frame_count : 4;
- unsigned rfa0 : 1;
- unsigned is_last_fragment : 1;
- unsigned is_first_fragment : 1;
- unsigned is_fragmented : 1;
-} __attribute__((packed));
-
-#elif __BYTE_ORDER == __BIG_ENDIAN
-
-struct rtp_header {
- unsigned v : 2;
- unsigned p : 1;
- unsigned x : 1;
- unsigned cc : 4;
-
- unsigned m : 1;
- unsigned pt : 7;
-
- uint16_t sequence_number;
- uint32_t timestamp;
- uint32_t ssrc;
- uint32_t csrc[0];
-} __attribute__((packed));
-
-struct rtp_payload {
- unsigned is_fragmented : 1;
- unsigned is_first_fragment : 1;
- unsigned is_last_fragment : 1;
- unsigned rfa0 : 1;
- unsigned frame_count : 4;
-} __attribute__((packed));
-
-#else
-#error "Unknown byte order"
-#endif
diff --git a/cras/src/common/sfh.c b/cras/src/common/sfh.c
deleted file mode 100644
index 56ac755f..00000000
--- a/cras/src/common/sfh.c
+++ /dev/null
@@ -1,92 +0,0 @@
-/* Copyright (c) 2010, Paul Hsieh
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- * * Neither my name, Paul Hsieh, nor the names of any other contributors to the
- * code use may not be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <stddef.h>
-#include <stdint.h>
-
-#undef get16bits
-#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) || \
- defined(_MSC_VER) || defined(__BORLANDC__) || defined(__TURBOC__)
-#define get16bits(d) (*((const uint16_t *)(d)))
-#endif
-
-#if !defined(get16bits)
-#define get16bits(d) \
- ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) + \
- (uint32_t)(((const uint8_t *)(d))[0]))
-#endif
-
-uint32_t SuperFastHash(const char *data, int len, uint32_t hash)
-{
- uint32_t tmp;
- int rem;
-
- if (len <= 0 || data == NULL)
- return 0;
-
- rem = len & 3;
- len >>= 2;
-
- /* Main loop */
- for (; len > 0; len--) {
- hash += get16bits(data);
- tmp = (get16bits(data + 2) << 11) ^ hash;
- hash = (hash << 16) ^ tmp;
- data += 2 * sizeof(uint16_t);
- hash += hash >> 11;
- }
-
- /* Handle end cases */
- switch (rem) {
- case 3:
- hash += get16bits(data);
- hash ^= hash << 16;
- hash ^= ((signed char)data[sizeof(uint16_t)]) << 18;
- hash += hash >> 11;
- break;
- case 2:
- hash += get16bits(data);
- hash ^= hash << 11;
- hash += hash >> 17;
- break;
- case 1:
- hash += (signed char)*data;
- hash ^= hash << 10;
- hash += hash >> 1;
- }
-
- /* Force "avalanching" of final 127 bits */
- hash ^= hash << 3;
- hash += hash >> 5;
- hash ^= hash << 4;
- hash += hash >> 17;
- hash ^= hash << 25;
- hash += hash >> 6;
-
- return hash;
-}
diff --git a/cras/src/common/sfh.h b/cras/src/common/sfh.h
deleted file mode 100644
index f68fc911..00000000
--- a/cras/src/common/sfh.h
+++ /dev/null
@@ -1,16 +0,0 @@
-/* Copyright (c) 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * An incremental version of the SuperFastHash hash function from
- * http://www.azillionmonkeys.com/qed/hash.html
- * The code did not come with its own header file, so declaring the function
- * here.
- */
-
-#ifndef SFH_H_
-#define SFH_H_
-
-uint32_t SuperFastHash(const char *data, int len, uint32_t hash);
-
-#endif /* SFH_H_ */
diff --git a/cras/src/common/utlist.h b/cras/src/common/utlist.h
deleted file mode 100644
index 6c7f1e32..00000000
--- a/cras/src/common/utlist.h
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
-Copyright (c) 2007-2011, Troy D. Hanson http://uthash.sourceforge.net
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef UTLIST_H
-#define UTLIST_H
-
-#define UTLIST_VERSION 1.9.4
-
-#include <assert.h>
-
-/*
- * This file contains macros to manipulate singly and doubly-linked lists.
- *
- * 1. LL_ macros: singly-linked lists.
- * 2. DL_ macros: doubly-linked lists.
- * 3. CDL_ macros: circular doubly-linked lists.
- *
- * To use singly-linked lists, your structure must have a "next" pointer.
- * To use doubly-linked lists, your structure must "prev" and "next" pointers.
- * Either way, the pointer to the head of the list must be initialized to NULL.
- *
- * ----------------.EXAMPLE -------------------------
- * struct item {
- * int id;
- * struct item *prev, *next;
- * }
- *
- * struct item *list = NULL:
- *
- * int main() {
- * struct item *item;
- * ... allocate and populate item ...
- * DL_APPEND(list, item);
- * }
- * --------------------------------------------------
- *
- * For doubly-linked lists, the append and delete macros are O(1)
- * For singly-linked lists, append and delete are O(n) but prepend is O(1)
- */
-
-/******************************************************************************
- * Singly linked list macros (non-circular).
- *****************************************************************************/
-#define LL_PREPEND(head, add) \
- do { \
- (add)->next = head; \
- head = add; \
- } while (0)
-
-#define LL_CONCAT(head1, head2) \
- do { \
- __typeof(head1) _tmp; \
- if (head1) { \
- _tmp = head1; \
- while (_tmp->next) \
- _tmp = _tmp->next; \
- _tmp->next = (head2); \
- } else \
- (head1) = (head2); \
- } while (0)
-
-#define LL_APPEND(head, add) \
- do { \
- __typeof(head) _tmp; \
- (add)->next = NULL; \
- if (head) { \
- _tmp = head; \
- while (_tmp->next) \
- _tmp = _tmp->next; \
- _tmp->next = (add); \
- } else { \
- (head) = (add); \
- } \
- } while (0)
-
-#define LL_DELETE(head, del) \
- do { \
- __typeof(head) _tmp; \
- if ((head) == (del)) \
- (head) = (head)->next; \
- else { \
- _tmp = head; \
- while (_tmp->next && (_tmp->next != (del))) \
- _tmp = _tmp->next; \
- if (_tmp->next) \
- _tmp->next = ((del)->next); \
- } \
- } while (0)
-
-#define LL_FOREACH(head, el) for (el = head; el; el = el->next)
-
-#define LL_FOREACH_SAFE(head, el, tmp) \
- for ((el) = (head); (el) && (tmp = (el)->next, 1); (el) = tmp)
-
-#define LL_SEARCH_SCALAR(head, out, field, val) \
- do { \
- LL_FOREACH (head, out) \
- if ((out)->field == (val)) \
- break; \
- } while (0)
-
-#define LL_SEARCH_SCALAR_WITH_CAST(head, out, nout, field, val) \
- do { \
- LL_FOREACH (head, out) { \
- (nout) = (__typeof(nout))out; \
- if ((nout)->field == (val)) \
- break; \
- (nout) = 0; \
- } \
- } while (0)
-
-#define LL_SEARCH(head, out, elt, cmp) \
- do { \
- LL_FOREACH (head, out) \
- if ((cmp(out, elt)) == 0) \
- break; \
- } while (0)
-
-/******************************************************************************
- * Doubly linked list macros (non-circular).
- *****************************************************************************/
-#define DL_PREPEND(head, add) \
- do { \
- (add)->next = head; \
- if (head) { \
- (add)->prev = (head)->prev; \
- (head)->prev = (add); \
- } else \
- (add)->prev = (add); \
- (head) = (add); \
- } while (0)
-
-#define DL_APPEND(head, add) \
- do { \
- if (head) { \
- (add)->prev = (head)->prev; \
- (head)->prev->next = (add); \
- (head)->prev = (add); \
- (add)->next = NULL; \
- } else { \
- (head) = (add); \
- (head)->prev = (head); \
- (head)->next = NULL; \
- } \
- } while (0)
-
-#define DL_INSERT(head, next_node, add) \
- do { \
- if (head == next_node) \
- DL_PREPEND(head, add); \
- else if (next_node == NULL) { \
- DL_APPEND(head, add); \
- } else { \
- (add)->prev = (next_node)->prev; \
- (next_node)->prev->next = (add); \
- (add)->next = (next_node); \
- (next_node)->prev = (add); \
- } \
- } while (0)
-
-#define DL_CONCAT(head1, head2) \
- do { \
- __typeof(head1) _tmp; \
- if (head2) { \
- if (head1) { \
- _tmp = (head2)->prev; \
- (head2)->prev = (head1)->prev; \
- (head1)->prev->next = (head2); \
- (head1)->prev = _tmp; \
- } else \
- (head1) = (head2); \
- } \
- } while (0)
-
-#define DL_DELETE(head, del) \
- do { \
- assert((head) != NULL); \
- assert((del)->prev != NULL); \
- if ((del)->prev == (del)) { \
- (head) = NULL; \
- } else if ((del) == (head)) { \
- (del)->next->prev = (del)->prev; \
- (head) = (del)->next; \
- } else { \
- (del)->prev->next = (del)->next; \
- if ((del)->next) \
- (del)->next->prev = (del)->prev; \
- else \
- (head)->prev = (del)->prev; \
- } \
- } while (0)
-
-/* Create a variable name using given prefix and current line number. */
-#define MAKE_NAME(prefix) TOKEN_PASTE2(prefix, __LINE__)
-#define TOKEN_PASTE2(x, y) TOKEN_PASTE(x, y)
-#define TOKEN_PASTE(x, y) x##y
-
-/* This version creates a temporary variable to to make it safe for deleting the
- * elements during iteration. */
-#define DL_FOREACH(head, el) \
- DL_FOREACH_INTERNAL (head, el, MAKE_NAME(_dl_foreach_))
-#define DL_FOREACH_INTERNAL(head, el, tmp) \
- __typeof__(el) tmp; \
- for ((el) = (head); (el) && (tmp = (el)->next, 1); (el) = tmp)
-
-/* These are identical to their singly-linked list counterparts. */
-#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR
-#define DL_SEARCH_SCALAR_WITH_CAST LL_SEARCH_SCALAR_WITH_CAST
-#define DL_SEARCH LL_SEARCH
-
-#endif /* UTLIST_H */
diff --git a/cras/src/dsp/biquad.c b/cras/src/dsp/biquad.c
deleted file mode 100644
index 337a4393..00000000
--- a/cras/src/dsp/biquad.c
+++ /dev/null
@@ -1,381 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Copyright (C) 2010 Google Inc. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE.WEBKIT file.
- */
-
-#include <math.h>
-#include "biquad.h"
-
-#ifndef max
-#define max(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a > _b ? _a : _b; \
- })
-#endif
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#endif
-
-static void set_coefficient(struct biquad *bq, double b0, double b1, double b2,
- double a0, double a1, double a2)
-{
- double a0_inv = 1 / a0;
- bq->b0 = b0 * a0_inv;
- bq->b1 = b1 * a0_inv;
- bq->b2 = b2 * a0_inv;
- bq->a1 = a1 * a0_inv;
- bq->a2 = a2 * a0_inv;
-}
-
-static void biquad_lowpass(struct biquad *bq, double cutoff, double resonance)
-{
- /* Limit cutoff to 0 to 1. */
- cutoff = max(0.0, min(cutoff, 1.0));
-
- if (cutoff == 1 || cutoff == 0) {
- /* When cutoff is 1, the z-transform is 1.
- * When cutoff is zero, nothing gets through the filter, so set
- * coefficients up correctly.
- */
- set_coefficient(bq, cutoff, 0, 0, 1, 0, 0);
- return;
- }
-
- /* Compute biquad coefficients for lowpass filter */
- resonance = max(0.0, resonance); /* can't go negative */
- double g = pow(10.0, 0.05 * resonance);
- double d = sqrt((4 - sqrt(16 - 16 / (g * g))) / 2);
-
- double theta = M_PI * cutoff;
- double sn = 0.5 * d * sin(theta);
- double beta = 0.5 * (1 - sn) / (1 + sn);
- double gamma = (0.5 + beta) * cos(theta);
- double alpha = 0.25 * (0.5 + beta - gamma);
-
- double b0 = 2 * alpha;
- double b1 = 2 * 2 * alpha;
- double b2 = 2 * alpha;
- double a1 = 2 * -gamma;
- double a2 = 2 * beta;
-
- set_coefficient(bq, b0, b1, b2, 1, a1, a2);
-}
-
-static void biquad_highpass(struct biquad *bq, double cutoff, double resonance)
-{
- /* Limit cutoff to 0 to 1. */
- cutoff = max(0.0, min(cutoff, 1.0));
-
- if (cutoff == 1 || cutoff == 0) {
- /* When cutoff is one, the z-transform is 0. */
- /* When cutoff is zero, we need to be careful because the above
- * gives a quadratic divided by the same quadratic, with poles
- * and zeros on the unit circle in the same place. When cutoff
- * is zero, the z-transform is 1.
- */
- set_coefficient(bq, 1 - cutoff, 0, 0, 1, 0, 0);
- return;
- }
-
- /* Compute biquad coefficients for highpass filter */
- resonance = max(0.0, resonance); /* can't go negative */
- double g = pow(10.0, 0.05 * resonance);
- double d = sqrt((4 - sqrt(16 - 16 / (g * g))) / 2);
-
- double theta = M_PI * cutoff;
- double sn = 0.5 * d * sin(theta);
- double beta = 0.5 * (1 - sn) / (1 + sn);
- double gamma = (0.5 + beta) * cos(theta);
- double alpha = 0.25 * (0.5 + beta + gamma);
-
- double b0 = 2 * alpha;
- double b1 = 2 * -2 * alpha;
- double b2 = 2 * alpha;
- double a1 = 2 * -gamma;
- double a2 = 2 * beta;
-
- set_coefficient(bq, b0, b1, b2, 1, a1, a2);
-}
-
-static void biquad_bandpass(struct biquad *bq, double frequency, double Q)
-{
- /* No negative frequencies allowed. */
- frequency = max(0.0, frequency);
-
- /* Don't let Q go negative, which causes an unstable filter. */
- Q = max(0.0, Q);
-
- if (frequency <= 0 || frequency >= 1) {
- /* When the cutoff is zero, the z-transform approaches 0, if Q
- * > 0. When both Q and cutoff are zero, the z-transform is
- * pretty much undefined. What should we do in this case?
- * For now, just make the filter 0. When the cutoff is 1, the
- * z-transform also approaches 0.
- */
- set_coefficient(bq, 0, 0, 0, 1, 0, 0);
- return;
- }
- if (Q <= 0) {
- /* When Q = 0, the above formulas have problems. If we
- * look at the z-transform, we can see that the limit
- * as Q->0 is 1, so set the filter that way.
- */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- return;
- }
-
- double w0 = M_PI * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = alpha;
- double b1 = 0;
- double b2 = -alpha;
- double a0 = 1 + alpha;
- double a1 = -2 * k;
- double a2 = 1 - alpha;
-
- set_coefficient(bq, b0, b1, b2, a0, a1, a2);
-}
-
-static void biquad_lowshelf(struct biquad *bq, double frequency, double db_gain)
-{
- /* Clip frequencies to between 0 and 1, inclusive. */
- frequency = max(0.0, min(frequency, 1.0));
-
- double A = pow(10.0, db_gain / 40);
-
- if (frequency == 1) {
- /* The z-transform is a constant gain. */
- set_coefficient(bq, A * A, 0, 0, 1, 0, 0);
- return;
- }
- if (frequency <= 0) {
- /* When frequency is 0, the z-transform is 1. */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- return;
- }
-
- double w0 = M_PI * frequency;
- double S = 1; /* filter slope (1 is max value) */
- double alpha = 0.5 * sin(w0) * sqrt((A + 1 / A) * (1 / S - 1) + 2);
- double k = cos(w0);
- double k2 = 2 * sqrt(A) * alpha;
- double a_plus_one = A + 1;
- double a_minus_one = A - 1;
-
- double b0 = A * (a_plus_one - a_minus_one * k + k2);
- double b1 = 2 * A * (a_minus_one - a_plus_one * k);
- double b2 = A * (a_plus_one - a_minus_one * k - k2);
- double a0 = a_plus_one + a_minus_one * k + k2;
- double a1 = -2 * (a_minus_one + a_plus_one * k);
- double a2 = a_plus_one + a_minus_one * k - k2;
-
- set_coefficient(bq, b0, b1, b2, a0, a1, a2);
-}
-
-static void biquad_highshelf(struct biquad *bq, double frequency,
- double db_gain)
-{
- /* Clip frequencies to between 0 and 1, inclusive. */
- frequency = max(0.0, min(frequency, 1.0));
-
- double A = pow(10.0, db_gain / 40);
-
- if (frequency == 1) {
- /* The z-transform is 1. */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- return;
- }
- if (frequency <= 0) {
- /* When frequency = 0, the filter is just a gain, A^2. */
- set_coefficient(bq, A * A, 0, 0, 1, 0, 0);
- return;
- }
-
- double w0 = M_PI * frequency;
- double S = 1; /* filter slope (1 is max value) */
- double alpha = 0.5 * sin(w0) * sqrt((A + 1 / A) * (1 / S - 1) + 2);
- double k = cos(w0);
- double k2 = 2 * sqrt(A) * alpha;
- double a_plus_one = A + 1;
- double a_minus_one = A - 1;
-
- double b0 = A * (a_plus_one + a_minus_one * k + k2);
- double b1 = -2 * A * (a_minus_one + a_plus_one * k);
- double b2 = A * (a_plus_one + a_minus_one * k - k2);
- double a0 = a_plus_one - a_minus_one * k + k2;
- double a1 = 2 * (a_minus_one - a_plus_one * k);
- double a2 = a_plus_one - a_minus_one * k - k2;
-
- set_coefficient(bq, b0, b1, b2, a0, a1, a2);
-}
-
-static void biquad_peaking(struct biquad *bq, double frequency, double Q,
- double db_gain)
-{
- /* Clip frequencies to between 0 and 1, inclusive. */
- frequency = max(0.0, min(frequency, 1.0));
-
- /* Don't let Q go negative, which causes an unstable filter. */
- Q = max(0.0, Q);
-
- double A = pow(10.0, db_gain / 40);
-
- if (frequency <= 0 || frequency >= 1) {
- /* When frequency is 0 or 1, the z-transform is 1. */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- return;
- }
- if (Q <= 0) {
- /* When Q = 0, the above formulas have problems. If we
- * look at the z-transform, we can see that the limit
- * as Q->0 is A^2, so set the filter that way.
- */
- set_coefficient(bq, A * A, 0, 0, 1, 0, 0);
- return;
- }
-
- double w0 = M_PI * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = 1 + alpha * A;
- double b1 = -2 * k;
- double b2 = 1 - alpha * A;
- double a0 = 1 + alpha / A;
- double a1 = -2 * k;
- double a2 = 1 - alpha / A;
-
- set_coefficient(bq, b0, b1, b2, a0, a1, a2);
-}
-
-static void biquad_notch(struct biquad *bq, double frequency, double Q)
-{
- /* Clip frequencies to between 0 and 1, inclusive. */
- frequency = max(0.0, min(frequency, 1.0));
-
- /* Don't let Q go negative, which causes an unstable filter. */
- Q = max(0.0, Q);
-
- if (frequency <= 0 || frequency >= 1) {
- /* When frequency is 0 or 1, the z-transform is 1. */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- return;
- }
- if (Q <= 0) {
- /* When Q = 0, the above formulas have problems. If we
- * look at the z-transform, we can see that the limit
- * as Q->0 is 0, so set the filter that way.
- */
- set_coefficient(bq, 0, 0, 0, 1, 0, 0);
- return;
- }
-
- double w0 = M_PI * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = 1;
- double b1 = -2 * k;
- double b2 = 1;
- double a0 = 1 + alpha;
- double a1 = -2 * k;
- double a2 = 1 - alpha;
-
- set_coefficient(bq, b0, b1, b2, a0, a1, a2);
-}
-
-static void biquad_allpass(struct biquad *bq, double frequency, double Q)
-{
- /* Clip frequencies to between 0 and 1, inclusive. */
- frequency = max(0.0, min(frequency, 1.0));
-
- /* Don't let Q go negative, which causes an unstable filter. */
- Q = max(0.0, Q);
-
- if (frequency <= 0 || frequency >= 1) {
- /* When frequency is 0 or 1, the z-transform is 1. */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- return;
- }
-
- if (Q <= 0) {
- /* When Q = 0, the above formulas have problems. If we
- * look at the z-transform, we can see that the limit
- * as Q->0 is -1, so set the filter that way.
- */
- set_coefficient(bq, -1, 0, 0, 1, 0, 0);
- return;
- }
-
- double w0 = M_PI * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = 1 - alpha;
- double b1 = -2 * k;
- double b2 = 1 + alpha;
- double a0 = 1 + alpha;
- double a1 = -2 * k;
- double a2 = 1 - alpha;
-
- set_coefficient(bq, b0, b1, b2, a0, a1, a2);
-}
-
-void biquad_set(struct biquad *bq, enum biquad_type type, double freq, double Q,
- double gain)
-{
- /* Default is an identity filter. Also clear history values. */
- set_coefficient(bq, 1, 0, 0, 1, 0, 0);
- bq->x1 = 0;
- bq->x2 = 0;
- bq->y1 = 0;
- bq->y2 = 0;
-
- switch (type) {
- case BQ_LOWPASS:
- biquad_lowpass(bq, freq, Q);
- break;
- case BQ_HIGHPASS:
- biquad_highpass(bq, freq, Q);
- break;
- case BQ_BANDPASS:
- biquad_bandpass(bq, freq, Q);
- break;
- case BQ_LOWSHELF:
- biquad_lowshelf(bq, freq, gain);
- break;
- case BQ_HIGHSHELF:
- biquad_highshelf(bq, freq, gain);
- break;
- case BQ_PEAKING:
- biquad_peaking(bq, freq, Q, gain);
- break;
- case BQ_NOTCH:
- biquad_notch(bq, freq, Q);
- break;
- case BQ_ALLPASS:
- biquad_allpass(bq, freq, Q);
- break;
- case BQ_NONE:
- break;
- }
-}
diff --git a/cras/src/dsp/biquad.h b/cras/src/dsp/biquad.h
deleted file mode 100644
index c584aa96..00000000
--- a/cras/src/dsp/biquad.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef BIQUAD_H_
-#define BIQUAD_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* The biquad filter parameters. The transfer function H(z) is (b0 + b1 * z^(-1)
- * + b2 * z^(-2)) / (1 + a1 * z^(-1) + a2 * z^(-2)). The previous two inputs
- * are stored in x1 and x2, and the previous two outputs are stored in y1 and
- * y2.
- *
- * We use double during the coefficients calculation for better accurary, but
- * float is used during the actual filtering for faster computation.
- */
-struct biquad {
- float b0, b1, b2;
- float a1, a2;
- float x1, x2;
- float y1, y2;
-};
-
-/* The type of the biquad filters */
-enum biquad_type {
- BQ_NONE,
- BQ_LOWPASS,
- BQ_HIGHPASS,
- BQ_BANDPASS,
- BQ_LOWSHELF,
- BQ_HIGHSHELF,
- BQ_PEAKING,
- BQ_NOTCH,
- BQ_ALLPASS
-};
-
-/* Initialize a biquad filter parameters from its type and parameters.
- * Args:
- * bq - The biquad filter we want to set.
- * type - The type of the biquad filter.
- * frequency - The value should be in the range [0, 1]. It is relative to
- * half of the sampling rate.
- * Q - Quality factor. See Web Audio API for details.
- * gain - The value is in dB. See Web Audio API for details.
- */
-void biquad_set(struct biquad *bq, enum biquad_type type, double freq, double Q,
- double gain);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* BIQUAD_H_ */
diff --git a/cras/src/dsp/crossover.c b/cras/src/dsp/crossover.c
deleted file mode 100644
index 48dce890..00000000
--- a/cras/src/dsp/crossover.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "crossover.h"
-#include "biquad.h"
-
-static void lr4_set(struct lr4 *lr4, enum biquad_type type, float freq)
-{
- struct biquad q;
- biquad_set(&q, type, freq, 0, 0);
- lr4->b0 = q.b0;
- lr4->b1 = q.b1;
- lr4->b2 = q.b2;
- lr4->a1 = q.a1;
- lr4->a2 = q.a2;
- lr4->x1 = 0;
- lr4->x2 = 0;
- lr4->y1 = 0;
- lr4->y2 = 0;
- lr4->z1 = 0;
- lr4->z2 = 0;
-}
-
-/* Split input data using two LR4 filters, put the result into the input array
- * and another array.
- *
- * data0 --+-- lp --> data0
- * |
- * \-- hp --> data1
- */
-static void lr4_split(struct lr4 *lp, struct lr4 *hp, int count, float *data0,
- float *data1)
-{
- float lx1 = lp->x1;
- float lx2 = lp->x2;
- float ly1 = lp->y1;
- float ly2 = lp->y2;
- float lz1 = lp->z1;
- float lz2 = lp->z2;
- float lb0 = lp->b0;
- float lb1 = lp->b1;
- float lb2 = lp->b2;
- float la1 = lp->a1;
- float la2 = lp->a2;
-
- float hx1 = hp->x1;
- float hx2 = hp->x2;
- float hy1 = hp->y1;
- float hy2 = hp->y2;
- float hz1 = hp->z1;
- float hz2 = hp->z2;
- float hb0 = hp->b0;
- float hb1 = hp->b1;
- float hb2 = hp->b2;
- float ha1 = hp->a1;
- float ha2 = hp->a2;
-
- int i;
- for (i = 0; i < count; i++) {
- float x, y, z;
- x = data0[i];
- y = lb0 * x + lb1 * lx1 + lb2 * lx2 - la1 * ly1 - la2 * ly2;
- z = lb0 * y + lb1 * ly1 + lb2 * ly2 - la1 * lz1 - la2 * lz2;
- lx2 = lx1;
- lx1 = x;
- ly2 = ly1;
- ly1 = y;
- lz2 = lz1;
- lz1 = z;
- data0[i] = z;
-
- y = hb0 * x + hb1 * hx1 + hb2 * hx2 - ha1 * hy1 - ha2 * hy2;
- z = hb0 * y + hb1 * hy1 + hb2 * hy2 - ha1 * hz1 - ha2 * hz2;
- hx2 = hx1;
- hx1 = x;
- hy2 = hy1;
- hy1 = y;
- hz2 = hz1;
- hz1 = z;
- data1[i] = z;
- }
-
- lp->x1 = lx1;
- lp->x2 = lx2;
- lp->y1 = ly1;
- lp->y2 = ly2;
- lp->z1 = lz1;
- lp->z2 = lz2;
-
- hp->x1 = hx1;
- hp->x2 = hx2;
- hp->y1 = hy1;
- hp->y2 = hy2;
- hp->z1 = hz1;
- hp->z2 = hz2;
-}
-
-/* Split input data using two LR4 filters and sum them back to the original
- * data array.
- *
- * data --+-- lp --+--> data
- * | |
- * \-- hp --/
- */
-static void lr4_merge(struct lr4 *lp, struct lr4 *hp, int count, float *data)
-{
- float lx1 = lp->x1;
- float lx2 = lp->x2;
- float ly1 = lp->y1;
- float ly2 = lp->y2;
- float lz1 = lp->z1;
- float lz2 = lp->z2;
- float lb0 = lp->b0;
- float lb1 = lp->b1;
- float lb2 = lp->b2;
- float la1 = lp->a1;
- float la2 = lp->a2;
-
- float hx1 = hp->x1;
- float hx2 = hp->x2;
- float hy1 = hp->y1;
- float hy2 = hp->y2;
- float hz1 = hp->z1;
- float hz2 = hp->z2;
- float hb0 = hp->b0;
- float hb1 = hp->b1;
- float hb2 = hp->b2;
- float ha1 = hp->a1;
- float ha2 = hp->a2;
-
- int i;
- for (i = 0; i < count; i++) {
- float x, y, z;
- x = data[i];
- y = lb0 * x + lb1 * lx1 + lb2 * lx2 - la1 * ly1 - la2 * ly2;
- z = lb0 * y + lb1 * ly1 + lb2 * ly2 - la1 * lz1 - la2 * lz2;
- lx2 = lx1;
- lx1 = x;
- ly2 = ly1;
- ly1 = y;
- lz2 = lz1;
- lz1 = z;
-
- y = hb0 * x + hb1 * hx1 + hb2 * hx2 - ha1 * hy1 - ha2 * hy2;
- z = hb0 * y + hb1 * hy1 + hb2 * hy2 - ha1 * hz1 - ha2 * hz2;
- hx2 = hx1;
- hx1 = x;
- hy2 = hy1;
- hy1 = y;
- hz2 = hz1;
- hz1 = z;
- data[i] = z + lz1;
- }
-
- lp->x1 = lx1;
- lp->x2 = lx2;
- lp->y1 = ly1;
- lp->y2 = ly2;
- lp->z1 = lz1;
- lp->z2 = lz2;
-
- hp->x1 = hx1;
- hp->x2 = hx2;
- hp->y1 = hy1;
- hp->y2 = hy2;
- hp->z1 = hz1;
- hp->z2 = hz2;
-}
-
-void crossover_init(struct crossover *xo, float freq1, float freq2)
-{
- int i;
- for (i = 0; i < 3; i++) {
- float f = (i == 0) ? freq1 : freq2;
- lr4_set(&xo->lp[i], BQ_LOWPASS, f);
- lr4_set(&xo->hp[i], BQ_HIGHPASS, f);
- }
-}
-
-void crossover_process(struct crossover *xo, int count, float *data0,
- float *data1, float *data2)
-{
- lr4_split(&xo->lp[0], &xo->hp[0], count, data0, data1);
- lr4_merge(&xo->lp[1], &xo->hp[1], count, data0);
- lr4_split(&xo->lp[2], &xo->hp[2], count, data1, data2);
-}
diff --git a/cras/src/dsp/crossover.h b/cras/src/dsp/crossover.h
deleted file mode 100644
index 99a601c1..00000000
--- a/cras/src/dsp/crossover.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CROSSOVER_H_
-#define CROSSOVER_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* An LR4 filter is two biquads with the same parameters connected in series:
- *
- * x -- [BIQUAD] -- y -- [BIQUAD] -- z
- *
- * Both biquad filter has the same parameter b[012] and a[12],
- * The variable [xyz][12] keep the history values.
- */
-struct lr4 {
- float b0, b1, b2;
- float a1, a2;
- float x1, x2;
- float y1, y2;
- float z1, z2;
-};
-
-/* Three bands crossover filter:
- *
- * INPUT --+-- lp0 --+-- lp1 --+---> LOW (0)
- * | | |
- * | \-- hp1 --/
- * |
- * \-- hp0 --+-- lp2 ------> MID (1)
- * |
- * \-- hp2 ------> HIGH (2)
- *
- * [f0] [f1]
- *
- * Each lp or hp is an LR4 filter, which consists of two second-order
- * lowpass or highpass butterworth filters.
- */
-struct crossover {
- struct lr4 lp[3], hp[3];
-};
-
-/* Initializes a crossover filter
- * Args:
- * xo - The crossover filter we want to initialize.
- * freq1 - The normalized frequency splits low and mid band.
- * freq2 - The normalized frequency splits mid and high band.
- */
-void crossover_init(struct crossover *xo, float freq1, float freq2);
-
-/* Splits input samples to three bands.
- * Args:
- * xo - The crossover filter to use.
- * count - The number of input samples.
- * data0 - The input samples, also the place to store low band output.
- * data1 - The place to store mid band output.
- * data2 - The place to store high band output.
- */
-void crossover_process(struct crossover *xo, int count, float *data0,
- float *data1, float *data2);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CROSSOVER_H_ */
diff --git a/cras/src/dsp/crossover2.c b/cras/src/dsp/crossover2.c
deleted file mode 100644
index 7d7e99c2..00000000
--- a/cras/src/dsp/crossover2.c
+++ /dev/null
@@ -1,689 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <string.h>
-#include "crossover2.h"
-#include "biquad.h"
-
-static void lr42_set(struct lr42 *lr42, enum biquad_type type, float freq)
-{
- struct biquad q;
- biquad_set(&q, type, freq, 0, 0);
- memset(lr42, 0, sizeof(*lr42));
- lr42->b0 = q.b0;
- lr42->b1 = q.b1;
- lr42->b2 = q.b2;
- lr42->a1 = q.a1;
- lr42->a2 = q.a2;
-}
-
-/* Split input data using two LR4 filters, put the result into the input array
- * and another array.
- *
- * data0 --+-- lp --> data0
- * |
- * \-- hp --> data1
- */
-#if defined(__ARM_NEON__)
-#include <arm_neon.h>
-static void lr42_split(struct lr42 *lp, struct lr42 *hp, int count,
- float *data0L, float *data0R, float *data1L,
- float *data1R)
-{
- float32x4_t x1 = { lp->x1L, hp->x1L, lp->x1R, hp->x1R };
- float32x4_t x2 = { lp->x2L, hp->x2L, lp->x2R, hp->x2R };
- float32x4_t y1 = { lp->y1L, hp->y1L, lp->y1R, hp->y1R };
- float32x4_t y2 = { lp->y2L, hp->y2L, lp->y2R, hp->y2R };
- float32x4_t z1 = { lp->z1L, hp->z1L, lp->z1R, hp->z1R };
- float32x4_t z2 = { lp->z2L, hp->z2L, lp->z2R, hp->z2R };
- float32x4_t b0 = { lp->b0, hp->b0, lp->b0, hp->b0 };
- float32x4_t b1 = { lp->b1, hp->b1, lp->b1, hp->b1 };
- float32x4_t b2 = { lp->b2, hp->b2, lp->b2, hp->b2 };
- float32x4_t a1 = { lp->a1, hp->a1, lp->a1, hp->a1 };
- float32x4_t a2 = { lp->a2, hp->a2, lp->a2, hp->a2 };
-
- // clang-format off
- __asm__ __volatile__(
- /* q0 = x, q1 = y, q2 = z */
- "1: \n"
- "vmul.f32 q1, %q[b1], %q[x1] \n"
- "vld1.32 d0[], [%[data0L]] \n"
- "vld1.32 d1[], [%[data0R]] \n"
- "subs %[count], #1 \n"
- "vmul.f32 q2, %q[b1], %q[y1] \n"
- "vmla.f32 q1, %q[b0], q0 \n"
- "vmla.f32 q1, %q[b2], %q[x2] \n"
- "vmov.f32 %q[x2], %q[x1] \n"
- "vmov.f32 %q[x1], q0 \n"
- "vmls.f32 q1, %q[a1], %q[y1] \n"
- "vmls.f32 q1, %q[a2], %q[y2] \n"
- "vmla.f32 q2, %q[b0], q1 \n"
- "vmla.f32 q2, %q[b2], %q[y2] \n"
- "vmov.f32 %q[y2], %q[y1] \n"
- "vmov.f32 %q[y1], q1 \n"
- "vmls.f32 q2, %q[a1], %q[z1] \n"
- "vmls.f32 q2, %q[a2], %q[z2] \n"
- "vmov.f32 %q[z2], %q[z1] \n"
- "vmov.f32 %q[z1], q2 \n"
- "vst1.f32 d4[0], [%[data0L]]! \n"
- "vst1.f32 d4[1], [%[data1L]]! \n"
- "vst1.f32 d5[0], [%[data0R]]! \n"
- "vst1.f32 d5[1], [%[data1R]]! \n"
- "bne 1b \n"
- : /* output */
- "=r"(data0L),
- "=r"(data0R),
- "=r"(data1L),
- "=r"(data1R),
- "=r"(count),
- [x1]"+w"(x1),
- [x2]"+w"(x2),
- [y1]"+w"(y1),
- [y2]"+w"(y2),
- [z1]"+w"(z1),
- [z2]"+w"(z2)
- : /* input */
- [data0L]"0"(data0L),
- [data0R]"1"(data0R),
- [data1L]"2"(data1L),
- [data1R]"3"(data1R),
- [count]"4"(count),
- [b0]"w"(b0),
- [b1]"w"(b1),
- [b2]"w"(b2),
- [a1]"w"(a1),
- [a2]"w"(a2)
- : /* clobber */
- "q0", "q1", "q2", "memory", "cc");
- // clang-format on
-
- lp->x1L = x1[0];
- lp->x1R = x1[2];
- lp->x2L = x2[0];
- lp->x2R = x2[2];
- lp->y1L = y1[0];
- lp->y1R = y1[2];
- lp->y2L = y2[0];
- lp->y2R = y2[2];
- lp->z1L = z1[0];
- lp->z1R = z1[2];
- lp->z2L = z2[0];
- lp->z2R = z2[2];
-
- hp->x1L = x1[1];
- hp->x1R = x1[3];
- hp->x2L = x2[1];
- hp->x2R = x2[3];
- hp->y1L = y1[1];
- hp->y1R = y1[3];
- hp->y2L = y2[1];
- hp->y2R = y2[3];
- hp->z1L = z1[1];
- hp->z1R = z1[3];
- hp->z2L = z2[1];
- hp->z2R = z2[3];
-}
-#elif defined(__SSE3__) && defined(__x86_64__)
-#include <emmintrin.h>
-static void lr42_split(struct lr42 *lp, struct lr42 *hp, int count,
- float *data0L, float *data0R, float *data1L,
- float *data1R)
-{
- __m128 x1 = { lp->x1L, hp->x1L, lp->x1R, hp->x1R };
- __m128 x2 = { lp->x2L, hp->x2L, lp->x2R, hp->x2R };
- __m128 y1 = { lp->y1L, hp->y1L, lp->y1R, hp->y1R };
- __m128 y2 = { lp->y2L, hp->y2L, lp->y2R, hp->y2R };
- __m128 z1 = { lp->z1L, hp->z1L, lp->z1R, hp->z1R };
- __m128 z2 = { lp->z2L, hp->z2L, lp->z2R, hp->z2R };
- __m128 b0 = { lp->b0, hp->b0, lp->b0, hp->b0 };
- __m128 b1 = { lp->b1, hp->b1, lp->b1, hp->b1 };
- __m128 b2 = { lp->b2, hp->b2, lp->b2, hp->b2 };
- __m128 a1 = { lp->a1, hp->a1, lp->a1, hp->a1 };
- __m128 a2 = { lp->a2, hp->a2, lp->a2, hp->a2 };
-
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "movss (%[data0L]), %%xmm2 \n"
- "movss (%[data0R]), %%xmm1 \n"
- "shufps $0, %%xmm1, %%xmm2 \n"
- "mulps %[b2],%[x2] \n"
- "movaps %[b0], %%xmm0 \n"
- "mulps %[a2],%[z2] \n"
- "movaps %[b1], %%xmm1 \n"
- "mulps %%xmm2,%%xmm0 \n"
- "mulps %[x1],%%xmm1 \n"
- "addps %%xmm1,%%xmm0 \n"
- "movaps %[a1],%%xmm1 \n"
- "mulps %[y1],%%xmm1 \n"
- "addps %[x2],%%xmm0 \n"
- "movaps %[b1],%[x2] \n"
- "mulps %[y1],%[x2] \n"
- "subps %%xmm1,%%xmm0 \n"
- "movaps %[a2],%%xmm1 \n"
- "mulps %[y2],%%xmm1 \n"
- "mulps %[b2],%[y2] \n"
- "subps %%xmm1,%%xmm0 \n"
- "movaps %[b0],%%xmm1 \n"
- "mulps %%xmm0,%%xmm1 \n"
- "addps %[x2],%%xmm1 \n"
- "movaps %[x1],%[x2] \n"
- "movaps %%xmm2,%[x1] \n"
- "addps %[y2],%%xmm1 \n"
- "movaps %[a1],%[y2] \n"
- "mulps %[z1],%[y2] \n"
- "subps %[y2],%%xmm1 \n"
- "movaps %[y1],%[y2] \n"
- "movaps %%xmm0,%[y1] \n"
- "subps %[z2],%%xmm1 \n"
- "movaps %[z1],%[z2] \n"
- "movaps %%xmm1,%[z1] \n"
- "movss %%xmm1, (%[data0L]) \n"
- "shufps $0x39, %%xmm1, %%xmm1 \n"
- "movss %%xmm1, (%[data1L]) \n"
- "shufps $0x39, %%xmm1, %%xmm1 \n"
- "movss %%xmm1, (%[data0R]) \n"
- "shufps $0x39, %%xmm1, %%xmm1 \n"
- "movss %%xmm1, (%[data1R]) \n"
- "add $4, %[data0L] \n"
- "add $4, %[data1L] \n"
- "add $4, %[data0R] \n"
- "add $4, %[data1R] \n"
- "sub $1, %[count] \n"
- "jnz 1b \n"
- : /* output */
- [data0L]"+r"(data0L),
- [data0R]"+r"(data0R),
- [data1L]"+r"(data1L),
- [data1R]"+r"(data1R),
- [count]"+r"(count),
- [x1]"+x"(x1),
- [x2]"+x"(x2),
- [y1]"+x"(y1),
- [y2]"+x"(y2),
- [z1]"+x"(z1),
- [z2]"+x"(z2)
- : /* input */
- [b0]"x"(b0),
- [b1]"x"(b1),
- [b2]"x"(b2),
- [a1]"x"(a1),
- [a2]"x"(a2)
- : /* clobber */
- "xmm0", "xmm1", "xmm2", "memory", "cc");
- // clang-format on
-
- lp->x1L = x1[0];
- lp->x1R = x1[2];
- lp->x2L = x2[0];
- lp->x2R = x2[2];
- lp->y1L = y1[0];
- lp->y1R = y1[2];
- lp->y2L = y2[0];
- lp->y2R = y2[2];
- lp->z1L = z1[0];
- lp->z1R = z1[2];
- lp->z2L = z2[0];
- lp->z2R = z2[2];
-
- hp->x1L = x1[1];
- hp->x1R = x1[3];
- hp->x2L = x2[1];
- hp->x2R = x2[3];
- hp->y1L = y1[1];
- hp->y1R = y1[3];
- hp->y2L = y2[1];
- hp->y2R = y2[3];
- hp->z1L = z1[1];
- hp->z1R = z1[3];
- hp->z2L = z2[1];
- hp->z2R = z2[3];
-}
-#else
-static void lr42_split(struct lr42 *lp, struct lr42 *hp, int count,
- float *data0L, float *data0R, float *data1L,
- float *data1R)
-{
- float lx1L = lp->x1L, lx1R = lp->x1R;
- float lx2L = lp->x2L, lx2R = lp->x2R;
- float ly1L = lp->y1L, ly1R = lp->y1R;
- float ly2L = lp->y2L, ly2R = lp->y2R;
- float lz1L = lp->z1L, lz1R = lp->z1R;
- float lz2L = lp->z2L, lz2R = lp->z2R;
- float lb0 = lp->b0;
- float lb1 = lp->b1;
- float lb2 = lp->b2;
- float la1 = lp->a1;
- float la2 = lp->a2;
-
- float hx1L = hp->x1L, hx1R = hp->x1R;
- float hx2L = hp->x2L, hx2R = hp->x2R;
- float hy1L = hp->y1L, hy1R = hp->y1R;
- float hy2L = hp->y2L, hy2R = hp->y2R;
- float hz1L = hp->z1L, hz1R = hp->z1R;
- float hz2L = hp->z2L, hz2R = hp->z2R;
- float hb0 = hp->b0;
- float hb1 = hp->b1;
- float hb2 = hp->b2;
- float ha1 = hp->a1;
- float ha2 = hp->a2;
-
- int i;
- for (i = 0; i < count; i++) {
- float xL, yL, zL, xR, yR, zR;
- xL = data0L[i];
- xR = data0R[i];
- yL = lb0 * xL + lb1 * lx1L + lb2 * lx2L - la1 * ly1L -
- la2 * ly2L;
- yR = lb0 * xR + lb1 * lx1R + lb2 * lx2R - la1 * ly1R -
- la2 * ly2R;
- zL = lb0 * yL + lb1 * ly1L + lb2 * ly2L - la1 * lz1L -
- la2 * lz2L;
- zR = lb0 * yR + lb1 * ly1R + lb2 * ly2R - la1 * lz1R -
- la2 * lz2R;
- lx2L = lx1L;
- lx2R = lx1R;
- lx1L = xL;
- lx1R = xR;
- ly2L = ly1L;
- ly2R = ly1R;
- ly1L = yL;
- ly1R = yR;
- lz2L = lz1L;
- lz2R = lz1R;
- lz1L = zL;
- lz1R = zR;
- data0L[i] = zL;
- data0R[i] = zR;
-
- yL = hb0 * xL + hb1 * hx1L + hb2 * hx2L - ha1 * hy1L -
- ha2 * hy2L;
- yR = hb0 * xR + hb1 * hx1R + hb2 * hx2R - ha1 * hy1R -
- ha2 * hy2R;
- zL = hb0 * yL + hb1 * hy1L + hb2 * hy2L - ha1 * hz1L -
- ha2 * hz2L;
- zR = hb0 * yR + hb1 * hy1R + hb2 * hy2R - ha1 * hz1R -
- ha2 * hz2R;
- hx2L = hx1L;
- hx2R = hx1R;
- hx1L = xL;
- hx1R = xR;
- hy2L = hy1L;
- hy2R = hy1R;
- hy1L = yL;
- hy1R = yR;
- hz2L = hz1L;
- hz2R = hz1R;
- hz1L = zL;
- hz1R = zR;
- data1L[i] = zL;
- data1R[i] = zR;
- }
-
- lp->x1L = lx1L;
- lp->x1R = lx1R;
- lp->x2L = lx2L;
- lp->x2R = lx2R;
- lp->y1L = ly1L;
- lp->y1R = ly1R;
- lp->y2L = ly2L;
- lp->y2R = ly2R;
- lp->z1L = lz1L;
- lp->z1R = lz1R;
- lp->z2L = lz2L;
- lp->z2R = lz2R;
-
- hp->x1L = hx1L;
- hp->x1R = hx1R;
- hp->x2L = hx2L;
- hp->x2R = hx2R;
- hp->y1L = hy1L;
- hp->y1R = hy1R;
- hp->y2L = hy2L;
- hp->y2R = hy2R;
- hp->z1L = hz1L;
- hp->z1R = hz1R;
- hp->z2L = hz2L;
- hp->z2R = hz2R;
-}
-#endif
-
-/* Split input data using two LR4 filters and sum them back to the original
- * data array.
- *
- * data --+-- lp --+--> data
- * | |
- * \-- hp --/
- */
-#if defined(__ARM_NEON__)
-#include <arm_neon.h>
-static void lr42_merge(struct lr42 *lp, struct lr42 *hp, int count,
- float *dataL, float *dataR)
-{
- float32x4_t x1 = { lp->x1L, hp->x1L, lp->x1R, hp->x1R };
- float32x4_t x2 = { lp->x2L, hp->x2L, lp->x2R, hp->x2R };
- float32x4_t y1 = { lp->y1L, hp->y1L, lp->y1R, hp->y1R };
- float32x4_t y2 = { lp->y2L, hp->y2L, lp->y2R, hp->y2R };
- float32x4_t z1 = { lp->z1L, hp->z1L, lp->z1R, hp->z1R };
- float32x4_t z2 = { lp->z2L, hp->z2L, lp->z2R, hp->z2R };
- float32x4_t b0 = { lp->b0, hp->b0, lp->b0, hp->b0 };
- float32x4_t b1 = { lp->b1, hp->b1, lp->b1, hp->b1 };
- float32x4_t b2 = { lp->b2, hp->b2, lp->b2, hp->b2 };
- float32x4_t a1 = { lp->a1, hp->a1, lp->a1, hp->a1 };
- float32x4_t a2 = { lp->a2, hp->a2, lp->a2, hp->a2 };
-
- // clang-format off
- __asm__ __volatile__(
- /* q0 = x, q1 = y, q2 = z */
- "1: \n"
- "vmul.f32 q1, %q[b1], %q[x1] \n"
- "vld1.32 d0[], [%[dataL]] \n"
- "vld1.32 d1[], [%[dataR]] \n"
- "subs %[count], #1 \n"
- "vmul.f32 q2, %q[b1], %q[y1] \n"
- "vmla.f32 q1, %q[b0], q0 \n"
- "vmla.f32 q1, %q[b2], %q[x2] \n"
- "vmov.f32 %q[x2], %q[x1] \n"
- "vmov.f32 %q[x1], q0 \n"
- "vmls.f32 q1, %q[a1], %q[y1] \n"
- "vmls.f32 q1, %q[a2], %q[y2] \n"
- "vmla.f32 q2, %q[b0], q1 \n"
- "vmla.f32 q2, %q[b2], %q[y2] \n"
- "vmov.f32 %q[y2], %q[y1] \n"
- "vmov.f32 %q[y1], q1 \n"
- "vmls.f32 q2, %q[a1], %q[z1] \n"
- "vmls.f32 q2, %q[a2], %q[z2] \n"
- "vmov.f32 %q[z2], %q[z1] \n"
- "vmov.f32 %q[z1], q2 \n"
- "vpadd.f32 d4, d4, d5 \n"
- "vst1.f32 d4[0], [%[dataL]]! \n"
- "vst1.f32 d4[1], [%[dataR]]! \n"
- "bne 1b \n"
- : /* output */
- "=r"(dataL),
- "=r"(dataR),
- "=r"(count),
- [x1]"+w"(x1),
- [x2]"+w"(x2),
- [y1]"+w"(y1),
- [y2]"+w"(y2),
- [z1]"+w"(z1),
- [z2]"+w"(z2)
- : /* input */
- [dataL]"0"(dataL),
- [dataR]"1"(dataR),
- [count]"2"(count),
- [b0]"w"(b0),
- [b1]"w"(b1),
- [b2]"w"(b2),
- [a1]"w"(a1),
- [a2]"w"(a2)
- : /* clobber */
- "q0", "q1", "q2", "memory", "cc");
- // clang-format on
-
- lp->x1L = x1[0];
- lp->x1R = x1[2];
- lp->x2L = x2[0];
- lp->x2R = x2[2];
- lp->y1L = y1[0];
- lp->y1R = y1[2];
- lp->y2L = y2[0];
- lp->y2R = y2[2];
- lp->z1L = z1[0];
- lp->z1R = z1[2];
- lp->z2L = z2[0];
- lp->z2R = z2[2];
-
- hp->x1L = x1[1];
- hp->x1R = x1[3];
- hp->x2L = x2[1];
- hp->x2R = x2[3];
- hp->y1L = y1[1];
- hp->y1R = y1[3];
- hp->y2L = y2[1];
- hp->y2R = y2[3];
- hp->z1L = z1[1];
- hp->z1R = z1[3];
- hp->z2L = z2[1];
- hp->z2R = z2[3];
-}
-#elif defined(__SSE3__) && defined(__x86_64__)
-#include <emmintrin.h>
-static void lr42_merge(struct lr42 *lp, struct lr42 *hp, int count,
- float *dataL, float *dataR)
-{
- __m128 x1 = { lp->x1L, hp->x1L, lp->x1R, hp->x1R };
- __m128 x2 = { lp->x2L, hp->x2L, lp->x2R, hp->x2R };
- __m128 y1 = { lp->y1L, hp->y1L, lp->y1R, hp->y1R };
- __m128 y2 = { lp->y2L, hp->y2L, lp->y2R, hp->y2R };
- __m128 z1 = { lp->z1L, hp->z1L, lp->z1R, hp->z1R };
- __m128 z2 = { lp->z2L, hp->z2L, lp->z2R, hp->z2R };
- __m128 b0 = { lp->b0, hp->b0, lp->b0, hp->b0 };
- __m128 b1 = { lp->b1, hp->b1, lp->b1, hp->b1 };
- __m128 b2 = { lp->b2, hp->b2, lp->b2, hp->b2 };
- __m128 a1 = { lp->a1, hp->a1, lp->a1, hp->a1 };
- __m128 a2 = { lp->a2, hp->a2, lp->a2, hp->a2 };
-
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "movss (%[dataL]), %%xmm2 \n"
- "movss (%[dataR]), %%xmm1 \n"
- "shufps $0, %%xmm1, %%xmm2 \n"
- "mulps %[b2],%[x2] \n"
- "movaps %[b0], %%xmm0 \n"
- "mulps %[a2],%[z2] \n"
- "movaps %[b1], %%xmm1 \n"
- "mulps %%xmm2,%%xmm0 \n"
- "mulps %[x1],%%xmm1 \n"
- "addps %%xmm1,%%xmm0 \n"
- "movaps %[a1],%%xmm1 \n"
- "mulps %[y1],%%xmm1 \n"
- "addps %[x2],%%xmm0 \n"
- "movaps %[b1],%[x2] \n"
- "mulps %[y1],%[x2] \n"
- "subps %%xmm1,%%xmm0 \n"
- "movaps %[a2],%%xmm1 \n"
- "mulps %[y2],%%xmm1 \n"
- "mulps %[b2],%[y2] \n"
- "subps %%xmm1,%%xmm0 \n"
- "movaps %[b0],%%xmm1 \n"
- "mulps %%xmm0,%%xmm1 \n"
- "addps %[x2],%%xmm1 \n"
- "movaps %[x1],%[x2] \n"
- "movaps %%xmm2,%[x1] \n"
- "addps %[y2],%%xmm1 \n"
- "movaps %[a1],%[y2] \n"
- "mulps %[z1],%[y2] \n"
- "subps %[y2],%%xmm1 \n"
- "movaps %[y1],%[y2] \n"
- "movaps %%xmm0,%[y1] \n"
- "subps %[z2],%%xmm1 \n"
- "movaps %[z1],%[z2] \n"
- "movaps %%xmm1,%[z1] \n"
- "haddps %%xmm1, %%xmm1 \n"
- "movss %%xmm1, (%[dataL]) \n"
- "shufps $0x39, %%xmm1, %%xmm1 \n"
- "movss %%xmm1, (%[dataR]) \n"
- "add $4, %[dataL] \n"
- "add $4, %[dataR] \n"
- "sub $1, %[count] \n"
- "jnz 1b \n"
- : /* output */
- [dataL]"+r"(dataL),
- [dataR]"+r"(dataR),
- [count]"+r"(count),
- [x1]"+x"(x1),
- [x2]"+x"(x2),
- [y1]"+x"(y1),
- [y2]"+x"(y2),
- [z1]"+x"(z1),
- [z2]"+x"(z2)
- : /* input */
- [b0]"x"(b0),
- [b1]"x"(b1),
- [b2]"x"(b2),
- [a1]"x"(a1),
- [a2]"x"(a2)
- : /* clobber */
- "xmm0", "xmm1", "xmm2", "memory", "cc");
- // clang-format on
-
- lp->x1L = x1[0];
- lp->x1R = x1[2];
- lp->x2L = x2[0];
- lp->x2R = x2[2];
- lp->y1L = y1[0];
- lp->y1R = y1[2];
- lp->y2L = y2[0];
- lp->y2R = y2[2];
- lp->z1L = z1[0];
- lp->z1R = z1[2];
- lp->z2L = z2[0];
- lp->z2R = z2[2];
-
- hp->x1L = x1[1];
- hp->x1R = x1[3];
- hp->x2L = x2[1];
- hp->x2R = x2[3];
- hp->y1L = y1[1];
- hp->y1R = y1[3];
- hp->y2L = y2[1];
- hp->y2R = y2[3];
- hp->z1L = z1[1];
- hp->z1R = z1[3];
- hp->z2L = z2[1];
- hp->z2R = z2[3];
-}
-#else
-static void lr42_merge(struct lr42 *lp, struct lr42 *hp, int count,
- float *dataL, float *dataR)
-{
- float lx1L = lp->x1L, lx1R = lp->x1R;
- float lx2L = lp->x2L, lx2R = lp->x2R;
- float ly1L = lp->y1L, ly1R = lp->y1R;
- float ly2L = lp->y2L, ly2R = lp->y2R;
- float lz1L = lp->z1L, lz1R = lp->z1R;
- float lz2L = lp->z2L, lz2R = lp->z2R;
- float lb0 = lp->b0;
- float lb1 = lp->b1;
- float lb2 = lp->b2;
- float la1 = lp->a1;
- float la2 = lp->a2;
-
- float hx1L = hp->x1L, hx1R = hp->x1R;
- float hx2L = hp->x2L, hx2R = hp->x2R;
- float hy1L = hp->y1L, hy1R = hp->y1R;
- float hy2L = hp->y2L, hy2R = hp->y2R;
- float hz1L = hp->z1L, hz1R = hp->z1R;
- float hz2L = hp->z2L, hz2R = hp->z2R;
- float hb0 = hp->b0;
- float hb1 = hp->b1;
- float hb2 = hp->b2;
- float ha1 = hp->a1;
- float ha2 = hp->a2;
-
- int i;
- for (i = 0; i < count; i++) {
- float xL, yL, zL, xR, yR, zR;
- xL = dataL[i];
- xR = dataR[i];
- yL = lb0 * xL + lb1 * lx1L + lb2 * lx2L - la1 * ly1L -
- la2 * ly2L;
- yR = lb0 * xR + lb1 * lx1R + lb2 * lx2R - la1 * ly1R -
- la2 * ly2R;
- zL = lb0 * yL + lb1 * ly1L + lb2 * ly2L - la1 * lz1L -
- la2 * lz2L;
- zR = lb0 * yR + lb1 * ly1R + lb2 * ly2R - la1 * lz1R -
- la2 * lz2R;
- lx2L = lx1L;
- lx2R = lx1R;
- lx1L = xL;
- lx1R = xR;
- ly2L = ly1L;
- ly2R = ly1R;
- ly1L = yL;
- ly1R = yR;
- lz2L = lz1L;
- lz2R = lz1R;
- lz1L = zL;
- lz1R = zR;
-
- yL = hb0 * xL + hb1 * hx1L + hb2 * hx2L - ha1 * hy1L -
- ha2 * hy2L;
- yR = hb0 * xR + hb1 * hx1R + hb2 * hx2R - ha1 * hy1R -
- ha2 * hy2R;
- zL = hb0 * yL + hb1 * hy1L + hb2 * hy2L - ha1 * hz1L -
- ha2 * hz2L;
- zR = hb0 * yR + hb1 * hy1R + hb2 * hy2R - ha1 * hz1R -
- ha2 * hz2R;
- hx2L = hx1L;
- hx2R = hx1R;
- hx1L = xL;
- hx1R = xR;
- hy2L = hy1L;
- hy2R = hy1R;
- hy1L = yL;
- hy1R = yR;
- hz2L = hz1L;
- hz2R = hz1R;
- hz1L = zL;
- hz1R = zR;
- dataL[i] = zL + lz1L;
- dataR[i] = zR + lz1R;
- }
-
- lp->x1L = lx1L;
- lp->x1R = lx1R;
- lp->x2L = lx2L;
- lp->x2R = lx2R;
- lp->y1L = ly1L;
- lp->y1R = ly1R;
- lp->y2L = ly2L;
- lp->y2R = ly2R;
- lp->z1L = lz1L;
- lp->z1R = lz1R;
- lp->z2L = lz2L;
- lp->z2R = lz2R;
-
- hp->x1L = hx1L;
- hp->x1R = hx1R;
- hp->x2L = hx2L;
- hp->x2R = hx2R;
- hp->y1L = hy1L;
- hp->y1R = hy1R;
- hp->y2L = hy2L;
- hp->y2R = hy2R;
- hp->z1L = hz1L;
- hp->z1R = hz1R;
- hp->z2L = hz2L;
- hp->z2R = hz2R;
-}
-#endif
-
-void crossover2_init(struct crossover2 *xo2, float freq1, float freq2)
-{
- int i;
- for (i = 0; i < 3; i++) {
- float f = (i == 0) ? freq1 : freq2;
- lr42_set(&xo2->lp[i], BQ_LOWPASS, f);
- lr42_set(&xo2->hp[i], BQ_HIGHPASS, f);
- }
-}
-
-void crossover2_process(struct crossover2 *xo2, int count, float *data0L,
- float *data0R, float *data1L, float *data1R,
- float *data2L, float *data2R)
-{
- if (!count)
- return;
-
- lr42_split(&xo2->lp[0], &xo2->hp[0], count, data0L, data0R, data1L,
- data1R);
- lr42_merge(&xo2->lp[1], &xo2->hp[1], count, data0L, data0R);
- lr42_split(&xo2->lp[2], &xo2->hp[2], count, data1L, data1R, data2L,
- data2R);
-}
diff --git a/cras/src/dsp/crossover2.h b/cras/src/dsp/crossover2.h
deleted file mode 100644
index 9afa0e8a..00000000
--- a/cras/src/dsp/crossover2.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CROSSOVER2_H_
-#define CROSSOVER2_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* "crossover2" is a two channel version of the "crossover" filter. It processes
- * two channels of data at once to increase performance. */
-
-/* An LR4 filter is two biquads with the same parameters connected in series:
- *
- * x -- [BIQUAD] -- y -- [BIQUAD] -- z
- *
- * Both biquad filter has the same parameter b[012] and a[12],
- * The variable [xyz][12][LR] keep the history values.
- */
-struct lr42 {
- float b0, b1, b2;
- float a1, a2;
- float x1L, x1R, x2L, x2R;
- float y1L, y1R, y2L, y2R;
- float z1L, z1R, z2L, z2R;
-};
-
-/* Three bands crossover filter:
- *
- * INPUT --+-- lp0 --+-- lp1 --+---> LOW (0)
- * | | |
- * | \-- hp1 --/
- * |
- * \-- hp0 --+-- lp2 ------> MID (1)
- * |
- * \-- hp2 ------> HIGH (2)
- *
- * [f0] [f1]
- *
- * Each lp or hp is an LR4 filter, which consists of two second-order
- * lowpass or highpass butterworth filters.
- */
-struct crossover2 {
- struct lr42 lp[3], hp[3];
-};
-
-/* Initializes a crossover2 filter
- * Args:
- * xo2 - The crossover2 filter we want to initialize.
- * freq1 - The normalized frequency splits low and mid band.
- * freq2 - The normalized frequency splits mid and high band.
- */
-void crossover2_init(struct crossover2 *xo2, float freq1, float freq2);
-
-/* Splits input samples to three bands.
- * Args:
- * xo2 - The crossover2 filter to use.
- * count - The number of input samples.
- * data0L, data0R - The input samples, also the place to store low band
- * output.
- * data1L, data1R - The place to store mid band output.
- * data2L, data2R - The place to store high band output.
- */
-void crossover2_process(struct crossover2 *xo2, int count, float *data0L,
- float *data0R, float *data1L, float *data1R,
- float *data2L, float *data2R);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CROSSOVER2_H_ */
diff --git a/cras/src/dsp/dcblock.c b/cras/src/dsp/dcblock.c
deleted file mode 100644
index 53ba9412..00000000
--- a/cras/src/dsp/dcblock.c
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include "dcblock.h"
-
-#define RAMP_TIME_MS 20
-
-struct dcblock {
- float R;
- float x_prev;
- float y_prev;
- float ramp_factor;
- float ramp_increment;
- int initialized;
-};
-
-struct dcblock *dcblock_new(float R, unsigned long sample_rate)
-{
- struct dcblock *dcblock = (struct dcblock *)calloc(1, sizeof(*dcblock));
- dcblock->R = R;
- dcblock->ramp_increment = 1000. / (float)(RAMP_TIME_MS * sample_rate);
- return dcblock;
-}
-
-void dcblock_free(struct dcblock *dcblock)
-{
- free(dcblock);
-}
-
-/* This is the prototype of the processing loop. */
-void dcblock_process(struct dcblock *dcblock, float *data, int count)
-{
- int n;
- float x_prev = dcblock->x_prev;
- float y_prev = dcblock->y_prev;
- float R = dcblock->R;
-
- if (!dcblock->initialized) {
- x_prev = data[0];
- dcblock->initialized = 1;
- }
-
- for (n = 0; n < count; n++) {
- float x = data[n];
- float d = x - x_prev + R * y_prev;
-
- y_prev = d;
- x_prev = x;
-
- /*
- * It takes a while for this DC-block filter to completely
- * filter out a large DC-offset, so apply a mix-in ramp to
- * avoid any residual jump discontinuities that can lead to
- * "pop" during capture.
- */
- if (dcblock->ramp_factor < 1.0) {
- d *= dcblock->ramp_factor;
- dcblock->ramp_factor += dcblock->ramp_increment;
- }
-
- data[n] = d;
- }
- dcblock->x_prev = x_prev;
- dcblock->y_prev = y_prev;
-}
diff --git a/cras/src/dsp/dcblock.h b/cras/src/dsp/dcblock.h
deleted file mode 100644
index a2ac427d..00000000
--- a/cras/src/dsp/dcblock.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef DCBLOCK_H_
-#define DCBLOCK_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* A DC blocking filter. */
-
-struct dcblock;
-
-/*
- * Create a DC blocking filter.
- *
- * Transfer fn: (1 - z^-1) / (1 - R * z^-1)
- * Args:
- * R - DC block filter coefficient.
- * sample_rate - The sample rate, in Hz.
- */
-struct dcblock *dcblock_new(float R, unsigned long sample_rate);
-
-/* Free a DC blocking filter. */
-void dcblock_free(struct dcblock *dcblock);
-
-/* Process a buffer of audio data through the filter.
- * Args:
- * dcblock - The filter we want to use.
- * data - The array of audio samples.
- * count - The number of elements in the data array to process.
- */
-void dcblock_process(struct dcblock *dcblock, float *data, int count);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* DCBLOCK_H_ */
diff --git a/cras/src/dsp/drc.c b/cras/src/dsp/drc.c
deleted file mode 100644
index e6098419..00000000
--- a/cras/src/dsp/drc.c
+++ /dev/null
@@ -1,396 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Copyright (C) 2011 Google Inc. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE.WEBKIT file.
- */
-
-#include <assert.h>
-#include <stdlib.h>
-
-#include "drc.h"
-#include "drc_math.h"
-
-static void set_default_parameters(struct drc *drc);
-static void init_data_buffer(struct drc *drc);
-static void init_emphasis_eq(struct drc *drc);
-static void init_crossover(struct drc *drc);
-static void init_kernel(struct drc *drc);
-static void free_data_buffer(struct drc *drc);
-static void free_emphasis_eq(struct drc *drc);
-static void free_kernel(struct drc *drc);
-
-struct drc *drc_new(float sample_rate)
-{
- struct drc *drc = (struct drc *)calloc(1, sizeof(struct drc));
- drc->sample_rate = sample_rate;
- set_default_parameters(drc);
- return drc;
-}
-
-void drc_init(struct drc *drc)
-{
- init_data_buffer(drc);
- init_emphasis_eq(drc);
- init_crossover(drc);
- init_kernel(drc);
-}
-
-void drc_free(struct drc *drc)
-{
- free_kernel(drc);
- free_emphasis_eq(drc);
- free_data_buffer(drc);
- free(drc);
-}
-
-/* Allocates temporary buffers used during drc_process(). */
-static void init_data_buffer(struct drc *drc)
-{
- int i;
- size_t size = sizeof(float) * DRC_PROCESS_MAX_FRAMES;
-
- for (i = 0; i < DRC_NUM_CHANNELS; i++) {
- drc->data1[i] = (float *)calloc(1, size);
- drc->data2[i] = (float *)calloc(1, size);
- }
-}
-
-/* Frees temporary buffers */
-static void free_data_buffer(struct drc *drc)
-{
- int i;
-
- for (i = 0; i < DRC_NUM_CHANNELS; i++) {
- free(drc->data1[i]);
- free(drc->data2[i]);
- }
-}
-
-void drc_set_param(struct drc *drc, int index, unsigned paramID, float value)
-{
- assert(paramID < PARAM_LAST);
- if (paramID < PARAM_LAST)
- drc->parameters[index][paramID] = value;
-}
-
-static float drc_get_param(struct drc *drc, int index, unsigned paramID)
-{
- assert(paramID < PARAM_LAST);
- return drc->parameters[index][paramID];
-}
-
-/* Initializes parameters to default values. */
-static void set_default_parameters(struct drc *drc)
-{
- float nyquist = drc->sample_rate / 2;
- int i;
-
- for (i = 0; i < DRC_NUM_KERNELS; i++) {
- float *param = drc->parameters[i];
- param[PARAM_THRESHOLD] = -24; /* dB */
- param[PARAM_KNEE] = 30; /* dB */
- param[PARAM_RATIO] = 12; /* unit-less */
- param[PARAM_ATTACK] = 0.003f; /* seconds */
- param[PARAM_RELEASE] = 0.250f; /* seconds */
- param[PARAM_PRE_DELAY] = DRC_DEFAULT_PRE_DELAY; /* seconds */
-
- /* Release zone values 0 -> 1. */
- param[PARAM_RELEASE_ZONE1] = 0.09f;
- param[PARAM_RELEASE_ZONE2] = 0.16f;
- param[PARAM_RELEASE_ZONE3] = 0.42f;
- param[PARAM_RELEASE_ZONE4] = 0.98f;
-
- /* This is effectively a main volume on the compressed
- * signal */
- param[PARAM_POST_GAIN] = 0; /* dB */
- param[PARAM_ENABLED] = 0;
- }
-
- drc->parameters[0][PARAM_CROSSOVER_LOWER_FREQ] = 0;
- drc->parameters[1][PARAM_CROSSOVER_LOWER_FREQ] = 200 / nyquist;
- drc->parameters[2][PARAM_CROSSOVER_LOWER_FREQ] = 2000 / nyquist;
-
- /* These parameters has only one copy */
- drc->parameters[0][PARAM_FILTER_STAGE_GAIN] = 4.4f; /* dB */
- drc->parameters[0][PARAM_FILTER_STAGE_RATIO] = 2;
- drc->parameters[0][PARAM_FILTER_ANCHOR] = 15000 / nyquist;
-}
-
-/* Finds the zero and pole for one stage of the emphasis filter */
-static void emphasis_stage_roots(float gain, float normalized_frequency,
- float *zero, float *pole)
-{
- float gk = 1 - gain / 20;
- float f1 = normalized_frequency * gk;
- float f2 = normalized_frequency / gk;
- *zero = expf(-f1 * PI_FLOAT);
- *pole = expf(-f2 * PI_FLOAT);
-}
-
-/* Calculates the biquad coefficients for two emphasis stages. */
-static void emphasis_stage_pair_biquads(float gain, float f1, float f2,
- struct biquad *emphasis,
- struct biquad *deemphasis)
-{
- float z1, p1;
- float z2, p2;
-
- emphasis_stage_roots(gain, f1, &z1, &p1);
- emphasis_stage_roots(gain, f2, &z2, &p2);
-
- float b0 = 1;
- float b1 = -(z1 + z2);
- float b2 = z1 * z2;
- float a0 = 1;
- float a1 = -(p1 + p2);
- float a2 = p1 * p2;
-
- /* Gain compensation to make 0dB @ 0Hz */
- float alpha = (a0 + a1 + a2) / (b0 + b1 + b2);
-
- emphasis->b0 = b0 * alpha;
- emphasis->b1 = b1 * alpha;
- emphasis->b2 = b2 * alpha;
- emphasis->a1 = a1;
- emphasis->a2 = a2;
-
- float beta = (b0 + b1 + b2) / (a0 + a1 + a2);
-
- deemphasis->b0 = a0 * beta;
- deemphasis->b1 = a1 * beta;
- deemphasis->b2 = a2 * beta;
- deemphasis->a1 = b1;
- deemphasis->a2 = b2;
-}
-
-/* Initializes the emphasis and deemphasis filter */
-static void init_emphasis_eq(struct drc *drc)
-{
- struct biquad e = { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
- struct biquad d = { 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f };
- int i, j;
-
- float stage_gain = drc_get_param(drc, 0, PARAM_FILTER_STAGE_GAIN);
- float stage_ratio = drc_get_param(drc, 0, PARAM_FILTER_STAGE_RATIO);
- float anchor_freq = drc_get_param(drc, 0, PARAM_FILTER_ANCHOR);
-
- drc->emphasis_eq = eq2_new();
- drc->deemphasis_eq = eq2_new();
-
- for (i = 0; i < 2; i++) {
- emphasis_stage_pair_biquads(stage_gain, anchor_freq,
- anchor_freq / stage_ratio, &e, &d);
- for (j = 0; j < 2; j++) {
- eq2_append_biquad_direct(drc->emphasis_eq, j, &e);
- eq2_append_biquad_direct(drc->deemphasis_eq, j, &d);
- }
- anchor_freq /= (stage_ratio * stage_ratio);
- }
-}
-
-/* Frees the emphasis and deemphasis filter */
-static void free_emphasis_eq(struct drc *drc)
-{
- eq2_free(drc->emphasis_eq);
- eq2_free(drc->deemphasis_eq);
-}
-
-/* Initializes the crossover filter */
-static void init_crossover(struct drc *drc)
-{
- float freq1 = drc->parameters[1][PARAM_CROSSOVER_LOWER_FREQ];
- float freq2 = drc->parameters[2][PARAM_CROSSOVER_LOWER_FREQ];
-
- crossover2_init(&drc->xo2, freq1, freq2);
-}
-
-/* Initializes the compressor kernels */
-static void init_kernel(struct drc *drc)
-{
- int i;
-
- for (i = 0; i < DRC_NUM_KERNELS; i++) {
- dk_init(&drc->kernel[i], drc->sample_rate);
-
- float db_threshold = drc_get_param(drc, i, PARAM_THRESHOLD);
- float db_knee = drc_get_param(drc, i, PARAM_KNEE);
- float ratio = drc_get_param(drc, i, PARAM_RATIO);
- float attack_time = drc_get_param(drc, i, PARAM_ATTACK);
- float release_time = drc_get_param(drc, i, PARAM_RELEASE);
- float pre_delay_time = drc_get_param(drc, i, PARAM_PRE_DELAY);
- float releaseZone1 = drc_get_param(drc, i, PARAM_RELEASE_ZONE1);
- float releaseZone2 = drc_get_param(drc, i, PARAM_RELEASE_ZONE2);
- float releaseZone3 = drc_get_param(drc, i, PARAM_RELEASE_ZONE3);
- float releaseZone4 = drc_get_param(drc, i, PARAM_RELEASE_ZONE4);
- float db_post_gain = drc_get_param(drc, i, PARAM_POST_GAIN);
- int enabled = drc_get_param(drc, i, PARAM_ENABLED);
-
- dk_set_parameters(&drc->kernel[i], db_threshold, db_knee, ratio,
- attack_time, release_time, pre_delay_time,
- db_post_gain, releaseZone1, releaseZone2,
- releaseZone3, releaseZone4);
-
- dk_set_enabled(&drc->kernel[i], enabled);
- }
-}
-
-/* Frees the compressor kernels */
-static void free_kernel(struct drc *drc)
-{
- int i;
- for (i = 0; i < DRC_NUM_KERNELS; i++)
- dk_free(&drc->kernel[i]);
-}
-
-// Note gcc 4.9+ with -O2 on aarch64 produces vectorized version of C
-// that is comparable performance, but twice as large. -O1 and -Os produce
-// small but slower code (4x slower than Neon).
-#if defined(__aarch64__)
-static void sum3(float *data, const float *data1, const float *data2, int n)
-{
- int count = n / 4;
- int i;
-
- if (count) {
- // clang-format off
- __asm__ __volatile(
- "1: \n"
- "ld1 {v0.4s}, [%[data1]], #16 \n"
- "ld1 {v1.4s}, [%[data2]], #16 \n"
- "ld1 {v2.4s}, [%[data]] \n"
- "fadd v0.4s, v0.4s, v1.4s \n"
- "fadd v0.4s, v0.4s, v2.4s \n"
- "st1 {v0.4s}, [%[data]], #16 \n"
- "subs %w[count], %w[count], #1 \n"
- "b.ne 1b \n"
- : /* output */
- [data]"+r"(data),
- [data1]"+r"(data1),
- [data2]"+r"(data2),
- [count]"+r"(count)
- : /* input */
- : /* clobber */
- "v0", "v1", "v2", "memory", "cc");
- // clang-format on
- }
-
- n &= 3;
- for (i = 0; i < n; i++)
- data[i] += data1[i] + data2[i];
-}
-#elif defined(__ARM_NEON__)
-static void sum3(float *data, const float *data1, const float *data2, int n)
-{
- int count = n / 4;
- int i;
-
- if (count) {
- // clang-format off
- __asm__ __volatile(
- "1: \n"
- "vld1.32 {q0}, [%[data1]]! \n"
- "vld1.32 {q1}, [%[data2]]! \n"
- "vld1.32 {q2}, [%[data]] \n"
- "vadd.f32 q0, q0, q1 \n"
- "vadd.f32 q0, q0, q2 \n"
- "vst1.32 {q0}, [%[data]]! \n"
- "subs %[count], #1 \n"
- "bne 1b \n"
- : /* output */
- [data]"+r"(data),
- [data1]"+r"(data1),
- [data2]"+r"(data2),
- [count]"+r"(count)
- : /* input */
- : /* clobber */
- "q0", "q1", "q2", "memory", "cc");
- // clang-format on
- }
-
- n &= 3;
- for (i = 0; i < n; i++)
- data[i] += data1[i] + data2[i];
-}
-#elif defined(__SSE3__)
-#include <emmintrin.h>
-static void sum3(float *data, const float *data1, const float *data2, int n)
-{
- __m128 x, y, z;
- int count = n / 4;
- int i;
-
- if (count) {
- // clang-format off
- __asm__ __volatile(
- "1: \n"
- "lddqu (%[data1]), %[x] \n"
- "lddqu (%[data2]), %[y] \n"
- "lddqu (%[data]), %[z] \n"
- "addps %[x], %[y] \n"
- "addps %[y], %[z] \n"
- "movdqu %[z], (%[data]) \n"
- "add $16, %[data1] \n"
- "add $16, %[data2] \n"
- "add $16, %[data] \n"
- "sub $1, %[count] \n"
- "jne 1b \n"
- : /* output */
- [data]"+r"(data),
- [data1]"+r"(data1),
- [data2]"+r"(data2),
- [count]"+r"(count),
- [x]"=x"(x),
- [y]"=x"(y),
- [z]"=x"(z)
- : /* input */
- : /* clobber */
- "memory", "cc");
- // clang-format on
- }
-
- n &= 3;
- for (i = 0; i < n; i++)
- data[i] += data1[i] + data2[i];
-}
-#else
-static void sum3(float *data, const float *data1, const float *data2, int n)
-{
- int i;
- for (i = 0; i < n; i++)
- data[i] += data1[i] + data2[i];
-}
-#endif
-
-void drc_process(struct drc *drc, float **data, int frames)
-{
- int i;
- float **data1 = drc->data1;
- float **data2 = drc->data2;
-
- /* Apply pre-emphasis filter if it is not disabled. */
- if (!drc->emphasis_disabled)
- eq2_process(drc->emphasis_eq, data[0], data[1], frames);
-
- /* Crossover */
- crossover2_process(&drc->xo2, frames, data[0], data[1], data1[0],
- data1[1], data2[0], data2[1]);
-
- /* Apply compression to each band of the signal. The processing is
- * performed in place.
- */
- dk_process(&drc->kernel[0], data, frames);
- dk_process(&drc->kernel[1], data1, frames);
- dk_process(&drc->kernel[2], data2, frames);
-
- /* Sum the three bands of signal */
- for (i = 0; i < DRC_NUM_CHANNELS; i++)
- sum3(data[i], data1[i], data2[i], frames);
-
- /* Apply de-emphasis filter if emphasis is not disabled. */
- if (!drc->emphasis_disabled)
- eq2_process(drc->deemphasis_eq, data[0], data[1], frames);
-}
diff --git a/cras/src/dsp/drc.h b/cras/src/dsp/drc.h
deleted file mode 100644
index f61e8518..00000000
--- a/cras/src/dsp/drc.h
+++ /dev/null
@@ -1,183 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Copyright (C) 2011 Google Inc. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE.WEBKIT file.
- */
-
-#ifndef DRC_H_
-#define DRC_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "crossover2.h"
-#include "drc_kernel.h"
-#include "eq2.h"
-
-/* DRC implements a flexible audio dynamics compression effect such as is
- * commonly used in musical production and game audio. It lowers the volume of
- * the loudest parts of the signal and raises the volume of the softest parts,
- * making the sound richer, fuller, and more controlled.
- *
- * This is a three band stereo DRC. There are three compressor kernels, and each
- * can have its own parameters. If a kernel is disabled, it only delays the
- * signal and does not compress it.
- *
- * INPUT
- * |
- * +----------+
- * | emphasis |
- * +----------+
- * |
- * +------------+
- * | crossover |
- * +------------+
- * / | \
- * (low band) (mid band) (high band)
- * / | \
- * +------+ +------+ +------+
- * | drc | | drc | | drc |
- * |kernel| |kernel| |kernel|
- * +------+ +------+ +------+
- * \ | /
- * \ | /
- * +-------------+
- * | (+) |
- * +-------------+
- * |
- * +------------+
- * | deemphasis |
- * +------------+
- * |
- * OUTPUT
- *
- */
-
-/* The parameters of the DRC compressor.
- *
- * PARAM_THRESHOLD - The value above which the compression starts, in dB.
- * PARAM_KNEE - The value above which the knee region starts, in dB.
- * PARAM_RATIO - The input/output dB ratio after the knee region.
- * PARAM_ATTACK - The time to reduce the gain by 10dB, in seconds.
- * PARAM_RELEASE - The time to increase the gain by 10dB, in seconds.
- * PARAM_PRE_DELAY - The lookahead time for the compressor, in seconds.
- * PARAM_RELEASE_ZONE[1-4] - The adaptive release curve parameters.
- * PARAM_POST_GAIN - The static boost value in output, in dB.
- * PARAM_FILTER_STAGE_GAIN - The gain of each emphasis filter stage.
- * PARAM_FILTER_STAGE_RATIO - The frequency ratio for each emphasis filter stage
- * to the previous stage.
- * PARAM_FILTER_ANCHOR - The frequency of the first emphasis filter, in
- * normalized frequency (in [0, 1], relative to half of the sample rate).
- * PARAM_CROSSOVER_LOWER_FREQ - The lower frequency of the band, in normalized
- * frequency (in [0, 1], relative to half of the sample rate).
- * PARAM_ENABLED - 1 to enable the compressor, 0 to disable it.
- */
-enum { PARAM_THRESHOLD,
- PARAM_KNEE,
- PARAM_RATIO,
- PARAM_ATTACK,
- PARAM_RELEASE,
- PARAM_PRE_DELAY,
- PARAM_RELEASE_ZONE1,
- PARAM_RELEASE_ZONE2,
- PARAM_RELEASE_ZONE3,
- PARAM_RELEASE_ZONE4,
- PARAM_POST_GAIN,
- PARAM_FILTER_STAGE_GAIN,
- PARAM_FILTER_STAGE_RATIO,
- PARAM_FILTER_ANCHOR,
- PARAM_CROSSOVER_LOWER_FREQ,
- PARAM_ENABLED,
- PARAM_LAST };
-
-/* The number of compressor kernels (also the number of bands). */
-#define DRC_NUM_KERNELS 3
-
-/* The maximum number of frames can be passed to drc_process() call. */
-#define DRC_PROCESS_MAX_FRAMES 2048
-
-/* The default value of PARAM_PRE_DELAY in seconds. */
-#define DRC_DEFAULT_PRE_DELAY 0.006f
-
-struct drc {
- /* sample rate in Hz */
- float sample_rate;
-
- /* 1 to disable the emphasis and deemphasis, 0 to enable it. */
- int emphasis_disabled;
-
- /* parameters holds the tweakable compressor parameters. */
- float parameters[DRC_NUM_KERNELS][PARAM_LAST];
-
- /* The emphasis filter and deemphasis filter */
- struct eq2 *emphasis_eq;
- struct eq2 *deemphasis_eq;
-
- /* The crossover filter */
- struct crossover2 xo2;
-
- /* The compressor kernels */
- struct drc_kernel kernel[DRC_NUM_KERNELS];
-
- /* Temporary buffer used during drc_process(). The mid and high band
- * signal is stored in these buffers (the low band is stored in the
- * original input buffer). */
- float *data1[DRC_NUM_CHANNELS];
- float *data2[DRC_NUM_CHANNELS];
-};
-
-/* DRC needs the parameters to be set before initialization. So drc_new() should
- * be called first to allocated an instance, then drc_set_param() is called
- * (multiple times) to set the parameters. Finally drc_init() is called to do
- * the initialization. After that drc_process() can be used to process data. The
- * sequence is:
- *
- * drc_new();
- * drc_set_param();
- * ...
- * drc_set_param();
- * drc_init();
- * drc_process();
- * ...
- * drc_process();
- * drc_free();
- */
-
-/* Allocates a DRC. */
-struct drc *drc_new(float sample_rate);
-
-/* Initializes a DRC. */
-void drc_init(struct drc *drc);
-
-/* Frees a DRC.*/
-void drc_free(struct drc *drc);
-
-/* Processes input data using a DRC.
- * Args:
- * drc - The DRC we want to use.
- * float **data - Pointers to input/output data. The input must be stereo
- * and one channel is pointed by data[0], another pointed by data[1]. The
- * output data is stored in the same place.
- * frames - The number of frames to process.
- */
-void drc_process(struct drc *drc, float **data, int frames);
-
-/* Sets a parameter for the DRC.
- * Args:
- * drc - The DRC we want to use.
- * index - The index of the kernel we want to set its parameter.
- * paramID - One of the PARAM_* enum constant.
- * value - The parameter value
- */
-void drc_set_param(struct drc *drc, int index, unsigned paramID, float value);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* DRC_H_ */
diff --git a/cras/src/dsp/drc_kernel.c b/cras/src/dsp/drc_kernel.c
deleted file mode 100644
index 8c3404fc..00000000
--- a/cras/src/dsp/drc_kernel.c
+++ /dev/null
@@ -1,1060 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Copyright (C) 2011 Google Inc. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE.WEBKIT file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "drc_math.h"
-#include "drc_kernel.h"
-
-#define MAX_PRE_DELAY_FRAMES 1024
-#define MAX_PRE_DELAY_FRAMES_MASK (MAX_PRE_DELAY_FRAMES - 1)
-#define DEFAULT_PRE_DELAY_FRAMES 256
-#define DIVISION_FRAMES 32
-#define DIVISION_FRAMES_MASK (DIVISION_FRAMES - 1)
-
-#define assert_on_compile(e) ((void)sizeof(char[1 - 2 * !(e)]))
-#define assert_on_compile_is_power_of_2(n) \
- assert_on_compile((n) != 0 && (((n) & ((n)-1)) == 0))
-
-const float uninitialized_value = -1;
-static int drc_math_initialized;
-
-void dk_init(struct drc_kernel *dk, float sample_rate)
-{
- int i;
-
- if (!drc_math_initialized) {
- drc_math_initialized = 1;
- drc_math_init();
- }
-
- dk->sample_rate = sample_rate;
- dk->detector_average = 0;
- dk->compressor_gain = 1;
- dk->enabled = 0;
- dk->processed = 0;
- dk->last_pre_delay_frames = DEFAULT_PRE_DELAY_FRAMES;
- dk->pre_delay_read_index = 0;
- dk->pre_delay_write_index = DEFAULT_PRE_DELAY_FRAMES;
- dk->max_attack_compression_diff_db = -INFINITY;
- dk->ratio = uninitialized_value;
- dk->slope = uninitialized_value;
- dk->linear_threshold = uninitialized_value;
- dk->db_threshold = uninitialized_value;
- dk->db_knee = uninitialized_value;
- dk->knee_threshold = uninitialized_value;
- dk->ratio_base = uninitialized_value;
- dk->K = uninitialized_value;
-
- assert_on_compile_is_power_of_2(DIVISION_FRAMES);
- assert_on_compile(DIVISION_FRAMES % 4 == 0);
- /* Allocate predelay buffers */
- assert_on_compile_is_power_of_2(MAX_PRE_DELAY_FRAMES);
- for (i = 0; i < DRC_NUM_CHANNELS; i++) {
- size_t size = sizeof(float) * MAX_PRE_DELAY_FRAMES;
- dk->pre_delay_buffers[i] = (float *)calloc(1, size);
- }
-}
-
-void dk_free(struct drc_kernel *dk)
-{
- int i;
- for (i = 0; i < DRC_NUM_CHANNELS; ++i)
- free(dk->pre_delay_buffers[i]);
-}
-
-/* Sets the pre-delay (lookahead) buffer size */
-static void set_pre_delay_time(struct drc_kernel *dk, float pre_delay_time)
-{
- int i;
- /* Re-configure look-ahead section pre-delay if delay time has
- * changed. */
- unsigned pre_delay_frames = pre_delay_time * dk->sample_rate;
- pre_delay_frames = min(pre_delay_frames, MAX_PRE_DELAY_FRAMES - 1);
-
- /* Make pre_delay_frames multiplies of DIVISION_FRAMES. This way we
- * won't split a division of samples into two blocks of memory, so it is
- * easier to process. This may make the actual delay time slightly less
- * than the specified value, but the difference is less than 1ms. */
- pre_delay_frames &= ~DIVISION_FRAMES_MASK;
-
- /* We need at least one division buffer, so the incoming data won't
- * overwrite the output data */
- pre_delay_frames = max(pre_delay_frames, DIVISION_FRAMES);
-
- if (dk->last_pre_delay_frames != pre_delay_frames) {
- dk->last_pre_delay_frames = pre_delay_frames;
- for (i = 0; i < DRC_NUM_CHANNELS; ++i) {
- size_t size = sizeof(float) * MAX_PRE_DELAY_FRAMES;
- memset(dk->pre_delay_buffers[i], 0, size);
- }
-
- dk->pre_delay_read_index = 0;
- dk->pre_delay_write_index = pre_delay_frames;
- }
-}
-
-/* Exponential curve for the knee. It is 1st derivative matched at
- * dk->linear_threshold and asymptotically approaches the value
- * dk->linear_threshold + 1 / k.
- *
- * This is used only when calculating the static curve, not used when actually
- * compress the input data (knee_curveK below is used instead).
- */
-static float knee_curve(struct drc_kernel *dk, float x, float k)
-{
- /* Linear up to threshold. */
- if (x < dk->linear_threshold)
- return x;
-
- return dk->linear_threshold +
- (1 - knee_expf(-k * (x - dk->linear_threshold))) / k;
-}
-
-/* Approximate 1st derivative with input and output expressed in dB. This slope
- * is equal to the inverse of the compression "ratio". In other words, a
- * compression ratio of 20 would be a slope of 1/20.
- */
-static float slope_at(struct drc_kernel *dk, float x, float k)
-{
- if (x < dk->linear_threshold)
- return 1;
-
- float x2 = x * 1.001;
-
- float x_db = linear_to_decibels(x);
- float x2Db = linear_to_decibels(x2);
-
- float y_db = linear_to_decibels(knee_curve(dk, x, k));
- float y2Db = linear_to_decibels(knee_curve(dk, x2, k));
-
- float m = (y2Db - y_db) / (x2Db - x_db);
-
- return m;
-}
-
-static float k_at_slope(struct drc_kernel *dk, float desired_slope)
-{
- float x_db = dk->db_threshold + dk->db_knee;
- float x = decibels_to_linear(x_db);
-
- /* Approximate k given initial values. */
- float minK = 0.1;
- float maxK = 10000;
- float k = 5;
- int i;
-
- for (i = 0; i < 15; ++i) {
- /* A high value for k will more quickly asymptotically approach
- * a slope of 0. */
- float slope = slope_at(dk, x, k);
-
- if (slope < desired_slope) {
- /* k is too high. */
- maxK = k;
- } else {
- /* k is too low. */
- minK = k;
- }
-
- /* Re-calculate based on geometric mean. */
- k = sqrtf(minK * maxK);
- }
-
- return k;
-}
-
-static void update_static_curve_parameters(struct drc_kernel *dk,
- float db_threshold, float db_knee,
- float ratio)
-{
- if (db_threshold != dk->db_threshold || db_knee != dk->db_knee ||
- ratio != dk->ratio) {
- /* Threshold and knee. */
- dk->db_threshold = db_threshold;
- dk->linear_threshold = decibels_to_linear(db_threshold);
- dk->db_knee = db_knee;
-
- /* Compute knee parameters. */
- dk->ratio = ratio;
- dk->slope = 1 / dk->ratio;
-
- float k = k_at_slope(dk, 1 / dk->ratio);
- dk->K = k;
- /* See knee_curveK() for details */
- dk->knee_alpha = dk->linear_threshold + 1 / k;
- dk->knee_beta = -expf(k * dk->linear_threshold) / k;
-
- dk->knee_threshold = decibels_to_linear(db_threshold + db_knee);
- /* See volume_gain() for details */
- float y0 = knee_curve(dk, dk->knee_threshold, k);
- dk->ratio_base = y0 * powf(dk->knee_threshold, -dk->slope);
- }
-}
-
-/* This is the knee part of the compression curve. Returns the output level
- * given the input level x. */
-static float knee_curveK(struct drc_kernel *dk, float x)
-{
- /* The formula in knee_curveK is dk->linear_threshold +
- * (1 - expf(-k * (x - dk->linear_threshold))) / k
- * which simplifies to (alpha + beta * expf(gamma))
- * where alpha = dk->linear_threshold + 1 / k
- * beta = -expf(k * dk->linear_threshold) / k
- * gamma = -k * x
- */
- return dk->knee_alpha + dk->knee_beta * knee_expf(-dk->K * x);
-}
-
-/* Full compression curve with constant ratio after knee. Returns the ratio of
- * output and input signal. */
-static float volume_gain(struct drc_kernel *dk, float x)
-{
- float y;
-
- if (x < dk->knee_threshold) {
- if (x < dk->linear_threshold)
- return 1;
- y = knee_curveK(dk, x) / x;
- } else {
- /* Constant ratio after knee.
- * log(y/y0) = s * log(x/x0)
- * => y = y0 * (x/x0)^s
- * => y = [y0 * (1/x0)^s] * x^s
- * => y = dk->ratio_base * x^s
- * => y/x = dk->ratio_base * x^(s - 1)
- * => y/x = dk->ratio_base * e^(log(x) * (s - 1))
- */
- y = dk->ratio_base * knee_expf(logf(x) * (dk->slope - 1));
- }
-
- return y;
-}
-
-void dk_set_parameters(struct drc_kernel *dk, float db_threshold, float db_knee,
- float ratio, float attack_time, float release_time,
- float pre_delay_time, float db_post_gain,
- float releaseZone1, float releaseZone2,
- float releaseZone3, float releaseZone4)
-{
- float sample_rate = dk->sample_rate;
-
- update_static_curve_parameters(dk, db_threshold, db_knee, ratio);
-
- /* Makeup gain. */
- float full_range_gain = volume_gain(dk, 1);
- float full_range_makeup_gain = 1 / full_range_gain;
-
- /* Empirical/perceptual tuning. */
- full_range_makeup_gain = powf(full_range_makeup_gain, 0.6f);
-
- dk->main_linear_gain =
- decibels_to_linear(db_post_gain) * full_range_makeup_gain;
-
- /* Attack parameters. */
- attack_time = max(0.001f, attack_time);
- dk->attack_frames = attack_time * sample_rate;
-
- /* Release parameters. */
- float release_frames = sample_rate * release_time;
-
- /* Detector release time. */
- float sat_release_time = 0.0025f;
- float sat_release_frames = sat_release_time * sample_rate;
- dk->sat_release_frames_inv_neg = -1 / sat_release_frames;
- dk->sat_release_rate_at_neg_two_db =
- decibels_to_linear(-2 * dk->sat_release_frames_inv_neg) - 1;
-
- /* Create a smooth function which passes through four points.
- * Polynomial of the form y = a + b*x + c*x^2 + d*x^3 + e*x^4
- */
- float y1 = release_frames * releaseZone1;
- float y2 = release_frames * releaseZone2;
- float y3 = release_frames * releaseZone3;
- float y4 = release_frames * releaseZone4;
-
- /* All of these coefficients were derived for 4th order polynomial curve
- * fitting where the y values match the evenly spaced x values as
- * follows: (y1 : x == 0, y2 : x == 1, y3 : x == 2, y4 : x == 3)
- */
- dk->kA = 0.9999999999999998f * y1 + 1.8432219684323923e-16f * y2 -
- 1.9373394351676423e-16f * y3 + 8.824516011816245e-18f * y4;
- dk->kB = -1.5788320352845888f * y1 + 2.3305837032074286f * y2 -
- 0.9141194204840429f * y3 + 0.1623677525612032f * y4;
- dk->kC = 0.5334142869106424f * y1 - 1.272736789213631f * y2 +
- 0.9258856042207512f * y3 - 0.18656310191776226f * y4;
- dk->kD = 0.08783463138207234f * y1 - 0.1694162967925622f * y2 +
- 0.08588057951595272f * y3 - 0.00429891410546283f * y4;
- dk->kE = -0.042416883008123074f * y1 + 0.1115693827987602f * y2 -
- 0.09764676325265872f * y3 + 0.028494263462021576f * y4;
-
- /* x ranges from 0 -> 3 0 1 2 3
- * -15 -10 -5 0db
- *
- * y calculates adaptive release frames depending on the amount of
- * compression.
- */
- set_pre_delay_time(dk, pre_delay_time);
-}
-
-void dk_set_enabled(struct drc_kernel *dk, int enabled)
-{
- dk->enabled = enabled;
-}
-
-/* Updates the envelope_rate used for the next division */
-static void dk_update_envelope(struct drc_kernel *dk)
-{
- const float kA = dk->kA;
- const float kB = dk->kB;
- const float kC = dk->kC;
- const float kD = dk->kD;
- const float kE = dk->kE;
- const float attack_frames = dk->attack_frames;
-
- /* Calculate desired gain */
- float desired_gain = dk->detector_average;
-
- /* Pre-warp so we get desired_gain after sin() warp below. */
- float scaled_desired_gain = warp_asinf(desired_gain);
-
- /* Deal with envelopes */
-
- /* envelope_rate is the rate we slew from current compressor level to
- * the desired level. The exact rate depends on if we're attacking or
- * releasing and by how much.
- */
- float envelope_rate;
-
- int is_releasing = scaled_desired_gain > dk->compressor_gain;
-
- /* compression_diff_db is the difference between current compression
- * level and the desired level. */
- float compression_diff_db =
- linear_to_decibels(dk->compressor_gain / scaled_desired_gain);
-
- if (is_releasing) {
- /* Release mode - compression_diff_db should be negative dB */
- dk->max_attack_compression_diff_db = -INFINITY;
-
- /* Fix gremlins. */
- if (isbadf(compression_diff_db))
- compression_diff_db = -1;
-
- /* Adaptive release - higher compression (lower
- * compression_diff_db) releases faster. Contain within range:
- * -12 -> 0 then scale to go from 0 -> 3
- */
- float x = compression_diff_db;
- x = max(-12.0f, x);
- x = min(0.0f, x);
- x = 0.25f * (x + 12);
-
- /* Compute adaptive release curve using 4th order polynomial.
- * Normal values for the polynomial coefficients would create a
- * monotonically increasing function.
- */
- float x2 = x * x;
- float x3 = x2 * x;
- float x4 = x2 * x2;
- float release_frames =
- kA + kB * x + kC * x2 + kD * x3 + kE * x4;
-
-#define kSpacingDb 5
- float db_per_frame = kSpacingDb / release_frames;
- envelope_rate = decibels_to_linear(db_per_frame);
- } else {
- /* Attack mode - compression_diff_db should be positive dB */
-
- /* Fix gremlins. */
- if (isbadf(compression_diff_db))
- compression_diff_db = 1;
-
- /* As long as we're still in attack mode, use a rate based off
- * the largest compression_diff_db we've encountered so far.
- */
- dk->max_attack_compression_diff_db =
- max(dk->max_attack_compression_diff_db,
- compression_diff_db);
-
- float eff_atten_diff_db =
- max(0.5f, dk->max_attack_compression_diff_db);
-
- float x = 0.25f / eff_atten_diff_db;
- envelope_rate = 1 - powf(x, 1 / attack_frames);
- }
-
- dk->envelope_rate = envelope_rate;
- dk->scaled_desired_gain = scaled_desired_gain;
-}
-
-/* For a division of frames, take the absolute values of left channel and right
- * channel, store the maximum of them in output. */
-#if defined(__aarch64__)
-static inline void max_abs_division(float *output, const float *data0,
- const float *data1)
-{
- int count = DIVISION_FRAMES / 4;
-
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "ld1 {v0.4s}, [%[data0]], #16 \n"
- "ld1 {v1.4s}, [%[data1]], #16 \n"
- "fabs v0.4s, v0.4s \n"
- "fabs v1.4s, v1.4s \n"
- "fmax v0.4s, v0.4s, v1.4s \n"
- "st1 {v0.4s}, [%[output]], #16 \n"
- "subs %w[count], %w[count], #1 \n"
- "b.ne 1b \n"
- : /* output */
- [data0]"+r"(data0),
- [data1]"+r"(data1),
- [output]"+r"(output),
- [count]"+r"(count)
- : /* input */
- : /* clobber */
- "v0", "v1", "memory", "cc");
- // clang-format on
-}
-#elif defined(__ARM_NEON__)
-static inline void max_abs_division(float *output, const float *data0,
- const float *data1)
-{
- int count = DIVISION_FRAMES / 4;
-
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "vld1.32 {q0}, [%[data0]]! \n"
- "vld1.32 {q1}, [%[data1]]! \n"
- "vabs.f32 q0, q0 \n"
- "vabs.f32 q1, q1 \n"
- "vmax.f32 q0, q1 \n"
- "vst1.32 {q0}, [%[output]]! \n"
- "subs %[count], #1 \n"
- "bne 1b \n"
- : /* output */
- [data0]"+r"(data0),
- [data1]"+r"(data1),
- [output]"+r"(output),
- [count]"+r"(count)
- : /* input */
- : /* clobber */
- "q0", "q1", "memory", "cc");
- // clang-format on
-}
-#elif defined(__SSE3__)
-#include <emmintrin.h>
-static inline void max_abs_division(float *output, const float *data0,
- const float *data1)
-{
- __m128 x, y;
- int count = DIVISION_FRAMES / 4;
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "lddqu (%[data0]), %[x] \n"
- "lddqu (%[data1]), %[y] \n"
- "andps %[mask], %[x] \n"
- "andps %[mask], %[y] \n"
- "maxps %[y], %[x] \n"
- "movdqu %[x], (%[output]) \n"
- "add $16, %[data0] \n"
- "add $16, %[data1] \n"
- "add $16, %[output] \n"
- "sub $1, %[count] \n"
- "jnz 1b \n"
- : /* output */
- [data0]"+r"(data0),
- [data1]"+r"(data1),
- [output]"+r"(output),
- [count]"+r"(count),
- [x]"=&x"(x),
- [y]"=&x"(y)
- : /* input */
- [mask]"x"(_mm_set1_epi32(0x7fffffff))
- : /* clobber */
- "memory", "cc");
- // clang-format on
-}
-#else
-static inline void max_abs_division(float *output, const float *data0,
- const float *data1)
-{
- int i;
- for (i = 0; i < DIVISION_FRAMES; i++)
- output[i] = fmaxf(fabsf(data0[i]), fabsf(data1[i]));
-}
-#endif
-
-/* Update detector_average from the last input division. */
-static void dk_update_detector_average(struct drc_kernel *dk)
-{
- float abs_input_array[DIVISION_FRAMES];
- const float sat_release_frames_inv_neg = dk->sat_release_frames_inv_neg;
- const float sat_release_rate_at_neg_two_db =
- dk->sat_release_rate_at_neg_two_db;
- float detector_average = dk->detector_average;
- int div_start, i;
-
- /* Calculate the start index of the last input division */
- if (dk->pre_delay_write_index == 0) {
- div_start = MAX_PRE_DELAY_FRAMES - DIVISION_FRAMES;
- } else {
- div_start = dk->pre_delay_write_index - DIVISION_FRAMES;
- }
-
- /* The max abs value across all channels for this frame */
- max_abs_division(abs_input_array, &dk->pre_delay_buffers[0][div_start],
- &dk->pre_delay_buffers[1][div_start]);
-
- for (i = 0; i < DIVISION_FRAMES; i++) {
- /* Compute compression amount from un-delayed signal */
- float abs_input = abs_input_array[i];
-
- /* Calculate shaped power on undelayed input. Put through
- * shaping curve. This is linear up to the threshold, then
- * enters a "knee" portion followed by the "ratio" portion. The
- * transition from the threshold to the knee is smooth (1st
- * derivative matched). The transition from the knee to the
- * ratio portion is smooth (1st derivative matched).
- */
- float gain = volume_gain(dk, abs_input);
- int is_release = (gain > detector_average);
- if (is_release) {
- if (gain > NEG_TWO_DB) {
- detector_average +=
- (gain - detector_average) *
- sat_release_rate_at_neg_two_db;
- } else {
- float gain_db = linear_to_decibels(gain);
- float db_per_frame =
- gain_db * sat_release_frames_inv_neg;
- float sat_release_rate =
- decibels_to_linear(db_per_frame) - 1;
- detector_average += (gain - detector_average) *
- sat_release_rate;
- }
- } else {
- detector_average = gain;
- }
-
- /* Fix gremlins. */
- if (isbadf(detector_average))
- detector_average = 1.0f;
- else
- detector_average = min(detector_average, 1.0f);
- }
-
- dk->detector_average = detector_average;
-}
-
-/* Calculate compress_gain from the envelope and apply total_gain to compress
- * the next output division. */
-/* TODO(fbarchard): Port to aarch64 */
-#if defined(__ARM_NEON__)
-#include <arm_neon.h>
-static void dk_compress_output(struct drc_kernel *dk)
-{
- const float main_linear_gain = dk->main_linear_gain;
- const float envelope_rate = dk->envelope_rate;
- const float scaled_desired_gain = dk->scaled_desired_gain;
- const float compressor_gain = dk->compressor_gain;
- const int div_start = dk->pre_delay_read_index;
- float *ptr_left = &dk->pre_delay_buffers[0][div_start];
- float *ptr_right = &dk->pre_delay_buffers[1][div_start];
- int count = DIVISION_FRAMES / 4;
-
- /* See warp_sinf() for the details for the constants. */
- const float32x4_t A7 = vdupq_n_f32(-4.3330336920917034149169921875e-3f);
- const float32x4_t A5 = vdupq_n_f32(7.9434238374233245849609375e-2f);
- const float32x4_t A3 = vdupq_n_f32(-0.645892798900604248046875f);
- const float32x4_t A1 = vdupq_n_f32(1.5707910060882568359375f);
-
- /* Exponential approach to desired gain. */
- if (envelope_rate < 1) {
- float c = compressor_gain - scaled_desired_gain;
- float r = 1 - envelope_rate;
- float32x4_t x0 = { c * r, c * r * r, c * r * r * r,
- c * r * r * r * r };
- float32x4_t x, x2, x4, left, right, tmp1, tmp2;
-
- // clang-format off
- __asm__ __volatile(
- "b 2f \n"
- "1: \n"
- "vmul.f32 %q[x0], %q[r4] \n"
- "2: \n"
- "vld1.32 {%e[left],%f[left]}, [%[ptr_left]] \n"
- "vld1.32 {%e[right],%f[right]}, [%[ptr_right]] \n"
- "vadd.f32 %q[x], %q[x0], %q[base] \n"
- /* Calculate warp_sin() for four values in x. */
- "vmul.f32 %q[x2], %q[x], %q[x] \n"
- "vmov.f32 %q[tmp1], %q[A5] \n"
- "vmov.f32 %q[tmp2], %q[A1] \n"
- "vmul.f32 %q[x4], %q[x2], %q[x2] \n"
- "vmla.f32 %q[tmp1], %q[A7], %q[x2] \n"
- "vmla.f32 %q[tmp2], %q[A3], %q[x2] \n"
- "vmla.f32 %q[tmp2], %q[tmp1], %q[x4] \n"
- "vmul.f32 %q[tmp2], %q[tmp2], %q[x] \n"
- /* Now tmp2 contains the result of warp_sin(). */
- "vmul.f32 %q[tmp2], %q[tmp2], %q[g] \n"
- "vmul.f32 %q[left], %q[tmp2] \n"
- "vmul.f32 %q[right], %q[tmp2] \n"
- "vst1.32 {%e[left],%f[left]}, [%[ptr_left]]! \n"
- "vst1.32 {%e[right],%f[right]}, [%[ptr_right]]! \n"
- "subs %[count], #1 \n"
- "bne 1b \n"
- : /* output */
- "=r"(count),
- "=r"(ptr_left),
- "=r"(ptr_right),
- "=w"(x0),
- [x]"=&w"(x),
- [x2]"=&w"(x2),
- [x4]"=&w"(x4),
- [left]"=&w"(left),
- [right]"=&w"(right),
- [tmp1]"=&w"(tmp1),
- [tmp2]"=&w"(tmp2)
- : /* input */
- [count]"0"(count),
- [ptr_left]"1"(ptr_left),
- [ptr_right]"2"(ptr_right),
- [x0]"3"(x0),
- [A1]"w"(A1),
- [A3]"w"(A3),
- [A5]"w"(A5),
- [A7]"w"(A7),
- [base]"w"(vdupq_n_f32(scaled_desired_gain)),
- [r4]"w"(vdupq_n_f32(r*r*r*r)),
- [g]"w"(vdupq_n_f32(main_linear_gain))
- : /* clobber */
- "memory", "cc");
- // clang-format on
- dk->compressor_gain = x[3];
- } else {
- float c = compressor_gain;
- float r = envelope_rate;
- float32x4_t x = { c * r, c * r * r, c * r * r * r,
- c * r * r * r * r };
- float32x4_t x2, x4, left, right, tmp1, tmp2;
-
- // clang-format off
- __asm__ __volatile(
- "b 2f \n"
- "1: \n"
- "vmul.f32 %q[x], %q[r4] \n"
- "2: \n"
- "vld1.32 {%e[left],%f[left]}, [%[ptr_left]] \n"
- "vld1.32 {%e[right],%f[right]}, [%[ptr_right]] \n"
- "vmin.f32 %q[x], %q[one] \n"
- /* Calculate warp_sin() for four values in x. */
- "vmul.f32 %q[x2], %q[x], %q[x] \n"
- "vmov.f32 %q[tmp1], %q[A5] \n"
- "vmov.f32 %q[tmp2], %q[A1] \n"
- "vmul.f32 %q[x4], %q[x2], %q[x2] \n"
- "vmla.f32 %q[tmp1], %q[A7], %q[x2] \n"
- "vmla.f32 %q[tmp2], %q[A3], %q[x2] \n"
- "vmla.f32 %q[tmp2], %q[tmp1], %q[x4] \n"
- "vmul.f32 %q[tmp2], %q[tmp2], %q[x] \n"
- /* Now tmp2 contains the result of warp_sin(). */
- "vmul.f32 %q[tmp2], %q[tmp2], %q[g] \n"
- "vmul.f32 %q[left], %q[tmp2] \n"
- "vmul.f32 %q[right], %q[tmp2] \n"
- "vst1.32 {%e[left],%f[left]}, [%[ptr_left]]! \n"
- "vst1.32 {%e[right],%f[right]}, [%[ptr_right]]! \n"
- "subs %[count], #1 \n"
- "bne 1b \n"
- : /* output */
- "=r"(count),
- "=r"(ptr_left),
- "=r"(ptr_right),
- "=w"(x),
- [x2]"=&w"(x2),
- [x4]"=&w"(x4),
- [left]"=&w"(left),
- [right]"=&w"(right),
- [tmp1]"=&w"(tmp1),
- [tmp2]"=&w"(tmp2)
- : /* input */
- [count]"0"(count),
- [ptr_left]"1"(ptr_left),
- [ptr_right]"2"(ptr_right),
- [x]"3"(x),
- [A1]"w"(A1),
- [A3]"w"(A3),
- [A5]"w"(A5),
- [A7]"w"(A7),
- [one]"w"(vdupq_n_f32(1)),
- [r4]"w"(vdupq_n_f32(r*r*r*r)),
- [g]"w"(vdupq_n_f32(main_linear_gain))
- : /* clobber */
- "memory", "cc");
- // clang-format on
- dk->compressor_gain = x[3];
- }
-}
-#elif defined(__SSE3__) && defined(__x86_64__)
-#include <emmintrin.h>
-static void dk_compress_output(struct drc_kernel *dk)
-{
- const float main_linear_gain = dk->main_linear_gain;
- const float envelope_rate = dk->envelope_rate;
- const float scaled_desired_gain = dk->scaled_desired_gain;
- const float compressor_gain = dk->compressor_gain;
- const int div_start = dk->pre_delay_read_index;
- float *ptr_left = &dk->pre_delay_buffers[0][div_start];
- float *ptr_right = &dk->pre_delay_buffers[1][div_start];
- int count = DIVISION_FRAMES / 4;
-
- /* See warp_sinf() for the details for the constants. */
- const __m128 A7 = _mm_set1_ps(-4.3330336920917034149169921875e-3f);
- const __m128 A5 = _mm_set1_ps(7.9434238374233245849609375e-2f);
- const __m128 A3 = _mm_set1_ps(-0.645892798900604248046875f);
- const __m128 A1 = _mm_set1_ps(1.5707910060882568359375f);
-
- /* Exponential approach to desired gain. */
- if (envelope_rate < 1) {
- float c = compressor_gain - scaled_desired_gain;
- float r = 1 - envelope_rate;
- __m128 x0 = { c * r, c * r * r, c * r * r * r,
- c * r * r * r * r };
- __m128 x, x2, x4, left, right, tmp1, tmp2;
-
- // clang-format off
- __asm__ __volatile(
- "jmp 2f \n"
- "1: \n"
- "mulps %[r4], %[x0] \n"
- "2: \n"
- "lddqu (%[ptr_left]), %[left] \n"
- "lddqu (%[ptr_right]), %[right] \n"
- "movaps %[x0], %[x] \n"
- "addps %[base], %[x] \n"
- /* Calculate warp_sin() for four values in x. */
- "movaps %[x], %[x2] \n"
- "mulps %[x], %[x2] \n"
- "movaps %[x2], %[x4] \n"
- "movaps %[x2], %[tmp1] \n"
- "movaps %[x2], %[tmp2] \n"
- "mulps %[x2], %[x4] \n"
- "mulps %[A7], %[tmp1] \n"
- "mulps %[A3], %[tmp2] \n"
- "addps %[A5], %[tmp1] \n"
- "addps %[A1], %[tmp2] \n"
- "mulps %[x4], %[tmp1] \n"
- "addps %[tmp1], %[tmp2] \n"
- "mulps %[x], %[tmp2] \n"
- /* Now tmp2 contains the result of warp_sin(). */
- "mulps %[g], %[tmp2] \n"
- "mulps %[tmp2], %[left] \n"
- "mulps %[tmp2], %[right] \n"
- "movdqu %[left], (%[ptr_left]) \n"
- "movdqu %[right], (%[ptr_right]) \n"
- "add $16, %[ptr_left] \n"
- "add $16, %[ptr_right] \n"
- "sub $1, %[count] \n"
- "jne 1b \n"
- : /* output */
- "=r"(count),
- "=r"(ptr_left),
- "=r"(ptr_right),
- "=x"(x0),
- [x]"=&x"(x),
- [x2]"=&x"(x2),
- [x4]"=&x"(x4),
- [left]"=&x"(left),
- [right]"=&x"(right),
- [tmp1]"=&x"(tmp1),
- [tmp2]"=&x"(tmp2)
- : /* input */
- [count]"0"(count),
- [ptr_left]"1"(ptr_left),
- [ptr_right]"2"(ptr_right),
- [x0]"3"(x0),
- [A1]"x"(A1),
- [A3]"x"(A3),
- [A5]"x"(A5),
- [A7]"x"(A7),
- [base]"x"(_mm_set1_ps(scaled_desired_gain)),
- [r4]"x"(_mm_set1_ps(r*r*r*r)),
- [g]"x"(_mm_set1_ps(main_linear_gain))
- : /* clobber */
- "memory", "cc");
- // clang-format on
- dk->compressor_gain = x[3];
- } else {
- /* See warp_sinf() for the details for the constants. */
- __m128 A7 = _mm_set1_ps(-4.3330336920917034149169921875e-3f);
- __m128 A5 = _mm_set1_ps(7.9434238374233245849609375e-2f);
- __m128 A3 = _mm_set1_ps(-0.645892798900604248046875f);
- __m128 A1 = _mm_set1_ps(1.5707910060882568359375f);
-
- float c = compressor_gain;
- float r = envelope_rate;
- __m128 x = { c * r, c * r * r, c * r * r * r,
- c * r * r * r * r };
- __m128 x2, x4, left, right, tmp1, tmp2;
-
- // clang-format off
- __asm__ __volatile(
- "jmp 2f \n"
- "1: \n"
- "mulps %[r4], %[x] \n"
- "2: \n"
- "lddqu (%[ptr_left]), %[left] \n"
- "lddqu (%[ptr_right]), %[right] \n"
- "minps %[one], %[x] \n"
- /* Calculate warp_sin() for four values in x. */
- "movaps %[x], %[x2] \n"
- "mulps %[x], %[x2] \n"
- "movaps %[x2], %[x4] \n"
- "movaps %[x2], %[tmp1] \n"
- "movaps %[x2], %[tmp2] \n"
- "mulps %[x2], %[x4] \n"
- "mulps %[A7], %[tmp1] \n"
- "mulps %[A3], %[tmp2] \n"
- "addps %[A5], %[tmp1] \n"
- "addps %[A1], %[tmp2] \n"
- "mulps %[x4], %[tmp1] \n"
- "addps %[tmp1], %[tmp2] \n"
- "mulps %[x], %[tmp2] \n"
- /* Now tmp2 contains the result of warp_sin(). */
- "mulps %[g], %[tmp2] \n"
- "mulps %[tmp2], %[left] \n"
- "mulps %[tmp2], %[right] \n"
- "movdqu %[left], (%[ptr_left]) \n"
- "movdqu %[right], (%[ptr_right]) \n"
- "add $16, %[ptr_left] \n"
- "add $16, %[ptr_right] \n"
- "sub $1, %[count] \n"
- "jne 1b \n"
- : /* output */
- "=r"(count),
- "=r"(ptr_left),
- "=r"(ptr_right),
- "=x"(x),
- [x2]"=&x"(x2),
- [x4]"=&x"(x4),
- [left]"=&x"(left),
- [right]"=&x"(right),
- [tmp1]"=&x"(tmp1),
- [tmp2]"=&x"(tmp2)
- : /* input */
- [count]"0"(count),
- [ptr_left]"1"(ptr_left),
- [ptr_right]"2"(ptr_right),
- [x]"3"(x),
- [A1]"x"(A1),
- [A3]"x"(A3),
- [A5]"x"(A5),
- [A7]"x"(A7),
- [one]"x"(_mm_set1_ps(1)),
- [r4]"x"(_mm_set1_ps(r*r*r*r)),
- [g]"x"(_mm_set1_ps(main_linear_gain))
- : /* clobber */
- "memory", "cc");
- // clang-format on
- dk->compressor_gain = x[3];
- }
-}
-#else
-static void dk_compress_output(struct drc_kernel *dk)
-{
- const float main_linear_gain = dk->main_linear_gain;
- const float envelope_rate = dk->envelope_rate;
- const float scaled_desired_gain = dk->scaled_desired_gain;
- const float compressor_gain = dk->compressor_gain;
- const int div_start = dk->pre_delay_read_index;
- float *ptr_left = &dk->pre_delay_buffers[0][div_start];
- float *ptr_right = &dk->pre_delay_buffers[1][div_start];
- int count = DIVISION_FRAMES / 4;
-
- int i, j;
-
- /* Exponential approach to desired gain. */
- if (envelope_rate < 1) {
- /* Attack - reduce gain to desired. */
- float c = compressor_gain - scaled_desired_gain;
- float base = scaled_desired_gain;
- float r = 1 - envelope_rate;
- float x[4] = { c * r, c * r * r, c * r * r * r,
- c * r * r * r * r };
- float r4 = r * r * r * r;
-
- i = 0;
- while (1) {
- for (j = 0; j < 4; j++) {
- /* Warp pre-compression gain to smooth out sharp
- * exponential transition points.
- */
- float post_warp_compressor_gain =
- warp_sinf(x[j] + base);
-
- /* Calculate total gain using main gain. */
- float total_gain = main_linear_gain *
- post_warp_compressor_gain;
-
- /* Apply final gain. */
- *ptr_left++ *= total_gain;
- *ptr_right++ *= total_gain;
- }
-
- if (++i == count)
- break;
-
- for (j = 0; j < 4; j++)
- x[j] = x[j] * r4;
- }
-
- dk->compressor_gain = x[3] + base;
- } else {
- /* Release - exponentially increase gain to 1.0 */
- float c = compressor_gain;
- float r = envelope_rate;
- float x[4] = { c * r, c * r * r, c * r * r * r,
- c * r * r * r * r };
- float r4 = r * r * r * r;
-
- i = 0;
- while (1) {
- for (j = 0; j < 4; j++) {
- /* Warp pre-compression gain to smooth out sharp
- * exponential transition points.
- */
- float post_warp_compressor_gain =
- warp_sinf(x[j]);
-
- /* Calculate total gain using main gain. */
- float total_gain = main_linear_gain *
- post_warp_compressor_gain;
-
- /* Apply final gain. */
- *ptr_left++ *= total_gain;
- *ptr_right++ *= total_gain;
- }
-
- if (++i == count)
- break;
-
- for (j = 0; j < 4; j++)
- x[j] = min(1.0f, x[j] * r4);
- }
-
- dk->compressor_gain = x[3];
- }
-}
-#endif
-
-/* After one complete divison of samples have been received (and one divison of
- * samples have been output), we calculate shaped power average
- * (detector_average) from the input division, update envelope parameters from
- * detector_average, then prepare the next output division by applying the
- * envelope to compress the samples.
- */
-static void dk_process_one_division(struct drc_kernel *dk)
-{
- dk_update_detector_average(dk);
- dk_update_envelope(dk);
- dk_compress_output(dk);
-}
-
-/* Copy the input data to the pre-delay buffer, and copy the output data back to
- * the input buffer */
-static void dk_copy_fragment(struct drc_kernel *dk, float *data_channels[],
- unsigned frame_index, int frames_to_process)
-{
- int write_index = dk->pre_delay_write_index;
- int read_index = dk->pre_delay_read_index;
- int j;
-
- for (j = 0; j < DRC_NUM_CHANNELS; ++j) {
- memcpy(&dk->pre_delay_buffers[j][write_index],
- &data_channels[j][frame_index],
- frames_to_process * sizeof(float));
- memcpy(&data_channels[j][frame_index],
- &dk->pre_delay_buffers[j][read_index],
- frames_to_process * sizeof(float));
- }
-
- dk->pre_delay_write_index =
- (write_index + frames_to_process) & MAX_PRE_DELAY_FRAMES_MASK;
- dk->pre_delay_read_index =
- (read_index + frames_to_process) & MAX_PRE_DELAY_FRAMES_MASK;
-}
-
-/* Delay the input sample only and don't do other processing. This is used when
- * the kernel is disabled. We want to do this to match the processing delay in
- * kernels of other bands.
- */
-static void dk_process_delay_only(struct drc_kernel *dk, float *data_channels[],
- unsigned count)
-{
- int read_index = dk->pre_delay_read_index;
- int write_index = dk->pre_delay_write_index;
- int i = 0;
-
- while (i < count) {
- int j;
- int small = min(read_index, write_index);
- int large = max(read_index, write_index);
- /* chunk is the minimum of readable samples in contiguous
- * buffer, writable samples in contiguous buffer, and the
- * available input samples. */
- int chunk = min(large - small, MAX_PRE_DELAY_FRAMES - large);
- chunk = min(chunk, count - i);
- for (j = 0; j < DRC_NUM_CHANNELS; ++j) {
- memcpy(&dk->pre_delay_buffers[j][write_index],
- &data_channels[j][i], chunk * sizeof(float));
- memcpy(&data_channels[j][i],
- &dk->pre_delay_buffers[j][read_index],
- chunk * sizeof(float));
- }
- read_index = (read_index + chunk) & MAX_PRE_DELAY_FRAMES_MASK;
- write_index = (write_index + chunk) & MAX_PRE_DELAY_FRAMES_MASK;
- i += chunk;
- }
-
- dk->pre_delay_read_index = read_index;
- dk->pre_delay_write_index = write_index;
-}
-
-void dk_process(struct drc_kernel *dk, float *data_channels[], unsigned count)
-{
- int i = 0;
- int fragment;
-
- if (!dk->enabled) {
- dk_process_delay_only(dk, data_channels, count);
- return;
- }
-
- if (!dk->processed) {
- dk_update_envelope(dk);
- dk_compress_output(dk);
- dk->processed = 1;
- }
-
- int offset = dk->pre_delay_write_index & DIVISION_FRAMES_MASK;
- while (i < count) {
- fragment = min(DIVISION_FRAMES - offset, count - i);
- dk_copy_fragment(dk, data_channels, i, fragment);
- i += fragment;
- offset = (offset + fragment) & DIVISION_FRAMES_MASK;
-
- /* Process the input division (32 frames). */
- if (offset == 0)
- dk_process_one_division(dk);
- }
-}
diff --git a/cras/src/dsp/drc_kernel.h b/cras/src/dsp/drc_kernel.h
deleted file mode 100644
index 2ed9956e..00000000
--- a/cras/src/dsp/drc_kernel.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Copyright (C) 2011 Google Inc. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE.WEBKIT file.
- */
-
-#ifndef DRC_KERNEL_H_
-#define DRC_KERNEL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define DRC_NUM_CHANNELS 2
-
-struct drc_kernel {
- float sample_rate;
-
- /* The detector_average is the target gain obtained by looking at the
- * future samples in the lookahead buffer and applying the compression
- * curve on them. compressor_gain is the gain applied to the current
- * samples. compressor_gain moves towards detector_average with the
- * speed envelope_rate which is calculated once for each division (32
- * frames). */
- float detector_average;
- float compressor_gain;
- int enabled;
- int processed;
-
- /* Lookahead section. */
- unsigned last_pre_delay_frames;
- float *pre_delay_buffers[DRC_NUM_CHANNELS];
- int pre_delay_read_index;
- int pre_delay_write_index;
-
- float max_attack_compression_diff_db;
-
- /* Amount of input change in dB required for 1 dB of output change.
- * This applies to the portion of the curve above knee_threshold
- * (see below).
- */
- float ratio;
- float slope; /* Inverse ratio. */
-
- /* The input to output change below the threshold is 1:1. */
- float linear_threshold;
- float db_threshold;
-
- /* db_knee is the number of dB above the threshold before we enter the
- * "ratio" portion of the curve. The portion between db_threshold and
- * (db_threshold + db_knee) is the "soft knee" portion of the curve
- * which transitions smoothly from the linear portion to the ratio
- * portion. knee_threshold is db_to_linear(db_threshold + db_knee).
- */
- float db_knee;
- float knee_threshold;
- float ratio_base;
-
- /* Internal parameter for the knee portion of the curve. */
- float K;
-
- /* The release frames coefficients */
- float kA, kB, kC, kD, kE;
-
- /* Calculated parameters */
- float main_linear_gain;
- float attack_frames;
- float sat_release_frames_inv_neg;
- float sat_release_rate_at_neg_two_db;
- float knee_alpha, knee_beta;
-
- /* envelope for the current division */
- float envelope_rate;
- float scaled_desired_gain;
-};
-
-/* Initializes a drc kernel */
-void dk_init(struct drc_kernel *dk, float sample_rate);
-
-/* Frees a drc kernel */
-void dk_free(struct drc_kernel *dk);
-
-/* Sets the parameters of a drc kernel. See drc.h for details */
-void dk_set_parameters(struct drc_kernel *dk, float db_threshold, float db_knee,
- float ratio, float attack_time, float release_time,
- float pre_delay_time, float db_post_gain,
- float releaseZone1, float releaseZone2,
- float releaseZone3, float releaseZone4);
-
-/* Enables or disables a drc kernel */
-void dk_set_enabled(struct drc_kernel *dk, int enabled);
-
-/* Performs stereo-linked compression.
- * Args:
- * dk - The DRC kernel.
- * data - The pointers to the audio sample buffer. One pointer per channel.
- * count - The number of audio samples per channel.
- */
-void dk_process(struct drc_kernel *dk, float *data_channels[], unsigned count);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* DRC_KERNEL_H_ */
diff --git a/cras/src/dsp/drc_math.c b/cras/src/dsp/drc_math.c
deleted file mode 100644
index 1ee5c81a..00000000
--- a/cras/src/dsp/drc_math.c
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include "drc_math.h"
-
-float db_to_linear[201]; /* from -100dB to 100dB */
-
-void drc_math_init()
-{
- int i;
- for (i = -100; i <= 100; i++)
- db_to_linear[i + 100] = pow(10, i / 20.0);
-}
diff --git a/cras/src/dsp/drc_math.h b/cras/src/dsp/drc_math.h
deleted file mode 100644
index 970b7295..00000000
--- a/cras/src/dsp/drc_math.h
+++ /dev/null
@@ -1,217 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef DRC_MATH_H_
-#define DRC_MATH_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stddef.h>
-#include <math.h>
-
-#ifndef __BIONIC__
-#include <ieee754.h>
-#else
-union ieee754_float {
- float f;
- /* Little endian float fields */
- struct {
- unsigned int mantissa : 23;
- unsigned int exponent : 8;
- unsigned int negative : 1;
- } ieee;
-};
-#endif
-
-/* Uncomment to use the slow but accurate functions. */
-/* #define SLOW_DB_TO_LINEAR */
-/* #define SLOW_LINEAR_TO_DB */
-/* #define SLOW_WARP_SIN */
-/* #define SLOW_KNEE_EXP */
-/* #define SLOW_FREXPF */
-
-#define PI_FLOAT 3.141592653589793f
-#define PI_OVER_TWO_FLOAT 1.57079632679489661923f
-#define TWO_OVER_PI_FLOAT 0.63661977236758134f
-#define NEG_TWO_DB 0.7943282347242815f /* -2dB = 10^(-2/20) */
-
-#ifndef max
-#define max(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a > _b ? _a : _b; \
- })
-#endif
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-#ifndef M_PI
-#define M_PI 3.14159265358979323846
-#endif
-
-#define PURE __attribute__((pure))
-static inline float decibels_to_linear(float decibels) PURE;
-static inline float linear_to_decibels(float linear) PURE;
-static inline float warp_sinf(float x) PURE;
-static inline float warp_asinf(float x) PURE;
-static inline float knee_expf(float input) PURE;
-
-extern float db_to_linear[201]; /* from -100dB to 100dB */
-
-void drc_math_init();
-
-/* Rounds the input number to the nearest integer */
-#if defined(__arm__)
-static inline float round_int(float x)
-{
- return x < 0 ? (int)(x - 0.5f) : (int)(x + 0.5f);
-}
-#else
-#define round_int rintf /* Uses frintx for arm64 and roundss for SSE4.1 */
-#endif
-
-static inline float decibels_to_linear(float decibels)
-{
-#ifdef SLOW_DB_TO_LINEAR
- /* 10^(x/20) = e^(x * log(10^(1/20))) */
- return expf(0.1151292546497022f * decibels);
-#else
- float x;
- float fi;
- int i;
-
- fi = round_int(decibels);
- x = decibels - fi;
- i = (int)fi;
- i = max(min(i, 100), -100);
-
- /* Coefficients obtained from:
- * fpminimax(10^(x/20), [|1,2,3|], [|SG...|], [-0.5;0.5], 1, absolute);
- * max error ~= 7.897e-8
- */
- const float A3 = 2.54408805631101131439208984375e-4f;
- const float A2 = 6.628888659179210662841796875e-3f;
- const float A1 = 0.11512924730777740478515625f;
- const float A0 = 1.0f;
-
- float x2 = x * x;
- return ((A3 * x + A2) * x2 + (A1 * x + A0)) * db_to_linear[i + 100];
-#endif
-}
-
-static inline float frexpf_fast(float x, int *e)
-{
-#ifdef SLOW_FREXPF
- return frexpf(x, e);
-#else
- union ieee754_float u;
- u.f = x;
- int exp = u.ieee.exponent;
- if (exp == 0xff)
- return NAN;
- *e = exp - 126;
- u.ieee.exponent = 126;
- return u.f;
-#endif
-}
-
-static inline float linear_to_decibels(float linear)
-{
- /* For negative or zero, just return a very small dB value. */
- if (linear <= 0)
- return -1000;
-
-#ifdef SLOW_LINEAR_TO_DB
- /* 20 * log10(x) = 20 / log(10) * log(x) */
- return 8.6858896380650366f * logf(linear);
-#else
- int e = 0;
- float x = frexpf_fast(linear, &e);
- float exp = e;
-
- if (x > 0.707106781186548f) {
- x *= 0.707106781186548f;
- exp += 0.5f;
- }
-
- /* Coefficients obtained from:
- * fpminimax(log10(x), 5, [|SG...|], [1/2;sqrt(2)/2], absolute);
- * max err ~= 6.088e-8
- */
- const float A5 = 1.131880283355712890625f;
- const float A4 = -4.258677959442138671875f;
- const float A3 = 6.81631565093994140625f;
- const float A2 = -6.1185703277587890625f;
- const float A1 = 3.6505267620086669921875f;
- const float A0 = -1.217894077301025390625f;
-
- float x2 = x * x;
- float x4 = x2 * x2;
- return ((A5 * x + A4) * x4 + (A3 * x + A2) * x2 + (A1 * x + A0)) *
- 20.0f +
- exp * 6.0205999132796239f;
-#endif
-}
-
-static inline float warp_sinf(float x)
-{
-#ifdef SLOW_WARP_SIN
- return sinf(PI_OVER_TWO_FLOAT * x);
-#else
- /* Coefficients obtained from:
- * fpminimax(sin(x*pi/2), [|1,3,5,7|], [|SG...|], [-1e-30;1], absolute)
- * max err ~= 5.901e-7
- */
- const float A7 = -4.3330336920917034149169921875e-3f;
- const float A5 = 7.9434238374233245849609375e-2f;
- const float A3 = -0.645892798900604248046875f;
- const float A1 = 1.5707910060882568359375f;
-
- float x2 = x * x;
- float x4 = x2 * x2;
- return x * ((A7 * x2 + A5) * x4 + (A3 * x2 + A1));
-#endif
-}
-
-static inline float warp_asinf(float x)
-{
- return asinf(x) * TWO_OVER_PI_FLOAT;
-}
-
-static inline float knee_expf(float input)
-{
-#ifdef SLOW_KNEE_EXP
- return expf(input);
-#else
- /* exp(x) = decibels_to_linear(20*log10(e)*x) */
- return decibels_to_linear(8.685889638065044f * input);
-#endif
-}
-
-/* Returns 1 for nan or inf, 0 otherwise. This is faster than the alternative
- * return x != 0 && !isnormal(x);
- */
-static inline int isbadf(float x)
-{
- union ieee754_float u;
- u.f = x;
- return u.ieee.exponent == 0xff;
-}
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* DRC_MATH_H_ */
diff --git a/cras/src/dsp/dsp_util.c b/cras/src/dsp/dsp_util.c
deleted file mode 100644
index 86679e1f..00000000
--- a/cras/src/dsp/dsp_util.c
+++ /dev/null
@@ -1,611 +0,0 @@
-/* Copyright 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <limits.h>
-#include <syslog.h>
-
-#include "dsp_util.h"
-
-#ifndef max
-#define max(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a > _b ? _a : _b; \
- })
-#endif
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-#undef deinterleave_stereo
-#undef interleave_stereo
-
-/* Converts shorts in range of -32768 to 32767 to floats in range of
- * -1.0f to 1.0f.
- * scvtf instruction accepts fixed point ints, so sxtl is used to lengthen
- * shorts to int with sign extension.
- */
-#ifdef __aarch64__
-static void deinterleave_stereo(int16_t *input, float *output1, float *output2,
- int frames)
-{
- int chunk = frames >> 3;
- frames &= 7;
- /* Process 8 frames (16 samples) each loop. */
- /* L0 R0 L1 R1 L2 R2 L3 R3... -> L0 L1 L2 L3... R0 R1 R2 R3... */
- if (chunk) {
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "ld2 {v2.8h, v3.8h}, [%[input]], #32 \n"
- "subs %w[chunk], %w[chunk], #1 \n"
- "sxtl v0.4s, v2.4h \n"
- "sxtl2 v1.4s, v2.8h \n"
- "sxtl v2.4s, v3.4h \n"
- "sxtl2 v3.4s, v3.8h \n"
- "scvtf v0.4s, v0.4s, #15 \n"
- "scvtf v1.4s, v1.4s, #15 \n"
- "scvtf v2.4s, v2.4s, #15 \n"
- "scvtf v3.4s, v3.4s, #15 \n"
- "st1 {v0.4s, v1.4s}, [%[output1]], #32 \n"
- "st1 {v2.4s, v3.4s}, [%[output2]], #32 \n"
- "b.ne 1b \n"
- : /* output */
- [chunk]"+r"(chunk),
- [input]"+r"(input),
- [output1]"+r"(output1),
- [output2]"+r"(output2)
- : /* input */
- : /* clobber */
- "v0", "v1", "v2", "v3", "memory", "cc");
- // clang-format on
- }
-
- /* The remaining samples. */
- while (frames--) {
- *output1++ = *input++ / 32768.0f;
- *output2++ = *input++ / 32768.0f;
- }
-}
-#define deinterleave_stereo deinterleave_stereo
-
-/* Converts floats in range of -1.0f to 1.0f to shorts in range of
- * -32768 to 32767 with rounding to nearest, with ties (0.5) rounding away
- * from zero.
- * Rounding is achieved by using fcvtas instruction. (a = away)
- * The float scaled to a range of -32768 to 32767 by adding 15 to the exponent.
- * Add to exponent is equivalent to multiply for exponent range of 0 to 239,
- * which is 2.59 * 10^33. A signed saturating add (sqadd) limits exponents
- * from 240 to 255 to clamp to 255.
- * For very large values, beyond +/- 2 billion, fcvtas will clamp the result
- * to the min or max value that fits an int.
- * For other values, sqxtn clamps the output to -32768 to 32767 range.
- */
-static void interleave_stereo(float *input1, float *input2, int16_t *output,
- int frames)
-{
- /* Process 4 frames (8 samples) each loop. */
- /* L0 L1 L2 L3, R0 R1 R2 R3 -> L0 R0 L1 R1, L2 R2 L3 R3 */
- int chunk = frames >> 2;
- frames &= 3;
-
- if (chunk) {
- // clang-format off
- __asm__ __volatile__(
- "dup v2.4s, %w[scale] \n"
- "1: \n"
- "ld1 {v0.4s}, [%[input1]], #16 \n"
- "ld1 {v1.4s}, [%[input2]], #16 \n"
- "subs %w[chunk], %w[chunk], #1 \n"
- "sqadd v0.4s, v0.4s, v2.4s \n"
- "sqadd v1.4s, v1.4s, v2.4s \n"
- "fcvtas v0.4s, v0.4s \n"
- "fcvtas v1.4s, v1.4s \n"
- "sqxtn v0.4h, v0.4s \n"
- "sqxtn v1.4h, v1.4s \n"
- "st2 {v0.4h, v1.4h}, [%[output]], #16 \n"
- "b.ne 1b \n"
- : /* output */
- [chunk]"+r"(chunk),
- [input1]"+r"(input1),
- [input2]"+r"(input2),
- [output]"+r"(output)
- : /* input */
- [scale]"r"(15 << 23)
- : /* clobber */
- "v0", "v1", "v2", "memory", "cc");
- // clang-format on
- }
-
- /* The remaining samples */
- while (frames--) {
- float f;
- f = *input1++ * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- f = *input2++ * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- }
-}
-#define interleave_stereo interleave_stereo
-#endif
-
-#ifdef __ARM_NEON__
-#include <arm_neon.h>
-
-static void deinterleave_stereo(int16_t *input, float *output1, float *output2,
- int frames)
-{
- /* Process 8 frames (16 samples) each loop. */
- /* L0 R0 L1 R1 L2 R2 L3 R3... -> L0 L1 L2 L3... R0 R1 R2 R3... */
- int chunk = frames >> 3;
- frames &= 7;
- if (chunk) {
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "vld2.16 {d0-d3}, [%[input]]! \n"
- "subs %[chunk], #1 \n"
- "vmovl.s16 q3, d3 \n"
- "vmovl.s16 q2, d2 \n"
- "vmovl.s16 q1, d1 \n"
- "vmovl.s16 q0, d0 \n"
- "vcvt.f32.s32 q3, q3, #15 \n"
- "vcvt.f32.s32 q2, q2, #15 \n"
- "vcvt.f32.s32 q1, q1, #15 \n"
- "vcvt.f32.s32 q0, q0, #15 \n"
- "vst1.32 {d4-d7}, [%[output2]]! \n"
- "vst1.32 {d0-d3}, [%[output1]]! \n"
- "bne 1b \n"
- : /* output */
- [chunk]"+r"(chunk),
- [input]"+r"(input),
- [output1]"+r"(output1),
- [output2]"+r"(output2)
- : /* input */
- : /* clobber */
- "q0", "q1", "q2", "q3", "memory", "cc");
- // clang-format on
- }
-
- /* The remaining samples. */
- while (frames--) {
- *output1++ = *input++ / 32768.0f;
- *output2++ = *input++ / 32768.0f;
- }
-}
-#define deinterleave_stereo deinterleave_stereo
-
-/* Converts floats in range of -1.0f to 1.0f to shorts in range of
- * -32768 to 32767 with rounding to nearest, with ties (0.5) rounding away
- * from zero.
- * Rounding is achieved by adding 0.5 or -0.5 adjusted for fixed point
- * precision, and then converting float to fixed point using vcvt instruction
- * which truncated toward zero.
- * For very large values, beyond +/- 2 billion, vcvt will clamp the result
- * to the min or max value that fits an int.
- * For other values, vqmovn clamps the output to -32768 to 32767 range.
- */
-static void interleave_stereo(float *input1, float *input2, int16_t *output,
- int frames)
-{
- /* Process 4 frames (8 samples) each loop. */
- /* L0 L1 L2 L3, R0 R1 R2 R3 -> L0 R0 L1 R1, L2 R2 L3 R3 */
- float32x4_t pos = vdupq_n_f32(0.5f / 32768.0f);
- float32x4_t neg = vdupq_n_f32(-0.5f / 32768.0f);
- int chunk = frames >> 2;
- frames &= 3;
-
- if (chunk) {
- // clang-format off
- __asm__ __volatile__(
- "veor q0, q0, q0 \n"
- "1: \n"
- "vld1.32 {d2-d3}, [%[input1]]! \n"
- "vld1.32 {d4-d5}, [%[input2]]! \n"
- "subs %[chunk], #1 \n"
- /* We try to round to the nearest number by adding 0.5
- * to positive input, and adding -0.5 to the negative
- * input, then truncate.
- */
- "vcgt.f32 q3, q1, q0 \n"
- "vcgt.f32 q4, q2, q0 \n"
- "vbsl q3, %q[pos], %q[neg] \n"
- "vbsl q4, %q[pos], %q[neg] \n"
- "vadd.f32 q1, q1, q3 \n"
- "vadd.f32 q2, q2, q4 \n"
- "vcvt.s32.f32 q1, q1, #15 \n"
- "vcvt.s32.f32 q2, q2, #15 \n"
- "vqmovn.s32 d2, q1 \n"
- "vqmovn.s32 d3, q2 \n"
- "vst2.16 {d2-d3}, [%[output]]! \n"
- "bne 1b \n"
- : /* output */
- [chunk]"+r"(chunk),
- [input1]"+r"(input1),
- [input2]"+r"(input2),
- [output]"+r"(output)
- : /* input */
- [pos]"w"(pos),
- [neg]"w"(neg)
- : /* clobber */
- "q0", "q1", "q2", "q3", "q4", "memory", "cc");
- // clang-format on
- }
-
- /* The remaining samples */
- while (frames--) {
- float f;
- f = *input1++ * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- f = *input2++ * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- }
-}
-#define interleave_stereo interleave_stereo
-#endif
-
-#ifdef __SSE3__
-#include <emmintrin.h>
-
-/* Converts shorts in range of -32768 to 32767 to floats in range of
- * -1.0f to 1.0f.
- * pslld and psrad shifts are used to isolate the low and high word, but
- * each in a different range:
- * The low word is shifted to the high bits in range 0x80000000 .. 0x7fff0000.
- * The high word is shifted to the low bits in range 0x00008000 .. 0x00007fff.
- * cvtdq2ps converts ints to floats as is.
- * mulps is used to normalize the range of the low and high words, adjusting
- * for high and low words being in different range.
- */
-static void deinterleave_stereo(int16_t *input, float *output1, float *output2,
- int frames)
-{
- /* Process 8 frames (16 samples) each loop. */
- /* L0 R0 L1 R1 L2 R2 L3 R3... -> L0 L1 L2 L3... R0 R1 R2 R3... */
- int chunk = frames >> 3;
- frames &= 7;
- if (chunk) {
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "lddqu (%[input]), %%xmm0 \n"
- "lddqu 16(%[input]), %%xmm1 \n"
- "add $32, %[input] \n"
- "movdqa %%xmm0, %%xmm2 \n"
- "movdqa %%xmm1, %%xmm3 \n"
- "pslld $16, %%xmm0 \n"
- "pslld $16, %%xmm1 \n"
- "psrad $16, %%xmm2 \n"
- "psrad $16, %%xmm3 \n"
- "cvtdq2ps %%xmm0, %%xmm0 \n"
- "cvtdq2ps %%xmm1, %%xmm1 \n"
- "cvtdq2ps %%xmm2, %%xmm2 \n"
- "cvtdq2ps %%xmm3, %%xmm3 \n"
- "mulps %[scale_2_n31], %%xmm0 \n"
- "mulps %[scale_2_n31], %%xmm1 \n"
- "mulps %[scale_2_n15], %%xmm2 \n"
- "mulps %[scale_2_n15], %%xmm3 \n"
- "movdqu %%xmm0, (%[output1]) \n"
- "movdqu %%xmm1, 16(%[output1]) \n"
- "movdqu %%xmm2, (%[output2]) \n"
- "movdqu %%xmm3, 16(%[output2]) \n"
- "add $32, %[output1] \n"
- "add $32, %[output2] \n"
- "sub $1, %[chunk] \n"
- "jnz 1b \n"
- : /* output */
- [chunk]"+r"(chunk),
- [input]"+r"(input),
- [output1]"+r"(output1),
- [output2]"+r"(output2)
- : /* input */
- [scale_2_n31]"x"(_mm_set1_ps(1.0f/(1<<15)/(1<<16))),
- [scale_2_n15]"x"(_mm_set1_ps(1.0f/(1<<15)))
- : /* clobber */
- "xmm0", "xmm1", "xmm2", "xmm3", "memory", "cc");
- // clang-format on
- }
-
- /* The remaining samples. */
- while (frames--) {
- *output1++ = *input++ / 32768.0f;
- *output2++ = *input++ / 32768.0f;
- }
-}
-#define deinterleave_stereo deinterleave_stereo
-
-/* Converts floats in range of -1.0f to 1.0f to shorts in range of
- * -32768 to 32767 with rounding to nearest, with ties (0.5) rounding to
- * even.
- * For very large values, beyond +/- 2 billion, cvtps2dq will produce
- * 0x80000000 and packssdw will clamp -32768.
- */
-static void interleave_stereo(float *input1, float *input2, int16_t *output,
- int frames)
-{
- /* Process 4 frames (8 samples) each loop. */
- /* L0 L1 L2 L3, R0 R1 R2 R3 -> L0 R0 L1 R1, L2 R2 L3 R3 */
- int chunk = frames >> 2;
- frames &= 3;
-
- if (chunk) {
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "lddqu (%[input1]), %%xmm0 \n"
- "lddqu (%[input2]), %%xmm2 \n"
- "add $16, %[input1] \n"
- "add $16, %[input2] \n"
- "movaps %%xmm0, %%xmm1 \n"
- "unpcklps %%xmm2, %%xmm0 \n"
- "unpckhps %%xmm2, %%xmm1 \n"
- "paddsw %[scale_2_15], %%xmm0 \n"
- "paddsw %[scale_2_15], %%xmm1 \n"
- "cvtps2dq %%xmm0, %%xmm0 \n"
- "cvtps2dq %%xmm1, %%xmm1 \n"
- "packssdw %%xmm1, %%xmm0 \n"
- "movdqu %%xmm0, (%[output]) \n"
- "add $16, %[output] \n"
- "sub $1, %[chunk] \n"
- "jnz 1b \n"
- : /* output */
- [chunk]"+r"(chunk),
- [input1]"+r"(input1),
- [input2]"+r"(input2),
- [output]"+r"(output)
- : /* input */
- [scale_2_15]"x"(_mm_set1_epi32(15 << 23)),
- [clamp_large]"x"(_mm_set1_ps(32767.0f))
- : /* clobber */
- "xmm0", "xmm1", "xmm2", "memory", "cc");
- // clang-format on
- }
-
- /* The remaining samples */
- while (frames--) {
- float f;
- f = *input1++ * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- f = *input2++ * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- }
-}
-#define interleave_stereo interleave_stereo
-#endif
-
-static void dsp_util_deinterleave_s16le(int16_t *input, float *const *output,
- int channels, int frames)
-{
- float *output_ptr[channels];
- int i, j;
-
-#ifdef deinterleave_stereo
- if (channels == 2) {
- deinterleave_stereo(input, output[0], output[1], frames);
- return;
- }
-#endif
-
- for (i = 0; i < channels; i++)
- output_ptr[i] = output[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++)
- *(output_ptr[j]++) = *input++ / 32768.0f;
-}
-
-static void dsp_util_deinterleave_s24le(int32_t *input, float *const *output,
- int channels, int frames)
-{
- float *output_ptr[channels];
- int i, j;
-
- for (i = 0; i < channels; i++)
- output_ptr[i] = output[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++, input++)
- *(output_ptr[j]++) = (*input << 8) / 2147483648.0f;
-}
-
-static void dsp_util_deinterleave_s243le(uint8_t *input, float *const *output,
- int channels, int frames)
-{
- float *output_ptr[channels];
- int32_t sample;
- int i, j;
-
- for (i = 0; i < channels; i++)
- output_ptr[i] = output[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++, input += 3) {
- sample = 0;
- memcpy((uint8_t *)&sample + 1, input, 3);
- *(output_ptr[j]++) = sample / 2147483648.0f;
- }
-}
-
-static void dsp_util_deinterleave_s32le(int32_t *input, float *const *output,
- int channels, int frames)
-{
- float *output_ptr[channels];
- int i, j;
-
- for (i = 0; i < channels; i++)
- output_ptr[i] = output[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++, input++)
- *(output_ptr[j]++) = *input / 2147483648.0f;
-}
-
-int dsp_util_deinterleave(uint8_t *input, float *const *output, int channels,
- snd_pcm_format_t format, int frames)
-{
- switch (format) {
- case SND_PCM_FORMAT_S16_LE:
- dsp_util_deinterleave_s16le((int16_t *)input, output, channels,
- frames);
- break;
- case SND_PCM_FORMAT_S24_LE:
- dsp_util_deinterleave_s24le((int32_t *)input, output, channels,
- frames);
- break;
- case SND_PCM_FORMAT_S24_3LE:
- dsp_util_deinterleave_s243le(input, output, channels, frames);
- break;
- case SND_PCM_FORMAT_S32_LE:
- dsp_util_deinterleave_s32le((int32_t *)input, output, channels,
- frames);
- break;
- default:
- syslog(LOG_ERR, "Invalid format to deinterleave");
- return -EINVAL;
- }
- return 0;
-}
-
-static void dsp_util_interleave_s16le(float *const *input, int16_t *output,
- int channels, int frames)
-{
- float *input_ptr[channels];
- int i, j;
-
-#ifdef interleave_stereo
- if (channels == 2) {
- interleave_stereo(input[0], input[1], output, frames);
- return;
- }
-#endif
-
- for (i = 0; i < channels; i++)
- input_ptr[i] = input[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++) {
- float f = *(input_ptr[j]++) * 32768.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output++ = max(-32768, min(32767, (int)(f)));
- }
-}
-
-static void dsp_util_interleave_s24le(float *const *input, int32_t *output,
- int channels, int frames)
-{
- float *input_ptr[channels];
- int i, j;
-
- for (i = 0; i < channels; i++)
- input_ptr[i] = input[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++, output++) {
- float f = *(input_ptr[j]++) * 2147483648.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output = max((float)INT_MIN, min((float)INT_MAX, f));
- *output = (*output >> 8) & 0x00ffffff;
- }
-}
-
-static void dsp_util_interleave_s243le(float *const *input, uint8_t *output,
- int channels, int frames)
-{
- float *input_ptr[channels];
- int i, j;
- int32_t tmp;
-
- for (i = 0; i < channels; i++)
- input_ptr[i] = input[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++, output += 3) {
- float f = *(input_ptr[j]++) * 2147483648.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- tmp = max((float)INT_MIN, min((float)INT_MAX, f));
- tmp >>= 8;
- memcpy(output, &tmp, 3);
- }
-}
-
-static void dsp_util_interleave_s32le(float *const *input, int32_t *output,
- int channels, int frames)
-{
- float *input_ptr[channels];
- int i, j;
-
- for (i = 0; i < channels; i++)
- input_ptr[i] = input[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++, output++) {
- float f = *(input_ptr[j]++) * 2147483648.0f;
- f += (f >= 0) ? 0.5f : -0.5f;
- *output = max((float)INT_MIN, min((float)INT_MAX, f));
- }
-}
-
-int dsp_util_interleave(float *const *input, uint8_t *output, int channels,
- snd_pcm_format_t format, int frames)
-{
- switch (format) {
- case SND_PCM_FORMAT_S16_LE:
- dsp_util_interleave_s16le(input, (int16_t *)output, channels,
- frames);
- break;
- case SND_PCM_FORMAT_S24_LE:
- dsp_util_interleave_s24le(input, (int32_t *)output, channels,
- frames);
- break;
- case SND_PCM_FORMAT_S24_3LE:
- dsp_util_interleave_s243le(input, output, channels, frames);
- break;
- case SND_PCM_FORMAT_S32_LE:
- dsp_util_interleave_s32le(input, (int32_t *)output, channels,
- frames);
- break;
- default:
- syslog(LOG_ERR, "Invalid format to interleave");
- return -EINVAL;
- }
- return 0;
-}
-
-void dsp_enable_flush_denormal_to_zero()
-{
-#if defined(__i386__) || defined(__x86_64__)
- unsigned int mxcsr;
- mxcsr = __builtin_ia32_stmxcsr();
- __builtin_ia32_ldmxcsr(mxcsr | 0x8040);
-#elif defined(__aarch64__)
- uint64_t cw;
- __asm__ __volatile__("mrs %0, fpcr \n"
- "orr %0, %0, #0x1000000 \n"
- "msr fpcr, %0 \n"
- "isb \n"
- : "=r"(cw)::"memory");
-#elif defined(__arm__)
- uint32_t cw;
- __asm__ __volatile__("vmrs %0, fpscr \n"
- "orr %0, %0, #0x1000000 \n"
- "vmsr fpscr, %0 \n"
- : "=r"(cw)::"memory");
-#else
-#warning "Don't know how to disable denorms. Performace may suffer."
-#endif
-}
diff --git a/cras/src/dsp/dsp_util.h b/cras/src/dsp/dsp_util.h
deleted file mode 100644
index 7ca227ad..00000000
--- a/cras/src/dsp/dsp_util.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef DSPUTIL_H_
-#define DSPUTIL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdint.h>
-
-#include "cras_audio_format.h"
-
-/* Converts from interleaved int16_t samples to non-interleaved float samples.
- * The int16_t samples have range [-32768, 32767], and the float samples have
- * range [-1.0, 1.0].
- * Args:
- * input - The interleaved input buffer. Every "channels" samples is a frame.
- * output - Pointers to output buffers. There are "channels" output buffers.
- * channels - The number of samples per frame.
- * frames - The number of frames to convert.
- * Returns:
- * Negative error if format isn't supported, otherwise 0.
- */
-int dsp_util_deinterleave(uint8_t *input, float *const *output, int channels,
- snd_pcm_format_t format, int frames);
-
-/* Converts from non-interleaved float samples to interleaved int16_t samples.
- * The int16_t samples have range [-32768, 32767], and the float samples have
- * range [-1.0, 1.0]. This is the inverse of dsputil_deinterleave().
- * Args:
- * input - Pointers to input buffers. There are "channels" input buffers.
- * output - The interleaved output buffer. Every "channels" samples is a
- * frame.
- * channels - The number of samples per frame.
- * frames - The number of frames to convert.
- * Returns:
- * Negative error if format isn't supported, otherwise 0.
- */
-int dsp_util_interleave(float *const *input, uint8_t *output, int channels,
- snd_pcm_format_t format, int frames);
-
-/* Disables denormal numbers in floating point calculation. Denormal numbers
- * happens often in IIR filters, and it can be very slow.
- */
-void dsp_enable_flush_denormal_to_zero();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* DSPUTIL_H_ */
diff --git a/cras/src/dsp/eq.c b/cras/src/dsp/eq.c
deleted file mode 100644
index 9f3197f6..00000000
--- a/cras/src/dsp/eq.c
+++ /dev/null
@@ -1,148 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include "eq.h"
-
-struct eq {
- int n;
- struct biquad biquad[MAX_BIQUADS_PER_EQ];
-};
-
-struct eq *eq_new()
-{
- struct eq *eq = (struct eq *)calloc(1, sizeof(*eq));
- return eq;
-}
-
-void eq_free(struct eq *eq)
-{
- free(eq);
-}
-
-int eq_append_biquad(struct eq *eq, enum biquad_type type, float freq, float Q,
- float gain)
-{
- if (eq->n >= MAX_BIQUADS_PER_EQ)
- return -1;
- biquad_set(&eq->biquad[eq->n++], type, freq, Q, gain);
- return 0;
-}
-
-int eq_append_biquad_direct(struct eq *eq, const struct biquad *biquad)
-{
- if (eq->n >= MAX_BIQUADS_PER_EQ)
- return -1;
- eq->biquad[eq->n++] = *biquad;
- return 0;
-}
-
-/* This is the prototype of the processing loop. */
-void eq_process1(struct eq *eq, float *data, int count)
-{
- int i, j;
- for (i = 0; i < eq->n; i++) {
- struct biquad *q = &eq->biquad[i];
- float x1 = q->x1;
- float x2 = q->x2;
- float y1 = q->y1;
- float y2 = q->y2;
- float b0 = q->b0;
- float b1 = q->b1;
- float b2 = q->b2;
- float a1 = q->a1;
- float a2 = q->a2;
- for (j = 0; j < count; j++) {
- float x = data[j];
- float y =
- b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
- data[j] = y;
- x2 = x1;
- x1 = x;
- y2 = y1;
- y1 = y;
- }
- q->x1 = x1;
- q->x2 = x2;
- q->y1 = y1;
- q->y2 = y2;
- }
-}
-
-/* This is the actual processing loop used. It is the unrolled version of the
- * above prototype. */
-void eq_process(struct eq *eq, float *data, int count)
-{
- int i, j;
- for (i = 0; i < eq->n; i += 2) {
- if (i + 1 == eq->n) {
- struct biquad *q = &eq->biquad[i];
- float x1 = q->x1;
- float x2 = q->x2;
- float y1 = q->y1;
- float y2 = q->y2;
- float b0 = q->b0;
- float b1 = q->b1;
- float b2 = q->b2;
- float a1 = q->a1;
- float a2 = q->a2;
- for (j = 0; j < count; j++) {
- float x = data[j];
- float y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 -
- a2 * y2;
- data[j] = y;
- x2 = x1;
- x1 = x;
- y2 = y1;
- y1 = y;
- }
- q->x1 = x1;
- q->x2 = x2;
- q->y1 = y1;
- q->y2 = y2;
- } else {
- struct biquad *q = &eq->biquad[i];
- struct biquad *r = &eq->biquad[i + 1];
- float x1 = q->x1;
- float x2 = q->x2;
- float y1 = q->y1;
- float y2 = q->y2;
- float qb0 = q->b0;
- float qb1 = q->b1;
- float qb2 = q->b2;
- float qa1 = q->a1;
- float qa2 = q->a2;
-
- float z1 = r->y1;
- float z2 = r->y2;
- float rb0 = r->b0;
- float rb1 = r->b1;
- float rb2 = r->b2;
- float ra1 = r->a1;
- float ra2 = r->a2;
-
- for (j = 0; j < count; j++) {
- float x = data[j];
- float y = qb0 * x + qb1 * x1 + qb2 * x2 -
- qa1 * y1 - qa2 * y2;
- float z = rb0 * y + rb1 * y1 + rb2 * y2 -
- ra1 * z1 - ra2 * z2;
- data[j] = z;
- x2 = x1;
- x1 = x;
- y2 = y1;
- y1 = y;
- z2 = z1;
- z1 = z;
- }
- q->x1 = x1;
- q->x2 = x2;
- q->y1 = y1;
- q->y2 = y2;
- r->y1 = z1;
- r->y2 = z2;
- }
- }
-}
diff --git a/cras/src/dsp/eq.h b/cras/src/dsp/eq.h
deleted file mode 100644
index 212f653c..00000000
--- a/cras/src/dsp/eq.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef EQ_H_
-#define EQ_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* An EQ is a chain of biquad filters. See Web Audio API spec for details of the
- * biquad filters and their parameters. */
-
-#include "biquad.h"
-
-/* Maximum number of biquad filters an EQ can have */
-#define MAX_BIQUADS_PER_EQ 10
-
-struct eq;
-
-/* Create an EQ. */
-struct eq *eq_new();
-
-/* Free an EQ. */
-void eq_free(struct eq *eq);
-
-/* Append a biquad filter to an EQ. An EQ can have at most MAX_BIQUADS_PER_EQ
- * biquad filters.
- * Args:
- * eq - The EQ we want to use.
- * type - The type of the biquad filter we want to append.
- * frequency - The value should be in the range [0, 1]. It is relative to
- * half of the sampling rate.
- * Q, gain - The meaning depends on the type of the filter. See Web Audio
- * API for details.
- * Returns:
- * 0 if success. -1 if the eq has no room for more biquads.
- */
-int eq_append_biquad(struct eq *eq, enum biquad_type type, float freq, float Q,
- float gain);
-
-/* Append a biquad filter to an EQ. An EQ can have at most MAX_BIQUADS_PER_EQ
- * biquad filters. This is similar to eq_append_biquad(), but it specifies the
- * biquad coefficients directly.
- * Args:
- * eq - The EQ we want to use.
- * biquad - The parameters for the biquad filter.
- * Returns:
- * 0 if success. -1 if the eq has no room for more biquads.
- */
-int eq_append_biquad_direct(struct eq *eq, const struct biquad *biquad);
-
-/* Process a buffer of audio data through the EQ.
- * Args:
- * eq - The EQ we want to use.
- * data - The array of audio samples.
- * count - The number of elements in the data array to process.
- */
-void eq_process(struct eq *eq, float *data, int count);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* EQ_H_ */
diff --git a/cras/src/dsp/eq2.c b/cras/src/dsp/eq2.c
deleted file mode 100644
index f4f4185b..00000000
--- a/cras/src/dsp/eq2.c
+++ /dev/null
@@ -1,343 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include "eq2.h"
-
-struct eq2 {
- int n[2];
- struct biquad biquad[MAX_BIQUADS_PER_EQ2][2];
-};
-
-struct eq2 *eq2_new()
-{
- struct eq2 *eq2 = (struct eq2 *)calloc(1, sizeof(*eq2));
- int i, j;
-
- /* Initialize all biquads to identity filter, so if two channels have
- * different numbers of biquads, it still works. */
- for (i = 0; i < MAX_BIQUADS_PER_EQ2; i++)
- for (j = 0; j < 2; j++)
- biquad_set(&eq2->biquad[i][j], BQ_NONE, 0, 0, 0);
-
- return eq2;
-}
-
-void eq2_free(struct eq2 *eq2)
-{
- free(eq2);
-}
-
-int eq2_append_biquad(struct eq2 *eq2, int channel, enum biquad_type type,
- float freq, float Q, float gain)
-{
- if (eq2->n[channel] >= MAX_BIQUADS_PER_EQ2)
- return -1;
- biquad_set(&eq2->biquad[eq2->n[channel]++][channel], type, freq, Q,
- gain);
- return 0;
-}
-
-int eq2_append_biquad_direct(struct eq2 *eq2, int channel,
- const struct biquad *biquad)
-{
- if (eq2->n[channel] >= MAX_BIQUADS_PER_EQ2)
- return -1;
- eq2->biquad[eq2->n[channel]++][channel] = *biquad;
- return 0;
-}
-
-static inline void eq2_process_one(struct biquad (*bq)[2], float *data0,
- float *data1, int count)
-{
- struct biquad *qL = &bq[0][0];
- struct biquad *qR = &bq[0][1];
-
- float x1L = qL->x1;
- float x2L = qL->x2;
- float y1L = qL->y1;
- float y2L = qL->y2;
- float b0L = qL->b0;
- float b1L = qL->b1;
- float b2L = qL->b2;
- float a1L = qL->a1;
- float a2L = qL->a2;
-
- float x1R = qR->x1;
- float x2R = qR->x2;
- float y1R = qR->y1;
- float y2R = qR->y2;
- float b0R = qR->b0;
- float b1R = qR->b1;
- float b2R = qR->b2;
- float a1R = qR->a1;
- float a2R = qR->a2;
-
- int j;
- for (j = 0; j < count; j++) {
- float xL = data0[j];
- float xR = data1[j];
-
- float yL = b0L * xL + b1L * x1L + b2L * x2L - a1L * y1L -
- a2L * y2L;
- x2L = x1L;
- x1L = xL;
- y2L = y1L;
- y1L = yL;
-
- float yR = b0R * xR + b1R * x1R + b2R * x2R - a1R * y1R -
- a2R * y2R;
- x2R = x1R;
- x1R = xR;
- y2R = y1R;
- y1R = yR;
-
- data0[j] = yL;
- data1[j] = yR;
- }
-
- qL->x1 = x1L;
- qL->x2 = x2L;
- qL->y1 = y1L;
- qL->y2 = y2L;
- qR->x1 = x1R;
- qR->x2 = x2R;
- qR->y1 = y1R;
- qR->y2 = y2R;
-}
-
-#ifdef __ARM_NEON__
-#include <arm_neon.h>
-static inline void eq2_process_two_neon(struct biquad (*bq)[2], float *data0,
- float *data1, int count)
-{
- struct biquad *qL = &bq[0][0];
- struct biquad *rL = &bq[1][0];
- struct biquad *qR = &bq[0][1];
- struct biquad *rR = &bq[1][1];
-
- float32x2_t x1 = { qL->x1, qR->x1 };
- float32x2_t x2 = { qL->x2, qR->x2 };
- float32x2_t y1 = { qL->y1, qR->y1 };
- float32x2_t y2 = { qL->y2, qR->y2 };
- float32x2_t qb0 = { qL->b0, qR->b0 };
- float32x2_t qb1 = { qL->b1, qR->b1 };
- float32x2_t qb2 = { qL->b2, qR->b2 };
- float32x2_t qa1 = { qL->a1, qR->a1 };
- float32x2_t qa2 = { qL->a2, qR->a2 };
-
- float32x2_t z1 = { rL->y1, rR->y1 };
- float32x2_t z2 = { rL->y2, rR->y2 };
- float32x2_t rb0 = { rL->b0, rR->b0 };
- float32x2_t rb1 = { rL->b1, rR->b1 };
- float32x2_t rb2 = { rL->b2, rR->b2 };
- float32x2_t ra1 = { rL->a1, rR->a1 };
- float32x2_t ra2 = { rL->a2, rR->a2 };
-
- // clang-format off
- __asm__ __volatile__(
- /* d0 = x, d1 = y, d2 = z */
- "1: \n"
- "vmul.f32 d1, %P[qb1], %P[x1] \n"
- "vld1.32 d0[0], [%[data0]] \n"
- "vld1.32 d0[1], [%[data1]] \n"
- "subs %[count], #1 \n"
- "vmul.f32 d2, %P[rb1], %P[y1] \n"
- "vmla.f32 d1, %P[qb0], d0 \n"
- "vmla.f32 d1, %P[qb2], %P[x2] \n"
- "vmov.f32 %P[x2], %P[x1] \n"
- "vmov.f32 %P[x1], d0 \n"
- "vmls.f32 d1, %P[qa1], %P[y1] \n"
- "vmls.f32 d1, %P[qa2], %P[y2] \n"
- "vmla.f32 d2, %P[rb0], d1 \n"
- "vmla.f32 d2, %P[rb2], %P[y2] \n"
- "vmov.f32 %P[y2], %P[y1] \n"
- "vmov.f32 %P[y1], d1 \n"
- "vmls.f32 d2, %P[ra1], %P[z1] \n"
- "vmls.f32 d2, %P[ra2], %P[z2] \n"
- "vmov.f32 %P[z2], %P[z1] \n"
- "vmov.f32 %P[z1], d2 \n"
- "vst1.f32 d2[0], [%[data0]]! \n"
- "vst1.f32 d2[1], [%[data1]]! \n"
- "bne 1b \n"
- : /* output */
- [data0]"+r"(data0),
- [data1]"+r"(data1),
- [count]"+r"(count),
- [x1]"+w"(x1),
- [x2]"+w"(x2),
- [y1]"+w"(y1),
- [y2]"+w"(y2),
- [z1]"+w"(z1),
- [z2]"+w"(z2)
- : /* input */
- [qb0]"w"(qb0),
- [qb1]"w"(qb1),
- [qb2]"w"(qb2),
- [qa1]"w"(qa1),
- [qa2]"w"(qa2),
- [rb0]"w"(rb0),
- [rb1]"w"(rb1),
- [rb2]"w"(rb2),
- [ra1]"w"(ra1),
- [ra2]"w"(ra2)
- : /* clobber */
- "d0", "d1", "d2", "memory", "cc");
- // clang-format on
-
- qL->x1 = x1[0];
- qL->x2 = x2[0];
- qL->y1 = y1[0];
- qL->y2 = y2[0];
- rL->y1 = z1[0];
- rL->y2 = z2[0];
- qR->x1 = x1[1];
- qR->x2 = x2[1];
- qR->y1 = y1[1];
- qR->y2 = y2[1];
- rR->y1 = z1[1];
- rR->y2 = z2[1];
-}
-#endif
-
-#if defined(__SSE3__) && defined(__x86_64__)
-#include <emmintrin.h>
-static inline void eq2_process_two_sse3(struct biquad (*bq)[2], float *data0,
- float *data1, int count)
-{
- struct biquad *qL = &bq[0][0];
- struct biquad *rL = &bq[1][0];
- struct biquad *qR = &bq[0][1];
- struct biquad *rR = &bq[1][1];
-
- __m128 x1 = { qL->x1, qR->x1 };
- __m128 x2 = { qL->x2, qR->x2 };
- __m128 y1 = { qL->y1, qR->y1 };
- __m128 y2 = { qL->y2, qR->y2 };
- __m128 qb0 = { qL->b0, qR->b0 };
- __m128 qb1 = { qL->b1, qR->b1 };
- __m128 qb2 = { qL->b2, qR->b2 };
- __m128 qa1 = { qL->a1, qR->a1 };
- __m128 qa2 = { qL->a2, qR->a2 };
-
- __m128 z1 = { rL->y1, rR->y1 };
- __m128 z2 = { rL->y2, rR->y2 };
- __m128 rb0 = { rL->b0, rR->b0 };
- __m128 rb1 = { rL->b1, rR->b1 };
- __m128 rb2 = { rL->b2, rR->b2 };
- __m128 ra1 = { rL->a1, rR->a1 };
- __m128 ra2 = { rL->a2, rR->a2 };
-
- // clang-format off
- __asm__ __volatile__(
- "1: \n"
- "movss (%[data0]), %%xmm2 \n"
- "movss (%[data1]), %%xmm1 \n"
- "unpcklps %%xmm1, %%xmm2 \n"
- "mulps %[qb2],%[x2] \n"
- "lddqu %[qb0],%%xmm0 \n"
- "mulps %[ra2],%[z2] \n"
- "lddqu %[qb1],%%xmm1 \n"
- "mulps %%xmm2,%%xmm0 \n"
- "mulps %[x1],%%xmm1 \n"
- "addps %%xmm1,%%xmm0 \n"
- "movaps %[qa1],%%xmm1 \n"
- "mulps %[y1],%%xmm1 \n"
- "addps %[x2],%%xmm0 \n"
- "movaps %[rb1],%[x2] \n"
- "mulps %[y1],%[x2] \n"
- "subps %%xmm1,%%xmm0 \n"
- "movaps %[qa2],%%xmm1 \n"
- "mulps %[y2],%%xmm1 \n"
- "mulps %[rb2],%[y2] \n"
- "subps %%xmm1,%%xmm0 \n"
- "movaps %[rb0],%%xmm1 \n"
- "mulps %%xmm0,%%xmm1 \n"
- "addps %[x2],%%xmm1 \n"
- "movaps %[x1],%[x2] \n"
- "movaps %%xmm2,%[x1] \n"
- "addps %[y2],%%xmm1 \n"
- "movaps %[ra1],%[y2] \n"
- "mulps %[z1],%[y2] \n"
- "subps %[y2],%%xmm1 \n"
- "movaps %[y1],%[y2] \n"
- "movaps %%xmm0,%[y1] \n"
- "subps %[z2],%%xmm1 \n"
- "movaps %[z1],%[z2] \n"
- "movaps %%xmm1,%[z1] \n"
- "movss %%xmm1, (%[data0]) \n"
- "shufps $1, %%xmm1, %%xmm1 \n"
- "movss %%xmm1, (%[data1]) \n"
- "add $4, %[data0] \n"
- "add $4, %[data1] \n"
- "sub $1, %[count] \n"
- "jnz 1b \n"
- : /* output */
- [data0]"+r"(data0),
- [data1]"+r"(data1),
- [count]"+r"(count),
- [x1]"+x"(x1),
- [x2]"+x"(x2),
- [y1]"+x"(y1),
- [y2]"+x"(y2),
- [z1]"+x"(z1),
- [z2]"+x"(z2)
- : /* input */
- [qb0]"m"(qb0),
- [qb1]"m"(qb1),
- [qb2]"m"(qb2),
- [qa1]"x"(qa1),
- [qa2]"x"(qa2),
- [rb0]"x"(rb0),
- [rb1]"x"(rb1),
- [rb2]"x"(rb2),
- [ra1]"x"(ra1),
- [ra2]"x"(ra2)
- : /* clobber */
- "xmm0", "xmm1", "xmm2", "memory", "cc");
- // clang-format on
-
- qL->x1 = x1[0];
- qL->x2 = x2[0];
- qL->y1 = y1[0];
- qL->y2 = y2[0];
- rL->y1 = z1[0];
- rL->y2 = z2[0];
- qR->x1 = x1[1];
- qR->x2 = x2[1];
- qR->y1 = y1[1];
- qR->y2 = y2[1];
- rR->y1 = z1[1];
- rR->y2 = z2[1];
-}
-#endif
-
-void eq2_process(struct eq2 *eq2, float *data0, float *data1, int count)
-{
- int i;
- int n;
- if (!count)
- return;
- n = eq2->n[0];
- if (eq2->n[1] > n)
- n = eq2->n[1];
- for (i = 0; i < n; i += 2) {
- if (i + 1 == n) {
- eq2_process_one(&eq2->biquad[i], data0, data1, count);
- } else {
-#if defined(__ARM_NEON__)
- eq2_process_two_neon(&eq2->biquad[i], data0, data1,
- count);
-#elif defined(__SSE3__) && defined(__x86_64__)
- eq2_process_two_sse3(&eq2->biquad[i], data0, data1,
- count);
-#else
- eq2_process_one(&eq2->biquad[i], data0, data1, count);
- eq2_process_one(&eq2->biquad[i + 1], data0, data1,
- count);
-#endif
- }
- }
-}
diff --git a/cras/src/dsp/eq2.h b/cras/src/dsp/eq2.h
deleted file mode 100644
index dfa9a1df..00000000
--- a/cras/src/dsp/eq2.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef EQ2_H_
-#define EQ2_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* "eq2" is a two channel version of the "eq" filter. It processes two channels
- * of data at once to increase performance. */
-
-#include "biquad.h"
-
-/* Maximum number of biquad filters an EQ2 can have per channel */
-#define MAX_BIQUADS_PER_EQ2 10
-
-struct eq2;
-
-/* Create an EQ2. */
-struct eq2 *eq2_new();
-
-/* Free an EQ2. */
-void eq2_free(struct eq2 *eq2);
-
-/* Append a biquad filter to an EQ2. An EQ2 can have at most MAX_BIQUADS_PER_EQ2
- * biquad filters per channel.
- * Args:
- * eq2 - The EQ2 we want to use.
- * channel - 0 or 1. The channel we want to append the filter to.
- * type - The type of the biquad filter we want to append.
- * frequency - The value should be in the range [0, 1]. It is relative to
- * half of the sampling rate.
- * Q, gain - The meaning depends on the type of the filter. See Web Audio
- * API for details.
- * Returns:
- * 0 if success. -1 if the eq has no room for more biquads.
- */
-int eq2_append_biquad(struct eq2 *eq2, int channel, enum biquad_type type,
- float freq, float Q, float gain);
-
-/* Append a biquad filter to an EQ2. An EQ2 can have at most MAX_BIQUADS_PER_EQ2
- * biquad filters. This is similar to eq2_append_biquad(), but it specifies the
- * biquad coefficients directly.
- * Args:
- * eq2 - The EQ2 we want to use.
- * channel - 0 or 1. The channel we want to append the filter to.
- * biquad - The parameters for the biquad filter.
- * Returns:
- * 0 if success. -1 if the eq has no room for more biquads.
- */
-int eq2_append_biquad_direct(struct eq2 *eq2, int channel,
- const struct biquad *biquad);
-
-/* Process a buffer of audio data through the EQ2.
- * Args:
- * eq2 - The EQ2 we want to use.
- * data0 - The array of channel 0 audio samples.
- * data1 - The array of channel 1 audio samples.
- * count - The number of elements in each of the data array to process.
- */
-void eq2_process(struct eq2 *eq2, float *data0, float *data1, int count);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* EQ2_H_ */
diff --git a/cras/src/dsp/tests/cmpraw.c b/cras/src/dsp/tests/cmpraw.c
deleted file mode 100644
index 911f19d8..00000000
--- a/cras/src/dsp/tests/cmpraw.c
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <math.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include "raw.h"
-
-/* Compare the difference between two raw files */
-
-static inline double max(double a, double b)
-{
- return (a > b) ? a : b;
-}
-
-int main(int argc, char **argv)
-{
- size_t frame1, frame2;
- float *data1, *data2;
- size_t i, n, changed;
- double diff = 0;
- double maxdiff = 0;
-
- if (argc != 3) {
- fprintf(stderr, "usage: cmpraw 1.raw 2.raw\n");
- exit(1);
- }
-
- data1 = read_raw(argv[1], &frame1);
- data2 = read_raw(argv[2], &frame2);
-
- if (frame1 != frame2) {
- fprintf(stderr, "mismatch size (%zu vs %zu)\n", frame1, frame2);
- exit(1);
- }
-
- n = frame1 * 2;
- changed = 0;
- for (i = 0; i < n; i++) {
- if (data1[i] != data2[i]) {
- changed++;
- diff += fabs(data1[i] - data2[i]);
- maxdiff = max(fabs(data1[i] - data2[i]), maxdiff);
- }
- }
- printf("avg diff = %g, max diff = %g, changed = %.3f%%\n", diff / n,
- maxdiff * 32768, changed * 100.0f / n);
-
- free(data1);
- free(data2);
- return 0;
-}
diff --git a/cras/src/dsp/tests/crossover2_test.c b/cras/src/dsp/tests/crossover2_test.c
deleted file mode 100644
index f313d38c..00000000
--- a/cras/src/dsp/tests/crossover2_test.c
+++ /dev/null
@@ -1,89 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <time.h>
-#include <memory.h>
-
-#include "crossover2.h"
-#include "dsp_test_util.h"
-#include "dsp_util.h"
-#include "raw.h"
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-static double tp_diff(struct timespec *tp2, struct timespec *tp1)
-{
- return (tp2->tv_sec - tp1->tv_sec) +
- (tp2->tv_nsec - tp1->tv_nsec) * 1e-9;
-}
-
-void process(struct crossover2 *xo2, int count, float *data0L, float *data0R,
- float *data1L, float *data1R, float *data2L, float *data2R)
-{
- int start;
- for (start = 0; start < count; start += 2048)
- crossover2_process(xo2, min(2048, count - start),
- data0L + start, data0R + start,
- data1L + start, data1R + start,
- data2L + start, data2R + start);
-}
-
-int main(int argc, char **argv)
-{
- size_t frames;
- float *data0, *data1, *data2;
- double NQ = 44100 / 2;
- struct timespec tp1, tp2;
- struct crossover2 xo2;
-
- if (argc != 3 && argc != 6) {
- printf("Usage: crossover2_test input.raw output.raw "
- "[low.raw mid.raw high.raw]\n");
- return 1;
- }
-
- dsp_enable_flush_denormal_to_zero();
- dsp_util_clear_fp_exceptions();
-
- data0 = read_raw(argv[1], &frames);
- data1 = (float *)malloc(sizeof(float) * frames * 2);
- data2 = (float *)malloc(sizeof(float) * frames * 2);
-
- crossover2_init(&xo2, 400 / NQ, 4000 / NQ);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(&xo2, frames, data0, data0 + frames, data1, data1 + frames,
- data2, data2 + frames);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames * 2);
-
- if (argc == 6) {
- write_raw(argv[3], data0, frames);
- write_raw(argv[4], data1, frames);
- write_raw(argv[5], data2, frames);
- }
-
- int i;
- for (i = 0; i < frames * 2; i++)
- data0[i] += data1[i] + data2[i];
- write_raw(argv[2], data0, frames);
-
- free(data0);
- free(data1);
- free(data2);
-
- dsp_util_print_fp_exceptions();
- return 0;
-}
diff --git a/cras/src/dsp/tests/crossover_test.c b/cras/src/dsp/tests/crossover_test.c
deleted file mode 100644
index 267438d6..00000000
--- a/cras/src/dsp/tests/crossover_test.c
+++ /dev/null
@@ -1,93 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <time.h>
-#include <memory.h>
-
-#include "crossover.h"
-#include "dsp_test_util.h"
-#include "dsp_util.h"
-#include "raw.h"
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-static double tp_diff(struct timespec *tp2, struct timespec *tp1)
-{
- return (tp2->tv_sec - tp1->tv_sec) +
- (tp2->tv_nsec - tp1->tv_nsec) * 1e-9;
-}
-
-void process(struct crossover *xo, int count, float *data0, float *data1,
- float *data2)
-{
- int start;
- for (start = 0; start < count; start += 2048)
- crossover_process(xo, min(2048, count - start), data0 + start,
- data1 + start, data2 + start);
-}
-
-int main(int argc, char **argv)
-{
- size_t frames;
- float *data0, *data1, *data2;
- double NQ = 44100 / 2;
- struct timespec tp1, tp2;
- struct crossover xo;
-
- if (argc != 3 && argc != 6) {
- printf("Usage: crossover_test input.raw output.raw "
- "[low.raw mid.raw high.raw]\n");
- return 1;
- }
-
- dsp_enable_flush_denormal_to_zero();
- dsp_util_clear_fp_exceptions();
-
- data0 = read_raw(argv[1], &frames);
- data1 = (float *)malloc(sizeof(float) * frames * 2);
- data2 = (float *)malloc(sizeof(float) * frames * 2);
-
- crossover_init(&xo, 400 / NQ, 4000 / NQ);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(&xo, frames, data0, data1, data2);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames);
-
- crossover_init(&xo, 400 / NQ, 4000 / NQ);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(&xo, frames, data0 + frames, data1 + frames, data2 + frames);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames);
-
- if (argc == 6) {
- write_raw(argv[3], data0, frames);
- write_raw(argv[4], data1, frames);
- write_raw(argv[5], data2, frames);
- }
-
- int i;
- for (i = 0; i < frames * 2; i++)
- data0[i] += data1[i] + data2[i];
- write_raw(argv[2], data0, frames);
-
- free(data0);
- free(data1);
- free(data2);
-
- dsp_util_print_fp_exceptions();
- return 0;
-}
diff --git a/cras/src/dsp/tests/dcblock_test.c b/cras/src/dsp/tests/dcblock_test.c
deleted file mode 100644
index 7beaa9f7..00000000
--- a/cras/src/dsp/tests/dcblock_test.c
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include "dsp_test_util.h"
-#include "dsp_util.h"
-#include "dcblock.h"
-#include "raw.h"
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-static double tp_diff(struct timespec *tp2, struct timespec *tp1)
-{
- return (tp2->tv_sec - tp1->tv_sec) +
- (tp2->tv_nsec - tp1->tv_nsec) * 1e-9;
-}
-
-/* Processes a buffer of data chunk by chunk using the filter */
-static void process(struct dcblock *dcblock, float *data, int count)
-{
- int start;
- for (start = 0; start < count; start += 128)
- dcblock_process(dcblock, data + start, min(128, count - start));
-}
-
-/* Runs the filters on an input file */
-static void test_file(const char *input_filename, const char *output_filename)
-{
- size_t frames;
- struct timespec tp1, tp2;
- struct dcblock *dcblockl;
- struct dcblock *dcblockr;
-
- float *data = read_raw(input_filename, &frames);
-
- dcblockl = dcblock_new(0.995, 48000);
- dcblockr = dcblock_new(0.995, 48000);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(dcblockl, data, frames);
- process(dcblockr, data + frames, frames);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames);
- dcblock_free(dcblockl);
- dcblock_free(dcblockr);
-
- write_raw(output_filename, data, frames);
- free(data);
-}
-
-int main(int argc, char **argv)
-{
- dsp_enable_flush_denormal_to_zero();
- if (dsp_util_has_denormal())
- printf("denormal still supported?\n");
- else
- printf("denormal disabled\n");
- dsp_util_clear_fp_exceptions();
-
- if (argc == 3)
- test_file(argv[1], argv[2]);
- else
- printf("Usage: dcblock_test input.raw output.raw\n");
-
- dsp_util_print_fp_exceptions();
- return 0;
-}
diff --git a/cras/src/dsp/tests/drc_test.c b/cras/src/dsp/tests/drc_test.c
deleted file mode 100644
index 17ccbcd5..00000000
--- a/cras/src/dsp/tests/drc_test.c
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include "dsp_test_util.h"
-#include "dsp_util.h"
-#include "drc.h"
-#include "raw.h"
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-static double tp_diff(struct timespec *tp2, struct timespec *tp1)
-{
- return (tp2->tv_sec - tp1->tv_sec) +
- (tp2->tv_nsec - tp1->tv_nsec) * 1e-9;
-}
-
-static void process(struct drc *drc, float *buf, size_t frames)
-{
- struct timespec tp1, tp2;
- int start;
- float *data[2];
- int chunk;
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- for (start = 0; start < frames;) {
- data[0] = buf + start;
- data[1] = buf + start + frames;
- chunk = min(DRC_PROCESS_MAX_FRAMES, frames - start);
- drc_process(drc, data, chunk);
- start += chunk;
- }
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("drc processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames * 2);
-}
-
-int main(int argc, char **argv)
-{
- double NQ = 44100 / 2; /* nyquist frequency */
- struct drc *drc;
- size_t frames;
- float *buf;
-
- if (argc != 3) {
- printf("Usage: drc_test input.raw output.raw\n");
- return 1;
- }
-
- dsp_enable_flush_denormal_to_zero();
- dsp_util_clear_fp_exceptions();
- drc = drc_new(44100);
-
- drc->emphasis_disabled = 0;
- drc_set_param(drc, 0, PARAM_CROSSOVER_LOWER_FREQ, 0);
- drc_set_param(drc, 0, PARAM_ENABLED, 1);
- drc_set_param(drc, 0, PARAM_THRESHOLD, -29);
- drc_set_param(drc, 0, PARAM_KNEE, 3);
- drc_set_param(drc, 0, PARAM_RATIO, 6.677);
- drc_set_param(drc, 0, PARAM_ATTACK, 0.02);
- drc_set_param(drc, 0, PARAM_RELEASE, 0.2);
- drc_set_param(drc, 0, PARAM_POST_GAIN, -7);
-
- drc_set_param(drc, 1, PARAM_CROSSOVER_LOWER_FREQ, 200 / NQ);
- drc_set_param(drc, 1, PARAM_ENABLED, 1);
- drc_set_param(drc, 1, PARAM_THRESHOLD, -32);
- drc_set_param(drc, 1, PARAM_KNEE, 23);
- drc_set_param(drc, 1, PARAM_RATIO, 12);
- drc_set_param(drc, 1, PARAM_ATTACK, 0.02);
- drc_set_param(drc, 1, PARAM_RELEASE, 0.2);
- drc_set_param(drc, 1, PARAM_POST_GAIN, 0.7);
-
- drc_set_param(drc, 2, PARAM_CROSSOVER_LOWER_FREQ, 1200 / NQ);
- drc_set_param(drc, 2, PARAM_ENABLED, 1);
- drc_set_param(drc, 2, PARAM_THRESHOLD, -24);
- drc_set_param(drc, 2, PARAM_KNEE, 30);
- drc_set_param(drc, 2, PARAM_RATIO, 1);
- drc_set_param(drc, 2, PARAM_ATTACK, 0.001);
- drc_set_param(drc, 2, PARAM_RELEASE, 1);
- drc_set_param(drc, 2, PARAM_POST_GAIN, 0);
-
- drc_init(drc);
- buf = read_raw(argv[1], &frames);
- process(drc, buf, frames);
- write_raw(argv[2], buf, frames);
- drc_free(drc);
- free(buf);
- dsp_util_print_fp_exceptions();
- return 0;
-}
diff --git a/cras/src/dsp/tests/dsp_test_util.c b/cras/src/dsp/tests/dsp_test_util.c
deleted file mode 100644
index e52a481a..00000000
--- a/cras/src/dsp/tests/dsp_test_util.c
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <fenv.h>
-#include <float.h>
-#include <stdio.h>
-#include "dsp_test_util.h"
-
-int dsp_util_has_denormal()
-{
- float x = 1;
- while (x >= FLT_MIN)
- x /= 2;
- return x > 0;
-}
-
-void dsp_util_clear_fp_exceptions()
-{
- feclearexcept(FE_ALL_EXCEPT);
-}
-
-void dsp_util_print_fp_exceptions()
-{
- int excepts = fetestexcept(FE_ALL_EXCEPT);
- printf("floating-point exceptions: ");
- if (excepts & FE_DIVBYZERO)
- printf("FE_DIVBYZERO ");
- if (excepts & FE_INVALID)
- printf("FE_INVALID ");
- if (excepts & FE_OVERFLOW)
- printf("FE_OVERFLOW ");
- if (excepts & FE_UNDERFLOW)
- printf("FE_UNDERFLOW ");
- printf("\n");
-}
diff --git a/cras/src/dsp/tests/dsp_test_util.h b/cras/src/dsp/tests/dsp_test_util.h
deleted file mode 100644
index eb97815c..00000000
--- a/cras/src/dsp/tests/dsp_test_util.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef DSP_TEST_UTIL_H_
-#define DSP_TEST_UTIL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Tests if the system supports denormal numbers. Returns 1 if so, 0
- * otherwise.*/
-int dsp_util_has_denormal();
-
-/* Clears floating point exceptions. For debugging only. */
-void dsp_util_clear_fp_exceptions();
-
-/* Prints floating point exceptions to stdout. For debugging only. */
-void dsp_util_print_fp_exceptions();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* DSP_TEST_UTIL_H_ */
diff --git a/cras/src/dsp/tests/dsp_util_test.c b/cras/src/dsp/tests/dsp_util_test.c
deleted file mode 100644
index 44f72575..00000000
--- a/cras/src/dsp/tests/dsp_util_test.c
+++ /dev/null
@@ -1,389 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <math.h> /* for abs() */
-#include <stdio.h> /* for printf() */
-#include <string.h> /* for memset() */
-#include <stdint.h> /* for uint64 definition */
-#include <stdlib.h> /* for exit() definition */
-#include <time.h> /* for clock_gettime */
-
-#include "../drc_math.h"
-#include "../dsp_util.h"
-
-/* Constant for converting time to milliseconds. */
-#define BILLION 1000000000LL
-/* Number of iterations for performance testing. */
-#define ITERATIONS 400000
-
-#if defined(__aarch64__)
-int16_t float_to_short(float a)
-{
- int32_t ret;
- asm volatile("fcvtas %s[ret], %s[a]\n"
- "sqxtn %h[ret], %s[ret]\n"
- : [ret] "=w"(ret)
- : [a] "w"(a)
- :);
- return (int16_t)(ret);
-}
-#else
-int16_t float_to_short(float a)
-{
- a += (a >= 0) ? 0.5f : -0.5f;
- return (int16_t)(max(-32768, min(32767, a)));
-}
-#endif
-
-void dsp_util_deinterleave_reference(int16_t *input, float *const *output,
- int channels, int frames)
-{
- float *output_ptr[channels];
- int i, j;
-
- for (i = 0; i < channels; i++)
- output_ptr[i] = output[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++)
- *(output_ptr[j]++) = *input++ / 32768.0f;
-}
-
-void dsp_util_interleave_reference(float *const *input, int16_t *output,
- int channels, int frames)
-{
- float *input_ptr[channels];
- int i, j;
-
- for (i = 0; i < channels; i++)
- input_ptr[i] = input[i];
-
- for (i = 0; i < frames; i++)
- for (j = 0; j < channels; j++) {
- float f = *(input_ptr[j]++) * 32768.0f;
- *output++ = float_to_short(f);
- }
-}
-
-/* Use fixed size allocation to avoid performance fluctuation of allocation. */
-#define MAXSAMPLES 4096
-#define MINSAMPLES 256
-/* PAD buffer to check for overflows. */
-#define PAD 4096
-
-void TestRounding(float in, int16_t expected, int samples)
-{
- int i;
- int max_diff;
- int d;
-
- short *in_shorts = (short *)malloc(MAXSAMPLES * 2 * 2 + PAD);
- float *out_floats_left_c = (float *)malloc(MAXSAMPLES * 4 + PAD);
- float *out_floats_right_c = (float *)malloc(MAXSAMPLES * 4 + PAD);
- float *out_floats_left_opt = (float *)malloc(MAXSAMPLES * 4 + PAD);
- float *out_floats_right_opt = (float *)malloc(MAXSAMPLES * 4 + PAD);
- short *out_shorts_c = (short *)malloc(MAXSAMPLES * 2 * 2 + PAD);
- short *out_shorts_opt = (short *)malloc(MAXSAMPLES * 2 * 2 + PAD);
-
- memset(in_shorts, 0xfb, MAXSAMPLES * 2 * 2 + PAD);
- memset(out_floats_left_c, 0xfb, MAXSAMPLES * 4 + PAD);
- memset(out_floats_right_c, 0xfb, MAXSAMPLES * 4 + PAD);
- memset(out_floats_left_opt, 0xfb, MAXSAMPLES * 4 + PAD);
- memset(out_floats_right_opt, 0xfb, MAXSAMPLES * 4 + PAD);
- memset(out_shorts_c, 0xfb, MAXSAMPLES * 2 * 2 + PAD);
- memset(out_shorts_opt, 0xfb, MAXSAMPLES * 2 * 2 + PAD);
-
- float *out_floats_ptr_c[2];
- float *out_floats_ptr_opt[2];
-
- out_floats_ptr_c[0] = out_floats_left_c;
- out_floats_ptr_c[1] = out_floats_right_c;
- out_floats_ptr_opt[0] = out_floats_left_opt;
- out_floats_ptr_opt[1] = out_floats_right_opt;
-
- for (i = 0; i < MAXSAMPLES; ++i) {
- out_floats_left_c[i] = in;
- out_floats_right_c[i] = in;
- }
-
- /* reference C interleave */
- dsp_util_interleave_reference(out_floats_ptr_c, out_shorts_c, 2,
- samples);
-
- /* measure optimized interleave */
- for (i = 0; i < ITERATIONS; ++i) {
- dsp_util_interleave(out_floats_ptr_c, (uint8_t *)out_shorts_opt,
- 2, SND_PCM_FORMAT_S16_LE, samples);
- }
-
- max_diff = 0;
- for (i = 0; i < (MAXSAMPLES * 2 + PAD / 2); ++i) {
- d = abs(out_shorts_c[i] - out_shorts_opt[i]);
- if (d > max_diff) {
- max_diff = d;
- }
- }
- printf("test interleave compare %6d, %10f %13f %6d %6d %6d %s\n",
- max_diff, in, in * 32768.0f, out_shorts_c[0], out_shorts_opt[0],
- expected,
- max_diff == 0 ? "PASS" :
- (out_shorts_opt[0] == expected ?
- "EXPECTED DIFFERENCE" :
- "UNEXPECTED DIFFERENCE"));
-
- /* measure reference C deinterleave */
- dsp_util_deinterleave_reference(in_shorts, out_floats_ptr_c, 2,
- samples);
-
- /* measure optimized deinterleave */
- dsp_util_deinterleave((uint8_t *)in_shorts, out_floats_ptr_opt, 2,
- SND_PCM_FORMAT_S16_LE, samples);
-
- d = memcmp(out_floats_ptr_c[0], out_floats_ptr_opt[0], samples * 4);
- if (d)
- printf("left compare %d, %f %f\n", d, out_floats_ptr_c[0][0],
- out_floats_ptr_opt[0][0]);
- d = memcmp(out_floats_ptr_c[1], out_floats_ptr_opt[1], samples * 4);
- if (d)
- printf("right compare %d, %f %f\n", d, out_floats_ptr_c[1][0],
- out_floats_ptr_opt[1][0]);
-
- free(in_shorts);
- free(out_floats_left_c);
- free(out_floats_right_c);
- free(out_floats_left_opt);
- free(out_floats_right_opt);
- free(out_shorts_c);
- free(out_shorts_opt);
-}
-
-int main(int argc, char **argv)
-{
- float e = 0.000000001f;
- int samples = 16;
-
- dsp_enable_flush_denormal_to_zero();
-
- // Print headings for TestRounding output.
- printf("test interleave compare maxdif, float, float * 32k "
- "C SIMD expect pass\n");
-
- // test clamping
- TestRounding(1.0f, 32767, samples);
- TestRounding(-1.0f, -32768, samples);
- TestRounding(1.1f, 32767, samples);
- TestRounding(-1.1f, -32768, samples);
- TestRounding(2000000000.f / 32768.f, 32767, samples);
- TestRounding(-2000000000.f / 32768.f, -32768, samples);
-
- /* Infinity produces zero on arm64. */
-#if defined(__aarch64__)
-#define EXPECTED_INF_RESULT 0
-#define EXPECTED_NEGINF_RESULT 0
-#elif defined(__i386__) || defined(__x86_64__)
-#define EXPECTED_INF_RESULT -32768
-#define EXPECTED_NEGINF_RESULT 0
-#else
-#define EXPECTED_INF_RESULT 32767
-#define EXPECTED_NEGINF_RESULT -32768
-#endif
-
- TestRounding(5000000000.f / 32768.f, EXPECTED_INF_RESULT, samples);
- TestRounding(-5000000000.f / 32768.f, EXPECTED_NEGINF_RESULT, samples);
-
- // test infinity
- union ieee754_float inf;
- inf.ieee.negative = 0;
- inf.ieee.exponent = 0xfe;
- inf.ieee.mantissa = 0x7fffff;
- TestRounding(inf.f, EXPECTED_INF_RESULT, samples); // expect fail
- inf.ieee.negative = 1;
- inf.ieee.exponent = 0xfe;
- inf.ieee.mantissa = 0x7fffff;
- TestRounding(inf.f, EXPECTED_NEGINF_RESULT, samples); // expect fail
-
- // test rounding
- TestRounding(0.25f, 8192, samples);
- TestRounding(-0.25f, -8192, samples);
- TestRounding(0.50f, 16384, samples);
- TestRounding(-0.50f, -16384, samples);
- TestRounding(1.0f / 32768.0f, 1, samples);
- TestRounding(-1.0f / 32768.0f, -1, samples);
- TestRounding(1.0f / 32768.0f + e, 1, samples);
- TestRounding(-1.0f / 32768.0f - e, -1, samples);
- TestRounding(1.0f / 32768.0f - e, 1, samples);
- TestRounding(-1.0f / 32768.0f + e, -1, samples);
-
- /* Rounding on 'tie' is different for Intel. */
-#if defined(__i386__) || defined(__x86_64__)
- TestRounding(0.5f / 32768.0f, 0, samples); /* Expect round to even */
- TestRounding(-0.5f / 32768.0f, 0, samples);
-#else
- TestRounding(0.5f / 32768.0f, 1, samples); /* Expect round away */
- TestRounding(-0.5f / 32768.0f, -1, samples);
-#endif
-
- TestRounding(0.5f / 32768.0f + e, 1, samples);
- TestRounding(-0.5f / 32768.0f - e, 1, samples);
- TestRounding(0.5f / 32768.0f - e, 0, samples);
- TestRounding(-0.5f / 32768.0f + e, 0, samples);
-
- TestRounding(1.5f / 32768.0f, 2, samples);
- TestRounding(-1.5f / 32768.0f, -2, samples);
- TestRounding(1.5f / 32768.0f + e, 2, samples);
- TestRounding(-1.5f / 32768.0f - e, -2, samples);
- TestRounding(1.5f / 32768.0f - e, 1, samples);
- TestRounding(-1.5f / 32768.0f + e, -1, samples);
-
- /* Test denormals */
- union ieee754_float denorm;
- denorm.ieee.negative = 0;
- denorm.ieee.exponent = 0;
- denorm.ieee.mantissa = 1;
- TestRounding(denorm.f, 0, samples);
- denorm.ieee.negative = 1;
- denorm.ieee.exponent = 0;
- denorm.ieee.mantissa = 1;
- TestRounding(denorm.f, 0, samples);
-
- /* Test NaNs. Caveat Results vary by implementation. */
-#if defined(__i386__) || defined(__x86_64__)
-#define EXPECTED_NAN_RESULT -32768
-#else
-#define EXPECTED_NAN_RESULT 0
-#endif
- union ieee754_float nan; /* Quiet NaN */
- nan.ieee.negative = 0;
- nan.ieee.exponent = 0xff;
- nan.ieee.mantissa = 0x400001;
- TestRounding(nan.f, EXPECTED_NAN_RESULT, samples);
- nan.ieee.negative = 0;
- nan.ieee.exponent = 0xff;
- nan.ieee.mantissa = 0x000001; /* Signalling NaN */
- TestRounding(nan.f, EXPECTED_NAN_RESULT, samples);
-
- /* Test Performance */
- uint64_t diff;
- struct timespec start, end;
- int i;
- int d;
-
- short *in_shorts = (short *)malloc(MAXSAMPLES * 2 * 2 + PAD);
- float *out_floats_left_c = (float *)malloc(MAXSAMPLES * 4 + PAD);
- float *out_floats_right_c = (float *)malloc(MAXSAMPLES * 4 + PAD);
- float *out_floats_left_opt = (float *)malloc(MAXSAMPLES * 4 + PAD);
- float *out_floats_right_opt = (float *)malloc(MAXSAMPLES * 4 + PAD);
- short *out_shorts_c = (short *)malloc(MAXSAMPLES * 2 * 2 + PAD);
- short *out_shorts_opt = (short *)malloc(MAXSAMPLES * 2 * 2 + PAD);
-
- memset(in_shorts, 0x11, MAXSAMPLES * 2 * 2 + PAD);
- memset(out_floats_left_c, 0x22, MAXSAMPLES * 4 + PAD);
- memset(out_floats_right_c, 0x33, MAXSAMPLES * 4 + PAD);
- memset(out_floats_left_opt, 0x44, MAXSAMPLES * 4 + PAD);
- memset(out_floats_right_opt, 0x55, MAXSAMPLES * 4 + PAD);
- memset(out_shorts_c, 0x66, MAXSAMPLES * 2 * 2 + PAD);
- memset(out_shorts_opt, 0x66, MAXSAMPLES * 2 * 2 + PAD);
-
- float *out_floats_ptr_c[2];
- float *out_floats_ptr_opt[2];
-
- out_floats_ptr_c[0] = out_floats_left_c;
- out_floats_ptr_c[1] = out_floats_right_c;
- out_floats_ptr_opt[0] = out_floats_left_opt;
- out_floats_ptr_opt[1] = out_floats_right_opt;
-
- /* Benchmark dsp_util_interleave */
- for (samples = MAXSAMPLES; samples >= MINSAMPLES; samples /= 2) {
- /* measure original C interleave */
- clock_gettime(CLOCK_MONOTONIC, &start); /* mark start time */
- for (i = 0; i < ITERATIONS; ++i) {
- dsp_util_interleave_reference(out_floats_ptr_c,
- out_shorts_c, 2, samples);
- }
- clock_gettime(CLOCK_MONOTONIC, &end); /* mark the end time */
- diff = (BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec -
- start.tv_nsec) /
- 1000000;
- printf("interleave ORIG size = %6d, elapsed time = %llu ms\n",
- samples, (long long unsigned int)diff);
-
- /* measure optimized interleave */
- clock_gettime(CLOCK_MONOTONIC, &start); /* mark start time */
- for (i = 0; i < ITERATIONS; ++i) {
- dsp_util_interleave(out_floats_ptr_c,
- (uint8_t *)out_shorts_opt, 2,
- SND_PCM_FORMAT_S16_LE, samples);
- }
- clock_gettime(CLOCK_MONOTONIC, &end); /* mark the end time */
- diff = (BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec -
- start.tv_nsec) /
- 1000000;
- printf("interleave SIMD size = %6d, elapsed time = %llu ms\n",
- samples, (long long unsigned int)diff);
-
- /* Test C and SIMD output match */
- d = memcmp(out_shorts_c, out_shorts_opt,
- MAXSAMPLES * 2 * 2 + PAD);
- if (d)
- printf("interleave compare %d, %d %d, %d %d\n", d,
- out_shorts_c[0], out_shorts_c[1],
- out_shorts_opt[0], out_shorts_opt[1]);
- }
-
- /* Benchmark dsp_util_deinterleave */
- for (samples = MAXSAMPLES; samples >= MINSAMPLES; samples /= 2) {
- /* Measure original C deinterleave */
- clock_gettime(CLOCK_MONOTONIC, &start); /* mark start time */
- for (i = 0; i < ITERATIONS; ++i) {
- dsp_util_deinterleave_reference(
- in_shorts, out_floats_ptr_c, 2, samples);
- }
- clock_gettime(CLOCK_MONOTONIC, &end); /* mark the end time */
- diff = (BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec -
- start.tv_nsec) /
- 1000000;
- printf("deinterleave ORIG size = %6d, "
- "elapsed time = %llu ms\n",
- samples, (long long unsigned int)diff);
-
- /* Measure optimized deinterleave */
- clock_gettime(CLOCK_MONOTONIC, &start); /* mark start time */
- for (i = 0; i < ITERATIONS; ++i) {
- dsp_util_deinterleave((uint8_t *)in_shorts,
- out_floats_ptr_opt, 2,
- SND_PCM_FORMAT_S16_LE, samples);
- }
- clock_gettime(CLOCK_MONOTONIC, &end); /* mark the end time */
- diff = (BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec -
- start.tv_nsec) /
- 1000000;
- printf("deinterleave SIMD size = %6d, elapsed time = %llu ms\n",
- samples, (long long unsigned int)diff);
-
- /* Test C and SIMD output match */
- d = memcmp(out_floats_ptr_c[0], out_floats_ptr_opt[0],
- samples * 4);
- if (d)
- printf("left compare %d, %f %f\n", d,
- out_floats_ptr_c[0][0],
- out_floats_ptr_opt[0][0]);
- d = memcmp(out_floats_ptr_c[1], out_floats_ptr_opt[1],
- samples * 4);
- if (d)
- printf("right compare %d, %f %f\n", d,
- out_floats_ptr_c[1][0],
- out_floats_ptr_opt[1][0]);
- }
-
- free(in_shorts);
- free(out_floats_left_c);
- free(out_floats_right_c);
- free(out_floats_left_opt);
- free(out_floats_right_opt);
- free(out_shorts_c);
- free(out_shorts_opt);
-
- return 0;
-}
diff --git a/cras/src/dsp/tests/eq2_test.c b/cras/src/dsp/tests/eq2_test.c
deleted file mode 100644
index 36ce80bd..00000000
--- a/cras/src/dsp/tests/eq2_test.c
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include "dsp_test_util.h"
-#include "dsp_util.h"
-#include "eq2.h"
-#include "raw.h"
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-static double tp_diff(struct timespec *tp2, struct timespec *tp1)
-{
- return (tp2->tv_sec - tp1->tv_sec) +
- (tp2->tv_nsec - tp1->tv_nsec) * 1e-9;
-}
-
-/* Processes a buffer of data chunk by chunk using eq2 */
-static void process(struct eq2 *eq2, float *data0, float *data1, int count)
-{
- int start;
- for (start = 0; start < count; start += 2048)
- eq2_process(eq2, data0 + start, data1 + start,
- min(2048, count - start));
-}
-
-/* Runs the filters on an input file */
-static void test_file(const char *input_filename, const char *output_filename)
-{
- size_t frames;
- int i;
- double NQ = 44100 / 2; /* nyquist frequency */
- struct timespec tp1, tp2;
- struct eq2 *eq2;
-
- float *data = read_raw(input_filename, &frames);
-
- /* Set some data to 0 to test for denormals. */
- for (i = frames / 10; i < frames; i++)
- data[i] = 0.0;
-
- /* eq chain */
- eq2 = eq2_new();
- eq2_append_biquad(eq2, 0, BQ_PEAKING, 380 / NQ, 3, -10);
- eq2_append_biquad(eq2, 0, BQ_PEAKING, 720 / NQ, 3, -12);
- eq2_append_biquad(eq2, 0, BQ_PEAKING, 1705 / NQ, 3, -8);
- eq2_append_biquad(eq2, 0, BQ_HIGHPASS, 218 / NQ, 0.7, -10.2);
- eq2_append_biquad(eq2, 0, BQ_PEAKING, 580 / NQ, 6, -8);
- eq2_append_biquad(eq2, 0, BQ_HIGHSHELF, 8000 / NQ, 3, 2);
- eq2_append_biquad(eq2, 1, BQ_PEAKING, 450 / NQ, 3, -12);
- eq2_append_biquad(eq2, 1, BQ_PEAKING, 721 / NQ, 3, -12);
- eq2_append_biquad(eq2, 1, BQ_PEAKING, 1800 / NQ, 8, -10.2);
- eq2_append_biquad(eq2, 1, BQ_PEAKING, 580 / NQ, 6, -8);
- eq2_append_biquad(eq2, 1, BQ_HIGHPASS, 250 / NQ, 0.6578, 0);
- eq2_append_biquad(eq2, 1, BQ_HIGHSHELF, 8000 / NQ, 0, 2);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(eq2, data, data + frames, frames);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames * 2);
- eq2_free(eq2);
-
- write_raw(output_filename, data, frames);
- free(data);
-}
-
-int main(int argc, char **argv)
-{
- dsp_enable_flush_denormal_to_zero();
- if (dsp_util_has_denormal())
- printf("denormal still supported?\n");
- else
- printf("denormal disabled\n");
- dsp_util_clear_fp_exceptions();
-
- if (argc == 3)
- test_file(argv[1], argv[2]);
- else
- printf("Usage: eq2_test [input.raw output.raw]\n");
-
- dsp_util_print_fp_exceptions();
- return 0;
-}
diff --git a/cras/src/dsp/tests/eq_test.c b/cras/src/dsp/tests/eq_test.c
deleted file mode 100644
index 4adcecf6..00000000
--- a/cras/src/dsp/tests/eq_test.c
+++ /dev/null
@@ -1,140 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include "dsp_test_util.h"
-#include "dsp_util.h"
-#include "eq.h"
-#include "raw.h"
-
-#ifndef min
-#define min(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-#endif
-
-static double tp_diff(struct timespec *tp2, struct timespec *tp1)
-{
- return (tp2->tv_sec - tp1->tv_sec) +
- (tp2->tv_nsec - tp1->tv_nsec) * 1e-9;
-}
-
-/* Generates impulse response */
-static void test_ir()
-{
- int N = 32768;
- float *data;
- struct eq *eq;
- double NQ = 44100 / 2; /* nyquist frequency */
- struct timespec tp1, tp2;
- int i;
- FILE *ir;
-
- data = calloc(1, sizeof(float) * N);
- data[0] = 1;
-
- eq = eq_new();
- eq_append_biquad(eq, BQ_PEAKING, 380 / NQ, 3, -10);
- eq_append_biquad(eq, BQ_PEAKING, 720 / NQ, 3, -12);
- eq_append_biquad(eq, BQ_PEAKING, 1705 / NQ, 3, -8);
- eq_append_biquad(eq, BQ_HIGHPASS, 218 / NQ, 0.7, -10.2);
- eq_append_biquad(eq, BQ_PEAKING, 580 / NQ, 6, -8);
- eq_append_biquad(eq, BQ_HIGHSHELF, 8000 / NQ, 3, 2);
-
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- eq_process(eq, data, N);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds\n", tp_diff(&tp2, &tp1));
- eq_free(eq);
-
- ir = fopen("ir.dat", "w");
- for (i = 0; i < N; i++)
- fprintf(ir, "%g\n", data[i]);
- fclose(ir);
- free(data);
-}
-
-/* Processes a buffer of data chunk by chunk using eq */
-static void process(struct eq *eq, float *data, int count)
-{
- int start;
- for (start = 0; start < count; start += 2048)
- eq_process(eq, data + start, min(2048, count - start));
-}
-
-/* Runs the filters on an input file */
-static void test_file(const char *input_filename, const char *output_filename)
-{
- size_t frames;
- int i;
- double NQ = 44100 / 2; /* nyquist frequency */
- struct timespec tp1, tp2;
- struct eq *eq;
-
- float *data = read_raw(input_filename, &frames);
-
- /* Set some data to 0 to test for denormals. */
- for (i = frames / 10; i < frames; i++)
- data[i] = 0.0;
-
- /* Left eq chain */
- eq = eq_new();
- eq_append_biquad(eq, BQ_PEAKING, 380 / NQ, 3, -10);
- eq_append_biquad(eq, BQ_PEAKING, 720 / NQ, 3, -12);
- eq_append_biquad(eq, BQ_PEAKING, 1705 / NQ, 3, -8);
- eq_append_biquad(eq, BQ_HIGHPASS, 218 / NQ, 0.7, -10.2);
- eq_append_biquad(eq, BQ_PEAKING, 580 / NQ, 6, -8);
- eq_append_biquad(eq, BQ_HIGHSHELF, 8000 / NQ, 3, 2);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(eq, data, frames);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames);
- eq_free(eq);
-
- /* Right eq chain */
- eq = eq_new();
- eq_append_biquad(eq, BQ_PEAKING, 450 / NQ, 3, -12);
- eq_append_biquad(eq, BQ_PEAKING, 721 / NQ, 3, -12);
- eq_append_biquad(eq, BQ_PEAKING, 1800 / NQ, 8, -10.2);
- eq_append_biquad(eq, BQ_PEAKING, 580 / NQ, 6, -8);
- eq_append_biquad(eq, BQ_HIGHPASS, 250 / NQ, 0.6578, 0);
- eq_append_biquad(eq, BQ_HIGHSHELF, 8000 / NQ, 0, 2);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp1);
- process(eq, data + frames, frames);
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tp2);
- printf("processing takes %g seconds for %zu samples\n",
- tp_diff(&tp2, &tp1), frames);
- eq_free(eq);
-
- write_raw(output_filename, data, frames);
- free(data);
-}
-
-int main(int argc, char **argv)
-{
- dsp_enable_flush_denormal_to_zero();
- if (dsp_util_has_denormal())
- printf("denormal still supported?\n");
- else
- printf("denormal disabled\n");
- dsp_util_clear_fp_exceptions();
-
- if (argc == 1)
- test_ir();
- else if (argc == 3)
- test_file(argv[1], argv[2]);
- else
- printf("Usage: eq_test [input.raw output.raw]\n");
-
- dsp_util_print_fp_exceptions();
- return 0;
-}
diff --git a/cras/src/dsp/tests/plot_fftl.m b/cras/src/dsp/tests/plot_fftl.m
deleted file mode 100644
index bffc0b8e..00000000
--- a/cras/src/dsp/tests/plot_fftl.m
+++ /dev/null
@@ -1,40 +0,0 @@
-% Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-% Use of this source code is governed by a BSD-style license that can be
-% found in the LICENSE file.
-%
-% This is an octave script.
-% It reads impulse response from "ir.dat" and plots frequency response.
-% Both x-axis and y-axis is in log scale.
-h=load("ir.dat");
-N=columns(h);
-K=rows(h)/2;
-NQ=44100/2;
-% This tries to match the labels in the audio tuning UI.
-xticks=[22050, 11025, 5513, 2756, 1378, 689, 345, 172, 86, 43, 21];
-xticklabels={"22050Hz", "11025Hz", "5513Hz", "2756Hz", "1378Hz", \
-"689Hz", "345Hz", "172Hz", "86Hz", "43Hz", "21Hz"};
-yticks=[18,12,6,0,-6,-12,-18,-24];
-yticklabels={"18dB","12dB","6dB","0dB","-6dB","-12dB","-18dB","-24dB"};
-xyrange=[21,22050,-24,18];
-xrange=[21,22050];
-
-for i=1:N
- figure(i);
- title('fftl');
- fr = fft(h(:,i))(1:K);
- subplot(2, 1, 1);
- semilogx(NQ*(1:K)/K, 20*log10(abs(fr)));
- xlabel('Frequency'), ylabel('Magnitude'), grid;
- set (gca, "xtick", xticks);
- set (gca, "xticklabel", xticklabels);
- set (gca, "ytick", yticks);
- set (gca, "yticklabel", yticklabels);
- axis(xyrange);
- subplot(2, 1, 2);
- semilogx(NQ*(1:K)/K,180/pi*unwrap(angle(fr)));
- xlabel('Frequency'), ylabel('Phase (degrees)'), grid;
- set (gca, "xtick", xticks);
- set (gca, "xticklabel", xticklabels);
- axis(xrange);
-end
-pause
diff --git a/cras/src/dsp/tests/raw.c b/cras/src/dsp/tests/raw.c
deleted file mode 100644
index d75e28fa..00000000
--- a/cras/src/dsp/tests/raw.c
+++ /dev/null
@@ -1,93 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-float *read_raw(const char *filename, size_t *frames)
-{
- struct stat st;
- int16_t *buf;
- size_t f, n;
- int fd;
- float *data;
- int i;
-
- if (stat(filename, &st) < 0) {
- fprintf(stderr, "cannot stat file %s\n", filename);
- return NULL;
- }
-
- fd = open(filename, O_RDONLY);
- if (fd < 0) {
- fprintf(stderr, "cannot open file %s\n", filename);
- return NULL;
- }
-
- f = st.st_size / 4;
- n = f * 4;
- buf = (int16_t *)malloc(n);
- if (read(fd, buf, n) != n) {
- fprintf(stderr, "short read %zu\n", n);
- free(buf);
- return NULL;
- }
- close(fd);
-
- /* deinterleave and convert to float */
- data = (float *)malloc(sizeof(float) * f * 2);
- for (i = 0; i < f; i++) {
- data[i] = buf[2 * i] / 32768.0f;
- data[i + f] = buf[2 * i + 1] / 32768.0f;
- }
- free(buf);
- *frames = f;
- return data;
-}
-
-static int16_t f2s16(float f)
-{
- int i;
- f *= 32768;
- i = (int)((f > 0) ? (f + 0.5f) : (f - 0.5f));
- if (i < -32768)
- i = -32768;
- else if (i > 32767)
- i = 32767;
- return (int16_t)i;
-}
-
-int write_raw(const char *filename, float *input, size_t frames)
-{
- int16_t *buf;
- int rc = -1;
- int n = frames * 4;
- int i;
-
- buf = (int16_t *)malloc(n);
- for (i = 0; i < frames; i++) {
- buf[2 * i] = f2s16(input[i]);
- buf[2 * i + 1] = f2s16(input[i + frames]);
- }
-
- int fd = open(filename, O_WRONLY | O_CREAT, 0644);
- if (fd < 0) {
- fprintf(stderr, "cannot open file %s\n", filename);
- goto quit;
- }
- if (write(fd, buf, n) != n) {
- fprintf(stderr, "short write file %s\n", filename);
- goto quit;
- }
- rc = 0;
-quit:
- close(fd);
- free(buf);
- return rc;
-}
diff --git a/cras/src/dsp/tests/raw.h b/cras/src/dsp/tests/raw.h
deleted file mode 100644
index a0a30ab3..00000000
--- a/cras/src/dsp/tests/raw.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef RAW_H_
-#define RAW_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stddef.h>
-
-/* Reads a raw file to a float buffer.
- * Args:
- * filename - The name of the raw file.
- * frames - Returns the number of frames read.
- * Returns:
- * The float buffer allocated by malloc(), or NULL if reading fails. The
- * first half of the buffer contains left channel data, and the second half
- * contains the right channel data.
- * The raw file is assumed to have two channel 16 bit signed integer samples in
- * native endian. The raw file can be created by:
- * sox input.wav output.raw
- * The raw file can be played by:
- * play -r 44100 -s -b 16 -c 2 test.raw
- */
-float *read_raw(const char *filename, size_t *frames);
-
-/* Writes a float buffer to a raw file.
- * Args:
- * filename - The name of the raw file.
- * buf - The float buffer containing the samples.
- * frames - The number of frames in the float buffer.
- * Returns:
- * 0 if success. -1 if writing fails.
- * The format of the float buffer is the same as described in read_raw().
- */
-void write_raw(const char *filename, float *buf, size_t frames);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* RAW_H_ */
diff --git a/cras/src/fuzz/.clang-format b/cras/src/fuzz/.clang-format
deleted file mode 100644
index 3f19e616..00000000
--- a/cras/src/fuzz/.clang-format
+++ /dev/null
@@ -1 +0,0 @@
-BasedOnStyle: Chromium
diff --git a/cras/src/fuzz/Dockerfile b/cras/src/fuzz/Dockerfile
deleted file mode 100644
index caffa995..00000000
--- a/cras/src/fuzz/Dockerfile
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2017 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-# Defines a docker image that can build cras fuzzers.
-#
-FROM gcr.io/oss-fuzz-base/base-builder
-LABEL maintainer="dgreid@chromium.org"
-
-COPY . "${SRC}/adhd"
-COPY cras/src/fuzz/build.sh "${SRC}/build.sh"
-RUN "${SRC}/adhd/cras/install_deps.sh"
-RUN mkdir -p /etc/cras && cp "${SRC}/adhd/cras-config/dsp.ini.sample" /etc/cras
diff --git a/cras/src/fuzz/README.md b/cras/src/fuzz/README.md
deleted file mode 100644
index 0d235cec..00000000
--- a/cras/src/fuzz/README.md
+++ /dev/null
@@ -1,44 +0,0 @@
-# OSS-Fuzz for CRAS
-
-This directory contains source code and build scripts for coverage-guided
-fuzzers.
-
-Detailed instructions are available at: https://github.com/google/oss-fuzz/blob/master/docs/
-
-## Quick start
-
-### Sudoless Docker
-```
-sudo adduser $USER docker
-```
-### Sync to the latest base-builder
-```
-docker pull gcr.io/oss-fuzz-base/base-builder
-```
-
-### Build a container from the adhd directory
-```
-docker build -t ossfuzz/cras -f cras/src/fuzz/Dockerfile .
-```
-Add `--no-cache` if you want a complete rebuild.
-
-### Build fuzzers
-```
-docker run --cap-add=SYS_PTRACE -ti --rm -v /tmp/fuzzers:/out ossfuzz/cras
-```
-
-### Look in /tmp/fuzzers to see the executables. Run them like so:
-```
-docker run --cap-add=SYS_PTRACE -ti -v $(pwd)/cras/src/fuzz/corpus:/corpus \
- -v /tmp/fuzzers:/out ossfuzz/cras /out/rclient_message \
- /corpus -runs=100
-```
-
-### Debug in docker
-
-Go into docker console by
-```
-docker run --cap-add=SYS_PTRACE -ti -v $(pwd)/cras/src/fuzz/corpus:/corpus \
- -v /tmp/fuzzers:/out ossfuzz/cras /bin/bash
-```
-and start debugging.
diff --git a/cras/src/fuzz/build.sh b/cras/src/fuzz/build.sh
deleted file mode 100755
index 44413a7f..00000000
--- a/cras/src/fuzz/build.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/bin/bash -eux
-
-# Copyright 2017 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-# Builds fuzzers from within a container into ${OUT} directory.
-# Expects "${SRC}/adhd" to contain an adhd checkout.
-
-cd "${SRC}/adhd/cras"
-./git_prepare.sh
-
-FUZZER_LDFLAGS="${FUZZER_LDFLAGS} ${LIB_FUZZING_ENGINE}"
-./configure --enable-fuzzer
-
-# Compile fuzzers
-make -j$(nproc)
-
-# Copy fuzzers and dependencies to "${OUT}" directory
-cp "${SRC}/adhd/cras/src/cras_rclient_message_fuzzer" "${OUT}/rclient_message"
-zip -j "${OUT}/rclient_message_corpus.zip" ./src/fuzz/corpus/*
-
-cp "${SRC}/adhd/cras/src/cras_hfp_slc_fuzzer" "${OUT}/cras_hfp_slc"
-cp "${SRC}/adhd/cras/src/fuzz/cras_hfp_slc.dict" "${OUT}/cras_hfp_slc.dict"
diff --git a/cras/src/fuzz/corpus/06051efd871be7eb2b4baed61c3ba53fe0b27833 b/cras/src/fuzz/corpus/06051efd871be7eb2b4baed61c3ba53fe0b27833
deleted file mode 100644
index 09605eca..00000000
--- a/cras/src/fuzz/corpus/06051efd871be7eb2b4baed61c3ba53fe0b27833
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/06e2b48cb549540ab62c0a62a1480f3de7807896 b/cras/src/fuzz/corpus/06e2b48cb549540ab62c0a62a1480f3de7807896
deleted file mode 100644
index fd0149bc..00000000
--- a/cras/src/fuzz/corpus/06e2b48cb549540ab62c0a62a1480f3de7807896
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/1cea528aa30177cb48d9b279b7d1f115b5a60c01 b/cras/src/fuzz/corpus/1cea528aa30177cb48d9b279b7d1f115b5a60c01
deleted file mode 100644
index ffd27bee..00000000
--- a/cras/src/fuzz/corpus/1cea528aa30177cb48d9b279b7d1f115b5a60c01
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/348b671615268f526f174ed2f89d887a26ee8b7a b/cras/src/fuzz/corpus/348b671615268f526f174ed2f89d887a26ee8b7a
deleted file mode 100644
index 0b7a92fa..00000000
--- a/cras/src/fuzz/corpus/348b671615268f526f174ed2f89d887a26ee8b7a
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/756692a278ad08a8f3a9e198b1436620c53247e9 b/cras/src/fuzz/corpus/756692a278ad08a8f3a9e198b1436620c53247e9
deleted file mode 100644
index c768e08b..00000000
--- a/cras/src/fuzz/corpus/756692a278ad08a8f3a9e198b1436620c53247e9
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/90c740f0e2e83b050ba7ccc2b963f2cb6bf23bc1 b/cras/src/fuzz/corpus/90c740f0e2e83b050ba7ccc2b963f2cb6bf23bc1
deleted file mode 100644
index 05718e12..00000000
--- a/cras/src/fuzz/corpus/90c740f0e2e83b050ba7ccc2b963f2cb6bf23bc1
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/9448261a4711bdb5e62490e57f78a9a8d99cfd90 b/cras/src/fuzz/corpus/9448261a4711bdb5e62490e57f78a9a8d99cfd90
deleted file mode 100644
index 6eaf65c8..00000000
--- a/cras/src/fuzz/corpus/9448261a4711bdb5e62490e57f78a9a8d99cfd90
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/b148b3ca1a089964a122b42170eb39e41461e8de b/cras/src/fuzz/corpus/b148b3ca1a089964a122b42170eb39e41461e8de
deleted file mode 100644
index 12f9ff65..00000000
--- a/cras/src/fuzz/corpus/b148b3ca1a089964a122b42170eb39e41461e8de
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/c66fae687ac462af608f9f22ea1b9493b66fe844 b/cras/src/fuzz/corpus/c66fae687ac462af608f9f22ea1b9493b66fe844
deleted file mode 100644
index 74c5e057..00000000
--- a/cras/src/fuzz/corpus/c66fae687ac462af608f9f22ea1b9493b66fe844
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/da39a3ee5e6b4b0d3255bfef95601890afd80709 b/cras/src/fuzz/corpus/da39a3ee5e6b4b0d3255bfef95601890afd80709
deleted file mode 100644
index e69de29b..00000000
--- a/cras/src/fuzz/corpus/da39a3ee5e6b4b0d3255bfef95601890afd80709
+++ /dev/null
diff --git a/cras/src/fuzz/corpus/da6b17d11511d4c4eb14933aa404715e753e2c02 b/cras/src/fuzz/corpus/da6b17d11511d4c4eb14933aa404715e753e2c02
deleted file mode 100644
index 99ceca05..00000000
--- a/cras/src/fuzz/corpus/da6b17d11511d4c4eb14933aa404715e753e2c02
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/e578774a32e52e17461c30848f554f78c3ffda66 b/cras/src/fuzz/corpus/e578774a32e52e17461c30848f554f78c3ffda66
deleted file mode 100644
index 6bfd3e09..00000000
--- a/cras/src/fuzz/corpus/e578774a32e52e17461c30848f554f78c3ffda66
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/corpus/e85fb46a837d5a798d371573b41fd60e1e1486ed b/cras/src/fuzz/corpus/e85fb46a837d5a798d371573b41fd60e1e1486ed
deleted file mode 100644
index ed467b13..00000000
--- a/cras/src/fuzz/corpus/e85fb46a837d5a798d371573b41fd60e1e1486ed
+++ /dev/null
Binary files differ
diff --git a/cras/src/fuzz/cras_hfp_slc.cc b/cras/src/fuzz/cras_hfp_slc.cc
deleted file mode 100644
index 4a76ea46..00000000
--- a/cras/src/fuzz/cras_hfp_slc.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <assert.h>
-#include <fuzzer/FuzzedDataProvider.h>
-#include <stddef.h>
-#include <stdint.h>
-
-extern "C" {
-#include "cras_bt_device.h"
-#include "cras_bt_log.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev_list.h"
-#include "cras_mix.h"
-#include "cras_observer.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-
-struct cras_bt_event_log* btlog;
-}
-
-int disconnect_cb(struct hfp_slc_handle*) {
- return 0;
-}
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
- FuzzedDataProvider data_provider(data, size);
- bool is_hsp = data_provider.ConsumeIntegralInRange(0, 1);
- int ag_supported_features = data_provider.ConsumeIntegral<int>();
- std::string command = data_provider.ConsumeRemainingBytesAsString();
- int fd = open("/dev/null", O_RDWR);
-
- struct cras_bt_device* bt_dev = cras_bt_device_create(NULL, "");
- struct hfp_slc_handle* handle = hfp_slc_create(
- fd, is_hsp, ag_supported_features, bt_dev, NULL, &disconnect_cb);
- if (!handle)
- return 0;
-
- handle_at_command_for_test(handle, command.c_str());
-
- hfp_slc_destroy(handle);
- cras_bt_device_remove(bt_dev);
- return 0;
-}
-
-extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
- char* shm_name;
- if (asprintf(&shm_name, "/cras-%d", getpid()) < 0)
- exit(-ENOMEM);
- struct cras_server_state* exp_state =
- (struct cras_server_state*)calloc(1, sizeof(*exp_state));
- if (!exp_state)
- exit(-1);
- int rw_shm_fd = open("/dev/null", O_RDWR);
- int ro_shm_fd = open("/dev/null", O_RDONLY);
- cras_system_state_init("/tmp", shm_name, rw_shm_fd, ro_shm_fd, exp_state,
- sizeof(*exp_state));
- free(shm_name);
- cras_observer_server_init();
- cras_mix_init(0);
- cras_iodev_list_init();
- btlog = cras_bt_event_log_init();
- return 0;
-}
diff --git a/cras/src/fuzz/cras_hfp_slc.dict b/cras/src/fuzz/cras_hfp_slc.dict
deleted file mode 100644
index cfc49895..00000000
--- a/cras/src/fuzz/cras_hfp_slc.dict
+++ /dev/null
@@ -1,23 +0,0 @@
-"ATA"
-"ATD"
-"AT+BAC"
-"AT+BCS"
-"AT+BIA"
-"AT+BIEV"
-"AT+BIND"
-"AT+BLDN"
-"AT+BRSF"
-"AT+CCWA"
-"AT+CHUP"
-"AT+CIND"
-"AT+CKPD"
-"AT+CLCC"
-"AT+CLIP"
-"AT+CMEE"
-"AT+CMER"
-"AT+CNUM"
-"AT+COPS"
-"AT+IPHONEACCEV"
-"AT+VG"
-"AT+VTS"
-"AT+XAPL"
diff --git a/cras/src/fuzz/rclient_message.cc b/cras/src/fuzz/rclient_message.cc
deleted file mode 100644
index eacf9dab..00000000
--- a/cras/src/fuzz/rclient_message.cc
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <assert.h>
-#include <fuzzer/FuzzedDataProvider.h>
-#include <stddef.h>
-#include <stdint.h>
-
-extern "C" {
-#include "cras_apm_list.h"
-#include "cras_bt_log.h"
-#include "cras_dsp.h"
-#include "cras_iodev_list.h"
-#include "cras_mix.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-
-struct cras_bt_event_log* btlog;
-}
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
- cras_rclient* client = cras_rclient_create(0, 0, CRAS_CONTROL);
- if (size < 300) {
- /* Feeds input data directly if the given bytes is too short. */
- cras_rclient_buffer_from_client(client, data, size, NULL, 0);
- } else {
- FuzzedDataProvider data_provider(data, size);
- int fds[1] = {0};
- int num_fds = data_provider.ConsumeIntegralInRange(0, 1);
- std::vector<uint8_t> msg = data_provider.ConsumeRemainingBytes<uint8_t>();
- cras_rclient_buffer_from_client(client, msg.data(), msg.size(), fds,
- num_fds);
- }
- cras_rclient_destroy(client);
-
- return 0;
-}
-
-extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) {
- char* shm_name;
- if (asprintf(&shm_name, "/cras-%d", getpid()) < 0)
- exit(-ENOMEM);
- struct cras_server_state* exp_state =
- (struct cras_server_state*)calloc(1, sizeof(*exp_state));
- if (!exp_state)
- exit(-1);
- int rw_shm_fd = open("/dev/null", O_RDWR);
- int ro_shm_fd = open("/dev/null", O_RDONLY);
- cras_system_state_init("/tmp", shm_name, rw_shm_fd, ro_shm_fd, exp_state,
- sizeof(*exp_state));
- free(shm_name);
-
- cras_observer_server_init();
- cras_mix_init(0);
- cras_apm_list_init("/etc/cras");
- cras_iodev_list_init();
- /* For cros fuzz, emerge adhd with USE=fuzzer will copy dsp.ini.sample to
- * etc/cras. For OSS-Fuzz the Dockerfile will be responsible for copying the
- * file. This shouldn't crash CRAS even if the dsp file does not exist. */
- cras_dsp_init("/etc/cras/dsp.ini.sample");
- /* Initializes btlog for CRAS_SERVER_DUMP_BT path with CRAS_DBUS defined. */
- btlog = cras_bt_event_log_init();
- return 0;
-}
diff --git a/cras/src/libcras/cras_client.c b/cras/src/libcras/cras_client.c
deleted file mode 100644
index 8420db1f..00000000
--- a/cras/src/libcras/cras_client.c
+++ /dev/null
@@ -1,4249 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Basic playback flow:
- * cras_client_create - Create new structure and set to defaults.
- * cras_client_connect - Connect client to server - sets up server_fd to
- * communicate with the audio server. After the client connects, the server
- * will send back a message containing the client id.
- * cras_client_add_stream - Add a playback or capture stream. Creates a
- * client_stream struct and send a file descriptor to server. That file
- * descriptor and aud_fd are a pair created from socketpair().
- * client_connected - The server will send a connected message to indicate that
- * the client should start receiving audio events from aud_fd. This message
- * also specifies the shared memory region to use to share audio samples.
- * This region will be shmat'd.
- * running - Once the connections are established, the client will listen for
- * requests on aud_fd and fill the shm region with the requested number of
- * samples. This happens in the aud_cb specified in the stream parameters.
- */
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE /* For ppoll() */
-#endif
-
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <poll.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <sys/eventfd.h>
-#include <sys/ipc.h>
-#include <sys/mman.h>
-#include <sys/param.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/timerfd.h>
-#include <sys/types.h>
-#include <sys/un.h>
-#include <syslog.h>
-#include <unistd.h>
-
-#include "cras_client.h"
-#include "cras_config.h"
-#include "cras_file_wait.h"
-#include "cras_messages.h"
-#include "cras_observer_ops.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-static const size_t MAX_CMD_MSG_LEN = 256;
-static const size_t SERVER_SHUTDOWN_TIMEOUT_US = 500000;
-static const size_t SERVER_CONNECT_TIMEOUT_MS = 1000;
-static const size_t HOTWORD_FRAME_RATE = 16000;
-static const size_t HOTWORD_BLOCK_SIZE = 320;
-
-/* Commands sent from the user to the running client. */
-enum { CLIENT_STOP,
- CLIENT_ADD_STREAM,
- CLIENT_REMOVE_STREAM,
- CLIENT_SET_STREAM_VOLUME_SCALER,
- CLIENT_SERVER_CONNECT,
- CLIENT_SERVER_CONNECT_ASYNC,
-};
-
-struct command_msg {
- unsigned len;
- unsigned msg_id;
- cras_stream_id_t stream_id;
-};
-
-struct set_stream_volume_command_message {
- struct command_msg header;
- float volume_scaler;
-};
-
-/* Adds a stream to the client.
- * stream - The stream to add.
- * stream_id_out - Filled with the stream id of the new stream.
- * dev_idx - Index of the device to attach the newly created stream.
- * NO_DEVICE means not to pin the stream to a device.
- */
-struct add_stream_command_message {
- struct command_msg header;
- struct client_stream *stream;
- cras_stream_id_t *stream_id_out;
- uint32_t dev_idx;
-};
-
-/* Commands send from a running stream to the client. */
-enum { CLIENT_STREAM_EOF,
-};
-
-struct stream_msg {
- unsigned msg_id;
- cras_stream_id_t stream_id;
-};
-
-enum CRAS_THREAD_STATE {
- CRAS_THREAD_STOP,
- /* Isn't (shouldn't be) running. */
- CRAS_THREAD_WARMUP,
- /* Is started, but not fully functional: waiting
- * for resources to be ready for example. */
- CRAS_THREAD_RUNNING,
- /* Is running and fully functional. */
-};
-
-/* Manage information for a thread. */
-struct thread_state {
- pthread_t tid;
- enum CRAS_THREAD_STATE state;
-};
-
-/* Parameters used when setting up a capture or playback stream. See comment
- * above cras_client_stream_params_create or libcras_stream_params_set in the
- * header for descriptions. */
-struct cras_stream_params {
- enum CRAS_STREAM_DIRECTION direction;
- size_t buffer_frames;
- size_t cb_threshold;
- enum CRAS_STREAM_TYPE stream_type;
- enum CRAS_CLIENT_TYPE client_type;
- uint32_t flags;
- uint64_t effects;
- void *user_data;
- cras_playback_cb_t aud_cb;
- cras_unified_cb_t unified_cb;
- cras_error_cb_t err_cb;
- struct cras_audio_format format;
- libcras_stream_cb_t stream_cb;
-};
-
-/* Represents an attached audio stream.
- * id - Unique stream identifier.
- * aud_fd - After server connects audio messages come in here.
- * direction - playback, capture, or loopback (see CRAS_STREAM_DIRECTION).
- * flags - Currently only used for CRAS_INPUT_STREAM_FLAG.
- * volume_scaler - Amount to scale the stream by, 0.0 to 1.0. Client could
- * change this scaler value before stream actually connected, so we need
- * to cache it until shm is prepared and apply it.
- * tid - Thread id of the audio thread spawned for this stream.
- * running - Audio thread runs while this is non-zero.
- * wake_fds - Pipe to wake the audio thread.
- * client - The client this stream is attached to.
- * config - Audio stream configuration.
- * shm - Shared memory used to exchange audio samples with the server.
- * prev, next - Form a linked list of streams attached to a client.
- */
-struct client_stream {
- cras_stream_id_t id;
- int aud_fd; /* audio messages from server come in here. */
- enum CRAS_STREAM_DIRECTION direction;
- uint32_t flags;
- float volume_scaler;
- struct thread_state thread;
- int wake_fds[2]; /* Pipe to wake the thread */
- struct cras_client *client;
- struct cras_stream_params *config;
- struct cras_audio_shm *shm;
- struct client_stream *prev, *next;
-};
-
-/* State of the socket. */
-typedef enum cras_socket_state {
- CRAS_SOCKET_STATE_DISCONNECTED,
- /* Not connected. Also used to cleanup the current connection
- * before restarting the connection attempt. */
- CRAS_SOCKET_STATE_WAIT_FOR_SOCKET,
- /* Waiting for the socket file to exist. Socket file existence
- * is monitored using cras_file_wait. */
- CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE,
- /* Waiting for the socket to have something at the other end. */
- CRAS_SOCKET_STATE_FIRST_MESSAGE,
- /* Waiting for the first messages from the server and set our
- * client ID. */
- CRAS_SOCKET_STATE_CONNECTED,
- /* The socket is connected and working. */
- CRAS_SOCKET_STATE_ERROR_DELAY,
- /* There was an error during one of the above states. Sleep for
- * a bit before continuing. If this state could not be initiated
- * then we move to the DISCONNECTED state and notify via the
- * connection callback. */
-} cras_socket_state_t;
-
-/* Represents a client used to communicate with the audio server.
- * id - Unique identifier for this client, negative until connected.
- * server_fd - Incoming messages from server.
- * server_fd_state - State of the server's socket.
- * server_event_fd - Eventfd to wait on until a connection is established.
- * stream_fds - Pipe for attached streams.
- * command_fds - Pipe for user commands to thread.
- * command_reply_fds - Pipe for acking/nacking command messages from thread.
- * sock_file - Server communication socket file.
- * sock_file_wait - Structure used to monitor existence of the socket file.
- * sock_file_exists - Set to true when the socket file exists.
- * running - The client thread will run while this is non zero.
- * next_stream_id - ID to give the next stream.
- * stream_start_cond - Condition used during stream startup.
- * stream_start_lock - Lock used during stream startup.
- * tid - Thread ID of the client thread started by "cras_client_run_thread".
- * last_command_result - Passes back the result of the last user command.
- * streams - Linked list of streams attached to this client.
- * server_state - RO shared memory region holding server state.
- * atlog_ro - RO shared memory region holding audio thread log.
- * debug_info_callback - Function to call when debug info is received.
- * atlog_access_callback - Function to call when atlog RO fd is received.
- * get_hotword_models_cb_t - Function to call when hotword models info is ready.
- * server_connection_cb - Function to called when a connection state changes.
- * server_connection_user_arg - User argument for server_connection_cb.
- * thread_priority_cb - Function to call for setting audio thread priority.
- * observer_ops - Functions to call when system state changes.
- * observer_context - Context passed to client in state change callbacks.
- */
-struct cras_client {
- int id;
- int server_fd;
- cras_socket_state_t server_fd_state;
- int server_event_fd;
- int stream_fds[2];
- int command_fds[2];
- int command_reply_fds[2];
- const char *sock_file;
- struct cras_file_wait *sock_file_wait;
- bool sock_file_exists;
- struct thread_state thread;
- cras_stream_id_t next_stream_id;
- pthread_cond_t stream_start_cond;
- pthread_mutex_t stream_start_lock;
- int last_command_result;
- struct client_stream *streams;
- const struct cras_server_state *server_state;
- struct audio_thread_event_log *atlog_ro;
- void (*debug_info_callback)(struct cras_client *);
- void (*atlog_access_callback)(struct cras_client *);
- get_hotword_models_cb_t get_hotword_models_cb;
- cras_connection_status_cb_t server_connection_cb;
- void *server_connection_user_arg;
- cras_thread_priority_cb_t thread_priority_cb;
- struct cras_observer_ops observer_ops;
- void *observer_context;
-};
-
-/*
- * Holds the client pointer plus internal book keeping.
- *
- * client - The client
- * server_state_rwlock - lock to make the client's server_state thread-safe.
- */
-struct client_int {
- struct cras_client client;
- pthread_rwlock_t server_state_rwlock;
-};
-
-#define to_client_int(cptr) \
- ((struct client_int *)((char *)cptr - \
- offsetof(struct client_int, client)))
-
-/*
- * Holds the hotword stream format, params, and ID used when waiting for a
- * hotword. The structure is created by cras_client_enable_hotword_callback and
- * destroyed by cras_client_disable_hotword_callback.
- */
-struct cras_hotword_handle {
- struct cras_audio_format *format;
- struct cras_stream_params *params;
- cras_stream_id_t stream_id;
- cras_hotword_trigger_cb_t trigger_cb;
- cras_hotword_error_cb_t err_cb;
- void *user_data;
-};
-
-struct cras_stream_cb_data {
- cras_stream_id_t stream_id;
- enum CRAS_STREAM_DIRECTION direction;
- uint8_t *buf;
- unsigned int frames;
- struct timespec sample_ts;
- void *user_arg;
-};
-
-int stream_cb_get_stream_id(struct cras_stream_cb_data *data,
- cras_stream_id_t *id)
-{
- *id = data->stream_id;
- return 0;
-}
-
-int stream_cb_get_buf(struct cras_stream_cb_data *data, uint8_t **buf)
-{
- *buf = data->buf;
- return 0;
-}
-
-int stream_cb_get_frames(struct cras_stream_cb_data *data, unsigned int *frames)
-{
- *frames = data->frames;
- return 0;
-}
-
-int stream_cb_get_latency(struct cras_stream_cb_data *data,
- struct timespec *latency)
-{
- if (data->direction == CRAS_STREAM_INPUT)
- cras_client_calc_capture_latency(&data->sample_ts, latency);
- else
- cras_client_calc_playback_latency(&data->sample_ts, latency);
- return 0;
-}
-
-int stream_cb_get_user_arg(struct cras_stream_cb_data *data, void **user_arg)
-{
- *user_arg = data->user_arg;
- return 0;
-}
-
-struct libcras_stream_cb_data *
-libcras_stream_cb_data_create(cras_stream_id_t stream_id,
- enum CRAS_STREAM_DIRECTION direction,
- uint8_t *buf, unsigned int frames,
- struct timespec sample_ts, void *user_arg)
-{
- struct libcras_stream_cb_data *data =
- (struct libcras_stream_cb_data *)calloc(
- 1, sizeof(struct libcras_stream_cb_data));
- if (!data) {
- syslog(LOG_ERR, "cras_client: calloc: %s", strerror(errno));
- return NULL;
- }
- data->data_ = (struct cras_stream_cb_data *)calloc(
- 1, sizeof(struct cras_stream_cb_data));
- if (!data->data_) {
- syslog(LOG_ERR, "cras_client: calloc: %s", strerror(errno));
- free(data);
- return NULL;
- }
- data->api_version = CRAS_API_VERSION;
- data->get_stream_id = stream_cb_get_stream_id;
- data->get_buf = stream_cb_get_buf;
- data->get_frames = stream_cb_get_frames;
- data->get_latency = stream_cb_get_latency;
- data->get_user_arg = stream_cb_get_user_arg;
- data->data_->stream_id = stream_id;
- data->data_->direction = direction;
- data->data_->buf = buf;
- data->data_->frames = frames;
- data->data_->sample_ts = sample_ts;
- data->data_->user_arg = user_arg;
- return data;
-}
-
-void libcras_stream_cb_data_destroy(struct libcras_stream_cb_data *data)
-{
- if (data)
- free(data->data_);
- free(data);
-}
-
-/*
- * Local Helpers
- */
-
-static int client_thread_rm_stream(struct cras_client *client,
- cras_stream_id_t stream_id);
-static int handle_message_from_server(struct cras_client *client);
-static int reregister_notifications(struct cras_client *client);
-
-static struct libcras_node_info *
-libcras_node_info_create(struct cras_iodev_info *iodev,
- struct cras_ionode_info *ionode);
-
-/*
- * Unlock the server_state_rwlock if lock_rc is 0.
- *
- * Args:
- * client - The CRAS client pointer.
- * lock_rc - The result of server_state_rdlock or
- * server_state_wrlock.
- */
-static void server_state_unlock(const struct cras_client *client, int lock_rc)
-{
- struct client_int *client_int;
-
- if (!client)
- return;
- client_int = to_client_int(client);
- if (lock_rc == 0)
- pthread_rwlock_unlock(&client_int->server_state_rwlock);
-}
-
-/*
- * Lock the server_state_rwlock for reading.
- *
- * Also checks that the server_state pointer is valid.
- *
- * Args:
- * client - The CRAS client pointer.
- * Returns:
- * 0 for success, positive error code on error.
- * Returns EINVAL if the server state pointer is NULL.
- */
-static int server_state_rdlock(const struct cras_client *client)
-{
- struct client_int *client_int;
- int lock_rc;
-
- if (!client)
- return EINVAL;
- client_int = to_client_int(client);
- lock_rc = pthread_rwlock_rdlock(&client_int->server_state_rwlock);
- if (lock_rc != 0)
- return lock_rc;
- if (!client->server_state) {
- pthread_rwlock_unlock(&client_int->server_state_rwlock);
- return EINVAL;
- }
- return 0;
-}
-
-/*
- * Lock the server_state_rwlock for writing.
- *
- * Args:
- * client - The CRAS client pointer.
- * Returns:
- * 0 for success, positive error code on error.
- */
-static int server_state_wrlock(const struct cras_client *client)
-{
- struct client_int *client_int;
-
- if (!client)
- return EINVAL;
- client_int = to_client_int(client);
- return pthread_rwlock_wrlock(&client_int->server_state_rwlock);
-}
-
-/* Get the stream pointer from a stream id. */
-static struct client_stream *stream_from_id(const struct cras_client *client,
- unsigned int id)
-{
- struct client_stream *out;
-
- DL_SEARCH_SCALAR(client->streams, out, id, id);
- return out;
-}
-
-/*
- * Fill a pollfd structure with the current server fd and events.
- */
-void server_fill_pollfd(const struct cras_client *client,
- struct pollfd *poll_fd)
-{
- int events = 0;
-
- poll_fd->fd = client->server_fd;
- switch (client->server_fd_state) {
- case CRAS_SOCKET_STATE_DISCONNECTED:
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
- case CRAS_SOCKET_STATE_FIRST_MESSAGE:
- case CRAS_SOCKET_STATE_CONNECTED:
- case CRAS_SOCKET_STATE_ERROR_DELAY:
- events = POLLIN;
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
- events = POLLOUT;
- break;
- }
- poll_fd->events = events;
- poll_fd->revents = 0;
-}
-
-/*
- * Change the server_fd_state.
- */
-static void server_fd_move_to_state(struct cras_client *client,
- cras_socket_state_t state)
-{
- if (state == client->server_fd_state)
- return;
-
- client->server_fd_state = state;
-}
-
-/*
- * Action to take when in state ERROR_DELAY.
- *
- * In this state we want to sleep for a few seconds before retrying the
- * connection to the audio server.
- *
- * If server_fd is negative: create a timer and setup server_fd with the
- * timer's fd. If server_fd is not negative and there is input, then assume
- * that the timer has expired, and restart the connection by moving to
- * WAIT_FOR_SOCKET state.
- */
-static int error_delay_next_action(struct cras_client *client, int poll_revents)
-{
- int rc;
- struct itimerspec timeout;
-
- if (client->server_fd == -1) {
- client->server_fd = timerfd_create(CLOCK_MONOTONIC,
- TFD_NONBLOCK | TFD_CLOEXEC);
- if (client->server_fd == -1) {
- rc = -errno;
- syslog(LOG_ERR,
- "cras_client: Could not create timerfd: %s",
- strerror(-rc));
- return rc;
- }
-
- /* Setup a relative timeout of 2 seconds. */
- memset(&timeout, 0, sizeof(timeout));
- timeout.it_value.tv_sec = 2;
- rc = timerfd_settime(client->server_fd, 0, &timeout, NULL);
- if (rc != 0) {
- rc = -errno;
- syslog(LOG_ERR,
- "cras_client: Could not set timeout: %s",
- strerror(-rc));
- return rc;
- }
- return 0;
- } else if ((poll_revents & POLLIN) == 0) {
- return 0;
- }
-
- /* Move to the next state: close the timer fd first. */
- close(client->server_fd);
- client->server_fd = -1;
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_WAIT_FOR_SOCKET);
- return 0;
-}
-
-/*
- * Action to take when in WAIT_FOR_SOCKET state.
- *
- * In this state we are waiting for the socket file to exist. The existence of
- * the socket file is continually monitored using the cras_file_wait structure
- * and a separate fd. When the sock_file_exists boolean is modified, the state
- * machine is invoked.
- *
- * If the socket file exists, then we move to the WAIT_FOR_WRITABLE state.
- */
-static void wait_for_socket_next_action(struct cras_client *client)
-{
- if (client->sock_file_exists)
- server_fd_move_to_state(client,
- CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE);
-}
-
-/*
- * Action to take when in WAIT_FOR_WRITABLE state.
- *
- * In this state we are initiating a connection the server and waiting for the
- * server to ready for incoming messages.
- *
- * Create the socket to the server, and wait while a connect request results in
- * -EINPROGRESS. Otherwise, we assume that the socket file will be deleted by
- * the server and the server_fd_state will be changed in
- * sock_file_wait_dispatch().
- */
-static int wait_for_writable_next_action(struct cras_client *client,
- int poll_revents)
-{
- int rc;
- struct sockaddr_un address;
-
- if (client->server_fd == -1) {
- client->server_fd = socket(PF_UNIX, SOCK_SEQPACKET, 0);
- if (client->server_fd < 0) {
- rc = -errno;
- syslog(LOG_ERR, "cras_client: server socket failed: %s",
- strerror(-rc));
- return rc;
- }
- } else if ((poll_revents & POLLOUT) == 0) {
- return 0;
- }
-
- /* We make the file descriptor non-blocking when we do connect(), so we
- * don't block indefinitely. */
- cras_make_fd_nonblocking(client->server_fd);
-
- memset(&address, 0, sizeof(struct sockaddr_un));
- address.sun_family = AF_UNIX;
- strcpy(address.sun_path, client->sock_file);
- rc = connect(client->server_fd, (struct sockaddr *)&address,
- sizeof(struct sockaddr_un));
- if (rc != 0) {
- rc = -errno;
- /* For -EINPROGRESS, we wait for POLLOUT on the server_fd.
- * Otherwise CRAS is not running and we assume that the socket
- * file will be deleted and recreated. Notification of that will
- * happen via the sock_file_wait_dispatch(). */
- if (rc == -ECONNREFUSED) {
- /* CRAS is not running, don't log this error and just
- * stay in this state waiting sock_file_wait_dispatch()
- * to move the state machine. */
- close(client->server_fd);
- client->server_fd = -1;
- } else if (rc != -EINPROGRESS) {
- syslog(LOG_ERR,
- "cras_client: server connect failed: %s",
- strerror(-rc));
- return rc;
- }
- return 0;
- }
-
- cras_make_fd_blocking(client->server_fd);
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_FIRST_MESSAGE);
- return 0;
-}
-
-/*
- * Action to take when transitioning to the CONNECTED state.
- */
-static int connect_transition_action(struct cras_client *client)
-{
- eventfd_t event_value;
- int rc;
-
- rc = reregister_notifications(client);
- if (rc < 0)
- return rc;
-
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_CONNECTED);
- /* Notify anyone waiting on this state change that we're
- * connected. */
- eventfd_read(client->server_event_fd, &event_value);
- eventfd_write(client->server_event_fd, 1);
- if (client->server_connection_cb)
- client->server_connection_cb(
- client, CRAS_CONN_STATUS_CONNECTED,
- client->server_connection_user_arg);
- return 0;
-}
-
-/*
- * Action to take when in the FIRST_MESSAGE state.
- *
- * We are waiting for the first message from the server. When our client ID has
- * been set, then we can move to the CONNECTED state.
- */
-static int first_message_next_action(struct cras_client *client,
- int poll_revents)
-{
- int rc;
-
- if (client->server_fd < 0)
- return -EINVAL;
-
- if ((poll_revents & POLLIN) == 0)
- return 0;
-
- rc = handle_message_from_server(client);
- if (rc < 0) {
- syslog(LOG_ERR, "handle first message: %s", strerror(-rc));
- } else if (client->id >= 0) {
- rc = connect_transition_action(client);
- } else {
- syslog(LOG_ERR, "did not get ID after first message!");
- rc = -EINVAL;
- }
- return rc;
-}
-
-/*
- * Play nice and shutdown the server socket.
- */
-static inline int shutdown_and_close_socket(int sockfd)
-{
- int rc;
- uint8_t buffer[CRAS_CLIENT_MAX_MSG_SIZE];
- struct timeval tv;
-
- tv.tv_sec = 0;
- tv.tv_usec = SERVER_SHUTDOWN_TIMEOUT_US;
- setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
-
- rc = shutdown(sockfd, SHUT_WR);
- if (rc < 0)
- return rc;
- /* Wait until the socket is closed by the peer. */
- for (;;) {
- rc = recv(sockfd, buffer, sizeof(buffer), 0);
- if (rc <= 0)
- break;
- }
- return close(sockfd);
-}
-
-/*
- * Action to take when disconnecting from the server.
- *
- * Clean up the server socket, and the server_state pointer. Move to the next
- * logical state.
- */
-static void disconnect_transition_action(struct cras_client *client, bool force)
-{
- eventfd_t event_value;
- cras_socket_state_t old_state = client->server_fd_state;
- struct client_stream *s;
- int lock_rc;
-
- /* Stop all playing streams.
- * TODO(muirj): Pause and resume streams. */
- DL_FOREACH (client->streams, s) {
- s->config->err_cb(client, s->id, -ENOTCONN,
- s->config->user_data);
- client_thread_rm_stream(client, s->id);
- }
-
- /* Clean up the server_state pointer. */
- lock_rc = server_state_wrlock(client);
- if (client->server_state) {
- munmap((void *)client->server_state,
- sizeof(*client->server_state));
- client->server_state = NULL;
- }
- server_state_unlock(client, lock_rc);
-
- /* Our ID is unknown now. */
- client->id = -1;
-
- /* Clean up the server fd. */
- if (client->server_fd >= 0) {
- if (!force)
- shutdown_and_close_socket(client->server_fd);
- else
- close(client->server_fd);
- client->server_fd = -1;
- }
-
- /* Reset the server_event_fd value to 0 (and cause subsequent threads
- * waiting on the connection to wait). */
- eventfd_read(client->server_event_fd, &event_value);
-
- switch (old_state) {
- case CRAS_SOCKET_STATE_DISCONNECTED:
- /* Do nothing: already disconnected. */
- break;
- case CRAS_SOCKET_STATE_ERROR_DELAY:
- /* We're disconnected and there was a failure to setup
- * automatic reconnection, so call the server error
- * callback now. */
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_DISCONNECTED);
- if (client->server_connection_cb)
- client->server_connection_cb(
- client, CRAS_CONN_STATUS_FAILED,
- client->server_connection_user_arg);
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
- case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
- case CRAS_SOCKET_STATE_FIRST_MESSAGE:
- /* We are running this state transition while a connection is
- * in progress for an error case. When there is no error, we
- * come into this function in the DISCONNECTED state. */
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_ERROR_DELAY);
- break;
- case CRAS_SOCKET_STATE_CONNECTED:
- /* Disconnected from CRAS (for an error), wait for the socket
- * file to be (re)created. */
- server_fd_move_to_state(client,
- CRAS_SOCKET_STATE_WAIT_FOR_SOCKET);
- /* Notify the caller that we aren't connected anymore. */
- if (client->server_connection_cb)
- client->server_connection_cb(
- client, CRAS_CONN_STATUS_DISCONNECTED,
- client->server_connection_user_arg);
- break;
- }
-}
-
-static int server_fd_dispatch(struct cras_client *client, int poll_revents)
-{
- int rc = 0;
- cras_socket_state_t old_state;
-
- if ((poll_revents & POLLHUP) != 0) {
- /* Error or disconnect: cleanup and make a state change now. */
- disconnect_transition_action(client, true);
- }
- old_state = client->server_fd_state;
-
- switch (client->server_fd_state) {
- case CRAS_SOCKET_STATE_DISCONNECTED:
- /* Assume that we've taken the necessary actions. */
- return -ENOTCONN;
- case CRAS_SOCKET_STATE_ERROR_DELAY:
- rc = error_delay_next_action(client, poll_revents);
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
- wait_for_socket_next_action(client);
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
- rc = wait_for_writable_next_action(client, poll_revents);
- break;
- case CRAS_SOCKET_STATE_FIRST_MESSAGE:
- rc = first_message_next_action(client, poll_revents);
- break;
- case CRAS_SOCKET_STATE_CONNECTED:
- if ((poll_revents & POLLIN) != 0)
- rc = handle_message_from_server(client);
- break;
- }
-
- if (rc != 0) {
- /* If there is an error, then start-over. */
- rc = server_fd_dispatch(client, POLLHUP);
- } else if (old_state != client->server_fd_state) {
- /* There was a state change, process the new state now. */
- rc = server_fd_dispatch(client, 0);
- }
- return rc;
-}
-
-/*
- * Start connecting to the server if we aren't already.
- */
-static int server_connect(struct cras_client *client)
-{
- if (client->server_fd_state != CRAS_SOCKET_STATE_DISCONNECTED)
- return 0;
- /* Start waiting for the server socket to exist. */
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_WAIT_FOR_SOCKET);
- return server_fd_dispatch(client, 0);
-}
-
-/*
- * Disconnect from the server if we haven't already.
- */
-static void server_disconnect(struct cras_client *client)
-{
- if (client->server_fd_state == CRAS_SOCKET_STATE_DISCONNECTED)
- return;
- /* Set the disconnected state first so that the disconnect
- * transition doesn't move the server state to ERROR_DELAY. */
- server_fd_move_to_state(client, CRAS_SOCKET_STATE_DISCONNECTED);
- disconnect_transition_action(client, false);
-}
-
-/*
- * Called when something happens to the socket file.
- */
-static void sock_file_wait_callback(void *context, cras_file_wait_event_t event,
- const char *filename)
-{
- struct cras_client *client = (struct cras_client *)context;
- switch (event) {
- case CRAS_FILE_WAIT_EVENT_CREATED:
- client->sock_file_exists = 1;
- switch (client->server_fd_state) {
- case CRAS_SOCKET_STATE_DISCONNECTED:
- case CRAS_SOCKET_STATE_ERROR_DELAY:
- case CRAS_SOCKET_STATE_FIRST_MESSAGE:
- case CRAS_SOCKET_STATE_CONNECTED:
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
- case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
- /* The socket file exists. Tell the server state
- * machine. */
- server_fd_dispatch(client, 0);
- break;
- }
- break;
- case CRAS_FILE_WAIT_EVENT_DELETED:
- client->sock_file_exists = 0;
- switch (client->server_fd_state) {
- case CRAS_SOCKET_STATE_DISCONNECTED:
- break;
- case CRAS_SOCKET_STATE_WAIT_FOR_SOCKET:
- case CRAS_SOCKET_STATE_WAIT_FOR_WRITABLE:
- case CRAS_SOCKET_STATE_ERROR_DELAY:
- case CRAS_SOCKET_STATE_FIRST_MESSAGE:
- case CRAS_SOCKET_STATE_CONNECTED:
- /* Restart the connection process. */
- server_disconnect(client);
- server_connect(client);
- break;
- }
- break;
- case CRAS_FILE_WAIT_EVENT_NONE:
- break;
- }
-}
-
-/*
- * Service the sock_file_wait's fd.
- *
- * If the socket file is deleted, then cause a disconnect from the server.
- * Otherwise, start a reconnect depending on the server_fd_state.
- */
-static int sock_file_wait_dispatch(struct cras_client *client, int poll_revents)
-{
- int rc;
-
- if ((poll_revents & POLLIN) == 0)
- return 0;
-
- rc = cras_file_wait_dispatch(client->sock_file_wait);
- if (rc == -EAGAIN || rc == -EWOULDBLOCK)
- rc = 0;
- else if (rc != 0)
- syslog(LOG_ERR, "cras_file_wait_dispatch: %s", strerror(-rc));
- return rc;
-}
-
-/*
- * Waits until we have heard back from the server so that we know we are
- * connected.
- *
- * The connected success/failure message is always the first message the server
- * sends. Return non zero if client is connected to the server. A return code
- * of zero means that the client is not connected to the server.
- */
-static int check_server_connected_wait(struct cras_client *client,
- struct timespec *timeout)
-{
- int rc = 0;
- struct pollfd poll_fd;
-
- poll_fd.fd = client->server_event_fd;
- poll_fd.events = POLLIN;
- poll_fd.revents = 0;
-
- /* The server_event_fd is only read and written by the functions
- * that connect to the server. When a connection is established the
- * eventfd has a value of 1 and cras_poll will return immediately
- * with 1. When there is no connection to the server, then this
- * function waits until the timeout has expired or a non-zero value
- * is written to the server_event_fd. */
- while (rc == 0)
- rc = cras_poll(&poll_fd, 1, timeout, NULL);
- return rc > 0;
-}
-
-/* Returns non-zero if the thread is running (not stopped). */
-static inline int thread_is_running(struct thread_state *thread)
-{
- return thread->state != CRAS_THREAD_STOP;
-}
-
-/*
- * Opens the server socket and connects to it.
- * Args:
- * client - Client pointer created with cras_client_create().
- * timeout - Connection timeout.
- * Returns:
- * 0 for success, negative error code on failure.
- */
-static int connect_to_server(struct cras_client *client,
- struct timespec *timeout, bool use_command_thread)
-{
- int rc;
- struct pollfd poll_fd[2];
- struct timespec connected_timeout;
-
- if (!client)
- return -EINVAL;
-
- if (thread_is_running(&client->thread) && use_command_thread) {
- rc = cras_client_connect_async(client);
- if (rc == 0) {
- rc = check_server_connected_wait(client, timeout);
- return rc ? 0 : -ESHUTDOWN;
- }
- }
-
- connected_timeout.tv_sec = 0;
- connected_timeout.tv_nsec = 0;
- if (check_server_connected_wait(client, &connected_timeout))
- return 0;
-
- poll_fd[0].fd = cras_file_wait_get_fd(client->sock_file_wait);
- poll_fd[0].events = POLLIN;
-
- rc = server_connect(client);
- while (rc == 0) {
- // Wait until we've connected or until there is a timeout.
- // Meanwhile handle incoming actions on our fds.
-
- server_fill_pollfd(client, &(poll_fd[1]));
- rc = cras_poll(poll_fd, 2, timeout, NULL);
- if (rc <= 0)
- continue;
-
- if (poll_fd[0].revents) {
- rc = sock_file_wait_dispatch(client,
- poll_fd[0].revents);
- continue;
- }
-
- if (poll_fd[1].revents) {
- rc = server_fd_dispatch(client, poll_fd[1].revents);
- if (rc == 0 && client->server_fd_state ==
- CRAS_SOCKET_STATE_CONNECTED)
- break;
- }
- }
-
- if (rc != 0)
- syslog(LOG_ERR, "cras_client: Connect server failed: %s",
- strerror(-rc));
-
- return rc;
-}
-
-static int connect_to_server_wait_retry(struct cras_client *client,
- int timeout_ms, bool use_command_thread)
-{
- struct timespec timeout_value;
- struct timespec *timeout;
-
- if (timeout_ms < 0) {
- timeout = NULL;
- } else {
- timeout = &timeout_value;
- ms_to_timespec(timeout_ms, timeout);
- }
-
- /* If connected, wait for the first message from the server
- * indicating it's ready. */
- return connect_to_server(client, timeout, use_command_thread);
-}
-
-/*
- * Tries to connect to the server. Waits for the initial message from the
- * server. This will happen near instantaneously if the server is already
- * running.
- */
-static int connect_to_server_wait(struct cras_client *client,
- bool use_command_thread)
-{
- return connect_to_server_wait_retry(client, SERVER_CONNECT_TIMEOUT_MS,
- use_command_thread);
-}
-
-/*
- * Audio thread.
- */
-
-/* Sends a message from the stream to the client to indicate an error.
- * If the running stream encounters an error, then it must tell the client
- * to stop running it.
- */
-static int send_stream_message(const struct client_stream *stream,
- unsigned msg_id)
-{
- int res;
- struct stream_msg msg;
-
- msg.stream_id = stream->id;
- msg.msg_id = msg_id;
- res = write(stream->client->stream_fds[1], &msg, sizeof(msg));
- if (res != sizeof(msg))
- return -EPIPE;
-
- return 0;
-}
-
-/* Blocks until there is data to be read from the read_fd or until woken by an
- * incoming "poke" on wake_fd. Up to "len" bytes are read into "buf". */
-static int read_with_wake_fd(int wake_fd, int read_fd, uint8_t *buf, size_t len)
-{
- struct pollfd pollfds[2];
- int nread = 0;
- int nfds = 1;
- int rc;
- char tmp;
-
- pollfds[0].fd = wake_fd;
- pollfds[0].events = POLLIN;
- if (read_fd >= 0) {
- nfds++;
- pollfds[1].fd = read_fd;
- pollfds[1].events = POLLIN;
- }
-
- rc = poll(pollfds, nfds, -1);
- if (rc < 0)
- return rc;
- if (read_fd >= 0 && pollfds[1].revents & POLLIN) {
- nread = read(read_fd, buf, len);
- if (nread != (int)len)
- return -EIO;
- }
- if (pollfds[0].revents & POLLIN) {
- rc = read(wake_fd, &tmp, 1);
- if (rc < 0)
- return rc;
- }
-
- return nread;
-}
-/* Check the availability and configures a capture buffer.
- * Args:
- * stream - The input stream to configure buffer for.
- * captured_frames - To be filled with the pointer to the beginning of
- * captured buffer.
- * num_frames - Number of captured frames.
- * Returns:
- * Number of frames available in captured_frames.
- */
-static unsigned int config_capture_buf(struct client_stream *stream,
- uint8_t **captured_frames,
- unsigned int num_frames)
-{
- /* Always return the beginning of the read buffer because Chrome expects
- * so. */
- *captured_frames = cras_shm_get_read_buffer_base(stream->shm);
-
- /* Don't ask for more frames than the client desires. */
- if (stream->flags & BULK_AUDIO_OK)
- num_frames = MIN(num_frames, stream->config->buffer_frames);
- else
- num_frames = MIN(num_frames, stream->config->cb_threshold);
-
- /* If shm readable frames is less than client requests, that means
- * overrun has happened in server side. Don't send partial corrupted
- * buffer to client. */
- if (cras_shm_get_curr_read_frames(stream->shm) < num_frames)
- return 0;
-
- return num_frames;
-}
-
-static void complete_capture_read_current(struct client_stream *stream,
- unsigned int num_frames)
-{
- cras_shm_buffer_read_current(stream->shm, num_frames);
-}
-
-static int send_capture_reply(struct client_stream *stream, unsigned int frames,
- int err)
-{
- struct audio_message aud_msg;
- int rc;
-
- if (!cras_stream_uses_input_hw(stream->direction))
- return 0;
-
- aud_msg.id = AUDIO_MESSAGE_DATA_CAPTURED;
- aud_msg.frames = frames;
- aud_msg.error = err;
-
- rc = write(stream->aud_fd, &aud_msg, sizeof(aud_msg));
- if (rc != sizeof(aud_msg))
- return -EPIPE;
-
- return 0;
-}
-
-/* For capture streams this handles the message signalling that data is ready to
- * be passed to the user of this stream. Calls the audio callback with the new
- * samples, and mark them as read.
- * Args:
- * stream - The stream the message was received for.
- * num_frames - The number of captured frames.
- * Returns:
- * 0, unless there is a fatal error or the client declares enod of file.
- */
-static int handle_capture_data_ready(struct client_stream *stream,
- unsigned int num_frames)
-{
- int frames;
- struct cras_stream_params *config;
- uint8_t *captured_frames;
- struct timespec ts;
- int rc = 0;
- struct libcras_stream_cb_data *data;
-
- config = stream->config;
- /* If this message is for an output stream, log error and drop it. */
- if (!cras_stream_has_input(stream->direction)) {
- syslog(LOG_ERR, "cras_client: Play data to input\n");
- return 0;
- }
-
- num_frames = config_capture_buf(stream, &captured_frames, num_frames);
- if (num_frames == 0)
- return 0;
-
- cras_timespec_to_timespec(&ts, &stream->shm->header->ts);
-
- if (config->stream_cb) {
- data = libcras_stream_cb_data_create(
- stream->id, stream->direction, captured_frames,
- num_frames, ts, config->user_data);
- if (!data)
- return -errno;
- frames = config->stream_cb(data);
- libcras_stream_cb_data_destroy(data);
- data = NULL;
- } else if (config->unified_cb) {
- frames = config->unified_cb(stream->client, stream->id,
- captured_frames, NULL, num_frames,
- &ts, NULL, config->user_data);
- } else {
- frames = config->aud_cb(stream->client, stream->id,
- captured_frames, num_frames, &ts,
- config->user_data);
- }
- if (frames < 0) {
- send_stream_message(stream, CLIENT_STREAM_EOF);
- rc = frames;
- goto reply_captured;
- }
- if (frames == 0)
- return 0;
-
- complete_capture_read_current(stream, frames);
-reply_captured:
- return send_capture_reply(stream, frames, rc);
-}
-
-/* Notifies the server that "frames" samples have been written. */
-static int send_playback_reply(struct client_stream *stream,
- unsigned int frames, int error)
-{
- struct audio_message aud_msg;
- int rc;
-
- if (!cras_stream_uses_output_hw(stream->direction))
- return 0;
-
- aud_msg.id = AUDIO_MESSAGE_DATA_READY;
- aud_msg.frames = frames;
- aud_msg.error = error;
-
- rc = write(stream->aud_fd, &aud_msg, sizeof(aud_msg));
- if (rc != sizeof(aud_msg))
- return -EPIPE;
-
- return 0;
-}
-
-/* For playback streams when current buffer is empty, this handles the request
- * for more samples by calling the audio callback for the thread, and signaling
- * the server that the samples have been written. */
-static int handle_playback_request(struct client_stream *stream,
- unsigned int num_frames)
-{
- uint8_t *buf;
- int frames;
- int rc = 0;
- struct cras_stream_params *config;
- struct cras_audio_shm *shm = stream->shm;
- struct timespec ts;
- struct libcras_stream_cb_data *data;
-
- config = stream->config;
-
- /* If this message is for an input stream, log error and drop it. */
- if (stream->direction != CRAS_STREAM_OUTPUT) {
- syslog(LOG_ERR, "cras_client: Record data from output\n");
- return 0;
- }
-
- buf = cras_shm_get_write_buffer_base(shm);
-
- /* Limit the amount of frames to the configured amount. */
- num_frames = MIN(num_frames, config->cb_threshold);
-
- cras_timespec_to_timespec(&ts, &shm->header->ts);
-
- /* Get samples from the user */
- if (config->stream_cb) {
- data = libcras_stream_cb_data_create(stream->id,
- stream->direction, buf,
- num_frames, ts,
- config->user_data);
- if (!data)
- return -errno;
- frames = config->stream_cb(data);
- libcras_stream_cb_data_destroy(data);
- data = NULL;
- } else if (config->unified_cb) {
- frames = config->unified_cb(stream->client, stream->id, NULL,
- buf, num_frames, NULL, &ts,
- config->user_data);
- } else {
- frames = config->aud_cb(stream->client, stream->id, buf,
- num_frames, &ts, config->user_data);
- }
- if (frames < 0) {
- send_stream_message(stream, CLIENT_STREAM_EOF);
- rc = frames;
- goto reply_written;
- }
-
- cras_shm_buffer_written_start(shm, frames);
-
-reply_written:
- /* Signal server that data is ready, or that an error has occurred. */
- rc = send_playback_reply(stream, frames, rc);
- return rc;
-}
-
-static void audio_thread_set_priority(struct client_stream *stream)
-{
- /* Use provided callback to set priority if available. */
- if (stream->client->thread_priority_cb) {
- stream->client->thread_priority_cb(stream->client);
- return;
- }
-
- /* Try to get RT scheduling, if that fails try to set the nice value. */
- if (cras_set_rt_scheduling(CRAS_CLIENT_RT_THREAD_PRIORITY) ||
- cras_set_thread_priority(CRAS_CLIENT_RT_THREAD_PRIORITY))
- cras_set_nice_level(CRAS_CLIENT_NICENESS_LEVEL);
-}
-
-/* Listens to the audio socket for messages from the server indicating that
- * the stream needs to be serviced. One of these runs per stream. */
-static void *audio_thread(void *arg)
-{
- struct client_stream *stream = (struct client_stream *)arg;
- int thread_terminated = 0;
- struct audio_message aud_msg;
- int aud_fd;
- int num_read;
-
- if (arg == NULL)
- return (void *)-EIO;
-
- audio_thread_set_priority(stream);
-
- /* Notify the control thread that we've started. */
- pthread_mutex_lock(&stream->client->stream_start_lock);
- pthread_cond_broadcast(&stream->client->stream_start_cond);
- pthread_mutex_unlock(&stream->client->stream_start_lock);
-
- while (thread_is_running(&stream->thread) && !thread_terminated) {
- /* While we are warming up, aud_fd may not be valid and some
- * shared memory resources may not yet be available. */
- aud_fd = (stream->thread.state == CRAS_THREAD_WARMUP) ?
- -1 :
- stream->aud_fd;
- num_read =
- read_with_wake_fd(stream->wake_fds[0], aud_fd,
- (uint8_t *)&aud_msg, sizeof(aud_msg));
- if (num_read < 0)
- return (void *)-EIO;
- if (num_read == 0)
- continue;
-
- switch (aud_msg.id) {
- case AUDIO_MESSAGE_DATA_READY:
- thread_terminated = handle_capture_data_ready(
- stream, aud_msg.frames);
- break;
- case AUDIO_MESSAGE_REQUEST_DATA:
- thread_terminated =
- handle_playback_request(stream, aud_msg.frames);
- break;
- default:
- break;
- }
- }
-
- return NULL;
-}
-
-/* Pokes the audio thread so that it can notice if it has been terminated. */
-static int wake_aud_thread(struct client_stream *stream)
-{
- int rc;
-
- rc = write(stream->wake_fds[1], &rc, 1);
- if (rc != 1)
- return rc;
- return 0;
-}
-
-/* Stop the audio thread for the given stream.
- * Args:
- * stream - Stream for which to stop the audio thread.
- * join - When non-zero, attempt to join the audio thread (wait for it to
- * complete).
- */
-static void stop_aud_thread(struct client_stream *stream, int join)
-{
- if (thread_is_running(&stream->thread)) {
- stream->thread.state = CRAS_THREAD_STOP;
- wake_aud_thread(stream);
- if (join)
- pthread_join(stream->thread.tid, NULL);
- }
-
- if (stream->wake_fds[0] >= 0) {
- close(stream->wake_fds[0]);
- close(stream->wake_fds[1]);
- stream->wake_fds[0] = -1;
- }
-}
-
-/* Start the audio thread for this stream.
- * Returns when the thread has started and is waiting.
- * Args:
- * stream - The stream that needs an audio thread.
- * Returns:
- * 0 for success, or a negative error code.
- */
-static int start_aud_thread(struct client_stream *stream)
-{
- int rc;
- struct timespec future;
-
- rc = pipe(stream->wake_fds);
- if (rc < 0) {
- rc = -errno;
- syslog(LOG_ERR, "cras_client: pipe: %s", strerror(-rc));
- return rc;
- }
-
- stream->thread.state = CRAS_THREAD_WARMUP;
-
- pthread_mutex_lock(&stream->client->stream_start_lock);
- rc = pthread_create(&stream->thread.tid, NULL, audio_thread, stream);
- if (rc) {
- pthread_mutex_unlock(&stream->client->stream_start_lock);
- syslog(LOG_ERR, "cras_client: Couldn't create audio stream: %s",
- strerror(rc));
- stream->thread.state = CRAS_THREAD_STOP;
- stop_aud_thread(stream, 0);
- return -rc;
- }
-
- clock_gettime(CLOCK_REALTIME, &future);
- future.tv_sec += 2; /* Wait up to two seconds. */
- rc = pthread_cond_timedwait(&stream->client->stream_start_cond,
- &stream->client->stream_start_lock,
- &future);
- pthread_mutex_unlock(&stream->client->stream_start_lock);
- if (rc != 0) {
- /* Something is very wrong: try to cancel the thread and don't
- * wait for it. */
- syslog(LOG_ERR, "cras_client: Client thread not responding: %s",
- strerror(rc));
- stop_aud_thread(stream, 0);
- return -rc;
- }
- return 0;
-}
-
-/*
- * Client thread.
- */
-
-/* Gets the update_count of the server state shm region. */
-static inline unsigned
-begin_server_state_read(const struct cras_server_state *state)
-{
- unsigned count;
-
- /* Version will be odd when the server is writing. */
- while ((count = *(volatile unsigned *)&state->update_count) & 1)
- sched_yield();
- __sync_synchronize();
- return count;
-}
-
-/* Checks if the update count of the server state shm region has changed from
- * count. Returns 0 if the count still matches.
- */
-static inline int end_server_state_read(const struct cras_server_state *state,
- unsigned count)
-{
- __sync_synchronize();
- if (count != *(volatile unsigned *)&state->update_count)
- return -EAGAIN;
- return 0;
-}
-
-/* Release shm areas if references to them are held. */
-static void free_shm(struct client_stream *stream)
-{
- cras_audio_shm_destroy(stream->shm);
- stream->shm = NULL;
-}
-
-/* Handles the stream connected message from the server. Check if we need a
- * format converter, configure the shared memory region, and start the audio
- * thread that will handle requests from the server. */
-static int stream_connected(struct client_stream *stream,
- const struct cras_client_stream_connected *msg,
- const int stream_fds[2], const unsigned int num_fds)
-{
- int rc, samples_prot;
- unsigned int i;
- struct cras_shm_info header_info, samples_info;
-
- if (msg->err || num_fds != 2) {
- syslog(LOG_ERR, "cras_client: Error setting up stream %d\n",
- msg->err);
- rc = msg->err;
- goto err_ret;
- }
-
- rc = cras_shm_info_init_with_fd(stream_fds[0], cras_shm_header_size(),
- &header_info);
- if (rc < 0)
- goto err_ret;
-
- rc = cras_shm_info_init_with_fd(stream_fds[1], msg->samples_shm_size,
- &samples_info);
- if (rc < 0) {
- cras_shm_info_cleanup(&header_info);
- goto err_ret;
- }
-
- if (stream->direction == CRAS_STREAM_OUTPUT)
- samples_prot = PROT_WRITE;
- else
- samples_prot = PROT_READ;
-
- rc = cras_audio_shm_create(&header_info, &samples_info, samples_prot,
- &stream->shm);
- if (rc < 0) {
- syslog(LOG_ERR, "cras_client: Error configuring shm");
- goto err_ret;
- }
- cras_shm_copy_shared_config(stream->shm);
- cras_shm_set_volume_scaler(stream->shm, stream->volume_scaler);
-
- stream->thread.state = CRAS_THREAD_RUNNING;
- wake_aud_thread(stream);
-
- close(stream_fds[0]);
- close(stream_fds[1]);
- return 0;
-err_ret:
- stop_aud_thread(stream, 1);
- for (i = 0; i < num_fds; i++)
- close(stream_fds[i]);
- free_shm(stream);
- return rc;
-}
-
-static int send_connect_message(struct cras_client *client,
- struct client_stream *stream, uint32_t dev_idx)
-{
- int rc;
- struct cras_connect_message serv_msg;
- int sock[2] = { -1, -1 };
-
- /* Create a socket pair for the server to notify of audio events. */
- rc = socketpair(AF_UNIX, SOCK_STREAM, 0, sock);
- if (rc != 0) {
- rc = -errno;
- syslog(LOG_ERR, "cras_client: socketpair: %s", strerror(-rc));
- goto fail;
- }
-
- cras_fill_connect_message(&serv_msg, stream->config->direction,
- stream->id, stream->config->stream_type,
- stream->config->client_type,
- stream->config->buffer_frames,
- stream->config->cb_threshold, stream->flags,
- stream->config->effects,
- stream->config->format, dev_idx);
-
- rc = cras_send_with_fds(client->server_fd, &serv_msg, sizeof(serv_msg),
- &sock[1], 1);
- if (rc != sizeof(serv_msg)) {
- rc = EIO;
- syslog(LOG_ERR,
- "cras_client: add_stream: Send server message failed.");
- goto fail;
- }
-
- stream->aud_fd = sock[0];
- close(sock[1]);
- return 0;
-
-fail:
- if (sock[0] != -1)
- close(sock[0]);
- if (sock[1] != -1)
- close(sock[1]);
- return rc;
-}
-
-/* Adds a stream to a running client. Checks to make sure that the client is
- * attached, waits if it isn't. The stream is prepared on the main thread and
- * passed here. */
-static int client_thread_add_stream(struct cras_client *client,
- struct client_stream *stream,
- cras_stream_id_t *stream_id_out,
- uint32_t dev_idx)
-{
- int rc;
- cras_stream_id_t new_id;
- struct client_stream *out;
-
- if ((stream->flags & HOTWORD_STREAM) == HOTWORD_STREAM) {
- int hotword_idx;
- hotword_idx = cras_client_get_first_dev_type_idx(
- client, CRAS_NODE_TYPE_HOTWORD, CRAS_STREAM_INPUT);
-
- /* Find the hotword device index. */
- if (dev_idx == NO_DEVICE) {
- if (hotword_idx < 0) {
- syslog(LOG_ERR,
- "cras_client: add_stream: No hotword dev");
- return hotword_idx;
- } else {
- dev_idx = (uint32_t)hotword_idx;
- }
- }
- /* A known Use case for client to pin hotword stream on a not
- * hotword device is to use internal mic for Assistant to work
- * on board without usable DSP hotwording. We assume there will
- * be only one hotword device exists. */
- else if (dev_idx != (uint32_t)hotword_idx) {
- /* Unmask the flag to fallback to normal pinned stream
- * on specified device. */
- stream->flags &= ~HOTWORD_STREAM;
- }
- }
-
- /* Find an available stream id. */
- do {
- new_id = cras_get_stream_id(client->id, client->next_stream_id);
- client->next_stream_id++;
- DL_SEARCH_SCALAR(client->streams, out, id, new_id);
- } while (out != NULL);
-
- stream->id = new_id;
- *stream_id_out = new_id;
- stream->client = client;
-
- /* Start the audio thread. */
- rc = start_aud_thread(stream);
- if (rc != 0)
- return rc;
-
- /* Start the thread associated with this stream. */
- /* send a message to the server asking that the stream be started. */
- rc = send_connect_message(client, stream, dev_idx);
- if (rc != 0) {
- stop_aud_thread(stream, 1);
- return rc;
- }
-
- /* Add the stream to the linked list */
- DL_APPEND(client->streams, stream);
-
- return 0;
-}
-
-/* Removes a stream from a running client from within the running client's
- * context. */
-static int client_thread_rm_stream(struct cras_client *client,
- cras_stream_id_t stream_id)
-{
- struct cras_disconnect_stream_message msg;
- struct client_stream *stream = stream_from_id(client, stream_id);
- int rc;
-
- if (stream == NULL)
- return 0;
-
- /* Tell server to remove. */
- if (client->server_fd_state == CRAS_SOCKET_STATE_CONNECTED) {
- cras_fill_disconnect_stream_message(&msg, stream_id);
- rc = write(client->server_fd, &msg, sizeof(msg));
- if (rc < 0)
- syslog(LOG_ERR,
- "cras_client: error removing stream from server\n");
- }
-
- /* And shut down locally. */
- stop_aud_thread(stream, 1);
-
- free_shm(stream);
-
- DL_DELETE(client->streams, stream);
- if (stream->aud_fd >= 0)
- close(stream->aud_fd);
-
- free(stream->config);
- free(stream);
-
- return 0;
-}
-
-/* Sets the volume scaling factor for a playback or capture stream. */
-static int client_thread_set_stream_volume(struct cras_client *client,
- cras_stream_id_t stream_id,
- float volume_scaler)
-{
- struct client_stream *stream;
-
- stream = stream_from_id(client, stream_id);
- if (stream == NULL || volume_scaler > 1.0 || volume_scaler < 0.0)
- return -EINVAL;
-
- stream->volume_scaler = volume_scaler;
- if (stream->shm)
- cras_shm_set_volume_scaler(stream->shm, volume_scaler);
-
- return 0;
-}
-
-/* Attach to the shm region containing the audio thread log. */
-static void attach_atlog_shm(struct cras_client *client, int fd)
-{
- client->atlog_ro = (struct audio_thread_event_log *)mmap(
- NULL, sizeof(*client->atlog_ro), PROT_READ, MAP_SHARED, fd, 0);
- close(fd);
-}
-
-/* Attach to the shm region containing the server state. */
-static int client_attach_shm(struct cras_client *client, int shm_fd)
-{
- int lock_rc;
- int rc;
-
- lock_rc = server_state_wrlock(client);
- if (client->server_state) {
- rc = -EBUSY;
- goto error;
- }
-
- client->server_state = (struct cras_server_state *)mmap(
- NULL, sizeof(*client->server_state), PROT_READ, MAP_SHARED,
- shm_fd, 0);
- rc = -errno;
- close(shm_fd);
- if (client->server_state == (struct cras_server_state *)-1) {
- syslog(LOG_ERR,
- "cras_client: mmap failed to map shm for client: %s",
- strerror(-rc));
- goto error;
- }
-
- if (client->server_state->state_version != CRAS_SERVER_STATE_VERSION) {
- munmap((void *)client->server_state,
- sizeof(*client->server_state));
- client->server_state = NULL;
- rc = -EINVAL;
- syslog(LOG_ERR, "cras_client: Unknown server_state version.");
- } else {
- rc = 0;
- }
-
-error:
- server_state_unlock(client, lock_rc);
- return rc;
-}
-
-static void cras_client_get_hotword_models_ready(struct cras_client *client,
- const char *hotword_models)
-{
- if (!client->get_hotword_models_cb)
- return;
- client->get_hotword_models_cb(client, hotword_models);
- client->get_hotword_models_cb = NULL;
-}
-
-/* Handles messages from the cras server. */
-static int handle_message_from_server(struct cras_client *client)
-{
- uint8_t buf[CRAS_CLIENT_MAX_MSG_SIZE];
- struct cras_client_message *msg;
- int rc = 0;
- int nread;
- int server_fds[2];
- unsigned int num_fds = 2;
-
- msg = (struct cras_client_message *)buf;
- nread = cras_recv_with_fds(client->server_fd, buf, sizeof(buf),
- server_fds, &num_fds);
- if (nread < (int)sizeof(msg->length) || (int)msg->length != nread)
- return -EIO;
-
- switch (msg->id) {
- case CRAS_CLIENT_CONNECTED: {
- struct cras_client_connected *cmsg =
- (struct cras_client_connected *)msg;
- if (num_fds != 1)
- return -EINVAL;
- rc = client_attach_shm(client, server_fds[0]);
- if (rc)
- return rc;
- client->id = cmsg->client_id;
-
- break;
- }
- case CRAS_CLIENT_STREAM_CONNECTED: {
- struct cras_client_stream_connected *cmsg =
- (struct cras_client_stream_connected *)msg;
- struct client_stream *stream =
- stream_from_id(client, cmsg->stream_id);
- if (stream == NULL) {
- if (num_fds != 2) {
- syslog(LOG_ERR,
- "cras_client: Error receiving "
- "stream 0x%x connected message",
- cmsg->stream_id);
- return -EINVAL;
- }
-
- /*
- * Usually, the fds should be closed in stream_connected
- * callback. However, sometimes a stream is removed
- * before it is connected.
- */
- close(server_fds[0]);
- close(server_fds[1]);
- break;
- }
- rc = stream_connected(stream, cmsg, server_fds, num_fds);
- if (rc < 0)
- stream->config->err_cb(stream->client, stream->id, rc,
- stream->config->user_data);
- break;
- }
- case CRAS_CLIENT_AUDIO_DEBUG_INFO_READY:
- if (client->debug_info_callback)
- client->debug_info_callback(client);
- client->debug_info_callback = NULL;
- break;
- case CRAS_CLIENT_ATLOG_FD_READY:
- if (num_fds != 1 || server_fds[0] < 0)
- return -EINVAL;
- attach_atlog_shm(client, server_fds[0]);
- if (client->atlog_access_callback)
- client->atlog_access_callback(client);
- client->atlog_access_callback = NULL;
- break;
- case CRAS_CLIENT_GET_HOTWORD_MODELS_READY: {
- struct cras_client_get_hotword_models_ready *cmsg =
- (struct cras_client_get_hotword_models_ready *)msg;
- cras_client_get_hotword_models_ready(
- client, (const char *)cmsg->hotword_models);
- break;
- }
- case CRAS_CLIENT_OUTPUT_VOLUME_CHANGED: {
- struct cras_client_volume_changed *cmsg =
- (struct cras_client_volume_changed *)msg;
- if (client->observer_ops.output_volume_changed)
- client->observer_ops.output_volume_changed(
- client->observer_context, cmsg->volume);
- break;
- }
- case CRAS_CLIENT_OUTPUT_MUTE_CHANGED: {
- struct cras_client_mute_changed *cmsg =
- (struct cras_client_mute_changed *)msg;
- if (client->observer_ops.output_mute_changed)
- client->observer_ops.output_mute_changed(
- client->observer_context, cmsg->muted,
- cmsg->user_muted, cmsg->mute_locked);
- break;
- }
- case CRAS_CLIENT_CAPTURE_GAIN_CHANGED: {
- struct cras_client_volume_changed *cmsg =
- (struct cras_client_volume_changed *)msg;
- if (client->observer_ops.capture_gain_changed)
- client->observer_ops.capture_gain_changed(
- client->observer_context, cmsg->volume);
- break;
- }
- case CRAS_CLIENT_CAPTURE_MUTE_CHANGED: {
- struct cras_client_mute_changed *cmsg =
- (struct cras_client_mute_changed *)msg;
- if (client->observer_ops.capture_mute_changed)
- client->observer_ops.capture_mute_changed(
- client->observer_context, cmsg->muted,
- cmsg->mute_locked);
- break;
- }
- case CRAS_CLIENT_NODES_CHANGED: {
- if (client->observer_ops.nodes_changed)
- client->observer_ops.nodes_changed(
- client->observer_context);
- break;
- }
- case CRAS_CLIENT_ACTIVE_NODE_CHANGED: {
- struct cras_client_active_node_changed *cmsg =
- (struct cras_client_active_node_changed *)msg;
- enum CRAS_STREAM_DIRECTION direction =
- (enum CRAS_STREAM_DIRECTION)cmsg->direction;
- if (client->observer_ops.active_node_changed)
- client->observer_ops.active_node_changed(
- client->observer_context, direction,
- cmsg->node_id);
- break;
- }
- case CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED: {
- struct cras_client_node_value_changed *cmsg =
- (struct cras_client_node_value_changed *)msg;
- if (client->observer_ops.output_node_volume_changed)
- client->observer_ops.output_node_volume_changed(
- client->observer_context, cmsg->node_id,
- cmsg->value);
- break;
- }
- case CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED: {
- struct cras_client_node_value_changed *cmsg =
- (struct cras_client_node_value_changed *)msg;
- if (client->observer_ops.node_left_right_swapped_changed)
- client->observer_ops.node_left_right_swapped_changed(
- client->observer_context, cmsg->node_id,
- cmsg->value);
- break;
- }
- case CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED: {
- struct cras_client_node_value_changed *cmsg =
- (struct cras_client_node_value_changed *)msg;
- if (client->observer_ops.input_node_gain_changed)
- client->observer_ops.input_node_gain_changed(
- client->observer_context, cmsg->node_id,
- cmsg->value);
- break;
- }
- case CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED: {
- struct cras_client_num_active_streams_changed *cmsg =
- (struct cras_client_num_active_streams_changed *)msg;
- enum CRAS_STREAM_DIRECTION direction =
- (enum CRAS_STREAM_DIRECTION)cmsg->direction;
- if (client->observer_ops.num_active_streams_changed)
- client->observer_ops.num_active_streams_changed(
- client->observer_context, direction,
- cmsg->num_active_streams);
- break;
- }
- default:
- break;
- }
-
- return 0;
-}
-
-/* Handles messages from streams to this client. */
-static int handle_stream_message(struct cras_client *client, int poll_revents)
-{
- struct stream_msg msg;
- int rc;
-
- if ((poll_revents & POLLIN) == 0)
- return 0;
-
- rc = read(client->stream_fds[0], &msg, sizeof(msg));
- if (rc < 0)
- syslog(LOG_ERR, "cras_client: Stream read failed %d\n", errno);
- /* The only reason a stream sends a message is if it needs to be
- * removed. An error on read would mean the same thing so regardless of
- * what gets us here, just remove the stream */
- client_thread_rm_stream(client, msg.stream_id);
- return 0;
-}
-
-/* Handles messages from users to this client. */
-static int handle_command_message(struct cras_client *client, int poll_revents)
-{
- uint8_t buf[MAX_CMD_MSG_LEN];
- struct command_msg *msg = (struct command_msg *)buf;
- int rc, to_read;
-
- if ((poll_revents & POLLIN) == 0)
- return 0;
-
- rc = read(client->command_fds[0], buf, sizeof(msg->len));
- if (rc != sizeof(msg->len) || msg->len > MAX_CMD_MSG_LEN) {
- rc = -EIO;
- goto cmd_msg_complete;
- }
- to_read = msg->len - rc;
- rc = read(client->command_fds[0], &buf[0] + rc, to_read);
- if (rc != to_read) {
- rc = -EIO;
- goto cmd_msg_complete;
- }
-
- switch (msg->msg_id) {
- case CLIENT_STOP: {
- struct client_stream *s;
-
- /* Stop all playing streams */
- DL_FOREACH (client->streams, s)
- client_thread_rm_stream(client, s->id);
-
- /* And stop this client */
- client->thread.state = CRAS_THREAD_STOP;
- rc = 0;
- break;
- }
- case CLIENT_ADD_STREAM: {
- struct add_stream_command_message *add_msg =
- (struct add_stream_command_message *)msg;
- rc = client_thread_add_stream(client, add_msg->stream,
- add_msg->stream_id_out,
- add_msg->dev_idx);
- break;
- }
- case CLIENT_REMOVE_STREAM:
- rc = client_thread_rm_stream(client, msg->stream_id);
- break;
- case CLIENT_SET_STREAM_VOLUME_SCALER: {
- struct set_stream_volume_command_message *vol_msg =
- (struct set_stream_volume_command_message *)msg;
- rc = client_thread_set_stream_volume(client,
- vol_msg->header.stream_id,
- vol_msg->volume_scaler);
- break;
- }
- case CLIENT_SERVER_CONNECT:
- rc = connect_to_server_wait(client, false);
- break;
- case CLIENT_SERVER_CONNECT_ASYNC:
- rc = server_connect(client);
- break;
- default:
- assert(0);
- break;
- }
-
-cmd_msg_complete:
- /* Wake the waiting main thread with the result of the command. */
- if (write(client->command_reply_fds[1], &rc, sizeof(rc)) != sizeof(rc))
- return -EIO;
- return rc;
-}
-
-/* This thread handles non audio sample communication with the audio server.
- * The client program will call fucntions below to send messages to this thread
- * to add or remove streams or change parameters.
- */
-static void *client_thread(void *arg)
-{
- struct cras_client *client = (struct cras_client *)arg;
- struct pollfd pollfds[4];
- int (*cbs[4])(struct cras_client * client, int poll_revents);
- unsigned int num_pollfds, i;
- int rc;
-
- if (arg == NULL)
- return (void *)-EINVAL;
-
- while (thread_is_running(&client->thread)) {
- num_pollfds = 0;
-
- rc = cras_file_wait_get_fd(client->sock_file_wait);
- if (rc >= 0) {
- cbs[num_pollfds] = sock_file_wait_dispatch;
- pollfds[num_pollfds].fd = rc;
- pollfds[num_pollfds].events = POLLIN;
- pollfds[num_pollfds].revents = 0;
- num_pollfds++;
- } else
- syslog(LOG_ERR, "file wait fd: %d", rc);
- if (client->server_fd >= 0) {
- cbs[num_pollfds] = server_fd_dispatch;
- server_fill_pollfd(client, &(pollfds[num_pollfds]));
- num_pollfds++;
- }
- if (client->command_fds[0] >= 0) {
- cbs[num_pollfds] = handle_command_message;
- pollfds[num_pollfds].fd = client->command_fds[0];
- pollfds[num_pollfds].events = POLLIN;
- pollfds[num_pollfds].revents = 0;
- num_pollfds++;
- }
- if (client->stream_fds[0] >= 0) {
- cbs[num_pollfds] = handle_stream_message;
- pollfds[num_pollfds].fd = client->stream_fds[0];
- pollfds[num_pollfds].events = POLLIN;
- pollfds[num_pollfds].revents = 0;
- num_pollfds++;
- }
-
- rc = poll(pollfds, num_pollfds, -1);
- if (rc <= 0)
- continue;
-
- for (i = 0; i < num_pollfds; i++) {
- /* Only do one at a time, since some messages may
- * result in change to other fds. */
- if (pollfds[i].revents) {
- cbs[i](client, pollfds[i].revents);
- break;
- }
- }
- }
-
- /* close the command reply pipe. */
- close(client->command_reply_fds[1]);
- client->command_reply_fds[1] = -1;
-
- return NULL;
-}
-
-/* Sends a message to the client thread to complete an action requested by the
- * user. Then waits for the action to complete and returns the result. */
-static int send_command_message(struct cras_client *client,
- struct command_msg *msg)
-{
- int rc, cmd_res;
- if (client == NULL || !thread_is_running(&client->thread))
- return -EINVAL;
-
- rc = write(client->command_fds[1], msg, msg->len);
- if (rc != (int)msg->len)
- return -EPIPE;
-
- /* Wait for command to complete. */
- rc = read(client->command_reply_fds[0], &cmd_res, sizeof(cmd_res));
- if (rc != sizeof(cmd_res))
- return -EPIPE;
- return cmd_res;
-}
-
-/* Send a simple message to the client thread that holds no data. */
-static int send_simple_cmd_msg(struct cras_client *client,
- cras_stream_id_t stream_id, unsigned msg_id)
-{
- struct command_msg msg;
-
- msg.len = sizeof(msg);
- msg.stream_id = stream_id;
- msg.msg_id = msg_id;
-
- return send_command_message(client, &msg);
-}
-
-/* Sends the set volume message to the client thread. */
-static int send_stream_volume_command_msg(struct cras_client *client,
- cras_stream_id_t stream_id,
- float volume_scaler)
-{
- struct set_stream_volume_command_message msg;
-
- msg.header.len = sizeof(msg);
- msg.header.stream_id = stream_id;
- msg.header.msg_id = CLIENT_SET_STREAM_VOLUME_SCALER;
- msg.volume_scaler = volume_scaler;
-
- return send_command_message(client, &msg.header);
-}
-
-/* Sends a message back to the client and returns the error code. */
-static int write_message_to_server(struct cras_client *client,
- const struct cras_server_message *msg)
-{
- ssize_t write_rc = -EPIPE;
-
- if (client->server_fd_state == CRAS_SOCKET_STATE_CONNECTED ||
- client->server_fd_state == CRAS_SOCKET_STATE_FIRST_MESSAGE) {
- write_rc = write(client->server_fd, msg, msg->length);
- if (write_rc < 0)
- write_rc = -errno;
- }
-
- if (write_rc != (ssize_t)msg->length &&
- client->server_fd_state != CRAS_SOCKET_STATE_FIRST_MESSAGE)
- return -EPIPE;
-
- if (write_rc < 0)
- return write_rc;
- else if (write_rc != (ssize_t)msg->length)
- return -EIO;
- else
- return 0;
-}
-
-/* Fills server socket file to connect by client's connection type. */
-static int fill_socket_file(struct cras_client *client,
- enum CRAS_CONNECTION_TYPE conn_type)
-{
- int rc;
-
- client->sock_file =
- (const char *)calloc(CRAS_MAX_SOCKET_PATH_SIZE, sizeof(char));
- if (client->sock_file == NULL)
- return -ENOMEM;
-
- rc = cras_fill_socket_path(conn_type, (char *)client->sock_file);
- if (rc < 0) {
- free((void *)client->sock_file);
- return rc;
- }
- return 0;
-}
-
-/*
- * Exported Client Interface
- */
-
-int cras_client_create_with_type(struct cras_client **client,
- enum CRAS_CONNECTION_TYPE conn_type)
-{
- int rc;
- struct client_int *client_int;
- pthread_condattr_t cond_attr;
-
- if (!cras_validate_connection_type(conn_type)) {
- syslog(LOG_ERR, "Input connection type is not supported.\n");
- return -EINVAL;
- }
-
- /* Ignore SIGPIPE while using this API. */
- signal(SIGPIPE, SIG_IGN);
-
- client_int = (struct client_int *)calloc(1, sizeof(*client_int));
- if (!client_int)
- return -ENOMEM;
- *client = &client_int->client;
- (*client)->server_fd = -1;
- (*client)->id = -1;
-
- rc = pthread_rwlock_init(&client_int->server_state_rwlock, NULL);
- if (rc != 0) {
- syslog(LOG_ERR, "cras_client: Could not init state rwlock.");
- rc = -rc;
- goto free_client;
- }
-
- rc = pthread_mutex_init(&(*client)->stream_start_lock, NULL);
- if (rc != 0) {
- syslog(LOG_ERR, "cras_client: Could not init start lock.");
- rc = -rc;
- goto free_rwlock;
- }
-
- pthread_condattr_init(&cond_attr);
- pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
- rc = pthread_cond_init(&(*client)->stream_start_cond, &cond_attr);
- pthread_condattr_destroy(&cond_attr);
- if (rc != 0) {
- syslog(LOG_ERR, "cras_client: Could not init start cond.");
- rc = -rc;
- goto free_lock;
- }
-
- (*client)->server_event_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
- if ((*client)->server_event_fd < 0) {
- syslog(LOG_ERR, "cras_client: Could not setup server eventfd.");
- rc = -errno;
- goto free_cond;
- }
-
- rc = fill_socket_file((*client), conn_type);
- if (rc < 0) {
- goto free_server_event_fd;
- }
-
- rc = cras_file_wait_create((*client)->sock_file,
- CRAS_FILE_WAIT_FLAG_NONE,
- sock_file_wait_callback, *client,
- &(*client)->sock_file_wait);
- if (rc < 0 && rc != -ENOENT) {
- syslog(LOG_ERR,
- "cras_client: Could not setup watch for '%s': %s",
- (*client)->sock_file, strerror(-rc));
- goto free_error;
- }
- (*client)->sock_file_exists = (rc == 0);
-
- /* Pipes used by the main thread and the client thread to send commands
- * and replies. */
- rc = pipe((*client)->command_fds);
- if (rc < 0)
- goto free_error;
- /* Pipe used to communicate between the client thread and the audio
- * thread. */
- rc = pipe((*client)->stream_fds);
- if (rc < 0) {
- close((*client)->command_fds[0]);
- close((*client)->command_fds[1]);
- goto free_error;
- }
- (*client)->command_reply_fds[0] = -1;
- (*client)->command_reply_fds[1] = -1;
-
- return 0;
-free_error:
- cras_file_wait_destroy((*client)->sock_file_wait);
- free((void *)(*client)->sock_file);
-free_server_event_fd:
- if ((*client)->server_event_fd >= 0)
- close((*client)->server_event_fd);
-free_cond:
- pthread_cond_destroy(&(*client)->stream_start_cond);
-free_lock:
- pthread_mutex_destroy(&(*client)->stream_start_lock);
-free_rwlock:
- pthread_rwlock_destroy(&client_int->server_state_rwlock);
-free_client:
- *client = NULL;
- free(client_int);
- return rc;
-}
-
-int cras_client_create(struct cras_client **client)
-{
- return cras_client_create_with_type(client, CRAS_CONTROL);
-}
-
-void cras_client_destroy(struct cras_client *client)
-{
- struct client_int *client_int;
- if (client == NULL)
- return;
- client_int = to_client_int(client);
- client->server_connection_cb = NULL;
- cras_client_stop(client);
- server_disconnect(client);
- close(client->server_event_fd);
- close(client->command_fds[0]);
- close(client->command_fds[1]);
- close(client->stream_fds[0]);
- close(client->stream_fds[1]);
- cras_file_wait_destroy(client->sock_file_wait);
- pthread_rwlock_destroy(&client_int->server_state_rwlock);
- free((void *)client->sock_file);
- free(client_int);
-}
-
-int cras_client_connect(struct cras_client *client)
-{
- return connect_to_server(client, NULL, true);
-}
-
-int cras_client_connect_timeout(struct cras_client *client,
- unsigned int timeout_ms)
-{
- return connect_to_server_wait_retry(client, timeout_ms, true);
-}
-
-int cras_client_connected_wait(struct cras_client *client)
-{
- return send_simple_cmd_msg(client, 0, CLIENT_SERVER_CONNECT);
-}
-
-int cras_client_connect_async(struct cras_client *client)
-{
- return send_simple_cmd_msg(client, 0, CLIENT_SERVER_CONNECT_ASYNC);
-}
-
-struct cras_stream_params *cras_client_stream_params_create(
- enum CRAS_STREAM_DIRECTION direction, size_t buffer_frames,
- size_t cb_threshold, size_t unused, enum CRAS_STREAM_TYPE stream_type,
- uint32_t flags, void *user_data, cras_playback_cb_t aud_cb,
- cras_error_cb_t err_cb, struct cras_audio_format *format)
-{
- struct cras_stream_params *params;
-
- params = (struct cras_stream_params *)malloc(sizeof(*params));
- if (params == NULL)
- return NULL;
-
- params->direction = direction;
- params->buffer_frames = buffer_frames;
- params->cb_threshold = cb_threshold;
- params->effects = 0;
- params->stream_type = stream_type;
- params->client_type = CRAS_CLIENT_TYPE_UNKNOWN;
- params->flags = flags;
- params->user_data = user_data;
- params->aud_cb = aud_cb;
- params->unified_cb = 0;
- params->stream_cb = 0;
- params->err_cb = err_cb;
- memcpy(&(params->format), format, sizeof(*format));
- return params;
-}
-
-void cras_client_stream_params_set_client_type(
- struct cras_stream_params *params, enum CRAS_CLIENT_TYPE client_type)
-{
- params->client_type = client_type;
-}
-
-void cras_client_stream_params_enable_aec(struct cras_stream_params *params)
-{
- params->effects |= APM_ECHO_CANCELLATION;
-}
-
-void cras_client_stream_params_disable_aec(struct cras_stream_params *params)
-{
- params->effects &= ~APM_ECHO_CANCELLATION;
-}
-
-void cras_client_stream_params_enable_ns(struct cras_stream_params *params)
-{
- params->effects |= APM_NOISE_SUPRESSION;
-}
-
-void cras_client_stream_params_disable_ns(struct cras_stream_params *params)
-{
- params->effects &= ~APM_NOISE_SUPRESSION;
-}
-
-void cras_client_stream_params_enable_agc(struct cras_stream_params *params)
-{
- params->effects |= APM_GAIN_CONTROL;
-}
-
-void cras_client_stream_params_disable_agc(struct cras_stream_params *params)
-{
- params->effects &= ~APM_GAIN_CONTROL;
-}
-
-void cras_client_stream_params_enable_vad(struct cras_stream_params *params)
-{
- params->effects |= APM_VOICE_DETECTION;
-}
-
-void cras_client_stream_params_disable_vad(struct cras_stream_params *params)
-{
- params->effects &= ~APM_VOICE_DETECTION;
-}
-
-struct cras_stream_params *cras_client_unified_params_create(
- enum CRAS_STREAM_DIRECTION direction, unsigned int block_size,
- enum CRAS_STREAM_TYPE stream_type, uint32_t flags, void *user_data,
- cras_unified_cb_t unified_cb, cras_error_cb_t err_cb,
- struct cras_audio_format *format)
-{
- struct cras_stream_params *params;
-
- params = (struct cras_stream_params *)malloc(sizeof(*params));
- if (params == NULL)
- return NULL;
-
- params->direction = direction;
- params->buffer_frames = block_size * 2;
- params->cb_threshold = block_size;
- params->stream_type = stream_type;
- params->client_type = CRAS_CLIENT_TYPE_UNKNOWN;
- params->flags = flags;
- params->effects = 0;
- params->user_data = user_data;
- params->aud_cb = 0;
- params->unified_cb = unified_cb;
- params->stream_cb = 0;
- params->err_cb = err_cb;
- memcpy(&(params->format), format, sizeof(*format));
-
- return params;
-}
-
-void cras_client_stream_params_destroy(struct cras_stream_params *params)
-{
- free(params);
-}
-
-static inline int cras_client_send_add_stream_command_message(
- struct cras_client *client, uint32_t dev_idx,
- cras_stream_id_t *stream_id_out, struct cras_stream_params *config)
-{
- struct add_stream_command_message cmd_msg;
- struct client_stream *stream;
- int rc = 0;
-
- if (client == NULL || config == NULL || stream_id_out == NULL)
- return -EINVAL;
-
- if (config->stream_cb == NULL && config->aud_cb == NULL &&
- config->unified_cb == NULL)
- return -EINVAL;
-
- if (config->err_cb == NULL)
- return -EINVAL;
-
- stream = (struct client_stream *)calloc(1, sizeof(*stream));
- if (stream == NULL) {
- rc = -ENOMEM;
- goto add_failed;
- }
- stream->config =
- (struct cras_stream_params *)malloc(sizeof(*(stream->config)));
- if (stream->config == NULL) {
- rc = -ENOMEM;
- goto add_failed;
- }
- memcpy(stream->config, config, sizeof(*config));
- stream->aud_fd = -1;
- stream->wake_fds[0] = -1;
- stream->wake_fds[1] = -1;
- stream->direction = config->direction;
- stream->flags = config->flags;
-
- /* Caller might not set this volume scaler after stream created,
- * so always initialize it to 1.0f */
- stream->volume_scaler = 1.0f;
-
- cmd_msg.header.len = sizeof(cmd_msg);
- cmd_msg.header.msg_id = CLIENT_ADD_STREAM;
- cmd_msg.header.stream_id = stream->id;
- cmd_msg.stream = stream;
- cmd_msg.stream_id_out = stream_id_out;
- cmd_msg.dev_idx = dev_idx;
- rc = send_command_message(client, &cmd_msg.header);
- if (rc < 0) {
- syslog(LOG_ERR,
- "cras_client: adding stream failed in thread %d", rc);
- goto add_failed;
- }
-
- return 0;
-
-add_failed:
- if (stream) {
- if (stream->config)
- free(stream->config);
- free(stream);
- }
- return rc;
-}
-
-int cras_client_add_stream(struct cras_client *client,
- cras_stream_id_t *stream_id_out,
- struct cras_stream_params *config)
-{
- return cras_client_send_add_stream_command_message(
- client, NO_DEVICE, stream_id_out, config);
-}
-
-int cras_client_add_pinned_stream(struct cras_client *client, uint32_t dev_idx,
- cras_stream_id_t *stream_id_out,
- struct cras_stream_params *config)
-{
- return cras_client_send_add_stream_command_message(
- client, dev_idx, stream_id_out, config);
-}
-
-int cras_client_rm_stream(struct cras_client *client,
- cras_stream_id_t stream_id)
-{
- if (client == NULL)
- return -EINVAL;
-
- return send_simple_cmd_msg(client, stream_id, CLIENT_REMOVE_STREAM);
-}
-
-int cras_client_set_stream_volume(struct cras_client *client,
- cras_stream_id_t stream_id,
- float volume_scaler)
-{
- if (client == NULL)
- return -EINVAL;
-
- return send_stream_volume_command_msg(client, stream_id, volume_scaler);
-}
-
-int cras_client_set_system_volume(struct cras_client *client, size_t volume)
-{
- struct cras_set_system_volume msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_system_volume(&msg, volume);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_system_mute(struct cras_client *client, int mute)
-{
- struct cras_set_system_mute msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_system_mute(&msg, mute);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_user_mute(struct cras_client *client, int mute)
-{
- struct cras_set_system_mute msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_user_mute(&msg, mute);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_system_mute_locked(struct cras_client *client, int locked)
-{
- struct cras_set_system_mute msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_system_mute_locked(&msg, locked);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_system_capture_mute(struct cras_client *client, int mute)
-{
- struct cras_set_system_mute msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_system_capture_mute(&msg, mute);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_system_capture_mute_locked(struct cras_client *client,
- int locked)
-{
- struct cras_set_system_mute msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_system_capture_mute_locked(&msg, locked);
- return write_message_to_server(client, &msg.header);
-}
-
-size_t cras_client_get_system_volume(const struct cras_client *client)
-{
- size_t volume;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- volume = client->server_state->volume;
- server_state_unlock(client, lock_rc);
- return volume;
-}
-
-long cras_client_get_system_capture_gain(const struct cras_client *client)
-{
- long gain;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- gain = client->server_state->capture_gain;
- server_state_unlock(client, lock_rc);
- return gain;
-}
-
-int cras_client_get_system_muted(const struct cras_client *client)
-{
- int muted;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- muted = client->server_state->mute;
- server_state_unlock(client, lock_rc);
- return muted;
-}
-
-int cras_client_get_user_muted(const struct cras_client *client)
-{
- int muted;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- muted = client->server_state->user_mute;
- server_state_unlock(client, lock_rc);
- return muted;
-}
-
-int cras_client_get_system_capture_muted(const struct cras_client *client)
-{
- int muted;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- muted = client->server_state->capture_mute;
- server_state_unlock(client, lock_rc);
- return muted;
-}
-
-long cras_client_get_system_min_volume(const struct cras_client *client)
-{
- long min_volume;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- min_volume = client->server_state->min_volume_dBFS;
- server_state_unlock(client, lock_rc);
- return min_volume;
-}
-
-long cras_client_get_system_max_volume(const struct cras_client *client)
-{
- long max_volume;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- max_volume = client->server_state->max_volume_dBFS;
- server_state_unlock(client, lock_rc);
- return max_volume;
-}
-
-int cras_client_get_default_output_buffer_size(struct cras_client *client)
-{
- int default_output_buffer_size;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return -EINVAL;
-
- default_output_buffer_size =
- client->server_state->default_output_buffer_size;
- server_state_unlock(client, lock_rc);
- return default_output_buffer_size;
-}
-
-const struct audio_debug_info *
-cras_client_get_audio_debug_info(const struct cras_client *client)
-{
- const struct audio_debug_info *debug_info;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- debug_info = &client->server_state->audio_debug_info;
- server_state_unlock(client, lock_rc);
- return debug_info;
-}
-
-const struct main_thread_debug_info *
-cras_client_get_main_thread_debug_info(const struct cras_client *client)
-{
- const struct main_thread_debug_info *debug_info;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- debug_info = &client->server_state->main_thread_debug_info;
- server_state_unlock(client, lock_rc);
- return debug_info;
-}
-
-const struct cras_bt_debug_info *
-cras_client_get_bt_debug_info(const struct cras_client *client)
-{
- const struct cras_bt_debug_info *debug_info;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- debug_info = &client->server_state->bt_debug_info;
- server_state_unlock(client, lock_rc);
- return debug_info;
-}
-
-const struct cras_audio_thread_snapshot_buffer *
-cras_client_get_audio_thread_snapshot_buffer(const struct cras_client *client)
-{
- const struct cras_audio_thread_snapshot_buffer *snapshot_buffer;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- snapshot_buffer = &client->server_state->snapshot_buffer;
- server_state_unlock(client, lock_rc);
- return snapshot_buffer;
-}
-
-unsigned cras_client_get_num_active_streams(const struct cras_client *client,
- struct timespec *ts)
-{
- unsigned num_streams, version, i;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
-read_active_streams_again:
- version = begin_server_state_read(client->server_state);
- num_streams = 0;
- for (i = 0; i < CRAS_NUM_DIRECTIONS; i++)
- num_streams += client->server_state->num_active_streams[i];
- if (ts) {
- if (num_streams)
- clock_gettime(CLOCK_MONOTONIC_RAW, ts);
- else
- cras_timespec_to_timespec(
- ts,
- &client->server_state->last_active_stream_time);
- }
- if (end_server_state_read(client->server_state, version))
- goto read_active_streams_again;
-
- server_state_unlock(client, lock_rc);
- return num_streams;
-}
-
-int cras_client_run_thread(struct cras_client *client)
-{
- int rc;
-
- if (client == NULL)
- return -EINVAL;
- if (thread_is_running(&client->thread))
- return 0;
-
- assert(client->command_reply_fds[0] == -1 &&
- client->command_reply_fds[1] == -1);
-
- if (pipe(client->command_reply_fds) < 0)
- return -EIO;
- client->thread.state = CRAS_THREAD_RUNNING;
- rc = pthread_create(&client->thread.tid, NULL, client_thread, client);
- if (rc) {
- client->thread.state = CRAS_THREAD_STOP;
- return -rc;
- }
-
- return 0;
-}
-
-int cras_client_stop(struct cras_client *client)
-{
- if (client == NULL)
- return -EINVAL;
- if (!thread_is_running(&client->thread))
- return 0;
-
- send_simple_cmd_msg(client, 0, CLIENT_STOP);
- pthread_join(client->thread.tid, NULL);
-
- /* The other end of the reply pipe is closed by the client thread, just
- * clost the read end here. */
- close(client->command_reply_fds[0]);
- client->command_reply_fds[0] = -1;
-
- return 0;
-}
-
-void cras_client_set_connection_status_cb(
- struct cras_client *client, cras_connection_status_cb_t connection_cb,
- void *user_arg)
-{
- client->server_connection_cb = connection_cb;
- client->server_connection_user_arg = user_arg;
-}
-
-void cras_client_set_thread_priority_cb(struct cras_client *client,
- cras_thread_priority_cb_t cb)
-{
- client->thread_priority_cb = cb;
-}
-
-int cras_client_get_output_devices(const struct cras_client *client,
- struct cras_iodev_info *devs,
- struct cras_ionode_info *nodes,
- size_t *num_devs, size_t *num_nodes)
-{
- const struct cras_server_state *state;
- unsigned avail_devs, avail_nodes, version;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return -EINVAL;
- state = client->server_state;
-
-read_outputs_again:
- version = begin_server_state_read(state);
- avail_devs = MIN(*num_devs, state->num_output_devs);
- memcpy(devs, state->output_devs, avail_devs * sizeof(*devs));
- avail_nodes = MIN(*num_nodes, state->num_output_nodes);
- memcpy(nodes, state->output_nodes, avail_nodes * sizeof(*nodes));
- if (end_server_state_read(state, version))
- goto read_outputs_again;
- server_state_unlock(client, lock_rc);
-
- *num_devs = avail_devs;
- *num_nodes = avail_nodes;
-
- return 0;
-}
-
-int cras_client_get_input_devices(const struct cras_client *client,
- struct cras_iodev_info *devs,
- struct cras_ionode_info *nodes,
- size_t *num_devs, size_t *num_nodes)
-{
- const struct cras_server_state *state;
- unsigned avail_devs, avail_nodes, version;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (!client)
- return -EINVAL;
- state = client->server_state;
-
-read_inputs_again:
- version = begin_server_state_read(state);
- avail_devs = MIN(*num_devs, state->num_input_devs);
- memcpy(devs, state->input_devs, avail_devs * sizeof(*devs));
- avail_nodes = MIN(*num_nodes, state->num_input_nodes);
- memcpy(nodes, state->input_nodes, avail_nodes * sizeof(*nodes));
- if (end_server_state_read(state, version))
- goto read_inputs_again;
- server_state_unlock(client, lock_rc);
-
- *num_devs = avail_devs;
- *num_nodes = avail_nodes;
-
- return 0;
-}
-
-int cras_client_get_attached_clients(const struct cras_client *client,
- struct cras_attached_client_info *clients,
- size_t max_clients)
-{
- const struct cras_server_state *state;
- unsigned num, version;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return -EINVAL;
- state = client->server_state;
-
-read_clients_again:
- version = begin_server_state_read(state);
- num = MIN(max_clients, state->num_attached_clients);
- memcpy(clients, state->client_info, num * sizeof(*clients));
- if (end_server_state_read(state, version))
- goto read_clients_again;
- server_state_unlock(client, lock_rc);
-
- return num;
-}
-
-/* Find an output ionode on an iodev with the matching name.
- *
- * Args:
- * dev_name - The prefix of the iodev name.
- * node_name - The prefix of the ionode name.
- * dev_info - The information about the iodev will be returned here.
- * node_info - The information about the ionode will be returned here.
- * Returns:
- * 0 if successful, -1 if the node cannot be found.
- */
-static int cras_client_find_output_node(const struct cras_client *client,
- const char *dev_name,
- const char *node_name,
- struct cras_iodev_info *dev_info,
- struct cras_ionode_info *node_info)
-{
- size_t ndevs, nnodes;
- struct cras_iodev_info *devs = NULL;
- struct cras_ionode_info *nodes = NULL;
- int rc = -1;
- unsigned i, j;
-
- if (!client || !dev_name || !node_name)
- goto quit;
-
- devs = (struct cras_iodev_info *)malloc(CRAS_MAX_IODEVS *
- sizeof(*devs));
- if (!devs)
- goto quit;
-
- nodes = (struct cras_ionode_info *)malloc(CRAS_MAX_IONODES *
- sizeof(*nodes));
- if (!nodes)
- goto quit;
-
- ndevs = CRAS_MAX_IODEVS;
- nnodes = CRAS_MAX_IONODES;
- rc = cras_client_get_output_devices(client, devs, nodes, &ndevs,
- &nnodes);
- if (rc < 0)
- goto quit;
-
- for (i = 0; i < ndevs; i++)
- if (!strncmp(dev_name, devs[i].name, strlen(dev_name)))
- goto found_dev;
- rc = -1;
- goto quit;
-
-found_dev:
- for (j = 0; j < nnodes; j++)
- if (nodes[j].iodev_idx == devs[i].idx &&
- !strncmp(node_name, nodes[j].name, strlen(node_name)))
- goto found_node;
- rc = -1;
- goto quit;
-
-found_node:
- *dev_info = devs[i];
- *node_info = nodes[j];
- rc = 0;
-
-quit:
- free(devs);
- free(nodes);
- return rc;
-}
-
-int cras_client_get_node_by_id(const struct cras_client *client, int input,
- const cras_node_id_t node_id,
- struct cras_ionode_info *node_info)
-{
- size_t ndevs, nnodes;
- struct cras_iodev_info *devs = NULL;
- struct cras_ionode_info *nodes = NULL;
- int rc = -EINVAL;
- unsigned i;
-
- if (!client || !node_info) {
- rc = -EINVAL;
- goto quit;
- }
-
- devs = (struct cras_iodev_info *)malloc(CRAS_MAX_IODEVS *
- sizeof(*devs));
- if (!devs) {
- rc = -ENOMEM;
- goto quit;
- }
-
- nodes = (struct cras_ionode_info *)malloc(CRAS_MAX_IONODES *
- sizeof(*nodes));
- if (!nodes) {
- rc = -ENOMEM;
- goto quit;
- }
-
- ndevs = CRAS_MAX_IODEVS;
- nnodes = CRAS_MAX_IONODES;
- if (input)
- rc = cras_client_get_input_devices(client, devs, nodes, &ndevs,
- &nnodes);
- else
- rc = cras_client_get_output_devices(client, devs, nodes, &ndevs,
- &nnodes);
- if (rc < 0)
- goto quit;
-
- rc = -ENOENT;
- for (i = 0; i < nnodes; i++) {
- if (node_id == cras_make_node_id(nodes[i].iodev_idx,
- nodes[i].ionode_idx)) {
- memcpy(node_info, &nodes[i], sizeof(*node_info));
- rc = 0;
- break;
- }
- }
-
-quit:
- free(devs);
- free(nodes);
- return rc;
-}
-
-int cras_client_output_dev_plugged(const struct cras_client *client,
- const char *name)
-{
- struct cras_iodev_info dev_info;
- struct cras_ionode_info node_info = { 0 };
-
- if (cras_client_find_output_node(client, name, "Front Headphone Jack",
- &dev_info, &node_info) < 0)
- return 0;
-
- return node_info.plugged;
-}
-
-int cras_client_set_node_attr(struct cras_client *client,
- cras_node_id_t node_id, enum ionode_attr attr,
- int value)
-{
- struct cras_set_node_attr msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_node_attr(&msg, node_id, attr, value);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_select_node(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- struct cras_select_node msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_select_node(&msg, direction, node_id);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_add_active_node(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- struct cras_add_active_node msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_add_active_node(&msg, direction, node_id);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_rm_active_node(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- struct cras_rm_active_node msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_rm_active_node(&msg, direction, node_id);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_format_bytes_per_frame(struct cras_audio_format *fmt)
-{
- if (fmt == NULL)
- return -EINVAL;
-
- return cras_get_format_bytes(fmt);
-}
-
-int cras_client_calc_playback_latency(const struct timespec *sample_time,
- struct timespec *delay)
-{
- struct timespec now;
-
- if (delay == NULL)
- return -EINVAL;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- /* for output return time until sample is played (t - now) */
- subtract_timespecs(sample_time, &now, delay);
- return 0;
-}
-
-int cras_client_calc_capture_latency(const struct timespec *sample_time,
- struct timespec *delay)
-{
- struct timespec now;
-
- if (delay == NULL)
- return -EINVAL;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- /* For input want time since sample read (now - t) */
- subtract_timespecs(&now, sample_time, delay);
- return 0;
-}
-
-int cras_client_reload_dsp(struct cras_client *client)
-{
- struct cras_reload_dsp msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_reload_dsp(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_dump_dsp_info(struct cras_client *client)
-{
- struct cras_dump_dsp_info msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_dump_dsp_info(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_update_audio_debug_info(
- struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
-{
- struct cras_dump_audio_thread msg;
-
- if (client == NULL)
- return -EINVAL;
-
- if (client->debug_info_callback != NULL)
- return -EINVAL;
- client->debug_info_callback = debug_info_cb;
-
- cras_fill_dump_audio_thread(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_get_atlog_access(struct cras_client *client,
- void (*atlog_access_cb)(struct cras_client *))
-{
- struct cras_get_atlog_fd msg;
-
- if (client == NULL)
- return -EINVAL;
-
- if (client->atlog_access_callback != NULL)
- return -EINVAL;
- client->atlog_access_callback = atlog_access_cb;
-
- cras_fill_get_atlog_fd(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_read_atlog(struct cras_client *client, uint64_t *read_idx,
- uint64_t *missing,
- struct audio_thread_event_log *buf)
-{
- struct audio_thread_event_log log;
- uint64_t i, sync_write_pos, len = 0;
- struct timespec timestamp, last_timestamp;
-
- if (!client->atlog_ro)
- return -EINVAL;
-
- sync_write_pos = client->atlog_ro->sync_write_pos;
- __sync_synchronize();
- memcpy(&log, client->atlog_ro, sizeof(log));
-
- if (sync_write_pos <= *read_idx)
- return 0;
-
- *missing = 0;
- for (i = sync_write_pos - 1; i >= *read_idx; --i) {
- uint64_t pos = i % log.len;
- timestamp.tv_sec = log.log[pos].tag_sec & 0x00ffffff;
- timestamp.tv_nsec = log.log[pos].nsec;
-
- if (i != sync_write_pos - 1 &&
- timespec_after(&timestamp, &last_timestamp)) {
- if (*read_idx)
- *missing = i - *read_idx + 1;
- *read_idx = i + 1;
- break;
- }
- last_timestamp = timestamp;
-
- if (!i)
- break;
- }
-
- /* Copies the continuous part of log. */
- if ((sync_write_pos - 1) % log.len < *read_idx % log.len) {
- len = log.len - *read_idx % log.len;
- memcpy(buf->log, &log.log[*read_idx % log.len],
- sizeof(struct audio_thread_event) * len);
- memcpy(&buf->log[len], log.log,
- sizeof(struct audio_thread_event) *
- ((sync_write_pos - 1) % log.len + 1));
- len = sync_write_pos - *read_idx;
- } else {
- len = sync_write_pos - *read_idx;
- memcpy(buf->log, &log.log[*read_idx % log.len],
- sizeof(struct audio_thread_event) * len);
- }
-
- *read_idx = sync_write_pos;
- return len;
-}
-
-int cras_client_update_main_thread_debug_info(
- struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
-{
- struct cras_dump_main msg;
-
- if (client == NULL)
- return -EINVAL;
- if (client->debug_info_callback != NULL)
- return -EINVAL;
- client->debug_info_callback = debug_info_cb;
- cras_fill_dump_main(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_update_bt_debug_info(
- struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
-{
- struct cras_dump_bt msg;
-
- if (client == NULL)
- return -EINVAL;
-
- if (client->debug_info_callback != NULL)
- return -EINVAL;
- client->debug_info_callback = debug_info_cb;
-
- cras_fill_dump_bt(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_update_audio_thread_snapshots(
- struct cras_client *client, void (*debug_info_cb)(struct cras_client *))
-{
- struct cras_dump_snapshots msg;
-
- if (client == NULL)
- return -EINVAL;
-
- if (client->debug_info_callback != NULL)
- return -EINVAL;
- client->debug_info_callback = debug_info_cb;
-
- cras_fill_dump_snapshots(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_get_max_supported_channels(const struct cras_client *client,
- cras_node_id_t node_id,
- uint32_t *max_channels)
-{
- size_t ndevs, nnodes;
- struct cras_iodev_info *devs = NULL;
- struct cras_ionode_info *nodes = NULL;
- int rc = -EINVAL;
- unsigned i;
-
- if (!client) {
- rc = -EINVAL;
- goto quit;
- }
-
- devs = (struct cras_iodev_info *)malloc(CRAS_MAX_IODEVS *
- sizeof(*devs));
- if (!devs) {
- rc = -ENOMEM;
- goto quit;
- }
-
- nodes = (struct cras_ionode_info *)malloc(CRAS_MAX_IONODES *
- sizeof(*nodes));
- if (!nodes) {
- rc = -ENOMEM;
- goto quit;
- }
-
- ndevs = CRAS_MAX_IODEVS;
- nnodes = CRAS_MAX_IONODES;
- rc = cras_client_get_output_devices(client, devs, nodes, &ndevs,
- &nnodes);
- if (rc < 0)
- goto quit;
-
- rc = -ENOENT;
- uint32_t iodev_idx;
- for (i = 0; i < nnodes; i++) {
- if (node_id == cras_make_node_id(nodes[i].iodev_idx,
- nodes[i].ionode_idx)) {
- iodev_idx = nodes[i].iodev_idx;
- rc = 0;
- break;
- }
- }
-
- if (rc < 0)
- goto quit;
-
- rc = -ENOENT;
- for (i = 0; i < ndevs; i++) {
- if (iodev_idx == devs[i].idx) {
- *max_channels = devs[i].max_supported_channels;
- rc = 0;
- break;
- }
- }
-
-quit:
- free(devs);
- free(nodes);
- return rc;
-}
-
-int cras_client_set_node_volume(struct cras_client *client,
- cras_node_id_t node_id, uint8_t volume)
-{
- struct cras_set_node_attr msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_node_attr(&msg, node_id, IONODE_ATTR_VOLUME, volume);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_swap_node_left_right(struct cras_client *client,
- cras_node_id_t node_id, int enable)
-{
- struct cras_set_node_attr msg;
-
- if (client == NULL)
- return -EINVAL;
-
- cras_fill_set_node_attr(&msg, node_id, IONODE_ATTR_SWAP_LEFT_RIGHT,
- enable);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_node_capture_gain(struct cras_client *client,
- cras_node_id_t node_id, long gain)
-{
- struct cras_set_node_attr msg;
-
- if (client == NULL)
- return -EINVAL;
- if (gain > INT_MAX || gain < INT_MIN)
- return -EINVAL;
-
- cras_fill_set_node_attr(&msg, node_id, IONODE_ATTR_CAPTURE_GAIN, gain);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_add_test_iodev(struct cras_client *client,
- enum TEST_IODEV_TYPE type)
-{
- struct cras_add_test_dev msg;
-
- cras_fill_add_test_dev(&msg, type);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_test_iodev_command(struct cras_client *client,
- unsigned int iodev_idx,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len, const uint8_t *data)
-{
- struct cras_test_dev_command *msg;
- int rc;
-
- msg = (struct cras_test_dev_command *)malloc(sizeof(*msg) + data_len);
- cras_fill_test_dev_command(msg, iodev_idx, command, data_len, data);
- rc = write_message_to_server(client, &msg->header);
- free(msg);
- return rc;
-}
-
-int cras_client_config_global_remix(struct cras_client *client,
- unsigned num_channels, float *coefficient)
-{
- struct cras_config_global_remix *msg;
- int rc;
- size_t nchan = (size_t)num_channels;
-
- msg = (struct cras_config_global_remix *)malloc(
- sizeof(*msg) + nchan * nchan * sizeof(*coefficient));
- cras_fill_config_global_remix_command(msg, num_channels, coefficient,
- num_channels * num_channels);
- rc = write_message_to_server(client, &msg->header);
- free(msg);
- return rc;
-}
-
-int cras_client_get_first_node_type_idx(const struct cras_client *client,
- enum CRAS_NODE_TYPE type,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t *node_id)
-{
- const struct cras_server_state *state;
- unsigned int version;
- unsigned int i;
- const struct cras_ionode_info *node_list;
- unsigned int num_nodes;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return -EINVAL;
- state = client->server_state;
-
-read_nodes_again:
- version = begin_server_state_read(state);
- if (direction == CRAS_STREAM_OUTPUT) {
- node_list = state->output_nodes;
- num_nodes = state->num_output_nodes;
- } else {
- node_list = state->input_nodes;
- num_nodes = state->num_input_nodes;
- }
- for (i = 0; i < num_nodes; i++) {
- if ((enum CRAS_NODE_TYPE)node_list[i].type_enum == type) {
- *node_id = cras_make_node_id(node_list[i].iodev_idx,
- node_list[i].ionode_idx);
- server_state_unlock(client, lock_rc);
- return 0;
- }
- }
- if (end_server_state_read(state, version))
- goto read_nodes_again;
- server_state_unlock(client, lock_rc);
-
- return -ENODEV;
-}
-
-int cras_client_get_first_dev_type_idx(const struct cras_client *client,
- enum CRAS_NODE_TYPE type,
- enum CRAS_STREAM_DIRECTION direction)
-{
- cras_node_id_t node_id;
- int rc;
-
- rc = cras_client_get_first_node_type_idx(client, type, direction,
- &node_id);
- if (rc)
- return rc;
-
- return dev_index_of(node_id);
-}
-
-int cras_client_set_suspend(struct cras_client *client, int suspend)
-{
- struct cras_server_message msg;
-
- cras_fill_suspend_message(&msg, suspend);
- return write_message_to_server(client, &msg);
-}
-
-int cras_client_get_hotword_models(struct cras_client *client,
- cras_node_id_t node_id,
- get_hotword_models_cb_t cb)
-{
- struct cras_get_hotword_models msg;
-
- if (!client)
- return -EINVAL;
- client->get_hotword_models_cb = cb;
-
- cras_fill_get_hotword_models_message(&msg, node_id);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_hotword_model(struct cras_client *client,
- cras_node_id_t node_id,
- const char *model_name)
-{
- struct cras_set_hotword_model msg;
-
- cras_fill_set_hotword_model_message(&msg, node_id, model_name);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_set_aec_dump(struct cras_client *client,
- cras_stream_id_t stream_id, int start, int fd)
-{
- struct cras_set_aec_dump msg;
-
- cras_fill_set_aec_dump_message(&msg, stream_id, start);
-
- if (fd != -1)
- return cras_send_with_fds(client->server_fd, &msg, sizeof(msg),
- &fd, 1);
- else
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_reload_aec_config(struct cras_client *client)
-{
- struct cras_reload_aec_config msg;
-
- cras_fill_reload_aec_config(&msg);
- return write_message_to_server(client, &msg.header);
-}
-
-int cras_client_get_aec_supported(struct cras_client *client)
-{
- int aec_supported;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return 0;
-
- aec_supported = client->server_state->aec_supported;
- server_state_unlock(client, lock_rc);
- return aec_supported;
-}
-
-int cras_client_get_aec_group_id(struct cras_client *client)
-{
- int aec_group_id;
- int lock_rc;
-
- lock_rc = server_state_rdlock(client);
- if (lock_rc)
- return -1;
-
- aec_group_id = client->server_state->aec_group_id;
- server_state_unlock(client, lock_rc);
- return aec_group_id;
-}
-
-int cras_client_set_bt_wbs_enabled(struct cras_client *client, bool enabled)
-{
- struct cras_set_bt_wbs_enabled msg;
-
- cras_fill_set_bt_wbs_enabled(&msg, enabled);
- return write_message_to_server(client, &msg.header);
-}
-
-void cras_client_set_state_change_callback_context(struct cras_client *client,
- void *context)
-{
- if (!client)
- return;
- client->observer_context = context;
-}
-
-static int cras_send_register_notification(struct cras_client *client,
- enum CRAS_CLIENT_MESSAGE_ID msg_id,
- int do_register)
-{
- struct cras_register_notification msg;
- int rc;
-
- /* This library automatically re-registers notifications when
- * reconnecting, so we can ignore message send failure due to no
- * connection. */
- cras_fill_register_notification_message(&msg, msg_id, do_register);
- rc = write_message_to_server(client, &msg.header);
- if (rc == -EPIPE)
- rc = 0;
- return rc;
-}
-
-int cras_client_set_output_volume_changed_callback(
- struct cras_client *client,
- cras_client_output_volume_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.output_volume_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_OUTPUT_VOLUME_CHANGED, cb != NULL);
-}
-
-int cras_client_set_output_mute_changed_callback(
- struct cras_client *client, cras_client_output_mute_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.output_mute_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_OUTPUT_MUTE_CHANGED, cb != NULL);
-}
-
-int cras_client_set_capture_gain_changed_callback(
- struct cras_client *client,
- cras_client_capture_gain_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.capture_gain_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_CAPTURE_GAIN_CHANGED, cb != NULL);
-}
-
-int cras_client_set_capture_mute_changed_callback(
- struct cras_client *client,
- cras_client_capture_mute_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.capture_mute_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_CAPTURE_MUTE_CHANGED, cb != NULL);
-}
-
-int cras_client_set_nodes_changed_callback(
- struct cras_client *client, cras_client_nodes_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.nodes_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_NODES_CHANGED, cb != NULL);
-}
-
-int cras_client_set_active_node_changed_callback(
- struct cras_client *client, cras_client_active_node_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.active_node_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_ACTIVE_NODE_CHANGED, cb != NULL);
-}
-
-int cras_client_set_output_node_volume_changed_callback(
- struct cras_client *client,
- cras_client_output_node_volume_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.output_node_volume_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED, cb != NULL);
-}
-
-int cras_client_set_node_left_right_swapped_changed_callback(
- struct cras_client *client,
- cras_client_node_left_right_swapped_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.node_left_right_swapped_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED,
- cb != NULL);
-}
-
-int cras_client_set_input_node_gain_changed_callback(
- struct cras_client *client,
- cras_client_input_node_gain_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.input_node_gain_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED, cb != NULL);
-}
-
-int cras_client_set_num_active_streams_changed_callback(
- struct cras_client *client,
- cras_client_num_active_streams_changed_callback cb)
-{
- if (!client)
- return -EINVAL;
- client->observer_ops.num_active_streams_changed = cb;
- return cras_send_register_notification(
- client, CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED, cb != NULL);
-}
-
-static int reregister_notifications(struct cras_client *client)
-{
- int rc;
-
- if (client->observer_ops.output_volume_changed) {
- rc = cras_client_set_output_volume_changed_callback(
- client, client->observer_ops.output_volume_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.output_mute_changed) {
- rc = cras_client_set_output_mute_changed_callback(
- client, client->observer_ops.output_mute_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.capture_gain_changed) {
- rc = cras_client_set_capture_gain_changed_callback(
- client, client->observer_ops.capture_gain_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.capture_mute_changed) {
- rc = cras_client_set_capture_mute_changed_callback(
- client, client->observer_ops.capture_mute_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.nodes_changed) {
- rc = cras_client_set_nodes_changed_callback(
- client, client->observer_ops.nodes_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.active_node_changed) {
- rc = cras_client_set_active_node_changed_callback(
- client, client->observer_ops.active_node_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.output_node_volume_changed) {
- rc = cras_client_set_output_node_volume_changed_callback(
- client,
- client->observer_ops.output_node_volume_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.node_left_right_swapped_changed) {
- rc = cras_client_set_node_left_right_swapped_changed_callback(
- client,
- client->observer_ops.node_left_right_swapped_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.input_node_gain_changed) {
- rc = cras_client_set_input_node_gain_changed_callback(
- client, client->observer_ops.input_node_gain_changed);
- if (rc != 0)
- return rc;
- }
- if (client->observer_ops.num_active_streams_changed) {
- rc = cras_client_set_num_active_streams_changed_callback(
- client,
- client->observer_ops.num_active_streams_changed);
- if (rc != 0)
- return rc;
- }
- return 0;
-}
-
-static int hotword_read_cb(struct cras_client *client,
- cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- struct cras_hotword_handle *handle;
-
- handle = (struct cras_hotword_handle *)user_arg;
- if (handle->trigger_cb)
- handle->trigger_cb(client, handle, handle->user_data);
-
- return 0;
-}
-
-static int hotword_err_cb(struct cras_client *client,
- cras_stream_id_t stream_id, int error, void *user_arg)
-{
- struct cras_hotword_handle *handle;
-
- handle = (struct cras_hotword_handle *)user_arg;
- if (handle->err_cb)
- handle->err_cb(client, handle, error, handle->user_data);
-
- return 0;
-}
-
-int cras_client_enable_hotword_callback(struct cras_client *client,
- void *user_data,
- cras_hotword_trigger_cb_t trigger_cb,
- cras_hotword_error_cb_t err_cb,
- struct cras_hotword_handle **handle_out)
-{
- struct cras_hotword_handle *handle;
- int ret = 0;
-
- if (!client)
- return -EINVAL;
-
- handle = (struct cras_hotword_handle *)calloc(1, sizeof(*handle));
- if (!handle)
- return -ENOMEM;
-
- handle->format = cras_audio_format_create(SND_PCM_FORMAT_S16_LE,
- HOTWORD_FRAME_RATE, 1);
- if (!handle->format) {
- ret = -ENOMEM;
- goto cleanup;
- }
-
- handle->params = cras_client_unified_params_create(
- CRAS_STREAM_INPUT, HOTWORD_BLOCK_SIZE, CRAS_STREAM_TYPE_DEFAULT,
- HOTWORD_STREAM | TRIGGER_ONLY, (void *)handle, hotword_read_cb,
- hotword_err_cb, handle->format);
- if (!handle->params) {
- ret = -ENOMEM;
- goto cleanup_format;
- }
-
- handle->trigger_cb = trigger_cb;
- handle->err_cb = err_cb;
- handle->user_data = user_data;
-
- ret = cras_client_add_stream(client, &handle->stream_id,
- handle->params);
- if (ret)
- goto cleanup_params;
-
- *handle_out = handle;
- return 0;
-
-cleanup_params:
- cras_client_stream_params_destroy(handle->params);
-cleanup_format:
- cras_audio_format_destroy(handle->format);
-cleanup:
- free(handle);
- return ret;
-}
-
-int cras_client_disable_hotword_callback(struct cras_client *client,
- struct cras_hotword_handle *handle)
-{
- if (!client || !handle)
- return -EINVAL;
-
- cras_client_rm_stream(client, handle->stream_id);
- cras_audio_format_destroy(handle->format);
- cras_client_stream_params_destroy(handle->params);
- free(handle);
- return 0;
-}
-
-int get_nodes(struct cras_client *client, enum CRAS_STREAM_DIRECTION direction,
- struct libcras_node_info ***nodes, size_t *num)
-{
- struct cras_iodev_info iodevs[CRAS_MAX_IODEVS];
- struct cras_ionode_info ionodes[CRAS_MAX_IONODES];
- size_t num_devs = CRAS_MAX_IODEVS, num_nodes = CRAS_MAX_IONODES;
- int rc, i, j;
-
- *num = 0;
- if (direction == CRAS_STREAM_INPUT) {
- rc = cras_client_get_input_devices(client, iodevs, ionodes,
- &num_devs, &num_nodes);
- } else {
- rc = cras_client_get_output_devices(client, iodevs, ionodes,
- &num_devs, &num_nodes);
- }
-
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to get devices: %d", rc);
- return rc;
- }
-
- *nodes = (struct libcras_node_info **)calloc(
- num_nodes, sizeof(struct libcras_node_info *));
-
- for (i = 0; i < num_devs; i++) {
- for (j = 0; j < num_nodes; j++) {
- if (iodevs[i].idx != ionodes[j].iodev_idx)
- continue;
- (*nodes)[*num] = libcras_node_info_create(&iodevs[i],
- &ionodes[j]);
- if ((*nodes)[*num] == NULL) {
- rc = -errno;
- goto clean;
- }
- (*num)++;
- }
- }
- return 0;
-clean:
- for (i = 0; i < *num; i++)
- libcras_node_info_destroy((*nodes)[i]);
- free(*nodes);
- *nodes = NULL;
- *num = 0;
- return rc;
-}
-
-int get_default_output_buffer_size(struct cras_client *client, int *size)
-{
- int rc = cras_client_get_default_output_buffer_size(client);
- if (rc < 0)
- return rc;
- *size = rc;
- return 0;
-}
-
-int get_aec_group_id(struct cras_client *client, int *id)
-{
- int rc = cras_client_get_aec_group_id(client);
- if (rc < 0)
- return rc;
- *id = rc;
- return 0;
-}
-
-int get_aec_supported(struct cras_client *client, int *supported)
-{
- *supported = cras_client_get_aec_supported(client);
- return 0;
-}
-
-int get_system_muted(struct cras_client *client, int *muted)
-{
- *muted = cras_client_get_system_muted(client);
- return 0;
-}
-
-int get_loopback_dev_idx(struct cras_client *client, int *idx)
-{
- int rc = cras_client_get_first_dev_type_idx(
- client, CRAS_NODE_TYPE_POST_MIX_PRE_DSP, CRAS_STREAM_INPUT);
- if (rc < 0)
- return rc;
- *idx = rc;
- return 0;
-}
-
-struct libcras_client *libcras_client_create()
-{
- struct libcras_client *client = (struct libcras_client *)calloc(
- 1, sizeof(struct libcras_client));
- if (!client) {
- syslog(LOG_ERR, "cras_client: calloc failed");
- return NULL;
- }
- if (cras_client_create(&client->client_)) {
- libcras_client_destroy(client);
- return NULL;
- }
- client->api_version = CRAS_API_VERSION;
- client->connect = cras_client_connect;
- client->connect_timeout = cras_client_connect_timeout;
- client->connected_wait = cras_client_connected_wait;
- client->run_thread = cras_client_run_thread;
- client->stop = cras_client_stop;
- client->add_pinned_stream = cras_client_add_pinned_stream;
- client->rm_stream = cras_client_rm_stream;
- client->set_stream_volume = cras_client_set_stream_volume;
- client->get_nodes = get_nodes;
- client->get_default_output_buffer_size = get_default_output_buffer_size;
- client->get_aec_group_id = get_aec_group_id;
- client->get_aec_supported = get_aec_supported;
- client->get_system_muted = get_system_muted;
- client->set_system_mute = cras_client_set_system_mute;
- client->get_loopback_dev_idx = get_loopback_dev_idx;
- return client;
-}
-
-void libcras_client_destroy(struct libcras_client *client)
-{
- cras_client_destroy(client->client_);
- free(client);
-}
-
-int stream_params_set(struct cras_stream_params *params,
- enum CRAS_STREAM_DIRECTION direction,
- size_t buffer_frames, size_t cb_threshold,
- enum CRAS_STREAM_TYPE stream_type,
- enum CRAS_CLIENT_TYPE client_type, uint32_t flags,
- void *user_data, libcras_stream_cb_t stream_cb,
- cras_error_cb_t err_cb, size_t rate,
- snd_pcm_format_t format, size_t num_channels)
-{
- params->direction = direction;
- params->buffer_frames = buffer_frames;
- params->cb_threshold = cb_threshold;
- params->stream_type = stream_type;
- params->client_type = client_type;
- params->flags = flags;
- params->user_data = user_data;
- params->stream_cb = stream_cb;
- params->err_cb = err_cb;
- params->format.frame_rate = rate;
- params->format.format = format;
- params->format.num_channels = num_channels;
- return 0;
-}
-
-int stream_params_set_channel_layout(struct cras_stream_params *params,
- int length, const int8_t *layout)
-{
- if (length != CRAS_CH_MAX)
- return -EINVAL;
- return cras_audio_format_set_channel_layout(&params->format, layout);
-}
-
-struct libcras_stream_params *libcras_stream_params_create()
-{
- struct libcras_stream_params *params =
- (struct libcras_stream_params *)calloc(
- 1, sizeof(struct libcras_stream_params));
- if (!params) {
- syslog(LOG_ERR, "cras_client: calloc failed");
- return NULL;
- }
- params->params_ = (struct cras_stream_params *)calloc(
- 1, sizeof(struct cras_stream_params));
- if (params->params_ == NULL) {
- syslog(LOG_ERR, "cras_client: calloc failed");
- free(params->params_);
- return NULL;
- }
- params->api_version = CRAS_API_VERSION;
- params->set = stream_params_set;
- params->set_channel_layout = stream_params_set_channel_layout;
- params->enable_aec = cras_client_stream_params_enable_aec;
- return params;
-}
-
-void libcras_stream_params_destroy(struct libcras_stream_params *params)
-{
- free(params->params_);
- free(params);
-}
-
-struct cras_node_info {
- uint64_t id;
- uint32_t dev_idx;
- uint32_t node_idx;
- uint32_t max_supported_channels;
- bool plugged;
- bool active;
- char type[CRAS_NODE_TYPE_BUFFER_SIZE];
- char node_name[CRAS_NODE_NAME_BUFFER_SIZE];
- char dev_name[CRAS_IODEV_NAME_BUFFER_SIZE];
-};
-
-int cras_node_info_get_id(struct cras_node_info *node, uint64_t *id)
-{
- (*id) = node->id;
- return 0;
-}
-
-int cras_node_info_get_dev_idx(struct cras_node_info *node, uint32_t *dev_idx)
-{
- (*dev_idx) = node->dev_idx;
- return 0;
-}
-
-int cras_node_info_get_node_idx(struct cras_node_info *node, uint32_t *node_idx)
-{
- (*node_idx) = node->node_idx;
- return 0;
-}
-
-int cras_node_info_get_max_supported_channels(struct cras_node_info *node,
- uint32_t *max_supported_channels)
-{
- (*max_supported_channels) = node->max_supported_channels;
- return 0;
-}
-
-int cras_node_info_is_plugged(struct cras_node_info *node, bool *is_plugged)
-{
- (*is_plugged) = node->plugged;
- return 0;
-}
-
-int cras_node_info_is_active(struct cras_node_info *node, bool *is_active)
-{
- (*is_active) = node->active;
- return 0;
-}
-
-int cras_node_info_get_type(struct cras_node_info *node, char **type)
-{
- (*type) = node->type;
- return 0;
-}
-
-int cras_node_info_get_node_name(struct cras_node_info *node, char **node_name)
-{
- (*node_name) = node->node_name;
- return 0;
-}
-
-int cras_node_info_get_dev_name(struct cras_node_info *node, char **dev_name)
-{
- (*dev_name) = node->dev_name;
- return 0;
-}
-
-struct libcras_node_info *
-libcras_node_info_create(struct cras_iodev_info *iodev,
- struct cras_ionode_info *ionode)
-{
- struct libcras_node_info *node = (struct libcras_node_info *)calloc(
- 1, sizeof(struct libcras_node_info));
- if (!node) {
- syslog(LOG_ERR, "cras_client: calloc failed");
- return NULL;
- }
- node->node_ = (struct cras_node_info *)calloc(
- 1, sizeof(struct cras_node_info));
- if (node->node_ == NULL) {
- syslog(LOG_ERR, "cras_client: calloc failed");
- free(node);
- return NULL;
- }
- node->api_version = CRAS_API_VERSION;
- node->node_->id =
- cras_make_node_id(ionode->iodev_idx, ionode->ionode_idx);
- node->node_->dev_idx = ionode->iodev_idx;
- node->node_->node_idx = ionode->ionode_idx;
- node->node_->max_supported_channels = iodev->max_supported_channels;
- node->node_->plugged = ionode->plugged;
- node->node_->active = ionode->active;
- strncpy(node->node_->type, ionode->type, CRAS_NODE_TYPE_BUFFER_SIZE);
- node->node_->type[CRAS_NODE_TYPE_BUFFER_SIZE - 1] = '\0';
- strncpy(node->node_->node_name, ionode->name,
- CRAS_NODE_NAME_BUFFER_SIZE);
- node->node_->node_name[CRAS_NODE_NAME_BUFFER_SIZE - 1] = '\0';
- strncpy(node->node_->dev_name, iodev->name,
- CRAS_IODEV_NAME_BUFFER_SIZE);
- node->node_->dev_name[CRAS_IODEV_NAME_BUFFER_SIZE - 1] = '\0';
- node->get_id = cras_node_info_get_id;
- node->get_dev_idx = cras_node_info_get_dev_idx;
- node->get_node_idx = cras_node_info_get_node_idx;
- node->get_max_supported_channels =
- cras_node_info_get_max_supported_channels;
- node->is_plugged = cras_node_info_is_plugged;
- node->is_active = cras_node_info_is_active;
- node->get_type = cras_node_info_get_type;
- node->get_node_name = cras_node_info_get_node_name;
- node->get_dev_name = cras_node_info_get_dev_name;
- return node;
-}
-
-void libcras_node_info_destroy(struct libcras_node_info *node)
-{
- free(node->node_);
- free(node);
-}
-
-void libcras_node_info_array_destroy(struct libcras_node_info **nodes,
- size_t num)
-{
- int i;
- for (i = 0; i < num; i++)
- libcras_node_info_destroy(nodes[i]);
- free(nodes);
-}
diff --git a/cras/src/libcras/cras_client.h b/cras/src/libcras/cras_client.h
deleted file mode 100644
index f26a0814..00000000
--- a/cras/src/libcras/cras_client.h
+++ /dev/null
@@ -1,2008 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * This API creates multiple threads, one for control, and a thread per audio
- * stream. The control thread is used to receive messages and notifications
- * from the audio server, and manage the per-stream threads. API calls below
- * may send messages to the control thread, or directly to the server. It is
- * required that the control thread is running in order to support audio
- * streams and notifications from the server.
- *
- * The API has multiple initialization sequences, but some of those can block
- * while waiting for a response from the server.
- *
- * The following is the non-blocking API initialization sequence:
- * cras_client_create()
- * cras_client_set_connection_status_cb() (optional)
- * cras_client_run_thread()
- * cras_client_connect_async()
- *
- * The connection callback is executed asynchronously from the control thread
- * when the connection has been established. The connection callback should be
- * used to turn on or off interactions with any API call that communicates with
- * the audio server or starts/stops audio streams. The above is implemented by
- * cras_helper_create_connect_async().
- *
- * The following alternative (deprecated) initialization sequence can ensure
- * that the connection is established synchronously.
- *
- * Just connect to the server (no control thread):
- * cras_client_create()
- * cras_client_set_server_connection_cb() (optional)
- * one of:
- * cras_client_connect() (blocks forever)
- * or
- * cras_client_connect_timeout() (blocks for timeout)
- *
- * For API calls below that require the control thread to be running:
- * cras_client_run_thread();
- * cras_client_connected_wait(); (blocks up to 1 sec.)
- *
- * The above minus setting the connection callback is implemented within
- * cras_helper_create_connect().
- */
-
-#ifndef CRAS_CLIENT_H_
-#define CRAS_CLIENT_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <sys/select.h>
-
-#include "cras_iodev_info.h"
-#include "cras_types.h"
-#include "cras_util.h"
-
-struct cras_client;
-struct cras_hotword_handle;
-struct cras_stream_params;
-
-/* Callback for audio received or transmitted.
- * Args (All pointer will be valid - except user_arg, that's up to the user):
- * client: The client requesting service.
- * stream_id - Unique identifier for the stream needing data read/written.
- * samples - Read or write samples to/form here.
- * frames - Maximum number of frames to read or write.
- * sample_time - Playback time for the first sample read/written.
- * user_arg - Value passed to add_stream;
- * Return:
- * Returns the number of frames read or written on success, or a negative
- * number if there is a stream-fatal error. Returns EOF when the end of the
- * stream is reached.
- */
-typedef int (*cras_playback_cb_t)(struct cras_client *client,
- cras_stream_id_t stream_id, uint8_t *samples,
- size_t frames,
- const struct timespec *sample_time,
- void *user_arg);
-
-/* Callback for audio received and/or transmitted.
- * Args (All pointer will be valid - except user_arg, that's up to the user):
- * client: The client requesting service.
- * stream_id - Unique identifier for the stream needing data read/written.
- * captured_samples - Read samples form here.
- * playback_samples - Read or write samples to here.
- * frames - Maximum number of frames to read or write.
- * captured_time - Time the first sample was read.
- * playback_time - Playback time for the first sample written.
- * user_arg - Value passed to add_stream;
- * Return:
- * Returns the number of frames read or written on success, or a negative
- * number if there is a stream-fatal error. Returns EOF when the end of the
- * stream is reached.
- */
-typedef int (*cras_unified_cb_t)(struct cras_client *client,
- cras_stream_id_t stream_id,
- uint8_t *captured_samples,
- uint8_t *playback_samples, unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time,
- void *user_arg);
-
-/* Callback for handling stream errors.
- * Args:
- * client - The client created with cras_client_create().
- * stream_id - The ID for this stream.
- * error - The error code,
- * user_arg - The argument defined in cras_client_*_params_create().
- */
-typedef int (*cras_error_cb_t)(struct cras_client *client,
- cras_stream_id_t stream_id, int error,
- void *user_arg);
-
-/* Server connection status. */
-typedef enum cras_connection_status {
- CRAS_CONN_STATUS_FAILED,
- /* Resource allocation problem. Free resources, and retry the
- * connection with cras_client_connect_async(), or (blocking)
- * cras_client_connect(). Do not call cras_client_connect(),
- * cras_client_connect_timeout(), or cras_client_destroy()
- * from the callback. */
- CRAS_CONN_STATUS_DISCONNECTED,
- /* The control thread is attempting to reconnect to the
- * server in the background. Any attempt to access the
- * server will fail or block (see
- * cras_client_set_server_message_blocking(). */
- CRAS_CONN_STATUS_CONNECTED,
- /* Connection is established. All state change callbacks
- * have been re-registered, but audio streams must be
- * restarted, and node state data must be updated. */
-} cras_connection_status_t;
-
-/* Callback for handling server connection status.
- *
- * See also cras_client_set_connection_status_cb(). Do not call
- * cras_client_connect(), cras_client_connect_timeout(), or
- * cras_client_destroy() from this callback.
- *
- * Args:
- * client - The client created with cras_client_create().
- * status - The status of the connection to the server.
- * user_arg - The argument defined in
- * cras_client_set_connection_status_cb().
- */
-typedef void (*cras_connection_status_cb_t)(struct cras_client *client,
- cras_connection_status_t status,
- void *user_arg);
-
-/* Callback for setting thread priority. */
-typedef void (*cras_thread_priority_cb_t)(struct cras_client *client);
-
-/* Callback for handling get hotword models reply. */
-typedef void (*get_hotword_models_cb_t)(struct cras_client *client,
- const char *hotword_models);
-
-/* Callback to wait for a hotword trigger. */
-typedef void (*cras_hotword_trigger_cb_t)(struct cras_client *client,
- struct cras_hotword_handle *handle,
- void *user_data);
-
-/* Callback for handling hotword errors. */
-typedef int (*cras_hotword_error_cb_t)(struct cras_client *client,
- struct cras_hotword_handle *handle,
- int error, void *user_data);
-
-/*
- * Client handling.
- */
-
-/* Creates a new client.
- * Args:
- * client - Filled with a pointer to the new client.
- * Returns:
- * 0 on success (*client is filled with a valid cras_client pointer).
- * Negative error code on failure(*client will be NULL).
- */
-int cras_client_create(struct cras_client **client);
-
-/* Creates a new client with given connection type.
- * Args:
- * client - Filled with a pointer to the new client.
- * conn_type - enum CRAS_CONNECTION_TYPE
- *
- * Returns:
- * 0 on success (*client is filled with a valid cras_client pointer).
- * Negative error code on failure(*client will be NULL).
- */
-int cras_client_create_with_type(struct cras_client **client,
- enum CRAS_CONNECTION_TYPE conn_type);
-
-/* Destroys a client.
- * Args:
- * client - returned from "cras_client_create".
- */
-void cras_client_destroy(struct cras_client *client);
-
-/* Connects a client to the running server.
- * Waits forever (until interrupted or connected).
- * Args:
- * client - pointer returned from "cras_client_create".
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-int cras_client_connect(struct cras_client *client);
-
-/* Connects a client to the running server, retries until timeout.
- * Args:
- * client - pointer returned from "cras_client_create".
- * timeout_ms - timeout in milliseconds or negative to wait forever.
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-int cras_client_connect_timeout(struct cras_client *client,
- unsigned int timeout_ms);
-
-/* Begins running the client control thread.
- *
- * Required for stream operations and other operations noted below.
- *
- * Args:
- * client - the client to start (from cras_client_create).
- * Returns:
- * 0 on success or if the thread is already running, -EINVAL if the client
- * pointer is NULL, or the negative result of pthread_create().
- */
-int cras_client_run_thread(struct cras_client *client);
-
-/* Stops running a client.
- * This function is executed automatically by cras_client_destroy().
- * Args:
- * client - the client to stop (from cras_client_create).
- * Returns:
- * 0 on success or if the thread was already stopped, -EINVAL if the client
- * isn't valid.
- */
-int cras_client_stop(struct cras_client *client);
-
-/* Wait up to 1 second for the client thread to complete the server connection.
- *
- * After cras_client_run_thread() is executed, this function can be used to
- * ensure that the connection has been established with the server and ensure
- * that any information about the server is up to date. If
- * cras_client_run_thread() has not yet been executed, or cras_client_stop()
- * was executed and thread isn't running, then this function returns -EINVAL.
- *
- * Args:
- * client - pointer returned from "cras_client_create".
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-int cras_client_connected_wait(struct cras_client *client);
-
-/* Ask the client control thread to connect to the audio server.
- *
- * After cras_client_run_thread() is executed, this function can be used
- * to ask the control thread to connect to the audio server asynchronously.
- * The callback set with cras_client_set_connection_status_cb() will be
- * executed when the connection is established.
- *
- * Args:
- * client - The client from cras_client_create().
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- * -EINVAL if the client pointer is invalid or the control thread is
- * not running.
- */
-int cras_client_connect_async(struct cras_client *client);
-
-/* Sets server connection status callback.
- *
- * See cras_connection_status_t for a description of the connection states
- * and appropriate user action.
- *
- * Args:
- * client - The client from cras_client_create.
- * connection_cb - The callback function to register.
- * user_arg - Pointer that will be passed to the callback.
- */
-void cras_client_set_connection_status_cb(
- struct cras_client *client, cras_connection_status_cb_t connection_cb,
- void *user_arg);
-
-/* Sets callback for setting thread priority.
- * Args:
- * client - The client from cras_client_create.
- * cb - The thread priority callback.
- */
-void cras_client_set_thread_priority_cb(struct cras_client *client,
- cras_thread_priority_cb_t cb);
-
-/* Returns the current list of output devices.
- *
- * Requires that the connection to the server has been established.
- *
- * Data is copied and thus can become out of date. This call must be
- * re-executed to get updates.
- *
- * Args:
- * client - The client from cras_client_create.
- * devs - Array that will be filled with device info.
- * nodes - Array that will be filled with node info.
- * *num_devs - Maximum number of devices to put in the array.
- * *num_nodes - Maximum number of nodes to put in the array.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- * *num_devs is set to the actual number of devices info filled.
- * *num_nodes is set to the actual number of nodes info filled.
- */
-int cras_client_get_output_devices(const struct cras_client *client,
- struct cras_iodev_info *devs,
- struct cras_ionode_info *nodes,
- size_t *num_devs, size_t *num_nodes);
-
-/* Returns the current list of input devices.
- *
- * Requires that the connection to the server has been established.
- *
- * Data is copied and thus can become out of date. This call must be
- * re-executed to get updates.
- *
- * Args:
- * client - The client from cras_client_create.
- * devs - Array that will be filled with device info.
- * nodes - Array that will be filled with node info.
- * *num_devs - Maximum number of devices to put in the array.
- * *num_nodes - Maximum number of nodes to put in the array.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- * *num_devs is set to the actual number of devices info filled.
- * *num_nodes is set to the actual number of nodes info filled.
- */
-int cras_client_get_input_devices(const struct cras_client *client,
- struct cras_iodev_info *devs,
- struct cras_ionode_info *nodes,
- size_t *num_devs, size_t *num_nodes);
-
-/* Returns the current list of clients attached to the server.
- *
- * Requires that the connection to the server has been established.
- *
- * Data is copied and thus can become out of date. This call must be
- * re-executed to get updates.
- *
- * Args:
- * client - This client (from cras_client_create).
- * clients - Array that will be filled with a list of attached clients.
- * max_clients - Maximum number of clients to put in the array.
- * Returns:
- * The number of attached clients. This may be more that max_clients passed
- * in, this indicates that all of the clients wouldn't fit in the provided
- * array.
- */
-int cras_client_get_attached_clients(const struct cras_client *client,
- struct cras_attached_client_info *clients,
- size_t max_clients);
-
-/* Find a node info with the matching node id.
- *
- * Requires that the connection to the server has been established.
- *
- * Data is copied and thus can become out of date. This call must be
- * re-executed to get updates.
- *
- * Args:
- * client - This client (from cras_client_create).
- * input - Non-zero for input nodes, zero for output nodes.
- * node_id - The node id to look for.
- * node_info - The information about the ionode will be returned here.
- * Returns:
- * 0 if successful, negative on error; -ENOENT if the node cannot be found.
- */
-int cras_client_get_node_by_id(const struct cras_client *client, int input,
- const cras_node_id_t node_id,
- struct cras_ionode_info *node_info);
-
-/* Checks if the output device with the given name is currently plugged in.
- *
- * For internal devices this checks that jack state, for USB devices this will
- * always be true if they are present. The name parameter can be the complete
- * name or any unique prefix of the name. If the name is not unique the first
- * matching name will be checked.
- *
- * Requires that the connection to the server has been established.
- *
- * Data is copied and thus can become out of date. This call must be
- * re-executed to get updates.
- *
- * Args:
- * client - The client from cras_client_create.
- * name - Name of the device to check.
- * Returns:
- * 1 if the device exists and is plugged, 0 otherwise.
- */
-int cras_client_output_dev_plugged(const struct cras_client *client,
- const char *name);
-
-/* Set the value of an attribute of an ionode.
- *
- * Args:
- * client - The client from cras_client_create.
- * node_id - The id of the ionode.
- * attr - the attribute we want to change.
- * value - the value we want to set.
- * Returns:
- * Returns 0 for success, negative on error (from errno.h).
- */
-int cras_client_set_node_attr(struct cras_client *client,
- cras_node_id_t node_id, enum ionode_attr attr,
- int value);
-
-/* Select the preferred node for playback/capture.
- *
- * Args:
- * client - The client from cras_client_create.
- * direction - The direction of the ionode.
- * node_id - The id of the ionode. If node_id is the special value 0, then
- * the preference is cleared and cras will choose automatically.
- */
-int cras_client_select_node(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/* Adds an active node for playback/capture.
- *
- * Args:
- * client - The client from cras_client_create.
- * direction - The direction of the ionode.
- * node_id - The id of the ionode. If there's no node matching given
- * id, nothing will happen in CRAS.
- */
-int cras_client_add_active_node(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/* Removes an active node for playback/capture.
- *
- * Args:
- * client - The client from cras_client_create.
- * direction - The direction of the ionode.
- * node_id - The id of the ionode. If there's no node matching given
- * id, nothing will happen in CRAS.
- */
-int cras_client_rm_active_node(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/* Asks the server to reload dsp plugin configuration from the ini file.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- */
-int cras_client_reload_dsp(struct cras_client *client);
-
-/* Asks the server to dump current dsp information to syslog.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- */
-int cras_client_dump_dsp_info(struct cras_client *client);
-
-/* Asks the server to dump current audio thread information.
- *
- * Args:
- * client - The client from cras_client_create.
- * cb - A function to call when the data is received.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- */
-int cras_client_update_audio_debug_info(struct cras_client *client,
- void (*cb)(struct cras_client *));
-
-/* Asks the server to dump current main thread information.
- * Args:
- * client - The client from cras_client_create.
- * cb - A function to call when the data is received.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- */
-int cras_client_update_main_thread_debug_info(struct cras_client *client,
- void (*cb)(struct cras_client *));
-
-/* Asks the server to dump bluetooth debug information.
- * Args:
- * client - The client from cras_client_create.
- * cb - Function to call when debug info is ready.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- */
-int cras_client_update_bt_debug_info(struct cras_client *client,
- void (*cb)(struct cras_client *));
-
-/* Gets read-only access to audio thread log. Should be called once before
- calling cras_client_read_atlog.
- * Args:
- * client - The client from cras_client_create.
- * atlog_access_cb - Function to call after getting atlog access.
- * Returns:
- * 0 on success, -EINVAL if the client or atlog_access_cb isn't valid.
- */
-int cras_client_get_atlog_access(struct cras_client *client,
- void (*atlog_access_cb)(struct cras_client *));
-
-/* Reads continuous audio thread log into 'buf', starting from 'read_idx'-th log
- * till the latest. The number of missing logs within the range will be stored
- * in 'missing'. Requires calling cras_client_get_atlog_access() beforehand
- * to get access to audio thread log.
- * Args:
- * client - The client from cras_client_create.
- * read_idx - The log number to start reading with.
- * missing - The pointer to store the number of missing logs.
- * buf - The buffer to which continuous logs will be copied.
- * Returns:
- * The number of logs copied. < 0 if failed to read audio thread log.
- */
-int cras_client_read_atlog(struct cras_client *client, uint64_t *read_idx,
- uint64_t *missing,
- struct audio_thread_event_log *buf);
-
-/* Asks the server to dump current audio thread snapshots.
- *
- * Args:
- * client - The client from cras_client_create.
- * cb - A function to call when the data is received.
- * Returns:
- * 0 on success, -EINVAL if the client isn't valid or isn't running.
- */
-int cras_client_update_audio_thread_snapshots(struct cras_client *client,
- void (*cb)(struct cras_client *));
-
-/* Gets the max supported channel count of the output device from node_id.
- * Args:
- * client - The client from cras_client_create.
- * node_id - ID of the node.
- * max_channels - Out parameter will be filled with the max supported channel
- * count.
- * Returns:
- * 0 on success, or negative error code on failure.
- */
-int cras_client_get_max_supported_channels(const struct cras_client *client,
- cras_node_id_t node_id,
- uint32_t *max_channels);
-
-/*
- * Stream handling.
- */
-
-/* Setup stream configuration parameters.
- * Args:
- * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT).
- * buffer_frames - total number of audio frames to buffer (dictates latency).
- * cb_threshold - For playback, call back for more data when the buffer
- * reaches this level. For capture, this is ignored (Audio callback will
- * be called when buffer_frames have been captured).
- * unused - No longer used.
- * stream_type - media or talk (currently only support "default").
- * flags - Currently only used for CRAS_INPUT_STREAM_FLAG.
- * user_data - Pointer that will be passed to the callback.
- * aud_cb - Called when audio is needed(playback) or ready(capture). Allowed
- * return EOF to indicate that the stream should terminate.
- * err_cb - Called when there is an error with the stream.
- * format - The format of the audio stream. Specifies bits per sample,
- * number of channels, and sample rate.
- */
-struct cras_stream_params *cras_client_stream_params_create(
- enum CRAS_STREAM_DIRECTION direction, size_t buffer_frames,
- size_t cb_threshold, size_t unused, enum CRAS_STREAM_TYPE stream_type,
- uint32_t flags, void *user_data, cras_playback_cb_t aud_cb,
- cras_error_cb_t err_cb, struct cras_audio_format *format);
-
-/* Functions to set the client type on given stream parameter.
- * Args:
- * params - Stream configuration parameters.
- * client_type - A client type.
- */
-void cras_client_stream_params_set_client_type(
- struct cras_stream_params *params, enum CRAS_CLIENT_TYPE client_type);
-
-/* Functions to enable or disable specific effect on given stream parameter.
- * Args:
- * params - Stream configuration parameters.
- */
-void cras_client_stream_params_enable_aec(struct cras_stream_params *params);
-void cras_client_stream_params_disable_aec(struct cras_stream_params *params);
-void cras_client_stream_params_enable_ns(struct cras_stream_params *params);
-void cras_client_stream_params_disable_ns(struct cras_stream_params *params);
-void cras_client_stream_params_enable_agc(struct cras_stream_params *params);
-void cras_client_stream_params_disable_agc(struct cras_stream_params *params);
-void cras_client_stream_params_enable_vad(struct cras_stream_params *params);
-void cras_client_stream_params_disable_vad(struct cras_stream_params *params);
-
-/* Setup stream configuration parameters. DEPRECATED.
- * TODO(crbug.com/972928): remove this
- * Use cras_client_stream_params_create instead.
- * Args:
- * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT) or
- * loopback(CRAS_STREAM_POST_MIX_PRE_DSP).
- * block_size - The number of frames per callback(dictates latency).
- * stream_type - media or talk (currently only support "default").
- * flags - None currently used.
- * user_data - Pointer that will be passed to the callback.
- * unified_cb - Called to request audio data or to notify the client when
- * captured audio is available. Though this is a unified_cb,
- * only one direction will be used for a stream, depending
- * on the 'direction' parameter.
- * err_cb - Called when there is an error with the stream.
- * format - The format of the audio stream. Specifies bits per sample,
- * number of channels, and sample rate.
- */
-struct cras_stream_params *cras_client_unified_params_create(
- enum CRAS_STREAM_DIRECTION direction, unsigned int block_size,
- enum CRAS_STREAM_TYPE stream_type, uint32_t flags, void *user_data,
- cras_unified_cb_t unified_cb, cras_error_cb_t err_cb,
- struct cras_audio_format *format);
-
-/* Destroy stream params created with cras_client_stream_params_create. */
-void cras_client_stream_params_destroy(struct cras_stream_params *params);
-
-/* Creates a new stream and return the stream id or < 0 on error.
- *
- * Requires execution of cras_client_run_thread(), and an active connection
- * to the audio server.
- *
- * Args:
- * client - The client to add the stream to (from cras_client_create).
- * stream_id_out - On success will be filled with the new stream id.
- * Guaranteed to be set before any callbacks are made.
- * config - The cras_stream_params struct specifying the parameters for the
- * stream.
- * Returns:
- * 0 on success, negative error code on failure (from errno.h).
- */
-int cras_client_add_stream(struct cras_client *client,
- cras_stream_id_t *stream_id_out,
- struct cras_stream_params *config);
-
-/* Creates a pinned stream and return the stream id or < 0 on error.
- *
- * Requires execution of cras_client_run_thread(), and an active connection
- * to the audio server.
- *
- * Args:
- * client - The client to add the stream to (from cras_client_create).
- * dev_idx - Index of the device to attach the newly created stream.
- * stream_id_out - On success will be filled with the new stream id.
- * Guaranteed to be set before any callbacks are made.
- * config - The cras_stream_params struct specifying the parameters for the
- * stream.
- * Returns:
- * 0 on success, negative error code on failure (from errno.h).
- */
-int cras_client_add_pinned_stream(struct cras_client *client, uint32_t dev_idx,
- cras_stream_id_t *stream_id_out,
- struct cras_stream_params *config);
-
-/* Removes a currently playing/capturing stream.
- *
- * Requires execution of cras_client_run_thread().
- *
- * Args:
- * client - Client to remove the stream (returned from cras_client_create).
- * stream_id - ID returned from cras_client_add_stream to identify the stream
- to remove.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-int cras_client_rm_stream(struct cras_client *client,
- cras_stream_id_t stream_id);
-
-/* Sets the volume scaling factor for the given stream.
- *
- * Requires execution of cras_client_run_thread().
- *
- * Args:
- * client - Client owning the stream.
- * stream_id - ID returned from cras_client_add_stream.
- * volume_scaler - 0.0-1.0 the new value to scale this stream by.
- */
-int cras_client_set_stream_volume(struct cras_client *client,
- cras_stream_id_t stream_id,
- float volume_scaler);
-
-/*
- * System level functions.
- */
-
-/* Sets the volume of the system.
- *
- * Volume here ranges from 0 to 100, and will be translated to dB based on the
- * output-specific volume curve.
- *
- * Args:
- * client - The client from cras_client_create.
- * volume - 0-100 the new volume index.
- * Returns:
- * 0 for success, -EPIPE if there is an I/O error talking to the server, or
- * -EINVAL if 'client' is invalid.
- */
-int cras_client_set_system_volume(struct cras_client *client, size_t volume);
-
-/* Sets the mute state of the system.
- *
- * Args:
- * client - The client from cras_client_create.
- * mute - 0 is un-mute, 1 is muted.
- * Returns:
- * 0 for success, -EPIPE if there is an I/O error talking to the server, or
- * -EINVAL if 'client' is invalid.
- */
-int cras_client_set_system_mute(struct cras_client *client, int mute);
-
-/* Sets the user mute state of the system.
- *
- * This is used for mutes caused by user interaction. Like the mute key.
- *
- * Args:
- * client - The client from cras_client_create.
- * mute - 0 is un-mute, 1 is muted.
- * Returns:
- * 0 for success, -EPIPE if there is an I/O error talking to the server, or
- * -EINVAL if 'client' is invalid.
- */
-int cras_client_set_user_mute(struct cras_client *client, int mute);
-
-/* Sets the mute locked state of the system.
- *
- * Changing mute state is impossible when this flag is set to locked.
- *
- * Args:
- * client - The client from cras_client_create.
- * locked - 0 is un-locked, 1 is locked.
- * Returns:
- * 0 for success, -EPIPE if there is an I/O error talking to the server, or
- * -EINVAL if 'client' is invalid.
- */
-int cras_client_set_system_mute_locked(struct cras_client *client, int locked);
-
-/* Sets the capture mute state of the system.
- *
- * Recordings will be muted when this is set.
- *
- * Args:
- * client - The client from cras_client_create.
- * mute - 0 is un-mute, 1 is muted.
- * Returns:
- * 0 for success, -EPIPE if there is an I/O error talking to the server, or
- * -EINVAL if 'client' is invalid.
- */
-int cras_client_set_system_capture_mute(struct cras_client *client, int mute);
-
-/* Sets the capture mute locked state of the system.
- *
- * Changing mute state is impossible when this flag is set to locked.
- *
- * Args:
- * client - The client from cras_client_create.
- * locked - 0 is un-locked, 1 is locked.
- * Returns:
- * 0 for success, -EPIPE if there is an I/O error talking to the server, or
- * -EINVAL if 'client' is invalid.
- */
-int cras_client_set_system_capture_mute_locked(struct cras_client *client,
- int locked);
-
-/* Gets the current system volume.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * The current system volume between 0 and 100.
- */
-size_t cras_client_get_system_volume(const struct cras_client *client);
-
-/* Gets the current system mute state.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * 0 if not muted, 1 if it is.
- */
-int cras_client_get_system_muted(const struct cras_client *client);
-
-/* Gets the current user mute state.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * 0 if not muted, 1 if it is.
- */
-int cras_client_get_user_muted(const struct cras_client *client);
-
-/* Gets the current system capture mute state.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * 0 if capture is not muted, 1 if it is.
- */
-int cras_client_get_system_capture_muted(const struct cras_client *client);
-
-/* Gets the current minimum system volume.
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * The minimum value for the current output device in dBFS * 100. This is
- * the level of attenuation at volume == 1.
- */
-long cras_client_get_system_min_volume(const struct cras_client *client);
-
-/* Gets the current maximum system volume.
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * The maximum value for the current output device in dBFS * 100. This is
- * the level of attenuation at volume == 100.
- */
-long cras_client_get_system_max_volume(const struct cras_client *client);
-
-/* Gets the default output buffer size.
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * Default output buffer size in frames. A negative error on failure.
- */
-int cras_client_get_default_output_buffer_size(struct cras_client *client);
-
-/* Gets audio debug info.
- *
- * Requires that the connection to the server has been established.
- * Access to the resulting pointer is not thread-safe.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * A pointer to the debug info. This info is only updated when requested by
- * calling cras_client_update_audio_debug_info.
- */
-const struct audio_debug_info *
-cras_client_get_audio_debug_info(const struct cras_client *client);
-
-/* Gets bluetooth debug info.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * A pointer to the debug info. This info is updated and requested by
- * calling cras_client_update_bt_debug_info.
- */
-const struct cras_bt_debug_info *
-cras_client_get_bt_debug_info(const struct cras_client *client);
-
-/* Gets main thread debug info.
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * A pointer to the debug info. This info is updated and requested by
- * calling cras_client_update_main_thread_debug_info.
- */
-const struct main_thread_debug_info *
-cras_client_get_main_thread_debug_info(const struct cras_client *client);
-
-/* Gets audio thread snapshot buffer.
- *
- * Requires that the connection to the server has been established.
- * Access to the resulting pointer is not thread-safe.
- *
- * Args:
- * client - The client from cras_client_create.
- * Returns:
- * A pointer to the snapshot buffer. This info is only updated when
- * requested by calling cras_client_update_audio_thread_snapshots.
- */
-const struct cras_audio_thread_snapshot_buffer *
-cras_client_get_audio_thread_snapshot_buffer(const struct cras_client *client);
-
-/* Gets the number of streams currently attached to the server.
- *
- * This is the total number of capture and playback streams. If the ts argument
- * is not null, then it will be filled with the last time audio was played or
- * recorded. ts will be set to the current time if streams are currently
- * active.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * ts - Filled with the timestamp of the last stream.
- * Returns:
- * The number of active streams.
- */
-unsigned cras_client_get_num_active_streams(const struct cras_client *client,
- struct timespec *ts);
-
-/*
- * Utility functions.
- */
-
-/* Returns the number of bytes in an audio frame for a stream.
- * Args:
- * format - The format of the audio stream. Specifies bits per sample,
- * number of channels, and sample rate.
- * Returns:
- * Positive number of bytes in a frame, or a negative error code if fmt is
- * NULL.
- */
-int cras_client_format_bytes_per_frame(struct cras_audio_format *fmt);
-
-/* For playback streams, calculates the latency of the next sample written.
- * Only valid when called from the audio callback function for the stream
- * (aud_cb).
- * Args:
- * sample_time - The sample time stamp passed in to aud_cb.
- * delay - Out parameter will be filled with the latency.
- * Returns:
- * 0 on success, -EINVAL if delay is NULL.
- */
-int cras_client_calc_playback_latency(const struct timespec *sample_time,
- struct timespec *delay);
-
-/* For capture returns the latency of the next frame to be read from the buffer
- * (based on when it was captured). Only valid when called from the audio
- * callback function for the stream (aud_cb).
- * Args:
- * sample_time - The sample time stamp passed in to aud_cb.
- * delay - Out parameter will be filled with the latency.
- * Returns:
- * 0 on success, -EINVAL if delay is NULL.
- */
-int cras_client_calc_capture_latency(const struct timespec *sample_time,
- struct timespec *delay);
-
-/* Set the volume of the given output node. Only for output nodes.
- *
- * Args:
- * client - The client from cras_client_create.
- * node_id - ID of the node.
- * volume - New value for node volume.
- */
-int cras_client_set_node_volume(struct cras_client *client,
- cras_node_id_t node_id, uint8_t volume);
-
-/* Swap the left and right channel of the given node.
- *
- * Args:
- * client - The client from cras_client_create.
- * node_id - ID of the node.
- * enable - 1 to enable swap mode, 0 to disable.
- */
-int cras_client_swap_node_left_right(struct cras_client *client,
- cras_node_id_t node_id, int enable);
-
-/* Set the capture gain of the given input node. Only for input nodes.
- *
- * Args:
- * client - The client from cras_client_create.
- * node_id - ID of the node.
- * gain - New capture gain for the node, in range (0, 100) which will
- * linearly maps to (-4000, 4000) 100*dBFS.
- */
-int cras_client_set_node_capture_gain(struct cras_client *client,
- cras_node_id_t node_id, long gain);
-
-/* Add a test iodev to the iodev list.
- *
- * Args:
- * client - The client from cras_client_create.
- * type - The type of test iodev, see cras_types.h
- */
-int cras_client_add_test_iodev(struct cras_client *client,
- enum TEST_IODEV_TYPE type);
-
-/* Send a test command to a test iodev.
- *
- * Args:
- * client - The client from cras_client_create.
- * iodev_idx - The index of the test iodev.
- * command - The command to send.
- * data_len - Length of command data.
- * data - Command data.
- */
-int cras_client_test_iodev_command(struct cras_client *client,
- unsigned int iodev_idx,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len, const uint8_t *data);
-
-/* Finds the first node of the given type.
- *
- * This is used for finding a special hotword node.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * type - The type of device to find.
- * direction - Search input or output devices.
- * node_id - The found node on success.
- * Returns:
- * 0 on success, a negative error on failure.
- */
-int cras_client_get_first_node_type_idx(const struct cras_client *client,
- enum CRAS_NODE_TYPE type,
- enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t *node_id);
-
-/* Finds the first device that contains a node of the given type.
- *
- * This is used for finding a special hotword device.
- *
- * Requires that the connection to the server has been established.
- *
- * Args:
- * client - The client from cras_client_create.
- * type - The type of device to find.
- * direction - Search input or output devices.
- * Returns the device index of a negative error on failure.
- */
-int cras_client_get_first_dev_type_idx(const struct cras_client *client,
- enum CRAS_NODE_TYPE type,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Sets the suspend state of audio playback and capture.
- *
- * Set this before putting the system into suspend.
- *
- * Args:
- * client - The client from cras_client_create.
- * suspend - Suspend the system if non-zero, otherwise resume.
- */
-int cras_client_set_suspend(struct cras_client *client, int suspend);
-
-/* Configures the global converter for output remixing.
- *
- * Args:
- * client - The client from cras_client_create.
- * num_channels - Number of output channels.
- * coefficient - Float array representing |num_channels| * |num_channels|
- * matrix. Channels of mixed PCM output will be remixed by
- * multiplying this matrix.
- */
-int cras_client_config_global_remix(struct cras_client *client,
- unsigned num_channels, float *coefficient);
-
-/* Gets the set of supported hotword language models on a node. The supported
- * models may differ on different nodes.
- *
- * Args:
- * client - The client from cras_client_create.
- * node_id - ID of a hotword input node (CRAS_NODE_TYPE_HOTWORD).
- * cb - The function to be called when hotword models are ready.
- * Returns:
- * 0 on success.
- */
-int cras_client_get_hotword_models(struct cras_client *client,
- cras_node_id_t node_id,
- get_hotword_models_cb_t cb);
-
-/* Sets the hotword language model on a node. If there are existing streams on
- * the hotword input node when this function is called, they need to be closed
- * then re-opend for the model change to take effect.
- * Args:
- * client - The client from cras_client_create.
- * node_id - ID of a hotword input node (CRAS_NODE_TYPE_HOTWORD).
- * model_name - Name of the model to use, e.g. "en_us".
- * Returns:
- * 0 on success.
- * -EINVAL if client or node_id is invalid.
- * -ENOENT if the specified model is not found.
- */
-int cras_client_set_hotword_model(struct cras_client *client,
- cras_node_id_t node_id,
- const char *model_name);
-
-/*
- * Creates a hotword stream and waits for the hotword to trigger.
- *
- * Args:
- * client - The client to add the stream to (from cras_client_create).
- * user_data - Pointer that will be passed to the callback.
- * trigger_cb - Called when a hotword is triggered.
- * err_cb - Called when there is an error with the stream.
- * handle_out - On success will be filled with a cras_hotword_handle.
- * Returns:
- * 0 on success, negative error code on failure (from errno.h).
- */
-int cras_client_enable_hotword_callback(
- struct cras_client *client, void *user_data,
- cras_hotword_trigger_cb_t trigger_cb, cras_hotword_error_cb_t err_cb,
- struct cras_hotword_handle **handle_out);
-
-/*
- * Closes a hotword stream that was created by cras_client_wait_for_hotword.
- *
- * Args:
- * client - Client to remove the stream (returned from cras_client_create).
- * handle - cras_hotword_handle returned from cras_client_wait_for_hotword.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-int cras_client_disable_hotword_callback(struct cras_client *client,
- struct cras_hotword_handle *handle);
-
-/* Starts or stops the aec dump task on server side.
- * Args:
- * client - The client from cras_client_create.
- * stream_id - The id of the input stream running with aec effect.
- * start - True to start APM debugging, otherwise to stop it.
- * fd - File descriptor of the file to store aec dump result.
- */
-int cras_client_set_aec_dump(struct cras_client *client,
- cras_stream_id_t stream_id, int start, int fd);
-/*
- * Reloads the aec.ini config file on server side.
- */
-int cras_client_reload_aec_config(struct cras_client *client);
-
-/*
- * Returns if AEC is supported.
- */
-int cras_client_get_aec_supported(struct cras_client *client);
-
-/*
- * Returns the AEC group ID if available.
- */
-int cras_client_get_aec_group_id(struct cras_client *client);
-
-/*
- * Sets the flag to enable bluetooth wideband speech in server.
- */
-int cras_client_set_bt_wbs_enabled(struct cras_client *client, bool enabled);
-
-/* Set the context pointer for system state change callbacks.
- * Args:
- * client - The client from cras_client_create.
- * context - The context pointer passed to all callbacks.
- */
-void cras_client_set_state_change_callback_context(struct cras_client *client,
- void *context);
-
-/* Output volume change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * volume - The system output volume, ranging from 0 to 100.
- */
-typedef void (*cras_client_output_volume_changed_callback)(void *context,
- int32_t volume);
-
-/* Output mute change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * muted - Non-zero when the audio is muted, zero otherwise.
- * user_muted - Non-zero when the audio has been muted by the
- * user, zero otherwise.
- * mute_locked - Non-zero when the mute funcion is locked,
- * zero otherwise.
- */
-typedef void (*cras_client_output_mute_changed_callback)(void *context,
- int muted,
- int user_muted,
- int mute_locked);
-
-/* Capture gain change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * gain - The system capture gain, in centi-decibels.
- */
-typedef void (*cras_client_capture_gain_changed_callback)(void *context,
- int32_t gain);
-
-/* Capture mute change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * muted - Non-zero when the audio is muted, zero otherwise.
- * mute_locked - Non-zero when the mute funcion is locked,
- * zero otherwise.
- */
-typedef void (*cras_client_capture_mute_changed_callback)(void *context,
- int muted,
- int mute_locked);
-
-/* Nodes change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- */
-typedef void (*cras_client_nodes_changed_callback)(void *context);
-
-/* Active node change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * direction - Indicates the direction of the selected node.
- * node_id - The ID of the selected node. Special device ID values
- * defined by CRAS_SPECIAL_DEVICE will be used when no other
- * device or node is selected or between selections.
- */
-typedef void (*cras_client_active_node_changed_callback)(
- void *context, enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/* Output node volume change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * node_id - The ID of the output node.
- * volume - The volume for this node with range 0 to 100.
- */
-typedef void (*cras_client_output_node_volume_changed_callback)(
- void *context, cras_node_id_t node_id, int32_t volume);
-
-/* Node left right swapped change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * node_id - The ID of the node.
- * swapped - Non-zero if the node is left-right swapped, zero otherwise.
- */
-typedef void (*cras_client_node_left_right_swapped_changed_callback)(
- void *context, cras_node_id_t node_id, int swapped);
-
-/* Input node gain change callback.
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * node_id - The ID of the input node.
- * gain - The gain for this node in centi-decibels.
- */
-typedef void (*cras_client_input_node_gain_changed_callback)(
- void *context, cras_node_id_t node_id, int32_t gain);
-
-/* Number of active streams change callback.
- *
- * Args:
- * context - Context pointer set with
- * cras_client_set_state_change_callback_context().
- * direction - Indicates the direction of the stream's node.
- * num_active_streams - The number of active streams.
- */
-typedef void (*cras_client_num_active_streams_changed_callback)(
- void *context, enum CRAS_STREAM_DIRECTION direction,
- uint32_t num_active_streams);
-
-/* Set system state information callbacks.
- * NOTE: These callbacks are executed from the client control thread.
- * Each state change callback is given the context pointer set with
- * cras_client_set_state_change_callback_context(). The context pointer is
- * NULL by default.
- * Args:
- * client - The client from cras_client_create.
- * cb - The callback, or NULL to disable the call-back.
- * Returns:
- * 0 for success or negative errno error code on error.
- */
-int cras_client_set_output_volume_changed_callback(
- struct cras_client *client,
- cras_client_output_volume_changed_callback cb);
-int cras_client_set_output_mute_changed_callback(
- struct cras_client *client,
- cras_client_output_mute_changed_callback cb);
-int cras_client_set_capture_gain_changed_callback(
- struct cras_client *client,
- cras_client_capture_gain_changed_callback cb);
-int cras_client_set_capture_mute_changed_callback(
- struct cras_client *client,
- cras_client_capture_mute_changed_callback cb);
-int cras_client_set_nodes_changed_callback(
- struct cras_client *client, cras_client_nodes_changed_callback cb);
-int cras_client_set_active_node_changed_callback(
- struct cras_client *client,
- cras_client_active_node_changed_callback cb);
-int cras_client_set_output_node_volume_changed_callback(
- struct cras_client *client,
- cras_client_output_node_volume_changed_callback cb);
-int cras_client_set_node_left_right_swapped_changed_callback(
- struct cras_client *client,
- cras_client_node_left_right_swapped_changed_callback cb);
-int cras_client_set_input_node_gain_changed_callback(
- struct cras_client *client,
- cras_client_input_node_gain_changed_callback cb);
-int cras_client_set_num_active_streams_changed_callback(
- struct cras_client *client,
- cras_client_num_active_streams_changed_callback cb);
-
-/*
- * The functions below prefixed with libcras wrap the original CRAS library
- * They provide an interface that maps the pointers to the functions above.
- * Please add a new function instead of modifying the existing function.
- * Here are some rules about how to add a new function:
- * 1. Increase the CRAS_API_VERSION by 1.
- * 2. Write a new function in cras_client.c.
- * 3. Append the corresponding pointer to the structure. Remeber DO NOT change
- * the order of functions in the structs.
- * 4. Assign the pointer to the new function in cras_client.c.
- * 5. Create the inline function in cras_client.h, which is used by clients.
- * Remember to add DISABLE_CFI_ICALL on the inline function.
- * 6. Add CHECK_VERSION in the inline function. If the api_version is smaller
- * than the supported version, this inline function will return -ENOSYS.
- */
-
-#define CRAS_API_VERSION 1
-#define CHECK_VERSION(object, version) \
- if (object->api_version < version) { \
- return -ENOSYS; \
- }
-
-/*
- * The inline functions use the indirect function call. Therefore, they are
- * incompatible with CFI-icall.
- */
-#define DISABLE_CFI_ICALL __attribute__((no_sanitize("cfi-icall")))
-
-struct libcras_node_info {
- int api_version;
- struct cras_node_info *node_;
- int (*get_id)(struct cras_node_info *node, uint64_t *id);
- int (*get_dev_idx)(struct cras_node_info *node, uint32_t *dev_idx);
- int (*get_node_idx)(struct cras_node_info *node, uint32_t *node_idx);
- int (*get_max_supported_channels)(struct cras_node_info *node,
- uint32_t *max_supported_channels);
- int (*is_plugged)(struct cras_node_info *node, bool *plugged);
- int (*is_active)(struct cras_node_info *node, bool *active);
- int (*get_type)(struct cras_node_info *node, char **name);
- int (*get_node_name)(struct cras_node_info *node, char **name);
- int (*get_dev_name)(struct cras_node_info *node, char **name);
-};
-
-struct libcras_client {
- int api_version;
- struct cras_client *client_;
- int (*connect)(struct cras_client *client);
- int (*connect_timeout)(struct cras_client *client,
- unsigned int timeout_ms);
- int (*connected_wait)(struct cras_client *client);
- int (*run_thread)(struct cras_client *client);
- int (*stop)(struct cras_client *client);
- int (*add_pinned_stream)(struct cras_client *client, uint32_t dev_idx,
- cras_stream_id_t *stream_id_out,
- struct cras_stream_params *config);
- int (*rm_stream)(struct cras_client *client,
- cras_stream_id_t stream_id);
- int (*set_stream_volume)(struct cras_client *client,
- cras_stream_id_t stream_id,
- float volume_scaler);
- int (*get_nodes)(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- struct libcras_node_info ***nodes, size_t *num);
- int (*get_default_output_buffer_size)(struct cras_client *client,
- int *size);
- int (*get_aec_group_id)(struct cras_client *client, int *id);
- int (*get_aec_supported)(struct cras_client *client, int *supported);
- int (*get_system_muted)(struct cras_client *client, int *muted);
- int (*set_system_mute)(struct cras_client *client, int mute);
- int (*get_loopback_dev_idx)(struct cras_client *client, int *idx);
-};
-
-struct cras_stream_cb_data;
-struct libcras_stream_cb_data {
- int api_version;
- struct cras_stream_cb_data *data_;
- int (*get_stream_id)(struct cras_stream_cb_data *data,
- cras_stream_id_t *id);
- int (*get_buf)(struct cras_stream_cb_data *data, uint8_t **buf);
- int (*get_frames)(struct cras_stream_cb_data *data,
- unsigned int *frames);
- int (*get_latency)(struct cras_stream_cb_data *data,
- struct timespec *latency);
- int (*get_user_arg)(struct cras_stream_cb_data *data, void **user_arg);
-};
-typedef int (*libcras_stream_cb_t)(struct libcras_stream_cb_data *data);
-
-struct libcras_stream_params {
- int api_version;
- struct cras_stream_params *params_;
- int (*set)(struct cras_stream_params *params,
- enum CRAS_STREAM_DIRECTION direction, size_t buffer_frames,
- size_t cb_threshold, enum CRAS_STREAM_TYPE stream_type,
- enum CRAS_CLIENT_TYPE client_type, uint32_t flags,
- void *user_data, libcras_stream_cb_t stream_cb,
- cras_error_cb_t err_cb, size_t rate, snd_pcm_format_t format,
- size_t num_channels);
- int (*set_channel_layout)(struct cras_stream_params *params, int length,
- const int8_t *layout);
- void (*enable_aec)(struct cras_stream_params *params);
-};
-
-/*
- * Creates a new client.
- * Returns:
- * If success, return a valid libcras_client pointer. Otherwise, return
- * NULL.
- */
-struct libcras_client *libcras_client_create();
-
-/*
- * Destroys a client.
- * Args:
- * client - pointer returned from "libcras_client_create".
- */
-void libcras_client_destroy(struct libcras_client *client);
-
-/*
- * Connects a client to the running server.
- * Waits forever (until interrupted or connected).
- * Args:
- * client - pointer returned from "libcras_client_create".
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_connect(struct libcras_client *client)
-{
- return client->connect(client->client_);
-}
-
-/*
- * Connects a client to the running server, retries until timeout.
- * Args:
- * client - pointer returned from "libcras_client_create".
- * timeout_ms - timeout in milliseconds or negative to wait forever.
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_connect_timeout(struct libcras_client *client,
- unsigned int timeout_ms)
-{
- return client->connect_timeout(client->client_, timeout_ms);
-}
-
-/*
- * Wait up to 1 second for the client thread to complete the server connection.
- *
- * After libcras_client_run_thread() is executed, this function can be
- * used to ensure that the connection has been established with the server and
- * ensure that any information about the server is up to date. If
- * libcras_client_run_thread() has not yet been executed, or
- * libcras_client_stop() was executed and thread isn't running, then this
- * function returns -EINVAL.
- *
- * Args:
- * client - pointer returned from "libcras_client_create".
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_connected_wait(struct libcras_client *client)
-{
- return client->connected_wait(client->client_);
-}
-
-/*
- * Begins running the client control thread.
- *
- * Required for stream operations and other operations noted below.
- *
- * Args:
- * client - pointer returned from "libcras_client_create".
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_run_thread(struct libcras_client *client)
-{
- return client->run_thread(client->client_);
-}
-
-/*
- * Stops running a client.
- * This function is executed automatically by cras_client_destroy().
- * Args:
- * client - pointer returned from "libcras_client_create".
- * Returns:
- * 0 on success or if the thread was already stopped, -EINVAL if the client
- * isn't valid.
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_stop(struct libcras_client *client)
-{
- return client->stop(client->client_);
-}
-
-/*
- * Creates a pinned stream and return the stream id or < 0 on error.
- *
- * Requires execution of libcras_client_run_thread(), and an active
- * connection to the audio server.
- *
- * Args:
- * client - pointer returned from "libcras_client_create".
- * dev_idx - Index of the device to attach the newly created stream.
- * stream_id_out - On success will be filled with the new stream id.
- * Guaranteed to be set before any callbacks are made.
- * params - The pointer specifying the parameters for the stream.
- * (returned from libcras_stream_params_create)
- * Returns:
- * 0 on success, negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_add_pinned_stream(
- struct libcras_client *client, uint32_t dev_idx,
- cras_stream_id_t *stream_id_out, struct libcras_stream_params *params)
-{
- return client->add_pinned_stream(client->client_, dev_idx,
- stream_id_out, params->params_);
-}
-
-/*
- * Removes a currently playing/capturing stream.
- *
- * Requires execution of libcras_client_run_thread().
- *
- * Args:
- * client - pointer returned from "libcras_client_create".
- * stream_id - ID returned from libcras_client_add_stream to identify
- * the stream to remove.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_rm_stream(struct libcras_client *client,
- cras_stream_id_t stream_id)
-{
- return client->rm_stream(client->client_, stream_id);
-}
-
-/*
- * Sets the volume scaling factor for the given stream.
- *
- * Requires execution of cras_client_run_thread().
- *
- * Args:
- * client - pointer returned from "libcras_client_create".
- * stream_id - ID returned from libcras_client_add_stream.
- * volume_scaler - 0.0-1.0 the new value to scale this stream by.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_set_stream_volume(struct libcras_client *client,
- cras_stream_id_t stream_id,
- float volume_scaler)
-{
- return client->set_stream_volume(client->client_, stream_id,
- volume_scaler);
-}
-
-/*
- * Gets the current list of audio nodes.
- *
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * direction - Input or output.
- * nodes - Array that will be filled with libcras_node_info pointers.
- * num - Pointer to store the size of the array.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- * Remember to call libcras_node_info_array_destroy to free the array.
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_get_nodes(struct libcras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- struct libcras_node_info ***nodes,
- size_t *num)
-{
- return client->get_nodes(client->client_, direction, nodes, num);
-}
-
-/*
- * Gets the default output buffer size.
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * size - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_client_get_default_output_buffer_size(struct libcras_client *client,
- int *size)
-{
- return client->get_default_output_buffer_size(client->client_, size);
-}
-
-/*
- * Gets the AEC group ID.
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * id - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_get_aec_group_id(struct libcras_client *client,
- int *id)
-{
- return client->get_aec_group_id(client->client_, id);
-}
-
-/*
- * Gets whether AEC is supported.
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * supported - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_get_aec_supported(struct libcras_client *client,
- int *supported)
-{
- return client->get_aec_supported(client->client_, supported);
-}
-
-/*
- * Gets whether the system is muted.
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * muted - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_get_system_muted(struct libcras_client *client,
- int *muted)
-{
- return client->get_aec_group_id(client->client_, muted);
-}
-
-/*
- * Mutes or unmutes the system.
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * mute - 1 is to mute and 0 is to unmute.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_set_system_mute(struct libcras_client *client,
- int mute)
-{
- return client->set_system_mute(client->client_, mute);
-}
-
-/*
- * Gets the index of the loopback device.
- * Args:
- * client - Pointer returned from "libcras_client_create".
- * idx - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_client_get_loopback_dev_idx(struct libcras_client *client,
- int *idx)
-{
- return client->get_loopback_dev_idx(client->client_, idx);
-}
-
-/*
- * Creates a new struct to save stream params.
- * Returns:
- * If success, return a valid libcras_stream_params pointer. Otherwise,
- * return NULL.
- */
-struct libcras_stream_params *libcras_stream_params_create();
-
-/*
- * Destroys a stream params instance.
- * Args:
- * params - The pointer returned from libcras_stream_params_create.
- */
-void libcras_stream_params_destroy(struct libcras_stream_params *params);
-
-/*
- * Setup stream configuration parameters.
- * Args:
- * params - The pointer returned from libcras_stream_params_create.
- * direction - Playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT).
- * buffer_frames - total number of audio frames to buffer (dictates latency).
- * cb_threshold - For playback, call back for more data when the buffer
- * reaches this level. For capture, this is ignored (Audio callback will
- * be called when buffer_frames have been captured).
- * stream_type - Media or talk (currently only support "default").
- * client_type - The client type, like Chrome or CrOSVM.
- * flags - Currently only used for CRAS_INPUT_STREAM_FLAG.
- * user_data - Pointer that will be passed to the callback.
- * stream_cb - The audio callback. Called when audio is needed(playback) or
- * ready(capture).
- * err_cb - Called when there is an error with the stream.
- * rate - The sample rate of the audio stream.
- * format - The format of the audio stream.
- * num_channels - The number of channels of the audio stream.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_stream_params_set(
- struct libcras_stream_params *params,
- enum CRAS_STREAM_DIRECTION direction, size_t buffer_frames,
- size_t cb_threshold, enum CRAS_STREAM_TYPE stream_type,
- enum CRAS_CLIENT_TYPE client_type, uint32_t flags, void *user_data,
- libcras_stream_cb_t stream_cb, cras_error_cb_t err_cb, size_t rate,
- snd_pcm_format_t format, size_t num_channels)
-{
- return params->set(params->params_, direction, buffer_frames,
- cb_threshold, stream_type, client_type, flags,
- user_data, stream_cb, err_cb, rate, format,
- num_channels);
-}
-
-/*
- * Sets channel layout on given stream parameter.
- * Args:
- * params - The pointer returned from libcras_stream_params_create.
- * length - The length of the array.
- * layout - An integer array representing the position of each channel in
- * enum CRAS_CHANNEL.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_stream_params_set_channel_layout(struct libcras_stream_params *params,
- int length, const int8_t *layout)
-{
- return params->set_channel_layout(params->params_, length, layout);
-}
-
-/*
- * Enables AEC on given stream parameter.
- * Args:
- * params - The pointer returned from libcras_stream_params_create.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_stream_params_enable_aec(struct libcras_stream_params *params)
-{
- params->enable_aec(params->params_);
- return 0;
-}
-
-/*
- * Gets stream id from the callback data.
- * Args:
- * data - The pointer passed to the callback function.
- * id - The pointer to save the stream id.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_stream_cb_data_get_stream_id(struct libcras_stream_cb_data *data,
- cras_stream_id_t *id)
-{
- return data->get_stream_id(data->data_, id);
-}
-
-/*
- * Gets stream buf from the callback data.
- * Args:
- * data - The pointer passed to the callback function.
- * buf - The pointer to save the stream buffer.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_stream_cb_data_get_buf(struct libcras_stream_cb_data *data,
- uint8_t **buf)
-{
- return data->get_buf(data->data_, buf);
-}
-
-/*
- * Gets how many frames to read or play from the callback data.
- * Args:
- * data - The pointer passed to the callback function.
- * frames - The pointer to save the number of frames.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_stream_cb_data_get_frames(struct libcras_stream_cb_data *data,
- unsigned int *frames)
-{
- return data->get_frames(data->data_, frames);
-}
-
-/*
- * Gets the latency from the callback data.
- * Args:
- * data - The pointer passed to the callback function.
- * frames - The timespec pointer to save the latency.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_stream_cb_data_get_latency(struct libcras_stream_cb_data *data,
- struct timespec *latency)
-{
- return data->get_latency(data->data_, latency);
-}
-
-/*
- * Gets the user data from the callback data.
- * Args:
- * data - The pointer passed to the callback function.
- * frames - The pointer to save the user data.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_stream_cb_data_get_usr_arg(struct libcras_stream_cb_data *data,
- void **user_arg)
-{
- return data->get_user_arg(data->data_, user_arg);
-}
-
-/*
- * Destroys a node info instance.
- * Args:
- * node - The libcras_node_info pointer to destroy.
- */
-void libcras_node_info_destroy(struct libcras_node_info *node);
-
-/*
- * Destroys a node info array.
- * Args:
- * nodes - The libcras_node_info pointer array to destroy.
- * num - The size of the array.
- */
-void libcras_node_info_array_destroy(struct libcras_node_info **nodes,
- size_t num);
-
-/*
- * Gets ID from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * id - The pointer to save ID.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_get_id(struct libcras_node_info *node,
- uint64_t *id)
-{
- return node->get_id(node->node_, id);
-}
-
-/*
- * Gets device index from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * dev_idx - The pointer to the device index.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_get_dev_idx(struct libcras_node_info *node,
- uint32_t *dev_idx)
-{
- return node->get_dev_idx(node->node_, dev_idx);
-}
-
-/*
- * Gets node index from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * node_idx - The pointer to save the node index.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_get_node_idx(struct libcras_node_info *node,
- uint32_t *node_idx)
-{
- return node->get_node_idx(node->node_, node_idx);
-}
-
-/*
- * Gets the max supported channels from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * max_supported_channels - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int
-libcras_node_info_get_max_supported_channels(struct libcras_node_info *node,
- uint32_t *max_supported_channels)
-{
- return node->get_max_supported_channels(node->node_,
- max_supported_channels);
-}
-
-/*
- * Gets whether the node is plugged from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * plugged - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_is_plugged(struct libcras_node_info *node,
- bool *plugged)
-{
- return node->is_plugged(node->node_, plugged);
-}
-
-/*
- * Gets whether the node is active from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * active - The pointer to save the result.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_is_active(struct libcras_node_info *node,
- bool *active)
-{
- return node->is_active(node->node_, active);
-}
-
-/*
- * Gets device type from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * type - The pointer to save the device type.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_get_type(struct libcras_node_info *node,
- char **type)
-{
- return node->get_type(node->node_, type);
-}
-
-/*
- * Gets device name from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * name - The pointer to save the device name.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_get_node_name(struct libcras_node_info *node,
- char **name)
-{
- return node->get_node_name(node->node_, name);
-}
-
-/*
- * Gets node name from the node info pointer.
- * Args:
- * node - The node info pointer. (Returned from libcras_client_get_nodes)
- * name - The pointer to save the node name.
- * Returns:
- * 0 on success negative error code on failure (from errno.h).
- */
-DISABLE_CFI_ICALL
-inline int libcras_node_info_get_dev_name(struct libcras_node_info *node,
- char **name)
-{
- return node->get_dev_name(node->node_, name);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CRAS_CLIENT_H_ */
diff --git a/cras/src/libcras/cras_helpers.c b/cras/src/libcras/cras_helpers.c
deleted file mode 100644
index a2120eae..00000000
--- a/cras/src/libcras/cras_helpers.c
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <stdint.h>
-#include <sys/param.h>
-
-#include "cras_client.h"
-#include "cras_util.h"
-
-struct buffer_data {
- const uint8_t *buffer;
- unsigned int offset;
- unsigned int frame_bytes;
- unsigned int len;
-};
-
-static int
-play_buffer_callback(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames, const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- struct buffer_data *data = (struct buffer_data *)user_arg;
- int to_copy = data->len - data->offset;
-
- if (to_copy <= 0) {
- free(user_arg);
- return EOF;
- }
-
- to_copy = MIN(to_copy, frames * data->frame_bytes);
-
- memcpy(playback_samples, data->buffer + data->offset, to_copy);
-
- data->offset += to_copy;
-
- return to_copy / data->frame_bytes;
-}
-
-static int play_buffer_error(struct cras_client *client,
- cras_stream_id_t stream_id, int error,
- void *user_arg)
-{
- free(user_arg);
- return 0;
-}
-
-int cras_helper_create_connect_async(struct cras_client **client,
- cras_connection_status_cb_t connection_cb,
- void *user_arg)
-{
- int rc;
-
- rc = cras_client_create(client);
- if (rc < 0)
- return rc;
-
- cras_client_set_connection_status_cb(*client, connection_cb, user_arg);
-
- rc = cras_client_run_thread(*client);
- if (rc < 0)
- goto client_start_error;
-
- rc = cras_client_connect_async(*client);
- if (rc < 0)
- goto client_start_error;
-
- return 0;
-
-client_start_error:
- cras_client_destroy(*client);
- return rc;
-}
-
-int cras_helper_create_connect(struct cras_client **client)
-{
- int rc;
-
- rc = cras_client_create(client);
- if (rc < 0)
- return rc;
-
- rc = cras_client_connect(*client);
- if (rc < 0)
- goto client_start_error;
-
- rc = cras_client_run_thread(*client);
- if (rc < 0)
- goto client_start_error;
-
- rc = cras_client_connected_wait(*client);
- if (rc < 0)
- goto client_start_error;
-
- return 0;
-
-client_start_error:
- cras_client_destroy(*client);
- return rc;
-}
-
-int cras_helper_add_stream_simple(
- struct cras_client *client, enum CRAS_STREAM_DIRECTION direction,
- void *user_data, cras_unified_cb_t unified_cb, cras_error_cb_t err_cb,
- snd_pcm_format_t format, unsigned int frame_rate,
- unsigned int num_channels, int dev_idx, cras_stream_id_t *stream_id_out)
-{
- struct cras_audio_format *aud_format;
- struct cras_stream_params *params;
- int rc;
-
- aud_format = cras_audio_format_create(format, frame_rate, num_channels);
- if (!aud_format)
- return -ENOMEM;
-
- params = cras_client_unified_params_create(CRAS_STREAM_OUTPUT, 2048,
- CRAS_STREAM_TYPE_DEFAULT, 0,
- user_data, unified_cb,
- err_cb, aud_format);
- if (!params) {
- rc = -ENOMEM;
- goto done_add_stream;
- }
-
- if (dev_idx < 0)
- dev_idx = NO_DEVICE;
- rc = cras_client_add_pinned_stream(client, dev_idx, stream_id_out,
- params);
-
-done_add_stream:
- cras_audio_format_destroy(aud_format);
- cras_client_stream_params_destroy(params);
- return rc;
-}
-
-int cras_helper_play_buffer(struct cras_client *client, const void *buffer,
- unsigned int frames, snd_pcm_format_t format,
- unsigned int frame_rate, unsigned int num_channels,
- int dev_idx)
-{
- struct buffer_data *data;
- cras_stream_id_t stream_id;
-
- data = malloc(sizeof(*data));
-
- data->buffer = buffer;
- data->frame_bytes = num_channels * PCM_FORMAT_WIDTH(format) / 8;
- data->offset = 0;
- data->len = frames * data->frame_bytes;
-
- return cras_helper_add_stream_simple(client, CRAS_STREAM_OUTPUT, data,
- play_buffer_callback,
- play_buffer_error, format,
- frame_rate, num_channels, dev_idx,
- &stream_id);
-}
diff --git a/cras/src/libcras/cras_helpers.h b/cras/src/libcras/cras_helpers.h
deleted file mode 100644
index 604b2660..00000000
--- a/cras/src/libcras/cras_helpers.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#ifndef _CRAS_HELPERS_H
-#define _CRAS_HELPERS_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Creates and connects a client to the running server asynchronously.
- *
- * When the connection has been established the connection_cb is executed
- * with the appropriate state. See cras_connection_status_cb_t for more
- * information.
- *
- * Args:
- * client - Filled with a pointer to the new client.
- * connection_cb - The connection status callback function.
- * user_arg - Argument passed to the connection status callback.
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-int cras_helper_create_connect_async(struct cras_client **client,
- cras_connection_status_cb_t connection_cb,
- void *user_arg);
-
-/* Creates and connects a client to the running server.
- *
- * Waits forever (or interrupt) for the server to be available.
- *
- * Args:
- * client - Filled with a pointer to the new client.
- * Returns:
- * 0 on success, or a negative error code on failure (from errno.h).
- */
-int cras_helper_create_connect(struct cras_client **client);
-
-/* Adds a stream with the given parameters, no flags and a buffer size of 2048
- * Note that the unified_cb parameter is being phased out.
- * TODO(crbug.com/972928): convert this from unified_cb.
- * Args:
- * client - The client to add the stream to (from cras_client_create).
- * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT) or
- * loopback(CRAS_STREAM_POST_MIX_PRE_DSP).
- * user_data - Pointer that will be passed to the callback.
- * unified_cb - Called to request audio data or to notify the client when
- * captured audio is available. Though this is a unified_cb,
- * only one direction will be used for a stream, depending
- * on the 'direction' parameter.
- * err_cb - Called when there is an error with the stream.
- * format - The type of the samples, ex. S16_LE.
- * frame_rate - Sample rate.
- * num_channels - Number of channels in the stream, should be 1 or 2 when
- * using this API, for > 2 channel streams see cras_client.h.
- * dev_idx - Set this to a negative number to play to the default device, if
- * positive it is the index of the device to pin the stream to.
- * stream_id_out - On success will be filled with the new stream id.
- * Guaranteed to be set before any callbacks are made.
- * Returns:
- * 0 on success, negative error code on failure (from errno.h).
- */
-int cras_helper_add_stream_simple(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION direction,
- void *user_data, cras_unified_cb_t unified_cb,
- cras_error_cb_t err_cb,
- snd_pcm_format_t format,
- unsigned int frame_rate,
- unsigned int num_channels, int dev_idx,
- cras_stream_id_t *stream_id_out);
-
-/* Plays the given buffer at a default latency.
- * Args:
- * client - The client to add the stream to (from cras_client_create).
- * buffer - The audio samples.
- * num_frames - The size of the buffer in number of samples.
- * format - The type of the samples, ex. S16_LE.
- * frame_rate - Sample rate.
- * num_channels - Number of channels in the stream.
- * dev_idx - Set this to a negative number to play to the default device, if
- * positive it is the index of the device to pin the stream to.
- * Returns:
- * 0 on success, negative error code on failure (from errno.h).
- */
-int cras_helper_play_buffer(struct cras_client *client, const void *buffer,
- unsigned int num_frames, snd_pcm_format_t format,
- unsigned int frame_rate, unsigned int num_channels,
- int dev_idx);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* _CRAS_HELPERS_H */
diff --git a/cras/src/plc/cras_plc.c b/cras/src/plc/cras_plc.c
deleted file mode 100644
index 74c3568b..00000000
--- a/cras/src/plc/cras_plc.c
+++ /dev/null
@@ -1,285 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <float.h>
-#include <math.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-
-#include "cras_plc.h"
-
-#define MSBC_SAMPLE_SIZE 2 /* 2 bytes*/
-#define MSBC_PKT_LEN 57 /* Packet length without the header */
-#define MSBC_FS 120 /* Frame Size */
-#define MSBC_CODE_SIZE 240 /* MSBC_SAMPLE_SIZE * MSBC_FS */
-
-#define PLC_WL 256 /* 16ms - Window Length for pattern matching */
-#define PLC_TL 64 /* 4ms - Template Length for matching */
-#define PLC_HL (PLC_WL + MSBC_FS - 1) /* Length of History buffer required */
-#define PLC_SBCRL 36 /* SBC Reconvergence sample Length */
-#define PLC_OLAL 16 /* OverLap-Add Length */
-
-#define PLC_WINDOW_SIZE 5
-#define PLC_PL_THRESHOLD 2
-
-/* The pre-computed zero input bit stream of mSBC codec, per HFP 1.7 spec.
- * This mSBC frame will be decoded into all-zero input PCM. */
-static const uint8_t msbc_zero_frame[] = {
- 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6d, 0xb6, 0xdd,
- 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6,
- 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d,
- 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77,
- 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c
-};
-
-/* Raised Cosine table for OLA */
-static const float rcos[PLC_OLAL] = { 0.99148655f, 0.96623611f, 0.92510857f,
- 0.86950446f, 0.80131732f, 0.72286918f,
- 0.63683150f, 0.54613418f, 0.45386582f,
- 0.36316850f, 0.27713082f, 0.19868268f,
- 0.13049554f, 0.07489143f, 0.03376389f,
- 0.00851345f };
-
-/* This structure tracks the packet loss information for last PLC_WINDOW_SIZE
- * of packets:
- * loss_hist - The packet loss history of receiving packets. 1 means lost.
- * ptr - The index of the to be updated packet loss status.
- * count - The count of lost packets in the window.
- */
-struct packet_window {
- uint8_t loss_hist[PLC_WINDOW_SIZE];
- unsigned int ptr;
- unsigned int count;
-};
-
-/* The PLC is specifically designed for mSBC. The algorithm searches the
- * history of receiving samples to find the best match samples and constructs
- * substitutions for the lost samples. The selection is based on pattern
- * matching a template, composed of a length of samples preceding to the lost
- * samples. It then uses the following samples after the best match as the
- * replacement samples and applies Overlap-Add to reduce the audible
- * distortion.
- *
- * This structure holds related info needed to conduct the PLC algorithm.
- * Members:
- * hist - The history buffer for receiving samples, we also use it to
- * buffer the processed replacement samples.
- * best_lag - The index of the best substitution samples in sample history.
- * handled_bad_frames - Number of bad frames handled since the last good
- * frame.
- * zero_frame - A buffer used for storing the samples from decoding the
- * mSBC zero frame packet.
- * pl_window - A window monitoring how many packets are bad within the recent
- * PLC_WINDOW_SIZE of packets. This is used to determine if we
- * want to disable the PLC temporarily.
- */
-struct cras_msbc_plc {
- int16_t hist[PLC_HL + MSBC_FS + PLC_SBCRL + PLC_OLAL];
- unsigned int best_lag;
- int handled_bad_frames;
- int16_t zero_frame[MSBC_FS];
- struct packet_window *pl_window;
-};
-
-struct cras_msbc_plc *cras_msbc_plc_create()
-{
- struct cras_msbc_plc *plc =
- (struct cras_msbc_plc *)calloc(1, sizeof(*plc));
- plc->pl_window =
- (struct packet_window *)calloc(1, sizeof(*plc->pl_window));
- return plc;
-}
-
-void cras_msbc_plc_destroy(struct cras_msbc_plc *plc)
-{
- free(plc->pl_window);
- free(plc);
-}
-
-static int16_t f_to_s16(float input)
-{
- return input > INT16_MAX ?
- INT16_MAX :
- input < INT16_MIN ? INT16_MIN : (int16_t)input;
-}
-
-void overlap_add(int16_t *output, float scaler_d, const int16_t *desc,
- float scaler_a, const int16_t *asc)
-{
- for (int i = 0; i < PLC_OLAL; i++) {
- output[i] =
- f_to_s16(scaler_d * desc[i] * rcos[i] +
- scaler_a * asc[i] * rcos[PLC_OLAL - 1 - i]);
- }
-}
-
-void update_plc_state(struct packet_window *w, uint8_t is_packet_loss)
-{
- uint8_t *curr = &w->loss_hist[w->ptr];
- if (is_packet_loss != *curr) {
- w->count += (is_packet_loss - *curr);
- *curr = is_packet_loss;
- }
- w->ptr = (w->ptr + 1) % PLC_WINDOW_SIZE;
-}
-
-int possibly_pause_plc(struct packet_window *w)
-{
- /* The packet loss count comes from a time window and we use it as an
- * indicator of our confidence of the PLC algorithm. It is known to
- * generate poorer and robotic feeling sounds, when the majority of
- * samples in the PLC history buffer are from the concealment results.
- */
- return w->count >= PLC_PL_THRESHOLD;
-}
-
-int cras_msbc_plc_handle_good_frames(struct cras_msbc_plc *state,
- const uint8_t *input, uint8_t *output)
-{
- int16_t *frame_head, *input_samples, *output_samples;
- if (state->handled_bad_frames == 0) {
- /* If there was no packet concealment before this good frame,
- * we just simply copy the input to output without reconverge.
- */
- memmove(output, input, MSBC_FS * MSBC_SAMPLE_SIZE);
- } else {
- frame_head = &state->hist[PLC_HL];
- input_samples = (int16_t *)input;
- output_samples = (int16_t *)output;
-
- /* For the first good frame after packet loss, we need to
- * conceal the received samples to have it reconverge with the
- * true output.
- */
- memcpy(output_samples, frame_head,
- PLC_SBCRL * MSBC_SAMPLE_SIZE);
- overlap_add(&output_samples[PLC_SBCRL], 1.0,
- &frame_head[PLC_SBCRL], 1.0,
- &input_samples[PLC_SBCRL]);
- memmove(&output_samples[PLC_SBCRL + PLC_OLAL],
- &input_samples[PLC_SBCRL + PLC_OLAL],
- (MSBC_FS - PLC_SBCRL - PLC_OLAL) * MSBC_SAMPLE_SIZE);
- state->handled_bad_frames = 0;
- }
-
- /* Shift the history and update the good frame to the end of it. */
- memmove(state->hist, &state->hist[MSBC_FS],
- (PLC_HL - MSBC_FS) * MSBC_SAMPLE_SIZE);
- memcpy(&state->hist[PLC_HL - MSBC_FS], output,
- MSBC_FS * MSBC_SAMPLE_SIZE);
- update_plc_state(state->pl_window, 0);
- return MSBC_CODE_SIZE;
-}
-
-float cross_correlation(int16_t *x, int16_t *y)
-{
- float sum = 0, x2 = 0, y2 = 0;
-
- for (int i = 0; i < PLC_TL; i++) {
- sum += ((float)x[i]) * y[i];
- x2 += ((float)x[i]) * x[i];
- y2 += ((float)y[i]) * y[i];
- }
- return sum / sqrtf(x2 * y2);
-}
-
-int pattern_match(int16_t *hist)
-{
- int best = 0;
- float cn, max_cn = FLT_MIN;
-
- for (int i = 0; i < PLC_WL; i++) {
- cn = cross_correlation(&hist[PLC_HL - PLC_TL], &hist[i]);
- if (cn > max_cn) {
- best = i;
- max_cn = cn;
- }
- }
- return best;
-}
-
-float amplitude_match(int16_t *x, int16_t *y)
-{
- uint32_t sum_x = 0, sum_y = 0;
- float scaler;
- for (int i = 0; i < MSBC_FS; i++) {
- sum_x += abs(x[i]);
- sum_y += abs(y[i]);
- }
-
- if (sum_y == 0)
- return 1.2f;
-
- scaler = (float)sum_x / sum_y;
- return scaler > 1.2f ? 1.2f : scaler < 0.75f ? 0.75f : scaler;
-}
-
-int cras_msbc_plc_handle_bad_frames(struct cras_msbc_plc *state,
- struct cras_audio_codec *codec,
- uint8_t *output)
-{
- float scaler;
- int16_t *best_match_hist;
- int16_t *frame_head = &state->hist[PLC_HL];
- size_t pcm_decoded = 0;
-
- /* mSBC codec is stateful, the history of signal would contribute to the
- * decode result state->zero_frame.
- */
- codec->decode(codec, msbc_zero_frame, MSBC_PKT_LEN, state->zero_frame,
- MSBC_FS, &pcm_decoded);
-
- /* The PLC algorithm is more likely to generate bad results that sound
- * robotic after severe packet losses happened. Only applying it when
- * we are confident.
- */
- if (!possibly_pause_plc(state->pl_window)) {
- if (state->handled_bad_frames == 0) {
- /* Finds the best matching samples and amplitude */
- state->best_lag = pattern_match(state->hist) + PLC_TL;
- best_match_hist = &state->hist[state->best_lag];
- scaler = amplitude_match(&state->hist[PLC_HL - MSBC_FS],
- best_match_hist);
-
- /* Constructs the substitution samples */
- overlap_add(frame_head, 1.0, state->zero_frame, scaler,
- best_match_hist);
- for (int i = PLC_OLAL; i < MSBC_FS; i++)
- state->hist[PLC_HL + i] =
- f_to_s16(scaler * best_match_hist[i]);
- overlap_add(&frame_head[MSBC_FS], scaler,
- &best_match_hist[MSBC_FS], 1.0,
- &best_match_hist[MSBC_FS]);
-
- memmove(&frame_head[MSBC_FS + PLC_OLAL],
- &best_match_hist[MSBC_FS + PLC_OLAL],
- PLC_SBCRL * MSBC_SAMPLE_SIZE);
- } else {
- memmove(frame_head, &state->hist[state->best_lag],
- (MSBC_FS + PLC_SBCRL + PLC_OLAL) *
- MSBC_SAMPLE_SIZE);
- }
- state->handled_bad_frames++;
- } else {
- /* This is a case similar to receiving a good frame with all
- * zeros, we set handled_bad_frames to zero to prevent the
- * following good frame from being concealed to reconverge with
- * the zero frames we fill in. The concealment result sounds
- * more artificial and weird than simply writing zeros and
- * following samples.
- */
- memmove(frame_head, state->zero_frame, MSBC_CODE_SIZE);
- memset(frame_head + MSBC_CODE_SIZE, 0,
- (PLC_SBCRL + PLC_OLAL) * MSBC_SAMPLE_SIZE);
- state->handled_bad_frames = 0;
- }
-
- memcpy(output, frame_head, MSBC_CODE_SIZE);
- memmove(state->hist, &state->hist[MSBC_FS],
- (PLC_HL + PLC_SBCRL + PLC_OLAL) * MSBC_SAMPLE_SIZE);
- update_plc_state(state->pl_window, 1);
- return MSBC_CODE_SIZE;
-}
diff --git a/cras/src/plc/cras_plc.h b/cras/src/plc/cras_plc.h
deleted file mode 100644
index ccde8bbe..00000000
--- a/cras/src/plc/cras_plc.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-
-#include "cras_audio_codec.h"
-
-/* PLC library provides helper functions to mask the effects of lost or
- * disrupted packets. It currentyl only supports the mSBC codec.
- *
- * This struct contains informations needed for applying the PLC algorithm.
- */
-struct cras_msbc_plc;
-
-/* Creates a plc component for mSBC codec, which is used for wideband speech
- * mode of HFP
- */
-struct cras_msbc_plc *cras_msbc_plc_create();
-
-/* Destroys a mSBC PLC.
- * Args:
- * plc - The PLC to destroy.
- */
-void cras_msbc_plc_destroy(struct cras_msbc_plc *plc);
-
-/* Conceals the packet loss by writing the substitution samples to the ouput
- * buffer provided by the caller. The samples will be generated based on the
- * informations recorded in the PLC struct passed in.
- * Args:
- * plc - The PLC you use.
- * codec - The mSBC codec.
- * output - Pointer to the output buffer.
- * Returns:
- * The number of bytes written to the output buffer.
- */
-int cras_msbc_plc_handle_bad_frames(struct cras_msbc_plc *plc,
- struct cras_audio_codec *codec,
- uint8_t *output);
-
-/* Updates informations needed and potentially processes the input samples to
- * help it to reconverge after a frame loss.
- *
- * The memory space input and output pointers point to can be overlapping.
- * Args:
- * plc - The PLC you use.
- * input - Pointer to the true input.
- * output - Pointer to the output buffer.
- * Returns:
- * The number of bytes written to the output buffer.
- */
-int cras_msbc_plc_handle_good_frames(struct cras_msbc_plc *plc,
- const uint8_t *input, uint8_t *output);
diff --git a/cras/src/plc/cras_plc_test.c b/cras/src/plc/cras_plc_test.c
deleted file mode 100644
index 4b7a6a77..00000000
--- a/cras/src/plc/cras_plc_test.c
+++ /dev/null
@@ -1,223 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <getopt.h>
-#include <math.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include "cras_sbc_codec.h"
-#include "cras_plc.h"
-
-#define MSBC_CODE_SIZE 240
-#define MSBC_PKT_FRAME_LEN 57
-#define RND_SEED 7
-
-static const uint8_t msbc_zero_frame[] = {
- 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6d, 0xb6, 0xdd,
- 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d, 0xb6,
- 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77, 0x6d,
- 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb, 0x77,
- 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c
-};
-
-bool *generate_pl_seq(int input_file_size, float pl_percent)
-{
- unsigned pk_count, pl_count;
- bool *seq;
-
- pk_count = input_file_size / MSBC_CODE_SIZE;
- pl_count = pk_count * (pl_percent / 100.0);
- seq = (bool *)calloc(pk_count, sizeof(*seq));
- srand(RND_SEED);
- while (pl_count > 0) {
- bool *missed = &seq[rand() % pk_count];
- if (!*missed) {
- *missed = true;
- pl_count--;
- }
- }
- return seq;
-}
-
-/* pl_hex is expected to be consecutive bytes(two chars) in hex format.*/
-bool *parse_pl_hex(int input_file_size, const char *pl_hex)
-{
- char tmp[3];
- uint8_t val = 0;
- int i, pl_hex_len, seq_len;
- bool *seq;
-
- pl_hex_len = strlen(pl_hex);
- seq_len = MAX(1 + input_file_size / MSBC_CODE_SIZE, pl_hex_len * 4);
- seq = (bool *)calloc(seq_len, sizeof(*seq));
-
- for (i = 0; i < seq_len; i++) {
- /* If sequence is longer then the provided pl_hex, leave the
- * rest to all zeros. */
- if (i > pl_hex_len * 4)
- break;
- if (i % 8 == 0) {
- memcpy(tmp, pl_hex + i / 4, 2);
- tmp[2] = '\0';
- val = strtol(tmp, NULL, 16);
- }
- seq[i] = val & 1U;
- val >>= 1;
- }
- printf("pl_hex string maps to %ld ms, total sequence size %f ms\n",
- strlen(pl_hex) * 30, seq_len * 7.5f);
- return seq;
-}
-
-void plc_experiment(const char *input_filename, bool *pl_seq, bool with_plc)
-{
- char output_filename[255];
- int input_fd, output_fd, rc;
- struct cras_audio_codec *msbc_input = cras_msbc_codec_create();
- struct cras_audio_codec *msbc_output = cras_msbc_codec_create();
- struct cras_msbc_plc *plc = cras_msbc_plc_create();
- uint8_t buffer[MSBC_CODE_SIZE], packet_buffer[MSBC_PKT_FRAME_LEN];
- size_t encoded, decoded;
- unsigned count = 0;
-
- input_fd = open(input_filename, O_RDONLY);
- if (input_fd == -1) {
- fprintf(stderr, "Cannout open input file %s\n", input_filename);
- return;
- }
-
- if (with_plc)
- sprintf(output_filename, "output_with_plc.raw");
- else
- sprintf(output_filename, "output_with_zero.raw");
-
- output_fd = open(output_filename, O_CREAT | O_RDWR | O_TRUNC, 0644);
- if (output_fd == -1) {
- fprintf(stderr, "Cannot open output file %s\n",
- output_filename);
- return;
- }
-
- while (1) {
- rc = read(input_fd, buffer, MSBC_CODE_SIZE);
- if (rc < 0) {
- fprintf(stderr, "Cannot read file %s", input_filename);
- return;
- } else if (rc == 0 || rc < MSBC_CODE_SIZE)
- break;
-
- msbc_input->encode(msbc_input, buffer, MSBC_CODE_SIZE,
- packet_buffer, MSBC_PKT_FRAME_LEN, &encoded);
-
- if (pl_seq[count]) {
- if (with_plc) {
- cras_msbc_plc_handle_bad_frames(
- plc, msbc_output, buffer);
- decoded = MSBC_CODE_SIZE;
- } else
- msbc_output->decode(msbc_output,
- msbc_zero_frame,
- MSBC_PKT_FRAME_LEN, buffer,
- MSBC_CODE_SIZE, &decoded);
- } else {
- msbc_output->decode(msbc_output, packet_buffer,
- MSBC_PKT_FRAME_LEN, buffer,
- MSBC_CODE_SIZE, &decoded);
- cras_msbc_plc_handle_good_frames(plc, buffer, buffer);
- }
-
- count++;
- rc = write(output_fd, buffer, decoded);
- if (rc < 0) {
- fprintf(stderr, "Cannot write file %s\n",
- output_filename);
- return;
- }
- }
-}
-
-static void show_usage()
-{
- printf("This test only supports reading/writing raw audio with format:\n"
- "\t16000 sample rate, mono channel, S16_LE\n");
- printf("--help - Print this usage.\n");
- printf("--input_file - path to an audio file.\n");
- printf("--pattern - Hex string representing consecutive packets'"
- "status.\n");
- printf("--random - Percentage of packet loss.\n");
-}
-
-int main(int argc, char **argv)
-{
- int fd;
- struct stat st;
- float pl_percent;
- int pl_percent_set = 0;
- int option_character;
- int option_index = 0;
- const char *input_file = NULL;
- const char *pl_hex = NULL;
- bool *pl_seq = NULL;
- static struct option long_options[] = {
- { "help", no_argument, NULL, 'h' },
- { "input", required_argument, NULL, 'i' },
- { "pattern", required_argument, NULL, 'p' },
- { "random", required_argument, NULL, 'r' },
- { NULL, 0, NULL, 0 },
- };
-
- while (true) {
- option_character = getopt_long(argc, argv, "i:r:p:h",
- long_options, &option_index);
- if (option_character == -1)
- break;
- switch (option_character) {
- case 'h':
- show_usage();
- break;
- case 'i':
- input_file = optarg;
- break;
- case 'p':
- pl_hex = optarg;
- break;
- case 'r':
- pl_percent = atof(optarg);
- pl_percent_set = 1;
- break;
- default:
- break;
- }
- }
-
- if ((!pl_percent_set && !pl_hex) || !input_file) {
- show_usage();
- return 1;
- }
-
- fd = open(input_file, O_RDONLY);
- if (fd == -1) {
- fprintf(stderr, "Cannout open input file %s\n", input_file);
- return 1;
- }
- fstat(fd, &st);
- close(fd);
- if (pl_percent_set)
- pl_seq = generate_pl_seq(st.st_size, pl_percent);
- else if (pl_hex)
- pl_seq = parse_pl_hex(st.st_size, pl_hex);
-
- plc_experiment(input_file, pl_seq, true);
- plc_experiment(input_file, pl_seq, false);
-}
diff --git a/cras/src/plc/parse_sco.py b/cras/src/plc/parse_sco.py
deleted file mode 100755
index c50df159..00000000
--- a/cras/src/plc/parse_sco.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# -*- coding: utf-8 -*-
-# Copyright 2020 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""
-A script to extract raw SCO RX packets from btsnoop.
-Use 'btmon -S' to dump SCO traffic from btsnoop file.
-Trim the btsnoop output to just the SCO traffic period.
-Then execute 'python parse-sco.py <btsnoop-output>'
-"""
-
-import atexit
-import binascii
-import os
-import re
-import sys
-
-
-class SCOParser:
- """
- Parser for grepping SCO packets
- """
-
- def __init__(self):
- # On old releases, +CIEV: 4,1 indicates the start point of call session
- # c 31 0d 0a 9a ..+CIEV: 4,1..
- self.call_start_re = re.compile(r'.*?\+CIEV:\s4,(\d).*?')
-
- # > SCO Data RX: Handle 257 flags 0x00 dlen 60 #13826 [hci0] 650.388305
- # 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
- # 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
- # 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
- # 00 00 00 00 00 00 00 00 00 00 00 00
- self.sco_rx_re = re.compile(r'.*?SCO\sData\sRX.*?flags\s0x(\d+).*?')
- self.sco_f = None
- self.output_idx = 0
- self.pk_count = 0
- self.pl_count = 0
-
- atexit.register(self._cleanup)
-
- def _cleanup(self):
- if self.sco_f is not None:
- print(
- "Current file contains %d packets (%d with erroneous status flag)" %
- (self.pk_count, self.pl_count))
- self.pk_count = 0
- self.pl_count = 0
- self.sco_f.close()
-
- def _new_session(self):
- if self.sco_f is not None:
- close(self.sco_f)
-
- new_file = "sco_file_%d" % self.output_idx
- print("Record to %s" % new_file)
- self.sco_f = open(new_file, 'wb')
- self.output_idx += 1
-
- return self.sco_f
-
- def parse(self, filename):
- if not os.path.exists(filename):
- print("%s doesn't exist" % filename)
- return
-
- print("Start parsing %s" % filename)
- parse_rx_data = 0
- with open(filename, "r") as f:
- for line in f.readlines():
- if parse_rx_data > 0:
- self.sco_f.write(binascii.unhexlify(''.join(line[:56].split())))
- parse_rx_data = (parse_rx_data + 1) % 5
-
- # Start a new session and output following SCO data to a new file
- match = self.call_start_re.search(line)
- if match and (1 == int(match.group(1))):
- self._new_session()
- continue
-
- match = self.sco_rx_re.search(line)
- if match:
- if self.sco_f is None:
- self._new_session()
-
- self.pk_count += 1
-
- status_flag = int(match.group(1))
- hdr = ['01', str(status_flag) + '1', '3c']
- if status_flag != 0:
- self.pl_count += 1
-
- self.sco_f.write(binascii.unhexlify(''.join(hdr)))
- parse_rx_data = 1
-
-
-def main(argv):
- if len(argv) < 1:
- print("parse_sco.py [btsnoop.txt]")
- return
-
- p = SCOParser()
- p.parse(argv[0])
-
-
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/cras/src/server/audio_thread.c b/cras/src/server/audio_thread.c
deleted file mode 100644
index 48bb0dc2..00000000
--- a/cras/src/server/audio_thread.c
+++ /dev/null
@@ -1,1314 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE /* for ppoll and asprintf*/
-#endif
-
-#include <pthread.h>
-#include <poll.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include "audio_thread_log.h"
-#include "cras_audio_thread_monitor.h"
-#include "cras_config.h"
-#include "cras_device_monitor.h"
-#include "cras_fmt_conv.h"
-#include "cras_iodev.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "dev_stream.h"
-#include "audio_thread.h"
-#include "utlist.h"
-
-#define MIN_PROCESS_TIME_US 500 /* 0.5ms - min amount of time to mix/src. */
-#define SLEEP_FUZZ_FRAMES 10 /* # to consider "close enough" to sleep frames. */
-#define MIN_READ_WAIT_US 2000 /* 2ms */
-/*
- * # to check whether a busyloop event happens
- */
-#define MAX_CONTINUOUS_ZERO_SLEEP_COUNT 2
-
-/*
- * If the number of continuous zero sleep is equal to this limit, the value
- * will be recorded immediately. It can ensure all busyloop will be recorded
- * even if the busyloop does not stop.
- */
-#define MAX_CONTINUOUS_ZERO_SLEEP_METRIC_LIMIT 1000
-
-/* Messages that can be sent from the main context to the audio thread. */
-enum AUDIO_THREAD_COMMAND {
- AUDIO_THREAD_ADD_OPEN_DEV,
- AUDIO_THREAD_RM_OPEN_DEV,
- AUDIO_THREAD_IS_DEV_OPEN,
- AUDIO_THREAD_ADD_STREAM,
- AUDIO_THREAD_DISCONNECT_STREAM,
- AUDIO_THREAD_STOP,
- AUDIO_THREAD_DUMP_THREAD_INFO,
- AUDIO_THREAD_DRAIN_STREAM,
- AUDIO_THREAD_CONFIG_GLOBAL_REMIX,
- AUDIO_THREAD_DEV_START_RAMP,
- AUDIO_THREAD_REMOVE_CALLBACK,
- AUDIO_THREAD_AEC_DUMP,
-};
-
-struct audio_thread_msg {
- size_t length;
- enum AUDIO_THREAD_COMMAND id;
-};
-
-struct audio_thread_config_global_remix {
- struct audio_thread_msg header;
- struct cras_fmt_conv *fmt_conv;
-};
-
-struct audio_thread_open_device_msg {
- struct audio_thread_msg header;
- struct cras_iodev *dev;
-};
-
-struct audio_thread_rm_device_msg {
- struct audio_thread_msg header;
- enum CRAS_STREAM_DIRECTION dir;
- unsigned dev_idx;
-};
-
-struct audio_thread_rm_callback_msg {
- struct audio_thread_msg header;
- int fd;
-};
-
-struct audio_thread_add_rm_stream_msg {
- struct audio_thread_msg header;
- struct cras_rstream *stream;
- struct cras_iodev **devs;
- unsigned int num_devs;
-};
-
-struct audio_thread_dump_debug_info_msg {
- struct audio_thread_msg header;
- struct audio_debug_info *info;
-};
-
-struct audio_thread_dev_start_ramp_msg {
- struct audio_thread_msg header;
- unsigned int dev_idx;
- enum CRAS_IODEV_RAMP_REQUEST request;
-};
-
-struct audio_thread_aec_dump_msg {
- struct audio_thread_msg header;
- cras_stream_id_t stream_id;
- unsigned int start; /* */
- int fd;
-};
-
-/* Audio thread logging. If atlog is successfully created from cras_shm_setup,
- * then the fds should have valid value. Or audio thread will fallback to use
- * calloc to create atlog and leave the fds as -1.
- */
-struct audio_thread_event_log *atlog;
-char *atlog_name;
-int atlog_rw_shm_fd;
-int atlog_ro_shm_fd;
-
-static struct iodev_callback_list *iodev_callbacks;
-
-struct iodev_callback_list {
- int fd;
- int events;
- enum AUDIO_THREAD_EVENTS_CB_TRIGGER trigger;
- thread_callback cb;
- void *cb_data;
- struct pollfd *pollfd;
- struct iodev_callback_list *prev, *next;
-};
-
-void audio_thread_add_events_callback(int fd, thread_callback cb, void *data,
- int events)
-{
- struct iodev_callback_list *iodev_cb;
-
- /* Don't add iodev_cb twice */
- DL_FOREACH (iodev_callbacks, iodev_cb)
- if (iodev_cb->fd == fd && iodev_cb->cb_data == data)
- return;
-
- iodev_cb = (struct iodev_callback_list *)calloc(1, sizeof(*iodev_cb));
- iodev_cb->fd = fd;
- iodev_cb->cb = cb;
- iodev_cb->cb_data = data;
- iodev_cb->trigger = TRIGGER_POLL;
- iodev_cb->events = events;
-
- DL_APPEND(iodev_callbacks, iodev_cb);
-}
-
-void audio_thread_rm_callback(int fd)
-{
- struct iodev_callback_list *iodev_cb;
-
- DL_FOREACH (iodev_callbacks, iodev_cb) {
- if (iodev_cb->fd == fd) {
- DL_DELETE(iodev_callbacks, iodev_cb);
- free(iodev_cb);
- return;
- }
- }
-}
-
-void audio_thread_config_events_callback(
- int fd, enum AUDIO_THREAD_EVENTS_CB_TRIGGER trigger)
-{
- struct iodev_callback_list *iodev_cb;
-
- DL_FOREACH (iodev_callbacks, iodev_cb) {
- if (iodev_cb->fd == fd) {
- iodev_cb->trigger = trigger;
- return;
- }
- }
-}
-
-/* Sends a response (error code) from the audio thread to the main thread.
- * Indicates that the last message sent to the audio thread has been handled
- * with an error code of rc.
- * Args:
- * thread - thread responding to command.
- * rc - Result code to send back to the main thread.
- * Returns:
- * The number of bytes written to the main thread.
- */
-static int audio_thread_send_response(struct audio_thread *thread, int rc)
-{
- return write(thread->to_main_fds[1], &rc, sizeof(rc));
-}
-
-/* Reads from a file descriptor until all bytes are read.
- *
- * Args:
- * fd - file descriptor to read
- * buf - the buffer to be written.
- * count - the number of bytes to read from fd
- * Returns:
- * |count| on success, negative error code on failure.
- */
-static int read_until_finished(int fd, void *buf, size_t count)
-{
- int nread, count_left = count;
-
- while (count_left > 0) {
- nread = read(fd, (uint8_t *)buf + count - count_left,
- count_left);
- if (nread < 0) {
- if (errno == EINTR)
- continue;
- else
- return nread;
- } else if (nread == 0) {
- syslog(LOG_ERR, "Pipe has been closed.");
- return -EPIPE;
- }
- count_left -= nread;
- }
- return count;
-}
-
-/* Reads a command from the main thread. Called from the playback/capture
- * thread. This will read the next available command from the main thread and
- * put it in buf.
- * Args:
- * thread - thread reading the command.
- * buf - Message is stored here on return.
- * max_len - maximum length of message to put into buf.
- * Returns:
- * 0 on success, negative error code on failure.
- */
-static int audio_thread_read_command(struct audio_thread *thread, uint8_t *buf,
- size_t max_len)
-{
- int to_read, nread, rc;
- struct audio_thread_msg *msg = (struct audio_thread_msg *)buf;
-
- /* Get the length of the message first */
- nread = read_until_finished(thread->to_thread_fds[0], buf,
- sizeof(msg->length));
- if (nread < 0)
- return nread;
-
- if (msg->length > max_len)
- return -ENOMEM;
-
- to_read = msg->length - sizeof(msg->length);
- rc = read_until_finished(thread->to_thread_fds[0],
- &buf[0] + sizeof(msg->length), to_read);
- if (rc < 0)
- return rc;
- return 0;
-}
-
-/* Builds an initial buffer to avoid an underrun. Adds min_level of latency. */
-static void fill_odevs_zeros_min_level(struct cras_iodev *odev)
-{
- cras_iodev_fill_odev_zeros(odev, odev->min_buffer_level);
-}
-
-/* Handles messages from main thread to add a new active device. */
-static int thread_add_open_dev(struct audio_thread *thread,
- struct cras_iodev *iodev)
-{
- struct open_dev *adev;
-
- DL_SEARCH_SCALAR(thread->open_devs[iodev->direction], adev, dev, iodev);
- if (adev)
- return -EEXIST;
-
- adev = (struct open_dev *)calloc(1, sizeof(*adev));
- adev->dev = iodev;
-
- /*
- * Start output devices by padding the output. This avoids a burst of
- * audio callbacks when the stream starts
- */
- if (iodev->direction == CRAS_STREAM_OUTPUT)
- fill_odevs_zeros_min_level(iodev);
-
- ATLOG(atlog, AUDIO_THREAD_DEV_ADDED, iodev->info.idx, 0, 0);
-
- DL_APPEND(thread->open_devs[iodev->direction], adev);
-
- return 0;
-}
-
-/* Handles messages from the main thread to remove an active device. */
-static int thread_rm_open_dev(struct audio_thread *thread,
- enum CRAS_STREAM_DIRECTION dir,
- unsigned int dev_idx)
-{
- struct open_dev *adev =
- dev_io_find_open_dev(thread->open_devs[dir], dev_idx);
- if (!adev)
- return -EINVAL;
-
- dev_io_rm_open_dev(&thread->open_devs[dir], adev);
- return 0;
-}
-
-/*
- * Handles message from the main thread to check if an iodev is in the
- * open dev list.
- */
-static int thread_is_dev_open(struct audio_thread *thread,
- struct cras_iodev *iodev)
-{
- struct open_dev *adev = dev_io_find_open_dev(
- thread->open_devs[iodev->direction], iodev->info.idx);
- return !!adev;
-}
-
-/*
- * Handles messages from the main thread to start ramping on a device.
- * Start ramping in audio thread and set mute/unmute
- * state on device. This should only be done when
- * device is running with valid streams.
- *
- * 1. Mute -> Unmute: Set device unmute state after
- * ramping is started.
- * 2. Unmute -> Mute: Set device mute state after
- * ramping is done.
- *
- * The above transition will be handled by cras_iodev_start_ramp.
- */
-static int thread_dev_start_ramp(struct audio_thread *thread,
- unsigned int dev_idx,
- enum CRAS_IODEV_RAMP_REQUEST request)
-{
- /* Do nothing if device wasn't already in the active dev list. */
- struct cras_iodev *iodev;
- struct open_dev *adev = dev_io_find_open_dev(
- thread->open_devs[CRAS_STREAM_OUTPUT], dev_idx);
- if (!adev)
- return -EINVAL;
- iodev = adev->dev;
-
- /*
- * Checks if a device should start ramping for mute/unmute change.
- * Device must meet all the conditions:
- *
- * - Device has ramp support.
- * - Device is in normal run state, that is, it must be running with valid
- * streams.
- * - Device volume, which considers both system volume and adjusted active
- * node volume, is not zero. If device volume is zero, all the samples are
- * suppressed to zero and there is no need to ramp.
- */
- if (iodev->ramp &&
- cras_iodev_state(iodev) == CRAS_IODEV_STATE_NORMAL_RUN &&
- !cras_iodev_is_zero_volume(iodev))
- return cras_iodev_start_ramp(iodev, request);
- else
- return cras_device_monitor_set_device_mute_state(
- iodev->info.idx);
-}
-
-/* Return non-zero if the stream is attached to any device. */
-static int thread_find_stream(struct audio_thread *thread,
- struct cras_rstream *rstream)
-{
- struct open_dev *open_dev;
- struct dev_stream *s;
-
- DL_FOREACH (thread->open_devs[rstream->direction], open_dev) {
- DL_FOREACH (open_dev->dev->streams, s) {
- if (s->stream == rstream)
- return 1;
- }
- }
- return 0;
-}
-
-/* Handles the disconnect_stream message from the main thread. */
-static int thread_disconnect_stream(struct audio_thread *thread,
- struct cras_rstream *stream,
- struct cras_iodev *dev)
-{
- int rc;
-
- if (!thread_find_stream(thread, stream))
- return 0;
-
- rc = dev_io_remove_stream(&thread->open_devs[stream->direction], stream,
- dev);
-
- return rc;
-}
-
-/* Initiates draining of a stream or returns the status of a draining stream.
- * If the stream has completed draining the thread forfeits ownership and must
- * never reference it again. Returns the number of milliseconds it will take to
- * finish draining, a minimum of one ms if any samples remain.
- */
-static int thread_drain_stream_ms_remaining(struct audio_thread *thread,
- struct cras_rstream *rstream)
-{
- int fr_in_buff;
- struct cras_audio_shm *shm;
-
- if (rstream->direction != CRAS_STREAM_OUTPUT)
- return 0;
-
- shm = cras_rstream_shm(rstream);
- fr_in_buff = cras_shm_get_frames(shm);
-
- if (fr_in_buff <= 0)
- return 0;
-
- cras_rstream_set_is_draining(rstream, 1);
-
- return 1 + cras_frames_to_ms(fr_in_buff, rstream->format.frame_rate);
-}
-
-/* Handles a request to begin draining and return the amount of time left to
- * draing a stream.
- */
-static int thread_drain_stream(struct audio_thread *thread,
- struct cras_rstream *rstream)
-{
- int ms_left;
-
- if (!thread_find_stream(thread, rstream))
- return 0;
-
- ms_left = thread_drain_stream_ms_remaining(thread, rstream);
- if (ms_left == 0)
- dev_io_remove_stream(&thread->open_devs[rstream->direction],
- rstream, NULL);
-
- return ms_left;
-}
-
-/* Handles the add_stream message from the main thread. */
-static int thread_add_stream(struct audio_thread *thread,
- struct cras_rstream *stream,
- struct cras_iodev **iodevs,
- unsigned int num_iodevs)
-{
- int rc;
-
- rc = dev_io_append_stream(&thread->open_devs[CRAS_STREAM_OUTPUT],
- &thread->open_devs[CRAS_STREAM_INPUT], stream,
- iodevs, num_iodevs);
- if (rc < 0)
- return rc;
-
- return 0;
-}
-
-/* Starts or stops aec dump task. */
-static int thread_set_aec_dump(struct audio_thread *thread,
- cras_stream_id_t stream_id, unsigned int start,
- int fd)
-{
- struct open_dev *idev_list = thread->open_devs[CRAS_STREAM_INPUT];
- struct open_dev *adev;
- struct dev_stream *stream;
-
- DL_FOREACH (idev_list, adev) {
- if (!cras_iodev_is_open(adev->dev))
- continue;
-
- DL_FOREACH (adev->dev->streams, stream) {
- if ((stream->stream->apm_list == NULL) ||
- (stream->stream->stream_id != stream_id))
- continue;
-
- cras_apm_list_set_aec_dump(stream->stream->apm_list,
- adev->dev, start, fd);
- }
- }
- return 0;
-}
-
-/* Stop the playback thread */
-static void terminate_pb_thread()
-{
- pthread_exit(0);
-}
-
-static void append_dev_dump_info(struct audio_dev_debug_info *di,
- struct open_dev *adev)
-{
- struct cras_audio_format *fmt = adev->dev->format;
- struct timespec now, time_since;
- strncpy(di->dev_name, adev->dev->info.name, sizeof(di->dev_name));
- di->buffer_size = adev->dev->buffer_size;
- di->min_buffer_level = adev->dev->min_buffer_level;
- di->min_cb_level = adev->dev->min_cb_level;
- di->max_cb_level = adev->dev->max_cb_level;
- di->direction = adev->dev->direction;
- di->num_underruns = cras_iodev_get_num_underruns(adev->dev);
- di->num_severe_underruns =
- cras_iodev_get_num_severe_underruns(adev->dev);
- di->highest_hw_level = adev->dev->highest_hw_level;
- di->software_gain_scaler = (adev->dev->direction == CRAS_STREAM_INPUT) ?
- adev->dev->software_gain_scaler :
- 0.0f;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &adev->dev->open_ts, &time_since);
- di->runtime_sec = time_since.tv_sec;
- di->runtime_nsec = time_since.tv_nsec;
- di->longest_wake_sec = adev->longest_wake.tv_sec;
- di->longest_wake_nsec = adev->longest_wake.tv_nsec;
-
- if (fmt) {
- di->frame_rate = fmt->frame_rate;
- di->num_channels = fmt->num_channels;
- di->est_rate_ratio = cras_iodev_get_est_rate_ratio(adev->dev);
- } else {
- di->frame_rate = 0;
- di->num_channels = 0;
- di->est_rate_ratio = 0;
- }
-}
-
-/* Put stream info for the given stream into the info struct. */
-static void append_stream_dump_info(struct audio_debug_info *info,
- struct dev_stream *stream,
- unsigned int dev_idx, int index)
-{
- struct audio_stream_debug_info *si;
- struct timespec now, time_since;
-
- si = &info->streams[index];
-
- si->stream_id = stream->stream->stream_id;
- si->dev_idx = dev_idx;
- si->direction = stream->stream->direction;
- si->stream_type = stream->stream->stream_type;
- si->client_type = stream->stream->client_type;
- si->buffer_frames = stream->stream->buffer_frames;
- si->cb_threshold = stream->stream->cb_threshold;
- si->frame_rate = stream->stream->format.frame_rate;
- si->num_channels = stream->stream->format.num_channels;
- memcpy(si->channel_layout, stream->stream->format.channel_layout,
- sizeof(si->channel_layout));
- si->longest_fetch_sec = stream->stream->longest_fetch_interval.tv_sec;
- si->longest_fetch_nsec = stream->stream->longest_fetch_interval.tv_nsec;
- si->num_overruns = cras_shm_num_overruns(stream->stream->shm);
- si->effects = cras_apm_list_get_effects(stream->stream->apm_list);
- si->pinned_dev_idx = stream->stream->pinned_dev_idx;
- si->is_pinned = stream->stream->is_pinned;
- si->num_missed_cb = stream->stream->num_missed_cb;
- si->stream_volume = cras_rstream_get_volume_scaler(stream->stream);
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &stream->stream->start_ts, &time_since);
- si->runtime_sec = time_since.tv_sec;
- si->runtime_nsec = time_since.tv_nsec;
-}
-
-/* Handle a message sent from main thread to the audio thread.
- * Returns:
- * Error code when reading or sending message fails.
- */
-static int handle_audio_thread_message(struct audio_thread *thread)
-{
- uint8_t buf[256];
- struct audio_thread_msg *msg = (struct audio_thread_msg *)buf;
- int ret = 0;
- int err;
-
- err = audio_thread_read_command(thread, buf, 256);
- if (err < 0)
- return err;
-
- ATLOG(atlog, AUDIO_THREAD_PB_MSG, msg->id, 0, 0);
-
- switch (msg->id) {
- case AUDIO_THREAD_ADD_STREAM: {
- struct audio_thread_add_rm_stream_msg *amsg;
- amsg = (struct audio_thread_add_rm_stream_msg *)msg;
- ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_WAIT,
- amsg->stream->stream_id, 0, 0);
- ret = thread_add_stream(thread, amsg->stream, amsg->devs,
- amsg->num_devs);
- break;
- }
- case AUDIO_THREAD_DISCONNECT_STREAM: {
- struct audio_thread_add_rm_stream_msg *rmsg;
-
- rmsg = (struct audio_thread_add_rm_stream_msg *)msg;
-
- ret = thread_disconnect_stream(thread, rmsg->stream,
- rmsg->devs[0]);
- break;
- }
- case AUDIO_THREAD_ADD_OPEN_DEV: {
- struct audio_thread_open_device_msg *rmsg;
-
- rmsg = (struct audio_thread_open_device_msg *)msg;
- ret = thread_add_open_dev(thread, rmsg->dev);
- break;
- }
- case AUDIO_THREAD_RM_OPEN_DEV: {
- struct audio_thread_rm_device_msg *rmsg;
-
- rmsg = (struct audio_thread_rm_device_msg *)msg;
- ret = thread_rm_open_dev(thread, rmsg->dir, rmsg->dev_idx);
- break;
- }
- case AUDIO_THREAD_IS_DEV_OPEN: {
- struct audio_thread_open_device_msg *rmsg;
-
- rmsg = (struct audio_thread_open_device_msg *)msg;
- ret = thread_is_dev_open(thread, rmsg->dev);
- break;
- }
- case AUDIO_THREAD_STOP:
- ret = 0;
- err = audio_thread_send_response(thread, ret);
- if (err < 0)
- return err;
- terminate_pb_thread();
- break;
- case AUDIO_THREAD_DUMP_THREAD_INFO: {
- struct dev_stream *curr;
- struct open_dev *adev;
- struct audio_thread_dump_debug_info_msg *dmsg;
- struct audio_debug_info *info;
- unsigned int num_streams = 0;
- unsigned int num_devs = 0;
-
- ret = 0;
- dmsg = (struct audio_thread_dump_debug_info_msg *)msg;
- info = dmsg->info;
-
- /* Go through all open devices. */
- DL_FOREACH (thread->open_devs[CRAS_STREAM_OUTPUT], adev) {
- append_dev_dump_info(&info->devs[num_devs], adev);
- if (++num_devs == MAX_DEBUG_DEVS)
- break;
- DL_FOREACH (adev->dev->streams, curr) {
- if (num_streams == MAX_DEBUG_STREAMS)
- break;
- append_stream_dump_info(info, curr,
- adev->dev->info.idx,
- num_streams++);
- }
- }
- DL_FOREACH (thread->open_devs[CRAS_STREAM_INPUT], adev) {
- if (num_devs == MAX_DEBUG_DEVS)
- break;
- append_dev_dump_info(&info->devs[num_devs], adev);
- DL_FOREACH (adev->dev->streams, curr) {
- if (num_streams == MAX_DEBUG_STREAMS)
- break;
- append_stream_dump_info(info, curr,
- adev->dev->info.idx,
- num_streams++);
- }
- ++num_devs;
- }
- info->num_devs = num_devs;
-
- info->num_streams = num_streams;
-
- memcpy(&info->log, atlog, sizeof(info->log));
- break;
- }
- case AUDIO_THREAD_DRAIN_STREAM: {
- struct audio_thread_add_rm_stream_msg *rmsg;
-
- rmsg = (struct audio_thread_add_rm_stream_msg *)msg;
- ret = thread_drain_stream(thread, rmsg->stream);
- break;
- }
- case AUDIO_THREAD_REMOVE_CALLBACK: {
- struct audio_thread_rm_callback_msg *rmsg;
-
- rmsg = (struct audio_thread_rm_callback_msg *)msg;
- audio_thread_rm_callback(rmsg->fd);
- break;
- }
- case AUDIO_THREAD_CONFIG_GLOBAL_REMIX: {
- struct audio_thread_config_global_remix *rmsg;
- void *rsp;
-
- /* Respond the pointer to the old remix converter, so it can be
- * freed later in main thread. */
- rsp = (void *)thread->remix_converter;
-
- rmsg = (struct audio_thread_config_global_remix *)msg;
- thread->remix_converter = rmsg->fmt_conv;
-
- return write(thread->to_main_fds[1], &rsp, sizeof(rsp));
- }
- case AUDIO_THREAD_DEV_START_RAMP: {
- struct audio_thread_dev_start_ramp_msg *rmsg;
-
- rmsg = (struct audio_thread_dev_start_ramp_msg *)msg;
- ret = thread_dev_start_ramp(thread, rmsg->dev_idx,
- rmsg->request);
- break;
- }
- case AUDIO_THREAD_AEC_DUMP: {
- struct audio_thread_aec_dump_msg *rmsg;
- rmsg = (struct audio_thread_aec_dump_msg *)msg;
- ret = thread_set_aec_dump(thread, rmsg->stream_id, rmsg->start,
- rmsg->fd);
- break;
- }
- default:
- ret = -EINVAL;
- break;
- }
-
- err = audio_thread_send_response(thread, ret);
- if (err < 0)
- return err;
- return 0;
-}
-
-/* Returns the number of active streams plus the number of active devices. */
-static int fill_next_sleep_interval(struct audio_thread *thread,
- struct timespec *ts)
-{
- struct timespec min_ts;
- struct timespec now;
- int ret;
-
- ts->tv_sec = 0;
- ts->tv_nsec = 0;
- /* Limit the sleep time to 20 seconds. */
- min_ts.tv_sec = 20;
- min_ts.tv_nsec = 0;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- add_timespecs(&min_ts, &now);
- ret = dev_io_next_output_wake(&thread->open_devs[CRAS_STREAM_OUTPUT],
- &min_ts);
- ret += dev_io_next_input_wake(&thread->open_devs[CRAS_STREAM_INPUT],
- &min_ts);
- if (timespec_after(&min_ts, &now))
- subtract_timespecs(&min_ts, &now, ts);
-
- return ret;
-}
-
-static struct pollfd *add_pollfd(struct audio_thread *thread, int fd,
- int events)
-{
- thread->pollfds[thread->num_pollfds].fd = fd;
- thread->pollfds[thread->num_pollfds].events = events;
- thread->num_pollfds++;
- if (thread->num_pollfds >= thread->pollfds_size) {
- thread->pollfds_size *= 2;
- thread->pollfds = (struct pollfd *)realloc(
- thread->pollfds,
- sizeof(*thread->pollfds) * thread->pollfds_size);
- return NULL;
- }
-
- return &thread->pollfds[thread->num_pollfds - 1];
-}
-
-static int continuous_zero_sleep_count = 0;
-static unsigned busyloop_count = 0;
-
-/*
- * Logs the number of busyloop during one audio thread running state
- * (wait_ts != NULL).
- */
-static void log_busyloop(struct timespec *wait_ts)
-{
- static struct timespec start_time;
- static bool started = false;
- struct timespec diff, now;
-
- /* If wait_ts is NULL, there is no stream running. */
- if (wait_ts && !started) {
- started = true;
- busyloop_count = 0;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start_time);
- } else if (!wait_ts && started) {
- started = false;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &start_time, &diff);
- cras_server_metrics_busyloop(&diff, busyloop_count);
- }
-}
-
-static void check_busyloop(struct timespec *wait_ts)
-{
- if (wait_ts->tv_sec == 0 && wait_ts->tv_nsec == 0) {
- continuous_zero_sleep_count++;
- if (continuous_zero_sleep_count ==
- MAX_CONTINUOUS_ZERO_SLEEP_COUNT) {
- busyloop_count++;
- cras_audio_thread_event_busyloop();
- }
- if (continuous_zero_sleep_count ==
- MAX_CONTINUOUS_ZERO_SLEEP_METRIC_LIMIT)
- cras_server_metrics_busyloop_length(
- continuous_zero_sleep_count);
-
- } else {
- if (continuous_zero_sleep_count >=
- MAX_CONTINUOUS_ZERO_SLEEP_COUNT &&
- continuous_zero_sleep_count <
- MAX_CONTINUOUS_ZERO_SLEEP_METRIC_LIMIT)
- cras_server_metrics_busyloop_length(
- continuous_zero_sleep_count);
- continuous_zero_sleep_count = 0;
- }
-}
-
-/* For playback, fill the audio buffer when needed, for capture, pull out
- * samples when they are ready.
- * This thread will attempt to run at a high priority to allow for low latency
- * streams. This thread sleeps while the device plays back or captures audio,
- * it will wake up as little as it can while avoiding xruns. It can also be
- * woken by sending it a message using the "audio_thread_post_message" function.
- */
-static void *audio_io_thread(void *arg)
-{
- struct audio_thread *thread = (struct audio_thread *)arg;
- struct open_dev *adev;
- struct dev_stream *curr;
- struct timespec ts;
- int msg_fd;
- int rc;
-
- msg_fd = thread->to_thread_fds[0];
-
- /* Attempt to get realtime scheduling */
- if (cras_set_rt_scheduling(CRAS_SERVER_RT_THREAD_PRIORITY) == 0)
- cras_set_thread_priority(CRAS_SERVER_RT_THREAD_PRIORITY);
-
- thread->pollfds[0].fd = msg_fd;
- thread->pollfds[0].events = POLLIN;
-
- while (1) {
- struct timespec *wait_ts;
- struct iodev_callback_list *iodev_cb;
- int non_empty;
-
- wait_ts = NULL;
- thread->num_pollfds = 1;
-
- /* device opened */
- dev_io_run(&thread->open_devs[CRAS_STREAM_OUTPUT],
- &thread->open_devs[CRAS_STREAM_INPUT],
- thread->remix_converter);
-
- non_empty = dev_io_check_non_empty_state_transition(
- thread->open_devs[CRAS_STREAM_OUTPUT]);
-
- if (fill_next_sleep_interval(thread, &ts))
- wait_ts = &ts;
-
- restart_poll_loop:
- thread->num_pollfds = 1;
-
- DL_FOREACH (iodev_callbacks, iodev_cb) {
- if (iodev_cb->trigger != TRIGGER_POLL) {
- iodev_cb->pollfd = NULL;
- continue;
- }
- iodev_cb->pollfd = add_pollfd(thread, iodev_cb->fd,
- iodev_cb->events);
- if (!iodev_cb->pollfd)
- goto restart_poll_loop;
- }
-
- /* TODO(dgreid) - once per rstream not per dev_stream */
- DL_FOREACH (thread->open_devs[CRAS_STREAM_OUTPUT], adev) {
- DL_FOREACH (adev->dev->streams, curr) {
- int fd = dev_stream_poll_stream_fd(curr);
- if (fd < 0)
- continue;
- if (!add_pollfd(thread, fd, POLLIN))
- goto restart_poll_loop;
- }
- }
- DL_FOREACH (thread->open_devs[CRAS_STREAM_INPUT], adev) {
- DL_FOREACH (adev->dev->streams, curr) {
- int fd = dev_stream_poll_stream_fd(curr);
- if (fd < 0)
- continue;
- if (!add_pollfd(thread, fd, POLLIN))
- goto restart_poll_loop;
- }
- }
-
- log_busyloop(wait_ts);
-
- ATLOG(atlog, AUDIO_THREAD_SLEEP, wait_ts ? wait_ts->tv_sec : 0,
- wait_ts ? wait_ts->tv_nsec : 0, non_empty);
- if (wait_ts)
- check_busyloop(wait_ts);
-
- /* Sync atlog with shared memory. */
- __sync_synchronize();
- atlog->sync_write_pos = atlog->write_pos;
-
- rc = ppoll(thread->pollfds, thread->num_pollfds, wait_ts, NULL);
- ATLOG(atlog, AUDIO_THREAD_WAKE, rc, 0, 0);
-
- /* Handle callbacks registered by TRIGGER_WAKEUP */
- DL_FOREACH (iodev_callbacks, iodev_cb) {
- if (iodev_cb->trigger == TRIGGER_WAKEUP) {
- ATLOG(atlog, AUDIO_THREAD_IODEV_CB, 0, 0, 0);
- iodev_cb->cb(iodev_cb->cb_data, 0);
- }
- }
-
- /* If there's no pollfd ready to handle. */
- if (rc <= 0)
- continue;
-
- if (thread->pollfds[0].revents & POLLIN) {
- rc = handle_audio_thread_message(thread);
- if (rc < 0)
- syslog(LOG_ERR, "handle message %d", rc);
- }
-
- DL_FOREACH (iodev_callbacks, iodev_cb) {
- if (iodev_cb->pollfd &&
- iodev_cb->pollfd->revents & iodev_cb->events) {
- ATLOG(atlog, AUDIO_THREAD_IODEV_CB,
- iodev_cb->pollfd->revents,
- iodev_cb->events, 0);
- iodev_cb->cb(iodev_cb->cb_data,
- iodev_cb->pollfd->revents);
- }
- }
- }
-
- return NULL;
-}
-
-/* Write a message to the playback thread and wait for an ack, This keeps these
- * operations synchronous for the main server thread. For instance when the
- * RM_STREAM message is sent, the stream can be deleted after the function
- * returns. Making this synchronous also allows the thread to return an error
- * code that can be handled by the caller.
- * Args:
- * thread - thread to receive message.
- * msg - The message to send.
- * Returns:
- * A return code from the message handler in the thread.
- */
-static int audio_thread_post_message(struct audio_thread *thread,
- struct audio_thread_msg *msg)
-{
- int err, rsp;
-
- err = write(thread->to_thread_fds[1], msg, msg->length);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to post message to thread.");
- return err;
- }
- /* Synchronous action, wait for response. */
- err = read_until_finished(thread->to_main_fds[0], &rsp, sizeof(rsp));
- if (err < 0) {
- syslog(LOG_ERR, "Failed to read reply from thread.");
- return err;
- }
-
- return rsp;
-}
-
-static void init_open_device_msg(struct audio_thread_open_device_msg *msg,
- enum AUDIO_THREAD_COMMAND id,
- struct cras_iodev *dev)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.id = id;
- msg->header.length = sizeof(*msg);
- msg->dev = dev;
-}
-
-static void init_rm_device_msg(struct audio_thread_rm_device_msg *msg,
- enum CRAS_STREAM_DIRECTION dir,
- unsigned int dev_idx)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.id = AUDIO_THREAD_RM_OPEN_DEV;
- msg->header.length = sizeof(*msg);
- msg->dir = dir;
- msg->dev_idx = dev_idx;
-}
-
-static void init_add_rm_stream_msg(struct audio_thread_add_rm_stream_msg *msg,
- enum AUDIO_THREAD_COMMAND id,
- struct cras_rstream *stream,
- struct cras_iodev **devs,
- unsigned int num_devs)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.id = id;
- msg->header.length = sizeof(*msg);
- msg->stream = stream;
- msg->devs = devs;
- msg->num_devs = num_devs;
-}
-
-static void
-init_dump_debug_info_msg(struct audio_thread_dump_debug_info_msg *msg,
- struct audio_debug_info *info)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.id = AUDIO_THREAD_DUMP_THREAD_INFO;
- msg->header.length = sizeof(*msg);
- msg->info = info;
-}
-
-static void
-init_config_global_remix_msg(struct audio_thread_config_global_remix *msg)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.id = AUDIO_THREAD_CONFIG_GLOBAL_REMIX;
- msg->header.length = sizeof(*msg);
-}
-
-static void
-init_device_start_ramp_msg(struct audio_thread_dev_start_ramp_msg *msg,
- enum AUDIO_THREAD_COMMAND id, unsigned int dev_idx,
- enum CRAS_IODEV_RAMP_REQUEST request)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.id = id;
- msg->header.length = sizeof(*msg);
- msg->dev_idx = dev_idx;
- msg->request = request;
-}
-
-/* Exported Interface */
-
-int audio_thread_event_log_shm_fd()
-{
- return atlog_ro_shm_fd;
-}
-
-int audio_thread_add_stream(struct audio_thread *thread,
- struct cras_rstream *stream,
- struct cras_iodev **devs, unsigned int num_devs)
-{
- struct audio_thread_add_rm_stream_msg msg;
-
- assert(thread && stream);
-
- if (!thread->started)
- return -EINVAL;
-
- init_add_rm_stream_msg(&msg, AUDIO_THREAD_ADD_STREAM, stream, devs,
- num_devs);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_disconnect_stream(struct audio_thread *thread,
- struct cras_rstream *stream,
- struct cras_iodev *dev)
-{
- struct audio_thread_add_rm_stream_msg msg;
-
- assert(thread && stream);
-
- init_add_rm_stream_msg(&msg, AUDIO_THREAD_DISCONNECT_STREAM, stream,
- &dev, 0);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_drain_stream(struct audio_thread *thread,
- struct cras_rstream *stream)
-{
- struct audio_thread_add_rm_stream_msg msg;
-
- assert(thread && stream);
-
- init_add_rm_stream_msg(&msg, AUDIO_THREAD_DRAIN_STREAM, stream, NULL,
- 0);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_dump_thread_info(struct audio_thread *thread,
- struct audio_debug_info *info)
-{
- struct audio_thread_dump_debug_info_msg msg;
-
- init_dump_debug_info_msg(&msg, info);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_set_aec_dump(struct audio_thread *thread,
- cras_stream_id_t stream_id, unsigned int start,
- int fd)
-{
- struct audio_thread_aec_dump_msg msg;
-
- memset(&msg, 0, sizeof(msg));
- msg.header.id = AUDIO_THREAD_AEC_DUMP;
- msg.header.length = sizeof(msg);
- msg.stream_id = stream_id;
- msg.start = start;
- msg.fd = fd;
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_rm_callback_sync(struct audio_thread *thread, int fd)
-{
- struct audio_thread_rm_callback_msg msg;
-
- memset(&msg, 0, sizeof(msg));
- msg.header.id = AUDIO_THREAD_REMOVE_CALLBACK;
- msg.header.length = sizeof(msg);
- msg.fd = fd;
-
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_config_global_remix(struct audio_thread *thread,
- unsigned int num_channels,
- const float *coefficient)
-{
- int err;
- int identity_remix = 1;
- unsigned int i, j;
- struct audio_thread_config_global_remix msg;
- void *rsp;
-
- init_config_global_remix_msg(&msg);
-
- /* Check if the coefficients represent an identity matrix for remix
- * conversion, which means no remix at all. If so then leave the
- * converter as NULL. */
- for (i = 0; i < num_channels; i++) {
- if (coefficient[i * num_channels + i] != 1.0f) {
- identity_remix = 0;
- break;
- }
- for (j = i + 1; j < num_channels; j++) {
- if (coefficient[i * num_channels + j] != 0 ||
- coefficient[j * num_channels + i] != 0) {
- identity_remix = 0;
- break;
- }
- }
- }
-
- if (!identity_remix) {
- msg.fmt_conv = cras_channel_remix_conv_create(num_channels,
- coefficient);
- if (NULL == msg.fmt_conv)
- return -ENOMEM;
- }
-
- err = write(thread->to_thread_fds[1], &msg, msg.header.length);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to post message to thread.");
- return err;
- }
- /* Synchronous action, wait for response. */
- err = read_until_finished(thread->to_main_fds[0], &rsp, sizeof(rsp));
- if (err < 0) {
- syslog(LOG_ERR, "Failed to read reply from thread.");
- return err;
- }
-
- if (rsp)
- cras_fmt_conv_destroy((struct cras_fmt_conv **)&rsp);
- return 0;
-}
-
-struct audio_thread *audio_thread_create()
-{
- int rc;
- struct audio_thread *thread;
-
- thread = (struct audio_thread *)calloc(1, sizeof(*thread));
- if (!thread)
- return NULL;
-
- thread->to_thread_fds[0] = -1;
- thread->to_thread_fds[1] = -1;
- thread->to_main_fds[0] = -1;
- thread->to_main_fds[1] = -1;
-
- /* Two way pipes for communication with the device's audio thread. */
- rc = pipe(thread->to_thread_fds);
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to pipe");
- free(thread);
- return NULL;
- }
- rc = pipe(thread->to_main_fds);
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to pipe");
- free(thread);
- return NULL;
- }
-
- if (asprintf(&atlog_name, "/ATlog-%d", getpid()) < 0) {
- syslog(LOG_ERR, "Failed to generate ATlog name.");
- exit(-1);
- }
-
- atlog = audio_thread_event_log_init(atlog_name);
-
- thread->pollfds_size = 32;
- thread->pollfds = (struct pollfd *)malloc(sizeof(*thread->pollfds) *
- thread->pollfds_size);
-
- return thread;
-}
-
-int audio_thread_add_open_dev(struct audio_thread *thread,
- struct cras_iodev *dev)
-{
- struct audio_thread_open_device_msg msg;
-
- assert(thread && dev);
-
- if (!thread->started)
- return -EINVAL;
-
- init_open_device_msg(&msg, AUDIO_THREAD_ADD_OPEN_DEV, dev);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_rm_open_dev(struct audio_thread *thread,
- enum CRAS_STREAM_DIRECTION dir,
- unsigned int dev_idx)
-{
- struct audio_thread_rm_device_msg msg;
-
- assert(thread);
- if (!thread->started)
- return -EINVAL;
-
- init_rm_device_msg(&msg, dir, dev_idx);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_is_dev_open(struct audio_thread *thread,
- struct cras_iodev *dev)
-{
- struct audio_thread_open_device_msg msg;
-
- if (!dev)
- return 0;
-
- init_open_device_msg(&msg, AUDIO_THREAD_IS_DEV_OPEN, dev);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_dev_start_ramp(struct audio_thread *thread,
- unsigned int dev_idx,
- enum CRAS_IODEV_RAMP_REQUEST request)
-{
- struct audio_thread_dev_start_ramp_msg msg;
-
- assert(thread);
-
- if (!thread->started)
- return -EINVAL;
-
- init_device_start_ramp_msg(&msg, AUDIO_THREAD_DEV_START_RAMP, dev_idx,
- request);
- return audio_thread_post_message(thread, &msg.header);
-}
-
-int audio_thread_start(struct audio_thread *thread)
-{
- int rc;
-
- rc = pthread_create(&thread->tid, NULL, audio_io_thread, thread);
- if (rc) {
- syslog(LOG_ERR, "Failed pthread_create");
- return rc;
- }
-
- thread->started = 1;
-
- return 0;
-}
-
-void audio_thread_destroy(struct audio_thread *thread)
-{
- if (thread->started) {
- struct audio_thread_msg msg;
-
- msg.id = AUDIO_THREAD_STOP;
- msg.length = sizeof(msg);
- audio_thread_post_message(thread, &msg);
- pthread_join(thread->tid, NULL);
- }
-
- free(thread->pollfds);
-
- audio_thread_event_log_deinit(atlog, atlog_name);
- free(atlog_name);
-
- if (thread->to_thread_fds[0] != -1) {
- close(thread->to_thread_fds[0]);
- close(thread->to_thread_fds[1]);
- }
- if (thread->to_main_fds[0] != -1) {
- close(thread->to_main_fds[0]);
- close(thread->to_main_fds[1]);
- }
-
- if (thread->remix_converter)
- cras_fmt_conv_destroy(&thread->remix_converter);
-
- free(thread);
-}
diff --git a/cras/src/server/audio_thread.h b/cras/src/server/audio_thread.h
deleted file mode 100644
index 34b47863..00000000
--- a/cras/src/server/audio_thread.h
+++ /dev/null
@@ -1,222 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef AUDIO_THREAD_H_
-#define AUDIO_THREAD_H_
-
-#include <pthread.h>
-#include <stdint.h>
-
-#include "cras_iodev.h"
-#include "cras_types.h"
-#include "dev_io.h"
-
-struct buffer_share;
-struct cras_fmt_conv;
-struct cras_iodev;
-struct cras_rstream;
-struct dev_stream;
-
-/* Hold communication pipes and pthread info for the thread used to play or
- * record audio.
- * to_thread_fds - Send a message from main to running thread.
- * to_main_fds - Send a synchronous response to main from running thread.
- * tid - Thread ID of the running playback/capture thread.
- * started - Non-zero if the thread has started successfully.
- * suspended - Non-zero if the thread is suspended.
- * open_devs - Lists of open input and output devices.
- * pollfds - What FDs wake up this thread.
- * pollfds_size - Number of available poll fds.
- * num_pollfds - Number of currently registered poll fds.
- * remix_converter - Format converter used to remix output channels.
- */
-struct audio_thread {
- int to_thread_fds[2];
- int to_main_fds[2];
- pthread_t tid;
- int started;
- int suspended;
- struct open_dev *open_devs[CRAS_NUM_DIRECTIONS];
- struct pollfd *pollfds;
- size_t pollfds_size;
- size_t num_pollfds;
- struct cras_fmt_conv *remix_converter;
-};
-
-/*
- * Enum to specify how a registered event callback be triggered.
- * TRIGGER_NONE - Callback will not be triggered.
- * TRIGGER_POLL - Triggered by poll given fd and revent.
- * TRIGGER_WAKEUP - Triggered everytime when audio thread wakes up.
- */
-enum AUDIO_THREAD_EVENTS_CB_TRIGGER {
- TRIGGER_NONE,
- TRIGGER_POLL,
- TRIGGER_WAKEUP,
-};
-
-/* Callback function to be handled in main loop in audio thread.
- * Args:
- * data - The data for callback function.
- * revent - The returned event from ppoll().
- */
-typedef int (*thread_callback)(void *data, int revent);
-
-/* Creates an audio thread.
- * Returns:
- * A pointer to the newly created audio thread. It must be freed by calling
- * audio_thread_destroy(). Returns NULL on error.
- */
-struct audio_thread *audio_thread_create();
-
-/* Adds an open device.
- * Args:
- * thread - The thread to add open device to.
- * dev - The open device to add.
- */
-int audio_thread_add_open_dev(struct audio_thread *thread,
- struct cras_iodev *dev);
-
-/* Removes an open device.
- * Args:
- * thread - The thread to remove open device from.
- * dev - The open device to remove.
- */
-int audio_thread_rm_open_dev(struct audio_thread *thread,
- enum CRAS_STREAM_DIRECTION dir,
- unsigned int dev_idx);
-
-/* Checks if dev is open and used by audio thread.
- * Args:
- * thread - The thread accessing open devs.
- * dev - The device to check if it has already been open.
- */
-int audio_thread_is_dev_open(struct audio_thread *thread,
- struct cras_iodev *dev);
-
-/* Adds a thread_callback to audio thread for requested events. By default
- * the callback trigger is set to TRIGGER_POLL.
- * Args:
- * fd - The file descriptor to be polled for the callback.
- * The callback will be called when any of requested events matched.
- * cb - The callback function.
- * data - The data for the callback function.
- * events - The requested events to ppoll().
- */
-void audio_thread_add_events_callback(int fd, thread_callback cb, void *data,
- int events);
-
-/* Removes an thread_callback from audio thread.
- * Args:
- * fd - The file descriptor of the previous added callback.
- */
-void audio_thread_rm_callback(int fd);
-
-/* Removes a thread_callback from main thread.
- * Args:
- * thread - The thread to remove callback from.
- * fd - The file descriptor of the previous added callback.
- */
-int audio_thread_rm_callback_sync(struct audio_thread *thread, int fd);
-
-/* Configures the callback associated with fd when it should be triggerred.
- * Args:
- * fd - The file descriptor associate to the callback.
- * trigger - Specifies how the callback should be triggered.
- */
-void audio_thread_config_events_callback(
- int fd, enum AUDIO_THREAD_EVENTS_CB_TRIGGER trigger);
-
-/* Starts a thread created with audio_thread_create.
- * Args:
- * thread - The thread to start.
- * Returns:
- * 0 on success, return code from pthread_crate on failure.
- */
-int audio_thread_start(struct audio_thread *thread);
-
-/* Frees an audio thread created with audio_thread_create(). */
-void audio_thread_destroy(struct audio_thread *thread);
-
-/* Returns the shm fd for the ATlog. */
-int audio_thread_event_log_shm_fd();
-
-/* Add a stream to the thread. After this call, the ownership of the stream will
- * be passed to the audio thread. Audio thread is responsible to release the
- * stream's resources.
- * Args:
- * thread - a pointer to the audio thread.
- * stream - the new stream to add.
- * devs - an array of devices to attach stream.
- * num_devs - number of devices in the array pointed by devs
- * Returns:
- * zero on success, negative error from the AUDIO_THREAD enum above when an
- * the thread can't be added.
- */
-int audio_thread_add_stream(struct audio_thread *thread,
- struct cras_rstream *stream,
- struct cras_iodev **devs, unsigned int num_devs);
-
-/* Begin draining a stream and check the draining status.
- * Args:
- * thread - a pointer to the audio thread.
- * stream - the stream to drain/remove.
- * Returns:
- * zero if the stream is drained and can be deleted. If the stream is not
- * completely drained, then the number of milliseconds until is is drained
- * are returned.
- */
-int audio_thread_drain_stream(struct audio_thread *thread,
- struct cras_rstream *stream);
-
-/* Disconnect a stream from the client.
- * Args:
- * thread - a pointer to the audio thread.
- * stream - the stream to be disconnected.
- * iodev - the device to disconnect from.
- * Returns:
- * 0 on success, negative if error.
- */
-int audio_thread_disconnect_stream(struct audio_thread *thread,
- struct cras_rstream *stream,
- struct cras_iodev *iodev);
-
-/* Dumps information about all active streams to syslog. */
-int audio_thread_dump_thread_info(struct audio_thread *thread,
- struct audio_debug_info *info);
-
-/* Starts or stops the aec dump task.
- * Args:
- * thread - pointer to the audio thread.
- * stream_id - id of the target stream for aec dump.
- * start - True to start the aec dump, false to stop.
- * fd - File to store aec dump result.
- */
-int audio_thread_set_aec_dump(struct audio_thread *thread,
- cras_stream_id_t stream_id, unsigned int start,
- int fd);
-
-/* Configures the global converter for output remixing. Called by main
- * thread. */
-int audio_thread_config_global_remix(struct audio_thread *thread,
- unsigned int num_channels,
- const float *coefficient);
-
-/* Start ramping on a device.
- *
- * Ramping is started/updated in audio thread. This function lets the main
- * thread request that the audio thread start ramping.
- *
- * Args:
- * thread - a pointer to the audio thread.
- * dev_idx - Index of the the device to start ramping.
- * request - Check the docstrings of CRAS_IODEV_RAMP_REQUEST.
- * Returns:
- * 0 on success, negative if error.
- */
-int audio_thread_dev_start_ramp(struct audio_thread *thread,
- unsigned int dev_idx,
- enum CRAS_IODEV_RAMP_REQUEST request);
-#endif /* AUDIO_THREAD_H_ */
diff --git a/cras/src/server/audio_thread_log.h b/cras/src/server/audio_thread_log.h
deleted file mode 100644
index ee5d159c..00000000
--- a/cras/src/server/audio_thread_log.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * The blow logging funcitons must only be called from the audio thread.
- */
-
-#ifndef AUDIO_THREAD_LOG_H_
-#define AUDIO_THREAD_LOG_H_
-
-#include <sys/mman.h>
-#include <pthread.h>
-#include <stdint.h>
-#include <syslog.h>
-
-#include "cras_types.h"
-#include "cras_shm.h"
-
-#define AUDIO_THREAD_LOGGING 1
-
-#if (AUDIO_THREAD_LOGGING)
-#define ATLOG(log, event, data1, data2, data3) \
- audio_thread_event_log_data(log, event, data1, data2, data3);
-#else
-#define ATLOG(log, event, data1, data2, data3)
-#endif
-
-extern struct audio_thread_event_log *atlog;
-extern int atlog_rw_shm_fd;
-extern int atlog_ro_shm_fd;
-
-static inline struct audio_thread_event_log *
-audio_thread_event_log_init(char *name)
-{
- struct audio_thread_event_log *log;
-
- atlog_ro_shm_fd = -1;
- atlog_rw_shm_fd = -1;
-
- log = (struct audio_thread_event_log *)cras_shm_setup(
- name, sizeof(*log), &atlog_rw_shm_fd, &atlog_ro_shm_fd);
- /* Fallback to calloc if device shared memory resource is empty and
- * cras_shm_setup fails.
- */
- if (log == NULL) {
- syslog(LOG_ERR, "Failed to create atlog by cras_shm_setup");
- log = (struct audio_thread_event_log *)calloc(
- 1, sizeof(struct audio_thread_event_log));
- }
- log->len = AUDIO_THREAD_EVENT_LOG_SIZE;
-
- return log;
-}
-
-static inline void
-audio_thread_event_log_deinit(struct audio_thread_event_log *log, char *name)
-{
- if (log) {
- if (atlog_rw_shm_fd >= 0) {
- munmap(log, sizeof(*log));
- cras_shm_close_unlink(name, atlog_rw_shm_fd);
- } else {
- free(log);
- }
-
- if (atlog_ro_shm_fd >= 0)
- close(atlog_ro_shm_fd);
- }
-}
-
-/* Log a tag and the current time, Uses two words, the first is split
- * 8 bits for tag and 24 for seconds, second word is micro seconds.
- */
-static inline void
-audio_thread_event_log_data(struct audio_thread_event_log *log,
- enum AUDIO_THREAD_LOG_EVENTS event, uint32_t data1,
- uint32_t data2, uint32_t data3)
-{
- struct timespec now;
- uint64_t pos_mod_len = log->write_pos % AUDIO_THREAD_EVENT_LOG_SIZE;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- log->log[pos_mod_len].tag_sec =
- (event << 24) | (now.tv_sec & 0x00ffffff);
- log->log[pos_mod_len].nsec = now.tv_nsec;
- log->log[pos_mod_len].data1 = data1;
- log->log[pos_mod_len].data2 = data2;
- log->log[pos_mod_len].data3 = data3;
-
- log->write_pos++;
-}
-
-#endif /* AUDIO_THREAD_LOG_H_ */
diff --git a/cras/src/server/buffer_share.c b/cras/src/server/buffer_share.c
deleted file mode 100644
index 5d106f05..00000000
--- a/cras/src/server/buffer_share.c
+++ /dev/null
@@ -1,171 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include <sys/param.h>
-
-#include "cras_types.h"
-#include "buffer_share.h"
-
-static inline struct id_offset *find_unused(const struct buffer_share *mix)
-{
- unsigned int i;
-
- for (i = 0; i < mix->id_sz; i++) {
- if (!mix->wr_idx[i].used)
- return &mix->wr_idx[i];
- }
-
- return NULL;
-}
-
-static inline struct id_offset *find_id(const struct buffer_share *mix,
- unsigned int id)
-{
- unsigned int i;
-
- for (i = 0; i < mix->id_sz; i++) {
- if (mix->wr_idx[i].used && id == mix->wr_idx[i].id)
- return &mix->wr_idx[i];
- }
-
- return NULL;
-}
-
-static void alloc_more_ids(struct buffer_share *mix)
-{
- unsigned int new_size = mix->id_sz * 2;
- unsigned int i;
-
- mix->wr_idx = (struct id_offset *)realloc(
- mix->wr_idx, sizeof(mix->wr_idx[0]) * new_size);
-
- for (i = mix->id_sz; i < new_size; i++)
- mix->wr_idx[i].used = 0;
-
- mix->id_sz = new_size;
-}
-
-struct buffer_share *buffer_share_create(unsigned int buf_sz)
-{
- struct buffer_share *mix;
-
- mix = (struct buffer_share *)calloc(1, sizeof(*mix));
- mix->id_sz = INITIAL_ID_SIZE;
- mix->wr_idx =
- (struct id_offset *)calloc(mix->id_sz, sizeof(mix->wr_idx[0]));
- mix->buf_sz = buf_sz;
-
- return mix;
-}
-
-void buffer_share_destroy(struct buffer_share *mix)
-{
- if (!mix)
- return;
- free(mix->wr_idx);
- free(mix);
-}
-
-int buffer_share_add_id(struct buffer_share *mix, unsigned int id, void *data)
-{
- struct id_offset *o;
-
- o = find_id(mix, id);
- if (o)
- return -EEXIST;
-
- o = find_unused(mix);
- if (!o)
- alloc_more_ids(mix);
-
- o = find_unused(mix);
- o->used = 1;
- o->id = id;
- o->offset = 0;
- o->data = data;
-
- return 0;
-}
-
-int buffer_share_rm_id(struct buffer_share *mix, unsigned int id)
-{
- struct id_offset *o;
-
- o = find_id(mix, id);
- if (!o)
- return -ENOENT;
- o->used = 0;
- o->data = NULL;
-
- return 0;
-}
-
-int buffer_share_offset_update(struct buffer_share *mix, unsigned int id,
- unsigned int delta)
-{
- unsigned int i;
-
- for (i = 0; i < mix->id_sz; i++) {
- if (id != mix->wr_idx[i].id)
- continue;
-
- mix->wr_idx[i].offset += delta;
- break;
- }
-
- return 0;
-}
-
-unsigned int buffer_share_get_new_write_point(struct buffer_share *mix)
-{
- unsigned int min_written = mix->buf_sz + 1;
- unsigned int i;
-
- for (i = 0; i < mix->id_sz; i++) {
- struct id_offset *o = &mix->wr_idx[i];
-
- if (!o->used)
- continue;
-
- min_written = MIN(min_written, o->offset);
- }
- for (i = 0; i < mix->id_sz; i++) {
- struct id_offset *o = &mix->wr_idx[i];
- o->offset -= min_written;
- }
-
- if (min_written > mix->buf_sz)
- return 0;
-
- return min_written;
-}
-
-static struct id_offset *get_id_offset(const struct buffer_share *mix,
- unsigned int id)
-{
- unsigned int i;
- struct id_offset *o;
-
- for (i = 0; i < mix->id_sz; i++) {
- o = &mix->wr_idx[i];
- if (o->used && o->id == id)
- return o;
- }
- return NULL;
-}
-
-unsigned int buffer_share_id_offset(const struct buffer_share *mix,
- unsigned int id)
-{
- struct id_offset *o = get_id_offset(mix, id);
- return o ? o->offset : 0;
-}
-
-void *buffer_share_get_data(const struct buffer_share *mix, unsigned int id)
-{
- struct id_offset *o = get_id_offset(mix, id);
- return o ? o->data : NULL;
-}
diff --git a/cras/src/server/buffer_share.h b/cras/src/server/buffer_share.h
deleted file mode 100644
index c61c7a07..00000000
--- a/cras/src/server/buffer_share.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef BUFFER_SHARE_H_
-#define BUFFER_SHARE_H_
-
-#define INITIAL_ID_SIZE 3
-
-struct id_offset {
- unsigned int used;
- unsigned int id;
- unsigned int offset;
- void *data;
-};
-
-struct buffer_share {
- unsigned int buf_sz;
- unsigned int id_sz;
- struct id_offset *wr_idx;
-};
-
-/*
- * Creates a buffer share object. This object is used to manage the read or
- * write offsets of several users in one shared buffer.
- */
-struct buffer_share *buffer_share_create(unsigned int buf_sz);
-
-/* Destroys a buffer_share returned from buffer_share_create. */
-void buffer_share_destroy(struct buffer_share *mix);
-
-/* Adds an ID that shares the buffer. */
-int buffer_share_add_id(struct buffer_share *mix, unsigned int id, void *data);
-
-/* Removes an ID that shares the buffer. */
-int buffer_share_rm_id(struct buffer_share *mix, unsigned int id);
-
-/* Updates the offset of the given user into the shared buffer. */
-int buffer_share_offset_update(struct buffer_share *mix, unsigned int id,
- unsigned int frames);
-
-/*
- * Updates the write point to the minimum offset from all users.
- * Returns the number of minimum number of frames written.
- */
-unsigned int buffer_share_get_new_write_point(struct buffer_share *mix);
-
-/*
- * The amount by which the user given by id is ahead of the current write
- * point.
- */
-unsigned int buffer_share_id_offset(const struct buffer_share *mix,
- unsigned int id);
-
-/*
- * Gets the data pointer for given id.
- */
-void *buffer_share_get_data(const struct buffer_share *mix, unsigned int id);
-
-#endif /* BUFFER_SHARE_H_ */
diff --git a/cras/src/server/config/cras_board_config.c b/cras/src/server/config/cras_board_config.c
deleted file mode 100644
index e36ea3cf..00000000
--- a/cras/src/server/config/cras_board_config.c
+++ /dev/null
@@ -1,97 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <syslog.h>
-
-#include "cras_board_config.h"
-#include "iniparser_wrapper.h"
-
-static const int32_t DEFAULT_OUTPUT_BUFFER_SIZE = 512;
-static const int32_t AEC_SUPPORTED_DEFAULT = 0;
-static const int32_t AEC_GROUP_ID_DEFAULT = -1;
-static const int32_t BLUETOOTH_WBS_ENABLED_INI_DEFAULT = 1;
-static const int32_t BLUETOOTH_DEPRIORITIZE_WBS_MIC_INI_DEFAULT = 0;
-static const int32_t HOTWORD_PAUSE_AT_SUSPEND_DEFAULT = 0;
-
-#define CONFIG_NAME "board.ini"
-#define DEFAULT_OUTPUT_BUF_SIZE_INI_KEY "output:default_output_buffer_size"
-#define AEC_SUPPORTED_INI_KEY "processing:aec_supported"
-#define AEC_GROUP_ID_INI_KEY "processing:group_id"
-#define BLUETOOTH_WBS_ENABLED_INI_KEY "bluetooth:wbs_enabled"
-#define BLUETOOTH_DEPRIORITIZE_WBS_MIC_INI_KEY "bluetooth:deprioritize_wbs_mic"
-#define UCM_IGNORE_SUFFIX_KEY "ucm:ignore_suffix"
-#define HOTWORD_PAUSE_AT_SUSPEND "hotword:pause_at_suspend"
-
-void cras_board_config_get(const char *config_path,
- struct cras_board_config *board_config)
-{
- char ini_name[MAX_INI_NAME_LENGTH + 1];
- char ini_key[MAX_INI_KEY_LENGTH + 1];
- const char *ptr;
- dictionary *ini;
-
- board_config->default_output_buffer_size = DEFAULT_OUTPUT_BUFFER_SIZE;
- board_config->aec_supported = AEC_SUPPORTED_DEFAULT;
- board_config->aec_group_id = AEC_GROUP_ID_DEFAULT;
- board_config->ucm_ignore_suffix = NULL;
- board_config->bt_wbs_enabled = BLUETOOTH_WBS_ENABLED_INI_DEFAULT;
- board_config->deprioritize_bt_wbs_mic =
- BLUETOOTH_DEPRIORITIZE_WBS_MIC_INI_DEFAULT;
- if (config_path == NULL)
- return;
-
- snprintf(ini_name, MAX_INI_NAME_LENGTH, "%s/%s", config_path,
- CONFIG_NAME);
- ini_name[MAX_INI_NAME_LENGTH] = '\0';
- ini = iniparser_load_wrapper(ini_name);
- if (ini == NULL) {
- syslog(LOG_DEBUG, "No ini file %s", ini_name);
- return;
- }
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, DEFAULT_OUTPUT_BUF_SIZE_INI_KEY);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- board_config->default_output_buffer_size =
- iniparser_getint(ini, ini_key, DEFAULT_OUTPUT_BUFFER_SIZE);
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, AEC_SUPPORTED_INI_KEY);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- board_config->aec_supported =
- iniparser_getint(ini, ini_key, AEC_SUPPORTED_DEFAULT);
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, AEC_GROUP_ID_INI_KEY);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- board_config->aec_group_id =
- iniparser_getint(ini, ini_key, AEC_GROUP_ID_DEFAULT);
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, BLUETOOTH_WBS_ENABLED_INI_KEY);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- board_config->bt_wbs_enabled = iniparser_getint(
- ini, ini_key, BLUETOOTH_WBS_ENABLED_INI_DEFAULT);
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH,
- BLUETOOTH_DEPRIORITIZE_WBS_MIC_INI_KEY);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- board_config->deprioritize_bt_wbs_mic = iniparser_getint(
- ini, ini_key, BLUETOOTH_DEPRIORITIZE_WBS_MIC_INI_DEFAULT);
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, UCM_IGNORE_SUFFIX_KEY);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- ptr = iniparser_getstring(ini, ini_key, "");
- if (ptr) {
- board_config->ucm_ignore_suffix = strdup(ptr);
- if (!board_config->ucm_ignore_suffix)
- syslog(LOG_ERR, "Failed to call strdup: %d", errno);
- }
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, HOTWORD_PAUSE_AT_SUSPEND);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- board_config->hotword_pause_at_suspend = iniparser_getint(
- ini, ini_key, HOTWORD_PAUSE_AT_SUSPEND_DEFAULT);
-
- iniparser_freedict(ini);
- syslog(LOG_DEBUG, "Loaded ini file %s", ini_name);
-}
diff --git a/cras/src/server/config/cras_board_config.h b/cras/src/server/config/cras_board_config.h
deleted file mode 100644
index d4bd8496..00000000
--- a/cras/src/server/config/cras_board_config.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BOARD_CONFIG_H_
-#define CRAS_BOARD_CONFIG_H_
-
-#include <stdint.h>
-
-struct cras_board_config {
- int32_t default_output_buffer_size;
- int32_t aec_supported;
- int32_t aec_group_id;
- int32_t bt_wbs_enabled;
- int32_t deprioritize_bt_wbs_mic;
- char *ucm_ignore_suffix;
- int32_t hotword_pause_at_suspend;
-};
-
-/* Gets a configuration based on the config file specified.
- * Args:
- * config_path - Path containing the config files.
- * board_config - The returned configs.
- */
-void cras_board_config_get(const char *config_path,
- struct cras_board_config *board_config);
-
-#endif /* CRAS_BOARD_CONFIG_H_ */
diff --git a/cras/src/server/config/cras_card_config.c b/cras/src/server/config/cras_card_config.c
deleted file mode 100644
index ae36565d..00000000
--- a/cras/src/server/config/cras_card_config.c
+++ /dev/null
@@ -1,110 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_util.h"
-#include "cras_volume_curve.h"
-#include "iniparser_wrapper.h"
-#include "utlist.h"
-
-struct cras_card_config {
- dictionary *ini;
-};
-
-static struct cras_volume_curve *
-create_simple_step_curve(const struct cras_card_config *card_config,
- const char *control_name)
-{
- char ini_key[MAX_INI_KEY_LENGTH + 1];
- int max_volume;
- int volume_step;
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, "%s:max_volume", control_name);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- max_volume = iniparser_getint(card_config->ini, ini_key, 0);
- snprintf(ini_key, MAX_INI_KEY_LENGTH, "%s:volume_step", control_name);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- volume_step = iniparser_getint(card_config->ini, ini_key, 300);
- syslog(LOG_INFO, "Configure curve found for %s.", control_name);
- return cras_volume_curve_create_simple_step(max_volume, volume_step);
-}
-
-static struct cras_volume_curve *
-create_explicit_curve(const struct cras_card_config *card_config,
- const char *control_name)
-{
- unsigned int i;
- char ini_key[MAX_INI_KEY_LENGTH + 1];
- long dB_values[101];
-
- for (i = 0; i < 101; i++) {
- snprintf(ini_key, MAX_INI_KEY_LENGTH, "%s:dB_at_%u",
- control_name, i);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- dB_values[i] = iniparser_getint(card_config->ini, ini_key, 0);
- }
- syslog(LOG_INFO, "Explicit volume curve found for %s.", control_name);
- return cras_volume_curve_create_explicit(dB_values);
-}
-
-/*
- * Exported interface.
- */
-
-struct cras_card_config *cras_card_config_create(const char *config_path,
- const char *card_name)
-{
- struct cras_card_config *card_config = NULL;
- char ini_name[MAX_INI_NAME_LENGTH + 1];
- dictionary *ini;
-
- snprintf(ini_name, MAX_INI_NAME_LENGTH, "%s/%s", config_path,
- card_name);
- ini_name[MAX_INI_NAME_LENGTH] = '\0';
- ini = iniparser_load_wrapper(ini_name);
- if (ini == NULL) {
- syslog(LOG_DEBUG, "No ini file %s", ini_name);
- return NULL;
- }
-
- card_config = calloc(1, sizeof(*card_config));
- if (card_config == NULL) {
- iniparser_freedict(ini);
- return NULL;
- }
-
- card_config->ini = ini;
- syslog(LOG_DEBUG, "Loaded ini file %s", ini_name);
- return card_config;
-}
-
-void cras_card_config_destroy(struct cras_card_config *card_config)
-{
- assert(card_config);
- iniparser_freedict(card_config->ini);
- free(card_config);
-}
-
-struct cras_volume_curve *cras_card_config_get_volume_curve_for_control(
- const struct cras_card_config *card_config, const char *control_name)
-{
- char ini_key[MAX_INI_KEY_LENGTH + 1];
- const char *curve_type;
-
- if (card_config == NULL || control_name == NULL)
- return NULL;
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, "%s:volume_curve", control_name);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- curve_type = iniparser_getstring(card_config->ini, ini_key, NULL);
-
- if (curve_type && strcmp(curve_type, "simple_step") == 0)
- return create_simple_step_curve(card_config, control_name);
- if (curve_type && strcmp(curve_type, "explicit") == 0)
- return create_explicit_curve(card_config, control_name);
- syslog(LOG_DEBUG, "No configure curve found for %s.", control_name);
- return NULL;
-}
diff --git a/cras/src/server/config/cras_card_config.h b/cras/src/server/config/cras_card_config.h
deleted file mode 100644
index 22ddc398..00000000
--- a/cras/src/server/config/cras_card_config.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_CARD_CONFIG_H_
-#define CRAS_CARD_CONFIG_H_
-
-struct cras_card_config;
-struct cras_volume_curve;
-
-/* Creates a configuration based on the config file specified.
- * Args:
- * config_path - Path containing the config files.
- * card_name - Name of the card to load a configuration for.
- * Returns:
- * A pointer to the created config on success, NULL on failure.
- */
-struct cras_card_config *cras_card_config_create(const char *config_path,
- const char *card_name);
-
-/* Destroys a configuration returned by cras_card_config_create().
- * Args:
- * card_config - Card configuration returned by cras_card_config_create()
- */
-void cras_card_config_destroy(struct cras_card_config *card_config);
-
-/* Returns the apporpriate volume curve to use for the control given by name.
- * Args:
- * card_config - Card configuration returned by cras_card_config_create()
- * Returns:
- * The specialized curve for the control if there is one, otherwise NULL.
- */
-struct cras_volume_curve *cras_card_config_get_volume_curve_for_control(
- const struct cras_card_config *card_config, const char *control_name);
-
-#endif /* CRAS_CARD_CONFIG_H_ */
diff --git a/cras/src/server/config/cras_device_blocklist.c b/cras/src/server/config/cras_device_blocklist.c
deleted file mode 100644
index d418fb80..00000000
--- a/cras/src/server/config/cras_device_blocklist.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "cras_device_blocklist.h"
-#include "iniparser_wrapper.h"
-#include "utlist.h"
-
-struct cras_device_blocklist {
- dictionary *ini;
-};
-
-/*
- * Exported Interface
- */
-
-struct cras_device_blocklist *
-cras_device_blocklist_create(const char *config_path)
-{
- struct cras_device_blocklist *blocklist;
- char ini_name[MAX_INI_NAME_LENGTH + 1];
-
- blocklist = calloc(1, sizeof(*blocklist));
- if (!blocklist)
- return NULL;
-
- snprintf(ini_name, MAX_INI_NAME_LENGTH, "%s/%s", config_path,
- "device_blocklist");
- ini_name[MAX_INI_NAME_LENGTH] = '\0';
- blocklist->ini = iniparser_load_wrapper(ini_name);
-
- return blocklist;
-}
-
-void cras_device_blocklist_destroy(struct cras_device_blocklist *blocklist)
-{
- if (blocklist && blocklist->ini)
- iniparser_freedict(blocklist->ini);
- free(blocklist);
-}
-
-int cras_device_blocklist_check(struct cras_device_blocklist *blocklist,
- unsigned vendor_id, unsigned product_id,
- unsigned desc_checksum, unsigned device_index)
-{
- char ini_key[MAX_INI_KEY_LENGTH + 1];
-
- if (!blocklist)
- return 0;
-
- snprintf(ini_key, MAX_INI_KEY_LENGTH, "USB_Outputs:%04x_%04x_%08x_%u",
- vendor_id, product_id, desc_checksum, device_index);
- ini_key[MAX_INI_KEY_LENGTH] = 0;
- return iniparser_getboolean(blocklist->ini, ini_key, 0);
-}
diff --git a/cras/src/server/config/cras_device_blocklist.h b/cras/src/server/config/cras_device_blocklist.h
deleted file mode 100644
index d0f750bd..00000000
--- a/cras/src/server/config/cras_device_blocklist.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Keeps a list of playback devices that should be ignored for a card. This is
- * useful for devices that present non-functional alsa devices. For instance
- * some mics show a phantom playback device.
- */
-#ifndef CRAS_DEVICE_BLOCKLIST_H_
-#define CRAS_DEVICE_BLOCKLIST_H_
-
-#include <stdint.h>
-
-#include "cras_types.h"
-
-struct cras_device_blocklist;
-
-/* Creates a blocklist of devices that should never be added to the system.
- * Args:
- * config_path - Path containing the config files.
- * Returns:
- * A pointer to the created blocklist on success, NULL on failure.
- */
-struct cras_device_blocklist *
-cras_device_blocklist_create(const char *config_path);
-
-/* Destroys a blocklist returned by cras_device_blocklist_create().
- * Args:
- * blocklist - Blocklist returned by cras_device_blocklist_create()
- */
-void cras_device_blocklist_destroy(struct cras_device_blocklist *blocklist);
-
-/* Checks if a playback device on a USB card is blocklisted.
- * Args:
- * blocklist - Blocklist returned by cras_device_blocklist_create()
- * vendor_id - USB vendor ID.
- * product_id - USB product ID.
- * device_index - Index of the alsa device in the card.
- * Returns:
- * 1 if the device is blocklisted, 0 otherwise.
- */
-int cras_device_blocklist_check(struct cras_device_blocklist *blocklist,
- unsigned vendor_id, unsigned product_id,
- unsigned desc_checksum, unsigned device_index);
-
-#endif /* CRAS_CARD_DEVICE_BLOCKLIST_H_ */
diff --git a/cras/src/server/cras.c b/cras/src/server/cras.c
deleted file mode 100644
index 8d23907a..00000000
--- a/cras/src/server/cras.c
+++ /dev/null
@@ -1,146 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#define _GNU_SOURCE /* for asprintf */
-#include <getopt.h>
-#include <signal.h>
-#include <stdio.h>
-#include <syslog.h>
-
-#include "cras_alsa_plugin_io.h"
-#include "cras_apm_list.h"
-#include "cras_config.h"
-#include "cras_iodev_list.h"
-#include "cras_server.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-#include "cras_dsp.h"
-
-static struct option long_options[] = {
- { "dsp_config", required_argument, 0, 'd' },
- { "syslog_mask", required_argument, 0, 'l' },
- { "device_config_dir", required_argument, 0, 'c' },
- { "disable_profile", required_argument, 0, 'D' },
- { "internal_ucm_suffix", required_argument, 0, 'u' },
- { 0, 0, 0, 0 }
-};
-
-/* Ignores sigpipe, we'll notice when a read/write fails. */
-static void set_signals()
-{
- signal(SIGPIPE, SIG_IGN);
- signal(SIGCHLD, SIG_IGN);
-}
-
-/* Entry point for the server. */
-int main(int argc, char **argv)
-{
- int c, option_index;
- int log_mask = LOG_WARNING;
- const char default_dsp_config[] = CRAS_CONFIG_FILE_DIR "/dsp.ini";
- const char *dsp_config = default_dsp_config;
- const char *device_config_dir = CRAS_CONFIG_FILE_DIR;
- const char *internal_ucm_suffix = NULL;
- unsigned int profile_disable_mask = 0;
-
- set_signals();
-
- while (1) {
- c = getopt_long(argc, argv, "", long_options, &option_index);
- if (c == -1)
- break;
-
- switch (c) {
- /* To keep this code simple we ask the (technical)
- user to pass one of integer values defined in
- syslog.h - this is a development feature after
- all. While there is no formal standard for the
- integer values there is an informal standard:
- http://tools.ietf.org/html/rfc5424#page-11 */
- case 'l':
- log_mask = atoi(optarg);
- break;
-
- case 'c':
- device_config_dir = optarg;
- break;
-
- case 'd':
- dsp_config = optarg;
- break;
- /* --disable_profile option takes list of profile names separated by ',' */
- case 'D':
- while ((optarg != NULL) && (*optarg != 0)) {
- if (strncmp(optarg, "hfp", 3) == 0) {
- profile_disable_mask |=
- CRAS_SERVER_PROFILE_MASK_HFP;
- }
- if (strncmp(optarg, "hsp", 3) == 0) {
- profile_disable_mask |=
- CRAS_SERVER_PROFILE_MASK_HSP;
- }
- if (strncmp(optarg, "a2dp", 4) == 0) {
- profile_disable_mask |=
- CRAS_SERVER_PROFILE_MASK_A2DP;
- }
- optarg = strchr(optarg, ',');
- if (optarg != NULL) {
- optarg++;
- }
- }
- break;
- case 'u':
- if (*optarg != 0)
- internal_ucm_suffix = optarg;
- break;
- default:
- break;
- }
- }
-
- switch (log_mask) {
- case LOG_EMERG:
- case LOG_ALERT:
- case LOG_CRIT:
- case LOG_ERR:
- case LOG_WARNING:
- case LOG_NOTICE:
- case LOG_INFO:
- case LOG_DEBUG:
- break;
- default:
- fprintf(stderr,
- "Unsupported syslog priority value: %d; using LOG_ERR=%d\n",
- log_mask, LOG_ERR);
- log_mask = LOG_ERR;
- break;
- }
- setlogmask(LOG_UPTO(log_mask));
-
- /* Initialize system. */
- cras_server_init();
- char *shm_name;
- if (asprintf(&shm_name, "/cras-%d", getpid()) < 0)
- exit(-1);
- int rw_shm_fd;
- int ro_shm_fd;
- struct cras_server_state *exp_state =
- (struct cras_server_state *)cras_shm_setup(
- shm_name, sizeof(*exp_state), &rw_shm_fd, &ro_shm_fd);
- if (!exp_state)
- exit(-1);
- cras_system_state_init(device_config_dir, shm_name, rw_shm_fd,
- ro_shm_fd, exp_state, sizeof(*exp_state));
- free(shm_name);
- if (internal_ucm_suffix)
- cras_system_state_set_internal_ucm_suffix(internal_ucm_suffix);
- cras_dsp_init(dsp_config);
- cras_apm_list_init(device_config_dir);
- cras_iodev_list_init();
- cras_alsa_plugin_io_init(device_config_dir);
-
- /* Start the server. */
- return cras_server_run(profile_disable_mask);
-}
diff --git a/cras/src/server/cras_a2dp_endpoint.c b/cras/src/server/cras_a2dp_endpoint.c
deleted file mode 100644
index 4cda169d..00000000
--- a/cras/src/server/cras_a2dp_endpoint.c
+++ /dev/null
@@ -1,226 +0,0 @@
-/* Copyright (c) 2013 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <stdint.h>
-#include <syslog.h>
-
-#include "a2dp-codecs.h"
-#include "cras_a2dp_endpoint.h"
-#include "cras_a2dp_iodev.h"
-#include "cras_iodev.h"
-#include "cras_bt_constants.h"
-#include "cras_bt_endpoint.h"
-#include "cras_bt_log.h"
-#include "cras_system_state.h"
-#include "cras_util.h"
-
-#define A2DP_SOURCE_ENDPOINT_PATH "/org/chromium/Cras/Bluetooth/A2DPSource"
-#define A2DP_SINK_ENDPOINT_PATH "/org/chromium/Cras/Bluetooth/A2DPSink"
-
-/* Pointers for the only connected a2dp device. */
-static struct a2dp {
- struct cras_iodev *iodev;
- struct cras_bt_device *device;
-} connected_a2dp;
-
-static int cras_a2dp_get_capabilities(struct cras_bt_endpoint *endpoint,
- void *capabilities, int *len)
-{
- a2dp_sbc_t *sbc_caps = capabilities;
-
- if (*len < sizeof(*sbc_caps))
- return -ENOSPC;
-
- *len = sizeof(*sbc_caps);
-
- /* Return all capabilities. */
- sbc_caps->channel_mode =
- SBC_CHANNEL_MODE_MONO | SBC_CHANNEL_MODE_DUAL_CHANNEL |
- SBC_CHANNEL_MODE_STEREO | SBC_CHANNEL_MODE_JOINT_STEREO;
- sbc_caps->frequency = SBC_SAMPLING_FREQ_16000 |
- SBC_SAMPLING_FREQ_32000 |
- SBC_SAMPLING_FREQ_44100 | SBC_SAMPLING_FREQ_48000;
- sbc_caps->allocation_method =
- SBC_ALLOCATION_SNR | SBC_ALLOCATION_LOUDNESS;
- sbc_caps->subbands = SBC_SUBBANDS_4 | SBC_SUBBANDS_8;
- sbc_caps->block_length = SBC_BLOCK_LENGTH_4 | SBC_BLOCK_LENGTH_8 |
- SBC_BLOCK_LENGTH_12 | SBC_BLOCK_LENGTH_16;
- sbc_caps->min_bitpool = MIN_BITPOOL;
- sbc_caps->max_bitpool = MAX_BITPOOL;
-
- return 0;
-}
-
-static int cras_a2dp_select_configuration(struct cras_bt_endpoint *endpoint,
- void *capabilities, int len,
- void *configuration)
-{
- a2dp_sbc_t *sbc_caps = capabilities;
- a2dp_sbc_t *sbc_config = configuration;
-
- /* Pick the highest configuration. */
- if (sbc_caps->channel_mode & SBC_CHANNEL_MODE_JOINT_STEREO) {
- sbc_config->channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
- } else if (sbc_caps->channel_mode & SBC_CHANNEL_MODE_STEREO) {
- sbc_config->channel_mode = SBC_CHANNEL_MODE_STEREO;
- } else if (sbc_caps->channel_mode & SBC_CHANNEL_MODE_DUAL_CHANNEL) {
- sbc_config->channel_mode = SBC_CHANNEL_MODE_DUAL_CHANNEL;
- } else if (sbc_caps->channel_mode & SBC_CHANNEL_MODE_MONO) {
- sbc_config->channel_mode = SBC_CHANNEL_MODE_MONO;
- } else {
- syslog(LOG_WARNING, "No supported channel modes.");
- return -ENOSYS;
- }
-
- if (sbc_caps->frequency & SBC_SAMPLING_FREQ_48000) {
- sbc_config->frequency = SBC_SAMPLING_FREQ_48000;
- } else if (sbc_caps->frequency & SBC_SAMPLING_FREQ_44100) {
- sbc_config->frequency = SBC_SAMPLING_FREQ_44100;
- } else if (sbc_caps->frequency & SBC_SAMPLING_FREQ_32000) {
- sbc_config->frequency = SBC_SAMPLING_FREQ_32000;
- } else if (sbc_caps->frequency & SBC_SAMPLING_FREQ_16000) {
- sbc_config->frequency = SBC_SAMPLING_FREQ_16000;
- } else {
- syslog(LOG_WARNING, "No supported sampling frequencies.");
- return -ENOSYS;
- }
-
- if (sbc_caps->allocation_method & SBC_ALLOCATION_LOUDNESS) {
- sbc_config->allocation_method = SBC_ALLOCATION_LOUDNESS;
- } else if (sbc_caps->allocation_method & SBC_ALLOCATION_SNR) {
- sbc_config->allocation_method = SBC_ALLOCATION_SNR;
- } else {
- syslog(LOG_WARNING, "No supported allocation method.");
- return -ENOSYS;
- }
-
- if (sbc_caps->subbands & SBC_SUBBANDS_8) {
- sbc_config->subbands = SBC_SUBBANDS_8;
- } else if (sbc_caps->subbands & SBC_SUBBANDS_4) {
- sbc_config->subbands = SBC_SUBBANDS_4;
- } else {
- syslog(LOG_WARNING, "No supported subbands.");
- return -ENOSYS;
- }
-
- if (sbc_caps->block_length & SBC_BLOCK_LENGTH_16) {
- sbc_config->block_length = SBC_BLOCK_LENGTH_16;
- } else if (sbc_caps->block_length & SBC_BLOCK_LENGTH_12) {
- sbc_config->block_length = SBC_BLOCK_LENGTH_12;
- } else if (sbc_caps->block_length & SBC_BLOCK_LENGTH_8) {
- sbc_config->block_length = SBC_BLOCK_LENGTH_8;
- } else if (sbc_caps->block_length & SBC_BLOCK_LENGTH_4) {
- sbc_config->block_length = SBC_BLOCK_LENGTH_4;
- } else {
- syslog(LOG_WARNING, "No supported block length.");
- return -ENOSYS;
- }
-
- sbc_config->min_bitpool =
- (sbc_caps->min_bitpool > MIN_BITPOOL ? sbc_caps->min_bitpool :
- MIN_BITPOOL);
- sbc_config->max_bitpool =
- (sbc_caps->max_bitpool < MAX_BITPOOL ? sbc_caps->max_bitpool :
- MAX_BITPOOL);
-
- return 0;
-}
-
-static void cras_a2dp_set_configuration(struct cras_bt_endpoint *endpoint,
- struct cras_bt_transport *transport)
-{
- struct cras_bt_device *device;
-
- device = cras_bt_transport_device(transport);
- cras_bt_device_a2dp_configured(device);
-}
-
-static void cras_a2dp_suspend(struct cras_bt_endpoint *endpoint,
- struct cras_bt_transport *transport)
-{
- struct cras_bt_device *device = cras_bt_transport_device(transport);
-
- BTLOG(btlog, BT_A2DP_SUSPENDED, 0, 0);
- cras_a2dp_suspend_connected_device(device);
- cras_bt_device_notify_profile_dropped(device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
-}
-
-static void a2dp_transport_state_changed(struct cras_bt_endpoint *endpoint,
- struct cras_bt_transport *transport)
-{
- if (connected_a2dp.iodev && transport) {
- /* When pending message is received in bluez, try to aquire
- * the transport. */
- if (cras_bt_transport_fd(transport) != -1 &&
- cras_bt_transport_state(transport) ==
- CRAS_BT_TRANSPORT_STATE_PENDING)
- cras_bt_transport_try_acquire(transport);
- }
-}
-
-static struct cras_bt_endpoint cras_a2dp_endpoint = {
- /* BlueZ connects the device A2DP Sink to our A2DP Source endpoint,
- * and the device A2DP Source to our A2DP Sink. It's best if you don't
- * think about it too hard.
- */
- .object_path = A2DP_SOURCE_ENDPOINT_PATH,
- .uuid = A2DP_SOURCE_UUID,
- .codec = A2DP_CODEC_SBC,
-
- .get_capabilities = cras_a2dp_get_capabilities,
- .select_configuration = cras_a2dp_select_configuration,
- .set_configuration = cras_a2dp_set_configuration,
- .suspend = cras_a2dp_suspend,
- .transport_state_changed = a2dp_transport_state_changed
-};
-
-int cras_a2dp_endpoint_create(DBusConnection *conn)
-{
- return cras_bt_endpoint_add(conn, &cras_a2dp_endpoint);
-}
-
-void cras_a2dp_start(struct cras_bt_device *device)
-{
- struct cras_bt_transport *transport = cras_a2dp_endpoint.transport;
-
- BTLOG(btlog, BT_A2DP_START, 0, 0);
-
- if (!transport || device != cras_bt_transport_device(transport)) {
- syslog(LOG_ERR, "Device and active transport not match.");
- return;
- }
-
- if (connected_a2dp.iodev) {
- syslog(LOG_WARNING,
- "Replacing existing endpoint configuration");
- a2dp_iodev_destroy(connected_a2dp.iodev);
- }
-
- connected_a2dp.iodev = a2dp_iodev_create(transport);
- connected_a2dp.device = cras_bt_transport_device(transport);
-
- if (!connected_a2dp.iodev)
- syslog(LOG_WARNING, "Failed to create a2dp iodev");
-}
-
-struct cras_bt_device *cras_a2dp_connected_device()
-{
- return connected_a2dp.device;
-}
-
-void cras_a2dp_suspend_connected_device(struct cras_bt_device *device)
-{
- if (connected_a2dp.device != device)
- return;
-
- if (connected_a2dp.iodev) {
- syslog(LOG_INFO, "Destroying iodev for A2DP device");
- a2dp_iodev_destroy(connected_a2dp.iodev);
- connected_a2dp.iodev = NULL;
- connected_a2dp.device = NULL;
- }
-}
diff --git a/cras/src/server/cras_a2dp_endpoint.h b/cras/src/server/cras_a2dp_endpoint.h
deleted file mode 100644
index 1ebd00d6..00000000
--- a/cras/src/server/cras_a2dp_endpoint.h
+++ /dev/null
@@ -1,26 +0,0 @@
-/* Copyright (c) 2013 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_A2DP_ENDPOINT_H_
-#define CRAS_A2DP_ENDPOINT_H_
-
-#include <dbus/dbus.h>
-
-struct cras_iodev;
-
-int cras_a2dp_endpoint_create(DBusConnection *conn);
-
-/* Gets the connected a2dp device, NULL is returned when there's none. */
-struct cras_bt_device *cras_a2dp_connected_device();
-
-/* Suspends the connected a2dp device, the purpose is to remove a2dp iodev
- * to release a2dp audio before sending dbus message to disconnect a2dp
- * device. */
-void cras_a2dp_suspend_connected_device(struct cras_bt_device *device);
-
-/* Starts A2DP output by creating the cras_iodev. */
-void cras_a2dp_start(struct cras_bt_device *device);
-
-#endif /* CRAS_A2DP_ENDPOINT_H_ */
diff --git a/cras/src/server/cras_a2dp_info.c b/cras/src/server/cras_a2dp_info.c
deleted file mode 100644
index b2db3848..00000000
--- a/cras/src/server/cras_a2dp_info.c
+++ /dev/null
@@ -1,187 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <netinet/in.h>
-#include <sbc/sbc.h>
-#include <syslog.h>
-
-#include "cras_a2dp_info.h"
-#include "cras_sbc_codec.h"
-#include "cras_types.h"
-#include "rtp.h"
-
-int init_a2dp(struct a2dp_info *a2dp, a2dp_sbc_t *sbc)
-{
- uint8_t frequency = 0, mode = 0, subbands = 0, allocation, blocks = 0,
- bitpool;
-
- if (sbc->frequency & SBC_SAMPLING_FREQ_48000)
- frequency = SBC_FREQ_48000;
- else if (sbc->frequency & SBC_SAMPLING_FREQ_44100)
- frequency = SBC_FREQ_44100;
- else if (sbc->frequency & SBC_SAMPLING_FREQ_32000)
- frequency = SBC_FREQ_32000;
- else if (sbc->frequency & SBC_SAMPLING_FREQ_16000)
- frequency = SBC_FREQ_16000;
-
- if (sbc->channel_mode & SBC_CHANNEL_MODE_JOINT_STEREO)
- mode = SBC_MODE_JOINT_STEREO;
- else if (sbc->channel_mode & SBC_CHANNEL_MODE_STEREO)
- mode = SBC_MODE_STEREO;
- else if (sbc->channel_mode & SBC_CHANNEL_MODE_DUAL_CHANNEL)
- mode = SBC_MODE_DUAL_CHANNEL;
- else if (sbc->channel_mode & SBC_CHANNEL_MODE_MONO)
- mode = SBC_MODE_MONO;
-
- if (sbc->allocation_method & SBC_ALLOCATION_LOUDNESS)
- allocation = SBC_AM_LOUDNESS;
- else
- allocation = SBC_AM_SNR;
-
- switch (sbc->subbands) {
- case SBC_SUBBANDS_4:
- subbands = SBC_SB_4;
- break;
- case SBC_SUBBANDS_8:
- subbands = SBC_SB_8;
- break;
- }
-
- switch (sbc->block_length) {
- case SBC_BLOCK_LENGTH_4:
- blocks = SBC_BLK_4;
- break;
- case SBC_BLOCK_LENGTH_8:
- blocks = SBC_BLK_8;
- break;
- case SBC_BLOCK_LENGTH_12:
- blocks = SBC_BLK_12;
- break;
- case SBC_BLOCK_LENGTH_16:
- blocks = SBC_BLK_16;
- break;
- }
-
- bitpool = sbc->max_bitpool;
-
- a2dp->codec = cras_sbc_codec_create(frequency, mode, subbands,
- allocation, blocks, bitpool);
- if (!a2dp->codec)
- return -1;
-
- /* SBC info */
- a2dp->codesize = cras_sbc_get_codesize(a2dp->codec);
- a2dp->frame_length = cras_sbc_get_frame_length(a2dp->codec);
-
- a2dp->a2dp_buf_used =
- sizeof(struct rtp_header) + sizeof(struct rtp_payload);
- a2dp->frame_count = 0;
- a2dp->seq_num = 0;
- a2dp->samples = 0;
-
- return 0;
-}
-
-void destroy_a2dp(struct a2dp_info *a2dp)
-{
- cras_sbc_codec_destroy(a2dp->codec);
-}
-
-int a2dp_codesize(struct a2dp_info *a2dp)
-{
- return a2dp->codesize;
-}
-
-int a2dp_block_size(struct a2dp_info *a2dp, int a2dp_bytes)
-{
- return a2dp_bytes / a2dp->frame_length * a2dp->codesize;
-}
-
-int a2dp_queued_frames(const struct a2dp_info *a2dp)
-{
- return a2dp->samples;
-}
-
-void a2dp_reset(struct a2dp_info *a2dp)
-{
- a2dp->a2dp_buf_used =
- sizeof(struct rtp_header) + sizeof(struct rtp_payload);
- a2dp->samples = 0;
- a2dp->seq_num = 0;
- a2dp->frame_count = 0;
-}
-
-static int avdtp_write(int stream_fd, struct a2dp_info *a2dp)
-{
- int err, samples;
- struct rtp_header *header;
- struct rtp_payload *payload;
-
- header = (struct rtp_header *)a2dp->a2dp_buf;
- payload = (struct rtp_payload *)(a2dp->a2dp_buf + sizeof(*header));
- memset(a2dp->a2dp_buf, 0, sizeof(*header) + sizeof(*payload));
-
- payload->frame_count = a2dp->frame_count;
- header->v = 2;
- header->pt = 1;
- header->sequence_number = htons(a2dp->seq_num);
- header->timestamp = htonl(a2dp->nsamples);
- header->ssrc = htonl(1);
-
- err = send(stream_fd, a2dp->a2dp_buf, a2dp->a2dp_buf_used,
- MSG_DONTWAIT);
- if (err < 0)
- return -errno;
-
- /* Returns the number of samples in frame. */
- samples = a2dp->samples;
-
- /* Reset some data */
- a2dp->a2dp_buf_used = sizeof(*header) + sizeof(*payload);
- a2dp->frame_count = 0;
- a2dp->samples = 0;
- a2dp->seq_num++;
-
- return samples;
-}
-
-int a2dp_encode(struct a2dp_info *a2dp, const void *pcm_buf, int pcm_buf_size,
- int format_bytes, size_t link_mtu)
-{
- int processed;
- size_t out_encoded;
-
- if (link_mtu > A2DP_BUF_SIZE_BYTES)
- link_mtu = A2DP_BUF_SIZE_BYTES;
- if (link_mtu == a2dp->a2dp_buf_used)
- return 0;
-
- processed = a2dp->codec->encode(a2dp->codec, pcm_buf, pcm_buf_size,
- a2dp->a2dp_buf + a2dp->a2dp_buf_used,
- link_mtu - a2dp->a2dp_buf_used,
- &out_encoded);
- if (processed < 0) {
- syslog(LOG_ERR, "a2dp encode error %d", processed);
- return processed;
- }
-
- if (a2dp->codesize > 0)
- a2dp->frame_count += processed / a2dp->codesize;
- a2dp->a2dp_buf_used += out_encoded;
-
- a2dp->samples += processed / format_bytes;
- a2dp->nsamples += processed / format_bytes;
-
- return processed;
-}
-
-int a2dp_write(struct a2dp_info *a2dp, int stream_fd, size_t link_mtu)
-{
- /* Do avdtp write when the max number of SBC frames is reached. */
- if (a2dp->a2dp_buf_used + a2dp->frame_length > link_mtu)
- return avdtp_write(stream_fd, a2dp);
-
- return 0;
-}
diff --git a/cras/src/server/cras_a2dp_info.h b/cras/src/server/cras_a2dp_info.h
deleted file mode 100644
index b33911e8..00000000
--- a/cras/src/server/cras_a2dp_info.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_A2DP_INFO_H_
-#define CRAS_A2DP_INFO_H_
-
-#include "a2dp-codecs.h"
-
-#define A2DP_BUF_SIZE_BYTES 2048
-
-/* Represents the codec and encoded state of a2dp iodev.
- * Members:
- * codec - The codec used to encode PCM buffer to a2dp buffer.
- * a2dp_buf - The buffer to hold encoded frames.
- * codesize - Size of a SBC frame in bytes.
- * frame_length - Size of an encoded SBC frame in bytes.
- * frame_count - Queued SBC frame count currently in a2dp buffer.
- * seq_num - Sequence number in rtp header.
- * samples - Queued PCM frame count currently in a2dp buffer.
- * nsamples - Cumulative number of encoded PCM frames.
- * a2dp_buf_used - Used a2dp buffer counter in bytes.
- */
-struct a2dp_info {
- struct cras_audio_codec *codec;
- uint8_t a2dp_buf[A2DP_BUF_SIZE_BYTES];
- int codesize;
- int frame_length;
- int frame_count;
- uint16_t seq_num;
- int samples;
- int nsamples;
- size_t a2dp_buf_used;
-};
-
-/*
- * Set up codec for given sbc capability.
- */
-int init_a2dp(struct a2dp_info *a2dp, a2dp_sbc_t *sbc);
-
-/*
- * Destroys an a2dp_info.
- */
-void destroy_a2dp(struct a2dp_info *a2dp);
-
-/*
- * Gets the codesize of the SBC codec.
- */
-int a2dp_codesize(struct a2dp_info *a2dp);
-
-/*
- * Gets original size of a2dp encoded bytes.
- */
-int a2dp_block_size(struct a2dp_info *a2dp, int encoded_bytes);
-
-/*
- * Gets the number of queued frames in a2dp_info.
- */
-int a2dp_queued_frames(const struct a2dp_info *a2dp);
-
-/*
- * Empty all queued samples in a2dp_info.
- */
-void a2dp_reset(struct a2dp_info *a2dp);
-
-/*
- * Encodes samples using the codec for this a2dp instance, returns the number of
- * pcm bytes processed.
- * Args:
- * a2dp: The a2dp info object.
- * pcm_buf: The buffer of pcm samples.
- * pcm_buf_size: Size of the pcm buffer.
- * format_bytes: Number of bytes per sample.
- * link_mtu: The maximum transmit unit.
- */
-int a2dp_encode(struct a2dp_info *a2dp, const void *pcm_buf, int pcm_buf_size,
- int format_bytes, size_t link_mtu);
-
-/*
- * Writes samples using a2dp, returns number of frames written.
- * Args:
- * a2dp: The a2dp info object.
- * stream_fd: The file descriptor to send stream to.
- * link_mtu: The maximum transmit unit.
- */
-int a2dp_write(struct a2dp_info *a2dp, int stream_fd, size_t link_mtu);
-
-#endif /* CRAS_A2DP_INFO_H_ */
diff --git a/cras/src/server/cras_a2dp_iodev.c b/cras/src/server/cras_a2dp_iodev.c
deleted file mode 100644
index b8a606e4..00000000
--- a/cras/src/server/cras_a2dp_iodev.c
+++ /dev/null
@@ -1,709 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-#include <sys/ioctl.h>
-#include <sys/param.h>
-#include <linux/sockios.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <syslog.h>
-#include <time.h>
-
-#include "audio_thread.h"
-#include "audio_thread_log.h"
-#include "byte_buffer.h"
-#include "cras_iodev_list.h"
-#include "cras_a2dp_endpoint.h"
-#include "cras_a2dp_info.h"
-#include "cras_a2dp_iodev.h"
-#include "cras_audio_area.h"
-#include "cras_audio_thread_monitor.h"
-#include "cras_bt_device.h"
-#include "cras_iodev.h"
-#include "cras_util.h"
-#include "rtp.h"
-#include "utlist.h"
-
-#define PCM_BUF_MAX_SIZE_FRAMES (4096 * 4)
-#define PCM_BUF_MAX_SIZE_BYTES (PCM_BUF_MAX_SIZE_FRAMES * 4)
-
-/* Threshold for reasonable a2dp throttle log in audio dump. */
-static const struct timespec throttle_log_threshold = {
- 0, 20000000 /* 20ms */
-};
-
-/* Threshold for severe a2dp throttle event. */
-static const struct timespec throttle_event_threshold = {
- 2, 0 /* 2s */
-};
-
-/* Child of cras_iodev to handle bluetooth A2DP streaming.
- * Members:
- * base - The cras_iodev structure "base class"
- * a2dp - The codec and encoded state of a2dp_io.
- * transport - The transport object for bluez media API.
- * sock_depth_frames - Socket depth in frames of the a2dp socket.
- * pcm_buf - Buffer to hold pcm samples before encode.
- * destroyed - Flag to note if this a2dp_io is about to destroy.
- * next_flush_time - The time when it is okay for next flush call.
- * flush_period - The time period between two a2dp packet writes.
- * write_block - How many frames of audio samples are transferred in one
- * a2dp packet write.
- */
-struct a2dp_io {
- struct cras_iodev base;
- struct a2dp_info a2dp;
- struct cras_bt_transport *transport;
- unsigned sock_depth_frames;
- struct byte_buffer *pcm_buf;
- int destroyed;
- struct timespec next_flush_time;
- struct timespec flush_period;
- unsigned int write_block;
-};
-
-static int encode_and_flush(const struct cras_iodev *iodev);
-
-static int update_supported_formats(struct cras_iodev *iodev)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- size_t rate = 0;
- size_t channel;
- a2dp_sbc_t a2dp;
-
- cras_bt_transport_configuration(a2dpio->transport, &a2dp, sizeof(a2dp));
-
- channel = (a2dp.channel_mode == SBC_CHANNEL_MODE_MONO) ? 1 : 2;
-
- if (a2dp.frequency & SBC_SAMPLING_FREQ_48000)
- rate = 48000;
- else if (a2dp.frequency & SBC_SAMPLING_FREQ_44100)
- rate = 44100;
- else if (a2dp.frequency & SBC_SAMPLING_FREQ_32000)
- rate = 32000;
- else if (a2dp.frequency & SBC_SAMPLING_FREQ_16000)
- rate = 16000;
-
- free(iodev->supported_rates);
- iodev->supported_rates = (size_t *)malloc(2 * sizeof(rate));
- iodev->supported_rates[0] = rate;
- iodev->supported_rates[1] = 0;
-
- free(iodev->supported_channel_counts);
- iodev->supported_channel_counts = (size_t *)malloc(2 * sizeof(channel));
- iodev->supported_channel_counts[0] = channel;
- iodev->supported_channel_counts[1] = 0;
-
- free(iodev->supported_formats);
- iodev->supported_formats =
- (snd_pcm_format_t *)malloc(2 * sizeof(snd_pcm_format_t));
- iodev->supported_formats[0] = SND_PCM_FORMAT_S16_LE;
- iodev->supported_formats[1] = (snd_pcm_format_t)0;
-
- return 0;
-}
-
-static unsigned int bt_local_queued_frames(const struct cras_iodev *iodev)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- return a2dp_queued_frames(&a2dpio->a2dp) +
- buf_queued(a2dpio->pcm_buf) /
- cras_get_format_bytes(iodev->format);
-}
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- int local_queued_frames = bt_local_queued_frames(iodev);
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return MIN(iodev->buffer_size, local_queued_frames);
-}
-
-/*
- * Utility function to fill zero frames until buffer level reaches
- * target_level. This is useful to allocate just enough data to write
- * to controller, while not introducing extra latency.
- */
-static int fill_zeros_to_target_level(struct cras_iodev *iodev,
- unsigned int target_level)
-{
- unsigned int local_queued_frames = bt_local_queued_frames(iodev);
-
- if (local_queued_frames < target_level)
- return cras_iodev_fill_odev_zeros(
- iodev, target_level - local_queued_frames);
- return 0;
-}
-
-/*
- * dev_io_playback_write() has the logic to detect underrun scenario
- * and calls into this underrun ops, by comparing buffer level with
- * number of frames just written. Note that it's not correct 100% of
- * the time in a2dp case, because we lose track of samples once they're
- * flushed to socket.
- */
-static int output_underrun(struct cras_iodev *iodev)
-{
- unsigned int local_queued_frames = bt_local_queued_frames(iodev);
-
- /*
- * Examples to help understand the check:
- *
- * [False-positive underrun]
- * Assume min_buffer_level = 1000, written 900, and flushes
- * 800 of data. Audio thread sees 1000 + 900 - 800 = 1100 of
- * data left. This is merely 100(< 900) above min_buffer_level
- * so audio_thread thinks it underruns, but actually not.
- *
- * [True underrun]
- * min_buffer_level = 1000, written 200, and flushes 800 of
- * data. Now that buffer runs lower than min_buffer_level so
- * it's indeed an underrun.
- */
- if (local_queued_frames > iodev->min_buffer_level)
- return 0;
-
- return cras_iodev_fill_odev_zeros(iodev, iodev->min_cb_level);
-}
-
-/*
- * This will be called multiple times when a2dpio is in no_stream state
- * frames_to_play_in_sleep ops determins how regular this will be called.
- */
-static int enter_no_stream(struct a2dp_io *a2dpio)
-{
- struct cras_iodev *odev = &a2dpio->base;
- int rc;
- /*
- * Setting target level to 3 times of min_buffer_level.
- * We want hw_level to stay bewteen 1-2 times of min_buffer_level on
- * top of the underrun threshold(i.e one min_cb_level).
- */
- rc = fill_zeros_to_target_level(odev, 3 * odev->min_buffer_level);
- if (rc)
- syslog(LOG_ERR, "Error in A2DP enter_no_stream");
- return encode_and_flush(odev);
-}
-
-/*
- * This is called when stream data is available to write. Prepare audio
- * data to one min_buffer_level. Don't flush it now because stream data is
- * coming right up which will trigger next flush at appropriate time.
- */
-static int leave_no_stream(struct a2dp_io *a2dpio)
-{
- struct cras_iodev *odev = &a2dpio->base;
-
- /*
- * Since stream data is ready, just make sure hw_level doesn't underrun
- * after one flush. Hence setting the target level to 2 times of
- * min_buffer_level.
- */
- return fill_zeros_to_target_level(odev, 2 * odev->min_buffer_level);
-}
-
-/*
- * Makes sure there's enough data(zero frames) to flush when no stream presents.
- * Note that the underrun condition is when real buffer level goes below
- * min_buffer_level, so we want to keep data at a reasonable higher level on top
- * of that.
- */
-static int no_stream(struct cras_iodev *odev, int enable)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)odev;
-
- if (enable)
- return enter_no_stream(a2dpio);
- else
- return leave_no_stream(a2dpio);
-}
-
-/* Encode as much PCM data as we can until the buffer level of a2dp_info
- * reaches MTU.
- * Returns:
- * 0 for success, otherwise negative error code.
- */
-static int encode_a2dp_packet(struct a2dp_io *a2dpio)
-{
- int processed;
- size_t format_bytes = cras_get_format_bytes(a2dpio->base.format);
-
- while (buf_queued(a2dpio->pcm_buf)) {
- processed = a2dp_encode(
- &a2dpio->a2dp, buf_read_pointer(a2dpio->pcm_buf),
- buf_readable(a2dpio->pcm_buf), format_bytes,
- cras_bt_transport_write_mtu(a2dpio->transport));
- if (processed == -ENOSPC || processed == 0)
- break;
- if (processed < 0)
- return processed;
-
- buf_increment_read(a2dpio->pcm_buf, processed);
- }
- return 0;
-}
-
-/*
- * To be called when a2dp socket becomes writable.
- */
-static int a2dp_socket_write_cb(void *arg, int revent)
-{
- struct cras_iodev *iodev = (struct cras_iodev *)arg;
- return encode_and_flush(iodev);
-}
-
-static int configure_dev(struct cras_iodev *iodev)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- int sock_depth;
- int err;
- socklen_t optlen;
- int a2dp_payload_length;
-
- err = cras_bt_transport_acquire(a2dpio->transport);
- if (err < 0) {
- syslog(LOG_ERR, "transport_acquire failed");
- return err;
- }
-
- /* Apply the node's volume after transport is acquired. Doing this
- * is necessary because the volume can not sync to hardware until
- * it is opened. */
- iodev->set_volume(iodev);
-
- /* Assert format is set before opening device. */
- if (iodev->format == NULL)
- return -EINVAL;
- iodev->format->format = SND_PCM_FORMAT_S16_LE;
- cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
-
- a2dpio->pcm_buf = byte_buffer_create(PCM_BUF_MAX_SIZE_BYTES);
- if (!a2dpio->pcm_buf)
- return -ENOMEM;
-
- /* Set up the socket to hold two MTUs full of data before returning
- * EAGAIN. This will allow the write to be throttled when a reasonable
- * amount of data is queued. */
- sock_depth = 2 * cras_bt_transport_write_mtu(a2dpio->transport);
- setsockopt(cras_bt_transport_fd(a2dpio->transport), SOL_SOCKET,
- SO_SNDBUF, &sock_depth, sizeof(sock_depth));
- optlen = sizeof(sock_depth);
- getsockopt(cras_bt_transport_fd(a2dpio->transport), SOL_SOCKET,
- SO_SNDBUF, &sock_depth, &optlen);
- a2dpio->sock_depth_frames = a2dp_block_size(&a2dpio->a2dp, sock_depth) /
- cras_get_format_bytes(iodev->format);
- /*
- * Per avdtp_write, subtract the room for packet header first.
- * Calculate how many frames are encapsulated in one a2dp packet, and
- * the corresponding time period between two packets.
- */
- a2dp_payload_length = cras_bt_transport_write_mtu(a2dpio->transport) -
- sizeof(struct rtp_header) -
- sizeof(struct rtp_payload);
- a2dpio->write_block =
- a2dp_block_size(&a2dpio->a2dp, a2dp_payload_length) /
- cras_get_format_bytes(iodev->format);
- cras_frames_to_time(a2dpio->write_block, iodev->format->frame_rate,
- &a2dpio->flush_period);
-
- /* PCM buffer size plus one encoded a2dp packet. */
- iodev->buffer_size = PCM_BUF_MAX_SIZE_FRAMES + a2dpio->write_block;
-
- /*
- * Buffer level less than one write_block can't be send over a2dp
- * packet. Configure min_buffer_level to this value so when stream
- * underruns, audio thread can take action to fill some zeros.
- */
- iodev->min_buffer_level = a2dpio->write_block;
-
- audio_thread_add_events_callback(
- cras_bt_transport_fd(a2dpio->transport), a2dp_socket_write_cb,
- iodev, POLLOUT | POLLERR | POLLHUP);
- audio_thread_config_events_callback(
- cras_bt_transport_fd(a2dpio->transport), TRIGGER_NONE);
- return 0;
-}
-
-static int start(const struct cras_iodev *iodev)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
-
- /*
- * This is called when iodev in open state, at the moment when
- * output sample is ready. Initialize the next_flush_time for
- * following flush calls.
- */
- clock_gettime(CLOCK_MONOTONIC_RAW, &a2dpio->next_flush_time);
-
- return 0;
-}
-
-static int close_dev(struct cras_iodev *iodev)
-{
- int err;
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- struct cras_bt_device *device;
-
- if (!a2dpio->transport)
- return 0;
-
- /* Remove audio thread callback and sync before releasing
- * the transport. */
- audio_thread_rm_callback_sync(cras_iodev_list_get_audio_thread(),
- cras_bt_transport_fd(a2dpio->transport));
-
- err = cras_bt_transport_release(a2dpio->transport, !a2dpio->destroyed);
- if (err < 0)
- syslog(LOG_ERR, "transport_release failed");
-
- device = cras_bt_transport_device(a2dpio->transport);
- if (device)
- cras_bt_device_cancel_suspend(device);
- a2dp_reset(&a2dpio->a2dp);
- byte_buffer_destroy(&a2dpio->pcm_buf);
- cras_iodev_free_format(iodev);
- cras_iodev_free_audio_area(iodev);
- return 0;
-}
-
-static unsigned int frames_to_play_in_sleep(struct cras_iodev *iodev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- int frames_until;
-
- *hw_level = frames_queued(iodev, hw_tstamp);
- if (*hw_level < a2dpio->write_block)
- *hw_level = 0;
- else
- *hw_level -= a2dpio->write_block;
-
- frames_until = cras_frames_until_time(&a2dpio->next_flush_time,
- iodev->format->frame_rate);
- if (frames_until > 0)
- return frames_until;
-
- /* If time has passed next_flush_time, for example when socket write
- * throttles, sleep a moderate of time so that audio thread doesn't
- * busy wake up. */
- return a2dpio->write_block;
-}
-
-/* Encodes PCM data to a2dp frames and try to flush it to the socket.
- * Returns:
- * 0 when the flush succeeded, -1 when error occurred.
- */
-static int encode_and_flush(const struct cras_iodev *iodev)
-{
- int err;
- size_t format_bytes;
- int written = 0;
- unsigned int queued_frames;
- struct a2dp_io *a2dpio;
- struct cras_bt_device *device;
- struct timespec now, ts;
- static const struct timespec flush_wake_fuzz_ts = {
- 0, 1000000 /* 1ms */
- };
-
- a2dpio = (struct a2dp_io *)iodev;
- format_bytes = cras_get_format_bytes(iodev->format);
- device = cras_bt_transport_device(a2dpio->transport);
-
- /* If bt device has been destroyed, this a2dp iodev will soon be
- * destroyed as well. */
- if (device == NULL)
- return -EINVAL;
-
- ATLOG(atlog, AUDIO_THREAD_A2DP_FLUSH, iodev->state,
- a2dpio->next_flush_time.tv_sec, a2dpio->next_flush_time.tv_nsec);
-
- /* Only allow data to be flushed after start() ops is called. */
- if ((iodev->state != CRAS_IODEV_STATE_NORMAL_RUN) &&
- (iodev->state != CRAS_IODEV_STATE_NO_STREAM_RUN))
- return 0;
-
- err = encode_a2dp_packet(a2dpio);
- if (err < 0)
- return err;
-
-do_flush:
- /* If flush gets called before targeted next flush time, do nothing. */
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- add_timespecs(&now, &flush_wake_fuzz_ts);
- if (!timespec_after(&now, &a2dpio->next_flush_time)) {
- if (iodev->buffer_size == bt_local_queued_frames(iodev)) {
- /*
- * If buffer is full, audio thread will no longer call
- * into get/put buffer in subsequent wake-ups. In that
- * case set the registered callback to be triggered at
- * next audio thread wake up.
- */
- audio_thread_config_events_callback(
- cras_bt_transport_fd(a2dpio->transport),
- TRIGGER_WAKEUP);
- cras_audio_thread_event_a2dp_overrun();
- syslog(LOG_WARNING, "Buffer overrun in A2DP iodev");
- }
- return 0;
- }
-
- /* If the A2DP write schedule miss exceeds a small threshold, log it for
- * debug purpose. */
- subtract_timespecs(&now, &a2dpio->next_flush_time, &ts);
- if (timespec_after(&ts, &throttle_log_threshold))
- ATLOG(atlog, AUDIO_THREAD_A2DP_THROTTLE_TIME, ts.tv_sec,
- ts.tv_nsec, bt_local_queued_frames(iodev));
-
- /* Log an event if the A2DP write schedule miss exceeds a large threshold
- * that we consider it as something severe. */
- if (timespec_after(&ts, &throttle_event_threshold))
- cras_audio_thread_event_a2dp_throttle();
-
- written = a2dp_write(&a2dpio->a2dp,
- cras_bt_transport_fd(a2dpio->transport),
- cras_bt_transport_write_mtu(a2dpio->transport));
- ATLOG(atlog, AUDIO_THREAD_A2DP_WRITE, written,
- a2dp_queued_frames(&a2dpio->a2dp), 0);
- if (written == -EAGAIN) {
- /* If EAGAIN error lasts longer than 5 seconds, suspend the
- * a2dp connection. */
- cras_bt_device_schedule_suspend(device, 5000,
- A2DP_LONG_TX_FAILURE);
- audio_thread_config_events_callback(
- cras_bt_transport_fd(a2dpio->transport), TRIGGER_POLL);
- return 0;
- } else if (written < 0) {
- /* Suspend a2dp immediately when receives error other than
- * EAGAIN. */
- cras_bt_device_cancel_suspend(device);
- cras_bt_device_schedule_suspend(device, 0, A2DP_TX_FATAL_ERROR);
- /* Stop polling the socket in audio thread. Main thread will
- * close this iodev soon. */
- audio_thread_config_events_callback(
- cras_bt_transport_fd(a2dpio->transport), TRIGGER_NONE);
- return written;
- }
-
- /* Update the next flush time if one block successfully been written. */
- if (written)
- add_timespecs(&a2dpio->next_flush_time, &a2dpio->flush_period);
-
- /* a2dp_write no longer return -EAGAIN when reaches here, disable
- * the polling write callback. */
- audio_thread_config_events_callback(
- cras_bt_transport_fd(a2dpio->transport), TRIGGER_NONE);
-
- /* Data succcessfully written to a2dp socket, cancel any scheduled
- * suspend timer. */
- cras_bt_device_cancel_suspend(device);
-
- /* If it looks okay to write more and we do have queued data, try
- * encode more. But avoid the case when PCM buffer level is too close
- * to min_buffer_level so that another A2DP write could causes underrun.
- */
- queued_frames = buf_queued(a2dpio->pcm_buf) / format_bytes;
- if (written &&
- (iodev->min_buffer_level + a2dpio->write_block < queued_frames)) {
- err = encode_a2dp_packet(a2dpio);
- if (err < 0)
- return err;
- goto do_flush;
- }
-
- return 0;
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- const struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- struct timespec tstamp;
-
- /* The number of frames in the pcm buffer plus two mtu packets */
- return frames_queued(iodev, &tstamp) + a2dpio->sock_depth_frames;
-}
-
-static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
- unsigned *frames)
-{
- size_t format_bytes;
- struct a2dp_io *a2dpio;
-
- a2dpio = (struct a2dp_io *)iodev;
-
- format_bytes = cras_get_format_bytes(iodev->format);
-
- if (iodev->direction != CRAS_STREAM_OUTPUT)
- return 0;
-
- *frames = MIN(*frames, buf_writable(a2dpio->pcm_buf) / format_bytes);
- iodev->area->frames = *frames;
- cras_audio_area_config_buf_pointers(iodev->area, iodev->format,
- buf_write_pointer(a2dpio->pcm_buf));
- *area = iodev->area;
- return 0;
-}
-
-static int put_buffer(struct cras_iodev *iodev, unsigned nwritten)
-{
- size_t written_bytes;
- size_t format_bytes;
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
-
- format_bytes = cras_get_format_bytes(iodev->format);
- written_bytes = nwritten * format_bytes;
-
- if (written_bytes > buf_writable(a2dpio->pcm_buf))
- return -EINVAL;
-
- buf_increment_write(a2dpio->pcm_buf, written_bytes);
-
- return encode_and_flush(iodev);
-}
-
-static int flush_buffer(struct cras_iodev *iodev)
-{
- return 0;
-}
-
-static void set_volume(struct cras_iodev *iodev)
-{
- size_t volume;
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- struct cras_bt_device *device =
- cras_bt_transport_device(a2dpio->transport);
-
- if (!cras_bt_device_get_use_hardware_volume(device))
- return;
-
- volume = iodev->active_node->volume * 127 / 100;
-
- if (a2dpio->transport)
- cras_bt_transport_set_volume(a2dpio->transport, volume);
-}
-
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
-}
-
-void free_resources(struct a2dp_io *a2dpio)
-{
- struct cras_ionode *node;
-
- node = a2dpio->base.active_node;
- if (node) {
- cras_iodev_rm_node(&a2dpio->base, node);
- free(node);
- }
- free(a2dpio->base.supported_channel_counts);
- free(a2dpio->base.supported_rates);
- free(a2dpio->base.supported_formats);
- destroy_a2dp(&a2dpio->a2dp);
-}
-
-struct cras_iodev *a2dp_iodev_create(struct cras_bt_transport *transport)
-{
- int err;
- struct a2dp_io *a2dpio;
- struct cras_iodev *iodev;
- struct cras_ionode *node;
- a2dp_sbc_t a2dp;
- struct cras_bt_device *device;
- const char *name;
-
- a2dpio = (struct a2dp_io *)calloc(1, sizeof(*a2dpio));
- if (!a2dpio)
- goto error;
-
- a2dpio->transport = transport;
- cras_bt_transport_configuration(a2dpio->transport, &a2dp, sizeof(a2dp));
- err = init_a2dp(&a2dpio->a2dp, &a2dp);
- if (err) {
- syslog(LOG_ERR, "Fail to init a2dp");
- goto error;
- }
-
- iodev = &a2dpio->base;
-
- /* A2DP only does output now */
- iodev->direction = CRAS_STREAM_OUTPUT;
-
- /* Set iodev's name by bluetooth device's readable name, if
- * the readable name is not available, use address instead.
- */
- device = cras_bt_transport_device(transport);
- name = cras_bt_device_name(device);
- if (!name)
- name = cras_bt_transport_object_path(a2dpio->transport);
-
- snprintf(iodev->info.name, sizeof(iodev->info.name), "%s", name);
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = '\0';
- iodev->info.stable_id = cras_bt_device_get_stable_id(device);
-
- iodev->configure_dev = configure_dev;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->flush_buffer = flush_buffer;
- iodev->no_stream = no_stream;
- iodev->output_underrun = output_underrun;
- iodev->close_dev = close_dev;
- iodev->update_supported_formats = update_supported_formats;
- iodev->update_active_node = update_active_node;
- iodev->set_volume = set_volume;
- iodev->start = start;
- iodev->frames_to_play_in_sleep = frames_to_play_in_sleep;
-
- /* Create an empty ionode */
- node = (struct cras_ionode *)calloc(1, sizeof(*node));
- node->dev = iodev;
- strcpy(node->name, iodev->info.name);
- node->plugged = 1;
- node->type = CRAS_NODE_TYPE_BLUETOOTH;
- node->volume = 100;
- gettimeofday(&node->plugged_time, NULL);
-
- /* Prepare active node before append, so bt_io can extract correct
- * info from A2DP iodev and node. */
- cras_iodev_add_node(iodev, node);
- cras_iodev_set_active_node(iodev, node);
- cras_bt_device_append_iodev(
- device, iodev, cras_bt_transport_profile(a2dpio->transport));
-
- /* Record max supported channels into cras_iodev_info. */
- iodev->info.max_supported_channels =
- (a2dp.channel_mode == SBC_CHANNEL_MODE_MONO) ? 1 : 2;
-
- ewma_power_disable(&iodev->ewma);
-
- return iodev;
-error:
- if (a2dpio) {
- free_resources(a2dpio);
- free(a2dpio);
- }
- return NULL;
-}
-
-void a2dp_iodev_destroy(struct cras_iodev *iodev)
-{
- struct a2dp_io *a2dpio = (struct a2dp_io *)iodev;
- struct cras_bt_device *device;
-
- a2dpio->destroyed = 1;
- device = cras_bt_transport_device(a2dpio->transport);
-
- /* A2DP does output only */
- cras_bt_device_rm_iodev(device, iodev);
-
- /* Free resources when device successfully removed. */
- free_resources(a2dpio);
- cras_iodev_free_resources(iodev);
- free(a2dpio);
-}
diff --git a/cras/src/server/cras_a2dp_iodev.h b/cras/src/server/cras_a2dp_iodev.h
deleted file mode 100644
index d4e489da..00000000
--- a/cras/src/server/cras_a2dp_iodev.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_A2DP_IODEV_H_
-#define CRAS_A2DP_IODEV_H_
-
-#include "cras_bt_transport.h"
-
-struct cras_iodev;
-
-/*
- * Creates an a2dp iodev from transport object.
- * Args:
- * transport - The transport to create a2dp iodev for
- */
-struct cras_iodev *a2dp_iodev_create(struct cras_bt_transport *transport);
-
-/*
- * Destroys a2dp iodev.
- */
-void a2dp_iodev_destroy(struct cras_iodev *iodev);
-
-#endif /* CRS_A2DP_IODEV_H_ */
diff --git a/cras/src/server/cras_alert.c b/cras/src/server/cras_alert.c
deleted file mode 100644
index 9950ec11..00000000
--- a/cras/src/server/cras_alert.c
+++ /dev/null
@@ -1,184 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "cras_alert.h"
-#include "utlist.h"
-
-/* A list of callbacks for an alert */
-struct cras_alert_cb_list {
- cras_alert_cb callback;
- void *arg;
- struct cras_alert_cb_list *prev, *next;
-};
-
-/* A list of data args to callbacks. Variable-length structure. */
-struct cras_alert_data {
- struct cras_alert_data *prev, *next;
- /* This field must be the last in this structure. */
- char buf[];
-};
-
-struct cras_alert {
- int pending;
- unsigned int flags;
- cras_alert_prepare prepare;
- struct cras_alert_cb_list *callbacks;
- struct cras_alert_data *data;
- struct cras_alert *prev, *next;
-};
-
-/* A list of all alerts in the system */
-static struct cras_alert *all_alerts;
-/* If there is any alert pending. */
-static int has_alert_pending;
-
-struct cras_alert *cras_alert_create(cras_alert_prepare prepare,
- unsigned int flags)
-{
- struct cras_alert *alert;
- alert = calloc(1, sizeof(*alert));
- if (!alert)
- return NULL;
- alert->prepare = prepare;
- alert->flags = flags;
- DL_APPEND(all_alerts, alert);
- return alert;
-}
-
-int cras_alert_add_callback(struct cras_alert *alert, cras_alert_cb cb,
- void *arg)
-{
- struct cras_alert_cb_list *alert_cb;
-
- if (cb == NULL)
- return -EINVAL;
-
- DL_FOREACH (alert->callbacks, alert_cb)
- if (alert_cb->callback == cb && alert_cb->arg == arg)
- return -EEXIST;
-
- alert_cb = calloc(1, sizeof(*alert_cb));
- if (alert_cb == NULL)
- return -ENOMEM;
- alert_cb->callback = cb;
- alert_cb->arg = arg;
- DL_APPEND(alert->callbacks, alert_cb);
- return 0;
-}
-
-int cras_alert_rm_callback(struct cras_alert *alert, cras_alert_cb cb,
- void *arg)
-{
- struct cras_alert_cb_list *alert_cb;
-
- DL_FOREACH (alert->callbacks, alert_cb)
- if (alert_cb->callback == cb && alert_cb->arg == arg) {
- DL_DELETE(alert->callbacks, alert_cb);
- free(alert_cb);
- return 0;
- }
- return -ENOENT;
-}
-
-/* Checks if the alert is pending, and invoke the prepare function and callbacks
- * if so. */
-static void cras_alert_process(struct cras_alert *alert)
-{
- struct cras_alert_cb_list *cb;
- struct cras_alert_data *data;
-
- if (!alert->pending)
- return;
-
- alert->pending = 0;
- if (alert->prepare)
- alert->prepare(alert);
-
- if (!alert->data) {
- DL_FOREACH (alert->callbacks, cb)
- cb->callback(cb->arg, NULL);
- }
-
- /* Have data arguments, pass each to the callbacks. */
- DL_FOREACH (alert->data, data) {
- DL_FOREACH (alert->callbacks, cb)
- cb->callback(cb->arg, (void *)data->buf);
- DL_DELETE(alert->data, data);
- free(data);
- }
-}
-
-void cras_alert_pending(struct cras_alert *alert)
-{
- alert->pending = 1;
- has_alert_pending = 1;
-}
-
-void cras_alert_pending_data(struct cras_alert *alert, void *data,
- size_t data_size)
-{
- struct cras_alert_data *d;
-
- alert->pending = 1;
- has_alert_pending = 1;
- d = calloc(1, offsetof(struct cras_alert_data, buf) + data_size);
- memcpy(d->buf, data, data_size);
-
- if (!(alert->flags & CRAS_ALERT_FLAG_KEEP_ALL_DATA) && alert->data) {
- /* There will never be more than one item in the list. */
- free(alert->data);
- alert->data = NULL;
- }
-
- /* Even when there is only one item, it is important to use DL_APPEND
- * here so that d's next and prev pointers are setup correctly. */
- DL_APPEND(alert->data, d);
-}
-
-void cras_alert_process_all_pending_alerts()
-{
- struct cras_alert *alert;
-
- while (has_alert_pending) {
- has_alert_pending = 0;
- DL_FOREACH (all_alerts, alert)
- cras_alert_process(alert);
- }
-}
-
-void cras_alert_destroy(struct cras_alert *alert)
-{
- struct cras_alert_cb_list *cb;
- struct cras_alert_data *data;
-
- if (!alert)
- return;
-
- DL_FOREACH (alert->callbacks, cb) {
- DL_DELETE(alert->callbacks, cb);
- free(cb);
- }
-
- DL_FOREACH (alert->data, data) {
- DL_DELETE(alert->data, data);
- free(data);
- }
-
- alert->callbacks = NULL;
- DL_DELETE(all_alerts, alert);
- free(alert);
-}
-
-void cras_alert_destroy_all()
-{
- struct cras_alert *alert;
- DL_FOREACH (all_alerts, alert)
- cras_alert_destroy(alert);
-}
diff --git a/cras/src/server/cras_alert.h b/cras/src/server/cras_alert.h
deleted file mode 100644
index 7149a0b1..00000000
--- a/cras/src/server/cras_alert.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_ALERT_H
-#define _CRAS_ALERT_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* The alert facility provides a way to signal the clients when a system state
- * changes.
- *
- * First the clients registers callbacks to an alert. Each time the system state
- * changes, we mark the associated alert as "pending". At the end of the event
- * loop, we invoke the callbacks for the pending alerts.
- *
- * We do this delayed callback to collapses multiple callbacks into one (for
- * example, if there are multiple nodes added at the same time, we will only
- * fire the "nodes changed" signal once).
- *
- * There is an optional "prepare" function which can be provided when creating
- * an alert. It is called before we invoke the callbacks. This gives the owner
- * of each alert a chance to update the system to a consistent state before
- * signalling the clients.
- *
- * The alert functions should only be used from the main thread.
- */
-
-struct cras_alert;
-
-/* Callback functions to be notified when settings change. arg is a user
- * provided argument that will be passed back, data is extra info about the
- * signal if available.
- */
-typedef void (*cras_alert_cb)(void *arg, void *data);
-typedef void (*cras_alert_prepare)(struct cras_alert *alert);
-
-/* Flags for alerts. */
-enum CRAS_ALERT_FLAGS {
- /* By default, alerts will only keep the last copy of the data
- * specified in cras_alert_pending_data as an optimization - then
- * the callback is executed once with the latest value, rather than
- * for every value. In some cases, it is important to send the data
- * with every change. Use this flag to enable that behavior. */
- CRAS_ALERT_FLAG_KEEP_ALL_DATA = 1 << 0,
-};
-
-/* Creates an alert.
- * Args:
- * prepare - A function which will be called before calling the callbacks.
- * The prepare function should update the system state in the shared
- * memory to be consistent. It can be NULL if not needed.
- * flags - 0 for defauts, or ORed values from enum CRAS_ALERT_FLAGS.
- * Returns:
- * A pointer to the alert, NULL if out of memory.
- */
-struct cras_alert *cras_alert_create(cras_alert_prepare prepare,
- unsigned int flags);
-
-/* Adds a callback to the alert.
- * Args:
- * alert - A pointer to the alert.
- * cb - The callback.
- * arg - will be passed to the callback when it is called.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int cras_alert_add_callback(struct cras_alert *alert, cras_alert_cb cb,
- void *arg);
-
-/* Removes a callback from the alert. It removes the callback if cb and arg
- * match a previously registered entry.
- * Args:
- * alert - A pointer to the alert.
- * cb - The callback.
- * arg - will be passed to the callback when it is called.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int cras_alert_rm_callback(struct cras_alert *alert, cras_alert_cb cb,
- void *arg);
-
-/* Marks an alert as pending. We don't call the callbacks immediately when an
- * alert becomes pending, but will do that when
- * cras_alert_process_all_pending_alerts() is called.
- * Args:
- * alert - A pointer to the alert.
- */
-void cras_alert_pending(struct cras_alert *alert);
-
-/* Marks an alert as pending. We don't call the callbacks immediately when an
- * alert becomes pending, but will do that when
- * cras_alert_process_all_pending_alerts() is called.
- * By default only the last data value supplied here is provided as an
- * argument to the callback. To have the callback executed with every
- * data value, call cras_alert_keep_all_data() (see above).
- * Args:
- * alert - A pointer to the alert.
- * data - A pointer to data that is copied and passed to the callback.
- * data_size - Size of the data.
- */
-void cras_alert_pending_data(struct cras_alert *alert, void *data,
- size_t data_size);
-
-/* Processes all alerts that are pending.
- *
- * For all pending alerts, its prepare function will be called, then the
- * callbacks will be called. If any alert becomes pending during the callbacks,
- * the process will start again until no alert is pending.
- */
-void cras_alert_process_all_pending_alerts();
-
-/* Frees the resources used by an alert.
- * Args:
- * alert - A pointer to the alert.
- */
-void cras_alert_destroy(struct cras_alert *alert);
-
-/* Frees the resources used by all alerts in the system. */
-void cras_alert_destroy_all();
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* _CRAS_ALERT_H */
diff --git a/cras/src/server/cras_alsa_card.c b/cras/src/server/cras_alsa_card.c
deleted file mode 100644
index 362e6a68..00000000
--- a/cras/src/server/cras_alsa_card.c
+++ /dev/null
@@ -1,641 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE /* For asprintf */
-#endif
-
-#include <alsa/asoundlib.h>
-#include <syslog.h>
-
-#include "cras_alsa_card.h"
-#include "cras_alsa_io.h"
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_ucm.h"
-#include "cras_device_blocklist.h"
-#include "cras_card_config.h"
-#include "cras_config.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-#define MAX_ALSA_CARDS 32 /* Alsa limit on number of cards. */
-#define MAX_ALSA_CARD_NAME_LENGTH 6 /* Alsa card name "hw:XX" + 1 for null. */
-#define MAX_ALSA_PCM_NAME_LENGTH 9 /* Alsa pcm name "hw:XX,YY" + 1 for null. */
-#define MAX_COUPLED_OUTPUT_SIZE 4
-
-struct iodev_list_node {
- struct cras_iodev *iodev;
- enum CRAS_STREAM_DIRECTION direction;
- struct iodev_list_node *prev, *next;
-};
-
-/* Keeps an fd that is registered with system state. A list of fds must be
- * kept so that they can be removed when the card is destroyed. */
-struct hctl_poll_fd {
- int fd;
- struct hctl_poll_fd *prev, *next;
-};
-
-/* Holds information about each sound card on the system.
- * name - of the form hw:XX.
- * card_index - 0 based index, value of "XX" in the name.
- * iodevs - Input and output devices for this card.
- * mixer - Controls the mixer controls for this card.
- * ucm - CRAS use case manager if available.
- * hctl - ALSA high-level control interface.
- * hctl_poll_fds - List of fds registered with cras_system_state.
- * config - Config info for this card, can be NULL if none found.
- */
-struct cras_alsa_card {
- char name[MAX_ALSA_CARD_NAME_LENGTH];
- size_t card_index;
- struct iodev_list_node *iodevs;
- struct cras_alsa_mixer *mixer;
- struct cras_use_case_mgr *ucm;
- snd_hctl_t *hctl;
- struct hctl_poll_fd *hctl_poll_fds;
- struct cras_card_config *config;
-};
-
-/* Creates an iodev for the given device.
- * Args:
- * alsa_card - the alsa_card the device will be added to.
- * info - Information about the card type and priority.
- * card_name - The name of the card.
- * dev_name - The name of the device.
- * dev_id - The id string of the device.
- * device_index - 0 based index, value of "YY" in "hw:XX,YY".
- * direction - Input or output.
- * Returns:
- * Pointer to the created iodev, or NULL on error.
- * other negative error code otherwise.
- */
-struct cras_iodev *create_iodev_for_device(
- struct cras_alsa_card *alsa_card, struct cras_alsa_card_info *info,
- const char *card_name, const char *dev_name, const char *dev_id,
- unsigned device_index, enum CRAS_STREAM_DIRECTION direction)
-{
- struct iodev_list_node *new_dev;
- struct iodev_list_node *node;
- int first = 1;
- char pcm_name[MAX_ALSA_PCM_NAME_LENGTH];
-
- /* Find whether this is the first device in this direction, and
- * avoid duplicate device indexes. */
- DL_FOREACH (alsa_card->iodevs, node) {
- if (node->direction != direction)
- continue;
- first = 0;
- if (alsa_iodev_index(node->iodev) == device_index) {
- syslog(LOG_DEBUG,
- "Skipping duplicate device for %s:%s:%s [%u]",
- card_name, dev_name, dev_id, device_index);
- return node->iodev;
- }
- }
-
- new_dev = calloc(1, sizeof(*new_dev));
- if (new_dev == NULL)
- return NULL;
-
- /* Append device index to card namem, ex: 'hw:0', for the PCM name of
- * target iodev. */
- snprintf(pcm_name, MAX_ALSA_PCM_NAME_LENGTH, "%s,%u", alsa_card->name,
- device_index);
-
- new_dev->direction = direction;
- new_dev->iodev =
- alsa_iodev_create(info->card_index, card_name, device_index,
- pcm_name, dev_name, dev_id, info->card_type,
- first, alsa_card->mixer, alsa_card->config,
- alsa_card->ucm, alsa_card->hctl, direction,
- info->usb_vendor_id, info->usb_product_id,
- info->usb_serial_number);
- if (new_dev->iodev == NULL) {
- syslog(LOG_ERR, "Couldn't create alsa_iodev for %s", pcm_name);
- free(new_dev);
- return NULL;
- }
-
- syslog(LOG_DEBUG, "New %s device %s",
- direction == CRAS_STREAM_OUTPUT ? "playback" : "capture",
- pcm_name);
-
- DL_APPEND(alsa_card->iodevs, new_dev);
- return new_dev->iodev;
-}
-
-/* Returns non-zero if this card has hctl jacks.
- */
-static int card_has_hctl_jack(struct cras_alsa_card *alsa_card)
-{
- struct iodev_list_node *node;
-
- /* Find the first device that has an hctl jack. */
- DL_FOREACH (alsa_card->iodevs, node) {
- if (alsa_iodev_has_hctl_jacks(node->iodev))
- return 1;
- }
- return 0;
-}
-
-/* Check if a device should be ignored for this card. Returns non-zero if the
- * device is in the blocklist and should be ignored.
- */
-static int should_ignore_dev(struct cras_alsa_card_info *info,
- struct cras_device_blocklist *blocklist,
- size_t device_index)
-{
- if (info->card_type == ALSA_CARD_TYPE_USB)
- return cras_device_blocklist_check(
- blocklist, info->usb_vendor_id, info->usb_product_id,
- info->usb_desc_checksum, device_index);
- return 0;
-}
-
-/* Filters an array of mixer control names. Keep a name if it is
- * specified in the ucm config. */
-static struct mixer_name *filter_controls(struct cras_use_case_mgr *ucm,
- struct mixer_name *controls)
-{
- struct mixer_name *control;
- DL_FOREACH (controls, control) {
- char *dev = ucm_get_dev_for_mixer(ucm, control->name,
- CRAS_STREAM_OUTPUT);
- if (!dev)
- DL_DELETE(controls, control);
- else
- free(dev);
- }
- return controls;
-}
-
-/* Handles notifications from alsa controls. Called by main thread when a poll
- * fd provided by alsa signals there is an event available. */
-static void alsa_control_event_pending(void *arg, int revent)
-{
- struct cras_alsa_card *card;
-
- card = (struct cras_alsa_card *)arg;
- if (card == NULL) {
- syslog(LOG_ERR, "Invalid card from control event.");
- return;
- }
-
- /* handle_events will trigger the callback registered with each control
- * that has changed. */
- snd_hctl_handle_events(card->hctl);
-}
-
-static int
-add_controls_and_iodevs_by_matching(struct cras_alsa_card_info *info,
- struct cras_device_blocklist *blocklist,
- struct cras_alsa_card *alsa_card,
- const char *card_name, snd_ctl_t *handle)
-{
- struct mixer_name *coupled_controls = NULL;
- int dev_idx;
- snd_pcm_info_t *dev_info;
- struct mixer_name *extra_controls = NULL;
- int rc = 0;
-
- snd_pcm_info_alloca(&dev_info);
-
- if (alsa_card->ucm) {
- char *extra_main_volume;
-
- /* Filter the extra output mixer names */
- extra_controls = filter_controls(
- alsa_card->ucm,
- mixer_name_add(extra_controls, "IEC958",
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME));
-
- /* Get the extra main volume control. */
- extra_main_volume =
- ucm_get_flag(alsa_card->ucm, "ExtraMainVolume");
- if (extra_main_volume) {
- extra_controls = mixer_name_add(extra_controls,
- extra_main_volume,
- CRAS_STREAM_OUTPUT,
- MIXER_NAME_MAIN_VOLUME);
- free(extra_main_volume);
- }
- mixer_name_dump(extra_controls, "extra controls");
-
- /* Check if coupled controls has been specified for speaker. */
- coupled_controls =
- ucm_get_coupled_mixer_names(alsa_card->ucm, "Speaker");
- mixer_name_dump(coupled_controls, "coupled controls");
- }
-
- /* Add controls to mixer by name matching. */
- rc = cras_alsa_mixer_add_controls_by_name_matching(
- alsa_card->mixer, extra_controls, coupled_controls);
- if (rc) {
- syslog(LOG_ERR, "Fail adding controls to mixer for %s.",
- alsa_card->name);
- goto error;
- }
-
- /* Go through every device. */
- dev_idx = -1;
- while (1) {
- rc = snd_ctl_pcm_next_device(handle, &dev_idx);
- if (rc < 0)
- goto error;
- if (dev_idx < 0)
- break;
-
- snd_pcm_info_set_device(dev_info, dev_idx);
- snd_pcm_info_set_subdevice(dev_info, 0);
-
- /* Check for playback devices. */
- snd_pcm_info_set_stream(dev_info, SND_PCM_STREAM_PLAYBACK);
- if (snd_ctl_pcm_info(handle, dev_info) == 0 &&
- !should_ignore_dev(info, blocklist, dev_idx)) {
- struct cras_iodev *iodev = create_iodev_for_device(
- alsa_card, info, card_name,
- snd_pcm_info_get_name(dev_info),
- snd_pcm_info_get_id(dev_info), dev_idx,
- CRAS_STREAM_OUTPUT);
- if (iodev) {
- rc = alsa_iodev_legacy_complete_init(iodev);
- if (rc < 0)
- goto error;
- }
- }
-
- /* Check for capture devices. */
- snd_pcm_info_set_stream(dev_info, SND_PCM_STREAM_CAPTURE);
- if (snd_ctl_pcm_info(handle, dev_info) == 0) {
- struct cras_iodev *iodev = create_iodev_for_device(
- alsa_card, info, card_name,
- snd_pcm_info_get_name(dev_info),
- snd_pcm_info_get_id(dev_info), dev_idx,
- CRAS_STREAM_INPUT);
- if (iodev) {
- rc = alsa_iodev_legacy_complete_init(iodev);
- if (rc < 0)
- goto error;
- }
- }
- }
-error:
- mixer_name_free(coupled_controls);
- mixer_name_free(extra_controls);
- return rc;
-}
-
-static int add_controls_and_iodevs_with_ucm(struct cras_alsa_card_info *info,
- struct cras_alsa_card *alsa_card,
- const char *card_name,
- snd_ctl_t *handle)
-{
- snd_pcm_info_t *dev_info;
- struct mixer_name *main_volume_control_names;
- struct iodev_list_node *node;
- int rc = 0;
- struct ucm_section *section;
- struct ucm_section *ucm_sections;
-
- snd_pcm_info_alloca(&dev_info);
-
- main_volume_control_names = ucm_get_main_volume_names(alsa_card->ucm);
- if (main_volume_control_names) {
- rc = cras_alsa_mixer_add_main_volume_control_by_name(
- alsa_card->mixer, main_volume_control_names);
- if (rc) {
- syslog(LOG_ERR,
- "Failed adding main volume controls to"
- " mixer for '%s'.'",
- card_name);
- goto cleanup_names;
- }
- }
-
- /* Get info on the devices specified in the UCM config. */
- ucm_sections = ucm_get_sections(alsa_card->ucm);
- if (!ucm_sections) {
- syslog(LOG_ERR,
- "Could not retrieve any UCM SectionDevice"
- " info for '%s'.",
- card_name);
- rc = -ENOENT;
- goto cleanup_names;
- }
-
- /* Create all of the controls first. */
- DL_FOREACH (ucm_sections, section) {
- rc = cras_alsa_mixer_add_controls_in_section(alsa_card->mixer,
- section);
- if (rc) {
- syslog(LOG_ERR,
- "Failed adding controls to"
- " mixer for '%s:%s'",
- card_name, section->name);
- goto cleanup;
- }
- }
-
- /* Create all of the devices. */
- DL_FOREACH (ucm_sections, section) {
- /* If a UCM section specifies certain device as dependency
- * then don't create an alsa iodev for it, just append it
- * as node later. */
- if (section->dependent_dev_idx != -1)
- continue;
- snd_pcm_info_set_device(dev_info, section->dev_idx);
- snd_pcm_info_set_subdevice(dev_info, 0);
- if (section->dir == CRAS_STREAM_OUTPUT)
- snd_pcm_info_set_stream(dev_info,
- SND_PCM_STREAM_PLAYBACK);
- else if (section->dir == CRAS_STREAM_INPUT)
- snd_pcm_info_set_stream(dev_info,
- SND_PCM_STREAM_CAPTURE);
- else {
- syslog(LOG_ERR, "Unexpected direction: %d",
- section->dir);
- rc = -EINVAL;
- goto cleanup;
- }
-
- if (snd_ctl_pcm_info(handle, dev_info)) {
- syslog(LOG_ERR, "Could not get info for device: %s",
- section->name);
- continue;
- }
-
- create_iodev_for_device(alsa_card, info, card_name,
- snd_pcm_info_get_name(dev_info),
- snd_pcm_info_get_id(dev_info),
- section->dev_idx, section->dir);
- }
-
- /* Setup jacks and controls for the devices. If a SectionDevice is
- * dependent on another SectionDevice, it'll be added as a node to
- * a existing ALSA iodev. */
- DL_FOREACH (ucm_sections, section) {
- DL_FOREACH (alsa_card->iodevs, node) {
- if (node->direction != section->dir)
- continue;
- if (alsa_iodev_index(node->iodev) == section->dev_idx)
- break;
- if (alsa_iodev_index(node->iodev) ==
- section->dependent_dev_idx)
- break;
- }
- if (node) {
- rc = alsa_iodev_ucm_add_nodes_and_jacks(node->iodev,
- section);
- if (rc < 0)
- goto cleanup;
- }
- }
-
- DL_FOREACH (alsa_card->iodevs, node) {
- alsa_iodev_ucm_complete_init(node->iodev);
- }
-
-cleanup:
- ucm_section_free_list(ucm_sections);
-cleanup_names:
- mixer_name_free(main_volume_control_names);
- return rc;
-}
-
-static void configure_echo_reference_dev(struct cras_alsa_card *alsa_card)
-{
- struct iodev_list_node *dev_node, *echo_ref_node;
- const char *echo_ref_name;
-
- if (!alsa_card->ucm)
- return;
-
- DL_FOREACH (alsa_card->iodevs, dev_node) {
- if (!dev_node->iodev->nodes)
- continue;
-
- echo_ref_name = ucm_get_echo_reference_dev_name_for_dev(
- alsa_card->ucm, dev_node->iodev->nodes->name);
- if (!echo_ref_name)
- continue;
- DL_FOREACH (alsa_card->iodevs, echo_ref_node) {
- if (echo_ref_node->iodev->nodes == NULL)
- continue;
- if (!strcmp(echo_ref_name,
- echo_ref_node->iodev->nodes->name))
- break;
- }
- if (echo_ref_node)
- dev_node->iodev->echo_reference_dev =
- echo_ref_node->iodev;
- else
- syslog(LOG_ERR,
- "Echo ref dev %s doesn't exist on card %s",
- echo_ref_name, alsa_card->name);
- free((void *)echo_ref_name);
- }
-}
-
-/*
- * Exported Interface.
- */
-
-struct cras_alsa_card *cras_alsa_card_create(
- struct cras_alsa_card_info *info, const char *device_config_dir,
- struct cras_device_blocklist *blocklist, const char *ucm_suffix)
-{
- snd_ctl_t *handle = NULL;
- int rc, n;
- snd_ctl_card_info_t *card_info;
- const char *card_name;
- struct cras_alsa_card *alsa_card;
-
- if (info->card_index >= MAX_ALSA_CARDS) {
- syslog(LOG_ERR, "Invalid alsa card index %u", info->card_index);
- return NULL;
- }
-
- snd_ctl_card_info_alloca(&card_info);
-
- alsa_card = calloc(1, sizeof(*alsa_card));
- if (alsa_card == NULL)
- return NULL;
- alsa_card->card_index = info->card_index;
-
- snprintf(alsa_card->name, MAX_ALSA_CARD_NAME_LENGTH, "hw:%u",
- info->card_index);
-
- rc = snd_ctl_open(&handle, alsa_card->name, 0);
- if (rc < 0) {
- syslog(LOG_ERR, "Fail opening control %s.", alsa_card->name);
- goto error_bail;
- }
-
- rc = snd_ctl_card_info(handle, card_info);
- if (rc < 0) {
- syslog(LOG_ERR, "Error getting card info.");
- goto error_bail;
- }
-
- card_name = snd_ctl_card_info_get_name(card_info);
- if (card_name == NULL) {
- syslog(LOG_ERR, "Error getting card name.");
- goto error_bail;
- }
-
- if (info->card_type != ALSA_CARD_TYPE_INTERNAL ||
- cras_system_check_ignore_ucm_suffix(card_name))
- ucm_suffix = NULL;
-
- /* Read config file for this card if it exists. */
- alsa_card->config =
- cras_card_config_create(device_config_dir, card_name);
- if (alsa_card->config == NULL)
- syslog(LOG_DEBUG, "No config file for %s", alsa_card->name);
-
- /* Create a use case manager if a configuration is available. */
- if (ucm_suffix) {
- char *ucm_name;
- if (asprintf(&ucm_name, "%s.%s", card_name, ucm_suffix) == -1) {
- syslog(LOG_ERR, "Error creating ucm name");
- goto error_bail;
- }
- alsa_card->ucm = ucm_create(ucm_name);
- syslog(LOG_INFO, "Card %s (%s) has UCM: %s", alsa_card->name,
- ucm_name, alsa_card->ucm ? "yes" : "no");
- free(ucm_name);
- } else {
- alsa_card->ucm = ucm_create(card_name);
- syslog(LOG_INFO, "Card %s (%s) has UCM: %s", alsa_card->name,
- card_name, alsa_card->ucm ? "yes" : "no");
- }
-
- if (info->card_type == ALSA_CARD_TYPE_INTERNAL && !alsa_card->ucm)
- syslog(LOG_ERR, "No ucm config on internal card %s", card_name);
-
- rc = snd_hctl_open(&alsa_card->hctl, alsa_card->name, SND_CTL_NONBLOCK);
- if (rc < 0) {
- syslog(LOG_DEBUG, "failed to get hctl for %s", alsa_card->name);
- alsa_card->hctl = NULL;
- } else {
- rc = snd_hctl_nonblock(alsa_card->hctl, 1);
- if (rc < 0) {
- syslog(LOG_ERR, "failed to nonblock hctl for %s",
- alsa_card->name);
- goto error_bail;
- }
-
- rc = snd_hctl_load(alsa_card->hctl);
- if (rc < 0) {
- syslog(LOG_ERR, "failed to load hctl for %s",
- alsa_card->name);
- goto error_bail;
- }
- }
-
- /* Create one mixer per card. */
- alsa_card->mixer = cras_alsa_mixer_create(alsa_card->name);
-
- if (alsa_card->mixer == NULL) {
- syslog(LOG_ERR, "Fail opening mixer for %s.", alsa_card->name);
- goto error_bail;
- }
-
- if (alsa_card->ucm && ucm_has_fully_specified_ucm_flag(alsa_card->ucm))
- rc = add_controls_and_iodevs_with_ucm(info, alsa_card,
- card_name, handle);
- else
- rc = add_controls_and_iodevs_by_matching(
- info, blocklist, alsa_card, card_name, handle);
- if (rc)
- goto error_bail;
-
- configure_echo_reference_dev(alsa_card);
-
- n = alsa_card->hctl ? snd_hctl_poll_descriptors_count(alsa_card->hctl) :
- 0;
- if (n != 0 && card_has_hctl_jack(alsa_card)) {
- struct hctl_poll_fd *registered_fd;
- struct pollfd *pollfds;
- int i;
-
- pollfds = malloc(n * sizeof(*pollfds));
- if (pollfds == NULL) {
- rc = -ENOMEM;
- goto error_bail;
- }
-
- n = snd_hctl_poll_descriptors(alsa_card->hctl, pollfds, n);
- for (i = 0; i < n; i++) {
- registered_fd = calloc(1, sizeof(*registered_fd));
- if (registered_fd == NULL) {
- free(pollfds);
- rc = -ENOMEM;
- goto error_bail;
- }
- registered_fd->fd = pollfds[i].fd;
- DL_APPEND(alsa_card->hctl_poll_fds, registered_fd);
- rc = cras_system_add_select_fd(
- registered_fd->fd, alsa_control_event_pending,
- alsa_card, POLLIN);
- if (rc < 0) {
- DL_DELETE(alsa_card->hctl_poll_fds,
- registered_fd);
- free(pollfds);
- goto error_bail;
- }
- }
- free(pollfds);
- }
-
- snd_ctl_close(handle);
- return alsa_card;
-
-error_bail:
- if (handle != NULL)
- snd_ctl_close(handle);
- cras_alsa_card_destroy(alsa_card);
- return NULL;
-}
-
-void cras_alsa_card_destroy(struct cras_alsa_card *alsa_card)
-{
- struct iodev_list_node *curr;
- struct hctl_poll_fd *poll_fd;
-
- if (alsa_card == NULL)
- return;
-
- DL_FOREACH (alsa_card->iodevs, curr) {
- alsa_iodev_destroy(curr->iodev);
- DL_DELETE(alsa_card->iodevs, curr);
- free(curr);
- }
- DL_FOREACH (alsa_card->hctl_poll_fds, poll_fd) {
- cras_system_rm_select_fd(poll_fd->fd);
- DL_DELETE(alsa_card->hctl_poll_fds, poll_fd);
- free(poll_fd);
- }
- if (alsa_card->hctl)
- snd_hctl_close(alsa_card->hctl);
- if (alsa_card->ucm)
- ucm_destroy(alsa_card->ucm);
- if (alsa_card->mixer)
- cras_alsa_mixer_destroy(alsa_card->mixer);
- if (alsa_card->config)
- cras_card_config_destroy(alsa_card->config);
- free(alsa_card);
-}
-
-size_t cras_alsa_card_get_index(const struct cras_alsa_card *alsa_card)
-{
- assert(alsa_card);
- return alsa_card->card_index;
-}
diff --git a/cras/src/server/cras_alsa_card.h b/cras/src/server/cras_alsa_card.h
deleted file mode 100644
index a63bf90a..00000000
--- a/cras/src/server/cras_alsa_card.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_ALSA_CARD_H
-#define _CRAS_ALSA_CARD_H
-
-#include "cras_types.h"
-
-/* cras_alsa_card represents an alsa sound card. It adds all the devices for
- * this card to the system when it is created, and removes them when it is
- * destroyed. It will create an alsa_mixer object that can control the volume
- * and mute settings for the card.
- */
-
-struct cras_alsa_card;
-struct cras_device_blocklist;
-
-/* Creates a cras_alsa_card instance for the given alsa device. Enumerates the
- * devices for the card and adds them to the system as possible playback or
- * capture endpoints.
- * Args:
- * card_info - Contains the card index, type, and priority.
- * device_config_dir - The directory of device configs which contains the
- * volume curves.
- * blocklist - List of devices that should be ignored.
- * ucm_suffix - The ucm config name is formed as <card-name>.<suffix>
- * Returns:
- * A pointer to the newly created cras_alsa_card which must later be freed
- * by calling cras_alsa_card_destroy or NULL on error.
- */
-struct cras_alsa_card *cras_alsa_card_create(
- struct cras_alsa_card_info *info, const char *device_config_dir,
- struct cras_device_blocklist *blocklist, const char *ucm_suffix);
-
-/* Destroys a cras_alsa_card that was returned from cras_alsa_card_create.
- * Args:
- * alsa_card - The cras_alsa_card pointer returned from
- * cras_alsa_card_create.
- */
-void cras_alsa_card_destroy(struct cras_alsa_card *alsa_card);
-
-/* Returns the alsa card index for the given card.
- * Args:
- * alsa_card - The cras_alsa_card pointer returned from
- * cras_alsa_card_create.
- */
-size_t cras_alsa_card_get_index(const struct cras_alsa_card *alsa_card);
-
-#endif /* _CRAS_ALSA_CARD_H */
diff --git a/cras/src/server/cras_alsa_helpers.c b/cras/src/server/cras_alsa_helpers.c
deleted file mode 100644
index 6cdc165a..00000000
--- a/cras/src/server/cras_alsa_helpers.c
+++ /dev/null
@@ -1,799 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <limits.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include "cras_alsa_helpers.h"
-#include "cras_audio_format.h"
-#include "cras_util.h"
-
-/* Macro to convert between snd_pcm_chmap_position(defined in
- * alsa-lib since 1.0.27) and CRAS_CHANNEL, values of which are
- * of the same order but shifted by 3.
- */
-#define CH_TO_ALSA(ch) ((ch) + (3))
-#define CH_TO_CRAS(ch) ((ch) - (3))
-
-/* Assert the channel is defined in CRAS_CHANNELS. */
-#define ALSA_CH_VALID(ch) ((ch >= SND_CHMAP_FL) && (ch <= SND_CHMAP_FRC))
-
-/* Time difference between two consecutive underrun logs. */
-#define UNDERRUN_LOG_TIME_SECS 30
-
-/* Limit the number of channels supported for devices: b/158509536 */
-#define TEMP_CHANNEL_LIMIT 20
-
-/* Chances to give mmap_begin to work. */
-static const size_t MAX_MMAP_BEGIN_ATTEMPTS = 3;
-/* Time to sleep between resume attempts. */
-static const size_t ALSA_SUSPENDED_SLEEP_TIME_US = 250000;
-
-/* What rates should we check for on this dev?
- * Listed in order of preference. 0 terminalted. */
-static const size_t test_sample_rates[] = {
- 44100, 48000, 32000, 96000, 22050, 16000, 8000, 4000, 192000, 0,
-};
-
-/* What channel counts shoud be checked on this dev?
- * Listed in order of preference. 0 terminalted. */
-static const size_t test_channel_counts[] = { 10, 6, 4, 2, 1, 8, 0 };
-
-static const snd_pcm_format_t test_formats[] = {
- SND_PCM_FORMAT_S16_LE, SND_PCM_FORMAT_S24_LE, SND_PCM_FORMAT_S32_LE,
- SND_PCM_FORMAT_S24_3LE, (snd_pcm_format_t)0
-};
-
-/* Looks up the list of channel map for the one can exactly matches
- * the layout specified in fmt.
- */
-static snd_pcm_chmap_query_t *
-cras_chmap_caps_match(snd_pcm_chmap_query_t **chmaps,
- struct cras_audio_format *fmt)
-{
- size_t ch, i;
- int idx, matches;
- snd_pcm_chmap_query_t **chmap;
-
- /* Search for channel map that already matches the order */
- for (chmap = chmaps; *chmap; chmap++) {
- if ((*chmap)->map.channels != fmt->num_channels)
- continue;
-
- matches = 1;
- for (ch = 0; ch < CRAS_CH_MAX; ch++) {
- idx = fmt->channel_layout[ch];
- if (idx == -1)
- continue;
- if ((unsigned)idx >= (*chmap)->map.channels)
- continue;
- if ((*chmap)->map.pos[idx] != CH_TO_ALSA(ch)) {
- matches = 0;
- break;
- }
- }
- if (matches)
- return *chmap;
- }
-
- /* Search for channel map that can arbitrarily swap order */
- for (chmap = chmaps; *chmap; chmap++) {
- if ((*chmap)->type == SND_CHMAP_TYPE_FIXED ||
- (*chmap)->map.channels != fmt->num_channels)
- continue;
-
- matches = 1;
- for (ch = 0; ch < CRAS_CH_MAX; ch++) {
- idx = fmt->channel_layout[ch];
- if (idx == -1)
- continue;
- int found = 0;
- for (i = 0; i < fmt->num_channels; i++) {
- if ((*chmap)->map.pos[i] == CH_TO_ALSA(ch)) {
- found = 1;
- break;
- }
- }
- if (found == 0) {
- matches = 0;
- break;
- }
- }
- if (matches && (*chmap)->type == SND_CHMAP_TYPE_VAR)
- return *chmap;
-
- /* Check if channel map is a match by arbitrarily swap
- * pair order */
- matches = 1;
- for (i = 0; i < fmt->num_channels; i += 2) {
- ch = CH_TO_CRAS((*chmap)->map.pos[i]);
- if (fmt->channel_layout[ch] & 0x01) {
- matches = 0;
- break;
- }
-
- if (fmt->channel_layout[ch] + 1 !=
- fmt->channel_layout[CH_TO_CRAS(
- (*chmap)->map.pos[i + 1])]) {
- matches = 0;
- break;
- }
- }
- if (matches)
- return *chmap;
- }
-
- return NULL;
-}
-
-/* When the exact match does not exist, select the best valid
- * channel map which can be supported by means of channel conversion
- * matrix.
- */
-static snd_pcm_chmap_query_t *
-cras_chmap_caps_conv_matrix(snd_pcm_chmap_query_t **chmaps,
- struct cras_audio_format *fmt)
-{
- float **conv_mtx;
- size_t i;
- snd_pcm_chmap_query_t **chmap;
- struct cras_audio_format *conv_fmt;
-
- conv_fmt = cras_audio_format_create(fmt->format, fmt->frame_rate,
- fmt->num_channels);
-
- for (chmap = chmaps; *chmap; chmap++) {
- if ((*chmap)->map.channels != fmt->num_channels)
- continue;
- for (i = 0; i < CRAS_CH_MAX; i++)
- conv_fmt->channel_layout[i] = -1;
- for (i = 0; i < conv_fmt->num_channels; i++) {
- if (!ALSA_CH_VALID((*chmap)->map.pos[i]))
- continue;
- conv_fmt->channel_layout[CH_TO_CRAS(
- (*chmap)->map.pos[i])] = i;
- }
-
- /* Examine channel map by test creating a conversion matrix
- * for each candidate. Once a non-null matrix is created,
- * that channel map is considered supported and select it as
- * the best match one.
- */
- conv_mtx = cras_channel_conv_matrix_create(fmt, conv_fmt);
- if (conv_mtx) {
- cras_channel_conv_matrix_destroy(
- conv_mtx, conv_fmt->num_channels);
- cras_audio_format_destroy(conv_fmt);
- return *chmap;
- }
- }
-
- cras_audio_format_destroy(conv_fmt);
- return NULL;
-}
-
-/* Finds the best channel map for given format and list of channel
- * map capability.
- */
-static snd_pcm_chmap_query_t *
-cras_chmap_caps_best(snd_pcm_t *handle, snd_pcm_chmap_query_t **chmaps,
- struct cras_audio_format *fmt)
-{
- snd_pcm_chmap_query_t **chmap;
- snd_pcm_chmap_query_t *match;
-
- match = cras_chmap_caps_match(chmaps, fmt);
- if (match)
- return match;
-
- match = cras_chmap_caps_conv_matrix(chmaps, fmt);
- if (match)
- return match;
-
- /* For capture stream, choose the first chmap matching channel
- * count. Channel positions reported in this chmap will be used
- * to fill correspond channels into client stream.
- */
- if (snd_pcm_stream(handle) == SND_PCM_STREAM_CAPTURE)
- for (chmap = chmaps; *chmap; chmap++)
- if ((*chmap)->map.channels == fmt->num_channels)
- return *chmap;
- return NULL;
-}
-
-int cras_alsa_pcm_open(snd_pcm_t **handle, const char *dev,
- snd_pcm_stream_t stream)
-{
- int rc;
- int retries = 3;
- static const unsigned int OPEN_RETRY_DELAY_US = 100000;
-
-retry_open:
- rc = snd_pcm_open(handle, dev, stream,
- SND_PCM_NONBLOCK | SND_PCM_NO_AUTO_RESAMPLE |
- SND_PCM_NO_AUTO_CHANNELS |
- SND_PCM_NO_AUTO_FORMAT);
- if (rc == -EBUSY && --retries) {
- usleep(OPEN_RETRY_DELAY_US);
- goto retry_open;
- }
-
- return rc;
-}
-
-int cras_alsa_pcm_close(snd_pcm_t *handle)
-{
- return snd_pcm_close(handle);
-}
-
-int cras_alsa_pcm_start(snd_pcm_t *handle)
-{
- return snd_pcm_start(handle);
-}
-
-int cras_alsa_pcm_drain(snd_pcm_t *handle)
-{
- return snd_pcm_drain(handle);
-}
-
-int cras_alsa_resume_appl_ptr(snd_pcm_t *handle, snd_pcm_uframes_t ahead)
-{
- int rc;
- snd_pcm_uframes_t period_frames, buffer_frames;
- snd_pcm_sframes_t to_move, avail_frames;
- rc = snd_pcm_avail(handle);
- if (rc == -EPIPE || rc == -ESTRPIPE) {
- cras_alsa_attempt_resume(handle);
- avail_frames = 0;
- } else if (rc < 0) {
- syslog(LOG_ERR, "Fail to get avail frames: %s",
- snd_strerror(rc));
- return rc;
- } else {
- avail_frames = rc;
- }
-
- rc = snd_pcm_get_params(handle, &buffer_frames, &period_frames);
- if (rc < 0) {
- syslog(LOG_ERR, "Fail to get buffer size: %s",
- snd_strerror(rc));
- return rc;
- }
-
- to_move = avail_frames - buffer_frames + ahead;
- if (to_move > 0) {
- rc = snd_pcm_forward(handle, to_move);
- } else if (to_move < 0) {
- rc = snd_pcm_rewind(handle, -to_move);
- } else {
- return 0;
- }
-
- if (rc < 0) {
- syslog(LOG_ERR, "Fail to resume appl_ptr: %s",
- snd_strerror(rc));
- return rc;
- }
- return 0;
-}
-
-int cras_alsa_set_channel_map(snd_pcm_t *handle, struct cras_audio_format *fmt)
-{
- size_t i, ch;
- snd_pcm_chmap_query_t **chmaps;
- snd_pcm_chmap_query_t *match;
-
- if (fmt->num_channels <= 2)
- return 0;
-
- chmaps = snd_pcm_query_chmaps(handle);
- if (chmaps == NULL) {
- syslog(LOG_WARNING, "No chmap queried! Skip chmap set");
- goto done;
- }
-
- match = cras_chmap_caps_best(handle, chmaps, fmt);
- if (!match) {
- syslog(LOG_ERR, "Unable to find the best channel map");
- goto done;
- }
-
- /* A channel map could match the layout after channels
- * pair/arbitrary swapped. Modified the channel positions
- * before set to HW.
- */
- for (i = 0; i < fmt->num_channels; i++) {
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- if (fmt->channel_layout[ch] == (int)i)
- break;
- if (ch != CRAS_CH_MAX)
- match->map.pos[i] = CH_TO_ALSA(ch);
- }
- if (snd_pcm_set_chmap(handle, &match->map) != 0)
- syslog(LOG_ERR, "Unable to set channel map");
-
-done:
- snd_pcm_free_chmaps(chmaps);
- return 0;
-}
-
-int cras_alsa_get_channel_map(snd_pcm_t *handle, struct cras_audio_format *fmt)
-{
- snd_pcm_chmap_query_t **chmaps;
- snd_pcm_chmap_query_t *match;
- int rc = 0;
- size_t i;
-
- chmaps = snd_pcm_query_chmaps(handle);
- if (chmaps == NULL) {
- rc = -EINVAL;
- goto done;
- }
-
- match = cras_chmap_caps_best(handle, chmaps, fmt);
- if (!match) {
- syslog(LOG_ERR, "Unable to find the best channel map");
- rc = -1;
- goto done;
- }
-
- /* Fill back the selected channel map so channel converter can
- * handle it. */
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt->channel_layout[i] = -1;
- for (i = 0; i < fmt->num_channels; i++) {
- if (!ALSA_CH_VALID(match->map.pos[i]))
- continue;
- fmt->channel_layout[CH_TO_CRAS(match->map.pos[i])] = i;
- }
-
- /* Handle the special channel map {SND_CHMAP_MONO} */
- if (match->map.channels == 1 && match->map.pos[0] == SND_CHMAP_MONO)
- fmt->channel_layout[CRAS_CH_FC] = 0;
-
-done:
- snd_pcm_free_chmaps(chmaps);
- return rc;
-}
-
-int cras_alsa_fill_properties(snd_pcm_t *handle, size_t **rates,
- size_t **channel_counts,
- snd_pcm_format_t **formats)
-{
- int rc;
- size_t i, num_found;
- snd_pcm_hw_params_t *params;
-
- snd_pcm_hw_params_alloca(&params);
-
- rc = snd_pcm_hw_params_any(handle, params);
- if (rc < 0) {
- syslog(LOG_ERR, "snd_pcm_hw_params_any: %s", snd_strerror(rc));
- return rc;
- }
-
- *rates = (size_t *)malloc(sizeof(test_sample_rates));
- if (*rates == NULL)
- return -ENOMEM;
- *channel_counts = (size_t *)malloc(sizeof(test_channel_counts));
- if (*channel_counts == NULL) {
- free(*rates);
- return -ENOMEM;
- }
- *formats = (snd_pcm_format_t *)malloc(sizeof(test_formats));
- if (*formats == NULL) {
- free(*channel_counts);
- free(*rates);
- return -ENOMEM;
- }
-
- num_found = 0;
- for (i = 0; test_sample_rates[i] != 0; i++) {
- rc = snd_pcm_hw_params_test_rate(handle, params,
- test_sample_rates[i], 0);
- if (rc == 0)
- (*rates)[num_found++] = test_sample_rates[i];
- }
- (*rates)[num_found] = 0;
- if (num_found == 0) {
- syslog(LOG_WARNING, "No valid sample rates.");
- return -EINVAL;
- }
-
- num_found = 0;
- for (i = 0; test_channel_counts[i] != 0; i++) {
- rc = snd_pcm_hw_params_test_channels(handle, params,
- test_channel_counts[i]);
- if (rc == 0)
- (*channel_counts)[num_found++] = test_channel_counts[i];
- }
- (*channel_counts)[num_found] = 0;
- if (num_found == 0) {
- // Pull the max channel count and use that.
- unsigned int max_channels = 0;
- rc = snd_pcm_hw_params_get_channels_max(params, &max_channels);
- if (rc < 0) {
- syslog(LOG_WARNING, "No valid channel counts found.");
- return -EINVAL;
- } else if (max_channels > TEMP_CHANNEL_LIMIT) {
- syslog(LOG_WARNING, "Can't support so many channels.");
- return -EINVAL;
- } else {
- (*channel_counts)[0] = (size_t)max_channels;
- (*channel_counts)[1] = 0;
- }
- }
-
- num_found = 0;
- for (i = 0; test_formats[i] != 0; i++) {
- rc = snd_pcm_hw_params_test_format(handle, params,
- test_formats[i]);
- if (rc == 0)
- (*formats)[num_found++] = test_formats[i];
- }
- (*formats)[num_found] = (snd_pcm_format_t)0;
- if (num_found == 0) {
- syslog(LOG_WARNING, "No valid sample formats.");
- return -EINVAL;
- }
-
- return 0;
-}
-
-int cras_alsa_set_hwparams(snd_pcm_t *handle, struct cras_audio_format *format,
- snd_pcm_uframes_t *buffer_frames, int period_wakeup,
- unsigned int dma_period_time)
-{
- unsigned int rate, ret_rate;
- int err;
- snd_pcm_hw_params_t *hwparams;
-
- rate = format->frame_rate;
- snd_pcm_hw_params_alloca(&hwparams);
-
- err = snd_pcm_hw_params_any(handle, hwparams);
- if (err < 0) {
- syslog(LOG_ERR, "hw_params_any failed %s\n", snd_strerror(err));
- return err;
- }
- /* Disable hardware resampling. */
- err = snd_pcm_hw_params_set_rate_resample(handle, hwparams, 0);
- if (err < 0) {
- syslog(LOG_ERR, "Disabling resampling %s\n", snd_strerror(err));
- return err;
- }
- /* Always interleaved. */
- err = snd_pcm_hw_params_set_access(handle, hwparams,
- SND_PCM_ACCESS_MMAP_INTERLEAVED);
- if (err < 0) {
- syslog(LOG_ERR, "Setting interleaved %s\n", snd_strerror(err));
- return err;
- }
- /* If period_wakeup flag is not set, try to disable ALSA wakeups,
- * we'll keep a timer. */
- if (!period_wakeup &&
- snd_pcm_hw_params_can_disable_period_wakeup(hwparams)) {
- err = snd_pcm_hw_params_set_period_wakeup(handle, hwparams, 0);
- if (err < 0)
- syslog(LOG_WARNING, "disabling wakeups %s\n",
- snd_strerror(err));
- }
- /* Setup the period time so that the hardware pulls the right amount
- * of data at the right time. */
- if (dma_period_time) {
- int dir = 0;
- unsigned int original = dma_period_time;
-
- err = snd_pcm_hw_params_set_period_time_near(
- handle, hwparams, &dma_period_time, &dir);
- if (err < 0) {
- syslog(LOG_ERR, "could not set period time: %s",
- snd_strerror(err));
- return err;
- } else if (original != dma_period_time) {
- syslog(LOG_DEBUG, "period time set to: %u",
- dma_period_time);
- }
- }
- /* Set the sample format. */
- err = snd_pcm_hw_params_set_format(handle, hwparams, format->format);
- if (err < 0) {
- syslog(LOG_ERR, "set format %s\n", snd_strerror(err));
- return err;
- }
- /* Set the stream rate. */
- ret_rate = rate;
- err = snd_pcm_hw_params_set_rate_near(handle, hwparams, &ret_rate, 0);
- if (err < 0) {
- syslog(LOG_ERR, "set_rate_near %iHz %s\n", rate,
- snd_strerror(err));
- return err;
- }
- if (ret_rate != rate) {
- syslog(LOG_ERR, "tried for %iHz, settled for %iHz)\n", rate,
- ret_rate);
- return -EINVAL;
- }
- /* Set the count of channels. */
- err = snd_pcm_hw_params_set_channels(handle, hwparams,
- format->num_channels);
- if (err < 0) {
- syslog(LOG_ERR, "set_channels %s\n", snd_strerror(err));
- return err;
- }
-
- /* Make sure buffer frames is even, or snd_pcm_hw_params will
- * return invalid argument error. */
- err = snd_pcm_hw_params_get_buffer_size_max(hwparams, buffer_frames);
- if (err < 0)
- syslog(LOG_WARNING, "get buffer max %s\n", snd_strerror(err));
-
- *buffer_frames &= ~0x01;
- err = snd_pcm_hw_params_set_buffer_size_max(handle, hwparams,
- buffer_frames);
- if (err < 0) {
- syslog(LOG_ERR, "set_buffer_size_max %s", snd_strerror(err));
- return err;
- }
-
- syslog(LOG_DEBUG, "buffer size set to %u\n",
- (unsigned int)*buffer_frames);
-
- /* Finally, write the parameters to the device. */
- err = snd_pcm_hw_params(handle, hwparams);
- if (err < 0) {
- syslog(LOG_ERR,
- "hw_params: %s: rate: %u, ret_rate: %u, "
- "channel: %zu, format: %u\n",
- snd_strerror(err), rate, ret_rate, format->num_channels,
- format->format);
- return err;
- }
- return 0;
-}
-
-int cras_alsa_set_swparams(snd_pcm_t *handle)
-{
- int err;
- snd_pcm_sw_params_t *swparams;
- snd_pcm_uframes_t boundary;
-
- snd_pcm_sw_params_alloca(&swparams);
-
- err = snd_pcm_sw_params_current(handle, swparams);
- if (err < 0) {
- syslog(LOG_ERR, "sw_params_current: %s\n", snd_strerror(err));
- return err;
- }
- err = snd_pcm_sw_params_get_boundary(swparams, &boundary);
- if (err < 0) {
- syslog(LOG_ERR, "get_boundary: %s\n", snd_strerror(err));
- return err;
- }
- err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, boundary);
- if (err < 0) {
- syslog(LOG_ERR, "set_stop_threshold: %s\n", snd_strerror(err));
- return err;
- }
- /* Don't auto start. */
- err = snd_pcm_sw_params_set_start_threshold(handle, swparams, LONG_MAX);
- if (err < 0) {
- syslog(LOG_ERR, "set_stop_threshold: %s\n", snd_strerror(err));
- return err;
- }
-
- /* Disable period events. */
- err = snd_pcm_sw_params_set_period_event(handle, swparams, 0);
- if (err < 0) {
- syslog(LOG_ERR, "set_period_event: %s\n", snd_strerror(err));
- return err;
- }
-
- err = snd_pcm_sw_params(handle, swparams);
-
- if (err < 0) {
- syslog(LOG_ERR, "sw_params: %s\n", snd_strerror(err));
- return err;
- }
- return 0;
-}
-
-int cras_alsa_get_avail_frames(snd_pcm_t *handle, snd_pcm_uframes_t buf_size,
- snd_pcm_uframes_t severe_underrun_frames,
- const char *dev_name, snd_pcm_uframes_t *avail,
- struct timespec *tstamp)
-{
- snd_pcm_sframes_t frames;
- int rc = 0;
- static struct timespec tstamp_last_underrun_log = { .tv_sec = 0,
- .tv_nsec = 0 };
-
- /* Use snd_pcm_avail still to ensure that the hardware pointer is
- * up to date. Otherwise, we could use the deprecated snd_pcm_hwsync().
- * IMO this is a deficiency in the ALSA API.
- */
- frames = snd_pcm_avail(handle);
- if (frames >= 0)
- rc = snd_pcm_htimestamp(handle, avail, tstamp);
- else
- rc = frames;
- if (rc == -EPIPE || rc == -ESTRPIPE) {
- cras_alsa_attempt_resume(handle);
- rc = 0;
- goto error;
- } else if (rc < 0) {
- syslog(LOG_ERR, "pcm_avail error %s, %s\n", dev_name,
- snd_strerror(rc));
- goto error;
- } else if (frames > (snd_pcm_sframes_t)buf_size) {
- struct timespec tstamp_now;
- clock_gettime(CLOCK_MONOTONIC_RAW, &tstamp_now);
- /* Limit the log rate. */
- if ((tstamp_now.tv_sec - tstamp_last_underrun_log.tv_sec) >
- UNDERRUN_LOG_TIME_SECS) {
- syslog(LOG_ERR,
- "pcm_avail returned frames larger than buf_size: "
- "%s: %ld > %lu\n",
- dev_name, frames, buf_size);
- tstamp_last_underrun_log.tv_sec = tstamp_now.tv_sec;
- tstamp_last_underrun_log.tv_nsec = tstamp_now.tv_nsec;
- }
- if ((frames - (snd_pcm_sframes_t)buf_size) >
- (snd_pcm_sframes_t)severe_underrun_frames) {
- rc = -EPIPE;
- goto error;
- } else {
- frames = buf_size;
- }
- }
- *avail = frames;
- return 0;
-
-error:
- *avail = 0;
- tstamp->tv_sec = 0;
- tstamp->tv_nsec = 0;
- return rc;
-}
-
-int cras_alsa_get_delay_frames(snd_pcm_t *handle, snd_pcm_uframes_t buf_size,
- snd_pcm_sframes_t *delay)
-{
- int rc;
-
- rc = snd_pcm_delay(handle, delay);
- if (rc < 0)
- return rc;
- if (*delay > (snd_pcm_sframes_t)buf_size)
- *delay = buf_size;
- if (*delay < 0)
- *delay = 0;
- return 0;
-}
-
-/*
- * Attempts to resume a PCM.
- * Note that this path does not get executed for default playback/capture
- * stream. Default playback/capture stream are removed from the device
- * upon suspend, and re-attached to the device after resume.
- * The only stream that lives across suspend resume is hotword stream.
- */
-int cras_alsa_attempt_resume(snd_pcm_t *handle)
-{
- int rc;
-
- syslog(LOG_INFO, "System suspended.");
- while ((rc = snd_pcm_resume(handle)) == -EAGAIN)
- usleep(ALSA_SUSPENDED_SLEEP_TIME_US);
- if (rc < 0) {
- /*
- * Some devices do not support snd_pcm_resume, that is
- * acceptable.
- */
- syslog(LOG_INFO, "System suspended, failed to resume %s.",
- snd_strerror(rc));
- rc = snd_pcm_prepare(handle);
- if (rc < 0) {
- syslog(LOG_ERR, "Suspended, failed to prepare: %s.",
- snd_strerror(rc));
- }
- /*
- * CRAS does not use auto-start (start_threshold = 0), so start
- * PCM after it is prepared. This is only for hotword stream.
- */
- rc = snd_pcm_start(handle);
- if (rc < 0) {
- syslog(LOG_ERR, "Suspended, failed to start: %s.",
- snd_strerror(rc));
- }
- }
- return rc;
-}
-
-int cras_alsa_mmap_get_whole_buffer(snd_pcm_t *handle, uint8_t **dst)
-{
- snd_pcm_uframes_t offset;
- /* The purpose of calling cras_alsa_mmap_begin is to get the base
- * address of the buffer. The requested and retrieved frames are not
- * meaningful here.
- * However, we need to set a non-zero requested frames to get a
- * non-zero retrieved frames. This is to avoid the error checking in
- * snd_pcm_mmap_begin, where it judges retrieved frames being 0 as a
- * failure.
- */
- snd_pcm_uframes_t frames = 1;
-
- return cras_alsa_mmap_begin(handle, 0, dst, &offset, &frames);
-}
-
-int cras_alsa_mmap_begin(snd_pcm_t *handle, unsigned int format_bytes,
- uint8_t **dst, snd_pcm_uframes_t *offset,
- snd_pcm_uframes_t *frames)
-{
- int rc;
- unsigned int attempts = 0;
- const snd_pcm_channel_area_t *my_areas;
-
- while (attempts++ < MAX_MMAP_BEGIN_ATTEMPTS) {
- rc = snd_pcm_mmap_begin(handle, &my_areas, offset, frames);
- if (rc == -ESTRPIPE) {
- /* First handle suspend/resume. */
- rc = cras_alsa_attempt_resume(handle);
- if (rc < 0)
- return rc;
- continue; /* Recovered from suspend, try again. */
- } else if (rc < 0) {
- /* If we can recover, continue and try again. */
- if (snd_pcm_recover(handle, rc, 0) == 0)
- continue;
- syslog(LOG_INFO, "recover failed begin: %s\n",
- snd_strerror(rc));
- return rc;
- }
- /* Available frames could be zero right after input pcm handle
- * resumed. As for output pcm handle, some error has occurred
- * when mmap_begin return zero frames, return -EIO for that
- * case.
- */
- if (snd_pcm_stream(handle) == SND_PCM_STREAM_PLAYBACK &&
- *frames == 0) {
- syslog(LOG_INFO, "mmap_begin set frames to 0.");
- return -EIO;
- }
- *dst = (uint8_t *)my_areas[0].addr + (*offset) * format_bytes;
- return 0;
- }
- return -EIO;
-}
-
-int cras_alsa_mmap_commit(snd_pcm_t *handle, snd_pcm_uframes_t offset,
- snd_pcm_uframes_t frames)
-{
- int rc;
- snd_pcm_sframes_t res;
-
- res = snd_pcm_mmap_commit(handle, offset, frames);
- if (res != (snd_pcm_sframes_t)frames) {
- res = res >= 0 ? (int)-EPIPE : res;
- if (res == -ESTRPIPE) {
- /* First handle suspend/resume. */
- rc = cras_alsa_attempt_resume(handle);
- if (rc < 0)
- return rc;
- } else {
- /* If we can recover, continue and try again. */
- rc = snd_pcm_recover(handle, res, 0);
- if (rc < 0) {
- syslog(LOG_ERR,
- "mmap_commit: pcm_recover failed: %s\n",
- snd_strerror(rc));
- return rc;
- }
- }
- }
- return 0;
-}
diff --git a/cras/src/server/cras_alsa_helpers.h b/cras/src/server/cras_alsa_helpers.h
deleted file mode 100644
index 01a42aea..00000000
--- a/cras/src/server/cras_alsa_helpers.h
+++ /dev/null
@@ -1,227 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Alsa Helpers - Keeps the interface to alsa localized to this file.
- */
-
-#ifndef _CRAS_ALSA_HELPERS_H
-#define _CRAS_ALSA_HELPERS_H
-
-#include <alsa/asoundlib.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-struct cras_audio_format;
-
-/* Sets the channel layout from given format to the pcm handle.
- * Args:
- * handle - Pointer to the opened pcm to set channel map to.
- * fmt - The format containing the channel layout info.
- * Returns:
- * 0 if a matched channel map is set to HW, -1 otherwise.
- */
-int cras_alsa_set_channel_map(snd_pcm_t *handle, struct cras_audio_format *fmt);
-
-/* Gets the supported channel mapping of the pcm handle which matches
- * the channel layout in the format.
- * Args:
- * handle - Pointer to the opened pcm to get channel map info.
- * fmt - The format to fill channel layout into.
- * Returns:
- * 0 if an exactly matched channel map is found, -1 otherwise.
- */
-int cras_alsa_get_channel_map(snd_pcm_t *handle, struct cras_audio_format *fmt);
-
-/* Opens an alsa device, thin wrapper to snd_pcm_open.
- * Args:
- * handle - Filled with a pointer to the opened pcm.
- * dev - Path to the alsa device to test.
- * stream - Alsa stream type, input or output.
- * Returns:
- * See docs for snd_pcm_open.
- */
-int cras_alsa_pcm_open(snd_pcm_t **handle, const char *dev,
- snd_pcm_stream_t stream);
-
-/* Closes an alsa device, thin wrapper to snd_pcm_close.
- * Args:
- * handle - Filled with a pointer to the opened pcm.
- * Returns:
- * See docs for snd_pcm_close.
- */
-int cras_alsa_pcm_close(snd_pcm_t *handle);
-
-/* Starts an alsa device, thin wrapper to snd_pcm_start.
- * Args:
- * handle - Filled with a pointer to the opened pcm.
- * Returns:
- * See docs for snd_pcm_start.
- */
-int cras_alsa_pcm_start(snd_pcm_t *handle);
-
-/* Drains an alsa device, thin wrapper to snd_pcm_drain.
- * Args:
- * handle - Filled with a pointer to the opened pcm.
- * Returns:
- * See docs for snd_pcm_drain.
- */
-int cras_alsa_pcm_drain(snd_pcm_t *handle);
-
-/* Forward/rewind appl_ptr so it becomes ahead of hw_ptr by fuzz samples.
- * After moving appl_ptr, device can play the new samples as quick as possible.
- * avail = buffer_frames - appl_ptr + hw_ptr
- * => hw_ptr - appl_ptr = avail - buffer_frames.
- * The difference between hw_ptr and app_ptr can be inferred from snd_pcm_avail.
- * So the amount of frames to forward appl_ptr is
- * avail - buffer_frames + fuzz.
- * When hw_ptr is wrapped around boundary, this value may be negative. Use
- * snd_pcm_rewind to move appl_ptr backward.
- *
- * Case 1: avail - buffer_frames + fuzz > 0
- *
- * -------|----------|-----------------------------------
- * app_ptr hw_ptr
- * |------------->| forward target
- *
- * Case 2: avail - buffer_frames + fuzz < 0
- *
- * -------|----------|-----------------------------------
- * hw_ptr app_ptr
- * |<------| rewind target
- *
- * Args:
- * handle - Filled with a pointer to the opened pcm.
- * ahead - Number of frames appl_ptr should be ahead of hw_ptr.
- * Returns:
- * 0 on success. A negative error code on failure.
- */
-int cras_alsa_resume_appl_ptr(snd_pcm_t *handle, snd_pcm_uframes_t ahead);
-
-/* Probes properties of the alsa device.
- * Args:
- * handle - The open PCM to configure.
- * rates - Pointer that will be set to the arrary of valid samples rates.
- * Must be freed by the caller.
- * channel_counts - Pointer that will be set to the array of valid channel
- * counts. Must be freed by the caller.
- * formats - Pointer that will be set to the arrary of valid PCM formats.
- * Must be freed by the caller.
- * Returns:
- * 0 on success. On failure an error code from alsa or -ENOMEM.
- */
-int cras_alsa_fill_properties(snd_pcm_t *handle, size_t **rates,
- size_t **channel_counts,
- snd_pcm_format_t **formats);
-
-/* Sets up the hwparams to alsa.
- * Args:
- * handle - The open PCM to configure.
- * format - The audio format desired for playback/capture.
- * buffer_frames - Number of frames in the ALSA buffer.
- * period_wakeup - Flag to determine if period_wakeup is required
- * 0 - disable, 1 - enable
- * dma_period_time - If non-zero, set the dma period time to this value
- * (in microseconds).
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_alsa_set_hwparams(snd_pcm_t *handle, struct cras_audio_format *format,
- snd_pcm_uframes_t *buffer_frames, int period_wakeup,
- unsigned int dma_period_time);
-
-/* Sets up the swparams to alsa.
- * Args:
- * handle - The open PCM to configure.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_alsa_set_swparams(snd_pcm_t *handle);
-
-/* Get the number of used frames in the alsa buffer.
- *
- * When underrun is not severe, this function masks the underrun situation
- * and set avail as 0. When underrun is severe, returns -EPIPE so caller
- * can handle it.
- * Args:
- * handle[in] - The open PCM to configure.
- * buf_size[in] - Number of frames in the ALSA buffer.
- * severe_underrun_frames[in] - Number of frames as the threshold for severe
- * underrun.
- * dev_name[in] - Device name for logging.
- * avail[out] - Filled with the number of frames available in the buffer.
- * tstamp[out] - Filled with the hardware timestamp for the available frames.
- * This value is {0, 0} when the device hasn't actually started
- * reading or writing frames.
- * Returns:
- * 0 on success, negative error on failure. -EPIPE if severe underrun
- * happens.
- */
-int cras_alsa_get_avail_frames(snd_pcm_t *handle, snd_pcm_uframes_t buf_size,
- snd_pcm_uframes_t severe_underrun_frames,
- const char *dev_name, snd_pcm_uframes_t *avail,
- struct timespec *tstamp);
-
-/* Get the current alsa delay, make sure it's no bigger than the buffer size.
- * Args:
- * handle - The open PCM to configure.
- * buf_size - Number of frames in the ALSA buffer.
- * delay - Filled with the number of delay frames.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_alsa_get_delay_frames(snd_pcm_t *handle, snd_pcm_uframes_t buf_size,
- snd_pcm_sframes_t *delay);
-
-/* Wrapper for snd_pcm_mmap_begin where only buffer is concerned.
- * Offset and frames from cras_alsa_mmap_begin are neglected.
- * Args:
- * handle - The open PCM to configure.
- * dst - Pointer set to the area for reading/writing the audio.
- * Returns:
- * zero on success, negative error code for fatal errors.
- */
-int cras_alsa_mmap_get_whole_buffer(snd_pcm_t *handle, uint8_t **dst);
-
-/* Wrapper for snd_pcm_mmap_begin
- * Args:
- * handle - The open PCM to configure.
- * format_bytes - Number of bytes in a single frame.
- * dst - Pointer set to the area for reading/writing the audio.
- * offset - Filled with the offset to pass back to commit.
- * frames - Passed with the max number of frames to request. Filled with the
- * max number to use.
- * Returns:
- * zero on success, negative error code for fatal
- * errors.
- */
-int cras_alsa_mmap_begin(snd_pcm_t *handle, unsigned int format_bytes,
- uint8_t **dst, snd_pcm_uframes_t *offset,
- snd_pcm_uframes_t *frames);
-
-/* Wrapper for snd_pcm_mmap_commit
- * Args:
- * handle - The open PCM to configure.
- * offset - offset from call to mmap_begin.
- * frames - # of frames written/read.
- * Returns:
- * zero on success, negative error code for fatal
- * errors.
- */
-int cras_alsa_mmap_commit(snd_pcm_t *handle, snd_pcm_uframes_t offset,
- snd_pcm_uframes_t frames);
-
-/* When the stream is suspended, due to a system suspend, loop until we can
- * resume it. Won't actually loop very much because the system will be
- * suspended.
- * Args:
- * handle - The open PCM to configure.
- * Returns:
- * zero on success, negative error code for fatal
- * errors.
- */
-int cras_alsa_attempt_resume(snd_pcm_t *handle);
-
-#endif /* _CRAS_ALSA_HELPERS_H */
diff --git a/cras/src/server/cras_alsa_io.c b/cras/src/server/cras_alsa_io.c
deleted file mode 100644
index 275a6810..00000000
--- a/cras/src/server/cras_alsa_io.c
+++ /dev/null
@@ -1,2473 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <errno.h>
-#include <limits.h>
-#include <stdio.h>
-#include <sys/param.h>
-#include <sys/select.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <syslog.h>
-#include <time.h>
-
-#include "audio_thread.h"
-#include "cras_alsa_helpers.h"
-#include "cras_alsa_io.h"
-#include "cras_alsa_jack.h"
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_ucm.h"
-#include "cras_audio_area.h"
-#include "cras_config.h"
-#include "cras_utf8.h"
-#include "cras_hotword_handler.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_messages.h"
-#include "cras_ramp.h"
-#include "cras_rclient.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "cras_volume_curve.h"
-#include "sfh.h"
-#include "softvol_curve.h"
-#include "utlist.h"
-
-#define HOTWORD_DEV "Wake on Voice"
-#define DEFAULT "(default)"
-#define HDMI "HDMI"
-#define INTERNAL_MICROPHONE "Internal Mic"
-#define INTERNAL_SPEAKER "Speaker"
-#define KEYBOARD_MIC "Keyboard Mic"
-#define HEADPHONE "Headphone"
-#define MIC "Mic"
-#define USB "USB"
-#define LOOPBACK_CAPTURE "Loopback Capture"
-#define LOOPBACK_PLAYBACK "Loopback Playback"
-
-/*
- * For USB, pad the output buffer. This avoids a situation where there isn't a
- * complete URB's worth of audio ready to be transmitted when it is requested.
- * The URB interval does track directly to the audio clock, making it hard to
- * predict the exact interval.
- */
-#define USB_EXTRA_BUFFER_FRAMES 768
-
-/*
- * When snd_pcm_avail returns a value that is greater than buffer size,
- * we know there is an underrun. If the number of underrun samples
- * (avail - buffer_size) is greater than SEVERE_UNDERRUN_MS * rate,
- * it is a severe underrun. Main thread should disable and then enable
- * device to recover it from underrun.
- */
-#define SEVERE_UNDERRUN_MS 5000
-
-/*
- * When entering no stream state, audio thread needs to fill extra zeros in
- * order to play remaining valid frames. The value indicates how many
- * time will be filled.
- */
-static const struct timespec no_stream_fill_zeros_duration = {
- 0, 50 * 1000 * 1000 /* 50 msec. */
-};
-
-/*
- * This extends cras_ionode to include alsa-specific information.
- * Members:
- * mixer_output - From cras_alsa_mixer.
- * pcm_name - PCM name for snd_pcm_open.
- * volume_curve - Volume curve for this node.
- * jack - The jack associated with the node.
- */
-struct alsa_output_node {
- struct cras_ionode base;
- struct mixer_control *mixer_output;
- const char *pcm_name;
- struct cras_volume_curve *volume_curve;
- const struct cras_alsa_jack *jack;
-};
-
-struct alsa_input_node {
- struct cras_ionode base;
- struct mixer_control *mixer_input;
- const char *pcm_name;
- const struct cras_alsa_jack *jack;
- int8_t *channel_layout;
-};
-
-/*
- * Child of cras_iodev, alsa_io handles ALSA interaction for sound devices.
- * base - The cras_iodev structure "base class".
- * pcm_name - The PCM name passed to snd_pcm_open() (e.g. "hw:0,0").
- * dev_name - value from snd_pcm_info_get_name
- * dev_id - value from snd_pcm_info_get_id
- * device_index - ALSA index of device, Y in "hw:X:Y".
- * next_ionode_index - The index we will give to the next ionode. Each ionode
- * have a unique index within the iodev.
- * card_type - the type of the card this iodev belongs.
- * is_first - true if this is the first iodev on the card.
- * fully_specified - true if this device and it's nodes were fully specified.
- * That is, don't automatically create nodes for it.
- * handle - Handle to the opened ALSA device.
- * num_severe_underruns - Number of times we have run out of data badly.
- Unlike num_underruns which records for the duration
- where device is opened, num_severe_underruns records
- since device is created. When severe underrun occurs
- a possible action is to close/open device.
- * alsa_stream - Playback or capture type.
- * mixer - Alsa mixer used to control volume and mute of the device.
- * config - Card config for this alsa device.
- * jack_list - List of alsa jack controls for this device.
- * ucm - CRAS use case manager, if configuration is found.
- * mmap_offset - offset returned from mmap_begin.
- * poll_fd - Descriptor used to block until data is ready.
- * dma_period_set_microsecs - If non-zero, the value to apply to the dma_period.
- * free_running - true if device is playing zeros in the buffer without
- * user filling meaningful data. The device buffer is filled
- * with zeros. In this state, appl_ptr remains the same
- * while hw_ptr keeps running ahead.
- * filled_zeros_for_draining - The number of zeros filled for draining.
- * severe_underrun_frames - The threshold for severe underrun.
- * default_volume_curve - Default volume curve that converts from an index
- * to dBFS.
- * has_dependent_dev - true if this iodev has dependent device.
- */
-struct alsa_io {
- struct cras_iodev base;
- char *pcm_name;
- char *dev_name;
- char *dev_id;
- uint32_t device_index;
- uint32_t next_ionode_index;
- enum CRAS_ALSA_CARD_TYPE card_type;
- int is_first;
- int fully_specified;
- snd_pcm_t *handle;
- unsigned int num_severe_underruns;
- snd_pcm_stream_t alsa_stream;
- struct cras_alsa_mixer *mixer;
- const struct cras_card_config *config;
- struct cras_alsa_jack_list *jack_list;
- struct cras_use_case_mgr *ucm;
- snd_pcm_uframes_t mmap_offset;
- int poll_fd;
- unsigned int dma_period_set_microsecs;
- int free_running;
- unsigned int filled_zeros_for_draining;
- snd_pcm_uframes_t severe_underrun_frames;
- struct cras_volume_curve *default_volume_curve;
- int hwparams_set;
- int has_dependent_dev;
-};
-
-static void init_device_settings(struct alsa_io *aio);
-
-static int alsa_iodev_set_active_node(struct cras_iodev *iodev,
- struct cras_ionode *ionode,
- unsigned dev_enabled);
-
-static int get_fixed_rate(struct alsa_io *aio);
-
-static int update_supported_formats(struct cras_iodev *iodev);
-
-/*
- * Defines the default values of nodes.
- */
-static const struct {
- const char *name;
- enum CRAS_NODE_TYPE type;
- enum CRAS_NODE_POSITION position;
-} node_defaults[] = {
- {
- .name = DEFAULT,
- .type = CRAS_NODE_TYPE_UNKNOWN,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = INTERNAL_SPEAKER,
- .type = CRAS_NODE_TYPE_INTERNAL_SPEAKER,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = INTERNAL_MICROPHONE,
- .type = CRAS_NODE_TYPE_MIC,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = KEYBOARD_MIC,
- .type = CRAS_NODE_TYPE_MIC,
- .position = NODE_POSITION_KEYBOARD,
- },
- {
- .name = HDMI,
- .type = CRAS_NODE_TYPE_HDMI,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "IEC958",
- .type = CRAS_NODE_TYPE_HDMI,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "Headphone",
- .type = CRAS_NODE_TYPE_HEADPHONE,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "Front Headphone",
- .type = CRAS_NODE_TYPE_HEADPHONE,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "Front Mic",
- .type = CRAS_NODE_TYPE_MIC,
- .position = NODE_POSITION_FRONT,
- },
- {
- .name = "Rear Mic",
- .type = CRAS_NODE_TYPE_MIC,
- .position = NODE_POSITION_REAR,
- },
- {
- .name = "Mic",
- .type = CRAS_NODE_TYPE_MIC,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = HOTWORD_DEV,
- .type = CRAS_NODE_TYPE_HOTWORD,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = "Haptic",
- .type = CRAS_NODE_TYPE_HAPTIC,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = "Rumbler",
- .type = CRAS_NODE_TYPE_HAPTIC,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = "Line Out",
- .type = CRAS_NODE_TYPE_LINEOUT,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "SCO Line In",
- .type = CRAS_NODE_TYPE_BLUETOOTH,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "SCO Line Out",
- .type = CRAS_NODE_TYPE_BLUETOOTH,
- .position = NODE_POSITION_EXTERNAL,
- },
- {
- .name = "Echo Reference",
- .type = CRAS_NODE_TYPE_ECHO_REFERENCE,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = LOOPBACK_CAPTURE,
- .type = CRAS_NODE_TYPE_ALSA_LOOPBACK,
- .position = NODE_POSITION_INTERNAL,
- },
- {
- .name = LOOPBACK_PLAYBACK,
- .type = CRAS_NODE_TYPE_ALSA_LOOPBACK,
- .position = NODE_POSITION_INTERNAL,
- },
-};
-
-static int set_hwparams(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int period_wakeup;
- int rc;
-
- /* Only need to set hardware params once. */
- if (aio->hwparams_set)
- return 0;
-
- /* If it's a wake on voice device, period_wakeups are required. */
- period_wakeup = (iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD);
-
- /* Sets frame rate and channel count to alsa device before
- * we test channel mapping. */
- rc = cras_alsa_set_hwparams(aio->handle, iodev->format,
- &iodev->buffer_size, period_wakeup,
- aio->dma_period_set_microsecs);
- if (rc < 0)
- return rc;
-
- aio->hwparams_set = 1;
- return 0;
-}
-
-/*
- * iodev callbacks.
- */
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int rc;
- snd_pcm_uframes_t frames;
-
- rc = cras_alsa_get_avail_frames(aio->handle, aio->base.buffer_size,
- aio->severe_underrun_frames,
- iodev->info.name, &frames, tstamp);
- if (rc < 0) {
- if (rc == -EPIPE)
- aio->num_severe_underruns++;
- return rc;
- }
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- if (iodev->direction == CRAS_STREAM_INPUT)
- return (int)frames;
-
- /* For output, return number of frames that are used. */
- return iodev->buffer_size - frames;
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- snd_pcm_sframes_t delay;
- int rc;
-
- rc = cras_alsa_get_delay_frames(aio->handle, iodev->buffer_size,
- &delay);
- if (rc < 0)
- return rc;
-
- return (int)delay;
-}
-
-static int close_dev(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
-
- /* Removes audio thread callback from main thread. */
- if (aio->poll_fd >= 0)
- audio_thread_rm_callback_sync(
- cras_iodev_list_get_audio_thread(), aio->poll_fd);
- if (!aio->handle)
- return 0;
- cras_alsa_pcm_close(aio->handle);
- aio->handle = NULL;
- aio->free_running = 0;
- aio->filled_zeros_for_draining = 0;
- aio->hwparams_set = 0;
- cras_iodev_free_format(&aio->base);
- cras_iodev_free_audio_area(&aio->base);
- return 0;
-}
-
-static int empty_hotword_cb(void *arg, int revents)
-{
- /* Only need this once. */
- struct alsa_io *aio = (struct alsa_io *)arg;
- audio_thread_rm_callback(aio->poll_fd);
- aio->poll_fd = -1;
- aio->base.input_streaming = 1;
-
- /* Send hotword triggered signal. */
- cras_hotword_send_triggered_msg();
-
- return 0;
-}
-
-static int open_dev(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- snd_pcm_t *handle;
- int rc;
- const char *pcm_name = NULL;
- int enable_noise_cancellation;
-
- if (aio->base.direction == CRAS_STREAM_OUTPUT) {
- struct alsa_output_node *aout =
- (struct alsa_output_node *)aio->base.active_node;
- pcm_name = aout->pcm_name;
- } else {
- struct alsa_input_node *ain =
- (struct alsa_input_node *)aio->base.active_node;
- pcm_name = ain->pcm_name;
- }
-
- /* For legacy UCM path which doesn't have PlaybackPCM or CapturePCM. */
- if (pcm_name == NULL)
- pcm_name = aio->pcm_name;
-
- rc = cras_alsa_pcm_open(&handle, pcm_name, aio->alsa_stream);
- if (rc < 0)
- return rc;
-
- aio->handle = handle;
-
- /* Enable or disable noise cancellation if it supports. */
- if (aio->ucm && iodev->direction == CRAS_STREAM_INPUT &&
- ucm_node_noise_cancellation_exists(aio->ucm,
- iodev->active_node->name)) {
- enable_noise_cancellation =
- cras_system_get_noise_cancellation_enabled();
- rc = ucm_enable_node_noise_cancellation(
- aio->ucm, iodev->active_node->name,
- enable_noise_cancellation);
- if (rc < 0)
- return rc;
- }
-
- return 0;
-}
-
-static int configure_dev(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int rc;
-
- /* This is called after the first stream added so configure for it.
- * format must be set before opening the device.
- */
- if (iodev->format == NULL)
- return -EINVAL;
- aio->free_running = 0;
- aio->filled_zeros_for_draining = 0;
- aio->severe_underrun_frames =
- SEVERE_UNDERRUN_MS * iodev->format->frame_rate / 1000;
-
- cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
-
- syslog(LOG_DEBUG, "Configure alsa device %s rate %zuHz, %zu channels",
- aio->pcm_name, iodev->format->frame_rate,
- iodev->format->num_channels);
-
- rc = set_hwparams(iodev);
- if (rc < 0)
- return rc;
-
- /* Set channel map to device */
- rc = cras_alsa_set_channel_map(aio->handle, iodev->format);
- if (rc < 0)
- return rc;
-
- /* Configure software params. */
- rc = cras_alsa_set_swparams(aio->handle);
- if (rc < 0)
- return rc;
-
- /* Initialize device settings. */
- init_device_settings(aio);
-
- aio->poll_fd = -1;
- if (iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD) {
- struct pollfd *ufds;
- int count, i;
-
- count = snd_pcm_poll_descriptors_count(aio->handle);
- if (count <= 0) {
- syslog(LOG_ERR, "Invalid poll descriptors count\n");
- return count;
- }
-
- ufds = (struct pollfd *)malloc(sizeof(struct pollfd) * count);
- if (ufds == NULL)
- return -ENOMEM;
-
- rc = snd_pcm_poll_descriptors(aio->handle, ufds, count);
- if (rc < 0) {
- syslog(LOG_ERR,
- "Getting hotword poll descriptors: %s\n",
- snd_strerror(rc));
- free(ufds);
- return rc;
- }
-
- for (i = 0; i < count; i++) {
- if (ufds[i].events & POLLIN) {
- aio->poll_fd = ufds[i].fd;
- break;
- }
- }
- free(ufds);
-
- if (aio->poll_fd >= 0)
- audio_thread_add_events_callback(
- aio->poll_fd, empty_hotword_cb, aio, POLLIN);
- }
-
- /* Capture starts right away, playback will wait for samples. */
- if (aio->alsa_stream == SND_PCM_STREAM_CAPTURE)
- cras_alsa_pcm_start(aio->handle);
-
- return 0;
-}
-
-/*
- * Check if ALSA device is opened by checking if handle is valid.
- * Note that to fully open a cras_iodev, ALSA device is opened first, then there
- * are some device init settings to be done in init_device_settings.
- * Therefore, when setting volume/mute/gain in init_device_settings,
- * cras_iodev is not in CRAS_IODEV_STATE_OPEN yet. We need to check if handle
- * is valid when setting those properties, instead of checking
- * cras_iodev_is_open.
- */
-static int has_handle(const struct alsa_io *aio)
-{
- return !!aio->handle;
-}
-
-static int start(const struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- snd_pcm_t *handle = aio->handle;
- int rc;
-
- if (snd_pcm_state(handle) == SND_PCM_STATE_RUNNING)
- return 0;
-
- if (snd_pcm_state(handle) == SND_PCM_STATE_SUSPENDED) {
- rc = cras_alsa_attempt_resume(handle);
- if (rc < 0) {
- syslog(LOG_ERR, "Resume error: %s", snd_strerror(rc));
- return rc;
- }
- cras_iodev_reset_rate_estimator(iodev);
- } else {
- rc = cras_alsa_pcm_start(handle);
- if (rc < 0) {
- syslog(LOG_ERR, "Start error: %s", snd_strerror(rc));
- return rc;
- }
- }
-
- return 0;
-}
-
-static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
- unsigned *frames)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- snd_pcm_uframes_t nframes = *frames;
- uint8_t *dst = NULL;
- size_t format_bytes;
- int rc;
-
- aio->mmap_offset = 0;
- format_bytes = cras_get_format_bytes(iodev->format);
-
- rc = cras_alsa_mmap_begin(aio->handle, format_bytes, &dst,
- &aio->mmap_offset, &nframes);
-
- iodev->area->frames = nframes;
- cras_audio_area_config_buf_pointers(iodev->area, iodev->format, dst);
-
- *area = iodev->area;
- *frames = nframes;
-
- return rc;
-}
-
-static int put_buffer(struct cras_iodev *iodev, unsigned nwritten)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
-
- return cras_alsa_mmap_commit(aio->handle, aio->mmap_offset, nwritten);
-}
-
-static int flush_buffer(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- snd_pcm_uframes_t nframes;
-
- if (iodev->direction == CRAS_STREAM_INPUT) {
- nframes = snd_pcm_avail(aio->handle);
- nframes = snd_pcm_forwardable(aio->handle);
- return snd_pcm_forward(aio->handle, nframes);
- }
- return 0;
-}
-
-/*
- * Gets the first plugged node in list. This is used as the
- * default node to set as active.
- */
-static struct cras_ionode *first_plugged_node(struct cras_iodev *iodev)
-{
- struct cras_ionode *n;
-
- /* When this is called at iodev creation, none of the nodes
- * are selected. Just pick the first plugged one and let Chrome
- * choose it later. */
- DL_FOREACH (iodev->nodes, n) {
- if (n->plugged)
- return n;
- }
- return iodev->nodes;
-}
-
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
- struct cras_ionode *n;
-
- /* If a node exists for node_idx, set it as active. */
- DL_FOREACH (iodev->nodes, n) {
- if (n->idx == node_idx) {
- alsa_iodev_set_active_node(iodev, n, dev_enabled);
- return;
- }
- }
-
- alsa_iodev_set_active_node(iodev, first_plugged_node(iodev),
- dev_enabled);
-}
-
-static int update_channel_layout(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int err = 0;
-
- /* If the capture channel map is specified in UCM, prefer it over
- * what ALSA provides. */
- if (aio->ucm && (iodev->direction == CRAS_STREAM_INPUT)) {
- struct alsa_input_node *input =
- (struct alsa_input_node *)iodev->active_node;
-
- if (input->channel_layout) {
- memcpy(iodev->format->channel_layout,
- input->channel_layout,
- CRAS_CH_MAX * sizeof(*input->channel_layout));
- return 0;
- }
- }
-
- err = set_hwparams(iodev);
- if (err < 0)
- return err;
-
- return cras_alsa_get_channel_map(aio->handle, iodev->format);
-}
-
-static int set_hotword_model(struct cras_iodev *iodev, const char *model_name)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- if (!aio->ucm)
- return -EINVAL;
-
- return ucm_set_hotword_model(aio->ucm, model_name);
-}
-
-static char *get_hotword_models(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- if (!aio->ucm)
- return NULL;
-
- return ucm_get_hotword_models(aio->ucm);
-}
-
-/*
- * Alsa helper functions.
- */
-
-static struct alsa_output_node *get_active_output(const struct alsa_io *aio)
-{
- return (struct alsa_output_node *)aio->base.active_node;
-}
-
-static struct alsa_input_node *get_active_input(const struct alsa_io *aio)
-{
- return (struct alsa_input_node *)aio->base.active_node;
-}
-
-/*
- * Gets the curve for the active output node. If the node doesn't have volume
- * curve specified, return the default volume curve of the parent iodev.
- */
-static const struct cras_volume_curve *
-get_curve_for_output_node(const struct alsa_io *aio,
- const struct alsa_output_node *node)
-{
- if (node && node->volume_curve)
- return node->volume_curve;
- return aio->default_volume_curve;
-}
-
-/*
- * Gets the curve for the active output.
- */
-static const struct cras_volume_curve *
-get_curve_for_active_output(const struct alsa_io *aio)
-{
- struct alsa_output_node *node = get_active_output(aio);
- return get_curve_for_output_node(aio, node);
-}
-
-/*
- * Informs the system of the volume limits for this device.
- */
-static void set_alsa_volume_limits(struct alsa_io *aio)
-{
- const struct cras_volume_curve *curve;
-
- /* Only set the limits if the dev is active. */
- if (!has_handle(aio))
- return;
-
- curve = get_curve_for_active_output(aio);
- cras_system_set_volume_limits(curve->get_dBFS(curve, 1), /* min */
- curve->get_dBFS(curve,
- CRAS_MAX_SYSTEM_VOLUME));
-}
-
-/*
- * Sets the volume of the playback device to the specified level. Receives a
- * volume index from the system settings, ranging from 0 to 100, converts it to
- * dB using the volume curve, and sends the dB value to alsa.
- */
-static void set_alsa_volume(struct cras_iodev *iodev)
-{
- const struct alsa_io *aio = (const struct alsa_io *)iodev;
- const struct cras_volume_curve *curve;
- size_t volume;
- struct alsa_output_node *aout;
-
- assert(aio);
- if (aio->mixer == NULL)
- return;
-
- /* Only set the volume if the dev is active. */
- if (!has_handle(aio))
- return;
-
- volume = cras_system_get_volume();
- curve = get_curve_for_active_output(aio);
- if (curve == NULL)
- return;
- aout = get_active_output(aio);
- if (aout)
- volume = cras_iodev_adjust_node_volume(&aout->base, volume);
-
- /* Samples get scaled for devices using software volume, set alsa
- * volume to 100. */
- if (cras_iodev_software_volume_needed(iodev))
- volume = 100;
-
- cras_alsa_mixer_set_dBFS(aio->mixer, curve->get_dBFS(curve, volume),
- aout ? aout->mixer_output : NULL);
-}
-
-/*
- * Sets the alsa mute control for this iodev.
- */
-static void set_alsa_mute(struct cras_iodev *iodev)
-{
- const struct alsa_io *aio = (const struct alsa_io *)iodev;
- struct alsa_output_node *aout;
-
- if (!has_handle(aio))
- return;
-
- aout = get_active_output(aio);
- cras_alsa_mixer_set_mute(aio->mixer, cras_system_get_mute(),
- aout ? aout->mixer_output : NULL);
-}
-
-/*
- * Sets the capture gain to the current system input gain level, given in dBFS.
- * Set mute based on the system mute state. This gain can be positive or
- * negative and might be adjusted often if an app is running an AGC.
- */
-static void set_alsa_capture_gain(struct cras_iodev *iodev)
-{
- const struct alsa_io *aio = (const struct alsa_io *)iodev;
- struct alsa_input_node *ain;
- long min_capture_gain, max_capture_gain, gain;
- assert(aio);
- if (aio->mixer == NULL)
- return;
-
- /* Only set the volume if the dev is active. */
- if (!has_handle(aio))
- return;
-
- ain = get_active_input(aio);
-
- cras_alsa_mixer_set_capture_mute(aio->mixer,
- cras_system_get_capture_mute(),
- ain ? ain->mixer_input : NULL);
-
- /* For USB device without UCM config, not change a gain control. */
- if (ain && ain->base.type == CRAS_NODE_TYPE_USB && !aio->ucm)
- return;
-
- /* Set hardware gain to 0dB if software gain is needed. */
- if (cras_iodev_software_volume_needed(iodev))
- gain = 0;
- else {
- min_capture_gain = cras_alsa_mixer_get_minimum_capture_gain(
- aio->mixer, ain ? ain->mixer_input : NULL);
- max_capture_gain = cras_alsa_mixer_get_maximum_capture_gain(
- aio->mixer, ain ? ain->mixer_input : NULL);
- gain = MAX(iodev->active_node->capture_gain, min_capture_gain);
- gain = MIN(gain, max_capture_gain);
- }
-
- cras_alsa_mixer_set_capture_dBFS(aio->mixer, gain,
- ain ? ain->mixer_input : NULL);
-}
-
-/*
- * Swaps the left and right channels of the given node.
- */
-static int set_alsa_node_swapped(struct cras_iodev *iodev,
- struct cras_ionode *node, int enable)
-{
- const struct alsa_io *aio = (const struct alsa_io *)iodev;
- assert(aio);
- return ucm_enable_swap_mode(aio->ucm, node->name, enable);
-}
-
-/*
- * Initializes the device settings according to system volume, mute, gain
- * settings.
- * Updates system capture gain limits based on current active device/node.
- */
-static void init_device_settings(struct alsa_io *aio)
-{
- /* Register for volume/mute callback and set initial volume/mute for
- * the device. */
- if (aio->base.direction == CRAS_STREAM_OUTPUT) {
- set_alsa_volume_limits(aio);
- set_alsa_volume(&aio->base);
- set_alsa_mute(&aio->base);
- } else {
- set_alsa_capture_gain(&aio->base);
- }
-}
-
-/*
- * Functions run in the main server context.
- */
-
-/*
- * Frees resources used by the alsa iodev.
- * Args:
- * iodev - the iodev to free the resources from.
- */
-static void free_alsa_iodev_resources(struct alsa_io *aio)
-{
- struct cras_ionode *node;
- struct alsa_output_node *aout;
- struct alsa_input_node *ain;
-
- free(aio->base.supported_rates);
- free(aio->base.supported_channel_counts);
- free(aio->base.supported_formats);
-
- DL_FOREACH (aio->base.nodes, node) {
- if (aio->base.direction == CRAS_STREAM_OUTPUT) {
- aout = (struct alsa_output_node *)node;
- cras_volume_curve_destroy(aout->volume_curve);
- free((void *)aout->pcm_name);
- } else {
- ain = (struct alsa_input_node *)node;
- free((void *)ain->pcm_name);
- }
- cras_iodev_rm_node(&aio->base, node);
- free(node->softvol_scalers);
- free((void *)node->dsp_name);
- free(node);
- }
-
- cras_iodev_free_resources(&aio->base);
- free(aio->pcm_name);
- if (aio->dev_id)
- free(aio->dev_id);
- if (aio->dev_name)
- free(aio->dev_name);
-}
-
-/*
- * Returns true if this is the first internal device.
- */
-static int first_internal_device(struct alsa_io *aio)
-{
- return aio->is_first && aio->card_type == ALSA_CARD_TYPE_INTERNAL;
-}
-
-/*
- * Returns true if there is already a node created with the given name.
- */
-static int has_node(struct alsa_io *aio, const char *name)
-{
- struct cras_ionode *node;
-
- DL_FOREACH (aio->base.nodes, node)
- if (!strcmp(node->name, name))
- return 1;
-
- return 0;
-}
-
-/*
- * Returns true if string s ends with the given suffix.
- */
-int endswith(const char *s, const char *suffix)
-{
- size_t n = strlen(s);
- size_t m = strlen(suffix);
- return n >= m && !strcmp(s + (n - m), suffix);
-}
-
-#ifdef CRAS_DBUS
-/*
- * Drop the node name and replace it with node type.
- */
-static void drop_node_name(struct cras_ionode *node)
-{
- if (node->type == CRAS_NODE_TYPE_USB)
- strcpy(node->name, USB);
- else if (node->type == CRAS_NODE_TYPE_HDMI)
- strcpy(node->name, HDMI);
- else {
- /* Only HDMI or USB node might have invalid name to drop */
- syslog(LOG_ERR,
- "Unexpectedly drop node name for "
- "node: %s, type: %d",
- node->name, node->type);
- strcpy(node->name, DEFAULT);
- }
-}
-#endif
-
-/*
- * Sets the initial plugged state and type of a node based on its
- * name. Chrome will assign priority to nodes base on node type.
- */
-static void set_node_initial_state(struct cras_ionode *node,
- enum CRAS_ALSA_CARD_TYPE card_type)
-{
- unsigned i;
-
- node->volume = 100;
- node->type = CRAS_NODE_TYPE_UNKNOWN;
- /* Go through the known names */
- for (i = 0; i < ARRAY_SIZE(node_defaults); i++)
- if (!strncmp(node->name, node_defaults[i].name,
- strlen(node_defaults[i].name))) {
- node->position = node_defaults[i].position;
- node->plugged =
- (node->position != NODE_POSITION_EXTERNAL);
- node->type = node_defaults[i].type;
- if (node->plugged)
- gettimeofday(&node->plugged_time, NULL);
- break;
- }
-
- /*
- * If we didn't find a matching name above, but the node is a jack node,
- * and there is no "HDMI" in the node name, then this must be a 3.5mm
- * headphone/mic.
- * Set its type and name to headphone/mic. The name is important because
- * it associates the UCM section to the node so the properties like
- * default node gain can be obtained.
- * This matches node names like "DAISY-I2S Mic Jack".
- * If HDMI is in the node name, set its type to HDMI. This matches node names
- * like "Rockchip HDMI Jack".
- */
- if (i == ARRAY_SIZE(node_defaults)) {
- if (endswith(node->name, "Jack") && !strstr(node->name, HDMI)) {
- if (node->dev->direction == CRAS_STREAM_OUTPUT) {
- node->type = CRAS_NODE_TYPE_HEADPHONE;
- strncpy(node->name, HEADPHONE,
- sizeof(node->name) - 1);
- } else {
- node->type = CRAS_NODE_TYPE_MIC;
- strncpy(node->name, MIC,
- sizeof(node->name) - 1);
- }
- }
- if (strstr(node->name, HDMI) &&
- node->dev->direction == CRAS_STREAM_OUTPUT)
- node->type = CRAS_NODE_TYPE_HDMI;
- }
-
- /* Regardless of the node name of a USB headset (it can be "Speaker"),
- * set it's type to usb.
- */
- if (card_type == ALSA_CARD_TYPE_USB) {
- node->type = CRAS_NODE_TYPE_USB;
- node->position = NODE_POSITION_EXTERNAL;
- }
-
-#ifdef CRAS_DBUS
- if (!is_utf8_string(node->name))
- drop_node_name(node);
-#endif
-}
-
-static int get_ucm_flag_integer(struct alsa_io *aio, const char *flag_name,
- int *result)
-{
- char *value;
- int i;
-
- if (!aio->ucm)
- return -1;
-
- value = ucm_get_flag(aio->ucm, flag_name);
- if (!value)
- return -1;
-
- i = atoi(value);
- free(value);
- *result = i;
- return 0;
-}
-
-static int auto_unplug_input_node(struct alsa_io *aio)
-{
- int result;
- if (get_ucm_flag_integer(aio, "AutoUnplugInputNode", &result))
- return 0;
- return result;
-}
-
-static int auto_unplug_output_node(struct alsa_io *aio)
-{
- int result;
- if (get_ucm_flag_integer(aio, "AutoUnplugOutputNode", &result))
- return 0;
- return result;
-}
-
-static int no_create_default_input_node(struct alsa_io *aio)
-{
- int result;
- if (get_ucm_flag_integer(aio, "NoCreateDefaultInputNode", &result))
- return 0;
- return result;
-}
-
-static int no_create_default_output_node(struct alsa_io *aio)
-{
- int result;
- if (get_ucm_flag_integer(aio, "NoCreateDefaultOutputNode", &result))
- return 0;
- return result;
-}
-
-static void
-set_output_node_software_volume_needed(struct alsa_output_node *output,
- struct alsa_io *aio)
-{
- struct cras_alsa_mixer *mixer = aio->mixer;
- long range = 0;
-
- if (aio->ucm && ucm_get_disable_software_volume(aio->ucm)) {
- output->base.software_volume_needed = 0;
- syslog(LOG_DEBUG, "Disable software volume for %s from ucm.",
- output->base.name);
- return;
- }
-
- /* Use software volume for HDMI output and nodes without volume mixer
- * control. */
- if ((output->base.type == CRAS_NODE_TYPE_HDMI) ||
- (!cras_alsa_mixer_has_main_volume(mixer) &&
- !cras_alsa_mixer_has_volume(output->mixer_output)))
- output->base.software_volume_needed = 1;
-
- /* Use software volume if the usb device's volume range is smaller
- * than 40dB */
- if (output->base.type == CRAS_NODE_TYPE_USB) {
- range += cras_alsa_mixer_get_dB_range(mixer);
- range += cras_alsa_mixer_get_output_dB_range(
- output->mixer_output);
- if (range < 4000)
- output->base.software_volume_needed = 1;
- }
- if (output->base.software_volume_needed)
- syslog(LOG_DEBUG, "Use software volume for node: %s",
- output->base.name);
-}
-
-static void set_input_default_node_gain(struct alsa_input_node *input,
- struct alsa_io *aio)
-{
- long gain;
-
- input->base.capture_gain = DEFAULT_CAPTURE_GAIN;
- input->base.ui_gain_scaler = 1.0f;
-
- if (!aio->ucm)
- return;
-
- if (ucm_get_default_node_gain(aio->ucm, input->base.name, &gain) == 0)
- input->base.capture_gain = gain;
-}
-
-static void set_input_node_intrinsic_sensitivity(struct alsa_input_node *input,
- struct alsa_io *aio)
-{
- long sensitivity;
- int rc;
-
- input->base.intrinsic_sensitivity = 0;
-
- if (aio->ucm) {
- rc = ucm_get_intrinsic_sensitivity(aio->ucm, input->base.name,
- &sensitivity);
- if (rc)
- return;
- } else if (input->base.type == CRAS_NODE_TYPE_USB) {
- /*
- * For USB devices without UCM config, trust the default capture gain.
- * Set sensitivity to the default dbfs so the capture gain is 0.
- */
- sensitivity = DEFAULT_CAPTURE_VOLUME_DBFS;
- } else {
- return;
- }
-
- input->base.intrinsic_sensitivity = sensitivity;
- input->base.capture_gain = DEFAULT_CAPTURE_VOLUME_DBFS - sensitivity;
- syslog(LOG_INFO,
- "Use software gain %ld for %s because IntrinsicSensitivity %ld is"
- " specified in UCM",
- input->base.capture_gain, input->base.name, sensitivity);
-}
-
-static void check_auto_unplug_output_node(struct alsa_io *aio,
- struct cras_ionode *node, int plugged)
-{
- struct cras_ionode *tmp;
-
- if (!auto_unplug_output_node(aio))
- return;
-
- /* Auto unplug internal speaker if any output node has been created */
- if (!strcmp(node->name, INTERNAL_SPEAKER) && plugged) {
- DL_FOREACH (aio->base.nodes, tmp)
- if (tmp->plugged && (tmp != node))
- cras_iodev_set_node_plugged(node, 0);
- } else {
- DL_FOREACH (aio->base.nodes, tmp) {
- if (!strcmp(tmp->name, INTERNAL_SPEAKER))
- cras_iodev_set_node_plugged(tmp, !plugged);
- }
- }
-}
-
-/*
- * Callback for listing mixer outputs. The mixer will call this once for each
- * output associated with this device. Most commonly this is used to tell the
- * device it has Headphones and Speakers.
- */
-static struct alsa_output_node *new_output(struct alsa_io *aio,
- struct mixer_control *cras_output,
- const char *name)
-{
- struct alsa_output_node *output;
- syslog(LOG_DEBUG, "New output node for '%s'", name);
- if (aio == NULL) {
- syslog(LOG_ERR, "Invalid aio when listing outputs.");
- return NULL;
- }
- output = (struct alsa_output_node *)calloc(1, sizeof(*output));
- if (output == NULL) {
- syslog(LOG_ERR, "Out of memory when listing outputs.");
- return NULL;
- }
- output->base.dev = &aio->base;
- output->base.idx = aio->next_ionode_index++;
- output->base.stable_id =
- SuperFastHash(name, strlen(name), aio->base.info.stable_id);
- if (aio->ucm)
- output->base.dsp_name =
- ucm_get_dsp_name_for_dev(aio->ucm, name);
-
- if (strcmp(name, "SCO Line Out") == 0)
- output->base.is_sco_pcm = 1;
- output->mixer_output = cras_output;
-
- /* Volume curve. */
- output->volume_curve = cras_card_config_get_volume_curve_for_control(
- aio->config,
- name ? name : cras_alsa_mixer_get_control_name(cras_output));
-
- strncpy(output->base.name, name, sizeof(output->base.name) - 1);
- set_node_initial_state(&output->base, aio->card_type);
- set_output_node_software_volume_needed(output, aio);
-
- cras_iodev_add_node(&aio->base, &output->base);
-
- check_auto_unplug_output_node(aio, &output->base, output->base.plugged);
- return output;
-}
-
-static void new_output_by_mixer_control(struct mixer_control *cras_output,
- void *callback_arg)
-{
- struct alsa_io *aio = (struct alsa_io *)callback_arg;
- char node_name[CRAS_IODEV_NAME_BUFFER_SIZE];
- const char *ctl_name;
-
- ctl_name = cras_alsa_mixer_get_control_name(cras_output);
- if (!ctl_name)
- return;
-
- if (aio->card_type == ALSA_CARD_TYPE_USB) {
- if (snprintf(node_name, sizeof(node_name), "%s: %s",
- aio->base.info.name, ctl_name) > 0) {
- new_output(aio, cras_output, node_name);
- }
- } else {
- new_output(aio, cras_output, ctl_name);
- }
-}
-
-static void check_auto_unplug_input_node(struct alsa_io *aio,
- struct cras_ionode *node, int plugged)
-{
- struct cras_ionode *tmp;
- if (!auto_unplug_input_node(aio))
- return;
-
- /* Auto unplug internal mic if any input node has already
- * been created */
- if (!strcmp(node->name, INTERNAL_MICROPHONE) && plugged) {
- DL_FOREACH (aio->base.nodes, tmp)
- if (tmp->plugged && (tmp != node))
- cras_iodev_set_node_plugged(node, 0);
- } else {
- DL_FOREACH (aio->base.nodes, tmp)
- if (!strcmp(tmp->name, INTERNAL_MICROPHONE))
- cras_iodev_set_node_plugged(tmp, !plugged);
- }
-}
-
-static struct alsa_input_node *new_input(struct alsa_io *aio,
- struct mixer_control *cras_input,
- const char *name)
-{
- struct cras_iodev *iodev = &aio->base;
- struct alsa_input_node *input;
- int err;
-
- input = (struct alsa_input_node *)calloc(1, sizeof(*input));
- if (input == NULL) {
- syslog(LOG_ERR, "Out of memory when listing inputs.");
- return NULL;
- }
- input->base.dev = &aio->base;
- input->base.idx = aio->next_ionode_index++;
- input->base.stable_id =
- SuperFastHash(name, strlen(name), aio->base.info.stable_id);
- if (strcmp(name, "SCO Line In") == 0)
- input->base.is_sco_pcm = 1;
- input->mixer_input = cras_input;
- strncpy(input->base.name, name, sizeof(input->base.name) - 1);
- set_node_initial_state(&input->base, aio->card_type);
- set_input_default_node_gain(input, aio);
- set_input_node_intrinsic_sensitivity(input, aio);
-
- if (aio->ucm) {
- /* Check if channel map is specified in UCM. */
- input->channel_layout = (int8_t *)malloc(
- CRAS_CH_MAX * sizeof(*input->channel_layout));
- err = ucm_get_capture_chmap_for_dev(aio->ucm, name,
- input->channel_layout);
- if (err) {
- free(input->channel_layout);
- input->channel_layout = 0;
- }
- if (ucm_get_preempt_hotword(aio->ucm, name)) {
- iodev->pre_open_iodev_hook =
- cras_iodev_list_suspend_hotword_streams;
- iodev->post_close_iodev_hook =
- cras_iodev_list_resume_hotword_stream;
- }
-
- input->base.dsp_name = ucm_get_dsp_name_for_dev(aio->ucm, name);
- }
-
- cras_iodev_add_node(&aio->base, &input->base);
- check_auto_unplug_input_node(aio, &input->base, input->base.plugged);
- return input;
-}
-
-static void new_input_by_mixer_control(struct mixer_control *cras_input,
- void *callback_arg)
-{
- struct alsa_io *aio = (struct alsa_io *)callback_arg;
- char node_name[CRAS_IODEV_NAME_BUFFER_SIZE];
- const char *ctl_name = cras_alsa_mixer_get_control_name(cras_input);
-
- if (aio->card_type == ALSA_CARD_TYPE_USB) {
- int ret = snprintf(node_name, sizeof(node_name), "%s: %s",
- aio->base.info.name, ctl_name);
- // Truncation is OK, but add a check to make the compiler happy.
- if (ret == sizeof(node_name))
- node_name[sizeof(node_name) - 1] = '\0';
- new_input(aio, cras_input, node_name);
- } else {
- new_input(aio, cras_input, ctl_name);
- }
-}
-
-/*
- * Finds the output node associated with the jack. Returns NULL if not found.
- */
-static struct alsa_output_node *
-get_output_node_from_jack(struct alsa_io *aio,
- const struct cras_alsa_jack *jack)
-{
- struct mixer_control *mixer_output;
- struct cras_ionode *node = NULL;
- struct alsa_output_node *aout = NULL;
-
- /* Search by jack first. */
- DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, aout, jack, jack);
- if (aout)
- return aout;
-
- /* Search by mixer control next. */
- mixer_output = cras_alsa_jack_get_mixer_output(jack);
- if (mixer_output == NULL)
- return NULL;
-
- DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, aout, mixer_output,
- mixer_output);
- return aout;
-}
-
-static struct alsa_input_node *
-get_input_node_from_jack(struct alsa_io *aio, const struct cras_alsa_jack *jack)
-{
- struct mixer_control *mixer_input;
- struct cras_ionode *node = NULL;
- struct alsa_input_node *ain = NULL;
-
- mixer_input = cras_alsa_jack_get_mixer_input(jack);
- if (mixer_input == NULL) {
- DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, ain, jack,
- jack);
- return ain;
- }
-
- DL_SEARCH_SCALAR_WITH_CAST(aio->base.nodes, node, ain, mixer_input,
- mixer_input);
- return ain;
-}
-
-static const struct cras_alsa_jack *get_jack_from_node(struct cras_ionode *node)
-{
- const struct cras_alsa_jack *jack = NULL;
-
- if (node == NULL)
- return NULL;
-
- if (node->dev->direction == CRAS_STREAM_OUTPUT)
- jack = ((struct alsa_output_node *)node)->jack;
- else if (node->dev->direction == CRAS_STREAM_INPUT)
- jack = ((struct alsa_input_node *)node)->jack;
-
- return jack;
-}
-
-/*
- * Returns the dsp name specified in the ucm config. If there is a dsp name
- * specified for the active node, use that. Otherwise NULL should be returned.
- */
-static const char *get_active_dsp_name(struct alsa_io *aio)
-{
- struct cras_ionode *node = aio->base.active_node;
-
- if (node == NULL)
- return NULL;
-
- return node->dsp_name;
-}
-
-/*
- * Creates volume curve for the node associated with given jack.
- */
-static struct cras_volume_curve *
-create_volume_curve_for_jack(const struct cras_card_config *config,
- const struct cras_alsa_jack *jack)
-{
- struct cras_volume_curve *curve;
- const char *name;
-
- /* Use jack's UCM device name as key to get volume curve. */
- name = cras_alsa_jack_get_ucm_device(jack);
- curve = cras_card_config_get_volume_curve_for_control(config, name);
- if (curve)
- return curve;
-
- /* Use alsa jack's name as key to get volume curve. */
- name = cras_alsa_jack_get_name(jack);
- curve = cras_card_config_get_volume_curve_for_control(config, name);
- if (curve)
- return curve;
-
- return NULL;
-}
-
-/*
- * Updates max_supported_channels value into cras_iodev_info.
- * Note that supported_rates, supported_channel_counts, and supported_formats of
- * iodev will be updated to the latest values after calling.
- */
-static void update_max_supported_channels(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- unsigned int max_channels = 0;
- size_t i;
- bool active_node_predicted = false;
- int rc;
-
- /*
- * max_supported_channels might be wrong in dependent PCM cases. Always
- * return 2 for such cases.
- */
- if (aio->has_dependent_dev) {
- max_channels = 2;
- goto update_info;
- }
-
- if (aio->handle) {
- syslog(LOG_ERR,
- "update_max_supported_channels should not be called "
- "while device is opened.");
- return;
- }
-
- /*
- * In the case of updating max_supported_channels on changing jack
- * plugging status of devices, the active node may not be determined
- * yet. Use the first node as the active node for obtaining the value of
- * max_supported_channels.
- */
- if (!iodev->active_node) {
- if (!iodev->nodes)
- goto update_info;
- iodev->active_node = iodev->nodes;
- syslog(LOG_DEBUG,
- "Predict ionode %s as active node temporarily.",
- iodev->active_node->name);
- active_node_predicted = true;
- }
-
- rc = open_dev(iodev);
- if (active_node_predicted)
- iodev->active_node = NULL; // Reset the predicted active_node.
- if (rc)
- goto update_info;
-
- rc = update_supported_formats(iodev);
- if (rc)
- goto close_iodev;
-
- for (i = 0; iodev->supported_channel_counts[i] != 0; i++) {
- if (iodev->supported_channel_counts[i] > max_channels)
- max_channels = iodev->supported_channel_counts[i];
- }
-
-close_iodev:
- close_dev(iodev);
-
-update_info:
- iodev->info.max_supported_channels = max_channels;
-}
-
-/*
- * Callback that is called when an output jack is plugged or unplugged.
- */
-static void jack_output_plug_event(const struct cras_alsa_jack *jack,
- int plugged, void *arg)
-{
- struct alsa_io *aio;
- struct alsa_output_node *node;
- const char *jack_name;
-
- if (arg == NULL)
- return;
-
- aio = (struct alsa_io *)arg;
- node = get_output_node_from_jack(aio, jack);
- jack_name = cras_alsa_jack_get_name(jack);
- if (!strcmp(jack_name, "Speaker Phantom Jack"))
- jack_name = INTERNAL_SPEAKER;
-
- /* If there isn't a node for this jack, create one. */
- if (node == NULL) {
- if (aio->fully_specified) {
- /* When fully specified, can't have new nodes. */
- syslog(LOG_ERR, "No matching output node for jack %s!",
- jack_name);
- return;
- }
- node = new_output(aio, NULL, jack_name);
- if (node == NULL)
- return;
-
- cras_alsa_jack_update_node_type(jack, &(node->base.type));
- }
-
- if (!node->jack) {
- if (aio->fully_specified)
- syslog(LOG_ERR,
- "Jack '%s' was found to match output node '%s'."
- " Please fix your UCM configuration to match.",
- jack_name, node->base.name);
-
- /* If we already have the node, associate with the jack. */
- node->jack = jack;
- if (node->volume_curve == NULL)
- node->volume_curve =
- create_volume_curve_for_jack(aio->config, jack);
- }
-
- syslog(LOG_DEBUG, "%s plugged: %d, %s", jack_name, plugged,
- cras_alsa_mixer_get_control_name(node->mixer_output));
-
- cras_alsa_jack_update_monitor_name(jack, node->base.name,
- sizeof(node->base.name));
-
-#ifdef CRAS_DBUS
- /* The name got from jack might be an invalid UTF8 string. */
- if (!is_utf8_string(node->base.name))
- drop_node_name(&node->base);
-#endif
-
- cras_iodev_set_node_plugged(&node->base, plugged);
-
- check_auto_unplug_output_node(aio, &node->base, plugged);
-
- /*
- * For HDMI plug event cases, update max supported channels according
- * to the current active node.
- */
- if (node->base.type == CRAS_NODE_TYPE_HDMI && plugged)
- update_max_supported_channels(&aio->base);
-}
-
-/*
- * Callback that is called when an input jack is plugged or unplugged.
- */
-static void jack_input_plug_event(const struct cras_alsa_jack *jack,
- int plugged, void *arg)
-{
- struct alsa_io *aio;
- struct alsa_input_node *node;
- struct mixer_control *cras_input;
- const char *jack_name;
-
- if (arg == NULL)
- return;
- aio = (struct alsa_io *)arg;
- node = get_input_node_from_jack(aio, jack);
- jack_name = cras_alsa_jack_get_name(jack);
-
- /* If there isn't a node for this jack, create one. */
- if (node == NULL) {
- if (aio->fully_specified) {
- /* When fully specified, can't have new nodes. */
- syslog(LOG_ERR, "No matching input node for jack %s!",
- jack_name);
- return;
- }
- cras_input = cras_alsa_jack_get_mixer_input(jack);
- node = new_input(aio, cras_input, jack_name);
- if (node == NULL)
- return;
- }
-
- syslog(LOG_DEBUG, "%s plugged: %d, %s", jack_name, plugged,
- cras_alsa_mixer_get_control_name(node->mixer_input));
-
- /* If we already have the node, associate with the jack. */
- if (!node->jack) {
- if (aio->fully_specified)
- syslog(LOG_ERR,
- "Jack '%s' was found to match input node '%s'."
- " Please fix your UCM configuration to match.",
- jack_name, node->base.name);
- node->jack = jack;
- }
-
- cras_iodev_set_node_plugged(&node->base, plugged);
-
- check_auto_unplug_input_node(aio, &node->base, plugged);
-}
-
-/*
- * Sets the name of the given iodev, using the name and index of the card
- * combined with the device index and direction.
- */
-static void set_iodev_name(struct cras_iodev *dev, const char *card_name,
- const char *dev_name, size_t card_index,
- size_t device_index,
- enum CRAS_ALSA_CARD_TYPE card_type, size_t usb_vid,
- size_t usb_pid, char *usb_serial_number)
-{
- snprintf(dev->info.name, sizeof(dev->info.name), "%s: %s:%zu,%zu",
- card_name, dev_name, card_index, device_index);
- dev->info.name[ARRAY_SIZE(dev->info.name) - 1] = '\0';
- syslog(LOG_DEBUG, "Add device name=%s", dev->info.name);
-
- dev->info.stable_id =
- SuperFastHash(card_name, strlen(card_name), strlen(card_name));
- dev->info.stable_id =
- SuperFastHash(dev_name, strlen(dev_name), dev->info.stable_id);
-
- switch (card_type) {
- case ALSA_CARD_TYPE_INTERNAL:
- dev->info.stable_id = SuperFastHash((const char *)&device_index,
- sizeof(device_index),
- dev->info.stable_id);
- break;
- case ALSA_CARD_TYPE_USB:
- dev->info.stable_id =
- SuperFastHash((const char *)&usb_vid, sizeof(usb_vid),
- dev->info.stable_id);
- dev->info.stable_id =
- SuperFastHash((const char *)&usb_pid, sizeof(usb_pid),
- dev->info.stable_id);
- dev->info.stable_id = SuperFastHash(usb_serial_number,
- strlen(usb_serial_number),
- dev->info.stable_id);
- break;
- default:
- break;
- }
- syslog(LOG_DEBUG, "Stable ID=%08x", dev->info.stable_id);
-}
-
-static int get_fixed_rate(struct alsa_io *aio)
-{
- const char *name;
-
- if (aio->base.direction == CRAS_STREAM_OUTPUT) {
- struct alsa_output_node *active = get_active_output(aio);
- if (!active)
- return -ENOENT;
- name = active->base.name;
- } else {
- struct alsa_input_node *active = get_active_input(aio);
- if (!active)
- return -ENOENT;
- name = active->base.name;
- }
-
- return ucm_get_sample_rate_for_dev(aio->ucm, name, aio->base.direction);
-}
-
-static size_t get_fixed_channels(struct alsa_io *aio)
-{
- const char *name;
- int rc;
- size_t channels;
-
- if (aio->base.direction == CRAS_STREAM_OUTPUT) {
- struct alsa_output_node *active = get_active_output(aio);
- if (!active)
- return -ENOENT;
- name = active->base.name;
- } else {
- struct alsa_input_node *active = get_active_input(aio);
- if (!active)
- return -ENOENT;
- name = active->base.name;
- }
-
- rc = ucm_get_channels_for_dev(aio->ucm, name, aio->base.direction,
- &channels);
- return (rc) ? 0 : channels;
-}
-
-/*
- * Updates the supported sample rates and channel counts.
- */
-static int update_supported_formats(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int err;
- int fixed_rate;
- size_t fixed_channels;
-
- free(iodev->supported_rates);
- iodev->supported_rates = NULL;
- free(iodev->supported_channel_counts);
- iodev->supported_channel_counts = NULL;
- free(iodev->supported_formats);
- iodev->supported_formats = NULL;
-
- err = cras_alsa_fill_properties(aio->handle, &iodev->supported_rates,
- &iodev->supported_channel_counts,
- &iodev->supported_formats);
- if (err)
- return err;
-
- if (aio->ucm) {
- /* Allow UCM to override supplied rates. */
- fixed_rate = get_fixed_rate(aio);
- if (fixed_rate > 0) {
- free(iodev->supported_rates);
- iodev->supported_rates = (size_t *)malloc(
- 2 * sizeof(iodev->supported_rates[0]));
- iodev->supported_rates[0] = fixed_rate;
- iodev->supported_rates[1] = 0;
- }
-
- /* Allow UCM to override supported channel counts. */
- fixed_channels = get_fixed_channels(aio);
- if (fixed_channels > 0) {
- free(iodev->supported_channel_counts);
- iodev->supported_channel_counts = (size_t *)malloc(
- 2 * sizeof(iodev->supported_channel_counts[0]));
- iodev->supported_channel_counts[0] = fixed_channels;
- iodev->supported_channel_counts[1] = 0;
- }
- }
- return 0;
-}
-
-/*
- * Builds software volume scalers for output nodes in the device.
- */
-static void build_softvol_scalers(struct alsa_io *aio)
-{
- struct cras_ionode *ionode;
-
- DL_FOREACH (aio->base.nodes, ionode) {
- struct alsa_output_node *aout;
- const struct cras_volume_curve *curve;
-
- aout = (struct alsa_output_node *)ionode;
- curve = get_curve_for_output_node(aio, aout);
-
- ionode->softvol_scalers = softvol_build_from_curve(curve);
- }
-}
-
-static void enable_active_ucm(struct alsa_io *aio, int plugged)
-{
- const struct cras_alsa_jack *jack;
- const char *name;
-
- if (aio->base.direction == CRAS_STREAM_OUTPUT) {
- struct alsa_output_node *active = get_active_output(aio);
- if (!active)
- return;
- name = active->base.name;
- jack = active->jack;
- } else {
- struct alsa_input_node *active = get_active_input(aio);
- if (!active)
- return;
- name = active->base.name;
- jack = active->jack;
- }
-
- if (jack)
- cras_alsa_jack_enable_ucm(jack, plugged);
- else if (aio->ucm)
- ucm_set_enabled(aio->ucm, name, plugged);
-}
-
-static int fill_whole_buffer_with_zeros(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int rc;
- uint8_t *dst = NULL;
- size_t format_bytes;
-
- /* Fill whole buffer with zeros. */
- rc = cras_alsa_mmap_get_whole_buffer(aio->handle, &dst);
-
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to get whole buffer: %s",
- snd_strerror(rc));
- return rc;
- }
-
- format_bytes = cras_get_format_bytes(iodev->format);
- memset(dst, 0, iodev->buffer_size * format_bytes);
-
- return 0;
-}
-
-/*
- * Move appl_ptr to min_buffer_level + min_cb_level frames ahead of hw_ptr
- * when resuming from free run.
- */
-static int adjust_appl_ptr_for_leaving_free_run(struct cras_iodev *odev)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
- snd_pcm_uframes_t ahead;
-
- ahead = odev->min_buffer_level + odev->min_cb_level;
- return cras_alsa_resume_appl_ptr(aio->handle, ahead);
-}
-
-/*
- * Move appl_ptr to min_buffer_level + min_cb_level * 1.5 frames ahead of
- * hw_ptr when adjusting appl_ptr from underrun.
- */
-static int adjust_appl_ptr_for_underrun(struct cras_iodev *odev)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
- snd_pcm_uframes_t ahead;
-
- ahead = odev->min_buffer_level + odev->min_cb_level +
- odev->min_cb_level / 2;
- return cras_alsa_resume_appl_ptr(aio->handle, ahead);
-}
-
-/* This function is for leaving no-stream state but still not in free run yet.
- * The device may have valid samples remaining. We need to adjust appl_ptr to
- * the correct position, which is MAX(min_cb_level + min_buffer_level,
- * valid_sample) */
-static int adjust_appl_ptr_samples_remaining(struct cras_iodev *odev)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
- int rc;
- unsigned int real_hw_level, valid_sample, offset;
- struct timespec hw_tstamp;
-
- /* Get the amount of valid samples which haven't been played yet.
- * The real_hw_level is the real hw_level in device buffer. It doesn't
- * subtract min_buffer_level. */
- valid_sample = 0;
- rc = odev->frames_queued(odev, &hw_tstamp);
- if (rc < 0)
- return rc;
- real_hw_level = rc;
-
- /*
- * If underrun happened, handle it. Because alsa_output_underrun function
- * has already called adjust_appl_ptr, we don't need to call it again.
- */
- if (real_hw_level <= odev->min_buffer_level)
- return cras_iodev_output_underrun(odev, real_hw_level, 0);
-
- if (real_hw_level > aio->filled_zeros_for_draining)
- valid_sample = real_hw_level - aio->filled_zeros_for_draining;
-
- offset = MAX(odev->min_buffer_level + odev->min_cb_level, valid_sample);
-
- /* Fill zeros to make sure there are enough zero samples in device buffer.*/
- if (offset > real_hw_level) {
- rc = cras_iodev_fill_odev_zeros(odev, offset - real_hw_level);
- if (rc)
- return rc;
- }
- return cras_alsa_resume_appl_ptr(aio->handle, offset);
-}
-
-static int alsa_output_underrun(struct cras_iodev *odev)
-{
- int rc;
-
- /* Fill whole buffer with zeros. This avoids samples left in buffer causing
- * noise when device plays them. */
- rc = fill_whole_buffer_with_zeros(odev);
- if (rc)
- return rc;
- /* Adjust appl_ptr to leave underrun. */
- return adjust_appl_ptr_for_underrun(odev);
-}
-
-static int possibly_enter_free_run(struct cras_iodev *odev)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
- int rc;
- unsigned int real_hw_level, fr_to_write;
- struct timespec hw_tstamp;
-
- if (aio->free_running)
- return 0;
-
- /* Check if all valid samples are played. If all valid samples are played,
- * fill whole buffer with zeros. The real_hw_level is the real hw_level in
- * device buffer. It doesn't subtract min_buffer_level.*/
- rc = odev->frames_queued(odev, &hw_tstamp);
- if (rc < 0)
- return rc;
- real_hw_level = rc;
-
- /* If underrun happened, handle it and enter free run state. */
- if (real_hw_level <= odev->min_buffer_level) {
- rc = cras_iodev_output_underrun(odev, real_hw_level, 0);
- if (rc < 0)
- return rc;
- aio->free_running = 1;
- return 0;
- }
-
- if (real_hw_level <= aio->filled_zeros_for_draining ||
- real_hw_level == 0) {
- rc = fill_whole_buffer_with_zeros(odev);
- if (rc < 0)
- return rc;
- aio->free_running = 1;
- return 0;
- }
-
- /* Fill zeros to drain valid samples. */
- fr_to_write = MIN(cras_time_to_frames(&no_stream_fill_zeros_duration,
- odev->format->frame_rate),
- odev->buffer_size - real_hw_level);
- rc = cras_iodev_fill_odev_zeros(odev, fr_to_write);
- if (rc)
- return rc;
- aio->filled_zeros_for_draining += fr_to_write;
-
- return 0;
-}
-
-static int leave_free_run(struct cras_iodev *odev)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
- int rc;
-
- /* Restart rate estimation because free run internval should not
- * be included. */
- cras_iodev_reset_rate_estimator(odev);
-
- if (aio->free_running)
- rc = adjust_appl_ptr_for_leaving_free_run(odev);
- else
- rc = adjust_appl_ptr_samples_remaining(odev);
- if (rc) {
- syslog(LOG_ERR, "device %s failed to leave free run, rc = %d",
- odev->info.name, rc);
- return rc;
- }
- aio->free_running = 0;
- aio->filled_zeros_for_draining = 0;
-
- return 0;
-}
-
-/*
- * Free run state is the optimization of no_stream playback on alsa_io.
- * The whole buffer will be filled with zeros. Device can play these zeros
- * indefinitely. When there is new meaningful sample, appl_ptr should be
- * resumed to some distance ahead of hw_ptr.
- */
-static int no_stream(struct cras_iodev *odev, int enable)
-{
- if (enable)
- return possibly_enter_free_run(odev);
- else
- return leave_free_run(odev);
-}
-
-static int is_free_running(const struct cras_iodev *odev)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
-
- return aio->free_running;
-}
-
-static unsigned int get_num_severe_underruns(const struct cras_iodev *iodev)
-{
- const struct alsa_io *aio = (const struct alsa_io *)iodev;
- return aio->num_severe_underruns;
-}
-
-static void set_default_hotword_model(struct cras_iodev *iodev)
-{
- const char *default_models[] = { "en_all", "en_us" };
- cras_node_id_t node_id;
- unsigned i;
-
- if (!iodev->active_node ||
- iodev->active_node->type != CRAS_NODE_TYPE_HOTWORD)
- return;
-
- node_id = cras_make_node_id(iodev->info.idx, iodev->active_node->idx);
- /* This is a no-op if the default_model is not supported */
- for (i = 0; i < ARRAY_SIZE(default_models); ++i)
- if (!cras_iodev_list_set_hotword_model(node_id,
- default_models[i]))
- return;
-}
-
-static int get_valid_frames(struct cras_iodev *odev, struct timespec *tstamp)
-{
- struct alsa_io *aio = (struct alsa_io *)odev;
- int rc;
- unsigned int real_hw_level;
-
- /*
- * Get the amount of valid frames which haven't been played yet.
- * The real_hw_level is the real hw_level in device buffer. It doesn't
- * subtract min_buffer_level.
- */
- if (aio->free_running) {
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return 0;
- }
-
- rc = odev->frames_queued(odev, tstamp);
- if (rc < 0)
- return rc;
- real_hw_level = rc;
-
- if (real_hw_level > aio->filled_zeros_for_draining)
- return real_hw_level - aio->filled_zeros_for_draining;
-
- return 0;
-}
-
-static int support_noise_cancellation(const struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
-
- if (!aio->ucm || !iodev->active_node)
- return 0;
-
- return ucm_node_noise_cancellation_exists(aio->ucm,
- iodev->active_node->name);
-}
-
-/*
- * Exported Interface.
- */
-
-struct cras_iodev *
-alsa_iodev_create(size_t card_index, const char *card_name, size_t device_index,
- const char *pcm_name, const char *dev_name,
- const char *dev_id, enum CRAS_ALSA_CARD_TYPE card_type,
- int is_first, struct cras_alsa_mixer *mixer,
- const struct cras_card_config *config,
- struct cras_use_case_mgr *ucm, snd_hctl_t *hctl,
- enum CRAS_STREAM_DIRECTION direction, size_t usb_vid,
- size_t usb_pid, char *usb_serial_number)
-{
- struct alsa_io *aio;
- struct cras_iodev *iodev;
-
- if (direction != CRAS_STREAM_INPUT && direction != CRAS_STREAM_OUTPUT)
- return NULL;
-
- aio = (struct alsa_io *)calloc(1, sizeof(*aio));
- if (!aio)
- return NULL;
- iodev = &aio->base;
- iodev->direction = direction;
-
- aio->device_index = device_index;
- aio->card_type = card_type;
- aio->is_first = is_first;
- aio->handle = NULL;
- aio->num_severe_underruns = 0;
- if (dev_name) {
- aio->dev_name = strdup(dev_name);
- if (!aio->dev_name)
- goto cleanup_iodev;
- }
- if (dev_id) {
- aio->dev_id = strdup(dev_id);
- if (!aio->dev_id)
- goto cleanup_iodev;
- }
- aio->free_running = 0;
- aio->filled_zeros_for_draining = 0;
- aio->has_dependent_dev = 0;
- aio->pcm_name = strdup(pcm_name);
- if (aio->pcm_name == NULL)
- goto cleanup_iodev;
-
- if (direction == CRAS_STREAM_INPUT) {
- aio->alsa_stream = SND_PCM_STREAM_CAPTURE;
- aio->base.set_capture_gain = set_alsa_capture_gain;
- aio->base.set_capture_mute = set_alsa_capture_gain;
- } else {
- aio->alsa_stream = SND_PCM_STREAM_PLAYBACK;
- aio->base.set_volume = set_alsa_volume;
- aio->base.set_mute = set_alsa_mute;
- aio->base.output_underrun = alsa_output_underrun;
- }
- iodev->open_dev = open_dev;
- iodev->configure_dev = configure_dev;
- iodev->close_dev = close_dev;
- iodev->update_supported_formats = update_supported_formats;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->flush_buffer = flush_buffer;
- iodev->start = start;
- iodev->update_active_node = update_active_node;
- iodev->update_channel_layout = update_channel_layout;
- iodev->set_hotword_model = set_hotword_model;
- iodev->get_hotword_models = get_hotword_models;
- iodev->no_stream = no_stream;
- iodev->is_free_running = is_free_running;
- iodev->get_num_severe_underruns = get_num_severe_underruns;
- iodev->get_valid_frames = get_valid_frames;
- iodev->set_swap_mode_for_node = cras_iodev_dsp_set_swap_mode_for_node;
- iodev->support_noise_cancellation = support_noise_cancellation;
-
- if (card_type == ALSA_CARD_TYPE_USB)
- iodev->min_buffer_level = USB_EXTRA_BUFFER_FRAMES;
-
- iodev->ramp = cras_ramp_create();
- if (iodev->ramp == NULL)
- goto cleanup_iodev;
- iodev->initial_ramp_request = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
-
- aio->mixer = mixer;
- aio->config = config;
- if (direction == CRAS_STREAM_OUTPUT) {
- aio->default_volume_curve =
- cras_card_config_get_volume_curve_for_control(
- config, "Default");
- if (aio->default_volume_curve == NULL)
- aio->default_volume_curve =
- cras_volume_curve_create_default();
- }
- aio->ucm = ucm;
- if (ucm) {
- unsigned int level;
- int rc;
-
- /* Set callback for swap mode if it is supported
- * in ucm modifier. */
- if (ucm_swap_mode_exists(ucm))
- aio->base.set_swap_mode_for_node =
- set_alsa_node_swapped;
-
- rc = ucm_get_min_buffer_level(ucm, &level);
- if (!rc && direction == CRAS_STREAM_OUTPUT)
- iodev->min_buffer_level = level;
- }
-
- set_iodev_name(iodev, card_name, dev_name, card_index, device_index,
- card_type, usb_vid, usb_pid, usb_serial_number);
-
- aio->jack_list = cras_alsa_jack_list_create(
- card_index, card_name, device_index, is_first, mixer, ucm, hctl,
- direction,
- direction == CRAS_STREAM_OUTPUT ? jack_output_plug_event :
- jack_input_plug_event,
- aio);
- if (!aio->jack_list)
- goto cleanup_iodev;
-
- /* HDMI outputs don't have volume adjustment, do it in software. */
- if (direction == CRAS_STREAM_OUTPUT && strstr(dev_name, HDMI))
- iodev->software_volume_needed = 1;
-
- /* Add this now so that cleanup of the iodev (in case of error or card
- * card removal will function as expected. */
- if (direction == CRAS_STREAM_OUTPUT)
- cras_iodev_list_add_output(&aio->base);
- else
- cras_iodev_list_add_input(&aio->base);
- return &aio->base;
-
-cleanup_iodev:
- free_alsa_iodev_resources(aio);
- free(aio);
- return NULL;
-}
-
-int alsa_iodev_legacy_complete_init(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- const char *dev_name;
- const char *dev_id;
- enum CRAS_STREAM_DIRECTION direction;
- int err;
- int is_first;
- struct cras_alsa_mixer *mixer;
-
- if (!aio)
- return -EINVAL;
- direction = iodev->direction;
- dev_name = aio->dev_name;
- dev_id = aio->dev_id;
- is_first = aio->is_first;
- mixer = aio->mixer;
-
- /* Create output nodes for mixer controls, such as Headphone
- * and Speaker, only for the first device. */
- if (direction == CRAS_STREAM_OUTPUT && is_first)
- cras_alsa_mixer_list_outputs(mixer, new_output_by_mixer_control,
- aio);
- else if (direction == CRAS_STREAM_INPUT && is_first)
- cras_alsa_mixer_list_inputs(mixer, new_input_by_mixer_control,
- aio);
-
- err = cras_alsa_jack_list_find_jacks_by_name_matching(aio->jack_list);
- if (err)
- return err;
-
- /* Create nodes for jacks that aren't associated with an
- * already existing node. Get an initial read of the jacks for
- * this device. */
- cras_alsa_jack_list_report(aio->jack_list);
-
- /* Make a default node if there is still no node for this
- * device, or we still don't have the "Speaker"/"Internal Mic"
- * node for the first internal device. Note that the default
- * node creation can be supressed by UCM flags for platforms
- * which really don't have an internal device. */
- if ((direction == CRAS_STREAM_OUTPUT) &&
- !no_create_default_output_node(aio)) {
- if (first_internal_device(aio) &&
- !has_node(aio, INTERNAL_SPEAKER) && !has_node(aio, HDMI)) {
- if (strstr(aio->base.info.name, HDMI))
- new_output(aio, NULL, HDMI);
- else
- new_output(aio, NULL, INTERNAL_SPEAKER);
- } else if (!aio->base.nodes) {
- new_output(aio, NULL, DEFAULT);
- }
- } else if ((direction == CRAS_STREAM_INPUT) &&
- !no_create_default_input_node(aio)) {
- if (first_internal_device(aio) &&
- !has_node(aio, INTERNAL_MICROPHONE))
- new_input(aio, NULL, INTERNAL_MICROPHONE);
- else if (strstr(dev_name, KEYBOARD_MIC))
- new_input(aio, NULL, KEYBOARD_MIC);
- else if (dev_id && strstr(dev_id, HOTWORD_DEV))
- new_input(aio, NULL, HOTWORD_DEV);
- else if (!aio->base.nodes)
- new_input(aio, NULL, DEFAULT);
- }
-
- /* Build software volume scalers. */
- if (direction == CRAS_STREAM_OUTPUT)
- build_softvol_scalers(aio);
-
- /* Set the active node as the best node we have now. */
- alsa_iodev_set_active_node(&aio->base, first_plugged_node(&aio->base),
- 0);
-
- /* Set plugged for the first USB device per card when it appears if
- * there is no jack reporting plug status. */
- if (aio->card_type == ALSA_CARD_TYPE_USB && is_first &&
- !get_jack_from_node(iodev->active_node))
- cras_iodev_set_node_plugged(iodev->active_node, 1);
-
- set_default_hotword_model(iodev);
-
- /* Record max supported channels into cras_iodev_info. */
- update_max_supported_channels(iodev);
-
- return 0;
-}
-
-int alsa_iodev_ucm_add_nodes_and_jacks(struct cras_iodev *iodev,
- struct ucm_section *section)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- struct mixer_control *control;
- struct alsa_input_node *input_node = NULL;
- struct cras_alsa_jack *jack;
- struct alsa_output_node *output_node = NULL;
- int rc;
-
- if (!aio || !section)
- return -EINVAL;
-
- /* Allow this section to add as a new node only if the device id
- * or dependent device id matches this iodev. */
- if (((uint32_t)section->dev_idx != aio->device_index) &&
- ((uint32_t)section->dependent_dev_idx != aio->device_index))
- return -EINVAL;
-
- /* Set flag has_dependent_dev for the case of dependent device. */
- if (section->dependent_dev_idx != -1)
- aio->has_dependent_dev = 1;
-
- /* This iodev is fully specified. Avoid automatic node creation. */
- aio->fully_specified = 1;
-
- /* Check here in case the DmaPeriodMicrosecs flag has only been
- * specified on one of many device entries with the same PCM. */
- if (!aio->dma_period_set_microsecs)
- aio->dma_period_set_microsecs =
- ucm_get_dma_period_for_dev(aio->ucm, section->name);
-
- /* Create a node matching this section. If there is a matching
- * control use that, otherwise make a node without a control. */
- control = cras_alsa_mixer_get_control_for_section(aio->mixer, section);
- if (iodev->direction == CRAS_STREAM_OUTPUT) {
- output_node = new_output(aio, control, section->name);
- if (!output_node)
- return -ENOMEM;
- output_node->pcm_name = strdup(section->pcm_name);
- } else if (iodev->direction == CRAS_STREAM_INPUT) {
- input_node = new_input(aio, control, section->name);
- if (!input_node)
- return -ENOMEM;
- input_node->pcm_name = strdup(section->pcm_name);
- }
-
- /* Find any jack controls for this device. */
- rc = cras_alsa_jack_list_add_jack_for_section(aio->jack_list, section,
- &jack);
- if (rc)
- return rc;
-
- /* Associated the jack with the node. */
- if (jack) {
- if (output_node) {
- output_node->jack = jack;
- if (!output_node->volume_curve)
- output_node->volume_curve =
- create_volume_curve_for_jack(
- aio->config, jack);
- } else if (input_node) {
- input_node->jack = jack;
- }
- }
- return 0;
-}
-
-void alsa_iodev_ucm_complete_init(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- struct cras_ionode *node;
-
- if (!iodev)
- return;
-
- /* Get an initial read of the jacks for this device. */
- cras_alsa_jack_list_report(aio->jack_list);
-
- /* Build software volume scaler. */
- if (iodev->direction == CRAS_STREAM_OUTPUT)
- build_softvol_scalers(aio);
-
- /* Set the active node as the best node we have now. */
- alsa_iodev_set_active_node(&aio->base, first_plugged_node(&aio->base),
- 0);
-
- /*
- * Set plugged for the USB device per card when it appears if
- * there is no jack reporting plug status
- */
- if (aio->card_type == ALSA_CARD_TYPE_USB) {
- DL_FOREACH (iodev->nodes, node) {
- if (!get_jack_from_node(node))
- cras_iodev_set_node_plugged(node, 1);
- }
- }
-
- set_default_hotword_model(iodev);
-
- node = iodev->active_node;
-
- /* Record max supported channels into cras_iodev_info. */
- if (node && node->plugged)
- update_max_supported_channels(iodev);
-}
-
-void alsa_iodev_destroy(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int rc;
-
- if (iodev->direction == CRAS_STREAM_INPUT)
- rc = cras_iodev_list_rm_input(iodev);
- else
- rc = cras_iodev_list_rm_output(iodev);
-
- if (rc == -EBUSY) {
- syslog(LOG_ERR, "Failed to remove iodev %s", iodev->info.name);
- return;
- }
-
- /* Free resources when device successfully removed. */
- cras_alsa_jack_list_destroy(aio->jack_list);
- free_alsa_iodev_resources(aio);
- cras_volume_curve_destroy(aio->default_volume_curve);
- free(iodev);
-}
-
-unsigned alsa_iodev_index(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- return aio->device_index;
-}
-
-int alsa_iodev_has_hctl_jacks(struct cras_iodev *iodev)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- return cras_alsa_jack_list_has_hctl_jacks(aio->jack_list);
-}
-
-static void alsa_iodev_unmute_node(struct alsa_io *aio,
- struct cras_ionode *ionode)
-{
- struct alsa_output_node *active = (struct alsa_output_node *)ionode;
- struct mixer_control *mixer = active->mixer_output;
- struct alsa_output_node *output;
- struct cras_ionode *node;
-
- /* If this node is associated with mixer output, unmute the
- * active mixer output and mute all others, otherwise just set
- * the node as active and set the volume curve. */
- if (mixer) {
- /* Unmute the active mixer output, mute all others. */
- DL_FOREACH (aio->base.nodes, node) {
- output = (struct alsa_output_node *)node;
- if (output->mixer_output)
- cras_alsa_mixer_set_output_active_state(
- output->mixer_output, node == ionode);
- }
- }
-}
-
-static int alsa_iodev_set_active_node(struct cras_iodev *iodev,
- struct cras_ionode *ionode,
- unsigned dev_enabled)
-{
- struct alsa_io *aio = (struct alsa_io *)iodev;
- int rc = 0;
-
- if (iodev->active_node == ionode)
- goto skip;
-
- /* Disable jack ucm before switching node. */
- enable_active_ucm(aio, 0);
- if (dev_enabled && (iodev->direction == CRAS_STREAM_OUTPUT))
- alsa_iodev_unmute_node(aio, ionode);
-
- cras_iodev_set_active_node(iodev, ionode);
- aio->base.dsp_name = get_active_dsp_name(aio);
- cras_iodev_update_dsp(iodev);
-skip:
- enable_active_ucm(aio, dev_enabled);
- if (ionode->type == CRAS_NODE_TYPE_HOTWORD) {
- if (dev_enabled) {
- rc = ucm_enable_hotword_model(aio->ucm);
- if (rc < 0)
- return rc;
- } else
- ucm_disable_all_hotword_models(aio->ucm);
- }
- /* Setting the volume will also unmute if the system isn't muted. */
- init_device_settings(aio);
- return 0;
-}
diff --git a/cras/src/server/cras_alsa_io.h b/cras/src/server/cras_alsa_io.h
deleted file mode 100644
index f8e613d0..00000000
--- a/cras/src/server/cras_alsa_io.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_ALSA_IO_H_
-#define CRAS_ALSA_IO_H_
-
-#include <alsa/asoundlib.h>
-
-#include "cras_card_config.h"
-#include "cras_types.h"
-
-struct cras_alsa_mixer;
-struct cras_ionode;
-struct cras_use_case_mgr;
-struct ucm_section;
-
-/* Initializes an alsa iodev.
- * Args:
- * card_index - 0 based index, value of "XX" in "hw:XX,YY".
- * card_name - The name of the card.
- * device_index - 0 based index, value of "YY" in "hw:XX,YY".
- * pcm_name - The pcm name passing to snd_pcm_open(), e.g hw:0,0
- * dev_name - The name of the device.
- * dev_id - The id string of the device.
- * card_type - the type of the card this iodev belongs.
- * is_first - if this is the first iodev on the card.
- * mixer - The mixer for the alsa device.
- * config - Card config for this alsa device.
- * ucm - CRAS use case manager if available.
- * hctl - high-level control manager if available.
- * direction - input or output.
- * usb_vid - vendor ID of USB device.
- * usb_pid - product ID of USB device.
- * usb_serial_number - serial number of USB device.
- * Returns:
- * A pointer to the newly created iodev if successful, NULL otherwise.
- */
-struct cras_iodev *
-alsa_iodev_create(size_t card_index, const char *card_name, size_t device_index,
- const char *pcm_name, const char *dev_name,
- const char *dev_id, enum CRAS_ALSA_CARD_TYPE card_type,
- int is_first, struct cras_alsa_mixer *mixer,
- const struct cras_card_config *config,
- struct cras_use_case_mgr *ucm, snd_hctl_t *hctl,
- enum CRAS_STREAM_DIRECTION direction, size_t usb_vid,
- size_t usb_pid, char *usb_serial_number);
-
-/* Complete initializeation of this iodev with the legacy method.
- * Add IO nodes and find jacks for this iodev with magic sauce, then choose
- * the current active node.
- * Args:
- * iodev - ALSA io device associated with the IO nodes.
- * section - UCM section information if available (or NULL).
- * Returns:
- * 0 for success, negative error code on error.
- */
-int alsa_iodev_legacy_complete_init(struct cras_iodev *iodev);
-
-/* Add IO nodes and jacks for this iodev using UCM data.
- * Args:
- * iodev - ALSA io device associated with the given section.
- * section - UCM section information.
- * Returns:
- * 0 for success, negative error code on error.
- */
-int alsa_iodev_ucm_add_nodes_and_jacks(struct cras_iodev *iodev,
- struct ucm_section *section);
-
-/* Complete initialization of this iodev with fully-spec UCM data.
- * After all UCM devices associated with the same iodev have been processed
- * this is called to finish iodev setup.
- * Args:
- * iodev - ALSA io device.
- */
-void alsa_iodev_ucm_complete_init(struct cras_iodev *iodev);
-
-/* Destroys an alsa_iodev created with alsa_iodev_create. */
-void alsa_iodev_destroy(struct cras_iodev *iodev);
-
-/* Returns the ALSA device index for the given ALSA iodev. */
-unsigned alsa_iodev_index(struct cras_iodev *iodev);
-
-/* Returns whether this IODEV has ALSA hctl jacks. */
-int alsa_iodev_has_hctl_jacks(struct cras_iodev *iodev);
-
-#endif /* CRAS_ALSA_IO_H_ */
diff --git a/cras/src/server/cras_alsa_jack.c b/cras/src/server/cras_alsa_jack.c
deleted file mode 100644
index 6d4d7bf5..00000000
--- a/cras/src/server/cras_alsa_jack.c
+++ /dev/null
@@ -1,1243 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <linux/input.h>
-#include <regex.h>
-#include <syslog.h>
-
-#include "cras_alsa_jack.h"
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_ucm.h"
-#include "cras_system_state.h"
-#include "cras_gpio_jack.h"
-#include "cras_tm.h"
-#include "cras_util.h"
-#include "edid_utils.h"
-#include "utlist.h"
-
-static const unsigned int DISPLAY_INFO_RETRY_DELAY_MS = 200;
-static const unsigned int DISPLAY_INFO_MAX_RETRIES = 10;
-static const unsigned int DISPLAY_INFO_GPIO_MAX_RETRIES = 25;
-
-/* Constants used to retrieve monitor name from ELD buffer. */
-static const unsigned int ELD_MNL_MASK = 31;
-static const unsigned int ELD_MNL_OFFSET = 4;
-static const unsigned int ELD_MONITOR_NAME_OFFSET = 20;
-
-/* Keeps an fd that is registered with system settings. A list of fds must be
- * kept so that they can be removed when the jack list is destroyed. */
-struct jack_poll_fd {
- int fd;
- struct jack_poll_fd *prev, *next;
-};
-
-/* cras_gpio_jack: Describes headphone & microphone jack connected to GPIO
- *
- * On Arm-based systems, the headphone & microphone jacks are
- * connected to GPIOs which are plumbed through the /dev/input/event
- * system. For these jacks, the software is written to open the
- * corresponding /dev/input/event file and monitor it for 'insert' &
- * 'remove' activity.
- *
- * fd : File descriptor corresponding to the /dev/input/event file.
- *
- * switch_event : Indicates the type of the /dev/input/event file.
- * Either SW_HEADPHONE_INSERT, or SW_MICROPHONE_INSERT.
- *
- * current_state: 0 -> device not plugged in
- * 1 -> device plugged in
- * device_name : Device name extracted from /dev/input/event[0..9]+.
- * Allocated on heap; must free.
- */
-struct cras_gpio_jack {
- int fd;
- unsigned switch_event;
- unsigned current_state;
- char *device_name;
-};
-
-/* Represents a single alsa Jack, e.g. "Headphone Jack" or "Mic Jack".
- * is_gpio: 1 -> gpio switch (union field: gpio)
- * 0 -> Alsa 'jack' (union field: elem)
- * elem - alsa hcontrol element for this jack, when is_gpio == 0.
- * gpio - description of gpio-based jack, when is_gpio != 0.
- * eld_control - mixer control for ELD info buffer.
- * jack_list - list of jacks this belongs to.
- * mixer_output - mixer output control used to control audio to this jack.
- * This will be null for input jacks.
- * mixer_input - mixer input control used to control audio to this jack.
- * This will be null for output jacks.
- * ucm_device - Name of the ucm device if found, otherwise, NULL.
- * edid_file - File to read the EDID from (if available, HDMI only).
- * display_info_timer - Timer used to poll display info for HDMI jacks.
- * display_info_retries - Number of times to retry reading display info.
- *
- * mixer_output/mixer_input fields are only used to find the node for this
- * jack. These are not used for setting volume or mute. There should be a
- * 1:1 map between node and jack. node->jack follows the pointer; jack->node
- * is done by either searching node->jack pointers or searching the node that
- * has the same mixer_control as the jack.
- */
-struct cras_alsa_jack {
- unsigned is_gpio; /* !0 -> 'gpio' valid
- * 0 -> 'elem' valid
- */
- union {
- snd_hctl_elem_t *elem;
- struct cras_gpio_jack gpio;
- };
-
- snd_hctl_elem_t *eld_control;
- struct cras_alsa_jack_list *jack_list;
- struct mixer_control *mixer_output;
- struct mixer_control *mixer_input;
- char *ucm_device;
- const char *override_type_name;
- const char *edid_file;
- struct cras_timer *display_info_timer;
- unsigned int display_info_retries;
- struct cras_alsa_jack *prev, *next;
-};
-
-/* Contains all Jacks for a given device.
- * hctl - alsa hcontrol for this device's card
- * - not opened by the jack list.
- * mixer - cras mixer for the card providing this device.
- * ucm - CRAS use case manager if available.
- * card_index - Index ALSA uses to refer to the card. The X in "hw:X".
- * card_name - The name of the card.
- * device_index - Index ALSA uses to refer to the device. The Y in "hw:X,Y".
- * is_first_device - whether this device is the first device on the card.
- * direction - Input or output.
- * change_callback - function to call when the state of a jack changes.
- * callback_data - data to pass back to the callback.
- * jacks - list of jacks for this device.
- */
-struct cras_alsa_jack_list {
- snd_hctl_t *hctl;
- struct cras_alsa_mixer *mixer;
- struct cras_use_case_mgr *ucm;
- unsigned int card_index;
- const char *card_name;
- size_t device_index;
- int is_first_device;
- enum CRAS_STREAM_DIRECTION direction;
- jack_state_change_callback *change_callback;
- void *callback_data;
- struct cras_alsa_jack *jacks;
-};
-
-/* Used to contain information needed while looking through GPIO jacks.
- * jack_list - The current jack_list.
- * section - An associated UCM section.
- * result_jack - The resulting jack.
- * rc - The return code for the operation.
- */
-struct gpio_switch_list_data {
- struct cras_alsa_jack_list *jack_list;
- struct ucm_section *section;
- struct cras_alsa_jack *result_jack;
- int rc;
-};
-
-/*
- * Local Helpers.
- */
-
-#define BITS_PER_BYTE (8)
-#define BITS_PER_LONG (sizeof(long) * BITS_PER_BYTE)
-#define NBITS(x) ((((x)-1) / BITS_PER_LONG) + 1)
-#define OFF(x) ((x) % BITS_PER_LONG)
-#define BIT(x) (1UL << OFF(x))
-#define LONG(x) ((x) / BITS_PER_LONG)
-#define IS_BIT_SET(bit, array) !!((array[LONG(bit)]) & (1UL << OFF(bit)))
-
-static int sys_input_get_switch_state(int fd, unsigned sw, unsigned *state)
-{
- unsigned long bits[NBITS(SW_CNT)];
- const unsigned long switch_no = sw;
-
- memset(bits, '\0', sizeof(bits));
- /* If switch event present & supported, get current state. */
- if (gpio_switch_eviocgbit(fd, bits, sizeof(bits)) < 0)
- return -EIO;
-
- if (IS_BIT_SET(switch_no, bits))
- if (gpio_switch_eviocgsw(fd, bits, sizeof(bits)) >= 0) {
- *state = IS_BIT_SET(switch_no, bits);
- return 0;
- }
-
- return -1;
-}
-
-static inline struct cras_alsa_jack *cras_alloc_jack(int is_gpio)
-{
- struct cras_alsa_jack *jack = calloc(1, sizeof(*jack));
- if (jack == NULL)
- return NULL;
- jack->is_gpio = is_gpio;
- return jack;
-}
-
-static void cras_free_jack(struct cras_alsa_jack *jack, int rm_select_fd)
-{
- if (!jack)
- return;
-
- free(jack->ucm_device);
- free((void *)jack->edid_file);
- if (jack->display_info_timer)
- cras_tm_cancel_timer(cras_system_state_get_tm(),
- jack->display_info_timer);
-
- if (jack->is_gpio) {
- free(jack->gpio.device_name);
- if (jack->gpio.fd >= 0) {
- if (rm_select_fd)
- cras_system_rm_select_fd(jack->gpio.fd);
- close(jack->gpio.fd);
- }
- }
-
- /*
- * Remove the jack callback set on hctl. Otherwise, snd_hctl_close will
- * trigger a callback while iodev might already be destroyed.
- */
- if (!jack->is_gpio && jack->elem)
- snd_hctl_elem_set_callback(jack->elem, NULL);
-
- free((void *)jack->override_type_name);
- free(jack);
-}
-
-/* Gets the current plug state of the jack */
-static int get_jack_current_state(struct cras_alsa_jack *jack)
-{
- snd_ctl_elem_value_t *elem_value;
-
- if (jack->is_gpio)
- return jack->gpio.current_state;
-
- snd_ctl_elem_value_alloca(&elem_value);
- snd_hctl_elem_read(jack->elem, elem_value);
-
- return snd_ctl_elem_value_get_boolean(elem_value, 0);
-}
-
-static int read_jack_edid(const struct cras_alsa_jack *jack, uint8_t *edid)
-{
- int fd, nread;
-
- fd = open(jack->edid_file, O_RDONLY);
- if (fd < 0)
- return -1;
-
- nread = read(fd, edid, EEDID_SIZE);
- close(fd);
-
- if (nread < EDID_SIZE || !edid_valid(edid))
- return -1;
- return 0;
-}
-
-static int check_jack_edid(struct cras_alsa_jack *jack)
-{
- uint8_t edid[EEDID_SIZE];
-
- if (read_jack_edid(jack, edid))
- return -1;
-
- /* If the jack supports EDID, check that it supports audio, clearing
- * the plugged state if it doesn't.
- */
- if (!edid_lpcm_support(edid, edid[EDID_EXT_FLAG]))
- jack->gpio.current_state = 0;
- return 0;
-}
-
-static int get_jack_edid_monitor_name(const struct cras_alsa_jack *jack,
- char *buf, unsigned int buf_size)
-{
- uint8_t edid[EEDID_SIZE];
-
- if (read_jack_edid(jack, edid))
- return -1;
-
- return edid_get_monitor_name(edid, buf, buf_size);
-}
-
-/* Checks the ELD control of the jack to see if the ELD buffer
- * is ready to read and report the plug status.
- */
-static int check_jack_eld(struct cras_alsa_jack *jack)
-{
- snd_ctl_elem_info_t *elem_info;
- snd_ctl_elem_info_alloca(&elem_info);
-
- /* Poll ELD control by getting the count of ELD buffer.
- * When seeing zero buffer count, retry after a delay until
- * it's ready or reached the max number of retries. */
- if (snd_hctl_elem_info(jack->eld_control, elem_info) != 0)
- return -1;
- if (snd_ctl_elem_info_get_count(elem_info) == 0)
- return -1;
- return 0;
-}
-
-static void display_info_delay_cb(struct cras_timer *timer, void *arg);
-
-/* Callback function doing following things:
- * 1. Reset timer and update max number of retries.
- * 2. Check all conditions to see if it's okay or needed to
- * report jack status directly. E.g. jack is unplugged or
- * EDID is not ready for some reason.
- * 3. Check if max number of retries is reached and decide
- * to set timer for next callback or report jack state.
- */
-static inline void jack_state_change_cb(struct cras_alsa_jack *jack, int retry)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
-
- if (jack->display_info_timer) {
- cras_tm_cancel_timer(tm, jack->display_info_timer);
- jack->display_info_timer = NULL;
- }
- if (retry) {
- jack->display_info_retries =
- jack->is_gpio ? DISPLAY_INFO_GPIO_MAX_RETRIES :
- DISPLAY_INFO_MAX_RETRIES;
- }
-
- if (!get_jack_current_state(jack))
- goto report_jack_state;
-
- /* If there is an edid file, check it. If it is ready continue, if we
- * need to try again later, return here as the timer has been armed and
- * will check again later.
- */
- if (jack->edid_file == NULL && jack->eld_control == NULL)
- goto report_jack_state;
- if (jack->edid_file && (check_jack_edid(jack) == 0))
- goto report_jack_state;
- if (jack->eld_control && (check_jack_eld(jack) == 0))
- goto report_jack_state;
-
- if (--jack->display_info_retries == 0) {
- if (jack->is_gpio)
- jack->gpio.current_state = 0;
- if (jack->edid_file)
- syslog(LOG_ERR, "Timeout to read EDID from %s",
- jack->edid_file);
- goto report_jack_state;
- }
-
- jack->display_info_timer = cras_tm_create_timer(
- tm, DISPLAY_INFO_RETRY_DELAY_MS, display_info_delay_cb, jack);
- return;
-
-report_jack_state:
- jack->jack_list->change_callback(jack, get_jack_current_state(jack),
- jack->jack_list->callback_data);
-}
-
-/* gpio_switch_initial_state
- *
- * Determines the initial state of a gpio-based switch.
- */
-static void gpio_switch_initial_state(struct cras_alsa_jack *jack)
-{
- unsigned v;
- int r = sys_input_get_switch_state(jack->gpio.fd,
- jack->gpio.switch_event, &v);
- jack->gpio.current_state = r == 0 ? v : 0;
- jack_state_change_cb(jack, 1);
-}
-
-/* Check if the input event is an audio switch event. */
-static inline int is_audio_switch_event(const struct input_event *ev,
- int sw_code)
-{
- return (ev->type == EV_SW && ev->code == sw_code);
-}
-
-/* Timer callback to read display info after a hotplug event for an HDMI jack.
- */
-static void display_info_delay_cb(struct cras_timer *timer, void *arg)
-{
- struct cras_alsa_jack *jack = (struct cras_alsa_jack *)arg;
-
- jack->display_info_timer = NULL;
- jack_state_change_cb(jack, 0);
-}
-
-/* gpio_switch_callback
- *
- * This callback is invoked whenever the associated /dev/input/event
- * file has data to read. Perform autoswitching to / from the
- * associated device when data is available.
- */
-static void gpio_switch_callback(void *arg, int events)
-{
- struct cras_alsa_jack *jack = arg;
- int i;
- int r;
- struct input_event ev[64];
-
- r = gpio_switch_read(jack->gpio.fd, ev,
- ARRAY_SIZE(ev) * sizeof(struct input_event));
- if (r < 0)
- return;
-
- for (i = 0; i < r / sizeof(struct input_event); ++i)
- if (is_audio_switch_event(&ev[i], jack->gpio.switch_event)) {
- jack->gpio.current_state = ev[i].value;
-
- jack_state_change_cb(jack, 1);
- }
-}
-
-/* Determines if the GPIO jack should be associated with the device of the
- * jack list. If the device name is not specified in UCM (common case),
- * assume it should be associated with the first input device or the first
- * output device on the card.
- */
-static unsigned int
-gpio_jack_match_device(const struct cras_alsa_jack *jack,
- struct cras_alsa_jack_list *jack_list,
- enum CRAS_STREAM_DIRECTION direction)
-{
- int target_dev_idx;
-
- /* If the device name is not specified in UCM, assume it should be
- * associated with device 0. */
- if (!jack_list->ucm || !jack->ucm_device)
- return jack_list->is_first_device;
-
- /* If jack has valid ucm_device, that means this jack has already been
- * associated to this card. Next step to match device index on this
- * card. */
- target_dev_idx = ucm_get_alsa_dev_idx_for_dev(
- jack_list->ucm, jack->ucm_device, direction);
-
- if (target_dev_idx < 0)
- return jack_list->is_first_device;
-
- syslog(LOG_DEBUG,
- "Matching GPIO jack, target device idx: %d, "
- "current card name: %s, device index: %zu\n",
- target_dev_idx, jack_list->card_name, jack_list->device_index);
-
- return (target_dev_idx == jack_list->device_index);
-}
-
-static int create_jack_for_gpio(struct cras_alsa_jack_list *jack_list,
- const char *pathname, const char *dev_name,
- unsigned switch_event,
- struct cras_alsa_jack **out_jack)
-{
- struct cras_alsa_jack *jack;
- unsigned long bits[NBITS(SW_CNT)];
- const char *card_name = jack_list->card_name;
- int r;
-
- if (!out_jack)
- return -EINVAL;
- *out_jack = NULL;
-
- jack = cras_alloc_jack(1);
- if (jack == NULL)
- return -ENOMEM;
-
- jack->gpio.fd = gpio_switch_open(pathname);
- if (jack->gpio.fd == -1) {
- r = -EIO;
- goto error;
- }
-
- jack->gpio.switch_event = switch_event;
- jack->jack_list = jack_list;
- jack->gpio.device_name = strdup(dev_name);
- if (!jack->gpio.device_name) {
- r = -ENOMEM;
- goto error;
- }
-
- if (!strstr(jack->gpio.device_name, card_name) ||
- (gpio_switch_eviocgbit(jack->gpio.fd, bits, sizeof(bits)) < 0) ||
- !IS_BIT_SET(switch_event, bits)) {
- r = -EIO;
- goto error;
- }
-
- *out_jack = jack;
- return 0;
-
-error:
- /* Not yet registered with system select. */
- cras_free_jack(jack, 0);
- return r;
-}
-
-/* Take ownership and finish setup of the jack.
- * Add the jack to the jack_list if everything goes well, or destroy it.
- */
-static int cras_complete_gpio_jack(struct gpio_switch_list_data *data,
- struct cras_alsa_jack *jack,
- unsigned switch_event)
-{
- struct cras_alsa_jack_list *jack_list = data->jack_list;
- int r;
-
- if (jack->ucm_device) {
- jack->edid_file = ucm_get_edid_file_for_dev(jack_list->ucm,
- jack->ucm_device);
- }
-
- r = sys_input_get_switch_state(jack->gpio.fd, switch_event,
- &jack->gpio.current_state);
- if (r < 0) {
- cras_free_jack(jack, 0);
- return -EIO;
- }
- r = cras_system_add_select_fd(jack->gpio.fd, gpio_switch_callback, jack,
- POLLIN);
- if (r < 0) {
- /* Not yet registered with system select. */
- cras_free_jack(jack, 0);
- return r;
- }
-
- DL_APPEND(jack_list->jacks, jack);
- if (!data->result_jack)
- data->result_jack = jack;
- else if (data->section)
- syslog(LOG_ERR, "More than one jack for SectionDevice '%s'.",
- data->section->name);
- return 0;
-}
-
-/* open_and_monitor_gpio:
- *
- * Opens a /dev/input/event file associated with a headphone /
- * microphone jack and watches it for activity.
- * Returns 0 when a jack has been successfully added.
- */
-static int open_and_monitor_gpio(struct gpio_switch_list_data *data,
- const char *pathname, const char *dev_name,
- unsigned switch_event)
-{
- struct cras_alsa_jack *jack;
- struct cras_alsa_jack_list *jack_list = data->jack_list;
- enum CRAS_STREAM_DIRECTION direction = jack_list->direction;
- int r;
-
- r = create_jack_for_gpio(jack_list, pathname, dev_name, switch_event,
- &jack);
- if (r != 0)
- return r;
-
- if (jack_list->ucm)
- jack->ucm_device = ucm_get_dev_for_jack(
- jack_list->ucm, jack->gpio.device_name, direction);
-
- if (!gpio_jack_match_device(jack, jack_list, direction)) {
- cras_free_jack(jack, 0);
- return -EIO;
- }
-
- if (direction == CRAS_STREAM_OUTPUT &&
- (strstr(jack->gpio.device_name, "Headphone") ||
- strstr(jack->gpio.device_name, "Headset")))
- jack->mixer_output = cras_alsa_mixer_get_output_matching_name(
- jack_list->mixer, "Headphone");
- else if (direction == CRAS_STREAM_OUTPUT &&
- strstr(jack->gpio.device_name, "HDMI"))
- jack->mixer_output = cras_alsa_mixer_get_output_matching_name(
- jack_list->mixer, "HDMI");
-
- if (jack->ucm_device && direction == CRAS_STREAM_INPUT) {
- char *control_name;
- control_name = ucm_get_cap_control(jack->jack_list->ucm,
- jack->ucm_device);
- if (control_name)
- jack->mixer_input =
- cras_alsa_mixer_get_input_matching_name(
- jack_list->mixer, control_name);
- }
-
- return cras_complete_gpio_jack(data, jack, switch_event);
-}
-
-static int
-open_and_monitor_gpio_with_section(struct gpio_switch_list_data *data,
- const char *pathname, unsigned switch_event)
-{
- struct cras_alsa_jack *jack;
- struct cras_alsa_jack_list *jack_list = data->jack_list;
- struct ucm_section *section = data->section;
- enum CRAS_STREAM_DIRECTION direction = jack_list->direction;
- int r;
-
- r = create_jack_for_gpio(jack_list, pathname, section->jack_name,
- switch_event, &jack);
- if (r != 0)
- return r;
-
- jack->ucm_device = strdup(section->name);
- if (!jack->ucm_device) {
- cras_free_jack(jack, 0);
- return -ENOMEM;
- }
-
- if (direction == CRAS_STREAM_OUTPUT)
- jack->mixer_output = cras_alsa_mixer_get_control_for_section(
- jack_list->mixer, section);
- else if (direction == CRAS_STREAM_INPUT)
- jack->mixer_input = cras_alsa_mixer_get_control_for_section(
- jack_list->mixer, section);
-
- return cras_complete_gpio_jack(data, jack, switch_event);
-}
-
-/* Monitor GPIO switches for this jack_list.
- * Args:
- * data - Data for GPIO switch search.
- * dev_path - Device full path.
- * dev_name - Device name.
- * Returns:
- * 0 for success, or negative on error. Assumes success if no jack is
- * found, or if the jack could not be accessed.
- */
-static int gpio_switches_monitor_device(struct gpio_switch_list_data *data,
- const char *dev_path,
- const char *dev_name)
-{
- static const int out_switches[] = { SW_HEADPHONE_INSERT,
- SW_LINEOUT_INSERT };
- static const int in_switches[] = { SW_MICROPHONE_INSERT };
- int sw;
- const int *switches = out_switches;
- int num_switches = ARRAY_SIZE(out_switches);
- int success = 1;
- int rc = 0;
-
- if (data->section && data->section->jack_switch >= 0) {
- switches = &data->section->jack_switch;
- num_switches = 1;
- } else if (data->jack_list->direction == CRAS_STREAM_INPUT) {
- switches = in_switches;
- num_switches = ARRAY_SIZE(in_switches);
- }
-
- /* Assume that -EIO is returned for jacks that we shouldn't
- * be looking at, but stop trying if we run into another
- * type of error.
- */
- for (sw = 0; (rc == 0 || rc == -EIO) && sw < num_switches; sw++) {
- if (data->section)
- rc = open_and_monitor_gpio_with_section(data, dev_path,
- switches[sw]);
- else
- rc = open_and_monitor_gpio(data, dev_path, dev_name,
- switches[sw]);
- if (rc != 0 && rc != -EIO)
- success = 0;
- }
-
- if (success)
- return 0;
- return rc;
-}
-
-static int gpio_switch_list_with_section(const char *dev_path,
- const char *dev_name, void *arg)
-{
- struct gpio_switch_list_data *data =
- (struct gpio_switch_list_data *)arg;
-
- if (strcmp(dev_name, data->section->jack_name)) {
- /* No match: continue searching. */
- return 0;
- }
-
- data->rc = gpio_switches_monitor_device(data, dev_path, dev_name);
- /* Found the only possible match: stop searching. */
- return 1;
-}
-
-/* Match the given jack name to the given regular expression.
- * Args:
- * jack_name - The jack's name.
- * re - Regular expression string.
- * Returns:
- * Non-zero for success, or 0 for failure.
- */
-static int jack_matches_regex(const char *jack_name, const char *re)
-{
- regmatch_t m[1];
- regex_t regex;
- int rc;
-
- rc = regcomp(&regex, re, REG_EXTENDED);
- if (rc != 0) {
- syslog(LOG_ERR, "Failed to compile regular expression: %s", re);
- return 0;
- }
-
- rc = regexec(&regex, jack_name, ARRAY_SIZE(m), m, 0) == 0;
- regfree(&regex);
- return rc;
-}
-
-static int gpio_switch_list_by_matching(const char *dev_path,
- const char *dev_name, void *arg)
-{
- struct gpio_switch_list_data *data =
- (struct gpio_switch_list_data *)arg;
-
- if (data->jack_list->direction == CRAS_STREAM_INPUT) {
- if (!jack_matches_regex(dev_name, "^.*Mic Jack$") &&
- !jack_matches_regex(dev_name, "^.*Headset Jack$")) {
- /* Continue searching. */
- return 0;
- }
- } else if (data->jack_list->direction == CRAS_STREAM_OUTPUT) {
- if (!jack_matches_regex(dev_name, "^.*Headphone Jack$") &&
- !jack_matches_regex(dev_name, "^.*Headset Jack$") &&
- !jack_matches_regex(dev_name, "^.*HDMI Jack$")) {
- /* Continue searching. */
- return 0;
- }
- }
-
- data->rc = gpio_switches_monitor_device(data, dev_path, dev_name);
- /* Stop searching for failure. */
- return data->rc;
-}
-
-/* Find ELD control for HDMI/DP gpio jack. */
-static snd_hctl_elem_t *find_eld_control_by_dev_index(snd_hctl_t *hctl,
- unsigned int dev_idx)
-{
- static const char eld_control_name[] = "ELD";
- snd_ctl_elem_id_t *elem_id;
-
- snd_ctl_elem_id_alloca(&elem_id);
- snd_ctl_elem_id_clear(elem_id);
- snd_ctl_elem_id_set_interface(elem_id, SND_CTL_ELEM_IFACE_PCM);
- snd_ctl_elem_id_set_device(elem_id, dev_idx);
- snd_ctl_elem_id_set_name(elem_id, eld_control_name);
- return snd_hctl_find_elem(hctl, elem_id);
-}
-
-/* For non-gpio jack, check if it's of type hdmi/dp by
- * matching jack name. */
-static int is_jack_hdmi_dp(const char *jack_name)
-{
- // TODO(hychao): Use the information provided in UCM instead of
- // name matching.
- static const char *hdmi_dp = "HDMI";
- return !!strstr(jack_name, hdmi_dp);
-}
-
-/* Find GPIO jacks for this jack_list.
- * Args:
- * jack_list - Jack list to add to.
- * section - UCM section.
- * result_jack - Filled with a pointer to the resulting cras_alsa_jack.
- * Returns:
- * 0 for success, or negative on error. Assumes success if no jack is
- * found, or if the jack could not be accessed.
- */
-static int find_gpio_jacks(struct cras_alsa_jack_list *jack_list,
- struct ucm_section *section,
- struct cras_alsa_jack **result_jack)
-{
- /* GPIO switches are on Arm-based machines, and are
- * only associated with on-board devices.
- */
- struct gpio_switch_list_data data;
- int rc;
-
- rc = wait_for_dev_input_access();
- if (rc != 0) {
- syslog(LOG_WARNING, "Could not access /dev/input/event0: %s",
- strerror(rc));
- return 0;
- }
-
- data.jack_list = jack_list;
- data.section = section;
- data.result_jack = NULL;
- data.rc = 0;
-
- if (section)
- gpio_switch_list_for_each(gpio_switch_list_with_section, &data);
- else
- gpio_switch_list_for_each(gpio_switch_list_by_matching, &data);
- if (result_jack) {
- *result_jack = data.result_jack;
-
- /* Find ELD control only for HDMI/DP gpio jack. */
- if (*result_jack &&
- is_jack_hdmi_dp((*result_jack)->gpio.device_name))
- (*result_jack)->eld_control =
- find_eld_control_by_dev_index(
- jack_list->hctl,
- jack_list->device_index);
- }
- return data.rc;
-}
-
-/* Callback from alsa when a jack control changes. This is registered with
- * snd_hctl_elem_set_callback in find_jack_controls and run by calling
- * snd_hctl_handle_events in alsa_control_event_pending below.
- * Args:
- * elem - The ALSA control element that has changed.
- * mask - unused.
- */
-static int hctl_jack_cb(snd_hctl_elem_t *elem, unsigned int mask)
-{
- const char *name;
- snd_ctl_elem_value_t *elem_value;
- struct cras_alsa_jack *jack;
-
- jack = snd_hctl_elem_get_callback_private(elem);
- if (jack == NULL) {
- syslog(LOG_ERR, "Invalid jack from control event.");
- return -EINVAL;
- }
-
- snd_ctl_elem_value_alloca(&elem_value);
- snd_hctl_elem_read(elem, elem_value);
- name = snd_hctl_elem_get_name(elem);
-
- syslog(LOG_DEBUG, "Jack %s %s", name,
- snd_ctl_elem_value_get_boolean(elem_value, 0) ? "plugged" :
- "unplugged");
- jack_state_change_cb(jack, 1);
- return 0;
-}
-
-/* Determines the device associated with this jack if any. If the device cannot
- * be determined (common case), assume device 0. */
-static unsigned int hctl_jack_device_index(const char *name)
-{
- /* Look for the substring 'pcm=<device number>' in the element name. */
- static const char pcm_search[] = "pcm=";
- const char *substr;
- int device_index;
-
- substr = strstr(name, pcm_search);
- if (substr == NULL)
- return 0;
- substr += ARRAY_SIZE(pcm_search) - 1;
- if (*substr == '\0')
- return 0;
- device_index = atoi(substr);
- if (device_index < 0)
- return 0;
- return (unsigned int)device_index;
-}
-
-/* Checks if the given control name is in the supplied list of possible jack
- * control base names. */
-static int is_jack_control_in_list(const char *const *list,
- unsigned int list_length,
- const char *control_name)
-{
- unsigned int i;
-
- for (i = 0; i < list_length; i++)
- if (strncmp(control_name, list[i], strlen(list[i])) == 0)
- return 1;
- return 0;
-}
-
-/* Check if the given name is a jack created for the connector control of a
- * input/output terminal entity on a USB Audio Class 2.0 device. */
-static int is_jack_uac2(const char *jack_name,
- enum CRAS_STREAM_DIRECTION direction)
-{
- return jack_matches_regex(jack_name, direction == CRAS_STREAM_OUTPUT ?
- "^.* - Output Jack$" :
- "^.* - Input Jack$");
-}
-
-/* Looks for any JACK controls. Monitors any found controls for changes and
- * decides to route based on plug/unlpug events. */
-static int find_jack_controls(struct cras_alsa_jack_list *jack_list)
-{
- snd_hctl_elem_t *elem;
- struct cras_alsa_jack *jack;
- const char *name;
- static const char *const output_jack_base_names[] = {
- "Headphone Jack",
- "Front Headphone Jack",
- "HDMI/DP",
- "Speaker Phantom Jack",
- };
- static const char *const input_jack_base_names[] = {
- "Mic Jack",
- };
- const char *const *jack_names;
- unsigned int num_jack_names;
-
- if (!jack_list->hctl) {
- syslog(LOG_WARNING, "Can't search hctl for jacks.");
- return 0;
- }
-
- if (jack_list->direction == CRAS_STREAM_OUTPUT) {
- jack_names = output_jack_base_names;
- num_jack_names = ARRAY_SIZE(output_jack_base_names);
- } else {
- jack_names = input_jack_base_names;
- num_jack_names = ARRAY_SIZE(input_jack_base_names);
- }
-
- for (elem = snd_hctl_first_elem(jack_list->hctl); elem != NULL;
- elem = snd_hctl_elem_next(elem)) {
- snd_ctl_elem_iface_t iface;
-
- iface = snd_hctl_elem_get_interface(elem);
- if (iface != SND_CTL_ELEM_IFACE_CARD)
- continue;
- name = snd_hctl_elem_get_name(elem);
- if (!is_jack_control_in_list(jack_names, num_jack_names,
- name) &&
- !is_jack_uac2(name, jack_list->direction))
- continue;
- if (hctl_jack_device_index(name) != jack_list->device_index)
- continue;
-
- jack = cras_alloc_jack(0);
- if (jack == NULL)
- return -ENOMEM;
- jack->elem = elem;
- jack->jack_list = jack_list;
- DL_APPEND(jack_list->jacks, jack);
-
- snd_hctl_elem_set_callback(elem, hctl_jack_cb);
- snd_hctl_elem_set_callback_private(elem, jack);
-
- if (jack_list->direction == CRAS_STREAM_OUTPUT)
- jack->mixer_output =
- cras_alsa_mixer_get_output_matching_name(
- jack_list->mixer, name);
- if (jack_list->ucm)
- jack->ucm_device = ucm_get_dev_for_jack(
- jack_list->ucm, name, jack_list->direction);
-
- if (jack->ucm_device &&
- jack_list->direction == CRAS_STREAM_INPUT) {
- char *control_name;
- control_name = ucm_get_cap_control(jack->jack_list->ucm,
- jack->ucm_device);
- if (control_name)
- jack->mixer_input =
- cras_alsa_mixer_get_input_matching_name(
- jack_list->mixer, control_name);
- }
-
- if (jack->ucm_device) {
- jack->override_type_name = ucm_get_override_type_name(
- jack->jack_list->ucm, jack->ucm_device);
- }
- }
-
- /* Look up ELD controls */
- DL_FOREACH (jack_list->jacks, jack) {
- if (jack->is_gpio || jack->eld_control)
- continue;
- name = snd_hctl_elem_get_name(jack->elem);
- if (!is_jack_hdmi_dp(name))
- continue;
-
- jack->eld_control = find_eld_control_by_dev_index(
- jack_list->hctl, jack_list->device_index);
- }
-
- return 0;
-}
-
-/*
- * Exported Interface.
- */
-
-int cras_alsa_jack_list_find_jacks_by_name_matching(
- struct cras_alsa_jack_list *jack_list)
-{
- int rc;
-
- rc = find_jack_controls(jack_list);
- if (rc != 0)
- return rc;
-
- return find_gpio_jacks(jack_list, NULL, NULL);
-}
-
-static int find_hctl_jack_for_section(struct cras_alsa_jack_list *jack_list,
- struct ucm_section *section,
- struct cras_alsa_jack **result_jack)
-{
- snd_hctl_elem_t *elem;
- snd_ctl_elem_id_t *elem_id;
- struct cras_alsa_jack *jack;
-
- if (!jack_list->hctl) {
- syslog(LOG_WARNING, "Can't search hctl for jacks.");
- return -ENODEV;
- }
-
- snd_ctl_elem_id_alloca(&elem_id);
- snd_ctl_elem_id_clear(elem_id);
- snd_ctl_elem_id_set_interface(elem_id, SND_CTL_ELEM_IFACE_CARD);
- snd_ctl_elem_id_set_device(elem_id, jack_list->device_index);
- snd_ctl_elem_id_set_name(elem_id, section->jack_name);
- elem = snd_hctl_find_elem(jack_list->hctl, elem_id);
- if (!elem)
- return -ENOENT;
-
- syslog(LOG_DEBUG, "Found Jack: %s for %s", section->jack_name,
- section->name);
-
- jack = cras_alloc_jack(0);
- if (jack == NULL)
- return -ENOMEM;
- jack->elem = elem;
- jack->jack_list = jack_list;
-
- jack->ucm_device = strdup(section->name);
- if (!jack->ucm_device) {
- free(jack);
- return -ENOMEM;
- }
- if (jack_list->direction == CRAS_STREAM_OUTPUT)
- jack->mixer_output = cras_alsa_mixer_get_control_for_section(
- jack_list->mixer, section);
- else if (jack_list->direction == CRAS_STREAM_INPUT)
- jack->mixer_input = cras_alsa_mixer_get_control_for_section(
- jack_list->mixer, section);
-
- snd_hctl_elem_set_callback(elem, hctl_jack_cb);
- snd_hctl_elem_set_callback_private(elem, jack);
- DL_APPEND(jack_list->jacks, jack);
- if (result_jack)
- *result_jack = jack;
-
- if (!strcmp(jack->ucm_device, "HDMI") ||
- !strcmp(jack->ucm_device, "DP"))
- return 0;
-
- /* Look up ELD control. */
- jack->eld_control = find_eld_control_by_dev_index(
- jack_list->hctl, jack_list->device_index);
- return 0;
-}
-
-/*
- * Exported Interface.
- */
-
-int cras_alsa_jack_list_add_jack_for_section(
- struct cras_alsa_jack_list *jack_list, struct ucm_section *ucm_section,
- struct cras_alsa_jack **result_jack)
-{
- if (result_jack)
- *result_jack = NULL;
- if (!ucm_section)
- return -EINVAL;
-
- if (!ucm_section->jack_name) {
- /* No jacks defined for this device. */
- return 0;
- }
-
- if (!ucm_section->jack_type) {
- syslog(LOG_ERR,
- "Must specify the JackType for jack '%s' in '%s'.",
- ucm_section->jack_name, ucm_section->name);
- return -EINVAL;
- }
-
- if (!strcmp(ucm_section->jack_type, "hctl")) {
- return find_hctl_jack_for_section(jack_list, ucm_section,
- result_jack);
- } else if (!strcmp(ucm_section->jack_type, "gpio")) {
- return find_gpio_jacks(jack_list, ucm_section, result_jack);
- } else {
- syslog(LOG_ERR, "Invalid JackType '%s' in '%s'.",
- ucm_section->jack_type, ucm_section->name);
- return -EINVAL;
- }
-}
-
-struct cras_alsa_jack_list *
-cras_alsa_jack_list_create(unsigned int card_index, const char *card_name,
- unsigned int device_index, int is_first_device,
- struct cras_alsa_mixer *mixer,
- struct cras_use_case_mgr *ucm, snd_hctl_t *hctl,
- enum CRAS_STREAM_DIRECTION direction,
- jack_state_change_callback *cb, void *cb_data)
-{
- struct cras_alsa_jack_list *jack_list;
-
- if (direction != CRAS_STREAM_INPUT && direction != CRAS_STREAM_OUTPUT)
- return NULL;
-
- jack_list = (struct cras_alsa_jack_list *)calloc(1, sizeof(*jack_list));
- if (jack_list == NULL)
- return NULL;
-
- jack_list->change_callback = cb;
- jack_list->callback_data = cb_data;
- jack_list->mixer = mixer;
- jack_list->ucm = ucm;
- jack_list->hctl = hctl;
- jack_list->card_index = card_index;
- jack_list->card_name = card_name;
- jack_list->device_index = device_index;
- jack_list->is_first_device = is_first_device;
- jack_list->direction = direction;
-
- return jack_list;
-}
-
-void cras_alsa_jack_list_destroy(struct cras_alsa_jack_list *jack_list)
-{
- struct cras_alsa_jack *jack;
-
- if (jack_list == NULL)
- return;
- DL_FOREACH (jack_list->jacks, jack) {
- DL_DELETE(jack_list->jacks, jack);
- cras_free_jack(jack, 1);
- }
- free(jack_list);
-}
-
-int cras_alsa_jack_list_has_hctl_jacks(struct cras_alsa_jack_list *jack_list)
-{
- struct cras_alsa_jack *jack;
-
- if (!jack_list)
- return 0;
- DL_FOREACH (jack_list->jacks, jack) {
- if (!jack->is_gpio)
- return 1;
- }
- return 0;
-}
-
-struct mixer_control *
-cras_alsa_jack_get_mixer_output(const struct cras_alsa_jack *jack)
-{
- if (jack == NULL)
- return NULL;
- return jack->mixer_output;
-}
-
-struct mixer_control *
-cras_alsa_jack_get_mixer_input(const struct cras_alsa_jack *jack)
-{
- return jack ? jack->mixer_input : NULL;
-}
-
-void cras_alsa_jack_list_report(const struct cras_alsa_jack_list *jack_list)
-{
- struct cras_alsa_jack *jack;
-
- if (jack_list == NULL)
- return;
-
- DL_FOREACH (jack_list->jacks, jack)
- if (jack->is_gpio)
- gpio_switch_initial_state(jack);
- else
- hctl_jack_cb(jack->elem, 0);
-}
-
-const char *cras_alsa_jack_get_name(const struct cras_alsa_jack *jack)
-{
- if (jack == NULL)
- return NULL;
- if (jack->is_gpio)
- return jack->gpio.device_name;
- return snd_hctl_elem_get_name(jack->elem);
-}
-
-const char *cras_alsa_jack_get_ucm_device(const struct cras_alsa_jack *jack)
-{
- return jack->ucm_device;
-}
-
-void cras_alsa_jack_update_monitor_name(const struct cras_alsa_jack *jack,
- char *name_buf, unsigned int buf_size)
-{
- snd_ctl_elem_value_t *elem_value;
- snd_ctl_elem_info_t *elem_info;
- const char *buf = NULL;
- int count;
- int mnl = 0;
-
- if (!jack->eld_control) {
- if (jack->edid_file)
- get_jack_edid_monitor_name(jack, name_buf, buf_size);
- return;
- }
-
- snd_ctl_elem_info_alloca(&elem_info);
- if (snd_hctl_elem_info(jack->eld_control, elem_info) < 0)
- goto fallback_jack_name;
-
- count = snd_ctl_elem_info_get_count(elem_info);
- if (count <= ELD_MNL_OFFSET)
- goto fallback_jack_name;
-
- snd_ctl_elem_value_alloca(&elem_value);
- if (snd_hctl_elem_read(jack->eld_control, elem_value) < 0)
- goto fallback_jack_name;
-
- buf = (const char *)snd_ctl_elem_value_get_bytes(elem_value);
- mnl = buf[ELD_MNL_OFFSET] & ELD_MNL_MASK;
-
- if (count < ELD_MONITOR_NAME_OFFSET + mnl)
- goto fallback_jack_name;
-
- /* Note that monitor name string does not contain terminate character.
- * Check monitor name length with name buffer size.
- */
- if (mnl >= buf_size)
- mnl = buf_size - 1;
- strncpy(name_buf, buf + ELD_MONITOR_NAME_OFFSET, mnl);
- name_buf[mnl] = '\0';
-
- return;
-
-fallback_jack_name:
- buf = cras_alsa_jack_get_name(jack);
- strncpy(name_buf, buf, buf_size - 1);
-
- return;
-}
-
-void cras_alsa_jack_update_node_type(const struct cras_alsa_jack *jack,
- enum CRAS_NODE_TYPE *type)
-{
- if (!jack->override_type_name)
- return;
- if (!strcmp(jack->override_type_name, "Internal Speaker"))
- *type = CRAS_NODE_TYPE_INTERNAL_SPEAKER;
- return;
-}
-
-void cras_alsa_jack_enable_ucm(const struct cras_alsa_jack *jack, int enable)
-{
- if (jack && jack->ucm_device)
- ucm_set_enabled(jack->jack_list->ucm, jack->ucm_device, enable);
-}
diff --git a/cras/src/server/cras_alsa_jack.h b/cras/src/server/cras_alsa_jack.h
deleted file mode 100644
index 9f354590..00000000
--- a/cras/src/server/cras_alsa_jack.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * Handles finding and monitoring ALSA Jack controls. These controls represent
- * external jacks and report back when the plugged state of teh hack changes.
- */
-
-#ifndef CRAS_ALSA_JACK_H_
-#define CRAS_ALSA_JACK_H_
-
-#include "cras_types.h"
-#include "cras_alsa_ucm.h"
-
-struct cras_alsa_jack;
-struct cras_alsa_jack_list;
-struct cras_alsa_mixer;
-
-/* Callback type for users of jack_list to define, it will be called when the
- * jack state changes.
- * Args:
- * jack - The jack that has changed.
- * plugged - non-zero if the jack is attached.
- * data - User defined pointer passed to cras_alsa_jack_create.
- */
-typedef void(jack_state_change_callback)(const struct cras_alsa_jack *jack,
- int plugged, void *data);
-
-/* Creates a jack list. The jacks can be added later by name matching or
- * fully specified UCM.
- * Args:
- * card_index - Index ALSA uses to refer to the card. The X in "hw:X".
- * card_name - The name of the card (used to find gpio jacks).
- * device_index - Index ALSA uses to refer to the device. The Y in "hw:X".
- * is_first_device - whether this device is the first device on the card.
- * mixer - The mixer associated with this card, used to find controls that
- * correspond to jacks. For instance "Headphone switch" for "Headphone
- * Jack".
- * ucm - CRAS use case manager if available.
- * hctl - ALSA high-level control interface if available.
- * direction - Input or output, look for mic or headphone jacks.
- * cb - Function to call when a jack state changes.
- * cb_data - Passed to the callback when called.
- * Returns:
- * A pointer to a new jack list on success, NULL if there is a failure.
- */
-struct cras_alsa_jack_list *
-cras_alsa_jack_list_create(unsigned int card_index, const char *card_name,
- unsigned int device_index, int is_first_device,
- struct cras_alsa_mixer *mixer,
- struct cras_use_case_mgr *ucm, snd_hctl_t *hctl,
- enum CRAS_STREAM_DIRECTION direction,
- jack_state_change_callback *cb, void *cb_data);
-
-/* Finds jacks by name matching.
- * The list holds all the interesting ALSA jacks for this
- * device. These jacks will be for headphones, speakers, HDMI, etc.
- * Args:
- * jack_list - A pointer to a jack list.
- * Returns:
- * 0 on success. Error code if there is a failure.
- */
-int cras_alsa_jack_list_find_jacks_by_name_matching(
- struct cras_alsa_jack_list *jack_list);
-
-/* Add the jack defined by the UCM section information.
- * Args:
- * jack_list - A pointer to a jack list.
- * ucm_section - UCM section data.
- * result_jack - Resulting jack that was added.
- * Returns:
- * 0 on success. Error code if there is a failure.
- */
-int cras_alsa_jack_list_add_jack_for_section(
- struct cras_alsa_jack_list *jack_list, struct ucm_section *ucm_section,
- struct cras_alsa_jack **result_jack);
-
-/* Destroys a jack list created with cras_alsa_jack_list_create.
- * Args:
- * jack_list - The list to destroy.
- */
-void cras_alsa_jack_list_destroy(struct cras_alsa_jack_list *jack_list);
-
-/* Returns non-zero if the jack list has hctl jacks.
- * Args:
- * jack_list - The list check.
- */
-int cras_alsa_jack_list_has_hctl_jacks(struct cras_alsa_jack_list *jack_list);
-
-/* Gets the mixer output associated with the given jack.
- * Args:
- * jack - The jack to query for a mixer output.
- * Returns:
- * A pointer to the mixer output if it exists, otherwise NULL.
- */
-struct mixer_control *
-cras_alsa_jack_get_mixer_output(const struct cras_alsa_jack *jack);
-
-/* Gets the mixer input associated with given jack.
- * Args:
- * jack - The jack to query for a mixer input.
- * Returns:
- * A pointer to the mixer input if it exists, otherwise NULL.
- */
-struct mixer_control *
-cras_alsa_jack_get_mixer_input(const struct cras_alsa_jack *jack);
-
-/* Query all jacks in the list and report the state to the callback.
- * Args:
- * jack_list - The jack list to query.
- */
-void cras_alsa_jack_list_report(const struct cras_alsa_jack_list *jack_list);
-
-/* Gets the name of a jack.
- * Args:
- * jack_list - The jack list to query.
- */
-const char *cras_alsa_jack_get_name(const struct cras_alsa_jack *jack);
-
-/* Gets the ucm device of a jack.
- * Args:
- * jack - The alsa jack.
- */
-const char *cras_alsa_jack_get_ucm_device(const struct cras_alsa_jack *jack);
-
-void cras_alsa_jack_update_monitor_name(const struct cras_alsa_jack *jack,
- char *name_buf, unsigned int buf_size);
-
-/* Updates the node type according to override_type_name in jack.
- * Currently this method only supports updating the node type to
- * CRAS_NODE_TYPE_INTERNAL_SPEAKER when override_type_name is
- * "Internal Speaker". This is used in All-In-One device where
- * output is an HDMI device, but it should be internal speaker from
- * user point of view.
- * Args:
- * jack - The jack to query node type.
- * type - The node type to be overwritten.
- */
-void cras_alsa_jack_update_node_type(const struct cras_alsa_jack *jack,
- enum CRAS_NODE_TYPE *type);
-
-/* Enables the ucm device for this jack if any.
- * Args:
- * jack - The jack to query for a mixer output.
- */
-void cras_alsa_jack_enable_ucm(const struct cras_alsa_jack *jack, int enable);
-
-/* Find out whether the specified card has a jack with the given name.
- * Args:
- * card_index - Index ALSA uses to refer to the card. The X in "hw:X".
- * jack_name - The name of the jack (for example, "Speaker Phantom Jack").
- */
-int cras_alsa_jack_exists(unsigned int card_index, const char *jack_name);
-
-#endif /* CRAS_ALSA_JACK_H_ */
diff --git a/cras/src/server/cras_alsa_mixer.c b/cras/src/server/cras_alsa_mixer.c
deleted file mode 100644
index 3379d959..00000000
--- a/cras/src/server/cras_alsa_mixer.c
+++ /dev/null
@@ -1,1174 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <limits.h>
-#include <stdio.h>
-#include <syslog.h>
-
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_mixer_name.h"
-#include "cras_alsa_ucm.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-#define MIXER_CONTROL_VOLUME_DB_INVALID LONG_MAX
-
-/* Represents an ALSA control element. Each device can have several of these,
- * each potentially having independent volume and mute controls.
- * elem - ALSA mixer element.
- * has_volume - non-zero indicates there is a volume control.
- * has_mute - non-zero indicates there is a mute switch.
- * max_volume_dB - the maximum volume for this control, or
- * MIXER_CONTROL_VOLUME_DB_INVALID.
- * min_volume_dB - the minimum volume for this control, or
- * MIXER_CONTROL_VOLUME_DB_INVALID.
- */
-struct mixer_control_element {
- snd_mixer_elem_t *elem;
- int has_volume;
- int has_mute;
- long max_volume_dB;
- long min_volume_dB;
- struct mixer_control_element *prev, *next;
-};
-
-/* Represents an ALSA control element related to a specific input/output
- * node such as speakers or headphones. A device can have several of these,
- * each potentially having independent volume and mute controls.
- *
- * Each will have at least one mixer_control_element. For cases where there
- * are separate control elements for left/right channels (for example),
- * additional mixer_control_elements are added.
- *
- * For controls with volume it is assumed that all elements have the same
- * range.
- *
- * name - Name of the control (typicially this is the same as the name of the
- * mixer_control_element when there is one, or the name of the UCM
- * parent when there are multiple).
- * dir - Control direction, OUTPUT or INPUT only.
- * elements - The mixer_control_elements that are driven by this control.
- * has_volume - non-zero indicates there is a volume control.
- * has_mute - non-zero indicates there is a mute switch.
- * max_volume_dB - Maximum volume available in the volume control.
- * min_volume_dB - Minimum volume available in the volume control.
- */
-struct mixer_control {
- const char *name;
- enum CRAS_STREAM_DIRECTION dir;
- struct mixer_control_element *elements;
- int has_volume;
- int has_mute;
- long max_volume_dB;
- long min_volume_dB;
- struct mixer_control *prev, *next;
-};
-
-/* Holds a reference to the opened mixer and the volume controls.
- * mixer - Pointer to the opened alsa mixer.
- * main_volume_controls - List of volume controls (normally 'Master' and 'PCM').
- * playback_switch - Switch used to mute the device.
- * main_capture_controls - List of capture gain controls (normally 'Capture').
- * capture_switch - Switch used to mute the capture stream.
- * max_volume_dB - Maximum volume available in main volume controls. The dBFS
- * value setting will be applied relative to this.
- * min_volume_dB - Minimum volume available in main volume controls.
- */
-struct cras_alsa_mixer {
- snd_mixer_t *mixer;
- struct mixer_control *main_volume_controls;
- struct mixer_control *output_controls;
- snd_mixer_elem_t *playback_switch;
- struct mixer_control *main_capture_controls;
- struct mixer_control *input_controls;
- snd_mixer_elem_t *capture_switch;
- long max_volume_dB;
- long min_volume_dB;
-};
-
-/* Wrapper for snd_mixer_open and helpers.
- * Args:
- * mixdev - Name of the device to open the mixer for.
- * mixer - Pointer filled with the opened mixer on success, NULL on failure.
- */
-static void alsa_mixer_open(const char *mixdev, snd_mixer_t **mixer)
-{
- int rc;
-
- *mixer = NULL;
- rc = snd_mixer_open(mixer, 0);
- if (rc < 0) {
- syslog(LOG_ERR, "snd_mixer_open: %d: %s", rc, strerror(-rc));
- return;
- }
- rc = snd_mixer_attach(*mixer, mixdev);
- if (rc < 0) {
- syslog(LOG_ERR, "snd_mixer_attach: %d: %s", rc, strerror(-rc));
- goto fail_after_open;
- }
- rc = snd_mixer_selem_register(*mixer, NULL, NULL);
- if (rc < 0) {
- syslog(LOG_ERR, "snd_mixer_selem_register: %d: %s", rc,
- strerror(-rc));
- goto fail_after_open;
- }
- rc = snd_mixer_load(*mixer);
- if (rc < 0) {
- syslog(LOG_ERR, "snd_mixer_load: %d: %s", rc, strerror(-rc));
- goto fail_after_open;
- }
- return;
-
-fail_after_open:
- snd_mixer_close(*mixer);
- *mixer = NULL;
-}
-
-static struct mixer_control_element *
-mixer_control_element_create(snd_mixer_elem_t *elem,
- enum CRAS_STREAM_DIRECTION dir)
-{
- struct mixer_control_element *c;
- long min, max;
-
- if (!elem)
- return NULL;
-
- c = (struct mixer_control_element *)calloc(1, sizeof(*c));
- if (!c) {
- syslog(LOG_ERR, "No memory for mixer_control_elem.");
- return NULL;
- }
-
- c->elem = elem;
- c->max_volume_dB = MIXER_CONTROL_VOLUME_DB_INVALID;
- c->min_volume_dB = MIXER_CONTROL_VOLUME_DB_INVALID;
-
- if (dir == CRAS_STREAM_OUTPUT) {
- c->has_mute = snd_mixer_selem_has_playback_switch(elem);
-
- if (snd_mixer_selem_has_playback_volume(elem) &&
- snd_mixer_selem_get_playback_dB_range(elem, &min, &max) ==
- 0) {
- c->max_volume_dB = max;
- c->min_volume_dB = min;
- c->has_volume = 1;
- }
- } else if (dir == CRAS_STREAM_INPUT) {
- c->has_mute = snd_mixer_selem_has_capture_switch(elem);
-
- if (snd_mixer_selem_has_capture_volume(elem) &&
- snd_mixer_selem_get_capture_dB_range(elem, &min, &max) ==
- 0) {
- c->max_volume_dB = max;
- c->min_volume_dB = min;
- c->has_volume = 1;
- }
- }
-
- return c;
-}
-
-static void mixer_control_destroy(struct mixer_control *control)
-{
- struct mixer_control_element *elem;
-
- if (!control)
- return;
-
- DL_FOREACH (control->elements, elem) {
- DL_DELETE(control->elements, elem);
- free(elem);
- }
- if (control->name)
- free((void *)control->name);
- free(control);
-}
-
-static void mixer_control_destroy_list(struct mixer_control *control_list)
-{
- struct mixer_control *control;
- if (!control_list)
- return;
- DL_FOREACH (control_list, control) {
- DL_DELETE(control_list, control);
- mixer_control_destroy(control);
- }
-}
-
-static int mixer_control_add_element(struct mixer_control *control,
- snd_mixer_elem_t *snd_elem)
-{
- struct mixer_control_element *elem;
-
- if (!control)
- return -EINVAL;
-
- elem = mixer_control_element_create(snd_elem, control->dir);
- if (!elem)
- return -ENOMEM;
-
- DL_APPEND(control->elements, elem);
-
- if (elem->has_volume) {
- if (!control->has_volume)
- control->has_volume = 1;
-
- /* Assume that all elements have a common volume range, and
- * that both min and max values are valid if one of the two
- * is valid. */
- if (control->min_volume_dB == MIXER_CONTROL_VOLUME_DB_INVALID) {
- control->min_volume_dB = elem->min_volume_dB;
- control->max_volume_dB = elem->max_volume_dB;
- } else if (control->min_volume_dB != elem->min_volume_dB ||
- control->max_volume_dB != elem->max_volume_dB) {
- syslog(LOG_WARNING,
- "Element '%s' of control '%s' has different"
- "volume range: [%ld:%ld] ctrl: [%ld:%ld]",
- snd_mixer_selem_get_name(elem->elem),
- control->name, elem->min_volume_dB,
- elem->max_volume_dB, control->min_volume_dB,
- control->max_volume_dB);
- }
- }
-
- if (elem->has_mute && !control->has_mute)
- control->has_mute = 1;
- return 0;
-}
-
-static int mixer_control_create(struct mixer_control **control,
- const char *name, snd_mixer_elem_t *elem,
- enum CRAS_STREAM_DIRECTION dir)
-{
- struct mixer_control *c;
- int rc = 0;
-
- if (!control)
- return -EINVAL;
-
- c = (struct mixer_control *)calloc(1, sizeof(*c));
- if (!c) {
- syslog(LOG_ERR, "No memory for mixer_control: %s", name);
- rc = -ENOMEM;
- goto error;
- }
-
- c->dir = dir;
- c->min_volume_dB = MIXER_CONTROL_VOLUME_DB_INVALID;
- c->max_volume_dB = MIXER_CONTROL_VOLUME_DB_INVALID;
-
- if (!name && elem)
- name = snd_mixer_selem_get_name(elem);
- if (!name) {
- syslog(LOG_ERR, "Control does not have a name.");
- rc = -EINVAL;
- goto error;
- }
-
- c->name = strdup(name);
- if (!c->name) {
- syslog(LOG_ERR, "No memory for control's name: %s", name);
- rc = -ENOMEM;
- goto error;
- }
-
- if (elem && (rc = mixer_control_add_element(c, elem)))
- goto error;
-
- *control = c;
- return 0;
-
-error:
- mixer_control_destroy(c);
- *control = NULL;
- return rc;
-}
-
-/* Creates a mixer_control by finding mixer element names in simple mixer
- * interface.
- * Args:
- * control[out] - Storage for resulting pointer to mixer_control.
- * cmix[in] - Parent alsa mixer.
- * name[in] - Optional name of the control. Input NULL to take the name of
- * the first element from mixer_names.
- * mixer_names[in] - Names of the ASLA mixer control elements. Must not
- * be empty.
- * dir[in] - Control direction: CRAS_STREAM_OUTPUT or CRAS_STREAM_INPUT.
- * Returns:
- * Returns 0 for success, negative error code otherwise. *control is
- * initialized to NULL on error, or has a valid pointer for success.
- */
-static int mixer_control_create_by_name(struct mixer_control **control,
- struct cras_alsa_mixer *cmix,
- const char *name,
- struct mixer_name *mixer_names,
- enum CRAS_STREAM_DIRECTION dir)
-{
- snd_mixer_selem_id_t *sid;
- snd_mixer_elem_t *elem;
- struct mixer_control *c;
- struct mixer_name *m_name;
- int rc;
-
- if (!control)
- return -EINVAL;
- *control = NULL;
- if (!mixer_names)
- return -EINVAL;
- if (!name) {
- /* Assume that we're using the first name in the list of mixer
- * names. */
- name = mixer_names->name;
- }
-
- rc = mixer_control_create(&c, name, NULL, dir);
- if (rc)
- return rc;
-
- snd_mixer_selem_id_malloc(&sid);
-
- DL_FOREACH (mixer_names, m_name) {
- snd_mixer_selem_id_set_index(sid, 0);
- snd_mixer_selem_id_set_name(sid, m_name->name);
- elem = snd_mixer_find_selem(cmix->mixer, sid);
- if (!elem) {
- mixer_control_destroy(c);
- snd_mixer_selem_id_free(sid);
- syslog(LOG_ERR, "Unable to find simple control %s, 0",
- m_name->name);
- return -ENOENT;
- }
- rc = mixer_control_add_element(c, elem);
- if (rc) {
- mixer_control_destroy(c);
- snd_mixer_selem_id_free(sid);
- return rc;
- }
- }
-
- snd_mixer_selem_id_free(sid);
- *control = c;
- return 0;
-}
-
-static int mixer_control_set_dBFS(const struct mixer_control *control,
- long to_set)
-{
- const struct mixer_control_element *elem = NULL;
- int rc = -EINVAL;
- if (!control)
- return rc;
- DL_FOREACH (control->elements, elem) {
- if (elem->has_volume) {
- if (control->dir == CRAS_STREAM_OUTPUT)
- rc = snd_mixer_selem_set_playback_dB_all(
- elem->elem, to_set, 1);
- else if (control->dir == CRAS_STREAM_INPUT)
- rc = snd_mixer_selem_set_capture_dB_all(
- elem->elem, to_set, 1);
- if (rc)
- break;
- syslog(LOG_DEBUG, "%s:%s volume set to %ld",
- control->name,
- snd_mixer_selem_get_name(elem->elem), to_set);
- }
- }
- if (rc && elem) {
- syslog(LOG_ERR, "Failed to set volume of '%s:%s': %d",
- control->name, snd_mixer_selem_get_name(elem->elem), rc);
- }
- return rc;
-}
-
-static int mixer_control_get_dBFS(const struct mixer_control *control,
- long *to_get)
-{
- const struct mixer_control_element *elem = NULL;
- int rc = -EINVAL;
- if (!control || !to_get)
- return -EINVAL;
- DL_FOREACH (control->elements, elem) {
- if (elem->has_volume) {
- if (control->dir == CRAS_STREAM_OUTPUT)
- rc = snd_mixer_selem_get_playback_dB(
- elem->elem, SND_MIXER_SCHN_FRONT_LEFT,
- to_get);
- else if (control->dir == CRAS_STREAM_INPUT)
- rc = snd_mixer_selem_get_capture_dB(
- elem->elem, SND_MIXER_SCHN_FRONT_LEFT,
- to_get);
- /* Assume all of the elements of this control have
- * the same value. */
- break;
- }
- }
- if (rc && elem) {
- syslog(LOG_ERR, "Failed to get volume of '%s:%s': %d",
- control->name, snd_mixer_selem_get_name(elem->elem), rc);
- }
- return rc;
-}
-
-static int mixer_control_set_mute(const struct mixer_control *control,
- int muted)
-{
- const struct mixer_control_element *elem = NULL;
- int rc = -EINVAL;
- if (!control)
- return -EINVAL;
- DL_FOREACH (control->elements, elem) {
- if (elem->has_mute) {
- if (control->dir == CRAS_STREAM_OUTPUT)
- rc = snd_mixer_selem_set_playback_switch_all(
- elem->elem, !muted);
- else if (control->dir == CRAS_STREAM_INPUT)
- rc = snd_mixer_selem_set_capture_switch_all(
- elem->elem, !muted);
- if (rc)
- break;
- }
- }
- if (rc && elem) {
- syslog(LOG_ERR, "Failed to mute '%s:%s': %d", control->name,
- snd_mixer_selem_get_name(elem->elem), rc);
- }
- return rc;
-}
-
-/* Adds the main volume control to the list and grabs the first seen playback
- * switch to use for mute. */
-static int add_main_volume_control(struct cras_alsa_mixer *cmix,
- snd_mixer_elem_t *elem)
-{
- if (snd_mixer_selem_has_playback_volume(elem)) {
- long range;
- struct mixer_control *c, *next;
- int rc = mixer_control_create(&c, NULL, elem,
- CRAS_STREAM_OUTPUT);
- if (rc)
- return rc;
-
- if (c->has_volume) {
- cmix->max_volume_dB += c->max_volume_dB;
- cmix->min_volume_dB += c->min_volume_dB;
- }
-
- range = c->max_volume_dB - c->min_volume_dB;
- DL_FOREACH (cmix->main_volume_controls, next) {
- if (range > next->max_volume_dB - next->min_volume_dB)
- break;
- }
-
- syslog(LOG_DEBUG, "Add main volume control %s\n", c->name);
- DL_INSERT(cmix->main_volume_controls, next, c);
- }
-
- /* If cmix doesn't yet have a playback switch and this is a playback
- * switch, use it. */
- if (cmix->playback_switch == NULL &&
- snd_mixer_selem_has_playback_switch(elem)) {
- syslog(LOG_DEBUG, "Using '%s' as playback switch.",
- snd_mixer_selem_get_name(elem));
- cmix->playback_switch = elem;
- }
-
- return 0;
-}
-
-/* Adds the main capture control to the list and grabs the first seen capture
- * switch to mute input. */
-static int add_main_capture_control(struct cras_alsa_mixer *cmix,
- snd_mixer_elem_t *elem)
-{
- /* TODO(dgreid) handle index != 0, map to correct input. */
- if (snd_mixer_selem_get_index(elem) > 0)
- return 0;
-
- if (snd_mixer_selem_has_capture_volume(elem)) {
- struct mixer_control *c;
- int rc =
- mixer_control_create(&c, NULL, elem, CRAS_STREAM_INPUT);
- if (rc)
- return rc;
-
- syslog(LOG_DEBUG, "Add main capture control %s\n", c->name);
- DL_APPEND(cmix->main_capture_controls, c);
- }
-
- /* If cmix doesn't yet have a capture switch and this is a capture
- * switch, use it. */
- if (cmix->capture_switch == NULL &&
- snd_mixer_selem_has_capture_switch(elem)) {
- syslog(LOG_DEBUG, "Using '%s' as capture switch.",
- snd_mixer_selem_get_name(elem));
- cmix->capture_switch = elem;
- }
-
- return 0;
-}
-
-/* Adds a control to the list. */
-static int add_control_with_name(struct cras_alsa_mixer *cmix,
- enum CRAS_STREAM_DIRECTION dir,
- snd_mixer_elem_t *elem, const char *name)
-{
- int index; /* Index part of mixer simple element */
- struct mixer_control *c;
- int rc;
-
- index = snd_mixer_selem_get_index(elem);
- syslog(LOG_DEBUG, "Add %s control: %s,%d\n",
- dir == CRAS_STREAM_OUTPUT ? "output" : "input", name, index);
-
- rc = mixer_control_create(&c, name, elem, dir);
- if (rc)
- return rc;
-
- if (c->has_volume)
- syslog(LOG_DEBUG, "Control '%s' volume range: [%ld:%ld]",
- c->name, c->min_volume_dB, c->max_volume_dB);
-
- if (dir == CRAS_STREAM_OUTPUT)
- DL_APPEND(cmix->output_controls, c);
- else if (dir == CRAS_STREAM_INPUT)
- DL_APPEND(cmix->input_controls, c);
- return 0;
-}
-
-static int add_control(struct cras_alsa_mixer *cmix,
- enum CRAS_STREAM_DIRECTION dir, snd_mixer_elem_t *elem)
-{
- return add_control_with_name(cmix, dir, elem,
- snd_mixer_selem_get_name(elem));
-}
-
-static void list_controls(struct mixer_control *control_list,
- cras_alsa_mixer_control_callback cb, void *cb_arg)
-{
- struct mixer_control *control;
-
- DL_FOREACH (control_list, control)
- cb(control, cb_arg);
-}
-
-static struct mixer_control *
-get_control_matching_name(struct mixer_control *control_list, const char *name)
-{
- struct mixer_control *c;
-
- DL_FOREACH (control_list, c) {
- if (strstr(name, c->name))
- return c;
- }
- return NULL;
-}
-
-/* Creates a mixer_control with multiple control elements. */
-static int add_control_with_coupled_mixers(struct cras_alsa_mixer *cmix,
- enum CRAS_STREAM_DIRECTION dir,
- const char *name,
- struct mixer_name *coupled_controls)
-{
- struct mixer_control *c;
- int rc;
-
- rc = mixer_control_create_by_name(&c, cmix, name, coupled_controls,
- dir);
- if (rc)
- return rc;
- syslog(LOG_DEBUG, "Add %s control: %s\n",
- dir == CRAS_STREAM_OUTPUT ? "output" : "input", c->name);
- mixer_name_dump(coupled_controls, " elements");
-
- if (c->has_volume)
- syslog(LOG_DEBUG, "Control '%s' volume range: [%ld:%ld]",
- c->name, c->min_volume_dB, c->max_volume_dB);
-
- if (dir == CRAS_STREAM_OUTPUT)
- DL_APPEND(cmix->output_controls, c);
- else if (dir == CRAS_STREAM_INPUT)
- DL_APPEND(cmix->input_controls, c);
- return 0;
-}
-
-static int add_control_by_name(struct cras_alsa_mixer *cmix,
- enum CRAS_STREAM_DIRECTION dir, const char *name)
-{
- struct mixer_control *c;
- struct mixer_name *m_name;
- int rc;
-
- m_name = mixer_name_add(NULL, name, dir, MIXER_NAME_VOLUME);
- if (!m_name)
- return -ENOMEM;
-
- rc = mixer_control_create_by_name(&c, cmix, name, m_name, dir);
- mixer_name_free(m_name);
- if (rc)
- return rc;
- syslog(LOG_DEBUG, "Add %s control: %s\n",
- dir == CRAS_STREAM_OUTPUT ? "output" : "input", c->name);
-
- if (c->has_volume)
- syslog(LOG_DEBUG, "Control '%s' volume range: [%ld:%ld]",
- c->name, c->min_volume_dB, c->max_volume_dB);
-
- if (dir == CRAS_STREAM_OUTPUT)
- DL_APPEND(cmix->output_controls, c);
- else if (dir == CRAS_STREAM_INPUT)
- DL_APPEND(cmix->input_controls, c);
- return 0;
-}
-
-/*
- * Exported interface.
- */
-
-struct cras_alsa_mixer *cras_alsa_mixer_create(const char *card_name)
-{
- struct cras_alsa_mixer *cmix;
-
- cmix = (struct cras_alsa_mixer *)calloc(1, sizeof(*cmix));
- if (cmix == NULL)
- return NULL;
-
- syslog(LOG_DEBUG, "Add mixer for device %s", card_name);
-
- alsa_mixer_open(card_name, &cmix->mixer);
-
- return cmix;
-}
-
-int cras_alsa_mixer_add_controls_by_name_matching(
- struct cras_alsa_mixer *cmix, struct mixer_name *extra_controls,
- struct mixer_name *coupled_controls)
-{
- /* Names of controls for main system volume. */
- static const char *const main_volume_names[] = {
- "Master",
- "Digital",
- "PCM",
- };
- /* Names of controls for individual outputs. */
- static const char *const output_names[] = {
- "Headphone",
- "Headset",
- "HDMI",
- "Speaker",
- };
- /* Names of controls for capture gain/attenuation and mute. */
- static const char *const main_capture_names[] = {
- "Capture",
- "Digital Capture",
- };
- /* Names of controls for individual inputs. */
- static const char *const input_names[] = {
- "Mic",
- "Microphone",
- };
-
- struct mixer_name *default_controls = NULL;
- snd_mixer_elem_t *elem;
- int extra_main_volume = 0;
- snd_mixer_elem_t *other_elem = NULL;
- long other_dB_range = 0;
- int rc = 0;
-
- /* Note that there is no mixer on some cards. This is acceptable. */
- if (cmix->mixer == NULL) {
- syslog(LOG_DEBUG, "Couldn't open mixer.");
- return 0;
- }
-
- default_controls =
- mixer_name_add_array(default_controls, output_names,
- ARRAY_SIZE(output_names),
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- default_controls =
- mixer_name_add_array(default_controls, input_names,
- ARRAY_SIZE(input_names), CRAS_STREAM_INPUT,
- MIXER_NAME_VOLUME);
- default_controls =
- mixer_name_add_array(default_controls, main_volume_names,
- ARRAY_SIZE(main_volume_names),
- CRAS_STREAM_OUTPUT,
- MIXER_NAME_MAIN_VOLUME);
- default_controls =
- mixer_name_add_array(default_controls, main_capture_names,
- ARRAY_SIZE(main_capture_names),
- CRAS_STREAM_INPUT, MIXER_NAME_MAIN_VOLUME);
- extra_main_volume =
- mixer_name_find(extra_controls, NULL, CRAS_STREAM_OUTPUT,
- MIXER_NAME_MAIN_VOLUME) != NULL;
-
- /* Find volume and mute controls. */
- for (elem = snd_mixer_first_elem(cmix->mixer); elem != NULL;
- elem = snd_mixer_elem_next(elem)) {
- const char *name;
- struct mixer_name *control;
- int found = 0;
-
- name = snd_mixer_selem_get_name(elem);
- if (name == NULL)
- continue;
-
- /* Find a matching control. */
- control = mixer_name_find(default_controls, name,
- CRAS_STREAM_OUTPUT,
- MIXER_NAME_UNDEFINED);
-
- /* If our extra controls contain a main volume
- * entry, and we found a main volume entry, then
- * skip it. */
- if (extra_main_volume && control &&
- control->type == MIXER_NAME_MAIN_VOLUME)
- control = NULL;
-
- /* If we didn't match any of the defaults, match
- * the extras list. */
- if (!control)
- control = mixer_name_find(extra_controls, name,
- CRAS_STREAM_OUTPUT,
- MIXER_NAME_UNDEFINED);
-
- if (control) {
- int rc = -1;
- switch (control->type) {
- case MIXER_NAME_MAIN_VOLUME:
- rc = add_main_volume_control(cmix, elem);
- break;
- case MIXER_NAME_VOLUME:
- /* TODO(dgreid) - determine device index. */
- rc = add_control(cmix, CRAS_STREAM_OUTPUT,
- elem);
- break;
- case MIXER_NAME_UNDEFINED:
- rc = -EINVAL;
- break;
- }
- if (rc) {
- syslog(LOG_ERR,
- "Failed to add mixer control '%s'"
- " with type '%d'",
- control->name, control->type);
- goto out;
- }
- found = 1;
- }
-
- /* Find a matching input control. */
- control = mixer_name_find(default_controls, name,
- CRAS_STREAM_INPUT,
- MIXER_NAME_UNDEFINED);
-
- /* If we didn't match any of the defaults, match
- the extras list */
- if (!control)
- control = mixer_name_find(extra_controls, name,
- CRAS_STREAM_INPUT,
- MIXER_NAME_UNDEFINED);
-
- if (control) {
- int rc = -1;
- switch (control->type) {
- case MIXER_NAME_MAIN_VOLUME:
- rc = add_main_capture_control(cmix, elem);
- break;
- case MIXER_NAME_VOLUME:
- rc = add_control(cmix, CRAS_STREAM_INPUT, elem);
- break;
- case MIXER_NAME_UNDEFINED:
- rc = -EINVAL;
- break;
- }
- if (rc) {
- syslog(LOG_ERR,
- "Failed to add mixer control '%s'"
- " with type '%d'",
- control->name, control->type);
- goto out;
- }
- found = 1;
- }
-
- if (!found && snd_mixer_selem_has_playback_volume(elem)) {
- /* Temporarily cache one elem whose name is not
- * in the list above, but has a playback volume
- * control and the largest volume range. */
- long min, max, range;
- if (snd_mixer_selem_get_playback_dB_range(elem, &min,
- &max) != 0)
- continue;
-
- range = max - min;
- if (other_dB_range < range) {
- other_dB_range = range;
- other_elem = elem;
- }
- }
- }
-
- /* Handle coupled output names for speaker */
- if (coupled_controls) {
- rc = add_control_with_coupled_mixers(
- cmix, CRAS_STREAM_OUTPUT, "Speaker", coupled_controls);
- if (rc) {
- syslog(LOG_ERR, "Could not add coupled output");
- goto out;
- }
- }
-
- /* If there is no volume control and output control found,
- * use the volume control which has the largest volume range
- * in the mixer as a main volume control. */
- if (!cmix->main_volume_controls && !cmix->output_controls &&
- other_elem) {
- rc = add_main_volume_control(cmix, other_elem);
- if (rc) {
- syslog(LOG_ERR, "Could not add other volume control");
- goto out;
- }
- }
-
-out:
- mixer_name_free(default_controls);
- return rc;
-}
-
-int cras_alsa_mixer_add_main_volume_control_by_name(
- struct cras_alsa_mixer *cmix, struct mixer_name *mixer_names)
-{
- snd_mixer_elem_t *elem;
- struct mixer_name *m_name;
- int rc = 0;
- snd_mixer_selem_id_t *sid;
-
- if (!mixer_names)
- return -EINVAL;
-
- snd_mixer_selem_id_malloc(&sid);
-
- DL_FOREACH (mixer_names, m_name) {
- snd_mixer_selem_id_set_index(sid, 0);
- snd_mixer_selem_id_set_name(sid, m_name->name);
- elem = snd_mixer_find_selem(cmix->mixer, sid);
- if (!elem) {
- rc = -ENOENT;
- syslog(LOG_ERR, "Unable to find simple control %s, 0",
- m_name->name);
- break;
- }
- rc = add_main_volume_control(cmix, elem);
- if (rc)
- break;
- }
-
- snd_mixer_selem_id_free(sid);
- return rc;
-}
-
-int cras_alsa_mixer_add_controls_in_section(struct cras_alsa_mixer *cmix,
- struct ucm_section *section)
-{
- int rc;
-
- /* Note that there is no mixer on some cards. This is acceptable. */
- if (cmix->mixer == NULL) {
- syslog(LOG_DEBUG, "Couldn't open mixer.");
- return 0;
- }
-
- if (!section) {
- syslog(LOG_ERR, "No UCM SectionDevice specified.");
- return -EINVAL;
- }
-
- /* TODO(muirj) - Extra main volume controls when fully-specified. */
-
- if (section->mixer_name) {
- rc = add_control_by_name(cmix, section->dir,
- section->mixer_name);
- if (rc) {
- syslog(LOG_ERR, "Could not add mixer control '%s': %s",
- section->mixer_name, strerror(-rc));
- return rc;
- }
- }
-
- if (section->coupled) {
- rc = add_control_with_coupled_mixers(
- cmix, section->dir, section->name, section->coupled);
- if (rc) {
- syslog(LOG_ERR, "Could not add coupled control: %s",
- strerror(-rc));
- return rc;
- }
- }
- return 0;
-}
-
-void cras_alsa_mixer_destroy(struct cras_alsa_mixer *cras_mixer)
-{
- assert(cras_mixer);
-
- mixer_control_destroy_list(cras_mixer->main_volume_controls);
- mixer_control_destroy_list(cras_mixer->main_capture_controls);
- mixer_control_destroy_list(cras_mixer->output_controls);
- mixer_control_destroy_list(cras_mixer->input_controls);
- if (cras_mixer->mixer)
- snd_mixer_close(cras_mixer->mixer);
- free(cras_mixer);
-}
-
-int cras_alsa_mixer_has_main_volume(const struct cras_alsa_mixer *cras_mixer)
-{
- return !!cras_mixer->main_volume_controls;
-}
-
-int cras_alsa_mixer_has_volume(const struct mixer_control *mixer_control)
-{
- return mixer_control && mixer_control->has_volume;
-}
-
-void cras_alsa_mixer_set_dBFS(struct cras_alsa_mixer *cras_mixer, long dBFS,
- struct mixer_control *mixer_output)
-{
- struct mixer_control *c;
- long to_set;
-
- assert(cras_mixer);
-
- /* dBFS is normally < 0 to specify the attenuation from max. max is the
- * combined max of the main controls and the current output.
- */
- to_set = dBFS + cras_mixer->max_volume_dB;
- if (cras_alsa_mixer_has_volume(mixer_output))
- to_set += mixer_output->max_volume_dB;
- /* Go through all the controls, set the volume level for each,
- * taking the value closest but greater than the desired volume. If the
- * entire volume can't be set on the current control, move on to the
- * next one until we have the exact volume, or gotten as close as we
- * can. Once all of the volume is set the rest of the controls should be
- * set to 0dB. */
- DL_FOREACH (cras_mixer->main_volume_controls, c) {
- long actual_dB;
-
- if (!c->has_volume)
- continue;
- if (mixer_control_set_dBFS(c, to_set) == 0 &&
- mixer_control_get_dBFS(c, &actual_dB) == 0)
- to_set -= actual_dB;
- }
- /* Apply the rest to the output-specific control. */
- if (cras_alsa_mixer_has_volume(mixer_output))
- mixer_control_set_dBFS(mixer_output, to_set);
-}
-
-long cras_alsa_mixer_get_dB_range(struct cras_alsa_mixer *cras_mixer)
-{
- if (!cras_mixer)
- return 0;
- return cras_mixer->max_volume_dB - cras_mixer->min_volume_dB;
-}
-
-long cras_alsa_mixer_get_output_dB_range(struct mixer_control *mixer_output)
-{
- if (!cras_alsa_mixer_has_volume(mixer_output))
- return 0;
-
- return mixer_output->max_volume_dB - mixer_output->min_volume_dB;
-}
-
-void cras_alsa_mixer_set_capture_dBFS(struct cras_alsa_mixer *cras_mixer,
- long dBFS,
- struct mixer_control *mixer_input)
-{
- struct mixer_control *c;
- long to_set;
-
- assert(cras_mixer);
- to_set = dBFS;
- /* Go through all the controls, set the gain for each, taking the value
- * closest but greater than the desired gain. If the entire gain can't
- * be set on the current control, move on to the next one until we have
- * the exact gain, or gotten as close as we can. Once all of the gain is
- * set the rest of the controls should be set to 0dB. */
- DL_FOREACH (cras_mixer->main_capture_controls, c) {
- long actual_dB;
-
- if (!c->has_volume)
- continue;
- if (mixer_control_set_dBFS(c, to_set) == 0 &&
- mixer_control_get_dBFS(c, &actual_dB) == 0)
- to_set -= actual_dB;
- }
-
- /* Apply the reset to input specific control */
- if (cras_alsa_mixer_has_volume(mixer_input))
- mixer_control_set_dBFS(mixer_input, to_set);
-}
-
-long cras_alsa_mixer_get_minimum_capture_gain(struct cras_alsa_mixer *cmix,
- struct mixer_control *mixer_input)
-{
- struct mixer_control *c;
- long total_min = 0;
-
- assert(cmix);
- DL_FOREACH (cmix->main_capture_controls, c)
- if (c->has_volume)
- total_min += c->min_volume_dB;
- if (mixer_input && mixer_input->has_volume)
- total_min += mixer_input->min_volume_dB;
-
- return total_min;
-}
-
-long cras_alsa_mixer_get_maximum_capture_gain(struct cras_alsa_mixer *cmix,
- struct mixer_control *mixer_input)
-{
- struct mixer_control *c;
- long total_max = 0;
-
- assert(cmix);
- DL_FOREACH (cmix->main_capture_controls, c)
- if (c->has_volume)
- total_max += c->max_volume_dB;
-
- if (mixer_input && mixer_input->has_volume)
- total_max += mixer_input->max_volume_dB;
-
- return total_max;
-}
-
-void cras_alsa_mixer_set_mute(struct cras_alsa_mixer *cras_mixer, int muted,
- struct mixer_control *mixer_output)
-{
- assert(cras_mixer);
-
- if (cras_mixer->playback_switch) {
- snd_mixer_selem_set_playback_switch_all(
- cras_mixer->playback_switch, !muted);
- }
- if (mixer_output && mixer_output->has_mute) {
- mixer_control_set_mute(mixer_output, muted);
- }
-}
-
-void cras_alsa_mixer_set_capture_mute(struct cras_alsa_mixer *cras_mixer,
- int muted,
- struct mixer_control *mixer_input)
-{
- assert(cras_mixer);
- if (cras_mixer->capture_switch) {
- snd_mixer_selem_set_capture_switch_all(
- cras_mixer->capture_switch, !muted);
- return;
- }
- if (mixer_input && mixer_input->has_mute)
- mixer_control_set_mute(mixer_input, muted);
-}
-
-void cras_alsa_mixer_list_outputs(struct cras_alsa_mixer *cras_mixer,
- cras_alsa_mixer_control_callback cb,
- void *cb_arg)
-{
- assert(cras_mixer);
- list_controls(cras_mixer->output_controls, cb, cb_arg);
-}
-
-void cras_alsa_mixer_list_inputs(struct cras_alsa_mixer *cras_mixer,
- cras_alsa_mixer_control_callback cb,
- void *cb_arg)
-{
- assert(cras_mixer);
- list_controls(cras_mixer->input_controls, cb, cb_arg);
-}
-
-const char *
-cras_alsa_mixer_get_control_name(const struct mixer_control *control)
-{
- if (!control)
- return NULL;
- return control->name;
-}
-
-struct mixer_control *
-cras_alsa_mixer_get_control_matching_name(struct cras_alsa_mixer *cras_mixer,
- enum CRAS_STREAM_DIRECTION dir,
- const char *name, int create_missing)
-{
- struct mixer_control *c;
-
- assert(cras_mixer);
- if (!name)
- return NULL;
-
- if (dir == CRAS_STREAM_OUTPUT) {
- c = get_control_matching_name(cras_mixer->output_controls,
- name);
- } else if (dir == CRAS_STREAM_INPUT) {
- c = get_control_matching_name(cras_mixer->input_controls, name);
- } else {
- return NULL;
- }
-
- /* TODO: Allowing creation of a new control is a workaround: we
- * should pass the input names in ucm config to
- * cras_alsa_mixer_create. */
- if (!c && cras_mixer->mixer && create_missing) {
- int rc = add_control_by_name(cras_mixer, dir, name);
- if (rc)
- return NULL;
- c = cras_alsa_mixer_get_control_matching_name(cras_mixer, dir,
- name, 0);
- }
- return c;
-}
-
-struct mixer_control *
-cras_alsa_mixer_get_control_for_section(struct cras_alsa_mixer *cras_mixer,
- const struct ucm_section *section)
-{
- assert(cras_mixer && section);
- if (section->mixer_name) {
- return cras_alsa_mixer_get_control_matching_name(
- cras_mixer, section->dir, section->mixer_name, 0);
- } else if (section->coupled) {
- return cras_alsa_mixer_get_control_matching_name(
- cras_mixer, section->dir, section->name, 0);
- }
- return NULL;
-}
-
-struct mixer_control *
-cras_alsa_mixer_get_output_matching_name(struct cras_alsa_mixer *cras_mixer,
- const char *const name)
-{
- return cras_alsa_mixer_get_control_matching_name(
- cras_mixer, CRAS_STREAM_OUTPUT, name, 0);
-}
-
-struct mixer_control *
-cras_alsa_mixer_get_input_matching_name(struct cras_alsa_mixer *cras_mixer,
- const char *name)
-{
- /* TODO: Allowing creation of a new control is a workaround: we
- * should pass the input names in ucm config to
- * cras_alsa_mixer_create. */
- return cras_alsa_mixer_get_control_matching_name(
- cras_mixer, CRAS_STREAM_INPUT, name, 1);
-}
-
-int cras_alsa_mixer_set_output_active_state(struct mixer_control *output,
- int active)
-{
- assert(output);
- if (!output->has_mute)
- return -1;
- return mixer_control_set_mute(output, !active);
-}
diff --git a/cras/src/server/cras_alsa_mixer.h b/cras/src/server/cras_alsa_mixer.h
deleted file mode 100644
index 878fbe54..00000000
--- a/cras/src/server/cras_alsa_mixer.h
+++ /dev/null
@@ -1,235 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_ALSA_MIXER_H
-#define _CRAS_ALSA_MIXER_H
-
-#include "cras_types.h"
-
-/* cras_alsa_mixer represents the alsa mixer interface for an alsa card. It
- * houses the volume and mute controls as well as playback switches for
- * headphones and mic.
- */
-
-struct mixer_control;
-struct cras_alsa_mixer;
-struct cras_volume_curve;
-struct cras_card_config;
-struct mixer_name;
-struct ucm_section;
-
-/* Creates a cras_alsa_mixer instance for the given alsa device.
- * Args:
- * card_name - Name of the card to open a mixer for. This is an alsa name of
- * the form "hw:X" where X ranges from 0 to 31 inclusive.
- * Returns:
- * A pointer to the newly created cras_alsa_mixer which must later be freed
- * by calling cras_alsa_mixer_destroy. The control in the mixer is not added
- * yet.
- */
-struct cras_alsa_mixer *cras_alsa_mixer_create(const char *card_name);
-
-/* Adds controls to a cras_alsa_mixer from the given UCM section.
- * Args:
- * cmix - A pointer to cras_alsa_mixer.
- * section - A UCM section.
- * Returns:
- * 0 on success. Negative error code otherwise.
- */
-int cras_alsa_mixer_add_controls_in_section(struct cras_alsa_mixer *cmix,
- struct ucm_section *section);
-
-/* Adds main volume controls to a cras_alsa_mixer from the given list of mixer
- * names of main volume controls.
- * Args:
- * cmix - A pointer to cras_alsa_mixer.
- * mixer_names - A list of mixer names from the given UCM MainVolumeNames.
- * Returns:
- * 0 on success. Negative error code otherwise.
- */
-int cras_alsa_mixer_add_main_volume_control_by_name(
- struct cras_alsa_mixer *cmix, struct mixer_name *mixer_names);
-
-/* Adds controls to a cras_alsa_mixer instance by name matching.
- * Args:
- * cmix - A pointer to cras_alsa_mixer.
- * extra_controls - A list array of extra mixer control names, always added.
- * coupled_controls - A list of coupled mixer control names.
- * Returns:
- * 0 on success. Other error code if error happens.
- */
-int cras_alsa_mixer_add_controls_by_name_matching(
- struct cras_alsa_mixer *cmix, struct mixer_name *extra_controls,
- struct mixer_name *coupled_controls);
-
-/* Destroys a cras_alsa_mixer that was returned from cras_alsa_mixer_create.
- * Args:
- * cras_mixer - The cras_alsa_mixer pointer returned from
- * cras_alsa_mixer_create.
- */
-void cras_alsa_mixer_destroy(struct cras_alsa_mixer *cras_mixer);
-
-/* Returns if the mixer has any main volume control. */
-int cras_alsa_mixer_has_main_volume(const struct cras_alsa_mixer *cras_mixer);
-
-/* Returns if the mixer control supports volume adjust. */
-int cras_alsa_mixer_has_volume(const struct mixer_control *mixer_control);
-
-/* Sets the output volume for the device associated with this mixer.
- * Args:
- * cras_mixer - The mixer to set the volume on.
- * dBFS - The volume level as dB * 100. dB is a normally a negative quantity
- * specifying how much to attenuate.
- * mixer_output - The mixer output to set if not all attenuation can be
- * obtained from the main controls. Can be null.
- */
-void cras_alsa_mixer_set_dBFS(struct cras_alsa_mixer *cras_mixer, long dBFS,
- struct mixer_control *mixer_output);
-
-/* Gets the volume range of the mixer in dB.
- * Args:
- * cras_mixer - The mixer to get the volume range.
- */
-long cras_alsa_mixer_get_dB_range(struct cras_alsa_mixer *cras_mixer);
-
-/* Gets the volume range of the mixer output in dB.
- * Args:
- * mixer_output - The mixer output to get the volume range.
- */
-long cras_alsa_mixer_get_output_dB_range(struct mixer_control *mixer_output);
-
-/* Sets the capture gain for the device associated with this mixer.
- * Args:
- * cras_mixer - The mixer to set the volume on.
- * dBFS - The capture gain level as dB * 100. dB can be a positive or a
- * negative quantity specifying how much gain or attenuation to apply.
- * mixer_input - The specific mixer control for input node, can be null.
- */
-void cras_alsa_mixer_set_capture_dBFS(struct cras_alsa_mixer *cras_mixer,
- long dBFS,
- struct mixer_control *mixer_input);
-
-/* Gets the minimum allowed setting for capture gain.
- * Args:
- * cmix - The mixer to set the capture gain on.
- * mixer_input - The additional input mixer control, mainly specified
- * in ucm config. Can be null.
- * Returns:
- * The minimum allowed capture gain in dBFS * 100.
- */
-long cras_alsa_mixer_get_minimum_capture_gain(
- struct cras_alsa_mixer *cmix, struct mixer_control *mixer_input);
-
-/* Gets the maximum allowed setting for capture gain.
- * Args:
- * cmix - The mixer to set the capture gain on.
- * mixer_input - The additional input mixer control, mainly specified
- * in ucm config. Can be null.
- * Returns:
- * The maximum allowed capture gain in dBFS * 100.
- */
-long cras_alsa_mixer_get_maximum_capture_gain(
- struct cras_alsa_mixer *cmix, struct mixer_control *mixer_input);
-
-/* Sets the playback switch for the device.
- * Args:
- * cras_mixer - Mixer to set the playback switch.
- * muted - 1 if muted, 0 if not.
- * mixer_output - The output specific mixer control to mute/unmute. Pass NULL
- * to skip it.
- */
-void cras_alsa_mixer_set_mute(struct cras_alsa_mixer *cras_mixer, int muted,
- struct mixer_control *mixer_output);
-
-/* Sets the capture switch for the device.
- * Args:
- * cras_mixer - Mixer to set the volume in.
- * muted - 1 if muted, 0 if not.
- * mixer_input - The mixer input to mute if no card mute.
- */
-void cras_alsa_mixer_set_capture_mute(struct cras_alsa_mixer *cras_mixer,
- int muted,
- struct mixer_control *mixer_input);
-
-/* Invokes the provided callback once for each output (input).
- * The callback will be provided with a reference to the control
- * that can be queried to see what the control supports.
- * Args:
- * cras_mixer - Mixer to set the volume in.
- * cb - Function to call for each output (input).
- * cb_arg - Argument to pass to cb.
- */
-typedef void (*cras_alsa_mixer_control_callback)(struct mixer_control *control,
- void *arg);
-void cras_alsa_mixer_list_outputs(struct cras_alsa_mixer *cras_mixer,
- cras_alsa_mixer_control_callback cb,
- void *cb_arg);
-
-void cras_alsa_mixer_list_inputs(struct cras_alsa_mixer *cras_mixer,
- cras_alsa_mixer_control_callback cb,
- void *cb_arg);
-
-/* Gets the name of a given control. */
-const char *
-cras_alsa_mixer_get_control_name(const struct mixer_control *control);
-
-/* Returns the mixer control matching the given direction and name.
- * Args:
- * cras_mixer - Mixer to search for a control.
- * dir - Control's direction (OUTPUT or INPUT).
- * name - Name to search for.
- * create_missing - When non-zero, attempt to create a new control with
- * the given name.
- * Returns:
- * A pointer to the matching mixer control, or NULL if none found.
- */
-struct mixer_control *
-cras_alsa_mixer_get_control_matching_name(struct cras_alsa_mixer *cras_mixer,
- enum CRAS_STREAM_DIRECTION dir,
- const char *name, int create_missing);
-
-/* Returns the mixer control associated with the given section.
- * The control is the one that matches 'mixer_name', or if that is not defined
- * then it will be the control matching 'section->name', based on the
- * coupled mixer controls.
- * Args:
- * cras_mixer - Mixer to search for a control.
- * section - Associated UCM section.
- * Returns:
- * A pointer to the associated mixer control, or NULL if none found.
- */
-struct mixer_control *
-cras_alsa_mixer_get_control_for_section(struct cras_alsa_mixer *cras_mixer,
- const struct ucm_section *section);
-
-/* Finds the output that matches the given string. Used to match Jacks to Mixer
- * elements.
- * Args:
- * cras_mixer - Mixer to search for a control.
- * name - The name to match against the controls.
- * Returns:
- * A pointer to the output with a mixer control that matches "name".
- */
-struct mixer_control *
-cras_alsa_mixer_get_output_matching_name(struct cras_alsa_mixer *cras_mixer,
- const char *name);
-
-/* Finds the mixer control for that matches the control name of input control
- * name specified in ucm config.
- * Args:
- * cras_mixer - Mixer to search for a control.
- * name - Name of the control to search for.
- * Returns:
- * A pointer to the input with a mixer control that matches "name".
- */
-struct mixer_control *
-cras_alsa_mixer_get_input_matching_name(struct cras_alsa_mixer *cras_mixer,
- const char *name);
-
-/* Sets the given output active or inactive. */
-int cras_alsa_mixer_set_output_active_state(struct mixer_control *output,
- int active);
-
-#endif /* _CRAS_ALSA_MIXER_H */
diff --git a/cras/src/server/cras_alsa_mixer_name.c b/cras/src/server/cras_alsa_mixer_name.c
deleted file mode 100644
index 45ef2c53..00000000
--- a/cras/src/server/cras_alsa_mixer_name.c
+++ /dev/null
@@ -1,131 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_alsa_mixer_name.h"
-#include "utlist.h"
-
-struct mixer_name *mixer_name_add(struct mixer_name *names, const char *name,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type)
-{
- struct mixer_name *m_name;
-
- if (!name)
- return names;
-
- m_name = (struct mixer_name *)calloc(1, sizeof(struct mixer_name));
- if (!m_name)
- return names;
-
- m_name->name = strdup(name);
- if (!m_name->name) {
- free(m_name);
- return names;
- }
- m_name->dir = dir;
- m_name->type = type;
-
- DL_APPEND(names, m_name);
- return names;
-}
-
-struct mixer_name *mixer_name_add_array(struct mixer_name *names,
- const char *const *name_array,
- size_t name_array_size,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type)
-{
- size_t i;
- for (i = 0; i < name_array_size; i++)
- names = mixer_name_add(names, name_array[i], dir, type);
- return names;
-}
-
-void mixer_name_free(struct mixer_name *names)
-{
- struct mixer_name *m_name;
- DL_FOREACH (names, m_name) {
- DL_DELETE(names, m_name);
- free((void *)m_name->name);
- free(m_name);
- }
-}
-
-struct mixer_name *mixer_name_find(struct mixer_name *names, const char *name,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type)
-{
- if (!name && type == MIXER_NAME_UNDEFINED)
- return NULL;
-
- struct mixer_name *m_name;
- DL_FOREACH (names, m_name) {
- /* Match the direction. */
- if (dir != m_name->dir)
- continue;
- /* Match the type unless the type is UNDEFINED. */
- if (type != MIXER_NAME_UNDEFINED && type != m_name->type)
- continue;
- /* Match the name if it is non-NULL, or return the first
- * item with the correct type when the name is not defined. */
- if ((type != MIXER_NAME_UNDEFINED && !name) ||
- (name && !strcmp(m_name->name, name)))
- return m_name;
- }
- return NULL;
-}
-
-static const char *mixer_name_type_str(enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type)
-{
- switch (dir) {
- case CRAS_STREAM_OUTPUT:
- switch (type) {
- case MIXER_NAME_VOLUME:
- return "output volume";
- case MIXER_NAME_MAIN_VOLUME:
- return "main volume";
- case MIXER_NAME_UNDEFINED:
- break;
- }
- break;
- case CRAS_STREAM_INPUT:
- switch (type) {
- case MIXER_NAME_VOLUME:
- return "input volume";
- case MIXER_NAME_MAIN_VOLUME:
- return "main capture";
- case MIXER_NAME_UNDEFINED:
- break;
- }
- break;
- case CRAS_STREAM_UNDEFINED:
- case CRAS_STREAM_POST_MIX_PRE_DSP:
- case CRAS_NUM_DIRECTIONS:
- break;
- }
- return "undefined";
-}
-
-void mixer_name_dump(struct mixer_name *names, const char *message)
-{
- struct mixer_name *m_name;
-
- if (!names) {
- syslog(LOG_DEBUG, "%s: empty", message);
- return;
- }
-
- syslog(LOG_DEBUG, "%s:", message);
- DL_FOREACH (names, m_name) {
- const char *type_str =
- mixer_name_type_str(m_name->dir, m_name->type);
- syslog(LOG_DEBUG, " %s %s", m_name->name, type_str);
- }
-}
diff --git a/cras/src/server/cras_alsa_mixer_name.h b/cras/src/server/cras_alsa_mixer_name.h
deleted file mode 100644
index 67f8e9e3..00000000
--- a/cras/src/server/cras_alsa_mixer_name.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_ALSA_MIXER_NAME_H
-#define _CRAS_ALSA_MIXER_NAME_H
-
-#include "cras_types.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Type of mixer control. */
-typedef enum mixer_name_type {
- MIXER_NAME_UNDEFINED,
- MIXER_NAME_MAIN_VOLUME,
- MIXER_NAME_VOLUME,
-} mixer_name_type;
-
-/* Represents a list of mixer names found in ALSA. */
-struct mixer_name {
- const char *name;
- enum CRAS_STREAM_DIRECTION dir;
- mixer_name_type type;
- struct mixer_name *prev, *next;
-};
-
-/* Add a name to the list.
- *
- * Args:
- * names - A list of controls (may be NULL).
- * name - The name to add.
- * dir - The direction for this control.
- * type - The type control being added.
- *
- * Returns:
- * Returns the new head of the list (which changes only
- * when names is NULL).
- */
-struct mixer_name *mixer_name_add(struct mixer_name *names, const char *name,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type);
-
-/* Add an array of name to the list.
- *
- * Args:
- * names - A list of controls (may be NULL).
- * name_array - The names to add.
- * name_array_size - The size of name_array.
- * dir - The direction for these controls.
- * type - The type controls being added.
- *
- * Returns:
- * Returns the new head of the list (which changes only
- * when names is NULL).
- */
-struct mixer_name *mixer_name_add_array(struct mixer_name *names,
- const char *const *name_array,
- size_t name_array_size,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type);
-
-/* Frees a list of names.
- *
- * Args:
- * names - A list of names.
- */
-void mixer_name_free(struct mixer_name *names);
-
-/* Find the mixer_name for the given direction, name, and type.
- *
- * Args:
- * names - A list of names (may be NULL).
- * name - The name to find, or NULL to match by type.
-
- * dir - The direction to match.
- * type - The type to match, or MIXER_NAME_UNDEFINED to
- * match by name only.
- *
- * Returns:
- * Returns a pointer to the matching struct mixer_name or NULL if
- * not found.
- */
-struct mixer_name *mixer_name_find(struct mixer_name *names, const char *name,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type);
-
-/* Dump the list of mixer names to DEBUG logs.
- *
- * Args:
- * names - A list of names to dump.
- * message - A message to print beforehand.
- */
-void mixer_name_dump(struct mixer_name *names, const char *message);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CRAS_ALSA_MIXER_NAME_H */
diff --git a/cras/src/server/cras_alsa_plugin_io.c b/cras/src/server/cras_alsa_plugin_io.c
deleted file mode 100644
index 32c1ae11..00000000
--- a/cras/src/server/cras_alsa_plugin_io.c
+++ /dev/null
@@ -1,265 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <alsa/use-case.h>
-#include <stdio.h>
-#include <sys/select.h>
-#include <syslog.h>
-
-#include "cras_alsa_io.h"
-#include "cras_alsa_jack.h"
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_ucm.h"
-#include "cras_iodev.h"
-#include "cras_system_state.h"
-#include "iniparser_wrapper.h"
-#include "utlist.h"
-
-#define PLUGINS_INI "plugins.ini"
-#define PLUGIN_KEY_CTL "ctl"
-#define PLUGIN_KEY_DIR "dir"
-#define PLUGIN_KEY_PCM "pcm"
-#define PLUGIN_KEY_CARD "card"
-
-#define NULL_USB_VID 0x00
-#define NULL_USB_PID 0x00
-#define NULL_USB_SERIAL_NUMBER "serial-number-not-used"
-
-struct hctl_poll_fd {
- int fd;
- struct hctl_poll_fd *prev, *next;
-};
-
-struct alsa_plugin {
- snd_hctl_t *hctl;
- struct cras_alsa_mixer *mixer;
- struct hctl_poll_fd *hctl_poll_fds;
- struct cras_use_case_mgr *ucm;
- struct cras_iodev *iodev;
- struct alsa_plugin *next, *prev;
-};
-
-static struct alsa_plugin *plugins;
-
-static char ini_name[MAX_INI_NAME_LENGTH + 1];
-static char key_name[MAX_INI_NAME_LENGTH + 1];
-static dictionary *plugins_ini = NULL;
-
-static void hctl_event_pending(void *arg, int revents)
-{
- struct alsa_plugin *plugin;
-
- plugin = (struct alsa_plugin *)arg;
- if (plugin->hctl == NULL)
- return;
-
- /* handle_events will trigger the callback registered with each control
- * that has changed. */
- snd_hctl_handle_events(plugin->hctl);
-}
-
-/* hctl poll descritpor */
-static void collect_poll_descriptors(struct alsa_plugin *plugin)
-{
- struct hctl_poll_fd *registered_fd;
- struct pollfd *pollfds;
- int i, n, rc;
-
- n = snd_hctl_poll_descriptors_count(plugin->hctl);
- if (n == 0) {
- syslog(LOG_DEBUG, "No hctl descritpor to poll");
- return;
- }
-
- pollfds = malloc(n * sizeof(*pollfds));
- if (pollfds == NULL)
- return;
-
- n = snd_hctl_poll_descriptors(plugin->hctl, pollfds, n);
- for (i = 0; i < n; i++) {
- registered_fd = calloc(1, sizeof(*registered_fd));
- if (registered_fd == NULL) {
- free(pollfds);
- return;
- }
- registered_fd->fd = pollfds[i].fd;
- DL_APPEND(plugin->hctl_poll_fds, registered_fd);
- rc = cras_system_add_select_fd(
- registered_fd->fd, hctl_event_pending, plugin, POLLIN);
- if (rc < 0) {
- DL_DELETE(plugin->hctl_poll_fds, registered_fd);
- free(pollfds);
- return;
- }
- }
- free(pollfds);
-}
-
-static void cleanup_poll_descriptors(struct alsa_plugin *plugin)
-{
- struct hctl_poll_fd *poll_fd;
- DL_FOREACH (plugin->hctl_poll_fds, poll_fd) {
- cras_system_rm_select_fd(poll_fd->fd);
- DL_DELETE(plugin->hctl_poll_fds, poll_fd);
- free(poll_fd);
- }
-}
-
-static void destroy_plugin(struct alsa_plugin *plugin);
-
-void alsa_plugin_io_create(enum CRAS_STREAM_DIRECTION direction,
- const char *pcm_name, const char *ctl_name,
- const char *card_name)
-{
- struct alsa_plugin *plugin;
- struct ucm_section *section;
- struct ucm_section *ucm_sections;
- int rc;
-
- plugin = (struct alsa_plugin *)calloc(1, sizeof(*plugin));
- if (!plugin) {
- syslog(LOG_ERR, "No memory to create alsa plugin");
- return;
- }
-
- rc = snd_hctl_open(&plugin->hctl, ctl_name, SND_CTL_NONBLOCK);
- if (rc < 0) {
- syslog(LOG_ERR, "open hctl fail for plugin %s", ctl_name);
- goto cleanup;
- }
-
- rc = snd_hctl_nonblock(plugin->hctl, 1);
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to nonblock hctl for %s", ctl_name);
- goto cleanup;
- }
- rc = snd_hctl_load(plugin->hctl);
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to load hctl for %s", ctl_name);
- goto cleanup;
- }
- collect_poll_descriptors(plugin);
-
- plugin->mixer = cras_alsa_mixer_create(ctl_name);
-
- plugin->ucm = ucm_create(card_name);
-
- DL_APPEND(plugins, plugin);
-
- ucm_sections = ucm_get_sections(plugin->ucm);
- DL_FOREACH (ucm_sections, section) {
- rc = cras_alsa_mixer_add_controls_in_section(plugin->mixer,
- section);
- if (rc)
- syslog(LOG_ERR,
- "Failed adding control to plugin,"
- "section %s mixer_name %s",
- section->name, section->mixer_name);
- }
- plugin->iodev = alsa_iodev_create(0, card_name, 0, pcm_name, "", "",
- ALSA_CARD_TYPE_USB, 1, /* is first */
- plugin->mixer, NULL, plugin->ucm,
- plugin->hctl, direction, NULL_USB_VID,
- NULL_USB_PID, NULL_USB_SERIAL_NUMBER);
-
- DL_FOREACH (ucm_sections, section) {
- if (section->dir != plugin->iodev->direction)
- continue;
- section->dev_idx = 0;
- alsa_iodev_ucm_add_nodes_and_jacks(plugin->iodev, section);
- }
-
- alsa_iodev_ucm_complete_init(plugin->iodev);
-
- return;
-cleanup:
- if (plugin)
- destroy_plugin(plugin);
-}
-
-static void destroy_plugin(struct alsa_plugin *plugin)
-{
- cleanup_poll_descriptors(plugin);
- if (plugin->hctl)
- snd_hctl_close(plugin->hctl);
- if (plugin->iodev)
- alsa_iodev_destroy(plugin->iodev);
- if (plugin->mixer)
- cras_alsa_mixer_destroy(plugin->mixer);
-
- free(plugin);
-}
-
-void alsa_pluigin_io_destroy_all()
-{
- struct alsa_plugin *plugin;
-
- DL_FOREACH (plugins, plugin)
- destroy_plugin(plugin);
-}
-
-void cras_alsa_plugin_io_init(const char *device_config_dir)
-{
- int nsec, i;
- enum CRAS_STREAM_DIRECTION direction;
- const char *sec_name;
- const char *tmp, *pcm_name, *ctl_name, *card_name;
-
- snprintf(ini_name, MAX_INI_NAME_LENGTH, "%s/%s", device_config_dir,
- PLUGINS_INI);
- ini_name[MAX_INI_NAME_LENGTH] = '\0';
-
- plugins_ini = iniparser_load_wrapper(ini_name);
- if (!plugins_ini)
- return;
-
- nsec = iniparser_getnsec(plugins_ini);
- for (i = 0; i < nsec; i++) {
- sec_name = iniparser_getsecname(plugins_ini, i);
-
- /* Parse dir=output or dir=input */
- snprintf(key_name, MAX_INI_NAME_LENGTH, "%s:%s", sec_name,
- PLUGIN_KEY_DIR);
- tmp = iniparser_getstring(plugins_ini, key_name, NULL);
- if (strcmp(tmp, "output") == 0)
- direction = CRAS_STREAM_OUTPUT;
- else if (strcmp(tmp, "input") == 0)
- direction = CRAS_STREAM_INPUT;
- else
- continue;
-
- /* pcm=<plugin-pcm-name> this name will be used with
- * snd_pcm_open. */
- snprintf(key_name, MAX_INI_NAME_LENGTH, "%s:%s", sec_name,
- PLUGIN_KEY_PCM);
- pcm_name = iniparser_getstring(plugins_ini, key_name, NULL);
- if (!pcm_name)
- continue;
-
- /* ctl=<plugin-ctl-name> this name will be used with
- * snd_hctl_open. */
- snprintf(key_name, MAX_INI_NAME_LENGTH, "%s:%s", sec_name,
- PLUGIN_KEY_CTL);
- ctl_name = iniparser_getstring(plugins_ini, key_name, NULL);
- if (!ctl_name)
- continue;
-
- /* card=<card-name> this name will be used with
- * snd_use_case_mgr_open. */
- snprintf(key_name, MAX_INI_NAME_LENGTH, "%s:%s", sec_name,
- PLUGIN_KEY_CARD);
- card_name = iniparser_getstring(plugins_ini, key_name, NULL);
- if (!card_name)
- continue;
-
- syslog(LOG_DEBUG,
- "Creating plugin for direction %s, pcm %s, ctl %s, card %s",
- direction == CRAS_STREAM_OUTPUT ? "output" : "input",
- pcm_name, ctl_name, card_name);
-
- alsa_plugin_io_create(direction, pcm_name, ctl_name, card_name);
- }
-}
diff --git a/cras/src/server/cras_alsa_plugin_io.h b/cras/src/server/cras_alsa_plugin_io.h
deleted file mode 100644
index 995f463e..00000000
--- a/cras/src/server/cras_alsa_plugin_io.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_ALSA_PLUGIN_IO_H_
-#define CRAS_ALSA_PLUGIN_IO_H_
-
-/*
- * Disclaimer:
- * The ALSA plugin path in CRAS is intended to be used for development or
- * testing. CrOS audio team is not responsible for nor provides hot-fix to
- * any breakage if it’s used in production code.
- */
-
-void alsa_pluigin_io_destroy_all();
-
-void cras_alsa_plugin_io_init(const char *device_config_dir);
-
-#endif /* CRAS_ALSA_PLUGIN_IO_H_ */
diff --git a/cras/src/server/cras_alsa_ucm.c b/cras/src/server/cras_alsa_ucm.c
deleted file mode 100644
index 3e46f6a9..00000000
--- a/cras/src/server/cras_alsa_ucm.c
+++ /dev/null
@@ -1,1237 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <alsa/asoundlib.h>
-#include <alsa/use-case.h>
-#include <ctype.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_alsa_ucm.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-static const char jack_control_var[] = "JackControl";
-static const char jack_dev_var[] = "JackDev";
-static const char jack_switch_var[] = "JackSwitch";
-static const char edid_var[] = "EDIDFile";
-static const char cap_var[] = "CaptureControl";
-static const char override_type_name_var[] = "OverrideNodeType";
-static const char dsp_name_var[] = "DspName";
-static const char playback_mixer_elem_var[] = "PlaybackMixerElem";
-static const char capture_mixer_elem_var[] = "CaptureMixerElem";
-static const char min_buffer_level_var[] = "MinBufferLevel";
-static const char dma_period_var[] = "DmaPeriodMicrosecs";
-static const char disable_software_volume[] = "DisableSoftwareVolume";
-static const char playback_device_name_var[] = "PlaybackPCM";
-static const char playback_device_rate_var[] = "PlaybackRate";
-static const char playback_channels_var[] = "PlaybackChannels";
-static const char capture_device_name_var[] = "CapturePCM";
-static const char capture_device_rate_var[] = "CaptureRate";
-static const char capture_channel_map_var[] = "CaptureChannelMap";
-static const char capture_channels_var[] = "CaptureChannels";
-static const char coupled_mixers[] = "CoupledMixers";
-static const char dependent_device_name_var[] = "DependentPCM";
-static const char preempt_hotword_var[] = "PreemptHotword";
-static const char echo_reference_dev_name_var[] = "EchoReferenceDev";
-
-/* SectionModifier prefixes and suffixes. */
-static const char hotword_model_prefix[] = "Hotword Model";
-static const char swap_mode_suffix[] = "Swap Mode";
-static const char noise_cancellation_suffix[] = "Noise Cancellation";
-
-/*
- * Set this value in a SectionDevice to specify the intrinsic sensitivity in
- * 0.01 dBFS/Pa. It currently only supports input devices. You should get the
- * value by recording samples without either hardware or software gain. We are
- * still working on building a standard process for measuring it. The value you
- * see now in our UCM is just estimated value. If it is set, CRAS will enable
- * software gain and use the value as a reference for calculating the
- * appropriate software gain to apply to the device to meet our target volume.
- */
-static const char intrinsic_sensitivity_var[] = "IntrinsicSensitivity";
-
-/*
- * Set this value in a SectionDevice to specify the default node gain in
- * 0.01 dB.
- */
-static const char default_node_gain[] = "DefaultNodeGain";
-static const char fully_specified_ucm_var[] = "FullySpecifiedUCM";
-static const char main_volume_names[] = "MainVolumeNames";
-
-/* Use case verbs corresponding to CRAS_STREAM_TYPE. */
-static const char *use_case_verbs[] = {
- "HiFi", "Multimedia", "Voice Call",
- "Speech", "Pro Audio", "Accessibility",
-};
-
-static const size_t max_section_name_len = 100;
-
-/* Represents a list of section names found in UCM. */
-struct section_name {
- const char *name;
- struct section_name *prev, *next;
-};
-
-struct cras_use_case_mgr {
- snd_use_case_mgr_t *mgr;
- char *name;
- unsigned int avail_use_cases;
- enum CRAS_STREAM_TYPE use_case;
- char *hotword_modifier;
-};
-
-static inline const char *uc_verb(struct cras_use_case_mgr *mgr)
-{
- return use_case_verbs[mgr->use_case];
-}
-
-static int device_enabled(struct cras_use_case_mgr *mgr, const char *dev)
-{
- const char **list;
- unsigned int i;
- int num_devs;
- int enabled = 0;
-
- num_devs = snd_use_case_get_list(mgr->mgr, "_enadevs", &list);
- if (num_devs <= 0)
- return 0;
-
- for (i = 0; i < (unsigned int)num_devs; i++)
- if (!strcmp(dev, list[i])) {
- enabled = 1;
- break;
- }
-
- snd_use_case_free_list(list, num_devs);
- return enabled;
-}
-
-static int modifier_enabled(struct cras_use_case_mgr *mgr, const char *mod)
-{
- const char **list;
- unsigned int mod_idx;
- int num_mods;
-
- num_mods = snd_use_case_get_list(mgr->mgr, "_enamods", &list);
- if (num_mods <= 0)
- return 0;
-
- for (mod_idx = 0; mod_idx < (unsigned int)num_mods; mod_idx++)
- if (!strcmp(mod, list[mod_idx]))
- break;
-
- snd_use_case_free_list(list, num_mods);
- return (mod_idx < (unsigned int)num_mods);
-}
-
-static int get_var(struct cras_use_case_mgr *mgr, const char *var,
- const char *dev, const char *verb, const char **value)
-{
- char *id;
- int rc;
- size_t len = strlen(var) + strlen(dev) + strlen(verb) + 4;
-
- id = (char *)malloc(len);
- if (!id)
- return -ENOMEM;
- snprintf(id, len, "=%s/%s/%s", var, dev, verb);
- rc = snd_use_case_get(mgr->mgr, id, value);
-
- free((void *)id);
- return rc;
-}
-
-static int get_int(struct cras_use_case_mgr *mgr, const char *var,
- const char *dev, const char *verb, int *value)
-{
- const char *str_value;
- int rc;
-
- if (!value)
- return -EINVAL;
- rc = get_var(mgr, var, dev, verb, &str_value);
- if (rc != 0)
- return rc;
- *value = atoi(str_value);
- free((void *)str_value);
- return 0;
-}
-
-static int ucm_set_modifier_enabled(struct cras_use_case_mgr *mgr,
- const char *mod, int enable)
-{
- return snd_use_case_set(mgr->mgr, enable ? "_enamod" : "_dismod", mod);
-}
-
-static int ucm_str_ends_with_suffix(const char *str, const char *suffix)
-{
- if (!str || !suffix)
- return 0;
- size_t len_str = strlen(str);
- size_t len_suffix = strlen(suffix);
- if (len_suffix > len_str)
- return 0;
- return strncmp(str + len_str - len_suffix, suffix, len_suffix) == 0;
-}
-
-static int ucm_section_exists_with_name(struct cras_use_case_mgr *mgr,
- const char *name,
- const char *identifier)
-{
- const char **list;
- unsigned int i;
- int num_entries;
- int exist = 0;
-
- num_entries = snd_use_case_get_list(mgr->mgr, identifier, &list);
- if (num_entries <= 0)
- return 0;
-
- for (i = 0; i < (unsigned int)num_entries; i += 2) {
- if (!list[i])
- continue;
-
- if (strcmp(list[i], name) == 0) {
- exist = 1;
- break;
- }
- }
- snd_use_case_free_list(list, num_entries);
- return exist;
-}
-
-static int ucm_section_exists_with_suffix(struct cras_use_case_mgr *mgr,
- const char *suffix,
- const char *identifier)
-{
- const char **list;
- unsigned int i;
- int num_entries;
- int exist = 0;
-
- num_entries = snd_use_case_get_list(mgr->mgr, identifier, &list);
- if (num_entries <= 0)
- return 0;
-
- for (i = 0; i < (unsigned int)num_entries; i += 2) {
- if (!list[i])
- continue;
-
- if (ucm_str_ends_with_suffix(list[i], suffix)) {
- exist = 1;
- break;
- }
- }
- snd_use_case_free_list(list, num_entries);
- return exist;
-}
-
-static int ucm_mod_exists_with_suffix(struct cras_use_case_mgr *mgr,
- const char *suffix)
-{
- char *identifier;
- int rc;
-
- identifier = snd_use_case_identifier("_modifiers/%s", uc_verb(mgr));
- rc = ucm_section_exists_with_suffix(mgr, suffix, identifier);
- free(identifier);
- return rc;
-}
-
-static int ucm_mod_exists_with_name(struct cras_use_case_mgr *mgr,
- const char *name)
-{
- char *identifier;
- int rc;
-
- identifier = snd_use_case_identifier("_modifiers/%s", uc_verb(mgr));
- rc = ucm_section_exists_with_name(mgr, name, identifier);
- free(identifier);
- return rc;
-}
-
-/* Get a list of section names whose variable is the matched value. */
-static struct section_name *
-ucm_get_sections_for_var(struct cras_use_case_mgr *mgr, const char *var,
- const char *value, const char *identifier,
- enum CRAS_STREAM_DIRECTION direction)
-{
- const char **list;
- struct section_name *section_names = NULL, *s_name;
- unsigned int i;
- int num_entries;
- int rc;
-
- num_entries = snd_use_case_get_list(mgr->mgr, identifier, &list);
- if (num_entries <= 0)
- return NULL;
-
- /* snd_use_case_get_list fills list with pairs of device name and
- * comment, so device names are in even-indexed elements. */
- for (i = 0; i < (unsigned int)num_entries; i += 2) {
- const char *this_value;
-
- if (!list[i])
- continue;
-
- rc = get_var(mgr, var, list[i], uc_verb(mgr), &this_value);
- if (rc)
- continue;
-
- if (!strcmp(value, this_value)) {
- s_name = (struct section_name *)malloc(
- sizeof(struct section_name));
-
- if (!s_name) {
- syslog(LOG_ERR, "Failed to allocate memory");
- free((void *)this_value);
- break;
- }
-
- s_name->name = strdup(list[i]);
- DL_APPEND(section_names, s_name);
- }
- free((void *)this_value);
- }
-
- snd_use_case_free_list(list, num_entries);
- return section_names;
-}
-
-static struct section_name *
-ucm_get_devices_for_var(struct cras_use_case_mgr *mgr, const char *var,
- const char *value, enum CRAS_STREAM_DIRECTION dir)
-{
- char *identifier;
- struct section_name *section_names;
-
- identifier = snd_use_case_identifier("_devices/%s", uc_verb(mgr));
- section_names =
- ucm_get_sections_for_var(mgr, var, value, identifier, dir);
- free(identifier);
- return section_names;
-}
-
-static const char *ucm_get_value_for_dev(struct cras_use_case_mgr *mgr,
- const char *value_var, const char *dev)
-{
- const char *name = NULL;
- int rc;
-
- rc = get_var(mgr, value_var, dev, uc_verb(mgr), &name);
- if (rc)
- return NULL;
-
- return name;
-}
-
-static inline const char *
-ucm_get_playback_device_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, playback_device_name_var, dev);
-}
-
-static inline const char *
-ucm_get_capture_device_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, capture_device_name_var, dev);
-}
-
-/* Gets the value of DependentPCM property. This is used to structure two
- * SectionDevices under one cras iodev to avoid two PCMs be open at the
- * same time because of restriction in lower layer driver or hardware.
- */
-static inline const char *
-ucm_get_dependent_device_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, dependent_device_name_var, dev);
-}
-
-/* Get a list of mixer names specified in a UCM variable separated by ",".
- * E.g. "Left Playback,Right Playback".
- */
-static struct mixer_name *ucm_get_mixer_names(struct cras_use_case_mgr *mgr,
- const char *dev, const char *var,
- enum CRAS_STREAM_DIRECTION dir,
- mixer_name_type type)
-{
- const char *names_in_string = NULL;
- int rc;
- char *tokens, *name;
- char *laststr = NULL;
- struct mixer_name *names = NULL;
-
- rc = get_var(mgr, var, dev, uc_verb(mgr), &names_in_string);
- if (rc)
- return NULL;
-
- tokens = strdup(names_in_string);
- name = strtok_r(tokens, ",", &laststr);
- while (name != NULL) {
- names = mixer_name_add(names, name, dir, type);
- name = strtok_r(NULL, ",", &laststr);
- }
- free((void *)names_in_string);
- free(tokens);
- return names;
-}
-
-/* Gets the modifier name of Noise Cancellation for the given node_name. */
-static void ucm_get_node_noise_cancellation_name(const char *node_name,
- char *mod_name)
-{
- size_t len =
- strlen(node_name) + 1 + strlen(noise_cancellation_suffix) + 1;
- if (len > max_section_name_len) {
- syslog(LOG_ERR,
- "Length of the given section name is %zu > %zu(max)",
- len, max_section_name_len);
- len = max_section_name_len;
- }
- snprintf(mod_name, len, "%s %s", node_name, noise_cancellation_suffix);
-}
-
-/* Exported Interface */
-
-struct cras_use_case_mgr *ucm_create(const char *name)
-{
- struct cras_use_case_mgr *mgr;
- int rc;
- const char **list;
- int num_verbs, i, j;
-
- assert_on_compile(ARRAY_SIZE(use_case_verbs) == CRAS_STREAM_NUM_TYPES);
-
- if (!name)
- return NULL;
-
- mgr = (struct cras_use_case_mgr *)malloc(sizeof(*mgr));
- if (!mgr)
- return NULL;
-
- mgr->name = strdup(name);
- if (!mgr->name)
- goto cleanup;
-
- rc = snd_use_case_mgr_open(&mgr->mgr, name);
- if (rc) {
- syslog(LOG_WARNING, "Can not open ucm for card %s, rc = %d",
- name, rc);
- goto cleanup;
- }
-
- mgr->avail_use_cases = 0;
- mgr->hotword_modifier = NULL;
- num_verbs = snd_use_case_get_list(mgr->mgr, "_verbs", &list);
- for (i = 0; i < num_verbs; i += 2) {
- for (j = 0; j < CRAS_STREAM_NUM_TYPES; ++j) {
- if (strcmp(list[i], use_case_verbs[j]) == 0)
- break;
- }
- if (j < CRAS_STREAM_NUM_TYPES)
- mgr->avail_use_cases |= (1 << j);
- }
- if (num_verbs > 0)
- snd_use_case_free_list(list, num_verbs);
-
- rc = ucm_set_use_case(mgr, CRAS_STREAM_TYPE_DEFAULT);
- if (rc)
- goto cleanup_mgr;
-
- return mgr;
-
-cleanup_mgr:
- snd_use_case_mgr_close(mgr->mgr);
-cleanup:
- free(mgr->name);
- free(mgr);
- return NULL;
-}
-
-void ucm_destroy(struct cras_use_case_mgr *mgr)
-{
- snd_use_case_mgr_close(mgr->mgr);
- free(mgr->hotword_modifier);
- free(mgr->name);
- free(mgr);
-}
-
-int ucm_set_use_case(struct cras_use_case_mgr *mgr,
- enum CRAS_STREAM_TYPE use_case)
-{
- int rc;
-
- if (mgr->avail_use_cases & (1 << use_case)) {
- mgr->use_case = use_case;
- } else {
- syslog(LOG_ERR, "Unavailable use case %d for card %s", use_case,
- mgr->name);
- return -1;
- }
-
- rc = snd_use_case_set(mgr->mgr, "_verb", uc_verb(mgr));
- if (rc) {
- syslog(LOG_ERR, "Can not set verb %s for card %s, rc = %d",
- uc_verb(mgr), mgr->name, rc);
- return rc;
- }
-
- return 0;
-}
-
-int ucm_swap_mode_exists(struct cras_use_case_mgr *mgr)
-{
- return ucm_mod_exists_with_suffix(mgr, swap_mode_suffix);
-}
-
-int ucm_enable_swap_mode(struct cras_use_case_mgr *mgr, const char *node_name,
- int enable)
-{
- char *swap_mod = NULL;
- int rc;
- size_t len = strlen(node_name) + 1 + strlen(swap_mode_suffix) + 1;
- swap_mod = (char *)malloc(len);
- if (!swap_mod)
- return -ENOMEM;
- snprintf(swap_mod, len, "%s %s", node_name, swap_mode_suffix);
- if (!ucm_mod_exists_with_name(mgr, swap_mod)) {
- syslog(LOG_ERR, "Can not find swap mode modifier %s.",
- swap_mod);
- free((void *)swap_mod);
- return -EPERM;
- }
- if (modifier_enabled(mgr, swap_mod) == !!enable) {
- free((void *)swap_mod);
- return 0;
- }
- rc = ucm_set_modifier_enabled(mgr, swap_mod, enable);
- free((void *)swap_mod);
- return rc;
-}
-
-int ucm_node_noise_cancellation_exists(struct cras_use_case_mgr *mgr,
- const char *node_name)
-{
- char *node_modifier_name = NULL;
- int exists;
-
- node_modifier_name = (char *)malloc(max_section_name_len);
- if (!node_modifier_name)
- return 0;
- ucm_get_node_noise_cancellation_name(node_name, node_modifier_name);
- exists = ucm_mod_exists_with_name(mgr, node_modifier_name);
- free((void *)node_modifier_name);
- return exists;
-}
-
-int ucm_enable_node_noise_cancellation(struct cras_use_case_mgr *mgr,
- const char *node_name, int enable)
-{
- char *node_modifier_name = NULL;
- int rc;
-
- node_modifier_name = (char *)malloc(max_section_name_len);
- if (!node_modifier_name)
- return -ENOMEM;
- ucm_get_node_noise_cancellation_name(node_name, node_modifier_name);
- if (!ucm_mod_exists_with_name(mgr, node_modifier_name)) {
- syslog(LOG_ERR, "Can not find modifier %s.",
- node_modifier_name);
- free((void *)node_modifier_name);
- return -EPERM;
- }
- if (modifier_enabled(mgr, node_modifier_name) == !!enable) {
- syslog(LOG_DEBUG, "Modifier %s is already %s.",
- node_modifier_name, enable ? "enabled" : "disabled");
- free((void *)node_modifier_name);
- return 0;
- }
-
- syslog(LOG_DEBUG, "UCM %s Modifier %s", enable ? "enable" : "disable",
- node_modifier_name);
- rc = ucm_set_modifier_enabled(mgr, node_modifier_name, enable);
- free((void *)node_modifier_name);
- return rc;
-}
-
-int ucm_set_enabled(struct cras_use_case_mgr *mgr, const char *dev, int enable)
-{
- int rc;
- if (device_enabled(mgr, dev) == !!enable)
- return 0;
- syslog(LOG_DEBUG, "UCM %s %s", enable ? "enable" : "disable", dev);
- rc = snd_use_case_set(mgr->mgr, enable ? "_enadev" : "_disdev", dev);
- if (rc && (rc != -ENOENT || ucm_has_fully_specified_ucm_flag(mgr))) {
- syslog(LOG_ERR, "Can not %s UCM for device %s, rc = %d",
- enable ? "enable" : "disable", dev, rc);
- }
- return rc;
-}
-
-char *ucm_get_flag(struct cras_use_case_mgr *mgr, const char *flag_name)
-{
- char *flag_value = NULL;
- const char *value;
- int rc;
-
- /* Set device to empty string since flag is specified in verb section */
- rc = get_var(mgr, flag_name, "", uc_verb(mgr), &value);
- if (!rc) {
- flag_value = strdup(value);
- free((void *)value);
- }
-
- return flag_value;
-}
-
-char *ucm_get_cap_control(struct cras_use_case_mgr *mgr, const char *ucm_dev)
-{
- char *control_name = NULL;
- const char *value;
- int rc;
-
- rc = get_var(mgr, cap_var, ucm_dev, uc_verb(mgr), &value);
- if (!rc) {
- control_name = strdup(value);
- free((void *)value);
- }
-
- return control_name;
-}
-
-inline const char *ucm_get_override_type_name(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, override_type_name_var, dev);
-}
-
-char *ucm_get_dev_for_jack(struct cras_use_case_mgr *mgr, const char *jack,
- enum CRAS_STREAM_DIRECTION direction)
-{
- struct section_name *section_names, *c;
- char *ret = NULL;
-
- section_names =
- ucm_get_devices_for_var(mgr, jack_dev_var, jack, direction);
-
- DL_FOREACH (section_names, c) {
- if (!strcmp(c->name, "Mic")) {
- /* Skip mic section for output */
- if (direction == CRAS_STREAM_OUTPUT)
- continue;
- } else {
- /* Only check mic for input. */
- if (direction == CRAS_STREAM_INPUT)
- continue;
- }
- ret = strdup(c->name);
- break;
- }
-
- DL_FOREACH (section_names, c) {
- DL_DELETE(section_names, c);
- free((void *)c->name);
- free(c);
- }
-
- return ret;
-}
-
-char *ucm_get_dev_for_mixer(struct cras_use_case_mgr *mgr, const char *mixer,
- enum CRAS_STREAM_DIRECTION dir)
-{
- struct section_name *section_names = NULL, *c;
- char *ret = NULL;
-
- if (dir == CRAS_STREAM_OUTPUT) {
- section_names = ucm_get_devices_for_var(
- mgr, playback_mixer_elem_var, mixer, dir);
- } else if (dir == CRAS_STREAM_INPUT) {
- section_names = ucm_get_devices_for_var(
- mgr, capture_mixer_elem_var, mixer, dir);
- }
-
- if (section_names)
- ret = strdup(section_names->name);
-
- DL_FOREACH (section_names, c) {
- DL_DELETE(section_names, c);
- free((void *)c->name);
- free(c);
- }
-
- return ret;
-}
-
-inline const char *ucm_get_edid_file_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, edid_var, dev);
-}
-
-inline const char *ucm_get_dsp_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, dsp_name_var, dev);
-}
-
-int ucm_get_min_buffer_level(struct cras_use_case_mgr *mgr, unsigned int *level)
-{
- int value;
- int rc;
-
- rc = get_int(mgr, min_buffer_level_var, "", uc_verb(mgr), &value);
- if (rc)
- return -ENOENT;
- *level = value;
-
- return 0;
-}
-
-unsigned int ucm_get_disable_software_volume(struct cras_use_case_mgr *mgr)
-{
- int value;
- int rc;
-
- rc = get_int(mgr, disable_software_volume, "", uc_verb(mgr), &value);
- if (rc)
- return 0;
-
- return value;
-}
-
-int ucm_get_default_node_gain(struct cras_use_case_mgr *mgr, const char *dev,
- long *gain)
-{
- int value;
- int rc;
-
- rc = get_int(mgr, default_node_gain, dev, uc_verb(mgr), &value);
- if (rc)
- return rc;
- *gain = value;
- return 0;
-}
-
-int ucm_get_intrinsic_sensitivity(struct cras_use_case_mgr *mgr,
- const char *dev, long *sensitivity)
-{
- int value;
- int rc;
-
- rc = get_int(mgr, intrinsic_sensitivity_var, dev, uc_verb(mgr), &value);
- if (rc)
- return rc;
- *sensitivity = value;
- return 0;
-}
-
-int ucm_get_preempt_hotword(struct cras_use_case_mgr *mgr, const char *dev)
-{
- int value;
- int rc;
-
- rc = get_int(mgr, preempt_hotword_var, dev, uc_verb(mgr), &value);
- if (rc)
- return 0;
- return value;
-}
-
-static int get_device_index_from_target(const char *target_device_name);
-
-int ucm_get_alsa_dev_idx_for_dev(struct cras_use_case_mgr *mgr, const char *dev,
- enum CRAS_STREAM_DIRECTION direction)
-{
- const char *pcm_name = NULL;
- int dev_idx = -1;
-
- if (direction == CRAS_STREAM_OUTPUT)
- pcm_name = ucm_get_playback_device_name_for_dev(mgr, dev);
- else if (direction == CRAS_STREAM_INPUT)
- pcm_name = ucm_get_capture_device_name_for_dev(mgr, dev);
-
- if (pcm_name) {
- dev_idx = get_device_index_from_target(pcm_name);
- free((void *)pcm_name);
- }
- return dev_idx;
-}
-
-inline const char *
-ucm_get_echo_reference_dev_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, echo_reference_dev_name_var, dev);
-}
-
-int ucm_get_sample_rate_for_dev(struct cras_use_case_mgr *mgr, const char *dev,
- enum CRAS_STREAM_DIRECTION direction)
-{
- int value;
- int rc;
- const char *var_name;
-
- if (direction == CRAS_STREAM_OUTPUT)
- var_name = playback_device_rate_var;
- else if (direction == CRAS_STREAM_INPUT)
- var_name = capture_device_rate_var;
- else
- return -EINVAL;
-
- rc = get_int(mgr, var_name, dev, uc_verb(mgr), &value);
- if (rc)
- return rc;
-
- return value;
-}
-
-int ucm_get_channels_for_dev(struct cras_use_case_mgr *mgr, const char *dev,
- enum CRAS_STREAM_DIRECTION direction,
- size_t *channels)
-{
- int value;
- int rc;
- const char *var_name;
-
- if (direction == CRAS_STREAM_OUTPUT)
- var_name = playback_channels_var;
- else if (direction == CRAS_STREAM_INPUT)
- var_name = capture_channels_var;
- else
- return -EINVAL;
-
- rc = get_int(mgr, var_name, dev, uc_verb(mgr), &value);
- if (rc)
- return rc;
- if (value < 0)
- return -1;
-
- *channels = (size_t)value;
- return 0;
-}
-
-int ucm_get_capture_chmap_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev, int8_t *channel_layout)
-{
- const char *var_str;
- char *tokens, *token;
- int i, rc;
-
- rc = get_var(mgr, capture_channel_map_var, dev, uc_verb(mgr), &var_str);
- if (rc)
- return rc;
-
- tokens = strdup(var_str);
- token = strtok(tokens, " ");
- for (i = 0; token && (i < CRAS_CH_MAX); i++) {
- channel_layout[i] = atoi(token);
- token = strtok(NULL, " ");
- }
-
- free((void *)tokens);
- free((void *)var_str);
- return (i == CRAS_CH_MAX) ? 0 : -EINVAL;
-}
-
-struct mixer_name *ucm_get_coupled_mixer_names(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_mixer_names(mgr, dev, coupled_mixers, CRAS_STREAM_OUTPUT,
- MIXER_NAME_VOLUME);
-}
-
-static int get_device_index_from_target(const char *target_device_name)
-{
- /* Expects a string in the form: hw:card-name,<num> */
- const char *pos = target_device_name;
- if (!pos)
- return -1;
- while (*pos && *pos != ',')
- ++pos;
- if (*pos == ',') {
- ++pos;
- return atoi(pos);
- }
- return -1;
-}
-
-static const char *ucm_get_dir_for_device(struct cras_use_case_mgr *mgr,
- const char *dev_name,
- enum CRAS_STREAM_DIRECTION *dir)
-{
- const char *pcm_name;
-
- pcm_name = ucm_get_playback_device_name_for_dev(mgr, dev_name);
-
- if (pcm_name) {
- *dir = CRAS_STREAM_OUTPUT;
- return pcm_name;
- }
-
- pcm_name = ucm_get_capture_device_name_for_dev(mgr, dev_name);
- if (pcm_name) {
- *dir = CRAS_STREAM_INPUT;
- return pcm_name;
- }
-
- *dir = CRAS_STREAM_UNDEFINED;
- return NULL;
-}
-
-static int ucm_parse_device_section(struct cras_use_case_mgr *mgr,
- const char *dev,
- struct ucm_section **sections)
-{
- enum CRAS_STREAM_DIRECTION dir;
- int dev_idx = -1;
- int dependent_dev_idx = -1;
- const char *jack_name = NULL;
- const char *jack_type = NULL;
- const char *jack_dev = NULL;
- const char *jack_control = NULL;
- const char *mixer_name = NULL;
- struct mixer_name *m_name;
- int rc = 0;
- const char *pcm_name;
- const char *dependent_dev_name = NULL;
- struct ucm_section *dev_sec;
- const char *dev_name;
-
- dev_name = strdup(dev);
- if (!dev_name)
- return 0;
-
- pcm_name = ucm_get_dir_for_device(mgr, dev_name, &dir);
-
- if (pcm_name)
- dev_idx = get_device_index_from_target(pcm_name);
-
- if (dir == CRAS_STREAM_UNDEFINED) {
- syslog(LOG_ERR,
- "UCM configuration for device '%s' missing"
- " PlaybackPCM or CapturePCM definition.",
- dev_name);
- rc = -EINVAL;
- goto error_cleanup;
- }
-
- dependent_dev_name =
- ucm_get_dependent_device_name_for_dev(mgr, dev_name);
- if (dependent_dev_name) {
- dependent_dev_idx =
- get_device_index_from_target(dependent_dev_name);
- }
-
- jack_dev = ucm_get_jack_dev_for_dev(mgr, dev_name);
- jack_control = ucm_get_jack_control_for_dev(mgr, dev_name);
- if (dir == CRAS_STREAM_OUTPUT)
- mixer_name = ucm_get_playback_mixer_elem_for_dev(mgr, dev_name);
- else if (dir == CRAS_STREAM_INPUT)
- mixer_name = ucm_get_capture_mixer_elem_for_dev(mgr, dev_name);
-
- if (jack_dev) {
- jack_name = jack_dev;
- jack_type = "gpio";
- } else if (jack_control) {
- jack_name = jack_control;
- jack_type = "hctl";
- }
-
- dev_sec = ucm_section_create(dev_name, pcm_name, dev_idx,
- dependent_dev_idx, dir, jack_name,
- jack_type);
-
- if (!dev_sec) {
- syslog(LOG_ERR, "Failed to allocate memory.");
- rc = -ENOMEM;
- goto error_cleanup;
- }
-
- dev_sec->jack_switch = ucm_get_jack_switch_for_dev(mgr, dev_name);
-
- if (mixer_name) {
- rc = ucm_section_set_mixer_name(dev_sec, mixer_name);
- if (rc)
- goto error_cleanup;
- }
-
- m_name = ucm_get_mixer_names(mgr, dev_name, coupled_mixers, dir,
- MIXER_NAME_VOLUME);
- ucm_section_concat_coupled(dev_sec, m_name);
-
- DL_APPEND(*sections, dev_sec);
- ucm_section_dump(dev_sec);
-error_cleanup:
- free((void *)dev_name);
- free((void *)dependent_dev_name);
- free((void *)jack_dev);
- free((void *)jack_control);
- free((void *)mixer_name);
- free((void *)pcm_name);
- return rc;
-}
-
-struct ucm_section *ucm_get_sections(struct cras_use_case_mgr *mgr)
-{
- struct ucm_section *sections = NULL;
- const char **list;
- int num_devs;
- int i;
- char *identifier;
-
- /* Find the list of all mixers using the control names defined in
- * the header definintion for this function. */
- identifier = snd_use_case_identifier("_devices/%s", uc_verb(mgr));
- num_devs = snd_use_case_get_list(mgr->mgr, identifier, &list);
- free(identifier);
-
- /* snd_use_case_get_list fills list with pairs of device name and
- * comment, so device names are in even-indexed elements. */
- for (i = 0; i < num_devs; i += 2) {
- if (ucm_parse_device_section(mgr, list[i], &sections) < 0) {
- ucm_section_free_list(sections);
- sections = NULL;
- break;
- }
- }
-
- if (num_devs > 0)
- snd_use_case_free_list(list, num_devs);
- return sections;
-}
-
-char *ucm_get_hotword_models(struct cras_use_case_mgr *mgr)
-{
- const char **list;
- int i, num_entries;
- int models_len = 0;
- char *models = NULL;
- const char *model_name;
- char *identifier;
-
- identifier = snd_use_case_identifier("_modifiers/%s", uc_verb(mgr));
- num_entries = snd_use_case_get_list(mgr->mgr, identifier, &list);
- free(identifier);
-
- if (num_entries <= 0)
- return 0;
-
- models = (char *)malloc(num_entries *
- (CRAS_MAX_HOTWORD_MODEL_NAME_SIZE + 1));
-
- for (i = 0; i < num_entries; i += 2) {
- if (!list[i])
- continue;
-
- if (strncmp(list[i], hotword_model_prefix,
- strlen(hotword_model_prefix)))
- continue;
-
- model_name = list[i] + strlen(hotword_model_prefix);
- while (isspace(*model_name))
- model_name++;
-
- if (strlen(model_name) > CRAS_MAX_HOTWORD_MODEL_NAME_SIZE) {
- syslog(LOG_ERR,
- "Ignore hotword model %s because the it is"
- "too long.",
- list[i]);
- continue;
- }
-
- if (models_len != 0)
- models[models_len++] = ',';
-
- strcpy(models + models_len, model_name);
- models_len += strlen(model_name);
- }
- models[models_len++] = 0;
- snd_use_case_free_list(list, num_entries);
-
- return models;
-}
-
-void ucm_disable_all_hotword_models(struct cras_use_case_mgr *mgr)
-{
- const char **list;
- int num_enmods, mod_idx;
-
- if (!mgr)
- return;
-
- /* Disable all currently enabled hotword model modifiers. */
- num_enmods = snd_use_case_get_list(mgr->mgr, "_enamods", &list);
- if (num_enmods <= 0)
- return;
-
- for (mod_idx = 0; mod_idx < num_enmods; mod_idx++) {
- if (!strncmp(list[mod_idx], hotword_model_prefix,
- strlen(hotword_model_prefix)))
- ucm_set_modifier_enabled(mgr, list[mod_idx], 0);
- }
- snd_use_case_free_list(list, num_enmods);
-}
-
-int ucm_enable_hotword_model(struct cras_use_case_mgr *mgr)
-{
- if (mgr->hotword_modifier)
- return ucm_set_modifier_enabled(mgr, mgr->hotword_modifier, 1);
- return -EINVAL;
-}
-
-static int ucm_is_modifier_enabled(struct cras_use_case_mgr *mgr,
- char *modifier, long *value)
-{
- int rc;
- char *id;
- size_t len = strlen(modifier) + 11 + 1;
-
- id = (char *)malloc(len);
-
- if (!id)
- return -ENOMEM;
-
- snprintf(id, len, "_modstatus/%s", modifier);
- rc = snd_use_case_geti(mgr->mgr, id, value);
- free(id);
- return rc;
-}
-
-int ucm_set_hotword_model(struct cras_use_case_mgr *mgr, const char *model)
-{
- char *model_mod;
- long mod_status = 0;
- size_t model_mod_size =
- strlen(model) + 1 + strlen(hotword_model_prefix) + 1;
-
- model_mod = (char *)malloc(model_mod_size);
-
- if (!model_mod)
- return -ENOMEM;
- snprintf(model_mod, model_mod_size, "%s %s", hotword_model_prefix,
- model);
- if (!ucm_mod_exists_with_name(mgr, model_mod)) {
- free((void *)model_mod);
- return -EINVAL;
- }
-
- /* If check failed, just move on, dont fail incoming model */
- if (mgr->hotword_modifier)
- ucm_is_modifier_enabled(mgr, mgr->hotword_modifier,
- &mod_status);
-
- ucm_disable_all_hotword_models(mgr);
- free(mgr->hotword_modifier);
- mgr->hotword_modifier = model_mod;
- if (mod_status)
- return ucm_enable_hotword_model(mgr);
- return 0;
-}
-
-int ucm_has_fully_specified_ucm_flag(struct cras_use_case_mgr *mgr)
-{
- char *flag;
- int ret = 0;
- flag = ucm_get_flag(mgr, fully_specified_ucm_var);
- if (!flag)
- return 0;
- ret = !strcmp(flag, "1");
- free(flag);
- return ret;
-}
-
-inline const char *
-ucm_get_playback_mixer_elem_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, playback_mixer_elem_var, dev);
-}
-
-inline const char *
-ucm_get_capture_mixer_elem_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, capture_mixer_elem_var, dev);
-}
-
-struct mixer_name *ucm_get_main_volume_names(struct cras_use_case_mgr *mgr)
-{
- return ucm_get_mixer_names(mgr, "", main_volume_names,
- CRAS_STREAM_OUTPUT, MIXER_NAME_MAIN_VOLUME);
-}
-
-int ucm_list_section_devices_by_device_name(
- struct cras_use_case_mgr *mgr, enum CRAS_STREAM_DIRECTION direction,
- const char *device_name, ucm_list_section_devices_callback cb,
- void *cb_arg)
-{
- int listed = 0;
- struct section_name *section_names, *c;
- const char *var;
- char *identifier;
-
- if (direction == CRAS_STREAM_OUTPUT)
- var = playback_device_name_var;
- else if (direction == CRAS_STREAM_INPUT)
- var = capture_device_name_var;
- else
- return 0;
-
- identifier = snd_use_case_identifier("_devices/%s", uc_verb(mgr));
- section_names = ucm_get_sections_for_var(mgr, var, device_name,
- identifier, direction);
- free(identifier);
- if (!section_names)
- return 0;
-
- DL_FOREACH (section_names, c) {
- cb(c->name, cb_arg);
- listed++;
- }
-
- DL_FOREACH (section_names, c) {
- DL_DELETE(section_names, c);
- free((void *)c->name);
- free(c);
- }
- return listed;
-}
-
-inline const char *ucm_get_jack_control_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, jack_control_var, dev);
-}
-
-inline const char *ucm_get_jack_dev_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- return ucm_get_value_for_dev(mgr, jack_dev_var, dev);
-}
-
-int ucm_get_jack_switch_for_dev(struct cras_use_case_mgr *mgr, const char *dev)
-{
- int value;
-
- int rc = get_int(mgr, jack_switch_var, dev, uc_verb(mgr), &value);
- if (rc || value < 0)
- return -1;
- return value;
-}
-
-unsigned int ucm_get_dma_period_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev)
-{
- int value;
-
- int rc = get_int(mgr, dma_period_var, dev, uc_verb(mgr), &value);
- if (rc || value < 0)
- return 0;
- return value;
-}
diff --git a/cras/src/server/cras_alsa_ucm.h b/cras/src/server/cras_alsa_ucm.h
deleted file mode 100644
index 55c3cf62..00000000
--- a/cras/src/server/cras_alsa_ucm.h
+++ /dev/null
@@ -1,512 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_ALSA_UCM_H
-#define _CRAS_ALSA_UCM_H
-
-#include <alsa/asoundlib.h>
-
-#include "cras_alsa_mixer_name.h"
-#include "cras_alsa_ucm_section.h"
-#include "cras_types.h"
-
-struct cras_use_case_mgr;
-
-/* Helpers to access UCM configuration for a card if any is provided.
- * This configuration can specify how to enable or disable certain inputs and
- * outputs on the card.
- */
-
-/* Creates a cras_use_case_mgr instance for the given card name if there is a
- * matching ucm configuration. It there is a matching UCM config, then it will
- * be configured to the default state.
- *
- * Args:
- * name - Name of the card to match against the UCM card list.
- * Returns:
- * A pointer to the use case manager if found, otherwise NULL. The pointer
- * must later be freed with ucm_destroy().
- */
-struct cras_use_case_mgr *ucm_create(const char *name);
-
-/* Destroys a cras_use_case_mgr that was returned from ucm_create.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- */
-void ucm_destroy(struct cras_use_case_mgr *mgr);
-
-/* Sets the new use case for the given cras_use_case_mgr.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from ucm_create.
- * use_case - The new use case to be set.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int ucm_set_use_case(struct cras_use_case_mgr *mgr,
- enum CRAS_STREAM_TYPE use_case);
-
-/* Checks if modifier for left right swap mode exists in ucm.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * 1 if it exists, 0 otherwise.
- */
-int ucm_swap_mode_exists(struct cras_use_case_mgr *mgr);
-
-/* Enables or disables swap mode for the given node_name. First checks
- * if the modifier is already enabled or disabled.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * node_name - The node name.
- * enable - Enable device if non-zero.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int ucm_enable_swap_mode(struct cras_use_case_mgr *mgr, const char *node_name,
- int enable);
-
-/* Checks if modifier of noise cancellation for given node_name exists in ucm.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * node_name - The node name.
- * Returns:
- * 1 if it exists, 0 otherwise.
- */
-int ucm_node_noise_cancellation_exists(struct cras_use_case_mgr *mgr,
- const char *node_name);
-
-/* Enables or disables noise cancellation for the given node_name. First checks
- * if the modifier is already enabled or disabled.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * node_name - The node name.
- * enable - Enable device if non-zero.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int ucm_enable_node_noise_cancellation(struct cras_use_case_mgr *mgr,
- const char *node_name, int enable);
-
-/* Enables or disables a UCM device. First checks if the device is already
- * enabled or disabled.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The ucm device to enable of disable.
- * enable - Enable device if non-zero.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int ucm_set_enabled(struct cras_use_case_mgr *mgr, const char *dev, int enable);
-
-/* Gets the value of given flag name.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * flag_name - The name of the flag.
- * Returns:
- * A pointer to the allocated string containing the flag value, or
- * NULL if the flag is not set.
- */
-char *ucm_get_flag(struct cras_use_case_mgr *mgr, const char *flag_name);
-
-/* Gets the capture control name which associated with given ucm device.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * ucm_dev - The ucm device to get capture control for.
- * Returns:
- * A pointer to the allocated string containing the name of the capture
- * control, or NULL if no capture control is found.
- */
-char *ucm_get_cap_control(struct cras_use_case_mgr *mgr, const char *ucm_dev);
-
-/* Gets the new node type name which user wants to override the old one for
- * given ucm device.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * ucm_dev - The ucm device to override node type.
- * Returns:
- * A pointer to the allocated string containing the new type name,
- * or NULL if no override_type_name is found.
- */
-const char *ucm_get_override_type_name(struct cras_use_case_mgr *mgr,
- const char *ucm_dev);
-
-/* Gets the name of the ucm device for the given jack name.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * jack - The name of the jack to search for.
- * direction - input or output
- * Rreturns:
- * A pointer to the allocated string containing the name of the device, or
- * NULL if no device is found.
- */
-char *ucm_get_dev_for_jack(struct cras_use_case_mgr *mgr, const char *jack,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Gets the name of the ucm device for the given mixer name.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * mixer - The name of the mixer control to search for.
- * dir - input or output
- * Rreturns:
- * A pointer to the allocated string containing the name of the device, or
- * NULL if no device is found.
- */
-char *ucm_get_dev_for_mixer(struct cras_use_case_mgr *mgr, const char *mixer,
- enum CRAS_STREAM_DIRECTION dir);
-
-/* If there is an EDID file variable specified for dev, return it. The EDID
- * file will be used for HDMI devices so supported audio formats can be checked.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for an EDID file.
- * Returns:
- * A string containing the name of the edid file on Success (Must be freed
- * later). NULL if none found.
- */
-const char *ucm_get_edid_file_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the dsp name which is associated with the given ucm device.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to get dsp name for.
- * Returns:
- * A pointer to the allocated string containing the dsp name, or NULL if no
- * dsp name is found.
- */
-const char *ucm_get_dsp_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the minimum buffer level for an output. This level will add latency to
- * all streams playing on the output, but can be used to work around an
- * unreliable dma residue.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * level - The pointer to the returned value.
- *
- */
-int ucm_get_min_buffer_level(struct cras_use_case_mgr *mgr,
- unsigned int *level);
-
-/* Gets the flag for disabling software volume.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * 0 on success, -ENOENT on failure.
- */
-unsigned int ucm_get_disable_software_volume(struct cras_use_case_mgr *mgr);
-
-/* Gets the value for default node gain.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for default node gain.
- * gain - The pointer to the returned value.
- * Returns:
- * 0 on success, other error codes on failure.
- */
-int ucm_get_default_node_gain(struct cras_use_case_mgr *mgr, const char *dev,
- long *gain);
-
-/* Gets the value for intrinsic sensitivity.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to query for intrinsic volume.
- * sensitivity - The pointer to the returned value.
- * Returns:
- * 0 on success, other error codes on failure.
- */
-int ucm_get_intrinsic_sensitivity(struct cras_use_case_mgr *mgr,
- const char *dev, long *sensitivity);
-
-/* Gets the flag if an input device can preempt hotword recording.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for preempt hotword flag.
- * Returns:
- * Non-zero value means input can preempt hotword recording, otherwise
- * return zero.
- */
-int ucm_get_preempt_hotword(struct cras_use_case_mgr *mgr, const char *dev);
-
-/* Gets the ALSA device index on the card for given UCM dev.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The UCM device to check for ALSA device index.
- * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT).
- * Returns:
- * Non-negative integer for the ALSA device index on the card, -1 if not
- * found. The ALSA device index is parsed from the PCM name which is
- * formatted as "hw:<some-name>,<idx>".
- */
-int ucm_get_alsa_dev_idx_for_dev(struct cras_use_case_mgr *mgr, const char *dev,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Gets the node name of the echo reference device on the card.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check echo reference for.
- * Returns:
- * String containing the node name of the echo reference to this
- * dev, caller is responsible to free it later. NULL if echo reference
- * doesn't exist.
- */
-const char *
-ucm_get_echo_reference_dev_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the sample rate at which to run this device.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for sample rate.
- * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT).
- * Returns:
- * The sample rate if specified, or negative error if not.
- */
-int ucm_get_sample_rate_for_dev(struct cras_use_case_mgr *mgr, const char *dev,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Gets the channel count at which to run this device.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for channel count.
- * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT).
- * channels - The pointer to the returned channel count.
- * Returns:
- * 0 on success, other error codes on failure.
- */
-int ucm_get_channels_for_dev(struct cras_use_case_mgr *mgr, const char *dev,
- enum CRAS_STREAM_DIRECTION direction,
- size_t *channels);
-
-/* Gets the capture channel map for this device.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for capture channel map.
- * channel_layout - The channel layout to fill.
- */
-int ucm_get_capture_chmap_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev, int8_t *channel_layout);
-
-/* Gets the mixer names for the coupled mixer controls of this device
- * on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for coupled mixer controls.
- * Returns:
- * A list of cras_alsa_control.
- */
-struct mixer_name *ucm_get_coupled_mixer_names(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets a list of UCM sections
- *
- * The data includes the represented devices and their controls.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer return from alsa_ucm_create.
- *
- * Returns:
- * A list of ucm_section or NULL. Free it with ucm_section_free_list().
- */
-struct ucm_section *ucm_get_sections(struct cras_use_case_mgr *mgr);
-
-/* Gets the list of supported hotword model names.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * String containing comma separated model names, e.g 'en,fr,zh'. Needs
- * to be freed by caller.
- */
-char *ucm_get_hotword_models(struct cras_use_case_mgr *mgr);
-
-/* Sets the desired hotword model.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * model - locale for model
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int ucm_set_hotword_model(struct cras_use_case_mgr *mgr, const char *model);
-
-/* Enable previously set hotword modifier
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * 0 on success or negative error code on failure.
- */
-int ucm_enable_hotword_model(struct cras_use_case_mgr *mgr);
-
-/* Disable all hotword model modifiers
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- */
-void ucm_disable_all_hotword_models(struct cras_use_case_mgr *mgr);
-
-/* Checks if this card has fully specified UCM config.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * 1 if this UCM uses fully specified UCM config. 0 otherwise.
- */
-int ucm_has_fully_specified_ucm_flag(struct cras_use_case_mgr *mgr);
-
-/* Gets the playback mixer name of this device on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for device name
- * Returns:
- * A pointer to the allocated string containing the mixer name, or NULL
- * if no device name is found.
- */
-const char *ucm_get_playback_mixer_elem_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the capture mixer name of this device on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for device name
- * Returns:
- * A pointer to the allocated string containing the mixer name, or NULL
- * if no device name is found.
- */
-const char *ucm_get_capture_mixer_elem_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the mixer names for the main volume controls on the card.
- *
- * The main volume controls in the list are considered in series.
- * If 3 controls are specified, MainVolumeNames "A,B,C", with dB ranges
- * A=-10dB~0dB, B=-20dB~0dB, C=-30dB~0dB, then applying -35dB overall volume
- * sets A=-10dB, B=-20dB, C=-5dB.
- * The volume control affects all output on this card, e.g.
- * speaker and headphone.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * names - A list of mixer_name.
- */
-struct mixer_name *ucm_get_main_volume_names(struct cras_use_case_mgr *mgr);
-
-/* The callback to be provided with a reference to the section name.
- *
- * Args:
- * section_name: The name of a SectionDevice in UCM.
- * arg - Argument to pass to this callback.
- */
-typedef void (*ucm_list_section_devices_callback)(const char *section_name,
- void *arg);
-
-/* Invokes the provided callback once for each section with matched device name.
- *
- * Iterate through each SectionDevice in UCM of this card. Invoke callback if
- * "PlaybackPCM" for output or "CapturePCM" for input of the section matches
- * the specified device_name.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * device_name - A string for device name of format "card_name:device_index".
- * cb - Function to call for each section.
- * cb_arg - Argument to pass to cb.
- * Returns:
- * Number of sections listed.
- */
-int ucm_list_section_devices_by_device_name(
- struct cras_use_case_mgr *mgr, enum CRAS_STREAM_DIRECTION direction,
- const char *device_name, ucm_list_section_devices_callback cb,
- void *cb_arg);
-
-/* Gets the jack name of this device on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for jack name.
- * Returns:
- * A pointer to the allocated string containing the jack name, or NULL
- * if no jack name is found.
- */
-const char *ucm_get_jack_name_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the jack type of this device on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for jack type.
- * Returns:
- * A pointer to the allocated string containing the jack type, or NULL
- * if no jack type is found or the found jack type is invalid. The valid
- * jack types are "hctl" or "gpio".
- */
-const char *ucm_get_jack_type_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the jack dev of this device on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for jack name.
- * Returns:
- * A pointer to the allocated string containing the input jack name, or NULL
- * if no jack name is found.
- */
-const char *ucm_get_jack_dev_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the jack control of this device on the card.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check for jack type.
- * Returns:
- * A pointer to the allocated string containing the alsa jack name, or NULL
- * if no jack type is found or the found jack type is invalid.
- */
-const char *ucm_get_jack_control_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the jack switch number for this device.
- * Some sound cards can detect multiple types of connections into the
- * audio jack - for example distinguish between line-out and headphones
- * by measuring the impedance on the other end. In that case we want each
- * jack to have it's own I/O node so that each can have it's own volume
- * settings. This allows us to specify the jack used more exactly.
- * Valid values are defined in /usr/include/linux/input.h.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check.
- * Returns:
- * A value >= 0 when the switch is defined, or -1 otherwise.
- */
-int ucm_get_jack_switch_for_dev(struct cras_use_case_mgr *mgr, const char *dev);
-
-/* Gets the DMA period time in microseconds for the given device.
- *
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * dev - The device to check.
- * Returns:
- * A value > 0, or 0 if no period is defined.
- */
-unsigned int ucm_get_dma_period_for_dev(struct cras_use_case_mgr *mgr,
- const char *dev);
-
-/* Gets the flag of optimization for no stream state.
- * This flag enables no_stream ops in alsa_io.
- * Args:
- * mgr - The cras_use_case_mgr pointer returned from alsa_ucm_create.
- * Returns:
- * 1 if the flag is enabled. 0 otherwise.
- */
-unsigned int ucm_get_optimize_no_stream_flag(struct cras_use_case_mgr *mgr);
-
-#endif /* _CRAS_ALSA_UCM_H */
diff --git a/cras/src/server/cras_alsa_ucm_section.c b/cras/src/server/cras_alsa_ucm_section.c
deleted file mode 100644
index d4df8c7d..00000000
--- a/cras/src/server/cras_alsa_ucm_section.c
+++ /dev/null
@@ -1,129 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_alsa_ucm_section.h"
-#include "cras_alsa_mixer_name.h"
-#include "utlist.h"
-
-static void ucm_section_free(struct ucm_section *section)
-{
- free((void *)section->name);
- free((void *)section->pcm_name);
- free((void *)section->jack_name);
- free((void *)section->jack_type);
- free((void *)section->mixer_name);
- mixer_name_free(section->coupled);
- free(section);
-}
-
-void ucm_section_free_list(struct ucm_section *sections)
-{
- struct ucm_section *section;
- DL_FOREACH (sections, section) {
- DL_DELETE(sections, section);
- ucm_section_free(section);
- }
-}
-
-struct ucm_section *ucm_section_create(const char *name, const char *pcm_name,
- int dev_idx, int dependent_dev_idx,
- enum CRAS_STREAM_DIRECTION dir,
- const char *jack_name,
- const char *jack_type)
-{
- struct ucm_section *section_list = NULL;
- struct ucm_section *section;
-
- if (!name)
- return NULL;
-
- section = (struct ucm_section *)calloc(1, sizeof(struct ucm_section));
- if (!section)
- return NULL;
-
- section->dev_idx = dev_idx;
- section->dependent_dev_idx = dependent_dev_idx;
- section->dir = dir;
- section->name = strdup(name);
- if (!section->name)
- goto error;
-
- section->pcm_name = strdup(pcm_name);
- if (!section->pcm_name)
- goto error;
-
- if (jack_name) {
- section->jack_name = strdup(jack_name);
- if (!section->jack_name)
- goto error;
- }
- if (jack_type) {
- section->jack_type = strdup(jack_type);
- if (!section->jack_type)
- goto error;
- }
- /* Default to -1 which means auto-detect. */
- section->jack_switch = -1;
-
- /* Make sure to initialize this item as a list. */
- DL_APPEND(section_list, section);
- return section_list;
-
-error:
- ucm_section_free(section);
- return NULL;
-}
-
-int ucm_section_set_mixer_name(struct ucm_section *section, const char *name)
-{
- if (!section || !name)
- return -EINVAL;
-
- if (section->mixer_name)
- free((void *)section->mixer_name);
- section->mixer_name = strdup(name);
- if (!section->mixer_name)
- return -ENOMEM;
- return 0;
-}
-
-int ucm_section_add_coupled(struct ucm_section *section, const char *name,
- mixer_name_type type)
-{
- struct mixer_name *m_name;
-
- if (!section || !name || type == MIXER_NAME_UNDEFINED)
- return -EINVAL;
-
- m_name = mixer_name_add(NULL, name, section->dir, type);
- if (!m_name)
- return -ENOMEM;
- DL_APPEND(section->coupled, m_name);
- return 0;
-}
-
-int ucm_section_concat_coupled(struct ucm_section *section,
- struct mixer_name *coupled)
-{
- if (!section || !coupled)
- return -EINVAL;
- DL_CONCAT(section->coupled, coupled);
- return 0;
-}
-
-void ucm_section_dump(struct ucm_section *section)
-{
- syslog(LOG_DEBUG, "section: %s [%d] (%s)", section->name,
- section->dev_idx,
- section->dir == CRAS_STREAM_OUTPUT ? "output" : "input");
- syslog(LOG_DEBUG, " jack: %s %s", section->jack_name,
- section->jack_type);
- syslog(LOG_DEBUG, " mixer_name: %s", section->mixer_name);
- mixer_name_dump(section->coupled, " coupled");
-}
diff --git a/cras/src/server/cras_alsa_ucm_section.h b/cras/src/server/cras_alsa_ucm_section.h
deleted file mode 100644
index 77c5ed89..00000000
--- a/cras/src/server/cras_alsa_ucm_section.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_ALSA_UCM_SECTION_H
-#define _CRAS_ALSA_UCM_SECTION_H
-
-#include "cras_types.h"
-#include "cras_alsa_mixer_name.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Represents an ALSA UCM section. */
-struct ucm_section {
- /* Section name. */
- const char *name;
- /* Value of PlaybackPCM or CapturePCM. */
- const char *pcm_name;
- /* Device PCM index. */
- int dev_idx;
- /* Device PCM index to associate this section to. */
- int dependent_dev_idx;
- /* Output or Input. */
- enum CRAS_STREAM_DIRECTION dir;
- /* Associated jack's name. */
- const char *jack_name;
- /* Associated jack's type. */
- const char *jack_type;
- /* Switch number for jack from linux/input.h, or -1. */
- int jack_switch;
- /* (Playback/Capture)MixerElem value. */
- const char *mixer_name;
- /* CoupledMixers value. */
- struct mixer_name *coupled;
- struct ucm_section *prev, *next;
-};
-
-/* Create a single UCM section.
- *
- * Args:
- * name - Section name (must not be NULL).
- * pcm_name - PCM name used for snd_pcm_open.
- * dev_idx - Section's device index (PCM number).
- * dependent_dev_idx - Another ALSA device index (PCM number) under which
- * we want to make this section a node.
- * dir - Device direction: INPUT or OUTPUT.
- * jack_name - Name of an associated jack (or NULL).
- * jack_type - Type of the associated jack (or NULL).
- *
- * Returns:
- * A valid pointer on success, NULL for memory allocation error.
- */
-struct ucm_section *ucm_section_create(const char *name, const char *pcm_name,
- int dev_idx, int dependent_dev_idx,
- enum CRAS_STREAM_DIRECTION dir,
- const char *jack_name,
- const char *jack_type);
-
-/* Sets the mixer_name value for the given section.
- *
- * Args:
- * section - Section to manipulate.
- * name - The name of the control.
- *
- * Returns:
- * 0 for success, -EINVAL for invalid arguments, or -ENOMEM.
- */
-int ucm_section_set_mixer_name(struct ucm_section *section, const char *name);
-
-/* Add a single coupled control to this section.
- * Control has the same direction as the section.
- *
- * Args:
- * section - Section to manipulate.
- * name - Coupled control name to add.
- * type - The type of control.
- *
- * Returns:
- * 0 for success, -EINVAL for invalid arguments, or -ENOMEM.
- */
-int ucm_section_add_coupled(struct ucm_section *section, const char *name,
- mixer_name_type type);
-
-/* Concatenate a list of coupled controls to this section.
- *
- * Args:
- * section - Section to manipulate.
- * coupled - Coupled control names to add.
- *
- * Returns:
- * 0 for success, -EINVAL for invalid arguments (NULL args).
- */
-int ucm_section_concat_coupled(struct ucm_section *section,
- struct mixer_name *coupled);
-
-/* Frees a list of sections.
- *
- * Args:
- * sections - List of sections to free.
- */
-void ucm_section_free_list(struct ucm_section *sections);
-
-/* Dump details on this section to syslog(LOG_DEBUG).
- *
- * Args:
- * section - Section to dump.
- */
-void ucm_section_dump(struct ucm_section *section);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* _CRAS_ALSA_MIXER_NAME_H */
diff --git a/cras/src/server/cras_apm_list.c b/cras/src/server/cras_apm_list.c
deleted file mode 100644
index ab891137..00000000
--- a/cras/src/server/cras_apm_list.c
+++ /dev/null
@@ -1,730 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <inttypes.h>
-#include <string.h>
-#include <syslog.h>
-
-#include <webrtc-apm/webrtc_apm.h>
-
-#include "byte_buffer.h"
-#include "cras_apm_list.h"
-#include "cras_audio_area.h"
-#include "cras_audio_format.h"
-#include "cras_dsp_pipeline.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "dsp_util.h"
-#include "dumper.h"
-#include "float_buffer.h"
-#include "iniparser_wrapper.h"
-#include "utlist.h"
-
-#define AEC_CONFIG_NAME "aec.ini"
-#define APM_CONFIG_NAME "apm.ini"
-
-/*
- * Structure holding a WebRTC audio processing module and necessary
- * info to process and transfer input buffer from device to stream.
- *
- * Below chart describes the buffer structure inside APM and how an input buffer
- * flows from a device through the APM to stream. APM processes audio buffers in
- * fixed 10ms width, and that's the main reason we need two copies of the
- * buffer:
- * (1) to cache input buffer from device until 10ms size is filled.
- * (2) to store the interleaved buffer, of 10ms size also, after APM processing.
- *
- * ________ _______ _______________________________
- * | | | | |_____________APM ____________|
- * |input |-> | DSP |---> || | | || -> stream 1
- * |device| | | | || float buf | -> | byte buf ||
- * |______| |_____| | ||___________| |__________||
- * | |_____________________________|
- * | _______________________________
- * |-> | APM 2 | -> stream 2
- * | |_____________________________|
- * | ...
- * |
- * |------------------------------------> stream N
- *
- * Members:
- * apm_ptr - An APM instance from libwebrtc_audio_processing
- * dev_ptr - Pointer to the device this APM is associated with.
- * buffer - Stores the processed/interleaved data ready for stream to read.
- * fbuffer - Stores the floating pointer buffer from input device waiting
- * for APM to process.
- * dev_fmt - The format used by the iodev this APM attaches to.
- * fmt - The audio data format configured for this APM.
- * area - The cras_audio_area used for copying processed data to client
- * stream.
- * work_queue - A task queue instance created and destroyed by
- * libwebrtc_apm.
- * is_aec_use_case - True if the input and output devices pair is in the
- * typical AEC use case. This flag decides whether to use settings
- * tuned specifically for this hardware if exists. Otherwise it uses
- * the generic settings like run inside browser.
- */
-struct cras_apm {
- webrtc_apm apm_ptr;
- void *dev_ptr;
- struct byte_buffer *buffer;
- struct float_buffer *fbuffer;
- struct cras_audio_format dev_fmt;
- struct cras_audio_format fmt;
- struct cras_audio_area *area;
- void *work_queue;
- bool is_aec_use_case;
- struct cras_apm *prev, *next;
-};
-
-/*
- * Lists of cras_apm instances created for a stream. A stream may
- * have more than one cras_apm when multiple input devices are
- * enabled. The most common scenario is the silent input iodev be
- * enabled when CRAS switches active input device.
- *
- * Note that cras_apm_list is owned and modified in main thread.
- * Only in synchronized audio thread event this cras_apm_list is safe
- * to access for passing single APM instance between threads.
- */
-struct cras_apm_list {
- void *stream_ptr;
- uint64_t effects;
- struct cras_apm *apms;
- struct cras_apm_list *prev, *next;
-};
-
-/*
- * Wrappers of APM instances that are active, which means it is associated
- * to a dev/stream pair in audio thread and ready for processing.
- *
- * Members:
- * apm - The APM for audio data processing.
- * stream_ptr - Stream pointer from the associated dev/stream pair.
- * effects - The effecets bit map of APM.
- */
-struct active_apm {
- struct cras_apm *apm;
- void *stream_ptr;
- int effects;
- struct active_apm *prev, *next;
-} * active_apms;
-
-/*
- * Object used to analyze playback audio from output iodev. It is responsible
- * to get buffer containing latest output data and provide it to the APM
- * instances which want to analyze reverse stream.
- * Member:
- * ext - The interface implemented to process reverse(output) stream
- * data in various formats.
- * fbuf - Middle buffer holding reverse data for APMs to analyze.
- * odev - Pointer to the output iodev playing audio as the reverse
- * stream. NULL if there's no playback stream.
- * dev_rate - The sample rate odev is opened for.
- * process_reverse - Flag to indicate if there's APM has effect that
- * needs to process reverse stream.
- */
-struct cras_apm_reverse_module {
- struct ext_dsp_module ext;
- struct float_buffer *fbuf;
- struct cras_iodev *odev;
- unsigned int dev_rate;
- unsigned process_reverse;
-};
-
-static struct cras_apm_reverse_module *rmodule = NULL;
-static const char *aec_config_dir = NULL;
-static char ini_name[MAX_INI_NAME_LENGTH + 1];
-static dictionary *aec_ini = NULL;
-static dictionary *apm_ini = NULL;
-
-/* Update the global process reverse flag. Should be called when apms are added
- * or removed. */
-static void update_process_reverse_flag()
-{
- struct active_apm *active;
-
- if (!rmodule)
- return;
- rmodule->process_reverse = 0;
- DL_FOREACH (active_apms, active) {
- rmodule->process_reverse |=
- !!(active->effects & APM_ECHO_CANCELLATION);
- }
-}
-
-static void apm_destroy(struct cras_apm **apm)
-{
- if (*apm == NULL)
- return;
- byte_buffer_destroy(&(*apm)->buffer);
- float_buffer_destroy(&(*apm)->fbuffer);
- cras_audio_area_destroy((*apm)->area);
-
- /* Any unfinished AEC dump handle will be closed. */
- webrtc_apm_destroy((*apm)->apm_ptr);
- free(*apm);
- *apm = NULL;
-}
-
-struct cras_apm_list *cras_apm_list_create(void *stream_ptr, uint64_t effects)
-{
- struct cras_apm_list *list;
-
- if (effects == 0)
- return NULL;
-
- list = (struct cras_apm_list *)calloc(1, sizeof(*list));
- if (list == NULL) {
- syslog(LOG_ERR, "No memory in creating apm list");
- return NULL;
- }
- list->stream_ptr = stream_ptr;
- list->effects = effects;
- list->apms = NULL;
-
- return list;
-}
-
-static struct active_apm *get_active_apm(void *stream_ptr, void *dev_ptr)
-{
- struct active_apm *active;
-
- DL_FOREACH (active_apms, active) {
- if ((active->apm->dev_ptr == dev_ptr) &&
- (active->stream_ptr == stream_ptr))
- return active;
- }
- return NULL;
-}
-
-struct cras_apm *cras_apm_list_get_active_apm(void *stream_ptr, void *dev_ptr)
-{
- struct active_apm *active = get_active_apm(stream_ptr, dev_ptr);
- return active ? active->apm : NULL;
-}
-
-uint64_t cras_apm_list_get_effects(struct cras_apm_list *list)
-{
- if (list == NULL)
- return 0;
- else
- return list->effects;
-}
-
-void cras_apm_list_remove_apm(struct cras_apm_list *list, void *dev_ptr)
-{
- struct cras_apm *apm;
-
- DL_FOREACH (list->apms, apm) {
- if (apm->dev_ptr == dev_ptr) {
- DL_DELETE(list->apms, apm);
- apm_destroy(&apm);
- }
- }
-}
-
-/*
- * WebRTC APM handles no more than stereo + keyboard mic channels.
- * Ignore keyboard mic feature for now because that requires processing on
- * mixed buffer from two input devices. Based on that we should modify the best
- * channel layout for APM use.
- * Args:
- * apm_fmt - Pointer to a format struct already filled with the value of
- * the open device format. Its content may be modified for APM use.
- */
-static void get_best_channels(struct cras_audio_format *apm_fmt)
-{
- int ch;
- int8_t layout[CRAS_CH_MAX];
-
- /* Using the format from dev_fmt is dangerous because input device
- * could have wild configurations like unuse the 1st channel and
- * connects 2nd channel to the only mic. Data in the first channel
- * is what APM cares about so always construct a new channel layout
- * containing subset of original channels that matches either FL, FR,
- * or FC.
- * TODO(hychao): extend the logic when we have a stream that wants
- * to record channels like RR(rear right).
- */
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- layout[ch] = -1;
-
- apm_fmt->num_channels = 0;
- if (apm_fmt->channel_layout[CRAS_CH_FL] != -1)
- layout[CRAS_CH_FL] = apm_fmt->num_channels++;
- if (apm_fmt->channel_layout[CRAS_CH_FR] != -1)
- layout[CRAS_CH_FR] = apm_fmt->num_channels++;
- if (apm_fmt->channel_layout[CRAS_CH_FC] != -1)
- layout[CRAS_CH_FC] = apm_fmt->num_channels++;
-
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- apm_fmt->channel_layout[ch] = layout[ch];
-}
-
-struct cras_apm *cras_apm_list_add_apm(struct cras_apm_list *list,
- void *dev_ptr,
- const struct cras_audio_format *dev_fmt,
- bool is_aec_use_case)
-{
- struct cras_apm *apm;
-
- DL_FOREACH (list->apms, apm)
- if (apm->dev_ptr == dev_ptr)
- return apm;
-
- // TODO(hychao): Remove the check when we enable more effects.
- if (!(list->effects & APM_ECHO_CANCELLATION))
- return NULL;
-
- apm = (struct cras_apm *)calloc(1, sizeof(*apm));
-
- /* Configures APM to the format used by input device. If the channel
- * count is larger than stereo, use the standard channel count/layout
- * in APM. */
- apm->dev_fmt = *dev_fmt;
- apm->fmt = *dev_fmt;
- get_best_channels(&apm->fmt);
-
- /* Use tuned settings only when the forward dev(capture) and reverse
- * dev(playback) both are in typical AEC use case. */
- apm->is_aec_use_case = is_aec_use_case;
- if (rmodule->odev) {
- apm->is_aec_use_case &=
- cras_iodev_is_aec_use_case(rmodule->odev->active_node);
- }
-
- /* Use the configs tuned specifically for internal device. Otherwise
- * just pass NULL so every other settings will be default. */
- apm->apm_ptr =
- apm->is_aec_use_case ?
- webrtc_apm_create(apm->fmt.num_channels,
- apm->fmt.frame_rate, aec_ini,
- apm_ini) :
- webrtc_apm_create(apm->fmt.num_channels,
- apm->fmt.frame_rate, NULL, NULL);
- if (apm->apm_ptr == NULL) {
- syslog(LOG_ERR,
- "Fail to create webrtc apm for ch %zu"
- " rate %zu effect %" PRIu64,
- dev_fmt->num_channels, dev_fmt->frame_rate,
- list->effects);
- free(apm);
- return NULL;
- }
-
- apm->dev_ptr = dev_ptr;
- apm->work_queue = NULL;
-
- /* WebRTC APM wants 10 ms equivalence of data to process. */
- apm->buffer = byte_buffer_create(10 * apm->fmt.frame_rate / 1000 *
- cras_get_format_bytes(&apm->fmt));
- apm->fbuffer = float_buffer_create(10 * apm->fmt.frame_rate / 1000,
- apm->fmt.num_channels);
- apm->area = cras_audio_area_create(apm->fmt.num_channels);
- cras_audio_area_config_channels(apm->area, &apm->fmt);
-
- DL_APPEND(list->apms, apm);
-
- return apm;
-}
-
-void cras_apm_list_start_apm(struct cras_apm_list *list, void *dev_ptr)
-{
- struct active_apm *active;
- struct cras_apm *apm;
-
- if (list == NULL)
- return;
-
- /* Check if this apm has already been started. */
- apm = cras_apm_list_get_active_apm(list->stream_ptr, dev_ptr);
- if (apm)
- return;
-
- DL_SEARCH_SCALAR(list->apms, apm, dev_ptr, dev_ptr);
- if (apm == NULL)
- return;
-
- active = (struct active_apm *)calloc(1, sizeof(*active));
- if (active == NULL) {
- syslog(LOG_ERR, "No memory to start apm.");
- return;
- }
- active->apm = apm;
- active->stream_ptr = list->stream_ptr;
- active->effects = list->effects;
- DL_APPEND(active_apms, active);
-
- update_process_reverse_flag();
-}
-
-void cras_apm_list_stop_apm(struct cras_apm_list *list, void *dev_ptr)
-{
- struct active_apm *active;
-
- if (list == NULL)
- return;
-
- active = get_active_apm(list->stream_ptr, dev_ptr);
- if (active) {
- DL_DELETE(active_apms, active);
- free(active);
- }
-
- update_process_reverse_flag();
-}
-
-int cras_apm_list_destroy(struct cras_apm_list *list)
-{
- struct cras_apm *apm;
-
- DL_FOREACH (list->apms, apm) {
- DL_DELETE(list->apms, apm);
- apm_destroy(&apm);
- }
- free(list);
-
- return 0;
-}
-
-/*
- * Determines the iodev to be used as the echo reference for APM reverse
- * analysis. If there exists the special purpose "echo reference dev" then
- * use it. Otherwise just use this output iodev.
- */
-static struct cras_iodev *get_echo_reference_target(struct cras_iodev *iodev)
-{
- return iodev->echo_reference_dev ? iodev->echo_reference_dev : iodev;
-}
-
-/*
- * Updates the first enabled output iodev in the list, determine the echo
- * reference target base on this output iodev, and register rmodule as ext dsp
- * module to this echo reference target.
- * When this echo reference iodev is opened and audio data flows through its
- * dsp pipeline, APMs will anaylize the reverse stream. This is expected to be
- * called in main thread when output devices enable/dsiable state changes.
- */
-static void update_first_output_dev_to_process()
-{
- struct cras_iodev *echo_ref;
- struct cras_iodev *iodev =
- cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT);
-
- if (iodev == NULL)
- return;
-
- echo_ref = get_echo_reference_target(iodev);
-
- /* If rmodule is already tracking echo_ref, do nothing. */
- if (rmodule->odev == echo_ref)
- return;
-
- /* Detach from the old iodev that rmodule was tracking. */
- if (rmodule->odev) {
- cras_iodev_set_ext_dsp_module(rmodule->odev, NULL);
- rmodule->odev = NULL;
- }
-
- rmodule->odev = echo_ref;
- cras_iodev_set_ext_dsp_module(echo_ref, &rmodule->ext);
-}
-
-static void handle_device_enabled(struct cras_iodev *iodev, void *cb_data)
-{
- if (iodev->direction != CRAS_STREAM_OUTPUT)
- return;
-
- /* Register to the first enabled output device. */
- update_first_output_dev_to_process();
-}
-
-static void handle_device_disabled(struct cras_iodev *iodev, void *cb_data)
-{
- struct cras_iodev *echo_ref;
-
- if (iodev->direction != CRAS_STREAM_OUTPUT)
- return;
-
- echo_ref = get_echo_reference_target(iodev);
-
- if (rmodule->odev == echo_ref) {
- cras_iodev_set_ext_dsp_module(echo_ref, NULL);
- rmodule->odev = NULL;
- }
-
- /* Register to the first enabled output device. */
- update_first_output_dev_to_process();
-}
-
-static int process_reverse(struct float_buffer *fbuf, unsigned int frame_rate)
-{
- struct active_apm *active;
- int ret;
- float *const *wp;
-
- if (float_buffer_writable(fbuf))
- return 0;
-
- wp = float_buffer_write_pointer(fbuf);
-
- DL_FOREACH (active_apms, active) {
- if (!(active->effects & APM_ECHO_CANCELLATION))
- continue;
-
- ret = webrtc_apm_process_reverse_stream_f(active->apm->apm_ptr,
- fbuf->num_channels,
- frame_rate, wp);
- if (ret) {
- syslog(LOG_ERR, "APM process reverse err");
- return ret;
- }
- }
- float_buffer_reset(fbuf);
- return 0;
-}
-
-void reverse_data_run(struct ext_dsp_module *ext, unsigned int nframes)
-{
- struct cras_apm_reverse_module *rmod =
- (struct cras_apm_reverse_module *)ext;
- unsigned int writable;
- int i, offset = 0;
- float *const *wp;
-
- if (!rmod->process_reverse)
- return;
-
- while (nframes) {
- process_reverse(rmod->fbuf, rmod->dev_rate);
- writable = float_buffer_writable(rmod->fbuf);
- writable = MIN(nframes, writable);
- wp = float_buffer_write_pointer(rmod->fbuf);
- for (i = 0; i < rmod->fbuf->num_channels; i++)
- memcpy(wp[i], ext->ports[i] + offset,
- writable * sizeof(float));
-
- offset += writable;
- float_buffer_written(rmod->fbuf, writable);
- nframes -= writable;
- }
-}
-
-void reverse_data_configure(struct ext_dsp_module *ext,
- unsigned int buffer_size, unsigned int num_channels,
- unsigned int rate)
-{
- struct cras_apm_reverse_module *rmod =
- (struct cras_apm_reverse_module *)ext;
- if (rmod->fbuf)
- float_buffer_destroy(&rmod->fbuf);
- rmod->fbuf = float_buffer_create(rate / 100, num_channels);
- rmod->dev_rate = rate;
-}
-
-static void get_aec_ini(const char *config_dir)
-{
- snprintf(ini_name, MAX_INI_NAME_LENGTH, "%s/%s", config_dir,
- AEC_CONFIG_NAME);
- ini_name[MAX_INI_NAME_LENGTH] = '\0';
-
- if (aec_ini) {
- iniparser_freedict(aec_ini);
- aec_ini = NULL;
- }
- aec_ini = iniparser_load_wrapper(ini_name);
- if (aec_ini == NULL)
- syslog(LOG_INFO, "No aec ini file %s", ini_name);
-}
-
-static void get_apm_ini(const char *config_dir)
-{
- snprintf(ini_name, MAX_INI_NAME_LENGTH, "%s/%s", config_dir,
- APM_CONFIG_NAME);
- ini_name[MAX_INI_NAME_LENGTH] = '\0';
-
- if (apm_ini) {
- iniparser_freedict(apm_ini);
- apm_ini = NULL;
- }
- apm_ini = iniparser_load_wrapper(ini_name);
- if (apm_ini == NULL)
- syslog(LOG_INFO, "No apm ini file %s", ini_name);
-}
-
-int cras_apm_list_init(const char *device_config_dir)
-{
- if (rmodule == NULL) {
- rmodule = (struct cras_apm_reverse_module *)calloc(
- 1, sizeof(*rmodule));
- rmodule->ext.run = reverse_data_run;
- rmodule->ext.configure = reverse_data_configure;
- }
-
- aec_config_dir = device_config_dir;
- get_aec_ini(aec_config_dir);
- get_apm_ini(aec_config_dir);
-
- update_first_output_dev_to_process();
- cras_iodev_list_set_device_enabled_callback(
- handle_device_enabled, handle_device_disabled, rmodule);
-
- return 0;
-}
-
-void cras_apm_list_reload_aec_config()
-{
- if (NULL == aec_config_dir)
- return;
-
- get_aec_ini(aec_config_dir);
- get_apm_ini(aec_config_dir);
-
- /* Dump the config content at reload only, for debug. */
- webrtc_apm_dump_configs(apm_ini, aec_ini);
-}
-
-int cras_apm_list_deinit()
-{
- if (rmodule) {
- if (rmodule->fbuf)
- float_buffer_destroy(&rmodule->fbuf);
- free(rmodule);
- rmodule = NULL;
- }
- return 0;
-}
-
-int cras_apm_list_process(struct cras_apm *apm, struct float_buffer *input,
- unsigned int offset)
-{
- unsigned int writable, nframes, nread;
- int ch, i, j, ret;
- float *const *wp;
- float *const *rp;
-
- nread = float_buffer_level(input);
- if (nread < offset) {
- syslog(LOG_ERR, "Process offset exceeds read level");
- return -EINVAL;
- }
-
- writable = float_buffer_writable(apm->fbuffer);
- writable = MIN(nread - offset, writable);
-
- nframes = writable;
- while (nframes) {
- nread = nframes;
- wp = float_buffer_write_pointer(apm->fbuffer);
- rp = float_buffer_read_pointer(input, offset, &nread);
-
- for (i = 0; i < apm->fbuffer->num_channels; i++) {
- /* Look up the channel position and copy from
- * the correct index of |input| buffer.
- */
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- if (apm->fmt.channel_layout[ch] == i)
- break;
- if (ch == CRAS_CH_MAX)
- continue;
-
- j = apm->dev_fmt.channel_layout[ch];
- if (j == -1)
- continue;
-
- memcpy(wp[i], rp[j], nread * sizeof(float));
- }
-
- nframes -= nread;
- offset += nread;
-
- float_buffer_written(apm->fbuffer, nread);
- }
-
- /* process and move to int buffer */
- if ((float_buffer_writable(apm->fbuffer) == 0) &&
- (buf_queued(apm->buffer) == 0)) {
- nread = float_buffer_level(apm->fbuffer);
- rp = float_buffer_read_pointer(apm->fbuffer, 0, &nread);
- ret = webrtc_apm_process_stream_f(apm->apm_ptr,
- apm->fmt.num_channels,
- apm->fmt.frame_rate, rp);
- if (ret) {
- syslog(LOG_ERR, "APM process stream f err");
- return ret;
- }
-
- dsp_util_interleave(rp, buf_write_pointer(apm->buffer),
- apm->fbuffer->num_channels, apm->fmt.format,
- nread);
- buf_increment_write(apm->buffer,
- nread * cras_get_format_bytes(&apm->fmt));
- float_buffer_reset(apm->fbuffer);
- }
-
- return writable;
-}
-
-struct cras_audio_area *cras_apm_list_get_processed(struct cras_apm *apm)
-{
- uint8_t *buf_ptr;
-
- buf_ptr = buf_read_pointer_size(apm->buffer, &apm->area->frames);
- apm->area->frames /= cras_get_format_bytes(&apm->fmt);
- cras_audio_area_config_buf_pointers(apm->area, &apm->fmt, buf_ptr);
- return apm->area;
-}
-
-void cras_apm_list_put_processed(struct cras_apm *apm, unsigned int frames)
-{
- buf_increment_read(apm->buffer,
- frames * cras_get_format_bytes(&apm->fmt));
-}
-
-struct cras_audio_format *cras_apm_list_get_format(struct cras_apm *apm)
-{
- return &apm->fmt;
-}
-
-bool cras_apm_list_get_use_tuned_settings(struct cras_apm *apm)
-{
- /* If input and output devices in AEC use case, plus that a
- * tuned setting is provided. */
- return apm->is_aec_use_case && (aec_ini || apm_ini);
-}
-
-void cras_apm_list_set_aec_dump(struct cras_apm_list *list, void *dev_ptr,
- int start, int fd)
-{
- struct cras_apm *apm;
- char file_name[256];
- int rc;
- FILE *handle;
-
- DL_SEARCH_SCALAR(list->apms, apm, dev_ptr, dev_ptr);
- if (apm == NULL)
- return;
-
- if (start) {
- handle = fdopen(fd, "w");
- if (handle == NULL) {
- syslog(LOG_ERR, "Create dump handle fail, errno %d",
- errno);
- return;
- }
- /* webrtc apm will own the FILE handle and close it. */
- rc = webrtc_apm_aec_dump(apm->apm_ptr, &apm->work_queue, start,
- handle);
- if (rc)
- syslog(LOG_ERR, "Fail to dump debug file %s, rc %d",
- file_name, rc);
- } else {
- rc = webrtc_apm_aec_dump(apm->apm_ptr, &apm->work_queue, 0,
- NULL);
- if (rc)
- syslog(LOG_ERR, "Failed to stop apm debug, rc %d", rc);
- }
-}
diff --git a/cras/src/server/cras_apm_list.h b/cras/src/server/cras_apm_list.h
deleted file mode 100644
index 7a36ceae..00000000
--- a/cras/src/server/cras_apm_list.h
+++ /dev/null
@@ -1,248 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_APM_LIST_H_
-#define CRAS_APM_LIST_H_
-
-#include "cras_types.h"
-
-struct cras_audio_area;
-struct cras_audio_format;
-struct cras_apm;
-struct cras_apm_list;
-struct float_buffer;
-
-#ifdef HAVE_WEBRTC_APM
-
-/* Initialize the apm list for analyzing output data. */
-int cras_apm_list_init(const char *device_config_dir);
-
-/* Reloads the aec config. Used for debug and tuning. */
-void cras_apm_list_reload_aec_config();
-
-/* Deinitialize apm list to free all allocated resources. */
-int cras_apm_list_deinit();
-
-/*
- * Creates an list to hold all APM instances created when a stream
- * attaches to iodev(s). This should be called in main thread.
- *
- * Below diagram explains the life cycle of an APM instance, how are
- * related APIs used, and in which thread should each API be called.
- *
- * Main thread Audio thread
- * maintaining apm_list maintaining active_apms
- * ----------- ------------
- * cras_apm_list_create
- * cras_apm_list_add_apm -> cras_apm_list_start_apm
- *
- * cras_apm_list_get_active_apm
- * cras_apm_list_process
- * cras_apm_list_get_processed
- * cras_apm_list_put_processed
- *
- * cras_apm_list_remove_apm <- cras_apm_list_stop_apm
- * cras_apm_list_destroy
- *
- * Args:
- * stream_ptr - Pointer to the stream.
- * effects - Bit map specifying the enabled effects on this stream.
- */
-struct cras_apm_list *cras_apm_list_create(void *stream_ptr, uint64_t effects);
-
-/*
- * Creates a cras_apm associated to given dev_ptr and adds it to the list.
- * If there already exists an APM instance linked to dev_ptr, we assume
- * the open format is unchanged so just return it. This should be called
- * in main thread.
- * Args:
- * list - The list holding APM instances.
- * dev_ptr - Pointer to the iodev to add new APM for.
- * fmt - Format of the audio data used for this cras_apm.
- * is_aec_use_case - If the dev_ptr is for typical AEC use case.
- */
-struct cras_apm *cras_apm_list_add_apm(struct cras_apm_list *list,
- void *dev_ptr,
- const struct cras_audio_format *fmt,
- bool is_aec_use_case);
-
-/*
- * Gets the active APM instance that is associated to given stream and dev pair.
- * This should be called in audio thread.
- * Args:
- * stream_ptr - Pointer to the stream.
- * dev_ptr - The iodev as key to look up associated APM.
- */
-struct cras_apm *cras_apm_list_get_active_apm(void *stream_ptr, void *dev_ptr);
-
-/*
- * Starts the APM instance in the list that is associated with dev_ptr by
- * adding it to the active APM list in audio thread.
- */
-void cras_apm_list_start_apm(struct cras_apm_list *list, void *dev_ptr);
-
-/*
- * Stops the APM instance in the list that is associated with dev_ptr by
- * removing it from the active APM list in audio thread.
- */
-void cras_apm_list_stop_apm(struct cras_apm_list *list, void *dev_ptr);
-
-/*
- * Gets the effects bit map of the APM list.
- * Args:
- * list - The list holding APM instances.
- */
-uint64_t cras_apm_list_get_effects(struct cras_apm_list *list);
-
-/* Removes a cras_apm from list and destroys it. */
-int cras_apm_list_destroy(struct cras_apm_list *list);
-
-/*
- * Removes an APM from the list, expected to be used when an iodev is no
- * longer open for the client stream holding the APM list. This should
- * be called in main thread.
- * Args:
- * list - The list holding APM instances.
- * dev_ptr - Device pointer used to look up which apm to remove.
- */
-void cras_apm_list_remove_apm(struct cras_apm_list *list, void *dev_ptr);
-
-/* Passes audio data from hardware for cras_apm to process.
- * Args:
- * apm - The cras_apm instance.
- * input - Float buffer from device for apm to process.
- * offset - Offset in |input| to note the data position to start
- * reading.
- */
-int cras_apm_list_process(struct cras_apm *apm, struct float_buffer *input,
- unsigned int offset);
-
-/* Gets the APM processed data in the form of audio area.
- * Args:
- * apm - The cras_apm instance that owns the audio area pointer and
- * processed data.
- * Returns:
- * The audio area used to read processed data. No need to free
- * by caller.
- */
-struct cras_audio_area *cras_apm_list_get_processed(struct cras_apm *apm);
-
-/* Tells |apm| that |frames| of processed data has been used, so |apm|
- * can allocate space to read more from input device.
- * Args:
- * apm - The cras_apm instance owns the processed data.
- * frames - The number in frames of processed data to mark as used.
- */
-void cras_apm_list_put_processed(struct cras_apm *apm, unsigned int frames);
-
-/* Gets the format of the actual data processed by webrtc-apm library.
- * Args:
- * apm - The cras_apm instance holding audio data and format info.
- */
-struct cras_audio_format *cras_apm_list_get_format(struct cras_apm *apm);
-
-/*
- * Gets if this apm instance is using tuned settings.
- */
-bool cras_apm_list_get_use_tuned_settings(struct cras_apm *apm);
-
-/* Sets debug recording to start or stop.
- * Args:
- * list - List contains the apm instance to start/stop debug recording.
- * dev_ptr - Use as key to look up specific apm to do aec dump.
- * start - True to set debug recording start, otherwise stop.
- * fd - File descriptor to aec dump destination.
- */
-void cras_apm_list_set_aec_dump(struct cras_apm_list *list, void *dev_ptr,
- int start, int fd);
-
-#else
-
-/*
- * If webrtc audio processing library is not available then define all
- * cras_apm_list functions as empty. As long as cras_apm_list_add returns
- * NULL, non of the other functions should be called.
- */
-static inline int cras_apm_list_init(const char *device_config_dir)
-{
- return 0;
-}
-static inline void cras_apm_list_reload_aec_config()
-{
-}
-static inline struct cras_apm_list *cras_apm_list_create(void *stream_ptr,
- unsigned int effects)
-{
- return NULL;
-}
-static inline struct cras_apm *
-cras_apm_list_add_apm(struct cras_apm_list *list, void *dev_ptr,
- const struct cras_audio_format *fmt, bool is_aec_use_case)
-{
- return NULL;
-}
-static inline struct cras_apm *cras_apm_list_get_active_apm(void *stream_ptr,
- void *dev_ptr)
-{
- return NULL;
-}
-static inline uint64_t cras_apm_list_get_effects(struct cras_apm_list *list)
-{
- return 0;
-}
-static inline int cras_apm_list_destroy(struct cras_apm_list *list)
-{
- return 0;
-}
-static inline void cras_apm_list_remove_apm(struct cras_apm_list *list,
- void *dev_ptr)
-{
-}
-
-static inline int cras_apm_list_process(struct cras_apm *apm,
- struct float_buffer *input,
- unsigned int offset)
-{
- return 0;
-}
-
-static inline struct cras_audio_area *
-cras_apm_list_get_processed(struct cras_apm *apm)
-{
- return NULL;
-}
-
-static inline void cras_apm_list_put_processed(struct cras_apm *apm,
- unsigned int frames)
-{
-}
-static inline void cras_apm_list_start_apm(struct cras_apm_list *list,
- void *dev_ptr)
-{
-}
-static inline void cras_apm_list_stop_apm(struct cras_apm_list *list,
- void *dev_ptr)
-{
-}
-
-static inline struct cras_audio_format *
-cras_apm_list_get_format(struct cras_apm *apm)
-{
- return NULL;
-}
-
-static inline bool cras_apm_list_get_use_tuned_settings(struct cras_apm *apm)
-{
- return 0;
-}
-
-static inline void cras_apm_list_set_aec_dump(struct cras_apm_list *list,
- void *dev_ptr, int start, int fd)
-{
-}
-
-#endif /* HAVE_WEBRTC_APM */
-
-#endif /* CRAS_APM_LIST_H_ */
diff --git a/cras/src/server/cras_audio_area.c b/cras/src/server/cras_audio_area.c
deleted file mode 100644
index 18615733..00000000
--- a/cras/src/server/cras_audio_area.c
+++ /dev/null
@@ -1,105 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include <sys/param.h>
-
-#include "cras_audio_area.h"
-#include "cras_audio_format.h"
-#include "cras_mix.h"
-
-struct cras_audio_area *cras_audio_area_create(int num_channels)
-{
- struct cras_audio_area *area;
- size_t sz;
-
- sz = sizeof(*area) + num_channels * sizeof(struct cras_channel_area);
- area = calloc(1, sz);
- area->num_channels = num_channels;
-
- return area;
-}
-
-unsigned int cras_audio_area_copy(const struct cras_audio_area *dst,
- unsigned int dst_offset,
- const struct cras_audio_format *dst_fmt,
- const struct cras_audio_area *src,
- unsigned int src_offset,
- float software_gain_scaler)
-{
- unsigned int src_idx, dst_idx;
- unsigned int ncopy;
- uint8_t *schan, *dchan;
-
- ncopy = MIN(src->frames - src_offset, dst->frames - dst_offset);
-
- /* TODO(dgreid) - this replaces a memcpy, it needs to be way faster. */
- for (src_idx = 0; src_idx < src->num_channels; src_idx++) {
- for (dst_idx = 0; dst_idx < dst->num_channels; dst_idx++) {
- if (!(src->channels[src_idx].ch_set &
- dst->channels[dst_idx].ch_set))
- continue;
-
- schan = src->channels[src_idx].buf +
- src_offset * src->channels[src_idx].step_bytes;
- dchan = dst->channels[dst_idx].buf +
- dst_offset * dst->channels[dst_idx].step_bytes;
-
- cras_mix_add_scale_stride(
- dst_fmt->format, dchan, schan, ncopy,
- dst->channels[dst_idx].step_bytes,
- src->channels[src_idx].step_bytes,
- software_gain_scaler);
- }
- }
-
- return ncopy;
-}
-
-void cras_audio_area_destroy(struct cras_audio_area *area)
-{
- free(area);
-}
-
-void cras_audio_area_config_channels(struct cras_audio_area *area,
- const struct cras_audio_format *fmt)
-{
- unsigned int i, ch;
-
- /* For mono, config the channel type to match both front
- * left and front right.
- * TODO(hychao): add more mapping when we have like {FL, FC}
- * for mono + kb mic.
- */
- if ((fmt->num_channels == 1) &&
- ((fmt->channel_layout[CRAS_CH_FC] == 0) ||
- (fmt->channel_layout[CRAS_CH_FL] == 0))) {
- channel_area_set_channel(area->channels, CRAS_CH_FL);
- channel_area_set_channel(area->channels, CRAS_CH_FR);
- return;
- }
-
- for (i = 0; i < fmt->num_channels; i++) {
- area->channels[i].ch_set = 0;
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- if (fmt->channel_layout[ch] == i)
- channel_area_set_channel(&area->channels[i],
- ch);
- }
-}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area *area,
- const struct cras_audio_format *fmt,
- uint8_t *base_buffer)
-{
- int i;
- const int sample_size = snd_pcm_format_physical_width(fmt->format) / 8;
-
- /* TODO(dgreid) - assuming interleaved audio here for now. */
- for (i = 0; i < area->num_channels; i++) {
- area->channels[i].step_bytes = cras_get_format_bytes(fmt);
- area->channels[i].buf = base_buffer + i * sample_size;
- }
-}
diff --git a/cras/src/server/cras_audio_area.h b/cras/src/server/cras_audio_area.h
deleted file mode 100644
index fe042325..00000000
--- a/cras/src/server/cras_audio_area.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_AUDIO_AREA_H_
-#define CRAS_AUDIO_AREA_H_
-
-#include <stdint.h>
-
-#include "cras_audio_format.h"
-
-/*
- * Descriptor of the memory area holding a channel of audio.
- * Members:
- * ch_set - Bit set of channels this channel area could map to.
- * step_bytes - The number of bytes between adjacent samples.
- * buf - A pointer to the start address of this area.
- */
-struct cras_channel_area {
- unsigned int ch_set;
- unsigned int step_bytes;
- uint8_t *buf;
-};
-
-/*
- * Descriptor of the memory area that provides various access to audio channels.
- * Members:
- * frames - The size of the audio buffer in frames.
- * num_channels - The number of channels in the audio area.
- * channels - array of channel areas.
- */
-struct cras_audio_area {
- unsigned int frames;
- unsigned int num_channels;
- struct cras_channel_area channels[];
-};
-
-/*
- * Sets the channel bit for a channel area.
- * Args:
- * ca - the channel area to set channel bit set.
- * channel - the channel bit to add to the channel area.
- */
-static inline void channel_area_set_channel(struct cras_channel_area *ca,
- enum CRAS_CHANNEL channel)
-{
- ca->ch_set |= (1 << channel);
-}
-
-/*
- * Creates a cras_audio_area.
- * Args:
- * num_channels - The number of channels in the audio area.
-*/
-struct cras_audio_area *cras_audio_area_create(int num_channels);
-
-/*
- * Copies a cras_audio_area to another cras_audio_area with given offset.
- * Args:
- * dst - The destination audio area.
- * dst_offset - The offset of dst audio area in frames.
- * format - The format of dst area.
- * src - The source audio area.
- * src_offset - The offset of src audio area in frames.
- * software_gain_scaler - The software gain scaler needed.
- * Returns the number of frames copied.
- */
-unsigned int cras_audio_area_copy(const struct cras_audio_area *dst,
- unsigned int dst_offset,
- const struct cras_audio_format *dst_fmt,
- const struct cras_audio_area *src,
- unsigned int src_offset,
- float software_gain_scaler);
-
-/*
- * Destroys a cras_audio_area.
- * Args:
- * area - the audio area to destroy
- */
-void cras_audio_area_destroy(struct cras_audio_area *area);
-
-/*
- * Configures the channel types based on the audio format.
- * Args:
- * area - The audio area created with cras_audio_area_create.
- * fmt - The format to use to configure the channels.
- */
-void cras_audio_area_config_channels(struct cras_audio_area *area,
- const struct cras_audio_format *fmt);
-
-/*
- * Sets the buffer pointers for each channel.
- */
-void cras_audio_area_config_buf_pointers(struct cras_audio_area *area,
- const struct cras_audio_format *fmt,
- uint8_t *base_buffer);
-
-#endif /* CRAS_AUDIO_AREA_H_ */
diff --git a/cras/src/server/cras_audio_thread_monitor.c b/cras/src/server/cras_audio_thread_monitor.c
deleted file mode 100644
index ed3afbac..00000000
--- a/cras/src/server/cras_audio_thread_monitor.c
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdbool.h>
-#include <syslog.h>
-#include "audio_thread.h"
-#include "cras_iodev_list.h"
-#include "cras_main_message.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_util.h"
-
-#define MIN_WAIT_SECOND 30
-
-struct cras_audio_thread_event_message {
- struct cras_main_message header;
- enum CRAS_AUDIO_THREAD_EVENT_TYPE event_type;
-};
-
-static void take_snapshot(enum CRAS_AUDIO_THREAD_EVENT_TYPE event_type)
-{
- struct cras_audio_thread_snapshot *snapshot;
-
- snapshot = (struct cras_audio_thread_snapshot *)calloc(
- 1, sizeof(struct cras_audio_thread_snapshot));
- struct timespec now_time;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now_time);
- snapshot->timestamp = now_time;
- snapshot->event_type = event_type;
- audio_thread_dump_thread_info(cras_iodev_list_get_audio_thread(),
- &snapshot->audio_debug_info);
- cras_system_state_add_snapshot(snapshot);
-}
-
-static void cras_audio_thread_event_message_init(
- struct cras_audio_thread_event_message *msg,
- enum CRAS_AUDIO_THREAD_EVENT_TYPE event_type)
-{
- msg->header.type = CRAS_MAIN_AUDIO_THREAD_EVENT;
- msg->header.length = sizeof(*msg);
- msg->event_type = event_type;
-}
-
-int cras_audio_thread_event_send(enum CRAS_AUDIO_THREAD_EVENT_TYPE event_type)
-{
- struct cras_audio_thread_event_message msg;
- cras_audio_thread_event_message_init(&msg, event_type);
- return cras_main_message_send(&msg.header);
-}
-
-int cras_audio_thread_event_a2dp_overrun()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_A2DP_OVERRUN);
-}
-
-int cras_audio_thread_event_a2dp_throttle()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_A2DP_THROTTLE);
-}
-
-int cras_audio_thread_event_debug()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_DEBUG);
-}
-
-int cras_audio_thread_event_busyloop()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_BUSYLOOP);
-}
-
-int cras_audio_thread_event_underrun()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_UNDERRUN);
-}
-
-int cras_audio_thread_event_severe_underrun()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_SEVERE_UNDERRUN);
-}
-
-int cras_audio_thread_event_drop_samples()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_DROP_SAMPLES);
-}
-
-int cras_audio_thread_event_dev_overrun()
-{
- return cras_audio_thread_event_send(AUDIO_THREAD_EVENT_DEV_OVERRUN);
-}
-
-static struct timespec last_event_snapshot_time[AUDIO_THREAD_EVENT_TYPE_COUNT];
-
-/*
- * Callback function for handling audio thread events in main thread,
- * which takes a snapshot of the audio thread and waits at least 30 seconds
- * for the same event type. Events with the same event type within 30 seconds
- * will be ignored by the handle function.
- */
-static void handle_audio_thread_event_message(struct cras_main_message *msg,
- void *arg)
-{
- struct cras_audio_thread_event_message *audio_thread_msg =
- (struct cras_audio_thread_event_message *)msg;
- struct timespec now_time;
-
- /*
- * Skip invalid event types
- */
- if (audio_thread_msg->event_type >= AUDIO_THREAD_EVENT_TYPE_COUNT)
- return;
-
- struct timespec *last_snapshot_time =
- &last_event_snapshot_time[audio_thread_msg->event_type];
-
- clock_gettime(CLOCK_REALTIME, &now_time);
-
- /*
- * Wait at least 30 seconds for the same event type
- */
- struct timespec diff_time;
- subtract_timespecs(&now_time, last_snapshot_time, &diff_time);
- if ((last_snapshot_time->tv_sec == 0 &&
- last_snapshot_time->tv_nsec == 0) ||
- diff_time.tv_sec >= MIN_WAIT_SECOND) {
- take_snapshot(audio_thread_msg->event_type);
- *last_snapshot_time = now_time;
- }
-}
-
-int cras_audio_thread_monitor_init()
-{
- memset(last_event_snapshot_time, 0,
- sizeof(struct timespec) * AUDIO_THREAD_EVENT_TYPE_COUNT);
- cras_main_message_add_handler(CRAS_MAIN_AUDIO_THREAD_EVENT,
- handle_audio_thread_event_message, NULL);
- return 0;
-}
diff --git a/cras/src/server/cras_audio_thread_monitor.h b/cras/src/server/cras_audio_thread_monitor.h
deleted file mode 100644
index 39b21765..00000000
--- a/cras/src/server/cras_audio_thread_monitor.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_AUDIO_THREAD_MONITOR_H_
-#define CRAS_AUDIO_THREAD_MONITOR_H_
-
-/*
- * Notifies the main thread when A2DP buffer overruns.
- */
-int cras_audio_thread_event_a2dp_overrun();
-
-/*
- * Notifies the main thread when A2DP packet transmittion throttles.
- */
-int cras_audio_thread_event_a2dp_throttle();
-
-/*
- * Sends a debug event to the audio thread for debugging.
- */
-int cras_audio_thread_event_debug();
-
-/*
- * Notifies the main thread when a busyloop event happens.
- */
-int cras_audio_thread_event_busyloop();
-
-/*
- * Notifies the main thread when a underrun event happens.
- */
-int cras_audio_thread_event_underrun();
-
-/*
- * Notifies the main thread when a severe underrun event happens.
- */
-int cras_audio_thread_event_severe_underrun();
-
-/*
- * Notifies the main thread when a drop samples event happens.
- */
-int cras_audio_thread_event_drop_samples();
-
-/*
- * Notifies the main thread when a device overrun event happens.
- */
-int cras_audio_thread_event_dev_overrun();
-
-/*
- * Initializes audio thread monitor and sets main thread callback.
- */
-int cras_audio_thread_monitor_init();
-
-#endif /* CRAS_AUDIO_THREAD_MONITOR_H_ */
diff --git a/cras/src/server/cras_bt_adapter.c b/cras/src/server/cras_bt_adapter.c
deleted file mode 100644
index bcdecefa..00000000
--- a/cras/src/server/cras_bt_adapter.c
+++ /dev/null
@@ -1,383 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-
-#include <errno.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-#include <sys/socket.h>
-#include <sys/ioctl.h>
-
-#include "bluetooth.h"
-#include "cras_bt_adapter.h"
-#include "cras_bt_constants.h"
-#include "utlist.h"
-
-/*
- * Object to represent a bluetooth adapter on the system. Used to query the
- * capabilities regarding certain bluetooth audio.
- * Members:
- * conn - The dbus connection used to send message to bluetoothd.
- * object_path - Object path of the bluetooth adapter.
- * address - The BT address of this adapter.
- * name - The readable name of this adapter.
- * bluetooth_class - The bluetooth class of device.
- * powered - Powered on or off.
- * bus_type - Type of bus this adapter runs on.
- * wide_band_speech - If this adapter supports wide band speech.
- */
-struct cras_bt_adapter {
- DBusConnection *conn;
- char *object_path;
- char *address;
- char *name;
- uint32_t bluetooth_class;
- int powered;
- int bus_type;
- int wide_band_speech;
-
- struct cras_bt_adapter *prev, *next;
-};
-
-static struct cras_bt_adapter *adapters;
-
-static int cras_bt_adapter_query_bus_type(struct cras_bt_adapter *adapter)
-{
- static const char *hci_str = "hci";
- struct hci_dev_info dev_info;
- char *pos;
- int ctl, err;
-
- /* Object path [variable prefix]/{hci0,hci1,...} */
- pos = strstr(adapter->object_path, hci_str);
- if (!pos)
- return -1;
-
- ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
- if (ctl < 0) {
- syslog(LOG_ERR, "Error creating HCI ctl socket");
- return -1;
- }
-
- /* dev_id = 0 for hci0 */
- dev_info.type = 0;
- dev_info.dev_id = atoi(pos + 3);
- err = ioctl(ctl, HCIGETDEVINFO, (void *)&dev_info);
- if (err) {
- syslog(LOG_ERR, "HCI get dev info error %s", strerror(errno));
- close(ctl);
- return -1;
- }
- if ((dev_info.type & 0x0f) < HCI_BUS_MAX)
- adapter->bus_type = (dev_info.type & 0x0f);
-
- close(ctl);
- return 0;
-}
-
-struct cras_bt_adapter *cras_bt_adapter_create(DBusConnection *conn,
- const char *object_path)
-{
- struct cras_bt_adapter *adapter;
-
- adapter = calloc(1, sizeof(*adapter));
- if (adapter == NULL)
- return NULL;
-
- adapter->conn = conn;
- adapter->object_path = strdup(object_path);
- if (adapter->object_path == NULL) {
- free(adapter);
- return NULL;
- }
-
- DL_APPEND(adapters, adapter);
-
- /* Set bus type to USB as default when query fails. */
- if (cras_bt_adapter_query_bus_type(adapter))
- adapter->bus_type = HCI_USB;
-
- return adapter;
-}
-
-void cras_bt_adapter_destroy(struct cras_bt_adapter *adapter)
-{
- DL_DELETE(adapters, adapter);
-
- free(adapter->object_path);
- free(adapter->address);
- free(adapter->name);
- free(adapter);
-}
-
-void cras_bt_adapter_reset()
-{
- while (adapters) {
- syslog(LOG_INFO, "Bluetooth Adapter: %s removed",
- adapters->address);
- cras_bt_adapter_destroy(adapters);
- }
-}
-
-struct cras_bt_adapter *cras_bt_adapter_get(const char *object_path)
-{
- struct cras_bt_adapter *adapter;
-
- if (object_path == NULL)
- return NULL;
-
- DL_FOREACH (adapters, adapter) {
- if (strcmp(adapter->object_path, object_path) == 0)
- return adapter;
- }
-
- return NULL;
-}
-
-size_t cras_bt_adapter_get_list(struct cras_bt_adapter ***adapter_list_out)
-{
- struct cras_bt_adapter *adapter;
- struct cras_bt_adapter **adapter_list = NULL;
- size_t num_adapters = 0;
-
- DL_FOREACH (adapters, adapter) {
- struct cras_bt_adapter **tmp;
-
- tmp = realloc(adapter_list,
- sizeof(adapter_list[0]) * (num_adapters + 1));
- if (!tmp) {
- free(adapter_list);
- return -ENOMEM;
- }
-
- adapter_list = tmp;
- adapter_list[num_adapters++] = adapter;
- }
-
- *adapter_list_out = adapter_list;
- return num_adapters;
-}
-
-const char *cras_bt_adapter_object_path(const struct cras_bt_adapter *adapter)
-{
- return adapter->object_path;
-}
-
-const char *cras_bt_adapter_address(const struct cras_bt_adapter *adapter)
-{
- return adapter->address;
-}
-
-const char *cras_bt_adapter_name(const struct cras_bt_adapter *adapter)
-{
- return adapter->name;
-}
-
-int cras_bt_adapter_powered(const struct cras_bt_adapter *adapter)
-{
- return adapter->powered;
-}
-
-int cras_bt_adapter_wbs_supported(struct cras_bt_adapter *adapter)
-{
- return adapter->wide_band_speech;
-}
-
-static void bt_adapter_set_powered(struct cras_bt_adapter *adapter, int powered)
-{
- adapter->powered = powered;
- if (powered)
- cras_bt_adapter_get_supported_capabilities(adapter);
-}
-
-void cras_bt_adapter_update_properties(struct cras_bt_adapter *adapter,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter)
-{
- while (dbus_message_iter_get_arg_type(properties_array_iter) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter properties_dict_iter, variant_iter;
- const char *key;
- int type;
-
- dbus_message_iter_recurse(properties_array_iter,
- &properties_dict_iter);
-
- dbus_message_iter_get_basic(&properties_dict_iter, &key);
- dbus_message_iter_next(&properties_dict_iter);
-
- dbus_message_iter_recurse(&properties_dict_iter, &variant_iter);
- type = dbus_message_iter_get_arg_type(&variant_iter);
-
- if (type == DBUS_TYPE_STRING) {
- const char *value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Address") == 0) {
- free(adapter->address);
- adapter->address = strdup(value);
-
- } else if (strcmp(key, "Alias") == 0) {
- free(adapter->name);
- adapter->name = strdup(value);
- }
-
- } else if (type == DBUS_TYPE_UINT32) {
- uint32_t value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Class") == 0)
- adapter->bluetooth_class = value;
-
- } else if (type == DBUS_TYPE_BOOLEAN) {
- int value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Powered") == 0)
- bt_adapter_set_powered(adapter, value);
- }
-
- dbus_message_iter_next(properties_array_iter);
- }
-
- while (invalidated_array_iter &&
- dbus_message_iter_get_arg_type(invalidated_array_iter) !=
- DBUS_TYPE_INVALID) {
- const char *key;
-
- dbus_message_iter_get_basic(invalidated_array_iter, &key);
-
- if (strcmp(key, "Address") == 0) {
- free(adapter->address);
- adapter->address = NULL;
- } else if (strcmp(key, "Alias") == 0) {
- free(adapter->name);
- adapter->name = NULL;
- } else if (strcmp(key, "Class") == 0) {
- adapter->bluetooth_class = 0;
- } else if (strcmp(key, "Powered") == 0) {
- adapter->powered = 0;
- }
-
- dbus_message_iter_next(invalidated_array_iter);
- }
-}
-
-int cras_bt_adapter_on_usb(struct cras_bt_adapter *adapter)
-{
- return !!(adapter->bus_type == HCI_USB);
-}
-
-/*
- * Expect to receive supported capabilities in reply, like below format:
- * array [
- * dict entry(
- * string "wide band speech"
- * variant
- * boolean <value>
- * )
- * ]
- */
-static void on_get_supported_capabilities_reply(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
- DBusMessageIter message_iter, capabilities;
- struct cras_bt_adapter *adapter;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR,
- "GetSupportedCapabilities message replied error: %s",
- dbus_message_get_error_name(reply));
- goto get_supported_capabilities_err;
- }
-
- if (!dbus_message_iter_init(reply, &message_iter)) {
- syslog(LOG_ERR, "GetSupportedCapabilities reply doesn't have"
- "argument");
- goto get_supported_capabilities_err;
- }
-
- DL_FOREACH (adapters, adapter) {
- if (adapter == (struct cras_bt_adapter *)data)
- break;
- }
- if (NULL == adapter)
- goto get_supported_capabilities_err;
-
- dbus_message_iter_recurse(&message_iter, &capabilities);
-
- while (dbus_message_iter_get_arg_type(&capabilities) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter cap_dict_iter, variant_iter;
- const char *key;
- int type;
-
- dbus_message_iter_recurse(&capabilities, &cap_dict_iter);
-
- dbus_message_iter_get_basic(&cap_dict_iter, &key);
- dbus_message_iter_next(&cap_dict_iter);
-
- dbus_message_iter_recurse(&cap_dict_iter, &variant_iter);
- type = dbus_message_iter_get_arg_type(&variant_iter);
-
- if (type == DBUS_TYPE_BOOLEAN) {
- int value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "wide band speech") == 0)
- adapter->wide_band_speech = value;
- }
-
- dbus_message_iter_next(&capabilities);
- }
-
-get_supported_capabilities_err:
- dbus_message_unref(reply);
-}
-
-int cras_bt_adapter_get_supported_capabilities(struct cras_bt_adapter *adapter)
-{
- DBusMessage *method_call;
- DBusError dbus_error;
- DBusPendingCall *pending_call;
-
- method_call = dbus_message_new_method_call(BLUEZ_SERVICE,
- adapter->object_path,
- BLUEZ_INTERFACE_ADAPTER,
- "GetSupportedCapabilities");
- if (!method_call)
- return -ENOMEM;
-
- dbus_error_init(&dbus_error);
- if (!dbus_connection_send_with_reply(adapter->conn, method_call,
- &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- syslog(LOG_ERR,
- "Failed to send GetSupportedCapabilities message");
- return -EIO;
- }
-
- dbus_message_unref(method_call);
- if (!dbus_pending_call_set_notify(pending_call,
- on_get_supported_capabilities_reply,
- adapter, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -EIO;
- }
- return 0;
-}
diff --git a/cras/src/server/cras_bt_adapter.h b/cras/src/server/cras_bt_adapter.h
deleted file mode 100644
index dc07b685..00000000
--- a/cras/src/server/cras_bt_adapter.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_ADAPTER_H_
-#define CRAS_BT_ADAPTER_H_
-
-#include <dbus/dbus.h>
-
-struct cras_bt_adapter;
-
-/* Creates an bt_adapter instance representing the bluetooth controller
- * on the system.
- * Args:
- * conn - The dbus connection.
- * object_path - Object path of the bluetooth controller.
- */
-struct cras_bt_adapter *cras_bt_adapter_create(DBusConnection *conn,
- const char *object_path);
-void cras_bt_adapter_destroy(struct cras_bt_adapter *adapter);
-void cras_bt_adapter_reset();
-
-struct cras_bt_adapter *cras_bt_adapter_get(const char *object_path);
-size_t cras_bt_adapter_get_list(struct cras_bt_adapter ***adapter_list_out);
-
-const char *cras_bt_adapter_object_path(const struct cras_bt_adapter *adapter);
-const char *cras_bt_adapter_address(const struct cras_bt_adapter *adapter);
-const char *cras_bt_adapter_name(const struct cras_bt_adapter *adapter);
-
-int cras_bt_adapter_powered(const struct cras_bt_adapter *adapter);
-
-/*
- * Returns true if adapter supports wide band speech feature.
- */
-int cras_bt_adapter_wbs_supported(struct cras_bt_adapter *adapter);
-
-void cras_bt_adapter_update_properties(struct cras_bt_adapter *adapter,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter);
-
-int cras_bt_adapter_on_usb(struct cras_bt_adapter *adapter);
-
-/*
- * Queries adapter supported capabilies from bluetooth daemon. This shall
- * be called only after adapter powers on.
- */
-int cras_bt_adapter_get_supported_capabilities(struct cras_bt_adapter *adapter);
-
-#endif /* CRAS_BT_ADAPTER_H_ */
diff --git a/cras/src/server/cras_bt_battery_provider.c b/cras/src/server/cras_bt_battery_provider.c
deleted file mode 100644
index 13e6590f..00000000
--- a/cras/src/server/cras_bt_battery_provider.c
+++ /dev/null
@@ -1,371 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_bt_adapter.h"
-#include "cras_bt_battery_provider.h"
-#include "cras_bt_constants.h"
-#include "cras_dbus_util.h"
-#include "cras_observer.h"
-#include "utlist.h"
-
-/* CRAS registers one battery provider to BlueZ, so we use a singleton. */
-static struct cras_bt_battery_provider battery_provider = {
- .object_path = CRAS_DEFAULT_BATTERY_PROVIDER,
- .interface = BLUEZ_INTERFACE_BATTERY_PROVIDER,
- .conn = NULL,
- .is_registered = false,
- .observer = NULL,
- .batteries = NULL,
-};
-
-static int cmp_battery_address(const struct cras_bt_battery *battery,
- const char *address)
-{
- return strcmp(battery->address, address);
-}
-
-static void replace_colon_with_underscore(char *str)
-{
- for (int i = 0; str[i]; i++) {
- if (str[i] == ':')
- str[i] = '_';
- }
-}
-
-/* Converts address XX:XX:XX:XX:XX:XX to Battery Provider object path:
- * /org/chromium/Cras/Bluetooth/BatteryProvider/XX_XX_XX_XX_XX_XX
- */
-static char *address_to_battery_path(const char *address)
-{
- char *object_path = malloc(strlen(CRAS_DEFAULT_BATTERY_PROVIDER) +
- strlen(address) + 2);
-
- sprintf(object_path, "%s/%s", CRAS_DEFAULT_BATTERY_PROVIDER, address);
- replace_colon_with_underscore(object_path);
-
- return object_path;
-}
-
-/* Converts address XX:XX:XX:XX:XX:XX to device object path:
- * /org/bluez/hci0/dev_XX_XX_XX_XX_XX_XX
- */
-static char *address_to_device_path(const char *address)
-{
- char *object_path = malloc(strlen(CRAS_DEFAULT_BATTERY_PREFIX) +
- strlen(address) + 1);
-
- sprintf(object_path, "%s%s", CRAS_DEFAULT_BATTERY_PREFIX, address);
- replace_colon_with_underscore(object_path);
-
- return object_path;
-}
-
-static struct cras_bt_battery *battery_new(const char *address, uint32_t level)
-{
- struct cras_bt_battery *battery;
-
- battery = calloc(1, sizeof(struct cras_bt_battery));
- battery->address = strdup(address);
- battery->object_path = address_to_battery_path(address);
- battery->device_path = address_to_device_path(address);
- battery->level = level;
-
- return battery;
-}
-
-static void battery_free(struct cras_bt_battery *battery)
-{
- if (battery->address)
- free(battery->address);
- if (battery->object_path)
- free(battery->object_path);
- if (battery->device_path)
- free(battery->device_path);
- free(battery);
-}
-
-static void populate_battery_properties(DBusMessageIter *iter,
- const struct cras_bt_battery *battery)
-{
- DBusMessageIter dict, entry, variant;
- const char *property_percentage = "Percentage";
- const char *property_device = "Device";
- uint8_t level = battery->level;
-
- dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "{sv}", &dict);
-
- dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY, NULL,
- &entry);
- dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
- &property_percentage);
- dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
- DBUS_TYPE_BYTE_AS_STRING, &variant);
- dbus_message_iter_append_basic(&variant, DBUS_TYPE_BYTE, &level);
- dbus_message_iter_close_container(&entry, &variant);
- dbus_message_iter_close_container(&dict, &entry);
-
- dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY, NULL,
- &entry);
- dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
- &property_device);
- dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
- DBUS_TYPE_OBJECT_PATH_AS_STRING,
- &variant);
- dbus_message_iter_append_basic(&variant, DBUS_TYPE_OBJECT_PATH,
- &battery->device_path);
- dbus_message_iter_close_container(&entry, &variant);
- dbus_message_iter_close_container(&dict, &entry);
-
- dbus_message_iter_close_container(iter, &dict);
-}
-
-/* Creates a new battery object and exposes it on D-Bus. */
-static struct cras_bt_battery *
-get_or_create_battery(struct cras_bt_battery_provider *provider,
- const char *address, uint32_t level)
-{
- struct cras_bt_battery *battery;
- DBusMessage *msg;
- DBusMessageIter iter, dict, entry;
-
- LL_SEARCH(provider->batteries, battery, address, cmp_battery_address);
-
- if (battery)
- return battery;
-
- syslog(LOG_DEBUG, "Creating new battery for %s", address);
-
- battery = battery_new(address, level);
- LL_APPEND(provider->batteries, battery);
-
- msg = dbus_message_new_signal(CRAS_DEFAULT_BATTERY_PROVIDER,
- DBUS_INTERFACE_OBJECT_MANAGER,
- DBUS_SIGNAL_INTERFACES_ADDED);
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH,
- &battery->object_path);
- dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sa{sv}}",
- &dict);
- dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY, NULL,
- &entry);
- dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
- &provider->interface);
- populate_battery_properties(&entry, battery);
- dbus_message_iter_close_container(&dict, &entry);
- dbus_message_iter_close_container(&iter, &dict);
-
- if (!dbus_connection_send(provider->conn, msg, NULL)) {
- syslog(LOG_ERR,
- "Error sending " DBUS_SIGNAL_INTERFACES_ADDED " signal");
- }
-
- dbus_message_unref(msg);
-
- return battery;
-}
-
-/* Updates the level of a battery object and signals it on D-Bus. */
-static void
-update_battery_level(const struct cras_bt_battery_provider *provider,
- struct cras_bt_battery *battery, uint32_t level)
-{
- DBusMessage *msg;
- DBusMessageIter iter;
-
- if (battery->level == level)
- return;
-
- battery->level = level;
-
- msg = dbus_message_new_signal(battery->object_path,
- DBUS_INTERFACE_PROPERTIES,
- DBUS_SIGNAL_PROPERTIES_CHANGED);
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
- &provider->interface);
- populate_battery_properties(&iter, battery);
-
- if (!dbus_connection_send(provider->conn, msg, NULL)) {
- syslog(LOG_ERR, "Error sending " DBUS_SIGNAL_PROPERTIES_CHANGED
- " signal");
- }
-
- dbus_message_unref(msg);
-}
-
-/* Invoked when HFP sends an alert about a battery value change. */
-static void on_bt_battery_changed(void *context, const char *address,
- uint32_t level)
-{
- struct cras_bt_battery_provider *provider = context;
-
- syslog(LOG_DEBUG, "Battery changed for address %s, level %d", address,
- level);
-
- if (!provider->is_registered) {
- syslog(LOG_WARNING, "Received battery level update while "
- "battery provider is not registered");
- return;
- }
-
- struct cras_bt_battery *battery =
- get_or_create_battery(provider, address, level);
-
- update_battery_level(provider, battery, level);
-}
-
-/* Invoked when we receive a D-Bus return of RegisterBatteryProvider from
- * BlueZ.
- */
-static void
-cras_bt_on_battery_provider_registered(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
- struct cras_bt_battery_provider *provider = data;
- struct cras_observer_ops observer_ops;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR, "RegisterBatteryProvider returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return;
- }
-
- syslog(LOG_INFO, "RegisterBatteryProvider succeeded");
-
- provider->is_registered = true;
-
- memset(&observer_ops, 0, sizeof(observer_ops));
- observer_ops.bt_battery_changed = on_bt_battery_changed;
- provider->observer = cras_observer_add(&observer_ops, provider);
-
- dbus_message_unref(reply);
-}
-
-int cras_bt_register_battery_provider(DBusConnection *conn,
- const struct cras_bt_adapter *adapter)
-{
- const char *adapter_path;
- DBusMessage *method_call;
- DBusMessageIter message_iter;
- DBusPendingCall *pending_call;
-
- if (battery_provider.is_registered) {
- syslog(LOG_ERR, "Battery Provider already registered");
- return -EBUSY;
- }
-
- if (battery_provider.conn)
- dbus_connection_unref(battery_provider.conn);
-
- battery_provider.conn = conn;
- dbus_connection_ref(battery_provider.conn);
-
- adapter_path = cras_bt_adapter_object_path(adapter);
- method_call = dbus_message_new_method_call(
- BLUEZ_SERVICE, adapter_path,
- BLUEZ_INTERFACE_BATTERY_PROVIDER_MANAGER,
- "RegisterBatteryProvider");
- if (!method_call)
- return -ENOMEM;
-
- dbus_message_iter_init_append(method_call, &message_iter);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_OBJECT_PATH,
- &battery_provider.object_path);
-
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
-
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(
- pending_call, cras_bt_on_battery_provider_registered,
- &battery_provider, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
-
- return 0;
-}
-
-/* Removes a battery object and signals the removal on D-Bus as well. */
-static void cleanup_battery(struct cras_bt_battery_provider *provider,
- struct cras_bt_battery *battery)
-{
- DBusMessage *msg;
- DBusMessageIter iter, entry;
-
- if (!battery)
- return;
-
- LL_DELETE(provider->batteries, battery);
-
- msg = dbus_message_new_signal(CRAS_DEFAULT_BATTERY_PROVIDER,
- DBUS_INTERFACE_OBJECT_MANAGER,
- DBUS_SIGNAL_INTERFACES_REMOVED);
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH,
- &battery->object_path);
- dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
- DBUS_TYPE_STRING_AS_STRING, &entry);
- dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
- &provider->interface);
- dbus_message_iter_close_container(&iter, &entry);
-
- if (!dbus_connection_send(provider->conn, msg, NULL)) {
- syslog(LOG_ERR, "Error sending " DBUS_SIGNAL_INTERFACES_REMOVED
- " signal");
- }
-
- dbus_message_unref(msg);
-
- battery_free(battery);
-}
-
-void cras_bt_battery_provider_reset()
-{
- struct cras_bt_battery *battery;
-
- syslog(LOG_INFO, "Resetting battery provider");
-
- if (!battery_provider.is_registered)
- return;
-
- battery_provider.is_registered = false;
-
- LL_FOREACH (battery_provider.batteries, battery) {
- cleanup_battery(&battery_provider, battery);
- }
-
- if (battery_provider.conn) {
- dbus_connection_unref(battery_provider.conn);
- battery_provider.conn = NULL;
- }
-
- if (battery_provider.observer) {
- cras_observer_remove(battery_provider.observer);
- battery_provider.observer = NULL;
- }
-}
diff --git a/cras/src/server/cras_bt_battery_provider.h b/cras/src/server/cras_bt_battery_provider.h
deleted file mode 100644
index 1998cd78..00000000
--- a/cras/src/server/cras_bt_battery_provider.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_BATTERY_PROVIDER_H_
-#define CRAS_BT_BATTERY_PROVIDER_H_
-
-#include <dbus/dbus.h>
-#include <stdbool.h>
-
-#include "cras_bt_adapter.h"
-
-/* Object to represent a battery that is exposed to BlueZ. */
-struct cras_bt_battery {
- char *address;
- char *object_path;
- char *device_path;
- uint32_t level;
- struct cras_bt_battery *next;
-};
-
-/* Object to register as battery provider so that bluetoothd will monitor
- * battery objects that we expose.
- */
-struct cras_bt_battery_provider {
- const char *object_path;
- const char *interface;
- DBusConnection *conn;
- bool is_registered;
- struct cras_observer_client *observer;
- struct cras_bt_battery *batteries;
-};
-
-/* Registers battery provider to bluetoothd. This is used when a Bluetooth
- * adapter got enumerated.
- * Args:
- * conn - The D-Bus connection.
- * adapter - The enumerated bluetooth adapter.
- */
-int cras_bt_register_battery_provider(DBusConnection *conn,
- const struct cras_bt_adapter *adapter);
-
-/* Resets internal state of battery provider. */
-void cras_bt_battery_provider_reset();
-
-#endif /* CRAS_BT_BATTERY_PROVIDER_H_ */
diff --git a/cras/src/server/cras_bt_constants.h b/cras/src/server/cras_bt_constants.h
deleted file mode 100644
index 318aecab..00000000
--- a/cras/src/server/cras_bt_constants.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_CONSTANTS_H_
-#define CRAS_BT_CONSTANTS_H_
-
-#define BLUEZ_SERVICE "org.bluez"
-
-#define BLUEZ_INTERFACE_ADAPTER "org.bluez.Adapter1"
-#define BLUEZ_INTERFACE_BATTERY_PROVIDER "org.bluez.BatteryProvider1"
-#define BLUEZ_INTERFACE_BATTERY_PROVIDER_MANAGER \
- "org.bluez.BatteryProviderManager1"
-#define BLUEZ_INTERFACE_DEVICE "org.bluez.Device1"
-#define BLUEZ_INTERFACE_MEDIA "org.bluez.Media1"
-#define BLUEZ_INTERFACE_MEDIA_ENDPOINT "org.bluez.MediaEndpoint1"
-#define BLUEZ_INTERFACE_MEDIA_PLAYER "org.mpris.MediaPlayer2.Player"
-#define BLUEZ_INTERFACE_MEDIA_TRANSPORT "org.bluez.MediaTransport1"
-#define BLUEZ_INTERFACE_PLAYER "org.bluez.MediaPlayer1"
-#define BLUEZ_INTERFACE_PROFILE "org.bluez.Profile1"
-#define BLUEZ_PROFILE_MGMT_INTERFACE "org.bluez.ProfileManager1"
-/* Remove once our D-Bus header files are updated to define this. */
-#ifndef DBUS_INTERFACE_OBJECT_MANAGER
-#define DBUS_INTERFACE_OBJECT_MANAGER "org.freedesktop.DBus.ObjectManager"
-#endif
-#define DBUS_SIGNAL_INTERFACES_ADDED "InterfacesAdded"
-#define DBUS_SIGNAL_INTERFACES_REMOVED "InterfacesRemoved"
-#define DBUS_SIGNAL_PROPERTIES_CHANGED "PropertiesChanged"
-
-/* UUIDs taken from lib/uuid.h in the BlueZ source */
-#define HSP_HS_UUID "00001108-0000-1000-8000-00805f9b34fb"
-#define HSP_AG_UUID "00001112-0000-1000-8000-00805f9b34fb"
-
-#define HFP_HF_UUID "0000111e-0000-1000-8000-00805f9b34fb"
-#define HFP_AG_UUID "0000111f-0000-1000-8000-00805f9b34fb"
-
-#define A2DP_SOURCE_UUID "0000110a-0000-1000-8000-00805f9b34fb"
-#define A2DP_SINK_UUID "0000110b-0000-1000-8000-00805f9b34fb"
-
-#define AVRCP_REMOTE_UUID "0000110e-0000-1000-8000-00805f9b34fb"
-#define AVRCP_TARGET_UUID "0000110c-0000-1000-8000-00805f9b34fb"
-
-#define GENERIC_AUDIO_UUID "00001203-0000-1000-8000-00805f9b34fb"
-
-/* Constants for CRAS BT player */
-#define CRAS_DEFAULT_PLAYER "/org/chromium/Cras/Bluetooth/DefaultPlayer"
-/* The longest possible player playback status is "forward-seek" */
-#define CRAS_PLAYER_PLAYBACK_STATUS_SIZE_MAX 13 * sizeof(char)
-#define CRAS_PLAYER_PLAYBACK_STATUS_DEFAULT "playing"
-/* Neither BlueZ or the MRPIS specs limited the player identity max size, 128
- * should be large enough for most.
- */
-#define CRAS_PLAYER_IDENTITY_SIZE_MAX 128 * sizeof(char)
-#define CRAS_PLAYER_IDENTITY_DEFAULT "DefaultPlayer"
-#define CRAS_PLAYER_METADATA_SIZE_MAX 128 * sizeof(char)
-
-#define CRAS_DEFAULT_BATTERY_PROVIDER \
- "/org/chromium/Cras/Bluetooth/BatteryProvider"
-#define CRAS_DEFAULT_BATTERY_PREFIX "/org/bluez/hci0/dev_"
-
-/* Instead of letting CRAS obtain the A2DP streaming packet size (a.k.a. AVDTP
- * MTU) from BlueZ Media Transport, force the packet size to the default L2CAP
- * packet size. This prevent the audio peripheral device to negotiate a larger
- * packet size and later failed to fulfill it and causing audio artifact. This
- * defined constant is for experiment only and is put back behind a
- * chrome://flag.
- */
-#define A2DP_FIX_PACKET_SIZE 672
-
-#endif /* CRAS_BT_CONSTANTS_H_ */
diff --git a/cras/src/server/cras_bt_device.c b/cras/src/server/cras_bt_device.c
deleted file mode 100644
index 6b06dd13..00000000
--- a/cras/src/server/cras_bt_device.c
+++ /dev/null
@@ -1,1409 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE /* for ppoll */
-#endif
-
-#include <dbus/dbus.h>
-
-#include <errno.h>
-#include <poll.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <syslog.h>
-
-#include "bluetooth.h"
-#include "cras_a2dp_endpoint.h"
-#include "cras_bt_adapter.h"
-#include "cras_bt_device.h"
-#include "cras_bt_constants.h"
-#include "cras_bt_log.h"
-#include "cras_bt_io.h"
-#include "cras_bt_profile.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_main_message.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_tm.h"
-#include "sfh.h"
-#include "utlist.h"
-
-/*
- * Bluetooth Core 5.0 spec, vol 4, part B, section 2 describes
- * the recommended HCI packet size in one USB transfer for CVSD
- * and MSBC codec.
- */
-#define USB_MSBC_PKT_SIZE 60
-#define USB_CVSD_PKT_SIZE 48
-#define DEFAULT_SCO_PKT_SIZE USB_CVSD_PKT_SIZE
-
-static const unsigned int PROFILE_SWITCH_DELAY_MS = 500;
-static const unsigned int PROFILE_DROP_SUSPEND_DELAY_MS = 5000;
-
-/* Check profile connections every 2 seconds and rerty 30 times maximum.
- * Attemp to connect profiles which haven't been ready every 3 retries.
- */
-static const unsigned int CONN_WATCH_PERIOD_MS = 2000;
-static const unsigned int CONN_WATCH_MAX_RETRIES = 30;
-
-/* This is used when a critical SCO failure happens and is worth scheduling a
- * suspend in case for some reason BT headset stays connected in baseband and
- * confuses user.
- */
-static const unsigned int SCO_SUSPEND_DELAY_MS = 5000;
-
-static const unsigned int CRAS_SUPPORTED_PROFILES =
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK | CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
-
-/* Object to represent a general bluetooth device, and used to
- * associate with some CRAS modules if it supports audio.
- * Members:
- * conn - The dbus connection object used to send message to bluetoothd.
- * object_path - Object path of the bluetooth device.
- * adapter - The object path of the adapter associates with this device.
- * address - The BT address of this device.
- * name - The readable name of this device.
- * bluetooth_class - The bluetooth class of this device.
- * paired - If this device is paired.
- * trusted - If this device is trusted.
- * connected - If this devices is connected.
- * connected_profiles - OR'ed all connected audio profiles.
- * profiles - OR'ed by all audio profiles this device supports.
- * hidden_profiles - OR'ed by all audio profiles this device actually
- * supports but is not scanned by BlueZ.
- * bt_iodevs - The pointer to the cras_iodevs of this device.
- * active_profile - The flag to indicate the active audio profile this
- * device is currently using.
- * conn_watch_retries - The retry count for conn_watch_timer.
- * conn_watch_timer - The timer used to watch connected profiles and start
- * BT audio input/ouput when all profiles are ready.
- * suspend_timer - The timer used to suspend device.
- * switch_profile_timer - The timer used to delay enabling iodev after
- * profile switch.
- * sco_fd - The file descriptor of the SCO connection.
- * sco_ref_count - The reference counts of the SCO connection.
- * suspend_reason - The reason code for why suspend is scheduled.
- * stable_id - The unique and persistent id of this bt_device.
- */
-struct cras_bt_device {
- DBusConnection *conn;
- char *object_path;
- char *adapter_obj_path;
- char *address;
- char *name;
- uint32_t bluetooth_class;
- int paired;
- int trusted;
- int connected;
- unsigned int connected_profiles;
- unsigned int profiles;
- unsigned int hidden_profiles;
- struct cras_iodev *bt_iodevs[CRAS_NUM_DIRECTIONS];
- unsigned int active_profile;
- int use_hardware_volume;
- int conn_watch_retries;
- struct cras_timer *conn_watch_timer;
- struct cras_timer *suspend_timer;
- struct cras_timer *switch_profile_timer;
- int sco_fd;
- size_t sco_ref_count;
- enum cras_bt_device_suspend_reason suspend_reason;
- unsigned int stable_id;
-
- struct cras_bt_device *prev, *next;
-};
-
-enum BT_DEVICE_COMMAND {
- BT_DEVICE_CANCEL_SUSPEND,
- BT_DEVICE_SCHEDULE_SUSPEND,
- BT_DEVICE_SWITCH_PROFILE,
- BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV,
-};
-
-struct bt_device_msg {
- struct cras_main_message header;
- enum BT_DEVICE_COMMAND cmd;
- struct cras_bt_device *device;
- struct cras_iodev *dev;
- unsigned int arg1;
- unsigned int arg2;
-};
-
-static struct cras_bt_device *devices;
-
-enum cras_bt_device_profile cras_bt_device_profile_from_uuid(const char *uuid)
-{
- if (strcmp(uuid, HSP_HS_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_HSP_HEADSET;
- else if (strcmp(uuid, HSP_AG_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
- else if (strcmp(uuid, HFP_HF_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
- else if (strcmp(uuid, HFP_AG_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
- else if (strcmp(uuid, A2DP_SOURCE_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
- else if (strcmp(uuid, A2DP_SINK_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_A2DP_SINK;
- else if (strcmp(uuid, AVRCP_REMOTE_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE;
- else if (strcmp(uuid, AVRCP_TARGET_UUID) == 0)
- return CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET;
- else
- return 0;
-}
-
-struct cras_bt_device *cras_bt_device_create(DBusConnection *conn,
- const char *object_path)
-{
- struct cras_bt_device *device;
-
- device = calloc(1, sizeof(*device));
- if (device == NULL)
- return NULL;
-
- device->conn = conn;
- device->object_path = strdup(object_path);
- if (device->object_path == NULL) {
- free(device);
- return NULL;
- }
- device->stable_id =
- SuperFastHash(device->object_path, strlen(device->object_path),
- strlen(device->object_path));
-
- DL_APPEND(devices, device);
-
- return device;
-}
-
-static void on_connect_profile_reply(DBusPendingCall *pending_call, void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
- syslog(LOG_ERR, "Connect profile message replied error: %s",
- dbus_message_get_error_name(reply));
-
- dbus_message_unref(reply);
-}
-
-static void on_disconnect_reply(DBusPendingCall *pending_call, void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
- syslog(LOG_ERR, "Disconnect message replied error");
-
- dbus_message_unref(reply);
-}
-
-int cras_bt_device_connect_profile(DBusConnection *conn,
- struct cras_bt_device *device,
- const char *uuid)
-{
- DBusMessage *method_call;
- DBusError dbus_error;
- DBusPendingCall *pending_call;
-
- method_call =
- dbus_message_new_method_call(BLUEZ_SERVICE, device->object_path,
- BLUEZ_INTERFACE_DEVICE,
- "ConnectProfile");
- if (!method_call)
- return -ENOMEM;
-
- if (!dbus_message_append_args(method_call, DBUS_TYPE_STRING, &uuid,
- DBUS_TYPE_INVALID))
- return -ENOMEM;
-
- dbus_error_init(&dbus_error);
-
- pending_call = NULL;
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- syslog(LOG_ERR, "Failed to send Disconnect message");
- return -EIO;
- }
-
- dbus_message_unref(method_call);
- if (!dbus_pending_call_set_notify(
- pending_call, on_connect_profile_reply, conn, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -EIO;
- }
- return 0;
-}
-
-int cras_bt_device_disconnect(DBusConnection *conn,
- struct cras_bt_device *device)
-{
- DBusMessage *method_call;
- DBusError dbus_error;
- DBusPendingCall *pending_call;
-
- method_call =
- dbus_message_new_method_call(BLUEZ_SERVICE, device->object_path,
- BLUEZ_INTERFACE_DEVICE,
- "Disconnect");
- if (!method_call)
- return -ENOMEM;
-
- dbus_error_init(&dbus_error);
-
- pending_call = NULL;
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- syslog(LOG_ERR, "Failed to send Disconnect message");
- return -EIO;
- }
-
- dbus_message_unref(method_call);
- if (!dbus_pending_call_set_notify(pending_call, on_disconnect_reply,
- conn, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -EIO;
- }
- return 0;
-}
-
-static void cras_bt_device_destroy(struct cras_bt_device *device)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
- DL_DELETE(devices, device);
-
- if (device->conn_watch_timer)
- cras_tm_cancel_timer(tm, device->conn_watch_timer);
- if (device->switch_profile_timer)
- cras_tm_cancel_timer(tm, device->switch_profile_timer);
- if (device->suspend_timer)
- cras_tm_cancel_timer(tm, device->suspend_timer);
- free(device->adapter_obj_path);
- free(device->object_path);
- free(device->address);
- free(device->name);
- free(device);
-}
-
-void cras_bt_device_remove(struct cras_bt_device *device)
-{
- /*
- * We expect BT stack to disconnect this device before removing it,
- * but it may not the case if there's issue at BT side. Print error
- * log whenever this happens.
- */
- if (device->connected)
- syslog(LOG_ERR, "Removing dev with connected profiles %u",
- device->connected_profiles);
- /*
- * Possibly clean up the associated A2DP and HFP AG iodevs that are
- * still accessing this device.
- */
- cras_a2dp_suspend_connected_device(device);
- cras_hfp_ag_suspend_connected_device(device);
- cras_bt_device_destroy(device);
-}
-
-void cras_bt_device_reset()
-{
- while (devices) {
- syslog(LOG_INFO, "Bluetooth Device: %s removed",
- devices->address);
- cras_bt_device_destroy(devices);
- }
-}
-
-struct cras_bt_device *cras_bt_device_get(const char *object_path)
-{
- struct cras_bt_device *device;
-
- DL_FOREACH (devices, device) {
- if (strcmp(device->object_path, object_path) == 0)
- return device;
- }
-
- return NULL;
-}
-
-const char *cras_bt_device_object_path(const struct cras_bt_device *device)
-{
- return device->object_path;
-}
-
-int cras_bt_device_get_stable_id(const struct cras_bt_device *device)
-{
- return device->stable_id;
-}
-
-struct cras_bt_adapter *
-cras_bt_device_adapter(const struct cras_bt_device *device)
-{
- return cras_bt_adapter_get(device->adapter_obj_path);
-}
-
-const char *cras_bt_device_address(const struct cras_bt_device *device)
-{
- return device->address;
-}
-
-const char *cras_bt_device_name(const struct cras_bt_device *device)
-{
- return device->name;
-}
-
-int cras_bt_device_paired(const struct cras_bt_device *device)
-{
- return device->paired;
-}
-
-int cras_bt_device_trusted(const struct cras_bt_device *device)
-{
- return device->trusted;
-}
-
-int cras_bt_device_connected(const struct cras_bt_device *device)
-{
- return device->connected;
-}
-
-int cras_bt_device_supports_profile(const struct cras_bt_device *device,
- enum cras_bt_device_profile profile)
-{
- return !!(device->profiles & profile);
-}
-
-void cras_bt_device_append_iodev(struct cras_bt_device *device,
- struct cras_iodev *iodev,
- enum cras_bt_device_profile profile)
-{
- struct cras_iodev *bt_iodev;
-
- bt_iodev = device->bt_iodevs[iodev->direction];
-
- if (bt_iodev) {
- cras_bt_io_append(bt_iodev, iodev, profile);
- } else {
- device->bt_iodevs[iodev->direction] =
- cras_bt_io_create(device, iodev, profile);
- }
-}
-
-/*
- * Sets the audio nodes to 'plugged' means UI can select it and open it
- * for streams. Sets to 'unplugged' to hide these nodes from UI, when device
- * disconnects in progress.
- */
-static void bt_device_set_nodes_plugged(struct cras_bt_device *device,
- int plugged)
-{
- struct cras_iodev *iodev;
-
- iodev = device->bt_iodevs[CRAS_STREAM_INPUT];
- if (iodev)
- cras_iodev_set_node_plugged(iodev->active_node, plugged);
-
- iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
- if (iodev)
- cras_iodev_set_node_plugged(iodev->active_node, plugged);
-}
-
-static void bt_device_switch_profile(struct cras_bt_device *device,
- struct cras_iodev *bt_iodev,
- int enable_dev);
-
-void cras_bt_device_rm_iodev(struct cras_bt_device *device,
- struct cras_iodev *iodev)
-{
- struct cras_iodev *bt_iodev;
- int rc;
-
- bt_device_set_nodes_plugged(device, 0);
-
- bt_iodev = device->bt_iodevs[iodev->direction];
- if (bt_iodev) {
- unsigned try_profile;
-
- /* Check what will the preffered profile be if we remove dev. */
- try_profile = cras_bt_io_try_remove(bt_iodev, iodev);
- if (!try_profile)
- goto destroy_bt_io;
-
- /* If the check result doesn't match with the active
- * profile we are currently using, switch to the
- * preffered profile before actually remove the iodev.
- */
- if (!cras_bt_io_on_profile(bt_iodev, try_profile)) {
- device->active_profile = try_profile;
- bt_device_switch_profile(device, bt_iodev, 0);
- }
- rc = cras_bt_io_remove(bt_iodev, iodev);
- if (rc) {
- syslog(LOG_ERR, "Fail to fallback to profile %u",
- try_profile);
- goto destroy_bt_io;
- }
- }
- return;
-
-destroy_bt_io:
- device->bt_iodevs[iodev->direction] = NULL;
- cras_bt_io_destroy(bt_iodev);
-
- if (!device->bt_iodevs[CRAS_STREAM_INPUT] &&
- !device->bt_iodevs[CRAS_STREAM_OUTPUT])
- cras_bt_device_set_active_profile(device, 0);
-}
-
-void cras_bt_device_a2dp_configured(struct cras_bt_device *device)
-{
- BTLOG(btlog, BT_A2DP_CONFIGURED, device->connected_profiles, 0);
- device->connected_profiles |= CRAS_BT_DEVICE_PROFILE_A2DP_SINK;
-}
-
-int cras_bt_device_has_a2dp(struct cras_bt_device *device)
-{
- struct cras_iodev *odev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
-
- /* Check if there is an output iodev with A2DP node attached. */
- return odev &&
- cras_bt_io_get_profile(odev, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-}
-
-int cras_bt_device_can_switch_to_a2dp(struct cras_bt_device *device)
-{
- struct cras_iodev *idev = device->bt_iodevs[CRAS_STREAM_INPUT];
-
- return cras_bt_device_has_a2dp(device) &&
- (!idev || !cras_iodev_is_open(idev));
-}
-
-static void bt_device_remove_conflict(struct cras_bt_device *device)
-{
- struct cras_bt_device *connected;
-
- /* Suspend other HFP audio gateways that conflict with device. */
- cras_hfp_ag_remove_conflict(device);
-
- /* Check if there's conflict A2DP headset and suspend it. */
- connected = cras_a2dp_connected_device();
- if (connected && (connected != device))
- cras_a2dp_suspend_connected_device(connected);
-}
-
-static void bt_device_conn_watch_cb(struct cras_timer *timer, void *arg);
-
-int cras_bt_device_audio_gateway_initialized(struct cras_bt_device *device)
-{
- BTLOG(btlog, BT_AUDIO_GATEWAY_INIT, device->profiles, 0);
- /* Marks HFP/HSP as connected. This is what connection watcher
- * checks. */
- device->connected_profiles |= (CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE |
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET);
-
- /* If device connects HFP but not reporting correct UUID, manually add
- * it to allow CRAS to enumerate audio node for it. We're seeing this
- * behavior on qualification test software. */
- if (!cras_bt_device_supports_profile(
- device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE)) {
- unsigned int profiles =
- device->profiles | CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
- cras_bt_device_set_supported_profiles(device, profiles);
- device->hidden_profiles |= CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE;
- bt_device_conn_watch_cb(NULL, (void *)device);
- }
-
- return 0;
-}
-
-unsigned int
-cras_bt_device_get_active_profile(const struct cras_bt_device *device)
-{
- return device->active_profile;
-}
-
-void cras_bt_device_set_active_profile(struct cras_bt_device *device,
- unsigned int profile)
-{
- device->active_profile = profile;
-}
-
-static void cras_bt_device_log_profile(const struct cras_bt_device *device,
- enum cras_bt_device_profile profile)
-{
- switch (profile) {
- case CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is HFP handsfree",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is HFP audio gateway",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is A2DP source",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_A2DP_SINK:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is A2DP sink",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is AVRCP remote",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is AVRCP target",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_HSP_HEADSET:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is HSP headset",
- device->address);
- break;
- case CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY:
- syslog(LOG_DEBUG, "Bluetooth Device: %s is HSP audio gateway",
- device->address);
- break;
- }
-}
-
-static void cras_bt_device_log_profiles(const struct cras_bt_device *device,
- unsigned int profiles)
-{
- unsigned int profile;
-
- while (profiles) {
- /* Get the LSB of profiles */
- profile = profiles & -profiles;
- cras_bt_device_log_profile(device, profile);
- profiles ^= profile;
- }
-}
-
-static int
-cras_bt_device_is_profile_connected(const struct cras_bt_device *device,
- enum cras_bt_device_profile profile)
-{
- return !!(device->connected_profiles & profile);
-}
-
-static void
-bt_device_schedule_suspend(struct cras_bt_device *device, unsigned int msec,
- enum cras_bt_device_suspend_reason suspend_reason);
-
-/* Callback used to periodically check if supported profiles are connected. */
-static void bt_device_conn_watch_cb(struct cras_timer *timer, void *arg)
-{
- struct cras_tm *tm;
- struct cras_bt_device *device = (struct cras_bt_device *)arg;
- int rc;
- bool a2dp_supported;
- bool a2dp_connected;
- bool hfp_supported;
- bool hfp_connected;
-
- BTLOG(btlog, BT_DEV_CONN_WATCH_CB, device->conn_watch_retries,
- device->profiles);
- device->conn_watch_timer = NULL;
-
- /* Skip the callback if it is not an audio device. */
- if (!device->profiles)
- return;
-
- a2dp_supported = cras_bt_device_supports_profile(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
- a2dp_connected = cras_bt_device_is_profile_connected(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
- hfp_supported = cras_bt_device_supports_profile(
- device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
- hfp_connected = cras_bt_device_is_profile_connected(
- device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- /* If not both A2DP and HFP are supported, simply wait for BlueZ
- * to notify us about the new connection.
- * Otherwise, when seeing one but not the other profile is connected,
- * send message to ask BlueZ to connect the pending one.
- */
- if (a2dp_supported && hfp_supported) {
- /* If both a2dp and hfp are not connected, do nothing. BlueZ
- * should be responsible to notify connection of one profile.
- */
- if (!a2dp_connected && hfp_connected)
- cras_bt_device_connect_profile(device->conn, device,
- A2DP_SINK_UUID);
- if (a2dp_connected && !hfp_connected)
- cras_bt_device_connect_profile(device->conn, device,
- HFP_HF_UUID);
- }
-
- if (a2dp_supported != a2dp_connected || hfp_supported != hfp_connected)
- goto arm_retry_timer;
-
- /* Expected profiles are all connected, no more connection watch
- * callback will be scheduled.
- * Base on the decision that we expose only the latest connected
- * BT audio device to user, treat all other connected devices as
- * conflict and remove them before we start A2DP/HFP of this device.
- */
- bt_device_remove_conflict(device);
-
- if (cras_bt_device_is_profile_connected(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK))
- cras_a2dp_start(device);
-
- if (cras_bt_device_is_profile_connected(
- device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE)) {
- rc = cras_hfp_ag_start(device);
- if (rc) {
- syslog(LOG_ERR, "Start audio gateway failed, rc %d",
- rc);
- bt_device_schedule_suspend(device, 0,
- HFP_AG_START_FAILURE);
- }
- }
- bt_device_set_nodes_plugged(device, 1);
- return;
-
-arm_retry_timer:
-
- syslog(LOG_DEBUG, "conn_watch_retries: %d", device->conn_watch_retries);
-
- if (--device->conn_watch_retries) {
- tm = cras_system_state_get_tm();
- device->conn_watch_timer =
- cras_tm_create_timer(tm, CONN_WATCH_PERIOD_MS,
- bt_device_conn_watch_cb, device);
- } else {
- syslog(LOG_ERR, "Connection watch timeout.");
- bt_device_schedule_suspend(device, 0, CONN_WATCH_TIME_OUT);
- }
-}
-
-static void
-cras_bt_device_start_new_conn_watch_timer(struct cras_bt_device *device)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
-
- if (device->conn_watch_timer) {
- cras_tm_cancel_timer(tm, device->conn_watch_timer);
- }
- device->conn_watch_retries = CONN_WATCH_MAX_RETRIES;
- device->conn_watch_timer = cras_tm_create_timer(
- tm, CONN_WATCH_PERIOD_MS, bt_device_conn_watch_cb, device);
-}
-
-static void bt_device_cancel_suspend(struct cras_bt_device *device);
-
-void cras_bt_device_set_connected(struct cras_bt_device *device, int value)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
- if (!device->connected && value) {
- BTLOG(btlog, BT_DEV_CONNECTED, device->profiles,
- device->stable_id);
- }
-
- if (device->connected && !value) {
- BTLOG(btlog, BT_DEV_DISCONNECTED, device->profiles,
- device->stable_id);
- cras_bt_profile_on_device_disconnected(device);
- /* Device is disconnected, resets connected profiles and the
- * suspend timer which scheduled earlier. */
- device->connected_profiles = 0;
- bt_device_cancel_suspend(device);
- }
-
- device->connected = value;
-
- if (!device->connected && device->conn_watch_timer) {
- cras_tm_cancel_timer(tm, device->conn_watch_timer);
- device->conn_watch_timer = NULL;
- }
-}
-
-void cras_bt_device_notify_profile_dropped(struct cras_bt_device *device,
- enum cras_bt_device_profile profile)
-{
- device->connected_profiles &= ~profile;
-
- /* Do nothing if device already disconnected. */
- if (!device->connected)
- return;
-
- /* If any profile, a2dp or hfp/hsp, has dropped for some reason,
- * we shall make sure this device is fully disconnected within
- * given time so that user does not see a headset stay connected
- * but works with partial function.
- */
- bt_device_schedule_suspend(device, PROFILE_DROP_SUSPEND_DELAY_MS,
- UNEXPECTED_PROFILE_DROP);
-}
-
-/* Refresh the list of known supported profiles.
- * Args:
- * device - The BT device holding scanned profiles bitmap.
- * profiles - The OR'ed profiles the device claims to support as is notified
- * by BlueZ.
- * Returns:
- * The OR'ed profiles that are both supported by Cras and isn't previously
- * supported by the device.
- */
-int cras_bt_device_set_supported_profiles(struct cras_bt_device *device,
- unsigned int profiles)
-{
- /* Do nothing if no new profiles. */
- if ((device->profiles & profiles) == profiles)
- return 0;
-
- unsigned int new_profiles = profiles & ~device->profiles;
-
- /* Log this event as we might need to re-intialize the BT audio nodes
- * if new audio profile is reported for already connected device. */
- if (device->connected && (new_profiles & CRAS_SUPPORTED_PROFILES))
- BTLOG(btlog, BT_NEW_AUDIO_PROFILE_AFTER_CONNECT,
- device->profiles, new_profiles);
- cras_bt_device_log_profiles(device, new_profiles);
- device->profiles = profiles | device->hidden_profiles;
-
- return (new_profiles & CRAS_SUPPORTED_PROFILES);
-}
-
-void cras_bt_device_update_properties(struct cras_bt_device *device,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter)
-{
- int watch_needed = 0;
- while (dbus_message_iter_get_arg_type(properties_array_iter) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter properties_dict_iter, variant_iter;
- const char *key;
- int type;
-
- dbus_message_iter_recurse(properties_array_iter,
- &properties_dict_iter);
-
- dbus_message_iter_get_basic(&properties_dict_iter, &key);
- dbus_message_iter_next(&properties_dict_iter);
-
- dbus_message_iter_recurse(&properties_dict_iter, &variant_iter);
- type = dbus_message_iter_get_arg_type(&variant_iter);
-
- if (type == DBUS_TYPE_STRING || type == DBUS_TYPE_OBJECT_PATH) {
- const char *value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Adapter") == 0) {
- free(device->adapter_obj_path);
- device->adapter_obj_path = strdup(value);
- } else if (strcmp(key, "Address") == 0) {
- free(device->address);
- device->address = strdup(value);
- } else if (strcmp(key, "Alias") == 0) {
- free(device->name);
- device->name = strdup(value);
- }
-
- } else if (type == DBUS_TYPE_UINT32) {
- uint32_t value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Class") == 0)
- device->bluetooth_class = value;
-
- } else if (type == DBUS_TYPE_BOOLEAN) {
- int value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Paired") == 0) {
- device->paired = value;
- } else if (strcmp(key, "Trusted") == 0) {
- device->trusted = value;
- } else if (strcmp(key, "Connected") == 0) {
- cras_bt_device_set_connected(device, value);
- watch_needed = device->connected &&
- cras_bt_device_supports_profile(
- device,
- CRAS_SUPPORTED_PROFILES);
- }
-
- } else if (strcmp(dbus_message_iter_get_signature(&variant_iter),
- "as") == 0 &&
- strcmp(key, "UUIDs") == 0) {
- DBusMessageIter uuid_array_iter;
- unsigned int profiles = 0;
-
- dbus_message_iter_recurse(&variant_iter,
- &uuid_array_iter);
- while (dbus_message_iter_get_arg_type(
- &uuid_array_iter) != DBUS_TYPE_INVALID) {
- const char *uuid;
-
- dbus_message_iter_get_basic(&uuid_array_iter,
- &uuid);
- profiles |=
- cras_bt_device_profile_from_uuid(uuid);
-
- dbus_message_iter_next(&uuid_array_iter);
- }
-
- /* If updated properties includes new audio profile and
- * device is connected, we need to start connection
- * watcher. This is needed because on some bluetooth
- * devices, supported profiles do not present when
- * device interface is added and they are updated later.
- */
- if (cras_bt_device_set_supported_profiles(device,
- profiles))
- watch_needed = device->connected;
- }
-
- dbus_message_iter_next(properties_array_iter);
- }
-
- while (invalidated_array_iter &&
- dbus_message_iter_get_arg_type(invalidated_array_iter) !=
- DBUS_TYPE_INVALID) {
- const char *key;
-
- dbus_message_iter_get_basic(invalidated_array_iter, &key);
-
- if (strcmp(key, "Adapter") == 0) {
- free(device->adapter_obj_path);
- device->adapter_obj_path = NULL;
- } else if (strcmp(key, "Address") == 0) {
- free(device->address);
- device->address = NULL;
- } else if (strcmp(key, "Alias") == 0) {
- free(device->name);
- device->name = NULL;
- } else if (strcmp(key, "Class") == 0) {
- device->bluetooth_class = 0;
- } else if (strcmp(key, "Paired") == 0) {
- device->paired = 0;
- } else if (strcmp(key, "Trusted") == 0) {
- device->trusted = 0;
- } else if (strcmp(key, "Connected") == 0) {
- device->connected = 0;
- } else if (strcmp(key, "UUIDs") == 0) {
- device->profiles = device->hidden_profiles;
- }
-
- dbus_message_iter_next(invalidated_array_iter);
- }
-
- if (watch_needed)
- cras_bt_device_start_new_conn_watch_timer(device);
-}
-
-/* Converts bluetooth address string into sockaddr structure. The address
- * string is expected of the form 1A:2B:3C:4D:5E:6F, and each of the six
- * hex values will be parsed into sockaddr in inverse order.
- * Args:
- * str - The string version of bluetooth address
- * addr - The struct to be filled with converted address
- */
-static int bt_address(const char *str, struct sockaddr *addr)
-{
- int i;
-
- if (strlen(str) != 17) {
- syslog(LOG_ERR, "Invalid bluetooth address %s", str);
- return -1;
- }
-
- memset(addr, 0, sizeof(*addr));
- addr->sa_family = AF_BLUETOOTH;
- for (i = 5; i >= 0; i--) {
- addr->sa_data[i] = (unsigned char)strtol(str, NULL, 16);
- str += 3;
- }
-
- return 0;
-}
-
-/* Apply codec specific settings to the socket fd. */
-static int apply_codec_settings(int fd, uint8_t codec)
-{
- struct bt_voice voice;
- uint32_t pkt_status;
-
- memset(&voice, 0, sizeof(voice));
- if (codec == HFP_CODEC_ID_CVSD)
- return 0;
-
- if (codec != HFP_CODEC_ID_MSBC) {
- syslog(LOG_ERR, "Unsupported codec %d", codec);
- return -1;
- }
-
- voice.setting = BT_VOICE_TRANSPARENT;
-
- if (setsockopt(fd, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)) <
- 0) {
- syslog(LOG_ERR, "Failed to apply voice setting");
- return -1;
- }
-
- pkt_status = 1;
- if (setsockopt(fd, SOL_BLUETOOTH, BT_PKT_STATUS, &pkt_status,
- sizeof(pkt_status))) {
- syslog(LOG_ERR, "Failed to enable BT_PKT_STATUS");
- }
- return 0;
-}
-
-int cras_bt_device_sco_connect(struct cras_bt_device *device, int codec)
-{
- int sk = 0, err;
- struct sockaddr addr;
- struct cras_bt_adapter *adapter;
- struct timespec timeout = { 1, 0 };
- struct pollfd pollfd;
-
- adapter = cras_bt_device_adapter(device);
- if (!adapter) {
- syslog(LOG_ERR, "No adapter found for device %s at SCO connect",
- cras_bt_device_object_path(device));
- goto error;
- }
-
- sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET | O_NONBLOCK | SOCK_CLOEXEC,
- BTPROTO_SCO);
- if (sk < 0) {
- syslog(LOG_ERR, "Failed to create socket: %s (%d)",
- strerror(errno), errno);
- cras_server_metrics_hfp_sco_connection_error(
- CRAS_METRICS_SCO_SKT_OPEN_ERROR);
- return -errno;
- }
-
- /* Bind to local address */
- if (bt_address(cras_bt_adapter_address(adapter), &addr))
- goto error;
- if (bind(sk, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
- syslog(LOG_ERR, "Failed to bind socket: %s (%d)",
- strerror(errno), errno);
- goto error;
- }
-
- /* Connect to remote in nonblocking mode */
- fcntl(sk, F_SETFL, O_NONBLOCK);
-
- if (bt_address(cras_bt_device_address(device), &addr))
- goto error;
-
- err = apply_codec_settings(sk, codec);
- if (err)
- goto error;
-
- err = connect(sk, (struct sockaddr *)&addr, sizeof(addr));
- if (err && errno != EINPROGRESS) {
- syslog(LOG_ERR, "Failed to connect: %s (%d)", strerror(errno),
- errno);
- cras_server_metrics_hfp_sco_connection_error(
- CRAS_METRICS_SCO_SKT_CONNECT_ERROR);
- goto error;
- }
-
- pollfd.fd = sk;
- pollfd.events = POLLOUT;
-
- err = ppoll(&pollfd, 1, &timeout, NULL);
- if (err <= 0) {
- syslog(LOG_ERR, "Connect SCO: poll for writable timeout");
- cras_server_metrics_hfp_sco_connection_error(
- CRAS_METRICS_SCO_SKT_POLL_TIMEOUT);
- goto error;
- }
-
- if (pollfd.revents & (POLLERR | POLLHUP)) {
- syslog(LOG_ERR,
- "SCO socket error, revents: %u. Suspend in %u seconds",
- pollfd.revents, SCO_SUSPEND_DELAY_MS);
- cras_server_metrics_hfp_sco_connection_error(
- CRAS_METRICS_SCO_SKT_POLL_ERR_HUP);
- bt_device_schedule_suspend(device, SCO_SUSPEND_DELAY_MS,
- HFP_SCO_SOCKET_ERROR);
- goto error;
- }
-
- cras_server_metrics_hfp_sco_connection_error(
- CRAS_METRICS_SCO_SKT_SUCCESS);
- BTLOG(btlog, BT_SCO_CONNECT, 1, sk);
- return sk;
-
-error:
- BTLOG(btlog, BT_SCO_CONNECT, 0, sk);
- if (sk)
- close(sk);
- return -1;
-}
-
-int cras_bt_device_sco_packet_size(struct cras_bt_device *device,
- int sco_socket, int codec)
-{
- struct sco_options so;
- socklen_t len = sizeof(so);
- struct cras_bt_adapter *adapter;
- uint32_t wbs_pkt_len = 0;
- socklen_t optlen = sizeof(wbs_pkt_len);
-
- adapter = cras_bt_adapter_get(device->adapter_obj_path);
-
- if (cras_bt_adapter_on_usb(adapter)) {
- if (codec == HFP_CODEC_ID_MSBC) {
- /* BT_SNDMTU and BT_RCVMTU return the same value. */
- if (getsockopt(sco_socket, SOL_BLUETOOTH, BT_SNDMTU,
- &wbs_pkt_len, &optlen))
- syslog(LOG_ERR, "Failed to get BT_SNDMTU");
-
- return (wbs_pkt_len > 0) ? wbs_pkt_len :
- USB_MSBC_PKT_SIZE;
- } else {
- return USB_CVSD_PKT_SIZE;
- }
- }
-
- /* For non-USB cases, query the SCO MTU from driver. */
- if (getsockopt(sco_socket, SOL_SCO, SCO_OPTIONS, &so, &len) < 0) {
- syslog(LOG_ERR, "Get SCO options error: %s", strerror(errno));
- return DEFAULT_SCO_PKT_SIZE;
- }
- return so.mtu;
-}
-
-void cras_bt_device_set_use_hardware_volume(struct cras_bt_device *device,
- int use_hardware_volume)
-{
- struct cras_iodev *iodev;
-
- device->use_hardware_volume = use_hardware_volume;
- iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
- if (iodev)
- iodev->software_volume_needed = !use_hardware_volume;
-}
-
-int cras_bt_device_get_use_hardware_volume(struct cras_bt_device *device)
-{
- return device->use_hardware_volume;
-}
-
-static void init_bt_device_msg(struct bt_device_msg *msg,
- enum BT_DEVICE_COMMAND cmd,
- struct cras_bt_device *device,
- struct cras_iodev *dev, unsigned int arg1,
- unsigned int arg2)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.type = CRAS_MAIN_BT;
- msg->header.length = sizeof(*msg);
- msg->cmd = cmd;
- msg->device = device;
- msg->dev = dev;
- msg->arg1 = arg1;
- msg->arg2 = arg2;
-}
-
-int cras_bt_device_cancel_suspend(struct cras_bt_device *device)
-{
- struct bt_device_msg msg;
- int rc;
-
- init_bt_device_msg(&msg, BT_DEVICE_CANCEL_SUSPEND, device, NULL, 0, 0);
- rc = cras_main_message_send((struct cras_main_message *)&msg);
- return rc;
-}
-
-int cras_bt_device_schedule_suspend(
- struct cras_bt_device *device, unsigned int msec,
- enum cras_bt_device_suspend_reason suspend_reason)
-{
- struct bt_device_msg msg;
- int rc;
-
- init_bt_device_msg(&msg, BT_DEVICE_SCHEDULE_SUSPEND, device, NULL, msec,
- suspend_reason);
- rc = cras_main_message_send((struct cras_main_message *)&msg);
- return rc;
-}
-
-/* This diagram describes how the profile switching happens. When
- * certain conditions met, bt iodev will call the APIs below to interact
- * with main thread to switch to another active profile.
- *
- * Audio thread:
- * +--------------------------------------------------------------+
- * | bt iodev |
- * | +------------------+ +-----------------+ |
- * | | condition met to | | open, close, or | |
- * | +--| change profile |<---| append profile |<--+ |
- * | | +------------------+ +-----------------+ | |
- * +-----------|------------------------------------------------|-+
- * | |
- * Main thread: |
- * +-----------|------------------------------------------------|-+
- * | | | |
- * | | +------------+ +----------------+ | |
- * | +----->| set active |---->| switch profile |-----+ |
- * | | profile | +----------------+ |
- * | bt device +------------+ |
- * +--------------------------------------------------------------+
- */
-int cras_bt_device_switch_profile_enable_dev(struct cras_bt_device *device,
- struct cras_iodev *bt_iodev)
-{
- struct bt_device_msg msg;
- int rc;
-
- init_bt_device_msg(&msg, BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV, device,
- bt_iodev, 0, 0);
- rc = cras_main_message_send((struct cras_main_message *)&msg);
- return rc;
-}
-
-int cras_bt_device_switch_profile(struct cras_bt_device *device,
- struct cras_iodev *bt_iodev)
-{
- struct bt_device_msg msg;
- int rc;
-
- init_bt_device_msg(&msg, BT_DEVICE_SWITCH_PROFILE, device, bt_iodev, 0,
- 0);
- rc = cras_main_message_send((struct cras_main_message *)&msg);
- return rc;
-}
-
-static void profile_switch_delay_cb(struct cras_timer *timer, void *arg)
-{
- struct cras_bt_device *device = (struct cras_bt_device *)arg;
- struct cras_iodev *iodev;
-
- device->switch_profile_timer = NULL;
- iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
- if (!iodev)
- return;
-
- /*
- * During the |PROFILE_SWITCH_DELAY_MS| time interval, BT iodev could
- * have been enabled by others, and its active profile may have changed.
- * If iodev has been enabled, that means it has already picked up a
- * reasonable profile to use and audio thread is accessing iodev now.
- * We should NOT call into update_active_node from main thread
- * because that may mess up the active node content.
- */
- iodev->update_active_node(iodev, 0, 1);
- cras_iodev_list_resume_dev(iodev->info.idx);
-}
-
-static void bt_device_switch_profile_with_delay(struct cras_bt_device *device,
- unsigned int delay_ms)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
-
- if (device->switch_profile_timer) {
- cras_tm_cancel_timer(tm, device->switch_profile_timer);
- device->switch_profile_timer = NULL;
- }
- device->switch_profile_timer = cras_tm_create_timer(
- tm, delay_ms, profile_switch_delay_cb, device);
-}
-
-/* Switches associated bt iodevs to use the active profile. This is
- * achieved by close the iodevs, update their active nodes, and then
- * finally reopen them. */
-static void bt_device_switch_profile(struct cras_bt_device *device,
- struct cras_iodev *bt_iodev,
- int enable_dev)
-{
- struct cras_iodev *iodev;
- int dir;
-
- /* If a bt iodev is active, temporarily force close it.
- * Note that we need to check all bt_iodevs for the situation that both
- * input and output are active while switches from HFP/HSP to A2DP.
- */
- for (dir = 0; dir < CRAS_NUM_DIRECTIONS; dir++) {
- iodev = device->bt_iodevs[dir];
- if (!iodev)
- continue;
- cras_iodev_list_suspend_dev(iodev->info.idx);
- }
-
- for (dir = 0; dir < CRAS_NUM_DIRECTIONS; dir++) {
- iodev = device->bt_iodevs[dir];
- if (!iodev)
- continue;
-
- /* If the iodev was active or this profile switching is
- * triggered at opening iodev, add it to active dev list.
- * However for the output iodev, adding it back to active dev
- * list could cause immediate switching from HFP to A2DP if
- * there exists an output stream. Certain headset/speaker
- * would fail to playback afterwards when the switching happens
- * too soon, so put this task in a delayed callback.
- */
- if (dir == CRAS_STREAM_INPUT) {
- iodev->update_active_node(iodev, 0, 1);
- cras_iodev_list_resume_dev(iodev->info.idx);
- } else {
- bt_device_switch_profile_with_delay(
- device, PROFILE_SWITCH_DELAY_MS);
- }
- }
-}
-
-static void bt_device_suspend_cb(struct cras_timer *timer, void *arg)
-{
- struct cras_bt_device *device = (struct cras_bt_device *)arg;
-
- BTLOG(btlog, BT_DEV_SUSPEND_CB, device->profiles,
- device->suspend_reason);
- device->suspend_timer = NULL;
-
- /* Error log the reason so we can track them in user reports. */
- switch (device->suspend_reason) {
- case A2DP_LONG_TX_FAILURE:
- syslog(LOG_ERR, "Suspend dev: A2DP long Tx failure");
- break;
- case A2DP_TX_FATAL_ERROR:
- syslog(LOG_ERR, "Suspend dev: A2DP Tx fatal error");
- break;
- case CONN_WATCH_TIME_OUT:
- syslog(LOG_ERR, "Suspend dev: Conn watch times out");
- break;
- case HFP_SCO_SOCKET_ERROR:
- syslog(LOG_ERR, "Suspend dev: SCO socket error");
- break;
- case HFP_AG_START_FAILURE:
- syslog(LOG_ERR, "Suspend dev: HFP AG start failure");
- break;
- case UNEXPECTED_PROFILE_DROP:
- syslog(LOG_ERR, "Suspend dev: Unexpected profile drop");
- break;
- }
-
- cras_a2dp_suspend_connected_device(device);
- cras_hfp_ag_suspend_connected_device(device);
- cras_bt_device_disconnect(device->conn, device);
-}
-
-static void
-bt_device_schedule_suspend(struct cras_bt_device *device, unsigned int msec,
- enum cras_bt_device_suspend_reason suspend_reason)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
-
- if (device->suspend_timer)
- return;
- device->suspend_reason = suspend_reason;
- device->suspend_timer =
- cras_tm_create_timer(tm, msec, bt_device_suspend_cb, device);
-}
-
-static void bt_device_cancel_suspend(struct cras_bt_device *device)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
- if (device->suspend_timer == NULL)
- return;
- cras_tm_cancel_timer(tm, device->suspend_timer);
- device->suspend_timer = NULL;
-}
-
-static void bt_device_process_msg(struct cras_main_message *msg, void *arg)
-{
- struct bt_device_msg *bt_msg = (struct bt_device_msg *)msg;
- struct cras_bt_device *device = NULL;
-
- DL_FOREACH (devices, device) {
- if (device == bt_msg->device)
- break;
- }
-
- /* Do nothing if target device no longer exists. */
- if (device == NULL)
- return;
-
- switch (bt_msg->cmd) {
- case BT_DEVICE_SWITCH_PROFILE:
- bt_device_switch_profile(bt_msg->device, bt_msg->dev, 0);
- break;
- case BT_DEVICE_SWITCH_PROFILE_ENABLE_DEV:
- bt_device_switch_profile(bt_msg->device, bt_msg->dev, 1);
- break;
- case BT_DEVICE_SCHEDULE_SUSPEND:
- bt_device_schedule_suspend(bt_msg->device, bt_msg->arg1,
- bt_msg->arg2);
- break;
- case BT_DEVICE_CANCEL_SUSPEND:
- bt_device_cancel_suspend(bt_msg->device);
- break;
- default:
- break;
- }
-}
-
-void cras_bt_device_start_monitor()
-{
- cras_main_message_add_handler(CRAS_MAIN_BT, bt_device_process_msg,
- NULL);
-}
-
-void cras_bt_device_update_hardware_volume(struct cras_bt_device *device,
- int volume)
-{
- struct cras_iodev *iodev;
-
- iodev = device->bt_iodevs[CRAS_STREAM_OUTPUT];
- if (iodev == NULL)
- return;
-
- /* Check if this BT device is okay to use hardware volume. If not
- * then ignore the reported volume change event.
- */
- if (!cras_bt_device_get_use_hardware_volume(device))
- return;
-
- iodev->active_node->volume = volume;
- cras_iodev_list_notify_node_volume(iodev->active_node);
-}
-
-int cras_bt_device_get_sco(struct cras_bt_device *device, int codec)
-{
- if (device->sco_ref_count == 0) {
- device->sco_fd = cras_bt_device_sco_connect(device, codec);
- if (device->sco_fd < 0)
- return device->sco_fd;
- }
-
- ++device->sco_ref_count;
- return 0;
-}
-
-void cras_bt_device_put_sco(struct cras_bt_device *device)
-{
- if (device->sco_ref_count == 0)
- return;
-
- if (--device->sco_ref_count == 0)
- close(device->sco_fd);
-}
diff --git a/cras/src/server/cras_bt_device.h b/cras/src/server/cras_bt_device.h
deleted file mode 100644
index 9d3a2b9e..00000000
--- a/cras/src/server/cras_bt_device.h
+++ /dev/null
@@ -1,230 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_DEVICE_H_
-#define CRAS_BT_DEVICE_H_
-
-#include <dbus/dbus.h>
-
-struct cras_bt_adapter;
-struct cras_bt_device;
-struct cras_iodev;
-struct cras_timer;
-
-/* All the reasons for when CRAS schedule a suspend to BT device. */
-enum cras_bt_device_suspend_reason {
- A2DP_LONG_TX_FAILURE,
- A2DP_TX_FATAL_ERROR,
- CONN_WATCH_TIME_OUT,
- HFP_SCO_SOCKET_ERROR,
- HFP_AG_START_FAILURE,
- UNEXPECTED_PROFILE_DROP,
-};
-
-enum cras_bt_device_profile {
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE = (1 << 0),
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK = (1 << 1),
- CRAS_BT_DEVICE_PROFILE_AVRCP_REMOTE = (1 << 2),
- CRAS_BT_DEVICE_PROFILE_AVRCP_TARGET = (1 << 3),
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE = (1 << 4),
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY = (1 << 5),
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET = (1 << 6),
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY = (1 << 7)
-};
-
-enum cras_bt_device_profile cras_bt_device_profile_from_uuid(const char *uuid);
-
-struct cras_bt_device *cras_bt_device_create(DBusConnection *conn,
- const char *object_path);
-
-/*
- * Removes a BT device from record. If this device is connected state,
- * ensure the associated A2DP and HFP AG be removed cleanly.
- */
-void cras_bt_device_remove(struct cras_bt_device *device);
-
-void cras_bt_device_reset();
-
-struct cras_bt_device *cras_bt_device_get(const char *object_path);
-
-const char *cras_bt_device_object_path(const struct cras_bt_device *device);
-
-/* Gets the stable id of given cras_bt_device. */
-int cras_bt_device_get_stable_id(const struct cras_bt_device *device);
-
-struct cras_bt_adapter *
-cras_bt_device_adapter(const struct cras_bt_device *device);
-const char *cras_bt_device_address(const struct cras_bt_device *device);
-const char *cras_bt_device_name(const struct cras_bt_device *device);
-int cras_bt_device_paired(const struct cras_bt_device *device);
-int cras_bt_device_trusted(const struct cras_bt_device *device);
-int cras_bt_device_connected(const struct cras_bt_device *device);
-
-void cras_bt_device_update_properties(struct cras_bt_device *device,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter);
-
-/* Updates the supported profiles on dev. Expose for unit test. */
-int cras_bt_device_set_supported_profiles(struct cras_bt_device *device,
- unsigned int profiles);
-
-/* Checks if profile is claimed supported by the device. */
-int cras_bt_device_supports_profile(const struct cras_bt_device *device,
- enum cras_bt_device_profile profile);
-
-/* Sets if the BT audio device should use hardware volume.
- * Args:
- * device - The remote bluetooth audio device.
- * use_hardware_volume - Set to true to indicate hardware volume
- * is preferred over software volume.
- */
-void cras_bt_device_set_use_hardware_volume(struct cras_bt_device *device,
- int use_hardware_volume);
-
-/* Gets if the BT audio device should use hardware volume. */
-int cras_bt_device_get_use_hardware_volume(struct cras_bt_device *device);
-
-/* Sets device connected state. Expose for unit test. */
-void cras_bt_device_set_connected(struct cras_bt_device *device, int value);
-
-/* Forces disconnect the bt device. Used when handling audio error
- * that we want to make the device be completely disconnected from
- * host to reflect the state that an error has occurred.
- * Args:
- * conn - The dbus connection.
- * device - The bt device to disconnect.
- */
-int cras_bt_device_disconnect(DBusConnection *conn,
- struct cras_bt_device *device);
-
-/* Gets the SCO socket for the device.
- * Args:
- * device - The device object to get SCO socket for.
- * codec - 1 for CVSD, 2 for mSBC
- */
-int cras_bt_device_sco_connect(struct cras_bt_device *device, int codec);
-
-/* Gets the SCO packet size in bytes, used by HFP iodev for audio I/O.
- * The logic is built base on experience: for USB bus, respect BT Core spec
- * that has clear recommendation of packet size of codecs (CVSD, mSBC).
- * As for other buses, use the MTU value of SCO socket filled by driver.
- * Args:
- * device - The bt device to query mtu.
- * sco_socket - The SCO socket.
- * codec - 1 for CVSD, 2 for mSBC per HFP 1.7 specification.
- */
-int cras_bt_device_sco_packet_size(struct cras_bt_device *device,
- int sco_socket, int codec);
-
-/* Appends an iodev to bt device.
- * Args:
- * device - The device to append iodev to.
- * iodev - The iodev to add.
- * profile - The profile of the iodev about to add.
- */
-void cras_bt_device_append_iodev(struct cras_bt_device *device,
- struct cras_iodev *iodev,
- enum cras_bt_device_profile profile);
-
-/* Removes an iodev from bt device.
- * Args:
- * device - The device to remove iodev from.
- * iodev - The iodev to remove.
- */
-void cras_bt_device_rm_iodev(struct cras_bt_device *device,
- struct cras_iodev *iodev);
-
-/* Gets the active profile of the bt device. */
-unsigned int
-cras_bt_device_get_active_profile(const struct cras_bt_device *device);
-
-/* Sets the active profile of the bt device. */
-void cras_bt_device_set_active_profile(struct cras_bt_device *device,
- unsigned int profile);
-
-/* Switches profile after the active profile of bt device has changed and
- * enables bt iodev immediately. This function is used for profile switching
- * at iodev open.
- * Args:
- * device - The bluetooth device.
- * bt_iodev - The iodev triggers the reactivaion.
- */
-int cras_bt_device_switch_profile_enable_dev(struct cras_bt_device *device,
- struct cras_iodev *bt_iodev);
-
-/* Switches profile after the active profile of bt device has changed. This
- * function is used when we want to switch profile without changing the
- * iodev's status.
- * Args:
- * device - The bluetooth device.
- * bt_iodev - The iodev triggers the reactivaion.
- */
-int cras_bt_device_switch_profile(struct cras_bt_device *device,
- struct cras_iodev *bt_iodev);
-
-void cras_bt_device_start_monitor();
-
-/* Checks if the device has an iodev for A2DP. */
-int cras_bt_device_has_a2dp(struct cras_bt_device *device);
-
-/* Returns true if and only if device has an iodev for A2DP and the bt device
- * is not opening for audio capture.
- */
-int cras_bt_device_can_switch_to_a2dp(struct cras_bt_device *device);
-
-/* Updates the volume to bt_device when a volume change event is reported. */
-void cras_bt_device_update_hardware_volume(struct cras_bt_device *device,
- int volume);
-
-/* Notifies bt_device that a2dp connection is configured. */
-void cras_bt_device_a2dp_configured(struct cras_bt_device *device);
-
-/* Cancels any scheduled suspension of device. */
-int cras_bt_device_cancel_suspend(struct cras_bt_device *device);
-
-/* Schedules device to suspend after given delay. */
-int cras_bt_device_schedule_suspend(
- struct cras_bt_device *device, unsigned int msec,
- enum cras_bt_device_suspend_reason suspend_reason);
-
-/* Notifies bt device that audio gateway is initialized.
- * Args:
- * device - The bluetooth device.
- * Returns:
- * 0 on success, error code otherwise.
- */
-int cras_bt_device_audio_gateway_initialized(struct cras_bt_device *device);
-
-/*
- * Notifies bt device about a profile no longer works. It could be caused
- * by initialize failure or fatal error has occurred.
- * Args:
- * device - The bluetooth audio device.
- * profile - The BT audio profile that has dropped.
- */
-void cras_bt_device_notify_profile_dropped(struct cras_bt_device *device,
- enum cras_bt_device_profile profile);
-
-/*
- * Establishes SCO connection if it has not been established on the BT device.
- * Note: this function should be only used for hfp_alsa_io.
- * Args:
- * device - The bluetooth device.
- * codec - 1 for CVSD, 2 for mSBC
- * Returns:
- * 0 on success, error code otherwise.
- */
-int cras_bt_device_get_sco(struct cras_bt_device *device, int codec);
-
-/*
- * Closes SCO connection if the caller is the last user for the connection on
- * the BT device.
- * Note: this function should be only used for hfp_alsa_io.
- * Args:
- * device - The bluetooth device.
- */
-void cras_bt_device_put_sco(struct cras_bt_device *device);
-
-#endif /* CRAS_BT_DEVICE_H_ */
diff --git a/cras/src/server/cras_bt_endpoint.c b/cras/src/server/cras_bt_endpoint.c
deleted file mode 100644
index 5b2b6e06..00000000
--- a/cras/src/server/cras_bt_endpoint.c
+++ /dev/null
@@ -1,583 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_bt_constants.h"
-#include "cras_bt_adapter.h"
-#include "cras_bt_endpoint.h"
-#include "cras_bt_transport.h"
-#include "utlist.h"
-
-/* Defined by doc/media-api.txt in the BlueZ source */
-#define ENDPOINT_INTROSPECT_XML \
- DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
- "<node>\n" \
- " <interface name=\"org.bluez.MediaEndpoint\">\n" \
- " <method name=\"SetConfiguration\">\n" \
- " <arg name=\"transport\" type=\"o\" direction=\"in\"/>\n" \
- " <arg name=\"configuration\" type=\"a{sv}\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SelectConfiguration\">\n" \
- " <arg name=\"capabilities\" type=\"ay\" direction=\"in\"/>\n" \
- " <arg name=\"configuration\" type=\"ay\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"ClearConfiguration\">\n" \
- " </method>\n" \
- " <method name=\"Release\">\n" \
- " </method>\n" \
- " </interface>\n" \
- " <interface name=\"" DBUS_INTERFACE_INTROSPECTABLE "\">\n" \
- " <method name=\"Introspect\">\n" \
- " <arg name=\"data\" type=\"s\" direction=\"out\"/>\n" \
- " </method>\n" \
- " </interface>\n" \
- "</node>\n"
-
-static void cras_bt_endpoint_suspend(struct cras_bt_endpoint *endpoint)
-{
- struct cras_bt_transport *transport;
-
- if (!endpoint->transport)
- return;
-
- endpoint->suspend(endpoint, endpoint->transport);
-
- transport = endpoint->transport;
- cras_bt_transport_set_endpoint(transport, NULL);
- endpoint->transport = NULL;
-
- /*
- * If BT stack has notified this transport interface removed.
- * Destroy transport now since all related objects has been
- * cleaned up.
- */
- if (cras_bt_transport_is_removed(transport))
- cras_bt_transport_destroy(transport);
-}
-
-static DBusHandlerResult
-cras_bt_endpoint_set_configuration(DBusConnection *conn, DBusMessage *message,
- void *arg)
-{
- DBusMessageIter message_iter, properties_array_iter;
- const char *endpoint_path, *transport_path;
- struct cras_bt_endpoint *endpoint;
- struct cras_bt_transport *transport;
- DBusMessage *reply;
-
- syslog(LOG_DEBUG, "SetConfiguration: %s",
- dbus_message_get_path(message));
-
- endpoint_path = dbus_message_get_path(message);
- endpoint = cras_bt_endpoint_get(endpoint_path);
- if (!endpoint)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- if (!dbus_message_has_signature(message, "oa{sv}")) {
- syslog(LOG_WARNING, "Bad SetConfiguration message received.");
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- dbus_message_iter_init(message, &message_iter);
-
- dbus_message_iter_get_basic(&message_iter, &transport_path);
- dbus_message_iter_next(&message_iter);
-
- dbus_message_iter_recurse(&message_iter, &properties_array_iter);
-
- transport = cras_bt_transport_get(transport_path);
- if (transport) {
- cras_bt_transport_update_properties(
- transport, &properties_array_iter, NULL);
- } else {
- transport = cras_bt_transport_create(conn, transport_path);
- if (transport) {
- cras_bt_transport_update_properties(
- transport, &properties_array_iter, NULL);
- syslog(LOG_INFO, "Bluetooth Transport: %s added",
- cras_bt_transport_object_path(transport));
- }
- }
-
- if (!cras_bt_transport_device(transport)) {
- syslog(LOG_ERR, "Do device found for transport %s",
- cras_bt_transport_object_path(transport));
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- cras_bt_transport_set_endpoint(transport, endpoint);
- endpoint->transport = transport;
- endpoint->set_configuration(endpoint, transport);
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-cras_bt_endpoint_select_configuration(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusError dbus_error;
- const char *endpoint_path;
- struct cras_bt_endpoint *endpoint;
- char buf[4];
- void *capabilities, *configuration = buf;
- int len;
- DBusMessage *reply;
-
- syslog(LOG_DEBUG, "SelectConfiguration: %s",
- dbus_message_get_path(message));
-
- endpoint_path = dbus_message_get_path(message);
- endpoint = cras_bt_endpoint_get(endpoint_path);
- if (!endpoint)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_ARRAY,
- DBUS_TYPE_BYTE, &capabilities, &len,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad SelectConfiguration method call: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- if (len > sizeof(configuration) ||
- endpoint->select_configuration(endpoint, capabilities, len,
- configuration) < 0) {
- reply = dbus_message_new_error(
- message,
- "org.chromium.Cras.Error.UnsupportedConfiguration",
- "Unable to select configuration from capabilities");
-
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
- }
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_message_append_args(reply, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE,
- &configuration, len, DBUS_TYPE_INVALID))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-cras_bt_endpoint_clear_configuration(DBusConnection *conn, DBusMessage *message,
- void *arg)
-{
- DBusError dbus_error;
- const char *endpoint_path, *transport_path;
- struct cras_bt_endpoint *endpoint;
- struct cras_bt_transport *transport;
- DBusMessage *reply;
-
- syslog(LOG_DEBUG, "ClearConfiguration: %s",
- dbus_message_get_path(message));
-
- endpoint_path = dbus_message_get_path(message);
- endpoint = cras_bt_endpoint_get(endpoint_path);
- if (!endpoint)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_OBJECT_PATH,
- &transport_path, DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad ClearConfiguration method call: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- transport = cras_bt_transport_get(transport_path);
-
- if (transport == endpoint->transport)
- cras_bt_endpoint_suspend(endpoint);
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-cras_bt_endpoint_release(DBusConnection *conn, DBusMessage *message, void *arg)
-{
- const char *endpoint_path;
- struct cras_bt_endpoint *endpoint;
- DBusMessage *reply;
-
- syslog(LOG_DEBUG, "Release: %s", dbus_message_get_path(message));
-
- endpoint_path = dbus_message_get_path(message);
- endpoint = cras_bt_endpoint_get(endpoint_path);
- if (!endpoint)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- cras_bt_endpoint_suspend(endpoint);
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult cras_bt_handle_endpoint_message(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- syslog(LOG_DEBUG, "Endpoint message: %s %s %s",
- dbus_message_get_path(message),
- dbus_message_get_interface(message),
- dbus_message_get_member(message));
-
- if (dbus_message_is_method_call(message, DBUS_INTERFACE_INTROSPECTABLE,
- "Introspect")) {
- DBusMessage *reply;
- const char *xml = ENDPOINT_INTROSPECT_XML;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &xml,
- DBUS_TYPE_INVALID))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-
- } else if (dbus_message_is_method_call(message,
- BLUEZ_INTERFACE_MEDIA_ENDPOINT,
- "SetConfiguration")) {
- return cras_bt_endpoint_set_configuration(conn, message, arg);
-
- } else if (dbus_message_is_method_call(message,
- BLUEZ_INTERFACE_MEDIA_ENDPOINT,
- "SelectConfiguration")) {
- return cras_bt_endpoint_select_configuration(conn, message,
- arg);
-
- } else if (dbus_message_is_method_call(message,
- BLUEZ_INTERFACE_MEDIA_ENDPOINT,
- "ClearConfiguration")) {
- return cras_bt_endpoint_clear_configuration(conn, message, arg);
-
- } else if (dbus_message_is_method_call(message,
- BLUEZ_INTERFACE_MEDIA_ENDPOINT,
- "Release")) {
- return cras_bt_endpoint_release(conn, message, arg);
-
- } else {
- syslog(LOG_DEBUG, "%s: %s.%s: Unknown MediaEndpoint message",
- dbus_message_get_path(message),
- dbus_message_get_interface(message),
- dbus_message_get_member(message));
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-}
-
-static void cras_bt_on_register_endpoint(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_WARNING, "RegisterEndpoint returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return;
- }
-
- dbus_message_unref(reply);
-}
-
-int cras_bt_register_endpoint(DBusConnection *conn,
- const struct cras_bt_adapter *adapter,
- struct cras_bt_endpoint *endpoint)
-{
- const char *adapter_path, *key;
- DBusMessage *method_call;
- DBusMessageIter message_iter;
- DBusMessageIter properties_array_iter, properties_dict_iter;
- DBusMessageIter variant_iter, bytes_iter;
- DBusPendingCall *pending_call;
- char buf[4];
- void *capabilities = buf;
- int len = sizeof(buf);
- int error;
-
- error = endpoint->get_capabilities(endpoint, capabilities, &len);
- if (error < 0)
- return error;
-
- adapter_path = cras_bt_adapter_object_path(adapter);
-
- method_call = dbus_message_new_method_call(BLUEZ_SERVICE, adapter_path,
- BLUEZ_INTERFACE_MEDIA,
- "RegisterEndpoint");
- if (!method_call)
- return -ENOMEM;
-
- dbus_message_iter_init_append(method_call, &message_iter);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_OBJECT_PATH,
- &endpoint->object_path);
-
- dbus_message_iter_open_container(
- &message_iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &properties_array_iter);
-
- key = "UUID";
- dbus_message_iter_open_container(&properties_array_iter,
- DBUS_TYPE_DICT_ENTRY, NULL,
- &properties_dict_iter);
- dbus_message_iter_append_basic(&properties_dict_iter, DBUS_TYPE_STRING,
- &key);
- dbus_message_iter_open_container(&properties_dict_iter,
- DBUS_TYPE_VARIANT,
- DBUS_TYPE_STRING_AS_STRING,
- &variant_iter);
- dbus_message_iter_append_basic(&variant_iter, DBUS_TYPE_STRING,
- &endpoint->uuid);
- dbus_message_iter_close_container(&properties_dict_iter, &variant_iter);
- dbus_message_iter_close_container(&properties_array_iter,
- &properties_dict_iter);
-
- key = "Codec";
- dbus_message_iter_open_container(&properties_array_iter,
- DBUS_TYPE_DICT_ENTRY, NULL,
- &properties_dict_iter);
- dbus_message_iter_append_basic(&properties_dict_iter, DBUS_TYPE_STRING,
- &key);
- dbus_message_iter_open_container(&properties_dict_iter,
- DBUS_TYPE_VARIANT,
- DBUS_TYPE_BYTE_AS_STRING,
- &variant_iter);
- dbus_message_iter_append_basic(&variant_iter, DBUS_TYPE_BYTE,
- &endpoint->codec);
- dbus_message_iter_close_container(&properties_dict_iter, &variant_iter);
- dbus_message_iter_close_container(&properties_array_iter,
- &properties_dict_iter);
-
- key = "Capabilities";
- dbus_message_iter_open_container(&properties_array_iter,
- DBUS_TYPE_DICT_ENTRY, NULL,
- &properties_dict_iter);
- dbus_message_iter_append_basic(&properties_dict_iter, DBUS_TYPE_STRING,
- &key);
- dbus_message_iter_open_container(
- &properties_dict_iter, DBUS_TYPE_VARIANT,
- DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_BYTE_AS_STRING,
- &variant_iter);
- dbus_message_iter_open_container(&variant_iter, DBUS_TYPE_ARRAY,
- DBUS_TYPE_BYTE_AS_STRING, &bytes_iter);
- dbus_message_iter_append_fixed_array(&bytes_iter, DBUS_TYPE_BYTE,
- &capabilities, len);
- dbus_message_iter_close_container(&variant_iter, &bytes_iter);
- dbus_message_iter_close_container(&properties_dict_iter, &variant_iter);
- dbus_message_iter_close_container(&properties_array_iter,
- &properties_dict_iter);
-
- dbus_message_iter_close_container(&message_iter,
- &properties_array_iter);
-
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(
- pending_call, cras_bt_on_register_endpoint, NULL, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
-
- return 0;
-}
-
-static void cras_bt_on_unregister_endpoint(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_WARNING, "UnregisterEndpoint returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return;
- }
-
- dbus_message_unref(reply);
-}
-
-int cras_bt_unregister_endpoint(DBusConnection *conn,
- const struct cras_bt_adapter *adapter,
- struct cras_bt_endpoint *endpoint)
-{
- const char *adapter_path;
- DBusMessage *method_call;
- DBusPendingCall *pending_call;
-
- adapter_path = cras_bt_adapter_object_path(adapter);
-
- method_call = dbus_message_new_method_call(BLUEZ_SERVICE, adapter_path,
- BLUEZ_INTERFACE_MEDIA,
- "UnregisterEndpoint");
- if (!method_call)
- return -ENOMEM;
-
- if (!dbus_message_append_args(method_call, DBUS_TYPE_OBJECT_PATH,
- &endpoint->object_path,
- DBUS_TYPE_INVALID))
- return -ENOMEM;
-
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(
- pending_call, cras_bt_on_unregister_endpoint, NULL, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
-
- return 0;
-}
-
-/* Available endpoints */
-static struct cras_bt_endpoint *endpoints;
-
-int cras_bt_register_endpoints(DBusConnection *conn,
- const struct cras_bt_adapter *adapter)
-{
- struct cras_bt_endpoint *endpoint;
-
- DL_FOREACH (endpoints, endpoint)
- cras_bt_register_endpoint(conn, adapter, endpoint);
-
- return 0;
-}
-
-int cras_bt_endpoint_add(DBusConnection *conn,
- struct cras_bt_endpoint *endpoint)
-{
- static const DBusObjectPathVTable endpoint_vtable = {
- .message_function = cras_bt_handle_endpoint_message
- };
-
- DBusError dbus_error;
- struct cras_bt_adapter **adapters;
- size_t num_adapters, i;
-
- DL_APPEND(endpoints, endpoint);
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_connection_register_object_path(conn, endpoint->object_path,
- &endpoint_vtable,
- &dbus_error)) {
- syslog(LOG_WARNING,
- "Couldn't register Bluetooth endpoint: %s: %s",
- endpoint->object_path, dbus_error.message);
- dbus_error_free(&dbus_error);
- return -ENOMEM;
- }
-
- num_adapters = cras_bt_adapter_get_list(&adapters);
- for (i = 0; i < num_adapters; ++i)
- cras_bt_register_endpoint(conn, adapters[i], endpoint);
- free(adapters);
-
- return 0;
-}
-
-void cras_bt_endpoint_rm(DBusConnection *conn,
- struct cras_bt_endpoint *endpoint)
-{
- struct cras_bt_adapter **adapters;
- size_t num_adapters, i;
-
- num_adapters = cras_bt_adapter_get_list(&adapters);
- for (i = 0; i < num_adapters; ++i)
- cras_bt_unregister_endpoint(conn, adapters[i], endpoint);
- free(adapters);
-
- dbus_connection_unregister_object_path(conn, endpoint->object_path);
-
- DL_DELETE(endpoints, endpoint);
-}
-
-void cras_bt_endpoint_reset()
-{
- struct cras_bt_endpoint *endpoint;
-
- DL_FOREACH (endpoints, endpoint)
- cras_bt_endpoint_suspend(endpoint);
-}
-
-struct cras_bt_endpoint *cras_bt_endpoint_get(const char *object_path)
-{
- struct cras_bt_endpoint *endpoint;
-
- DL_FOREACH (endpoints, endpoint) {
- if (strcmp(endpoint->object_path, object_path) == 0)
- return endpoint;
- }
-
- return NULL;
-}
diff --git a/cras/src/server/cras_bt_endpoint.h b/cras/src/server/cras_bt_endpoint.h
deleted file mode 100644
index 963071ca..00000000
--- a/cras/src/server/cras_bt_endpoint.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_ENDPOINT_H_
-#define CRAS_BT_ENDPOINT_H_
-
-#include <dbus/dbus.h>
-#include <stdint.h>
-
-#include "cras_bt_adapter.h"
-
-struct cras_bt_transport;
-
-struct cras_bt_endpoint {
- const char *object_path;
- const char *uuid;
- uint8_t codec;
-
- int (*get_capabilities)(struct cras_bt_endpoint *endpoint,
- void *capabilities, int *len);
- int (*select_configuration)(struct cras_bt_endpoint *endpoint,
- void *capabilities, int len,
- void *configuration);
-
- void (*set_configuration)(struct cras_bt_endpoint *endpoint,
- struct cras_bt_transport *transport);
- void (*suspend)(struct cras_bt_endpoint *endpoint,
- struct cras_bt_transport *transport);
-
- void (*transport_state_changed)(struct cras_bt_endpoint *endpoint,
- struct cras_bt_transport *transport);
-
- struct cras_bt_transport *transport;
- struct cras_bt_endpoint *prev, *next;
-};
-
-int cras_bt_register_endpoint(DBusConnection *conn,
- const struct cras_bt_adapter *adapter,
- struct cras_bt_endpoint *endpoint);
-
-int cras_bt_unregister_endpoint(DBusConnection *conn,
- const struct cras_bt_adapter *adapter,
- struct cras_bt_endpoint *endpoint);
-
-int cras_bt_register_endpoints(DBusConnection *conn,
- const struct cras_bt_adapter *adapter);
-
-int cras_bt_endpoint_add(DBusConnection *conn,
- struct cras_bt_endpoint *endpoint);
-void cras_bt_endpoint_rm(DBusConnection *conn,
- struct cras_bt_endpoint *endpoint);
-
-void cras_bt_endpoint_reset();
-
-struct cras_bt_endpoint *cras_bt_endpoint_get(const char *object_path);
-
-#endif /* CRAS_BT_ENDPOINT_H_ */
diff --git a/cras/src/server/cras_bt_io.c b/cras/src/server/cras_bt_io.c
deleted file mode 100644
index acdca809..00000000
--- a/cras/src/server/cras_bt_io.c
+++ /dev/null
@@ -1,721 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <sys/time.h>
-#include <syslog.h>
-
-#include "cras_bt_io.h"
-#include "cras_bt_device.h"
-#include "cras_hfp_iodev.h"
-#include "cras_utf8.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "sfh.h"
-#include "utlist.h"
-
-#define DEFAULT_BT_DEVICE_NAME "BLUETOOTH"
-
-/* Extends cras_ionode to hold bluetooth profile information
- * so that iodevs of different profile(A2DP or HFP/HSP) can be
- * associated with the same bt_io.
- * Members:
- * base - The base class cras_ionode.
- * profile_dev - Pointer to the profile specific iodev.
- * profile - The bluetooth profile profile_dev runs on.
- */
-struct bt_node {
- struct cras_ionode base;
- struct cras_iodev *profile_dev;
- unsigned int profile;
-};
-
-/* The structure represents a virtual input or output device of a
- * bluetooth audio device, speaker or headset for example. A node
- * will be added to this virtual iodev for each profile supported
- * by the bluetooth audio device.
- * Member:
- * base - The base class cras_iodev
- * next_node_id - The index will give to the next node
- */
-struct bt_io {
- struct cras_iodev base;
- unsigned int next_node_id;
- struct cras_bt_device *device;
-};
-
-/* Returns the active profile specific iodev. */
-static struct cras_iodev *active_profile_dev(const struct cras_iodev *iodev)
-{
- struct bt_node *active = (struct bt_node *)iodev->active_node;
-
- return active->profile_dev;
-}
-
-/* Adds a profile specific iodev to btio. */
-static struct cras_ionode *add_profile_dev(struct cras_iodev *bt_iodev,
- struct cras_iodev *dev,
- enum cras_bt_device_profile profile)
-{
- struct bt_node *n;
- struct bt_io *btio = (struct bt_io *)bt_iodev;
-
- n = (struct bt_node *)calloc(1, sizeof(*n));
- if (!n)
- return NULL;
-
- n->base.dev = bt_iodev;
- n->base.idx = btio->next_node_id++;
- n->base.type = CRAS_NODE_TYPE_BLUETOOTH;
- n->base.volume = 100;
- n->base.stable_id = dev->info.stable_id;
- n->base.capture_gain = 0;
- gettimeofday(&n->base.plugged_time, NULL);
-
- strcpy(n->base.name, dev->info.name);
- n->profile_dev = dev;
- n->profile = profile;
-
- cras_iodev_add_node(bt_iodev, &n->base);
- return &n->base;
-}
-
-/* Forces bt device to switch to use the given profile. Note that if
- * it has already been open for streaming, the new active profile will
- * take effect after the related btio(s) are reopened.
- */
-static void bt_switch_to_profile(struct cras_bt_device *device,
- enum cras_bt_device_profile profile)
-{
- switch (profile) {
- case CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY:
- case CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY:
- cras_bt_device_set_active_profile(
- device,
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- break;
- case CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE:
- cras_bt_device_set_active_profile(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
- break;
- default:
- syslog(LOG_ERR, "Unexpect profile %u", profile);
- break;
- }
-}
-
-/* Switches the active profile to A2DP if it can. */
-static void bt_possibly_switch_to_a2dp(struct bt_io *btio)
-{
- if (!cras_bt_device_has_a2dp(btio->device))
- return;
- cras_bt_device_set_active_profile(btio->device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
- cras_bt_device_switch_profile(btio->device, &btio->base);
-}
-
-/* Checks if bt device is active for the given profile.
- */
-static int device_using_profile(struct cras_bt_device *device,
- unsigned int profile)
-{
- return cras_bt_device_get_active_profile(device) & profile;
-}
-
-/* Checks if the condition is met to switch to a different profile based
- * on two rules:
- * (1) Prefer to use A2DP for output since the audio quality is better.
- * (2) Must use HFP/HSP for input since A2DP doesn't support audio input.
- *
- * If the profile switch happens, return non-zero error code, otherwise
- * return zero.
- */
-static int open_dev(struct cras_iodev *iodev)
-{
- struct bt_io *btio = (struct bt_io *)iodev;
- struct cras_iodev *dev = active_profile_dev(iodev);
- int rc;
-
- /* Force to use HFP if opening input dev. */
- if (device_using_profile(btio->device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE) &&
- iodev->direction == CRAS_STREAM_INPUT) {
- bt_switch_to_profile(btio->device,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- cras_bt_device_switch_profile_enable_dev(btio->device, iodev);
- return -EAGAIN;
- }
-
- if (dev && dev->open_dev) {
- rc = dev->open_dev(dev);
- if (rc == 0)
- return 0;
-
- /* If input iodev open fails, switch profile back to A2DP. */
- if (iodev->direction == CRAS_STREAM_INPUT)
- bt_possibly_switch_to_a2dp(btio);
- return rc;
- }
-
- return 0;
-}
-
-static int update_supported_formats(struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- int rc, length, i;
-
- if (!dev)
- return -EINVAL;
-
- if (dev->update_supported_formats) {
- rc = dev->update_supported_formats(dev);
- if (rc)
- return rc;
- }
-
- /* Fill in the supported rates and channel counts. */
- for (length = 0; dev->supported_rates[length]; length++)
- ;
- free(iodev->supported_rates);
- iodev->supported_rates = (size_t *)malloc(
- (length + 1) * sizeof(*iodev->supported_rates));
- for (i = 0; i < length + 1; i++)
- iodev->supported_rates[i] = dev->supported_rates[i];
-
- for (length = 0; dev->supported_channel_counts[length]; length++)
- ;
- iodev->supported_channel_counts = (size_t *)malloc(
- (length + 1) * sizeof(*iodev->supported_channel_counts));
- for (i = 0; i < length + 1; i++)
- iodev->supported_channel_counts[i] =
- dev->supported_channel_counts[i];
-
- for (length = 0; dev->supported_formats[length]; length++)
- ;
-
- iodev->supported_formats = (snd_pcm_format_t *)malloc(
- (length + 1) * sizeof(*iodev->supported_formats));
- for (i = 0; i < length + 1; i++)
- iodev->supported_formats[i] = dev->supported_formats[i];
-
- /* Record max supported channels into cras_iodev_info. */
- iodev->info.max_supported_channels = dev->info.max_supported_channels;
- return 0;
-}
-
-static int configure_dev(struct cras_iodev *iodev)
-{
- int rc;
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
-
- /* Fill back the format iodev is using. */
- if (dev->format == NULL) {
- dev->format = (struct cras_audio_format *)malloc(
- sizeof(*dev->format));
- if (!dev->format)
- return -ENOMEM;
- *dev->format = *iodev->format;
- }
-
- rc = dev->configure_dev(dev);
- if (rc)
- return rc;
-
- iodev->buffer_size = dev->buffer_size;
- iodev->min_buffer_level = dev->min_buffer_level;
- if (dev->start)
- dev->state = CRAS_IODEV_STATE_OPEN;
- else
- dev->state = CRAS_IODEV_STATE_NO_STREAM_RUN;
-
- return 0;
-}
-
-static int close_dev(struct cras_iodev *iodev)
-{
- struct bt_io *btio = (struct bt_io *)iodev;
- int rc;
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
-
- /* If input iodev is in open state and being closed, switch profile
- * from HFP to A2DP. */
- if (cras_iodev_is_open(iodev) &&
- device_using_profile(
- btio->device,
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY) &&
- (iodev->direction == CRAS_STREAM_INPUT))
- bt_possibly_switch_to_a2dp(btio);
-
- rc = dev->close_dev(dev);
- if (rc < 0)
- return rc;
- cras_iodev_free_format(iodev);
- dev->state = CRAS_IODEV_STATE_CLOSE;
- return 0;
-}
-
-static void set_bt_volume(struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return;
-
- if (dev->active_node)
- dev->active_node->volume = iodev->active_node->volume;
-
- /* The parent bt_iodev could set software_volume_needed flag for cases
- * that software volume provides better experience across profiles
- * (HFP and A2DP). Otherwise, use the profile specific implementation
- * to adjust volume. */
- if (dev->set_volume && !iodev->software_volume_needed)
- dev->set_volume(dev);
-}
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
- return dev->frames_queued(dev, tstamp);
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
- return dev->delay_frames(dev);
-}
-
-static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
- unsigned *frames)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
- return dev->get_buffer(dev, area, frames);
-}
-
-static int put_buffer(struct cras_iodev *iodev, unsigned nwritten)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
- return dev->put_buffer(dev, nwritten);
-}
-
-static int flush_buffer(struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
- return dev->flush_buffer(dev);
-}
-
-/* If the first private iodev doesn't match the active profile stored on
- * device, select to the correct private iodev.
- */
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
- struct bt_io *btio = (struct bt_io *)iodev;
- struct cras_ionode *node;
- struct bt_node *active = (struct bt_node *)iodev->active_node;
- struct cras_iodev *dev;
- int rc;
-
- if (device_using_profile(btio->device, active->profile))
- goto leave;
-
- /* Switch to the correct dev using active_profile. */
- DL_FOREACH (iodev->nodes, node) {
- struct bt_node *n = (struct bt_node *)node;
- if (n == active)
- continue;
-
- if (device_using_profile(btio->device, n->profile)) {
- active->profile = n->profile;
- active->profile_dev = n->profile_dev;
-
- /* Set volume for the new profile. */
- set_bt_volume(iodev);
- }
- }
-
-leave:
- dev = active_profile_dev(iodev);
- if (dev && dev->update_active_node)
- dev->update_active_node(dev, node_idx, dev_enabled);
-
- /* Update supported formats here to get the supported formats from the
- * new updated active profile dev.
- */
- rc = update_supported_formats(iodev);
- if (rc) {
- syslog(LOG_ERR, "Failed to update supported formats, rc=%d",
- rc);
- }
-}
-
-static int output_underrun(struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
-
- if (dev->output_underrun) {
- dev->min_cb_level = iodev->min_cb_level;
- dev->max_cb_level = iodev->max_cb_level;
- dev->buffer_size = iodev->buffer_size;
- return dev->output_underrun(dev);
- }
-
- return 0;
-}
-
-static int no_stream(struct cras_iodev *iodev, int enable)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- int rc;
-
- if (!dev)
- return -EINVAL;
-
- if (dev->no_stream) {
- /*
- * Copy iodev->min_cb_level and iodev->max_cb_level from the
- * parent (i.e. bt_io). no_stream() of hfp_alsa_iodev will
- * use them.
- * A2DP and HFP dev will use buffer and callback sizes to fill
- * zeros in no stream state.
- */
- dev->min_cb_level = iodev->min_cb_level;
- dev->max_cb_level = iodev->max_cb_level;
- dev->buffer_size = iodev->buffer_size;
- rc = dev->no_stream(dev, enable);
- if (rc < 0)
- return rc;
- }
- if (enable)
- dev->state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- else
- dev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- return 0;
-}
-
-static int is_free_running(const struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
-
- if (dev->is_free_running)
- return dev->is_free_running(dev);
-
- return 0;
-}
-
-static int start(const struct cras_iodev *iodev)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- int rc;
-
- if (!dev)
- return -EINVAL;
-
- if (dev->start) {
- rc = dev->start(dev);
- if (rc)
- return rc;
- }
- dev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- return 0;
-}
-
-static unsigned int frames_to_play_in_sleep(struct cras_iodev *iodev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev || !dev->frames_to_play_in_sleep)
- return cras_iodev_default_frames_to_play_in_sleep(
- iodev, hw_level, hw_tstamp);
-
- return dev->frames_to_play_in_sleep(dev, hw_level, hw_tstamp);
-}
-
-static int get_valid_frames(struct cras_iodev *iodev,
- struct timespec *hw_tstamp)
-{
- struct cras_iodev *dev = active_profile_dev(iodev);
- if (!dev)
- return -EINVAL;
-
- if (dev->get_valid_frames)
- return dev->get_valid_frames(dev, hw_tstamp);
-
- return cras_iodev_frames_queued(iodev, hw_tstamp);
-}
-
-struct cras_iodev *cras_bt_io_create(struct cras_bt_device *device,
- struct cras_iodev *dev,
- enum cras_bt_device_profile profile)
-{
- int err;
- struct bt_io *btio;
- struct cras_iodev *iodev;
- struct cras_ionode *node;
- struct bt_node *active;
-
- if (!dev)
- return NULL;
-
- btio = (struct bt_io *)calloc(1, sizeof(*btio));
- if (!btio)
- goto error;
- btio->device = device;
-
- iodev = &btio->base;
- iodev->direction = dev->direction;
- strcpy(iodev->info.name, dev->info.name);
- iodev->info.stable_id = dev->info.stable_id;
-
- iodev->open_dev = open_dev;
- iodev->configure_dev = configure_dev;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->flush_buffer = flush_buffer;
- iodev->close_dev = close_dev;
- iodev->update_supported_formats = update_supported_formats;
- iodev->update_active_node = update_active_node;
- iodev->no_stream = no_stream;
- iodev->output_underrun = output_underrun;
- iodev->is_free_running = is_free_running;
- iodev->get_valid_frames = get_valid_frames;
- iodev->start = start;
- iodev->frames_to_play_in_sleep = frames_to_play_in_sleep;
-
- /* Input also checks |software_volume_needed| flag for using software
- * gain. Keep it as false for BT input.
- * TODO(hychao): after wide band speech mode is supported, consider
- * enable software gain.
- */
- if (dev->direction == CRAS_STREAM_OUTPUT) {
- iodev->software_volume_needed =
- !cras_bt_device_get_use_hardware_volume(device);
- iodev->set_volume = set_bt_volume;
- }
-
- /* Create the fake node so it's the only node exposed to UI, and
- * point it to the first profile dev. */
- active = (struct bt_node *)calloc(1, sizeof(*active));
- if (!active)
- goto error;
- active->base.dev = iodev;
- active->base.idx = btio->next_node_id++;
- active->base.type = dev->active_node->type;
- active->base.volume = 100;
- active->base.stable_id = cras_bt_device_get_stable_id(device);
- active->base.ui_gain_scaler = 1.0f;
- /*
- * If the same headset is connected in wideband mode, we shall assign
- * a separate stable_id so the node priority/preference mechanism in
- * Chrome UI doesn't break.
- */
- if ((active->base.type == CRAS_NODE_TYPE_BLUETOOTH) &&
- (dev->direction == CRAS_STREAM_INPUT))
- active->base.stable_id =
- SuperFastHash((const char *)&active->base.type,
- sizeof(active->base.type),
- active->base.stable_id);
- active->profile = profile;
- active->profile_dev = dev;
- strcpy(active->base.name, dev->info.name);
- /* The node name exposed to UI should be a valid UTF8 string. */
- if (!is_utf8_string(active->base.name))
- strcpy(active->base.name, DEFAULT_BT_DEVICE_NAME);
- cras_iodev_add_node(iodev, &active->base);
-
- node = add_profile_dev(&btio->base, dev, profile);
- if (node == NULL)
- goto error;
-
- /* Default active profile to a2dp whenever it's allowed. */
- if (!cras_bt_device_get_active_profile(device) ||
- (profile == CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE &&
- cras_bt_device_can_switch_to_a2dp(device)))
- bt_switch_to_profile(device, profile);
-
- if (iodev->direction == CRAS_STREAM_OUTPUT)
- err = cras_iodev_list_add_output(iodev);
- else
- err = cras_iodev_list_add_input(iodev);
- if (err)
- goto error;
-
- cras_iodev_set_active_node(iodev, &active->base);
- return &btio->base;
-
-error:
- if (btio)
- free(btio);
- return NULL;
-}
-
-void cras_bt_io_free_resources(struct cras_iodev *bt_iodev)
-{
- struct cras_ionode *node;
- struct bt_node *n;
-
- free(bt_iodev->supported_rates);
- free(bt_iodev->supported_channel_counts);
- free(bt_iodev->supported_formats);
-
- DL_FOREACH (bt_iodev->nodes, node) {
- n = (struct bt_node *)node;
- cras_iodev_rm_node(bt_iodev, node);
- free(n);
- }
-
- cras_iodev_free_resources(bt_iodev);
-}
-
-void cras_bt_io_destroy(struct cras_iodev *bt_iodev)
-{
- int rc;
- struct bt_io *btio = (struct bt_io *)bt_iodev;
-
- if (bt_iodev->direction == CRAS_STREAM_OUTPUT)
- rc = cras_iodev_list_rm_output(bt_iodev);
- else
- rc = cras_iodev_list_rm_input(bt_iodev);
- if (rc == -EBUSY)
- return;
-
- cras_bt_io_free_resources(bt_iodev);
- free(btio);
-}
-
-struct cras_ionode *cras_bt_io_get_profile(struct cras_iodev *bt_iodev,
- enum cras_bt_device_profile profile)
-{
- struct cras_ionode *node;
- DL_FOREACH (bt_iodev->nodes, node) {
- struct bt_node *n = (struct bt_node *)node;
- if (n->profile & profile)
- return node;
- }
- return NULL;
-}
-
-int cras_bt_io_append(struct cras_iodev *bt_iodev, struct cras_iodev *dev,
- enum cras_bt_device_profile profile)
-{
- struct cras_ionode *node;
- struct bt_io *btio = (struct bt_io *)bt_iodev;
-
- if (cras_bt_io_get_profile(bt_iodev, profile))
- return -EEXIST;
-
- node = add_profile_dev(bt_iodev, dev, profile);
- if (!node)
- return -ENOMEM;
-
- if (profile == CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE &&
- cras_bt_device_can_switch_to_a2dp(btio->device)) {
- bt_switch_to_profile(btio->device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
- cras_bt_device_switch_profile(btio->device, bt_iodev);
- syslog(LOG_ERR, "Switch to A2DP on append");
- }
- return 0;
-}
-
-int cras_bt_io_on_profile(struct cras_iodev *bt_iodev,
- enum cras_bt_device_profile profile)
-{
- struct bt_node *btnode = (struct bt_node *)bt_iodev->active_node;
- return !!(profile & btnode->profile);
-}
-
-enum cras_bt_device_profile
-cras_bt_io_profile_to_log(struct cras_iodev *bt_iodev)
-{
- struct bt_node *btnode = (struct bt_node *)bt_iodev->active_node;
-
- if (btnode->profile & CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE)
- return CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
-
- if (hfp_iodev_is_hsp(btnode->profile_dev))
- return CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
- else
- return CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
-}
-
-unsigned int cras_bt_io_try_remove(struct cras_iodev *bt_iodev,
- struct cras_iodev *dev)
-{
- struct cras_ionode *node;
- struct bt_node *active, *btnode;
- unsigned int try_profile = 0;
-
- active = (struct bt_node *)bt_iodev->active_node;
-
- if (active->profile_dev == dev) {
- DL_FOREACH (bt_iodev->nodes, node) {
- btnode = (struct bt_node *)node;
- /* Skip the active node and the node we're trying
- * to remove. */
- if (btnode == active || btnode->profile_dev == dev)
- continue;
- try_profile = btnode->profile;
- break;
- }
- } else {
- try_profile = active->profile;
- }
- return try_profile;
-}
-
-int cras_bt_io_remove(struct cras_iodev *bt_iodev, struct cras_iodev *dev)
-{
- struct cras_ionode *node;
- struct bt_node *btnode;
-
- DL_FOREACH (bt_iodev->nodes, node) {
- btnode = (struct bt_node *)node;
- if (btnode->profile_dev != dev)
- continue;
-
- /* If this is the active node, reset it. Otherwise delete
- * this node. */
- if (node == bt_iodev->active_node) {
- btnode->profile_dev = NULL;
- btnode->profile = 0;
- } else {
- DL_DELETE(bt_iodev->nodes, node);
- free(node);
- }
- }
-
- /* The node of active profile could have been removed, update it.
- * Return err when fail to locate the active profile dev. */
- update_active_node(bt_iodev, 0, 1);
- btnode = (struct bt_node *)bt_iodev->active_node;
- if ((btnode->profile == 0) || (btnode->profile_dev == NULL))
- return -EINVAL;
-
- return 0;
-}
diff --git a/cras/src/server/cras_bt_io.h b/cras/src/server/cras_bt_io.h
deleted file mode 100644
index a867afd9..00000000
--- a/cras/src/server/cras_bt_io.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_IODEV_H_
-#define CRAS_BT_IODEV_H_
-
-#include "cras_bt_device.h"
-
-struct cras_iodev;
-
-/* Creates a bluetooth iodev. */
-struct cras_iodev *cras_bt_io_create(struct cras_bt_device *device,
- struct cras_iodev *dev,
- enum cras_bt_device_profile profile);
-
-/* Destroys a bluetooth iodev. */
-void cras_bt_io_destroy(struct cras_iodev *bt_iodev);
-
-/* Looks up for the node of given profile, returns NULL if doesn't exist. */
-struct cras_ionode *cras_bt_io_get_profile(struct cras_iodev *bt_iodev,
- enum cras_bt_device_profile profile);
-
-/* Appends a profile specific iodev to bt_iodev. */
-int cras_bt_io_append(struct cras_iodev *bt_iodev, struct cras_iodev *dev,
- enum cras_bt_device_profile profile);
-
-/* Checks if the active node of bt_io matches a profile. */
-int cras_bt_io_on_profile(struct cras_iodev *bt_iodev,
- enum cras_bt_device_profile profile);
-
-/* Returns A2DP, HFP or HSP that this bt_iodev is running for.
- * Do NOT use this function except for logging.
- */
-enum cras_bt_device_profile
-cras_bt_io_profile_to_log(struct cras_iodev *bt_iodev);
-
-/* Dry-run the profile device removal from bt_iodev.
- * Returns:
- * 0 if the bt_iodev will be empty and should to be destroied
- * after the removal, othersie the value of the next preffered
- * profile to use.
- */
-unsigned int cras_bt_io_try_remove(struct cras_iodev *bt_iodev,
- struct cras_iodev *dev);
-
-/* Removes a profile specific iodev from bt_iodev.
- * Returns:
- * 0 if dev is removed and bt_iodev successfully updated to
- * the new profile, otherwise return negative error code. */
-int cras_bt_io_remove(struct cras_iodev *bt_iodev, struct cras_iodev *dev);
-
-#endif /* CRAS_BT_IODEV_H_ */
diff --git a/cras/src/server/cras_bt_log.h b/cras/src/server/cras_bt_log.h
deleted file mode 100644
index 26c559a3..00000000
--- a/cras/src/server/cras_bt_log.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_LOG_H_
-#define CRAS_BT_LOG_H_
-
-#include <stdint.h>
-
-#include "cras_types.h"
-
-#define CRAS_BT_LOGGING 1
-
-#if (CRAS_BT_LOGGING)
-#define BTLOG(log, event, data1, data2) \
- cras_bt_event_log_data(log, event, data1, data2);
-#else
-#define BTLOG(log, event, data1, data2)
-#endif
-
-extern struct cras_bt_event_log *btlog;
-
-static inline struct cras_bt_event_log *cras_bt_event_log_init()
-{
- struct cras_bt_event_log *log;
- log = (struct cras_bt_event_log *)calloc(
- 1, sizeof(struct cras_bt_event_log));
- log->len = CRAS_BT_EVENT_LOG_SIZE;
-
- return log;
-}
-
-static inline void cras_bt_event_log_deinit(struct cras_bt_event_log *log)
-{
- free(log);
-}
-
-static inline void cras_bt_event_log_data(struct cras_bt_event_log *log,
- enum CRAS_BT_LOG_EVENTS event,
- uint32_t data1, uint32_t data2)
-{
- struct timespec now;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- log->log[log->write_pos].tag_sec =
- (event << 24) | (now.tv_sec & 0x00ffffff);
- log->log[log->write_pos].nsec = now.tv_nsec;
- log->log[log->write_pos].data1 = data1;
- log->log[log->write_pos].data2 = data2;
-
- log->write_pos++;
- log->write_pos %= CRAS_BT_EVENT_LOG_SIZE;
-}
-
-#endif /* CRAS_BT_LOG_H_ */ \ No newline at end of file
diff --git a/cras/src/server/cras_bt_manager.c b/cras/src/server/cras_bt_manager.c
deleted file mode 100644
index a7103406..00000000
--- a/cras/src/server/cras_bt_manager.c
+++ /dev/null
@@ -1,619 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_bt_constants.h"
-#include "cras_bt_manager.h"
-#include "cras_bt_adapter.h"
-#include "cras_bt_device.h"
-#include "cras_bt_endpoint.h"
-#include "cras_bt_log.h"
-#include "cras_bt_player.h"
-#include "cras_bt_profile.h"
-#include "cras_bt_transport.h"
-#include "cras_bt_battery_provider.h"
-#include "utlist.h"
-
-struct cras_bt_event_log *btlog;
-
-static void cras_bt_interface_added(DBusConnection *conn,
- const char *object_path,
- const char *interface_name,
- DBusMessageIter *properties_array_iter)
-{
- if (strcmp(interface_name, BLUEZ_INTERFACE_ADAPTER) == 0) {
- struct cras_bt_adapter *adapter;
-
- adapter = cras_bt_adapter_get(object_path);
- if (adapter) {
- cras_bt_adapter_update_properties(
- adapter, properties_array_iter, NULL);
- } else {
- BTLOG(btlog, BT_ADAPTER_ADDED, 0, 0);
- adapter = cras_bt_adapter_create(conn, object_path);
- if (adapter) {
- cras_bt_adapter_update_properties(
- adapter, properties_array_iter, NULL);
-
- syslog(LOG_INFO, "Bluetooth Adapter: %s added",
- cras_bt_adapter_address(adapter));
- } else {
- syslog(LOG_WARNING,
- "Failed to create Bluetooth Adapter: %s",
- object_path);
- }
- }
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_MEDIA) == 0) {
- struct cras_bt_adapter *adapter;
-
- adapter = cras_bt_adapter_get(object_path);
- if (adapter) {
- cras_bt_register_endpoints(conn, adapter);
- cras_bt_register_player(conn, adapter);
-
- syslog(LOG_INFO,
- "Bluetooth Endpoint and/or Player: %s added",
- cras_bt_adapter_address(adapter));
- } else {
- syslog(LOG_WARNING,
- "Failed to create Bluetooth Endpoint and/or Player: %s",
- object_path);
- }
-
- } else if (strcmp(interface_name, BLUEZ_PROFILE_MGMT_INTERFACE) == 0) {
- cras_bt_register_profiles(conn);
-
- syslog(LOG_INFO, "Bluetooth Profile Manager added");
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_DEVICE) == 0) {
- struct cras_bt_device *device;
-
- device = cras_bt_device_get(object_path);
- if (device) {
- cras_bt_device_update_properties(
- device, properties_array_iter, NULL);
- } else {
- device = cras_bt_device_create(conn, object_path);
- if (device) {
- cras_bt_device_update_properties(
- device, properties_array_iter, NULL);
-
- syslog(LOG_INFO, "Bluetooth Device: %s added",
- cras_bt_device_address(device));
- } else {
- syslog(LOG_WARNING,
- "Failed to create Bluetooth Device: %s",
- object_path);
- }
- }
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_MEDIA_TRANSPORT) ==
- 0) {
- struct cras_bt_transport *transport;
-
- transport = cras_bt_transport_get(object_path);
- if (transport) {
- cras_bt_transport_update_properties(
- transport, properties_array_iter, NULL);
- } else {
- transport = cras_bt_transport_create(conn, object_path);
- if (transport) {
- cras_bt_transport_update_properties(
- transport, properties_array_iter, NULL);
-
- syslog(LOG_INFO,
- "Bluetooth Transport: %s added",
- cras_bt_transport_object_path(
- transport));
- } else {
- syslog(LOG_WARNING,
- "Failed to create Bluetooth Transport: "
- "%s",
- object_path);
- }
- }
- } else if (strcmp(interface_name,
- BLUEZ_INTERFACE_BATTERY_PROVIDER_MANAGER) == 0) {
- struct cras_bt_adapter *adapter;
- int ret;
-
- syslog(LOG_INFO,
- "Bluetooth Battery Provider Manager available");
-
- adapter = cras_bt_adapter_get(object_path);
- if (adapter) {
- syslog(LOG_INFO,
- "Registering Battery Provider for adapter %s",
- cras_bt_adapter_address(adapter));
- ret = cras_bt_register_battery_provider(conn, adapter);
- if (ret != 0) {
- syslog(LOG_ERR,
- "Error registering Battery Provider "
- "for adapter %s: %s",
- cras_bt_adapter_address(adapter),
- strerror(-ret));
- }
- } else {
- syslog(LOG_WARNING,
- "Adapter not available when trying to create "
- "Battery Provider");
- }
- }
-}
-
-static void cras_bt_interface_removed(DBusConnection *conn,
- const char *object_path,
- const char *interface_name)
-{
- if (strcmp(interface_name, BLUEZ_INTERFACE_ADAPTER) == 0) {
- struct cras_bt_adapter *adapter;
-
- BTLOG(btlog, BT_ADAPTER_REMOVED, 0, 0);
- adapter = cras_bt_adapter_get(object_path);
- if (adapter) {
- syslog(LOG_INFO, "Bluetooth Adapter: %s removed",
- cras_bt_adapter_address(adapter));
- cras_bt_adapter_destroy(adapter);
- }
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_DEVICE) == 0) {
- struct cras_bt_device *device;
-
- device = cras_bt_device_get(object_path);
- if (device) {
- syslog(LOG_INFO, "Bluetooth Device: %s removed",
- cras_bt_device_address(device));
- cras_bt_device_remove(device);
- }
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_MEDIA_TRANSPORT) ==
- 0) {
- struct cras_bt_transport *transport;
-
- transport = cras_bt_transport_get(object_path);
- if (transport) {
- syslog(LOG_INFO, "Bluetooth Transport: %s removed",
- cras_bt_transport_object_path(transport));
- cras_bt_transport_remove(transport);
- }
- } else if (strcmp(interface_name,
- BLUEZ_INTERFACE_BATTERY_PROVIDER_MANAGER) == 0) {
- syslog(LOG_INFO, "Bluetooth Battery Provider Manager removed");
- cras_bt_battery_provider_reset();
- }
-}
-
-static void cras_bt_update_properties(DBusConnection *conn,
- const char *object_path,
- const char *interface_name,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter)
-{
- if (strcmp(interface_name, BLUEZ_INTERFACE_ADAPTER) == 0) {
- struct cras_bt_adapter *adapter;
-
- adapter = cras_bt_adapter_get(object_path);
- if (adapter) {
- cras_bt_adapter_update_properties(
- adapter, properties_array_iter,
- invalidated_array_iter);
- }
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_DEVICE) == 0) {
- struct cras_bt_device *device;
-
- device = cras_bt_device_get(object_path);
- if (device) {
- cras_bt_device_update_properties(
- device, properties_array_iter,
- invalidated_array_iter);
- }
-
- } else if (strcmp(interface_name, BLUEZ_INTERFACE_MEDIA_TRANSPORT) ==
- 0) {
- struct cras_bt_transport *transport;
-
- transport = cras_bt_transport_get(object_path);
- if (transport) {
- cras_bt_transport_update_properties(
- transport, properties_array_iter,
- invalidated_array_iter);
- }
- }
-}
-
-/* Destroys all bt related stuff. The reset functions must be called in
- * reverse order of the adapter -> device -> profile(s) hierarchy.
- */
-static void cras_bt_reset()
-{
- BTLOG(btlog, BT_RESET, 0, 0);
- cras_bt_endpoint_reset();
- cras_bt_transport_reset();
- cras_bt_profile_reset();
- cras_bt_device_reset();
- cras_bt_adapter_reset();
-}
-
-static void cras_bt_on_get_managed_objects(DBusPendingCall *pending_call,
- void *data)
-{
- DBusConnection *conn = (DBusConnection *)data;
- DBusMessage *reply;
- DBusMessageIter message_iter, object_array_iter;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_WARNING, "GetManagedObjects returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return;
- }
-
- if (!dbus_message_has_signature(reply, "a{oa{sa{sv}}}")) {
- syslog(LOG_WARNING, "Bad GetManagedObjects reply received");
- dbus_message_unref(reply);
- return;
- }
-
- dbus_message_iter_init(reply, &message_iter);
- dbus_message_iter_recurse(&message_iter, &object_array_iter);
-
- while (dbus_message_iter_get_arg_type(&object_array_iter) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter object_dict_iter, interface_array_iter;
- const char *object_path;
-
- dbus_message_iter_recurse(&object_array_iter,
- &object_dict_iter);
-
- dbus_message_iter_get_basic(&object_dict_iter, &object_path);
- dbus_message_iter_next(&object_dict_iter);
-
- dbus_message_iter_recurse(&object_dict_iter,
- &interface_array_iter);
-
- while (dbus_message_iter_get_arg_type(&interface_array_iter) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter interface_dict_iter;
- DBusMessageIter properties_array_iter;
- const char *interface_name;
-
- dbus_message_iter_recurse(&interface_array_iter,
- &interface_dict_iter);
-
- dbus_message_iter_get_basic(&interface_dict_iter,
- &interface_name);
- dbus_message_iter_next(&interface_dict_iter);
-
- dbus_message_iter_recurse(&interface_dict_iter,
- &properties_array_iter);
-
- cras_bt_interface_added(conn, object_path,
- interface_name,
- &properties_array_iter);
-
- dbus_message_iter_next(&interface_array_iter);
- }
-
- dbus_message_iter_next(&object_array_iter);
- }
-
- dbus_message_unref(reply);
-}
-
-static int cras_bt_get_managed_objects(DBusConnection *conn)
-{
- DBusMessage *method_call;
- DBusPendingCall *pending_call;
-
- method_call =
- dbus_message_new_method_call(BLUEZ_SERVICE, "/",
- DBUS_INTERFACE_OBJECT_MANAGER,
- "GetManagedObjects");
- if (!method_call)
- return -ENOMEM;
-
- pending_call = NULL;
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(
- pending_call, cras_bt_on_get_managed_objects, conn, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
-
- return 0;
-}
-
-static DBusHandlerResult cras_bt_handle_name_owner_changed(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusError dbus_error;
- const char *service_name, *old_owner, *new_owner;
-
- if (!dbus_message_is_signal(message, DBUS_INTERFACE_DBUS,
- "NameOwnerChanged"))
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- dbus_error_init(&dbus_error);
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_STRING,
- &service_name, DBUS_TYPE_STRING, &old_owner,
- DBUS_TYPE_STRING, &new_owner,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad NameOwnerChanged signal received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- syslog(LOG_INFO, "Bluetooth daemon disconnected from the bus.");
- cras_bt_reset();
-
- if (strlen(new_owner) > 0)
- cras_bt_get_managed_objects(conn);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult cras_bt_handle_interfaces_added(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessageIter message_iter, interface_array_iter;
- const char *object_path;
-
- if (!dbus_message_is_signal(message, DBUS_INTERFACE_OBJECT_MANAGER,
- "InterfacesAdded"))
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- if (!dbus_message_has_signature(message, "oa{sa{sv}}")) {
- syslog(LOG_WARNING, "Bad InterfacesAdded signal received");
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- dbus_message_iter_init(message, &message_iter);
-
- dbus_message_iter_get_basic(&message_iter, &object_path);
- dbus_message_iter_next(&message_iter);
-
- dbus_message_iter_recurse(&message_iter, &interface_array_iter);
-
- while (dbus_message_iter_get_arg_type(&interface_array_iter) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter interface_dict_iter, properties_array_iter;
- const char *interface_name;
-
- dbus_message_iter_recurse(&interface_array_iter,
- &interface_dict_iter);
-
- dbus_message_iter_get_basic(&interface_dict_iter,
- &interface_name);
- dbus_message_iter_next(&interface_dict_iter);
-
- dbus_message_iter_recurse(&interface_dict_iter,
- &properties_array_iter);
-
- cras_bt_interface_added(conn, object_path, interface_name,
- &properties_array_iter);
-
- dbus_message_iter_next(&interface_array_iter);
- }
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult cras_bt_handle_interfaces_removed(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessageIter message_iter, interface_array_iter;
- const char *object_path;
-
- if (!dbus_message_is_signal(message, DBUS_INTERFACE_OBJECT_MANAGER,
- "InterfacesRemoved"))
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- if (!dbus_message_has_signature(message, "oas")) {
- syslog(LOG_WARNING, "Bad InterfacesRemoved signal received");
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- dbus_message_iter_init(message, &message_iter);
-
- dbus_message_iter_get_basic(&message_iter, &object_path);
- dbus_message_iter_next(&message_iter);
-
- dbus_message_iter_recurse(&message_iter, &interface_array_iter);
-
- while (dbus_message_iter_get_arg_type(&interface_array_iter) !=
- DBUS_TYPE_INVALID) {
- const char *interface_name;
-
- dbus_message_iter_get_basic(&interface_array_iter,
- &interface_name);
-
- cras_bt_interface_removed(conn, object_path, interface_name);
-
- dbus_message_iter_next(&interface_array_iter);
- }
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult cras_bt_handle_properties_changed(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessageIter message_iter, properties_array_iter;
- DBusMessageIter invalidated_array_iter;
- const char *object_path, *interface_name;
-
- if (!dbus_message_is_signal(message, DBUS_INTERFACE_PROPERTIES,
- "PropertiesChanged"))
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- if (!dbus_message_has_signature(message, "sa{sv}as")) {
- syslog(LOG_WARNING, "Bad PropertiesChanged signal received");
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- object_path = dbus_message_get_path(message);
-
- dbus_message_iter_init(message, &message_iter);
-
- dbus_message_iter_get_basic(&message_iter, &interface_name);
- dbus_message_iter_next(&message_iter);
-
- dbus_message_iter_recurse(&message_iter, &properties_array_iter);
- dbus_message_iter_next(&message_iter);
-
- dbus_message_iter_recurse(&message_iter, &invalidated_array_iter);
-
- cras_bt_update_properties(conn, object_path, interface_name,
- &properties_array_iter,
- &invalidated_array_iter);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-void cras_bt_start(DBusConnection *conn)
-{
- DBusError dbus_error;
-
- btlog = cras_bt_event_log_init();
-
- dbus_error_init(&dbus_error);
-
- /* Inform the bus daemon which signals we wish to receive. */
- dbus_bus_add_match(conn,
- "type='signal',"
- "sender='" DBUS_SERVICE_DBUS "',"
- "interface='" DBUS_INTERFACE_DBUS "',"
- "member='NameOwnerChanged',"
- "arg0='" BLUEZ_SERVICE "'",
- &dbus_error);
- if (dbus_error_is_set(&dbus_error))
- goto add_match_error;
-
- dbus_bus_add_match(conn,
- "type='signal',"
- "sender='" BLUEZ_SERVICE "',"
- "interface='" DBUS_INTERFACE_OBJECT_MANAGER "',"
- "member='InterfacesAdded'",
- &dbus_error);
- if (dbus_error_is_set(&dbus_error))
- goto add_match_error;
-
- dbus_bus_add_match(conn,
- "type='signal',"
- "sender='" BLUEZ_SERVICE "',"
- "interface='" DBUS_INTERFACE_OBJECT_MANAGER "',"
- "member='InterfacesRemoved'",
- &dbus_error);
- if (dbus_error_is_set(&dbus_error))
- goto add_match_error;
-
- dbus_bus_add_match(conn,
- "type='signal',"
- "sender='" BLUEZ_SERVICE "',"
- "interface='" DBUS_INTERFACE_PROPERTIES "',"
- "member='PropertiesChanged'",
- &dbus_error);
- if (dbus_error_is_set(&dbus_error))
- goto add_match_error;
-
- /* Install filter functions to handle the signals we receive. */
- if (!dbus_connection_add_filter(conn, cras_bt_handle_name_owner_changed,
- NULL, NULL))
- goto add_filter_error;
-
- if (!dbus_connection_add_filter(conn, cras_bt_handle_interfaces_added,
- NULL, NULL))
- goto add_filter_error;
-
- if (!dbus_connection_add_filter(conn, cras_bt_handle_interfaces_removed,
- NULL, NULL))
- goto add_filter_error;
-
- if (!dbus_connection_add_filter(conn, cras_bt_handle_properties_changed,
- NULL, NULL))
- goto add_filter_error;
-
- cras_bt_get_managed_objects(conn);
- return;
-
-add_match_error:
- syslog(LOG_WARNING, "Couldn't setup Bluetooth device monitoring: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- cras_bt_stop(conn);
- return;
-
-add_filter_error:
- syslog(LOG_WARNING, "Couldn't setup Bluetooth device monitoring: %s",
- strerror(ENOMEM));
- cras_bt_stop(conn);
- return;
-}
-
-void cras_bt_stop(DBusConnection *conn)
-{
- cras_bt_reset();
-
- dbus_bus_remove_match(conn,
- "type='signal',"
- "sender='" DBUS_SERVICE_DBUS "',"
- "interface='" DBUS_INTERFACE_DBUS "',"
- "member='NameOwnerChanged',"
- "arg0='" BLUEZ_SERVICE "'",
- NULL);
- dbus_bus_remove_match(conn,
- "type='signal',"
- "sender='" BLUEZ_SERVICE "',"
- "interface='" DBUS_INTERFACE_OBJECT_MANAGER "',"
- "member='InterfacesAdded'",
- NULL);
- dbus_bus_remove_match(conn,
- "type='signal',"
- "sender='" BLUEZ_SERVICE "',"
- "interface='" DBUS_INTERFACE_OBJECT_MANAGER "',"
- "member='InterfacesRemoved'",
- NULL);
- dbus_bus_remove_match(conn,
- "type='signal',"
- "sender='" BLUEZ_SERVICE "',"
- "interface='" DBUS_INTERFACE_PROPERTIES "',"
- "member='PropertiesChanged'",
- NULL);
-
- dbus_connection_remove_filter(conn, cras_bt_handle_name_owner_changed,
- NULL);
- dbus_connection_remove_filter(conn, cras_bt_handle_interfaces_added,
- NULL);
- dbus_connection_remove_filter(conn, cras_bt_handle_interfaces_removed,
- NULL);
- dbus_connection_remove_filter(conn, cras_bt_handle_properties_changed,
- NULL);
-}
diff --git a/cras/src/server/cras_bt_manager.h b/cras/src/server/cras_bt_manager.h
deleted file mode 100644
index 155d8ef0..00000000
--- a/cras/src/server/cras_bt_manager.h
+++ /dev/null
@@ -1,14 +0,0 @@
-/* Copyright (c) 2013 The Chromium Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_MANAGER_H_
-#define CRAS_BT_MANAGER_H_
-
-#include <dbus/dbus.h>
-
-void cras_bt_start(DBusConnection *conn);
-void cras_bt_stop(DBusConnection *conn);
-
-#endif /* CRAS_BT_MANAGER_H_ */
diff --git a/cras/src/server/cras_bt_player.c b/cras/src/server/cras_bt_player.c
deleted file mode 100644
index 446cd916..00000000
--- a/cras/src/server/cras_bt_player.c
+++ /dev/null
@@ -1,486 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_bt_adapter.h"
-#include "cras_bt_constants.h"
-#include "cras_bt_player.h"
-#include "cras_dbus_util.h"
-#include "cras_utf8.h"
-#include "utlist.h"
-
-static void cras_bt_on_player_registered(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR, "RegisterPlayer returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return;
- }
-
- dbus_message_unref(reply);
-}
-
-static int cras_bt_add_player(DBusConnection *conn,
- const struct cras_bt_adapter *adapter,
- struct cras_bt_player *player)
-{
- const char *adapter_path;
- DBusMessage *method_call;
- DBusMessageIter message_iter, dict;
- DBusPendingCall *pending_call;
-
- adapter_path = cras_bt_adapter_object_path(adapter);
- method_call = dbus_message_new_method_call(BLUEZ_SERVICE, adapter_path,
- BLUEZ_INTERFACE_MEDIA,
- "RegisterPlayer");
- if (!method_call)
- return -ENOMEM;
-
- dbus_message_iter_init_append(method_call, &message_iter);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_OBJECT_PATH,
- &player->object_path);
-
- dbus_message_iter_open_container(
- &message_iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &dict);
-
- append_key_value(&dict, "PlaybackStatus", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &player->playback_status);
- append_key_value(&dict, "Identity", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &player->identity);
- append_key_value(&dict, "LoopStatus", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &player->loop_status);
- append_key_value(&dict, "Position", DBUS_TYPE_INT64,
- DBUS_TYPE_INT64_AS_STRING, &player->position);
- append_key_value(&dict, "Shuffle", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &player->shuffle);
- append_key_value(&dict, "CanGoNext", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &player->can_go_next);
- append_key_value(&dict, "CanGoPrevious", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &player->can_go_prev);
- append_key_value(&dict, "CanPlay", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &player->can_play);
- append_key_value(&dict, "CanPause", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &player->can_pause);
- append_key_value(&dict, "CanControl", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &player->can_control);
-
- dbus_message_iter_close_container(&message_iter, &dict);
-
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(
- pending_call, cras_bt_on_player_registered, player, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
- return 0;
-}
-
-/* Note that player properties will be used mostly for AVRCP qualification and
- * not for normal use cases. The corresponding media events won't be routed by
- * CRAS until we have a plan to provide general system API to handle media
- * control.
- */
-static struct cras_bt_player player = {
- .object_path = CRAS_DEFAULT_PLAYER,
- .playback_status = NULL,
- .identity = NULL,
- .loop_status = "None",
- .shuffle = 0,
- .metadata = NULL,
- .position = 0,
- .can_go_next = 0,
- .can_go_prev = 0,
- .can_play = 0,
- .can_pause = 0,
- .can_control = 0,
- .message_cb = NULL,
-};
-
-static DBusHandlerResult cras_bt_player_handle_message(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- const char *msg = dbus_message_get_member(message);
-
- if (player.message_cb)
- player.message_cb(msg);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static struct cras_bt_player_metadata *cras_bt_player_metadata_init()
-{
- struct cras_bt_player_metadata *metadata =
- malloc(sizeof(struct cras_bt_player_metadata));
- metadata->title = calloc(1, CRAS_PLAYER_METADATA_SIZE_MAX);
- metadata->album = calloc(1, CRAS_PLAYER_METADATA_SIZE_MAX);
- metadata->artist = calloc(1, CRAS_PLAYER_METADATA_SIZE_MAX);
- metadata->length = 0;
-
- return metadata;
-}
-
-static void cras_bt_player_init()
-{
- player.playback_status = malloc(CRAS_PLAYER_PLAYBACK_STATUS_SIZE_MAX);
- player.identity = malloc(CRAS_PLAYER_IDENTITY_SIZE_MAX);
-
- strcpy(player.playback_status, CRAS_PLAYER_PLAYBACK_STATUS_DEFAULT);
- strcpy(player.identity, CRAS_PLAYER_IDENTITY_DEFAULT);
- player.position = 0;
-
- player.metadata = cras_bt_player_metadata_init();
-}
-
-static void cras_bt_player_append_metadata_artist(DBusMessageIter *iter,
- const char *artist)
-{
- DBusMessageIter dict, varient, array;
- const char *artist_key = "xesam:artist";
-
- dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL,
- &dict);
- dbus_message_iter_append_basic(&dict, DBUS_TYPE_STRING, &artist_key);
- dbus_message_iter_open_container(
- &dict, DBUS_TYPE_VARIANT,
- DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_STRING_AS_STRING, &varient);
- dbus_message_iter_open_container(&varient, DBUS_TYPE_ARRAY,
- DBUS_TYPE_STRING_AS_STRING, &array);
- dbus_message_iter_append_basic(&array, DBUS_TYPE_STRING, &artist);
- dbus_message_iter_close_container(&varient, &array);
- dbus_message_iter_close_container(&dict, &varient);
- dbus_message_iter_close_container(iter, &dict);
-}
-
-static void cras_bt_player_append_metadata(DBusMessageIter *iter,
- const char *title,
- const char *artist,
- const char *album,
- dbus_int64_t length)
-{
- DBusMessageIter varient, array;
- dbus_message_iter_open_container(
- iter, DBUS_TYPE_VARIANT,
- DBUS_TYPE_ARRAY_AS_STRING DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
- DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &varient);
- dbus_message_iter_open_container(
- &varient, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &array);
- if (!is_utf8_string(title)) {
- syslog(LOG_INFO, "Non-utf8 title: %s", title);
- title = "";
- }
- if (!is_utf8_string(album)) {
- syslog(LOG_INFO, "Non-utf8 album: %s", album);
- album = "";
- }
- if (!is_utf8_string(artist)) {
- syslog(LOG_INFO, "Non-utf8 artist: %s", artist);
- artist = "";
- }
-
- append_key_value(&array, "xesam:title", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &title);
- append_key_value(&array, "xesam:album", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &album);
- append_key_value(&array, "mpris:length", DBUS_TYPE_INT64,
- DBUS_TYPE_INT64_AS_STRING, &length);
- cras_bt_player_append_metadata_artist(&array, artist);
-
- dbus_message_iter_close_container(&varient, &array);
- dbus_message_iter_close_container(iter, &varient);
-}
-
-static bool cras_bt_player_parse_metadata(const char *title, const char *album,
- const char *artist,
- const dbus_int64_t length)
-{
- bool require_update = false;
-
- if (title && strcmp(player.metadata->title, title)) {
- snprintf(player.metadata->title, CRAS_PLAYER_METADATA_SIZE_MAX,
- "%s", title);
- require_update = true;
- }
- if (artist && strcmp(player.metadata->artist, artist)) {
- snprintf(player.metadata->artist, CRAS_PLAYER_METADATA_SIZE_MAX,
- "%s", artist);
- require_update = true;
- }
- if (album && strcmp(player.metadata->album, album)) {
- snprintf(player.metadata->album, CRAS_PLAYER_METADATA_SIZE_MAX,
- "%s", album);
- require_update = true;
- }
- if (length && player.metadata->length != length) {
- player.metadata->length = length;
- require_update = true;
- }
-
- return require_update;
-}
-
-int cras_bt_player_create(DBusConnection *conn)
-{
- static const DBusObjectPathVTable player_vtable = {
- .message_function = cras_bt_player_handle_message
- };
-
- DBusError dbus_error;
- struct cras_bt_adapter **adapters;
- size_t num_adapters, i;
-
- dbus_error_init(&dbus_error);
-
- cras_bt_player_init();
- if (!dbus_connection_register_object_path(
- conn, player.object_path, &player_vtable, &dbus_error)) {
- syslog(LOG_ERR, "Cannot register player %s",
- player.object_path);
- dbus_error_free(&dbus_error);
- return -ENOMEM;
- }
-
- num_adapters = cras_bt_adapter_get_list(&adapters);
- for (i = 0; i < num_adapters; ++i)
- cras_bt_add_player(conn, adapters[i], &player);
- free(adapters);
- return 0;
-}
-
-int cras_bt_register_player(DBusConnection *conn,
- const struct cras_bt_adapter *adapter)
-{
- return cras_bt_add_player(conn, adapter, &player);
-}
-
-int cras_bt_player_update_playback_status(DBusConnection *conn,
- const char *status)
-{
- DBusMessage *msg;
- DBusMessageIter iter, dict;
- const char *playerInterface = BLUEZ_INTERFACE_MEDIA_PLAYER;
-
- if (!player.playback_status)
- return -ENXIO;
-
- /* Verify the string value matches one of the possible status defined in
- * bluez/profiles/audio/avrcp.c
- */
- if (strcasecmp(status, "stopped") != 0 &&
- strcasecmp(status, "playing") != 0 &&
- strcasecmp(status, "paused") != 0 &&
- strcasecmp(status, "forward-seek") != 0 &&
- strcasecmp(status, "reverse-seek") != 0 &&
- strcasecmp(status, "error") != 0)
- return -EINVAL;
-
- if (!strcasecmp(player.playback_status, status))
- return 0;
-
- strcpy(player.playback_status, status);
-
- msg = dbus_message_new_signal(CRAS_DEFAULT_PLAYER,
- DBUS_INTERFACE_PROPERTIES,
- "PropertiesChanged");
- if (!msg)
- return -ENOMEM;
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
- &playerInterface);
- dbus_message_iter_open_container(
- &iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &dict);
- append_key_value(&dict, "PlaybackStatus", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &status);
- dbus_message_iter_close_container(&iter, &dict);
-
- if (!dbus_connection_send(conn, msg, NULL)) {
- dbus_message_unref(msg);
- return -ENOMEM;
- }
-
- dbus_message_unref(msg);
- return 0;
-}
-
-int cras_bt_player_update_identity(DBusConnection *conn, const char *identity)
-{
- DBusMessage *msg;
- DBusMessageIter iter, dict;
- const char *playerInterface = BLUEZ_INTERFACE_MEDIA_PLAYER;
-
- if (!player.identity)
- return -ENXIO;
-
- if (!identity)
- return -EINVAL;
-
- if (!is_utf8_string(identity)) {
- syslog(LOG_INFO, "Non-utf8 identity: %s", identity);
- identity = "";
- }
-
- if (!strcasecmp(player.identity, identity))
- return 0;
-
- strcpy(player.identity, identity);
-
- msg = dbus_message_new_signal(CRAS_DEFAULT_PLAYER,
- DBUS_INTERFACE_PROPERTIES,
- "PropertiesChanged");
- if (!msg)
- return -ENOMEM;
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
- &playerInterface);
- dbus_message_iter_open_container(
- &iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &dict);
- append_key_value(&dict, "Identity", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &identity);
- dbus_message_iter_close_container(&iter, &dict);
-
- if (!dbus_connection_send(conn, msg, NULL)) {
- dbus_message_unref(msg);
- return -ENOMEM;
- }
-
- dbus_message_unref(msg);
- return 0;
-}
-
-int cras_bt_player_update_position(DBusConnection *conn,
- const dbus_int64_t position)
-{
- DBusMessage *msg;
- DBusMessageIter iter, dict;
- const char *playerInterface = BLUEZ_INTERFACE_MEDIA_PLAYER;
-
- if (position < 0)
- return -EINVAL;
-
- player.position = position;
-
- msg = dbus_message_new_signal(CRAS_DEFAULT_PLAYER,
- DBUS_INTERFACE_PROPERTIES,
- "PropertiesChanged");
- if (!msg)
- return -ENOMEM;
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
- &playerInterface);
- dbus_message_iter_open_container(
- &iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &dict);
- append_key_value(&dict, "Position", DBUS_TYPE_INT64,
- DBUS_TYPE_INT64_AS_STRING, &player.position);
- dbus_message_iter_close_container(&iter, &dict);
-
- if (!dbus_connection_send(conn, msg, NULL)) {
- dbus_message_unref(msg);
- return -ENOMEM;
- }
-
- dbus_message_unref(msg);
- return 0;
-}
-
-int cras_bt_player_update_metadata(DBusConnection *conn, const char *title,
- const char *artist, const char *album,
- const dbus_int64_t length)
-{
- DBusMessage *msg;
- DBusMessageIter iter, array, dict;
- const char *property = "Metadata";
- const char *playerInterface = BLUEZ_INTERFACE_MEDIA_PLAYER;
-
- if (!player.metadata)
- return -ENXIO;
-
- msg = dbus_message_new_signal(CRAS_DEFAULT_PLAYER,
- DBUS_INTERFACE_PROPERTIES,
- "PropertiesChanged");
- if (!msg)
- return -ENOMEM;
-
- dbus_message_iter_init_append(msg, &iter);
- dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING,
- &playerInterface);
- dbus_message_iter_open_container(
- &iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &array);
- dbus_message_iter_open_container(&array, DBUS_TYPE_DICT_ENTRY, NULL,
- &dict);
- dbus_message_iter_append_basic(&dict, DBUS_TYPE_STRING, &property);
-
- if (!cras_bt_player_parse_metadata(title, album, artist, length)) {
- /* Nothing to update. */
- dbus_message_unref(msg);
- return 0;
- }
-
- cras_bt_player_append_metadata(&dict, player.metadata->title,
- player.metadata->artist,
- player.metadata->album,
- player.metadata->length);
-
- dbus_message_iter_close_container(&array, &dict);
- dbus_message_iter_close_container(&iter, &array);
-
- if (!dbus_connection_send(conn, msg, NULL)) {
- dbus_message_unref(msg);
- return -ENOMEM;
- }
-
- dbus_message_unref(msg);
- return 0;
-}
diff --git a/cras/src/server/cras_bt_player.h b/cras/src/server/cras_bt_player.h
deleted file mode 100644
index 25a6c8c5..00000000
--- a/cras/src/server/cras_bt_player.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_PLAYER_H_
-#define CRAS_BT_PLAYER_H_
-
-#include <dbus/dbus.h>
-#include <stdbool.h>
-
-#include "cras_bt_adapter.h"
-
-/* Object to hold current metadata. This is not a full list of what BlueZ/MPRIS
- * supports but a subset because Chromium only provides the following.
- */
-struct cras_bt_player_metadata {
- char *title;
- char *artist;
- char *album;
- int64_t length;
-};
-
-/* Object to register as media player so that bluetoothd will report hardware
- * volume from device through bt_transport. Properties of the player are defined
- * in BlueZ's media API.
- */
-struct cras_bt_player {
- const char *object_path;
- char *playback_status;
- char *identity;
- const char *loop_status;
- struct cras_bt_player_metadata *metadata;
- int64_t position;
- bool can_go_next;
- bool can_go_prev;
- bool can_play;
- bool can_pause;
- bool can_control;
- bool shuffle;
- void (*message_cb)(const char *message);
-};
-
-/* Creates a player object and register it to bluetoothd.
- * Args:
- * conn - The dbus connection.
- */
-int cras_bt_player_create(DBusConnection *conn);
-
-/* Registers created player to bluetoothd. This is used when an bluetooth
- * adapter got enumerated.
- * Args:
- * conn - The dbus connection.
- * adapter - The enumerated bluetooth adapter.
- */
-int cras_bt_register_player(DBusConnection *conn,
- const struct cras_bt_adapter *adapter);
-
-/* Updates playback status for player and notifies bluetoothd
- * Args:
- * conn - The dbus connection.
- * status - The player playback status.
- */
-int cras_bt_player_update_playback_status(DBusConnection *conn,
- const char *status);
-
-/* Updates the player identity and notifies bluetoothd.
- * Args:
- * conn - The dbus connection.
- * identity - The identity of the registered player. This could be the name
- * of the app or the name of the site playing media.
- */
-int cras_bt_player_update_identity(DBusConnection *conn, const char *identity);
-
-/* Updates the player current track's position and notifies bluetoothd.
- * Args:
- * conn - The dbus connection.
- * position - The current track position in microseconds.
- */
-int cras_bt_player_update_position(DBusConnection *conn,
- const dbus_int64_t position);
-
-/* Updates the player current metadata and notifies bluetoothd.
- * Args:
- * conn - The dbus connection.
- * title - The title associated to the current media session.
- * artist - The artist associated to the current media session.
- * album - The album associated to the current media session.
- * length - The duration in microseconds associated to the current media
- * session.
- */
-int cras_bt_player_update_metadata(DBusConnection *conn, const char *title,
- const char *artist, const char *album,
- const dbus_int64_t length);
-#endif /* CRAS_BT_PLAYER_H_ */
diff --git a/cras/src/server/cras_bt_profile.c b/cras/src/server/cras_bt_profile.c
deleted file mode 100644
index 9b4171fa..00000000
--- a/cras/src/server/cras_bt_profile.c
+++ /dev/null
@@ -1,479 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-#include <unistd.h>
-
-#include "cras_bt_constants.h"
-#include "cras_bt_device.h"
-#include "cras_bt_profile.h"
-#include "cras_dbus_util.h"
-#include "utlist.h"
-
-#define PROFILE_INTROSPECT_XML \
- DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
- "<node>\n" \
- " <interface name=\"org.bluez.Profile1\">\n" \
- " <method name=\"Release\">\n" \
- " </method>\n" \
- " <method name=\"NewConnection\">\n" \
- " <arg name=\"device\" type=\"o\" direction=\"in\">\n" \
- " <arg name=\"fd\" type=\"h\" direction=\"in\">\n" \
- " <arg name=\"fd_properties\" type=\"a{sv}\" direction=\"in\">\n" \
- " </method>\n" \
- " <method name=\"RequestDisconnection\">\n" \
- " <arg name=\"device\" type=\"o\" direction=\"in\">\n" \
- " </method>\n" \
- " <method name=\"Cancel\">\n" \
- " </method>\n" \
- " <interface name=\"" DBUS_INTERFACE_INTROSPECTABLE "\">\n" \
- " <method name=\"Introspect\">\n" \
- " <arg name=\"data\" type=\"s\" direction=\"out\"/>\n" \
- " </method>\n" \
- " </interface>\n" \
- "</node>\n"
-
-/* Profiles */
-static struct cras_bt_profile *profiles;
-
-static DBusHandlerResult cras_bt_profile_handle_release(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessage *reply;
- const char *profile_path;
- struct cras_bt_profile *profile;
-
- profile_path = dbus_message_get_path(message);
-
- profile = cras_bt_profile_get(profile_path);
- if (!profile)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- syslog(LOG_ERR, "Profile %s released by bluetoothd", profile->name);
- profile->release(profile);
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL)) {
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- }
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-cras_bt_profile_handle_new_connection(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusMessageIter message_iter;
- DBusMessage *reply;
- const char *profile_path, *object_path;
- int fd = -1;
- int err;
- struct cras_bt_profile *profile;
- struct cras_bt_device *device;
-
- profile_path = dbus_message_get_path(message);
-
- dbus_message_iter_init(message, &message_iter);
- dbus_message_iter_get_basic(&message_iter, &object_path);
- dbus_message_iter_next(&message_iter);
-
- if (dbus_message_iter_get_arg_type(&message_iter) !=
- DBUS_TYPE_UNIX_FD) {
- syslog(LOG_ERR, "Argument not a valid unix file descriptor");
- goto invalid;
- }
-
- dbus_message_iter_get_basic(&message_iter, &fd);
- dbus_message_iter_next(&message_iter);
- if (fd < 0)
- goto invalid;
-
- profile = cras_bt_profile_get(profile_path);
- if (!profile)
- goto invalid;
-
- device = cras_bt_device_get(object_path);
- if (!device) {
- syslog(LOG_ERR, "Device %s not found at %s new connection",
- object_path, profile_path);
- device = cras_bt_device_create(conn, object_path);
- }
-
- err = profile->new_connection(conn, profile, device, fd);
- if (err) {
- syslog(LOG_INFO, "%s new connection rejected", profile->name);
- close(fd);
- reply = dbus_message_new_error(
- message, "org.chromium.Cras.Error.RejectNewConnection",
- "Possibly another headset already in use");
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
- }
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL)) {
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- }
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-
-invalid:
- if (fd >= 0)
- close(fd);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-static DBusHandlerResult
-cras_bt_profile_handle_request_disconnection(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusMessageIter message_iter;
- DBusMessage *reply;
- const char *prpofile_path, *object_path;
- struct cras_bt_profile *profile;
- struct cras_bt_device *device;
-
- prpofile_path = dbus_message_get_path(message);
-
- dbus_message_iter_init(message, &message_iter);
- dbus_message_iter_get_basic(&message_iter, &object_path);
- dbus_message_iter_next(&message_iter);
-
- profile = cras_bt_profile_get(prpofile_path);
- if (!profile)
- goto invalid;
-
- device = cras_bt_device_get(object_path);
- if (!device)
- goto invalid;
-
- profile->request_disconnection(profile, device);
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL)) {
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- }
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-
-invalid:
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-static DBusHandlerResult cras_bt_profile_handle_cancel(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessage *reply;
- const char *profile_path;
- struct cras_bt_profile *profile;
-
- profile_path = dbus_message_get_path(message);
-
- profile = cras_bt_profile_get(profile_path);
- if (!profile)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- profile->cancel(profile);
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL)) {
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- }
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult cras_bt_handle_profile_messages(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- if (dbus_message_is_method_call(message, DBUS_INTERFACE_INTROSPECTABLE,
- "Introspect")) {
- DBusMessage *reply;
- const char *xml = PROFILE_INTROSPECT_XML;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &xml,
- DBUS_TYPE_INVALID)) {
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- }
- if (!dbus_connection_send(conn, reply, NULL)) {
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- }
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
- } else if (dbus_message_is_method_call(message, BLUEZ_INTERFACE_PROFILE,
- "Release")) {
- return cras_bt_profile_handle_release(conn, message, arg);
- } else if (dbus_message_is_method_call(message, BLUEZ_INTERFACE_PROFILE,
- "NewConnection")) {
- return cras_bt_profile_handle_new_connection(conn, message,
- arg);
- } else if (dbus_message_is_method_call(message, BLUEZ_INTERFACE_PROFILE,
- "RequestDisconnection")) {
- return cras_bt_profile_handle_request_disconnection(
- conn, message, arg);
- } else if (dbus_message_is_method_call(message, BLUEZ_INTERFACE_PROFILE,
- "Cancel")) {
- return cras_bt_profile_handle_cancel(conn, message, arg);
- } else {
- syslog(LOG_ERR, "Unknown Profile message");
- }
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static void cras_bt_on_register_profile(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
- syslog(LOG_ERR, "RegisterProfile returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
-}
-
-int cras_bt_register_profile(DBusConnection *conn,
- struct cras_bt_profile *profile)
-{
- DBusMessage *method_call;
- DBusMessageIter message_iter;
- DBusMessageIter properties_array_iter;
- DBusPendingCall *pending_call;
-
- method_call = dbus_message_new_method_call(BLUEZ_SERVICE,
- PROFILE_MANAGER_OBJ_PATH,
- BLUEZ_PROFILE_MGMT_INTERFACE,
- "RegisterProfile");
-
- if (!method_call)
- return -ENOMEM;
-
- dbus_message_iter_init_append(method_call, &message_iter);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_OBJECT_PATH,
- &profile->object_path);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_STRING,
- &profile->uuid);
-
- dbus_message_iter_open_container(
- &message_iter, DBUS_TYPE_ARRAY,
- DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING
- DBUS_TYPE_VARIANT_AS_STRING
- DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
- &properties_array_iter);
-
- if (!append_key_value(&properties_array_iter, "Name", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &profile->name)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- if (profile->record &&
- !append_key_value(&properties_array_iter, "ServiceRecord",
- DBUS_TYPE_STRING, DBUS_TYPE_STRING_AS_STRING,
- &profile->record)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- if (!append_key_value(&properties_array_iter, "Version",
- DBUS_TYPE_UINT16, DBUS_TYPE_UINT16_AS_STRING,
- &profile->version)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- if (profile->role &&
- !append_key_value(&properties_array_iter, "Role", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &profile->role)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- if (profile->features &&
- !append_key_value(&properties_array_iter, "Features",
- DBUS_TYPE_UINT16, DBUS_TYPE_UINT16_AS_STRING,
- &profile->features)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_iter_close_container(&message_iter,
- &properties_array_iter);
-
- if (!dbus_connection_send_with_reply(conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(
- pending_call, cras_bt_on_register_profile, NULL, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- syslog(LOG_ERR, "register profile fail on set notify");
- return -ENOMEM;
- }
-
- return 0;
-}
-
-int cras_bt_unregister_profile(DBusConnection *conn,
- struct cras_bt_profile *profile)
-{
- DBusMessage *method_call;
- DBusMessageIter message_iter;
- DBusError dbus_error;
- DBusMessage *reply;
-
- method_call = dbus_message_new_method_call(BLUEZ_SERVICE,
- PROFILE_MANAGER_OBJ_PATH,
- BLUEZ_PROFILE_MGMT_INTERFACE,
- "UnregisterProfile");
-
- if (!method_call)
- return -ENOMEM;
- dbus_error_init(&dbus_error);
- dbus_message_iter_init_append(method_call, &message_iter);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_OBJECT_PATH,
- &profile->object_path);
- reply = dbus_connection_send_with_reply_and_block(
- conn, method_call, DBUS_TIMEOUT_USE_DEFAULT, &dbus_error);
-
- if (!reply) {
- dbus_error_free(&dbus_error);
- dbus_message_unref(method_call);
- return -EIO;
- }
-
- dbus_message_unref(method_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR, "Unregister profile returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return -EIO;
- }
- dbus_message_unref(reply);
- return 0;
-}
-
-int cras_bt_register_profiles(DBusConnection *conn)
-{
- struct cras_bt_profile *profile;
- int err;
-
- DL_FOREACH (profiles, profile) {
- err = cras_bt_register_profile(conn, profile);
- if (err)
- return err;
- }
-
- return 0;
-}
-
-int cras_bt_add_profile(DBusConnection *conn, struct cras_bt_profile *profile)
-{
- static const DBusObjectPathVTable profile_vtable = {
- NULL, cras_bt_handle_profile_messages, NULL, NULL, NULL, NULL
- };
-
- DBusError dbus_error;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_connection_register_object_path(
- conn, profile->object_path, &profile_vtable, &dbus_error)) {
- syslog(LOG_ERR, "Could not register BT profile %s: %s",
- profile->object_path, dbus_error.message);
- dbus_error_free(&dbus_error);
- return -ENOMEM;
- }
-
- DL_APPEND(profiles, profile);
-
- return 0;
-}
-
-int cras_bt_rm_profile(DBusConnection *conn, struct cras_bt_profile *profile)
-{
- DL_DELETE(profiles, profile);
-
- if (!dbus_connection_unregister_object_path(conn,
- profile->object_path)) {
- syslog(LOG_ERR, "Could not unregister BT profile %s",
- profile->object_path);
- return -ENOMEM;
- }
- return 0;
-}
-
-void cras_bt_profile_reset()
-{
- struct cras_bt_profile *profile;
-
- DL_FOREACH (profiles, profile)
- profile->release(profile);
-}
-
-struct cras_bt_profile *cras_bt_profile_get(const char *path)
-{
- struct cras_bt_profile *profile;
- DL_FOREACH (profiles, profile) {
- if (strcmp(profile->object_path, path) == 0)
- return profile;
- }
-
- return NULL;
-}
-
-void cras_bt_profile_on_device_disconnected(struct cras_bt_device *device)
-{
- struct cras_bt_profile *profile;
- DL_FOREACH (profiles, profile)
- profile->request_disconnection(profile, device);
-}
diff --git a/cras/src/server/cras_bt_profile.h b/cras/src/server/cras_bt_profile.h
deleted file mode 100644
index 4f8ab448..00000000
--- a/cras/src/server/cras_bt_profile.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_PROFILE_H_
-#define CRAS_BT_PROFILE_H_
-
-#include <dbus/dbus.h>
-
-#include "cras_bt_device.h"
-
-#define PROFILE_MANAGER_OBJ_PATH "/org/bluez"
-
-/* Structure in cras to represent an external profile of bluez. All members
- * and functions are documented in bluez/doc/profile-api.txt, more options
- * can be put into this structure when we need it.
- */
-struct cras_bt_profile {
- const char *name;
- const char *object_path;
- const char *uuid;
- const char *role;
- const char *record;
- int version;
- int features;
- void (*release)(struct cras_bt_profile *profile);
- int (*new_connection)(DBusConnection *conn,
- struct cras_bt_profile *profile,
- struct cras_bt_device *device, int rfcomm_fd);
- void (*request_disconnection)(struct cras_bt_profile *profile,
- struct cras_bt_device *device);
- void (*cancel)(struct cras_bt_profile *profile);
- struct cras_bt_profile *prev, *next;
-};
-
-/* Adds the profile to cras and registers it with bluez.
- * Args:
- * conn - The dbus connection.
- * profile - Pointer to the profile structure to be add.
- */
-int cras_bt_add_profile(DBusConnection *conn, struct cras_bt_profile *profile);
-
-/* Removes |profile| from the list of profiles registered with bluez.
- * Args:
- * conn - The dbus connection.
- * profile - Pointer to the profile structure to be removed.
- */
-int cras_bt_rm_profile(DBusConnection *conn, struct cras_bt_profile *profile);
-
-/* Gets the profile by object path.
- * Args:
- * path - The object path of the desired profile.
- *
- * Returns:
- * The profile of the requested object path, or NULL if it
- * does not exist.
- */
-struct cras_bt_profile *cras_bt_profile_get(const char *path);
-
-/* Resets all added profiles. */
-void cras_bt_profile_reset();
-
-/* Notifies all profiles when a device is disconnected. */
-void cras_bt_profile_on_device_disconnected(struct cras_bt_device *device);
-
-/* Registeres |profile| with bluez.
- * Args:
- * conn - The dbus connection.
- * profile - Pointer to the profile structure to be registered.
- */
-int cras_bt_register_profile(DBusConnection *conn,
- struct cras_bt_profile *profile);
-
-/* Unregisteres |profile| with bluez.
- * Args:
- * conn - The dbus connection.
- * profile - Pointer to the profile structure to be unregistered.
- */
-int cras_bt_unregister_profile(DBusConnection *conn,
- struct cras_bt_profile *profile);
-
-/* Registers all added profiles.
- * Args:
- * conn - The dbus connection.
- * Returns:
- * 0 on success, or negative error code on failure.
- */
-int cras_bt_register_profiles(DBusConnection *conn);
-
-#endif /* CRAS_BT_PROFILE_H_ */
diff --git a/cras/src/server/cras_bt_transport.c b/cras/src/server/cras_bt_transport.c
deleted file mode 100644
index 402cd75a..00000000
--- a/cras/src/server/cras_bt_transport.c
+++ /dev/null
@@ -1,634 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-
-#include <errno.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-#include <unistd.h>
-
-#include "cras_bt_device.h"
-#include "cras_bt_endpoint.h"
-#include "cras_bt_log.h"
-#include "cras_bt_transport.h"
-#include "cras_bt_constants.h"
-#include "cras_system_state.h"
-#include "utlist.h"
-
-struct cras_bt_transport {
- DBusConnection *conn;
- char *object_path;
- struct cras_bt_device *device;
- enum cras_bt_device_profile profile;
- int codec;
- void *configuration;
- int configuration_len;
- enum cras_bt_transport_state state;
- int fd;
- uint16_t read_mtu;
- uint16_t write_mtu;
- int volume;
- int removed;
-
- struct cras_bt_endpoint *endpoint;
- struct cras_bt_transport *prev, *next;
-};
-
-static struct cras_bt_transport *transports;
-
-struct cras_bt_transport *cras_bt_transport_create(DBusConnection *conn,
- const char *object_path)
-{
- struct cras_bt_transport *transport;
-
- transport = calloc(1, sizeof(*transport));
- if (transport == NULL)
- return NULL;
-
- transport->object_path = strdup(object_path);
- if (transport->object_path == NULL) {
- free(transport);
- return NULL;
- }
-
- transport->conn = conn;
- dbus_connection_ref(transport->conn);
-
- transport->fd = -1;
- transport->volume = -1;
-
- DL_APPEND(transports, transport);
-
- return transport;
-}
-
-void cras_bt_transport_set_endpoint(struct cras_bt_transport *transport,
- struct cras_bt_endpoint *endpoint)
-{
- transport->endpoint = endpoint;
-}
-
-int cras_bt_transport_is_removed(struct cras_bt_transport *transport)
-{
- return transport->removed;
-}
-
-void cras_bt_transport_remove(struct cras_bt_transport *transport)
-{
- /*
- * If the transport object is still associated with a valid
- * endpoint. Flag it as removed and wait for the ClearConfiguration
- * message from BT to actually suspend this A2DP connection and
- * destroy the transport.
- */
- if (transport->endpoint)
- transport->removed = 1;
- else
- cras_bt_transport_destroy(transport);
-}
-
-void cras_bt_transport_destroy(struct cras_bt_transport *transport)
-{
- DL_DELETE(transports, transport);
-
- dbus_connection_unref(transport->conn);
-
- if (transport->fd >= 0)
- close(transport->fd);
-
- cras_bt_device_set_use_hardware_volume(transport->device, 0);
-
- free(transport->object_path);
- free(transport->configuration);
- free(transport);
-}
-
-void cras_bt_transport_reset()
-{
- while (transports) {
- syslog(LOG_INFO, "Bluetooth Transport: %s removed",
- transports->object_path);
- cras_bt_transport_destroy(transports);
- }
-}
-
-struct cras_bt_transport *cras_bt_transport_get(const char *object_path)
-{
- struct cras_bt_transport *transport;
-
- DL_FOREACH (transports, transport) {
- if (strcmp(transport->object_path, object_path) == 0)
- return transport;
- }
-
- return NULL;
-}
-
-size_t
-cras_bt_transport_get_list(struct cras_bt_transport ***transport_list_out)
-{
- struct cras_bt_transport *transport;
- struct cras_bt_transport **transport_list = NULL;
- size_t num_transports = 0;
-
- DL_FOREACH (transports, transport) {
- struct cras_bt_transport **tmp;
-
- tmp = realloc(transport_list,
- sizeof(transport_list[0]) * (num_transports + 1));
- if (!tmp) {
- free(transport_list);
- return -ENOMEM;
- }
-
- transport_list = tmp;
- transport_list[num_transports++] = transport;
- }
-
- *transport_list_out = transport_list;
- return num_transports;
-}
-
-const char *
-cras_bt_transport_object_path(const struct cras_bt_transport *transport)
-{
- return transport->object_path;
-}
-
-struct cras_bt_device *
-cras_bt_transport_device(const struct cras_bt_transport *transport)
-{
- return transport->device;
-}
-
-enum cras_bt_device_profile
-cras_bt_transport_profile(const struct cras_bt_transport *transport)
-{
- return transport->profile;
-}
-
-int cras_bt_transport_configuration(const struct cras_bt_transport *transport,
- void *configuration, int len)
-{
- if (len < transport->configuration_len)
- return -ENOSPC;
-
- memcpy(configuration, transport->configuration,
- transport->configuration_len);
-
- return 0;
-}
-
-enum cras_bt_transport_state
-cras_bt_transport_state(const struct cras_bt_transport *transport)
-{
- return transport->state;
-}
-
-int cras_bt_transport_fd(const struct cras_bt_transport *transport)
-{
- return transport->fd;
-}
-
-uint16_t cras_bt_transport_write_mtu(const struct cras_bt_transport *transport)
-{
- return transport->write_mtu;
-}
-
-static enum cras_bt_transport_state
-cras_bt_transport_state_from_string(const char *value)
-{
- if (strcmp("idle", value) == 0)
- return CRAS_BT_TRANSPORT_STATE_IDLE;
- else if (strcmp("pending", value) == 0)
- return CRAS_BT_TRANSPORT_STATE_PENDING;
- else if (strcmp("active", value) == 0)
- return CRAS_BT_TRANSPORT_STATE_ACTIVE;
- else
- return CRAS_BT_TRANSPORT_STATE_IDLE;
-}
-
-static void cras_bt_transport_state_changed(struct cras_bt_transport *transport)
-{
- if (transport->endpoint && transport->endpoint->transport_state_changed)
- transport->endpoint->transport_state_changed(
- transport->endpoint, transport);
-}
-
-/* Updates bt_device when certain transport property has changed. */
-static void cras_bt_transport_update_device(struct cras_bt_transport *transport)
-{
- if (!transport->device)
- return;
-
- /* When the transport has non-negaive volume, it means the remote
- * BT audio devices supports AVRCP absolute volume. Set the flag in bt
- * device to use hardware volume. Also map the volume value from 0-127
- * to 0-100.
- */
- if (transport->volume != -1) {
- cras_bt_device_set_use_hardware_volume(transport->device, 1);
- cras_bt_device_update_hardware_volume(
- transport->device, transport->volume * 100 / 127);
- }
-}
-
-void cras_bt_transport_update_properties(struct cras_bt_transport *transport,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter)
-{
- while (dbus_message_iter_get_arg_type(properties_array_iter) !=
- DBUS_TYPE_INVALID) {
- DBusMessageIter properties_dict_iter, variant_iter;
- const char *key;
- int type;
-
- dbus_message_iter_recurse(properties_array_iter,
- &properties_dict_iter);
-
- dbus_message_iter_get_basic(&properties_dict_iter, &key);
- dbus_message_iter_next(&properties_dict_iter);
-
- dbus_message_iter_recurse(&properties_dict_iter, &variant_iter);
- type = dbus_message_iter_get_arg_type(&variant_iter);
-
- if (type == DBUS_TYPE_STRING) {
- const char *value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "UUID") == 0) {
- transport->profile =
- cras_bt_device_profile_from_uuid(value);
-
- } else if (strcmp(key, "State") == 0) {
- enum cras_bt_transport_state old_state =
- transport->state;
- transport->state =
- cras_bt_transport_state_from_string(
- value);
- if (transport->state != old_state)
- cras_bt_transport_state_changed(
- transport);
- }
-
- } else if (type == DBUS_TYPE_BYTE) {
- int value;
-
- dbus_message_iter_get_basic(&variant_iter, &value);
-
- if (strcmp(key, "Codec") == 0)
- transport->codec = value;
- } else if (type == DBUS_TYPE_OBJECT_PATH) {
- const char *obj_path;
-
- if (strcmp(key, "Device") == 0) {
- /* Property: object Device [readonly] */
- dbus_message_iter_get_basic(&variant_iter,
- &obj_path);
- transport->device =
- cras_bt_device_get(obj_path);
- if (!transport->device) {
- syslog(LOG_ERR,
- "Device %s not found at update "
- "transport properties",
- obj_path);
- transport->device =
- cras_bt_device_create(
- transport->conn,
- obj_path);
- cras_bt_transport_update_device(
- transport);
- }
- }
- } else if (strcmp(dbus_message_iter_get_signature(&variant_iter),
- "ay") == 0 &&
- strcmp(key, "Configuration") == 0) {
- DBusMessageIter value_iter;
- char *value;
- int len;
-
- dbus_message_iter_recurse(&variant_iter, &value_iter);
- dbus_message_iter_get_fixed_array(&value_iter, &value,
- &len);
-
- free(transport->configuration);
- transport->configuration_len = 0;
-
- transport->configuration = malloc(len);
- if (transport->configuration) {
- memcpy(transport->configuration, value, len);
- transport->configuration_len = len;
- }
-
- } else if (strcmp(key, "Volume") == 0) {
- uint16_t volume;
-
- dbus_message_iter_get_basic(&variant_iter, &volume);
- transport->volume = volume;
- BTLOG(btlog, BT_TRANSPORT_UPDATE_VOLUME, volume, 0);
- cras_bt_transport_update_device(transport);
- }
-
- dbus_message_iter_next(properties_array_iter);
- }
-
- while (invalidated_array_iter &&
- dbus_message_iter_get_arg_type(invalidated_array_iter) !=
- DBUS_TYPE_INVALID) {
- const char *key;
-
- dbus_message_iter_get_basic(invalidated_array_iter, &key);
-
- if (strcmp(key, "Device") == 0) {
- transport->device = NULL;
- } else if (strcmp(key, "UUID") == 0) {
- transport->profile = 0;
- } else if (strcmp(key, "State") == 0) {
- transport->state = CRAS_BT_TRANSPORT_STATE_IDLE;
- } else if (strcmp(key, "Codec") == 0) {
- transport->codec = 0;
- } else if (strcmp(key, "Configuration") == 0) {
- free(transport->configuration);
- transport->configuration = NULL;
- transport->configuration_len = 0;
- }
-
- dbus_message_iter_next(invalidated_array_iter);
- }
-}
-
-static void on_transport_volume_set(DBusPendingCall *pending_call, void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR)
- syslog(LOG_ERR, "Set absolute volume returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
-}
-
-int cras_bt_transport_set_volume(struct cras_bt_transport *transport,
- uint16_t volume)
-{
- const char *key = "Volume";
- const char *interface = BLUEZ_INTERFACE_MEDIA_TRANSPORT;
- DBusMessage *method_call;
- DBusMessageIter message_iter, variant;
- DBusPendingCall *pending_call;
-
- BTLOG(btlog, BT_TRANSPORT_SET_VOLUME, volume, 0);
- method_call =
- dbus_message_new_method_call(BLUEZ_SERVICE,
- transport->object_path,
- DBUS_INTERFACE_PROPERTIES, "Set");
- if (!method_call)
- return -ENOMEM;
-
- dbus_message_iter_init_append(method_call, &message_iter);
-
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_STRING,
- &interface);
- dbus_message_iter_append_basic(&message_iter, DBUS_TYPE_STRING, &key);
-
- dbus_message_iter_open_container(&message_iter, DBUS_TYPE_VARIANT,
- DBUS_TYPE_UINT16_AS_STRING, &variant);
- dbus_message_iter_append_basic(&variant, DBUS_TYPE_UINT16, &volume);
- dbus_message_iter_close_container(&message_iter, &variant);
-
- if (!dbus_connection_send_with_reply(transport->conn, method_call,
- &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(pending_call, on_transport_volume_set,
- NULL, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
-
- return 0;
-}
-
-int cras_bt_transport_acquire(struct cras_bt_transport *transport)
-{
- DBusMessage *method_call, *reply;
- DBusError dbus_error;
- int rc = 0;
-
- if (transport->fd >= 0)
- return 0;
-
- method_call = dbus_message_new_method_call(
- BLUEZ_SERVICE, transport->object_path,
- BLUEZ_INTERFACE_MEDIA_TRANSPORT, "Acquire");
- if (!method_call)
- return -ENOMEM;
-
- dbus_error_init(&dbus_error);
-
- reply = dbus_connection_send_with_reply_and_block(
- transport->conn, method_call, DBUS_TIMEOUT_USE_DEFAULT,
- &dbus_error);
- if (!reply) {
- syslog(LOG_ERR, "Failed to acquire transport %s: %s",
- transport->object_path, dbus_error.message);
- dbus_error_free(&dbus_error);
- dbus_message_unref(method_call);
- rc = -EIO;
- goto acquire_fail;
- }
-
- dbus_message_unref(method_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR, "Acquire returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- rc = -EIO;
- goto acquire_fail;
- }
-
- if (!dbus_message_get_args(
- reply, &dbus_error, DBUS_TYPE_UNIX_FD, &(transport->fd),
- DBUS_TYPE_UINT16, &(transport->read_mtu), DBUS_TYPE_UINT16,
- &(transport->write_mtu), DBUS_TYPE_INVALID)) {
- syslog(LOG_ERR, "Bad Acquire reply received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- dbus_message_unref(reply);
- rc = -EINVAL;
- goto acquire_fail;
- }
-
- if (cras_system_get_bt_fix_a2dp_packet_size_enabled() &&
- transport->write_mtu > A2DP_FIX_PACKET_SIZE)
- transport->write_mtu = A2DP_FIX_PACKET_SIZE;
-
- BTLOG(btlog, BT_TRANSPORT_ACQUIRE, 1, transport->fd);
- dbus_message_unref(reply);
- return 0;
-
-acquire_fail:
- BTLOG(btlog, BT_TRANSPORT_ACQUIRE, 0, 0);
- return rc;
-}
-
-int cras_bt_transport_try_acquire(struct cras_bt_transport *transport)
-{
- DBusMessage *method_call, *reply;
- DBusError dbus_error;
- int fd, read_mtu, write_mtu;
-
- method_call = dbus_message_new_method_call(
- BLUEZ_SERVICE, transport->object_path,
- BLUEZ_INTERFACE_MEDIA_TRANSPORT, "TryAcquire");
- if (!method_call)
- return -ENOMEM;
-
- dbus_error_init(&dbus_error);
-
- reply = dbus_connection_send_with_reply_and_block(
- transport->conn, method_call, DBUS_TIMEOUT_USE_DEFAULT,
- &dbus_error);
- if (!reply) {
- syslog(LOG_ERR, "Failed to try acquire transport %s: %s",
- transport->object_path, dbus_error.message);
- dbus_error_free(&dbus_error);
- dbus_message_unref(method_call);
- return -EIO;
- }
-
- dbus_message_unref(method_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR, "TryAcquire returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return -EIO;
- }
-
- if (!dbus_message_get_args(reply, &dbus_error, DBUS_TYPE_UNIX_FD, &fd,
- DBUS_TYPE_UINT16, &read_mtu,
- DBUS_TYPE_UINT16, &write_mtu,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_ERR, "Bad TryAcquire reply received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- dbus_message_unref(reply);
- return -EINVAL;
- }
-
- /* Done TryAcquired the transport so it won't be released in bluez,
- * no need for the new file descriptor so close it. */
- if (transport->fd != fd)
- close(fd);
-
- dbus_message_unref(reply);
- return 0;
-}
-
-/* Callback to trigger when transport release completed. */
-static void cras_bt_on_transport_release(DBusPendingCall *pending_call,
- void *data)
-{
- DBusMessage *reply;
-
- reply = dbus_pending_call_steal_reply(pending_call);
- dbus_pending_call_unref(pending_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_WARNING, "Release transport returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return;
- }
-
- dbus_message_unref(reply);
-}
-
-int cras_bt_transport_release(struct cras_bt_transport *transport,
- unsigned int blocking)
-{
- DBusMessage *method_call, *reply;
- DBusPendingCall *pending_call;
- DBusError dbus_error;
-
- if (transport->fd < 0)
- return 0;
-
- BTLOG(btlog, BT_TRANSPORT_RELEASE, transport->fd, 0);
-
- /* Close the transport on our end no matter whether or not the server
- * gives us an error.
- */
- close(transport->fd);
- transport->fd = -1;
-
- method_call = dbus_message_new_method_call(
- BLUEZ_SERVICE, transport->object_path,
- BLUEZ_INTERFACE_MEDIA_TRANSPORT, "Release");
- if (!method_call)
- return -ENOMEM;
-
- if (blocking) {
- dbus_error_init(&dbus_error);
-
- reply = dbus_connection_send_with_reply_and_block(
- transport->conn, method_call, DBUS_TIMEOUT_USE_DEFAULT,
- &dbus_error);
- if (!reply) {
- syslog(LOG_ERR, "Failed to release transport %s: %s",
- transport->object_path, dbus_error.message);
- dbus_error_free(&dbus_error);
- dbus_message_unref(method_call);
- return -EIO;
- }
-
- dbus_message_unref(method_call);
-
- if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
- syslog(LOG_ERR, "Release returned error: %s",
- dbus_message_get_error_name(reply));
- dbus_message_unref(reply);
- return -EIO;
- }
-
- dbus_message_unref(reply);
- } else {
- if (!dbus_connection_send_with_reply(
- transport->conn, method_call, &pending_call,
- DBUS_TIMEOUT_USE_DEFAULT)) {
- dbus_message_unref(method_call);
- return -ENOMEM;
- }
-
- dbus_message_unref(method_call);
- if (!pending_call)
- return -EIO;
-
- if (!dbus_pending_call_set_notify(pending_call,
- cras_bt_on_transport_release,
- transport, NULL)) {
- dbus_pending_call_cancel(pending_call);
- dbus_pending_call_unref(pending_call);
- return -ENOMEM;
- }
- }
- return 0;
-}
diff --git a/cras/src/server/cras_bt_transport.h b/cras/src/server/cras_bt_transport.h
deleted file mode 100644
index 6722fb0a..00000000
--- a/cras/src/server/cras_bt_transport.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_BT_TRANSPORT_H_
-#define CRAS_BT_TRANSPORT_H_
-
-#include <dbus/dbus.h>
-#include <stdint.h>
-
-#include "cras_bt_device.h"
-
-struct cras_bt_endpoint;
-struct cras_bt_transport;
-
-enum cras_bt_transport_state {
- CRAS_BT_TRANSPORT_STATE_IDLE,
- CRAS_BT_TRANSPORT_STATE_PENDING,
- CRAS_BT_TRANSPORT_STATE_ACTIVE
-};
-
-struct cras_bt_transport *cras_bt_transport_create(DBusConnection *conn,
- const char *object_path);
-void cras_bt_transport_set_endpoint(struct cras_bt_transport *transport,
- struct cras_bt_endpoint *endpoint);
-
-/* Handles the event when BT stack notifies specific transport is removed.
- * Args:
- * transport - The transport object representing an A2DP connection.
- */
-void cras_bt_transport_remove(struct cras_bt_transport *transport);
-
-/* Queries the state if BT stack has removed given transport.
- * Args:
- * transport - The transport object representing an A2DP connection.
- */
-int cras_bt_transport_is_removed(struct cras_bt_transport *transport);
-
-void cras_bt_transport_destroy(struct cras_bt_transport *transport);
-void cras_bt_transport_reset();
-
-struct cras_bt_transport *cras_bt_transport_get(const char *object_path);
-size_t
-cras_bt_transport_get_list(struct cras_bt_transport ***transport_list_out);
-
-const char *
-cras_bt_transport_object_path(const struct cras_bt_transport *transport);
-struct cras_bt_device *
-cras_bt_transport_device(const struct cras_bt_transport *transport);
-enum cras_bt_device_profile
-cras_bt_transport_profile(const struct cras_bt_transport *transport);
-int cras_bt_transport_configuration(const struct cras_bt_transport *transport,
- void *configuration, int len);
-enum cras_bt_transport_state
-cras_bt_transport_state(const struct cras_bt_transport *transport);
-
-int cras_bt_transport_fd(const struct cras_bt_transport *transport);
-uint16_t cras_bt_transport_write_mtu(const struct cras_bt_transport *transport);
-
-void cras_bt_transport_update_properties(
- struct cras_bt_transport *transport,
- DBusMessageIter *properties_array_iter,
- DBusMessageIter *invalidated_array_iter);
-
-int cras_bt_transport_try_acquire(struct cras_bt_transport *transport);
-int cras_bt_transport_acquire(struct cras_bt_transport *transport);
-
-/* Releases the cras_bt_transport.
- * Args:
- * transport - The transport object to release
- * blocking - True to send release dbus message in blocking mode, otherwise
- * in non-block mode.
- */
-int cras_bt_transport_release(struct cras_bt_transport *transport,
- unsigned int blocking);
-
-/* Sets the volume to cras_bt_transport. Note that the volume gets applied
- * to BT headset only when the transport is in ACTIVE state.
- * Args:
- * transport - The transport object to set volume to.
- * volume - The desired volume value, range in [0-127].
- */
-int cras_bt_transport_set_volume(struct cras_bt_transport *transport,
- uint16_t volume);
-
-#endif /* CRAS_BT_TRANSPORT_H_ */
diff --git a/cras/src/server/cras_capture_rclient.c b/cras/src/server/cras_capture_rclient.c
deleted file mode 100644
index 9b1f2b84..00000000
--- a/cras/src/server/cras_capture_rclient.c
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_iodev_list.h"
-#include "cras_messages.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_rclient_util.h"
-#include "cras_rstream.h"
-#include "cras_types.h"
-#include "cras_util.h"
-
-/* Declarations of cras_rclient operators for cras_capture_rclient. */
-static const struct cras_rclient_ops cras_capture_rclient_ops = {
- .handle_message_from_client = rclient_handle_message_from_client,
- .send_message_to_client = rclient_send_message_to_client,
- .destroy = rclient_destroy,
-};
-
-/*
- * Exported Functions.
- */
-
-/* Creates a client structure and sends a message back informing the client that
- * the connection has succeeded. */
-struct cras_rclient *cras_capture_rclient_create(int fd, size_t id)
-{
- return rclient_generic_create(
- fd, id, &cras_capture_rclient_ops,
- cras_stream_direction_mask(CRAS_STREAM_INPUT));
-}
diff --git a/cras/src/server/cras_capture_rclient.h b/cras/src/server/cras_capture_rclient.h
deleted file mode 100644
index 129e559c..00000000
--- a/cras/src/server/cras_capture_rclient.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_CAPTURE_RCLIENT_H_
-#define CRAS_CAPTURE_RCLIENT_H_
-
-struct cras_rclient;
-
-/* Creates a capture rclient structure.
- * Args:
- * fd - The file descriptor used for communication with the client.
- * id - Unique identifier for this client.
- * Returns:
- * A pointer to the newly created rclient on success, NULL on failure.
- */
-struct cras_rclient *cras_capture_rclient_create(int fd, size_t id);
-
-#endif /* CRAS_CAPTURE_RCLIENT_H_ */
diff --git a/cras/src/server/cras_control_rclient.c b/cras/src/server/cras_control_rclient.c
deleted file mode 100644
index cd0c4d3b..00000000
--- a/cras/src/server/cras_control_rclient.c
+++ /dev/null
@@ -1,572 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <assert.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include "audio_thread.h"
-#include "audio_thread_log.h"
-#include "cras_apm_list.h"
-#include "cras_bt_log.h"
-#include "cras_config.h"
-#include "cras_control_rclient.h"
-#include "cras_dsp.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_main_thread_log.h"
-#include "cras_messages.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_rclient_util.h"
-#include "cras_rstream.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-/* Handles dumping audio thread debug info back to the client. */
-static void dump_audio_thread_info(struct cras_rclient *client)
-{
- struct cras_client_audio_debug_info_ready msg;
- struct cras_server_state *state;
-
- cras_fill_client_audio_debug_info_ready(&msg);
- state = cras_system_state_get_no_lock();
- audio_thread_dump_thread_info(cras_iodev_list_get_audio_thread(),
- &state->audio_debug_info);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-/* Sends shared memory fd for audio thread event log back to the client. */
-static void get_atlog_fd(struct cras_rclient *client)
-{
- struct cras_client_atlog_fd_ready msg;
- int atlog_fd;
-
- cras_fill_client_atlog_fd_ready(&msg);
- atlog_fd = audio_thread_event_log_shm_fd();
- client->ops->send_message_to_client(client, &msg.header, &atlog_fd, 1);
-}
-
-/* Handles dumping audio snapshots to shared memory for the client. */
-static void dump_audio_thread_snapshots(struct cras_rclient *client)
-{
- struct cras_client_audio_debug_info_ready msg;
-
- cras_fill_client_audio_debug_info_ready(&msg);
- cras_system_state_dump_snapshots();
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void handle_get_hotword_models(struct cras_rclient *client,
- cras_node_id_t node_id)
-{
- struct cras_client_get_hotword_models_ready *msg;
- char *hotword_models;
- unsigned hotword_models_size;
- uint8_t buf[CRAS_CLIENT_MAX_MSG_SIZE];
-
- msg = (struct cras_client_get_hotword_models_ready *)buf;
- hotword_models = cras_iodev_list_get_hotword_models(node_id);
- if (!hotword_models)
- goto empty_reply;
- hotword_models_size = strlen(hotword_models);
- if (hotword_models_size > CRAS_MAX_HOTWORD_MODELS) {
- free(hotword_models);
- goto empty_reply;
- }
-
- cras_fill_client_get_hotword_models_ready(msg, hotword_models,
- hotword_models_size);
- client->ops->send_message_to_client(client, &msg->header, NULL, 0);
- free(hotword_models);
- return;
-
-empty_reply:
- cras_fill_client_get_hotword_models_ready(msg, NULL, 0);
- client->ops->send_message_to_client(client, &msg->header, NULL, 0);
-}
-
-/* Client notification callback functions. */
-
-static void send_output_volume_changed(void *context, int32_t volume)
-{
- struct cras_client_volume_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_output_volume_changed(&msg, volume);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_output_mute_changed(void *context, int muted, int user_muted,
- int mute_locked)
-{
- struct cras_client_mute_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_output_mute_changed(&msg, muted, user_muted,
- mute_locked);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_capture_gain_changed(void *context, int32_t gain)
-{
- struct cras_client_volume_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_capture_gain_changed(&msg, gain);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_capture_mute_changed(void *context, int muted, int mute_locked)
-{
- struct cras_client_mute_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_capture_mute_changed(&msg, muted, mute_locked);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_nodes_changed(void *context)
-{
- struct cras_client_nodes_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_nodes_changed(&msg);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_active_node_changed(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_client_active_node_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_active_node_changed(&msg, dir, node_id);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_output_node_volume_changed(void *context,
- cras_node_id_t node_id,
- int32_t volume)
-{
- struct cras_client_node_value_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_output_node_volume_changed(&msg, node_id, volume);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_node_left_right_swapped_changed(void *context,
- cras_node_id_t node_id,
- int swapped)
-{
- struct cras_client_node_value_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_node_left_right_swapped_changed(&msg, node_id,
- swapped);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_input_node_gain_changed(void *context, cras_node_id_t node_id,
- int32_t gain)
-{
- struct cras_client_node_value_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_input_node_gain_changed(&msg, node_id, gain);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void send_num_active_streams_changed(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams)
-{
- struct cras_client_num_active_streams_changed msg;
- struct cras_rclient *client = (struct cras_rclient *)context;
-
- cras_fill_client_num_active_streams_changed(&msg, dir,
- num_active_streams);
- client->ops->send_message_to_client(client, &msg.header, NULL, 0);
-}
-
-static void register_for_notification(struct cras_rclient *client,
- enum CRAS_CLIENT_MESSAGE_ID msg_id,
- int do_register)
-{
- struct cras_observer_ops observer_ops;
- int empty;
-
- cras_observer_get_ops(client->observer, &observer_ops);
-
- switch (msg_id) {
- case CRAS_CLIENT_OUTPUT_VOLUME_CHANGED:
- observer_ops.output_volume_changed =
- do_register ? send_output_volume_changed : NULL;
- break;
- case CRAS_CLIENT_OUTPUT_MUTE_CHANGED:
- observer_ops.output_mute_changed =
- do_register ? send_output_mute_changed : NULL;
- break;
- case CRAS_CLIENT_CAPTURE_GAIN_CHANGED:
- observer_ops.capture_gain_changed =
- do_register ? send_capture_gain_changed : NULL;
- break;
- case CRAS_CLIENT_CAPTURE_MUTE_CHANGED:
- observer_ops.capture_mute_changed =
- do_register ? send_capture_mute_changed : NULL;
- break;
- case CRAS_CLIENT_NODES_CHANGED:
- observer_ops.nodes_changed =
- do_register ? send_nodes_changed : NULL;
- break;
- case CRAS_CLIENT_ACTIVE_NODE_CHANGED:
- observer_ops.active_node_changed =
- do_register ? send_active_node_changed : NULL;
- break;
- case CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED:
- observer_ops.output_node_volume_changed =
- do_register ? send_output_node_volume_changed : NULL;
- break;
- case CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED:
- observer_ops.node_left_right_swapped_changed =
- do_register ? send_node_left_right_swapped_changed :
- NULL;
- break;
- case CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED:
- observer_ops.input_node_gain_changed =
- do_register ? send_input_node_gain_changed : NULL;
- break;
- case CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED:
- observer_ops.num_active_streams_changed =
- do_register ? send_num_active_streams_changed : NULL;
- break;
- default:
- syslog(LOG_ERR, "Invalid client notification message ID: %u",
- msg_id);
- break;
- }
-
- empty = cras_observer_ops_are_empty(&observer_ops);
- if (client->observer) {
- if (empty) {
- cras_observer_remove(client->observer);
- client->observer = NULL;
- } else {
- cras_observer_set_ops(client->observer, &observer_ops);
- }
- } else if (!empty) {
- client->observer = cras_observer_add(&observer_ops, client);
- }
-}
-
-static int direction_valid(enum CRAS_STREAM_DIRECTION direction)
-{
- return direction < CRAS_NUM_DIRECTIONS &&
- direction != CRAS_STREAM_UNDEFINED;
-}
-
-/* Entry point for handling a message from the client. Called from the main
- * server context.
- *
- * If the message from clients has incorrect length (truncated message), return
- * an error up to CRAS server.
- * If the message from clients has invalid content, should return the errors to
- * clients by send_message_to_client and return 0 here.
- *
- */
-static int ccr_handle_message_from_client(struct cras_rclient *client,
- const struct cras_server_message *msg,
- int *fds, unsigned int num_fds)
-{
- int rc = 0;
- assert(client && msg);
-
- rc = rclient_validate_message_fds(msg, fds, num_fds);
- if (rc < 0) {
- for (int i = 0; i < (int)num_fds; i++)
- if (fds[i] >= 0)
- close(fds[i]);
- return rc;
- }
- int fd = num_fds > 0 ? fds[0] : -1;
-
- switch (msg->id) {
- case CRAS_SERVER_CONNECT_STREAM: {
- int client_shm_fd = num_fds > 1 ? fds[1] : -1;
- if (MSG_LEN_VALID(msg, struct cras_connect_message)) {
- rclient_handle_client_stream_connect(
- client,
- (const struct cras_connect_message *)msg, fd,
- client_shm_fd);
- } else {
- return -EINVAL;
- }
- break;
- }
- case CRAS_SERVER_DISCONNECT_STREAM:
- if (!MSG_LEN_VALID(msg, struct cras_disconnect_stream_message))
- return -EINVAL;
- rclient_handle_client_stream_disconnect(
- client,
- (const struct cras_disconnect_stream_message *)msg);
- break;
- case CRAS_SERVER_SET_SYSTEM_VOLUME:
- if (!MSG_LEN_VALID(msg, struct cras_set_system_volume))
- return -EINVAL;
- cras_system_set_volume(
- ((const struct cras_set_system_volume *)msg)->volume);
- break;
- case CRAS_SERVER_SET_SYSTEM_MUTE:
- if (!MSG_LEN_VALID(msg, struct cras_set_system_mute))
- return -EINVAL;
- cras_system_set_mute(
- ((const struct cras_set_system_mute *)msg)->mute);
- break;
- case CRAS_SERVER_SET_USER_MUTE:
- if (!MSG_LEN_VALID(msg, struct cras_set_system_mute))
- return -EINVAL;
- cras_system_set_user_mute(
- ((const struct cras_set_system_mute *)msg)->mute);
- break;
- case CRAS_SERVER_SET_SYSTEM_MUTE_LOCKED:
- if (!MSG_LEN_VALID(msg, struct cras_set_system_mute))
- return -EINVAL;
- cras_system_set_mute_locked(
- ((const struct cras_set_system_mute *)msg)->mute);
- break;
- case CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE:
- if (!MSG_LEN_VALID(msg, struct cras_set_system_mute))
- return -EINVAL;
- cras_system_set_capture_mute(
- ((const struct cras_set_system_mute *)msg)->mute);
- break;
- case CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE_LOCKED:
- if (!MSG_LEN_VALID(msg, struct cras_set_system_mute))
- return -EINVAL;
- cras_system_set_capture_mute_locked(
- ((const struct cras_set_system_mute *)msg)->mute);
- break;
- case CRAS_SERVER_SET_NODE_ATTR: {
- const struct cras_set_node_attr *m =
- (const struct cras_set_node_attr *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_set_node_attr))
- return -EINVAL;
- cras_iodev_list_set_node_attr(m->node_id, m->attr, m->value);
- break;
- }
- case CRAS_SERVER_SELECT_NODE: {
- const struct cras_select_node *m =
- (const struct cras_select_node *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_select_node) ||
- !direction_valid(m->direction))
- return -EINVAL;
- cras_iodev_list_select_node(m->direction, m->node_id);
- break;
- }
- case CRAS_SERVER_ADD_ACTIVE_NODE: {
- const struct cras_add_active_node *m =
- (const struct cras_add_active_node *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_add_active_node) ||
- !direction_valid(m->direction))
- return -EINVAL;
- cras_iodev_list_add_active_node(m->direction, m->node_id);
- break;
- }
- case CRAS_SERVER_RM_ACTIVE_NODE: {
- const struct cras_rm_active_node *m =
- (const struct cras_rm_active_node *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_rm_active_node) ||
- !direction_valid(m->direction))
- return -EINVAL;
- cras_iodev_list_rm_active_node(m->direction, m->node_id);
- break;
- }
- case CRAS_SERVER_RELOAD_DSP:
- cras_dsp_reload_ini();
- break;
- case CRAS_SERVER_DUMP_DSP_INFO:
- cras_dsp_dump_info();
- break;
- case CRAS_SERVER_DUMP_AUDIO_THREAD:
- dump_audio_thread_info(client);
- break;
- case CRAS_SERVER_GET_ATLOG_FD:
- get_atlog_fd(client);
- break;
- case CRAS_SERVER_DUMP_MAIN: {
- struct cras_client_audio_debug_info_ready msg;
- struct cras_server_state *state;
-
- state = cras_system_state_get_no_lock();
- memcpy(&state->main_thread_debug_info.main_log, main_log,
- sizeof(struct main_thread_event_log));
-
- cras_fill_client_audio_debug_info_ready(&msg);
- client->ops->send_message_to_client(client, &msg.header, NULL,
- 0);
- break;
- }
- case CRAS_SERVER_DUMP_BT: {
- struct cras_client_audio_debug_info_ready msg;
- struct cras_server_state *state;
-
- state = cras_system_state_get_no_lock();
-#ifdef CRAS_DBUS
- memcpy(&state->bt_debug_info.bt_log, btlog,
- sizeof(struct cras_bt_event_log));
- memcpy(&state->bt_debug_info.wbs_logger,
- cras_hfp_ag_get_wbs_logger(),
- sizeof(struct packet_status_logger));
-#else
- memset(&state->bt_debug_info.bt_log, 0,
- sizeof(struct cras_bt_debug_info));
- memset(&state->bt_debug_info.wbs_logger, 0,
- sizeof(struct packet_status_logger));
-#endif
-
- cras_fill_client_audio_debug_info_ready(&msg);
- client->ops->send_message_to_client(client, &msg.header, NULL,
- 0);
- break;
- }
- case CRAS_SERVER_SET_BT_WBS_ENABLED: {
- const struct cras_set_bt_wbs_enabled *m =
- (const struct cras_set_bt_wbs_enabled *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_set_bt_wbs_enabled))
- return -EINVAL;
- cras_system_set_bt_wbs_enabled(m->enabled);
- break;
- }
- case CRAS_SERVER_DUMP_SNAPSHOTS:
- dump_audio_thread_snapshots(client);
- break;
- case CRAS_SERVER_ADD_TEST_DEV: {
- const struct cras_add_test_dev *m =
- (const struct cras_add_test_dev *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_add_test_dev))
- return -EINVAL;
- cras_iodev_list_add_test_dev(m->type);
- break;
- }
- case CRAS_SERVER_TEST_DEV_COMMAND: {
- const struct cras_test_dev_command *m =
- (const struct cras_test_dev_command *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_test_dev_command))
- return -EINVAL;
- cras_iodev_list_test_dev_command(
- m->iodev_idx, (enum CRAS_TEST_IODEV_CMD)m->command,
- m->data_len, m->data);
- break;
- }
- case CRAS_SERVER_SUSPEND:
- cras_system_set_suspended(1);
- break;
- case CRAS_SERVER_RESUME:
- cras_system_set_suspended(0);
- break;
- case CRAS_CONFIG_GLOBAL_REMIX: {
- const struct cras_config_global_remix *m =
- (const struct cras_config_global_remix *)msg;
- float *coefficient;
-
- if (!MSG_LEN_VALID(msg, struct cras_config_global_remix) ||
- m->num_channels > CRAS_MAX_REMIX_CHANNELS)
- return -EINVAL;
- const size_t coefficient_len =
- (size_t)m->num_channels * (size_t)m->num_channels;
- const size_t size_with_coefficients =
- sizeof(*m) +
- coefficient_len * sizeof(m->coefficient[0]);
- if (size_with_coefficients != msg->length)
- return -EINVAL;
-
- coefficient =
- (float *)calloc(coefficient_len, sizeof(coefficient));
- if (!coefficient) {
- syslog(LOG_ERR,
- "Failed to create local coefficient array.");
- break;
- }
- memcpy(coefficient, m->coefficient,
- coefficient_len * sizeof(coefficient));
-
- audio_thread_config_global_remix(
- cras_iodev_list_get_audio_thread(), m->num_channels,
- coefficient);
- free(coefficient);
- break;
- }
- case CRAS_SERVER_GET_HOTWORD_MODELS: {
- if (!MSG_LEN_VALID(msg, struct cras_get_hotword_models))
- return -EINVAL;
- handle_get_hotword_models(
- client,
- ((const struct cras_get_hotword_models *)msg)->node_id);
- break;
- }
- case CRAS_SERVER_SET_HOTWORD_MODEL: {
- const struct cras_set_hotword_model *m =
- (const struct cras_set_hotword_model *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_set_hotword_model))
- return -EINVAL;
- cras_iodev_list_set_hotword_model(m->node_id, m->model_name);
- break;
- }
- case CRAS_SERVER_REGISTER_NOTIFICATION: {
- const struct cras_register_notification *m =
- (struct cras_register_notification *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_register_notification))
- return -EINVAL;
- register_for_notification(
- client, (enum CRAS_CLIENT_MESSAGE_ID)m->msg_id,
- m->do_register);
- break;
- }
- case CRAS_SERVER_SET_AEC_DUMP: {
- const struct cras_set_aec_dump *m =
- (const struct cras_set_aec_dump *)msg;
- if (!MSG_LEN_VALID(msg, struct cras_set_aec_dump))
- return -EINVAL;
- audio_thread_set_aec_dump(cras_iodev_list_get_audio_thread(),
- m->stream_id, m->start, fd);
- break;
- }
- case CRAS_SERVER_RELOAD_AEC_CONFIG:
- cras_apm_list_reload_aec_config();
- break;
- default:
- break;
- }
-
- return 0;
-}
-
-/* Declarations of cras_rclient operators for cras_control_rclient. */
-static const struct cras_rclient_ops cras_control_rclient_ops = {
- .handle_message_from_client = ccr_handle_message_from_client,
- .send_message_to_client = rclient_send_message_to_client,
- .destroy = rclient_destroy,
-};
-
-/*
- * Exported Functions.
- */
-
-/* Creates a client structure and sends a message back informing the client that
- * the conneciton has succeeded. */
-struct cras_rclient *cras_control_rclient_create(int fd, size_t id)
-{
- /* Supports all directions but not CRAS_STREAM_UNDEFINED. */
- int supported_directions =
- CRAS_STREAM_ALL_DIRECTION ^
- cras_stream_direction_mask(CRAS_STREAM_UNDEFINED);
-
- return rclient_generic_create(fd, id, &cras_control_rclient_ops,
- supported_directions);
-}
diff --git a/cras/src/server/cras_control_rclient.h b/cras/src/server/cras_control_rclient.h
deleted file mode 100644
index d654df54..00000000
--- a/cras/src/server/cras_control_rclient.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_CONTROL_RCLIENT_H_
-#define CRAS_CONTROL_RCLIENT_H_
-
-struct cras_rclient;
-
-/* Creates a control rclient structure.
- * Args:
- * fd - The file descriptor used for communication with the client.
- * id - Unique identifier for this client.
- * Returns:
- * A pointer to the newly created rclient on success, NULL on failure.
- */
-struct cras_rclient *cras_control_rclient_create(int fd, size_t id);
-
-#endif /* CRAS_CONTROL_RCLIENT_H_ */
diff --git a/cras/src/server/cras_dbus.c b/cras/src/server/cras_dbus.c
deleted file mode 100644
index 5975f1c6..00000000
--- a/cras/src/server/cras_dbus.c
+++ /dev/null
@@ -1,184 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <poll.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <syslog.h>
-#include <sys/select.h>
-#include <unistd.h>
-
-#include "cras_system_state.h"
-#include "cras_tm.h"
-
-static void dbus_watch_callback(void *arg, int revents)
-{
- DBusWatch *watch = (DBusWatch *)arg;
- int r, flags;
- struct pollfd pollfd;
-
- pollfd.fd = dbus_watch_get_unix_fd(watch);
- pollfd.events = POLLIN | POLLOUT;
-
- r = poll(&pollfd, 1, 0);
- if (r <= 0)
- return;
-
- flags = 0;
- if (pollfd.revents & POLLIN)
- flags |= DBUS_WATCH_READABLE;
- if (pollfd.revents & POLLOUT)
- flags |= DBUS_WATCH_WRITABLE;
-
- if (!dbus_watch_handle(watch, flags))
- syslog(LOG_WARNING, "Failed to handle D-Bus watch.");
-}
-
-static dbus_bool_t dbus_watch_add(DBusWatch *watch, void *data)
-{
- int r;
- unsigned int flags = dbus_watch_get_flags(watch);
-
- /* Only select the read watch.
- * TODO(hychao): select on write watch when we have a use case.
- */
- if ((flags & DBUS_WATCH_READABLE) && dbus_watch_get_enabled(watch)) {
- r = cras_system_add_select_fd(dbus_watch_get_unix_fd(watch),
- dbus_watch_callback, watch,
- POLLIN);
- if (r != 0)
- return FALSE;
- }
-
- return TRUE;
-}
-
-static void dbus_watch_remove(DBusWatch *watch, void *data)
-{
- unsigned int flags = dbus_watch_get_flags(watch);
-
- /* Only select the read watch. */
- if (flags & DBUS_WATCH_READABLE)
- cras_system_rm_select_fd(dbus_watch_get_unix_fd(watch));
-}
-
-static void dbus_watch_toggled(DBusWatch *watch, void *data)
-{
- if (dbus_watch_get_enabled(watch)) {
- dbus_watch_add(watch, NULL);
- } else {
- dbus_watch_remove(watch, NULL);
- }
-}
-
-static void dbus_timeout_callback(struct cras_timer *t, void *data)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
- struct DBusTimeout *timeout = data;
-
- /* Timer is automatically removed after it fires. Add a new one so this
- * fires until it is removed by dbus. */
- t = cras_tm_create_timer(tm, dbus_timeout_get_interval(timeout),
- dbus_timeout_callback, timeout);
- dbus_timeout_set_data(timeout, t, NULL);
-
- if (!dbus_timeout_handle(timeout))
- syslog(LOG_WARNING, "Failed to handle D-Bus timeout.");
-}
-
-static dbus_bool_t dbus_timeout_add(DBusTimeout *timeout, void *arg)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
- struct cras_timer *t = dbus_timeout_get_data(timeout);
-
- if (t) {
- dbus_timeout_set_data(timeout, NULL, NULL);
- cras_tm_cancel_timer(tm, t);
- }
-
- if (dbus_timeout_get_enabled(timeout)) {
- t = cras_tm_create_timer(tm, dbus_timeout_get_interval(timeout),
- dbus_timeout_callback, timeout);
- dbus_timeout_set_data(timeout, t, NULL);
- if (t == NULL)
- return FALSE;
- }
-
- return TRUE;
-}
-
-static void dbus_timeout_remove(DBusTimeout *timeout, void *arg)
-{
- struct cras_tm *tm = cras_system_state_get_tm();
- struct cras_timer *t = dbus_timeout_get_data(timeout);
-
- if (t) {
- dbus_timeout_set_data(timeout, NULL, NULL);
- cras_tm_cancel_timer(tm, t);
- }
-}
-
-static void dbus_timeout_toggled(DBusTimeout *timeout, void *arg)
-{
- if (dbus_timeout_get_enabled(timeout))
- dbus_timeout_add(timeout, NULL);
- else
- dbus_timeout_remove(timeout, NULL);
-}
-
-DBusConnection *cras_dbus_connect_system_bus()
-{
- DBusError dbus_error;
- DBusConnection *conn;
- int rc;
-
- dbus_error_init(&dbus_error);
-
- conn = dbus_bus_get(DBUS_BUS_SYSTEM, &dbus_error);
- if (!conn) {
- syslog(LOG_WARNING, "Failed to connect to D-Bus: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return NULL;
- }
-
- /* Request a name on the bus. */
- rc = dbus_bus_request_name(conn, "org.chromium.cras", 0, &dbus_error);
- if (dbus_error_is_set(&dbus_error)) {
- syslog(LOG_ERR, "Requesting dbus name %s", dbus_error.message);
- dbus_error_free(&dbus_error);
- }
- if (rc != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
- syslog(LOG_ERR, "Not primary owner of dbus name.");
-
- if (!dbus_connection_set_watch_functions(
- conn, dbus_watch_add, dbus_watch_remove, dbus_watch_toggled,
- NULL, NULL))
- goto error;
- if (!dbus_connection_set_timeout_functions(
- conn, dbus_timeout_add, dbus_timeout_remove,
- dbus_timeout_toggled, NULL, NULL))
- goto error;
-
- return conn;
-
-error:
- syslog(LOG_WARNING, "Failed to setup D-Bus connection.");
- dbus_connection_unref(conn);
- return NULL;
-}
-
-void cras_dbus_dispatch(DBusConnection *conn)
-{
- while (dbus_connection_dispatch(conn) == DBUS_DISPATCH_DATA_REMAINS)
- ;
-}
-
-void cras_dbus_disconnect_system_bus(DBusConnection *conn)
-{
- dbus_connection_unref(conn);
-}
diff --git a/cras/src/server/cras_dbus.h b/cras/src/server/cras_dbus.h
deleted file mode 100644
index 35014ed3..00000000
--- a/cras/src/server/cras_dbus.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DBUS_H_
-#define CRAS_DBUS_H_
-
-#include <dbus/dbus.h>
-
-/* Establish connection to the D-Bus System Bus. */
-DBusConnection *cras_dbus_connect_system_bus();
-
-/* Dispatch pending incoming and outgoing messages.
- *
- * This function must be called from the main loop to dispatch any
- * pending incoming and outgoing messages to the appropriate registered
- * object handler functions or filter functions - including those internal
- * to libdbus.
- *
- * It does nothing if there are no pending messages.
- */
-void cras_dbus_dispatch(DBusConnection *conn);
-
-/* Disconnect from the D-Bus System Bus. */
-void cras_dbus_disconnect_system_bus(DBusConnection *conn);
-
-#endif /* CRAS_DBUS_H_ */
diff --git a/cras/src/server/cras_dbus_control.c b/cras/src/server/cras_dbus_control.c
deleted file mode 100644
index b66e1276..00000000
--- a/cras/src/server/cras_dbus_control.c
+++ /dev/null
@@ -1,1532 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-#include <errno.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "audio_thread.h"
-#include "cras_bt_player.h"
-#include "cras_dbus.h"
-#include "cras_dbus_control.h"
-#include "cras_dbus_util.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_iodev_list.h"
-#include "cras_main_thread_log.h"
-#include "cras_observer.h"
-#include "cras_system_state.h"
-#include "cras_utf8.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-#define CRAS_CONTROL_INTERFACE "org.chromium.cras.Control"
-#define CRAS_ROOT_OBJECT_PATH "/org/chromium/cras"
-#define CONTROL_INTROSPECT_XML \
- DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
- "<node>\n" \
- " <interface name=\"" CRAS_CONTROL_INTERFACE "\">\n" \
- " <method name=\"SetOutputVolume\">\n" \
- " <arg name=\"volume\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetOutputNodeVolume\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " <arg name=\"volume\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SwapLeftRight\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " <arg name=\"swap\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetOutputMute\">\n" \
- " <arg name=\"mute_on\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetOutputUserMute\">\n" \
- " <arg name=\"mute_on\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetSuspendAudio\">\n" \
- " <arg name=\"suspend\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetInputNodeGain\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " <arg name=\"gain\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetInputMute\">\n" \
- " <arg name=\"mute_on\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"GetVolumeState\">\n" \
- " <arg name=\"output_volume\" type=\"i\" direction=\"out\"/>\n" \
- " <arg name=\"output_mute\" type=\"b\" direction=\"out\"/>\n" \
- " <arg name=\"input_mute\" type=\"b\" direction=\"out\"/>\n" \
- " <arg name=\"output_user_mute\" type=\"b\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetDefaultOutputBufferSize\">\n" \
- " <arg name=\"buffer_size\" type=\"i\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetNodes\">\n" \
- " <arg name=\"nodes\" type=\"a{sv}\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetSystemAecSupported\">\n" \
- " <arg name=\"supported\" type=\"b\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetSystemAecGroupId\">\n" \
- " <arg name=\"group_id\" type=\"i\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetDeprioritizeBtWbsMic\">\n" \
- " <arg name=\"deprioritized\" type=\"b\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"SetActiveOutputNode\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetActiveInputNode\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"AddActiveInputNode\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"AddActiveOutputNode\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"RemoveActiveInputNode\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"RemoveActiveOutputNode\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetFixA2dpPacketSize\">\n" \
- " <arg name=\"toggle\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"GetNumberOfActiveStreams\">\n" \
- " <arg name=\"num\" type=\"i\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetNumberOfActiveOutputStreams\">\n" \
- " <arg name=\"num\" type=\"i\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetNumberOfActiveInputStreams\">\n" \
- " <arg name=\"num\" type=\"i\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"GetNumberOfInputStreamsWithPermission\">\n" \
- " <arg name=\"num\" type=\"a{sv}\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"SetGlobalOutputChannelRemix\">\n" \
- " <arg name=\"num_channels\" type=\"i\" direction=\"in\"/>\n" \
- " <arg name=\"coefficient\" type=\"ad\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetHotwordModel\">\n" \
- " <arg name=\"node_id\" type=\"t\" direction=\"in\"/>\n" \
- " <arg name=\"model_name\" type=\"s\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"IsAudioOutputActive\">\n" \
- " <arg name=\"active\" type=\"b\" direction=\"out\"/>\n" \
- " </method>\n" \
- " <method name=\"SetWbsEnabled\">\n" \
- " <arg name=\"enabled\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetNoiseCancellationEnabled\">\n" \
- " <arg name=\"enabled\" type=\"b\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetPlayerPlaybackStatus\">\n" \
- " <arg name=\"status\" type=\"s\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetPlayerIdentity\">\n" \
- " <arg name=\"identity\" type=\"s\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetPlayerPosition\">\n" \
- " <arg name=\"position\" type=\"x\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetPlayerMetadata\">\n" \
- " <arg name=\"metadata\" type=\"a{sv}\" direction=\"in\"/>\n" \
- " </method>\n" \
- " </interface>\n" \
- " <interface name=\"" DBUS_INTERFACE_INTROSPECTABLE "\">\n" \
- " <method name=\"Introspect\">\n" \
- " <arg name=\"data\" type=\"s\" direction=\"out\"/>\n" \
- " </method>\n" \
- " </interface>\n" \
- "</node>\n"
-
-struct cras_dbus_control {
- DBusConnection *conn;
- struct cras_observer_client *observer;
-};
-static struct cras_dbus_control dbus_control;
-
-/* helper to extract a single argument from a DBus message. */
-static int get_single_arg(DBusMessage *message, int dbus_type, void *arg)
-{
- DBusError dbus_error;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, dbus_type, arg,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad method received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- return 0;
-}
-
-static bool get_string_metadata(DBusMessageIter *iter, const char **dst)
-{
- if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
- return FALSE;
-
- dbus_message_iter_get_basic(iter, dst);
- return TRUE;
-}
-
-static bool get_int64_metadata(DBusMessageIter *iter, dbus_int64_t *dst)
-{
- if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_INT64)
- return FALSE;
-
- dbus_message_iter_get_basic(iter, dst);
- return TRUE;
-}
-
-static bool get_metadata(DBusMessage *message, const char **title,
- const char **artist, const char **album,
- dbus_int64_t *length)
-{
- DBusError dbus_error;
- DBusMessageIter iter, dict;
-
- dbus_error_init(&dbus_error);
- dbus_message_iter_init(message, &iter);
-
- if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY)
- return FALSE;
-
- dbus_message_iter_recurse(&iter, &dict);
-
- while (dbus_message_iter_get_arg_type(&dict) != DBUS_TYPE_INVALID) {
- DBusMessageIter entry, var;
- const char *key;
-
- if (dbus_message_iter_get_arg_type(&dict) !=
- DBUS_TYPE_DICT_ENTRY)
- return FALSE;
-
- dbus_message_iter_recurse(&dict, &entry);
- if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_STRING)
- return FALSE;
-
- dbus_message_iter_get_basic(&entry, &key);
- dbus_message_iter_next(&entry);
-
- if (dbus_message_iter_get_arg_type(&entry) != DBUS_TYPE_VARIANT)
- return FALSE;
-
- dbus_message_iter_recurse(&entry, &var);
- if (strcasecmp(key, "title") == 0) {
- if (!get_string_metadata(&var, title))
- return FALSE;
- } else if (strcasecmp(key, "artist") == 0) {
- if (!get_string_metadata(&var, artist))
- return FALSE;
- } else if (strcasecmp(key, "album") == 0) {
- if (!get_string_metadata(&var, album))
- return FALSE;
- } else if (strcasecmp(key, "length") == 0) {
- if (!get_int64_metadata(&var, length))
- return FALSE;
- } else
- syslog(LOG_WARNING, "%s not supported, ignoring", key);
-
- dbus_message_iter_next(&dict);
- }
-
- return TRUE;
-}
-
-/* Helper to send an empty reply. */
-static void send_empty_reply(DBusConnection *conn, DBusMessage *message)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return;
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-}
-
-/* Helper to send an int32 reply. */
-static void send_int32_reply(DBusConnection *conn, DBusMessage *message,
- dbus_int32_t value)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return;
-
- dbus_message_append_args(reply, DBUS_TYPE_INT32, &value,
- DBUS_TYPE_INVALID);
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-}
-
-/* Handlers for exported DBus method calls. */
-static DBusHandlerResult
-handle_set_output_volume(DBusConnection *conn, DBusMessage *message, void *arg)
-{
- int rc;
- dbus_int32_t new_vol;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &new_vol);
- if (rc)
- return rc;
-
- cras_system_set_volume(new_vol);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_output_node_volume(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- dbus_int32_t new_vol;
- cras_node_id_t id;
- DBusError dbus_error;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_UINT64, &id,
- DBUS_TYPE_INT32, &new_vol,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad method received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- cras_iodev_list_set_node_attr(id, IONODE_ATTR_VOLUME, new_vol);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_swap_left_right(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- cras_node_id_t id;
- dbus_bool_t swap;
- DBusError dbus_error;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_UINT64, &id,
- DBUS_TYPE_BOOLEAN, &swap,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad method received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- cras_iodev_list_set_node_attr(id, IONODE_ATTR_SWAP_LEFT_RIGHT, swap);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_output_mute(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- int rc;
- dbus_bool_t new_mute;
-
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &new_mute);
- if (rc)
- return rc;
-
- cras_system_set_mute(new_mute);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_output_user_mute(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- int rc;
- dbus_bool_t new_mute;
-
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &new_mute);
- if (rc)
- return rc;
-
- cras_system_set_user_mute(new_mute);
- MAINLOG(main_log, MAIN_THREAD_SET_OUTPUT_USER_MUTE, new_mute, 0, 0);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_set_suspend_audio(DBusConnection *conn, DBusMessage *message, void *arg)
-{
- int rc;
- dbus_bool_t suspend;
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &suspend);
- if (rc)
- return rc;
-
- cras_system_set_suspended(suspend);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_input_node_gain(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- dbus_int32_t new_gain;
- cras_node_id_t id;
- DBusError dbus_error;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_UINT64, &id,
- DBUS_TYPE_INT32, &new_gain,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad method received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- cras_iodev_list_set_node_attr(id, IONODE_ATTR_CAPTURE_GAIN, new_gain);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_input_mute(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- int rc;
- dbus_bool_t new_mute;
-
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &new_mute);
- if (rc)
- return rc;
-
- cras_system_set_capture_mute(new_mute);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_get_volume_state(DBusConnection *conn, DBusMessage *message, void *arg)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
- dbus_int32_t volume;
- dbus_bool_t system_muted;
- dbus_bool_t user_muted;
- dbus_bool_t capture_muted;
-
- reply = dbus_message_new_method_return(message);
-
- volume = cras_system_get_volume();
- system_muted = cras_system_get_system_mute();
- user_muted = cras_system_get_user_mute();
- capture_muted = cras_system_get_capture_mute();
-
- dbus_message_append_args(reply, DBUS_TYPE_INT32, &volume,
- DBUS_TYPE_BOOLEAN, &system_muted,
- DBUS_TYPE_BOOLEAN, &capture_muted,
- DBUS_TYPE_BOOLEAN, &user_muted,
- DBUS_TYPE_INVALID);
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_get_default_output_buffer_size(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
- dbus_int32_t buffer_size;
-
- reply = dbus_message_new_method_return(message);
-
- buffer_size = cras_system_get_default_output_buffer_size();
- dbus_message_append_args(reply, DBUS_TYPE_INT32, &buffer_size,
- DBUS_TYPE_INVALID);
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-/* Appends the information about a node to the dbus message. Returns
- * false if not enough memory. */
-static dbus_bool_t append_node_dict(DBusMessageIter *iter,
- const struct cras_iodev_info *dev,
- const struct cras_ionode_info *node,
- enum CRAS_STREAM_DIRECTION direction)
-{
- DBusMessageIter dict;
- dbus_bool_t is_input;
- dbus_uint64_t id;
- const char *dev_name = dev->name;
- dbus_uint64_t stable_dev_id = node->stable_id;
- const char *node_type = node->type;
- const char *node_name = node->name;
- dbus_bool_t active;
- dbus_uint64_t plugged_time = node->plugged_time.tv_sec * 1000000ULL +
- node->plugged_time.tv_usec;
- dbus_uint64_t node_volume = node->volume;
- dbus_int64_t node_capture_gain = node->capture_gain;
- char *models, *empty_models = "";
-
- is_input = (direction == CRAS_STREAM_INPUT);
- id = node->iodev_idx;
- id = (id << 32) | node->ionode_idx;
- active = !!node->active;
-
- // If dev_name is not utf8, libdbus may abort cras.
- if (!is_utf8_string(dev_name)) {
- syslog(LOG_ERR,
- "Non-utf8 device name '%s' cannot be sent via dbus",
- dev_name);
- dev_name = "";
- }
-
- if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "{sv}",
- &dict))
- return FALSE;
- if (!append_key_value(&dict, "IsInput", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &is_input))
- return FALSE;
- if (!append_key_value(&dict, "Id", DBUS_TYPE_UINT64,
- DBUS_TYPE_UINT64_AS_STRING, &id))
- return FALSE;
- if (!append_key_value(&dict, "DeviceName", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &dev_name))
- return FALSE;
- /*
- * If stable id migration is needed, use key 'StableDeviceIdNew'
- * together with 'StableDeviceId'.
- */
- if (!append_key_value(&dict, "StableDeviceId", DBUS_TYPE_UINT64,
- DBUS_TYPE_UINT64_AS_STRING, &stable_dev_id))
- return FALSE;
- if (!append_key_value(&dict, "Type", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &node_type))
- return FALSE;
- if (!append_key_value(&dict, "Name", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING, &node_name))
- return FALSE;
- if (!append_key_value(&dict, "Active", DBUS_TYPE_BOOLEAN,
- DBUS_TYPE_BOOLEAN_AS_STRING, &active))
- return FALSE;
- if (!append_key_value(&dict, "PluggedTime", DBUS_TYPE_UINT64,
- DBUS_TYPE_UINT64_AS_STRING, &plugged_time))
- return FALSE;
- if (!append_key_value(&dict, "NodeVolume", DBUS_TYPE_UINT64,
- DBUS_TYPE_UINT64_AS_STRING, &node_volume))
- return FALSE;
- if (!append_key_value(&dict, "NodeCaptureGain", DBUS_TYPE_INT64,
- DBUS_TYPE_INT64_AS_STRING, &node_capture_gain))
- return FALSE;
-
- models = cras_iodev_list_get_hotword_models(id);
- if (!append_key_value(&dict, "HotwordModels", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING,
- models ? &models : &empty_models)) {
- free(models);
- return FALSE;
- }
- free(models);
-
- if (!dbus_message_iter_close_container(iter, &dict))
- return FALSE;
-
- return TRUE;
-}
-
-/* Appends the information about all nodes in a given direction. Returns false
- * if not enough memory. */
-static dbus_bool_t append_nodes(enum CRAS_STREAM_DIRECTION direction,
- DBusMessageIter *array)
-{
- const struct cras_iodev_info *devs;
- const struct cras_ionode_info *nodes;
- int ndevs, nnodes;
- int i, j;
-
- if (direction == CRAS_STREAM_OUTPUT) {
- ndevs = cras_system_state_get_output_devs(&devs);
- nnodes = cras_system_state_get_output_nodes(&nodes);
- } else {
- ndevs = cras_system_state_get_input_devs(&devs);
- nnodes = cras_system_state_get_input_nodes(&nodes);
- }
-
- for (i = 0; i < nnodes; i++) {
- /* Don't reply unplugged nodes. */
- if (!nodes[i].plugged)
- continue;
- /* Find the device for this node. */
- for (j = 0; j < ndevs; j++)
- if (devs[j].idx == nodes[i].iodev_idx)
- break;
- if (j == ndevs)
- continue;
- /* Send information about this node. */
- if (!append_node_dict(array, &devs[j], &nodes[i], direction))
- return FALSE;
- }
-
- return TRUE;
-}
-
-static DBusHandlerResult handle_get_nodes(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusMessage *reply;
- DBusMessageIter array;
- dbus_uint32_t serial = 0;
-
- reply = dbus_message_new_method_return(message);
- dbus_message_iter_init_append(reply, &array);
- if (!append_nodes(CRAS_STREAM_OUTPUT, &array))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!append_nodes(CRAS_STREAM_INPUT, &array))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- dbus_connection_send(conn, reply, &serial);
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_get_system_aec_supported(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
- dbus_bool_t system_aec_supported;
-
- reply = dbus_message_new_method_return(message);
-
- system_aec_supported = cras_system_get_aec_supported();
- dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN,
- &system_aec_supported, DBUS_TYPE_INVALID);
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_get_system_aec_group_id(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
- dbus_int32_t system_aec_group_id;
-
- reply = dbus_message_new_method_return(message);
-
- system_aec_group_id = cras_system_get_aec_group_id();
- dbus_message_append_args(reply, DBUS_TYPE_INT32, &system_aec_group_id,
- DBUS_TYPE_INVALID);
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_get_deprioritize_bt_wbs_mic(DBusConnection *conn, DBusMessage *message,
- void *arg)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
- dbus_bool_t deprioritized;
-
- reply = dbus_message_new_method_return(message);
-
- deprioritized = cras_system_get_deprioritize_bt_wbs_mic();
- dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &deprioritized,
- DBUS_TYPE_INVALID);
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_set_active_node(DBusConnection *conn, DBusMessage *message, void *arg,
- enum CRAS_STREAM_DIRECTION direction)
-{
- int rc;
- cras_node_id_t id;
-
- rc = get_single_arg(message, DBUS_TYPE_UINT64, &id);
- if (rc)
- return rc;
-
- cras_iodev_list_select_node(direction, id);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_add_active_node(DBusConnection *conn, DBusMessage *message, void *arg,
- enum CRAS_STREAM_DIRECTION direction)
-{
- int rc;
- cras_node_id_t id;
-
- rc = get_single_arg(message, DBUS_TYPE_UINT64, &id);
- if (rc)
- return rc;
-
- cras_iodev_list_add_active_node(direction, id);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_rm_active_node(DBusConnection *conn, DBusMessage *message, void *arg,
- enum CRAS_STREAM_DIRECTION direction)
-{
- int rc;
- cras_node_id_t id;
-
- rc = get_single_arg(message, DBUS_TYPE_UINT64, &id);
- if (rc)
- return rc;
-
- cras_iodev_list_rm_active_node(direction, id);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_fix_a2dp_packet_size(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- int rc;
- dbus_bool_t enabled = FALSE;
-
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &enabled);
- if (rc)
- return rc;
-
- cras_system_set_bt_fix_a2dp_packet_size_enabled(enabled);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_get_num_active_streams(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- send_int32_reply(conn, message, cras_system_state_get_active_streams());
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_get_num_active_streams_use_input_hw(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- dbus_int32_t num = 0;
- unsigned i;
-
- for (i = 0; i < CRAS_NUM_DIRECTIONS; i++) {
- if (cras_stream_uses_input_hw(i))
- num += cras_system_state_get_active_streams_by_direction(
- i);
- }
- send_int32_reply(conn, message, num);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_get_num_active_streams_use_output_hw(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- dbus_int32_t num = 0;
- unsigned i;
-
- for (i = 0; i < CRAS_NUM_DIRECTIONS; i++) {
- if (cras_stream_uses_output_hw(i))
- num += cras_system_state_get_active_streams_by_direction(
- i);
- }
- send_int32_reply(conn, message, num);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static bool append_num_input_streams_with_permission(
- DBusMessage *message, uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE])
-{
- DBusMessageIter array;
- DBusMessageIter dict;
- unsigned type;
-
- dbus_message_iter_init_append(message, &array);
- for (type = 0; type < CRAS_NUM_CLIENT_TYPE; ++type) {
- const char *client_type_str = cras_client_type_str(type);
- if (!is_utf8_string(client_type_str)) {
- syslog(LOG_ERR,
- "Non-utf8 clinet_type_str '%s' cannot be sent "
- "via dbus",
- client_type_str);
- client_type_str = "";
- }
-
- if (!dbus_message_iter_open_container(&array, DBUS_TYPE_ARRAY,
- "{sv}", &dict))
- return false;
- if (!append_key_value(&dict, "ClientType", DBUS_TYPE_STRING,
- DBUS_TYPE_STRING_AS_STRING,
- &client_type_str))
- return false;
- if (!append_key_value(&dict, "NumStreamsWithPermission",
- DBUS_TYPE_UINT32,
- DBUS_TYPE_UINT32_AS_STRING,
- &num_input_streams[type]))
- return false;
- if (!dbus_message_iter_close_container(&array, &dict))
- return false;
- }
- return true;
-}
-
-static DBusHandlerResult
-handle_get_num_input_streams_with_permission(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE] = {};
-
- reply = dbus_message_new_method_return(message);
-
- cras_system_state_get_input_streams_with_permission(num_input_streams);
- if (!append_num_input_streams_with_permission(reply, num_input_streams))
- goto error;
-
- dbus_connection_send(conn, reply, &serial);
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-
-error:
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-}
-
-static DBusHandlerResult
-handle_set_global_output_channel_remix(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- dbus_int32_t num_channels;
- double *coeff_array;
- dbus_int32_t count;
- DBusError dbus_error;
- float *coefficient;
- int i;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_INT32,
- &num_channels, DBUS_TYPE_ARRAY,
- DBUS_TYPE_DOUBLE, &coeff_array, &count,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Set global output channel remix error: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- coefficient = (float *)calloc(count, sizeof(*coefficient));
- if (!coefficient)
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-
- for (i = 0; i < count; i++)
- coefficient[i] = coeff_array[i];
-
- audio_thread_config_global_remix(cras_iodev_list_get_audio_thread(),
- num_channels, coefficient);
-
- send_empty_reply(conn, message);
- free(coefficient);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_set_hotword_model(DBusConnection *conn, DBusMessage *message, void *arg)
-{
- cras_node_id_t id;
- const char *model_name;
- DBusError dbus_error;
- dbus_int32_t ret;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, DBUS_TYPE_UINT64, &id,
- DBUS_TYPE_STRING, &model_name,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad method received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- ret = cras_iodev_list_set_hotword_model(id, model_name);
- send_int32_reply(conn, message, ret);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_is_audio_active(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- dbus_int32_t active = cras_system_state_get_non_empty_status();
-
- send_int32_reply(conn, message, active);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_wbs_enabled(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- int rc;
- dbus_bool_t enabled;
-
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &enabled);
- if (rc)
- return rc;
-
- cras_system_set_bt_wbs_enabled(enabled);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult
-handle_set_noise_cancellation_enabled(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- int rc;
- dbus_bool_t enabled;
-
- rc = get_single_arg(message, DBUS_TYPE_BOOLEAN, &enabled);
- if (rc)
- return rc;
-
- cras_system_set_noise_cancellation_enabled(enabled);
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_player_playback_status(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- char *status;
- DBusError dbus_error;
- int rc;
-
- dbus_error_init(&dbus_error);
-
- rc = get_single_arg(message, DBUS_TYPE_STRING, &status);
- if (rc)
- return rc;
-
- rc = cras_bt_player_update_playback_status(conn, status);
- if (rc) {
- syslog(LOG_WARNING,
- "CRAS failed to update BT Player Status: %d", rc);
- }
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_player_identity(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- char *identity;
- DBusError dbus_error;
- int rc;
-
- dbus_error_init(&dbus_error);
-
- rc = get_single_arg(message, DBUS_TYPE_STRING, &identity);
- if (rc)
- return rc;
-
- rc = cras_bt_player_update_identity(conn, identity);
- if (rc) {
- syslog(LOG_WARNING,
- "CRAS failed to update BT Player Identity: %d", rc);
- }
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_player_position(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- dbus_int64_t position;
- DBusError dbus_error;
- int rc;
-
- dbus_error_init(&dbus_error);
-
- rc = get_single_arg(message, DBUS_TYPE_INT64, &position);
- if (rc)
- return rc;
-
- rc = cras_bt_player_update_position(conn, position);
- if (rc) {
- syslog(LOG_WARNING,
- "CRAS failed to update BT Player Position: %d", rc);
- }
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_player_metadata(DBusConnection *conn,
- DBusMessage *message,
- void *arg)
-{
- DBusError dbus_error;
- int rc;
-
- dbus_error_init(&dbus_error);
- const char *title = NULL, *artist = NULL, *album = NULL;
- dbus_int64_t length = 0;
-
- if (!get_metadata(message, &title, &artist, &album, &length))
- return -EINVAL;
-
- rc = cras_bt_player_update_metadata(conn, title, artist, album, length);
- if (rc) {
- syslog(LOG_WARNING, "CRAS failed to update BT Metadata: %d",
- rc);
- }
-
- send_empty_reply(conn, message);
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-/* Handle incoming messages. */
-static DBusHandlerResult handle_control_message(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- syslog(LOG_DEBUG, "Control message: %s %s %s",
- dbus_message_get_path(message),
- dbus_message_get_interface(message),
- dbus_message_get_member(message));
-
- if (dbus_message_is_method_call(message, DBUS_INTERFACE_INTROSPECTABLE,
- "Introspect")) {
- DBusMessage *reply;
- const char *xml = CONTROL_INTROSPECT_XML;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &xml,
- DBUS_TYPE_INVALID))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
-
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetOutputVolume")) {
- return handle_set_output_volume(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetOutputNodeVolume")) {
- return handle_set_output_node_volume(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SwapLeftRight")) {
- return handle_swap_left_right(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetOutputMute")) {
- return handle_set_output_mute(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetOutputUserMute")) {
- return handle_set_output_user_mute(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetSuspendAudio")) {
- return handle_set_suspend_audio(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetInputNodeGain")) {
- return handle_set_input_node_gain(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetInputMute")) {
- return handle_set_input_mute(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetVolumeState")) {
- return handle_get_volume_state(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetDefaultOutputBufferSize")) {
- return handle_get_default_output_buffer_size(conn, message,
- arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetNodes")) {
- return handle_get_nodes(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetSystemAecSupported")) {
- return handle_get_system_aec_supported(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetSystemAecGroupId")) {
- return handle_get_system_aec_group_id(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetDeprioritizeBtWbsMic")) {
- return handle_get_deprioritize_bt_wbs_mic(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetActiveOutputNode")) {
- return handle_set_active_node(conn, message, arg,
- CRAS_STREAM_OUTPUT);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetActiveInputNode")) {
- return handle_set_active_node(conn, message, arg,
- CRAS_STREAM_INPUT);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "AddActiveInputNode")) {
- return handle_add_active_node(conn, message, arg,
- CRAS_STREAM_INPUT);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "AddActiveOutputNode")) {
- return handle_add_active_node(conn, message, arg,
- CRAS_STREAM_OUTPUT);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "RemoveActiveInputNode")) {
- return handle_rm_active_node(conn, message, arg,
- CRAS_STREAM_INPUT);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "RemoveActiveOutputNode")) {
- return handle_rm_active_node(conn, message, arg,
- CRAS_STREAM_OUTPUT);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetFixA2dpPacketSize")) {
- return handle_set_fix_a2dp_packet_size(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "GetNumberOfActiveStreams")) {
- return handle_get_num_active_streams(conn, message, arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_CONTROL_INTERFACE,
- "GetNumberOfActiveInputStreams")) {
- return handle_get_num_active_streams_use_input_hw(conn, message,
- arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_CONTROL_INTERFACE,
- "GetNumberOfInputStreamsWithPermission")) {
- return handle_get_num_input_streams_with_permission(
- conn, message, arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_CONTROL_INTERFACE,
- "GetNumberOfActiveOutputStreams")) {
- return handle_get_num_active_streams_use_output_hw(
- conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetGlobalOutputChannelRemix")) {
- return handle_set_global_output_channel_remix(conn, message,
- arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetHotwordModel")) {
- return handle_set_hotword_model(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "IsAudioOutputActive")) {
- return handle_is_audio_active(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetWbsEnabled")) {
- return handle_set_wbs_enabled(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetNoiseCancellationEnabled")) {
- return handle_set_noise_cancellation_enabled(conn, message,
- arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetPlayerPlaybackStatus")) {
- return handle_set_player_playback_status(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetPlayerIdentity")) {
- return handle_set_player_identity(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetPlayerPosition")) {
- return handle_set_player_position(conn, message, arg);
- } else if (dbus_message_is_method_call(message, CRAS_CONTROL_INTERFACE,
- "SetPlayerMetadata")) {
- return handle_set_player_metadata(conn, message, arg);
- }
-
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-/* Creates a new DBus message, must be freed with dbus_message_unref. */
-static DBusMessage *create_dbus_message(const char *name)
-{
- DBusMessage *msg;
- msg = dbus_message_new_signal(CRAS_ROOT_OBJECT_PATH,
- CRAS_CONTROL_INTERFACE, name);
- if (!msg)
- syslog(LOG_ERR, "Failed to create signal");
-
- return msg;
-}
-
-/* Handlers for system updates that generate DBus signals. */
-
-static void signal_output_volume(void *context, int32_t volume)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("OutputVolumeChanged");
- if (!msg)
- return;
-
- volume = cras_system_get_volume();
- dbus_message_append_args(msg, DBUS_TYPE_INT32, &volume,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_output_mute(void *context, int muted, int user_muted,
- int mute_locked)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("OutputMuteChanged");
- if (!msg)
- return;
-
- muted = cras_system_get_system_mute();
- user_muted = cras_system_get_user_mute();
- dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &muted,
- DBUS_TYPE_BOOLEAN, &user_muted,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_capture_gain(void *context, int32_t gain)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("InputGainChanged");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_INT32, &gain,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_capture_mute(void *context, int muted, int mute_locked)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("InputMuteChanged");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &muted,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_nodes_changed(void *context)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("NodesChanged");
- if (!msg)
- return;
-
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_active_node_changed(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- DBusMessage *msg;
- dbus_uint32_t serial = 0;
-
- msg = create_dbus_message((dir == CRAS_STREAM_OUTPUT) ?
- "ActiveOutputNodeChanged" :
- "ActiveInputNodeChanged");
- if (!msg)
- return;
- dbus_message_append_args(msg, DBUS_TYPE_UINT64, &node_id,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-/* Called by iodev_list when a node volume changes. */
-static void signal_node_volume_changed(void *context, cras_node_id_t node_id,
- int32_t volume)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("OutputNodeVolumeChanged");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_UINT64, &node_id,
- DBUS_TYPE_INT32, &volume, DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_node_capture_gain_changed(void *context,
- cras_node_id_t node_id,
- int capture_gain)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("InputNodeGainChanged");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_UINT64, &node_id,
- DBUS_TYPE_INT32, &capture_gain,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_node_left_right_swapped_changed(void *context,
- cras_node_id_t node_id,
- int swapped)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("NodeLeftRightSwappedChanged");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_UINT64, &node_id,
- DBUS_TYPE_BOOLEAN, &swapped,
- DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_num_active_streams_changed(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
- dbus_int32_t num;
-
- msg = create_dbus_message("NumberOfActiveStreamsChanged");
- if (!msg)
- return;
-
- num = cras_system_state_get_active_streams();
- dbus_message_append_args(msg, DBUS_TYPE_INT32, &num, DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_num_input_streams_with_permission_changed(
- void *context, uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE])
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("NumberOfInputStreamsWithPermissionChanged");
- if (!msg)
- return;
-
- if (!append_num_input_streams_with_permission(msg, num_input_streams))
- goto error;
-
- dbus_connection_send(control->conn, msg, &serial);
-error:
- dbus_message_unref(msg);
-}
-
-static void signal_hotword_triggered(void *context, int64_t tv_sec,
- int64_t tv_nsec)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("HotwordTriggered");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_INT64, &tv_sec, DBUS_TYPE_INT64,
- &tv_nsec, DBUS_TYPE_INVALID);
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-static void signal_non_empty_audio_state_changed(void *context, int non_empty)
-{
- struct cras_dbus_control *control = (struct cras_dbus_control *)context;
-
- dbus_uint32_t serial = 0;
- DBusMessage *msg;
-
- msg = create_dbus_message("AudioOutputActiveStateChanged");
- if (!msg)
- return;
-
- dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &non_empty,
- DBUS_TYPE_INVALID);
-
- dbus_connection_send(control->conn, msg, &serial);
- dbus_message_unref(msg);
-}
-
-/* Exported Interface */
-
-void cras_dbus_control_start(DBusConnection *conn)
-{
- static const DBusObjectPathVTable control_vtable = {
- .message_function = handle_control_message,
- };
-
- DBusError dbus_error;
- struct cras_observer_ops observer_ops;
-
- dbus_control.conn = conn;
- dbus_connection_ref(dbus_control.conn);
-
- if (!dbus_connection_register_object_path(conn, CRAS_ROOT_OBJECT_PATH,
- &control_vtable,
- &dbus_error)) {
- syslog(LOG_WARNING, "Couldn't register CRAS control: %s: %s",
- CRAS_ROOT_OBJECT_PATH, dbus_error.message);
- dbus_error_free(&dbus_error);
- return;
- }
-
- memset(&observer_ops, 0, sizeof(observer_ops));
- observer_ops.output_volume_changed = signal_output_volume;
- observer_ops.output_mute_changed = signal_output_mute;
- observer_ops.capture_gain_changed = signal_capture_gain;
- observer_ops.capture_mute_changed = signal_capture_mute;
- observer_ops.num_active_streams_changed =
- signal_num_active_streams_changed;
- observer_ops.num_input_streams_with_permission_changed =
- signal_num_input_streams_with_permission_changed;
- observer_ops.nodes_changed = signal_nodes_changed;
- observer_ops.active_node_changed = signal_active_node_changed;
- observer_ops.input_node_gain_changed = signal_node_capture_gain_changed;
- observer_ops.output_node_volume_changed = signal_node_volume_changed;
- observer_ops.node_left_right_swapped_changed =
- signal_node_left_right_swapped_changed;
- observer_ops.hotword_triggered = signal_hotword_triggered;
- observer_ops.non_empty_audio_state_changed =
- signal_non_empty_audio_state_changed;
-
- dbus_control.observer = cras_observer_add(&observer_ops, &dbus_control);
-}
-
-void cras_dbus_control_stop()
-{
- if (!dbus_control.conn)
- return;
-
- dbus_connection_unregister_object_path(dbus_control.conn,
- CRAS_ROOT_OBJECT_PATH);
-
- dbus_connection_unref(dbus_control.conn);
- dbus_control.conn = NULL;
- cras_observer_remove(dbus_control.observer);
- dbus_control.observer = NULL;
-}
diff --git a/cras/src/server/cras_dbus_control.h b/cras/src/server/cras_dbus_control.h
deleted file mode 100644
index e4c845b2..00000000
--- a/cras/src/server/cras_dbus_control.h
+++ /dev/null
@@ -1,15 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DBUS_CONTROL_H_
-#define CRAS_DBUS_CONTROL_H_
-
-/* Starts the dbus control interface, begins listening for incoming messages. */
-void cras_dbus_control_start(DBusConnection *conn);
-
-/* Stops monitoring the dbus interface for command messages. */
-void cras_dbus_control_stop();
-
-#endif /* CRAS_DBUS_CONTROL_H_ */
diff --git a/cras/src/server/cras_dbus_util.c b/cras/src/server/cras_dbus_util.c
deleted file mode 100644
index 79e48348..00000000
--- a/cras/src/server/cras_dbus_util.c
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "cras_dbus_util.h"
-
-dbus_bool_t append_key_value(DBusMessageIter *iter, const char *key, int type,
- const char *type_string, void *value)
-{
- DBusMessageIter entry, variant;
-
- if (!dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL,
- &entry))
- return FALSE;
- if (!dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &key))
- return FALSE;
- if (!dbus_message_iter_open_container(&entry, DBUS_TYPE_VARIANT,
- type_string, &variant))
- return FALSE;
- if (!dbus_message_iter_append_basic(&variant, type, value))
- return FALSE;
- if (!dbus_message_iter_close_container(&entry, &variant))
- return FALSE;
- if (!dbus_message_iter_close_container(iter, &entry))
- return FALSE;
-
- return TRUE;
-}
diff --git a/cras/src/server/cras_dbus_util.h b/cras/src/server/cras_dbus_util.h
deleted file mode 100644
index 94d5320b..00000000
--- a/cras/src/server/cras_dbus_util.h
+++ /dev/null
@@ -1,18 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-
-/* Appends a key-value pair to the dbus message.
- * Args:
- * key - the key (a string)
- * type - the type of the value (for example, 'y')
- * type_string - the type of the value in string form (for example, "y")
- * value - a pointer to the value to be appended.
- * Returns:
- * false if not enough memory.
-*/
-dbus_bool_t append_key_value(DBusMessageIter *iter, const char *key, int type,
- const char *type_string, void *value);
diff --git a/cras/src/server/cras_device_monitor.c b/cras/src/server/cras_device_monitor.c
deleted file mode 100644
index e9730a0b..00000000
--- a/cras/src/server/cras_device_monitor.c
+++ /dev/null
@@ -1,119 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdbool.h>
-#include <syslog.h>
-
-#include "cras_device_monitor.h"
-#include "cras_iodev_list.h"
-#include "cras_main_message.h"
-
-enum CRAS_DEVICE_MONITOR_MSG_TYPE {
- RESET_DEVICE,
- SET_MUTE_STATE,
- ERROR_CLOSE,
-};
-
-struct cras_device_monitor_message {
- struct cras_main_message header;
- enum CRAS_DEVICE_MONITOR_MSG_TYPE message_type;
- unsigned int dev_idx;
-};
-
-static void init_device_msg(struct cras_device_monitor_message *msg,
- enum CRAS_DEVICE_MONITOR_MSG_TYPE type,
- unsigned int dev_idx)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.type = CRAS_MAIN_MONITOR_DEVICE;
- msg->header.length = sizeof(*msg);
- msg->message_type = type;
- msg->dev_idx = dev_idx;
-}
-
-int cras_device_monitor_reset_device(unsigned int dev_idx)
-{
- struct cras_device_monitor_message msg;
- int err;
-
- init_device_msg(&msg, RESET_DEVICE, dev_idx);
- err = cras_main_message_send((struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send device message %d",
- RESET_DEVICE);
- return err;
- }
- return 0;
-}
-
-int cras_device_monitor_set_device_mute_state(unsigned int dev_idx)
-{
- struct cras_device_monitor_message msg;
- int err;
-
- init_device_msg(&msg, SET_MUTE_STATE, dev_idx);
- err = cras_main_message_send((struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send device message %d",
- SET_MUTE_STATE);
- return err;
- }
- return 0;
-}
-
-int cras_device_monitor_error_close(unsigned int dev_idx)
-{
- struct cras_device_monitor_message msg;
- int err;
-
- init_device_msg(&msg, ERROR_CLOSE, dev_idx);
- err = cras_main_message_send((struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send device message %d",
- ERROR_CLOSE);
- return err;
- }
- return 0;
-}
-
-/* When device is in a bad state, e.g. severe underrun,
- * it might break how audio thread works and cause busy wake up loop.
- * Resetting the device can bring device back to normal state.
- * Let main thread follow the disable/enable sequence in iodev_list
- * to properly close/open the device while enabling/disabling fallback
- * device.
- */
-static void handle_device_message(struct cras_main_message *msg, void *arg)
-{
- struct cras_device_monitor_message *device_msg =
- (struct cras_device_monitor_message *)msg;
-
- switch (device_msg->message_type) {
- case RESET_DEVICE:
- syslog(LOG_ERR, "trying to recover device 0x%x by resetting it",
- device_msg->dev_idx);
- cras_iodev_list_suspend_dev(device_msg->dev_idx);
- cras_iodev_list_resume_dev(device_msg->dev_idx);
- break;
- case SET_MUTE_STATE:
- cras_iodev_list_set_dev_mute(device_msg->dev_idx);
- break;
- case ERROR_CLOSE:
- syslog(LOG_ERR, "Close erroneous device in main thread");
- cras_iodev_list_suspend_dev(device_msg->dev_idx);
- break;
- default:
- syslog(LOG_ERR, "Unknown device message type %u",
- device_msg->message_type);
- break;
- }
-}
-
-int cras_device_monitor_init()
-{
- cras_main_message_add_handler(CRAS_MAIN_MONITOR_DEVICE,
- handle_device_message, NULL);
- return 0;
-}
diff --git a/cras/src/server/cras_device_monitor.h b/cras/src/server/cras_device_monitor.h
deleted file mode 100644
index eca2372b..00000000
--- a/cras/src/server/cras_device_monitor.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DEVICE_MONITOR_H_
-#define CRAS_DEVICE_MONITOR_H_
-
-/* Asks main thread to reset a device */
-int cras_device_monitor_reset_device(unsigned int dev_idx);
-
-/* Asks main thread to set mute/unmute state on a device. */
-int cras_device_monitor_set_device_mute_state(unsigned int dev_idx);
-
-/* Initializes device monitor and sets main thread callback. */
-int cras_device_monitor_init();
-
-/* Asks main thread to close device because error has occured in audio
- * thread. */
-int cras_device_monitor_error_close(unsigned int dev_idx);
-
-#endif /* CRAS_DEVICE_MONITOR_H_ */
diff --git a/cras/src/server/cras_dsp.c b/cras/src/server/cras_dsp.c
deleted file mode 100644
index 9c4cc7b5..00000000
--- a/cras/src/server/cras_dsp.c
+++ /dev/null
@@ -1,265 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <pthread.h>
-#include <syslog.h>
-#include "dumper.h"
-#include "cras_expr.h"
-#include "cras_dsp_ini.h"
-#include "cras_dsp_pipeline.h"
-#include "dsp_util.h"
-#include "utlist.h"
-
-/* We have a dsp_context for each pipeline. The context records the
- * parameters used to create a pipeline, so the pipeline can be
- * (re-)loaded later. The pipeline is (re-)loaded in the following
- * cases:
- *
- * (1) The client asks to (re-)load it with cras_load_pipeline().
- * (2) The client asks to reload the ini with cras_reload_ini().
- *
- * The pipeline is (re-)loaded asynchronously in an internal thread,
- * so the client needs to use cras_dsp_get_pipeline() and
- * cras_dsp_put_pipeline() to safely access the pipeline.
- */
-struct cras_dsp_context {
- pthread_mutex_t mutex;
- struct pipeline *pipeline;
-
- struct cras_expr_env env;
- int sample_rate;
- const char *purpose;
- struct cras_dsp_context *prev, *next;
-};
-
-static struct dumper *syslog_dumper;
-static const char *ini_filename;
-static struct ini *global_ini;
-static struct cras_dsp_context *context_list;
-
-static void initialize_environment(struct cras_expr_env *env)
-{
- cras_expr_env_install_builtins(env);
- cras_expr_env_set_variable_boolean(env, "disable_eq", 0);
- cras_expr_env_set_variable_boolean(env, "disable_drc", 0);
- cras_expr_env_set_variable_string(env, "dsp_name", "");
- cras_expr_env_set_variable_boolean(env, "swap_lr_disabled", 1);
-}
-
-static void destroy_pipeline(struct pipeline *pipeline)
-{
- struct ini *private_ini;
-
- private_ini = cras_dsp_pipeline_get_ini(pipeline);
- cras_dsp_pipeline_free(pipeline);
-
- /*
- * If pipeline is using an dsp ini other than the global one, free
- * this ini so its life cycle is aligned with the associated dsp
- * pipeline.
- */
- if (private_ini && (private_ini != global_ini))
- cras_dsp_ini_free(private_ini);
-}
-
-static struct pipeline *prepare_pipeline(struct cras_dsp_context *ctx,
- struct ini *target_ini)
-{
- struct pipeline *pipeline;
- const char *purpose = ctx->purpose;
-
- pipeline = cras_dsp_pipeline_create(target_ini, &ctx->env, purpose);
-
- if (pipeline) {
- syslog(LOG_DEBUG, "pipeline created");
- } else {
- syslog(LOG_DEBUG, "cannot create pipeline");
- goto bail;
- }
-
- if (cras_dsp_pipeline_load(pipeline) != 0) {
- syslog(LOG_ERR, "cannot load pipeline");
- goto bail;
- }
-
- if (cras_dsp_pipeline_instantiate(pipeline, ctx->sample_rate) != 0) {
- syslog(LOG_ERR, "cannot instantiate pipeline");
- goto bail;
- }
-
- if (cras_dsp_pipeline_get_sample_rate(pipeline) != ctx->sample_rate) {
- syslog(LOG_ERR, "pipeline sample rate mismatch (%d vs %d)",
- cras_dsp_pipeline_get_sample_rate(pipeline),
- ctx->sample_rate);
- goto bail;
- }
-
- return pipeline;
-
-bail:
- if (pipeline)
- destroy_pipeline(pipeline);
- return NULL;
-}
-
-static void cmd_load_pipeline(struct cras_dsp_context *ctx,
- struct ini *target_ini)
-{
- struct pipeline *pipeline, *old_pipeline;
-
- pipeline = target_ini ? prepare_pipeline(ctx, target_ini) : NULL;
-
- /* This locking is short to avoild blocking audio thread. */
- pthread_mutex_lock(&ctx->mutex);
- old_pipeline = ctx->pipeline;
- ctx->pipeline = pipeline;
- pthread_mutex_unlock(&ctx->mutex);
-
- if (old_pipeline)
- destroy_pipeline(old_pipeline);
-}
-
-static void cmd_reload_ini()
-{
- struct ini *old_ini = global_ini;
- struct cras_dsp_context *ctx;
-
- struct ini *new_ini = cras_dsp_ini_create(ini_filename);
- if (!new_ini) {
- syslog(LOG_DEBUG, "cannot create dsp ini");
- return;
- }
-
- DL_FOREACH (context_list, ctx) {
- cmd_load_pipeline(ctx, new_ini);
- }
-
- global_ini = new_ini;
-
- if (old_ini)
- cras_dsp_ini_free(old_ini);
-}
-
-/* Exported functions */
-
-void cras_dsp_init(const char *filename)
-{
- dsp_enable_flush_denormal_to_zero();
- ini_filename = strdup(filename);
- syslog_dumper = syslog_dumper_create(LOG_ERR);
- cmd_reload_ini();
-}
-
-void cras_dsp_stop()
-{
- syslog_dumper_free(syslog_dumper);
- if (ini_filename)
- free((char *)ini_filename);
- if (global_ini) {
- cras_dsp_ini_free(global_ini);
- global_ini = NULL;
- }
-}
-
-struct cras_dsp_context *cras_dsp_context_new(int sample_rate,
- const char *purpose)
-{
- struct cras_dsp_context *ctx = calloc(1, sizeof(*ctx));
-
- pthread_mutex_init(&ctx->mutex, NULL);
- initialize_environment(&ctx->env);
- ctx->sample_rate = sample_rate;
- ctx->purpose = strdup(purpose);
-
- DL_APPEND(context_list, ctx);
- return ctx;
-}
-
-void cras_dsp_context_free(struct cras_dsp_context *ctx)
-{
- DL_DELETE(context_list, ctx);
-
- pthread_mutex_destroy(&ctx->mutex);
- if (ctx->pipeline) {
- destroy_pipeline(ctx->pipeline);
- ctx->pipeline = NULL;
- }
- cras_expr_env_free(&ctx->env);
- free((char *)ctx->purpose);
- free(ctx);
-}
-
-void cras_dsp_set_variable_string(struct cras_dsp_context *ctx, const char *key,
- const char *value)
-{
- cras_expr_env_set_variable_string(&ctx->env, key, value);
-}
-
-void cras_dsp_set_variable_boolean(struct cras_dsp_context *ctx,
- const char *key, char value)
-{
- cras_expr_env_set_variable_boolean(&ctx->env, key, value);
-}
-
-void cras_dsp_load_pipeline(struct cras_dsp_context *ctx)
-{
- cmd_load_pipeline(ctx, global_ini);
-}
-
-void cras_dsp_load_mock_pipeline(struct cras_dsp_context *ctx,
- unsigned int num_channels)
-{
- struct ini *mock_ini;
- mock_ini = create_mock_ini(ctx->purpose, num_channels);
- if (mock_ini == NULL)
- syslog(LOG_ERR, "Failed to create mock ini");
- else
- cmd_load_pipeline(ctx, mock_ini);
-}
-
-struct pipeline *cras_dsp_get_pipeline(struct cras_dsp_context *ctx)
-{
- pthread_mutex_lock(&ctx->mutex);
- if (!ctx->pipeline) {
- pthread_mutex_unlock(&ctx->mutex);
- return NULL;
- }
- return ctx->pipeline;
-}
-
-void cras_dsp_put_pipeline(struct cras_dsp_context *ctx)
-{
- pthread_mutex_unlock(&ctx->mutex);
-}
-
-void cras_dsp_reload_ini()
-{
- cmd_reload_ini();
-}
-
-void cras_dsp_dump_info()
-{
- struct pipeline *pipeline;
- struct cras_dsp_context *ctx;
-
- if (global_ini)
- cras_dsp_ini_dump(syslog_dumper, global_ini);
- DL_FOREACH (context_list, ctx) {
- cras_expr_env_dump(syslog_dumper, &ctx->env);
- pipeline = ctx->pipeline;
- if (pipeline)
- cras_dsp_pipeline_dump(syslog_dumper, pipeline);
- }
-}
-
-unsigned int cras_dsp_num_output_channels(const struct cras_dsp_context *ctx)
-{
- return cras_dsp_pipeline_get_num_output_channels(ctx->pipeline);
-}
-
-unsigned int cras_dsp_num_input_channels(const struct cras_dsp_context *ctx)
-{
- return cras_dsp_pipeline_get_num_input_channels(ctx->pipeline);
-}
diff --git a/cras/src/server/cras_dsp.h b/cras/src/server/cras_dsp.h
deleted file mode 100644
index 366e2e67..00000000
--- a/cras/src/server/cras_dsp.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DSP_H_
-#define CRAS_DSP_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "cras_dsp_pipeline.h"
-
-struct cras_dsp_context;
-
-/* Starts the dsp subsystem. It starts a thread internally to load the
- * plugins. This should be called before other functions.
- * Args:
- * filename - The ini file where the dsp plugin graph should be read from.
- */
-void cras_dsp_init(const char *filename);
-
-/* Stops the dsp subsystem. */
-void cras_dsp_stop();
-
-/* Creates a dsp context. The context holds a pipeline and its
- * parameters. To use the pipeline in the context, first use
- * cras_dsp_load_pipeline() to load it and then use
- * cras_dsp_get_pipeline() to lock it for access.
- * Args:
- * sample_rate - The sampling rate of the pipeline.
- * purpose - The purpose of the pipeline, "playback" or "capture".
- * Returns:
- * A pointer to the dsp context.
- */
-struct cras_dsp_context *cras_dsp_context_new(int sample_rate,
- const char *purpose);
-
-/* Frees a dsp context. */
-void cras_dsp_context_free(struct cras_dsp_context *ctx);
-
-/* Sets a configuration string variable in the context. */
-void cras_dsp_set_variable_string(struct cras_dsp_context *ctx, const char *key,
- const char *value);
-
-/* Sets a configuration boolean variable in the context. */
-void cras_dsp_set_variable_boolean(struct cras_dsp_context *ctx,
- const char *key, char value);
-
-/* Loads the pipeline to the context. This should be called again when
- * new values of configuration variables may change the plugin
- * graph. The actual loading happens in another thread to avoid
- * blocking the audio thread. */
-void cras_dsp_load_pipeline(struct cras_dsp_context *ctx);
-
-/* Loads a mock pipeline of source directly connects to sink, of given
- * number of channels.
- */
-void cras_dsp_load_mock_pipeline(struct cras_dsp_context *ctx,
- unsigned int num_channels);
-
-/* Locks the pipeline in the context for access. Returns NULL if the
- * pipeline is still being loaded or cannot be loaded. */
-struct pipeline *cras_dsp_get_pipeline(struct cras_dsp_context *ctx);
-
-/* Releases the pipeline in the context. This must be called in pair
- * with cras_dsp_get_pipeline() once the client finishes using the
- * pipeline. This should be called in the same thread as
- * cras_dsp_get_pipeline() was called. */
-void cras_dsp_put_pipeline(struct cras_dsp_context *ctx);
-
-/* Re-reads the ini file and reloads all pipelines in the system. */
-void cras_dsp_reload_ini();
-
-/* Dump current dsp information to syslog. */
-void cras_dsp_dump_info();
-
-/* Number of channels output. */
-unsigned int cras_dsp_num_output_channels(const struct cras_dsp_context *ctx);
-
-/* Number of channels input. */
-unsigned int cras_dsp_num_input_channels(const struct cras_dsp_context *ctx);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_DSP_H_ */
diff --git a/cras/src/server/cras_dsp_ini.c b/cras/src/server/cras_dsp_ini.c
deleted file mode 100644
index a331acf8..00000000
--- a/cras/src/server/cras_dsp_ini.c
+++ /dev/null
@@ -1,492 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <stdlib.h>
-#include <syslog.h>
-#include "cras_dsp_ini.h"
-#include "iniparser_wrapper.h"
-
-#define MAX_NR_PORT 128 /* the max number of ports for a plugin */
-#define MAX_PORT_NAME_LENGTH 20 /* names like "output_32" */
-#define MAX_MOCK_INI_CH 20 /* Max number of channels to create mock ini */
-
-/* Format of the ini file (See dsp.ini.sample for an example).
-
-- Each section in the ini file specifies a plugin. The section name is
- just an identifier. The "library" and "label" attributes in a
- section must be defined. The "library" attribute is the name of the
- shared library from which this plugin will be loaded, or a special
- value "builtin" for built-in plugins. The "label" attribute specify
- which plugin inside the shared library should be loaded.
-
-- Built-in plugins have an attribute "label" which has value "source"
- or "sink". It defines where the audio data flows into and flows out
- of the pipeline. Built-in plugins also have a attribute "purpose"
- which has the value "playback" or "capture". It defines which
- pipeline these plugins belong to.
-
-- Each plugin can have an optional "disable expression", which defines
- under which conditions the plugin is disabled.
-
-- Each plugin have some ports which specify the parameters for the
- plugin or to specify connections to other plugins. The ports in each
- plugin are numbered from 0. Each port is either an input port or an
- output port, and each port is either an audio port or a control
- port. The connections between two ports are expressed by giving the
- same value to both ports. For audio ports, the value should be
- "{identifier}". For control ports, the value shoule be
- "<identifier>". For example, the following fragment
-
- [plugin1]
- ...
- output_4={audio_left}
- output_5={audio_right}
-
- [plugin2]
- ...
- input_0={audio_left}
-
- [plugin3]
- ...
- input_2={audio_right}
-
- specifies these connections:
- port 4 of plugin1 --> port 0 of plugin2
- port 5 of plugin1 --> port 2 of plugin3
-
-*/
-
-static const char *getstring(struct ini *ini, const char *sec_name,
- const char *key)
-{
- char full_key[MAX_INI_KEY_LENGTH + 1];
- snprintf(full_key, sizeof(full_key), "%s:%s", sec_name, key);
- return iniparser_getstring(ini->dict, full_key, NULL);
-}
-
-static int lookup_flow(struct ini *ini, const char *name)
-{
- int i;
- const struct flow *flow;
-
- ARRAY_ELEMENT_FOREACH (&ini->flows, i, flow) {
- if (strcmp(flow->name, name) == 0)
- return i;
- }
-
- return -1;
-}
-
-static int lookup_or_add_flow(struct ini *ini, const char *name)
-{
- struct flow *flow;
- int i = lookup_flow(ini, name);
- if (i != -1)
- return i;
- i = ARRAY_COUNT(&ini->flows);
- flow = ARRAY_APPEND_ZERO(&ini->flows);
- flow->name = name;
- return i;
-}
-
-static int parse_ports(struct ini *ini, const char *sec_name,
- struct plugin *plugin)
-{
- char key[MAX_PORT_NAME_LENGTH];
- const char *str;
- int i;
- struct port *p;
- int direction;
-
- for (i = 0; i < MAX_NR_PORT; i++) {
- direction = PORT_INPUT;
- snprintf(key, sizeof(key), "input_%d", i);
- str = getstring(ini, sec_name, key);
- if (str == NULL) {
- direction = PORT_OUTPUT;
- snprintf(key, sizeof(key), "output_%d", i);
- str = getstring(ini, sec_name, key);
- if (str == NULL)
- break; /* no more ports */
- }
-
- if (*str == '\0') {
- syslog(LOG_ERR, "empty value for %s:%s", sec_name, key);
- return -1;
- }
-
- if (str[0] == '<' || str[0] == '{') {
- p = ARRAY_APPEND_ZERO(&plugin->ports);
- p->type = (str[0] == '<') ? PORT_CONTROL : PORT_AUDIO;
- p->flow_id = lookup_or_add_flow(ini, str);
- p->init_value = 0;
- } else {
- char *endptr;
- float init_value = strtof(str, &endptr);
- if (endptr == str) {
- syslog(LOG_ERR, "cannot parse number from '%s'",
- str);
- }
- p = ARRAY_APPEND_ZERO(&plugin->ports);
- p->type = PORT_CONTROL;
- p->flow_id = INVALID_FLOW_ID;
- p->init_value = init_value;
- }
- p->direction = direction;
- }
-
- return 0;
-}
-
-static int parse_plugin_section(struct ini *ini, const char *sec_name,
- struct plugin *p)
-{
- p->title = sec_name;
- p->library = getstring(ini, sec_name, "library");
- p->label = getstring(ini, sec_name, "label");
- p->purpose = getstring(ini, sec_name, "purpose");
- p->disable_expr =
- cras_expr_expression_parse(getstring(ini, sec_name, "disable"));
-
- if (p->library == NULL || p->label == NULL) {
- syslog(LOG_ERR, "A plugin must have library and label: %s",
- sec_name);
- return -1;
- }
-
- if (parse_ports(ini, sec_name, p) < 0) {
- syslog(LOG_ERR, "Failed to parse ports: %s", sec_name);
- return -1;
- }
-
- return 0;
-}
-
-static void fill_flow_info(struct ini *ini)
-{
- int i, j;
- struct plugin *plugin;
- struct port *port;
- struct flow *flow;
- struct plugin **pplugin;
- int *pport;
-
- ARRAY_ELEMENT_FOREACH (&ini->plugins, i, plugin) {
- ARRAY_ELEMENT_FOREACH (&plugin->ports, j, port) {
- int flow_id = port->flow_id;
- if (flow_id == INVALID_FLOW_ID)
- continue;
- flow = ARRAY_ELEMENT(&ini->flows, flow_id);
- flow->type = port->type;
- if (port->direction == PORT_INPUT) {
- pplugin = &flow->to;
- pport = &flow->to_port;
- } else {
- pplugin = &flow->from;
- pport = &flow->from_port;
- }
- *pplugin = plugin;
- *pport = j;
- }
- }
-}
-
-/* Adds a port to a plugin with specified flow id and direction. */
-static void add_audio_port(struct ini *ini, struct plugin *plugin, int flow_id,
- enum port_direction port_direction)
-{
- struct port *p;
- p = ARRAY_APPEND_ZERO(&plugin->ports);
- p->type = PORT_AUDIO;
- p->flow_id = flow_id;
- p->init_value = 0;
- p->direction = port_direction;
-}
-
-/* Fills fields for a swap_lr plugin.*/
-static void fill_swap_lr_plugin(struct ini *ini, struct plugin *plugin,
- int input_flowid_0, int input_flowid_1,
- int output_flowid_0, int output_flowid_1)
-{
- plugin->title = "swap_lr";
- plugin->library = "builtin";
- plugin->label = "swap_lr";
- plugin->purpose = "playback";
- plugin->disable_expr = cras_expr_expression_parse("swap_lr_disabled");
-
- add_audio_port(ini, plugin, input_flowid_0, PORT_INPUT);
- add_audio_port(ini, plugin, input_flowid_1, PORT_INPUT);
- add_audio_port(ini, plugin, output_flowid_0, PORT_OUTPUT);
- add_audio_port(ini, plugin, output_flowid_1, PORT_OUTPUT);
-}
-
-/* Adds a new flow with name. If there is already a flow with the name, returns
- * INVALID_FLOW_ID.
- */
-static int add_new_flow(struct ini *ini, const char *name)
-{
- struct flow *flow;
- int i = lookup_flow(ini, name);
- if (i != -1)
- return INVALID_FLOW_ID;
- i = ARRAY_COUNT(&ini->flows);
- flow = ARRAY_APPEND_ZERO(&ini->flows);
- flow->name = name;
- return i;
-}
-
-/* Finds the first playback sink plugin in ini. */
-struct plugin *find_first_playback_sink_plugin(struct ini *ini)
-{
- int i;
- struct plugin *plugin;
-
- ARRAY_ELEMENT_FOREACH (&ini->plugins, i, plugin) {
- if (strcmp(plugin->library, "builtin") != 0)
- continue;
- if (strcmp(plugin->label, "sink") != 0)
- continue;
- if (!plugin->purpose ||
- strcmp(plugin->purpose, "playback") != 0)
- continue;
- return plugin;
- }
-
- return NULL;
-}
-
-/* Inserts a swap_lr plugin before sink. Handles the port change such that
- * the port originally connects to sink will connect to swap_lr.
- */
-static int insert_swap_lr_plugin(struct ini *ini)
-{
- struct plugin *swap_lr, *sink;
- int sink_input_flowid_0, sink_input_flowid_1;
- int swap_lr_output_flowid_0, swap_lr_output_flowid_1;
-
- /* Only add swap_lr plugin for two-channel playback dsp.
- * TODO(cychiang): Handle multiple sinks if needed.
- */
- sink = find_first_playback_sink_plugin(ini);
- if ((sink == NULL) || ARRAY_COUNT(&sink->ports) != 2)
- return 0;
-
- /* Gets the original flow ids of the sink input ports. */
- sink_input_flowid_0 = ARRAY_ELEMENT(&sink->ports, 0)->flow_id;
- sink_input_flowid_1 = ARRAY_ELEMENT(&sink->ports, 1)->flow_id;
-
- /* Create new flow ids for swap_lr output ports. */
- swap_lr_output_flowid_0 = add_new_flow(ini, "{swap_lr_out:0}");
- swap_lr_output_flowid_1 = add_new_flow(ini, "{swap_lr_out:1}");
-
- if (swap_lr_output_flowid_0 == INVALID_FLOW_ID ||
- swap_lr_output_flowid_1 == INVALID_FLOW_ID) {
- syslog(LOG_ERR, "Can not create flow id for swap_lr_out");
- return -EINVAL;
- }
-
- /* Creates a swap_lr plugin and sets the input and output ports. */
- swap_lr = ARRAY_APPEND_ZERO(&ini->plugins);
- fill_swap_lr_plugin(ini, swap_lr, sink_input_flowid_0,
- sink_input_flowid_1, swap_lr_output_flowid_0,
- swap_lr_output_flowid_1);
-
- /* Look up first sink again because ini->plugins could be realloc'ed */
- sink = find_first_playback_sink_plugin(ini);
-
- /* The flow ids of sink input ports should be changed to flow ids of
- * {swap_lr_out:0}, {swap_lr_out:1}. */
- ARRAY_ELEMENT(&sink->ports, 0)->flow_id = swap_lr_output_flowid_0;
- ARRAY_ELEMENT(&sink->ports, 1)->flow_id = swap_lr_output_flowid_1;
-
- return 0;
-}
-
-struct ini *create_mock_ini(const char *purpose, unsigned int num_channels)
-{
- static char mock_flow_names[MAX_MOCK_INI_CH][9] = {
- "{tmp:0}", "{tmp:1}", "{tmp:2}", "{tmp:3}", "{tmp:4}",
- "{tmp:5}", "{tmp:6}", "{tmp:7}", "{tmp:8}", "{tmp:9}",
- "{tmp:10}", "{tmp:11}", "{tmp:12}", "{tmp:13}", "{tmp:14}",
- "{tmp:15}", "{tmp:16}", "{tmp:17}", "{tmp:18}", "{tmp:19}",
- };
- struct ini *ini;
- struct plugin *source, *sink;
- int tmp_flow_ids[MAX_MOCK_INI_CH];
- int i;
-
- if (num_channels > MAX_MOCK_INI_CH) {
- syslog(LOG_ERR, "Unable to create %u channels of mock ini",
- num_channels);
- return NULL;
- }
-
- ini = calloc(1, sizeof(struct ini));
- if (!ini) {
- syslog(LOG_ERR, "no memory for ini struct");
- return NULL;
- }
-
- for (i = 0; i < num_channels; i++)
- tmp_flow_ids[i] = add_new_flow(ini, mock_flow_names[i]);
-
- source = ARRAY_APPEND_ZERO(&ini->plugins);
- source->title = "source";
- source->library = "builtin";
- source->label = "source";
- source->purpose = purpose;
-
- for (i = 0; i < num_channels; i++)
- add_audio_port(ini, source, tmp_flow_ids[i], PORT_OUTPUT);
-
- sink = ARRAY_APPEND_ZERO(&ini->plugins);
- sink->title = "sink";
- sink->library = "builtin";
- sink->label = "sink";
- sink->purpose = purpose;
-
- for (i = 0; i < num_channels; i++)
- add_audio_port(ini, sink, tmp_flow_ids[i], PORT_INPUT);
-
- fill_flow_info(ini);
-
- return ini;
-}
-
-struct ini *cras_dsp_ini_create(const char *ini_filename)
-{
- struct ini *ini;
- dictionary *dict;
- int nsec, i;
- const char *sec_name;
- struct plugin *plugin;
- int rc;
-
- ini = calloc(1, sizeof(struct ini));
- if (!ini) {
- syslog(LOG_ERR, "no memory for ini struct");
- return NULL;
- }
-
- dict = iniparser_load_wrapper((char *)ini_filename);
- if (!dict) {
- syslog(LOG_DEBUG, "no ini file %s", ini_filename);
- goto bail;
- }
- ini->dict = dict;
-
- /* Parse the plugin sections */
- nsec = iniparser_getnsec(dict);
- for (i = 0; i < nsec; i++) {
- sec_name = iniparser_getsecname(dict, i);
- plugin = ARRAY_APPEND_ZERO(&ini->plugins);
- if (parse_plugin_section(ini, sec_name, plugin) < 0)
- goto bail;
- }
-
- /* Insert a swap_lr plugin before sink. */
- rc = insert_swap_lr_plugin(ini);
- if (rc < 0) {
- syslog(LOG_ERR, "failed to insert swap_lr plugin");
- goto bail;
- }
-
- /* Fill flow info now because now the plugin array won't change */
- fill_flow_info(ini);
-
- return ini;
-bail:
- cras_dsp_ini_free(ini);
- return NULL;
-}
-
-void cras_dsp_ini_free(struct ini *ini)
-{
- struct plugin *p;
- int i;
-
- /* free plugins */
- ARRAY_ELEMENT_FOREACH (&ini->plugins, i, p) {
- cras_expr_expression_free(p->disable_expr);
- ARRAY_FREE(&p->ports);
- }
- ARRAY_FREE(&ini->plugins);
- ARRAY_FREE(&ini->flows);
-
- if (ini->dict) {
- iniparser_freedict(ini->dict);
- ini->dict = NULL;
- }
-
- free(ini);
-}
-
-static const char *port_direction_str(enum port_direction port_direction)
-{
- switch (port_direction) {
- case PORT_INPUT:
- return "input";
- case PORT_OUTPUT:
- return "output";
- default:
- return "unknown";
- }
-}
-
-static const char *port_type_str(enum port_type port_type)
-{
- switch (port_type) {
- case PORT_CONTROL:
- return "control";
- case PORT_AUDIO:
- return "audio";
- default:
- return "unknown";
- }
-}
-
-static const char *plugin_title(struct plugin *plugin)
-{
- if (plugin == NULL)
- return "(null)";
- return plugin->title;
-}
-
-void cras_dsp_ini_dump(struct dumper *d, struct ini *ini)
-{
- int i, j;
- struct plugin *plugin;
- struct port *port;
- const struct flow *flow;
-
- dumpf(d, "---- ini dump begin ---\n");
- dumpf(d, "ini->dict = %p\n", ini->dict);
-
- dumpf(d, "number of plugins = %d\n", ARRAY_COUNT(&ini->plugins));
- ARRAY_ELEMENT_FOREACH (&ini->plugins, i, plugin) {
- dumpf(d, "[plugin %d: %s]\n", i, plugin->title);
- dumpf(d, "library=%s\n", plugin->library);
- dumpf(d, "label=%s\n", plugin->label);
- dumpf(d, "purpose=%s\n", plugin->purpose);
- dumpf(d, "disable=%p\n", plugin->disable_expr);
- ARRAY_ELEMENT_FOREACH (&plugin->ports, j, port) {
- dumpf(d,
- " [%s port %d] type=%s, flow_id=%d, value=%g\n",
- port_direction_str(port->direction), j,
- port_type_str(port->type), port->flow_id,
- port->init_value);
- }
- }
-
- dumpf(d, "number of flows = %d\n", ARRAY_COUNT(&ini->flows));
- ARRAY_ELEMENT_FOREACH (&ini->flows, i, flow) {
- dumpf(d, " [flow %d] %s, %s, %s:%d -> %s:%d\n", i, flow->name,
- port_type_str(flow->type), plugin_title(flow->from),
- flow->from_port, plugin_title(flow->to), flow->to_port);
- }
-
- dumpf(d, "---- ini dump end ----\n");
-}
diff --git a/cras/src/server/cras_dsp_ini.h b/cras/src/server/cras_dsp_ini.h
deleted file mode 100644
index c839d4b0..00000000
--- a/cras/src/server/cras_dsp_ini.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DSP_INI_H_
-#define CRAS_DSP_INI_H_
-
-#include "iniparser_wrapper.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "array.h"
-#include "dumper.h"
-#include "cras_expr.h"
-
-enum port_direction {
- PORT_INPUT,
- PORT_OUTPUT,
-};
-
-enum port_type {
- PORT_CONTROL,
- PORT_AUDIO,
-};
-
-#define INVALID_FLOW_ID -1
-
-struct port {
- enum port_direction direction;
- enum port_type type;
-
- /* This is only used if there is a flow connects to this port,
- -1 otherwise (i.e. the port has a constant input/output) */
- int flow_id;
-
- /* This is only used if type is PORT_CONTROL */
- float init_value;
-};
-
-DECLARE_ARRAY_TYPE(struct port, port_array)
-
-struct plugin {
- const char *title;
- const char *library; /* file name like "plugin.so" */
- const char *label; /* label like "Eq" */
- const char *purpose; /* like "playback" or "capture" */
- struct cras_expr_expression *disable_expr; /* the disable expression of
- this plugin */
- port_array ports;
-};
-
-struct flow {
- enum port_type type; /* the type of the ports this flow connects to */
- const char *name;
- struct plugin *from;
- struct plugin *to;
- int from_port;
- int to_port;
-};
-
-DECLARE_ARRAY_TYPE(struct plugin, plugin_array)
-DECLARE_ARRAY_TYPE(struct flow, flow_array)
-
-struct ini {
- dictionary *dict;
- plugin_array plugins;
- flow_array flows;
-};
-
-/*
- * Creates a mock ini structure equivalent to:
- *
- * [src]
- * out0={tmp:0}
- * out1={tmp:1}
- * ...
- *
- * [sink]
- * in0={tmp:0}
- * in1={tmp:1}
- * ...
- *
- * The caller of this function is responsible to free the returned
- * ini by calling cras_dsp_ini_free().
- */
-struct ini *create_mock_ini(const char *purpose, unsigned int num_channels);
-
-/* Reads the ini file into the ini structure */
-struct ini *cras_dsp_ini_create(const char *ini_filename);
-/* Frees the dsp structure. */
-void cras_dsp_ini_free(struct ini *ini);
-/* Dumps the information in the ini structure to syslog. */
-void cras_dsp_ini_dump(struct dumper *d, struct ini *ini);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_DSP_INI_H_ */
diff --git a/cras/src/server/cras_dsp_mod_builtin.c b/cras/src/server/cras_dsp_mod_builtin.c
deleted file mode 100644
index 296c0eba..00000000
--- a/cras/src/server/cras_dsp_mod_builtin.c
+++ /dev/null
@@ -1,631 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include "cras_dsp_module.h"
-#include "drc.h"
-#include "dsp_util.h"
-#include "dcblock.h"
-#include "eq.h"
-#include "eq2.h"
-
-/*
- * empty module functions (for source and sink)
- */
-static int empty_instantiate(struct dsp_module *module,
- unsigned long sample_rate)
-{
- return 0;
-}
-
-static void empty_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
-}
-
-static int empty_get_delay(struct dsp_module *module)
-{
- return 0;
-}
-
-static void empty_run(struct dsp_module *module, unsigned long sample_count)
-{
-}
-
-static void empty_deinstantiate(struct dsp_module *module)
-{
-}
-
-static void empty_free_module(struct dsp_module *module)
-{
- free(module);
-}
-
-static int empty_get_properties(struct dsp_module *module)
-{
- return 0;
-}
-
-static void empty_dump(struct dsp_module *module, struct dumper *d)
-{
- dumpf(d, "built-in module\n");
-}
-
-static void empty_init_module(struct dsp_module *module)
-{
- module->instantiate = &empty_instantiate;
- module->connect_port = &empty_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &empty_run;
- module->deinstantiate = &empty_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-/*
- * swap_lr module functions
- */
-static int swap_lr_instantiate(struct dsp_module *module,
- unsigned long sample_rate)
-{
- module->data = calloc(4, sizeof(float *));
- return 0;
-}
-
-static void swap_lr_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- float **ports;
- ports = (float **)module->data;
- ports[port] = data_location;
-}
-
-static void swap_lr_run(struct dsp_module *module, unsigned long sample_count)
-{
- size_t i;
- float **ports = (float **)module->data;
-
- /* This module runs dsp in-place, so ports[0] == ports[2],
- * ports[1] == ports[3]. Here we swap data on two channels.
- */
- for (i = 0; i < sample_count; i++) {
- float temp = ports[0][i];
- ports[2][i] = ports[1][i];
- ports[3][i] = temp;
- }
-}
-
-static void swap_lr_deinstantiate(struct dsp_module *module)
-{
- free(module->data);
-}
-
-static void swap_lr_init_module(struct dsp_module *module)
-{
- module->instantiate = &swap_lr_instantiate;
- module->connect_port = &swap_lr_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &swap_lr_run;
- module->deinstantiate = &swap_lr_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
-}
-
-/*
- * invert_lr module functions
- */
-static int invert_lr_instantiate(struct dsp_module *module,
- unsigned long sample_rate)
-{
- module->data = calloc(4, sizeof(float *));
- return 0;
-}
-
-static void invert_lr_connect_port(struct dsp_module *module,
- unsigned long port, float *data_location)
-{
- float **ports;
- ports = (float **)module->data;
- ports[port] = data_location;
-}
-
-static void invert_lr_run(struct dsp_module *module, unsigned long sample_count)
-{
- size_t i;
- float **ports = (float **)module->data;
-
- for (i = 0; i < sample_count; i++) {
- ports[2][i] = -ports[0][i];
- ports[3][i] = ports[1][i];
- }
-}
-
-static void invert_lr_deinstantiate(struct dsp_module *module)
-{
- free(module->data);
-}
-
-static void invert_lr_init_module(struct dsp_module *module)
-{
- module->instantiate = &invert_lr_instantiate;
- module->connect_port = &invert_lr_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &invert_lr_run;
- module->deinstantiate = &invert_lr_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
-}
-
-/*
- * mix_stereo module functions
- */
-static int mix_stereo_instantiate(struct dsp_module *module,
- unsigned long sample_rate)
-{
- module->data = calloc(4, sizeof(float *));
- return 0;
-}
-
-static void mix_stereo_connect_port(struct dsp_module *module,
- unsigned long port, float *data_location)
-{
- float **ports;
- ports = (float **)module->data;
- ports[port] = data_location;
-}
-
-static void mix_stereo_run(struct dsp_module *module,
- unsigned long sample_count)
-{
- size_t i;
- float tmp;
- float **ports = (float **)module->data;
-
- for (i = 0; i < sample_count; i++) {
- tmp = ports[0][i] + ports[1][i];
- ports[2][i] = tmp;
- ports[3][i] = tmp;
- }
-}
-
-static void mix_stereo_deinstantiate(struct dsp_module *module)
-{
- free(module->data);
-}
-
-static void mix_stereo_init_module(struct dsp_module *module)
-{
- module->instantiate = &mix_stereo_instantiate;
- module->connect_port = &mix_stereo_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &mix_stereo_run;
- module->deinstantiate = &mix_stereo_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-/*
- * dcblock module functions
- */
-struct dcblock_data {
- struct dcblock *dcblockl;
- struct dcblock *dcblockr;
- unsigned long sample_rate;
-
- /* One port for input, one for output, and 1 parameter */
- float *ports[5];
-};
-
-static int dcblock_instantiate(struct dsp_module *module,
- unsigned long sample_rate)
-{
- struct dcblock_data *data;
-
- module->data = calloc(1, sizeof(struct dcblock_data));
- data = (struct dcblock_data *)module->data;
- data->sample_rate = sample_rate;
-
- return 0;
-}
-
-static void dcblock_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- struct dcblock_data *data = (struct dcblock_data *)module->data;
- data->ports[port] = data_location;
-}
-
-static void dcblock_run(struct dsp_module *module, unsigned long sample_count)
-{
- struct dcblock_data *data = (struct dcblock_data *)module->data;
- if (!data->dcblockl)
- data->dcblockl =
- dcblock_new(*data->ports[4], data->sample_rate);
- if (!data->dcblockr)
- data->dcblockr =
- dcblock_new(*data->ports[4], data->sample_rate);
- if (data->ports[0] != data->ports[2])
- memcpy(data->ports[2], data->ports[0],
- sizeof(float) * sample_count);
- if (data->ports[1] != data->ports[3])
- memcpy(data->ports[3], data->ports[1],
- sizeof(float) * sample_count);
-
- dcblock_process(data->dcblockl, data->ports[2], (int)sample_count);
- dcblock_process(data->dcblockr, data->ports[3], (int)sample_count);
-}
-
-static void dcblock_deinstantiate(struct dsp_module *module)
-{
- struct dcblock_data *data = (struct dcblock_data *)module->data;
- if (data->dcblockl)
- dcblock_free(data->dcblockl);
- if (data->dcblockr)
- dcblock_free(data->dcblockr);
- free(data);
-}
-
-static void dcblock_init_module(struct dsp_module *module)
-{
- module->instantiate = &dcblock_instantiate;
- module->connect_port = &dcblock_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &dcblock_run;
- module->deinstantiate = &dcblock_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-/*
- * eq module functions
- */
-struct eq_data {
- int sample_rate;
- struct eq *eq; /* Initialized in the first call of eq_run() */
-
- /* One port for input, one for output, and 4 parameters per eq */
- float *ports[2 + MAX_BIQUADS_PER_EQ * 4];
-};
-
-static int eq_instantiate(struct dsp_module *module, unsigned long sample_rate)
-{
- struct eq_data *data;
-
- module->data = calloc(1, sizeof(struct eq_data));
- data = (struct eq_data *)module->data;
- data->sample_rate = (int)sample_rate;
- return 0;
-}
-
-static void eq_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- struct eq_data *data = (struct eq_data *)module->data;
- data->ports[port] = data_location;
-}
-
-static void eq_run(struct dsp_module *module, unsigned long sample_count)
-{
- struct eq_data *data = (struct eq_data *)module->data;
- if (!data->eq) {
- float nyquist = data->sample_rate / 2;
- int i;
-
- data->eq = eq_new();
- for (i = 2; i < 2 + MAX_BIQUADS_PER_EQ * 4; i += 4) {
- if (!data->ports[i])
- break;
- int type = (int)*data->ports[i];
- float freq = *data->ports[i + 1];
- float Q = *data->ports[i + 2];
- float gain = *data->ports[i + 3];
- eq_append_biquad(data->eq, type, freq / nyquist, Q,
- gain);
- }
- }
- if (data->ports[0] != data->ports[1])
- memcpy(data->ports[1], data->ports[0],
- sizeof(float) * sample_count);
- eq_process(data->eq, data->ports[1], (int)sample_count);
-}
-
-static void eq_deinstantiate(struct dsp_module *module)
-{
- struct eq_data *data = (struct eq_data *)module->data;
- if (data->eq)
- eq_free(data->eq);
- free(data);
-}
-
-static void eq_init_module(struct dsp_module *module)
-{
- module->instantiate = &eq_instantiate;
- module->connect_port = &eq_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &eq_run;
- module->deinstantiate = &eq_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-/*
- * eq2 module functions
- */
-struct eq2_data {
- int sample_rate;
- struct eq2 *eq2; /* Initialized in the first call of eq2_run() */
-
- /* Two ports for input, two for output, and 8 parameters per eq pair */
- float *ports[4 + MAX_BIQUADS_PER_EQ2 * 8];
-};
-
-static int eq2_instantiate(struct dsp_module *module, unsigned long sample_rate)
-{
- struct eq2_data *data;
-
- module->data = calloc(1, sizeof(struct eq2_data));
- data = (struct eq2_data *)module->data;
- data->sample_rate = (int)sample_rate;
- return 0;
-}
-
-static void eq2_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- struct eq2_data *data = (struct eq2_data *)module->data;
- data->ports[port] = data_location;
-}
-
-static void eq2_run(struct dsp_module *module, unsigned long sample_count)
-{
- struct eq2_data *data = (struct eq2_data *)module->data;
- if (!data->eq2) {
- float nyquist = data->sample_rate / 2;
- int i, channel;
-
- data->eq2 = eq2_new();
- for (i = 4; i < 4 + MAX_BIQUADS_PER_EQ2 * 8; i += 8) {
- if (!data->ports[i])
- break;
- for (channel = 0; channel < 2; channel++) {
- int k = i + channel * 4;
- int type = (int)*data->ports[k];
- float freq = *data->ports[k + 1];
- float Q = *data->ports[k + 2];
- float gain = *data->ports[k + 3];
- eq2_append_biquad(data->eq2, channel, type,
- freq / nyquist, Q, gain);
- }
- }
- }
-
- if (data->ports[0] != data->ports[2])
- memcpy(data->ports[2], data->ports[0],
- sizeof(float) * sample_count);
- if (data->ports[3] != data->ports[1])
- memcpy(data->ports[3], data->ports[1],
- sizeof(float) * sample_count);
-
- eq2_process(data->eq2, data->ports[2], data->ports[3],
- (int)sample_count);
-}
-
-static void eq2_deinstantiate(struct dsp_module *module)
-{
- struct eq2_data *data = (struct eq2_data *)module->data;
- if (data->eq2)
- eq2_free(data->eq2);
- free(data);
-}
-
-static void eq2_init_module(struct dsp_module *module)
-{
- module->instantiate = &eq2_instantiate;
- module->connect_port = &eq2_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &eq2_run;
- module->deinstantiate = &eq2_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-/*
- * drc module functions
- */
-struct drc_data {
- int sample_rate;
- struct drc *drc; /* Initialized in the first call of drc_run() */
-
- /* Two ports for input, two for output, one for disable_emphasis,
- * and 8 parameters each band */
- float *ports[4 + 1 + 8 * 3];
-};
-
-static int drc_instantiate(struct dsp_module *module, unsigned long sample_rate)
-{
- struct drc_data *data;
-
- module->data = calloc(1, sizeof(struct drc_data));
- data = (struct drc_data *)module->data;
- data->sample_rate = (int)sample_rate;
- return 0;
-}
-
-static void drc_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- struct drc_data *data = (struct drc_data *)module->data;
- data->ports[port] = data_location;
-}
-
-static int drc_get_delay(struct dsp_module *module)
-{
- struct drc_data *data = (struct drc_data *)module->data;
- return DRC_DEFAULT_PRE_DELAY * data->sample_rate;
-}
-
-static void drc_run(struct dsp_module *module, unsigned long sample_count)
-{
- struct drc_data *data = (struct drc_data *)module->data;
- if (!data->drc) {
- int i;
- float nyquist = data->sample_rate / 2;
- struct drc *drc = drc_new(data->sample_rate);
-
- data->drc = drc;
- drc->emphasis_disabled = (int)*data->ports[4];
- for (i = 0; i < 3; i++) {
- int k = 5 + i * 8;
- float f = *data->ports[k];
- float enable = *data->ports[k + 1];
- float threshold = *data->ports[k + 2];
- float knee = *data->ports[k + 3];
- float ratio = *data->ports[k + 4];
- float attack = *data->ports[k + 5];
- float release = *data->ports[k + 6];
- float boost = *data->ports[k + 7];
- drc_set_param(drc, i, PARAM_CROSSOVER_LOWER_FREQ,
- f / nyquist);
- drc_set_param(drc, i, PARAM_ENABLED, enable);
- drc_set_param(drc, i, PARAM_THRESHOLD, threshold);
- drc_set_param(drc, i, PARAM_KNEE, knee);
- drc_set_param(drc, i, PARAM_RATIO, ratio);
- drc_set_param(drc, i, PARAM_ATTACK, attack);
- drc_set_param(drc, i, PARAM_RELEASE, release);
- drc_set_param(drc, i, PARAM_POST_GAIN, boost);
- }
- drc_init(drc);
- }
- if (data->ports[0] != data->ports[2])
- memcpy(data->ports[2], data->ports[0],
- sizeof(float) * sample_count);
- if (data->ports[1] != data->ports[3])
- memcpy(data->ports[3], data->ports[1],
- sizeof(float) * sample_count);
-
- drc_process(data->drc, &data->ports[2], (int)sample_count);
-}
-
-static void drc_deinstantiate(struct dsp_module *module)
-{
- struct drc_data *data = (struct drc_data *)module->data;
- if (data->drc)
- drc_free(data->drc);
- free(data);
-}
-
-static void drc_init_module(struct dsp_module *module)
-{
- module->instantiate = &drc_instantiate;
- module->connect_port = &drc_connect_port;
- module->get_delay = &drc_get_delay;
- module->run = &drc_run;
- module->deinstantiate = &drc_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-/*
- * sink module functions
- */
-struct sink_data {
- struct ext_dsp_module *ext_module;
- float *ports[MAX_EXT_DSP_PORTS];
-};
-
-static int sink_instantiate(struct dsp_module *module,
- unsigned long sample_rate)
-{
- module->data = (struct sink_data *)calloc(1, sizeof(struct sink_data));
- return 0;
-}
-
-static void sink_deinstantiate(struct dsp_module *module)
-{
- struct sink_data *data = (struct sink_data *)module->data;
- free(data);
-}
-
-static void sink_connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- struct sink_data *data = (struct sink_data *)module->data;
- data->ports[port] = data_location;
-}
-
-static void sink_run(struct dsp_module *module, unsigned long sample_count)
-{
- struct sink_data *data = (struct sink_data *)module->data;
-
- if (!data->ext_module)
- return;
- data->ext_module->run(data->ext_module, sample_count);
-}
-
-static void sink_init_module(struct dsp_module *module)
-{
- module->instantiate = &sink_instantiate;
- module->connect_port = &sink_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &sink_run;
- module->deinstantiate = &sink_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-void cras_dsp_module_set_sink_ext_module(struct dsp_module *module,
- struct ext_dsp_module *ext_module)
-{
- struct sink_data *data = (struct sink_data *)module->data;
- int i;
- data->ext_module = ext_module;
-
- if (data->ext_module == NULL)
- return;
-
- for (i = 0; i < MAX_EXT_DSP_PORTS; i++)
- ext_module->ports[i] = data->ports[i];
-}
-
-/*
- * builtin module dispatcher
- */
-struct dsp_module *cras_dsp_module_load_builtin(struct plugin *plugin)
-{
- struct dsp_module *module;
- if (strcmp(plugin->library, "builtin") != 0)
- return NULL;
-
- module = calloc(1, sizeof(struct dsp_module));
-
- if (strcmp(plugin->label, "mix_stereo") == 0) {
- mix_stereo_init_module(module);
- } else if (strcmp(plugin->label, "invert_lr") == 0) {
- invert_lr_init_module(module);
- } else if (strcmp(plugin->label, "dcblock") == 0) {
- dcblock_init_module(module);
- } else if (strcmp(plugin->label, "eq") == 0) {
- eq_init_module(module);
- } else if (strcmp(plugin->label, "eq2") == 0) {
- eq2_init_module(module);
- } else if (strcmp(plugin->label, "drc") == 0) {
- drc_init_module(module);
- } else if (strcmp(plugin->label, "swap_lr") == 0) {
- swap_lr_init_module(module);
- } else if (strcmp(plugin->label, "sink") == 0) {
- sink_init_module(module);
- } else {
- empty_init_module(module);
- }
-
- return module;
-}
diff --git a/cras/src/server/cras_dsp_mod_ladspa.c b/cras/src/server/cras_dsp_mod_ladspa.c
deleted file mode 100644
index 2ee15391..00000000
--- a/cras/src/server/cras_dsp_mod_ladspa.c
+++ /dev/null
@@ -1,217 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dlfcn.h>
-#include <syslog.h>
-#include <ladspa.h>
-
-#include "cras_dsp_module.h"
-
-#define PLUGIN_PATH_PREFIX "/usr/lib/ladspa"
-#define PLUGIN_PATH_MAX 256
-
-struct ladspa_data {
- void *dlopen_handle; /* the handle returned by dlopen() */
- const LADSPA_Descriptor *descriptor;
- LADSPA_Handle *handle; /* returned by instantiate() */
- int activated;
-};
-
-static void activate(struct dsp_module *module)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *desc = data->descriptor;
- data->activated = 1;
- if (!desc->activate)
- return;
- desc->activate(data->handle);
-}
-
-static void deactivate(struct dsp_module *module)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *desc = data->descriptor;
- data->activated = 0;
- if (!desc->deactivate)
- return;
- desc->deactivate(data->handle);
-}
-
-static int instantiate(struct dsp_module *module, unsigned long sample_rate)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *desc = data->descriptor;
-
- data->handle = desc->instantiate(desc, sample_rate);
- if (!data->handle) {
- syslog(LOG_ERR, "instantiate failed for %s, rate %ld",
- desc->Label, sample_rate);
- return -1;
- }
- return 0;
-}
-
-static void deinstantiate(struct dsp_module *module)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *desc = data->descriptor;
-
- if (data->activated)
- deactivate(module);
- desc->cleanup(data->handle);
- data->handle = NULL;
-}
-
-static void connect_port(struct dsp_module *module, unsigned long port,
- float *data_location)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *desc = data->descriptor;
- desc->connect_port(data->handle, port, data_location);
-}
-
-static int get_delay(struct dsp_module *module)
-{
- return 0;
-}
-
-static void run(struct dsp_module *module, unsigned long sample_count)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *desc = data->descriptor;
-
- if (!data->activated)
- activate(module);
- desc->run(data->handle, sample_count);
-}
-
-static void free_module(struct dsp_module *module)
-{
- struct ladspa_data *data = module->data;
- if (data->activated)
- deactivate(module);
- if (data->dlopen_handle) {
- dlclose(data->dlopen_handle);
- data->dlopen_handle = NULL;
- }
- free(module->data);
- free(module);
-}
-
-static int get_properties(struct dsp_module *module)
-{
- struct ladspa_data *data = module->data;
- int properties = 0;
- if (LADSPA_IS_INPLACE_BROKEN(data->descriptor->Properties))
- properties |= MODULE_INPLACE_BROKEN;
- return properties;
-}
-
-static void dump(struct dsp_module *module, struct dumper *d)
-{
- struct ladspa_data *data = module->data;
- const LADSPA_Descriptor *descriptor = data->descriptor;
-
- dumpf(d, " LADSPA: dlopen=%p, desc=%p, handle=%p, activated=%d\n",
- data->dlopen_handle, data->descriptor, data->handle,
- data->activated);
- if (descriptor) {
- dumpf(d, " Name=%s\n", descriptor->Name);
- dumpf(d, " Maker=%s\n", descriptor->Maker);
- }
-}
-
-static int verify_plugin_descriptor(struct plugin *plugin,
- const LADSPA_Descriptor *desc)
-{
- int i;
- struct port *port;
-
- if (desc->PortCount != ARRAY_COUNT(&plugin->ports)) {
- syslog(LOG_ERR, "port count mismatch: %s", plugin->title);
- return -1;
- }
-
- ARRAY_ELEMENT_FOREACH (&plugin->ports, i, port) {
- LADSPA_PortDescriptor port_desc = desc->PortDescriptors[i];
- if ((port->direction == PORT_INPUT) !=
- !!(port_desc & LADSPA_PORT_INPUT)) {
- syslog(LOG_ERR, "port direction mismatch: %s:%d!",
- plugin->title, i);
- return -1;
- }
-
- if ((port->type == PORT_CONTROL) !=
- !!(port_desc & LADSPA_PORT_CONTROL)) {
- syslog(LOG_ERR, "port type mismatch: %s:%d!",
- plugin->title, i);
- return -1;
- }
- }
-
- return 0;
-}
-
-struct dsp_module *cras_dsp_module_load_ladspa(struct plugin *plugin)
-{
- char path[PLUGIN_PATH_MAX];
- int index;
- LADSPA_Descriptor_Function desc_func;
- struct ladspa_data *data = calloc(1, sizeof(struct ladspa_data));
- struct dsp_module *module;
-
- snprintf(path, sizeof(path), "%s/%s", PLUGIN_PATH_PREFIX,
- plugin->library);
-
- data->dlopen_handle = dlopen(path, RTLD_NOW);
- if (!data->dlopen_handle) {
- syslog(LOG_ERR, "cannot open plugin from %s: %s", path,
- dlerror());
- goto bail;
- }
-
- desc_func = (LADSPA_Descriptor_Function)dlsym(data->dlopen_handle,
- "ladspa_descriptor");
-
- if (!desc_func) {
- syslog(LOG_ERR, "cannot find descriptor function from %s: %s",
- path, dlerror());
- goto bail;
- }
-
- for (index = 0;; index++) {
- const LADSPA_Descriptor *desc = desc_func(index);
- if (desc == NULL) {
- syslog(LOG_ERR, "cannot find label %s from %s",
- plugin->label, path);
- goto bail;
- }
- if (strcmp(desc->Label, plugin->label) == 0) {
- syslog(LOG_DEBUG, "plugin '%s' loaded from %s",
- plugin->label, path);
- if (verify_plugin_descriptor(plugin, desc) != 0)
- goto bail;
- data->descriptor = desc;
- break;
- }
- }
-
- module = calloc(1, sizeof(struct dsp_module));
- module->data = data;
- module->instantiate = &instantiate;
- module->connect_port = &connect_port;
- module->get_delay = &get_delay;
- module->run = &run;
- module->deinstantiate = &deinstantiate;
- module->get_properties = &get_properties;
- module->free_module = &free_module;
- module->dump = &dump;
- return module;
-bail:
- if (data->dlopen_handle)
- dlclose(data->dlopen_handle);
- free(data);
- return NULL;
-}
diff --git a/cras/src/server/cras_dsp_module.h b/cras/src/server/cras_dsp_module.h
deleted file mode 100644
index 53b9dca7..00000000
--- a/cras/src/server/cras_dsp_module.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DSP_MODULE_H_
-#define CRAS_DSP_MODULE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "cras_dsp_ini.h"
-
-#define MAX_EXT_DSP_PORTS 8
-
-/* Holds the functions we can use on a dsp module. */
-struct dsp_module {
- /* Opaque data used by the implementation of this module */
- void *data;
-
- /* Initializes the module for a given sampling rate. To change
- * the sampling rate, deinstantiate() must be called before
- * calling instantiate again.
- * Args:
- * sample_rate - The sampling rate for the audio data, like 44100.
- * Returns:
- * 0 if the initialization is successful. -1 otherwise.
- */
- int (*instantiate)(struct dsp_module *mod, unsigned long sample_rate);
-
- /* Assigns the memory location for a port of this module.
- * Args:
- * port - The index of the port.
- * data_location - The memory address of the data for this port.
- */
- void (*connect_port)(struct dsp_module *mod, unsigned long port,
- float *data_location);
-
- /* Returns the buffering delay of this module. This should be called
- * only after all input control ports have been connected.
- * Returns:
- * The buffering delay in frames. The value returned should only be
- * based on the sampling rate and the input control ports values and not
- * the audio data itself.
- */
- int (*get_delay)(struct dsp_module *mod);
-
- /* Processes a block of samples using this module. The memory
- * location for the input and output data are assigned by the
- * connect_port() call.
- * Args:
- * sample_count - The number of samples to be processed.
- */
- void (*run)(struct dsp_module *mod, unsigned long sample_count);
-
- /* Free resources used by the module. This module can be used
- * again by calling instantiate() */
- void (*deinstantiate)(struct dsp_module *mod);
-
- /* Frees all resources used by this module. After calling
- * free_module(), this struct dsp_module cannot be used
- * anymore.
- */
- void (*free_module)(struct dsp_module *mod);
-
- /* Returns special properties of this module, see the enum
- * below for details */
- int (*get_properties)(struct dsp_module *mod);
-
- /* Dumps the information about current state of this module */
- void (*dump)(struct dsp_module *mod, struct dumper *d);
-};
-
-/* An external module interface working with existing dsp pipeline.
- * __________ ___________ ____________ __________
- * | | | | | | | |
- * | |->| dsp mod |-> ...->| dsp mod | ---> | |
- * | device | |_________| |__________| | stream |
- * | | | ___________ | |
- * | | | | ext | | |
- * | | ->| dsp mod | -> | |
- * |________| |_________| |________|
- *
- * According to above diagram, an ext_dsp_module works by appending to
- * the sink of existing dsp pipeline. For audio input, this creates a
- * multiple output pipeline that stream can read processed buffer from.
- * This is useful for a stream to apply special processing effects while
- * sharing the common dsp with the other streams.
- *
- * Members:
- * ports - A list of ports can connect to existing dsp ports in a pipeline.
- * run - Processes |nframes| of data.
- * configure - Configures given external dsp module by the device buffer
- * size, rate, and number of channels of the format of the device that
- * the associated pipeline runs for.
- */
-struct ext_dsp_module {
- float *ports[MAX_EXT_DSP_PORTS];
- void (*run)(struct ext_dsp_module *ext, unsigned int nframes);
- void (*configure)(struct ext_dsp_module *ext, unsigned int buffer_size,
- unsigned int num_channels, unsigned int rate);
-};
-
-enum { MODULE_INPLACE_BROKEN = 1 }; /* See ladspa.h for explanation */
-
-/* Connects an external dsp module to a builtin sink module. */
-void cras_dsp_module_set_sink_ext_module(struct dsp_module *module,
- struct ext_dsp_module *ext_module);
-
-struct dsp_module *cras_dsp_module_load_ladspa(struct plugin *plugin);
-struct dsp_module *cras_dsp_module_load_builtin(struct plugin *plugin);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_DSP_MODULE_H_ */
diff --git a/cras/src/server/cras_dsp_pipeline.c b/cras/src/server/cras_dsp_pipeline.c
deleted file mode 100644
index 9e492ac5..00000000
--- a/cras/src/server/cras_dsp_pipeline.c
+++ /dev/null
@@ -1,1007 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <inttypes.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include "cras_util.h"
-#include "cras_dsp_module.h"
-#include "cras_dsp_pipeline.h"
-#include "dsp_util.h"
-
-/* We have a static representation of the dsp graph in a "struct ini",
- * and here we will construct a dynamic representation of it in a
- * "struct pipeline". The difference between the static one and the
- * dynamic one is that we will only include the subset of the dsp
- * graph actually needed in the dynamic one (so those plugins that are
- * disabled will not be included). Here are the mapping between the
- * static representation and the dynamic representation:
- *
- * static dynamic
- * ------------- --------------------------------------
- * struct ini struct pipeline
- * struct plugin struct instance
- * strict port struct audio_port, struct control_port
- *
- * For example, if the ini file specifies these plugins and their
- * connections:
- *
- * [A]
- * output_0={audio}
- * [B]
- * input_0={audio}
- * output_1={result}
- * [C]
- * input_0={result}
- *
- * That is, A connects to B, and B connects to C. If the plugin B is
- * now disabled, in the pipeline we construct there will only be two
- * instances (A and C) and the audio ports on these instances will
- * connect to each other directly, bypassing B.
- */
-
-/* This represents an audio port on an instance. */
-struct audio_port {
- struct audio_port *peer; /* the audio port this port connects to */
- struct plugin *plugin; /* the plugin corresponds to the instance */
- int original_index; /* the port index in the plugin */
- int buf_index; /* the buffer index in the pipeline */
-};
-
-/* This represents a control port on an instance. */
-struct control_port {
- struct control_port *peer; /* the control port this port connects to */
- struct plugin *plugin; /* the plugin corresponds to the instance */
- int original_index; /* the port index in the plugin */
- float value; /* the value of the control port */
-};
-
-DECLARE_ARRAY_TYPE(struct audio_port, audio_port_array);
-DECLARE_ARRAY_TYPE(struct control_port, control_port_array);
-
-/* An instance is a dynamic representation of a plugin. We only create
- * an instance when a plugin is needed (data actually flows through it
- * and it is not disabled). An instance also contains a pointer to a
- * struct dsp_module, which is the implementation of the plugin */
-struct instance {
- /* The plugin this instance corresponds to */
- struct plugin *plugin;
-
- /* These are the ports on this instance. The difference
- * between this and the port array in a struct plugin is that
- * the ports skip disabled plugins and connect to the upstream
- * ports directly.
- */
- audio_port_array input_audio_ports;
- audio_port_array output_audio_ports;
- control_port_array input_control_ports;
- control_port_array output_control_ports;
-
- /* The implementation of the plugin */
- struct dsp_module *module;
-
- /* Whether this module's instantiate() function has been called */
- int instantiated;
-
- /* This caches the value returned from get_properties() of a module */
- int properties;
-
- /* This is the total buffering delay from source to this instance. It is
- * in number of frames. */
- int total_delay;
-};
-
-DECLARE_ARRAY_TYPE(struct instance, instance_array)
-
-/* An pipeline is a dynamic representation of a dsp ini file. */
-struct pipeline {
- /* The purpose of the pipeline. "playback" or "capture" */
- const char *purpose;
-
- /* The ini file this pipeline comes from */
- struct ini *ini;
-
- /* All needed instances for this pipeline. It is sorted in an
- * order that if instance B depends on instance A, then A will
- * appear in front of B. */
- instance_array instances;
-
- /* The maximum number of audio buffers that will be used at
- * the same time for this pipeline */
- int peak_buf;
-
- /* The audio data buffers */
- float **buffers;
-
- /* The instance where the audio data flow in */
- struct instance *source_instance;
-
- /* The instance where the audio data flow out */
- struct instance *sink_instance;
-
- /* The number of audio channels for this pipeline */
- int input_channels;
- int output_channels;
-
- /* The audio sampling rate for this pipleine. It is zero if
- * cras_dsp_pipeline_instantiate() has not been called. */
- int sample_rate;
-
- /* The total time it takes to run the pipeline, in nanoseconds. */
- int64_t total_time;
-
- /* The max/min time it takes to run the pipeline, in nanoseconds. */
- int64_t max_time;
- int64_t min_time;
-
- /* The number of blocks the pipeline. */
- int64_t total_blocks;
-
- /* The total number of sample frames the pipeline processed */
- int64_t total_samples;
-};
-
-static struct instance *find_instance_by_plugin(const instance_array *instances,
- const struct plugin *plugin)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (instances, i, instance) {
- if (instance->plugin == plugin)
- return instance;
- }
-
- return NULL;
-}
-
-/* Finds out where the data sent to plugin:index come from. The issue
- * we need to handle here is the previous plugin may be disabled, so
- * we need to go upstream until we find the real origin */
-static int find_origin_port(struct ini *ini, const instance_array *instances,
- const struct plugin *plugin, int index,
- const struct plugin **origin, int *origin_index)
-{
- enum port_type type;
- struct port *port;
- int flow_id;
- struct flow *flow;
- int i, k;
- int found;
-
- port = ARRAY_ELEMENT(&plugin->ports, index);
- type = port->type;
- flow_id = port->flow_id;
- if (flow_id == INVALID_FLOW_ID)
- return -1;
- flow = ARRAY_ELEMENT(&ini->flows, flow_id);
-
- /* move to the previous plugin */
- plugin = flow->from;
- index = flow->from_port;
-
- /* if the plugin is not disabled, it will be pointed by some instance */
- if (find_instance_by_plugin(instances, plugin)) {
- *origin = plugin;
- *origin_index = index;
- return 0;
- }
-
- /* Now we know the previous plugin is disabled, we need to go
- * upstream. We assume the k-th output port of the plugin
- * corresponds to the k-th input port of the plugin (with the
- * same type) */
-
- k = 0;
- found = 0;
- ARRAY_ELEMENT_FOREACH (&plugin->ports, i, port) {
- if (index == i) {
- found = 1;
- break;
- }
- if (port->direction == PORT_OUTPUT && port->type == type)
- k++;
- }
- if (!found)
- return -1;
-
- found = 0;
- ARRAY_ELEMENT_FOREACH (&plugin->ports, i, port) {
- if (port->direction == PORT_INPUT && port->type == type) {
- if (k-- == 0) {
- index = i;
- found = 1;
- break;
- }
- }
- }
- if (!found)
- return -1;
-
- return find_origin_port(ini, instances, plugin, index, origin,
- origin_index);
-}
-
-static struct audio_port *find_output_audio_port(instance_array *instances,
- const struct plugin *plugin,
- int index)
-{
- int i;
- struct instance *instance;
- struct audio_port *audio_port;
-
- instance = find_instance_by_plugin(instances, plugin);
- if (!instance)
- return NULL;
-
- ARRAY_ELEMENT_FOREACH (&instance->output_audio_ports, i, audio_port) {
- if (audio_port->original_index == index)
- return audio_port;
- }
-
- return NULL;
-}
-
-static struct control_port *find_output_control_port(instance_array *instances,
- const struct plugin *plugin,
- int index)
-{
- int i;
- struct instance *instance;
- struct control_port *control_port;
-
- instance = find_instance_by_plugin(instances, plugin);
- if (!instance)
- return NULL;
-
- ARRAY_ELEMENT_FOREACH (&instance->output_control_ports, i,
- control_port) {
- if (control_port->original_index == index)
- return control_port;
- }
-
- return NULL;
-}
-
-static char is_disabled(struct plugin *plugin, struct cras_expr_env *env)
-{
- char disabled;
- return (plugin->disable_expr &&
- cras_expr_expression_eval_boolean(plugin->disable_expr, env,
- &disabled) == 0 &&
- disabled == 1);
-}
-
-static int topological_sort(struct pipeline *pipeline,
- struct cras_expr_env *env, struct plugin *plugin,
- char *visited)
-{
- struct port *port;
- struct flow *flow;
- int index;
- int i;
- int flow_id;
- struct instance *instance;
- struct ini *ini = pipeline->ini;
-
- index = ARRAY_INDEX(&ini->plugins, plugin);
- if (visited[index])
- return 0;
- visited[index] = 1;
-
- ARRAY_ELEMENT_FOREACH (&plugin->ports, i, port) {
- if (port->flow_id == INVALID_FLOW_ID)
- continue;
- flow_id = port->flow_id;
- flow = ARRAY_ELEMENT(&ini->flows, flow_id);
- if (!flow->from) {
- syslog(LOG_ERR, "no plugin flows to %s:%d",
- plugin->title, i);
- return -1;
- }
- if (topological_sort(pipeline, env, flow->from, visited) < 0)
- return -1;
- }
-
- /* if the plugin is disabled, we don't construct an instance for it */
- if (is_disabled(plugin, env))
- return 0;
-
- instance = ARRAY_APPEND_ZERO(&pipeline->instances);
- instance->plugin = plugin;
-
- /* constructs audio and control ports for the instance */
- ARRAY_ELEMENT_FOREACH (&plugin->ports, i, port) {
- int need_connect = (port->flow_id != INVALID_FLOW_ID &&
- port->direction == PORT_INPUT);
- const struct plugin *origin = NULL;
- int origin_index = 0;
-
- if (need_connect) {
- if (find_origin_port(ini, &pipeline->instances, plugin,
- i, &origin, &origin_index) < 0)
- return -1;
- }
-
- if (port->type == PORT_AUDIO) {
- audio_port_array *audio_port_array =
- (port->direction == PORT_INPUT) ?
- &instance->input_audio_ports :
- &instance->output_audio_ports;
- struct audio_port *audio_port =
- ARRAY_APPEND_ZERO(audio_port_array);
- audio_port->plugin = plugin;
- audio_port->original_index = i;
- if (need_connect) {
- struct audio_port *from;
- from = find_output_audio_port(
- &pipeline->instances, origin,
- origin_index);
- if (!from)
- return -1;
- from->peer = audio_port;
- audio_port->peer = from;
- }
- } else if (port->type == PORT_CONTROL) {
- control_port_array *control_port_array =
- (port->direction == PORT_INPUT) ?
- &instance->input_control_ports :
- &instance->output_control_ports;
- struct control_port *control_port =
- ARRAY_APPEND_ZERO(control_port_array);
- control_port->plugin = plugin;
- control_port->original_index = i;
- control_port->value = port->init_value;
- if (need_connect) {
- struct control_port *from;
- from = find_output_control_port(
- &pipeline->instances, origin,
- origin_index);
- if (!from)
- return -1;
- from->peer = control_port;
- control_port->peer = from;
- }
- }
- }
-
- return 0;
-}
-
-static struct plugin *find_enabled_builtin_plugin(struct ini *ini,
- const char *label,
- const char *purpose,
- struct cras_expr_env *env)
-{
- int i;
- struct plugin *plugin, *found = NULL;
-
- ARRAY_ELEMENT_FOREACH (&ini->plugins, i, plugin) {
- if (strcmp(plugin->library, "builtin") != 0)
- continue;
- if (strcmp(plugin->label, label) != 0)
- continue;
- if (!plugin->purpose || strcmp(plugin->purpose, purpose) != 0)
- continue;
- if (is_disabled(plugin, env))
- continue;
- if (found) {
- syslog(LOG_ERR, "two %s plugins enabled: %s and %s",
- label, found->title, plugin->title);
- return NULL;
- }
- found = plugin;
- }
-
- return found;
-}
-
-struct pipeline *cras_dsp_pipeline_create(struct ini *ini,
- struct cras_expr_env *env,
- const char *purpose)
-{
- struct pipeline *pipeline;
- int n;
- char *visited;
- int rc;
- struct plugin *source =
- find_enabled_builtin_plugin(ini, "source", purpose, env);
- struct plugin *sink =
- find_enabled_builtin_plugin(ini, "sink", purpose, env);
-
- if (!source || !sink) {
- syslog(LOG_DEBUG,
- "no enabled source or sink found %p/%p for %s", source,
- sink, purpose);
- return NULL;
- }
-
- pipeline = calloc(1, sizeof(struct pipeline));
- if (!pipeline) {
- syslog(LOG_ERR, "no memory for pipeline");
- return NULL;
- }
-
- pipeline->ini = ini;
- pipeline->purpose = purpose;
- /* create instances for needed plugins, in the order of dependency */
- n = ARRAY_COUNT(&ini->plugins);
- visited = calloc(1, n);
- rc = topological_sort(pipeline, env, sink, visited);
- free(visited);
-
- if (rc < 0) {
- syslog(LOG_ERR, "failed to construct pipeline");
- cras_dsp_pipeline_free(pipeline);
- return NULL;
- }
-
- pipeline->source_instance =
- find_instance_by_plugin(&pipeline->instances, source);
- pipeline->sink_instance =
- find_instance_by_plugin(&pipeline->instances, sink);
-
- if (!pipeline->source_instance || !pipeline->sink_instance) {
- syslog(LOG_ERR, "source(%p) or sink(%p) missing/disabled?",
- source, sink);
- cras_dsp_pipeline_free(pipeline);
- return NULL;
- }
-
- pipeline->input_channels =
- ARRAY_COUNT(&pipeline->source_instance->output_audio_ports);
- pipeline->output_channels =
- ARRAY_COUNT(&pipeline->sink_instance->input_audio_ports);
- if (pipeline->output_channels > pipeline->input_channels) {
- /* Can't increase channel count, no where to put them. */
- syslog(LOG_ERR, "DSP output more channels than input\n");
- cras_dsp_pipeline_free(pipeline);
- return NULL;
- }
-
- return pipeline;
-}
-
-static int load_module(struct plugin *plugin, struct instance *instance)
-{
- struct dsp_module *module;
- module = cras_dsp_module_load_builtin(plugin);
- if (!module)
- module = cras_dsp_module_load_ladspa(plugin);
- if (!module)
- return -1;
- instance->module = module;
- instance->properties = module->get_properties(module);
- return 0;
-}
-
-static void use_buffers(char *busy, audio_port_array *audio_ports)
-{
- int i, k = 0;
- struct audio_port *audio_port;
-
- ARRAY_ELEMENT_FOREACH (audio_ports, i, audio_port) {
- while (busy[k])
- k++;
- audio_port->buf_index = k;
- busy[k] = 1;
- }
-}
-
-static void unuse_buffers(char *busy, audio_port_array *audio_ports)
-{
- int i;
- struct audio_port *audio_port;
-
- ARRAY_ELEMENT_FOREACH (audio_ports, i, audio_port) {
- busy[audio_port->buf_index] = 0;
- }
-}
-
-/* assign which buffer each audio port on each instance should use */
-static int allocate_buffers(struct pipeline *pipeline)
-{
- int i;
- struct instance *instance;
- int need_buf = 0, peak_buf = 0;
- char *busy;
-
- /* first figure out how many buffers do we need */
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- int in = ARRAY_COUNT(&instance->input_audio_ports);
- int out = ARRAY_COUNT(&instance->output_audio_ports);
-
- if (instance->properties & MODULE_INPLACE_BROKEN) {
- /* We cannot reuse input buffer as output
- * buffer, so we need to use extra buffers */
- need_buf += out;
- peak_buf = MAX(peak_buf, need_buf);
- need_buf -= in;
- } else {
- need_buf += out - in;
- peak_buf = MAX(peak_buf, need_buf);
- }
- }
- /*
- * cras_dsp_pipeline_create creates pipeline with source and sink and it
- * makes sure all ports could be accessed from some sources, which means
- * that there is at least one source with out > 0 and in == 0.
- * This will give us peak_buf > 0 in the previous calculation.
- */
- if (peak_buf <= 0) {
- syslog(LOG_ERR, "peak_buf = %d, which must be greater than 0.",
- peak_buf);
- return -1;
- }
-
- /* then allocate the buffers */
- pipeline->peak_buf = peak_buf;
- pipeline->buffers = (float **)calloc(peak_buf, sizeof(float *));
-
- if (!pipeline->buffers) {
- syslog(LOG_ERR, "failed to allocate buffers");
- return -1;
- }
-
- for (i = 0; i < peak_buf; i++) {
- size_t size = DSP_BUFFER_SIZE * sizeof(float);
- float *buf = calloc(1, size);
- if (!buf) {
- syslog(LOG_ERR, "failed to allocate buf");
- return -1;
- }
- pipeline->buffers[i] = buf;
- }
-
- /* Now assign buffer index for each instance's input/output ports */
- busy = calloc(peak_buf, sizeof(*busy));
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- int j;
- struct audio_port *audio_port;
-
- /* Collect input buffers from upstream */
- ARRAY_ELEMENT_FOREACH (&instance->input_audio_ports, j,
- audio_port) {
- audio_port->buf_index = audio_port->peer->buf_index;
- }
-
- /* If the module has the MODULE_INPLACE_BROKEN flag,
- * we cannot reuse input buffers as output buffers, so
- * we need to use extra buffers. For example, in this graph
- *
- * [A]
- * output_0={x}
- * output_1={y}
- * output_2={z}
- * output_3={w}
- * [B]
- * input_0={x}
- * input_1={y}
- * input_2={z}
- * input_3={w}
- * output_4={u}
- *
- * Then peak_buf for this pipeline is 4. However if
- * plugin B has the MODULE_INPLACE_BROKEN flag, then
- * peak_buf is 5 because plugin B cannot output to the
- * same buffer used for input.
- *
- * This means if we don't have the flag, we can free
- * the input buffers then allocate the output buffers,
- * but if we have the flag, we have to allocate the
- * output buffers before freeing the input buffers.
- */
- if (instance->properties & MODULE_INPLACE_BROKEN) {
- use_buffers(busy, &instance->output_audio_ports);
- unuse_buffers(busy, &instance->input_audio_ports);
- } else {
- unuse_buffers(busy, &instance->input_audio_ports);
- use_buffers(busy, &instance->output_audio_ports);
- }
- }
- free(busy);
-
- return 0;
-}
-
-int cras_dsp_pipeline_load(struct pipeline *pipeline)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct plugin *plugin = instance->plugin;
- if (load_module(plugin, instance) != 0)
- return -1;
- }
-
- if (allocate_buffers(pipeline) != 0)
- return -1;
-
- return 0;
-}
-
-/* Calculates the total buffering delay of each instance from the source */
-static void calculate_audio_delay(struct pipeline *pipeline)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct dsp_module *module = instance->module;
- audio_port_array *audio_in = &instance->input_audio_ports;
- struct audio_port *audio_port;
- int delay = 0;
- int j;
-
- /* Finds the max delay of all modules that provide input to this
- * instance. */
- ARRAY_ELEMENT_FOREACH (audio_in, j, audio_port) {
- struct instance *upstream = find_instance_by_plugin(
- &pipeline->instances, audio_port->peer->plugin);
- delay = MAX(upstream->total_delay, delay);
- }
-
- instance->total_delay = delay + module->get_delay(module);
- }
-}
-
-int cras_dsp_pipeline_instantiate(struct pipeline *pipeline, int sample_rate)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct dsp_module *module = instance->module;
- if (module->instantiate(module, sample_rate) != 0)
- return -1;
- instance->instantiated = 1;
- syslog(LOG_DEBUG, "instantiate %s", instance->plugin->label);
- }
- pipeline->sample_rate = sample_rate;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- audio_port_array *audio_in = &instance->input_audio_ports;
- audio_port_array *audio_out = &instance->output_audio_ports;
- control_port_array *control_in = &instance->input_control_ports;
- control_port_array *control_out =
- &instance->output_control_ports;
- int j;
- struct audio_port *audio_port;
- struct control_port *control_port;
- struct dsp_module *module = instance->module;
-
- /* connect audio ports */
- ARRAY_ELEMENT_FOREACH (audio_in, j, audio_port) {
- float *buf = pipeline->buffers[audio_port->buf_index];
- module->connect_port(module, audio_port->original_index,
- buf);
- syslog(LOG_DEBUG, "connect audio buf %d to %s:%d (in)",
- audio_port->buf_index, instance->plugin->title,
- audio_port->original_index);
- }
- ARRAY_ELEMENT_FOREACH (audio_out, j, audio_port) {
- float *buf = pipeline->buffers[audio_port->buf_index];
- module->connect_port(module, audio_port->original_index,
- buf);
- syslog(LOG_DEBUG, "connect audio buf %d to %s:%d (out)",
- audio_port->buf_index, instance->plugin->title,
- audio_port->original_index);
- }
-
- /* connect control ports */
- ARRAY_ELEMENT_FOREACH (control_in, j, control_port) {
- /* Note for input control ports which has a
- * peer, we use &control_port->peer->value, so
- * we can get the peer port's output value
- * directly */
- float *value = control_port->peer ?
- &control_port->peer->value :
- &control_port->value;
- module->connect_port(
- module, control_port->original_index, value);
- syslog(LOG_DEBUG,
- "connect control (val=%g) to %s:%d (in)",
- control_port->value, instance->plugin->title,
- control_port->original_index);
- }
- ARRAY_ELEMENT_FOREACH (control_out, j, control_port) {
- module->connect_port(module,
- control_port->original_index,
- &control_port->value);
- syslog(LOG_DEBUG,
- "connect control (val=%g) to %s:%d (out)",
- control_port->value, instance->plugin->title,
- control_port->original_index);
- }
- }
-
- calculate_audio_delay(pipeline);
- return 0;
-}
-
-void cras_dsp_pipeline_deinstantiate(struct pipeline *pipeline)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct dsp_module *module = instance->module;
- if (instance->instantiated) {
- module->deinstantiate(module);
- instance->instantiated = 0;
- }
- }
- pipeline->sample_rate = 0;
-}
-
-int cras_dsp_pipeline_get_delay(struct pipeline *pipeline)
-{
- return pipeline->sink_instance->total_delay;
-}
-
-int cras_dsp_pipeline_get_sample_rate(struct pipeline *pipeline)
-{
- return pipeline->sample_rate;
-}
-
-int cras_dsp_pipeline_get_num_input_channels(struct pipeline *pipeline)
-{
- return pipeline->input_channels;
-}
-
-int cras_dsp_pipeline_get_num_output_channels(struct pipeline *pipeline)
-{
- return pipeline->output_channels;
-}
-
-int cras_dsp_pipeline_get_peak_audio_buffers(struct pipeline *pipeline)
-{
- return pipeline->peak_buf;
-}
-
-static float *find_buffer(struct pipeline *pipeline,
- audio_port_array *audio_ports, int index)
-{
- int i;
- struct audio_port *audio_port;
-
- ARRAY_ELEMENT_FOREACH (audio_ports, i, audio_port) {
- if (audio_port->original_index == index)
- return pipeline->buffers[audio_port->buf_index];
- }
- return NULL;
-}
-
-float *cras_dsp_pipeline_get_source_buffer(struct pipeline *pipeline, int index)
-{
- return find_buffer(pipeline,
- &pipeline->source_instance->output_audio_ports,
- index);
-}
-
-float *cras_dsp_pipeline_get_sink_buffer(struct pipeline *pipeline, int index)
-{
- return find_buffer(pipeline,
- &pipeline->sink_instance->input_audio_ports, index);
-}
-
-void cras_dsp_pipeline_set_sink_ext_module(struct pipeline *pipeline,
- struct ext_dsp_module *ext_module)
-{
- cras_dsp_module_set_sink_ext_module(pipeline->sink_instance->module,
- ext_module);
-}
-
-struct ini *cras_dsp_pipeline_get_ini(struct pipeline *pipeline)
-{
- return pipeline->ini;
-}
-
-void cras_dsp_pipeline_run(struct pipeline *pipeline, int sample_count)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct dsp_module *module = instance->module;
- module->run(module, sample_count);
- }
-}
-
-void cras_dsp_pipeline_add_statistic(struct pipeline *pipeline,
- const struct timespec *time_delta,
- int samples)
-{
- int64_t t;
- if (samples <= 0)
- return;
-
- t = time_delta->tv_sec * 1000000000LL + time_delta->tv_nsec;
-
- if (pipeline->total_blocks == 0) {
- pipeline->max_time = t;
- pipeline->min_time = t;
- } else {
- pipeline->max_time = MAX(pipeline->max_time, t);
- pipeline->min_time = MIN(pipeline->min_time, t);
- }
-
- pipeline->total_blocks++;
- pipeline->total_samples += samples;
- pipeline->total_time += t;
-}
-
-int cras_dsp_pipeline_apply(struct pipeline *pipeline, uint8_t *buf,
- snd_pcm_format_t format, unsigned int frames)
-{
- size_t remaining;
- size_t chunk;
- size_t i;
- unsigned int input_channels = pipeline->input_channels;
- unsigned int output_channels = pipeline->output_channels;
- float *source[input_channels];
- float *sink[output_channels];
- struct timespec begin, end, delta;
- int rc;
-
- if (!pipeline || frames == 0)
- return 0;
-
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &begin);
-
- /* get pointers to source and sink buffers */
- for (i = 0; i < input_channels; i++)
- source[i] = cras_dsp_pipeline_get_source_buffer(pipeline, i);
- for (i = 0; i < output_channels; i++)
- sink[i] = cras_dsp_pipeline_get_sink_buffer(pipeline, i);
-
- remaining = frames;
-
- /* process at most DSP_BUFFER_SIZE frames each loop */
- while (remaining > 0) {
- chunk = MIN(remaining, (size_t)DSP_BUFFER_SIZE);
-
- /* deinterleave and convert to float */
- rc = dsp_util_deinterleave(buf, source, input_channels, format,
- chunk);
- if (rc)
- return rc;
-
- /* Run the pipeline */
- cras_dsp_pipeline_run(pipeline, chunk);
-
- /* interleave and convert back to int16_t */
- rc = dsp_util_interleave(sink, buf, output_channels, format,
- chunk);
- if (rc)
- return rc;
-
- buf += chunk * output_channels * PCM_FORMAT_WIDTH(format) / 8;
- remaining -= chunk;
- }
-
- clock_gettime(CLOCK_THREAD_CPUTIME_ID, &end);
- subtract_timespecs(&end, &begin, &delta);
- cras_dsp_pipeline_add_statistic(pipeline, &delta, frames);
- return 0;
-}
-
-void cras_dsp_pipeline_free(struct pipeline *pipeline)
-{
- int i;
- struct instance *instance;
-
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct dsp_module *module = instance->module;
- instance->plugin = NULL;
- ARRAY_FREE(&instance->input_audio_ports);
- ARRAY_FREE(&instance->input_control_ports);
- ARRAY_FREE(&instance->output_audio_ports);
- ARRAY_FREE(&instance->output_control_ports);
-
- if (module) {
- if (instance->instantiated) {
- module->deinstantiate(module);
- instance->instantiated = 0;
- }
- module->free_module(module);
- instance->module = NULL;
- }
- }
-
- pipeline->ini = NULL;
- ARRAY_FREE(&pipeline->instances);
-
- for (i = 0; i < pipeline->peak_buf; i++)
- free(pipeline->buffers[i]);
- free(pipeline->buffers);
- free(pipeline);
-}
-
-static void dump_audio_ports(struct dumper *d, const char *name,
- audio_port_array *audio_ports)
-{
- int i;
- struct audio_port *audio_port;
- int n = ARRAY_COUNT(audio_ports);
-
- if (n == 0)
- return;
- dumpf(d, " %s (%d) =\n", name, n);
-
- ARRAY_ELEMENT_FOREACH (audio_ports, i, audio_port) {
- dumpf(d, " %p, peer %p, orig=%d, buf=%d\n", audio_port,
- audio_port->peer, audio_port->original_index,
- audio_port->buf_index);
- }
-}
-
-static void dump_control_ports(struct dumper *d, const char *name,
- control_port_array *control_ports)
-{
- int i;
- struct control_port *control_port;
- int n = ARRAY_COUNT(control_ports);
-
- if (n == 0)
- return;
- dumpf(d, " %s (%d) =\n", name, ARRAY_COUNT(control_ports));
-
- ARRAY_ELEMENT_FOREACH (control_ports, i, control_port) {
- dumpf(d, " %p, peer %p, orig=%d, value=%g\n", control_port,
- control_port->peer, control_port->original_index,
- control_port->value);
- }
-}
-
-void cras_dsp_pipeline_dump(struct dumper *d, struct pipeline *pipeline)
-{
- int i;
- struct instance *instance;
-
- dumpf(d, "---- pipeline dump begin ----\n");
- dumpf(d, "pipeline (%s):\n", pipeline->purpose);
- dumpf(d, " input channels: %d\n", pipeline->input_channels);
- dumpf(d, " output channels: %d\n", pipeline->output_channels);
- dumpf(d, " sample_rate: %d\n", pipeline->sample_rate);
- dumpf(d, " processed samples: %" PRId64 "\n", pipeline->total_samples);
- dumpf(d, " processed blocks: %" PRId64 "\n", pipeline->total_blocks);
- dumpf(d, " total processing time: %" PRId64 "ns\n",
- pipeline->total_time);
- if (pipeline->total_blocks) {
- dumpf(d, " average block size: %" PRId64 "\n",
- pipeline->total_samples / pipeline->total_blocks);
- dumpf(d, " avg processing time per block: %" PRId64 "ns\n",
- pipeline->total_time / pipeline->total_blocks);
- }
- dumpf(d, " min processing time per block: %" PRId64 "ns\n",
- pipeline->min_time);
- dumpf(d, " max processing time per block: %" PRId64 "ns\n",
- pipeline->max_time);
- if (pipeline->total_samples)
- dumpf(d, " cpu load: %g%%\n",
- pipeline->total_time * 1e-9 / pipeline->total_samples *
- pipeline->sample_rate * 100);
- dumpf(d, " instances (%d):\n", ARRAY_COUNT(&pipeline->instances));
- ARRAY_ELEMENT_FOREACH (&pipeline->instances, i, instance) {
- struct dsp_module *module = instance->module;
- dumpf(d, " [%d]%s mod=%p, total delay=%d\n", i,
- instance->plugin->title, module, instance->total_delay);
- if (module)
- module->dump(module, d);
- dump_audio_ports(d, "input_audio_ports",
- &instance->input_audio_ports);
- dump_audio_ports(d, "output_audio_ports",
- &instance->output_audio_ports);
- dump_control_ports(d, "input_control_ports",
- &instance->input_control_ports);
- dump_control_ports(d, "output_control_ports",
- &instance->output_control_ports);
- }
- dumpf(d, " peak_buf = %d\n", pipeline->peak_buf);
- dumpf(d, "---- pipeline dump end ----\n");
-}
diff --git a/cras/src/server/cras_dsp_pipeline.h b/cras/src/server/cras_dsp_pipeline.h
deleted file mode 100644
index 1a5a85a7..00000000
--- a/cras/src/server/cras_dsp_pipeline.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DSP_PIPELINE_H_
-#define CRAS_DSP_PIPELINE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdint.h>
-
-#include "dumper.h"
-#include "cras_audio_format.h"
-#include "cras_dsp_ini.h"
-#include "cras_dsp_module.h"
-
-/* These are the functions to create and use dsp pipelines. A dsp
- * pipeline is a collection of dsp plugins that process audio
- * data. The plugins and their connections are specified in an ini
- * file. Before using the pipeline, we need to instantiate the
- * pipeline by giving an audio sampling rate. Then we get the pointers
- * to the input buffers, fill the input data, run the pipeline, and
- * obtain the processed data from the output buffers.
- */
-
-/* The maximum number of samples that cras_dsp_pipeline_run() can
- * accept. Beyond this the user should break the samples into several
- * blocks and call cras_dsp_pipeline_run() several times.
- */
-#define DSP_BUFFER_SIZE 2048
-
-struct pipeline;
-
-/* Creates a pipeline from the given ini file.
- * Args:
- * ini - The ini file the pipeline is created from.
- * env - The expression environment for evaluating disable expression.
- * purpose - The purpose of the pipeline, "playback" or "capture".
- * Returns:
- * A pointer to the pipeline, or NULL if the creation fails.
- */
-struct pipeline *cras_dsp_pipeline_create(struct ini *ini,
- struct cras_expr_env *env,
- const char *purpose);
-
-/* Frees the resources used by the pipeline. */
-void cras_dsp_pipeline_free(struct pipeline *pipeline);
-
-/* Loads the implementation of the plugins in the pipeline (from
- * shared libraries). Must be called before
- * cras_dsp_pipeline_instantiate().
- * Returns:
- * 0 if successful. -1 otherwise.
- */
-int cras_dsp_pipeline_load(struct pipeline *pipeline);
-
-/* Instantiates the pipeline given the sampling rate.
- * Args:
- * sample_rate - The audio sampling rate.
- * Returns:
- * 0 if successful. -1 otherwise.
- */
-int cras_dsp_pipeline_instantiate(struct pipeline *pipeline, int sample_rate);
-
-/* The counterpart of cras_dsp_pipeline_instantiate(). To change the
- * sampling rate, this must be called before another call to
- * cras_dsp_pipeline_instantiate(). */
-void cras_dsp_pipeline_deinstantiate(struct pipeline *pipeline);
-
-/* Returns the buffering delay of the pipeline. This should only be called
- * after a pipeline has been instantiated.
- * Returns:
- * The buffering delay in frames.
- */
-int cras_dsp_pipeline_get_delay(struct pipeline *pipeline);
-
-/* Returns the number of input/output audio channels this pipeline expects */
-int cras_dsp_pipeline_get_num_input_channels(struct pipeline *pipeline);
-int cras_dsp_pipeline_get_num_output_channels(struct pipeline *pipeline);
-
-/* Returns the pointer to the input buffer for a channel of this
- * pipeline. The size of the buffer is DSP_BUFFER_SIZE samples, and
- * the number of samples acually used should be passed to
- * cras_dsp_pipeline_run().
- *
- * Args:
- * index - The channel index. The valid value is 0 to
- * cras_dsp_pipeline_get_num_channels() - 1.
- */
-float *cras_dsp_pipeline_get_source_buffer(struct pipeline *pipeline,
- int index);
-
-/* Returns the pointer to the output buffer for a channel of this
- * pipeline. The size of the buffer is DSP_BUFFER_SIZE samples.
- *
- * Args:
- * index - The channel index. The valid value is 0 to
- * cras_dsp_pipeline_get_num_channels() - 1.
- */
-float *cras_dsp_pipeline_get_sink_buffer(struct pipeline *pipeline, int index);
-
-/*
- * Connects |ext_module| to the sink of given dsp pipeline.
- * Args:
- * pipeline - The pipeline whose sink should connect to ext_module.
- * ext_module - The external dsp module to connect to pipeline sink.
- */
-void cras_dsp_pipeline_set_sink_ext_module(struct pipeline *pipeline,
- struct ext_dsp_module *ext_module);
-
-/* Returns the number of internal audio buffers allocated by the
- * pipeline. This is used by the unit test only */
-int cras_dsp_pipeline_get_peak_audio_buffers(struct pipeline *pipeline);
-
-/* Returns the sampling rate passed by cras_dsp_pipeline_instantiate(),
- * or 0 if is has not been called */
-int cras_dsp_pipeline_get_sample_rate(struct pipeline *pipeline);
-
-/* Gets the dsp ini that corresponds to the pipeline. */
-struct ini *cras_dsp_pipeline_get_ini(struct pipeline *pipeline);
-
-/* Processes a block of audio samples. sample_count should be no more
- * than DSP_BUFFER_SIZE */
-void cras_dsp_pipeline_run(struct pipeline *pipeline, int sample_count);
-
-/* Add a statistic of running time for the pipeline.
- *
- * Args:
- * time_delta - The time it takes to run the pipeline and any other
- * preprocessing and postprocessing.
- * samples - The number of audio sample frames processed.
- */
-void cras_dsp_pipeline_add_statistic(struct pipeline *pipeline,
- const struct timespec *time_delta,
- int samples);
-
-/* Runs the specified pipeline across the given interleaved buffer in place.
- * Args:
- * pipeline - The pipeline to run.
- * buf - The samples to be processed, interleaved.
- * format - Sample format of the buffer.
- * frames - the numver of samples in the buffer.
- * Returns:
- * Negative code if error, otherwise 0.
- */
-int cras_dsp_pipeline_apply(struct pipeline *pipeline, uint8_t *buf,
- snd_pcm_format_t format, unsigned int frames);
-
-/* Dumps the current state of the pipeline. For debugging only */
-void cras_dsp_pipeline_dump(struct dumper *d, struct pipeline *pipeline);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_DSP_PIPELINE_H_ */
diff --git a/cras/src/server/cras_empty_iodev.c b/cras/src/server/cras_empty_iodev.c
deleted file mode 100644
index 3471c756..00000000
--- a/cras/src/server/cras_empty_iodev.c
+++ /dev/null
@@ -1,254 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <pthread.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include "cras_audio_area.h"
-#include "cras_config.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_rstream.h"
-#include "cras_types.h"
-#include "utlist.h"
-
-#define EMPTY_BUFFER_SIZE (32 * 1024)
-#define MAX_EMPTY_FRAME_SIZE 8
-#define EMPTY_FRAMES (EMPTY_BUFFER_SIZE / MAX_EMPTY_FRAME_SIZE)
-
-static size_t empty_supported_rates[] = { 44100, 48000, 0 };
-
-static size_t empty_supported_channel_counts[] = { 1, 2, 0 };
-
-static snd_pcm_format_t empty_supported_formats[] = {
- SND_PCM_FORMAT_S16_LE, SND_PCM_FORMAT_S24_LE, SND_PCM_FORMAT_S32_LE,
- SND_PCM_FORMAT_S24_3LE, 0
-};
-
-struct empty_iodev {
- struct cras_iodev base;
- uint8_t *audio_buffer;
- uint64_t read_frames, written_frames;
- struct timespec dev_start_time;
-};
-
-/*
- * Current level of the audio buffer. This is made up based on what has been
- * read/written and how long it has been since the start. Simulates audio
- * hardware running at the given sample rate.
- */
-static unsigned int current_level(const struct cras_iodev *iodev)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
- uint64_t frames_since_start, nframes;
-
- if (iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD)
- return 0;
-
- frames_since_start = cras_frames_since_time(
- &empty_iodev->dev_start_time, iodev->format->frame_rate);
-
- if (iodev->direction == CRAS_STREAM_INPUT) {
- nframes = frames_since_start - empty_iodev->read_frames;
- return MIN(nframes, EMPTY_FRAMES);
- }
-
- /* output */
- if (empty_iodev->written_frames <= frames_since_start)
- return 0;
- return empty_iodev->written_frames - frames_since_start;
-}
-
-/*
- * iodev callbacks.
- */
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return current_level(iodev);
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- return 0;
-}
-
-static int close_dev(struct cras_iodev *iodev)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
-
- free(empty_iodev->audio_buffer);
- empty_iodev->audio_buffer = NULL;
- cras_iodev_free_audio_area(iodev);
- return 0;
-}
-
-static int configure_dev(struct cras_iodev *iodev)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
-
- if (iodev->format == NULL)
- return -EINVAL;
-
- cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
- empty_iodev->audio_buffer = calloc(1, EMPTY_BUFFER_SIZE);
- empty_iodev->read_frames = 0;
- empty_iodev->written_frames = 0;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &empty_iodev->dev_start_time);
-
- return 0;
-}
-
-static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
- unsigned *frames)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
- unsigned int avail, current;
-
- if (iodev->direction == CRAS_STREAM_OUTPUT) {
- avail = EMPTY_FRAMES - current_level(iodev);
- *frames = MIN(*frames, avail);
- } else {
- current = current_level(iodev);
- *frames = MIN(*frames, current);
- }
-
- iodev->area->frames = *frames;
- cras_audio_area_config_buf_pointers(iodev->area, iodev->format,
- empty_iodev->audio_buffer);
- *area = iodev->area;
- return 0;
-}
-
-/*
- * Returns -EPIPE if there are not enough frames or spaces in device buffer.
- * It matches other alsa-based devices.
- */
-static int put_buffer(struct cras_iodev *iodev, unsigned frames)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
-
- if (iodev->direction == CRAS_STREAM_INPUT) {
- if (current_level(iodev) < frames)
- return -EPIPE;
- empty_iodev->read_frames += frames;
- } else {
- if (EMPTY_FRAMES - current_level(iodev) < frames)
- return -EPIPE;
- empty_iodev->written_frames += frames;
- }
- return 0;
-}
-
-static int flush_buffer(struct cras_iodev *iodev)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
-
- if (iodev->direction == CRAS_STREAM_INPUT)
- empty_iodev->read_frames = 0;
- else
- empty_iodev->written_frames = 0;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &empty_iodev->dev_start_time);
- return 0;
-}
-
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
-}
-
-/*
- * Exported Interface.
- */
-
-struct cras_iodev *empty_iodev_create(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_NODE_TYPE node_type)
-{
- struct empty_iodev *empty_iodev;
- struct cras_iodev *iodev;
- struct cras_ionode *node;
-
- if (direction != CRAS_STREAM_INPUT && direction != CRAS_STREAM_OUTPUT)
- return NULL;
-
- empty_iodev = calloc(1, sizeof(*empty_iodev));
- if (empty_iodev == NULL)
- return NULL;
- iodev = &empty_iodev->base;
- iodev->direction = direction;
-
- iodev->supported_rates = empty_supported_rates;
- iodev->supported_channel_counts = empty_supported_channel_counts;
- iodev->supported_formats = empty_supported_formats;
- iodev->buffer_size = EMPTY_FRAMES;
-
- iodev->configure_dev = configure_dev;
- iodev->close_dev = close_dev;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->flush_buffer = flush_buffer;
- iodev->update_active_node = update_active_node;
- iodev->no_stream = cras_iodev_default_no_stream_playback;
-
- /* Create an empty ionode */
- node = (struct cras_ionode *)calloc(1, sizeof(*node));
- node->dev = iodev;
- node->type = node_type;
- node->volume = 100;
- node->ui_gain_scaler = 1.0f;
- strcpy(node->name, "(default)");
- cras_iodev_add_node(iodev, node);
- cras_iodev_set_active_node(iodev, node);
-
- /* Finally add it to the appropriate iodev list. */
- if (direction == CRAS_STREAM_INPUT) {
- if (node->type == CRAS_NODE_TYPE_HOTWORD) {
- snprintf(iodev->info.name, ARRAY_SIZE(iodev->info.name),
- "Silent hotword device.");
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] =
- '\0';
- iodev->info.idx = SILENT_HOTWORD_DEVICE;
- } else {
- snprintf(iodev->info.name, ARRAY_SIZE(iodev->info.name),
- "Silent record device.");
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] =
- '\0';
- iodev->info.idx = SILENT_RECORD_DEVICE;
- }
- } else {
- snprintf(iodev->info.name, ARRAY_SIZE(iodev->info.name),
- "Silent playback device.");
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = '\0';
- iodev->info.idx = SILENT_PLAYBACK_DEVICE;
- }
-
- /*
- * Record max supported channels into cras_iodev_info.
- * The value is the max of empty_supported_channel_counts.
- */
- iodev->info.max_supported_channels = 2;
-
- return iodev;
-}
-
-void empty_iodev_destroy(struct cras_iodev *iodev)
-{
- struct empty_iodev *empty_iodev = (struct empty_iodev *)iodev;
-
- if (iodev->direction == CRAS_STREAM_INPUT)
- cras_iodev_list_rm_input(iodev);
- else
- cras_iodev_list_rm_output(iodev);
- free(iodev->active_node);
- cras_iodev_free_resources(iodev);
- free(empty_iodev);
-}
diff --git a/cras/src/server/cras_empty_iodev.h b/cras/src/server/cras_empty_iodev.h
deleted file mode 100644
index d85b9e02..00000000
--- a/cras/src/server/cras_empty_iodev.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_EMPTY_IO_H_
-#define CRAS_EMPTY_IO_H_
-
-#include "cras_types.h"
-
-struct cras_iodev;
-
-/* Initializes an empty iodev. Empty iodevs are used when there are no other
- * iodevs available. They give the attached streams a temporary place to live
- * until a new iodev becomes available.
- * Args:
- * direciton - input or output.
- * node_type - the default node type.
- * Returns:
- * A pointer to the newly created iodev if successful, NULL otherwise.
- */
-struct cras_iodev *empty_iodev_create(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_NODE_TYPE node_type);
-
-/* Destroys an empty_iodev created with empty_iodev_create. */
-void empty_iodev_destroy(struct cras_iodev *iodev);
-
-#endif /* CRAS_EMPTY_IO_H_ */
diff --git a/cras/src/server/cras_expr.c b/cras/src/server/cras_expr.c
deleted file mode 100644
index f7fab0d2..00000000
--- a/cras/src/server/cras_expr.c
+++ /dev/null
@@ -1,653 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <ctype.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include "array.h"
-#include "cras_expr.h"
-
-static const char *copy_str(const char *begin, const char *end)
-{
- char *s = malloc(end - begin + 1);
- memcpy(s, begin, end - begin);
- s[end - begin] = '\0';
- return s;
-}
-
-static void value_set_boolean(struct cras_expr_value *value, char boolean)
-{
- cras_expr_value_free(value);
- value->type = CRAS_EXPR_VALUE_TYPE_BOOLEAN;
- value->u.boolean = !!boolean;
-}
-
-static void value_set_integer(struct cras_expr_value *value, int integer)
-{
- cras_expr_value_free(value);
- value->type = CRAS_EXPR_VALUE_TYPE_INT;
- value->u.integer = integer;
-}
-
-static void value_set_string2(struct cras_expr_value *value, const char *begin,
- const char *end)
-{
- cras_expr_value_free(value);
- value->type = CRAS_EXPR_VALUE_TYPE_STRING;
- value->u.string = copy_str(begin, end);
-}
-
-static void value_set_string(struct cras_expr_value *value, const char *str)
-{
- value_set_string2(value, str, str + strlen(str));
-}
-
-static void cras_expr_value_set_function(struct cras_expr_value *value,
- cras_expr_function_type function)
-{
- cras_expr_value_free(value);
- value->type = CRAS_EXPR_VALUE_TYPE_FUNCTION;
- value->u.function = function;
-}
-
-static void copy_value(struct cras_expr_value *value,
- struct cras_expr_value *original)
-{
- cras_expr_value_free(value); /* free the original value first */
- value->type = original->type;
- switch (value->type) {
- case CRAS_EXPR_VALUE_TYPE_NONE:
- break;
- case CRAS_EXPR_VALUE_TYPE_BOOLEAN:
- value->u.boolean = original->u.boolean;
- break;
- case CRAS_EXPR_VALUE_TYPE_INT:
- value->u.integer = original->u.integer;
- break;
- case CRAS_EXPR_VALUE_TYPE_STRING:
- value->u.string = strdup(original->u.string);
- break;
- case CRAS_EXPR_VALUE_TYPE_FUNCTION:
- value->u.function = original->u.function;
- break;
- }
-}
-
-void cras_expr_value_free(struct cras_expr_value *value)
-{
- switch (value->type) {
- case CRAS_EXPR_VALUE_TYPE_STRING:
- free((char *)value->u.string);
- value->u.string = NULL;
- break;
- case CRAS_EXPR_VALUE_TYPE_NONE:
- case CRAS_EXPR_VALUE_TYPE_BOOLEAN:
- case CRAS_EXPR_VALUE_TYPE_INT:
- case CRAS_EXPR_VALUE_TYPE_FUNCTION:
- break;
- }
- value->type = CRAS_EXPR_VALUE_TYPE_NONE;
-}
-
-void cras_expr_value_dump(struct dumper *d, const struct cras_expr_value *value)
-{
- switch (value->type) {
- case CRAS_EXPR_VALUE_TYPE_NONE:
- dumpf(d, "none");
- break;
- case CRAS_EXPR_VALUE_TYPE_BOOLEAN:
- dumpf(d, "boolean(%s)", value->u.boolean ? "true" : "false");
- break;
- case CRAS_EXPR_VALUE_TYPE_INT:
- dumpf(d, "integer(%d)", value->u.integer);
- break;
- case CRAS_EXPR_VALUE_TYPE_STRING:
- dumpf(d, "string(%s)", value->u.string);
- break;
- case CRAS_EXPR_VALUE_TYPE_FUNCTION:
- dumpf(d, "function(%p)", value->u.function);
- break;
- }
-}
-
-static struct cras_expr_value *find_value(struct cras_expr_env *env,
- const char *name)
-{
- int i;
- const char **key;
-
- ARRAY_ELEMENT_FOREACH (&env->keys, i, key) {
- if (strcmp(*key, name) == 0)
- return ARRAY_ELEMENT(&env->values, i);
- }
- return NULL;
-}
-
-/* Insert a (key, value) pair to the environment. The value is
- * initialized to zero. Return the pointer to value so it can be set
- * to the proper value. */
-static struct cras_expr_value *insert_value(struct cras_expr_env *env,
- const char *key)
-{
- *ARRAY_APPEND_ZERO(&env->keys) = strdup(key);
- return ARRAY_APPEND_ZERO(&env->values);
-}
-
-static struct cras_expr_value *find_or_insert_value(struct cras_expr_env *env,
- const char *key)
-{
- struct cras_expr_value *value = find_value(env, key);
- if (!value)
- value = insert_value(env, key);
- return value;
-}
-
-static void function_not(cras_expr_value_array *operands,
- struct cras_expr_value *result)
-{
- struct cras_expr_value *value;
- int is_false;
-
- if (ARRAY_COUNT(operands) != 2) {
- cras_expr_value_free(result);
- syslog(LOG_ERR, "not takes one argument");
- return;
- }
-
- value = ARRAY_ELEMENT(operands, 1);
- is_false = (value->type == CRAS_EXPR_VALUE_TYPE_BOOLEAN &&
- !value->u.boolean);
- value_set_boolean(result, is_false);
-}
-
-static void function_and(cras_expr_value_array *operands,
- struct cras_expr_value *result)
-{
- int i;
- struct cras_expr_value *value;
- int n = ARRAY_COUNT(operands);
-
- /* no operands -- return #t */
- if (n <= 1) {
- value_set_boolean(result, 1);
- return;
- }
-
- /* if there is any #f, return it */
- ARRAY_ELEMENT_FOREACH (operands, i, value) {
- if (i == 0)
- continue; /* ignore "and" itself */
- if (value->type == CRAS_EXPR_VALUE_TYPE_BOOLEAN &&
- !value->u.boolean) {
- value_set_boolean(result, 0);
- return;
- }
- }
-
- /* otherwise return the last element */
- copy_value(result, ARRAY_ELEMENT(operands, n - 1));
-}
-
-static void function_or(cras_expr_value_array *operands,
- struct cras_expr_value *result)
-{
- int i;
- struct cras_expr_value *value;
-
- ARRAY_ELEMENT_FOREACH (operands, i, value) {
- if (i == 0)
- continue; /* ignore "or" itself */
- if (value->type != CRAS_EXPR_VALUE_TYPE_BOOLEAN ||
- value->u.boolean) {
- copy_value(result, value);
- return;
- }
- }
-
- value_set_boolean(result, 0);
-}
-
-static char function_equal_real(cras_expr_value_array *operands)
-{
- int i;
- struct cras_expr_value *value, *prev;
-
- ARRAY_ELEMENT_FOREACH (operands, i, value) {
- if (i <= 1)
- continue; /* ignore equal? and first operand */
- /* compare with the previous operand */
-
- prev = ARRAY_ELEMENT(operands, i - 1);
-
- if (prev->type != value->type)
- return 0;
-
- switch (prev->type) {
- case CRAS_EXPR_VALUE_TYPE_NONE:
- break;
- case CRAS_EXPR_VALUE_TYPE_BOOLEAN:
- if (prev->u.boolean != value->u.boolean)
- return 0;
- break;
- case CRAS_EXPR_VALUE_TYPE_INT:
- if (prev->u.integer != value->u.integer)
- return 0;
- break;
- case CRAS_EXPR_VALUE_TYPE_STRING:
- if (strcmp(prev->u.string, value->u.string) != 0)
- return 0;
- break;
- case CRAS_EXPR_VALUE_TYPE_FUNCTION:
- if (prev->u.function != value->u.function)
- return 0;
- break;
- }
- }
-
- return 1;
-}
-
-static void function_equal(cras_expr_value_array *operands,
- struct cras_expr_value *result)
-{
- value_set_boolean(result, function_equal_real(operands));
-}
-
-static void env_set_variable(struct cras_expr_env *env, const char *name,
- struct cras_expr_value *new_value)
-{
- struct cras_expr_value *value = find_or_insert_value(env, name);
- copy_value(value, new_value);
-}
-
-void cras_expr_env_install_builtins(struct cras_expr_env *env)
-{
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
-
- /* initialize env with builtin functions */
- cras_expr_value_set_function(&value, &function_not);
- env_set_variable(env, "not", &value);
-
- cras_expr_value_set_function(&value, &function_and);
- env_set_variable(env, "and", &value);
-
- cras_expr_value_set_function(&value, &function_or);
- env_set_variable(env, "or", &value);
-
- cras_expr_value_set_function(&value, &function_equal);
- env_set_variable(env, "equal?", &value);
-
- cras_expr_value_free(&value);
-}
-
-void cras_expr_env_set_variable_boolean(struct cras_expr_env *env,
- const char *name, char boolean)
-{
- struct cras_expr_value *value = find_or_insert_value(env, name);
- value_set_boolean(value, boolean);
-}
-
-void cras_expr_env_set_variable_integer(struct cras_expr_env *env,
- const char *name, int integer)
-{
- struct cras_expr_value *value = find_or_insert_value(env, name);
- value_set_integer(value, integer);
-}
-
-void cras_expr_env_set_variable_string(struct cras_expr_env *env,
- const char *name, const char *str)
-{
- struct cras_expr_value *value = find_or_insert_value(env, name);
- value_set_string(value, str);
-}
-
-void cras_expr_env_free(struct cras_expr_env *env)
-{
- int i;
- const char **key;
- struct cras_expr_value *value;
-
- ARRAY_ELEMENT_FOREACH (&env->keys, i, key) {
- free((char *)*key);
- }
-
- ARRAY_ELEMENT_FOREACH (&env->values, i, value) {
- cras_expr_value_free(value);
- }
-
- ARRAY_FREE(&env->keys);
- ARRAY_FREE(&env->values);
-}
-
-void cras_expr_env_dump(struct dumper *d, const struct cras_expr_env *env)
-{
- int i;
- const char **key;
- struct cras_expr_value *value;
-
- dumpf(d, "--- environment ---\n");
- ARRAY_ELEMENT_FOREACH (&env->keys, i, key) {
- dumpf(d, " key=%s,", *key);
- dumpf(d, " value=");
- value = ARRAY_ELEMENT(&env->values, i);
- cras_expr_value_dump(d, value);
- dumpf(d, "\n");
- }
-}
-
-static struct cras_expr_expression *new_boolean_literal(char boolean)
-{
- struct cras_expr_expression *expr;
- expr = calloc(1, sizeof(struct cras_expr_expression));
- expr->type = EXPR_TYPE_LITERAL;
- value_set_boolean(&expr->u.literal, boolean);
- return expr;
-}
-
-static struct cras_expr_expression *new_integer_literal(int integer)
-{
- struct cras_expr_expression *expr;
- expr = calloc(1, sizeof(struct cras_expr_expression));
- expr->type = EXPR_TYPE_LITERAL;
- value_set_integer(&expr->u.literal, integer);
- return expr;
-}
-
-static struct cras_expr_expression *new_string_literal(const char *begin,
- const char *end)
-{
- struct cras_expr_expression *expr;
- expr = calloc(1, sizeof(struct cras_expr_expression));
- expr->type = EXPR_TYPE_LITERAL;
- value_set_string2(&expr->u.literal, begin, end);
- return expr;
-}
-
-static struct cras_expr_expression *new_variable(const char *begin,
- const char *end)
-{
- struct cras_expr_expression *expr;
- expr = calloc(1, sizeof(struct cras_expr_expression));
- expr->type = EXPR_TYPE_VARIABLE;
- expr->u.variable = copy_str(begin, end);
- return expr;
-}
-
-static struct cras_expr_expression *new_compound_expression()
-{
- struct cras_expr_expression *expr;
- expr = calloc(1, sizeof(struct cras_expr_expression));
- expr->type = EXPR_TYPE_COMPOUND;
- return expr;
-}
-
-static void add_sub_expression(struct cras_expr_expression *expr,
- struct cras_expr_expression *sub)
-{
- ARRAY_APPEND(&expr->u.children, sub);
-}
-
-static int is_identifier_char(char c)
-{
- if (isspace(c))
- return 0;
- if (c == '\0')
- return 0;
- if (isalpha(c))
- return 1;
- if (c == '_' || c == '-' || c == '?')
- return 1;
- return 0;
-}
-
-static struct cras_expr_expression *parse_one_expr(const char **str)
-{
- /* skip whitespace */
- while (isspace(**str))
- (*str)++;
-
- if (**str == '\0')
- return NULL;
-
- /* boolean literal: #t, #f */
- if (**str == '#') {
- (*str)++;
- char c = **str;
- if (c == 't' || c == 'f') {
- (*str)++;
- return new_boolean_literal(c == 't');
- } else {
- syslog(LOG_ERR, "unexpected char after #: '%c'", c);
- }
- return NULL;
- }
-
- /* integer literal: (-)[0-9]+ */
- if (isdigit(**str) || (**str == '-' && isdigit((*str)[1])))
- return new_integer_literal(strtol(*str, (char **)str, 10));
-
- /* string literal: "..." */
- if (**str == '"') {
- const char *begin = *str + 1;
- const char *end = strchr(begin, '"');
- if (end == NULL) {
- syslog(LOG_ERR, "no matching \"");
- end = begin;
- *str = begin;
- } else {
- *str = end + 1;
- }
- return new_string_literal(begin, end);
- }
-
- /* compound expression: (expr1 expr2 ...) */
- if (**str == '(') {
- (*str)++;
- struct cras_expr_expression *expr = new_compound_expression();
- while (1) {
- struct cras_expr_expression *next = parse_one_expr(str);
- if (next == NULL)
- break;
- add_sub_expression(expr, next);
- }
- if (**str != ')') {
- syslog(LOG_ERR, "no matching ): found '%c'", **str);
- cras_expr_expression_free(expr);
- return NULL;
- } else {
- (*str)++;
- }
- return expr;
- }
-
- /* variable name */
- if (is_identifier_char(**str)) {
- const char *begin = *str;
- while (is_identifier_char(**str))
- (*str)++;
- return new_variable(begin, *str);
- }
-
- return NULL;
-}
-
-struct cras_expr_expression *cras_expr_expression_parse(const char *str)
-{
- if (!str)
- return NULL;
- return parse_one_expr(&str);
-}
-
-static void dump_value(struct dumper *d, const struct cras_expr_value *value,
- int indent)
-{
- switch (value->type) {
- case CRAS_EXPR_VALUE_TYPE_NONE:
- dumpf(d, "%*s(none)", indent, "");
- break;
- case CRAS_EXPR_VALUE_TYPE_BOOLEAN:
- dumpf(d, "%*s%s", indent, "", value->u.boolean ? "#t" : "#f");
- break;
- case CRAS_EXPR_VALUE_TYPE_INT:
- dumpf(d, "%*s%d", indent, "", value->u.integer);
- break;
- case CRAS_EXPR_VALUE_TYPE_STRING:
- dumpf(d, "%*s%s", indent, "", value->u.string);
- break;
- case CRAS_EXPR_VALUE_TYPE_FUNCTION:
- dumpf(d, "%*s%p", indent, "", value->u.function);
- break;
- }
-}
-
-static void dump_one_expression(struct dumper *d,
- const struct cras_expr_expression *expr,
- int indent)
-{
- int i;
- struct cras_expr_expression **sub;
-
- switch (expr->type) {
- case EXPR_TYPE_NONE:
- dumpf(d, "%*snone", indent, "");
- break;
- case EXPR_TYPE_LITERAL:
- dumpf(d, "%*sliteral", indent, "");
- dump_value(d, &expr->u.literal, indent + 2);
- break;
- case EXPR_TYPE_VARIABLE:
- dumpf(d, "%*svariable (%s)", indent, "", expr->u.variable);
- break;
- case EXPR_TYPE_COMPOUND:
- dumpf(d, "%*scompound", indent, "");
- ARRAY_ELEMENT_FOREACH (&expr->u.children, i, sub) {
- dump_one_expression(d, *sub, indent + 2);
- }
- break;
- }
-}
-
-void cras_expr_expression_dump(struct dumper *d,
- const struct cras_expr_expression *expr)
-{
- dump_one_expression(d, expr, 0);
-}
-
-void cras_expr_expression_free(struct cras_expr_expression *expr)
-{
- if (!expr)
- return;
-
- switch (expr->type) {
- case EXPR_TYPE_NONE:
- break;
- case EXPR_TYPE_LITERAL:
- cras_expr_value_free(&expr->u.literal);
- break;
- case EXPR_TYPE_VARIABLE:
- free((char *)expr->u.variable);
- break;
- case EXPR_TYPE_COMPOUND: {
- int i;
- struct cras_expr_expression **psub;
- ARRAY_ELEMENT_FOREACH (&expr->u.children, i, psub) {
- cras_expr_expression_free(*psub);
- }
- ARRAY_FREE(&expr->u.children);
- break;
- }
- }
- free(expr);
-}
-
-void cras_expr_expression_eval(struct cras_expr_expression *expr,
- struct cras_expr_env *env,
- struct cras_expr_value *result)
-{
- cras_expr_value_free(result);
-
- switch (expr->type) {
- case EXPR_TYPE_NONE:
- break;
- case EXPR_TYPE_LITERAL:
- copy_value(result, &expr->u.literal);
- break;
- case EXPR_TYPE_VARIABLE: {
- struct cras_expr_value *value =
- find_value(env, expr->u.variable);
- if (value == NULL) {
- syslog(LOG_ERR, "cannot find value for %s",
- expr->u.variable);
- } else {
- copy_value(result, value);
- }
- break;
- }
- case EXPR_TYPE_COMPOUND: {
- int i;
- struct cras_expr_expression **psub;
- cras_expr_value_array values = ARRAY_INIT;
- struct cras_expr_value *value;
-
- ARRAY_ELEMENT_FOREACH (&expr->u.children, i, psub) {
- value = ARRAY_APPEND_ZERO(&values);
- cras_expr_expression_eval(*psub, env, value);
- }
-
- if (ARRAY_COUNT(&values) > 0) {
- struct cras_expr_value *f = ARRAY_ELEMENT(&values, 0);
- if (f->type == CRAS_EXPR_VALUE_TYPE_FUNCTION)
- f->u.function(&values, result);
- else
- syslog(LOG_ERR,
- "first element is not a function");
- } else {
- syslog(LOG_ERR, "empty compound expression?");
- }
-
- ARRAY_ELEMENT_FOREACH (&values, i, value) {
- cras_expr_value_free(value);
- }
-
- ARRAY_FREE(&values);
- break;
- }
- }
-}
-
-int cras_expr_expression_eval_int(struct cras_expr_expression *expr,
- struct cras_expr_env *env, int *integer)
-{
- int rc = 0;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
-
- cras_expr_expression_eval(expr, env, &value);
- if (value.type == CRAS_EXPR_VALUE_TYPE_INT) {
- *integer = value.u.integer;
- } else {
- syslog(LOG_ERR, "value type is not integer (%d)", value.type);
- rc = -1;
- }
- cras_expr_value_free(&value);
- return rc;
-}
-
-int cras_expr_expression_eval_boolean(struct cras_expr_expression *expr,
- struct cras_expr_env *env, char *boolean)
-{
- int rc = 0;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
-
- cras_expr_expression_eval(expr, env, &value);
- if (value.type == CRAS_EXPR_VALUE_TYPE_BOOLEAN) {
- *boolean = value.u.boolean;
- } else {
- syslog(LOG_ERR, "value type is not boolean (%d)", value.type);
- rc = -1;
- }
- cras_expr_value_free(&value);
- return rc;
-}
diff --git a/cras/src/server/cras_expr.h b/cras/src/server/cras_expr.h
deleted file mode 100644
index a26e98d4..00000000
--- a/cras/src/server/cras_expr.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_EXPR_H_
-#define CRAS_EXPR_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "array.h"
-#include "dumper.h"
-
-/* Value */
-
-enum cras_expr_value_type {
- CRAS_EXPR_VALUE_TYPE_NONE,
- CRAS_EXPR_VALUE_TYPE_BOOLEAN,
- CRAS_EXPR_VALUE_TYPE_INT,
- CRAS_EXPR_VALUE_TYPE_STRING,
- CRAS_EXPR_VALUE_TYPE_FUNCTION,
-};
-
-DECLARE_ARRAY_TYPE(struct cras_expr_value, cras_expr_value_array);
-typedef void (*cras_expr_function_type)(cras_expr_value_array *operands,
- struct cras_expr_value *result);
-
-struct cras_expr_value {
- enum cras_expr_value_type type;
- union {
- char boolean;
- int integer;
- const char *string;
- cras_expr_function_type function;
- } u;
-};
-
-/* initial value for the value type is zero */
-// clang-format off
-#define CRAS_EXPR_VALUE_INIT {}
-// clang-format on
-
-/* Expression */
-
-enum expr_type {
- EXPR_TYPE_NONE,
- EXPR_TYPE_LITERAL,
- EXPR_TYPE_VARIABLE,
- EXPR_TYPE_COMPOUND,
-};
-
-DECLARE_ARRAY_TYPE(struct cras_expr_expression *, expr_array);
-
-struct cras_expr_expression {
- enum expr_type type;
- union {
- struct cras_expr_value literal;
- const char *variable;
- expr_array children;
- } u;
-};
-
-/* Environment */
-
-DECLARE_ARRAY_TYPE(const char *, string_array);
-
-struct cras_expr_env {
- string_array keys;
- cras_expr_value_array values;
-};
-
-/* initial value for the environment type is zero */
-// clang-format off
-#define CRAS_EXPR_ENV_INIT {}
-// clang-format on
-
-void cras_expr_env_install_builtins(struct cras_expr_env *env);
-void cras_expr_env_set_variable_boolean(struct cras_expr_env *env,
- const char *name, char boolean);
-void cras_expr_env_set_variable_integer(struct cras_expr_env *env,
- const char *name, int integer);
-void cras_expr_env_set_variable_string(struct cras_expr_env *env,
- const char *name, const char *str);
-void cras_expr_env_free(struct cras_expr_env *env);
-void cras_expr_env_dump(struct dumper *d, const struct cras_expr_env *env);
-
-struct cras_expr_expression *cras_expr_expression_parse(const char *str);
-void cras_expr_expression_eval(struct cras_expr_expression *expr,
- struct cras_expr_env *env,
- struct cras_expr_value *value);
-int cras_expr_expression_eval_boolean(struct cras_expr_expression *expr,
- struct cras_expr_env *env, char *boolean);
-int cras_expr_expression_eval_int(struct cras_expr_expression *expr,
- struct cras_expr_env *env, int *integer);
-void cras_expr_expression_free(struct cras_expr_expression *expr);
-void cras_expr_expression_dump(struct dumper *d,
- const struct cras_expr_expression *expr);
-void cras_expr_value_free(struct cras_expr_value *value);
-void cras_expr_value_dump(struct dumper *d,
- const struct cras_expr_value *value);
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#endif /* CRAS_EXPR_H_ */
diff --git a/cras/src/server/cras_fmt_conv.c b/cras/src/server/cras_fmt_conv.c
deleted file mode 100644
index 842529b9..00000000
--- a/cras/src/server/cras_fmt_conv.c
+++ /dev/null
@@ -1,847 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* For now just use speex, can add more resamplers later. */
-#include <speex/speex_resampler.h>
-#include <sys/param.h>
-#include <syslog.h>
-#include <endian.h>
-#include <limits.h>
-#include <math.h>
-
-#include "cras_fmt_conv.h"
-#include "cras_fmt_conv_ops.h"
-#include "cras_audio_format.h"
-#include "cras_util.h"
-#include "linear_resampler.h"
-
-/* The quality level is a value between 0 and 10. This is a tradeoff between
- * performance, latency, and quality. */
-#define SPEEX_QUALITY_LEVEL 4
-/* Max number of converters, src, down/up mix, 2xformat, and linear resample. */
-#define MAX_NUM_CONVERTERS 5
-/* Channel index for stereo. */
-#define STEREO_L 0
-#define STEREO_R 1
-
-typedef void (*sample_format_converter_t)(const uint8_t *in, size_t in_samples,
- uint8_t *out);
-typedef size_t (*channel_converter_t)(struct cras_fmt_conv *conv,
- const uint8_t *in, size_t in_frames,
- uint8_t *out);
-
-/* Member data for the resampler. */
-struct cras_fmt_conv {
- SpeexResamplerState *speex_state;
- channel_converter_t channel_converter;
- float **ch_conv_mtx; /* Coefficient matrix for mixing channels. */
- sample_format_converter_t in_format_converter;
- sample_format_converter_t out_format_converter;
- struct linear_resampler *resampler;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
- uint8_t *tmp_bufs[MAX_NUM_CONVERTERS - 1];
- size_t tmp_buf_frames;
- size_t pre_linear_resample;
- size_t num_converters; /* Incremented once for SRC, channel, format. */
-};
-
-static int is_channel_layout_equal(const struct cras_audio_format *a,
- const struct cras_audio_format *b)
-{
- int ch;
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- if (a->channel_layout[ch] != b->channel_layout[ch])
- return 0;
-
- return 1;
-}
-
-/*
- * Calculates the normalize_factor abs_sum(ci) from given coefficients.
- * Since sum(ci / abs_sum(ci)) <= 1, this could prevent sample overflow while
- * upmixing or downmixing.
- */
-static float normalize_factor(float *buf, size_t n)
-{
- int i;
- float abs_sum = 0.0;
- for (i = 0; i < n; i++)
- abs_sum += fabs(buf[i]);
-
- return 1.0 / abs_sum;
-}
-
-/*
- * Normalize all channels with the same factor to maintain
- * the energy ratio between original channels.
- */
-static void normalize(float **mtx, size_t m, size_t n, float factor)
-{
- int i, j;
- for (i = 0; i < m; i++)
- for (j = 0; j < n; j++)
- mtx[i][j] *= factor;
-}
-
-/*
- * Populates the down mix matrix by rules:
- * 1. Front/side left(right) channel will mix to left(right) of
- * full scale.
- * 2. Center and LFE will be split equally to left and right.
- * Rear
- * 3. Rear left/right will split 1/4 of the power to opposite
- * channel.
- */
-static void surround51_to_stereo_downmix_mtx(float **mtx,
- int8_t layout[CRAS_CH_MAX])
-{
- if (layout[CRAS_CH_FC] != -1) {
- mtx[STEREO_L][layout[CRAS_CH_FC]] = 0.707;
- mtx[STEREO_R][layout[CRAS_CH_FC]] = 0.707;
- }
- if (layout[CRAS_CH_FL] != -1 && layout[CRAS_CH_FR] != -1) {
- mtx[STEREO_L][layout[CRAS_CH_FL]] = 1.0;
- mtx[STEREO_R][layout[CRAS_CH_FR]] = 1.0;
- }
- if (layout[CRAS_CH_SL] != -1 && layout[CRAS_CH_SR] != -1) {
- mtx[STEREO_L][layout[CRAS_CH_SL]] = 1.0;
- mtx[STEREO_R][layout[CRAS_CH_SR]] = 1.0;
- }
- if (layout[CRAS_CH_RL] != -1 && layout[CRAS_CH_RR] != -1) {
- /* Split 1/4 power to the other side */
- mtx[STEREO_L][layout[CRAS_CH_RL]] = 0.866;
- mtx[STEREO_R][layout[CRAS_CH_RL]] = 0.5;
- mtx[STEREO_R][layout[CRAS_CH_RR]] = 0.866;
- mtx[STEREO_L][layout[CRAS_CH_RR]] = 0.5;
- }
- if (layout[CRAS_CH_LFE] != -1) {
- mtx[STEREO_L][layout[CRAS_CH_LFE]] = 0.707;
- mtx[STEREO_R][layout[CRAS_CH_LFE]] = 0.707;
- }
- normalize(mtx, 2, 6, normalize_factor(mtx[STEREO_L], 6));
-}
-
-/* Populates the down mix matrix by rules:
- * 1. Front left(right) channel will mix to the front left(right) of
- * full scale.
- * 2. Rear and side left(right) channel will mix to the rear left(right) of
- * full scale.
- * 3. Center will be split equally to the front left and right.
- * 4. LFE will be split equally to the other channels.
- */
-static void surround51_to_quad_downmix_mtx(float **mtx,
- int8_t layout[CRAS_CH_MAX])
-{
- if (layout[CRAS_CH_FL] != -1 && layout[CRAS_CH_FR] != -1) {
- mtx[CRAS_CH_FL][layout[CRAS_CH_FL]] = 1.0;
- mtx[CRAS_CH_FR][layout[CRAS_CH_FR]] = 1.0;
- }
- if (layout[CRAS_CH_RL] != -1 && layout[CRAS_CH_RR] != -1) {
- mtx[CRAS_CH_RL][layout[CRAS_CH_RL]] = 1.0;
- mtx[CRAS_CH_RR][layout[CRAS_CH_RR]] = 1.0;
- }
- if (layout[CRAS_CH_SL] != -1 && layout[CRAS_CH_SR] != -1) {
- mtx[CRAS_CH_RL][layout[CRAS_CH_SL]] = 1.0;
- mtx[CRAS_CH_RR][layout[CRAS_CH_SR]] = 1.0;
- }
- if (layout[CRAS_CH_FC] != -1) {
- /* Split 1/2 power to the front L/R */
- mtx[CRAS_CH_FL][layout[CRAS_CH_FC]] = 0.707;
- mtx[CRAS_CH_FR][layout[CRAS_CH_FC]] = 0.707;
- }
- if (layout[CRAS_CH_LFE] != -1) {
- /* Split 1/4 power to the other channel */
- mtx[CRAS_CH_FL][layout[CRAS_CH_LFE]] = 0.5;
- mtx[CRAS_CH_FR][layout[CRAS_CH_LFE]] = 0.5;
- mtx[CRAS_CH_RL][layout[CRAS_CH_LFE]] = 0.5;
- mtx[CRAS_CH_RR][layout[CRAS_CH_LFE]] = 0.5;
- }
-
- normalize(mtx, 4, 6, normalize_factor(mtx[CRAS_CH_FL], 6));
-}
-
-static int is_supported_format(const struct cras_audio_format *fmt)
-{
- if (!fmt)
- return 0;
-
- switch (fmt->format) {
- case SND_PCM_FORMAT_U8:
- case SND_PCM_FORMAT_S16_LE:
- case SND_PCM_FORMAT_S24_3LE:
- case SND_PCM_FORMAT_S24_LE:
- case SND_PCM_FORMAT_S32_LE:
- return 1;
- default:
- return 0;
- }
-}
-
-static size_t mono_to_stereo(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- return s16_mono_to_stereo(in, in_frames, out);
-}
-
-static size_t stereo_to_mono(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- return s16_stereo_to_mono(in, in_frames, out);
-}
-
-static size_t mono_to_51(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- size_t left, right, center;
-
- left = conv->out_fmt.channel_layout[CRAS_CH_FL];
- right = conv->out_fmt.channel_layout[CRAS_CH_FR];
- center = conv->out_fmt.channel_layout[CRAS_CH_FC];
-
- return s16_mono_to_51(left, right, center, in, in_frames, out);
-}
-
-static size_t stereo_to_51(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- size_t left, right, center;
-
- left = conv->out_fmt.channel_layout[CRAS_CH_FL];
- right = conv->out_fmt.channel_layout[CRAS_CH_FR];
- center = conv->out_fmt.channel_layout[CRAS_CH_FC];
-
- return s16_stereo_to_51(left, right, center, in, in_frames, out);
-}
-
-static size_t quad_to_51(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- size_t fl, fr, rl, rr;
-
- fl = conv->out_fmt.channel_layout[CRAS_CH_FL];
- fr = conv->out_fmt.channel_layout[CRAS_CH_FR];
- rl = conv->out_fmt.channel_layout[CRAS_CH_RL];
- rr = conv->out_fmt.channel_layout[CRAS_CH_RR];
-
- return s16_quad_to_51(fl, fr, rl, rr, in, in_frames, out);
-}
-
-static size_t _51_to_stereo(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- return s16_51_to_stereo(in, in_frames, out);
-}
-
-static size_t _51_to_quad(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- return s16_51_to_quad(in, in_frames, out);
-}
-
-static size_t stereo_to_quad(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- size_t front_left, front_right, rear_left, rear_right;
-
- front_left = conv->out_fmt.channel_layout[CRAS_CH_FL];
- front_right = conv->out_fmt.channel_layout[CRAS_CH_FR];
- rear_left = conv->out_fmt.channel_layout[CRAS_CH_RL];
- rear_right = conv->out_fmt.channel_layout[CRAS_CH_RR];
-
- return s16_stereo_to_quad(front_left, front_right, rear_left,
- rear_right, in, in_frames, out);
-}
-
-static size_t quad_to_stereo(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- size_t front_left, front_right, rear_left, rear_right;
-
- front_left = conv->in_fmt.channel_layout[CRAS_CH_FL];
- front_right = conv->in_fmt.channel_layout[CRAS_CH_FR];
- rear_left = conv->in_fmt.channel_layout[CRAS_CH_RL];
- rear_right = conv->in_fmt.channel_layout[CRAS_CH_RR];
-
- return s16_quad_to_stereo(front_left, front_right, rear_left,
- rear_right, in, in_frames, out);
-}
-
-static size_t default_all_to_all(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- size_t num_in_ch, num_out_ch;
-
- num_in_ch = conv->in_fmt.num_channels;
- num_out_ch = conv->out_fmt.num_channels;
-
- return s16_default_all_to_all(&conv->out_fmt, num_in_ch, num_out_ch, in,
- in_frames, out);
-}
-
-// Fill min(in channels, out_channels), leave the rest 0s.
-static size_t default_some_to_some(struct cras_fmt_conv *conv,
- const uint8_t *in,
- size_t in_frames,
- uint8_t *out)
-{
- size_t num_in_ch, num_out_ch;
-
- num_in_ch = conv->in_fmt.num_channels;
- num_out_ch = conv->out_fmt.num_channels;
-
- return s16_some_to_some(&conv->out_fmt, num_in_ch, num_out_ch, in,
- in_frames, out);
-}
-
-static size_t convert_channels(struct cras_fmt_conv *conv, const uint8_t *in,
- size_t in_frames, uint8_t *out)
-{
- float **ch_conv_mtx;
- size_t num_in_ch, num_out_ch;
-
- ch_conv_mtx = conv->ch_conv_mtx;
- num_in_ch = conv->in_fmt.num_channels;
- num_out_ch = conv->out_fmt.num_channels;
-
- return s16_convert_channels(ch_conv_mtx, num_in_ch, num_out_ch, in,
- in_frames, out);
-}
-
-/*
- * Exported interface
- */
-
-struct cras_fmt_conv *cras_fmt_conv_create(const struct cras_audio_format *in,
- const struct cras_audio_format *out,
- size_t max_frames,
- size_t pre_linear_resample)
-{
- struct cras_fmt_conv *conv;
- int rc;
- unsigned i;
-
- conv = calloc(1, sizeof(*conv));
- if (conv == NULL)
- return NULL;
- conv->in_fmt = *in;
- conv->out_fmt = *out;
- conv->tmp_buf_frames = max_frames;
- conv->pre_linear_resample = pre_linear_resample;
-
- if (!is_supported_format(in)) {
- syslog(LOG_ERR, "Invalid input format %d", in->format);
- cras_fmt_conv_destroy(&conv);
- return NULL;
- }
-
- if (!is_supported_format(out)) {
- syslog(LOG_ERR, "Invalid output format %d", out->format);
- cras_fmt_conv_destroy(&conv);
- return NULL;
- }
-
- /* Set up sample format conversion. */
- /* TODO(dgreid) - modify channel and sample rate conversion so
- * converting to s16 isnt necessary. */
- if (in->format != SND_PCM_FORMAT_S16_LE) {
- conv->num_converters++;
- syslog(LOG_DEBUG, "Convert from format %d to %d.", in->format,
- out->format);
- switch (in->format) {
- case SND_PCM_FORMAT_U8:
- conv->in_format_converter = convert_u8_to_s16le;
- break;
- case SND_PCM_FORMAT_S24_LE:
- conv->in_format_converter = convert_s24le_to_s16le;
- break;
- case SND_PCM_FORMAT_S32_LE:
- conv->in_format_converter = convert_s32le_to_s16le;
- break;
- case SND_PCM_FORMAT_S24_3LE:
- conv->in_format_converter = convert_s243le_to_s16le;
- break;
- default:
- syslog(LOG_ERR, "Should never reachable");
- break;
- }
- }
- if (out->format != SND_PCM_FORMAT_S16_LE) {
- conv->num_converters++;
- syslog(LOG_DEBUG, "Convert from format %d to %d.", in->format,
- out->format);
- switch (out->format) {
- case SND_PCM_FORMAT_U8:
- conv->out_format_converter = convert_s16le_to_u8;
- break;
- case SND_PCM_FORMAT_S24_LE:
- conv->out_format_converter = convert_s16le_to_s24le;
- break;
- case SND_PCM_FORMAT_S32_LE:
- conv->out_format_converter = convert_s16le_to_s32le;
- break;
- case SND_PCM_FORMAT_S24_3LE:
- conv->out_format_converter = convert_s16le_to_s243le;
- break;
- default:
- syslog(LOG_ERR, "Should never reachable");
- break;
- }
- }
-
- /* Set up channel number conversion. */
- if (in->num_channels != out->num_channels) {
- conv->num_converters++;
- syslog(LOG_DEBUG, "Convert from %zu to %zu channels.",
- in->num_channels, out->num_channels);
-
- /* Populate the conversion matrix base on in/out channel count
- * and layout. */
- if (in->num_channels == 1 && out->num_channels == 2) {
- conv->channel_converter = mono_to_stereo;
- } else if (in->num_channels == 1 && out->num_channels == 6) {
- conv->channel_converter = mono_to_51;
- } else if (in->num_channels == 2 && out->num_channels == 1) {
- conv->channel_converter = stereo_to_mono;
- } else if (in->num_channels == 2 && out->num_channels == 4) {
- conv->channel_converter = stereo_to_quad;
- } else if (in->num_channels == 4 && out->num_channels == 2) {
- conv->channel_converter = quad_to_stereo;
- } else if (in->num_channels == 2 && out->num_channels == 6) {
- conv->channel_converter = stereo_to_51;
- } else if (in->num_channels == 4 && out->num_channels == 6) {
- conv->channel_converter = quad_to_51;
- } else if (in->num_channels == 6 &&
- (out->num_channels == 2 || out->num_channels == 4)) {
- int in_channel_layout_set = 0;
-
- /* Checks if channel_layout is set in the incoming format */
- for (i = 0; i < CRAS_CH_MAX; i++)
- if (in->channel_layout[i] != -1)
- in_channel_layout_set = 1;
-
- /* Use the conversion matrix based converter when a
- * channel layout is set, or default to use existing
- * converter to downmix to stereo */
- if (in_channel_layout_set) {
- conv->ch_conv_mtx =
- cras_channel_conv_matrix_alloc(
- in->num_channels,
- out->num_channels);
- if (conv->ch_conv_mtx == NULL) {
- cras_fmt_conv_destroy(&conv);
- return NULL;
- }
- conv->channel_converter = convert_channels;
- if (out->num_channels == 4) {
- surround51_to_quad_downmix_mtx(
- conv->ch_conv_mtx,
- conv->in_fmt.channel_layout);
- } else {
- surround51_to_stereo_downmix_mtx(
- conv->ch_conv_mtx,
- conv->in_fmt.channel_layout);
- }
- } else {
- if (out->num_channels == 4)
- conv->channel_converter = _51_to_quad;
- else
- conv->channel_converter = _51_to_stereo;
- }
- } else if (in->num_channels <= 8 && out->num_channels <= 8) {
- // For average channel counts mix from all to all.
- syslog(LOG_WARNING,
- "Using all_to_all map for %zu to %zu",
- in->num_channels, out->num_channels);
- conv->channel_converter = default_all_to_all;
- } else {
- syslog(LOG_WARNING,
- "Using some_to_some channel map for %zu to %zu",
- in->num_channels, out->num_channels);
- conv->channel_converter = default_some_to_some;
- }
- } else if (in->num_channels > 2 && !is_channel_layout_equal(in, out)) {
- conv->num_converters++;
- conv->ch_conv_mtx = cras_channel_conv_matrix_create(in, out);
- if (conv->ch_conv_mtx == NULL) {
- syslog(LOG_ERR,
- "Failed to create channel conversion matrix."
- "Fallback to default_all_to_all.");
- conv->channel_converter = default_all_to_all;
- } else {
- conv->channel_converter = convert_channels;
- }
- }
- /* Set up sample rate conversion. */
- if (in->frame_rate != out->frame_rate) {
- conv->num_converters++;
- syslog(LOG_DEBUG, "Convert from %zu to %zu Hz.", in->frame_rate,
- out->frame_rate);
- conv->speex_state =
- speex_resampler_init(out->num_channels, in->frame_rate,
- out->frame_rate,
- SPEEX_QUALITY_LEVEL, &rc);
- if (conv->speex_state == NULL) {
- syslog(LOG_ERR, "Fail to create speex:%zu %zu %zu %d",
- out->num_channels, in->frame_rate,
- out->frame_rate, rc);
- cras_fmt_conv_destroy(&conv);
- return NULL;
- }
- }
-
- /*
- * Set up linear resampler.
- *
- * Note: intended to give both src_rate and dst_rate the same value
- * (i.e. out->frame_rate). They will be updated in runtime in
- * update_estimated_rate() when the audio thread wants to adjust the
- * rate for inaccurate device consumption rate.
- */
- conv->num_converters++;
- conv->resampler =
- linear_resampler_create(out->num_channels,
- cras_get_format_bytes(out),
- out->frame_rate, out->frame_rate);
- if (conv->resampler == NULL) {
- syslog(LOG_ERR, "Fail to create linear resampler");
- cras_fmt_conv_destroy(&conv);
- return NULL;
- }
-
- /* Need num_converters-1 temp buffers, the final converter renders
- * directly into the output. */
- for (i = 0; i < conv->num_converters - 1; i++) {
- conv->tmp_bufs[i] = malloc(
- max_frames * 4 * /* width in bytes largest format. */
- MAX(in->num_channels, out->num_channels));
- if (conv->tmp_bufs[i] == NULL) {
- cras_fmt_conv_destroy(&conv);
- return NULL;
- }
- }
-
- assert(conv->num_converters <= MAX_NUM_CONVERTERS);
-
- return conv;
-}
-
-void cras_fmt_conv_destroy(struct cras_fmt_conv **convp)
-{
- unsigned i;
- struct cras_fmt_conv *conv = *convp;
-
- if (conv->ch_conv_mtx)
- cras_channel_conv_matrix_destroy(conv->ch_conv_mtx,
- conv->out_fmt.num_channels);
- if (conv->speex_state)
- speex_resampler_destroy(conv->speex_state);
- if (conv->resampler)
- linear_resampler_destroy(conv->resampler);
- for (i = 0; i < MAX_NUM_CONVERTERS - 1; i++)
- free(conv->tmp_bufs[i]);
- free(conv);
- *convp = NULL;
-}
-
-struct cras_fmt_conv *cras_channel_remix_conv_create(unsigned int num_channels,
- const float *coefficient)
-{
- struct cras_fmt_conv *conv;
- unsigned out_ch, in_ch;
-
- conv = calloc(1, sizeof(*conv));
- if (conv == NULL)
- return NULL;
- conv->in_fmt.num_channels = num_channels;
- conv->out_fmt.num_channels = num_channels;
-
- conv->ch_conv_mtx =
- cras_channel_conv_matrix_alloc(num_channels, num_channels);
- /* Convert the coeffiencnt array to conversion matrix. */
- for (out_ch = 0; out_ch < num_channels; out_ch++)
- for (in_ch = 0; in_ch < num_channels; in_ch++)
- conv->ch_conv_mtx[out_ch][in_ch] =
- coefficient[in_ch + out_ch * num_channels];
-
- conv->num_converters = 1;
- conv->tmp_bufs[0] = malloc(4 * /* width in bytes largest format. */
- num_channels);
- return conv;
-}
-
-void cras_channel_remix_convert(struct cras_fmt_conv *conv,
- const struct cras_audio_format *fmt,
- uint8_t *in_buf, size_t nframes)
-{
- unsigned ch, fr;
- int16_t *tmp = (int16_t *)conv->tmp_bufs[0];
- int16_t *buf = (int16_t *)in_buf;
-
- /*
- * Skip remix for non S16_LE format.
- * TODO(tzungbi): support 24 bits remix convert.
- */
- if (fmt->format != SND_PCM_FORMAT_S16_LE)
- return;
-
- /* Do remix only when input buffer has the same number of channels. */
- if (fmt->num_channels != conv->in_fmt.num_channels)
- return;
-
- for (fr = 0; fr < nframes; fr++) {
- for (ch = 0; ch < conv->in_fmt.num_channels; ch++)
- tmp[ch] = s16_multiply_buf_with_coef(
- conv->ch_conv_mtx[ch], buf,
- conv->in_fmt.num_channels);
- for (ch = 0; ch < conv->in_fmt.num_channels; ch++)
- buf[ch] = tmp[ch];
- buf += conv->in_fmt.num_channels;
- }
-}
-
-const struct cras_audio_format *
-cras_fmt_conv_in_format(const struct cras_fmt_conv *conv)
-{
- return &conv->in_fmt;
-}
-
-const struct cras_audio_format *
-cras_fmt_conv_out_format(const struct cras_fmt_conv *conv)
-{
- return &conv->out_fmt;
-}
-
-size_t cras_fmt_conv_in_frames_to_out(struct cras_fmt_conv *conv,
- size_t in_frames)
-{
- if (!conv)
- return in_frames;
-
- if (conv->pre_linear_resample)
- in_frames = linear_resampler_in_frames_to_out(conv->resampler,
- in_frames);
- in_frames = cras_frames_at_rate(conv->in_fmt.frame_rate, in_frames,
- conv->out_fmt.frame_rate);
- if (!conv->pre_linear_resample)
- in_frames = linear_resampler_in_frames_to_out(conv->resampler,
- in_frames);
- return in_frames;
-}
-
-size_t cras_fmt_conv_out_frames_to_in(struct cras_fmt_conv *conv,
- size_t out_frames)
-{
- if (!conv)
- return out_frames;
- if (!conv->pre_linear_resample)
- out_frames = linear_resampler_out_frames_to_in(conv->resampler,
- out_frames);
- out_frames = cras_frames_at_rate(conv->out_fmt.frame_rate, out_frames,
- conv->in_fmt.frame_rate);
- if (conv->pre_linear_resample)
- out_frames = linear_resampler_out_frames_to_in(conv->resampler,
- out_frames);
- return out_frames;
-}
-
-void cras_fmt_conv_set_linear_resample_rates(struct cras_fmt_conv *conv,
- float from, float to)
-{
- linear_resampler_set_rates(conv->resampler, from, to);
-}
-
-size_t cras_fmt_conv_convert_frames(struct cras_fmt_conv *conv,
- const uint8_t *in_buf, uint8_t *out_buf,
- unsigned int *in_frames, size_t out_frames)
-{
- uint32_t fr_in, fr_out;
- uint8_t *buffers[MAX_NUM_CONVERTERS + 1]; /* converters + out buffer. */
- size_t buf_idx = 0;
- static int logged_frames_dont_fit;
- unsigned int used_converters = conv->num_converters;
- unsigned int post_linear_resample = 0;
- unsigned int pre_linear_resample = 0;
- unsigned int linear_resample_fr = 0;
-
- assert(conv);
- assert(*in_frames <= conv->tmp_buf_frames);
-
- if (linear_resampler_needed(conv->resampler)) {
- post_linear_resample = !conv->pre_linear_resample;
- pre_linear_resample = conv->pre_linear_resample;
- }
-
- /* If no SRC, then in_frames should = out_frames. */
- if (conv->speex_state == NULL) {
- fr_in = MIN(*in_frames, out_frames);
- if (out_frames < *in_frames && !logged_frames_dont_fit) {
- syslog(LOG_INFO, "fmt_conv: %u to %zu no SRC.",
- *in_frames, out_frames);
- logged_frames_dont_fit = 1;
- }
- } else {
- fr_in = *in_frames;
- }
- fr_out = fr_in;
-
- /* Set up a chain of buffers. The output buffer of the first conversion
- * is used as input to the second and so forth, ending in the output
- * buffer. */
- if (!linear_resampler_needed(conv->resampler))
- used_converters--;
-
- buffers[4] = (uint8_t *)conv->tmp_bufs[3];
- buffers[3] = (uint8_t *)conv->tmp_bufs[2];
- buffers[2] = (uint8_t *)conv->tmp_bufs[1];
- buffers[1] = (uint8_t *)conv->tmp_bufs[0];
- buffers[0] = (uint8_t *)in_buf;
- buffers[used_converters] = out_buf;
-
- if (pre_linear_resample) {
- linear_resample_fr = fr_in;
- unsigned resample_limit = out_frames;
-
- /* If there is a 2nd fmt conversion we should convert the
- * resample limit and round it to the lower bound in order
- * not to convert too many frames in the pre linear resampler.
- */
- if (conv->speex_state != NULL) {
- resample_limit = resample_limit *
- conv->in_fmt.frame_rate /
- conv->out_fmt.frame_rate;
- /*
- * However if the limit frames count is less than
- * |out_rate / in_rate|, the final limit value could be
- * rounded to zero so it confuses linear resampler to
- * do nothing. Make sure it's non-zero in that case.
- */
- if (resample_limit == 0)
- resample_limit = 1;
- }
-
- resample_limit = MIN(resample_limit, conv->tmp_buf_frames);
- fr_in = linear_resampler_resample(
- conv->resampler, buffers[buf_idx], &linear_resample_fr,
- buffers[buf_idx + 1], resample_limit);
- buf_idx++;
- }
-
- /* If the input format isn't S16_LE convert to it. */
- if (conv->in_fmt.format != SND_PCM_FORMAT_S16_LE) {
- conv->in_format_converter(buffers[buf_idx],
- fr_in * conv->in_fmt.num_channels,
- (uint8_t *)buffers[buf_idx + 1]);
- buf_idx++;
- }
-
- /* Then channel conversion. */
- if (conv->channel_converter != NULL) {
- conv->channel_converter(conv, buffers[buf_idx], fr_in,
- buffers[buf_idx + 1]);
- buf_idx++;
- }
-
- /* Then SRC. */
- if (conv->speex_state != NULL) {
- unsigned int out_limit = out_frames;
-
- if (post_linear_resample)
- out_limit = linear_resampler_out_frames_to_in(
- conv->resampler, out_limit);
- fr_out = cras_frames_at_rate(conv->in_fmt.frame_rate, fr_in,
- conv->out_fmt.frame_rate);
- if (fr_out > out_frames + 1 && !logged_frames_dont_fit) {
- syslog(LOG_INFO,
- "fmt_conv: put %u frames in %zu sized buffer",
- fr_out, out_frames);
- logged_frames_dont_fit = 1;
- }
- /* limit frames to the output size. */
- fr_out = MIN(fr_out, out_limit);
- speex_resampler_process_interleaved_int(
- conv->speex_state, (int16_t *)buffers[buf_idx], &fr_in,
- (int16_t *)buffers[buf_idx + 1], &fr_out);
- buf_idx++;
- }
-
- if (post_linear_resample) {
- linear_resample_fr = fr_out;
- unsigned resample_limit = MIN(conv->tmp_buf_frames, out_frames);
- fr_out = linear_resampler_resample(
- conv->resampler, buffers[buf_idx], &linear_resample_fr,
- buffers[buf_idx + 1], resample_limit);
- buf_idx++;
- }
-
- /* If the output format isn't S16_LE convert to it. */
- if (conv->out_fmt.format != SND_PCM_FORMAT_S16_LE) {
- conv->out_format_converter(buffers[buf_idx],
- fr_out * conv->out_fmt.num_channels,
- (uint8_t *)buffers[buf_idx + 1]);
- buf_idx++;
- }
-
- if (pre_linear_resample) {
- *in_frames = linear_resample_fr;
-
- /* When buffer sizes are small, there's a corner case that
- * speex library resamples 0 frame to N-1 frames, where N
- * is the integer ratio of output and input rate. For example,
- * 16KHz to 48KHz. In this case fmt_conv should claim zero
- * frames processed, instead of using the linear resampler
- * processed frames count. Otherwise there will be a frame
- * leak and, if accumulated, causes delay in multiple devices
- * use case.
- */
- if (conv->speex_state && (fr_in == 0))
- *in_frames = 0;
- } else {
- *in_frames = fr_in;
- }
- return fr_out;
-}
-
-int cras_fmt_conversion_needed(const struct cras_fmt_conv *conv)
-{
- return linear_resampler_needed(conv->resampler) ||
- (conv->num_converters > 1);
-}
-
-/* If the server cannot provide the requested format, configures an audio format
- * converter that handles transforming the input format to the format used by
- * the server. */
-int config_format_converter(struct cras_fmt_conv **conv,
- enum CRAS_STREAM_DIRECTION dir,
- const struct cras_audio_format *from,
- const struct cras_audio_format *to,
- unsigned int frames)
-{
- struct cras_audio_format target;
-
- /* For input, preserve the channel count and layout of
- * from format */
- if (dir == CRAS_STREAM_INPUT) {
- target = *from;
- target.format = to->format;
- target.frame_rate = to->frame_rate;
- } else {
- target = *to;
- }
-
- syslog(LOG_DEBUG,
- "format convert: from:%d %zu %zu target: %d %zu %zu "
- "frames = %u",
- from->format, from->frame_rate, from->num_channels,
- target.format, target.frame_rate, target.num_channels, frames);
- *conv = cras_fmt_conv_create(from, &target, frames,
- (dir == CRAS_STREAM_INPUT));
- if (!*conv) {
- syslog(LOG_ERR, "Failed to create format converter");
- return -ENOMEM;
- }
-
- return 0;
-}
diff --git a/cras/src/server/cras_fmt_conv.h b/cras/src/server/cras_fmt_conv.h
deleted file mode 100644
index 12c0c16a..00000000
--- a/cras/src/server/cras_fmt_conv.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Used to convert from one audio format to another. Currently only supports
- * sample rate conversion with the speex backend.
- */
-#ifndef CRAS_FMT_CONV_H_
-#define CRAS_FMT_CONV_H_
-
-#include <stdint.h>
-#include <stdlib.h>
-
-#include "cras_types.h"
-
-struct cras_audio_format;
-struct cras_fmt_conv;
-
-/* Create and destroy format converters. */
-struct cras_fmt_conv *cras_fmt_conv_create(const struct cras_audio_format *in,
- const struct cras_audio_format *out,
- size_t max_frames,
- size_t pre_linear_resample);
-void cras_fmt_conv_destroy(struct cras_fmt_conv **conv);
-
-/* Creates the format converter for channel remixing. The conversion takes
- * a N by N float matrix, to multiply each N-channels sample.
- * Args:
- * num_channels - Number of channels of PCM data.
- * coefficient - Float array of length N * N representing the conversion
- * matrix, where matrix[i][j] corresponds to coefficient[i * N + j]
- */
-struct cras_fmt_conv *cras_channel_remix_conv_create(unsigned int num_channels,
- const float *coefficient);
-
-/* Converts nframes of sample from in_buf, using given remix converter.
- * Args:
- * conv - The format converter.
- * fmt - The format of the buffer to convert.
- * in_buf - The buffer to convert.
- * nframes - The number of frames to convert.
- */
-void cras_channel_remix_convert(struct cras_fmt_conv *conv,
- const struct cras_audio_format *fmt,
- uint8_t *in_buf, size_t nframes);
-
-/* Get the input format of the converter. */
-const struct cras_audio_format *
-cras_fmt_conv_in_format(const struct cras_fmt_conv *conv);
-
-/* Get the output format of the converter. */
-const struct cras_audio_format *
-cras_fmt_conv_out_format(const struct cras_fmt_conv *conv);
-
-/* Get the number of output frames that will result from converting in_frames */
-size_t cras_fmt_conv_in_frames_to_out(struct cras_fmt_conv *conv,
- size_t in_frames);
-/* Get the number of input frames that will result from converting out_frames */
-size_t cras_fmt_conv_out_frames_to_in(struct cras_fmt_conv *conv,
- size_t out_frames);
-/* Sets the input and output rate to the linear resampler. */
-void cras_fmt_conv_set_linear_resample_rates(struct cras_fmt_conv *conv,
- float from, float to);
-/* Converts in_frames samples from in_buf, storing the results in out_buf.
- * Args:
- * conv - The format converter returned from cras_fmt_conv_create().
- * in_buf - Samples to convert.
- * out_buf - Converted samples are placed here.
- * in_frames - Number of frames from in_buf to convert.
- * out_frames - Maximum number of frames to store in out_buf. If there isn't
- * any format conversion, out_frames must be >= in_frames. When doing
- * format conversion out_frames should be able to hold all the converted
- * frames, this can be checked with cras_fmt_conv_in_frames_to_out().
- * Return number of frames put in out_buf. */
-size_t cras_fmt_conv_convert_frames(struct cras_fmt_conv *conv,
- const uint8_t *in_buf, uint8_t *out_buf,
- unsigned int *in_frames, size_t out_frames);
-
-/* Checks if format conversion is needed for a fmt converter.
- * Args:
- * conv - The format convert to check.
- * Returns:
- * Non-zero if a format conversion is needed.
- */
-int cras_fmt_conversion_needed(const struct cras_fmt_conv *conv);
-
-/* If the server cannot provide the requested format, configures an audio format
- * converter that handles transforming the input format to the format used by
- * the server.
- * Args:
- * conv - filled with the new converter if needed.
- * dir - the stream direction the new converter used for.
- * from - Format to convert from.
- * to - Format to convert to.
- * frames - size of buffer.
- */
-int config_format_converter(struct cras_fmt_conv **conv,
- enum CRAS_STREAM_DIRECTION dir,
- const struct cras_audio_format *from,
- const struct cras_audio_format *to,
- unsigned int frames);
-
-#endif /* CRAS_FMT_CONV_H_ */
diff --git a/cras/src/server/cras_fmt_conv_ops.c b/cras/src/server/cras_fmt_conv_ops.c
deleted file mode 100644
index adc55215..00000000
--- a/cras/src/server/cras_fmt_conv_ops.c
+++ /dev/null
@@ -1,503 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <stdint.h>
-#include <limits.h>
-#include <string.h>
-
-#include "cras_fmt_conv_ops.h"
-
-#define MAX(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a > _b ? _a : _b; \
- })
-#define MIN(a, b) \
- ({ \
- __typeof__(a) _a = (a); \
- __typeof__(b) _b = (b); \
- _a < _b ? _a : _b; \
- })
-
-/*
- * Add and clip.
- */
-static int16_t s16_add_and_clip(int16_t a, int16_t b)
-{
- int32_t sum;
-
- a = htole16(a);
- b = htole16(b);
- sum = (int32_t)a + (int32_t)b;
- sum = MAX(sum, SHRT_MIN);
- sum = MIN(sum, SHRT_MAX);
- return (int16_t)le16toh(sum);
-}
-
-/*
- * Format converter.
- */
-void convert_u8_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- uint16_t *_out = (uint16_t *)out;
-
- for (i = 0; i < in_samples; i++, in++, _out++)
- *_out = (uint16_t)((int16_t)*in - 0x80) << 8;
-}
-
-void convert_s243le_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- /* find how to calculate in and out size, implement the conversion
- * between S24_3LE and S16 */
-
- size_t i;
- int8_t *_in = (int8_t *)in;
- uint16_t *_out = (uint16_t *)out;
-
- for (i = 0; i < in_samples; i++, _in += 3, _out++)
- memcpy(_out, _in + 1, 2);
-}
-
-void convert_s24le_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- int32_t *_in = (int32_t *)in;
- uint16_t *_out = (uint16_t *)out;
-
- for (i = 0; i < in_samples; i++, _in++, _out++)
- *_out = (int16_t)((*_in & 0x00ffffff) >> 8);
-}
-
-void convert_s32le_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- int32_t *_in = (int32_t *)in;
- uint16_t *_out = (uint16_t *)out;
-
- for (i = 0; i < in_samples; i++, _in++, _out++)
- *_out = (int16_t)(*_in >> 16);
-}
-
-void convert_s16le_to_u8(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- int16_t *_in = (int16_t *)in;
-
- for (i = 0; i < in_samples; i++, _in++, out++)
- *out = (uint8_t)(*_in >> 8) + 128;
-}
-
-void convert_s16le_to_s243le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- int16_t *_in = (int16_t *)in;
- uint8_t *_out = (uint8_t *)out;
-
- for (i = 0; i < in_samples; i++, _in++, _out += 3) {
- *_out = 0;
- memcpy(_out + 1, _in, 2);
- }
-}
-
-void convert_s16le_to_s24le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- int16_t *_in = (int16_t *)in;
- uint32_t *_out = (uint32_t *)out;
-
- for (i = 0; i < in_samples; i++, _in++, _out++)
- *_out = ((uint32_t)(int32_t)*_in << 8);
-}
-
-void convert_s16le_to_s32le(const uint8_t *in, size_t in_samples, uint8_t *out)
-{
- size_t i;
- int16_t *_in = (int16_t *)in;
- uint32_t *_out = (uint32_t *)out;
-
- for (i = 0; i < in_samples; i++, _in++, _out++)
- *_out = ((uint32_t)(int32_t)*_in << 16);
-}
-
-/*
- * Channel converter: mono to stereo.
- */
-size_t s16_mono_to_stereo(const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- for (i = 0; i < in_frames; i++) {
- out[2 * i] = in[i];
- out[2 * i + 1] = in[i];
- }
- return in_frames;
-}
-
-/*
- * Channel converter: stereo to mono.
- */
-size_t s16_stereo_to_mono(const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- for (i = 0; i < in_frames; i++)
- out[i] = s16_add_and_clip(in[2 * i], in[2 * i + 1]);
- return in_frames;
-}
-
-/*
- * Channel converter: mono to 5.1 surround.
- *
- * Fit mono to front center of the output, or split to front left/right
- * if front center is missing from the output channel layout.
- */
-size_t s16_mono_to_51(size_t left, size_t right, size_t center,
- const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- memset(out, 0, sizeof(*out) * 6 * in_frames);
-
- if (center != -1)
- for (i = 0; i < in_frames; i++)
- out[6 * i + center] = in[i];
- else if (left != -1 && right != -1)
- for (i = 0; i < in_frames; i++) {
- out[6 * i + right] = in[i] / 2;
- out[6 * i + left] = in[i] / 2;
- }
- else
- /* Select the first channel to convert to as the
- * default behavior.
- */
- for (i = 0; i < in_frames; i++)
- out[6 * i] = in[i];
-
- return in_frames;
-}
-
-/*
- * Channel converter: stereo to 5.1 surround.
- *
- * Fit the left/right of input to the front left/right of output respectively
- * and fill others with zero. If any of the front left/right is missed from
- * the output channel layout, mix to front center.
- */
-size_t s16_stereo_to_51(size_t left, size_t right, size_t center,
- const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- memset(out, 0, sizeof(*out) * 6 * in_frames);
-
- if (left != -1 && right != -1)
- for (i = 0; i < in_frames; i++) {
- out[6 * i + left] = in[2 * i];
- out[6 * i + right] = in[2 * i + 1];
- }
- else if (center != -1)
- for (i = 0; i < in_frames; i++)
- out[6 * i + center] =
- s16_add_and_clip(in[2 * i], in[2 * i + 1]);
- else
- /* Select the first two channels to convert to as the
- * default behavior.
- */
- for (i = 0; i < in_frames; i++) {
- out[6 * i] = in[2 * i];
- out[6 * i + 1] = in[2 * i + 1];
- }
-
- return in_frames;
-}
-
-/*
- * Channel converter: quad to 5.1 surround.
- *
- * Fit the front left/right of input to the front left/right of output
- * and rear left/right of input to the rear left/right of output
- * respectively and fill others with zero.
- */
-size_t s16_quad_to_51(size_t font_left, size_t front_right, size_t rear_left,
- size_t rear_right, const uint8_t *_in, size_t in_frames,
- uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- memset(out, 0, sizeof(*out) * 6 * in_frames);
-
- if (font_left != -1 && front_right != -1 && rear_left != -1 &&
- rear_right != -1)
- for (i = 0; i < in_frames; i++) {
- out[6 * i + font_left] = in[4 * i];
- out[6 * i + front_right] = in[4 * i + 1];
- out[6 * i + rear_left] = in[4 * i + 2];
- out[6 * i + rear_right] = in[4 * i + 3];
- }
- else
- /* Use default 5.1 channel mapping for the conversion.
- */
- for (i = 0; i < in_frames; i++) {
- out[6 * i] = in[4 * i];
- out[6 * i + 1] = in[4 * i + 1];
- out[6 * i + 4] = in[4 * i + 2];
- out[6 * i + 5] = in[4 * i + 3];
- }
-
- return in_frames;
-}
-
-/*
- * Channel converter: 5.1 surround to stereo.
- *
- * The out buffer can have room for just stereo samples. This convert function
- * is used as the default behavior when channel layout is not set from the
- * client side.
- */
-size_t s16_51_to_stereo(const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
- static const unsigned int left_idx = 0;
- static const unsigned int right_idx = 1;
- static const unsigned int center_idx = 2;
- /* static const unsigned int lfe_idx = 3; */
- /* static const unsigned int left_surround_idx = 4; */
- /* static const unsigned int right_surround_idx = 5; */
-
- size_t i;
- int16_t half_center;
- /* Use the normalized_factor from the left channel = 1 / (|1| + |0.707|)
- * to prevent mixing overflow.
- */
- const float normalized_factor = 0.585;
- for (i = 0; i < in_frames; i++) {
- half_center =
- in[6 * i + center_idx] * 0.707 * normalized_factor;
- out[2 * i + left_idx] =
- in[6 * i + left_idx] * normalized_factor + half_center;
- out[2 * i + right_idx] =
- in[6 * i + right_idx] * normalized_factor + half_center;
- }
- return in_frames;
-}
-
-/*
- * Channel converter: 5.1 surround to quad (front L/R, rear L/R).
- *
- * The out buffer can have room for just quad samples. This convert function
- * is used as the default behavior when channel layout is not set from the
- * client side.
- */
-size_t s16_51_to_quad(const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
- static const unsigned int l_quad = 0;
- static const unsigned int r_quad = 1;
- static const unsigned int rl_quad = 2;
- static const unsigned int rr_quad = 3;
-
- static const unsigned int l_51 = 0;
- static const unsigned int r_51 = 1;
- static const unsigned int center_51 = 2;
- static const unsigned int lfe_51 = 3;
- static const unsigned int rl_51 = 4;
- static const unsigned int rr_51 = 5;
-
- /* Use normalized_factor from the left channel = 1 / (|1| + |0.707| + |0.5|)
- * to prevent overflow. */
- const float normalized_factor = 0.453;
- size_t i;
- for (i = 0; i < in_frames; i++) {
- int16_t half_center;
- int16_t lfe;
-
- half_center = in[6 * i + center_51] * 0.707 * normalized_factor;
- lfe = in[6 * i + lfe_51] * 0.5 * normalized_factor;
- out[4 * i + l_quad] = normalized_factor * in[6 * i + l_51] +
- half_center + lfe;
- out[4 * i + r_quad] = normalized_factor * in[6 * i + r_51] +
- half_center + lfe;
- out[4 * i + rl_quad] =
- normalized_factor * in[6 * i + rl_51] + lfe;
- out[4 * i + rr_quad] =
- normalized_factor * in[6 * i + rr_51] + lfe;
- }
- return in_frames;
-}
-
-/*
- * Channel converter: stereo to quad (front L/R, rear L/R).
- *
- * Fit left/right of input to the front left/right of output respectively
- * and fill others with zero.
- */
-size_t s16_stereo_to_quad(size_t front_left, size_t front_right,
- size_t rear_left, size_t rear_right,
- const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- if (front_left != -1 && front_right != -1 && rear_left != -1 &&
- rear_right != -1)
- for (i = 0; i < in_frames; i++) {
- out[4 * i + front_left] = in[2 * i];
- out[4 * i + front_right] = in[2 * i + 1];
- out[4 * i + rear_left] = in[2 * i];
- out[4 * i + rear_right] = in[2 * i + 1];
- }
- else
- /* Select the first four channels to convert to as the
- * default behavior.
- */
- for (i = 0; i < in_frames; i++) {
- out[4 * i] = in[2 * i];
- out[4 * i + 1] = in[2 * i + 1];
- out[4 * i + 2] = in[2 * i];
- out[4 * i + 3] = in[2 * i + 1];
- }
-
- return in_frames;
-}
-
-/*
- * Channel converter: quad (front L/R, rear L/R) to stereo.
- */
-size_t s16_quad_to_stereo(size_t front_left, size_t front_right,
- size_t rear_left, size_t rear_right,
- const uint8_t *_in, size_t in_frames, uint8_t *_out)
-{
- size_t i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- if (front_left == -1 || front_right == -1 || rear_left == -1 ||
- rear_right == -1) {
- front_left = 0;
- front_right = 1;
- rear_left = 2;
- rear_right = 3;
- }
-
- for (i = 0; i < in_frames; i++) {
- out[2 * i] = s16_add_and_clip(in[4 * i + front_left],
- in[4 * i + rear_left] / 4);
- out[2 * i + 1] = s16_add_and_clip(in[4 * i + front_right],
- in[4 * i + rear_right] / 4);
- }
- return in_frames;
-}
-
-/*
- * Channel converter: N channels to M channels.
- *
- * The out buffer must have room for M channel. This convert function is used
- * as the default behavior when channel layout is not set from the client side.
- */
-size_t s16_default_all_to_all(struct cras_audio_format *out_fmt,
- size_t num_in_ch, size_t num_out_ch,
- const uint8_t *_in, size_t in_frames,
- uint8_t *_out)
-{
- unsigned int in_ch, out_ch, i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
- int32_t sum;
-
- for (i = 0; i < in_frames; i++) {
- sum = 0;
- for (in_ch = 0; in_ch < num_in_ch; in_ch++) {
- sum += (int32_t)in[in_ch + i * num_in_ch];
- }
- /*
- * 1. Divide `int32_t` by `size_t` without an explicit
- * conversion will generate corrupted results.
- * 2. After the division, `sum` should be in the range of
- * int16_t. No clipping is needed.
- */
- sum /= (int32_t)num_in_ch;
- for (out_ch = 0; out_ch < num_out_ch; out_ch++) {
- out[out_ch + i * num_out_ch] = (int16_t)sum;
- }
- }
- return in_frames;
-}
-
-/*
- * Copies the input channels across output channels. Drops input channels that
- * don't fit. Ignores output channels greater than the number of input channels.
- */
-size_t s16_some_to_some(const struct cras_audio_format *out_fmt,
- const size_t num_in_ch, const size_t num_out_ch,
- const uint8_t *_in, const size_t frame_count,
- uint8_t *_out)
-{
- unsigned int i;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
- const size_t num_copy_ch = MIN(num_in_ch, num_out_ch);
-
- memset(out, 0, frame_count * cras_get_format_bytes(out_fmt));
- for (i = 0; i < frame_count; i++, out += num_out_ch, in += num_in_ch) {
- memcpy(out, in, num_copy_ch * sizeof(int16_t));
- }
-
- return frame_count;
-}
-
-/*
- * Multiplies buffer vector with coefficient vector.
- */
-int16_t s16_multiply_buf_with_coef(float *coef, const int16_t *buf, size_t size)
-{
- int32_t sum = 0;
- int i;
-
- for (i = 0; i < size; i++)
- sum += coef[i] * buf[i];
- sum = MAX(sum, -0x8000);
- sum = MIN(sum, 0x7fff);
- return (int16_t)sum;
-}
-
-/*
- * Channel layout converter.
- *
- * Converts channels based on the channel conversion coefficient matrix.
- */
-size_t s16_convert_channels(float **ch_conv_mtx, size_t num_in_ch,
- size_t num_out_ch, const uint8_t *_in,
- size_t in_frames, uint8_t *_out)
-{
- unsigned i, fr;
- unsigned in_idx = 0;
- unsigned out_idx = 0;
- const int16_t *in = (const int16_t *)_in;
- int16_t *out = (int16_t *)_out;
-
- for (fr = 0; fr < in_frames; fr++) {
- for (i = 0; i < num_out_ch; i++)
- out[out_idx + i] = s16_multiply_buf_with_coef(
- ch_conv_mtx[i], &in[in_idx], num_in_ch);
- in_idx += num_in_ch;
- out_idx += num_out_ch;
- }
-
- return in_frames;
-}
diff --git a/cras/src/server/cras_fmt_conv_ops.h b/cras/src/server/cras_fmt_conv_ops.h
deleted file mode 100644
index 0af7564b..00000000
--- a/cras/src/server/cras_fmt_conv_ops.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_FMT_CONV_OPS_H_
-#define CRAS_FMT_CONV_OPS_H_
-
-#include <sys/types.h>
-#include "cras_audio_format.h"
-
-/*
- * Format converter.
- */
-void convert_u8_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out);
-void convert_s243le_to_s16le(const uint8_t *in, size_t in_samples,
- uint8_t *out);
-void convert_s24le_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out);
-void convert_s32le_to_s16le(const uint8_t *in, size_t in_samples, uint8_t *out);
-void convert_s16le_to_u8(const uint8_t *in, size_t in_samples, uint8_t *out);
-void convert_s16le_to_s243le(const uint8_t *in, size_t in_samples,
- uint8_t *out);
-void convert_s16le_to_s24le(const uint8_t *in, size_t in_samples, uint8_t *out);
-void convert_s16le_to_s32le(const uint8_t *in, size_t in_samples, uint8_t *out);
-
-/*
- * Channel converter: mono to stereo.
- */
-size_t s16_mono_to_stereo(const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: stereo to mono.
- */
-size_t s16_stereo_to_mono(const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: mono to 5.1 surround.
- */
-size_t s16_mono_to_51(size_t left, size_t right, size_t center,
- const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: stereo to 5.1 surround.
- */
-size_t s16_stereo_to_51(size_t left, size_t right, size_t center,
- const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: quad to 5.1 surround.
- */
-size_t s16_quad_to_51(size_t font_left, size_t front_right, size_t rear_left,
- size_t rear_right, const uint8_t *in, size_t in_frames,
- uint8_t *out);
-
-/*
- * Channel converter: 5.1 surround to stereo.
- */
-size_t s16_51_to_stereo(const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: 5.1 surround to quad.
- */
-size_t s16_51_to_quad(const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: stereo to quad (front L/R, rear L/R).
- */
-size_t s16_stereo_to_quad(size_t front_left, size_t front_right,
- size_t rear_left, size_t rear_right,
- const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: quad (front L/R, rear L/R) to stereo.
- */
-size_t s16_quad_to_stereo(size_t front_left, size_t front_right,
- size_t rear_left, size_t rear_right,
- const uint8_t *in, size_t in_frames, uint8_t *out);
-
-/*
- * Channel converter: N channels to M channels.
- */
-size_t s16_default_all_to_all(struct cras_audio_format *out_fmt,
- size_t num_in_ch, size_t num_out_ch,
- const uint8_t *in, size_t in_frames,
- uint8_t *out);
-
-/*
- * Channel converter: N channels to M channels filling min(N,M) channels by
- * directly copying to the destination.
- */
-size_t s16_some_to_some(const struct cras_audio_format *out_fmt,
- const size_t num_in_ch, const size_t num_out_ch,
- const uint8_t *_in, const size_t frame_count,
- uint8_t *_out);
-
-/*
- * Multiplies buffer vector with coefficient vector.
- */
-int16_t s16_multiply_buf_with_coef(float *coef, const int16_t *buf,
- size_t size);
-
-/*
- * Channel layout converter.
- */
-size_t s16_convert_channels(float **ch_conv_mtx, size_t num_in_ch,
- size_t num_out_ch, const uint8_t *in,
- size_t in_frames, uint8_t *out);
-
-#endif /* CRAS_FMT_CONV_OPS_H_ */
diff --git a/cras/src/server/cras_gpio_jack.c b/cras/src/server/cras_gpio_jack.c
deleted file mode 100644
index 70219087..00000000
--- a/cras/src/server/cras_gpio_jack.c
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <fcntl.h>
-#include <linux/input.h>
-#include <stdio.h>
-#include <string.h>
-#include <syslog.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <libudev.h>
-
-#include "cras_util.h"
-#include "cras_gpio_jack.h"
-
-int gpio_switch_open(const char *pathname)
-{
- return open(pathname, O_RDONLY);
-}
-
-int gpio_switch_read(int fd, void *buf, size_t n_bytes)
-{
- return read(fd, buf, n_bytes);
-}
-
-int gpio_switch_eviocgname(int fd, char *name, size_t n_bytes)
-{
- return ioctl(fd, EVIOCGNAME(n_bytes), name);
-}
-
-int gpio_switch_eviocgbit(int fd, void *buf, size_t n_bytes)
-{
- return ioctl(fd, EVIOCGBIT(EV_SW, n_bytes), buf);
-}
-
-int gpio_switch_eviocgsw(int fd, void *bits, size_t n_bytes)
-{
- return ioctl(fd, EVIOCGSW(n_bytes), bits);
-}
-
-char *sys_input_get_device_name(const char *path)
-{
- char name[256];
- int fd = open(path, O_RDONLY);
-
- if (fd >= 0) {
- gpio_switch_eviocgname(fd, name, sizeof(name));
- close(fd);
- return strdup(name);
- } else {
- syslog(LOG_WARNING, "Could not open '%s': %s", path,
- strerror(errno));
- return NULL;
- }
-}
-
-void gpio_switch_list_for_each(gpio_switch_list_callback callback, void *arg)
-{
- struct udev *udev;
- struct udev_enumerate *enumerate;
- struct udev_list_entry *dl;
- struct udev_list_entry *dev_list_entry;
-
- if (!callback)
- return;
-
- udev = udev_new();
- assert(udev != NULL);
- enumerate = udev_enumerate_new(udev);
- udev_enumerate_add_match_subsystem(enumerate, "input");
- udev_enumerate_scan_devices(enumerate);
- dl = udev_enumerate_get_list_entry(enumerate);
-
- udev_list_entry_foreach(dev_list_entry, dl)
- {
- const char *path = udev_list_entry_get_name(dev_list_entry);
- struct udev_device *dev =
- udev_device_new_from_syspath(udev, path);
- const char *devnode = udev_device_get_devnode(dev);
- char *ioctl_name;
-
- if (devnode == NULL)
- continue;
-
- ioctl_name = sys_input_get_device_name(devnode);
- if (ioctl_name == NULL)
- continue;
-
- if (callback(devnode, ioctl_name, arg)) {
- free(ioctl_name);
- break;
- }
- free(ioctl_name);
- }
- udev_enumerate_unref(enumerate);
- udev_unref(udev);
-}
diff --git a/cras/src/server/cras_gpio_jack.h b/cras/src/server/cras_gpio_jack.h
deleted file mode 100644
index e6dd8aab..00000000
--- a/cras/src/server/cras_gpio_jack.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_GPIO_JACK_H
-#define _CRAS_GPIO_JACK_H
-
-#include "cras_types.h"
-
-struct mixer_name;
-
-int gpio_switch_open(const char *pathname);
-int gpio_switch_read(int fd, void *buf, size_t n_bytes);
-
-int gpio_switch_eviocgbit(int fd, void *buf, size_t n_bytes);
-int gpio_switch_eviocgsw(int fd, void *bits, size_t n_bytes);
-
-/* sys_input_get_device_name:
- *
- * Returns the heap-allocated device name of a /dev/input/event*
- * pathname. Caller is responsible for releasing.
- */
-char *sys_input_get_device_name(const char *path);
-
-/* List for each callback function.
- *
- * Args:
- * dev_path - Full path to the GPIO device.
- * dev_name - The name of the GPIO device.
- * arg - The argument passed to gpio_switch_list_for_each.
- *
- * Returns:
- * 0 to continue searching, non-zero otherwise.
- */
-typedef int (*gpio_switch_list_callback)(const char *dev_path,
- const char *dev_name, void *arg);
-
-/* Execute the given callback on each GPIO device.
- *
- * Args:
- * callback - The callback to execute.
- * arg - An argument to pass to the callback.
- */
-void gpio_switch_list_for_each(gpio_switch_list_callback callback, void *arg);
-
-#endif
diff --git a/cras/src/server/cras_hfp_ag_profile.c b/cras/src/server/cras_hfp_ag_profile.c
deleted file mode 100644
index b5fcecc3..00000000
--- a/cras/src/server/cras_hfp_ag_profile.c
+++ /dev/null
@@ -1,466 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-#include <syslog.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-#include "cras_a2dp_endpoint.h"
-#include "cras_bt_adapter.h"
-#include "cras_bt_constants.h"
-#include "cras_bt_log.h"
-#include "cras_bt_profile.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_hfp_info.h"
-#include "cras_hfp_iodev.h"
-#include "cras_hfp_alsa_iodev.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_iodev_list.h"
-#include "utlist.h"
-#include "packet_status_logger.h"
-
-#define HFP_AG_PROFILE_NAME "Hands-Free Voice gateway"
-#define HFP_AG_PROFILE_PATH "/org/chromium/Cras/Bluetooth/HFPAG"
-#define HFP_VERSION 0x0107
-#define HSP_AG_PROFILE_NAME "Headset Voice gateway"
-#define HSP_AG_PROFILE_PATH "/org/chromium/Cras/Bluetooth/HSPAG"
-#define HSP_VERSION_1_2 0x0102
-#define HSP_VERSION_1_2_STR "0x0102"
-
-#define HSP_AG_RECORD \
- "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" \
- "<record>" \
- " <attribute id=\"0x0001\">" \
- " <sequence>" \
- " <uuid value=\"" HSP_AG_UUID "\" />" \
- " <uuid value=\"" GENERIC_AUDIO_UUID "\" />" \
- " </sequence>" \
- " </attribute>" \
- " <attribute id=\"0x0004\">" \
- " <sequence>" \
- " <sequence>" \
- " <uuid value=\"0x0100\" />" \
- " </sequence>" \
- " <sequence>" \
- " <uuid value=\"0x0003\" />" \
- " <uint8 value=\"0x0c\" />" \
- " </sequence>" \
- " </sequence>" \
- " </attribute>" \
- " <attribute id=\"0x0005\">" \
- " <sequence>" \
- " <uuid value=\"0x1002\" />" \
- " </sequence>" \
- " </attribute>" \
- " <attribute id=\"0x0009\">" \
- " <sequence>" \
- " <sequence>" \
- " <uuid value=\"" HSP_HS_UUID "\" />" \
- " <uint16 value=\"" HSP_VERSION_1_2_STR "\" />" \
- " </sequence>" \
- " </sequence>" \
- " </attribute>" \
- " <attribute id=\"0x0100\">" \
- " <text value=\"" HSP_AG_PROFILE_NAME "\" />" \
- " </attribute>" \
- " <attribute id=\"0x0301\" >" \
- " <uint8 value=\"0x01\" />" \
- " </attribute>" \
- "</record>"
-
-/* The supported features value in +BSRF command response of HFP AG in CRAS */
-#define BSRF_SUPPORTED_FEATURES (AG_ENHANCED_CALL_STATUS | AG_HF_INDICATORS)
-
-/* The "SupportedFeatures" attribute value of HFP AG service record in CRAS. */
-#define SDP_SUPPORTED_FEATURES FEATURES_AG_WIDE_BAND_SPEECH
-
-/* Object representing the audio gateway role for HFP/HSP.
- * Members:
- * idev - The input iodev for HFP/HSP.
- * odev - The output iodev for HFP/HSP.
- * info - The hfp_info object for SCO audio.
- * slc_handle - The service level connection.
- * device - The bt device associated with this audio gateway.
- * a2dp_delay_retries - The number of retries left to delay starting
- * the hfp/hsp audio gateway to wait for a2dp connection.
- * conn - The dbus connection used to send message to bluetoothd.
- * profile - The profile enum of this audio gateway.
- */
-struct audio_gateway {
- struct cras_iodev *idev;
- struct cras_iodev *odev;
- struct hfp_info *info;
- struct hfp_slc_handle *slc_handle;
- struct cras_bt_device *device;
- int a2dp_delay_retries;
- DBusConnection *conn;
- enum cras_bt_device_profile profile;
- struct audio_gateway *prev, *next;
-};
-
-static struct audio_gateway *connected_ags;
-static struct packet_status_logger wbs_logger;
-
-static int need_go_sco_pcm(struct cras_bt_device *device)
-{
- return cras_iodev_list_get_sco_pcm_iodev(CRAS_STREAM_INPUT) ||
- cras_iodev_list_get_sco_pcm_iodev(CRAS_STREAM_OUTPUT);
-}
-
-static void destroy_audio_gateway(struct audio_gateway *ag)
-{
- DL_DELETE(connected_ags, ag);
-
- cras_server_metrics_hfp_battery_indicator(
- hfp_slc_get_hf_supports_battery_indicator(ag->slc_handle));
-
- if (need_go_sco_pcm(ag->device)) {
- if (ag->idev)
- hfp_alsa_iodev_destroy(ag->idev);
- if (ag->odev)
- hfp_alsa_iodev_destroy(ag->odev);
- } else {
- if (ag->idev)
- hfp_iodev_destroy(ag->idev);
- if (ag->odev)
- hfp_iodev_destroy(ag->odev);
- }
-
- if (ag->info) {
- if (hfp_info_running(ag->info))
- hfp_info_stop(ag->info);
- hfp_info_destroy(ag->info);
- }
- if (ag->slc_handle)
- hfp_slc_destroy(ag->slc_handle);
-
- free(ag);
-}
-
-/* Checks if there already a audio gateway connected for device. */
-static int has_audio_gateway(struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
- DL_FOREACH (connected_ags, ag) {
- if (ag->device == device)
- return 1;
- }
- return 0;
-}
-
-static void cras_hfp_ag_release(struct cras_bt_profile *profile)
-{
- struct audio_gateway *ag;
-
- DL_FOREACH (connected_ags, ag)
- destroy_audio_gateway(ag);
-}
-
-/* Callback triggered when SLC is initialized. */
-static int cras_hfp_ag_slc_initialized(struct hfp_slc_handle *handle)
-{
- struct audio_gateway *ag;
-
- DL_SEARCH_SCALAR(connected_ags, ag, slc_handle, handle);
- if (!ag)
- return -EINVAL;
-
- /* Log if the hands-free device supports WBS or not. Assuming the
- * codec negotiation feature means the WBS capability on headset.
- */
- cras_server_metrics_hfp_wideband_support(
- hfp_slc_get_hf_codec_negotiation_supported(handle));
-
- /* Log the final selected codec given that codec negotiation is
- * supported.
- */
- if (hfp_slc_get_hf_codec_negotiation_supported(handle) &&
- hfp_slc_get_ag_codec_negotiation_supported(handle))
- cras_server_metrics_hfp_wideband_selected_codec(
- hfp_slc_get_selected_codec(handle));
-
- /* Defer the starting of audio gateway to bt_device. */
- return cras_bt_device_audio_gateway_initialized(ag->device);
-}
-
-static int cras_hfp_ag_slc_disconnected(struct hfp_slc_handle *handle)
-{
- struct audio_gateway *ag;
-
- DL_SEARCH_SCALAR(connected_ags, ag, slc_handle, handle);
- if (!ag)
- return -EINVAL;
-
- destroy_audio_gateway(ag);
- cras_bt_device_notify_profile_dropped(
- ag->device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
- return 0;
-}
-
-static int check_for_conflict_ag(struct cras_bt_device *new_connected)
-{
- struct audio_gateway *ag;
-
- /* Check if there's already an A2DP/HFP device. */
- DL_FOREACH (connected_ags, ag) {
- if (cras_bt_device_has_a2dp(ag->device))
- return -1;
- }
-
- /* Check if there's already an A2DP-only device. */
- if (cras_a2dp_connected_device() &&
- cras_bt_device_supports_profile(new_connected,
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK))
- return -1;
-
- return 0;
-}
-
-int cras_hfp_ag_remove_conflict(struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
-
- DL_FOREACH (connected_ags, ag) {
- if (ag->device == device)
- continue;
- cras_bt_device_notify_profile_dropped(
- ag->device, CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
- destroy_audio_gateway(ag);
- }
- return 0;
-}
-
-static int cras_hfp_ag_new_connection(DBusConnection *conn,
- struct cras_bt_profile *profile,
- struct cras_bt_device *device,
- int rfcomm_fd)
-{
- struct cras_bt_adapter *adapter;
- struct audio_gateway *ag;
- int ag_features;
-
- BTLOG(btlog, BT_HFP_NEW_CONNECTION, 0, 0);
-
- if (has_audio_gateway(device)) {
- syslog(LOG_ERR,
- "Audio gateway exists when %s connects for profile %s",
- cras_bt_device_name(device), profile->name);
- close(rfcomm_fd);
- return 0;
- }
-
- if (check_for_conflict_ag(device))
- return -1;
-
- ag = (struct audio_gateway *)calloc(1, sizeof(*ag));
- ag->device = device;
- ag->conn = conn;
- ag->profile = cras_bt_device_profile_from_uuid(profile->uuid);
-
- adapter = cras_bt_device_adapter(device);
- /*
- * If the WBS enabled flag is set and adapter reports wbs capability
- * then add codec negotiation feature.
- * TODO(hychao): AND the two conditions to let bluetooth daemon
- * control whether to turn on WBS feature.
- */
- ag_features = BSRF_SUPPORTED_FEATURES;
- if (cras_system_get_bt_wbs_enabled() && adapter &&
- cras_bt_adapter_wbs_supported(adapter))
- ag_features |= AG_CODEC_NEGOTIATION;
-
- ag->slc_handle = hfp_slc_create(rfcomm_fd, 0, ag_features, device,
- cras_hfp_ag_slc_initialized,
- cras_hfp_ag_slc_disconnected);
- DL_APPEND(connected_ags, ag);
- return 0;
-}
-
-static void cras_hfp_ag_request_disconnection(struct cras_bt_profile *profile,
- struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
-
- BTLOG(btlog, BT_HFP_REQUEST_DISCONNECT, 0, 0);
-
- DL_FOREACH (connected_ags, ag) {
- if (ag->slc_handle && ag->device == device) {
- cras_bt_device_notify_profile_dropped(
- ag->device,
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
- destroy_audio_gateway(ag);
- }
- }
-}
-
-static void cras_hfp_ag_cancel(struct cras_bt_profile *profile)
-{
-}
-
-static struct cras_bt_profile cras_hfp_ag_profile = {
- .name = HFP_AG_PROFILE_NAME,
- .object_path = HFP_AG_PROFILE_PATH,
- .uuid = HFP_AG_UUID,
- .version = HFP_VERSION,
- .role = NULL,
- .features = SDP_SUPPORTED_FEATURES,
- .record = NULL,
- .release = cras_hfp_ag_release,
- .new_connection = cras_hfp_ag_new_connection,
- .request_disconnection = cras_hfp_ag_request_disconnection,
- .cancel = cras_hfp_ag_cancel
-};
-
-int cras_hfp_ag_profile_create(DBusConnection *conn)
-{
- return cras_bt_add_profile(conn, &cras_hfp_ag_profile);
-}
-
-static int cras_hsp_ag_new_connection(DBusConnection *conn,
- struct cras_bt_profile *profile,
- struct cras_bt_device *device,
- int rfcomm_fd)
-{
- struct audio_gateway *ag;
-
- BTLOG(btlog, BT_HSP_NEW_CONNECTION, 0, 0);
-
- if (has_audio_gateway(device)) {
- syslog(LOG_ERR,
- "Audio gateway exists when %s connects for profile %s",
- cras_bt_device_name(device), profile->name);
- close(rfcomm_fd);
- return 0;
- }
-
- if (check_for_conflict_ag(device))
- return -1;
-
- ag = (struct audio_gateway *)calloc(1, sizeof(*ag));
- ag->device = device;
- ag->conn = conn;
- ag->profile = cras_bt_device_profile_from_uuid(profile->uuid);
- ag->slc_handle =
- hfp_slc_create(rfcomm_fd, 1, BSRF_SUPPORTED_FEATURES, device,
- NULL, cras_hfp_ag_slc_disconnected);
- DL_APPEND(connected_ags, ag);
- cras_hfp_ag_slc_initialized(ag->slc_handle);
- return 0;
-}
-
-static void cras_hsp_ag_request_disconnection(struct cras_bt_profile *profile,
- struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
-
- BTLOG(btlog, BT_HSP_REQUEST_DISCONNECT, 0, 0);
-
- DL_FOREACH (connected_ags, ag) {
- if (ag->slc_handle && ag->device == device) {
- cras_bt_device_notify_profile_dropped(
- ag->device, CRAS_BT_DEVICE_PROFILE_HSP_HEADSET);
- destroy_audio_gateway(ag);
- }
- }
-}
-
-static struct cras_bt_profile cras_hsp_ag_profile = {
- .name = HSP_AG_PROFILE_NAME,
- .object_path = HSP_AG_PROFILE_PATH,
- .uuid = HSP_AG_UUID,
- .version = HSP_VERSION_1_2,
- .role = NULL,
- .record = HSP_AG_RECORD,
- .release = cras_hfp_ag_release,
- .new_connection = cras_hsp_ag_new_connection,
- .request_disconnection = cras_hsp_ag_request_disconnection,
- .cancel = cras_hfp_ag_cancel
-};
-
-int cras_hfp_ag_start(struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
-
- BTLOG(btlog, BT_AUDIO_GATEWAY_START, 0, 0);
-
- DL_SEARCH_SCALAR(connected_ags, ag, device, device);
- if (ag == NULL)
- return -EEXIST;
-
- /*
- * There is chance that bluetooth stack notifies us about remote
- * device's capability incrementally in multiple events. That could
- * cause hfp_ag_start be called more than once. Check if the input
- * HFP iodev is already created so we don't re-create HFP resources.
- */
- if (ag->idev)
- return 0;
-
- if (need_go_sco_pcm(device)) {
- struct cras_iodev *in_aio, *out_aio;
-
- in_aio = cras_iodev_list_get_sco_pcm_iodev(CRAS_STREAM_INPUT);
- out_aio = cras_iodev_list_get_sco_pcm_iodev(CRAS_STREAM_OUTPUT);
-
- ag->idev = hfp_alsa_iodev_create(in_aio, ag->device,
- ag->slc_handle, ag->profile);
- ag->odev = hfp_alsa_iodev_create(out_aio, ag->device,
- ag->slc_handle, ag->profile);
- } else {
- ag->info = hfp_info_create();
- hfp_info_set_wbs_logger(ag->info, &wbs_logger);
- ag->idev =
- hfp_iodev_create(CRAS_STREAM_INPUT, ag->device,
- ag->slc_handle, ag->profile, ag->info);
- ag->odev =
- hfp_iodev_create(CRAS_STREAM_OUTPUT, ag->device,
- ag->slc_handle, ag->profile, ag->info);
- }
-
- if (!ag->idev && !ag->odev) {
- destroy_audio_gateway(ag);
- return -ENOMEM;
- }
-
- return 0;
-}
-
-void cras_hfp_ag_suspend_connected_device(struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
-
- DL_SEARCH_SCALAR(connected_ags, ag, device, device);
- if (ag)
- destroy_audio_gateway(ag);
-}
-
-struct hfp_slc_handle *cras_hfp_ag_get_active_handle()
-{
- /* Returns the first handle for HFP qualification. In future we
- * might want this to return the HFP device user is selected. */
- return connected_ags ? connected_ags->slc_handle : NULL;
-}
-
-struct hfp_slc_handle *cras_hfp_ag_get_slc(struct cras_bt_device *device)
-{
- struct audio_gateway *ag;
- DL_FOREACH (connected_ags, ag) {
- if (ag->device == device)
- return ag->slc_handle;
- }
- return NULL;
-}
-
-struct packet_status_logger *cras_hfp_ag_get_wbs_logger()
-{
- return &wbs_logger;
-}
-
-int cras_hsp_ag_profile_create(DBusConnection *conn)
-{
- return cras_bt_add_profile(conn, &cras_hsp_ag_profile);
-}
diff --git a/cras/src/server/cras_hfp_ag_profile.h b/cras/src/server/cras_hfp_ag_profile.h
deleted file mode 100644
index 3de56184..00000000
--- a/cras/src/server/cras_hfp_ag_profile.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_HFP_AG_PROFILE_H_
-#define CRAS_HFP_AG_PROFILE_H_
-
-#include <dbus/dbus.h>
-#include <stdbool.h>
-
-#include "cras_bt_device.h"
-#include "cras_hfp_slc.h"
-
-/*
- * For service record profile, 'SupportedFearues' attribute bit mapping
- * for HFP AG. Bits 0 to 4 are identical to the unsolicited result code
- * of +BRSF command.
- */
-#define FEATURES_AG_THREE_WAY_CALLING 0x0001
-#define FEATURES_AG_EC_ANDOR_NR 0x0002
-#define FEATURES_AG_VOICE_RECOGNITION 0x0004
-#define FEATURES_AG_INBAND_RINGTONE 0x0008
-#define FEATURES_AG_ATTACH_NUMBER_TO_VOICETAG 0x0010
-#define FEATURES_AG_WIDE_BAND_SPEECH 0x0020
-
-struct hfp_slc_handle;
-
-/* Adds a profile instance for HFP AG (Hands-Free Profile Audio Gateway). */
-int cras_hfp_ag_profile_create(DBusConnection *conn);
-
-/* Adds a profile instance for HSP AG (Headset Profile Audio Gateway). */
-int cras_hsp_ag_profile_create(DBusConnection *conn);
-
-/* Starts the HFP audio gateway for audio input/output. */
-int cras_hfp_ag_start(struct cras_bt_device *device);
-
-/*
- * Suspends all connected audio gateways except the one associated to device.
- * Used to stop previously running HFP/HSP audio when a new device is connected.
- * Args:
- * device - The device that we want to keep connection while others should
- * be removed.
- */
-int cras_hfp_ag_remove_conflict(struct cras_bt_device *device);
-
-/* Suspends audio gateway associated with given bt device. */
-void cras_hfp_ag_suspend_connected_device(struct cras_bt_device *device);
-
-/* Gets the active SLC handle. Used for HFP qualification. */
-struct hfp_slc_handle *cras_hfp_ag_get_active_handle();
-
-/* Gets the SLC handle for given cras_bt_device. */
-struct hfp_slc_handle *cras_hfp_ag_get_slc(struct cras_bt_device *device);
-
-/* Gets the logger for WBS packet status. */
-struct packet_status_logger *cras_hfp_ag_get_wbs_logger();
-
-#endif /* CRAS_HFP_AG_PROFILE_H_ */
diff --git a/cras/src/server/cras_hfp_alsa_iodev.c b/cras/src/server/cras_hfp_alsa_iodev.c
deleted file mode 100644
index c1b60b30..00000000
--- a/cras/src/server/cras_hfp_alsa_iodev.c
+++ /dev/null
@@ -1,336 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <syslog.h>
-
-#include "cras_audio_area.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev.h"
-#include "cras_system_state.h"
-#include "cras_util.h"
-#include "utlist.h"
-#include "cras_bt_device.h"
-
-#include "cras_hfp_alsa_iodev.h"
-
-/* Object to represent a special HFP iodev which would be managed by bt_io but
- * playback/capture via an inner ALSA iodev.
- * Members:
- * base - The base class cras_iodev.
- * device - The corresponding remote BT device.
- * slc - The service level connection.
- * aio - The effective iodev for playback/capture.
- */
-struct hfp_alsa_io {
- struct cras_iodev base;
- struct cras_bt_device *device;
- struct hfp_slc_handle *slc;
- struct cras_iodev *aio;
-};
-
-static int hfp_alsa_get_valid_frames(struct cras_iodev *iodev,
- struct timespec *hw_tstamp)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->get_valid_frames(aio, hw_tstamp);
-}
-
-static int hfp_alsa_open_dev(struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->open_dev(aio);
-}
-
-static int hfp_alsa_update_supported_formats(struct cras_iodev *iodev)
-{
- /* 16 bit, mono, 8kHz (narrow band speech); */
- free(iodev->supported_rates);
- iodev->supported_rates = malloc(2 * sizeof(*iodev->supported_rates));
- if (!iodev->supported_rates)
- return -ENOMEM;
- iodev->supported_rates[0] = 8000;
- iodev->supported_rates[1] = 0;
-
- free(iodev->supported_channel_counts);
- iodev->supported_channel_counts =
- malloc(2 * sizeof(*iodev->supported_channel_counts));
- if (!iodev->supported_channel_counts)
- return -ENOMEM;
- iodev->supported_channel_counts[0] = 1;
- iodev->supported_channel_counts[1] = 0;
-
- free(iodev->supported_formats);
- iodev->supported_formats =
- malloc(2 * sizeof(*iodev->supported_formats));
- if (!iodev->supported_formats)
- return -ENOMEM;
- iodev->supported_formats[0] = SND_PCM_FORMAT_S16_LE;
- iodev->supported_formats[1] = 0;
-
- return 0;
-}
-
-static int hfp_alsa_configure_dev(struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
- int rc;
-
- /* Fill back the format iodev is using. */
- if (aio->format == NULL) {
- aio->format = (struct cras_audio_format *)malloc(
- sizeof(*aio->format));
- if (!aio->format)
- return -ENOMEM;
- *aio->format = *iodev->format;
- }
-
- rc = aio->configure_dev(aio);
- if (rc) {
- syslog(LOG_ERR, "Failed to configure aio: %d\n", rc);
- return rc;
- }
-
- rc = cras_bt_device_get_sco(
- hfp_alsa_io->device,
- hfp_slc_get_selected_codec(hfp_alsa_io->slc));
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to get sco: %d\n", rc);
- return rc;
- }
-
- hfp_set_call_status(hfp_alsa_io->slc, 1);
- iodev->buffer_size = aio->buffer_size;
-
- return 0;
-}
-
-static int hfp_alsa_close_dev(struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- hfp_set_call_status(hfp_alsa_io->slc, 0);
- cras_bt_device_put_sco(hfp_alsa_io->device);
- cras_iodev_free_format(iodev);
- return aio->close_dev(aio);
-}
-
-static int hfp_alsa_frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->frames_queued(aio, tstamp);
-}
-
-static int hfp_alsa_delay_frames(const struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->delay_frames(aio);
-}
-
-static int hfp_alsa_get_buffer(struct cras_iodev *iodev,
- struct cras_audio_area **area, unsigned *frames)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->get_buffer(aio, area, frames);
-}
-
-static int hfp_alsa_put_buffer(struct cras_iodev *iodev, unsigned nwritten)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->put_buffer(aio, nwritten);
-}
-
-static int hfp_alsa_flush_buffer(struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->flush_buffer(aio);
-}
-
-static void hfp_alsa_update_active_node(struct cras_iodev *iodev,
- unsigned node_idx, unsigned dev_enabled)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- aio->update_active_node(aio, node_idx, dev_enabled);
-}
-
-static int hfp_alsa_start(const struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->start(aio);
-}
-
-static void hfp_alsa_set_volume(struct cras_iodev *iodev)
-{
- size_t volume;
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
-
- volume = cras_system_get_volume();
- if (iodev->active_node)
- volume = cras_iodev_adjust_node_volume(iodev->active_node,
- volume);
-
- hfp_event_speaker_gain(hfp_alsa_io->slc, volume);
-}
-
-static int hfp_alsa_no_stream(struct cras_iodev *iodev, int enable)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- /*
- * Copy iodev->min_cb_level and iodev->max_cb_level from the parent
- * (i.e. hfp_alsa_iodev). no_stream() of alsa_io will use them.
- */
- aio->min_cb_level = iodev->min_cb_level;
- aio->max_cb_level = iodev->max_cb_level;
- return aio->no_stream(aio, enable);
-}
-
-static int hfp_alsa_is_free_running(const struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- return aio->is_free_running(aio);
-}
-
-static int hfp_alsa_output_underrun(struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_iodev *aio = hfp_alsa_io->aio;
-
- /*
- * Copy iodev->min_cb_level and iodev->max_cb_level from the parent
- * (i.e. hfp_alsa_iodev). output_underrun() of alsa_io will use them.
- */
- aio->min_cb_level = iodev->min_cb_level;
- aio->max_cb_level = iodev->max_cb_level;
-
- return aio->output_underrun(aio);
-}
-
-struct cras_iodev *hfp_alsa_iodev_create(struct cras_iodev *aio,
- struct cras_bt_device *device,
- struct hfp_slc_handle *slc,
- enum cras_bt_device_profile profile)
-{
- struct hfp_alsa_io *hfp_alsa_io;
- struct cras_iodev *iodev;
- struct cras_ionode *node;
- const char *name;
-
- hfp_alsa_io = calloc(1, sizeof(*hfp_alsa_io));
- if (!hfp_alsa_io)
- return NULL;
-
- iodev = &hfp_alsa_io->base;
- iodev->direction = aio->direction;
-
- hfp_alsa_io->device = device;
- hfp_alsa_io->slc = slc;
- hfp_alsa_io->aio = aio;
-
- /* Set iodev's name to device readable name or the address. */
- name = cras_bt_device_name(device);
- if (!name)
- name = cras_bt_device_object_path(device);
- snprintf(iodev->info.name, sizeof(iodev->info.name), "%s", name);
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = 0;
- iodev->info.stable_id = cras_bt_device_get_stable_id(device);
-
- iodev->open_dev = hfp_alsa_open_dev;
- iodev->update_supported_formats = hfp_alsa_update_supported_formats;
- iodev->configure_dev = hfp_alsa_configure_dev;
- iodev->close_dev = hfp_alsa_close_dev;
-
- iodev->frames_queued = hfp_alsa_frames_queued;
- iodev->delay_frames = hfp_alsa_delay_frames;
- iodev->get_buffer = hfp_alsa_get_buffer;
- iodev->put_buffer = hfp_alsa_put_buffer;
- iodev->flush_buffer = hfp_alsa_flush_buffer;
-
- iodev->update_active_node = hfp_alsa_update_active_node;
- iodev->start = hfp_alsa_start;
- iodev->set_volume = hfp_alsa_set_volume;
- iodev->get_valid_frames = hfp_alsa_get_valid_frames;
- iodev->no_stream = hfp_alsa_no_stream;
- iodev->is_free_running = hfp_alsa_is_free_running;
- iodev->output_underrun = hfp_alsa_output_underrun;
-
- iodev->min_buffer_level = aio->min_buffer_level;
-
- node = calloc(1, sizeof(*node));
- node->dev = iodev;
- strcpy(node->name, iodev->info.name);
-
- node->plugged = 1;
- /* If headset mic uses legacy narrow band, i.e CVSD codec, report a
- * different node type so UI can set different plug priority. */
- node->type = CRAS_NODE_TYPE_BLUETOOTH;
- if ((hfp_slc_get_selected_codec(hfp_alsa_io->slc) ==
- HFP_CODEC_ID_CVSD) &&
- (iodev->direction == CRAS_STREAM_INPUT))
- node->type = CRAS_NODE_TYPE_BLUETOOTH_NB_MIC;
- node->volume = 100;
- gettimeofday(&node->plugged_time, NULL);
-
- /* Prepare active node before append, so bt_io can extract correct
- * info from hfp_alsa iodev and node. */
- cras_iodev_add_node(iodev, node);
- cras_iodev_set_active_node(iodev, node);
- cras_bt_device_append_iodev(device, iodev, profile);
-
- /* Record max supported channels into cras_iodev_info. */
- iodev->info.max_supported_channels = 1;
-
- /* Specifically disable EWMA calculation on this and the child iodev. */
- ewma_power_disable(&iodev->ewma);
- ewma_power_disable(&aio->ewma);
-
- return iodev;
-}
-
-void hfp_alsa_iodev_destroy(struct cras_iodev *iodev)
-{
- struct hfp_alsa_io *hfp_alsa_io = (struct hfp_alsa_io *)iodev;
- struct cras_ionode *node;
-
- cras_bt_device_rm_iodev(hfp_alsa_io->device, iodev);
-
- node = iodev->active_node;
- if (node) {
- cras_iodev_rm_node(iodev, node);
- free(node);
- }
-
- free(iodev->supported_channel_counts);
- free(iodev->supported_rates);
- free(iodev->supported_formats);
- cras_iodev_free_resources(iodev);
-
- free(hfp_alsa_io);
-}
diff --git a/cras/src/server/cras_hfp_alsa_iodev.h b/cras/src/server/cras_hfp_alsa_iodev.h
deleted file mode 100644
index e05af688..00000000
--- a/cras/src/server/cras_hfp_alsa_iodev.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_HFP_ALSA_IODEV_H_
-#define CRAS_HFP_ALSA_IODEV_H_
-
-#include "cras_bt_device.h"
-#include "cras_hfp_info.h"
-#include "cras_types.h"
-
-struct hfp_slc_handle;
-
-/*
- * Creates a hfp alsa iodev.
- *
- * hfp_alsa_iodev is a special HFP iodev which would be managed by bt_io but
- * playback/capture via an inner ALSA iodev.
- *
- * The usage of hfp_alsa_iodev is only for SCO connection over PCM/I2S.
- */
-struct cras_iodev *hfp_alsa_iodev_create(struct cras_iodev *aio,
- struct cras_bt_device *device,
- struct hfp_slc_handle *slc,
- enum cras_bt_device_profile profile);
-
-void hfp_alsa_iodev_destroy(struct cras_iodev *iodev);
-
-#endif /* CRAS_HFP_ALSA_IODEV_H_ */
diff --git a/cras/src/server/cras_hfp_info.c b/cras/src/server/cras_hfp_info.c
deleted file mode 100644
index fc407b29..00000000
--- a/cras/src/server/cras_hfp_info.c
+++ /dev/null
@@ -1,868 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <syslog.h>
-
-#include "audio_thread.h"
-#include "bluetooth.h"
-#include "byte_buffer.h"
-#include "cras_hfp_info.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev_list.h"
-#include "cras_plc.h"
-#include "cras_sbc_codec.h"
-#include "cras_server_metrics.h"
-#include "utlist.h"
-#include "packet_status_logger.h"
-
-/* The max buffer size. Note that the actual used size must set to multiple
- * of SCO packet size, and the packet size does not necessarily be equal to
- * MTU. We should keep this as common multiple of possible packet sizes, for
- * example: 48, 60, 64, 128.
- */
-#define MAX_HFP_BUF_SIZE_BYTES 28800
-
-/* rate(8kHz) * sample_size(2 bytes) * channels(1) */
-#define HFP_BYTE_RATE 16000
-
-/* Per Bluetooth Core v5.0 and HFP 1.7 specification. */
-#define MSBC_H2_HEADER_LEN 2
-#define MSBC_FRAME_LEN 57
-#define MSBC_FRAME_SIZE 59
-#define MSBC_CODE_SIZE 240
-#define MSBC_SYNC_WORD 0xAD
-
-/* For one mSBC 1 compressed wideband audio channel the HCI packets will
- * be 3 octets of HCI header + 60 octets of data. */
-#define MSBC_PKT_SIZE 60
-
-#define H2_HEADER_0 0x01
-
-/* Supported HCI SCO packet sizes. The wideband speech mSBC frame parsing
- * code ties to limited packet size values. Specifically list them out
- * to check against when setting packet size.
- *
- * Temp buffer size should be set to least common multiple of HCI SCO packet
- * size and MSBC_PKT_SIZE for optimizing buffer copy.
- * To add a new supported packet size value, add corresponding entry to the
- * lists, test the read/write msbc code, and fix the code if needed.
- */
-static const size_t wbs_supported_packet_size[] = { 60, 24, 0 };
-static const size_t wbs_hci_sco_buffer_size[] = { 60, 120, 0 };
-
-/* Second octet of H2 header is composed by 4 bits fixed 0x8 and 4 bits
- * sequence number 0000, 0011, 1100, 1111. */
-static const uint8_t h2_header_frames_count[] = { 0x08, 0x38, 0xc8, 0xf8 };
-
-/* Structure to hold variables for a HFP connection. Since HFP supports
- * bi-direction audio, two iodevs should share one hfp_info if they
- * represent two directions of the same HFP headset
- * Members:
- * fd - The file descriptor for SCO socket.
- * started - If the hfp_info has started to read/write SCO data.
- * mtu - The max transmit unit reported from BT adapter.
- * packet_size - The size of SCO packet to read/write preferred by
- * adapter, could be different than mtu.
- * capture_buf - The buffer to hold samples read from SCO socket.
- * playback_buf - The buffer to hold samples about to write to SCO socket.
- * msbc_read - mSBC codec to decode input audio in wideband speech mode.
- * msbc_write - mSBC codec to encode output audio in wideband speech mode.
- * msbc_plc - PLC component to handle the packet loss of input audio in
- * wideband speech mode.
- * msbc_num_out_frames - Number of total written mSBC frames.
- * msbc_num_in_frames - Number of total read mSBC frames.
- * msbc_num_lost_frames - Number of total lost mSBC frames.
- * read_cb - Callback to call when SCO socket can read. It returns the
- * number of PCM bytes read.
- * write_cb - Callback to call when SCO socket can write.
- * write_buf - Temp buffer for writeing HCI SCO packet in wideband.
- * read_buf - Temp buffer for reading HCI SCO packet in wideband.
- * input_format_bytes - The audio format bytes for input device. 0 means
- * there is no input device for the hfp_info.
- * output_format_bytes - The audio format bytes for output device. 0 means
- * there is no output device for the hfp_info.
- * write_wp - Write pointer of write_buf.
- * write_rp - Read pointer of write_buf.
- * read_wp - Write pointer of read_buf.
- * read_rp - Read pointer of read_buf.
- * read_align_cb - Callback used to align mSBC frame reading with read buf.
- * msbc_read_current_corrupted - Flag to mark if the current mSBC frame
- * read is corrupted.
- * wbs_logger - The logger for packet status in WBS.
- */
-struct hfp_info {
- int fd;
- int started;
- unsigned int mtu;
- unsigned int packet_size;
- struct byte_buffer *capture_buf;
- struct byte_buffer *playback_buf;
- struct cras_audio_codec *msbc_read;
- struct cras_audio_codec *msbc_write;
- struct cras_msbc_plc *msbc_plc;
- unsigned int msbc_num_out_frames;
- unsigned int msbc_num_in_frames;
- unsigned int msbc_num_lost_frames;
- int (*read_cb)(struct hfp_info *info);
- int (*write_cb)(struct hfp_info *info);
- uint8_t *write_buf;
- uint8_t *read_buf;
- size_t input_format_bytes;
- size_t output_format_bytes;
- size_t write_wp;
- size_t write_rp;
- size_t read_wp;
- size_t read_rp;
- int (*read_align_cb)(uint8_t *buf);
- bool msbc_read_current_corrupted;
- struct packet_status_logger *wbs_logger;
-};
-
-int hfp_info_add_iodev(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction,
- struct cras_audio_format *format)
-{
- if (direction == CRAS_STREAM_OUTPUT) {
- if (info->output_format_bytes)
- goto invalid;
- info->output_format_bytes = cras_get_format_bytes(format);
-
- buf_reset(info->playback_buf);
- } else if (direction == CRAS_STREAM_INPUT) {
- if (info->input_format_bytes)
- goto invalid;
- info->input_format_bytes = cras_get_format_bytes(format);
-
- buf_reset(info->capture_buf);
- }
-
- return 0;
-
-invalid:
- return -EINVAL;
-}
-
-int hfp_info_rm_iodev(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction)
-{
- if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes) {
- memset(info->playback_buf->bytes, 0,
- info->playback_buf->used_size);
- info->output_format_bytes = 0;
- } else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes) {
- info->input_format_bytes = 0;
- } else {
- return -EINVAL;
- }
-
- return 0;
-}
-
-int hfp_info_has_iodev(struct hfp_info *info)
-{
- return info->output_format_bytes || info->input_format_bytes;
-}
-
-void hfp_buf_acquire(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction, uint8_t **buf,
- unsigned *count)
-{
- size_t format_bytes;
- unsigned int buf_avail;
-
- if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes) {
- *buf = buf_write_pointer_size(info->playback_buf, &buf_avail);
- format_bytes = info->output_format_bytes;
- } else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes) {
- *buf = buf_read_pointer_size(info->capture_buf, &buf_avail);
- format_bytes = info->input_format_bytes;
- } else {
- *count = 0;
- return;
- }
-
- if (*count * format_bytes > buf_avail)
- *count = buf_avail / format_bytes;
-}
-
-int hfp_buf_size(struct hfp_info *info, enum CRAS_STREAM_DIRECTION direction)
-{
- if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes)
- return info->playback_buf->used_size /
- info->output_format_bytes;
- else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes)
- return info->capture_buf->used_size / info->input_format_bytes;
- return 0;
-}
-
-void hfp_buf_release(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction,
- unsigned written_frames)
-{
- if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes)
- buf_increment_write(info->playback_buf,
- written_frames * info->output_format_bytes);
- else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes)
- buf_increment_read(info->capture_buf,
- written_frames * info->input_format_bytes);
- else
- written_frames = 0;
-}
-
-int hfp_buf_queued(struct hfp_info *info, enum CRAS_STREAM_DIRECTION direction)
-{
- if (direction == CRAS_STREAM_OUTPUT && info->output_format_bytes)
- return buf_queued(info->playback_buf) /
- info->output_format_bytes;
- else if (direction == CRAS_STREAM_INPUT && info->input_format_bytes)
- return buf_queued(info->capture_buf) / info->input_format_bytes;
- else
- return 0;
-}
-
-int hfp_fill_output_with_zeros(struct hfp_info *info, unsigned int nframes)
-{
- unsigned int buf_avail;
- unsigned int nbytes;
- uint8_t *buf;
- int i;
- int ret = 0;
-
- if (info->output_format_bytes) {
- nbytes = nframes * info->output_format_bytes;
- /* Loop twice to make sure ring buffer is filled. */
- for (i = 0; i < 2; i++) {
- buf = buf_write_pointer_size(info->playback_buf,
- &buf_avail);
- if (buf_avail == 0)
- break;
- buf_avail = MIN(nbytes, buf_avail);
- memset(buf, 0, buf_avail);
- buf_increment_write(info->playback_buf, buf_avail);
- nbytes -= buf_avail;
- ret += buf_avail / info->output_format_bytes;
- }
- }
- return ret;
-}
-
-void hfp_force_output_level(struct hfp_info *info, unsigned int level)
-{
- if (info->output_format_bytes) {
- level *= info->output_format_bytes;
- level = MIN(level, MAX_HFP_BUF_SIZE_BYTES);
- buf_adjust_readable(info->playback_buf, level);
- }
-}
-
-int hfp_write_msbc(struct hfp_info *info)
-{
- size_t encoded;
- int err;
- int pcm_encoded;
- unsigned int pcm_avail, to_write;
- uint8_t *samples;
- uint8_t *wp;
-
- if (info->write_rp + info->packet_size <= info->write_wp)
- goto msbc_send_again;
-
- /* Make sure there are MSBC_CODE_SIZE bytes to encode. */
- samples = buf_read_pointer_size(info->playback_buf, &pcm_avail);
- if (pcm_avail < MSBC_CODE_SIZE) {
- to_write = MSBC_CODE_SIZE - pcm_avail;
- /*
- * Size of playback_buf is multiple of MSBC_CODE_SIZE so we
- * are safe to prepare the buffer by appending some zero bytes.
- */
- wp = buf_write_pointer_size(info->playback_buf, &pcm_avail);
- memset(wp, 0, to_write);
- buf_increment_write(info->playback_buf, to_write);
-
- samples = buf_read_pointer_size(info->playback_buf, &pcm_avail);
- if (pcm_avail < MSBC_CODE_SIZE)
- return -EINVAL;
- }
-
- /* Encode the next MSBC_CODE_SIZE of bytes. */
- wp = info->write_buf + info->write_wp;
- wp[0] = H2_HEADER_0;
- wp[1] = h2_header_frames_count[info->msbc_num_out_frames % 4];
- pcm_encoded = info->msbc_write->encode(
- info->msbc_write, samples, pcm_avail, wp + MSBC_H2_HEADER_LEN,
- MSBC_PKT_SIZE - MSBC_H2_HEADER_LEN, &encoded);
- if (pcm_encoded < 0) {
- syslog(LOG_ERR, "msbc encoding err: %s", strerror(pcm_encoded));
- return pcm_encoded;
- }
- buf_increment_read(info->playback_buf, pcm_encoded);
- pcm_avail -= pcm_encoded;
- info->write_wp += MSBC_PKT_SIZE;
- info->msbc_num_out_frames++;
-
- if (info->write_rp + info->packet_size > info->write_wp)
- return 0;
-
-msbc_send_again:
- err = send(info->fd, info->write_buf + info->write_rp,
- info->packet_size, 0);
- if (err < 0) {
- if (errno == EINTR)
- goto msbc_send_again;
- return err;
- }
- if (err != (int)info->packet_size) {
- syslog(LOG_ERR, "Partially write %d bytes for mSBC", err);
- return -1;
- }
- info->write_rp += info->packet_size;
- if (info->write_rp == info->write_wp) {
- info->write_rp = 0;
- info->write_wp = 0;
- }
-
- return err;
-}
-
-int hfp_write(struct hfp_info *info)
-{
- int err = 0;
- unsigned to_send;
- uint8_t *samples;
-
- /* Write something */
- samples = buf_read_pointer_size(info->playback_buf, &to_send);
- if (to_send < info->packet_size)
- return 0;
- to_send = info->packet_size;
-
-send_sample:
- err = send(info->fd, samples, to_send, 0);
- if (err < 0) {
- if (errno == EINTR)
- goto send_sample;
-
- return err;
- }
-
- if (err != (int)info->packet_size) {
- syslog(LOG_ERR,
- "Partially write %d bytes for SCO packet size %u", err,
- info->packet_size);
- return -1;
- }
-
- buf_increment_read(info->playback_buf, to_send);
-
- return err;
-}
-
-static int h2_header_get_seq(const uint8_t *p)
-{
- int i;
- for (i = 0; i < 4; i++) {
- if (*p == h2_header_frames_count[i])
- return i;
- }
- return -1;
-}
-
-/*
- * Extract mSBC frame from SCO socket input bytes, given that the mSBC frame
- * could be lost or corrupted.
- * Args:
- * input - Pointer to input bytes read from SCO socket.
- * len - Length of input bytes.
- * seq_out - To be filled by the sequence number of mSBC packet.
- * Returns:
- * The starting position of mSBC frame if found.
- */
-static const uint8_t *extract_msbc_frame(const uint8_t *input, int len,
- unsigned int *seq_out)
-{
- int rp = 0;
- int seq = -1;
- while (len - rp >= MSBC_FRAME_SIZE) {
- if ((input[rp] != H2_HEADER_0) ||
- (input[rp + 2] != MSBC_SYNC_WORD)) {
- rp++;
- continue;
- }
- seq = h2_header_get_seq(input + rp + 1);
- if (seq < 0) {
- rp++;
- continue;
- }
- // `seq` is guaranteed to be positive now.
- *seq_out = (unsigned int)seq;
- return input + rp;
- }
- return NULL;
-}
-
-/* Log value 0 when packet is received. */
-static void log_wbs_packet_received(struct hfp_info *info)
-{
- if (info->wbs_logger)
- packet_status_logger_update(info->wbs_logger, 0);
-}
-
-/* Log value 1 when packet is lost. */
-static void log_wbs_packet_lost(struct hfp_info *info)
-{
- if (info->wbs_logger)
- packet_status_logger_update(info->wbs_logger, 1);
-}
-
-/*
- * Handle the case when mSBC frame is considered lost.
- * Args:
- * info - The hfp_info instance holding mSBC codec and PLC objects.
- */
-static int handle_packet_loss(struct hfp_info *info)
-{
- int decoded;
- unsigned int pcm_avail;
- uint8_t *in_bytes;
-
- /* It's possible client doesn't consume data causing overrun. In that
- * case we treat it as one mSBC frame read but dropped. */
- info->msbc_num_in_frames++;
- info->msbc_num_lost_frames++;
-
- log_wbs_packet_lost(info);
-
- in_bytes = buf_write_pointer_size(info->capture_buf, &pcm_avail);
- if (pcm_avail < MSBC_CODE_SIZE)
- return 0;
-
- decoded = cras_msbc_plc_handle_bad_frames(info->msbc_plc,
- info->msbc_read, in_bytes);
- if (decoded < 0)
- return decoded;
-
- buf_increment_write(info->capture_buf, decoded);
-
- return decoded;
-}
-
-/* Checks if mSBC frame header aligns with the beginning of buffer. */
-static int msbc_frame_align(uint8_t *buf)
-{
- if ((buf[0] != H2_HEADER_0) || (buf[2] != MSBC_SYNC_WORD)) {
- syslog(LOG_DEBUG, "Waiting for valid mSBC frame head");
- return 0;
- }
- return 1;
-}
-
-int hfp_read_msbc(struct hfp_info *info)
-{
- int err = 0;
- unsigned int pcm_avail = 0;
- int decoded;
- size_t pcm_decoded = 0;
- size_t pcm_read = 0;
- uint8_t *capture_buf;
- const uint8_t *frame_head = NULL;
- unsigned int seq;
-
- struct msghdr msg = { 0 };
- struct iovec iov;
- struct cmsghdr *cmsg;
- const unsigned int control_size = CMSG_SPACE(sizeof(int));
- char control[control_size];
- uint8_t pkt_status;
-
- memset(control, 0, sizeof(control));
-recv_msbc_bytes:
- msg.msg_iov = &iov;
- msg.msg_iovlen = 1;
- iov.iov_base = info->read_buf + info->read_wp;
- iov.iov_len = info->packet_size;
- msg.msg_control = control;
- msg.msg_controllen = control_size;
-
- err = recvmsg(info->fd, &msg, 0);
- if (err < 0) {
- syslog(LOG_ERR, "HCI SCO packet read err %s", strerror(errno));
- if (errno == EINTR)
- goto recv_msbc_bytes;
- return err;
- }
- /*
- * Treat return code 0 (socket shutdown) as error here. BT stack
- * shall send signal to main thread for device disconnection.
- */
- if (err != (int)info->packet_size) {
- syslog(LOG_ERR, "Partially read %d bytes for mSBC packet", err);
- return -1;
- }
-
- /* Offset in input data breaks mSBC frame parsing. Discard this packet
- * until read alignment succeed. */
- if (info->read_align_cb) {
- if (!info->read_align_cb(info->read_buf))
- return 0;
- else
- info->read_align_cb = NULL;
- }
- info->read_wp += err;
-
- pkt_status = 0;
- for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
- cmsg = CMSG_NXTHDR(&msg, cmsg)) {
- if (cmsg->cmsg_level == SOL_BLUETOOTH &&
- cmsg->cmsg_type == BT_SCM_PKT_STATUS) {
- size_t len = cmsg->cmsg_len - sizeof(*cmsg);
- memcpy(&pkt_status, CMSG_DATA(cmsg), len);
- }
- }
-
- /*
- * HCI SCO packet status flag:
- * 0x00 - correctly received data.
- * 0x01 - possibly invalid data.
- * 0x10 - No data received.
- * 0x11 - Data partially lost.
- *
- * If the latest SCO packet read doesn't cross the boundary of a mSBC
- * frame, the packet status flag can be used to derive if the current
- * mSBC frame is corrupted.
- */
- if (info->read_rp + MSBC_PKT_SIZE >= info->read_wp)
- info->msbc_read_current_corrupted |= (pkt_status > 0);
-
- /* Read buffer not enough to parse another mSBC frame. */
- if (info->read_rp + MSBC_PKT_SIZE > info->read_wp)
- return 0;
-
- if (info->msbc_read_current_corrupted) {
- syslog(LOG_DEBUG, "mSBC frame corrputed from packet status");
- info->msbc_read_current_corrupted = 0;
- frame_head = NULL;
- } else {
- frame_head =
- extract_msbc_frame(info->read_buf + info->read_rp,
- info->read_wp - info->read_rp, &seq);
- if (!frame_head)
- syslog(LOG_DEBUG, "Failed to extract msbc frame");
- }
-
- /*
- * Done with parsing the raw bytes just read. If mSBC frame head not
- * found, we shall handle it as packet loss.
- */
- info->read_rp += MSBC_PKT_SIZE;
- if (info->read_rp == info->read_wp) {
- info->read_rp = 0;
- info->read_wp = 0;
- }
- if (!frame_head)
- return handle_packet_loss(info);
-
- /*
- * Consider packet loss when found discontinuity in sequence number.
- */
- while (seq != (info->msbc_num_in_frames % 4)) {
- syslog(LOG_DEBUG, "SCO packet seq unmatch");
- err = handle_packet_loss(info);
- if (err < 0)
- return err;
- pcm_read += err;
- }
-
- /* Check if there's room for more PCM. */
- capture_buf = buf_write_pointer_size(info->capture_buf, &pcm_avail);
- if (pcm_avail < MSBC_CODE_SIZE)
- return pcm_read;
-
- decoded = info->msbc_read->decode(info->msbc_read,
- frame_head + MSBC_H2_HEADER_LEN,
- MSBC_FRAME_LEN, capture_buf,
- pcm_avail, &pcm_decoded);
- if (decoded < 0) {
- /*
- * If mSBC frame cannot be decoded, consider this packet is
- * corrupted and lost.
- */
- syslog(LOG_ERR, "mSBC decode failed");
- err = handle_packet_loss(info);
- if (err < 0)
- return err;
- pcm_read += err;
- } else {
- /* Good mSBC frame decoded. */
- log_wbs_packet_received(info);
- buf_increment_write(info->capture_buf, pcm_decoded);
- info->msbc_num_in_frames++;
- cras_msbc_plc_handle_good_frames(info->msbc_plc, capture_buf,
- capture_buf);
- pcm_read += pcm_decoded;
- }
- return pcm_read;
-}
-
-int hfp_read(struct hfp_info *info)
-{
- int err = 0;
- unsigned to_read;
- uint8_t *capture_buf;
-
- capture_buf = buf_write_pointer_size(info->capture_buf, &to_read);
-
- if (to_read < info->packet_size)
- return 0;
- to_read = info->packet_size;
-
-recv_sample:
- err = recv(info->fd, capture_buf, to_read, 0);
- if (err < 0) {
- syslog(LOG_ERR, "Read error %s", strerror(errno));
- if (errno == EINTR)
- goto recv_sample;
-
- return err;
- }
-
- if (err != (int)info->packet_size) {
- /* Allow the SCO packet size be modified from the default MTU
- * value to the size of SCO data we first read. This is for
- * some adapters who prefers a different value than MTU for
- * transmitting SCO packet.
- */
- if (err && (info->packet_size == info->mtu)) {
- info->packet_size = err;
- } else {
- syslog(LOG_ERR,
- "Partially read %d bytes for %u size SCO packet",
- err, info->packet_size);
- return -1;
- }
- }
-
- buf_increment_write(info->capture_buf, err);
-
- return err;
-}
-
-/* Callback function to handle sample read and write.
- * Note that we poll the SCO socket for read sample, since it reflects
- * there is actual some sample to read while the socket always reports
- * writable even when device buffer is full.
- * The strategy is to synchronize read & write operations:
- * 1. Read one chunk of MTU bytes of data.
- * 2. When input device not attached, ignore the data just read.
- * 3. When output device attached, write one chunk of MTU bytes of data.
- */
-static int hfp_info_callback(void *arg, int revents)
-{
- struct hfp_info *info = (struct hfp_info *)arg;
- int err = 0;
-
- if (!info->started)
- return 0;
-
- /* Allow last read before handling error or hang-up events. */
- if (revents & POLLIN) {
- err = info->read_cb(info);
- if (err < 0) {
- syslog(LOG_ERR, "Read error");
- goto read_write_error;
- }
- }
- /* Ignore the bytes just read if input dev not in present */
- if (!info->input_format_bytes)
- buf_increment_read(info->capture_buf, err);
-
- if (revents & (POLLERR | POLLHUP)) {
- syslog(LOG_ERR, "Error polling SCO socket, revent %d", revents);
- goto read_write_error;
- }
-
- /* Without output stream's presence, we shall still send zero packets
- * to HF. This is required for some HF devices to start sending non-zero
- * data to AG.
- */
- if (!info->output_format_bytes)
- buf_increment_write(info->playback_buf,
- info->msbc_write ? err : info->packet_size);
-
- err = info->write_cb(info);
- if (err < 0) {
- syslog(LOG_ERR, "Write error");
- goto read_write_error;
- }
-
- return 0;
-
-read_write_error:
- /*
- * This callback is executing in audio thread, so it's safe to
- * unregister itself by audio_thread_rm_callback().
- */
- audio_thread_rm_callback(info->fd);
- close(info->fd);
- info->fd = 0;
- info->started = 0;
-
- return 0;
-}
-
-struct hfp_info *hfp_info_create()
-{
- struct hfp_info *info;
- info = (struct hfp_info *)calloc(1, sizeof(*info));
- if (!info)
- goto error;
-
- info->capture_buf = byte_buffer_create(MAX_HFP_BUF_SIZE_BYTES);
- if (!info->capture_buf)
- goto error;
-
- info->playback_buf = byte_buffer_create(MAX_HFP_BUF_SIZE_BYTES);
- if (!info->playback_buf)
- goto error;
-
- return info;
-
-error:
- if (info) {
- if (info->capture_buf)
- byte_buffer_destroy(&info->capture_buf);
- if (info->playback_buf)
- byte_buffer_destroy(&info->playback_buf);
- free(info);
- }
- return NULL;
-}
-
-void hfp_info_set_wbs_logger(struct hfp_info *info,
- struct packet_status_logger *wbs_logger)
-{
- info->wbs_logger = wbs_logger;
-}
-
-int hfp_info_running(struct hfp_info *info)
-{
- return info->started;
-}
-
-int hfp_info_start(int fd, unsigned int mtu, int codec, struct hfp_info *info)
-{
- info->fd = fd;
- info->mtu = mtu;
-
- /* Initialize to MTU, it may change when actually read the socket. */
- info->packet_size = mtu;
- buf_reset(info->playback_buf);
- buf_reset(info->capture_buf);
-
- if (codec == HFP_CODEC_ID_MSBC) {
- int i;
- for (i = 0; wbs_supported_packet_size[i] != 0; i++) {
- if (info->packet_size == wbs_supported_packet_size[i])
- break;
- }
- /* In case of unsupported value, error log and fallback to
- * MSBC_PKT_SIZE(60). */
- if (wbs_supported_packet_size[i] == 0) {
- syslog(LOG_ERR, "Unsupported packet size %u",
- info->packet_size);
- i = 0;
- }
- info->packet_size = wbs_supported_packet_size[i];
- info->write_buf = (uint8_t *)malloc(wbs_hci_sco_buffer_size[i]);
- info->read_buf = (uint8_t *)malloc(wbs_hci_sco_buffer_size[i]);
-
- info->write_cb = hfp_write_msbc;
- info->read_cb = hfp_read_msbc;
- info->msbc_read = cras_msbc_codec_create();
- info->msbc_write = cras_msbc_codec_create();
- info->msbc_plc = cras_msbc_plc_create();
-
- packet_status_logger_init(info->wbs_logger);
- } else {
- info->write_cb = hfp_write;
- info->read_cb = hfp_read;
- }
-
- audio_thread_add_events_callback(info->fd, hfp_info_callback, info,
- POLLIN | POLLERR | POLLHUP);
-
- info->started = 1;
- info->msbc_num_out_frames = 0;
- info->msbc_num_in_frames = 0;
- info->msbc_num_lost_frames = 0;
- info->write_rp = 0;
- info->write_wp = 0;
- info->read_rp = 0;
- info->read_wp = 0;
-
- /* Mark as aligned if packet size equals to MSBC_PKT_SIZE. */
- info->read_align_cb =
- (info->packet_size == MSBC_PKT_SIZE) ? NULL : msbc_frame_align;
- info->msbc_read_current_corrupted = 0;
-
- return 0;
-}
-
-int hfp_info_stop(struct hfp_info *info)
-{
- if (!info->started)
- return 0;
-
- audio_thread_rm_callback_sync(cras_iodev_list_get_audio_thread(),
- info->fd);
-
- close(info->fd);
- info->fd = 0;
- info->started = 0;
-
- /* Unset the write/read callbacks. */
- info->write_cb = NULL;
- info->read_cb = NULL;
-
- if (info->write_buf)
- free(info->write_buf);
- if (info->read_buf)
- free(info->read_buf);
-
- if (info->msbc_read) {
- cras_sbc_codec_destroy(info->msbc_read);
- info->msbc_read = NULL;
- }
- if (info->msbc_write) {
- cras_sbc_codec_destroy(info->msbc_write);
- info->msbc_write = NULL;
- }
- if (info->msbc_plc) {
- cras_msbc_plc_destroy(info->msbc_plc);
- info->msbc_plc = NULL;
- }
-
- if (info->msbc_num_in_frames) {
- cras_server_metrics_hfp_packet_loss(
- (float)info->msbc_num_lost_frames /
- info->msbc_num_in_frames);
- }
-
- return 0;
-}
-
-void hfp_info_destroy(struct hfp_info *info)
-{
- if (info->capture_buf)
- byte_buffer_destroy(&info->capture_buf);
-
- if (info->playback_buf)
- byte_buffer_destroy(&info->playback_buf);
-
- free(info);
-}
diff --git a/cras/src/server/cras_hfp_info.h b/cras/src/server/cras_hfp_info.h
deleted file mode 100644
index 3472aeab..00000000
--- a/cras/src/server/cras_hfp_info.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_HFP_INFO_H_
-#define CRAS_HFP_INFO_H_
-
-#include "cras_audio_format.h"
-#include "cras_types.h"
-
-/* Linked list to hold the information of callbacks to trigger
- * when the size of SCO packet has changed.
- */
-struct hfp_packet_size_changed_callback {
- void *data;
- void (*cb)(void *data);
- struct hfp_packet_size_changed_callback *next, *prev;
-};
-
-/* Structure to handle sample transmission between CRAS and the SCO
- * socket acquired from bluez.
- */
-struct hfp_info;
-
-/* Creates an hfp_info instance.
- */
-struct hfp_info *hfp_info_create();
-
-/* Destroys given hfp_info instance. */
-void hfp_info_destroy(struct hfp_info *info);
-
-/* Sets the wbs_logger to hfp_info instance. */
-void hfp_info_set_wbs_logger(struct hfp_info *info,
- struct packet_status_logger *wbs_logger);
-
-/* Checks if given hfp_info is running. */
-int hfp_info_running(struct hfp_info *info);
-
-/* Starts the hfp_info to transmit and reveice samples to and from the file
- * descriptor of a SCO socket. This should be called from main thread.
- * Args:
- * codec - 1 for CVSD, 2 for mSBC per HFP 1.7 specification.
- */
-int hfp_info_start(int fd, unsigned int mtu, int codec, struct hfp_info *info);
-
-/* Stops given hfp_info. This implies sample transmission will
- * stop and socket be closed. This should be called from main thread.
- */
-int hfp_info_stop(struct hfp_info *info);
-
-/* Queries how many frames of data are queued.
- * Args:
- * info - The hfp_info holding the buffer to query.
- * direction - The direction to indicate which buffer to query, playback
- * or capture.
- */
-int hfp_buf_queued(struct hfp_info *info, enum CRAS_STREAM_DIRECTION direction);
-
-/* Fill output buffer with zero frames.
- * Args:
- * info - The hfp_info holding the output buffer.
- * nframes - How many zero frames to fill.
- * Returns:
- * The actual number of zero frames filled.
- */
-int hfp_fill_output_with_zeros(struct hfp_info *info, unsigned int nframes);
-
-/* Force output buffer level to given value. Calling this may override
- * existing data so use it only when buffer has been filled by zeros.
- * If no output device was added, calling this has no effect.
- * Args:
- * info - The hfp_info holding output buffer.
- * level - Value of the target output level.
- */
-void hfp_force_output_level(struct hfp_info *info, unsigned int level);
-
-/* Gets how many frames of the buffer are used.
- * Args:
- * info - The hfp_info holding buffer.
- * direction - The direction of the buffer.
- */
-int hfp_buf_size(struct hfp_info *info, enum CRAS_STREAM_DIRECTION direction);
-
-/* Acquire buffer of count frames for dev to write(or read,
- * depend on dev's direction).
- * Args:
- * info - The hfp_info holding buffer.
- * direction - The direction of dev to acquire buffer for.
- * buf - To hold the returned pointer of acquired buffer.
- * count - Number of bytes of buffer to acquire, will be filled with the
- * actual acquired buffer size in bytes.
- */
-void hfp_buf_acquire(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction, uint8_t **buf,
- unsigned *count);
-
-/* Releases the previously acquired buffer.
- * Args:
- * info - The hfp_info holding the buffer.
- * direction - The direction of dev to release buffer for.
- * written_frames - The size of the previously acquired buffer in frames
- * which's been used.
- */
-void hfp_buf_release(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction,
- unsigned written_frames);
-
-/* Adds cras_iodev to given hfp_info. Only when an output iodev is added,
- * hfp_info starts sending samples to the SCO socket. Similarly, only when an
- * input iodev is added, it starts to read samples from SCO socket.
- */
-int hfp_info_add_iodev(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction,
- struct cras_audio_format *format);
-
-/* Removes cras_iodev from hfp_info. hfp_info will stop sending or
- * reading samples right after the iodev is removed. This function is used for
- * iodev closure.
- */
-int hfp_info_rm_iodev(struct hfp_info *info,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Checks if there's any iodev added to the given hfp_info. */
-int hfp_info_has_iodev(struct hfp_info *info);
-
-#endif /* CRAS_HFP_INFO_H_ */
diff --git a/cras/src/server/cras_hfp_iodev.c b/cras/src/server/cras_hfp_iodev.c
deleted file mode 100644
index 6a4ced04..00000000
--- a/cras/src/server/cras_hfp_iodev.c
+++ /dev/null
@@ -1,371 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdbool.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <syslog.h>
-
-#include "cras_audio_area.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_hfp_iodev.h"
-#include "cras_hfp_info.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev.h"
-#include "cras_system_state.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-/* Implementation of bluetooth hands-free profile iodev.
- * Members:
- * base - The cras_iodev structure base class.
- * device - The assciated bt_device.
- * slc - Handle to the HFP service level connection.
- * info - hfp_info taking care of SCO data read/write.
- * drain_complete - Flag to indicate if valid samples are drained
- * in no stream state. Only used for output.
- * filled_zeros - Number of zero data in frames have been filled
- * to buffer of hfp_info in no stream state. Only used for output
- */
-struct hfp_io {
- struct cras_iodev base;
- struct cras_bt_device *device;
- struct hfp_slc_handle *slc;
- struct hfp_info *info;
- bool drain_complete;
- unsigned int filled_zeros;
-};
-
-static int update_supported_formats(struct cras_iodev *iodev)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
-
- free(iodev->supported_rates);
- iodev->supported_rates = (size_t *)malloc(2 * sizeof(size_t));
-
- /* 16 bit, mono, 8kHz for narrowband and 16KHz for wideband */
- iodev->supported_rates[0] =
- (hfp_slc_get_selected_codec(hfpio->slc) == HFP_CODEC_ID_MSBC) ?
- 16000 :
- 8000;
- iodev->supported_rates[1] = 0;
-
- free(iodev->supported_channel_counts);
- iodev->supported_channel_counts = (size_t *)malloc(2 * sizeof(size_t));
- iodev->supported_channel_counts[0] = 1;
- iodev->supported_channel_counts[1] = 0;
-
- free(iodev->supported_formats);
- iodev->supported_formats =
- (snd_pcm_format_t *)malloc(2 * sizeof(snd_pcm_format_t));
- iodev->supported_formats[0] = SND_PCM_FORMAT_S16_LE;
- iodev->supported_formats[1] = 0;
-
- return 0;
-}
-
-static int no_stream(struct cras_iodev *iodev, int enable)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
- struct timespec hw_tstamp;
- unsigned int hw_level;
- unsigned int level_target;
-
- if (iodev->direction != CRAS_STREAM_OUTPUT)
- return 0;
-
- hw_level = iodev->frames_queued(iodev, &hw_tstamp);
- if (enable) {
- if (!hfpio->drain_complete && (hw_level <= hfpio->filled_zeros))
- hfpio->drain_complete = 1;
- hfpio->filled_zeros += hfp_fill_output_with_zeros(
- hfpio->info, iodev->buffer_size);
- return 0;
- }
-
- /* Leave no stream state.*/
- level_target = iodev->min_cb_level;
- if (hfpio->drain_complete) {
- hfp_force_output_level(hfpio->info, level_target);
- } else {
- unsigned int valid_samples = 0;
- if (hw_level > hfpio->filled_zeros)
- valid_samples = hw_level - hfpio->filled_zeros;
- level_target = MAX(level_target, valid_samples);
-
- if (level_target > hw_level)
- hfp_fill_output_with_zeros(hfpio->info,
- level_target - hw_level);
- else
- hfp_force_output_level(hfpio->info, level_target);
- }
- hfpio->drain_complete = 0;
- hfpio->filled_zeros = 0;
-
- return 0;
-}
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
-
- if (!hfp_info_running(hfpio->info))
- return -1;
-
- /* Do not enable timestamp mechanism on HFP device because last time
- * stamp might be a long time ago and it is not really useful. */
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return hfp_buf_queued(hfpio->info, iodev->direction);
-}
-
-static int output_underrun(struct cras_iodev *iodev)
-{
- /* Handle it the same way as cras_iodev_output_underrun(). */
- return cras_iodev_fill_odev_zeros(iodev, iodev->min_cb_level);
-}
-
-static int configure_dev(struct cras_iodev *iodev)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
- int sk, err, mtu;
-
- /* Assert format is set before opening device. */
- if (iodev->format == NULL)
- return -EINVAL;
-
- iodev->format->format = SND_PCM_FORMAT_S16_LE;
- cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
-
- if (hfp_info_running(hfpio->info))
- goto add_dev;
-
- /*
- * Might require a codec negotiation before building the sco connection.
- */
- hfp_slc_codec_connection_setup(hfpio->slc);
-
- sk = cras_bt_device_sco_connect(hfpio->device,
- hfp_slc_get_selected_codec(hfpio->slc));
- if (sk < 0)
- goto error;
-
- mtu = cras_bt_device_sco_packet_size(
- hfpio->device, sk, hfp_slc_get_selected_codec(hfpio->slc));
-
- /* Start hfp_info */
- err = hfp_info_start(sk, mtu, hfp_slc_get_selected_codec(hfpio->slc),
- hfpio->info);
- if (err)
- goto error;
-
- hfpio->drain_complete = 0;
- hfpio->filled_zeros = 0;
-add_dev:
- hfp_info_add_iodev(hfpio->info, iodev->direction, iodev->format);
- hfp_set_call_status(hfpio->slc, 1);
-
- iodev->buffer_size = hfp_buf_size(hfpio->info, iodev->direction);
-
- return 0;
-error:
- syslog(LOG_ERR, "Failed to open HFP iodev");
- return -1;
-}
-
-static int close_dev(struct cras_iodev *iodev)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
-
- hfp_info_rm_iodev(hfpio->info, iodev->direction);
- if (hfp_info_running(hfpio->info) && !hfp_info_has_iodev(hfpio->info)) {
- hfp_info_stop(hfpio->info);
- hfp_set_call_status(hfpio->slc, 0);
- }
-
- cras_iodev_free_format(iodev);
- cras_iodev_free_audio_area(iodev);
- return 0;
-}
-
-static void set_hfp_volume(struct cras_iodev *iodev)
-{
- size_t volume;
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
-
- volume = cras_system_get_volume();
- if (iodev->active_node)
- volume = cras_iodev_adjust_node_volume(iodev->active_node,
- volume);
-
- hfp_event_speaker_gain(hfpio->slc, volume);
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- struct timespec tstamp;
-
- return frames_queued(iodev, &tstamp);
-}
-
-static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
- unsigned *frames)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
- uint8_t *dst = NULL;
-
- if (!hfp_info_running(hfpio->info))
- return -1;
-
- hfp_buf_acquire(hfpio->info, iodev->direction, &dst, frames);
-
- iodev->area->frames = *frames;
- /* HFP is mono only. */
- iodev->area->channels[0].step_bytes =
- cras_get_format_bytes(iodev->format);
- iodev->area->channels[0].buf = dst;
-
- *area = iodev->area;
- return 0;
-}
-
-static int put_buffer(struct cras_iodev *iodev, unsigned nwritten)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
-
- if (!hfp_info_running(hfpio->info))
- return -1;
-
- hfp_buf_release(hfpio->info, iodev->direction, nwritten);
- return 0;
-}
-
-static int flush_buffer(struct cras_iodev *iodev)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
- unsigned nframes;
-
- if (iodev->direction == CRAS_STREAM_INPUT) {
- nframes = hfp_buf_queued(hfpio->info, iodev->direction);
- hfp_buf_release(hfpio->info, iodev->direction, nframes);
- }
- return 0;
-}
-
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
-}
-
-int hfp_iodev_is_hsp(struct cras_iodev *iodev)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
- return hfp_slc_is_hsp(hfpio->slc);
-}
-
-void hfp_free_resources(struct hfp_io *hfpio)
-{
- struct cras_ionode *node;
- node = hfpio->base.active_node;
- if (node) {
- cras_iodev_rm_node(&hfpio->base, node);
- free(node);
- }
- free(hfpio->base.supported_channel_counts);
- free(hfpio->base.supported_rates);
- free(hfpio->base.supported_formats);
- cras_iodev_free_resources(&hfpio->base);
-}
-
-struct cras_iodev *hfp_iodev_create(enum CRAS_STREAM_DIRECTION dir,
- struct cras_bt_device *device,
- struct hfp_slc_handle *slc,
- enum cras_bt_device_profile profile,
- struct hfp_info *info)
-{
- struct hfp_io *hfpio;
- struct cras_iodev *iodev;
- struct cras_ionode *node;
- const char *name;
-
- hfpio = (struct hfp_io *)calloc(1, sizeof(*hfpio));
- if (!hfpio)
- goto error;
-
- iodev = &hfpio->base;
- iodev->direction = dir;
-
- hfpio->device = device;
- hfpio->slc = slc;
-
- /* Set iodev's name to device readable name or the address. */
- name = cras_bt_device_name(device);
- if (!name)
- name = cras_bt_device_object_path(device);
-
- snprintf(iodev->info.name, sizeof(iodev->info.name), "%s", name);
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = 0;
- iodev->info.stable_id = cras_bt_device_get_stable_id(device);
-
- iodev->configure_dev = configure_dev;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->flush_buffer = flush_buffer;
- iodev->no_stream = no_stream;
- iodev->close_dev = close_dev;
- iodev->update_supported_formats = update_supported_formats;
- iodev->update_active_node = update_active_node;
- iodev->set_volume = set_hfp_volume;
- iodev->output_underrun = output_underrun;
-
- node = (struct cras_ionode *)calloc(1, sizeof(*node));
- node->dev = iodev;
- strcpy(node->name, iodev->info.name);
-
- node->plugged = 1;
- /* If headset mic doesn't support the wideband speech, report a
- * different node type so UI can set different plug priority. */
- node->type = CRAS_NODE_TYPE_BLUETOOTH;
- if (!hfp_slc_get_wideband_speech_supported(hfpio->slc) &&
- (dir == CRAS_STREAM_INPUT))
- node->type = CRAS_NODE_TYPE_BLUETOOTH_NB_MIC;
-
- node->volume = 100;
- gettimeofday(&node->plugged_time, NULL);
-
- /* Prepare active node before append, so bt_io can extract correct
- * info from HFP iodev and node. */
- cras_iodev_add_node(iodev, node);
- cras_iodev_set_active_node(iodev, node);
- cras_bt_device_append_iodev(device, iodev, profile);
-
- hfpio->info = info;
-
- /* Record max supported channels into cras_iodev_info. */
- iodev->info.max_supported_channels = 1;
-
- ewma_power_disable(&iodev->ewma);
-
- return iodev;
-
-error:
- if (hfpio) {
- hfp_free_resources(hfpio);
- free(hfpio);
- }
- return NULL;
-}
-
-void hfp_iodev_destroy(struct cras_iodev *iodev)
-{
- struct hfp_io *hfpio = (struct hfp_io *)iodev;
-
- cras_bt_device_rm_iodev(hfpio->device, iodev);
- hfp_free_resources(hfpio);
- free(hfpio);
-}
diff --git a/cras/src/server/cras_hfp_iodev.h b/cras/src/server/cras_hfp_iodev.h
deleted file mode 100644
index b50aa259..00000000
--- a/cras/src/server/cras_hfp_iodev.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_HFP_IODEV_H_
-#define CRAS_HFP_IODEV_H_
-
-#include "cras_bt_device.h"
-#include "cras_hfp_info.h"
-#include "cras_types.h"
-
-struct hfp_slc_handle;
-
-/*
- * Creates an hfp iodev.
- */
-struct cras_iodev *hfp_iodev_create(enum CRAS_STREAM_DIRECTION dir,
- struct cras_bt_device *device,
- struct hfp_slc_handle *slc,
- enum cras_bt_device_profile profile,
- struct hfp_info *info);
-
-void hfp_iodev_destroy(struct cras_iodev *iodev);
-
-/*
- * Returns if the iodev is running for a HSP connection. Note that
- * hfp_iodev is implemented for both HFP and HSP connection. And this
- * function allows caller to test if it falls to the rare case - HSP.
- */
-int hfp_iodev_is_hsp(struct cras_iodev *iodev);
-
-#endif /* CRAS_HFP_IODEV_H_ */
diff --git a/cras/src/server/cras_hfp_slc.c b/cras/src/server/cras_hfp_slc.c
deleted file mode 100644
index 28f73edc..00000000
--- a/cras/src/server/cras_hfp_slc.c
+++ /dev/null
@@ -1,1400 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <sys/socket.h>
-#include <syslog.h>
-
-#include "stdbool.h"
-
-#include "cras_bt_device.h"
-#include "cras_bt_log.h"
-#include "cras_observer.h"
-#include "cras_telephony.h"
-#include "cras_hfp_slc.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_tm.h"
-#include "cras_util.h"
-
-/* Message start and end with "\r\n". refer to spec 4.33. */
-#define AT_CMD(cmd) "\r\n" cmd "\r\n"
-
-/* The timeout between event reporting and HF indicator commands */
-#define HF_INDICATORS_TIMEOUT_MS 2000
-/* The sleep time before reading and processing the following AT commands during
- * codec connection setup.
- */
-#define CODEC_CONN_SLEEP_TIME_US 2000
-#define SLC_BUF_SIZE_BYTES 256
-
-/* Indicator update command response and indicator indices.
- * Note that indicator index starts from '1', index 0 is used for CRAS to record
- * if the event report has been enabled or not.
- */
-#define CRAS_INDICATOR_ENABLE_INDEX 0
-#define BATTERY_IND_INDEX 1
-#define SIGNAL_IND_INDEX 2
-#define SERVICE_IND_INDEX 3
-#define CALL_IND_INDEX 4
-#define CALLSETUP_IND_INDEX 5
-#define CALLHELD_IND_INDEX 6
-#define ROAM_IND_INDEX 7
-#define INDICATOR_IND_MAX 8
-#define INDICATOR_UPDATE_RSP \
- "+CIND: " \
- "(\"battchg\",(0-5))," \
- "(\"signal\",(0-5))," \
- "(\"service\",(0,1))," \
- "(\"call\",(0,1))," \
- "(\"callsetup\",(0-3))," \
- "(\"callheld\",(0-2))," \
- "(\"roam\",(0,1))" \
- ""
-/* Mode values for standard event reporting activation/deactivation AT
- * command AT+CMER. Used for indicator events reporting in HFP. */
-#define FORWARD_UNSOLICIT_RESULT_CODE 3
-
-/* Handle object to hold required info to initialize and maintain
- * an HFP service level connection.
- * Args:
- * buf - Buffer hold received commands.
- * buf_read_idx - Read index for buf.
- * buf_write_idx - Write index for buf.
- * rfcomm_fd - File descriptor for the established RFCOMM connection.
- * init_cb - Callback to be triggered when an SLC is initialized.
- * cli_active - Calling line identification notification is enabled or not.
- * battery - Current battery level of AG stored in SLC.
- * signal - Current signal strength of AG stored in SLC.
- * service - Current service availability of AG stored in SLC.
- * callheld - Current callheld status of AG stored in SLC.
- * ind_event_reports - Activate statuses of indicator events reporting.
- * ag_supported_features - Supported AG features bitmap.
- * hf_supported_features - Bit map of HF supported features.
- * hf_supports_battery_indicator - Bit map of battery indicator support of
- * connected HF.
- * hf_battery - Current battery level of HF reported by the HF. The data
- * range should be 0 ~ 100. Use -1 for no battery level reported.
- * preferred_codec - CVSD or mSBC based on the situation and strategy. This
- * needs not to be equal to selected_codec because codec negotiation
- * process may fail.
- * selected_codec - The codec id defaults to HFP_CODEC_UNUSED and changes
- * only if codec negotiation is supported and the negotiation flow
- * has completed.
- * telephony - A reference of current telephony handle.
- * device - The associated bt device.
- */
-struct hfp_slc_handle {
- char buf[SLC_BUF_SIZE_BYTES];
- int buf_read_idx;
- int buf_write_idx;
- int is_hsp;
- int rfcomm_fd;
- hfp_slc_init_cb init_cb;
- hfp_slc_disconnect_cb disconnect_cb;
- int cli_active;
- int battery;
- int signal;
- int service;
- int callheld;
- int ind_event_reports[INDICATOR_IND_MAX];
- int ag_supported_features;
- bool hf_codec_supported[HFP_MAX_CODECS];
- int hf_supported_features;
- int hf_supports_battery_indicator;
- int hf_battery;
- int preferred_codec;
- int selected_codec;
- struct cras_bt_device *device;
- struct cras_timer *timer;
-
- struct cras_telephony_handle *telephony;
-};
-
-/* AT command exchanges between AG(Audio gateway) and HF(Hands-free device) */
-struct at_command {
- const char *cmd;
- int (*callback)(struct hfp_slc_handle *handle, const char *cmd);
-};
-
-/* Sends a response or command to HF */
-static int hfp_send(struct hfp_slc_handle *handle, const char *buf)
-{
- int written, err, len;
-
- if (handle->rfcomm_fd < 0)
- return -EIO;
-
- len = strlen(buf);
- written = 0;
- while (written < len) {
- err = write(handle->rfcomm_fd, buf + written, len - written);
- if (err < 0)
- return -errno;
- written += err;
- }
-
- return 0;
-}
-
-/* Sends a response for indicator event reporting. */
-static int hfp_send_ind_event_report(struct hfp_slc_handle *handle,
- int ind_index, int value)
-{
- char cmd[64];
-
- if (handle->is_hsp ||
- !handle->ind_event_reports[CRAS_INDICATOR_ENABLE_INDEX] ||
- !handle->ind_event_reports[ind_index])
- return 0;
-
- snprintf(cmd, 64, AT_CMD("+CIEV: %d,%d"), ind_index, value);
- return hfp_send(handle, cmd);
-}
-
-/* Sends calling line identification unsolicited result code and
- * standard call waiting notification. */
-static int hfp_send_calling_line_identification(struct hfp_slc_handle *handle,
- const char *number, int type)
-{
- char cmd[64];
-
- if (handle->is_hsp)
- return 0;
-
- if (handle->telephony->call) {
- snprintf(cmd, 64, AT_CMD("+CCWA: \"%s\",%d"), number, type);
- } else {
- snprintf(cmd, 64, AT_CMD("+CLIP: \"%s\",%d"), number, type);
- }
- return hfp_send(handle, cmd);
-}
-
-/* ATA command to accept an incoming call. Mandatory support per spec 4.13. */
-static int answer_call(struct hfp_slc_handle *handle, const char *cmd)
-{
- int rc;
- rc = hfp_send(handle, AT_CMD("OK"));
- if (rc)
- return rc;
-
- return cras_telephony_event_answer_call();
-}
-
-/* AT+CCWA command to enable the "Call Waiting notification" function.
- * Mandatory support per spec 4.21. */
-static int call_waiting_notify(struct hfp_slc_handle *handle, const char *buf)
-{
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+CLIP command to enable the "Calling Line Identification notification"
- * function. Mandatory per spec 4.23.
- */
-static int cli_notification(struct hfp_slc_handle *handle, const char *cmd)
-{
- if (strlen(cmd) < 9) {
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
- handle->cli_active = (cmd[8] == '1');
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* ATDdd...dd command to place call with supplied number, or ATD>nnn...
- * command to dial the number stored at memory location. Mandatory per
- * spec 4.18 and 4.19.
- */
-static int dial_number(struct hfp_slc_handle *handle, const char *cmd)
-{
- int rc, cmd_len;
-
- cmd_len = strlen(cmd);
- if (cmd_len < 4)
- goto error_out;
-
- if (cmd[3] == '>') {
- /* Handle memory dial. Extract memory location from command
- * ATD>nnn...; and lookup. */
- int memory_location;
- memory_location = strtol(cmd + 4, NULL, 0);
- if (handle->telephony->dial_number == NULL ||
- memory_location != 1)
- return hfp_send(handle, AT_CMD("ERROR"));
- } else {
- /* ATDddddd; Store dial number to the only memory slot. */
- cras_telephony_store_dial_number(cmd_len - 3 - 1, cmd + 3);
- }
-
- rc = hfp_send(handle, AT_CMD("OK"));
- if (rc)
- return rc;
-
- handle->telephony->callsetup = 2;
- return hfp_send_ind_event_report(handle, CALLSETUP_IND_INDEX, 2);
-
-error_out:
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-/* AT+VTS command to generate a DTMF code. Mandatory per spec 4.27. */
-static int dtmf_tone(struct hfp_slc_handle *handle, const char *buf)
-{
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* Sends +BCS command to tell HF about our preferred codec. This shall
- * be called only if codec negotiation is supported.
- */
-static void select_preferred_codec(struct hfp_slc_handle *handle)
-{
- char buf[64];
- snprintf(buf, 64, AT_CMD("+BCS:%d"), handle->preferred_codec);
- hfp_send(handle, buf);
- BTLOG(btlog, BT_CODEC_SELECTION, 0, handle->preferred_codec);
-}
-
-/* Marks SLC handle as initialized and trigger HFP AG's init_cb. */
-static void initialize_slc_handle(struct cras_timer *timer, void *arg)
-{
- struct hfp_slc_handle *handle = (struct hfp_slc_handle *)arg;
- if (timer)
- handle->timer = NULL;
-
- if (handle->init_cb) {
- handle->init_cb(handle);
- handle->init_cb = NULL;
- }
-}
-
-/* Handles the event that headset request to start a codec connection
- * procedure.
- */
-static int bluetooth_codec_connection(struct hfp_slc_handle *handle,
- const char *cmd)
-{
- /* Reset current selected codec to force a new codec connection
- * procedure when the next hfp_slc_codec_connection_setup is called.
- */
- handle->selected_codec = HFP_CODEC_UNUSED;
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* Handles the event that headset request to select specific codec. */
-static int bluetooth_codec_selection(struct hfp_slc_handle *handle,
- const char *cmd)
-{
- char *tokens = strdup(cmd);
- char *codec;
- int id, err;
-
- strtok(tokens, "=");
- codec = strtok(NULL, ",");
- if (!codec)
- goto bcs_cmd_cleanup;
- id = atoi(codec);
- if ((id <= HFP_CODEC_UNUSED) || (id >= HFP_MAX_CODECS)) {
- syslog(LOG_ERR, "%s: invalid codec id: '%s'", __func__, cmd);
- free(tokens);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
-
- if (id != handle->preferred_codec)
- syslog(LOG_WARNING, "%s: inconsistent codec id: '%s'", __func__,
- cmd);
-
- BTLOG(btlog, BT_CODEC_SELECTION, 1, id);
- handle->selected_codec = id;
-
-bcs_cmd_cleanup:
- free(tokens);
- err = hfp_send(handle, AT_CMD("OK"));
- return err;
-}
-
-/*
- * AT+IPHONEACCEV command from HF to report state change.You can find details
- * of this command in the Accessory Design Guidelines for Apple Devices R11
- * section 16.1.
- */
-static int apple_accessory_state_change(struct hfp_slc_handle *handle,
- const char *cmd)
-{
- char *tokens, *num, *key, *val;
- int i, level;
-
- /* AT+IPHONEACCEV=Number of key/value pairs,key1,val1,key2,val2,...
- * Number of key/value pairs: The number of parameters coming next.
- * key: the type of change being reported:
- * 1 = Battery Level
- * 2 = Dock State
- * val: the value of the change:
- * Battery Level: string value between '0' and '9'
- * Dock State: 0 = undocked, 1 = docked
- */
- tokens = strdup(cmd);
- strtok(tokens, "=");
- num = strtok(NULL, ",");
- if (!num) {
- free(tokens);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
-
- for (i = 0; i < atoi(num); i++) {
- key = strtok(NULL, ",");
- val = strtok(NULL, ",");
- if (!key || !val) {
- syslog(LOG_WARNING,
- "IPHONEACCEV: Expected %d kv pairs but got %d",
- atoi(num), i);
- break;
- }
-
- if (atoi(key) == 1) {
- level = atoi(val);
- if (level >= 0 && level < 10) {
- cras_server_metrics_hfp_battery_report(
- CRAS_HFP_BATTERY_INDICATOR_APPLE);
- level = (level + 1) * 10;
- if (handle->hf_battery != level) {
- handle->hf_battery = level;
- cras_observer_notify_bt_battery_changed(
- cras_bt_device_address(
- handle->device),
- (uint32_t)(level));
- }
- } else {
- syslog(LOG_ERR,
- "Get invalid battery status from cmd:%s",
- cmd);
- }
- }
- }
- free(tokens);
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/*
- * AT+XAPL command from HF to enable Apple custom features. You can find details
- * of it in the Accessory Design Guidelines for Apple Devices R11 section 15.1.
- */
-static int apple_supported_features(struct hfp_slc_handle *handle,
- const char *cmd)
-{
- char *tokens, *features;
- int apple_features, err;
- char buf[64];
-
- /* AT+XAPL=<vendorID>-<productID>-<version>,<features>
- * Parse <features>, the only token we care about.
- */
- tokens = strdup(cmd);
- strtok(tokens, "=");
-
- strtok(NULL, ",");
- features = strtok(NULL, ",");
- if (!features)
- goto error_out;
-
- apple_features = atoi(features);
-
- if (apple_features & APL_BATTERY)
- handle->hf_supports_battery_indicator |=
- CRAS_HFP_BATTERY_INDICATOR_APPLE;
-
- snprintf(buf, 64, AT_CMD("+XAPL=iPhone,%d"),
- CRAS_APL_SUPPORTED_FEATURES);
- err = hfp_send(handle, buf);
- if (err)
- goto error_out;
-
- err = hfp_send(handle, AT_CMD("OK"));
- free(tokens);
- return err;
-
-error_out:
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- free(tokens);
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-/* Handles the event when headset reports its available codecs list. */
-static int available_codecs(struct hfp_slc_handle *handle, const char *cmd)
-{
- char *tokens, *id_str;
- int id;
-
- for (id = 0; id < HFP_MAX_CODECS; id++)
- handle->hf_codec_supported[id] = false;
-
- tokens = strdup(cmd);
- strtok(tokens, "=");
- id_str = strtok(NULL, ",");
- while (id_str) {
- id = atoi(id_str);
- if ((id > HFP_CODEC_UNUSED) && (id < HFP_MAX_CODECS)) {
- handle->hf_codec_supported[id] = true;
- BTLOG(btlog, BT_AVAILABLE_CODECS, 0, id);
- }
- id_str = strtok(NULL, ",");
- }
-
- if (hfp_slc_get_wideband_speech_supported(handle))
- handle->preferred_codec = HFP_CODEC_ID_MSBC;
- else
- handle->preferred_codec = HFP_CODEC_ID_CVSD;
-
- free(tokens);
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+CMER command enables the registration status update function in AG.
- * The service level connection is consider initialized when successfully
- * responded OK to the AT+CMER command. Mandatory support per spec 4.4.
- */
-static int event_reporting(struct hfp_slc_handle *handle, const char *cmd)
-{
- char *tokens, *mode, *tmp;
- int err = 0;
-
- /* AT+CMER=[<mode>[,<keyp>[,<disp>[,<ind> [,<bfr>]]]]]
- * Parse <ind>, the only token we care about.
- */
- tokens = strdup(cmd);
- strtok(tokens, "=");
-
- mode = strtok(NULL, ",");
- tmp = strtok(NULL, ",");
- tmp = strtok(NULL, ",");
- tmp = strtok(NULL, ",");
-
- /* mode = 3 for forward unsolicited result codes.
- * AT+CMER=3,0,0,1 activates “indicator events reporting”.
- * The service level connection is considered established after
- * successfully responded with OK, regardless of the indicator
- * events reporting status.
- */
- if (!mode || !tmp) {
- syslog(LOG_ERR, "Invalid event reporting” cmd %s", cmd);
- err = -EINVAL;
- goto event_reporting_done;
- }
- if (atoi(mode) == FORWARD_UNSOLICIT_RESULT_CODE)
- handle->ind_event_reports[CRAS_INDICATOR_ENABLE_INDEX] =
- atoi(tmp);
-
- err = hfp_send(handle, AT_CMD("OK"));
- if (err) {
- syslog(LOG_ERR, "Error sending response for command %s", cmd);
- goto event_reporting_done;
- }
-
- /*
- * Wait for HF to retrieve information about HF indicators and consider
- * the Service Level Connection to be fully initialized, and thereby
- * established, if HF doesn't support HF indicators.
- */
- if (hfp_slc_get_hf_hf_indicators_supported(handle))
- handle->timer =
- cras_tm_create_timer(cras_system_state_get_tm(),
- HF_INDICATORS_TIMEOUT_MS,
- initialize_slc_handle, handle);
- /*
- * Otherwise, regard the Service Level Connection to be fully
- * initialized and ready for the potential codec negotiation.
- */
- else
- initialize_slc_handle(NULL, (void *)handle);
-
-event_reporting_done:
- free(tokens);
- return err;
-}
-
-/* AT+CMEE command to set the "Extended Audio Gateway Error Result Code".
- * Mandatory per spec 4.9.
- */
-static int extended_errors(struct hfp_slc_handle *handle, const char *buf)
-{
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+CKPD command to handle the user initiated action from headset profile
- * device.
- */
-static int key_press(struct hfp_slc_handle *handle, const char *buf)
-{
- hfp_send(handle, AT_CMD("OK"));
-
- /* Release the call and connection. */
- if (handle->telephony->call || handle->telephony->callsetup) {
- cras_telephony_event_terminate_call();
- handle->disconnect_cb(handle);
- return -EIO;
- }
- return 0;
-}
-
-/* AT+BLDN command to re-dial the last number. Mandatory support
- * per spec 4.20.
- */
-static int last_dialed_number(struct hfp_slc_handle *handle, const char *buf)
-{
- int rc;
-
- if (!handle->telephony->dial_number)
- return hfp_send(handle, AT_CMD("ERROR"));
-
- rc = hfp_send(handle, AT_CMD("OK"));
- if (rc)
- return rc;
-
- handle->telephony->callsetup = 2;
- return hfp_send_ind_event_report(handle, CALLSETUP_IND_INDEX, 2);
-}
-
-/* AT+CLCC command to query list of current calls. Mandatory support
- * per spec 4.31.
- *
- * +CLCC: <idx>,<direction>,<status>,<mode>,<multiparty>
- */
-static int list_current_calls(struct hfp_slc_handle *handle, const char *cmd)
-{
- char buf[64];
-
- int idx = 1;
- int rc;
- /* Fake the call list base on callheld and call status
- * since we have no API exposed to manage call list.
- * This is a hack to pass qualification test which ask us to
- * handle the basic case that one call is active and
- * the other is on hold. */
- if (handle->telephony->callheld) {
- snprintf(buf, 64, AT_CMD("+CLCC: %d,1,1,0,0"), idx++);
- rc = hfp_send(handle, buf);
- if (rc)
- return rc;
- }
-
- if (handle->telephony->call) {
- snprintf(buf, 64, AT_CMD("+CLCC: %d,1,0,0,0"), idx++);
- rc = hfp_send(handle, buf);
- if (rc)
- return rc;
- }
-
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+COPS command to query currently selected operator or set name format.
- * Mandatory support per spec 4.8.
- */
-static int operator_selection(struct hfp_slc_handle *handle, const char *buf)
-{
- int rc;
- if (buf[7] == '?') {
- /* HF sends AT+COPS? command to find current network operator.
- * AG responds with +COPS:<mode>,<format>,<operator>, where
- * the mode=0 means automatic for network selection. If no
- * operator is selected, <format> and <operator> are omitted.
- */
- rc = hfp_send(handle, AT_CMD("+COPS: 0"));
- if (rc)
- return rc;
- }
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* The AT+CHLD command is used to control call hold, release, and multiparty
- * states.
- */
-static int call_hold(struct hfp_slc_handle *handle, const char *buf)
-{
- int rc;
-
- // Chrome OS doesn't yet support CHLD features but we need to reply
- // the query with an empty feature list rather than "ERROR" to increase
- // interoperability with certain devices (b/172413440).
- if (strlen(buf) > 8 && buf[7] == '=' && buf[8] == '?') {
- rc = hfp_send(handle, AT_CMD("+CHLD:"));
- if (rc)
- return rc;
- return hfp_send(handle, AT_CMD("OK"));
- }
-
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-/* AT+CIND command retrieves the supported indicator and its corresponding
- * range and order index or read current status of indicators. Mandatory
- * support per spec 4.2.
- */
-static int report_indicators(struct hfp_slc_handle *handle, const char *cmd)
-{
- int err;
- char buf[64];
-
- if (strlen(cmd) < 8) {
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
-
- if (cmd[7] == '=') {
- /* Indicator update test command "AT+CIND=?" */
- err = hfp_send(handle, AT_CMD(INDICATOR_UPDATE_RSP));
- } else {
- /* Indicator update read command "AT+CIND?".
- * Respond with current status of AG indicators,
- * the values must be listed in the indicator order declared
- * in INDICATOR_UPDATE_RSP.
- * +CIND: <signal>,<service>,<call>,
- * <callsetup>,<callheld>,<roam>
- */
- snprintf(buf, 64, AT_CMD("+CIND: %d,%d,%d,%d,%d,%d,0"),
- handle->battery, handle->signal, handle->service,
- handle->telephony->call, handle->telephony->callsetup,
- handle->telephony->callheld);
- err = hfp_send(handle, buf);
- }
-
- if (err < 0)
- return err;
-
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+BIA command to change the subset of indicators that shall be
- * sent by the AG.
- */
-static int indicator_activation(struct hfp_slc_handle *handle, const char *cmd)
-{
- char *ptr;
- int idx = BATTERY_IND_INDEX;
-
- /* AT+BIA=[[<indrep 1>][,[<indrep 2>][,...[,[<indrep n>]]]]]
- * According to the spec:
- * - The indicator state can be omitted and the current reporting
- * states of the indicator shall not change.
- * Ex: AT+BIA=,1,,0
- * Only the 2nd and 4th indicators may be affected.
- * - HF can provide fewer indicators than AG and states not provided
- * shall not change.
- * Ex: CRAS supports 7 indicators and gets AT+BIA=1,0,1
- * Only the first three indicators may be affected.
- * - Call, Call Setup and Held Call are mandatory and should be always
- * on no matter what state HF set.
- */
- ptr = strchr(cmd, '=');
- while (ptr && idx < INDICATOR_IND_MAX) {
- if (idx != CALL_IND_INDEX && idx != CALLSETUP_IND_INDEX &&
- idx != CALLHELD_IND_INDEX) {
- if (*(ptr + 1) == '1')
- handle->ind_event_reports[idx] = 1;
- else if (*(ptr + 1) == '0')
- handle->ind_event_reports[idx] = 0;
- }
- ptr = strchr(ptr + 1, ',');
- idx++;
- }
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+BIND command to report, query and activate Generic Status Indicators.
- * It is sent by the HF if both AG and HF support the HF indicator feature.
- */
-static int indicator_support(struct hfp_slc_handle *handle, const char *cmd)
-{
- char *tokens, *key;
- int err, cmd_len;
-
- cmd_len = strlen(cmd);
- if (cmd_len < 8)
- goto error_out;
-
- if (cmd[7] == '=') {
- /* AT+BIND=? (Read AG supported indicators) */
- if (cmd_len > 8 && cmd[8] == '?') {
- /* +BIND: (<a>,<b>,<c>,...,<n>) (Response to AT+BIND=?)
- * <a> ... <n>: 0-65535, entered as decimal unsigned
- * integer values without leading zeros, referencing an
- * HF indicator assigned number.
- * 1 is for Enhanced Driver Status.
- * 2 is for Battery Level.
- * For the list of HF indicator assigned number, you can
- * check the Bluetooth SIG Assigned Numbers web page.
- */
- BTLOG(btlog, BT_HFP_HF_INDICATOR, 1, 0);
- /* "2" is for HF Battery Level that we support. We don't
- * support "1" but this is a workaround for Pixel Buds 2
- * which expects this exact combination for battery
- * reporting (HFP 1.7 standard) to work. This workaround
- * is fine since we don't enable Safety Drive with
- * +BIND: 1,1 (b/172680041).
- */
- err = hfp_send(handle, AT_CMD("+BIND: (1,2)"));
- if (err < 0)
- return err;
- }
- /* AT+BIND=<a>,<b>,...,<n>(List HF supported indicators) */
- else {
- tokens = strdup(cmd);
- strtok(tokens, "=");
- key = strtok(NULL, ",");
- while (key != NULL) {
- if (atoi(key) == 2)
- handle->hf_supports_battery_indicator |=
- CRAS_HFP_BATTERY_INDICATOR_HFP;
- key = strtok(NULL, ",");
- }
- free(tokens);
- }
- }
- /* AT+BIND? (Read AG enabled/disabled status of indicators) */
- else if (cmd[7] == '?') {
- /* +BIND: <a>,<state> (Unsolicited or Response to AT+BIND?)
- * This response enables the AG to notify the HF which HF
- * indicators are supported and their state, enabled or
- * disabled.
- * <a>: 1 or 2, referencing an HF indicator assigned number.
- * <state>: 0-1, entered as integer values, where
- * 0 = disabled, no value changes shall be sent for this
- * indicator
- * 1 = enabled, value changes may be sent for this indicator
- */
-
- /* We don't support Enhanced Driver Status, so explicitly
- * disable it (b/172680041).
- */
- err = hfp_send(handle, AT_CMD("+BIND: 1,0"));
- if (err < 0)
- return err;
-
- BTLOG(btlog, BT_HFP_HF_INDICATOR, 0, 0);
-
- err = hfp_send(handle, AT_CMD("+BIND: 2,1"));
- if (err < 0)
- return err;
-
- err = hfp_send(handle, AT_CMD("OK"));
- if (err)
- return err;
- /*
- * Consider the Service Level Connection to be fully initialized
- * and thereby established, after successfully responded with OK
- */
- initialize_slc_handle(NULL, (void *)handle);
- return 0;
- } else {
- goto error_out;
- }
- /* This OK reply is required after both +BIND AT commands. It also
- * covers the AT+BIND= <a>,<b>,...,<n> case.
- */
- return hfp_send(handle, AT_CMD("OK"));
-
-error_out:
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-/* AT+BIEV command reports updated values of enabled HF indicators to the AG.
- */
-static int indicator_state_change(struct hfp_slc_handle *handle,
- const char *cmd)
-{
- char *tokens, *key, *val;
- int level;
- /* AT+BIEV= <assigned number>,<value> (Update value of indicator)
- * CRAS only supports battery level, which is with assigned number 2.
- * Battery level should range from 0 to 100 defined by the spec.
- */
- tokens = strdup(cmd);
- strtok(tokens, "=");
- key = strtok(NULL, ",");
- if (!key)
- goto error_out;
-
- if (atoi(key) == 2) {
- val = strtok(NULL, ",");
- if (!val)
- goto error_out;
- level = atoi(val);
- if (level >= 0 && level <= 100) {
- cras_server_metrics_hfp_battery_report(
- CRAS_HFP_BATTERY_INDICATOR_HFP);
- if (handle->hf_battery != level) {
- handle->hf_battery = level;
- cras_observer_notify_bt_battery_changed(
- cras_bt_device_address(handle->device),
- (uint32_t)(level));
- }
- } else {
- syslog(LOG_ERR,
- "Get invalid battery status from cmd:%s", cmd);
- }
- } else {
- goto error_out;
- }
-
- free(tokens);
- return hfp_send(handle, AT_CMD("OK"));
-
-error_out:
- syslog(LOG_WARNING, "%s: invalid command: '%s'", __func__, cmd);
- free(tokens);
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-/* AT+VGM and AT+VGS command reports the current mic and speaker gain
- * level respectively. Optional support per spec 4.28.
- */
-static int signal_gain_setting(struct hfp_slc_handle *handle, const char *cmd)
-{
- int gain;
-
- if (strlen(cmd) < 8) {
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
-
- /* Map 0 to the smallest non-zero scale 6/100, and 15 to
- * 100/100 full. */
- if (cmd[5] == 'S') {
- gain = atoi(&cmd[7]);
- if (gain < 0 || gain > 15) {
- syslog(LOG_ERR,
- "signal_gain_setting: gain %d is not between 0 and 15",
- gain);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
- BTLOG(btlog, BT_HFP_UPDATE_SPEAKER_GAIN, gain, 0);
- cras_bt_device_update_hardware_volume(handle->device,
- (gain + 1) * 100 / 16);
- }
-
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+CNUM command to query the subscriber number. Mandatory support
- * per spec 4.30.
- */
-static int subscriber_number(struct hfp_slc_handle *handle, const char *buf)
-{
- return hfp_send(handle, AT_CMD("OK"));
-}
-
-/* AT+BRSF command notifies the HF(Hands-free device) supported features
- * and retrieves the AG(Audio gateway) supported features. Mandatory
- * support per spec 4.2.
- */
-static int supported_features(struct hfp_slc_handle *handle, const char *cmd)
-{
- int err;
- char response[128];
- char *tokens, *features;
-
- if (strlen(cmd) < 9) {
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
- }
-
- tokens = strdup(cmd);
- strtok(tokens, "=");
- features = strtok(NULL, ",");
- if (!features)
- goto error_out;
-
- handle->hf_supported_features = atoi(features);
- BTLOG(btlog, BT_HFP_SUPPORTED_FEATURES, 0,
- handle->hf_supported_features);
- free(tokens);
-
- /* AT+BRSF=<feature> command received, ignore the HF supported feature
- * for now. Respond with +BRSF:<feature> to notify mandatory supported
- * features in AG(audio gateway).
- */
- BTLOG(btlog, BT_HFP_SUPPORTED_FEATURES, 1,
- handle->ag_supported_features);
- snprintf(response, 128, AT_CMD("+BRSF: %u"),
- handle->ag_supported_features);
- err = hfp_send(handle, response);
- if (err < 0)
- return err;
-
- return hfp_send(handle, AT_CMD("OK"));
-
-error_out:
- free(tokens);
- syslog(LOG_ERR, "%s: malformed command: '%s'", __func__, cmd);
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-int hfp_event_speaker_gain(struct hfp_slc_handle *handle, int gain)
-{
- char command[128];
-
- /* Normailize gain value to 0-15 */
- gain = gain * 15 / 100;
- BTLOG(btlog, BT_HFP_SET_SPEAKER_GAIN, gain, 0);
- snprintf(command, 128, AT_CMD("+VGS=%d"), gain);
-
- return hfp_send(handle, command);
-}
-
-/* AT+CHUP command to terminate current call. Mandatory support
- * per spec 4.15.
- */
-static int terminate_call(struct hfp_slc_handle *handle, const char *cmd)
-{
- int rc;
- rc = hfp_send(handle, AT_CMD("OK"));
- if (rc)
- return rc;
-
- return cras_telephony_event_terminate_call();
-}
-
-/* AT+XEVENT is defined by Android to support vendor specific features.
- * Currently, the only known supported case for CrOS is the battery event sent
- * by some Plantronics headsets.
- */
-static int vendor_specific_features(struct hfp_slc_handle *handle,
- const char *cmd)
-{
- char *tokens, *event, *level_str, *num_of_level_str;
- int level, num_of_level;
-
- tokens = strdup(cmd);
- strtok(tokens, "=");
- event = strtok(NULL, ",");
- if (!event)
- goto error_out;
-
- /* AT+XEVENT=BATTERY,Level,NumberOfLevel,MinutesOfTalkTime,IsCharging
- * Level: The charge level with a zero-based integer.
- * NumberOfLevel: How many charging levels there are.
- * MinuteOfTalkTime: The estimated number of talk minutes remaining.
- * IsCharging: A 0 or 1 value.
- *
- * We only support the battery level and thus only care about the first
- * 3 arguments.
- */
- if (!strncmp(event, "BATTERY", 7)) {
- level_str = strtok(NULL, ",");
- num_of_level_str = strtok(NULL, ",");
- if (!level_str || !num_of_level_str)
- goto error_out;
-
- level = atoi(level_str);
- num_of_level = atoi(num_of_level_str);
- if (level < 0 || num_of_level <= 1 || level >= num_of_level)
- goto error_out;
-
- level = (int64_t)level * 100 / (num_of_level - 1);
- if (handle->hf_battery != level) {
- handle->hf_supports_battery_indicator |=
- CRAS_HFP_BATTERY_INDICATOR_PLANTRONICS;
- cras_server_metrics_hfp_battery_report(
- CRAS_HFP_BATTERY_INDICATOR_PLANTRONICS);
- handle->hf_battery = level;
- cras_observer_notify_bt_battery_changed(
- cras_bt_device_address(handle->device),
- (uint32_t)(level));
- }
- }
-
- free(tokens);
- /* For Plantronic headsets, it is required to reply "OK" for the first
- * AT+XEVENT=USER-AGENT... command to tell the headset our support of
- * the xevent protocol. Otherwise, all following events including
- * BATTERY won't be sent.
- */
- return hfp_send(handle, AT_CMD("OK"));
-
-error_out:
- syslog(LOG_ERR, "%s: malformed vendor specific command: '%s'", __func__,
- cmd);
- free(tokens);
- return hfp_send(handle, AT_CMD("ERROR"));
-}
-
-/* AT commands to support in order to conform HFP specification.
- *
- * An initialized service level connection is the pre-condition for all
- * call related procedures. Note that for the call related commands,
- * we are good to just respond with a meaningless "OK".
- *
- * The procedure to establish a service level connection is described below:
- *
- * 1. HF notifies AG about its own supported features and AG responds
- * with its supported feature.
- *
- * HF(hands-free) AG(audio gateway)
- * AT+BRSF=<HF supported feature> -->
- * <-- +BRSF:<AG supported feature>
- * <-- OK
- *
- * 2. HF retrieves the information about the indicators supported in AG.
- *
- * HF(hands-free) AG(audio gateway)
- * AT+CIND=? -->
- * <-- +CIND:...
- * <-- OK
- *
- * 3. The HF requests the current status of the indicators in AG.
- *
- * HF(hands-free) AG(audio gateway)
- * AT+CIND -->
- * <-- +CIND:...
- * <-- OK
- *
- * 4. HF requests enabling indicator status update in the AG.
- *
- * HF(hands-free) AG(audio gateway)
- * AT+CMER= -->
- * <-- OK
- */
-static struct at_command at_commands[] = {
- { "ATA", answer_call },
- { "ATD", dial_number },
- { "AT+BAC", available_codecs },
- { "AT+BCC", bluetooth_codec_connection },
- { "AT+BCS", bluetooth_codec_selection },
- { "AT+BIA", indicator_activation },
- { "AT+BIEV", indicator_state_change },
- { "AT+BIND", indicator_support },
- { "AT+BLDN", last_dialed_number },
- { "AT+BRSF", supported_features },
- { "AT+CCWA", call_waiting_notify },
- { "AT+CHUP", terminate_call },
- { "AT+CIND", report_indicators },
- { "AT+CKPD", key_press },
- { "AT+CLCC", list_current_calls },
- { "AT+CLIP", cli_notification },
- { "AT+CMEE", extended_errors },
- { "AT+CMER", event_reporting },
- { "AT+CNUM", subscriber_number },
- { "AT+COPS", operator_selection },
- { "AT+IPHONEACCEV", apple_accessory_state_change },
- { "AT+VG", signal_gain_setting },
- { "AT+VTS", dtmf_tone },
- { "AT+XAPL", apple_supported_features },
- { "AT+XEVENT", vendor_specific_features },
- { "AT+CHLD", call_hold },
- { 0 }
-};
-
-static int handle_at_command(struct hfp_slc_handle *slc_handle, const char *cmd)
-{
- struct at_command *atc;
-
- for (atc = at_commands; atc->cmd; atc++)
- if (!strncmp(cmd, atc->cmd, strlen(atc->cmd)))
- return atc->callback(slc_handle, cmd);
-
- syslog(LOG_DEBUG, "AT command %s not supported", cmd);
- return hfp_send(slc_handle, AT_CMD("ERROR"));
-}
-
-int handle_at_command_for_test(struct hfp_slc_handle *slc_handle,
- const char *cmd)
-{
- return handle_at_command(slc_handle, cmd);
-}
-
-static int process_at_commands(struct hfp_slc_handle *handle)
-{
- ssize_t bytes_read;
- int err;
-
- bytes_read =
- read(handle->rfcomm_fd, &handle->buf[handle->buf_write_idx],
- SLC_BUF_SIZE_BYTES - handle->buf_write_idx - 1);
- if (bytes_read < 0)
- return bytes_read;
-
- handle->buf_write_idx += bytes_read;
- handle->buf[handle->buf_write_idx] = '\0';
-
- while (handle->buf_read_idx != handle->buf_write_idx) {
- char *end_char;
- end_char = strchr(&handle->buf[handle->buf_read_idx], '\r');
- if (end_char == NULL)
- break;
-
- *end_char = '\0';
- err = handle_at_command(handle,
- &handle->buf[handle->buf_read_idx]);
- if (err < 0)
- return 0;
-
- /* Shift the read index */
- handle->buf_read_idx = 1 + end_char - handle->buf;
- if (handle->buf_read_idx == handle->buf_write_idx) {
- handle->buf_read_idx = 0;
- handle->buf_write_idx = 0;
- }
- }
-
- /* Handle the case when buffer is full and no command found. */
- if (handle->buf_write_idx == SLC_BUF_SIZE_BYTES - 1) {
- if (handle->buf_read_idx) {
- memmove(handle->buf, &handle->buf[handle->buf_read_idx],
- handle->buf_write_idx - handle->buf_read_idx);
- handle->buf_write_idx -= handle->buf_read_idx;
- handle->buf_read_idx = 0;
- } else {
- syslog(LOG_ERR,
- "Parse SLC command error, clean up buffer");
- handle->buf_write_idx = 0;
- }
- }
- return bytes_read;
-}
-
-static void slc_watch_callback(void *arg, int revents)
-{
- struct hfp_slc_handle *handle = (struct hfp_slc_handle *)arg;
- int err;
-
- err = process_at_commands(handle);
- if (err < 0) {
- syslog(LOG_ERR, "Error reading slc command %s",
- strerror(errno));
- cras_system_rm_select_fd(handle->rfcomm_fd);
- handle->disconnect_cb(handle);
- }
- return;
-}
-
-/* Exported interfaces */
-
-struct hfp_slc_handle *hfp_slc_create(int fd, int is_hsp,
- int ag_supported_features,
- struct cras_bt_device *device,
- hfp_slc_init_cb init_cb,
- hfp_slc_disconnect_cb disconnect_cb)
-{
- struct hfp_slc_handle *handle;
- int i;
-
- if (!disconnect_cb)
- return NULL;
-
- handle = (struct hfp_slc_handle *)calloc(1, sizeof(*handle));
- if (!handle)
- return NULL;
-
- handle->rfcomm_fd = fd;
- handle->is_hsp = is_hsp;
- handle->ag_supported_features = ag_supported_features;
- handle->hf_supported_features = 0;
- handle->device = device;
- handle->init_cb = init_cb;
- handle->disconnect_cb = disconnect_cb;
- handle->cli_active = 0;
- handle->battery = 5;
- handle->signal = 5;
- handle->service = 1;
- handle->ind_event_reports[CRAS_INDICATOR_ENABLE_INDEX] = 0;
- for (i = BATTERY_IND_INDEX; i < INDICATOR_IND_MAX; i++)
- handle->ind_event_reports[i] = 1;
- handle->telephony = cras_telephony_get();
- handle->preferred_codec = HFP_CODEC_ID_CVSD;
- handle->selected_codec = HFP_CODEC_UNUSED;
- handle->hf_supports_battery_indicator = CRAS_HFP_BATTERY_INDICATOR_NONE;
- handle->hf_battery = -1;
- cras_system_add_select_fd(handle->rfcomm_fd, slc_watch_callback, handle,
- POLLIN | POLLERR | POLLHUP);
-
- return handle;
-}
-
-void hfp_slc_destroy(struct hfp_slc_handle *slc_handle)
-{
- cras_system_rm_select_fd(slc_handle->rfcomm_fd);
- if (slc_handle->timer)
- cras_tm_cancel_timer(cras_system_state_get_tm(),
- slc_handle->timer);
- close(slc_handle->rfcomm_fd);
- free(slc_handle);
-}
-
-int hfp_slc_is_hsp(struct hfp_slc_handle *handle)
-{
- return handle->is_hsp;
-}
-
-int hfp_slc_get_selected_codec(struct hfp_slc_handle *handle)
-{
- /* If codec negotiation is not supported on HF, or the negotiation
- * process never completed. Fallback to the preffered codec. */
- if (handle->selected_codec == HFP_CODEC_UNUSED)
- return handle->preferred_codec;
- else
- return handle->selected_codec;
-}
-
-int hfp_slc_codec_connection_setup(struct hfp_slc_handle *handle)
-{
- /* The time we wait for codec selection response. */
- static struct timespec timeout = { 0, 100000000 };
- struct pollfd poll_fd;
- int rc = 0;
- struct timespec ts = timeout;
-
- /*
- * Codec negotiation is not required, if either AG or HF doesn't support
- * it or it has been done once.
- */
- if (!hfp_slc_get_hf_codec_negotiation_supported(handle) ||
- !hfp_slc_get_ag_codec_negotiation_supported(handle) ||
- handle->selected_codec == handle->preferred_codec)
- return 0;
-
-redo_codec_conn:
- select_preferred_codec(handle);
-
- poll_fd.fd = handle->rfcomm_fd;
- poll_fd.events = POLLIN;
-
- ts = timeout;
- while (rc <= 0) {
- rc = cras_poll(&poll_fd, 1, &ts, NULL);
- if (rc == -ETIMEDOUT) {
- /*
- * Catch the case that the first initial codec
- * negotiation timeout. At this point we're not sure
- * if HF is good with the preferred codec from AG.
- * Fallback to CVSD doesn't help because very likely
- * HF won't reply that either. The best thing we can
- * do is just leave a warning log.
- */
- if (handle->selected_codec == HFP_CODEC_UNUSED) {
- syslog(LOG_WARNING,
- "Proceed using codec %d without HF reply",
- handle->preferred_codec);
- }
- return rc;
- }
- }
-
- if (rc > 0) {
- do {
- usleep(CODEC_CONN_SLEEP_TIME_US);
- rc = process_at_commands(handle);
- } while (rc == -EAGAIN);
-
- if (rc <= 0)
- return rc;
- if (handle->selected_codec != handle->preferred_codec)
- goto redo_codec_conn;
- }
-
- return 0;
-}
-
-int hfp_set_call_status(struct hfp_slc_handle *handle, int call)
-{
- int old_call = handle->telephony->call;
-
- if (old_call == call)
- return 0;
-
- handle->telephony->call = call;
- return hfp_event_update_call(handle);
-}
-
-/* Procedure to setup a call when AG sees incoming call.
- *
- * HF(hands-free) AG(audio gateway)
- * <-- Incoming call
- * <-- +CIEV: (callsetup = 1)
- * <-- RING (ALERT)
- */
-int hfp_event_incoming_call(struct hfp_slc_handle *handle, const char *number,
- int type)
-{
- int rc;
-
- if (handle->is_hsp)
- return 0;
-
- if (handle->cli_active) {
- rc = hfp_send_calling_line_identification(handle, number, type);
- if (rc)
- return rc;
- }
-
- if (handle->telephony->call)
- return 0;
- else
- return hfp_send(handle, AT_CMD("RING"));
-}
-
-int hfp_event_update_call(struct hfp_slc_handle *handle)
-{
- return hfp_send_ind_event_report(handle, CALL_IND_INDEX,
- handle->telephony->call);
-}
-
-int hfp_event_update_callsetup(struct hfp_slc_handle *handle)
-{
- return hfp_send_ind_event_report(handle, CALLSETUP_IND_INDEX,
- handle->telephony->callsetup);
-}
-
-int hfp_event_update_callheld(struct hfp_slc_handle *handle)
-{
- return hfp_send_ind_event_report(handle, CALLHELD_IND_INDEX,
- handle->telephony->callheld);
-}
-
-int hfp_event_set_battery(struct hfp_slc_handle *handle, int level)
-{
- handle->battery = level;
- return hfp_send_ind_event_report(handle, BATTERY_IND_INDEX, level);
-}
-
-int hfp_event_set_signal(struct hfp_slc_handle *handle, int level)
-{
- handle->signal = level;
- return hfp_send_ind_event_report(handle, SIGNAL_IND_INDEX, level);
-}
-
-int hfp_event_set_service(struct hfp_slc_handle *handle, int avail)
-{
- /* Convert to 0 or 1.
- * Since the value must be either 1 or 0. (service presence or not) */
- handle->service = !!avail;
- return hfp_send_ind_event_report(handle, SERVICE_IND_INDEX, avail);
-}
-
-int hfp_slc_get_ag_codec_negotiation_supported(struct hfp_slc_handle *handle)
-{
- return handle->ag_supported_features & AG_CODEC_NEGOTIATION;
-}
-
-int hfp_slc_get_hf_codec_negotiation_supported(struct hfp_slc_handle *handle)
-{
- return handle->hf_supported_features & HF_CODEC_NEGOTIATION;
-}
-
-int hfp_slc_get_hf_hf_indicators_supported(struct hfp_slc_handle *handle)
-{
- return handle->hf_supported_features & HF_HF_INDICATORS;
-}
-
-bool hfp_slc_get_wideband_speech_supported(struct hfp_slc_handle *handle)
-{
- return hfp_slc_get_ag_codec_negotiation_supported(handle) &&
- hfp_slc_get_hf_codec_negotiation_supported(handle) &&
- handle->hf_codec_supported[HFP_CODEC_ID_MSBC];
-}
-
-int hfp_slc_get_hf_supports_battery_indicator(struct hfp_slc_handle *handle)
-{
- return handle->hf_supports_battery_indicator;
-}
diff --git a/cras/src/server/cras_hfp_slc.h b/cras/src/server/cras_hfp_slc.h
deleted file mode 100644
index 99335eab..00000000
--- a/cras/src/server/cras_hfp_slc.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_HFP_SLC_H_
-#define CRAS_HFP_SLC_H_
-
-struct hfp_slc_handle;
-struct cras_bt_device;
-
-/*
- * Hands-free HFP and AG supported features bits definition.
- * Per HFP 1.7.1 specification section 4.34.1, command
- * AT+BRSF (Bluetooth Retrieve Supported Features)
- */
-#define HF_EC_ANDOR_NR 0x0001
-#define HF_THREE_WAY_CALLING 0x0002
-#define HF_CLI_PRESENTATION_CAP 0x0004
-#define HF_VOICE_RECOGNITION 0x0008
-#define HF_REMOTE_VOLUME_CONTROL 0x0010
-#define HF_ENHANCED_CALL_STATUS 0x0020
-#define HF_ENHANCED_CALL_CONTROL 0x0040
-#define HF_CODEC_NEGOTIATION 0x0080
-#define HF_HF_INDICATORS 0x0100
-#define HF_ESCO_S4_T2_SETTINGS 0x0200
-
-#define AG_THREE_WAY_CALLING 0x0001
-#define AG_EC_ANDOR_NR 0x0002
-#define AG_VOICE_RECOGNITION 0x0004
-#define AG_INBAND_RINGTONE 0x0008
-#define AG_ATTACH_NUMBER_TO_VOICETAG 0x0010
-#define AG_REJECT_A_CALL 0x0020
-#define AG_ENHANCED_CALL_STATUS 0x0040
-#define AG_ENHANCED_CALL_CONTROL 0x0080
-#define AG_EXTENDED_ERROR_RESULT_CODES 0x0100
-#define AG_CODEC_NEGOTIATION 0x0200
-#define AG_HF_INDICATORS 0x0400
-#define AG_ESCO_S4_T2_SETTINGS 0x0800
-
-/*
- * Apple specific bluetooth commands that extend accessory capabilities.
- * Per Accessory Design Guidelines for Apple devices, command AT+XAPL
- */
-
-#define APL_RESERVED 0x01
-#define APL_BATTERY 0x02
-#define APL_DOCKED_OR_POWERED 0x04
-#define APL_SIRI 0x08
-#define APL_NOISE_REDUCTION 0x10
-
-#define CRAS_APL_SUPPORTED_FEATURES (APL_BATTERY)
-
-/* Codec ids for codec negotiation, per HFP 1.7.1 spec appendix B. */
-#define HFP_CODEC_UNUSED 0
-#define HFP_CODEC_ID_CVSD 1
-#define HFP_CODEC_ID_MSBC 2
-#define HFP_MAX_CODECS 3
-
-/* Hands-free HFP supported battery indicator bit definition.
- * This is currently only used for logging purpose. */
-#define CRAS_HFP_BATTERY_INDICATOR_NONE 0x0
-#define CRAS_HFP_BATTERY_INDICATOR_HFP 0x1
-#define CRAS_HFP_BATTERY_INDICATOR_APPLE 0x2
-#define CRAS_HFP_BATTERY_INDICATOR_PLANTRONICS 0x4
-
-/* Callback to call when service level connection initialized. */
-typedef int (*hfp_slc_init_cb)(struct hfp_slc_handle *handle);
-
-/* Callback to call when service level connection disconnected. */
-typedef int (*hfp_slc_disconnect_cb)(struct hfp_slc_handle *handle);
-
-/* Creates an hfp_slc_handle to poll the RFCOMM file descriptor
- * to read and handle received AT commands.
- * Args:
- * fd - the rfcomm fd used to initialize service level connection
- * is_hsp - if the slc handle is created for headset profile
- * ag_supported_features - Supported AG features bitmap.
- * device - The bt device associated with the created slc object
- * init_cb - the callback function to be triggered when a service level
- * connection is initialized.
- * disconnect_cb - the callback function to be triggered when the service
- * level connection is disconnected.
- */
-struct hfp_slc_handle *hfp_slc_create(int fd, int is_hsp,
- int ag_supported_features,
- struct cras_bt_device *device,
- hfp_slc_init_cb init_cb,
- hfp_slc_disconnect_cb disconnect_cb);
-
-/* Destroys an hfp_slc_handle. */
-void hfp_slc_destroy(struct hfp_slc_handle *handle);
-
-/* Returns true if this SLC is created for headset profile(HSP), false
- * means it's created for hands-free profile(HFP).
- */
-int hfp_slc_is_hsp(struct hfp_slc_handle *handle);
-
-/* Sets the call status to notify handsfree device. */
-int hfp_set_call_status(struct hfp_slc_handle *handle, int call);
-
-/* Fakes the incoming call event for qualification test. */
-int hfp_event_incoming_call(struct hfp_slc_handle *handle, const char *number,
- int type);
-
-/* Handles the call status changed event.
- * AG will send notification to HF accordingly. */
-int hfp_event_update_call(struct hfp_slc_handle *handle);
-
-/* Handles the call setup status changed event.
- * AG will send notification to HF accordingly. */
-int hfp_event_update_callsetup(struct hfp_slc_handle *handle);
-
-/* Handles the call held status changed event.
- * AG will send notification to HF accordingly. */
-int hfp_event_update_callheld(struct hfp_slc_handle *handle);
-
-/* Sets battery level which is required for qualification test. */
-int hfp_event_set_battery(struct hfp_slc_handle *handle, int value);
-
-/* Sets signal strength which is required for qualification test. */
-int hfp_event_set_signal(struct hfp_slc_handle *handle, int value);
-
-/* Sets service availability which is required for qualification test. */
-int hfp_event_set_service(struct hfp_slc_handle *handle, int value);
-
-/* Sets speaker gain value to headsfree device. */
-int hfp_event_speaker_gain(struct hfp_slc_handle *handle, int gain);
-
-/* Gets the selected codec for HFP, mSBC or CVSD. */
-int hfp_slc_get_selected_codec(struct hfp_slc_handle *handle);
-
-/* Gets if the remote HF supports codec negotiation. */
-int hfp_slc_get_hf_codec_negotiation_supported(struct hfp_slc_handle *handle);
-
-/* Gets if the remote HF supports HF indicator. */
-int hfp_slc_get_hf_hf_indicators_supported(struct hfp_slc_handle *handle);
-
-/* Gets if the HF side supports wideband speech. */
-bool hfp_slc_get_wideband_speech_supported(struct hfp_slc_handle *handle);
-
-/* Gets if the AG side supports codec negotiation. */
-int hfp_slc_get_ag_codec_negotiation_supported(struct hfp_slc_handle *handle);
-
-/* Gets an enum representing which spec the HF supports battery indicator.
- * Apple, HFP, none, or both. */
-int hfp_slc_get_hf_supports_battery_indicator(struct hfp_slc_handle *handle);
-
-/* Init the codec negotiation process if needed. */
-int hfp_slc_codec_connection_setup(struct hfp_slc_handle *handle);
-
-// Expose internal AT command handling for fuzzing.
-int handle_at_command_for_test(struct hfp_slc_handle *slc_handle,
- const char *cmd);
-
-#endif /* CRAS_HFP_SLC_H_ */
diff --git a/cras/src/server/cras_hotword_handler.c b/cras/src/server/cras_hotword_handler.c
deleted file mode 100644
index 055294ab..00000000
--- a/cras/src/server/cras_hotword_handler.c
+++ /dev/null
@@ -1,64 +0,0 @@
-/* Copyright (c) 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_main_message.h"
-#include "cras_observer.h"
-
-struct hotword_triggered_msg {
- struct cras_main_message header;
- int64_t tv_sec;
- int64_t tv_nsec;
-};
-
-/* The following functions are called from audio thread. */
-
-static void init_hotword_triggered_msg(struct hotword_triggered_msg *msg)
-{
- struct timespec now;
-
- clock_gettime(CLOCK_MONOTONIC, &now);
-
- memset(msg, 0, sizeof(*msg));
- msg->header.type = CRAS_MAIN_HOTWORD_TRIGGERED;
- msg->header.length = sizeof(*msg);
- msg->tv_sec = now.tv_sec;
- msg->tv_nsec = now.tv_nsec;
-}
-
-int cras_hotword_send_triggered_msg()
-{
- struct hotword_triggered_msg msg;
- int rc;
-
- init_hotword_triggered_msg(&msg);
-
- rc = cras_main_message_send((struct cras_main_message *)&msg);
- if (rc < 0)
- syslog(LOG_ERR, "Failed to send hotword triggered message!");
-
- return rc;
-}
-
-/* The following functions are called from main thread. */
-
-static void handle_hotword_message(struct cras_main_message *msg, void *arg)
-{
- struct hotword_triggered_msg *hotword_msg =
- (struct hotword_triggered_msg *)msg;
-
- cras_observer_notify_hotword_triggered(hotword_msg->tv_sec,
- hotword_msg->tv_nsec);
-}
-
-int cras_hotword_handler_init()
-{
- cras_main_message_add_handler(CRAS_MAIN_HOTWORD_TRIGGERED,
- handle_hotword_message, NULL);
- return 0;
-}
diff --git a/cras/src/server/cras_hotword_handler.h b/cras/src/server/cras_hotword_handler.h
deleted file mode 100644
index 48fc405f..00000000
--- a/cras/src/server/cras_hotword_handler.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Copyright (c) 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * The hotword handler is used to send a DBus signal when a hotword device is
- * triggered.
- *
- * cras_hotword_send_triggered_msg() is called from audio thread to send a
- * hotword message to main thread which in turn sends the DBus signal.
- *
- * cras_hotword_handler_init() is used to setup message handler in main thread
- * to handle the hotword message from audio thread.
- */
-
-#ifndef CRAS_HOTWORD_HANDLER_H_
-#define CRAS_HOTWORD_HANDLER_H_
-
-/* Send hotword triggered message. */
-int cras_hotword_send_triggered_msg();
-
-/* Initialize hotword handler. */
-int cras_hotword_handler_init();
-
-#endif /* CRAS_HOTWORD_HANDLER_H_ */
diff --git a/cras/src/server/cras_iodev.c b/cras/src/server/cras_iodev.c
deleted file mode 100644
index 651cef71..00000000
--- a/cras/src/server/cras_iodev.c
+++ /dev/null
@@ -1,1719 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <pthread.h>
-#include <stdbool.h>
-#include <stdlib.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <syslog.h>
-#include <time.h>
-
-#include "audio_thread.h"
-#include "audio_thread_log.h"
-#include "buffer_share.h"
-#include "cras_audio_area.h"
-#include "cras_audio_thread_monitor.h"
-#include "cras_device_monitor.h"
-#include "cras_dsp.h"
-#include "cras_dsp_pipeline.h"
-#include "cras_fmt_conv.h"
-#include "cras_iodev.h"
-#include "cras_main_thread_log.h"
-#include "cras_iodev_list.h"
-#include "cras_mix.h"
-#include "cras_ramp.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_util.h"
-#include "dev_stream.h"
-#include "input_data.h"
-#include "utlist.h"
-#include "rate_estimator.h"
-#include "softvol_curve.h"
-
-static const float RAMP_UNMUTE_DURATION_SECS = 0.5;
-static const float RAMP_NEW_STREAM_DURATION_SECS = 0.01;
-static const float RAMP_MUTE_DURATION_SECS = 0.1;
-static const float RAMP_RESUME_MUTE_DURATION_SECS = 1;
-static const float RAMP_SWITCH_MUTE_DURATION_SECS = 0.5;
-static const float RAMP_VOLUME_CHANGE_DURATION_SECS = 0.1;
-
-/*
- * It is the lastest time for the device to wake up when it is in the normal
- * run state. It represents how many remaining frames in the device buffer.
- */
-static const struct timespec dev_normal_run_wake_up_time = {
- 0, 1 * 1000 * 1000 /* 1 msec. */
-};
-
-/*
- * It is the lastest time for the device to wake up when it is in the no stream
- * state. It represents how many remaining frames in the device buffer.
- */
-static const struct timespec dev_no_stream_wake_up_time = {
- 0, 5 * 1000 * 1000 /* 5 msec. */
-};
-
-/*
- * Check issu b/72496547 and commit message for the history of
- * rate estimator tuning.
- */
-static const struct timespec rate_estimation_window_sz = {
- 5, 0 /* 5 sec. */
-};
-static const double rate_estimation_smooth_factor = 0.3f;
-
-static void cras_iodev_alloc_dsp(struct cras_iodev *iodev);
-
-static int default_no_stream_playback(struct cras_iodev *odev)
-{
- int rc;
- unsigned int hw_level, fr_to_write;
- unsigned int target_hw_level = odev->min_cb_level * 2;
- struct timespec hw_tstamp;
-
- /* The default action for no stream playback is to fill zeros. */
- rc = cras_iodev_frames_queued(odev, &hw_tstamp);
- if (rc < 0)
- return rc;
- hw_level = rc;
-
- /* If underrun happened, handle underrun and get hw_level again. */
- if (hw_level == 0) {
- rc = cras_iodev_output_underrun(odev, hw_level, 0);
- if (rc < 0)
- return rc;
-
- rc = cras_iodev_frames_queued(odev, &hw_tstamp);
- if (rc < 0)
- return rc;
- hw_level = rc;
- }
-
- ATLOG(atlog, AUDIO_THREAD_ODEV_DEFAULT_NO_STREAMS, odev->info.idx,
- hw_level, target_hw_level);
-
- fr_to_write = cras_iodev_buffer_avail(odev, hw_level);
- if (hw_level <= target_hw_level) {
- fr_to_write = MIN(target_hw_level - hw_level, fr_to_write);
- return cras_iodev_fill_odev_zeros(odev, fr_to_write);
- }
- return 0;
-}
-
-static int cras_iodev_start(struct cras_iodev *iodev)
-{
- int rc;
- if (!cras_iodev_is_open(iodev))
- return -EPERM;
- if (!iodev->start) {
- syslog(LOG_ERR,
- "start called on device %s not supporting start ops",
- iodev->info.name);
- return -EINVAL;
- }
- rc = iodev->start(iodev);
- if (rc)
- return rc;
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- return 0;
-}
-
-/* Gets the number of frames ready for this device to play.
- * It is the minimum number of available samples in dev_streams.
- */
-static unsigned int dev_playback_frames(struct cras_iodev *odev)
-{
- struct dev_stream *curr;
- int frames = 0;
-
- DL_FOREACH (odev->streams, curr) {
- int dev_frames;
-
- /* Skip stream which hasn't started running yet. */
- if (!dev_stream_is_running(curr))
- continue;
-
- /* If this is a single output dev stream, updates the latest
- * number of frames for playback. */
- if (dev_stream_attached_devs(curr) == 1)
- dev_stream_update_frames(curr);
-
- dev_frames = dev_stream_playback_frames(curr);
- /* Do not handle stream error or end of draining in this
- * function because they should be handled in write_streams. */
- if (dev_frames < 0)
- continue;
- if (!dev_frames) {
- if (cras_rstream_get_is_draining(curr->stream))
- continue;
- else
- return 0;
- }
- if (frames == 0)
- frames = dev_frames;
- else
- frames = MIN(dev_frames, frames);
- }
- return frames;
-}
-
-/* Let device enter/leave no stream playback.
- * Args:
- * iodev[in] - The output device.
- * enable[in] - 1 to enter no stream playback, 0 to leave.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-static int cras_iodev_no_stream_playback_transition(struct cras_iodev *odev,
- int enable)
-{
- int rc;
-
- if (odev->direction != CRAS_STREAM_OUTPUT)
- return -EINVAL;
-
- /* This function is for transition between normal run and
- * no stream run state.
- */
- if ((odev->state != CRAS_IODEV_STATE_NORMAL_RUN) &&
- (odev->state != CRAS_IODEV_STATE_NO_STREAM_RUN))
- return -EINVAL;
-
- if (enable) {
- ATLOG(atlog, AUDIO_THREAD_ODEV_NO_STREAMS, odev->info.idx, 0,
- 0);
- } else {
- ATLOG(atlog, AUDIO_THREAD_ODEV_LEAVE_NO_STREAMS, odev->info.idx,
- 0, 0);
- }
-
- rc = odev->no_stream(odev, enable);
- if (rc < 0)
- return rc;
- if (enable)
- odev->state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- else
- odev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- return 0;
-}
-
-/* Determines if the output device should mute. It considers system mute,
- * system volume, and active node volume on the device. */
-static int output_should_mute(struct cras_iodev *odev)
-{
- /* System mute has highest priority. */
- if (cras_system_get_mute())
- return 1;
-
- /* consider system volume and active node volume. */
- return cras_iodev_is_zero_volume(odev);
-}
-
-int cras_iodev_is_zero_volume(const struct cras_iodev *odev)
-{
- size_t system_volume;
- unsigned int adjusted_node_volume;
-
- system_volume = cras_system_get_volume();
- if (odev->active_node) {
- adjusted_node_volume = cras_iodev_adjust_node_volume(
- odev->active_node, system_volume);
- return (adjusted_node_volume == 0);
- }
- return (system_volume == 0);
-}
-
-/* Output device state transition diagram:
- *
- * ----------------
- * -------------<-----------| S0 Closed |------<-------.
- * | ---------------- |
- * | | iodev_list enables |
- * | | device and adds to |
- * | V audio thread | iodev_list removes
- * | ---------------- | device from
- * | | S1 Open | | audio_thread and
- * | ---------------- | closes device
- * | Device with empty start | |
- * | ops transits into | Sample is ready |
- * | no stream state right V |
- * | after open. ---------------- |
- * | | S2 Normal | |
- * | ---------------- |
- * | | ^ |
- * | There is no stream | | Sample is ready |
- * | V | |
- * | ---------------- |
- * ------------->-----------| S3 No Stream |------->------
- * ----------------
- *
- * Device in open_devs can be in one of S1, S2, S3.
- *
- * cras_iodev_output_event_sample_ready change device state from S1 or S3 into
- * S2.
- */
-static int cras_iodev_output_event_sample_ready(struct cras_iodev *odev)
-{
- if (odev->state == CRAS_IODEV_STATE_OPEN ||
- odev->state == CRAS_IODEV_STATE_NO_STREAM_RUN) {
- /* Starts ramping up if device should not be muted.
- * Both mute and volume are taken into consideration.
- */
- if (odev->ramp && !output_should_mute(odev)) {
- cras_iodev_start_ramp(odev, odev->initial_ramp_request);
- }
- }
-
- if (odev->state == CRAS_IODEV_STATE_OPEN) {
- /* S1 => S2:
- * If device is not started yet, and there is sample ready from
- * stream, fill 1 min_cb_level of zeros first and fill sample
- * from stream later.
- * Starts the device here to finish state transition. */
- cras_iodev_fill_odev_zeros(odev, odev->min_cb_level);
- ATLOG(atlog, AUDIO_THREAD_ODEV_START, odev->info.idx,
- odev->min_cb_level, 0);
- return cras_iodev_start(odev);
- } else if (odev->state == CRAS_IODEV_STATE_NO_STREAM_RUN) {
- /* S3 => S2:
- * Device in no stream state get sample ready. Leave no stream
- * state and transit to normal run state.*/
- return cras_iodev_no_stream_playback_transition(odev, 0);
- } else {
- syslog(LOG_ERR,
- "Device %s in state %d received sample ready event",
- odev->info.name, odev->state);
- return -EINVAL;
- }
- return 0;
-}
-
-/*
- * Exported Interface.
- */
-
-/* Finds the supported sample rate that best suits the requested rate, "rrate".
- * Exact matches have highest priority, then integer multiples, then the default
- * rate for the device. */
-static size_t get_best_rate(struct cras_iodev *iodev, size_t rrate)
-{
- size_t i;
- size_t best;
-
- if (iodev->supported_rates[0] == 0) /* No rates supported */
- return 0;
-
- for (i = 0, best = 0; iodev->supported_rates[i] != 0; i++) {
- if (rrate == iodev->supported_rates[i] && rrate >= 44100)
- return rrate;
- if (best == 0 && (rrate % iodev->supported_rates[i] == 0 ||
- iodev->supported_rates[i] % rrate == 0))
- best = iodev->supported_rates[i];
- }
-
- if (best)
- return best;
- return iodev->supported_rates[0];
-}
-
-/* Finds the best match for the channel count. The following match rules
- * will apply in order and return the value once matched:
- * 1. Match the exact given channel count.
- * 2. Match the preferred channel count.
- * 3. The first channel count in the list.
- */
-static size_t get_best_channel_count(struct cras_iodev *iodev, size_t count)
-{
- static const size_t preferred_channel_count = 2;
- size_t i;
-
- assert(iodev->supported_channel_counts[0] != 0);
-
- for (i = 0; iodev->supported_channel_counts[i] != 0; i++) {
- if (iodev->supported_channel_counts[i] == count)
- return count;
- }
-
- /* If provided count is not supported, search for preferred
- * channel count to which we're good at converting.
- */
- for (i = 0; iodev->supported_channel_counts[i] != 0; i++) {
- if (iodev->supported_channel_counts[i] ==
- preferred_channel_count)
- return preferred_channel_count;
- }
-
- return iodev->supported_channel_counts[0];
-}
-
-/* finds the best match for the current format. If no exact match is
- * found, use the first. */
-static snd_pcm_format_t get_best_pcm_format(struct cras_iodev *iodev,
- snd_pcm_format_t fmt)
-{
- size_t i;
-
- for (i = 0; iodev->supported_formats[i] != 0; i++) {
- if (fmt == iodev->supported_formats[i])
- return fmt;
- }
-
- return iodev->supported_formats[0];
-}
-
-/* Applies the DSP to the samples for the iodev if applicable. */
-static int apply_dsp(struct cras_iodev *iodev, uint8_t *buf, size_t frames)
-{
- struct cras_dsp_context *ctx;
- struct pipeline *pipeline;
- int rc;
-
- ctx = iodev->dsp_context;
- if (!ctx)
- return 0;
-
- pipeline = cras_dsp_get_pipeline(ctx);
- if (!pipeline)
- return 0;
-
- rc = cras_dsp_pipeline_apply(pipeline, buf, iodev->format->format,
- frames);
-
- cras_dsp_put_pipeline(ctx);
- return rc;
-}
-
-static void cras_iodev_free_dsp(struct cras_iodev *iodev)
-{
- if (iodev->dsp_context) {
- cras_dsp_context_free(iodev->dsp_context);
- iodev->dsp_context = NULL;
- }
-}
-
-/* Modifies the number of channels in device format to the one that will be
- * presented to the device after any channel changes from the DSP. */
-static inline void adjust_dev_channel_for_dsp(const struct cras_iodev *iodev)
-{
- struct cras_dsp_context *ctx = iodev->dsp_context;
-
- if (!ctx || !cras_dsp_get_pipeline(ctx))
- return;
-
- if (iodev->direction == CRAS_STREAM_OUTPUT)
- iodev->format->num_channels = cras_dsp_num_output_channels(ctx);
- else
- iodev->format->num_channels = cras_dsp_num_input_channels(ctx);
-
- cras_dsp_put_pipeline(ctx);
-}
-
-/* Updates channel layout based on the number of channels set by a
- * client stream. Set a default value to format if the update call
- * fails.
- */
-static void update_channel_layout(struct cras_iodev *iodev)
-{
- int rc;
-
- if (iodev->update_channel_layout == NULL)
- return;
-
- rc = iodev->update_channel_layout(iodev);
- if (rc < 0)
- cras_audio_format_set_default_channel_layout(iodev->format);
-}
-
-/*
- * For the specified format, removes any channels from the channel layout that
- * are higher than the supported number of channels. Should be used when the
- * number of channels of the format been reduced.
- */
-static void trim_channel_layout(struct cras_audio_format *fmt)
-{
- int i;
- for (i = 0; i < CRAS_CH_MAX; i++)
- if (fmt->channel_layout[i] >= fmt->num_channels)
- fmt->channel_layout[i] = -1;
-}
-
-int cras_iodev_set_format(struct cras_iodev *iodev,
- const struct cras_audio_format *fmt)
-{
- size_t actual_rate, actual_num_channels;
- snd_pcm_format_t actual_format;
- int rc;
-
- /* Update supported formats on iodev before negotiating the final value
- * with what stream requested.
- */
- if (iodev->update_supported_formats) {
- rc = iodev->update_supported_formats(iodev);
- if (rc) {
- syslog(LOG_ERR, "Failed to update formats");
- return rc;
- }
- }
-
- /* If this device isn't already using a format, try to match the one
- * requested in "fmt". */
- if (iodev->format == NULL) {
- iodev->format = malloc(sizeof(struct cras_audio_format));
- if (!iodev->format)
- return -ENOMEM;
- *iodev->format = *fmt;
-
- /* Finds the actual rate of device before allocating DSP
- * because DSP needs to use the rate of device, not rate of
- * stream. */
- actual_rate = get_best_rate(iodev, fmt->frame_rate);
- iodev->format->frame_rate = actual_rate;
-
- cras_iodev_alloc_dsp(iodev);
- cras_iodev_update_dsp(iodev);
- if (iodev->dsp_context)
- adjust_dev_channel_for_dsp(iodev);
-
- actual_num_channels = get_best_channel_count(
- iodev, iodev->format->num_channels);
- actual_format = get_best_pcm_format(iodev, fmt->format);
- if (actual_rate == 0 || actual_num_channels == 0 ||
- actual_format == 0) {
- /* No compatible frame rate found. */
- rc = -EINVAL;
- goto error;
- }
- iodev->format->format = actual_format;
- if (iodev->format->num_channels != actual_num_channels) {
- /* If the DSP for this device doesn't match, drop it. */
- iodev->format->num_channels = actual_num_channels;
- trim_channel_layout(iodev->format);
- cras_iodev_free_dsp(iodev);
- }
-
- update_channel_layout(iodev);
-
- if (!iodev->rate_est)
- iodev->rate_est = rate_estimator_create(
- actual_rate, &rate_estimation_window_sz,
- rate_estimation_smooth_factor);
- else
- rate_estimator_reset_rate(iodev->rate_est, actual_rate);
- }
-
- return 0;
-
-error:
- free(iodev->format);
- iodev->format = NULL;
- return rc;
-}
-
-/*
- * Configures the external dsp module and adds it to the existing dsp pipeline.
- */
-static void add_ext_dsp_module_to_pipeline(struct cras_iodev *iodev)
-{
- struct pipeline *pipeline;
-
- pipeline = iodev->dsp_context ?
- cras_dsp_get_pipeline(iodev->dsp_context) :
- NULL;
-
- if (!pipeline) {
- cras_iodev_alloc_dsp(iodev);
- cras_dsp_load_mock_pipeline(iodev->dsp_context,
- iodev->format->num_channels);
- pipeline = cras_dsp_get_pipeline(iodev->dsp_context);
- }
- /* dsp_context mutex locked. Now it's safe to modify dsp
- * pipeline resources. */
-
- if (iodev->ext_dsp_module)
- iodev->ext_dsp_module->configure(iodev->ext_dsp_module,
- iodev->buffer_size,
- iodev->format->num_channels,
- iodev->format->frame_rate);
-
- cras_dsp_pipeline_set_sink_ext_module(pipeline, iodev->ext_dsp_module);
-
- /* Unlock dsp_context mutex. */
- cras_dsp_put_pipeline(iodev->dsp_context);
-}
-
-/*
- * Releases the ext_dsp_module if it ever added to iodev's dsp pipeline.
- */
-static void release_ext_dsp_module_from_pipeline(struct cras_iodev *iodev)
-{
- struct pipeline *pipeline;
-
- if (iodev->dsp_context == NULL)
- return;
-
- pipeline = cras_dsp_get_pipeline(iodev->dsp_context);
- if (pipeline == NULL)
- return;
- /* dsp_context mutex locked. */
-
- cras_dsp_pipeline_set_sink_ext_module(pipeline, NULL);
-
- /* Unlock dsp_context mutex. */
- cras_dsp_put_pipeline(iodev->dsp_context);
-}
-
-void cras_iodev_set_ext_dsp_module(struct cras_iodev *iodev,
- struct ext_dsp_module *ext)
-{
- iodev->ext_dsp_module = ext;
-
- if (!cras_iodev_is_open(iodev))
- return;
-
- if (iodev->ext_dsp_module)
- add_ext_dsp_module_to_pipeline(iodev);
- else
- release_ext_dsp_module_from_pipeline(iodev);
-}
-
-void cras_iodev_update_dsp(struct cras_iodev *iodev)
-{
- char swap_lr_disabled = 1;
-
- if (!iodev->dsp_context)
- return;
-
- cras_dsp_set_variable_string(iodev->dsp_context, "dsp_name",
- iodev->dsp_name ?: "");
-
- if (iodev->active_node && iodev->active_node->left_right_swapped)
- swap_lr_disabled = 0;
-
- cras_dsp_set_variable_boolean(iodev->dsp_context, "swap_lr_disabled",
- swap_lr_disabled);
-
- cras_dsp_load_pipeline(iodev->dsp_context);
-}
-
-int cras_iodev_dsp_set_swap_mode_for_node(struct cras_iodev *iodev,
- struct cras_ionode *node, int enable)
-{
- if (node->left_right_swapped == enable)
- return 0;
-
- /* Sets left_right_swapped property on the node. It will be used
- * when cras_iodev_update_dsp is called. */
- node->left_right_swapped = enable;
-
- /* Possibly updates dsp if the node is active on the device and there
- * is dsp context. If dsp context is not created yet,
- * cras_iodev_update_dsp returns right away. */
- if (iodev->active_node == node)
- cras_iodev_update_dsp(iodev);
- return 0;
-}
-
-void cras_iodev_free_format(struct cras_iodev *iodev)
-{
- free(iodev->format);
- iodev->format = NULL;
-}
-
-void cras_iodev_init_audio_area(struct cras_iodev *iodev, int num_channels)
-{
- if (iodev->area)
- cras_iodev_free_audio_area(iodev);
-
- iodev->area = cras_audio_area_create(num_channels);
- cras_audio_area_config_channels(iodev->area, iodev->format);
-}
-
-void cras_iodev_free_audio_area(struct cras_iodev *iodev)
-{
- if (!iodev->area)
- return;
-
- cras_audio_area_destroy(iodev->area);
- iodev->area = NULL;
-}
-
-void cras_iodev_free_resources(struct cras_iodev *iodev)
-{
- cras_iodev_free_dsp(iodev);
- rate_estimator_destroy(iodev->rate_est);
- if (iodev->ramp)
- cras_ramp_destroy(iodev->ramp);
-}
-
-static void cras_iodev_alloc_dsp(struct cras_iodev *iodev)
-{
- const char *purpose;
-
- if (iodev->direction == CRAS_STREAM_OUTPUT)
- purpose = "playback";
- else
- purpose = "capture";
-
- cras_iodev_free_dsp(iodev);
- iodev->dsp_context =
- cras_dsp_context_new(iodev->format->frame_rate, purpose);
-}
-
-void cras_iodev_fill_time_from_frames(size_t frames, size_t frame_rate,
- struct timespec *ts)
-{
- uint64_t to_play_usec;
-
- ts->tv_sec = 0;
- /* adjust sleep time to target our callback threshold */
- to_play_usec = (uint64_t)frames * 1000000L / (uint64_t)frame_rate;
-
- while (to_play_usec > 1000000) {
- ts->tv_sec++;
- to_play_usec -= 1000000;
- }
- ts->tv_nsec = to_play_usec * 1000;
-}
-
-/* This is called when a node is plugged/unplugged */
-void cras_iodev_set_node_plugged(struct cras_ionode *node, int plugged)
-{
- if (node->plugged == plugged)
- return;
- node->plugged = plugged;
- MAINLOG(main_log, MAIN_THREAD_NODE_PLUGGED, node->dev->info.idx,
- plugged, 0);
- if (plugged) {
- gettimeofday(&node->plugged_time, NULL);
- } else if (node == node->dev->active_node) {
- /*
- * Remove normal and pinned streams, when node unplugged.
- * TODO(hychao): clean this up, per crbug.com/1006646
- */
- cras_iodev_list_disable_dev(node->dev, true);
- }
- cras_iodev_list_notify_nodes_changed();
-}
-
-void cras_iodev_add_node(struct cras_iodev *iodev, struct cras_ionode *node)
-{
- DL_APPEND(iodev->nodes, node);
- cras_iodev_list_notify_nodes_changed();
-}
-
-void cras_iodev_rm_node(struct cras_iodev *iodev, struct cras_ionode *node)
-{
- DL_DELETE(iodev->nodes, node);
- cras_iodev_list_notify_nodes_changed();
-}
-
-void cras_iodev_set_active_node(struct cras_iodev *iodev,
- struct cras_ionode *node)
-{
- iodev->active_node = node;
- cras_iodev_list_notify_active_node_changed(iodev->direction);
-}
-
-bool cras_iodev_is_aec_use_case(const struct cras_ionode *node)
-{
- if ((node->type == CRAS_NODE_TYPE_INTERNAL_SPEAKER) ||
- (node->type == CRAS_NODE_TYPE_ECHO_REFERENCE))
- return true;
-
- if (node->type == CRAS_NODE_TYPE_MIC)
- return (node->position == NODE_POSITION_INTERNAL) ||
- (node->position == NODE_POSITION_FRONT);
-
- return false;
-}
-
-bool cras_iodev_is_on_internal_card(const struct cras_ionode *node)
-{
- if (node->type == CRAS_NODE_TYPE_INTERNAL_SPEAKER)
- return true;
- if (node->type == CRAS_NODE_TYPE_HEADPHONE)
- return true;
- if (node->type == CRAS_NODE_TYPE_MIC)
- return true;
- return false;
-}
-
-float cras_iodev_get_software_volume_scaler(struct cras_iodev *iodev)
-{
- unsigned int volume;
-
- volume = cras_iodev_adjust_active_node_volume(iodev,
- cras_system_get_volume());
-
- if (iodev->active_node && iodev->active_node->softvol_scalers)
- return iodev->active_node->softvol_scalers[volume];
- return softvol_get_scaler(volume);
-}
-
-float cras_iodev_get_software_gain_scaler(const struct cras_iodev *iodev)
-{
- if (cras_iodev_software_volume_needed(iodev))
- return convert_softvol_scaler_from_dB(
- iodev->active_node->capture_gain);
- return 1.0f;
-}
-
-int cras_iodev_get_valid_frames(struct cras_iodev *odev,
- struct timespec *hw_tstamp)
-{
- int rc;
-
- if (odev->direction != CRAS_STREAM_OUTPUT)
- return -EINVAL;
-
- if (odev->get_valid_frames) {
- rc = odev->get_valid_frames(odev, hw_tstamp);
- if (rc < 0)
- return rc;
-
- if (rc < odev->min_buffer_level)
- return 0;
-
- return rc - odev->min_buffer_level;
- } else {
- return cras_iodev_frames_queued(odev, hw_tstamp);
- }
-}
-
-int cras_iodev_add_stream(struct cras_iodev *iodev, struct dev_stream *stream)
-{
- /*
- * For input stream, start stream right after adding stream.
- * For output stream, start stream after its first fetch such that it does not
- * block other existing streams.
- */
- DL_APPEND(iodev->streams, stream);
- if (!iodev->buf_state)
- iodev->buf_state = buffer_share_create(iodev->buffer_size);
- if (stream->stream->direction == CRAS_STREAM_INPUT)
- cras_iodev_start_stream(iodev, stream);
- return 0;
-}
-
-void cras_iodev_start_stream(struct cras_iodev *iodev,
- struct dev_stream *stream)
-{
- unsigned int cb_threshold = dev_stream_cb_threshold(stream);
-
- if (dev_stream_is_running(stream))
- return;
- /*
- * TRIGGER_ONLY streams do not want to receive data, so do not add them
- * to buffer_share, otherwise they'll affect other streams to receive.
- */
- if (!(stream->stream->flags & TRIGGER_ONLY))
- buffer_share_add_id(iodev->buf_state, stream->stream->stream_id,
- NULL);
- iodev->min_cb_level = MIN(iodev->min_cb_level, cb_threshold);
- iodev->max_cb_level = MAX(iodev->max_cb_level, cb_threshold);
- iodev->largest_cb_level = MAX(iodev->largest_cb_level, cb_threshold);
- dev_stream_set_running(stream);
-}
-
-struct dev_stream *cras_iodev_rm_stream(struct cras_iodev *iodev,
- const struct cras_rstream *rstream)
-{
- struct dev_stream *out;
- struct dev_stream *ret = NULL;
- unsigned int cb_threshold;
- struct timespec earliest_next_cb_ts;
- int set_earliest = 0;
-
- iodev->min_cb_level = iodev->buffer_size / 2;
- iodev->max_cb_level = 0;
- DL_FOREACH (iodev->streams, out) {
- if (out->stream == rstream) {
- buffer_share_rm_id(iodev->buf_state,
- rstream->stream_id);
- ret = out;
- DL_DELETE(iodev->streams, out);
- continue;
- }
- if (!dev_stream_is_running(out))
- continue;
- cb_threshold = dev_stream_cb_threshold(out);
- iodev->min_cb_level = MIN(iodev->min_cb_level, cb_threshold);
- iodev->max_cb_level = MAX(iodev->max_cb_level, cb_threshold);
- if (!set_earliest) {
- set_earliest = 1;
- earliest_next_cb_ts = out->stream->next_cb_ts;
- }
- if (timespec_after(&earliest_next_cb_ts,
- &out->stream->next_cb_ts))
- earliest_next_cb_ts = out->stream->next_cb_ts;
- }
-
- if (!iodev->streams) {
- buffer_share_destroy(iodev->buf_state);
- iodev->buf_state = NULL;
- iodev->min_cb_level = iodev->buffer_size / 2;
- /* Let output device transit into no stream state if it's
- * in normal run state now. Leave input device in normal
- * run state. */
- if ((iodev->direction == CRAS_STREAM_OUTPUT) &&
- (iodev->state == CRAS_IODEV_STATE_NORMAL_RUN))
- cras_iodev_no_stream_playback_transition(iodev, 1);
- }
-
- if (!set_earliest)
- return ret;
-
- DL_FOREACH (iodev->streams, out) {
- if (!dev_stream_is_running(out))
- out->stream->next_cb_ts = earliest_next_cb_ts;
- }
-
- return ret;
-}
-
-unsigned int cras_iodev_stream_offset(struct cras_iodev *iodev,
- struct dev_stream *stream)
-{
- return buffer_share_id_offset(iodev->buf_state,
- stream->stream->stream_id);
-}
-
-void cras_iodev_stream_written(struct cras_iodev *iodev,
- struct dev_stream *stream, unsigned int nwritten)
-{
- buffer_share_offset_update(iodev->buf_state, stream->stream->stream_id,
- nwritten);
-}
-
-unsigned int cras_iodev_all_streams_written(struct cras_iodev *iodev)
-{
- if (!iodev->buf_state)
- return 0;
- return buffer_share_get_new_write_point(iodev->buf_state);
-}
-
-unsigned int cras_iodev_max_stream_offset(const struct cras_iodev *iodev)
-{
- unsigned int max = 0;
- struct dev_stream *curr;
-
- DL_FOREACH (iodev->streams, curr) {
- /* Skip stream which hasn't started running yet. */
- if (!dev_stream_is_running(curr))
- continue;
-
- max = MAX(max, buffer_share_id_offset(iodev->buf_state,
- curr->stream->stream_id));
- }
-
- return max;
-}
-
-int cras_iodev_open(struct cras_iodev *iodev, unsigned int cb_level,
- const struct cras_audio_format *fmt)
-{
- struct cras_loopback *loopback;
- int rc;
-
- if (iodev->pre_open_iodev_hook)
- iodev->pre_open_iodev_hook();
-
- DL_FOREACH (iodev->loopbacks, loopback) {
- if (loopback->hook_control)
- loopback->hook_control(true, loopback->cb_data);
- }
-
- if (iodev->open_dev) {
- rc = iodev->open_dev(iodev);
- if (rc)
- return rc;
- }
-
- if (iodev->format == NULL) {
- rc = cras_iodev_set_format(iodev, fmt);
- if (rc) {
- iodev->close_dev(iodev);
- return rc;
- }
- }
-
- rc = iodev->configure_dev(iodev);
- if (rc < 0) {
- iodev->close_dev(iodev);
- return rc;
- }
-
- /*
- * Convert cb_level from input format to device format
- */
- cb_level = cras_frames_at_rate(fmt->frame_rate, cb_level,
- iodev->format->frame_rate);
- /* Make sure the min_cb_level doesn't get too large. */
- iodev->min_cb_level = MIN(iodev->buffer_size / 2, cb_level);
- iodev->max_cb_level = 0;
- iodev->largest_cb_level = 0;
- iodev->num_underruns = 0;
-
- iodev->reset_request_pending = 0;
- iodev->state = CRAS_IODEV_STATE_OPEN;
- iodev->highest_hw_level = 0;
- iodev->input_dsp_offset = 0;
-
- ewma_power_init(&iodev->ewma, iodev->format->frame_rate);
-
- if (iodev->direction == CRAS_STREAM_OUTPUT) {
- /* If device supports start ops, device can be in open state.
- * Otherwise, device starts running right after opening. */
- if (iodev->start) {
- iodev->state = CRAS_IODEV_STATE_OPEN;
- } else {
- iodev->state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- cras_iodev_fill_odev_zeros(iodev, iodev->min_cb_level);
- }
- } else {
- iodev->input_data = input_data_create(iodev);
- /* If this is the echo reference dev, its ext_dsp_module will
- * be set to APM reverse module. Do not override it to its
- * input data. */
- if (iodev->ext_dsp_module == NULL)
- iodev->ext_dsp_module = &iodev->input_data->ext;
-
- /* Input device starts running right after opening.
- * No stream state is only for output device. Input device
- * should be in normal run state. */
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- /* Initialize the input_streaming flag to zero.*/
- iodev->input_streaming = 0;
-
- /*
- * The device specific gain scaler to be used in audio thread.
- * It's expected to stick to 1.0f if device has hardware gain
- * control. For alsa device, this gain value will be configured
- * based on UCM labels IntrinsicSensitivity.
- */
- iodev->software_gain_scaler =
- cras_iodev_get_software_gain_scaler(iodev);
- }
-
- add_ext_dsp_module_to_pipeline(iodev);
- clock_gettime(CLOCK_MONOTONIC_RAW, &iodev->open_ts);
-
- return 0;
-}
-
-enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev *iodev)
-{
- return iodev->state;
-}
-
-int cras_iodev_close(struct cras_iodev *iodev)
-{
- struct cras_loopback *loopback;
- int rc;
-
- if (!cras_iodev_is_open(iodev))
- return 0;
-
- if (iodev->active_node) {
- cras_server_metrics_device_runtime(iodev);
- cras_server_metrics_device_gain(iodev);
- cras_server_metrics_device_volume(iodev);
- }
-
- if (iodev->input_data) {
- if (iodev->ext_dsp_module == &iodev->input_data->ext)
- iodev->ext_dsp_module = NULL;
- input_data_destroy(&iodev->input_data);
- }
-
- rc = iodev->close_dev(iodev);
- if (rc)
- syslog(LOG_ERR, "Error closing dev %s, rc %d", iodev->info.name,
- rc);
- iodev->state = CRAS_IODEV_STATE_CLOSE;
- if (iodev->ramp)
- cras_ramp_reset(iodev->ramp);
-
- if (iodev->post_close_iodev_hook)
- iodev->post_close_iodev_hook();
-
- DL_FOREACH (iodev->loopbacks, loopback) {
- if (loopback->hook_control)
- loopback->hook_control(false, loopback->cb_data);
- }
-
- return 0;
-}
-
-int cras_iodev_put_input_buffer(struct cras_iodev *iodev)
-{
- unsigned int min_frames;
- unsigned int dsp_frames;
- struct input_data *data = iodev->input_data;
- int rc;
-
- if (iodev->streams)
- min_frames = buffer_share_get_new_write_point(iodev->buf_state);
- else
- min_frames = data->area->frames;
-
- // Update the max number of frames has applied input dsp.
- dsp_frames = MAX(iodev->input_frames_read, iodev->input_dsp_offset);
- iodev->input_dsp_offset = dsp_frames - min_frames;
-
- input_data_set_all_streams_read(data, min_frames);
- rate_estimator_add_frames(iodev->rate_est, -min_frames);
- rc = iodev->put_buffer(iodev, min_frames);
- if (rc < 0)
- return rc;
- return min_frames;
-}
-
-int cras_iodev_put_output_buffer(struct cras_iodev *iodev, uint8_t *frames,
- unsigned int nframes, int *is_non_empty,
- struct cras_fmt_conv *remix_converter)
-{
- const struct cras_audio_format *fmt = iodev->format;
- struct cras_ramp_action ramp_action = {
- .type = CRAS_RAMP_ACTION_NONE,
- .scaler = 0.0f,
- .increment = 0.0f,
- .target = 1.0f,
- };
- float software_volume_scaler = 1.0;
- int software_volume_needed = cras_iodev_software_volume_needed(iodev);
- int rc;
- struct cras_loopback *loopback;
-
- /* Calculate whether the final output was non-empty, if requested. */
- if (is_non_empty) {
- const size_t bytes = nframes * cras_get_format_bytes(fmt);
-
- /*
- * Speed up checking frames are all zeros using memcmp.
- * frames contains all zeros if both conditions are met:
- * - frames[0] is 0.
- * - frames[i] == frames[i+1] for i in [0, 1, ..., bytes - 2].
- */
- *is_non_empty = bytes ? (*frames || memcmp(frames, frames + 1,
- bytes - 1)) :
- 0;
- }
-
- DL_FOREACH (iodev->loopbacks, loopback) {
- if (loopback->type == LOOPBACK_POST_MIX_PRE_DSP)
- loopback->hook_data(frames, nframes, iodev->format,
- loopback->cb_data);
- }
-
- ewma_power_calculate(&iodev->ewma, (int16_t *)frames,
- iodev->format->num_channels, nframes);
-
- rc = apply_dsp(iodev, frames, nframes);
- if (rc)
- return rc;
-
- DL_FOREACH (iodev->loopbacks, loopback) {
- if (loopback->type == LOOPBACK_POST_DSP)
- loopback->hook_data(frames, nframes, iodev->format,
- loopback->cb_data);
- }
-
- if (iodev->ramp) {
- ramp_action = cras_ramp_get_current_action(iodev->ramp);
- }
-
- /* Mute samples if adjusted volume is 0 or system is muted, plus
- * that this device is not ramping. */
- if (output_should_mute(iodev) &&
- ramp_action.type != CRAS_RAMP_ACTION_PARTIAL) {
- const unsigned int frame_bytes = cras_get_format_bytes(fmt);
- cras_mix_mute_buffer(frames, frame_bytes, nframes);
- }
-
- /* Compute scaler for software volume if needed. */
- if (software_volume_needed) {
- software_volume_scaler =
- cras_iodev_get_software_volume_scaler(iodev);
- }
-
- if (ramp_action.type == CRAS_RAMP_ACTION_PARTIAL) {
- /* Scale with increment for ramp and possibly
- * software volume using cras_scale_buffer_increment.*/
- float starting_scaler = ramp_action.scaler;
- float increment = ramp_action.increment;
- float target = ramp_action.target;
-
- if (software_volume_needed) {
- starting_scaler *= software_volume_scaler;
- increment *= software_volume_scaler;
- target *= software_volume_scaler;
- }
-
- cras_scale_buffer_increment(fmt->format, frames, nframes,
- starting_scaler, increment, target,
- fmt->num_channels);
- cras_ramp_update_ramped_frames(iodev->ramp, nframes);
- } else if (!output_should_mute(iodev) && software_volume_needed) {
- /* Just scale for software volume using
- * cras_scale_buffer. */
- unsigned int nsamples = nframes * fmt->num_channels;
- cras_scale_buffer(fmt->format, frames, nsamples,
- software_volume_scaler);
- }
-
- if (remix_converter)
- cras_channel_remix_convert(remix_converter, iodev->format,
- frames, nframes);
- if (iodev->rate_est)
- rate_estimator_add_frames(iodev->rate_est, nframes);
-
- return iodev->put_buffer(iodev, nframes);
-}
-
-int cras_iodev_get_input_buffer(struct cras_iodev *iodev, unsigned int *frames)
-{
- const unsigned int frame_bytes = cras_get_format_bytes(iodev->format);
- struct input_data *data = iodev->input_data;
- int rc;
- uint8_t *hw_buffer;
- unsigned frame_requested = *frames;
-
- rc = iodev->get_buffer(iodev, &data->area, frames);
- if (rc < 0 || *frames == 0)
- return rc;
-
- if (*frames > frame_requested) {
- syslog(LOG_ERR,
- "frames returned from get_buffer is greater than "
- "requested: %u > %u",
- *frames, frame_requested);
- return -EINVAL;
- }
-
- iodev->input_frames_read = *frames;
-
- /* TODO(hychao) - This assumes interleaved audio. */
- hw_buffer = data->area->channels[0].buf;
-
- /*
- * input_dsp_offset records the position where input dsp has applied to
- * last time. It's possible the requested |frames| count is smaller
- * than the tracked offset. That could happen when client stream uses
- * small buffer size and runs APM processing (which requires 10 ms
- * equivalent of data to process).
- * Only apply input dsp to the part of read buffer beyond where we've
- * already applied dsp.
- */
- if (*frames > iodev->input_dsp_offset) {
- rc = apply_dsp(iodev,
- hw_buffer +
- iodev->input_dsp_offset * frame_bytes,
- *frames - iodev->input_dsp_offset);
- if (rc)
- return rc;
- ewma_power_calculate_area(
- &iodev->ewma,
- (int16_t *)(hw_buffer +
- iodev->input_dsp_offset * frame_bytes),
- data->area, *frames - iodev->input_dsp_offset);
- }
-
- if (cras_system_get_capture_mute())
- cras_mix_mute_buffer(hw_buffer, frame_bytes, *frames);
-
- return rc;
-}
-
-int cras_iodev_get_output_buffer(struct cras_iodev *iodev,
- struct cras_audio_area **area,
- unsigned *frames)
-{
- int rc;
- unsigned frame_requested = *frames;
-
- rc = iodev->get_buffer(iodev, area, frames);
- if (*frames > frame_requested) {
- syslog(LOG_ERR,
- "frames returned from get_buffer is greater than "
- "requested: %u > %u",
- *frames, frame_requested);
- return -EINVAL;
- }
- return rc;
-}
-
-int cras_iodev_update_rate(struct cras_iodev *iodev, unsigned int level,
- struct timespec *level_tstamp)
-{
- /* If output underruns, reset to avoid incorrect estimated rate. */
- if ((iodev->direction == CRAS_STREAM_OUTPUT) && !level)
- rate_estimator_reset_rate(iodev->rate_est,
- iodev->format->frame_rate);
-
- return rate_estimator_check(iodev->rate_est, level, level_tstamp);
-}
-
-int cras_iodev_reset_rate_estimator(const struct cras_iodev *iodev)
-{
- rate_estimator_reset_rate(iodev->rate_est, iodev->format->frame_rate);
- return 0;
-}
-
-double cras_iodev_get_est_rate_ratio(const struct cras_iodev *iodev)
-{
- return rate_estimator_get_rate(iodev->rate_est) /
- iodev->format->frame_rate;
-}
-
-int cras_iodev_get_dsp_delay(const struct cras_iodev *iodev)
-{
- struct cras_dsp_context *ctx;
- struct pipeline *pipeline;
- int delay;
-
- ctx = iodev->dsp_context;
- if (!ctx)
- return 0;
-
- pipeline = cras_dsp_get_pipeline(ctx);
- if (!pipeline)
- return 0;
-
- delay = cras_dsp_pipeline_get_delay(pipeline);
-
- cras_dsp_put_pipeline(ctx);
- return delay;
-}
-
-int cras_iodev_frames_queued(struct cras_iodev *iodev,
- struct timespec *hw_tstamp)
-{
- int rc;
-
- rc = iodev->frames_queued(iodev, hw_tstamp);
- if (rc < 0)
- return rc;
-
- if (iodev->direction == CRAS_STREAM_INPUT) {
- if (rc > 0)
- iodev->input_streaming = 1;
- return rc;
- }
-
- if (rc < iodev->min_buffer_level)
- return 0;
-
- return rc - iodev->min_buffer_level;
-}
-
-int cras_iodev_buffer_avail(struct cras_iodev *iodev, unsigned hw_level)
-{
- if (iodev->direction == CRAS_STREAM_INPUT)
- return hw_level;
-
- if (hw_level + iodev->min_buffer_level > iodev->buffer_size)
- return 0;
-
- return iodev->buffer_size - iodev->min_buffer_level - hw_level;
-}
-
-int cras_iodev_fill_odev_zeros(struct cras_iodev *odev, unsigned int frames)
-{
- struct cras_audio_area *area = NULL;
- unsigned int frame_bytes, frames_written;
- int rc;
- uint8_t *buf;
-
- if (odev->direction != CRAS_STREAM_OUTPUT)
- return -EINVAL;
-
- ATLOG(atlog, AUDIO_THREAD_FILL_ODEV_ZEROS, odev->info.idx, frames, 0);
-
- frame_bytes = cras_get_format_bytes(odev->format);
- while (frames > 0) {
- frames_written = frames;
- rc = cras_iodev_get_output_buffer(odev, &area, &frames_written);
- if (rc < 0) {
- syslog(LOG_ERR, "fill zeros fail: %d", rc);
- return rc;
- }
-
- /* This assumes consecutive channel areas. */
- buf = area->channels[0].buf;
- memset(buf, 0, (size_t)frames_written * (size_t)frame_bytes);
- cras_iodev_put_output_buffer(odev, buf, frames_written, NULL,
- NULL);
- frames -= frames_written;
- }
-
- return 0;
-}
-
-int cras_iodev_output_underrun(struct cras_iodev *odev, unsigned int hw_level,
- unsigned int frames_written)
-{
- ATLOG(atlog, AUDIO_THREAD_UNDERRUN, odev->info.idx, hw_level,
- frames_written);
- odev->num_underruns++;
- cras_audio_thread_event_underrun();
- if (odev->output_underrun)
- return odev->output_underrun(odev);
- else
- return cras_iodev_fill_odev_zeros(odev, odev->min_cb_level);
-}
-
-int cras_iodev_odev_should_wake(const struct cras_iodev *odev)
-{
- if (odev->direction != CRAS_STREAM_OUTPUT)
- return 0;
-
- if (odev->is_free_running && odev->is_free_running(odev))
- return 0;
-
- /* Do not wake up for device not started yet. */
- return (odev->state == CRAS_IODEV_STATE_NORMAL_RUN ||
- odev->state == CRAS_IODEV_STATE_NO_STREAM_RUN);
-}
-
-unsigned int
-cras_iodev_default_frames_to_play_in_sleep(struct cras_iodev *odev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp)
-{
- int rc = cras_iodev_frames_queued(odev, hw_tstamp);
- unsigned int level = (rc < 0) ? 0 : rc;
- unsigned int wakeup_frames;
- *hw_level = level;
-
- if (odev->streams) {
- /*
- * We have two cases in this scope. The first one is if there are frames
- * waiting to be played, audio thread will wake up when hw_level drops
- * to min_cb_level. This situation only happens when hardware buffer is
- * smaller than the client stream buffer. The second one is waking up
- * when hw_level drops to dev_normal_run_wake_up_time. It is a default
- * behavior. This wake up time is the bottom line to avoid underrun.
- * Normally, the audio thread does not wake up at that time because the
- * streams should wake it up before then.
- */
- if (*hw_level > odev->min_cb_level && dev_playback_frames(odev))
- return *hw_level - odev->min_cb_level;
-
- wakeup_frames = cras_time_to_frames(
- &dev_normal_run_wake_up_time, odev->format->frame_rate);
- if (level > wakeup_frames)
- return level - wakeup_frames;
- else
- return level;
- }
-
- /*
- * When this device has no stream, schedule audio thread to wake up when
- * hw_level drops to dev_no_stream_wake_up_time so audio thread can
- * fill zeros to it. We also need to consider min_cb_level in order to avoid
- * busyloop when device buffer size is smaller than wake up time.
- */
- wakeup_frames = cras_time_to_frames(&dev_no_stream_wake_up_time,
- odev->format->frame_rate);
- if (level > MIN(odev->min_cb_level, wakeup_frames))
- return level - MIN(odev->min_cb_level, wakeup_frames);
- else
- return 0;
-}
-
-unsigned int cras_iodev_frames_to_play_in_sleep(struct cras_iodev *odev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp)
-{
- /* Use odev's own implementation, if not supported then fall back
- * to default behavior below. */
- if (odev->frames_to_play_in_sleep)
- return odev->frames_to_play_in_sleep(odev, hw_level, hw_tstamp);
- else
- return cras_iodev_default_frames_to_play_in_sleep(
- odev, hw_level, hw_tstamp);
-}
-
-int cras_iodev_default_no_stream_playback(struct cras_iodev *odev, int enable)
-{
- if (enable)
- return default_no_stream_playback(odev);
- return 0;
-}
-
-int cras_iodev_prepare_output_before_write_samples(struct cras_iodev *odev)
-{
- int may_enter_normal_run;
- enum CRAS_IODEV_STATE state;
-
- if (odev->direction != CRAS_STREAM_OUTPUT)
- return -EINVAL;
-
- state = cras_iodev_state(odev);
-
- may_enter_normal_run = (state == CRAS_IODEV_STATE_OPEN ||
- state == CRAS_IODEV_STATE_NO_STREAM_RUN);
-
- if (may_enter_normal_run && dev_playback_frames(odev))
- return cras_iodev_output_event_sample_ready(odev);
-
- /* no_stream ops is called every cycle in no_stream state. */
- if (state == CRAS_IODEV_STATE_NO_STREAM_RUN)
- return odev->no_stream(odev, 1);
-
- return 0;
-}
-
-unsigned int cras_iodev_get_num_underruns(const struct cras_iodev *iodev)
-{
- return iodev->num_underruns;
-}
-
-unsigned int cras_iodev_get_num_severe_underruns(const struct cras_iodev *iodev)
-{
- if (iodev->get_num_severe_underruns)
- return iodev->get_num_severe_underruns(iodev);
- return 0;
-}
-
-int cras_iodev_reset_request(struct cras_iodev *iodev)
-{
- /* Ignore requests if there is a pending request.
- * This function sends the request from audio thread to main
- * thread when audio thread finds a device is in a bad state
- * e.g. severe underrun. Before main thread receives the
- * request and resets device, audio thread might try to send
- * multiple requests because it finds device is still in bad
- * state. We should ignore requests in this cause. Otherwise,
- * main thread will reset device multiple times.
- * The flag is cleared in cras_iodev_open.
- * */
- if (iodev->reset_request_pending)
- return 0;
- iodev->reset_request_pending = 1;
- return cras_device_monitor_reset_device(iodev->info.idx);
-}
-
-static void ramp_down_mute_callback(void *data)
-{
- struct cras_iodev *odev = (struct cras_iodev *)data;
- cras_device_monitor_set_device_mute_state(odev->info.idx);
-}
-
-/* Used in audio thread. Check the docstrings of CRAS_IODEV_RAMP_REQUEST. */
-int cras_iodev_start_ramp(struct cras_iodev *odev,
- enum CRAS_IODEV_RAMP_REQUEST request)
-{
- cras_ramp_cb cb = NULL;
- void *cb_data = NULL;
- int rc;
- float from, to, duration_secs;
-
- /* Ignores request if device is closed. */
- if (!cras_iodev_is_open(odev))
- return 0;
-
- switch (request) {
- case CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE:
- from = 0.0;
- to = 1.0;
- duration_secs = RAMP_UNMUTE_DURATION_SECS;
- break;
- case CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK:
- from = 0.0;
- to = 1.0;
- duration_secs = RAMP_NEW_STREAM_DURATION_SECS;
- break;
- /* Unmute -> mute. Callback to set mute state should be called after
- * ramping is done. */
- case CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE:
- from = 1.0;
- to = 0.0;
- duration_secs = RAMP_MUTE_DURATION_SECS;
- cb = ramp_down_mute_callback;
- cb_data = (void *)odev;
- break;
- case CRAS_IODEV_RAMP_REQUEST_RESUME_MUTE:
- from = 0;
- to = 0;
- duration_secs = RAMP_RESUME_MUTE_DURATION_SECS;
- odev->initial_ramp_request =
- CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- break;
- case CRAS_IODEV_RAMP_REQUEST_SWITCH_MUTE:
- from = 0;
- to = 0;
- duration_secs = RAMP_SWITCH_MUTE_DURATION_SECS;
- odev->initial_ramp_request =
- CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- break;
- default:
- return -EINVAL;
- }
-
- /* Starts ramping. */
- rc = cras_mute_ramp_start(odev->ramp, from, to,
- duration_secs * odev->format->frame_rate, cb,
- cb_data);
-
- if (rc)
- return rc;
-
- /* Mute -> unmute case, unmute state should be set after ramping is
- * started so device can start playing with samples close to 0. */
- if (request == CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE)
- cras_device_monitor_set_device_mute_state(odev->info.idx);
-
- return 0;
-}
-
-int cras_iodev_start_volume_ramp(struct cras_iodev *odev,
- unsigned int old_volume,
- unsigned int new_volume)
-{
- float old_scaler, new_scaler;
- float from, to;
-
- if (old_volume == new_volume)
- return 0;
- if (!cras_iodev_is_open(odev))
- return 0;
- if (!odev->format)
- return -EINVAL;
- if (odev->active_node && odev->active_node->softvol_scalers) {
- old_scaler = odev->active_node->softvol_scalers[old_volume];
- new_scaler = odev->active_node->softvol_scalers[new_volume];
- } else {
- old_scaler = softvol_get_scaler(old_volume);
- new_scaler = softvol_get_scaler(new_volume);
- }
- if (new_scaler == 0.0) {
- return -EINVAL;
- }
- /* We will soon set odev's volume to new_volume from old_volume.
- * Because we're using softvol, we were previously scaling our volume by
- * old_scaler. If we want to avoid a jump in volume, we need to start
- * our ramp so that (from * new_scaler) = old_scaler. */
- from = old_scaler / new_scaler;
- to = 1.0;
-
- return cras_volume_ramp_start(odev->ramp, from, to,
- RAMP_VOLUME_CHANGE_DURATION_SECS *
- odev->format->frame_rate,
- NULL, NULL);
-}
-
-int cras_iodev_set_mute(struct cras_iodev *iodev)
-{
- if (!cras_iodev_is_open(iodev))
- return 0;
-
- if (iodev->set_mute)
- iodev->set_mute(iodev);
- return 0;
-}
-
-void cras_iodev_update_highest_hw_level(struct cras_iodev *iodev,
- unsigned int hw_level)
-{
- /*
- * If the hw_level is unreasonably high and reach to the device's
- * buffer size, regard it as a device overrun.
- * In the normal status, the hw_level for should be between 1 to 2
- * largest_cb_level for an output device and 0 to 1 largest_cb_level
- * for an input device. Therefore, larger than 3 can be considered
- * unreasonable.
- */
- if (hw_level == iodev->buffer_size &&
- iodev->largest_cb_level * 3 < iodev->buffer_size) {
- ATLOG(atlog, AUDIO_THREAD_DEV_OVERRUN, iodev->info.idx,
- hw_level, 0);
- /* Only log the event when the first time it happens. */
- if (iodev->highest_hw_level != hw_level)
- cras_audio_thread_event_dev_overrun();
- }
- iodev->highest_hw_level = MAX(iodev->highest_hw_level, hw_level);
-}
-
-/*
- * Makes an input device drop the given number of frames.
- * Args:
- * iodev - The device.
- * frames - How many frames will be dropped in a device.
- * Returns:
- * The number of frames have been dropped. Negative error code on failure.
- */
-static int cras_iodev_drop_frames(struct cras_iodev *iodev, unsigned int frames)
-{
- struct timespec hw_tstamp;
- int i, rc;
- unsigned int target_frames, dropped_frames = 0;
-
- if (iodev->direction != CRAS_STREAM_INPUT)
- return -EINVAL;
-
- rc = cras_iodev_frames_queued(iodev, &hw_tstamp);
- if (rc < 0)
- return rc;
-
- target_frames = MIN(frames, rc);
-
- /*
- * Loop reading the buffer, at most twice. This is to cover when
- * circular buffer is at the end and returns partial of the target
- * frames.
- */
- for (i = 0; (dropped_frames < target_frames) && (i < 2); i++) {
- frames = target_frames - dropped_frames;
- rc = iodev->get_buffer(iodev, &iodev->input_data->area,
- &frames);
- if (rc < 0)
- return rc;
-
- rc = iodev->put_buffer(iodev, frames);
- if (rc < 0)
- return rc;
- dropped_frames += frames;
- /*
- * Tell rate estimator that some frames have been dropped to
- * avoid calculating the wrong rate.
- */
- rate_estimator_add_frames(iodev->rate_est, -frames);
- }
-
- ATLOG(atlog, AUDIO_THREAD_DEV_DROP_FRAMES, iodev->info.idx,
- dropped_frames, 0);
-
- return frames;
-}
-
-int cras_iodev_drop_frames_by_time(struct cras_iodev *iodev, struct timespec ts)
-{
- int frames_to_set;
- double est_rate;
- int rc;
-
- est_rate = iodev->format->frame_rate *
- cras_iodev_get_est_rate_ratio(iodev);
- frames_to_set = cras_time_to_frames(&ts, est_rate);
-
- rc = cras_iodev_drop_frames(iodev, frames_to_set);
-
- return rc;
-}
-
-bool cras_iodev_support_noise_cancellation(const struct cras_iodev *iodev)
-{
- if (iodev->direction != CRAS_STREAM_INPUT)
- return false;
-
- if (iodev->support_noise_cancellation)
- return !!iodev->support_noise_cancellation(iodev);
- return false;
-}
diff --git a/cras/src/server/cras_iodev.h b/cras/src/server/cras_iodev.h
deleted file mode 100644
index 18a0962c..00000000
--- a/cras/src/server/cras_iodev.h
+++ /dev/null
@@ -1,850 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * cras_iodev represents playback or capture devices on the system. Each iodev
- * will attach to a thread to render or capture audio. For playback, this
- * thread will gather audio from the streams that are attached to the device and
- * render the samples it gets to the iodev. For capture the process is
- * reversed, the samples are pulled from the device and passed on to the
- * attached streams.
- */
-#ifndef CRAS_IODEV_H_
-#define CRAS_IODEV_H_
-
-#include <stdbool.h>
-
-#include "cras_dsp.h"
-#include "cras_iodev_info.h"
-#include "cras_messages.h"
-#include "ewma_power.h"
-
-struct buffer_share;
-struct cras_fmt_conv;
-struct cras_ramp;
-struct cras_rstream;
-struct cras_audio_area;
-struct cras_audio_format;
-struct audio_thread;
-struct cras_iodev;
-struct rate_estimator;
-
-/*
- * Type of callback function to execute when loopback sender transfers audio
- * to the receiver. For example, this is called in audio thread when playback
- * samples are mixed and about to write to hardware.
- * Args:
- * frames - Loopback audio data from sender.
- * nframes - Number loopback audio data in frames.
- * fmt - Format of the loopback audio data.
- * cb_data - Pointer to the loopback receiver.
- */
-typedef int (*loopback_hook_data_t)(const uint8_t *frames, unsigned int nframes,
- const struct cras_audio_format *fmt,
- void *cb_data);
-
-/*
- * Type of callback function to notify loopback receiver that the loopback path
- * starts or stops.
- * Args:
- * start - True to notify receiver that loopback starts. False to notify
- * loopback stops.
- * cb_data - Pointer to the loopback receiver.
- */
-typedef int (*loopback_hook_control_t)(bool start, void *cb_data);
-
-/* Callback type for an iodev event. */
-typedef int (*iodev_hook_t)();
-
-/*
- * Holds the information of a receiver of loopback audio, used to register
- * with the sender of loopback audio. A sender keeps a list of cras_loopback
- * objects representing all the receivers.
- * Members:
- * type - Pre-dsp loopback can be used for system loopback. Post-dsp
- * loopback can be used for echo reference.
- * hook_data - Callback used for playback samples after mixing, before or
- * after applying DSP depends on the value of |type|.
- * hook_control - Callback to notify receiver that loopback starts or stops.
- * cb_data - Pointer to the loopback receiver, will be passing to hook functions.
- */
-struct cras_loopback {
- enum CRAS_LOOPBACK_TYPE type;
- loopback_hook_data_t hook_data;
- loopback_hook_control_t hook_control;
- void *cb_data;
- struct cras_loopback *prev, *next;
-};
-
-/* State of an iodev.
- * no_stream state is only supported on output device.
- * Open state is only supported for device supporting start ops.
- */
-enum CRAS_IODEV_STATE {
- CRAS_IODEV_STATE_CLOSE = 0,
- CRAS_IODEV_STATE_OPEN = 1,
- CRAS_IODEV_STATE_NORMAL_RUN = 2,
- CRAS_IODEV_STATE_NO_STREAM_RUN = 3,
-};
-
-/* Holds an output/input node for this device. An ionode is a control that
- * can be switched on and off such as headphones or speakers.
- * Members:
- * dev - iodev which this node belongs to.
- * idx - ionode index.
- * plugged - true if the device is plugged.
- * plugged_time - If plugged is true, this is the time it was attached.
- * volume - per-node volume (0-100)
- * capture_gain - Internal per-node capture gain/attenuation (in 100*dBFS)
- * This is only used for CRAS internal tuning, no way to change by
- * client.
- * ui_gain_scaler - The adjustable gain scaler set by client.
- * left_right_swapped - If left and right output channels are swapped.
- * type - Type displayed to the user.
- * position - Specify where on the system this node locates.
- * name - Name displayed to the user.
- * dsp_name - The "DspName" variable specified in the ucm config.
- * active_hotword_model - name of the currently selected hotword model.
- * softvol_scalers - pointer to software volume scalers.
- * software_volume_needed - For output: True if the volume range of the node
- * is smaller than desired. For input: True if this node needs software
- * gain.
- * intrinsic_sensitivity - The "IntrinsicSensitivity" in 0.01 dBFS/Pa
- * specified in the ucm config.
- * stable_id - id for node that doesn't change after unplug/plug.
- * is_sco_pcm - Bool to indicate whether the ionode is for SCO over PCM.
- */
-struct cras_ionode {
- struct cras_iodev *dev;
- uint32_t idx;
- int plugged;
- struct timeval plugged_time;
- unsigned int volume;
- long capture_gain;
- float ui_gain_scaler;
- int left_right_swapped;
- enum CRAS_NODE_TYPE type;
- enum CRAS_NODE_POSITION position;
- char name[CRAS_NODE_NAME_BUFFER_SIZE];
- const char *dsp_name;
- char active_hotword_model[CRAS_NODE_HOTWORD_MODEL_BUFFER_SIZE];
- float *softvol_scalers;
- int software_volume_needed;
- long intrinsic_sensitivity;
- unsigned int stable_id;
- int is_sco_pcm;
- struct cras_ionode *prev, *next;
-};
-
-/* An input or output device, that can have audio routed to/from it.
- * set_volume - Function to call if the system volume changes.
- * set_capture_gain - Function to call if active node's capture_gain changes.
- * set_mute - Function to call if the system mute state changes.
- * set_capture_mute - Function to call if the system capture mute state changes.
- * set_swap_mode_for_node - Function to call to set swap mode for the node.
- * open_dev - Opens the device.
- * configure_dev - Configures the device.
- * close_dev - Closes the device if it is open.
- * update_supported_formats - Refresh supported frame rates and channel counts.
- * frames_queued - The number of frames in the audio buffer, and fills tstamp
- * with the associated timestamp. The timestamp is {0, 0} when
- * the device hasn't started processing data (and on error).
- * delay_frames - The delay of the next sample in frames.
- * get_buffer - Returns a buffer to read/write to/from.
- * put_buffer - Marks a buffer from get_buffer as read/written.
- * flush_buffer - Flushes the buffer and return the number of frames flushed.
- * start - Starts running device. This is optionally supported on output device.
- * If device supports this ops, device can be in CRAS_IODEV_STATE_OPEN
- * state after being opened.
- * If device does not support this ops, then device will be in
- * CRAS_IODEV_STATE_NO_STREAM_RUN.
- * no_stream - (Optional) When there is no stream, we let device keep running
- * for some time to save the time to open device for the next
- * stream. This is the no stream state of an output device.
- * The default action of no stream state is to fill zeros
- * periodically. Device can implement this function to define
- * its own optimization of entering/exiting no stream state.
- * is_free_running - (Optional) Checks if the device is in free running state.
- * output_underrun - (Optional) Handle output device underrun.
- * update_active_node - Update the active node when the selected device/node has
- * changed.
- * update_channel_layout - Update the channel layout base on set iodev->format,
- * expect the best available layout be filled to iodev->format.
- * set_hotword_model - Sets the hotword model to this iodev.
- * get_hotword_models - Gets a comma separated string of the list of supported
- * hotword models of this iodev.
- * get_num_severe_underruns - Gets number of severe underrun recorded since
- * iodev was created.
- * get_valid_frames - Gets number of valid frames in device which have not
- * played yet. Valid frames does not include zero samples
- * we filled under no streams state.
- * frames_to_play_in_sleep - Returns the non-negative number of frames that
- * audio thread can sleep before serving this playback dev the next time.
- * Not implementing this ops means fall back to default behavior in
- * cras_iodev_default_frames_to_play_in_sleep().
- * support_noise_cancellation - (Optional) Checks if the device supports noise
- * cancellation.
- * format - The audio format being rendered or captured to hardware.
- * rate_est - Rate estimator to estimate the actual device rate.
- * area - Information about how the samples are stored.
- * info - Unique identifier for this device (index and name).
- * nodes - The output or input nodes available for this device.
- * active_node - The current node being used for playback or capture.
- * direction - Input or Output.
- * supported_rates - Array of sample rates supported by device 0-terminated.
- * supported_channel_counts - List of number of channels supported by device.
- * supported_formats - List of audio formats (s16le, s32le) supported by device.
- * buffer_size - Size of the audio buffer in frames.
- * min_buffer_level - Extra frames to keep queued in addition to requested.
- * dsp_context - The context used for dsp processing on the audio data.
- * dsp_name - The "dsp_name" dsp variable specified in the ucm config.
- * echo_reference_dev - Used only for playback iodev. Pointer to the input
- * iodev, which can be used to record what is playing out from this
- * iodev. This will be used as the echo reference for echo cancellation.
- * is_enabled - True if this iodev is enabled, false otherwise.
- * software_volume_needed - True if volume control is not supported by hardware.
- * software_gain_scaler - Scaler value to apply to captured data. This can
- * be different when active node changes. Configured when there's no
- * hardware gain control.
- * streams - List of audio streams serviced by dev.
- * state - Device is in one of close, open, normal, or no_stream state defined
- * in enum CRAS_IODEV_STATE.
- * min_cb_level - min callback level of any stream attached.
- * max_cb_level - max callback level of any stream attached.
- * highest_hw_level - The highest hardware level of the device.
- * largest_cb_level - The largest callback level of streams attached to this
- * device. The difference with max_cb_level is it takes all
- * streams into account even if they have been removed.
- * num_underruns - Number of times we have run out of data (playback only).
- * buf_state - If multiple streams are writing to this device, then this
- * keeps track of how much each stream has written.
- * idle_timeout - The timestamp when to close the dev after being idle.
- * open_ts - The time when the device opened.
- * loopbacks - List of registered cras_loopback objects representing the
- * receivers who wants a copy of the audio sending through this iodev.
- * pre_open_iodev_hook - Optional callback to call before iodev open.
- * post_close_iodev_hook - Optional callback to call after iodev close.
- * ext_dsp_module - External dsp module to process audio data in stream level
- * after dsp_context.
- * reset_request_pending - The flag for pending reset request.
- * ramp - The cras_ramp struct to control ramping up/down at mute/unmute and
- * start of playback.
- * input_streaming - For capture only. Indicate if input has started.
- * input_frames_read - The number of frames read from the device, but that
- * haven't been "put" yet.
- * input_dsp_offset - The number of frames in the HW buffer that have already
- * been processed by the input DSP.
- * input_data - Used to pass audio input data to streams with or without
- * stream side processing.
- * initial_ramp_request - The value indicates which type of ramp the device
- * should perform when some samples are ready for playback.
- * ewma - The ewma instance to calculate iodev volume.
- */
-struct cras_iodev {
- void (*set_volume)(struct cras_iodev *iodev);
- void (*set_mute)(struct cras_iodev *iodev);
- void (*set_capture_gain)(struct cras_iodev *iodev);
- void (*set_capture_mute)(struct cras_iodev *iodev);
- int (*set_swap_mode_for_node)(struct cras_iodev *iodev,
- struct cras_ionode *node, int enable);
- int (*open_dev)(struct cras_iodev *iodev);
- int (*configure_dev)(struct cras_iodev *iodev);
- int (*close_dev)(struct cras_iodev *iodev);
- int (*update_supported_formats)(struct cras_iodev *iodev);
- int (*frames_queued)(const struct cras_iodev *iodev,
- struct timespec *tstamp);
- int (*delay_frames)(const struct cras_iodev *iodev);
- int (*get_buffer)(struct cras_iodev *iodev,
- struct cras_audio_area **area, unsigned *frames);
- int (*put_buffer)(struct cras_iodev *iodev, unsigned nwritten);
- int (*flush_buffer)(struct cras_iodev *iodev);
- int (*start)(const struct cras_iodev *iodev);
- int (*is_free_running)(const struct cras_iodev *iodev);
- int (*output_underrun)(struct cras_iodev *iodev);
- int (*no_stream)(struct cras_iodev *iodev, int enable);
- void (*update_active_node)(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled);
- int (*update_channel_layout)(struct cras_iodev *iodev);
- int (*set_hotword_model)(struct cras_iodev *iodev,
- const char *model_name);
- char *(*get_hotword_models)(struct cras_iodev *iodev);
- unsigned int (*get_num_severe_underruns)(const struct cras_iodev *iodev);
- int (*get_valid_frames)(struct cras_iodev *odev,
- struct timespec *tstamp);
- unsigned int (*frames_to_play_in_sleep)(struct cras_iodev *iodev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp);
- int (*support_noise_cancellation)(const struct cras_iodev *iodev);
- struct cras_audio_format *format;
- struct rate_estimator *rate_est;
- struct cras_audio_area *area;
- struct cras_iodev_info info;
- struct cras_ionode *nodes;
- struct cras_ionode *active_node;
- enum CRAS_STREAM_DIRECTION direction;
- size_t *supported_rates;
- size_t *supported_channel_counts;
- snd_pcm_format_t *supported_formats;
- snd_pcm_uframes_t buffer_size;
- unsigned int min_buffer_level;
- struct cras_dsp_context *dsp_context;
- const char *dsp_name;
- struct cras_iodev *echo_reference_dev;
- int is_enabled;
- int software_volume_needed;
- float software_gain_scaler;
- struct dev_stream *streams;
- enum CRAS_IODEV_STATE state;
- unsigned int min_cb_level;
- unsigned int max_cb_level;
- unsigned int highest_hw_level;
- unsigned int largest_cb_level;
- unsigned int num_underruns;
- struct buffer_share *buf_state;
- struct timespec idle_timeout;
- struct timespec open_ts;
- struct cras_loopback *loopbacks;
- iodev_hook_t pre_open_iodev_hook;
- iodev_hook_t post_close_iodev_hook;
- struct ext_dsp_module *ext_dsp_module;
- int reset_request_pending;
- struct cras_ramp *ramp;
- int input_streaming;
- unsigned int input_frames_read;
- unsigned int input_dsp_offset;
- unsigned int initial_ramp_request;
- struct input_data *input_data;
- struct ewma_power ewma;
- struct cras_iodev *prev, *next;
-};
-
-/*
- * Ramp request used in cras_iodev_start_ramp.
- *
- * - CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE: Mute->unmute.
- * Change device to unmute state after ramping is stared,
- * that is, (a) in the plot.
- *
- * ____
- * .... /
- * _____/
- * (a)
- *
- * - CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE: Unmute->mute.
- * Change device to mute state after ramping is done, that is,
- * (b) in the plot.
- *
- * _____
- * \....
- * \____
- * (b)
- *
- * - CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK: Ramping is requested because
- * first sample of new stream is ready, there is no need to change mute/unmute
- * state.
- *
- * - CRAS_IODEV_RAMP_REQUEST_RESUME_MUTE: To prevent popped noise, mute the
- * device for RAMP_RESUME_MUTE_DURATION_SECS seconds on sample ready after
- * resume if there were playback stream before suspend.
- *
- * - CRAS_IODEV_RAMP_REQUEST_SWITCH_MUTE: To prevent popped noise, mute the
- * device for RAMP_SWITCH_MUTE_DURATION_SECS seconds on sample ready after
- * device switch if there were playback stream before switch.
- *
- */
-
-enum CRAS_IODEV_RAMP_REQUEST {
- CRAS_IODEV_RAMP_REQUEST_NONE = 0,
- CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE = 1,
- CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE = 2,
- CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK = 3,
- CRAS_IODEV_RAMP_REQUEST_RESUME_MUTE = 4,
- CRAS_IODEV_RAMP_REQUEST_SWITCH_MUTE = 5,
-};
-
-/*
- * Utility functions to be used by iodev implementations.
- */
-
-/* Sets up the iodev for the given format if possible. If the iodev can't
- * handle the requested format, format conversion will happen in dev_stream.
- * It also allocates a dsp context for the iodev.
- * Args:
- * iodev - the iodev you want the format for.
- * fmt - the desired format.
- */
-int cras_iodev_set_format(struct cras_iodev *iodev,
- const struct cras_audio_format *fmt);
-
-/* Clear the format previously set for this iodev.
- *
- * Args:
- * iodev - the iodev you want to free the format.
- */
-void cras_iodev_free_format(struct cras_iodev *iodev);
-
-/* Initializes the audio area for this iodev.
- * Args:
- * iodev - the iodev to init audio area
- * num_channels - the total number of channels
- */
-void cras_iodev_init_audio_area(struct cras_iodev *iodev, int num_channels);
-
-/* Frees the audio area for this iodev.
- * Args:
- * iodev - the iodev to free audio area
- */
-void cras_iodev_free_audio_area(struct cras_iodev *iodev);
-
-/* Free resources allocated for this iodev.
- *
- * Args:
- * iodev - the iodev you want to free the resources for.
- */
-void cras_iodev_free_resources(struct cras_iodev *iodev);
-
-/* Fill timespec ts with the time to sleep based on the number of frames and
- * frame rate.
- * Args:
- * frames - Number of frames in buffer..
- * frame_rate - 44100, 48000, etc.
- * ts - Filled with the time to sleep for.
- */
-void cras_iodev_fill_time_from_frames(size_t frames, size_t frame_rate,
- struct timespec *ts);
-
-/* Update the "dsp_name" dsp variable. This may cause the dsp pipeline to be
- * reloaded.
- * Args:
- * iodev - device which the state changes.
- */
-void cras_iodev_update_dsp(struct cras_iodev *iodev);
-
-/* Sets swap mode on a node using dsp. This function can be called when
- * dsp pipline is not created yet. It will take effect when dsp pipeline
- * is created later. If there is dsp pipeline, this function causes the dsp
- * pipeline to be reloaded and swap mode takes effect right away.
- * Args:
- * iodev - device to be changed for swap mode.
- * node - the node to be changed for swap mode.
- * enable - 1 to enable swap mode, 0 otherwise.
- * Returns:
- * 0 on success, error code on failure.
- */
-int cras_iodev_dsp_set_swap_mode_for_node(struct cras_iodev *iodev,
- struct cras_ionode *node, int enable);
-
-/* Handles a plug event happening on this node.
- * Args:
- * node - ionode on which a plug event was detected.
- * plugged - true if the device was plugged, false for unplugged.
- */
-void cras_ionode_plug_event(struct cras_ionode *node, int plugged);
-
-/* Returns true if node a is preferred over node b. */
-int cras_ionode_better(struct cras_ionode *a, struct cras_ionode *b);
-
-/* Sets the plugged state of a node. */
-void cras_iodev_set_node_plugged(struct cras_ionode *node, int plugged);
-
-/* Adds a node to the iodev's node list. */
-void cras_iodev_add_node(struct cras_iodev *iodev, struct cras_ionode *node);
-
-/* Removes a node from iodev's node list. */
-void cras_iodev_rm_node(struct cras_iodev *iodev, struct cras_ionode *node);
-
-/* Assign a node to be the active node of the device */
-void cras_iodev_set_active_node(struct cras_iodev *iodev,
- struct cras_ionode *node);
-
-/* Checks if the node is the typical playback or capture option for AEC usage. */
-bool cras_iodev_is_aec_use_case(const struct cras_ionode *node);
-
-/* Checks if the node is a playback or capture node on internal card. */
-bool cras_iodev_is_on_internal_card(const struct cras_ionode *node);
-
-/* Adjust the system volume based on the volume of the given node. */
-static inline unsigned int
-cras_iodev_adjust_node_volume(const struct cras_ionode *node,
- unsigned int system_volume)
-{
- unsigned int node_vol_offset = 100 - node->volume;
-
- if (system_volume > node_vol_offset)
- return system_volume - node_vol_offset;
- else
- return 0;
-}
-
-/* Get the volume scaler for the active node. */
-static inline unsigned int
-cras_iodev_adjust_active_node_volume(struct cras_iodev *iodev,
- unsigned int system_volume)
-{
- if (!iodev->active_node)
- return system_volume;
-
- return cras_iodev_adjust_node_volume(iodev->active_node, system_volume);
-}
-
-/* Returns true if the active node of the iodev needs software volume. */
-static inline int
-cras_iodev_software_volume_needed(const struct cras_iodev *iodev)
-{
- if (iodev->software_volume_needed)
- return 1;
-
- if (!iodev->active_node)
- return 0;
-
- if (iodev->active_node->intrinsic_sensitivity)
- return 1;
-
- return iodev->active_node->software_volume_needed;
-}
-
-static inline float
-cras_iodev_get_ui_gain_scaler(const struct cras_iodev *iodev)
-{
- if (!iodev->active_node)
- return 1.0f;
- return iodev->active_node->ui_gain_scaler;
-}
-
-/* Gets the software gain scaler should be applied on the deivce.
- * Args:
- * iodev - The device.
- * Returns:
- * A scaler translated from system gain and active node gain.
- * Returns 1.0 if software gain is not needed. */
-float cras_iodev_get_software_gain_scaler(const struct cras_iodev *iodev);
-
-/* Gets the software volume scaler of the iodev. The scaler should only be
- * applied if the device needs software volume. */
-float cras_iodev_get_software_volume_scaler(struct cras_iodev *iodev);
-
-/* Indicate that a stream has been added from the device. */
-int cras_iodev_add_stream(struct cras_iodev *iodev, struct dev_stream *stream);
-
-/* Indicate that a stream is taken into consideration of device's I/O. This
- * function is for output stream only. For input stream, it is already included
- * by add_stream function. */
-void cras_iodev_start_stream(struct cras_iodev *iodev,
- struct dev_stream *stream);
-
-/* Indicate that a stream has been removed from the device. */
-struct dev_stream *cras_iodev_rm_stream(struct cras_iodev *iodev,
- const struct cras_rstream *stream);
-
-/* Get the offset of this stream into the dev's buffer. */
-unsigned int cras_iodev_stream_offset(struct cras_iodev *iodev,
- struct dev_stream *stream);
-
-/* Get the maximum offset of any stream into the dev's buffer. */
-unsigned int cras_iodev_max_stream_offset(const struct cras_iodev *iodev);
-
-/* Tell the device how many frames the given stream wrote. */
-void cras_iodev_stream_written(struct cras_iodev *iodev,
- struct dev_stream *stream,
- unsigned int nwritten);
-
-/* All streams have written what they can, update the write pointers and return
- * the amount that has been filled by all streams and can be comitted to the
- * device.
- */
-unsigned int cras_iodev_all_streams_written(struct cras_iodev *iodev);
-
-/* Return the state of an iodev. */
-enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev *iodev);
-
-/* Open an iodev, does setup and invokes the open_dev callback. */
-int cras_iodev_open(struct cras_iodev *iodev, unsigned int cb_level,
- const struct cras_audio_format *fmt);
-
-/* Open an iodev, does teardown and invokes the close_dev callback. */
-int cras_iodev_close(struct cras_iodev *iodev);
-
-/* Gets the available buffer to write/read audio.*/
-int cras_iodev_buffer_avail(struct cras_iodev *iodev, unsigned hw_level);
-
-/* Marks a buffer from get_buffer as read.
- * Args:
- * iodev - The input device.
- * Returns:
- * Number of frames to put sucessfully. Negative error code on failure.
- */
-int cras_iodev_put_input_buffer(struct cras_iodev *iodev);
-
-/* Marks a buffer from get_buffer as written. */
-int cras_iodev_put_output_buffer(struct cras_iodev *iodev, uint8_t *frames,
- unsigned int nframes, int *is_non_empty,
- struct cras_fmt_conv *remix_converter);
-
-/* Returns a buffer to read from.
- * Args:
- * iodev - The device.
- * frames - Filled with the number of frames that can be read/written.
- */
-int cras_iodev_get_input_buffer(struct cras_iodev *iodev, unsigned *frames);
-
-/* Returns a buffer to read from.
- * Args:
- * iodev - The device.
- * area - Filled with a pointer to the audio to read/write.
- * frames - Filled with the number of frames that can be read/written.
- */
-int cras_iodev_get_output_buffer(struct cras_iodev *iodev,
- struct cras_audio_area **area,
- unsigned *frames);
-
-/* Update the estimated sample rate of the device. */
-int cras_iodev_update_rate(struct cras_iodev *iodev, unsigned int level,
- struct timespec *level_tstamp);
-
-/* Resets the rate estimator of the device. */
-int cras_iodev_reset_rate_estimator(const struct cras_iodev *iodev);
-
-/* Returns the rate of estimated frame rate and the claimed frame rate of
- * the device. */
-double cras_iodev_get_est_rate_ratio(const struct cras_iodev *iodev);
-
-/* Get the delay from DSP processing in frames. */
-int cras_iodev_get_dsp_delay(const struct cras_iodev *iodev);
-
-/* Returns the number of frames in the hardware buffer.
- * Args:
- * iodev - The device.
- * tstamp - The associated hardware time stamp.
- * Returns:
- * Number of frames in the hardware buffer.
- * Returns -EPIPE if there is severe underrun.
- */
-int cras_iodev_frames_queued(struct cras_iodev *iodev, struct timespec *tstamp);
-
-/* Get the delay for input/output in frames. */
-static inline int cras_iodev_delay_frames(const struct cras_iodev *iodev)
-{
- return iodev->delay_frames(iodev) + cras_iodev_get_dsp_delay(iodev);
-}
-
-/* Returns if input iodev has started streaming. */
-static inline int cras_iodev_input_streaming(const struct cras_iodev *iodev)
-{
- return iodev->input_streaming;
-}
-
-/* Returns true if the device is open. */
-static inline int cras_iodev_is_open(const struct cras_iodev *iodev)
-{
- if (iodev && iodev->state != CRAS_IODEV_STATE_CLOSE)
- return 1;
- return 0;
-}
-
-/* Configure iodev to exit idle mode. */
-static inline void cras_iodev_exit_idle(struct cras_iodev *iodev)
-{
- iodev->idle_timeout.tv_sec = 0;
-}
-
-/*
- * Sets the external dsp module for |iodev| and configures the module
- * accordingly if iodev is already open. This function should be called
- * in main thread.
- * Args:
- * iodev - The iodev to hold the dsp module.
- * ext - External dsp module to set to iodev. Pass NULL to release
- * the ext_dsp_module already added to dsp pipeline.
- */
-void cras_iodev_set_ext_dsp_module(struct cras_iodev *iodev,
- struct ext_dsp_module *ext);
-
-/* Put 'frames' worth of zero samples into odev. */
-int cras_iodev_fill_odev_zeros(struct cras_iodev *odev, unsigned int frames);
-
-/*
- * The default implementation of frames_to_play_in_sleep ops, used when an
- * iodev doesn't have its own logic.
- * The default behavior is to calculate how log it takes for buffer level to
- * run to as low as min_buffer_level.
- */
-unsigned int
-cras_iodev_default_frames_to_play_in_sleep(struct cras_iodev *odev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp);
-
-/* Gets the number of frames to play when audio thread sleeps.
- * Args:
- * iodev[in] - The device.
- * hw_level[out] - Pointer to number of frames in hardware.
- * hw_tstamp[out] - Pointer to the timestamp for hw_level.
- * Returns:
- * Number of frames to play in sleep for this output device.
- */
-unsigned int cras_iodev_frames_to_play_in_sleep(struct cras_iodev *odev,
- unsigned int *hw_level,
- struct timespec *hw_tstamp);
-
-/* Checks if audio thread should wake for this output device.
- * Args:
- * iodev[in] - The output device.
- * Returns:
- * 1 if audio thread should wake for this output device. 0 otherwise.
- */
-int cras_iodev_odev_should_wake(const struct cras_iodev *odev);
-
-/* The default implementation of no_stream ops.
- * The default behavior is to fill some zeros when entering no stream state.
- * Note that when a device in no stream state enters into no stream state again,
- * device needs to fill some zeros again.
- * Do nothing to leave no stream state.
- * Args:
- * iodev[in] - The output device.
- * enable[in] - 1 to enter no stream playback, 0 to leave.
- * Returns:
- * 0 on success. Negative error code on failure.
- * */
-int cras_iodev_default_no_stream_playback(struct cras_iodev *odev, int enable);
-
-/* Get current state of iodev.
- * Args:
- * iodev[in] - The device.
- * Returns:
- * One of states defined in CRAS_IODEV_STATE.
- */
-enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev *iodev);
-
-/* Possibly transit state for output device.
- * Check if this output device needs to transit from open state/no_stream state
- * into normal run state. If device does not need transition and is still in
- * no stream state, call no_stream ops to do its work for one cycle.
- * Args:
- * odev[in] - The output device.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int cras_iodev_prepare_output_before_write_samples(struct cras_iodev *odev);
-
-/* Get number of underruns recorded so far.
- * Args:
- * iodev[in] - The device.
- * Returns:
- * An unsigned int for number of underruns recorded.
- */
-unsigned int cras_iodev_get_num_underruns(const struct cras_iodev *iodev);
-
-/* Get number of severe underruns recorded so far.
- * Args:
- * iodev[in] - The device.
- * Returns:
- * An unsigned int for number of severe underruns recorded since iodev
- * was created.
- */
-unsigned int
-cras_iodev_get_num_severe_underruns(const struct cras_iodev *iodev);
-
-/* Get number of valid frames in the hardware buffer. The valid frames does
- * not include zero samples we filled with before.
- * Args:
- * iodev[in] - The device.
- * hw_tstamp[out] - Pointer to the timestamp for hw_level.
- * Returns:
- * Number of valid frames in the hardware buffer.
- * Negative error code on failure.
- */
-int cras_iodev_get_valid_frames(struct cras_iodev *iodev,
- struct timespec *hw_tstamp);
-
-/* Request main thread to re-open device. This should be used in audio thread
- * when it finds device is in a bad state. The request will be ignored if
- * there is still a pending request.
- * Args:
- * iodev[in] - The device.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int cras_iodev_reset_request(struct cras_iodev *iodev);
-
-/* Handle output underrun.
- * Args:
- * odev[in] - The output device.
- * hw_level[in] - The current hw_level. Used in the debug log.
- * frames_written[in] - The number of written frames. Used in the debug log.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int cras_iodev_output_underrun(struct cras_iodev *odev, unsigned int hw_level,
- unsigned int frames_written);
-
-/* Start ramping samples up/down on a device.
- * Args:
- * iodev[in] - The device.
- * request[in] - The request type. Check the docstrings of
- * CRAS_IODEV_RAMP_REQUEST.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int cras_iodev_start_ramp(struct cras_iodev *odev,
- enum CRAS_IODEV_RAMP_REQUEST request);
-
-/* Start ramping samples up/down on a device after a volume change.
- * Args:
- * iodev[in] - The device.
- * old_volume[in] - The previous volume percentage of the device.
- * new_volume[in] - The new volume percentage of the device.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int cras_iodev_start_volume_ramp(struct cras_iodev *odev,
- unsigned int old_volume,
- unsigned int new_volume);
-
-/* Set iodev to mute/unmute state.
- * Args:
- * iodev[in] - The device.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int cras_iodev_set_mute(struct cras_iodev *iodev);
-
-/*
- * Checks if an output iodev's volume is zero.
- * If there is an active node, check the adjusted node volume.
- * If there is no active node, check system volume.
- * Args:
- * odev[in] - The device.
- * Returns:
- * 1 if device's volume is 0. 0 otherwise.
- */
-int cras_iodev_is_zero_volume(const struct cras_iodev *odev);
-
-/*
- * Updates the highest hardware level of the device.
- * Args:
- * iodev - The device.
- */
-void cras_iodev_update_highest_hw_level(struct cras_iodev *iodev,
- unsigned int hw_level);
-
-/*
- * Makes an input device drop the specific number of frames by given time.
- * Args:
- * iodev - The device.
- * ts - The time indicates how many frames will be dropped in a device.
- * Returns:
- * The number of frames have been dropped. Negative error code on failure.
- */
-int cras_iodev_drop_frames_by_time(struct cras_iodev *iodev,
- struct timespec ts);
-
-/* Checks if an input device supports noise cancellation.
- * Args:
- * iodev - The device.
- * Returns:
- * True if device supports noise cancellation. False otherwise.
- */
-bool cras_iodev_support_noise_cancellation(const struct cras_iodev *iodev);
-
-#endif /* CRAS_IODEV_H_ */
diff --git a/cras/src/server/cras_iodev_list.c b/cras/src/server/cras_iodev_list.c
deleted file mode 100644
index b818c97b..00000000
--- a/cras/src/server/cras_iodev_list.c
+++ /dev/null
@@ -1,1920 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "audio_thread.h"
-#include "cras_empty_iodev.h"
-#include "cras_iodev.h"
-#include "cras_iodev_info.h"
-#include "cras_iodev_list.h"
-#include "cras_loopback_iodev.h"
-#include "cras_main_thread_log.h"
-#include "cras_observer.h"
-#include "cras_rstream.h"
-#include "cras_server.h"
-#include "cras_tm.h"
-#include "cras_types.h"
-#include "cras_system_state.h"
-#include "server_stream.h"
-#include "softvol_curve.h"
-#include "stream_list.h"
-#include "test_iodev.h"
-#include "utlist.h"
-
-const struct timespec idle_timeout_interval = { .tv_sec = 10, .tv_nsec = 0 };
-
-/* Linked list of available devices. */
-struct iodev_list {
- struct cras_iodev *iodevs;
- size_t size;
-};
-
-/* List of enabled input/output devices.
- * dev - The device.
- * init_timer - Timer for a delayed call to init this iodev.
- */
-struct enabled_dev {
- struct cras_iodev *dev;
- struct enabled_dev *prev, *next;
-};
-
-struct dev_init_retry {
- int dev_idx;
- struct cras_timer *init_timer;
- struct dev_init_retry *next, *prev;
-};
-
-struct device_enabled_cb {
- device_enabled_callback_t enabled_cb;
- device_disabled_callback_t disabled_cb;
- void *cb_data;
- struct device_enabled_cb *next, *prev;
-};
-
-struct main_thread_event_log *main_log;
-
-/* Lists for devs[CRAS_STREAM_INPUT] and devs[CRAS_STREAM_OUTPUT]. */
-static struct iodev_list devs[CRAS_NUM_DIRECTIONS];
-/* The observer client iodev_list used to listen on various events. */
-static struct cras_observer_client *list_observer;
-/* Keep a list of enabled inputs and outputs. */
-static struct enabled_dev *enabled_devs[CRAS_NUM_DIRECTIONS];
-/* Keep an empty device per direction. */
-static struct cras_iodev *fallback_devs[CRAS_NUM_DIRECTIONS];
-/* Special empty device for hotword streams. */
-static struct cras_iodev *empty_hotword_dev;
-/* Loopback devices. */
-static struct cras_iodev *loopdev_post_mix;
-static struct cras_iodev *loopdev_post_dsp;
-/* List of pending device init retries. */
-static struct dev_init_retry *init_retries;
-
-/* Keep a constantly increasing index for iodevs. Index 0 is reserved
- * to mean "no device". */
-static uint32_t next_iodev_idx = MAX_SPECIAL_DEVICE_IDX;
-
-/* Call when a device is enabled or disabled. */
-struct device_enabled_cb *device_enable_cbs;
-
-/* Thread that handles audio input and output. */
-static struct audio_thread *audio_thread;
-/* List of all streams. */
-static struct stream_list *stream_list;
-/* Idle device timer. */
-static struct cras_timer *idle_timer;
-/* Flag to indicate that the stream list is disconnected from audio thread. */
-static int stream_list_suspended = 0;
-/* If init device failed, retry after 1 second. */
-static const unsigned int INIT_DEV_DELAY_MS = 1000;
-/* Flag to indicate that hotword streams are suspended. */
-static int hotword_suspended = 0;
-/* Flag to indicate that suspended hotword streams should be auto-resumed at
- * system resume. */
-static int hotword_auto_resume = 0;
-
-static void idle_dev_check(struct cras_timer *timer, void *data);
-
-static struct cras_iodev *find_dev(size_t dev_index)
-{
- struct cras_iodev *dev;
-
- DL_FOREACH (devs[CRAS_STREAM_OUTPUT].iodevs, dev)
- if (dev->info.idx == dev_index)
- return dev;
-
- DL_FOREACH (devs[CRAS_STREAM_INPUT].iodevs, dev)
- if (dev->info.idx == dev_index)
- return dev;
-
- return NULL;
-}
-
-static struct cras_ionode *find_node(struct cras_iodev *iodev,
- unsigned int node_idx)
-{
- struct cras_ionode *node;
- DL_SEARCH_SCALAR(iodev->nodes, node, idx, node_idx);
- return node;
-}
-
-/* Adds a device to the list. Used from add_input and add_output. */
-static int add_dev_to_list(struct cras_iodev *dev)
-{
- struct cras_iodev *tmp;
- uint32_t new_idx;
- struct iodev_list *list = &devs[dev->direction];
-
- DL_FOREACH (list->iodevs, tmp)
- if (tmp == dev)
- return -EEXIST;
-
- dev->format = NULL;
- dev->format = NULL;
- dev->prev = dev->next = NULL;
-
- /* Move to the next index and make sure it isn't taken. */
- new_idx = next_iodev_idx;
- while (1) {
- if (new_idx < MAX_SPECIAL_DEVICE_IDX)
- new_idx = MAX_SPECIAL_DEVICE_IDX;
- DL_SEARCH_SCALAR(list->iodevs, tmp, info.idx, new_idx);
- if (tmp == NULL)
- break;
- new_idx++;
- }
- dev->info.idx = new_idx;
- next_iodev_idx = new_idx + 1;
- list->size++;
-
- syslog(LOG_INFO, "Adding %s dev at index %u.",
- dev->direction == CRAS_STREAM_OUTPUT ? "output" : "input",
- dev->info.idx);
- DL_PREPEND(list->iodevs, dev);
-
- cras_iodev_list_update_device_list();
- return 0;
-}
-
-/* Removes a device to the list. Used from rm_input and rm_output. */
-static int rm_dev_from_list(struct cras_iodev *dev)
-{
- struct cras_iodev *tmp;
-
- DL_FOREACH (devs[dev->direction].iodevs, tmp)
- if (tmp == dev) {
- if (cras_iodev_is_open(dev))
- return -EBUSY;
- DL_DELETE(devs[dev->direction].iodevs, dev);
- devs[dev->direction].size--;
- return 0;
- }
-
- /* Device not found. */
- return -EINVAL;
-}
-
-/* Fills a dev_info array from the iodev_list. */
-static void fill_dev_list(struct iodev_list *list,
- struct cras_iodev_info *dev_info, size_t out_size)
-{
- int i = 0;
- struct cras_iodev *tmp;
- DL_FOREACH (list->iodevs, tmp) {
- memcpy(&dev_info[i], &tmp->info, sizeof(dev_info[0]));
- i++;
- if (i == out_size)
- return;
- }
-}
-
-static const char *node_type_to_str(struct cras_ionode *node)
-{
- switch (node->type) {
- case CRAS_NODE_TYPE_INTERNAL_SPEAKER:
- return "INTERNAL_SPEAKER";
- case CRAS_NODE_TYPE_HEADPHONE:
- return "HEADPHONE";
- case CRAS_NODE_TYPE_HDMI:
- return "HDMI";
- case CRAS_NODE_TYPE_HAPTIC:
- return "HAPTIC";
- case CRAS_NODE_TYPE_MIC:
- switch (node->position) {
- case NODE_POSITION_INTERNAL:
- return "INTERNAL_MIC";
- case NODE_POSITION_FRONT:
- return "FRONT_MIC";
- case NODE_POSITION_REAR:
- return "REAR_MIC";
- case NODE_POSITION_KEYBOARD:
- return "KEYBOARD_MIC";
- case NODE_POSITION_EXTERNAL:
- default:
- return "MIC";
- }
- case CRAS_NODE_TYPE_HOTWORD:
- return "HOTWORD";
- case CRAS_NODE_TYPE_LINEOUT:
- return "LINEOUT";
- case CRAS_NODE_TYPE_POST_MIX_PRE_DSP:
- return "POST_MIX_LOOPBACK";
- case CRAS_NODE_TYPE_POST_DSP:
- return "POST_DSP_LOOPBACK";
- case CRAS_NODE_TYPE_USB:
- return "USB";
- case CRAS_NODE_TYPE_BLUETOOTH:
- return "BLUETOOTH";
- case CRAS_NODE_TYPE_BLUETOOTH_NB_MIC:
- return "BLUETOOTH_NB_MIC";
- case CRAS_NODE_TYPE_FALLBACK_NORMAL:
- return "FALLBACK_NORMAL";
- case CRAS_NODE_TYPE_FALLBACK_ABNORMAL:
- return "FALLBACK_ABNORMAL";
- case CRAS_NODE_TYPE_ECHO_REFERENCE:
- return "ECHO_REFERENCE";
- case CRAS_NODE_TYPE_ALSA_LOOPBACK:
- return "ALSA_LOOPBACK";
- case CRAS_NODE_TYPE_UNKNOWN:
- default:
- return "UNKNOWN";
- }
-}
-
-/* Fills an ionode_info array from the iodev_list. */
-static int fill_node_list(struct iodev_list *list,
- struct cras_ionode_info *node_info, size_t out_size)
-{
- int i = 0;
- struct cras_iodev *dev;
- struct cras_ionode *node;
- DL_FOREACH (list->iodevs, dev) {
- DL_FOREACH (dev->nodes, node) {
- node_info->iodev_idx = dev->info.idx;
- node_info->ionode_idx = node->idx;
- node_info->plugged = node->plugged;
- node_info->plugged_time.tv_sec =
- node->plugged_time.tv_sec;
- node_info->plugged_time.tv_usec =
- node->plugged_time.tv_usec;
- node_info->active =
- dev->is_enabled && (dev->active_node == node);
- node_info->volume = node->volume;
- node_info->capture_gain = node->capture_gain;
- node_info->ui_gain_scaler = node->ui_gain_scaler;
- node_info->left_right_swapped =
- node->left_right_swapped;
- node_info->stable_id = node->stable_id;
- strcpy(node_info->name, node->name);
- strcpy(node_info->active_hotword_model,
- node->active_hotword_model);
- snprintf(node_info->type, sizeof(node_info->type), "%s",
- node_type_to_str(node));
- node_info->type_enum = node->type;
- node_info++;
- i++;
- if (i == out_size)
- return i;
- }
- }
- return i;
-}
-
-/* Copies the info for each device in the list to "list_out". */
-static int get_dev_list(struct iodev_list *list,
- struct cras_iodev_info **list_out)
-{
- struct cras_iodev_info *dev_info;
-
- if (!list_out)
- return list->size;
-
- *list_out = NULL;
- if (list->size == 0)
- return 0;
-
- dev_info = malloc(sizeof(*list_out[0]) * list->size);
- if (dev_info == NULL)
- return -ENOMEM;
-
- fill_dev_list(list, dev_info, list->size);
-
- *list_out = dev_info;
- return list->size;
-}
-
-/* Called when the system volume changes. Pass the current volume setting to
- * the default output if it is active. */
-static void sys_vol_change(void *context, int32_t volume)
-{
- struct cras_iodev *dev;
-
- DL_FOREACH (devs[CRAS_STREAM_OUTPUT].iodevs, dev) {
- if (dev->set_volume && cras_iodev_is_open(dev))
- dev->set_volume(dev);
- }
-}
-
-/* Called when the system mute state changes. Pass the current mute setting
- * to the default output if it is active. */
-static void sys_mute_change(void *context, int muted, int user_muted,
- int mute_locked)
-{
- struct cras_iodev *dev;
- int should_mute = muted || user_muted;
-
- DL_FOREACH (devs[CRAS_STREAM_OUTPUT].iodevs, dev) {
- if (!cras_iodev_is_open(dev)) {
- /* For closed devices, just set its mute state. */
- cras_iodev_set_mute(dev);
- } else {
- audio_thread_dev_start_ramp(
- audio_thread, dev->info.idx,
- (should_mute ?
- CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE :
- CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE));
- }
- }
-}
-
-static void remove_all_streams_from_dev(struct cras_iodev *dev)
-{
- struct cras_rstream *rstream;
-
- audio_thread_rm_open_dev(audio_thread, dev->direction, dev->info.idx);
-
- DL_FOREACH (stream_list_get(stream_list), rstream) {
- if (rstream->apm_list == NULL)
- continue;
- cras_apm_list_remove_apm(rstream->apm_list, dev);
- }
-}
-
-/*
- * If output dev has an echo reference dev associated, add a server
- * stream to read audio data from it so APM can analyze.
- */
-static void possibly_enable_echo_reference(struct cras_iodev *dev)
-{
- if (dev->direction != CRAS_STREAM_OUTPUT)
- return;
-
- if (dev->echo_reference_dev == NULL)
- return;
-
- server_stream_create(stream_list, dev->echo_reference_dev->info.idx,
- dev->format);
-}
-
-/*
- * If output dev has an echo reference dev associated, check if there
- * is server stream opened for it and remove it.
- */
-static void possibly_disable_echo_reference(struct cras_iodev *dev)
-{
- if (dev->echo_reference_dev == NULL)
- return;
-
- server_stream_destroy(stream_list, dev->echo_reference_dev->info.idx);
-}
-
-/*
- * Removes all attached streams and close dev if it's opened.
- */
-static void close_dev(struct cras_iodev *dev)
-{
- if (!cras_iodev_is_open(dev))
- return;
-
- MAINLOG(main_log, MAIN_THREAD_DEV_CLOSE, dev->info.idx, 0, 0);
- remove_all_streams_from_dev(dev);
- dev->idle_timeout.tv_sec = 0;
- /* close echo ref first to avoid underrun in hardware */
- possibly_disable_echo_reference(dev);
- cras_iodev_close(dev);
-}
-
-static void idle_dev_check(struct cras_timer *timer, void *data)
-{
- struct enabled_dev *edev;
- struct timespec now;
- struct timespec min_idle_expiration;
- unsigned int num_idle_devs = 0;
- unsigned int min_idle_timeout_ms;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- min_idle_expiration.tv_sec = 0;
- min_idle_expiration.tv_nsec = 0;
-
- DL_FOREACH (enabled_devs[CRAS_STREAM_OUTPUT], edev) {
- if (edev->dev->idle_timeout.tv_sec == 0)
- continue;
- if (timespec_after(&now, &edev->dev->idle_timeout)) {
- close_dev(edev->dev);
- continue;
- }
- num_idle_devs++;
- if (min_idle_expiration.tv_sec == 0 ||
- timespec_after(&min_idle_expiration,
- &edev->dev->idle_timeout))
- min_idle_expiration = edev->dev->idle_timeout;
- }
-
- idle_timer = NULL;
- if (!num_idle_devs)
- return;
- if (timespec_after(&now, &min_idle_expiration)) {
- min_idle_timeout_ms = 0;
- } else {
- struct timespec timeout;
- subtract_timespecs(&min_idle_expiration, &now, &timeout);
- min_idle_timeout_ms = timespec_to_ms(&timeout);
- }
- /* Wake up when it is time to close the next idle device. Sleep for a
- * minimum of 10 milliseconds. */
- idle_timer = cras_tm_create_timer(cras_system_state_get_tm(),
- MAX(min_idle_timeout_ms, 10),
- idle_dev_check, NULL);
-}
-
-/*
- * Cancel pending init tries. Called at device initialization or when device
- * is disabled.
- */
-static void cancel_pending_init_retries(unsigned int dev_idx)
-{
- struct dev_init_retry *retry;
-
- DL_FOREACH (init_retries, retry) {
- if (retry->dev_idx != dev_idx)
- continue;
- cras_tm_cancel_timer(cras_system_state_get_tm(),
- retry->init_timer);
- DL_DELETE(init_retries, retry);
- free(retry);
- }
-}
-
-/* Open the device potentially filling the output with a pre buffer. */
-static int init_device(struct cras_iodev *dev, struct cras_rstream *rstream)
-{
- int rc;
-
- cras_iodev_exit_idle(dev);
-
- if (cras_iodev_is_open(dev))
- return 0;
- cancel_pending_init_retries(dev->info.idx);
- MAINLOG(main_log, MAIN_THREAD_DEV_INIT, dev->info.idx,
- rstream->format.num_channels, rstream->format.frame_rate);
-
- rc = cras_iodev_open(dev, rstream->cb_threshold, &rstream->format);
- if (rc)
- return rc;
-
- rc = audio_thread_add_open_dev(audio_thread, dev);
- if (rc)
- cras_iodev_close(dev);
-
- possibly_enable_echo_reference(dev);
-
- return rc;
-}
-
-static void suspend_devs()
-{
- struct enabled_dev *edev;
- struct cras_rstream *rstream;
-
- MAINLOG(main_log, MAIN_THREAD_SUSPEND_DEVS, 0, 0, 0);
-
- DL_FOREACH (stream_list_get(stream_list), rstream) {
- if (rstream->is_pinned) {
- struct cras_iodev *dev;
-
- /* Skip closing hotword stream in the first pass.
- * Closing an input device may resume hotword stream
- * with its post_close_iodev_hook so we should deal
- * with hotword stream in the second pass.
- */
- if ((rstream->flags & HOTWORD_STREAM) == HOTWORD_STREAM)
- continue;
-
- dev = find_dev(rstream->pinned_dev_idx);
- if (dev) {
- audio_thread_disconnect_stream(audio_thread,
- rstream, dev);
- if (!cras_iodev_list_dev_is_enabled(dev))
- close_dev(dev);
- }
- } else {
- audio_thread_disconnect_stream(audio_thread, rstream,
- NULL);
- }
- }
- stream_list_suspended = 1;
-
- DL_FOREACH (enabled_devs[CRAS_STREAM_OUTPUT], edev) {
- close_dev(edev->dev);
- }
- DL_FOREACH (enabled_devs[CRAS_STREAM_INPUT], edev) {
- close_dev(edev->dev);
- }
-
- /* Doing this check after all the other enabled iodevs are closed to
- * ensure preempted hotword streams obey the pause_at_suspend flag.
- */
- if (cras_system_get_hotword_pause_at_suspend()) {
- cras_iodev_list_suspend_hotword_streams();
- hotword_auto_resume = 1;
- }
-}
-
-static int stream_added_cb(struct cras_rstream *rstream);
-
-static void resume_devs()
-{
- struct enabled_dev *edev;
- struct cras_rstream *rstream;
-
- int has_output_stream = 0;
- stream_list_suspended = 0;
-
- MAINLOG(main_log, MAIN_THREAD_RESUME_DEVS, 0, 0, 0);
-
- /* Auto-resume based on the local flag in case the system state flag has
- * changed.
- */
- if (hotword_auto_resume) {
- cras_iodev_list_resume_hotword_stream();
- hotword_auto_resume = 0;
- }
-
- /*
- * To remove the short popped noise caused by applications that can not
- * stop playback "right away" after resume, we mute all output devices
- * for a short time if there is any output stream.
- */
- DL_FOREACH (stream_list_get(stream_list), rstream) {
- if (rstream->direction == CRAS_STREAM_OUTPUT)
- has_output_stream++;
- }
- if (has_output_stream) {
- DL_FOREACH (enabled_devs[CRAS_STREAM_OUTPUT], edev) {
- edev->dev->initial_ramp_request =
- CRAS_IODEV_RAMP_REQUEST_RESUME_MUTE;
- }
- }
-
- DL_FOREACH (stream_list_get(stream_list), rstream) {
- if ((rstream->flags & HOTWORD_STREAM) == HOTWORD_STREAM)
- continue;
- stream_added_cb(rstream);
- }
-}
-
-/* Called when the system audio is suspended or resumed. */
-void sys_suspend_change(void *arg, int suspended)
-{
- if (suspended)
- suspend_devs();
- else
- resume_devs();
-}
-
-/* Called when the system capture mute state changes. Pass the current capture
- * mute setting to the default input if it is active. */
-static void sys_cap_mute_change(void *context, int muted, int mute_locked)
-{
- struct cras_iodev *dev;
-
- DL_FOREACH (devs[CRAS_STREAM_INPUT].iodevs, dev) {
- if (dev->set_capture_mute && cras_iodev_is_open(dev))
- dev->set_capture_mute(dev);
- }
-}
-
-static int disable_device(struct enabled_dev *edev, bool force);
-static int enable_device(struct cras_iodev *dev);
-
-static void possibly_disable_fallback(enum CRAS_STREAM_DIRECTION dir)
-{
- struct enabled_dev *edev;
-
- DL_FOREACH (enabled_devs[dir], edev) {
- if (edev->dev == fallback_devs[dir])
- disable_device(edev, false);
- }
-}
-
-/*
- * Possibly enables fallback device to handle streams.
- * dir - output or input.
- * error - true if enable fallback device because no other iodevs can be
- * initialized successfully.
- */
-static void possibly_enable_fallback(enum CRAS_STREAM_DIRECTION dir, bool error)
-{
- if (fallback_devs[dir] == NULL)
- return;
-
- /*
- * The fallback device is a special device. It doesn't have a real
- * device to get a correct node type. Therefore, we need to set it by
- * ourselves, which indicates the reason to use this device.
- * NORMAL - Use it because of nodes changed.
- * ABNORMAL - Use it because there are no other usable devices.
- */
- if (error)
- syslog(LOG_ERR,
- "Enable fallback device because there are no other usable devices.");
-
- fallback_devs[dir]->active_node->type =
- error ? CRAS_NODE_TYPE_FALLBACK_ABNORMAL :
- CRAS_NODE_TYPE_FALLBACK_NORMAL;
- if (!cras_iodev_list_dev_is_enabled(fallback_devs[dir]))
- enable_device(fallback_devs[dir]);
-}
-
-/*
- * Adds stream to one or more open iodevs. If the stream has processing effect
- * turned on, create new APM instance and add to the list. This makes sure the
- * time consuming APM creation happens in main thread.
- */
-static int add_stream_to_open_devs(struct cras_rstream *stream,
- struct cras_iodev **iodevs,
- unsigned int num_iodevs)
-{
- int i;
- if (stream->apm_list) {
- for (i = 0; i < num_iodevs; i++)
- cras_apm_list_add_apm(stream->apm_list, iodevs[i],
- iodevs[i]->format,
- cras_iodev_is_aec_use_case(
- iodevs[i]->active_node));
- }
- return audio_thread_add_stream(audio_thread, stream, iodevs,
- num_iodevs);
-}
-
-static int init_and_attach_streams(struct cras_iodev *dev)
-{
- int rc;
- enum CRAS_STREAM_DIRECTION dir = dev->direction;
- struct cras_rstream *stream;
- int dev_enabled = cras_iodev_list_dev_is_enabled(dev);
-
- /* If called after suspend, for example bluetooth
- * profile switching, don't add back the stream list. */
- if (stream_list_suspended)
- return 0;
-
- /* If there are active streams to attach to this device,
- * open it. */
- DL_FOREACH (stream_list_get(stream_list), stream) {
- bool can_attach = 0;
-
- if (stream->direction != dir)
- continue;
- /*
- * For normal stream, if device is enabled by UI then it can
- * attach to this dev.
- */
- if (!stream->is_pinned) {
- can_attach = dev_enabled;
- }
- /*
- * If this is a pinned stream, attach it if its pinned dev id
- * matches this device or any fallback dev. Note that attaching
- * a pinned stream to fallback device is temporary. When the
- * fallback dev gets disabled in possibly_disable_fallback()
- * the check stream_list_has_pinned_stream() is key to allow
- * all streams to be removed from fallback and close it.
- */
- else if ((stream->pinned_dev_idx == dev->info.idx) ||
- (SILENT_PLAYBACK_DEVICE == dev->info.idx) ||
- (SILENT_RECORD_DEVICE == dev->info.idx)) {
- can_attach = 1;
- }
-
- if (!can_attach)
- continue;
-
- /*
- * Note that the stream list is descending ordered by channel
- * count, which guarantees the first attachable stream will have
- * the highest channel count.
- */
- rc = init_device(dev, stream);
- if (rc) {
- syslog(LOG_ERR, "Enable %s failed, rc = %d",
- dev->info.name, rc);
- return rc;
- }
- add_stream_to_open_devs(stream, &dev, 1);
- }
- return 0;
-}
-
-static void init_device_cb(struct cras_timer *timer, void *arg)
-{
- int rc;
- struct dev_init_retry *retry = (struct dev_init_retry *)arg;
- struct cras_iodev *dev = find_dev(retry->dev_idx);
-
- /*
- * First of all, remove retry record to avoid confusion to the
- * actual device init work.
- */
- DL_DELETE(init_retries, retry);
- free(retry);
-
- if (!dev || cras_iodev_is_open(dev))
- return;
-
- rc = init_and_attach_streams(dev);
- if (rc < 0)
- syslog(LOG_ERR, "Init device retry failed");
- else
- possibly_disable_fallback(dev->direction);
-}
-
-static int schedule_init_device_retry(struct cras_iodev *dev)
-{
- struct dev_init_retry *retry;
- struct cras_tm *tm = cras_system_state_get_tm();
-
- retry = (struct dev_init_retry *)calloc(1, sizeof(*retry));
- if (!retry)
- return -ENOMEM;
-
- retry->dev_idx = dev->info.idx;
- retry->init_timer = cras_tm_create_timer(tm, INIT_DEV_DELAY_MS,
- init_device_cb, retry);
- DL_APPEND(init_retries, retry);
- return 0;
-}
-
-static int init_pinned_device(struct cras_iodev *dev,
- struct cras_rstream *rstream)
-{
- int rc;
-
- cras_iodev_exit_idle(dev);
-
- if (audio_thread_is_dev_open(audio_thread, dev))
- return 0;
-
- /* Make sure the active node is configured properly, it could be
- * disabled when last normal stream removed. */
- dev->update_active_node(dev, dev->active_node->idx, 1);
-
- /* Negative EAGAIN code indicates dev will be opened later. */
- rc = init_device(dev, rstream);
- if (rc)
- return rc;
- return 0;
-}
-
-/*
- * Close device enabled by pinned stream. Since it's NOT in the enabled
- * dev list, make sure update_active_node() is called to correctly
- * configure the ALSA UCM or BT profile state.
- */
-static int close_pinned_device(struct cras_iodev *dev)
-{
- close_dev(dev);
- dev->update_active_node(dev, dev->active_node->idx, 0);
- return 0;
-}
-
-static struct cras_iodev *find_pinned_device(struct cras_rstream *rstream)
-{
- struct cras_iodev *dev;
- if (!rstream->is_pinned)
- return NULL;
-
- dev = find_dev(rstream->pinned_dev_idx);
-
- if ((rstream->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
- return dev;
-
- /* Double check node type for hotword stream */
- if (dev && dev->active_node->type != CRAS_NODE_TYPE_HOTWORD) {
- syslog(LOG_ERR, "Hotword stream pinned to invalid dev %u",
- dev->info.idx);
- return NULL;
- }
-
- return hotword_suspended ? empty_hotword_dev : dev;
-}
-
-static int pinned_stream_added(struct cras_rstream *rstream)
-{
- struct cras_iodev *dev;
- int rc;
-
- /* Check that the target device is valid for pinned streams. */
- dev = find_pinned_device(rstream);
- if (!dev)
- return -EINVAL;
-
- rc = init_pinned_device(dev, rstream);
- if (rc) {
- syslog(LOG_INFO, "init_pinned_device failed, rc %d", rc);
- return schedule_init_device_retry(dev);
- }
-
- return add_stream_to_open_devs(rstream, &dev, 1);
-}
-
-static int stream_added_cb(struct cras_rstream *rstream)
-{
- struct enabled_dev *edev;
- struct cras_iodev *iodevs[10];
- unsigned int num_iodevs;
- int rc;
- bool iodev_reopened;
-
- if (stream_list_suspended)
- return 0;
-
- MAINLOG(main_log, MAIN_THREAD_STREAM_ADDED, rstream->stream_id,
- rstream->direction, rstream->buffer_frames);
-
- if (rstream->is_pinned)
- return pinned_stream_added(rstream);
-
- /* Add the new stream to all enabled iodevs at once to avoid offset
- * in shm level between different ouput iodevs. */
- num_iodevs = 0;
- iodev_reopened = false;
- DL_FOREACH (enabled_devs[rstream->direction], edev) {
- if (num_iodevs >= ARRAY_SIZE(iodevs)) {
- syslog(LOG_ERR, "too many enabled devices");
- break;
- }
-
- if (cras_iodev_is_open(edev->dev) &&
- (rstream->format.num_channels >
- edev->dev->format->num_channels) &&
- (rstream->format.num_channels <=
- edev->dev->info.max_supported_channels)) {
- /* Re-open the device with the format of the attached
- * stream if it has higher channel count than the
- * current format of the device, and doesn't exceed the
- * max_supported_channels of the device.
- * Fallback device will be transciently enabled during
- * the device re-opening.
- */
- MAINLOG(main_log, MAIN_THREAD_DEV_REOPEN,
- rstream->format.num_channels,
- edev->dev->format->num_channels,
- edev->dev->format->frame_rate);
- syslog(LOG_INFO, "re-open %s for higher channel count",
- edev->dev->info.name);
- possibly_enable_fallback(rstream->direction, false);
- cras_iodev_list_suspend_dev(edev->dev->info.idx);
- cras_iodev_list_resume_dev(edev->dev->info.idx);
- possibly_disable_fallback(rstream->direction);
- iodev_reopened = true;
- } else {
- rc = init_device(edev->dev, rstream);
- if (rc) {
- /* Error log but don't return error here, because
- * stopping audio could block video playback.
- */
- syslog(LOG_ERR, "Init %s failed, rc = %d",
- edev->dev->info.name, rc);
- schedule_init_device_retry(edev->dev);
- continue;
- }
-
- iodevs[num_iodevs++] = edev->dev;
- }
- }
- if (num_iodevs) {
- rc = add_stream_to_open_devs(rstream, iodevs, num_iodevs);
- if (rc) {
- syslog(LOG_ERR, "adding stream to thread fail");
- return rc;
- }
- } else if (!iodev_reopened) {
- /* Enable fallback device if no other iodevs can be initialized
- * or re-opened successfully.
- * For error codes like EAGAIN and ENOENT, a new iodev will be
- * enabled soon so streams are going to route there. As for the
- * rest of the error cases, silence will be played or recorded
- * so client won't be blocked.
- * The enabled fallback device will be disabled when
- * cras_iodev_list_select_node() is called to re-select the
- * active node.
- */
- possibly_enable_fallback(rstream->direction, true);
- }
- return 0;
-}
-
-static int possibly_close_enabled_devs(enum CRAS_STREAM_DIRECTION dir)
-{
- struct enabled_dev *edev;
- const struct cras_rstream *s;
-
- /* Check if there are still default streams attached. */
- DL_FOREACH (stream_list_get(stream_list), s) {
- if (s->direction == dir && !s->is_pinned)
- return 0;
- }
-
- /* No more default streams, close any device that doesn't have a stream
- * pinned to it. */
- DL_FOREACH (enabled_devs[dir], edev) {
- if (stream_list_has_pinned_stream(stream_list,
- edev->dev->info.idx))
- continue;
- if (dir == CRAS_STREAM_INPUT) {
- close_dev(edev->dev);
- continue;
- }
- /* Allow output devs to drain before closing. */
- clock_gettime(CLOCK_MONOTONIC_RAW, &edev->dev->idle_timeout);
- add_timespecs(&edev->dev->idle_timeout, &idle_timeout_interval);
- idle_dev_check(NULL, NULL);
- }
-
- return 0;
-}
-
-static void pinned_stream_removed(struct cras_rstream *rstream)
-{
- struct cras_iodev *dev;
-
- dev = find_pinned_device(rstream);
- if (!dev)
- return;
- if (!cras_iodev_list_dev_is_enabled(dev) &&
- !stream_list_has_pinned_stream(stream_list, dev->info.idx))
- close_pinned_device(dev);
-}
-
-/* Returns the number of milliseconds left to drain this stream. This is passed
- * directly from the audio thread. */
-static int stream_removed_cb(struct cras_rstream *rstream)
-{
- enum CRAS_STREAM_DIRECTION direction = rstream->direction;
- int rc;
-
- rc = audio_thread_drain_stream(audio_thread, rstream);
- if (rc)
- return rc;
-
- MAINLOG(main_log, MAIN_THREAD_STREAM_REMOVED, rstream->stream_id, 0, 0);
-
- if (rstream->is_pinned)
- pinned_stream_removed(rstream);
-
- possibly_close_enabled_devs(direction);
-
- return 0;
-}
-
-static int enable_device(struct cras_iodev *dev)
-{
- int rc;
- struct enabled_dev *edev;
- enum CRAS_STREAM_DIRECTION dir = dev->direction;
- struct device_enabled_cb *callback;
-
- DL_FOREACH (enabled_devs[dir], edev) {
- if (edev->dev == dev)
- return -EEXIST;
- }
-
- edev = calloc(1, sizeof(*edev));
- edev->dev = dev;
- DL_APPEND(enabled_devs[dir], edev);
- dev->is_enabled = 1;
-
- rc = init_and_attach_streams(dev);
- if (rc < 0) {
- syslog(LOG_INFO, "Enable device fail, rc %d", rc);
- schedule_init_device_retry(dev);
- return rc;
- }
-
- DL_FOREACH (device_enable_cbs, callback)
- callback->enabled_cb(dev, callback->cb_data);
-
- return 0;
-}
-
-/* Set `force to true to flush any pinned streams before closing the device. */
-static int disable_device(struct enabled_dev *edev, bool force)
-{
- struct cras_iodev *dev = edev->dev;
- enum CRAS_STREAM_DIRECTION dir = dev->direction;
- struct cras_rstream *stream;
- struct device_enabled_cb *callback;
-
- MAINLOG(main_log, MAIN_THREAD_DEV_DISABLE, dev->info.idx, force, 0);
- /*
- * Remove from enabled dev list. However this dev could have a stream
- * pinned to it, only cancel pending init timers when force flag is set.
- */
- DL_DELETE(enabled_devs[dir], edev);
- free(edev);
- dev->is_enabled = 0;
- if (force) {
- cancel_pending_init_retries(dev->info.idx);
- }
- /* If there's a pinned stream exists, simply disconnect all the normal
- * streams off this device and return. */
- else if (stream_list_has_pinned_stream(stream_list, dev->info.idx)) {
- DL_FOREACH (stream_list_get(stream_list), stream) {
- if (stream->direction != dev->direction)
- continue;
- if (stream->is_pinned)
- continue;
- audio_thread_disconnect_stream(audio_thread, stream,
- dev);
- }
- return 0;
- }
-
- DL_FOREACH (device_enable_cbs, callback)
- callback->disabled_cb(dev, callback->cb_data);
- close_dev(dev);
- dev->update_active_node(dev, dev->active_node->idx, 0);
-
- return 0;
-}
-
-/*
- * Exported Interface.
- */
-
-void cras_iodev_list_init()
-{
- struct cras_observer_ops observer_ops;
-
- memset(&observer_ops, 0, sizeof(observer_ops));
- observer_ops.output_volume_changed = sys_vol_change;
- observer_ops.output_mute_changed = sys_mute_change;
- observer_ops.capture_mute_changed = sys_cap_mute_change;
- observer_ops.suspend_changed = sys_suspend_change;
- list_observer = cras_observer_add(&observer_ops, NULL);
- idle_timer = NULL;
-
- main_log = main_thread_event_log_init();
-
- /* Create the audio stream list for the system. */
- stream_list =
- stream_list_create(stream_added_cb, stream_removed_cb,
- cras_rstream_create, cras_rstream_destroy,
- cras_system_state_get_tm());
-
- /* Add an empty device so there is always something to play to or
- * capture from. */
- fallback_devs[CRAS_STREAM_OUTPUT] = empty_iodev_create(
- CRAS_STREAM_OUTPUT, CRAS_NODE_TYPE_FALLBACK_NORMAL);
- fallback_devs[CRAS_STREAM_INPUT] = empty_iodev_create(
- CRAS_STREAM_INPUT, CRAS_NODE_TYPE_FALLBACK_NORMAL);
- enable_device(fallback_devs[CRAS_STREAM_OUTPUT]);
- enable_device(fallback_devs[CRAS_STREAM_INPUT]);
-
- empty_hotword_dev =
- empty_iodev_create(CRAS_STREAM_INPUT, CRAS_NODE_TYPE_HOTWORD);
-
- /* Create loopback devices. */
- loopdev_post_mix = loopback_iodev_create(LOOPBACK_POST_MIX_PRE_DSP);
- loopdev_post_dsp = loopback_iodev_create(LOOPBACK_POST_DSP);
-
- audio_thread = audio_thread_create();
- if (!audio_thread) {
- syslog(LOG_ERR, "Fatal: audio thread init");
- exit(-ENOMEM);
- }
- audio_thread_start(audio_thread);
-
- cras_iodev_list_update_device_list();
-}
-
-void cras_iodev_list_deinit()
-{
- audio_thread_destroy(audio_thread);
- loopback_iodev_destroy(loopdev_post_dsp);
- loopback_iodev_destroy(loopdev_post_mix);
- empty_iodev_destroy(empty_hotword_dev);
- empty_iodev_destroy(fallback_devs[CRAS_STREAM_INPUT]);
- empty_iodev_destroy(fallback_devs[CRAS_STREAM_OUTPUT]);
- stream_list_destroy(stream_list);
- main_thread_event_log_deinit(main_log);
- if (list_observer) {
- cras_observer_remove(list_observer);
- list_observer = NULL;
- }
-}
-
-int cras_iodev_list_dev_is_enabled(const struct cras_iodev *dev)
-{
- struct enabled_dev *edev;
-
- DL_FOREACH (enabled_devs[dev->direction], edev) {
- if (edev->dev == dev)
- return 1;
- }
-
- return 0;
-}
-
-void cras_iodev_list_enable_dev(struct cras_iodev *dev)
-{
- possibly_disable_fallback(dev->direction);
- /* Enable ucm setting of active node. */
- dev->update_active_node(dev, dev->active_node->idx, 1);
- enable_device(dev);
- cras_iodev_list_notify_active_node_changed(dev->direction);
-}
-
-void cras_iodev_list_add_active_node(enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_iodev *new_dev;
- new_dev = find_dev(dev_index_of(node_id));
- if (!new_dev || new_dev->direction != dir)
- return;
-
- MAINLOG(main_log, MAIN_THREAD_ADD_ACTIVE_NODE, new_dev->info.idx, 0, 0);
-
- /* If the new dev is already enabled but its active node needs to be
- * changed. Disable new dev first, update active node, and then
- * re-enable it again.
- */
- if (cras_iodev_list_dev_is_enabled(new_dev)) {
- if (node_index_of(node_id) == new_dev->active_node->idx)
- return;
- else
- cras_iodev_list_disable_dev(new_dev, true);
- }
-
- new_dev->update_active_node(new_dev, node_index_of(node_id), 1);
- cras_iodev_list_enable_dev(new_dev);
-}
-
-/*
- * Disables device which may or may not be in enabled_devs list.
- */
-void cras_iodev_list_disable_dev(struct cras_iodev *dev, bool force_close)
-{
- struct enabled_dev *edev, *edev_to_disable = NULL;
-
- int is_the_only_enabled_device = 1;
-
- DL_FOREACH (enabled_devs[dev->direction], edev) {
- if (edev->dev == dev)
- edev_to_disable = edev;
- else
- is_the_only_enabled_device = 0;
- }
-
- /*
- * Disables the device for these two cases:
- * 1. Disable a device in the enabled_devs list.
- * 2. Force close a device that is not in the enabled_devs list,
- * but it is running a pinned stream.
- */
- if (!edev_to_disable) {
- if (force_close)
- close_pinned_device(dev);
- return;
- }
-
- /* If the device to be closed is the only enabled device, we should
- * enable the fallback device first then disable the target
- * device. */
- if (is_the_only_enabled_device && fallback_devs[dev->direction])
- enable_device(fallback_devs[dev->direction]);
-
- disable_device(edev_to_disable, force_close);
-
- cras_iodev_list_notify_active_node_changed(dev->direction);
- return;
-}
-
-void cras_iodev_list_suspend_dev(unsigned int dev_idx)
-{
- struct cras_iodev *dev = find_dev(dev_idx);
-
- if (!dev)
- return;
-
- /* Remove all streams including the pinned streams, and close
- * this iodev. */
- close_dev(dev);
- dev->update_active_node(dev, dev->active_node->idx, 0);
-}
-
-void cras_iodev_list_resume_dev(unsigned int dev_idx)
-{
- struct cras_iodev *dev = find_dev(dev_idx);
- int rc;
-
- if (!dev)
- return;
-
- dev->update_active_node(dev, dev->active_node->idx, 1);
- rc = init_and_attach_streams(dev);
- if (rc == 0) {
- /* If dev initialize succeeded and this is not a pinned device,
- * disable the silent fallback device because it's just
- * unnecessary. */
- if (!stream_list_has_pinned_stream(stream_list, dev_idx))
- possibly_disable_fallback(dev->direction);
- } else {
- syslog(LOG_INFO, "Enable dev fail at resume, rc %d", rc);
- schedule_init_device_retry(dev);
- }
-}
-
-void cras_iodev_list_set_dev_mute(unsigned int dev_idx)
-{
- struct cras_iodev *dev;
-
- dev = find_dev(dev_idx);
- if (!dev)
- return;
-
- cras_iodev_set_mute(dev);
-}
-
-void cras_iodev_list_rm_active_node(enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_iodev *dev;
-
- dev = find_dev(dev_index_of(node_id));
- if (!dev)
- return;
-
- cras_iodev_list_disable_dev(dev, false);
-}
-
-int cras_iodev_list_add_output(struct cras_iodev *output)
-{
- int rc;
-
- if (output->direction != CRAS_STREAM_OUTPUT)
- return -EINVAL;
-
- rc = add_dev_to_list(output);
- if (rc)
- return rc;
-
- MAINLOG(main_log, MAIN_THREAD_ADD_TO_DEV_LIST, output->info.idx,
- CRAS_STREAM_OUTPUT, 0);
- return 0;
-}
-
-int cras_iodev_list_add_input(struct cras_iodev *input)
-{
- int rc;
-
- if (input->direction != CRAS_STREAM_INPUT)
- return -EINVAL;
-
- rc = add_dev_to_list(input);
- if (rc)
- return rc;
-
- MAINLOG(main_log, MAIN_THREAD_ADD_TO_DEV_LIST, input->info.idx,
- CRAS_STREAM_INPUT, 0);
- return 0;
-}
-
-int cras_iodev_list_rm_output(struct cras_iodev *dev)
-{
- int res;
-
- /* Retire the current active output device before removing it from
- * list, otherwise it could be busy and remain in the list.
- */
- cras_iodev_list_disable_dev(dev, true);
- res = rm_dev_from_list(dev);
- if (res == 0)
- cras_iodev_list_update_device_list();
- return res;
-}
-
-int cras_iodev_list_rm_input(struct cras_iodev *dev)
-{
- int res;
-
- /* Retire the current active input device before removing it from
- * list, otherwise it could be busy and remain in the list.
- */
- cras_iodev_list_disable_dev(dev, true);
- res = rm_dev_from_list(dev);
- if (res == 0)
- cras_iodev_list_update_device_list();
- return res;
-}
-
-int cras_iodev_list_get_outputs(struct cras_iodev_info **list_out)
-{
- return get_dev_list(&devs[CRAS_STREAM_OUTPUT], list_out);
-}
-
-int cras_iodev_list_get_inputs(struct cras_iodev_info **list_out)
-{
- return get_dev_list(&devs[CRAS_STREAM_INPUT], list_out);
-}
-
-struct cras_iodev *
-cras_iodev_list_get_first_enabled_iodev(enum CRAS_STREAM_DIRECTION direction)
-{
- struct enabled_dev *edev = enabled_devs[direction];
-
- return edev ? edev->dev : NULL;
-}
-
-struct cras_iodev *
-cras_iodev_list_get_sco_pcm_iodev(enum CRAS_STREAM_DIRECTION direction)
-{
- struct cras_iodev *dev;
- struct cras_ionode *node;
-
- DL_FOREACH (devs[direction].iodevs, dev) {
- DL_FOREACH (dev->nodes, node) {
- if (node->is_sco_pcm)
- return dev;
- }
- }
-
- return NULL;
-}
-
-cras_node_id_t
-cras_iodev_list_get_active_node_id(enum CRAS_STREAM_DIRECTION direction)
-{
- struct enabled_dev *edev = enabled_devs[direction];
-
- if (!edev || !edev->dev || !edev->dev->active_node)
- return 0;
-
- return cras_make_node_id(edev->dev->info.idx,
- edev->dev->active_node->idx);
-}
-
-void cras_iodev_list_update_device_list()
-{
- struct cras_server_state *state;
-
- state = cras_system_state_update_begin();
- if (!state)
- return;
-
- state->num_output_devs = devs[CRAS_STREAM_OUTPUT].size;
- state->num_input_devs = devs[CRAS_STREAM_INPUT].size;
- fill_dev_list(&devs[CRAS_STREAM_OUTPUT], &state->output_devs[0],
- CRAS_MAX_IODEVS);
- fill_dev_list(&devs[CRAS_STREAM_INPUT], &state->input_devs[0],
- CRAS_MAX_IODEVS);
-
- state->num_output_nodes =
- fill_node_list(&devs[CRAS_STREAM_OUTPUT],
- &state->output_nodes[0], CRAS_MAX_IONODES);
- state->num_input_nodes =
- fill_node_list(&devs[CRAS_STREAM_INPUT], &state->input_nodes[0],
- CRAS_MAX_IONODES);
-
- cras_system_state_update_complete();
-}
-
-/* Look up the first hotword stream and the device it pins to. */
-int find_hotword_stream_dev(struct cras_iodev **dev,
- struct cras_rstream **stream)
-{
- DL_FOREACH (stream_list_get(stream_list), *stream) {
- if (((*stream)->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
- continue;
-
- *dev = find_dev((*stream)->pinned_dev_idx);
- if (*dev == NULL)
- return -ENOENT;
- break;
- }
- return 0;
-}
-
-/* Suspend/resume hotword streams functions are used to provide seamless
- * experience to cras clients when there's hardware limitation about concurrent
- * DSP and normal recording. The empty hotword iodev is used to hold all
- * hotword streams during suspend, so client side will not know about the
- * transition, and can still remove or add streams. At resume, the real hotword
- * device will be initialized and opened again to re-arm the DSP.
- */
-int cras_iodev_list_suspend_hotword_streams()
-{
- struct cras_iodev *hotword_dev;
- struct cras_rstream *stream = NULL;
- int rc;
-
- rc = find_hotword_stream_dev(&hotword_dev, &stream);
- if (rc)
- return rc;
-
- if (stream == NULL) {
- hotword_suspended = 1;
- return 0;
- }
- /* Move all existing hotword streams to the empty hotword iodev. */
- init_pinned_device(empty_hotword_dev, stream);
- DL_FOREACH (stream_list_get(stream_list), stream) {
- if ((stream->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
- continue;
- if (stream->pinned_dev_idx != hotword_dev->info.idx) {
- syslog(LOG_ERR,
- "Failed to suspend hotword stream on dev %u",
- stream->pinned_dev_idx);
- continue;
- }
-
- audio_thread_disconnect_stream(audio_thread, stream,
- hotword_dev);
- audio_thread_add_stream(audio_thread, stream,
- &empty_hotword_dev, 1);
- }
- close_pinned_device(hotword_dev);
- hotword_suspended = 1;
- return 0;
-}
-
-int cras_iodev_list_resume_hotword_stream()
-{
- struct cras_iodev *hotword_dev;
- struct cras_rstream *stream = NULL;
- int rc;
-
- rc = find_hotword_stream_dev(&hotword_dev, &stream);
- if (rc)
- return rc;
-
- if (stream == NULL) {
- hotword_suspended = 0;
- return 0;
- }
- /* Move all existing hotword streams to the real hotword iodev. */
- init_pinned_device(hotword_dev, stream);
- DL_FOREACH (stream_list_get(stream_list), stream) {
- if ((stream->flags & HOTWORD_STREAM) != HOTWORD_STREAM)
- continue;
- if (stream->pinned_dev_idx != hotword_dev->info.idx) {
- syslog(LOG_ERR,
- "Fail to resume hotword stream on dev %u",
- stream->pinned_dev_idx);
- continue;
- }
-
- audio_thread_disconnect_stream(audio_thread, stream,
- empty_hotword_dev);
- audio_thread_add_stream(audio_thread, stream, &hotword_dev, 1);
- }
- close_pinned_device(empty_hotword_dev);
- hotword_suspended = 0;
- return 0;
-}
-
-char *cras_iodev_list_get_hotword_models(cras_node_id_t node_id)
-{
- struct cras_iodev *dev = NULL;
-
- dev = find_dev(dev_index_of(node_id));
- if (!dev || !dev->get_hotword_models ||
- (dev->active_node->type != CRAS_NODE_TYPE_HOTWORD))
- return NULL;
-
- return dev->get_hotword_models(dev);
-}
-
-int cras_iodev_list_set_hotword_model(cras_node_id_t node_id,
- const char *model_name)
-{
- int ret;
- struct cras_iodev *dev = find_dev(dev_index_of(node_id));
- if (!dev || !dev->get_hotword_models ||
- (dev->active_node->type != CRAS_NODE_TYPE_HOTWORD))
- return -EINVAL;
-
- ret = dev->set_hotword_model(dev, model_name);
- if (!ret)
- strncpy(dev->active_node->active_hotword_model, model_name,
- sizeof(dev->active_node->active_hotword_model) - 1);
- return ret;
-}
-
-void cras_iodev_list_notify_nodes_changed()
-{
- cras_observer_notify_nodes();
-}
-
-void cras_iodev_list_notify_active_node_changed(
- enum CRAS_STREAM_DIRECTION direction)
-{
- cras_observer_notify_active_node(
- direction, cras_iodev_list_get_active_node_id(direction));
-}
-
-void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id)
-{
- struct cras_iodev *new_dev = NULL;
- struct enabled_dev *edev;
- int new_node_already_enabled = 0;
- struct cras_rstream *rstream;
- int has_output_stream = 0;
- int rc;
-
- /* find the devices for the id. */
- new_dev = find_dev(dev_index_of(node_id));
-
- MAINLOG(main_log, MAIN_THREAD_SELECT_NODE, dev_index_of(node_id), 0, 0);
-
- /* Do nothing if the direction is mismatched. The new_dev == NULL case
- could happen if node_id is 0 (no selection), or the client tries
- to select a non-existing node (maybe it's unplugged just before
- the client selects it). We will just behave like there is no selected
- node. */
- if (new_dev && new_dev->direction != direction)
- return;
-
- /* Determine whether the new device and node are already enabled - if
- * they are, the selection algorithm should avoid disabling the new
- * device. */
- DL_FOREACH (enabled_devs[direction], edev) {
- if (edev->dev == new_dev &&
- edev->dev->active_node->idx == node_index_of(node_id)) {
- new_node_already_enabled = 1;
- break;
- }
- }
-
- /* Enable fallback device during the transition so client will not be
- * blocked in this duration, which is as long as 300 ms on some boards
- * before new device is opened.
- * Note that the fallback node is not needed if the new node is already
- * enabled - the new node will remain enabled. */
- if (!new_node_already_enabled)
- possibly_enable_fallback(direction, false);
-
- DL_FOREACH (enabled_devs[direction], edev) {
- /* Don't disable fallback devices. */
- if (edev->dev == fallback_devs[direction])
- continue;
- /*
- * Disable enabled device if it's not the new one, use non-force
- * disable call so we don't interrupt existing pinned streams on
- * it.
- */
- if (edev->dev != new_dev) {
- disable_device(edev, false);
- }
- /*
- * Otherwise if this happens to be the new device but about to
- * select to a different node (on the same dev). Force disable
- * this device to avoid any pinned stream occupies it in audio
- * thread and cause problem in later update_active_node call.
- */
- else if (!new_node_already_enabled) {
- disable_device(edev, true);
- }
- }
-
- if (new_dev && !new_node_already_enabled) {
- new_dev->update_active_node(new_dev, node_index_of(node_id), 1);
-
- /* To reduce the popped noise of active device change, mute
- * new_dev's for RAMP_SWITCH_MUTE_DURATION_SECS s.
- */
- DL_FOREACH (stream_list_get(stream_list), rstream) {
- if (rstream->direction == CRAS_STREAM_OUTPUT)
- has_output_stream++;
- }
- if (direction == CRAS_STREAM_OUTPUT && has_output_stream) {
- new_dev->initial_ramp_request =
- CRAS_IODEV_RAMP_REQUEST_SWITCH_MUTE;
- }
-
- rc = enable_device(new_dev);
- if (rc == 0) {
- /* Disable fallback device after new device is enabled.
- * Leave the fallback device enabled if new_dev failed
- * to open, or the new_dev == NULL case. */
- possibly_disable_fallback(direction);
- }
- }
-
- cras_iodev_list_notify_active_node_changed(direction);
-}
-
-static int set_node_plugged(struct cras_iodev *iodev, unsigned int node_idx,
- int plugged)
-{
- struct cras_ionode *node;
-
- node = find_node(iodev, node_idx);
- if (!node)
- return -EINVAL;
- cras_iodev_set_node_plugged(node, plugged);
- return 0;
-}
-
-static int set_node_volume(struct cras_iodev *iodev, unsigned int node_idx,
- int volume)
-{
- struct cras_ionode *node;
-
- node = find_node(iodev, node_idx);
- if (!node)
- return -EINVAL;
-
- if (iodev->ramp && cras_iodev_software_volume_needed(iodev) &&
- !cras_system_get_mute())
- cras_iodev_start_volume_ramp(iodev, node->volume, volume);
-
- node->volume = volume;
- if (iodev->set_volume)
- iodev->set_volume(iodev);
- cras_iodev_list_notify_node_volume(node);
- MAINLOG(main_log, MAIN_THREAD_OUTPUT_NODE_VOLUME, iodev->info.idx,
- volume, 0);
- return 0;
-}
-
-static int set_node_capture_gain(struct cras_iodev *iodev,
- unsigned int node_idx, int value)
-{
- struct cras_ionode *node;
- int db_scale;
-
- node = find_node(iodev, node_idx);
- if (!node)
- return -EINVAL;
-
- /* Assert value in range 0 - 100. */
- if (value < 0)
- value = 0;
- if (value > 100)
- value = 100;
-
- /* Linear maps (0, 50) to (-4000, 0) and (50, 100) to (0, 2000) dBFS.
- * Calculate and store corresponding scaler in ui_gain_scaler. */
- db_scale = (value > 50) ? 40 : 80;
- node->ui_gain_scaler =
- convert_softvol_scaler_from_dB((value - 50) * db_scale);
-
- if (iodev->set_capture_gain)
- iodev->set_capture_gain(iodev);
- cras_iodev_list_notify_node_capture_gain(node);
- MAINLOG(main_log, MAIN_THREAD_INPUT_NODE_GAIN, iodev->info.idx, value,
- 0);
- return 0;
-}
-
-static int set_node_left_right_swapped(struct cras_iodev *iodev,
- unsigned int node_idx,
- int left_right_swapped)
-{
- struct cras_ionode *node;
- int rc;
-
- if (!iodev->set_swap_mode_for_node)
- return -EINVAL;
- node = find_node(iodev, node_idx);
- if (!node)
- return -EINVAL;
-
- rc = iodev->set_swap_mode_for_node(iodev, node, left_right_swapped);
- if (rc) {
- syslog(LOG_ERR, "Failed to set swap mode on node %s to %d",
- node->name, left_right_swapped);
- return rc;
- }
- node->left_right_swapped = left_right_swapped;
- cras_iodev_list_notify_node_left_right_swapped(node);
- return 0;
-}
-
-int cras_iodev_list_set_node_attr(cras_node_id_t node_id, enum ionode_attr attr,
- int value)
-{
- struct cras_iodev *iodev;
- int rc = 0;
-
- iodev = find_dev(dev_index_of(node_id));
- if (!iodev)
- return -EINVAL;
-
- switch (attr) {
- case IONODE_ATTR_PLUGGED:
- rc = set_node_plugged(iodev, node_index_of(node_id), value);
- break;
- case IONODE_ATTR_VOLUME:
- rc = set_node_volume(iodev, node_index_of(node_id), value);
- break;
- case IONODE_ATTR_CAPTURE_GAIN:
- rc = set_node_capture_gain(iodev, node_index_of(node_id),
- value);
- break;
- case IONODE_ATTR_SWAP_LEFT_RIGHT:
- rc = set_node_left_right_swapped(iodev, node_index_of(node_id),
- value);
- break;
- default:
- return -EINVAL;
- }
-
- return rc;
-}
-
-void cras_iodev_list_notify_node_volume(struct cras_ionode *node)
-{
- cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
- cras_iodev_list_update_device_list();
- cras_observer_notify_output_node_volume(id, node->volume);
-}
-
-void cras_iodev_list_notify_node_left_right_swapped(struct cras_ionode *node)
-{
- cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
- cras_iodev_list_update_device_list();
- cras_observer_notify_node_left_right_swapped(id,
- node->left_right_swapped);
-}
-
-void cras_iodev_list_notify_node_capture_gain(struct cras_ionode *node)
-{
- cras_node_id_t id = cras_make_node_id(node->dev->info.idx, node->idx);
- cras_iodev_list_update_device_list();
- cras_observer_notify_input_node_gain(id, node->capture_gain);
-}
-
-void cras_iodev_list_add_test_dev(enum TEST_IODEV_TYPE type)
-{
- if (type != TEST_IODEV_HOTWORD)
- return;
- test_iodev_create(CRAS_STREAM_INPUT, type);
-}
-
-void cras_iodev_list_test_dev_command(unsigned int iodev_idx,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len,
- const uint8_t *data)
-{
- struct cras_iodev *dev = find_dev(iodev_idx);
-
- if (!dev)
- return;
-
- test_iodev_command(dev, command, data_len, data);
-}
-
-struct audio_thread *cras_iodev_list_get_audio_thread()
-{
- return audio_thread;
-}
-
-struct stream_list *cras_iodev_list_get_stream_list()
-{
- return stream_list;
-}
-
-int cras_iodev_list_set_device_enabled_callback(
- device_enabled_callback_t enabled_cb,
- device_disabled_callback_t disabled_cb, void *cb_data)
-{
- struct device_enabled_cb *callback;
-
- DL_FOREACH (device_enable_cbs, callback) {
- if (callback->cb_data != cb_data)
- continue;
-
- DL_DELETE(device_enable_cbs, callback);
- free(callback);
- }
-
- if (enabled_cb && disabled_cb) {
- callback = (struct device_enabled_cb *)calloc(
- 1, sizeof(*callback));
- callback->enabled_cb = enabled_cb;
- callback->disabled_cb = disabled_cb;
- callback->cb_data = cb_data;
- DL_APPEND(device_enable_cbs, callback);
- }
-
- return 0;
-}
-
-void cras_iodev_list_register_loopback(enum CRAS_LOOPBACK_TYPE loopback_type,
- unsigned int output_dev_idx,
- loopback_hook_data_t hook_data,
- loopback_hook_control_t hook_control,
- unsigned int loopback_dev_idx)
-{
- struct cras_iodev *iodev = find_dev(output_dev_idx);
- struct cras_iodev *loopback_dev;
- struct cras_loopback *loopback;
- bool dev_open;
-
- if (iodev == NULL) {
- syslog(LOG_ERR, "Output dev %u not found for loopback",
- output_dev_idx);
- return;
- }
-
- loopback_dev = find_dev(loopback_dev_idx);
- if (loopback_dev == NULL) {
- syslog(LOG_ERR, "Loopback dev %u not found", loopback_dev_idx);
- return;
- }
-
- dev_open = cras_iodev_is_open(iodev);
-
- loopback = (struct cras_loopback *)calloc(1, sizeof(*loopback));
- if (NULL == loopback) {
- syslog(LOG_ERR, "Not enough memory for loopback");
- return;
- }
-
- loopback->type = loopback_type;
- loopback->hook_data = hook_data;
- loopback->hook_control = hook_control;
- loopback->cb_data = loopback_dev;
- if (loopback->hook_control && dev_open)
- loopback->hook_control(true, loopback->cb_data);
-
- DL_APPEND(iodev->loopbacks, loopback);
-}
-
-void cras_iodev_list_unregister_loopback(enum CRAS_LOOPBACK_TYPE type,
- unsigned int output_dev_idx,
- unsigned int loopback_dev_idx)
-{
- struct cras_iodev *iodev = find_dev(output_dev_idx);
- struct cras_iodev *loopback_dev;
- struct cras_loopback *loopback;
-
- if (iodev == NULL)
- return;
-
- loopback_dev = find_dev(loopback_dev_idx);
- if (loopback_dev == NULL)
- return;
-
- DL_FOREACH (iodev->loopbacks, loopback) {
- if ((loopback->cb_data == loopback_dev) &&
- (loopback->type == type)) {
- DL_DELETE(iodev->loopbacks, loopback);
- free(loopback);
- }
- }
-}
-
-void cras_iodev_list_reset_for_noise_cancellation()
-{
- struct cras_iodev *dev;
- bool enabled = cras_system_get_noise_cancellation_enabled();
-
- DL_FOREACH (devs[CRAS_STREAM_INPUT].iodevs, dev) {
- if (!cras_iodev_is_open(dev) ||
- !cras_iodev_support_noise_cancellation(dev))
- continue;
- syslog(LOG_INFO, "Re-open %s for %s noise cancellation",
- dev->info.name, enabled ? "enabling" : "disabling");
- possibly_enable_fallback(CRAS_STREAM_INPUT, false);
- cras_iodev_list_suspend_dev(dev->info.idx);
- cras_iodev_list_resume_dev(dev->info.idx);
- possibly_disable_fallback(CRAS_STREAM_INPUT);
- }
-}
-
-void cras_iodev_list_reset()
-{
- struct enabled_dev *edev;
-
- DL_FOREACH (enabled_devs[CRAS_STREAM_OUTPUT], edev) {
- DL_DELETE(enabled_devs[CRAS_STREAM_OUTPUT], edev);
- free(edev);
- }
- enabled_devs[CRAS_STREAM_OUTPUT] = NULL;
- DL_FOREACH (enabled_devs[CRAS_STREAM_INPUT], edev) {
- DL_DELETE(enabled_devs[CRAS_STREAM_INPUT], edev);
- free(edev);
- }
- enabled_devs[CRAS_STREAM_INPUT] = NULL;
- devs[CRAS_STREAM_OUTPUT].iodevs = NULL;
- devs[CRAS_STREAM_INPUT].iodevs = NULL;
- devs[CRAS_STREAM_OUTPUT].size = 0;
- devs[CRAS_STREAM_INPUT].size = 0;
-}
diff --git a/cras/src/server/cras_iodev_list.h b/cras/src/server/cras_iodev_list.h
deleted file mode 100644
index d6e9ba54..00000000
--- a/cras/src/server/cras_iodev_list.h
+++ /dev/null
@@ -1,285 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * IO list manages the list of inputs and outputs available.
- */
-#ifndef CRAS_IODEV_LIST_H_
-#define CRAS_IODEV_LIST_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include "cras_iodev.h"
-#include "cras_types.h"
-
-struct cras_rclient;
-struct stream_list;
-
-/* Device enabled/disabled callback. */
-typedef void (*device_enabled_callback_t)(struct cras_iodev *dev,
- void *cb_data);
-typedef void (*device_disabled_callback_t)(struct cras_iodev *dev,
- void *cb_data);
-
-/* Initialize the list of iodevs. */
-void cras_iodev_list_init();
-
-/* Clean up any resources used by iodev. */
-void cras_iodev_list_deinit();
-
-/* Adds an output to the output list.
- * Args:
- * output - the output to add.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_iodev_list_add_output(struct cras_iodev *output);
-
-/* Adds an input to the input list.
- * Args:
- * input - the input to add.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_iodev_list_add_input(struct cras_iodev *input);
-
-/* Removes an output from the output list.
- * Args:
- * output - the output to remove.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_iodev_list_rm_output(struct cras_iodev *output);
-
-/* Removes an input from the input list.
- * Args:
- * output - the input to remove.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int cras_iodev_list_rm_input(struct cras_iodev *input);
-
-/* Gets a list of outputs. Callee must free the list when finished. If list_out
- * is NULL, this function can be used to return the number of outputs.
- * Args:
- * list_out - This will be set to the malloc'd area containing the list of
- * devices. Ignored if NULL.
- * Returns:
- * The number of devices on the list.
- */
-int cras_iodev_list_get_outputs(struct cras_iodev_info **list_out);
-
-/* Gets a list of inputs. Callee must free the list when finished. If list_out
- * is NULL, this function can be used to return the number of inputs.
- * Args:
- * list_out - This will be set to the malloc'd area containing the list of
- * devices. Ignored if NULL.
- * Returns:
- * The number of devices on the list.
- */
-int cras_iodev_list_get_inputs(struct cras_iodev_info **list_out);
-
-/* Returns the first enabled device.
- * Args:
- * direction - Playback or capture.
- * Returns:
- * Pointer to the first enabled device of direction.
- */
-struct cras_iodev *
-cras_iodev_list_get_first_enabled_iodev(enum CRAS_STREAM_DIRECTION direction);
-
-/* Returns SCO PCM device.
- * Args:
- * direction - Playback or capture.
- * Returns:
- * Pointer to the SCO PCM device of direction.
- */
-struct cras_iodev *
-cras_iodev_list_get_sco_pcm_iodev(enum CRAS_STREAM_DIRECTION direction);
-
-/* Returns the active node id.
- * Args:
- * direction - Playback or capture.
- * Returns:
- * The id of the active node.
- */
-cras_node_id_t
-cras_iodev_list_get_active_node_id(enum CRAS_STREAM_DIRECTION direction);
-
-/* Stores the following data to the shared memory server state region:
- * (1) device list
- * (2) node list
- * (3) selected nodes
- */
-void cras_iodev_list_update_device_list();
-
-/* Stores the node list in the shared memory server state region. */
-void cras_iodev_list_update_node_list();
-
-/* Gets the supported hotword models of an ionode. Caller should free
- * the returned string after use. */
-char *cras_iodev_list_get_hotword_models(cras_node_id_t node_id);
-
-/* Sets the desired hotword model to an ionode. */
-int cras_iodev_list_set_hotword_model(cras_node_id_t id,
- const char *model_name);
-
-/* Notify that nodes are added/removed. */
-void cras_iodev_list_notify_nodes_changed();
-
-/* Notify that active node is changed for the given direction.
- * Args:
- * direction - Direction of the node.
- */
-void cras_iodev_list_notify_active_node_changed(
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Sets an attribute of an ionode on a device.
- * Args:
- * id - the id of the ionode.
- * node_index - Index of the ionode on the device.
- * attr - the attribute we want to change.
- * value - the value we want to set.
- */
-int cras_iodev_list_set_node_attr(cras_node_id_t id, enum ionode_attr attr,
- int value);
-
-/* Select a node as the preferred node.
- * Args:
- * direction - Playback or capture.
- * node_id - the id of the ionode to be selected. As a special case, if
- * node_id is 0, don't select any node in this direction.
- */
-void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/*
- * Checks if an iodev is enabled. By enabled we mean all default streams will
- * be routed to this iodev.
- */
-int cras_iodev_list_dev_is_enabled(const struct cras_iodev *dev);
-
-/* Enables an iodev. If the fallback device was already enabled, this
- * call will disable it. */
-void cras_iodev_list_enable_dev(struct cras_iodev *dev);
-
-/*
- * Suspends the connection of all types of stream attached to given iodev.
- * This call doesn't disable the given iodev.
- */
-void cras_iodev_list_suspend_dev(unsigned int dev_idx);
-
-/*
- * Resumes the connection of all types of stream attached to given iodev.
- * This call doesn't enable the given dev.
- */
-void cras_iodev_list_resume_dev(unsigned int dev_idx);
-
-/*
- * Sets mute state to device of given index.
- * Args:
- * dev_idx - Index of the device to set mute state.
- */
-void cras_iodev_list_set_dev_mute(unsigned int dev_idx);
-
-/*
- * Disables an iodev. If this is the last device to disable, the
- * fallback devices will be enabled accordingly.
- * Set `foce_close` to true if the device must be closed regardless of having
- * pinned streams attached.
- */
-void cras_iodev_list_disable_dev(struct cras_iodev *dev, bool force_close);
-
-/* Adds a node to the active devices list.
- * Args:
- * direction - Playback or capture.
- * node_id - The id of the ionode to be added.
- */
-void cras_iodev_list_add_active_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/* Removes a node from the active devices list.
- * Args:
- * direction - Playback or capture.
- * node_id - The id of the ionode to be removed.
- */
-void cras_iodev_list_rm_active_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id);
-
-/* Returns 1 if the node is selected, 0 otherwise. */
-int cras_iodev_list_node_selected(struct cras_ionode *node);
-
-/* Notify the current volume of the given node. */
-void cras_iodev_list_notify_node_volume(struct cras_ionode *node);
-
-/* Notify the current capture gain of the given node. */
-void cras_iodev_list_notify_node_capture_gain(struct cras_ionode *node);
-
-/* Notify the current left right channel swapping state of the given node. */
-void cras_iodev_list_notify_node_left_right_swapped(struct cras_ionode *node);
-
-/* Handles the adding and removing of test iodevs. */
-void cras_iodev_list_add_test_dev(enum TEST_IODEV_TYPE type);
-
-/* Handles sending a command to a test iodev. */
-void cras_iodev_list_test_dev_command(unsigned int iodev_idx,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len,
- const uint8_t *data);
-
-/* Gets the audio thread used by the devices. */
-struct audio_thread *cras_iodev_list_get_audio_thread();
-
-/* Gets the list of all active audio streams attached to devices. */
-struct stream_list *cras_iodev_list_get_stream_list();
-
-/* Sets the function to call when a device is enabled or disabled. */
-int cras_iodev_list_set_device_enabled_callback(
- device_enabled_callback_t enabled_cb,
- device_disabled_callback_t disabled_cb, void *cb_data);
-
-/* Registers loopback to an output device.
- * Args:
- * loopback_type - Pre or post software DSP.
- * output_dev_idx - Index of the target output device.
- * hook_data - Callback function to process loopback data.
- * hook_start - Callback for starting or stopping loopback.
- * loopback_dev_idx - Index of the loopback device that
- * listens for output data.
- */
-void cras_iodev_list_register_loopback(enum CRAS_LOOPBACK_TYPE loopback_type,
- unsigned int output_dev_idx,
- loopback_hook_data_t hook_data,
- loopback_hook_control_t hook_start,
- unsigned int loopback_dev_idx);
-
-/* Unregisters loopback from an output device by matching
- * loopback type and loopback device index.
- * Args:
- * loopback_type - Pre or post software DSP.
- * output_dev_idx - Index of the target output device.
- * loopback_dev_idx - Index of the loopback device that
- * listens for output data.
- */
-void cras_iodev_list_unregister_loopback(enum CRAS_LOOPBACK_TYPE loopback_type,
- unsigned int output_dev_idx,
- unsigned int loopback_dev_idx);
-
-/* Suspends all hotwording streams. */
-int cras_iodev_list_suspend_hotword_streams();
-
-/* Resumes all hotwording streams. */
-int cras_iodev_list_resume_hotword_stream();
-
-/* Sets the state of noise cancellation for input devices which supports noise
- * cancellation by suspend, enable/disable, then resume.
- */
-void cras_iodev_list_reset_for_noise_cancellation();
-
-/* For unit test only. */
-void cras_iodev_list_reset();
-
-#endif /* CRAS_IODEV_LIST_H_ */
diff --git a/cras/src/server/cras_loopback_iodev.c b/cras/src/server/cras_loopback_iodev.c
deleted file mode 100644
index cf3ba4ae..00000000
--- a/cras/src/server/cras_loopback_iodev.c
+++ /dev/null
@@ -1,362 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <pthread.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include "audio_thread_log.h"
-#include "byte_buffer.h"
-#include "cras_audio_area.h"
-#include "cras_config.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "sfh.h"
-#include "utlist.h"
-
-#define LOOPBACK_BUFFER_SIZE 8192
-
-static const char *loopdev_names[LOOPBACK_NUM_TYPES] = {
- "Post Mix Pre DSP Loopback",
- "Post DSP Loopback",
-};
-
-static size_t loopback_supported_rates[] = { 48000, 0 };
-
-static size_t loopback_supported_channel_counts[] = { 2, 0 };
-
-static snd_pcm_format_t loopback_supported_formats[] = {
- SND_PCM_FORMAT_S16_LE,
- 0,
-};
-
-/* loopack iodev. Keep state of a loopback device.
- * loopback_type - Pre-dsp or post-dsp.
- * read_frames - Frames of audio data read since last dev start.
- * started - True to indicate the target device is running, otherwise false.
- * dev_start_time - The timestamp of the last call to configure_dev.
- * sample_buffer - Pointer to sample buffer.
- * sender_idx - Index of the output device to read loopback audio.
- */
-struct loopback_iodev {
- struct cras_iodev base;
- enum CRAS_LOOPBACK_TYPE loopback_type;
- uint64_t read_frames;
- bool started;
- struct timespec dev_start_time;
- struct byte_buffer *sample_buffer;
- unsigned int sender_idx;
-};
-
-static int sample_hook_start(bool start, void *cb_data)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)cb_data;
- loopdev->started = start;
- return 0;
-}
-
-/*
- * Called in the put buffer function of the sender that hooked to.
- *
- * Returns:
- * Number of frames copied to the sample buffer in the hook.
- */
-static int sample_hook(const uint8_t *frames, unsigned int nframes,
- const struct cras_audio_format *fmt, void *cb_data)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)cb_data;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
- unsigned int frame_bytes = cras_get_format_bytes(fmt);
- unsigned int frames_to_copy, bytes_to_copy, frames_copied = 0;
- int i;
-
- for (i = 0; i < 2; i++) {
- frames_to_copy = MIN(buf_writable(sbuf) / frame_bytes, nframes);
- if (!frames_to_copy)
- break;
-
- bytes_to_copy = frames_to_copy * frame_bytes;
- memcpy(buf_write_pointer(sbuf), frames, bytes_to_copy);
- buf_increment_write(sbuf, bytes_to_copy);
- frames += bytes_to_copy;
- nframes -= frames_to_copy;
- frames_copied += frames_to_copy;
- }
-
- ATLOG(atlog, AUDIO_THREAD_LOOPBACK_SAMPLE_HOOK, nframes + frames_copied,
- frames_copied, 0);
-
- return frames_copied;
-}
-
-static void update_first_output_to_loopback(struct loopback_iodev *loopdev)
-{
- struct cras_iodev *edev;
-
- /* Register loopback hook onto first enabled iodev. */
- edev = cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT);
- if (edev) {
- loopdev->sender_idx = edev->info.idx;
- cras_iodev_list_register_loopback(
- loopdev->loopback_type, loopdev->sender_idx,
- sample_hook, sample_hook_start, loopdev->base.info.idx);
- }
-}
-
-static void device_enabled_hook(struct cras_iodev *iodev, void *cb_data)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)cb_data;
-
- if (iodev->direction != CRAS_STREAM_OUTPUT)
- return;
-
- update_first_output_to_loopback(loopdev);
-}
-
-static void device_disabled_hook(struct cras_iodev *iodev, void *cb_data)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)cb_data;
-
- if (loopdev->sender_idx != iodev->info.idx)
- return;
-
- /* Unregister loopback hook from disabled iodev. */
- cras_iodev_list_unregister_loopback(loopdev->loopback_type,
- loopdev->sender_idx,
- loopdev->base.info.idx);
- update_first_output_to_loopback(loopdev);
-}
-
-/*
- * iodev callbacks.
- */
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *hw_tstamp)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
- unsigned int frame_bytes = cras_get_format_bytes(iodev->format);
-
- if (!loopdev->started) {
- unsigned int frames_since_start, frames_to_fill, bytes_to_fill;
-
- frames_since_start = cras_frames_since_time(
- &loopdev->dev_start_time, iodev->format->frame_rate);
- frames_to_fill =
- frames_since_start > loopdev->read_frames ?
- frames_since_start - loopdev->read_frames :
- 0;
- frames_to_fill =
- MIN(buf_writable(sbuf) / frame_bytes, frames_to_fill);
- if (frames_to_fill > 0) {
- bytes_to_fill = frames_to_fill * frame_bytes;
- memset(buf_write_pointer(sbuf), 0, bytes_to_fill);
- buf_increment_write(sbuf, bytes_to_fill);
- }
- }
- clock_gettime(CLOCK_MONOTONIC_RAW, hw_tstamp);
- return buf_queued(sbuf) / frame_bytes;
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- struct timespec tstamp;
-
- return frames_queued(iodev, &tstamp);
-}
-
-static int close_record_dev(struct cras_iodev *iodev)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
-
- cras_iodev_free_format(iodev);
- cras_iodev_free_audio_area(iodev);
- buf_reset(sbuf);
-
- cras_iodev_list_unregister_loopback(loopdev->loopback_type,
- loopdev->sender_idx,
- loopdev->base.info.idx);
- loopdev->sender_idx = NO_DEVICE;
- cras_iodev_list_set_device_enabled_callback(NULL, NULL, (void *)iodev);
-
- return 0;
-}
-
-static int configure_record_dev(struct cras_iodev *iodev)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct cras_iodev *edev;
-
- cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
- clock_gettime(CLOCK_MONOTONIC_RAW, &loopdev->dev_start_time);
- loopdev->read_frames = 0;
- loopdev->started = 0;
-
- edev = cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT);
- if (edev) {
- loopdev->sender_idx = edev->info.idx;
- cras_iodev_list_register_loopback(
- loopdev->loopback_type, loopdev->sender_idx,
- sample_hook, sample_hook_start, iodev->info.idx);
- }
- cras_iodev_list_set_device_enabled_callback(
- device_enabled_hook, device_disabled_hook, (void *)iodev);
-
- return 0;
-}
-
-static int get_record_buffer(struct cras_iodev *iodev,
- struct cras_audio_area **area, unsigned *frames)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
- unsigned int frame_bytes = cras_get_format_bytes(iodev->format);
- unsigned int avail_frames = buf_readable(sbuf) / frame_bytes;
-
- ATLOG(atlog, AUDIO_THREAD_LOOPBACK_GET, *frames, avail_frames, 0);
-
- *frames = MIN(avail_frames, *frames);
- iodev->area->frames = *frames;
- cras_audio_area_config_buf_pointers(iodev->area, iodev->format,
- buf_read_pointer(sbuf));
- *area = iodev->area;
-
- return 0;
-}
-
-static int put_record_buffer(struct cras_iodev *iodev, unsigned nframes)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
- unsigned int frame_bytes = cras_get_format_bytes(iodev->format);
-
- buf_increment_read(sbuf, (size_t)nframes * (size_t)frame_bytes);
- loopdev->read_frames += nframes;
- ATLOG(atlog, AUDIO_THREAD_LOOPBACK_PUT, nframes, 0, 0);
- return 0;
-}
-
-static int flush_record_buffer(struct cras_iodev *iodev)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
- unsigned int queued_bytes = buf_queued(sbuf);
- buf_increment_read(sbuf, queued_bytes);
- loopdev->read_frames = 0;
- return 0;
-}
-
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
-}
-
-static struct cras_iodev *create_loopback_iodev(enum CRAS_LOOPBACK_TYPE type)
-{
- struct loopback_iodev *loopback_iodev;
- struct cras_iodev *iodev;
-
- loopback_iodev = calloc(1, sizeof(*loopback_iodev));
- if (loopback_iodev == NULL)
- return NULL;
-
- loopback_iodev->sample_buffer = byte_buffer_create(1024 * 16 * 4);
- if (loopback_iodev->sample_buffer == NULL) {
- free(loopback_iodev);
- return NULL;
- }
-
- loopback_iodev->loopback_type = type;
-
- iodev = &loopback_iodev->base;
- iodev->direction = CRAS_STREAM_INPUT;
- snprintf(iodev->info.name, ARRAY_SIZE(iodev->info.name), "%s",
- loopdev_names[type]);
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = '\0';
- iodev->info.stable_id =
- SuperFastHash(iodev->info.name, strlen(iodev->info.name),
- strlen(iodev->info.name));
-
- iodev->supported_rates = loopback_supported_rates;
- iodev->supported_channel_counts = loopback_supported_channel_counts;
- iodev->supported_formats = loopback_supported_formats;
- iodev->buffer_size = LOOPBACK_BUFFER_SIZE;
-
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->update_active_node = update_active_node;
- iodev->configure_dev = configure_record_dev;
- iodev->close_dev = close_record_dev;
- iodev->get_buffer = get_record_buffer;
- iodev->put_buffer = put_record_buffer;
- iodev->flush_buffer = flush_record_buffer;
-
- /*
- * Record max supported channels into cras_iodev_info.
- * The value is the max of loopback_supported_channel_counts.
- */
- iodev->info.max_supported_channels = 2;
-
- return iodev;
-}
-
-/*
- * Exported Interface.
- */
-
-struct cras_iodev *loopback_iodev_create(enum CRAS_LOOPBACK_TYPE type)
-{
- struct cras_iodev *iodev;
- struct cras_ionode *node;
- enum CRAS_NODE_TYPE node_type;
-
- switch (type) {
- case LOOPBACK_POST_MIX_PRE_DSP:
- node_type = CRAS_NODE_TYPE_POST_MIX_PRE_DSP;
- break;
- case LOOPBACK_POST_DSP:
- node_type = CRAS_NODE_TYPE_POST_DSP;
- break;
- default:
- return NULL;
- }
-
- iodev = create_loopback_iodev(type);
- if (iodev == NULL)
- return NULL;
-
- /* Create an empty ionode */
- node = (struct cras_ionode *)calloc(1, sizeof(*node));
- node->dev = iodev;
- node->type = node_type;
- node->plugged = 1;
- node->volume = 100;
- node->ui_gain_scaler = 1.0f;
- node->stable_id = iodev->info.stable_id;
- node->software_volume_needed = 0;
- strcpy(node->name, loopdev_names[type]);
- cras_iodev_add_node(iodev, node);
- cras_iodev_set_active_node(iodev, node);
-
- cras_iodev_list_add_input(iodev);
-
- return iodev;
-}
-
-void loopback_iodev_destroy(struct cras_iodev *iodev)
-{
- struct loopback_iodev *loopdev = (struct loopback_iodev *)iodev;
- struct byte_buffer *sbuf = loopdev->sample_buffer;
-
- cras_iodev_list_rm_input(iodev);
- free(iodev->nodes);
-
- byte_buffer_destroy(&sbuf);
- free(loopdev);
-}
diff --git a/cras/src/server/cras_loopback_iodev.h b/cras/src/server/cras_loopback_iodev.h
deleted file mode 100644
index 7cc5da82..00000000
--- a/cras/src/server/cras_loopback_iodev.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_LOOPBACK_IO_H_
-#define CRAS_LOOPBACK_IO_H_
-
-#include "cras_types.h"
-
-struct cras_iodev;
-
-/* Initializes loopback iodevs. loopback iodevs provide the ability to
- * capture exactly what is being output by the system.
- */
-struct cras_iodev *loopback_iodev_create(enum CRAS_LOOPBACK_TYPE type);
-
-/* Destroys loopback_iodevs created with loopback_iodev_create. */
-void loopback_iodev_destroy(struct cras_iodev *loopdev);
-
-#endif /* CRAS_LOOPBACK_IO_H_ */
diff --git a/cras/src/server/cras_main_message.c b/cras/src/server/cras_main_message.c
deleted file mode 100644
index b88e4000..00000000
--- a/cras/src/server/cras_main_message.c
+++ /dev/null
@@ -1,117 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include "cras_main_message.h"
-#include "cras_system_state.h"
-#include "cras_util.h"
-
-/* Callback to handle specific type of main thread message. */
-struct cras_main_msg_callback {
- enum CRAS_MAIN_MESSAGE_TYPE type;
- cras_message_callback callback;
- void *callback_data;
- struct cras_main_msg_callback *prev, *next;
-};
-
-static int main_msg_fds[2];
-static struct cras_main_msg_callback *main_msg_callbacks;
-
-int cras_main_message_add_handler(enum CRAS_MAIN_MESSAGE_TYPE type,
- cras_message_callback callback,
- void *callback_data)
-{
- struct cras_main_msg_callback *msg_cb;
-
- DL_FOREACH (main_msg_callbacks, msg_cb) {
- if (msg_cb->type == type) {
- syslog(LOG_ERR, "Main message type %u already exists",
- type);
- return -EEXIST;
- }
- }
-
- msg_cb = (struct cras_main_msg_callback *)calloc(1, sizeof(*msg_cb));
- msg_cb->type = type;
- msg_cb->callback = callback;
- msg_cb->callback_data = callback_data;
-
- DL_APPEND(main_msg_callbacks, msg_cb);
- return 0;
-}
-
-int cras_main_message_send(struct cras_main_message *msg)
-{
- int err;
-
- err = write(main_msg_fds[1], msg, msg->length);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send main message, type %u",
- msg->type);
- return err;
- }
- return 0;
-}
-
-static int read_main_message(int msg_fd, uint8_t *buf, size_t max_len)
-{
- int to_read, nread, rc;
- struct cras_main_message *msg = (struct cras_main_message *)buf;
-
- nread = read(msg_fd, buf, sizeof(msg->length));
- if (nread < 0)
- return nread;
- if (msg->length > max_len)
- return -ENOMEM;
-
- to_read = msg->length - nread;
- rc = read(msg_fd, &buf[0] + nread, to_read);
- if (rc < 0)
- return rc;
- return 0;
-}
-
-static void handle_main_messages(void *arg, int revents)
-{
- uint8_t buf[256];
- int rc;
- struct cras_main_msg_callback *main_msg_cb;
- struct cras_main_message *msg = (struct cras_main_message *)buf;
-
- rc = read_main_message(main_msg_fds[0], buf, sizeof(buf));
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to read main message");
- return;
- }
-
- DL_FOREACH (main_msg_callbacks, main_msg_cb) {
- if (main_msg_cb->type == msg->type) {
- main_msg_cb->callback(msg, main_msg_cb->callback_data);
- break;
- }
- }
-}
-
-void cras_main_message_init()
-{
- int rc;
-
- rc = pipe(main_msg_fds);
- if (rc < 0) {
- syslog(LOG_ERR, "Fatal: main message init");
- exit(-ENOMEM);
- }
-
- /* When full it's preferred to get error instead of blocked. */
- cras_make_fd_nonblocking(main_msg_fds[0]);
- cras_make_fd_nonblocking(main_msg_fds[1]);
-
- cras_system_add_select_fd(main_msg_fds[0], handle_main_messages, NULL,
- POLLIN);
-}
diff --git a/cras/src/server/cras_main_message.h b/cras/src/server/cras_main_message.h
deleted file mode 100644
index fd63488b..00000000
--- a/cras/src/server/cras_main_message.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_MAIN_MESSAGE_H_
-#define CRAS_MAIN_MESSAGE_H_
-
-#include <stdio.h>
-
-#include "utlist.h"
-
-/* The types of message main thread can handle. */
-enum CRAS_MAIN_MESSAGE_TYPE {
- /* Audio thread -> main thread */
- CRAS_MAIN_A2DP,
- CRAS_MAIN_AUDIO_THREAD_EVENT,
- CRAS_MAIN_BT,
- CRAS_MAIN_METRICS,
- CRAS_MAIN_MONITOR_DEVICE,
- CRAS_MAIN_HOTWORD_TRIGGERED,
- CRAS_MAIN_NON_EMPTY_AUDIO_STATE,
-};
-
-/* Structure of the header of the message handled by main thread.
- * Args:
- * length - Size of the whole message.
- * type - Type of the message.
- */
-struct cras_main_message {
- size_t length;
- enum CRAS_MAIN_MESSAGE_TYPE type;
-};
-
-/* Callback function to handle main thread message. */
-typedef void (*cras_message_callback)(struct cras_main_message *msg, void *arg);
-
-/* Sends a message to main thread. */
-int cras_main_message_send(struct cras_main_message *msg);
-
-/* Registers the handler function for specific type of message. */
-int cras_main_message_add_handler(enum CRAS_MAIN_MESSAGE_TYPE type,
- cras_message_callback callback,
- void *callback_data);
-
-/* Initialize the message handling mechanism in main thread. */
-void cras_main_message_init();
-
-#endif /* CRAS_MAIN_MESSAGE_H_ */
diff --git a/cras/src/server/cras_main_thread_log.h b/cras/src/server/cras_main_thread_log.h
deleted file mode 100644
index 1d92585a..00000000
--- a/cras/src/server/cras_main_thread_log.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_MAIN_THREAD_LOG_H_
-#define CRAS_MAIN_THREAD_LOG_H_
-
-#include <stdint.h>
-
-#include "cras_types.h"
-
-#define CRAS_MAIN_THREAD_LOGGING 1
-
-#if (CRAS_MAIN_THREAD_LOGGING)
-#define MAINLOG(log, event, data1, data2, data3) \
- main_thread_event_log_data(log, event, data1, data2, data3);
-#else
-#define MAINLOG(log, event, data1, data2, data3)
-#endif
-
-extern struct main_thread_event_log *main_log;
-
-static inline struct main_thread_event_log *main_thread_event_log_init()
-{
- struct main_thread_event_log *log;
- log = (struct main_thread_event_log *)calloc(
- 1, sizeof(struct main_thread_event_log));
- if (!log)
- return NULL;
-
- log->len = MAIN_THREAD_EVENT_LOG_SIZE;
- return log;
-}
-
-static inline void
-main_thread_event_log_deinit(struct main_thread_event_log *log)
-{
- if (log)
- free(log);
-}
-
-static inline void main_thread_event_log_data(struct main_thread_event_log *log,
- enum MAIN_THREAD_LOG_EVENTS event,
- uint32_t data1, uint32_t data2,
- uint32_t data3)
-{
- struct timespec now;
-
- if (!log)
- return;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- log->log[log->write_pos].tag_sec =
- (event << 24) | ((now.tv_sec % 86400) & 0x00ffffff);
- log->log[log->write_pos].nsec = now.tv_nsec;
- log->log[log->write_pos].data1 = data1;
- log->log[log->write_pos].data2 = data2;
- log->log[log->write_pos].data3 = data3;
- log->write_pos++;
- log->write_pos %= MAIN_THREAD_EVENT_LOG_SIZE;
-}
-
-#endif /* CRAS_MAIN_THREAD_LOG_H_ */
diff --git a/cras/src/server/cras_mix.c b/cras/src/server/cras_mix.c
deleted file mode 100644
index ffe556b5..00000000
--- a/cras/src/server/cras_mix.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-
-#include "cras_system_state.h"
-#include "cras_mix.h"
-#include "cras_mix_ops.h"
-
-static const struct cras_mix_ops *ops = &mixer_ops;
-
-static const struct cras_mix_ops *get_mixer_ops(unsigned int cpu_flags)
-{
-#if defined HAVE_FMA
- if (cpu_flags & CPU_X86_FMA)
- return &mixer_ops_fma;
-#endif
-#if defined HAVE_AVX2
- if (cpu_flags & CPU_X86_AVX2)
- return &mixer_ops_avx2;
-#endif
-#if defined HAVE_AVX
- if (cpu_flags & CPU_X86_AVX)
- return &mixer_ops_avx;
-#endif
-#if defined HAVE_SSE42
- if (cpu_flags & CPU_X86_SSE4_2)
- return &mixer_ops_sse42;
-#endif
-
- /* default C implementation */
- return &mixer_ops;
-}
-
-void cras_mix_init(unsigned int flags)
-{
- ops = get_mixer_ops(flags);
-}
-
-/*
- * Exported Interface
- */
-
-void cras_scale_buffer_increment(snd_pcm_format_t fmt, uint8_t *buff,
- unsigned int frame, float scaler,
- float increment, float target, int channel)
-{
- ops->scale_buffer_increment(fmt, buff, frame * channel, scaler,
- increment, target, channel);
-}
-
-void cras_scale_buffer(snd_pcm_format_t fmt, uint8_t *buff, unsigned int count,
- float scaler)
-{
- ops->scale_buffer(fmt, buff, count, scaler);
-}
-
-void cras_mix_add(snd_pcm_format_t fmt, uint8_t *dst, uint8_t *src,
- unsigned int count, unsigned int index, int mute,
- float mix_vol)
-{
- ops->add(fmt, dst, src, count, index, mute, mix_vol);
-}
-
-void cras_mix_add_scale_stride(snd_pcm_format_t fmt, uint8_t *dst, uint8_t *src,
- unsigned int count, unsigned int dst_stride,
- unsigned int src_stride, float scaler)
-{
- ops->add_scale_stride(fmt, dst, src, count, dst_stride, src_stride,
- scaler);
-}
-
-size_t cras_mix_mute_buffer(uint8_t *dst, size_t frame_bytes, size_t count)
-{
- return ops->mute_buffer(dst, frame_bytes, count);
-}
diff --git a/cras/src/server/cras_mix.h b/cras/src/server/cras_mix.h
deleted file mode 100644
index 5c21df91..00000000
--- a/cras/src/server/cras_mix.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef _CRAS_MIX_H
-#define _CRAS_MIX_H
-
-#include "cras_types.h"
-
-struct cras_audio_shm;
-
-/* SIMD optimisation flags */
-#define CPU_X86_SSE4_2 1
-#define CPU_X86_AVX 2
-#define CPU_X86_AVX2 4
-#define CPU_X86_FMA 8
-
-void cras_mix_init(unsigned int flags);
-
-/* Scale the given buffer with the provided scaler and increment.
- * Args:
- * fmt - The format (SND_PCM_FORMAT_*)
- * buff - Buffer of samples to scale.
- * frame - The number of frames to render.
- * scaler - Amount to scale samples (0.0 - 1.0).
- * increment - The increment(+/-) of scaler at each frame. The scaler after
- * increasing/decreasing will be clipped at target.
- * target - The value at which to clip the scaler.
- * channel - Number of samples in a frame.
- */
-void cras_scale_buffer_increment(snd_pcm_format_t fmt, uint8_t *buff,
- unsigned int frame, float scaler,
- float increment, float target, int channel);
-
-/* Scale the given buffer with the provided scaler.
- * Args:
- * fmt - The format (SND_PCM_FORMAT_*)
- * buff - Buffer of samples to scale.
- * scaler - Amount to scale samples (0.0 - 1.0).
- * count - The number of samples to render, on return holds the number
- * actually mixed.
- */
-void cras_scale_buffer(snd_pcm_format_t fmt, uint8_t *buff, unsigned int count,
- float scaler);
-
-/* Add src buffer to dst, scaling and setting mute.
- * Args:
- * fmt - The format (SND_PCM_FORMAT_*)
- * dst - Buffer of samples to mix to.
- * src - Buffer of samples to mix from.
- * count - The number of samples to mix.
- * index - If zero this is the first buffer written to dst.
- * mute - Is the stream providing the buffer muted.
- * mix_vol - Scaler for the buffer to be mixed.
- */
-void cras_mix_add(snd_pcm_format_t fmt, uint8_t *dst, uint8_t *src,
- unsigned int count, unsigned int index, int mute,
- float mix_vol);
-
-/* Add src buffer to dst with independent channel strides.
- * Args:
- * fmt - The format (SND_PCM_FORMAT_*)
- * dst - Buffer of samples to mix to.
- * src - Buffer of samples to mix from.
- * count - The number of samples to mix.
- * dst_stride - Stride between channel samples in dst in bytes.
- * src_stride - Stride between channel samples in src in bytes.
- * scaler - Amount to scale samples.
- */
-void cras_mix_add_scale_stride(snd_pcm_format_t fmt, uint8_t *dst, uint8_t *src,
- unsigned int count, unsigned int dst_stride,
- unsigned int src_stride, float scaler);
-
-/* Mutes the given buffer.
- * Args:
- * num_channel - Number of channels in data.
- * frame_bytes - number of bytes in a frame.
- * count - The number of frames to render.
- */
-size_t cras_mix_mute_buffer(uint8_t *dst, size_t frame_bytes, size_t count);
-
-#endif /* _CRAS_MIX_H */
diff --git a/cras/src/server/cras_mix_ops.c b/cras/src/server/cras_mix_ops.c
deleted file mode 100644
index 2425f094..00000000
--- a/cras/src/server/cras_mix_ops.c
+++ /dev/null
@@ -1,850 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-
-#include "cras_system_state.h"
-#include "cras_mix_ops.h"
-
-#define MAX_VOLUME_TO_SCALE 0.9999999
-#define MIN_VOLUME_TO_SCALE 0.0000001
-
-/* function suffixes for SIMD ops */
-#ifdef OPS_SSE42
-#define OPS(a) a##_sse42
-#elif OPS_AVX
-#define OPS(a) a##_avx
-#elif OPS_AVX2
-#define OPS(a) a##_avx2
-#elif OPS_FMA
-#define OPS(a) a##_fma
-#else
-#define OPS(a) a
-#endif
-
-/* Checks if the scaler needs a scaling operation.
- * We skip scaling for scaler too close to 1.0.
- * Note that this is not subjected to MAX_VOLUME_TO_SCALE
- * and MIN_VOLUME_TO_SCALE. */
-static inline int need_to_scale(float scaler)
-{
- return (scaler < 0.99 || scaler > 1.01);
-}
-
-/*
- * Signed 16 bit little endian functions.
- */
-
-static void cras_mix_add_clip_s16_le(int16_t *dst, const int16_t *src,
- size_t count)
-{
- int32_t sum;
- size_t i;
-
- for (i = 0; i < count; i++) {
- sum = dst[i] + src[i];
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- dst[i] = sum;
- }
-}
-
-/* Adds src into dst, after scaling by vol.
- * Just hard limits to the min and max S16 value, can be improved later. */
-static void scale_add_clip_s16_le(int16_t *dst, const int16_t *src,
- size_t count, float vol)
-{
- int32_t sum;
- size_t i;
-
- if (vol > MAX_VOLUME_TO_SCALE)
- return cras_mix_add_clip_s16_le(dst, src, count);
-
- for (i = 0; i < count; i++) {
- sum = dst[i] + (int16_t)(src[i] * vol);
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- dst[i] = sum;
- }
-}
-
-/* Adds the first stream to the mix. Don't need to mix, just setup to the new
- * values. If volume is 1.0, just memcpy. */
-static void copy_scaled_s16_le(int16_t *dst, const int16_t *src, size_t count,
- float volume_scaler)
-{
- int i;
-
- if (volume_scaler > MAX_VOLUME_TO_SCALE) {
- memcpy(dst, src, count * sizeof(*src));
- return;
- }
-
- for (i = 0; i < count; i++)
- dst[i] = src[i] * volume_scaler;
-}
-
-static void cras_scale_buffer_inc_s16_le(uint8_t *buffer, unsigned int count,
- float scaler, float increment,
- float target, int step)
-{
- int i = 0, j;
- int16_t *out = (int16_t *)buffer;
-
- if (scaler < MIN_VOLUME_TO_SCALE && increment < 0) {
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- while (i + step <= count) {
- for (j = 0; j < step; j++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > MAX_VOLUME_TO_SCALE) {
- } else if (applied_scaler < MIN_VOLUME_TO_SCALE) {
- out[i] = 0;
- } else {
- out[i] *= applied_scaler;
- }
- i++;
- }
- scaler += increment;
- }
-}
-
-static void cras_scale_buffer_s16_le(uint8_t *buffer, unsigned int count,
- float scaler)
-{
- int i;
- int16_t *out = (int16_t *)buffer;
-
- if (scaler > MAX_VOLUME_TO_SCALE)
- return;
-
- if (scaler < MIN_VOLUME_TO_SCALE) {
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- for (i = 0; i < count; i++)
- out[i] *= scaler;
-}
-
-static void cras_mix_add_s16_le(uint8_t *dst, uint8_t *src, unsigned int count,
- unsigned int index, int mute, float mix_vol)
-{
- int16_t *out = (int16_t *)dst;
- int16_t *in = (int16_t *)src;
-
- if (mute || (mix_vol < MIN_VOLUME_TO_SCALE)) {
- if (index == 0)
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- if (index == 0)
- return copy_scaled_s16_le(out, in, count, mix_vol);
-
- scale_add_clip_s16_le(out, in, count, mix_vol);
-}
-
-static void cras_mix_add_scale_stride_s16_le(uint8_t *dst, uint8_t *src,
- unsigned int dst_stride,
- unsigned int src_stride,
- unsigned int count, float scaler)
-{
- unsigned int i;
-
- /* optimise the loops for vectorization */
- if (dst_stride == src_stride && dst_stride == 2) {
- for (i = 0; i < count; i++) {
- int32_t sum;
- if (need_to_scale(scaler))
- sum = *(int16_t *)dst +
- *(int16_t *)src * scaler;
- else
- sum = *(int16_t *)dst + *(int16_t *)src;
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- *(int16_t *)dst = sum;
- dst += 2;
- src += 2;
- }
- } else if (dst_stride == src_stride && dst_stride == 4) {
- for (i = 0; i < count; i++) {
- int32_t sum;
- if (need_to_scale(scaler))
- sum = *(int16_t *)dst +
- *(int16_t *)src * scaler;
- else
- sum = *(int16_t *)dst + *(int16_t *)src;
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- *(int16_t *)dst = sum;
- dst += 4;
- src += 4;
- }
- } else {
- for (i = 0; i < count; i++) {
- int32_t sum;
- if (need_to_scale(scaler))
- sum = *(int16_t *)dst +
- *(int16_t *)src * scaler;
- else
- sum = *(int16_t *)dst + *(int16_t *)src;
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- *(int16_t *)dst = sum;
- dst += dst_stride;
- src += src_stride;
- }
- }
-}
-
-/*
- * Signed 24 bit little endian functions.
- */
-
-static int32_t scale_s24_le(int32_t value, float scaler)
-{
- value = ((uint32_t)(value & 0x00ffffff)) << 8;
- value *= scaler;
- return (value >> 8) & 0x00ffffff;
-}
-
-static void cras_mix_add_clip_s24_le(int32_t *dst, const int32_t *src,
- size_t count)
-{
- int32_t sum;
- size_t i;
-
- for (i = 0; i < count; i++) {
- sum = dst[i] + src[i];
- if (sum > 0x007fffff)
- sum = 0x007fffff;
- else if (sum < (int32_t)0xff800000)
- sum = (int32_t)0xff800000;
- dst[i] = sum;
- }
-}
-
-/* Adds src into dst, after scaling by vol.
- * Just hard limits to the min and max S24 value, can be improved later. */
-static void scale_add_clip_s24_le(int32_t *dst, const int32_t *src,
- size_t count, float vol)
-{
- int32_t sum;
- size_t i;
-
- if (vol > MAX_VOLUME_TO_SCALE)
- return cras_mix_add_clip_s24_le(dst, src, count);
-
- for (i = 0; i < count; i++) {
- sum = dst[i] + (int32_t)(src[i] * vol);
- if (sum > 0x007fffff)
- sum = 0x007fffff;
- else if (sum < (int32_t)0xff800000)
- sum = (int32_t)0xff800000;
- dst[i] = sum;
- }
-}
-
-/* Adds the first stream to the mix. Don't need to mix, just setup to the new
- * values. If volume is 1.0, just memcpy. */
-static void copy_scaled_s24_le(int32_t *dst, const int32_t *src, size_t count,
- float volume_scaler)
-{
- int i;
-
- if (volume_scaler > MAX_VOLUME_TO_SCALE) {
- memcpy(dst, src, count * sizeof(*src));
- return;
- }
-
- for (i = 0; i < count; i++)
- dst[i] = scale_s24_le(src[i], volume_scaler);
-}
-
-static void cras_scale_buffer_inc_s24_le(uint8_t *buffer, unsigned int count,
- float scaler, float increment,
- float target, int step)
-{
- int i = 0, j;
- int32_t *out = (int32_t *)buffer;
-
- if (scaler < MIN_VOLUME_TO_SCALE && increment < 0) {
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- while (i + step <= count) {
- for (j = 0; j < step; j++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > MAX_VOLUME_TO_SCALE) {
- } else if (applied_scaler < MIN_VOLUME_TO_SCALE) {
- out[i] = 0;
- } else {
- out[i] = scale_s24_le(out[i], applied_scaler);
- }
- i++;
- }
- scaler += increment;
- }
-}
-
-static void cras_scale_buffer_s24_le(uint8_t *buffer, unsigned int count,
- float scaler)
-{
- int i;
- int32_t *out = (int32_t *)buffer;
-
- if (scaler > MAX_VOLUME_TO_SCALE)
- return;
-
- if (scaler < MIN_VOLUME_TO_SCALE) {
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- for (i = 0; i < count; i++)
- out[i] = scale_s24_le(out[i], scaler);
-}
-
-static void cras_mix_add_s24_le(uint8_t *dst, uint8_t *src, unsigned int count,
- unsigned int index, int mute, float mix_vol)
-{
- int32_t *out = (int32_t *)dst;
- int32_t *in = (int32_t *)src;
-
- if (mute || (mix_vol < MIN_VOLUME_TO_SCALE)) {
- if (index == 0)
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- if (index == 0)
- return copy_scaled_s24_le(out, in, count, mix_vol);
-
- scale_add_clip_s24_le(out, in, count, mix_vol);
-}
-
-static void cras_mix_add_scale_stride_s24_le(uint8_t *dst, uint8_t *src,
- unsigned int dst_stride,
- unsigned int src_stride,
- unsigned int count, float scaler)
-{
- unsigned int i;
-
- /* optimise the loops for vectorization */
- if (dst_stride == src_stride && dst_stride == 4) {
- for (i = 0; i < count; i++) {
- int32_t sum;
- if (need_to_scale(scaler))
- sum = *(int32_t *)dst +
- scale_s24_le(*(int32_t *)src, scaler);
- else
- sum = *(int32_t *)dst + *(int32_t *)src;
- if (sum > 0x007fffff)
- sum = 0x007fffff;
- else if (sum < (int32_t)0xff800000)
- sum = (int32_t)0xff800000;
- *(int32_t *)dst = sum;
- dst += 4;
- src += 4;
- }
- } else {
- for (i = 0; i < count; i++) {
- int32_t sum;
- if (need_to_scale(scaler))
- sum = *(int32_t *)dst +
- scale_s24_le(*(int32_t *)src, scaler);
- else
- sum = *(int32_t *)dst + *(int32_t *)src;
- if (sum > 0x007fffff)
- sum = 0x007fffff;
- else if (sum < (int32_t)0xff800000)
- sum = (int32_t)0xff800000;
- *(int32_t *)dst = sum;
- dst += dst_stride;
- src += src_stride;
- }
- }
-}
-
-/*
- * Signed 32 bit little endian functions.
- */
-
-static void cras_mix_add_clip_s32_le(int32_t *dst, const int32_t *src,
- size_t count)
-{
- int64_t sum;
- size_t i;
-
- for (i = 0; i < count; i++) {
- sum = (int64_t)dst[i] + (int64_t)src[i];
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- dst[i] = sum;
- }
-}
-
-/* Adds src into dst, after scaling by vol.
- * Just hard limits to the min and max S32 value, can be improved later. */
-static void scale_add_clip_s32_le(int32_t *dst, const int32_t *src,
- size_t count, float vol)
-{
- int64_t sum;
- size_t i;
-
- if (vol > MAX_VOLUME_TO_SCALE)
- return cras_mix_add_clip_s32_le(dst, src, count);
-
- for (i = 0; i < count; i++) {
- sum = (int64_t)dst[i] + (int64_t)(src[i] * vol);
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- dst[i] = sum;
- }
-}
-
-/* Adds the first stream to the mix. Don't need to mix, just setup to the new
- * values. If volume is 1.0, just memcpy. */
-static void copy_scaled_s32_le(int32_t *dst, const int32_t *src, size_t count,
- float volume_scaler)
-{
- int i;
-
- if (volume_scaler > MAX_VOLUME_TO_SCALE) {
- memcpy(dst, src, count * sizeof(*src));
- return;
- }
-
- for (i = 0; i < count; i++)
- dst[i] = src[i] * volume_scaler;
-}
-
-static void cras_scale_buffer_inc_s32_le(uint8_t *buffer, unsigned int count,
- float scaler, float increment,
- float target, int step)
-{
- int i = 0, j;
- int32_t *out = (int32_t *)buffer;
-
- if (scaler < MIN_VOLUME_TO_SCALE && increment < 0) {
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- while (i + step <= count) {
- for (j = 0; j < step; j++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > MAX_VOLUME_TO_SCALE) {
- } else if (applied_scaler < MIN_VOLUME_TO_SCALE) {
- out[i] = 0;
- } else {
- out[i] *= applied_scaler;
- }
- i++;
- }
- scaler += increment;
- }
-}
-
-static void cras_scale_buffer_s32_le(uint8_t *buffer, unsigned int count,
- float scaler)
-{
- int i;
- int32_t *out = (int32_t *)buffer;
-
- if (scaler > MAX_VOLUME_TO_SCALE)
- return;
-
- if (scaler < MIN_VOLUME_TO_SCALE) {
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- for (i = 0; i < count; i++)
- out[i] *= scaler;
-}
-
-static void cras_mix_add_s32_le(uint8_t *dst, uint8_t *src, unsigned int count,
- unsigned int index, int mute, float mix_vol)
-{
- int32_t *out = (int32_t *)dst;
- int32_t *in = (int32_t *)src;
-
- if (mute || (mix_vol < MIN_VOLUME_TO_SCALE)) {
- if (index == 0)
- memset(out, 0, count * sizeof(*out));
- return;
- }
-
- if (index == 0)
- return copy_scaled_s32_le(out, in, count, mix_vol);
-
- scale_add_clip_s32_le(out, in, count, mix_vol);
-}
-
-static void cras_mix_add_scale_stride_s32_le(uint8_t *dst, uint8_t *src,
- unsigned int dst_stride,
- unsigned int src_stride,
- unsigned int count, float scaler)
-{
- unsigned int i;
-
- /* optimise the loops for vectorization */
- if (dst_stride == src_stride && dst_stride == 4) {
- for (i = 0; i < count; i++) {
- int64_t sum;
- if (need_to_scale(scaler))
- sum = *(int32_t *)dst +
- *(int32_t *)src * scaler;
- else
- sum = *(int32_t *)dst + *(int32_t *)src;
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- *(int32_t *)dst = sum;
- dst += 4;
- src += 4;
- }
- } else {
- for (i = 0; i < count; i++) {
- int64_t sum;
- if (need_to_scale(scaler))
- sum = *(int32_t *)dst +
- *(int32_t *)src * scaler;
- else
- sum = *(int32_t *)dst + *(int32_t *)src;
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- *(int32_t *)dst = sum;
- dst += dst_stride;
- src += src_stride;
- }
- }
-}
-
-/*
- * Signed 24 bit little endian in three bytes functions.
- */
-
-/* Convert 3bytes Signed 24bit integer to a Signed 32bit integer.
- * Just a helper function. */
-static inline void convert_single_s243le_to_s32le(int32_t *dst,
- const uint8_t *src)
-{
- *dst = 0;
- memcpy((uint8_t *)dst + 1, src, 3);
-}
-
-static inline void convert_single_s32le_to_s243le(uint8_t *dst,
- const int32_t *src)
-{
- memcpy(dst, (uint8_t *)src + 1, 3);
-}
-
-static void cras_mix_add_clip_s24_3le(uint8_t *dst, const uint8_t *src,
- size_t count)
-{
- int64_t sum;
- int32_t dst_frame;
- int32_t src_frame;
- size_t i;
-
- for (i = 0; i < count; i++, dst += 3, src += 3) {
- convert_single_s243le_to_s32le(&dst_frame, dst);
- convert_single_s243le_to_s32le(&src_frame, src);
- sum = (int64_t)dst_frame + (int64_t)src_frame;
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- dst_frame = (int32_t)sum;
- convert_single_s32le_to_s243le(dst, &dst_frame);
- }
-}
-
-/* Adds src into dst, after scaling by vol.
- * Just hard limits to the min and max S24 value, can be improved later. */
-static void scale_add_clip_s24_3le(uint8_t *dst, const uint8_t *src,
- size_t count, float vol)
-{
- int64_t sum;
- int32_t dst_frame;
- int32_t src_frame;
- size_t i;
-
- if (vol > MAX_VOLUME_TO_SCALE)
- return cras_mix_add_clip_s24_3le(dst, src, count);
-
- for (i = 0; i < count; i++, dst += 3, src += 3) {
- convert_single_s243le_to_s32le(&dst_frame, dst);
- convert_single_s243le_to_s32le(&src_frame, src);
- sum = (int64_t)dst_frame + (int64_t)(src_frame * vol);
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- dst_frame = (int32_t)sum;
- convert_single_s32le_to_s243le(dst, &dst_frame);
- }
-}
-
-/* Adds the first stream to the mix. Don't need to mix, just setup to the new
- * values. If volume is 1.0, just memcpy. */
-static void copy_scaled_s24_3le(uint8_t *dst, const uint8_t *src, size_t count,
- float volume_scaler)
-{
- int32_t frame;
- size_t i;
-
- if (volume_scaler > MAX_VOLUME_TO_SCALE) {
- memcpy(dst, src, 3 * count * sizeof(*src));
- return;
- }
-
- for (i = 0; i < count; i++, dst += 3, src += 3) {
- convert_single_s243le_to_s32le(&frame, src);
- frame *= volume_scaler;
- convert_single_s32le_to_s243le(dst, &frame);
- }
-}
-
-static void cras_scale_buffer_inc_s24_3le(uint8_t *buffer, unsigned int count,
- float scaler, float increment,
- float target, int step)
-{
- int32_t frame;
- int i = 0, j;
-
- if (scaler < MIN_VOLUME_TO_SCALE && increment < 0) {
- memset(buffer, 0, 3 * count * sizeof(*buffer));
- return;
- }
-
- while (i + step <= count) {
- for (j = 0; j < step; j++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- convert_single_s243le_to_s32le(&frame, buffer);
-
- if (applied_scaler > MAX_VOLUME_TO_SCALE) {
- } else if (applied_scaler < MIN_VOLUME_TO_SCALE) {
- frame = 0;
- } else {
- frame *= applied_scaler;
- }
-
- convert_single_s32le_to_s243le(buffer, &frame);
-
- i++;
- buffer += 3;
- }
- scaler += increment;
- }
-}
-
-static void cras_scale_buffer_s24_3le(uint8_t *buffer, unsigned int count,
- float scaler)
-{
- int32_t frame;
- int i;
-
- if (scaler > MAX_VOLUME_TO_SCALE)
- return;
-
- if (scaler < MIN_VOLUME_TO_SCALE) {
- memset(buffer, 0, 3 * count * sizeof(*buffer));
- return;
- }
-
- for (i = 0; i < count; i++, buffer += 3) {
- convert_single_s243le_to_s32le(&frame, buffer);
- frame *= scaler;
- convert_single_s32le_to_s243le(buffer, &frame);
- }
-}
-
-static void cras_mix_add_s24_3le(uint8_t *dst, uint8_t *src, unsigned int count,
- unsigned int index, int mute, float mix_vol)
-{
- uint8_t *out = dst;
- uint8_t *in = src;
-
- if (mute || (mix_vol < MIN_VOLUME_TO_SCALE)) {
- if (index == 0)
- memset(out, 0, 3 * count * sizeof(*out));
- return;
- }
-
- if (index == 0)
- return copy_scaled_s24_3le(out, in, count, mix_vol);
-
- scale_add_clip_s24_3le(out, in, count, mix_vol);
-}
-
-static void cras_mix_add_scale_stride_s24_3le(uint8_t *dst, uint8_t *src,
- unsigned int dst_stride,
- unsigned int src_stride,
- unsigned int count, float scaler)
-{
- unsigned int i;
- int64_t sum;
- int32_t dst_frame;
- int32_t src_frame;
-
- for (i = 0; i < count; i++) {
- convert_single_s243le_to_s32le(&dst_frame, dst);
- convert_single_s243le_to_s32le(&src_frame, src);
- if (need_to_scale(scaler))
- sum = (int64_t)dst_frame + (int64_t)src_frame * scaler;
- else
- sum = (int64_t)dst_frame + (int64_t)src_frame;
- if (sum > INT32_MAX)
- sum = INT32_MAX;
- else if (sum < INT32_MIN)
- sum = INT32_MIN;
- dst_frame = (int32_t)sum;
- convert_single_s32le_to_s243le(dst, &dst_frame);
- dst += dst_stride;
- src += src_stride;
- }
-}
-
-static void scale_buffer_increment(snd_pcm_format_t fmt, uint8_t *buff,
- unsigned int count, float scaler,
- float increment, float target, int step)
-{
- switch (fmt) {
- case SND_PCM_FORMAT_S16_LE:
- return cras_scale_buffer_inc_s16_le(buff, count, scaler,
- increment, target, step);
- case SND_PCM_FORMAT_S24_LE:
- return cras_scale_buffer_inc_s24_le(buff, count, scaler,
- increment, target, step);
- case SND_PCM_FORMAT_S32_LE:
- return cras_scale_buffer_inc_s32_le(buff, count, scaler,
- increment, target, step);
- case SND_PCM_FORMAT_S24_3LE:
- return cras_scale_buffer_inc_s24_3le(buff, count, scaler,
- increment, target, step);
- default:
- break;
- }
-}
-
-static void scale_buffer(snd_pcm_format_t fmt, uint8_t *buff,
- unsigned int count, float scaler)
-{
- switch (fmt) {
- case SND_PCM_FORMAT_S16_LE:
- return cras_scale_buffer_s16_le(buff, count, scaler);
- case SND_PCM_FORMAT_S24_LE:
- return cras_scale_buffer_s24_le(buff, count, scaler);
- case SND_PCM_FORMAT_S32_LE:
- return cras_scale_buffer_s32_le(buff, count, scaler);
- case SND_PCM_FORMAT_S24_3LE:
- return cras_scale_buffer_s24_3le(buff, count, scaler);
- default:
- break;
- }
-}
-
-static void mix_add(snd_pcm_format_t fmt, uint8_t *dst, uint8_t *src,
- unsigned int count, unsigned int index, int mute,
- float mix_vol)
-{
- switch (fmt) {
- case SND_PCM_FORMAT_S16_LE:
- return cras_mix_add_s16_le(dst, src, count, index, mute,
- mix_vol);
- case SND_PCM_FORMAT_S24_LE:
- return cras_mix_add_s24_le(dst, src, count, index, mute,
- mix_vol);
- case SND_PCM_FORMAT_S32_LE:
- return cras_mix_add_s32_le(dst, src, count, index, mute,
- mix_vol);
- case SND_PCM_FORMAT_S24_3LE:
- return cras_mix_add_s24_3le(dst, src, count, index, mute,
- mix_vol);
- default:
- break;
- }
-}
-
-static void mix_add_scale_stride(snd_pcm_format_t fmt, uint8_t *dst,
- uint8_t *src, unsigned int count,
- unsigned int dst_stride,
- unsigned int src_stride, float scaler)
-{
- switch (fmt) {
- case SND_PCM_FORMAT_S16_LE:
- return cras_mix_add_scale_stride_s16_le(
- dst, src, dst_stride, src_stride, count, scaler);
- case SND_PCM_FORMAT_S24_LE:
- return cras_mix_add_scale_stride_s24_le(
- dst, src, dst_stride, src_stride, count, scaler);
- case SND_PCM_FORMAT_S32_LE:
- return cras_mix_add_scale_stride_s32_le(
- dst, src, dst_stride, src_stride, count, scaler);
- case SND_PCM_FORMAT_S24_3LE:
- return cras_mix_add_scale_stride_s24_3le(
- dst, src, dst_stride, src_stride, count, scaler);
- default:
- break;
- }
-}
-
-static size_t mix_mute_buffer(uint8_t *dst, size_t frame_bytes, size_t count)
-{
- memset(dst, 0, count * frame_bytes);
- return count;
-}
-
-const struct cras_mix_ops OPS(mixer_ops) = {
- .scale_buffer = scale_buffer,
- .scale_buffer_increment = scale_buffer_increment,
- .add = mix_add,
- .add_scale_stride = mix_add_scale_stride,
- .mute_buffer = mix_mute_buffer,
-};
diff --git a/cras/src/server/cras_mix_ops.h b/cras/src/server/cras_mix_ops.h
deleted file mode 100644
index 1fac6f3e..00000000
--- a/cras/src/server/cras_mix_ops.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_MIX_OPS_H_
-#define CRAS_MIX_OPS_H_
-
-#include <stdint.h>
-
-#include "cras_system_state.h"
-
-extern const struct cras_mix_ops mixer_ops;
-extern const struct cras_mix_ops mixer_ops_sse42;
-extern const struct cras_mix_ops mixer_ops_avx;
-extern const struct cras_mix_ops mixer_ops_avx2;
-extern const struct cras_mix_ops mixer_ops_fma;
-
-/* Struct containing ops to implement mix/scale on a buffer of samples.
- * Different architecture can provide different implementations and wraps
- * the implementations into cras_mix_ops.
- * Different sample formats will be handled by different implementations.
- * The usage of each operation is explained in cras_mix.h
- *
- * Members:
- * scale_buffer_increment: See cras_scale_buffer_increment.
- * scale_buffer: See cras_scale_buffer.
- * add: See cras_mix_add.
- * add_scale_stride: See cras_mix_add_scale_stride.
- * mute_buffer: cras_mix_mute_buffer.
- */
-struct cras_mix_ops {
- void (*scale_buffer_increment)(snd_pcm_format_t fmt, uint8_t *buff,
- unsigned int count, float scaler,
- float increment, float target, int step);
- void (*scale_buffer)(snd_pcm_format_t fmt, uint8_t *buff,
- unsigned int count, float scaler);
- void (*add)(snd_pcm_format_t fmt, uint8_t *dst, uint8_t *src,
- unsigned int count, unsigned int index, int mute,
- float mix_vol);
- void (*add_scale_stride)(snd_pcm_format_t fmt, uint8_t *dst,
- uint8_t *src, unsigned int count,
- unsigned int dst_stride,
- unsigned int src_stride, float scaler);
- size_t (*mute_buffer)(uint8_t *dst, size_t frame_bytes, size_t count);
-};
-#endif
diff --git a/cras/src/server/cras_non_empty_audio_handler.c b/cras/src/server/cras_non_empty_audio_handler.c
deleted file mode 100644
index 313149ff..00000000
--- a/cras/src/server/cras_non_empty_audio_handler.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdint.h>
-#include <string.h>
-#include <syslog.h>
-
-#include "cras_main_message.h"
-#include "cras_observer.h"
-#include "cras_system_state.h"
-
-struct non_empty_audio_msg {
- struct cras_main_message header;
- int32_t non_empty;
-};
-
-/* The following functions are called from audio thread. */
-
-static void init_non_empty_audio_msg(struct non_empty_audio_msg *msg)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.type = CRAS_MAIN_NON_EMPTY_AUDIO_STATE;
- msg->header.length = sizeof(*msg);
-}
-
-int cras_non_empty_audio_send_msg(int32_t non_empty)
-{
- struct non_empty_audio_msg msg;
- int rc;
-
- init_non_empty_audio_msg(&msg);
- msg.non_empty = non_empty;
-
- rc = cras_main_message_send((struct cras_main_message *)&msg);
- if (rc < 0)
- syslog(LOG_ERR, "Failed to send non-empty audio message!");
-
- return rc;
-}
-
-/* The following functions are called from main thread. */
-
-static void handle_non_empty_audio_message(struct cras_main_message *msg,
- void *arg)
-{
- struct non_empty_audio_msg *audio_msg =
- (struct non_empty_audio_msg *)msg;
-
- cras_system_state_set_non_empty_status(audio_msg->non_empty);
- cras_observer_notify_non_empty_audio_state_changed(
- audio_msg->non_empty);
-}
-
-int cras_non_empty_audio_handler_init()
-{
- cras_main_message_add_handler(CRAS_MAIN_NON_EMPTY_AUDIO_STATE,
- handle_non_empty_audio_message, NULL);
- return 0;
-} \ No newline at end of file
diff --git a/cras/src/server/cras_non_empty_audio_handler.h b/cras/src/server/cras_non_empty_audio_handler.h
deleted file mode 100644
index dac6b221..00000000
--- a/cras/src/server/cras_non_empty_audio_handler.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * The non-empty audio state handler is used to send a DBus signal when the
- * system-level non-empty audio state changes.
- *
- * cras_non_empty_audio_msg() is called from audio thread to update the
- * non-empty audio state in the main thread, which in turn sends the DBus
- * signal.
- *
- * cras_non_empty_audio_handler_init() is used to setup the message handler
- * in the main thread to handle the non-empty audiomessage from audio thread.
- */
-
-#ifndef CRAS_NON_EMPTY_AUDIO_HANDLER_H_
-#define CRAS_NON_EMPTY_AUDIO_HANDLER_H_
-
-/* Send non-empty audio state message. */
-int cras_non_empty_audio_send_msg(int32_t non_empty);
-
-/* Initialize non-empty audio handler. */
-int cras_non_empty_audio_handler_init();
-
-#endif /* CRAS_NON_EMPTY_AUDIO_HANDLER_H_ */
diff --git a/cras/src/server/cras_observer.c b/cras/src/server/cras_observer.c
deleted file mode 100644
index 0f17dc92..00000000
--- a/cras/src/server/cras_observer.c
+++ /dev/null
@@ -1,634 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "cras_observer.h"
-
-#include "cras_alert.h"
-#include "cras_iodev_list.h"
-#include "cras_types.h"
-#include "utlist.h"
-
-struct cras_observer_client {
- struct cras_observer_ops ops;
- void *context;
- struct cras_observer_client *next, *prev;
-};
-
-struct cras_observer_alerts {
- struct cras_alert *output_volume;
- struct cras_alert *output_mute;
- struct cras_alert *capture_gain;
- struct cras_alert *capture_mute;
- struct cras_alert *nodes;
- struct cras_alert *active_node;
- struct cras_alert *output_node_volume;
- struct cras_alert *node_left_right_swapped;
- struct cras_alert *input_node_gain;
- struct cras_alert *suspend_changed;
- struct cras_alert *hotword_triggered;
- /* If all events for active streams went through a single alert then
- * we might miss some because the alert code does not send every
- * alert message. To ensure that the event sent contains the correct
- * number of active streams per direction, make the alerts
- * per-direciton. */
- struct cras_alert *num_active_streams[CRAS_NUM_DIRECTIONS];
- struct cras_alert *non_empty_audio_state_changed;
- struct cras_alert *bt_battery_changed;
- struct cras_alert *num_input_streams_with_permission;
-};
-
-struct cras_observer_server {
- struct cras_observer_alerts alerts;
- struct cras_observer_client *clients;
-};
-
-struct cras_observer_alert_data_volume {
- int32_t volume;
-};
-
-struct cras_observer_alert_data_mute {
- int muted;
- int user_muted;
- int mute_locked;
-};
-
-struct cras_observer_alert_data_active_node {
- enum CRAS_STREAM_DIRECTION direction;
- cras_node_id_t node_id;
-};
-
-struct cras_observer_alert_data_node_volume {
- cras_node_id_t node_id;
- int32_t volume;
-};
-
-struct cras_observer_alert_data_node_lr_swapped {
- cras_node_id_t node_id;
- int swapped;
-};
-
-struct cras_observer_alert_data_suspend {
- int suspended;
-};
-
-struct cras_observer_alert_data_streams {
- enum CRAS_STREAM_DIRECTION direction;
- uint32_t num_active_streams;
-};
-
-struct cras_observer_alert_data_input_streams {
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE];
-};
-
-struct cras_observer_alert_data_hotword_triggered {
- int64_t tv_sec;
- int64_t tv_nsec;
-};
-
-struct cras_observer_non_empty_audio_state {
- int non_empty;
-};
-
-struct cras_observer_alert_data_bt_battery_changed {
- const char *address;
- uint32_t level;
-};
-
-/* Global observer instance. */
-static struct cras_observer_server *g_observer;
-
-/* Empty observer ops. */
-static struct cras_observer_ops g_empty_ops;
-
-/*
- * Alert handlers for delayed callbacks.
- */
-
-static void output_volume_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_volume *volume_data =
- (struct cras_observer_alert_data_volume *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.output_volume_changed)
- client->ops.output_volume_changed(client->context,
- volume_data->volume);
- }
-}
-
-static void output_mute_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_mute *mute_data =
- (struct cras_observer_alert_data_mute *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.output_mute_changed)
- client->ops.output_mute_changed(client->context,
- mute_data->muted,
- mute_data->user_muted,
- mute_data->mute_locked);
- }
-}
-
-static void capture_gain_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_volume *volume_data =
- (struct cras_observer_alert_data_volume *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.capture_gain_changed)
- client->ops.capture_gain_changed(client->context,
- volume_data->volume);
- }
-}
-
-static void capture_mute_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_mute *mute_data =
- (struct cras_observer_alert_data_mute *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.capture_mute_changed)
- client->ops.capture_mute_changed(
- client->context, mute_data->muted,
- mute_data->mute_locked);
- }
-}
-
-static void nodes_prepare(struct cras_alert *alert)
-{
- cras_iodev_list_update_device_list();
-}
-
-static void nodes_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.nodes_changed)
- client->ops.nodes_changed(client->context);
- }
-}
-
-static void active_node_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_active_node *node_data =
- (struct cras_observer_alert_data_active_node *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.active_node_changed)
- client->ops.active_node_changed(client->context,
- node_data->direction,
- node_data->node_id);
- }
-}
-
-static void output_node_volume_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_node_volume *node_data =
- (struct cras_observer_alert_data_node_volume *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.output_node_volume_changed)
- client->ops.output_node_volume_changed(
- client->context, node_data->node_id,
- node_data->volume);
- }
-}
-
-static void node_left_right_swapped_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_node_lr_swapped *node_data =
- (struct cras_observer_alert_data_node_lr_swapped *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.node_left_right_swapped_changed)
- client->ops.node_left_right_swapped_changed(
- client->context, node_data->node_id,
- node_data->swapped);
- }
-}
-
-static void input_node_gain_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_node_volume *node_data =
- (struct cras_observer_alert_data_node_volume *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.input_node_gain_changed)
- client->ops.input_node_gain_changed(client->context,
- node_data->node_id,
- node_data->volume);
- }
-}
-
-static void suspend_changed_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_suspend *suspend_data =
- (struct cras_observer_alert_data_suspend *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.suspend_changed)
- client->ops.suspend_changed(client->context,
- suspend_data->suspended);
- }
-}
-
-static void num_active_streams_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_streams *streams_data =
- (struct cras_observer_alert_data_streams *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.num_active_streams_changed)
- client->ops.num_active_streams_changed(
- client->context, streams_data->direction,
- streams_data->num_active_streams);
- }
-}
-
-static void num_input_streams_with_permission_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_input_streams *input_streams_data =
- (struct cras_observer_alert_data_input_streams *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.num_input_streams_with_permission_changed)
- client->ops.num_input_streams_with_permission_changed(
- client->context,
- input_streams_data->num_input_streams);
- }
-}
-
-static void hotword_triggered_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_hotword_triggered *triggered_data =
- (struct cras_observer_alert_data_hotword_triggered *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.hotword_triggered)
- client->ops.hotword_triggered(client->context,
- triggered_data->tv_sec,
- triggered_data->tv_nsec);
- }
-}
-
-static void non_empty_audio_state_changed_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_non_empty_audio_state *non_empty_audio_data =
- (struct cras_observer_non_empty_audio_state *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.non_empty_audio_state_changed) {
- client->ops.non_empty_audio_state_changed(
- client->context,
- non_empty_audio_data->non_empty);
- }
- }
-}
-
-static void bt_battery_changed_alert(void *arg, void *data)
-{
- struct cras_observer_client *client;
- struct cras_observer_alert_data_bt_battery_changed *triggered_data =
- (struct cras_observer_alert_data_bt_battery_changed *)data;
-
- DL_FOREACH (g_observer->clients, client) {
- if (client->ops.bt_battery_changed)
- client->ops.bt_battery_changed(client->context,
- triggered_data->address,
- triggered_data->level);
- }
-}
-
-static int cras_observer_server_set_alert(struct cras_alert **alert,
- cras_alert_cb cb,
- cras_alert_prepare prepare,
- unsigned int flags)
-{
- *alert = cras_alert_create(prepare, flags);
- if (!*alert)
- return -ENOMEM;
- return cras_alert_add_callback(*alert, cb, NULL);
-}
-
-#define CRAS_OBSERVER_SET_ALERT(alert, prepare, flags) \
- do { \
- rc = cras_observer_server_set_alert(&g_observer->alerts.alert, \
- alert##_alert, prepare, \
- flags); \
- if (rc) \
- goto error; \
- } while (0)
-
-#define CRAS_OBSERVER_SET_ALERT_WITH_DIRECTION(alert, direction) \
- do { \
- rc = cras_observer_server_set_alert( \
- &g_observer->alerts.alert[direction], alert##_alert, \
- NULL, 0); \
- if (rc) \
- goto error; \
- } while (0)
-
-/*
- * Public interface
- */
-
-int cras_observer_server_init()
-{
- int rc;
-
- memset(&g_empty_ops, 0, sizeof(g_empty_ops));
- g_observer = (struct cras_observer_server *)calloc(
- 1, sizeof(struct cras_observer_server));
- if (!g_observer)
- return -ENOMEM;
-
- CRAS_OBSERVER_SET_ALERT(output_volume, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(output_mute, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(capture_gain, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(capture_mute, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(nodes, nodes_prepare, 0);
- CRAS_OBSERVER_SET_ALERT(active_node, nodes_prepare,
- CRAS_ALERT_FLAG_KEEP_ALL_DATA);
- CRAS_OBSERVER_SET_ALERT(output_node_volume, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(node_left_right_swapped, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(input_node_gain, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(suspend_changed, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(hotword_triggered, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(non_empty_audio_state_changed, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(bt_battery_changed, NULL, 0);
- CRAS_OBSERVER_SET_ALERT(num_input_streams_with_permission, NULL, 0);
-
- CRAS_OBSERVER_SET_ALERT_WITH_DIRECTION(num_active_streams,
- CRAS_STREAM_OUTPUT);
- CRAS_OBSERVER_SET_ALERT_WITH_DIRECTION(num_active_streams,
- CRAS_STREAM_INPUT);
- CRAS_OBSERVER_SET_ALERT_WITH_DIRECTION(num_active_streams,
- CRAS_STREAM_POST_MIX_PRE_DSP);
-
- return 0;
-
-error:
- cras_observer_server_free();
- return rc;
-}
-
-void cras_observer_server_free()
-{
- if (!g_observer)
- return;
- cras_alert_destroy(g_observer->alerts.output_volume);
- cras_alert_destroy(g_observer->alerts.output_mute);
- cras_alert_destroy(g_observer->alerts.capture_gain);
- cras_alert_destroy(g_observer->alerts.capture_mute);
- cras_alert_destroy(g_observer->alerts.nodes);
- cras_alert_destroy(g_observer->alerts.active_node);
- cras_alert_destroy(g_observer->alerts.output_node_volume);
- cras_alert_destroy(g_observer->alerts.node_left_right_swapped);
- cras_alert_destroy(g_observer->alerts.input_node_gain);
- cras_alert_destroy(g_observer->alerts.suspend_changed);
- cras_alert_destroy(g_observer->alerts.hotword_triggered);
- cras_alert_destroy(g_observer->alerts.non_empty_audio_state_changed);
- cras_alert_destroy(g_observer->alerts.bt_battery_changed);
- cras_alert_destroy(
- g_observer->alerts.num_input_streams_with_permission);
- cras_alert_destroy(
- g_observer->alerts.num_active_streams[CRAS_STREAM_OUTPUT]);
- cras_alert_destroy(
- g_observer->alerts.num_active_streams[CRAS_STREAM_INPUT]);
- cras_alert_destroy(
- g_observer->alerts
- .num_active_streams[CRAS_STREAM_POST_MIX_PRE_DSP]);
- free(g_observer);
- g_observer = NULL;
-}
-
-int cras_observer_ops_are_empty(const struct cras_observer_ops *ops)
-{
- return memcmp(ops, &g_empty_ops, sizeof(*ops)) == 0;
-}
-
-void cras_observer_get_ops(const struct cras_observer_client *client,
- struct cras_observer_ops *ops)
-{
- if (!ops)
- return;
- if (!client)
- memset(ops, 0, sizeof(*ops));
- else
- memcpy(ops, &client->ops, sizeof(*ops));
-}
-
-void cras_observer_set_ops(struct cras_observer_client *client,
- const struct cras_observer_ops *ops)
-{
- if (!client)
- return;
- if (!ops)
- memset(&client->ops, 0, sizeof(client->ops));
- else
- memcpy(&client->ops, ops, sizeof(client->ops));
-}
-
-struct cras_observer_client *
-cras_observer_add(const struct cras_observer_ops *ops, void *context)
-{
- struct cras_observer_client *client;
-
- client = (struct cras_observer_client *)calloc(1, sizeof(*client));
- if (!client)
- return NULL;
- client->context = context;
- DL_APPEND(g_observer->clients, client);
- cras_observer_set_ops(client, ops);
- return client;
-}
-
-void cras_observer_remove(struct cras_observer_client *client)
-{
- if (!client)
- return;
- DL_DELETE(g_observer->clients, client);
- free(client);
-}
-
-/*
- * Public interface for notifiers.
- */
-
-void cras_observer_notify_output_volume(int32_t volume)
-{
- struct cras_observer_alert_data_volume data;
-
- data.volume = volume;
- cras_alert_pending_data(g_observer->alerts.output_volume, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_output_mute(int muted, int user_muted,
- int mute_locked)
-{
- struct cras_observer_alert_data_mute data;
-
- data.muted = muted;
- data.user_muted = user_muted;
- data.mute_locked = mute_locked;
- cras_alert_pending_data(g_observer->alerts.output_mute, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_capture_gain(int32_t gain)
-{
- struct cras_observer_alert_data_volume data;
-
- data.volume = gain;
- cras_alert_pending_data(g_observer->alerts.capture_gain, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_capture_mute(int muted, int mute_locked)
-{
- struct cras_observer_alert_data_mute data;
-
- data.muted = muted;
- data.user_muted = 0;
- data.mute_locked = mute_locked;
- cras_alert_pending_data(g_observer->alerts.capture_mute, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_nodes(void)
-{
- cras_alert_pending(g_observer->alerts.nodes);
-}
-
-void cras_observer_notify_active_node(enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_observer_alert_data_active_node data;
-
- data.direction = dir;
- data.node_id = node_id;
- cras_alert_pending_data(g_observer->alerts.active_node, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_output_node_volume(cras_node_id_t node_id,
- int32_t volume)
-{
- struct cras_observer_alert_data_node_volume data;
-
- data.node_id = node_id;
- data.volume = volume;
- cras_alert_pending_data(g_observer->alerts.output_node_volume, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_node_left_right_swapped(cras_node_id_t node_id,
- int swapped)
-{
- struct cras_observer_alert_data_node_lr_swapped data;
-
- data.node_id = node_id;
- data.swapped = swapped;
- cras_alert_pending_data(g_observer->alerts.node_left_right_swapped,
- &data, sizeof(data));
-}
-
-void cras_observer_notify_input_node_gain(cras_node_id_t node_id, int32_t gain)
-{
- struct cras_observer_alert_data_node_volume data;
-
- data.node_id = node_id;
- data.volume = gain;
- cras_alert_pending_data(g_observer->alerts.input_node_gain, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_suspend_changed(int suspended)
-{
- struct cras_observer_alert_data_suspend data;
-
- data.suspended = suspended;
- cras_alert_pending_data(g_observer->alerts.suspend_changed, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_num_active_streams(enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams)
-{
- struct cras_observer_alert_data_streams data;
- struct cras_alert *alert;
-
- data.direction = dir;
- data.num_active_streams = num_active_streams;
- alert = g_observer->alerts.num_active_streams[dir];
- if (!alert)
- return;
-
- cras_alert_pending_data(alert, &data, sizeof(data));
-}
-
-void cras_observer_notify_input_streams_with_permission(
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE])
-{
- struct cras_observer_alert_data_input_streams data;
- struct cras_alert *alert;
-
- memcpy(&data.num_input_streams, num_input_streams,
- sizeof(*num_input_streams) * CRAS_NUM_CLIENT_TYPE);
- alert = g_observer->alerts.num_input_streams_with_permission;
- if (!alert)
- return;
-
- cras_alert_pending_data(alert, &data, sizeof(data));
-}
-
-void cras_observer_notify_hotword_triggered(int64_t tv_sec, int64_t tv_nsec)
-{
- struct cras_observer_alert_data_hotword_triggered data;
-
- data.tv_sec = tv_sec;
- data.tv_nsec = tv_nsec;
- cras_alert_pending_data(g_observer->alerts.hotword_triggered, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_non_empty_audio_state_changed(int non_empty)
-{
- struct cras_observer_non_empty_audio_state data;
-
- data.non_empty = non_empty;
-
- cras_alert_pending_data(
- g_observer->alerts.non_empty_audio_state_changed, &data,
- sizeof(data));
-}
-
-void cras_observer_notify_bt_battery_changed(const char *address,
- uint32_t level)
-{
- struct cras_observer_alert_data_bt_battery_changed data;
-
- data.address = address;
- data.level = level;
-
- cras_alert_pending_data(g_observer->alerts.bt_battery_changed, &data,
- sizeof(data));
-}
diff --git a/cras/src/server/cras_observer.h b/cras/src/server/cras_observer.h
deleted file mode 100644
index 2dd013b8..00000000
--- a/cras/src/server/cras_observer.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_OBSERVER_H
-#define CRAS_OBSERVER_H
-
-#include "cras_observer_ops.h"
-
-struct cras_observer_client;
-
-/* Add an observer.
- * Args:
- * ops - Set callback function pointers in the operations that should be
- * called for state changes, or NULL otherwise.
- * context - Context pointer passed to the callbacks.
- * Returns:
- * Valid pointer to the client reference, or NULL on memory allocation
- * error.
- */
-struct cras_observer_client *
-cras_observer_add(const struct cras_observer_ops *ops, void *context);
-
-/* Retrieve the observed state changes.
- * Args:
- * client - The client to query.
- * ops - Filled with the current values in the callback table.
- */
-void cras_observer_get_ops(const struct cras_observer_client *client,
- struct cras_observer_ops *ops);
-
-/* Update the observed state changes.
- * Args:
- * client - The client to modify.
- * ops - Set callback function pointers in the operations that should be
- * called for state changes, or NULL otherwise.
- */
-void cras_observer_set_ops(struct cras_observer_client *client,
- const struct cras_observer_ops *ops);
-
-/* Returns non-zero if the given ops are empty. */
-int cras_observer_ops_are_empty(const struct cras_observer_ops *ops);
-
-/* Remove this observer client.
- * Args:
- * client - The client to remove.
- */
-void cras_observer_remove(struct cras_observer_client *client);
-
-/* Initialize the observer server. */
-int cras_observer_server_init();
-
-/* Destroy the observer server. */
-void cras_observer_server_free();
-
-/* Notify observers of output volume change. */
-void cras_observer_notify_output_volume(int32_t volume);
-
-/* Notify observers of output mute change. */
-void cras_observer_notify_output_mute(int muted, int user_muted,
- int mute_locked);
-
-/* Notify observers of capture gain change. */
-void cras_observer_notify_capture_gain(int32_t gain);
-
-/* Notify observers of capture mute change. */
-void cras_observer_notify_capture_mute(int muted, int mute_locked);
-
-/* Notify observers of a nodes list change. */
-void cras_observer_notify_nodes(void);
-
-/* Notify observers of active output node change. */
-void cras_observer_notify_active_node(enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id);
-
-/* Notify observers of output node volume change. */
-void cras_observer_notify_output_node_volume(cras_node_id_t node_id,
- int32_t volume);
-
-/* Notify observers of node left-right swap change. */
-void cras_observer_notify_node_left_right_swapped(cras_node_id_t node_id,
- int swapped);
-
-/* Notify observers of input node gain change. */
-void cras_observer_notify_input_node_gain(cras_node_id_t node_id, int32_t gain);
-
-/* Notify observers of suspend state changed. */
-void cras_observer_notify_suspend_changed(int suspended);
-
-/* Notify observers of the number of active streams. */
-void cras_observer_notify_num_active_streams(enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams);
-
-/* Notify observers of the number of input streams with permission. */
-void cras_observer_notify_input_streams_with_permission(
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE]);
-
-/* Notify observers of the timestamp when hotword triggered. */
-void cras_observer_notify_hotword_triggered(int64_t tv_sec, int64_t tv_nsec);
-
-/* Notify observers the non-empty audio state changed. */
-void cras_observer_notify_non_empty_audio_state_changed(int active);
-
-/* Notify observers the bluetooth headset battery level changed. */
-void cras_observer_notify_bt_battery_changed(const char *address,
- uint32_t level);
-
-#endif /* CRAS_OBSERVER_H */
diff --git a/cras/src/server/cras_playback_rclient.c b/cras/src/server/cras_playback_rclient.c
deleted file mode 100644
index 54a75dbd..00000000
--- a/cras/src/server/cras_playback_rclient.c
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_iodev_list.h"
-#include "cras_messages.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_rclient_util.h"
-#include "cras_rstream.h"
-#include "cras_types.h"
-#include "cras_util.h"
-
-/* Declarations of cras_rclient operators for cras_playback_rclient. */
-static const struct cras_rclient_ops cras_playback_rclient_ops = {
- .handle_message_from_client = rclient_handle_message_from_client,
- .send_message_to_client = rclient_send_message_to_client,
- .destroy = rclient_destroy,
-};
-
-/*
- * Exported Functions.
- */
-
-/* Creates a client structure and sends a message back informing the client that
- * the connection has succeeded. */
-struct cras_rclient *cras_playback_rclient_create(int fd, size_t id)
-{
- return rclient_generic_create(
- fd, id, &cras_playback_rclient_ops,
- cras_stream_direction_mask(CRAS_STREAM_OUTPUT));
-}
diff --git a/cras/src/server/cras_playback_rclient.h b/cras/src/server/cras_playback_rclient.h
deleted file mode 100644
index 37f03cfb..00000000
--- a/cras/src/server/cras_playback_rclient.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_PLAYBACK_RCLIENT_H_
-#define CRAS_PLAYBACK_RCLIENT_H_
-
-struct cras_rclient;
-
-/* Creates a playback rclient structure.
- * Args:
- * fd - The file descriptor used for communication with the client.
- * id - Unique identifier for this client.
- * Returns:
- * A pointer to the newly created rclient on success, NULL on failure.
- */
-struct cras_rclient *cras_playback_rclient_create(int fd, size_t id);
-
-#endif /* CRAS_PLAYBACK_RCLIENT_H_ */
diff --git a/cras/src/server/cras_ramp.c b/cras/src/server/cras_ramp.c
deleted file mode 100644
index f0272047..00000000
--- a/cras/src/server/cras_ramp.c
+++ /dev/null
@@ -1,136 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_ramp.h"
-
-/*
- * Struct to hold ramping information.
- * Members:
- * state: Current state. One of CRAS_RAMP_STATE.
- * ramped_frames: Number of frames that have passed after starting ramping.
- * duration_frames: The targeted number of frames for whole ramping duration.
- * increment: The scaler increment that should be added to scaler for
- * every frame.
- * start_scaler: The initial scaler.
- * cb: Callback function to call after ramping is done.
- * cb_data: Data passed to cb.
- */
-struct cras_ramp {
- int active;
- int ramped_frames;
- int duration_frames;
- float increment;
- float start_scaler;
- float target;
- void (*cb)(void *data);
- void *cb_data;
-};
-
-void cras_ramp_destroy(struct cras_ramp *ramp)
-{
- free(ramp);
-}
-
-struct cras_ramp *cras_ramp_create()
-{
- struct cras_ramp *ramp;
- ramp = (struct cras_ramp *)malloc(sizeof(*ramp));
- if (ramp == NULL) {
- return NULL;
- }
- cras_ramp_reset(ramp);
- return ramp;
-}
-
-int cras_ramp_reset(struct cras_ramp *ramp)
-{
- ramp->active = 0;
- ramp->ramped_frames = 0;
- ramp->duration_frames = 0;
- ramp->increment = 0;
- ramp->start_scaler = 1.0;
- ramp->target = 1.0;
- return 0;
-}
-
-int cras_ramp_start(struct cras_ramp *ramp, int mute_ramp, float from, float to,
- int duration_frames, cras_ramp_cb cb, void *cb_data)
-{
- struct cras_ramp_action action;
-
- if (!ramp)
- return -EINVAL;
-
- /* if from == to == 0 means we want to mute for duration_frames */
- if (from == to && from != 0)
- return 0;
-
- /* Get current scaler position so it can serve as new start scaler. */
- action = cras_ramp_get_current_action(ramp);
- if (action.type == CRAS_RAMP_ACTION_INVALID)
- return -EINVAL;
-
- /* Set initial scaler to current scaler so ramping up/down can be
- * smoothly switched. */
- ramp->active = 1;
- if (action.type == CRAS_RAMP_ACTION_NONE) {
- ramp->start_scaler = from;
- } else {
- /* If this a mute ramp, we want to match the previous multiplier
- * so that there is not a jump in the audio. Otherwise, we are
- * applying a volume ramp so we need to multiply |from| by the
- * previous scaler so that we can stack volume ramps. */
- ramp->start_scaler = action.scaler;
- if (!mute_ramp)
- ramp->start_scaler *= from;
- }
- ramp->increment = (to - ramp->start_scaler) / duration_frames;
- ramp->target = to;
- ramp->ramped_frames = 0;
- ramp->duration_frames = duration_frames;
- ramp->cb = cb;
- ramp->cb_data = cb_data;
- return 0;
-}
-
-struct cras_ramp_action
-cras_ramp_get_current_action(const struct cras_ramp *ramp)
-{
- struct cras_ramp_action action;
-
- if (ramp->ramped_frames < 0) {
- action.type = CRAS_RAMP_ACTION_INVALID;
- action.scaler = 1.0;
- action.increment = 0.0;
- action.target = 1.0;
- } else if (ramp->active) {
- action.type = CRAS_RAMP_ACTION_PARTIAL;
- action.scaler = ramp->start_scaler +
- ramp->ramped_frames * ramp->increment;
- action.increment = ramp->increment;
- action.target = ramp->target;
- } else {
- action.type = CRAS_RAMP_ACTION_NONE;
- action.scaler = 1.0;
- action.increment = 0.0;
- action.target = 1.0;
- }
- return action;
-}
-
-int cras_ramp_update_ramped_frames(struct cras_ramp *ramp, int num_frames)
-{
- if (!ramp->active)
- return -EINVAL;
- ramp->ramped_frames += num_frames;
- if (ramp->ramped_frames >= ramp->duration_frames) {
- ramp->active = 0;
- if (ramp->cb)
- ramp->cb(ramp->cb_data);
- }
- return 0;
-}
diff --git a/cras/src/server/cras_ramp.h b/cras/src/server/cras_ramp.h
deleted file mode 100644
index 077e9bea..00000000
--- a/cras/src/server/cras_ramp.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_RAMP_H_
-#define CRAS_RAMP_H_
-
-#include "cras_iodev.h"
-
-struct cras_ramp;
-
-/*
- * Infomation telling user how to do ramping.
- * action CRAS_RAMP_ACTION_NONE: No scale should be applied.
- * action CRAS_RAMP_ACTION_PARTIAL: scale sample by sample starting from scaler
- * and increase increment for each sample.
- * action CRAS_RAMP_ACTION_INVALID: There is an error in cras_ramp.
- */
-enum CRAS_RAMP_ACTION_TYPE {
- CRAS_RAMP_ACTION_NONE,
- CRAS_RAMP_ACTION_PARTIAL,
- CRAS_RAMP_ACTION_INVALID,
-};
-
-/*
- * Struct to hold current ramping action for user.
- * Members:
- * type: See CRAS_RAMP_ACTION_TYPE.
- * scaler: The initial scaler to be applied.
- * increment: The scaler increment that should be added to scaler for every
- * frame.
- */
-struct cras_ramp_action {
- enum CRAS_RAMP_ACTION_TYPE type;
- float scaler;
- float increment;
- float target;
-};
-
-typedef void (*cras_ramp_cb)(void *arg);
-
-/* Creates a ramp. */
-struct cras_ramp *cras_ramp_create();
-
-/* Destroys a ramp. */
-void cras_ramp_destroy(struct cras_ramp *ramp);
-
-/* Ramps the scaler between from and to for duration_frames frames.
- * Args:
- * ramp[in]: The ramp struct to start.
- * mute_ramp[in]: Is this ramp a mute->unmute or unmute->mute ramp.
- * from[in]: The scaler value to ramp from.
- * to[in]: The scaler value to ramp to.
- * duration_frames[in]: Ramp duration in frames.
- * cb[in]: The callback function to call after ramping is done. User can set
- * cb to turn off speaker/headphone switch after ramping down
- * is done.
- * cb_data[in]: The data passed to callback function.
- * Returns:
- * 0 on success; negative error code on failure.
- */
-int cras_ramp_start(struct cras_ramp *ramp, int mute_ramp, float from, float to,
- int duration_frames, cras_ramp_cb cb, void *cb_data);
-
-/* Convenience wrappers for cras_ramp_start */
-static inline int cras_mute_ramp_start(struct cras_ramp *ramp, float from,
- float to, int duration_frames,
- cras_ramp_cb cb, void *cb_data)
-{
- return cras_ramp_start(ramp, 1, from, to, duration_frames, cb, cb_data);
-}
-
-static inline int cras_volume_ramp_start(struct cras_ramp *ramp, float from,
- float to, int duration_frames,
- cras_ramp_cb cb, void *cb_data)
-{
- return cras_ramp_start(ramp, 0, from, to, duration_frames, cb, cb_data);
-}
-
-/* Resets ramp and cancels current ramping. */
-int cras_ramp_reset(struct cras_ramp *ramp);
-
-/* Gets current ramp action. */
-struct cras_ramp_action
-cras_ramp_get_current_action(const struct cras_ramp *ramp);
-
-/* Updates number of samples that went through ramping. */
-int cras_ramp_update_ramped_frames(struct cras_ramp *ramp, int num_frames);
-
-#endif /* CRAS_RAMP_H_ */
diff --git a/cras/src/server/cras_rclient.c b/cras/src/server/cras_rclient.c
deleted file mode 100644
index d2646e75..00000000
--- a/cras/src/server/cras_rclient.c
+++ /dev/null
@@ -1,101 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <assert.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include "audio_thread.h"
-#include "cras_apm_list.h"
-#include "cras_bt_log.h"
-#include "cras_capture_rclient.h"
-#include "cras_config.h"
-#include "cras_control_rclient.h"
-#include "cras_dsp.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_messages.h"
-#include "cras_observer.h"
-#include "cras_playback_rclient.h"
-#include "cras_rclient.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_unified_rclient.h"
-#include "cras_util.h"
-#include "stream_list.h"
-#include "utlist.h"
-
-/* Removes all streams that the client owns and destroys it. */
-void cras_rclient_destroy(struct cras_rclient *client)
-{
- client->ops->destroy(client);
-}
-
-/* Entry point for handling a message from the client. Called from the main
- * server context. */
-int cras_rclient_buffer_from_client(struct cras_rclient *client,
- const uint8_t *buf, size_t buf_len,
- int *fds, int num_fds)
-{
- struct cras_server_message *msg = (struct cras_server_message *)buf;
-
- if (buf_len < sizeof(*msg))
- return -EINVAL;
- if (msg->length != buf_len)
- return -EINVAL;
- return client->ops->handle_message_from_client(client, msg, fds,
- num_fds);
-}
-
-/* Sends a message to the client. */
-int cras_rclient_send_message(const struct cras_rclient *client,
- const struct cras_client_message *msg, int *fds,
- unsigned int num_fds)
-{
- return client->ops->send_message_to_client(client, msg, fds, num_fds);
-}
-
-static void cras_rclient_set_client_type(struct cras_rclient *client,
- enum CRAS_CLIENT_TYPE client_type)
-{
- client->client_type = client_type;
-}
-
-struct cras_rclient *cras_rclient_create(int fd, size_t id,
- enum CRAS_CONNECTION_TYPE conn_type)
-{
- struct cras_rclient *client;
- if (!cras_validate_connection_type(conn_type))
- goto error;
-
- switch (conn_type) {
- case CRAS_CONTROL:
- return cras_control_rclient_create(fd, id);
- case CRAS_PLAYBACK:
- return cras_playback_rclient_create(fd, id);
- case CRAS_CAPTURE:
- return cras_capture_rclient_create(fd, id);
- case CRAS_VMS_LEGACY:
- return cras_playback_rclient_create(fd, id);
- case CRAS_VMS_UNIFIED:
- return cras_unified_rclient_create(fd, id);
- case CRAS_PLUGIN_PLAYBACK:
- client = cras_playback_rclient_create(fd, id);
- cras_rclient_set_client_type(client, CRAS_CLIENT_TYPE_PLUGIN);
- return client;
- case CRAS_PLUGIN_UNIFIED:
- client = cras_unified_rclient_create(fd, id);
- cras_rclient_set_client_type(client, CRAS_CLIENT_TYPE_PLUGIN);
- return client;
- default:
- goto error;
- }
-
-error:
- syslog(LOG_ERR, "unsupported connection type");
- return NULL;
-}
diff --git a/cras/src/server/cras_rclient.h b/cras/src/server/cras_rclient.h
deleted file mode 100644
index 3a3988c2..00000000
--- a/cras/src/server/cras_rclient.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * A remote client to the server.
- */
-#ifndef CRAS_RCLIENT_H_
-#define CRAS_RCLIENT_H_
-
-#include "cras_types.h"
-
-struct cras_client_message;
-struct cras_message;
-struct cras_server_message;
-
-/* An attached client.
- * id - The id of the client.
- * fd - Connection for client communication.
- * ops - cras_rclient_ops for the cras_rclient.
- * supported_directions - Bit mask for supported stream directions.
- * client_type - Client type of this rclient. If this is set to value other
- * than CRAS_CLIENT_TYPE_UNKNOWN, rclient will overwrite incoming
- * messages' client type.
- */
-struct cras_rclient {
- struct cras_observer_client *observer;
- size_t id;
- int fd;
- const struct cras_rclient_ops *ops;
- int supported_directions;
- enum CRAS_CLIENT_TYPE client_type;
-};
-
-/* Operations for cras_rclient.
- * handle_message_from_client - Entry point for handling a message from the
- * corresponded client.
- * send_message_to_client - Method for sending message to the corresponded
- * client.
- * destroy - Method to destroy and free the cras_rclient.
- */
-struct cras_rclient_ops {
- int (*handle_message_from_client)(struct cras_rclient *,
- const struct cras_server_message *,
- int *fds, unsigned int num_fds);
- int (*send_message_to_client)(const struct cras_rclient *,
- const struct cras_client_message *,
- int *fds, unsigned int num_fds);
- void (*destroy)(struct cras_rclient *);
-};
-
-/* Creates an rclient structure.
- * Args:
- * fd - The file descriptor used for communication with the client.
- * id - Unique identifier for this client.
- * conn_type - Client connection type.
- * Returns:
- * A pointer to the newly created rclient on success, NULL on failure.
- */
-struct cras_rclient *cras_rclient_create(int fd, size_t id,
- enum CRAS_CONNECTION_TYPE conn_type);
-
-/* Destroys an rclient created with "cras_rclient_create".
- * Args:
- * client - The client to destroy.
- */
-void cras_rclient_destroy(struct cras_rclient *client);
-
-/* Handles a received buffer from the client.
- * Args:
- * client - The client that received this message.
- * buf - The raw byte buffer the client sent. It should contain a valid
- * cras_server_message.
- * buf_len - The length of |buf|.
- * fds - Array of valid file descriptors sent by the remote client.
- * num_fds - Length of |fds|.
- * Returns:
- * 0 on success, otherwise a negative error code.
- */
-int cras_rclient_buffer_from_client(struct cras_rclient *client,
- const uint8_t *buf, size_t buf_len,
- int *fds, int num_fds);
-
-/* Sends a message to the client.
- * Args:
- * client - The client to send the message to.
- * msg - The message to send.
- * fds - Array of file descriptors or null
- * num_fds - Number of entries in the fds array.
- * Returns:
- * number of bytes written on success, otherwise a negative error code.
- */
-int cras_rclient_send_message(const struct cras_rclient *client,
- const struct cras_client_message *msg, int *fds,
- unsigned int num_fds);
-
-#endif /* CRAS_RCLIENT_H_ */
diff --git a/cras/src/server/cras_rclient_util.c b/cras/src/server/cras_rclient_util.c
deleted file mode 100644
index 0af98863..00000000
--- a/cras/src/server/cras_rclient_util.c
+++ /dev/null
@@ -1,316 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_iodev_list.h"
-#include "cras_messages.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_rclient_util.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_tm.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "stream_list.h"
-
-int rclient_send_message_to_client(const struct cras_rclient *client,
- const struct cras_client_message *msg,
- int *fds, unsigned int num_fds)
-{
- return cras_send_with_fds(client->fd, (const void *)msg, msg->length,
- fds, num_fds);
-}
-
-void rclient_destroy(struct cras_rclient *client)
-{
- cras_observer_remove(client->observer);
- stream_list_rm_all_client_streams(cras_iodev_list_get_stream_list(),
- client);
- free(client);
-}
-
-int rclient_validate_message_fds(const struct cras_server_message *msg,
- int *fds, unsigned int num_fds)
-{
- switch (msg->id) {
- case CRAS_SERVER_CONNECT_STREAM:
- if (num_fds > 2)
- goto error;
- break;
- case CRAS_SERVER_SET_AEC_DUMP:
- if (num_fds > 1)
- goto error;
- break;
- default:
- if (num_fds > 0)
- goto error;
- break;
- }
-
- return 0;
-
-error:
- syslog(LOG_ERR, "Message %d should not have %u fds attached.", msg->id,
- num_fds);
- return -EINVAL;
-}
-
-static int
-rclient_validate_stream_connect_message(const struct cras_rclient *client,
- const struct cras_connect_message *msg)
-{
- if (!cras_valid_stream_id(msg->stream_id, client->id)) {
- syslog(LOG_ERR,
- "stream_connect: invalid stream_id: %x for "
- "client: %zx.\n",
- msg->stream_id, client->id);
- return -EINVAL;
- }
-
- int direction = cras_stream_direction_mask(msg->direction);
- if (direction < 0 || !(client->supported_directions & direction)) {
- syslog(LOG_ERR,
- "stream_connect: invalid stream direction: %x for "
- "client: %zx.\n",
- msg->direction, client->id);
- return -EINVAL;
- }
-
- if (!cras_validate_client_type(msg->client_type)) {
- syslog(LOG_ERR,
- "stream_connect: invalid stream client_type: %x for "
- "client: %zx.\n",
- msg->client_type, client->id);
- }
- return 0;
-}
-
-static int rclient_validate_stream_connect_fds(int audio_fd, int client_shm_fd,
- size_t client_shm_size)
-{
- /* check audio_fd is valid. */
- if (audio_fd < 0) {
- syslog(LOG_ERR, "Invalid audio fd in stream connect.\n");
- return -EBADF;
- }
-
- /* check client_shm_fd is valid if client wants to use client shm. */
- if (client_shm_size > 0 && client_shm_fd < 0) {
- syslog(LOG_ERR,
- "client_shm_fd must be valid if client_shm_size > 0.\n");
- return -EBADF;
- } else if (client_shm_size == 0 && client_shm_fd >= 0) {
- syslog(LOG_ERR,
- "client_shm_fd can be valid only if client_shm_size > 0.\n");
- return -EINVAL;
- }
- return 0;
-}
-
-int rclient_validate_stream_connect_params(
- const struct cras_rclient *client,
- const struct cras_connect_message *msg, int audio_fd, int client_shm_fd)
-{
- int rc;
-
- rc = rclient_validate_stream_connect_message(client, msg);
- if (rc)
- return rc;
-
- rc = rclient_validate_stream_connect_fds(audio_fd, client_shm_fd,
- msg->client_shm_size);
- if (rc)
- return rc;
-
- return 0;
-}
-
-int rclient_handle_client_stream_connect(struct cras_rclient *client,
- const struct cras_connect_message *msg,
- int aud_fd, int client_shm_fd)
-{
- struct cras_rstream *stream;
- struct cras_client_stream_connected stream_connected;
- struct cras_client_message *reply;
- struct cras_audio_format remote_fmt;
- struct cras_rstream_config stream_config;
- int rc, header_fd, samples_fd;
- size_t samples_size;
- int stream_fds[2];
-
- rc = rclient_validate_stream_connect_params(client, msg, aud_fd,
- client_shm_fd);
- remote_fmt = unpack_cras_audio_format(&msg->format);
- if (rc == 0 && !cras_audio_format_valid(&remote_fmt)) {
- rc = -EINVAL;
- }
- if (rc) {
- if (client_shm_fd >= 0)
- close(client_shm_fd);
- if (aud_fd >= 0)
- close(aud_fd);
- goto reply_err;
- }
-
- /* When full, getting an error is preferable to blocking. */
- cras_make_fd_nonblocking(aud_fd);
-
- stream_config = cras_rstream_config_init_with_message(
- client, msg, &aud_fd, &client_shm_fd, &remote_fmt);
- /* Overwrite client_type if client->client_type is set. */
- if (client->client_type != CRAS_CLIENT_TYPE_UNKNOWN)
- stream_config.client_type = client->client_type;
- rc = stream_list_add(cras_iodev_list_get_stream_list(), &stream_config,
- &stream);
- if (rc)
- goto cleanup_config;
-
- detect_rtc_stream_pair(cras_iodev_list_get_stream_list(), stream);
-
- /* Tell client about the stream setup. */
- syslog(LOG_DEBUG, "Send connected for stream %x\n", msg->stream_id);
-
- // Check that shm size is at most UINT32_MAX for non-shm streams.
- samples_size = cras_rstream_get_samples_shm_size(stream);
- if (samples_size > UINT32_MAX && stream_config.client_shm_fd < 0) {
- syslog(LOG_ERR,
- "Non client-provided shm stream has samples shm larger "
- "than uint32_t: %zu",
- samples_size);
- if (aud_fd >= 0)
- close(aud_fd);
- rc = -EINVAL;
- goto cleanup_config;
- }
- cras_fill_client_stream_connected(&stream_connected, 0, /* No error. */
- msg->stream_id, &remote_fmt,
- samples_size,
- cras_rstream_get_effects(stream));
- reply = &stream_connected.header;
-
- rc = cras_rstream_get_shm_fds(stream, &header_fd, &samples_fd);
- if (rc)
- goto cleanup_config;
-
- stream_fds[0] = header_fd;
- /* If we're using client-provided shm, samples_fd here refers to the
- * same shm area as client_shm_fd */
- stream_fds[1] = samples_fd;
-
- rc = client->ops->send_message_to_client(client, reply, stream_fds, 2);
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to send connected messaged\n");
- stream_list_rm(cras_iodev_list_get_stream_list(),
- stream->stream_id);
- goto cleanup_config;
- }
-
- /* Cleanup local object explicitly. */
- cras_rstream_config_cleanup(&stream_config);
- return 0;
-
-cleanup_config:
- cras_rstream_config_cleanup(&stream_config);
-
-reply_err:
- /* Send the error code to the client. */
- cras_fill_client_stream_connected(&stream_connected, rc, msg->stream_id,
- &remote_fmt, 0, msg->effects);
- reply = &stream_connected.header;
- client->ops->send_message_to_client(client, reply, NULL, 0);
-
- return rc;
-}
-
-/* Handles messages from the client requesting that a stream be removed from the
- * server. */
-int rclient_handle_client_stream_disconnect(
- struct cras_rclient *client,
- const struct cras_disconnect_stream_message *msg)
-{
- if (!cras_valid_stream_id(msg->stream_id, client->id)) {
- syslog(LOG_ERR,
- "stream_disconnect: invalid stream_id: %x for "
- "client: %zx.\n",
- msg->stream_id, client->id);
- return -EINVAL;
- }
- return stream_list_rm(cras_iodev_list_get_stream_list(),
- msg->stream_id);
-}
-
-/* Creates a client structure and sends a message back informing the client that
- * the connection has succeeded. */
-struct cras_rclient *rclient_generic_create(int fd, size_t id,
- const struct cras_rclient_ops *ops,
- int supported_directions)
-{
- struct cras_rclient *client;
- struct cras_client_connected msg;
- int state_fd;
-
- client = (struct cras_rclient *)calloc(1, sizeof(struct cras_rclient));
- if (!client)
- return NULL;
-
- client->fd = fd;
- client->id = id;
- client->ops = ops;
- client->supported_directions = supported_directions;
-
- cras_fill_client_connected(&msg, client->id);
- state_fd = cras_sys_state_shm_fd();
- client->ops->send_message_to_client(client, &msg.header, &state_fd, 1);
-
- return client;
-}
-
-/* A generic entry point for handling a message from the client. Called from
- * the main server context. */
-int rclient_handle_message_from_client(struct cras_rclient *client,
- const struct cras_server_message *msg,
- int *fds, unsigned int num_fds)
-{
- int rc = 0;
- assert(client && msg);
-
- rc = rclient_validate_message_fds(msg, fds, num_fds);
- if (rc < 0) {
- for (int i = 0; i < (int)num_fds; i++)
- if (fds[i] >= 0)
- close(fds[i]);
- return rc;
- }
- int fd = num_fds > 0 ? fds[0] : -1;
-
- switch (msg->id) {
- case CRAS_SERVER_CONNECT_STREAM: {
- int client_shm_fd = num_fds > 1 ? fds[1] : -1;
- if (MSG_LEN_VALID(msg, struct cras_connect_message)) {
- rclient_handle_client_stream_connect(
- client,
- (const struct cras_connect_message *)msg, fd,
- client_shm_fd);
- } else {
- return -EINVAL;
- }
- break;
- }
- case CRAS_SERVER_DISCONNECT_STREAM:
- if (!MSG_LEN_VALID(msg, struct cras_disconnect_stream_message))
- return -EINVAL;
- rclient_handle_client_stream_disconnect(
- client,
- (const struct cras_disconnect_stream_message *)msg);
- break;
- default:
- break;
- }
-
- return rc;
-}
diff --git a/cras/src/server/cras_rclient_util.h b/cras/src/server/cras_rclient_util.h
deleted file mode 100644
index 089c2ecb..00000000
--- a/cras/src/server/cras_rclient_util.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Common utility functions for rclients.
- */
-#ifndef CRAS_RCLIENT_UTIL_H_
-#define CRAS_RCLIENT_UTIL_H_
-
-#define MSG_LEN_VALID(msg, type) ((msg)->length >= sizeof(type))
-
-struct cras_connect_message;
-struct cras_rclient;
-struct cras_rclient_message;
-struct cras_rstream_config;
-struct cras_server_message;
-
-/* Sends a message to the client. */
-int rclient_send_message_to_client(const struct cras_rclient *client,
- const struct cras_client_message *msg,
- int *fds, unsigned int num_fds);
-
-/* Removes all streams that the client owns and destroys it. */
-void rclient_destroy(struct cras_rclient *client);
-
-/* Checks if the number of incoming fds matches the needs of the message from
- * client.
- *
- * Args:
- * msg - The cras_server_message from client.
- * fds - The array for incoming fds from client.
- * num_fds - The number of fds from client.
- *
- * Returns:
- * 0 on success. Or negative value if the number of fds is invalid.
- */
-int rclient_validate_message_fds(const struct cras_server_message *msg,
- int *fds, unsigned int num_fds);
-
-/* Checks if the incoming stream connect message contains
- * - stream_id matches client->id.
- * - direction supported by the client.
- *
- * Args:
- * client - The cras_rclient which gets the message.
- * msg - cras_connect_message from client.
- * audio_fd - Audio fd from client.
- * client_shm_fd - client shared memory fd from client. It can be -1.
- *
- * Returns:
- * 0 on success, negative error on failure.
- */
-int rclient_validate_stream_connect_params(
- const struct cras_rclient *client,
- const struct cras_connect_message *msg, int audio_fd,
- int client_shm_fd);
-
-/* Handles a message from the client to connect a new stream
- *
- * Args:
- * client - The cras_rclient which gets the message.
- * msg - The cras_connect_message from client.
- * aud_fd - The audio fd comes from client. Its ownership will be taken.
- * client_shm_fd - The client_shm_fd from client. Its ownership will be taken.
- *
- * Returns:
- * 0 on success, negative error on failure.
- */
-int rclient_handle_client_stream_connect(struct cras_rclient *client,
- const struct cras_connect_message *msg,
- int aud_fd, int client_shm_fd);
-
-/* Handles messages from the client requesting that a stream be removed from the
- * server.
- *
- * Args:
- * client - The cras_rclient which gets the message.
- * msg - The cras_disconnect_stream_message from client.
- *
- * Returns:
- * 0 on success, negative error on failure.
- */
-int rclient_handle_client_stream_disconnect(
- struct cras_rclient *client,
- const struct cras_disconnect_stream_message *msg);
-
-/* Generic rclient create function for different types of rclients.
- * Creates a client structure and sends a message back informing the client
- * that the connection has succeeded.
- *
- * Args:
- * fd - The file descriptor used for communication with the client.
- * id - Unique identifier for this client.
- * ops - cras_rclient_ops pointer for the client.
- * supported_directions - supported directions for the this rclient.
- * Returns:
- * A pointer to the newly created rclient on success, NULL on failure.
- */
-struct cras_rclient *rclient_generic_create(int fd, size_t id,
- const struct cras_rclient_ops *ops,
- int supported_directions);
-
-/* Generic handle_message_from_client function for different types of rlicnets.
- * Supports only stream connect and stream disconnect messages.
- *
- * If the message from clients has incorrect length (truncated message), return
- * an error up to CRAS server.
- * If the message from clients has invalid content, should return the errors to
- * clients by send_message_to_client and return 0 here.
- *
- * Args:
- * client - The cras_rclient which gets the message.
- * msg - The cras_server_message from client.
- * fds - The array for incoming fds from client.
- * num_fds - The number of fds from client.
- * Returns:
- * 0 on success, negative error on failure.
- */
-int rclient_handle_message_from_client(struct cras_rclient *client,
- const struct cras_server_message *msg,
- int *fds, unsigned int num_fds);
-
-#endif /* CRAS_RCLIENT_UTIL_H_ */
diff --git a/cras/src/server/cras_rstream.c b/cras/src/server/cras_rstream.c
deleted file mode 100644
index 3c0a0ce3..00000000
--- a/cras/src/server/cras_rstream.c
+++ /dev/null
@@ -1,560 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <fcntl.h>
-#include <stdint.h>
-#include <sys/mman.h>
-#include <sys/types.h>
-#include <syslog.h>
-
-#include "cras_audio_area.h"
-#include "cras_config.h"
-#include "cras_messages.h"
-#include "cras_rclient.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "cras_system_state.h"
-
-static bool cras_rstream_config_is_client_shm_stream(
- const struct cras_rstream_config *config)
-{
- return config && config->client_shm_fd >= 0 &&
- config->client_shm_size > 0;
-}
-
-/* Setup the shared memory area used for audio samples. config->client_shm_fd
- * must be closed after calling this function.
- */
-static inline int setup_shm_area(struct cras_rstream *stream,
- struct cras_rstream_config *config)
-{
- const struct cras_audio_format *fmt = &stream->format;
- char header_name[NAME_MAX];
- char samples_name[NAME_MAX];
- struct cras_shm_info header_info, samples_info;
- uint32_t frame_bytes, used_size;
- int rc;
- bool client_shm_stream =
- cras_rstream_config_is_client_shm_stream(config);
-
- if (stream->shm) {
- /* already setup */
- return -EEXIST;
- }
-
- snprintf(header_name, sizeof(header_name),
- "/cras-%d-stream-%08x-header", getpid(), stream->stream_id);
-
- rc = cras_shm_info_init(header_name, cras_shm_header_size(),
- &header_info);
- if (rc)
- return rc;
-
- frame_bytes = snd_pcm_format_physical_width(fmt->format) / 8 *
- fmt->num_channels;
- used_size = stream->buffer_frames * frame_bytes;
-
- if (client_shm_stream) {
- rc = cras_shm_info_init_with_fd(config->client_shm_fd,
- config->client_shm_size,
- &samples_info);
- } else {
- snprintf(samples_name, sizeof(samples_name),
- "/cras-%d-stream-%08x-samples", getpid(),
- stream->stream_id);
- rc = cras_shm_info_init(
- samples_name,
- cras_shm_calculate_samples_size(used_size),
- &samples_info);
- }
- if (rc) {
- cras_shm_info_cleanup(&header_info);
- return rc;
- }
-
- int samples_prot = 0;
- if (stream->direction == CRAS_STREAM_OUTPUT)
- samples_prot = PROT_READ;
- else
- samples_prot = PROT_WRITE;
-
- rc = cras_audio_shm_create(&header_info, &samples_info, samples_prot,
- &stream->shm);
- if (rc)
- return rc;
-
- cras_shm_set_frame_bytes(stream->shm, frame_bytes);
- cras_shm_set_used_size(stream->shm, used_size);
- if (client_shm_stream) {
- for (int i = 0; i < 2; i++)
- cras_shm_set_buffer_offset(stream->shm, i,
- config->buffer_offsets[i]);
- }
-
- stream->audio_area =
- cras_audio_area_create(stream->format.num_channels);
- cras_audio_area_config_channels(stream->audio_area, &stream->format);
-
- return 0;
-}
-
-static inline int buffer_meets_size_limit(size_t buffer_size, size_t rate)
-{
- return (buffer_size < (CRAS_MAX_BUFFER_TIME_IN_S * rate)) &&
- (buffer_size > (CRAS_MIN_BUFFER_TIME_IN_US * rate) / 1000000);
-}
-
-/* Verifies that the given stream parameters are valid. */
-static int verify_rstream_parameters(const struct cras_rstream_config *config,
- struct cras_rstream *const *stream_out)
-{
- const struct cras_audio_format *format = config->format;
-
- if (stream_out == NULL) {
- syslog(LOG_ERR, "rstream: stream_out can't be NULL\n");
- return -EINVAL;
- }
- if (format == NULL) {
- syslog(LOG_ERR, "rstream: format can't be NULL\n");
- return -EINVAL;
- }
- if (format->frame_rate < 4000 || format->frame_rate > 192000) {
- syslog(LOG_ERR, "rstream: invalid frame_rate %zu\n",
- format->frame_rate);
- return -EINVAL;
- }
- /*
- * Valid buffer settings:
- * Frames in 1ms <= cb_threshold <= buffer_frames <= Frames in 10s.
- */
- if (!buffer_meets_size_limit(config->buffer_frames,
- format->frame_rate)) {
- syslog(LOG_ERR, "rstream: invalid buffer_frames %zu\n",
- config->buffer_frames);
- return -EINVAL;
- }
- if (!buffer_meets_size_limit(config->cb_threshold,
- format->frame_rate) ||
- config->cb_threshold > config->buffer_frames) {
- syslog(LOG_ERR, "rstream: invalid cb_threshold %zu\n",
- config->cb_threshold);
- return -EINVAL;
- }
- if (format->num_channels < 0 || format->num_channels > CRAS_CH_MAX) {
- syslog(LOG_ERR, "rstream: invalid num_channels %zu\n",
- format->num_channels);
- return -EINVAL;
- }
- if ((format->format != SND_PCM_FORMAT_S16_LE) &&
- (format->format != SND_PCM_FORMAT_S32_LE) &&
- (format->format != SND_PCM_FORMAT_U8) &&
- (format->format != SND_PCM_FORMAT_S24_LE)) {
- syslog(LOG_ERR, "rstream: format %d not supported\n",
- format->format);
- return -EINVAL;
- }
- if (config->direction != CRAS_STREAM_OUTPUT &&
- config->direction != CRAS_STREAM_INPUT) {
- syslog(LOG_ERR, "rstream: Invalid direction.\n");
- return -EINVAL;
- }
- if (config->stream_type < CRAS_STREAM_TYPE_DEFAULT ||
- config->stream_type >= CRAS_STREAM_NUM_TYPES) {
- syslog(LOG_ERR, "rstream: Invalid stream type.\n");
- return -EINVAL;
- }
- if (config->client_type < CRAS_CLIENT_TYPE_UNKNOWN ||
- config->client_type >= CRAS_NUM_CLIENT_TYPE) {
- syslog(LOG_ERR, "rstream: Invalid client type.\n");
- return -EINVAL;
- }
- if ((config->client_shm_size > 0 && config->client_shm_fd < 0) ||
- (config->client_shm_size == 0 && config->client_shm_fd >= 0)) {
- syslog(LOG_ERR, "rstream: invalid client-provided shm info\n");
- return -EINVAL;
- }
- if (cras_rstream_config_is_client_shm_stream(config) &&
- (config->buffer_offsets[0] > config->client_shm_size ||
- config->buffer_offsets[1] > config->client_shm_size)) {
- syslog(LOG_ERR,
- "rstream: initial buffer offsets are outside shm area\n");
- return -EINVAL;
- }
-
- return 0;
-}
-
-/*
- * Setting pending reply is only needed inside this module.
- */
-static void set_pending_reply(struct cras_rstream *stream)
-{
- cras_shm_set_callback_pending(stream->shm, 1);
-}
-
-/*
- * Clearing pending reply is only needed inside this module.
- */
-static void clear_pending_reply(struct cras_rstream *stream)
-{
- cras_shm_set_callback_pending(stream->shm, 0);
-}
-
-/*
- * Reads one response of audio request from client.
- * Args:
- * stream[in]: A pointer to cras_rstream.
- * msg[out]: A pointer to audio_message to hold the message.
- * Returns:
- * Number of bytes read from the socket.
- * A negative error code if read fails or the message from client
- * has errors.
- */
-static int get_audio_request_reply(const struct cras_rstream *stream,
- struct audio_message *msg)
-{
- int rc;
-
- rc = read(stream->fd, msg, sizeof(*msg));
- if (rc < 0)
- return -errno;
- if (rc == 0)
- return rc;
- if (msg->error < 0)
- return msg->error;
- return rc;
-}
-
-/*
- * Reads and handles one audio message from client.
- * Returns:
- * Number of bytes read from the socket.
- * A negative error code if read fails or the message from client
- * has errors.
- */
-static int read_and_handle_client_message(struct cras_rstream *stream)
-{
- struct audio_message msg;
- int rc;
-
- rc = get_audio_request_reply(stream, &msg);
- if (rc <= 0) {
- clear_pending_reply(stream);
- return rc;
- }
-
- /*
- * Got client reply that data in the input stream is captured.
- */
- if (stream->direction == CRAS_STREAM_INPUT &&
- msg.id == AUDIO_MESSAGE_DATA_CAPTURED) {
- clear_pending_reply(stream);
- }
-
- /*
- * Got client reply that data for output stream is ready in shm.
- */
- if (stream->direction == CRAS_STREAM_OUTPUT &&
- msg.id == AUDIO_MESSAGE_DATA_READY) {
- clear_pending_reply(stream);
- }
-
- return rc;
-}
-
-/* Exported functions */
-
-int cras_rstream_create(struct cras_rstream_config *config,
- struct cras_rstream **stream_out)
-{
- struct cras_rstream *stream;
- int rc;
-
- rc = verify_rstream_parameters(config, stream_out);
- if (rc < 0)
- return rc;
-
- stream = calloc(1, sizeof(*stream));
- if (stream == NULL)
- return -ENOMEM;
-
- stream->stream_id = config->stream_id;
- stream->stream_type = config->stream_type;
- stream->client_type = config->client_type;
- stream->direction = config->direction;
- stream->flags = config->flags;
- stream->format = *config->format;
- stream->buffer_frames = config->buffer_frames;
- stream->cb_threshold = config->cb_threshold;
- stream->client = config->client;
- stream->shm = NULL;
- stream->main_dev.dev_id = NO_DEVICE;
- stream->main_dev.dev_ptr = NULL;
- stream->num_missed_cb = 0;
- stream->is_pinned = (config->dev_idx != NO_DEVICE);
- stream->pinned_dev_idx = config->dev_idx;
- ewma_power_init(&stream->ewma, stream->format.frame_rate);
-
- rc = setup_shm_area(stream, config);
- if (rc < 0) {
- syslog(LOG_ERR, "failed to setup shm %d\n", rc);
- free(stream);
- return rc;
- }
-
- stream->fd = config->audio_fd;
- config->audio_fd = -1;
- stream->buf_state = buffer_share_create(stream->buffer_frames);
- stream->apm_list =
- (stream->direction == CRAS_STREAM_INPUT) ?
- cras_apm_list_create(stream, config->effects) :
- NULL;
-
- syslog(LOG_DEBUG, "stream %x frames %zu, cb_thresh %zu",
- config->stream_id, config->buffer_frames, config->cb_threshold);
- *stream_out = stream;
-
- cras_system_state_stream_added(stream->direction, stream->client_type);
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &stream->start_ts);
-
- cras_server_metrics_stream_create(config);
-
- return 0;
-}
-
-void cras_rstream_destroy(struct cras_rstream *stream)
-{
- cras_server_metrics_stream_destroy(stream);
- cras_system_state_stream_removed(stream->direction,
- stream->client_type);
- close(stream->fd);
- cras_audio_shm_destroy(stream->shm);
- cras_audio_area_destroy(stream->audio_area);
- buffer_share_destroy(stream->buf_state);
- if (stream->apm_list)
- cras_apm_list_destroy(stream->apm_list);
- free(stream);
-}
-
-unsigned int cras_rstream_get_effects(const struct cras_rstream *stream)
-{
- return stream->apm_list ? cras_apm_list_get_effects(stream->apm_list) :
- 0;
-}
-
-struct cras_audio_format *
-cras_rstream_post_processing_format(const struct cras_rstream *stream,
- void *dev_ptr)
-{
- struct cras_apm *apm;
-
- apm = cras_apm_list_get_active_apm((void *)stream, dev_ptr);
- if (NULL == apm)
- return NULL;
- return cras_apm_list_get_format(apm);
-}
-
-void cras_rstream_record_fetch_interval(struct cras_rstream *rstream,
- const struct timespec *now)
-{
- struct timespec ts;
-
- if (rstream->last_fetch_ts.tv_sec || rstream->last_fetch_ts.tv_nsec) {
- subtract_timespecs(now, &rstream->last_fetch_ts, &ts);
- if (timespec_after(&ts, &rstream->longest_fetch_interval))
- rstream->longest_fetch_interval = ts;
- }
-}
-
-static void init_audio_message(struct audio_message *msg,
- enum CRAS_AUDIO_MESSAGE_ID id, uint32_t frames)
-{
- memset(msg, 0, sizeof(*msg));
- msg->id = id;
- msg->frames = frames;
-}
-
-int cras_rstream_request_audio(struct cras_rstream *stream,
- const struct timespec *now)
-{
- struct audio_message msg;
- int rc;
-
- /* Only request samples from output streams. */
- if (stream->direction != CRAS_STREAM_OUTPUT)
- return 0;
-
- stream->last_fetch_ts = *now;
-
- init_audio_message(&msg, AUDIO_MESSAGE_REQUEST_DATA,
- stream->cb_threshold);
- rc = write(stream->fd, &msg, sizeof(msg));
- if (rc < 0)
- return -errno;
-
- set_pending_reply(stream);
-
- return rc;
-}
-
-int cras_rstream_audio_ready(struct cras_rstream *stream, size_t count)
-{
- struct audio_message msg;
- int rc;
-
- cras_shm_buffer_write_complete(stream->shm);
-
- /* Mark shm as used. */
- if (stream_is_server_only(stream)) {
- cras_shm_buffer_read_current(stream->shm, count);
- return 0;
- }
-
- init_audio_message(&msg, AUDIO_MESSAGE_DATA_READY, count);
- rc = write(stream->fd, &msg, sizeof(msg));
- if (rc < 0)
- return -errno;
-
- set_pending_reply(stream);
-
- return rc;
-}
-
-void cras_rstream_dev_attach(struct cras_rstream *rstream, unsigned int dev_id,
- void *dev_ptr)
-{
- if (buffer_share_add_id(rstream->buf_state, dev_id, dev_ptr) == 0)
- rstream->num_attached_devs++;
-
- /* TODO(hychao): Handle main device assignment for complicated
- * routing case.
- */
- if (rstream->main_dev.dev_id == NO_DEVICE) {
- rstream->main_dev.dev_id = dev_id;
- rstream->main_dev.dev_ptr = dev_ptr;
- }
-}
-
-void cras_rstream_dev_detach(struct cras_rstream *rstream, unsigned int dev_id)
-{
- if (buffer_share_rm_id(rstream->buf_state, dev_id) == 0)
- rstream->num_attached_devs--;
-
- if (rstream->main_dev.dev_id == dev_id) {
- int i;
- struct id_offset *o;
-
- /* Choose the first device id as a main device. */
- rstream->main_dev.dev_id = NO_DEVICE;
- rstream->main_dev.dev_ptr = NULL;
- for (i = 0; i < rstream->buf_state->id_sz; i++) {
- o = &rstream->buf_state->wr_idx[i];
- if (o->used) {
- rstream->main_dev.dev_id = o->id;
- rstream->main_dev.dev_ptr = o->data;
- break;
- }
- }
- }
-}
-
-void cras_rstream_dev_offset_update(struct cras_rstream *rstream,
- unsigned int frames, unsigned int dev_id)
-{
- buffer_share_offset_update(rstream->buf_state, dev_id, frames);
-}
-
-void cras_rstream_update_input_write_pointer(struct cras_rstream *rstream)
-{
- unsigned int nwritten =
- buffer_share_get_new_write_point(rstream->buf_state);
-
- cras_shm_buffer_written(rstream->shm, nwritten);
-}
-
-void cras_rstream_update_output_read_pointer(struct cras_rstream *rstream)
-{
- size_t nfr = 0;
- uint8_t *src;
- unsigned int nwritten =
- buffer_share_get_new_write_point(rstream->buf_state);
-
- /* Retrieve the read pointer |src| start from which to calculate
- * the EWMA power. */
- src = cras_shm_get_readable_frames(rstream->shm, 0, &nfr);
- ewma_power_calculate(&rstream->ewma, (int16_t *)src,
- rstream->format.num_channels, nwritten);
- cras_shm_buffer_read(rstream->shm, nwritten);
-}
-
-unsigned int cras_rstream_dev_offset(const struct cras_rstream *rstream,
- unsigned int dev_id)
-{
- return buffer_share_id_offset(rstream->buf_state, dev_id);
-}
-
-void cras_rstream_update_queued_frames(struct cras_rstream *rstream)
-{
- rstream->queued_frames =
- MIN(cras_shm_get_frames(rstream->shm), rstream->buffer_frames);
-}
-
-unsigned int cras_rstream_playable_frames(struct cras_rstream *rstream,
- unsigned int dev_id)
-{
- return rstream->queued_frames -
- cras_rstream_dev_offset(rstream, dev_id);
-}
-
-float cras_rstream_get_volume_scaler(struct cras_rstream *rstream)
-{
- return cras_shm_get_volume_scaler(rstream->shm);
-}
-
-uint8_t *cras_rstream_get_readable_frames(struct cras_rstream *rstream,
- unsigned int offset, size_t *frames)
-{
- return cras_shm_get_readable_frames(rstream->shm, offset, frames);
-}
-
-int cras_rstream_get_mute(const struct cras_rstream *rstream)
-{
- return cras_shm_get_mute(rstream->shm);
-}
-
-int cras_rstream_is_pending_reply(const struct cras_rstream *stream)
-{
- return cras_shm_callback_pending(stream->shm);
-}
-
-int cras_rstream_flush_old_audio_messages(struct cras_rstream *stream)
-{
- struct pollfd pollfd;
- int err;
-
- if (!stream->fd)
- return 0;
-
- if (stream_is_server_only(stream))
- return 0;
-
- pollfd.fd = stream->fd;
- pollfd.events = POLLIN;
-
- do {
- err = poll(&pollfd, 1, 0);
- if (pollfd.revents & POLLIN) {
- err = read_and_handle_client_message(stream);
- }
- } while (err > 0);
-
- if (err < 0)
- syslog(LOG_ERR, "Error reading msg from client: rc: %d", err);
-
- return 0;
-}
diff --git a/cras/src/server/cras_rstream.h b/cras/src/server/cras_rstream.h
deleted file mode 100644
index d57c13be..00000000
--- a/cras/src/server/cras_rstream.h
+++ /dev/null
@@ -1,325 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Remote Stream - An audio steam from/to a client.
- */
-#ifndef CRAS_RSTREAM_H_
-#define CRAS_RSTREAM_H_
-
-#include "buffer_share.h"
-#include "cras_apm_list.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "cras_rstream_config.h"
-#include "ewma_power.h"
-
-struct cras_connect_message;
-struct cras_rclient;
-struct dev_mix;
-
-/* Holds informations about the main active device.
- * Members:
- * dev_id - id of the main device.
- * dev_ptr - pointer to the main device.
- */
-struct main_dev_info {
- int dev_id;
- void *dev_ptr;
-};
-
-/* cras_rstream is used to manage an active audio stream from
- * a client. Each client can have any number of open streams for
- * playing or recording.
- * Members:
- * stream_id - identifier for this stream.
- * stream_type - not used.
- * client_type - The client type of this stream, like Chrome, ARC++.
- * direction - input or output.
- * flags - Indicative of what special handling is needed.
- * fd - Socket for requesting and sending audio buffer events.
- * buffer_frames - Buffer size in frames.
- * cb_threshold - Callback client when this much is left.
- * main_dev_info - The info of the main device this stream attaches to.
- * is_draining - The stream is draining and waiting to be removed.
- * client - The client who uses this stream.
- * shm - shared memory
- * audio_area - space for playback/capture audio
- * format - format of the stream
- * next_cb_ts - Next callback time for this stream.
- * sleep_interval_ts - Time between audio callbacks.
- * last_fetch_ts - The time of the last stream fetch.
- * longest_fetch_interval_ts - Longest interval between two fetches.
- * start_ts - The time when the stream started.
- * first_missed_cb_ts - The time when the first missed callback happens.
- * buf_state - State of the buffer from all devices for this stream.
- * apm_list - List of audio processing module instances.
- * ewma - The ewma instance to calculate stream volume.
- * num_attached_devs - Number of iodevs this stream has attached to.
- * num_missed_cb - Number of callback schedules have been missed.
- * queued_frames - Cached value of the number of queued frames in shm.
- * is_pinned - True if the stream is a pinned stream, false otherwise.
- * pinned_dev_idx - device the stream is pinned, 0 if none.
- * triggered - True if already notified TRIGGER_ONLY stream, false otherwise.
- */
-struct cras_rstream {
- cras_stream_id_t stream_id;
- enum CRAS_STREAM_TYPE stream_type;
- enum CRAS_CLIENT_TYPE client_type;
- enum CRAS_STREAM_DIRECTION direction;
- uint32_t flags;
- int fd;
- size_t buffer_frames;
- size_t cb_threshold;
- int is_draining;
- struct main_dev_info main_dev;
- struct cras_rclient *client;
- struct cras_audio_shm *shm;
- struct cras_audio_area *audio_area;
- struct cras_audio_format format;
- struct timespec next_cb_ts;
- struct timespec sleep_interval_ts;
- struct timespec last_fetch_ts;
- struct timespec longest_fetch_interval;
- struct timespec start_ts;
- struct timespec first_missed_cb_ts;
- struct buffer_share *buf_state;
- struct cras_apm_list *apm_list;
- struct ewma_power ewma;
- int num_attached_devs;
- int num_missed_cb;
- int queued_frames;
- int is_pinned;
- uint32_t pinned_dev_idx;
- int triggered;
- struct cras_rstream *prev, *next;
-};
-
-/* Creates an rstream.
- * Args:
- * config - Params for configuration of the new rstream. It's a mutable
- * borrow.
- * stream_out - Filled with the newly created stream pointer.
- * Returns:
- * 0 on success, EINVAL if an invalid argument is passed, or ENOMEM if out of
- * memory.
- */
-int cras_rstream_create(struct cras_rstream_config *config,
- struct cras_rstream **stream_out);
-
-/* Destroys an rstream. */
-void cras_rstream_destroy(struct cras_rstream *stream);
-
-/* Gets the id of the stream */
-static inline cras_stream_id_t
-cras_rstream_id(const struct cras_rstream *stream)
-{
- return stream->stream_id;
-}
-
-/* Gets the total buffer size in frames for the given client stream. */
-static inline size_t
-cras_rstream_get_buffer_frames(const struct cras_rstream *stream)
-{
- return stream->buffer_frames;
-}
-
-/* Gets the callback threshold in frames for the given client stream. */
-static inline size_t
-cras_rstream_get_cb_threshold(const struct cras_rstream *stream)
-{
- return stream->cb_threshold;
-}
-
-/* Gets the max write size for the stream. */
-static inline size_t
-cras_rstream_get_max_write_frames(const struct cras_rstream *stream)
-{
- if (stream->flags & BULK_AUDIO_OK)
- return cras_rstream_get_buffer_frames(stream);
- return cras_rstream_get_cb_threshold(stream);
-}
-
-/* Gets the stream type of this stream. */
-static inline enum CRAS_STREAM_TYPE
-cras_rstream_get_type(const struct cras_rstream *stream)
-{
- return stream->stream_type;
-}
-
-/* Gets the direction (input/output/loopback) of the stream. */
-static inline enum CRAS_STREAM_DIRECTION
-cras_rstream_get_direction(const struct cras_rstream *stream)
-{
- return stream->direction;
-}
-
-/* Gets the format for the stream. */
-static inline void cras_rstream_set_format(struct cras_rstream *stream,
- const struct cras_audio_format *fmt)
-{
- stream->format = *fmt;
-}
-
-/* Sets the format for the stream. */
-static inline int cras_rstream_get_format(const struct cras_rstream *stream,
- struct cras_audio_format *fmt)
-{
- *fmt = stream->format;
- return 0;
-}
-
-/* Gets the fd to be used to poll this client for audio. */
-static inline int cras_rstream_get_audio_fd(const struct cras_rstream *stream)
-{
- return stream->fd;
-}
-
-/* Gets the is_draning flag. */
-static inline int
-cras_rstream_get_is_draining(const struct cras_rstream *stream)
-{
- return stream->is_draining;
-}
-
-/* Sets the is_draning flag. */
-static inline void cras_rstream_set_is_draining(struct cras_rstream *stream,
- int is_draining)
-{
- stream->is_draining = is_draining;
-}
-
-/* Gets the shm fds used for the stream shm */
-static inline int cras_rstream_get_shm_fds(const struct cras_rstream *stream,
- int *header_fd, int *samples_fd)
-{
- if (!header_fd || !samples_fd)
- return -EINVAL;
-
- *header_fd = stream->shm->header_info.fd;
- *samples_fd = stream->shm->samples_info.fd;
-
- return 0;
-}
-
-/* Gets the size of the shm area used for samples for this stream. */
-static inline size_t
-cras_rstream_get_samples_shm_size(const struct cras_rstream *stream)
-{
- return cras_shm_samples_size(stream->shm);
-}
-
-/* Gets shared memory region for this stream. */
-static inline struct cras_audio_shm *
-cras_rstream_shm(struct cras_rstream *stream)
-{
- return stream->shm;
-}
-
-/* Checks if the stream uses an output device. */
-static inline int stream_uses_output(const struct cras_rstream *s)
-{
- return cras_stream_uses_output_hw(s->direction);
-}
-
-/* Checks if the stream uses an input device. */
-static inline int stream_uses_input(const struct cras_rstream *s)
-{
- return cras_stream_uses_input_hw(s->direction);
-}
-
-static inline int stream_is_server_only(const struct cras_rstream *s)
-{
- return s->flags & SERVER_ONLY;
-}
-
-/* Gets the enabled effects of this stream. */
-unsigned int cras_rstream_get_effects(const struct cras_rstream *stream);
-
-/* Gets the format of data after stream specific processing. */
-struct cras_audio_format *
-cras_rstream_post_processing_format(const struct cras_rstream *stream,
- void *dev_ptr);
-
-/* Checks how much time has passed since last stream fetch and records
- * the longest fetch interval. */
-void cras_rstream_record_fetch_interval(struct cras_rstream *rstream,
- const struct timespec *now);
-
-/* Requests min_req frames from the client. */
-int cras_rstream_request_audio(struct cras_rstream *stream,
- const struct timespec *now);
-
-/* Tells a capture client that count frames are ready. */
-int cras_rstream_audio_ready(struct cras_rstream *stream, size_t count);
-
-/* Let the rstream know when a device is added or removed. */
-void cras_rstream_dev_attach(struct cras_rstream *rstream, unsigned int dev_id,
- void *dev_ptr);
-void cras_rstream_dev_detach(struct cras_rstream *rstream, unsigned int dev_id);
-
-static inline void *cras_rstream_dev_ptr(struct cras_rstream *rstream,
- unsigned int dev_id)
-{
- return buffer_share_get_data(rstream->buf_state, dev_id);
-}
-
-/* A device using this stream has read or written samples. */
-void cras_rstream_dev_offset_update(struct cras_rstream *rstream,
- unsigned int frames, unsigned int dev_id);
-
-void cras_rstream_update_input_write_pointer(struct cras_rstream *rstream);
-void cras_rstream_update_output_read_pointer(struct cras_rstream *rstream);
-
-unsigned int cras_rstream_dev_offset(const struct cras_rstream *rstream,
- unsigned int dev_id);
-
-static inline unsigned int cras_rstream_level(struct cras_rstream *rstream)
-{
- const struct cras_audio_shm *shm = cras_rstream_shm(rstream);
- return cras_shm_frames_written(shm);
-}
-
-static inline int cras_rstream_input_level_met(struct cras_rstream *rstream)
-{
- const struct cras_audio_shm *shm = cras_rstream_shm(rstream);
- return cras_shm_frames_written(shm) >= rstream->cb_threshold;
-}
-
-/* Updates the number of queued frames in shm. The queued frames should be
- * updated everytime before calling cras_rstream_playable_frames.
- */
-void cras_rstream_update_queued_frames(struct cras_rstream *rstream);
-
-/* Returns the number of playable samples in shm for the given device id. */
-unsigned int cras_rstream_playable_frames(struct cras_rstream *rstream,
- unsigned int dev_id);
-
-/* Returns the volume scaler for this stream. */
-float cras_rstream_get_volume_scaler(struct cras_rstream *rstream);
-
-/* Returns a pointer to readable frames, fills frames with the number of frames
- * available. */
-uint8_t *cras_rstream_get_readable_frames(struct cras_rstream *rstream,
- unsigned int offset, size_t *frames);
-
-/* Returns non-zero if the stream is muted. */
-int cras_rstream_get_mute(const struct cras_rstream *rstream);
-
-/*
- * Returns non-zero if the stream is pending a reply from client.
- * - For playback, stream is waiting for AUDIO_MESSAGE_DATA_READY message from
- * client.
- * - For capture, stream is waiting for AUDIO_MESSAGE_DATA_CAPTURED message
- * from client.
- */
-int cras_rstream_is_pending_reply(const struct cras_rstream *stream);
-
-/*
- * Reads any pending audio message from the socket.
- */
-int cras_rstream_flush_old_audio_messages(struct cras_rstream *stream);
-
-#endif /* CRAS_RSTREAM_H_ */
diff --git a/cras/src/server/cras_rstream_config.c b/cras/src/server/cras_rstream_config.c
deleted file mode 100644
index c5cd9c57..00000000
--- a/cras/src/server/cras_rstream_config.c
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <fcntl.h>
-#include <stdint.h>
-#include <sys/mman.h>
-#include <sys/types.h>
-#include <syslog.h>
-
-#include "cras_audio_area.h"
-#include "cras_config.h"
-#include "cras_messages.h"
-#include "cras_rclient.h"
-#include "cras_rstream.h"
-#include "cras_rstream_config.h"
-#include "cras_server_metrics.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "cras_system_state.h"
-
-void cras_rstream_config_init(
- struct cras_rclient *client, cras_stream_id_t stream_id,
- enum CRAS_STREAM_TYPE stream_type, enum CRAS_CLIENT_TYPE client_type,
- enum CRAS_STREAM_DIRECTION direction, uint32_t dev_idx, uint32_t flags,
- uint32_t effects, const struct cras_audio_format *format,
- size_t buffer_frames, size_t cb_threshold, int *audio_fd,
- int *client_shm_fd, size_t client_shm_size,
- const uint64_t buffer_offsets[2],
- struct cras_rstream_config *stream_config)
-{
- stream_config->stream_id = stream_id;
- stream_config->stream_type = stream_type;
- stream_config->client_type = client_type;
- stream_config->direction = direction;
- stream_config->dev_idx = dev_idx;
- stream_config->flags = flags;
- stream_config->effects = effects;
- stream_config->format = format;
- stream_config->buffer_frames = buffer_frames;
- stream_config->cb_threshold = cb_threshold;
- stream_config->audio_fd = *audio_fd;
- *audio_fd = -1;
- stream_config->client_shm_fd = *client_shm_fd;
- *client_shm_fd = -1;
- stream_config->client_shm_size = client_shm_size;
- stream_config->buffer_offsets[0] = buffer_offsets[0];
- stream_config->buffer_offsets[1] = buffer_offsets[1];
- stream_config->client = client;
-}
-
-struct cras_rstream_config cras_rstream_config_init_with_message(
- struct cras_rclient *client, const struct cras_connect_message *msg,
- int *aud_fd, int *client_shm_fd,
- const struct cras_audio_format *remote_fmt)
-{
- struct cras_rstream_config stream_config;
-
- const uint64_t buffer_offsets[2] = { msg->buffer_offsets[0],
- msg->buffer_offsets[1] };
- cras_rstream_config_init(client, msg->stream_id, msg->stream_type,
- msg->client_type, msg->direction, msg->dev_idx,
- msg->flags, msg->effects, remote_fmt,
- msg->buffer_frames, msg->cb_threshold, aud_fd,
- client_shm_fd, msg->client_shm_size,
- buffer_offsets, &stream_config);
- return stream_config;
-}
-
-void cras_rstream_config_cleanup(struct cras_rstream_config *stream_config)
-{
- if (stream_config->audio_fd >= 0)
- close(stream_config->audio_fd);
- if (stream_config->client_shm_fd >= 0)
- close(stream_config->client_shm_fd);
-}
diff --git a/cras/src/server/cras_rstream_config.h b/cras/src/server/cras_rstream_config.h
deleted file mode 100644
index 4d3713ce..00000000
--- a/cras/src/server/cras_rstream_config.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * Remote Stream Configuration
- */
-#ifndef CRAS_RSTREAM_CONFIG_H_
-#define CRAS_RSTREAM_CONFIG_H_
-
-#include "buffer_share.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-
-struct cras_connect_message;
-struct dev_mix;
-
-/* Config for creating an rstream.
- * stream_type - CRAS_STREAM_TYPE.
- * client_type - CRAS_CLIENT_TYPE.
- * direction - CRAS_STREAM_OUTPUT or CRAS_STREAM_INPUT.
- * dev_idx - Pin to this device if != NO_DEVICE.
- * flags - Any special handling for this stream.
- * effects - Bit map of effects to be enabled on this stream.
- * format - The audio format the stream wishes to use.
- * buffer_frames - Total number of audio frames to buffer.
- * cb_threshold - # of frames when to request more from the client.
- * audio_fd - The fd to read/write audio signals to. May be -1 for server
- * stream. Some functions may mutably borrow the config and move
- * the fd ownership.
- * client_shm_fd - The shm fd to use to back the samples area. May be -1.
- * Some functions may dup this fd while borrowing the config.
- * client_shm_size - The size of shm area backed by client_shm_fd.
- * buffer_offsets - Initial values for buffer_offset for a client shm stream.
- * client - The client that owns this stream.
- */
-struct cras_rstream_config {
- cras_stream_id_t stream_id;
- enum CRAS_STREAM_TYPE stream_type;
- enum CRAS_CLIENT_TYPE client_type;
- enum CRAS_STREAM_DIRECTION direction;
- uint32_t dev_idx;
- uint32_t flags;
- uint32_t effects;
- const struct cras_audio_format *format;
- size_t buffer_frames;
- size_t cb_threshold;
- int audio_fd;
- int client_shm_fd;
- size_t client_shm_size;
- uint32_t buffer_offsets[2];
- struct cras_rclient *client;
-};
-
-/* Fills cras_rstream_config with given parameters.
- *
- * Args:
- * audio_fd - The audio fd pointer from client. Its ownership will be moved to
- * stream_config.
- * client_shm_fd - The shared memory fd pointer for samples from client. Its
- * ownership will be moved to stream_config.
- * Other args - See comments in struct cras_rstream_config.
- */
-void cras_rstream_config_init(
- struct cras_rclient *client, cras_stream_id_t stream_id,
- enum CRAS_STREAM_TYPE stream_type, enum CRAS_CLIENT_TYPE client_type,
- enum CRAS_STREAM_DIRECTION direction, uint32_t dev_idx, uint32_t flags,
- uint32_t effects, const struct cras_audio_format *format,
- size_t buffer_frames, size_t cb_threshold, int *audio_fd,
- int *client_shm_fd, size_t client_shm_size,
- const uint64_t buffer_offsets[2],
- struct cras_rstream_config *stream_config);
-
-/* Fills cras_rstream_config with given parameters and a cras_connect_message.
- *
- * Args:
- * client - The rclient which handles the connect message.
- * msg - The cras_connect_message from client.
- * aud_fd - The audio fd pointer from client. Its ownership will be moved to
- * stream_config.
- * client_shm_fd - The shared memory fd pointer for samples from client. Its
- * ownership will be moved to stream_config.
- * remote_format - The remote_format for the config.
- *
- * Returns a cras_rstream_config struct filled in with params from the message.
- */
-struct cras_rstream_config cras_rstream_config_init_with_message(
- struct cras_rclient *client, const struct cras_connect_message *msg,
- int *aud_fd, int *client_shm_fd,
- const struct cras_audio_format *remote_format);
-
-/* Cleans up given cras_rstream_config. All fds inside the config will be
- * closed.
- *
- * Args:
- * stream_config - The config to be cleaned up.
- */
-void cras_rstream_config_cleanup(struct cras_rstream_config *stream_config);
-
-#endif /* CRAS_RSTREAM_CONFIG_H_ */
diff --git a/cras/src/server/cras_server.c b/cras/src/server/cras_server.c
deleted file mode 100644
index 5f2ce632..00000000
--- a/cras/src/server/cras_server.c
+++ /dev/null
@@ -1,720 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#define _GNU_SOURCE /* Needed for Linux socket credential passing. */
-
-#ifdef CRAS_DBUS
-#include <dbus/dbus.h>
-#endif
-#include <errno.h>
-#include <poll.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/param.h>
-#include <sys/select.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/un.h>
-#include <syslog.h>
-#include <unistd.h>
-
-#ifdef CRAS_DBUS
-#include "cras_a2dp_endpoint.h"
-#include "cras_bt_manager.h"
-#include "cras_bt_device.h"
-#include "cras_bt_player.h"
-#include "cras_dbus.h"
-#include "cras_dbus_control.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_telephony.h"
-#endif
-#include "cras_alert.h"
-#include "cras_audio_thread_monitor.h"
-#include "cras_config.h"
-#include "cras_device_monitor.h"
-#include "cras_hotword_handler.h"
-#include "cras_iodev_list.h"
-#include "cras_main_message.h"
-#include "cras_messages.h"
-#include "cras_metrics.h"
-#include "cras_non_empty_audio_handler.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_server.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-#include "cras_tm.h"
-#include "cras_types.h"
-#include "cras_udev.h"
-#include "cras_util.h"
-#include "cras_mix.h"
-#include "utlist.h"
-
-/* Store a list of clients that are attached to the server.
- * Members:
- * id - Unique identifier for this client.
- * fd - socket file descriptor used to communicate with client.
- * ucred - Process, user, and group ID of the client.
- * client - rclient to handle messages from this client.
- * pollfd - Pointer to struct pollfd for this callback.
- */
-struct attached_client {
- size_t id;
- int fd;
- struct ucred ucred;
- struct cras_rclient *client;
- struct pollfd *pollfd;
- struct attached_client *next, *prev;
-};
-
-/* Stores file descriptors to callback mappings for clients. Callback/fd/data
- * args are registered by clients. When fd is ready, the callback will be
- * called on the main server thread and the callback data will be passed back to
- * it. This allows the use of the main server loop instead of spawning a thread
- * to watch file descriptors. The client can then read or write the fd.
- * Members:
- * fd - The file descriptor passed to select.
- * callback - The funciton to call when fd is ready.
- * callback_data - Pointer passed to the callback.
- * pollfd - Pointer to struct pollfd for this callback.
- * events - The events to poll for.
- */
-struct client_callback {
- int select_fd;
- void (*callback)(void *data, int revents);
- void *callback_data;
- struct pollfd *pollfd;
- int deleted;
- int events;
- struct client_callback *prev, *next;
-};
-
-/* Stores callback function and argument data to be executed later. */
-struct system_task {
- void (*callback)(void *);
- void *callback_data;
- struct system_task *next, *prev;
-};
-
-/* A structure wraps data related to server socket. */
-struct server_socket {
- struct sockaddr_un addr;
- int fd;
- enum CRAS_CONNECTION_TYPE type;
-};
-
-/* Local server data. */
-struct server_data {
- struct attached_client *clients_head;
- size_t num_clients;
- struct client_callback *client_callbacks;
- struct system_task *system_tasks;
- size_t num_client_callbacks;
- size_t next_client_id;
- struct server_socket server_sockets[CRAS_NUM_CONN_TYPE];
-} server_instance;
-
-/* Cleanup a given server_socket */
-static void server_socket_cleanup(struct server_socket *socket)
-{
- if (socket && socket->fd >= 0) {
- close(socket->fd);
- socket->fd = -1;
- unlink(socket->addr.sun_path);
- }
-}
-
-/* Remove a client from the list and destroy it. Calling rclient_destroy will
- * also free all the streams owned by the client */
-static void remove_client(struct attached_client *client)
-{
- close(client->fd);
- DL_DELETE(server_instance.clients_head, client);
- server_instance.num_clients--;
- cras_rclient_destroy(client->client);
- free(client);
-}
-
-/* This is called when "select" indicates that the client has written data to
- * the socket. Read out one message and pass it to the client message handler.
- */
-static void handle_message_from_client(struct attached_client *client)
-{
- uint8_t buf[CRAS_SERV_MAX_MSG_SIZE];
- int nread;
- unsigned int num_fds = 2;
- int fds[num_fds];
-
- nread = cras_recv_with_fds(client->fd, buf, sizeof(buf), fds, &num_fds);
- if (nread < 0)
- goto read_error;
- if (cras_rclient_buffer_from_client(client->client, buf, nread, fds,
- num_fds) < 0)
- goto read_error;
- return;
-
-read_error:
- for (int i = 0; i < num_fds; i++)
- if (fds[i] >= 0)
- close(fds[i]);
- switch (nread) {
- case 0:
- break;
- default:
- syslog(LOG_DEBUG, "read err [%d] '%s', removing client %zu",
- -nread, strerror(-nread), client->id);
- break;
- }
- remove_client(client);
-}
-
-/* Discovers and fills in info about the client that can be obtained from the
- * socket. The pid of the attaching client identifies it in logs. */
-static void fill_client_info(struct attached_client *client)
-{
- socklen_t ucred_length = sizeof(client->ucred);
-
- if (getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED, &client->ucred,
- &ucred_length))
- syslog(LOG_INFO, "Failed to get client socket info\n");
-}
-
-/* Fills the server_state with the current list of attached clients. */
-static void send_client_list_to_clients(struct server_data *serv)
-{
- struct attached_client *c;
- struct cras_attached_client_info *info;
- struct cras_server_state *state;
- unsigned i;
-
- state = cras_system_state_update_begin();
- if (!state)
- return;
-
- state->num_attached_clients =
- MIN(CRAS_MAX_ATTACHED_CLIENTS, serv->num_clients);
-
- info = state->client_info;
- i = 0;
- DL_FOREACH (serv->clients_head, c) {
- info->id = c->id;
- info->pid = c->ucred.pid;
- info->uid = c->ucred.uid;
- info->gid = c->ucred.gid;
- info++;
- if (++i == CRAS_MAX_ATTACHED_CLIENTS)
- break;
- }
-
- cras_system_state_update_complete();
-}
-
-/* Handles requests from a client to attach to the server. Create a local
- * structure to track the client, assign it a unique id and let it attach */
-static void handle_new_connection(struct server_socket *server_socket)
-{
- int connection_fd;
- struct attached_client *poll_client;
- socklen_t address_length;
-
- poll_client = malloc(sizeof(struct attached_client));
- if (poll_client == NULL) {
- syslog(LOG_ERR, "Allocating poll_client");
- return;
- }
-
- memset(&address_length, 0, sizeof(address_length));
- connection_fd = accept(server_socket->fd,
- (struct sockaddr *)&server_socket->addr,
- &address_length);
- if (connection_fd < 0) {
- syslog(LOG_ERR, "connecting");
- free(poll_client);
- return;
- }
-
- /* find next available client id */
- while (1) {
- struct attached_client *out;
- DL_SEARCH_SCALAR(server_instance.clients_head, out, id,
- server_instance.next_client_id);
- poll_client->id = server_instance.next_client_id;
- server_instance.next_client_id++;
- if (out == NULL)
- break;
- }
-
- /* When full, getting an error is preferable to blocking. */
- cras_make_fd_nonblocking(connection_fd);
-
- poll_client->fd = connection_fd;
- poll_client->next = NULL;
- poll_client->pollfd = NULL;
- fill_client_info(poll_client);
-
- poll_client->client = cras_rclient_create(
- connection_fd, poll_client->id, server_socket->type);
- if (poll_client->client == NULL) {
- syslog(LOG_ERR, "failed to create client");
- goto error;
- }
-
- DL_APPEND(server_instance.clients_head, poll_client);
- server_instance.num_clients++;
- /* Send a current list of available inputs and outputs. */
- cras_iodev_list_update_device_list();
- send_client_list_to_clients(&server_instance);
- return;
-error:
- close(connection_fd);
- free(poll_client);
- return;
-}
-
-/* Add a file descriptor to be passed to select in the main loop. This is
- * registered with system state so that it is called when any client asks to
- * have a callback triggered based on an fd being readable. */
-static int add_select_fd(int fd, void (*cb)(void *data, int events),
- void *callback_data, int events, void *server_data)
-{
- struct client_callback *new_cb;
- struct client_callback *client_cb;
- struct server_data *serv;
-
- serv = (struct server_data *)server_data;
- if (serv == NULL)
- return -EINVAL;
-
- /* Check if fd already exists. */
- DL_FOREACH (serv->client_callbacks, client_cb)
- if (client_cb->select_fd == fd && !client_cb->deleted)
- return -EEXIST;
-
- new_cb = (struct client_callback *)calloc(1, sizeof(*new_cb));
- if (new_cb == NULL)
- return -ENOMEM;
-
- new_cb->select_fd = fd;
- new_cb->callback = cb;
- new_cb->callback_data = callback_data;
- new_cb->deleted = 0;
- new_cb->events = events;
- new_cb->pollfd = NULL;
-
- DL_APPEND(serv->client_callbacks, new_cb);
- server_instance.num_client_callbacks++;
- return 0;
-}
-
-/* Removes a file descriptor to be passed to select in the main loop. This is
- * registered with system state so that it is called when any client asks to
- * remove a callback added with add_select_fd. */
-static void rm_select_fd(int fd, void *server_data)
-{
- struct server_data *serv;
- struct client_callback *client_cb;
-
- serv = (struct server_data *)server_data;
- if (serv == NULL)
- return;
-
- DL_FOREACH (serv->client_callbacks, client_cb)
- if (client_cb->select_fd == fd)
- client_cb->deleted = 1;
-}
-
-/* Creates a new task entry and append to system_tasks list, which will be
- * executed in main loop later without wait time.
- */
-static int add_task(void (*cb)(void *data), void *callback_data,
- void *server_data)
-{
- struct server_data *serv;
- struct system_task *new_task;
-
- serv = (struct server_data *)server_data;
- if (serv == NULL)
- return -EINVAL;
-
- new_task = (struct system_task *)calloc(1, sizeof(*new_task));
- if (new_task == NULL)
- return -ENOMEM;
-
- new_task->callback = cb;
- new_task->callback_data = callback_data;
-
- DL_APPEND(serv->system_tasks, new_task);
- return 0;
-}
-
-/* Cleans up the file descriptor list removing items deleted during the main
- * loop iteration. */
-static void cleanup_select_fds(void *server_data)
-{
- struct server_data *serv;
- struct client_callback *client_cb;
-
- serv = (struct server_data *)server_data;
- if (serv == NULL)
- return;
-
- DL_FOREACH (serv->client_callbacks, client_cb)
- if (client_cb->deleted) {
- DL_DELETE(serv->client_callbacks, client_cb);
- server_instance.num_client_callbacks--;
- free(client_cb);
- }
-}
-
-/* Checks that at least two outputs are present (one will be the "empty"
- * default device. */
-void check_output_exists(struct cras_timer *t, void *data)
-{
- if (cras_iodev_list_get_outputs(NULL) < 2)
- cras_metrics_log_event(kNoCodecsFoundMetric);
-}
-
-#if defined(__amd64__)
-/* CPU detection - probaby best to move this elsewhere */
-static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
- unsigned int *edx, unsigned int op)
-{
- // clang-format off
- __asm__ __volatile__ (
- "cpuid"
- : "=a" (*eax),
- "=b" (*ebx),
- "=c" (*ecx),
- "=d" (*edx)
- : "a" (op), "c" (0)
- );
- // clang-format on
-}
-
-static unsigned int cpu_x86_flags(void)
-{
- unsigned int eax, ebx, ecx, edx, id;
- unsigned int cpu_flags = 0;
-
- cpuid(&id, &ebx, &ecx, &edx, 0);
-
- if (id >= 1) {
- cpuid(&eax, &ebx, &ecx, &edx, 1);
-
- if (ecx & (1 << 20))
- cpu_flags |= CPU_X86_SSE4_2;
-
- if (ecx & (1 << 28))
- cpu_flags |= CPU_X86_AVX;
-
- if (ecx & (1 << 12))
- cpu_flags |= CPU_X86_FMA;
- }
-
- if (id >= 7) {
- cpuid(&eax, &ebx, &ecx, &edx, 7);
-
- if (ebx & (1 << 5))
- cpu_flags |= CPU_X86_AVX2;
- }
-
- return cpu_flags;
-}
-#endif
-
-int cpu_get_flags(void)
-{
-#if defined(__amd64__)
- return cpu_x86_flags();
-#endif
- return 0;
-}
-
-/*
- * Exported Interface.
- */
-
-int cras_server_init()
-{
- /* Log to syslog. */
- openlog("cras_server", LOG_PID, LOG_USER);
-
- server_instance.next_client_id = RESERVED_CLIENT_IDS;
-
- /* Initialize global observer. */
- cras_observer_server_init();
-
- /* init mixer with CPU capabilities */
- cras_mix_init(cpu_get_flags());
-
- /* Allow clients to register callbacks for file descriptors.
- * add_select_fd and rm_select_fd will add and remove file descriptors
- * from the list that are passed to select in the main loop below. */
- cras_system_set_select_handler(add_select_fd, rm_select_fd,
- &server_instance);
- cras_system_set_add_task_handler(add_task, &server_instance);
- cras_main_message_init();
-
- /* Initializes all server_sockets */
- for (int conn_type = 0; conn_type < CRAS_NUM_CONN_TYPE; conn_type++) {
- server_instance.server_sockets[conn_type].fd = -1;
- }
-
- return 0;
-}
-
-/*
- * Creates a server socket with given connection type and listens on it.
- * The socket_file will be created under cras_config_get_system_socket_file_dir
- * with permission=0770. The socket_fd will be listened with parameter
- * backlog=5.
- *
- * Returns 0 on success and leaves the created fd and the address information
- * in server_socket.
- * When error occurs, the created fd will be closed and the file path will be
- * unlinked and returns negative error code.
- */
-static int create_and_listen_server_socket(enum CRAS_CONNECTION_TYPE conn_type,
- struct server_socket *server_socket)
-{
- int socket_fd = -1;
- int rc = 0;
- struct sockaddr_un *addr = &server_socket->addr;
-
- socket_fd = socket(PF_UNIX, SOCK_SEQPACKET, 0);
- if (socket_fd < 0) {
- syslog(LOG_ERR, "Main server socket failed.");
- rc = socket_fd;
- goto error;
- }
-
- memset(addr, 0, sizeof(*addr));
- addr->sun_family = AF_UNIX;
- rc = cras_fill_socket_path(conn_type, addr->sun_path);
- if (rc < 0)
- goto error;
- unlink(addr->sun_path);
-
- /* Linux quirk: calling fchmod before bind, sets the permissions of the
- * file created by bind, leaving no window for it to be modified. Start
- * with very restricted permissions. */
- rc = fchmod(socket_fd, 0700);
- if (rc < 0)
- goto error;
-
- rc = bind(socket_fd, (struct sockaddr *)addr,
- sizeof(struct sockaddr_un));
- if (rc < 0) {
- syslog(LOG_ERR, "Bind to server socket failed.");
- rc = -errno;
- goto error;
- }
-
- /* Let other members in our group play audio through this socket. */
- rc = chmod(addr->sun_path, 0770);
- if (rc < 0)
- goto error;
-
- if (listen(socket_fd, 5) != 0) {
- syslog(LOG_ERR, "Listen on server socket failed.");
- rc = -errno;
- goto error;
- }
-
- server_socket->fd = socket_fd;
- server_socket->type = conn_type;
- return 0;
-error:
- if (socket_fd >= 0) {
- close(socket_fd);
- unlink(addr->sun_path);
- }
- return rc;
-}
-
-/* Cleans up all server_socket in server_instance */
-static void cleanup_server_sockets()
-{
- for (int conn_type = 0; conn_type < CRAS_NUM_CONN_TYPE; conn_type++) {
- server_socket_cleanup(
- &server_instance.server_sockets[conn_type]);
- }
-}
-
-int cras_server_run(unsigned int profile_disable_mask)
-{
- static const unsigned int OUTPUT_CHECK_MS = 5 * 1000;
-#ifdef CRAS_DBUS
- DBusConnection *dbus_conn;
-#endif
- int rc = 0;
- struct attached_client *elm;
- struct client_callback *client_cb;
- struct system_task *tasks;
- struct system_task *system_task;
- struct cras_tm *tm;
- struct timespec ts, *poll_timeout;
- int timers_active;
- struct pollfd *pollfds;
- unsigned int pollfds_size = 32;
- unsigned int num_pollfds, poll_size_needed;
-
- pollfds = malloc(sizeof(*pollfds) * pollfds_size);
-
- cras_udev_start_sound_subsystem_monitor();
-#ifdef CRAS_DBUS
- cras_bt_device_start_monitor();
-#endif
-
- cras_server_metrics_init();
-
- cras_device_monitor_init();
-
- cras_hotword_handler_init();
-
- cras_non_empty_audio_handler_init();
-
- cras_audio_thread_monitor_init();
-
-#ifdef CRAS_DBUS
- dbus_threads_init_default();
- dbus_conn = cras_dbus_connect_system_bus();
- if (dbus_conn) {
- cras_bt_start(dbus_conn);
- if (!(profile_disable_mask & CRAS_SERVER_PROFILE_MASK_HFP))
- cras_hfp_ag_profile_create(dbus_conn);
- if (!(profile_disable_mask & CRAS_SERVER_PROFILE_MASK_HSP))
- cras_hsp_ag_profile_create(dbus_conn);
- cras_telephony_start(dbus_conn);
- if (!(profile_disable_mask & CRAS_SERVER_PROFILE_MASK_A2DP))
- cras_a2dp_endpoint_create(dbus_conn);
- cras_bt_player_create(dbus_conn);
- cras_dbus_control_start(dbus_conn);
- }
-#endif
-
- for (int conn_type = 0; conn_type < CRAS_NUM_CONN_TYPE; conn_type++) {
- rc = create_and_listen_server_socket(
- conn_type, &server_instance.server_sockets[conn_type]);
- if (rc < 0)
- goto bail;
- }
-
- tm = cras_system_state_get_tm();
- if (!tm) {
- syslog(LOG_ERR, "Getting timer manager.");
- rc = -ENOMEM;
- goto bail;
- }
-
- /* After a delay, make sure there is at least one real output device. */
- cras_tm_create_timer(tm, OUTPUT_CHECK_MS, check_output_exists, 0);
-
- /* Main server loop - client callbacks are run from this context. */
- while (1) {
- poll_size_needed = CRAS_NUM_CONN_TYPE +
- server_instance.num_clients +
- server_instance.num_client_callbacks;
- if (poll_size_needed > pollfds_size) {
- pollfds_size = 2 * poll_size_needed;
- pollfds = realloc(pollfds,
- sizeof(*pollfds) * pollfds_size);
- }
-
- for (int conn_type = 0; conn_type < CRAS_NUM_CONN_TYPE;
- conn_type++) {
- pollfds[conn_type].fd =
- server_instance.server_sockets[conn_type].fd;
- pollfds[conn_type].events = POLLIN;
- }
- num_pollfds = CRAS_NUM_CONN_TYPE;
-
- DL_FOREACH (server_instance.clients_head, elm) {
- pollfds[num_pollfds].fd = elm->fd;
- pollfds[num_pollfds].events = POLLIN;
- elm->pollfd = &pollfds[num_pollfds];
- num_pollfds++;
- }
- DL_FOREACH (server_instance.client_callbacks, client_cb) {
- if (client_cb->deleted)
- continue;
- pollfds[num_pollfds].fd = client_cb->select_fd;
- pollfds[num_pollfds].events = client_cb->events;
- client_cb->pollfd = &pollfds[num_pollfds];
- num_pollfds++;
- }
-
- tasks = server_instance.system_tasks;
- server_instance.system_tasks = NULL;
- DL_FOREACH (tasks, system_task) {
- system_task->callback(system_task->callback_data);
- DL_DELETE(tasks, system_task);
- free(system_task);
- }
-
- timers_active = cras_tm_get_next_timeout(tm, &ts);
-
- /*
- * If new client task has been scheduled, no need to wait
- * for timeout, just do another loop to execute them.
- */
- if (server_instance.system_tasks)
- poll_timeout = NULL;
- else
- poll_timeout = timers_active ? &ts : NULL;
-
- rc = ppoll(pollfds, num_pollfds, poll_timeout, NULL);
- if (rc < 0)
- continue;
-
- cras_tm_call_callbacks(tm);
-
- /* Check for new connections. */
- for (int conn_type = 0; conn_type < CRAS_NUM_CONN_TYPE;
- conn_type++) {
- if (pollfds[conn_type].revents & POLLIN)
- handle_new_connection(
- &server_instance
- .server_sockets[conn_type]);
- }
-
- /* Check if there are messages pending for any clients. */
- DL_FOREACH (server_instance.clients_head, elm)
- if (elm->pollfd && elm->pollfd->revents & POLLIN)
- handle_message_from_client(elm);
- /* Check any client-registered fd/callback pairs. */
- DL_FOREACH (server_instance.client_callbacks, client_cb)
- if (!client_cb->deleted && client_cb->pollfd &&
- (client_cb->pollfd->revents & client_cb->events))
- client_cb->callback(client_cb->callback_data,
- client_cb->pollfd->revents);
-
- cleanup_select_fds(&server_instance);
-
-#ifdef CRAS_DBUS
- if (dbus_conn)
- cras_dbus_dispatch(dbus_conn);
-#endif
-
- cras_alert_process_all_pending_alerts();
- }
-
-bail:
- cleanup_server_sockets();
- free(pollfds);
- cras_observer_server_free();
- return rc;
-}
-
-void cras_server_send_to_all_clients(const struct cras_client_message *msg)
-{
- struct attached_client *client;
-
- DL_FOREACH (server_instance.clients_head, client)
- cras_rclient_send_message(client->client, msg, NULL, 0);
-}
diff --git a/cras/src/server/cras_server.h b/cras/src/server/cras_server.h
deleted file mode 100644
index a7dfa639..00000000
--- a/cras/src/server/cras_server.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/*
- * The CRAS server instance.
- */
-#ifndef CRAS_SERVER_H_
-#define CRAS_SERVER_H_
-
-/*
- * Bitmask for cras_server_run() argument profile_disable_mask
- */
-#define CRAS_SERVER_PROFILE_MASK_HFP (1 << 0)
-#define CRAS_SERVER_PROFILE_MASK_HSP (1 << 1)
-#define CRAS_SERVER_PROFILE_MASK_A2DP (1 << 2)
-
-/* Reserver client id 0-15 for internal server usage. */
-#define RESERVED_CLIENT_IDS 16
-#define SERVER_STREAM_CLIENT_ID 0
-
-struct cras_client_message;
-
-/* Initialize some server setup. Mainly to add the select handler first
- * so that client callbacks can be registered before server start running.
- */
-int cras_server_init();
-
-/* Runs the CRAS server. Open the main socket and begin listening for
- * connections and for messages from clients that have connected.
- */
-int cras_server_run(unsigned int profile_disable_mask);
-
-/* Send a message to all attached clients. */
-void cras_server_send_to_all_clients(const struct cras_client_message *msg);
-
-#endif /* CRAS_SERVER_H_ */
diff --git a/cras/src/server/cras_server_metrics.c b/cras/src/server/cras_server_metrics.c
deleted file mode 100644
index 7e487107..00000000
--- a/cras/src/server/cras_server_metrics.c
+++ /dev/null
@@ -1,1326 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <math.h>
-#include <stdio.h>
-#include <string.h>
-#include <syslog.h>
-
-#ifdef CRAS_DBUS
-#include "cras_bt_io.h"
-#endif
-#include "cras_iodev.h"
-#include "cras_metrics.h"
-#include "cras_main_message.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "cras_system_state.h"
-
-#define METRICS_NAME_BUFFER_SIZE 100
-
-const char kBusyloop[] = "Cras.Busyloop";
-const char kBusyloopLength[] = "Cras.BusyloopLength";
-const char kDeviceTypeInput[] = "Cras.DeviceTypeInput";
-const char kDeviceTypeOutput[] = "Cras.DeviceTypeOutput";
-const char kDeviceGain[] = "Cras.DeviceGain";
-const char kDeviceVolume[] = "Cras.DeviceVolume";
-const char kFetchDelayMilliSeconds[] = "Cras.FetchDelayMilliSeconds";
-const char kHighestDeviceDelayInput[] = "Cras.HighestDeviceDelayInput";
-const char kHighestDeviceDelayOutput[] = "Cras.HighestDeviceDelayOutput";
-const char kHighestInputHardwareLevel[] = "Cras.HighestInputHardwareLevel";
-const char kHighestOutputHardwareLevel[] = "Cras.HighestOutputHardwareLevel";
-const char kMissedCallbackFirstTimeInput[] =
- "Cras.MissedCallbackFirstTimeInput";
-const char kMissedCallbackFirstTimeOutput[] =
- "Cras.MissedCallbackFirstTimeOutput";
-const char kMissedCallbackFrequencyInput[] =
- "Cras.MissedCallbackFrequencyInput";
-const char kMissedCallbackFrequencyOutput[] =
- "Cras.MissedCallbackFrequencyOutput";
-const char kMissedCallbackFrequencyAfterReschedulingInput[] =
- "Cras.MissedCallbackFrequencyAfterReschedulingInput";
-const char kMissedCallbackFrequencyAfterReschedulingOutput[] =
- "Cras.MissedCallbackFrequencyAfterReschedulingOutput";
-const char kMissedCallbackSecondTimeInput[] =
- "Cras.MissedCallbackSecondTimeInput";
-const char kMissedCallbackSecondTimeOutput[] =
- "Cras.MissedCallbackSecondTimeOutput";
-const char kNoCodecsFoundMetric[] = "Cras.NoCodecsFoundAtBoot";
-const char kStreamCallbackThreshold[] = "Cras.StreamCallbackThreshold";
-const char kStreamClientTypeInput[] = "Cras.StreamClientTypeInput";
-const char kStreamClientTypeOutput[] = "Cras.StreamClientTypeOutput";
-const char kStreamFlags[] = "Cras.StreamFlags";
-const char kStreamEffects[] = "Cras.StreamEffects";
-const char kStreamRuntime[] = "Cras.StreamRuntime";
-const char kStreamSamplingFormat[] = "Cras.StreamSamplingFormat";
-const char kStreamSamplingRate[] = "Cras.StreamSamplingRate";
-const char kUnderrunsPerDevice[] = "Cras.UnderrunsPerDevice";
-const char kHfpScoConnectionError[] = "Cras.HfpScoConnectionError";
-const char kHfpBatteryIndicatorSupported[] =
- "Cras.HfpBatteryIndicatorSupported";
-const char kHfpBatteryReport[] = "Cras.HfpBatteryReport";
-const char kHfpWidebandSpeechSupported[] = "Cras.HfpWidebandSpeechSupported";
-const char kHfpWidebandSpeechPacketLoss[] = "Cras.HfpWidebandSpeechPacketLoss";
-const char kHfpWidebandSpeechSelectedCodec[] =
- "Cras.kHfpWidebandSpeechSelectedCodec";
-
-/*
- * Records missed callback frequency only when the runtime of stream is larger
- * than the threshold.
- */
-const double MISSED_CB_FREQUENCY_SECONDS_MIN = 10.0;
-
-const time_t CRAS_METRICS_SHORT_PERIOD_THRESHOLD_SECONDS = 600;
-const time_t CRAS_METRICS_LONG_PERIOD_THRESHOLD_SECONDS = 3600;
-
-static const char *get_timespec_period_str(struct timespec ts)
-{
- if (ts.tv_sec < CRAS_METRICS_SHORT_PERIOD_THRESHOLD_SECONDS)
- return "ShortPeriod";
- if (ts.tv_sec < CRAS_METRICS_LONG_PERIOD_THRESHOLD_SECONDS)
- return "MediumPeriod";
- return "LongPeriod";
-}
-
-/* Type of metrics to log. */
-enum CRAS_SERVER_METRICS_TYPE {
- BT_BATTERY_INDICATOR_SUPPORTED,
- BT_BATTERY_REPORT,
- BT_SCO_CONNECTION_ERROR,
- BT_WIDEBAND_PACKET_LOSS,
- BT_WIDEBAND_SUPPORTED,
- BT_WIDEBAND_SELECTED_CODEC,
- BUSYLOOP,
- BUSYLOOP_LENGTH,
- DEVICE_GAIN,
- DEVICE_RUNTIME,
- DEVICE_VOLUME,
- HIGHEST_DEVICE_DELAY_INPUT,
- HIGHEST_DEVICE_DELAY_OUTPUT,
- HIGHEST_INPUT_HW_LEVEL,
- HIGHEST_OUTPUT_HW_LEVEL,
- LONGEST_FETCH_DELAY,
- MISSED_CB_FIRST_TIME_INPUT,
- MISSED_CB_FIRST_TIME_OUTPUT,
- MISSED_CB_FREQUENCY_INPUT,
- MISSED_CB_FREQUENCY_OUTPUT,
- MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_INPUT,
- MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_OUTPUT,
- MISSED_CB_SECOND_TIME_INPUT,
- MISSED_CB_SECOND_TIME_OUTPUT,
- NUM_UNDERRUNS,
- STREAM_CONFIG,
- STREAM_RUNTIME
-};
-
-enum CRAS_METRICS_DEVICE_TYPE {
- /* Output devices. */
- CRAS_METRICS_DEVICE_INTERNAL_SPEAKER,
- CRAS_METRICS_DEVICE_HEADPHONE,
- CRAS_METRICS_DEVICE_HDMI,
- CRAS_METRICS_DEVICE_HAPTIC,
- CRAS_METRICS_DEVICE_LINEOUT,
- /* Input devices. */
- CRAS_METRICS_DEVICE_INTERNAL_MIC,
- CRAS_METRICS_DEVICE_FRONT_MIC,
- CRAS_METRICS_DEVICE_REAR_MIC,
- CRAS_METRICS_DEVICE_KEYBOARD_MIC,
- CRAS_METRICS_DEVICE_MIC,
- CRAS_METRICS_DEVICE_HOTWORD,
- CRAS_METRICS_DEVICE_POST_MIX_LOOPBACK,
- CRAS_METRICS_DEVICE_POST_DSP_LOOPBACK,
- /* Devices supporting input and output function. */
- CRAS_METRICS_DEVICE_USB,
- CRAS_METRICS_DEVICE_A2DP,
- CRAS_METRICS_DEVICE_HFP,
- CRAS_METRICS_DEVICE_HSP,
- CRAS_METRICS_DEVICE_BLUETOOTH,
- CRAS_METRICS_DEVICE_BLUETOOTH_NB_MIC,
- CRAS_METRICS_DEVICE_NO_DEVICE,
- CRAS_METRICS_DEVICE_NORMAL_FALLBACK,
- CRAS_METRICS_DEVICE_ABNORMAL_FALLBACK,
- CRAS_METRICS_DEVICE_SILENT_HOTWORD,
- CRAS_METRICS_DEVICE_UNKNOWN,
- CRAS_METRICS_DEVICE_BLUETOOTH_WB_MIC,
- CRAS_METRICS_DEVICE_ALSA_LOOPBACK,
-};
-
-struct cras_server_metrics_stream_config {
- enum CRAS_STREAM_DIRECTION direction;
- unsigned cb_threshold;
- unsigned flags;
- unsigned effects;
- int format;
- unsigned rate;
- enum CRAS_CLIENT_TYPE client_type;
-};
-
-struct cras_server_metrics_device_data {
- enum CRAS_METRICS_DEVICE_TYPE type;
- enum CRAS_STREAM_DIRECTION direction;
- struct timespec runtime;
- unsigned value;
-};
-
-struct cras_server_metrics_stream_data {
- enum CRAS_CLIENT_TYPE client_type;
- enum CRAS_STREAM_TYPE stream_type;
- enum CRAS_STREAM_DIRECTION direction;
- struct timespec runtime;
-};
-
-struct cras_server_metrics_timespec_data {
- struct timespec runtime;
- unsigned count;
-};
-
-union cras_server_metrics_data {
- unsigned value;
- struct cras_server_metrics_stream_config stream_config;
- struct cras_server_metrics_device_data device_data;
- struct cras_server_metrics_stream_data stream_data;
- struct cras_server_metrics_timespec_data timespec_data;
-};
-
-/*
- * Make sure the size of message in the acceptable range. Otherwise, it may
- * be split into mutiple packets while sending.
- */
-static_assert(sizeof(union cras_server_metrics_data) <= 256,
- "The size is too large.");
-
-struct cras_server_metrics_message {
- struct cras_main_message header;
- enum CRAS_SERVER_METRICS_TYPE metrics_type;
- union cras_server_metrics_data data;
-};
-
-static void init_server_metrics_msg(struct cras_server_metrics_message *msg,
- enum CRAS_SERVER_METRICS_TYPE type,
- union cras_server_metrics_data data)
-{
- memset(msg, 0, sizeof(*msg));
- msg->header.type = CRAS_MAIN_METRICS;
- msg->header.length = sizeof(*msg);
- msg->metrics_type = type;
- msg->data = data;
-}
-
-static void handle_metrics_message(struct cras_main_message *msg, void *arg);
-
-/* The wrapper function of cras_main_message_send. */
-static int cras_server_metrics_message_send(struct cras_main_message *msg)
-{
- /* If current function is in the main thread, call handler directly. */
- if (cras_system_state_in_main_thread()) {
- handle_metrics_message(msg, NULL);
- return 0;
- }
- return cras_main_message_send(msg);
-}
-
-static inline const char *
-metrics_device_type_str(enum CRAS_METRICS_DEVICE_TYPE device_type)
-{
- switch (device_type) {
- case CRAS_METRICS_DEVICE_INTERNAL_SPEAKER:
- return "InternalSpeaker";
- case CRAS_METRICS_DEVICE_HEADPHONE:
- return "Headphone";
- case CRAS_METRICS_DEVICE_HDMI:
- return "HDMI";
- case CRAS_METRICS_DEVICE_HAPTIC:
- return "Haptic";
- case CRAS_METRICS_DEVICE_LINEOUT:
- return "Lineout";
- /* Input devices. */
- case CRAS_METRICS_DEVICE_INTERNAL_MIC:
- return "InternalMic";
- case CRAS_METRICS_DEVICE_FRONT_MIC:
- return "FrontMic";
- case CRAS_METRICS_DEVICE_REAR_MIC:
- return "RearMic";
- case CRAS_METRICS_DEVICE_KEYBOARD_MIC:
- return "KeyboardMic";
- case CRAS_METRICS_DEVICE_MIC:
- return "Mic";
- case CRAS_METRICS_DEVICE_HOTWORD:
- return "Hotword";
- case CRAS_METRICS_DEVICE_POST_MIX_LOOPBACK:
- return "PostMixLoopback";
- case CRAS_METRICS_DEVICE_POST_DSP_LOOPBACK:
- return "PostDspLoopback";
- /* Devices supporting input and output function. */
- case CRAS_METRICS_DEVICE_USB:
- return "USB";
- case CRAS_METRICS_DEVICE_A2DP:
- return "A2DP";
- case CRAS_METRICS_DEVICE_HFP:
- return "HFP";
- case CRAS_METRICS_DEVICE_HSP:
- return "HSP";
- case CRAS_METRICS_DEVICE_BLUETOOTH:
- return "Bluetooth";
- case CRAS_METRICS_DEVICE_BLUETOOTH_NB_MIC:
- return "BluetoothNarrowBandMic";
- case CRAS_METRICS_DEVICE_BLUETOOTH_WB_MIC:
- return "BluetoothWideBandMic";
- case CRAS_METRICS_DEVICE_NO_DEVICE:
- return "NoDevice";
- case CRAS_METRICS_DEVICE_ALSA_LOOPBACK:
- return "AlsaLoopback";
- /* Other fallback devices. */
- case CRAS_METRICS_DEVICE_NORMAL_FALLBACK:
- return "NormalFallback";
- case CRAS_METRICS_DEVICE_ABNORMAL_FALLBACK:
- return "AbnormalFallback";
- case CRAS_METRICS_DEVICE_SILENT_HOTWORD:
- return "SilentHotword";
- case CRAS_METRICS_DEVICE_UNKNOWN:
- return "Unknown";
- default:
- return "InvalidType";
- }
-}
-
-static inline const char *
-metrics_client_type_str(enum CRAS_CLIENT_TYPE client_type)
-{
- switch (client_type) {
- case CRAS_CLIENT_TYPE_UNKNOWN:
- return "Unknown";
- case CRAS_CLIENT_TYPE_LEGACY:
- return "Legacy";
- case CRAS_CLIENT_TYPE_TEST:
- return "Test";
- case CRAS_CLIENT_TYPE_PCM:
- return "PCM";
- case CRAS_CLIENT_TYPE_CHROME:
- return "Chrome";
- case CRAS_CLIENT_TYPE_ARC:
- return "ARC";
- case CRAS_CLIENT_TYPE_CROSVM:
- return "CrOSVM";
- case CRAS_CLIENT_TYPE_SERVER_STREAM:
- return "ServerStream";
- case CRAS_CLIENT_TYPE_LACROS:
- return "LaCrOS";
- case CRAS_CLIENT_TYPE_PLUGIN:
- return "PluginVM";
- case CRAS_CLIENT_TYPE_ARCVM:
- return "ARCVM";
- default:
- return "InvalidType";
- }
-}
-
-static inline const char *
-metrics_stream_type_str(enum CRAS_STREAM_TYPE stream_type)
-{
- switch (stream_type) {
- case CRAS_STREAM_TYPE_DEFAULT:
- return "Default";
- case CRAS_STREAM_TYPE_MULTIMEDIA:
- return "Multimedia";
- case CRAS_STREAM_TYPE_VOICE_COMMUNICATION:
- return "VoiceCommunication";
- case CRAS_STREAM_TYPE_SPEECH_RECOGNITION:
- return "SpeechRecognition";
- case CRAS_STREAM_TYPE_PRO_AUDIO:
- return "ProAudio";
- case CRAS_STREAM_TYPE_ACCESSIBILITY:
- return "Accessibility";
- default:
- return "InvalidType";
- }
-}
-
-static enum CRAS_METRICS_DEVICE_TYPE
-get_metrics_device_type(struct cras_iodev *iodev)
-{
- /* Check whether it is a special device. */
- if (iodev->info.idx < MAX_SPECIAL_DEVICE_IDX) {
- switch (iodev->info.idx) {
- case NO_DEVICE:
- syslog(LOG_ERR, "The invalid device has been used.");
- return CRAS_METRICS_DEVICE_NO_DEVICE;
- case SILENT_RECORD_DEVICE:
- case SILENT_PLAYBACK_DEVICE:
- if (iodev->active_node->type ==
- CRAS_NODE_TYPE_FALLBACK_NORMAL)
- return CRAS_METRICS_DEVICE_NORMAL_FALLBACK;
- else
- return CRAS_METRICS_DEVICE_ABNORMAL_FALLBACK;
- case SILENT_HOTWORD_DEVICE:
- return CRAS_METRICS_DEVICE_SILENT_HOTWORD;
- }
- }
-
- switch (iodev->active_node->type) {
- case CRAS_NODE_TYPE_INTERNAL_SPEAKER:
- return CRAS_METRICS_DEVICE_INTERNAL_SPEAKER;
- case CRAS_NODE_TYPE_HEADPHONE:
- return CRAS_METRICS_DEVICE_HEADPHONE;
- case CRAS_NODE_TYPE_HDMI:
- return CRAS_METRICS_DEVICE_HDMI;
- case CRAS_NODE_TYPE_HAPTIC:
- return CRAS_METRICS_DEVICE_HAPTIC;
- case CRAS_NODE_TYPE_LINEOUT:
- return CRAS_METRICS_DEVICE_LINEOUT;
- case CRAS_NODE_TYPE_MIC:
- switch (iodev->active_node->position) {
- case NODE_POSITION_INTERNAL:
- return CRAS_METRICS_DEVICE_INTERNAL_MIC;
- case NODE_POSITION_FRONT:
- return CRAS_METRICS_DEVICE_FRONT_MIC;
- case NODE_POSITION_REAR:
- return CRAS_METRICS_DEVICE_REAR_MIC;
- case NODE_POSITION_KEYBOARD:
- return CRAS_METRICS_DEVICE_KEYBOARD_MIC;
- case NODE_POSITION_EXTERNAL:
- default:
- return CRAS_METRICS_DEVICE_MIC;
- }
- case CRAS_NODE_TYPE_HOTWORD:
- return CRAS_METRICS_DEVICE_HOTWORD;
- case CRAS_NODE_TYPE_POST_MIX_PRE_DSP:
- return CRAS_METRICS_DEVICE_POST_MIX_LOOPBACK;
- case CRAS_NODE_TYPE_POST_DSP:
- return CRAS_METRICS_DEVICE_POST_DSP_LOOPBACK;
- case CRAS_NODE_TYPE_USB:
- return CRAS_METRICS_DEVICE_USB;
- case CRAS_NODE_TYPE_BLUETOOTH: {
-#ifdef CRAS_DBUS
- enum cras_bt_device_profile profile =
- cras_bt_io_profile_to_log(iodev);
- switch (profile) {
- case CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE:
- return CRAS_METRICS_DEVICE_A2DP;
- case CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY:
- /* HFP narrow band has its own node type so we know
- * this is wideband mic for sure. */
- return (iodev->direction == CRAS_STREAM_INPUT) ?
- CRAS_METRICS_DEVICE_BLUETOOTH_WB_MIC :
- CRAS_METRICS_DEVICE_HFP;
- case CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY:
- return CRAS_METRICS_DEVICE_HSP;
- default:
- break;
- }
-#endif
- return CRAS_METRICS_DEVICE_BLUETOOTH;
- }
- case CRAS_NODE_TYPE_BLUETOOTH_NB_MIC:
- return CRAS_METRICS_DEVICE_BLUETOOTH_NB_MIC;
- case CRAS_NODE_TYPE_ALSA_LOOPBACK:
- return CRAS_METRICS_DEVICE_ALSA_LOOPBACK;
- case CRAS_NODE_TYPE_UNKNOWN:
- default:
- return CRAS_METRICS_DEVICE_UNKNOWN;
- }
-}
-
-/*
- * Logs metrics for each group it belongs to. The UMA does not merge subgroups
- * automatically so we need to log them separately.
- *
- * For example, if we call this function with argument (3, 48000,
- * Cras.StreamSamplingRate, Input, Chrome), it will send 48000 to below
- * metrics:
- * Cras.StreamSamplingRate.Input.Chrome
- * Cras.StreamSamplingRate.Input
- * Cras.StreamSamplingRate
- */
-static void log_sparse_histogram_each_level(int num, int sample, ...)
-{
- char metrics_name[METRICS_NAME_BUFFER_SIZE] = {};
- va_list valist;
- int i, len = 0;
-
- va_start(valist, sample);
-
- for (i = 0; i < num && len < METRICS_NAME_BUFFER_SIZE; i++) {
- int metric_len =
- snprintf(metrics_name + len,
- METRICS_NAME_BUFFER_SIZE - len, "%s%s",
- i ? "." : "", va_arg(valist, char *));
- // Exit early on error or running out of bufferspace. Avoids
- // logging partial or corrupted strings.
- if (metric_len < 0 ||
- metric_len > METRICS_NAME_BUFFER_SIZE - len)
- break;
- len += metric_len;
- cras_metrics_log_sparse_histogram(metrics_name, sample);
- }
-
- va_end(valist);
-}
-
-static void log_histogram_each_level(int num, int sample, int min, int max,
- int nbuckets, ...)
-{
- char metrics_name[METRICS_NAME_BUFFER_SIZE] = {};
- va_list valist;
- int i, len = 0;
-
- va_start(valist, nbuckets);
-
- for (i = 0; i < num && len < METRICS_NAME_BUFFER_SIZE; i++) {
- int metric_len =
- snprintf(metrics_name + len,
- METRICS_NAME_BUFFER_SIZE - len, "%s%s",
- i ? "." : "", va_arg(valist, char *));
- // Exit early on error or running out of bufferspace. Avoids
- // logging partial or corrupted strings.
- if (metric_len < 0 ||
- metric_len > METRICS_NAME_BUFFER_SIZE - len)
- break;
- len += metric_len;
- cras_metrics_log_histogram(metrics_name, sample, min, max,
- nbuckets);
- }
-
- va_end(valist);
-}
-
-int cras_server_metrics_hfp_sco_connection_error(
- enum CRAS_METRICS_BT_SCO_ERROR_TYPE type)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = type;
- init_server_metrics_msg(&msg, BT_SCO_CONNECTION_ERROR, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: "
- "BT_SCO_CONNECTION_ERROR");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_hfp_battery_indicator(int battery_indicator_support)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = battery_indicator_support;
- init_server_metrics_msg(&msg, BT_BATTERY_INDICATOR_SUPPORTED, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: "
- "BT_BATTERY_INDICATOR_SUPPORTED");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_hfp_battery_report(int battery_report)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = battery_report;
- init_server_metrics_msg(&msg, BT_BATTERY_REPORT, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: "
- "BT_BATTERY_REPORT");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_hfp_packet_loss(float packet_loss_ratio)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- /* Percentage is too coarse for packet loss, so we use number of bad
- * packets per thousand packets instead. */
- data.value = (unsigned)(round(packet_loss_ratio * 1000));
- init_server_metrics_msg(&msg, BT_WIDEBAND_PACKET_LOSS, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: BT_WIDEBAND_PACKET_LOSS");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_hfp_wideband_support(bool supported)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = supported;
- init_server_metrics_msg(&msg, BT_WIDEBAND_SUPPORTED, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: BT_WIDEBAND_SUPPORTED");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_hfp_wideband_selected_codec(int codec)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = codec;
- init_server_metrics_msg(&msg, BT_WIDEBAND_SELECTED_CODEC, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: "
- "BT_WIDEBAND_SELECTED_CODEC");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_device_runtime(struct cras_iodev *iodev)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- struct timespec now;
- int err;
-
- data.device_data.type = get_metrics_device_type(iodev);
- data.device_data.direction = iodev->direction;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &iodev->open_ts, &data.device_data.runtime);
-
- init_server_metrics_msg(&msg, DEVICE_RUNTIME, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: DEVICE_RUNTIME");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_device_gain(struct cras_iodev *iodev)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- if (iodev->direction == CRAS_STREAM_OUTPUT)
- return 0;
-
- data.device_data.type = get_metrics_device_type(iodev);
- data.device_data.value =
- (unsigned)100 * iodev->active_node->ui_gain_scaler;
-
- init_server_metrics_msg(&msg, DEVICE_GAIN, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: DEVICE_GAIN");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_device_volume(struct cras_iodev *iodev)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- if (iodev->direction == CRAS_STREAM_INPUT)
- return 0;
-
- data.device_data.type = get_metrics_device_type(iodev);
- data.device_data.value = iodev->active_node->volume;
-
- init_server_metrics_msg(&msg, DEVICE_VOLUME, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: DEVICE_VOLUME");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_highest_device_delay(
- unsigned int hw_level, unsigned int largest_cb_level,
- enum CRAS_STREAM_DIRECTION direction)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- if (largest_cb_level == 0) {
- syslog(LOG_ERR,
- "Failed to record device delay: devided by zero");
- return -1;
- }
-
- /*
- * Because the latency depends on the callback threshold of streams, it
- * should be calculated as dividing the highest hardware level by largest
- * callback threshold of streams. For output device, this value should fall
- * around 2 because CRAS 's scheduling maintain device buffer level around
- * 1~2 minimum callback level. For input device, this value should be around
- * 1 because the device buffer level is around 0~1 minimum callback level.
- * Besides, UMA cannot record float so this ratio is multiplied by 1000.
- */
- data.value = hw_level * 1000 / largest_cb_level;
-
- switch (direction) {
- case CRAS_STREAM_INPUT:
- init_server_metrics_msg(&msg, HIGHEST_DEVICE_DELAY_INPUT, data);
- break;
- case CRAS_STREAM_OUTPUT:
- init_server_metrics_msg(&msg, HIGHEST_DEVICE_DELAY_OUTPUT,
- data);
- break;
- default:
- return 0;
- }
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: HIGHEST_DEVICE_DELAY");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_highest_hw_level(unsigned hw_level,
- enum CRAS_STREAM_DIRECTION direction)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = hw_level;
-
- switch (direction) {
- case CRAS_STREAM_INPUT:
- init_server_metrics_msg(&msg, HIGHEST_INPUT_HW_LEVEL, data);
- break;
- case CRAS_STREAM_OUTPUT:
- init_server_metrics_msg(&msg, HIGHEST_OUTPUT_HW_LEVEL, data);
- break;
- default:
- return 0;
- }
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: HIGHEST_HW_LEVEL");
- return err;
- }
-
- return 0;
-}
-
-/* Logs longest fetch delay of a stream. */
-int cras_server_metrics_longest_fetch_delay(const struct cras_rstream *stream)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.stream_data.client_type = stream->client_type;
- data.stream_data.stream_type = stream->stream_type;
- data.stream_data.direction = stream->direction;
-
- /*
- * There is no delay when the sleep_interval_ts larger than the
- * longest_fetch_interval.
- */
- if (!timespec_after(&stream->longest_fetch_interval,
- &stream->sleep_interval_ts)) {
- data.stream_data.runtime.tv_sec = 0;
- data.stream_data.runtime.tv_nsec = 0;
- } else {
- subtract_timespecs(&stream->longest_fetch_interval,
- &stream->sleep_interval_ts,
- &data.stream_data.runtime);
- }
-
- init_server_metrics_msg(&msg, LONGEST_FETCH_DELAY, data);
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: LONGEST_FETCH_DELAY");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_num_underruns(unsigned num_underruns)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = num_underruns;
- init_server_metrics_msg(&msg, NUM_UNDERRUNS, data);
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: NUM_UNDERRUNS");
- return err;
- }
-
- return 0;
-}
-
-/* Logs the frequency of missed callback. */
-static int
-cras_server_metrics_missed_cb_frequency(const struct cras_rstream *stream)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- struct timespec now, time_since;
- double seconds, frequency;
- int err;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &stream->start_ts, &time_since);
- seconds = (double)time_since.tv_sec + time_since.tv_nsec / 1000000000.0;
-
- /* Ignore streams which do not have enough runtime. */
- if (seconds < MISSED_CB_FREQUENCY_SECONDS_MIN)
- return 0;
-
- /* Compute how many callbacks are missed in a day. */
- frequency = (double)stream->num_missed_cb * 86400.0 / seconds;
- data.value = (unsigned)(round(frequency) + 1e-9);
-
- if (stream->direction == CRAS_STREAM_INPUT)
- init_server_metrics_msg(&msg, MISSED_CB_FREQUENCY_INPUT, data);
- else
- init_server_metrics_msg(&msg, MISSED_CB_FREQUENCY_OUTPUT, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: MISSED_CB_FREQUENCY");
- return err;
- }
-
- /*
- * If missed callback happened at least once, also record frequncy after
- * rescheduling.
- */
- if (!stream->num_missed_cb)
- return 0;
-
- subtract_timespecs(&now, &stream->first_missed_cb_ts, &time_since);
- seconds = (double)time_since.tv_sec + time_since.tv_nsec / 1000000000.0;
-
- /* Compute how many callbacks are missed in a day. */
- frequency = (double)(stream->num_missed_cb - 1) * 86400.0 / seconds;
- data.value = (unsigned)(round(frequency) + 1e-9);
-
- if (stream->direction == CRAS_STREAM_INPUT) {
- init_server_metrics_msg(
- &msg, MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_INPUT,
- data);
- } else {
- init_server_metrics_msg(
- &msg, MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_OUTPUT,
- data);
- }
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: MISSED_CB_FREQUENCY");
- return err;
- }
-
- return 0;
-}
-
-/*
- * Logs the duration between stream starting time and the first missed
- * callback.
- */
-static int
-cras_server_metrics_missed_cb_first_time(const struct cras_rstream *stream)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- struct timespec time_since;
- int err;
-
- subtract_timespecs(&stream->first_missed_cb_ts, &stream->start_ts,
- &time_since);
- data.value = (unsigned)time_since.tv_sec;
-
- if (stream->direction == CRAS_STREAM_INPUT) {
- init_server_metrics_msg(&msg, MISSED_CB_FIRST_TIME_INPUT, data);
- } else {
- init_server_metrics_msg(&msg, MISSED_CB_FIRST_TIME_OUTPUT,
- data);
- }
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: "
- "MISSED_CB_FIRST_TIME");
- return err;
- }
-
- return 0;
-}
-
-/* Logs the duration between the first and the second missed callback events. */
-static int
-cras_server_metrics_missed_cb_second_time(const struct cras_rstream *stream)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- struct timespec now, time_since;
- int err;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &stream->first_missed_cb_ts, &time_since);
- data.value = (unsigned)time_since.tv_sec;
-
- if (stream->direction == CRAS_STREAM_INPUT) {
- init_server_metrics_msg(&msg, MISSED_CB_SECOND_TIME_INPUT,
- data);
- } else {
- init_server_metrics_msg(&msg, MISSED_CB_SECOND_TIME_OUTPUT,
- data);
- }
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: "
- "MISSED_CB_SECOND_TIME");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_missed_cb_event(struct cras_rstream *stream)
-{
- int rc = 0;
-
- stream->num_missed_cb += 1;
- if (stream->num_missed_cb == 1)
- clock_gettime(CLOCK_MONOTONIC_RAW, &stream->first_missed_cb_ts);
-
- /* Do not record missed cb if the stream has these flags. */
- if (stream->flags & (BULK_AUDIO_OK | USE_DEV_TIMING | TRIGGER_ONLY))
- return 0;
-
- /* Only record the first and the second events. */
- if (stream->num_missed_cb == 1)
- rc = cras_server_metrics_missed_cb_first_time(stream);
- else if (stream->num_missed_cb == 2)
- rc = cras_server_metrics_missed_cb_second_time(stream);
-
- return rc;
-}
-
-/* Logs the stream configurations from clients. */
-static int
-cras_server_metrics_stream_config(const struct cras_rstream_config *config)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.stream_config.direction = config->direction;
- data.stream_config.cb_threshold = (unsigned)config->cb_threshold;
- data.stream_config.flags = (unsigned)config->flags;
- data.stream_config.effects = (unsigned)config->effects;
- data.stream_config.format = (int)config->format->format;
- data.stream_config.rate = (unsigned)config->format->frame_rate;
- data.stream_config.client_type = config->client_type;
-
- init_server_metrics_msg(&msg, STREAM_CONFIG, data);
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: STREAM_CONFIG");
- return err;
- }
-
- return 0;
-}
-
-/* Logs runtime of a stream. */
-int cras_server_metrics_stream_runtime(const struct cras_rstream *stream)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- struct timespec now;
- int err;
-
- data.stream_data.client_type = stream->client_type;
- data.stream_data.stream_type = stream->stream_type;
- data.stream_data.direction = stream->direction;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- subtract_timespecs(&now, &stream->start_ts, &data.stream_data.runtime);
-
- init_server_metrics_msg(&msg, STREAM_RUNTIME, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: STREAM_RUNTIME");
- return err;
- }
-
- return 0;
-}
-
-int cras_server_metrics_stream_create(const struct cras_rstream_config *config)
-{
- return cras_server_metrics_stream_config(config);
-}
-
-int cras_server_metrics_stream_destroy(const struct cras_rstream *stream)
-{
- int rc;
- rc = cras_server_metrics_missed_cb_frequency(stream);
- if (rc < 0)
- return rc;
- rc = cras_server_metrics_stream_runtime(stream);
- if (rc < 0)
- return rc;
- return cras_server_metrics_longest_fetch_delay(stream);
-}
-
-int cras_server_metrics_busyloop(struct timespec *ts, unsigned count)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.timespec_data.runtime = *ts;
- data.timespec_data.count = count;
-
- init_server_metrics_msg(&msg, BUSYLOOP, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR, "Failed to send metrics message: BUSYLOOP");
- return err;
- }
- return 0;
-}
-
-int cras_server_metrics_busyloop_length(unsigned length)
-{
- struct cras_server_metrics_message msg;
- union cras_server_metrics_data data;
- int err;
-
- data.value = length;
-
- init_server_metrics_msg(&msg, BUSYLOOP_LENGTH, data);
-
- err = cras_server_metrics_message_send(
- (struct cras_main_message *)&msg);
- if (err < 0) {
- syslog(LOG_ERR,
- "Failed to send metrics message: BUSYLOOP_LENGTH");
- return err;
- }
- return 0;
-}
-
-static void metrics_device_runtime(struct cras_server_metrics_device_data data)
-{
- char metrics_name[METRICS_NAME_BUFFER_SIZE];
-
- snprintf(metrics_name, METRICS_NAME_BUFFER_SIZE,
- "Cras.%sDevice%sRuntime",
- data.direction == CRAS_STREAM_INPUT ? "Input" : "Output",
- metrics_device_type_str(data.type));
- cras_metrics_log_histogram(metrics_name, (unsigned)data.runtime.tv_sec,
- 0, 10000, 20);
-
- /* Logs the usage of each device. */
- if (data.direction == CRAS_STREAM_INPUT)
- cras_metrics_log_sparse_histogram(kDeviceTypeInput, data.type);
- else
- cras_metrics_log_sparse_histogram(kDeviceTypeOutput, data.type);
-}
-
-static void metrics_device_gain(struct cras_server_metrics_device_data data)
-{
- char metrics_name[METRICS_NAME_BUFFER_SIZE];
-
- snprintf(metrics_name, METRICS_NAME_BUFFER_SIZE, "%s.%s", kDeviceGain,
- metrics_device_type_str(data.type));
- cras_metrics_log_histogram(metrics_name, data.value, 0, 2000, 20);
-}
-
-static void metrics_device_volume(struct cras_server_metrics_device_data data)
-{
- char metrics_name[METRICS_NAME_BUFFER_SIZE];
-
- snprintf(metrics_name, METRICS_NAME_BUFFER_SIZE, "%s.%s", kDeviceVolume,
- metrics_device_type_str(data.type));
- cras_metrics_log_histogram(metrics_name, data.value, 0, 100, 20);
-}
-
-static void
-metrics_longest_fetch_delay(struct cras_server_metrics_stream_data data)
-{
- int fetch_delay_msec =
- data.runtime.tv_sec * 1000 + data.runtime.tv_nsec / 1000000;
- log_histogram_each_level(3, fetch_delay_msec, 0, 10000, 20,
- kFetchDelayMilliSeconds,
- metrics_client_type_str(data.client_type),
- metrics_stream_type_str(data.stream_type));
-}
-
-static void metrics_stream_runtime(struct cras_server_metrics_stream_data data)
-{
- log_histogram_each_level(
- 4, (int)data.runtime.tv_sec, 0, 10000, 20, kStreamRuntime,
- data.direction == CRAS_STREAM_INPUT ? "Input" : "Output",
- metrics_client_type_str(data.client_type),
- metrics_stream_type_str(data.stream_type));
-}
-
-static void metrics_busyloop(struct cras_server_metrics_timespec_data data)
-{
- char metrics_name[METRICS_NAME_BUFFER_SIZE];
-
- snprintf(metrics_name, METRICS_NAME_BUFFER_SIZE, "%s.%s", kBusyloop,
- get_timespec_period_str(data.runtime));
-
- cras_metrics_log_histogram(metrics_name, data.count, 0, 1000, 20);
-}
-
-static void
-metrics_stream_config(struct cras_server_metrics_stream_config config)
-{
- const char *direction;
-
- if (config.direction == CRAS_STREAM_INPUT)
- direction = "Input";
- else
- direction = "Output";
-
- /* Logs stream callback threshold. */
- log_sparse_histogram_each_level(
- 3, config.cb_threshold, kStreamCallbackThreshold, direction,
- metrics_client_type_str(config.client_type));
-
- /* Logs stream flags. */
- log_sparse_histogram_each_level(
- 3, config.flags, kStreamFlags, direction,
- metrics_client_type_str(config.client_type));
-
- /* Logs stream effects. */
- log_sparse_histogram_each_level(
- 3, config.effects, kStreamEffects, direction,
- metrics_client_type_str(config.client_type));
-
- /* Logs stream sampling format. */
- log_sparse_histogram_each_level(
- 3, config.format, kStreamSamplingFormat, direction,
- metrics_client_type_str(config.client_type));
-
- /* Logs stream sampling rate. */
- log_sparse_histogram_each_level(
- 3, config.rate, kStreamSamplingRate, direction,
- metrics_client_type_str(config.client_type));
-
- /* Logs stream client type. */
- if (config.direction == CRAS_STREAM_INPUT)
- cras_metrics_log_sparse_histogram(kStreamClientTypeInput,
- config.client_type);
- else
- cras_metrics_log_sparse_histogram(kStreamClientTypeOutput,
- config.client_type);
-}
-
-static void handle_metrics_message(struct cras_main_message *msg, void *arg)
-{
- struct cras_server_metrics_message *metrics_msg =
- (struct cras_server_metrics_message *)msg;
- switch (metrics_msg->metrics_type) {
- case BT_SCO_CONNECTION_ERROR:
- cras_metrics_log_sparse_histogram(kHfpScoConnectionError,
- metrics_msg->data.value);
- break;
- case BT_BATTERY_INDICATOR_SUPPORTED:
- cras_metrics_log_sparse_histogram(kHfpBatteryIndicatorSupported,
- metrics_msg->data.value);
- break;
- case BT_BATTERY_REPORT:
- cras_metrics_log_sparse_histogram(kHfpBatteryReport,
- metrics_msg->data.value);
- break;
- case BT_WIDEBAND_PACKET_LOSS:
- cras_metrics_log_histogram(kHfpWidebandSpeechPacketLoss,
- metrics_msg->data.value, 0, 1000,
- 20);
- break;
- case BT_WIDEBAND_SUPPORTED:
- cras_metrics_log_sparse_histogram(kHfpWidebandSpeechSupported,
- metrics_msg->data.value);
- break;
- case BT_WIDEBAND_SELECTED_CODEC:
- cras_metrics_log_sparse_histogram(
- kHfpWidebandSpeechSelectedCodec,
- metrics_msg->data.value);
- break;
- case DEVICE_GAIN:
- metrics_device_gain(metrics_msg->data.device_data);
- break;
- case DEVICE_RUNTIME:
- metrics_device_runtime(metrics_msg->data.device_data);
- break;
- case DEVICE_VOLUME:
- metrics_device_volume(metrics_msg->data.device_data);
- break;
- case HIGHEST_DEVICE_DELAY_INPUT:
- cras_metrics_log_histogram(kHighestDeviceDelayInput,
- metrics_msg->data.value, 1, 10000,
- 20);
- break;
- case HIGHEST_DEVICE_DELAY_OUTPUT:
- cras_metrics_log_histogram(kHighestDeviceDelayOutput,
- metrics_msg->data.value, 1, 10000,
- 20);
- break;
- case HIGHEST_INPUT_HW_LEVEL:
- cras_metrics_log_histogram(kHighestInputHardwareLevel,
- metrics_msg->data.value, 1, 10000,
- 20);
- break;
- case HIGHEST_OUTPUT_HW_LEVEL:
- cras_metrics_log_histogram(kHighestOutputHardwareLevel,
- metrics_msg->data.value, 1, 10000,
- 20);
- break;
- case LONGEST_FETCH_DELAY:
- metrics_longest_fetch_delay(metrics_msg->data.stream_data);
- break;
- case MISSED_CB_FIRST_TIME_INPUT:
- cras_metrics_log_histogram(kMissedCallbackFirstTimeInput,
- metrics_msg->data.value, 0, 90000,
- 20);
- break;
- case MISSED_CB_FIRST_TIME_OUTPUT:
- cras_metrics_log_histogram(kMissedCallbackFirstTimeOutput,
- metrics_msg->data.value, 0, 90000,
- 20);
- break;
- case MISSED_CB_FREQUENCY_INPUT:
- cras_metrics_log_histogram(kMissedCallbackFrequencyInput,
- metrics_msg->data.value, 0, 90000,
- 20);
- break;
- case MISSED_CB_FREQUENCY_OUTPUT:
- cras_metrics_log_histogram(kMissedCallbackFrequencyOutput,
- metrics_msg->data.value, 0, 90000,
- 20);
- break;
- case MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_INPUT:
- cras_metrics_log_histogram(
- kMissedCallbackFrequencyAfterReschedulingInput,
- metrics_msg->data.value, 0, 90000, 20);
- break;
- case MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_OUTPUT:
- cras_metrics_log_histogram(
- kMissedCallbackFrequencyAfterReschedulingOutput,
- metrics_msg->data.value, 0, 90000, 20);
- break;
- case MISSED_CB_SECOND_TIME_INPUT:
- cras_metrics_log_histogram(kMissedCallbackSecondTimeInput,
- metrics_msg->data.value, 0, 90000,
- 20);
- break;
- case MISSED_CB_SECOND_TIME_OUTPUT:
- cras_metrics_log_histogram(kMissedCallbackSecondTimeOutput,
- metrics_msg->data.value, 0, 90000,
- 20);
- break;
- case NUM_UNDERRUNS:
- cras_metrics_log_histogram(kUnderrunsPerDevice,
- metrics_msg->data.value, 0, 1000,
- 10);
- break;
- case STREAM_CONFIG:
- metrics_stream_config(metrics_msg->data.stream_config);
- break;
- case STREAM_RUNTIME:
- metrics_stream_runtime(metrics_msg->data.stream_data);
- break;
- case BUSYLOOP:
- metrics_busyloop(metrics_msg->data.timespec_data);
- break;
- case BUSYLOOP_LENGTH:
- cras_metrics_log_histogram(
- kBusyloopLength, metrics_msg->data.value, 0, 1000, 50);
- break;
- default:
- syslog(LOG_ERR, "Unknown metrics type %u",
- metrics_msg->metrics_type);
- break;
- }
-}
-
-int cras_server_metrics_init()
-{
- cras_main_message_add_handler(CRAS_MAIN_METRICS, handle_metrics_message,
- NULL);
- return 0;
-}
diff --git a/cras/src/server/cras_server_metrics.h b/cras/src/server/cras_server_metrics.h
deleted file mode 100644
index e8458087..00000000
--- a/cras/src/server/cras_server_metrics.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_SERVER_METRICS_H_
-#define CRAS_SERVER_METRICS_H_
-
-#include <stdbool.h>
-
-#include "cras_iodev.h"
-#include "cras_rstream.h"
-
-extern const char kNoCodecsFoundMetric[];
-
-enum CRAS_METRICS_BT_SCO_ERROR_TYPE {
- CRAS_METRICS_SCO_SKT_SUCCESS = 0,
- CRAS_METRICS_SCO_SKT_CONNECT_ERROR = 1,
- CRAS_METRICS_SCO_SKT_OPEN_ERROR = 2,
- CRAS_METRICS_SCO_SKT_POLL_TIMEOUT = 3,
- CRAS_METRICS_SCO_SKT_POLL_ERR_HUP = 4,
-};
-
-/* Logs the error type happens when setting up SCO connection. This is mainly
- * used to track whether the setup of SCO connection succeeds and the frequency
- * of different errors. This will also be used to track if our fixes for these
- * errors address the issues we find.
- */
-int cras_server_metrics_hfp_sco_connection_error(
- enum CRAS_METRICS_BT_SCO_ERROR_TYPE type);
-
-/* Logs an enum representing which spec does HFP headset supports battery
- * indicator. Apple, HFP, none or both. */
-int cras_server_metrics_hfp_battery_indicator(int battery_indicator_support);
-
-/* Logs an enum representing the spec through which the battery level change
- * event reported. Apple or HFP.*/
-int cras_server_metrics_hfp_battery_report(int battery_report);
-
-/* Logs if connected HFP headset supports wideband speech. */
-int cras_server_metrics_hfp_wideband_support(bool supported);
-
-/* Logs the selected codec in HFP wideband connection. */
-int cras_server_metrics_hfp_wideband_selected_codec(int codec);
-
-/* Logs the number of packet loss per 1000 packets under HFP capture. */
-int cras_server_metrics_hfp_packet_loss(float packet_loss_ratio);
-
-/* Logs runtime of a device. */
-int cras_server_metrics_device_runtime(struct cras_iodev *iodev);
-
-/* Logs the gain of a device. */
-int cras_server_metrics_device_gain(struct cras_iodev *iodev);
-
-/* Logs the volume of a device. */
-int cras_server_metrics_device_volume(struct cras_iodev *iodev);
-
-/* Logs the highest delay time of a device. */
-int cras_server_metrics_highest_device_delay(
- unsigned int hw_level, unsigned int largest_cb_level,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Logs the highest hardware level of a device. */
-int cras_server_metrics_highest_hw_level(unsigned hw_level,
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Logs the number of underruns of a device. */
-int cras_server_metrics_num_underruns(unsigned num_underruns);
-
-/* Logs the missed callback event. */
-int cras_server_metrics_missed_cb_event(struct cras_rstream *stream);
-
-/* Logs information when a stream creates. */
-int cras_server_metrics_stream_create(const struct cras_rstream_config *config);
-
-/* Logs information when a stream destroys. */
-int cras_server_metrics_stream_destroy(const struct cras_rstream *stream);
-
-/* Logs the number of busyloops for different time periods. */
-int cras_server_metrics_busyloop(struct timespec *ts, unsigned count);
-
-/* Logs the length of busyloops. */
-int cras_server_metrics_busyloop_length(unsigned length);
-
-/* Initialize metrics logging stuff. */
-int cras_server_metrics_init();
-
-#endif /* CRAS_SERVER_METRICS_H_ */
diff --git a/cras/src/server/cras_system_state.c b/cras/src/server/cras_system_state.c
deleted file mode 100644
index 366afb5f..00000000
--- a/cras/src/server/cras_system_state.c
+++ /dev/null
@@ -1,714 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <string.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <syslog.h>
-
-#include "cras_alsa_card.h"
-#include "cras_alert.h"
-#include "cras_board_config.h"
-#include "cras_config.h"
-#include "cras_device_blocklist.h"
-#include "cras_iodev_list.h"
-#include "cras_observer.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-#include "cras_tm.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-struct card_list {
- struct cras_alsa_card *card;
- struct card_list *prev, *next;
-};
-
-struct name_list {
- char name[NAME_MAX];
- struct name_list *prev, *next;
-};
-
-/* The system state.
- * Members:
- * exp_state - The exported system state shared with clients.
- * shm_name - Name of posix shm region for exported state.
- * shm_fd - fd for shm area of system_state struct.
- * shm_fd_ro - fd for shm area of system_state struct, opened read-only.
- * This copy is to dup and pass to clients.
- * shm_size - Size of the shm area.
- * device_config_dir - Directory of device configs where volume curves live.
- * internal_ucm_suffix - The suffix to append to internal card name to
- * control which ucm config file to load.
- * device_blocklist - Blocklist of device the server will ignore.
- * cards - A list of active sound cards in the system.
- * update_lock - Protects the update_count, as audio threads can update the
- * stream count.
- * tm - The system-wide timer manager.
- * add_task - Function to handle adding a task for main thread to execute.
- * task_data - Data to be passed to add_task handler function.
- * main_thread_tid - The thread id of the main thread.
- * bt_fix_a2dp_packet_size - The flag to override A2DP packet size set by
- * Blueetoh peer devices to a smaller default value.
- */
-static struct {
- struct cras_server_state *exp_state;
- char shm_name[NAME_MAX];
- int shm_fd;
- int shm_fd_ro;
- size_t shm_size;
- const char *device_config_dir;
- const char *internal_ucm_suffix;
- struct name_list *ignore_suffix_cards;
- struct cras_device_blocklist *device_blocklist;
- struct card_list *cards;
- pthread_mutex_t update_lock;
- struct cras_tm *tm;
- /* Select loop callback registration. */
- int (*fd_add)(int fd, void (*cb)(void *data, int events), void *cb_data,
- int events, void *select_data);
- void (*fd_rm)(int fd, void *select_data);
- void *select_data;
- int (*add_task)(void (*callback)(void *data), void *callback_data,
- void *task_data);
- void *task_data;
- struct cras_audio_thread_snapshot_buffer snapshot_buffer;
- pthread_t main_thread_tid;
- bool bt_fix_a2dp_packet_size;
-} state;
-
-/* The string format is CARD1,CARD2,CARD3. Divide it into a list. */
-void init_ignore_suffix_cards(char *str)
-{
- struct name_list *card;
- char *ptr;
-
- state.ignore_suffix_cards = NULL;
-
- if (str == NULL)
- return;
-
- ptr = strtok(str, ",");
- while (ptr != NULL) {
- card = (struct name_list *)calloc(1, sizeof(*card));
- if (!card) {
- syslog(LOG_ERR, "Failed to call calloc: %d", errno);
- return;
- }
- strncpy(card->name, ptr, NAME_MAX - 1);
- DL_APPEND(state.ignore_suffix_cards, card);
- ptr = strtok(NULL, ",");
- }
-}
-
-void deinit_ignore_suffix_cards()
-{
- struct name_list *card;
- DL_FOREACH (state.ignore_suffix_cards, card) {
- DL_DELETE(state.ignore_suffix_cards, card);
- free(card);
- }
-}
-
-/*
- * Exported Interface.
- */
-
-void cras_system_state_init(const char *device_config_dir, const char *shm_name,
- int rw_shm_fd, int ro_shm_fd,
- struct cras_server_state *exp_state,
- size_t exp_state_size)
-{
- struct cras_board_config board_config;
- int rc;
-
- assert(sizeof(*exp_state) == exp_state_size);
- state.shm_size = sizeof(*exp_state);
-
- strncpy(state.shm_name, shm_name, sizeof(state.shm_name));
- state.shm_name[sizeof(state.shm_name) - 1] = '\0';
- state.shm_fd = rw_shm_fd;
- state.shm_fd_ro = ro_shm_fd;
-
- /* Read board config. */
- memset(&board_config, 0, sizeof(board_config));
- cras_board_config_get(device_config_dir, &board_config);
-
- /* Initial system state. */
- exp_state->state_version = CRAS_SERVER_STATE_VERSION;
- exp_state->volume = CRAS_MAX_SYSTEM_VOLUME;
- exp_state->mute = 0;
- exp_state->mute_locked = 0;
- exp_state->suspended = 0;
- exp_state->capture_mute = 0;
- exp_state->capture_mute_locked = 0;
- exp_state->min_volume_dBFS = DEFAULT_MIN_VOLUME_DBFS;
- exp_state->max_volume_dBFS = DEFAULT_MAX_VOLUME_DBFS;
- exp_state->num_streams_attached = 0;
- exp_state->default_output_buffer_size =
- board_config.default_output_buffer_size;
- exp_state->aec_supported = board_config.aec_supported;
- exp_state->aec_group_id = board_config.aec_group_id;
- exp_state->bt_wbs_enabled = board_config.bt_wbs_enabled;
- exp_state->deprioritize_bt_wbs_mic =
- board_config.deprioritize_bt_wbs_mic;
- exp_state->noise_cancellation_enabled = 0;
- exp_state->hotword_pause_at_suspend =
- board_config.hotword_pause_at_suspend;
-
- if ((rc = pthread_mutex_init(&state.update_lock, 0) != 0)) {
- syslog(LOG_ERR, "Fatal: system state mutex init");
- exit(rc);
- }
-
- state.exp_state = exp_state;
-
- /* Directory for volume curve configs.
- * Note that device_config_dir does not affect device blocklist.
- * Device blocklist is common to all boards so we do not need
- * to change device blocklist at run time. */
- state.device_config_dir = device_config_dir;
- state.internal_ucm_suffix = NULL;
- init_ignore_suffix_cards(board_config.ucm_ignore_suffix);
- free(board_config.ucm_ignore_suffix);
-
- state.tm = cras_tm_init();
- if (!state.tm) {
- syslog(LOG_ERR, "Fatal: system state timer init");
- exit(-ENOMEM);
- }
-
- /* Read config file for blocklisted devices. */
- state.device_blocklist =
- cras_device_blocklist_create(CRAS_CONFIG_FILE_DIR);
-
- /* Initialize snapshot buffer memory */
- memset(&state.snapshot_buffer, 0,
- sizeof(struct cras_audio_thread_snapshot_buffer));
-
- /* Save thread id of the main thread. */
- state.main_thread_tid = pthread_self();
-
- state.bt_fix_a2dp_packet_size = false;
-}
-
-void cras_system_state_set_internal_ucm_suffix(const char *internal_ucm_suffix)
-{
- state.internal_ucm_suffix = internal_ucm_suffix;
-}
-
-void cras_system_state_deinit()
-{
- /* Free any resources used. This prevents unit tests from leaking. */
-
- cras_device_blocklist_destroy(state.device_blocklist);
-
- cras_tm_deinit(state.tm);
-
- if (state.exp_state) {
- munmap(state.exp_state, state.shm_size);
- cras_shm_close_unlink(state.shm_name, state.shm_fd);
- if (state.shm_fd_ro != state.shm_fd)
- close(state.shm_fd_ro);
- }
-
- deinit_ignore_suffix_cards();
- pthread_mutex_destroy(&state.update_lock);
-}
-
-void cras_system_set_volume(size_t volume)
-{
- if (volume > CRAS_MAX_SYSTEM_VOLUME)
- syslog(LOG_DEBUG, "system volume set out of range %zu", volume);
-
- state.exp_state->volume = MIN(volume, CRAS_MAX_SYSTEM_VOLUME);
- cras_observer_notify_output_volume(state.exp_state->volume);
-}
-
-size_t cras_system_get_volume()
-{
- return state.exp_state->volume;
-}
-
-void cras_system_notify_mute(void)
-{
- cras_observer_notify_output_mute(state.exp_state->mute,
- state.exp_state->user_mute,
- state.exp_state->mute_locked);
-}
-
-void cras_system_set_user_mute(int mute)
-{
- int current_mute = cras_system_get_mute();
-
- if (state.exp_state->user_mute == !!mute)
- return;
-
- state.exp_state->user_mute = !!mute;
-
- if (current_mute == (mute || state.exp_state->mute))
- return;
-
- cras_system_notify_mute();
-}
-
-void cras_system_set_mute(int mute)
-{
- int current_mute = cras_system_get_mute();
-
- if (state.exp_state->mute_locked)
- return;
-
- if (state.exp_state->mute == !!mute)
- return;
-
- state.exp_state->mute = !!mute;
-
- if (current_mute == (mute || state.exp_state->user_mute))
- return;
-
- cras_system_notify_mute();
-}
-
-void cras_system_set_mute_locked(int locked)
-{
- if (state.exp_state->mute_locked == !!locked)
- return;
-
- state.exp_state->mute_locked = !!locked;
-}
-
-int cras_system_get_mute()
-{
- return state.exp_state->mute || state.exp_state->user_mute;
-}
-
-int cras_system_get_user_mute()
-{
- return state.exp_state->user_mute;
-}
-
-int cras_system_get_system_mute()
-{
- return state.exp_state->mute;
-}
-
-int cras_system_get_mute_locked()
-{
- return state.exp_state->mute_locked;
-}
-
-void cras_system_notify_capture_mute(void)
-{
- cras_observer_notify_capture_mute(state.exp_state->capture_mute,
- state.exp_state->capture_mute_locked);
-}
-
-void cras_system_set_capture_mute(int mute)
-{
- if (state.exp_state->capture_mute_locked)
- return;
-
- state.exp_state->capture_mute = !!mute;
- cras_system_notify_capture_mute();
-}
-
-void cras_system_set_capture_mute_locked(int locked)
-{
- state.exp_state->capture_mute_locked = !!locked;
- cras_system_notify_capture_mute();
-}
-
-int cras_system_get_capture_mute()
-{
- return state.exp_state->capture_mute;
-}
-
-int cras_system_get_capture_mute_locked()
-{
- return state.exp_state->capture_mute_locked;
-}
-
-int cras_system_get_suspended()
-{
- return state.exp_state->suspended;
-}
-
-void cras_system_set_suspended(int suspended)
-{
- state.exp_state->suspended = suspended;
- cras_observer_notify_suspend_changed(suspended);
- cras_alert_process_all_pending_alerts();
-}
-
-void cras_system_set_volume_limits(long min, long max)
-{
- state.exp_state->min_volume_dBFS = min;
- state.exp_state->max_volume_dBFS = max;
-}
-
-long cras_system_get_min_volume()
-{
- return state.exp_state->min_volume_dBFS;
-}
-
-long cras_system_get_max_volume()
-{
- return state.exp_state->max_volume_dBFS;
-}
-
-int cras_system_get_default_output_buffer_size()
-{
- return state.exp_state->default_output_buffer_size;
-}
-
-int cras_system_get_aec_supported()
-{
- return state.exp_state->aec_supported;
-}
-
-int cras_system_get_aec_group_id()
-{
- return state.exp_state->aec_group_id;
-}
-
-void cras_system_set_bt_wbs_enabled(bool enabled)
-{
- state.exp_state->bt_wbs_enabled = enabled;
-}
-
-bool cras_system_get_bt_wbs_enabled()
-{
- return !!state.exp_state->bt_wbs_enabled;
-}
-
-bool cras_system_get_deprioritize_bt_wbs_mic()
-{
- return !!state.exp_state->deprioritize_bt_wbs_mic;
-}
-
-void cras_system_set_bt_fix_a2dp_packet_size_enabled(bool enabled)
-{
- state.bt_fix_a2dp_packet_size = enabled;
-}
-
-bool cras_system_get_bt_fix_a2dp_packet_size_enabled()
-{
- return state.bt_fix_a2dp_packet_size;
-}
-
-void cras_system_set_noise_cancellation_enabled(bool enabled)
-{
- /* When the flag is toggled, propagate to all iodevs immediately. */
- if (cras_system_get_noise_cancellation_enabled() != enabled) {
- state.exp_state->noise_cancellation_enabled = enabled;
- cras_iodev_list_reset_for_noise_cancellation();
- }
-}
-
-bool cras_system_get_noise_cancellation_enabled()
-{
- return !!state.exp_state->noise_cancellation_enabled;
-}
-
-bool cras_system_check_ignore_ucm_suffix(const char *card_name)
-{
- /* Check the general case: ALSA Loopback card "Loopback". */
- if (!strcmp("Loopback", card_name))
- return true;
-
- /* Check board-specific ignore ucm suffix cards. */
- struct name_list *card;
- DL_FOREACH (state.ignore_suffix_cards, card) {
- if (!strcmp(card->name, card_name))
- return true;
- }
- return false;
-}
-
-bool cras_system_get_hotword_pause_at_suspend()
-{
- return !!state.exp_state->hotword_pause_at_suspend;
-}
-
-void cras_system_set_hotword_pause_at_suspend(bool pause)
-{
- state.exp_state->hotword_pause_at_suspend = pause;
-}
-
-int cras_system_add_alsa_card(struct cras_alsa_card_info *alsa_card_info)
-{
- struct card_list *card;
- struct cras_alsa_card *alsa_card;
- unsigned card_index;
-
- if (alsa_card_info == NULL)
- return -EINVAL;
-
- card_index = alsa_card_info->card_index;
-
- DL_FOREACH (state.cards, card) {
- if (card_index == cras_alsa_card_get_index(card->card))
- return -EEXIST;
- }
- alsa_card =
- cras_alsa_card_create(alsa_card_info, state.device_config_dir,
- state.device_blocklist,
- state.internal_ucm_suffix);
- if (alsa_card == NULL)
- return -ENOMEM;
- card = calloc(1, sizeof(*card));
- if (card == NULL)
- return -ENOMEM;
- card->card = alsa_card;
- DL_APPEND(state.cards, card);
- return 0;
-}
-
-int cras_system_remove_alsa_card(size_t alsa_card_index)
-{
- struct card_list *card;
-
- DL_FOREACH (state.cards, card) {
- if (alsa_card_index == cras_alsa_card_get_index(card->card))
- break;
- }
- if (card == NULL)
- return -EINVAL;
- DL_DELETE(state.cards, card);
- cras_alsa_card_destroy(card->card);
- free(card);
- return 0;
-}
-
-int cras_system_alsa_card_exists(unsigned alsa_card_index)
-{
- struct card_list *card;
-
- DL_FOREACH (state.cards, card)
- if (alsa_card_index == cras_alsa_card_get_index(card->card))
- return 1;
- return 0;
-}
-
-int cras_system_set_select_handler(
- int (*add)(int fd, void (*callback)(void *data, int events),
- void *callback_data, int events, void *select_data),
- void (*rm)(int fd, void *select_data), void *select_data)
-{
- if (state.fd_add != NULL || state.fd_rm != NULL)
- return -EEXIST;
- state.fd_add = add;
- state.fd_rm = rm;
- state.select_data = select_data;
- return 0;
-}
-
-int cras_system_add_select_fd(int fd, void (*callback)(void *data, int revents),
- void *callback_data, int events)
-{
- if (state.fd_add == NULL)
- return -EINVAL;
- return state.fd_add(fd, callback, callback_data, events,
- state.select_data);
-}
-
-int cras_system_set_add_task_handler(int (*add_task)(void (*cb)(void *data),
- void *callback_data,
- void *task_data),
- void *task_data)
-{
- if (state.add_task != NULL)
- return -EEXIST;
-
- state.add_task = add_task;
- state.task_data = task_data;
- return 0;
-}
-
-int cras_system_add_task(void (*callback)(void *data), void *callback_data)
-{
- if (state.add_task == NULL)
- return -EINVAL;
-
- return state.add_task(callback, callback_data, state.task_data);
-}
-
-void cras_system_rm_select_fd(int fd)
-{
- if (state.fd_rm != NULL)
- state.fd_rm(fd, state.select_data);
-}
-
-void cras_system_state_stream_added(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type)
-{
- struct cras_server_state *s;
-
- s = cras_system_state_update_begin();
- if (!s)
- return;
-
- s->num_active_streams[direction]++;
- s->num_streams_attached++;
- if (direction == CRAS_STREAM_INPUT) {
- s->num_input_streams_with_permission[client_type]++;
- cras_observer_notify_input_streams_with_permission(
- s->num_input_streams_with_permission);
- }
-
- cras_system_state_update_complete();
- cras_observer_notify_num_active_streams(
- direction, s->num_active_streams[direction]);
-}
-
-void cras_system_state_stream_removed(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type)
-{
- struct cras_server_state *s;
- unsigned i, sum;
-
- s = cras_system_state_update_begin();
- if (!s)
- return;
-
- sum = 0;
- for (i = 0; i < CRAS_NUM_DIRECTIONS; i++)
- sum += s->num_active_streams[i];
-
- /* Set the last active time when removing the final stream. */
- if (sum == 1)
- cras_clock_gettime(CLOCK_MONOTONIC_RAW,
- &s->last_active_stream_time);
- s->num_active_streams[direction]--;
- if (direction == CRAS_STREAM_INPUT) {
- s->num_input_streams_with_permission[client_type]--;
- cras_observer_notify_input_streams_with_permission(
- s->num_input_streams_with_permission);
- }
-
- cras_system_state_update_complete();
- cras_observer_notify_num_active_streams(
- direction, s->num_active_streams[direction]);
-}
-
-unsigned cras_system_state_get_active_streams()
-{
- unsigned i, sum;
- sum = 0;
- for (i = 0; i < CRAS_NUM_DIRECTIONS; i++)
- sum += state.exp_state->num_active_streams[i];
- return sum;
-}
-
-unsigned cras_system_state_get_active_streams_by_direction(
- enum CRAS_STREAM_DIRECTION direction)
-{
- return state.exp_state->num_active_streams[direction];
-}
-
-void cras_system_state_get_input_streams_with_permission(
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE])
-{
- unsigned type;
- for (type = 0; type < CRAS_NUM_CLIENT_TYPE; ++type)
- num_input_streams[type] =
- state.exp_state->num_input_streams_with_permission[type];
-}
-
-void cras_system_state_get_last_stream_active_time(struct cras_timespec *ts)
-{
- *ts = state.exp_state->last_active_stream_time;
-}
-
-int cras_system_state_get_output_devs(const struct cras_iodev_info **devs)
-{
- *devs = state.exp_state->output_devs;
- return state.exp_state->num_output_devs;
-}
-
-int cras_system_state_get_input_devs(const struct cras_iodev_info **devs)
-{
- *devs = state.exp_state->input_devs;
- return state.exp_state->num_input_devs;
-}
-
-int cras_system_state_get_output_nodes(const struct cras_ionode_info **nodes)
-{
- *nodes = state.exp_state->output_nodes;
- return state.exp_state->num_output_nodes;
-}
-
-int cras_system_state_get_input_nodes(const struct cras_ionode_info **nodes)
-{
- *nodes = state.exp_state->input_nodes;
- return state.exp_state->num_input_nodes;
-}
-
-void cras_system_state_set_non_empty_status(int non_empty)
-{
- state.exp_state->non_empty_status = non_empty;
-}
-
-int cras_system_state_get_non_empty_status()
-{
- return state.exp_state->non_empty_status;
-}
-
-struct cras_server_state *cras_system_state_update_begin()
-{
- if (pthread_mutex_lock(&state.update_lock)) {
- syslog(LOG_ERR, "Failed to lock stream mutex");
- return NULL;
- }
-
- __sync_fetch_and_add(&state.exp_state->update_count, 1);
- return state.exp_state;
-}
-
-void cras_system_state_update_complete()
-{
- __sync_fetch_and_add(&state.exp_state->update_count, 1);
- pthread_mutex_unlock(&state.update_lock);
-}
-
-struct cras_server_state *cras_system_state_get_no_lock()
-{
- return state.exp_state;
-}
-
-key_t cras_sys_state_shm_fd()
-{
- return state.shm_fd_ro;
-}
-
-struct cras_tm *cras_system_state_get_tm()
-{
- return state.tm;
-}
-
-void cras_system_state_dump_snapshots()
-{
- memcpy(&state.exp_state->snapshot_buffer, &state.snapshot_buffer,
- sizeof(struct cras_audio_thread_snapshot_buffer));
-}
-
-void cras_system_state_add_snapshot(struct cras_audio_thread_snapshot *snapshot)
-{
- state.snapshot_buffer.snapshots[state.snapshot_buffer.pos++] =
- (*snapshot);
- state.snapshot_buffer.pos %= CRAS_MAX_AUDIO_THREAD_SNAPSHOTS;
-}
-
-int cras_system_state_in_main_thread()
-{
- return pthread_self() == state.main_thread_tid;
-}
diff --git a/cras/src/server/cras_system_state.h b/cras/src/server/cras_system_state.h
deleted file mode 100644
index bd09395c..00000000
--- a/cras/src/server/cras_system_state.h
+++ /dev/null
@@ -1,365 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * Handles various system-level settings.
- *
- * Volume: The system volume is represented as a value from 0 to 100. This
- * number will be interpreted by the output device and applied to the hardware.
- * The value will be mapped to dB by the active device as it will know its curve
- * the best.
- */
-
-#ifndef CRAS_SYSTEM_STATE_H_
-#define CRAS_SYSTEM_STATE_H_
-
-#include <stdbool.h>
-#include <stddef.h>
-
-#include "cras_types.h"
-
-#define CRAS_MAX_SYSTEM_VOLUME 100
-#define DEFAULT_CAPTURE_GAIN 2000 /* 20dB of gain. */
-/* Default to -6 dBFS as 90% of CrOS boards use microphone with -26dBFS
- * sensitivity under 94dB SPL @ 1kHz and we generally added 20dB gain to it.
- * This is a temporary value that should be refined when the standard process
- * measuring intrinsic sensitivity is built. */
-#define DEFAULT_CAPTURE_VOLUME_DBFS -600
-/* Default to 1--dB of range for playback and capture. */
-#define DEFAULT_MIN_VOLUME_DBFS -10000
-#define DEFAULT_MAX_VOLUME_DBFS 0
-#define DEFAULT_MIN_CAPTURE_GAIN -5000
-#define DEFAULT_MAX_CAPTURE_GAIN 5000
-
-struct cras_tm;
-
-/* Initialize system settings.
- *
- * Args:
- * device_config_dir - Directory for device configs where volume curves live.
- * shm_name - Name of the shared memory region used to store the state.
- * rw_shm_fd - FD of the shm region.
- * ro_shm_fd - FD of the shm region opened RO for sharing with clients.
- * exp_state - Shared memory region for storing state.
- * exp_state_size - Size of |exp_state|.
- */
-void cras_system_state_init(const char *device_config_dir, const char *shm_name,
- int rw_shm_fd, int ro_shm_fd,
- struct cras_server_state *exp_state,
- size_t exp_state_size);
-void cras_system_state_deinit();
-
-/* Sets the suffix string to control which UCM config fo load. */
-void cras_system_state_set_internal_ucm_suffix(const char *internal_ucm_suffix);
-
-/* Sets the system volume. Will be applied by the active device. */
-void cras_system_set_volume(size_t volume);
-/* Gets the current system volume. */
-size_t cras_system_get_volume();
-
-/* Gets the current system capture volume. As we remove the support of setting
- * system capture gain, it should always be DEFAULT_CAPTURE_GAIN now. */
-long cras_system_get_capture_gain();
-
-/* Sets if the system is muted by the user. */
-void cras_system_set_user_mute(int muted);
-/* Sets if the system is muted for . */
-void cras_system_set_mute(int muted);
-/* Sets if the system muting is locked or not. */
-void cras_system_set_mute_locked(int locked);
-/* Gets the current mute state of the system. */
-int cras_system_get_mute();
-/* Gets the current user mute state. */
-int cras_system_get_user_mute();
-/* Gets the current system mute state. */
-int cras_system_get_system_mute();
-/* Gets if the system muting is locked or not. */
-int cras_system_get_mute_locked();
-
-/* Gets the suspend state of audio. */
-int cras_system_get_suspended();
-
-/* Sets the suspend state of audio.
- * Args:
- * suspend - True for suspend, false for resume.
- */
-void cras_system_set_suspended(int suspend);
-
-/* Sets if the system capture path is muted or not. */
-void cras_system_set_capture_mute(int muted);
-/* Sets if the system capture path muting is locked or not. */
-void cras_system_set_capture_mute_locked(int locked);
-/* Gets the current mute state of the system capture path. */
-int cras_system_get_capture_mute();
-/* Gets if the system capture path muting is locked or not. */
-int cras_system_get_capture_mute_locked();
-
-/* Sets the value in dB of the MAX and MIN volume settings. This will allow
- * clients to query what range of control is available. Both arguments are
- * specified as dB * 100.
- * Args:
- * min - dB value when volume = 1 (0 mutes).
- * max - dB value when volume = CRAS_MAX_SYSTEM_VOLUME
- */
-void cras_system_set_volume_limits(long min, long max);
-/* Returns the dB value when volume = 1, in dB * 100. */
-long cras_system_get_min_volume();
-/* Returns the dB value when volume = CRAS_MAX_SYSTEM_VOLUME, in dB * 100. */
-long cras_system_get_max_volume();
-
-/* Returns the default value of output buffer size in frames. */
-int cras_system_get_default_output_buffer_size();
-
-/* Returns if system aec is supported. */
-int cras_system_get_aec_supported();
-
-/* Returns the system aec group id is available. */
-int cras_system_get_aec_group_id();
-
-/* Sets the flag to enable or disable bluetooth wideband speech feature. */
-void cras_system_set_bt_wbs_enabled(bool enabled);
-
-/* Gets the elable flag of bluetooth wideband speech feature. */
-bool cras_system_get_bt_wbs_enabled();
-
-/*
- * Returns if Bluetooth WBS mic should be deprioritized for selecting
- * as default audio input option.
- */
-bool cras_system_get_deprioritize_bt_wbs_mic();
-
-/* Sets the flag to enable or disable Bluetooth fixed A2DP packet size. */
-void cras_system_set_bt_fix_a2dp_packet_size_enabled(bool enabled);
-
-/* Gets the flag of Bluetooth fixed A2DP packet size. */
-bool cras_system_get_bt_fix_a2dp_packet_size_enabled();
-
-/* Sets the flag to enable or disable Noise Cancellation. */
-void cras_system_set_noise_cancellation_enabled(bool enabled);
-
-/* Gets the flag of Noise Cancellation. */
-bool cras_system_get_noise_cancellation_enabled();
-
-/* Checks if the card ignores the ucm suffix. */
-bool cras_system_check_ignore_ucm_suffix(const char *card_name);
-
-/* Returns true if hotword detection is paused at system suspend. */
-bool cras_system_get_hotword_pause_at_suspend();
-
-/* Sets whether to pause hotword detection at system suspend. */
-void cras_system_set_hotword_pause_at_suspend(bool pause);
-
-/* Adds a card at the given index to the system. When a new card is found
- * (through a udev event notification) this will add the card to the system,
- * causing its devices to become available for playback/capture.
- * Args:
- * alsa_card_info - Info about the alsa card (Index, type, etc.).
- * Returns:
- * 0 on success, negative error on failure (Can't create or card already
- * exists).
- */
-int cras_system_add_alsa_card(struct cras_alsa_card_info *alsa_card_info);
-
-/* Removes a card. When a device is removed this will do the cleanup. Device
- * at index must have been added using cras_system_add_alsa_card().
- * Args:
- * alsa_card_index - Index ALSA uses to refer to the card. The X in "hw:X".
- * Returns:
- * 0 on success, negative error on failure (Can't destroy or card doesn't
- * exist).
- */
-int cras_system_remove_alsa_card(size_t alsa_card_index);
-
-/* Checks if an alsa card has been added to the system.
- * Args:
- * alsa_card_index - Index ALSA uses to refer to the card. The X in "hw:X".
- * Returns:
- * 1 if the card has already been added, 0 if not.
- */
-int cras_system_alsa_card_exists(unsigned alsa_card_index);
-
-/* Poll interface provides a way of getting a callback when 'select'
- * returns for a given file descriptor.
- */
-
-/* Register the function to use to inform the select loop about new
- * file descriptors and callbacks.
- * Args:
- * add - The function to call when a new fd is added.
- * rm - The function to call when a new fd is removed.
- * select_data - Additional value passed back to add and remove.
- * Returns:
- * 0 on success, or -EBUSY if there is already a registered handler.
- */
-int cras_system_set_select_handler(
- int (*add)(int fd, void (*callback)(void *data, int revents),
- void *callback_data, int events, void *select_data),
- void (*rm)(int fd, void *select_data), void *select_data);
-
-/* Adds the fd and callback pair. When select indicates that fd is readable,
- * the callback will be called.
- * Args:
- * fd - The file descriptor to pass to select(2).
- * callback - The callback to call when fd is ready.
- * callback_data - Value passed back to the callback.
- * events - The events to poll for.
- * Returns:
- * 0 on success or a negative error code on failure.
- */
-int cras_system_add_select_fd(int fd, void (*callback)(void *data, int revents),
- void *callback_data, int events);
-
-/* Removes the fd from the list of fds that are passed to select.
- * Args:
- * fd - The file descriptor to remove from the list.
- */
-void cras_system_rm_select_fd(int fd);
-
-/*
- * Register the function to use to add a task for main thread to execute.
- * Args:
- * add_task - The function to call when new task is added.
- * task_data - Additional data to pass back to add_task.
- * Returns:
- * 0 on success, or -EEXIST if there's already a registered handler.
- */
-int cras_system_set_add_task_handler(int (*add_task)(void (*cb)(void *data),
- void *callback_data,
- void *task_data),
- void *task_data);
-
-/*
- * Adds a task callback and data pair, to be executed in the next main thread
- * loop without additional wait time.
- * Args:
- * callback - The function to execute.
- * callback_data - The data to be passed to callback when executed.
- * Returns:
- * 0 on success, or -EINVAL if there's no handler for adding task.
- */
-int cras_system_add_task(void (*callback)(void *data), void *callback_data);
-
-/* Signals that an audio input or output stream has been added to the system.
- * This allows the count of active streams can be used to notice when the audio
- * subsystem is idle.
- * Args:
- * direction - Directions of audio streams.
- * client_type - CRAS_CLIENT_TYPE of the audio stream.
- */
-void cras_system_state_stream_added(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type);
-
-/* Signals that an audio input or output stream has been removed from the
- * system. This allows the count of active streams can be used to notice when
- * the audio subsystem is idle.
- * Args:
- * direction - Directions of audio stream.
- * client_type - CRAS_CLIENT_TYPE of the audio stream.
- */
-void cras_system_state_stream_removed(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type);
-
-/* Returns the number of active playback and capture streams. */
-unsigned cras_system_state_get_active_streams();
-
-/* Returns the number of active streams with given direction.
- * Args:
- * direction - Directions of audio stream.
- */
-unsigned cras_system_state_get_active_streams_by_direction(
- enum CRAS_STREAM_DIRECTION direction);
-
-/* Returns the number of input streams with permission per CRAS_CLIENT_TYPE.
- *
- * Returns:
- * num_input_streams - An array with length = CRAS_NUM_CLIENT_TYPE and each
- * element is the number of the current input
- * streams with permission in each client type.
- */
-void cras_system_state_get_input_streams_with_permission(
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE]);
-
-/* Fills ts with the time the last stream was removed from the system, the time
- * the stream count went to zero.
- */
-void cras_system_state_get_last_stream_active_time(struct cras_timespec *ts);
-
-/* Returns output devices information.
- * Args:
- * devs - returns the array of output devices information.
- * Returns:
- * number of output devices.
- */
-int cras_system_state_get_output_devs(const struct cras_iodev_info **devs);
-
-/* Returns input devices information.
- * Args:
- * devs - returns the array of input devices information.
- * Returns:
- * number of input devices.
- */
-int cras_system_state_get_input_devs(const struct cras_iodev_info **devs);
-
-/* Returns output nodes information.
- * Args:
- * nodes - returns the array of output nodes information.
- * Returns:
- * number of output nodes.
- */
-int cras_system_state_get_output_nodes(const struct cras_ionode_info **nodes);
-
-/* Returns input nodes information.
- * Args:
- * nodes - returns the array of input nodes information.
- * Returns:
- * number of input nodes.
- */
-int cras_system_state_get_input_nodes(const struct cras_ionode_info **nodes);
-
-/*
- * Sets the non-empty audio status.
- */
-void cras_system_state_set_non_empty_status(int non_empty);
-
-/*
- * Returns the non-empty audio status.
- */
-int cras_system_state_get_non_empty_status();
-
-/* Returns a pointer to the current system state that is shared with clients.
- * This also 'locks' the structure by incrementing the update count to an odd
- * value.
- */
-struct cras_server_state *cras_system_state_update_begin();
-
-/* Unlocks the system state structure that was updated after calling
- * cras_system_state_update_begin by again incrementing the update count.
- */
-void cras_system_state_update_complete();
-
-/* Gets a pointer to the system state without locking it. Only used for debug
- * log. Don't add calls to this function. */
-struct cras_server_state *cras_system_state_get_no_lock();
-
-/* Returns the shm fd for the server_state structure. */
-key_t cras_sys_state_shm_fd();
-
-/* Returns the timer manager. */
-struct cras_tm *cras_system_state_get_tm();
-
-/*
- * Add snapshot to snapshot buffer in system state
- */
-void cras_system_state_add_snapshot(struct cras_audio_thread_snapshot *);
-
-/*
- * Dump snapshots from system state to shared memory with client
- */
-void cras_system_state_dump_snapshots();
-
-/*
- * Returns true if in the main thread.
- */
-int cras_system_state_in_main_thread();
-
-#endif /* CRAS_SYSTEM_STATE_H_ */
diff --git a/cras/src/server/cras_telephony.c b/cras/src/server/cras_telephony.c
deleted file mode 100644
index 805fb137..00000000
--- a/cras/src/server/cras_telephony.c
+++ /dev/null
@@ -1,455 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <string.h>
-#include <stdlib.h>
-#include <syslog.h>
-
-#include <dbus/dbus.h>
-
-#include "cras_telephony.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_hfp_slc.h"
-
-#define CRAS_TELEPHONY_INTERFACE "org.chromium.cras.Telephony"
-#define CRAS_TELEPHONY_OBJECT_PATH "/org/chromium/cras/telephony"
-#define TELEPHONY_INTROSPECT_XML \
- DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE \
- "<node>\n" \
- " <interface name=\"" CRAS_TELEPHONY_INTERFACE "\">\n" \
- " <method name=\"AnswerCall\">\n" \
- " </method>\n" \
- " <method name=\"IncomingCall\">\n" \
- " <arg name=\"value\" type=\"s\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"TerminateCall\">\n" \
- " </method>\n" \
- " <method name=\"SetBatteryLevel\">\n" \
- " <arg name=\"value\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetSignalStrength\">\n" \
- " <arg name=\"value\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetServiceAvailability\">\n" \
- " <arg name=\"value\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetDialNumber\">\n" \
- " <arg name=\"value\" type=\"s\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetCallheld\">\n" \
- " <arg name=\"value\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetCallsetup\">\n" \
- " <arg name=\"value\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " <method name=\"SetCall\">\n" \
- " <arg name=\"value\" type=\"i\" direction=\"in\"/>\n" \
- " </method>\n" \
- " </interface>\n" \
- " <interface name=\"" DBUS_INTERFACE_INTROSPECTABLE "\">\n" \
- " <method name=\"Introspect\">\n" \
- " <arg name=\"data\" type=\"s\" direction=\"out\"/>\n" \
- " </method>\n" \
- " </interface>\n" \
- "</node>\n"
-
-static struct cras_telephony_handle telephony_handle;
-
-/* Helper to extract a single argument from a DBus message. */
-static DBusHandlerResult get_single_arg(DBusMessage *message, int dbus_type,
- void *arg)
-{
- DBusError dbus_error;
-
- dbus_error_init(&dbus_error);
-
- if (!dbus_message_get_args(message, &dbus_error, dbus_type, arg,
- DBUS_TYPE_INVALID)) {
- syslog(LOG_WARNING, "Bad method received: %s",
- dbus_error.message);
- dbus_error_free(&dbus_error);
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
- }
-
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-/* Helper to send an empty reply. */
-static void send_empty_reply(DBusConnection *conn, DBusMessage *message)
-{
- DBusMessage *reply;
- dbus_uint32_t serial = 0;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return;
-
- dbus_connection_send(conn, reply, &serial);
-
- dbus_message_unref(reply);
-}
-
-static DBusHandlerResult handle_incoming_call(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- const char *number;
-
- rc = get_single_arg(message, DBUS_TYPE_STRING, &number);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- handle = cras_hfp_ag_get_active_handle();
-
- telephony_handle.callsetup = 1;
-
- if (handle) {
- hfp_event_update_callsetup(handle);
- hfp_event_incoming_call(handle, number, 129);
- }
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_terminate_call(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- cras_telephony_event_terminate_call();
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_answer_call(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- cras_telephony_event_answer_call();
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_dial_number(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- DBusHandlerResult rc;
- const char *number;
-
- rc = get_single_arg(message, DBUS_TYPE_STRING, &number);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- cras_telephony_store_dial_number(strlen(number), number);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_battery(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- int value;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &value);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- handle = cras_hfp_ag_get_active_handle();
- if (handle)
- hfp_event_set_battery(handle, value);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_signal(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- int value;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &value);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- handle = cras_hfp_ag_get_active_handle();
- if (handle)
- hfp_event_set_signal(handle, value);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_service(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- int value;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &value);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- handle = cras_hfp_ag_get_active_handle();
- if (handle)
- hfp_event_set_service(handle, value);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_callheld(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- int value;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &value);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- telephony_handle.callheld = value;
- handle = cras_hfp_ag_get_active_handle();
- if (handle)
- hfp_event_update_callheld(handle);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_callsetup(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- int value;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &value);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- telephony_handle.callsetup = value;
- handle = cras_hfp_ag_get_active_handle();
- if (handle)
- hfp_event_update_callsetup(handle);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-static DBusHandlerResult handle_set_call(DBusConnection *conn,
- DBusMessage *message, void *arg)
-{
- struct hfp_slc_handle *handle;
- DBusHandlerResult rc;
- int value;
-
- rc = get_single_arg(message, DBUS_TYPE_INT32, &value);
- if (rc != DBUS_HANDLER_RESULT_HANDLED)
- return rc;
-
- telephony_handle.call = value;
- handle = cras_hfp_ag_get_active_handle();
- if (handle)
- hfp_event_update_call(handle);
-
- send_empty_reply(conn, message);
- return DBUS_HANDLER_RESULT_HANDLED;
-}
-
-/* Handle incoming messages. */
-static DBusHandlerResult
-handle_telephony_message(DBusConnection *conn, DBusMessage *message, void *arg)
-{
- syslog(LOG_ERR, "Telephony message: %s %s %s",
- dbus_message_get_path(message),
- dbus_message_get_interface(message),
- dbus_message_get_member(message));
-
- if (dbus_message_is_method_call(message, DBUS_INTERFACE_INTROSPECTABLE,
- "Introspect")) {
- DBusMessage *reply;
- const char *xml = TELEPHONY_INTROSPECT_XML;
-
- reply = dbus_message_new_method_return(message);
- if (!reply)
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &xml,
- DBUS_TYPE_INVALID))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
- if (!dbus_connection_send(conn, reply, NULL))
- return DBUS_HANDLER_RESULT_NEED_MEMORY;
-
- dbus_message_unref(reply);
- return DBUS_HANDLER_RESULT_HANDLED;
- } else if (dbus_message_is_method_call(
- message, CRAS_TELEPHONY_INTERFACE, "IncomingCall")) {
- return handle_incoming_call(conn, message, arg);
- } else if (dbus_message_is_method_call(message,
- CRAS_TELEPHONY_INTERFACE,
- "TerminateCall")) {
- return handle_terminate_call(conn, message, arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_TELEPHONY_INTERFACE, "AnswerCall")) {
- return handle_answer_call(conn, message, arg);
- } else if (dbus_message_is_method_call(message,
- CRAS_TELEPHONY_INTERFACE,
- "SetDialNumber")) {
- return handle_set_dial_number(conn, message, arg);
- } else if (dbus_message_is_method_call(message,
- CRAS_TELEPHONY_INTERFACE,
- "SetBatteryLevel")) {
- return handle_set_battery(conn, message, arg);
- } else if (dbus_message_is_method_call(message,
- CRAS_TELEPHONY_INTERFACE,
- "SetSignalStrength")) {
- return handle_set_signal(conn, message, arg);
- } else if (dbus_message_is_method_call(message,
- CRAS_TELEPHONY_INTERFACE,
- "SetServiceAvailability")) {
- return handle_set_service(conn, message, arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_TELEPHONY_INTERFACE, "SetCallheld")) {
- return handle_set_callheld(conn, message, arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_TELEPHONY_INTERFACE, "SetCallsetup")) {
- return handle_set_callsetup(conn, message, arg);
- } else if (dbus_message_is_method_call(
- message, CRAS_TELEPHONY_INTERFACE, "SetCall")) {
- return handle_set_call(conn, message, arg);
- }
-
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-/* Exported Interface */
-
-void cras_telephony_start(DBusConnection *conn)
-{
- static const DBusObjectPathVTable control_vtable = {
- .message_function = handle_telephony_message,
- };
-
- DBusError dbus_error;
-
- telephony_handle.dbus_conn = conn;
- dbus_connection_ref(telephony_handle.dbus_conn);
-
- if (!dbus_connection_register_object_path(
- conn, CRAS_TELEPHONY_OBJECT_PATH, &control_vtable,
- &dbus_error)) {
- syslog(LOG_ERR, "Couldn't register telephony control: %s: %s",
- CRAS_TELEPHONY_OBJECT_PATH, dbus_error.message);
- dbus_error_free(&dbus_error);
- return;
- }
-}
-
-void cras_telephony_stop()
-{
- if (!telephony_handle.dbus_conn)
- return;
-
- dbus_connection_unregister_object_path(telephony_handle.dbus_conn,
- CRAS_TELEPHONY_OBJECT_PATH);
- dbus_connection_unref(telephony_handle.dbus_conn);
- telephony_handle.dbus_conn = NULL;
-}
-
-struct cras_telephony_handle *cras_telephony_get()
-{
- return &telephony_handle;
-}
-
-/* Procedure to answer a call from AG.
- *
- * HF(hands-free) AG(audio gateway)
- * <-- Call answered
- * <-- +CIEV: (call = 1)
- * <-- +CIEV: (callsetup = 0)
- */
-int cras_telephony_event_answer_call()
-{
- int rc;
-
- struct hfp_slc_handle *handle;
-
- handle = cras_hfp_ag_get_active_handle();
-
- if (telephony_handle.call == 0) {
- telephony_handle.call = 1;
- if (handle) {
- rc = hfp_event_update_call(handle);
- if (rc)
- return rc;
- }
- }
-
- telephony_handle.callsetup = 0;
- if (handle) {
- rc = hfp_event_update_callsetup(handle);
- if (rc)
- return rc;
- }
-
- return 0;
-}
-
-/* Procedure to terminate a call from AG.
- *
- * HF(hands-free) AG(audio gateway)
- * <-- Call dropped
- * <-- +CIEV: (call = 0)
- */
-int cras_telephony_event_terminate_call()
-{
- int rc;
- struct hfp_slc_handle *handle;
-
- handle = cras_hfp_ag_get_active_handle();
-
- if (telephony_handle.call) {
- telephony_handle.call = 0;
- if (handle) {
- rc = hfp_event_update_call(handle);
- if (rc)
- return rc;
- }
- }
- if (telephony_handle.callsetup) {
- telephony_handle.callsetup = 0;
- if (handle) {
- rc = hfp_event_update_callsetup(handle);
- if (rc)
- return rc;
- }
- }
- return 0;
-}
-
-void cras_telephony_store_dial_number(int len, const char *number)
-{
- if (telephony_handle.dial_number != NULL) {
- free(telephony_handle.dial_number);
- telephony_handle.dial_number = NULL;
- }
-
- if (len == 0)
- return;
-
- telephony_handle.dial_number =
- (char *)calloc(len + 1, sizeof(*telephony_handle.dial_number));
- strncpy(telephony_handle.dial_number, number, len);
-
- syslog(LOG_ERR, "store dial_number: \"%s\"",
- telephony_handle.dial_number);
-}
diff --git a/cras/src/server/cras_telephony.h b/cras/src/server/cras_telephony.h
deleted file mode 100644
index 7c0a6c54..00000000
--- a/cras/src/server/cras_telephony.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_TELEPHONY_H_
-#define CRAS_TELEPHONY_H_
-
-#include <dbus/dbus.h>
-
-/* Handle object to hold required info to handle telephony status which
- * is required for responsing HFP query commands.
- * Args:
- * call - standard call status indicator, where
- * 0: no call active
- * 1: call is active
- * callsetup - call set up status indicator.
- * 0: not currently in call set up
- * 1: an incoming call prcess ongoing
- * 2: an outgoing call set up is ongoing
- * callhold - call hold status indicator.
- * 0: no call hold
- * 1: call is placed on hold or active/held calls swapped
- * (The AG has both and active AND a held call)
- * 2: call on hold, no active call
- * dial_number - phone number, used on fake memory storage and last phone
- * number storage.
- * dbus_conn - dus connetion which is used in whole telephony module.
- */
-struct cras_telephony_handle {
- int call;
- int callsetup;
- int callheld;
- char *dial_number;
-
- DBusConnection *dbus_conn;
-};
-
-void cras_telephony_start(DBusConnection *conn);
-
-void cras_telephony_stop();
-
-struct cras_telephony_handle *cras_telephony_get();
-
-/* Stores dial number in telephony module. */
-void cras_telephony_store_dial_number(int len, const char *num);
-
-/* Handles answer call event from dbus or HF */
-int cras_telephony_event_answer_call();
-
-/* Handles answer call event from dbus or HF */
-int cras_telephony_event_terminate_call();
-
-#endif /* CRAS_TELEPHONY_H_ */
diff --git a/cras/src/server/cras_tm.c b/cras/src/server/cras_tm.c
deleted file mode 100644
index c215fdc0..00000000
--- a/cras/src/server/cras_tm.c
+++ /dev/null
@@ -1,149 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-#include <time.h>
-
-/* Represents an armed timer.
- * Members:
- * ts - timespec at which the timer should fire.
- * cb - Callback to call when the timer expires.
- * cb_data - Data passed to the callback.
- */
-struct cras_timer {
- struct timespec ts;
- void (*cb)(struct cras_timer *t, void *data);
- void *cb_data;
- struct cras_timer *next, *prev;
-};
-
-/* Timer Manager, keeps a list of active timers. */
-struct cras_tm {
- struct cras_timer *timers;
-};
-
-/* Local Functions. */
-
-/* Adds ms milliseconds to ts. */
-static inline void add_ms_ts(struct timespec *ts, unsigned int ms)
-{
- if (ms >= 1000) {
- ts->tv_sec += ms / 1000;
- ms %= 1000;
- }
- ts->tv_nsec += ms * 1000000L;
- if (ts->tv_nsec >= 1000000000L) {
- ts->tv_sec += ts->tv_nsec / 1000000000L;
- ts->tv_nsec %= 1000000000L;
- }
-}
-
-/* Checks if timespec a is less than b. */
-static inline int timespec_sooner(const struct timespec *a,
- const struct timespec *b)
-{
- return (a->tv_sec < b->tv_sec ||
- (a->tv_sec == b->tv_sec && a->tv_nsec <= b->tv_nsec));
-}
-
-/* Exported Interface. */
-
-struct cras_timer *cras_tm_create_timer(struct cras_tm *tm, unsigned int ms,
- void (*cb)(struct cras_timer *t,
- void *data),
- void *cb_data)
-{
- struct cras_timer *t;
-
- t = calloc(1, sizeof(*t));
- if (!t)
- return NULL;
-
- t->cb = cb;
- t->cb_data = cb_data;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &t->ts);
- add_ms_ts(&t->ts, ms);
-
- DL_APPEND(tm->timers, t);
-
- return t;
-}
-
-void cras_tm_cancel_timer(struct cras_tm *tm, struct cras_timer *t)
-{
- DL_DELETE(tm->timers, t);
- free(t);
-}
-
-struct cras_tm *cras_tm_init()
-{
- return calloc(1, sizeof(struct cras_tm));
-}
-
-void cras_tm_deinit(struct cras_tm *tm)
-{
- struct cras_timer *t;
-
- DL_FOREACH (tm->timers, t) {
- DL_DELETE(tm->timers, t);
- free(t);
- }
- free(tm);
-}
-
-int cras_tm_get_next_timeout(const struct cras_tm *tm, struct timespec *ts)
-{
- struct cras_timer *t;
- struct timespec now;
- struct timespec *min;
-
- if (!tm->timers)
- return 0;
-
- min = &tm->timers->ts;
- DL_FOREACH (tm->timers, t)
- if (timespec_sooner(&t->ts, min))
- min = &t->ts;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- if (timespec_sooner(min, &now)) {
- /* Timer already expired. */
- ts->tv_sec = ts->tv_nsec = 0;
- return 1;
- }
-
- subtract_timespecs(min, &now, ts);
- return 1;
-}
-
-void cras_tm_call_callbacks(struct cras_tm *tm)
-{
- struct timespec now;
- struct cras_timer *t, *next;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- /* Don't use DL_FOREACH to iterate timers because in each loop the
- * next timer pointer is stored for later access but it could be
- * cancelled and freed in current timer's callback causing invalid
- * memory access. */
- t = tm->timers;
- while (t) {
- next = t->next;
- if (timespec_sooner(&t->ts, &now)) {
- t->cb(t, t->cb_data);
- /* Update next timer because it could have been modified
- * in t->cb(). */
- next = t->next;
- cras_tm_cancel_timer(tm, t);
- }
- t = next;
- }
-}
diff --git a/cras/src/server/cras_tm.h b/cras/src/server/cras_tm.h
deleted file mode 100644
index 4cc37ac4..00000000
--- a/cras/src/server/cras_tm.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_TM_H_
-#define CRAS_TM_H_
-
-/* cras_timer provides an interface to register a function to be called at a
- * later time. This interface should be used from the main thread only, it is
- * not thread safe.
- */
-
-struct cras_tm; /* timer manager */
-struct cras_timer;
-
-/* Creates a timer. Must later be removed with cras_rm_cancel_timer.
- * Args:
- * tm - Timer manager.
- * ms - Call 'cb' in ms milliseconds.
- * cb - The callback to call at timeout.
- * cb_data - Passed to the callback when it is run.
- * Returns:
- * Pointer to a newly allocated timer, passed timer to cras_tm_cancel_timer
- * to cancel before it fires.
- */
-struct cras_timer *cras_tm_create_timer(struct cras_tm *tm, unsigned int ms,
- void (*cb)(struct cras_timer *t,
- void *data),
- void *cb_data);
-
-/* Deletes a timer returned from cras_tm_create_timer. */
-void cras_tm_cancel_timer(struct cras_tm *tm, struct cras_timer *t);
-
-/* Interface for system to create the timer manager. */
-struct cras_tm *cras_tm_init();
-
-/* Interface for system to destroy the timer manager. */
-void cras_tm_deinit(struct cras_tm *tm);
-
-/* Get the amount of time before the next timer expires. ts is set to an
- * the amount of time before the next timer expires (0 if already past due).
- * Args:
- * tm - Timer manager.
- * ts - Filled with time before next event.
- * Returns:
- * 0 if no timers are active, 1 if they are.
- */
-int cras_tm_get_next_timeout(const struct cras_tm *tm, struct timespec *ts);
-
-/* Calls any expired timers. */
-void cras_tm_call_callbacks(struct cras_tm *tm);
-
-#endif /* CRAS_TM_H_ */
diff --git a/cras/src/server/cras_udev.c b/cras/src/server/cras_udev.c
deleted file mode 100644
index 16f0e3b2..00000000
--- a/cras/src/server/cras_udev.c
+++ /dev/null
@@ -1,426 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <assert.h>
-#include <libudev.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <regex.h>
-#include <syslog.h>
-
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "cras_checksum.h"
-
-struct udev_callback_data {
- struct udev_monitor *mon;
- struct udev *udev;
- int fd;
-};
-
-static unsigned is_action(const char *desired, const char *actual)
- __attribute__((nonnull(1)));
-
-/* Matches Alsa sound device entries generated by udev. For
- * example:
- *
- * /devices/pci0000:00/0000:00:1b.0/sound/card1/pcmC1D0p
- *
- * We want to be able to extract:
- *
- * o The card number
- * o The device number
- * o If it's 'playback' (p) or 'capture' (c). (It may not be both.)
- *
- * Given the example above, the following matches should occur:
- *
- *
- * | A |
- * BBCCCD
- * /devices/pci0000:00/0000:00:1b.0/sound/card1/pcmC1D10p
- *
- * A: The whole regex will be matched.
- * B: The card.
- * C: The device.
- * D: 'p' (playback) or 'c' (capture)
- *
- * The order of the offsets in the 'pmatch' buffer does not appear
- * to match with the documentation:
- *
- * Each rm_so element that is not -1 indicates the start
- * offset of the next largest substring match within the
- * string.
- *
- * But are, instead, filled in the same order presented in the
- * string. To alleviate possible issudes, the 'C' (card) and 'D'
- * (device) identifying characters are included in the result.
- */
-static const char pcm_regex_string[] = "^.*pcm(C[0-9]+)(D[0-9]+)([pc])";
-static regex_t pcm_regex;
-
-/* Card regex is similar to above, but only has one field -- the card. The
- * format is the same with the exception of the leaf node being of the form:
- *
- * /devices/...../card0
- *
- * Where 0 is the card number and the only thing we care about in
- * this case.
- */
-
-static const char card_regex_string[] = "^.*/card([0-9]+)";
-static regex_t card_regex;
-
-static char const *const subsystem = "sound";
-static const unsigned int MAX_DESC_NAME_LEN = 256;
-
-static unsigned is_action(const char *desired, const char *actual)
-{
- return actual != NULL && strcmp(desired, actual) == 0;
-}
-
-static unsigned is_action_change(const char *action)
-{
- return is_action("change", action);
-}
-
-static unsigned is_action_remove(const char *action)
-{
- return is_action("remove", action);
-}
-
-static unsigned is_internal_bus(const char *bus)
-{
- return (bus != NULL &&
- (strcmp(bus, "pci") == 0 || strcmp(bus, "platform") == 0));
-}
-
-static unsigned is_external_bus(const char *bus)
-{
- return (bus != NULL && (strcmp(bus, "usb") == 0));
-}
-
-static unsigned is_internal_device(struct udev_device *dev)
-{
- struct udev_device *parent = udev_device_get_parent(dev);
- while (parent != NULL) {
- const char *name = udev_device_get_subsystem(parent);
-
- if (name != NULL) {
- if (is_external_bus(name))
- return 0;
- else if (is_internal_bus(name))
- return 1;
- }
- parent = udev_device_get_parent(parent);
- }
- return 0;
-}
-
-static unsigned is_card_device(struct udev_device *dev, unsigned *internal,
- unsigned *card_number, const char **sysname)
-{
- regmatch_t m[2];
- const char *devpath = udev_device_get_devpath(dev);
-
- if (devpath != NULL &&
- regexec(&card_regex, devpath, ARRAY_SIZE(m), m, 0) == 0) {
- *sysname = udev_device_get_sysname(dev);
- *internal = is_internal_device(dev);
- *card_number = (unsigned)atoi(&devpath[m[1].rm_so]);
- return 1;
- }
-
- return 0;
-}
-
-static void set_factory_default(unsigned card_number)
-{
- static const char alsactl[] = "/usr/sbin/alsactl";
- static const char asound_state[] = "/etc/asound.state";
- char cmd_buf[128];
- struct stat stat_buf;
- int r;
-
- if (stat(asound_state, &stat_buf) == 0) {
- syslog(LOG_INFO, "%s: init card '%u' to factory default",
- __FUNCTION__, card_number);
- r = snprintf(cmd_buf, ARRAY_SIZE(cmd_buf),
- "%s --file %s restore %u", alsactl, asound_state,
- card_number);
- cmd_buf[ARRAY_SIZE(cmd_buf) - 1] = '\0';
- r = system(cmd_buf);
- if (r != 0)
- syslog(LOG_ERR,
- "%s: failed to init card '%d' "
- "to factory default. Failure: %d. Command: %s",
- __FUNCTION__, card_number, r, cmd_buf);
- }
-}
-
-static inline void udev_delay_for_alsa()
-{
- /* Provide a small delay so that the udev message can
- * propogate throughout the whole system, and Alsa can set up
- * the new device. Without a small delay, an error of the
- * form:
- *
- * Fail opening control hw:?
- *
- * will be produced by cras_alsa_card_create().
- */
- usleep(125000); /* 0.125 second */
-}
-
-/* Reads the "descriptors" file of the usb device and returns the
- * checksum of the contents. Returns 0 if the file can not be read */
-static uint32_t calculate_desc_checksum(struct udev_device *dev)
-{
- char path[MAX_DESC_NAME_LEN];
- struct stat stat_buf;
- int fd;
- unsigned char *buf = NULL;
- int buf_size = 0;
- int read_size;
- ssize_t n;
- uint32_t result;
-
- if (snprintf(path, sizeof(path), "%s/descriptors",
- udev_device_get_syspath(dev)) >= sizeof(path)) {
- syslog(LOG_ERR, "failed to build path");
- return 0;
- }
-
- if (stat(path, &stat_buf) < 0) {
- syslog(LOG_ERR, "failed to stat file %s: %s", path,
- strerror(errno));
- return 0;
- }
-
- fd = open(path, O_RDONLY);
- if (fd < 0) {
- syslog(LOG_ERR, "failed to open file %s: %s", path,
- strerror(errno));
- return 0;
- }
-
- read_size = 0;
- while (read_size < stat_buf.st_size) {
- if (read_size == buf_size) {
- if (buf_size == 0)
- buf_size = 256;
- else
- buf_size *= 2;
- uint8_t *new_buf = realloc(buf, buf_size);
- if (new_buf == NULL) {
- syslog(LOG_ERR, "no memory to read file %s",
- path);
- goto bail;
- }
- buf = new_buf;
- }
- n = read(fd, buf + read_size, buf_size - read_size);
- if (n == 0)
- break;
- if (n < 0) {
- syslog(LOG_ERR, "failed to read file %s", path);
- goto bail;
- }
- read_size += n;
- }
-
- close(fd);
- result = crc32_checksum(buf, read_size);
- free(buf);
- return result;
-bail:
- close(fd);
- free(buf);
- return 0;
-}
-
-static void fill_usb_card_info(struct cras_alsa_card_info *card_info,
- struct udev_device *dev)
-{
- const char *sysattr;
- struct udev_device *parent_dev =
- udev_device_get_parent_with_subsystem_devtype(dev, "usb",
- "usb_device");
- if (!parent_dev)
- return;
-
- sysattr = udev_device_get_sysattr_value(parent_dev, "idVendor");
- if (sysattr)
- card_info->usb_vendor_id = strtol(sysattr, NULL, 16);
- sysattr = udev_device_get_sysattr_value(parent_dev, "idProduct");
- if (sysattr)
- card_info->usb_product_id = strtol(sysattr, NULL, 16);
- sysattr = udev_device_get_sysattr_value(parent_dev, "serial");
- if (sysattr) {
- strncpy(card_info->usb_serial_number, sysattr,
- USB_SERIAL_NUMBER_BUFFER_SIZE - 1);
- card_info->usb_serial_number[USB_SERIAL_NUMBER_BUFFER_SIZE - 1] =
- '\0';
- }
-
- card_info->usb_desc_checksum = calculate_desc_checksum(parent_dev);
-
- syslog(LOG_INFO,
- "USB card: vendor:%04x, product:%04x, serial num:%s, "
- "checksum:%08x",
- card_info->usb_vendor_id, card_info->usb_product_id,
- card_info->usb_serial_number, card_info->usb_desc_checksum);
-}
-
-static void device_add_alsa(struct udev_device *dev, const char *sysname,
- unsigned card, unsigned internal)
-{
- struct cras_alsa_card_info card_info;
- memset(&card_info, 0, sizeof(card_info));
-
- udev_delay_for_alsa();
- card_info.card_index = card;
- if (internal) {
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- } else {
- card_info.card_type = ALSA_CARD_TYPE_USB;
- fill_usb_card_info(&card_info, dev);
- }
-
- cras_system_add_alsa_card(&card_info);
-}
-
-void device_remove_alsa(const char *sysname, unsigned card)
-{
- udev_delay_for_alsa();
- cras_system_remove_alsa_card(card);
-}
-
-static int udev_sound_initialized(struct udev_device *dev)
-{
- /* udev will set SOUND_INITALIZED=1 for the main card node when the
- * system has already been initialized, i.e. when cras is restarted
- * on an already running system.
- */
- const char *s;
-
- s = udev_device_get_property_value(dev, "SOUND_INITIALIZED");
- if (s)
- return 1;
-
- return 0;
-}
-
-static void change_udev_device_if_alsa_device(struct udev_device *dev)
-{
- /* If the device, 'dev' is an alsa device, add it to the set of
- * devices available for I/O. Mark it as the active device.
- */
- unsigned internal;
- unsigned card_number;
- const char *sysname;
-
- if (is_card_device(dev, &internal, &card_number, &sysname) &&
- udev_sound_initialized(dev) &&
- !cras_system_alsa_card_exists(card_number)) {
- if (internal)
- set_factory_default(card_number);
- device_add_alsa(dev, sysname, card_number, internal);
- }
-}
-
-static void remove_device_if_card(struct udev_device *dev)
-{
- unsigned internal;
- unsigned card_number;
- const char *sysname;
-
- if (is_card_device(dev, &internal, &card_number, &sysname))
- device_remove_alsa(sysname, card_number);
-}
-
-static void enumerate_devices(struct udev_callback_data *data)
-{
- struct udev_enumerate *enumerate = udev_enumerate_new(data->udev);
- struct udev_list_entry *dl;
- struct udev_list_entry *dev_list_entry;
-
- udev_enumerate_add_match_subsystem(enumerate, subsystem);
- udev_enumerate_scan_devices(enumerate);
- dl = udev_enumerate_get_list_entry(enumerate);
-
- udev_list_entry_foreach(dev_list_entry, dl)
- {
- const char *path = udev_list_entry_get_name(dev_list_entry);
- struct udev_device *dev =
- udev_device_new_from_syspath(data->udev, path);
-
- change_udev_device_if_alsa_device(dev);
- udev_device_unref(dev);
- }
- udev_enumerate_unref(enumerate);
-}
-
-static void udev_sound_subsystem_callback(void *arg, int revents)
-{
- struct udev_callback_data *data = (struct udev_callback_data *)arg;
- struct udev_device *dev;
-
- dev = udev_monitor_receive_device(data->mon);
- if (dev) {
- const char *action = udev_device_get_action(dev);
-
- if (is_action_change(action))
- change_udev_device_if_alsa_device(dev);
- else if (is_action_remove(action))
- remove_device_if_card(dev);
- udev_device_unref(dev);
- } else
- syslog(LOG_WARNING,
- "%s (internal error): "
- "No device obtained",
- __FUNCTION__);
-}
-
-static void compile_regex(regex_t *regex, const char *str)
-{
- int r = regcomp(regex, str, REG_EXTENDED);
- assert(r == 0);
-}
-
-static struct udev_callback_data udev_data;
-void cras_udev_start_sound_subsystem_monitor()
-{
- int r;
-
- udev_data.udev = udev_new();
- assert(udev_data.udev != NULL);
- udev_data.mon = udev_monitor_new_from_netlink(udev_data.udev, "udev");
-
- udev_monitor_filter_add_match_subsystem_devtype(udev_data.mon,
- subsystem, NULL);
- udev_monitor_enable_receiving(udev_data.mon);
- udev_data.fd = udev_monitor_get_fd(udev_data.mon);
-
- r = cras_system_add_select_fd(udev_data.fd,
- udev_sound_subsystem_callback, &udev_data,
- POLLIN);
- assert(r == 0);
- compile_regex(&pcm_regex, pcm_regex_string);
- compile_regex(&card_regex, card_regex_string);
-
- enumerate_devices(&udev_data);
-}
-
-void cras_udev_stop_sound_subsystem_monitor()
-{
- udev_unref(udev_data.udev);
- regfree(&pcm_regex);
- regfree(&card_regex);
-}
diff --git a/cras/src/server/cras_udev.h b/cras/src/server/cras_udev.h
deleted file mode 100644
index 7a90ea7c..00000000
--- a/cras/src/server/cras_udev.h
+++ /dev/null
@@ -1,12 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_UDEV_H_
-#define CRAS_UDEV_H_
-
-void cras_udev_start_sound_subsystem_monitor();
-void cras_udev_stop_sound_subsystem_monitor();
-
-#endif /* CRAS_UDEV_H_ */
diff --git a/cras/src/server/cras_unified_rclient.c b/cras/src/server/cras_unified_rclient.c
deleted file mode 100644
index cdb7b47d..00000000
--- a/cras/src/server/cras_unified_rclient.c
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_iodev_list.h"
-#include "cras_messages.h"
-#include "cras_observer.h"
-#include "cras_rclient.h"
-#include "cras_rclient_util.h"
-#include "cras_rstream.h"
-#include "cras_types.h"
-#include "cras_util.h"
-
-/* Declarations of cras_rclient operators for cras_unified_rclient. */
-static const struct cras_rclient_ops cras_unified_rclient_ops = {
- .handle_message_from_client = rclient_handle_message_from_client,
- .send_message_to_client = rclient_send_message_to_client,
- .destroy = rclient_destroy,
-};
-
-/*
- * Exported Functions.
- */
-
-/* Creates a client structure and sends a message back informing the client that
- * the connection has succeeded. */
-struct cras_rclient *cras_unified_rclient_create(int fd, size_t id)
-{
- int supported_directions =
- cras_stream_direction_mask(CRAS_STREAM_OUTPUT) |
- cras_stream_direction_mask(CRAS_STREAM_INPUT);
- return rclient_generic_create(fd, id, &cras_unified_rclient_ops,
- supported_directions);
-}
diff --git a/cras/src/server/cras_unified_rclient.h b/cras/src/server/cras_unified_rclient.h
deleted file mode 100644
index 19973f88..00000000
--- a/cras/src/server/cras_unified_rclient.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_UNIFIED_RCLIENT_H_
-#define CRAS_UNIFIED_RCLIENT_H_
-
-struct cras_rclient;
-
-/* Creates a unified rclient structure. This client supports only playback
- * and capture functions but not control features.
- * Args:
- * fd - The file descriptor used for communication with the client.
- * id - Unique identifier for this client.
- * Returns:
- * A pointer to the newly created rclient on success, NULL on failure.
- */
-struct cras_rclient *cras_unified_rclient_create(int fd, size_t id);
-
-#endif /* CRAS_UNIFIED_RCLIENT_H_ */
diff --git a/cras/src/server/cras_utf8.c b/cras/src/server/cras_utf8.c
deleted file mode 100644
index ebb8a89a..00000000
--- a/cras/src/server/cras_utf8.c
+++ /dev/null
@@ -1,182 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#ifdef CRAS_DBUS
-#include <dbus/dbus.h>
-#endif
-
-#include "cras_utf8.h"
-#include "cras_util.h"
-
-static const uint8_t kUTF8ByteOrderMask[3] = { 0xef, 0xbb, 0xbf };
-
-typedef struct u8range {
- uint8_t min;
- uint8_t max;
-} u8range_t;
-
-static const u8range_t kUTF8TwoByteSeq[] = {
- { 0xc2, 0xdf },
- { 0x80, 0xbf },
- { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqE0[] = {
- { 0xe0, 0xe0 },
- { 0xa0, 0xbf },
- { 0x80, 0xbf },
- { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqE1EC[] = {
- { 0xe1, 0xec },
- { 0x80, 0xbf },
- { 0x80, 0xbf },
- { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqED[] = {
- { 0xed, 0xed },
- { 0x80, 0x9f },
- { 0x80, 0xbf },
- { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqEEEF[] = {
- { 0xee, 0xef },
- { 0x80, 0xbf },
- { 0x80, 0xbf },
- { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqF0[] = {
- { 0xf0, 0xf0 }, { 0x90, 0xbf }, { 0x80, 0xbf },
- { 0x80, 0xbf }, { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqF1F3[] = {
- { 0xf1, 0xf3 }, { 0x80, 0xbf }, { 0x80, 0xbf },
- { 0x80, 0xbf }, { 0, 0 },
-};
-
-static const u8range_t kUTF8ByteSeqF4[] = {
- { 0xf4, 0xf4 }, { 0x80, 0x8f }, { 0x80, 0xbf },
- { 0x80, 0xbf }, { 0, 0 },
-};
-
-static const u8range_t kUTF8NullRange[] = { { 0, 0 } };
-
-typedef struct utf8seq {
- const u8range_t *ranges;
-} utf8seq_t;
-
-static const utf8seq_t kUTF8Sequences[] = {
- { kUTF8TwoByteSeq }, { kUTF8ByteSeqE0 }, { kUTF8ByteSeqE1EC },
- { kUTF8ByteSeqED }, { kUTF8ByteSeqEEEF }, { kUTF8ByteSeqF0 },
- { kUTF8ByteSeqF1F3 }, { kUTF8ByteSeqF4 }, { kUTF8NullRange }
-};
-
-int valid_utf8_string(const char *string, size_t *bad_pos)
-{
- int bom_chars = 0;
- uint8_t byte;
- const char *pos = string;
- int ret = 1;
- const utf8seq_t *seq = NULL;
- const u8range_t *range = NULL;
-
- if (!pos) {
- ret = 0;
- goto error;
- }
-
- while ((byte = (uint8_t) * (pos++))) {
- if (!range || range->min == 0) {
- if (byte < 128) {
- /* Ascii character. */
- continue;
- }
-
- if (bom_chars < ARRAY_SIZE(kUTF8ByteOrderMask)) {
- if (byte == kUTF8ByteOrderMask[bom_chars]) {
- bom_chars++;
- continue;
- } else {
- /* Characters not matching BOM.
- * Rewind and assume that there is
- * no BOM. */
- bom_chars =
- ARRAY_SIZE(kUTF8ByteOrderMask);
- pos = string;
- continue;
- }
- }
-
- /* Find the matching sequence of characters by
- * matching the first character in the sequence.
- */
- seq = kUTF8Sequences;
- while (seq->ranges->min != 0) {
- if (byte >= seq->ranges->min &&
- byte <= seq->ranges->max) {
- /* Matching sequence. */
- break;
- }
- seq++;
- }
-
- if (seq->ranges->min == 0) {
- /* Could not find a matching sequence. */
- ret = 0;
- goto error;
- }
-
- /* Found the appropriate sequence. */
- range = seq->ranges + 1;
- continue;
- }
-
- if (byte >= range->min && byte <= range->max) {
- range++;
- continue;
- }
-
- /* This character doesn't belong in UTF8. */
- ret = 0;
- goto error;
- }
-
- if (range && range->min != 0) {
- /* Stopped in the middle of a sequence. */
- ret = 0;
- }
-
-error:
- if (bad_pos)
- *bad_pos = pos - string - 1;
- return ret;
-}
-
-#ifdef CRAS_DBUS
-/* Use the DBus implementation if available to ensure that the UTF-8
- * sequences match those expected by the DBus implementation. */
-
-int is_utf8_string(const char *string)
-{
- return !!dbus_validate_utf8(string, NULL);
-}
-
-#else
-
-int is_utf8_string(const char *string)
-{
- return valid_utf8_string(string, NULL);
-}
-
-#endif
diff --git a/cras/src/server/cras_utf8.h b/cras/src/server/cras_utf8.h
deleted file mode 100644
index b4625fbd..00000000
--- a/cras/src/server/cras_utf8.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <sys/types.h>
-
-/* Checks if a string is valid UTF-8.
- *
- * Supports 1 to 4 character UTF-8 sequences. Passes tests here:
- * https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
- *
- * Exceptions: The following unicode non-characters are allowed:
- * U+FFFE, U+FFFF, U+FDD0 - U+FDEF, U+nFFFE (n = 1 - 10),
- * U+nFFFD (n = 1 - 10).
- *
- * Args:
- * string[in] - a string.
- * bad_pos[out] - position of the first bad character.
- *
- * Returns:
- * 1 if it is a vlid utf-8 string. 0 otherwise.
- * bad_pos contains the strlen() of the string if it is
- * valid.
- */
-int valid_utf8_string(const char *string, size_t *bad_pos);
-
-/* Checks if a string is a valid utf-8 string.
- *
- * Args:
- * string[in] - a string.
- *
- * Returns:
- * 1 if it is a valid utf-8 string. 0 otherwise.
- */
-int is_utf8_string(const char *string);
diff --git a/cras/src/server/cras_volume_curve.c b/cras/src/server/cras_volume_curve.c
deleted file mode 100644
index a8661220..00000000
--- a/cras/src/server/cras_volume_curve.c
+++ /dev/null
@@ -1,80 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stddef.h>
-#include <stdlib.h>
-#include <sys/param.h>
-
-#include "cras_util.h"
-#include "cras_volume_curve.h"
-
-/* Simple curve with configurable max volume and volume step. */
-struct stepped_curve {
- struct cras_volume_curve curve;
- long max_vol;
- long step;
-};
-
-static long get_dBFS_step(const struct cras_volume_curve *curve, size_t volume)
-{
- const struct stepped_curve *c = (const struct stepped_curve *)curve;
- return c->max_vol - (c->step * (MAX_VOLUME - volume));
-}
-
-/* Curve that has each step explicitly called out by value. */
-struct explicit_curve {
- struct cras_volume_curve curve;
- long dB_values[NUM_VOLUME_STEPS];
-};
-
-static long get_dBFS_explicit(const struct cras_volume_curve *curve,
- size_t volume)
-{
- const struct explicit_curve *c = (const struct explicit_curve *)curve;
-
- /* Limit volume to (0, MAX_VOLUME). */
- volume = MIN(MAX_VOLUME, MAX(0, volume));
- return c->dB_values[volume];
-}
-
-/*
- * Exported Interface.
- */
-
-struct cras_volume_curve *cras_volume_curve_create_default()
-{
- /* Default to max volume of 0dBFS, and a step of 0.5dBFS. */
- return cras_volume_curve_create_simple_step(0, 50);
-}
-
-struct cras_volume_curve *cras_volume_curve_create_simple_step(long max_volume,
- long volume_step)
-{
- struct stepped_curve *curve;
- curve = (struct stepped_curve *)calloc(1, sizeof(*curve));
- if (curve == NULL)
- return NULL;
- curve->curve.get_dBFS = get_dBFS_step;
- curve->max_vol = max_volume;
- curve->step = volume_step;
- return &curve->curve;
-}
-
-struct cras_volume_curve *
-cras_volume_curve_create_explicit(long dB_values[NUM_VOLUME_STEPS])
-{
- struct explicit_curve *curve;
- curve = (struct explicit_curve *)calloc(1, sizeof(*curve));
- if (curve == NULL)
- return NULL;
- curve->curve.get_dBFS = get_dBFS_explicit;
- memcpy(curve->dB_values, dB_values, sizeof(curve->dB_values));
- return &curve->curve;
-}
-
-void cras_volume_curve_destroy(struct cras_volume_curve *curve)
-{
- free(curve);
-}
diff --git a/cras/src/server/cras_volume_curve.h b/cras/src/server/cras_volume_curve.h
deleted file mode 100644
index c3b0ee66..00000000
--- a/cras/src/server/cras_volume_curve.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_VOLUME_CURVE_H_
-#define CRAS_VOLUME_CURVE_H_
-
-#define MAX_VOLUME 100
-#define NUM_VOLUME_STEPS (MAX_VOLUME + 1) /* 0-100 inclusive. */
-
-/* Holds the function that converts from a volume index to a dBFS value. */
-struct cras_volume_curve {
- /* Function to convert from index to dBFS value.
- * Args:
- * curve - A curve from cras_volume_curve_create_* functions.
- * volume - The volume level from 0 to 100.
- * Returns:
- * The volume to apply in dB * 100. This value will normally be
- * negative and is means dB down from full scale.
- */
- long (*get_dBFS)(const struct cras_volume_curve *curve, size_t volume);
-};
-
-/* Creates a system-default volume curve. The default curve maps one volume step
- * to 1 dB down.
- * Returns null on error, or the new volume curve on success.
- */
-struct cras_volume_curve *cras_volume_curve_create_default();
-
-/* Creates a volume curve with a specified max volume and step.
- * Args:
- * max_volume - Maximum volume allowed in dBFS.
- * volume_step - Number of dB to change for one volume tick.
- */
-struct cras_volume_curve *
-cras_volume_curve_create_simple_step(long max_volume, long volume_step);
-
-/* Creates a volume curve with each step's dB value called out.
- * Args:
- * dB_values - Each element specifies what the volume should be set to (in
- * dB) for the volume at that index.
- * Returns:
- * A volume curve pointer that should be passed to
- * cras_volume_curve_destroy() when it is no longer needed. If there is an
- * error NULL will be returned.
- */
-struct cras_volume_curve *
-cras_volume_curve_create_explicit(long dB_values[101]);
-
-/* Destroys a curve created with cras_volume_curve_create_*.
- * Args:
- * curve - The curve to destroy.
- */
-void cras_volume_curve_destroy(struct cras_volume_curve *curve);
-
-#endif /* CRAS_VOLUME_CURVE_H_ */
diff --git a/cras/src/server/dev_io.c b/cras/src/server/dev_io.c
deleted file mode 100644
index b311b221..00000000
--- a/cras/src/server/dev_io.c
+++ /dev/null
@@ -1,1583 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <poll.h>
-#include <stdbool.h>
-#include <syslog.h>
-
-#include "audio_thread_log.h"
-#include "cras_audio_area.h"
-#include "cras_audio_thread_monitor.h"
-#include "cras_device_monitor.h"
-#include "cras_iodev.h"
-#include "cras_non_empty_audio_handler.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.h"
-#include "dev_stream.h"
-#include "input_data.h"
-#include "polled_interval_checker.h"
-#include "rate_estimator.h"
-#include "utlist.h"
-
-#include "dev_io.h"
-
-static const struct timespec playback_wake_fuzz_ts = {
- 0, 500 * 1000 /* 500 usec. */
-};
-
-/* The maximum time to wait before checking the device's non-empty status. */
-static const int NON_EMPTY_UPDATE_INTERVAL_SEC = 5;
-
-/*
- * The minimum number of consecutive seconds of empty audio that must be
- * played before a device is considered to be playing empty audio.
- */
-static const int MIN_EMPTY_PERIOD_SEC = 30;
-
-/*
- * When the hw_level is less than this time, do not drop frames.
- * (unit: millisecond).
- * TODO(yuhsuan): Reduce the threshold when we create the other overrun op for
- * boards which captures a lot of frames at one time.
- * e.g. Input devices on grunt reads 1024 frames each time.
- */
-static const int DROP_FRAMES_THRESHOLD_MS = 50;
-
-/* The number of devices playing/capturing non-empty stream(s). */
-static int non_empty_device_count = 0;
-
-/* The timestamp of last EIO error time. */
-static struct timespec last_io_err_time = { 0, 0 };
-
-/* The gap time to avoid repeated error close request to main thread. */
-static const int ERROR_CLOSE_GAP_TIME_SECS = 10;
-
-/* Gets the main device which the stream is attached to. */
-static inline struct cras_iodev *get_main_dev(const struct dev_stream *stream)
-{
- return (struct cras_iodev *)stream->stream->main_dev.dev_ptr;
-}
-
-/* Updates the estimated sample rate of open device to all attached
- * streams.
- */
-static void update_estimated_rate(struct open_dev *adev,
- struct open_dev *odev_list,
- bool self_rate_need_update)
-{
- struct cras_iodev *main_dev;
- struct cras_iodev *dev = adev->dev;
- struct cras_iodev *tracked_dev = NULL;
- struct dev_stream *dev_stream;
- double dev_rate_ratio;
- double main_dev_rate_ratio;
-
- /*
- * If there is an output device on the same sound card running with the same
- * sampling rate, use the rate of that output device for this device.
- */
- if (dev->direction == CRAS_STREAM_INPUT &&
- cras_iodev_is_on_internal_card(dev->active_node)) {
- struct open_dev *odev;
- DL_FOREACH (odev_list, odev) {
- if (!cras_iodev_is_on_internal_card(
- odev->dev->active_node))
- continue;
- if (odev->dev->format->frame_rate !=
- dev->format->frame_rate)
- continue;
- tracked_dev = odev->dev;
- break;
- }
- }
-
- /*
- * Self-owned rate esimator does not need to udpate rate. There is no tracked
- * output device. So there is no need to update.
- */
- if (!self_rate_need_update && !tracked_dev)
- return;
-
- DL_FOREACH (dev->streams, dev_stream) {
- main_dev = get_main_dev(dev_stream);
- if (main_dev == NULL) {
- syslog(LOG_ERR, "Fail to find main open dev.");
- continue;
- }
-
- if (tracked_dev) {
- dev_rate_ratio =
- cras_iodev_get_est_rate_ratio(tracked_dev);
- main_dev_rate_ratio = dev_rate_ratio;
- } else {
- dev_rate_ratio = cras_iodev_get_est_rate_ratio(dev);
- main_dev_rate_ratio =
- cras_iodev_get_est_rate_ratio(main_dev);
- }
-
- dev_stream_set_dev_rate(dev_stream, dev->format->frame_rate,
- dev_rate_ratio, main_dev_rate_ratio,
- adev->coarse_rate_adjust);
- }
-}
-
-/*
- * Counts the number of devices which are currently playing/capturing non-empty
- * audio.
- */
-static inline int count_non_empty_dev(struct open_dev *adevs)
-{
- int count = 0;
- struct open_dev *adev;
- DL_FOREACH (adevs, adev) {
- if (!adev->empty_pi || !pic_interval_elapsed(adev->empty_pi))
- count++;
- }
- return count;
-}
-
-int dev_io_check_non_empty_state_transition(struct open_dev *adevs)
-{
- int new_non_empty_dev_count = count_non_empty_dev(adevs);
-
- // If we have transitioned to or from a state with 0 non-empty devices,
- // notify the main thread to update system state.
- if ((non_empty_device_count == 0) != (new_non_empty_dev_count == 0))
- cras_non_empty_audio_send_msg(new_non_empty_dev_count > 0 ? 1 :
- 0);
-
- non_empty_device_count = new_non_empty_dev_count;
- return non_empty_device_count > 0;
-}
-
-/* Checks whether it is time to fetch. */
-static bool is_time_to_fetch(const struct dev_stream *dev_stream,
- struct timespec now)
-{
- const struct timespec *next_cb_ts;
- next_cb_ts = dev_stream_next_cb_ts(dev_stream);
- if (!next_cb_ts)
- return 0;
-
- /*
- * Check if it's time to get more data from this stream.
- * Allow for waking up a little early.
- */
- add_timespecs(&now, &playback_wake_fuzz_ts);
- if (timespec_after(&now, next_cb_ts))
- return 1;
-
- return 0;
-}
-
-/* The log only accepts uint32 arguments, so the float power
- * must be written as bits and assumed to have a float when
- * parsing the log.
- */
-static uint32_t get_ewma_power_as_int(struct ewma_power *ewma)
-{
- uint32_t pow_as_int = 0;
-
- if (sizeof(uint32_t) == sizeof(float))
- memcpy(&pow_as_int, &ewma->power, sizeof(uint32_t));
- return pow_as_int;
-}
-
-/* Asks any stream with room for more data. Sets the time stamp for all streams.
- * Args:
- * adev - The output device streams are attached to.
- * Returns:
- * 0 on success, negative error on failure. If failed, can assume that all
- * streams have been removed from the device.
- */
-static int fetch_streams(struct open_dev *adev)
-{
- struct dev_stream *dev_stream;
- struct cras_iodev *odev = adev->dev;
- int rc;
- int delay;
-
- delay = cras_iodev_delay_frames(odev);
- if (delay < 0)
- return delay;
-
- DL_FOREACH (adev->dev->streams, dev_stream) {
- struct cras_rstream *rstream = dev_stream->stream;
- struct cras_audio_shm *shm = cras_rstream_shm(rstream);
- struct timespec now;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- if (dev_stream_is_pending_reply(dev_stream)) {
- dev_stream_flush_old_audio_messages(dev_stream);
- cras_rstream_record_fetch_interval(dev_stream->stream,
- &now);
- }
-
- if (!dev_stream_is_running(dev_stream))
- continue;
-
- if (!is_time_to_fetch(dev_stream, now))
- continue;
-
- if (cras_shm_get_frames(shm) < 0)
- cras_rstream_set_is_draining(rstream, 1);
-
- if (cras_rstream_get_is_draining(dev_stream->stream))
- continue;
-
- /*
- * Skip fetching if client still has not replied yet.
- */
- if (cras_rstream_is_pending_reply(rstream)) {
- ATLOG(atlog, AUDIO_THREAD_STREAM_FETCH_PENDING,
- cras_rstream_id(rstream), 0, 0);
- continue;
- }
-
- /*
- * Skip fetching if there are enough frames in shared memory.
- */
- if (!cras_shm_is_buffer_available(shm)) {
- ATLOG(atlog, AUDIO_THREAD_STREAM_SKIP_CB,
- cras_rstream_id(rstream),
- shm->header->write_offset[0],
- shm->header->write_offset[1]);
- dev_stream_update_next_wake_time(dev_stream);
- cras_server_metrics_missed_cb_event(dev_stream->stream);
- continue;
- }
-
- dev_stream_set_delay(dev_stream, delay);
-
- ATLOG(atlog, AUDIO_THREAD_FETCH_STREAM, rstream->stream_id,
- cras_rstream_get_cb_threshold(rstream),
- get_ewma_power_as_int(&rstream->ewma));
-
- rc = dev_stream_request_playback_samples(dev_stream, &now);
- if (rc < 0) {
- syslog(LOG_ERR, "fetch err: %d for %x", rc,
- cras_rstream_id(rstream));
- cras_rstream_set_is_draining(rstream, 1);
- }
- }
-
- return 0;
-}
-
-/* Gets the max delay frames of open input devices. */
-static int input_delay_frames(struct open_dev *adevs)
-{
- struct open_dev *adev;
- int delay;
- int max_delay = 0;
-
- DL_FOREACH (adevs, adev) {
- if (!cras_iodev_is_open(adev->dev))
- continue;
- delay = cras_iodev_delay_frames(adev->dev);
- if (delay < 0)
- return delay;
- if (delay > max_delay)
- max_delay = delay;
- }
- return max_delay;
-}
-
-/* Sets the stream delay.
- * Args:
- * adev[in] - The device to capture from.
- */
-static unsigned int set_stream_delay(struct open_dev *adev)
-{
- struct dev_stream *stream;
- int delay;
-
- /* TODO(dgreid) - Setting delay from last dev only. */
- delay = input_delay_frames(adev);
-
- DL_FOREACH (adev->dev->streams, stream) {
- if (stream->stream->flags & TRIGGER_ONLY)
- continue;
-
- dev_stream_set_delay(stream, delay);
- }
-
- return 0;
-}
-
-/* Gets the minimum amount of space available for writing across all streams.
- * Args:
- * adev[in] - The device to capture from.
- * write_limit[in] - Initial limit to number of frames to capture.
- * limit_stream[out] - The pointer to the pointer of stream which
- * causes capture limit.
- * Output NULL if there is no stream that causes
- * capture limit less than the initial limit.
- */
-static unsigned int get_stream_limit(struct open_dev *adev,
- unsigned int write_limit,
- struct dev_stream **limit_stream)
-{
- struct cras_rstream *rstream;
- struct cras_audio_shm *shm;
- struct dev_stream *stream;
- unsigned int avail;
-
- *limit_stream = NULL;
-
- DL_FOREACH (adev->dev->streams, stream) {
- rstream = stream->stream;
- if (rstream->flags & TRIGGER_ONLY)
- continue;
-
- shm = cras_rstream_shm(rstream);
- if (cras_shm_check_write_overrun(shm))
- ATLOG(atlog, AUDIO_THREAD_READ_OVERRUN,
- adev->dev->info.idx, rstream->stream_id,
- shm->header->num_overruns);
- avail = dev_stream_capture_avail(stream);
- if (avail < write_limit) {
- write_limit = avail;
- *limit_stream = stream;
- }
- }
-
- return write_limit;
-}
-
-/*
- * The minimum wake time for a input device, which is 5ms. It's only used by
- * function get_input_dev_max_wake_ts.
- */
-static const struct timespec min_input_dev_wake_ts = {
- 0, 5 * 1000 * 1000 /* 5 ms. */
-};
-
-/*
- * Get input device maximum sleep time, which is the approximate time that the
- * device will have hw_level = buffer_size / 2 samples. Some devices have
- * capture period = 2 so the audio_thread should wake up and consume some
- * samples from hardware at that time. To prevent busy loop occurs, the returned
- * sleep time should be >= 5ms.
- *
- * Returns: 0 on success negative error on device failure.
- */
-static int get_input_dev_max_wake_ts(struct open_dev *adev,
- unsigned int curr_level,
- struct timespec *res_ts)
-{
- struct timespec dev_wake_ts, now;
- unsigned int dev_rate, half_buffer_size, target_frames;
-
- if (!adev || !adev->dev || !adev->dev->format ||
- !adev->dev->format->frame_rate || !adev->dev->buffer_size)
- return -EINVAL;
-
- *res_ts = min_input_dev_wake_ts;
-
- dev_rate = adev->dev->format->frame_rate;
- half_buffer_size = adev->dev->buffer_size / 2;
- if (curr_level < half_buffer_size)
- target_frames = half_buffer_size - curr_level;
- else
- target_frames = 0;
-
- cras_frames_to_time(target_frames, dev_rate, &dev_wake_ts);
-
- if (timespec_after(&dev_wake_ts, res_ts)) {
- *res_ts = dev_wake_ts;
- }
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- add_timespecs(res_ts, &now);
- return 0;
-}
-
-/* Returns whether a device can drop samples. */
-static bool input_devices_can_drop_samples(struct cras_iodev *iodev)
-{
- if (!cras_iodev_is_open(iodev))
- return false;
- if (!iodev->streams)
- return false;
- if (!iodev->active_node ||
- iodev->active_node->type == CRAS_NODE_TYPE_HOTWORD ||
- iodev->active_node->type == CRAS_NODE_TYPE_POST_MIX_PRE_DSP ||
- iodev->active_node->type == CRAS_NODE_TYPE_POST_DSP)
- return false;
- return true;
-}
-
-/*
- * Set wake_ts for this device to be the earliest wake up time for
- * dev_streams. Default value for adev->wake_ts will be now + 20s even if
- * any error occurs in this function.
- * Args:
- * adev - The input device.
- * need_to_drop - The pointer to store whether we need to drop samples from
- * a device in order to keep the lower hw_level.
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-static int set_input_dev_wake_ts(struct open_dev *adev, bool *need_to_drop)
-{
- int rc;
- struct timespec level_tstamp, wake_time_out, min_ts, now, dev_wake_ts;
- unsigned int curr_level, cap_limit;
- struct dev_stream *stream;
- struct dev_stream *cap_limit_stream;
-
- /* Limit the sleep time to 20 seconds. */
- min_ts.tv_sec = 20;
- min_ts.tv_nsec = 0;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- add_timespecs(&min_ts, &now);
- /* Set default value for device wake_ts. */
- adev->wake_ts = min_ts;
-
- rc = cras_iodev_frames_queued(adev->dev, &level_tstamp);
- if (rc < 0)
- return rc;
- curr_level = rc;
- if (!timespec_is_nonzero(&level_tstamp))
- clock_gettime(CLOCK_MONOTONIC_RAW, &level_tstamp);
-
- /*
- * Drop frames from all devices if any device meets these requirements:
- * 1. The hw_level is larger than largest_cb_level * 1.5 or larger than
- * buffer_size * 0.5.
- * 2. The time of those frames is larger than DROP_FRAMES_THRESHOLD_MS.
- */
- if (input_devices_can_drop_samples(adev->dev) &&
- (rc >= adev->dev->largest_cb_level * 1.5 ||
- rc >= adev->dev->buffer_size * 0.5) &&
- cras_frames_to_ms(rc, adev->dev->format->frame_rate) >=
- DROP_FRAMES_THRESHOLD_MS)
- *need_to_drop = true;
-
- cap_limit = get_stream_limit(adev, UINT_MAX, &cap_limit_stream);
-
- /*
- * Loop through streams to find the earliest time audio thread
- * should wake up.
- */
- DL_FOREACH (adev->dev->streams, stream) {
- wake_time_out = min_ts;
- rc = dev_stream_wake_time(stream, curr_level, &level_tstamp,
- cap_limit, cap_limit_stream == stream,
- &wake_time_out);
-
- /*
- * rc > 0 means there is no need to set wake up time for this
- * stream.
- */
- if (rc > 0)
- continue;
-
- if (rc < 0)
- return rc;
-
- if (timespec_after(&min_ts, &wake_time_out)) {
- min_ts = wake_time_out;
- }
- }
-
- /* If there's no room in streams, don't bother schedule wake for more
- * input data. */
- if (adev->dev->active_node &&
- adev->dev->active_node->type != CRAS_NODE_TYPE_HOTWORD &&
- cap_limit) {
- rc = get_input_dev_max_wake_ts(adev, curr_level, &dev_wake_ts);
- if (rc < 0) {
- syslog(LOG_ERR,
- "Failed to call get_input_dev_max_wake_ts."
- "rc = %d",
- rc);
- } else if (timespec_after(&min_ts, &dev_wake_ts)) {
- min_ts = dev_wake_ts;
- }
- }
-
- adev->wake_ts = min_ts;
- return rc;
-}
-
-/* Read samples from an input device to the specified stream.
- * Args:
- * adev - The device to capture samples from.
- * Returns 0 on success.
- */
-static int capture_to_streams(struct open_dev *adev, struct open_dev *odev_list)
-{
- struct cras_iodev *idev = adev->dev;
- snd_pcm_uframes_t remainder, hw_level, cap_limit;
- struct timespec hw_tstamp;
- int rc;
- struct dev_stream *cap_limit_stream;
- struct dev_stream *stream;
-
- DL_FOREACH (adev->dev->streams, stream)
- dev_stream_flush_old_audio_messages(stream);
-
- rc = cras_iodev_frames_queued(idev, &hw_tstamp);
- if (rc < 0)
- return rc;
- hw_level = rc;
-
- cras_iodev_update_highest_hw_level(idev, hw_level);
-
- ATLOG(atlog, AUDIO_THREAD_READ_AUDIO_TSTAMP, idev->info.idx,
- hw_tstamp.tv_sec, hw_tstamp.tv_nsec);
- if (timespec_is_nonzero(&hw_tstamp)) {
- bool self_rate_need_update;
-
- if (hw_level < idev->min_cb_level / 2)
- adev->coarse_rate_adjust = 1;
- else if (hw_level > idev->max_cb_level * 2)
- adev->coarse_rate_adjust = -1;
- else
- adev->coarse_rate_adjust = 0;
-
- /*
- * This values means whether the rate estimator in the device
- * wants to update estimated rate.
- */
- self_rate_need_update =
- !!cras_iodev_update_rate(idev, hw_level, &hw_tstamp);
-
- /*
- * Always calls update_estimated_rate so that new output rate
- * has a chance to propagate to input. In update_estimated_rate,
- * it will decide whether the new rate is from self rate estimator
- * or from the tracked output device.
- */
- update_estimated_rate(adev, odev_list, self_rate_need_update);
- }
-
- cap_limit = get_stream_limit(adev, hw_level, &cap_limit_stream);
- set_stream_delay(adev);
-
- remainder = MIN(hw_level, cap_limit);
-
- ATLOG(atlog, AUDIO_THREAD_READ_AUDIO, idev->info.idx, hw_level,
- remainder);
-
- if (cras_iodev_state(idev) != CRAS_IODEV_STATE_NORMAL_RUN)
- return 0;
-
- while (remainder > 0) {
- struct cras_audio_area *area = NULL;
- unsigned int nread, total_read;
-
- nread = remainder;
-
- rc = cras_iodev_get_input_buffer(idev, &nread);
- if (rc < 0 || nread == 0)
- return rc;
-
- DL_FOREACH (adev->dev->streams, stream) {
- unsigned int this_read;
- unsigned int area_offset;
- float software_gain_scaler;
-
- if ((stream->stream->flags & TRIGGER_ONLY) &&
- stream->stream->triggered)
- continue;
-
- input_data_get_for_stream(idev->input_data,
- stream->stream,
- idev->buf_state, &area,
- &area_offset);
-
- /*
- * The UI gain scaler should always take effect.
- * input_data will decide if stream and iodev internal
- * software gains should be used or not, based on use
- * case.
- */
- software_gain_scaler =
- cras_iodev_get_ui_gain_scaler(idev) *
- input_data_get_software_gain_scaler(
- idev->input_data,
- idev->software_gain_scaler,
- stream->stream);
-
- this_read =
- dev_stream_capture(stream, area, area_offset,
- software_gain_scaler);
-
- input_data_put_for_stream(idev->input_data,
- stream->stream,
- idev->buf_state, this_read);
- }
-
- rc = cras_iodev_put_input_buffer(idev);
- if (rc < 0)
- return rc;
-
- total_read = rc;
- remainder -= nread;
-
- if (total_read < nread)
- break;
- }
-
- ATLOG(atlog, AUDIO_THREAD_READ_AUDIO_DONE, remainder,
- get_ewma_power_as_int(&idev->ewma), 0);
-
- return 0;
-}
-
-/* Fill the buffer with samples from the attached streams.
- * Args:
- * odevs - The list of open output devices, provided so streams can be
- * removed from all devices on error.
- * adev - The device to write to.
- * dst - The buffer to put the samples in (returned from snd_pcm_mmap_begin)
- * write_limit - The maximum number of frames to write to dst.
- *
- * Returns:
- * The number of frames rendered on success.
- * This number of frames is the minimum of the amount of frames each stream
- * could provide which is the maximum that can currently be rendered.
- */
-static unsigned int write_streams(struct open_dev **odevs,
- struct open_dev *adev, uint8_t *dst,
- size_t write_limit)
-{
- struct cras_iodev *odev = adev->dev;
- struct dev_stream *curr;
- unsigned int max_offset = 0;
- unsigned int frame_bytes = cras_get_format_bytes(odev->format);
- unsigned int num_playing = 0;
- unsigned int drain_limit = write_limit;
-
- /* Mix as much as we can, the minimum fill level of any stream. */
- max_offset = cras_iodev_max_stream_offset(odev);
-
- /* Mix as much as we can, the minimum fill level of any stream. */
- DL_FOREACH (adev->dev->streams, curr) {
- int dev_frames;
-
- /* Skip stream which hasn't started running yet. */
- if (!dev_stream_is_running(curr))
- continue;
-
- /* If this is a single output dev stream, updates the latest
- * number of frames for playback. */
- if (dev_stream_attached_devs(curr) == 1)
- dev_stream_update_frames(curr);
-
- dev_frames = dev_stream_playback_frames(curr);
- if (dev_frames < 0) {
- dev_io_remove_stream(odevs, curr->stream, NULL);
- continue;
- }
- ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_STREAM,
- curr->stream->stream_id, dev_frames,
- dev_stream_is_pending_reply(curr));
- if (cras_rstream_get_is_draining(curr->stream)) {
- drain_limit = MIN((size_t)dev_frames, drain_limit);
- if (!dev_frames)
- dev_io_remove_stream(odevs, curr->stream, NULL);
- } else {
- write_limit = MIN((size_t)dev_frames, write_limit);
- num_playing++;
- }
- }
-
- if (!num_playing)
- write_limit = drain_limit;
-
- if (write_limit > max_offset)
- memset(dst + max_offset * frame_bytes, 0,
- (write_limit - max_offset) * frame_bytes);
-
- ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_MIX, write_limit, max_offset,
- 0);
-
- DL_FOREACH (adev->dev->streams, curr) {
- unsigned int offset;
- int nwritten;
-
- if (!dev_stream_is_running(curr))
- continue;
-
- offset = cras_iodev_stream_offset(odev, curr);
- if (offset >= write_limit)
- continue;
- nwritten = dev_stream_mix(curr, odev->format,
- dst + frame_bytes * offset,
- write_limit - offset);
-
- if (nwritten < 0) {
- dev_io_remove_stream(odevs, curr->stream, NULL);
- continue;
- }
-
- cras_iodev_stream_written(odev, curr, nwritten);
- }
-
- write_limit = cras_iodev_all_streams_written(odev);
-
- ATLOG(atlog, AUDIO_THREAD_WRITE_STREAMS_MIXED, write_limit, 0, 0);
-
- return write_limit;
-}
-
-/* Update next wake up time of the device.
- * Args:
- * adev[in] - The device to update to.
- * hw_level[out] - Pointer to number of frames in hardware.
- */
-void update_dev_wakeup_time(struct open_dev *adev, unsigned int *hw_level)
-{
- struct timespec now;
- struct timespec sleep_time;
- double est_rate;
- unsigned int frames_to_play_in_sleep;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- frames_to_play_in_sleep = cras_iodev_frames_to_play_in_sleep(
- adev->dev, hw_level, &adev->wake_ts);
- if (!timespec_is_nonzero(&adev->wake_ts))
- adev->wake_ts = now;
-
- if (cras_iodev_state(adev->dev) == CRAS_IODEV_STATE_NORMAL_RUN)
- cras_iodev_update_highest_hw_level(adev->dev, *hw_level);
-
- est_rate = adev->dev->format->frame_rate *
- cras_iodev_get_est_rate_ratio(adev->dev);
-
- ATLOG(atlog, AUDIO_THREAD_SET_DEV_WAKE, adev->dev->info.idx, *hw_level,
- frames_to_play_in_sleep);
-
- cras_frames_to_time_precise(frames_to_play_in_sleep, est_rate,
- &sleep_time);
-
- add_timespecs(&adev->wake_ts, &sleep_time);
-
- ATLOG(atlog, AUDIO_THREAD_DEV_SLEEP_TIME, adev->dev->info.idx,
- adev->wake_ts.tv_sec, adev->wake_ts.tv_nsec);
-}
-
-/* Returns 0 on success negative error on device failure. */
-int write_output_samples(struct open_dev **odevs, struct open_dev *adev,
- struct cras_fmt_conv *output_converter)
-{
- struct cras_iodev *odev = adev->dev;
- unsigned int hw_level;
- struct timespec hw_tstamp;
- unsigned int frames, fr_to_req;
- snd_pcm_sframes_t written;
- snd_pcm_uframes_t total_written = 0;
- int rc;
- int non_empty = 0;
- int *non_empty_ptr = NULL;
- uint8_t *dst = NULL;
- struct cras_audio_area *area = NULL;
-
- /* Possibly fill zeros for no_stream state and possibly transit state.
- */
- rc = cras_iodev_prepare_output_before_write_samples(odev);
- if (rc < 0) {
- syslog(LOG_ERR, "Failed to prepare output dev for write");
- return rc;
- }
-
- if (cras_iodev_state(odev) != CRAS_IODEV_STATE_NORMAL_RUN)
- return 0;
-
- rc = cras_iodev_frames_queued(odev, &hw_tstamp);
- if (rc < 0)
- return rc;
- hw_level = rc;
-
- ATLOG(atlog, AUDIO_THREAD_FILL_AUDIO_TSTAMP, adev->dev->info.idx,
- hw_tstamp.tv_sec, hw_tstamp.tv_nsec);
- if (timespec_is_nonzero(&hw_tstamp)) {
- if (hw_level < odev->min_cb_level / 2)
- adev->coarse_rate_adjust = 1;
- else if (hw_level > odev->max_cb_level * 2)
- adev->coarse_rate_adjust = -1;
- else
- adev->coarse_rate_adjust = 0;
-
- if (cras_iodev_update_rate(odev, hw_level, &hw_tstamp))
- update_estimated_rate(adev, NULL, true);
- }
- ATLOG(atlog, AUDIO_THREAD_FILL_AUDIO, adev->dev->info.idx, hw_level,
- odev->min_cb_level);
-
- /* Don't request more than hardware can hold. Note that min_buffer_level
- * has been subtracted from the actual hw_level so we need to take it
- * into account here. */
- fr_to_req = cras_iodev_buffer_avail(odev, hw_level);
-
- /* Have to loop writing to the device, will be at most 2 loops, this
- * only happens when the circular buffer is at the end and returns us a
- * partial area to write to from mmap_begin */
- while (total_written < fr_to_req) {
- frames = fr_to_req - total_written;
- rc = cras_iodev_get_output_buffer(odev, &area, &frames);
- if (rc < 0)
- return rc;
-
- /* TODO(dgreid) - This assumes interleaved audio. */
- dst = area->channels[0].buf;
- written = write_streams(odevs, adev, dst, frames);
- if (written < (snd_pcm_sframes_t)frames)
- /* Got all the samples from client that we can, but it
- * won't fill the request. */
- fr_to_req = 0; /* break out after committing samples */
-
- // This interval is lazily initialized once per device.
- // Note that newly opened devices are considered non-empty
- // (until their status is updated through the normal flow).
- if (!adev->non_empty_check_pi) {
- adev->non_empty_check_pi = pic_polled_interval_create(
- NON_EMPTY_UPDATE_INTERVAL_SEC);
- }
-
- // If we were empty last iteration, or the sampling interval
- // has elapsed, check for emptiness.
- if (adev->empty_pi ||
- pic_interval_elapsed(adev->non_empty_check_pi)) {
- non_empty_ptr = &non_empty;
- pic_interval_reset(adev->non_empty_check_pi);
- }
-
- rc = cras_iodev_put_output_buffer(
- odev, dst, written, non_empty_ptr, output_converter);
-
- if (rc < 0)
- return rc;
- total_written += written;
-
- if (non_empty && adev->empty_pi) {
- // We're not empty, but we were previously.
- // Reset the empty period.
- pic_polled_interval_destroy(&adev->empty_pi);
- }
-
- if (non_empty_ptr && !non_empty && !adev->empty_pi)
- // We checked for emptiness, we were empty, and we
- // previously weren't. Start the empty period.
- adev->empty_pi = pic_polled_interval_create(
- MIN_EMPTY_PERIOD_SEC);
- }
-
- ATLOG(atlog, AUDIO_THREAD_FILL_AUDIO_DONE, hw_level, total_written,
- get_ewma_power_as_int(&odev->ewma));
-
- return total_written;
-}
-
-/*
- * Chooses the smallest difference between hw_level and min_cb_level as the
- * drop time.
- */
-static void get_input_devices_drop_time(struct open_dev *idev_list,
- struct timespec *reset_ts)
-{
- struct open_dev *adev;
- struct cras_iodev *iodev;
- struct timespec tmp;
- struct timespec hw_tstamp;
- double est_rate;
- unsigned int target_level;
- bool is_set = false;
- int rc;
-
- DL_FOREACH (idev_list, adev) {
- iodev = adev->dev;
- if (!input_devices_can_drop_samples(iodev))
- continue;
-
- rc = cras_iodev_frames_queued(iodev, &hw_tstamp);
- if (rc < 0) {
- syslog(LOG_ERR, "Get frames from device %d, rc = %d",
- iodev->info.idx, rc);
- continue;
- }
-
- target_level = iodev->min_cb_level;
- if (rc <= target_level) {
- reset_ts->tv_sec = 0;
- reset_ts->tv_nsec = 0;
- return;
- }
- est_rate = iodev->format->frame_rate *
- cras_iodev_get_est_rate_ratio(iodev);
- cras_frames_to_time(rc - target_level, est_rate, &tmp);
-
- if (!is_set || timespec_after(reset_ts, &tmp)) {
- *reset_ts = tmp;
- is_set = true;
- }
- }
-}
-
-/*
- * Drop samples from all input devices.
- */
-static void dev_io_drop_samples(struct open_dev *idev_list)
-{
- struct open_dev *adev;
- struct timespec drop_time = {};
- int rc;
-
- get_input_devices_drop_time(idev_list, &drop_time);
- ATLOG(atlog, AUDIO_THREAD_CAPTURE_DROP_TIME, drop_time.tv_sec,
- drop_time.tv_nsec, 0);
-
- if (timespec_is_zero(&drop_time))
- return;
-
- DL_FOREACH (idev_list, adev) {
- if (!input_devices_can_drop_samples(adev->dev))
- continue;
-
- rc = cras_iodev_drop_frames_by_time(adev->dev, drop_time);
- if (rc < 0) {
- syslog(LOG_ERR,
- "Failed to drop frames from device %d, rc = %d",
- adev->dev->info.idx, rc);
- continue;
- }
- }
-
- cras_audio_thread_event_drop_samples();
-
- return;
-}
-
-/*
- * Public funcitons.
- */
-
-int dev_io_send_captured_samples(struct open_dev *idev_list)
-{
- struct open_dev *adev;
- bool need_to_drop = false;
- int rc;
-
- // TODO(dgreid) - once per rstream, not once per dev_stream.
- DL_FOREACH (idev_list, adev) {
- struct dev_stream *stream;
-
- if (!cras_iodev_is_open(adev->dev))
- continue;
-
- /* Post samples to rstream if there are enough samples. */
- DL_FOREACH (adev->dev->streams, stream) {
- dev_stream_capture_update_rstream(stream);
- }
-
- /* Set wake_ts for this device. */
- rc = set_input_dev_wake_ts(adev, &need_to_drop);
- if (rc < 0)
- return rc;
- }
-
- if (need_to_drop)
- dev_io_drop_samples(idev_list);
-
- return 0;
-}
-
-static void handle_dev_err(int err_rc, struct open_dev **odevs,
- struct open_dev *adev)
-{
- struct timespec diff, now;
- if (err_rc == -EPIPE) {
- /* Handle severe underrun. */
- ATLOG(atlog, AUDIO_THREAD_SEVERE_UNDERRUN, adev->dev->info.idx,
- 0, 0);
- cras_iodev_reset_request(adev->dev);
- cras_audio_thread_event_severe_underrun();
- } else if (err_rc == -EIO) {
- syslog(LOG_WARNING, "I/O err, reseting %s dev %s",
- adev->dev->direction == CRAS_STREAM_OUTPUT ? "output" :
- "input",
- adev->dev->info.name);
- clock_gettime(CLOCK_REALTIME, &now);
- subtract_timespecs(&now, &last_io_err_time, &diff);
- if ((last_io_err_time.tv_sec == 0 &&
- last_io_err_time.tv_nsec == 0) ||
- diff.tv_sec > ERROR_CLOSE_GAP_TIME_SECS)
- cras_iodev_reset_request(adev->dev);
- else
- cras_device_monitor_error_close(adev->dev->info.idx);
-
- last_io_err_time = now;
- } else {
- syslog(LOG_ERR, "Dev %s err %d", adev->dev->info.name, err_rc);
- }
- /* Device error, remove it. */
- dev_io_rm_open_dev(odevs, adev);
-}
-
-int dev_io_capture(struct open_dev **list, struct open_dev **olist)
-{
- struct open_dev *idev_list = *list;
- struct open_dev *odev_list = *olist;
- struct open_dev *adev;
- int rc;
-
- DL_FOREACH (idev_list, adev) {
- if (!cras_iodev_is_open(adev->dev))
- continue;
- rc = capture_to_streams(adev, odev_list);
- if (rc < 0)
- handle_dev_err(rc, list, adev);
- }
-
- return 0;
-}
-
-/* If it is the time to fetch, start dev_stream. */
-static void dev_io_check_dev_stream_start(struct open_dev *adev)
-{
- struct dev_stream *dev_stream;
- struct timespec now;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-
- DL_FOREACH (adev->dev->streams, dev_stream) {
- if (!is_time_to_fetch(dev_stream, now))
- continue;
- if (!dev_stream_is_running(dev_stream))
- cras_iodev_start_stream(adev->dev, dev_stream);
- }
-}
-
-void dev_io_playback_fetch(struct open_dev *odev_list)
-{
- struct open_dev *adev;
-
- /* Check whether it is the time to start dev_stream before fetching. */
- DL_FOREACH (odev_list, adev) {
- if (!cras_iodev_is_open(adev->dev))
- continue;
- dev_io_check_dev_stream_start(adev);
- }
-
- DL_FOREACH (odev_list, adev) {
- if (!cras_iodev_is_open(adev->dev))
- continue;
- fetch_streams(adev);
- }
-}
-
-int dev_io_playback_write(struct open_dev **odevs,
- struct cras_fmt_conv *output_converter)
-{
- struct open_dev *adev;
- struct dev_stream *curr;
- int rc;
- unsigned int hw_level, total_written;
-
- /* For multiple output case, update the number of queued frames in shm
- * of all streams before starting write output samples. */
- adev = *odevs;
- if (adev && adev->next) {
- DL_FOREACH (*odevs, adev) {
- DL_FOREACH (adev->dev->streams, curr)
- dev_stream_update_frames(curr);
- }
- }
-
- DL_FOREACH (*odevs, adev) {
- if (!cras_iodev_is_open(adev->dev))
- continue;
-
- rc = write_output_samples(odevs, adev, output_converter);
- if (rc < 0) {
- handle_dev_err(rc, odevs, adev);
- } else {
- total_written = rc;
-
- /*
- * Skip the underrun check and device wake up time update if
- * device should not wake up.
- */
- if (!cras_iodev_odev_should_wake(adev->dev))
- continue;
-
- /*
- * Update device wake up time and get the new hardware
- * level.
- */
- update_dev_wakeup_time(adev, &hw_level);
-
- /*
- * If new hardware level is less than or equal to the
- * written frames, we can suppose underrun happened. But
- * keep in mind there may have a false positive. If
- * hardware level changed just after frames being
- * written, we may get hw_level <= total_written here
- * without underrun happened. However, we can still
- * treat it as underrun because it is an abnormal state
- * we should handle it.
- */
- if (hw_level <= total_written) {
- rc = cras_iodev_output_underrun(
- adev->dev, hw_level, total_written);
- if (rc < 0) {
- handle_dev_err(rc, odevs, adev);
- } else {
- update_dev_wakeup_time(adev, &hw_level);
- }
- }
- }
- }
-
- /* TODO(dgreid) - once per rstream, not once per dev_stream. */
- DL_FOREACH (*odevs, adev) {
- struct dev_stream *stream;
- if (!cras_iodev_is_open(adev->dev))
- continue;
- DL_FOREACH (adev->dev->streams, stream) {
- dev_stream_playback_update_rstream(stream);
- }
- }
-
- return 0;
-}
-
-static void update_longest_wake(struct open_dev *dev_list,
- const struct timespec *ts)
-{
- struct open_dev *adev;
- struct timespec wake_interval;
-
- DL_FOREACH (dev_list, adev) {
- if (adev->dev->streams == NULL)
- continue;
- /*
- * Calculate longest wake only when there's stream attached
- * and the last wake time has been set.
- */
- if (adev->last_wake.tv_sec) {
- subtract_timespecs(ts, &adev->last_wake,
- &wake_interval);
- if (timespec_after(&wake_interval, &adev->longest_wake))
- adev->longest_wake = wake_interval;
- }
- adev->last_wake = *ts;
- }
-}
-
-void dev_io_run(struct open_dev **odevs, struct open_dev **idevs,
- struct cras_fmt_conv *output_converter)
-{
- struct timespec now;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- pic_update_current_time();
- update_longest_wake(*odevs, &now);
- update_longest_wake(*idevs, &now);
-
- dev_io_playback_fetch(*odevs);
- dev_io_capture(idevs, odevs);
- dev_io_send_captured_samples(*idevs);
- dev_io_playback_write(odevs, output_converter);
-}
-
-static int input_adev_ignore_wake(const struct open_dev *adev)
-{
- if (!cras_iodev_is_open(adev->dev))
- return 1;
-
- if (!adev->dev->active_node)
- return 1;
-
- if (adev->dev->active_node->type == CRAS_NODE_TYPE_HOTWORD &&
- !cras_iodev_input_streaming(adev->dev))
- return 1;
-
- return 0;
-}
-
-int dev_io_next_input_wake(struct open_dev **idevs, struct timespec *min_ts)
-{
- struct open_dev *adev;
- int ret = 0; /* The total number of devices to wait on. */
-
- DL_FOREACH (*idevs, adev) {
- if (input_adev_ignore_wake(adev))
- continue;
- ret++;
- ATLOG(atlog, AUDIO_THREAD_DEV_SLEEP_TIME, adev->dev->info.idx,
- adev->wake_ts.tv_sec, adev->wake_ts.tv_nsec);
- if (timespec_after(min_ts, &adev->wake_ts))
- *min_ts = adev->wake_ts;
- }
-
- return ret;
-}
-
-/* Fills the time that the next stream needs to be serviced. */
-static int get_next_stream_wake_from_list(struct dev_stream *streams,
- struct timespec *min_ts)
-{
- struct dev_stream *dev_stream;
- int ret = 0; /* The total number of streams to wait on. */
-
- DL_FOREACH (streams, dev_stream) {
- const struct timespec *next_cb_ts;
-
- if (cras_rstream_get_is_draining(dev_stream->stream))
- continue;
-
- if (cras_rstream_is_pending_reply(dev_stream->stream))
- continue;
-
- next_cb_ts = dev_stream_next_cb_ts(dev_stream);
- if (!next_cb_ts)
- continue;
-
- ATLOG(atlog, AUDIO_THREAD_STREAM_SLEEP_TIME,
- dev_stream->stream->stream_id, next_cb_ts->tv_sec,
- next_cb_ts->tv_nsec);
- if (timespec_after(min_ts, next_cb_ts))
- *min_ts = *next_cb_ts;
- ret++;
- }
-
- return ret;
-}
-
-int dev_io_next_output_wake(struct open_dev **odevs, struct timespec *min_ts)
-{
- struct open_dev *adev;
- int ret = 0;
-
- DL_FOREACH (*odevs, adev)
- ret += get_next_stream_wake_from_list(adev->dev->streams,
- min_ts);
-
- DL_FOREACH (*odevs, adev) {
- if (!cras_iodev_odev_should_wake(adev->dev))
- continue;
-
- ret++;
- if (timespec_after(min_ts, &adev->wake_ts))
- *min_ts = adev->wake_ts;
- }
-
- return ret;
-}
-
-struct open_dev *dev_io_find_open_dev(struct open_dev *odev_list,
- unsigned int dev_idx)
-{
- struct open_dev *odev;
- DL_FOREACH (odev_list, odev)
- if (odev->dev->info.idx == dev_idx)
- return odev;
- return NULL;
-}
-
-void dev_io_rm_open_dev(struct open_dev **odev_list, struct open_dev *dev_to_rm)
-{
- struct open_dev *odev;
- struct dev_stream *dev_stream;
-
- /* Do nothing if dev_to_rm wasn't already in the active dev list. */
- DL_FOREACH (*odev_list, odev) {
- if (odev == dev_to_rm)
- break;
- }
- if (!odev)
- return;
-
- DL_DELETE(*odev_list, dev_to_rm);
-
- /* Metrics logs the number of underruns of this device. */
- cras_server_metrics_num_underruns(
- cras_iodev_get_num_underruns(dev_to_rm->dev));
-
- /* Metrics logs the delay of this device. */
- cras_server_metrics_highest_device_delay(
- dev_to_rm->dev->highest_hw_level,
- dev_to_rm->dev->largest_cb_level, dev_to_rm->dev->direction);
-
- /* Metrics logs the highest_hw_level of this device. */
- cras_server_metrics_highest_hw_level(dev_to_rm->dev->highest_hw_level,
- dev_to_rm->dev->direction);
-
- dev_io_check_non_empty_state_transition(*odev_list);
-
- ATLOG(atlog, AUDIO_THREAD_DEV_REMOVED, dev_to_rm->dev->info.idx, 0, 0);
-
- DL_FOREACH (dev_to_rm->dev->streams, dev_stream) {
- cras_iodev_rm_stream(dev_to_rm->dev, dev_stream->stream);
- dev_stream_destroy(dev_stream);
- }
-
- if (dev_to_rm->empty_pi)
- pic_polled_interval_destroy(&dev_to_rm->empty_pi);
- if (dev_to_rm->non_empty_check_pi)
- pic_polled_interval_destroy(&dev_to_rm->non_empty_check_pi);
- free(dev_to_rm);
-}
-
-static void delete_stream_from_dev(struct cras_iodev *dev,
- struct cras_rstream *stream)
-{
- struct dev_stream *out;
-
- out = cras_iodev_rm_stream(dev, stream);
- if (out)
- dev_stream_destroy(out);
-}
-
-/*
- * Finds a matched input stream from open device list.
- * The definition of the matched streams: Two streams having
- * the same sampling rate and the same cb_threshold.
- * This means their sleep time intervals should be very close
- * if we neglect device estimated rate.
- */
-static struct dev_stream *
-find_matched_input_stream(const struct cras_rstream *out_stream,
- struct open_dev *odev_list)
-{
- struct open_dev *odev;
- struct dev_stream *dev_stream;
- size_t out_rate = out_stream->format.frame_rate;
- size_t out_cb_threshold = cras_rstream_get_cb_threshold(out_stream);
-
- DL_FOREACH (odev_list, odev) {
- DL_FOREACH (odev->dev->streams, dev_stream) {
- if (dev_stream->stream->format.frame_rate != out_rate)
- continue;
- if (cras_rstream_get_cb_threshold(dev_stream->stream) !=
- out_cb_threshold)
- continue;
- return dev_stream;
- }
- }
- return NULL;
-}
-
-static bool
-find_matched_input_stream_next_cb_ts(const struct cras_rstream *stream,
- struct open_dev *odev_list,
- const struct timespec **next_cb_ts,
- const struct timespec **sleep_interval_ts)
-{
- struct dev_stream *dev_stream =
- find_matched_input_stream(stream, odev_list);
- if (dev_stream) {
- *next_cb_ts = dev_stream_next_cb_ts(dev_stream);
- *sleep_interval_ts = dev_stream_sleep_interval_ts(dev_stream);
- return *next_cb_ts != NULL;
- }
- return false;
-}
-
-int dev_io_append_stream(struct open_dev **odevs, struct open_dev **idevs,
- struct cras_rstream *stream,
- struct cras_iodev **iodevs, unsigned int num_iodevs)
-{
- struct open_dev **dev_list;
- struct open_dev *open_dev;
- struct cras_iodev *dev;
- struct dev_stream *out;
- struct timespec init_cb_ts;
- const struct timespec *init_sleep_interval_ts = NULL;
- struct timespec extra_sleep;
- const struct timespec *stream_ts;
- unsigned int i;
- bool cb_ts_set = false;
- int level;
- int rc = 0;
-
- if (stream->direction == CRAS_STREAM_OUTPUT)
- dev_list = odevs;
- else
- dev_list = idevs;
-
- for (i = 0; i < num_iodevs; i++) {
- DL_SEARCH_SCALAR(*dev_list, open_dev, dev, iodevs[i]);
- if (!open_dev)
- continue;
-
- dev = iodevs[i];
- DL_SEARCH_SCALAR(dev->streams, out, stream, stream);
- if (out)
- continue;
-
- /*
- * When dev transitions from no stream to the 1st stream, reset
- * last_wake and longest_wake so it can start over the tracking.
- */
- if (dev->streams == NULL) {
- open_dev->last_wake.tv_sec = 0;
- open_dev->last_wake.tv_nsec = 0;
- open_dev->longest_wake.tv_sec = 0;
- open_dev->longest_wake.tv_nsec = 0;
- }
-
- /*
- * When the first input stream is added, flush the input buffer
- * so that we can read from multiple input devices of the same
- * buffer level.
- */
- if ((stream->direction == CRAS_STREAM_INPUT) && !dev->streams) {
- int num_flushed = dev->flush_buffer(dev);
- if (num_flushed < 0) {
- rc = num_flushed;
- break;
- }
- }
-
- /*
- * For output, if open device already has stream, get the earliest next
- * callback time from these streams to align with. Otherwise, check whether
- * there are remaining frames in the device. Set the initial callback time to
- * the time when hw_level of device is close to min_cb_level.
- * If next callback time is too far from now, it will block writing and
- * lower hardware level. Else if we fetch the new stream immediately, it
- * may cause device buffer level stack up.
- */
- if (stream->direction == CRAS_STREAM_OUTPUT) {
- /*
- * If there is a matched input stream, find its next cb time.
- * Use that as the initial cb time for this output stream.
- */
- const struct timespec *in_stream_ts;
- const struct timespec *in_stream_sleep_interval_ts;
- bool found_matched_input;
- found_matched_input =
- find_matched_input_stream_next_cb_ts(
- stream, *idevs, &in_stream_ts,
- &in_stream_sleep_interval_ts);
- if (found_matched_input) {
- init_cb_ts = *in_stream_ts;
- init_sleep_interval_ts =
- in_stream_sleep_interval_ts;
- } else {
- DL_FOREACH (dev->streams, out) {
- stream_ts = dev_stream_next_cb_ts(out);
- if (stream_ts &&
- (!cb_ts_set ||
- timespec_after(&init_cb_ts,
- stream_ts))) {
- init_cb_ts = *stream_ts;
- cb_ts_set = true;
- }
- }
- if (!cb_ts_set) {
- level = cras_iodev_get_valid_frames(
- dev, &init_cb_ts);
- if (level < 0) {
- syslog(LOG_ERR,
- "Failed to set output init_cb_ts, rc = %d",
- level);
- rc = -EINVAL;
- break;
- }
- level -= cras_frames_at_rate(
- stream->format.frame_rate,
- cras_rstream_get_cb_threshold(
- stream),
- dev->format->frame_rate);
- if (level < 0)
- level = 0;
- cras_frames_to_time(
- level, dev->format->frame_rate,
- &extra_sleep);
- add_timespecs(&init_cb_ts,
- &extra_sleep);
- }
- }
- } else {
- /*
- * For input streams, because audio thread can calculate wake up time
- * by hw_level of input device, set the first cb_ts to zero. The stream
- * will wake up when it gets enough samples to post. The next_cb_ts will
- * be updated after its first post.
- *
- * TODO(yuhsuan) - Align the new stream fetch time to avoid getting a large
- * delay. If a new stream with smaller block size starts when the hardware
- * level is high, the hardware level will keep high after removing other
- * old streams.
- */
- init_cb_ts.tv_sec = 0;
- init_cb_ts.tv_nsec = 0;
- }
-
- out = dev_stream_create(stream, dev->info.idx, dev->format, dev,
- &init_cb_ts, init_sleep_interval_ts);
- if (!out) {
- rc = -EINVAL;
- break;
- }
-
- cras_iodev_add_stream(dev, out);
-
- /*
- * For multiple inputs case, if the new stream is not the first
- * one to append, copy the 1st stream's offset to it so that
- * future read offsets can be aligned across all input streams
- * to avoid the deadlock scenario when multiple streams reading
- * from multiple devices.
- */
- if ((stream->direction == CRAS_STREAM_INPUT) &&
- (dev->streams != out)) {
- unsigned int offset =
- cras_iodev_stream_offset(dev, dev->streams);
- if (offset > stream->cb_threshold)
- offset = stream->cb_threshold;
- cras_iodev_stream_written(dev, out, offset);
-
- offset = cras_rstream_dev_offset(dev->streams->stream,
- dev->info.idx);
- if (offset > stream->cb_threshold)
- offset = stream->cb_threshold;
- cras_rstream_dev_offset_update(stream, offset,
- dev->info.idx);
- }
- ATLOG(atlog, AUDIO_THREAD_STREAM_ADDED, stream->stream_id,
- dev->info.idx, 0);
- }
-
- if (rc) {
- DL_FOREACH (*dev_list, open_dev) {
- dev = open_dev->dev;
- DL_SEARCH_SCALAR(dev->streams, out, stream, stream);
- if (!out)
- continue;
-
- cras_iodev_rm_stream(dev, stream);
- dev_stream_destroy(out);
- }
- }
-
- return rc;
-}
-
-int dev_io_remove_stream(struct open_dev **dev_list,
- struct cras_rstream *stream, struct cras_iodev *dev)
-{
- struct open_dev *open_dev;
-
- ATLOG(atlog, AUDIO_THREAD_STREAM_REMOVED, stream->stream_id, 0, 0);
-
- if (dev == NULL) {
- DL_FOREACH (*dev_list, open_dev) {
- delete_stream_from_dev(open_dev->dev, stream);
- }
- } else {
- delete_stream_from_dev(dev, stream);
- }
-
- return 0;
-}
diff --git a/cras/src/server/dev_io.h b/cras/src/server/dev_io.h
deleted file mode 100644
index ca71a809..00000000
--- a/cras/src/server/dev_io.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * `dev_io` Handles playback to and capture from open devices. It runs only on
- * the audio thread.
- */
-
-#ifndef DEV_IO_H_
-#define DEV_IO_H_
-
-#include "cras_iodev.h"
-#include "cras_types.h"
-#include "polled_interval_checker.h"
-
-/*
- * Open input/output devices.
- * dev - The device.
- * last_wake - The last timestamp audio thread woke up and there is stream
- * on this open device.
- * longest_wake - The longest time between consecutive audio thread wakes
- * in this open_dev's life cycle.
- * wake_ts - When callback is needed to avoid xrun.
- * last_non_empty_ts - The last time we know the device played/captured
- * non-empty (zero) audio.
- * coarse_rate_adjust - Hack for when the sample rate needs heavy correction.
- */
-struct open_dev {
- struct cras_iodev *dev;
- struct timespec last_wake;
- struct timespec longest_wake;
- struct timespec wake_ts;
- struct polled_interval *non_empty_check_pi;
- struct polled_interval *empty_pi;
- int coarse_rate_adjust;
- struct open_dev *prev, *next;
-};
-
-/*
- * Fetches streams from each device in `odev_list`.
- * odev_list - The list of open devices.
- */
-void dev_io_playback_fetch(struct open_dev *odev_list);
-
-/*
- * Writes the samples fetched from the streams to the playback devices.
- * odev_list - The list of open devices. Devices will be removed when
- * writing returns an error.
- */
-int dev_io_playback_write(struct open_dev **odevs,
- struct cras_fmt_conv *output_converter);
-
-/* Only public for testing. */
-int write_output_samples(struct open_dev **odevs, struct open_dev *adev,
- struct cras_fmt_conv *output_converter);
-
-/*
- * Captures samples from each device in the list.
- * list - Pointer to the list of input devices. Devices that fail to read
- * will be removed from the list.
- * olist - Pointer to the list of output devices.
- */
-int dev_io_capture(struct open_dev **list, struct open_dev **olist);
-
-/*
- * Send samples that have been captured to their streams.
- */
-int dev_io_send_captured_samples(struct open_dev *idev_list);
-
-/* Reads and/or writes audio samples from/to the devices. */
-void dev_io_run(struct open_dev **odevs, struct open_dev **idevs,
- struct cras_fmt_conv *output_converter);
-
-/*
- * Checks the non-empty device state in active output lists and return
- * if there's at least one non-empty device.
- */
-int dev_io_check_non_empty_state_transition(struct open_dev *adevs);
-
-/*
- * Fills min_ts with the next time the system should wake to service input.
- * Returns the number of devices waiting.
- */
-int dev_io_next_input_wake(struct open_dev **idevs, struct timespec *min_ts);
-
-/*
- * Fills min_ts with the next time the system should wake to service output.
- * Returns the number of devices waiting.
- */
-int dev_io_next_output_wake(struct open_dev **odevs, struct timespec *min_ts);
-
-/*
- * Removes a device from a list of devices.
- * odev_list - A pointer to the list to modify.
- * dev_to_rm - Find this device in the list and remove it.
- */
-void dev_io_rm_open_dev(struct open_dev **odev_list,
- struct open_dev *dev_to_rm);
-
-/* Returns a pointer to an open_dev if it is in the list, otherwise NULL. */
-struct open_dev *dev_io_find_open_dev(struct open_dev *odev_list,
- unsigned int dev_idx);
-
-/* Append a new stream to a specified set of iodevs. */
-int dev_io_append_stream(struct open_dev **odevs, struct open_dev **idevs,
- struct cras_rstream *stream,
- struct cras_iodev **iodevs, unsigned int num_iodevs);
-
-/* Remove a stream from the provided list of devices. */
-int dev_io_remove_stream(struct open_dev **dev_list,
- struct cras_rstream *stream, struct cras_iodev *dev);
-
-#endif /* DEV_IO_H_ */
diff --git a/cras/src/server/dev_stream.c b/cras/src/server/dev_stream.c
deleted file mode 100644
index be5a6dab..00000000
--- a/cras/src/server/dev_stream.c
+++ /dev/null
@@ -1,782 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "audio_thread_log.h"
-#include "byte_buffer.h"
-#include "cras_fmt_conv.h"
-#include "dev_stream.h"
-#include "cras_audio_area.h"
-#include "cras_mix.h"
-#include "cras_server_metrics.h"
-#include "cras_shm.h"
-
-/* Adjust device's sample rate by this step faster or slower. Used
- * to make sure multiple active device has stable buffer level.
- */
-static const int coarse_rate_adjust_step = 3;
-
-/*
- * Allow capture callback to fire this much earlier than the scheduled
- * next_cb_ts to avoid an extra wake of audio thread.
- */
-static const struct timespec capture_callback_fuzz_ts = {
- .tv_sec = 0,
- .tv_nsec = 1000000, /* 1 ms. */
-};
-
-/*
- * Returns the size in frames that a format converter must allocate for its
- * temporary buffers to be able to convert the specified number of stream
- * frames to or from the corresponding number of device frames, at the
- * specified device rate.
- */
-unsigned int max_frames_for_conversion(unsigned int stream_frames,
- unsigned int stream_rate,
- unsigned int device_rate)
-{
- /*
- * There are multiple temp buffers in the format converter,
- * which are all the same size. Some of these contain audio
- * in the source sample rate, and others in the converted
- * sample rate. We need to make sure the converter is large
- * enough to hold either.
- */
- return MAX(
- // Number of stream frames does not require conversion.
- stream_frames,
- // Calculate corresponding number of frames at device rate.
- cras_frames_at_rate(stream_rate, stream_frames,
- device_rate))
- /*
- * Add 1 because the linear resampler's frame rate
- * conversion does this, and is used to calculate
- * how many frames to read from the device.
- * See linear_resampler_{in,out}_frames_to_{out,in}(..)
- */
- + 1;
-}
-
-struct dev_stream *dev_stream_create(struct cras_rstream *stream,
- unsigned int dev_id,
- const struct cras_audio_format *dev_fmt,
- void *dev_ptr, struct timespec *cb_ts,
- const struct timespec *sleep_interval_ts)
-{
- struct dev_stream *out;
- struct cras_audio_format *stream_fmt = &stream->format;
- int rc = 0;
- unsigned int max_frames, dev_frames, buf_bytes;
- const struct cras_audio_format *ofmt;
-
- out = calloc(1, sizeof(*out));
- out->dev_id = dev_id;
- out->stream = stream;
- out->dev_rate = dev_fmt->frame_rate;
- out->is_running = 0;
-
- max_frames = max_frames_for_conversion(stream->buffer_frames,
- stream_fmt->frame_rate,
- dev_fmt->frame_rate);
-
- if (stream->direction == CRAS_STREAM_OUTPUT) {
- rc = config_format_converter(&out->conv, stream->direction,
- stream_fmt, dev_fmt, max_frames);
- } else {
- /*
- * For input, take into account the stream specific processing
- * like AEC. APM exists only in input path, and has no dependency
- * to dev_stream. Starts APM in dev_stream's constructor just to
- * align with its life cycle, and then gets the post processing
- * format to configure format converter.
- */
- cras_apm_list_start_apm(stream->apm_list, dev_ptr);
- ofmt = cras_rstream_post_processing_format(stream, dev_ptr) ?:
- dev_fmt,
- rc = config_format_converter(&out->conv, stream->direction,
- ofmt, stream_fmt, max_frames);
- }
- if (rc) {
- free(out);
- return NULL;
- }
-
- ofmt = cras_fmt_conv_out_format(out->conv);
-
- dev_frames =
- (stream->direction == CRAS_STREAM_OUTPUT) ?
- cras_fmt_conv_in_frames_to_out(out->conv,
- stream->buffer_frames) :
- cras_fmt_conv_out_frames_to_in(out->conv,
- stream->buffer_frames);
-
- out->conv_buffer_size_frames =
- 2 * MAX(dev_frames, stream->buffer_frames);
-
- /* Create conversion buffer and area using the output format
- * of the format converter. Note that this format might not be
- * identical to stream_fmt for capture. */
- buf_bytes = out->conv_buffer_size_frames * cras_get_format_bytes(ofmt);
- out->conv_buffer = byte_buffer_create(buf_bytes);
- out->conv_area = cras_audio_area_create(ofmt->num_channels);
-
- /* Use sleep interval hint from argument if it is provided */
- if (sleep_interval_ts) {
- stream->sleep_interval_ts = *sleep_interval_ts;
- } else {
- cras_frames_to_time(cras_rstream_get_cb_threshold(stream),
- stream_fmt->frame_rate,
- &stream->sleep_interval_ts);
- }
-
- stream->next_cb_ts = *cb_ts;
-
- /* Sets up the stream & dev pair. */
- cras_rstream_dev_attach(stream, dev_id, dev_ptr);
-
- return out;
-}
-
-void dev_stream_destroy(struct dev_stream *dev_stream)
-{
- void *dev_ptr =
- cras_rstream_dev_ptr(dev_stream->stream, dev_stream->dev_id);
- /* Stops the APM and then unlink the dev stream pair. */
- cras_apm_list_stop_apm(dev_stream->stream->apm_list, dev_ptr);
- cras_rstream_dev_detach(dev_stream->stream, dev_stream->dev_id);
- if (dev_stream->conv) {
- cras_audio_area_destroy(dev_stream->conv_area);
- cras_fmt_conv_destroy(&dev_stream->conv);
- byte_buffer_destroy(&dev_stream->conv_buffer);
- }
- free(dev_stream);
-}
-
-void dev_stream_set_dev_rate(struct dev_stream *dev_stream,
- unsigned int dev_rate, double dev_rate_ratio,
- double main_rate_ratio, int coarse_rate_adjust)
-{
- if (dev_stream->dev_id == dev_stream->stream->main_dev.dev_id) {
- cras_fmt_conv_set_linear_resample_rates(dev_stream->conv,
- dev_rate, dev_rate);
- cras_frames_to_time_precise(
- cras_rstream_get_cb_threshold(dev_stream->stream),
- dev_stream->stream->format.frame_rate * dev_rate_ratio,
- &dev_stream->stream->sleep_interval_ts);
- } else {
- double new_rate = dev_rate * dev_rate_ratio / main_rate_ratio +
- coarse_rate_adjust_step * coarse_rate_adjust;
- cras_fmt_conv_set_linear_resample_rates(dev_stream->conv,
- dev_rate, new_rate);
- }
-}
-
-int dev_stream_mix(struct dev_stream *dev_stream,
- const struct cras_audio_format *fmt, uint8_t *dst,
- unsigned int num_to_write)
-{
- struct cras_rstream *rstream = dev_stream->stream;
- uint8_t *src;
- uint8_t *target = dst;
- unsigned int fr_written, fr_read;
- unsigned int buffer_offset;
- int fr_in_buf;
- unsigned int num_samples;
- size_t frames = 0;
- unsigned int dev_frames;
- float mix_vol;
-
- fr_in_buf = dev_stream_playback_frames(dev_stream);
- if (fr_in_buf <= 0)
- return fr_in_buf;
- if (fr_in_buf < num_to_write)
- num_to_write = fr_in_buf;
-
- buffer_offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
-
- /* Stream volume scaler. */
- mix_vol = cras_rstream_get_volume_scaler(dev_stream->stream);
-
- fr_written = 0;
- fr_read = 0;
- while (fr_written < num_to_write) {
- unsigned int read_frames;
- src = cras_rstream_get_readable_frames(
- rstream, buffer_offset + fr_read, &frames);
- if (frames == 0)
- break;
- if (cras_fmt_conversion_needed(dev_stream->conv)) {
- read_frames = frames;
- dev_frames = cras_fmt_conv_convert_frames(
- dev_stream->conv, src,
- dev_stream->conv_buffer->bytes, &read_frames,
- num_to_write - fr_written);
- src = dev_stream->conv_buffer->bytes;
- } else {
- dev_frames = MIN(frames, num_to_write - fr_written);
- read_frames = dev_frames;
- }
- num_samples = dev_frames * fmt->num_channels;
- cras_mix_add(fmt->format, target, src, num_samples, 1,
- cras_rstream_get_mute(rstream), mix_vol);
- target += dev_frames * cras_get_format_bytes(fmt);
- fr_written += dev_frames;
- fr_read += read_frames;
- }
-
- cras_rstream_dev_offset_update(rstream, fr_read, dev_stream->dev_id);
- ATLOG(atlog, AUDIO_THREAD_DEV_STREAM_MIX, fr_written, fr_read, 0);
-
- return fr_written;
-}
-
-/* Copy from the captured buffer to the temporary format converted buffer. */
-static unsigned int capture_with_fmt_conv(struct dev_stream *dev_stream,
- const uint8_t *source_samples,
- unsigned int num_frames)
-{
- const struct cras_audio_format *source_format;
- const struct cras_audio_format *dst_format;
- uint8_t *buffer;
- unsigned int total_read = 0;
- unsigned int write_frames;
- unsigned int read_frames;
- unsigned int source_frame_bytes;
- unsigned int dst_frame_bytes;
-
- source_format = cras_fmt_conv_in_format(dev_stream->conv);
- source_frame_bytes = cras_get_format_bytes(source_format);
- dst_format = cras_fmt_conv_out_format(dev_stream->conv);
- dst_frame_bytes = cras_get_format_bytes(dst_format);
-
- dev_stream->conv_area->num_channels = dst_format->num_channels;
-
- while (total_read < num_frames) {
- buffer = buf_write_pointer_size(dev_stream->conv_buffer,
- &write_frames);
- write_frames /= dst_frame_bytes;
- if (write_frames == 0)
- break;
-
- read_frames = num_frames - total_read;
- write_frames = cras_fmt_conv_convert_frames(
- dev_stream->conv, source_samples, buffer, &read_frames,
- write_frames);
- total_read += read_frames;
- source_samples += read_frames * source_frame_bytes;
- buf_increment_write(dev_stream->conv_buffer,
- (size_t)write_frames *
- (size_t)dst_frame_bytes);
- }
-
- return total_read;
-}
-
-/* Copy from the converted buffer to the stream shm. These have the same format
- * at this point. */
-static unsigned int
-capture_copy_converted_to_stream(struct dev_stream *dev_stream,
- struct cras_rstream *rstream,
- float software_gain_scaler)
-{
- struct cras_audio_shm *shm;
- uint8_t *stream_samples;
- uint8_t *converted_samples;
- unsigned int num_frames;
- unsigned int total_written = 0;
- unsigned int write_frames;
- unsigned int frame_bytes;
- unsigned int offset;
- const struct cras_audio_format *fmt;
-
- shm = cras_rstream_shm(rstream);
-
- fmt = cras_fmt_conv_out_format(dev_stream->conv);
- frame_bytes = cras_get_format_bytes(fmt);
-
- offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
-
- stream_samples = cras_shm_get_writeable_frames(
- shm, cras_rstream_get_cb_threshold(rstream),
- &rstream->audio_area->frames);
- num_frames = MIN(rstream->audio_area->frames - offset,
- buf_queued(dev_stream->conv_buffer) / frame_bytes);
-
- ATLOG(atlog, AUDIO_THREAD_CONV_COPY, shm->header->write_buf_idx,
- rstream->audio_area->frames, offset);
-
- while (total_written < num_frames) {
- converted_samples = buf_read_pointer_size(
- dev_stream->conv_buffer, &write_frames);
- write_frames /= frame_bytes;
- write_frames = MIN(write_frames, num_frames - total_written);
-
- cras_audio_area_config_buf_pointers(dev_stream->conv_area, fmt,
- converted_samples);
- cras_audio_area_config_channels(dev_stream->conv_area, fmt);
- dev_stream->conv_area->frames = write_frames;
-
- cras_audio_area_config_buf_pointers(
- rstream->audio_area, &rstream->format, stream_samples);
-
- cras_audio_area_copy(rstream->audio_area, offset,
- &rstream->format, dev_stream->conv_area, 0,
- software_gain_scaler);
-
- buf_increment_read(dev_stream->conv_buffer,
- (size_t)write_frames * (size_t)frame_bytes);
- total_written += write_frames;
- cras_rstream_dev_offset_update(rstream, write_frames,
- dev_stream->dev_id);
- offset = cras_rstream_dev_offset(rstream, dev_stream->dev_id);
- }
-
- ATLOG(atlog, AUDIO_THREAD_CAPTURE_WRITE, rstream->stream_id,
- total_written, cras_shm_frames_written(shm));
- return total_written;
-}
-
-unsigned int dev_stream_capture(struct dev_stream *dev_stream,
- const struct cras_audio_area *area,
- unsigned int area_offset,
- float software_gain_scaler)
-{
- struct cras_rstream *rstream = dev_stream->stream;
- struct cras_audio_shm *shm;
- uint8_t *stream_samples;
- unsigned int nread;
-
- /* Check if format conversion is needed. */
- if (cras_fmt_conversion_needed(dev_stream->conv)) {
- unsigned int format_bytes, fr_to_capture;
-
- fr_to_capture = dev_stream_capture_avail(dev_stream);
- fr_to_capture = MIN(fr_to_capture, area->frames - area_offset);
-
- format_bytes = cras_get_format_bytes(
- cras_fmt_conv_in_format(dev_stream->conv));
- nread = capture_with_fmt_conv(
- dev_stream,
- area->channels[0].buf + area_offset * format_bytes,
- fr_to_capture);
-
- capture_copy_converted_to_stream(dev_stream, rstream,
- software_gain_scaler);
- } else {
- unsigned int offset =
- cras_rstream_dev_offset(rstream, dev_stream->dev_id);
-
- /* Set up the shm area and copy to it. */
- shm = cras_rstream_shm(rstream);
- stream_samples = cras_shm_get_writeable_frames(
- shm, cras_rstream_get_cb_threshold(rstream),
- &rstream->audio_area->frames);
- cras_audio_area_config_buf_pointers(
- rstream->audio_area, &rstream->format, stream_samples);
-
- nread = cras_audio_area_copy(rstream->audio_area, offset,
- &rstream->format, area,
- area_offset, software_gain_scaler);
-
- ATLOG(atlog, AUDIO_THREAD_CAPTURE_WRITE, rstream->stream_id,
- nread, cras_shm_frames_written(shm));
- cras_rstream_dev_offset_update(rstream, nread,
- dev_stream->dev_id);
- }
-
- return nread;
-}
-
-int dev_stream_attached_devs(const struct dev_stream *dev_stream)
-{
- return dev_stream->stream->num_attached_devs;
-}
-
-void dev_stream_update_frames(const struct dev_stream *dev_stream)
-{
- cras_rstream_update_queued_frames(dev_stream->stream);
-}
-
-int dev_stream_playback_frames(const struct dev_stream *dev_stream)
-{
- int frames;
-
- frames = cras_rstream_playable_frames(dev_stream->stream,
- dev_stream->dev_id);
- if (frames < 0)
- return frames;
-
- if (!dev_stream->conv)
- return frames;
-
- return cras_fmt_conv_in_frames_to_out(dev_stream->conv, frames);
-}
-
-unsigned int dev_stream_cb_threshold(const struct dev_stream *dev_stream)
-{
- const struct cras_rstream *rstream = dev_stream->stream;
- unsigned int cb_threshold = cras_rstream_get_cb_threshold(rstream);
-
- if (rstream->direction == CRAS_STREAM_OUTPUT)
- return cras_fmt_conv_in_frames_to_out(dev_stream->conv,
- cb_threshold);
- else
- return cras_fmt_conv_out_frames_to_in(dev_stream->conv,
- cb_threshold);
-}
-
-unsigned int dev_stream_capture_avail(const struct dev_stream *dev_stream)
-{
- struct cras_audio_shm *shm;
- struct cras_rstream *rstream = dev_stream->stream;
- unsigned int frames_avail;
- unsigned int conv_buf_level;
- unsigned int format_bytes;
- unsigned int wlimit;
- unsigned int dev_offset =
- cras_rstream_dev_offset(rstream, dev_stream->dev_id);
-
- shm = cras_rstream_shm(rstream);
-
- wlimit = cras_rstream_get_max_write_frames(rstream);
- wlimit -= dev_offset;
- cras_shm_get_writeable_frames(shm, wlimit, &frames_avail);
-
- if (!dev_stream->conv)
- return frames_avail;
-
- format_bytes = cras_get_format_bytes(
- cras_fmt_conv_out_format(dev_stream->conv));
-
- /* Sample rate conversion may cause some sample left in conv_buffer
- * take this buffer into account. */
- conv_buf_level = buf_queued(dev_stream->conv_buffer) / format_bytes;
- if (frames_avail <= conv_buf_level)
- return 0;
- else
- frames_avail -= conv_buf_level;
-
- frames_avail =
- MIN(frames_avail,
- buf_available(dev_stream->conv_buffer) / format_bytes);
-
- return cras_fmt_conv_out_frames_to_in(dev_stream->conv, frames_avail);
-}
-
-/* TODO(dgreid) remove this hack to reset the time if needed. */
-static void check_next_wake_time(struct dev_stream *dev_stream)
-{
- struct cras_rstream *rstream = dev_stream->stream;
- struct timespec now;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- if (timespec_after(&now, &rstream->next_cb_ts)) {
- rstream->next_cb_ts = now;
- add_timespecs(&rstream->next_cb_ts,
- &rstream->sleep_interval_ts);
- ATLOG(atlog, AUDIO_THREAD_STREAM_RESCHEDULE, rstream->stream_id,
- rstream->next_cb_ts.tv_sec, rstream->next_cb_ts.tv_nsec);
- cras_server_metrics_missed_cb_event(rstream);
- }
-}
-
-void dev_stream_update_next_wake_time(struct dev_stream *dev_stream)
-{
- struct cras_rstream *rstream = dev_stream->stream;
-
- /*
- * The empty next_cb_ts means it is the first time update for input stream.
- * Initialize next_cb_ts without recording missed callback.
- */
- if (rstream->direction == CRAS_STREAM_INPUT &&
- !timespec_is_nonzero(&rstream->next_cb_ts)) {
- clock_gettime(CLOCK_MONOTONIC_RAW, &rstream->next_cb_ts);
- add_timespecs(&rstream->next_cb_ts,
- &rstream->sleep_interval_ts);
- return;
- }
- /* Update next callback time according to perfect schedule. */
- add_timespecs(&rstream->next_cb_ts, &rstream->sleep_interval_ts);
- /* Reset schedule if the schedule is missed. */
- check_next_wake_time(dev_stream);
-}
-
-int dev_stream_playback_update_rstream(struct dev_stream *dev_stream)
-{
- cras_rstream_update_output_read_pointer(dev_stream->stream);
- return 0;
-}
-
-static int late_enough_for_capture_callback(struct dev_stream *dev_stream)
-{
- struct timespec now;
- struct cras_rstream *rstream = dev_stream->stream;
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
- add_timespecs(&now, &capture_callback_fuzz_ts);
- return timespec_after(&now, &rstream->next_cb_ts);
-}
-
-int dev_stream_capture_update_rstream(struct dev_stream *dev_stream)
-{
- struct cras_rstream *rstream = dev_stream->stream;
- unsigned int frames_ready = cras_rstream_get_cb_threshold(rstream);
- int rc;
-
- if ((rstream->flags & TRIGGER_ONLY) && rstream->triggered)
- return 0;
-
- cras_rstream_update_input_write_pointer(rstream);
-
- /*
- * For stream without BULK_AUDIO_OK flag, if it isn't time for
- * this stream then skip it.
- */
- if (!(rstream->flags & BULK_AUDIO_OK) &&
- !late_enough_for_capture_callback(dev_stream))
- return 0;
-
- /* If there is not enough data for one callback, skip it. */
- if (!cras_rstream_input_level_met(rstream))
- return 0;
-
- /* Enough data for this stream. */
- if (rstream->flags & BULK_AUDIO_OK)
- frames_ready = cras_rstream_level(rstream);
-
- ATLOG(atlog, AUDIO_THREAD_CAPTURE_POST, rstream->stream_id,
- frames_ready, rstream->shm->header->read_buf_idx);
-
- rc = cras_rstream_audio_ready(rstream, frames_ready);
-
- if (rc < 0)
- return rc;
-
- if (rstream->flags & TRIGGER_ONLY)
- rstream->triggered = 1;
-
- dev_stream_update_next_wake_time(dev_stream);
-
- return 0;
-}
-
-void cras_set_playback_timestamp(size_t frame_rate, size_t frames,
- struct cras_timespec *ts)
-{
- cras_clock_gettime(CLOCK_MONOTONIC_RAW, ts);
-
- /* For playback, want now + samples left to be played.
- * ts = time next written sample will be played to DAC,
- */
- ts->tv_nsec += frames * 1000000000ULL / frame_rate;
- while (ts->tv_nsec > 1000000000ULL) {
- ts->tv_sec++;
- ts->tv_nsec -= 1000000000ULL;
- }
-}
-
-void cras_set_capture_timestamp(size_t frame_rate, size_t frames,
- struct cras_timespec *ts)
-{
- long tmp;
-
- cras_clock_gettime(CLOCK_MONOTONIC_RAW, ts);
-
- /* For capture, now - samples left to be read.
- * ts = time next sample to be read was captured at ADC.
- */
- tmp = frames * (1000000000L / frame_rate);
- while (tmp > 1000000000L) {
- tmp -= 1000000000L;
- ts->tv_sec--;
- }
- if (ts->tv_nsec >= tmp)
- ts->tv_nsec -= tmp;
- else {
- tmp -= ts->tv_nsec;
- ts->tv_nsec = 1000000000L - tmp;
- ts->tv_sec--;
- }
-}
-
-void dev_stream_set_delay(const struct dev_stream *dev_stream,
- unsigned int delay_frames)
-{
- struct cras_rstream *rstream = dev_stream->stream;
- struct cras_audio_shm *shm;
- unsigned int stream_frames;
-
- if (rstream->direction == CRAS_STREAM_OUTPUT) {
- shm = cras_rstream_shm(rstream);
- stream_frames = cras_fmt_conv_out_frames_to_in(dev_stream->conv,
- delay_frames);
- cras_set_playback_timestamp(rstream->format.frame_rate,
- stream_frames +
- cras_shm_get_frames(shm),
- &shm->header->ts);
- } else {
- shm = cras_rstream_shm(rstream);
- stream_frames = cras_fmt_conv_in_frames_to_out(dev_stream->conv,
- delay_frames);
- if (cras_shm_frames_written(shm) == 0)
- cras_set_capture_timestamp(rstream->format.frame_rate,
- stream_frames,
- &shm->header->ts);
- }
-}
-
-int dev_stream_request_playback_samples(struct dev_stream *dev_stream,
- const struct timespec *now)
-{
- int rc;
-
- rc = cras_rstream_request_audio(dev_stream->stream, now);
- if (rc < 0)
- return rc;
-
- dev_stream_update_next_wake_time(dev_stream);
-
- return 0;
-}
-
-int dev_stream_poll_stream_fd(const struct dev_stream *dev_stream)
-{
- const struct cras_rstream *stream = dev_stream->stream;
-
- /* For streams which rely on dev level timing, we should
- * let client response wake audio thread up. */
- if (stream_uses_input(stream) && (stream->flags & USE_DEV_TIMING) &&
- cras_rstream_is_pending_reply(stream))
- return stream->fd;
-
- if (!stream_uses_output(stream) ||
- !cras_rstream_is_pending_reply(stream) ||
- cras_rstream_get_is_draining(stream))
- return -1;
-
- return stream->fd;
-}
-
-/*
- * Gets proper wake up time for an input stream. It considers both
- * time for samples to reach one callback level, and the time for next callback.
- * Returns:
- * 0 on success; negavite error code on failure. A positive value if
- * there is no need to set wake up time for this stream.
- */
-static int get_input_wake_time(struct dev_stream *dev_stream,
- unsigned int curr_level,
- struct timespec *level_tstamp,
- unsigned int cap_limit, int is_cap_limit_stream,
- struct timespec *wake_time_out)
-{
- struct cras_rstream *rstream = dev_stream->stream;
- struct timespec time_for_sample;
- int needed_frames_from_device;
-
- needed_frames_from_device = dev_stream_capture_avail(dev_stream);
-
- /*
- * If this stream is not cap_limit stream, and it needs more
- * frames than the capture limit from audio thread, don't bother
- * re-calculating the wake time for it because
- * |needed_frames_from_device| cannot be all copied to shm until
- * the cap_limit stream get its samples in shm read by client
- * and relieve the cap_limit.
- *
- * Note that we need to know whether this stream is cap_limit
- * stream here because the client of cap_limit stream may read
- * the data from shm during this time window, and cause
- * needed_frames_from_device to be greater than cap_limit which
- * was calculated before.
- */
- if (!is_cap_limit_stream && needed_frames_from_device > cap_limit)
- return 1;
-
- /*
- * For capture stream using device timing, the flow would be:
- * 1. Device has less than one cb_threshold of data.
- * 2. Device has a large chunk of data that client needs to consume
- * in multiple cycles.
- * 3. Audio thread sends one block to client and goes to sleep.
- * 4. Client sends reply to wake up audio thread.
- * 5. Repeat 3 and 4 until there is less than one cb_threshold of data.
- * 6. Goes to 1.
- *
- * In 1, we schedule the next wake up time based on the needed frames.
- * This is needed to poll the samples from device.
- *
- * In 3, we do not schedule a wake up time for this stream.
- * We let reply from client wakes up audio thread to send next
- * cb_threshold of data.
- *
- * TODO(cychiang) Do we want to actually block sending data to client
- * until client replies ? Or control the scheduling of wake up time
- * is enough ?
- *
- */
- if ((rstream->flags & USE_DEV_TIMING) &&
- cras_rstream_is_pending_reply(rstream))
- return 1;
-
- *wake_time_out = rstream->next_cb_ts;
-
- /*
- * If current frames in the device can provide needed amount for stream,
- * there is no need to wait.
- */
- if (curr_level >= needed_frames_from_device)
- needed_frames_from_device = 0;
- else
- needed_frames_from_device -= curr_level;
-
- cras_frames_to_time(needed_frames_from_device, dev_stream->dev_rate,
- &time_for_sample);
-
- add_timespecs(&time_for_sample, level_tstamp);
-
- /* Select the time that is later so both sample and time conditions
- * are met. */
- if (timespec_after(&time_for_sample, &rstream->next_cb_ts))
- *wake_time_out = time_for_sample;
- /* Using device timing means the stream neglects next callback time. */
- if (rstream->flags & USE_DEV_TIMING)
- *wake_time_out = time_for_sample;
-
- ATLOG(atlog, AUDIO_THREAD_STREAM_SLEEP_TIME,
- dev_stream->stream->stream_id, wake_time_out->tv_sec,
- wake_time_out->tv_nsec);
-
- return 0;
-}
-
-int dev_stream_wake_time(struct dev_stream *dev_stream, unsigned int curr_level,
- struct timespec *level_tstamp, unsigned int cap_limit,
- int is_cap_limit_stream,
- struct timespec *wake_time_out)
-{
- if (dev_stream->stream->direction == CRAS_STREAM_OUTPUT) {
- /*
- * TODO(cychiang) Implement the method for output stream.
- * The logic should be similar to what
- * get_next_stream_wake_from_list in audio_thread.c is doing.
- */
- return -EINVAL;
- }
-
- return get_input_wake_time(dev_stream, curr_level, level_tstamp,
- cap_limit, is_cap_limit_stream,
- wake_time_out);
-}
-
-int dev_stream_is_pending_reply(const struct dev_stream *dev_stream)
-{
- return cras_rstream_is_pending_reply(dev_stream->stream);
-}
-
-int dev_stream_flush_old_audio_messages(struct dev_stream *dev_stream)
-{
- return cras_rstream_flush_old_audio_messages(dev_stream->stream);
-}
diff --git a/cras/src/server/dev_stream.h b/cras/src/server/dev_stream.h
deleted file mode 100644
index 6b34d5d7..00000000
--- a/cras/src/server/dev_stream.h
+++ /dev/null
@@ -1,234 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- *
- * The dev_stream structure is used for mapping streams to a device. In
- * addition to the rstream, other mixing information is stored here.
- */
-
-#ifndef DEV_STREAM_H_
-#define DEV_STREAM_H_
-
-#include <stdint.h>
-#include <sys/time.h>
-
-#include "cras_types.h"
-#include "cras_rstream.h"
-
-struct cras_audio_area;
-struct cras_fmt_conv;
-struct cras_iodev;
-
-/*
- * Linked list of streams of audio from/to a client.
- * Args:
- * dev_id - Index of the hw device.
- * stream - The rstream attached to a device.
- * conv - Sample rate or format converter.
- * conv_buffer - The buffer for converter if needed.
- * conv_buffer_size_frames - Size of conv_buffer in frames.
- * dev_rate - Sampling rate of device. This is set when dev_stream is
- * created.
- * is_running - For input stream, it should be set to true after it is added
- * into device. For output stream, it should be set to true
- * just before its first fetch to avoid affecting other existing
- * streams.
- */
-struct dev_stream {
- unsigned int dev_id;
- struct cras_rstream *stream;
- struct cras_fmt_conv *conv;
- struct byte_buffer *conv_buffer;
- struct cras_audio_area *conv_area;
- unsigned int conv_buffer_size_frames;
- size_t dev_rate;
- struct dev_stream *prev, *next;
- int is_running;
-};
-
-/*
- * Creates a dev_stream.
- *
- * Args:
- * stream - The associated rstream.
- * dev_id - Index of the device.
- * dev_fmt - The format of the device.
- * dev_ptr - A pointer to the device
- * cb_ts - A pointer to the initial callback time.
- * sleep_interval_ts - A pointer to the initial sleep interval.
- * Set to null to calculate the value from device rate and block size.
- * Note that we need this argument so that output device sleep interval
- * can use input device sleep interval in the beginning to have perfect
- * alignment in WebRTC use case.
- * Returns the pointer to the created dev_stream.
- */
-struct dev_stream *dev_stream_create(struct cras_rstream *stream,
- unsigned int dev_id,
- const struct cras_audio_format *dev_fmt,
- void *dev_ptr, struct timespec *cb_ts,
- const struct timespec *sleep_interval_ts);
-void dev_stream_destroy(struct dev_stream *dev_stream);
-
-/*
- * Update the estimated sample rate of the device. For multiple active
- * devices case, the linear resampler will be configured by the estimated
- * rate ration of the main device and the current active device the
- * rstream attaches to.
- *
- * Args:
- * dev_stream - The structure holding the stream.
- * dev_rate - The sample rate device is using.
- * dev_rate_ratio - The ratio of estimated rate and used rate.
- * main_rate_ratio - The ratio of estimated rate and used rate of
- * main device.
- * coarse_rate_adjust - The flag to indicate the direction device
- * sample rate should adjust to.
- */
-void dev_stream_set_dev_rate(struct dev_stream *dev_stream,
- unsigned int dev_rate, double dev_rate_ratio,
- double main_rate_ratio, int coarse_rate_adjust);
-
-/*
- * Renders count frames from shm into dst. Updates count if anything is
- * written. If it's muted and the only stream zero memory.
- * Args:
- * dev_stream - The struct holding the stream to mix.
- * format - The format of the audio device.
- * dst - The destination buffer for mixing.
- * num_to_write - The number of frames written.
- */
-int dev_stream_mix(struct dev_stream *dev_stream,
- const struct cras_audio_format *fmt, uint8_t *dst,
- unsigned int num_to_write);
-
-/*
- * Reads froms from the source into the dev_stream.
- * Args:
- * dev_stream - The struct holding the stream to mix to.
- * area - The area to copy audio from.
- * area_offset - The offset at which to start reading from area.
- * software_gain_scaler - The software gain scaler.
- */
-unsigned int dev_stream_capture(struct dev_stream *dev_stream,
- const struct cras_audio_area *area,
- unsigned int area_offset,
- float software_gain_scaler);
-
-/* Returns the number of iodevs this stream has attached to. */
-int dev_stream_attached_devs(const struct dev_stream *dev_stream);
-
-/* Updates the number of queued frames in dev_stream. */
-void dev_stream_update_frames(const struct dev_stream *dev_stream);
-
-/*
- * Returns the number of playback frames queued in shared memory. This is a
- * post-format-conversion number. If the stream is 24k with 10 frames queued
- * and the device is playing at 48k, 20 will be returned.
- */
-int dev_stream_playback_frames(const struct dev_stream *dev_stream);
-
-/*
- * Returns the number of frames free to be written to in a capture stream. This
- * number is also post format conversion, similar to playback_frames above.
- */
-unsigned int dev_stream_capture_avail(const struct dev_stream *dev_stream);
-
-/*
- * Returns the callback threshold, if necesary converted from a stream frame
- * count to a device frame count.
- */
-unsigned int dev_stream_cb_threshold(const struct dev_stream *dev_stream);
-
-/* Update next callback time for the stream. */
-void dev_stream_update_next_wake_time(struct dev_stream *dev_stream);
-
-/*
- * If enough samples have been captured, post them to the client.
- * TODO(dgreid) - see if this function can be eliminated.
- */
-int dev_stream_capture_update_rstream(struct dev_stream *dev_stream);
-
-/* Updates the read buffer pointers for the stream. */
-int dev_stream_playback_update_rstream(struct dev_stream *dev_stream);
-
-/* Fill ts with the time the playback sample will be played. */
-void cras_set_playback_timestamp(size_t frame_rate, size_t frames,
- struct cras_timespec *ts);
-
-/* Fill ts with the time the capture sample was recorded. */
-void cras_set_capture_timestamp(size_t frame_rate, size_t frames,
- struct cras_timespec *ts);
-
-/* Fill shm ts with the time the playback sample will be played or the capture
- * sample was captured depending on the direction of the stream.
- * Args:
- * delay_frames - The delay reproted by the device, in frames at the device's
- * sample rate.
- */
-void dev_stream_set_delay(const struct dev_stream *dev_stream,
- unsigned int delay_frames);
-
-/* Ask the client for cb_threshold samples of audio to play. */
-int dev_stream_request_playback_samples(struct dev_stream *dev_stream,
- const struct timespec *now);
-
-/*
- * Gets the wake up time for a dev_stream.
- * For an input stream, it considers both needed samples and proper time
- * interval between each callbacks.
- * Args:
- * dev_stream[in]: The dev_stream to check wake up time.
- * curr_level[in]: The current level of device.
- * level_tstamp[in]: The time stamp when getting current level of device.
- * cap_limit[in]: The number of frames that can be captured across all
- * streams.
- * is_cap_limit_stream[in]: 1 if this stream is causing cap_limit.
- * wake_time_out[out]: A timespec for wake up time.
- * Returns:
- * 0 on success; negative error code on failure.
- * A positive value if there is no need to set wake up time for this stream.
- */
-int dev_stream_wake_time(struct dev_stream *dev_stream, unsigned int curr_level,
- struct timespec *level_tstamp, unsigned int cap_limit,
- int is_cap_limit_stream,
- struct timespec *wake_time_out);
-
-/*
- * Returns a non-negative fd if the fd is expecting a message and should be
- * added to the list of descriptors to poll.
- */
-int dev_stream_poll_stream_fd(const struct dev_stream *dev_stream);
-
-static inline int dev_stream_is_running(struct dev_stream *dev_stream)
-{
- return dev_stream->is_running;
-}
-
-static inline void dev_stream_set_running(struct dev_stream *dev_stream)
-{
- dev_stream->is_running = 1;
-}
-
-static inline const struct timespec *
-dev_stream_next_cb_ts(const struct dev_stream *dev_stream)
-{
- if (dev_stream->stream->flags & USE_DEV_TIMING)
- return NULL;
-
- return &dev_stream->stream->next_cb_ts;
-}
-
-static inline const struct timespec *
-dev_stream_sleep_interval_ts(struct dev_stream *dev_stream)
-{
- return &dev_stream->stream->sleep_interval_ts;
-}
-
-int dev_stream_is_pending_reply(const struct dev_stream *dev_stream);
-
-/*
- * Reads any pending audio message from the socket.
- */
-int dev_stream_flush_old_audio_messages(struct dev_stream *dev_stream);
-
-#endif /* DEV_STREAM_H_ */
diff --git a/cras/src/server/ewma_power.c b/cras/src/server/ewma_power.c
deleted file mode 100644
index 5270ef0e..00000000
--- a/cras/src/server/ewma_power.c
+++ /dev/null
@@ -1,81 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "ewma_power.h"
-#include "math.h"
-
-/* One sample per 1ms. */
-#define EWMA_SAMPLE_RATE 1000
-
-/* Smooth factor for EWMA, 1 - expf(-1.0/(rate * 0.01))
- * where the 0.01 corresponds to 10ms interval that is chosen and
- * being used in Chrome for a long time.
- * Here the |rate| is set to the down sampled EWMA_SAMPLE_RATE and
- * whenever it changes the calculated |smooth_factor| should be updated
- * accordingly.
- */
-const static float smooth_factor = 0.095;
-
-void ewma_power_disable(struct ewma_power *ewma)
-{
- ewma->enabled = 0;
-}
-
-void ewma_power_init(struct ewma_power *ewma, unsigned int rate)
-{
- ewma->enabled = 1;
- ewma->power_set = 0;
- ewma->step_fr = rate / EWMA_SAMPLE_RATE;
-}
-
-void ewma_power_calculate(struct ewma_power *ewma, const int16_t *buf,
- unsigned int channels, unsigned int size)
-{
- int i, ch;
- float power, f;
-
- if (!ewma->enabled)
- return;
- for (i = 0; i < size; i += ewma->step_fr * channels) {
- power = 0.0f;
- for (ch = 0; ch < channels; ch++) {
- f = buf[i + ch] / 32768.0f;
- power += f * f / channels;
- }
- if (!ewma->power_set) {
- ewma->power = power;
- ewma->power_set = 1;
- } else {
- ewma->power = smooth_factor * power +
- (1 - smooth_factor) * ewma->power;
- }
- }
-}
-
-void ewma_power_calculate_area(struct ewma_power *ewma, const int16_t *buf,
- struct cras_audio_area *area, unsigned int size)
-{
- int i, ch;
- float power, f;
-
- if (!ewma->enabled)
- return;
- for (i = 0; i < size; i += ewma->step_fr * area->num_channels) {
- power = 0.0f;
- for (ch = 0; ch < area->num_channels; ch++) {
- if (area->channels[ch].ch_set == 0)
- continue;
- f = buf[i + ch] / 32768.0f;
- power += f * f / area->num_channels;
- }
- if (!ewma->power_set) {
- ewma->power = power;
- ewma->power_set = 1;
- } else {
- ewma->power = smooth_factor * power +
- (1 - smooth_factor) * ewma->power;
- }
- }
-}
diff --git a/cras/src/server/ewma_power.h b/cras/src/server/ewma_power.h
deleted file mode 100644
index 78d2e504..00000000
--- a/cras/src/server/ewma_power.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Copyright 2020 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef EWMA_POWER_H_
-#define EWMA_POWER_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#include "cras_audio_area.h"
-
-/*
- * The exponentially weighted moving average power module used to
- * calculate the energe level in audio stream.
- * Members:
- * power_set - Flag to note if the first power value has set.
- * enabled - Flag to enable ewma calculation. Set to false to
- * make all calculations no-ops.
- * power - The power value.
- * step_fr - How many frames to sample one for EWMA calculation.
- */
-struct ewma_power {
- bool power_set;
- bool enabled;
- float power;
- unsigned int step_fr;
-};
-
-/*
- * Disables the ewma instance.
- */
-void ewma_power_disable(struct ewma_power *ewma);
-
-/*
- * Initializes the ewma_power object.
- * Args:
- * ewma - The ewma_power object to initialize.
- * rate - The sample rate of the audio data that the ewma object
- * will calculate power from.
- */
-void ewma_power_init(struct ewma_power *ewma, unsigned int rate);
-
-/*
- * Feeds an audio buffer to ewma_power object to calculate the
- * latest power value.
- * Args:
- * ewma - The ewma_power object to calculate power.
- * buf - Pointer to the audio data.
- * channels - Number of channels of the audio data.
- * size - Length in frames of the audio data.
- */
-void ewma_power_calculate(struct ewma_power *ewma, const int16_t *buf,
- unsigned int channels, unsigned int size);
-
-/*
- * Feeds non-interleaved audio data to ewma_power to calculate the
- * latest power value. This is similar to ewma_power_calculate but
- * accepts cras_audio_area.
- */
-void ewma_power_calculate_area(struct ewma_power *ewma, const int16_t *buf,
- struct cras_audio_area *area, unsigned int size);
-
-#endif /* EWMA_POWER_H_ */
diff --git a/cras/src/server/float_buffer.h b/cras/src/server/float_buffer.h
deleted file mode 100644
index ba3523d9..00000000
--- a/cras/src/server/float_buffer.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef FLOAT_BUFFER_H_
-#define FLOAT_BUFFER_H_
-
-#include "byte_buffer.h"
-
-/*
- * Circular buffer storing deinterleaved floating point data.
- * Members:
- * fp - Pointer to be filled wtih read/write position of the buffer.
- * num_channels - Number of channels.
- */
-struct float_buffer {
- struct byte_buffer *buf;
- float **fp;
- unsigned int num_channels;
-};
-
-/*
- * Creates an float_buffer.
- * Args:
- * max_size - The max number of frames this buffer may store.
- * num_channels - Number of channels of the deinterleaved data.
- */
-static inline struct float_buffer *
-float_buffer_create(unsigned int max_size, unsigned int num_channels)
-{
- struct float_buffer *b;
-
- b = (struct float_buffer *)calloc(1, sizeof(*b));
-
- b->num_channels = num_channels;
- b->fp = (float **)malloc(num_channels * sizeof(float *));
- b->buf = (struct byte_buffer *)calloc(
- 1, sizeof(struct byte_buffer) +
- sizeof(float) * max_size * num_channels);
- b->buf->max_size = max_size;
- b->buf->used_size = max_size;
- return b;
-}
-
-/* Destroys the float buffer. */
-static inline void float_buffer_destroy(struct float_buffer **b)
-{
- if (*b == NULL)
- return;
-
- byte_buffer_destroy(&(*b)->buf);
- free((*b)->fp);
- free(*b);
- *b = NULL;
-}
-
-/* Gets the write pointer of given float_buffer. */
-static inline float *const *float_buffer_write_pointer(struct float_buffer *b)
-{
- unsigned int i;
- float *data = (float *)b->buf->bytes;
-
- for (i = 0; i < b->num_channels; i++, data += b->buf->max_size)
- b->fp[i] = data + b->buf->write_idx;
- return b->fp;
-}
-
-/* Gets the number of frames can write to the float_buffer. */
-static inline unsigned int float_buffer_writable(struct float_buffer *b)
-{
- return buf_writable(b->buf);
-}
-
-/* Marks |nwritten| of frames as written to float_buffer. */
-static inline void float_buffer_written(struct float_buffer *b,
- unsigned int nwritten)
-{
- buf_increment_write(b->buf, nwritten);
-}
-
-/* Gets the read pointer of given float_buffer. */
-static inline float *const *float_buffer_read_pointer(struct float_buffer *b,
- unsigned int offset,
- unsigned int *readable)
-{
- unsigned int i;
- float *data = (float *)b->buf->bytes;
- unsigned int nread = buf_readable(b->buf);
-
- if (offset >= buf_queued(b->buf)) {
- *readable = 0;
- offset = 0;
- } else if (offset >= nread) {
- /* wraps */
- offset = offset + b->buf->read_idx - b->buf->max_size;
- *readable = MIN(*readable, b->buf->write_idx - offset);
- } else {
- *readable = MIN(*readable, nread - offset);
- offset += b->buf->read_idx;
- }
-
- for (i = 0; i < b->num_channels; i++, data += b->buf->max_size)
- b->fp[i] = data + offset;
- return b->fp;
-}
-
-/* Gets the buffer level in frames queued in float_buffer. */
-static inline unsigned int float_buffer_level(struct float_buffer *b)
-{
- return buf_queued(b->buf);
-}
-
-/* Resets float_buffer to initial state. */
-static inline void float_buffer_reset(struct float_buffer *b)
-{
- buf_reset(b->buf);
-}
-
-/* Marks |nread| frames as read in float_buffer. */
-static inline void float_buffer_read(struct float_buffer *b, unsigned int nread)
-{
- buf_increment_read(b->buf, nread);
-}
-
-#endif /* FLOAT_BUFFER_H_ */
diff --git a/cras/src/server/iniparser_wrapper.h b/cras/src/server/iniparser_wrapper.h
deleted file mode 100644
index 89a213bb..00000000
--- a/cras/src/server/iniparser_wrapper.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#ifndef INIPARSER_WRAPPER_H_
-#define INIPARSER_WRAPPER_H_
-
-#ifdef HAVE_INIPARSER_INIPARSER_H
-#include <iniparser/iniparser.h>
-#else
-#include <iniparser.h>
-#endif
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-/* Allocate 63 chars + 1 for null where declared. */
-#define MAX_INI_NAME_LENGTH 63
-#define MAX_INI_KEY_LENGTH 63 /* names like "output_source:output_0" */
-
-static inline dictionary *iniparser_load_wrapper(const char *ini_name)
-{
- struct stat st;
- int rc = stat(ini_name, &st);
- if (rc < 0)
- return NULL;
- return iniparser_load(ini_name);
-}
-
-#endif /* INIPARSER_WRAPPER_H_ */
diff --git a/cras/src/server/input_data.c b/cras/src/server/input_data.c
deleted file mode 100644
index cc0f10ba..00000000
--- a/cras/src/server/input_data.c
+++ /dev/null
@@ -1,210 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "buffer_share.h"
-#include "cras_audio_area.h"
-#include "cras_dsp_pipeline.h"
-#include "cras_mix.h"
-#include "cras_rstream.h"
-#include "cras_system_state.h"
-#include "dsp_util.h"
-#include "input_data.h"
-#include "utlist.h"
-
-void input_data_run(struct ext_dsp_module *ext, unsigned int nframes)
-{
- struct input_data *data = (struct input_data *)ext;
- float *const *wp;
- int i;
- unsigned int writable;
- unsigned int offset = 0;
-
- while (nframes) {
- writable = float_buffer_writable(data->fbuffer);
- writable = MIN(nframes, writable);
- if (!writable) {
- syslog(LOG_ERR,
- "Not enough space to process input data");
- break;
- }
- wp = float_buffer_write_pointer(data->fbuffer);
- for (i = 0; i < data->fbuffer->num_channels; i++)
- memcpy(wp[i], ext->ports[i] + offset,
- writable * sizeof(float));
-
- float_buffer_written(data->fbuffer, writable);
- nframes -= writable;
- offset += writable;
- }
-}
-
-void input_data_configure(struct ext_dsp_module *ext, unsigned int buffer_size,
- unsigned int num_channels, unsigned int rate)
-{
- struct input_data *data = (struct input_data *)ext;
-
- if (data->fbuffer)
- float_buffer_destroy(&data->fbuffer);
- data->fbuffer = float_buffer_create(buffer_size, num_channels);
-}
-
-struct input_data *input_data_create(void *dev_ptr)
-{
- struct input_data *data = (struct input_data *)calloc(1, sizeof(*data));
-
- data->dev_ptr = dev_ptr;
-
- data->ext.run = input_data_run;
- data->ext.configure = input_data_configure;
-
- return data;
-}
-
-void input_data_destroy(struct input_data **data)
-{
- if ((*data)->fbuffer)
- float_buffer_destroy(&(*data)->fbuffer);
- free(*data);
- *data = NULL;
-}
-
-void input_data_set_all_streams_read(struct input_data *data,
- unsigned int nframes)
-{
- if (!data->fbuffer)
- return;
-
- if (float_buffer_level(data->fbuffer) < nframes) {
- syslog(LOG_ERR,
- "All streams read %u frames exceeds %u"
- " in input_data's buffer",
- nframes, float_buffer_level(data->fbuffer));
- float_buffer_reset(data->fbuffer);
- return;
- }
- float_buffer_read(data->fbuffer, nframes);
-}
-
-/*
- * The logic is not trivial to return the cras_audio_area and offset for
- * a input stream to read. The buffer position and length of a bunch of
- * input member variables are described below.
- *
- * hw_ptr appl_ptr
- * a. buffer of input device: |------------------------|
- * b. fbuffer of input data: |<--------------->|
- * c. stream offset of input data: |<--------->|
- * stream offset of input data: |<-->|
- * stream offset of input data: |<------------->|
- * d. audio area of input data: |<----------->|
- *
- * One thing to keep in mind is, the offset could exceed the size of
- * buffer to read. It's not intuitive though why the stream offset would
- * exceed buffer size. Check this example:
- *
- * Idev gets input buffer 500 frames. One stream read 400, while the other
- * stream read 100. We track stream offset [0, 300] after both stream
- * consumes 100 frames. In the next wake up, audio thread asks idev to
- * get 250 frames. Now the input data holds audio area containing 250 frames
- * of audio as queried, while its float buffer contains 400 frames of audio
- * deinterleaved from last wake up.
- *
- * Wake up at T0:
- * hw_ptr appl_ptr
- * Input audio area |-------------------------------|
- * deinterleave float |-------------------------------|
- * Stream 1 read |------|
- * Stream 2 read |-----------------------|
- *
- * Wake up at T1:
- hw_ptr appl_ptr
- * Input audio area |------------|
- * deinterleave float |------------------------|
- * Stream 1 offset |
- * Stream 2 offset |----------------|
- *
- * Case 1:
- * A normal input stream, of read offset 0, about to read from device.
- * We shall return the exact audio area from idev, and set read offset to 0.
- *
- * Case 2:
- * A normal input stream, of read offset 300, about to read from device.
- * We shall return the exact audio area from idev but clip read offset to 250.
- *
- * Case 3:
- * An APM Stream of read offset 300, would like to read the deinterleaved
- * float buffer. We shall let APM process the float buffer from offset 300.
- * Don't bother clip read offset in this case, because fbuffer contains
- * the deepest deinterleaved audio data ever read from idev.
- */
-int input_data_get_for_stream(struct input_data *data,
- struct cras_rstream *stream,
- struct buffer_share *offsets,
- struct cras_audio_area **area,
- unsigned int *offset)
-{
- int apm_processed;
- struct cras_apm *apm;
- int stream_offset = buffer_share_id_offset(offsets, stream->stream_id);
-
- apm = cras_apm_list_get_active_apm(stream, data->dev_ptr);
- if (apm == NULL) {
- /*
- * Case 1 and 2 from above example.
- */
- *area = data->area;
- *offset = MIN(stream_offset, data->area->frames);
- } else {
- /*
- * Case 3 from above example.
- */
- apm_processed = cras_apm_list_process(apm, data->fbuffer,
- stream_offset);
- if (apm_processed < 0) {
- cras_apm_list_remove_apm(stream->apm_list, apm);
- return 0;
- }
- buffer_share_offset_update(offsets, stream->stream_id,
- apm_processed);
- *area = cras_apm_list_get_processed(apm);
- *offset = 0;
- }
-
- return 0;
-}
-
-int input_data_put_for_stream(struct input_data *data,
- struct cras_rstream *stream,
- struct buffer_share *offsets, unsigned int frames)
-{
- struct cras_apm *apm =
- cras_apm_list_get_active_apm(stream, data->dev_ptr);
-
- if (apm)
- cras_apm_list_put_processed(apm, frames);
- else
- buffer_share_offset_update(offsets, stream->stream_id, frames);
-
- return 0;
-}
-
-float input_data_get_software_gain_scaler(struct input_data *data,
- float idev_sw_gain_scaler,
- struct cras_rstream *stream)
-{
- struct cras_apm *apm;
- /*
- * APM has more advanced gain control mechanism. If it is using tuned
- * settings, give APM total control of the captured samples without
- * additional gain scaler at all.
- */
- apm = cras_apm_list_get_active_apm(stream, data->dev_ptr);
- if (apm && cras_apm_list_get_use_tuned_settings(apm))
- return 1.0f;
-
- return idev_sw_gain_scaler * cras_rstream_get_volume_scaler(stream);
-}
diff --git a/cras/src/server/input_data.h b/cras/src/server/input_data.h
deleted file mode 100644
index 7ac80be4..00000000
--- a/cras/src/server/input_data.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef INPUT_DATA_H_
-#define INPUT_DATA_H_
-
-#include "cras_dsp_pipeline.h"
-#include "float_buffer.h"
-
-/*
- * Structure holding the information used when a chunk of input buffer
- * is accessed by multiple streams with different properties and
- * processing requirements.
- * Member:
- * ext - Provides interface to read and process buffer in dsp pipeline.
- * dev_ptr - Pointer to the associated input iodev.
- * area - The audio area used for deinterleaved data copy.
- * fbuffer - Floating point buffer from input device.
- */
-struct input_data {
- struct ext_dsp_module ext;
- void *dev_ptr;
- struct cras_audio_area *area;
- struct float_buffer *fbuffer;
-};
-
-/*
- * Creates an input_data instance for input iodev.
- * Args:
- * dev_ptr - Pointer to the associated input device.
- */
-struct input_data *input_data_create(void *dev_ptr);
-
-/* Destroys an input_data instance. */
-void input_data_destroy(struct input_data **data);
-
-/* Sets how many frames in buffer has been read by all input streams. */
-void input_data_set_all_streams_read(struct input_data *data,
- unsigned int nframes);
-
-/*
- * Gets an audio area for |stream| to read data from. An input_data may be
- * accessed by multiple streams while some requires processing, the
- * |offsets| arguments helps track the offset value each stream has read
- * into |data|.
- * Args:
- * data - The input data to get audio area from.
- * stream - The stream that reads data.
- * offsets - Structure holding the mapping from stream to the offset value
- * of how many frames each stream has read into input buffer.
- * area - To be filled with a pointer to an audio area struct for stream to
- * read data.
- * offset - To be filled with the samples offset in |area| that |stream|
- * should start reading.
- */
-int input_data_get_for_stream(struct input_data *data,
- struct cras_rstream *stream,
- struct buffer_share *offsets,
- struct cras_audio_area **area,
- unsigned int *offset);
-
-/*
- * Marks |frames| of audio data as read by |stream|.
- * Args:
- * data - The input_data to mark frames has been read by |stream|.
- * stream - The stream that has read audio data.
- * offsets - Structure holding the mapping from stream to the offset value
- * of how many frames each stream has read into input buffer.
- * frames - Number of frames |stream| has read.
- */
-int input_data_put_for_stream(struct input_data *data,
- struct cras_rstream *stream,
- struct buffer_share *offsets,
- unsigned int frames);
-
-/*
- * The software gain scaler of input path consist of two parts:
- * (1) The device gain scaler used when lack of hardware gain control.
- * Configured by the IntrinsicSensitivity label in alsa UCM config.
- * (2) The gain scaler in cras_rstream set by app, for example the AGC
- * module in Chrome.
- * Args:
- * data - The input data that holds pointer to APM instance.
- * idev_sw_agin_scaler - The gain scaler configured on input iodev.
- * stream - To provide stream layer software gain.
- * Returns:
- * 1.0 if tuned APM in use, otherwise |iodev gain| * |cras_rstream gain|
- */
-float input_data_get_software_gain_scaler(struct input_data *data,
- float idev_sw_gain_scaler,
- struct cras_rstream *stream);
-
-#endif /* INPUT_DATA_H_ */
diff --git a/cras/src/server/linear_resampler.c b/cras/src/server/linear_resampler.c
deleted file mode 100644
index ed2b6d60..00000000
--- a/cras/src/server/linear_resampler.c
+++ /dev/null
@@ -1,171 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Author. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "cras_audio_area.h"
-#include "cras_util.h"
-#include "linear_resampler.h"
-
-/* A linear resampler.
- * Members:
- * num_channels - The number of channles in once frames.
- * format_bytes - The size of one frame in bytes.
- * src_offset - The accumulated offset for resampled src data.
- * dst_offset - The accumulated offset for resampled dst data.
- * to_times_100 - The numerator of the rate factor used for SRC.
- * from_times_100 - The denominator of the rate factor used for SRC.
- * f - The rate factor used for linear resample.
- */
-struct linear_resampler {
- unsigned int num_channels;
- unsigned int format_bytes;
- unsigned int src_offset;
- unsigned int dst_offset;
- unsigned int to_times_100;
- unsigned int from_times_100;
- float f;
-};
-
-struct linear_resampler *linear_resampler_create(unsigned int num_channels,
- unsigned int format_bytes,
- float src_rate, float dst_rate)
-{
- struct linear_resampler *lr;
-
- lr = (struct linear_resampler *)calloc(1, sizeof(*lr));
- if (!lr)
- return NULL;
- lr->num_channels = num_channels;
- lr->format_bytes = format_bytes;
-
- linear_resampler_set_rates(lr, src_rate, dst_rate);
-
- return lr;
-}
-
-void linear_resampler_destroy(struct linear_resampler *lr)
-{
- if (lr)
- free(lr);
-}
-
-void linear_resampler_set_rates(struct linear_resampler *lr, float from,
- float to)
-{
- lr->f = (float)to / from;
- lr->to_times_100 = to * 100;
- lr->from_times_100 = from * 100;
- lr->src_offset = 0;
- lr->dst_offset = 0;
-}
-
-/* Assuming the linear resampler transforms X frames of input buffer into
- * Y frames of output buffer. The resample method requires the last output
- * buffer at Y-1 be interpolated from input buffer in range (X-d, X-1) as
- * illustrated.
- * Input Index: ... X-1 <--floor--| X
- * Output Index: ... Y-1 |--ceiling-> Y
- *
- * That said, the calculation between input and output frames is based on
- * equations X-1 = floor(Y/f) and Y = ceil((X-1)*f). Note that in any case
- * when the resampled frames number isn't sufficient to consume the first
- * buffer at input or output offset(index 0), always count as one buffer
- * used so the intput/output offset can always increment.
- */
-unsigned int linear_resampler_out_frames_to_in(struct linear_resampler *lr,
- unsigned int frames)
-{
- float in_frames;
- if (frames == 0)
- return 0;
-
- in_frames = (float)(lr->dst_offset + frames) / lr->f;
- if ((in_frames > lr->src_offset))
- return 1 + (unsigned int)(in_frames - lr->src_offset);
- else
- return 1;
-}
-
-unsigned int linear_resampler_in_frames_to_out(struct linear_resampler *lr,
- unsigned int frames)
-{
- float out_frames;
- if (frames == 0)
- return 0;
-
- out_frames = lr->f * (lr->src_offset + frames - 1);
- if (out_frames > lr->dst_offset)
- return 1 + (unsigned int)(out_frames - lr->dst_offset);
- else
- return 1;
-}
-
-int linear_resampler_needed(struct linear_resampler *lr)
-{
- return lr->from_times_100 != lr->to_times_100;
-}
-
-unsigned int linear_resampler_resample(struct linear_resampler *lr,
- uint8_t *src, unsigned int *src_frames,
- uint8_t *dst, unsigned dst_frames)
-{
- int ch;
- unsigned int src_idx = 0;
- unsigned int dst_idx = 0;
- float src_pos;
- int16_t *in, *out;
-
- /* Check for corner cases so that we can assume both src_idx and
- * dst_idx are valid with value 0 in the loop below. */
- if (dst_frames == 0 || *src_frames == 0) {
- *src_frames = 0;
- return 0;
- }
-
- for (dst_idx = 0; dst_idx <= dst_frames; dst_idx++) {
- src_pos = (float)(lr->dst_offset + dst_idx) / lr->f;
- if (src_pos > lr->src_offset)
- src_pos -= lr->src_offset;
- else
- src_pos = 0;
- src_idx = (unsigned int)src_pos;
-
- if (src_pos > *src_frames - 1 || dst_idx >= dst_frames) {
- if (src_pos > *src_frames - 1)
- src_idx = *src_frames - 1;
- /* When this loop stops, dst_idx is always at the last
- * used index incremented by 1. */
- break;
- }
-
- in = (int16_t *)(src + src_idx * lr->format_bytes);
- out = (int16_t *)(dst + dst_idx * lr->format_bytes);
-
- /* Don't do linear interpolcation if src_pos falls on the
- * last index. */
- if (src_idx == *src_frames - 1) {
- for (ch = 0; ch < lr->num_channels; ch++)
- out[ch] = in[ch];
- } else {
- for (ch = 0; ch < lr->num_channels; ch++) {
- out[ch] = in[ch] +
- (src_pos - src_idx) *
- (in[lr->num_channels + ch] -
- in[ch]);
- }
- }
- }
-
- *src_frames = src_idx + 1;
-
- lr->src_offset += *src_frames;
- lr->dst_offset += dst_idx;
- while ((lr->src_offset > lr->from_times_100) &&
- (lr->dst_offset > lr->to_times_100)) {
- lr->src_offset -= lr->from_times_100;
- lr->dst_offset -= lr->to_times_100;
- }
-
- return dst_idx;
-}
diff --git a/cras/src/server/linear_resampler.h b/cras/src/server/linear_resampler.h
deleted file mode 100644
index 25eff2b5..00000000
--- a/cras/src/server/linear_resampler.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef LINEAR_RESAMPLER_H_
-#define LINEAR_RESAMPLER_H_
-
-struct linear_resampler;
-
-/* Creates a linear resampler.
- * Args:
- * num_channels - The number of channels in each frames.
- * format_bytes - The length of one frame in bytes.
- * src_rate - The source rate to resample from.
- * dst_rate - The destination rate to resample to.
- */
-struct linear_resampler *linear_resampler_create(unsigned int num_channels,
- unsigned int format_bytes,
- float src_rate,
- float dst_rate);
-
-/* Sets the rates for the linear resampler.
- * Args:
- * from - The rate to resample from.
- * to - The rate to resample to.
- */
-void linear_resampler_set_rates(struct linear_resampler *lr, float from,
- float to);
-
-/* Converts the frames count from output rate to input rate. */
-unsigned int linear_resampler_out_frames_to_in(struct linear_resampler *lr,
- unsigned int frames);
-
-/* Converts the frames count from input rate to output rate. */
-unsigned int linear_resampler_in_frames_to_out(struct linear_resampler *lr,
- unsigned int frames);
-
-/* Returns true if SRC is needed, otherwise return false. */
-int linear_resampler_needed(struct linear_resampler *lr);
-
-/* Run linear resample for audio samples.
- * Args:
- * lr - The linear resampler.
- * src - The input buffer.
- * src_frames - The number of frames of input buffer.
- * dst - The output buffer.
- * dst_frames - The number of frames of output buffer.
- */
-unsigned int linear_resampler_resample(struct linear_resampler *lr,
- uint8_t *src, unsigned int *src_frames,
- uint8_t *dst, unsigned dst_frames);
-
-/* Destroy a linear resampler. */
-void linear_resampler_destroy(struct linear_resampler *lr);
-
-#endif /* LINEAR_RESAMPLER_H_ */
diff --git a/cras/src/server/polled_interval_checker.c b/cras/src/server/polled_interval_checker.c
deleted file mode 100644
index 37f93684..00000000
--- a/cras/src/server/polled_interval_checker.c
+++ /dev/null
@@ -1,53 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include "cras_util.h"
-#include "polled_interval_checker.h"
-
-struct polled_interval {
- struct timespec last_interval_start_ts;
- int interval_sec;
-};
-
-static struct timespec now;
-
-static inline int
-get_sec_since_last_active(const struct timespec *last_active_ts)
-{
- struct timespec diff;
- subtract_timespecs(&now, last_active_ts, &diff);
- return diff.tv_sec;
-}
-
-void pic_update_current_time()
-{
- clock_gettime(CLOCK_MONOTONIC_RAW, &now);
-}
-
-struct polled_interval *pic_polled_interval_create(int interval_sec)
-{
- struct polled_interval *pi;
- pi = malloc(sizeof(*pi));
- pi->last_interval_start_ts = now;
- pi->interval_sec = interval_sec;
- return pi;
-}
-
-void pic_polled_interval_destroy(struct polled_interval **interval)
-{
- free(*interval);
- *interval = NULL;
-}
-
-int pic_interval_elapsed(const struct polled_interval *pi)
-{
- return get_sec_since_last_active(&pi->last_interval_start_ts) >=
- pi->interval_sec;
-}
-
-void pic_interval_reset(struct polled_interval *pi)
-{
- pi->last_interval_start_ts = now;
-} \ No newline at end of file
diff --git a/cras/src/server/polled_interval_checker.h b/cras/src/server/polled_interval_checker.h
deleted file mode 100644
index 1b4619d8..00000000
--- a/cras/src/server/polled_interval_checker.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef POLLED_ACTIVITY_CHECKER_H_
-#define POLLED_ACTIVITY_CHECKER_H_
-
-#include <time.h>
-
-/* Represents a time interval, in seconds, which can be checked periodically. */
-struct polled_interval;
-
-/*
- * Creates a new polled_interval, of the specified duration. The interval will
- * first elapse interval_sec after it was created.
- *
- * Call pic_update_current_time() shortly before this function.
- */
-struct polled_interval *pic_polled_interval_create(int interval_sec);
-
-/*
- * Destroys the specified polled_interval, and set's the pointer to it to NULL.
- */
-void pic_polled_interval_destroy(struct polled_interval **interval);
-
-/*
- * Whether the interval's duration has elapsed (since the interval was created
- * or reset).
- *
- * Call pic_update_current_time() shortly before this function.
- */
-int pic_interval_elapsed(const struct polled_interval *interval);
-
-/*
- * Resets the interval; it will elapse it's specified duration from now.
- *
- * Call pic_update_current_time() shortly before this function.
- */
-void pic_interval_reset(struct polled_interval *pi);
-
-/*
- * Updates the current time, which is used in all other pic_* functions (which
- * will never update the current time). This update is pulled out separately to
- * allow the caller to control when and how often the time is updated.
- */
-void pic_update_current_time();
-
-#endif /* POLLED_ACTIVITY_CHECKER_H_ */ \ No newline at end of file
diff --git a/cras/src/server/rust/.gitignore b/cras/src/server/rust/.gitignore
deleted file mode 100644
index 2f7896d1..00000000
--- a/cras/src/server/rust/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-target/
diff --git a/cras/src/server/rust/Cargo.toml b/cras/src/server/rust/Cargo.toml
deleted file mode 100644
index afebda83..00000000
--- a/cras/src/server/rust/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "cras_rust"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-
-[lib]
-path = "src/rate_estimator.rs"
-crate-type = ["staticlib"]
-
-[dependencies]
-libc = "0.2.44"
-
-[profile.release]
-lto = true
-panic = "abort"
-overflow-checks = true
diff --git a/cras/src/server/rust/binding_generator/Cargo.toml b/cras/src/server/rust/binding_generator/Cargo.toml
deleted file mode 100644
index 1ec73483..00000000
--- a/cras/src/server/rust/binding_generator/Cargo.toml
+++ /dev/null
@@ -1,8 +0,0 @@
-[package]
-name = "binding_generator"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-
-[dependencies]
-cbindgen = "*"
diff --git a/cras/src/server/rust/binding_generator/src/main.rs b/cras/src/server/rust/binding_generator/src/main.rs
deleted file mode 100644
index f7803968..00000000
--- a/cras/src/server/rust/binding_generator/src/main.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-extern crate cbindgen;
-
-use cbindgen::Builder;
-
-const HEADER: &str = "// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Generated from files in cras/src/server/rust/src in adhd.";
-
-fn main() {
- Builder::new()
- .with_src("../src/rate_estimator.rs")
- .rename_item("RateEstimator", "rate_estimator")
- .rename_item("timespec", "struct timespec")
- .with_no_includes()
- .with_sys_include("time.h")
- .with_include_guard("RATE_ESTIMATOR_H_")
- .with_language(cbindgen::Language::C)
- .with_header(HEADER)
- .generate()
- .expect("Unable to generate bindings")
- .write_to_file("../src/headers/rate_estimator.h");
-}
diff --git a/cras/src/server/rust/src/headers/rate_estimator.h b/cras/src/server/rust/src/headers/rate_estimator.h
deleted file mode 100644
index 3ac9cfa9..00000000
--- a/cras/src/server/rust/src/headers/rate_estimator.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Generated from files in cras/src/server/rust/src in adhd.
-
-#ifndef RATE_ESTIMATOR_H_
-#define RATE_ESTIMATOR_H_
-
-#include <time.h>
-
-/**
- * An estimator holding the required information to determine the actual frame
- * rate of an audio device.
- *
- * # Members
- * * `last_level` - Buffer level of the audio device at last check time.
- * * `level_diff` - Number of frames written to or read from audio device
- * since the last check time. Rate estimator will use this
- * change plus the difference of buffer level to derive the
- * number of frames audio device has actually processed.
- * * `window_start` - The start time of the current window.
- * * `window_size` - The size of the window.
- * * `window_frames` - The number of frames accumulated in current window.
- * * `lsq` - The helper used to estimate sample rate.
- * * `smooth_factor` - A scaling factor used to average the previous and new
- * rate estimates to ensure that estimates do not change
- * too quickly.
- * * `estimated_rate` - The estimated rate at which samples are consumed.
- */
-typedef struct rate_estimator rate_estimator;
-
-/**
- * # Safety
- *
- * To use this function safely, `re` must be a pointer returned from
- * rate_estimator_create, or null.
- */
-void rate_estimator_add_frames(rate_estimator *re, int frames);
-
-/**
- * # Safety
- *
- * To use this function safely, `re` must be a pointer returned from
- * rate_estimator_create, or null, and `now` must be a valid pointer to a
- * timespec.
- */
-int32_t rate_estimator_check(rate_estimator *re, int level,
- const struct timespec *now);
-
-/**
- * # Safety
- *
- * To use this function safely, `window_size` must be a valid pointer to a
- * timespec.
- */
-rate_estimator *rate_estimator_create(unsigned int rate,
- const struct timespec *window_size,
- double smooth_factor);
-
-/**
- * # Safety
- *
- * To use this function safely, `re` must be a pointer returned from
- * rate_estimator_create, or null.
- */
-void rate_estimator_destroy(rate_estimator *re);
-
-/**
- * # Safety
- *
- * To use this function safely, `re` must be a pointer returned from
- * rate_estimator_create, or null.
- */
-double rate_estimator_get_rate(const rate_estimator *re);
-
-/**
- * # Safety
- *
- * To use this function safely, `re` must be a pointer returned from
- * rate_estimator_create, or null.
- */
-void rate_estimator_reset_rate(rate_estimator *re, unsigned int rate);
-
-#endif /* RATE_ESTIMATOR_H_ */
diff --git a/cras/src/server/rust/src/rate_estimator.rs b/cras/src/server/rust/src/rate_estimator.rs
deleted file mode 100644
index 585f346b..00000000
--- a/cras/src/server/rust/src/rate_estimator.rs
+++ /dev/null
@@ -1,188 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-pub mod rate_estimator_bindings;
-
-use std::error;
-use std::fmt;
-use std::time::Duration;
-
-#[derive(Debug)]
-pub enum Error {
- InvalidSmoothFactor(f64),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- InvalidSmoothFactor(sf) => write!(f, "Smooth factor {} is not between 0.0 and 1.0", sf),
- }
- }
-}
-
-type Result<T> = std::result::Result<T, Error>;
-
-const MAX_RATE_SKEW: f64 = 100.0;
-
-/// Hold information to calculate linear least square from
-/// several (x, y) samples.
-#[derive(Debug, Default)]
-struct LeastSquares {
- sum_x: f64,
- sum_y: f64,
- sum_xy: f64,
- sum_x2: f64,
- num_samples: u32,
-}
-
-impl LeastSquares {
- fn new() -> Self {
- Self::default()
- }
-
- fn add_sample(&mut self, x: f64, y: f64) {
- self.sum_x += x;
- self.sum_y += y;
- self.sum_xy += x * y;
- self.sum_x2 += x * x;
- self.num_samples += 1;
- }
-
- fn best_fit_slope(&self) -> f64 {
- let num = self.num_samples as f64 * self.sum_xy - self.sum_x * self.sum_y;
- let den = self.num_samples as f64 * self.sum_x2 - self.sum_x * self.sum_x;
- num / den
- }
-}
-
-/// An estimator holding the required information to determine the actual frame
-/// rate of an audio device.
-///
-/// # Members
-/// * `last_level` - Buffer level of the audio device at last check time.
-/// * `level_diff` - Number of frames written to or read from audio device
-/// since the last check time. Rate estimator will use this
-/// change plus the difference of buffer level to derive the
-/// number of frames audio device has actually processed.
-/// * `window_start` - The start time of the current window.
-/// * `window_size` - The size of the window.
-/// * `window_frames` - The number of frames accumulated in current window.
-/// * `lsq` - The helper used to estimate sample rate.
-/// * `smooth_factor` - A scaling factor used to average the previous and new
-/// rate estimates to ensure that estimates do not change
-/// too quickly.
-/// * `estimated_rate` - The estimated rate at which samples are consumed.
-pub struct RateEstimator {
- last_level: i32,
- level_diff: i32,
- window_start: Option<Duration>,
- window_size: Duration,
- window_frames: u32,
- lsq: LeastSquares,
- smooth_factor: f64,
- estimated_rate: f64,
-}
-
-impl RateEstimator {
- /// Creates a rate estimator.
- ///
- /// # Arguments
- /// * `rate` - The initial value to estimate rate from.
- /// * `window_size` - The window size of the rate estimator.
- /// * `smooth_factor` - The coefficient used to calculate moving average
- /// from old estimated rate values. Must be between
- /// 0.0 and 1.0
- ///
- /// # Errors
- /// * If `smooth_factor` is not between 0.0 and 1.0
- pub fn try_new(rate: u32, window_size: Duration, smooth_factor: f64) -> Result<Self> {
- if smooth_factor < 0.0 || smooth_factor > 1.0 {
- return Err(Error::InvalidSmoothFactor(smooth_factor));
- }
-
- Ok(RateEstimator {
- last_level: 0,
- level_diff: 0,
- window_start: None,
- window_size,
- window_frames: 0,
- lsq: LeastSquares::new(),
- smooth_factor,
- estimated_rate: rate as f64,
- })
- }
-
- /// Resets the estimated rate
- ///
- /// Reset the estimated rate to `rate`, and erase all collected data.
- pub fn reset_rate(&mut self, rate: u32) {
- self.last_level = 0;
- self.level_diff = 0;
- self.window_start = None;
- self.window_frames = 0;
- self.lsq = LeastSquares::new();
- self.estimated_rate = rate as f64;
- }
-
- /// Adds additional frames transmitted to/from audio device.
- ///
- /// # Arguments
- /// * `frames` - The number of frames written to the device. For input,
- /// this should be negative to indicate how many samples
- /// were read.
- pub fn add_frames(&mut self, frames: i32) {
- self.level_diff += frames;
- }
-
- /// Gets the estimated rate.
- pub fn get_estimated_rate(&self) -> f64 {
- self.estimated_rate
- }
-
- /// Check the timestamp and buffer level difference since last check time,
- /// and use them as a new sample to update the estimated rate.
- ///
- /// # Arguments
- /// * `level` - The current buffer level of audio device.
- /// * `now` - The time at which this function is called.
- ///
- /// # Returns
- /// True if the estimated rate is updated and window is reset,
- /// otherwise false.
- pub fn update_estimated_rate(&mut self, level: i32, now: Duration) -> bool {
- let start = match self.window_start {
- None => {
- self.window_start = Some(now);
- return false;
- }
- Some(t) => t,
- };
-
- let delta = match now.checked_sub(start) {
- Some(d) => d,
- None => return false,
- };
- self.window_frames += (self.last_level - level + self.level_diff).abs() as u32;
- self.level_diff = 0;
- self.last_level = level;
-
- let secs = (delta.as_secs() as f64) + delta.subsec_nanos() as f64 / 1_000_000_000.0;
- self.lsq.add_sample(secs, self.window_frames as f64);
- if delta > self.window_size && self.lsq.num_samples > 1 {
- let rate = self.lsq.best_fit_slope();
- if (self.estimated_rate - rate).abs() < MAX_RATE_SKEW {
- self.estimated_rate =
- rate * (1.0 - self.smooth_factor) + self.estimated_rate * self.smooth_factor;
- }
- self.lsq = LeastSquares::new();
- self.window_start = Some(now);
- self.window_frames = 0;
- return true;
- }
- false
- }
-}
diff --git a/cras/src/server/rust/src/rate_estimator_bindings.rs b/cras/src/server/rust/src/rate_estimator_bindings.rs
deleted file mode 100644
index 3073ba73..00000000
--- a/cras/src/server/rust/src/rate_estimator_bindings.rs
+++ /dev/null
@@ -1,110 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-use std::time::Duration;
-
-use libc;
-
-use crate::RateEstimator;
-
-/// # Safety
-///
-/// To use this function safely, `window_size` must be a valid pointer to a
-/// timespec.
-#[no_mangle]
-pub unsafe extern "C" fn rate_estimator_create(
- rate: libc::c_uint,
- window_size: *const libc::timespec,
- smooth_factor: libc::c_double,
-) -> *mut RateEstimator {
- if window_size.is_null() {
- return std::ptr::null_mut::<RateEstimator>();
- }
-
- let ts = &*window_size;
- let window = Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32);
-
- match RateEstimator::try_new(rate, window, smooth_factor) {
- Ok(re) => Box::into_raw(Box::new(re)),
- Err(_) => std::ptr::null_mut::<RateEstimator>(),
- }
-}
-
-/// # Safety
-///
-/// To use this function safely, `re` must be a pointer returned from
-/// rate_estimator_create, or null.
-#[no_mangle]
-pub unsafe extern "C" fn rate_estimator_destroy(re: *mut RateEstimator) {
- if re.is_null() {
- return;
- }
-
- drop(Box::from_raw(re));
-}
-
-/// # Safety
-///
-/// To use this function safely, `re` must be a pointer returned from
-/// rate_estimator_create, or null.
-#[no_mangle]
-pub unsafe extern "C" fn rate_estimator_add_frames(re: *mut RateEstimator, frames: libc::c_int) {
- if re.is_null() {
- return;
- }
-
- (*re).add_frames(frames)
-}
-
-/// # Safety
-///
-/// To use this function safely, `re` must be a pointer returned from
-/// rate_estimator_create, or null, and `now` must be a valid pointer to a
-/// timespec.
-#[no_mangle]
-pub unsafe extern "C" fn rate_estimator_check(
- re: *mut RateEstimator,
- level: libc::c_int,
- now: *const libc::timespec,
-) -> i32 {
- if re.is_null() || now.is_null() {
- return 0;
- }
-
- let ts = &*now;
- if ts.tv_sec < 0 || ts.tv_nsec < 0 {
- return 0;
- }
- let secs = ts.tv_sec as u64 + (ts.tv_nsec / 1_000_000_000) as u64;
- let nsecs = (ts.tv_nsec % 1_000_000_000) as u32;
- let now = Duration::new(secs, nsecs);
-
- (*re).update_estimated_rate(level, now) as i32
-}
-
-/// # Safety
-///
-/// To use this function safely, `re` must be a pointer returned from
-/// rate_estimator_create, or null.
-#[no_mangle]
-pub unsafe extern "C" fn rate_estimator_get_rate(re: *const RateEstimator) -> libc::c_double {
- if re.is_null() {
- return 0.0;
- }
-
- (*re).get_estimated_rate()
-}
-
-/// # Safety
-///
-/// To use this function safely, `re` must be a pointer returned from
-/// rate_estimator_create, or null.
-#[no_mangle]
-pub unsafe extern "C" fn rate_estimator_reset_rate(re: *mut RateEstimator, rate: libc::c_uint) {
- if re.is_null() {
- return;
- }
-
- (*re).reset_rate(rate)
-}
diff --git a/cras/src/server/server_stream.c b/cras/src/server/server_stream.c
deleted file mode 100644
index 36d5496e..00000000
--- a/cras/src/server/server_stream.c
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-
-#include "cras_rstream.h"
-#include "cras_server.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-#include "server_stream.h"
-#include "stream_list.h"
-
-/* Parameters used for server stream. */
-static unsigned int server_stream_block_size = 480;
-
-/*
- * Information of a stream created by server. Currently only
- * one server stream is allowed, for echo reference use.
- */
-static struct cras_rstream_config *stream_config;
-
-/* Actually create the server stream and add to stream list. */
-static void server_stream_add_cb(void *data)
-{
- struct stream_list *stream_list = (struct stream_list *)data;
- struct cras_rstream *stream;
-
- if (!stream_config)
- return;
-
- stream_list_add(stream_list, stream_config, &stream);
-}
-
-void server_stream_create(struct stream_list *stream_list, unsigned int dev_idx,
- struct cras_audio_format *format)
-{
- int audio_fd = -1;
- int client_shm_fd = -1;
- uint64_t buffer_offsets[2] = { 0, 0 };
-
- if (stream_config) {
- syslog(LOG_ERR, "server stream already exists, dev %u",
- stream_config->dev_idx);
- return;
- }
-
- stream_config =
- (struct cras_rstream_config *)calloc(1, sizeof(*stream_config));
- cras_rstream_config_init(
- /*client=*/NULL, cras_get_stream_id(SERVER_STREAM_CLIENT_ID, 0),
- CRAS_STREAM_TYPE_DEFAULT, CRAS_CLIENT_TYPE_SERVER_STREAM,
- CRAS_STREAM_INPUT, dev_idx,
- /*flags=*/SERVER_ONLY,
- /*effects=*/0, format, server_stream_block_size,
- server_stream_block_size, &audio_fd, &client_shm_fd,
- /*client_shm_size=*/0, buffer_offsets, stream_config);
-
- /* Schedule add stream in next main thread loop. */
- cras_system_add_task(server_stream_add_cb, stream_list);
-}
-
-static void server_stream_rm_cb(void *data)
-{
- struct stream_list *stream_list = (struct stream_list *)data;
-
- if (stream_config == NULL)
- return;
-
- if (stream_list_rm(stream_list, stream_config->stream_id))
- syslog(LOG_ERR, "Server stream %x no longer exist",
- stream_config->stream_id);
-
- free(stream_config);
- stream_config = NULL;
-}
-
-void server_stream_destroy(struct stream_list *stream_list,
- unsigned int dev_idx)
-{
- if (!stream_config || stream_config->dev_idx != dev_idx) {
- syslog(LOG_ERR, "No server stream to destroy");
- return;
- }
- server_stream_rm_cb(stream_list);
-}
diff --git a/cras/src/server/server_stream.h b/cras/src/server/server_stream.h
deleted file mode 100644
index e1eb8e10..00000000
--- a/cras/src/server/server_stream.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SERVER_STREAM_H_
-#define SERVER_STREAM_H_
-
-struct stream_list;
-
-/*
- * Asynchronously creates a server stream pinned to device of given idx.
- * Args:
- * stream_list - List of stream to add new server stream to.
- * dev_idx - The id of the device that new server stream will pin to.
- */
-void server_stream_create(struct stream_list *stream_list, unsigned int dev_idx,
- struct cras_audio_format *format);
-
-/*
- * Asynchronously destroys existing server stream pinned to device of given idx.
- * Args:
- * stream_list - List of stream to look up server stream.
- * dev_idx - The device id that target server stream is pinned to.
- **/
-void server_stream_destroy(struct stream_list *stream_list,
- unsigned int dev_idx);
-
-#endif /* SERVER_STREAM_H_ */
diff --git a/cras/src/server/softvol_curve.c b/cras/src/server/softvol_curve.c
deleted file mode 100644
index e4467ef9..00000000
--- a/cras/src/server/softvol_curve.c
+++ /dev/null
@@ -1,62 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stddef.h>
-#include <stdlib.h>
-
-#include "cras_volume_curve.h"
-#include "softvol_curve.h"
-
-/* This is a ramp that increases 0.5dB per step, for a total range of 50dB. */
-const float softvol_scalers[101] = {
- 0.003162, /* volume 0 */
- 0.003350, 0.003548, 0.003758, 0.003981, 0.004217, 0.004467, 0.004732,
- 0.005012, 0.005309, 0.005623, 0.005957, 0.006310, 0.006683, 0.007079,
- 0.007499, 0.007943, 0.008414, 0.008913, 0.009441, 0.010000, 0.010593,
- 0.011220, 0.011885, 0.012589, 0.013335, 0.014125, 0.014962, 0.015849,
- 0.016788, 0.017783, 0.018836, 0.019953, 0.021135, 0.022387, 0.023714,
- 0.025119, 0.026607, 0.028184, 0.029854, 0.031623, 0.033497, 0.035481,
- 0.037584, 0.039811, 0.042170, 0.044668, 0.047315, 0.050119, 0.053088,
- 0.056234, 0.059566, 0.063096, 0.066834, 0.070795, 0.074989, 0.079433,
- 0.084140, 0.089125, 0.094406, 0.100000, 0.105925, 0.112202, 0.118850,
- 0.125893, 0.133352, 0.141254, 0.149624, 0.158489, 0.167880, 0.177828,
- 0.188365, 0.199526, 0.211349, 0.223872, 0.237137, 0.251189, 0.266073,
- 0.281838, 0.298538, 0.316228, 0.334965, 0.354813, 0.375837, 0.398107,
- 0.421697, 0.446684, 0.473151, 0.501187, 0.530884, 0.562341, 0.595662,
- 0.630957, 0.668344, 0.707946, 0.749894, 0.794328, 0.841395, 0.891251,
- 0.944061, 1.000000, /* volume 100 */
-};
-
-float *softvol_build_from_curve(const struct cras_volume_curve *curve)
-{
- float *scalers;
- unsigned int volume;
-
- if (!curve)
- return NULL;
-
- scalers = (float *)malloc(NUM_VOLUME_STEPS * sizeof(float));
- if (!scalers)
- return NULL;
-
- /* When software volume is used, it is assumed all volume curve values
- * are relative to 0 dBFS when converting to scale. If a positive dBFS
- * value is specified in curve config, it will be treated as invalid
- * and clip to 1.0 in scale.
- */
- for (volume = 0; volume <= MAX_VOLUME; volume++) {
- scalers[volume] = convert_softvol_scaler_from_dB(
- curve->get_dBFS(curve, volume));
- if (scalers[volume] > 1.0)
- scalers[volume] = 1.0;
- /* Clip scalers so that all values are non-zero to make volume
- * ramping simpler. Because of how mix_ops treats small values,
- * this should be effectively the same as a 0 value. */
- else if (scalers[volume] < 1e-7)
- scalers[volume] = 1e-7;
- }
-
- return scalers;
-}
diff --git a/cras/src/server/softvol_curve.h b/cras/src/server/softvol_curve.h
deleted file mode 100644
index 4fc2f40c..00000000
--- a/cras/src/server/softvol_curve.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SOFTVOL_CURVE_H_
-#define SOFTVOL_CURVE_H_
-
-#include <math.h>
-
-#define LOG_10 2.302585
-
-struct cras_volume_curve;
-
-extern const float softvol_scalers[101];
-
-/* Returns the volume scaler in the soft volume curve for the given index. */
-static inline float softvol_get_scaler(unsigned int volume_index)
-{
- return softvol_scalers[volume_index];
-}
-
-/* convert dBFS to softvol scaler */
-static inline float convert_softvol_scaler_from_dB(long dBFS)
-{
- return expf(LOG_10 * dBFS / 2000);
-}
-
-/* Builds software volume scalers from volume curve. */
-float *softvol_build_from_curve(const struct cras_volume_curve *curve);
-
-#endif /* SOFTVOL_CURVE_H_ */
diff --git a/cras/src/server/stream_list.c b/cras/src/server/stream_list.c
deleted file mode 100644
index 04ef9fe1..00000000
--- a/cras/src/server/stream_list.c
+++ /dev/null
@@ -1,188 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <syslog.h>
-#include "cras_rstream.h"
-#include "cras_tm.h"
-#include "cras_types.h"
-#include "stream_list.h"
-#include "utlist.h"
-
-/*
- * If the time difference of two streams is short than 10s, they may be the RTC
- * streams.
- */
-static const struct timespec RTC_STREAM_THRESHOLD = { 10, 0 };
-
-struct stream_list {
- struct cras_rstream *streams;
- struct cras_rstream *streams_to_delete;
- stream_callback *stream_added_cb;
- stream_callback *stream_removed_cb;
- stream_create_func *stream_create_cb;
- stream_destroy_func *stream_destroy_cb;
- struct cras_tm *timer_manager;
- struct cras_timer *drain_timer;
-};
-
-static void delete_streams(struct cras_timer *timer, void *data)
-{
- struct cras_rstream *to_delete;
- struct stream_list *list = (struct stream_list *)data;
- int max_drain_delay = 0;
-
- DL_FOREACH (list->streams_to_delete, to_delete) {
- int drain_delay;
-
- drain_delay = list->stream_removed_cb(to_delete);
- if (drain_delay) {
- max_drain_delay = MAX(max_drain_delay, drain_delay);
- continue;
- }
- DL_DELETE(list->streams_to_delete, to_delete);
- list->stream_destroy_cb(to_delete);
- }
-
- list->drain_timer = NULL;
- if (max_drain_delay)
- list->drain_timer =
- cras_tm_create_timer(list->timer_manager,
- MAX(max_drain_delay, 10),
- delete_streams, list);
-}
-
-/*
- * Exported Interface
- */
-
-struct stream_list *stream_list_create(stream_callback *add_cb,
- stream_callback *rm_cb,
- stream_create_func *create_cb,
- stream_destroy_func *destroy_cb,
- struct cras_tm *timer_manager)
-{
- struct stream_list *list = calloc(1, sizeof(struct stream_list));
-
- list->stream_added_cb = add_cb;
- list->stream_removed_cb = rm_cb;
- list->stream_create_cb = create_cb;
- list->stream_destroy_cb = destroy_cb;
- list->timer_manager = timer_manager;
- return list;
-}
-
-void stream_list_destroy(struct stream_list *list)
-{
- free(list);
-}
-
-struct cras_rstream *stream_list_get(struct stream_list *list)
-{
- return list->streams;
-}
-
-int stream_list_add(struct stream_list *list,
- struct cras_rstream_config *stream_config,
- struct cras_rstream **stream)
-{
- int rc;
- struct cras_rstream *next_stream;
-
- rc = list->stream_create_cb(stream_config, stream);
- if (rc)
- return rc;
-
- /* Keep stream list in descending order by channel count. */
- DL_FOREACH (list->streams, next_stream) {
- if ((*stream)->format.num_channels >=
- next_stream->format.num_channels)
- break;
- }
- DL_INSERT(list->streams, next_stream, *stream);
- rc = list->stream_added_cb(*stream);
- if (rc) {
- DL_DELETE(list->streams, *stream);
- list->stream_destroy_cb(*stream);
- }
-
- return rc;
-}
-
-int stream_list_rm(struct stream_list *list, cras_stream_id_t id)
-{
- struct cras_rstream *to_remove;
-
- DL_SEARCH_SCALAR(list->streams, to_remove, stream_id, id);
- if (!to_remove)
- return -EINVAL;
- DL_DELETE(list->streams, to_remove);
- DL_APPEND(list->streams_to_delete, to_remove);
- if (list->drain_timer) {
- cras_tm_cancel_timer(list->timer_manager, list->drain_timer);
- list->drain_timer = NULL;
- }
- delete_streams(NULL, list);
-
- return 0;
-}
-
-int stream_list_rm_all_client_streams(struct stream_list *list,
- struct cras_rclient *rclient)
-{
- struct cras_rstream *to_remove;
- int rc = 0;
-
- DL_FOREACH (list->streams, to_remove) {
- if (to_remove->client == rclient) {
- DL_DELETE(list->streams, to_remove);
- DL_APPEND(list->streams_to_delete, to_remove);
- }
- }
- if (list->drain_timer) {
- cras_tm_cancel_timer(list->timer_manager, list->drain_timer);
- list->drain_timer = NULL;
- }
- delete_streams(NULL, list);
-
- return rc;
-}
-
-bool stream_list_has_pinned_stream(struct stream_list *list,
- unsigned int dev_idx)
-{
- struct cras_rstream *rstream;
- DL_FOREACH (list->streams, rstream) {
- if (!rstream->is_pinned)
- continue;
- if (rstream->pinned_dev_idx == dev_idx)
- return true;
- }
- return false;
-}
-
-void detect_rtc_stream_pair(struct stream_list *list,
- struct cras_rstream *stream)
-{
- struct cras_rstream *next_stream;
- if (stream->cb_threshold != 480)
- return;
- if (stream->client_type != CRAS_CLIENT_TYPE_CHROME &&
- stream->client_type != CRAS_CLIENT_TYPE_LACROS)
- return;
- DL_FOREACH (list->streams, next_stream) {
- if (next_stream->cb_threshold == 480 &&
- next_stream->direction != stream->direction &&
- next_stream->client_type == stream->client_type &&
- timespec_diff_shorter_than(&stream->start_ts,
- &next_stream->start_ts,
- &RTC_STREAM_THRESHOLD)) {
- stream->stream_type =
- CRAS_STREAM_TYPE_VOICE_COMMUNICATION;
- next_stream->stream_type =
- CRAS_STREAM_TYPE_VOICE_COMMUNICATION;
- return;
- }
- }
-}
diff --git a/cras/src/server/stream_list.h b/cras/src/server/stream_list.h
deleted file mode 100644
index a527bc97..00000000
--- a/cras/src/server/stream_list.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <stdbool.h>
-
-#include "cras_types.h"
-#include "utlist.h"
-
-struct cras_rclient;
-struct cras_rstream;
-struct cras_rstream_config;
-struct cras_audio_format;
-struct stream_list;
-
-typedef int(stream_callback)(struct cras_rstream *rstream);
-/* This function will mutably borrow stream_config. */
-typedef int(stream_create_func)(struct cras_rstream_config *stream_config,
- struct cras_rstream **rstream);
-typedef void(stream_destroy_func)(struct cras_rstream *rstream);
-
-struct stream_list *stream_list_create(stream_callback *add_cb,
- stream_callback *rm_cb,
- stream_create_func *create_cb,
- stream_destroy_func *destroy_cb,
- struct cras_tm *timer_manager);
-
-void stream_list_destroy(struct stream_list *list);
-
-struct cras_rstream *stream_list_get(struct stream_list *list);
-
-/* Creates a cras_rstream from cras_rstream_config and inserts the cras_rstream
- * to stream_list in descending order by channel count.
- *
- * Args:
- * list - stream_list to add streams.
- * stream_config - A mutable borrow of cras_rstream_config.
- * stream - A pointer to place created cras_rstream.
- *
- * Returns:
- * 0 on success. Negative error code on failure.
- */
-int stream_list_add(struct stream_list *list,
- struct cras_rstream_config *stream_config,
- struct cras_rstream **stream);
-
-int stream_list_rm(struct stream_list *list, cras_stream_id_t id);
-
-int stream_list_rm_all_client_streams(struct stream_list *list,
- struct cras_rclient *rclient);
-
-/*
- * Checks if there is a stream pinned to the given device.
- */
-bool stream_list_has_pinned_stream(struct stream_list *list,
- unsigned int dev_idx);
-
-/*
- * Detects whether there is a RTC stream pair based on these rules:
- * 1. The cb_threshold is 480.
- * 2. The direction of two streams are opposite.
- * 3. Two streams are from the same client. (Chrome or LaCrOS)
- * 4. The start time of two streams are close enough. (shorter than 1s)
- * If all rules are passed, set the stream type to the voice communication.
- */
-void detect_rtc_stream_pair(struct stream_list *list,
- struct cras_rstream *stream);
diff --git a/cras/src/server/test_iodev.c b/cras/src/server/test_iodev.c
deleted file mode 100644
index cb7d5f3a..00000000
--- a/cras/src/server/test_iodev.c
+++ /dev/null
@@ -1,267 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <sys/ioctl.h>
-#include <pthread.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include "audio_thread.h"
-#include "byte_buffer.h"
-#include "cras_audio_area.h"
-#include "cras_config.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "test_iodev.h"
-#include "utlist.h"
-
-#define TEST_BUFFER_SIZE (16 * 1024)
-
-static size_t test_supported_rates[] = { 16000, 0 };
-
-static size_t test_supported_channel_counts[] = { 1, 0 };
-
-static snd_pcm_format_t test_supported_formats[] = { SND_PCM_FORMAT_S16_LE, 0 };
-
-struct test_iodev {
- struct cras_iodev base;
- int fd;
- struct byte_buffer *audbuff;
- unsigned int fmt_bytes;
-};
-
-/*
- * iodev callbacks.
- */
-
-static int frames_queued(const struct cras_iodev *iodev,
- struct timespec *tstamp)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
- int available;
-
- if (testio->fd < 0)
- return 0;
- ioctl(testio->fd, FIONREAD, &available);
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return available / testio->fmt_bytes;
-}
-
-static int delay_frames(const struct cras_iodev *iodev)
-{
- return 0;
-}
-
-static int close_dev(struct cras_iodev *iodev)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
-
- byte_buffer_destroy(&testio->audbuff);
- testio->audbuff = NULL;
- cras_iodev_free_audio_area(iodev);
- return 0;
-}
-
-static int configure_dev(struct cras_iodev *iodev)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
-
- if (iodev->format == NULL)
- return -EINVAL;
-
- cras_iodev_init_audio_area(iodev, iodev->format->num_channels);
- testio->fmt_bytes = cras_get_format_bytes(iodev->format);
- testio->audbuff =
- byte_buffer_create(TEST_BUFFER_SIZE * testio->fmt_bytes);
-
- return 0;
-}
-
-static int get_buffer(struct cras_iodev *iodev, struct cras_audio_area **area,
- unsigned *frames)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
- unsigned int readable;
- uint8_t *buff;
-
- buff = buf_read_pointer_size(testio->audbuff, &readable);
- *frames = MIN(*frames, readable);
-
- iodev->area->frames = *frames;
- cras_audio_area_config_buf_pointers(iodev->area, iodev->format, buff);
- *area = iodev->area;
- return 0;
-}
-
-static int put_buffer(struct cras_iodev *iodev, unsigned frames)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
-
- /* Input */
- buf_increment_read(testio->audbuff,
- (size_t)frames * (size_t)testio->fmt_bytes);
-
- return 0;
-}
-
-static int get_buffer_fd_read(struct cras_iodev *iodev,
- struct cras_audio_area **area, unsigned *frames)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
- int nread;
- uint8_t *write_ptr;
- unsigned int avail;
-
- if (testio->fd < 0) {
- *frames = 0;
- return 0;
- }
-
- write_ptr = buf_write_pointer_size(testio->audbuff, &avail);
- avail = MIN(avail, *frames * testio->fmt_bytes);
- nread = read(testio->fd, write_ptr, avail);
- if (nread <= 0) {
- *frames = 0;
- audio_thread_rm_callback(testio->fd);
- close(testio->fd);
- testio->fd = -1;
- return 0;
- }
- buf_increment_write(testio->audbuff, nread);
- *frames = nread / testio->fmt_bytes;
- iodev->area->frames = *frames;
- cras_audio_area_config_buf_pointers(iodev->area, iodev->format,
- write_ptr);
- *area = iodev->area;
- return nread;
-}
-
-static void update_active_node(struct cras_iodev *iodev, unsigned node_idx,
- unsigned dev_enabled)
-{
-}
-
-static void play_file_as_hotword(struct test_iodev *testio, const char *path)
-{
- if (testio->fd >= 0) {
- /* Remove audio thread callback from main thread. */
- audio_thread_rm_callback_sync(
- cras_iodev_list_get_audio_thread(), testio->fd);
- close(testio->fd);
- }
-
- testio->fd = open(path, O_RDONLY);
- buf_reset(testio->audbuff);
-}
-
-/*
- * Exported Interface.
- */
-
-struct cras_iodev *test_iodev_create(enum CRAS_STREAM_DIRECTION direction,
- enum TEST_IODEV_TYPE type)
-{
- struct test_iodev *testio;
- struct cras_iodev *iodev;
- struct cras_ionode *node;
-
- if (direction != CRAS_STREAM_INPUT || type != TEST_IODEV_HOTWORD)
- return NULL;
-
- testio = calloc(1, sizeof(*testio));
- if (testio == NULL)
- return NULL;
- iodev = &testio->base;
- iodev->direction = direction;
- testio->fd = -1;
-
- iodev->supported_rates = test_supported_rates;
- iodev->supported_channel_counts = test_supported_channel_counts;
- iodev->supported_formats = test_supported_formats;
- iodev->buffer_size = TEST_BUFFER_SIZE;
-
- iodev->configure_dev = configure_dev;
- iodev->close_dev = close_dev;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- if (type == TEST_IODEV_HOTWORD)
- iodev->get_buffer = get_buffer_fd_read;
- else
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->update_active_node = update_active_node;
-
- /*
- * Record max supported channels into cras_iodev_info.
- * The value is the max of test_supported_channel_counts.
- */
- iodev->info.max_supported_channels = 1;
-
- /* Create an empty ionode */
- node = (struct cras_ionode *)calloc(1, sizeof(*node));
- node->dev = iodev;
- node->plugged = 1;
- if (type == TEST_IODEV_HOTWORD)
- node->type = CRAS_NODE_TYPE_HOTWORD;
- else
- node->type = CRAS_NODE_TYPE_UNKNOWN;
- node->volume = 100;
- node->software_volume_needed = 0;
- node->ui_gain_scaler = 1.0f;
- strcpy(node->name, "(default)");
- cras_iodev_add_node(iodev, node);
- cras_iodev_set_active_node(iodev, node);
-
- /* Finally add it to the appropriate iodev list. */
- snprintf(iodev->info.name, ARRAY_SIZE(iodev->info.name), "Tester");
- iodev->info.name[ARRAY_SIZE(iodev->info.name) - 1] = '\0';
- cras_iodev_list_add_input(iodev);
-
- return iodev;
-}
-
-void test_iodev_destroy(struct cras_iodev *iodev)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
-
- cras_iodev_list_rm_input(iodev);
- free(iodev->active_node);
- cras_iodev_free_resources(iodev);
- free(testio);
-}
-
-unsigned int test_iodev_add_samples(struct test_iodev *testio, uint8_t *samples,
- unsigned int count)
-{
- unsigned int avail;
- uint8_t *write_ptr;
-
- write_ptr = buf_write_pointer_size(testio->audbuff, &avail);
- count = MIN(count, avail);
- memcpy(write_ptr, samples, (size_t)count * (size_t)testio->fmt_bytes);
- buf_increment_write(testio->audbuff,
- (size_t)count * (size_t)testio->fmt_bytes);
- return count;
-}
-
-void test_iodev_command(struct cras_iodev *iodev,
- enum CRAS_TEST_IODEV_CMD command, unsigned int data_len,
- const uint8_t *data)
-{
- struct test_iodev *testio = (struct test_iodev *)iodev;
-
- if (!cras_iodev_is_open(iodev))
- return;
-
- switch (command) {
- case TEST_IODEV_CMD_HOTWORD_TRIGGER:
- play_file_as_hotword(testio, (char *)data);
- break;
- default:
- break;
- }
-}
diff --git a/cras/src/server/test_iodev.h b/cras/src/server/test_iodev.h
deleted file mode 100644
index 782bf5c8..00000000
--- a/cras/src/server/test_iodev.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef TEST_IODEV_H_
-#define TEST_IODEV_H_
-
-#include "cras_types.h"
-
-struct cras_iodev;
-
-/* Initializes an test iodev. The Test iodev is used to simulate hardware
- * iodevs when they aren't available.
- * Args:
- * direciton - input or output.
- * type - The test type.
- * Returns:
- * A pointer to the newly created iodev if successful, NULL otherwise.
- */
-struct cras_iodev *test_iodev_create(enum CRAS_STREAM_DIRECTION direction,
- enum TEST_IODEV_TYPE type);
-
-/* Destroys an test_iodev created with test_iodev_create. */
-void test_iodev_destroy(struct cras_iodev *iodev);
-
-/* Handle a test commdn to the given iodev. */
-void test_iodev_command(struct cras_iodev *iodev,
- enum CRAS_TEST_IODEV_CMD command, unsigned int data_len,
- const uint8_t *data);
-
-#endif /* TEST_IODEV_H_ */
diff --git a/cras/src/tests/.clang-format b/cras/src/tests/.clang-format
deleted file mode 100644
index a675ede3..00000000
--- a/cras/src/tests/.clang-format
+++ /dev/null
@@ -1,14 +0,0 @@
-BasedOnStyle: Chromium
-
-# Taken from:
-# git grep -h '^#define [^[:space:]]*FOREACH[^[:space:]]*(' cras/ \
-# | sed "s,^#define \([^[:space:]]*FOREACH[^[:space:]]*\)(.*$, - '\1'," \
-# | sort | uniq
-
-ForEachMacros:
- - 'ARRAY_ELEMENT_FOREACH'
- - 'DL_FOREACH'
- - 'DL_FOREACH_INTERNAL'
- - 'LL_FOREACH'
- - 'LL_FOREACH_SAFE'
-
diff --git a/cras/src/tests/a2dp_info_unittest.cc b/cras/src/tests/a2dp_info_unittest.cc
deleted file mode 100644
index eb082b0c..00000000
--- a/cras/src/tests/a2dp_info_unittest.cc
+++ /dev/null
@@ -1,133 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-extern "C" {
-#include <sbc/sbc.h>
-
-#include "cras_a2dp_info.h"
-#include "cras_sbc_codec.h"
-#include "sbc_codec_stub.h"
-}
-
-static size_t a2dp_write_link_mtu_val;
-static struct a2dp_info a2dp;
-static a2dp_sbc_t sbc;
-
-void ResetStubData() {
- sbc_codec_stub_reset();
-
- a2dp_write_link_mtu_val = 40;
-
- sbc.frequency = SBC_SAMPLING_FREQ_48000;
- sbc.channel_mode = SBC_CHANNEL_MODE_JOINT_STEREO;
- sbc.allocation_method = SBC_ALLOCATION_LOUDNESS;
- sbc.subbands = SBC_SUBBANDS_8;
- sbc.block_length = SBC_BLOCK_LENGTH_16;
- sbc.max_bitpool = 50;
-
- a2dp.a2dp_buf_used = 0;
- a2dp.frame_count = 0;
- a2dp.samples = 0;
- a2dp.nsamples = 0;
-}
-
-namespace {
-
-TEST(A2dpInfoInit, InitA2dp) {
- ResetStubData();
- init_a2dp(&a2dp, &sbc);
-
- ASSERT_EQ(1, get_sbc_codec_create_called());
- ASSERT_EQ(SBC_FREQ_48000, get_sbc_codec_create_freq_val());
- ASSERT_EQ(SBC_MODE_JOINT_STEREO, get_sbc_codec_create_mode_val());
- ASSERT_EQ(SBC_AM_LOUDNESS, get_sbc_codec_create_alloc_val());
- ASSERT_EQ(SBC_SB_8, get_sbc_codec_create_subbands_val());
- ASSERT_EQ(SBC_BLK_16, get_sbc_codec_create_blocks_val());
- ASSERT_EQ(50, get_sbc_codec_create_bitpool_val());
-
- ASSERT_NE(a2dp.codec, (void*)NULL);
- ASSERT_EQ(a2dp.a2dp_buf_used, 13);
- ASSERT_EQ(a2dp.frame_count, 0);
- ASSERT_EQ(a2dp.seq_num, 0);
- ASSERT_EQ(a2dp.samples, 0);
-
- destroy_a2dp(&a2dp);
-}
-
-TEST(A2dpInfoInit, InitA2dpFail) {
- ResetStubData();
- int err;
- set_sbc_codec_create_fail(1);
- err = init_a2dp(&a2dp, &sbc);
-
- ASSERT_EQ(1, get_sbc_codec_create_called());
- ASSERT_NE(0, err);
- ASSERT_EQ(a2dp.codec, (void*)NULL);
-}
-
-TEST(A2dpInfoInit, DestroyA2dp) {
- ResetStubData();
- init_a2dp(&a2dp, &sbc);
- destroy_a2dp(&a2dp);
-
- ASSERT_EQ(1, get_sbc_codec_destroy_called());
-}
-
-TEST(A2dpInfoInit, ResetA2dp) {
- ResetStubData();
- init_a2dp(&a2dp, &sbc);
- a2dp.a2dp_buf_used = 99;
- a2dp.samples = 10;
- a2dp.seq_num = 11;
- a2dp.frame_count = 12;
-
- a2dp_reset(&a2dp);
-
- ASSERT_EQ(a2dp.a2dp_buf_used, 13);
- ASSERT_EQ(a2dp.frame_count, 0);
- ASSERT_EQ(a2dp.seq_num, 0);
- ASSERT_EQ(a2dp.samples, 0);
-
- destroy_a2dp(&a2dp);
-}
-
-TEST(A2dpEncode, WriteA2dp) {
- unsigned int processed;
-
- ResetStubData();
- init_a2dp(&a2dp, &sbc);
-
- set_sbc_codec_encoded_out(4);
- processed = a2dp_encode(&a2dp, NULL, 20, 4, (size_t)40);
-
- ASSERT_EQ(20, processed);
- ASSERT_EQ(4, a2dp.frame_count);
-
- // 13 + 4 used a2dp buffer still below half mtu unwritten
- ASSERT_EQ(17, a2dp.a2dp_buf_used);
- ASSERT_EQ(5, a2dp.samples);
- ASSERT_EQ(5, a2dp.nsamples);
- ASSERT_EQ(0, a2dp.seq_num);
-
- set_sbc_codec_encoded_out(15);
- processed = a2dp_encode(&a2dp, NULL, 20, 4, (size_t)40);
-
- ASSERT_EQ(32, a2dp.a2dp_buf_used);
- ASSERT_EQ(10, a2dp.samples);
- ASSERT_EQ(10, a2dp.nsamples);
- ASSERT_EQ(0, a2dp.seq_num);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/a2dp_iodev_unittest.cc b/cras/src/tests/a2dp_iodev_unittest.cc
deleted file mode 100644
index 06c1cd3c..00000000
--- a/cras/src/tests/a2dp_iodev_unittest.cc
+++ /dev/null
@@ -1,962 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_a2dp_iodev.c"
-
-#include "audio_thread.h"
-#include "audio_thread_log.h"
-#include "cras_audio_area.h"
-#include "cras_bt_transport.h"
-#include "cras_iodev.h"
-}
-
-#define FAKE_OBJECT_PATH "/fake/obj/path"
-
-#define MAX_A2DP_ENCODE_CALLS 8
-#define MAX_A2DP_WRITE_CALLS 4
-
-/* Fake the codec to encode (512/4) frames into 128 bytes. */
-#define FAKE_A2DP_CODE_SIZE 512
-#define FAKE_A2DP_FRAME_LENGTH 128
-
-static struct cras_bt_transport* fake_transport;
-static cras_audio_format format;
-static size_t cras_bt_device_append_iodev_called;
-static size_t cras_bt_device_rm_iodev_called;
-static size_t cras_iodev_add_node_called;
-static size_t cras_iodev_rm_node_called;
-static size_t cras_iodev_set_active_node_called;
-static size_t cras_bt_transport_acquire_called;
-static size_t cras_bt_transport_configuration_called;
-static size_t cras_bt_transport_release_called;
-static size_t init_a2dp_called;
-static int init_a2dp_return_val;
-static size_t destroy_a2dp_called;
-static size_t a2dp_reset_called;
-static size_t cras_iodev_free_format_called;
-static size_t cras_iodev_free_resources_called;
-static int a2dp_write_return_val[MAX_A2DP_WRITE_CALLS];
-static unsigned int a2dp_write_index;
-static int a2dp_encode_called;
-static cras_audio_area* mock_audio_area;
-static thread_callback write_callback;
-static void* write_callback_data;
-static const char* fake_device_name = "fake device name";
-static const char* cras_bt_device_name_ret;
-static unsigned int cras_bt_transport_write_mtu_ret;
-static int cras_iodev_fill_odev_zeros_called;
-static unsigned int cras_iodev_fill_odev_zeros_frames;
-static int audio_thread_config_events_callback_called;
-static enum AUDIO_THREAD_EVENTS_CB_TRIGGER
- audio_thread_config_events_callback_trigger;
-
-void ResetStubData() {
- cras_bt_device_append_iodev_called = 0;
- cras_bt_device_rm_iodev_called = 0;
- cras_iodev_add_node_called = 0;
- cras_iodev_rm_node_called = 0;
- cras_iodev_set_active_node_called = 0;
- cras_bt_transport_acquire_called = 0;
- cras_bt_transport_configuration_called = 0;
- cras_bt_transport_release_called = 0;
- init_a2dp_called = 0;
- init_a2dp_return_val = 0;
- destroy_a2dp_called = 0;
- a2dp_reset_called = 0;
- cras_iodev_free_format_called = 0;
- cras_iodev_free_resources_called = 0;
- a2dp_write_index = 0;
- a2dp_encode_called = 0;
- /* Fake the MTU value. min_buffer_level will be derived from this value. */
- cras_bt_transport_write_mtu_ret = 950;
- cras_iodev_fill_odev_zeros_called = 0;
-
- fake_transport = reinterpret_cast<struct cras_bt_transport*>(0x123);
-
- if (!mock_audio_area) {
- mock_audio_area = (cras_audio_area*)calloc(
- 1, sizeof(*mock_audio_area) + sizeof(cras_channel_area) * 2);
- }
-
- write_callback = NULL;
-}
-
-int iodev_set_format(struct cras_iodev* iodev, struct cras_audio_format* fmt) {
- fmt->format = SND_PCM_FORMAT_S16_LE;
- fmt->num_channels = 2;
- fmt->frame_rate = 44100;
- iodev->format = fmt;
- return 0;
-}
-
-namespace {
-
-static struct timespec time_now;
-class A2dpIodev : public testing::Test {
- protected:
- virtual void SetUp() {
- ResetStubData();
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- atlog = (audio_thread_event_log*)calloc(1, sizeof(audio_thread_event_log));
- }
-
- virtual void TearDown() {
- free(mock_audio_area);
- mock_audio_area = NULL;
- free(atlog);
- }
-};
-
-TEST_F(A2dpIodev, InitializeA2dpIodev) {
- struct cras_iodev* iodev;
-
- cras_bt_device_name_ret = NULL;
- iodev = a2dp_iodev_create(fake_transport);
-
- ASSERT_NE(iodev, (void*)NULL);
- ASSERT_EQ(iodev->direction, CRAS_STREAM_OUTPUT);
- ASSERT_EQ(1, cras_bt_transport_configuration_called);
- ASSERT_EQ(1, init_a2dp_called);
- ASSERT_EQ(1, cras_bt_device_append_iodev_called);
- ASSERT_EQ(1, cras_iodev_add_node_called);
- ASSERT_EQ(1, cras_iodev_set_active_node_called);
-
- /* Assert iodev name matches the object path when bt device doesn't
- * have its readable name populated. */
- ASSERT_STREQ(FAKE_OBJECT_PATH, iodev->info.name);
-
- a2dp_iodev_destroy(iodev);
-
- ASSERT_EQ(1, cras_bt_device_rm_iodev_called);
- ASSERT_EQ(1, cras_iodev_rm_node_called);
- ASSERT_EQ(1, destroy_a2dp_called);
- ASSERT_EQ(1, cras_iodev_free_resources_called);
-
- cras_bt_device_name_ret = fake_device_name;
- /* Assert iodev name matches the bt device's name */
- iodev = a2dp_iodev_create(fake_transport);
- ASSERT_STREQ(fake_device_name, iodev->info.name);
-
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, InitializeFail) {
- struct cras_iodev* iodev;
-
- init_a2dp_return_val = -1;
- iodev = a2dp_iodev_create(fake_transport);
-
- ASSERT_EQ(iodev, (void*)NULL);
- ASSERT_EQ(1, cras_bt_transport_configuration_called);
- ASSERT_EQ(1, init_a2dp_called);
- ASSERT_EQ(0, cras_bt_device_append_iodev_called);
- ASSERT_EQ(0, cras_iodev_add_node_called);
- ASSERT_EQ(0, cras_iodev_set_active_node_called);
- ASSERT_EQ(0, cras_iodev_rm_node_called);
-}
-
-TEST_F(A2dpIodev, OpenIodev) {
- struct cras_iodev* iodev;
-
- iodev = a2dp_iodev_create(fake_transport);
-
- iodev_set_format(iodev, &format);
- iodev->configure_dev(iodev);
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- ASSERT_EQ(1, cras_bt_transport_acquire_called);
-
- iodev->close_dev(iodev);
- ASSERT_EQ(1, cras_bt_transport_release_called);
- ASSERT_EQ(1, a2dp_reset_called);
- ASSERT_EQ(1, cras_iodev_free_format_called);
-
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, GetPutBuffer) {
- struct cras_iodev* iodev;
- struct cras_audio_area *area1, *area2, *area3;
- uint8_t* last_buf_head;
- unsigned frames;
- struct timespec tstamp;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- /* (950 - 13) / 128 * 512 / 4 */
- ASSERT_EQ(iodev->min_buffer_level, 896);
-
- frames = 1500;
- iodev->get_buffer(iodev, &area1, &frames);
- ASSERT_EQ(1500, frames);
- ASSERT_EQ(1500, area1->frames);
- last_buf_head = area1->channels[0].buf;
- iodev->put_buffer(iodev, 1000);
- /* 1000 frames takes 8 encode call, FAKE_A2DP_CODE_SIZE / 4 = 128
- * and 7 * 128 < 1000 < 8 * 128
- */
- EXPECT_EQ(8, a2dp_encode_called);
- /* Expect flushed one block, leaving 1000 - 896 = 104 queued and
- * next_flush_time has shifted. */
- EXPECT_EQ(1, a2dp_write_index);
- EXPECT_EQ(104, iodev->frames_queued(iodev, &tstamp));
- EXPECT_GT(a2dpio->next_flush_time.tv_nsec, 0);
-
- /* Assert buffer possition shifted 1000 * 4 bytes */
- frames = 1000;
- iodev->get_buffer(iodev, &area2, &frames);
- ASSERT_EQ(1000, frames);
- ASSERT_EQ(1000, area2->frames);
- ASSERT_EQ(4000, area2->channels[0].buf - last_buf_head);
- last_buf_head = area2->channels[0].buf;
-
- iodev->put_buffer(iodev, 700);
- EXPECT_EQ(804, iodev->frames_queued(iodev, &tstamp));
- /* Assert that even next_flush_time is not met, pcm data still processed.
- * Expect to takes 7 more encode calls to process the 804 frames of data.
- * and 6 * 128 < 804 < 7 * 128
- */
- EXPECT_EQ(15, a2dp_encode_called);
- EXPECT_EQ(768, a2dpio->a2dp.samples);
-
- time_now.tv_nsec = 25000000;
- frames = 50;
- iodev->get_buffer(iodev, &area3, &frames);
- ASSERT_EQ(50, frames);
- /* Assert buffer possition shifted 700 * 4 bytes */
- EXPECT_EQ(2800, area3->channels[0].buf - last_buf_head);
-
- iodev->put_buffer(iodev, 50);
- /* 804 + 50 = 854 queued, 768 of them are encoded. */
- EXPECT_EQ(854, iodev->frames_queued(iodev, &tstamp));
- EXPECT_EQ(768, a2dpio->a2dp.samples);
- /* Expect one a2dp encode call was executed for the left un-encoded frames.
- * 854 - 768 = 86 < 128 */
- EXPECT_EQ(16, a2dp_encode_called);
- /* Even time now has passed next_flush_time, no a2dp write gets called
- * because the number of encoded samples is not sufficient for a flush. */
- EXPECT_EQ(1, a2dp_write_index);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, FramesQueued) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
- /* a2dp_block_size(mtu) / format_bytes
- * (950 - 13) / 128 * 512 / 4 = 896 */
- EXPECT_EQ(896, a2dpio->write_block);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- frames = 256;
- iodev->get_buffer(iodev, &area, &frames);
- ASSERT_EQ(256, frames);
- ASSERT_EQ(256, area->frames);
-
- /* Data less than write_block hence not written. */
- iodev->put_buffer(iodev, 200);
- EXPECT_EQ(200, iodev->frames_queued(iodev, &tstamp));
- EXPECT_EQ(tstamp.tv_sec, time_now.tv_sec);
- EXPECT_EQ(tstamp.tv_nsec, time_now.tv_nsec);
-
- /* 200 + 800 - 896 = 104 */
- a2dp_write_return_val[0] = 0;
- frames = 800;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, 800);
- EXPECT_EQ(104, iodev->frames_queued(iodev, &tstamp));
-
- /* Some time has passed, same amount of frames are queued. */
- time_now.tv_nsec = 15000000;
- write_callback(write_callback_data, POLLOUT);
- EXPECT_EQ(104, iodev->frames_queued(iodev, &tstamp));
-
- /* Put 900 more frames. next_flush_time not yet passed so expect
- * total 900 + 104 = 1004 are queued. */
- frames = 900;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, 900);
- EXPECT_EQ(1004, iodev->frames_queued(iodev, &tstamp));
-
- /* Time passes next_flush_time, 1004 + 300 - 896 = 408 */
- time_now.tv_nsec = 25000000;
- frames = 300;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, 300);
- EXPECT_EQ(408, iodev->frames_queued(iodev, &tstamp));
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, SleepTimeWithWriteThrottle) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- unsigned frames;
- unsigned int level;
- unsigned long target;
- struct timespec tstamp;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
- /* a2dp_block_size(mtu) / format_bytes
- * 900 / 128 * 512 / 4 = 896 */
- EXPECT_EQ(896, a2dpio->write_block);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- /* Both time now and next_flush_time are at 0. Expect write_block of
- * time to sleep */
- EXPECT_EQ(a2dpio->write_block,
- iodev->frames_to_play_in_sleep(iodev, &level, &tstamp));
-
- /* Fake that 1000 frames are put and one block got flushed.
- * Expect next_wake_time be fast forward by one flush_period. */
- frames = 1000;
- iodev->get_buffer(iodev, &area, &frames);
- ASSERT_EQ(1000, frames);
- ASSERT_EQ(1000, area->frames);
-
- /* Expect the first block be flushed at time 0. */
- time_now.tv_nsec = 0;
- a2dp_write_return_val[0] = 0;
- EXPECT_EQ(0, iodev->put_buffer(iodev, 1000));
- EXPECT_EQ(104, iodev->frames_queued(iodev, &tstamp)); /* 1000 - 896 */
-
- /* Same amount of frames are queued after some time has passed. */
- time_now.tv_nsec = 10000000;
- EXPECT_EQ(104, iodev->frames_queued(iodev, &tstamp));
-
- /* Expect to sleep the time between now(10ms) and next_flush_time(~20.3ms). */
- frames = iodev->frames_to_play_in_sleep(iodev, &level, &tstamp);
- target =
- a2dpio->write_block - time_now.tv_nsec * format.frame_rate / 1000000000;
- EXPECT_GE(frames + 1, target);
- EXPECT_GE(target + 1, frames);
-
- /* Time now has passed the next flush time(~20.3ms), expect to return
- * write_block of time to sleep. */
- time_now.tv_nsec = 25000000;
- EXPECT_EQ(a2dpio->write_block,
- iodev->frames_to_play_in_sleep(iodev, &level, &tstamp));
-
- a2dp_write_return_val[1] = 0;
- frames = 1000;
- iodev->get_buffer(iodev, &area, &frames);
- EXPECT_EQ(0, iodev->put_buffer(iodev, 1000));
- EXPECT_EQ(208, iodev->frames_queued(iodev, &tstamp)); /* 104 + 1000 - 896 */
-
- /* Flush another write_block of data, next_wake_time fast forward by
- * another flush_period. Expect to sleep the time between now(25ms)
- * and next_flush_time(~40.6ms). */
- frames = iodev->frames_to_play_in_sleep(iodev, &level, &tstamp);
- target = a2dpio->write_block * 2 -
- time_now.tv_nsec * format.frame_rate / 1000000000;
- EXPECT_GE(frames + 1, target);
- EXPECT_GE(target + 1, frames);
-
- /* Put 1000 more frames, and make a fake failure to this flush. */
- time_now.tv_nsec = 45000000;
- a2dp_write_return_val[2] = -EAGAIN;
- frames = 1000;
- iodev->get_buffer(iodev, &area, &frames);
- EXPECT_EQ(0, iodev->put_buffer(iodev, 1000));
-
- /* Last a2dp write call failed with -EAGAIN, time now(45ms) is after
- * next_flush_time. Expect to return exact |write_block| equivalant
- * of time to sleep. */
- EXPECT_EQ(1208, iodev->frames_queued(iodev, &tstamp)); /* 208 + 1000 */
- EXPECT_EQ(a2dpio->write_block,
- iodev->frames_to_play_in_sleep(iodev, &level, &tstamp));
-
- /* Fake the event that socket becomes writable so data continues to flush.
- * next_flush_time fast forwards by another flush_period. */
- a2dp_write_return_val[3] = 0;
- write_callback(write_callback_data, POLLOUT);
- EXPECT_EQ(312, iodev->frames_queued(iodev, &tstamp)); /* 1208 - 896 */
-
- /* Expect to sleep the time between now and next_flush_time(~60.9ms). */
- frames = iodev->frames_to_play_in_sleep(iodev, &level, &tstamp);
- target = a2dpio->write_block * 3 -
- time_now.tv_nsec * format.frame_rate / 1000000000;
- EXPECT_GE(frames + 1, target);
- EXPECT_GE(target + 1, frames);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, EnableThreadCallbackAtBufferFull) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- audio_thread_config_events_callback_called = 0;
- a2dp_write_return_val[0] = 0;
- frames = iodev->buffer_size;
- iodev->get_buffer(iodev, &area, &frames);
- EXPECT_LE(frames, iodev->buffer_size);
- EXPECT_EQ(0, iodev->put_buffer(iodev, frames));
- EXPECT_EQ(1, a2dp_write_index);
- EXPECT_EQ(a2dpio->flush_period.tv_nsec, a2dpio->next_flush_time.tv_nsec);
- EXPECT_EQ(1, audio_thread_config_events_callback_called);
- EXPECT_EQ(TRIGGER_NONE, audio_thread_config_events_callback_trigger);
-
- /* Fastfoward time 1ms, not yet reaches the next flush time. */
- time_now.tv_nsec = 1000000;
-
- /* Cram into iodev as much data as possible. Expect its buffer to
- * be full because flush time does not yet met. */
- frames = iodev->buffer_size;
- iodev->get_buffer(iodev, &area, &frames);
- EXPECT_LE(frames, iodev->buffer_size);
- EXPECT_EQ(0, iodev->put_buffer(iodev, frames));
- frames = iodev->frames_queued(iodev, &tstamp);
- EXPECT_EQ(frames, iodev->buffer_size);
-
- /* Expect a2dp_write didn't get called in last get/put buffer. And
- * audio thread callback has been enabled. */
- EXPECT_EQ(1, a2dp_write_index);
- EXPECT_EQ(2, audio_thread_config_events_callback_called);
- EXPECT_EQ(TRIGGER_WAKEUP, audio_thread_config_events_callback_trigger);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, FlushAtLowBufferLevel) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames;
-
- iodev = a2dp_iodev_create(fake_transport);
-
- iodev_set_format(iodev, &format);
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
-
- /* (950 - 13)/ 128 * 512 / 4 */
- ASSERT_EQ(iodev->min_buffer_level, 896);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- frames = 1500;
- iodev->get_buffer(iodev, &area, &frames);
- ASSERT_EQ(1500, frames);
- ASSERT_EQ(1500, area->frames);
-
- /*
- * Assert put_buffer shouldn't trigger the 2nd call to a2dp_encode()
- * because buffer is low: 896 < 1500 < 896 * 2
- */
- a2dp_write_return_val[0] = 0;
- EXPECT_EQ(0, iodev->put_buffer(iodev, 1500));
- EXPECT_EQ(1, a2dp_write_index);
-
- /* 1500 - 896 */
- time_now.tv_nsec = 25000000;
- EXPECT_EQ(604, iodev->frames_queued(iodev, &tstamp));
- EXPECT_EQ(tstamp.tv_sec, time_now.tv_sec);
- EXPECT_EQ(tstamp.tv_nsec, time_now.tv_nsec);
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, HandleUnderrun) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames;
-
- iodev = a2dp_iodev_create(fake_transport);
-
- iodev_set_format(iodev, &format);
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- iodev->configure_dev(iodev);
- /* (950 - 13) / 128 * 512 / 4 */
- EXPECT_EQ(896, iodev->min_buffer_level);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- frames = 300;
- iodev->get_buffer(iodev, &area, &frames);
- ASSERT_EQ(300, frames);
- ASSERT_EQ(300, area->frames);
- a2dp_write_return_val[0] = -EAGAIN;
-
- time_now.tv_nsec = 10000000;
- iodev->put_buffer(iodev, 300);
-
- time_now.tv_nsec = 20000000;
- EXPECT_EQ(300, iodev->frames_queued(iodev, &tstamp));
-
- /* Frames queued below min_buffer_level, which is derived from transport MTU.
- * Assert min_cb_level of zero frames are filled. */
- iodev->min_cb_level = 150;
- iodev->output_underrun(iodev);
- ASSERT_EQ(1, cras_iodev_fill_odev_zeros_called);
- EXPECT_EQ(150, cras_iodev_fill_odev_zeros_frames);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, LeavingNoStreamStateWithSmallStreamDoesntUnderrun) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
- /* (950 - 13)/ 128 * 512 / 4 */
- ASSERT_EQ(896, iodev->min_buffer_level);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- /* Put iodev in no_stream state. Verify it doesn't underrun after each
- * call of no_stream ops. */
- a2dp_write_return_val[0] = 0;
- iodev->no_stream(iodev, 1);
- EXPECT_EQ(1, a2dp_write_index);
- EXPECT_EQ(a2dpio->flush_period.tv_nsec, a2dpio->next_flush_time.tv_nsec);
- frames = iodev->frames_queued(iodev, &tstamp);
- EXPECT_LE(iodev->min_buffer_level, frames);
-
- /* Some time has passed and a small stream of 200 frames block is added.
- * Verify leaving no_stream state doesn't underrun immediately. */
- time_now.tv_nsec = 20000000;
- iodev->no_stream(iodev, 1);
- frames = 200;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, 200);
- frames = iodev->frames_queued(iodev, &tstamp);
- EXPECT_LE(iodev->min_buffer_level, frames);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, NoStreamStateFillZerosToTargetLevel) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
- /* (950 - 13)/ 128 * 512 / 4 */
- ASSERT_EQ(896, iodev->min_buffer_level);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- iodev->min_cb_level = 480;
- frames = 200;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, 200);
-
- a2dp_write_return_val[0] = 0;
- iodev->no_stream(iodev, 1);
- EXPECT_EQ(1, a2dp_write_index);
- EXPECT_EQ(a2dpio->flush_period.tv_nsec, a2dpio->next_flush_time.tv_nsec);
-
- /* Some time has passed but not yet reach next flush. Entering no_stream
- * fills buffer to 3 times of min_buffer_level. */
- time_now.tv_nsec = 10000000;
- iodev->no_stream(iodev, 1);
- frames = iodev->frames_queued(iodev, &tstamp);
- EXPECT_EQ(3 * iodev->min_buffer_level, frames);
-
- /* Time has passed next flush time, expect one block is flushed. */
- a2dp_write_return_val[1] = 0;
- time_now.tv_nsec = 25000000;
- iodev->no_stream(iodev, 1);
- frames = iodev->frames_queued(iodev, &tstamp);
- ASSERT_EQ(2 * iodev->min_buffer_level, frames);
- EXPECT_EQ(2, a2dp_write_index);
-
- /* Leaving no_stream state fills buffer level back to 2 * min_buffer_level.
- */
- a2dp_write_return_val[2] = 0;
- time_now.tv_nsec = 30000000;
- iodev->no_stream(iodev, 0);
- frames = iodev->frames_queued(iodev, &tstamp);
- ASSERT_EQ(2 * iodev->min_buffer_level, frames);
- EXPECT_EQ(2, a2dp_write_index);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-
-TEST_F(A2dpIodev, EnterNoStreamStateAtHighBufferLevelDoesntFillMore) {
- struct cras_iodev* iodev;
- struct cras_audio_area* area;
- struct timespec tstamp;
- unsigned frames, start_level;
- struct a2dp_io* a2dpio;
-
- iodev = a2dp_iodev_create(fake_transport);
- a2dpio = (struct a2dp_io*)iodev;
-
- iodev_set_format(iodev, &format);
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- iodev->configure_dev(iodev);
- ASSERT_NE(write_callback, (void*)NULL);
- /* (950 - 13)/ 128 * 512 / 4 */
- ASSERT_EQ(896, iodev->min_buffer_level);
-
- iodev->start(iodev);
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- a2dp_write_return_val[0] = 0;
- start_level = 6000;
- frames = start_level;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, frames);
- frames = iodev->frames_queued(iodev, &tstamp);
- /* Assert one block has fluxhed */
- EXPECT_EQ(start_level - iodev->min_buffer_level, frames);
- EXPECT_EQ(1, a2dp_write_index);
- EXPECT_EQ(a2dpio->flush_period.tv_nsec, a2dpio->next_flush_time.tv_nsec);
-
- a2dp_write_return_val[1] = 0;
- time_now.tv_nsec = 25000000;
- iodev->no_stream(iodev, 1);
- frames = iodev->frames_queued(iodev, &tstamp);
- /* Next flush time meets requirement so another block is flushed. */
- ASSERT_EQ(start_level - 2 * iodev->min_buffer_level, frames);
-
- a2dp_write_return_val[2] = 0;
- time_now.tv_nsec = 50000000;
- iodev->no_stream(iodev, 1);
- frames = iodev->frames_queued(iodev, &tstamp);
- /* Another block flushed at leaving no stream state. No more data
- * filled because level is high. */
- ASSERT_EQ(start_level - 3 * iodev->min_buffer_level, frames);
-
- iodev->close_dev(iodev);
- a2dp_iodev_destroy(iodev);
-}
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-extern "C" {
-
-int cras_bt_transport_configuration(const struct cras_bt_transport* transport,
- void* configuration,
- int len) {
- memset(configuration, 0, len);
- cras_bt_transport_configuration_called++;
- return 0;
-}
-
-int cras_bt_transport_acquire(struct cras_bt_transport* transport) {
- cras_bt_transport_acquire_called++;
- return 0;
-}
-
-int cras_bt_transport_release(struct cras_bt_transport* transport,
- unsigned int blocking) {
- cras_bt_transport_release_called++;
- return 0;
-}
-
-int cras_bt_transport_fd(const struct cras_bt_transport* transport) {
- return 0;
-}
-
-const char* cras_bt_transport_object_path(
- const struct cras_bt_transport* transport) {
- return FAKE_OBJECT_PATH;
-}
-
-uint16_t cras_bt_transport_write_mtu(
- const struct cras_bt_transport* transport) {
- return cras_bt_transport_write_mtu_ret;
-}
-
-int cras_bt_transport_set_volume(struct cras_bt_transport* transport,
- uint16_t volume) {
- return 0;
-}
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {
- cras_iodev_free_format_called++;
-}
-
-void cras_iodev_free_resources(struct cras_iodev* iodev) {
- cras_iodev_free_resources_called++;
-}
-
-// Cras iodev
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_add_node_called++;
- iodev->nodes = node;
-}
-
-void cras_iodev_rm_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_rm_node_called++;
- iodev->nodes = NULL;
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {
- cras_iodev_set_active_node_called++;
- iodev->active_node = node;
-}
-
-// From cras_bt_transport
-struct cras_bt_device* cras_bt_transport_device(
- const struct cras_bt_transport* transport) {
- return reinterpret_cast<struct cras_bt_device*>(0x456);
- ;
-}
-
-enum cras_bt_device_profile cras_bt_transport_profile(
- const struct cras_bt_transport* transport) {
- return CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
-}
-
-// From cras_bt_device
-const char* cras_bt_device_name(const struct cras_bt_device* device) {
- return cras_bt_device_name_ret;
-}
-
-const char* cras_bt_device_object_path(const struct cras_bt_device* device) {
- return "/org/bluez/hci0/dev_1A_2B_3C_4D_5E_6F";
-}
-
-int cras_bt_device_get_stable_id(const struct cras_bt_device* device) {
- return 123;
-}
-
-void cras_bt_device_append_iodev(struct cras_bt_device* device,
- struct cras_iodev* iodev,
- enum cras_bt_device_profile profile) {
- cras_bt_device_append_iodev_called++;
-}
-
-void cras_bt_device_rm_iodev(struct cras_bt_device* device,
- struct cras_iodev* iodev) {
- cras_bt_device_rm_iodev_called++;
-}
-
-int cras_bt_device_get_use_hardware_volume(struct cras_bt_device* device) {
- return 0;
-}
-
-int cras_bt_device_cancel_suspend(struct cras_bt_device* device) {
- return 0;
-}
-
-int cras_bt_device_schedule_suspend(
- struct cras_bt_device* device,
- unsigned int msec,
- enum cras_bt_device_suspend_reason suspend_reason) {
- return 0;
-}
-
-int init_a2dp(struct a2dp_info* a2dp, a2dp_sbc_t* sbc) {
- init_a2dp_called++;
- memset(a2dp, 0, sizeof(*a2dp));
- a2dp->frame_length = FAKE_A2DP_FRAME_LENGTH;
- a2dp->codesize = FAKE_A2DP_CODE_SIZE;
- return init_a2dp_return_val;
-}
-
-void destroy_a2dp(struct a2dp_info* a2dp) {
- destroy_a2dp_called++;
-}
-
-int a2dp_codesize(struct a2dp_info* a2dp) {
- return a2dp->codesize;
-}
-
-int a2dp_block_size(struct a2dp_info* a2dp, int encoded_bytes) {
- return encoded_bytes / a2dp->frame_length * a2dp->codesize;
-}
-
-int a2dp_queued_frames(const struct a2dp_info* a2dp) {
- return a2dp->samples;
-}
-
-void a2dp_reset(struct a2dp_info* a2dp) {
- a2dp_reset_called++;
- a2dp->samples = 0;
-}
-
-int a2dp_encode(struct a2dp_info* a2dp,
- const void* pcm_buf,
- int pcm_buf_size,
- int format_bytes,
- size_t link_mtu) {
- int processed = 0;
- a2dp_encode_called++;
-
- if (a2dp->a2dp_buf_used + a2dp->frame_length > link_mtu)
- return 0;
- if (pcm_buf_size < a2dp->codesize)
- return 0;
-
- processed += a2dp->codesize;
- a2dp->a2dp_buf_used += a2dp->frame_length;
- a2dp->samples += processed / format_bytes;
-
- return processed;
-}
-
-int a2dp_write(struct a2dp_info* a2dp, int stream_fd, size_t link_mtu) {
- int ret, samples;
- if (a2dp->frame_length + a2dp->a2dp_buf_used < link_mtu)
- return 0;
-
- ret = a2dp_write_return_val[a2dp_write_index++];
- if (ret < 0)
- return ret;
-
- samples = a2dp->samples;
- a2dp->samples = 0;
- a2dp->a2dp_buf_used = 0;
- return samples;
-}
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = time_now;
- return 0;
-}
-
-void cras_iodev_init_audio_area(struct cras_iodev* iodev, int num_channels) {
- iodev->area = mock_audio_area;
-}
-
-void cras_iodev_free_audio_area(struct cras_iodev* iodev) {}
-
-int cras_iodev_fill_odev_zeros(struct cras_iodev* odev, unsigned int frames) {
- struct cras_audio_area* area;
- cras_iodev_fill_odev_zeros_called++;
- cras_iodev_fill_odev_zeros_frames = frames;
-
- odev->get_buffer(odev, &area, &frames);
- odev->put_buffer(odev, frames);
- return 0;
-}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {
- mock_audio_area->channels[0].buf = base_buffer;
-}
-
-struct audio_thread* cras_iodev_list_get_audio_thread() {
- return NULL;
-}
-// From ewma_power
-void ewma_power_disable(struct ewma_power* ewma) {}
-
-// From audio_thread
-struct audio_thread_event_log* atlog;
-
-void audio_thread_add_events_callback(int fd,
- thread_callback cb,
- void* data,
- int events) {
- write_callback = cb;
- write_callback_data = data;
-}
-
-int audio_thread_rm_callback_sync(struct audio_thread* thread, int fd) {
- return 0;
-}
-
-void audio_thread_config_events_callback(
- int fd,
- enum AUDIO_THREAD_EVENTS_CB_TRIGGER trigger) {
- audio_thread_config_events_callback_called++;
- audio_thread_config_events_callback_trigger = trigger;
-}
-}
-
-int cras_audio_thread_event_a2dp_overrun() {
- return 0;
-}
-
-int cras_audio_thread_event_a2dp_throttle() {
- return 0;
-}
diff --git a/cras/src/tests/alert_unittest.cc b/cras/src/tests/alert_unittest.cc
deleted file mode 100644
index ec1efcc4..00000000
--- a/cras/src/tests/alert_unittest.cc
+++ /dev/null
@@ -1,227 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "cras_alert.h"
-
-namespace {
-
-void callback1(void* arg, void* data);
-void callback2(void* arg, void* data);
-void prepare(struct cras_alert* alert);
-
-struct cb_data_struct {
- int data;
-};
-
-static int cb1_called = 0;
-static cb_data_struct cb1_data;
-static int cb2_called = 0;
-static int cb2_set_pending = 0;
-static int prepare_called = 0;
-
-void ResetStub() {
- cb1_called = 0;
- cb2_called = 0;
- cb2_set_pending = 0;
- prepare_called = 0;
- cb1_data.data = 0;
-}
-
-class Alert : public testing::Test {
- protected:
- virtual void SetUp() { cb1_data.data = 0; }
-
- virtual void TearDown() {}
-};
-
-TEST_F(Alert, OneCallback) {
- struct cras_alert* alert = cras_alert_create(NULL, 0);
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- cras_alert_pending(alert);
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, cb1_called);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, OneCallbackPost2Call1) {
- struct cras_alert* alert = cras_alert_create(NULL, 0);
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- // Alert twice, callback should only be called once.
- cras_alert_pending(alert);
- cras_alert_pending(alert);
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, cb1_called);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, OneCallbackWithData) {
- struct cras_alert* alert = cras_alert_create(NULL, 0);
- struct cb_data_struct data = {1};
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- cras_alert_pending_data(alert, (void*)&data, sizeof(struct cb_data_struct));
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, cb1_called);
- EXPECT_EQ(1, cb1_data.data);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, OneCallbackTwoDataCalledOnce) {
- struct cras_alert* alert = cras_alert_create(NULL, 0);
- struct cb_data_struct data = {1};
- struct cb_data_struct data2 = {2};
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- // Callback called with last data only.
- cras_alert_pending_data(alert, (void*)&data, sizeof(struct cb_data_struct));
- cras_alert_pending_data(alert, (void*)&data2, sizeof(struct cb_data_struct));
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, cb1_called);
- EXPECT_EQ(2, cb1_data.data);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, OneCallbackTwoDataKeepAll) {
- struct cras_alert* alert =
- cras_alert_create(NULL, CRAS_ALERT_FLAG_KEEP_ALL_DATA);
- struct cb_data_struct data = {1};
- struct cb_data_struct data2 = {2};
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- // Callbacks with data should each be called.
- cras_alert_pending_data(alert, (void*)&data, sizeof(cb_data_struct));
- cras_alert_pending_data(alert, (void*)&data2, sizeof(cb_data_struct));
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(2, cb1_called);
- EXPECT_EQ(2, cb1_data.data);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, TwoCallbacks) {
- struct cras_alert* alert = cras_alert_create(NULL, 0);
- cras_alert_add_callback(alert, &callback1, NULL);
- cras_alert_add_callback(alert, &callback2, NULL);
- ResetStub();
- cras_alert_pending(alert);
- EXPECT_EQ(0, cb1_called);
- EXPECT_EQ(0, cb2_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, cb1_called);
- EXPECT_EQ(1, cb2_called);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, NoPending) {
- struct cras_alert* alert = cras_alert_create(NULL, 0);
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(0, cb1_called);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, PendingInCallback) {
- struct cras_alert* alert1 = cras_alert_create(NULL, 0);
- struct cras_alert* alert2 = cras_alert_create(NULL, 0);
- cras_alert_add_callback(alert1, &callback1, NULL);
- cras_alert_add_callback(alert2, &callback2, alert1);
- ResetStub();
- cras_alert_pending(alert2);
- EXPECT_EQ(0, cb1_called);
- EXPECT_EQ(0, cb2_called);
- cb2_set_pending = 1;
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, cb1_called);
- EXPECT_EQ(1, cb2_called);
- cras_alert_destroy(alert1);
- cras_alert_destroy(alert2);
-}
-
-TEST_F(Alert, Prepare) {
- struct cras_alert* alert = cras_alert_create(prepare, 0);
- cras_alert_add_callback(alert, &callback1, NULL);
- ResetStub();
- cras_alert_pending(alert);
- EXPECT_EQ(0, cb1_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, prepare_called);
- EXPECT_EQ(1, cb1_called);
- cras_alert_destroy(alert);
-}
-
-TEST_F(Alert, TwoAlerts) {
- struct cras_alert* alert1 = cras_alert_create(prepare, 0);
- struct cras_alert* alert2 = cras_alert_create(prepare, 0);
- cras_alert_add_callback(alert1, &callback1, NULL);
- cras_alert_add_callback(alert2, &callback2, NULL);
-
- ResetStub();
- cras_alert_pending(alert1);
- EXPECT_EQ(0, cb1_called);
- EXPECT_EQ(0, cb2_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, prepare_called);
- EXPECT_EQ(1, cb1_called);
- EXPECT_EQ(0, cb2_called);
-
- ResetStub();
- cras_alert_pending(alert2);
- EXPECT_EQ(0, cb1_called);
- EXPECT_EQ(0, cb2_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(1, prepare_called);
- EXPECT_EQ(0, cb1_called);
- EXPECT_EQ(1, cb2_called);
-
- ResetStub();
- cras_alert_pending(alert1);
- cras_alert_pending(alert2);
- EXPECT_EQ(0, cb1_called);
- EXPECT_EQ(0, cb2_called);
- cras_alert_process_all_pending_alerts();
- EXPECT_EQ(2, prepare_called);
- EXPECT_EQ(1, cb1_called);
- EXPECT_EQ(1, cb2_called);
-
- cras_alert_destroy_all();
-}
-
-void callback1(void* arg, void* data) {
- cb1_called++;
- if (data)
- cb1_data.data = ((struct cb_data_struct*)data)->data;
-}
-
-void callback2(void* arg, void* data) {
- cb2_called++;
- if (cb2_set_pending) {
- cb2_set_pending = 0;
- cras_alert_pending((struct cras_alert*)arg);
- }
-}
-
-void prepare(struct cras_alert* alert) {
- prepare_called++;
- return;
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/alsa_card_unittest.cc b/cras/src/tests/alsa_card_unittest.cc
deleted file mode 100644
index cfb67560..00000000
--- a/cras/src/tests/alsa_card_unittest.cc
+++ /dev/null
@@ -1,1289 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include <map>
-
-extern "C" {
-#include "cras_alsa_card.h"
-#include "cras_alsa_io.h"
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_ucm.h"
-#include "cras_iodev.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-}
-
-namespace {
-
-static size_t cras_alsa_mixer_create_called;
-static struct cras_alsa_mixer* cras_alsa_mixer_create_return;
-static size_t cras_alsa_mixer_destroy_called;
-static size_t cras_alsa_iodev_create_called;
-static struct cras_iodev** cras_alsa_iodev_create_return;
-static struct cras_iodev fake_dev1, fake_dev2, fake_dev3, fake_dev4;
-static struct cras_iodev* cras_alsa_iodev_create_default_return[] = {
- &fake_dev1,
- &fake_dev2,
- &fake_dev3,
- &fake_dev4,
-};
-static size_t cras_alsa_iodev_create_return_size;
-static size_t cras_alsa_iodev_legacy_complete_init_called;
-static size_t cras_alsa_iodev_ucm_add_nodes_and_jacks_called;
-static size_t cras_alsa_iodev_ucm_complete_init_called;
-static size_t cras_alsa_iodev_destroy_called;
-static struct cras_iodev* cras_alsa_iodev_destroy_arg;
-static size_t cras_alsa_iodev_index_called;
-static std::map<struct cras_iodev*, unsigned int> cras_alsa_iodev_index_return;
-static int alsa_iodev_has_hctl_jacks_return;
-static size_t snd_ctl_open_called;
-static size_t snd_ctl_open_return;
-static size_t snd_ctl_close_called;
-static size_t snd_ctl_close_return;
-static size_t snd_ctl_pcm_next_device_called;
-static bool snd_ctl_pcm_next_device_return_error;
-static int* snd_ctl_pcm_next_device_set_devs;
-static size_t snd_ctl_pcm_next_device_set_devs_size;
-static size_t snd_ctl_pcm_next_device_set_devs_index;
-static size_t snd_ctl_pcm_info_called;
-static int* snd_ctl_pcm_info_rets;
-static size_t snd_ctl_pcm_info_rets_size;
-static size_t snd_ctl_pcm_info_rets_index;
-static size_t snd_ctl_card_info_called;
-static int snd_ctl_card_info_ret;
-static size_t snd_hctl_open_called;
-static int snd_hctl_open_return_value;
-static int snd_hctl_close_called;
-static size_t snd_hctl_nonblock_called;
-static snd_hctl_t* snd_hctl_open_pointer_val;
-static size_t snd_hctl_load_called;
-static int snd_hctl_load_return_value;
-static struct pollfd* snd_hctl_poll_descriptors_fds;
-static size_t snd_hctl_poll_descriptors_num_fds;
-static size_t snd_hctl_poll_descriptors_called;
-static size_t cras_system_add_select_fd_called;
-static std::vector<int> cras_system_add_select_fd_values;
-static size_t cras_system_rm_select_fd_called;
-static std::vector<int> cras_system_rm_select_fd_values;
-static size_t snd_hctl_handle_events_called;
-static size_t iniparser_freedict_called;
-static size_t iniparser_load_called;
-static struct cras_device_blocklist* fake_blocklist;
-static int cras_device_blocklist_check_retval;
-static unsigned ucm_create_called;
-static char ucm_create_name[100];
-static unsigned ucm_destroy_called;
-static size_t ucm_get_dev_for_mixer_called;
-static size_t ucm_get_flag_called;
-static char ucm_get_flag_name[65];
-static char* device_config_dir;
-static const char* cras_card_config_dir;
-static struct mixer_name* ucm_get_coupled_mixer_names_return_value;
-static struct mixer_name* coupled_output_names_value;
-static int ucm_has_fully_specified_ucm_flag_return_value;
-static int ucm_get_sections_called;
-static struct mixer_name* ucm_get_main_volume_names_return_value;
-static struct ucm_section* ucm_get_sections_return_value;
-static size_t cras_alsa_mixer_add_controls_in_section_called;
-static int cras_alsa_mixer_add_controls_in_section_return_value;
-static int cras_alsa_mixer_add_main_volume_control_by_name_called;
-static int cras_alsa_mixer_add_main_volume_control_by_name_return_value;
-static int ucm_get_echo_reference_dev_name_for_dev_called;
-static size_t cras_system_check_ignore_ucm_suffix_called;
-static bool cras_system_check_ignore_ucm_suffix_value;
-static const char* ucm_get_echo_reference_dev_name_for_dev_return_value[4];
-
-static void ResetStubData() {
- cras_alsa_mixer_create_called = 0;
- cras_alsa_mixer_create_return = reinterpret_cast<struct cras_alsa_mixer*>(1);
- cras_alsa_mixer_destroy_called = 0;
- cras_alsa_iodev_destroy_arg = NULL;
- cras_alsa_iodev_create_called = 0;
- cras_alsa_iodev_create_return = cras_alsa_iodev_create_default_return;
- cras_alsa_iodev_create_return_size =
- ARRAY_SIZE(cras_alsa_iodev_create_default_return);
- cras_alsa_iodev_legacy_complete_init_called = 0;
- cras_alsa_iodev_ucm_add_nodes_and_jacks_called = 0;
- cras_alsa_iodev_ucm_complete_init_called = 0;
- cras_alsa_iodev_destroy_called = 0;
- cras_alsa_iodev_index_called = 0;
- cras_alsa_iodev_index_return.clear();
- alsa_iodev_has_hctl_jacks_return = 1;
- snd_ctl_open_called = 0;
- snd_ctl_open_return = 0;
- snd_ctl_close_called = 0;
- snd_ctl_close_return = 0;
- snd_ctl_pcm_next_device_called = 0;
- snd_ctl_pcm_next_device_return_error = false;
- snd_ctl_pcm_next_device_set_devs_size = 0;
- snd_ctl_pcm_next_device_set_devs_index = 0;
- snd_ctl_pcm_info_called = 0;
- snd_ctl_pcm_info_rets_size = 0;
- snd_ctl_pcm_info_rets_index = 0;
- snd_ctl_card_info_called = 0;
- snd_ctl_card_info_ret = 0;
- snd_hctl_open_called = 0;
- snd_hctl_open_return_value = 0;
- snd_hctl_open_pointer_val = reinterpret_cast<snd_hctl_t*>(0x4323);
- snd_hctl_load_called = 0;
- snd_hctl_load_return_value = 0;
- snd_hctl_close_called = 0;
- snd_hctl_nonblock_called = 0;
- snd_hctl_poll_descriptors_num_fds = 0;
- snd_hctl_poll_descriptors_called = 0;
- snd_hctl_handle_events_called = 0;
- snd_hctl_poll_descriptors_num_fds = 0;
- snd_hctl_poll_descriptors_called = 0;
- cras_system_add_select_fd_called = 0;
- cras_system_add_select_fd_values.clear();
- cras_system_rm_select_fd_called = 0;
- cras_system_rm_select_fd_values.clear();
- iniparser_freedict_called = 0;
- iniparser_load_called = 0;
- fake_blocklist = reinterpret_cast<struct cras_device_blocklist*>(3);
- cras_device_blocklist_check_retval = 0;
- ucm_create_called = 0;
- memset(ucm_create_name, 0, sizeof(ucm_get_flag_name));
- ucm_destroy_called = 0;
- ucm_get_dev_for_mixer_called = 0;
- ucm_get_flag_called = 0;
- memset(ucm_get_flag_name, 0, sizeof(ucm_get_flag_name));
- device_config_dir = reinterpret_cast<char*>(3);
- cras_card_config_dir = NULL;
- ucm_get_coupled_mixer_names_return_value = NULL;
- ucm_get_main_volume_names_return_value = NULL;
- mixer_name_free(coupled_output_names_value);
- coupled_output_names_value = NULL;
- ucm_has_fully_specified_ucm_flag_return_value = 0;
- ucm_get_sections_called = 0;
- ucm_get_sections_return_value = NULL;
- cras_alsa_mixer_add_controls_in_section_called = 0;
- cras_alsa_mixer_add_controls_in_section_return_value = 0;
- cras_alsa_mixer_add_main_volume_control_by_name_called = 0;
- cras_alsa_mixer_add_main_volume_control_by_name_return_value = 0;
- ucm_get_echo_reference_dev_name_for_dev_called = 0;
- cras_system_check_ignore_ucm_suffix_called = 0;
- cras_system_check_ignore_ucm_suffix_value = 0;
- fake_dev1.nodes = NULL;
- fake_dev2.nodes = NULL;
- fake_dev3.nodes = NULL;
- fake_dev4.nodes = NULL;
-}
-
-TEST(AlsaCard, CreateFailInvalidCard) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 55;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
-}
-
-TEST(AlsaCard, CreateFailMixerInit) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- cras_alsa_mixer_create_return = static_cast<struct cras_alsa_mixer*>(NULL);
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(1, cras_alsa_mixer_create_called);
- EXPECT_EQ(0, cras_alsa_mixer_destroy_called);
-}
-
-TEST(AlsaCard, CreateFailCtlOpen) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_open_return = -1;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(1, snd_ctl_open_called);
- EXPECT_EQ(0, snd_ctl_close_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
- EXPECT_EQ(0, cras_alsa_mixer_create_called);
-}
-
-TEST(AlsaCard, CreateFailHctlOpen) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_hctl_open_pointer_val = NULL;
- snd_hctl_open_return_value = -1;
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(1, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_close_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
- EXPECT_EQ(1, snd_hctl_open_called);
- EXPECT_EQ(0, snd_hctl_nonblock_called);
- EXPECT_EQ(0, snd_hctl_load_called);
- EXPECT_EQ(1, cras_alsa_mixer_create_called);
- cras_alsa_card_destroy(c);
-}
-
-TEST(AlsaCard, CreateFailHctlLoad) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_hctl_load_return_value = -1;
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(1, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_close_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
- EXPECT_EQ(1, snd_hctl_open_called);
- EXPECT_EQ(1, snd_hctl_nonblock_called);
- EXPECT_EQ(1, snd_hctl_load_called);
- EXPECT_EQ(0, cras_alsa_mixer_create_called);
-}
-
-TEST(AlsaCard, AddSelectForHctlNoDevices) {
- struct pollfd poll_fds[] = {
- {3, 0, 0},
- };
-
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_hctl_poll_descriptors_fds = poll_fds;
- snd_hctl_poll_descriptors_num_fds = ARRAY_SIZE(poll_fds);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(1, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_close_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
- EXPECT_EQ(1, snd_hctl_open_called);
- EXPECT_EQ(1, snd_hctl_nonblock_called);
- EXPECT_EQ(1, snd_hctl_load_called);
- EXPECT_EQ(1, cras_alsa_mixer_create_called);
- EXPECT_EQ(0, cras_system_add_select_fd_called);
- cras_alsa_card_destroy(c);
- EXPECT_EQ(0, cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaCard, AddSelectForHctlWithDevices) {
- struct pollfd poll_fds[] = {
- {3, 0, 0},
- };
- int dev_nums[] = {0};
- int info_rets[] = {0, -1};
-
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_hctl_poll_descriptors_fds = poll_fds;
- snd_hctl_poll_descriptors_num_fds = ARRAY_SIZE(poll_fds);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(2, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(1, cras_alsa_iodev_create_called);
- EXPECT_EQ(0, cras_alsa_iodev_index_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_create_called);
- EXPECT_EQ(1, ucm_get_dev_for_mixer_called);
- EXPECT_EQ(1, ucm_get_flag_called);
- EXPECT_EQ(0, strcmp(ucm_get_flag_name, "ExtraMainVolume"));
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
- EXPECT_EQ(1, snd_hctl_open_called);
- EXPECT_EQ(1, snd_hctl_nonblock_called);
- EXPECT_EQ(1, snd_hctl_load_called);
- EXPECT_EQ(1, cras_alsa_mixer_create_called);
- ASSERT_EQ(1, cras_system_add_select_fd_called);
- EXPECT_EQ(3, cras_system_add_select_fd_values[0]);
- cras_alsa_card_destroy(c);
- EXPECT_EQ(ARRAY_SIZE(poll_fds), cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaCard, CreateFailCtlCardInfo) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_card_info_ret = -1;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(1, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_close_called);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateNoDevices) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 1;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(0, cras_alsa_iodev_create_called);
- EXPECT_EQ(0, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(1, cras_alsa_card_get_index(c));
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(0, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneOutputNextDevError) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_return_error = true;
- card_info.card_type = ALSA_CARD_TYPE_USB;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(snd_ctl_open_called, snd_ctl_close_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneOutput) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0};
- int info_rets[] = {0, -1};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_USB;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(2, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(1, cras_alsa_iodev_create_called);
- EXPECT_EQ(1, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(0, cras_alsa_iodev_index_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_create_called);
- EXPECT_EQ(1, ucm_get_dev_for_mixer_called);
- EXPECT_EQ(1, ucm_get_flag_called);
- EXPECT_EQ(0, strcmp(ucm_get_flag_name, "ExtraMainVolume"));
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(1, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[0], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneOutputBlocklisted) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0};
- int info_rets[] = {0, -1};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- alsa_iodev_has_hctl_jacks_return = 0;
- cras_device_blocklist_check_retval = 1;
- card_info.card_type = ALSA_CARD_TYPE_USB;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(2, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(0, cras_alsa_iodev_create_called);
- EXPECT_EQ(0, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(0, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(NULL, cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateTwoOutputs) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0, 3};
- int info_rets[] = {0, -1, 0};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(3, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(2, cras_alsa_iodev_create_called);
- EXPECT_EQ(2, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(1, cras_alsa_iodev_index_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(2, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[1], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateTwoDuplicateDeviceIndex) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0, 0};
- int info_rets[] = {0, -1, 0};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(3, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(1, cras_alsa_iodev_create_called);
- EXPECT_EQ(2, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(1, cras_alsa_iodev_index_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[0], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneInput) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0};
- int info_rets[] = {-1, 0};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(2, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(1, cras_alsa_iodev_create_called);
- EXPECT_EQ(1, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(0, cras_alsa_iodev_index_called);
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[0], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneInputAndOneOutput) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0};
- int info_rets[] = {0, 0};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(2, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(2, cras_alsa_iodev_create_called);
- EXPECT_EQ(2, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(0, cras_alsa_iodev_index_called);
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(2, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[1], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneInputAndOneOutputTwoDevices) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0, 3};
- int info_rets[] = {0, -1, -1, 0};
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(3, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(2, cras_alsa_iodev_create_called);
- EXPECT_EQ(2, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(0, cras_alsa_iodev_index_called);
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(2, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[1], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateOneOutputWithCoupledMixers) {
- struct cras_alsa_card* c;
- int dev_nums[] = {0};
- int info_rets[] = {0, -1};
- struct mixer_name *mixer_name_1, *mixer_name_2;
- /* Use strdup because cras_alsa_card_create will delete it. */
- const char *name1 = strdup("MixerName1"), *name2 = strdup("MixerName2");
-
- cras_alsa_card_info card_info;
-
- ResetStubData();
- snd_ctl_pcm_next_device_set_devs_size = ARRAY_SIZE(dev_nums);
- snd_ctl_pcm_next_device_set_devs = dev_nums;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
-
- /* Creates a list of mixer names as return value of
- * ucm_get_coupled_mixer_names. */
- mixer_name_1 = (struct mixer_name*)malloc(sizeof(*mixer_name_1));
- mixer_name_2 = (struct mixer_name*)malloc(sizeof(*mixer_name_2));
- mixer_name_1->name = name1;
- mixer_name_2->name = name2;
- mixer_name_1->dir = CRAS_STREAM_OUTPUT;
- mixer_name_2->dir = CRAS_STREAM_OUTPUT;
- mixer_name_1->type = MIXER_NAME_VOLUME;
- mixer_name_2->type = MIXER_NAME_VOLUME;
-
- DL_APPEND(ucm_get_coupled_mixer_names_return_value, mixer_name_1);
- DL_APPEND(ucm_get_coupled_mixer_names_return_value, mixer_name_2);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
-
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(2, snd_ctl_pcm_next_device_called);
- EXPECT_EQ(1, cras_alsa_iodev_create_called);
- EXPECT_EQ(1, cras_alsa_iodev_legacy_complete_init_called);
- EXPECT_EQ(0, cras_alsa_iodev_index_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_create_called);
- EXPECT_EQ(1, ucm_get_dev_for_mixer_called);
- EXPECT_EQ(1, ucm_get_flag_called);
- EXPECT_EQ(0, strcmp(ucm_get_flag_name, "ExtraMainVolume"));
- EXPECT_EQ(cras_card_config_dir, device_config_dir);
- EXPECT_EQ(0, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- /* Checks cras_alsa_card_create can handle the list and pass the names to
- * cras_alsa_mixer_create. */
- struct mixer_name* m_name = coupled_output_names_value;
- EXPECT_EQ(0, m_name ? strcmp(m_name->name, "MixerName1") : 1);
- if (m_name)
- m_name = m_name->next;
- EXPECT_EQ(0, m_name ? strcmp(m_name->name, "MixerName2") : 1);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(1, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[0], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-
- mixer_name_free(coupled_output_names_value);
- coupled_output_names_value = NULL;
-}
-
-TEST(AlsaCard, CreateFullyUCMNoSections) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = NULL;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(0, cras_alsa_iodev_create_called);
- EXPECT_EQ(0, cras_alsa_iodev_ucm_complete_init_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(0, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(NULL, cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateFullyUCMTwoMainVolume) {
- struct cras_alsa_card* c;
- struct mixer_name *mixer_name_1, *mixer_name_2;
- const char *name1 = strdup("MixerName1"), *name2 = strdup("MixerName2");
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
-
- /* Creates a list of mixer names as return value of
- * ucm_get_main_volume_names_return_value. */
- mixer_name_1 = (struct mixer_name*)malloc(sizeof(*mixer_name_1));
- mixer_name_2 = (struct mixer_name*)malloc(sizeof(*mixer_name_2));
- mixer_name_1->name = name1;
- mixer_name_2->name = name2;
- mixer_name_1->dir = CRAS_STREAM_OUTPUT;
- mixer_name_2->dir = CRAS_STREAM_OUTPUT;
- mixer_name_1->type = MIXER_NAME_MAIN_VOLUME;
- mixer_name_2->type = MIXER_NAME_MAIN_VOLUME;
-
- DL_APPEND(ucm_get_main_volume_names_return_value, mixer_name_1);
- DL_APPEND(ucm_get_main_volume_names_return_value, mixer_name_2);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
-
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(0, cras_alsa_iodev_create_called);
- EXPECT_EQ(0, cras_alsa_iodev_ucm_complete_init_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, cras_alsa_mixer_add_main_volume_control_by_name_called);
- EXPECT_EQ(1, ucm_get_sections_called);
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(0, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(NULL, cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, TwoUCMSecionsDependentPCM) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
- struct ucm_section* sections = NULL;
- struct ucm_section* section;
-
- /* Create UCM so that MIC1 and MIC2 will be two nodes on the same iodev. */
- section = ucm_section_create("MIC1", "hw:0,3", 0, -1, CRAS_STREAM_INPUT,
- "my-sound-card Headset Jack", "gpio");
- DL_APPEND(sections, section);
- section = ucm_section_create("MIC2", "hw:0,5", 0, 3, CRAS_STREAM_INPUT,
- "my-sound-card Headset Jack", "gpio");
- DL_APPEND(sections, section);
-
- ResetStubData();
- int info_rets[] = {0, 0};
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = sections;
- ASSERT_NE(ucm_get_sections_return_value, (struct ucm_section*)NULL);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
-
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_get_sections_called);
- EXPECT_EQ(1, snd_ctl_pcm_info_called);
- EXPECT_EQ(2, cras_alsa_mixer_add_controls_in_section_called);
- EXPECT_EQ(1, cras_alsa_iodev_create_called);
- EXPECT_EQ(2, cras_alsa_iodev_ucm_add_nodes_and_jacks_called);
- EXPECT_EQ(1, cras_alsa_iodev_ucm_complete_init_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(1, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[0], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-struct ucm_section* GenerateUcmSections(void) {
- struct ucm_section* sections = NULL;
- struct ucm_section* section;
-
- section = ucm_section_create("Headphone", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "my-sound-card Headset Jack", "gpio");
- ucm_section_add_coupled(section, "HP-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "HP-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
-
- section = ucm_section_create("Speaker", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- NULL, NULL);
- ucm_section_add_coupled(section, "SPK-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "SPK-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
-
- section = ucm_section_create("Internal Mic", "hw:0,1", 0, -1,
- CRAS_STREAM_INPUT, NULL, NULL);
- ucm_section_add_coupled(section, "INT-MIC-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "INT-MIC-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
-
- section = ucm_section_create("Mic", "hw:0,1", 1, -1, CRAS_STREAM_INPUT,
- "my-sound-card Headset Jack", "gpio");
- ucm_section_add_coupled(section, "MIC-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "MIC-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
-
- section = ucm_section_create("HDMI", "hw:0,1", 2, -1, CRAS_STREAM_OUTPUT,
- NULL, NULL);
- ucm_section_set_mixer_name(section, "HDMI");
- DL_APPEND(sections, section);
-
- return sections;
-}
-
-TEST(AlsaCard, CreateFullyUCMFailureOnControls) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = GenerateUcmSections();
- ASSERT_NE(ucm_get_sections_return_value, (struct ucm_section*)NULL);
-
- cras_alsa_mixer_add_controls_in_section_return_value = -EINVAL;
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
-
- EXPECT_EQ(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_get_sections_called);
- EXPECT_EQ(1, cras_alsa_mixer_add_controls_in_section_called);
- EXPECT_EQ(0, cras_alsa_iodev_create_called);
- EXPECT_EQ(0, cras_alsa_iodev_ucm_complete_init_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(0, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(NULL, cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, CreateFullyUCMFourDevicesFiveSections) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
- int info_rets[] = {0, 0, 0, 0, 0, -1};
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = GenerateUcmSections();
- cras_alsa_iodev_index_return[cras_alsa_iodev_create_return[0]] = 0;
- cras_alsa_iodev_index_return[cras_alsa_iodev_create_return[1]] = 0;
- cras_alsa_iodev_index_return[cras_alsa_iodev_create_return[2]] = 1;
- cras_alsa_iodev_index_return[cras_alsa_iodev_create_return[3]] = 2;
- ASSERT_NE(ucm_get_sections_return_value, (struct ucm_section*)NULL);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
-
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(snd_ctl_close_called, snd_ctl_open_called);
- EXPECT_EQ(1, snd_ctl_card_info_called);
- EXPECT_EQ(1, ucm_get_sections_called);
- EXPECT_EQ(5, snd_ctl_pcm_info_called);
- EXPECT_EQ(5, cras_alsa_mixer_add_controls_in_section_called);
- EXPECT_EQ(4, cras_alsa_iodev_create_called);
- EXPECT_EQ(5, cras_alsa_iodev_ucm_add_nodes_and_jacks_called);
- EXPECT_EQ(4, cras_alsa_iodev_ucm_complete_init_called);
-
- cras_alsa_card_destroy(c);
- EXPECT_EQ(1, ucm_destroy_called);
- EXPECT_EQ(4, cras_alsa_iodev_destroy_called);
- EXPECT_EQ(cras_alsa_iodev_create_return[3], cras_alsa_iodev_destroy_arg);
- EXPECT_EQ(cras_alsa_mixer_create_called, cras_alsa_mixer_destroy_called);
- EXPECT_EQ(iniparser_load_called, iniparser_freedict_called);
-}
-
-TEST(AlsaCard, GG) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
- int info_rets[] = {0, 0, 0, 0, 0, -1};
- struct cras_ionode nodes[4];
- const char* echo_ref = "echo ref";
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = GenerateUcmSections();
-
- fake_dev1.nodes = nodes;
- fake_dev2.nodes = nodes + 1;
- fake_dev3.nodes = nodes + 2;
- fake_dev4.nodes = nodes + 3;
- snprintf(nodes[0].name, CRAS_NODE_NAME_BUFFER_SIZE, "dev1");
- snprintf(nodes[1].name, CRAS_NODE_NAME_BUFFER_SIZE, "dev2");
- snprintf(nodes[2].name, CRAS_NODE_NAME_BUFFER_SIZE, "dev3");
- snprintf(nodes[3].name, CRAS_NODE_NAME_BUFFER_SIZE, "echo ref");
-
- ucm_get_echo_reference_dev_name_for_dev_return_value[0] = strdup(echo_ref);
-
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- NULL);
-
- EXPECT_NE(static_cast<struct cras_alsa_card*>(NULL), c);
- EXPECT_EQ(fake_dev1.echo_reference_dev, &fake_dev4);
- cras_alsa_card_destroy(c);
-}
-
-TEST(AlsaCard, UCMSuffix) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
- int info_rets[] = {0, 0, 0, 0, 0, -1};
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = GenerateUcmSections();
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- "1mic");
- EXPECT_EQ(0, strcmp(ucm_create_name, "TestName.1mic"));
- EXPECT_EQ(1, cras_system_check_ignore_ucm_suffix_called);
- cras_alsa_card_destroy(c);
-}
-
-TEST(AlsaCard, UCMIgnoreSuffix) {
- struct cras_alsa_card* c;
- cras_alsa_card_info card_info;
- int info_rets[] = {0, 0, 0, 0, 0, -1};
-
- ResetStubData();
- card_info.card_type = ALSA_CARD_TYPE_INTERNAL;
- card_info.card_index = 0;
- snd_ctl_pcm_info_rets_size = ARRAY_SIZE(info_rets);
- snd_ctl_pcm_info_rets = info_rets;
- ucm_has_fully_specified_ucm_flag_return_value = 1;
- ucm_get_sections_return_value = GenerateUcmSections();
- cras_system_check_ignore_ucm_suffix_value = true;
- c = cras_alsa_card_create(&card_info, device_config_dir, fake_blocklist,
- "1mic");
- EXPECT_EQ(0, strcmp(ucm_create_name, "TestName"));
- EXPECT_EQ(1, cras_system_check_ignore_ucm_suffix_called);
- cras_alsa_card_destroy(c);
-}
-
-/* Stubs */
-
-extern "C" {
-struct cras_alsa_mixer* cras_alsa_mixer_create(const char* card_name) {
- cras_alsa_mixer_create_called++;
- return cras_alsa_mixer_create_return;
-}
-
-int cras_alsa_mixer_add_controls_by_name_matching(
- struct cras_alsa_mixer* cmix,
- struct mixer_name* extra_controls,
- struct mixer_name* coupled_controls) {
- /* Duplicate coupled_output_names to verify in the end of unittest
- * because names will get freed later in cras_alsa_card_create. */
- struct mixer_name* control;
- DL_FOREACH (coupled_controls, control) {
- coupled_output_names_value =
- mixer_name_add(coupled_output_names_value, control->name,
- CRAS_STREAM_OUTPUT, control->type);
- }
- return 0;
-}
-
-void cras_alsa_mixer_destroy(struct cras_alsa_mixer* cras_mixer) {
- cras_alsa_mixer_destroy_called++;
-}
-
-struct cras_iodev* alsa_iodev_create(size_t card_index,
- const char* card_name,
- size_t device_index,
- const char* pcm_name,
- const char* dev_name,
- const char* dev_id,
- enum CRAS_ALSA_CARD_TYPE card_type,
- int is_first,
- struct cras_alsa_mixer* mixer,
- const struct cras_card_config* config,
- struct cras_use_case_mgr* ucm,
- snd_hctl_t* hctl,
- enum CRAS_STREAM_DIRECTION direction,
- size_t usb_vid,
- size_t usb_pid,
- char* usb_serial_number) {
- struct cras_iodev* result = NULL;
- if (cras_alsa_iodev_create_called < cras_alsa_iodev_create_return_size)
- result = cras_alsa_iodev_create_return[cras_alsa_iodev_create_called];
- cras_alsa_iodev_create_called++;
- return result;
-}
-void alsa_iodev_destroy(struct cras_iodev* iodev) {
- cras_alsa_iodev_destroy_called++;
- cras_alsa_iodev_destroy_arg = iodev;
-}
-int alsa_iodev_legacy_complete_init(struct cras_iodev* iodev) {
- cras_alsa_iodev_legacy_complete_init_called++;
- return 0;
-}
-int alsa_iodev_ucm_add_nodes_and_jacks(struct cras_iodev* iodev,
- struct ucm_section* section) {
- cras_alsa_iodev_ucm_add_nodes_and_jacks_called++;
- return 0;
-}
-void alsa_iodev_ucm_complete_init(struct cras_iodev* iodev) {
- cras_alsa_iodev_ucm_complete_init_called++;
-}
-unsigned alsa_iodev_index(struct cras_iodev* iodev) {
- std::map<struct cras_iodev*, unsigned int>::iterator i;
- cras_alsa_iodev_index_called++;
- i = cras_alsa_iodev_index_return.find(iodev);
- if (i != cras_alsa_iodev_index_return.end())
- return i->second;
- return 0;
-}
-int alsa_iodev_has_hctl_jacks(struct cras_iodev* iodev) {
- return alsa_iodev_has_hctl_jacks_return;
-}
-
-size_t snd_pcm_info_sizeof() {
- return 10;
-}
-size_t snd_ctl_card_info_sizeof() {
- return 10;
-}
-int snd_ctl_open(snd_ctl_t** handle, const char* name, int card) {
- snd_ctl_open_called++;
- if (snd_ctl_open_return == 0)
- *handle = reinterpret_cast<snd_ctl_t*>(0xff);
- else
- *handle = NULL;
- return snd_ctl_open_return;
-}
-int snd_ctl_close(snd_ctl_t* handle) {
- snd_ctl_close_called++;
- return snd_ctl_close_return;
-}
-int snd_ctl_pcm_next_device(snd_ctl_t* ctl, int* device) {
- if (snd_ctl_pcm_next_device_return_error) {
- *device = 10;
- return -1;
- }
- snd_ctl_pcm_next_device_called++;
- if (snd_ctl_pcm_next_device_set_devs_index >=
- snd_ctl_pcm_next_device_set_devs_size) {
- *device = -1;
- return 0;
- }
- *device =
- snd_ctl_pcm_next_device_set_devs[snd_ctl_pcm_next_device_set_devs_index];
- snd_ctl_pcm_next_device_set_devs_index++;
- return 0;
-}
-void snd_pcm_info_set_device(snd_pcm_info_t* obj, unsigned int val) {}
-void snd_pcm_info_set_subdevice(snd_pcm_info_t* obj, unsigned int val) {}
-void snd_pcm_info_set_stream(snd_pcm_info_t* obj, snd_pcm_stream_t val) {}
-const char* snd_pcm_info_get_name(const snd_pcm_info_t* obj) {
- return "Fake device name";
-}
-const char* snd_pcm_info_get_id(const snd_pcm_info_t* obj) {
- return "Fake device id";
-}
-int snd_ctl_pcm_info(snd_ctl_t* ctl, snd_pcm_info_t* info) {
- int ret;
- snd_ctl_pcm_info_called++;
- if (snd_ctl_pcm_info_rets_index >= snd_ctl_pcm_info_rets_size) {
- return -1;
- }
- ret = snd_ctl_pcm_info_rets[snd_ctl_pcm_info_rets_index];
- snd_ctl_pcm_info_rets_index++;
- return ret;
-}
-int snd_ctl_card_info(snd_ctl_t* ctl, snd_ctl_card_info_t* info) {
- snd_ctl_card_info_called++;
- return snd_ctl_card_info_ret;
-}
-const char* snd_ctl_card_info_get_name(const snd_ctl_card_info_t* obj) {
- return "TestName";
-}
-const char* snd_ctl_card_info_get_id(const snd_ctl_card_info_t* obj) {
- return "TestId";
-}
-int snd_hctl_open(snd_hctl_t** hctlp, const char* name, int mode) {
- *hctlp = snd_hctl_open_pointer_val;
- snd_hctl_open_called++;
- return snd_hctl_open_return_value;
-}
-int snd_hctl_nonblock(snd_hctl_t* hctl, int nonblock) {
- snd_hctl_nonblock_called++;
- return 0;
-}
-int snd_hctl_load(snd_hctl_t* hctl) {
- snd_hctl_load_called++;
- return snd_hctl_load_return_value;
-}
-int snd_hctl_close(snd_hctl_t* hctl) {
- snd_hctl_close_called++;
- return 0;
-}
-int snd_hctl_poll_descriptors_count(snd_hctl_t* hctl) {
- return snd_hctl_poll_descriptors_num_fds;
-}
-int snd_hctl_poll_descriptors(snd_hctl_t* hctl,
- struct pollfd* pfds,
- unsigned int space) {
- unsigned int num = MIN(space, snd_hctl_poll_descriptors_num_fds);
- memcpy(pfds, snd_hctl_poll_descriptors_fds, num * sizeof(*pfds));
- snd_hctl_poll_descriptors_called++;
- return num;
-}
-int snd_hctl_handle_events(snd_hctl_t* hctl) {
- snd_hctl_handle_events_called++;
- return 0;
-}
-
-int cras_system_add_select_fd(int fd,
- void (*callback)(void* data),
- void* callback_data) {
- cras_system_add_select_fd_called++;
- cras_system_add_select_fd_values.push_back(fd);
- return 0;
-}
-void cras_system_rm_select_fd(int fd) {
- cras_system_rm_select_fd_called++;
- cras_system_rm_select_fd_values.push_back(fd);
-}
-
-struct cras_card_config* cras_card_config_create(const char* config_path,
- const char* card_name) {
- cras_card_config_dir = config_path;
- return NULL;
-}
-
-void cras_card_config_destroy(struct cras_card_config* card_config) {}
-
-struct cras_volume_curve* cras_card_config_get_volume_curve_for_control(
- const struct cras_card_config* card_config,
- const char* control_name) {
- return NULL;
-}
-
-int cras_device_blocklist_check(struct cras_device_blocklist* blocklist,
- unsigned vendor_id,
- unsigned product_id,
- unsigned device_index) {
- EXPECT_EQ(fake_blocklist, blocklist);
-
- return cras_device_blocklist_check_retval;
-}
-
-struct cras_use_case_mgr* ucm_create(const char* name) {
- ucm_create_called++;
- strncpy(ucm_create_name, name, sizeof(ucm_create_name) - 1);
- return reinterpret_cast<struct cras_use_case_mgr*>(0x44);
-}
-
-void ucm_destroy(struct cras_use_case_mgr* mgr) {
- ucm_destroy_called++;
-}
-
-char* ucm_get_dev_for_mixer(struct cras_use_case_mgr* mgr,
- const char* mixer,
- enum CRAS_STREAM_DIRECTION dir) {
- ucm_get_dev_for_mixer_called++;
- return strdup("device");
-}
-
-char* ucm_get_flag(struct cras_use_case_mgr* mgr, const char* flag_name) {
- ucm_get_flag_called++;
- strncpy(ucm_get_flag_name, flag_name, sizeof(ucm_get_flag_name) - 1);
- return NULL;
-}
-
-struct mixer_name* ucm_get_coupled_mixer_names(struct cras_use_case_mgr* mgr,
- const char* dev) {
- return ucm_get_coupled_mixer_names_return_value;
-}
-
-int ucm_has_fully_specified_ucm_flag(struct cras_use_case_mgr* mgr) {
- return ucm_has_fully_specified_ucm_flag_return_value;
-}
-
-struct mixer_name* ucm_get_main_volume_names(struct cras_use_case_mgr* mgr) {
- return ucm_get_main_volume_names_return_value;
-}
-
-struct ucm_section* ucm_get_sections(struct cras_use_case_mgr* mgr) {
- ucm_get_sections_called++;
- return ucm_get_sections_return_value;
-}
-const char* ucm_get_echo_reference_dev_name_for_dev(
- struct cras_use_case_mgr* mgr,
- const char* dev) {
- int idx = ucm_get_echo_reference_dev_name_for_dev_called++;
- return ucm_get_echo_reference_dev_name_for_dev_return_value[idx];
-}
-
-int cras_alsa_mixer_add_main_volume_control_by_name(
- struct cras_alsa_mixer* cmix,
- struct mixer_name* mixer_names) {
- cras_alsa_mixer_add_main_volume_control_by_name_called++;
- return cras_alsa_mixer_add_main_volume_control_by_name_return_value;
-}
-
-int cras_alsa_mixer_add_controls_in_section(struct cras_alsa_mixer* cmix,
- struct ucm_section* section) {
- cras_alsa_mixer_add_controls_in_section_called++;
- return cras_alsa_mixer_add_controls_in_section_return_value;
-}
-
-bool cras_system_check_ignore_ucm_suffix(const char* card_name) {
- cras_system_check_ignore_ucm_suffix_called++;
- return cras_system_check_ignore_ucm_suffix_value;
-}
-
-void ucm_free_mixer_names(struct mixer_name* names) {
- struct mixer_name* m;
- DL_FOREACH (names, m) {
- DL_DELETE(names, m);
- free((void*)m->name);
- free(m);
- }
-}
-
-} /* extern "C" */
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/alsa_helpers_unittest.cc b/cras/src/tests/alsa_helpers_unittest.cc
deleted file mode 100644
index 32df30af..00000000
--- a/cras/src/tests/alsa_helpers_unittest.cc
+++ /dev/null
@@ -1,293 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-#include <vector>
-
-extern "C" {
-// For static function test.
-#include "cras_alsa_helpers.c"
-}
-
-static int snd_pcm_sw_params_set_tstamp_type_called;
-static int snd_pcm_sw_params_set_tstamp_mode_called;
-static snd_pcm_uframes_t snd_pcm_htimestamp_avail_ret_val;
-static timespec snd_pcm_htimestamp_tstamp_ret_val;
-static std::vector<int> snd_pcm_sw_params_ret_vals;
-
-static void ResetStubData() {
- snd_pcm_sw_params_set_tstamp_type_called = 0;
- snd_pcm_sw_params_set_tstamp_mode_called = 0;
- snd_pcm_htimestamp_avail_ret_val = 0;
- snd_pcm_htimestamp_tstamp_ret_val.tv_sec = 0;
- snd_pcm_htimestamp_tstamp_ret_val.tv_nsec = 0;
- snd_pcm_sw_params_ret_vals.clear();
-}
-
-namespace {
-
-static snd_pcm_chmap_query_t* create_chmap_cap(snd_pcm_chmap_type type,
- size_t channels) {
- snd_pcm_chmap_query_t* c;
- c = (snd_pcm_chmap_query_t*)calloc(channels + 2, sizeof(int));
- c->type = type;
- c->map.channels = channels;
- return c;
-}
-
-TEST(AlsaHelper, MatchChannelMapCapabilityStereo) {
- snd_pcm_chmap_query_t** caps;
- snd_pcm_chmap_query_t* c;
- struct cras_audio_format* fmt;
-
- caps = (snd_pcm_chmap_query_t**)calloc(4, sizeof(*caps));
-
- /* Layout (CRAS_CH_RL, CRAS_CH_RR) corresponds to
- * ALSA channel map (5, 6)
- */
- int8_t channel_layout[CRAS_CH_MAX] = {-1, -1, 0, 1, -1, -1,
- -1, -1, -1, -1, -1};
-
- fmt = cras_audio_format_create(SND_PCM_FORMAT_S16_LE, 44100, 2);
- cras_audio_format_set_channel_layout(fmt, channel_layout);
-
- /* Create a list of capabilities */
- c = create_chmap_cap(SND_CHMAP_TYPE_FIXED, 3);
- c->map.pos[0] = 3;
- c->map.pos[1] = 4;
- c->map.pos[2] = 5;
- caps[0] = c;
-
- c = create_chmap_cap(SND_CHMAP_TYPE_VAR, 2);
- c->map.pos[0] = 5;
- c->map.pos[1] = 6;
- caps[1] = c;
-
- c = create_chmap_cap(SND_CHMAP_TYPE_VAR, 2);
- c->map.pos[0] = 9;
- c->map.pos[1] = 10;
- caps[2] = c;
-
- caps[3] = NULL;
-
- /* Test if there's a cap matches fmt */
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_NE((void*)NULL, c);
-
- caps[1]->map.pos[0] = 5;
- caps[1]->map.pos[1] = 7;
-
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_EQ((void*)NULL, c);
-
- free(caps[0]);
- free(caps[1]);
- free(caps[2]);
- free(caps[3]);
- free(caps);
- cras_audio_format_destroy(fmt);
-}
-
-TEST(AlsaHelper, MatchChannelMapCapability51) {
- snd_pcm_chmap_query_t** caps = NULL;
- snd_pcm_chmap_query_t* c = NULL;
- struct cras_audio_format* fmt;
-
- caps = (snd_pcm_chmap_query_t**)calloc(4, sizeof(*caps));
-
- /* Layout (CRAS_CH_FL, CRAS_CH_FR, CRAS_CH_RL, CRAS_CH_RR, CRAS_CH_FC)
- * corresponds to ALSA channel map (3, 4, 5, 6, 7)
- */
- int8_t channel_layout[CRAS_CH_MAX] = {0, 1, 2, 3, 4, 5, -1, -1, -1, -1, -1};
-
- fmt = cras_audio_format_create(SND_PCM_FORMAT_S16_LE, 44100, 6);
- cras_audio_format_set_channel_layout(fmt, channel_layout);
-
- /* Create a list of capabilities */
- c = create_chmap_cap(SND_CHMAP_TYPE_FIXED, 6);
- c->map.pos[0] = 3;
- c->map.pos[1] = 4;
- c->map.pos[2] = 5;
- c->map.pos[3] = 6;
- c->map.pos[4] = 7;
- c->map.pos[5] = 8;
- caps[0] = c;
-
- c = create_chmap_cap(SND_CHMAP_TYPE_VAR, 2);
- c->map.pos[0] = 6;
- c->map.pos[1] = 4;
- caps[1] = c;
-
- c = create_chmap_cap(SND_CHMAP_TYPE_VAR, 6);
- c->map.pos[0] = 9;
- c->map.pos[1] = 10;
- c->map.pos[2] = 5;
- c->map.pos[3] = 6;
- c->map.pos[4] = 7;
- c->map.pos[5] = 8;
- caps[2] = c;
- caps[3] = NULL;
-
- /* Test if there's a cap matches fmt */
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_NE((void*)NULL, c);
-
- caps[0]->map.pos[0] = 7;
- caps[0]->map.pos[1] = 8;
- caps[0]->map.pos[4] = 3;
- caps[0]->map.pos[5] = 4;
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_EQ((void*)NULL, c);
-
- caps[0]->type = SND_CHMAP_TYPE_PAIRED;
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_NE((void*)NULL, c);
-
- caps[0]->map.pos[0] = 8;
- caps[0]->map.pos[1] = 7;
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_EQ((void*)NULL, c);
-
- caps[0]->type = SND_CHMAP_TYPE_VAR;
- c = cras_chmap_caps_match(caps, fmt);
- ASSERT_NE((void*)NULL, c);
-
- free(caps[0]);
- free(caps[1]);
- free(caps[2]);
- free(caps[3]);
- free(caps);
- cras_audio_format_destroy(fmt);
-}
-
-TEST(AlsaHelper, Htimestamp) {
- snd_pcm_t* mock_handle = reinterpret_cast<snd_pcm_t*>(0x1);
- snd_pcm_uframes_t used;
- snd_pcm_uframes_t severe_underrun_frames = 480;
- struct timespec tstamp;
- const char* dev_name = "dev_name";
-
- ResetStubData();
- tstamp.tv_sec = 0;
- tstamp.tv_nsec = 0;
- snd_pcm_htimestamp_avail_ret_val = 20000;
- snd_pcm_htimestamp_tstamp_ret_val.tv_sec = 10;
- snd_pcm_htimestamp_tstamp_ret_val.tv_nsec = 10000;
-
- cras_alsa_get_avail_frames(mock_handle, 48000, severe_underrun_frames,
- dev_name, &used, &tstamp);
- EXPECT_EQ(used, snd_pcm_htimestamp_avail_ret_val);
- EXPECT_EQ(tstamp.tv_sec, snd_pcm_htimestamp_tstamp_ret_val.tv_sec);
- EXPECT_EQ(tstamp.tv_nsec, snd_pcm_htimestamp_tstamp_ret_val.tv_nsec);
-}
-
-TEST(AlsaHelper, GetAvailFramesSevereUnderrun) {
- snd_pcm_t* mock_handle = reinterpret_cast<snd_pcm_t*>(0x1);
- snd_pcm_uframes_t avail;
- snd_pcm_uframes_t severe_underrun_frames = 480;
- snd_pcm_uframes_t buffer_size = 48000;
- struct timespec tstamp;
- int rc;
- const char* dev_name = "dev_name";
-
- ResetStubData();
- snd_pcm_htimestamp_avail_ret_val = buffer_size + severe_underrun_frames + 1;
- rc = cras_alsa_get_avail_frames(mock_handle, buffer_size,
- severe_underrun_frames, dev_name, &avail,
- &tstamp);
- // Returns -EPIPE when severe underrun happens.
- EXPECT_EQ(rc, -EPIPE);
-
- ResetStubData();
- snd_pcm_htimestamp_avail_ret_val = buffer_size + severe_underrun_frames;
- rc = cras_alsa_get_avail_frames(mock_handle, buffer_size,
- severe_underrun_frames, dev_name, &avail,
- &tstamp);
- // Underrun which is not severe enough will be masked.
- // avail will be adjusted to buffer_size.
- EXPECT_EQ(avail, buffer_size);
- EXPECT_EQ(rc, 0);
-
- ResetStubData();
- snd_pcm_htimestamp_avail_ret_val = buffer_size - 1;
- rc = cras_alsa_get_avail_frames(mock_handle, buffer_size,
- severe_underrun_frames, dev_name, &avail,
- &tstamp);
- // When avail < buffer_size, there is no underrun.
- EXPECT_EQ(avail, buffer_size - 1);
- EXPECT_EQ(rc, 0);
-}
-} // namespace
-
-extern "C" {
-
-int snd_pcm_sw_params_current(snd_pcm_t* pcm, snd_pcm_sw_params_t* params) {
- return 0;
-}
-
-int snd_pcm_sw_params_get_boundary(const snd_pcm_sw_params_t* params,
- snd_pcm_uframes_t* val) {
- return 0;
-}
-
-int snd_pcm_sw_params_set_stop_threshold(snd_pcm_t* pcm,
- snd_pcm_sw_params_t* params,
- snd_pcm_uframes_t val) {
- return 0;
-}
-
-int snd_pcm_sw_params_set_start_threshold(snd_pcm_t* pcm,
- snd_pcm_sw_params_t* params,
- snd_pcm_uframes_t val) {
- return 0;
-}
-
-int snd_pcm_sw_params_set_period_event(snd_pcm_t* pcm,
- snd_pcm_sw_params_t* params,
- int val) {
- return 0;
-}
-
-int snd_pcm_sw_params_set_tstamp_mode(snd_pcm_t* pcm,
- snd_pcm_sw_params_t* params,
- snd_pcm_tstamp_t val) {
- snd_pcm_sw_params_set_tstamp_mode_called++;
- return 0;
-}
-
-int snd_pcm_sw_params_set_tstamp_type(snd_pcm_t* pcm,
- snd_pcm_sw_params_t* params,
- snd_pcm_tstamp_type_t val) {
- snd_pcm_sw_params_set_tstamp_type_called++;
- return 0;
-}
-
-int snd_pcm_sw_params(snd_pcm_t* pcm, snd_pcm_sw_params_t* params) {
- int rc;
-
- if (snd_pcm_sw_params_ret_vals.size() == 0)
- return 0;
- rc = snd_pcm_sw_params_ret_vals.back();
- snd_pcm_sw_params_ret_vals.pop_back();
- return rc;
-}
-
-snd_pcm_sframes_t snd_pcm_avail(snd_pcm_t* pcm) {
- return snd_pcm_htimestamp_avail_ret_val;
-}
-
-int snd_pcm_htimestamp(snd_pcm_t* pcm,
- snd_pcm_uframes_t* avail,
- snd_htimestamp_t* tstamp) {
- *avail = snd_pcm_htimestamp_avail_ret_val;
- *tstamp = snd_pcm_htimestamp_tstamp_ret_val;
- return 0;
-}
-}
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/alsa_io_unittest.cc b/cras/src/tests/alsa_io_unittest.cc
deleted file mode 100644
index 021b4789..00000000
--- a/cras/src/tests/alsa_io_unittest.cc
+++ /dev/null
@@ -1,3045 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <syslog.h>
-
-#include <map>
-#include <vector>
-
-extern "C" {
-
-#include "cras_alsa_mixer.h"
-#include "cras_iodev.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-
-// Include C file to test static functions.
-#include "cras_alsa_io.c"
-}
-
-#define BUFFER_SIZE 8192
-
-// Data for simulating functions stubbed below.
-static int cras_alsa_open_called;
-static int cras_iodev_append_stream_ret;
-static int cras_alsa_get_avail_frames_ret;
-static int cras_alsa_get_avail_frames_avail;
-static int cras_alsa_start_called;
-static uint8_t* cras_alsa_mmap_begin_buffer;
-static size_t cras_alsa_mmap_begin_frames;
-static size_t cras_alsa_fill_properties_called;
-static bool cras_alsa_support_8_channels;
-static size_t alsa_mixer_set_dBFS_called;
-static int alsa_mixer_set_dBFS_value;
-static const struct mixer_control* alsa_mixer_set_dBFS_output;
-static size_t alsa_mixer_set_capture_dBFS_called;
-static int alsa_mixer_set_capture_dBFS_value;
-static const struct mixer_control* alsa_mixer_set_capture_dBFS_input;
-static const struct mixer_control*
- cras_alsa_mixer_get_minimum_capture_gain_mixer_input;
-static const struct mixer_control*
- cras_alsa_mixer_get_maximum_capture_gain_mixer_input;
-static size_t cras_alsa_mixer_list_outputs_called;
-static size_t cras_alsa_mixer_list_inputs_called;
-static size_t cras_alsa_mixer_get_control_for_section_called;
-static struct mixer_control*
- cras_alsa_mixer_get_control_for_section_return_value;
-static size_t sys_get_volume_called;
-static size_t sys_get_volume_return_value;
-static size_t alsa_mixer_set_mute_called;
-static int alsa_mixer_set_mute_value;
-static size_t alsa_mixer_get_dB_range_called;
-static long alsa_mixer_get_dB_range_value;
-static size_t alsa_mixer_get_output_dB_range_called;
-static long alsa_mixer_get_output_dB_range_value;
-static const struct mixer_control* alsa_mixer_set_mute_output;
-static size_t alsa_mixer_set_capture_mute_called;
-static int alsa_mixer_set_capture_mute_value;
-static const struct mixer_control* alsa_mixer_set_capture_mute_input;
-static size_t sys_get_mute_called;
-static int sys_get_mute_return_value;
-static size_t sys_get_capture_mute_called;
-static int sys_get_capture_mute_return_value;
-static struct cras_alsa_mixer* fake_mixer = (struct cras_alsa_mixer*)1;
-static struct cras_card_config* fake_config = (struct cras_card_config*)2;
-static struct mixer_control** cras_alsa_mixer_list_outputs_outputs;
-static size_t cras_alsa_mixer_list_outputs_outputs_length;
-static struct mixer_control** cras_alsa_mixer_list_inputs_outputs;
-static size_t cras_alsa_mixer_list_inputs_outputs_length;
-static size_t cras_alsa_mixer_set_output_active_state_called;
-static std::vector<struct mixer_control*>
- cras_alsa_mixer_set_output_active_state_outputs;
-static std::vector<int> cras_alsa_mixer_set_output_active_state_values;
-static cras_audio_format* fake_format;
-static size_t sys_set_volume_limits_called;
-static size_t cras_alsa_mixer_get_minimum_capture_gain_called;
-static size_t cras_alsa_mixer_get_maximum_capture_gain_called;
-static struct mixer_control* cras_alsa_jack_get_mixer_output_ret;
-static struct mixer_control* cras_alsa_jack_get_mixer_input_ret;
-static size_t cras_alsa_mixer_get_output_volume_curve_called;
-typedef std::map<const struct mixer_control*, std::string> ControlNameMap;
-static ControlNameMap cras_alsa_mixer_get_control_name_values;
-static size_t cras_alsa_mixer_get_control_name_called;
-static size_t cras_alsa_jack_list_create_called;
-static size_t cras_alsa_jack_list_find_jacks_by_name_matching_called;
-static size_t cras_alsa_jack_list_add_jack_for_section_called;
-static struct cras_alsa_jack*
- cras_alsa_jack_list_add_jack_for_section_result_jack;
-static size_t cras_alsa_jack_list_destroy_called;
-static int cras_alsa_jack_list_has_hctl_jacks_return_val;
-static jack_state_change_callback* cras_alsa_jack_list_create_cb;
-static void* cras_alsa_jack_list_create_cb_data;
-static char test_card_name[] = "TestCard";
-static char test_pcm_name[] = "TestPCM";
-static char test_dev_name[] = "TestDev";
-static char test_dev_id[] = "TestDevId";
-static size_t cras_iodev_add_node_called;
-static struct cras_ionode* cras_iodev_set_node_plugged_ionode;
-static size_t cras_iodev_set_node_plugged_called;
-static int cras_iodev_set_node_plugged_value;
-static unsigned cras_alsa_jack_enable_ucm_called;
-static unsigned ucm_set_enabled_called;
-static size_t cras_iodev_update_dsp_called;
-static const char* cras_iodev_update_dsp_name;
-typedef std::map<const char*, std::string> DspNameMap;
-static size_t ucm_get_dsp_name_for_dev_called;
-static DspNameMap ucm_get_dsp_name_for_dev_values;
-static size_t cras_iodev_free_resources_called;
-static size_t cras_alsa_jack_update_node_type_called;
-static int ucm_swap_mode_exists_ret_value;
-static int ucm_enable_swap_mode_ret_value;
-static size_t ucm_enable_swap_mode_called;
-static int is_utf8_string_ret_value;
-static const char* cras_alsa_jack_update_monitor_fake_name = 0;
-static int cras_alsa_jack_get_name_called;
-static const char* cras_alsa_jack_get_name_ret_value = 0;
-static char default_jack_name[] = "Something Jack";
-static int auto_unplug_input_node_ret = 0;
-static int auto_unplug_output_node_ret = 0;
-static long cras_alsa_mixer_get_minimum_capture_gain_ret_value;
-static long cras_alsa_mixer_get_maximum_capture_gain_ret_value;
-static snd_pcm_state_t snd_pcm_state_ret;
-static int cras_alsa_attempt_resume_called;
-static snd_hctl_t* fake_hctl = (snd_hctl_t*)2;
-static size_t ucm_get_dma_period_for_dev_called;
-static unsigned int ucm_get_dma_period_for_dev_ret;
-static int cras_card_config_get_volume_curve_for_control_called;
-typedef std::map<std::string, struct cras_volume_curve*> VolCurveMap;
-static VolCurveMap cras_card_config_get_volume_curve_vals;
-static int cras_alsa_mmap_get_whole_buffer_called;
-static int cras_iodev_fill_odev_zeros_called;
-static unsigned int cras_iodev_fill_odev_zeros_frames;
-static int cras_iodev_frames_queued_ret;
-static int cras_iodev_buffer_avail_ret;
-static int cras_alsa_resume_appl_ptr_called;
-static int cras_alsa_resume_appl_ptr_ahead;
-static const struct cras_volume_curve* fake_get_dBFS_volume_curve_val;
-static int cras_iodev_dsp_set_swap_mode_for_node_called;
-static std::map<std::string, long> ucm_get_default_node_gain_values;
-static std::map<std::string, long> ucm_get_intrinsic_sensitivity_values;
-static thread_callback audio_thread_cb;
-static void* audio_thread_cb_data;
-static int hotword_send_triggered_msg_called;
-static struct timespec clock_gettime_retspec;
-static unsigned cras_iodev_reset_rate_estimator_called;
-
-void ResetStubData() {
- cras_alsa_open_called = 0;
- cras_iodev_append_stream_ret = 0;
- cras_alsa_get_avail_frames_ret = 0;
- cras_alsa_get_avail_frames_avail = 0;
- cras_alsa_start_called = 0;
- cras_alsa_fill_properties_called = 0;
- cras_alsa_support_8_channels = false;
- sys_get_volume_called = 0;
- alsa_mixer_set_dBFS_called = 0;
- alsa_mixer_set_capture_dBFS_called = 0;
- sys_get_mute_called = 0;
- sys_get_capture_mute_called = 0;
- alsa_mixer_set_mute_called = 0;
- alsa_mixer_get_dB_range_called = 0;
- alsa_mixer_get_output_dB_range_called = 0;
- alsa_mixer_set_capture_mute_called = 0;
- cras_alsa_mixer_get_control_for_section_called = 0;
- cras_alsa_mixer_get_control_for_section_return_value = NULL;
- cras_alsa_mixer_list_outputs_called = 0;
- cras_alsa_mixer_list_outputs_outputs_length = 0;
- cras_alsa_mixer_list_inputs_called = 0;
- cras_alsa_mixer_list_inputs_outputs_length = 0;
- cras_alsa_mixer_set_output_active_state_called = 0;
- cras_alsa_mixer_set_output_active_state_outputs.clear();
- cras_alsa_mixer_set_output_active_state_values.clear();
- sys_set_volume_limits_called = 0;
- cras_alsa_mixer_get_minimum_capture_gain_called = 0;
- cras_alsa_mixer_get_maximum_capture_gain_called = 0;
- cras_alsa_mixer_get_output_volume_curve_called = 0;
- cras_alsa_jack_get_mixer_output_ret = NULL;
- cras_alsa_jack_get_mixer_input_ret = NULL;
- cras_alsa_mixer_get_control_name_values.clear();
- cras_alsa_mixer_get_control_name_called = 0;
- cras_alsa_jack_list_create_called = 0;
- cras_alsa_jack_list_find_jacks_by_name_matching_called = 0;
- cras_alsa_jack_list_add_jack_for_section_called = 0;
- cras_alsa_jack_list_add_jack_for_section_result_jack = NULL;
- cras_alsa_jack_list_destroy_called = 0;
- cras_alsa_jack_list_has_hctl_jacks_return_val = 1;
- cras_iodev_add_node_called = 0;
- cras_iodev_set_node_plugged_called = 0;
- cras_alsa_jack_enable_ucm_called = 0;
- ucm_set_enabled_called = 0;
- cras_iodev_update_dsp_called = 0;
- cras_iodev_update_dsp_name = 0;
- ucm_get_dsp_name_for_dev_called = 0;
- ucm_get_dsp_name_for_dev_values.clear();
- cras_iodev_free_resources_called = 0;
- cras_alsa_jack_update_node_type_called = 0;
- ucm_swap_mode_exists_ret_value = 0;
- ucm_enable_swap_mode_ret_value = 0;
- ucm_enable_swap_mode_called = 0;
- is_utf8_string_ret_value = 1;
- cras_alsa_jack_get_name_called = 0;
- cras_alsa_jack_get_name_ret_value = default_jack_name;
- cras_alsa_jack_update_monitor_fake_name = 0;
- cras_card_config_get_volume_curve_for_control_called = 0;
- cras_card_config_get_volume_curve_vals.clear();
- cras_alsa_mixer_get_minimum_capture_gain_ret_value = 0;
- cras_alsa_mixer_get_maximum_capture_gain_ret_value = 0;
- snd_pcm_state_ret = SND_PCM_STATE_RUNNING;
- cras_alsa_attempt_resume_called = 0;
- ucm_get_dma_period_for_dev_called = 0;
- ucm_get_dma_period_for_dev_ret = 0;
- cras_alsa_mmap_get_whole_buffer_called = 0;
- cras_iodev_fill_odev_zeros_called = 0;
- cras_iodev_fill_odev_zeros_frames = 0;
- cras_iodev_frames_queued_ret = 0;
- cras_iodev_buffer_avail_ret = 0;
- cras_alsa_resume_appl_ptr_called = 0;
- cras_alsa_resume_appl_ptr_ahead = 0;
- fake_get_dBFS_volume_curve_val = NULL;
- cras_iodev_dsp_set_swap_mode_for_node_called = 0;
- ucm_get_default_node_gain_values.clear();
- ucm_get_intrinsic_sensitivity_values.clear();
- cras_iodev_reset_rate_estimator_called = 0;
-}
-
-static long fake_get_dBFS(const struct cras_volume_curve* curve,
- size_t volume) {
- fake_get_dBFS_volume_curve_val = curve;
- return (volume - 100) * 100;
-}
-static cras_volume_curve default_curve = {
- .get_dBFS = fake_get_dBFS,
-};
-
-static struct cras_iodev* alsa_iodev_create_with_default_parameters(
- size_t card_index,
- const char* dev_id,
- enum CRAS_ALSA_CARD_TYPE card_type,
- int is_first,
- struct cras_alsa_mixer* mixer,
- struct cras_card_config* config,
- struct cras_use_case_mgr* ucm,
- enum CRAS_STREAM_DIRECTION direction) {
- return alsa_iodev_create(card_index, test_card_name, 0, test_pcm_name,
- test_dev_name, dev_id, card_type, is_first, mixer,
- config, ucm, fake_hctl, direction, 0, 0,
- (char*)"123");
-}
-
-namespace {
-TEST(AlsaIoInit, InitializeInvalidDirection) {
- struct alsa_io* aio;
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_NUM_DIRECTIONS);
- ASSERT_EQ(aio, (void*)NULL);
-}
-
-TEST(AlsaIoInit, InitializePlayback) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, test_dev_id, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- /* Get volume curve twice for iodev, and default node. */
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- EXPECT_EQ(1, cras_alsa_mixer_list_outputs_called);
- EXPECT_EQ(
- 0, strncmp(test_card_name, aio->base.info.name, strlen(test_card_name)));
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ("", cras_iodev_update_dsp_name);
- ASSERT_NE(reinterpret_cast<const char*>(NULL), aio->dev_name);
- EXPECT_EQ(0, strcmp(test_dev_name, aio->dev_name));
- ASSERT_NE(reinterpret_cast<const char*>(NULL), aio->dev_id);
- EXPECT_EQ(0, strcmp(test_dev_id, aio->dev_id));
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
- EXPECT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST(AlsaIoInit, DefaultNodeInternalCard) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- ASSERT_STREQ(DEFAULT, aio->base.active_node->name);
- ASSERT_EQ(1, aio->base.active_node->plugged);
- ASSERT_EQ((void*)no_stream, (void*)aio->base.no_stream);
- ASSERT_EQ((void*)is_free_running, (void*)aio->base.is_free_running);
- alsa_iodev_destroy((struct cras_iodev*)aio);
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- ASSERT_STREQ(INTERNAL_SPEAKER, aio->base.active_node->name);
- ASSERT_EQ(1, aio->base.active_node->plugged);
- ASSERT_EQ((void*)no_stream, (void*)aio->base.no_stream);
- ASSERT_EQ((void*)is_free_running, (void*)aio->base.is_free_running);
- alsa_iodev_destroy((struct cras_iodev*)aio);
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- /* No more call to get volume curve for input device. */
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- ASSERT_STREQ(DEFAULT, aio->base.active_node->name);
- ASSERT_EQ(1, aio->base.active_node->plugged);
- ASSERT_EQ((void*)no_stream, (void*)aio->base.no_stream);
- ASSERT_EQ((void*)is_free_running, (void*)aio->base.is_free_running);
- alsa_iodev_destroy((struct cras_iodev*)aio);
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- ASSERT_STREQ(INTERNAL_MICROPHONE, aio->base.active_node->name);
- ASSERT_EQ(1, aio->base.active_node->plugged);
- ASSERT_EQ((void*)no_stream, (void*)aio->base.no_stream);
- ASSERT_EQ((void*)is_free_running, (void*)aio->base.is_free_running);
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, DefaultNodeUSBCard) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_USB, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- ASSERT_STREQ(DEFAULT, aio->base.active_node->name);
- ASSERT_EQ(1, aio->base.active_node->plugged);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- alsa_iodev_destroy((struct cras_iodev*)aio);
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_USB, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- ASSERT_STREQ(DEFAULT, aio->base.active_node->name);
- ASSERT_EQ(1, aio->base.active_node->plugged);
- EXPECT_EQ(2, cras_iodev_set_node_plugged_called);
-
- /* No extra gain applied. */
- ASSERT_EQ(DEFAULT_CAPTURE_VOLUME_DBFS,
- aio->base.active_node->intrinsic_sensitivity);
- ASSERT_EQ(0, aio->base.active_node->capture_gain);
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, OpenPlayback) {
- struct cras_iodev* iodev;
- struct cras_audio_format format;
- struct alsa_io* aio;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- /* Call open_dev once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_open_called);
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- aio = (struct alsa_io*)iodev;
- format.frame_rate = 48000;
- format.num_channels = 1;
- cras_iodev_set_format(iodev, &format);
-
- // Test that these flags are cleared after open_dev.
- aio->free_running = 1;
- aio->filled_zeros_for_draining = 512;
- iodev->open_dev(iodev);
- EXPECT_EQ(2, cras_alsa_open_called);
- iodev->configure_dev(iodev);
- EXPECT_EQ(2, cras_alsa_open_called);
- EXPECT_EQ(1, sys_set_volume_limits_called);
- EXPECT_EQ(1, alsa_mixer_set_dBFS_called);
- EXPECT_EQ(0, cras_alsa_start_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(0, aio->free_running);
- EXPECT_EQ(0, aio->filled_zeros_for_draining);
- EXPECT_EQ(SEVERE_UNDERRUN_MS * format.frame_rate / 1000,
- aio->severe_underrun_frames);
-
- alsa_iodev_destroy(iodev);
- free(fake_format);
-}
-
-TEST(AlsaIoInit, UsbCardAutoPlug) {
- struct cras_iodev* iodev;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_called);
- alsa_iodev_destroy(iodev);
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(0, NULL, ALSA_CARD_TYPE_USB,
- 0, fake_mixer, fake_config,
- NULL, CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_called);
- alsa_iodev_destroy(iodev);
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(0, NULL, ALSA_CARD_TYPE_USB,
- 1, fake_mixer, fake_config,
- NULL, CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- // Should assume USB devs are plugged when they appear.
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(1, iodev->active_node->plugged);
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaIoInit, UsbCardUseSoftwareVolume) {
- struct cras_iodev* iodev;
-
- alsa_mixer_get_dB_range_value = 1000;
- alsa_mixer_get_output_dB_range_value = 1000;
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(0, NULL, ALSA_CARD_TYPE_USB,
- 1, fake_mixer, fake_config,
- NULL, CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(1, alsa_mixer_get_dB_range_called);
- EXPECT_EQ(1, alsa_mixer_get_output_dB_range_called);
- EXPECT_EQ(1, iodev->active_node->software_volume_needed);
- alsa_iodev_destroy(iodev);
-
- alsa_mixer_get_dB_range_value = 3000;
- alsa_mixer_get_output_dB_range_value = 2000;
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(0, NULL, ALSA_CARD_TYPE_USB,
- 1, fake_mixer, fake_config,
- NULL, CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(1, alsa_mixer_get_dB_range_called);
- EXPECT_EQ(1, alsa_mixer_get_output_dB_range_called);
- EXPECT_EQ(0, iodev->active_node->software_volume_needed);
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaIoInit, SoftwareGainIntrinsicSensitivity) {
- struct cras_iodev* iodev;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- long intrinsic_sensitivity = -2700;
-
- ResetStubData();
-
- // Set intrinsic sensitivity to -2700 * 0.01 dBFS/Pa.
- ucm_get_intrinsic_sensitivity_values[INTERNAL_MICROPHONE] =
- intrinsic_sensitivity;
-
- // Assume this is the first device so it gets internal mic node name.
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- ASSERT_EQ(intrinsic_sensitivity, iodev->active_node->intrinsic_sensitivity);
- ASSERT_EQ(DEFAULT_CAPTURE_VOLUME_DBFS - intrinsic_sensitivity,
- iodev->active_node->capture_gain);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaIoInit, RouteBasedOnJackCallback) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(aio, (void*)NULL);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- EXPECT_EQ(1, cras_alsa_mixer_list_outputs_called);
- EXPECT_EQ(1, cras_alsa_jack_list_create_called);
- EXPECT_EQ(1, cras_alsa_jack_list_find_jacks_by_name_matching_called);
- EXPECT_EQ(0, cras_alsa_jack_list_add_jack_for_section_called);
-
- cras_alsa_jack_list_create_cb(NULL, 1, cras_alsa_jack_list_create_cb_data);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_value);
- cras_alsa_jack_list_create_cb(NULL, 0, cras_alsa_jack_list_create_cb_data);
- EXPECT_EQ(2, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_value);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
- EXPECT_EQ(1, cras_alsa_jack_list_destroy_called);
-}
-
-TEST(AlsaIoInit, RouteBasedOnInputJackCallback) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- ASSERT_NE(aio, (void*)NULL);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
-
- EXPECT_EQ(SND_PCM_STREAM_CAPTURE, aio->alsa_stream);
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- EXPECT_EQ(1, cras_alsa_jack_list_create_called);
- EXPECT_EQ(1, cras_alsa_jack_list_find_jacks_by_name_matching_called);
- EXPECT_EQ(0, cras_alsa_jack_list_add_jack_for_section_called);
-
- cras_alsa_jack_list_create_cb(NULL, 1, cras_alsa_jack_list_create_cb_data);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_value);
- cras_alsa_jack_list_create_cb(NULL, 0, cras_alsa_jack_list_create_cb_data);
- EXPECT_EQ(2, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_value);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
- EXPECT_EQ(1, cras_alsa_jack_list_destroy_called);
-}
-
-TEST(AlsaIoInit, InitializeCapture) {
- struct alsa_io* aio;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- ASSERT_NE(aio, (void*)NULL);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
-
- EXPECT_EQ(SND_PCM_STREAM_CAPTURE, aio->alsa_stream);
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- EXPECT_EQ(1, cras_alsa_mixer_list_inputs_called);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, OpenCapture) {
- struct cras_iodev* iodev;
- struct cras_audio_format format;
- struct alsa_io* aio;
-
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
-
- aio = (struct alsa_io*)iodev;
- format.frame_rate = 48000;
- format.num_channels = 1;
- cras_iodev_set_format(iodev, &format);
-
- ResetStubData();
- iodev->open_dev(iodev);
- EXPECT_EQ(1, cras_alsa_open_called);
- iodev->configure_dev(iodev);
- EXPECT_EQ(1, cras_alsa_open_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_minimum_capture_gain_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_maximum_capture_gain_called);
- EXPECT_EQ(1, alsa_mixer_set_capture_dBFS_called);
- EXPECT_EQ(1, sys_get_capture_mute_called);
- EXPECT_EQ(1, alsa_mixer_set_capture_mute_called);
- EXPECT_EQ(1, cras_alsa_start_called);
- EXPECT_EQ(SEVERE_UNDERRUN_MS * format.frame_rate / 1000,
- aio->severe_underrun_frames);
-
- alsa_iodev_destroy(iodev);
- free(fake_format);
-}
-
-TEST(AlsaIoInit, OpenCaptureSetCaptureGainWithDefaultNodeGain) {
- struct cras_iodev* iodev;
- struct cras_audio_format format;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- long default_node_gain = 1000;
-
- ResetStubData();
- // Set default node gain to -1000 * 0.01 dB.
- ucm_get_default_node_gain_values[INTERNAL_MICROPHONE] = default_node_gain;
-
- // Assume this is the first device so it gets internal mic node name.
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
-
- cras_iodev_set_format(iodev, &format);
-
- // Check the default node gain is the same as what specified in UCM.
- EXPECT_EQ(default_node_gain, iodev->active_node->capture_gain);
- cras_alsa_mixer_get_minimum_capture_gain_ret_value = 0;
- cras_alsa_mixer_get_maximum_capture_gain_ret_value = 2000;
-
- iodev->open_dev(iodev);
- iodev->configure_dev(iodev);
- iodev->close_dev(iodev);
-
- // Hardware gain is in the hardware gain range and set to 1000 * 0.01 dB.
- EXPECT_EQ(default_node_gain, alsa_mixer_set_capture_dBFS_value);
-
- // Check we do respect the hardware maximum capture gain.
- cras_alsa_mixer_get_maximum_capture_gain_ret_value = 500;
-
- iodev->open_dev(iodev);
- iodev->configure_dev(iodev);
- iodev->close_dev(iodev);
-
- EXPECT_EQ(500, alsa_mixer_set_capture_dBFS_value);
-
- alsa_iodev_destroy(iodev);
- free(fake_format);
-}
-
-TEST(AlsaIoInit, OpenCaptureSetCaptureGainWithSoftwareGain) {
- struct cras_iodev* iodev;
- struct cras_audio_format format;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
-
- /* Meet the requirements of using software gain. */
- ResetStubData();
-
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
-
- format.frame_rate = 48000;
- format.num_channels = 1;
- cras_iodev_set_format(iodev, &format);
-
- iodev->open_dev(iodev);
- iodev->configure_dev(iodev);
- iodev->close_dev(iodev);
-
- /* Hardware gain is set to 0dB when software gain is used. */
- EXPECT_EQ(0, alsa_mixer_set_capture_dBFS_value);
-
- /* Test the case where software gain is not needed. */
- iodev->active_node->software_volume_needed = 0;
- iodev->active_node->capture_gain = 1000;
- iodev->open_dev(iodev);
- iodev->configure_dev(iodev);
- iodev->close_dev(iodev);
-
- /* Hardware gain is set to 1000 * 0.01 dB as got from catpure_gain.*/
- EXPECT_EQ(0, alsa_mixer_set_capture_dBFS_value);
-
- alsa_iodev_destroy(iodev);
- free(fake_format);
-}
-
-TEST(AlsaIoInit, OpenCaptureSetCaptureGainWithDefaultUsbDevice) {
- struct cras_iodev* iodev;
- struct cras_audio_format format;
-
- iodev = alsa_iodev_create_with_default_parameters(0, NULL, ALSA_CARD_TYPE_USB,
- 0, fake_mixer, fake_config,
- NULL, CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
-
- format.frame_rate = 48000;
- format.num_channels = 1;
- cras_iodev_set_format(iodev, &format);
-
- iodev->active_node->intrinsic_sensitivity = DEFAULT_CAPTURE_VOLUME_DBFS;
- iodev->active_node->capture_gain = 0;
-
- ResetStubData();
- iodev->open_dev(iodev);
- iodev->configure_dev(iodev);
-
- EXPECT_EQ(1, sys_get_capture_mute_called);
- EXPECT_EQ(1, alsa_mixer_set_capture_mute_called);
-
- /* Not change mixer controls for USB devices without UCM config. */
- EXPECT_EQ(0, alsa_mixer_set_capture_dBFS_called);
-
- alsa_iodev_destroy(iodev);
- free(fake_format);
-}
-
-TEST(AlsaIoInit, UpdateActiveNode) {
- struct cras_iodev* iodev;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
-
- iodev->update_active_node(iodev, 0, 1);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaIoInit, StartDevice) {
- struct cras_iodev* iodev;
- int rc;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, NULL, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
-
- // Return right away if it is already running.
- snd_pcm_state_ret = SND_PCM_STATE_RUNNING;
- rc = iodev->start(iodev);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_alsa_start_called);
-
- // Otherwise, start the device.
- snd_pcm_state_ret = SND_PCM_STATE_SETUP;
- rc = iodev->start(iodev);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_start_called);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaIoInit, ResumeDevice) {
- struct cras_iodev* iodev;
- int rc;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, NULL, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init(iodev));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
-
- // Attempt to resume if the device is suspended.
- snd_pcm_state_ret = SND_PCM_STATE_SUSPENDED;
- rc = iodev->start(iodev);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_attempt_resume_called);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaIoInit, DspNameDefault) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(1, ucm_get_dsp_name_for_dev_called);
- EXPECT_STREQ("", cras_iodev_update_dsp_name);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, DspName) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
-
- ResetStubData();
- ucm_get_dsp_name_for_dev_values[DEFAULT] = "hello";
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(1, ucm_get_dsp_name_for_dev_called);
- EXPECT_STREQ("hello", cras_iodev_update_dsp_name);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, DspNameJackOverride) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- const struct cras_alsa_jack* jack = (struct cras_alsa_jack*)4;
- static const char* jack_name = "jack";
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(1, ucm_get_dsp_name_for_dev_called);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_STREQ("", cras_iodev_update_dsp_name);
-
- cras_alsa_jack_get_name_ret_value = jack_name;
- ucm_get_dsp_name_for_dev_values[jack_name] = "override_dsp";
- // Add the jack node.
- cras_alsa_jack_list_create_cb(jack, 1, cras_alsa_jack_list_create_cb_data);
- EXPECT_EQ(2, cras_alsa_jack_get_name_called);
- EXPECT_EQ(2, ucm_get_dsp_name_for_dev_called);
-
- // Mark the jack node as active.
- alsa_iodev_set_active_node(&aio->base, aio->base.nodes->next, 1);
- EXPECT_EQ(2, ucm_get_dsp_name_for_dev_called);
- EXPECT_EQ(2, cras_iodev_update_dsp_called);
- EXPECT_STREQ("override_dsp", cras_iodev_update_dsp_name);
-
- // Mark the default node as active.
- alsa_iodev_set_active_node(&aio->base, aio->base.nodes, 1);
- EXPECT_EQ(2, ucm_get_dsp_name_for_dev_called);
- EXPECT_EQ(3, cras_iodev_update_dsp_called);
- EXPECT_STREQ("", cras_iodev_update_dsp_name);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, NodeTypeOverride) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- const struct cras_alsa_jack* jack = (struct cras_alsa_jack*)4;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- // Add the jack node.
- cras_alsa_jack_list_create_cb(jack, 1, cras_alsa_jack_list_create_cb_data);
- // Verify that cras_alsa_jack_update_node_type is called when an output device
- // is created.
- EXPECT_EQ(1, cras_alsa_jack_update_node_type_called);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaIoInit, SwapMode) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_ionode* const fake_node =
- (cras_ionode*)calloc(1, sizeof(struct cras_ionode));
- ResetStubData();
- // Stub replies that swap mode does not exist.
- ucm_swap_mode_exists_ret_value = 0;
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
-
- aio->base.set_swap_mode_for_node((cras_iodev*)aio, fake_node, 1);
- /* Swap mode is implemented by dsp. */
- EXPECT_EQ(1, cras_iodev_dsp_set_swap_mode_for_node_called);
-
- // Stub replies that swap mode exists.
- ucm_swap_mode_exists_ret_value = 1;
- alsa_iodev_destroy((struct cras_iodev*)aio);
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- // Enable swap mode.
- aio->base.set_swap_mode_for_node((cras_iodev*)aio, fake_node, 1);
-
- // Verify that ucm_enable_swap_mode is called when callback to enable
- // swap mode is called.
- EXPECT_EQ(1, ucm_enable_swap_mode_called);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
- free(fake_node);
-}
-
-TEST(AlsaIoInit, MaxSupportedChannels) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- int i;
-
- // i = 0: cras_alsa_support_8_channels is false, support 2 channels only.
- // i = 1: cras_alsa_support_8_channels is true, support up to 8 channels.
- for (i = 0; i < 2; i++) {
- ResetStubData();
- cras_alsa_support_8_channels = (bool)i;
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, test_dev_id, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config,
- NULL, CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- uint32_t max_channels = (cras_alsa_support_8_channels) ? 8 : 2;
- EXPECT_EQ(max_channels, aio->base.info.max_supported_channels);
- alsa_iodev_destroy((struct cras_iodev*)aio);
- EXPECT_EQ(1, cras_iodev_free_resources_called);
- }
-}
-
-// Test that system settins aren't touched if no streams active.
-TEST(AlsaOutputNode, SystemSettingsWhenInactive) {
- int rc;
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct mixer_control* outputs[2];
-
- ResetStubData();
- outputs[0] = reinterpret_cast<struct mixer_control*>(3);
- outputs[1] = reinterpret_cast<struct mixer_control*>(4);
- cras_alsa_mixer_list_outputs_outputs = outputs;
- cras_alsa_mixer_list_outputs_outputs_length = ARRAY_SIZE(outputs);
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- /* Two mixer controls calls get volume curve. */
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(1, cras_alsa_mixer_list_outputs_called);
-
- ResetStubData();
- rc = alsa_iodev_set_active_node((struct cras_iodev*)aio,
- aio->base.nodes->next, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, alsa_mixer_set_mute_called);
- EXPECT_EQ(0, alsa_mixer_set_dBFS_called);
- ASSERT_EQ(2, cras_alsa_mixer_set_output_active_state_called);
- EXPECT_EQ(outputs[0], cras_alsa_mixer_set_output_active_state_outputs[0]);
- EXPECT_EQ(0, cras_alsa_mixer_set_output_active_state_values[0]);
- EXPECT_EQ(outputs[1], cras_alsa_mixer_set_output_active_state_outputs[1]);
- EXPECT_EQ(1, cras_alsa_mixer_set_output_active_state_values[1]);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- // No jack is defined, and UCM is not used.
- EXPECT_EQ(0, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(0, ucm_set_enabled_called);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-// Test handling of different amounts of outputs.
-TEST(AlsaOutputNode, TwoOutputs) {
- int rc;
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct mixer_control* outputs[2];
-
- ResetStubData();
- outputs[0] = reinterpret_cast<struct mixer_control*>(3);
- outputs[1] = reinterpret_cast<struct mixer_control*>(4);
- cras_alsa_mixer_list_outputs_outputs = outputs;
- cras_alsa_mixer_list_outputs_outputs_length = ARRAY_SIZE(outputs);
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(1, cras_alsa_mixer_list_outputs_called);
-
- aio->handle = (snd_pcm_t*)0x24;
-
- ResetStubData();
- rc = alsa_iodev_set_active_node((struct cras_iodev*)aio,
- aio->base.nodes->next, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, alsa_mixer_set_mute_called);
- EXPECT_EQ(outputs[1], alsa_mixer_set_mute_output);
- EXPECT_EQ(1, alsa_mixer_set_dBFS_called);
- EXPECT_EQ(outputs[1], alsa_mixer_set_dBFS_output);
- ASSERT_EQ(2, cras_alsa_mixer_set_output_active_state_called);
- EXPECT_EQ(outputs[0], cras_alsa_mixer_set_output_active_state_outputs[0]);
- EXPECT_EQ(0, cras_alsa_mixer_set_output_active_state_values[0]);
- EXPECT_EQ(outputs[1], cras_alsa_mixer_set_output_active_state_outputs[1]);
- EXPECT_EQ(1, cras_alsa_mixer_set_output_active_state_values[1]);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- // No jacks defined, and UCM is not used.
- EXPECT_EQ(0, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(0, ucm_set_enabled_called);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaOutputNode, TwoJacksHeadphoneLineout) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- struct mixer_control* output;
- struct ucm_section* section;
-
- ResetStubData();
- output = reinterpret_cast<struct mixer_control*>(3);
- cras_alsa_mixer_get_control_name_values[output] = HEADPHONE;
-
- // Create the iodev
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
- EXPECT_EQ(1, cras_card_config_get_volume_curve_for_control_called);
-
- // First node 'Headphone'
- section = ucm_section_create(HEADPHONE, "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "fake-jack", "gpio");
- ucm_section_set_mixer_name(section, HEADPHONE);
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(10);
- cras_alsa_mixer_get_control_for_section_return_value = output;
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- ucm_section_free_list(section);
-
- // Second node 'Line Out'
- section = ucm_section_create("Line Out", "hw:0.1", 0, -1, CRAS_STREAM_OUTPUT,
- "fake-jack", "gpio");
- ucm_section_set_mixer_name(section, HEADPHONE);
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(20);
- cras_alsa_mixer_get_control_for_section_return_value = output;
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- EXPECT_EQ(7, cras_card_config_get_volume_curve_for_control_called);
- ucm_section_free_list(section);
-
- // Both nodes are associated with the same mixer output. Different jack plug
- // report should trigger different node attribute change.
- cras_alsa_jack_get_mixer_output_ret = output;
- jack_output_plug_event(reinterpret_cast<struct cras_alsa_jack*>(10), 0, aio);
- EXPECT_STREQ(cras_iodev_set_node_plugged_ionode->name, HEADPHONE);
-
- jack_output_plug_event(reinterpret_cast<struct cras_alsa_jack*>(20), 0, aio);
- EXPECT_STREQ(cras_iodev_set_node_plugged_ionode->name, "Line Out");
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, MaxSupportedChannels) {
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- struct ucm_section* section;
- int i;
-
- // i = 0: cras_alsa_support_8_channels is false, support 2 channels only.
- // i = 1: cras_alsa_support_8_channels is true, support up to 8 channels.
- for (i = 0; i < 2; i++) {
- ResetStubData();
- cras_alsa_support_8_channels = (bool)i;
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 1, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(iodev, (void*)NULL);
-
- // Node without controls or jacks.
- section = ucm_section_create(INTERNAL_SPEAKER, "hw:0,1", 1, -1,
- CRAS_STREAM_OUTPUT, NULL, NULL);
- // Device index doesn't match.
- EXPECT_EQ(-22, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- section->dev_idx = 0;
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
-
- // Complete initialization, and make first node active.
- alsa_iodev_ucm_complete_init(iodev);
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- uint32_t max_channels = (cras_alsa_support_8_channels) ? 8 : 2;
- EXPECT_EQ(max_channels, iodev->info.max_supported_channels);
- alsa_iodev_destroy(iodev);
- }
-}
-
-TEST(AlsaOutputNode, OutputsFromUCM) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- static const char* jack_name = "TestCard - Headset Jack";
- struct mixer_control* outputs[2];
- int rc;
- struct ucm_section* section;
-
- ResetStubData();
- outputs[0] = reinterpret_cast<struct mixer_control*>(3);
- outputs[1] = reinterpret_cast<struct mixer_control*>(4);
- cras_alsa_mixer_list_outputs_outputs = outputs;
- cras_alsa_mixer_list_outputs_outputs_length = ARRAY_SIZE(outputs);
- cras_alsa_mixer_get_control_name_values[outputs[0]] = INTERNAL_SPEAKER;
- cras_alsa_mixer_get_control_name_values[outputs[1]] = HEADPHONE;
- ucm_get_dma_period_for_dev_ret = 1000;
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
- EXPECT_EQ(1, cras_card_config_get_volume_curve_for_control_called);
-
- // First node.
- section = ucm_section_create(INTERNAL_SPEAKER, "hw:0,1", 0, -1,
- CRAS_STREAM_OUTPUT, NULL, NULL);
- ucm_section_set_mixer_name(section, INTERNAL_SPEAKER);
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(1);
- cras_alsa_mixer_get_control_for_section_return_value = outputs[0];
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
-
- // Add a second node (will use the same iodev).
- section = ucm_section_create(HEADPHONE, "hw:0,2", 0, -1, CRAS_STREAM_OUTPUT,
- jack_name, "hctl");
- ucm_section_add_coupled(section, "HP-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "HP-R", MIXER_NAME_VOLUME);
- cras_alsa_jack_list_add_jack_for_section_result_jack = NULL;
- cras_alsa_mixer_get_control_for_section_return_value = outputs[1];
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
- /* New nodes creation calls get volume curve once, NULL jack doesn't make
- * more calls. */
- EXPECT_EQ(5, cras_card_config_get_volume_curve_for_control_called);
-
- // Jack plug of an unkonwn device should do nothing.
- cras_alsa_jack_get_mixer_output_ret = NULL;
- cras_alsa_jack_get_name_ret_value = "Some other jack";
- jack_output_plug_event(reinterpret_cast<struct cras_alsa_jack*>(4), 0, aio);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_called);
-
- // Complete initialization, and make first node active.
- cras_alsa_support_8_channels = false; // Support 2 channels only.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(2, cras_alsa_jack_list_add_jack_for_section_called);
- EXPECT_EQ(2, cras_alsa_mixer_get_control_for_section_called);
- EXPECT_EQ(1, ucm_get_dma_period_for_dev_called);
- EXPECT_EQ(ucm_get_dma_period_for_dev_ret, aio->dma_period_set_microsecs);
- /* Call cras_alsa_fill_properties once on update_max_supported_channels. */
- EXPECT_EQ(1, cras_alsa_fill_properties_called);
- EXPECT_EQ(2, iodev->info.max_supported_channels);
-
- aio->handle = (snd_pcm_t*)0x24;
-
- ResetStubData();
- rc = alsa_iodev_set_active_node(iodev, aio->base.nodes->next, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, alsa_mixer_set_mute_called);
- EXPECT_EQ(outputs[1], alsa_mixer_set_mute_output);
- EXPECT_EQ(1, alsa_mixer_set_dBFS_called);
- EXPECT_EQ(outputs[1], alsa_mixer_set_dBFS_output);
- ASSERT_EQ(2, cras_alsa_mixer_set_output_active_state_called);
- EXPECT_EQ(outputs[0], cras_alsa_mixer_set_output_active_state_outputs[0]);
- EXPECT_EQ(0, cras_alsa_mixer_set_output_active_state_values[0]);
- EXPECT_EQ(outputs[1], cras_alsa_mixer_set_output_active_state_outputs[1]);
- EXPECT_EQ(1, cras_alsa_mixer_set_output_active_state_values[1]);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ(1, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(1, ucm_set_enabled_called);
-
- // Simulate jack plug event.
- cras_alsa_support_8_channels = true; // Support up to 8 channels.
- cras_alsa_jack_get_mixer_output_ret = outputs[1];
- cras_alsa_jack_get_name_ret_value = jack_name;
- jack_output_plug_event(reinterpret_cast<struct cras_alsa_jack*>(4), 0, aio);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- /* Headphone plug event shouldn't trigger update_max_supported_channels. */
- EXPECT_EQ(0, cras_alsa_fill_properties_called);
- EXPECT_EQ(2, iodev->info.max_supported_channels);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, OutputNoControlsUCM) {
- struct alsa_io* aio;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- struct ucm_section* section;
-
- ResetStubData();
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 1, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
- EXPECT_EQ(1, cras_card_config_get_volume_curve_for_control_called);
-
- // Node without controls or jacks.
- section = ucm_section_create(INTERNAL_SPEAKER, "hw:0,1", 1, -1,
- CRAS_STREAM_OUTPUT, NULL, NULL);
- // Device index doesn't match.
- EXPECT_EQ(-22, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- section->dev_idx = 0;
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_control_for_section_called);
- EXPECT_EQ(1, cras_iodev_add_node_called);
- ucm_section_free_list(section);
-
- // Complete initialization, and make first node active.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(0, cras_alsa_mixer_get_control_name_called);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ(0, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(1, ucm_set_enabled_called);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, OutputFromJackUCM) {
- struct alsa_io* aio;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- static const char* jack_name = "TestCard - Headset Jack";
- struct ucm_section* section;
-
- ResetStubData();
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 1, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
- EXPECT_EQ(1, cras_card_config_get_volume_curve_for_control_called);
-
- // Node without controls or jacks.
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(1);
- section = ucm_section_create(HEADPHONE, "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- jack_name, "hctl");
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- EXPECT_EQ(4, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_control_for_section_called);
- EXPECT_EQ(1, cras_iodev_add_node_called);
- EXPECT_EQ(1, cras_alsa_jack_list_add_jack_for_section_called);
- ucm_section_free_list(section);
-
- // Complete initialization, and make first node active.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- EXPECT_EQ(0, cras_alsa_mixer_get_control_name_called);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ(1, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(0, ucm_set_enabled_called);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, InputsFromUCM) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct mixer_control* inputs[2];
- struct cras_iodev* iodev;
- static const char* jack_name = "TestCard - Headset Jack";
- int rc;
- struct ucm_section* section;
- long intrinsic_sensitivity = -2700;
-
- ResetStubData();
- inputs[0] = reinterpret_cast<struct mixer_control*>(3);
- inputs[1] = reinterpret_cast<struct mixer_control*>(4);
- cras_alsa_mixer_list_inputs_outputs = inputs;
- cras_alsa_mixer_list_inputs_outputs_length = ARRAY_SIZE(inputs);
- cras_alsa_mixer_get_control_name_values[inputs[0]] = INTERNAL_MICROPHONE;
- cras_alsa_mixer_get_control_name_values[inputs[1]] = MIC;
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
-
- // First node.
- cras_alsa_mixer_get_control_for_section_return_value = inputs[0];
- section = ucm_section_create(INTERNAL_MICROPHONE, "hw:0,1", 0, -1,
- CRAS_STREAM_INPUT, NULL, NULL);
- ucm_section_add_coupled(section, "MIC-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "MIC-R", MIXER_NAME_VOLUME);
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
-
- // Add a second node (will use the same iodev).
- cras_alsa_mixer_get_control_name_called = 0;
- // Set intrinsic sensitivity to enable software gain.
- ucm_get_intrinsic_sensitivity_values[MIC] = intrinsic_sensitivity;
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(1);
- cras_alsa_mixer_get_control_for_section_return_value = inputs[1];
- section = ucm_section_create(MIC, "hw:0,2", 0, -1, CRAS_STREAM_INPUT,
- jack_name, "hctl");
- ucm_section_set_mixer_name(section, MIC);
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
-
- // Jack plug of an unknown device should do nothing.
- cras_alsa_jack_get_mixer_input_ret = NULL;
- cras_alsa_jack_get_name_ret_value = "Some other jack";
- jack_input_plug_event(reinterpret_cast<struct cras_alsa_jack*>(4), 0, aio);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_called);
-
- // Simulate jack plug event.
- cras_alsa_jack_get_mixer_input_ret = inputs[1];
- cras_alsa_jack_get_name_ret_value = jack_name;
- jack_input_plug_event(reinterpret_cast<struct cras_alsa_jack*>(4), 0, aio);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
-
- // Complete initialization, and make first node active.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_CAPTURE, aio->alsa_stream);
- EXPECT_EQ(2, cras_alsa_jack_list_add_jack_for_section_called);
- EXPECT_EQ(2, cras_alsa_mixer_get_control_for_section_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_control_name_called);
- EXPECT_EQ(2, cras_iodev_add_node_called);
- EXPECT_EQ(2, ucm_get_dma_period_for_dev_called);
- EXPECT_EQ(0, aio->dma_period_set_microsecs);
-
- aio->handle = (snd_pcm_t*)0x24;
-
- ResetStubData();
- rc = alsa_iodev_set_active_node(iodev, aio->base.nodes->next, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, alsa_mixer_set_capture_dBFS_called);
- EXPECT_EQ(inputs[1], alsa_mixer_set_capture_dBFS_input);
- EXPECT_EQ(0, alsa_mixer_set_capture_dBFS_value);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ(1, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(1, ucm_set_enabled_called);
- EXPECT_EQ(1, alsa_mixer_set_capture_mute_called);
- ASSERT_EQ(DEFAULT_CAPTURE_VOLUME_DBFS - intrinsic_sensitivity,
- iodev->active_node->capture_gain);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, InputNoControlsUCM) {
- struct alsa_io* aio;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- struct ucm_section* section;
-
- ResetStubData();
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 1, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
-
- // Node without controls or jacks.
- section = ucm_section_create(INTERNAL_MICROPHONE, "hw:0,1", 1, -1,
- CRAS_STREAM_INPUT, NULL, NULL);
- // Device index doesn't match.
- EXPECT_EQ(-22, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- section->dev_idx = 0;
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- EXPECT_EQ(1, cras_alsa_jack_list_add_jack_for_section_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_control_for_section_called);
- EXPECT_EQ(0, cras_alsa_mixer_get_control_name_called);
- EXPECT_EQ(1, cras_iodev_add_node_called);
- ucm_section_free_list(section);
-
- // Complete initialization, and make first node active.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_CAPTURE, aio->alsa_stream);
- EXPECT_EQ(0, cras_alsa_mixer_get_control_name_called);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ(0, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(1, ucm_set_enabled_called);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, InputFromJackUCM) {
- struct alsa_io* aio;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- static const char* jack_name = "TestCard - Headset Jack";
- struct ucm_section* section;
-
- ResetStubData();
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 1, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
-
- // Node without controls or jacks.
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(1);
- section = ucm_section_create(MIC, "hw:0,1", 0, -1, CRAS_STREAM_INPUT,
- jack_name, "hctl");
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- EXPECT_EQ(1, cras_alsa_mixer_get_control_for_section_called);
- EXPECT_EQ(1, cras_iodev_add_node_called);
- EXPECT_EQ(1, cras_alsa_jack_list_add_jack_for_section_called);
- ucm_section_free_list(section);
-
- // Complete initialization, and make first node active.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_CAPTURE, aio->alsa_stream);
- EXPECT_EQ(0, cras_alsa_mixer_get_control_name_called);
- EXPECT_EQ(1, cras_iodev_update_dsp_called);
- EXPECT_EQ(1, cras_alsa_jack_enable_ucm_called);
- EXPECT_EQ(0, ucm_set_enabled_called);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaOutputNode, AutoUnplugOutputNode) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct mixer_control* outputs[2];
- const struct cras_alsa_jack* jack = (struct cras_alsa_jack*)4;
-
- ResetStubData();
- outputs[0] = reinterpret_cast<struct mixer_control*>(5);
- outputs[1] = reinterpret_cast<struct mixer_control*>(6);
-
- cras_alsa_mixer_list_outputs_outputs = outputs;
- cras_alsa_mixer_list_outputs_outputs_length = ARRAY_SIZE(outputs);
-
- cras_alsa_mixer_get_control_name_values[outputs[0]] = INTERNAL_SPEAKER;
- cras_alsa_mixer_get_control_name_values[outputs[1]] = HEADPHONE;
- auto_unplug_output_node_ret = 1;
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
-
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(3, cras_card_config_get_volume_curve_for_control_called);
- EXPECT_EQ(1, cras_alsa_mixer_list_outputs_called);
- EXPECT_EQ(2, cras_alsa_mixer_get_control_name_called);
-
- // Assert that the the internal speaker is plugged and other nodes aren't.
- ASSERT_NE(aio->base.nodes, (void*)NULL);
- EXPECT_EQ(aio->base.nodes->plugged, 1);
- ASSERT_NE(aio->base.nodes->next, (void*)NULL);
- EXPECT_EQ(aio->base.nodes->next->plugged, 0);
-
- // Plug headphone jack
- cras_alsa_jack_get_name_ret_value = "Headphone Jack";
- is_utf8_string_ret_value = 1;
- cras_alsa_jack_get_mixer_output_ret = outputs[1];
- cras_alsa_jack_list_create_cb(jack, 1, cras_alsa_jack_list_create_cb_data);
-
- // Assert internal speaker is auto unplugged
- EXPECT_EQ(aio->base.nodes->plugged, 0);
- EXPECT_EQ(aio->base.nodes->next->plugged, 1);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaOutputNode, AutoUnplugInputNode) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct mixer_control* inputs[2];
- const struct cras_alsa_jack* jack = (struct cras_alsa_jack*)4;
-
- ResetStubData();
- inputs[0] = reinterpret_cast<struct mixer_control*>(5);
- inputs[1] = reinterpret_cast<struct mixer_control*>(6);
-
- cras_alsa_mixer_list_inputs_outputs = inputs;
- cras_alsa_mixer_list_inputs_outputs_length = ARRAY_SIZE(inputs);
-
- cras_alsa_mixer_get_control_name_values[inputs[0]] = INTERNAL_MICROPHONE;
- cras_alsa_mixer_get_control_name_values[inputs[1]] = MIC;
- auto_unplug_input_node_ret = 1;
-
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
- EXPECT_EQ(1, cras_alsa_mixer_list_inputs_called);
- EXPECT_EQ(2, cras_alsa_mixer_get_control_name_called);
-
- // Assert that the the internal speaker is plugged and other nodes aren't.
- ASSERT_NE(aio->base.nodes, (void*)NULL);
- EXPECT_EQ(aio->base.nodes->plugged, 1);
- ASSERT_NE(aio->base.nodes->next, (void*)NULL);
- EXPECT_EQ(aio->base.nodes->next->plugged, 0);
-
- // Plug headphone jack
- cras_alsa_jack_get_name_ret_value = "Mic Jack";
- is_utf8_string_ret_value = 1;
- cras_alsa_jack_get_mixer_input_ret = inputs[1];
- cras_alsa_jack_list_create_cb(jack, 1, cras_alsa_jack_list_create_cb_data);
-
- // Assert internal speaker is auto unplugged
- EXPECT_EQ(aio->base.nodes->plugged, 0);
- EXPECT_EQ(aio->base.nodes->next->plugged, 1);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-TEST(AlsaLoopback, InitializePlayback) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- static const char* jack_name = "TestCard - Alsa Loopback";
- struct mixer_control* outputs[1];
- struct ucm_section* section;
-
- ResetStubData();
- outputs[0] = reinterpret_cast<struct mixer_control*>(3);
- cras_alsa_mixer_list_outputs_outputs = outputs;
- cras_alsa_mixer_list_outputs_outputs_length = ARRAY_SIZE(outputs);
- cras_alsa_mixer_get_control_name_values[outputs[0]] = LOOPBACK_PLAYBACK;
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
-
- // Add node.
- section = ucm_section_create(LOOPBACK_PLAYBACK, "hw:0,1", 0, -1,
- CRAS_STREAM_OUTPUT, jack_name, NULL);
- ucm_section_set_mixer_name(section, LOOPBACK_PLAYBACK);
- cras_alsa_jack_list_add_jack_for_section_result_jack = NULL;
- cras_alsa_mixer_get_control_for_section_return_value = outputs[0];
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
-
- // Complete initialization, and check the loopback playback node is plugged as
- // the active node.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_PLAYBACK, aio->alsa_stream);
- ASSERT_NE(aio->base.active_node, (void*)NULL);
- EXPECT_STREQ(LOOPBACK_PLAYBACK, aio->base.active_node->name);
- EXPECT_EQ(1, aio->base.active_node->plugged);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaLoopback, InitializeCapture) {
- struct alsa_io* aio;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- struct cras_iodev* iodev;
- static const char* jack_name = "TestCard - Alsa Loopback";
- struct ucm_section* section;
-
- ResetStubData();
-
- // Create the IO device.
- iodev = alsa_iodev_create_with_default_parameters(
- 1, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_INPUT);
- ASSERT_NE(iodev, (void*)NULL);
- aio = reinterpret_cast<struct alsa_io*>(iodev);
-
- // Node without controls or jacks.
- cras_alsa_jack_list_add_jack_for_section_result_jack =
- reinterpret_cast<struct cras_alsa_jack*>(1);
- section = ucm_section_create(LOOPBACK_CAPTURE, "hw:0,1", 0, -1,
- CRAS_STREAM_INPUT, jack_name, NULL);
- ASSERT_EQ(0, alsa_iodev_ucm_add_nodes_and_jacks(iodev, section));
- ucm_section_free_list(section);
-
- // Complete initialization, and check the loopback capture node is plugged as
- // the active node.
- alsa_iodev_ucm_complete_init(iodev);
- EXPECT_EQ(SND_PCM_STREAM_CAPTURE, aio->alsa_stream);
- ASSERT_NE(aio->base.active_node, (void*)NULL);
- EXPECT_STREQ(LOOPBACK_CAPTURE, aio->base.active_node->name);
- EXPECT_EQ(1, aio->base.active_node->plugged);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaInitNode, SetNodeInitialState) {
- struct cras_ionode node;
- struct cras_iodev dev;
-
- memset(&dev, 0, sizeof(dev));
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Unknown");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(0, node.plugged_time.tv_sec);
- ASSERT_EQ(CRAS_NODE_TYPE_UNKNOWN, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, INTERNAL_SPEAKER);
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(1, node.plugged);
- ASSERT_GT(node.plugged_time.tv_sec, 0);
- ASSERT_EQ(CRAS_NODE_TYPE_INTERNAL_SPEAKER, node.type);
- ASSERT_EQ(NODE_POSITION_INTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, INTERNAL_MICROPHONE);
- dev.direction = CRAS_STREAM_INPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(1, node.plugged);
- ASSERT_GT(node.plugged_time.tv_sec, 0);
- ASSERT_EQ(CRAS_NODE_TYPE_MIC, node.type);
- ASSERT_EQ(NODE_POSITION_INTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, HDMI);
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(0, node.plugged_time.tv_sec);
- ASSERT_EQ(CRAS_NODE_TYPE_HDMI, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "IEC958");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_HDMI, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "HDMI Jack");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_HDMI, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Something HDMI Jack");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_HDMI, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, HEADPHONE);
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_HEADPHONE, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Headphone Jack");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_HEADPHONE, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, MIC);
- dev.direction = CRAS_STREAM_INPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_MIC, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Front Mic");
- dev.direction = CRAS_STREAM_INPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(1, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_MIC, node.type);
- ASSERT_EQ(NODE_POSITION_FRONT, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Rear Mic");
- dev.direction = CRAS_STREAM_INPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(1, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_MIC, node.type);
- ASSERT_EQ(NODE_POSITION_REAR, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Mic Jack");
- dev.direction = CRAS_STREAM_INPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_MIC, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Unknown");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_USB);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_USB, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- dev.direction = CRAS_STREAM_INPUT;
- strcpy(node.name, "DAISY-I2S Mic Jack");
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_MIC, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
- // Node name is changed to "MIC".
- ASSERT_EQ(0, strcmp(node.name, MIC));
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- dev.direction = CRAS_STREAM_OUTPUT;
- strcpy(node.name, "DAISY-I2S Headphone Jack");
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(0, node.plugged);
- ASSERT_EQ(CRAS_NODE_TYPE_HEADPHONE, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
- // Node name is changed to "Headphone".
- ASSERT_EQ(0, strcmp(node.name, HEADPHONE));
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, INTERNAL_SPEAKER);
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_USB);
- ASSERT_EQ(1, node.plugged);
- ASSERT_GT(node.plugged_time.tv_sec, 0);
- ASSERT_EQ(CRAS_NODE_TYPE_USB, node.type);
- ASSERT_EQ(NODE_POSITION_EXTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Haptic");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(1, node.plugged);
- ASSERT_GT(node.plugged_time.tv_sec, 0);
- ASSERT_EQ(CRAS_NODE_TYPE_HAPTIC, node.type);
- ASSERT_EQ(NODE_POSITION_INTERNAL, node.position);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Rumbler");
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(1, node.plugged);
- ASSERT_GT(node.plugged_time.tv_sec, 0);
- ASSERT_EQ(CRAS_NODE_TYPE_HAPTIC, node.type);
- ASSERT_EQ(NODE_POSITION_INTERNAL, node.position);
-}
-
-TEST(AlsaInitNode, SetNodeInitialStateDropInvalidUTF8NodeName) {
- struct cras_ionode node;
- struct cras_iodev dev;
-
- memset(&dev, 0, sizeof(dev));
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Something USB");
- // 0xfe can not appear in a valid UTF-8 string.
- node.name[0] = 0xfe;
- is_utf8_string_ret_value = 0;
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_USB);
- ASSERT_EQ(CRAS_NODE_TYPE_USB, node.type);
- ASSERT_STREQ(USB, node.name);
-
- memset(&node, 0, sizeof(node));
- node.dev = &dev;
- strcpy(node.name, "Something HDMI Jack");
- // 0xfe can not appear in a valid UTF-8 string.
- node.name[0] = 0xfe;
- is_utf8_string_ret_value = 0;
- dev.direction = CRAS_STREAM_OUTPUT;
- set_node_initial_state(&node, ALSA_CARD_TYPE_INTERNAL);
- ASSERT_EQ(CRAS_NODE_TYPE_HDMI, node.type);
- ASSERT_STREQ(HDMI, node.name);
-}
-
-TEST(AlsaIoInit, HDMIJackUpdateInvalidUTF8MonitorName) {
- struct alsa_io* aio;
- struct cras_alsa_mixer* const fake_mixer = (struct cras_alsa_mixer*)2;
- struct cras_use_case_mgr* const fake_ucm = (struct cras_use_case_mgr*)3;
- const struct cras_alsa_jack* jack = (struct cras_alsa_jack*)4;
-
- ResetStubData();
- aio = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, fake_ucm,
- CRAS_STREAM_OUTPUT);
- ASSERT_EQ(0, alsa_iodev_legacy_complete_init((struct cras_iodev*)aio));
-
- // Prepare the stub data such that the jack will be identified as an
- // HDMI jack, and thus the callback creates an HDMI node.
- cras_alsa_jack_get_name_ret_value = "HDMI Jack";
- // Set the jack name updated from monitor to be an invalid UTF8 string.
- cras_alsa_jack_update_monitor_fake_name = "\xfeomething";
- is_utf8_string_ret_value = 0;
-
- // Add the jack node.
- cras_alsa_jack_list_create_cb(jack, 1, cras_alsa_jack_list_create_cb_data);
-
- EXPECT_EQ(2, cras_alsa_jack_get_name_called);
- ASSERT_EQ(CRAS_NODE_TYPE_HDMI, aio->base.nodes->next->type);
- // The node name should be "HDMI".
- ASSERT_STREQ(HDMI, aio->base.nodes->next->name);
-
- alsa_iodev_destroy((struct cras_iodev*)aio);
-}
-
-// Test thread add/rm stream, open_alsa, and iodev config.
-class AlsaVolumeMuteSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- ResetStubData();
- output_control_ = reinterpret_cast<struct mixer_control*>(10);
- cras_alsa_mixer_list_outputs_outputs = &output_control_;
- cras_alsa_mixer_list_outputs_outputs_length = 1;
- cras_alsa_mixer_get_control_name_values[output_control_] = INTERNAL_SPEAKER;
- cras_alsa_mixer_list_outputs_outputs_length = 1;
- aio_output_ = (struct alsa_io*)alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 1, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- alsa_iodev_legacy_complete_init((struct cras_iodev*)aio_output_);
- EXPECT_EQ(2, cras_card_config_get_volume_curve_for_control_called);
-
- struct cras_ionode* node;
- int count = 0;
- DL_FOREACH (aio_output_->base.nodes, node) { printf("node %d \n", count); }
- aio_output_->base.direction = CRAS_STREAM_OUTPUT;
- fmt_.frame_rate = 44100;
- fmt_.num_channels = 2;
- fmt_.format = SND_PCM_FORMAT_S16_LE;
- aio_output_->base.format = &fmt_;
- cras_alsa_get_avail_frames_ret = -1;
- }
-
- virtual void TearDown() {
- alsa_iodev_destroy((struct cras_iodev*)aio_output_);
- cras_alsa_get_avail_frames_ret = 0;
- }
-
- struct mixer_control* output_control_;
- struct alsa_io* aio_output_;
- struct cras_audio_format fmt_;
-};
-
-TEST_F(AlsaVolumeMuteSuite, GetDefaultVolumeCurve) {
- int rc;
- struct cras_audio_format* fmt;
-
- fmt = (struct cras_audio_format*)malloc(sizeof(*fmt));
- memcpy(fmt, &fmt_, sizeof(fmt_));
- aio_output_->base.format = fmt;
- aio_output_->handle = (snd_pcm_t*)0x24;
-
- rc = aio_output_->base.configure_dev(&aio_output_->base);
- ASSERT_EQ(0, rc);
- EXPECT_EQ(&default_curve, fake_get_dBFS_volume_curve_val);
-
- aio_output_->base.set_volume(&aio_output_->base);
- EXPECT_EQ(&default_curve, fake_get_dBFS_volume_curve_val);
- free(fmt);
-}
-
-TEST_F(AlsaVolumeMuteSuite, GetVolumeCurveFromNode) {
- int rc;
- struct cras_audio_format* fmt;
- struct cras_alsa_jack* jack = (struct cras_alsa_jack*)4;
- struct cras_ionode* node;
- struct cras_volume_curve hp_curve = {
- .get_dBFS = fake_get_dBFS,
- };
-
- // Headphone jack plugged and has its own volume curve.
- cras_alsa_jack_get_mixer_output_ret = NULL;
- cras_alsa_jack_get_name_ret_value = HEADPHONE;
- cras_card_config_get_volume_curve_vals[HEADPHONE] = &hp_curve;
- cras_alsa_jack_list_create_cb(jack, 1, cras_alsa_jack_list_create_cb_data);
- EXPECT_EQ(1, cras_alsa_jack_update_node_type_called);
- EXPECT_EQ(3, cras_card_config_get_volume_curve_for_control_called);
-
- // These settings should be placed after plugging jacks to make it safer.
- // If is HDMI jack, plug event will trigger update_max_supported_channels()
- // and do open_dev() and close_dev() once. close_dev() will perform alsa_io
- // cleanup.
- // Headphone jack won't trigger, but we still place here due to coherence.
- fmt = (struct cras_audio_format*)malloc(sizeof(*fmt));
- memcpy(fmt, &fmt_, sizeof(fmt_));
- aio_output_->base.format = fmt;
- aio_output_->handle = (snd_pcm_t*)0x24;
-
- // Switch to node 'Headphone'.
- node = aio_output_->base.nodes->next;
- aio_output_->base.active_node = node;
-
- rc = aio_output_->base.configure_dev(&aio_output_->base);
- ASSERT_EQ(0, rc);
- EXPECT_EQ(&hp_curve, fake_get_dBFS_volume_curve_val);
-
- aio_output_->base.set_volume(&aio_output_->base);
- EXPECT_EQ(&hp_curve, fake_get_dBFS_volume_curve_val);
- free(fmt);
-}
-
-TEST_F(AlsaVolumeMuteSuite, SetVolume) {
- int rc;
- struct cras_audio_format* fmt;
- const size_t fake_system_volume = 55;
- const size_t fake_system_volume_dB = (fake_system_volume - 100) * 100;
-
- fmt = (struct cras_audio_format*)malloc(sizeof(*fmt));
- memcpy(fmt, &fmt_, sizeof(fmt_));
- aio_output_->base.format = fmt;
- aio_output_->handle = (snd_pcm_t*)0x24;
-
- sys_get_volume_return_value = fake_system_volume;
- rc = aio_output_->base.configure_dev(&aio_output_->base);
- ASSERT_EQ(0, rc);
- EXPECT_EQ(1, alsa_mixer_set_dBFS_called);
- EXPECT_EQ(fake_system_volume_dB, alsa_mixer_set_dBFS_value);
-
- alsa_mixer_set_dBFS_called = 0;
- alsa_mixer_set_dBFS_value = 0;
- sys_get_volume_return_value = 50;
- sys_get_volume_called = 0;
- aio_output_->base.set_volume(&aio_output_->base);
- EXPECT_EQ(1, sys_get_volume_called);
- EXPECT_EQ(1, alsa_mixer_set_dBFS_called);
- EXPECT_EQ(-5000, alsa_mixer_set_dBFS_value);
- EXPECT_EQ(output_control_, alsa_mixer_set_dBFS_output);
-
- alsa_mixer_set_dBFS_called = 0;
- alsa_mixer_set_dBFS_value = 0;
- sys_get_volume_return_value = 0;
- sys_get_volume_called = 0;
- aio_output_->base.set_volume(&aio_output_->base);
- EXPECT_EQ(1, sys_get_volume_called);
- EXPECT_EQ(1, alsa_mixer_set_dBFS_called);
- EXPECT_EQ(-10000, alsa_mixer_set_dBFS_value);
-
- sys_get_volume_return_value = 80;
- aio_output_->base.active_node->volume = 90;
- aio_output_->base.set_volume(&aio_output_->base);
- EXPECT_EQ(-3000, alsa_mixer_set_dBFS_value);
-
- // close the dev.
- rc = aio_output_->base.close_dev(&aio_output_->base);
- EXPECT_EQ(0, rc);
- EXPECT_EQ((void*)NULL, aio_output_->handle);
-
- free(fmt);
-}
-
-TEST_F(AlsaVolumeMuteSuite, SetMute) {
- int muted;
-
- aio_output_->handle = (snd_pcm_t*)0x24;
-
- // Test mute.
- ResetStubData();
- muted = 1;
-
- sys_get_mute_return_value = muted;
-
- aio_output_->base.set_mute(&aio_output_->base);
-
- EXPECT_EQ(1, sys_get_mute_called);
- EXPECT_EQ(1, alsa_mixer_set_mute_called);
- EXPECT_EQ(muted, alsa_mixer_set_mute_value);
- EXPECT_EQ(output_control_, alsa_mixer_set_mute_output);
-
- // Test unmute.
- ResetStubData();
- muted = 0;
-
- sys_get_mute_return_value = muted;
-
- aio_output_->base.set_mute(&aio_output_->base);
-
- EXPECT_EQ(1, sys_get_mute_called);
- EXPECT_EQ(1, alsa_mixer_set_mute_called);
- EXPECT_EQ(muted, alsa_mixer_set_mute_value);
- EXPECT_EQ(output_control_, alsa_mixer_set_mute_output);
-}
-
-// Test free run.
-class AlsaFreeRunTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- ResetStubData();
- memset(&aio, 0, sizeof(aio));
- fmt_.format = SND_PCM_FORMAT_S16_LE;
- fmt_.frame_rate = 48000;
- fmt_.num_channels = 2;
- aio.base.frames_queued = frames_queued;
- aio.base.output_underrun = alsa_output_underrun;
- aio.base.direction = CRAS_STREAM_OUTPUT;
- aio.base.format = &fmt_;
- aio.base.buffer_size = BUFFER_SIZE;
- aio.base.min_cb_level = 240;
- aio.base.min_buffer_level = 0;
- aio.filled_zeros_for_draining = 0;
- cras_alsa_mmap_begin_buffer = (uint8_t*)calloc(
- BUFFER_SIZE * 2 * 2, sizeof(*cras_alsa_mmap_begin_buffer));
- memset(cras_alsa_mmap_begin_buffer, 0xff,
- sizeof(*cras_alsa_mmap_begin_buffer));
- }
-
- virtual void TearDown() { free(cras_alsa_mmap_begin_buffer); }
-
- struct alsa_io aio;
- struct cras_audio_format fmt_;
-};
-
-TEST_F(AlsaFreeRunTestSuite, FillWholeBufferWithZeros) {
- int rc;
- int16_t* zeros;
-
- rc = fill_whole_buffer_with_zeros(&aio.base);
-
- EXPECT_EQ(0, rc);
- zeros = (int16_t*)calloc(BUFFER_SIZE * 2, sizeof(*zeros));
- EXPECT_EQ(0, memcmp(zeros, cras_alsa_mmap_begin_buffer, BUFFER_SIZE * 2 * 2));
-
- free(zeros);
-}
-
-TEST_F(AlsaFreeRunTestSuite, EnterFreeRunAlreadyFreeRunning) {
- int rc;
-
- // Device is in free run state, no need to fill zeros or fill whole buffer.
- aio.free_running = 1;
-
- rc = no_stream(&aio.base, 1);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_alsa_mmap_get_whole_buffer_called);
- EXPECT_EQ(0, cras_iodev_fill_odev_zeros_called);
- EXPECT_EQ(0, cras_iodev_fill_odev_zeros_frames);
-}
-
-TEST_F(AlsaFreeRunTestSuite, EnterFreeRunNotDrainedYetNeedToFillZeros) {
- int rc, real_hw_level;
- struct timespec hw_tstamp;
- int fill_zeros_duration = 50;
- // Device is not in free run state. There are still valid samples to play.
- // In cras_alsa_io.c, we defined there are 50ms zeros to be filled.
- real_hw_level = 200;
- cras_alsa_get_avail_frames_avail = BUFFER_SIZE - real_hw_level;
-
- rc = aio.base.frames_queued(&aio.base, &hw_tstamp);
- EXPECT_EQ(200, rc);
-
- rc = no_stream(&aio.base, 1);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_alsa_mmap_get_whole_buffer_called);
- EXPECT_EQ(1, cras_iodev_fill_odev_zeros_called);
- EXPECT_EQ(fmt_.frame_rate / 1000 * fill_zeros_duration,
- cras_iodev_fill_odev_zeros_frames);
- EXPECT_EQ(fmt_.frame_rate / 1000 * fill_zeros_duration,
- aio.filled_zeros_for_draining);
- EXPECT_EQ(0, aio.free_running);
-}
-
-TEST_F(AlsaFreeRunTestSuite, EnterFreeRunNotDrainedYetFillZerosExceedBuffer) {
- int rc, real_hw_level;
-
- // Device is not in free run state. There are still valid samples to play.
- // If frames avail is smaller than 50ms(48 * 50 = 2400 zeros), only fill
- // zeros until buffer size.
- real_hw_level = 7000;
- cras_alsa_get_avail_frames_avail = BUFFER_SIZE - real_hw_level;
-
- rc = no_stream(&aio.base, 1);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_alsa_mmap_get_whole_buffer_called);
- EXPECT_EQ(1, cras_iodev_fill_odev_zeros_called);
- EXPECT_EQ(cras_alsa_get_avail_frames_avail,
- cras_iodev_fill_odev_zeros_frames);
- EXPECT_EQ(cras_alsa_get_avail_frames_avail, aio.filled_zeros_for_draining);
- EXPECT_EQ(0, aio.free_running);
-}
-
-TEST_F(AlsaFreeRunTestSuite, EnterFreeRunDrained) {
- int rc, real_hw_level;
-
- // Device is not in free run state. There are still valid samples to play.
- // The number of valid samples is less than filled zeros.
- // Should enter free run state and fill whole buffer with zeros.
- real_hw_level = 40;
- cras_alsa_get_avail_frames_avail = BUFFER_SIZE - real_hw_level;
- aio.filled_zeros_for_draining = 100;
-
- rc = no_stream(&aio.base, 1);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_mmap_get_whole_buffer_called);
- EXPECT_EQ(0, cras_iodev_fill_odev_zeros_called);
- EXPECT_EQ(1, aio.free_running);
-}
-
-TEST_F(AlsaFreeRunTestSuite, EnterFreeRunNoSamples) {
- int rc, real_hw_level;
-
- // Device is not in free run state. There is no sample to play.
- // Should enter free run state and fill whole buffer with zeros.
- real_hw_level = 0;
- cras_alsa_get_avail_frames_avail = BUFFER_SIZE - real_hw_level;
-
- rc = no_stream(&aio.base, 1);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_mmap_get_whole_buffer_called);
- EXPECT_EQ(0, cras_iodev_fill_odev_zeros_called);
- EXPECT_EQ(1, aio.free_running);
-}
-
-TEST_F(AlsaFreeRunTestSuite, IsFreeRunning) {
- aio.free_running = 1;
- EXPECT_EQ(1, is_free_running(&aio.base));
-
- aio.free_running = 0;
- EXPECT_EQ(0, is_free_running(&aio.base));
-}
-
-TEST_F(AlsaFreeRunTestSuite, LeaveFreeRunNotInFreeRunMoreRemain) {
- int rc, real_hw_level;
-
- // Compare min_buffer_level + min_cb_level with valid samples left.
- // 240 + 512 < 900 - 100, so we will get 900 - 100 in appl_ptr_ahead.
-
- aio.free_running = 0;
- aio.filled_zeros_for_draining = 100;
- aio.base.min_buffer_level = 512;
- real_hw_level = 900;
- cras_alsa_get_avail_frames_avail = BUFFER_SIZE - real_hw_level;
-
- rc = no_stream(&aio.base, 0);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_resume_appl_ptr_called);
- EXPECT_EQ(800, cras_alsa_resume_appl_ptr_ahead);
- EXPECT_EQ(0, cras_iodev_fill_odev_zeros_frames);
- EXPECT_EQ(0, aio.free_running);
- EXPECT_EQ(0, aio.filled_zeros_for_draining);
- EXPECT_EQ(1, cras_iodev_reset_rate_estimator_called);
-}
-
-TEST_F(AlsaFreeRunTestSuite, LeaveFreeRunNotInFreeRunLessRemain) {
- int rc, real_hw_level;
-
- // Compare min_buffer_level + min_cb_level with valid samples left.
- // 240 + 256 > 400 - 500, so we will get 240 + 256 in appl_ptr_ahead.
- // And it will fill 240 + 256 - 400 = 96 zeros frames into device.
-
- aio.free_running = 0;
- aio.filled_zeros_for_draining = 500;
- aio.base.min_buffer_level = 256;
- real_hw_level = 400;
- cras_alsa_get_avail_frames_avail = BUFFER_SIZE - real_hw_level;
-
- rc = no_stream(&aio.base, 0);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_resume_appl_ptr_called);
- EXPECT_EQ(aio.base.min_buffer_level + aio.base.min_cb_level,
- cras_alsa_resume_appl_ptr_ahead);
- EXPECT_EQ(96, cras_iodev_fill_odev_zeros_frames);
- EXPECT_EQ(0, aio.free_running);
- EXPECT_EQ(0, aio.filled_zeros_for_draining);
- EXPECT_EQ(1, cras_iodev_reset_rate_estimator_called);
-}
-
-TEST_F(AlsaFreeRunTestSuite, LeaveFreeRunInFreeRun) {
- int rc;
-
- aio.free_running = 1;
- aio.filled_zeros_for_draining = 100;
- aio.base.min_buffer_level = 512;
-
- rc = no_stream(&aio.base, 0);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_alsa_resume_appl_ptr_called);
- EXPECT_EQ(aio.base.min_buffer_level + aio.base.min_cb_level,
- cras_alsa_resume_appl_ptr_ahead);
- EXPECT_EQ(0, aio.free_running);
- EXPECT_EQ(0, aio.filled_zeros_for_draining);
- EXPECT_EQ(1, cras_iodev_reset_rate_estimator_called);
-}
-
-// Reuse AlsaFreeRunTestSuite for output underrun handling because they are
-// similar.
-TEST_F(AlsaFreeRunTestSuite, OutputUnderrun) {
- int rc;
- int16_t* zeros;
- snd_pcm_uframes_t offset;
-
- // Ask alsa_io to handle output underrun.
- rc = alsa_output_underrun(&aio.base);
- EXPECT_EQ(0, rc);
-
- // mmap buffer should be filled with zeros.
- zeros = (int16_t*)calloc(BUFFER_SIZE * 2, sizeof(*zeros));
- EXPECT_EQ(0, memcmp(zeros, cras_alsa_mmap_begin_buffer, BUFFER_SIZE * 2 * 2));
-
- // appl_ptr should be moved to min_buffer_level + 1.5 * min_cb_level ahead of
- // hw_ptr.
- offset = aio.base.min_buffer_level + aio.base.min_cb_level +
- aio.base.min_cb_level / 2;
- EXPECT_EQ(1, cras_alsa_resume_appl_ptr_called);
- EXPECT_EQ(offset, cras_alsa_resume_appl_ptr_ahead);
-
- free(zeros);
-}
-
-TEST(AlsaHotwordNode, HotwordTriggeredSendMessage) {
- struct cras_iodev* iodev;
- struct cras_audio_format format;
- struct alsa_input_node alsa_node;
- struct cras_ionode* node = &alsa_node.base;
- int rc;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_INPUT);
- format.frame_rate = 16000;
- format.num_channels = 1;
- cras_iodev_set_format(iodev, &format);
-
- memset(&alsa_node, 0, sizeof(alsa_node));
- node->dev = iodev;
- strcpy(node->name, HOTWORD_DEV);
- set_node_initial_state(node, ALSA_CARD_TYPE_INTERNAL);
- EXPECT_EQ(CRAS_NODE_TYPE_HOTWORD, node->type);
-
- iodev->active_node = node;
- iodev->open_dev(iodev);
- rc = iodev->configure_dev(iodev);
- free(fake_format);
- ASSERT_EQ(0, rc);
-
- ASSERT_NE(reinterpret_cast<thread_callback>(NULL), audio_thread_cb);
- audio_thread_cb(audio_thread_cb_data, POLLIN);
- EXPECT_EQ(1, hotword_send_triggered_msg_called);
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaGetValidFrames, GetValidFramesNormalState) {
- struct cras_iodev* iodev;
- struct alsa_io* aio;
- struct timespec tstamp;
- int rc;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- aio = (struct alsa_io*)iodev;
-
- aio->free_running = 0;
- aio->filled_zeros_for_draining = 200;
- cras_alsa_get_avail_frames_avail = iodev->buffer_size - 500;
- cras_alsa_get_avail_frames_ret = 0;
- clock_gettime_retspec.tv_sec = 123;
- clock_gettime_retspec.tv_nsec = 321;
- rc = iodev->get_valid_frames(iodev, &tstamp);
- EXPECT_EQ(rc, 300);
- EXPECT_EQ(tstamp.tv_sec, clock_gettime_retspec.tv_sec);
- EXPECT_EQ(tstamp.tv_nsec, clock_gettime_retspec.tv_nsec);
-
- alsa_iodev_destroy(iodev);
-}
-
-TEST(AlsaGetValidFrames, GetValidFramesFreeRunning) {
- struct cras_iodev* iodev;
- struct alsa_io* aio;
- struct timespec tstamp;
- int rc;
-
- ResetStubData();
- iodev = alsa_iodev_create_with_default_parameters(
- 0, NULL, ALSA_CARD_TYPE_INTERNAL, 0, fake_mixer, fake_config, NULL,
- CRAS_STREAM_OUTPUT);
- aio = (struct alsa_io*)iodev;
-
- aio->free_running = 1;
- clock_gettime_retspec.tv_sec = 123;
- clock_gettime_retspec.tv_nsec = 321;
- rc = iodev->get_valid_frames(iodev, &tstamp);
- EXPECT_EQ(rc, 0);
- EXPECT_EQ(tstamp.tv_sec, clock_gettime_retspec.tv_sec);
- EXPECT_EQ(tstamp.tv_nsec, clock_gettime_retspec.tv_nsec);
-
- alsa_iodev_destroy(iodev);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
-
-// Stubs
-
-extern "C" {
-
-// From iodev.
-int cras_iodev_list_add_output(struct cras_iodev* output) {
- return 0;
-}
-int cras_iodev_list_rm_output(struct cras_iodev* dev) {
- return 0;
-}
-
-int cras_iodev_list_add_input(struct cras_iodev* input) {
- return 0;
-}
-int cras_iodev_list_rm_input(struct cras_iodev* dev) {
- return 0;
-}
-
-char* cras_iodev_list_get_hotword_models(cras_node_id_t node_id) {
- return NULL;
-}
-
-int cras_iodev_list_set_hotword_model(cras_node_id_t node_id,
- const char* model_name) {
- return 0;
-}
-
-int cras_iodev_list_suspend_hotword_streams() {
- return 0;
-}
-
-int cras_iodev_list_resume_hotword_stream() {
- return 0;
-}
-
-struct audio_thread* cras_iodev_list_get_audio_thread() {
- return NULL;
-}
-
-// From alsa helper.
-int cras_alsa_set_channel_map(snd_pcm_t* handle,
- struct cras_audio_format* fmt) {
- return 0;
-}
-int cras_alsa_get_channel_map(snd_pcm_t* handle,
- struct cras_audio_format* fmt) {
- return 0;
-}
-int cras_alsa_pcm_open(snd_pcm_t** handle,
- const char* dev,
- snd_pcm_stream_t stream) {
- *handle = (snd_pcm_t*)0x24;
- cras_alsa_open_called++;
- return 0;
-}
-int cras_alsa_pcm_close(snd_pcm_t* handle) {
- return 0;
-}
-int cras_alsa_pcm_start(snd_pcm_t* handle) {
- cras_alsa_start_called++;
- return 0;
-}
-int cras_alsa_pcm_drain(snd_pcm_t* handle) {
- return 0;
-}
-int cras_alsa_fill_properties(snd_pcm_t* handle,
- size_t** rates,
- size_t** channel_counts,
- snd_pcm_format_t** formats) {
- *rates = (size_t*)malloc(sizeof(**rates) * 3);
- (*rates)[0] = 44100;
- (*rates)[1] = 48000;
- (*rates)[2] = 0;
-
- if (cras_alsa_support_8_channels) { // Support up to 8 channels.
- *channel_counts = (size_t*)malloc(sizeof(**channel_counts) * 6);
- (*channel_counts)[0] = 6;
- (*channel_counts)[1] = 4;
- (*channel_counts)[2] = 2;
- (*channel_counts)[3] = 1;
- (*channel_counts)[4] = 8;
- (*channel_counts)[5] = 0;
- } else { // Support 2 channels only.
- *channel_counts = (size_t*)malloc(sizeof(**channel_counts) * 2);
- (*channel_counts)[0] = 2;
- (*channel_counts)[1] = 0;
- }
-
- *formats = (snd_pcm_format_t*)malloc(sizeof(**formats) * 2);
- (*formats)[0] = SND_PCM_FORMAT_S16_LE;
- (*formats)[1] = (snd_pcm_format_t)0;
-
- cras_alsa_fill_properties_called++;
- return 0;
-}
-int cras_alsa_set_hwparams(snd_pcm_t* handle,
- struct cras_audio_format* format,
- snd_pcm_uframes_t* buffer_size,
- int period_wakeup,
- unsigned int dma_period_time) {
- return 0;
-}
-int cras_alsa_set_swparams(snd_pcm_t* handle) {
- return 0;
-}
-int cras_alsa_get_avail_frames(snd_pcm_t* handle,
- snd_pcm_uframes_t buf_size,
- snd_pcm_uframes_t severe_underrun_frames,
- const char* dev_name,
- snd_pcm_uframes_t* used,
- struct timespec* tstamp) {
- *used = cras_alsa_get_avail_frames_avail;
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return cras_alsa_get_avail_frames_ret;
-}
-int cras_alsa_get_delay_frames(snd_pcm_t* handle,
- snd_pcm_uframes_t buf_size,
- snd_pcm_sframes_t* delay) {
- *delay = 0;
- return 0;
-}
-int cras_alsa_mmap_begin(snd_pcm_t* handle,
- unsigned int format_bytes,
- uint8_t** dst,
- snd_pcm_uframes_t* offset,
- snd_pcm_uframes_t* frames) {
- *dst = cras_alsa_mmap_begin_buffer;
- *frames = cras_alsa_mmap_begin_frames;
- return 0;
-}
-int cras_alsa_mmap_commit(snd_pcm_t* handle,
- snd_pcm_uframes_t offset,
- snd_pcm_uframes_t frames) {
- return 0;
-}
-int cras_alsa_attempt_resume(snd_pcm_t* handle) {
- cras_alsa_attempt_resume_called++;
- return 0;
-}
-
-// ALSA stubs.
-int snd_pcm_format_physical_width(snd_pcm_format_t format) {
- return 16;
-}
-
-snd_pcm_state_t snd_pcm_state(snd_pcm_t* handle) {
- return snd_pcm_state_ret;
-}
-
-const char* snd_strerror(int errnum) {
- return "Alsa Error in UT";
-}
-
-struct mixer_control* cras_alsa_mixer_get_control_for_section(
- struct cras_alsa_mixer* cras_mixer,
- const struct ucm_section* section) {
- cras_alsa_mixer_get_control_for_section_called++;
- return cras_alsa_mixer_get_control_for_section_return_value;
-}
-
-const char* cras_alsa_mixer_get_control_name(
- const struct mixer_control* control) {
- ControlNameMap::iterator it;
- cras_alsa_mixer_get_control_name_called++;
- it = cras_alsa_mixer_get_control_name_values.find(control);
- if (it == cras_alsa_mixer_get_control_name_values.end())
- return "";
- return it->second.c_str();
-}
-
-// From system_state.
-size_t cras_system_get_volume() {
- sys_get_volume_called++;
- return sys_get_volume_return_value;
-}
-
-int cras_system_get_mute() {
- sys_get_mute_called++;
- return sys_get_mute_return_value;
-}
-
-int cras_system_get_capture_mute() {
- sys_get_capture_mute_called++;
- return sys_get_capture_mute_return_value;
-}
-
-void cras_system_set_volume_limits(long min, long max) {
- sys_set_volume_limits_called++;
-}
-
-bool cras_system_get_noise_cancellation_enabled() {
- return false;
-}
-
-// From cras_alsa_mixer.
-void cras_alsa_mixer_set_dBFS(struct cras_alsa_mixer* m,
- long dB_level,
- struct mixer_control* output) {
- alsa_mixer_set_dBFS_called++;
- alsa_mixer_set_dBFS_value = dB_level;
- alsa_mixer_set_dBFS_output = output;
-}
-
-void cras_alsa_mixer_set_mute(struct cras_alsa_mixer* cras_mixer,
- int muted,
- struct mixer_control* mixer_output) {
- alsa_mixer_set_mute_called++;
- alsa_mixer_set_mute_value = muted;
- alsa_mixer_set_mute_output = mixer_output;
-}
-
-long cras_alsa_mixer_get_dB_range(struct cras_alsa_mixer* cras_mixer) {
- alsa_mixer_get_dB_range_called++;
- return alsa_mixer_get_dB_range_value;
-}
-
-long cras_alsa_mixer_get_output_dB_range(struct mixer_control* mixer_output) {
- alsa_mixer_get_output_dB_range_called++;
- return alsa_mixer_get_output_dB_range_value;
-}
-
-void cras_alsa_mixer_set_capture_dBFS(struct cras_alsa_mixer* m,
- long dB_level,
- struct mixer_control* mixer_input) {
- alsa_mixer_set_capture_dBFS_called++;
- alsa_mixer_set_capture_dBFS_value = dB_level;
- alsa_mixer_set_capture_dBFS_input = mixer_input;
-}
-
-void cras_alsa_mixer_set_capture_mute(struct cras_alsa_mixer* m,
- int mute,
- struct mixer_control* mixer_input) {
- alsa_mixer_set_capture_mute_called++;
- alsa_mixer_set_capture_mute_value = mute;
- alsa_mixer_set_capture_mute_input = mixer_input;
-}
-
-void cras_alsa_mixer_list_outputs(struct cras_alsa_mixer* cras_mixer,
- cras_alsa_mixer_control_callback cb,
- void* callback_arg) {
- cras_alsa_mixer_list_outputs_called++;
- for (size_t i = 0; i < cras_alsa_mixer_list_outputs_outputs_length; i++) {
- cb(cras_alsa_mixer_list_outputs_outputs[i], callback_arg);
- }
-}
-
-void cras_alsa_mixer_list_inputs(struct cras_alsa_mixer* cras_mixer,
- cras_alsa_mixer_control_callback cb,
- void* callback_arg) {
- cras_alsa_mixer_list_inputs_called++;
- for (size_t i = 0; i < cras_alsa_mixer_list_inputs_outputs_length; i++) {
- cb(cras_alsa_mixer_list_inputs_outputs[i], callback_arg);
- }
-}
-
-int cras_alsa_mixer_set_output_active_state(struct mixer_control* output,
- int active) {
- cras_alsa_mixer_set_output_active_state_called++;
- cras_alsa_mixer_set_output_active_state_outputs.push_back(output);
- cras_alsa_mixer_set_output_active_state_values.push_back(active);
- return 0;
-}
-
-void cras_volume_curve_destroy(struct cras_volume_curve* curve) {}
-
-long cras_alsa_mixer_get_minimum_capture_gain(
- struct cras_alsa_mixer* cmix,
- struct mixer_control* mixer_input) {
- cras_alsa_mixer_get_minimum_capture_gain_called++;
- cras_alsa_mixer_get_minimum_capture_gain_mixer_input = mixer_input;
- return cras_alsa_mixer_get_minimum_capture_gain_ret_value;
-}
-
-long cras_alsa_mixer_get_maximum_capture_gain(
- struct cras_alsa_mixer* cmix,
- struct mixer_control* mixer_input) {
- cras_alsa_mixer_get_maximum_capture_gain_called++;
- cras_alsa_mixer_get_maximum_capture_gain_mixer_input = mixer_input;
- return cras_alsa_mixer_get_maximum_capture_gain_ret_value;
-}
-
-int cras_alsa_mixer_has_main_volume(const struct cras_alsa_mixer* cras_mixer) {
- return 1;
-}
-
-int cras_alsa_mixer_has_volume(const struct mixer_control* mixer_control) {
- return 1;
-}
-
-// From cras_alsa_jack
-struct cras_alsa_jack_list* cras_alsa_jack_list_create(
- unsigned int card_index,
- const char* card_name,
- unsigned int device_index,
- int check_gpio_jack,
- struct cras_alsa_mixer* mixer,
- struct cras_use_case_mgr* ucm,
- snd_hctl_t* hctl,
- enum CRAS_STREAM_DIRECTION direction,
- jack_state_change_callback* cb,
- void* cb_data) {
- cras_alsa_jack_list_create_called++;
- cras_alsa_jack_list_create_cb = cb;
- cras_alsa_jack_list_create_cb_data = cb_data;
- return (struct cras_alsa_jack_list*)0xfee;
-}
-
-int cras_alsa_jack_list_find_jacks_by_name_matching(
- struct cras_alsa_jack_list* jack_list) {
- cras_alsa_jack_list_find_jacks_by_name_matching_called++;
- return 0;
-}
-
-int cras_alsa_jack_list_add_jack_for_section(
- struct cras_alsa_jack_list* jack_list,
- struct ucm_section* ucm_section,
- struct cras_alsa_jack** result_jack) {
- cras_alsa_jack_list_add_jack_for_section_called++;
- if (result_jack)
- *result_jack = cras_alsa_jack_list_add_jack_for_section_result_jack;
- return 0;
-}
-
-void cras_alsa_jack_list_destroy(struct cras_alsa_jack_list* jack_list) {
- cras_alsa_jack_list_destroy_called++;
-}
-
-int cras_alsa_jack_list_has_hctl_jacks(struct cras_alsa_jack_list* jack_list) {
- return cras_alsa_jack_list_has_hctl_jacks_return_val;
-}
-
-void cras_alsa_jack_list_report(const struct cras_alsa_jack_list* jack_list) {}
-
-void cras_alsa_jack_enable_ucm(const struct cras_alsa_jack* jack, int enable) {
- cras_alsa_jack_enable_ucm_called++;
-}
-
-const char* cras_alsa_jack_get_name(const struct cras_alsa_jack* jack) {
- cras_alsa_jack_get_name_called++;
- return cras_alsa_jack_get_name_ret_value;
-}
-
-const char* ucm_get_dsp_name_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev) {
- DspNameMap::iterator it;
- ucm_get_dsp_name_for_dev_called++;
- if (!dev)
- return NULL;
- it = ucm_get_dsp_name_for_dev_values.find(dev);
- if (it == ucm_get_dsp_name_for_dev_values.end())
- return NULL;
- return strdup(it->second.c_str());
-}
-
-struct mixer_control* cras_alsa_jack_get_mixer_output(
- const struct cras_alsa_jack* jack) {
- return cras_alsa_jack_get_mixer_output_ret;
-}
-
-struct mixer_control* cras_alsa_jack_get_mixer_input(
- const struct cras_alsa_jack* jack) {
- return cras_alsa_jack_get_mixer_input_ret;
-}
-
-int ucm_set_enabled(struct cras_use_case_mgr* mgr,
- const char* dev,
- int enabled) {
- ucm_set_enabled_called++;
- return 0;
-}
-
-char* ucm_get_flag(struct cras_use_case_mgr* mgr, const char* flag_name) {
- if ((!strcmp(flag_name, "AutoUnplugInputNode") &&
- auto_unplug_input_node_ret) ||
- (!strcmp(flag_name, "AutoUnplugOutputNode") &&
- auto_unplug_output_node_ret)) {
- char* ret = (char*)malloc(8);
- snprintf(ret, 8, "%s", "1");
- return ret;
- }
-
- return NULL;
-}
-
-int ucm_swap_mode_exists(struct cras_use_case_mgr* mgr) {
- return ucm_swap_mode_exists_ret_value;
-}
-
-int ucm_enable_swap_mode(struct cras_use_case_mgr* mgr,
- const char* node_name,
- int enable) {
- ucm_enable_swap_mode_called++;
- return ucm_enable_swap_mode_ret_value;
-}
-
-int ucm_get_min_buffer_level(struct cras_use_case_mgr* mgr,
- unsigned int* level) {
- *level = 0;
- return 0;
-}
-
-unsigned int ucm_get_disable_software_volume(struct cras_use_case_mgr* mgr) {
- return 0;
-}
-
-char* ucm_get_hotword_models(struct cras_use_case_mgr* mgr) {
- return NULL;
-}
-
-int ucm_set_hotword_model(struct cras_use_case_mgr* mgr, const char* model) {
- return 0;
-}
-
-unsigned int ucm_get_dma_period_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev) {
- ucm_get_dma_period_for_dev_called++;
- return ucm_get_dma_period_for_dev_ret;
-}
-
-int ucm_get_sample_rate_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev,
- enum CRAS_STREAM_DIRECTION direction) {
- return -EINVAL;
-}
-
-int ucm_get_capture_chmap_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev,
- int8_t* channel_layout) {
- return -EINVAL;
-}
-
-int ucm_get_preempt_hotword(struct cras_use_case_mgr* mgr, const char* dev) {
- return 0;
-}
-
-int ucm_get_channels_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev,
- enum CRAS_STREAM_DIRECTION direction,
- size_t* channels) {
- return -EINVAL;
-}
-
-int ucm_node_noise_cancellation_exists(struct cras_use_case_mgr* mgr,
- const char* node_name) {
- return 0;
-}
-
-int ucm_enable_node_noise_cancellation(struct cras_use_case_mgr* mgr,
- const char* node_name,
- int enable) {
- return 0;
-}
-
-struct cras_volume_curve* cras_volume_curve_create_default() {
- return &default_curve;
-}
-
-struct cras_volume_curve* cras_card_config_get_volume_curve_for_control(
- const struct cras_card_config* card_config,
- const char* control_name) {
- VolCurveMap::iterator it;
- cras_card_config_get_volume_curve_for_control_called++;
- if (!control_name)
- return NULL;
- it = cras_card_config_get_volume_curve_vals.find(control_name);
- if (it == cras_card_config_get_volume_curve_vals.end())
- return NULL;
- return it->second;
-}
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {}
-
-int cras_iodev_set_format(struct cras_iodev* iodev,
- const struct cras_audio_format* fmt) {
- fake_format = (struct cras_audio_format*)calloc(1, sizeof(cras_audio_format));
- // Copy the content of format from fmt into format of iodev.
- memcpy(fake_format, fmt, sizeof(cras_audio_format));
- iodev->format = fake_format;
- return 0;
-}
-
-struct audio_thread* audio_thread_create() {
- return reinterpret_cast<audio_thread*>(0x323);
-}
-
-void audio_thread_destroy(audio_thread* thread) {}
-
-void cras_iodev_update_dsp(struct cras_iodev* iodev) {
- cras_iodev_update_dsp_called++;
- cras_iodev_update_dsp_name = iodev->dsp_name ?: "";
-}
-
-void cras_iodev_set_node_plugged(struct cras_ionode* ionode, int plugged) {
- cras_iodev_set_node_plugged_called++;
- cras_iodev_set_node_plugged_ionode = ionode;
- cras_iodev_set_node_plugged_value = plugged;
- if (ionode)
- ionode->plugged = plugged;
-}
-
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_add_node_called++;
- DL_APPEND(iodev->nodes, node);
-}
-
-void cras_iodev_rm_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- DL_DELETE(iodev->nodes, node);
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {
- iodev->active_node = node;
-}
-
-void cras_iodev_free_resources(struct cras_iodev* iodev) {
- cras_iodev_free_resources_called++;
-}
-
-void cras_alsa_jack_update_monitor_name(const struct cras_alsa_jack* jack,
- char* name_buf,
- unsigned int buf_size) {
- if (cras_alsa_jack_update_monitor_fake_name)
- strcpy(name_buf, cras_alsa_jack_update_monitor_fake_name);
-}
-
-void cras_alsa_jack_update_node_type(const struct cras_alsa_jack* jack,
- enum CRAS_NODE_TYPE* type) {
- cras_alsa_jack_update_node_type_called++;
-}
-
-const char* cras_alsa_jack_get_ucm_device(const struct cras_alsa_jack* jack) {
- return NULL;
-}
-
-void ucm_disable_all_hotword_models(struct cras_use_case_mgr* mgr) {}
-
-int ucm_enable_hotword_model(struct cras_use_case_mgr* mgr) {
- return 0;
-}
-
-int ucm_get_default_node_gain(struct cras_use_case_mgr* mgr,
- const char* dev,
- long* gain) {
- if (ucm_get_default_node_gain_values.find(dev) ==
- ucm_get_default_node_gain_values.end())
- return 1;
-
- *gain = ucm_get_default_node_gain_values[dev];
- return 0;
-}
-
-int ucm_get_intrinsic_sensitivity(struct cras_use_case_mgr* mgr,
- const char* dev,
- long* vol) {
- if (ucm_get_intrinsic_sensitivity_values.find(dev) ==
- ucm_get_intrinsic_sensitivity_values.end())
- return 1;
-
- *vol = ucm_get_intrinsic_sensitivity_values[dev];
- return 0;
-}
-
-void cras_iodev_init_audio_area(struct cras_iodev* iodev, int num_channels) {}
-
-void cras_iodev_free_audio_area(struct cras_iodev* iodev) {}
-
-int cras_iodev_reset_rate_estimator(const struct cras_iodev* iodev) {
- cras_iodev_reset_rate_estimator_called++;
- return 0;
-}
-
-int cras_iodev_frames_queued(struct cras_iodev* iodev,
- struct timespec* tstamp) {
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return cras_iodev_frames_queued_ret;
-}
-
-int cras_iodev_buffer_avail(struct cras_iodev* iodev, unsigned hw_level) {
- return cras_iodev_buffer_avail_ret;
-}
-
-int cras_iodev_fill_odev_zeros(struct cras_iodev* odev, unsigned int frames) {
- cras_iodev_fill_odev_zeros_called++;
- cras_iodev_fill_odev_zeros_frames = frames;
- return 0;
-}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {}
-
-void audio_thread_add_events_callback(int fd,
- thread_callback cb,
- void* data,
- int events) {
- audio_thread_cb = cb;
- audio_thread_cb_data = data;
-}
-
-void audio_thread_rm_callback(int fd) {}
-
-int audio_thread_rm_callback_sync(struct audio_thread* thread, int fd) {
- return 0;
-}
-
-int cras_hotword_send_triggered_msg() {
- hotword_send_triggered_msg_called++;
- return 0;
-}
-
-int snd_pcm_poll_descriptors_count(snd_pcm_t* pcm) {
- return 1;
-}
-
-int snd_pcm_poll_descriptors(snd_pcm_t* pcm,
- struct pollfd* pfds,
- unsigned int space) {
- if (space >= 1) {
- pfds[0].events = POLLIN;
- pfds[0].fd = 99;
- }
- return 0;
-}
-
-int is_utf8_string(const char* string) {
- return is_utf8_string_ret_value;
-}
-
-int cras_alsa_mmap_get_whole_buffer(snd_pcm_t* handle, uint8_t** dst) {
- snd_pcm_uframes_t offset, frames;
-
- cras_alsa_mmap_get_whole_buffer_called++;
- return cras_alsa_mmap_begin(handle, 0, dst, &offset, &frames);
-}
-
-int cras_alsa_resume_appl_ptr(snd_pcm_t* handle, snd_pcm_uframes_t ahead) {
- cras_alsa_resume_appl_ptr_called++;
- cras_alsa_resume_appl_ptr_ahead = ahead;
- return 0;
-}
-
-int cras_iodev_default_no_stream_playback(struct cras_iodev* odev, int enable) {
- return 0;
-}
-
-int cras_iodev_output_underrun(struct cras_iodev* odev,
- unsigned int hw_level,
- unsigned int frames_written) {
- return odev->output_underrun(odev);
-}
-
-enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev* iodev) {
- return iodev->state;
-}
-
-int cras_iodev_dsp_set_swap_mode_for_node(struct cras_iodev* iodev,
- struct cras_ionode* node,
- int enable) {
- cras_iodev_dsp_set_swap_mode_for_node_called++;
- return 0;
-}
-
-struct cras_ramp* cras_ramp_create() {
- return (struct cras_ramp*)0x1;
-}
-
-// From librt.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = clock_gettime_retspec.tv_sec;
- tp->tv_nsec = clock_gettime_retspec.tv_nsec;
- return 0;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/alsa_jack_unittest.cc b/cras/src/tests/alsa_jack_unittest.cc
deleted file mode 100644
index 1aa95491..00000000
--- a/cras/src/tests/alsa_jack_unittest.cc
+++ /dev/null
@@ -1,1104 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <linux/input.h>
-#include <poll.h>
-#include <stdio.h>
-#include <sys/param.h>
-#include <syslog.h>
-
-#include <deque>
-#include <map>
-#include <string>
-#include <vector>
-
-extern "C" {
-#include "cras_alsa_jack.h"
-#include "cras_alsa_ucm_section.h"
-#include "cras_gpio_jack.h"
-#include "cras_tm.h"
-#include "cras_types.h"
-#include "cras_util.h"
-}
-
-namespace {
-
-#define BITS_PER_BYTE (8)
-#define BITS_PER_LONG (sizeof(long) * BITS_PER_BYTE)
-#define NBITS(x) ((((x)-1) / BITS_PER_LONG) + 1)
-#define OFF(x) ((x) % BITS_PER_LONG)
-#define BIT(x) (1UL << OFF(x))
-#define LONG(x) ((x) / BITS_PER_LONG)
-#define IS_BIT_SET(bit, array) !!((array[LONG(bit)]) & (1UL << OFF(bit)))
-
-static int fake_jack_cb_plugged;
-static void* fake_jack_cb_data;
-static size_t fake_jack_cb_called;
-unsigned int snd_hctl_elem_get_device_return_val;
-unsigned int snd_hctl_elem_get_device_called;
-static size_t snd_hctl_first_elem_called;
-static snd_hctl_elem_t* snd_hctl_first_elem_return_val;
-static size_t snd_hctl_elem_next_called;
-std::deque<snd_hctl_elem_t*> snd_hctl_elem_next_ret_vals;
-std::deque<snd_hctl_elem_t*> snd_hctl_elem_next_ret_vals_poped;
-static size_t snd_hctl_elem_get_name_called;
-static size_t snd_hctl_elem_set_callback_called;
-static snd_hctl_elem_t* snd_hctl_elem_set_callback_obj;
-static snd_hctl_elem_callback_t snd_hctl_elem_set_callback_value;
-static size_t snd_hctl_find_elem_called;
-static std::vector<snd_hctl_elem_t*> snd_hctl_find_elem_return_vals;
-static std::map<std::string, size_t> snd_ctl_elem_id_set_name_map;
-static size_t cras_system_add_select_fd_called;
-static std::vector<int> cras_system_add_select_fd_values;
-static size_t cras_system_rm_select_fd_called;
-static std::vector<int> cras_system_rm_select_fd_values;
-static size_t snd_hctl_elem_set_callback_private_called;
-static void* snd_hctl_elem_set_callback_private_value;
-static size_t snd_hctl_elem_get_hctl_called;
-static snd_hctl_t* snd_hctl_elem_get_hctl_return_value;
-static size_t snd_ctl_elem_value_get_boolean_called;
-static int snd_ctl_elem_value_get_boolean_return_value;
-static void* fake_jack_cb_arg;
-static struct cras_alsa_mixer* fake_mixer;
-static size_t cras_alsa_mixer_get_output_matching_name_called;
-static size_t cras_alsa_mixer_get_input_matching_name_called;
-static size_t cras_alsa_mixer_get_control_for_section_called;
-static struct mixer_control*
- cras_alsa_mixer_get_output_matching_name_return_value;
-static struct mixer_control*
- cras_alsa_mixer_get_input_matching_name_return_value;
-static struct mixer_control*
- cras_alsa_mixer_get_control_for_section_return_value;
-static size_t gpio_switch_list_for_each_called;
-static std::vector<std::string> gpio_switch_list_for_each_dev_paths;
-static std::vector<std::string> gpio_switch_list_for_each_dev_names;
-static size_t gpio_switch_open_called;
-static size_t gpio_switch_eviocgsw_called;
-static size_t gpio_switch_eviocgbit_called;
-static unsigned ucm_get_dev_for_jack_called;
-static unsigned ucm_get_cap_control_called;
-static char* ucm_get_cap_control_value;
-static bool ucm_get_dev_for_jack_return;
-static int ucm_set_enabled_value;
-static unsigned long eviocbit_ret[NBITS(SW_CNT)];
-static int gpio_switch_eviocgbit_fd;
-static const char* edid_file_ret;
-static unsigned ucm_get_override_type_name_called;
-static int ucm_get_alsa_dev_idx_for_dev_value;
-static snd_hctl_t* fake_hctl = (snd_hctl_t*)2;
-
-static void ResetStubData() {
- gpio_switch_list_for_each_called = 0;
- gpio_switch_list_for_each_dev_paths.clear();
- gpio_switch_list_for_each_dev_paths.push_back("/dev/input/event3");
- gpio_switch_list_for_each_dev_paths.push_back("/dev/input/event2");
- gpio_switch_list_for_each_dev_names.clear();
- gpio_switch_open_called = 0;
- gpio_switch_eviocgsw_called = 0;
- gpio_switch_eviocgbit_called = 0;
- snd_hctl_elem_get_device_return_val = 0;
- snd_hctl_elem_get_device_called = 0;
- snd_hctl_first_elem_called = 0;
- snd_hctl_first_elem_return_val = reinterpret_cast<snd_hctl_elem_t*>(0x87);
- snd_hctl_elem_next_called = 0;
- snd_hctl_elem_next_ret_vals.clear();
- snd_hctl_elem_next_ret_vals_poped.clear();
- snd_hctl_elem_get_name_called = 0;
- snd_hctl_elem_set_callback_called = 0;
- snd_hctl_elem_set_callback_obj = NULL;
- snd_hctl_elem_set_callback_value = NULL;
- snd_hctl_find_elem_called = 0;
- snd_hctl_find_elem_return_vals.clear();
- snd_ctl_elem_id_set_name_map.clear();
- cras_system_add_select_fd_called = 0;
- cras_system_add_select_fd_values.clear();
- cras_system_rm_select_fd_called = 0;
- cras_system_rm_select_fd_values.clear();
- snd_hctl_elem_set_callback_private_called = 0;
- snd_hctl_elem_get_hctl_called = 0;
- snd_ctl_elem_value_get_boolean_called = 0;
- fake_jack_cb_called = 0;
- fake_jack_cb_plugged = 0;
- fake_jack_cb_arg = reinterpret_cast<void*>(0x987);
- fake_mixer = reinterpret_cast<struct cras_alsa_mixer*>(0x789);
- cras_alsa_mixer_get_output_matching_name_called = 0;
- cras_alsa_mixer_get_input_matching_name_called = 0;
- cras_alsa_mixer_get_control_for_section_called = 0;
- cras_alsa_mixer_get_output_matching_name_return_value =
- reinterpret_cast<struct mixer_control*>(0x456);
- cras_alsa_mixer_get_input_matching_name_return_value = NULL;
- cras_alsa_mixer_get_control_for_section_return_value =
- reinterpret_cast<struct mixer_control*>(0x456);
- ucm_get_dev_for_jack_called = 0;
- ucm_get_cap_control_called = 0;
- ucm_get_cap_control_value = NULL;
- ucm_get_dev_for_jack_return = false;
- edid_file_ret = NULL;
- ucm_get_override_type_name_called = 0;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- memset(eviocbit_ret, 0, sizeof(eviocbit_ret));
-}
-
-static void fake_jack_cb(const struct cras_alsa_jack* jack,
- int plugged,
- void* data) {
- fake_jack_cb_called++;
- fake_jack_cb_plugged = plugged;
- fake_jack_cb_data = data;
-
- // Check that jack enable callback is called if there is a ucm device.
- ucm_set_enabled_value = !plugged;
- cras_alsa_jack_enable_ucm(jack, plugged);
- EXPECT_EQ(ucm_get_dev_for_jack_return ? plugged : !plugged,
- ucm_set_enabled_value);
-}
-
-TEST(AlsaJacks, CreateNullHctl) {
- struct cras_alsa_jack_list* jack_list;
- ResetStubData();
- jack_list = cras_alsa_jack_list_create(0, "c1", 0, 1, fake_mixer, NULL, NULL,
- CRAS_STREAM_OUTPUT, fake_jack_cb,
- fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_EQ(0, gpio_switch_open_called);
- EXPECT_EQ(0, gpio_switch_eviocgsw_called);
- EXPECT_EQ(0, gpio_switch_eviocgbit_called);
-
- cras_alsa_jack_list_destroy(jack_list);
-}
-
-TEST(AlsaJacks, CreateNoElements) {
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- snd_hctl_first_elem_return_val = NULL;
- jack_list = cras_alsa_jack_list_create(0, "c1", 0, 1, fake_mixer, NULL,
- fake_hctl, CRAS_STREAM_OUTPUT,
- fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_EQ(0, gpio_switch_open_called);
- EXPECT_EQ(0, gpio_switch_eviocgsw_called);
- EXPECT_EQ(0, gpio_switch_eviocgbit_called);
- EXPECT_EQ(1, snd_hctl_first_elem_called);
- EXPECT_EQ(0, snd_hctl_elem_next_called);
-
- cras_alsa_jack_list_destroy(jack_list);
-}
-
-static struct cras_alsa_jack_list* run_test_with_elem_list(
- CRAS_STREAM_DIRECTION direction,
- std::string* elems,
- unsigned int device_index,
- struct cras_use_case_mgr* ucm,
- size_t nelems,
- size_t nhdmi_jacks,
- size_t njacks) {
- struct cras_alsa_jack_list* jack_list;
-
- snd_hctl_first_elem_return_val =
- reinterpret_cast<snd_hctl_elem_t*>(&elems[0]);
- for (unsigned int i = 1; i < nelems; i++)
- snd_hctl_elem_next_ret_vals.push_front(
- reinterpret_cast<snd_hctl_elem_t*>(&elems[i]));
-
- jack_list = cras_alsa_jack_list_create(0, "card_name", device_index, 1,
- fake_mixer, ucm, fake_hctl, direction,
- fake_jack_cb, fake_jack_cb_arg);
- if (jack_list == NULL)
- return jack_list;
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- EXPECT_EQ(ucm ? njacks : 0, ucm_get_dev_for_jack_called);
- EXPECT_EQ(ucm ? njacks : 0, ucm_get_override_type_name_called);
- EXPECT_EQ(1, snd_hctl_first_elem_called);
- EXPECT_EQ(njacks, snd_hctl_elem_set_callback_called);
- EXPECT_EQ(nhdmi_jacks, snd_hctl_find_elem_called);
-
- /* For some functions, the number of calls to them could
- * be larger then expected count if there is ELD control
- * in given elements. */
- EXPECT_GE(snd_hctl_elem_next_called, nelems);
- EXPECT_GE(snd_hctl_elem_get_name_called, nelems);
-
- if (direction == CRAS_STREAM_OUTPUT) {
- EXPECT_EQ(njacks, cras_alsa_mixer_get_output_matching_name_called);
- }
- if (direction == CRAS_STREAM_INPUT && ucm_get_dev_for_jack_return) {
- EXPECT_EQ(njacks, ucm_get_cap_control_called);
- }
-
- return jack_list;
-}
-
-static struct cras_alsa_jack_list* run_test_with_section(
- CRAS_STREAM_DIRECTION direction,
- std::string* elems,
- size_t nelems,
- unsigned int device_index,
- struct cras_use_case_mgr* ucm,
- struct ucm_section* ucm_section,
- int add_jack_rc,
- size_t njacks) {
- struct cras_alsa_jack_list* jack_list;
- struct cras_alsa_jack* jack;
-
- for (size_t i = 0; i < nelems; i++) {
- snd_ctl_elem_id_set_name_map[elems[i]] = i;
- snd_hctl_find_elem_return_vals.push_back(
- reinterpret_cast<snd_hctl_elem_t*>(&elems[i]));
- }
-
- jack_list = cras_alsa_jack_list_create(0, "card_name", device_index, 1,
- fake_mixer, ucm, fake_hctl, direction,
- fake_jack_cb, fake_jack_cb_arg);
- if (jack_list == NULL)
- return jack_list;
- EXPECT_EQ(add_jack_rc, cras_alsa_jack_list_add_jack_for_section(
- jack_list, ucm_section, &jack));
- if (add_jack_rc == 0) {
- EXPECT_NE(jack, reinterpret_cast<struct cras_alsa_jack*>(NULL));
- } else {
- EXPECT_EQ(jack, reinterpret_cast<struct cras_alsa_jack*>(NULL));
- }
- if (add_jack_rc != 0) {
- cras_alsa_jack_list_destroy(jack_list);
- return NULL;
- }
- EXPECT_EQ(njacks, snd_hctl_elem_set_callback_called);
- EXPECT_EQ(njacks, cras_alsa_mixer_get_control_for_section_called);
-
- return jack_list;
-}
-
-TEST(AlsaJacks, ReportNull) {
- cras_alsa_jack_list_report(NULL);
-}
-
-TEST(AlsaJacks, CreateNoJacks) {
- static std::string elem_names[] = {
- "Mic Jack",
- "foo",
- "bar",
- };
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- jack_list = run_test_with_elem_list(CRAS_STREAM_OUTPUT, elem_names, 0, NULL,
- ARRAY_SIZE(elem_names), 0, 0);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
-
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(0, cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaJacks, CreateGPIOHp) {
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- gpio_switch_list_for_each_dev_names.push_back("some-other-device");
- gpio_switch_list_for_each_dev_names.push_back("c1 Headphone Jack");
- eviocbit_ret[LONG(SW_HEADPHONE_INSERT)] |= 1 << OFF(SW_HEADPHONE_INSERT);
- gpio_switch_eviocgbit_fd = 2;
- snd_hctl_first_elem_return_val = NULL;
- jack_list = cras_alsa_jack_list_create(0, "c1", 0, 1, fake_mixer, NULL,
- fake_hctl, CRAS_STREAM_OUTPUT,
- fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_GT(gpio_switch_open_called, 1);
- EXPECT_EQ(1, gpio_switch_eviocgsw_called);
- EXPECT_GT(gpio_switch_eviocgbit_called, 1);
- EXPECT_EQ(1, cras_system_add_select_fd_called);
- EXPECT_EQ(1, cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaJacks, CreateGPIOMic) {
- struct cras_alsa_jack_list* jack_list;
- ResetStubData();
- ucm_get_dev_for_jack_return = true;
- gpio_switch_list_for_each_dev_names.push_back("c1 Mic Jack");
- gpio_switch_list_for_each_dev_names.push_back("c1 Headphone Jack");
- eviocbit_ret[LONG(SW_MICROPHONE_INSERT)] |= 1 << OFF(SW_MICROPHONE_INSERT);
- gpio_switch_eviocgbit_fd = 3;
- snd_hctl_first_elem_return_val = NULL;
- ucm_get_cap_control_value = reinterpret_cast<char*>(0x1);
-
- cras_alsa_mixer_get_input_matching_name_return_value =
- reinterpret_cast<struct mixer_control*>(malloc(1));
-
- jack_list = cras_alsa_jack_list_create(
- 0, "c1", 0, 1, fake_mixer,
- reinterpret_cast<struct cras_use_case_mgr*>(0x55), fake_hctl,
- CRAS_STREAM_INPUT, fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- EXPECT_EQ(ucm_get_cap_control_called, 1);
- EXPECT_EQ(cras_alsa_mixer_get_input_matching_name_called, 1);
- cras_alsa_jack_list_destroy(jack_list);
- // Mixer will be free by alsa_card_destroy, we should free it explicitly here
- free(cras_alsa_mixer_get_input_matching_name_return_value);
-}
-
-TEST(AlsaJacks, CreateGPIOHdmi) {
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- gpio_switch_list_for_each_dev_names.push_back("c1 HDMI Jack");
- gpio_switch_list_for_each_dev_names.push_back("c1 Mic Jack");
- eviocbit_ret[LONG(SW_LINEOUT_INSERT)] |= 1 << OFF(SW_LINEOUT_INSERT);
- gpio_switch_eviocgbit_fd = 3;
- snd_hctl_first_elem_return_val = NULL;
- jack_list = cras_alsa_jack_list_create(0, "c1", 0, 1, fake_mixer, NULL,
- fake_hctl, CRAS_STREAM_OUTPUT,
- fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- EXPECT_EQ(1, gpio_switch_eviocgsw_called);
-
- fake_jack_cb_called = 0;
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
-
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_GT(gpio_switch_open_called, 1);
- EXPECT_GT(gpio_switch_eviocgbit_called, 1);
- EXPECT_EQ(1, cras_system_add_select_fd_called);
- EXPECT_EQ(1, cras_system_rm_select_fd_called);
-}
-
-void run_gpio_jack_test(int device_index,
- int is_first_device,
- enum CRAS_STREAM_DIRECTION direction,
- int should_create_jack,
- const char* jack_name) {
- struct cras_alsa_jack_list* jack_list;
- struct cras_use_case_mgr* ucm =
- reinterpret_cast<struct cras_use_case_mgr*>(0x55);
-
- gpio_switch_list_for_each_dev_names.push_back("some-other-device one");
- gpio_switch_eviocgbit_fd = 2;
- if (direction == CRAS_STREAM_OUTPUT) {
- eviocbit_ret[LONG(SW_HEADPHONE_INSERT)] |= 1 << OFF(SW_HEADPHONE_INSERT);
- } else {
- eviocbit_ret[LONG(SW_MICROPHONE_INSERT)] |= 1 << OFF(SW_MICROPHONE_INSERT);
- }
- gpio_switch_list_for_each_dev_names.push_back(jack_name);
- snd_hctl_first_elem_return_val = NULL;
-
- jack_list = cras_alsa_jack_list_create(0, "c1", device_index, is_first_device,
- fake_mixer, ucm, fake_hctl, direction,
- fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
-
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(should_create_jack, fake_jack_cb_plugged);
- EXPECT_EQ(should_create_jack, fake_jack_cb_called);
-
- cras_alsa_jack_list_destroy(jack_list);
-}
-
-TEST(AlsaJacks, CreateGPIOHpUCMPlaybackPCMMatched) {
- int device_index = 1;
- int is_first_device = 0;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_OUTPUT;
- int should_create_jack = 1;
-
- ResetStubData();
-
- /* PlaybackPCM matched, so create jack even if this is not the first device.*/
- ucm_get_dev_for_jack_return = true;
- ucm_get_alsa_dev_idx_for_dev_value = 1;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOHpUCMCapturePCMMatched) {
- int device_index = 1;
- int is_first_device = 0;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_INPUT;
- int should_create_jack = 1;
-
- ResetStubData();
-
- /* CapturePCM matched, so create jack even if this is not the first device.*/
- ucm_get_dev_for_jack_return = true;
- ucm_get_alsa_dev_idx_for_dev_value = 1;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Mic Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOHpUCMPlaybackPCMNotMatched) {
- int device_index = 0;
- int is_first_device = 1;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_OUTPUT;
- int should_create_jack = 0;
-
- ResetStubData();
-
- /* PlaybackPCM not matched, do not create jack. */
- ucm_get_dev_for_jack_return = true;
- ucm_get_alsa_dev_idx_for_dev_value = 2;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOHpUCMPlaybackPCMNotSpecifiedFirstDevice) {
- int device_index = 1;
- int is_first_device = 1;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_OUTPUT;
- int should_create_jack = 1;
-
- ResetStubData();
-
- /* PlaybackPCM not specified, create jack for the first device. */
- ucm_get_dev_for_jack_return = true;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOHpUCMPlaybackPCMNotSpecifiedSecondDevice) {
- int device_index = 1;
- int is_first_device = 0;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_OUTPUT;
- int should_create_jack = 0;
-
- ResetStubData();
-
- /* PlaybackPCM not specified, do not create jack for the second device. */
- ucm_get_dev_for_jack_return = true;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOHpNoUCMFirstDevice) {
- int device_index = 1;
- int is_first_device = 1;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_OUTPUT;
- int should_create_jack = 1;
-
- ResetStubData();
-
- /* No UCM for this jack, create jack for the first device. */
- ucm_get_dev_for_jack_return = false;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOHpNoUCMSecondDevice) {
- int device_index = 1;
- int is_first_device = 0;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_OUTPUT;
- int should_create_jack = 0;
-
- ResetStubData();
-
- /* No UCM for this jack, dot not create jack for the second device. */
- ucm_get_dev_for_jack_return = false;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOMicNoUCMFirstDeviceMicJack) {
- int device_index = 1;
- int is_first_device = 1;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_INPUT;
- int should_create_jack = 1;
-
- ResetStubData();
-
- // No UCM for this jack, create jack for the first device.
- ucm_get_dev_for_jack_return = false;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- // Mic Jack is a valid name for microphone jack.
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Mic Jack");
-}
-
-TEST(AlsaJacks, CreateGPIOMicNoUCMFirstDeviceHeadsetJack) {
- int device_index = 1;
- int is_first_device = 1;
- enum CRAS_STREAM_DIRECTION direction = CRAS_STREAM_INPUT;
- int should_create_jack = 1;
-
- ResetStubData();
-
- // No UCM for this jack, create jack for the first device.
- ucm_get_dev_for_jack_return = false;
- ucm_get_alsa_dev_idx_for_dev_value = -1;
-
- // Headset Jack is a valid name for microphone jack.
- run_gpio_jack_test(device_index, is_first_device, direction,
- should_create_jack, "c1 Headset Jack");
-}
-
-TEST(AlsaJacks, GPIOHdmiWithEdid) {
- cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- ucm_get_dev_for_jack_return = 1;
- edid_file_ret = static_cast<char*>(calloc(1, 1)); // Freed in destroy.
- gpio_switch_list_for_each_dev_names.push_back("c1 HDMI Jack");
- eviocbit_ret[LONG(SW_LINEOUT_INSERT)] |= 1 << OFF(SW_LINEOUT_INSERT);
- gpio_switch_eviocgbit_fd = 3;
- snd_hctl_first_elem_return_val = NULL;
- jack_list = cras_alsa_jack_list_create(
- 0, "c1", 0, 1, fake_mixer,
- reinterpret_cast<struct cras_use_case_mgr*>(0x55), fake_hctl,
- CRAS_STREAM_OUTPUT, fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
- EXPECT_EQ(1, gpio_switch_eviocgsw_called);
-
- // EDID shouldn't open, callback should be skipped until re-try.
- fake_jack_cb_called = 0;
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(0, fake_jack_cb_called);
-
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_GT(gpio_switch_open_called, 1);
- EXPECT_GT(gpio_switch_eviocgbit_called, 1);
- EXPECT_EQ(1, cras_system_add_select_fd_called);
- EXPECT_EQ(1, cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaJacks, CreateGPIOHpNoNameMatch) {
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- gpio_switch_list_for_each_dev_names.push_back("some-other-device one");
- gpio_switch_list_for_each_dev_names.push_back("some-other-device two");
- snd_hctl_first_elem_return_val = NULL;
- jack_list = cras_alsa_jack_list_create(0, "c2", 0, 1, fake_mixer, NULL,
- fake_hctl, CRAS_STREAM_OUTPUT,
- fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(0, cras_alsa_jack_list_find_jacks_by_name_matching(jack_list));
-
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_EQ(0, gpio_switch_open_called);
- EXPECT_EQ(0, cras_system_add_select_fd_called);
- EXPECT_EQ(0, cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaJacks, CreateOneHpJack) {
- std::string elem_names[] = {
- "asdf",
- "Headphone Jack, klasdjf",
- "Mic Jack",
- };
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- jack_list = run_test_with_elem_list(CRAS_STREAM_OUTPUT, elem_names, 0, NULL,
- ARRAY_SIZE(elem_names), 0, 1);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- ASSERT_NE(reinterpret_cast<snd_hctl_elem_callback_t>(NULL),
- snd_hctl_elem_set_callback_value);
- EXPECT_EQ(1, snd_hctl_elem_set_callback_called);
-
- snd_hctl_elem_get_hctl_return_value = reinterpret_cast<snd_hctl_t*>(0x33);
- snd_hctl_elem_get_name_called = 0;
- snd_ctl_elem_value_get_boolean_return_value = 1;
- snd_hctl_elem_set_callback_value(
- reinterpret_cast<snd_hctl_elem_t*>(&elem_names[1]), 0);
- EXPECT_EQ(1, snd_hctl_elem_get_name_called);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
- EXPECT_EQ(fake_jack_cb_arg, fake_jack_cb_data);
- EXPECT_EQ(reinterpret_cast<snd_hctl_elem_t*>(&elem_names[1]),
- snd_hctl_elem_set_callback_obj);
-
- fake_jack_cb_called = 0;
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
-
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(2, snd_hctl_elem_set_callback_called);
- EXPECT_EQ(reinterpret_cast<snd_hctl_elem_callback_t>(NULL),
- snd_hctl_elem_set_callback_value);
-}
-
-TEST(AlsaJacks, CreateOneMicJack) {
- static std::string elem_names[] = {
- "asdf", "Headphone Jack", "HDMI/DP,pcm=5 Jack", "HDMI/DP,pcm=6 Jack",
- "Mic Jack",
- };
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- jack_list = run_test_with_elem_list(CRAS_STREAM_INPUT, elem_names, 0, NULL,
- ARRAY_SIZE(elem_names), 0, 1);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- ASSERT_NE(reinterpret_cast<snd_hctl_elem_callback_t>(NULL),
- snd_hctl_elem_set_callback_value);
- EXPECT_EQ(1, snd_hctl_elem_set_callback_called);
-
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(0, cras_system_rm_select_fd_called);
- EXPECT_EQ(2, snd_hctl_elem_set_callback_called);
- EXPECT_EQ(reinterpret_cast<snd_hctl_elem_callback_t>(NULL),
- snd_hctl_elem_set_callback_value);
-}
-
-TEST(AlsaJacks, CreateHDMIJacksWithELD) {
- std::string elem_names[] = {"asdf", "HDMI/DP,pcm=3 Jack", "ELD",
- "HDMI/DP,pcm=4 Jack"};
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- snd_hctl_elem_get_device_return_val = 3;
-
- jack_list = run_test_with_elem_list(CRAS_STREAM_OUTPUT, elem_names, 3, NULL,
- ARRAY_SIZE(elem_names), 1, 1);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
-
- /* Assert get device is called for the ELD control */
- EXPECT_EQ(1, snd_hctl_find_elem_called);
- cras_alsa_jack_list_destroy(jack_list);
-}
-
-TEST(AlsaJacks, CreateOneHpTwoHDMIJacks) {
- std::string elem_names[] = {
- "asdf",
- "Headphone Jack, klasdjf",
- "HDMI/DP,pcm=5 Jack",
- "HDMI/DP,pcm=6 Jack",
- "Mic Jack",
- };
- struct cras_alsa_jack_list* jack_list;
-
- ResetStubData();
- ucm_get_dev_for_jack_return = true;
- jack_list =
- run_test_with_elem_list(CRAS_STREAM_OUTPUT, elem_names, 5,
- reinterpret_cast<struct cras_use_case_mgr*>(0x55),
- ARRAY_SIZE(elem_names), 1, 1);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
-
- snd_hctl_elem_get_hctl_return_value = reinterpret_cast<snd_hctl_t*>(0x33);
- snd_hctl_elem_get_name_called = 0;
- snd_ctl_elem_value_get_boolean_return_value = 1;
- snd_hctl_elem_set_callback_value(
- reinterpret_cast<snd_hctl_elem_t*>(&elem_names[2]), 0);
- EXPECT_EQ(1, snd_hctl_elem_get_name_called);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
- EXPECT_EQ(fake_jack_cb_arg, fake_jack_cb_data);
- EXPECT_EQ(reinterpret_cast<snd_hctl_elem_t*>(&elem_names[2]),
- snd_hctl_elem_set_callback_obj);
-
- fake_jack_cb_called = 0;
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
-
- cras_alsa_jack_list_destroy(jack_list);
-}
-
-TEST(AlsaJacks, CreateHCTLHeadphoneJackFromUCM) {
- std::string elem_names[] = {
- "HP/DP,pcm=5 Jack",
- "Headphone Jack",
- };
- struct cras_alsa_jack_list* jack_list;
- struct ucm_section* section;
-
- section = ucm_section_create("Headphone", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "Headphone Jack", "hctl");
-
- ResetStubData();
- ucm_get_dev_for_jack_return = true;
-
- jack_list = run_test_with_section(
- CRAS_STREAM_OUTPUT, elem_names, ARRAY_SIZE(elem_names), 5,
- reinterpret_cast<struct cras_use_case_mgr*>(0x55), section, 0, 1);
- ASSERT_NE(reinterpret_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
-
- snd_hctl_elem_get_hctl_return_value = reinterpret_cast<snd_hctl_t*>(0x33);
- snd_ctl_elem_value_get_boolean_return_value = 1;
- snd_hctl_elem_set_callback_value(
- reinterpret_cast<snd_hctl_elem_t*>(&elem_names[1]), 0);
- EXPECT_EQ(1, snd_hctl_elem_get_name_called);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
- EXPECT_EQ(fake_jack_cb_arg, fake_jack_cb_data);
- EXPECT_EQ(reinterpret_cast<snd_hctl_elem_t*>(&elem_names[1]),
- snd_hctl_elem_set_callback_obj);
-
- fake_jack_cb_called = 0;
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
-
- ucm_section_free_list(section);
- cras_alsa_jack_list_destroy(jack_list);
-}
-
-TEST(AlsaJacks, CreateGPIOHeadphoneJackFromUCM) {
- struct cras_alsa_jack_list* jack_list;
- struct cras_alsa_jack* jack;
- struct ucm_section* section;
-
- section = ucm_section_create("Headphone", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "c1 Headphone Jack", "gpio");
-
- ResetStubData();
- gpio_switch_list_for_each_dev_names.push_back("some-other-device");
- gpio_switch_list_for_each_dev_names.push_back("c1 Headphone Jack");
- eviocbit_ret[LONG(SW_HEADPHONE_INSERT)] |= 1 << OFF(SW_HEADPHONE_INSERT);
- gpio_switch_eviocgbit_fd = 2;
- snd_hctl_first_elem_return_val = NULL;
- jack_list = cras_alsa_jack_list_create(0, "c1", 0, 1, fake_mixer, NULL,
- fake_hctl, CRAS_STREAM_OUTPUT,
- fake_jack_cb, fake_jack_cb_arg);
- ASSERT_NE(static_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
- EXPECT_EQ(
- 0, cras_alsa_jack_list_add_jack_for_section(jack_list, section, &jack));
- EXPECT_EQ(1, gpio_switch_list_for_each_called);
- EXPECT_GT(gpio_switch_open_called, 1);
- EXPECT_EQ(1, gpio_switch_eviocgsw_called);
- EXPECT_GT(gpio_switch_eviocgbit_called, 1);
- EXPECT_EQ(1, cras_system_add_select_fd_called);
- EXPECT_EQ(1, cras_alsa_mixer_get_control_for_section_called);
-
- fake_jack_cb_called = 0;
- ucm_get_dev_for_jack_return = true;
- cras_alsa_jack_list_report(jack_list);
- EXPECT_EQ(1, fake_jack_cb_plugged);
- EXPECT_EQ(1, fake_jack_cb_called);
- EXPECT_EQ(fake_jack_cb_arg, fake_jack_cb_data);
-
- ucm_section_free_list(section);
- cras_alsa_jack_list_destroy(jack_list);
- EXPECT_EQ(1, cras_system_rm_select_fd_called);
-}
-
-TEST(AlsaJacks, BadJackTypeFromUCM) {
- std::string elem_names[] = {
- "HP/DP,pcm=5 Jack",
- "Headphone Jack",
- };
- struct cras_alsa_jack_list* jack_list;
- struct ucm_section* section;
-
- section = ucm_section_create("Headphone", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "Headphone Jack", "badtype");
-
- ResetStubData();
- ucm_get_dev_for_jack_return = true;
-
- jack_list = run_test_with_section(
- CRAS_STREAM_OUTPUT, elem_names, ARRAY_SIZE(elem_names), 5,
- reinterpret_cast<struct cras_use_case_mgr*>(0x55), section, -22, 1);
- EXPECT_EQ(reinterpret_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
-
- ucm_section_free_list(section);
-}
-
-TEST(AlsaJacks, NoJackTypeFromUCM) {
- std::string elem_names[] = {
- "HP/DP,pcm=5 Jack",
- "Headphone Jack",
- };
- struct cras_alsa_jack_list* jack_list;
- struct ucm_section* section;
-
- section = ucm_section_create("Headphone", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "Headphone Jack", NULL);
-
- ResetStubData();
- ucm_get_dev_for_jack_return = true;
-
- jack_list = run_test_with_section(
- CRAS_STREAM_OUTPUT, elem_names, ARRAY_SIZE(elem_names), 5,
- reinterpret_cast<struct cras_use_case_mgr*>(0x55), section, -22, 1);
- EXPECT_EQ(reinterpret_cast<struct cras_alsa_jack_list*>(NULL), jack_list);
-
- ucm_section_free_list(section);
-}
-
-/* Stubs */
-
-extern "C" {
-
-// From cras_system_state
-int cras_system_add_select_fd(int fd,
- void (*callback)(void* data),
- void* callback_data) {
- cras_system_add_select_fd_called++;
- cras_system_add_select_fd_values.push_back(fd);
- return 0;
-}
-void cras_system_rm_select_fd(int fd) {
- cras_system_rm_select_fd_called++;
- cras_system_rm_select_fd_values.push_back(fd);
-}
-
-// From alsa-lib hcontrol.c
-unsigned int snd_hctl_elem_get_device(const snd_hctl_elem_t* obj) {
- snd_hctl_elem_get_device_called = 1;
- return snd_hctl_elem_get_device_return_val;
-}
-snd_hctl_elem_t* snd_hctl_first_elem(snd_hctl_t* hctl) {
- snd_hctl_first_elem_called++;
-
- /* When first elem is called, restored the poped ret values */
- while (!snd_hctl_elem_next_ret_vals_poped.empty()) {
- snd_hctl_elem_t* tmp = snd_hctl_elem_next_ret_vals_poped.back();
- snd_hctl_elem_next_ret_vals_poped.pop_back();
- snd_hctl_elem_next_ret_vals.push_back(tmp);
- }
- return snd_hctl_first_elem_return_val;
-}
-snd_hctl_elem_t* snd_hctl_elem_next(snd_hctl_elem_t* elem) {
- snd_hctl_elem_next_called++;
- if (snd_hctl_elem_next_ret_vals.empty())
- return NULL;
- snd_hctl_elem_t* ret_elem = snd_hctl_elem_next_ret_vals.back();
- snd_hctl_elem_next_ret_vals.pop_back();
- snd_hctl_elem_next_ret_vals_poped.push_back(ret_elem);
- return ret_elem;
-}
-const char* snd_hctl_elem_get_name(const snd_hctl_elem_t* obj) {
- snd_hctl_elem_get_name_called++;
- const std::string* name = reinterpret_cast<const std::string*>(obj);
- return name->c_str();
-}
-snd_ctl_elem_iface_t snd_hctl_elem_get_interface(const snd_hctl_elem_t* obj) {
- return SND_CTL_ELEM_IFACE_CARD;
-}
-void snd_hctl_elem_set_callback(snd_hctl_elem_t* obj,
- snd_hctl_elem_callback_t val) {
- snd_hctl_elem_set_callback_called++;
- snd_hctl_elem_set_callback_obj = obj;
- snd_hctl_elem_set_callback_value = val;
-}
-void snd_hctl_elem_set_callback_private(snd_hctl_elem_t* obj, void* val) {
- snd_hctl_elem_set_callback_private_called++;
- snd_hctl_elem_set_callback_private_value = val;
-}
-void* snd_hctl_elem_get_callback_private(const snd_hctl_elem_t* obj) {
- return snd_hctl_elem_set_callback_private_value;
-}
-snd_hctl_t* snd_hctl_elem_get_hctl(snd_hctl_elem_t* elem) {
- snd_hctl_elem_get_hctl_called++;
- return snd_hctl_elem_get_hctl_return_value;
-}
-int snd_hctl_elem_read(snd_hctl_elem_t* elem, snd_ctl_elem_value_t* value) {
- return 0;
-}
-snd_hctl_elem_t* snd_hctl_find_elem(snd_hctl_t* hctl,
- const snd_ctl_elem_id_t* id) {
- const size_t* index = reinterpret_cast<const size_t*>(id);
- snd_hctl_find_elem_called++;
- if (*index < snd_hctl_find_elem_return_vals.size())
- return snd_hctl_find_elem_return_vals[*index];
- return NULL;
-}
-void snd_ctl_elem_id_set_interface(snd_ctl_elem_id_t* obj,
- snd_ctl_elem_iface_t val) {}
-void snd_ctl_elem_id_set_device(snd_ctl_elem_id_t* obj, unsigned int val) {}
-void snd_ctl_elem_id_set_name(snd_ctl_elem_id_t* obj, const char* val) {
- size_t* obj_id = reinterpret_cast<size_t*>(obj);
- std::map<std::string, size_t>::iterator id_name_it =
- snd_ctl_elem_id_set_name_map.find(val);
- if (id_name_it != snd_ctl_elem_id_set_name_map.end())
- *obj_id = id_name_it->second;
- else
- *obj_id = INT_MAX;
-}
-
-// From alsa-lib control.c
-int snd_ctl_elem_value_get_boolean(const snd_ctl_elem_value_t* obj,
- unsigned int idx) {
- snd_ctl_elem_value_get_boolean_called++;
- return snd_ctl_elem_value_get_boolean_return_value;
-}
-
-// From cras_alsa_mixer
-struct mixer_control* cras_alsa_mixer_get_output_matching_name(
- const struct cras_alsa_mixer* cras_mixer,
- size_t device_index,
- const char* const name) {
- cras_alsa_mixer_get_output_matching_name_called++;
- return cras_alsa_mixer_get_output_matching_name_return_value;
-}
-
-struct mixer_control* cras_alsa_mixer_get_input_matching_name(
- struct cras_alsa_mixer* cras_mixer,
- const char* control_name) {
- cras_alsa_mixer_get_input_matching_name_called++;
- return cras_alsa_mixer_get_input_matching_name_return_value;
-}
-
-struct mixer_control* cras_alsa_mixer_get_control_for_section(
- struct cras_alsa_mixer* cras_mixer,
- struct ucm_section* section) {
- cras_alsa_mixer_get_control_for_section_called++;
- return cras_alsa_mixer_get_control_for_section_return_value;
-}
-
-int gpio_switch_eviocgbit(int fd, void* buf, size_t n_bytes) {
- unsigned char* p = (unsigned char*)buf;
-
- /* Returns >= 0 if 'sw' is supported, negative if not.
- *
- * Set the bit corresponding to 'sw' in 'buf'. 'buf' must have
- * been allocated by the caller to accommodate this.
- */
- if (fd == gpio_switch_eviocgbit_fd)
- memcpy(p, eviocbit_ret, n_bytes);
- else
- memset(p, 0, n_bytes);
-
- gpio_switch_eviocgbit_called++;
- return 1;
-}
-
-int gpio_switch_eviocgsw(int fd, void* bits, size_t n_bytes) {
- /* Bits set to '1' indicate a switch is enabled.
- * Bits set to '0' indicate a switch is disabled
- */
- gpio_switch_eviocgsw_called++;
- memset(bits, 0xff, n_bytes);
- return 1;
-}
-
-int gpio_switch_read(int fd, void* buf, size_t n_bytes) {
- /* This function is only invoked when the 'switch has changed'
- * callback is invoked. That code is not exercised by this
- * unittest.
- */
- assert(0);
- return 0;
-}
-
-int gpio_switch_open(const char* pathname) {
- ++gpio_switch_open_called;
- if (strstr(pathname, "event2"))
- return 2;
- if (strstr(pathname, "event3"))
- return 3;
- return 0;
-}
-
-void gpio_switch_list_for_each(gpio_switch_list_callback callback, void* arg) {
- size_t i = 0;
-
- ++gpio_switch_list_for_each_called;
-
- while (i < gpio_switch_list_for_each_dev_names.size() &&
- i < gpio_switch_list_for_each_dev_paths.size()) {
- callback(gpio_switch_list_for_each_dev_paths[i].c_str(),
- gpio_switch_list_for_each_dev_names[i].c_str(), arg);
- i++;
- }
-}
-
-int ucm_set_enabled(struct cras_use_case_mgr* mgr,
- const char* dev,
- int enable) {
- ucm_set_enabled_value = enable;
- return 0;
-}
-
-char* ucm_get_cap_control(struct cras_use_case_mgr* mgr, const char* ucm_dev) {
- ++ucm_get_cap_control_called;
- return ucm_get_cap_control_value;
-}
-
-char* ucm_get_dev_for_jack(struct cras_use_case_mgr* mgr,
- const char* jack,
- CRAS_STREAM_DIRECTION direction) {
- ++ucm_get_dev_for_jack_called;
- if (ucm_get_dev_for_jack_return)
- return static_cast<char*>(
- malloc(1)); // Will be freed in jack_list_destroy.
- return NULL;
-}
-
-const char* ucm_get_edid_file_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev) {
- return edid_file_ret;
-}
-
-const char* ucm_get_override_type_name(struct cras_use_case_mgr* mgr,
- const char* ucm_dev) {
- ++ucm_get_override_type_name_called;
- return NULL;
-}
-
-int ucm_get_alsa_dev_idx_for_dev(struct cras_use_case_mgr* mgr,
- const char* dev,
- enum CRAS_STREAM_DIRECTION direction) {
- return ucm_get_alsa_dev_idx_for_dev_value;
-}
-
-cras_timer* cras_tm_create_timer(cras_tm* tm,
- unsigned int ms,
- void (*cb)(cras_timer* t, void* data),
- void* cb_data) {
- return reinterpret_cast<cras_timer*>(0x55);
-}
-
-void cras_tm_cancel_timer(cras_tm* tm, cras_timer* t) {}
-
-cras_tm* cras_system_state_get_tm() {
- return reinterpret_cast<cras_tm*>(0x66);
-}
-
-int edid_valid(const unsigned char* edid_data) {
- return 0;
-}
-
-int edid_lpcm_support(const unsigned char* edid_data, int ext) {
- return 0;
-}
-
-int edid_get_monitor_name(const unsigned char* edid_data,
- char* buf,
- unsigned int buf_size) {
- return 0;
-}
-
-// Overwrite this function so unittest can run without 2 seconds of wait
-// in find_gpio_jacks.
-int wait_for_dev_input_access() {
- return 0;
-}
-
-} /* extern "C" */
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/alsa_mixer_unittest.cc b/cras/src/tests/alsa_mixer_unittest.cc
deleted file mode 100644
index b3db9de5..00000000
--- a/cras/src/tests/alsa_mixer_unittest.cc
+++ /dev/null
@@ -1,1645 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <syslog.h>
-
-#include <map>
-#include <string>
-#include <vector>
-
-extern "C" {
-#include "cras_alsa_mixer.h"
-#include "cras_alsa_mixer_name.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "cras_volume_curve.h"
-#include "utlist.h"
-
-// Include C file to test static functions and use the definition of some
-// structure.
-#include "cras_alsa_mixer.c"
-}
-
-namespace {
-
-static size_t snd_mixer_open_called;
-static int snd_mixer_open_return_value;
-static size_t snd_mixer_close_called;
-static size_t snd_mixer_attach_called;
-static int snd_mixer_attach_return_value;
-const char* snd_mixer_attach_mixdev;
-static size_t snd_mixer_selem_register_called;
-static int snd_mixer_selem_register_return_value;
-static size_t snd_mixer_load_called;
-static int snd_mixer_load_return_value;
-static size_t snd_mixer_first_elem_called;
-static snd_mixer_elem_t* snd_mixer_first_elem_return_value;
-static int snd_mixer_elem_next_called;
-static snd_mixer_elem_t** snd_mixer_elem_next_return_values;
-static int snd_mixer_elem_next_return_values_index;
-static int snd_mixer_elem_next_return_values_length;
-static int snd_mixer_selem_set_playback_dB_all_called;
-static long* snd_mixer_selem_set_playback_dB_all_values;
-static int snd_mixer_selem_set_playback_dB_all_values_length;
-static int snd_mixer_selem_set_playback_switch_all_called;
-static int snd_mixer_selem_set_playback_switch_all_value;
-static int snd_mixer_selem_has_playback_volume_called;
-static int* snd_mixer_selem_has_playback_volume_return_values;
-static int snd_mixer_selem_has_playback_volume_return_values_length;
-static int snd_mixer_selem_has_playback_switch_called;
-static int* snd_mixer_selem_has_playback_switch_return_values;
-static int snd_mixer_selem_has_playback_switch_return_values_length;
-static int snd_mixer_selem_set_capture_dB_all_called;
-static long* snd_mixer_selem_set_capture_dB_all_values;
-static int snd_mixer_selem_set_capture_dB_all_values_length;
-static int snd_mixer_selem_set_capture_switch_all_called;
-static int snd_mixer_selem_set_capture_switch_all_value;
-static int snd_mixer_selem_has_capture_volume_called;
-static int* snd_mixer_selem_has_capture_volume_return_values;
-static int snd_mixer_selem_has_capture_volume_return_values_length;
-static int snd_mixer_selem_has_capture_switch_called;
-static int* snd_mixer_selem_has_capture_switch_return_values;
-static int snd_mixer_selem_has_capture_switch_return_values_length;
-static int snd_mixer_selem_get_name_called;
-static const char** snd_mixer_selem_get_name_return_values;
-static int snd_mixer_selem_get_name_return_values_length;
-static int snd_mixer_selem_get_playback_dB_called;
-static long* snd_mixer_selem_get_playback_dB_return_values;
-static int snd_mixer_selem_get_playback_dB_return_values_length;
-static int snd_mixer_selem_get_capture_dB_called;
-static long* snd_mixer_selem_get_capture_dB_return_values;
-static int snd_mixer_selem_get_capture_dB_return_values_length;
-static size_t cras_volume_curve_destroy_called;
-static size_t snd_mixer_selem_get_playback_dB_range_called;
-static size_t snd_mixer_selem_get_playback_dB_range_values_length;
-static const long* snd_mixer_selem_get_playback_dB_range_min_values;
-static const long* snd_mixer_selem_get_playback_dB_range_max_values;
-static size_t snd_mixer_selem_get_capture_dB_range_called;
-static size_t snd_mixer_selem_get_capture_dB_range_values_length;
-static const long* snd_mixer_selem_get_capture_dB_range_min_values;
-static const long* snd_mixer_selem_get_capture_dB_range_max_values;
-static size_t iniparser_getstring_return_index;
-static size_t iniparser_getstring_return_length;
-static char** iniparser_getstring_returns;
-static size_t snd_mixer_find_selem_called;
-static std::map<std::string, snd_mixer_elem_t*> snd_mixer_find_elem_map;
-static std::string snd_mixer_find_elem_id_name;
-
-static void ResetStubData() {
- iniparser_getstring_return_index = 0;
- iniparser_getstring_return_length = 0;
- snd_mixer_open_called = 0;
- snd_mixer_open_return_value = 0;
- snd_mixer_close_called = 0;
- snd_mixer_attach_called = 0;
- snd_mixer_attach_return_value = 0;
- snd_mixer_attach_mixdev = static_cast<const char*>(NULL);
- snd_mixer_selem_register_called = 0;
- snd_mixer_selem_register_return_value = 0;
- snd_mixer_load_called = 0;
- snd_mixer_load_return_value = 0;
- snd_mixer_first_elem_called = 0;
- snd_mixer_first_elem_return_value = static_cast<snd_mixer_elem_t*>(NULL);
- snd_mixer_elem_next_called = 0;
- snd_mixer_elem_next_return_values = static_cast<snd_mixer_elem_t**>(NULL);
- snd_mixer_elem_next_return_values_index = 0;
- snd_mixer_elem_next_return_values_length = 0;
- snd_mixer_selem_set_playback_dB_all_called = 0;
- snd_mixer_selem_set_playback_dB_all_values = static_cast<long*>(NULL);
- snd_mixer_selem_set_playback_dB_all_values_length = 0;
- snd_mixer_selem_set_playback_switch_all_called = 0;
- snd_mixer_selem_has_playback_volume_called = 0;
- snd_mixer_selem_has_playback_volume_return_values = static_cast<int*>(NULL);
- snd_mixer_selem_has_playback_volume_return_values_length = 0;
- snd_mixer_selem_has_playback_switch_called = 0;
- snd_mixer_selem_has_playback_switch_return_values = static_cast<int*>(NULL);
- snd_mixer_selem_has_playback_switch_return_values_length = 0;
- snd_mixer_selem_set_capture_dB_all_called = 0;
- snd_mixer_selem_set_capture_dB_all_values = static_cast<long*>(NULL);
- snd_mixer_selem_set_capture_dB_all_values_length = 0;
- snd_mixer_selem_set_capture_switch_all_called = 0;
- snd_mixer_selem_has_capture_volume_called = 0;
- snd_mixer_selem_has_capture_volume_return_values = static_cast<int*>(NULL);
- snd_mixer_selem_has_capture_volume_return_values_length = 0;
- snd_mixer_selem_has_capture_switch_called = 0;
- snd_mixer_selem_has_capture_switch_return_values = static_cast<int*>(NULL);
- snd_mixer_selem_has_capture_switch_return_values_length = 0;
- snd_mixer_selem_get_name_called = 0;
- snd_mixer_selem_get_name_return_values = static_cast<const char**>(NULL);
- snd_mixer_selem_get_name_return_values_length = 0;
- snd_mixer_selem_get_playback_dB_called = 0;
- snd_mixer_selem_get_playback_dB_return_values = static_cast<long*>(NULL);
- snd_mixer_selem_get_playback_dB_return_values_length = 0;
- snd_mixer_selem_get_capture_dB_called = 0;
- snd_mixer_selem_get_capture_dB_return_values = static_cast<long*>(NULL);
- snd_mixer_selem_get_capture_dB_return_values_length = 0;
- cras_volume_curve_destroy_called = 0;
- snd_mixer_selem_get_playback_dB_range_called = 0;
- snd_mixer_selem_get_playback_dB_range_values_length = 0;
- snd_mixer_selem_get_playback_dB_range_min_values = static_cast<long*>(NULL);
- snd_mixer_selem_get_playback_dB_range_max_values = static_cast<long*>(NULL);
- snd_mixer_selem_get_capture_dB_range_called = 0;
- snd_mixer_selem_get_capture_dB_range_values_length = 0;
- snd_mixer_selem_get_capture_dB_range_min_values = static_cast<long*>(NULL);
- snd_mixer_selem_get_capture_dB_range_max_values = static_cast<long*>(NULL);
- snd_mixer_find_selem_called = 0;
- snd_mixer_find_elem_map.clear();
- snd_mixer_find_elem_id_name.clear();
-}
-
-struct cras_alsa_mixer* create_mixer_and_add_controls_by_name_matching(
- const char* card_name,
- struct mixer_name* extra_controls,
- struct mixer_name* coupled_controls) {
- struct cras_alsa_mixer* cmix = cras_alsa_mixer_create(card_name);
- cras_alsa_mixer_add_controls_by_name_matching(cmix, extra_controls,
- coupled_controls);
- return cmix;
-}
-
-TEST(AlsaMixer, CreateFailOpen) {
- struct cras_alsa_mixer* c;
-
- ResetStubData();
- snd_mixer_open_return_value = -1;
- c = cras_alsa_mixer_create("hw:0");
- EXPECT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- cras_alsa_mixer_destroy(c);
-}
-
-TEST(AlsaMixer, CreateFailAttach) {
- struct cras_alsa_mixer* c;
-
- ResetStubData();
- snd_mixer_attach_return_value = -1;
- c = cras_alsa_mixer_create("hw:0");
- EXPECT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_close_called);
- cras_alsa_mixer_destroy(c);
-}
-
-TEST(AlsaMixer, CreateFailSelemRegister) {
- struct cras_alsa_mixer* c;
-
- ResetStubData();
- snd_mixer_selem_register_return_value = -1;
- c = cras_alsa_mixer_create("hw:0");
- EXPECT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_close_called);
- cras_alsa_mixer_destroy(c);
-}
-
-TEST(AlsaMixer, CreateFailLoad) {
- struct cras_alsa_mixer* c;
-
- ResetStubData();
- snd_mixer_load_return_value = -1;
- c = cras_alsa_mixer_create("hw:0");
- EXPECT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(1, snd_mixer_close_called);
- cras_alsa_mixer_destroy(c);
-}
-
-TEST(AlsaMixer, CreateNoElements) {
- struct cras_alsa_mixer* c;
-
- ResetStubData();
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
-
- /* set mute shouldn't call anything. */
- cras_alsa_mixer_set_mute(c, 0, NULL);
- EXPECT_EQ(0, snd_mixer_selem_set_playback_switch_all_called);
- /* set volume shouldn't call anything. */
- cras_alsa_mixer_set_dBFS(c, 0, NULL);
- EXPECT_EQ(0, snd_mixer_selem_set_playback_dB_all_called);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
-}
-
-TEST(AlsaMixer, CreateOneUnknownElementWithoutVolume) {
- struct cras_alsa_mixer* c;
- int element_playback_volume[] = {
- 0,
- };
- int element_playback_switches[] = {
- 1,
- };
- const char* element_names[] = {
- "Unknown",
- };
- struct mixer_control* mixer_output;
- int rc;
-
- ResetStubData();
- snd_mixer_first_elem_return_value = reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_get_name_called);
- EXPECT_EQ(0, snd_mixer_selem_get_playback_dB_range_called);
-
- /* set mute shouldn't call anything. */
- cras_alsa_mixer_set_mute(c, 0, NULL);
- EXPECT_EQ(0, snd_mixer_selem_set_playback_switch_all_called);
-
- ResetStubData();
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- rc = mixer_control_create(&mixer_output, NULL,
- reinterpret_cast<snd_mixer_elem_t*>(1),
- CRAS_STREAM_OUTPUT);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_mixer_selem_get_name_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_switch_called);
- EXPECT_EQ(1, snd_mixer_selem_get_playback_dB_range_called);
-
- /* if passed a mixer output then it should mute that. */
- cras_alsa_mixer_set_mute(c, 0, mixer_output);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_switch_all_called);
- /* set volume shouldn't call anything. */
- cras_alsa_mixer_set_dBFS(c, 0, NULL);
- EXPECT_EQ(0, snd_mixer_selem_set_playback_dB_all_called);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_control_destroy(mixer_output);
-}
-
-TEST(AlsaMixer, CreateOneUnknownElementWithVolume) {
- struct cras_alsa_mixer* c;
- static const long min_volumes[] = {-500};
- static const long max_volumes[] = {40};
- int element_playback_volume[] = {
- 1,
- 0,
- };
- int element_playback_switches[] = {
- 0,
- 1,
- };
- const char* element_names[] = {
- "Unknown",
- "Playback",
- };
- struct mixer_control* mixer_output;
- int rc;
-
- ResetStubData();
- snd_mixer_first_elem_return_value = reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
- EXPECT_EQ(3, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(2, snd_mixer_selem_get_playback_dB_range_called);
- EXPECT_EQ(3, snd_mixer_selem_get_name_called);
-
- /* Should use "Playback" since it has playback switch. */
- cras_alsa_mixer_set_mute(c, 0, NULL);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_switch_all_called);
-
- ResetStubData();
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- rc = mixer_control_create(&mixer_output, NULL,
- reinterpret_cast<snd_mixer_elem_t*>(2),
- CRAS_STREAM_OUTPUT);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_mixer_selem_get_name_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_switch_called);
- EXPECT_EQ(0, snd_mixer_selem_get_playback_dB_range_called);
-
- /*
- * If passed a mixer output then it should mute both "Playback" and that
- * mixer_output.
- */
- cras_alsa_mixer_set_mute(c, 0, mixer_output);
- EXPECT_EQ(2, snd_mixer_selem_set_playback_switch_all_called);
- cras_alsa_mixer_set_dBFS(c, 0, NULL);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_dB_all_called);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_control_destroy(mixer_output);
-}
-
-TEST(AlsaMixer, CreateOneMainElement) {
- struct cras_alsa_mixer* c;
- int element_playback_volume[] = {
- 1,
- 1,
- };
- int element_playback_switches[] = {
- 1,
- 1,
- };
- const char* element_names[] = {"Master", "Playback"};
- struct mixer_control* mixer_output;
- int rc;
- long set_dB_values[3];
- static const long min_volumes[] = {0, 0};
- static const long max_volumes[] = {950, 950};
-
- ResetStubData();
- snd_mixer_first_elem_return_value = reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
- EXPECT_EQ(3, snd_mixer_selem_get_name_called);
- EXPECT_EQ(1, snd_mixer_elem_next_called);
-
- /* set mute should be called for Main. */
- cras_alsa_mixer_set_mute(c, 0, NULL);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_switch_all_called);
- /* set volume should be called for Main. */
- cras_alsa_mixer_set_dBFS(c, 0, NULL);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_dB_all_called);
-
- ResetStubData();
- snd_mixer_selem_set_playback_dB_all_values = set_dB_values;
- snd_mixer_selem_set_playback_dB_all_values_length = ARRAY_SIZE(set_dB_values);
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- rc = mixer_control_create(&mixer_output, NULL,
- reinterpret_cast<snd_mixer_elem_t*>(2),
- CRAS_STREAM_OUTPUT);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_mixer_selem_get_name_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_switch_called);
- EXPECT_EQ(1, snd_mixer_selem_get_playback_dB_range_called);
-
- /* if passed a mixer output then it should set the volume for that too. */
- cras_alsa_mixer_set_dBFS(c, 0, mixer_output);
- EXPECT_EQ(2, snd_mixer_selem_set_playback_dB_all_called);
- EXPECT_EQ(950, set_dB_values[0]);
- EXPECT_EQ(950, set_dB_values[1]);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_control_destroy(mixer_output);
-}
-
-TEST(AlsaMixer, CreateTwoMainVolumeElements) {
- struct cras_alsa_mixer* c;
- snd_mixer_elem_t* elements[] = {
- reinterpret_cast<snd_mixer_elem_t*>(2),
- };
- int element_playback_volume[] = {
- 1,
- 1,
- 1,
- };
- int element_playback_switches[] = {
- 1,
- 1,
- 1,
- };
- const char* element_names[] = {
- "Master",
- "PCM",
- "Other",
- };
- struct mixer_control* mixer_output;
- int rc;
- static const long min_volumes[] = {-500, -1250, -500};
- static const long max_volumes[] = {40, 40, 0};
- long get_dB_returns[] = {0, 0, 0};
- long set_dB_values[3];
-
- ResetStubData();
- snd_mixer_first_elem_return_value = reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_elem_next_return_values = elements;
- snd_mixer_elem_next_return_values_length = ARRAY_SIZE(elements);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- snd_mixer_selem_get_playback_dB_range_called = 0;
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
- snd_mixer_selem_set_playback_dB_all_values = set_dB_values;
- snd_mixer_selem_set_playback_dB_all_values_length = ARRAY_SIZE(set_dB_values);
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(2, snd_mixer_selem_get_playback_dB_range_called);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
- EXPECT_EQ(2, snd_mixer_elem_next_called);
- EXPECT_EQ(5, snd_mixer_selem_get_name_called);
- EXPECT_EQ(3, snd_mixer_selem_has_playback_switch_called);
-
- /* Set mute should be called for Main only. */
- cras_alsa_mixer_set_mute(c, 0, NULL);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_switch_all_called);
-
- /* Set volume should be called for Main and PCM. If Main doesn't set to
- * anything but zero then the entire volume should be passed to the PCM
- * control.*/
-
- /* Set volume should be called for Main and PCM. (without mixer_output) */
- snd_mixer_selem_get_playback_dB_return_values = get_dB_returns;
- snd_mixer_selem_get_playback_dB_return_values_length =
- ARRAY_SIZE(get_dB_returns);
- cras_alsa_mixer_set_dBFS(c, -50, NULL);
- EXPECT_EQ(2, snd_mixer_selem_set_playback_dB_all_called);
- EXPECT_EQ(2, snd_mixer_selem_get_playback_dB_called);
- /* volume should be set relative to max volume (40 + 40). */
- EXPECT_EQ(30, set_dB_values[0]);
- EXPECT_EQ(30, set_dB_values[1]);
-
- ResetStubData();
- snd_mixer_selem_set_playback_dB_all_values = set_dB_values;
- snd_mixer_selem_set_playback_dB_all_values_length = ARRAY_SIZE(set_dB_values);
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- rc = mixer_control_create(&mixer_output, NULL,
- reinterpret_cast<snd_mixer_elem_t*>(3),
- CRAS_STREAM_OUTPUT);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_mixer_selem_get_name_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_has_playback_switch_called);
- EXPECT_EQ(1, snd_mixer_selem_get_playback_dB_range_called);
-
- /* Set volume should be called for Main, PCM, and the mixer_output passed
- * in. If Main doesn't set to anything but zero then the entire volume
- * should be passed to the PCM control.*/
- cras_alsa_mixer_set_dBFS(c, -50, mixer_output);
- EXPECT_EQ(3, snd_mixer_selem_set_playback_dB_all_called);
- EXPECT_EQ(2, snd_mixer_selem_get_playback_dB_called);
- EXPECT_EQ(30, set_dB_values[0]);
- EXPECT_EQ(30, set_dB_values[1]);
- EXPECT_EQ(30, set_dB_values[2]);
- /* Set volume should be called for Main and PCM. Since the controls were
- * sorted, Main should get the volume remaining after PCM is set, in this
- * case -50 - -24 = -26. */
- long get_dB_returns2[] = {
- -25,
- -24,
- };
- snd_mixer_selem_get_playback_dB_return_values = get_dB_returns2;
- snd_mixer_selem_get_playback_dB_return_values_length =
- ARRAY_SIZE(get_dB_returns2);
- snd_mixer_selem_set_playback_dB_all_called = 0;
- snd_mixer_selem_get_playback_dB_called = 0;
- mixer_output->has_volume = 0;
- mixer_output->min_volume_dB = MIXER_CONTROL_VOLUME_DB_INVALID;
- mixer_output->max_volume_dB = MIXER_CONTROL_VOLUME_DB_INVALID;
- cras_alsa_mixer_set_dBFS(c, -50, mixer_output);
- EXPECT_EQ(2, snd_mixer_selem_set_playback_dB_all_called);
- EXPECT_EQ(2, snd_mixer_selem_get_playback_dB_called);
- EXPECT_EQ(54, set_dB_values[0]); // Main
- EXPECT_EQ(30, set_dB_values[1]); // PCM
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_control_destroy(mixer_output);
-}
-
-TEST(AlsaMixer, CreateTwoMainCaptureElements) {
- struct cras_alsa_mixer* c;
- snd_mixer_elem_t* elements[] = {
- reinterpret_cast<snd_mixer_elem_t*>(2),
- };
- int element_capture_volume[] = {
- 1,
- 1,
- 1,
- };
- int element_capture_switches[] = {
- 1,
- 1,
- 1,
- };
- const char* element_names[] = {
- "Capture",
- "Digital Capture",
- "Mic",
- };
- struct mixer_control* mixer_input;
- int rc;
-
- ResetStubData();
- snd_mixer_first_elem_return_value = reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_elem_next_return_values = elements;
- snd_mixer_elem_next_return_values_length = ARRAY_SIZE(elements);
- snd_mixer_selem_has_capture_volume_return_values = element_capture_volume;
- snd_mixer_selem_has_capture_volume_return_values_length =
- ARRAY_SIZE(element_capture_volume);
- snd_mixer_selem_has_capture_switch_return_values = element_capture_switches;
- snd_mixer_selem_has_capture_switch_return_values_length =
- ARRAY_SIZE(element_capture_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
- EXPECT_EQ(2, snd_mixer_elem_next_called);
- EXPECT_EQ(5, snd_mixer_selem_get_name_called);
- EXPECT_EQ(3, snd_mixer_selem_has_capture_switch_called);
-
- /* Set mute should be called for Main only. */
- cras_alsa_mixer_set_capture_mute(c, 0, NULL);
- EXPECT_EQ(1, snd_mixer_selem_set_capture_switch_all_called);
- /* Set volume should be called for Capture and Digital Capture. If Capture
- * doesn't set to anything but zero then the entire volume should be passed to
- * the Digital Capture control. */
- long get_dB_returns[] = {
- 0,
- 0,
- };
- long set_dB_values[2];
- snd_mixer_selem_get_capture_dB_return_values = get_dB_returns;
- snd_mixer_selem_get_capture_dB_return_values_length =
- ARRAY_SIZE(get_dB_returns);
- snd_mixer_selem_set_capture_dB_all_values = set_dB_values;
- snd_mixer_selem_set_capture_dB_all_values_length = ARRAY_SIZE(set_dB_values);
- cras_alsa_mixer_set_capture_dBFS(c, -10, NULL);
- EXPECT_EQ(2, snd_mixer_selem_set_capture_dB_all_called);
- EXPECT_EQ(2, snd_mixer_selem_get_capture_dB_called);
- EXPECT_EQ(-10, set_dB_values[0]);
- EXPECT_EQ(-10, set_dB_values[1]);
- /* Set volume should be called for Capture and Digital Capture. Capture should
- * get the gain remaining after Mic Boos is set, in this case 20 - 25 = -5. */
- long get_dB_returns2[] = {
- 25,
- -5,
- };
- snd_mixer_selem_get_capture_dB_return_values = get_dB_returns2;
- snd_mixer_selem_get_capture_dB_return_values_length =
- ARRAY_SIZE(get_dB_returns2);
- snd_mixer_selem_set_capture_dB_all_values = set_dB_values;
- snd_mixer_selem_set_capture_dB_all_values_length = ARRAY_SIZE(set_dB_values);
- snd_mixer_selem_set_capture_dB_all_called = 0;
- snd_mixer_selem_get_capture_dB_called = 0;
- cras_alsa_mixer_set_capture_dBFS(c, 20, NULL);
- EXPECT_EQ(2, snd_mixer_selem_set_capture_dB_all_called);
- EXPECT_EQ(2, snd_mixer_selem_get_capture_dB_called);
- EXPECT_EQ(20, set_dB_values[0]);
- EXPECT_EQ(-5, set_dB_values[1]);
-
- /* Set volume to the two main controls plus additional specific input
- * volume control */
-
- long get_dB_returns3[] = {
- 0,
- 0,
- 0,
- };
- long set_dB_values3[3];
-
- snd_mixer_selem_get_capture_dB_return_values = get_dB_returns3;
- snd_mixer_selem_get_capture_dB_return_values_length =
- ARRAY_SIZE(get_dB_returns3);
- snd_mixer_selem_get_capture_dB_called = 0;
- snd_mixer_selem_set_capture_dB_all_values = set_dB_values3;
- snd_mixer_selem_set_capture_dB_all_values_length = ARRAY_SIZE(set_dB_values3);
- snd_mixer_selem_set_capture_dB_all_called = 0;
- snd_mixer_selem_has_capture_volume_return_values = element_capture_volume;
- snd_mixer_selem_has_capture_volume_return_values_length =
- ARRAY_SIZE(element_capture_volume);
- snd_mixer_selem_has_capture_switch_return_values = element_capture_switches;
- snd_mixer_selem_has_capture_switch_return_values_length =
- ARRAY_SIZE(element_capture_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- snd_mixer_selem_get_name_called = 0;
- snd_mixer_selem_has_capture_volume_called = 0;
- snd_mixer_selem_has_capture_switch_called = 0;
- snd_mixer_selem_get_capture_dB_range_called = 0;
- rc = mixer_control_create(&mixer_input, NULL,
- reinterpret_cast<snd_mixer_elem_t*>(3),
- CRAS_STREAM_INPUT);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_mixer_selem_get_name_called);
- EXPECT_EQ(1, snd_mixer_selem_has_capture_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_has_capture_switch_called);
- EXPECT_EQ(1, snd_mixer_selem_get_capture_dB_range_called);
- EXPECT_EQ(1, mixer_input->has_volume);
-
- cras_alsa_mixer_set_capture_dBFS(c, 20, mixer_input);
-
- EXPECT_EQ(3, snd_mixer_selem_set_capture_dB_all_called);
- EXPECT_EQ(2, snd_mixer_selem_get_capture_dB_called);
- EXPECT_EQ(20, set_dB_values3[0]);
- EXPECT_EQ(20, set_dB_values3[1]);
- EXPECT_EQ(20, set_dB_values3[2]);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_control_destroy(mixer_input);
-}
-
-class AlsaMixerOutputs : public testing::Test {
- protected:
- virtual void SetUp() {
- output_called_values_.clear();
- output_callback_called_ = 0;
- static snd_mixer_elem_t* elements[] = {
- reinterpret_cast<snd_mixer_elem_t*>(2), // PCM
- reinterpret_cast<snd_mixer_elem_t*>(3), // Headphone
- reinterpret_cast<snd_mixer_elem_t*>(4), // Speaker
- reinterpret_cast<snd_mixer_elem_t*>(5), // HDMI
- reinterpret_cast<snd_mixer_elem_t*>(6), // IEC958
- reinterpret_cast<snd_mixer_elem_t*>(7), // Mic Boost
- reinterpret_cast<snd_mixer_elem_t*>(8), // Capture
- };
- static int element_playback_volume[] = {
- 1, 1, 1, 0, 0, 1, 1,
- };
- static int element_playback_switches[] = {
- 1, 1, 1, 0, 1, 1, 1,
- };
- static int element_capture_volume[] = {
- 0, 0, 0, 0, 0, 0, 1, 1,
- };
- static int element_capture_switches[] = {
- 0, 0, 0, 0, 0, 0, 1, 1,
- };
- static const long min_volumes[] = {0, 0, 0, 0, 0, 0, 500, -1250};
- static const long max_volumes[] = {0, 0, 0, 0, 0, 0, 3000, 400};
- static const char* element_names[] = {
- "Master", "PCM", "Headphone", "Speaker",
- "HDMI", "IEC958", "Capture", "Digital Capture",
- };
- static const char* output_names_extra[] = {"IEC958"};
- static char* iniparser_returns[] = {
- NULL,
- };
- struct mixer_name* extra_controls = mixer_name_add_array(
- NULL, output_names_extra, ARRAY_SIZE(output_names_extra),
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
-
- ResetStubData();
- snd_mixer_first_elem_return_value =
- reinterpret_cast<snd_mixer_elem_t*>(1); // Main
- snd_mixer_elem_next_return_values = elements;
- snd_mixer_elem_next_return_values_length = ARRAY_SIZE(elements);
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values =
- element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_has_capture_volume_return_values = element_capture_volume;
- snd_mixer_selem_has_capture_volume_return_values_length =
- ARRAY_SIZE(element_capture_volume);
- snd_mixer_selem_has_capture_switch_return_values = element_capture_switches;
- snd_mixer_selem_has_capture_switch_return_values_length =
- ARRAY_SIZE(element_capture_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- snd_mixer_selem_get_capture_dB_range_called = 0;
- snd_mixer_selem_get_capture_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_capture_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_capture_dB_range_values_length =
- ARRAY_SIZE(min_volumes);
- iniparser_getstring_returns = iniparser_returns;
- iniparser_getstring_return_length = ARRAY_SIZE(iniparser_returns);
- cras_mixer_ = create_mixer_and_add_controls_by_name_matching(
- "hw:0", extra_controls, NULL);
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), cras_mixer_);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
- EXPECT_EQ(ARRAY_SIZE(elements) + 1, snd_mixer_elem_next_called);
- EXPECT_EQ(8, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(7, snd_mixer_selem_has_playback_switch_called);
- EXPECT_EQ(4, snd_mixer_selem_has_capture_volume_called);
- EXPECT_EQ(3, snd_mixer_selem_has_capture_switch_called);
- mixer_name_free(extra_controls);
- }
-
- virtual void TearDown() {
- cras_alsa_mixer_destroy(cras_mixer_);
- EXPECT_EQ(1, snd_mixer_close_called);
- }
-
- static void OutputCallback(struct mixer_control* out, void* arg) {
- output_callback_called_++;
- output_called_values_.push_back(out);
- }
-
- struct cras_alsa_mixer* cras_mixer_;
- static size_t output_callback_called_;
- static std::vector<struct mixer_control*> output_called_values_;
-};
-
-size_t AlsaMixerOutputs::output_callback_called_;
-std::vector<struct mixer_control*> AlsaMixerOutputs::output_called_values_;
-
-TEST_F(AlsaMixerOutputs, CheckFourOutputs) {
- cras_alsa_mixer_list_outputs(cras_mixer_, AlsaMixerOutputs::OutputCallback,
- reinterpret_cast<void*>(555));
- EXPECT_EQ(4, output_callback_called_);
-}
-
-TEST_F(AlsaMixerOutputs, CheckFindOutputByNameNoMatch) {
- struct mixer_control* out;
-
- out = cras_alsa_mixer_get_output_matching_name(cras_mixer_, "AAAAA Jack");
- EXPECT_EQ(static_cast<struct mixer_control*>(NULL), out);
-}
-
-TEST_F(AlsaMixerOutputs, CheckFindOutputByName) {
- struct mixer_control* out;
-
- out = cras_alsa_mixer_get_output_matching_name(cras_mixer_, "Headphone Jack");
- EXPECT_NE(static_cast<struct mixer_control*>(NULL), out);
-}
-
-TEST_F(AlsaMixerOutputs, CheckFindOutputHDMIByName) {
- struct mixer_control* out;
-
- out = cras_alsa_mixer_get_output_matching_name(cras_mixer_, "HDMI Jack");
- EXPECT_NE(static_cast<struct mixer_control*>(NULL), out);
-}
-
-TEST_F(AlsaMixerOutputs, CheckFindInputNameWorkaround) {
- struct mixer_control* control;
- snd_mixer_elem_t* elements[] = {
- reinterpret_cast<snd_mixer_elem_t*>(1), // Speaker
- reinterpret_cast<snd_mixer_elem_t*>(2), // Headphone
- reinterpret_cast<snd_mixer_elem_t*>(3), // MIC
- };
- const char* element_names[] = {
- "Speaker",
- "Headphone",
- "MIC",
- };
- size_t i;
-
- ResetStubData();
- for (i = 0; i < ARRAY_SIZE(elements); i++)
- snd_mixer_find_elem_map[element_names[i]] = elements[i];
-
- snd_mixer_selem_get_name_called = 0;
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- control = cras_alsa_mixer_get_input_matching_name(cras_mixer_, "MIC");
- EXPECT_NE(static_cast<struct mixer_control*>(NULL), control);
- /* This exercises the 'workaround' where the control is added if it was
- * previouly missing in cras_alsa_mixer_get_input_matching_name().
- * snd_mixer_find_selem is called once for the missing control. */
- EXPECT_EQ(1, snd_mixer_find_selem_called);
- EXPECT_EQ(1, snd_mixer_selem_has_capture_volume_called);
- EXPECT_EQ(1, snd_mixer_selem_has_capture_switch_called);
-}
-
-TEST_F(AlsaMixerOutputs, ActivateDeactivate) {
- int rc;
-
- cras_alsa_mixer_list_outputs(cras_mixer_, AlsaMixerOutputs::OutputCallback,
- reinterpret_cast<void*>(555));
- EXPECT_EQ(4, output_callback_called_);
- EXPECT_EQ(4, output_called_values_.size());
-
- rc = cras_alsa_mixer_set_output_active_state(output_called_values_[0], 0);
- ASSERT_EQ(0, rc);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_switch_all_called);
- cras_alsa_mixer_set_output_active_state(output_called_values_[0], 1);
- EXPECT_EQ(2, snd_mixer_selem_set_playback_switch_all_called);
-}
-
-TEST_F(AlsaMixerOutputs, MinMaxCaptureGain) {
- long min, max;
- min = cras_alsa_mixer_get_minimum_capture_gain(cras_mixer_, NULL);
- EXPECT_EQ(-750, min);
- max = cras_alsa_mixer_get_maximum_capture_gain(cras_mixer_, NULL);
- EXPECT_EQ(3400, max);
-}
-
-TEST_F(AlsaMixerOutputs, MinMaxCaptureGainWithActiveInput) {
- struct mixer_control* mixer_input;
- long min, max;
-
- mixer_input = (struct mixer_control*)calloc(1, sizeof(*mixer_input));
- mixer_input->min_volume_dB = 50;
- mixer_input->max_volume_dB = 60;
- mixer_input->has_volume = 1;
- min = cras_alsa_mixer_get_minimum_capture_gain(cras_mixer_, mixer_input);
- max = cras_alsa_mixer_get_maximum_capture_gain(cras_mixer_, mixer_input);
- EXPECT_EQ(-700, min);
- EXPECT_EQ(3460, max);
-
- free((void*)mixer_input);
-}
-
-TEST(AlsaMixer, CreateWithCoupledOutputControls) {
- struct cras_alsa_mixer* c;
- struct mixer_control* output_control;
- struct mixer_control_element *c1, *c2, *c3, *c4;
-
- static const long min_volumes[] = {-70, -70};
- static const long max_volumes[] = {30, 30};
-
- long set_dB_values[2];
-
- const char* coupled_output_names[] = {"Left Master", "Right Master",
- "Left Speaker", "Right Speaker"};
- struct mixer_name* coupled_controls = mixer_name_add_array(
- NULL, coupled_output_names, ARRAY_SIZE(coupled_output_names),
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- int element_playback_volume[] = {1, 1, 0, 0};
- int element_playback_switches[] = {0, 0, 1, 1};
-
- long target_dBFS = -30;
- long expected_dB_value = target_dBFS + max_volumes[0];
-
- ResetStubData();
-
- snd_mixer_find_elem_map[std::string("Left Master")] =
- reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_find_elem_map[std::string("Right Master")] =
- reinterpret_cast<snd_mixer_elem_t*>(2);
- snd_mixer_find_elem_map[std::string("Left Speaker")] =
- reinterpret_cast<snd_mixer_elem_t*>(3);
- snd_mixer_find_elem_map[std::string("Right Speaker")] =
- reinterpret_cast<snd_mixer_elem_t*>(4);
-
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
-
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
-
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL,
- coupled_controls);
-
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
-
- output_control = c->output_controls;
- EXPECT_EQ(NULL, output_control->next);
- c1 = output_control->elements;
- c2 = c1->next;
- c3 = c2->next;
- c4 = c3->next;
- EXPECT_EQ(c1->elem, reinterpret_cast<snd_mixer_elem_t*>(1));
- EXPECT_EQ(c2->elem, reinterpret_cast<snd_mixer_elem_t*>(2));
- EXPECT_EQ(c3->elem, reinterpret_cast<snd_mixer_elem_t*>(3));
- EXPECT_EQ(c4->elem, reinterpret_cast<snd_mixer_elem_t*>(4));
- EXPECT_EQ(c4->next, reinterpret_cast<mixer_control_element*>(NULL));
- EXPECT_EQ(c1->has_volume, 1);
- EXPECT_EQ(c1->has_mute, 0);
- EXPECT_EQ(c2->has_volume, 1);
- EXPECT_EQ(c2->has_mute, 0);
- EXPECT_EQ(c3->has_volume, 0);
- EXPECT_EQ(c3->has_mute, 1);
- EXPECT_EQ(c4->has_volume, 0);
- EXPECT_EQ(c4->has_mute, 1);
- EXPECT_EQ(output_control->max_volume_dB, max_volumes[0]);
- EXPECT_EQ(output_control->min_volume_dB, min_volumes[0]);
-
- snd_mixer_selem_set_playback_dB_all_values = set_dB_values;
- snd_mixer_selem_set_playback_dB_all_values_length = ARRAY_SIZE(set_dB_values);
-
- cras_alsa_mixer_set_dBFS(c, target_dBFS, output_control);
-
- /* Set volume should set playback dB on two of the coupled controls. */
- EXPECT_EQ(2, snd_mixer_selem_set_playback_dB_all_called);
- EXPECT_EQ(set_dB_values[0], expected_dB_value);
- EXPECT_EQ(set_dB_values[1], expected_dB_value);
-
- /* Mute should set playback switch on two of the coupled controls. */
- cras_alsa_mixer_set_mute(c, 1, output_control);
- EXPECT_EQ(2, snd_mixer_selem_set_playback_switch_all_called);
- EXPECT_EQ(0, snd_mixer_selem_set_playback_switch_all_value);
-
- /* Unmute should set playback switch on two of the coupled controls. */
- cras_alsa_mixer_set_mute(c, 0, output_control);
- EXPECT_EQ(4, snd_mixer_selem_set_playback_switch_all_called);
- EXPECT_EQ(1, snd_mixer_selem_set_playback_switch_all_value);
-
- EXPECT_EQ(max_volumes[0] - min_volumes[0],
- cras_alsa_mixer_get_output_dB_range(output_control));
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_name_free(coupled_controls);
-}
-
-TEST(AlsaMixer, CoupledOutputHasMuteNoVolume) {
- struct cras_alsa_mixer* c;
- struct mixer_control* output_control;
- struct mixer_control_element *c1, *c2, *c3, *c4;
-
- static const long min_volumes[] = {-70};
- static const long max_volumes[] = {30};
-
- const char* coupled_output_names[] = {"Left Master", "Right Master",
- "Left Speaker", "Right Speaker"};
- struct mixer_name* coupled_controls = mixer_name_add_array(
- NULL, coupled_output_names, ARRAY_SIZE(coupled_output_names),
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- int element_playback_volume[] = {0, 0, 0, 0};
- int element_playback_switches[] = {0, 0, 1, 1};
-
- ResetStubData();
-
- snd_mixer_find_elem_map[std::string("Left Master")] =
- reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_find_elem_map[std::string("Right Master")] =
- reinterpret_cast<snd_mixer_elem_t*>(2);
- snd_mixer_find_elem_map[std::string("Left Speaker")] =
- reinterpret_cast<snd_mixer_elem_t*>(3);
- snd_mixer_find_elem_map[std::string("Right Speaker")] =
- reinterpret_cast<snd_mixer_elem_t*>(4);
-
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
-
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
-
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL,
- coupled_controls);
-
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
-
- output_control = c->output_controls;
- EXPECT_EQ(NULL, output_control->next);
- c1 = output_control->elements;
- c2 = c1->next;
- c3 = c2->next;
- c4 = c3->next;
- EXPECT_EQ(c1->elem, reinterpret_cast<snd_mixer_elem_t*>(1));
- EXPECT_EQ(c2->elem, reinterpret_cast<snd_mixer_elem_t*>(2));
- EXPECT_EQ(c3->elem, reinterpret_cast<snd_mixer_elem_t*>(3));
- EXPECT_EQ(c4->elem, reinterpret_cast<snd_mixer_elem_t*>(4));
- EXPECT_EQ(c4->next, reinterpret_cast<mixer_control_element*>(NULL));
- EXPECT_EQ(c1->has_volume, 0);
- EXPECT_EQ(c1->has_mute, 0);
- EXPECT_EQ(c2->has_volume, 0);
- EXPECT_EQ(c2->has_mute, 0);
- EXPECT_EQ(c3->has_volume, 0);
- EXPECT_EQ(c3->has_mute, 1);
- EXPECT_EQ(c4->has_volume, 0);
- EXPECT_EQ(c4->has_mute, 1);
-
- EXPECT_EQ(0, cras_alsa_mixer_has_volume(output_control));
- EXPECT_EQ(1, output_control->has_mute);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_name_free(coupled_controls);
-}
-
-TEST(AlsaMixer, CoupledOutputHasVolumeNoMute) {
- struct cras_alsa_mixer* c;
- struct mixer_control* output_control;
- struct mixer_control_element *c1, *c2, *c3, *c4;
-
- static const long min_volumes[] = {-70, -70};
- static const long max_volumes[] = {30, 30};
-
- const char* coupled_output_names[] = {"Left Master", "Right Master",
- "Left Speaker", "Right Speaker"};
- struct mixer_name* coupled_controls = mixer_name_add_array(
- NULL, coupled_output_names, ARRAY_SIZE(coupled_output_names),
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- int element_playback_volume[] = {1, 1, 0, 0};
- int element_playback_switches[] = {0, 0, 0, 0};
-
- ResetStubData();
-
- snd_mixer_find_elem_map[std::string("Left Master")] =
- reinterpret_cast<snd_mixer_elem_t*>(1);
- snd_mixer_find_elem_map[std::string("Right Master")] =
- reinterpret_cast<snd_mixer_elem_t*>(2);
- snd_mixer_find_elem_map[std::string("Left Speaker")] =
- reinterpret_cast<snd_mixer_elem_t*>(3);
- snd_mixer_find_elem_map[std::string("Right Speaker")] =
- reinterpret_cast<snd_mixer_elem_t*>(4);
-
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values = element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
-
- snd_mixer_selem_get_playback_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_playback_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_playback_dB_range_values_length = ARRAY_SIZE(min_volumes);
-
- c = create_mixer_and_add_controls_by_name_matching("hw:0", NULL,
- coupled_controls);
-
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), c);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
-
- output_control = c->output_controls;
- EXPECT_EQ(NULL, output_control->next);
- c1 = output_control->elements;
- c2 = c1->next;
- c3 = c2->next;
- c4 = c3->next;
- EXPECT_EQ(c1->elem, reinterpret_cast<snd_mixer_elem_t*>(1));
- EXPECT_EQ(c2->elem, reinterpret_cast<snd_mixer_elem_t*>(2));
- EXPECT_EQ(c3->elem, reinterpret_cast<snd_mixer_elem_t*>(3));
- EXPECT_EQ(c4->elem, reinterpret_cast<snd_mixer_elem_t*>(4));
- EXPECT_EQ(c4->next, reinterpret_cast<mixer_control_element*>(NULL));
- EXPECT_EQ(c1->has_volume, 1);
- EXPECT_EQ(c1->has_mute, 0);
- EXPECT_EQ(c2->has_volume, 1);
- EXPECT_EQ(c2->has_mute, 0);
- EXPECT_EQ(c3->has_volume, 0);
- EXPECT_EQ(c3->has_mute, 0);
- EXPECT_EQ(c4->has_volume, 0);
- EXPECT_EQ(c4->has_mute, 0);
-
- EXPECT_EQ(1, cras_alsa_mixer_has_volume(output_control));
- EXPECT_EQ(0, output_control->has_mute);
-
- cras_alsa_mixer_destroy(c);
- EXPECT_EQ(1, snd_mixer_close_called);
- mixer_name_free(coupled_controls);
-}
-
-TEST(AlsaMixer, MixerName) {
- struct mixer_name* names;
- struct mixer_name* control;
- size_t mixer_name_count;
- static const char* element_names[] = {
- "Master", "PCM", "Headphone", "Speaker", "HDMI", "IEC958",
- };
-
- names = mixer_name_add_array(NULL, element_names, ARRAY_SIZE(element_names),
- CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- names =
- mixer_name_add(names, "Playback", CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- names =
- mixer_name_add(names, "Main", CRAS_STREAM_OUTPUT, MIXER_NAME_MAIN_VOLUME);
- names = mixer_name_add(names, "Mic", CRAS_STREAM_INPUT, MIXER_NAME_VOLUME);
- names = mixer_name_add(names, "Capture", CRAS_STREAM_INPUT,
- MIXER_NAME_MAIN_VOLUME);
-
- /* Number of items (test mixer_name_add(_array)). */
- mixer_name_count = 0;
- DL_FOREACH (names, control) { mixer_name_count++; }
- EXPECT_EQ(10, mixer_name_count);
-
- /* Item not in the list: mismatch direction. */
- control =
- mixer_name_find(names, "Main", CRAS_STREAM_INPUT, MIXER_NAME_UNDEFINED);
- EXPECT_EQ(1, control == NULL);
-
- /* Item not in the list: mismatch type. */
- control =
- mixer_name_find(names, "Main", CRAS_STREAM_OUTPUT, MIXER_NAME_VOLUME);
- EXPECT_EQ(1, control == NULL);
-
- /* Find by name and direction. */
- control =
- mixer_name_find(names, "Main", CRAS_STREAM_OUTPUT, MIXER_NAME_UNDEFINED);
- EXPECT_EQ(0, strcmp("Main", control->name));
-
- /* Find by type and direction. */
- control = mixer_name_find(names, NULL, CRAS_STREAM_INPUT, MIXER_NAME_VOLUME);
- EXPECT_EQ(0, strcmp("Mic", control->name));
-
- mixer_name_free(names);
-}
-
-class AlsaMixerFullySpeced : public testing::Test {
- protected:
- virtual void SetUp() {
- callback_values_.clear();
- callback_called_ = 0;
- static snd_mixer_elem_t* elements[] = {
- reinterpret_cast<snd_mixer_elem_t*>(1), // HP-L
- reinterpret_cast<snd_mixer_elem_t*>(2), // HP-R
- reinterpret_cast<snd_mixer_elem_t*>(3), // SPK-L
- reinterpret_cast<snd_mixer_elem_t*>(4), // SPK-R
- reinterpret_cast<snd_mixer_elem_t*>(5), // HDMI
- reinterpret_cast<snd_mixer_elem_t*>(6), // CAPTURE
- reinterpret_cast<snd_mixer_elem_t*>(7), // MIC-L
- reinterpret_cast<snd_mixer_elem_t*>(8), // MIC-R
- reinterpret_cast<snd_mixer_elem_t*>(0), // Unknown
- };
- static int element_playback_volume[] = {
- 1, 1, 1, 1, 1, 0, 0, 0,
- };
- static int element_playback_switches[] = {
- 0, 0, 0, 0, 1, 0, 0, 0,
- };
- static int element_capture_volume[] = {
- 0, 0, 0, 0, 0, 0, 1, 1,
- };
- static int element_capture_switches[] = {
- 0, 0, 0, 0, 0, 1, 0, 0,
- };
- static const long min_volumes[] = {-84, -84, -84, -84, -84, 0, 0, 0};
- static const long max_volumes[] = {0, 0, 0, 0, 0, 0, 84, 84};
- static const char* element_names[] = {"HP-L", "HP-R", "SPK-L",
- "SPK-R", "HDMI", "CAPTURE",
- "MIC-L", "MIC-R", "Unknown"};
- struct ucm_section* sections = NULL;
- struct ucm_section* section;
- size_t i;
-
- ResetStubData();
-
- for (i = 0; i < ARRAY_SIZE(elements); i++)
- snd_mixer_find_elem_map[element_names[i]] = elements[i];
-
- section = ucm_section_create("NullElement", "hw:0,1", 0, -1,
- CRAS_STREAM_OUTPUT, NULL, NULL);
- ucm_section_set_mixer_name(section, "Unknown");
- DL_APPEND(sections, section);
- section =
- ucm_section_create("Headphone", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- "my-sound-card Headset Jack", "gpio");
- ucm_section_add_coupled(section, "HP-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "HP-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
- section = ucm_section_create("Speaker", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- NULL, NULL);
- ucm_section_add_coupled(section, "SPK-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "SPK-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
- section = ucm_section_create("Mic", "hw:0,1", 0, -1, CRAS_STREAM_INPUT,
- "my-sound-card Headset Jack", "gpio");
- ucm_section_set_mixer_name(section, "CAPTURE");
- DL_APPEND(sections, section);
- section = ucm_section_create("Internal Mic", "hw:0,1", 0, -1,
- CRAS_STREAM_INPUT, NULL, NULL);
- ucm_section_add_coupled(section, "MIC-L", MIXER_NAME_VOLUME);
- ucm_section_add_coupled(section, "MIC-R", MIXER_NAME_VOLUME);
- DL_APPEND(sections, section);
- section = ucm_section_create("HDMI", "hw:0,1", 0, -1, CRAS_STREAM_OUTPUT,
- NULL, NULL);
- ucm_section_set_mixer_name(section, "HDMI");
- DL_APPEND(sections, section);
- ASSERT_NE(sections, (struct ucm_section*)NULL);
-
- snd_mixer_selem_has_playback_volume_return_values = element_playback_volume;
- snd_mixer_selem_has_playback_volume_return_values_length =
- ARRAY_SIZE(element_playback_volume);
- snd_mixer_selem_has_playback_switch_return_values =
- element_playback_switches;
- snd_mixer_selem_has_playback_switch_return_values_length =
- ARRAY_SIZE(element_playback_switches);
- snd_mixer_selem_has_capture_volume_return_values = element_capture_volume;
- snd_mixer_selem_has_capture_volume_return_values_length =
- ARRAY_SIZE(element_capture_volume);
- snd_mixer_selem_has_capture_switch_return_values = element_capture_switches;
- snd_mixer_selem_has_capture_switch_return_values_length =
- ARRAY_SIZE(element_capture_switches);
- snd_mixer_selem_get_name_return_values = element_names;
- snd_mixer_selem_get_name_return_values_length = ARRAY_SIZE(element_names);
- snd_mixer_selem_get_capture_dB_range_min_values = min_volumes;
- snd_mixer_selem_get_capture_dB_range_max_values = max_volumes;
- snd_mixer_selem_get_capture_dB_range_values_length =
- ARRAY_SIZE(min_volumes);
-
- cras_mixer_ = cras_alsa_mixer_create("hw:0");
- ASSERT_NE(static_cast<struct cras_alsa_mixer*>(NULL), cras_mixer_);
- EXPECT_EQ(1, snd_mixer_open_called);
- EXPECT_EQ(1, snd_mixer_attach_called);
- EXPECT_EQ(0, strcmp(snd_mixer_attach_mixdev, "hw:0"));
- EXPECT_EQ(1, snd_mixer_selem_register_called);
- EXPECT_EQ(1, snd_mixer_load_called);
- EXPECT_EQ(0, snd_mixer_close_called);
-
- section = sections;
- EXPECT_EQ(-ENOENT,
- cras_alsa_mixer_add_controls_in_section(cras_mixer_, section));
- ASSERT_NE((struct ucm_section*)NULL, section->next);
- section = section->next;
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section(cras_mixer_, section));
- ASSERT_NE((struct ucm_section*)NULL, section->next);
- section = section->next;
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section(cras_mixer_, section));
- ASSERT_NE((struct ucm_section*)NULL, section->next);
- section = section->next;
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section(cras_mixer_, section));
- ASSERT_NE((struct ucm_section*)NULL, section->next);
- section = section->next;
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section(cras_mixer_, section));
- ASSERT_NE((struct ucm_section*)NULL, section->next);
- section = section->next;
- EXPECT_EQ(0, cras_alsa_mixer_add_controls_in_section(cras_mixer_, section));
- EXPECT_EQ(section->next, (struct ucm_section*)NULL);
-
- EXPECT_EQ(9, snd_mixer_find_selem_called);
- EXPECT_EQ(5, snd_mixer_selem_has_playback_volume_called);
- EXPECT_EQ(5, snd_mixer_selem_has_playback_switch_called);
- EXPECT_EQ(3, snd_mixer_selem_has_capture_volume_called);
- EXPECT_EQ(3, snd_mixer_selem_has_capture_switch_called);
- EXPECT_EQ(5, snd_mixer_selem_get_playback_dB_range_called);
- EXPECT_EQ(2, snd_mixer_selem_get_capture_dB_range_called);
-
- sections_ = sections;
- }
-
- virtual void TearDown() {
- ucm_section_free_list(sections_);
- cras_alsa_mixer_destroy(cras_mixer_);
- EXPECT_EQ(1, snd_mixer_close_called);
- }
-
- static void Callback(struct mixer_control* control, void* arg) {
- callback_called_++;
- callback_values_.push_back(control);
- }
-
- struct cras_alsa_mixer* cras_mixer_;
- static size_t callback_called_;
- static std::vector<struct mixer_control*> callback_values_;
- struct ucm_section* sections_;
-};
-
-size_t AlsaMixerFullySpeced::callback_called_;
-std::vector<struct mixer_control*> AlsaMixerFullySpeced::callback_values_;
-
-TEST_F(AlsaMixerFullySpeced, CheckControlCounts) {
- cras_alsa_mixer_list_outputs(cras_mixer_, AlsaMixerFullySpeced::Callback,
- reinterpret_cast<void*>(555));
- EXPECT_EQ(3, callback_called_);
- callback_called_ = 0;
- cras_alsa_mixer_list_inputs(cras_mixer_, AlsaMixerFullySpeced::Callback,
- reinterpret_cast<void*>(555));
- EXPECT_EQ(2, callback_called_);
-}
-
-TEST_F(AlsaMixerFullySpeced, CheckFindOutputByNameNoMatch) {
- struct mixer_control* out;
-
- out = cras_alsa_mixer_get_output_matching_name(cras_mixer_, "AAAAA Jack");
- EXPECT_EQ(static_cast<struct mixer_control*>(NULL), out);
-}
-
-TEST_F(AlsaMixerFullySpeced, CheckFindOutputByName) {
- struct mixer_control* out;
-
- out = cras_alsa_mixer_get_output_matching_name(cras_mixer_, "Headphone Jack");
- EXPECT_NE(static_cast<struct mixer_control*>(NULL), out);
-}
-
-TEST_F(AlsaMixerFullySpeced, CheckFindControlForSection) {
- struct mixer_control* control;
- struct ucm_section* section = sections_;
-
- // Look for the control for the Headphone section.
- // We've already asserted that section != NULL above.
- // Matching the control created by CoupledMixers.
- section = section->next;
- control = cras_alsa_mixer_get_control_for_section(cras_mixer_, section);
- ASSERT_NE(static_cast<struct mixer_control*>(NULL), control);
- EXPECT_EQ(0, strcmp(control->name, "Headphone"));
-
- // Look for the control for the Mic section.
- // Matching the control created by MixerName.
- section = section->next->next;
- control = cras_alsa_mixer_get_control_for_section(cras_mixer_, section);
- ASSERT_NE(static_cast<struct mixer_control*>(NULL), control);
- EXPECT_EQ(0, strcmp(control->name, "CAPTURE"));
-}
-
-/* Stubs */
-
-extern "C" {
-int snd_mixer_open(snd_mixer_t** mixer, int mode) {
- snd_mixer_open_called++;
- *mixer = reinterpret_cast<snd_mixer_t*>(2);
- return snd_mixer_open_return_value;
-}
-int snd_mixer_attach(snd_mixer_t* mixer, const char* name) {
- snd_mixer_attach_called++;
- snd_mixer_attach_mixdev = name;
- return snd_mixer_attach_return_value;
-}
-int snd_mixer_selem_register(snd_mixer_t* mixer,
- struct snd_mixer_selem_regopt* options,
- snd_mixer_class_t** classp) {
- snd_mixer_selem_register_called++;
- return snd_mixer_selem_register_return_value;
-}
-int snd_mixer_load(snd_mixer_t* mixer) {
- snd_mixer_load_called++;
- return snd_mixer_load_return_value;
-}
-const char* snd_mixer_selem_get_name(snd_mixer_elem_t* elem) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_get_name_called++;
- if (index >= snd_mixer_selem_get_name_return_values_length)
- return static_cast<char*>(NULL);
-
- return snd_mixer_selem_get_name_return_values[index];
-}
-unsigned int snd_mixer_selem_get_index(snd_mixer_elem_t* elem) {
- return 0;
-}
-int snd_mixer_selem_has_playback_volume(snd_mixer_elem_t* elem) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_has_playback_volume_called++;
- if (index >= snd_mixer_selem_has_playback_volume_return_values_length)
- return -1;
-
- return snd_mixer_selem_has_playback_volume_return_values[index];
-}
-int snd_mixer_selem_has_playback_switch(snd_mixer_elem_t* elem) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_has_playback_switch_called++;
- if (index >= snd_mixer_selem_has_playback_switch_return_values_length)
- return -1;
-
- return snd_mixer_selem_has_playback_switch_return_values[index];
-}
-int snd_mixer_selem_has_capture_volume(snd_mixer_elem_t* elem) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_has_capture_volume_called++;
- if (index >= snd_mixer_selem_has_capture_volume_return_values_length)
- return -1;
-
- return snd_mixer_selem_has_capture_volume_return_values[index];
-}
-int snd_mixer_selem_has_capture_switch(snd_mixer_elem_t* elem) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_has_capture_switch_called++;
- if (index >= snd_mixer_selem_has_capture_switch_return_values_length)
- return -1;
-
- return snd_mixer_selem_has_capture_switch_return_values[index];
-}
-snd_mixer_elem_t* snd_mixer_first_elem(snd_mixer_t* mixer) {
- snd_mixer_first_elem_called++;
- return snd_mixer_first_elem_return_value;
-}
-snd_mixer_elem_t* snd_mixer_elem_next(snd_mixer_elem_t* elem) {
- snd_mixer_elem_next_called++;
- if (snd_mixer_elem_next_return_values_index >=
- snd_mixer_elem_next_return_values_length)
- return static_cast<snd_mixer_elem_t*>(NULL);
-
- return snd_mixer_elem_next_return_values
- [snd_mixer_elem_next_return_values_index++];
-}
-int snd_mixer_close(snd_mixer_t* mixer) {
- snd_mixer_close_called++;
- return 0;
-}
-int snd_mixer_selem_set_playback_dB_all(snd_mixer_elem_t* elem,
- long value,
- int dir) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_set_playback_dB_all_called++;
- if (index < snd_mixer_selem_set_playback_dB_all_values_length)
- snd_mixer_selem_set_playback_dB_all_values[index] = value;
- return 0;
-}
-int snd_mixer_selem_get_playback_dB(snd_mixer_elem_t* elem,
- snd_mixer_selem_channel_id_t channel,
- long* value) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_get_playback_dB_called++;
- if (index >= snd_mixer_selem_get_playback_dB_return_values_length)
- *value = 0;
- else
- *value = snd_mixer_selem_get_playback_dB_return_values[index];
- return 0;
-}
-int snd_mixer_selem_set_playback_switch_all(snd_mixer_elem_t* elem, int value) {
- snd_mixer_selem_set_playback_switch_all_called++;
- snd_mixer_selem_set_playback_switch_all_value = value;
- return 0;
-}
-int snd_mixer_selem_set_capture_dB_all(snd_mixer_elem_t* elem,
- long value,
- int dir) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_set_capture_dB_all_called++;
- if (index < snd_mixer_selem_set_capture_dB_all_values_length)
- snd_mixer_selem_set_capture_dB_all_values[index] = value;
- return 0;
-}
-int snd_mixer_selem_get_capture_dB(snd_mixer_elem_t* elem,
- snd_mixer_selem_channel_id_t channel,
- long* value) {
- int index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_get_capture_dB_called++;
- if (index >= snd_mixer_selem_get_capture_dB_return_values_length)
- *value = 0;
- else
- *value = snd_mixer_selem_get_capture_dB_return_values[index];
- return 0;
-}
-int snd_mixer_selem_set_capture_switch_all(snd_mixer_elem_t* elem, int value) {
- snd_mixer_selem_set_capture_switch_all_called++;
- snd_mixer_selem_set_capture_switch_all_value = value;
- return 0;
-}
-int snd_mixer_selem_get_capture_dB_range(snd_mixer_elem_t* elem,
- long* min,
- long* max) {
- size_t index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_get_capture_dB_range_called++;
- if (index >= snd_mixer_selem_get_capture_dB_range_values_length) {
- *min = 0;
- *max = 0;
- } else {
- *min = snd_mixer_selem_get_capture_dB_range_min_values[index];
- *max = snd_mixer_selem_get_capture_dB_range_max_values[index];
- }
- return 0;
-}
-int snd_mixer_selem_get_playback_dB_range(snd_mixer_elem_t* elem,
- long* min,
- long* max) {
- size_t index = reinterpret_cast<size_t>(elem) - 1;
- snd_mixer_selem_get_playback_dB_range_called++;
- if (index >= snd_mixer_selem_get_playback_dB_range_values_length) {
- *min = 0;
- *max = 0;
- } else {
- *min = snd_mixer_selem_get_playback_dB_range_min_values[index];
- *max = snd_mixer_selem_get_playback_dB_range_max_values[index];
- }
- return 0;
-}
-
-snd_mixer_elem_t* snd_mixer_find_selem(snd_mixer_t* mixer,
- const snd_mixer_selem_id_t* id) {
- std::string name(snd_mixer_selem_id_get_name(id));
- unsigned int index = snd_mixer_selem_id_get_index(id);
- snd_mixer_find_selem_called++;
- if (index != 0)
- return NULL;
- if (snd_mixer_find_elem_map.find(name) == snd_mixer_find_elem_map.end()) {
- return NULL;
- }
- return snd_mixer_find_elem_map[name];
-}
-
-// From cras_volume_curve.
-static long get_dBFS_default(const struct cras_volume_curve* curve,
- size_t volume) {
- return 100 * (volume - 100);
-}
-
-struct cras_volume_curve* cras_volume_curve_create_default() {
- struct cras_volume_curve* curve;
- curve = (struct cras_volume_curve*)calloc(1, sizeof(*curve));
- if (curve)
- curve->get_dBFS = get_dBFS_default;
- return curve;
-}
-
-void cras_volume_curve_destroy(struct cras_volume_curve* curve) {
- cras_volume_curve_destroy_called++;
- free(curve);
-}
-
-// From libiniparser.
-struct cras_volume_curve* cras_card_config_get_volume_curve_for_control(
- const struct cras_card_config* card_config,
- const char* control_name) {
- struct cras_volume_curve* curve;
- curve = (struct cras_volume_curve*)calloc(1, sizeof(*curve));
- if (curve != NULL)
- curve->get_dBFS = get_dBFS_default;
- return curve;
-}
-
-} /* extern "C" */
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/alsa_ucm_unittest.cc b/cras/src/tests/alsa_ucm_unittest.cc
deleted file mode 100644
index 1b351ddf..00000000
--- a/cras/src/tests/alsa_ucm_unittest.cc
+++ /dev/null
@@ -1,1564 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <syslog.h>
-
-#include <map>
-
-extern "C" {
-#include "cras_alsa_ucm.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "utlist.h"
-
-// Include C file to test static functions.
-#include "cras_alsa_ucm.c"
-}
-
-namespace {
-
-static int snd_use_case_mgr_open_return;
-static snd_use_case_mgr_t* snd_use_case_mgr_open_mgr_ptr;
-static unsigned snd_use_case_mgr_open_called;
-static unsigned snd_use_case_mgr_close_called;
-static unsigned snd_use_case_get_called;
-static std::vector<std::string> snd_use_case_get_id;
-static int snd_use_case_set_return;
-static std::map<std::string, std::string> snd_use_case_get_value;
-static std::map<std::string, unsigned> snd_use_case_geti_value;
-static unsigned snd_use_case_set_called;
-static std::vector<std::pair<std::string, std::string> > snd_use_case_set_param;
-static std::map<std::string, const char**> fake_list;
-static std::map<std::string, unsigned> fake_list_size;
-static unsigned snd_use_case_free_list_called;
-static unsigned snd_use_case_geti_called;
-static std::vector<std::string> list_devices_callback_names;
-static std::vector<void*> list_devices_callback_args;
-static struct cras_use_case_mgr cras_ucm_mgr;
-static const char* avail_verbs[] = {"HiFi", "Comment for Verb1"};
-
-static void ResetStubData() {
- snd_use_case_mgr_open_called = 0;
- snd_use_case_mgr_open_return = 0;
- snd_use_case_mgr_close_called = 0;
- snd_use_case_set_return = 0;
- snd_use_case_get_called = 0;
- snd_use_case_set_called = 0;
- snd_use_case_geti_called = 0;
- snd_use_case_set_param.clear();
- snd_use_case_free_list_called = 0;
- snd_use_case_get_id.clear();
- snd_use_case_get_value.clear();
- snd_use_case_geti_value.clear();
- fake_list.clear();
- fake_list_size.clear();
- fake_list["_verbs"] = avail_verbs;
- fake_list_size["_verbs"] = 2;
- list_devices_callback_names.clear();
- list_devices_callback_args.clear();
- snd_use_case_mgr_open_mgr_ptr = reinterpret_cast<snd_use_case_mgr_t*>(0x55);
- cras_ucm_mgr.use_case = CRAS_STREAM_TYPE_DEFAULT;
- cras_ucm_mgr.hotword_modifier = NULL;
-}
-
-static void list_devices_callback(const char* section_name, void* arg) {
- list_devices_callback_names.push_back(std::string(section_name));
- list_devices_callback_args.push_back(arg);
-}
-
-static void SetSectionDeviceData() {
- static const char* sections[] = {
- "Speaker", "Comment for Dev1", "IntMic", "Comment for Dev2",
- "Headphone", "Comment for Dev3", "ExtMic", "Comment for Dev4",
- "HDMI", "Comment for Dev5"};
- fake_list["_devices/HiFi"] = sections;
- fake_list_size["_devices/HiFi"] = 10;
- std::string id_1 = "=PlaybackPCM/Speaker/HiFi";
- std::string id_2 = "=CapturePCM/IntMic/HiFi";
- std::string id_3 = "=PlaybackPCM/Headphone/HiFi";
- std::string id_4 = "=CapturePCM/ExtMic/HiFi";
- std::string id_5 = "=PlaybackPCM/HDMI/HiFi";
- std::string value_1 = "test_card:0";
- std::string value_2 = "test_card:0";
- std::string value_3 = "test_card:0";
- std::string value_4 = "test_card:0";
- std::string value_5 = "test_card:1";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- snd_use_case_get_value[id_3] = value_3;
- snd_use_case_get_value[id_4] = value_4;
- snd_use_case_get_value[id_5] = value_5;
-}
-
-TEST(AlsaUcm, CreateFailInvalidCard) {
- ResetStubData();
- EXPECT_EQ(NULL, ucm_create(NULL));
- EXPECT_EQ(0, snd_use_case_mgr_open_called);
-}
-
-TEST(AlsaUcm, CreateFailCardNotFound) {
- ResetStubData();
- snd_use_case_mgr_open_return = -1;
- EXPECT_EQ(NULL, ucm_create("foo"));
- EXPECT_EQ(1, snd_use_case_mgr_open_called);
-}
-
-TEST(AlsaUcm, CreateFailNoHiFi) {
- ResetStubData();
- snd_use_case_set_return = -1;
- EXPECT_EQ(NULL, ucm_create("foo"));
- EXPECT_EQ(1, snd_use_case_mgr_open_called);
- EXPECT_EQ(1, snd_use_case_set_called);
- EXPECT_EQ(1, snd_use_case_mgr_close_called);
-}
-
-TEST(AlsaUcm, CreateSuccess) {
- struct cras_use_case_mgr* mgr;
-
- ResetStubData();
-
- mgr = ucm_create("foo");
- EXPECT_NE(static_cast<snd_use_case_mgr_t*>(NULL), mgr->mgr);
- EXPECT_EQ(1, snd_use_case_mgr_open_called);
- EXPECT_EQ(1, snd_use_case_set_called);
- EXPECT_EQ(0, snd_use_case_mgr_close_called);
-
- ucm_destroy(mgr);
- EXPECT_EQ(1, snd_use_case_mgr_close_called);
-}
-
-TEST(AlsaUcm, CheckEnabledEmptyList) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
-
- ResetStubData();
- fake_list["_enadevs"] = NULL;
- fake_list_size["_enadevs"] = 0;
-
- EXPECT_EQ(0, ucm_set_enabled(mgr, "Dev1", 0));
- EXPECT_EQ(0, snd_use_case_set_called);
-
- EXPECT_EQ(0, ucm_set_enabled(mgr, "Dev1", 1));
- EXPECT_EQ(1, snd_use_case_set_called);
-
- EXPECT_EQ(0, snd_use_case_free_list_called);
-}
-
-TEST(AlsaUcm, CheckEnabledAlready) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* enabled[] = {"Dev2", "Dev1"};
-
- ResetStubData();
-
- fake_list["_enadevs"] = enabled;
- fake_list_size["_enadevs"] = 2;
-
- EXPECT_EQ(0, ucm_set_enabled(mgr, "Dev1", 1));
- EXPECT_EQ(0, snd_use_case_set_called);
-
- EXPECT_EQ(0, ucm_set_enabled(mgr, "Dev1", 0));
- EXPECT_EQ(1, snd_use_case_set_called);
-
- EXPECT_EQ(2, snd_use_case_free_list_called);
-}
-
-TEST(AlsaUcm, GetEdidForDev) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- std::string id = "=EDIDFile/Dev1/HiFi";
- std::string value = "EdidFileName";
- const char* file_name;
-
- ResetStubData();
-
- snd_use_case_get_value[id] = value;
-
- file_name = ucm_get_edid_file_for_dev(mgr, "Dev1");
- ASSERT_TRUE(file_name);
- EXPECT_EQ(0, strcmp(file_name, value.c_str()));
- free((void*)file_name);
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id);
-}
-
-TEST(AlsaUcm, GetCapControlForDev) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- char* cap_control;
- std::string id = "=CaptureControl/Dev1/HiFi";
- std::string value = "MIC";
-
- ResetStubData();
-
- snd_use_case_get_value[id] = value;
-
- cap_control = ucm_get_cap_control(mgr, "Dev1");
- ASSERT_TRUE(cap_control);
- EXPECT_EQ(0, strcmp(cap_control, value.c_str()));
- free(cap_control);
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id);
-}
-
-TEST(AlsaUcm, GetOverrideType) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* override_type_name;
- std::string id = "=OverrideNodeType/Dev1/HiFi";
- std::string value = "HDMI";
-
- ResetStubData();
-
- snd_use_case_get_value[id] = value;
-
- override_type_name = ucm_get_override_type_name(mgr, "Dev1");
- ASSERT_TRUE(override_type_name);
- EXPECT_EQ(0, strcmp(override_type_name, value.c_str()));
- free((void*)override_type_name);
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id);
-}
-
-TEST(AlsaUcm, GetSectionsForVar) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- struct section_name *section_names, *c;
-
- ResetStubData();
-
- const char* sections[] = {"Sec1", "Comment for Sec1",
- "Sec2", "Comment for Sec2",
- "Sec3", "Comment for Sec3"};
- fake_list["Identifier"] = sections;
- fake_list_size["Identifier"] = 6;
- std::string id_1 = "=Var/Sec1/HiFi";
- std::string id_2 = "=Var/Sec2/HiFi";
- std::string id_3 = "=Var/Sec3/HiFi";
- std::string value_1 = "Value1";
- std::string value_2 = "Value2";
- std::string value_3 = "Value2";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- snd_use_case_get_value[id_3] = value_3;
-
- section_names = ucm_get_sections_for_var(mgr, "Var", "Value2", "Identifier",
- CRAS_STREAM_OUTPUT);
-
- ASSERT_TRUE(section_names);
- EXPECT_EQ(0, strcmp(section_names->name, "Sec2"));
- EXPECT_EQ(0, strcmp(section_names->next->name, "Sec3"));
-
- ASSERT_EQ(3, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(snd_use_case_get_id[1], id_2);
- EXPECT_EQ(snd_use_case_get_id[2], id_3);
-
- DL_FOREACH (section_names, c) {
- DL_DELETE(section_names, c);
- free((void*)c->name);
- free(c);
- }
-}
-
-TEST(AlsaUcm, GetDevForJack) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* dev_name;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=JackDev/Dev1/HiFi";
- std::string id_2 = "=JackDev/Dev2/HiFi";
- std::string value_1 = "Value1";
- std::string value_2 = "Value2";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- dev_name = ucm_get_dev_for_jack(mgr, value_2.c_str(), CRAS_STREAM_OUTPUT);
- ASSERT_TRUE(dev_name);
- EXPECT_EQ(0, strcmp(dev_name, "Dev2"));
- free((void*)dev_name);
-
- ASSERT_EQ(2, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(snd_use_case_get_id[1], id_2);
-}
-
-TEST(AlsaUcm, GetDevForHeadphoneJack) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* dev_name;
- const char* devices[] = {"Mic", "Comment for Dev1", "Headphone",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=JackDev/Mic/HiFi";
- std::string id_2 = "=JackDev/Headphone/HiFi";
- std::string value = "JackValue";
-
- snd_use_case_get_value[id_1] = value;
- snd_use_case_get_value[id_2] = value;
-
- /* Looking for jack with matched value with output direction, Headphone will
- * be found even though Mic section has the matched value too. */
- dev_name = ucm_get_dev_for_jack(mgr, value.c_str(), CRAS_STREAM_OUTPUT);
-
- ASSERT_TRUE(dev_name);
- EXPECT_EQ(0, strcmp(dev_name, "Headphone"));
- free((void*)dev_name);
-}
-
-TEST(AlsaUcm, GetDevForMicJack) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* dev_name;
- const char* devices[] = {"Headphone", "Comment for Dev1", "Mic",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=JackDev/Headphone/HiFi";
- std::string id_2 = "=JackDev/Mic/HiFi";
- std::string value = "JackValue";
-
- snd_use_case_get_value[id_1] = value;
- snd_use_case_get_value[id_2] = value;
-
- /* Looking for jack with matched value with input direction, Mic will be found
- * even though Headphone section has the matched value too. */
- dev_name = ucm_get_dev_for_jack(mgr, value.c_str(), CRAS_STREAM_INPUT);
-
- ASSERT_TRUE(dev_name);
- EXPECT_EQ(0, strcmp(dev_name, "Mic"));
- free((void*)dev_name);
-}
-
-TEST(AlsaUcm, GetDevForMixer) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char *dev_name_out, *dev_name_in;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=PlaybackMixerElem/Dev1/HiFi";
- std::string id_2 = "=CaptureMixerElem/Dev2/HiFi";
- std::string value_1 = "Value1";
- std::string value_2 = "Value2";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- dev_name_out =
- ucm_get_dev_for_mixer(mgr, value_1.c_str(), CRAS_STREAM_OUTPUT);
- dev_name_in = ucm_get_dev_for_mixer(mgr, value_2.c_str(), CRAS_STREAM_INPUT);
-
- ASSERT_TRUE(dev_name_out);
- EXPECT_EQ(0, strcmp(dev_name_out, "Dev1"));
- free((void*)dev_name_out);
-
- ASSERT_TRUE(dev_name_in);
- EXPECT_EQ(0, strcmp(dev_name_in, "Dev2"));
- free((void*)dev_name_in);
-}
-
-TEST(AlsaUcm, GetAlsaDeviceIndexForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=CapturePCM/Dev1/HiFi";
- std::string id_2 = "=PlaybackPCM/Dev2/HiFi";
- std::string value_1 = "PCMName,1";
- std::string value_2 = "PCMName,2";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- EXPECT_EQ(1, ucm_get_alsa_dev_idx_for_dev(mgr, "Dev1", CRAS_STREAM_INPUT));
- EXPECT_EQ(2, ucm_get_alsa_dev_idx_for_dev(mgr, "Dev2", CRAS_STREAM_OUTPUT));
-
- ASSERT_EQ(2, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(snd_use_case_get_id[1], id_2);
-}
-
-TEST(AlsaUcm, GetDeviceRateForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int input_dev_rate, output_dev_rate;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=CaptureRate/Dev1/HiFi";
- std::string id_2 = "=PlaybackRate/Dev2/HiFi";
- std::string value_1 = "44100";
- std::string value_2 = "48000";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- input_dev_rate = ucm_get_sample_rate_for_dev(mgr, "Dev1", CRAS_STREAM_INPUT);
- output_dev_rate =
- ucm_get_sample_rate_for_dev(mgr, "Dev2", CRAS_STREAM_OUTPUT);
- EXPECT_EQ(44100, input_dev_rate);
- EXPECT_EQ(48000, output_dev_rate);
-
- ASSERT_EQ(2, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(snd_use_case_get_id[1], id_2);
-}
-
-TEST(AlsaUcm, GetDeviceChannelsForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int rc;
- size_t input_dev_channels, output_dev_channels;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=CaptureChannels/Dev1/HiFi";
- std::string id_2 = "=PlaybackChannels/Dev2/HiFi";
- std::string value_1 = "4";
- std::string value_2 = "8";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- rc = ucm_get_channels_for_dev(mgr, "Dev1", CRAS_STREAM_INPUT,
- &input_dev_channels);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(4, input_dev_channels);
- rc = ucm_get_channels_for_dev(mgr, "Dev2", CRAS_STREAM_OUTPUT,
- &output_dev_channels);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(8, output_dev_channels);
-
- ASSERT_EQ(2, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(snd_use_case_get_id[1], id_2);
-}
-
-TEST(AlsaUcm, GetCaptureChannelMapForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int8_t channel_layout[CRAS_CH_MAX];
- int rc;
-
- ResetStubData();
-
- std::string id_1 = "=CaptureChannelMap/Dev1/HiFi";
- std::string value_1 = "-1 -1 0 1 -1 -1 -1 -1 -1 -1 -1";
-
- snd_use_case_get_value[id_1] = value_1;
- rc = ucm_get_capture_chmap_for_dev(mgr, "Dev1", channel_layout);
-
- EXPECT_EQ(0, rc);
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(channel_layout[0], -1);
- EXPECT_EQ(channel_layout[1], -1);
- EXPECT_EQ(channel_layout[2], 0);
- EXPECT_EQ(channel_layout[3], 1);
- EXPECT_EQ(channel_layout[4], -1);
- EXPECT_EQ(channel_layout[5], -1);
- EXPECT_EQ(channel_layout[6], -1);
- EXPECT_EQ(channel_layout[7], -1);
- EXPECT_EQ(channel_layout[8], -1);
- EXPECT_EQ(channel_layout[9], -1);
- EXPECT_EQ(channel_layout[10], -1);
-}
-
-TEST(AlsaUcm, GetEchoReferenceDev) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* echo_ref_dev;
-
- ResetStubData();
-
- std::string id_1 = "=EchoReferenceDev/Dev1/HiFi";
- std::string value_1 = "Echo Ref";
-
- snd_use_case_get_value[id_1] = value_1;
- echo_ref_dev = ucm_get_echo_reference_dev_name_for_dev(mgr, "Dev1");
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id_1);
- EXPECT_EQ(0, strcmp(echo_ref_dev, value_1.c_str()));
- free((void*)echo_ref_dev);
-}
-
-TEST(AlsaUcm, GetHotwordModels) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* models;
- const char* modifiers[] = {"Mod1", "Comment1", "Hotword Model en",
- "Comment2", "Hotword Model jp", "Comment3",
- "Mod2", "Comment4", "Hotword Model de",
- "Comment5"};
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 10;
-
- models = ucm_get_hotword_models(mgr);
- ASSERT_TRUE(models);
- EXPECT_EQ(0, strcmp(models, "en,jp,de"));
- free((void*)models);
-}
-
-TEST(AlsaUcm, SetHotwordModel) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* modifiers[] = {"Hotword Model en", "Comment1",
- "Hotword Model jp", "Comment2",
- "Hotword Model de", "Comment3"};
- const char* enabled_mods[] = {"Hotword Model jp"};
- int ret;
- std::string id = "_modstatus/Hotword Model jp";
- ResetStubData();
-
- snd_use_case_geti_value[id] = 1;
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 6;
-
- EXPECT_EQ(-EINVAL, ucm_set_hotword_model(mgr, "zh"));
- EXPECT_EQ(0, snd_use_case_set_called);
-
- ret = ucm_set_hotword_model(mgr, "jp");
-
- EXPECT_EQ(0, ret);
- EXPECT_EQ(0, snd_use_case_set_called);
- EXPECT_EQ(0, strcmp(mgr->hotword_modifier, "Hotword Model jp"));
-
- fake_list["_enamods"] = enabled_mods;
- fake_list_size["_enamods"] = 1;
- ret = ucm_set_hotword_model(mgr, "de");
- EXPECT_EQ(0, ret);
- EXPECT_EQ(2, snd_use_case_set_called);
- EXPECT_EQ(1, snd_use_case_geti_called);
- EXPECT_EQ(
- snd_use_case_set_param[0],
- std::make_pair(std::string("_dismod"), std::string("Hotword Model jp")));
- EXPECT_EQ(
- snd_use_case_set_param[1],
- std::make_pair(std::string("_enamod"), std::string("Hotword Model de")));
- free(mgr->hotword_modifier);
-}
-
-TEST(AlsaUcm, DisableAllHotwordModels) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* modifiers[] = {"Hotword Model en", "Comment1",
- "Hotword Model jp", "Comment2",
- "Hotword Model de", "Comment3"};
- const char* enabled_mods[] = {"Hotword Model en"};
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 6;
- fake_list["_enamods"] = enabled_mods;
- fake_list_size["_enamods"] = 1;
-
- ucm_disable_all_hotword_models(mgr);
-
- EXPECT_EQ(1, snd_use_case_set_called);
- EXPECT_EQ(
- snd_use_case_set_param[0],
- std::make_pair(std::string("_dismod"), std::string("Hotword Model en")));
-}
-
-TEST(AlsaUcm, EnableHotwordModel) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* modifiers[] = {"Hotword Model en", "Comment1",
- "Hotword Model jp", "Comment2",
- "Hotword Model de", "Comment3"};
- const char* enabled_mods[] = {""};
- int ret;
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 6;
- fake_list["_enamods"] = enabled_mods;
- fake_list_size["_enamods"] = 0;
-
- EXPECT_EQ(-EINVAL, ucm_enable_hotword_model(mgr));
-
- mgr->hotword_modifier = strdup("Hotword Model de");
- ret = ucm_enable_hotword_model(mgr);
-
- EXPECT_EQ(0, ret);
- EXPECT_EQ(1, snd_use_case_set_called);
- EXPECT_EQ(
- snd_use_case_set_param[0],
- std::make_pair(std::string("_enamod"), std::string("Hotword Model de")));
- free(mgr->hotword_modifier);
-}
-
-TEST(AlsaUcm, SwapModeExists) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int rc;
- const char* modifiers_1[] = {
- "Speaker Swap Mode", "Comment for Speaker Swap Mode",
- "Microphone Swap Mode", "Comment for Microphone Swap Mode"};
- const char* modifiers_2[] = {
- "Speaker Some Mode", "Comment for Speaker Some Mode",
- "Microphone Some Mode", "Comment for Microphone Some Mode"};
-
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers_1;
- fake_list_size["_modifiers/HiFi"] = 4;
- rc = ucm_swap_mode_exists(mgr);
- EXPECT_EQ(1, rc);
-
- fake_list["_modifiers/HiFi"] = modifiers_2;
- fake_list_size["_modifiers/HiFi"] = 4;
- rc = ucm_swap_mode_exists(mgr);
- EXPECT_EQ(0, rc);
-}
-
-TEST(AlsaUcm, EnableSwapMode) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int rc;
- const char* modifiers[] = {
- "Speaker Swap Mode", "Comment for Speaker Swap Mode",
- "Microphone Swap Mode", "Comment for Microphone Swap Mode"};
- const char* modifiers_enabled[] = {"Speaker Swap Mode"};
-
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 4;
-
- fake_list["_enamods"] = modifiers_enabled;
- fake_list_size["_enamods"] = 1;
-
- snd_use_case_set_return = 0;
-
- rc = ucm_enable_swap_mode(mgr, "Headphone", 1);
- EXPECT_EQ(-EPERM, rc);
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_swap_mode(mgr, "Speaker", 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_swap_mode(mgr, "Microphone", 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_use_case_set_called);
-}
-
-TEST(AlsaUcm, DisableSwapMode) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int rc;
- const char* modifiers[] = {
- "Speaker Swap Mode", "Comment for Speaker Swap Mode",
- "Microphone Swap Mode", "Comment for Microphone Swap Mode"};
- const char* modifiers_enabled[] = {"Speaker Swap Mode"};
-
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 4;
-
- fake_list["_enamods"] = modifiers_enabled;
- fake_list_size["_enamods"] = 1;
-
- snd_use_case_set_return = 0;
-
- rc = ucm_enable_swap_mode(mgr, "Headphone", 0);
- EXPECT_EQ(-EPERM, rc);
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_swap_mode(mgr, "Microphone", 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_swap_mode(mgr, "Speaker", 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_use_case_set_called);
-}
-
-TEST(AlsaUcm, NoiseCancellationExists) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int rc;
- const char* node = "Internal Mic";
- const char* modifiers_1[] = {"Internal Mic Noise Cancellation", "Comment"};
- const char* modifiers_2[] = {"Internal Mic Noise Augmentation", "Comment"};
- const char* modifiers_3[] = {"Microphone Noise Cancellation", "Comment"};
-
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers_1;
- fake_list_size["_modifiers/HiFi"] = 2;
- rc = ucm_node_noise_cancellation_exists(mgr, node);
- EXPECT_EQ(1, rc);
-
- fake_list["_modifiers/HiFi"] = modifiers_2;
- fake_list_size["_modifiers/HiFi"] = 2;
- rc = ucm_node_noise_cancellation_exists(mgr, node);
- EXPECT_EQ(0, rc);
-
- fake_list["_modifiers/HiFi"] = modifiers_3;
- fake_list_size["_modifiers/HiFi"] = 2;
- rc = ucm_node_noise_cancellation_exists(mgr, node);
- EXPECT_EQ(0, rc);
-}
-
-TEST(AlsaUcm, EnableDisableNoiseCancellation) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int rc;
- const char* modifiers[] = {"Internal Mic Noise Cancellation", "Comment1",
- "Microphone Noise Cancellation", "Comment2"};
- const char* modifiers_enabled[] = {"Internal Mic Noise Cancellation"};
-
- ResetStubData();
-
- fake_list["_modifiers/HiFi"] = modifiers;
- fake_list_size["_modifiers/HiFi"] = 4;
-
- fake_list["_enamods"] = modifiers_enabled;
- fake_list_size["_enamods"] = 1;
-
- snd_use_case_set_return = 0;
-
- rc = ucm_enable_node_noise_cancellation(mgr, "Line In", 1);
- EXPECT_EQ(-EPERM, rc); // Modifier is not existed
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_node_noise_cancellation(mgr, "Line In", 0);
- EXPECT_EQ(-EPERM, rc); // Modifier is not existed
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_node_noise_cancellation(mgr, "Microphone", 0);
- EXPECT_EQ(0, rc); // Modifier is already disabled
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_node_noise_cancellation(mgr, "Microphone", 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_use_case_set_called);
-
- snd_use_case_set_called = 0;
-
- rc = ucm_enable_node_noise_cancellation(mgr, "Internal Mic", 1);
- EXPECT_EQ(0, rc); // Modifier is already enabled
- EXPECT_EQ(0, snd_use_case_set_called);
-
- rc = ucm_enable_node_noise_cancellation(mgr, "Internal Mic", 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, snd_use_case_set_called);
-}
-
-TEST(AlsaFlag, GetFlag) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- char* flag_value;
-
- std::string id = "=FlagName//HiFi";
- std::string value = "1";
- ResetStubData();
-
- snd_use_case_get_value[id] = value;
-
- flag_value = ucm_get_flag(mgr, "FlagName");
- ASSERT_TRUE(flag_value);
- EXPECT_EQ(0, strcmp(flag_value, value.c_str()));
- free(flag_value);
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id);
-}
-
-TEST(AlsaUcm, ModifierEnabled) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int enabled;
-
- ResetStubData();
-
- const char* mods[] = {"Mod1", "Mod2"};
- fake_list["_enamods"] = mods;
- fake_list_size["_enamods"] = 2;
-
- enabled = modifier_enabled(mgr, "Mod1");
- EXPECT_EQ(1, enabled);
- enabled = modifier_enabled(mgr, "Mod2");
- EXPECT_EQ(1, enabled);
- enabled = modifier_enabled(mgr, "Mod3");
- EXPECT_EQ(0, enabled);
-}
-
-TEST(AlsaUcm, SetModifierEnabled) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
-
- ResetStubData();
-
- ucm_set_modifier_enabled(mgr, "Mod1", 1);
- EXPECT_EQ(snd_use_case_set_param[0],
- std::make_pair(std::string("_enamod"), std::string("Mod1")));
- EXPECT_EQ(1, snd_use_case_set_called);
- ucm_set_modifier_enabled(mgr, "Mod1", 0);
- EXPECT_EQ(snd_use_case_set_param[1],
- std::make_pair(std::string("_dismod"), std::string("Mod1")));
- EXPECT_EQ(2, snd_use_case_set_called);
-}
-
-TEST(AlsaUcm, EndWithSuffix) {
- EXPECT_EQ(1, ucm_str_ends_with_suffix("Foo bar", "bar"));
- EXPECT_EQ(1, ucm_str_ends_with_suffix("bar", "bar"));
- EXPECT_EQ(0, ucm_str_ends_with_suffix("Foo car", "bar"));
-}
-
-TEST(AlsaUcm, SectionExistsWithName) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char* sections[] = {"Sec1", "Comment for Sec1", "Sec2",
- "Comment for Sec2"};
-
- ResetStubData();
-
- fake_list["Identifier"] = sections;
- fake_list_size["Identifier"] = 4;
- EXPECT_EQ(1, ucm_section_exists_with_name(mgr, "Sec1", "Identifier"));
- EXPECT_EQ(1, ucm_section_exists_with_name(mgr, "Sec2", "Identifier"));
- EXPECT_EQ(0, ucm_section_exists_with_name(mgr, "Sec3", "Identifier"));
-}
-
-TEST(AlsaUcm, SectionExistsWithSuffix) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
-
- ResetStubData();
-
- const char* sections[] = {"Sec1 Suffix1", "Comment for Sec1", "Sec2 Suffix2",
- "Comment for Sec2"};
- fake_list["Identifier"] = sections;
- fake_list_size["Identifier"] = 4;
- EXPECT_EQ(1, ucm_section_exists_with_suffix(mgr, "Suffix1", "Identifier"));
- EXPECT_EQ(1, ucm_section_exists_with_suffix(mgr, "Suffix2", "Identifier"));
- EXPECT_EQ(0, ucm_section_exists_with_suffix(mgr, "Suffix3", "Identifier"));
-}
-
-TEST(AlsaUcm, DisableSoftwareVolume) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- unsigned int disable_software_volume;
- std::string id = "=DisableSoftwareVolume//HiFi";
- std::string value = "1";
-
- ResetStubData();
-
- snd_use_case_get_value[id] = value;
-
- disable_software_volume = ucm_get_disable_software_volume(mgr);
- ASSERT_TRUE(disable_software_volume);
-
- ASSERT_EQ(1, snd_use_case_get_called);
- EXPECT_EQ(snd_use_case_get_id[0], id);
-}
-
-TEST(AlsaUcm, GetCoupledMixersForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- struct mixer_name *mixer_names_1, *mixer_names_2, *c;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=CoupledMixers/Dev1/HiFi";
- std::string value_1 = "Mixer Name1,Mixer Name2,Mixer Name3";
- std::string id_2 = "=CoupledMixers/Dev2/HiFi";
- std::string value_2 = "";
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- mixer_names_1 = ucm_get_coupled_mixer_names(mgr, "Dev1");
- mixer_names_2 = ucm_get_coupled_mixer_names(mgr, "Dev2");
-
- ASSERT_TRUE(mixer_names_1);
- EXPECT_EQ(0, strcmp(mixer_names_1->name, "Mixer Name1"));
- EXPECT_EQ(0, strcmp(mixer_names_1->next->name, "Mixer Name2"));
- EXPECT_EQ(0, strcmp(mixer_names_1->next->next->name, "Mixer Name3"));
- EXPECT_EQ(NULL, mixer_names_1->next->next->next);
-
- EXPECT_EQ(NULL, mixer_names_2);
-
- DL_FOREACH (mixer_names_1, c) {
- DL_DELETE(mixer_names_1, c);
- free((void*)c->name);
- free(c);
- }
-}
-
-TEST(AlsaUcm, FreeMixerNames) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- struct mixer_name* mixer_names_1;
- const char* devices[] = {"Dev1", "Comment for Dev1"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 2;
- std::string id_1 = "=CoupledMixers/Dev1/HiFi";
- std::string value_1 = "Mixer Name1,Mixer Name2,Mixer Name3";
- snd_use_case_get_value[id_1] = value_1;
- mixer_names_1 = ucm_get_coupled_mixer_names(mgr, "Dev1");
-
- ASSERT_TRUE(mixer_names_1);
- EXPECT_EQ(0, strcmp(mixer_names_1->name, "Mixer Name1"));
- EXPECT_EQ(0, strcmp(mixer_names_1->next->name, "Mixer Name2"));
- EXPECT_EQ(0, strcmp(mixer_names_1->next->next->name, "Mixer Name3"));
- EXPECT_EQ(NULL, mixer_names_1->next->next->next);
-
- /* No way to actually check if memory is freed. */
- mixer_name_free(mixer_names_1);
-}
-
-TEST(AlsaUcm, DefaultNodeGain) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- long default_node_gain;
- int ret;
- std::string id = "=DefaultNodeGain/Internal Mic/HiFi";
- std::string value = "-2000";
-
- ResetStubData();
-
- /* Value can be found in UCM. */
- snd_use_case_get_value[id] = value;
-
- ret = ucm_get_default_node_gain(mgr, "Internal Mic", &default_node_gain);
-
- EXPECT_EQ(0, ret);
- EXPECT_EQ(-2000, default_node_gain);
-
- ResetStubData();
-
- /* Value can not be found in UCM. */
- ret = ucm_get_default_node_gain(mgr, "Internal Mic", &default_node_gain);
-
- ASSERT_TRUE(ret);
-}
-
-TEST(AlsaUcm, IntrinsicSensitivity) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- long intrinsic_vol;
- int ret;
- std::string id = "=IntrinsicSensitivity/Internal Mic/HiFi";
- std::string value = "-2000";
-
- ResetStubData();
-
- /* Value can be found in UCM. */
- snd_use_case_get_value[id] = value;
-
- ret = ucm_get_intrinsic_sensitivity(mgr, "Internal Mic", &intrinsic_vol);
-
- EXPECT_EQ(0, ret);
- EXPECT_EQ(-2000, intrinsic_vol);
-
- ResetStubData();
-
- /* Value can not be found in UCM. */
- ret = ucm_get_intrinsic_sensitivity(mgr, "Internal Mic", &intrinsic_vol);
-
- ASSERT_TRUE(ret);
-}
-
-TEST(AlsaUcm, UseFullySpecifiedUCMConfig) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int fully_specified_flag;
-
- std::string id = "=FullySpecifiedUCM//HiFi";
- ResetStubData();
-
- /* Flag is not set */
- fully_specified_flag = ucm_has_fully_specified_ucm_flag(mgr);
- ASSERT_FALSE(fully_specified_flag);
-
- /* Flag is set to "1". */
- snd_use_case_get_value[id] = std::string("1");
- fully_specified_flag = ucm_has_fully_specified_ucm_flag(mgr);
- ASSERT_TRUE(fully_specified_flag);
-
- /* Flag is set to "0". */
- snd_use_case_get_value[id] = std::string("0");
- fully_specified_flag = ucm_has_fully_specified_ucm_flag(mgr);
- ASSERT_FALSE(fully_specified_flag);
-}
-
-TEST(AlsaUcm, GetMixerNameForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char *mixer_name_1, *mixer_name_2;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=PlaybackMixerElem/Dev1/HiFi";
- std::string id_2 = "=CaptureMixerElem/Dev2/HiFi";
- std::string value_1 = "MixerName1";
- std::string value_2 = "MixerName2";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
- mixer_name_1 = ucm_get_playback_mixer_elem_for_dev(mgr, "Dev1");
- mixer_name_2 = ucm_get_capture_mixer_elem_for_dev(mgr, "Dev2");
-
- EXPECT_EQ(0, strcmp(mixer_name_1, value_1.c_str()));
- EXPECT_EQ(0, strcmp(mixer_name_2, value_2.c_str()));
- free((void*)mixer_name_1);
- free((void*)mixer_name_2);
-}
-
-TEST(AlsaUcm, GetMainVolumeMixerName) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- struct mixer_name *mixer_names_1, *mixer_names_2, *c;
-
- ResetStubData();
-
- std::string id = "=MainVolumeNames//HiFi";
- std::string value_1 = "Mixer Name1,Mixer Name2,Mixer Name3";
-
- snd_use_case_get_value[id] = value_1;
- mixer_names_1 = ucm_get_main_volume_names(mgr);
-
- ResetStubData();
-
- /* Can not find MainVolumeNames */
- mixer_names_2 = ucm_get_main_volume_names(mgr);
-
- ASSERT_TRUE(mixer_names_1);
- EXPECT_EQ(0, strcmp(mixer_names_1->name, "Mixer Name1"));
- EXPECT_EQ(0, strcmp(mixer_names_1->next->name, "Mixer Name2"));
- EXPECT_EQ(0, strcmp(mixer_names_1->next->next->name, "Mixer Name3"));
- EXPECT_EQ(NULL, mixer_names_1->next->next->next);
-
- DL_FOREACH (mixer_names_1, c) {
- DL_DELETE(mixer_names_1, c);
- free((void*)c->name);
- free(c);
- }
-
- EXPECT_EQ(NULL, mixer_names_2);
-}
-
-TEST(AlsaUcm, ListSectionsByDeviceNameOutput) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- void* callback_arg = reinterpret_cast<void*>(0x56);
- int listed = 0;
-
- ResetStubData();
- SetSectionDeviceData();
-
- listed = ucm_list_section_devices_by_device_name(
- mgr, CRAS_STREAM_OUTPUT, "test_card:0", list_devices_callback,
- callback_arg);
-
- EXPECT_EQ(2, listed);
- EXPECT_EQ(2, list_devices_callback_names.size());
- EXPECT_EQ(2, list_devices_callback_args.size());
-
- EXPECT_EQ(0, strcmp(list_devices_callback_names[0].c_str(), "Speaker"));
- EXPECT_EQ(callback_arg, list_devices_callback_args[0]);
-
- EXPECT_EQ(0, strcmp(list_devices_callback_names[1].c_str(), "Headphone"));
- EXPECT_EQ(callback_arg, list_devices_callback_args[1]);
-}
-
-TEST(AlsaUcm, ListSectionsByDeviceNameInput) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- void* callback_arg = reinterpret_cast<void*>(0x56);
- int listed = 0;
-
- ResetStubData();
- SetSectionDeviceData();
-
- listed = ucm_list_section_devices_by_device_name(
- mgr, CRAS_STREAM_INPUT, "test_card:0", list_devices_callback,
- callback_arg);
-
- EXPECT_EQ(2, listed);
- EXPECT_EQ(2, list_devices_callback_names.size());
- EXPECT_EQ(2, list_devices_callback_args.size());
-
- EXPECT_EQ(0, strcmp(list_devices_callback_names[0].c_str(), "IntMic"));
- EXPECT_EQ(callback_arg, list_devices_callback_args[0]);
-
- EXPECT_EQ(0, strcmp(list_devices_callback_names[1].c_str(), "ExtMic"));
- EXPECT_EQ(callback_arg, list_devices_callback_args[1]);
-}
-
-TEST(AlsaUcm, GetJackDevForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char *jack_name_1, *jack_name_2;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=JackDev/Dev1/HiFi";
- std::string value_1 = "JackDev1";
-
- snd_use_case_get_value[id_1] = value_1;
- jack_name_1 = ucm_get_jack_dev_for_dev(mgr, "Dev1");
- jack_name_2 = ucm_get_jack_dev_for_dev(mgr, "Dev2");
-
- EXPECT_EQ(0, strcmp(jack_name_1, value_1.c_str()));
- EXPECT_EQ(NULL, jack_name_2);
-
- free((void*)jack_name_1);
- free((void*)jack_name_2);
-}
-
-TEST(AlsaUcm, GetJackControlForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- const char *jack_name_1, *jack_name_2;
- const char* devices[] = {"Dev1", "Comment for Dev1", "Dev2",
- "Comment for Dev2"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 4;
- std::string id_1 = "=JackControl/Dev1/HiFi";
- std::string value_1 = "JackControl1";
-
- snd_use_case_get_value[id_1] = value_1;
- jack_name_1 = ucm_get_jack_control_for_dev(mgr, "Dev1");
- jack_name_2 = ucm_get_jack_control_for_dev(mgr, "Dev2");
-
- EXPECT_EQ(0, strcmp(jack_name_1, value_1.c_str()));
- EXPECT_EQ(NULL, jack_name_2);
-
- free((void*)jack_name_1);
- free((void*)jack_name_2);
-}
-
-TEST(AlsaUcm, GetPeriodFramesForDevice) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- int dma_period_1, dma_period_2, dma_period_3;
- const char* devices[] = {"Dev1", "Comment for Dev1",
- "Dev2", "Comment for Dev2",
- "Dev3", "Comment for Dev3"};
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = 6;
- std::string id_1 = "=DmaPeriodMicrosecs/Dev1/HiFi";
- std::string value_1 = "1000";
- std::string id_2 = "=DmaPeriodMicrosecs/Dev2/HiFi";
- std::string value_2 = "-10";
-
- snd_use_case_get_value[id_1] = value_1;
- snd_use_case_get_value[id_2] = value_2;
-
- dma_period_1 = ucm_get_dma_period_for_dev(mgr, "Dev1");
- dma_period_2 = ucm_get_dma_period_for_dev(mgr, "Dev2");
- dma_period_3 = ucm_get_dma_period_for_dev(mgr, "Dev3");
-
- EXPECT_EQ(1000, dma_period_1);
- EXPECT_EQ(0, dma_period_2);
- EXPECT_EQ(0, dma_period_3);
-}
-
-TEST(AlsaUcm, UcmSection) {
- struct ucm_section* section_list = NULL;
- struct ucm_section* section;
- struct mixer_name* controls = NULL;
- struct mixer_name* m_name;
- int dev_idx = 0;
- int dependent_dev_idx = -1;
- size_t i;
- enum CRAS_STREAM_DIRECTION dir = CRAS_STREAM_OUTPUT;
- static const char* name = "Headphone";
- static const char* pcm_name = "hw:0,1";
- static const char* jack_name = "my-card-name Headset Jack";
- static const char* jack_type = "gpio";
- static const char* mixer_name = "Control1";
- static const char* coupled_names[] = {"Coupled1", "Coupled2"};
-
- section =
- ucm_section_create(NULL, NULL, 0, -1, CRAS_STREAM_OUTPUT, NULL, NULL);
- EXPECT_EQ(reinterpret_cast<struct ucm_section*>(NULL), section);
-
- section = ucm_section_create(name, pcm_name, dev_idx, dependent_dev_idx, dir,
- jack_name, jack_type);
- EXPECT_NE(reinterpret_cast<struct ucm_section*>(NULL), section);
- EXPECT_NE(name, section->name);
- EXPECT_EQ(0, strcmp(name, section->name));
- EXPECT_EQ(dev_idx, section->dev_idx);
- EXPECT_EQ(dir, section->dir);
- EXPECT_NE(jack_name, section->jack_name);
- EXPECT_NE(jack_type, section->jack_type);
- EXPECT_EQ(section->prev, section);
- EXPECT_EQ(reinterpret_cast<const char*>(NULL), section->mixer_name);
- EXPECT_EQ(reinterpret_cast<struct mixer_name*>(NULL), section->coupled);
-
- EXPECT_EQ(-EINVAL, ucm_section_set_mixer_name(section, NULL));
- EXPECT_EQ(-EINVAL, ucm_section_set_mixer_name(NULL, mixer_name));
- EXPECT_EQ(0, ucm_section_set_mixer_name(section, mixer_name));
-
- EXPECT_NE(section->mixer_name, mixer_name);
- EXPECT_EQ(0, strcmp(section->mixer_name, mixer_name));
-
- EXPECT_EQ(-EINVAL, ucm_section_add_coupled(section, NULL, MIXER_NAME_VOLUME));
- EXPECT_EQ(-EINVAL,
- ucm_section_add_coupled(NULL, coupled_names[0], MIXER_NAME_VOLUME));
- EXPECT_EQ(
- 0, ucm_section_add_coupled(section, coupled_names[0], MIXER_NAME_VOLUME));
-
- EXPECT_EQ(-EINVAL, ucm_section_concat_coupled(section, NULL));
- EXPECT_EQ(-EINVAL, ucm_section_concat_coupled(
- NULL, reinterpret_cast<struct mixer_name*>(0x1111)));
-
- controls = NULL;
- for (i = 1; i < ARRAY_SIZE(coupled_names); i++) {
- controls = mixer_name_add(controls, coupled_names[i], CRAS_STREAM_OUTPUT,
- MIXER_NAME_VOLUME);
- }
- /* Add controls to the list of coupled controls for this section. */
- EXPECT_EQ(0, ucm_section_concat_coupled(section, controls));
-
- i = 0;
- DL_FOREACH (section->coupled, m_name) {
- EXPECT_NE(m_name->name, coupled_names[i]);
- EXPECT_EQ(0, strcmp(m_name->name, coupled_names[i]));
- i++;
- }
- EXPECT_EQ(i, ARRAY_SIZE(coupled_names));
-
- DL_APPEND(section_list, section);
- ucm_section_free_list(section_list);
-}
-
-TEST(AlsaUcm, GetSections) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- struct ucm_section* sections;
- struct ucm_section* section;
- struct mixer_name* m_name;
- int section_count = 0;
- int dev_idx;
- int i = 0;
- const char* devices[] = {"Headphone", "The headphones jack.",
- "Speaker", "The speakers.",
- "Mic", "Microphone jack.",
- "Internal Mic", "Internal Microphones",
- "HDMI", "HDMI output"};
- const char* ids[] = {"=PlaybackPCM/Headphone/HiFi",
- "=JackDev/Headphone/HiFi",
- "=JackSwitch/Headphone/HiFi",
- "=CoupledMixers/Headphone/HiFi",
-
- "=PlaybackPCM/Speaker/HiFi",
- "=CoupledMixers/Speaker/HiFi",
- "=DependentPCM/Speaker/HiFi",
-
- "=CapturePCM/Mic/HiFi",
- "=JackDev/Mic/HiFi",
- "=JackSwitch/Mic/HiFi",
- "=CaptureMixerElem/Mic/HiFi",
-
- "=CapturePCM/Internal Mic/HiFi",
- "=CoupledMixers/Internal Mic/HiFi",
- "=JackSwitch/Internal Mic/HiFi",
-
- "=PlaybackPCM/HDMI/HiFi",
- "=PlaybackMixerElem/HDMI/HiFi",
-
- NULL};
- const char* values[] = {
- "hw:my-sound-card,0",
- "my-sound-card Headset Jack",
- "2",
- "HP-L,HP-R",
-
- "hw:my-sound-card,1",
- "SPK-L,SPK-R",
- "hw:my-sound-card,0",
-
- "hw:my-sound-card,2",
- "my-sound-card Headset Jack",
- "0",
- "CAPTURE",
-
- "hw:my-sound-card,3",
- "MIC-L,MIC-R",
- "-10",
-
- "hw:my-sound-card,4",
- "HDMI",
- };
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = ARRAY_SIZE(devices);
-
- while (ids[i]) {
- snd_use_case_get_value[ids[i]] = values[i];
- i++;
- }
-
- sections = ucm_get_sections(mgr);
- ASSERT_NE(sections, (struct ucm_section*)NULL);
- DL_FOREACH (sections, section) { section_count++; }
- EXPECT_EQ(section_count, ARRAY_SIZE(devices) / 2);
-
- // Headphone
- section = sections;
- EXPECT_EQ(0, strcmp(section->pcm_name, "hw:my-sound-card,0"));
- EXPECT_EQ(0, strcmp(section->name, "Headphone"));
- EXPECT_EQ(0, section->dev_idx);
- EXPECT_EQ(CRAS_STREAM_OUTPUT, section->dir);
- EXPECT_EQ(0, strcmp(section->jack_name, values[1]));
- EXPECT_EQ(0, strcmp(section->jack_type, "gpio"));
- EXPECT_EQ(NULL, section->mixer_name);
- ASSERT_NE((struct mixer_name*)NULL, section->coupled);
- m_name = section->coupled;
- EXPECT_EQ(0, strcmp(m_name->name, "HP-L"));
- m_name = m_name->next;
- EXPECT_EQ(0, strcmp(m_name->name, "HP-R"));
- EXPECT_EQ(NULL, m_name->next);
- EXPECT_EQ(2, section->jack_switch);
- dev_idx = section->dev_idx;
-
- // Speaker
- section = section->next;
- EXPECT_EQ(0, strcmp(section->pcm_name, "hw:my-sound-card,1"));
- EXPECT_EQ(0, strcmp(section->name, "Speaker"));
- EXPECT_EQ(1, section->dev_idx);
- EXPECT_EQ(CRAS_STREAM_OUTPUT, section->dir);
- EXPECT_EQ(NULL, section->jack_name);
- EXPECT_EQ(NULL, section->jack_type);
- EXPECT_EQ(-1, section->jack_switch);
- EXPECT_EQ(NULL, section->mixer_name);
- EXPECT_EQ(dev_idx, section->dependent_dev_idx);
- ASSERT_NE((struct mixer_name*)NULL, section->coupled);
- m_name = section->coupled;
- EXPECT_EQ(0, strcmp(m_name->name, "SPK-L"));
- m_name = m_name->next;
- EXPECT_EQ(0, strcmp(m_name->name, "SPK-R"));
- EXPECT_EQ(NULL, m_name->next);
-
- // Mic
- section = section->next;
- EXPECT_EQ(0, strcmp(section->pcm_name, "hw:my-sound-card,2"));
- EXPECT_EQ(0, strcmp(section->name, "Mic"));
- EXPECT_EQ(2, section->dev_idx);
- EXPECT_EQ(CRAS_STREAM_INPUT, section->dir);
- EXPECT_EQ(0, strcmp(section->jack_name, values[1]));
- EXPECT_EQ(0, strcmp(section->jack_type, "gpio"));
- EXPECT_EQ(0, section->jack_switch);
- ASSERT_NE((const char*)NULL, section->mixer_name);
- EXPECT_EQ(0, strcmp(section->mixer_name, "CAPTURE"));
- EXPECT_EQ(NULL, section->coupled);
-
- // Internal Mic
- section = section->next;
- EXPECT_EQ(0, strcmp(section->pcm_name, "hw:my-sound-card,3"));
- EXPECT_EQ(0, strcmp(section->name, "Internal Mic"));
- EXPECT_EQ(3, section->dev_idx);
- EXPECT_EQ(CRAS_STREAM_INPUT, section->dir);
- EXPECT_EQ(NULL, section->jack_name);
- EXPECT_EQ(NULL, section->jack_type);
- EXPECT_EQ(-1, section->jack_switch);
- EXPECT_EQ(NULL, section->mixer_name);
- ASSERT_NE((struct mixer_name*)NULL, section->coupled);
- m_name = section->coupled;
- EXPECT_EQ(0, strcmp(m_name->name, "MIC-L"));
- m_name = m_name->next;
- EXPECT_EQ(0, strcmp(m_name->name, "MIC-R"));
-
- // HDMI
- section = section->next;
- EXPECT_EQ(0, strcmp(section->pcm_name, "hw:my-sound-card,4"));
- EXPECT_EQ(0, strcmp(section->name, "HDMI"));
- EXPECT_EQ(4, section->dev_idx);
- EXPECT_EQ(CRAS_STREAM_OUTPUT, section->dir);
- EXPECT_EQ(NULL, section->jack_name);
- EXPECT_EQ(NULL, section->jack_type);
- EXPECT_EQ(-1, section->jack_switch);
- ASSERT_NE((const char*)NULL, section->mixer_name);
- EXPECT_EQ(0, strcmp(section->mixer_name, "HDMI"));
-
- EXPECT_EQ(NULL, section->next);
- ucm_section_free_list(sections);
-}
-
-TEST(AlsaUcm, GetSectionsMissingPCM) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
- struct ucm_section* sections;
- int i = 0;
- const char* devices[] = {"Headphone", "The headphones jack."};
- const char* ids[] = {"=JackDev/Headphone/HiFi",
- "=CoupledMixers/Headphone/HiFi", NULL};
- const char* values[] = {
- "my-sound-card Headset Jack",
- "HP-L,HP-R",
- };
-
- ResetStubData();
-
- fake_list["_devices/HiFi"] = devices;
- fake_list_size["_devices/HiFi"] = ARRAY_SIZE(devices);
-
- while (ids[i]) {
- snd_use_case_get_value[ids[i]] = values[i];
- i++;
- }
-
- sections = ucm_get_sections(mgr);
- EXPECT_EQ(NULL, sections);
-}
-
-TEST(AlsaUcm, CheckUseCaseVerbs) {
- struct cras_use_case_mgr* mgr = &cras_ucm_mgr;
-
- /* Verifies the mapping between stream types and verbs are correct. */
- mgr->use_case = CRAS_STREAM_TYPE_DEFAULT;
- EXPECT_EQ(0, strcmp("HiFi", uc_verb(mgr)));
- mgr->use_case = CRAS_STREAM_TYPE_MULTIMEDIA;
- EXPECT_EQ(0, strcmp("Multimedia", uc_verb(mgr)));
- mgr->use_case = CRAS_STREAM_TYPE_VOICE_COMMUNICATION;
- EXPECT_EQ(0, strcmp("Voice Call", uc_verb(mgr)));
- mgr->use_case = CRAS_STREAM_TYPE_SPEECH_RECOGNITION;
- EXPECT_EQ(0, strcmp("Speech", uc_verb(mgr)));
- mgr->use_case = CRAS_STREAM_TYPE_PRO_AUDIO;
- EXPECT_EQ(0, strcmp("Pro Audio", uc_verb(mgr)));
-}
-
-TEST(AlsaUcm, GetAvailUseCases) {
- struct cras_use_case_mgr* mgr;
- const char* verbs[] = {"HiFi", "Comment for Verb1",
- "Voice Call", "Comment for Verb2",
- "Speech", "Comment for Verb3"};
-
- ResetStubData();
-
- fake_list["_verbs"] = verbs;
- fake_list_size["_verbs"] = 6;
-
- mgr = ucm_create("foo");
- EXPECT_EQ(0x0D, mgr->avail_use_cases);
- ucm_destroy(mgr);
-}
-
-TEST(AlsaUcm, SetUseCase) {
- struct cras_use_case_mgr* mgr;
- const char* verbs[] = {"HiFi", "Comment for Verb1",
- "Voice Call", "Comment for Verb2",
- "Speech", "Comment for Verb3"};
- int rc;
-
- ResetStubData();
-
- fake_list["_verbs"] = verbs;
- fake_list_size["_verbs"] = 6;
-
- mgr = ucm_create("foo");
- EXPECT_EQ(snd_use_case_set_param[0],
- std::make_pair(std::string("_verb"), std::string("HiFi")));
-
- rc = ucm_set_use_case(mgr, CRAS_STREAM_TYPE_VOICE_COMMUNICATION);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(mgr->use_case, CRAS_STREAM_TYPE_VOICE_COMMUNICATION);
- EXPECT_EQ(snd_use_case_set_param[1],
- std::make_pair(std::string("_verb"), std::string("Voice Call")));
-
- /* Request unavailable use case will fail. */
- rc = ucm_set_use_case(mgr, CRAS_STREAM_TYPE_PRO_AUDIO);
- EXPECT_EQ(-1, rc);
- /* cras_use_case_mgr's use case should not be changed. */
- EXPECT_EQ(mgr->use_case, CRAS_STREAM_TYPE_VOICE_COMMUNICATION);
- /* And snd_use_case_set not being called. */
- EXPECT_EQ(2, snd_use_case_set_param.size());
-
- ucm_destroy(mgr);
-}
-
-/* Stubs */
-
-extern "C" {
-
-int snd_use_case_mgr_open(snd_use_case_mgr_t** uc_mgr, const char* card_name) {
- snd_use_case_mgr_open_called++;
- *uc_mgr = snd_use_case_mgr_open_mgr_ptr;
- return snd_use_case_mgr_open_return;
-}
-
-int snd_use_case_mgr_close(snd_use_case_mgr_t* uc_mgr) {
- snd_use_case_mgr_close_called++;
- return 0;
-}
-
-int snd_use_case_get(snd_use_case_mgr_t* uc_mgr,
- const char* identifier,
- const char** value) {
- snd_use_case_get_called++;
- snd_use_case_get_id.push_back(std::string(identifier));
- if (snd_use_case_get_value.find(identifier) == snd_use_case_get_value.end()) {
- *value = NULL;
- return -1;
- }
- *value = strdup(snd_use_case_get_value[identifier].c_str());
- return 0;
-}
-
-int snd_use_case_set(snd_use_case_mgr_t* uc_mgr,
- const char* identifier,
- const char* value) {
- snd_use_case_set_called++;
- snd_use_case_set_param.push_back(
- std::make_pair(std::string(identifier), std::string(value)));
- return snd_use_case_set_return;
-}
-
-int snd_use_case_get_list(snd_use_case_mgr_t* uc_mgr,
- const char* identifier,
- const char** list[]) {
- *list = fake_list[identifier];
- return fake_list_size[identifier];
-}
-
-int snd_use_case_free_list(const char* list[], int items) {
- snd_use_case_free_list_called++;
- return 0;
-}
-
-int snd_use_case_geti(snd_use_case_mgr_t* uc_mgr,
- const char* identifier,
- long* value) {
- snd_use_case_geti_called++;
- if (snd_use_case_geti_value.find(identifier) ==
- snd_use_case_geti_value.end()) {
- *value = 0;
- return -1;
- }
- *value = snd_use_case_geti_value[identifier];
- return 0;
-}
-
-} /* extern "C" */
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/apm_list_unittest.cc b/cras/src/tests/apm_list_unittest.cc
deleted file mode 100644
index 65e712fb..00000000
--- a/cras/src/tests/apm_list_unittest.cc
+++ /dev/null
@@ -1,444 +0,0 @@
-// Copyright 2018 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_apm_list.h"
-#include "cras_audio_area.h"
-#include "cras_dsp_pipeline.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_types.h"
-#include "float_buffer.h"
-#include "webrtc_apm.h"
-}
-
-#define FILENAME_TEMPLATE "ApmTest.XXXXXX"
-
-namespace {
-
-static void* stream_ptr = reinterpret_cast<void*>(0x123);
-static void* dev_ptr = reinterpret_cast<void*>(0x345);
-static void* dev_ptr2 = reinterpret_cast<void*>(0x678);
-static struct cras_apm_list* list;
-static struct cras_audio_area fake_audio_area;
-static unsigned int dsp_util_interleave_frames;
-static unsigned int webrtc_apm_process_stream_f_called;
-static unsigned int webrtc_apm_process_reverse_stream_f_called;
-static device_enabled_callback_t device_enabled_callback_val;
-static struct ext_dsp_module* ext_dsp_module_value;
-static struct cras_ionode fake_node;
-static struct cras_iodev fake_iodev;
-static int webrtc_apm_create_called;
-static bool cras_iodev_is_aec_use_case_ret;
-static dictionary* webrtc_apm_create_aec_ini_val = NULL;
-static dictionary* webrtc_apm_create_apm_ini_val = NULL;
-
-TEST(ApmList, ApmListCreate) {
- list = cras_apm_list_create(stream_ptr, 0);
- EXPECT_EQ((void*)NULL, list);
-
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
- EXPECT_EQ(APM_ECHO_CANCELLATION, cras_apm_list_get_effects(list));
-
- cras_apm_list_destroy(list);
-}
-
-static char* prepare_tempdir() {
- char dirname[sizeof(FILENAME_TEMPLATE) + 1];
- char filename[64];
- char* tempdir;
- FILE* fp;
-
- strcpy(dirname, FILENAME_TEMPLATE);
- tempdir = mkdtemp(dirname);
- snprintf(filename, 64, "%s/apm.ini", tempdir);
- fp = fopen(filename, "w");
- fprintf(fp, "%s", "[foo]\n");
- fclose(fp);
- fp = NULL;
- snprintf(filename, 64, "%s/aec.ini", tempdir);
- fp = fopen(filename, "w");
- fprintf(fp, "%s", "[bar]\n");
- fclose(fp);
- fp = NULL;
- return strdup(tempdir);
-}
-
-static void delete_tempdir(char* dir) {
- char filename[64];
-
- snprintf(filename, 64, "%s/apm.ini", dir);
- unlink(filename);
- snprintf(filename, 64, "%s/aec.ini", dir);
- unlink(filename);
- rmdir(dir);
-}
-
-static void init_channel_layout(struct cras_audio_format* fmt) {
- int i;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt->channel_layout[i] = -1;
-}
-
-TEST(ApmList, AddApmInputDevUnuseFirstChannel) {
- struct cras_audio_format fmt;
- struct cras_audio_format* val;
- struct cras_apm* apm;
- int ch;
- const int num_test_casts = 9;
- int test_layouts[num_test_casts][CRAS_CH_MAX] = {
- {0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {2, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {3, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1},
- {3, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1}};
- int test_num_channels[num_test_casts] = {1, 2, 2, 2, 2, 3, 4, 4, 4};
-
- fmt.frame_rate = 48000;
- fmt.format = SND_PCM_FORMAT_S16_LE;
-
- cras_apm_list_init("");
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
-
- for (int i = 0; i < num_test_casts; i++) {
- fmt.num_channels = test_num_channels[i];
- init_channel_layout(&fmt);
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- fmt.channel_layout[ch] = test_layouts[i][ch];
-
- /* Input dev is of aec use case. */
- apm = cras_apm_list_add_apm(list, dev_ptr, &fmt, 1);
- EXPECT_NE((void*)NULL, apm);
-
- /* Assert that the post-processing format never has an unset
- * first channel in the layout. */
- bool first_channel_found_in_layout = 0;
- val = cras_apm_list_get_format(apm);
- for (ch = 0; ch < CRAS_CH_MAX; ch++)
- if (0 == val->channel_layout[ch])
- first_channel_found_in_layout = 1;
-
- EXPECT_EQ(1, first_channel_found_in_layout);
-
- cras_apm_list_remove_apm(list, dev_ptr);
- }
-
- cras_apm_list_destroy(list);
- cras_apm_list_deinit();
-}
-
-TEST(ApmList, AddRemoveApm) {
- struct cras_audio_format fmt;
- char* dir;
-
- fmt.num_channels = 2;
- fmt.frame_rate = 48000;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fake_iodev.active_node = &fake_node;
- fake_node.type = CRAS_NODE_TYPE_INTERNAL_SPEAKER;
-
- dir = prepare_tempdir();
- cras_apm_list_init(dir);
- cras_iodev_is_aec_use_case_ret = 1;
-
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
-
- /* Input dev is of aec use case. */
- EXPECT_NE((void*)NULL, cras_apm_list_add_apm(list, dev_ptr, &fmt, 1));
- EXPECT_NE((void*)NULL, webrtc_apm_create_aec_ini_val);
- EXPECT_NE((void*)NULL, webrtc_apm_create_apm_ini_val);
- EXPECT_EQ((void*)NULL, cras_apm_list_get_active_apm(stream_ptr, dev_ptr));
-
- cras_apm_list_start_apm(list, dev_ptr);
- EXPECT_NE((void*)NULL, cras_apm_list_get_active_apm(stream_ptr, dev_ptr));
- EXPECT_EQ((void*)NULL, cras_apm_list_get_active_apm(stream_ptr, dev_ptr2));
-
- /* Input dev is not of aec use case. */
- EXPECT_NE((void*)NULL, cras_apm_list_add_apm(list, dev_ptr2, &fmt, 0));
- EXPECT_EQ((void*)NULL, webrtc_apm_create_aec_ini_val);
- EXPECT_EQ((void*)NULL, webrtc_apm_create_apm_ini_val);
- cras_apm_list_start_apm(list, dev_ptr2);
- cras_apm_list_stop_apm(list, dev_ptr);
-
- EXPECT_EQ((void*)NULL, cras_apm_list_get_active_apm(stream_ptr, dev_ptr));
- EXPECT_NE((void*)NULL, cras_apm_list_get_active_apm(stream_ptr, dev_ptr2));
-
- cras_apm_list_stop_apm(list, dev_ptr2);
- cras_apm_list_remove_apm(list, dev_ptr);
- cras_apm_list_remove_apm(list, dev_ptr2);
-
- cras_apm_list_destroy(list);
- cras_apm_list_deinit();
- delete_tempdir(dir);
- free(dir);
-}
-
-TEST(ApmList, OutputTypeNotAecUseCase) {
- struct cras_audio_format fmt;
- char* dir;
-
- fmt.num_channels = 2;
- fmt.frame_rate = 48000;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fake_iodev.active_node = &fake_node;
-
- dir = prepare_tempdir();
- cras_apm_list_init(dir);
-
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
-
- /* Output device is of aec use case. */
- cras_iodev_is_aec_use_case_ret = 1;
- EXPECT_NE((void*)NULL, cras_apm_list_add_apm(list, dev_ptr, &fmt, 1));
- EXPECT_NE((void*)NULL, webrtc_apm_create_aec_ini_val);
- EXPECT_NE((void*)NULL, webrtc_apm_create_apm_ini_val);
- cras_apm_list_remove_apm(list, dev_ptr);
-
- /* Output device is not of aec use case. */
- cras_iodev_is_aec_use_case_ret = 0;
- EXPECT_NE((void*)NULL, cras_apm_list_add_apm(list, dev_ptr, &fmt, 1));
- EXPECT_EQ((void*)NULL, webrtc_apm_create_aec_ini_val);
- EXPECT_EQ((void*)NULL, webrtc_apm_create_apm_ini_val);
- cras_apm_list_remove_apm(list, dev_ptr);
-
- cras_apm_list_destroy(list);
- cras_apm_list_deinit();
- delete_tempdir(dir);
- free(dir);
-}
-
-TEST(ApmList, ApmProcessForwardBuffer) {
- struct cras_apm* apm;
- struct cras_audio_format fmt;
- struct cras_audio_area* area;
- struct float_buffer* buf;
-
- fmt.num_channels = 2;
- fmt.frame_rate = 48000;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- init_channel_layout(&fmt);
- fmt.channel_layout[CRAS_CH_FL] = 0;
- fmt.channel_layout[CRAS_CH_FR] = 1;
-
- cras_apm_list_init("");
-
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
-
- apm = cras_apm_list_add_apm(list, dev_ptr, &fmt, 1);
-
- buf = float_buffer_create(500, 2);
- float_buffer_written(buf, 300);
- webrtc_apm_process_stream_f_called = 0;
- cras_apm_list_process(apm, buf, 0);
- EXPECT_EQ(0, webrtc_apm_process_stream_f_called);
-
- area = cras_apm_list_get_processed(apm);
- EXPECT_EQ(0, area->frames);
-
- float_buffer_reset(buf);
- float_buffer_written(buf, 200);
- cras_apm_list_process(apm, buf, 0);
- area = cras_apm_list_get_processed(apm);
- EXPECT_EQ(1, webrtc_apm_process_stream_f_called);
- EXPECT_EQ(480, dsp_util_interleave_frames);
- EXPECT_EQ(480, area->frames);
-
- /* Put some processed frames. Another apm_list process will not call
- * into webrtc_apm because the processed buffer is not yet empty.
- */
- cras_apm_list_put_processed(apm, 200);
- float_buffer_reset(buf);
- float_buffer_written(buf, 500);
- cras_apm_list_process(apm, buf, 0);
- EXPECT_EQ(1, webrtc_apm_process_stream_f_called);
-
- /* Put another 280 processed frames, so it's now ready for webrtc_apm
- * to process another chunk of 480 frames (10ms) data.
- */
- cras_apm_list_put_processed(apm, 280);
- cras_apm_list_process(apm, buf, 0);
- EXPECT_EQ(2, webrtc_apm_process_stream_f_called);
-
- float_buffer_destroy(&buf);
- cras_apm_list_destroy(list);
- cras_apm_list_deinit();
-}
-
-TEST(ApmList, ApmProcessReverseData) {
- struct cras_apm* apm;
- struct cras_audio_format fmt;
- struct float_buffer* buf;
- float* const* rp;
- unsigned int nread;
- struct cras_iodev fake_iodev;
-
- fmt.num_channels = 2;
- fmt.frame_rate = 48000;
- fmt.format = SND_PCM_FORMAT_S16_LE;
-
- fake_iodev.direction = CRAS_STREAM_OUTPUT;
- device_enabled_callback_val = NULL;
- ext_dsp_module_value = NULL;
- webrtc_apm_process_reverse_stream_f_called = 0;
-
- cras_apm_list_init("");
- EXPECT_NE((void*)NULL, device_enabled_callback_val);
-
- device_enabled_callback_val(&fake_iodev, NULL);
- EXPECT_NE((void*)NULL, ext_dsp_module_value);
- EXPECT_NE((void*)NULL, ext_dsp_module_value->ports);
-
- buf = float_buffer_create(500, 2);
- float_buffer_written(buf, 500);
- nread = 500;
- rp = float_buffer_read_pointer(buf, 0, &nread);
-
- for (int i = 0; i < buf->num_channels; i++)
- ext_dsp_module_value->ports[i] = rp[i];
-
- ext_dsp_module_value->configure(ext_dsp_module_value, 800, 2, 48000);
- ext_dsp_module_value->run(ext_dsp_module_value, 500);
- EXPECT_EQ(0, webrtc_apm_process_reverse_stream_f_called);
-
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
-
- apm = cras_apm_list_add_apm(list, dev_ptr, &fmt, 1);
- cras_apm_list_start_apm(list, dev_ptr);
-
- ext_dsp_module_value->run(ext_dsp_module_value, 250);
- EXPECT_EQ(0, webrtc_apm_process_reverse_stream_f_called);
-
- ext_dsp_module_value->run(ext_dsp_module_value, 250);
- EXPECT_EQ(1, webrtc_apm_process_reverse_stream_f_called);
-
- float_buffer_destroy(&buf);
- cras_apm_list_destroy(list);
- cras_apm_list_deinit();
-}
-
-TEST(ApmList, StreamAddToAlreadyOpenedDev) {
- struct cras_audio_format fmt;
- struct cras_apm *apm1, *apm2;
-
- fmt.num_channels = 2;
- fmt.frame_rate = 48000;
- fmt.format = SND_PCM_FORMAT_S16_LE;
-
- cras_apm_list_init("");
-
- webrtc_apm_create_called = 0;
- list = cras_apm_list_create(stream_ptr, APM_ECHO_CANCELLATION);
- EXPECT_NE((void*)NULL, list);
-
- apm1 = cras_apm_list_add_apm(list, dev_ptr, &fmt, 1);
- EXPECT_EQ(1, webrtc_apm_create_called);
- EXPECT_NE((void*)NULL, apm1);
-
- apm2 = cras_apm_list_add_apm(list, dev_ptr, &fmt, 1);
- EXPECT_EQ(1, webrtc_apm_create_called);
- EXPECT_EQ(apm1, apm2);
-
- cras_apm_list_destroy(list);
- cras_apm_list_deinit();
-}
-
-extern "C" {
-int cras_iodev_list_set_device_enabled_callback(
- device_enabled_callback_t enabled_cb,
- device_disabled_callback_t disabled_cb,
- void* cb_data) {
- device_enabled_callback_val = enabled_cb;
- return 0;
-}
-struct cras_iodev* cras_iodev_list_get_first_enabled_iodev(
- enum CRAS_STREAM_DIRECTION direction) {
- return &fake_iodev;
-}
-void cras_iodev_set_ext_dsp_module(struct cras_iodev* iodev,
- struct ext_dsp_module* ext) {
- ext_dsp_module_value = ext;
-}
-bool cras_iodev_is_aec_use_case(const struct cras_ionode* node) {
- return cras_iodev_is_aec_use_case_ret;
-}
-struct cras_audio_area* cras_audio_area_create(int num_channels) {
- return &fake_audio_area;
-}
-
-void cras_audio_area_destroy(struct cras_audio_area* area) {}
-void cras_audio_area_config_channels(struct cras_audio_area* area,
- const struct cras_audio_format* fmt) {}
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {}
-void dsp_util_interleave(float* const* input,
- int16_t* output,
- int channels,
- snd_pcm_format_t format,
- int frames) {
- dsp_util_interleave_frames = frames;
-}
-struct aec_config* aec_config_get(const char* device_config_dir) {
- return NULL;
-}
-void aec_config_dump(struct aec_config* config) {}
-struct apm_config* apm_config_get(const char* device_config_dir) {
- return NULL;
-}
-void apm_config_dump(struct apm_config* config) {}
-webrtc_apm webrtc_apm_create(unsigned int num_channels,
- unsigned int frame_rate,
- dictionary* aec_ini,
- dictionary* apm_ini) {
- webrtc_apm_create_called++;
- webrtc_apm_create_aec_ini_val = aec_ini;
- webrtc_apm_create_apm_ini_val = apm_ini;
- return reinterpret_cast<webrtc_apm>(0x11);
-}
-void webrtc_apm_dump_configs(dictionary* aec_ini, dictionary* apm_ini) {}
-void webrtc_apm_destroy(webrtc_apm apm) {
- return;
-}
-int webrtc_apm_process_stream_f(webrtc_apm ptr,
- int num_channels,
- int rate,
- float* const* data) {
- webrtc_apm_process_stream_f_called++;
- return 0;
-}
-
-int webrtc_apm_process_reverse_stream_f(webrtc_apm ptr,
- int num_channels,
- int rate,
- float* const* data) {
- webrtc_apm_process_reverse_stream_f_called++;
- return 0;
-}
-int webrtc_apm_aec_dump(webrtc_apm ptr,
- void** work_queue,
- int start,
- FILE* handle) {
- return 0;
-}
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/array_unittest.cc b/cras/src/tests/array_unittest.cc
deleted file mode 100644
index e95cd713..00000000
--- a/cras/src/tests/array_unittest.cc
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "array.h"
-
-#include <gtest/gtest.h>
-
-namespace {
-
-struct point {
- int x, y;
-};
-
-DECLARE_ARRAY_TYPE(double, double_array);
-DECLARE_ARRAY_TYPE(struct point, point_array);
-
-TEST(ArrayTest, Basic) {
- double_array a = ARRAY_INIT;
-
- /* create an array {1.0, 2.0} */
- ARRAY_APPEND(&a, 1.0);
- double* p = ARRAY_APPEND_ZERO(&a);
- EXPECT_EQ(0.0, *p);
- *p = 2.0;
-
- EXPECT_EQ(2, ARRAY_COUNT(&a));
- EXPECT_EQ(2, a.count);
- EXPECT_GE(a.size, 2);
- EXPECT_EQ(1.0, *ARRAY_ELEMENT(&a, 0));
- EXPECT_EQ(2.0, *ARRAY_ELEMENT(&a, 1));
- EXPECT_EQ(1.0, a.element[0]);
- EXPECT_EQ(2.0, a.element[1]);
- EXPECT_EQ(0, ARRAY_FIND(&a, 1.0));
- EXPECT_EQ(1, ARRAY_FIND(&a, 2.0));
- EXPECT_EQ(-1, ARRAY_FIND(&a, 0.0));
- EXPECT_EQ(0, ARRAY_INDEX(&a, ARRAY_ELEMENT(&a, 0)));
- EXPECT_EQ(1, ARRAY_INDEX(&a, ARRAY_ELEMENT(&a, 1)));
-
- ARRAY_FREE(&a);
- EXPECT_EQ(0, ARRAY_COUNT(&a));
- EXPECT_EQ(0, a.count);
- EXPECT_EQ(0, a.size);
- EXPECT_EQ(NULL, a.element);
-}
-
-TEST(ArrayTest, StructElement) {
- struct point p = {1, 2};
- struct point q = {3, 4};
- point_array a = ARRAY_INIT;
-
- ARRAY_APPEND(&a, p);
- ARRAY_APPEND(&a, q);
-
- EXPECT_EQ(2, ARRAY_COUNT(&a));
- EXPECT_EQ(1, ARRAY_ELEMENT(&a, 0)->x);
- EXPECT_EQ(2, ARRAY_ELEMENT(&a, 0)->y);
- EXPECT_EQ(3, a.element[1].x);
- EXPECT_EQ(4, a.element[1].y);
- ARRAY_ELEMENT(&a, 1)->y = 5;
- EXPECT_EQ(5, a.element[1].y);
-
- ARRAY_FREE(&a);
- EXPECT_EQ(0, ARRAY_COUNT(&a));
- EXPECT_EQ(0, a.size);
- EXPECT_EQ(NULL, a.element);
-}
-
-TEST(ArrayTest, AppendZeroStruct) {
- point_array a = ARRAY_INIT;
- struct point *p, *q;
-
- p = ARRAY_APPEND_ZERO(&a);
- EXPECT_EQ(0, p->x);
- EXPECT_EQ(0, p->y);
- EXPECT_EQ(1, a.count);
-
- q = ARRAY_APPEND_ZERO(&a);
- EXPECT_EQ(0, q->x);
- EXPECT_EQ(0, q->y);
- EXPECT_EQ(2, a.count);
-
- ARRAY_FREE(&a);
-}
-
-TEST(ArrayTest, ForLoop) {
- int i;
- double* p;
- double_array a = ARRAY_INIT;
-
- for (i = 0; i < 100; i++) {
- ARRAY_APPEND(&a, i * 2);
- }
-
- int expectedIndex = 0;
- double expectedValue = 0;
- ARRAY_ELEMENT_FOREACH (&a, i, p) {
- EXPECT_EQ(expectedIndex, i);
- EXPECT_EQ(expectedValue, *p);
- expectedIndex++;
- expectedValue += 2;
- }
- EXPECT_EQ(expectedIndex, 100);
-
- ARRAY_FREE(&a);
- EXPECT_EQ(0, a.count);
- EXPECT_EQ(0, a.size);
- EXPECT_EQ(NULL, a.element);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/audio_area_unittest.cc b/cras/src/tests/audio_area_unittest.cc
deleted file mode 100644
index 091d8dec..00000000
--- a/cras/src/tests/audio_area_unittest.cc
+++ /dev/null
@@ -1,340 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_audio_area.h"
-#include "cras_audio_format.h"
-}
-
-static const int8_t stereo[CRAS_CH_MAX] = {
- 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-};
-static const int8_t mono[CRAS_CH_MAX] = {
- -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1,
-};
-static const int8_t kb_mic[CRAS_CH_MAX] = {
- 0, 1, -1, -1, 2, -1, -1, -1, -1, -1, -1,
-};
-
-static uint16_t buf1[32];
-static uint16_t buf2[32];
-struct cras_audio_area* a1;
-struct cras_audio_area* a2;
-
-namespace {
-
-TEST(AudioArea, CopyAudioArea) {
- struct cras_audio_format fmt;
- int i;
-
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = stereo[i];
-
- a1 = cras_audio_area_create(2);
- a2 = cras_audio_area_create(2);
- cras_audio_area_config_channels(a1, &fmt);
- cras_audio_area_config_channels(a2, &fmt);
- cras_audio_area_config_buf_pointers(a1, &fmt, (uint8_t*)buf1);
- cras_audio_area_config_buf_pointers(a2, &fmt, (uint8_t*)buf2);
- a1->frames = 16;
- a2->frames = 16;
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand();
- cras_audio_area_copy(a1, 0, &fmt, a2, 0, 1.0);
- for (i = 0; i < 32; i++)
- EXPECT_EQ(buf1[i], buf2[i]);
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-TEST(AudioArea, CopyAudioAreaWithGain) {
- struct cras_audio_format fmt;
- int i;
- /* Check a gain of 10x can be applied. */
- float gain_scaler = 10.0f;
-
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = stereo[i];
-
- a1 = cras_audio_area_create(2);
- a2 = cras_audio_area_create(2);
- cras_audio_area_config_channels(a1, &fmt);
- cras_audio_area_config_channels(a2, &fmt);
- cras_audio_area_config_buf_pointers(a1, &fmt, (uint8_t*)buf1);
- cras_audio_area_config_buf_pointers(a2, &fmt, (uint8_t*)buf2);
- a1->frames = 16;
- a2->frames = 16;
-
- memset(buf1, 0, 32 * 2);
- /* Let src has some samples smaller than 32768/10 and some samples larger than
- * 32768/10 to test clipping. */
- for (i = 0; i < 16; i++)
- buf2[i] = rand() % 3270;
- for (i = 17; i < 32; i++)
- buf2[i] = 3280 + rand() % 3200;
- cras_audio_area_copy(a1, 0, &fmt, a2, 0, gain_scaler);
- for (i = 0; i < 32; i++) {
- int32_t expected_value = buf2[i] * gain_scaler;
- if (expected_value > INT16_MAX)
- expected_value = INT16_MAX;
- EXPECT_EQ(buf1[i], expected_value);
- }
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-TEST(AudioArea, CopyAudioAreaOffset) {
- struct cras_audio_format fmt;
- int i;
-
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = stereo[i];
-
- a1 = cras_audio_area_create(2);
- a2 = cras_audio_area_create(2);
- cras_audio_area_config_channels(a1, &fmt);
- cras_audio_area_config_channels(a2, &fmt);
- cras_audio_area_config_buf_pointers(a1, &fmt, (uint8_t*)buf1);
- cras_audio_area_config_buf_pointers(a2, &fmt, (uint8_t*)buf2);
- a1->frames = 16;
- a2->frames = 14;
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand();
- cras_audio_area_copy(a1, 2, &fmt, a2, 0, 1.0);
- EXPECT_EQ(buf1[0], 0);
- EXPECT_EQ(buf1[1], 0);
- EXPECT_EQ(buf1[2], 0);
- EXPECT_EQ(buf1[3], 0);
- for (i = 4; i < 32; i++)
- EXPECT_EQ(buf1[i], buf2[i - 4]);
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-TEST(AudioArea, CopyAudioAreaOffsetLimit) {
- struct cras_audio_format fmt;
- int i;
-
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = stereo[i];
-
- a1 = cras_audio_area_create(2);
- a2 = cras_audio_area_create(2);
- cras_audio_area_config_channels(a1, &fmt);
- cras_audio_area_config_channels(a2, &fmt);
- cras_audio_area_config_buf_pointers(a1, &fmt, (uint8_t*)buf1);
- cras_audio_area_config_buf_pointers(a2, &fmt, (uint8_t*)buf2);
- a1->frames = 14;
- a2->frames = 14;
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand();
- cras_audio_area_copy(a1, 2, &fmt, a2, 0, 1.0);
- EXPECT_EQ(buf1[0], 0);
- EXPECT_EQ(buf1[1], 0);
- EXPECT_EQ(buf1[2], 0);
- EXPECT_EQ(buf1[3], 0);
- for (i = 4; i < 28; i++)
- EXPECT_EQ(buf1[i], buf2[i - 4]);
- EXPECT_EQ(buf1[28], 0);
- EXPECT_EQ(buf1[29], 0);
- EXPECT_EQ(buf1[30], 0);
- EXPECT_EQ(buf1[31], 0);
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-TEST(AudioArea, CopyMonoToStereo) {
- struct cras_audio_format dst_fmt;
- struct cras_audio_format src_fmt;
- int i;
-
- dst_fmt.num_channels = 2;
- dst_fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- dst_fmt.channel_layout[i] = stereo[i];
- a1 = cras_audio_area_create(2);
- a1->frames = 16;
- cras_audio_area_config_channels(a1, &dst_fmt);
- cras_audio_area_config_buf_pointers(a1, &dst_fmt, (uint8_t*)buf1);
-
- src_fmt.num_channels = 1;
- src_fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- src_fmt.channel_layout[i] = mono[i];
- a2 = cras_audio_area_create(1);
- a2->frames = 16;
- cras_audio_area_config_channels(a2, &src_fmt);
- cras_audio_area_config_buf_pointers(a2, &src_fmt, (uint8_t*)buf2);
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand();
- cras_audio_area_copy(a1, 0, &dst_fmt, a2, 0, 1.0);
- for (i = 0; i < 16; i++) {
- EXPECT_EQ(buf1[i * 2], buf2[i]);
- EXPECT_EQ(buf1[i * 2 + 1], buf2[i]);
- }
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-TEST(AudioArea, CopyStereoToMono) {
- struct cras_audio_format fmt;
- int i;
-
- fmt.num_channels = 1;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = mono[i];
- a1 = cras_audio_area_create(1);
- a1->frames = 16;
- cras_audio_area_config_channels(a1, &fmt);
- cras_audio_area_config_buf_pointers(a1, &fmt, (uint8_t*)buf1);
-
- fmt.num_channels = 2;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = stereo[i];
- a2 = cras_audio_area_create(2);
- a2->frames = 16;
- cras_audio_area_config_channels(a2, &fmt);
- cras_audio_area_config_buf_pointers(a2, &fmt, (uint8_t*)buf2);
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand() % 10000;
- cras_audio_area_copy(a1, 0, &fmt, a2, 0, 1.0);
- for (i = 0; i < 16; i++)
- EXPECT_EQ(buf1[i], buf2[i * 2] + buf2[i * 2 + 1]);
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-TEST(AudioArea, KeyboardMicCopyStereo) {
- struct cras_audio_format fmt;
- int i;
-
- fmt.num_channels = 3;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = kb_mic[i];
- a1 = cras_audio_area_create(3);
- a1->frames = 10;
- cras_audio_area_config_channels(a1, &fmt);
- cras_audio_area_config_buf_pointers(a1, &fmt, (uint8_t*)buf1);
-
- fmt.num_channels = 2;
- for (i = 0; i < CRAS_CH_MAX; i++)
- fmt.channel_layout[i] = stereo[i];
- a2 = cras_audio_area_create(2);
- a2->frames = 10;
- cras_audio_area_config_channels(a2, &fmt);
- cras_audio_area_config_buf_pointers(a2, &fmt, (uint8_t*)buf2);
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand();
- cras_audio_area_copy(a1, 0, &fmt, a2, 0, 1.0);
- for (i = 0; i < 10; i++) {
- EXPECT_EQ(buf1[i * 3], buf2[i * 2]);
- EXPECT_EQ(buf1[i * 3 + 1], buf2[i * 2 + 1]);
- EXPECT_EQ(buf1[i * 3 + 2], 0);
- }
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-TEST(AudioArea, KeyboardMicCopyFrontCenter) {
- struct cras_audio_format dst_fmt;
- struct cras_audio_format src_fmt;
- int i;
-
- dst_fmt.num_channels = 3;
- dst_fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- dst_fmt.channel_layout[i] = kb_mic[i];
- a1 = cras_audio_area_create(3);
- a1->frames = 10;
- cras_audio_area_config_channels(a1, &dst_fmt);
- cras_audio_area_config_buf_pointers(a1, &dst_fmt, (uint8_t*)buf1);
-
- /* Test 2 channels area with only front center in layout. */
- src_fmt.num_channels = 2;
- src_fmt.format = SND_PCM_FORMAT_S16_LE;
- for (i = 0; i < CRAS_CH_MAX; i++)
- src_fmt.channel_layout[i] = -1;
- src_fmt.channel_layout[CRAS_CH_FC] = 0;
- a2 = cras_audio_area_create(2);
- a2->frames = 10;
- cras_audio_area_config_channels(a2, &src_fmt);
- cras_audio_area_config_buf_pointers(a2, &src_fmt, (uint8_t*)buf2);
-
- memset(buf1, 0, 32 * 2);
- for (i = 0; i < 32; i++)
- buf2[i] = rand();
- cras_audio_area_copy(a1, 0, &dst_fmt, a2, 0, 1.0);
- for (i = 0; i < 10; i++) {
- EXPECT_EQ(buf1[i * 3], 0);
- EXPECT_EQ(buf1[i * 3 + 1], 0);
- EXPECT_EQ(buf1[i * 3 + 2], buf2[i * 2]);
- }
-
- cras_audio_area_destroy(a1);
- cras_audio_area_destroy(a2);
-}
-
-} // namespace
-
-extern "C" {
-
-void cras_mix_add_scale_stride(snd_pcm_format_t fmt,
- uint8_t* dst,
- uint8_t* src,
- unsigned int count,
- unsigned int dst_stride,
- unsigned int src_stride,
- float scaler) {
- unsigned int i;
-
- for (i = 0; i < count; i++) {
- int32_t sum;
- sum = *(int16_t*)dst + *(int16_t*)src * scaler;
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- *(int16_t*)dst = sum;
- dst += dst_stride;
- src += src_stride;
- }
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/audio_format_unittest.cc b/cras/src/tests/audio_format_unittest.cc
deleted file mode 100644
index f03f6878..00000000
--- a/cras/src/tests/audio_format_unittest.cc
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-extern "C" {
-// Test static functions
-#include "cras_audio_format.c"
-}
-
-namespace {
-
-class ChannelConvMtxTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- int i;
- in_fmt = cras_audio_format_create(SND_PCM_FORMAT_S16_LE, 44100, 6);
- out_fmt = cras_audio_format_create(SND_PCM_FORMAT_S16_LE, 44100, 6);
- for (i = 0; i < CRAS_CH_MAX; i++) {
- in_fmt->channel_layout[i] = -1;
- out_fmt->channel_layout[i] = -1;
- }
- }
-
- virtual void TearDown() {
- cras_audio_format_destroy(in_fmt);
- cras_audio_format_destroy(out_fmt);
- if (conv_mtx)
- cras_channel_conv_matrix_destroy(conv_mtx, 6);
- }
-
- struct cras_audio_format* in_fmt;
- struct cras_audio_format* out_fmt;
- float** conv_mtx;
-};
-
-TEST_F(ChannelConvMtxTestSuite, MatrixCreateSuccess) {
- in_fmt->channel_layout[0] = 5;
- in_fmt->channel_layout[1] = 4;
- in_fmt->channel_layout[2] = 3;
- in_fmt->channel_layout[3] = 2;
- in_fmt->channel_layout[4] = 1;
- in_fmt->channel_layout[5] = 0;
-
- out_fmt->channel_layout[0] = 0;
- out_fmt->channel_layout[1] = 1;
- out_fmt->channel_layout[2] = 2;
- out_fmt->channel_layout[3] = 3;
- out_fmt->channel_layout[4] = 4;
- out_fmt->channel_layout[5] = 5;
-
- conv_mtx = cras_channel_conv_matrix_create(in_fmt, out_fmt);
- ASSERT_NE(conv_mtx, (void*)NULL);
-}
-
-TEST_F(ChannelConvMtxTestSuite, MatrixCreateFail) {
- in_fmt->channel_layout[0] = 5;
- in_fmt->channel_layout[1] = 4;
- in_fmt->channel_layout[2] = 3;
- in_fmt->channel_layout[3] = 2;
- in_fmt->channel_layout[4] = 1;
- in_fmt->channel_layout[5] = 0;
-
- out_fmt->channel_layout[0] = 0;
- out_fmt->channel_layout[1] = 1;
- out_fmt->channel_layout[2] = 2;
- out_fmt->channel_layout[3] = 3;
- out_fmt->channel_layout[4] = 4;
- out_fmt->channel_layout[7] = 5;
-
- conv_mtx = cras_channel_conv_matrix_create(in_fmt, out_fmt);
- ASSERT_EQ(conv_mtx, (void*)NULL);
-}
-
-TEST_F(ChannelConvMtxTestSuite, SLSRToRRRL) {
- in_fmt->channel_layout[0] = 0;
- in_fmt->channel_layout[1] = 1;
- in_fmt->channel_layout[4] = 2;
- in_fmt->channel_layout[5] = 3;
- /* Input format uses SL and SR*/
- in_fmt->channel_layout[6] = 4;
- in_fmt->channel_layout[7] = 5;
-
- out_fmt->channel_layout[0] = 0;
- out_fmt->channel_layout[1] = 1;
- /* Output format uses RR and RR */
- out_fmt->channel_layout[2] = 4;
- out_fmt->channel_layout[3] = 5;
- out_fmt->channel_layout[4] = 2;
- out_fmt->channel_layout[5] = 3;
-
- conv_mtx = cras_channel_conv_matrix_create(in_fmt, out_fmt);
- ASSERT_NE(conv_mtx, (void*)NULL);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/audio_test_gui.py b/cras/src/tests/audio_test_gui.py
deleted file mode 100644
index 6ee401be..00000000
--- a/cras/src/tests/audio_test_gui.py
+++ /dev/null
@@ -1,266 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2016 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-"""Script functions as a web app and wrapper for the cras_router program."""
-
-import re
-import subprocess
-import logging
-import cherrypy
-
-# Node Format: [Stable_Id, ID, Vol, Plugged, L/R_swapped, Time, Type, Name]
-ID_INDEX = 1
-PLUGGED_INDEX = 3
-TYPE_INDEX = 6
-NAME_INDEX = 7
-
-
-def get_plugged_nodes(plugged_nodes, lines, is_input):
- start_str = 'Input Nodes:' if is_input else 'Output Nodes:'
- end_str = 'Attached clients:' if is_input else 'Input Devices:'
- for i in range(lines.index(start_str) + 2,
- lines.index(end_str)):
- node = filter(None, re.split(r'\s+|\*+', lines[i]))
- # check for nodes that are plugged nodes and loopback
- if node[PLUGGED_INDEX] == 'yes' and node[TYPE_INDEX][:4] != 'POST':
- key = node[TYPE_INDEX] + ' ' + node[NAME_INDEX]
- plugged_nodes[key] = node[ID_INDEX]
-
-
-class CrasRouterTest(object):
- """Cherrypy class that builds and runs the HTML for audio testing tool."""
-
- @cherrypy.expose
- def index(self):
- """Builds up and displays the html for the audio testing tool.
-
- Returns:
- html that was built up based on plugged audio devices.
- """
-
- # Stop program if currently being run.
- if 'process' in cherrypy.session:
- print 'Existing process'
- # If return code is None process is still running
- if cherrypy.session['process'].poll() is None:
- print 'Killing existing process'
- cherrypy.session['process'].kill()
- else:
- print 'Process already finished'
-
- html = """<html>
- <head>
- <title>Audio Test</title>
- </head>
- <body style="background-color:lightgrey;">
- <font color="red">
- <h1>Audio Closed Loop Test</h1>
- <font style="color:rgb(100, 149, 237)">
- <h3>
- <form name="routerOptions" method="get"
- onsubmit="return validateForm()" action="start_test">
- <h2>Input Type</h2>
- """
- dump = subprocess.check_output(['cras_test_client', '--dump_s'])
- if not dump:
- return 'Could not connect to server'
- dump_lines = dump.split('\n')
- input_plugged_nodes = {}
- get_plugged_nodes(input_plugged_nodes, dump_lines, True)
- for name, node_id in input_plugged_nodes.items():
- line = '<input type ="radio" name="input_type" value="'
- line += node_id + '">' +name + '<br>\n'
- html += line
-
- html += """<input type ="radio" id="i0" name="input_type"
- value="file">File<br>
- <div id="input_file" style="display:none;">
- Filename <input type="text" name="input_file"><br><br>
- </div>
- <h2>Output Type</h2>"""
- output_plugged_nodes = {}
- get_plugged_nodes(output_plugged_nodes, dump_lines, False)
- for name, node_id in output_plugged_nodes.items():
- line = '<input type ="radio" name="output_type" value="'
- line = line + node_id + '">' +name + '<br>\n'
- html += line
-
- html += """<input type ="radio" name="output_type"
- value="file">File<br>
- <div id="output_file" style="display:none;">
- Filename <input type="text" name="output_file">
- </div><br>
- <h2>Sample Rate</h2>
- <input type="radio" name="rate" id="sample_rate1" value=48000
- checked>48,000 Hz<br>
- <input type="radio" name="rate" id="sample_rate0" value=44100>
- 44,100 Hz<br><br>
- <button type="submit" onclick="onOff(this)">Test!</button>
- </h3>
- </form>
- </font>
- </body>
- </html>
- """
- javascript = """
- <script>
- /* Does basic error checking to make sure user doesn't
- * give bad options to the router.
- */
- function validateForm(){
- var input_type =
- document.forms['routerOptions']['input_type'].value;
- var output_type =
- document.forms['routerOptions']['output_type'].value;
- if (input_type == '' || output_type == '') {
- alert('Please select an input and output type.');
- return false;
- }
- if (input_type == 'file' && output_type == 'file') {
- alert('Input and Output Types cannot both be files!');
- return false;
- }
- //check if filename is valid
- if (input_type == 'file') {
- var input_file =
- document.forms['routerOptions']['input_file'].value;
- if (input_file == '') {
- alert('Please enter a file name');
- return false;
- }
- }
- if (output_type == 'file') {
- var output_file =
- document.forms['routerOptions']['output_file'].value;
- if (output_file == '') {
- alert('Please enter a file name');
- return false;
- }
- }
- }
-
- function show_filename(radio, file_elem) {
- for(var i =0; i < radio.length; i++){
- radio[i].onclick = function(){
- if (this.value == 'file') {
- file_elem.style.display = 'block';
- } else {
- file_elem.style.display = 'none';
- }
- }
- }
- }
- /* Loops determine if filename field should be shown */
- var input_type_rad =
- document.forms['routerOptions']['input_type'];
- var input_file_elem =
- document.getElementById('input_file');
- var output_type_rad =
- document.forms['routerOptions']['output_type'];
- var output_file_elem =
- document.getElementById('output_file');
- show_filename(input_type_rad, input_file_elem);
- show_filename(output_type_rad, output_file_elem);
- </script>"""
- html += javascript
- return html
-
- @cherrypy.expose
- def start_test(self, input_type, output_type, input_file='',
- output_file='', rate=48000):
- """Capture audio from the input_type and plays it back to the output_type.
-
- Args:
- input_type: Node id for the selected input or 'file' for files
- output_type: Node id for the selected output or 'file' for files
- input_file: Path of the input if 'file' is input type
- output_file: Path of the output if 'file' is output type
- rate: Sample rate for the test.
-
- Returns:
- html for the tesing in progress page.
- """
- print 'Beginning test'
- if input_type == 'file' or output_type == 'file':
- command = ['cras_test_client']
- else:
- command = ['cras_router']
- if input_type == 'file':
- command.append('--playback_file')
- command.append(str(input_file))
- else:
- set_input = ['cras_test_client', '--select_input', str(input_type)]
- if subprocess.check_call(set_input):
- print 'Error setting input'
- if output_type == 'file':
- command.append('--capture_file')
- command.append(str(output_file))
- else:
- set_output = ['cras_test_client', '--select_output', str(output_type)]
- if subprocess.check_call(set_output):
- print 'Error setting output'
- command.append('--rate')
- command.append(str(rate))
- print 'Running commmand: ' + str(command)
- p = subprocess.Popen(command)
- cherrypy.session['process'] = p
- return """
- <html>
- <head>
- <style type="text/css">
- body {
- background-color: #DC143C;
- }
- #test {
- color: white;
- text-align: center;
- }
- </style>
- <title>Running test</title>
- </head>
- <body>
- <div id="test">
- <h1>Test in progress</h1>
- <form action="index"><!--Go back to orginal page-->
- <button type="submit" id="stop">Click to stop</button>
- </form>
- <h2>Time Elapsed<br>
- <time id="elapsed_time">00:00</time>
- </h2>
- </div>
- </body>
- </html>
- <script type="text/javascript">
- var seconds = 0;
- var minutes = 0;
- var elapsed_time;
- var start_time = new Date().getTime();
- function secondPassed(){
- var time = new Date().getTime() - start_time;
- elapsed_time = Math.floor(time / 100) / 10;
- minutes = Math.floor(elapsed_time / 60);
- seconds = Math.floor(elapsed_time % 60);
- var seconds_str = (seconds < 10 ? '0' + seconds: '' + seconds);
- var minutes_str = (minutes < 10 ? '0' + minutes: '' + minutes);
- var time_passed = minutes_str + ':' + seconds_str;
- document.getElementById("elapsed_time").textContent = time_passed;
- }
- //have time tic every second
- var timer = setInterval(secondPassed, 1000);
- var stop = document.getElementById("stop");
- stop.onclick = function(){
- seconds = 0;
- minutes = 0;
- clearInterval(timer);
- }
- </script>"""
-
-if __name__ == '__main__':
- conf = {
- '/': {
- 'tools.sessions.on': True
- }
- }
- cherrypy.quickstart(CrasRouterTest(), '/', conf)
diff --git a/cras/src/tests/audio_thread_monitor_unittest.cc b/cras/src/tests/audio_thread_monitor_unittest.cc
deleted file mode 100644
index 9e1de636..00000000
--- a/cras/src/tests/audio_thread_monitor_unittest.cc
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2018 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_audio_thread_monitor.c"
-#include "cras_main_message.h"
-}
-
-// Function call counters
-static int cras_system_state_add_snapshot_called;
-static int audio_thread_dump_thread_info_called;
-
-// Stub data
-static enum CRAS_MAIN_MESSAGE_TYPE type_set;
-struct cras_audio_thread_event_message message;
-
-void ResetStubData() {
- cras_system_state_add_snapshot_called = 0;
- audio_thread_dump_thread_info_called = 0;
- type_set = (enum CRAS_MAIN_MESSAGE_TYPE)999;
- message.event_type = (enum CRAS_AUDIO_THREAD_EVENT_TYPE)999;
-}
-
-namespace {
-
-class AudioThreadMonitorTestSuite : public testing::Test {
- protected:
- virtual void SetUp() { ResetStubData(); }
-
- virtual void TearDown() {}
-};
-
-TEST_F(AudioThreadMonitorTestSuite, Init) {
- cras_audio_thread_monitor_init();
- EXPECT_EQ(type_set, CRAS_MAIN_AUDIO_THREAD_EVENT);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, Busyloop) {
- cras_audio_thread_event_busyloop();
- EXPECT_EQ(message.event_type, AUDIO_THREAD_EVENT_BUSYLOOP);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, Debug) {
- cras_audio_thread_event_debug();
- EXPECT_EQ(message.event_type, AUDIO_THREAD_EVENT_DEBUG);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, Underrun) {
- cras_audio_thread_event_underrun();
- EXPECT_EQ(message.event_type, AUDIO_THREAD_EVENT_UNDERRUN);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, SevereUnderrun) {
- cras_audio_thread_event_severe_underrun();
- EXPECT_EQ(message.event_type, AUDIO_THREAD_EVENT_SEVERE_UNDERRUN);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, DropSamples) {
- cras_audio_thread_event_drop_samples();
- EXPECT_EQ(message.event_type, AUDIO_THREAD_EVENT_DROP_SAMPLES);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, TakeSnapshot) {
- take_snapshot(AUDIO_THREAD_EVENT_DEBUG);
- EXPECT_EQ(cras_system_state_add_snapshot_called, 1);
- EXPECT_EQ(audio_thread_dump_thread_info_called, 1);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, EventHandlerDoubleCall) {
- struct cras_audio_thread_event_message msg;
- msg.event_type = AUDIO_THREAD_EVENT_DEBUG;
- handle_audio_thread_event_message((struct cras_main_message*)&msg, NULL);
- EXPECT_EQ(cras_system_state_add_snapshot_called, 1);
- EXPECT_EQ(audio_thread_dump_thread_info_called, 1);
-
- // take_snapshot shouldn't be called since the time interval is short
- handle_audio_thread_event_message((struct cras_main_message*)&msg, NULL);
- EXPECT_EQ(cras_system_state_add_snapshot_called, 1);
- EXPECT_EQ(audio_thread_dump_thread_info_called, 1);
-}
-
-TEST_F(AudioThreadMonitorTestSuite, EventHandlerIgnoreInvalidEvent) {
- struct cras_audio_thread_event_message msg;
- msg.event_type = (enum CRAS_AUDIO_THREAD_EVENT_TYPE)999;
- handle_audio_thread_event_message((struct cras_main_message*)&msg, NULL);
- EXPECT_EQ(cras_system_state_add_snapshot_called, 0);
- EXPECT_EQ(audio_thread_dump_thread_info_called, 0);
-}
-
-extern "C" {
-
-void cras_system_state_add_snapshot(
- struct cras_audio_thread_snapshot* snapshot) {
- cras_system_state_add_snapshot_called++;
-}
-
-struct audio_thread* cras_iodev_list_get_audio_thread() {
- return reinterpret_cast<struct audio_thread*>(0xff);
-}
-
-int audio_thread_dump_thread_info(struct audio_thread* thread,
- struct audio_debug_info* info) {
- audio_thread_dump_thread_info_called++;
- return 0;
-}
-
-int cras_main_message_add_handler(enum CRAS_MAIN_MESSAGE_TYPE type,
- cras_message_callback callback,
- void* callback_data) {
- type_set = type;
- return 0;
-}
-
-int cras_main_message_send(struct cras_main_message* msg) {
- message = *(struct cras_audio_thread_event_message*)msg;
- return 0;
-}
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- int rc = RUN_ALL_TESTS();
-
- return rc;
-}
diff --git a/cras/src/tests/audio_thread_unittest.cc b/cras/src/tests/audio_thread_unittest.cc
deleted file mode 100644
index 93045e0b..00000000
--- a/cras/src/tests/audio_thread_unittest.cc
+++ /dev/null
@@ -1,1475 +0,0 @@
-// Copyright 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-extern "C" {
-#include "audio_thread.c"
-
-#include "cras_audio_area.h"
-#include "metrics_stub.h"
-}
-
-#include <gtest/gtest.h>
-
-#include <map>
-
-#define MAX_CALLS 10
-#define BUFFER_SIZE 8192
-#define FIRST_CB_LEVEL 480
-
-static int cras_audio_thread_event_busyloop_called;
-static int cras_audio_thread_event_severe_underrun_called;
-static unsigned int cras_rstream_dev_offset_called;
-static unsigned int cras_rstream_dev_offset_ret[MAX_CALLS];
-static const struct cras_rstream*
- cras_rstream_dev_offset_rstream_val[MAX_CALLS];
-static unsigned int cras_rstream_dev_offset_dev_id_val[MAX_CALLS];
-static unsigned int cras_rstream_dev_offset_update_called;
-static const struct cras_rstream*
- cras_rstream_dev_offset_update_rstream_val[MAX_CALLS];
-static unsigned int cras_rstream_dev_offset_update_frames_val[MAX_CALLS];
-static unsigned int cras_rstream_dev_offset_update_dev_id_val[MAX_CALLS];
-static int cras_rstream_is_pending_reply_ret;
-static int cras_iodev_all_streams_written_ret;
-static struct cras_audio_area* cras_iodev_get_output_buffer_area;
-static int cras_iodev_put_output_buffer_called;
-static unsigned int cras_iodev_put_output_buffer_nframes;
-static unsigned int cras_iodev_fill_odev_zeros_frames;
-static int dev_stream_playback_frames_ret;
-static int dev_stream_mix_called;
-static unsigned int dev_stream_update_next_wake_time_called;
-static unsigned int dev_stream_request_playback_samples_called;
-static unsigned int cras_iodev_prepare_output_before_write_samples_called;
-static enum CRAS_IODEV_STATE
- cras_iodev_prepare_output_before_write_samples_state;
-static unsigned int cras_iodev_get_output_buffer_called;
-static unsigned int cras_iodev_frames_to_play_in_sleep_called;
-static int cras_iodev_prepare_output_before_write_samples_ret;
-static int cras_iodev_reset_request_called;
-static struct cras_iodev* cras_iodev_reset_request_iodev;
-static int cras_iodev_get_valid_frames_ret;
-static int cras_iodev_output_underrun_called;
-static int cras_iodev_start_stream_called;
-static int cras_device_monitor_reset_device_called;
-static struct cras_iodev* cras_device_monitor_reset_device_iodev;
-static struct cras_iodev* cras_iodev_start_ramp_odev;
-static enum CRAS_IODEV_RAMP_REQUEST cras_iodev_start_ramp_request;
-static struct timespec clock_gettime_retspec;
-static struct timespec init_cb_ts_;
-static struct timespec sleep_interval_ts_;
-static std::map<const struct dev_stream*, struct timespec>
- dev_stream_wake_time_val;
-static int cras_device_monitor_set_device_mute_state_called;
-static int cras_iodev_is_zero_volume_ret;
-
-void ResetGlobalStubData() {
- cras_rstream_dev_offset_called = 0;
- cras_rstream_dev_offset_update_called = 0;
- cras_rstream_is_pending_reply_ret = 0;
- for (int i = 0; i < MAX_CALLS; i++) {
- cras_rstream_dev_offset_ret[i] = 0;
- cras_rstream_dev_offset_rstream_val[i] = NULL;
- cras_rstream_dev_offset_dev_id_val[i] = 0;
- cras_rstream_dev_offset_update_rstream_val[i] = NULL;
- cras_rstream_dev_offset_update_frames_val[i] = 0;
- cras_rstream_dev_offset_update_dev_id_val[i] = 0;
- }
- cras_iodev_all_streams_written_ret = 0;
- if (cras_iodev_get_output_buffer_area) {
- free(cras_iodev_get_output_buffer_area->channels[0].buf);
- free(cras_iodev_get_output_buffer_area);
- cras_iodev_get_output_buffer_area = NULL;
- }
- cras_iodev_put_output_buffer_called = 0;
- cras_iodev_put_output_buffer_nframes = 0;
- cras_iodev_fill_odev_zeros_frames = 0;
- cras_iodev_frames_to_play_in_sleep_called = 0;
- dev_stream_playback_frames_ret = 0;
- dev_stream_mix_called = 0;
- dev_stream_request_playback_samples_called = 0;
- dev_stream_update_next_wake_time_called = 0;
- cras_iodev_prepare_output_before_write_samples_called = 0;
- cras_iodev_prepare_output_before_write_samples_state = CRAS_IODEV_STATE_OPEN;
- cras_iodev_get_output_buffer_called = 0;
- cras_iodev_prepare_output_before_write_samples_ret = 0;
- cras_iodev_reset_request_called = 0;
- cras_iodev_reset_request_iodev = NULL;
- cras_iodev_get_valid_frames_ret = 0;
- cras_iodev_output_underrun_called = 0;
- cras_iodev_start_stream_called = 0;
- cras_device_monitor_reset_device_called = 0;
- cras_device_monitor_reset_device_iodev = NULL;
- cras_iodev_start_ramp_odev = NULL;
- cras_iodev_start_ramp_request = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- cras_device_monitor_set_device_mute_state_called = 0;
- cras_iodev_is_zero_volume_ret = 0;
- clock_gettime_retspec.tv_sec = 0;
- clock_gettime_retspec.tv_nsec = 0;
- dev_stream_wake_time_val.clear();
-}
-
-void SetupRstream(struct cras_rstream* rstream,
- enum CRAS_STREAM_DIRECTION direction) {
- uint32_t frame_bytes = 4;
- uint32_t used_size = 4096 * frame_bytes;
-
- memset(rstream, 0, sizeof(*rstream));
- rstream->direction = direction;
- rstream->cb_threshold = 480;
- rstream->format.frame_rate = 48000;
-
- rstream->shm = static_cast<cras_audio_shm*>(calloc(1, sizeof(*rstream->shm)));
- rstream->shm->header = static_cast<cras_audio_shm_header*>(
- calloc(1, sizeof(*rstream->shm->header)));
-
- rstream->shm->samples = static_cast<uint8_t*>(
- calloc(1, cras_shm_calculate_samples_size(used_size)));
-
- cras_shm_set_frame_bytes(rstream->shm, frame_bytes);
- cras_shm_set_used_size(rstream->shm, used_size);
-}
-
-void TearDownRstream(struct cras_rstream* rstream) {
- free(rstream->shm->samples);
- free(rstream->shm->header);
- free(rstream->shm);
-}
-
-// Test streams and devices manipulation.
-class StreamDeviceSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- thread_ = audio_thread_create();
- ResetStubData();
- }
-
- virtual void TearDown() {
- audio_thread_destroy(thread_);
- ResetGlobalStubData();
- }
-
- virtual void SetupDevice(cras_iodev* iodev,
- enum CRAS_STREAM_DIRECTION direction) {
- memset(iodev, 0, sizeof(*iodev));
- iodev->info.idx = ++device_id_;
- iodev->direction = direction;
- iodev->configure_dev = configure_dev;
- iodev->close_dev = close_dev;
- iodev->frames_queued = frames_queued;
- iodev->delay_frames = delay_frames;
- iodev->get_buffer = get_buffer;
- iodev->put_buffer = put_buffer;
- iodev->flush_buffer = flush_buffer;
- iodev->format = &format_;
- iodev->buffer_size = BUFFER_SIZE;
- iodev->min_cb_level = FIRST_CB_LEVEL;
- iodev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- format_.frame_rate = 48000;
- }
-
- void ResetStubData() {
- device_id_ = 0;
- open_dev_called_ = 0;
- close_dev_called_ = 0;
- frames_queued_ = 0;
- delay_frames_ = 0;
- audio_buffer_size_ = 0;
- cras_iodev_start_ramp_odev = NULL;
- cras_iodev_is_zero_volume_ret = 0;
- }
-
- void SetupPinnedStream(struct cras_rstream* rstream,
- enum CRAS_STREAM_DIRECTION direction,
- cras_iodev* pin_to_dev) {
- SetupRstream(rstream, direction);
- rstream->is_pinned = 1;
- rstream->pinned_dev_idx = pin_to_dev->info.idx;
- }
-
- static int configure_dev(cras_iodev* iodev) {
- open_dev_called_++;
- return 0;
- }
-
- static int close_dev(cras_iodev* iodev) {
- close_dev_called_++;
- return 0;
- }
-
- static int frames_queued(const cras_iodev* iodev, struct timespec* tstamp) {
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return frames_queued_;
- }
-
- static int delay_frames(const cras_iodev* iodev) { return delay_frames_; }
-
- static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- size_t sz = sizeof(*area_) + sizeof(struct cras_channel_area) * 2;
-
- if (audio_buffer_size_ < *num)
- *num = audio_buffer_size_;
-
- area_ = (cras_audio_area*)calloc(1, sz);
- area_->frames = *num;
- area_->num_channels = 2;
- area_->channels[0].buf = audio_buffer_;
- channel_area_set_channel(&area_->channels[0], CRAS_CH_FL);
- area_->channels[0].step_bytes = 4;
- area_->channels[1].buf = audio_buffer_ + 2;
- channel_area_set_channel(&area_->channels[1], CRAS_CH_FR);
- area_->channels[1].step_bytes = 4;
-
- *area = area_;
- return 0;
- }
-
- static int put_buffer(cras_iodev* iodev, unsigned int num) {
- free(area_);
- return 0;
- }
-
- static int flush_buffer(cras_iodev* iodev) { return 0; }
-
- int device_id_;
- struct audio_thread* thread_;
-
- static int open_dev_called_;
- static int close_dev_called_;
- static int frames_queued_;
- static int delay_frames_;
- static struct cras_audio_format format_;
- static struct cras_audio_area* area_;
- static uint8_t audio_buffer_[BUFFER_SIZE];
- static unsigned int audio_buffer_size_;
-};
-
-int StreamDeviceSuite::open_dev_called_;
-int StreamDeviceSuite::close_dev_called_;
-int StreamDeviceSuite::frames_queued_;
-int StreamDeviceSuite::delay_frames_;
-struct cras_audio_format StreamDeviceSuite::format_;
-struct cras_audio_area* StreamDeviceSuite::area_;
-uint8_t StreamDeviceSuite::audio_buffer_[8192];
-unsigned int StreamDeviceSuite::audio_buffer_size_;
-
-TEST_F(StreamDeviceSuite, AddRemoveOpenOutputDevice) {
- struct cras_iodev iodev;
- struct open_dev* adev;
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- // Check the newly added device is open.
- thread_add_open_dev(thread_, &iodev);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
- EXPECT_EQ(adev->dev, &iodev);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
- EXPECT_EQ(NULL, adev);
-}
-
-TEST_F(StreamDeviceSuite, StartRamp) {
- struct cras_iodev iodev;
- struct open_dev* adev;
- int rc;
- enum CRAS_IODEV_RAMP_REQUEST req;
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- // Check the newly added device is open.
- thread_add_open_dev(thread_, &iodev);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
- EXPECT_EQ(adev->dev, &iodev);
-
- // Ramp up for unmute.
- iodev.ramp = reinterpret_cast<cras_ramp*>(0x123);
- req = CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE;
- rc = thread_dev_start_ramp(thread_, iodev.info.idx, req);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(&iodev, cras_iodev_start_ramp_odev);
- EXPECT_EQ(req, cras_iodev_start_ramp_request);
-
- // Ramp down for mute.
- ResetStubData();
- req = CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE;
-
- rc = thread_dev_start_ramp(thread_, iodev.info.idx, req);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(&iodev, cras_iodev_start_ramp_odev);
- EXPECT_EQ(req, cras_iodev_start_ramp_request);
-
- // If device's volume percentage is zero, than ramp won't start.
- ResetStubData();
- cras_iodev_is_zero_volume_ret = 1;
- rc = thread_dev_start_ramp(thread_, iodev.info.idx, req);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(NULL, cras_iodev_start_ramp_odev);
- EXPECT_EQ(1, cras_device_monitor_set_device_mute_state_called);
-
- // Assume iodev changed to no_stream run state, it should not use ramp.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- rc = thread_dev_start_ramp(thread_, iodev.info.idx, req);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(NULL, cras_iodev_start_ramp_odev);
- EXPECT_EQ(2, cras_device_monitor_set_device_mute_state_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
-}
-
-TEST_F(StreamDeviceSuite, AddRemoveOpenInputDevice) {
- struct cras_iodev iodev;
- struct open_dev* adev;
-
- SetupDevice(&iodev, CRAS_STREAM_INPUT);
-
- // Check the newly added device is open.
- thread_add_open_dev(thread_, &iodev);
- adev = thread_->open_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adev->dev, &iodev);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, iodev.info.idx);
- adev = thread_->open_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(NULL, adev);
-}
-
-TEST_F(StreamDeviceSuite, AddRemoveMultipleOpenDevices) {
- struct cras_iodev odev;
- struct cras_iodev odev2;
- struct cras_iodev odev3;
- struct cras_iodev idev;
- struct cras_iodev idev2;
- struct cras_iodev idev3;
- struct open_dev* adev;
-
- SetupDevice(&odev, CRAS_STREAM_OUTPUT);
- SetupDevice(&odev2, CRAS_STREAM_OUTPUT);
- SetupDevice(&odev3, CRAS_STREAM_OUTPUT);
- SetupDevice(&idev, CRAS_STREAM_INPUT);
- SetupDevice(&idev2, CRAS_STREAM_INPUT);
- SetupDevice(&idev3, CRAS_STREAM_INPUT);
-
- // Add 2 open devices and check both are open.
- thread_add_open_dev(thread_, &odev);
- thread_add_open_dev(thread_, &odev2);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
- EXPECT_EQ(adev->dev, &odev);
- EXPECT_EQ(adev->next->dev, &odev2);
-
- // Remove first open device and check the second one is still open.
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, odev.info.idx);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
- EXPECT_EQ(adev->dev, &odev2);
-
- // Add another open device and check both are open.
- thread_add_open_dev(thread_, &odev3);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
- EXPECT_EQ(adev->dev, &odev2);
- EXPECT_EQ(adev->next->dev, &odev3);
-
- // Add 2 open devices and check both are open.
- thread_add_open_dev(thread_, &idev);
- thread_add_open_dev(thread_, &idev2);
- adev = thread_->open_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adev->dev, &idev);
- EXPECT_EQ(adev->next->dev, &idev2);
-
- // Remove first open device and check the second one is still open.
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, idev.info.idx);
- adev = thread_->open_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adev->dev, &idev2);
-
- // Add and remove another open device and check still open.
- thread_add_open_dev(thread_, &idev3);
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, idev3.info.idx);
- adev = thread_->open_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adev->dev, &idev2);
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, idev2.info.idx);
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, odev2.info.idx);
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, odev3.info.idx);
-}
-
-TEST_F(StreamDeviceSuite, MultipleInputStreamsCopyFirstStreamOffset) {
- struct cras_iodev iodev;
- struct cras_iodev iodev2;
- struct cras_iodev* iodevs[] = {&iodev, &iodev2};
- struct cras_rstream rstream;
- struct cras_rstream rstream2;
- struct cras_rstream rstream3;
-
- SetupDevice(&iodev, CRAS_STREAM_INPUT);
- SetupDevice(&iodev2, CRAS_STREAM_INPUT);
- SetupRstream(&rstream, CRAS_STREAM_INPUT);
- SetupRstream(&rstream2, CRAS_STREAM_INPUT);
- SetupRstream(&rstream3, CRAS_STREAM_INPUT);
-
- thread_add_open_dev(thread_, &iodev);
- thread_add_open_dev(thread_, &iodev2);
-
- thread_add_stream(thread_, &rstream, iodevs, 2);
- EXPECT_NE((void*)NULL, iodev.streams);
- EXPECT_NE((void*)NULL, iodev2.streams);
-
- EXPECT_EQ(0, cras_rstream_dev_offset_called);
- EXPECT_EQ(0, cras_rstream_dev_offset_update_called);
-
- // Fake offset for rstream
- cras_rstream_dev_offset_ret[0] = 30;
- cras_rstream_dev_offset_ret[1] = 0;
-
- thread_add_stream(thread_, &rstream2, iodevs, 2);
- EXPECT_EQ(2, cras_rstream_dev_offset_called);
- EXPECT_EQ(&rstream, cras_rstream_dev_offset_rstream_val[0]);
- EXPECT_EQ(iodev.info.idx, cras_rstream_dev_offset_dev_id_val[0]);
- EXPECT_EQ(&rstream, cras_rstream_dev_offset_rstream_val[1]);
- EXPECT_EQ(iodev2.info.idx, cras_rstream_dev_offset_dev_id_val[1]);
-
- EXPECT_EQ(2, cras_rstream_dev_offset_update_called);
- EXPECT_EQ(&rstream2, cras_rstream_dev_offset_update_rstream_val[0]);
- EXPECT_EQ(30, cras_rstream_dev_offset_update_frames_val[0]);
- EXPECT_EQ(&rstream2, cras_rstream_dev_offset_update_rstream_val[1]);
- EXPECT_EQ(0, cras_rstream_dev_offset_update_frames_val[1]);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, iodev.info.idx);
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, iodev2.info.idx);
- TearDownRstream(&rstream);
- TearDownRstream(&rstream2);
- TearDownRstream(&rstream3);
-}
-
-TEST_F(StreamDeviceSuite, InputStreamsSetInputDeviceWakeTime) {
- struct cras_iodev iodev;
- struct cras_iodev* iodevs[] = {&iodev};
- struct cras_rstream rstream1, rstream2;
- struct timespec ts_wake_1 = {.tv_sec = 1, .tv_nsec = 500};
- struct timespec ts_wake_2 = {.tv_sec = 1, .tv_nsec = 1000};
- struct open_dev* adev;
-
- SetupDevice(&iodev, CRAS_STREAM_INPUT);
- SetupRstream(&rstream1, CRAS_STREAM_INPUT);
- SetupRstream(&rstream2, CRAS_STREAM_INPUT);
-
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream1, iodevs, 1);
- thread_add_stream(thread_, &rstream2, iodevs, 1);
- EXPECT_NE((void*)NULL, iodev.streams);
-
- // Assume device is running.
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- // Set stub data for dev_stream_wake_time.
- dev_stream_wake_time_val[iodev.streams] = ts_wake_1;
- dev_stream_wake_time_val[iodev.streams->next] = ts_wake_2;
-
- // Send captured samples to client.
- // This will also update wake time for this device based on
- // dev_stream_wake_time of each stream of this device.
- dev_io_send_captured_samples(thread_->open_devs[CRAS_STREAM_INPUT]);
-
- // wake_ts is maintained in open_dev.
- adev = thread_->open_devs[CRAS_STREAM_INPUT];
-
- // The wake up time for this device is the minimum of
- // ts_wake_1 and ts_wake_2.
- EXPECT_EQ(ts_wake_1.tv_sec, adev->wake_ts.tv_sec);
- EXPECT_EQ(ts_wake_1.tv_nsec, adev->wake_ts.tv_nsec);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_INPUT, iodev.info.idx);
- TearDownRstream(&rstream1);
- TearDownRstream(&rstream2);
-}
-
-TEST_F(StreamDeviceSuite, AddOutputStream) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct cras_rstream rstream;
- struct cras_audio_shm_header* shm_header;
- struct dev_stream* dev_stream;
- struct open_dev* adev;
-
- ResetGlobalStubData();
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream, CRAS_STREAM_OUTPUT);
- shm_header = rstream.shm->header;
-
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream, &piodev, 1);
- dev_stream = iodev.streams;
- EXPECT_EQ(dev_stream->stream, &rstream);
- /*
- * When a output stream is added, the start_stream function will be called
- * just before its first fetch.
- */
- EXPECT_EQ(cras_iodev_start_stream_called, 0);
-
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
-
- shm_header->write_buf_idx = 0;
- shm_header->write_offset[0] = 0;
-
- /* Assume device is started. */
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- /* Fetch stream. */
- cras_rstream_is_pending_reply_ret = 0;
- dev_io_playback_fetch(adev);
- EXPECT_EQ(dev_stream_request_playback_samples_called, 1);
- EXPECT_EQ(cras_iodev_start_stream_called, 1);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream);
-}
-
-TEST_F(StreamDeviceSuite, OutputStreamFetchTime) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct cras_rstream rstream1, rstream2;
- struct dev_stream* dev_stream;
- struct timespec expect_ts;
-
- ResetGlobalStubData();
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream1, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream2, CRAS_STREAM_OUTPUT);
-
- thread_add_open_dev(thread_, &iodev);
-
- /* Add a new stream. init_cb_ts should be the time right now. */
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 500;
- cras_iodev_get_valid_frames_ret = 0;
- expect_ts = clock_gettime_retspec;
- thread_add_stream(thread_, &rstream1, &piodev, 1);
- dev_stream = iodev.streams;
- EXPECT_EQ(dev_stream->stream, &rstream1);
- EXPECT_EQ(init_cb_ts_.tv_sec, expect_ts.tv_sec);
- EXPECT_EQ(init_cb_ts_.tv_nsec, expect_ts.tv_nsec);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
-
- thread_add_open_dev(thread_, &iodev);
-
- /*
- * Add a new stream when there are remaining frames in device buffer.
- * init_cb_ts should be the time that hw_level drops to min_cb_level.
- * In this case, we should wait 480 / 48000 = 0.01s.
- */
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 500;
- expect_ts = clock_gettime_retspec;
- cras_iodev_get_valid_frames_ret = 960;
- rstream1.cb_threshold = 480;
- expect_ts.tv_nsec += 10 * 1000000;
- thread_add_stream(thread_, &rstream1, &piodev, 1);
- dev_stream = iodev.streams;
- EXPECT_EQ(dev_stream->stream, &rstream1);
- EXPECT_EQ(init_cb_ts_.tv_sec, expect_ts.tv_sec);
- EXPECT_EQ(init_cb_ts_.tv_nsec, expect_ts.tv_nsec);
-
- /*
- * Add a new stream when there are other streams exist. init_cb_ts should
- * be the earliest next callback time from other streams.
- */
- rstream1.next_cb_ts = expect_ts;
- thread_add_stream(thread_, &rstream2, &piodev, 1);
- dev_stream = iodev.streams->prev;
- EXPECT_EQ(dev_stream->stream, &rstream2);
- EXPECT_EQ(init_cb_ts_.tv_sec, expect_ts.tv_sec);
- EXPECT_EQ(init_cb_ts_.tv_nsec, expect_ts.tv_nsec);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream1);
- TearDownRstream(&rstream2);
-}
-
-TEST_F(StreamDeviceSuite, AddRemoveMultipleStreamsOnMultipleDevices) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct cras_iodev iodev2, *piodev2 = &iodev2;
- struct cras_rstream rstream;
- struct cras_rstream rstream2;
- struct cras_rstream rstream3;
- struct dev_stream* dev_stream;
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
- SetupDevice(&iodev2, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream2, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream3, CRAS_STREAM_OUTPUT);
-
- // Add first device as open and check 2 streams can be added.
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream, &piodev, 1);
- dev_stream = iodev.streams;
- EXPECT_EQ(dev_stream->stream, &rstream);
- thread_add_stream(thread_, &rstream2, &piodev, 1);
- EXPECT_EQ(dev_stream->next->stream, &rstream2);
-
- // Add second device as open and check no streams are copied over.
- thread_add_open_dev(thread_, &iodev2);
- dev_stream = iodev2.streams;
- EXPECT_EQ(NULL, dev_stream);
- // Also check the 2 streams on first device remain intact.
- dev_stream = iodev.streams;
- EXPECT_EQ(dev_stream->stream, &rstream);
- EXPECT_EQ(dev_stream->next->stream, &rstream2);
-
- // Add a stream to the second dev and check it isn't also added to the first.
- thread_add_stream(thread_, &rstream3, &piodev2, 1);
- dev_stream = iodev.streams;
- EXPECT_EQ(dev_stream->stream, &rstream);
- EXPECT_EQ(dev_stream->next->stream, &rstream2);
- EXPECT_EQ(NULL, dev_stream->next->next);
- dev_stream = iodev2.streams;
- EXPECT_EQ(&rstream3, dev_stream->stream);
- EXPECT_EQ(NULL, dev_stream->next);
-
- // Remove first device from open and streams on second device remain
- // intact.
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- dev_stream = iodev2.streams;
- EXPECT_EQ(&rstream3, dev_stream->stream);
- EXPECT_EQ(NULL, dev_stream->next);
-
- // Remove 2 streams, check the streams are removed from both open devices.
- dev_io_remove_stream(&thread_->open_devs[rstream.direction], &rstream,
- &iodev);
- dev_io_remove_stream(&thread_->open_devs[rstream3.direction], &rstream3,
- &iodev2);
- dev_stream = iodev2.streams;
- EXPECT_EQ(NULL, dev_stream);
-
- // Remove open devices and check stream is on fallback device.
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev2.info.idx);
-
- // Add open device, again check it is empty of streams.
- thread_add_open_dev(thread_, &iodev);
- dev_stream = iodev.streams;
- EXPECT_EQ(NULL, dev_stream);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream);
- TearDownRstream(&rstream2);
- TearDownRstream(&rstream3);
-}
-
-TEST_F(StreamDeviceSuite, FetchStreams) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct open_dev* adev;
- struct cras_rstream rstream;
- struct cras_audio_shm_header* shm_header;
-
- SetupRstream(&rstream, CRAS_STREAM_OUTPUT);
- shm_header = rstream.shm->header;
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- shm_header->write_buf_idx = 0;
-
- /* Add the device and add the stream. */
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream, &piodev, 1);
-
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
-
- /* Assume device is started. */
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- /*
- * If the stream is pending a reply and shm buffer for writing is empty,
- * just skip it.
- */
- cras_rstream_is_pending_reply_ret = 1;
- shm_header->write_offset[0] = 0;
- dev_io_playback_fetch(adev);
-
- EXPECT_EQ(dev_stream_request_playback_samples_called, 0);
- EXPECT_EQ(dev_stream_update_next_wake_time_called, 0);
-
- /*
- * If the stream is not pending a reply and shm buffer for writing is full,
- * update next wake up time and skip fetching.
- */
- cras_rstream_is_pending_reply_ret = 0;
- shm_header->write_offset[0] = cras_shm_used_size(rstream.shm);
- dev_io_playback_fetch(adev);
- EXPECT_EQ(dev_stream_request_playback_samples_called, 0);
- EXPECT_EQ(dev_stream_update_next_wake_time_called, 1);
-
- /* If the stream can be fetched, fetch it. */
- cras_rstream_is_pending_reply_ret = 0;
- shm_header->write_offset[0] = 0;
- dev_io_playback_fetch(adev);
- EXPECT_EQ(dev_stream_request_playback_samples_called, 1);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream);
-}
-
-TEST_F(StreamDeviceSuite, WriteOutputSamplesPrepareOutputFailed) {
- struct cras_iodev iodev;
- struct open_dev* adev;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- // Add the device.
- thread_add_open_dev(thread_, &iodev);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
-
- // Assume device is started.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Assume device remains in no stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NO_STREAM_RUN;
-
- // Assume there is an error in prepare_output.
- cras_iodev_prepare_output_before_write_samples_ret = -EINVAL;
-
- // cras_iodev should handle no stream playback.
- EXPECT_EQ(-EINVAL,
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev,
- nullptr));
-
- // cras_iodev_get_output_buffer in audio_thread write_output_samples is not
- // called.
- EXPECT_EQ(0, cras_iodev_get_output_buffer_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
-}
-
-TEST_F(StreamDeviceSuite, WriteOutputSamplesNoStream) {
- struct cras_iodev iodev;
- struct open_dev* adev;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- // Add the device.
- thread_add_open_dev(thread_, &iodev);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
-
- // Assume device is started.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Assume device remains in no stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NO_STREAM_RUN;
-
- // cras_iodev should handle no stream playback.
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(1, cras_iodev_prepare_output_before_write_samples_called);
- // cras_iodev_get_output_buffer in audio_thread write_output_samples is not
- // called.
- EXPECT_EQ(0, cras_iodev_get_output_buffer_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
-}
-
-TEST_F(StreamDeviceSuite, WriteOutputSamplesLeaveNoStream) {
- struct cras_iodev iodev;
- struct open_dev* adev;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- // Setup the output buffer for device.
- cras_iodev_get_output_buffer_area = cras_audio_area_create(2);
-
- // Add the device.
- thread_add_open_dev(thread_, &iodev);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
-
- // Assume device in no stream state.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
-
- // Assume device remains in no stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NO_STREAM_RUN;
-
- // cras_iodev should NOT leave no stream state;
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(1, cras_iodev_prepare_output_before_write_samples_called);
- // cras_iodev_get_output_buffer in audio_thread write_output_samples is not
- // called.
- EXPECT_EQ(0, cras_iodev_get_output_buffer_called);
-
- // Assume device leaves no stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NORMAL_RUN;
-
- // cras_iodev should write samples from streams.
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(2, cras_iodev_prepare_output_before_write_samples_called);
- EXPECT_EQ(1, cras_iodev_get_output_buffer_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
-}
-
-TEST_F(StreamDeviceSuite, MixOutputSamples) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct cras_rstream rstream1;
- struct cras_rstream rstream2;
- struct open_dev* adev;
- struct dev_stream* dev_stream;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream1, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream2, CRAS_STREAM_OUTPUT);
-
- // Setup the output buffer for device.
- cras_iodev_get_output_buffer_area = cras_audio_area_create(2);
-
- // Add the device and add the stream.
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream1, &piodev, 1);
- adev = thread_->open_devs[CRAS_STREAM_OUTPUT];
-
- // Assume device is running.
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- // Assume device in normal run stream state.
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NORMAL_RUN;
-
- // cras_iodev should not mix samples because the stream has not started
- // running.
- frames_queued_ = 0;
- dev_stream_playback_frames_ret = 100;
- dev_stream = iodev.streams;
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(1, cras_iodev_prepare_output_before_write_samples_called);
- EXPECT_EQ(1, cras_iodev_get_output_buffer_called);
- EXPECT_EQ(0, dev_stream_mix_called);
-
- // Set rstream1 to be running. cras_iodev should mix samples from rstream1.
- dev_stream_set_running(dev_stream);
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(2, cras_iodev_prepare_output_before_write_samples_called);
- EXPECT_EQ(2, cras_iodev_get_output_buffer_called);
- EXPECT_EQ(1, dev_stream_mix_called);
-
- // Add rstream2. cras_iodev should mix samples from rstream1 but not from
- // rstream2.
- thread_add_stream(thread_, &rstream2, &piodev, 1);
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(3, cras_iodev_prepare_output_before_write_samples_called);
- EXPECT_EQ(3, cras_iodev_get_output_buffer_called);
- EXPECT_EQ(2, dev_stream_mix_called);
-
- // Set rstream2 to be running. cras_iodev should mix samples from rstream1
- // and rstream2.
- dev_stream = iodev.streams->prev;
- dev_stream_set_running(dev_stream);
- write_output_samples(&thread_->open_devs[CRAS_STREAM_OUTPUT], adev, nullptr);
- EXPECT_EQ(4, cras_iodev_prepare_output_before_write_samples_called);
- EXPECT_EQ(4, cras_iodev_get_output_buffer_called);
- EXPECT_EQ(4, dev_stream_mix_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream1);
- TearDownRstream(&rstream2);
-}
-
-TEST_F(StreamDeviceSuite, DoPlaybackNoStream) {
- struct cras_iodev iodev;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
-
- // Add the device.
- thread_add_open_dev(thread_, &iodev);
-
- // Assume device is started.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Assume device remains in no stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Add 10 frames in queue to prevent underrun
- frames_queued_ = 10;
-
- // cras_iodev should handle no stream playback.
- dev_io_playback_write(&thread_->open_devs[CRAS_STREAM_OUTPUT], nullptr);
- EXPECT_EQ(1, cras_iodev_prepare_output_before_write_samples_called);
- // cras_iodev_get_output_buffer in audio_thread write_output_samples is not
- // called.
- EXPECT_EQ(0, cras_iodev_get_output_buffer_called);
-
- EXPECT_EQ(0, cras_iodev_output_underrun_called);
- // cras_iodev_frames_to_play_in_sleep should be called from
- // update_dev_wakeup_time.
- EXPECT_EQ(1, cras_iodev_frames_to_play_in_sleep_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
-}
-
-TEST_F(StreamDeviceSuite, DoPlaybackUnderrun) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct cras_rstream rstream;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream, CRAS_STREAM_OUTPUT);
-
- // Setup the output buffer for device.
- cras_iodev_get_output_buffer_area = cras_audio_area_create(2);
-
- // Add the device and add the stream.
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream, &piodev, 1);
-
- // Assume device is running and there is an underrun.
- // It wrote 11 frames into device but new hw_level is only 10.
- // It means underrun may happened because 10 - 11 < 0.
- // Audio thread should ask iodev to handle output underrun.
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- frames_queued_ = 10;
- cras_iodev_all_streams_written_ret = 11;
-
- // Assume device in normal run stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NORMAL_RUN;
-
- EXPECT_EQ(0, cras_iodev_output_underrun_called);
- dev_io_playback_write(&thread_->open_devs[CRAS_STREAM_OUTPUT], nullptr);
- EXPECT_EQ(1, cras_iodev_output_underrun_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream);
-}
-
-TEST_F(StreamDeviceSuite, DoPlaybackSevereUnderrun) {
- struct cras_iodev iodev, *piodev = &iodev;
- struct cras_rstream rstream;
-
- ResetGlobalStubData();
-
- SetupDevice(&iodev, CRAS_STREAM_OUTPUT);
- SetupRstream(&rstream, CRAS_STREAM_OUTPUT);
-
- // Setup the output buffer for device.
- cras_iodev_get_output_buffer_area = cras_audio_area_create(2);
-
- // Add the device and add the stream.
- thread_add_open_dev(thread_, &iodev);
- thread_add_stream(thread_, &rstream, &piodev, 1);
-
- // Assume device is running and there is a severe underrun.
- cras_audio_thread_event_severe_underrun_called = 0;
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- frames_queued_ = -EPIPE;
-
- // Assume device in normal run stream state;
- cras_iodev_prepare_output_before_write_samples_state =
- CRAS_IODEV_STATE_NORMAL_RUN;
-
- dev_io_playback_write(&thread_->open_devs[CRAS_STREAM_OUTPUT], nullptr);
-
- // Audio thread should ask main thread to reset device.
- EXPECT_EQ(1, cras_iodev_reset_request_called);
- EXPECT_EQ(&iodev, cras_iodev_reset_request_iodev);
- EXPECT_EQ(1, cras_audio_thread_event_severe_underrun_called);
-
- thread_rm_open_dev(thread_, CRAS_STREAM_OUTPUT, iodev.info.idx);
- TearDownRstream(&rstream);
-}
-
-TEST(AudioThreadStreams, DrainStream) {
- struct cras_rstream rstream;
- struct cras_audio_shm_header* shm_header;
- struct audio_thread thread;
-
- SetupRstream(&rstream, CRAS_STREAM_OUTPUT);
- shm_header = rstream.shm->header;
-
- shm_header->write_offset[0] = 1 * 4;
- EXPECT_EQ(1, thread_drain_stream_ms_remaining(&thread, &rstream));
-
- shm_header->write_offset[0] = 479 * 4;
- EXPECT_EQ(10, thread_drain_stream_ms_remaining(&thread, &rstream));
-
- shm_header->write_offset[0] = 0;
- EXPECT_EQ(0, thread_drain_stream_ms_remaining(&thread, &rstream));
-
- rstream.direction = CRAS_STREAM_INPUT;
- shm_header->write_offset[0] = 479 * 4;
- EXPECT_EQ(0, thread_drain_stream_ms_remaining(&thread, &rstream));
- TearDownRstream(&rstream);
-}
-
-TEST(BusyloopDetectSuite, CheckerTest) {
- continuous_zero_sleep_count = 0;
- cras_audio_thread_event_busyloop_called = 0;
- timespec wait_ts;
- wait_ts.tv_sec = 0;
- wait_ts.tv_nsec = 0;
-
- check_busyloop(&wait_ts);
- EXPECT_EQ(continuous_zero_sleep_count, 1);
- EXPECT_EQ(cras_audio_thread_event_busyloop_called, 0);
- check_busyloop(&wait_ts);
- EXPECT_EQ(continuous_zero_sleep_count, 2);
- EXPECT_EQ(cras_audio_thread_event_busyloop_called, 1);
- check_busyloop(&wait_ts);
- EXPECT_EQ(continuous_zero_sleep_count, 3);
- EXPECT_EQ(cras_audio_thread_event_busyloop_called, 1);
-
- wait_ts.tv_sec = 1;
- check_busyloop(&wait_ts);
- EXPECT_EQ(continuous_zero_sleep_count, 0);
- EXPECT_EQ(cras_audio_thread_event_busyloop_called, 1);
-}
-
-extern "C" {
-
-int cras_iodev_add_stream(struct cras_iodev* iodev, struct dev_stream* stream) {
- DL_APPEND(iodev->streams, stream);
- return 0;
-}
-
-void cras_iodev_start_stream(struct cras_iodev* iodev,
- struct dev_stream* stream) {
- dev_stream_set_running(stream);
- cras_iodev_start_stream_called++;
-}
-
-unsigned int cras_iodev_all_streams_written(struct cras_iodev* iodev) {
- return cras_iodev_all_streams_written_ret;
-}
-
-int cras_iodev_close(struct cras_iodev* iodev) {
- return 0;
-}
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {
- return;
-}
-
-double cras_iodev_get_est_rate_ratio(const struct cras_iodev* iodev) {
- return 1.0;
-}
-
-unsigned int cras_iodev_max_stream_offset(const struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_open(struct cras_iodev* iodev,
- unsigned int cb_level,
- const struct cras_audio_format* fmt) {
- return 0;
-}
-
-int cras_iodev_put_buffer(struct cras_iodev* iodev, unsigned int nframes) {
- return 0;
-}
-
-struct dev_stream* cras_iodev_rm_stream(struct cras_iodev* iodev,
- const struct cras_rstream* stream) {
- struct dev_stream* out;
- DL_FOREACH (iodev->streams, out) {
- if (out->stream == stream) {
- DL_DELETE(iodev->streams, out);
- return out;
- }
- }
- return NULL;
-}
-
-int cras_iodev_set_format(struct cras_iodev* iodev,
- const struct cras_audio_format* fmt) {
- return 0;
-}
-
-unsigned int cras_iodev_stream_offset(struct cras_iodev* iodev,
- struct dev_stream* stream) {
- return 0;
-}
-
-int cras_iodev_is_zero_volume(const struct cras_iodev* iodev) {
- return cras_iodev_is_zero_volume_ret;
-}
-
-int dev_stream_attached_devs(const struct dev_stream* dev_stream) {
- return 1;
-}
-
-void cras_iodev_stream_written(struct cras_iodev* iodev,
- struct dev_stream* stream,
- unsigned int nwritten) {}
-
-int cras_iodev_update_rate(struct cras_iodev* iodev,
- unsigned int level,
- struct timespec* level_tstamp) {
- return 0;
-}
-
-int cras_iodev_put_input_buffer(struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_put_output_buffer(struct cras_iodev* iodev,
- uint8_t* frames,
- unsigned int nframes,
- int* non_empty,
- struct cras_fmt_conv* output_converter) {
- cras_iodev_put_output_buffer_called++;
- cras_iodev_put_output_buffer_nframes = nframes;
- return 0;
-}
-
-int cras_iodev_get_input_buffer(struct cras_iodev* iodev, unsigned* frames) {
- return 0;
-}
-
-int cras_iodev_get_output_buffer(struct cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned* frames) {
- cras_iodev_get_output_buffer_called++;
- *area = cras_iodev_get_output_buffer_area;
- return 0;
-}
-
-int cras_iodev_get_dsp_delay(const struct cras_iodev* iodev) {
- return 0;
-}
-
-void cras_fmt_conv_destroy(struct cras_fmt_conv** conv) {}
-
-struct cras_fmt_conv* cras_channel_remix_conv_create(unsigned int num_channels,
- const float* coefficient) {
- return NULL;
-}
-
-void cras_rstream_dev_attach(struct cras_rstream* rstream,
- unsigned int dev_id,
- void* dev_ptr) {}
-
-void cras_rstream_dev_detach(struct cras_rstream* rstream,
- unsigned int dev_id) {}
-
-void cras_rstream_destroy(struct cras_rstream* stream) {}
-
-void cras_rstream_dev_offset_update(struct cras_rstream* rstream,
- unsigned int frames,
- unsigned int dev_id) {
- int i = cras_rstream_dev_offset_update_called;
- if (i < MAX_CALLS) {
- cras_rstream_dev_offset_update_rstream_val[i] = rstream;
- cras_rstream_dev_offset_update_frames_val[i] = frames;
- cras_rstream_dev_offset_update_dev_id_val[i] = dev_id;
- cras_rstream_dev_offset_update_called++;
- }
-}
-
-unsigned int cras_rstream_dev_offset(const struct cras_rstream* rstream,
- unsigned int dev_id) {
- int i = cras_rstream_dev_offset_called;
- if (i < MAX_CALLS) {
- cras_rstream_dev_offset_rstream_val[i] = rstream;
- cras_rstream_dev_offset_dev_id_val[i] = dev_id;
- cras_rstream_dev_offset_called++;
- return cras_rstream_dev_offset_ret[i];
- }
- return 0;
-}
-
-void cras_rstream_record_fetch_interval(struct cras_rstream* rstream,
- const struct timespec* now) {}
-
-int cras_rstream_is_pending_reply(const struct cras_rstream* stream) {
- return cras_rstream_is_pending_reply_ret;
-}
-
-float cras_rstream_get_volume_scaler(struct cras_rstream* rstream) {
- return 1.0f;
-}
-
-int cras_set_rt_scheduling(int rt_lim) {
- return 0;
-}
-
-int cras_set_thread_priority(int priority) {
- return 0;
-}
-
-void cras_system_rm_select_fd(int fd) {}
-
-unsigned int dev_stream_capture(struct dev_stream* dev_stream,
- const struct cras_audio_area* area,
- unsigned int area_offset,
- float software_gain_scaler) {
- return 0;
-}
-
-unsigned int dev_stream_capture_avail(const struct dev_stream* dev_stream) {
- return 0;
-}
-unsigned int dev_stream_cb_threshold(const struct dev_stream* dev_stream) {
- return 0;
-}
-
-int dev_stream_capture_update_rstream(struct dev_stream* dev_stream) {
- return 0;
-}
-
-struct dev_stream* dev_stream_create(struct cras_rstream* stream,
- unsigned int dev_id,
- const struct cras_audio_format* dev_fmt,
- void* dev_ptr,
- struct timespec* cb_ts,
- const struct timespec* sleep_interval_ts) {
- struct dev_stream* out = static_cast<dev_stream*>(calloc(1, sizeof(*out)));
- out->stream = stream;
- init_cb_ts_ = *cb_ts;
- sleep_interval_ts_ = *sleep_interval_ts;
- return out;
-}
-
-void dev_stream_destroy(struct dev_stream* dev_stream) {
- free(dev_stream);
-}
-
-int dev_stream_mix(struct dev_stream* dev_stream,
- const struct cras_audio_format* fmt,
- uint8_t* dst,
- unsigned int num_to_write) {
- dev_stream_mix_called++;
- return num_to_write;
-}
-
-int dev_stream_playback_frames(const struct dev_stream* dev_stream) {
- return dev_stream_playback_frames_ret;
-}
-
-int dev_stream_playback_update_rstream(struct dev_stream* dev_stream) {
- return 0;
-}
-
-int dev_stream_poll_stream_fd(const struct dev_stream* dev_stream) {
- return dev_stream->stream->fd;
-}
-
-int dev_stream_request_playback_samples(struct dev_stream* dev_stream,
- const struct timespec* now) {
- dev_stream_request_playback_samples_called++;
- return 0;
-}
-
-void dev_stream_set_delay(const struct dev_stream* dev_stream,
- unsigned int delay_frames) {}
-
-void dev_stream_set_dev_rate(struct dev_stream* dev_stream,
- unsigned int dev_rate,
- double dev_rate_ratio,
- double main_rate_ratio,
- int coarse_rate_adjust) {}
-
-void dev_stream_update_frames(const struct dev_stream* dev_stream) {}
-
-void dev_stream_update_next_wake_time(struct dev_stream* dev_stream) {
- dev_stream_update_next_wake_time_called++;
-}
-
-int dev_stream_wake_time(struct dev_stream* dev_stream,
- unsigned int curr_level,
- struct timespec* level_tstamp,
- unsigned int cap_limit,
- int is_cap_limit_stream,
- struct timespec* wake_time) {
- if (dev_stream_wake_time_val.find(dev_stream) !=
- dev_stream_wake_time_val.end()) {
- wake_time->tv_sec = dev_stream_wake_time_val[dev_stream].tv_sec;
- wake_time->tv_nsec = dev_stream_wake_time_val[dev_stream].tv_nsec;
- }
- return 0;
-}
-
-int dev_stream_is_pending_reply(const struct dev_stream* dev_stream) {
- return 0;
-}
-
-int dev_stream_flush_old_audio_messages(struct dev_stream* dev_stream) {
- return 0;
-}
-
-int cras_iodev_frames_queued(struct cras_iodev* iodev,
- struct timespec* tstamp) {
- return iodev->frames_queued(iodev, tstamp);
-}
-
-int cras_iodev_buffer_avail(struct cras_iodev* iodev, unsigned hw_level) {
- struct timespec tstamp;
- return iodev->buffer_size - iodev->frames_queued(iodev, &tstamp);
-}
-
-int cras_iodev_fill_odev_zeros(struct cras_iodev* odev, unsigned int frames) {
- cras_iodev_fill_odev_zeros_frames = frames;
- return 0;
-}
-
-int cras_iodev_output_underrun(struct cras_iodev* odev,
- unsigned int hw_level,
- unsigned int frames_written) {
- cras_iodev_output_underrun_called++;
- return 0;
-}
-
-int cras_iodev_prepare_output_before_write_samples(struct cras_iodev* odev) {
- cras_iodev_prepare_output_before_write_samples_called++;
- odev->state = cras_iodev_prepare_output_before_write_samples_state;
- return cras_iodev_prepare_output_before_write_samples_ret;
-}
-
-float cras_iodev_get_software_gain_scaler(const struct cras_iodev* iodev) {
- return 1.0f;
-}
-
-unsigned int cras_iodev_frames_to_play_in_sleep(struct cras_iodev* odev,
- unsigned int* hw_level,
- struct timespec* hw_tstamp) {
- *hw_level = cras_iodev_frames_queued(odev, hw_tstamp);
- cras_iodev_frames_to_play_in_sleep_called++;
- return 0;
-}
-
-int cras_iodev_odev_should_wake(const struct cras_iodev* odev) {
- return 1;
-}
-
-struct cras_audio_area* cras_audio_area_create(int num_channels) {
- struct cras_audio_area* area;
- size_t sz;
-
- sz = sizeof(*area) + num_channels * sizeof(struct cras_channel_area);
- area = (cras_audio_area*)calloc(1, sz);
- area->num_channels = num_channels;
- area->channels[0].buf = (uint8_t*)calloc(1, BUFFER_SIZE * 2 * num_channels);
-
- return area;
-}
-
-enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev* iodev) {
- return iodev->state;
-}
-
-unsigned int cras_iodev_get_num_underruns(const struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_get_valid_frames(struct cras_iodev* iodev,
- struct timespec* hw_tstamp) {
- clock_gettime(CLOCK_MONOTONIC_RAW, hw_tstamp);
- return cras_iodev_get_valid_frames_ret;
-}
-
-int cras_iodev_reset_request(struct cras_iodev* iodev) {
- cras_iodev_reset_request_called++;
- cras_iodev_reset_request_iodev = iodev;
- return 0;
-}
-
-unsigned int cras_iodev_get_num_severe_underruns(
- const struct cras_iodev* iodev) {
- return 0;
-}
-
-void cras_iodev_update_highest_hw_level(struct cras_iodev* iodev,
- unsigned int hw_level) {}
-
-int cras_iodev_start_ramp(struct cras_iodev* odev,
- enum CRAS_IODEV_RAMP_REQUEST request) {
- cras_iodev_start_ramp_odev = odev;
- cras_iodev_start_ramp_request = request;
- return 0;
-}
-
-int input_data_get_for_stream(struct input_data* data,
- struct cras_rstream* stream,
- struct buffer_share* offsets,
- struct cras_audio_area** area,
- unsigned int* offset) {
- return 0;
-}
-
-int input_data_put_for_stream(struct input_data* data,
- struct cras_rstream* stream,
- struct buffer_share* offsets,
- unsigned int frames) {
- return 0;
-}
-
-int cras_device_monitor_set_device_mute_state(unsigned int dev_idx) {
- cras_device_monitor_set_device_mute_state_called++;
- return 0;
-}
-int cras_device_monitor_error_close(unsigned int dev_idx) {
- return 0;
-}
-
-int cras_iodev_drop_frames_by_time(struct cras_iodev* iodev,
- struct timespec ts) {
- return 0;
-}
-
-bool cras_iodev_is_on_internal_card(const struct cras_ionode* node) {
- return 0;
-}
-
-// From librt.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = clock_gettime_retspec;
- return 0;
-}
-
-#ifdef HAVE_WEBRTC_APM
-
-uint64_t cras_apm_list_get_effects(struct cras_apm_list* list) {
- return 0;
-}
-
-void cras_apm_list_set_debug_recording(struct cras_apm* apm,
- unsigned int stream_id,
- int start,
- const char* file_name_base) {}
-void cras_apm_list_set_aec_dump(struct cras_apm_list* list,
- void* dev_ptr,
- int start,
- int fd) {}
-
-#endif
-
-int cras_audio_thread_event_busyloop() {
- cras_audio_thread_event_busyloop_called++;
- return 0;
-}
-
-int cras_audio_thread_event_drop_samples() {
- return 0;
-}
-
-int cras_audio_thread_event_severe_underrun() {
- cras_audio_thread_event_severe_underrun_called++;
- return 0;
-}
-
-float input_data_get_software_gain_scaler(struct input_data* data,
- float idev_sw_gain_scaler,
- struct cras_rstream* stream) {
- return 1.0;
-}
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/audio_thread_unittest_obsolete.cc b/cras/src/tests/audio_thread_unittest_obsolete.cc
deleted file mode 100644
index ae9f5ef3..00000000
--- a/cras/src/tests/audio_thread_unittest_obsolete.cc
+++ /dev/null
@@ -1,2191 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-extern "C" {
-#include "audio_thread.c"
-}
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <sys/select.h>
-
-extern "C" {
-
-struct dev_stream_capture_call {
- struct dev_stream* dev_stream;
- const struct cras_audio_area* area;
- unsigned int dev_index;
- unsigned int num_called;
-};
-
-struct cap_sleep_frames_call {
- struct dev_stream* dev_stream;
- unsigned int written;
- unsigned int num_called;
-};
-
-static int dev_stream_mix_dont_fill_next;
-static unsigned int dev_stream_mix_count;
-static unsigned int cras_mix_mute_count;
-static unsigned int dev_stream_request_playback_samples_called;
-static unsigned int cras_rstream_destroy_called;
-static unsigned int cras_metrics_log_histogram_called;
-static const char* cras_metrics_log_histogram_name;
-static unsigned int cras_metrics_log_histogram_sample;
-static unsigned int cras_metrics_log_event_called;
-
-static void (*cras_system_add_select_fd_callback)(void* data);
-static void* cras_system_add_select_fd_callback_data;
-
-static int select_return_value;
-static struct timeval select_timeval;
-static int select_max_fd;
-static fd_set select_in_fds;
-static fd_set select_out_fds;
-static uint32_t* select_write_ptr;
-static uint32_t select_write_value;
-static unsigned int cras_iodev_set_format_called;
-static unsigned int dev_stream_set_delay_called;
-static unsigned int cras_system_get_volume_return;
-static unsigned int dev_stream_mix_called;
-
-static struct timespec time_now;
-static int cras_fmt_conversion_needed_return_val;
-static struct cras_audio_area* mock_audio_area1;
-static struct cras_audio_area* mock_audio_area2;
-static struct cras_audio_format cras_iodev_set_format_val;
-
-static struct dev_stream_capture_call dev_stream_capture_call;
-static struct cap_sleep_frames_call cap_sleep_frames_call;
-}
-
-// Number of frames past target that will be added to sleep times to insure that
-// all frames are ready.
-static const int CAP_EXTRA_SLEEP_FRAMES = 16;
-
-// Test the audio capture path.
-class ReadStreamSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- memset(&cras_iodev_set_format_val, 0, sizeof(cras_iodev_set_format_val));
- cras_iodev_set_format_val.frame_rate = 44100;
- cras_iodev_set_format_val.num_channels = 2;
- cras_iodev_set_format_val.format = SND_PCM_FORMAT_S16_LE;
-
- memset(&iodev_, 0, sizeof(iodev_));
- iodev_.buffer_size = 16384;
- cb_threshold_ = 480;
- iodev_.direction = CRAS_STREAM_INPUT;
-
- iodev_.frames_queued = frames_queued;
- iodev_.delay_frames = delay_frames;
- iodev_.get_buffer = get_buffer;
- iodev_.put_buffer = put_buffer;
- iodev_.is_open = is_open;
- iodev_.open_dev = open_dev;
- iodev_.close_dev = close_dev;
- iodev_.dev_running = dev_running;
-
- memcpy(&output_dev_, &iodev_, sizeof(output_dev_));
- output_dev_.direction = CRAS_STREAM_OUTPUT;
-
- SetupRstream(&rstream_, 1);
- shm_ = cras_rstream_input_shm(rstream_);
- SetupRstream(&rstream2_, 2);
- shm2_ = cras_rstream_input_shm(rstream2_);
-
- mock_audio_area1 = (cras_audio_area*)calloc(
- 1, sizeof(cras_audio_area) + 2 * sizeof(cras_channel_area));
- mock_audio_area1->num_channels = 2;
- channel_area_set_channel(&mock_audio_area1->channels[0], CRAS_CH_FL);
- channel_area_set_channel(&mock_audio_area1->channels[1], CRAS_CH_FR);
- rstream_->input_audio_area = mock_audio_area1;
- mock_audio_area2 = (cras_audio_area*)calloc(
- 1, sizeof(cras_audio_area) + 2 * sizeof(cras_channel_area));
- mock_audio_area2->num_channels = 2;
- channel_area_set_channel(&mock_audio_area2->channels[0], CRAS_CH_FL);
- channel_area_set_channel(&mock_audio_area2->channels[1], CRAS_CH_FR);
- rstream2_->input_audio_area = mock_audio_area2;
-
- dev_stream_mix_dont_fill_next = 0;
- dev_stream_mix_count = 0;
- dev_running_called_ = 0;
- is_open_ = 0;
- close_dev_called_ = 0;
-
- cras_iodev_set_format_called = 0;
- dev_stream_set_delay_called = 0;
- }
-
- virtual void TearDown() {
- free(shm_->area);
- free(rstream_);
- free(shm2_->area);
- free(rstream2_);
- free(mock_audio_area1);
- free(mock_audio_area2);
- }
-
- void SetupRstream(struct cras_rstream** rstream, int fd) {
- struct cras_audio_shm* shm;
-
- *rstream = (struct cras_rstream*)calloc(1, sizeof(**rstream));
- memcpy(&(*rstream)->format, &cras_iodev_set_format_val,
- sizeof(cras_iodev_set_format_val));
- (*rstream)->direction = CRAS_STREAM_INPUT;
- (*rstream)->cb_threshold = cb_threshold_;
- (*rstream)->client = (struct cras_rclient*)this;
-
- shm = cras_rstream_input_shm(*rstream);
- shm->header = (struct cras_audio_shm_header*)calloc(
- 1, sizeof(*shm->header) + cb_threshold_ * 8);
- cras_shm_set_frame_bytes(shm, 4);
- cras_shm_set_used_size(shm, cb_threshold_ * cras_shm_frame_bytes(shm));
- }
-
- unsigned int GetCaptureSleepFrames() {
- // Account for padding the sleep interval to ensure the wake up happens
- // after the last desired frame is received.
- return cb_threshold_ + 16;
- }
-
- // Stub functions for the iodev structure.
- static int frames_queued(const cras_iodev* iodev) { return frames_queued_; }
-
- static int delay_frames(const cras_iodev* iodev) { return delay_frames_; }
-
- static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- size_t sz = sizeof(*area_) + sizeof(struct cras_channel_area) * 2;
-
- if (audio_buffer_size_ < *num)
- *num = audio_buffer_size_;
-
- area_ = (cras_audio_area*)calloc(1, sz);
- area_->frames = *num;
- area_->num_channels = 2;
- area_->channels[0].buf = audio_buffer_;
- channel_area_set_channel(&area_->channels[0], CRAS_CH_FL);
- area_->channels[0].step_bytes = 4;
- area_->channels[1].buf = audio_buffer_ + 2;
- channel_area_set_channel(&area_->channels[1], CRAS_CH_FR);
- area_->channels[1].step_bytes = 4;
-
- *area = area_;
- return 0;
- }
-
- static int put_buffer(cras_iodev* iodev, unsigned int num) {
- free(area_);
- return 0;
- }
-
- static int is_open(const cras_iodev* iodev) { return is_open_; }
-
- static int open_dev(cras_iodev* iodev) { return 0; }
-
- static int close_dev(cras_iodev* iodev) {
- close_dev_called_++;
- return 0;
- }
-
- static int dev_running(const cras_iodev* iodev) {
- dev_running_called_++;
- return 1;
- }
-
- struct cras_iodev iodev_;
- struct cras_iodev output_dev_;
- static int is_open_;
- static int frames_queued_;
- static int delay_frames_;
- static unsigned int cb_threshold_;
- static uint8_t audio_buffer_[8192];
- static struct cras_audio_area* area_;
- static unsigned int audio_buffer_size_;
- static unsigned int dev_running_called_;
- static unsigned int close_dev_called_;
- struct cras_rstream* rstream_;
- struct cras_rstream* rstream2_;
- struct cras_audio_shm* shm_;
- struct cras_audio_shm* shm2_;
-};
-
-int ReadStreamSuite::is_open_ = 0;
-int ReadStreamSuite::frames_queued_ = 0;
-int ReadStreamSuite::delay_frames_ = 0;
-unsigned int ReadStreamSuite::close_dev_called_ = 0;
-uint8_t ReadStreamSuite::audio_buffer_[8192];
-unsigned int ReadStreamSuite::audio_buffer_size_ = 0;
-unsigned int ReadStreamSuite::dev_running_called_ = 0;
-unsigned int ReadStreamSuite::cb_threshold_ = 0;
-struct cras_audio_area* ReadStreamSuite::area_;
-
-TEST_F(ReadStreamSuite, PossiblyReadGetAvailError) {
- struct timespec ts;
- int rc;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- thread_add_stream(thread, rstream_);
- EXPECT_EQ(1, cras_iodev_set_format_called);
-
- frames_queued_ = -4;
- is_open_ = 1;
- rc = unified_io(thread, &ts);
- EXPECT_EQ(-4, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(0, ts.tv_nsec);
- EXPECT_EQ(0, dev_stream_set_delay_called);
- EXPECT_EQ(1, close_dev_called_);
-
- audio_thread_destroy(thread);
-}
-
-TEST_F(ReadStreamSuite, PossiblyReadEmpty) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- thread_add_stream(thread, rstream_);
- EXPECT_EQ(1, cras_iodev_set_format_called);
-
- // If no samples are present, it should sleep for cb_threshold frames.
- frames_queued_ = 0;
- is_open_ = 1;
- nsec_expected = (GetCaptureSleepFrames()) * 1000000000ULL /
- (uint64_t)cras_iodev_set_format_val.frame_rate;
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(0, shm_->area->write_offset[0]);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(1, dev_running_called_);
- EXPECT_EQ(1, dev_stream_set_delay_called);
-
- audio_thread_destroy(thread);
-}
-
-TEST_F(ReadStreamSuite, PossiblyReadTooLittleData) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
- static const uint64_t num_frames_short = 40;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- thread_add_stream(thread, rstream_);
-
- frames_queued_ = cb_threshold_ - num_frames_short;
- is_open_ = 1;
- audio_buffer_size_ = frames_queued_;
- nsec_expected = ((uint64_t)num_frames_short + CAP_EXTRA_SLEEP_FRAMES) *
- 1000000000ULL /
- (uint64_t)cras_iodev_set_format_val.frame_rate;
-
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- /* As much data as can be, should be read. */
- EXPECT_EQ(&audio_buffer_[0], dev_stream_capture_call.area->channels[0].buf);
- EXPECT_EQ(rstream_, dev_stream_capture_call.dev_stream->stream);
- EXPECT_EQ(cb_threshold_ - num_frames_short, cap_sleep_frames_call.written);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
-
- audio_thread_destroy(thread);
-}
-
-TEST_F(ReadStreamSuite, PossiblyReadHasDataWriteStream) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- thread_add_stream(thread, rstream_);
-
- // A full block plus 4 frames.
- frames_queued_ = cb_threshold_ + 4;
- audio_buffer_size_ = frames_queued_;
-
- for (unsigned int i = 0; i < sizeof(audio_buffer_); i++)
- audio_buffer_[i] = i;
-
- uint64_t sleep_frames = GetCaptureSleepFrames() - 4;
- nsec_expected = (uint64_t)sleep_frames * 1000000000ULL /
- (uint64_t)cras_iodev_set_format_val.frame_rate;
- is_open_ = 1;
- // Give it some samples to copy.
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(1, dev_stream_set_delay_called);
- EXPECT_EQ(&audio_buffer_[0], dev_stream_capture_call.area->channels[0].buf);
- EXPECT_EQ(rstream_, dev_stream_capture_call.dev_stream->stream);
- EXPECT_EQ(cb_threshold_, cap_sleep_frames_call.written);
- EXPECT_EQ(rstream_, cap_sleep_frames_call.dev_stream->stream);
-
- audio_thread_destroy(thread);
-}
-
-TEST_F(ReadStreamSuite, PossiblyReadHasDataWriteTwoStreams) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
- struct audio_thread* thread;
-
- dev_stream_capture_call.num_called = 0;
- cap_sleep_frames_call.num_called = 0;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- rc = thread_add_stream(thread, rstream_);
- EXPECT_EQ(0, rc);
- rc = thread_add_stream(thread, rstream2_);
- EXPECT_EQ(0, rc);
-
- // A full block plus 4 frames.
- frames_queued_ = cb_threshold_ + 4;
- audio_buffer_size_ = frames_queued_;
-
- for (unsigned int i = 0; i < sizeof(audio_buffer_); i++)
- audio_buffer_[i] = i;
-
- uint64_t sleep_frames = GetCaptureSleepFrames() - 4;
- nsec_expected = (uint64_t)sleep_frames * 1000000000ULL /
- (uint64_t)cras_iodev_set_format_val.frame_rate;
- is_open_ = 1;
- // Give it some samples to copy.
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(2, dev_stream_capture_call.num_called);
- EXPECT_EQ(2, cap_sleep_frames_call.num_called);
-
- audio_thread_destroy(thread);
-}
-
-TEST_F(ReadStreamSuite, PossiblyReadHasDataWriteTwoDifferentStreams) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- cb_threshold_ /= 2;
- rstream_->cb_threshold = cb_threshold_;
-
- rc = thread_add_stream(thread, rstream_);
- EXPECT_EQ(0, rc);
- rc = thread_add_stream(thread, rstream2_);
- EXPECT_EQ(0, rc);
-
- // A full block plus 4 frames.
- frames_queued_ = cb_threshold_ + 4;
- audio_buffer_size_ = frames_queued_;
-
- uint64_t sleep_frames = GetCaptureSleepFrames() - 4;
- nsec_expected = (uint64_t)sleep_frames * 1000000000ULL /
- (uint64_t)cras_iodev_set_format_val.frame_rate;
- is_open_ = 1;
- // Give it some samples to copy.
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
-
- frames_queued_ = cb_threshold_ + 5;
- sleep_frames = GetCaptureSleepFrames() - 5;
- nsec_expected = (uint64_t)sleep_frames * 1000000000ULL /
- (uint64_t)cras_iodev_set_format_val.frame_rate;
- audio_buffer_size_ = frames_queued_;
- is_open_ = 1;
- // Give it some samples to copy.
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
-
- audio_thread_destroy(thread);
-}
-
-TEST_F(ReadStreamSuite, PossiblyReadWriteThreeBuffers) {
- struct timespec ts;
- int rc;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
-
- thread_add_stream(thread, rstream_);
-
- // A full block plus 4 frames.
- frames_queued_ = cb_threshold_ + 4;
- audio_buffer_size_ = frames_queued_;
- is_open_ = 1;
-
- // Give it some samples to copy.
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_shm_num_overruns(shm_));
- EXPECT_EQ(&audio_buffer_[0], dev_stream_capture_call.area->channels[0].buf);
- EXPECT_EQ(rstream_, dev_stream_capture_call.dev_stream->stream);
- EXPECT_EQ(cb_threshold_, cap_sleep_frames_call.written);
- EXPECT_EQ(rstream_, cap_sleep_frames_call.dev_stream->stream);
-
- is_open_ = 1;
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_shm_num_overruns(shm_));
- EXPECT_EQ(&audio_buffer_[0], dev_stream_capture_call.area->channels[0].buf);
- EXPECT_EQ(rstream_, dev_stream_capture_call.dev_stream->stream);
- EXPECT_EQ(cb_threshold_, cap_sleep_frames_call.written);
- EXPECT_EQ(rstream_, cap_sleep_frames_call.dev_stream->stream);
-
- is_open_ = 1;
- rc = unified_io(thread, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(&audio_buffer_[0], dev_stream_capture_call.area->channels[0].buf);
- EXPECT_EQ(rstream_, dev_stream_capture_call.dev_stream->stream);
- EXPECT_EQ(cb_threshold_, cap_sleep_frames_call.written);
- EXPECT_EQ(rstream_, cap_sleep_frames_call.dev_stream->stream);
-
- audio_thread_destroy(thread);
-}
-
-// Test the audio playback path.
-class WriteStreamSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- memset(&fmt_, 0, sizeof(fmt_));
- fmt_.frame_rate = 44100;
- fmt_.num_channels = 2;
- fmt_.format = SND_PCM_FORMAT_S16_LE;
-
- memset(&iodev_, 0, sizeof(iodev_));
- iodev_.format = &fmt_;
- iodev_.buffer_size = 16384;
- iodev_.direction = CRAS_STREAM_OUTPUT;
-
- iodev_.frames_queued = frames_queued;
- iodev_.delay_frames = delay_frames;
- iodev_.get_buffer = get_buffer;
- iodev_.put_buffer = put_buffer;
- iodev_.dev_running = dev_running;
- iodev_.is_open = is_open;
- iodev_.open_dev = open_dev;
- iodev_.close_dev = close_dev;
- iodev_.buffer_size = 480;
-
- buffer_frames_ = iodev_.buffer_size;
- cb_threshold_ = 96;
- SetupRstream(&rstream_, 1);
- shm_ = cras_rstream_output_shm(rstream_);
- SetupRstream(&rstream2_, 2);
- shm2_ = cras_rstream_output_shm(rstream2_);
-
- thread_ = audio_thread_create();
- ASSERT_TRUE(thread_);
- thread_set_active_dev(thread_, &iodev_);
-
- dev_stream_mix_dont_fill_next = 0;
- dev_stream_mix_count = 0;
- select_max_fd = -1;
- select_write_ptr = NULL;
- cras_metrics_log_event_called = 0;
- dev_stream_request_playback_samples_called = 0;
- cras_rstream_destroy_called = 0;
- dev_stream_mix_called = 0;
- is_open_ = 0;
- close_dev_called_ = 0;
-
- dev_running_called_ = 0;
-
- audio_buffer_size_ = 8196;
- thread_add_stream(thread_, rstream_);
- frames_written_ = 0;
- }
-
- virtual void TearDown() {
- free(shm_->area);
- free(rstream_);
- free(shm2_->area);
- free(rstream2_);
- audio_thread_destroy(thread_);
- }
-
- void SetupRstream(struct cras_rstream** rstream, int fd) {
- struct cras_audio_shm* shm;
-
- *rstream = (struct cras_rstream*)calloc(1, sizeof(**rstream));
- memcpy(&(*rstream)->format, &fmt_, sizeof(fmt_));
- (*rstream)->fd = fd;
- (*rstream)->buffer_frames = buffer_frames_;
- (*rstream)->cb_threshold = cb_threshold_;
- (*rstream)->client = (struct cras_rclient*)this;
-
- shm = cras_rstream_output_shm(*rstream);
- shm->header = (struct cras_audio_shm_header*)calloc(
- 1, sizeof(*shm->header) + cb_threshold_ * 8);
- cras_shm_set_frame_bytes(shm, 4);
- cras_shm_set_used_size(shm, buffer_frames_ * cras_shm_frame_bytes(shm));
- }
-
- uint64_t GetCaptureSleepFrames() {
- // Account for padding the sleep interval to ensure the wake up happens
- // after the last desired frame is received.
- return cb_threshold_ + CAP_EXTRA_SLEEP_FRAMES;
- }
-
- // Stub functions for the iodev structure.
- static int frames_queued(const cras_iodev* iodev) {
- return frames_queued_ + frames_written_;
- }
-
- static int delay_frames(const cras_iodev* iodev) { return delay_frames_; }
-
- static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- size_t sz = sizeof(*area_) + sizeof(struct cras_channel_area) * 2;
-
- if (audio_buffer_size_ < *num)
- *num = audio_buffer_size_;
-
- area_ = (cras_audio_area*)calloc(1, sz);
- area_->frames = *num;
- area_->num_channels = 2;
- area_->channels[0].buf = audio_buffer_;
- channel_area_set_channel(&area_->channels[0], CRAS_CH_FL);
- area_->channels[0].step_bytes = 4;
- area_->channels[1].buf = audio_buffer_ + 2;
- channel_area_set_channel(&area_->channels[1], CRAS_CH_FR);
- area_->channels[1].step_bytes = 4;
-
- *area = area_;
- return 0;
- }
-
- static int put_buffer(cras_iodev* iodev, unsigned int num) {
- free(area_);
- frames_written_ += num;
- return 0;
- }
-
- static int dev_running(const cras_iodev* iodev) {
- dev_running_called_++;
- return dev_running_;
- }
-
- static int is_open(const cras_iodev* iodev) { return is_open_; }
-
- static int open_dev(cras_iodev* iodev) {
- is_open_ = 1;
- open_dev_called_++;
- return 0;
- }
-
- static int close_dev(cras_iodev* iodev) {
- close_dev_called_++;
- is_open_ = 0;
- return 0;
- }
-
- struct cras_iodev iodev_;
- static int is_open_;
- static int frames_queued_;
- static int frames_written_;
- static int delay_frames_;
- static unsigned int cb_threshold_;
- static unsigned int buffer_frames_;
- static uint8_t audio_buffer_[8192];
- static unsigned int audio_buffer_size_;
- static int dev_running_;
- static unsigned int dev_running_called_;
- static unsigned int close_dev_called_;
- static unsigned int open_dev_called_;
- static struct cras_audio_area* area_;
- struct cras_audio_format fmt_;
- struct cras_rstream* rstream_;
- struct cras_rstream* rstream2_;
- struct cras_audio_shm* shm_;
- struct cras_audio_shm* shm2_;
- struct audio_thread* thread_;
-};
-
-int WriteStreamSuite::is_open_ = 0;
-int WriteStreamSuite::frames_queued_ = 0;
-int WriteStreamSuite::frames_written_ = 0;
-int WriteStreamSuite::delay_frames_ = 0;
-unsigned int WriteStreamSuite::cb_threshold_ = 0;
-unsigned int WriteStreamSuite::buffer_frames_ = 0;
-uint8_t WriteStreamSuite::audio_buffer_[8192];
-unsigned int WriteStreamSuite::audio_buffer_size_ = 0;
-int WriteStreamSuite::dev_running_ = 1;
-unsigned int WriteStreamSuite::dev_running_called_ = 0;
-unsigned int WriteStreamSuite::close_dev_called_ = 0;
-unsigned int WriteStreamSuite::open_dev_called_ = 0;
-struct cras_audio_area* WriteStreamSuite::area_;
-
-TEST_F(WriteStreamSuite, PossiblyFillGetAvailError) {
- struct timespec ts;
- int rc;
-
- frames_queued_ = -4;
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(-4, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(0, ts.tv_nsec);
- EXPECT_EQ(1, close_dev_called_);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillEarlyWake) {
- struct timespec ts;
- int rc;
-
- // If woken and still have tons of data to play, go back to sleep.
- frames_queued_ = cb_threshold_ * 2;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- iodev_.direction = CRAS_STREAM_OUTPUT;
- is_open_ = 1;
-
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromStreamFull) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- nsec_expected =
- (uint64_t)cb_threshold_ * 1000000000ULL / (uint64_t)fmt_.frame_rate;
-
- // shm has plenty of data in it.
- shm_->area->write_offset[0] = cb_threshold_ * 4;
-
- FD_ZERO(&select_out_fds);
- FD_SET(rstream_->fd, &select_out_fds);
- select_return_value = 1;
- is_open_ = 1;
-
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(cb_threshold_, dev_stream_mix_count);
- EXPECT_EQ(0, dev_stream_request_playback_samples_called);
- EXPECT_EQ(-1, select_max_fd);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromStreamMinSet) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_ * 2;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- // Setting the min_buffer_level should shorten the sleep time.
- iodev_.min_buffer_level = cb_threshold_;
-
- // shm has is empty.
- shm_->area->write_offset[0] = 0;
-
- FD_ZERO(&select_out_fds);
- FD_SET(rstream_->fd, &select_out_fds);
- select_return_value = 1;
- is_open_ = 1;
- // Set write offset after call to select.
- select_write_ptr = &shm_->area->write_offset[0];
- select_write_value = cb_threshold_ * 4;
-
- // After the callback there will be cb_thresh of data in the buffer and
- // cb_thresh x 2 data in the hardware (frames_queued_) = 3 cb_thresh total.
- // It should sleep until there is a total of cb_threshold + min_buffer_level
- // left, or 3 - 2 = 1 cb_thresh worth of delay.
- nsec_expected =
- (uint64_t)cb_threshold_ * 1000000000ULL / (uint64_t)fmt_.frame_rate;
-
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(cb_threshold_, dev_stream_mix_count);
- EXPECT_EQ(1, dev_stream_request_playback_samples_called);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillFramesQueued) {
- struct timespec ts;
- int rc;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- // shm has plenty of data in it.
- shm_->area->write_offset[0] = cras_shm_used_size(shm_);
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, dev_running_called_);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromStreamOneEmpty) {
- struct timespec ts;
- int rc;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- // shm has plenty of data in it.
- shm_->area->write_offset[0] = cras_shm_used_size(shm_);
-
- // Test that nothing breaks if there is an empty stream.
- dev_stream_mix_dont_fill_next = 1;
-
- FD_ZERO(&select_out_fds);
- FD_SET(rstream_->fd, &select_out_fds);
- select_return_value = 1;
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, dev_stream_request_playback_samples_called);
- EXPECT_EQ(-1, select_max_fd);
- EXPECT_EQ(0, shm_->area->read_offset[0]);
- EXPECT_EQ(0, shm_->area->read_offset[1]);
- EXPECT_EQ(cras_shm_used_size(shm_), shm_->area->write_offset[0]);
- EXPECT_EQ(0, shm_->area->write_offset[1]);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromStreamNeedFill) {
- struct timespec ts;
- uint64_t nsec_expected;
- int rc;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- // shm is out of data.
- shm_->area->write_offset[0] = 0;
-
- FD_ZERO(&select_out_fds);
- FD_SET(rstream_->fd, &select_out_fds);
- select_return_value = 1;
- // Set write offset after call to select.
- select_write_ptr = &shm_->area->write_offset[0];
- select_write_value = (buffer_frames_ - cb_threshold_) * 4;
-
- nsec_expected = (buffer_frames_ - cb_threshold_) * 1000000000ULL /
- (uint64_t)fmt_.frame_rate;
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(buffer_frames_ - cb_threshold_, dev_stream_mix_count);
- EXPECT_EQ(1, dev_stream_request_playback_samples_called);
- EXPECT_NE(-1, select_max_fd);
- EXPECT_EQ(0, memcmp(&select_out_fds, &select_in_fds, sizeof(select_in_fds)));
- EXPECT_EQ(0, shm_->area->read_offset[0]);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromTwoStreamsFull) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
-
- // Have cb_threshold samples left.
- frames_queued_ = cras_rstream_get_cb_threshold(rstream_);
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- nsec_expected = (uint64_t)cras_rstream_get_cb_threshold(rstream_) *
- 1000000000ULL / (uint64_t)fmt_.frame_rate;
-
- // shm has plenty of data in it.
- shm_->area->write_offset[0] = cras_rstream_get_cb_threshold(rstream_) * 4;
- shm2_->area->write_offset[0] = cras_rstream_get_cb_threshold(rstream2_) * 4;
-
- thread_add_stream(thread_, rstream2_);
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(2, dev_stream_mix_called);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(cras_rstream_get_cb_threshold(rstream_), dev_stream_mix_count);
- EXPECT_EQ(0, dev_stream_request_playback_samples_called);
- EXPECT_EQ(-1, select_max_fd);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromTwoOneEmptySmallerCbThreshold) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- // First stream is empty and with a smaller cb_threshold. This is to test
- // the case that when buffer level reaches the cb_threshold of one stream
- // but not yet the other stream of smaller cb_threshold.
- rstream_->cb_threshold -= 20;
- nsec_expected = 20 * 1000000000ULL / (uint64_t)fmt_.frame_rate;
- shm_->area->write_offset[0] = 0;
- shm2_->area->write_offset[0] = cras_shm_used_size(shm2_);
-
- thread_add_stream(thread_, rstream2_);
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
-
- // In this case, assert (1) we didn't request the empty stream since buffer
- // level is larger then its cb_threshold, (2) still mix both streams so
- // dev_stream_mix_count is zero, and (3) the resulting sleep frames
- // equals the cb_threshold difference.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(2, dev_stream_mix_called);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(0, dev_stream_mix_count);
- EXPECT_EQ(0, dev_stream_request_playback_samples_called);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromTwoOneEmptyAfterFetch) {
- struct timespec ts;
- int rc;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- // First stream empty while the second stream full.
- shm_->area->write_offset[0] = 0;
- shm2_->area->write_offset[0] = cras_shm_used_size(shm2_);
-
- thread_add_stream(thread_, rstream2_);
-
- FD_ZERO(&select_out_fds);
- FD_SET(rstream_->fd, &select_out_fds);
- select_return_value = 1;
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
-
- // Assert that the empty stream is skipped, only one stream mixed.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, dev_stream_mix_called);
- EXPECT_EQ(buffer_frames_ - cb_threshold_, dev_stream_mix_count);
- EXPECT_EQ(1, dev_stream_request_playback_samples_called);
- EXPECT_NE(-1, select_max_fd);
- EXPECT_EQ(0, memcmp(&select_out_fds, &select_in_fds, sizeof(select_in_fds)));
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromTwoStreamsFullOneMixes) {
- struct timespec ts;
- int rc;
- size_t written_expected;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- written_expected = buffer_frames_ - cb_threshold_;
-
- // shm has plenty of data in it.
- shm_->area->write_offset[0] = cras_shm_used_size(shm_);
- shm2_->area->write_offset[0] = cras_shm_used_size(shm2_);
-
- thread_add_stream(thread_, rstream2_);
-
- // Test that nothing breaks if one stream doesn't fill.
- dev_stream_mix_dont_fill_next = 1;
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, dev_stream_request_playback_samples_called);
- EXPECT_EQ(0, shm_->area->read_offset[0]); // No write from first stream.
- EXPECT_EQ(written_expected * 4, shm2_->area->read_offset[0]);
-}
-
-TEST_F(WriteStreamSuite, PossiblyFillGetFromTwoStreamsOneLimited) {
- struct timespec ts;
- int rc;
- uint64_t nsec_expected;
- static const unsigned int smaller_frames = 10;
-
- // Have cb_threshold samples left.
- frames_queued_ = cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- nsec_expected =
- (uint64_t)smaller_frames * (1000000000ULL / (uint64_t)fmt_.frame_rate);
-
- // One has too little the other is full.
- shm_->area->write_offset[0] = smaller_frames * 4;
- shm_->area->write_buf_idx = 1;
- shm2_->area->write_offset[0] = cras_shm_used_size(shm2_);
- shm2_->area->write_buf_idx = 1;
-
- thread_add_stream(thread_, rstream2_);
-
- FD_ZERO(&select_out_fds);
- FD_SET(rstream_->fd, &select_out_fds);
- select_return_value = 1;
-
- is_open_ = 1;
- rc = unified_io(thread_, &ts);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, nsec_expected - 1000);
- EXPECT_LE(ts.tv_nsec, nsec_expected + 1000);
- EXPECT_EQ(smaller_frames, dev_stream_mix_count);
- EXPECT_EQ(1, dev_stream_request_playback_samples_called);
- EXPECT_NE(-1, select_max_fd);
-}
-
-TEST_F(WriteStreamSuite, DrainOutputBufferCompelete) {
- frames_queued_ = 3 * cb_threshold_;
- close_dev_called_ = 0;
- // All the audio in hw buffer are extra silent frames.
- iodev_.extra_silent_frames = frames_queued_ + 1;
- drain_output_buffer(thread_, &iodev_);
- EXPECT_EQ(1, close_dev_called_);
-}
-
-TEST_F(WriteStreamSuite, DrainOutputBufferWaitForPlayback) {
- // Hardware buffer is full.
- frames_queued_ = buffer_frames_;
- iodev_.extra_silent_frames = 0;
- close_dev_called_ = 0;
- drain_output_buffer(thread_, &iodev_);
- EXPECT_EQ(0, close_dev_called_);
-}
-
-TEST_F(WriteStreamSuite, DrainOutputBufferWaitForAudio) {
- // Hardware buffer is almost empty
- frames_queued_ = 30;
- iodev_.extra_silent_frames = 0;
- close_dev_called_ = 0;
- drain_output_buffer(thread_, &iodev_);
- EXPECT_LT(cb_threshold_ - frames_queued_, frames_written_);
- EXPECT_EQ(0, close_dev_called_);
-}
-
-TEST_F(WriteStreamSuite, DrainOutputStream) {
- struct timespec ts;
- int rc;
-
- // Have 3 * cb_threshold samples in the hw buffer.
- // Have 4 * cb_threshold samples in the first stream's shm
- // Note: used_size = 5 * cb_threshold.
- frames_queued_ = 3 * cb_threshold_;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- shm_->area->write_offset[0] = 4 * cb_threshold_ * 4;
-
- is_open_ = 1;
- close_dev_called_ = 0;
- open_dev_called_ = 0;
-
- thread_disconnect_stream(thread_, rstream_);
-
- // We should be draining the audio.
- EXPECT_EQ(0, close_dev_called_);
- EXPECT_EQ(0, open_dev_called_);
-
- rc = unified_io(thread_, &ts);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(2 * cb_threshold_, frames_written_);
- EXPECT_EQ(0, open_dev_called_);
- EXPECT_EQ(0, close_dev_called_);
-
- // Clear the hardware buffer
- frames_queued_ = 0;
- frames_written_ = 0;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
-
- rc = unified_io(thread_, &ts);
-
- // Verified that all data in stream1 is written.
- // The device is not closed before we have played all the content.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(2 * cb_threshold_, frames_written_);
- EXPECT_EQ(0, close_dev_called_);
-
- // Clear the hardware buffer again.
- frames_queued_ = 0;
- frames_written_ = 0;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- rc = unified_io(thread_, &ts);
-
- EXPECT_EQ(1, cras_rstream_destroy_called);
- EXPECT_EQ(1, iodev_.is_draining);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(480, thread_->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(96, thread_->cb_threshold[CRAS_STREAM_OUTPUT]);
-
- // Clear the hardware buffer again.
- frames_queued_ = 0;
- frames_written_ = 0;
- audio_buffer_size_ = buffer_frames_ - frames_queued_;
- rc = unified_io(thread_, &ts);
-
- EXPECT_EQ(1, close_dev_called_);
- EXPECT_EQ(0, thread_->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(0, thread_->cb_threshold[CRAS_STREAM_OUTPUT]);
-}
-
-// Test adding and removing streams.
-class AddStreamSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- memset(&cras_iodev_set_format_val, 0, sizeof(cras_iodev_set_format_val));
- cras_iodev_set_format_val.frame_rate = 44100;
- cras_iodev_set_format_val.num_channels = 2;
- cras_iodev_set_format_val.format = SND_PCM_FORMAT_S16_LE;
-
- memset(&iodev_, 0, sizeof(iodev_));
- iodev_.buffer_size = 16384;
- used_size_ = 480;
- cb_threshold_ = 96;
- iodev_.direction = CRAS_STREAM_OUTPUT;
-
- iodev_.is_open = is_open;
- iodev_.open_dev = open_dev;
- iodev_.close_dev = close_dev;
- iodev_.get_buffer = get_buffer;
- iodev_.put_buffer = put_buffer;
-
- is_open_ = 0;
- is_open_called_ = 0;
- open_dev_called_ = 0;
- close_dev_called_ = 0;
- open_dev_return_val_ = 0;
-
- cras_iodev_set_format_called = 0;
- cras_rstream_destroy_called = 0;
- cras_metrics_log_histogram_called = 0;
- cras_metrics_log_histogram_name = NULL;
- cras_metrics_log_histogram_sample = 0;
-
- audio_buffer_size_ = 8196;
- }
-
- virtual void TearDown() {}
-
- unsigned int GetCaptureSleepFrames() {
- // Account for padding the sleep interval to ensure the wake up happens
- // after the last desired frame is received.
- return cb_threshold_ + 16;
- }
-
- // Stub functions for the iodev structure.
- static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- size_t sz = sizeof(*area_) + sizeof(struct cras_channel_area) * 2;
-
- if (audio_buffer_size_ < *num)
- *num = audio_buffer_size_;
-
- area_ = (cras_audio_area*)calloc(1, sz);
- area_->frames = *num;
- area_->num_channels = 2;
- area_->channels[0].buf = audio_buffer_;
- channel_area_set_channel(&area_->channels[0], CRAS_CH_FL);
- area_->channels[0].step_bytes = 4;
- area_->channels[1].buf = audio_buffer_ + 2;
- channel_area_set_channel(&area_->channels[1], CRAS_CH_FR);
- area_->channels[1].step_bytes = 4;
-
- *area = area_;
- return 0;
- }
-
- static int put_buffer(cras_iodev* iodev, unsigned int num) {
- free(area_);
- return 0;
- }
-
- static int is_open(const cras_iodev* iodev) {
- is_open_called_++;
- return is_open_;
- }
-
- static int open_dev(cras_iodev* iodev) {
- open_dev_called_++;
- is_open_ = true;
- return open_dev_return_val_;
- }
-
- static int close_dev(cras_iodev* iodev) {
- close_dev_called_++;
- is_open_ = false;
- return 0;
- }
-
- void add_rm_two_streams(CRAS_STREAM_DIRECTION direction) {
- int rc;
- struct cras_rstream *new_stream, *second_stream;
- cras_audio_shm* shm;
- struct cras_audio_format* fmt;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
-
- fmt = (struct cras_audio_format*)malloc(sizeof(*fmt));
- memcpy(fmt, &cras_iodev_set_format_val, sizeof(*fmt));
- iodev_.direction = direction;
- new_stream = (struct cras_rstream*)calloc(1, sizeof(*new_stream));
- new_stream->fd = 55;
- new_stream->buffer_frames = 65;
- new_stream->cb_threshold = 80;
- new_stream->direction = direction;
- memcpy(&new_stream->format, fmt, sizeof(*fmt));
- shm = cras_rstream_output_shm(new_stream);
- shm->header =
- (struct cras_audio_shm_header*)calloc(1, sizeof(*shm->header));
-
- if (direction == CRAS_STREAM_INPUT)
- thread_set_active_dev(thread, &iodev_);
- else
- thread_set_active_dev(thread, &iodev_);
-
- thread_add_stream(thread, new_stream);
- EXPECT_EQ(1, thread->devs_open[direction]);
- EXPECT_EQ(1, open_dev_called_);
- EXPECT_EQ(65, thread->buffer_frames[direction]);
- if (direction == CRAS_STREAM_OUTPUT)
- EXPECT_EQ(32, thread->cb_threshold[direction]);
- else
- EXPECT_EQ(80, thread->cb_threshold[direction]);
-
- is_open_ = 1;
-
- second_stream = (struct cras_rstream*)calloc(1, sizeof(*second_stream));
- second_stream->fd = 56;
- second_stream->buffer_frames = 25;
- second_stream->cb_threshold = 12;
- second_stream->direction = direction;
- memcpy(&second_stream->format, fmt, sizeof(*fmt));
- shm = cras_rstream_output_shm(second_stream);
- shm->header =
- (struct cras_audio_shm_header*)calloc(1, sizeof(*shm->header));
-
- is_open_called_ = 0;
- thread_add_stream(thread, second_stream);
- EXPECT_EQ(1, thread->devs_open[direction]);
- EXPECT_EQ(1, open_dev_called_);
- EXPECT_EQ(25, thread->buffer_frames[direction]);
- EXPECT_EQ(12, thread->cb_threshold[direction]);
-
- // Remove the streams.
- rc = thread_remove_stream(thread, second_stream);
- EXPECT_EQ(1, rc);
- EXPECT_EQ(0, close_dev_called_);
- if (direction == CRAS_STREAM_OUTPUT)
- EXPECT_EQ(32, thread->cb_threshold[direction]);
- else
- EXPECT_EQ(80, thread->cb_threshold[direction]);
-
- rc = thread_remove_stream(thread, new_stream);
- EXPECT_EQ(0, rc);
-
- // For output stream, we enter the draining mode;
- // for input stream, we close the device directly.
- if (direction == CRAS_STREAM_INPUT) {
- EXPECT_EQ(0, thread->devs_open[direction]);
- EXPECT_EQ(0, thread->buffer_frames[direction]);
- EXPECT_EQ(0, thread->cb_threshold[direction]);
- } else {
- EXPECT_EQ(1, iodev_.is_draining);
- }
-
- free(fmt);
- shm = cras_rstream_output_shm(new_stream);
- audio_thread_destroy(thread);
- free(shm->header);
- free(new_stream);
- shm = cras_rstream_output_shm(second_stream);
- free(shm->header);
- free(second_stream);
- }
-
- struct cras_iodev iodev_;
- static int is_open_;
- static int is_open_called_;
- static int open_dev_called_;
- static int open_dev_return_val_;
- static int close_dev_called_;
- static int used_size_;
- static int cb_threshold_;
- struct cras_audio_format fmt_;
- static struct cras_audio_area* area_;
- static uint8_t audio_buffer_[8192];
- static unsigned int audio_buffer_size_;
-};
-
-int AddStreamSuite::is_open_ = 0;
-int AddStreamSuite::is_open_called_ = 0;
-int AddStreamSuite::open_dev_called_ = 0;
-int AddStreamSuite::open_dev_return_val_ = 0;
-int AddStreamSuite::close_dev_called_ = 0;
-int AddStreamSuite::used_size_ = 0;
-int AddStreamSuite::cb_threshold_ = 0;
-struct cras_audio_area* AddStreamSuite::area_;
-uint8_t AddStreamSuite::audio_buffer_[8192];
-unsigned int AddStreamSuite::audio_buffer_size_ = 0;
-
-TEST_F(AddStreamSuite, SimpleAddOutputStream) {
- int rc;
- cras_rstream* new_stream;
- cras_audio_shm* shm;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
-
- new_stream = (struct cras_rstream*)calloc(1, sizeof(*new_stream));
- new_stream->client = (struct cras_rclient*)this;
- new_stream->fd = 55;
- new_stream->buffer_frames = 65;
- new_stream->cb_threshold = 80;
- memcpy(&new_stream->format, &cras_iodev_set_format_val,
- sizeof(cras_iodev_set_format_val));
-
- shm = cras_rstream_output_shm(new_stream);
- shm->header = (struct cras_audio_shm_header*)calloc(1, sizeof(*shm->header));
-
- thread_set_active_dev(thread, &iodev_);
-
- rc = thread_add_stream(thread, new_stream);
- ASSERT_EQ(0, rc);
- EXPECT_EQ(1, thread->devs_open[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(1, open_dev_called_);
- EXPECT_EQ(65, thread->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(32, thread->cb_threshold[CRAS_STREAM_OUTPUT]);
-
- is_open_ = 1;
-
- // remove the stream.
- rc = thread_remove_stream(thread, new_stream);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, iodev_.is_draining);
- EXPECT_EQ(0, cras_metrics_log_histogram_called);
- EXPECT_EQ(0, cras_rstream_destroy_called);
-
- rc = thread_disconnect_stream(thread, new_stream);
- EXPECT_EQ(1, cras_rstream_destroy_called);
-
- free(shm->header);
- audio_thread_destroy(thread);
- free(new_stream);
-}
-
-TEST_F(AddStreamSuite, AddStreamOpenFail) {
- struct audio_thread* thread;
- cras_rstream new_stream;
- cras_audio_shm* shm;
-
- thread = audio_thread_create();
- ASSERT_TRUE(thread);
- thread_set_active_dev(thread, &iodev_);
- printf("1\n");
-
- shm = cras_rstream_output_shm(&new_stream);
- shm->header = (struct cras_audio_shm_header*)calloc(1, sizeof(*shm->header));
-
- open_dev_return_val_ = -1;
- new_stream.direction = CRAS_STREAM_OUTPUT;
- EXPECT_EQ(AUDIO_THREAD_OUTPUT_DEV_ERROR,
- thread_add_stream(thread, &new_stream));
- printf("2\n");
- EXPECT_EQ(1, open_dev_called_);
- EXPECT_EQ(1, cras_iodev_set_format_called);
- audio_thread_destroy(thread);
- printf("3\n");
- free(shm->header);
-}
-
-TEST_F(AddStreamSuite, AddRmTwoOutputStreams) {
- add_rm_two_streams(CRAS_STREAM_OUTPUT);
-}
-
-TEST_F(AddStreamSuite, AddRmTwoInputStreams) {
- add_rm_two_streams(CRAS_STREAM_INPUT);
-}
-
-TEST_F(AddStreamSuite, RmStreamLogLongestTimeout) {
- int rc;
- cras_rstream* new_stream;
- cras_audio_shm* shm;
- struct audio_thread* thread;
-
- thread = audio_thread_create();
-
- new_stream = (struct cras_rstream*)calloc(1, sizeof(*new_stream));
- new_stream->fd = 55;
- new_stream->buffer_frames = 65;
- new_stream->cb_threshold = 80;
- memcpy(&new_stream->format, &cras_iodev_set_format_val,
- sizeof(cras_iodev_set_format_val));
-
- shm = cras_rstream_output_shm(new_stream);
- shm->header = (struct cras_audio_shm_header*)calloc(1, sizeof(*shm->header));
-
- thread_set_active_dev(thread, &iodev_);
- rc = thread_add_stream(thread, new_stream);
- ASSERT_EQ(0, rc);
- EXPECT_EQ(1, thread->devs_open[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(1, open_dev_called_);
- EXPECT_EQ(65, thread->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(32, thread->cb_threshold[CRAS_STREAM_OUTPUT]);
-
- is_open_ = 1;
- cras_shm_set_longest_timeout(shm, 90);
-
- // remove the stream.
- rc = thread_remove_stream(thread, new_stream);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, iodev_.is_draining);
-
- cras_system_add_select_fd_callback(cras_system_add_select_fd_callback_data);
-
- EXPECT_EQ(1, cras_metrics_log_histogram_called);
- EXPECT_STREQ(kStreamTimeoutMilliSeconds, cras_metrics_log_histogram_name);
- EXPECT_EQ(90, cras_metrics_log_histogram_sample);
-
- free(shm->header);
- free(new_stream);
- audio_thread_destroy(thread);
-}
-
-class ActiveDevicesSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- memset(&cras_iodev_set_format_val, 0, sizeof(cras_iodev_set_format_val));
- cras_iodev_set_format_val.frame_rate = 44100;
- cras_iodev_set_format_val.num_channels = 2;
- cras_iodev_set_format_val.format = SND_PCM_FORMAT_S16_LE;
-
- memset(&iodev_, 0, sizeof(iodev_));
- memset(&iodev2_, 0, sizeof(iodev2_));
- iodev_.close_dev = close_dev;
- iodev_.is_open = is_open;
- iodev_.open_dev = open_dev;
- iodev_.delay_frames = delay_frames;
- iodev_.get_buffer = get_buffer;
- iodev_.put_buffer = put_buffer;
- iodev_.frames_queued = frames_queued;
- iodev_.delay_frames = delay_frames;
- iodev_.dev_running = dev_running;
- iodev_.buffer_size = 2048;
- iodev2_.close_dev = close_dev;
- iodev2_.is_open = is_open;
- iodev2_.open_dev = open_dev;
- iodev2_.delay_frames = delay_frames;
- iodev2_.get_buffer = get_buffer;
- iodev2_.put_buffer = put_buffer;
- iodev2_.frames_queued = frames_queued;
- iodev2_.delay_frames = delay_frames;
- iodev2_.dev_running = dev_running;
- iodev2_.buffer_size = 2048;
- thread_ = audio_thread_create();
- ASSERT_TRUE(thread_);
-
- buffer_frames_ = 500;
- cb_threshold_ = 250;
- SetupRstream(&rstream_);
- SetupRstream(&rstream2_);
- rstream2_->buffer_frames -= 50;
- rstream2_->cb_threshold -= 50;
-
- mock_audio_area1 = (cras_audio_area*)calloc(
- 1, sizeof(cras_audio_area) + 2 * sizeof(cras_channel_area));
- mock_audio_area1->num_channels = 2;
- channel_area_set_channel(&mock_audio_area1->channels[0], CRAS_CH_FL);
- channel_area_set_channel(&mock_audio_area1->channels[1], CRAS_CH_FR);
- rstream_->input_audio_area = mock_audio_area1;
- mock_audio_area2 = (cras_audio_area*)calloc(
- 1, sizeof(cras_audio_area) + 2 * sizeof(cras_channel_area));
- mock_audio_area2->num_channels = 2;
- channel_area_set_channel(&mock_audio_area2->channels[0], CRAS_CH_FL);
- channel_area_set_channel(&mock_audio_area2->channels[1], CRAS_CH_FR);
- rstream2_->input_audio_area = mock_audio_area2;
-
- cras_iodev_set_format_called = 0;
- close_dev_called_ = 0;
- is_open_ = 0;
- cras_fmt_conversion_needed_return_val = 0;
- open_dev_val_idx_ = 0;
- delay_frames_val_idx_ = 0;
- frames_queued_val_idx_ = 0;
- frames_queued_[0] = 250;
- frames_queued_[1] = 250;
- get_buffer_val_idx_ = 0;
- put_buffer_val_idx_ = 0;
- for (int i = 0; i < 8; i++) {
- open_dev_val_[i] = 0;
- delay_frames_[i] = 0;
- audio_buffer_size_[i] = 250;
- get_buffer_rc_[i] = 0;
- put_buffer_rc_[i] = 0;
- }
- }
-
- virtual void TearDown() {
- struct cras_audio_shm* shm;
- audio_thread_destroy(thread_);
- shm = cras_rstream_output_shm(rstream_);
- free(shm->header);
- free(rstream_);
- free(mock_audio_area1);
- free(mock_audio_area2);
- }
-
- void SetupRstream(struct cras_rstream** rstream) {
- struct cras_audio_shm* shm;
- *rstream = (struct cras_rstream*)calloc(1, sizeof(**rstream));
- memcpy(&(*rstream)->format, &cras_iodev_set_format_val,
- sizeof(cras_iodev_set_format_val));
- (*rstream)->direction = CRAS_STREAM_OUTPUT;
- (*rstream)->buffer_frames = buffer_frames_;
- (*rstream)->cb_threshold = cb_threshold_;
- shm = cras_rstream_output_shm(*rstream);
- shm->header = (struct cras_audio_shm_header*)calloc(
- 1, sizeof(*shm->header) + cb_threshold_ * 8);
- cras_shm_set_frame_bytes(shm, 4);
- cras_shm_set_used_size(shm, buffer_frames_ * cras_shm_frame_bytes(shm));
- shm = cras_rstream_input_shm(*rstream);
- shm->header = (struct cras_audio_shm_header*)calloc(
- 1, sizeof(*shm->header) + buffer_frames_ * 8);
- cras_shm_set_frame_bytes(shm, 4);
- cras_shm_set_used_size(shm, cb_threshold_ * cras_shm_frame_bytes(shm));
- }
-
- static int close_dev(struct cras_iodev* iodev) {
- close_dev_called_++;
- return 0;
- }
-
- static int is_open(const cras_iodev* iodev) { return is_open_; }
-
- static int open_dev(struct cras_iodev* iodev) {
- open_dev_val_idx_ %= 8;
- is_open_ = 1;
- return open_dev_val_[open_dev_val_idx_++];
- }
-
- static int delay_frames(const cras_iodev* iodev) {
- delay_frames_val_idx_ %= 8;
- return delay_frames_[delay_frames_val_idx_++];
- }
-
- static int dev_running(const cras_iodev* iodev) { return 1; }
-
- static int frames_queued(const cras_iodev* iodev) {
- frames_queued_val_idx_ %= 2;
- return frames_queued_[frames_queued_val_idx_++];
- }
-
- static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- size_t sz = sizeof(*area_) + sizeof(struct cras_channel_area) * 2;
-
- get_buffer_val_idx_ %= 8;
- if (audio_buffer_size_[get_buffer_val_idx_] < *num)
- *num = audio_buffer_size_[get_buffer_val_idx_];
-
- area_ = (cras_audio_area*)calloc(1, sz);
- area_->frames = *num;
- area_->num_channels = 2;
- area_->channels[0].buf = audio_buffer_[get_buffer_val_idx_];
- channel_area_set_channel(&area_->channels[0], CRAS_CH_FL);
- area_->channels[0].step_bytes = 4;
- area_->channels[1].buf = audio_buffer_[get_buffer_val_idx_] + 2;
- channel_area_set_channel(&area_->channels[1], CRAS_CH_FR);
- area_->channels[1].step_bytes = 4;
-
- *area = area_;
-
- get_buffer_val_idx_++;
- return 0;
- }
-
- static int put_buffer(cras_iodev* iodev, unsigned int num) {
- free(area_);
- put_buffer_val_idx_ %= 8;
- return put_buffer_rc_[put_buffer_val_idx_++];
- }
-
- static int is_open_;
- static int open_dev_val_[8];
- static int open_dev_val_idx_;
- static int close_dev_called_;
- static int buffer_frames_;
- static int cb_threshold_;
- static int frames_queued_[2];
- static int frames_queued_val_idx_;
- static uint8_t audio_buffer_[8][8192];
- static unsigned int audio_buffer_size_[8];
- static int get_buffer_rc_[8];
- static int put_buffer_rc_[8];
- static int get_buffer_val_idx_;
- static int put_buffer_val_idx_;
- struct cras_iodev iodev_;
- struct cras_iodev iodev2_;
- struct cras_rstream* rstream_;
- struct cras_rstream* rstream2_;
- struct audio_thread* thread_;
- static struct cras_audio_area* area_;
- static int delay_frames_val_idx_;
- static int delay_frames_[8];
-};
-
-int ActiveDevicesSuite::is_open_ = 0;
-int ActiveDevicesSuite::buffer_frames_ = 0;
-int ActiveDevicesSuite::cb_threshold_ = 0;
-int ActiveDevicesSuite::frames_queued_[2];
-int ActiveDevicesSuite::frames_queued_val_idx_;
-int ActiveDevicesSuite::close_dev_called_ = 0;
-int ActiveDevicesSuite::open_dev_val_[8];
-int ActiveDevicesSuite::open_dev_val_idx_ = 0;
-int ActiveDevicesSuite::delay_frames_val_idx_ = 0;
-int ActiveDevicesSuite::delay_frames_[8];
-uint8_t ActiveDevicesSuite::audio_buffer_[8][8192];
-unsigned int ActiveDevicesSuite::audio_buffer_size_[8];
-int ActiveDevicesSuite::get_buffer_val_idx_ = 0;
-int ActiveDevicesSuite::put_buffer_val_idx_ = 0;
-int ActiveDevicesSuite::get_buffer_rc_[8];
-int ActiveDevicesSuite::put_buffer_rc_[8];
-struct cras_audio_area* ActiveDevicesSuite::area_;
-
-TEST_F(ActiveDevicesSuite, SetActiveDevRemoveOld) {
- struct active_dev* adevs;
- struct cras_iodev iodev3_;
-
- iodev_.direction = CRAS_STREAM_INPUT;
- iodev2_.direction = CRAS_STREAM_INPUT;
- iodev3_.direction = CRAS_STREAM_INPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_NE((void*)NULL, adevs);
- EXPECT_EQ(adevs->dev, &iodev_);
- EXPECT_EQ(1, iodev_.is_active);
-
- /* Assert the first active dev is still iodev. */
- thread_add_active_dev(thread_, &iodev2_);
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adevs->dev, &iodev_);
-
- thread_set_active_dev(thread_, &iodev3_);
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adevs->dev, &iodev3_);
- EXPECT_EQ(iodev3_.is_active, 1);
- EXPECT_EQ(iodev_.is_active, 0);
-}
-
-TEST_F(ActiveDevicesSuite, SetActiveDevAlreadyInList) {
- struct active_dev* adevs;
- iodev_.direction = CRAS_STREAM_INPUT;
- iodev2_.direction = CRAS_STREAM_INPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adevs->dev, &iodev_);
- EXPECT_EQ(iodev_.is_active, 1);
-
- thread_set_active_dev(thread_, &iodev2_);
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ(adevs->dev, &iodev2_);
- EXPECT_EQ(iodev2_.is_active, 1);
- EXPECT_EQ(iodev_.is_active, 0);
-}
-
-TEST_F(ActiveDevicesSuite, AddRemoveActiveDevice) {
- struct active_dev* adevs;
- iodev_.direction = CRAS_STREAM_INPUT;
- iodev2_.direction = CRAS_STREAM_INPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_NE((void*)NULL, adevs);
- EXPECT_EQ(adevs->dev, &iodev_);
- EXPECT_EQ(1, iodev_.is_active);
-
- thread_add_active_dev(thread_, &iodev2_);
- EXPECT_NE((void*)NULL, adevs->next);
- EXPECT_EQ(adevs->next->dev, &iodev2_);
- EXPECT_EQ(1, iodev2_.is_active);
-
- thread_rm_active_dev(thread_, &iodev_);
- adevs = thread_->active_devs[CRAS_STREAM_INPUT];
- EXPECT_EQ((void*)NULL, adevs->next);
- EXPECT_EQ(adevs->dev, &iodev2_);
- EXPECT_EQ(0, iodev_.is_active);
-
- iodev_.direction = CRAS_STREAM_POST_MIX_PRE_DSP;
- thread_add_active_dev(thread_, &iodev_);
- EXPECT_NE((void*)NULL, thread_->active_devs[CRAS_STREAM_POST_MIX_PRE_DSP]);
- EXPECT_EQ(1, iodev_.is_active);
-}
-
-TEST_F(ActiveDevicesSuite, ClearActiveDevices) {
- iodev_.direction = CRAS_STREAM_OUTPUT;
- iodev2_.direction = CRAS_STREAM_OUTPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
- EXPECT_NE((void*)NULL, thread_->active_devs[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(1, iodev_.is_active);
- EXPECT_EQ(1, iodev2_.is_active);
-
- thread_clear_active_devs(thread_, CRAS_STREAM_OUTPUT);
- EXPECT_EQ((void*)NULL, thread_->active_devs[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(0, iodev_.is_active);
- EXPECT_EQ(0, iodev2_.is_active);
-}
-
-TEST_F(ActiveDevicesSuite, OpenActiveDevices) {
- iodev_.direction = CRAS_STREAM_OUTPUT;
- iodev2_.direction = CRAS_STREAM_OUTPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
- thread_add_stream(thread_, rstream_);
-
- EXPECT_EQ(2, cras_iodev_set_format_called);
- EXPECT_EQ(500, thread_->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(250, thread_->cb_threshold[CRAS_STREAM_OUTPUT]);
-}
-
-TEST_F(ActiveDevicesSuite, OpenFirstActiveDeviceFail) {
- int rc;
- iodev_.direction = CRAS_STREAM_OUTPUT;
- iodev2_.direction = CRAS_STREAM_OUTPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- open_dev_val_[0] = -1;
- rc = thread_add_stream(thread_, rstream_);
- EXPECT_EQ(rc, AUDIO_THREAD_OUTPUT_DEV_ERROR);
- EXPECT_EQ(2, cras_iodev_set_format_called);
- EXPECT_EQ(0, thread_->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(0, thread_->cb_threshold[CRAS_STREAM_OUTPUT]);
-}
-
-TEST_F(ActiveDevicesSuite, OpenSecondActiveDeviceFail) {
- int rc;
- iodev_.direction = CRAS_STREAM_OUTPUT;
- iodev2_.direction = CRAS_STREAM_OUTPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- open_dev_val_[1] = -1;
- rc = thread_add_stream(thread_, rstream_);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(2, cras_iodev_set_format_called);
- EXPECT_EQ(500, thread_->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(250, thread_->cb_threshold[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(0, close_dev_called_);
- EXPECT_EQ((void*)NULL, thread_->active_devs[CRAS_STREAM_OUTPUT]->next);
-}
-
-TEST_F(ActiveDevicesSuite, OpenSecondActiveDeviceFormatIncompatible) {
- int rc;
- iodev_.direction = CRAS_STREAM_OUTPUT;
- iodev2_.direction = CRAS_STREAM_OUTPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- cras_fmt_conversion_needed_return_val = 1;
- rc = thread_add_stream(thread_, rstream_);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(2, cras_iodev_set_format_called);
- EXPECT_EQ(500, thread_->buffer_frames[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(250, thread_->cb_threshold[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(1, close_dev_called_);
- EXPECT_EQ((void*)NULL, thread_->active_devs[CRAS_STREAM_OUTPUT]->next);
-}
-
-TEST_F(ActiveDevicesSuite, CloseActiveDevices) {
- iodev_.direction = CRAS_STREAM_OUTPUT;
- iodev2_.direction = CRAS_STREAM_OUTPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- thread_add_stream(thread_, rstream_);
- EXPECT_EQ(1, thread_->devs_open[CRAS_STREAM_OUTPUT]);
- EXPECT_EQ(2, cras_iodev_set_format_called);
-
- thread_add_stream(thread_, rstream2_);
- EXPECT_EQ(4, cras_iodev_set_format_called);
-
- thread_remove_stream(thread_, rstream2_);
-
- thread_remove_stream(thread_, rstream_);
- EXPECT_EQ(1, iodev_.is_draining);
- EXPECT_EQ(1, iodev2_.is_draining);
-}
-
-TEST_F(ActiveDevicesSuite, InputDelayFrames) {
- int fr;
- iodev_.direction = CRAS_STREAM_INPUT;
- iodev2_.direction = CRAS_STREAM_INPUT;
- rstream_->direction = CRAS_STREAM_INPUT;
-
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- thread_add_stream(thread_, rstream_);
- delay_frames_[0] = 3;
- delay_frames_[1] = 33;
- fr = input_delay_frames(thread_->active_devs[CRAS_STREAM_INPUT]);
- EXPECT_EQ(33, fr);
-
- delay_frames_val_idx_ = 0;
- delay_frames_[1] = -1;
- fr = input_delay_frames(thread_->active_devs[CRAS_STREAM_INPUT]);
- EXPECT_EQ(-1, fr);
-}
-
-TEST_F(ActiveDevicesSuite, InputFramesQueued) {
- int fr;
- iodev_.direction = CRAS_STREAM_INPUT;
- iodev2_.direction = CRAS_STREAM_INPUT;
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
- frames_queued_val_idx_ = 0;
- frames_queued_[0] = 195;
- frames_queued_[1] = 190;
- fr = input_min_frames_queued(thread_->active_devs[CRAS_STREAM_INPUT]);
- EXPECT_EQ(190, fr);
-
- /* Test error path. */
- frames_queued_val_idx_ = 0;
- frames_queued_[0] = -1;
- frames_queued_[1] = 190;
- fr = input_min_frames_queued(thread_->active_devs[CRAS_STREAM_INPUT]);
- EXPECT_EQ(-1, fr);
-}
-
-TEST_F(ActiveDevicesSuite, MixMultipleInputs) {
- struct timespec ts;
-
- iodev_.direction = CRAS_STREAM_INPUT;
- iodev2_.direction = CRAS_STREAM_INPUT;
- rstream_->direction = CRAS_STREAM_INPUT;
- rstream2_->direction = CRAS_STREAM_INPUT;
-
- for (unsigned int dev = 0; dev < 8; dev++) {
- int16_t* buff = (int16_t*)audio_buffer_[dev];
- for (unsigned int i = 0; i < 250; i++)
- buff[i] = i;
- }
- thread_set_active_dev(thread_, &iodev_);
- thread_add_active_dev(thread_, &iodev2_);
-
- /* Assert shm from rstream_ is used. */
- thread_add_stream(thread_, rstream_);
- unified_io(thread_, &ts);
- EXPECT_EQ(rstream_, cap_sleep_frames_call.dev_stream->stream);
-
- thread_add_stream(thread_, rstream2_);
- unified_io(thread_, &ts);
- EXPECT_EQ(rstream2_, cap_sleep_frames_call.dev_stream->stream);
-}
-
-extern "C" {
-
-const char kNoCodecsFoundMetric[] = "Cras.NoCodecsFoundAtBoot";
-const char kStreamTimeoutMilliSeconds[] = "Cras.StreamTimeoutMilliSeconds";
-
-int cras_iodev_get_thread_poll_fd(const struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_read_thread_command(struct cras_iodev* iodev,
- uint8_t* buf,
- size_t max_len) {
- return 0;
-}
-
-int cras_iodev_send_command_response(struct cras_iodev* iodev, int rc) {
- return 0;
-}
-
-void cras_iodev_fill_time_from_frames(size_t frames,
- size_t frame_rate,
- struct timespec* ts) {
- uint64_t to_play_usec;
-
- ts->tv_sec = 0;
- /* adjust sleep time to target our callback threshold */
- to_play_usec = (uint64_t)frames * 1000000L / (uint64_t)frame_rate;
-
- while (to_play_usec > 1000000) {
- ts->tv_sec++;
- to_play_usec -= 1000000;
- }
- ts->tv_nsec = to_play_usec * 1000;
-}
-
-void dev_stream_set_delay(const struct dev_stream* dev_stream,
- unsigned int delay_frames) {
- dev_stream_set_delay_called++;
-}
-
-void cras_set_capture_timestamp(size_t frame_rate,
- size_t frames,
- struct cras_timespec* ts) {}
-
-int cras_iodev_set_format(struct cras_iodev* iodev,
- struct cras_audio_format* fmt) {
- cras_iodev_set_format_called++;
- iodev->format = &cras_iodev_set_format_val;
- return 0;
-}
-
-// From mixer.
-unsigned int dev_stream_mix(struct dev_stream* dev_stream,
- size_t num_channels,
- uint8_t* dst,
- size_t* count,
- size_t* index) {
- int16_t* src;
- int16_t* target = (int16_t*)dst;
- size_t fr_written, fr_in_buf;
- size_t num_samples;
- size_t frames = 0;
- struct cras_audio_shm* shm;
-
- if (dev_stream->stream->direction == CRAS_STREAM_OUTPUT) {
- shm = &dev_stream->stream->output_shm;
- } else {
- shm = &dev_stream->stream->input_shm;
- }
-
- dev_stream_mix_called++;
-
- if (dev_stream_mix_dont_fill_next) {
- dev_stream_mix_dont_fill_next = 0;
- return 0;
- }
- dev_stream_mix_count = *count;
-
- /* We only copy the data from shm to dst, not actually mix them. */
- fr_in_buf = cras_shm_get_frames(shm);
- if (fr_in_buf == 0)
- return 0;
- if (fr_in_buf < *count)
- *count = fr_in_buf;
-
- fr_written = 0;
- while (fr_written < *count) {
- src = cras_shm_get_readable_frames(shm, fr_written, &frames);
- if (frames > *count - fr_written)
- frames = *count - fr_written;
- num_samples = frames * num_channels;
- memcpy(target, src, num_samples * 2);
- fr_written += frames;
- target += num_samples;
- }
-
- *index = *index + 1;
- cras_shm_buffer_read(shm, fr_written);
- return *count;
-}
-
-void cras_scale_buffer(int16_t* buffer, unsigned int count, float scaler) {}
-
-size_t cras_mix_mute_buffer(uint8_t* dst, size_t frame_bytes, size_t count) {
- cras_mix_mute_count = count;
- return count;
-}
-
-void cras_mix_add_clip(int16_t* dst, const int16_t* src, size_t count) {
- int32_t sum;
- unsigned int i;
-
- for (i = 0; i < count; i++) {
- sum = dst[i] + src[i];
- if (sum > 0x7fff)
- sum = 0x7fff;
- else if (sum < -0x8000)
- sum = -0x8000;
- dst[i] = sum;
- }
-}
-
-// From cras_metrics.c
-void cras_metrics_log_event(const char* event) {
- cras_metrics_log_event_called++;
-}
-
-void cras_metrics_log_histogram(const char* name,
- int sample,
- int min,
- int max,
- int nbuckets) {
- cras_metrics_log_histogram_called++;
- cras_metrics_log_histogram_name = name;
- cras_metrics_log_histogram_sample = sample;
-}
-
-// From util.
-int cras_set_rt_scheduling(int rt_lim) {
- return 0;
-}
-
-int cras_set_thread_priority(int priority) {
- return 0;
-}
-
-// From rstream.
-int cras_rstream_get_audio_request_reply(const struct cras_rstream* stream) {
- return 0;
-}
-
-void cras_rstream_log_overrun(const struct cras_rstream* stream) {}
-
-int cras_system_add_select_fd(int fd,
- void (*callback)(void* data),
- void* callback_data) {
- cras_system_add_select_fd_callback = callback;
- cras_system_add_select_fd_callback_data = callback_data;
- return 0;
-}
-
-void cras_system_rm_select_fd(int fd) {}
-
-size_t cras_system_get_volume() {
- return cras_system_get_volume_return;
-}
-
-int cras_system_get_mute() {
- return 0;
-}
-
-int cras_system_get_capture_mute() {
- return 0;
-}
-
-void cras_rstream_destroy(struct cras_rstream* stream) {
- cras_rstream_destroy_called++;
-}
-
-void loopback_iodev_set_format(struct cras_iodev* loopback_dev,
- const struct cras_audio_format* fmt) {}
-
-int loopback_iodev_add_audio(struct cras_iodev* loopback_dev,
- const uint8_t* audio,
- unsigned int count) {
- return 0;
-}
-
-int loopback_iodev_add_zeros(struct cras_iodev* dev, unsigned int count) {
- return 0;
-}
-
-int cras_fmt_conversion_needed(const struct cras_audio_format* a,
- const struct cras_audio_format* b) {
- return cras_fmt_conversion_needed_return_val;
-}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {
- unsigned int i;
- const int sample_size = snd_pcm_format_physical_width(fmt->format) / 8;
-
- /* TODO(dgreid) - assuming interleaved audio here for now. */
- for (i = 0; i < area->num_channels; i++) {
- area->channels[i].step_bytes = cras_get_format_bytes(fmt);
- area->channels[i].buf = base_buffer + i * sample_size;
- }
-}
-
-void cras_audio_area_copy(const struct cras_audio_area* dst,
- unsigned int dst_offset,
- unsigned int dst_format_bytes,
- const struct cras_audio_area* src,
- unsigned int src_index) {
- unsigned count, i;
- int16_t *dchan, *schan;
-
- if (src_index == 0)
- memset(dst->channels[0].buf, 0, src->frames * dst_format_bytes);
-
- dchan = (int16_t*)(dst->channels[0].buf +
- dst_offset * dst->channels[0].step_bytes);
- schan = (int16_t*)src->channels[0].buf;
- count = src->frames * src->num_channels;
- for (i = 0; i < count; i++) {
- int32_t sum;
- sum = *dchan + *schan;
- if (sum > 0x7fff)
- sum = 0x7fff;
- else if (sum < -0x8000)
- sum = -0x8000;
- *dchan = sum;
- dchan++;
- schan++;
- }
-}
-
-// Override select so it can be stubbed.
-int select(int nfds,
- fd_set* readfds,
- fd_set* writefds,
- fd_set* exceptfds,
- struct timeval* timeout) {
- select_max_fd = nfds;
- select_timeval.tv_sec = timeout->tv_sec;
- select_timeval.tv_usec = timeout->tv_usec;
- select_in_fds = *readfds;
- *readfds = select_out_fds;
- if (select_write_ptr)
- *select_write_ptr = select_write_value;
- return select_return_value;
-}
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = time_now;
- return 0;
-}
-
-struct dev_stream* dev_stream_create(struct cras_rstream* stream,
- const struct cras_audio_format* fmt) {
- struct dev_stream* out = static_cast<dev_stream*>(calloc(1, sizeof(*out)));
- out->stream = stream;
-
- return out;
-}
-
-void dev_stream_destroy(struct dev_stream* dev_stream) {
- free(dev_stream);
-}
-
-void dev_stream_capture(struct dev_stream* dev_stream,
- const struct cras_audio_area* area,
- unsigned int dev_index) {
- dev_stream_capture_call.dev_stream = dev_stream;
- dev_stream_capture_call.area = area;
- dev_stream_capture_call.dev_index = dev_index;
- dev_stream_capture_call.num_called++;
-}
-
-int dev_stream_playback_frames(const struct dev_stream* dev_stream) {
- struct cras_audio_shm* shm;
- int frames;
-
- shm = cras_rstream_output_shm(dev_stream->stream);
-
- frames = cras_shm_get_frames(shm);
- if (frames < 0)
- return frames;
-
- if (!dev_stream->conv)
- return frames;
-
- return cras_fmt_conv_in_frames_to_out(dev_stream->conv, frames);
-}
-
-unsigned int dev_stream_capture_avail(const struct dev_stream* dev_stream) {
- struct cras_audio_shm* shm;
- struct cras_rstream* rstream = dev_stream->stream;
- unsigned int cb_threshold = cras_rstream_get_cb_threshold(rstream);
- unsigned int frames_avail;
-
- shm = cras_rstream_input_shm(rstream);
-
- cras_shm_get_writeable_frames(shm, cb_threshold, &frames_avail);
-
- return frames_avail;
-}
-
-int dev_stream_capture_sleep_frames(struct dev_stream* dev_stream,
- unsigned int written) {
- cap_sleep_frames_call.dev_stream = dev_stream;
- cap_sleep_frames_call.written = written;
- cap_sleep_frames_call.num_called++;
- return 0;
-}
-
-int dev_stream_request_playback_samples(struct dev_stream* dev_stream) {
- struct cras_rstream* rstream = dev_stream->stream;
-
- dev_stream_request_playback_samples_called++;
-
- cras_shm_set_callback_pending(cras_rstream_output_shm(rstream), 1);
- return 0;
-}
-
-size_t cras_fmt_conv_in_frames_to_out(struct cras_fmt_conv* conv,
- size_t in_frames) {
- return in_frames;
-}
-
-size_t cras_fmt_conv_out_frames_to_in(struct cras_fmt_conv* conv,
- size_t out_frames) {
- return out_frames;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/biquad_unittest.cc b/cras/src/tests/biquad_unittest.cc
deleted file mode 100644
index 30e67ea9..00000000
--- a/cras/src/tests/biquad_unittest.cc
+++ /dev/null
@@ -1,216 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "biquad.h"
-
-#include <assert.h>
-#include <gtest/gtest.h>
-#include <math.h>
-
-namespace {
-
-TEST(InvalidFrequencyTest, All) {
- struct biquad bq, test_bq;
- float f_over = 1.5;
- float f_under = -0.1;
- double db_gain = 2;
- double A = pow(10.0, db_gain / 40);
-
- // check response to freq >= 1
- biquad_set(&bq, BQ_LOWPASS, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_HIGHPASS, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_BANDPASS, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_LOWSHELF, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = A * A;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_HIGHSHELF, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_PEAKING, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_NOTCH, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_ALLPASS, f_over, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- // check response to frew <= 0
- biquad_set(&bq, BQ_LOWPASS, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_HIGHPASS, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_BANDPASS, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_LOWSHELF, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_HIGHSHELF, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = A * A;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_PEAKING, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_NOTCH, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_ALLPASS, f_under, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-}
-
-TEST(InvalidQTest, All) {
- struct biquad bq, test_bq;
- float f = 0.5;
- float Q = -0.1;
- double db_gain = 2;
- double A = pow(10.0, db_gain / 40);
-
- // check response to Q <= 0
- // Low and High pass filters scope Q making the test mute
-
- biquad_set(&bq, BQ_BANDPASS, f, Q, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = 1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- // Low and high shelf do not compute resonance
-
- biquad_set(&bq, BQ_PEAKING, f, Q, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = A * A;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_NOTCH, f, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-
- biquad_set(&bq, BQ_ALLPASS, f, 0, db_gain);
- test_bq = {0, 0, 0, 0, 0, 0, 0, 0, 0};
- test_bq.b0 = -1;
- EXPECT_EQ(bq.b0, test_bq.b0);
- EXPECT_EQ(bq.b1, test_bq.b1);
- EXPECT_EQ(bq.b2, test_bq.b2);
- EXPECT_EQ(bq.a1, test_bq.a1);
- EXPECT_EQ(bq.a2, test_bq.a2);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/bt_device_unittest.cc b/cras/src/tests/bt_device_unittest.cc
deleted file mode 100644
index ccb581cc..00000000
--- a/cras/src/tests/bt_device_unittest.cc
+++ /dev/null
@@ -1,781 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "cras_bt_constants.h"
-#include "cras_bt_device.h"
-#include "cras_bt_io.h"
-#include "cras_bt_log.h"
-#include "cras_iodev.h"
-#include "cras_main_message.h"
-
-#define FAKE_OBJ_PATH "/obj/path"
-}
-
-static const unsigned int CONN_WATCH_MAX_RETRIES = 30;
-
-static struct cras_iodev* cras_bt_io_create_profile_ret;
-static struct cras_iodev* cras_bt_io_append_btio_val;
-static struct cras_ionode* cras_bt_io_get_profile_ret;
-static unsigned int cras_bt_io_create_called;
-static unsigned int cras_bt_io_append_called;
-static unsigned int cras_bt_io_remove_called;
-static unsigned int cras_bt_io_destroy_called;
-static enum cras_bt_device_profile cras_bt_io_create_profile_val;
-static enum cras_bt_device_profile cras_bt_io_append_profile_val;
-static unsigned int cras_bt_io_try_remove_ret;
-
-static cras_main_message* cras_main_message_send_msg;
-static cras_message_callback cras_main_message_add_handler_callback;
-static void* cras_main_message_add_handler_callback_data;
-static int cras_tm_create_timer_called;
-static int cras_tm_cancel_timer_called;
-static int cras_a2dp_start_called;
-static int cras_a2dp_suspend_connected_device_called;
-static int cras_hfp_ag_remove_conflict_called;
-static int cras_hfp_ag_start_called;
-static int cras_hfp_ag_suspend_connected_device_called;
-static void (*cras_tm_create_timer_cb)(struct cras_timer* t, void* data);
-static void* cras_tm_create_timer_cb_data;
-static int dbus_message_new_method_call_called;
-static const char* dbus_message_new_method_call_method;
-static struct cras_bt_device* cras_a2dp_connected_device_ret;
-static struct cras_bt_device* cras_a2dp_suspend_connected_device_dev;
-static struct cras_timer* cras_tm_cancel_timer_arg;
-static struct cras_timer* cras_tm_create_timer_ret;
-static size_t cras_iodev_set_node_plugged_called;
-static int cras_iodev_set_node_plugged_value;
-
-struct MockDBusMessage {
- int type;
- void* value;
- MockDBusMessage* next;
- MockDBusMessage* recurse;
-};
-
-void ResetStubData() {
- cras_bt_io_get_profile_ret = NULL;
- cras_bt_io_create_called = 0;
- cras_bt_io_append_called = 0;
- cras_bt_io_remove_called = 0;
- cras_bt_io_destroy_called = 0;
- cras_bt_io_try_remove_ret = 0;
- cras_main_message_send_msg = NULL;
- cras_tm_create_timer_called = 0;
- cras_tm_cancel_timer_called = 0;
- cras_a2dp_start_called = 0;
- cras_a2dp_suspend_connected_device_called = 0;
- cras_hfp_ag_remove_conflict_called = 0;
- cras_hfp_ag_start_called = 0;
- cras_hfp_ag_suspend_connected_device_called = 0;
- dbus_message_new_method_call_method = NULL;
- dbus_message_new_method_call_called = 0;
- cras_a2dp_connected_device_ret = NULL;
- cras_iodev_set_node_plugged_called = 0;
-}
-
-static void FreeMockDBusMessage(MockDBusMessage* head) {
- if (head->next != NULL)
- FreeMockDBusMessage(head->next);
- if (head->recurse != NULL)
- FreeMockDBusMessage(head->recurse);
- if (head->type == DBUS_TYPE_STRING)
- free((char*)head->value);
- delete head;
-}
-
-static struct MockDBusMessage* NewMockDBusConnectedMessage(long connected) {
- MockDBusMessage* msg = new MockDBusMessage{DBUS_TYPE_ARRAY, NULL};
- MockDBusMessage* dict =
- new MockDBusMessage{DBUS_TYPE_STRING, (void*)strdup("Connected")};
- MockDBusMessage* variant =
- new MockDBusMessage{DBUS_TYPE_BOOLEAN, (void*)connected};
-
- msg->recurse = dict;
- dict->next = new MockDBusMessage{DBUS_TYPE_INVALID, NULL};
- dict->next->recurse = variant;
- return msg;
-}
-
-namespace {
-
-class BtDeviceTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- ResetStubData();
- bt_iodev1.direction = CRAS_STREAM_OUTPUT;
- bt_iodev1.update_active_node = update_active_node;
- bt_iodev2.direction = CRAS_STREAM_INPUT;
- bt_iodev2.update_active_node = update_active_node;
- d1_.direction = CRAS_STREAM_OUTPUT;
- d1_.update_active_node = update_active_node;
- d2_.direction = CRAS_STREAM_OUTPUT;
- d2_.update_active_node = update_active_node;
- d3_.direction = CRAS_STREAM_INPUT;
- d3_.update_active_node = update_active_node;
- btlog = cras_bt_event_log_init();
- }
-
- virtual void TearDown() {
- if (cras_main_message_send_msg)
- free(cras_main_message_send_msg);
- cras_bt_event_log_deinit(btlog);
- }
-
- static void update_active_node(struct cras_iodev* iodev,
- unsigned node_idx,
- unsigned dev_enabled) {}
-
- struct cras_iodev bt_iodev1;
- struct cras_iodev bt_iodev2;
- struct cras_iodev d3_;
- struct cras_iodev d2_;
- struct cras_iodev d1_;
-};
-
-TEST(BtDeviceSuite, CreateBtDevice) {
- struct cras_bt_device* device;
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- device = cras_bt_device_get(FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_remove(device);
- device = cras_bt_device_get(FAKE_OBJ_PATH);
- EXPECT_EQ((void*)NULL, device);
-}
-
-TEST_F(BtDeviceTestSuite, AppendRmIodev) {
- struct cras_bt_device* device;
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- bt_iodev1.nodes = reinterpret_cast<struct cras_ionode*>(0x123);
- cras_bt_io_create_profile_ret = &bt_iodev1;
- cras_bt_device_append_iodev(device, &d1_, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
- EXPECT_EQ(1, cras_bt_io_create_called);
- EXPECT_EQ(0, cras_bt_io_append_called);
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE, cras_bt_io_create_profile_val);
- cras_bt_device_set_active_profile(device, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- cras_bt_device_append_iodev(device, &d2_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- EXPECT_EQ(1, cras_bt_io_create_called);
- EXPECT_EQ(1, cras_bt_io_append_called);
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY,
- cras_bt_io_append_profile_val);
- EXPECT_EQ(&bt_iodev1, cras_bt_io_append_btio_val);
-
- /* Test HFP disconnected and switch to A2DP. */
- cras_bt_io_get_profile_ret = bt_iodev1.nodes;
- cras_bt_io_try_remove_ret = CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
- cras_bt_device_set_active_profile(device,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- cras_bt_device_rm_iodev(device, &d2_);
- EXPECT_EQ(1, cras_bt_io_remove_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_value);
-
- /* Test A2DP disconnection will cause bt_io destroy. */
- cras_bt_io_try_remove_ret = 0;
- cras_bt_device_rm_iodev(device, &d1_);
- EXPECT_EQ(1, cras_bt_io_remove_called);
- EXPECT_EQ(1, cras_bt_io_destroy_called);
- EXPECT_EQ(0, cras_bt_device_get_active_profile(device));
- EXPECT_EQ(2, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(0, cras_iodev_set_node_plugged_value);
- cras_bt_device_remove(device);
-}
-
-TEST_F(BtDeviceTestSuite, SwitchProfile) {
- struct cras_bt_device* device;
-
- ResetStubData();
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- cras_bt_io_create_profile_ret = &bt_iodev1;
- cras_bt_device_append_iodev(device, &d1_, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
- cras_bt_io_create_profile_ret = &bt_iodev2;
- cras_bt_device_append_iodev(device, &d3_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- cras_bt_device_start_monitor();
- cras_bt_device_switch_profile_enable_dev(device, &bt_iodev1);
-
- /* Two bt iodevs were all active. */
- cras_main_message_add_handler_callback(
- cras_main_message_send_msg, cras_main_message_add_handler_callback_data);
-
- /* One bt iodev was active, the other was not. */
- cras_bt_device_switch_profile_enable_dev(device, &bt_iodev2);
- cras_main_message_add_handler_callback(
- cras_main_message_send_msg, cras_main_message_add_handler_callback_data);
-
- /* Output bt iodev wasn't active, close the active input iodev. */
- cras_bt_device_switch_profile(device, &bt_iodev2);
- cras_main_message_add_handler_callback(
- cras_main_message_send_msg, cras_main_message_add_handler_callback_data);
- cras_bt_device_remove(device);
-}
-
-TEST_F(BtDeviceTestSuite, SetDeviceConnectedA2dpOnly) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
-
- /* Schedule another timer, if A2DP not yet configured. */
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- /* ConnectProfile must not be called, since this is A2DP only case. */
- EXPECT_EQ(0, dbus_message_new_method_call_called);
-
- cras_bt_device_a2dp_configured(device);
-
- /* Prepate the iodev created by cras_a2dp_start. */
- cras_bt_io_create_profile_ret = &bt_iodev1;
- cras_bt_device_append_iodev(device, &d1_, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(2, cras_tm_create_timer_called);
- EXPECT_EQ(1, cras_hfp_ag_remove_conflict_called);
- EXPECT_EQ(1, cras_a2dp_start_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_value);
-
- cras_bt_device_remove(device);
- FreeMockDBusMessage(msg_root);
-}
-
-TEST_F(BtDeviceTestSuite, SetDeviceConnectedHfpHspOnly) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
-
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(
- device, CRAS_BT_DEVICE_PROFILE_HSP_HEADSET |
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
-
- /* Schedule another timer, if HFP AG not yet intialized. */
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- /* ConnectProfile must not be called, since this is HFP only case. */
- EXPECT_EQ(0, dbus_message_new_method_call_called);
-
- cras_bt_device_audio_gateway_initialized(device);
-
- /* Prepate the iodev created by ag initialization. */
- cras_bt_io_create_profile_ret = &bt_iodev2;
- cras_bt_device_append_iodev(device, &d3_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(2, cras_tm_create_timer_called);
- EXPECT_EQ(1, cras_hfp_ag_remove_conflict_called);
- EXPECT_EQ(1, cras_hfp_ag_start_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_called);
- EXPECT_EQ(1, cras_iodev_set_node_plugged_value);
-
- cras_bt_device_remove(device);
- FreeMockDBusMessage(msg_root);
-}
-
-TEST_F(BtDeviceTestSuite, SetDeviceConnectedA2dpHfpHsp) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
-
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK |
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET |
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
-
- /* Schedule another timer, if not HFP nor A2DP is ready. */
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- /* ConnectProfile must not be called, since the first profile connection
- * should be initiated by Bluez.
- */
- EXPECT_EQ(0, dbus_message_new_method_call_called);
-
- cras_bt_device_audio_gateway_initialized(device);
-
- /* Schedule another timer, because A2DP is not ready. */
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(3, cras_tm_create_timer_called);
- EXPECT_EQ(0, cras_hfp_ag_start_called);
-
- /* ConnectProfile should be called to connect A2DP, since HFP is connected */
- EXPECT_EQ(1, dbus_message_new_method_call_called);
- EXPECT_STREQ("ConnectProfile", dbus_message_new_method_call_method);
-
- cras_bt_device_a2dp_configured(device);
-
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(3, cras_tm_create_timer_called);
- EXPECT_EQ(1, cras_hfp_ag_remove_conflict_called);
- EXPECT_EQ(1, cras_a2dp_start_called);
- EXPECT_EQ(1, cras_hfp_ag_start_called);
-
- cras_bt_device_remove(device);
- FreeMockDBusMessage(msg_root);
-}
-
-TEST_F(BtDeviceTestSuite, DevConnectedConflictCheck) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
-
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK |
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET |
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- cras_bt_device_audio_gateway_initialized(device);
- cras_bt_device_a2dp_configured(device);
- EXPECT_EQ(1, cras_tm_create_timer_called);
-
- /* Fake that a different device already connected with A2DP */
- cras_a2dp_connected_device_ret =
- reinterpret_cast<struct cras_bt_device*>(0x99);
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(1, cras_tm_create_timer_called);
-
- /* Expect check conflict in HFP AG and A2DP. */
- EXPECT_EQ(1, cras_hfp_ag_remove_conflict_called);
- EXPECT_EQ(1, cras_a2dp_suspend_connected_device_called);
- EXPECT_EQ(cras_a2dp_suspend_connected_device_dev,
- cras_a2dp_connected_device_ret);
-
- EXPECT_EQ(1, cras_a2dp_start_called);
- EXPECT_EQ(1, cras_hfp_ag_start_called);
-
- cras_bt_device_remove(device);
- FreeMockDBusMessage(msg_root);
-}
-
-TEST_F(BtDeviceTestSuite, A2dpDropped) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
-
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK |
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET |
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- cras_bt_device_audio_gateway_initialized(device);
- cras_bt_device_a2dp_configured(device);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
-
- cras_bt_device_notify_profile_dropped(device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- /* Expect suspend timer is scheduled. */
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(1, cras_a2dp_suspend_connected_device_called);
- EXPECT_EQ(1, cras_hfp_ag_suspend_connected_device_called);
- EXPECT_EQ(1, dbus_message_new_method_call_called);
- EXPECT_STREQ("Disconnect", dbus_message_new_method_call_method);
-
- cras_bt_device_remove(device);
- FreeMockDBusMessage(msg_root);
-}
-
-TEST_F(BtDeviceTestSuite, DevConnectDisconnectBackToBack) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
-
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK |
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET |
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
- FreeMockDBusMessage(msg_root);
-
- cras_bt_device_a2dp_configured(device);
- cras_bt_device_audio_gateway_initialized(device);
-
- /* Expect suspend timer is scheduled. */
- cras_tm_create_timer_ret = reinterpret_cast<struct cras_timer*>(0x101);
- cras_bt_device_notify_profile_dropped(device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
- EXPECT_EQ(2, cras_tm_create_timer_called);
- /* Another profile drop won't schedule another timer because one is
- * already armed. */
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
- cras_bt_device_notify_profile_dropped(device,
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- cur = msg_root = NewMockDBusConnectedMessage(0);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
-
- /* When BlueZ reports headset disconnection, cancel the pending timer. */
- EXPECT_EQ(cras_tm_cancel_timer_called, 1);
- EXPECT_EQ(cras_tm_cancel_timer_arg, (void*)0x101);
- FreeMockDBusMessage(msg_root);
-
- /* Headset connects again. */
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- EXPECT_EQ(3, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
- FreeMockDBusMessage(msg_root);
-
- /* Headset disconnects, later profile drop events shouldn't trigger
- * suspend timer because headset is already in disconnected stats.
- */
- cur = msg_root = NewMockDBusConnectedMessage(0);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- FreeMockDBusMessage(msg_root);
-
- cras_tm_create_timer_called = 0;
- cras_bt_device_notify_profile_dropped(device,
- CRAS_BT_DEVICE_PROFILE_A2DP_SINK);
- EXPECT_EQ(0, cras_tm_create_timer_called);
- cras_bt_device_notify_profile_dropped(device,
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
- EXPECT_EQ(0, cras_tm_create_timer_called);
-
- cras_bt_device_remove(device);
-}
-
-TEST_F(BtDeviceTestSuite, ConnectionWatchTimeout) {
- struct cras_bt_device* device;
- struct MockDBusMessage *msg_root, *cur;
-
- ResetStubData();
-
- device = cras_bt_device_create(NULL, FAKE_OBJ_PATH);
- EXPECT_NE((void*)NULL, device);
-
- cras_bt_device_set_supported_profiles(
- device, CRAS_BT_DEVICE_PROFILE_A2DP_SINK |
- CRAS_BT_DEVICE_PROFILE_HSP_HEADSET |
- CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE);
-
- cur = msg_root = NewMockDBusConnectedMessage(1);
- cras_bt_device_update_properties(device, (DBusMessageIter*)&cur, NULL);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_create_timer_cb);
-
- cras_bt_device_a2dp_configured(device);
-
- for (unsigned int i = 0; i < CONN_WATCH_MAX_RETRIES; i++) {
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(i + 2, cras_tm_create_timer_called);
- EXPECT_EQ(0, cras_a2dp_start_called);
- EXPECT_EQ(0, cras_hfp_ag_start_called);
- EXPECT_EQ(0, cras_hfp_ag_remove_conflict_called);
- }
-
- dbus_message_new_method_call_called = 0;
-
- /* Expect suspend timer is scheduled. */
- cras_tm_create_timer_cb(NULL, cras_tm_create_timer_cb_data);
- EXPECT_EQ(1, cras_a2dp_suspend_connected_device_called);
- EXPECT_EQ(1, cras_hfp_ag_suspend_connected_device_called);
- EXPECT_EQ(1, dbus_message_new_method_call_called);
- EXPECT_STREQ("Disconnect", dbus_message_new_method_call_method);
-
- cras_bt_device_remove(device);
- FreeMockDBusMessage(msg_root);
-}
-
-/* Stubs */
-extern "C" {
-
-struct cras_bt_event_log* btlog;
-
-/* From bt_io */
-struct cras_iodev* cras_bt_io_create(struct cras_bt_device* device,
- struct cras_iodev* dev,
- enum cras_bt_device_profile profile) {
- cras_bt_io_create_called++;
- cras_bt_io_create_profile_val = profile;
- return cras_bt_io_create_profile_ret;
-}
-void cras_bt_io_destroy(struct cras_iodev* bt_iodev) {
- cras_bt_io_destroy_called++;
-}
-struct cras_ionode* cras_bt_io_get_profile(
- struct cras_iodev* bt_iodev,
- enum cras_bt_device_profile profile) {
- return cras_bt_io_get_profile_ret;
-}
-int cras_bt_io_append(struct cras_iodev* bt_iodev,
- struct cras_iodev* dev,
- enum cras_bt_device_profile profile) {
- cras_bt_io_append_called++;
- cras_bt_io_append_profile_val = profile;
- cras_bt_io_append_btio_val = bt_iodev;
- return 0;
-}
-int cras_bt_io_on_profile(struct cras_iodev* bt_iodev,
- enum cras_bt_device_profile profile) {
- return 0;
-}
-unsigned int cras_bt_io_try_remove(struct cras_iodev* bt_iodev,
- struct cras_iodev* dev) {
- return cras_bt_io_try_remove_ret;
-}
-int cras_bt_io_remove(struct cras_iodev* bt_iodev, struct cras_iodev* dev) {
- cras_bt_io_remove_called++;
- return 0;
-}
-
-/* From bt_adapter */
-struct cras_bt_adapter* cras_bt_adapter_get(const char* object_path) {
- return NULL;
-}
-const char* cras_bt_adapter_address(const struct cras_bt_adapter* adapter) {
- return NULL;
-}
-
-int cras_bt_adapter_on_usb(struct cras_bt_adapter* adapter) {
- return 1;
-}
-
-/* From bt_profile */
-void cras_bt_profile_on_device_disconnected(struct cras_bt_device* device) {}
-
-/* From hfp_ag_profile */
-struct hfp_slc_handle* cras_hfp_ag_get_slc(struct cras_bt_device* device) {
- return NULL;
-}
-
-void cras_hfp_ag_suspend_connected_device(struct cras_bt_device* device) {
- cras_hfp_ag_suspend_connected_device_called++;
-}
-
-void cras_a2dp_suspend_connected_device(struct cras_bt_device* device) {
- cras_a2dp_suspend_connected_device_called++;
- cras_a2dp_suspend_connected_device_dev = device;
-}
-
-void cras_a2dp_start(struct cras_bt_device* device) {
- cras_a2dp_start_called++;
-}
-
-struct cras_bt_device* cras_a2dp_connected_device() {
- return cras_a2dp_connected_device_ret;
-}
-
-int cras_hfp_ag_remove_conflict(struct cras_bt_device* device) {
- cras_hfp_ag_remove_conflict_called++;
- return 0;
-}
-
-int cras_hfp_ag_start(struct cras_bt_device* device) {
- cras_hfp_ag_start_called++;
- return 0;
-}
-
-void cras_hfp_ag_suspend() {}
-
-/* From hfp_slc */
-int hfp_event_speaker_gain(struct hfp_slc_handle* handle, int gain) {
- return 0;
-}
-
-/* From iodev_list */
-
-int cras_iodev_open(struct cras_iodev* dev,
- unsigned int cb_level,
- const struct cras_audio_format* fmt) {
- return 0;
-}
-
-int cras_iodev_close(struct cras_iodev* dev) {
- return 0;
-}
-
-void cras_iodev_set_node_plugged(struct cras_ionode* ionode, int plugged) {
- cras_iodev_set_node_plugged_called++;
- cras_iodev_set_node_plugged_value = plugged;
-}
-
-int cras_iodev_list_dev_is_enabled(const struct cras_iodev* dev) {
- return 0;
-}
-
-void cras_iodev_list_suspend_dev(struct cras_iodev* dev) {}
-
-void cras_iodev_list_resume_dev(struct cras_iodev* dev) {}
-
-void cras_iodev_list_notify_node_volume(struct cras_ionode* node) {}
-
-int cras_main_message_send(struct cras_main_message* msg) {
- // cras_main_message is a local variable from caller, we should allocate
- // memory from heap and copy its data
- if (cras_main_message_send_msg)
- free(cras_main_message_send_msg);
- cras_main_message_send_msg =
- (struct cras_main_message*)calloc(1, msg->length);
- memcpy((void*)cras_main_message_send_msg, (void*)msg, msg->length);
- return 0;
-}
-
-int cras_main_message_add_handler(enum CRAS_MAIN_MESSAGE_TYPE type,
- cras_message_callback callback,
- void* callback_data) {
- cras_main_message_add_handler_callback = callback;
- cras_main_message_add_handler_callback_data = callback_data;
- return 0;
-}
-
-/* From cras_system_state */
-struct cras_tm* cras_system_state_get_tm() {
- return NULL;
-}
-
-/* From cras_tm */
-struct cras_timer* cras_tm_create_timer(struct cras_tm* tm,
- unsigned int ms,
- void (*cb)(struct cras_timer* t,
- void* data),
- void* cb_data) {
- cras_tm_create_timer_called++;
- cras_tm_create_timer_cb = cb;
- cras_tm_create_timer_cb_data = cb_data;
- return cras_tm_create_timer_ret;
-}
-
-void cras_tm_cancel_timer(struct cras_tm* tm, struct cras_timer* t) {
- cras_tm_cancel_timer_called++;
- cras_tm_cancel_timer_arg = t;
-}
-
-DBusMessage* dbus_message_new_method_call(const char* destination,
- const char* path,
- const char* iface,
- const char* method) {
- dbus_message_new_method_call_called++;
- dbus_message_new_method_call_method = method;
- return reinterpret_cast<DBusMessage*>(0x456);
-}
-
-void dbus_message_unref(DBusMessage* message) {}
-
-dbus_bool_t dbus_message_append_args(DBusMessage* message,
- int first_arg_type,
- ...) {
- return true;
-}
-
-dbus_bool_t dbus_connection_send_with_reply(DBusConnection* connection,
- DBusMessage* message,
- DBusPendingCall** pending_return,
- int timeout_milliseconds) {
- return true;
-}
-
-dbus_bool_t dbus_pending_call_set_notify(DBusPendingCall* pending,
- DBusPendingCallNotifyFunction function,
- void* user_data,
- DBusFreeFunction free_user_data) {
- return true;
-}
-
-void dbus_message_iter_recurse(DBusMessageIter* iter, DBusMessageIter* sub) {
- MockDBusMessage* msg = *(MockDBusMessage**)iter;
- MockDBusMessage** cur = (MockDBusMessage**)sub;
- *cur = msg->recurse;
-}
-
-dbus_bool_t dbus_message_iter_next(DBusMessageIter* iter) {
- MockDBusMessage** cur = (MockDBusMessage**)iter;
- MockDBusMessage* msg = *cur;
- *cur = msg->next;
- return true;
-}
-
-int dbus_message_iter_get_arg_type(DBusMessageIter* iter) {
- MockDBusMessage* msg;
-
- if (iter == NULL)
- return DBUS_TYPE_INVALID;
-
- msg = *(MockDBusMessage**)iter;
- if (msg == NULL)
- return DBUS_TYPE_INVALID;
-
- return msg->type;
-}
-
-void dbus_message_iter_get_basic(DBusMessageIter* iter, void* value) {
- MockDBusMessage* msg = *(MockDBusMessage**)iter;
- switch (msg->type) {
- case DBUS_TYPE_BOOLEAN:
- memcpy(value, &msg->value, sizeof(int));
- break;
- case DBUS_TYPE_STRING:
- memcpy(value, &msg->value, sizeof(char*));
- break;
- }
-}
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/bt_io_unittest.cc b/cras/src/tests/bt_io_unittest.cc
deleted file mode 100644
index dd02652f..00000000
--- a/cras/src/tests/bt_io_unittest.cc
+++ /dev/null
@@ -1,493 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-extern "C" {
-
-// To test static functions.
-#include "cras_bt_io.c"
-#include "utlist.h"
-}
-
-static struct cras_bt_device* fake_device =
- reinterpret_cast<struct cras_bt_device*>(0x123);
-static unsigned int cras_iodev_add_node_called;
-static unsigned int cras_iodev_rm_node_called;
-static unsigned int cras_iodev_free_format_called;
-static unsigned int cras_iodev_free_resources_called;
-static unsigned int cras_iodev_set_active_node_called;
-static unsigned int cras_iodev_list_add_output_called;
-static unsigned int cras_iodev_list_rm_output_called;
-static unsigned int cras_iodev_list_add_input_called;
-static unsigned int cras_iodev_list_rm_input_called;
-static unsigned int cras_bt_device_set_active_profile_called;
-static unsigned int cras_bt_device_set_active_profile_val;
-static int cras_bt_device_get_active_profile_ret;
-static int cras_bt_device_switch_profile_enable_dev_called;
-static int cras_bt_device_switch_profile_called;
-static int cras_bt_device_can_switch_to_a2dp_ret;
-static int cras_bt_device_has_a2dp_ret;
-static int is_utf8_string_ret_value;
-
-void ResetStubData() {
- cras_iodev_add_node_called = 0;
- cras_iodev_rm_node_called = 0;
- cras_iodev_free_format_called = 0;
- cras_iodev_free_resources_called = 0;
- cras_iodev_set_active_node_called = 0;
- cras_iodev_list_add_output_called = 0;
- cras_iodev_list_rm_output_called = 0;
- cras_iodev_list_add_input_called = 0;
- cras_iodev_list_rm_input_called = 0;
- cras_bt_device_set_active_profile_called = 0;
- cras_bt_device_set_active_profile_val = 0;
- cras_bt_device_get_active_profile_ret = 0;
- cras_bt_device_switch_profile_enable_dev_called = 0;
- cras_bt_device_switch_profile_called = 0;
- cras_bt_device_can_switch_to_a2dp_ret = 0;
- cras_bt_device_has_a2dp_ret = 0;
- is_utf8_string_ret_value = 1;
-}
-
-namespace {
-
-class BtIoBasicSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- ResetStubData();
- SetUpIodev(&iodev_, CRAS_STREAM_OUTPUT);
- SetUpIodev(&iodev2_, CRAS_STREAM_OUTPUT);
- iodev_.active_node = &node_;
- iodev2_.active_node = &node2_;
-
- update_supported_formats_called_ = 0;
- frames_queued_called_ = 0;
- delay_frames_called_ = 0;
- get_buffer_called_ = 0;
- put_buffer_called_ = 0;
- configure_dev_called_ = 0;
- close_dev_called_ = 0;
- }
-
- virtual void TearDown() {}
-
- static void SetUpIodev(struct cras_iodev* d, enum CRAS_STREAM_DIRECTION dir) {
- d->direction = dir;
- d->update_supported_formats = update_supported_formats;
- d->frames_queued = frames_queued;
- d->delay_frames = delay_frames;
- d->get_buffer = get_buffer;
- d->put_buffer = put_buffer;
- d->configure_dev = configure_dev;
- d->close_dev = close_dev;
- d->supported_rates = NULL;
- d->supported_channel_counts = NULL;
- d->supported_formats = NULL;
- }
-
- // Stub functions for the iodev structure.
- static int update_supported_formats(struct cras_iodev* iodev) {
- free(iodev->supported_rates);
- free(iodev->supported_channel_counts);
- free(iodev->supported_formats);
- iodev->supported_rates =
- (size_t*)calloc(2, sizeof(*iodev->supported_rates));
- iodev->supported_rates[0] = 48000;
- iodev->supported_rates[1] = 0;
- iodev->supported_channel_counts =
- (size_t*)calloc(2, sizeof(*iodev->supported_channel_counts));
- iodev->supported_channel_counts[0] = 2;
- iodev->supported_channel_counts[1] = 0;
- iodev->supported_formats =
- (snd_pcm_format_t*)calloc(2, sizeof(*iodev->supported_formats));
- iodev->supported_formats[0] = SND_PCM_FORMAT_S16_LE;
- iodev->supported_formats[1] = (snd_pcm_format_t)0;
- update_supported_formats_called_++;
- return 0;
- }
- static int frames_queued(const cras_iodev* iodev, struct timespec* tstamp) {
- frames_queued_called_++;
- return 0;
- }
- static int delay_frames(const cras_iodev* iodev) {
- delay_frames_called_++;
- return 0;
- }
- static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- get_buffer_called_++;
- return 0;
- }
- static int put_buffer(cras_iodev* iodev, unsigned int num) {
- put_buffer_called_++;
- return 0;
- }
- static int configure_dev(cras_iodev* iodev) {
- configure_dev_called_++;
- return 0;
- }
- static int close_dev(cras_iodev* iodev) {
- free(iodev->format);
- iodev->format = NULL;
- close_dev_called_++;
- return 0;
- }
-
- static struct cras_iodev* bt_iodev;
- static struct cras_iodev iodev_;
- static struct cras_iodev iodev2_;
- static struct cras_ionode node_;
- static struct cras_ionode node2_;
- static unsigned int update_supported_formats_called_;
- static unsigned int frames_queued_called_;
- static unsigned int delay_frames_called_;
- static unsigned int get_buffer_called_;
- static unsigned int put_buffer_called_;
- static unsigned int configure_dev_called_;
- static unsigned int close_dev_called_;
-};
-
-struct cras_iodev* BtIoBasicSuite::bt_iodev;
-struct cras_iodev BtIoBasicSuite::iodev_;
-struct cras_iodev BtIoBasicSuite::iodev2_;
-struct cras_ionode BtIoBasicSuite::node_;
-struct cras_ionode BtIoBasicSuite::node2_;
-unsigned int BtIoBasicSuite::update_supported_formats_called_;
-unsigned int BtIoBasicSuite::frames_queued_called_;
-unsigned int BtIoBasicSuite::delay_frames_called_;
-unsigned int BtIoBasicSuite::get_buffer_called_;
-unsigned int BtIoBasicSuite::put_buffer_called_;
-unsigned int BtIoBasicSuite::configure_dev_called_;
-unsigned int BtIoBasicSuite::close_dev_called_;
-
-TEST_F(BtIoBasicSuite, CreateBtIo) {
- struct cras_audio_area* fake_area;
- struct cras_audio_format fake_fmt;
- struct timespec tstamp;
- unsigned fr;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
- EXPECT_NE((void*)NULL, bt_iodev);
- EXPECT_EQ(&iodev_, active_profile_dev(bt_iodev));
- EXPECT_EQ(1, cras_iodev_list_add_output_called);
- bt_iodev->open_dev(bt_iodev);
- bt_iodev->format = &fake_fmt;
- bt_iodev->update_supported_formats(bt_iodev);
- EXPECT_EQ(1, update_supported_formats_called_);
-
- bt_iodev->state = CRAS_IODEV_STATE_OPEN;
- bt_iodev->configure_dev(bt_iodev);
- EXPECT_EQ(1, configure_dev_called_);
- bt_iodev->frames_queued(bt_iodev, &tstamp);
- EXPECT_EQ(1, frames_queued_called_);
- bt_iodev->get_buffer(bt_iodev, &fake_area, &fr);
- EXPECT_EQ(1, get_buffer_called_);
- bt_iodev->put_buffer(bt_iodev, fr);
- EXPECT_EQ(1, put_buffer_called_);
- bt_iodev->close_dev(bt_iodev);
- EXPECT_EQ(1, close_dev_called_);
- EXPECT_EQ(1, cras_iodev_free_format_called);
- cras_bt_io_destroy(bt_iodev);
- EXPECT_EQ(1, cras_iodev_free_resources_called);
- EXPECT_EQ(1, cras_iodev_list_rm_output_called);
-
- free(iodev_.supported_rates);
- free(iodev_.supported_channel_counts);
- free(iodev_.supported_formats);
-}
-
-TEST_F(BtIoBasicSuite, SwitchProfileOnOpenDevForInputDev) {
- ResetStubData();
- iodev_.direction = CRAS_STREAM_INPUT;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- cras_bt_device_get_active_profile_ret = CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE;
- bt_iodev->open_dev(bt_iodev);
-
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY,
- cras_bt_device_set_active_profile_val);
- EXPECT_EQ(1, cras_bt_device_switch_profile_enable_dev_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, NoSwitchProfileOnOpenDevForInputDevAlreadyOnHfp) {
- ResetStubData();
- iodev_.direction = CRAS_STREAM_INPUT;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- /* No need to switch profile if already on HFP. */
- cras_bt_device_get_active_profile_ret =
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
- bt_iodev->open_dev(bt_iodev);
-
- EXPECT_EQ(0, cras_bt_device_switch_profile_enable_dev_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, SwitchProfileOnCloseInputDev) {
- ResetStubData();
- iodev_.direction = CRAS_STREAM_INPUT;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- bt_iodev->state = CRAS_IODEV_STATE_OPEN;
-
- cras_bt_device_get_active_profile_ret =
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
- cras_bt_device_has_a2dp_ret = 1;
- bt_iodev->close_dev(bt_iodev);
-
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE,
- cras_bt_device_set_active_profile_val);
- EXPECT_EQ(1, cras_bt_device_switch_profile_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, NoSwitchProfileOnCloseInputDevNoSupportA2dp) {
- ResetStubData();
- iodev_.direction = CRAS_STREAM_INPUT;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- bt_iodev->state = CRAS_IODEV_STATE_OPEN;
-
- cras_bt_device_get_active_profile_ret =
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
- cras_bt_device_has_a2dp_ret = 0;
- bt_iodev->close_dev(bt_iodev);
-
- EXPECT_EQ(0, cras_bt_device_switch_profile_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, NoSwitchProfileOnCloseInputDevInCloseState) {
- ResetStubData();
- iodev_.direction = CRAS_STREAM_INPUT;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- bt_iodev->state = CRAS_IODEV_STATE_CLOSE;
-
- cras_bt_device_get_active_profile_ret =
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
- cras_bt_device_has_a2dp_ret = 1;
- bt_iodev->close_dev(bt_iodev);
-
- EXPECT_EQ(0, cras_bt_device_switch_profile_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, SwitchProfileOnAppendA2dpDev) {
- ResetStubData();
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- cras_bt_device_can_switch_to_a2dp_ret = 1;
- cras_bt_io_append(bt_iodev, &iodev2_, CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE,
- cras_bt_device_set_active_profile_val);
- EXPECT_EQ(0, cras_bt_device_switch_profile_enable_dev_called);
- EXPECT_EQ(1, cras_bt_device_switch_profile_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, NoSwitchProfileOnAppendHfpDev) {
- ResetStubData();
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- cras_bt_device_can_switch_to_a2dp_ret = 1;
- cras_bt_io_append(bt_iodev, &iodev2_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- EXPECT_EQ(0, cras_bt_device_switch_profile_enable_dev_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, CreateSetDeviceActiveProfileToA2DP) {
- ResetStubData();
- cras_bt_device_get_active_profile_ret =
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
- cras_bt_device_can_switch_to_a2dp_ret = 1;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- EXPECT_EQ(1, cras_bt_device_set_active_profile_called);
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE,
- cras_bt_device_set_active_profile_val);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, CreateNoSetDeviceActiveProfileToA2DP) {
- ResetStubData();
- cras_bt_device_get_active_profile_ret =
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY;
- cras_bt_device_can_switch_to_a2dp_ret = 0;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- EXPECT_EQ(0, cras_bt_device_set_active_profile_called);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, CreateSetDeviceActiveProfileToHFP) {
- ResetStubData();
- cras_bt_device_get_active_profile_ret = 0;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY |
- CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY,
- cras_bt_device_set_active_profile_val);
- cras_bt_io_destroy(bt_iodev);
-}
-
-TEST_F(BtIoBasicSuite, CreateDeviceWithInvalidUTF8Name) {
- ResetStubData();
- strcpy(iodev_.info.name, "Something BT");
- iodev_.info.name[0] = 0xfe;
- is_utf8_string_ret_value = 0;
- bt_iodev = cras_bt_io_create(fake_device, &iodev_,
- CRAS_BT_DEVICE_PROFILE_A2DP_SOURCE);
-
- ASSERT_STREQ("BLUETOOTH", bt_iodev->active_node->name);
- cras_bt_io_destroy(bt_iodev);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-extern "C" {
-
-// Cras iodev
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_add_node_called++;
- DL_APPEND(iodev->nodes, node);
-}
-
-void cras_iodev_rm_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_rm_node_called++;
- DL_DELETE(iodev->nodes, node);
-}
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {
- cras_iodev_free_format_called++;
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {
- cras_iodev_set_active_node_called++;
- iodev->active_node = node;
-}
-
-int cras_iodev_set_node_attr(struct cras_ionode* ionode,
- enum ionode_attr attr,
- int value) {
- return 0;
-}
-
-void cras_iodev_free_resources(struct cras_iodev* iodev) {
- cras_iodev_free_resources_called++;
-}
-
-// From iodev list.
-int cras_iodev_list_add_output(struct cras_iodev* output) {
- cras_iodev_list_add_output_called++;
- return 0;
-}
-
-int cras_iodev_list_rm_output(struct cras_iodev* dev) {
- cras_iodev_list_rm_output_called++;
- return 0;
-}
-
-int cras_iodev_list_add_input(struct cras_iodev* output) {
- cras_iodev_list_add_input_called++;
- return 0;
-}
-
-int cras_iodev_list_rm_input(struct cras_iodev* dev) {
- cras_iodev_list_rm_input_called++;
- return 0;
-}
-
-// From bt device
-unsigned int cras_bt_device_get_active_profile(
- const struct cras_bt_device* device) {
- return cras_bt_device_get_active_profile_ret;
-}
-
-void cras_bt_device_set_active_profile(struct cras_bt_device* device,
- unsigned int profile) {
- cras_bt_device_set_active_profile_called++;
- cras_bt_device_set_active_profile_val = profile;
-}
-
-int cras_bt_device_has_a2dp(struct cras_bt_device* device) {
- return cras_bt_device_has_a2dp_ret;
-}
-
-int cras_bt_device_can_switch_to_a2dp(struct cras_bt_device* device) {
- return cras_bt_device_can_switch_to_a2dp_ret;
-}
-
-int cras_bt_device_switch_profile(struct cras_bt_device* device,
- struct cras_iodev* bt_iodev) {
- cras_bt_device_switch_profile_called++;
- return 0;
-}
-
-int cras_bt_device_switch_profile_enable_dev(struct cras_bt_device* device,
- struct cras_iodev* bt_iodev) {
- cras_bt_device_switch_profile_enable_dev_called++;
- return 0;
-}
-
-const char* cras_bt_device_object_path(const struct cras_bt_device* device) {
- return "/fake/object/path";
-}
-
-int cras_bt_device_get_stable_id(const struct cras_bt_device* device) {
- return 123;
-}
-
-int cras_bt_device_get_use_hardware_volume(struct cras_bt_device* device) {
- return 1;
-}
-
-int is_utf8_string(const char* string) {
- return is_utf8_string_ret_value;
-}
-
-int cras_iodev_default_no_stream_playback(struct cras_iodev* odev, int enable) {
- return 0;
-}
-
-int cras_iodev_frames_queued(struct cras_iodev* iodev,
- struct timespec* hw_tstamp) {
- return 0;
-}
-
-unsigned int cras_iodev_default_frames_to_play_in_sleep(
- struct cras_iodev* odev,
- unsigned int* hw_level,
- struct timespec* hw_tstamp) {
- return 0;
-}
-
-int hfp_iodev_is_hsp(struct cras_iodev* iodev) {
- return 0;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/bt_profile_unittest.cc b/cras/src/tests/bt_profile_unittest.cc
deleted file mode 100644
index 0758b448..00000000
--- a/cras/src/tests/bt_profile_unittest.cc
+++ /dev/null
@@ -1,182 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <dbus/dbus.h>
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <sys/socket.h>
-
-#include "dbus_test.h"
-
-extern "C" {
-#include "cras_bt_constants.h"
-#include "cras_bt_profile.h"
-}
-
-namespace {
-
-static struct cras_bt_profile fake_profile;
-static struct cras_bt_transport* fake_transport;
-static int profile_release_called;
-static struct cras_bt_profile* profile_release_arg_value;
-static int profile_new_connection_called;
-static struct cras_bt_transport* profile_new_connection_arg_value;
-static int profile_request_disconnection_called;
-static struct cras_bt_transport* profile_request_disconnection_arg_value;
-static int profile_cancel_called;
-static struct cras_bt_profile* profile_cancel_arg_value;
-static int cras_bt_transport_get_called;
-static const char* cras_bt_transport_get_arg_value;
-
-void fake_profile_release(struct cras_bt_profile* profile);
-void fake_profile_new_connection(struct cras_bt_profile* profile,
- struct cras_bt_transport* transport);
-void fake_profile_request_disconnection(struct cras_bt_profile* profile,
- struct cras_bt_transport* transport);
-void fake_profile_cancel(struct cras_bt_profile* profile);
-
-class BtProfileTestSuite : public DBusTest {
- virtual void SetUp() {
- DBusTest::SetUp();
-
- profile_release_called = 0;
- profile_new_connection_called = 0;
- profile_request_disconnection_called = 0;
- profile_cancel_called = 0;
-
- fake_profile.name = "fake";
- fake_profile.object_path = "/fake";
- fake_profile.uuid = "0";
- fake_profile.version = 0;
- fake_profile.role = NULL;
- fake_profile.features = 0;
- fake_profile.release = fake_profile_release;
- fake_profile.new_connection = fake_profile_new_connection;
- fake_profile.request_disconnection = fake_profile_request_disconnection;
- fake_profile.cancel = fake_profile_cancel;
-
- fake_transport = reinterpret_cast<struct cras_bt_transport*>(0x321);
- cras_bt_transport_get_called = 0;
- }
-};
-
-TEST_F(BtProfileTestSuite, RegisterProfile) {
- struct cras_bt_profile* profile;
-
- ExpectMethodCall(PROFILE_MANAGER_OBJ_PATH, BLUEZ_PROFILE_MGMT_INTERFACE,
- "RegisterProfile")
- .WithObjectPath("/fake")
- .SendReply();
-
- cras_bt_add_profile(conn_, &fake_profile);
- cras_bt_register_profiles(conn_);
-
- WaitForMatches();
- profile = cras_bt_profile_get("/fake");
-
- EXPECT_TRUE(profile == &fake_profile);
-}
-
-TEST_F(BtProfileTestSuite, ResetProfile) {
- cras_bt_add_profile(conn_, &fake_profile);
- cras_bt_profile_reset();
-
- ASSERT_EQ(1, profile_release_called);
-}
-
-TEST_F(BtProfileTestSuite, HandleMessage) {
- ExpectMethodCall(PROFILE_MANAGER_OBJ_PATH, BLUEZ_PROFILE_MGMT_INTERFACE,
- "RegisterProfile")
- .WithObjectPath("/fake")
- .SendReply();
-
- cras_bt_add_profile(conn_, &fake_profile);
- cras_bt_register_profiles(conn_);
-
- WaitForMatches();
-
- /* Use stdin as mock fd */
- CreateMessageCall("/fake", "org.bluez.Profile1", "NewConnection")
- .WithString("device")
- .WithUnixFd(0)
- .Send();
-
- WaitForMatches();
- ASSERT_EQ(1, profile_new_connection_called);
- ASSERT_STREQ("device", cras_bt_transport_get_arg_value);
- ASSERT_EQ(1, cras_bt_transport_get_called);
- ASSERT_EQ(fake_transport, profile_new_connection_arg_value);
-
- CreateMessageCall("/fake", "org.bluez.Profile1", "RequestDisconnection")
- .WithString("device")
- .Send();
- WaitForMatches();
- ASSERT_EQ(2, cras_bt_transport_get_called);
- ASSERT_EQ(1, profile_request_disconnection_called);
- ASSERT_EQ(fake_transport, profile_request_disconnection_arg_value);
-
- CreateMessageCall("/fake", "org.bluez.Profile1", "Release").Send();
- WaitForMatches();
- ASSERT_EQ(1, profile_release_called);
- ASSERT_EQ(&fake_profile, profile_release_arg_value);
-
- CreateMessageCall("/fake", "org.bluez.Profile1", "Cancel").Send();
- WaitForMatches();
- ASSERT_EQ(1, profile_cancel_called);
- ASSERT_EQ(&fake_profile, profile_cancel_arg_value);
-}
-
-void fake_profile_release(struct cras_bt_profile* profile) {
- profile_release_arg_value = profile;
- profile_release_called++;
-}
-
-void fake_profile_new_connection(struct cras_bt_profile* profile,
- struct cras_bt_transport* transport) {
- profile_new_connection_arg_value = transport;
- profile_new_connection_called++;
-}
-
-void fake_profile_request_disconnection(struct cras_bt_profile* profile,
- struct cras_bt_transport* transport) {
- profile_request_disconnection_arg_value = transport;
- profile_request_disconnection_called++;
-}
-
-void fake_profile_cancel(struct cras_bt_profile* profile) {
- profile_cancel_arg_value = profile;
- profile_cancel_called++;
-}
-
-} // namespace
-
-extern "C" {
-dbus_bool_t append_key_value(DBusMessageIter* iter,
- const char* key,
- int type,
- const char* type_string,
- void* value) {
- return TRUE;
-}
-
-struct cras_bt_transport* cras_bt_transport_get(const char* object_path) {
- cras_bt_transport_get_called++;
- cras_bt_transport_get_arg_value = object_path;
- return fake_transport;
-}
-
-void cras_bt_transport_destroy(struct cras_bt_transport* transport) {}
-
-struct cras_bt_transport* cras_bt_transport_create(DBusConnection* conn,
- const char* object_path) {
- return fake_transport;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/buffer_share_unittest.cc b/cras/src/tests/buffer_share_unittest.cc
deleted file mode 100644
index f16456bf..00000000
--- a/cras/src/tests/buffer_share_unittest.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "buffer_share.h"
-#include "cras_types.h"
-}
-
-namespace {
-
-class BufferShareTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {}
-
- virtual void TearDown() {}
-};
-
-TEST_F(BufferShareTestSuite, Create) {
- buffer_share* dm = buffer_share_create(1024);
- EXPECT_NE(static_cast<buffer_share*>(NULL), dm);
- buffer_share_destroy(dm);
-}
-
-TEST_F(BufferShareTestSuite, AddRmDev) {
- buffer_share* dm = buffer_share_create(1024);
- int rc;
-
- rc = buffer_share_add_id(dm, 0xf00, NULL);
- EXPECT_EQ(0, rc);
- rc = buffer_share_add_id(dm, 0xf00, NULL);
- EXPECT_NE(0, rc);
-
- rc = buffer_share_rm_id(dm, 0xf00);
- EXPECT_EQ(0, rc);
- rc = buffer_share_rm_id(dm, 0xf00);
- EXPECT_NE(0, rc);
-
- buffer_share_destroy(dm);
-}
-
-TEST_F(BufferShareTestSuite, AddManyDevs) {
- buffer_share* dm = buffer_share_create(1024);
-
- for (unsigned int i = 0; i < INITIAL_ID_SIZE; i++)
- EXPECT_EQ(0, buffer_share_add_id(dm, 0xf00 + i, NULL));
-
- EXPECT_EQ(0, buffer_share_add_id(dm, 0xf00 + INITIAL_ID_SIZE, NULL));
- EXPECT_EQ(0, buffer_share_rm_id(dm, 0xf00 + INITIAL_ID_SIZE));
-
- for (unsigned int i = 0; i < INITIAL_ID_SIZE; i++)
- EXPECT_EQ(0, buffer_share_rm_id(dm, 0xf00 + i));
-
- buffer_share_destroy(dm);
-}
-
-TEST_F(BufferShareTestSuite, OneDev) {
- buffer_share* dm = buffer_share_create(1024);
- int rc;
-
- rc = buffer_share_add_id(dm, 0xf00, NULL);
- EXPECT_EQ(0, rc);
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(500, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(500, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(500, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(500, buffer_share_get_new_write_point(dm));
-
- buffer_share_destroy(dm);
-}
-
-TEST_F(BufferShareTestSuite, TwoDevs) {
- buffer_share* dm = buffer_share_create(1024);
- int rc;
-
- rc = buffer_share_add_id(dm, 0xf00, NULL);
- EXPECT_EQ(0, rc);
- rc = buffer_share_add_id(dm, 0xf02, NULL);
- EXPECT_EQ(0, rc);
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(0, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf02, 750);
- EXPECT_EQ(500, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(250, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf02, 750);
- EXPECT_EQ(250, buffer_share_get_new_write_point(dm));
-
- buffer_share_offset_update(dm, 0xf00, 500);
- EXPECT_EQ(500, buffer_share_get_new_write_point(dm));
-
- buffer_share_destroy(dm);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/byte_buffer_unittest.cc b/cras/src/tests/byte_buffer_unittest.cc
deleted file mode 100644
index 7b28b0fd..00000000
--- a/cras/src/tests/byte_buffer_unittest.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2015 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "byte_buffer.h"
-
-#include <gtest/gtest.h>
-
-namespace {
-
-TEST(ByteBuffer, ReadWrite) {
- struct byte_buffer* b;
- uint8_t* data;
- unsigned int data_size;
-
- b = byte_buffer_create(100);
- EXPECT_EQ(100, buf_available(b));
- EXPECT_EQ(0, buf_queued(b));
-
- data = buf_read_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(0, data_size);
-
- data = buf_write_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(100, data_size);
-
- buf_increment_write(b, 50);
- data = buf_read_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(50, data_size);
-
- buf_increment_read(b, 40);
- EXPECT_EQ(10, buf_queued(b));
- EXPECT_EQ(90, buf_available(b));
-
- /* Test write to the end of ring buffer. */
- data = buf_write_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(50, data_size);
-
- buf_increment_write(b, 50);
- data = buf_write_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(40, data_size);
-
- byte_buffer_destroy(&b);
-}
-
-TEST(ByteBuffer, SetUsedSizeReadWrite) {
- struct byte_buffer* b;
- uint8_t* data;
- unsigned int data_size;
-
- b = byte_buffer_create(100);
- EXPECT_EQ(100, buf_available(b));
- EXPECT_EQ(0, buf_queued(b));
-
- /* Test set used_size to limit the initial allocated max size. */
- byte_buffer_set_used_size(b, 90);
- EXPECT_EQ(90, buf_available(b));
-
- data = buf_write_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(90, data_size);
-
- buf_increment_write(b, 90);
- data = buf_read_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(90, data_size);
-
- buf_increment_read(b, 50);
- EXPECT_EQ(50, buf_available(b));
- EXPECT_EQ(40, buf_queued(b));
-
- data = buf_write_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(50, data_size);
-
- buf_increment_write(b, 50);
- data = buf_write_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(0, data_size);
-
- /* Test read to the end of ring buffer. */
- data = buf_read_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(40, data_size);
-
- buf_increment_read(b, 40);
- data = buf_read_pointer_size(b, &data_size);
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(50, data_size);
-
- byte_buffer_destroy(&b);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-} \ No newline at end of file
diff --git a/cras/src/tests/capture_rclient_unittest.cc b/cras/src/tests/capture_rclient_unittest.cc
deleted file mode 100644
index 446fddfa..00000000
--- a/cras/src/tests/capture_rclient_unittest.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <unistd.h>
-
-extern "C" {
-#include "audio_thread.h"
-#include "cras_bt_log.h"
-#include "cras_messages.h"
-#include "cras_rclient.h"
-#include "cras_rstream.h"
-#include "cras_system_state.h"
-
-// Access to data structures and static functions.
-#include "cras_capture_rclient.c"
-#include "cras_rclient_util.c"
-}
-static unsigned int cras_make_fd_nonblocking_called;
-static unsigned int cras_observer_remove_called;
-static int stream_list_add_called;
-static int stream_list_add_return;
-static unsigned int stream_list_rm_called;
-static struct cras_audio_shm mock_shm;
-static struct cras_rstream mock_rstream;
-
-void ResetStubData() {
- cras_make_fd_nonblocking_called = 0;
- cras_observer_remove_called = 0;
- stream_list_add_called = 0;
- stream_list_add_return = 0;
- stream_list_rm_called = 0;
-}
-
-namespace {
-
-TEST(RClientSuite, CreateSendMessage) {
- struct cras_rclient* rclient;
- int rc;
- struct cras_client_connected msg;
- int pipe_fds[2];
-
- ResetStubData();
-
- rc = pipe(pipe_fds);
- ASSERT_EQ(0, rc);
-
- rclient = cras_capture_rclient_create(pipe_fds[1], 800);
- ASSERT_NE((void*)NULL, rclient);
- EXPECT_EQ(800, rclient->id);
-
- rc = read(pipe_fds[0], &msg, sizeof(msg));
- EXPECT_EQ(sizeof(msg), rc);
- EXPECT_EQ(CRAS_CLIENT_CONNECTED, msg.header.id);
-
- rclient->ops->destroy(rclient);
- EXPECT_EQ(1, cras_observer_remove_called);
- close(pipe_fds[0]);
- close(pipe_fds[1]);
-}
-
-class CCRMessageSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- int rc;
- struct cras_client_connected msg;
-
- rc = pipe(pipe_fds_);
- if (rc < 0)
- return;
-
- rclient_ = cras_capture_rclient_create(pipe_fds_[1], 1);
- rc = read(pipe_fds_[0], &msg, sizeof(msg));
- if (rc < 0)
- return;
-
- fmt = {
- .format = SND_PCM_FORMAT_S16_LE,
- .frame_rate = 48000,
- .num_channels = 2,
- };
- cras_audio_format_set_default_channel_layout(&fmt);
- ResetStubData();
- }
-
- virtual void TearDown() {
- rclient_->ops->destroy(rclient_);
- close(pipe_fds_[0]);
- close(pipe_fds_[1]);
- }
-
- struct cras_rclient* rclient_;
- struct cras_audio_format fmt;
- int pipe_fds_[2];
- int fd_;
-};
-
-TEST_F(CCRMessageSuite, StreamConnectMessage) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x10002;
- cras_fill_connect_message(&msg, CRAS_STREAM_INPUT, stream_id,
- CRAS_STREAM_TYPE_DEFAULT, CRAS_CLIENT_TYPE_UNKNOWN,
- 480, 240, /*flags=*/0, /*effects=*/0, fmt,
- NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- fd_ = 100;
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_, 1);
- EXPECT_EQ(1, cras_make_fd_nonblocking_called);
- EXPECT_EQ(1, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id, out_msg.stream_id);
-}
-
-TEST_F(CCRMessageSuite, StreamConnectMessageInvalidDirection) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x10002;
-
- for (int i = 0; i < CRAS_NUM_DIRECTIONS; i++) {
- const auto dir = static_cast<CRAS_STREAM_DIRECTION>(i);
- if (dir == CRAS_STREAM_INPUT)
- continue;
- cras_fill_connect_message(&msg, dir, stream_id, CRAS_STREAM_TYPE_DEFAULT,
- CRAS_CLIENT_TYPE_UNKNOWN, 480, 240, /*flags=*/0,
- /*effects=*/0, fmt, NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_,
- 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(stream_id, out_msg.stream_id);
- }
-}
-
-TEST_F(CCRMessageSuite, StreamConnectMessageInvalidClientId) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x20002; // stream_id with invalid client_id
- cras_fill_connect_message(&msg, CRAS_STREAM_INPUT, stream_id,
- CRAS_STREAM_TYPE_DEFAULT, CRAS_CLIENT_TYPE_UNKNOWN,
- 480, 240, /*flags=*/0, /*effects=*/0, fmt,
- NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- fd_ = 100;
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(stream_id, out_msg.stream_id);
-}
-
-TEST_F(CCRMessageSuite, StreamDisconnectMessage) {
- struct cras_disconnect_stream_message msg;
- cras_stream_id_t stream_id = 0x10002;
- cras_fill_disconnect_stream_message(&msg, stream_id);
-
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(1, stream_list_rm_called);
-}
-
-TEST_F(CCRMessageSuite, StreamDisconnectMessageInvalidClientId) {
- struct cras_disconnect_stream_message msg;
- cras_stream_id_t stream_id = 0x20002; // stream_id with invalid client_id
- cras_fill_disconnect_stream_message(&msg, stream_id);
-
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-}
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-/* stubs */
-extern "C" {
-
-struct stream_list* cras_iodev_list_get_stream_list() {
- return NULL;
-}
-
-int cras_make_fd_nonblocking(int fd) {
- cras_make_fd_nonblocking_called++;
- return 0;
-}
-
-void cras_observer_remove(struct cras_observer_client* client) {
- cras_observer_remove_called++;
-}
-
-unsigned int cras_rstream_get_effects(const struct cras_rstream* stream) {
- return 0;
-}
-
-int cras_send_with_fds(int sockfd,
- const void* buf,
- size_t len,
- int* fd,
- unsigned int num_fds) {
- return write(sockfd, buf, len);
-}
-
-key_t cras_sys_state_shm_fd() {
- return 1;
-}
-
-void cras_system_set_suspended(int suspended) {}
-
-int stream_list_rm_all_client_streams(struct stream_list* list,
- struct cras_rclient* rclient) {
- return 0;
-}
-
-int stream_list_rm(struct stream_list* list, cras_stream_id_t id) {
- stream_list_rm_called++;
- return 0;
-}
-
-int stream_list_add(struct stream_list* list,
- struct cras_rstream_config* config,
- struct cras_rstream** stream) {
- int ret;
-
- *stream = &mock_rstream;
-
- stream_list_add_called++;
- ret = stream_list_add_return;
- if (ret)
- stream_list_add_return = -EINVAL;
-
- mock_rstream.shm = &mock_shm;
- mock_rstream.direction = config->direction;
- mock_rstream.stream_id = config->stream_id;
-
- return ret;
-}
-
-bool cras_audio_format_valid(const struct cras_audio_format* fmt) {
- return true;
-}
-
-void detect_rtc_stream_pair(struct stream_list* list,
- struct cras_rstream* stream) {
- return;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/card_config_unittest.cc b/cras/src/tests/card_config_unittest.cc
deleted file mode 100644
index 4616515b..00000000
--- a/cras/src/tests/card_config_unittest.cc
+++ /dev/null
@@ -1,283 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_card_config.h"
-#include "cras_types.h"
-}
-
-namespace {
-
-static unsigned int cras_volume_curve_create_default_called;
-static struct cras_volume_curve* cras_volume_curve_create_default_return;
-static unsigned int cras_volume_curve_create_simple_step_called;
-static long cras_volume_curve_create_simple_step_max_volume;
-static long cras_volume_curve_create_simple_step_volume_step;
-static struct cras_volume_curve* cras_volume_curve_create_simple_step_return;
-static unsigned int cras_volume_curve_create_explicit_called;
-static long cras_explicit_curve[101];
-static struct cras_volume_curve* cras_volume_curve_create_explicit_return;
-
-static const char CONFIG_PATH[] = CRAS_UT_TMPDIR;
-
-void CreateConfigFile(const char* name, const char* config_text) {
- FILE* f;
- char card_path[128];
-
- snprintf(card_path, sizeof(card_path), "%s/%s", CONFIG_PATH, name);
- f = fopen(card_path, "w");
- if (f == NULL)
- return;
-
- fprintf(f, "%s", config_text);
-
- fclose(f);
-}
-
-class CardConfigTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- cras_volume_curve_create_default_called = 0;
- cras_volume_curve_create_default_return =
- reinterpret_cast<struct cras_volume_curve*>(0x55);
- cras_volume_curve_create_simple_step_return =
- reinterpret_cast<struct cras_volume_curve*>(0x56);
- cras_volume_curve_create_explicit_return =
- reinterpret_cast<struct cras_volume_curve*>(0x57);
- cras_volume_curve_create_simple_step_called = 0;
- cras_volume_curve_create_simple_step_return = NULL;
- cras_volume_curve_create_explicit_called = 0;
- cras_volume_curve_create_explicit_return = NULL;
- }
-};
-
-// Test that no config is returned if the file doesn't exist.
-TEST_F(CardConfigTestSuite, NoConfigFound) {
- struct cras_card_config* config;
-
- config = cras_card_config_create(CONFIG_PATH, "no_effing_way_this_exists");
- EXPECT_EQ(NULL, config);
-}
-
-// Test an empty config file, should return a null volume curve.
-TEST_F(CardConfigTestSuite, EmptyConfigFileReturnsNullVolumeCurve) {
- static const char empty_config_text[] = "";
- static const char empty_config_name[] = "EmptyConfigCard";
- struct cras_card_config* config;
- struct cras_volume_curve* curve;
-
- CreateConfigFile(empty_config_name, empty_config_text);
-
- config = cras_card_config_create(CONFIG_PATH, empty_config_name);
- EXPECT_NE(static_cast<struct cras_card_config*>(NULL), config);
-
- curve = cras_card_config_get_volume_curve_for_control(config, "asdf");
- EXPECT_EQ(0, cras_volume_curve_create_default_called);
- EXPECT_EQ(static_cast<struct cras_volume_curve*>(NULL), curve);
-
- cras_card_config_destroy(config);
-}
-
-// Getting a curve from a null config should always return null volume curve.
-TEST_F(CardConfigTestSuite, NullConfigGivesDefaultVolumeCurve) {
- struct cras_volume_curve* curve;
-
- curve = cras_card_config_get_volume_curve_for_control(NULL, "asdf");
- EXPECT_EQ(0, cras_volume_curve_create_default_called);
- EXPECT_EQ(static_cast<struct cras_volume_curve*>(NULL), curve);
-}
-
-// Test getting a curve from a simple_step configuration.
-TEST_F(CardConfigTestSuite, SimpleStepConfig) {
- static const char simple_config_name[] = "simple";
- static const char simple_config_text[] =
- "[Card1]\n"
- "volume_curve = simple_step\n"
- "volume_step = 75\n"
- "max_volume = -600\n";
- struct cras_card_config* config;
- struct cras_volume_curve* curve;
-
- CreateConfigFile(simple_config_name, simple_config_text);
-
- config = cras_card_config_create(CONFIG_PATH, simple_config_name);
- EXPECT_NE(static_cast<struct cras_card_config*>(NULL), config);
-
- // Unknown config should return default curve.
- curve = cras_card_config_get_volume_curve_for_control(NULL, "asdf");
- EXPECT_EQ(0, cras_volume_curve_create_default_called);
- EXPECT_EQ(static_cast<struct cras_volume_curve*>(NULL), curve);
-
- // Test a config that specifies simple_step.
- curve = cras_card_config_get_volume_curve_for_control(config, "Card1");
- EXPECT_EQ(cras_volume_curve_create_simple_step_return, curve);
- EXPECT_EQ(0, cras_volume_curve_create_default_called);
- EXPECT_EQ(1, cras_volume_curve_create_simple_step_called);
- EXPECT_EQ(-600, cras_volume_curve_create_simple_step_max_volume);
- EXPECT_EQ(75, cras_volume_curve_create_simple_step_volume_step);
-
- cras_card_config_destroy(config);
-}
-
-// Test getting a curve from an explicit configuration.
-TEST_F(CardConfigTestSuite, ExplicitCurveConfig) {
- static const char explicit_config_name[] = "explicit";
- static const char explicit_config_text[] =
- "[Card1]\n"
- "volume_curve = explicit\n"
- "dB_at_0 = -9950\n"
- "dB_at_1 = -9850\n"
- "dB_at_2 = -9750\n"
- "dB_at_3 = -9650\n"
- "dB_at_4 = -9550\n"
- "dB_at_5 = -9450\n"
- "dB_at_6 = -9350\n"
- "dB_at_7 = -9250\n"
- "dB_at_8 = -9150\n"
- "dB_at_9 = -9050\n"
- "dB_at_10 = -8950\n"
- "dB_at_11 = -8850\n"
- "dB_at_12 = -8750\n"
- "dB_at_13 = -8650\n"
- "dB_at_14 = -8550\n"
- "dB_at_15 = -8450\n"
- "dB_at_16 = -8350\n"
- "dB_at_17 = -8250\n"
- "dB_at_18 = -8150\n"
- "dB_at_19 = -8050\n"
- "dB_at_20 = -7950\n"
- "dB_at_21 = -7850\n"
- "dB_at_22 = -7750\n"
- "dB_at_23 = -7650\n"
- "dB_at_24 = -7550\n"
- "dB_at_25 = -7450\n"
- "dB_at_26 = -7350\n"
- "dB_at_27 = -7250\n"
- "dB_at_28 = -7150\n"
- "dB_at_29 = -7050\n"
- "dB_at_30 = -6950\n"
- "dB_at_31 = -6850\n"
- "dB_at_32 = -6750\n"
- "dB_at_33 = -6650\n"
- "dB_at_34 = -6550\n"
- "dB_at_35 = -6450\n"
- "dB_at_36 = -6350\n"
- "dB_at_37 = -6250\n"
- "dB_at_38 = -6150\n"
- "dB_at_39 = -6050\n"
- "dB_at_40 = -5950\n"
- "dB_at_41 = -5850\n"
- "dB_at_42 = -5750\n"
- "dB_at_43 = -5650\n"
- "dB_at_44 = -5550\n"
- "dB_at_45 = -5450\n"
- "dB_at_46 = -5350\n"
- "dB_at_47 = -5250\n"
- "dB_at_48 = -5150\n"
- "dB_at_49 = -5050\n"
- "dB_at_50 = -4950\n"
- "dB_at_51 = -4850\n"
- "dB_at_52 = -4750\n"
- "dB_at_53 = -4650\n"
- "dB_at_54 = -4550\n"
- "dB_at_55 = -4450\n"
- "dB_at_56 = -4350\n"
- "dB_at_57 = -4250\n"
- "dB_at_58 = -4150\n"
- "dB_at_59 = -4050\n"
- "dB_at_60 = -3950\n"
- "dB_at_61 = -3850\n"
- "dB_at_62 = -3750\n"
- "dB_at_63 = -3650\n"
- "dB_at_64 = -3550\n"
- "dB_at_65 = -3450\n"
- "dB_at_66 = -3350\n"
- "dB_at_67 = -3250\n"
- "dB_at_68 = -3150\n"
- "dB_at_69 = -3050\n"
- "dB_at_70 = -2950\n"
- "dB_at_71 = -2850\n"
- "dB_at_72 = -2750\n"
- "dB_at_73 = -2650\n"
- "dB_at_74 = -2550\n"
- "dB_at_75 = -2450\n"
- "dB_at_76 = -2350\n"
- "dB_at_77 = -2250\n"
- "dB_at_78 = -2150\n"
- "dB_at_79 = -2050\n"
- "dB_at_80 = -1950\n"
- "dB_at_81 = -1850\n"
- "dB_at_82 = -1750\n"
- "dB_at_83 = -1650\n"
- "dB_at_84 = -1550\n"
- "dB_at_85 = -1450\n"
- "dB_at_86 = -1350\n"
- "dB_at_87 = -1250\n"
- "dB_at_88 = -1150\n"
- "dB_at_89 = -1050\n"
- "dB_at_90 = -950\n"
- "dB_at_91 = -850\n"
- "dB_at_92 = -750\n"
- "dB_at_93 = -650\n"
- "dB_at_94 = -550\n"
- "dB_at_95 = -450\n"
- "dB_at_96 = -350\n"
- "dB_at_97 = -250\n"
- "dB_at_98 = -150\n"
- "dB_at_99 = -50\n"
- "dB_at_100 = 50\n";
- struct cras_card_config* config;
- struct cras_volume_curve* curve;
-
- CreateConfigFile(explicit_config_name, explicit_config_text);
-
- config = cras_card_config_create(CONFIG_PATH, explicit_config_name);
- EXPECT_NE(static_cast<struct cras_card_config*>(NULL), config);
-
- // Test a explicit curve config.
- curve = cras_card_config_get_volume_curve_for_control(config, "Card1");
- EXPECT_EQ(0, cras_volume_curve_create_default_called);
- EXPECT_EQ(0, cras_volume_curve_create_simple_step_called);
- EXPECT_EQ(1, cras_volume_curve_create_explicit_called);
- EXPECT_EQ(cras_volume_curve_create_explicit_return, curve);
- for (unsigned int i = 0; i < 101; i++) {
- EXPECT_EQ((static_cast<long>(i) - 100) * 100 + 50, cras_explicit_curve[i]);
- }
-
- cras_card_config_destroy(config);
-}
-
-// Stubs.
-extern "C" {
-
-struct cras_volume_curve* cras_volume_curve_create_default() {
- cras_volume_curve_create_default_called++;
- return cras_volume_curve_create_default_return;
-}
-
-struct cras_volume_curve* cras_volume_curve_create_simple_step(
- long max_volume,
- long volume_step) {
- cras_volume_curve_create_simple_step_called++;
- cras_volume_curve_create_simple_step_max_volume = max_volume;
- cras_volume_curve_create_simple_step_volume_step = volume_step;
- return cras_volume_curve_create_simple_step_return;
-}
-
-struct cras_volume_curve* cras_volume_curve_create_explicit(long dB_vals[101]) {
- cras_volume_curve_create_explicit_called++;
- memcpy(cras_explicit_curve, dB_vals, sizeof(cras_explicit_curve));
- return cras_volume_curve_create_explicit_return;
-}
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/checksum_unittest.cc b/cras/src/tests/checksum_unittest.cc
deleted file mode 100644
index 4d54b2c2..00000000
--- a/cras/src/tests/checksum_unittest.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-#include "cras_checksum.h"
-#include "cras_util.h"
-
-namespace {
-
-struct TestCase {
- const char* input;
- uint32_t output;
-};
-
-static TestCase test_case[] = {
- /* The answers can be obtained by a command like "echo -n a | cksum" */
- {"", 4294967295U},
- {"a", 1220704766U},
- {"12345678901234567890", 970143720U},
-};
-
-TEST(ChecksumTest, All) {
- for (size_t i = 0; i < ARRAY_SIZE(test_case); i++) {
- const char* input = test_case[i].input;
- uint32_t output = test_case[i].output;
- EXPECT_EQ(output, crc32_checksum((unsigned char*)input, strlen(input)));
- }
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/control_rclient_unittest.cc b/cras/src/tests/control_rclient_unittest.cc
deleted file mode 100644
index 63e3c8f0..00000000
--- a/cras/src/tests/control_rclient_unittest.cc
+++ /dev/null
@@ -1,977 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <unistd.h>
-
-extern "C" {
-#include "audio_thread.h"
-#include "cras_bt_log.h"
-#include "cras_main_thread_log.h"
-#include "cras_messages.h"
-#include "cras_rclient.h"
-#include "cras_rstream.h"
-#include "cras_system_state.h"
-
-// Access to data structures and static functions.
-#include "cras_control_rclient.c"
-#include "cras_rclient_util.c"
-}
-
-// Stub data.
-static int audio_thread_config_global_remix_called;
-static float audio_thread_config_global_remix_copy[CRAS_MAX_REMIX_CHANNELS *
- CRAS_MAX_REMIX_CHANNELS];
-static int cras_rstream_create_return;
-static struct cras_rstream* cras_rstream_create_stream_out;
-static int cras_iodev_attach_stream_retval;
-static size_t cras_system_set_volume_value;
-static int cras_system_set_volume_called;
-static size_t cras_system_set_mute_value;
-static int cras_system_set_mute_called;
-static size_t cras_system_set_user_mute_value;
-static int cras_system_set_user_mute_called;
-static size_t cras_system_set_mute_locked_value;
-static int cras_system_set_mute_locked_called;
-static size_t cras_system_set_capture_mute_value;
-static int cras_system_set_capture_mute_called;
-static size_t cras_system_set_capture_mute_locked_value;
-static int cras_system_set_capture_mute_locked_called;
-static int cras_system_state_dump_snapshots_called;
-static size_t cras_make_fd_nonblocking_called;
-static audio_thread* iodev_get_thread_return;
-static int stream_list_add_stream_return;
-static unsigned int stream_list_add_stream_called;
-static unsigned int stream_list_disconnect_stream_called;
-static unsigned int cras_iodev_list_rm_input_called;
-static unsigned int cras_iodev_list_rm_output_called;
-static struct cras_audio_shm mock_shm;
-static struct cras_rstream mock_rstream;
-static size_t cras_observer_num_ops_registered;
-static size_t cras_observer_register_notify_called;
-static size_t cras_observer_add_called;
-static void* cras_observer_add_context_value;
-static struct cras_observer_client* cras_observer_add_return_value;
-static size_t cras_observer_get_ops_called;
-static struct cras_observer_ops cras_observer_ops_value;
-static size_t cras_observer_set_ops_called;
-static size_t cras_observer_ops_are_empty_called;
-static struct cras_observer_ops cras_observer_ops_are_empty_empty_ops;
-static size_t cras_observer_remove_called;
-
-void ResetStubData() {
- audio_thread_config_global_remix_called = 0;
- memset(audio_thread_config_global_remix_copy, 0,
- sizeof(audio_thread_config_global_remix_copy));
- cras_rstream_create_return = 0;
- cras_rstream_create_stream_out = (struct cras_rstream*)NULL;
- cras_iodev_attach_stream_retval = 0;
- cras_system_set_volume_value = 0;
- cras_system_set_volume_called = 0;
- cras_system_set_mute_value = 0;
- cras_system_set_mute_called = 0;
- cras_system_set_user_mute_value = 0;
- cras_system_set_user_mute_called = 0;
- cras_system_set_mute_locked_value = 0;
- cras_system_set_mute_locked_called = 0;
- cras_system_set_capture_mute_value = 0;
- cras_system_set_capture_mute_called = 0;
- cras_system_set_capture_mute_locked_value = 0;
- cras_system_set_capture_mute_locked_called = 0;
- cras_system_state_dump_snapshots_called = 0;
- cras_make_fd_nonblocking_called = 0;
- iodev_get_thread_return = reinterpret_cast<audio_thread*>(0xad);
- stream_list_add_stream_return = 0;
- stream_list_add_stream_called = 0;
- stream_list_disconnect_stream_called = 0;
- cras_iodev_list_rm_output_called = 0;
- cras_iodev_list_rm_input_called = 0;
- cras_observer_num_ops_registered = 0;
- cras_observer_register_notify_called = 0;
- cras_observer_add_called = 0;
- cras_observer_add_return_value =
- reinterpret_cast<struct cras_observer_client*>(1);
- cras_observer_add_context_value = NULL;
- cras_observer_get_ops_called = 0;
- memset(&cras_observer_ops_value, 0, sizeof(cras_observer_ops_value));
- cras_observer_set_ops_called = 0;
- cras_observer_ops_are_empty_called = 0;
- memset(&cras_observer_ops_are_empty_empty_ops, 0,
- sizeof(cras_observer_ops_are_empty_empty_ops));
- cras_observer_remove_called = 0;
-}
-
-namespace {
-
-TEST(RClientSuite, CreateSendMessage) {
- struct cras_rclient* rclient;
- int rc;
- struct cras_client_connected msg;
- int pipe_fds[2];
-
- ResetStubData();
-
- rc = pipe(pipe_fds);
- ASSERT_EQ(0, rc);
-
- rclient = cras_control_rclient_create(pipe_fds[1], 800);
- ASSERT_NE((void*)NULL, rclient);
-
- rc = read(pipe_fds[0], &msg, sizeof(msg));
- EXPECT_EQ(sizeof(msg), rc);
- EXPECT_EQ(CRAS_CLIENT_CONNECTED, msg.header.id);
-
- rclient->ops->destroy(rclient);
- close(pipe_fds[0]);
- close(pipe_fds[1]);
-}
-
-class RClientMessagesSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- int rc;
- struct cras_client_connected msg;
-
- rc = pipe(pipe_fds_);
- if (rc < 0)
- return;
- rclient_ = cras_control_rclient_create(pipe_fds_[1], 1);
- rc = read(pipe_fds_[0], &msg, sizeof(msg));
- if (rc < 0)
- return;
-
- rstream_ = (struct cras_rstream*)calloc(1, sizeof(*rstream_));
-
- stream_id_ = 0x10002;
- connect_msg_.header.id = CRAS_SERVER_CONNECT_STREAM;
- connect_msg_.header.length = sizeof(connect_msg_);
- connect_msg_.proto_version = CRAS_PROTO_VER;
- connect_msg_.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- connect_msg_.direction = CRAS_STREAM_OUTPUT;
- connect_msg_.stream_id = stream_id_;
- connect_msg_.buffer_frames = 480;
- connect_msg_.cb_threshold = 240;
- connect_msg_.flags = 0;
- connect_msg_.format.num_channels = 2;
- connect_msg_.format.frame_rate = 48000;
- connect_msg_.format.format = SND_PCM_FORMAT_S16_LE;
- connect_msg_.dev_idx = NO_DEVICE;
- connect_msg_.client_shm_size = 0;
- btlog = cras_bt_event_log_init();
- main_log = main_thread_event_log_init();
- ResetStubData();
- }
-
- virtual void TearDown() {
- rclient_->ops->destroy(rclient_);
- free(rstream_);
- close(pipe_fds_[0]);
- close(pipe_fds_[1]);
- cras_bt_event_log_deinit(btlog);
- main_thread_event_log_deinit(main_log);
- }
-
- void RegisterNotification(enum CRAS_CLIENT_MESSAGE_ID msg_id,
- void* callback,
- void** ops_address);
-
- struct cras_connect_message connect_msg_;
- struct cras_rclient* rclient_;
- struct cras_rstream* rstream_;
- size_t stream_id_;
- int pipe_fds_[2];
- int fd_;
-};
-
-TEST_F(RClientMessagesSuite, AudThreadAttachFail) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- cras_rstream_create_stream_out = rstream_;
- stream_list_add_stream_return = -EINVAL;
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &connect_msg_.header,
- &fd_, 1);
- EXPECT_EQ(0, rc);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id_, out_msg.stream_id);
- EXPECT_NE(0, out_msg.err);
- EXPECT_EQ(0, cras_iodev_list_rm_output_called);
- EXPECT_EQ(1, stream_list_add_stream_called);
- EXPECT_EQ(0, stream_list_disconnect_stream_called);
-}
-
-TEST_F(RClientMessagesSuite, ConnectMsgWithBadFd) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- rc = rclient_->ops->handle_message_from_client(rclient_, &connect_msg_.header,
- NULL, 0);
- EXPECT_EQ(0, rc);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id_, out_msg.stream_id);
- EXPECT_NE(0, out_msg.err);
- EXPECT_EQ(stream_list_add_stream_called,
- stream_list_disconnect_stream_called);
-}
-
-TEST_F(RClientMessagesSuite, StreamConnectMessageValidDirection) {
- struct cras_client_stream_connected out_msg;
- int rc;
- int called = 0;
-
- for (int i = 0; i < CRAS_NUM_DIRECTIONS; i++) {
- connect_msg_.direction = static_cast<CRAS_STREAM_DIRECTION>(i);
- if (connect_msg_.direction == CRAS_STREAM_UNDEFINED)
- continue;
- called++;
- cras_rstream_create_stream_out = rstream_;
- cras_iodev_attach_stream_retval = 0;
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(
- rclient_, &connect_msg_.header, &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(called, cras_make_fd_nonblocking_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id_, out_msg.stream_id);
- EXPECT_EQ(0, out_msg.err);
- EXPECT_EQ(called, stream_list_add_stream_called);
- EXPECT_EQ(0, stream_list_disconnect_stream_called);
- }
-}
-
-TEST_F(RClientMessagesSuite, StreamConnectMessageInvalidDirection) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- connect_msg_.direction = CRAS_STREAM_UNDEFINED;
- cras_rstream_create_stream_out = rstream_;
- cras_iodev_attach_stream_retval = 0;
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &connect_msg_.header,
- &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id_, out_msg.stream_id);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(0, stream_list_add_stream_called);
- EXPECT_EQ(0, stream_list_disconnect_stream_called);
-}
-
-TEST_F(RClientMessagesSuite, StreamConnectMessageInvalidClientId) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- connect_msg_.stream_id = 0x20002; // stream_id with invalid client_id
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &connect_msg_.header,
- &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
- EXPECT_EQ(0, stream_list_add_stream_called);
- EXPECT_EQ(0, stream_list_disconnect_stream_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(connect_msg_.stream_id, out_msg.stream_id);
-}
-
-TEST_F(RClientMessagesSuite, SuccessReply) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- cras_rstream_create_stream_out = rstream_;
- cras_iodev_attach_stream_retval = 0;
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &connect_msg_.header,
- &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_make_fd_nonblocking_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id_, out_msg.stream_id);
- EXPECT_EQ(0, out_msg.err);
- EXPECT_EQ(1, stream_list_add_stream_called);
- EXPECT_EQ(0, stream_list_disconnect_stream_called);
-}
-
-TEST_F(RClientMessagesSuite, SuccessCreateThreadReply) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- cras_rstream_create_stream_out = rstream_;
- cras_iodev_attach_stream_retval = 0;
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &connect_msg_.header,
- &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_make_fd_nonblocking_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id_, out_msg.stream_id);
- EXPECT_EQ(0, out_msg.err);
- EXPECT_EQ(1, stream_list_add_stream_called);
- EXPECT_EQ(0, stream_list_disconnect_stream_called);
-}
-
-TEST_F(RClientMessagesSuite, SetVolume) {
- struct cras_set_system_volume msg;
- int rc;
-
- msg.header.id = CRAS_SERVER_SET_SYSTEM_VOLUME;
- msg.header.length = sizeof(msg);
- msg.volume = 66;
-
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_set_volume_called);
- EXPECT_EQ(66, cras_system_set_volume_value);
-}
-
-TEST_F(RClientMessagesSuite, SetMute) {
- struct cras_set_system_mute msg;
- int rc;
-
- msg.header.id = CRAS_SERVER_SET_SYSTEM_MUTE;
- msg.header.length = sizeof(msg);
- msg.mute = 1;
-
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_set_mute_called);
- EXPECT_EQ(1, cras_system_set_mute_value);
-
- msg.header.id = CRAS_SERVER_SET_SYSTEM_MUTE_LOCKED;
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_set_mute_locked_called);
- EXPECT_EQ(1, cras_system_set_mute_locked_value);
-}
-
-TEST_F(RClientMessagesSuite, SetUserMute) {
- struct cras_set_system_mute msg;
- int rc;
-
- msg.header.id = CRAS_SERVER_SET_USER_MUTE;
- msg.header.length = sizeof(msg);
- msg.mute = 1;
-
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_set_user_mute_called);
- EXPECT_EQ(1, cras_system_set_user_mute_value);
-}
-
-TEST_F(RClientMessagesSuite, SetCaptureMute) {
- struct cras_set_system_mute msg;
- int rc;
-
- msg.header.id = CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE;
- msg.header.length = sizeof(msg);
- msg.mute = 1;
-
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_set_capture_mute_called);
- EXPECT_EQ(1, cras_system_set_capture_mute_value);
-
- msg.header.id = CRAS_SERVER_SET_SYSTEM_CAPTURE_MUTE_LOCKED;
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_set_capture_mute_locked_called);
- EXPECT_EQ(1, cras_system_set_capture_mute_locked_value);
-}
-
-TEST_F(RClientMessagesSuite, DumpSnapshots) {
- struct cras_dump_snapshots msg;
- int rc;
- cras_fill_dump_snapshots(&msg);
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_system_state_dump_snapshots_called);
-}
-
-TEST_F(RClientMessagesSuite, ConfigGlobalRemix) {
- int rc;
- struct cras_config_global_remix msg;
- const int num_channels = 2;
- float coefficient[4] = {0.1, 0.2, 0.3, 0.4};
- cras_fill_config_global_remix_command(&msg, num_channels, coefficient,
- num_channels * num_channels);
-
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, audio_thread_config_global_remix_called);
- for (unsigned i = 0; i < (unsigned)num_channels * num_channels; i++) {
- EXPECT_EQ(audio_thread_config_global_remix_copy[i], coefficient[i]);
- }
-}
-
-void RClientMessagesSuite::RegisterNotification(
- enum CRAS_CLIENT_MESSAGE_ID msg_id,
- void* callback,
- void** ops_address) {
- struct cras_register_notification msg;
- int do_register = callback != NULL ? 1 : 0;
- int rc;
-
- cras_observer_register_notify_called++;
-
- cras_fill_register_notification_message(&msg, msg_id, do_register);
- EXPECT_EQ(msg.header.length, sizeof(msg));
- EXPECT_EQ(msg.header.id, CRAS_SERVER_REGISTER_NOTIFICATION);
- EXPECT_EQ(msg.do_register, do_register);
- EXPECT_EQ(msg.msg_id, msg_id);
-
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(cras_observer_register_notify_called, cras_observer_get_ops_called);
- EXPECT_EQ(cras_observer_register_notify_called,
- cras_observer_ops_are_empty_called);
- if (msg.do_register)
- cras_observer_num_ops_registered++;
- if (cras_observer_num_ops_registered == 1) {
- if (msg.do_register) {
- EXPECT_EQ(1, cras_observer_add_called);
- EXPECT_EQ(rclient_, cras_observer_add_context_value);
- EXPECT_EQ(rclient_->observer, cras_observer_add_return_value);
- } else {
- EXPECT_EQ(1, cras_observer_remove_called);
- EXPECT_EQ(rclient_->observer, (struct cras_observer_client*)NULL);
- }
- } else {
- EXPECT_EQ(cras_observer_register_notify_called - 1,
- cras_observer_set_ops_called);
- }
- if (!msg.do_register)
- cras_observer_num_ops_registered--;
- if (cras_observer_num_ops_registered) {
- EXPECT_EQ(callback, *ops_address);
- }
-}
-
-TEST_F(RClientMessagesSuite, RegisterStatusNotification) {
- /* First registration for this client. */
- RegisterNotification(CRAS_CLIENT_OUTPUT_VOLUME_CHANGED,
- (void*)send_output_volume_changed,
- (void**)&cras_observer_ops_value.output_volume_changed);
-
- /* Second registration for this client. */
- RegisterNotification(CRAS_CLIENT_CAPTURE_GAIN_CHANGED,
- (void*)send_capture_gain_changed,
- (void**)&cras_observer_ops_value.capture_gain_changed);
-
- /* Deregister output_volume. */
- RegisterNotification(CRAS_CLIENT_OUTPUT_VOLUME_CHANGED, NULL,
- (void**)&cras_observer_ops_value.output_volume_changed);
-
- /* Register/deregister all msg_ids. */
-
- RegisterNotification(CRAS_CLIENT_OUTPUT_MUTE_CHANGED,
- (void*)send_output_mute_changed,
- (void**)&cras_observer_ops_value.output_mute_changed);
- RegisterNotification(CRAS_CLIENT_OUTPUT_MUTE_CHANGED, NULL,
- (void**)&cras_observer_ops_value.output_mute_changed);
-
- RegisterNotification(CRAS_CLIENT_CAPTURE_MUTE_CHANGED,
- (void*)send_capture_mute_changed,
- (void**)&cras_observer_ops_value.capture_mute_changed);
- RegisterNotification(CRAS_CLIENT_CAPTURE_MUTE_CHANGED, NULL,
- (void**)&cras_observer_ops_value.capture_mute_changed);
-
- RegisterNotification(CRAS_CLIENT_NODES_CHANGED, (void*)send_nodes_changed,
- (void**)&cras_observer_ops_value.nodes_changed);
- RegisterNotification(CRAS_CLIENT_NODES_CHANGED, NULL,
- (void**)&cras_observer_ops_value.nodes_changed);
-
- RegisterNotification(CRAS_CLIENT_ACTIVE_NODE_CHANGED,
- (void*)send_active_node_changed,
- (void**)&cras_observer_ops_value.active_node_changed);
- RegisterNotification(CRAS_CLIENT_ACTIVE_NODE_CHANGED, NULL,
- (void**)&cras_observer_ops_value.active_node_changed);
-
- RegisterNotification(
- CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED,
- (void*)send_output_node_volume_changed,
- (void**)&cras_observer_ops_value.output_node_volume_changed);
- RegisterNotification(
- CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED, NULL,
- (void**)&cras_observer_ops_value.output_node_volume_changed);
-
- RegisterNotification(
- CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED,
- (void*)send_node_left_right_swapped_changed,
- (void**)&cras_observer_ops_value.node_left_right_swapped_changed);
- RegisterNotification(
- CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED, NULL,
- (void**)&cras_observer_ops_value.node_left_right_swapped_changed);
-
- RegisterNotification(
- CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED, (void*)send_input_node_gain_changed,
- (void**)&cras_observer_ops_value.input_node_gain_changed);
- RegisterNotification(
- CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED, NULL,
- (void**)&cras_observer_ops_value.input_node_gain_changed);
-
- RegisterNotification(
- CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED,
- (void*)send_num_active_streams_changed,
- (void**)&cras_observer_ops_value.num_active_streams_changed);
- RegisterNotification(
- CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED, NULL,
- (void**)&cras_observer_ops_value.num_active_streams_changed);
-
- /* Deregister last. */
- RegisterNotification(CRAS_CLIENT_CAPTURE_GAIN_CHANGED, NULL,
- (void**)&cras_observer_ops_value.capture_gain_changed);
-}
-
-TEST_F(RClientMessagesSuite, SendOutputVolumeChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_volume_changed* msg =
- (struct cras_client_volume_changed*)buf;
- const int32_t volume = 90;
-
- send_output_volume_changed(void_client, volume);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_OUTPUT_VOLUME_CHANGED);
- EXPECT_EQ(msg->volume, volume);
-}
-
-TEST_F(RClientMessagesSuite, SendOutputMuteChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_mute_changed* msg = (struct cras_client_mute_changed*)buf;
- const int muted = 1;
- const int user_muted = 0;
- const int mute_locked = 1;
-
- send_output_mute_changed(void_client, muted, user_muted, mute_locked);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_OUTPUT_MUTE_CHANGED);
- EXPECT_EQ(msg->muted, muted);
- EXPECT_EQ(msg->user_muted, user_muted);
- EXPECT_EQ(msg->mute_locked, mute_locked);
-}
-
-TEST_F(RClientMessagesSuite, SendCaptureMuteChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_mute_changed* msg = (struct cras_client_mute_changed*)buf;
- const int muted = 1;
- const int mute_locked = 0;
-
- send_capture_mute_changed(void_client, muted, mute_locked);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_CAPTURE_MUTE_CHANGED);
- EXPECT_EQ(msg->muted, muted);
- EXPECT_EQ(msg->mute_locked, mute_locked);
-}
-
-TEST_F(RClientMessagesSuite, SendNodesChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_nodes_changed* msg =
- (struct cras_client_nodes_changed*)buf;
-
- send_nodes_changed(void_client);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_NODES_CHANGED);
-}
-
-TEST_F(RClientMessagesSuite, SendActiveNodeChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_active_node_changed* msg =
- (struct cras_client_active_node_changed*)buf;
- const enum CRAS_STREAM_DIRECTION dir = CRAS_STREAM_INPUT;
- const cras_node_id_t node_id = 0x0001000200030004;
-
- send_active_node_changed(void_client, dir, node_id);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_ACTIVE_NODE_CHANGED);
- EXPECT_EQ(msg->direction, (int32_t)dir);
- EXPECT_EQ((uint64_t)msg->node_id, node_id);
-}
-
-TEST_F(RClientMessagesSuite, SendOutputNodeVolumeChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_node_value_changed* msg =
- (struct cras_client_node_value_changed*)buf;
- const cras_node_id_t node_id = 0x0001000200030004;
- const int32_t value = 90;
-
- send_output_node_volume_changed(void_client, node_id, value);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_OUTPUT_NODE_VOLUME_CHANGED);
- EXPECT_EQ(msg->node_id, node_id);
- EXPECT_EQ(msg->value, value);
-}
-
-TEST_F(RClientMessagesSuite, SendNodeLeftRightSwappedChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_node_value_changed* msg =
- (struct cras_client_node_value_changed*)buf;
- const cras_node_id_t node_id = 0x0001000200030004;
- const int32_t value = 0;
-
- send_node_left_right_swapped_changed(void_client, node_id, value);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_NODE_LEFT_RIGHT_SWAPPED_CHANGED);
- EXPECT_EQ(msg->node_id, node_id);
- EXPECT_EQ(msg->value, value);
-}
-
-TEST_F(RClientMessagesSuite, SendNodeInputNodeGainChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_node_value_changed* msg =
- (struct cras_client_node_value_changed*)buf;
- const cras_node_id_t node_id = 0x0001000200030004;
- const int32_t value = -19;
-
- send_input_node_gain_changed(void_client, node_id, value);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_INPUT_NODE_GAIN_CHANGED);
- EXPECT_EQ(msg->node_id, node_id);
- EXPECT_EQ(msg->value, value);
-}
-
-TEST_F(RClientMessagesSuite, SendNumActiveStreamsChanged) {
- void* void_client = reinterpret_cast<void*>(rclient_);
- char buf[1024];
- ssize_t rc;
- struct cras_client_num_active_streams_changed* msg =
- (struct cras_client_num_active_streams_changed*)buf;
- const enum CRAS_STREAM_DIRECTION dir = CRAS_STREAM_INPUT;
- const uint32_t num_active_streams = 3;
-
- send_num_active_streams_changed(void_client, dir, num_active_streams);
- rc = read(pipe_fds_[0], buf, sizeof(buf));
- ASSERT_EQ(rc, (ssize_t)sizeof(*msg));
- EXPECT_EQ(msg->header.id, CRAS_CLIENT_NUM_ACTIVE_STREAMS_CHANGED);
- EXPECT_EQ(msg->direction, (int32_t)dir);
- EXPECT_EQ(msg->num_active_streams, num_active_streams);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-/* stubs */
-extern "C" {
-
-struct cras_bt_event_log* btlog;
-struct main_thread_event_log* main_log;
-
-struct audio_thread* cras_iodev_list_get_audio_thread() {
- return iodev_get_thread_return;
-}
-
-void cras_iodev_list_add_active_node(enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id) {}
-
-void cras_iodev_list_rm_active_node(enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id) {}
-
-int audio_thread_rm_stream(audio_thread* thread, cras_rstream* stream) {
- return 0;
-}
-
-void audio_thread_add_output_dev(struct audio_thread* thread,
- struct cras_iodev* odev) {}
-
-int audio_thread_dump_thread_info(struct audio_thread* thread,
- struct audio_debug_info* info) {
- return 0;
-}
-
-int audio_thread_suspend(struct audio_thread* thread) {
- return 0;
-}
-
-int audio_thread_resume(struct audio_thread* thread) {
- return 0;
-}
-
-int audio_thread_config_global_remix(struct audio_thread* thread,
- unsigned int num_channels,
- const float* coefficient) {
- audio_thread_config_global_remix_called++;
- memcpy(audio_thread_config_global_remix_copy, coefficient,
- num_channels * num_channels * sizeof(coefficient));
- return 0;
-}
-
-int audio_thread_set_aec_dump(struct audio_thread* thread,
- cras_stream_id_t stream_id,
- unsigned int start,
- int fd) {
- return 0;
-}
-
-int audio_thread_event_log_shm_fd() {
- return -1;
-}
-
-#ifdef HAVE_WEBRTC_APM
-void cras_apm_list_reload_aec_config() {}
-#endif
-
-void cras_system_set_bt_wbs_enabled(bool enabled) {}
-
-const char* cras_config_get_socket_file_dir() {
- return CRAS_UT_TMPDIR;
-}
-
-int cras_rstream_create(struct cras_rstream_config* stream_config,
- struct cras_rstream** stream_out) {
- *stream_out = cras_rstream_create_stream_out;
- return cras_rstream_create_return;
-}
-
-unsigned int cras_rstream_get_effects(const struct cras_rstream* stream) {
- return 0;
-}
-
-int cras_iodev_move_stream_type(uint32_t type, uint32_t index) {
- return 0;
-}
-
-int cras_iodev_list_rm_output(struct cras_iodev* output) {
- cras_iodev_list_rm_output_called++;
- return 0;
-}
-
-int cras_iodev_list_rm_input(struct cras_iodev* input) {
- cras_iodev_list_rm_input_called++;
- return 0;
-}
-
-int cras_server_disconnect_from_client_socket(int socket_fd) {
- return 0;
-}
-
-int cras_make_fd_nonblocking(int fd) {
- cras_make_fd_nonblocking_called++;
- return 0;
-}
-
-void cras_system_state_dump_snapshots() {
- cras_system_state_dump_snapshots_called++;
-}
-
-void cras_system_set_volume(size_t volume) {
- cras_system_set_volume_value = volume;
- cras_system_set_volume_called++;
-}
-
-// From system_state.
-void cras_system_set_mute(int mute) {
- cras_system_set_mute_value = mute;
- cras_system_set_mute_called++;
-}
-void cras_system_set_user_mute(int mute) {
- cras_system_set_user_mute_value = mute;
- cras_system_set_user_mute_called++;
-}
-void cras_system_set_mute_locked(int mute) {
- cras_system_set_mute_locked_value = mute;
- cras_system_set_mute_locked_called++;
-}
-void cras_system_set_capture_mute(int mute) {
- cras_system_set_capture_mute_value = mute;
- cras_system_set_capture_mute_called++;
-}
-void cras_system_set_capture_mute_locked(int mute) {
- cras_system_set_capture_mute_locked_value = mute;
- cras_system_set_capture_mute_locked_called++;
-}
-
-int cras_system_remove_alsa_card(size_t alsa_card_index) {
- return -1;
-}
-
-void cras_system_set_suspended(int suspended) {}
-
-struct cras_server_state* cras_system_state_get_no_lock() {
- return NULL;
-}
-
-key_t cras_sys_state_shm_fd() {
- return 1;
-}
-
-void cras_dsp_reload_ini() {}
-
-void cras_dsp_dump_info() {}
-
-int cras_iodev_list_set_node_attr(cras_node_id_t id,
- enum ionode_attr attr,
- int value) {
- return 0;
-}
-
-void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id) {}
-
-void cras_iodev_list_add_test_dev(enum TEST_IODEV_TYPE type) {}
-
-struct stream_list* cras_iodev_list_get_stream_list() {
- return NULL;
-}
-
-/* Handles sending a command to a test iodev. */
-void cras_iodev_list_test_dev_command(unsigned int iodev_idx,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len,
- const uint8_t* data) {}
-
-void cras_iodev_list_configure_global_remix_converter(
- unsigned int num_channels,
- const float* coefficient) {}
-
-int stream_list_add(struct stream_list* list,
- struct cras_rstream_config* config,
- struct cras_rstream** stream) {
- int ret;
-
- *stream = &mock_rstream;
-
- stream_list_add_stream_called++;
- ret = stream_list_add_stream_return;
- if (ret)
- stream_list_add_stream_return = -EINVAL;
-
- mock_rstream.shm = &mock_shm;
- mock_rstream.direction = config->direction;
- mock_rstream.stream_id = config->stream_id;
-
- return ret;
-}
-
-int stream_list_rm(struct stream_list* list, cras_stream_id_t id) {
- stream_list_disconnect_stream_called++;
- return 0;
-}
-
-int stream_list_rm_all_client_streams(struct stream_list* list,
- struct cras_rclient* rclient) {
- return 0;
-}
-
-int cras_send_with_fds(int sockfd,
- const void* buf,
- size_t len,
- int* fd,
- unsigned int num_fds) {
- return write(sockfd, buf, len);
-}
-
-char* cras_iodev_list_get_hotword_models(cras_node_id_t node_id) {
- return NULL;
-}
-
-int cras_iodev_list_set_hotword_model(cras_node_id_t id,
- const char* model_name) {
- return 0;
-}
-
-struct cras_observer_client* cras_observer_add(
- const struct cras_observer_ops* ops,
- void* context) {
- cras_observer_add_called++;
- cras_observer_add_context_value = context;
- memcpy(&cras_observer_ops_value, ops, sizeof(cras_observer_ops_value));
- return cras_observer_add_return_value;
-}
-
-void cras_observer_get_ops(const struct cras_observer_client* client,
- struct cras_observer_ops* ops) {
- cras_observer_get_ops_called++;
- memcpy(ops, &cras_observer_ops_value, sizeof(*ops));
-}
-
-void cras_observer_set_ops(struct cras_observer_client* client,
- const struct cras_observer_ops* ops) {
- cras_observer_set_ops_called++;
- memcpy(&cras_observer_ops_value, ops, sizeof(cras_observer_ops_value));
-}
-
-int cras_observer_ops_are_empty(const struct cras_observer_ops* ops) {
- cras_observer_ops_are_empty_called++;
- return memcmp(&cras_observer_ops_are_empty_empty_ops, ops,
- sizeof(cras_observer_ops_are_empty_empty_ops)) == 0;
-}
-
-void cras_observer_remove(struct cras_observer_client* client) {
- cras_observer_remove_called++;
-}
-
-bool cras_audio_format_valid(const struct cras_audio_format* fmt) {
- return true;
-}
-
-struct packet_status_logger* cras_hfp_ag_get_wbs_logger() {
- return NULL;
-}
-
-void detect_rtc_stream_pair(struct stream_list* list,
- struct cras_rstream* stream) {
- return;
-}
-
-void cras_system_set_hotword_pause_at_suspend(bool pause) {}
-
-} // extern "C"
diff --git a/cras/src/tests/cras_abi_unittest.cc b/cras/src/tests/cras_abi_unittest.cc
deleted file mode 100644
index d566a9b7..00000000
--- a/cras/src/tests/cras_abi_unittest.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Copyright 2021 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "cras_client.c"
-#include "cras_client.h"
-
-inline int libcras_unsupported_func(struct libcras_client* client) {
- CHECK_VERSION(client, INT_MAX);
- return 0;
-}
-
-cras_stream_id_t cb_stream_id;
-uint8_t* cb_buf;
-unsigned int cb_frames;
-struct timespec cb_latency;
-void* cb_usr_arg;
-int get_stream_cb_called;
-struct timespec now;
-
-int get_stream_cb(struct libcras_stream_cb_data* data) {
- get_stream_cb_called++;
- EXPECT_NE((void*)NULL, data);
- EXPECT_EQ(0, libcras_stream_cb_data_get_stream_id(data, &cb_stream_id));
- EXPECT_EQ(0, libcras_stream_cb_data_get_buf(data, &cb_buf));
- EXPECT_EQ(0, libcras_stream_cb_data_get_frames(data, &cb_frames));
- EXPECT_EQ(0, libcras_stream_cb_data_get_latency(data, &cb_latency));
- EXPECT_EQ(0, libcras_stream_cb_data_get_usr_arg(data, &cb_usr_arg));
- return 0;
-}
-}
-
-namespace {
-class CrasAbiTestSuite : public testing::Test {
- protected:
- struct cras_audio_shm* InitShm(int frames) {
- struct cras_audio_shm* shm =
- static_cast<struct cras_audio_shm*>(calloc(1, sizeof(*shm)));
- shm->header =
- static_cast<cras_audio_shm_header*>(calloc(1, sizeof(*shm->header)));
- cras_shm_set_frame_bytes(shm, 4);
- uint32_t used_size = frames * 4;
- cras_shm_set_used_size(shm, used_size);
- shm->samples_info.length = used_size * 2;
- memcpy(&shm->header->config, &shm->config, sizeof(shm->config));
- return shm;
- }
-
- void DestroyShm(struct cras_audio_shm* shm) {
- if (shm)
- free(shm->header);
- free(shm);
- }
-
- virtual void SetUp() { get_stream_cb_called = 0; }
-};
-
-TEST_F(CrasAbiTestSuite, CheckUnsupportedFunction) {
- auto* client = libcras_client_create();
- EXPECT_NE((void*)NULL, client);
- EXPECT_EQ(-ENOSYS, libcras_unsupported_func(client));
- libcras_client_destroy(client);
-}
-
-TEST_F(CrasAbiTestSuite, BasicStream) {
- auto* client = libcras_client_create();
- EXPECT_NE((void*)NULL, client);
- auto* stream = libcras_stream_params_create();
- EXPECT_NE((void*)NULL, stream);
- /* Returns timeout because there is no real CRAS server in unittest. */
- EXPECT_EQ(-ETIMEDOUT, libcras_client_connect_timeout(client, 0));
- EXPECT_EQ(0, libcras_client_run_thread(client));
- EXPECT_EQ(0, libcras_stream_params_set(stream, CRAS_STREAM_INPUT, 480, 480,
- CRAS_STREAM_TYPE_DEFAULT,
- CRAS_CLIENT_TYPE_TEST, 0, NULL, NULL,
- NULL, 48000, SND_PCM_FORMAT_S16, 2));
- cras_stream_id_t id;
- /* Fails to add a stream because the stream callback is not set. */
- EXPECT_EQ(-EINVAL, libcras_client_add_pinned_stream(client, 0, &id, stream));
- /* Fails to set a stream volume because the stream is not added. */
- EXPECT_EQ(-EINVAL, libcras_client_set_stream_volume(client, id, 1.0));
- EXPECT_EQ(0, libcras_client_rm_stream(client, id));
- EXPECT_EQ(0, libcras_client_stop(client));
- libcras_stream_params_destroy(stream);
- libcras_client_destroy(client);
-}
-
-TEST_F(CrasAbiTestSuite, StreamCallback) {
- struct client_stream stream;
- struct cras_stream_params params;
- stream.id = 0x123;
- stream.direction = CRAS_STREAM_INPUT;
- stream.flags = 0;
- stream.config = &params;
- params.stream_cb = get_stream_cb;
- params.cb_threshold = 480;
- params.user_data = (void*)0x321;
- stream.shm = InitShm(960);
- stream.shm->header->write_offset[0] = 960 * 4;
- stream.shm->header->write_buf_idx = 0;
- stream.shm->header->read_offset[0] = 0;
- stream.shm->header->read_buf_idx = 0;
- now.tv_sec = 100;
- now.tv_nsec = 0;
- stream.shm->header->ts.tv_sec = 90;
- stream.shm->header->ts.tv_nsec = 0;
-
- handle_capture_data_ready(&stream, 480);
-
- EXPECT_EQ(1, get_stream_cb_called);
- EXPECT_EQ(stream.id, cb_stream_id);
- EXPECT_EQ(cras_shm_get_write_buffer_base(stream.shm), cb_buf);
- EXPECT_EQ(480, cb_frames);
- EXPECT_EQ(10, cb_latency.tv_sec);
- EXPECT_EQ(0, cb_latency.tv_nsec);
- EXPECT_EQ((void*)0x321, cb_usr_arg);
-
- DestroyShm(stream.shm);
-}
-
-} // namespace
-
-extern "C" {
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = now;
- return 0;
-}
-}
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/cras_client_unittest.cc b/cras/src/tests/cras_client_unittest.cc
deleted file mode 100644
index c1103afb..00000000
--- a/cras/src/tests/cras_client_unittest.cc
+++ /dev/null
@@ -1,432 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_messages.h"
-
-// Include C file to test static functions.
-#include "cras_client.c"
-}
-
-static const cras_stream_id_t FIRST_STREAM_ID = 1;
-
-static int pthread_create_called;
-static int pthread_join_called;
-static int pthread_cond_timedwait_called;
-static int pthread_cond_timedwait_retval;
-static int close_called;
-static int sendmsg_called;
-static void* mmap_return_value;
-static int samples_ready_called;
-static int samples_ready_frames_value;
-static uint8_t* samples_ready_samples_value;
-
-static int pthread_create_returned_value;
-
-namespace {
-
-void InitStaticVariables() {
- pthread_create_called = 0;
- pthread_join_called = 0;
- pthread_cond_timedwait_called = 0;
- pthread_cond_timedwait_retval = 0;
- close_called = 0;
- sendmsg_called = 0;
- pthread_create_returned_value = 0;
- mmap_return_value = NULL;
- samples_ready_called = 0;
- samples_ready_frames_value = 0;
-}
-
-class CrasClientTestSuite : public testing::Test {
- protected:
- struct cras_audio_shm* InitShm() {
- struct cras_audio_shm* shm =
- static_cast<struct cras_audio_shm*>(calloc(1, sizeof(*shm)));
- shm->header =
- static_cast<cras_audio_shm_header*>(calloc(1, sizeof(*shm->header)));
- cras_shm_set_frame_bytes(shm, 4);
- uint32_t used_size = shm_writable_frames_ * 4;
- cras_shm_set_used_size(shm, used_size);
- shm->samples_info.length = used_size * 2;
- memcpy(&shm->header->config, &shm->config, sizeof(shm->config));
- return shm;
- }
-
- virtual void SetUp() {
- shm_writable_frames_ = 100;
- InitStaticVariables();
-
- memset(&client_, 0, sizeof(client_));
- client_.server_fd_state = CRAS_SOCKET_STATE_CONNECTED;
- memset(&stream_, 0, sizeof(stream_));
- stream_.id = FIRST_STREAM_ID;
-
- struct cras_stream_params* config =
- static_cast<cras_stream_params*>(calloc(1, sizeof(*config)));
- config->buffer_frames = 1024;
- config->cb_threshold = 512;
- stream_.config = config;
- }
-
- virtual void TearDown() {
- if (stream_.config) {
- free(stream_.config);
- stream_.config = NULL;
- }
-
- if (stream_.shm) {
- free(stream_.shm->header);
- }
- free(stream_.shm);
- stream_.shm = NULL;
- }
-
- void StreamConnected(CRAS_STREAM_DIRECTION direction);
-
- void StreamConnectedFail(CRAS_STREAM_DIRECTION direction);
-
- struct client_stream stream_;
- struct cras_client client_;
- int shm_writable_frames_;
-};
-
-void set_audio_format(struct cras_audio_format* format,
- snd_pcm_format_t pcm_format,
- size_t frame_rate,
- size_t num_channels) {
- format->format = pcm_format;
- format->frame_rate = frame_rate;
- format->num_channels = num_channels;
- for (size_t i = 0; i < CRAS_CH_MAX; ++i)
- format->channel_layout[i] = i < num_channels ? i : -1;
-}
-
-int capture_samples_ready(cras_client* client,
- cras_stream_id_t stream_id,
- uint8_t* samples,
- size_t frames,
- const timespec* sample_ts,
- void* arg) {
- samples_ready_called++;
- samples_ready_samples_value = samples;
- samples_ready_frames_value = frames;
- return frames;
-}
-
-TEST_F(CrasClientTestSuite, HandleCaptureDataReady) {
- struct cras_audio_shm* shm;
-
- stream_.direction = CRAS_STREAM_INPUT;
-
- shm_writable_frames_ = 480;
- shm = InitShm();
- stream_.shm = shm;
- stream_.config->buffer_frames = 480;
- stream_.config->cb_threshold = 480;
- stream_.config->aud_cb = capture_samples_ready;
- stream_.config->unified_cb = 0;
-
- shm->header->write_buf_idx = 0;
- shm->header->read_buf_idx = 0;
- shm->header->write_offset[0] = 480 * 4;
- shm->header->read_offset[0] = 0;
-
- /* Normal scenario: read buffer has full of data written,
- * handle_capture_data_ready() should consume all 480 frames and move
- * read_buf_idx to the next buffer. */
- handle_capture_data_ready(&stream_, 480);
- EXPECT_EQ(1, samples_ready_called);
- EXPECT_EQ(480, samples_ready_frames_value);
- EXPECT_EQ(cras_shm_buff_for_idx(shm, 0), samples_ready_samples_value);
- EXPECT_EQ(1, shm->header->read_buf_idx);
- EXPECT_EQ(0, shm->header->write_offset[0]);
- EXPECT_EQ(0, shm->header->read_offset[0]);
-
- /* At the beginning of overrun: handle_capture_data_ready() should not
- * proceed to call audio_cb because there's no data captured. */
- shm->header->read_buf_idx = 0;
- shm->header->write_offset[0] = 0;
- shm->header->read_offset[0] = 0;
- handle_capture_data_ready(&stream_, 480);
- EXPECT_EQ(1, samples_ready_called);
- EXPECT_EQ(0, shm->header->read_buf_idx);
-
- /* In the middle of overrun: partially written buffer should trigger
- * audio_cb, feed the full-sized read buffer to client. */
- shm->header->read_buf_idx = 0;
- shm->header->write_offset[0] = 123;
- shm->header->read_offset[0] = 0;
- handle_capture_data_ready(&stream_, 480);
- EXPECT_EQ(1, samples_ready_called);
- EXPECT_EQ(0, shm->header->read_buf_idx);
-}
-
-void CrasClientTestSuite::StreamConnected(CRAS_STREAM_DIRECTION direction) {
- struct cras_client_stream_connected msg;
- int shm_fds[2] = {0, 1};
- int shm_max_size = 600;
- size_t format_bytes;
- size_t effects = 123;
- struct cras_audio_shm_header* header;
-
- stream_.direction = direction;
- set_audio_format(&stream_.config->format, SND_PCM_FORMAT_S16_LE, 48000, 4);
-
- struct cras_audio_format server_format;
- set_audio_format(&server_format, SND_PCM_FORMAT_S16_LE, 44100, 2);
-
- // Initialize shm area
- format_bytes = cras_get_format_bytes(&server_format);
- header = (struct cras_audio_shm_header*)calloc(1, sizeof(*header));
- header->config.frame_bytes = format_bytes;
- header->config.used_size = shm_writable_frames_ * format_bytes;
-
- mmap_return_value = header;
-
- cras_fill_client_stream_connected(&msg, 0, stream_.id, &server_format,
- shm_max_size, effects);
-
- stream_connected(&stream_, &msg, shm_fds, 2);
-
- EXPECT_EQ(CRAS_THREAD_RUNNING, stream_.thread.state);
- EXPECT_EQ(header, stream_.shm->header);
-}
-
-TEST_F(CrasClientTestSuite, InputStreamConnected) {
- StreamConnected(CRAS_STREAM_INPUT);
-}
-
-TEST_F(CrasClientTestSuite, OutputStreamConnected) {
- StreamConnected(CRAS_STREAM_OUTPUT);
-}
-
-void CrasClientTestSuite::StreamConnectedFail(CRAS_STREAM_DIRECTION direction) {
- struct cras_client_stream_connected msg;
- int shm_fds[2] = {0, 1};
- int shm_max_size = 600;
- size_t format_bytes;
- size_t effects = 123;
- struct cras_audio_shm_header header;
- int rc;
-
- stream_.direction = direction;
- set_audio_format(&stream_.config->format, SND_PCM_FORMAT_S16_LE, 48000, 4);
-
- struct cras_audio_format server_format;
- set_audio_format(&server_format, SND_PCM_FORMAT_S16_LE, 44100, 2);
-
- // Thread setup
- rc = pipe(stream_.wake_fds);
- ASSERT_EQ(0, rc);
- stream_.thread.state = CRAS_THREAD_WARMUP;
-
- // Initialize shm area
- format_bytes = cras_get_format_bytes(&server_format);
- memset(&header, 0, sizeof(header));
- header.config.frame_bytes = format_bytes;
- header.config.used_size = shm_writable_frames_ * format_bytes;
-
- mmap_return_value = &header;
-
- // Put an error in the message.
- cras_fill_client_stream_connected(&msg, 1, stream_.id, &server_format,
- shm_max_size, effects);
-
- stream_connected(&stream_, &msg, shm_fds, 2);
-
- EXPECT_EQ(CRAS_THREAD_STOP, stream_.thread.state);
- EXPECT_EQ(4, close_called); // close the pipefds and shm_fds
-}
-
-TEST_F(CrasClientTestSuite, InputStreamConnectedFail) {
- StreamConnectedFail(CRAS_STREAM_INPUT);
-}
-
-TEST_F(CrasClientTestSuite, OutputStreamConnectedFail) {
- StreamConnectedFail(CRAS_STREAM_OUTPUT);
-}
-
-TEST_F(CrasClientTestSuite, AddAndRemoveStream) {
- cras_stream_id_t stream_id;
- struct cras_disconnect_stream_message msg;
- int serv_fds[2];
- int rc;
-
- // Dynamically allocate the stream so that it can be freed later.
- struct client_stream* stream_ptr =
- (struct client_stream*)malloc(sizeof(*stream_ptr));
- memcpy(stream_ptr, &stream_, sizeof(client_stream));
-
- stream_ptr->config =
- (struct cras_stream_params*)malloc(sizeof(*(stream_ptr->config)));
- memcpy(stream_ptr->config, stream_.config, sizeof(*(stream_.config)));
-
- stream_ptr->wake_fds[0] = -1;
- stream_ptr->wake_fds[1] = -1;
-
- pthread_cond_timedwait_retval = ETIMEDOUT;
- EXPECT_EQ(-ETIMEDOUT, client_thread_add_stream(&client_, stream_ptr,
- &stream_id, NO_DEVICE));
- EXPECT_EQ(pthread_cond_timedwait_called, 1);
- EXPECT_EQ(pthread_join_called, 0);
-
- InitStaticVariables();
- EXPECT_EQ(
- 0, client_thread_add_stream(&client_, stream_ptr, &stream_id, NO_DEVICE));
- EXPECT_EQ(&client_, stream_ptr->client);
- EXPECT_EQ(stream_id, stream_ptr->id);
- EXPECT_EQ(pthread_create_called, 1);
- EXPECT_NE(-1, stream_ptr->wake_fds[0]);
- EXPECT_NE(-1, stream_ptr->wake_fds[1]);
- EXPECT_EQ(1, sendmsg_called); // send connect message to server
- EXPECT_EQ(stream_ptr, stream_from_id(&client_, stream_id));
-
- stream_ptr->thread.state = CRAS_THREAD_RUNNING;
-
- rc = pipe(serv_fds);
- EXPECT_EQ(0, rc);
- client_.server_fd = serv_fds[1];
- client_.server_fd_state = CRAS_SOCKET_STATE_CONNECTED;
- EXPECT_EQ(0, client_thread_rm_stream(&client_, stream_id));
-
- rc = read(serv_fds[0], &msg, sizeof(msg));
- EXPECT_EQ(sizeof(msg), rc);
- EXPECT_EQ(stream_id, msg.stream_id);
- EXPECT_EQ(1, pthread_join_called);
-
- EXPECT_EQ(NULL, stream_from_id(&client_, stream_id));
-}
-
-TEST_F(CrasClientTestSuite, SetOutputStreamVolume) {
- cras_stream_id_t stream_id;
-
- client_thread_add_stream(&client_, &stream_, &stream_id, NO_DEVICE);
- EXPECT_EQ(&stream_, stream_from_id(&client_, stream_id));
-
- /* Set volume before stream connected. */
- client_thread_set_stream_volume(&client_, stream_id, 0.3f);
- StreamConnected(CRAS_STREAM_OUTPUT);
- EXPECT_EQ(0.3f, cras_shm_get_volume_scaler(stream_.shm));
-
- /* Set volume after stream connected. */
- client_thread_set_stream_volume(&client_, stream_id, 0.6f);
- EXPECT_EQ(0.6f, cras_shm_get_volume_scaler(stream_.shm));
-}
-
-TEST_F(CrasClientTestSuite, SetInputStreamVolume) {
- cras_stream_id_t stream_id;
-
- client_thread_add_stream(&client_, &stream_, &stream_id, NO_DEVICE);
- EXPECT_EQ(&stream_, stream_from_id(&client_, stream_id));
-
- /* Set volume before stream connected. */
- client_thread_set_stream_volume(&client_, stream_id, 0.3f);
- StreamConnected(CRAS_STREAM_INPUT);
- EXPECT_EQ(0.3f, cras_shm_get_volume_scaler(stream_.shm));
-
- /* Set volume after stream connected. */
- client_thread_set_stream_volume(&client_, stream_id, 0.6f);
- EXPECT_EQ(0.6f, cras_shm_get_volume_scaler(stream_.shm));
-}
-
-TEST(CrasClientTest, InitStreamVolume) {
- cras_stream_id_t stream_id;
- struct cras_stream_params config;
- struct add_stream_command_message cmd_msg;
- int rc;
- struct cras_client client;
-
- memset(&client, 0, sizeof(client));
- memset(&config, 0, sizeof(config));
- client.server_fd_state = CRAS_SOCKET_STATE_CONNECTED;
-
- config.aud_cb = reinterpret_cast<cras_playback_cb_t>(0x123);
- config.err_cb = reinterpret_cast<cras_error_cb_t>(0x456);
- client.thread.state = CRAS_THREAD_RUNNING;
- rc = pipe(client.command_reply_fds);
- EXPECT_EQ(0, rc);
- rc = pipe(client.command_fds);
- EXPECT_EQ(0, rc);
-
- rc = write(client.command_reply_fds[1], &rc, sizeof(rc));
- cras_client_add_stream(&client, &stream_id, &config);
-
- rc = read(client.command_fds[0], &cmd_msg, sizeof(cmd_msg));
- EXPECT_EQ(sizeof(cmd_msg), rc);
- EXPECT_NE((void*)NULL, cmd_msg.stream);
-
- EXPECT_EQ(1.0f, cmd_msg.stream->volume_scaler);
-
- if (cmd_msg.stream->config)
- free(cmd_msg.stream->config);
- free(cmd_msg.stream);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-/* stubs */
-extern "C" {
-
-ssize_t sendmsg(int sockfd, const struct msghdr* msg, int flags) {
- ++sendmsg_called;
- return msg->msg_iov->iov_len;
-}
-
-int close(int fd) {
- ++close_called;
- return 0;
-}
-
-int pthread_create(pthread_t* thread,
- const pthread_attr_t* attr,
- void* (*start_routine)(void*),
- void* arg) {
- ++pthread_create_called;
- return pthread_create_returned_value;
-}
-
-int pthread_join(pthread_t thread, void** retval) {
- ++pthread_join_called;
- return 0;
-}
-
-int pthread_cond_timedwait(pthread_cond_t* __restrict cond,
- pthread_mutex_t* __restrict mutex,
- const struct timespec* __restrict timeout) {
- ++pthread_cond_timedwait_called;
- return pthread_cond_timedwait_retval;
-}
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = 0;
- tp->tv_nsec = 0;
- return 0;
-}
-
-void* mmap(void* addr,
- size_t length,
- int prot,
- int flags,
- int fd,
- off_t offset) {
- return mmap_return_value;
-}
-
-struct cras_audio_format* cras_audio_format_create(snd_pcm_format_t format,
- size_t frame_rate,
- size_t num_channels) {
- return reinterpret_cast<struct cras_audio_format*>(0x123);
-}
-
-void cras_audio_format_destroy(struct cras_audio_format* fmt) {}
-}
diff --git a/cras/src/tests/cras_dsp_pipeline_unittest.cc b/cras/src/tests/cras_dsp_pipeline_unittest.cc
deleted file mode 100644
index b6c733ac..00000000
--- a/cras/src/tests/cras_dsp_pipeline_unittest.cc
+++ /dev/null
@@ -1,518 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "cras_dsp_pipeline.h"
-
-#include <gtest/gtest.h>
-
-#include "cras_config.h"
-#include "cras_dsp_module.h"
-
-#define MAX_MODULES 10
-#define MAX_MOCK_PORTS 30
-#define FILENAME_TEMPLATE "DspIniTest.XXXXXX"
-
-static void fill_test_data(int16_t* data, size_t size) {
- for (size_t i = 0; i < size; i++)
- data[i] = i;
-}
-
-static void verify_processed_data(int16_t* data, size_t size, int times) {
- /* Each time the audio data flow through the mock plugin, the data
- * will be multiplied by 2 in module->run() below, so if there are n
- * plugins, the data will be multiplied by (1 << n). */
- int multiples = (1 << times);
- for (size_t i = 0; i < size; i++) {
- EXPECT_EQ(i * multiples, data[i]);
- if ((int16_t)i * multiples != data[i])
- return;
- }
-}
-
-struct data {
- const char* title;
- int nr_ports;
- port_direction port_dir[MAX_MOCK_PORTS];
- int nr_in_audio;
- int nr_in_control;
- int nr_out_audio;
- int nr_out_control;
- int in_audio[MAX_MOCK_PORTS];
- int in_control[MAX_MOCK_PORTS];
- int out_audio[MAX_MOCK_PORTS];
- int out_control[MAX_MOCK_PORTS];
- int properties;
-
- int instantiate_called;
- int sample_rate;
-
- int connect_port_called[MAX_MOCK_PORTS];
- float* data_location[MAX_MOCK_PORTS];
-
- int run_called;
- float input[MAX_MOCK_PORTS];
- float output[MAX_MOCK_PORTS];
-
- int sample_count;
-
- int get_delay_called;
- int deinstantiate_called;
- int free_module_called;
- int get_properties_called;
-};
-
-static int instantiate(struct dsp_module* module, unsigned long sample_rate) {
- struct data* data = (struct data*)module->data;
- data->instantiate_called++;
- data->sample_rate = sample_rate;
- return 0;
-}
-
-static void connect_port(struct dsp_module* module,
- unsigned long port,
- float* data_location) {
- struct data* data = (struct data*)module->data;
- data->connect_port_called[port]++;
- data->data_location[port] = data_location;
-}
-
-static int get_delay(struct dsp_module* module) {
- struct data* data = (struct data*)module->data;
- data->get_delay_called++;
-
- /* If the module title is "mN", then use N as the delay. */
- int delay = 0;
- sscanf(data->title, "m%d", &delay);
- return delay;
-}
-
-static void run(struct dsp_module* module, unsigned long sample_count) {
- struct data* data = (struct data*)module->data;
- data->run_called++;
- data->sample_count = sample_count;
-
- for (int i = 0; i < data->nr_ports; i++) {
- if (data->port_dir[i] == PORT_INPUT)
- data->input[i] = *data->data_location[i];
- }
-
- /* copy the control port data */
- for (int i = 0; i < std::min(data->nr_in_control, data->nr_out_control);
- i++) {
- int from = data->in_control[i];
- int to = data->out_control[i];
- data->data_location[to][0] = data->data_location[from][0];
- }
-
- /* multiply the audio port data by 2 */
- for (int i = 0; i < std::min(data->nr_in_audio, data->nr_out_audio); i++) {
- int from = data->in_audio[i];
- int to = data->out_audio[i];
- for (unsigned int j = 0; j < sample_count; j++)
- data->data_location[to][j] = data->data_location[from][j] * 2;
- }
-}
-
-static void deinstantiate(struct dsp_module* module) {
- struct data* data = (struct data*)module->data;
- data->deinstantiate_called++;
-}
-
-static void free_module(struct dsp_module* module) {
- struct data* data = (struct data*)module->data;
- data->free_module_called++;
-}
-
-static void really_free_module(struct dsp_module* module) {
- struct data* data = (struct data*)module->data;
- free(data);
- free(module);
-}
-
-static int get_properties(struct dsp_module* module) {
- struct data* data = (struct data*)module->data;
- data->get_properties_called++;
- return data->properties;
-}
-static void dump(struct dsp_module* module, struct dumper* d) {}
-
-static struct dsp_module* create_mock_module(struct plugin* plugin) {
- struct data* data;
- struct dsp_module* module;
-
- data = (struct data*)calloc(1, sizeof(struct data));
- data->title = plugin->title;
- data->nr_ports = ARRAY_COUNT(&plugin->ports);
- for (int i = 0; i < data->nr_ports; i++) {
- struct port* port = ARRAY_ELEMENT(&plugin->ports, i);
- data->port_dir[i] = port->direction;
-
- if (port->direction == PORT_INPUT) {
- if (port->type == PORT_AUDIO)
- data->in_audio[data->nr_in_audio++] = i;
- else
- data->in_control[data->nr_in_control++] = i;
- } else {
- if (port->type == PORT_AUDIO)
- data->out_audio[data->nr_out_audio++] = i;
- else
- data->out_control[data->nr_out_control++] = i;
- }
- }
- if (strcmp(plugin->label, "inplace_broken") == 0) {
- data->properties = MODULE_INPLACE_BROKEN;
- } else {
- data->properties = 0;
- }
-
- module = (struct dsp_module*)calloc(1, sizeof(struct dsp_module));
- module->data = data;
- module->instantiate = &instantiate;
- module->connect_port = &connect_port;
- module->get_delay = &get_delay;
- module->run = &run;
- module->deinstantiate = &deinstantiate;
- module->free_module = &free_module;
- module->get_properties = &get_properties;
- module->dump = &dump;
- return module;
-}
-
-static struct dsp_module* modules[MAX_MODULES];
-static struct dsp_module* cras_dsp_module_set_sink_ext_module_val;
-static int num_modules;
-static struct dsp_module* find_module(const char* name) {
- for (int i = 0; i < num_modules; i++) {
- struct data* data = (struct data*)modules[i]->data;
- if (strcmp(name, data->title) == 0)
- return modules[i];
- }
- return NULL;
-}
-
-extern "C" {
-struct dsp_module* cras_dsp_module_load_ladspa(struct plugin* plugin) {
- return NULL;
-}
-struct dsp_module* cras_dsp_module_load_builtin(struct plugin* plugin) {
- struct dsp_module* module = create_mock_module(plugin);
- modules[num_modules++] = module;
- return module;
-}
-void cras_dsp_module_set_sink_ext_module(struct dsp_module* module,
- struct ext_dsp_module* ext_module) {
- cras_dsp_module_set_sink_ext_module_val = module;
-}
-}
-
-namespace {
-
-class DspPipelineTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- num_modules = 0;
- strcpy(filename, FILENAME_TEMPLATE);
- int fd = mkstemp(filename);
- fp = fdopen(fd, "w");
- }
-
- virtual void TearDown() {
- CloseFile();
- unlink(filename);
- }
-
- virtual void CloseFile() {
- if (fp) {
- fclose(fp);
- fp = NULL;
- }
- }
-
- char filename[sizeof(FILENAME_TEMPLATE) + 1];
- FILE* fp;
- struct ext_dsp_module ext_mod;
-};
-
-TEST_F(DspPipelineTestSuite, Simple) {
- const char* content =
- "[M1]\n"
- "library=builtin\n"
- "label=source\n"
- "purpose=capture\n"
- "output_0={audio}\n"
- "output_1=<control>\n"
- "input_2=3.0\n"
- "[M2]\n"
- "library=builtin\n"
- "label=sink\n"
- "purpose=capture\n"
- "input_0=<control>\n"
- "input_1={audio}\n"
- "\n";
- fprintf(fp, "%s", content);
- CloseFile();
-
- struct cras_expr_env env = CRAS_EXPR_ENV_INIT;
- struct ini* ini = cras_dsp_ini_create(filename);
- ASSERT_TRUE(ini);
- struct pipeline* p = cras_dsp_pipeline_create(ini, &env, "capture");
- ASSERT_TRUE(p);
- ASSERT_EQ(0, cras_dsp_pipeline_load(p));
-
- ASSERT_EQ(2, num_modules);
- struct dsp_module* m1 = find_module("m1");
- struct dsp_module* m2 = find_module("m2");
- ASSERT_TRUE(m1);
- ASSERT_TRUE(m2);
-
- ASSERT_EQ(1, cras_dsp_pipeline_get_num_input_channels(p));
- ASSERT_EQ(0, cras_dsp_pipeline_instantiate(p, 48000));
-
- struct data* d1 = (struct data*)m1->data;
- struct data* d2 = (struct data*)m2->data;
-
- /* check m1 */
- ASSERT_STREQ("m1", d1->title);
- ASSERT_EQ(3, d1->nr_ports);
- ASSERT_EQ(PORT_OUTPUT, d1->port_dir[0]);
- ASSERT_EQ(PORT_OUTPUT, d1->port_dir[1]);
- ASSERT_EQ(PORT_INPUT, d1->port_dir[2]);
- ASSERT_EQ(1, d1->instantiate_called);
- ASSERT_EQ(1, d1->get_delay_called);
- ASSERT_EQ(48000, d1->sample_rate);
- ASSERT_EQ(1, d1->connect_port_called[0]);
- ASSERT_EQ(1, d1->connect_port_called[1]);
- ASSERT_EQ(1, d1->connect_port_called[2]);
- ASSERT_TRUE(d1->data_location[0]);
- ASSERT_TRUE(d1->data_location[1]);
- ASSERT_TRUE(d1->data_location[2]);
- ASSERT_EQ(0, d1->run_called);
- ASSERT_EQ(0, d1->deinstantiate_called);
- ASSERT_EQ(0, d1->free_module_called);
- ASSERT_EQ(1, d1->get_properties_called);
-
- /* check m2 */
- ASSERT_STREQ("m2", d2->title);
- ASSERT_EQ(2, d2->nr_ports);
- ASSERT_EQ(PORT_INPUT, d2->port_dir[0]);
- ASSERT_EQ(PORT_INPUT, d2->port_dir[1]);
- ASSERT_EQ(1, d2->instantiate_called);
- ASSERT_EQ(1, d2->get_delay_called);
- ASSERT_EQ(48000, d2->sample_rate);
- ASSERT_EQ(1, d2->connect_port_called[0]);
- ASSERT_EQ(1, d2->connect_port_called[1]);
- ASSERT_TRUE(d2->data_location[0]);
- ASSERT_TRUE(d2->data_location[1]);
- ASSERT_EQ(0, d2->run_called);
- ASSERT_EQ(0, d2->deinstantiate_called);
- ASSERT_EQ(0, d2->free_module_called);
- ASSERT_EQ(1, d2->get_properties_called);
-
- /* check the buffer is shared */
- ASSERT_EQ(d1->data_location[0], d2->data_location[1]);
- ASSERT_EQ(d1->data_location[1], d2->data_location[0]);
- ASSERT_EQ(1, cras_dsp_pipeline_get_peak_audio_buffers(p));
-
- d1->data_location[0][0] = 100;
- cras_dsp_pipeline_run(p, DSP_BUFFER_SIZE);
- ASSERT_EQ(1, d1->run_called);
- ASSERT_EQ(1, d2->run_called);
- ASSERT_EQ(3, d1->input[2]);
- ASSERT_EQ(3, d2->input[0]);
- ASSERT_EQ(100, d2->input[1]);
-
- d1->data_location[0][0] = 1000;
- cras_dsp_pipeline_run(p, DSP_BUFFER_SIZE);
- ASSERT_EQ(2, d1->run_called);
- ASSERT_EQ(2, d2->run_called);
- ASSERT_EQ(3, d1->input[2]);
- ASSERT_EQ(3, d2->input[0]);
- ASSERT_EQ(1000, d2->input[1]);
-
- /* Expect the sink module "m2" is set. */
- cras_dsp_pipeline_set_sink_ext_module(p, &ext_mod);
- struct data* d = (struct data*)cras_dsp_module_set_sink_ext_module_val->data;
- ASSERT_STREQ("m2", d->title);
-
- cras_dsp_pipeline_deinstantiate(p);
- ASSERT_EQ(1, d1->deinstantiate_called);
- ASSERT_EQ(1, d2->deinstantiate_called);
-
- cras_dsp_pipeline_free(p);
- ASSERT_EQ(1, d1->free_module_called);
- ASSERT_EQ(1, d2->free_module_called);
-
- cras_dsp_ini_free(ini);
- cras_expr_env_free(&env);
-
- really_free_module(m1);
- really_free_module(m2);
-}
-
-TEST_F(DspPipelineTestSuite, Complex) {
- /*
- * / --(b)-- 2 --(c)-- \
- * 0 ==(a0, a1)== 1 4 ==(f0,f1)== 5
- * \ --(d)-- 3 --(e)-- /
- *
- *
- * --(g)-- 6 --(h)--
- */
-
- const char* content =
- "[M6]\n"
- "library=builtin\n"
- "label=foo\n"
- "input_0={g}\n"
- "output_1={h}\n"
- "[M5]\n"
- "library=builtin\n"
- "label=sink\n"
- "purpose=playback\n"
- "input_0={f0}\n"
- "input_1={f1}\n"
- "[M4]\n"
- "library=builtin\n"
- "label=foo\n"
- "disable=(equal? output_device \"HDMI\")\n"
- "input_0=3.14\n"
- "input_1={c}\n"
- "output_2={f0}\n"
- "input_3={e}\n"
- "output_4={f1}\n"
- "[M3]\n"
- "library=builtin\n"
- "label=foo\n"
- "input_0={d}\n"
- "output_1={e}\n"
- "[M2]\n"
- "library=builtin\n"
- "label=inplace_broken\n"
- "input_0={b}\n"
- "output_1={c}\n"
- "[M1]\n"
- "library=builtin\n"
- "label=foo\n"
- "disable=(equal? output_device \"USB\")\n"
- "input_0={a0}\n"
- "input_1={a1}\n"
- "output_2={b}\n"
- "output_3={d}\n"
- "[M0]\n"
- "library=builtin\n"
- "label=source\n"
- "purpose=playback\n"
- "output_0={a0}\n"
- "output_1={a1}\n";
- fprintf(fp, "%s", content);
- CloseFile();
-
- struct cras_expr_env env = CRAS_EXPR_ENV_INIT;
- cras_expr_env_install_builtins(&env);
- cras_expr_env_set_variable_string(&env, "output_device", "HDMI");
- cras_expr_env_set_variable_boolean(&env, "swap_lr_disabled", 1);
-
- struct ini* ini = cras_dsp_ini_create(filename);
- ASSERT_TRUE(ini);
- struct pipeline* p = cras_dsp_pipeline_create(ini, &env, "playback");
- ASSERT_TRUE(p);
- ASSERT_EQ(0, cras_dsp_pipeline_load(p));
-
- ASSERT_EQ(5, num_modules); /* one not connected, one disabled */
- struct dsp_module* m0 = find_module("m0");
- struct dsp_module* m1 = find_module("m1");
- struct dsp_module* m2 = find_module("m2");
- struct dsp_module* m3 = find_module("m3");
- struct dsp_module* m5 = find_module("m5");
-
- ASSERT_TRUE(m0);
- ASSERT_TRUE(m1);
- ASSERT_TRUE(m2);
- ASSERT_TRUE(m3);
- ASSERT_FALSE(find_module("m4"));
- ASSERT_TRUE(m5);
- ASSERT_FALSE(find_module("m6"));
-
- ASSERT_EQ(2, cras_dsp_pipeline_get_num_input_channels(p));
- ASSERT_EQ(0, cras_dsp_pipeline_instantiate(p, 48000));
-
- struct data* d0 = (struct data*)m0->data;
- struct data* d1 = (struct data*)m1->data;
- struct data* d2 = (struct data*)m2->data;
- struct data* d3 = (struct data*)m3->data;
- struct data* d5 = (struct data*)m5->data;
-
- /*
- * / --(b)-- 2 --(c)-- \
- * 0 ==(a0, a1)== 1 4 ==(f0,f1)== 5
- * \ --(d)-- 3 --(e)-- /
- *
- *
- * --(g)-- 6 --(h)--
- */
-
- ASSERT_EQ(d0->data_location[0], d1->data_location[0]);
- ASSERT_EQ(d0->data_location[1], d1->data_location[1]);
- ASSERT_EQ(d1->data_location[2], d2->data_location[0]);
- ASSERT_EQ(d1->data_location[3], d3->data_location[0]);
- ASSERT_NE(d2->data_location[0], d2->data_location[1]); /* inplace-broken */
- ASSERT_EQ(d2->data_location[1], d5->data_location[0]); /* m4 is disabled */
- ASSERT_EQ(d3->data_location[1], d5->data_location[1]);
-
- /* need 3 buffers because m2 has inplace-broken flag */
- ASSERT_EQ(3, cras_dsp_pipeline_get_peak_audio_buffers(p));
-
- int16_t* samples = new int16_t[DSP_BUFFER_SIZE];
- fill_test_data(samples, DSP_BUFFER_SIZE);
- cras_dsp_pipeline_apply(p, (uint8_t*)samples, SND_PCM_FORMAT_S16_LE, 100);
- /* the data flow through 2 plugins because m4 is disabled. */
- verify_processed_data(samples, 100, 2);
- delete[] samples;
-
- ASSERT_EQ(1, d1->run_called);
- ASSERT_EQ(1, d3->run_called);
-
- /* check m5 */
- ASSERT_EQ(1, d5->run_called);
- ASSERT_EQ(100, d5->sample_count);
-
- /* Expect the sink module "m5" is set. */
- cras_dsp_pipeline_set_sink_ext_module(p, &ext_mod);
- struct data* d = (struct data*)cras_dsp_module_set_sink_ext_module_val->data;
- ASSERT_STREQ("m5", d->title);
-
- /* re-instantiate */
- ASSERT_EQ(1, d5->instantiate_called);
- ASSERT_EQ(1, d5->get_delay_called);
- ASSERT_EQ(1 + 3 + 5, cras_dsp_pipeline_get_delay(p));
-
- cras_dsp_pipeline_deinstantiate(p);
- cras_dsp_pipeline_instantiate(p, 44100);
-
- ASSERT_EQ(1, d5->deinstantiate_called);
- ASSERT_EQ(2, d5->instantiate_called);
- ASSERT_EQ(2, d5->get_delay_called);
- ASSERT_EQ(1 + 3 + 5, cras_dsp_pipeline_get_delay(p));
- ASSERT_EQ(0, d5->free_module_called);
- ASSERT_EQ(44100, d5->sample_rate);
- ASSERT_EQ(2, d5->connect_port_called[0]);
- ASSERT_EQ(2, d5->connect_port_called[1]);
-
- cras_dsp_pipeline_free(p);
- cras_dsp_ini_free(ini);
- cras_expr_env_free(&env);
-
- really_free_module(m0);
- really_free_module(m1);
- really_free_module(m2);
- really_free_module(m3);
- really_free_module(m5);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/cras_selinux_helper_unittest.c b/cras/src/tests/cras_selinux_helper_unittest.c
deleted file mode 100644
index 64fce142..00000000
--- a/cras/src/tests/cras_selinux_helper_unittest.c
+++ /dev/null
@@ -1,10 +0,0 @@
-// Copyright 2018 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "cras_shm.h"
-
-/* Define a stub cras_selinux_restorecon() which doesn't do anything */
-int cras_selinux_restorecon(const char* pathname) {
- return 0;
-}
diff --git a/cras/src/tests/cras_tm_unittest.cc b/cras/src/tests/cras_tm_unittest.cc
deleted file mode 100644
index 3f5521eb..00000000
--- a/cras/src/tests/cras_tm_unittest.cc
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_tm.h"
-#include "cras_types.h"
-}
-
-namespace {
-
-class TimerTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- tm_ = cras_tm_init();
- ASSERT_TRUE(tm_);
- }
-
- virtual void TearDown() { cras_tm_deinit(tm_); }
-
- struct cras_tm* tm_;
-};
-
-static struct timespec time_now;
-static unsigned int test_cb_called;
-static unsigned int test_cb2_called;
-
-void test_cb(struct cras_timer* t, void* data) {
- test_cb_called++;
-}
-
-void test_cb2(struct cras_timer* t, void* data) {
- test_cb2_called++;
-}
-
-TEST_F(TimerTestSuite, InitNoTimers) {
- struct timespec ts;
- int timers_active;
-
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- EXPECT_FALSE(timers_active);
-}
-
-TEST_F(TimerTestSuite, AddTimer) {
- struct cras_timer* t;
-
- t = cras_tm_create_timer(tm_, 10, test_cb, this);
- EXPECT_TRUE(t);
-}
-
-TEST_F(TimerTestSuite, AddLongTimer) {
- struct timespec ts;
- struct cras_timer* t;
- int timers_active;
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- t = cras_tm_create_timer(tm_, 10000, test_cb, this);
- EXPECT_TRUE(t);
-
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
- EXPECT_EQ(10, ts.tv_sec);
- EXPECT_EQ(0, ts.tv_nsec);
-
- // All timers already fired.
- time_now.tv_sec = 12;
- time_now.tv_nsec = 0;
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(0, ts.tv_nsec);
-
- cras_tm_cancel_timer(tm_, t);
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- EXPECT_FALSE(timers_active);
-}
-
-TEST_F(TimerTestSuite, AddRemoveTimer) {
- struct timespec ts;
- struct cras_timer* t;
- int timers_active;
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- t = cras_tm_create_timer(tm_, 10, test_cb, this);
- EXPECT_TRUE(t);
-
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(10 * 1000000, ts.tv_nsec);
-
- // All timers already fired.
- time_now.tv_sec = 1;
- time_now.tv_nsec = 0;
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(0, ts.tv_nsec);
-
- cras_tm_cancel_timer(tm_, t);
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- EXPECT_FALSE(timers_active);
-}
-
-TEST_F(TimerTestSuite, AddTwoTimers) {
- struct timespec ts;
- struct cras_timer *t1, *t2;
- int timers_active;
- static const unsigned int t1_to = 10;
- static const unsigned int t2_offset = 5;
- static const unsigned int t2_to = 7;
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- t1 = cras_tm_create_timer(tm_, t1_to, test_cb, this);
- ASSERT_TRUE(t1);
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = t2_offset;
- t2 = cras_tm_create_timer(tm_, t2_to, test_cb2, this);
- ASSERT_TRUE(t2);
-
- /* Check That the right calls are made at the right times. */
- test_cb_called = 0;
- test_cb2_called = 0;
- time_now.tv_sec = 0;
- time_now.tv_nsec = t2_to * 1000000 + t2_offset;
- cras_tm_call_callbacks(tm_);
- EXPECT_EQ(0, test_cb_called);
- EXPECT_EQ(1, test_cb2_called);
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = t2_offset;
- t2 = cras_tm_create_timer(tm_, t2_to, test_cb2, this);
- ASSERT_TRUE(t2);
-
- test_cb_called = 0;
- test_cb2_called = 0;
- time_now.tv_sec = 0;
- time_now.tv_nsec = t1_to * 1000000;
- cras_tm_call_callbacks(tm_);
- EXPECT_EQ(1, test_cb_called);
- EXPECT_EQ(1, test_cb2_called);
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- EXPECT_FALSE(timers_active);
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = 0;
- t1 = cras_tm_create_timer(tm_, t1_to, test_cb, this);
- ASSERT_TRUE(t1);
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = t2_offset;
- t2 = cras_tm_create_timer(tm_, t2_to, test_cb2, this);
- ASSERT_TRUE(t2);
-
- /* Timeout values returned are correct. */
- time_now.tv_sec = 0;
- time_now.tv_nsec = 50;
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(t2_to * 1000000 + t2_offset - time_now.tv_nsec, ts.tv_nsec);
-
- cras_tm_cancel_timer(tm_, t2);
-
- time_now.tv_sec = 0;
- time_now.tv_nsec = 60;
- timers_active = cras_tm_get_next_timeout(tm_, &ts);
- ASSERT_TRUE(timers_active);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(t1_to * 1000000 - time_now.tv_nsec, ts.tv_nsec);
- cras_tm_cancel_timer(tm_, t1);
-}
-
-/* Stubs */
-extern "C" {
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = time_now;
- return 0;
-}
-
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/dbus_test.cc b/cras/src/tests/dbus_test.cc
deleted file mode 100644
index b435825d..00000000
--- a/cras/src/tests/dbus_test.cc
+++ /dev/null
@@ -1,734 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "dbus_test.h"
-
-#include <stdlib.h>
-#include <sys/select.h>
-#include <unistd.h>
-
-#include <algorithm>
-
-namespace {
-
-const char kServerAddress[] = "unix:abstract=/org/chromium/DBusTest";
-
-} // namespace
-
-DBusMatch::DBusMatch()
- : message_type_(DBUS_MESSAGE_TYPE_INVALID),
- as_property_dictionary_(false),
- send_reply_(false),
- send_error_(false),
- expect_serial_(false),
- matched_(false) {}
-
-DBusMatch& DBusMatch::WithString(std::string value) {
- Arg arg;
- arg.type = DBUS_TYPE_STRING;
- arg.array = false;
- arg.string_value = value;
-
- if (send_reply_)
- reply_args_.push_back(arg);
- else
- args_.push_back(arg);
- return *this;
-}
-
-DBusMatch& DBusMatch::WithUnixFd(int value) {
- Arg arg;
- arg.type = DBUS_TYPE_UNIX_FD;
- arg.array = false;
- arg.int_value = value;
-
- if (send_reply_)
- reply_args_.push_back(arg);
- else
- args_.push_back(arg);
- return *this;
-}
-
-DBusMatch& DBusMatch::WithObjectPath(std::string value) {
- Arg arg;
- arg.type = DBUS_TYPE_OBJECT_PATH;
- arg.array = false;
- arg.string_value = value;
-
- if (send_reply_)
- reply_args_.push_back(arg);
- else
- args_.push_back(arg);
- return *this;
-}
-
-DBusMatch& DBusMatch::WithArrayOfStrings(std::vector<std::string> values) {
- Arg arg;
- arg.type = DBUS_TYPE_STRING;
- arg.array = true;
- arg.string_values = values;
-
- if (send_reply_)
- reply_args_.push_back(arg);
- else
- args_.push_back(arg);
- return *this;
-}
-
-DBusMatch& DBusMatch::WithArrayOfObjectPaths(std::vector<std::string> values) {
- Arg arg;
- arg.type = DBUS_TYPE_OBJECT_PATH;
- arg.array = true;
- arg.string_values = values;
-
- if (send_reply_)
- reply_args_.push_back(arg);
- else
- args_.push_back(arg);
- return *this;
-}
-
-DBusMatch& DBusMatch::WithNoMoreArgs() {
- Arg arg;
- arg.type = DBUS_TYPE_INVALID;
-
- args_.push_back(arg);
- return *this;
-}
-
-DBusMatch& DBusMatch::AsPropertyDictionary() {
- as_property_dictionary_ = true;
- return *this;
-}
-
-DBusMatch& DBusMatch::SendReply() {
- send_reply_ = true;
- expect_serial_ = true;
- return *this;
-}
-
-DBusMatch& DBusMatch::SendError(std::string error_name,
- std::string error_message) {
- send_error_ = true;
- error_name_ = error_name;
- error_message_ = error_message;
- expect_serial_ = true;
- return *this;
-}
-
-DBusMatch& DBusMatch::SendReplyNoWait() {
- send_reply_ = true;
- expect_serial_ = false;
- return *this;
-}
-
-DBusMatch& DBusMatch::Send() {
- DBusMessage* message;
- if (message_type_ == DBUS_MESSAGE_TYPE_SIGNAL)
- message = dbus_message_new_signal(path_.c_str(), interface_.c_str(),
- member_.c_str());
- else if (message_type_ == DBUS_MESSAGE_TYPE_METHOD_CALL)
- message = dbus_message_new_method_call(NULL, path_.c_str(),
- interface_.c_str(), member_.c_str());
- else
- return *this;
-
- AppendArgsToMessage(message, &args_);
- SendMessage(conn_, message);
-
- dbus_message_unref(message);
-
- return *this;
-}
-
-void DBusMatch::ExpectMethodCall(std::string path,
- std::string interface,
- std::string method) {
- message_type_ = DBUS_MESSAGE_TYPE_METHOD_CALL;
- path_ = path;
- interface_ = interface;
- member_ = method;
-}
-
-void DBusMatch::CreateSignal(DBusConnection* conn,
- std::string path,
- std::string interface,
- std::string signal_name) {
- message_type_ = DBUS_MESSAGE_TYPE_SIGNAL;
- path_ = path;
- interface_ = interface;
- member_ = signal_name;
-
- conn_ = conn;
- expect_serial_ = true;
- matched_ = true;
-}
-
-void DBusMatch::CreateMessageCall(DBusConnection* conn,
- std::string path,
- std::string interface,
- std::string method_name) {
- message_type_ = DBUS_MESSAGE_TYPE_METHOD_CALL;
- path_ = path;
- interface_ = interface;
- member_ = method_name;
-
- conn_ = conn;
- expect_serial_ = true;
- matched_ = true;
-}
-
-bool DBusMatch::MatchMessageArgs(DBusMessage* message, std::vector<Arg>* args) {
- DBusMessageIter iter;
- dbus_message_iter_init(message, &iter);
- for (std::vector<Arg>::iterator it = args->begin(); it != args->end(); ++it) {
- Arg& arg = *it;
-
- int type = dbus_message_iter_get_arg_type(&iter);
- if (type != arg.type)
- return false;
-
- if (arg.type == DBUS_TYPE_STRING || arg.type == DBUS_TYPE_OBJECT_PATH) {
- const char* str_value;
- dbus_message_iter_get_basic(&iter, &str_value);
- if (strcmp(str_value, arg.string_value.c_str()) != 0)
- return false;
- }
- // TODO(keybuk): additional argument types
-
- dbus_message_iter_next(&iter);
- }
-
- return true;
-}
-
-void DBusMatch::AppendArgsToMessage(DBusMessage* message,
- std::vector<Arg>* args) {
- DBusMessageIter message_iter;
- DBusMessageIter dict_array_iter;
- DBusMessageIter struct_iter;
- DBusMessageIter iter;
-
- if (as_property_dictionary_) {
- dbus_message_iter_init_append(message, &message_iter);
- dbus_message_iter_open_container(&message_iter, DBUS_TYPE_ARRAY, "{sv}",
- &dict_array_iter);
- } else {
- dbus_message_iter_init_append(message, &iter);
- }
-
- for (std::vector<Arg>::iterator it = args->begin(); it != args->end(); ++it) {
- Arg& arg = *it;
-
- if (as_property_dictionary_) {
- dbus_message_iter_open_container(&dict_array_iter, DBUS_TYPE_DICT_ENTRY,
- NULL, &struct_iter);
-
- const char* str_value = arg.string_value.c_str();
- dbus_message_iter_append_basic(&struct_iter, arg.type, &str_value);
-
- arg = *(++it);
- }
-
- const char *array_type, *element_type;
- switch (arg.type) {
- case DBUS_TYPE_STRING:
- array_type = DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_STRING_AS_STRING;
- element_type = DBUS_TYPE_STRING_AS_STRING;
- break;
- case DBUS_TYPE_OBJECT_PATH:
- array_type = DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_OBJECT_PATH_AS_STRING;
- element_type = DBUS_TYPE_OBJECT_PATH_AS_STRING;
- break;
- case DBUS_TYPE_UNIX_FD:
- array_type = DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_UNIX_FD_AS_STRING;
- element_type = DBUS_TYPE_UNIX_FD_AS_STRING;
- break;
- default:
- abort();
- // TODO(keybuk): additional argument types
- }
-
- if (as_property_dictionary_) {
- dbus_message_iter_open_container(&struct_iter, DBUS_TYPE_VARIANT,
- arg.array ? array_type : element_type,
- &iter);
- }
-
- DBusMessageIter array_iter;
- if (arg.array) {
- dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, element_type,
- &array_iter);
-
- if (arg.type == DBUS_TYPE_STRING || arg.type == DBUS_TYPE_OBJECT_PATH) {
- for (std::vector<std::string>::const_iterator vit =
- arg.string_values.begin();
- vit != arg.string_values.end(); ++vit) {
- const char* str_value = vit->c_str();
- dbus_message_iter_append_basic(&array_iter, arg.type, &str_value);
- }
- }
- // TODO(keybuk): additional element types
-
- dbus_message_iter_close_container(&iter, &array_iter);
- } else {
- if (arg.type == DBUS_TYPE_STRING || arg.type == DBUS_TYPE_OBJECT_PATH) {
- const char* str_value = arg.string_value.c_str();
- dbus_message_iter_append_basic(&iter, arg.type, &str_value);
- } else if (arg.type == DBUS_TYPE_UNIX_FD) {
- dbus_message_iter_append_basic(&iter, arg.type, &arg.int_value);
- }
- // TODO(keybuk): additional argument types
- }
-
- if (as_property_dictionary_) {
- dbus_message_iter_close_container(&struct_iter, &iter);
- dbus_message_iter_close_container(&dict_array_iter, &struct_iter);
- }
- }
-
- if (as_property_dictionary_)
- dbus_message_iter_close_container(&message_iter, &dict_array_iter);
-}
-
-void DBusMatch::SendMessage(DBusConnection* conn, DBusMessage* message) {
- dbus_bool_t success;
- dbus_uint32_t serial;
- success = dbus_connection_send(conn, message, &serial);
-
- if (success && expect_serial_)
- expected_serials_.push_back(serial);
-}
-
-bool DBusMatch::HandleServerMessage(DBusConnection* conn,
- DBusMessage* message) {
- // Make sure we're expecting a method call or signal of this name
- if (message_type_ == DBUS_MESSAGE_TYPE_METHOD_CALL &&
- !dbus_message_is_method_call(message, interface_.c_str(),
- member_.c_str()))
- return false;
- else if (message_type_ == DBUS_MESSAGE_TYPE_SIGNAL &&
- !dbus_message_is_signal(message, interface_.c_str(),
- member_.c_str()))
- return false;
-
- // Make sure the path is what we expected.
- if (path_.length() &&
- strcmp(path_.c_str(), dbus_message_get_path(message)) != 0)
- return false;
-
- // And the arguments.
- if (!MatchMessageArgs(message, &args_))
- return false;
-
- // Handle any actions.
- matched_ = true;
- if (send_reply_ || send_error_) {
- // Send out the reply
- DBusMessage* reply = NULL;
- if (send_reply_)
- reply = dbus_message_new_method_return(message);
- else if (send_error_)
- reply = dbus_message_new_error(message, error_name_.c_str(),
- error_message_.c_str());
-
- AppendArgsToMessage(reply, &reply_args_);
- SendMessage(conn, reply);
-
- dbus_message_unref(reply);
- }
-
- return true;
-}
-
-bool DBusMatch::HandleClientMessage(DBusConnection* conn,
- DBusMessage* message) {
- // From the client side we check whether the message has a serial number
- // we generated on our server side, and if so, remove it from the list of
- // those we're expecting to see.
- for (std::vector<dbus_uint32_t>::iterator it = expected_serials_.begin();
- it != expected_serials_.end(); ++it) {
- if (*it == dbus_message_get_serial(message)) {
- expected_serials_.erase(it);
- return true;
- }
- }
-
- return false;
-}
-
-bool DBusMatch::Complete() {
- return matched_ && expected_serials_.size() == 0;
-}
-
-DBusTest::DBusTest()
- : conn_(NULL), server_(NULL), server_conn_(NULL), dispatch_(false) {}
-
-DBusTest::~DBusTest() {}
-
-DBusMatch& DBusTest::ExpectMethodCall(std::string path,
- std::string interface,
- std::string method) {
- DBusMatch match;
- match.ExpectMethodCall(path, interface, method);
- pthread_mutex_lock(&mutex_);
- matches_.push_back(match);
- DBusMatch& ref = matches_.back();
- pthread_mutex_unlock(&mutex_);
- return ref;
-}
-
-DBusMatch& DBusTest::CreateSignal(std::string path,
- std::string interface,
- std::string signal_name) {
- DBusMatch match;
- match.CreateSignal(server_conn_, path, interface, signal_name);
- pthread_mutex_lock(&mutex_);
- matches_.push_back(match);
- DBusMatch& ref = matches_.back();
- pthread_mutex_unlock(&mutex_);
- return ref;
-}
-
-DBusMatch& DBusTest::CreateMessageCall(std::string path,
- std::string interface,
- std::string signal_name) {
- DBusMatch match;
- match.CreateMessageCall(server_conn_, path, interface, signal_name);
- pthread_mutex_lock(&mutex_);
- matches_.push_back(match);
- DBusMatch& ref = matches_.back();
- pthread_mutex_unlock(&mutex_);
- return ref;
-}
-
-void DBusTest::WaitForMatches() {
- for (;;) {
- pthread_mutex_lock(&mutex_);
- size_t incomplete_matches = 0;
- for (std::vector<DBusMatch>::iterator it = matches_.begin();
- it != matches_.end(); ++it) {
- DBusMatch& match = *it;
- if (!match.Complete())
- ++incomplete_matches;
- }
- pthread_mutex_unlock(&mutex_);
-
- if (!incomplete_matches)
- break;
-
- // Fish a message from the queue.
- DBusMessage* message;
- while ((message = dbus_connection_borrow_message(conn_)) == NULL)
- dbus_connection_read_write(conn_, -1);
-
- // Allow matches to verify the serial of the message.
- pthread_mutex_lock(&mutex_);
- for (std::vector<DBusMatch>::iterator it = matches_.begin();
- it != matches_.end(); ++it) {
- DBusMatch& match = *it;
-
- if (match.HandleClientMessage(conn_, message))
- break;
- }
- pthread_mutex_unlock(&mutex_);
-
- // Throw it back and dispatch.
- dbus_connection_return_message(conn_, message);
- dbus_connection_dispatch(conn_);
- }
-
- pthread_mutex_lock(&mutex_);
- matches_.erase(matches_.begin(), matches_.end());
- pthread_mutex_unlock(&mutex_);
-}
-
-void DBusTest::SetUp() {
- dbus_threads_init_default();
-
- // Create the D-Bus server that will accept a connection for us, since
- // there's no "just give me a socketpair" option in libdbus.
- server_ = dbus_server_listen(kServerAddress, NULL);
- ASSERT_TRUE(server_ != NULL);
-
- dbus_server_set_new_connection_function(server_, NewConnectionThunk, this,
- NULL);
-
- dbus_bool_t success;
- success = dbus_server_set_watch_functions(
- server_, AddWatchThunk, RemoveWatchThunk, WatchToggledThunk, this, NULL);
- ASSERT_TRUE(success);
-
- success = dbus_server_set_timeout_functions(server_, AddTimeoutThunk,
- RemoveTimeoutThunk,
- TimeoutToggledThunk, this, NULL);
- ASSERT_TRUE(success);
-
- // Open a connection to our server, this returns the "client" side of the
- // connection.
- conn_ = dbus_connection_open_private(kServerAddress, NULL);
- ASSERT_TRUE(conn_ != NULL);
-
- // The "server" side of the connection comes from the NewConnection method
- // we set above. Dispatch until we have it.
- while (!server_conn_)
- DispatchOnce();
-
- // Now we set off "main loop" in the background to dispatch until the
- // client is disconnected by the TearDown method.
- int r;
- r = pthread_mutex_init(&mutex_, NULL);
- ASSERT_EQ(0, r);
-
- dispatch_ = true;
- r = pthread_create(&thread_id_, NULL, DispatchLoopThunk, this);
- ASSERT_EQ(0, r);
-}
-
-void DBusTest::TearDown() {
- WaitForMatches();
-
- // Close the client end of the connection, this will result in a signal
- // within the dispatch loop of the server.
- if (conn_) {
- dbus_connection_flush(conn_);
- dbus_connection_close(conn_);
- dbus_connection_unref(conn_);
- conn_ = NULL;
- }
-
- // Join the thread and wait for it to finish dispatch.
- if (dispatch_)
- pthread_join(thread_id_, NULL);
- pthread_mutex_destroy(&mutex_);
-
- // Clean up the server end of the connection and the server itself.
- if (server_conn_) {
- dbus_connection_flush(server_conn_);
- dbus_connection_close(server_conn_);
- dbus_connection_unref(server_conn_);
- server_conn_ = NULL;
- }
-
- dbus_server_disconnect(server_);
- dbus_server_unref(server_);
- server_ = NULL;
-
- dbus_shutdown();
-}
-
-void DBusTest::NewConnectionThunk(DBusServer* server,
- DBusConnection* conn,
- void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- test->NewConnection(server, conn);
-}
-
-void DBusTest::NewConnection(DBusServer* server, DBusConnection* conn) {
- ASSERT_TRUE(server_conn_ == NULL);
-
- dbus_bool_t success;
- success = dbus_connection_set_watch_functions(
- conn, AddWatchThunk, RemoveWatchThunk, WatchToggledThunk, this, NULL);
- ASSERT_TRUE(success);
-
- success = dbus_connection_set_timeout_functions(
- conn, AddTimeoutThunk, RemoveTimeoutThunk, TimeoutToggledThunk, this,
- NULL);
- ASSERT_TRUE(success);
-
- success = dbus_connection_add_filter(conn, HandleMessageThunk, this, NULL);
- ASSERT_TRUE(success);
-
- server_conn_ = conn;
- dbus_connection_ref(server_conn_);
-}
-
-dbus_bool_t DBusTest::AddWatchThunk(DBusWatch* watch, void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- return test->AddWatch(watch);
-}
-
-dbus_bool_t DBusTest::AddWatch(DBusWatch* watch) {
- watches_.push_back(watch);
- return TRUE;
-}
-
-void DBusTest::RemoveWatchThunk(DBusWatch* watch, void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- test->RemoveWatch(watch);
-}
-
-void DBusTest::RemoveWatch(DBusWatch* watch) {
- std::vector<DBusWatch*>::iterator it =
- find(watches_.begin(), watches_.end(), watch);
- if (it != watches_.end())
- watches_.erase(it);
-}
-
-void DBusTest::WatchToggledThunk(DBusWatch* watch, void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- test->WatchToggled(watch);
-}
-
-void DBusTest::WatchToggled(DBusWatch* watch) {}
-
-dbus_bool_t DBusTest::AddTimeoutThunk(DBusTimeout* timeout, void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- return test->AddTimeout(timeout);
-}
-
-dbus_bool_t DBusTest::AddTimeout(DBusTimeout* timeout) {
- timeouts_.push_back(timeout);
- return TRUE;
-}
-
-void DBusTest::RemoveTimeoutThunk(DBusTimeout* timeout, void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- test->RemoveTimeout(timeout);
-}
-
-void DBusTest::RemoveTimeout(DBusTimeout* timeout) {
- std::vector<DBusTimeout*>::iterator it =
- find(timeouts_.begin(), timeouts_.end(), timeout);
- if (it != timeouts_.end())
- timeouts_.erase(it);
-}
-
-void DBusTest::TimeoutToggledThunk(DBusTimeout* timeout, void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- test->TimeoutToggled(timeout);
-}
-
-void DBusTest::TimeoutToggled(DBusTimeout* timeout) {}
-
-DBusHandlerResult DBusTest::HandleMessageThunk(DBusConnection* conn,
- DBusMessage* message,
- void* data) {
- DBusTest* test = static_cast<DBusTest*>(data);
- return test->HandleMessage(conn, message);
-}
-
-DBusHandlerResult DBusTest::HandleMessage(DBusConnection* conn,
- DBusMessage* message) {
- if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
- dispatch_ = false;
- return DBUS_HANDLER_RESULT_HANDLED;
- }
-
- pthread_mutex_lock(&mutex_);
- for (std::vector<DBusMatch>::iterator it = matches_.begin();
- it != matches_.end(); ++it) {
- DBusMatch& match = *it;
-
- if (match.HandleServerMessage(conn, message)) {
- pthread_mutex_unlock(&mutex_);
- return DBUS_HANDLER_RESULT_HANDLED;
- }
- }
- pthread_mutex_unlock(&mutex_);
-
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-void* DBusTest::DispatchLoopThunk(void* ptr) {
- DBusTest* test = static_cast<DBusTest*>(ptr);
- return test->DispatchLoop();
-}
-
-void* DBusTest::DispatchLoop() {
- while (dispatch_)
- DispatchOnce();
-
- return NULL;
-}
-
-void DBusTest::DispatchOnce() {
- fd_set readfds, writefds;
- int nfds = 0;
- int r;
-
- // Ideally we'd just use dbus_connection_read_write_dispatch() here, but
- // we have to deal with both the server itself and its connection, so we
- // have to do it all by hand.
- FD_ZERO(&readfds);
- FD_ZERO(&writefds);
-
- for (std::vector<DBusWatch*>::iterator it = watches_.begin();
- it != watches_.end(); ++it) {
- DBusWatch* watch = *it;
-
- if (!dbus_watch_get_enabled(watch))
- continue;
-
- int fd = dbus_watch_get_unix_fd(watch);
- if (fd + 1 > nfds)
- nfds = fd + 1;
-
- unsigned int flags = dbus_watch_get_flags(watch);
- if (flags & DBUS_WATCH_READABLE)
- FD_SET(fd, &readfds);
- if (flags & DBUS_WATCH_WRITABLE)
- FD_SET(fd, &writefds);
- }
-
- // Only block in select for the interval of the smallest timeout; this
- // isn't quite right according to the D-Bus spec, since the interval is
- // supposed to be since the time the timeout was added or toggled, but
- // it's good enough for the purposes of testing.
- DBusTimeout* earliest_timeout = NULL;
- struct timeval timeval;
-
- for (std::vector<DBusTimeout*>::iterator it = timeouts_.begin();
- it != timeouts_.end(); ++it) {
- DBusTimeout* timeout = *it;
-
- if (!dbus_timeout_get_enabled(timeout))
- continue;
-
- if (!earliest_timeout || (dbus_timeout_get_interval(timeout) <
- dbus_timeout_get_interval(earliest_timeout)))
- earliest_timeout = timeout;
- }
-
- if (earliest_timeout) {
- int interval = dbus_timeout_get_interval(earliest_timeout);
- timeval.tv_sec = interval / 1000;
- timeval.tv_usec = (interval % 1000) * 1000;
-
- r = select(nfds, &readfds, &writefds, NULL, &timeval);
- } else {
- r = select(nfds, &readfds, &writefds, NULL, NULL);
- }
-
- ASSERT_LE(0, r);
-
- // Handle the timeout if we didn't poll for anything else.
- if (r == 0 && earliest_timeout)
- dbus_timeout_handle(earliest_timeout);
-
- // Handle the watches, use a copy of the vector since a watch handler
- // might remove other watches in the vector.
- std::vector<DBusWatch*> immutable_watches = watches_;
- for (std::vector<DBusWatch*>::iterator it = immutable_watches.begin();
- it != immutable_watches.end(); ++it) {
- DBusWatch* watch = *it;
-
- int fd = dbus_watch_get_unix_fd(watch);
- unsigned int flags = 0;
-
- if (FD_ISSET(fd, &readfds))
- flags |= DBUS_WATCH_READABLE;
- if (FD_ISSET(fd, &writefds))
- flags |= DBUS_WATCH_WRITABLE;
-
- if (flags)
- dbus_watch_handle(watch, flags);
- }
-
- // Dispatch data on the server-side of the connection.
- while (server_conn_ &&
- dbus_connection_dispatch(server_conn_) == DBUS_DISPATCH_DATA_REMAINS)
- ;
-}
diff --git a/cras/src/tests/dbus_test.h b/cras/src/tests/dbus_test.h
deleted file mode 100644
index d266037b..00000000
--- a/cras/src/tests/dbus_test.h
+++ /dev/null
@@ -1,325 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef CRAS_DBUS_TEST_H_
-#define CRAS_DBUS_TEST_H_
-
-#include <dbus/dbus.h>
-#include <gtest/gtest.h>
-#include <pthread.h>
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-/* DBusTest, and the related DBusMatch class, are used to provide a
- * GMock-like experience for testing D-Bus code within cras.
- *
- * It works by providing a connection to a private D-Bus Server for use
- * by code you intend to test. Before making calls, you set expectations
- * of method calls that the server should receive and reply to, or
- * instructions for the server to send signals that your connection
- * should receive and handle.
- *
- * The code style is similar to GMock for purposes of familiarity.
- *
- * Examples
- * --------
- *
- * To create a test suite class implementing a SetUp and TearDown method,
- * be sure to call the base-class methods at the appropriate time.
- *
- * class ExampleTestSuite : public DBusTest {
- * virtual void SetUp() {
- * DBusTest::SetUp();
- * // your setup code here
- * }
- *
- * virtual void TearDown() {
- * // your teardown code here
- * DBusTest::TearDown();
- * }
- * };
- *
- * To expect a method call to be made against the server; matching the
- * object path, interface and method name and then generating an empty
- * reply. The test code ensures that the reply is received during the
- * TearDown method.
- *
- * TEST_F(ExampleTestSuite, ExampleTest) {
- * ExpectMethodCall("/object/path", "object.Interface", "MethodName")
- * .SendReply();
- *
- * // code to generate the method call here
- * }
- *
- * Due to the asynchronous nature of D-Bus, if you need to check some
- * state, it's not enough to immediately follow the code that generates
- * the method call. You must instead ensure that all expectations up to
- * that point have been met:
- *
- * TEST_F(ExampleTestSuite, ExampleTest) {
- * ExpectMethodCall("/object/path", "object.Interface", "MethodName")
- * .SendReply();
- *
- * // code to generate the method call here
- *
- * WaitForMatches();
- *
- * // code to examine state here
- * }
- *
- * To verify the arguments to method calls, place .With*() calls before
- * sending the reply:
- *
- * ExpectMethodCall("/object/path", "object.Interface", "MethodName")
- * .WithObjectPath("/arg0/object/path")
- * .WithString("arg1")
- * .WithString("arg2")
- * .SendReply();
- *
- * Normally additional arguments are permitted, since most D-Bus services
- * don't go out of their way to check they aren't provided; to verify
- * there are no more arguments use .WithNoMoreArgs():
- *
- * ExpectMethodCall("/object/path", "object.Interface", "MethodName")
- * .WithString("arg0")
- * .WithNoMoreArgs()
- * .SendReply();
- *
- * To append arguments to the reply, place .With*() calls after the
- * instruction to send the reply:
- *
- * ExpectMethodCall("/object/path", "object.Interface", "MethodName")
- * .SendReply()
- * .WithString("arg0")
- * .WithObjectPath("/arg1/object/path");
- *
- * Property dictionaries are sufficiently difficult to deal with that
- * there is special handling for them; to append one to the reply use
- * .AsPropertyDictionary() and follow with alternate .WithString() and
- * other .With*() calls for each property:
- *
- * ExpectMethodCall("/object/path", "object.Interface", "GetProperties")
- * .SendReply()
- * .AsPropertyDictionary()
- * .WithString("Keyword")
- * .WithObjectPath("/value/of/keyword");
- *
- * To reply with an error use .SendError() instead of .SendReply(),
- * passing the error name and message
- *
- * ExpectMethodCall("/object/path", "object.Interface", "MethodName")
- * .SendError("some.error.Name", "Message for error");
- *
- * In some cases (notably "AddMatch" method calls) the method call will
- * be handled by libdbus itself and the mechanism DBusTest uses to verify
- * that the reply is recieved does not work. In which case you need to use
- * .SendReplyNoWait() instead.
- *
- * ExpectMethodCall("", DBUS_INTERFACE_DBUS, "AddMatch")
- * .SendReplyNoWait();
- *
- * Sending signals from the server side is very similar:
- *
- * CreateSignal("/object/path", "object.Interface", "SignalName")
- * .WithString("arg0")
- * .WithObjectPat("/arg1/object/path")
- * .Send();
- *
- * Create messages from server side:
- * CreateMessageCall("/object/path". "object.Interface", "MethodName")
- * .WithString("arg0")
- * .WithUnixFd(arg1)
- * .Send();
- *
- * The TearDown() method will verify that it is received by the client,
- * use WaitForMatches() to force verification earlier in order to check
- * state.
- */
-
-class DBusTest;
-
-class DBusMatch {
- public:
- DBusMatch();
-
- struct Arg {
- int type;
- bool array;
- std::string string_value;
- int int_value;
- std::vector<std::string> string_values;
- };
-
- // Append arguments to a match.
- DBusMatch& WithString(std::string value);
- DBusMatch& WithUnixFd(int value);
- DBusMatch& WithObjectPath(std::string value);
- DBusMatch& WithArrayOfStrings(std::vector<std::string> values);
- DBusMatch& WithArrayOfObjectPaths(std::vector<std::string> values);
- DBusMatch& WithNoMoreArgs();
-
- // Indicates that all arguments in either the method call or reply
- // should be wrapped into a property dictionary with a string for keys
- // and a variant for the data.
- DBusMatch& AsPropertyDictionary();
-
- // Send a reply to a method call and wait for it to be received by the
- // client; may be followed by methods to append arguments.
- DBusMatch& SendReply();
-
- // Send an error in reply to a method call and wait for it to be received
- // by the client; may also be followed by methods to append arguments.
- DBusMatch& SendError(std::string error_name, std::string error_message);
-
- // Send a reply to a method call but do not wait for it to be received;
- // mostly needed for internal D-Bus messages.
- DBusMatch& SendReplyNoWait();
-
- // Send a created signal.
- DBusMatch& Send();
-
- private:
- friend class DBusTest;
-
- // Methods used by DBusTest after constructing the DBusMatch instance
- // to set the type of match.
- void ExpectMethodCall(std::string path,
- std::string interface,
- std::string method);
-
- void CreateSignal(DBusConnection* conn,
- std::string path,
- std::string interface,
- std::string signal_name);
-
- void CreateMessageCall(DBusConnection* conn,
- std::string path,
- std::string interface,
- std::string signal_name);
-
- // Determine whether a message matches a set of arguments.
- bool MatchMessageArgs(DBusMessage* message, std::vector<Arg>* args);
-
- // Append a set of arguments to a message.
- void AppendArgsToMessage(DBusMessage* message, std::vector<Arg>* args);
-
- // Send a message on a connection.
- void SendMessage(DBusConnection* conn, DBusMessage* message);
-
- // Handle a message received by the server connection.
- bool HandleServerMessage(DBusConnection* conn, DBusMessage* message);
-
- // Handle a message received by the client connection.
- bool HandleClientMessage(DBusConnection* conn, DBusMessage* message);
-
- // Verify whether the match is complete.
- bool Complete();
-
- int message_type_;
- std::string path_;
- std::string interface_;
- std::string member_;
-
- bool as_property_dictionary_;
- std::vector<Arg> args_;
-
- DBusConnection* conn_;
-
- bool send_reply_;
- std::vector<Arg> reply_args_;
-
- bool send_error_;
- std::string error_name_;
- std::string error_message_;
-
- bool expect_serial_;
- std::vector<dbus_uint32_t> expected_serials_;
-
- bool matched_;
-};
-
-class DBusTest : public ::testing::Test {
- public:
- DBusTest();
- virtual ~DBusTest();
-
- protected:
- // Connection to the D-Bus server, this may be used during tests as the
- // "bus" connection, all messages go to and from the internal D-Bus server.
- DBusConnection* conn_;
-
- // Expect a method call to be received by the server.
- DBusMatch& ExpectMethodCall(std::string path,
- std::string interface,
- std::string method);
-
- // Send a signal from the client to the server.
- DBusMatch& CreateSignal(std::string path,
- std::string interface,
- std::string signal_name);
-
- // Send a message from the client to the server.
- DBusMatch& CreateMessageCall(std::string path,
- std::string interface,
- std::string signal_name);
-
- // Wait for all matches created by Expect*() or Create*() methods to
- // be complete.
- void WaitForMatches();
-
- // When overriding be sure to call these parent methods to allow the
- // D-Bus server thread to be cleanly initialized and shut down.
- virtual void SetUp();
- virtual void TearDown();
-
- private:
- DBusServer* server_;
- DBusConnection* server_conn_;
-
- std::vector<DBusWatch*> watches_;
- std::vector<DBusTimeout*> timeouts_;
-
- pthread_t thread_id_;
- pthread_mutex_t mutex_;
- bool dispatch_;
-
- std::vector<DBusMatch> matches_;
-
- static void NewConnectionThunk(DBusServer* server,
- DBusConnection* conn,
- void* data);
- void NewConnection(DBusServer* server, DBusConnection* conn);
-
- static dbus_bool_t AddWatchThunk(DBusWatch* watch, void* data);
- dbus_bool_t AddWatch(DBusWatch* watch);
-
- static void RemoveWatchThunk(DBusWatch* watch, void* data);
- void RemoveWatch(DBusWatch* watch);
-
- static void WatchToggledThunk(DBusWatch* watch, void* data);
- void WatchToggled(DBusWatch* watch);
-
- static dbus_bool_t AddTimeoutThunk(DBusTimeout* timeout, void* data);
- dbus_bool_t AddTimeout(DBusTimeout* timeout);
-
- static void RemoveTimeoutThunk(DBusTimeout* timeout, void* data);
- void RemoveTimeout(DBusTimeout* timeout);
-
- static void TimeoutToggledThunk(DBusTimeout* timeout, void* data);
- void TimeoutToggled(DBusTimeout* timeout);
-
- static DBusHandlerResult HandleMessageThunk(DBusConnection* conn,
- DBusMessage* message,
- void* data);
- DBusHandlerResult HandleMessage(DBusConnection* conn, DBusMessage* message);
-
- static void* DispatchLoopThunk(void* ptr);
- void* DispatchLoop();
- void DispatchOnce();
-};
-
-#endif /* CRAS_DBUS_TEST_H_ */
diff --git a/cras/src/tests/dev_io_stubs.cc b/cras/src/tests/dev_io_stubs.cc
deleted file mode 100644
index d97dde50..00000000
--- a/cras/src/tests/dev_io_stubs.cc
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright 2017 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <stdint.h>
-#include <stdio.h>
-#include <time.h>
-
-#include <algorithm>
-#include <memory>
-
-extern "C" {
-#include "cras_iodev.h"
-#include "cras_rstream.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "dev_stream.h"
-#include "utlist.h"
-}
-
-#include "dev_io_stubs.h"
-
-ShmPtr create_shm(size_t cb_threshold) {
- uint32_t frame_bytes = 4;
- uint32_t used_size = cb_threshold * 2 * frame_bytes;
-
- ShmPtr shm(reinterpret_cast<struct cras_audio_shm*>(
- calloc(1, sizeof(struct cras_audio_shm))),
- destroy_shm);
-
- shm->header = reinterpret_cast<struct cras_audio_shm_header*>(
- calloc(1, sizeof(struct cras_audio_shm_header)));
- shm->header->config.used_size = used_size;
- shm->header->config.frame_bytes = frame_bytes;
- shm->config = shm->header->config;
-
- uint32_t samples_size = cras_shm_calculate_samples_size(used_size);
- shm->samples = reinterpret_cast<uint8_t*>(calloc(1, samples_size));
- shm->samples_info.length = samples_size;
- return shm;
-}
-
-void destroy_shm(struct cras_audio_shm* shm) {
- free(shm->header);
- free(shm->samples);
- free(shm);
-}
-
-RstreamPtr create_rstream(cras_stream_id_t id,
- CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- const cras_audio_format* format,
- cras_audio_shm* shm) {
- RstreamPtr rstream(
- reinterpret_cast<cras_rstream*>(calloc(1, sizeof(cras_rstream))), free);
- rstream->stream_id = id;
- rstream->direction = direction;
- rstream->fd = RSTREAM_FAKE_POLL_FD;
- rstream->buffer_frames = cb_threshold * 2;
- rstream->cb_threshold = cb_threshold;
- rstream->shm = shm;
- rstream->format = *format;
- cras_frames_to_time(cb_threshold, rstream->format.frame_rate,
- &rstream->sleep_interval_ts);
- return rstream;
-}
-
-DevStreamPtr create_dev_stream(unsigned int dev_id, cras_rstream* rstream) {
- DevStreamPtr dstream(
- reinterpret_cast<dev_stream*>(calloc(1, sizeof(dev_stream))), free);
- dstream->dev_id = dev_id;
- dstream->stream = rstream;
- dstream->dev_rate = rstream->format.frame_rate;
- dstream->is_running = true;
- return dstream;
-}
-
-StreamPtr create_stream(cras_stream_id_t id,
- unsigned int dev_id,
- CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- const cras_audio_format* format) {
- ShmPtr shm = create_shm(cb_threshold);
- RstreamPtr rstream =
- create_rstream(1, CRAS_STREAM_INPUT, cb_threshold, format, shm.get());
- DevStreamPtr dstream = create_dev_stream(1, rstream.get());
- StreamPtr s(
- new Stream(std::move(shm), std::move(rstream), std::move(dstream)));
- return s;
-}
-
-void AddFakeDataToStream(Stream* stream, unsigned int frames) {
- cras_shm_check_write_overrun(stream->rstream->shm);
- cras_shm_buffer_written(stream->rstream->shm, frames);
-}
-
-int delay_frames_stub(const struct cras_iodev* iodev) {
- return 0;
-}
-
-IonodePtr create_ionode(CRAS_NODE_TYPE type) {
- IonodePtr ionode(
- reinterpret_cast<cras_ionode*>(calloc(1, sizeof(cras_ionode))), free);
- ionode->type = type;
- return ionode;
-}
-
-int fake_flush_buffer(struct cras_iodev* iodev) {
- return 0;
-}
-
-IodevPtr create_open_iodev(CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- cras_audio_format* format,
- cras_ionode* active_node) {
- IodevPtr iodev(reinterpret_cast<cras_iodev*>(calloc(1, sizeof(cras_iodev))),
- free);
- iodev->is_enabled = 1;
- iodev->direction = direction;
- iodev->format = format;
- iodev->state = CRAS_IODEV_STATE_OPEN;
- iodev->delay_frames = delay_frames_stub;
- iodev->active_node = active_node;
- iodev->buffer_size = cb_threshold * 2;
- iodev->min_cb_level = UINT_MAX;
- iodev->max_cb_level = 0;
- iodev->largest_cb_level = 0;
- iodev->flush_buffer = &fake_flush_buffer;
- return iodev;
-}
-
-DevicePtr create_device(CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- cras_audio_format* format,
- CRAS_NODE_TYPE active_node_type) {
- IonodePtr node = create_ionode(active_node_type);
- IodevPtr dev = create_open_iodev(direction, cb_threshold, format, node.get());
- OpendevPtr odev(reinterpret_cast<open_dev*>(calloc(1, sizeof(open_dev))),
- free);
- odev->dev = dev.get();
-
- DevicePtr d(new Device(std::move(dev), std::move(node), std::move(odev)));
- return d;
-}
-
-void add_stream_to_dev(IodevPtr& dev, const StreamPtr& stream) {
- DL_APPEND(dev->streams, stream->dstream.get());
- dev->min_cb_level = std::min(stream->rstream->cb_threshold,
- static_cast<size_t>(dev->min_cb_level));
- dev->max_cb_level = std::max(stream->rstream->cb_threshold,
- static_cast<size_t>(dev->max_cb_level));
- dev->largest_cb_level = std::max(stream->rstream->cb_threshold,
- static_cast<size_t>(dev->max_cb_level));
-
- if (stream->rstream->main_dev.dev_id == NO_DEVICE) {
- stream->rstream->main_dev.dev_id = dev->info.idx;
- stream->rstream->main_dev.dev_ptr = dev.get();
- }
-}
-
-void fill_audio_format(cras_audio_format* format, unsigned int rate) {
- format->format = SND_PCM_FORMAT_S16_LE;
- format->frame_rate = rate;
- format->num_channels = 2;
- format->channel_layout[0] = 0;
- format->channel_layout[1] = 1;
- for (int i = 2; i < CRAS_CH_MAX; i++)
- format->channel_layout[i] = -1;
-}
diff --git a/cras/src/tests/dev_io_stubs.h b/cras/src/tests/dev_io_stubs.h
deleted file mode 100644
index 9db193c5..00000000
--- a/cras/src/tests/dev_io_stubs.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2017 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <stdint.h>
-#include <stdio.h>
-#include <time.h>
-
-#include <memory>
-
-extern "C" {
-#include "cras_iodev.h"
-#include "cras_rstream.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "dev_io.h"
-#include "dev_stream.h"
-#include "utlist.h"
-}
-
-#include "iodev_stub.h"
-#include "rstream_stub.h"
-
-#define RSTREAM_FAKE_POLL_FD 33
-
-using DevStreamPtr = std::unique_ptr<dev_stream, decltype(free)*>;
-using IodevPtr = std::unique_ptr<cras_iodev, decltype(free)*>;
-using IonodePtr = std::unique_ptr<cras_ionode, decltype(free)*>;
-using OpendevPtr = std::unique_ptr<open_dev, decltype(free)*>;
-using RstreamPtr = std::unique_ptr<cras_rstream, decltype(free)*>;
-
-void destroy_shm(struct cras_audio_shm* shm);
-using ShmPtr = std::unique_ptr<cras_audio_shm, decltype(destroy_shm)*>;
-ShmPtr create_shm(size_t cb_threshold);
-
-// Holds the rstream and devstream pointers for an attached stream.
-struct Stream {
- Stream(ShmPtr shm, RstreamPtr rstream, DevStreamPtr dstream)
- : shm(std::move(shm)),
- rstream(std::move(rstream)),
- dstream(std::move(dstream)) {}
- ShmPtr shm;
- RstreamPtr rstream;
- DevStreamPtr dstream;
-};
-using StreamPtr = std::unique_ptr<Stream>;
-
-// Holds the iodev and ionode pointers for an attached device.
-struct Device {
- Device(IodevPtr dev, IonodePtr node, OpendevPtr odev)
- : dev(std::move(dev)), node(std::move(node)), odev(std::move(odev)) {}
- IodevPtr dev;
- IonodePtr node;
- OpendevPtr odev;
-};
-using DevicePtr = std::unique_ptr<Device>;
-
-RstreamPtr create_rstream(cras_stream_id_t id,
- CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- const cras_audio_format* format,
- cras_audio_shm* shm);
-DevStreamPtr create_dev_stream(unsigned int dev_id, cras_rstream* rstream);
-StreamPtr create_stream(cras_stream_id_t id,
- unsigned int dev_id,
- CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- const cras_audio_format* format);
-void AddFakeDataToStream(Stream* stream, unsigned int frames);
-int delay_frames_stub(const struct cras_iodev* iodev);
-IonodePtr create_ionode(CRAS_NODE_TYPE type);
-IodevPtr create_open_iodev(CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- cras_audio_format* format,
- cras_ionode* active_node);
-DevicePtr create_device(CRAS_STREAM_DIRECTION direction,
- size_t cb_threshold,
- cras_audio_format* format,
- CRAS_NODE_TYPE active_node_type);
-void add_stream_to_dev(IodevPtr& dev, const StreamPtr& stream);
-void fill_audio_format(cras_audio_format* format, unsigned int rate);
diff --git a/cras/src/tests/dev_io_unittest.cc b/cras/src/tests/dev_io_unittest.cc
deleted file mode 100644
index 2dbf344e..00000000
--- a/cras/src/tests/dev_io_unittest.cc
+++ /dev/null
@@ -1,468 +0,0 @@
-// Copyright 2017 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <time.h>
-
-#include <memory>
-#include <unordered_map>
-
-extern "C" {
-#include "cras_iodev.h" // stubbed
-#include "cras_rstream.h" // stubbed
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "dev_io.h" // tested
-#include "dev_stream.h" // stubbed
-#include "utlist.h"
-
-struct audio_thread_event_log* atlog;
-}
-
-#include "dev_io_stubs.h"
-#include "iodev_stub.h"
-#include "metrics_stub.h"
-#include "rstream_stub.h"
-
-static float dev_stream_capture_software_gain_scaler_val;
-static float input_data_get_software_gain_scaler_val;
-static unsigned int dev_stream_capture_avail_ret = 480;
-struct set_dev_rate_data {
- unsigned int dev_rate;
- double dev_rate_ratio;
- double main_rate_ratio;
- int coarse_rate_adjust;
-};
-std::unordered_map<struct dev_stream*, set_dev_rate_data> set_dev_rate_map;
-
-namespace {
-
-class DevIoSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- atlog = static_cast<audio_thread_event_log*>(calloc(1, sizeof(*atlog)));
- iodev_stub_reset();
- rstream_stub_reset();
- fill_audio_format(&format, 48000);
- set_dev_rate_map.clear();
- stream = create_stream(1, 1, CRAS_STREAM_INPUT, cb_threshold, &format);
- }
-
- virtual void TearDown() { free(atlog); }
-
- size_t cb_threshold = 480;
- cras_audio_format format;
- StreamPtr stream;
-};
-
-TEST_F(DevIoSuite, SendCapturedFails) {
- // rstream's next callback is now and there is enough data to fill.
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream.get(), 480);
-
- struct open_dev* dev_list = NULL;
- DevicePtr dev = create_device(CRAS_STREAM_INPUT, cb_threshold, &format,
- CRAS_NODE_TYPE_MIC);
- DL_APPEND(dev_list, dev->odev.get());
- add_stream_to_dev(dev->dev, stream);
-
- // Set failure response from frames_queued.
- iodev_stub_frames_queued(dev->dev.get(), -3, start);
-
- EXPECT_EQ(-3, dev_io_send_captured_samples(dev_list));
-}
-
-TEST_F(DevIoSuite, CaptureGain) {
- struct open_dev* dev_list = NULL;
- struct open_dev* odev_list = NULL;
- struct timespec ts;
- DevicePtr dev = create_device(CRAS_STREAM_INPUT, cb_threshold, &format,
- CRAS_NODE_TYPE_MIC);
-
- dev->dev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev_stub_frames_queued(dev->dev.get(), 20, ts);
- DL_APPEND(dev_list, dev->odev.get());
- add_stream_to_dev(dev->dev, stream);
-
- /* The applied scaler gain should match what is reported by input_data. */
- dev->dev->active_node->ui_gain_scaler = 1.0f;
- input_data_get_software_gain_scaler_val = 1.0f;
- dev_io_capture(&dev_list, &odev_list);
- EXPECT_EQ(1.0f, dev_stream_capture_software_gain_scaler_val);
-
- input_data_get_software_gain_scaler_val = 0.99f;
- dev_io_capture(&dev_list, &odev_list);
- EXPECT_EQ(0.99f, dev_stream_capture_software_gain_scaler_val);
-
- dev->dev->active_node->ui_gain_scaler = 0.6f;
- input_data_get_software_gain_scaler_val = 0.7f;
- dev_io_capture(&dev_list, &odev_list);
- EXPECT_FLOAT_EQ(0.42f, dev_stream_capture_software_gain_scaler_val);
-}
-
-/*
- * When input and output devices are on the internal sound card,
- * and their device rates are the same, use the estimated rate
- * on the output device as the estimated rate of input device.
- */
-TEST_F(DevIoSuite, CopyOutputEstimatedRate) {
- struct open_dev* idev_list = NULL;
- struct open_dev* odev_list = NULL;
- struct timespec ts;
- DevicePtr out_dev = create_device(CRAS_STREAM_OUTPUT, cb_threshold, &format,
- CRAS_NODE_TYPE_INTERNAL_SPEAKER);
- DevicePtr in_dev = create_device(CRAS_STREAM_INPUT, cb_threshold, &format,
- CRAS_NODE_TYPE_MIC);
-
- in_dev->dev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev_stub_frames_queued(in_dev->dev.get(), 20, ts);
- DL_APPEND(idev_list, in_dev->odev.get());
- add_stream_to_dev(in_dev->dev, stream);
- DL_APPEND(odev_list, out_dev->odev.get());
- iodev_stub_on_internal_card(out_dev->dev->active_node, 1);
- iodev_stub_on_internal_card(in_dev->dev->active_node, 1);
-
- iodev_stub_est_rate_ratio(in_dev->dev.get(), 0.8f);
- iodev_stub_est_rate_ratio(out_dev->dev.get(), 1.2f);
-
- dev_io_capture(&idev_list, &odev_list);
-
- EXPECT_FLOAT_EQ(1.2f, set_dev_rate_map[stream->dstream.get()].dev_rate_ratio);
-}
-
-/*
- * When input and output devices are not both on the internal sound card,
- * estimated rates are independent.
- */
-TEST_F(DevIoSuite, InputOutputIndependentEstimatedRate) {
- struct open_dev* idev_list = NULL;
- struct open_dev* odev_list = NULL;
- struct timespec ts;
- DevicePtr out_dev = create_device(CRAS_STREAM_OUTPUT, cb_threshold, &format,
- CRAS_NODE_TYPE_INTERNAL_SPEAKER);
- DevicePtr in_dev = create_device(CRAS_STREAM_INPUT, cb_threshold, &format,
- CRAS_NODE_TYPE_USB);
-
- in_dev->dev->state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev_stub_frames_queued(in_dev->dev.get(), 20, ts);
- DL_APPEND(idev_list, in_dev->odev.get());
- add_stream_to_dev(in_dev->dev, stream);
- DL_APPEND(odev_list, out_dev->odev.get());
- iodev_stub_on_internal_card(out_dev->dev->active_node, 1);
- iodev_stub_on_internal_card(in_dev->dev->active_node, 0);
-
- iodev_stub_est_rate_ratio(in_dev->dev.get(), 0.8f);
- iodev_stub_est_rate_ratio(out_dev->dev.get(), 1.2f);
- iodev_stub_update_rate(in_dev->dev.get(), 1);
-
- dev_io_capture(&idev_list, &odev_list);
-
- EXPECT_FLOAT_EQ(0.8f, set_dev_rate_map[stream->dstream.get()].dev_rate_ratio);
-}
-
-/*
- * If any hw_level is larger than 1.5 * largest_cb_level and
- * DROP_FRAMES_THRESHOLD_MS, reset all input devices.
- */
-TEST_F(DevIoSuite, SendCapturedNeedToResetDevices) {
- struct timespec start;
- struct timespec drop_time;
- struct open_dev* dev_list = NULL;
- bool rc;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- AddFakeDataToStream(stream.get(), 0);
-
- DevicePtr dev1 =
- create_device(CRAS_STREAM_INPUT, 1000, &format, CRAS_NODE_TYPE_MIC);
- DevicePtr dev2 =
- create_device(CRAS_STREAM_INPUT, 10000, &format, CRAS_NODE_TYPE_MIC);
- DL_APPEND(dev_list, dev1->odev.get());
- DL_APPEND(dev_list, dev2->odev.get());
- add_stream_to_dev(dev1->dev, stream);
- add_stream_to_dev(dev2->dev, stream);
-
- iodev_stub_frames_queued(dev1->dev.get(), 2880, start);
- iodev_stub_frames_queued(dev2->dev.get(), 4800, start);
- EXPECT_EQ(0, dev_io_send_captured_samples(dev_list));
-
- /*
- * Should drop frames to one min_cb_level, which is MIN(2880, 4800) - 480 =
- * 2400 (50ms).
- */
- rc = iodev_stub_get_drop_time(dev1->dev.get(), &drop_time);
- EXPECT_EQ(true, rc);
- EXPECT_EQ(0, drop_time.tv_sec);
- EXPECT_EQ(50000000, drop_time.tv_nsec);
-
- rc = iodev_stub_get_drop_time(dev2->dev.get(), &drop_time);
- EXPECT_EQ(true, rc);
- EXPECT_EQ(0, drop_time.tv_sec);
- EXPECT_EQ(50000000, drop_time.tv_nsec);
-}
-
-/*
- * If any hw_level is larger than 0.5 * buffer_size and
- * DROP_FRAMES_THRESHOLD_MS, reset all input devices.
- */
-
-TEST_F(DevIoSuite, SendCapturedNeedToResetDevices2) {
- struct timespec start;
- struct timespec drop_time;
- struct open_dev* dev_list = NULL;
- bool rc;
-
- stream = create_stream(1, 1, CRAS_STREAM_INPUT, 2000, &format);
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- AddFakeDataToStream(stream.get(), 0);
-
- DevicePtr dev1 =
- create_device(CRAS_STREAM_INPUT, 2048, &format, CRAS_NODE_TYPE_MIC);
- DevicePtr dev2 =
- create_device(CRAS_STREAM_INPUT, 10000, &format, CRAS_NODE_TYPE_MIC);
- DL_APPEND(dev_list, dev1->odev.get());
- DL_APPEND(dev_list, dev2->odev.get());
- add_stream_to_dev(dev1->dev, stream);
- add_stream_to_dev(dev2->dev, stream);
-
- iodev_stub_frames_queued(dev1->dev.get(), 2480, start);
- iodev_stub_frames_queued(dev2->dev.get(), 2480, start);
- EXPECT_EQ(0, dev_io_send_captured_samples(dev_list));
-
- /*
- * Should drop frames to one min_cb_level, which is 2480 - 2000 = 480 (10ms).
- */
- rc = iodev_stub_get_drop_time(dev1->dev.get(), &drop_time);
- EXPECT_EQ(true, rc);
- EXPECT_EQ(0, drop_time.tv_sec);
- EXPECT_EQ(10000000, drop_time.tv_nsec);
-
- rc = iodev_stub_get_drop_time(dev2->dev.get(), &drop_time);
- EXPECT_EQ(true, rc);
- EXPECT_EQ(0, drop_time.tv_sec);
- EXPECT_EQ(10000000, drop_time.tv_nsec);
-}
-
-/*
- * If the hw_level is larger than 1.5 * largest_cb_level but less than
- * DROP_FRAMES_THRESHOLD_MS, do nothing.
- */
-TEST_F(DevIoSuite, SendCapturedLevelLessThanThreshold) {
- struct timespec start;
- struct timespec drop_time;
- struct open_dev* dev_list = NULL;
- bool rc;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- AddFakeDataToStream(stream.get(), 0);
-
- DevicePtr dev =
- create_device(CRAS_STREAM_INPUT, 480, &format, CRAS_NODE_TYPE_MIC);
- DL_APPEND(dev_list, dev->odev.get());
- add_stream_to_dev(dev->dev, stream);
-
- iodev_stub_frames_queued(dev->dev.get(), 2048, start);
- EXPECT_EQ(0, dev_io_send_captured_samples(dev_list));
-
- rc = iodev_stub_get_drop_time(dev->dev.get(), &drop_time);
- EXPECT_EQ(false, rc);
-}
-
-/*
- * If all hw_level is less than 1.5 * largest_cb_level and 0.5 * buffer_size,
- * do nothing.
- */
-TEST_F(DevIoSuite, SendCapturedNoNeedToResetDevices) {
- struct timespec start;
- struct timespec drop_time;
- struct open_dev* dev_list = NULL;
- bool rc;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- AddFakeDataToStream(stream.get(), 0);
-
- DevicePtr dev1 =
- create_device(CRAS_STREAM_INPUT, 1000, &format, CRAS_NODE_TYPE_MIC);
- DevicePtr dev2 =
- create_device(CRAS_STREAM_INPUT, 10000, &format, CRAS_NODE_TYPE_MIC);
- DL_APPEND(dev_list, dev1->odev.get());
- DL_APPEND(dev_list, dev2->odev.get());
- add_stream_to_dev(dev1->dev, stream);
- add_stream_to_dev(dev2->dev, stream);
-
- iodev_stub_frames_queued(dev1->dev.get(), 400, start);
- iodev_stub_frames_queued(dev2->dev.get(), 400, start);
- EXPECT_EQ(0, dev_io_send_captured_samples(dev_list));
-
- rc = iodev_stub_get_drop_time(dev1->dev.get(), &drop_time);
- EXPECT_EQ(false, rc);
-
- rc = iodev_stub_get_drop_time(dev2->dev.get(), &drop_time);
- EXPECT_EQ(false, rc);
-}
-
-/*
- * On loopback and hotword devices, if any hw_level is larger than
- * 1.5 * largest_cb_level and DROP_FRAMES_THRESHOLD_MS, do nothing.
- */
-TEST_F(DevIoSuite, SendCapturedNoNeedToDrop) {
- struct timespec start;
- struct timespec drop_time;
- struct open_dev* dev_list = NULL;
- bool rc;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- AddFakeDataToStream(stream.get(), 0);
-
- DevicePtr dev1 =
- create_device(CRAS_STREAM_INPUT, 480, &format, CRAS_NODE_TYPE_HOTWORD);
- DevicePtr dev2 = create_device(CRAS_STREAM_INPUT, 480, &format,
- CRAS_NODE_TYPE_POST_MIX_PRE_DSP);
- DevicePtr dev3 =
- create_device(CRAS_STREAM_INPUT, 480, &format, CRAS_NODE_TYPE_POST_DSP);
-
- DL_APPEND(dev_list, dev1->odev.get());
- DL_APPEND(dev_list, dev2->odev.get());
- DL_APPEND(dev_list, dev3->odev.get());
-
- add_stream_to_dev(dev1->dev, stream);
- add_stream_to_dev(dev2->dev, stream);
- add_stream_to_dev(dev3->dev, stream);
-
- iodev_stub_frames_queued(dev1->dev.get(), 4800, start);
- iodev_stub_frames_queued(dev2->dev.get(), 4800, start);
- iodev_stub_frames_queued(dev2->dev.get(), 4800, start);
-
- EXPECT_EQ(0, dev_io_send_captured_samples(dev_list));
-
- rc = iodev_stub_get_drop_time(dev1->dev.get(), &drop_time);
- EXPECT_EQ(false, rc);
-
- rc = iodev_stub_get_drop_time(dev2->dev.get(), &drop_time);
- EXPECT_EQ(false, rc);
-
- rc = iodev_stub_get_drop_time(dev3->dev.get(), &drop_time);
- EXPECT_EQ(false, rc);
-}
-
-/* Stubs */
-extern "C" {
-
-int input_data_get_for_stream(struct input_data* data,
- struct cras_rstream* stream,
- struct buffer_share* offsets,
- struct cras_audio_area** area,
- unsigned int* offset) {
- return 0;
-}
-
-int input_data_put_for_stream(struct input_data* data,
- struct cras_rstream* stream,
- struct buffer_share* offsets,
- unsigned int frames) {
- return 0;
-}
-
-float input_data_get_software_gain_scaler(struct input_data* data,
- float idev_sw_gain_scaler,
- struct cras_rstream* stream) {
- return input_data_get_software_gain_scaler_val;
-}
-
-int cras_audio_thread_event_drop_samples() {
- return 0;
-}
-
-int cras_audio_thread_event_severe_underrun() {
- return 0;
-}
-
-int dev_stream_attached_devs(const struct dev_stream* dev_stream) {
- return 0;
-}
-void dev_stream_update_frames(const struct dev_stream* dev_stream) {}
-int dev_stream_playback_frames(const struct dev_stream* dev_stream) {
- return 0;
-}
-int dev_stream_is_pending_reply(const struct dev_stream* dev_stream) {
- return 0;
-}
-int dev_stream_mix(struct dev_stream* dev_stream,
- const struct cras_audio_format* fmt,
- uint8_t* dst,
- unsigned int num_to_write) {
- return 0;
-}
-void dev_stream_set_dev_rate(struct dev_stream* dev_stream,
- unsigned int dev_rate,
- double dev_rate_ratio,
- double main_rate_ratio,
- int coarse_rate_adjust) {
- set_dev_rate_data new_data;
- new_data.dev_rate = dev_rate;
- new_data.dev_rate_ratio = dev_rate_ratio;
- new_data.main_rate_ratio = main_rate_ratio;
- new_data.coarse_rate_adjust = coarse_rate_adjust;
-
- set_dev_rate_map[dev_stream] = new_data;
-}
-int dev_stream_capture_update_rstream(struct dev_stream* dev_stream) {
- return 0;
-}
-int dev_stream_wake_time(struct dev_stream* dev_stream,
- unsigned int curr_level,
- struct timespec* level_tstamp,
- unsigned int cap_limit,
- int is_cap_limit_stream,
- struct timespec* wake_time_out) {
- return 0;
-}
-int dev_stream_flush_old_audio_messages(struct dev_stream* dev_stream) {
- return 0;
-}
-void dev_stream_set_delay(const struct dev_stream* dev_stream,
- unsigned int delay_frames) {}
-unsigned int dev_stream_capture(struct dev_stream* dev_stream,
- const struct cras_audio_area* area,
- unsigned int area_offset,
- float software_gain_scaler) {
- dev_stream_capture_software_gain_scaler_val = software_gain_scaler;
- return 0;
-}
-void dev_stream_update_next_wake_time(struct dev_stream* dev_stream) {}
-int dev_stream_request_playback_samples(struct dev_stream* dev_stream,
- const struct timespec* now) {
- return 0;
-}
-int dev_stream_playback_update_rstream(struct dev_stream* dev_stream) {
- return 0;
-}
-void dev_stream_destroy(struct dev_stream* dev_stream) {}
-unsigned int dev_stream_capture_avail(const struct dev_stream* dev_stream) {
- return dev_stream_capture_avail_ret;
-}
-struct dev_stream* dev_stream_create(struct cras_rstream* stream,
- unsigned int dev_id,
- const struct cras_audio_format* dev_fmt,
- void* dev_ptr,
- struct timespec* cb_ts,
- const struct timespec* sleep_interval_ts) {
- return 0;
-}
-int cras_device_monitor_error_close(unsigned int dev_idx) {
- return 0;
-}
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/dev_stream_unittest.cc b/cras/src/tests/dev_stream_unittest.cc
deleted file mode 100644
index 700376fb..00000000
--- a/cras/src/tests/dev_stream_unittest.cc
+++ /dev/null
@@ -1,1336 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "audio_thread_log.h"
-#include "byte_buffer.h"
-#include "cras_audio_area.h"
-#include "cras_rstream.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "dev_stream.h"
-}
-
-namespace {
-
-extern "C" {
-struct audio_thread_event_log* atlog;
-// For audio_thread_log.h use.
-int atlog_rw_shm_fd;
-int atlog_ro_shm_fd;
-unsigned int max_frames_for_conversion(unsigned int stream_frames,
- unsigned int stream_rate,
- unsigned int device_rate);
-};
-
-static struct timespec clock_gettime_retspec;
-static struct timespec cb_ts;
-
-static const int kBufferFrames = 1024;
-static const struct cras_audio_format fmt_s16le_44_1 = {
- SND_PCM_FORMAT_S16_LE,
- 44100,
- 2,
-};
-static const struct cras_audio_format fmt_s16le_48 = {
- SND_PCM_FORMAT_S16_LE,
- 48000,
- 2,
-};
-static const struct cras_audio_format fmt_s16le_48_mono = {
- SND_PCM_FORMAT_S16_LE,
- 48000,
- 1,
-};
-static const struct cras_audio_format fmt_s16le_8 = {
- SND_PCM_FORMAT_S16_LE,
- 8000,
- 2,
-};
-
-struct cras_audio_area_copy_call {
- const struct cras_audio_area* dst;
- unsigned int dst_offset;
- unsigned int dst_format_bytes;
- const struct cras_audio_area* src;
- unsigned int src_offset;
- float software_gain_scaler;
-};
-
-struct fmt_conv_call {
- struct cras_fmt_conv* conv;
- uint8_t* in_buf;
- uint8_t* out_buf;
- size_t in_frames;
- size_t out_frames;
-};
-
-struct mix_add_call {
- int16_t* dst;
- int16_t* src;
- unsigned int count;
- unsigned int index;
- int mute;
- float mix_vol;
-};
-
-struct rstream_get_readable_call {
- struct cras_rstream* rstream;
- unsigned int offset;
- unsigned int num_called;
-};
-
-static int config_format_converter_called;
-static const struct cras_audio_format* config_format_converter_from_fmt;
-static int config_format_converter_frames;
-static struct cras_fmt_conv* config_format_converter_conv;
-static struct cras_audio_format in_fmt;
-static struct cras_audio_format out_fmt;
-static struct cras_audio_area_copy_call copy_area_call;
-static struct fmt_conv_call conv_frames_call;
-static int cras_audio_area_create_num_channels_val;
-static int cras_fmt_conversion_needed_val;
-static int cras_fmt_conv_set_linear_resample_rates_called;
-static float cras_fmt_conv_set_linear_resample_rates_from;
-static float cras_fmt_conv_set_linear_resample_rates_to;
-
-static unsigned int rstream_playable_frames_ret;
-static struct mix_add_call mix_add_call;
-static struct rstream_get_readable_call rstream_get_readable_call;
-static unsigned int rstream_get_readable_num;
-static uint8_t* rstream_get_readable_ptr;
-
-static struct cras_audio_format* cras_rstream_post_processing_format_val;
-static int cras_rstream_audio_ready_called;
-static int cras_rstream_audio_ready_count;
-static int cras_rstream_is_pending_reply_ret;
-static int cras_rstream_flush_old_audio_messages_called;
-static int cras_server_metrics_missed_cb_event_called;
-
-static char* atlog_name;
-
-class CreateSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 2;
-
- SetupShm(&rstream_.shm);
-
- rstream_.stream_id = 0x10001;
- rstream_.buffer_frames = kBufferFrames;
- rstream_.cb_threshold = kBufferFrames / 2;
- rstream_.is_draining = 0;
- rstream_.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- rstream_.direction = CRAS_STREAM_OUTPUT;
- rstream_.format.format = SND_PCM_FORMAT_S16_LE;
- rstream_.format.num_channels = 2;
- rstream_.format = fmt_s16le_44_1;
- rstream_.flags = 0;
- rstream_.num_missed_cb = 0;
-
- config_format_converter_from_fmt = NULL;
- config_format_converter_called = 0;
- cras_fmt_conversion_needed_val = 0;
- cras_fmt_conv_set_linear_resample_rates_called = 0;
-
- cras_rstream_audio_ready_called = 0;
- cras_rstream_audio_ready_count = 0;
- cras_rstream_is_pending_reply_ret = 0;
- cras_rstream_flush_old_audio_messages_called = 0;
- cras_server_metrics_missed_cb_event_called = 0;
-
- memset(&copy_area_call, 0xff, sizeof(copy_area_call));
- memset(&conv_frames_call, 0xff, sizeof(conv_frames_call));
-
- ASSERT_FALSE(asprintf(&atlog_name, "/ATlog-%d", getpid()) < 0);
- /* To avoid un-used variable warning. */
- atlog_rw_shm_fd = atlog_ro_shm_fd = -1;
- atlog = audio_thread_event_log_init(atlog_name);
-
- devstr.stream = &rstream_;
- devstr.conv = NULL;
- devstr.conv_buffer = NULL;
- devstr.conv_buffer_size_frames = 0;
-
- area = (struct cras_audio_area*)calloc(
- 1, sizeof(*area) + 2 * sizeof(struct cras_channel_area));
- area->num_channels = 2;
- channel_area_set_channel(&area->channels[0], CRAS_CH_FL);
- channel_area_set_channel(&area->channels[1], CRAS_CH_FR);
- area->channels[0].step_bytes = 4;
- area->channels[0].buf = (uint8_t*)(cap_buf);
- area->channels[1].step_bytes = 4;
- area->channels[1].buf = (uint8_t*)(cap_buf + 1);
- area->frames = kBufferFrames;
-
- stream_area = (struct cras_audio_area*)calloc(
- 1, sizeof(*area) + 2 * sizeof(struct cras_channel_area));
- stream_area->num_channels = 2;
- rstream_.audio_area = stream_area;
- int16_t* shm_samples = (int16_t*)rstream_.shm->samples;
- stream_area->channels[0].step_bytes = 4;
- stream_area->channels[0].buf = (uint8_t*)(shm_samples);
- stream_area->channels[1].step_bytes = 4;
- stream_area->channels[1].buf = (uint8_t*)(shm_samples + 1);
- }
-
- virtual void TearDown() {
- free(area);
- free(stream_area);
- free(rstream_.shm->header);
- free(rstream_.shm->samples);
- free(rstream_.shm);
- audio_thread_event_log_deinit(atlog, atlog_name);
- free(atlog_name);
- }
-
- void SetupShm(struct cras_audio_shm** shm_out) {
- int16_t* buf;
- struct cras_audio_shm* shm;
- uint32_t used_size;
-
- shm = static_cast<struct cras_audio_shm*>(
- calloc(1, sizeof(struct cras_audio_shm)));
-
- shm->header = static_cast<struct cras_audio_shm_header*>(
- calloc(1, sizeof(struct cras_audio_shm_header)));
- cras_shm_set_frame_bytes(shm, 4);
- used_size = kBufferFrames * cras_shm_frame_bytes(shm);
- cras_shm_set_used_size(shm, used_size);
-
- shm->samples = static_cast<uint8_t*>(
- calloc(1, cras_shm_calculate_samples_size(used_size)));
- shm->samples_info.length = cras_shm_calculate_samples_size(used_size);
-
- buf = (int16_t*)shm->samples;
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- buf[i] = i;
- cras_shm_set_mute(shm, 0);
- cras_shm_set_volume_scaler(shm, 1.0);
-
- *shm_out = shm;
- }
-
- void SetUpFmtConv(unsigned int in_rate,
- unsigned int out_rate,
- unsigned int conv_buf_size) {
- in_fmt.frame_rate = in_rate;
- out_fmt.frame_rate = out_rate;
- cras_fmt_conversion_needed_val = 1;
-
- devstr.conv = (struct cras_fmt_conv*)0xdead;
- devstr.conv_buffer =
- (struct byte_buffer*)byte_buffer_create(conv_buf_size * 4);
- devstr.conv_buffer_size_frames = kBufferFrames * 2;
-
- devstr.conv_area = (struct cras_audio_area*)calloc(
- 1, sizeof(*area) + 2 * sizeof(*area->channels));
- devstr.conv_area->num_channels = 2;
- devstr.conv_area->channels[0].step_bytes = 4;
- devstr.conv_area->channels[0].buf = (uint8_t*)(devstr.conv_buffer->bytes);
- devstr.conv_area->channels[1].step_bytes = 4;
- devstr.conv_area->channels[1].buf =
- (uint8_t*)(devstr.conv_buffer->bytes + 1);
- }
-
- struct dev_stream devstr;
- struct cras_audio_area* area;
- struct cras_audio_area* stream_area;
- int16_t cap_buf[kBufferFrames * 2];
- struct cras_rstream rstream_;
-};
-
-TEST_F(CreateSuite, CaptureNoSRC) {
- float software_gain_scaler = 10;
-
- dev_stream_capture(&devstr, area, 0, software_gain_scaler);
-
- EXPECT_EQ(stream_area, copy_area_call.dst);
- EXPECT_EQ(0, copy_area_call.dst_offset);
- EXPECT_EQ(4, copy_area_call.dst_format_bytes);
- EXPECT_EQ(area, copy_area_call.src);
- EXPECT_EQ(software_gain_scaler, copy_area_call.software_gain_scaler);
-}
-
-TEST_F(CreateSuite, CaptureSRCSmallConverterBuffer) {
- float software_gain_scaler = 10;
- unsigned int conv_buf_avail_at_input_rate;
- int nread;
-
- SetUpFmtConv(44100, 32000, kBufferFrames / 4);
- nread = dev_stream_capture(&devstr, area, 0, software_gain_scaler);
-
- // |nread| is bound by small converter buffer size (kBufferFrames / 4)
- conv_buf_avail_at_input_rate = cras_frames_at_rate(
- out_fmt.frame_rate, (kBufferFrames / 4), in_fmt.frame_rate);
-
- EXPECT_EQ(conv_buf_avail_at_input_rate, nread);
- EXPECT_EQ((struct cras_fmt_conv*)0xdead, conv_frames_call.conv);
- EXPECT_EQ((uint8_t*)cap_buf, conv_frames_call.in_buf);
- EXPECT_EQ(devstr.conv_buffer->bytes, conv_frames_call.out_buf);
-
- EXPECT_EQ(conv_buf_avail_at_input_rate, conv_frames_call.in_frames);
-
- // Expect number of output frames is limited by the size of converter buffer.
- EXPECT_EQ(kBufferFrames / 4, conv_frames_call.out_frames);
-
- EXPECT_EQ(stream_area, copy_area_call.dst);
- EXPECT_EQ(0, copy_area_call.dst_offset);
- EXPECT_EQ(4, copy_area_call.dst_format_bytes);
- EXPECT_EQ(devstr.conv_area, copy_area_call.src);
- EXPECT_EQ(software_gain_scaler, copy_area_call.software_gain_scaler);
-
- free(devstr.conv_area);
- byte_buffer_destroy(&devstr.conv_buffer);
-}
-
-TEST_F(CreateSuite, CaptureSRCLargeConverterBuffer) {
- float software_gain_scaler = 10;
- unsigned int stream_avail_at_input_rate;
- int nread;
-
- SetUpFmtConv(44100, 32000, kBufferFrames * 2);
- nread = dev_stream_capture(&devstr, area, 0, software_gain_scaler);
-
- // Available frames at stream side is bound by cb_threshold, which
- // equals to kBufferFrames / 2.
- stream_avail_at_input_rate = cras_frames_at_rate(
- out_fmt.frame_rate, (kBufferFrames / 2), in_fmt.frame_rate);
-
- EXPECT_EQ(stream_avail_at_input_rate, nread);
- EXPECT_EQ((struct cras_fmt_conv*)0xdead, conv_frames_call.conv);
- EXPECT_EQ((uint8_t*)cap_buf, conv_frames_call.in_buf);
- EXPECT_EQ(devstr.conv_buffer->bytes, conv_frames_call.out_buf);
-
- // Expect number of input frames is limited by |stream_avail_at_input_rate|
- // at format conversion.
- EXPECT_EQ(stream_avail_at_input_rate, conv_frames_call.in_frames);
-
- // Expect number of output frames is limited by the size of converter buffer.
- EXPECT_EQ(kBufferFrames * 2, conv_frames_call.out_frames);
-
- EXPECT_EQ(stream_area, copy_area_call.dst);
- EXPECT_EQ(0, copy_area_call.dst_offset);
- EXPECT_EQ(4, copy_area_call.dst_format_bytes);
- EXPECT_EQ(devstr.conv_area, copy_area_call.src);
- EXPECT_EQ(software_gain_scaler, copy_area_call.software_gain_scaler);
-
- free(devstr.conv_area);
- byte_buffer_destroy(&devstr.conv_buffer);
-}
-
-TEST_F(CreateSuite, CreateSRC44to48) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_44_1;
- in_fmt.frame_rate = 44100; // Input to converter is stream rate.
- out_fmt.frame_rate = 48000; // Output from converter is device rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream =
- dev_stream_create(&rstream_, 0, &fmt_s16le_48, (void*)0x55, &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for device output.
- unsigned int device_frames =
- cras_frames_at_rate(in_fmt.frame_rate, kBufferFrames, out_fmt.frame_rate);
- EXPECT_LE(kBufferFrames, device_frames); // Soundness check.
- EXPECT_LE(device_frames, config_format_converter_frames);
- EXPECT_LE(device_frames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateOutputWithSchedule) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- // init_cb_ts and non-null init_sleep_ts will be used.
- struct timespec init_cb_ts = {1, 2};
- struct timespec init_sleep_ts = {3, 4};
-
- rstream_.direction = CRAS_STREAM_OUTPUT;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_48, (void*)0x55,
- &init_cb_ts, &init_sleep_ts);
-
- EXPECT_EQ(init_cb_ts.tv_sec, rstream_.next_cb_ts.tv_sec);
- EXPECT_EQ(init_cb_ts.tv_nsec, rstream_.next_cb_ts.tv_nsec);
- EXPECT_EQ(init_sleep_ts.tv_sec, rstream_.sleep_interval_ts.tv_sec);
- EXPECT_EQ(init_sleep_ts.tv_nsec, rstream_.sleep_interval_ts.tv_nsec);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC44from48Input) {
- struct dev_stream* dev_stream;
- struct cras_audio_format processed_fmt = fmt_s16le_48;
-
- processed_fmt.num_channels = 1;
- rstream_.format = fmt_s16le_44_1;
- rstream_.direction = CRAS_STREAM_INPUT;
- in_fmt.frame_rate = 48000; // Input to converter is device rate.
- out_fmt.frame_rate = 44100; // Output from converter is stream rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- cras_rstream_post_processing_format_val = &processed_fmt;
- dev_stream =
- dev_stream_create(&rstream_, 0, &fmt_s16le_48, (void*)0x55, &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for device input.
- unsigned int device_frames =
- cras_frames_at_rate(out_fmt.frame_rate, kBufferFrames, in_fmt.frame_rate);
- EXPECT_LE(kBufferFrames, device_frames); // Soundness check.
- EXPECT_LE(device_frames, config_format_converter_frames);
- EXPECT_EQ(&processed_fmt, config_format_converter_from_fmt);
- EXPECT_LE(device_frames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC48to44) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_48;
- in_fmt.frame_rate = 48000; // Stream rate.
- out_fmt.frame_rate = 44100; // Device rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream = dev_stream_create(&rstream_, 0, &fmt_s16le_44_1, (void*)0x55,
- &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for stream input.
- EXPECT_LE(kBufferFrames, config_format_converter_frames);
- EXPECT_LE(kBufferFrames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC48from44Input) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_48;
- rstream_.direction = CRAS_STREAM_INPUT;
- in_fmt.frame_rate = 44100; // Device rate.
- out_fmt.frame_rate = 48000; // Stream rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream = dev_stream_create(&rstream_, 0, &fmt_s16le_44_1, (void*)0x55,
- &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for stream output.
- EXPECT_LE(kBufferFrames, config_format_converter_frames);
- EXPECT_LE(kBufferFrames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC8to48) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_8;
- in_fmt.frame_rate = 8000; // Stream rate.
- out_fmt.frame_rate = 48000; // Device rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream =
- dev_stream_create(&rstream_, 0, &fmt_s16le_48, (void*)0x55, &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for device output.
- unsigned int device_frames =
- cras_frames_at_rate(in_fmt.frame_rate, kBufferFrames, out_fmt.frame_rate);
- EXPECT_LE(kBufferFrames, device_frames); // Soundness check.
- EXPECT_LE(device_frames, config_format_converter_frames);
- EXPECT_LE(device_frames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC8from48Input) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_8;
- rstream_.direction = CRAS_STREAM_INPUT;
- in_fmt.frame_rate = 48000; // Device rate.
- out_fmt.frame_rate = 8000; // Stream rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream =
- dev_stream_create(&rstream_, 0, &fmt_s16le_48, (void*)0x55, &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for device input.
- unsigned int device_frames =
- cras_frames_at_rate(out_fmt.frame_rate, kBufferFrames, in_fmt.frame_rate);
- EXPECT_LE(kBufferFrames, device_frames); // Soundness check.
- EXPECT_LE(device_frames, config_format_converter_frames);
- EXPECT_LE(device_frames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC48to8) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_48;
- in_fmt.frame_rate = 48000; // Stream rate.
- out_fmt.frame_rate = 8000; // Device rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream =
- dev_stream_create(&rstream_, 0, &fmt_s16le_8, (void*)0x55, &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for stream input.
- EXPECT_LE(kBufferFrames, config_format_converter_frames);
- EXPECT_LE(kBufferFrames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC48from8Input) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_48;
- rstream_.direction = CRAS_STREAM_INPUT;
- in_fmt.frame_rate = 8000; // Device rate.
- out_fmt.frame_rate = 48000; // Stream rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream =
- dev_stream_create(&rstream_, 0, &fmt_s16le_8, (void*)0x55, &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for stream output.
- EXPECT_LE(kBufferFrames, config_format_converter_frames);
- EXPECT_LE(kBufferFrames, dev_stream->conv_buffer_size_frames);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CreateSRC48MonoFrom44StereoInput) {
- struct dev_stream* dev_stream;
-
- rstream_.format = fmt_s16le_48_mono;
- rstream_.direction = CRAS_STREAM_INPUT;
- in_fmt.frame_rate = 44100; // Device rate.
- out_fmt.frame_rate = 48000; // Stream rate.
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream = dev_stream_create(&rstream_, 0, &fmt_s16le_44_1, (void*)0x55,
- &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- // Converter tmp and output buffers are large enough for stream output.
- EXPECT_LE(kBufferFrames, config_format_converter_frames);
- EXPECT_LE(kBufferFrames, dev_stream->conv_buffer_size_frames);
- EXPECT_EQ(dev_stream->conv_buffer_size_frames * 4,
- dev_stream->conv_buffer->max_size);
- EXPECT_EQ(2, cras_audio_area_create_num_channels_val);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, CaptureAvailConvBufHasSamples) {
- struct dev_stream* dev_stream;
- unsigned int avail;
-
- rstream_.format = fmt_s16le_48;
- rstream_.direction = CRAS_STREAM_INPUT;
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream = dev_stream_create(&rstream_, 0, &fmt_s16le_44_1, (void*)0x55,
- &cb_ts, NULL);
- EXPECT_EQ(1, config_format_converter_called);
- EXPECT_NE(static_cast<byte_buffer*>(NULL), dev_stream->conv_buffer);
- EXPECT_LE(
- cras_frames_at_rate(in_fmt.frame_rate, kBufferFrames, out_fmt.frame_rate),
- dev_stream->conv_buffer_size_frames);
- EXPECT_EQ(dev_stream->conv_buffer_size_frames * 4,
- dev_stream->conv_buffer->max_size);
- EXPECT_EQ(2, cras_audio_area_create_num_channels_val);
-
- buf_increment_write(dev_stream->conv_buffer, 50 * 4);
- avail = dev_stream_capture_avail(dev_stream);
-
- EXPECT_EQ(cras_frames_at_rate(48000, 512 - 50, 44100), avail);
-
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, SetDevRateNotMainDev) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
-
- rstream_.format = fmt_s16le_48;
- rstream_.direction = CRAS_STREAM_INPUT;
- rstream_.main_dev.dev_id = 4;
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- dev_stream_set_dev_rate(dev_stream, 44100, 1.01, 1.0, 0);
- EXPECT_EQ(1, cras_fmt_conv_set_linear_resample_rates_called);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_from);
- EXPECT_EQ(44541, cras_fmt_conv_set_linear_resample_rates_to);
-
- dev_stream_set_dev_rate(dev_stream, 44100, 1.01, 1.0, 1);
- EXPECT_EQ(2, cras_fmt_conv_set_linear_resample_rates_called);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_from);
- EXPECT_LE(44541, cras_fmt_conv_set_linear_resample_rates_to);
-
- dev_stream_set_dev_rate(dev_stream, 44100, 1.0, 1.01, -1);
- EXPECT_EQ(3, cras_fmt_conv_set_linear_resample_rates_called);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_from);
- EXPECT_GE(43663, cras_fmt_conv_set_linear_resample_rates_to);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, SetDevRateMainDev) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- unsigned int expected_ts_nsec;
-
- rstream_.format = fmt_s16le_48;
- rstream_.direction = CRAS_STREAM_INPUT;
- rstream_.main_dev.dev_id = dev_id;
- config_format_converter_conv = reinterpret_cast<struct cras_fmt_conv*>(0x33);
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- dev_stream_set_dev_rate(dev_stream, 44100, 1.01, 1.0, 0);
- EXPECT_EQ(1, cras_fmt_conv_set_linear_resample_rates_called);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_from);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_to);
- expected_ts_nsec = 1000000000.0 * kBufferFrames / 2.0 / 48000.0 / 1.01;
- EXPECT_EQ(0, rstream_.sleep_interval_ts.tv_sec);
- EXPECT_EQ(expected_ts_nsec, rstream_.sleep_interval_ts.tv_nsec);
-
- dev_stream_set_dev_rate(dev_stream, 44100, 1.01, 1.0, 1);
- EXPECT_EQ(2, cras_fmt_conv_set_linear_resample_rates_called);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_from);
- EXPECT_LE(44100, cras_fmt_conv_set_linear_resample_rates_to);
- expected_ts_nsec = 1000000000.0 * kBufferFrames / 2.0 / 48000.0 / 1.01;
- EXPECT_EQ(0, rstream_.sleep_interval_ts.tv_sec);
- EXPECT_EQ(expected_ts_nsec, rstream_.sleep_interval_ts.tv_nsec);
-
- dev_stream_set_dev_rate(dev_stream, 44100, 1.0, 1.33, -1);
- EXPECT_EQ(3, cras_fmt_conv_set_linear_resample_rates_called);
- EXPECT_EQ(44100, cras_fmt_conv_set_linear_resample_rates_from);
- EXPECT_GE(44100, cras_fmt_conv_set_linear_resample_rates_to);
- expected_ts_nsec = 1000000000.0 * kBufferFrames / 2.0 / 48000.0;
- EXPECT_EQ(0, rstream_.sleep_interval_ts.tv_sec);
- EXPECT_EQ(expected_ts_nsec, rstream_.sleep_interval_ts.tv_nsec);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, StreamMixNoFrames) {
- struct dev_stream dev_stream;
- struct cras_audio_format fmt;
-
- dev_stream.conv = NULL;
- rstream_playable_frames_ret = 0;
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- EXPECT_EQ(0, dev_stream_mix(&dev_stream, &fmt, 0, 3));
-}
-
-TEST_F(CreateSuite, StreamMixNoConv) {
- struct dev_stream dev_stream;
- const unsigned int nfr = 100;
- struct cras_audio_format fmt;
-
- dev_stream.conv = NULL;
- dev_stream.stream = reinterpret_cast<cras_rstream*>(0x5446);
- rstream_playable_frames_ret = nfr;
- rstream_get_readable_num = nfr;
- rstream_get_readable_ptr = reinterpret_cast<uint8_t*>(0x4000);
- rstream_get_readable_call.num_called = 0;
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- EXPECT_EQ(nfr, dev_stream_mix(&dev_stream, &fmt, (uint8_t*)0x5000, nfr));
- EXPECT_EQ((int16_t*)0x5000, mix_add_call.dst);
- EXPECT_EQ((int16_t*)0x4000, mix_add_call.src);
- EXPECT_EQ(200, mix_add_call.count);
- EXPECT_EQ(1, mix_add_call.index);
- EXPECT_EQ(dev_stream.stream, rstream_get_readable_call.rstream);
- EXPECT_EQ(0, rstream_get_readable_call.offset);
- EXPECT_EQ(1, rstream_get_readable_call.num_called);
-}
-
-TEST_F(CreateSuite, StreamMixNoConvTwoPass) {
- struct dev_stream dev_stream;
- const unsigned int nfr = 100;
- const unsigned int bytes_per_sample = 2;
- const unsigned int num_channels = 2;
- const unsigned int bytes_per_frame = bytes_per_sample * num_channels;
- struct cras_audio_format fmt;
-
- dev_stream.conv = NULL;
- dev_stream.stream = reinterpret_cast<cras_rstream*>(0x5446);
- rstream_playable_frames_ret = nfr;
- rstream_get_readable_num = nfr / 2;
- rstream_get_readable_ptr = reinterpret_cast<uint8_t*>(0x4000);
- rstream_get_readable_call.num_called = 0;
- fmt.num_channels = 2;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- EXPECT_EQ(nfr, dev_stream_mix(&dev_stream, &fmt, (uint8_t*)0x5000, nfr));
- const unsigned int half_offset = nfr / 2 * bytes_per_frame;
- EXPECT_EQ((int16_t*)(0x5000 + half_offset), mix_add_call.dst);
- EXPECT_EQ((int16_t*)0x4000, mix_add_call.src);
- EXPECT_EQ(nfr / 2 * num_channels, mix_add_call.count);
- EXPECT_EQ(1, mix_add_call.index);
- EXPECT_EQ(dev_stream.stream, rstream_get_readable_call.rstream);
- EXPECT_EQ(nfr / 2, rstream_get_readable_call.offset);
- EXPECT_EQ(2, rstream_get_readable_call.num_called);
-}
-
-TEST_F(CreateSuite, DevStreamFlushAudioMessages) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
-
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- dev_stream_flush_old_audio_messages(dev_stream);
- EXPECT_EQ(1, cras_rstream_flush_old_audio_messages_called);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, DevStreamIsPending) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
-
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- // dev_stream_is_pending_reply is only a wrapper.
- cras_rstream_is_pending_reply_ret = 0;
- EXPECT_EQ(0, dev_stream_is_pending_reply(dev_stream));
-
- cras_rstream_is_pending_reply_ret = 1;
- EXPECT_EQ(1, dev_stream_is_pending_reply(dev_stream));
-
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, StreamCanSend) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- int written_frames;
- int rc;
- struct timespec expected_next_cb_ts;
-
- rstream_.direction = CRAS_STREAM_INPUT;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- // Assume there is a next_cb_ts on rstream.
- rstream_.next_cb_ts.tv_sec = 1;
- rstream_.next_cb_ts.tv_nsec = 0;
-
- // Case 1: Not enough samples. Time is not late enough.
- // Stream can not send data to client.
- clock_gettime_retspec.tv_sec = 0;
- clock_gettime_retspec.tv_nsec = 0;
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(0, cras_rstream_audio_ready_called);
- EXPECT_EQ(0, cras_server_metrics_missed_cb_event_called);
- EXPECT_EQ(0, rc);
-
- // Case 2: Not enough samples. Time is late enough.
- // Stream can not send data to client.
-
- // Assume time is greater than next_cb_ts.
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 500;
- // However, written frames is less than cb_threshold.
- // Stream still can not send samples to client.
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(0, cras_rstream_audio_ready_called);
- EXPECT_EQ(0, cras_server_metrics_missed_cb_event_called);
- EXPECT_EQ(0, rc);
-
- // Case 3: Enough samples. Time is not late enough.
- // Stream can not send data to client.
-
- // Assume time is less than next_cb_ts.
- clock_gettime_retspec.tv_sec = 0;
- clock_gettime_retspec.tv_nsec = 0;
- // Enough samples are written.
- written_frames = rstream_.cb_threshold + 10;
- cras_shm_buffer_written(rstream_.shm, written_frames);
- // Stream still can not send samples to client.
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(0, cras_rstream_audio_ready_called);
- EXPECT_EQ(0, cras_server_metrics_missed_cb_event_called);
- EXPECT_EQ(0, rc);
-
- // Case 4: Enough samples. Time is late enough.
- // Stream should send one cb_threshold to client.
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 500;
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(1, cras_rstream_audio_ready_called);
- EXPECT_EQ(rstream_.cb_threshold, cras_rstream_audio_ready_count);
- EXPECT_EQ(0, cras_server_metrics_missed_cb_event_called);
- EXPECT_EQ(0, rc);
-
- // Check next_cb_ts is increased by one sleep interval.
- expected_next_cb_ts.tv_sec = 1;
- expected_next_cb_ts.tv_nsec = 0;
- add_timespecs(&expected_next_cb_ts, &rstream_.sleep_interval_ts);
- EXPECT_EQ(expected_next_cb_ts.tv_sec, rstream_.next_cb_ts.tv_sec);
- EXPECT_EQ(expected_next_cb_ts.tv_nsec, rstream_.next_cb_ts.tv_nsec);
-
- // Reset stub data of interest.
- cras_rstream_audio_ready_called = 0;
- cras_rstream_audio_ready_count = 0;
- rstream_.next_cb_ts.tv_sec = 1;
- rstream_.next_cb_ts.tv_nsec = 0;
-
- // Case 5: Enough samples. Time is late enough and it is too late
- // such that a new next_cb_ts is in the past.
- // Stream should send one cb_threshold to client and reset schedule.
- clock_gettime_retspec.tv_sec = 2;
- clock_gettime_retspec.tv_nsec = 0;
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(1, cras_rstream_audio_ready_called);
- EXPECT_EQ(rstream_.cb_threshold, cras_rstream_audio_ready_count);
- EXPECT_EQ(1, cras_server_metrics_missed_cb_event_called);
- EXPECT_EQ(0, rc);
-
- // Check next_cb_ts is rest to be now plus one sleep interval.
- expected_next_cb_ts.tv_sec = 2;
- expected_next_cb_ts.tv_nsec = 0;
- add_timespecs(&expected_next_cb_ts, &rstream_.sleep_interval_ts);
- EXPECT_EQ(expected_next_cb_ts.tv_sec, rstream_.next_cb_ts.tv_sec);
- EXPECT_EQ(expected_next_cb_ts.tv_nsec, rstream_.next_cb_ts.tv_nsec);
-
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, StreamCanSendBulkAudio) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- int written_frames;
- int rc;
- struct timespec expected_next_cb_ts;
-
- rstream_.direction = CRAS_STREAM_INPUT;
- rstream_.flags |= BULK_AUDIO_OK;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- // Assume there is a next_cb_ts on rstream.
- rstream_.next_cb_ts.tv_sec = 1;
- rstream_.next_cb_ts.tv_nsec = 0;
-
- // Case 1: Not enough samples. Time is not late enough.
- // Bulk audio stream can not send data to client.
- clock_gettime_retspec.tv_sec = 0;
- clock_gettime_retspec.tv_nsec = 0;
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(0, cras_rstream_audio_ready_called);
- EXPECT_EQ(0, rc);
-
- // Case 2: Not enough samples. Time is late enough.
- // Bulk audio stream can not send data to client.
-
- // Assume time is greater than next_cb_ts.
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 500;
- // However, written frames is less than cb_threshold.
- // Stream still can not send samples to client.
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(0, cras_rstream_audio_ready_called);
- EXPECT_EQ(0, rc);
-
- // Case 3: Enough samples. Time is not late enough.
- // Bulk audio stream CAN send data to client.
-
- // Assume time is less than next_cb_ts.
- clock_gettime_retspec.tv_sec = 0;
- clock_gettime_retspec.tv_nsec = 0;
- // Enough samples are written.
- written_frames = rstream_.cb_threshold + 10;
- cras_shm_buffer_written(rstream_.shm, written_frames);
- // Bulk audio stream can send all written samples to client.
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(1, cras_rstream_audio_ready_called);
- EXPECT_EQ(written_frames, cras_rstream_audio_ready_count);
- EXPECT_EQ(0, rc);
-
- // Case 4: Enough samples. Time is late enough.
- // Bulk audio stream can send all written samples to client.
-
- // Reset stub data of interest.
- cras_rstream_audio_ready_called = 0;
- cras_rstream_audio_ready_count = 0;
- rstream_.next_cb_ts.tv_sec = 1;
- rstream_.next_cb_ts.tv_nsec = 0;
-
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 500;
- rc = dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(1, cras_rstream_audio_ready_called);
- EXPECT_EQ(written_frames, cras_rstream_audio_ready_count);
- EXPECT_EQ(0, rc);
-
- // Check next_cb_ts is increased by one sleep interval.
- expected_next_cb_ts.tv_sec = 1;
- expected_next_cb_ts.tv_nsec = 0;
- add_timespecs(&expected_next_cb_ts, &rstream_.sleep_interval_ts);
- EXPECT_EQ(expected_next_cb_ts.tv_sec, rstream_.next_cb_ts.tv_sec);
- EXPECT_EQ(expected_next_cb_ts.tv_nsec, rstream_.next_cb_ts.tv_nsec);
-
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, TriggerOnlyStreamSendOnlyOnce) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
-
- rstream_.direction = CRAS_STREAM_INPUT;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
- dev_stream->stream->flags = TRIGGER_ONLY;
- dev_stream->stream->triggered = 0;
-
- // Check first trigger callback called.
- cras_shm_buffer_written(rstream_.shm, rstream_.cb_threshold);
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 0;
- dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(1, cras_rstream_audio_ready_called);
- EXPECT_EQ(1, dev_stream->stream->triggered);
-
- // No future callback will be called for TRIGGER_ONLY streams.
- cras_shm_buffer_written(rstream_.shm, rstream_.cb_threshold);
- clock_gettime_retspec.tv_sec = 2;
- clock_gettime_retspec.tv_nsec = 0;
- dev_stream_capture_update_rstream(dev_stream);
- EXPECT_EQ(1, cras_rstream_audio_ready_called);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, InputDevStreamWakeTimeByNextCbTs) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- int rc;
- unsigned int curr_level = 0;
- int written_frames;
- struct timespec level_tstamp = {.tv_sec = 1, .tv_nsec = 0};
- struct timespec wake_time_out = {.tv_sec = 0, .tv_nsec = 0};
-
- rstream_.direction = CRAS_STREAM_INPUT;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- // Assume there is a next_cb_ts on rstream.
- rstream_.next_cb_ts.tv_sec = 1;
- rstream_.next_cb_ts.tv_nsec = 500000;
-
- // Assume there are enough samples for stream.
- written_frames = rstream_.cb_threshold + 10;
- cras_shm_buffer_written(rstream_.shm, written_frames);
-
- rc = dev_stream_wake_time(dev_stream, curr_level, &level_tstamp,
- rstream_.cb_threshold, 0, &wake_time_out);
-
- // The next wake up time is determined by next_cb_ts on dev_stream.
- EXPECT_EQ(rstream_.next_cb_ts.tv_sec, wake_time_out.tv_sec);
- EXPECT_EQ(rstream_.next_cb_ts.tv_nsec, wake_time_out.tv_nsec);
- EXPECT_EQ(0, rc);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, InputDevStreamWakeTimeByDevice) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- int rc;
- unsigned int curr_level = 100;
- int written_frames;
- struct timespec level_tstamp = {.tv_sec = 1, .tv_nsec = 0};
- struct timespec wake_time_out = {.tv_sec = 0, .tv_nsec = 0};
- struct timespec expected_tstamp = {.tv_sec = 0, .tv_nsec = 0};
- struct timespec needed_time_for_device = {.tv_sec = 0, .tv_nsec = 0};
- int needed_frames_from_device = 0;
-
- rstream_.direction = CRAS_STREAM_INPUT;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_48, (void*)0x55,
- &cb_ts, NULL);
-
- // Assume there is a next_cb_ts on rstream, that is, 1.005 seconds.
- rstream_.next_cb_ts.tv_sec = 1;
- rstream_.next_cb_ts.tv_nsec = 5000000; // 5ms
-
- // Assume there are not enough samples for stream.
- written_frames = 123;
- cras_shm_buffer_written(rstream_.shm, written_frames);
-
- // Compute wake up time for device level to reach enough samples
- // for one cb_threshold:
- // Device has 100 samples (48K rate).
- // Stream has 123 samples (44.1K rate)
- // cb_threshold = 512 samples.
- // Stream needs 512 - 123 = 389 samples.
- // Converted to device rate => 389 * 48000.0 / 44100 = 423.4 samples
- // => 424 samples.
- // Device needs another 424 - 100 = 324 samples.
- // Time for 252 samples = 324 / 48000 = 0.00675 sec.
- // So expected wake up time for samples is at level_tstamp + 0.00675 sec =
- // 1.00675 seconds.
- needed_frames_from_device =
- cras_frames_at_rate(44100, rstream_.cb_threshold - written_frames, 48000);
- needed_frames_from_device -= curr_level;
- cras_frames_to_time(needed_frames_from_device, 48000,
- &needed_time_for_device);
-
- expected_tstamp.tv_sec = level_tstamp.tv_sec;
- expected_tstamp.tv_nsec = level_tstamp.tv_nsec;
-
- add_timespecs(&expected_tstamp, &needed_time_for_device);
-
- // Set the stub data for cras_fmt_conv_out_frames_to_in.
- out_fmt.frame_rate = 44100;
- in_fmt.frame_rate = 48000;
-
- rc = dev_stream_wake_time(dev_stream, curr_level, &level_tstamp,
- rstream_.cb_threshold, 0, &wake_time_out);
-
- // The next wake up time is determined by needed time for device level
- // to reach enough samples for one cb_threshold.
- EXPECT_EQ(expected_tstamp.tv_sec, wake_time_out.tv_sec);
- EXPECT_EQ(expected_tstamp.tv_nsec, wake_time_out.tv_nsec);
- EXPECT_EQ(0, rc);
-
- // Assume current level is larger than cb_threshold.
- // The wake up time is determined by next_cb_ts.
- curr_level += rstream_.cb_threshold;
- rc = dev_stream_wake_time(dev_stream, curr_level, &level_tstamp,
- rstream_.cb_threshold, 0, &wake_time_out);
- EXPECT_EQ(rstream_.next_cb_ts.tv_sec, wake_time_out.tv_sec);
- EXPECT_EQ(rstream_.next_cb_ts.tv_nsec, wake_time_out.tv_nsec);
- EXPECT_EQ(0, rc);
- dev_stream_destroy(dev_stream);
-}
-
-TEST_F(CreateSuite, UpdateNextWakeTime) {
- struct dev_stream* dev_stream;
- unsigned int dev_id = 9;
- struct timespec expected_next_cb_ts;
-
- rstream_.direction = CRAS_STREAM_OUTPUT;
- dev_stream = dev_stream_create(&rstream_, dev_id, &fmt_s16le_44_1,
- (void*)0x55, &cb_ts, NULL);
-
- // Case 1: The new next_cb_ts is greater than now. Do not need to reschedule.
- rstream_.next_cb_ts.tv_sec = 2;
- rstream_.next_cb_ts.tv_nsec = 0;
- clock_gettime_retspec.tv_sec = 2;
- clock_gettime_retspec.tv_nsec = 500;
- expected_next_cb_ts = rstream_.next_cb_ts;
-
- dev_stream_update_next_wake_time(dev_stream);
- EXPECT_EQ(0, cras_server_metrics_missed_cb_event_called);
- add_timespecs(&expected_next_cb_ts, &rstream_.sleep_interval_ts);
- EXPECT_EQ(expected_next_cb_ts.tv_sec, rstream_.next_cb_ts.tv_sec);
- EXPECT_EQ(expected_next_cb_ts.tv_nsec, rstream_.next_cb_ts.tv_nsec);
-
- // Case 2: The new next_cb_ts is less than now. Need to reset schedule.
- rstream_.next_cb_ts.tv_sec = 2;
- rstream_.next_cb_ts.tv_nsec = 0;
- clock_gettime_retspec.tv_sec = 3;
- clock_gettime_retspec.tv_nsec = 0;
- expected_next_cb_ts = clock_gettime_retspec;
-
- dev_stream_update_next_wake_time(dev_stream);
- EXPECT_EQ(1, cras_server_metrics_missed_cb_event_called);
- add_timespecs(&expected_next_cb_ts, &rstream_.sleep_interval_ts);
- EXPECT_EQ(expected_next_cb_ts.tv_sec, rstream_.next_cb_ts.tv_sec);
- EXPECT_EQ(expected_next_cb_ts.tv_nsec, rstream_.next_cb_ts.tv_nsec);
- dev_stream_destroy(dev_stream);
-}
-
-// Test set_playback_timestamp.
-TEST(DevStreamTimimg, SetPlaybackTimeStampSimple) {
- struct cras_timespec ts;
-
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 0;
- cras_set_playback_timestamp(48000, 24000, &ts);
- EXPECT_EQ(1, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 499900000);
- EXPECT_LE(ts.tv_nsec, 500100000);
-}
-
-TEST(DevStreamTimimg, SetPlaybackTimeStampWrap) {
- struct cras_timespec ts;
-
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 750000000;
- cras_set_playback_timestamp(48000, 24000, &ts);
- EXPECT_EQ(2, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 249900000);
- EXPECT_LE(ts.tv_nsec, 250100000);
-}
-
-TEST(DevStreamTimimg, SetPlaybackTimeStampWrapTwice) {
- struct cras_timespec ts;
-
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 750000000;
- cras_set_playback_timestamp(48000, 72000, &ts);
- EXPECT_EQ(3, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 249900000);
- EXPECT_LE(ts.tv_nsec, 250100000);
-}
-
-// Test set_capture_timestamp.
-TEST(DevStreamTimimg, SetCaptureTimeStampSimple) {
- struct cras_timespec ts;
-
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 750000000;
- cras_set_capture_timestamp(48000, 24000, &ts);
- EXPECT_EQ(1, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 249900000);
- EXPECT_LE(ts.tv_nsec, 250100000);
-}
-
-TEST(DevStreamTimimg, SetCaptureTimeStampWrap) {
- struct cras_timespec ts;
-
- clock_gettime_retspec.tv_sec = 1;
- clock_gettime_retspec.tv_nsec = 0;
- cras_set_capture_timestamp(48000, 24000, &ts);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 499900000);
- EXPECT_LE(ts.tv_nsec, 500100000);
-}
-
-TEST(DevStreamTimimg, SetCaptureTimeStampWrapPartial) {
- struct cras_timespec ts;
-
- clock_gettime_retspec.tv_sec = 2;
- clock_gettime_retspec.tv_nsec = 750000000;
- cras_set_capture_timestamp(48000, 72000, &ts);
- EXPECT_EQ(1, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 249900000);
- EXPECT_LE(ts.tv_nsec, 250100000);
-}
-
-TEST(MaxFramesForConverter, 8to48) {
- EXPECT_EQ(481, max_frames_for_conversion(80, // Stream frames.
- 8000, // Stream rate.
- 48000)); // Device rate.
-}
-
-TEST(MaxFramesForConverter, 48to8) {
- EXPECT_EQ(81, max_frames_for_conversion(80, // Stream frames.
- 48000, // Stream rate.
- 8000)); // Device rate.
-}
-
-/* Stubs */
-extern "C" {
-
-int cras_rstream_audio_ready(struct cras_rstream* stream, size_t count) {
- cras_rstream_audio_ready_count = count;
- cras_rstream_audio_ready_called++;
- return 0;
-}
-
-int cras_rstream_request_audio(struct cras_rstream* stream,
- const struct timespec* now) {
- return 0;
-}
-
-void cras_rstream_record_fetch_interval(struct cras_rstream* rstream,
- const struct timespec* now) {}
-
-void cras_rstream_update_input_write_pointer(struct cras_rstream* rstream) {}
-
-void cras_rstream_update_output_read_pointer(struct cras_rstream* rstream) {}
-
-void cras_rstream_dev_offset_update(struct cras_rstream* rstream,
- unsigned int frames,
- unsigned int dev_id) {}
-
-void cras_rstream_dev_attach(struct cras_rstream* rstream,
- unsigned int dev_id,
- void* dev_ptr) {}
-
-void cras_rstream_dev_detach(struct cras_rstream* rstream,
- unsigned int dev_id) {}
-
-unsigned int cras_rstream_dev_offset(const struct cras_rstream* rstream,
- unsigned int dev_id) {
- return 0;
-}
-
-unsigned int cras_rstream_playable_frames(struct cras_rstream* rstream,
- unsigned int dev_id) {
- return rstream_playable_frames_ret;
-}
-
-float cras_rstream_get_volume_scaler(struct cras_rstream* rstream) {
- return 1.0;
-}
-
-uint8_t* cras_rstream_get_readable_frames(struct cras_rstream* rstream,
- unsigned int offset,
- size_t* frames) {
- rstream_get_readable_call.rstream = rstream;
- rstream_get_readable_call.offset = offset;
- rstream_get_readable_call.num_called++;
- *frames = rstream_get_readable_num;
- return rstream_get_readable_ptr;
-}
-
-int cras_rstream_get_mute(const struct cras_rstream* rstream) {
- return 0;
-}
-void cras_rstream_update_queued_frames(struct cras_rstream* rstream) {}
-
-struct cras_audio_format* cras_rstream_post_processing_format(
- const struct cras_rstream* stream,
- void* dev_ptr) {
- return cras_rstream_post_processing_format_val;
-}
-void* buffer_share_get_data(const struct buffer_share* mix, unsigned int id) {
- return NULL;
-};
-void cras_apm_list_start_apm(struct cras_apm_list* list, void* dev_ptr){};
-void cras_apm_list_stop_apm(struct cras_apm_list* list, void* dev_ptr){};
-
-int config_format_converter(struct cras_fmt_conv** conv,
- enum CRAS_STREAM_DIRECTION dir,
- const struct cras_audio_format* from,
- const struct cras_audio_format* to,
- unsigned int frames) {
- config_format_converter_called++;
- config_format_converter_from_fmt = from;
- config_format_converter_frames = frames;
- *conv = config_format_converter_conv;
- return 0;
-}
-
-void cras_fmt_conv_destroy(struct cras_fmt_conv* conv) {}
-
-size_t cras_fmt_conv_convert_frames(struct cras_fmt_conv* conv,
- uint8_t* in_buf,
- uint8_t* out_buf,
- unsigned int* in_frames,
- unsigned int out_frames) {
- unsigned int ret;
- conv_frames_call.conv = conv;
- conv_frames_call.in_buf = in_buf;
- conv_frames_call.out_buf = out_buf;
- conv_frames_call.in_frames = *in_frames;
- ret = cras_frames_at_rate(in_fmt.frame_rate, *in_frames, out_fmt.frame_rate);
- conv_frames_call.out_frames = out_frames;
- if (ret > out_frames) {
- ret = out_frames;
- *in_frames =
- cras_frames_at_rate(out_fmt.frame_rate, ret, in_fmt.frame_rate);
- }
-
- return ret;
-}
-
-void cras_mix_add(snd_pcm_format_t fmt,
- uint8_t* dst,
- uint8_t* src,
- unsigned int count,
- unsigned int index,
- int mute,
- float mix_vol) {
- mix_add_call.dst = (int16_t*)dst;
- mix_add_call.src = (int16_t*)src;
- mix_add_call.count = count;
- mix_add_call.index = index;
- mix_add_call.mute = mute;
- mix_add_call.mix_vol = mix_vol;
-}
-
-struct cras_audio_area* cras_audio_area_create(int num_channels) {
- cras_audio_area_create_num_channels_val = num_channels;
- return NULL;
-}
-
-void cras_audio_area_destroy(struct cras_audio_area* area) {}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {}
-
-void cras_audio_area_config_channels(struct cras_audio_area* area,
- const struct cras_audio_format* fmt) {}
-
-unsigned int cras_audio_area_copy(const struct cras_audio_area* dst,
- unsigned int dst_offset,
- const struct cras_audio_format* dst_fmt,
- const struct cras_audio_area* src,
- unsigned int src_offset,
- float software_gain_scaler) {
- copy_area_call.dst = dst;
- copy_area_call.dst_offset = dst_offset;
- copy_area_call.dst_format_bytes = cras_get_format_bytes(dst_fmt);
- copy_area_call.src = src;
- copy_area_call.src_offset = src_offset;
- copy_area_call.software_gain_scaler = software_gain_scaler;
- return src->frames;
-}
-
-size_t cras_fmt_conv_in_frames_to_out(struct cras_fmt_conv* conv,
- size_t in_frames) {
- return cras_frames_at_rate(in_fmt.frame_rate, in_frames, out_fmt.frame_rate);
-}
-
-size_t cras_fmt_conv_out_frames_to_in(struct cras_fmt_conv* conv,
- size_t out_frames) {
- return cras_frames_at_rate(out_fmt.frame_rate, out_frames, in_fmt.frame_rate);
-}
-
-const struct cras_audio_format* cras_fmt_conv_in_format(
- const struct cras_fmt_conv* conv) {
- return &in_fmt;
-}
-
-const struct cras_audio_format* cras_fmt_conv_out_format(
- const struct cras_fmt_conv* conv) {
- return &out_fmt;
-}
-
-int cras_fmt_conversion_needed(const struct cras_fmt_conv* conv) {
- return cras_fmt_conversion_needed_val;
-}
-
-void cras_fmt_conv_set_linear_resample_rates(struct cras_fmt_conv* conv,
- float from,
- float to) {
- cras_fmt_conv_set_linear_resample_rates_from = from;
- cras_fmt_conv_set_linear_resample_rates_to = to;
- cras_fmt_conv_set_linear_resample_rates_called++;
-}
-
-int cras_rstream_is_pending_reply(const struct cras_rstream* stream) {
- return cras_rstream_is_pending_reply_ret;
-}
-
-int cras_rstream_flush_old_audio_messages(struct cras_rstream* stream) {
- cras_rstream_flush_old_audio_messages_called++;
- return 0;
-}
-
-int cras_server_metrics_missed_cb_event(struct cras_rstream* stream) {
- cras_server_metrics_missed_cb_event_called++;
- return 0;
-}
-
-// From librt.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = clock_gettime_retspec.tv_sec;
- tp->tv_nsec = clock_gettime_retspec.tv_nsec;
- return 0;
-}
-
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/device_blocklist_unittest.cc b/cras/src/tests/device_blocklist_unittest.cc
deleted file mode 100644
index 44a976e1..00000000
--- a/cras/src/tests/device_blocklist_unittest.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_device_blocklist.h"
-}
-
-namespace {
-
-static const char CONFIG_PATH[] = CRAS_UT_TMPDIR;
-static const char CONFIG_FILENAME[] = "device_blocklist";
-
-void CreateConfigFile(const char* config_text) {
- FILE* f;
- char card_path[128];
-
- snprintf(card_path, sizeof(card_path), "%s/%s", CONFIG_PATH, CONFIG_FILENAME);
- f = fopen(card_path, "w");
- if (f == NULL)
- return;
-
- fprintf(f, "%s", config_text);
-
- fclose(f);
-}
-
-TEST(Blocklist, EmptyBlocklist) {
- static const char empty_config_text[] = "";
- struct cras_device_blocklist* blocklist;
-
- CreateConfigFile(empty_config_text);
-
- blocklist = cras_device_blocklist_create(CONFIG_PATH);
- ASSERT_NE(static_cast<cras_device_blocklist*>(NULL), blocklist);
- EXPECT_EQ(0, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0008, 0, 0));
-
- cras_device_blocklist_destroy(blocklist);
-}
-
-TEST(Blocklist, BlockListOneUsbOutput) {
- static const char usb_output_config_text[] =
- "[USB_Outputs]\n"
- "0d8c_0008_00000012_0 = 1\n";
- struct cras_device_blocklist* blocklist;
-
- CreateConfigFile(usb_output_config_text);
-
- blocklist = cras_device_blocklist_create(CONFIG_PATH);
- ASSERT_NE(static_cast<cras_device_blocklist*>(NULL), blocklist);
-
- EXPECT_EQ(0, cras_device_blocklist_check(blocklist, 0x0d8d, 0x0008, 0x12, 0));
- EXPECT_EQ(0, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0009, 0x12, 0));
- EXPECT_EQ(0, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0008, 0x13, 0));
- EXPECT_EQ(0, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0008, 0x12, 1));
- EXPECT_EQ(1, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0008, 0x12, 0));
-
- cras_device_blocklist_destroy(blocklist);
-}
-
-TEST(Blocklist, BlockListTwoUsbOutput) {
- static const char usb_output_config_text[] =
- "[USB_Outputs]\n"
- "0d8c_0008_00000000_0 = 1\n"
- "0d8c_0009_00000000_0 = 1\n";
- struct cras_device_blocklist* blocklist;
-
- CreateConfigFile(usb_output_config_text);
-
- blocklist = cras_device_blocklist_create(CONFIG_PATH);
- ASSERT_NE(static_cast<cras_device_blocklist*>(NULL), blocklist);
-
- EXPECT_EQ(1, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0009, 0, 0));
- EXPECT_EQ(1, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0008, 0, 0));
- EXPECT_EQ(0, cras_device_blocklist_check(blocklist, 0x0d8c, 0x0008, 0, 1));
-
- cras_device_blocklist_destroy(blocklist);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/device_monitor_unittest.cc b/cras/src/tests/device_monitor_unittest.cc
deleted file mode 100644
index 31c2e8c6..00000000
--- a/cras/src/tests/device_monitor_unittest.cc
+++ /dev/null
@@ -1,150 +0,0 @@
-// Copyright 2016 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_device_monitor.c"
-#include "cras_iodev.h"
-#include "cras_main_message.h"
-}
-
-static enum CRAS_MAIN_MESSAGE_TYPE type_set;
-static struct cras_device_monitor_message* sent_msg;
-static int resume_dev_called;
-unsigned int resume_dev_idx;
-static int suspend_dev_called;
-unsigned int suspend_dev_idx;
-static int set_mute_called;
-unsigned int mute_dev_idx;
-unsigned int fake_dev_idx = 123;
-
-void ResetStubData() {
- type_set = (enum CRAS_MAIN_MESSAGE_TYPE)0;
- resume_dev_called = 0;
- resume_dev_idx = 0;
- suspend_dev_called = 0;
- suspend_dev_idx = 0;
- set_mute_called = 0;
- mute_dev_idx = 0;
-}
-
-namespace {
-
-TEST(DeviceMonitorTestSuite, Init) {
- ResetStubData();
-
- cras_device_monitor_init();
-
- EXPECT_EQ(type_set, CRAS_MAIN_MONITOR_DEVICE);
-}
-
-TEST(DeviceMonitorTestSuite, ResetDevice) {
- ResetStubData();
- // sent_msg will be filled with message content in cras_main_message_send.
- sent_msg = (struct cras_device_monitor_message*)calloc(1, sizeof(*sent_msg));
-
- cras_device_monitor_reset_device(fake_dev_idx);
-
- EXPECT_EQ(sent_msg->header.type, CRAS_MAIN_MONITOR_DEVICE);
- EXPECT_EQ(sent_msg->header.length, sizeof(*sent_msg));
- EXPECT_EQ(sent_msg->message_type, RESET_DEVICE);
- EXPECT_EQ(sent_msg->dev_idx, fake_dev_idx);
-
- free(sent_msg);
-}
-
-TEST(DeviceMonitorTestSuite, HandleResetDevice) {
- struct cras_device_monitor_message msg;
- struct cras_main_message* main_message =
- reinterpret_cast<struct cras_main_message*>(&msg);
-
- ResetStubData();
-
- // Filled msg with message content for resetting device.
- init_device_msg(&msg, RESET_DEVICE, fake_dev_idx);
- // Assume the pipe works fine and main message handler receives the same
- // message.
- handle_device_message(main_message, NULL);
-
- // Verify that disable/enable functions are called with correct device.
- EXPECT_EQ(resume_dev_called, 1);
- EXPECT_EQ(resume_dev_idx, fake_dev_idx);
- EXPECT_EQ(suspend_dev_called, 1);
- EXPECT_EQ(suspend_dev_idx, fake_dev_idx);
-}
-
-TEST(DeviceMonitorTestSuite, MuteDevice) {
- ResetStubData();
- // sent_msg will be filled with message content in cras_main_message_send.
- sent_msg = (struct cras_device_monitor_message*)calloc(1, sizeof(*sent_msg));
-
- cras_device_monitor_set_device_mute_state(fake_dev_idx);
-
- EXPECT_EQ(sent_msg->header.type, CRAS_MAIN_MONITOR_DEVICE);
- EXPECT_EQ(sent_msg->header.length, sizeof(*sent_msg));
- EXPECT_EQ(sent_msg->message_type, SET_MUTE_STATE);
- EXPECT_EQ(sent_msg->dev_idx, fake_dev_idx);
-
- free(sent_msg);
-}
-
-TEST(DeviceMonitorTestSuite, HandleMuteDevice) {
- struct cras_device_monitor_message msg;
- struct cras_main_message* main_message =
- reinterpret_cast<struct cras_main_message*>(&msg);
-
- ResetStubData();
-
- // Filled msg with message content for device mute/unmute.
- init_device_msg(&msg, SET_MUTE_STATE, fake_dev_idx);
- // Assume the pipe works fine and main message handler receives the same
- // message.
- handle_device_message(main_message, NULL);
-
- // Verify that cras_iodev_set_mute is called with correct device.
- EXPECT_EQ(set_mute_called, 1);
- EXPECT_EQ(mute_dev_idx, fake_dev_idx);
-}
-
-extern "C" {
-
-int cras_main_message_add_handler(enum CRAS_MAIN_MESSAGE_TYPE type,
- cras_message_callback callback,
- void* callback_data) {
- type_set = type;
- return 0;
-}
-
-int cras_main_message_send(struct cras_main_message* msg) {
- // Copy the sent message so we can examine it in the test later.
- memcpy(sent_msg, msg, sizeof(*sent_msg));
- return 0;
-};
-
-void cras_iodev_list_resume_dev(unsigned int dev_idx) {
- resume_dev_called++;
- resume_dev_idx = dev_idx;
-}
-
-void cras_iodev_list_suspend_dev(unsigned int dev_idx) {
- suspend_dev_called++;
- suspend_dev_idx = dev_idx;
-}
-
-void cras_iodev_list_set_dev_mute(unsigned int dev_idx) {
- set_mute_called++;
- mute_dev_idx = dev_idx;
-}
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- int rc = RUN_ALL_TESTS();
-
- return rc;
-}
diff --git a/cras/src/tests/dsp_core_unittest.cc b/cras/src/tests/dsp_core_unittest.cc
deleted file mode 100644
index 82c7957b..00000000
--- a/cras/src/tests/dsp_core_unittest.cc
+++ /dev/null
@@ -1,433 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <math.h>
-
-#include "crossover.h"
-#include "crossover2.h"
-#include "drc.h"
-#include "dsp_util.h"
-#include "eq.h"
-#include "eq2.h"
-
-namespace {
-
-/* Adds amplitude * sin(pi*freq*i + offset) to the data array. */
-static void add_sine(float* data,
- size_t len,
- float freq,
- float offset,
- float amplitude) {
- for (size_t i = 0; i < len; i++)
- data[i] += amplitude * sinf((float)M_PI * freq * i + offset);
-}
-
-/* Calculates the magnitude at normalized frequency f. The output is
- * the result of DFT, multiplied by 2/len. */
-static float magnitude_at(float* data, size_t len, float f) {
- double re = 0, im = 0;
- f *= (float)M_PI;
- for (size_t i = 0; i < len; i++) {
- re += data[i] * cos(i * f);
- im += data[i] * sin(i * f);
- }
- return sqrt(re * re + im * im) * (2.0 / len);
-}
-
-TEST(InterleaveTest, All) {
- const int FRAMES = 12;
- const int SAMPLES = FRAMES * 2;
-
- /* Repeat the same data twice, so it will exercise neon/sse
- * optimized functions. */
- int16_t input[SAMPLES] = {
- -32768, -32767, -32766, -2, -1, 0, 1, 2, 3, 32765, 32766, 32767,
- -32768, -32767, -32766, -2, -1, 0, 1, 2, 3, 32765, 32766, 32767};
-
- float answer[SAMPLES] = {-1,
- -32766 / 32768.0f,
- -1 / 32768.0f,
- 1 / 32768.0f,
- 3 / 32768.0f,
- 32766 / 32768.0f,
- -1,
- -32766 / 32768.0f,
- -1 / 32768.0f,
- 1 / 32768.0f,
- 3 / 32768.0f,
- 32766 / 32768.0f,
- -32767 / 32768.0f,
- -2 / 32768.0f,
- 0,
- 2 / 32768.0f,
- 32765 / 32768.0f,
- 32767 / 32768.0f,
- -32767 / 32768.0f,
- -2 / 32768.0f,
- 0,
- 2 / 32768.0f,
- 32765 / 32768.0f,
- 32767 / 32768.0f};
-
- float output[SAMPLES];
- float* out_ptr[] = {output, output + FRAMES};
-
- dsp_util_deinterleave((uint8_t*)input, out_ptr, 2, SND_PCM_FORMAT_S16_LE,
- FRAMES);
-
- for (int i = 0; i < SAMPLES; i++) {
- EXPECT_EQ(answer[i], output[i]);
- }
-
- /* dsp_util_interleave() should round to nearest number. */
- for (int i = 0; i < SAMPLES; i += 2) {
- output[i] += 0.499 / 32768.0f;
- output[i + 1] -= 0.499 / 32768.0f;
- }
-
- int16_t output2[SAMPLES];
- dsp_util_interleave(out_ptr, (uint8_t*)output2, 2, SND_PCM_FORMAT_S16_LE,
- FRAMES);
- for (int i = 0; i < SAMPLES; i++) {
- EXPECT_EQ(input[i], output2[i]);
- }
-}
-
-TEST(EqTest, All) {
- struct eq* eq;
- size_t len = 44100;
- float NQ = len / 2;
- float f_low = 10 / NQ;
- float f_mid = 100 / NQ;
- float f_high = 1000 / NQ;
- float* data = (float*)malloc(sizeof(float) * len);
-
- dsp_enable_flush_denormal_to_zero();
- /* low pass */
- memset(data, 0, sizeof(float) * len);
- add_sine(data, len, f_low, 0, 1); // 10Hz sine, magnitude = 1
- EXPECT_FLOAT_EQ(1, magnitude_at(data, len, f_low));
- add_sine(data, len, f_high, 0, 1); // 1000Hz sine, magnitude = 1
- EXPECT_FLOAT_EQ(1, magnitude_at(data, len, f_low));
- EXPECT_FLOAT_EQ(1, magnitude_at(data, len, f_high));
-
- eq = eq_new();
- EXPECT_EQ(0, eq_append_biquad(eq, BQ_LOWPASS, f_mid, 0, 0));
- eq_process(eq, data, len);
- EXPECT_NEAR(1, magnitude_at(data, len, f_low), 0.01);
- EXPECT_NEAR(0, magnitude_at(data, len, f_high), 0.01);
-
- /* Test for empty input */
- eq_process(eq, NULL, 0);
-
- eq_free(eq);
-
- /* high pass */
- memset(data, 0, sizeof(float) * len);
- add_sine(data, len, f_low, 0, 1);
- add_sine(data, len, f_high, 0, 1);
-
- eq = eq_new();
- EXPECT_EQ(0, eq_append_biquad(eq, BQ_HIGHPASS, f_mid, 0, 0));
- eq_process(eq, data, len);
- EXPECT_NEAR(0, magnitude_at(data, len, f_low), 0.01);
- EXPECT_NEAR(1, magnitude_at(data, len, f_high), 0.01);
- eq_free(eq);
-
- /* peaking */
- memset(data, 0, sizeof(float) * len);
- add_sine(data, len, f_low, 0, 1);
- add_sine(data, len, f_high, 0, 1);
-
- eq = eq_new();
- EXPECT_EQ(0,
- eq_append_biquad(eq, BQ_PEAKING, f_high, 5, 6)); // Q=5, 6dB gain
- eq_process(eq, data, len);
- EXPECT_NEAR(1, magnitude_at(data, len, f_low), 0.01);
- EXPECT_NEAR(2, magnitude_at(data, len, f_high), 0.01);
- eq_free(eq);
-
- free(data);
-
- /* Too many biquads */
- eq = eq_new();
- for (int i = 0; i < MAX_BIQUADS_PER_EQ; i++) {
- EXPECT_EQ(0, eq_append_biquad(eq, BQ_PEAKING, f_high, 5, 6));
- }
- EXPECT_EQ(-1, eq_append_biquad(eq, BQ_PEAKING, f_high, 5, 6));
- eq_free(eq);
-}
-
-TEST(Eq2Test, All) {
- struct eq2* eq2;
- size_t len = 44100;
- float NQ = len / 2;
- float f_low = 10 / NQ;
- float f_mid = 100 / NQ;
- float f_high = 1000 / NQ;
- float* data0 = (float*)malloc(sizeof(float) * len);
- float* data1 = (float*)malloc(sizeof(float) * len);
-
- dsp_enable_flush_denormal_to_zero();
-
- /* a mixture of 10Hz an 1000Hz sine */
- memset(data0, 0, sizeof(float) * len);
- memset(data1, 0, sizeof(float) * len);
- add_sine(data0, len, f_low, 0, 1); // 10Hz sine, magnitude = 1
- add_sine(data0, len, f_high, 0, 1); // 1000Hz sine, magnitude = 1
- add_sine(data1, len, f_low, 0, 1); // 10Hz sine, magnitude = 1
- add_sine(data1, len, f_high, 0, 1); // 1000Hz sine, magnitude = 1
-
- /* low pass at left and high pass at right */
- eq2 = eq2_new();
- EXPECT_EQ(0, eq2_append_biquad(eq2, 0, BQ_LOWPASS, f_mid, 0, 0));
- EXPECT_EQ(0, eq2_append_biquad(eq2, 1, BQ_HIGHPASS, f_mid, 0, 0));
- eq2_process(eq2, data0, data1, len);
- EXPECT_NEAR(1, magnitude_at(data0, len, f_low), 0.01);
- EXPECT_NEAR(0, magnitude_at(data0, len, f_high), 0.01);
- EXPECT_NEAR(0, magnitude_at(data1, len, f_low), 0.01);
- EXPECT_NEAR(1, magnitude_at(data1, len, f_high), 0.01);
-
- /* Test for empty input */
- eq2_process(eq2, NULL, NULL, 0);
- eq2_free(eq2);
-
- /* a mixture of 10Hz and 1000Hz sine */
- memset(data0, 0, sizeof(float) * len);
- memset(data1, 0, sizeof(float) * len);
- add_sine(data0, len, f_low, 0, 1);
- add_sine(data0, len, f_high, 0, 1);
- add_sine(data1, len, f_low, 0, 1);
- add_sine(data1, len, f_high, 0, 1);
-
- /* one high-shelving biquad at left and two low-shelving biquads at right */
- eq2 = eq2_new();
- EXPECT_EQ(0, eq2_append_biquad(eq2, 0, BQ_HIGHSHELF, f_mid, 5, 6));
- EXPECT_EQ(0, eq2_append_biquad(eq2, 1, BQ_LOWSHELF, f_mid, 0, -6));
- EXPECT_EQ(0, eq2_append_biquad(eq2, 1, BQ_LOWSHELF, f_mid, 0, -6));
-
- eq2_process(eq2, data0, data1, len);
- EXPECT_NEAR(1, magnitude_at(data0, len, f_low), 0.01);
- EXPECT_NEAR(2, magnitude_at(data0, len, f_high), 0.01);
- EXPECT_NEAR(0.25, magnitude_at(data1, len, f_low), 0.01);
- EXPECT_NEAR(1, magnitude_at(data1, len, f_high), 0.01);
- eq2_free(eq2);
-
- free(data0);
- free(data1);
-
- /* Too many biquads */
- eq2 = eq2_new();
- for (int i = 0; i < MAX_BIQUADS_PER_EQ2; i++) {
- EXPECT_EQ(0, eq2_append_biquad(eq2, 0, BQ_PEAKING, f_high, 5, 6));
- EXPECT_EQ(0, eq2_append_biquad(eq2, 1, BQ_PEAKING, f_high, 5, 6));
- }
- EXPECT_EQ(-1, eq2_append_biquad(eq2, 0, BQ_PEAKING, f_high, 5, 6));
- EXPECT_EQ(-1, eq2_append_biquad(eq2, 1, BQ_PEAKING, f_high, 5, 6));
- eq2_free(eq2);
-}
-
-TEST(CrossoverTest, All) {
- struct crossover xo;
- size_t len = 44100;
- float NQ = len / 2;
- float f0 = 62.5 / NQ;
- float f1 = 250 / NQ;
- float f2 = 1000 / NQ;
- float f3 = 4000 / NQ;
- float f4 = 16000 / NQ;
- float* data = (float*)malloc(sizeof(float) * len);
- float* data1 = (float*)malloc(sizeof(float) * len);
- float* data2 = (float*)malloc(sizeof(float) * len);
-
- dsp_enable_flush_denormal_to_zero();
- crossover_init(&xo, f1, f3);
- memset(data, 0, sizeof(float) * len);
- add_sine(data, len, f0, 0, 1);
- add_sine(data, len, f2, 0, 1);
- add_sine(data, len, f4, 0, 1);
-
- crossover_process(&xo, len, data, data1, data2);
-
- // low band
- EXPECT_NEAR(1, magnitude_at(data, len, f0), 0.01);
- EXPECT_NEAR(0, magnitude_at(data, len, f2), 0.01);
- EXPECT_NEAR(0, magnitude_at(data, len, f4), 0.01);
-
- // mid band
- EXPECT_NEAR(0, magnitude_at(data1, len, f0), 0.01);
- EXPECT_NEAR(1, magnitude_at(data1, len, f2), 0.01);
- EXPECT_NEAR(0, magnitude_at(data1, len, f4), 0.01);
-
- // high band
- EXPECT_NEAR(0, magnitude_at(data2, len, f0), 0.01);
- EXPECT_NEAR(0, magnitude_at(data2, len, f2), 0.01);
- EXPECT_NEAR(1, magnitude_at(data2, len, f4), 0.01);
-
- /* Test for empty input */
- crossover_process(&xo, 0, NULL, NULL, NULL);
-
- free(data);
- free(data1);
- free(data2);
-}
-
-TEST(Crossover2Test, All) {
- struct crossover2 xo2;
- size_t len = 44100;
- float NQ = len / 2;
- float f0 = 62.5 / NQ;
- float f1 = 250 / NQ;
- float f2 = 1000 / NQ;
- float f3 = 4000 / NQ;
- float f4 = 16000 / NQ;
- float* data0L = (float*)malloc(sizeof(float) * len);
- float* data1L = (float*)malloc(sizeof(float) * len);
- float* data2L = (float*)malloc(sizeof(float) * len);
- float* data0R = (float*)malloc(sizeof(float) * len);
- float* data1R = (float*)malloc(sizeof(float) * len);
- float* data2R = (float*)malloc(sizeof(float) * len);
-
- dsp_enable_flush_denormal_to_zero();
- crossover2_init(&xo2, f1, f3);
- memset(data0L, 0, sizeof(float) * len);
- memset(data0R, 0, sizeof(float) * len);
-
- add_sine(data0L, len, f0, 0, 1);
- add_sine(data0L, len, f2, 0, 1);
- add_sine(data0L, len, f4, 0, 1);
-
- add_sine(data0R, len, f0, 0, 0.5);
- add_sine(data0R, len, f2, 0, 0.5);
- add_sine(data0R, len, f4, 0, 0.5);
-
- crossover2_process(&xo2, len, data0L, data0R, data1L, data1R, data2L, data2R);
-
- // left low band
- EXPECT_NEAR(1, magnitude_at(data0L, len, f0), 0.01);
- EXPECT_NEAR(0, magnitude_at(data0L, len, f2), 0.01);
- EXPECT_NEAR(0, magnitude_at(data0L, len, f4), 0.01);
-
- // left mid band
- EXPECT_NEAR(0, magnitude_at(data1L, len, f0), 0.01);
- EXPECT_NEAR(1, magnitude_at(data1L, len, f2), 0.01);
- EXPECT_NEAR(0, magnitude_at(data1L, len, f4), 0.01);
-
- // left high band
- EXPECT_NEAR(0, magnitude_at(data2L, len, f0), 0.01);
- EXPECT_NEAR(0, magnitude_at(data2L, len, f2), 0.01);
- EXPECT_NEAR(1, magnitude_at(data2L, len, f4), 0.01);
-
- // right low band
- EXPECT_NEAR(0.5, magnitude_at(data0R, len, f0), 0.005);
- EXPECT_NEAR(0, magnitude_at(data0R, len, f2), 0.005);
- EXPECT_NEAR(0, magnitude_at(data0R, len, f4), 0.005);
-
- // right mid band
- EXPECT_NEAR(0, magnitude_at(data1R, len, f0), 0.005);
- EXPECT_NEAR(0.5, magnitude_at(data1R, len, f2), 0.005);
- EXPECT_NEAR(0, magnitude_at(data1R, len, f4), 0.005);
-
- // right high band
- EXPECT_NEAR(0, magnitude_at(data2R, len, f0), 0.005);
- EXPECT_NEAR(0, magnitude_at(data2R, len, f2), 0.005);
- EXPECT_NEAR(0.5, magnitude_at(data2R, len, f4), 0.005);
-
- /* Test for empty input */
- crossover2_process(&xo2, 0, NULL, NULL, NULL, NULL, NULL, NULL);
-
- free(data0L);
- free(data1L);
- free(data2L);
- free(data0R);
- free(data1R);
- free(data2R);
-}
-
-TEST(DrcTest, All) {
- size_t len = 44100;
- float NQ = len / 2;
- float f0 = 62.5 / NQ;
- float f1 = 250 / NQ;
- float f2 = 1000 / NQ;
- float f3 = 4000 / NQ;
- float f4 = 16000 / NQ;
- float* data_left = (float*)malloc(sizeof(float) * len);
- float* data_right = (float*)malloc(sizeof(float) * len);
- float* data[] = {data_left, data_right};
- float* data_empty[] = {NULL, NULL};
- struct drc* drc;
-
- dsp_enable_flush_denormal_to_zero();
- drc = drc_new(44100);
-
- drc_set_param(drc, 0, PARAM_CROSSOVER_LOWER_FREQ, 0);
- drc_set_param(drc, 0, PARAM_ENABLED, 1);
- drc_set_param(drc, 0, PARAM_THRESHOLD, -30);
- drc_set_param(drc, 0, PARAM_KNEE, 0);
- drc_set_param(drc, 0, PARAM_RATIO, 3);
- drc_set_param(drc, 0, PARAM_ATTACK, 0.02);
- drc_set_param(drc, 0, PARAM_RELEASE, 0.2);
- drc_set_param(drc, 0, PARAM_POST_GAIN, 0);
-
- drc_set_param(drc, 1, PARAM_CROSSOVER_LOWER_FREQ, f1);
- drc_set_param(drc, 1, PARAM_ENABLED, 0);
- drc_set_param(drc, 1, PARAM_THRESHOLD, -30);
- drc_set_param(drc, 1, PARAM_KNEE, 0);
- drc_set_param(drc, 1, PARAM_RATIO, 3);
- drc_set_param(drc, 1, PARAM_ATTACK, 0.02);
- drc_set_param(drc, 1, PARAM_RELEASE, 0.2);
- drc_set_param(drc, 1, PARAM_POST_GAIN, 0);
-
- drc_set_param(drc, 2, PARAM_CROSSOVER_LOWER_FREQ, f3);
- drc_set_param(drc, 2, PARAM_ENABLED, 1);
- drc_set_param(drc, 2, PARAM_THRESHOLD, -30);
- drc_set_param(drc, 2, PARAM_KNEE, 0);
- drc_set_param(drc, 2, PARAM_RATIO, 1);
- drc_set_param(drc, 2, PARAM_ATTACK, 0.02);
- drc_set_param(drc, 2, PARAM_RELEASE, 0.2);
- drc_set_param(drc, 2, PARAM_POST_GAIN, 20);
-
- drc_init(drc);
-
- memset(data_left, 0, sizeof(float) * len);
- memset(data_right, 0, sizeof(float) * len);
- add_sine(data_left, len, f0, 0, 1);
- add_sine(data_left, len, f2, 0, 1);
- add_sine(data_left, len, f4, 0, 1);
- add_sine(data_right, len, f0, 0, 1);
- add_sine(data_right, len, f2, 0, 1);
- add_sine(data_right, len, f4, 0, 1);
-
- for (size_t start = 0; start < len; start += DRC_PROCESS_MAX_FRAMES) {
- int chunk = std::min(len - start, (size_t)DRC_PROCESS_MAX_FRAMES);
- drc_process(drc, data, chunk);
- data[0] += chunk;
- data[1] += chunk;
- }
-
- /* This is -8dB because there is a 12dB makeup (20dB^0.6) inside the DRC */
- EXPECT_NEAR(0.4, magnitude_at(data_right, len, f0), 0.1);
-
- /* This is 0dB because the DRC is disabled */
- EXPECT_NEAR(1, magnitude_at(data_right, len, f2), 0.1);
-
- /* This is 20dB because of the post gain */
- EXPECT_NEAR(10, magnitude_at(data_right, len, f4), 1);
-
- /* Test for empty input */
- drc_process(drc, data_empty, 0);
-
- drc_free(drc);
- free(data_left);
- free(data_right);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/dsp_ini_unittest.cc b/cras/src/tests/dsp_ini_unittest.cc
deleted file mode 100644
index ee187906..00000000
--- a/cras/src/tests/dsp_ini_unittest.cc
+++ /dev/null
@@ -1,308 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "cras_dsp_ini.h"
-
-#define FILENAME_TEMPLATE "DspIniTest.XXXXXX"
-
-namespace {
-
-class DspIniTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- strcpy(filename, FILENAME_TEMPLATE);
- int fd = mkstemp(filename);
- fp = fdopen(fd, "w");
- }
-
- virtual void TearDown() {
- CloseFile();
- unlink(filename);
- }
-
- virtual void CloseFile() {
- if (fp) {
- fclose(fp);
- fp = NULL;
- }
- }
-
- char filename[sizeof(FILENAME_TEMPLATE) + 1];
- FILE* fp;
-};
-
-TEST_F(DspIniTestSuite, EmptyIni) {
- struct ini* ini = cras_dsp_ini_create(filename);
- EXPECT_EQ(0, ARRAY_COUNT(&ini->plugins));
- EXPECT_EQ(0, ARRAY_COUNT(&ini->flows));
- cras_dsp_ini_free(ini);
-}
-
-TEST_F(DspIniTestSuite, NoLibraryOrLabel) {
- fprintf(fp, "[Test]\n");
- CloseFile();
-
- struct ini* ini = cras_dsp_ini_create(filename);
- /* NULL because a plugin doesn't have library or label */
- EXPECT_EQ(NULL, ini);
-}
-
-TEST_F(DspIniTestSuite, OneSimplePlugin) {
- fprintf(fp, "[Test]\n");
- fprintf(fp, "library=foo.so\n");
- fprintf(fp, "label=bar\n");
- fprintf(fp, "disable=\"#f\"\n");
- CloseFile();
-
- struct ini* ini = cras_dsp_ini_create(filename);
- EXPECT_EQ(1, ARRAY_COUNT(&ini->plugins));
- EXPECT_EQ(0, ARRAY_COUNT(&ini->flows));
-
- struct plugin* plugin = ARRAY_ELEMENT(&ini->plugins, 0);
- EXPECT_STREQ("test", plugin->title);
- EXPECT_STREQ("foo.so", plugin->library);
- EXPECT_STREQ("bar", plugin->label);
- EXPECT_TRUE(plugin->disable_expr);
- EXPECT_EQ(0, ARRAY_COUNT(&plugin->ports));
-
- cras_dsp_ini_free(ini);
-}
-
-TEST_F(DspIniTestSuite, BuiltinPlugin) {
- fprintf(fp, "[foo]\n");
- fprintf(fp, "library=builtin\n");
- fprintf(fp, "label=source\n");
- fprintf(fp, "purpose=playback\n");
- fprintf(fp, "[bar]\n");
- fprintf(fp, "library=builtin\n");
- fprintf(fp, "label=sink\n");
- fprintf(fp, "purpose=capture\n");
- CloseFile();
-
- struct ini* ini = cras_dsp_ini_create(filename);
- EXPECT_EQ(2, ARRAY_COUNT(&ini->plugins));
- EXPECT_EQ(0, ARRAY_COUNT(&ini->flows));
- EXPECT_STREQ(ARRAY_ELEMENT(&ini->plugins, 0)->purpose, "playback");
- EXPECT_STREQ(ARRAY_ELEMENT(&ini->plugins, 1)->purpose, "capture");
- cras_dsp_ini_free(ini);
-}
-
-TEST_F(DspIniTestSuite, Ports) {
- fprintf(fp, "[foo]\n");
- fprintf(fp, "library=bar\n");
- fprintf(fp, "label=baz\n");
- fprintf(fp, "input_0=10\n");
- CloseFile();
-
- struct ini* ini = cras_dsp_ini_create(filename);
- EXPECT_EQ(1, ARRAY_COUNT(&ini->plugins));
- EXPECT_EQ(0, ARRAY_COUNT(&ini->flows));
- struct plugin* plugin = ARRAY_ELEMENT(&ini->plugins, 0);
- EXPECT_EQ(1, ARRAY_COUNT(&plugin->ports));
- struct port* port = ARRAY_ELEMENT(&plugin->ports, 0);
- EXPECT_EQ(PORT_INPUT, port->direction);
- EXPECT_EQ(PORT_CONTROL, port->type);
- EXPECT_EQ(INVALID_FLOW_ID, port->flow_id);
- EXPECT_EQ(10, port->init_value);
- cras_dsp_ini_free(ini);
-}
-
-TEST_F(DspIniTestSuite, Flows) {
- fprintf(fp, "[foo]\n");
- fprintf(fp, "library=foo\n");
- fprintf(fp, "label=foo\n");
- fprintf(fp, "output_0=<control>\n");
- fprintf(fp, "output_1={audio}\n");
- fprintf(fp, "[bar]\n");
- fprintf(fp, "library=bar\n");
- fprintf(fp, "label=bar\n");
- fprintf(fp, "input_0={audio}\n");
- fprintf(fp, "input_1=<control>\n");
-
- CloseFile();
-
- struct ini* ini = cras_dsp_ini_create(filename);
- EXPECT_EQ(2, ARRAY_COUNT(&ini->plugins));
- struct plugin* foo = ARRAY_ELEMENT(&ini->plugins, 0);
- struct plugin* bar = ARRAY_ELEMENT(&ini->plugins, 1);
- EXPECT_EQ(2, ARRAY_COUNT(&foo->ports));
- EXPECT_EQ(2, ARRAY_COUNT(&bar->ports));
-
- struct port* foo0 = ARRAY_ELEMENT(&foo->ports, 0);
- struct port* foo1 = ARRAY_ELEMENT(&foo->ports, 1);
- EXPECT_EQ(PORT_OUTPUT, foo0->direction);
- EXPECT_EQ(PORT_CONTROL, foo0->type);
- EXPECT_EQ(PORT_OUTPUT, foo1->direction);
- EXPECT_EQ(PORT_AUDIO, foo1->type);
- EXPECT_EQ(0, foo0->flow_id);
- EXPECT_EQ(1, foo1->flow_id);
-
- struct port* bar0 = ARRAY_ELEMENT(&bar->ports, 0);
- struct port* bar1 = ARRAY_ELEMENT(&bar->ports, 1);
- EXPECT_EQ(PORT_INPUT, bar0->direction);
- EXPECT_EQ(PORT_AUDIO, bar0->type);
- EXPECT_EQ(PORT_INPUT, bar1->direction);
- EXPECT_EQ(PORT_CONTROL, bar1->type);
- EXPECT_EQ(1, bar0->flow_id);
- EXPECT_EQ(0, bar1->flow_id);
-
- EXPECT_EQ(2, ARRAY_COUNT(&ini->flows));
- struct flow* flow0 = ARRAY_ELEMENT(&ini->flows, 0);
- struct flow* flow1 = ARRAY_ELEMENT(&ini->flows, 1);
-
- EXPECT_EQ(PORT_CONTROL, flow0->type);
- EXPECT_STREQ("<control>", flow0->name);
-
- EXPECT_EQ(PORT_AUDIO, flow1->type);
- EXPECT_STREQ("{audio}", flow1->name);
-
- EXPECT_EQ(flow0->from, foo);
- EXPECT_EQ(flow0->to, bar);
- EXPECT_EQ(flow0->from_port, 0);
- EXPECT_EQ(flow0->to_port, 1);
-
- EXPECT_EQ(flow1->from, foo);
- EXPECT_EQ(flow1->to, bar);
- EXPECT_EQ(flow1->from_port, 1);
- EXPECT_EQ(flow1->to_port, 0);
-
- cras_dsp_ini_free(ini);
-}
-
-TEST_F(DspIniTestSuite, TwoChannelWithSwap) {
- /*
- * Stated in ini:
- *
- * m0 ==(a0, a1)== m1 ==(b0, b1)== m2
- *
- * After inserting swap_lr plugin:
- *
- * m0 ==(a0, a1)== m1 ==(b0, b1)== m_swap_lr ==(swap_lr_0, swap_lr_1)== m2
- *
- */
-
- const char* content =
- "[M0]\n"
- "library=builtin\n"
- "label=source\n"
- "purpose=playback\n"
- "output_0={a0}\n"
- "output_1={a1}\n"
- "[M1]\n"
- "library=builtin\n"
- "label=foo\n"
- "purpose=playback\n"
- "input_0={a0}\n"
- "input_1={a1}\n"
- "output_2={b0}\n"
- "output_3={b1}\n"
- "[M2]\n"
- "library=builtin\n"
- "label=sink\n"
- "purpose=playback\n"
- "input_0={b0}\n"
- "input_1={b1}\n";
- fprintf(fp, "%s", content);
- CloseFile();
-
- struct ini* ini = cras_dsp_ini_create(filename);
-
- /* 3 plugins and 1 swap_lr plugin. */
- EXPECT_EQ(4, ARRAY_COUNT(&ini->plugins));
-
- struct plugin* m0 = ARRAY_ELEMENT(&ini->plugins, 0);
- struct plugin* m1 = ARRAY_ELEMENT(&ini->plugins, 1);
- struct plugin* m2 = ARRAY_ELEMENT(&ini->plugins, 2);
- struct plugin* m_swap_lr = ARRAY_ELEMENT(&ini->plugins, 3);
-
- EXPECT_EQ(2, ARRAY_COUNT(&m0->ports));
- EXPECT_EQ(4, ARRAY_COUNT(&m1->ports));
- EXPECT_EQ(4, ARRAY_COUNT(&m_swap_lr->ports));
- EXPECT_EQ(2, ARRAY_COUNT(&m2->ports));
-
- struct port* m0_0 = ARRAY_ELEMENT(&m0->ports, 0);
- struct port* m0_1 = ARRAY_ELEMENT(&m0->ports, 1);
- struct port* m1_0 = ARRAY_ELEMENT(&m1->ports, 0);
- struct port* m1_1 = ARRAY_ELEMENT(&m1->ports, 1);
- struct port* m1_2 = ARRAY_ELEMENT(&m1->ports, 2);
- struct port* m1_3 = ARRAY_ELEMENT(&m1->ports, 3);
- struct port* m_swap_lr_0 = ARRAY_ELEMENT(&m_swap_lr->ports, 0);
- struct port* m_swap_lr_1 = ARRAY_ELEMENT(&m_swap_lr->ports, 1);
- struct port* m_swap_lr_2 = ARRAY_ELEMENT(&m_swap_lr->ports, 2);
- struct port* m_swap_lr_3 = ARRAY_ELEMENT(&m_swap_lr->ports, 3);
- struct port* m2_0 = ARRAY_ELEMENT(&m2->ports, 0);
- struct port* m2_1 = ARRAY_ELEMENT(&m2->ports, 1);
-
- /* flow flow_id from port to port
- * ------------------------------------------------------------
- * a0 0 m0_0 m1_0
- * a1 1 m0_1 m1_1
- * b0 2 m1_2 m_swap_lr_0
- * b1 3 m1_3 m_swap_lr_1
- * swap_lr_0 4 m_swap_lr_2 m2_0
- * swap_lr_1 5 m_swap_lr_3 m2_1
- */
- EXPECT_EQ(0, m0_0->flow_id);
- EXPECT_EQ(1, m0_1->flow_id);
- EXPECT_EQ(0, m1_0->flow_id);
- EXPECT_EQ(1, m1_1->flow_id);
- EXPECT_EQ(2, m1_2->flow_id);
- EXPECT_EQ(3, m1_3->flow_id);
- EXPECT_EQ(2, m_swap_lr_0->flow_id);
- EXPECT_EQ(3, m_swap_lr_1->flow_id);
- EXPECT_EQ(4, m_swap_lr_2->flow_id);
- EXPECT_EQ(5, m_swap_lr_3->flow_id);
- EXPECT_EQ(4, m2_0->flow_id);
- EXPECT_EQ(5, m2_1->flow_id);
-
- struct flow* flow_a0 = ARRAY_ELEMENT(&ini->flows, 0);
- struct flow* flow_a1 = ARRAY_ELEMENT(&ini->flows, 1);
- struct flow* flow_b0 = ARRAY_ELEMENT(&ini->flows, 2);
- struct flow* flow_b1 = ARRAY_ELEMENT(&ini->flows, 3);
- struct flow* flow_swap_lr_0 = ARRAY_ELEMENT(&ini->flows, 4);
- struct flow* flow_swap_lr_1 = ARRAY_ELEMENT(&ini->flows, 5);
-
- EXPECT_EQ(flow_a0->from, m0);
- EXPECT_EQ(flow_a0->from_port, 0);
- EXPECT_EQ(flow_a0->to, m1);
- EXPECT_EQ(flow_a0->to_port, 0);
-
- EXPECT_EQ(flow_a1->from, m0);
- EXPECT_EQ(flow_a1->from_port, 1);
- EXPECT_EQ(flow_a1->to, m1);
- EXPECT_EQ(flow_a1->to_port, 1);
-
- EXPECT_EQ(flow_b0->from, m1);
- EXPECT_EQ(flow_b0->from_port, 2);
- EXPECT_EQ(flow_b0->to, m_swap_lr);
- EXPECT_EQ(flow_b0->to_port, 0);
-
- EXPECT_EQ(flow_b1->from, m1);
- EXPECT_EQ(flow_b1->from_port, 3);
- EXPECT_EQ(flow_b1->to, m_swap_lr);
- EXPECT_EQ(flow_b1->to_port, 1);
-
- EXPECT_EQ(flow_swap_lr_0->from, m_swap_lr);
- EXPECT_EQ(flow_swap_lr_0->from_port, 2);
- EXPECT_EQ(flow_swap_lr_0->to, m2);
- EXPECT_EQ(flow_swap_lr_0->to_port, 0);
-
- EXPECT_EQ(flow_swap_lr_1->from, m_swap_lr);
- EXPECT_EQ(flow_swap_lr_1->from_port, 3);
- EXPECT_EQ(flow_swap_lr_1->to, m2);
- EXPECT_EQ(flow_swap_lr_1->to_port, 1);
-
- cras_dsp_ini_free(ini);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/dsp_unittest.cc b/cras/src/tests/dsp_unittest.cc
deleted file mode 100644
index b1f4c4ee..00000000
--- a/cras/src/tests/dsp_unittest.cc
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-#include "cras_dsp.h"
-#include "cras_dsp_module.h"
-
-#define FILENAME_TEMPLATE "DspTest.XXXXXX"
-
-namespace {
-
-extern "C" {
-struct dsp_module* cras_dsp_module_load_ladspa(struct plugin* plugin) {
- return NULL;
-}
-}
-
-class DspTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- strcpy(filename, FILENAME_TEMPLATE);
- int fd = mkstemp(filename);
- fp = fdopen(fd, "w");
- }
-
- virtual void TearDown() {
- CloseFile();
- unlink(filename);
- }
-
- virtual void CloseFile() {
- if (fp) {
- fclose(fp);
- fp = NULL;
- }
- }
-
- char filename[sizeof(FILENAME_TEMPLATE) + 1];
- FILE* fp;
-};
-
-TEST_F(DspTestSuite, Simple) {
- const char* content =
- "[M1]\n"
- "library=builtin\n"
- "label=source\n"
- "purpose=capture\n"
- "output_0={audio}\n"
- "disable=(not (equal? variable \"foo\"))\n"
- "[M2]\n"
- "library=builtin\n"
- "label=sink\n"
- "purpose=capture\n"
- "input_0={audio}\n"
- "\n";
- fprintf(fp, "%s", content);
- CloseFile();
-
- cras_dsp_init(filename);
- struct cras_dsp_context *ctx1, *ctx3, *ctx4;
- ctx1 = cras_dsp_context_new(44100, "playback"); /* wrong purpose */
- ctx3 = cras_dsp_context_new(44100, "capture");
- ctx4 = cras_dsp_context_new(44100, "capture");
-
- cras_dsp_set_variable_string(ctx1, "variable", "foo");
- cras_dsp_set_variable_string(ctx3, "variable", "bar"); /* wrong value */
- cras_dsp_set_variable_string(ctx4, "variable", "foo");
-
- cras_dsp_load_pipeline(ctx1);
- cras_dsp_load_pipeline(ctx3);
- cras_dsp_load_pipeline(ctx4);
-
- /* only ctx4 should load the pipeline successfully */
- ASSERT_EQ(NULL, cras_dsp_get_pipeline(ctx1));
- ASSERT_EQ(NULL, cras_dsp_get_pipeline(ctx3));
-
- struct pipeline* pipeline = cras_dsp_get_pipeline(ctx4);
- ASSERT_TRUE(pipeline);
- cras_dsp_put_pipeline(ctx4);
-
- /* change the variable to a wrong value, and we should fail to reload. */
- cras_dsp_set_variable_string(ctx4, "variable", "bar");
- cras_dsp_load_pipeline(ctx4);
- ASSERT_EQ(NULL, cras_dsp_get_pipeline(ctx4));
-
- /* change the variable back, and we should reload successfully. */
- cras_dsp_set_variable_string(ctx4, "variable", "foo");
- cras_dsp_reload_ini();
- ASSERT_TRUE(cras_dsp_get_pipeline(ctx4));
-
- cras_dsp_context_free(ctx1);
- cras_dsp_context_free(ctx3);
- cras_dsp_context_free(ctx4);
- cras_dsp_stop();
-}
-
-static int empty_instantiate(struct dsp_module* module,
- unsigned long sample_rate) {
- return 0;
-}
-
-static void empty_connect_port(struct dsp_module* module,
- unsigned long port,
- float* data_location) {}
-
-static int empty_get_delay(struct dsp_module* module) {
- return 0;
-}
-
-static void empty_run(struct dsp_module* module, unsigned long sample_count) {}
-
-static void empty_deinstantiate(struct dsp_module* module) {}
-
-static void empty_free_module(struct dsp_module* module) {
- free(module);
-}
-
-static int empty_get_properties(struct dsp_module* module) {
- return 0;
-}
-
-static void empty_dump(struct dsp_module* module, struct dumper* d) {
- dumpf(d, "built-in module\n");
-}
-
-static void empty_init_module(struct dsp_module* module) {
- module->instantiate = &empty_instantiate;
- module->connect_port = &empty_connect_port;
- module->get_delay = &empty_get_delay;
- module->run = &empty_run;
- module->deinstantiate = &empty_deinstantiate;
- module->free_module = &empty_free_module;
- module->get_properties = &empty_get_properties;
- module->dump = &empty_dump;
-}
-
-} // namespace
-
-extern "C" {
-struct dsp_module* cras_dsp_module_load_builtin(struct plugin* plugin) {
- struct dsp_module* module;
- module = (struct dsp_module*)calloc(1, sizeof(struct dsp_module));
- empty_init_module(module);
- return module;
-}
-void cras_dsp_module_set_sink_ext_module(struct dsp_module* module,
- struct ext_dsp_module* ext_module) {}
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/dumper_unittest.cc b/cras/src/tests/dumper_unittest.cc
deleted file mode 100644
index 7bd1421a..00000000
--- a/cras/src/tests/dumper_unittest.cc
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "dumper.h"
-
-#include <gtest/gtest.h>
-#include <syslog.h>
-
-namespace {
-
-TEST(DumperTest, SyslogDumper) {
- struct dumper* dumper = syslog_dumper_create(LOG_ERR);
- dumpf(dumper, "hello %d", 1);
- dumpf(dumper, "world %d\n123", 2);
- dumpf(dumper, "456\n");
- // The following should appear in syslog:
- // dumper_unittest: hello 1world 2
- // dumper_unittest: 123456
- syslog_dumper_free(dumper);
-}
-
-TEST(DumperTest, MemDumper) {
- struct dumper* dumper = mem_dumper_create();
- char* buf;
- int size, i;
-
- mem_dumper_get(dumper, &buf, &size);
- EXPECT_STREQ("", buf);
-
- dumpf(dumper, "hello %d\n", 1);
- mem_dumper_get(dumper, &buf, &size);
- EXPECT_STREQ("hello 1\n", buf);
- EXPECT_EQ(8, size);
-
- dumpf(dumper, "world %d", 2);
- mem_dumper_get(dumper, &buf, &size);
- EXPECT_STREQ("hello 1\nworld 2", buf);
- EXPECT_EQ(15, size);
-
- mem_dumper_clear(dumper);
- mem_dumper_get(dumper, &buf, &size);
- EXPECT_STREQ("", buf);
- EXPECT_EQ(0, size);
-
- for (i = 0; i < 1000; i++) {
- dumpf(dumper, "a");
- }
- mem_dumper_get(dumper, &buf, &size);
- EXPECT_EQ(1000, strlen(buf));
- EXPECT_EQ(1000, 1000);
-
- mem_dumper_free(dumper);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/edid_utils_unittest.cc b/cras/src/tests/edid_utils_unittest.cc
deleted file mode 100644
index 6b059afc..00000000
--- a/cras/src/tests/edid_utils_unittest.cc
+++ /dev/null
@@ -1,274 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "edid_utils.h"
-
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <stdio.h>
-
-#include "cras_util.h"
-
-namespace {
-
-class EDIDTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- static const uint8_t header[] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
- };
-
- memcpy(edid_, header, sizeof(header));
- SetChecksum();
- }
-
- void SetChecksum() {
- uint8_t sum = 0;
-
- for (unsigned int i = 0; i < 127; i++)
- sum += edid_[i];
-
- edid_[127] = 256 - sum;
- }
-
- uint8_t edid_[2048];
-};
-
-TEST_F(EDIDTestSuite, EDIDValid) {
- EXPECT_TRUE(edid_valid(edid_));
-}
-
-TEST_F(EDIDTestSuite, EDIDBadHeader) {
- static const uint8_t bad_header[] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xee, 0xff, 0x00,
- };
-
- memcpy(edid_, bad_header, sizeof(bad_header));
- SetChecksum();
-
- EXPECT_FALSE(edid_valid(edid_));
-}
-
-// Actual EDIDs read from sinks.
-
-static const uint8_t test_no_aud_edid1[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x06, 0xaf, 0x5c, 0x20,
- 0x00, 0x00, 0x00, 0x00, 0x01, 0x12, 0x01, 0x03, 0x80, 0x1a, 0x0e, 0x78,
- 0x0a, 0x99, 0x85, 0x95, 0x55, 0x56, 0x92, 0x28, 0x22, 0x50, 0x54, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x96, 0x19, 0x56, 0x28, 0x50, 0x00,
- 0x08, 0x30, 0x18, 0x10, 0x24, 0x00, 0x00, 0x90, 0x10, 0x00, 0x00, 0x18,
- 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x41,
- 0x55, 0x4f, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfe, 0x00, 0x42, 0x31, 0x31, 0x36, 0x58, 0x57, 0x30,
- 0x32, 0x20, 0x56, 0x30, 0x20, 0x0a, 0x00, 0xf8};
-
-static const uint8_t test_no_aud_edid2[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0xe4, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x01, 0x03, 0x80, 0x1a, 0x0e, 0x78,
- 0x0a, 0xbf, 0x45, 0x95, 0x58, 0x52, 0x8a, 0x28, 0x25, 0x50, 0x54, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x84, 0x1c, 0x56, 0xa8, 0x50, 0x00,
- 0x19, 0x30, 0x30, 0x20, 0x35, 0x00, 0x00, 0x90, 0x10, 0x00, 0x00, 0x1b,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x4c,
- 0x47, 0x20, 0x44, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x0a, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4c, 0x50, 0x31, 0x31, 0x36, 0x57, 0x48,
- 0x31, 0x2d, 0x54, 0x4c, 0x4e, 0x31, 0x00, 0x4e};
-
-/* Has DTD that is too wide */
-static const uint8_t test_no_aud_edid3[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x10, 0xac, 0x63, 0x40,
- 0x4c, 0x35, 0x31, 0x33, 0x0c, 0x15, 0x01, 0x03, 0x80, 0x40, 0x28, 0x78,
- 0xea, 0x8d, 0x85, 0xad, 0x4f, 0x35, 0xb1, 0x25, 0x0e, 0x50, 0x54, 0xa5,
- 0x4b, 0x00, 0x71, 0x4f, 0x81, 0x00, 0x81, 0x80, 0xa9, 0x40, 0xd1, 0x00,
- 0xd1, 0x40, 0x01, 0x01, 0x01, 0x01, 0xe2, 0x68, 0x00, 0xa0, 0xa0, 0x40,
- 0x2e, 0x60, 0x30, 0x20, 0x36, 0x00, 0x81, 0x91, 0x21, 0x00, 0x00, 0x1a,
- 0x00, 0x00, 0x00, 0xff, 0x00, 0x50, 0x48, 0x35, 0x4e, 0x59, 0x31, 0x33,
- 0x4d, 0x33, 0x31, 0x35, 0x4c, 0x0a, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x44,
- 0x45, 0x4c, 0x4c, 0x20, 0x55, 0x33, 0x30, 0x31, 0x31, 0x0a, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x31, 0x56, 0x1d, 0x71, 0x1c, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0xb0};
-
-static const uint8_t test_edid1[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x4d, 0xd9, 0x02, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x01, 0x03, 0x80, 0x00, 0x00, 0x78,
- 0x0a, 0x0d, 0xc9, 0xa0, 0x57, 0x47, 0x98, 0x27, 0x12, 0x48, 0x4c, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x80, 0xd0, 0x72, 0x1c,
- 0x16, 0x20, 0x10, 0x2c, 0x25, 0x80, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e,
- 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00,
- 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x48,
- 0x44, 0x4d, 0x49, 0x20, 0x4c, 0x4c, 0x43, 0x0a, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x0f, 0x2d, 0x08, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0xc0, 0x02, 0x03, 0x1e, 0x47,
- 0x4f, 0x94, 0x13, 0x05, 0x03, 0x04, 0x02, 0x01, 0x16, 0x15, 0x07, 0x06,
- 0x11, 0x10, 0x12, 0x1f, 0x23, 0x09, 0x07, 0x01, 0x65, 0x03, 0x0c, 0x00,
- 0x10, 0x00, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40,
- 0x55, 0x00, 0x13, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0xbc,
- 0x52, 0xd0, 0x1e, 0x20, 0xb8, 0x28, 0x55, 0x40, 0xc4, 0x8e, 0x21, 0x00,
- 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72,
- 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xc4, 0x8e, 0x21, 0x00,
- 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0x13, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xfb};
-
-static const uint8_t test_edid2[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x4c, 0x2d, 0x10, 0x02,
- 0x00, 0x00, 0x00, 0x00, 0x31, 0x0f, 0x01, 0x03, 0x80, 0x10, 0x09, 0x8c,
- 0x0a, 0xe2, 0xbd, 0xa1, 0x5b, 0x4a, 0x98, 0x24, 0x15, 0x47, 0x4a, 0x20,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0,
- 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x1e,
- 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00,
- 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b,
- 0x3d, 0x1e, 0x2e, 0x08, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfc, 0x00, 0x53, 0x41, 0x4d, 0x53, 0x55, 0x4e, 0x47,
- 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x8d, 0x02, 0x03, 0x16, 0x71,
- 0x43, 0x84, 0x05, 0x03, 0x23, 0x09, 0x07, 0x07, 0x83, 0x01, 0x00, 0x00,
- 0x65, 0x03, 0x0c, 0x00, 0x20, 0x00, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0,
- 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0xa0, 0x5a, 0x00, 0x00, 0x00, 0x18,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x30};
-
-static const uint8_t test_edid3[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x3d, 0xcb, 0x61, 0x07,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x01, 0x03, 0x80, 0x00, 0x00, 0x78,
- 0x0a, 0x0d, 0xc9, 0xa0, 0x57, 0x47, 0x98, 0x27, 0x12, 0x48, 0x4c, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c,
- 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e,
- 0x01, 0x1d, 0x80, 0xd0, 0x72, 0x1c, 0x16, 0x20, 0x10, 0x2c, 0x25, 0x80,
- 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x54,
- 0x58, 0x2d, 0x53, 0x52, 0x36, 0x30, 0x35, 0x0a, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x17, 0xf0, 0x0f, 0x7e, 0x11, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x93, 0x02, 0x03, 0x3b, 0x72,
- 0x55, 0x85, 0x04, 0x03, 0x02, 0x0e, 0x0f, 0x07, 0x23, 0x24, 0x10, 0x94,
- 0x13, 0x12, 0x11, 0x1d, 0x1e, 0x16, 0x25, 0x26, 0x01, 0x1f, 0x35, 0x09,
- 0x7f, 0x07, 0x0f, 0x7f, 0x07, 0x17, 0x07, 0x50, 0x3f, 0x06, 0xc0, 0x57,
- 0x06, 0x00, 0x5f, 0x7e, 0x01, 0x67, 0x5e, 0x00, 0x83, 0x4f, 0x00, 0x00,
- 0x66, 0x03, 0x0c, 0x00, 0x20, 0x00, 0x80, 0x8c, 0x0a, 0xd0, 0x8a, 0x20,
- 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00,
- 0x18, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40, 0x55,
- 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72, 0x51,
- 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00,
- 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xdd};
-
-static const uint8_t test_edid4[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x04, 0x72, 0x30, 0x02,
- 0x01, 0x00, 0x00, 0x00, 0x18, 0x14, 0x01, 0x03, 0x80, 0x33, 0x1d, 0x78,
- 0x0a, 0xdc, 0x55, 0xa3, 0x59, 0x48, 0x9e, 0x24, 0x11, 0x50, 0x54, 0xbf,
- 0x6f, 0x00, 0x71, 0x4f, 0x81, 0xc0, 0xd1, 0xc0, 0xb3, 0x00, 0x81, 0x80,
- 0x95, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x3a, 0x80, 0x18, 0x71, 0x38,
- 0x2d, 0x40, 0x58, 0x2c, 0x45, 0x00, 0xfe, 0x22, 0x11, 0x00, 0x00, 0x18,
- 0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00,
- 0xfe, 0x22, 0x11, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x38,
- 0x4c, 0x1e, 0x4b, 0x0f, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
- 0x00, 0x00, 0x00, 0xfc, 0x00, 0x4d, 0x32, 0x33, 0x30, 0x41, 0x0a, 0x20,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0xf0, 0x02, 0x03, 0x18, 0x74,
- 0x45, 0x04, 0x05, 0x90, 0x03, 0x01, 0x23, 0x09, 0x17, 0x07, 0x83, 0x01,
- 0x00, 0x00, 0x65, 0x03, 0x0c, 0x00, 0x30, 0x00, 0x01, 0x1d, 0x80, 0x18,
- 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00, 0xfe, 0x22, 0x11, 0x00,
- 0x00, 0x9e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0xfe, 0x22, 0x11, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xd0,
-};
-
-static const uint8_t test_monitor_edid[256] = {
- 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x4d, 0xd9, 0x02, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x01, 0x03, 0x80, 0x00, 0x00, 0x78,
- 0x0a, 0x0d, 0xc9, 0xa0, 0x57, 0x47, 0x98, 0x27, 0x12, 0x48, 0x4c, 0x00,
- 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
- 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x1d, 0x80, 0xd0, 0x72, 0x1c,
- 0x16, 0x20, 0x10, 0x2c, 0x25, 0x80, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e,
- 0x01, 0x1d, 0x80, 0x18, 0x71, 0x1c, 0x16, 0x20, 0x58, 0x2c, 0x25, 0x00,
- 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x9e, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x48,
- 0x44, 0x4d, 0x49, 0x20, 0x4c, 0x4c, 0x43, 0x20, 0x41, 0x42, 0x43, 0x44,
- 0x00, 0x00, 0x00, 0xfd, 0x00, 0x3b, 0x3d, 0x0f, 0x2d, 0x08, 0x00, 0x0a,
- 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0xc0, 0x02, 0x03, 0x1e, 0x47,
- 0x4f, 0x94, 0x13, 0x05, 0x03, 0x04, 0x02, 0x01, 0x16, 0x15, 0x07, 0x06,
- 0x11, 0x10, 0x12, 0x1f, 0x23, 0x09, 0x07, 0x01, 0x65, 0x03, 0x0c, 0x00,
- 0x10, 0x00, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40,
- 0x55, 0x00, 0x13, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0xbc,
- 0x52, 0xd0, 0x1e, 0x20, 0xb8, 0x28, 0x55, 0x40, 0xc4, 0x8e, 0x21, 0x00,
- 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0xc4, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72,
- 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0xc4, 0x8e, 0x21, 0x00,
- 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e,
- 0x96, 0x00, 0x13, 0x8e, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0xfb};
-
-static const uint8_t* test_no_aud_edids[] = {
- test_no_aud_edid1,
- test_no_aud_edid2,
- test_no_aud_edid3,
-};
-
-static const uint8_t* test_edids[] = {
- test_edid1,
- test_edid2,
- test_edid3,
- test_edid4,
-};
-
-static const char* monitor_names[] = {
- "HDMI LLC",
- "SAMSUNG",
- "TX-SR605",
- "M230A",
-};
-
-TEST_F(EDIDTestSuite, NoAudEDID) {
- unsigned int i;
-
- for (i = 0; i < ARRAY_SIZE(test_no_aud_edids); i++) {
- EXPECT_TRUE(edid_valid(test_no_aud_edids[i]));
- EXPECT_FALSE(edid_lpcm_support(test_no_aud_edids[i], 1));
- }
-}
-
-TEST_F(EDIDTestSuite, AudEDID) {
- unsigned int i;
-
- for (i = 0; i < ARRAY_SIZE(test_edids); i++) {
- EXPECT_TRUE(edid_valid(test_edids[i]));
- EXPECT_TRUE(edid_lpcm_support(test_edids[i], 1));
- }
-}
-
-TEST_F(EDIDTestSuite, EDIDMonitorName) {
- unsigned int i;
- char buf[DTD_SIZE];
-
- for (i = 0; i < ARRAY_SIZE(test_edids); i++) {
- EXPECT_EQ(0, edid_get_monitor_name(test_edids[i], buf, DTD_SIZE));
- EXPECT_STREQ(monitor_names[i], buf);
- }
-
- EXPECT_EQ(0, edid_get_monitor_name(test_monitor_edid, buf, DTD_SIZE));
- EXPECT_STREQ("HDMI LLC ABCD", buf);
- EXPECT_EQ(0, edid_get_monitor_name(test_monitor_edid, buf, 11));
- EXPECT_STREQ("HDMI LLC A", buf);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/empty_audio_stub.cc b/cras/src/tests/empty_audio_stub.cc
deleted file mode 100644
index 00ede69f..00000000
--- a/cras/src/tests/empty_audio_stub.cc
+++ /dev/null
@@ -1,24 +0,0 @@
-/* Copyright 2018 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-extern "C" {
-#include "polled_interval_checker.h"
-
-struct polled_interval* pic_polled_interval_create(int interval_sec) {
- return NULL;
-}
-
-int pic_interval_elapsed(const struct polled_interval* interval) {
- return 0;
-}
-
-void pic_interval_reset(struct polled_interval* interval) {}
-
-void pic_polled_interval_destroy(struct polled_interval** interval) {}
-
-void pic_update_current_time() {}
-
-void cras_non_empty_audio_send_msg(int non_empty) {}
-}
diff --git a/cras/src/tests/empty_iodev_unittest.cc b/cras/src/tests/empty_iodev_unittest.cc
deleted file mode 100644
index 148d5301..00000000
--- a/cras/src/tests/empty_iodev_unittest.cc
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "cras_audio_area.h"
-#include "cras_empty_iodev.h"
-#include "cras_iodev.h"
-}
-
-static struct timespec clock_gettime_retspec;
-static struct cras_audio_format fake_format;
-static cras_audio_area mock_audio_area;
-
-namespace {
-
-TEST(EmptyIodev, GetInputBuffer) {
- struct cras_iodev* iodev;
- struct timespec ts;
- cras_audio_area* area;
- unsigned nframes;
-
- iodev = empty_iodev_create(CRAS_STREAM_INPUT, CRAS_NODE_TYPE_FALLBACK_NORMAL);
-
- clock_gettime_retspec.tv_sec = 0;
- clock_gettime_retspec.tv_nsec = 10000000;
- fake_format.frame_rate = 48000;
- iodev->format = &fake_format;
- iodev->configure_dev(iodev);
-
- clock_gettime_retspec.tv_nsec = 20000000;
- nframes = iodev->frames_queued(iodev, &ts);
- ASSERT_EQ(480, nframes);
-
- /* If client takes too long to get input data, number of frames
- * returned shouldn't exceeds device's own buffer size. */
- nframes = 5000;
- clock_gettime_retspec.tv_sec = 1;
- iodev->get_buffer(iodev, &area, &nframes);
- ASSERT_EQ(4096, nframes);
-
- iodev->close_dev(iodev);
- empty_iodev_destroy(iodev);
-}
-
-} // namespace
-
-extern "C" {
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {}
-
-int cras_iodev_default_no_stream_playback(struct cras_iodev* odev, int enable) {
- return 0;
-}
-
-void cras_iodev_init_audio_area(struct cras_iodev* iodev, int num_channels) {
- iodev->area = &mock_audio_area;
-}
-
-void cras_iodev_free_audio_area(struct cras_iodev* iodev) {}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {}
-
-int cras_iodev_list_rm_input(struct cras_iodev* input) {
- return 0;
-}
-
-int cras_iodev_list_rm_output(struct cras_iodev* output) {
- return 0;
-}
-
-void cras_iodev_free_resources(struct cras_iodev* iodev) {}
-
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- iodev->nodes = node;
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {
- iodev->active_node = node;
-}
-
-// From librt.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = clock_gettime_retspec.tv_sec;
- tp->tv_nsec = clock_gettime_retspec.tv_nsec;
- return 0;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/ewma_power_unittest.cc b/cras/src/tests/ewma_power_unittest.cc
deleted file mode 100644
index 10f03189..00000000
--- a/cras/src/tests/ewma_power_unittest.cc
+++ /dev/null
@@ -1,129 +0,0 @@
-// Copyright (c) 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "ewma_power.h"
-}
-
-namespace {
-
-TEST(EWMAPower, RelativePowerValue) {
- struct ewma_power ewma;
- int16_t buf[480];
- float f;
- int i;
-
- for (i = 0; i < 480; i++)
- buf[i] = 0x00fe;
-
- ewma_power_init(&ewma, 48000);
- EXPECT_EQ(48, ewma.step_fr);
-
- ewma_power_calculate(&ewma, buf, 1, 480);
- EXPECT_LT(0.0f, ewma.power);
-
- // After 10ms of silence the power value decreases.
- f = ewma.power;
- for (i = 0; i < 480; i++)
- buf[i] = 0x00;
- ewma_power_calculate(&ewma, buf, 1, 480);
- EXPECT_LT(ewma.power, f);
-
- // After 300ms of silence the power value decreases to insignificant low.
- for (i = 0; i < 30; i++)
- ewma_power_calculate(&ewma, buf, 1, 480);
- EXPECT_LT(ewma.power, 1.0e-10);
-}
-
-TEST(EWMAPower, PowerInStereoData) {
- struct ewma_power ewma;
- int16_t buf[960];
- int i;
- float f;
-
- ewma_power_init(&ewma, 48000);
-
- for (i = 0; i < 960; i += 2) {
- buf[i] = 0x0;
- buf[i + 1] = 0x00fe;
- }
- ewma_power_calculate(&ewma, buf, 2, 480);
- EXPECT_LT(0.0f, ewma.power);
-
- // After 10ms of silence the power value decreases.
- f = ewma.power;
- for (i = 0; i < 960; i++)
- buf[i] = 0x0;
- ewma_power_calculate(&ewma, buf, 2, 480);
- EXPECT_LT(ewma.power, f);
-
- // After 300ms of silence the power value decreases to insignificant low.
- for (i = 0; i < 30; i++)
- ewma_power_calculate(&ewma, buf, 2, 480);
- EXPECT_LT(ewma.power, 1.0e-10);
-
- // Assume the data is silent in the other channel.
- ewma_power_init(&ewma, 48000);
-
- for (i = 0; i < 960; i += 2) {
- buf[i] = 0x0ffe;
- buf[i + 1] = 0x0;
- }
- ewma_power_calculate(&ewma, buf, 2, 480);
- EXPECT_LT(0.0f, ewma.power);
-}
-
-TEST(EWMAPower, PowerInAudioArea) {
- struct ewma_power ewma;
- struct cras_audio_area* area = cras_audio_area_create(4);
- struct cras_audio_format* fmt =
- cras_audio_format_create(SND_PCM_FORMAT_S16_LE, 48000, 4);
- int8_t layout[CRAS_CH_MAX] = {0, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1};
- int16_t buf[1920];
- int i;
- float f;
-
- cras_audio_format_set_channel_layout(fmt, layout);
- cras_audio_area_config_channels(area, fmt);
-
- for (i = 0; i < 1920; i += 4) {
- buf[i] = 0x0ffe;
- buf[i + 1] = 0x0;
- buf[i + 2] = 0x0;
- buf[i + 3] = 0x0ffe;
- }
- ewma_power_init(&ewma, 48000);
- ewma_power_calculate_area(&ewma, buf, area, 480);
- f = ewma.power;
- EXPECT_LT(0.0f, f);
-
- /* Change the layout in the same audio area. Expect the power be lower because
- * one of the channel is now silent. */
- layout[CRAS_CH_FR] = 2;
- cras_audio_format_set_channel_layout(fmt, layout);
- cras_audio_area_config_channels(area, fmt);
- ewma_power_init(&ewma, 48000);
- ewma_power_calculate_area(&ewma, buf, area, 480);
- EXPECT_GT(f, ewma.power);
-
- /* Change layout to the two silent channels. Expect power is 0.0f. */
- layout[CRAS_CH_FL] = 1;
- cras_audio_format_set_channel_layout(fmt, layout);
- cras_audio_area_config_channels(area, fmt);
- ewma_power_init(&ewma, 48000);
- ewma_power_calculate_area(&ewma, buf, area, 480);
- EXPECT_EQ(0.0f, ewma.power);
-
- cras_audio_format_destroy(fmt);
- cras_audio_area_destroy(area);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/expr_unittest.cc b/cras/src/tests/expr_unittest.cc
deleted file mode 100644
index dbfdb46b..00000000
--- a/cras/src/tests/expr_unittest.cc
+++ /dev/null
@@ -1,248 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-#include "cras_expr.h"
-
-namespace {
-
-TEST(ExprTest, UnparsibleExpression) {
- struct cras_expr_expression* expr;
-
- /* un-parsable input */
- expr = cras_expr_expression_parse("#");
- EXPECT_EQ(NULL, expr);
-
- expr = cras_expr_expression_parse(NULL);
- EXPECT_EQ(NULL, expr);
-
- cras_expr_expression_free(expr);
-}
-
-TEST(ExprTest, LiteralExpression) {
- struct cras_expr_expression* expr;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
- struct cras_expr_env env = CRAS_EXPR_ENV_INIT;
- int integer = 0;
-
- /* parse integer literal */
- expr = cras_expr_expression_parse(" -2");
- EXPECT_EQ(EXPR_TYPE_LITERAL, expr->type);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_INT, expr->u.literal.type);
- EXPECT_EQ(-2, expr->u.literal.u.integer);
-
- /* evaluate integer literal */
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_INT, value.type);
- EXPECT_EQ(-2, value.u.integer);
-
- EXPECT_EQ(0, cras_expr_expression_eval_int(expr, &env, &integer));
- EXPECT_EQ(-2, integer);
- cras_expr_expression_free(expr);
-
- /* parse string literal */
- expr = cras_expr_expression_parse("\"hello\" ");
- EXPECT_EQ(EXPR_TYPE_LITERAL, expr->type);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_STRING, expr->u.literal.type);
- EXPECT_STREQ("hello", expr->u.literal.u.string);
-
- /* evaluate string literal */
- cras_expr_expression_eval(expr, &env, &value);
- ASSERT_EQ(CRAS_EXPR_VALUE_TYPE_STRING, value.type);
- EXPECT_STREQ("hello", value.u.string);
-
- cras_expr_value_free(&value);
- cras_expr_expression_free(expr);
- cras_expr_env_free(&env);
-}
-
-TEST(ExprTest, Variable) {
- struct cras_expr_expression* expr;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
- struct cras_expr_env env = CRAS_EXPR_ENV_INIT;
- int integer = 0;
-
- /* parse variable */
- expr = cras_expr_expression_parse("a");
- ASSERT_EQ(EXPR_TYPE_VARIABLE, expr->type);
- EXPECT_STREQ("a", expr->u.variable);
-
- /* evaluate variable (undefined now) */
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_NONE, value.type);
-
- /* undefined variable */
- EXPECT_EQ(-1, cras_expr_expression_eval_int(expr, &env, &integer));
-
- /* now define a variable with integer value 2 */
- cras_expr_env_set_variable_integer(&env, "a", 2);
-
- /* re-evaluate the variable */
- EXPECT_EQ(0, cras_expr_expression_eval_int(expr, &env, &integer));
- EXPECT_EQ(2, integer);
-
- cras_expr_value_free(&value);
- cras_expr_expression_free(expr);
- cras_expr_env_free(&env);
-}
-
-TEST(ExprTest, Compound) {
- struct cras_expr_expression *expr, *expr1, *expr2;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
- struct cras_expr_env env = CRAS_EXPR_ENV_INIT;
-
- /* parse empty compound expression */
- expr = cras_expr_expression_parse("()");
- ASSERT_EQ(EXPR_TYPE_COMPOUND, expr->type);
- EXPECT_EQ(0, ARRAY_COUNT(&expr->u.children));
-
- /* evaluate empty compound expression */
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_NONE, value.type);
- cras_expr_expression_free(expr);
-
- /* parse non-empty compound expression */
- expr = cras_expr_expression_parse("(foo bar)");
- ASSERT_EQ(EXPR_TYPE_COMPOUND, expr->type);
- EXPECT_EQ(2, ARRAY_COUNT(&expr->u.children));
-
- /* evaluate non-empty compound expression */
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_NONE, value.type);
- cras_expr_expression_free(expr);
-
- /* parse nested compound expression */
- expr = cras_expr_expression_parse("((foo 3)bar )");
- ASSERT_EQ(EXPR_TYPE_COMPOUND, expr->type);
- ASSERT_EQ(2, ARRAY_COUNT(&expr->u.children));
-
- expr1 = *ARRAY_ELEMENT(&expr->u.children, 0);
- ASSERT_EQ(EXPR_TYPE_COMPOUND, expr1->type);
- ASSERT_EQ(2, ARRAY_COUNT(&expr1->u.children));
-
- expr2 = *ARRAY_ELEMENT(&expr1->u.children, 1);
- ASSERT_EQ(EXPR_TYPE_LITERAL, expr2->type);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_INT, expr2->u.literal.type);
- EXPECT_EQ(3, expr2->u.literal.u.integer);
-
- /* evaluate nested compound expression */
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_NONE, value.type);
- cras_expr_expression_free(expr);
-
- cras_expr_value_free(&value);
- cras_expr_env_free(&env);
-}
-
-TEST(ExprTest, Environment) {
- struct cras_expr_expression* expr;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
- struct cras_expr_env env1 = CRAS_EXPR_ENV_INIT;
- struct cras_expr_env env2 = CRAS_EXPR_ENV_INIT;
- int integer = 0;
- char boolean = 0;
-
- /* parse variable */
- expr = cras_expr_expression_parse("baz");
-
- /* put baz=4 into env1 */
- cras_expr_env_set_variable_integer(&env1, "baz", 4);
-
- /* evaluate expr against env1 and env2 */
- EXPECT_EQ(0, cras_expr_expression_eval_int(expr, &env1, &integer));
- EXPECT_EQ(4, integer);
- EXPECT_EQ(-1, cras_expr_expression_eval_int(expr, &env2, &integer));
-
- /* put baz=5 into env2 */
- cras_expr_env_set_variable_integer(&env2, "baz", 5);
-
- /* evaluate again */
- EXPECT_EQ(0, cras_expr_expression_eval_int(expr, &env1, &integer));
- EXPECT_EQ(4, integer);
- EXPECT_EQ(0, cras_expr_expression_eval_int(expr, &env2, &integer));
- EXPECT_EQ(5, integer);
-
- /* an integer is not a boolean */
- EXPECT_EQ(-1, cras_expr_expression_eval_boolean(expr, &env2, &boolean));
-
- cras_expr_value_free(&value);
- cras_expr_expression_free(expr);
- cras_expr_env_free(&env1);
- cras_expr_env_free(&env2);
-}
-
-static void expect_int(int expected,
- const char* str,
- struct cras_expr_env* env) {
- struct cras_expr_expression* expr;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
-
- expr = cras_expr_expression_parse(str);
- cras_expr_expression_eval(expr, env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_INT, value.type);
- EXPECT_EQ(expected, value.u.integer);
- cras_expr_expression_free(expr);
-}
-
-static void expect_boolean(char expected,
- const char* str,
- struct cras_expr_env* env) {
- struct cras_expr_expression* expr;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
-
- expr = cras_expr_expression_parse(str);
- cras_expr_expression_eval(expr, env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_BOOLEAN, value.type);
- EXPECT_EQ(expected, value.u.boolean);
- cras_expr_expression_free(expr);
-}
-
-TEST(ExprTest, Builtin) {
- struct cras_expr_expression* expr;
- struct cras_expr_value value = CRAS_EXPR_VALUE_INIT;
- struct cras_expr_env env = CRAS_EXPR_ENV_INIT;
-
- cras_expr_env_install_builtins(&env);
-
- /* parse variable */
- expr = cras_expr_expression_parse("or");
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_FUNCTION, value.type);
- cras_expr_expression_free(expr);
-
- /* test builtin functions */
- expect_boolean(1, "(and)", &env);
- expect_boolean(1, "(and #t)", &env);
- expect_boolean(1, "(and #t #t)", &env);
- expect_int(3, "(and 1 2 3)", &env);
- expect_boolean(0, "(and #f 4)", &env);
- expect_boolean(0, "(or)", &env);
- expect_boolean(1, "(or #t)", &env);
- expect_boolean(0, "(or #f #f)", &env);
- expect_int(2, "(or #f #f 2)", &env);
- expect_int(3, "(or #f (or 3))", &env);
- expect_boolean(0, "(equal? \"hello\" 3)", &env);
- expect_boolean(1, "(equal? \"hello\" \"hello\")", &env);
-
- /* a more complex example a="hello" b="world"*/
- expr = cras_expr_expression_parse("(or (equal? \"test\" a) b)");
- cras_expr_env_set_variable_string(&env, "a", "hello");
- cras_expr_env_set_variable_string(&env, "b", "world");
-
- cras_expr_expression_eval(expr, &env, &value);
- EXPECT_EQ(CRAS_EXPR_VALUE_TYPE_STRING, value.type);
- EXPECT_STREQ("world", value.u.string);
- cras_expr_expression_free(expr);
-
- cras_expr_value_free(&value);
- cras_expr_env_free(&env);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/file_wait_unittest.cc b/cras/src/tests/file_wait_unittest.cc
deleted file mode 100644
index 87cd53c9..00000000
--- a/cras/src/tests/file_wait_unittest.cc
+++ /dev/null
@@ -1,277 +0,0 @@
-// Copyright 2016 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <fcntl.h>
-#include <gtest/gtest.h>
-#include <stdlib.h>
-
-#include <string>
-
-#include "cras_file_wait.h"
-#include "cras_util.h"
-
-extern "C" {
-// This function is not exported in cras_util.h.
-void cras_file_wait_mock_race_condition(struct cras_file_wait* file_wait);
-}
-
-namespace {
-
-// Executes "rm -rf <path>".
-static int RmRF(const std::string& path) {
- std::string cmd("rm -rf \"");
- cmd += path + "\"";
-
- if (path == "/")
- return -EINVAL;
-
- int rc = system(cmd.c_str());
- if (rc < 0)
- return -errno;
- return WEXITSTATUS(rc);
-}
-
-// Filled-in by the FileWaitCallback.
-struct FileWaitResult {
- size_t called;
- cras_file_wait_event_t event;
-};
-
-// Called by the file wait code for an event.
-static void FileWaitCallback(void* context,
- cras_file_wait_event_t event,
- const char* filename) {
- FileWaitResult* result = reinterpret_cast<FileWaitResult*>(context);
- result->called++;
- result->event = event;
-}
-
-// Do all of the EXPECTed steps for a simple wait for one file.
-static void SimpleFileWait(const char* file_path) {
- struct cras_file_wait* file_wait;
- FileWaitResult file_wait_result;
- struct pollfd poll_fd;
- struct timespec timeout = {0, 100000000};
- struct stat stat_buf;
- int stat_rc;
-
- stat_rc = stat(file_path, &stat_buf);
- if (stat_rc < 0)
- stat_rc = -errno;
-
- file_wait_result.called = 0;
- EXPECT_EQ(0, cras_file_wait_create(file_path, CRAS_FILE_WAIT_FLAG_NONE,
- FileWaitCallback, &file_wait_result,
- &file_wait));
- EXPECT_NE(reinterpret_cast<struct cras_file_wait*>(NULL), file_wait);
- if (stat_rc == 0) {
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_CREATED, file_wait_result.event);
- } else {
- EXPECT_EQ(0, file_wait_result.called);
- }
- poll_fd.events = POLLIN;
- poll_fd.fd = cras_file_wait_get_fd(file_wait);
-
- file_wait_result.called = 0;
- if (stat_rc == 0)
- EXPECT_EQ(0, RmRF(file_path));
- else
- EXPECT_EQ(0, mknod(file_path, S_IFREG | 0600, 0));
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- if (stat_rc == 0)
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_DELETED, file_wait_result.event);
- else
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_CREATED, file_wait_result.event);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
- cras_file_wait_destroy(file_wait);
-}
-
-// Test the cras_file_wait functions including multiple path components
-// missing and path components deleted and recreated.
-TEST(Util, FileWait) {
- struct cras_file_wait* file_wait;
- FileWaitResult file_wait_result;
- pid_t pid = getpid();
- struct pollfd poll_fd;
- int current_dir;
- struct timespec timeout = {0, 100000000};
- char pid_buf[32];
- std::string tmp_dir(CRAS_UT_TMPDIR);
- std::string dir_path;
- std::string subdir_path;
- std::string file_path;
-
- snprintf(pid_buf, sizeof(pid_buf), "%d", pid);
- dir_path = tmp_dir + "/" + pid_buf;
- subdir_path = dir_path + "/subdir";
- file_path = subdir_path + "/does_not_exist";
-
- // Test arguments.
- // Null file path.
- EXPECT_EQ(-EINVAL, cras_file_wait_create(NULL, CRAS_FILE_WAIT_FLAG_NONE,
- FileWaitCallback, &file_wait_result,
- &file_wait));
- // Empty file path.
- EXPECT_EQ(-EINVAL, cras_file_wait_create("", CRAS_FILE_WAIT_FLAG_NONE,
- FileWaitCallback, &file_wait_result,
- &file_wait));
- // No callback structure.
- EXPECT_EQ(-EINVAL, cras_file_wait_create(".", CRAS_FILE_WAIT_FLAG_NONE, NULL,
- NULL, &file_wait));
- // No file wait structure.
- EXPECT_EQ(-EINVAL,
- cras_file_wait_create(".", CRAS_FILE_WAIT_FLAG_NONE,
- FileWaitCallback, &file_wait_result, NULL));
- EXPECT_EQ(-EINVAL, cras_file_wait_dispatch(NULL));
- EXPECT_EQ(-EINVAL, cras_file_wait_get_fd(NULL));
-
- // Make sure that /tmp exists.
- file_wait_result.called = 0;
- EXPECT_EQ(0, cras_file_wait_create(CRAS_UT_TMPDIR, CRAS_FILE_WAIT_FLAG_NONE,
- FileWaitCallback, &file_wait_result,
- &file_wait));
- EXPECT_NE(reinterpret_cast<struct cras_file_wait*>(NULL), file_wait);
- EXPECT_EQ(file_wait_result.called, 1);
- ASSERT_EQ(file_wait_result.event, CRAS_FILE_WAIT_EVENT_CREATED);
- cras_file_wait_destroy(file_wait);
-
- // Create our temporary dir.
- ASSERT_EQ(0, RmRF(dir_path));
- ASSERT_EQ(0, mkdir(dir_path.c_str(), 0700));
-
- // Start looking for our file '.../does_not_exist'.
- EXPECT_EQ(0, cras_file_wait_create(file_path.c_str(),
- CRAS_FILE_WAIT_FLAG_NONE, FileWaitCallback,
- &file_wait_result, &file_wait));
- EXPECT_NE(reinterpret_cast<struct cras_file_wait*>(NULL), file_wait);
- poll_fd.events = POLLIN;
- poll_fd.fd = cras_file_wait_get_fd(file_wait);
- EXPECT_NE(0, poll_fd.fd >= 0);
-
- // Create a sub-directory in the path.
- file_wait_result.called = 0;
- EXPECT_EQ(0, mkdir(subdir_path.c_str(), 0700));
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(0, file_wait_result.called);
- // Removing a watch causes generation of an IN_IGNORED event for the previous
- // watch_id. cras_file_wait_dispatch will ignore this and return 0.
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Remove the directory that we're watching.
- EXPECT_EQ(0, RmRF(subdir_path));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(0, file_wait_result.called);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Create a sub-directory in the path (again).
- EXPECT_EQ(0, mkdir(subdir_path.c_str(), 0700));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(0, file_wait_result.called);
- // See IN_IGNORED above.
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Create the file we're looking for.
- EXPECT_EQ(0, mknod(file_path.c_str(), S_IFREG | 0600, 0));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_CREATED, file_wait_result.event);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Remove the file.
- file_wait_result.called = 0;
- EXPECT_EQ(0, unlink(file_path.c_str()));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_DELETED, file_wait_result.event);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Re-create the file.
- file_wait_result.called = 0;
- EXPECT_EQ(0, mknod(file_path.c_str(), S_IFREG | 0600, 0));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_CREATED, file_wait_result.event);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Remove the subdir.
- file_wait_result.called = 0;
- EXPECT_EQ(0, RmRF(subdir_path));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_DELETED, file_wait_result.event);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Create a sub-directory in the path (again), and this time mock a race
- // condition for creation of the file.
- file_wait_result.called = 0;
- EXPECT_EQ(0, mkdir(subdir_path.c_str(), 0700));
- timeout.tv_sec = 0;
- timeout.tv_nsec = 100000000;
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, &timeout, NULL));
- cras_file_wait_mock_race_condition(file_wait);
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(CRAS_FILE_WAIT_EVENT_CREATED, file_wait_result.event);
- EXPECT_EQ(0, cras_file_wait_dispatch(file_wait));
- EXPECT_EQ(1, file_wait_result.called);
- EXPECT_EQ(-EAGAIN, cras_file_wait_dispatch(file_wait));
-
- // Cleanup.
- cras_file_wait_destroy(file_wait);
-
- // Treat consecutive '/' as one.
- file_path = dir_path + "//does_not_exist_too";
- SimpleFileWait(file_path.c_str());
-
- // Stash the current directory.
- current_dir = open(".", O_RDONLY | O_PATH | O_DIRECTORY);
- ASSERT_NE(0, current_dir >= 0);
-
- // Search for a file in the current directory.
- ASSERT_EQ(0, chdir(dir_path.c_str()));
- SimpleFileWait("does_not_exist_either");
-
- // Test notification of deletion in the current directory.
- SimpleFileWait("does_not_exist_either");
-
- // Search for a file in the current directory (variation).
- SimpleFileWait("./does_not_exist_either_too");
-
- // Return to the start directory.
- EXPECT_EQ(0, fchdir(current_dir));
-
- // Clean up.
- EXPECT_EQ(0, RmRF(dir_path));
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/float_buffer_unittest.cc b/cras/src/tests/float_buffer_unittest.cc
deleted file mode 100644
index eee523b1..00000000
--- a/cras/src/tests/float_buffer_unittest.cc
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright 2018 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "float_buffer.h"
-
-#include <gtest/gtest.h>
-
-namespace {
-TEST(FloatBuffer, ReadWrite) {
- unsigned int readable = 10;
- struct float_buffer* b = float_buffer_create(10, 2);
- EXPECT_EQ(10, float_buffer_writable(b));
-
- // (w, r)=(8, 0)
- float_buffer_written(b, 8);
- EXPECT_EQ(8, float_buffer_level(b));
-
- float_buffer_read_pointer(b, 0, &readable);
- EXPECT_EQ(8, readable);
- EXPECT_EQ(2, float_buffer_writable(b));
-
- readable = 10;
- float_buffer_read_pointer(b, 3, &readable);
- EXPECT_EQ(5, readable);
-
- // (w, r)=(8, 6)
- float_buffer_read(b, 6);
- EXPECT_EQ(2, float_buffer_writable(b));
-
- // (w, r)=(0, 6)
- float_buffer_written(b, 2);
- EXPECT_EQ(6, float_buffer_writable(b));
-
- // (w, r)=(3, 6)
- readable = 10;
- float_buffer_written(b, 3);
- float_buffer_read_pointer(b, 0, &readable);
- EXPECT_EQ(4, readable);
-
- readable = 10;
- float_buffer_read_pointer(b, 1, &readable);
- EXPECT_EQ(3, readable);
-
- float_buffer_destroy(&b);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/fmt_conv_ops_unittest.cc b/cras/src/tests/fmt_conv_ops_unittest.cc
deleted file mode 100644
index 0baf37b1..00000000
--- a/cras/src/tests/fmt_conv_ops_unittest.cc
+++ /dev/null
@@ -1,855 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <limits.h>
-#include <math.h>
-#include <stdint.h>
-#include <sys/param.h>
-
-#include <memory>
-
-extern "C" {
-#include "cras_fmt_conv_ops.h"
-#include "cras_types.h"
-}
-
-static uint8_t* AllocateRandomBytes(size_t size) {
- uint8_t* buf = (uint8_t*)malloc(size);
- while (size--)
- buf[size] = rand() & 0xff;
- return buf;
-}
-
-using U8Ptr = std::unique_ptr<uint8_t[], decltype(free)*>;
-using S16LEPtr = std::unique_ptr<int16_t[], decltype(free)*>;
-using S243LEPtr = std::unique_ptr<uint8_t[], decltype(free)*>;
-using S24LEPtr = std::unique_ptr<int32_t[], decltype(free)*>;
-using S32LEPtr = std::unique_ptr<int32_t[], decltype(free)*>;
-using FloatPtr = std::unique_ptr<float[], decltype(free)*>;
-
-static U8Ptr CreateU8(size_t size) {
- uint8_t* buf = AllocateRandomBytes(size * sizeof(uint8_t));
- U8Ptr ret(buf, free);
- return ret;
-}
-
-static S16LEPtr CreateS16LE(size_t size) {
- uint8_t* buf = AllocateRandomBytes(size * sizeof(int16_t));
- S16LEPtr ret(reinterpret_cast<int16_t*>(buf), free);
- return ret;
-}
-
-static S243LEPtr CreateS243LE(size_t size) {
- uint8_t* buf = AllocateRandomBytes(size * sizeof(uint8_t) * 3);
- S243LEPtr ret(buf, free);
- return ret;
-}
-
-static S24LEPtr CreateS24LE(size_t size) {
- uint8_t* buf = AllocateRandomBytes(size * sizeof(int32_t));
- S24LEPtr ret(reinterpret_cast<int32_t*>(buf), free);
- return ret;
-}
-
-static S32LEPtr CreateS32LE(size_t size) {
- uint8_t* buf = AllocateRandomBytes(size * sizeof(int32_t));
- S32LEPtr ret(reinterpret_cast<int32_t*>(buf), free);
- return ret;
-}
-
-static FloatPtr CreateFloat(size_t size) {
- float* buf = (float*)malloc(size * sizeof(float));
- while (size--)
- buf[size] = (float)(rand() & 0xff) / 0xfff;
- FloatPtr ret(buf, free);
- return ret;
-}
-
-static int32_t ToS243LE(const uint8_t* in) {
- int32_t ret = 0;
-
- ret |= in[2];
- ret <<= 8;
- ret |= in[1];
- ret <<= 8;
- ret |= in[0];
- return ret;
-}
-
-static int16_t S16AddAndClip(int16_t a, int16_t b) {
- int32_t sum;
-
- sum = (int32_t)a + (int32_t)b;
- sum = MAX(sum, SHRT_MIN);
- sum = MIN(sum, SHRT_MAX);
- return sum;
-}
-
-// Test U8 to S16_LE conversion.
-TEST(FormatConverterOpsTest, ConvertU8ToS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- U8Ptr src = CreateU8(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- convert_u8_to_s16le(src.get(), frames * in_ch, (uint8_t*)dst.get());
-
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int16_t)((uint16_t)((int16_t)(int8_t)src[i] - 0x80) << 8),
- dst[i]);
- }
-}
-
-// Test S24_3LE to S16_LE conversion.
-TEST(FormatConverterOpsTest, ConvertS243LEToS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S243LEPtr src = CreateS243LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- convert_s243le_to_s16le(src.get(), frames * in_ch, (uint8_t*)dst.get());
-
- uint8_t* p = src.get();
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int16_t)(ToS243LE(p) >> 8), dst[i]);
- p += 3;
- }
-}
-
-// Test S24_LE to S16_LE conversion.
-TEST(FormatConverterOpsTest, ConvertS24LEToS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S24LEPtr src = CreateS24LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- convert_s24le_to_s16le((uint8_t*)src.get(), frames * in_ch,
- (uint8_t*)dst.get());
-
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int16_t)(src[i] >> 8), dst[i]);
- }
-}
-
-// Test S32_LE to S16_LE conversion.
-TEST(FormatConverterOpsTest, ConvertS32LEToS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S32LEPtr src = CreateS32LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- convert_s32le_to_s16le((uint8_t*)src.get(), frames * in_ch,
- (uint8_t*)dst.get());
-
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int16_t)(src[i] >> 16), dst[i]);
- }
-}
-
-// Test S16_LE to U8 conversion.
-TEST(FormatConverterOpsTest, ConvertS16LEToU8) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- U8Ptr dst = CreateU8(frames * out_ch);
-
- convert_s16le_to_u8((uint8_t*)src.get(), frames * in_ch, dst.get());
-
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((uint8_t)(int8_t)((src[i] >> 8) + 0x80), dst[i]);
- }
-}
-
-// Test S16_LE to S24_3LE conversion.
-TEST(FormatConverterOpsTest, ConvertS16LEToS243LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S243LEPtr dst = CreateS243LE(frames * out_ch);
-
- convert_s16le_to_s243le((uint8_t*)src.get(), frames * in_ch, dst.get());
-
- uint8_t* p = dst.get();
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int32_t)((uint32_t)src[i] << 8) & 0x00ffffff,
- ToS243LE(p) & 0x00ffffff);
- p += 3;
- }
-}
-
-// Test S16_LE to S24_LE conversion.
-TEST(FormatConverterOpsTest, ConvertS16LEToS24LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S24LEPtr dst = CreateS24LE(frames * out_ch);
-
- convert_s16le_to_s24le((uint8_t*)src.get(), frames * in_ch,
- (uint8_t*)dst.get());
-
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int32_t)((uint32_t)src[i] << 8) & 0x00ffffff,
- dst[i] & 0x00ffffff);
- }
-}
-
-// Test S16_LE to S32_LE conversion.
-TEST(FormatConverterOpsTest, ConvertS16LEToS32LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 2;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S32LEPtr dst = CreateS32LE(frames * out_ch);
-
- convert_s16le_to_s32le((uint8_t*)src.get(), frames * in_ch,
- (uint8_t*)dst.get());
-
- for (size_t i = 0; i < frames * in_ch; ++i) {
- EXPECT_EQ((int32_t)((uint32_t)src[i] << 16) & 0xffffff00,
- dst[i] & 0xffffff00);
- }
-}
-
-// Test Mono to Stereo conversion. S16_LE.
-TEST(FormatConverterOpsTest, MonoToStereoS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 1;
- const size_t out_ch = 2;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret =
- s16_mono_to_stereo((uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(src[i], dst[i * 2 + 0]);
- EXPECT_EQ(src[i], dst[i * 2 + 1]);
- }
-}
-
-// Test Stereo to Mono conversion. S16_LE.
-TEST(FormatConverterOpsTest, StereoToMonoS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
- for (size_t i = 0; i < frames; ++i) {
- src[i * 2 + 0] = 13450;
- src[i * 2 + 1] = -13449;
- }
-
- size_t ret =
- s16_stereo_to_mono((uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(1, dst[i]);
- }
-}
-
-// Test Stereo to Mono conversion. S16_LE, Overflow.
-TEST(FormatConverterOpsTest, StereoToMonoS16LEOverflow) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
- for (size_t i = 0; i < frames; ++i) {
- src[i * 2 + 0] = 0x7fff;
- src[i * 2 + 1] = 1;
- }
-
- size_t ret =
- s16_stereo_to_mono((uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(0x7fff, dst[i]);
- }
-}
-
-// Test Stereo to Mono conversion. S16_LE, Underflow.
-TEST(FormatConverterOpsTest, StereoToMonoS16LEUnderflow) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
- for (size_t i = 0; i < frames; ++i) {
- src[i * 2 + 0] = -0x8000;
- src[i * 2 + 1] = -0x1;
- }
-
- size_t ret =
- s16_stereo_to_mono((uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(-0x8000, dst[i]);
- }
-}
-
-// Test Mono to 5.1 conversion. S16_LE, Center.
-TEST(FormatConverterOpsTest, MonoTo51S16LECenter) {
- const size_t frames = 4096;
- const size_t in_ch = 1;
- const size_t out_ch = 6;
- const size_t left = 0;
- const size_t right = 1;
- const size_t center = 4;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_mono_to_51(left, right, center, (uint8_t*)src.get(), frames,
- (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < 6; ++k) {
- if (k == center)
- EXPECT_EQ(src[i], dst[i * 6 + k]);
- else
- EXPECT_EQ(0, dst[i * 6 + k]);
- }
- }
-}
-
-// Test Mono to 5.1 conversion. S16_LE, LeftRight.
-TEST(FormatConverterOpsTest, MonoTo51S16LELeftRight) {
- const size_t frames = 4096;
- const size_t in_ch = 1;
- const size_t out_ch = 6;
- const size_t left = 0;
- const size_t right = 1;
- const size_t center = -1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_mono_to_51(left, right, center, (uint8_t*)src.get(), frames,
- (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < 6; ++k) {
- if (k == left)
- EXPECT_EQ(src[i] / 2, dst[i * 6 + k]);
- else if (k == right)
- EXPECT_EQ(src[i] / 2, dst[i * 6 + k]);
- else
- EXPECT_EQ(0, dst[i * 6 + k]);
- }
- }
-}
-
-// Test Mono to 5.1 conversion. S16_LE, Unknown.
-TEST(FormatConverterOpsTest, MonoTo51S16LEUnknown) {
- const size_t frames = 4096;
- const size_t in_ch = 1;
- const size_t out_ch = 6;
- const size_t left = -1;
- const size_t right = -1;
- const size_t center = -1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_mono_to_51(left, right, center, (uint8_t*)src.get(), frames,
- (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < 6; ++k) {
- if (k == 0)
- EXPECT_EQ(src[i], dst[i * 6 + k]);
- else
- EXPECT_EQ(0, dst[6 * i + k]);
- }
- }
-}
-
-// Test Stereo to 5.1 conversion. S16_LE, Center.
-TEST(FormatConverterOpsTest, StereoTo51S16LECenter) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 6;
- const size_t left = -1;
- const size_t right = 1;
- const size_t center = 4;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_stereo_to_51(left, right, center, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < 6; ++k) {
- if (k == center)
- EXPECT_EQ(S16AddAndClip(src[i * 2], src[i * 2 + 1]), dst[i * 6 + k]);
- else
- EXPECT_EQ(0, dst[i * 6 + k]);
- }
- }
-}
-
-// Test Quad to 5.1 conversion. S16_LE.
-TEST(FormatConverterOpsTest, QuadTo51S16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 4;
- const size_t out_ch = 6;
- const unsigned int fl_quad = 0;
- const unsigned int fr_quad = 1;
- const unsigned int rl_quad = 2;
- const unsigned int rr_quad = 3;
-
- const unsigned int fl_51 = 0;
- const unsigned int fr_51 = 1;
- const unsigned int center_51 = 2;
- const unsigned int lfe_51 = 3;
- const unsigned int rl_51 = 4;
- const unsigned int rr_51 = 5;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_quad_to_51(fl_51, fr_51, rl_51, rr_51, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(0, dst[i * 6 + center_51]);
- EXPECT_EQ(0, dst[i * 6 + lfe_51]);
- EXPECT_EQ(src[i * 4 + fl_quad], dst[i * 6 + fl_51]);
- EXPECT_EQ(src[i * 4 + fr_quad], dst[i * 6 + fr_51]);
- EXPECT_EQ(src[i * 4 + rl_quad], dst[i * 6 + rl_51]);
- EXPECT_EQ(src[i * 4 + rr_quad], dst[i * 6 + rr_51]);
- }
-}
-
-// Test Stereo to 5.1 conversion. S16_LE, LeftRight.
-TEST(FormatConverterOpsTest, StereoTo51S16LELeftRight) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 6;
- const size_t left = 0;
- const size_t right = 1;
- const size_t center = -1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_stereo_to_51(left, right, center, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < 6; ++k) {
- if (k == left)
- EXPECT_EQ(src[i * 2 + 0], dst[i * 6 + k]);
- else if (k == right)
- EXPECT_EQ(src[i * 2 + 1], dst[i * 6 + k]);
- else
- EXPECT_EQ(0, dst[i * 6 + k]);
- }
- }
-}
-
-// Test Stereo to 5.1 conversion. S16_LE, Unknown.
-TEST(FormatConverterOpsTest, StereoTo51S16LEUnknown) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 6;
- const size_t left = -1;
- const size_t right = -1;
- const size_t center = -1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_stereo_to_51(left, right, center, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < 6; ++k) {
- if (k == 0 || k == 1)
- EXPECT_EQ(src[i * 2 + k], dst[i * 6 + k]);
- else
- EXPECT_EQ(0, dst[i * 6 + k]);
- }
- }
-}
-
-// Test 5.1 to Stereo conversion. S16_LE.
-TEST(FormatConverterOpsTest, _51ToStereoS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 6;
- const size_t out_ch = 2;
- const size_t left = 0;
- const size_t right = 1;
- const size_t center = 2;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret =
- s16_51_to_stereo((uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- /* Use the normalized_factor from the left channel = 1 / (|1| + |0.707|)
- * to prevent mixing overflow.
- */
- const float normalized_factor = 0.585;
-
- for (size_t i = 0; i < frames; ++i) {
- int16_t half_center = src[i * 6 + center] * 0.707 * normalized_factor;
- int16_t l = normalized_factor * src[i * 6 + left] + half_center;
- int16_t r = normalized_factor * src[i * 6 + right] + half_center;
-
- EXPECT_EQ(l, dst[i * 2 + left]);
- EXPECT_EQ(r, dst[i * 2 + right]);
- }
-}
-
-// Test 5.1 to Quad conversion. S16_LE.
-TEST(FormatConverterOpsTest, _51ToQuadS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 6;
- const size_t out_ch = 4;
- const unsigned int fl_quad = 0;
- const unsigned int fr_quad = 1;
- const unsigned int rl_quad = 2;
- const unsigned int rr_quad = 3;
-
- const unsigned int fl_51 = 0;
- const unsigned int fr_51 = 1;
- const unsigned int center_51 = 2;
- const unsigned int lfe_51 = 3;
- const unsigned int rl_51 = 4;
- const unsigned int rr_51 = 5;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_51_to_quad((uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- /* Use normalized_factor from the left channel = 1 / (|1| + |0.707| + |0.5|)
- * to prevent overflow. */
- const float normalized_factor = 0.453;
- for (size_t i = 0; i < frames; ++i) {
- int16_t half_center = src[i * 6 + center_51] * 0.707 * normalized_factor;
- int16_t lfe = src[6 * i + lfe_51] * 0.5 * normalized_factor;
- int16_t fl = normalized_factor * src[6 * i + fl_51] + half_center + lfe;
- int16_t fr = normalized_factor * src[6 * i + fr_51] + half_center + lfe;
- int16_t rl = normalized_factor * src[6 * i + rl_51] + lfe;
- int16_t rr = normalized_factor * src[6 * i + rr_51] + lfe;
- EXPECT_EQ(fl, dst[4 * i + fl_quad]);
- EXPECT_EQ(fr, dst[4 * i + fr_quad]);
- EXPECT_EQ(rl, dst[4 * i + rl_quad]);
- EXPECT_EQ(rr, dst[4 * i + rr_quad]);
- }
-}
-
-// Test Stereo to Quad conversion. S16_LE, Specify.
-TEST(FormatConverterOpsTest, StereoToQuadS16LESpecify) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 4;
- const size_t front_left = 2;
- const size_t front_right = 3;
- const size_t rear_left = 0;
- const size_t rear_right = 1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret =
- s16_stereo_to_quad(front_left, front_right, rear_left, rear_right,
- (uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(src[i * 2 + 0], dst[i * 4 + front_left]);
- EXPECT_EQ(src[i * 2 + 0], dst[i * 4 + rear_left]);
- EXPECT_EQ(src[i * 2 + 1], dst[i * 4 + front_right]);
- EXPECT_EQ(src[i * 2 + 1], dst[i * 4 + rear_right]);
- }
-}
-
-// Test Stereo to Quad conversion. S16_LE, Default.
-TEST(FormatConverterOpsTest, StereoToQuadS16LEDefault) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 4;
- const size_t front_left = -1;
- const size_t front_right = -1;
- const size_t rear_left = -1;
- const size_t rear_right = -1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret =
- s16_stereo_to_quad(front_left, front_right, rear_left, rear_right,
- (uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- EXPECT_EQ(src[i * 2 + 0], dst[i * 4 + 0]);
- EXPECT_EQ(src[i * 2 + 0], dst[i * 4 + 2]);
- EXPECT_EQ(src[i * 2 + 1], dst[i * 4 + 1]);
- EXPECT_EQ(src[i * 2 + 1], dst[i * 4 + 3]);
- }
-}
-
-// Test Quad to Stereo conversion. S16_LE, Specify.
-TEST(FormatConverterOpsTest, QuadToStereoS16LESpecify) {
- const size_t frames = 4096;
- const size_t in_ch = 4;
- const size_t out_ch = 2;
- const size_t front_left = 2;
- const size_t front_right = 3;
- const size_t rear_left = 0;
- const size_t rear_right = 1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret =
- s16_quad_to_stereo(front_left, front_right, rear_left, rear_right,
- (uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- int16_t left =
- S16AddAndClip(src[i * 4 + front_left], src[i * 4 + rear_left] / 4);
- int16_t right =
- S16AddAndClip(src[i * 4 + front_right], src[i * 4 + rear_right] / 4);
- EXPECT_EQ(left, dst[i * 2 + 0]);
- EXPECT_EQ(right, dst[i * 2 + 1]);
- }
-}
-
-// Test Quad to Stereo conversion. S16_LE, Default.
-TEST(FormatConverterOpsTest, QuadToStereoS16LEDefault) {
- const size_t frames = 4096;
- const size_t in_ch = 4;
- const size_t out_ch = 2;
- const size_t front_left = -1;
- const size_t front_right = -1;
- const size_t rear_left = -1;
- const size_t rear_right = -1;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret =
- s16_quad_to_stereo(front_left, front_right, rear_left, rear_right,
- (uint8_t*)src.get(), frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- int16_t left = S16AddAndClip(src[i * 4 + 0], src[i * 4 + 2] / 4);
- int16_t right = S16AddAndClip(src[i * 4 + 1], src[i * 4 + 3] / 4);
- EXPECT_EQ(left, dst[i * 2 + 0]);
- EXPECT_EQ(right, dst[i * 2 + 1]);
- }
-}
-
-// Test Stereo to 3ch conversion. S16_LE.
-TEST(FormatConverterOpsTest, StereoTo3chS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 3;
- struct cras_audio_format fmt = {
- .format = SND_PCM_FORMAT_S16_LE,
- .frame_rate = 48000,
- .num_channels = 3,
- };
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_default_all_to_all(&fmt, in_ch, out_ch, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- int32_t sum = 0;
- for (size_t k = 0; k < in_ch; ++k)
- sum += (int32_t)src[i * in_ch + k];
- src[i * in_ch + 0] = (int16_t)(sum / (int32_t)in_ch);
- }
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < out_ch; ++k)
- EXPECT_EQ(src[i * in_ch + 0], dst[i * out_ch + k]);
- }
-}
-
-// Test 6ch to 8ch conversion. S16_LE.
-TEST(FormatConverterOpsTest, 6chTo8chS16LE) {
- const size_t frames = 65536;
- const size_t in_ch = 6;
- const size_t out_ch = 8;
- struct cras_audio_format fmt = {
- .format = SND_PCM_FORMAT_S16_LE,
- .frame_rate = 48000,
- .num_channels = 8,
- };
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
- for (size_t i = 0; i < frames; ++i) {
- for (size_t k = 0; k < in_ch; k++) {
- src[i * in_ch + k] = (k == 0) ? (INT16_MIN + (int16_t)i) : 0;
- }
- }
-
- size_t ret = s16_default_all_to_all(&fmt, in_ch, out_ch, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- src[i * in_ch + 0] /= (int16_t)in_ch;
- for (size_t k = 0; k < out_ch; ++k)
- EXPECT_EQ(src[i * in_ch + 0], dst[i * out_ch + k]);
- }
-}
-
-// Test Multiply with Coef. S16_LE.
-TEST(FormatConverterOpsTest, MultiplyWithCoefS16LE) {
- const size_t buf_size = 4096;
-
- S16LEPtr buf = CreateS16LE(buf_size);
- FloatPtr coef = CreateFloat(buf_size);
-
- int16_t ret = s16_multiply_buf_with_coef(coef.get(), buf.get(), buf_size);
-
- int32_t exp = 0;
- for (size_t i = 0; i < buf_size; ++i)
- exp += coef[i] * buf[i];
- exp = MIN(MAX(exp, SHRT_MIN), SHRT_MAX);
-
- EXPECT_EQ((int16_t)exp, ret);
-}
-
-// Test Convert Channels. S16_LE.
-TEST(FormatConverterOpsTest, ConvertChannelsS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 3;
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
- FloatPtr ch_conv_mtx = CreateFloat(out_ch * in_ch);
- std::unique_ptr<float*[]> mtx(new float*[out_ch]);
- for (size_t i = 0; i < out_ch; ++i)
- mtx[i] = &ch_conv_mtx[i * in_ch];
-
- size_t ret =
- s16_convert_channels(mtx.get(), in_ch, out_ch, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t fr = 0; fr < frames; ++fr) {
- for (size_t i = 0; i < out_ch; ++i) {
- int16_t exp = 0;
- for (size_t k = 0; k < in_ch; ++k)
- exp += mtx[i][k] * src[fr * in_ch + k];
- exp = MIN(MAX(exp, SHRT_MIN), SHRT_MAX);
- EXPECT_EQ(exp, dst[fr * out_ch + i]);
- }
- }
-}
-
-// Test Stereo to 20ch conversion. S16_LE.
-TEST(FormatConverterOpsTest, TwoToTwentyS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 2;
- const size_t out_ch = 20;
- struct cras_audio_format fmt = {
- .format = SND_PCM_FORMAT_S16_LE,
- .frame_rate = 48000,
- .num_channels = 20,
- };
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_some_to_some(&fmt, in_ch, out_ch, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- size_t k;
- // Input channles should be directly copied over.
- for (k = 0; k < in_ch; ++k) {
- EXPECT_EQ(src[i * in_ch + k], dst[i * out_ch + k]);
- }
- // The rest should be zeroed.
- for (; k < out_ch; ++k) {
- EXPECT_EQ(0, dst[i * out_ch + k]);
- }
-
- }
-}
-
-// Test 20ch to Stereo. S16_LE.
-TEST(FormatConverterOpsTest, TwentyToTwoS16LE) {
- const size_t frames = 4096;
- const size_t in_ch = 20;
- const size_t out_ch = 2;
- struct cras_audio_format fmt = {
- .format = SND_PCM_FORMAT_S16_LE,
- .frame_rate = 48000,
- .num_channels = 2,
- };
-
- S16LEPtr src = CreateS16LE(frames * in_ch);
- S16LEPtr dst = CreateS16LE(frames * out_ch);
-
- size_t ret = s16_some_to_some(&fmt, in_ch, out_ch, (uint8_t*)src.get(),
- frames, (uint8_t*)dst.get());
- EXPECT_EQ(ret, frames);
-
- for (size_t i = 0; i < frames; ++i) {
- size_t k;
- // Input channles should be directly copied over.
- for (k = 0; k < out_ch; ++k) {
- EXPECT_EQ(src[i * in_ch + k], dst[i * out_ch + k]);
- }
- }
-}
-
-extern "C" {} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/fmt_conv_unittest.cc b/cras/src/tests/fmt_conv_unittest.cc
deleted file mode 100644
index c66984ee..00000000
--- a/cras/src/tests/fmt_conv_unittest.cc
+++ /dev/null
@@ -1,1781 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <math.h>
-#include <sys/param.h>
-
-extern "C" {
-#include "cras_fmt_conv.h"
-#include "cras_types.h"
-}
-
-static int mono_channel_layout[CRAS_CH_MAX] = {-1, -1, -1, -1, 0, -1,
- -1, -1, -1, -1, -1};
-static int stereo_channel_layout[CRAS_CH_MAX] = {0, 1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1};
-static int surround_channel_center_layout[CRAS_CH_MAX] = {0, 1, 2, 3, 4, 5,
- -1, -1, -1, -1, -1};
-static int surround_channel_left_right_layout[CRAS_CH_MAX] = {
- 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
-static int surround_channel_unknown_layout[CRAS_CH_MAX] = {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
-static int quad_channel_layout[CRAS_CH_MAX] = {0, 1, 2, 3, -1, -1,
- -1, -1, -1, -1, -1};
-static int linear_resampler_needed_val;
-static double linear_resampler_ratio = 1.0;
-static unsigned int linear_resampler_num_channels;
-static unsigned int linear_resampler_format_bytes;
-static int linear_resampler_src_rate;
-static int linear_resampler_dst_rate;
-
-void ResetStub() {
- linear_resampler_needed_val = 0;
- linear_resampler_ratio = 1.0;
-}
-
-// Like malloc or calloc, but fill the memory with random bytes.
-static void* ralloc(size_t size) {
- unsigned char* buf = (unsigned char*)malloc(size);
- while (size--)
- buf[size] = rand() & 0xff;
- return buf;
-}
-
-static void swap_channel_layout(int8_t* layout,
- CRAS_CHANNEL a,
- CRAS_CHANNEL b) {
- int8_t tmp = layout[a];
- layout[a] = layout[b];
- layout[b] = tmp;
-}
-
-TEST(FormatConverterTest, SmallFramesSRCWithLinearResampler) {
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
- struct cras_fmt_conv* c;
- int16_t* in_buf;
- int16_t* out_buf;
- unsigned int in_frames = 1;
- unsigned int out_frames = 2;
-
- ResetStub();
- in_fmt.format = out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = out_fmt.num_channels = 1;
- in_fmt.frame_rate = 16000;
- out_fmt.frame_rate = 48000;
- linear_resampler_needed_val = 1;
-
- in_buf = (int16_t*)malloc(10 * 2 * 2);
- out_buf = (int16_t*)malloc(10 * 2 * 2);
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, 10, 1);
- EXPECT_NE((void*)NULL, c);
- EXPECT_EQ(out_fmt.frame_rate, linear_resampler_src_rate);
- EXPECT_EQ(out_fmt.frame_rate, linear_resampler_dst_rate);
-
- /* When process on small buffers doing SRC 16KHz -> 48KHz,
- * speex does the work in two steps:
- *
- * (1) 0 -> 2 frames in output
- * (2) 1 -> 1 frame in output
- *
- * Total result is 1 frame consumed in input and generated
- * 3 frames in output.
- */
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buf, (uint8_t*)out_buf, &in_frames, out_frames);
- EXPECT_EQ(2, out_frames);
- EXPECT_EQ(0, in_frames);
-
- in_frames = 1;
- out_frames = 2;
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buf, (uint8_t*)out_buf, &in_frames, out_frames);
- EXPECT_EQ(1, out_frames);
- EXPECT_EQ(1, in_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buf);
- free(out_buf);
-}
-
-// Only support LE, BE should fail.
-TEST(FormatConverterTest, InvalidParamsOnlyLE) {
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
- struct cras_fmt_conv* c;
-
- ResetStub();
- in_fmt.format = out_fmt.format = SND_PCM_FORMAT_S32_BE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, 4096, 0);
- EXPECT_EQ(NULL, c);
-}
-
-// Test Mono to Stereo mix.
-TEST(FormatConverterTest, MonoToStereo) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 1;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (size_t i = 0; i < buf_size; i++) {
- if (in_buff[i] != out_buff[i * 2] || in_buff[i] != out_buff[i * 2 + 1]) {
- EXPECT_TRUE(false);
- break;
- }
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test Stereo to Mono mix.
-TEST(FormatConverterTest, StereoToMono) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- unsigned int i;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 1;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)malloc(buf_size * cras_get_format_bytes(&out_fmt));
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 2] = 13450;
- in_buff[i * 2 + 1] = -13449;
- }
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(1, out_buff[i]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test Stereo to Mono mix. Overflow.
-TEST(FormatConverterTest, StereoToMonoOverflow) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- unsigned int i;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 1;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)malloc(buf_size * cras_get_format_bytes(&out_fmt));
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 2] = 0x7fff;
- in_buff[i * 2 + 1] = 1;
- }
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(0x7fff, out_buff[i]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test Stereo to Mono mix. Underflow.
-TEST(FormatConverterTest, StereoToMonoUnderflow) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- unsigned int i;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 1;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)malloc(buf_size * cras_get_format_bytes(&out_fmt));
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 2] = -0x8000;
- in_buff[i * 2 + 1] = -1;
- }
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(-0x8000, out_buff[i]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test Stereo to Mono mix 24 and 32 bit.
-TEST(FormatConverterTest, StereoToMono24bit) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int32_t* out_buff;
- unsigned int i;
- const size_t buf_size = 100;
- unsigned int in_buf_size = 100;
- unsigned int test;
-
- for (test = 0; test < 2; test++) {
- ResetStub();
- if (test == 0) {
- in_fmt.format = SND_PCM_FORMAT_S24_LE;
- out_fmt.format = SND_PCM_FORMAT_S24_LE;
- } else {
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S32_LE;
- }
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 1;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int32_t*)malloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int32_t*)malloc(buf_size * cras_get_format_bytes(&out_fmt));
- // TODO(dgreid) - s/0x10000/1/ once it stays full bits the whole way.
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 2] = 13450 << 16;
- in_buff[i * 2 + 1] = -in_buff[i * 2] + 0x10000;
- }
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(0x10000, out_buff[i]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
- }
-}
-
-// Test 5.1 to Stereo mix.
-TEST(FormatConverterTest, SurroundToStereo) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- unsigned int i;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
-
- /* Swap channel to FL = 13450, RL = -100.
- * Assert right channel is silent.
- */
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 6] = 13450;
- in_buff[i * 6 + 1] = 0;
- in_buff[i * 6 + 2] = -100;
- in_buff[i * 6 + 3] = 0;
- in_buff[i * 6 + 4] = 0;
- in_buff[i * 6 + 5] = 0;
- }
- out_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++)
- EXPECT_LT(0, out_buff[i * 2]);
- cras_fmt_conv_destroy(&c);
-
- /* Swap channel to FR = 13450, RR = -100.
- * Assert left channel is silent.
- */
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_FL, CRAS_CH_FR);
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_RL, CRAS_CH_RR);
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++)
- EXPECT_LT(0, out_buff[i * 2 + 1]);
- cras_fmt_conv_destroy(&c);
-
- /* Swap channel to FC = 13450, LFE = -100.
- * Assert output left and right has equal magnitude.
- */
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_FR, CRAS_CH_FC);
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_RR, CRAS_CH_LFE);
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_NE(0, out_buff[i * 2]);
- EXPECT_EQ(out_buff[i * 2], out_buff[i * 2 + 1]);
- }
- cras_fmt_conv_destroy(&c);
-
- /* Swap channel to FR = 13450, FL = -100.
- * Assert output left is positive and right is negative. */
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_LFE, CRAS_CH_FR);
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_FC, CRAS_CH_FL);
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_LT(0, out_buff[i * 2]);
- EXPECT_GT(0, out_buff[i * 2 + 1]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 5.1 to Quad mix.
-TEST(FormatConverterTest, SurroundToQuad) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- unsigned int i;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 4;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
-
- const int16_t in_fl = 100;
- const int16_t in_fr = 200;
- const int16_t in_rl = 200;
- const int16_t in_rr = 300;
- const int16_t in_fc = 60;
- const int16_t in_lfe = 90;
-
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 6 + CRAS_CH_FL] = in_fl;
- in_buff[i * 6 + CRAS_CH_FR] = in_fr;
- in_buff[i * 6 + CRAS_CH_RL] = in_rl;
- in_buff[i * 6 + CRAS_CH_RR] = in_rr;
- in_buff[i * 6 + CRAS_CH_FC] = in_fc;
- in_buff[i * 6 + CRAS_CH_LFE] = in_lfe;
- }
- out_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- // This is the sum of mtx[CRAS_CH_FL] coefficients.
- const float normalize_factor = 1.0 / (1 + 0.707 + 0.5);
-
- for (i = 0; i < buf_size; i++) {
- int16_t lfe = 0.5 * normalize_factor * in_lfe;
- int16_t center = 0.707 * normalize_factor * in_fc;
- int16_t fl = normalize_factor * in_fl + center + lfe;
- int16_t fr = normalize_factor * in_fr + center + lfe;
- int16_t rl = normalize_factor * in_rl + lfe;
- int16_t rr = normalize_factor * in_rr + lfe;
-
- EXPECT_EQ(fl, out_buff[i * 4 + CRAS_CH_FL]);
- EXPECT_EQ(fr, out_buff[i * 4 + CRAS_CH_FR]);
- EXPECT_EQ(rl, out_buff[i * 4 + CRAS_CH_RL]);
- EXPECT_EQ(rr, out_buff[i * 4 + CRAS_CH_RR]);
- }
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test Quad to Stereo mix.
-TEST(FormatConverterTest, QuadToStereo) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- unsigned int i;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 4;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = quad_channel_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
-
- /*
- * Set left channel positive, right channel negative, assert values are
- * copied and scaled as expected.
- */
- for (i = 0; i < buf_size; i++) {
- in_buff[i * 4] = 800;
- in_buff[i * 4 + 1] = -800;
- in_buff[i * 4 + 2] = 80;
- in_buff[i * 4 + 3] = -80;
- }
- out_buff = (int16_t*)malloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
-
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(820, out_buff[i * 2]);
- EXPECT_EQ(-820, out_buff[i * 2 + 1]);
- }
- cras_fmt_conv_destroy(&c);
-
- /*
- * Swap left and right channels, check channel map is respected.
- */
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_FL, CRAS_CH_FR);
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_RL, CRAS_CH_RR);
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(-820, out_buff[i * 2]);
- EXPECT_EQ(820, out_buff[i * 2 + 1]);
- }
- cras_fmt_conv_destroy(&c);
-
- /*
- * Swap front and rear, check channel map is respected.
- */
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_FR, CRAS_CH_RR);
- swap_channel_layout(in_fmt.channel_layout, CRAS_CH_FL, CRAS_CH_RL);
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(-280, out_buff[i * 2]);
- EXPECT_EQ(280, out_buff[i * 2 + 1]);
- }
- cras_fmt_conv_destroy(&c);
-
- /*
- * Empty channel map, check default behavior is applied.
- */
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = -1;
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (i = 0; i < buf_size; i++) {
- EXPECT_EQ(820, out_buff[i * 2]);
- EXPECT_EQ(-820, out_buff[i * 2 + 1]);
- }
- cras_fmt_conv_destroy(&c);
-
- free(in_buff);
- free(out_buff);
-}
-
-// Test 2 to 1 SRC.
-TEST(FormatConverterTest, Convert2To1) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- in_fmt.frame_rate = 96000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size / 2, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size / 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size / 2);
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 1 to 2 SRC.
-TEST(FormatConverterTest, Convert1To2) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- in_fmt.frame_rate = 22050;
- out_fmt.frame_rate = 44100;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size * 2, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size * 2);
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 1 to 2 SRC with mono to stereo conversion.
-TEST(FormatConverterTest, Convert1To2MonoToStereo) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 1;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 22050;
- out_fmt.frame_rate = 44100;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_out_frames_to_in(c, buf_size);
- EXPECT_EQ(buf_size / 2, out_frames);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size * 2, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size * 2);
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 32 to 16 bit conversion.
-TEST(FormatConverterTest, ConvertS32LEToS16LE) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++)
- EXPECT_EQ((int16_t)(in_buff[i] >> 16), out_buff[i]);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 24 to 16 bit conversion.
-TEST(FormatConverterTest, ConvertS24LEToS16LE) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S24_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++)
- EXPECT_EQ((int16_t)(in_buff[i] >> 8), out_buff[i]);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 8 to 16 bit conversion.
-TEST(FormatConverterTest, ConvertU8LEToS16LE) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- uint8_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_U8;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (uint8_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++)
- EXPECT_EQ((int16_t)((uint16_t)((int16_t)(in_buff[i]) - 128) << 8),
- out_buff[i]);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 to 32 bit conversion.
-TEST(FormatConverterTest, ConvertS16LEToS32LE) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int32_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S32_LE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++)
- EXPECT_EQ((int32_t)((uint32_t)(int32_t)in_buff[i] << 16), out_buff[i]);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 to 24 bit conversion.
-TEST(FormatConverterTest, ConvertS16LEToS24LE) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int32_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S24_LE;
- in_fmt.num_channels = out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int32_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++)
- EXPECT_EQ((int32_t)((uint32_t)(int32_t)in_buff[i] << 8), out_buff[i]);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 to 8 bit conversion.
-TEST(FormatConverterTest, ConvertS16LEToU8) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- uint8_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_U8;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (uint8_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++)
- EXPECT_EQ((in_buff[i] >> 8) + 128, out_buff[i]);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 32 bit 5.1 to 16 bit stereo conversion.
-TEST(FormatConverterTest, ConvertS32LEToS16LEDownmix51ToStereo) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 bit stereo to 5.1 conversion.
-TEST(FormatConverterTest, ConvertS16LEToS16LEStereoTo51) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 6;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- out_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++) {
- /* Check mono be converted to CRAS_CH_FL and CRAS_CH_FR */
- EXPECT_EQ(in_buff[2 * i], out_buff[6 * i]);
- EXPECT_EQ(in_buff[2 * i + 1], out_buff[6 * i + 1]);
- EXPECT_EQ(0, out_buff[6 * i + 2]);
- EXPECT_EQ(0, out_buff[6 * i + 3]);
- EXPECT_EQ(0, out_buff[6 * i + 4]);
- EXPECT_EQ(0, out_buff[6 * i + 5]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 bit mono to 5.1 conversion. Center.
-TEST(FormatConverterTest, ConvertS16LEToS16LEMonoTo51Center) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 1;
- out_fmt.num_channels = 6;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- out_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++) {
- /* Check mono be converted to CRAS_CH_FC */
- EXPECT_EQ(in_buff[i], out_buff[6 * i + 4]);
- EXPECT_EQ(0, out_buff[6 * i + 0]);
- EXPECT_EQ(0, out_buff[6 * i + 1]);
- EXPECT_EQ(0, out_buff[6 * i + 2]);
- EXPECT_EQ(0, out_buff[6 * i + 3]);
- EXPECT_EQ(0, out_buff[6 * i + 5]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 bit mono to 5.1 conversion. Left Right.
-TEST(FormatConverterTest, ConvertS16LEToS16LEMonoTo51LeftRight) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- unsigned int i, left, right;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 1;
- out_fmt.num_channels = 6;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- out_fmt.channel_layout[i] = surround_channel_left_right_layout[i];
- left = surround_channel_left_right_layout[CRAS_CH_FL];
- right = surround_channel_left_right_layout[CRAS_CH_FR];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++) {
- /* Check mono be converted to CRAS_CH_FL and CRAS_CH_FR */
- for (unsigned int k = 0; k < 6; ++k) {
- if (k == left)
- EXPECT_EQ(in_buff[i] / 2, out_buff[6 * i + left]);
- else if (k == right)
- EXPECT_EQ(in_buff[i] / 2, out_buff[6 * i + right]);
- else
- EXPECT_EQ(0, out_buff[6 * i + k]);
- }
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 bit mono to 5.1 conversion. Unknown.
-TEST(FormatConverterTest, ConvertS16LEToS16LEMonoTo51Unknown) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 1;
- out_fmt.num_channels = 6;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- out_fmt.channel_layout[i] = surround_channel_unknown_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++) {
- /* Check mono be converted to CRAS_CH_FL */
- EXPECT_EQ(in_buff[i], out_buff[6 * i + 0]);
- EXPECT_EQ(0, out_buff[6 * i + 1]);
- EXPECT_EQ(0, out_buff[6 * i + 2]);
- EXPECT_EQ(0, out_buff[6 * i + 3]);
- EXPECT_EQ(0, out_buff[6 * i + 4]);
- EXPECT_EQ(0, out_buff[6 * i + 5]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 16 bit stereo to quad conversion.
-TEST(FormatConverterTest, ConvertS16LEToS16LEStereoToQuad) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int16_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 4;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (unsigned int i = 0; i < CRAS_CH_MAX; i++)
- out_fmt.channel_layout[i] = quad_channel_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size, out_frames);
-
- in_buff = (int16_t*)malloc(buf_size * cras_get_format_bytes(&in_fmt));
- for (unsigned int i = 0; i < in_buf_size; i++) {
- in_buff[i * 2] = 40;
- in_buff[i * 2 + 1] = 80;
- }
-
- out_buff = (int16_t*)malloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++) {
- EXPECT_EQ(40, out_buff[4 * i]);
- EXPECT_EQ(80, out_buff[4 * i + 1]);
- EXPECT_EQ(40, out_buff[4 * i + 2]);
- EXPECT_EQ(80, out_buff[4 * i + 3]);
- }
- cras_fmt_conv_destroy(&c);
-
- // Swap channels and check channel layout is respected.
- swap_channel_layout(out_fmt.channel_layout, CRAS_CH_FL, CRAS_CH_RR);
- swap_channel_layout(out_fmt.channel_layout, CRAS_CH_RL, CRAS_CH_FR);
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(buf_size, out_frames);
- for (unsigned int i = 0; i < buf_size; i++) {
- EXPECT_EQ(80, out_buff[4 * i]);
- EXPECT_EQ(40, out_buff[4 * i + 1]);
- EXPECT_EQ(80, out_buff[4 * i + 2]);
- EXPECT_EQ(40, out_buff[4 * i + 3]);
- }
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 32 bit 5.1 to 16 bit stereo conversion with SRC 1 to 2.
-TEST(FormatConverterTest, ConvertS32LEToS16LEDownmix51ToStereo48To96) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 96000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size * 2, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size * 2);
- EXPECT_EQ(buf_size * 2, out_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 32 bit 5.1 to 16 bit stereo conversion with SRC 2 to 1.
-TEST(FormatConverterTest, ConvertS32LEToS16LEDownmix51ToStereo96To48) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 96000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size / 2, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size / 2 * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size / 2);
- EXPECT_EQ(buf_size / 2, out_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 32 bit 5.1 to 16 bit stereo conversion with SRC 48 to 44.1.
-TEST(FormatConverterTest, ConvertS32LEToS16LEDownmix51ToStereo48To441) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- size_t ret_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 44100;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_LT(out_frames, buf_size);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(out_frames * cras_get_format_bytes(&out_fmt));
- ret_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, out_frames);
- EXPECT_EQ(out_frames, ret_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test 32 bit 5.1 to 16 bit stereo conversion with SRC 441 to 48.
-TEST(FormatConverterTest, ConvertS32LEToS16LEDownmix51ToStereo441To48) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- size_t ret_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 44100;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_GT(out_frames, buf_size);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff =
- (int16_t*)ralloc((out_frames - 1) * cras_get_format_bytes(&out_fmt));
- ret_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, out_frames - 1);
- EXPECT_EQ(out_frames - 1, ret_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test Invalid buffer length just truncates.
-TEST(FormatConverterTest, ConvertS32LEToS16LEDownmix51ToStereo96To48Short) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- size_t ret_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S32_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 6;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 96000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++)
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size, 0);
- ASSERT_NE(c, (void*)NULL);
-
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(buf_size / 2, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff =
- (int16_t*)ralloc((out_frames - 2) * cras_get_format_bytes(&out_fmt));
- ret_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, out_frames - 2);
- EXPECT_EQ(out_frames - 2, ret_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test format convert pre linear resample and then follows SRC from 96 to 48.
-TEST(FormatConverterTest, Convert96to48PreLinearResample) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- unsigned int expected_fr;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 96000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++) {
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
- out_fmt.channel_layout[i] = surround_channel_center_layout[i];
- }
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size * 2, 1);
- ASSERT_NE(c, (void*)NULL);
- EXPECT_EQ(out_fmt.frame_rate, linear_resampler_src_rate);
- EXPECT_EQ(out_fmt.frame_rate, linear_resampler_dst_rate);
-
- linear_resampler_needed_val = 1;
- linear_resampler_ratio = 1.01;
- expected_fr = buf_size / 2 * linear_resampler_ratio;
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(expected_fr, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, out_frames);
- EXPECT_EQ(expected_fr, out_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test format convert SRC from 96 to 48 and then post linear resample.
-TEST(FormatConverterTest, Convert96to48PostLinearResample) {
- struct cras_fmt_conv* c;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- size_t out_frames;
- int32_t* in_buff;
- int16_t* out_buff;
- const size_t buf_size = 4096;
- unsigned int in_buf_size = 4096;
- unsigned int expected_fr;
- int i;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 96000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++) {
- in_fmt.channel_layout[i] = surround_channel_center_layout[i];
- out_fmt.channel_layout[i] = surround_channel_center_layout[i];
- }
-
- c = cras_fmt_conv_create(&in_fmt, &out_fmt, buf_size * 2, 0);
- ASSERT_NE(c, (void*)NULL);
- EXPECT_EQ(out_fmt.frame_rate, linear_resampler_src_rate);
- EXPECT_EQ(out_fmt.frame_rate, linear_resampler_dst_rate);
-
- linear_resampler_needed_val = 1;
- linear_resampler_ratio = 0.99;
- expected_fr = buf_size / 2 * linear_resampler_ratio;
- out_frames = cras_fmt_conv_in_frames_to_out(c, buf_size);
- EXPECT_EQ(expected_fr, out_frames);
-
- in_buff = (int32_t*)ralloc(buf_size * cras_get_format_bytes(&in_fmt));
- out_buff = (int16_t*)ralloc(buf_size * cras_get_format_bytes(&out_fmt));
- out_frames = cras_fmt_conv_convert_frames(
- c, (uint8_t*)in_buff, (uint8_t*)out_buff, &in_buf_size, buf_size);
- EXPECT_EQ(expected_fr, out_frames);
-
- cras_fmt_conv_destroy(&c);
- free(in_buff);
- free(out_buff);
-}
-
-// Test format converter created in config_format_converter
-TEST(FormatConverterTest, ConfigConverter) {
- int i;
- struct cras_fmt_conv* c = NULL;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 1;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 96000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++) {
- in_fmt.channel_layout[i] = mono_channel_layout[i];
- out_fmt.channel_layout[i] = stereo_channel_layout[i];
- }
-
- config_format_converter(&c, CRAS_STREAM_OUTPUT, &in_fmt, &out_fmt, 4096);
- ASSERT_NE(c, (void*)NULL);
-
- cras_fmt_conv_destroy(&c);
-}
-
-// Test format converter not created when in/out format conversion is not
-// needed.
-TEST(FormatConverterTest, ConfigConverterNoNeed) {
- int i;
- struct cras_fmt_conv* c = NULL;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 2;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++) {
- in_fmt.channel_layout[i] = stereo_channel_layout[i];
- out_fmt.channel_layout[i] = stereo_channel_layout[i];
- }
-
- config_format_converter(&c, CRAS_STREAM_OUTPUT, &in_fmt, &out_fmt, 4096);
- EXPECT_NE(c, (void*)NULL);
- EXPECT_EQ(0, cras_fmt_conversion_needed(c));
- cras_fmt_conv_destroy(&c);
-}
-
-// Test format converter not created for input when in/out format differs
-// at channel count or layout.
-TEST(FormatConverterTest, ConfigConverterNoNeedForInput) {
- static int kmic_channel_layout[CRAS_CH_MAX] = {0, 1, -1, -1, 2, -1,
- -1, -1, -1, -1, -1};
- int i;
- struct cras_fmt_conv* c = NULL;
- struct cras_audio_format in_fmt;
- struct cras_audio_format out_fmt;
-
- ResetStub();
- in_fmt.format = SND_PCM_FORMAT_S16_LE;
- out_fmt.format = SND_PCM_FORMAT_S16_LE;
- in_fmt.num_channels = 2;
- out_fmt.num_channels = 3;
- in_fmt.frame_rate = 48000;
- out_fmt.frame_rate = 48000;
- for (i = 0; i < CRAS_CH_MAX; i++) {
- in_fmt.channel_layout[i] = stereo_channel_layout[i];
- out_fmt.channel_layout[i] = kmic_channel_layout[i];
- }
-
- config_format_converter(&c, CRAS_STREAM_INPUT, &in_fmt, &out_fmt, 4096);
- EXPECT_NE(c, (void*)NULL);
- EXPECT_EQ(0, cras_fmt_conversion_needed(c));
- cras_fmt_conv_destroy(&c);
-}
-
-TEST(ChannelRemixTest, ChannelRemixAppliedOrNot) {
- float coeff[4] = {0.5, 0.5, 0.26, 0.73};
- struct cras_fmt_conv* conv;
- struct cras_audio_format fmt;
- int16_t *buf, *res;
- unsigned i;
-
- fmt.num_channels = 2;
- conv = cras_channel_remix_conv_create(2, coeff);
-
- buf = (int16_t*)ralloc(50 * 4);
- res = (int16_t*)malloc(50 * 4);
-
- memcpy(res, buf, 50 * 4);
-
- /* Remix conversion will not apply for non S16_LE format. */
- fmt.format = SND_PCM_FORMAT_S24_LE;
- cras_channel_remix_convert(conv, &fmt, (uint8_t*)buf, 50);
- for (i = 0; i < 100; i++)
- EXPECT_EQ(res[i], buf[i]);
-
- for (i = 0; i < 100; i += 2) {
- res[i] = coeff[0] * buf[i];
- res[i] += coeff[1] * buf[i + 1];
- res[i + 1] = coeff[2] * buf[i];
- res[i + 1] += coeff[3] * buf[i + 1];
- }
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- cras_channel_remix_convert(conv, &fmt, (uint8_t*)buf, 50);
- for (i = 0; i < 100; i++)
- EXPECT_EQ(res[i], buf[i]);
-
- /* If num_channels not match, remix conversion will not apply. */
- fmt.num_channels = 6;
- cras_channel_remix_convert(conv, &fmt, (uint8_t*)buf, 50);
- for (i = 0; i < 100; i++)
- EXPECT_EQ(res[i], buf[i]);
-
- cras_fmt_conv_destroy(&conv);
- free(buf);
- free(res);
-}
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-extern "C" {
-float** cras_channel_conv_matrix_alloc(size_t in_ch, size_t out_ch) {
- int i;
- float** conv_mtx;
- conv_mtx = (float**)calloc(CRAS_CH_MAX, sizeof(*conv_mtx));
- for (i = 0; i < CRAS_CH_MAX; i++)
- conv_mtx[i] = (float*)calloc(CRAS_CH_MAX, sizeof(*conv_mtx[i]));
- return conv_mtx;
-}
-void cras_channel_conv_matrix_destroy(float** mtx, size_t out_ch) {
- int i;
- for (i = 0; i < CRAS_CH_MAX; i++)
- free(mtx[i]);
- free(mtx);
-}
-float** cras_channel_conv_matrix_create(const struct cras_audio_format* in,
- const struct cras_audio_format* out) {
- return cras_channel_conv_matrix_alloc(in->num_channels, out->num_channels);
-}
-struct linear_resampler* linear_resampler_create(unsigned int num_channels,
- unsigned int format_bytes,
- float src_rate,
- float dst_rate) {
- linear_resampler_format_bytes = format_bytes;
- linear_resampler_num_channels = num_channels;
- linear_resampler_src_rate = src_rate;
- linear_resampler_dst_rate = dst_rate;
- return reinterpret_cast<struct linear_resampler*>(0x33);
- ;
-}
-
-int linear_resampler_needed(struct linear_resampler* lr) {
- return linear_resampler_needed_val;
-}
-
-void linear_resampler_set_rates(struct linear_resampler* lr,
- unsigned int from,
- unsigned int to) {
- linear_resampler_src_rate = from;
- linear_resampler_dst_rate = to;
-}
-
-unsigned int linear_resampler_out_frames_to_in(struct linear_resampler* lr,
- unsigned int frames) {
- return (double)frames / linear_resampler_ratio;
-}
-
-/* Converts the frames count from input rate to output rate. */
-unsigned int linear_resampler_in_frames_to_out(struct linear_resampler* lr,
- unsigned int frames) {
- return (double)frames * linear_resampler_ratio;
-}
-
-unsigned int linear_resampler_resample(struct linear_resampler* lr,
- uint8_t* src,
- unsigned int* src_frames,
- uint8_t* dst,
- unsigned dst_frames) {
- unsigned int resampled_fr = *src_frames * linear_resampler_ratio;
-
- if (resampled_fr > dst_frames) {
- resampled_fr = dst_frames;
- *src_frames = dst_frames / linear_resampler_ratio;
- }
- unsigned int resampled_bytes = resampled_fr * linear_resampler_format_bytes *
- linear_resampler_num_channels;
- for (size_t i = 0; i < resampled_bytes; i++)
- dst[i] = (uint8_t)rand() & 0xff;
-
- return resampled_fr;
-}
-
-void linear_resampler_destroy(struct linear_resampler* lr) {}
-} // extern "C"
diff --git a/cras/src/tests/hfp_ag_profile_unittest.cc b/cras/src/tests/hfp_ag_profile_unittest.cc
deleted file mode 100644
index 3ecd2407..00000000
--- a/cras/src/tests/hfp_ag_profile_unittest.cc
+++ /dev/null
@@ -1,310 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "cras_bt_log.h"
-#include "cras_bt_profile.h"
-#include "cras_hfp_ag_profile.h"
-#include "cras_iodev.h"
-}
-
-static int with_sco_pcm;
-static struct cras_iodev fake_sco_out, fake_sco_in;
-static struct cras_bt_device* fake_device;
-static struct cras_bt_profile* internal_bt_profile;
-
-static size_t hfp_alsa_iodev_create_called;
-static size_t hfp_alsa_iodev_destroy_called;
-static size_t hfp_iodev_create_called;
-static size_t hfp_iodev_destroy_called;
-static size_t cras_bt_device_notify_profile_dropped_called;
-static struct cras_bt_device* cras_bt_device_notify_profile_dropped_dev;
-static enum cras_bt_device_profile
- cras_bt_device_notify_profile_dropped_profile;
-
-static void ResetStubData() {
- hfp_alsa_iodev_create_called = 0;
- hfp_alsa_iodev_destroy_called = 0;
- hfp_iodev_create_called = 0;
- hfp_iodev_destroy_called = 0;
- cras_bt_device_notify_profile_dropped_called = 0;
-}
-
-namespace {
-
-class HfpAgProfile : public testing::Test {
- protected:
- virtual void SetUp() {
- btlog = cras_bt_event_log_init();
- ResetStubData();
- }
-
- virtual void TearDown() { cras_bt_event_log_deinit(btlog); }
-};
-
-TEST_F(HfpAgProfile, StartWithoutScoPCM) {
- int ret;
- struct cras_bt_profile* bt_profile;
-
- with_sco_pcm = 0;
- fake_device = (struct cras_bt_device*)0xdeadbeef;
- /* to get the cras_hfp_ag_profile */
- cras_hfp_ag_profile_create(NULL);
- bt_profile = internal_bt_profile;
- bt_profile->new_connection(NULL, bt_profile, fake_device, 0);
-
- ret = cras_hfp_ag_start(fake_device);
-
- EXPECT_EQ(0, ret);
- EXPECT_EQ(2, hfp_iodev_create_called);
-
- /* Start ag twice won't create more iodev. */
- ret = cras_hfp_ag_start(fake_device);
- EXPECT_EQ(0, ret);
- EXPECT_EQ(2, hfp_iodev_create_called);
-
- bt_profile->release(bt_profile);
-
- EXPECT_EQ(2, hfp_iodev_destroy_called);
-}
-
-TEST_F(HfpAgProfile, StartWithScoPCM) {
- int ret;
- struct cras_bt_profile* bt_profile;
-
- with_sco_pcm = 1;
- fake_device = (struct cras_bt_device*)0xdeadbeef;
- /* to get the cras_hfp_ag_profile */
- cras_hfp_ag_profile_create(NULL);
- bt_profile = internal_bt_profile;
- bt_profile->new_connection(NULL, bt_profile, fake_device, 0);
-
- ret = cras_hfp_ag_start(fake_device);
-
- EXPECT_EQ(0, ret);
- EXPECT_EQ(2, hfp_alsa_iodev_create_called);
-
- bt_profile->release(bt_profile);
-
- EXPECT_EQ(2, hfp_alsa_iodev_destroy_called);
-}
-
-TEST_F(HfpAgProfile, RemoveConflictAG) {
- struct cras_bt_profile* bt_profile;
- struct cras_bt_device* new_dev =
- reinterpret_cast<struct cras_bt_device*>(0x123);
- ;
-
- with_sco_pcm = 0;
- fake_device = (struct cras_bt_device*)0xdeadbeef;
- /* to get the cras_hfp_ag_profile */
- cras_hfp_ag_profile_create(NULL);
- bt_profile = internal_bt_profile;
- bt_profile->new_connection(NULL, bt_profile, fake_device, 0);
-
- bt_profile->new_connection(NULL, bt_profile, new_dev, 0);
-
- /* Expect removing conflict of new_dev triggers profile drop on
- * fake_device. */
- cras_hfp_ag_remove_conflict(new_dev);
- EXPECT_EQ(1, cras_bt_device_notify_profile_dropped_called);
- EXPECT_EQ(fake_device, cras_bt_device_notify_profile_dropped_dev);
- EXPECT_EQ(CRAS_BT_DEVICE_PROFILE_HFP_HANDSFREE,
- cras_bt_device_notify_profile_dropped_profile);
-
- bt_profile->release(bt_profile);
-}
-
-} // namespace
-
-extern "C" {
-
-struct cras_bt_event_log* btlog;
-
-struct cras_iodev* cras_iodev_list_get_sco_pcm_iodev(
- enum CRAS_STREAM_DIRECTION direction) {
- if (with_sco_pcm) {
- if (direction == CRAS_STREAM_OUTPUT)
- return &fake_sco_out;
- else
- return &fake_sco_in;
- }
-
- return NULL;
-}
-
-struct cras_iodev* hfp_alsa_iodev_create(enum CRAS_STREAM_DIRECTION dir,
- struct cras_bt_device* device,
- struct hfp_slc_handle* slc,
- enum cras_bt_device_profile profile) {
- hfp_alsa_iodev_create_called++;
- return (struct cras_iodev*)0xdeadbeef;
-}
-
-void hfp_alsa_iodev_destroy(struct cras_iodev* iodev) {
- hfp_alsa_iodev_destroy_called++;
-}
-
-struct cras_iodev* hfp_iodev_create(enum CRAS_STREAM_DIRECTION dir,
- struct cras_bt_device* device,
- struct hfp_slc_handle* slc,
- enum cras_bt_device_profile profile,
- struct hfp_info* info) {
- hfp_iodev_create_called++;
- return (struct cras_iodev*)0xdeadbeef;
-}
-
-void hfp_iodev_destroy(struct cras_iodev* iodev) {
- hfp_iodev_destroy_called++;
-}
-
-int cras_bt_add_profile(DBusConnection* conn, struct cras_bt_profile* profile) {
- internal_bt_profile = profile;
- return 0;
-}
-
-int cras_bt_rm_profile(DBusConnection* conn, struct cras_bt_profile* profile) {
- internal_bt_profile = NULL;
- return 0;
-}
-
-int cras_bt_register_profile(DBusConnection* conn,
- struct cras_bt_profile* profile) {
- return 0;
-}
-
-int cras_bt_register_profiles(DBusConnection* conn) {
- return 0;
-}
-
-int cras_bt_unregister_profile(DBusConnection* conn,
- struct cras_bt_profile* profile) {
- return 0;
-}
-
-struct hfp_info* hfp_info_create() {
- return NULL;
-}
-
-int hfp_info_running(struct hfp_info* info) {
- return 0;
-}
-
-int hfp_info_stop(struct hfp_info* info) {
- return 0;
-}
-
-void hfp_info_destroy(struct hfp_info* info) {}
-
-void hfp_slc_destroy(struct hfp_slc_handle* slc_handle) {}
-
-int cras_bt_device_has_a2dp(struct cras_bt_device* device) {
- return 0;
-}
-
-int cras_bt_device_disconnect(DBusConnection* conn,
- struct cras_bt_device* device) {
- return 0;
-}
-
-const char* cras_bt_device_name(const struct cras_bt_device* device) {
- return NULL;
-}
-
-void cras_bt_device_set_append_iodev_cb(struct cras_bt_device* device,
- void (*cb)(void* data)) {}
-
-enum cras_bt_device_profile cras_bt_device_profile_from_uuid(const char* uuid) {
- return CRAS_BT_DEVICE_PROFILE_HSP_AUDIOGATEWAY;
-}
-
-struct cras_bt_adapter* cras_bt_device_adapter(
- const struct cras_bt_device* device) {
- return reinterpret_cast<struct cras_bt_adapter*>(0x123);
-}
-
-int cras_bt_adapter_wbs_supported(struct cras_bt_adapter* adapter) {
- return 1;
-}
-
-struct hfp_slc_handle* hfp_slc_create(int fd,
- int is_hsp,
- int ag_supported_features,
- struct cras_bt_device* device,
- hfp_slc_init_cb init_cb,
- hfp_slc_disconnect_cb disconnect_cb) {
- return NULL;
-}
-
-int hfp_slc_get_selected_codec(struct hfp_slc_handle* handle) {
- return HFP_CODEC_ID_CVSD;
-}
-int hfp_slc_get_ag_codec_negotiation_supported(struct hfp_slc_handle* handle) {
- return 1;
-}
-
-int hfp_slc_get_hf_codec_negotiation_supported(struct hfp_slc_handle* handle) {
- return 1;
-}
-
-int hfp_slc_get_hf_supports_battery_indicator(struct hfp_slc_handle* handle) {
- return 0;
-}
-
-int hfp_slc_get_hf_battery_level(struct hfp_slc_handle* handle) {
- return -1;
-}
-
-struct cras_bt_device* cras_a2dp_connected_device() {
- return NULL;
-}
-
-int cras_bt_device_supports_profile(const struct cras_bt_device* device,
- enum cras_bt_device_profile profile) {
- return 0;
-}
-
-void cras_a2dp_suspend_connected_device(struct cras_bt_device* device) {}
-
-const char* cras_bt_device_address(const struct cras_bt_device* device) {
- return "";
-}
-
-int cras_bt_device_audio_gateway_initialized(struct cras_bt_device* device) {
- return 0;
-}
-
-void cras_bt_device_notify_profile_dropped(
- struct cras_bt_device* device,
- enum cras_bt_device_profile profile) {
- cras_bt_device_notify_profile_dropped_called++;
- cras_bt_device_notify_profile_dropped_dev = device;
- cras_bt_device_notify_profile_dropped_profile = profile;
-}
-
-void hfp_info_set_wbs_logger(struct hfp_info* info,
- struct packet_status_logger* wbs_logger) {}
-
-void cras_observer_notify_bt_battery_changed(const char* address,
- uint32_t level) {
- return;
-}
-
-bool cras_system_get_bt_wbs_enabled() {
- return true;
-}
-
-int cras_server_metrics_hfp_wideband_selected_codec(int codec) {
- return HFP_CODEC_ID_MSBC;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/hfp_alsa_iodev_unittest.cc b/cras/src/tests/hfp_alsa_iodev_unittest.cc
deleted file mode 100644
index 8756c201..00000000
--- a/cras/src/tests/hfp_alsa_iodev_unittest.cc
+++ /dev/null
@@ -1,543 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "cras_audio_format.h"
-#include "cras_hfp_alsa_iodev.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev.h"
-}
-
-struct hfp_alsa_io {
- struct cras_iodev base;
- struct cras_bt_device* device;
- struct hfp_slc_handle* slc;
- struct cras_iodev* aio;
-};
-
-static struct cras_iodev fake_sco_out, fake_sco_in;
-static struct cras_bt_device* fake_device;
-static struct hfp_slc_handle* fake_slc;
-static struct cras_audio_format fake_format;
-
-static size_t cras_bt_device_append_iodev_called;
-static size_t cras_bt_device_rm_iodev_called;
-static size_t cras_iodev_add_node_called;
-static size_t cras_iodev_rm_node_called;
-static size_t cras_iodev_set_active_node_called;
-static size_t cras_iodev_free_format_called;
-static size_t cras_iodev_free_resources_called;
-static size_t cras_iodev_set_format_called;
-static size_t hfp_set_call_status_called;
-static size_t hfp_event_speaker_gain_called;
-
-#define _FAKE_CALL1(name) \
- static size_t fake_##name##_called; \
- static int fake_##name(void* a) { \
- fake_##name##_called++; \
- return 0; \
- }
-#define _FAKE_CALL2(name) \
- static size_t fake_##name##_called; \
- static int fake_##name(void* a, void* b) { \
- fake_##name##_called++; \
- return 0; \
- }
-#define _FAKE_CALL3(name) \
- static size_t fake_##name##_called; \
- static int fake_##name(void* a, void* b, void* c) { \
- fake_##name##_called++; \
- return 0; \
- }
-
-_FAKE_CALL1(open_dev);
-_FAKE_CALL1(update_supported_formats);
-_FAKE_CALL1(configure_dev);
-_FAKE_CALL1(close_dev);
-_FAKE_CALL1(output_underrun);
-_FAKE_CALL2(frames_queued);
-_FAKE_CALL1(delay_frames);
-_FAKE_CALL3(get_buffer);
-_FAKE_CALL2(put_buffer);
-_FAKE_CALL1(flush_buffer);
-_FAKE_CALL3(update_active_node);
-_FAKE_CALL1(start);
-_FAKE_CALL2(no_stream);
-_FAKE_CALL1(is_free_running);
-_FAKE_CALL2(get_valid_frames);
-
-static void ResetStubData() {
- cras_bt_device_append_iodev_called = 0;
- cras_bt_device_rm_iodev_called = 0;
- cras_iodev_add_node_called = 0;
- cras_iodev_rm_node_called = 0;
- cras_iodev_set_active_node_called = 0;
- cras_iodev_free_format_called = 0;
- cras_iodev_free_resources_called = 0;
- cras_iodev_set_format_called = 0;
- hfp_set_call_status_called = 0;
- hfp_event_speaker_gain_called = 0;
-
- fake_sco_out.open_dev = fake_sco_in.open_dev =
- (int (*)(struct cras_iodev*))fake_open_dev;
- fake_open_dev_called = 0;
-
- fake_sco_out.update_supported_formats = fake_sco_in.update_supported_formats =
- (int (*)(struct cras_iodev*))fake_update_supported_formats;
- fake_update_supported_formats_called = 0;
-
- fake_sco_out.configure_dev = fake_sco_in.configure_dev =
- (int (*)(struct cras_iodev*))fake_configure_dev;
- fake_configure_dev_called = 0;
-
- fake_sco_out.close_dev = fake_sco_in.close_dev =
- (int (*)(struct cras_iodev*))fake_close_dev;
- fake_close_dev_called = 0;
-
- fake_sco_out.frames_queued = fake_sco_in.frames_queued =
- (int (*)(const struct cras_iodev*, struct timespec*))fake_frames_queued;
- fake_frames_queued_called = 0;
-
- fake_sco_out.delay_frames = fake_sco_in.delay_frames =
- (int (*)(const struct cras_iodev*))fake_delay_frames;
- fake_delay_frames_called = 0;
-
- fake_sco_out.get_buffer = fake_sco_in.get_buffer = (int (*)(
- struct cras_iodev*, struct cras_audio_area**, unsigned*))fake_get_buffer;
- fake_get_buffer_called = 0;
-
- fake_sco_out.put_buffer = fake_sco_in.put_buffer =
- (int (*)(struct cras_iodev*, unsigned))fake_put_buffer;
- fake_put_buffer_called = 0;
-
- fake_sco_out.flush_buffer = fake_sco_in.flush_buffer =
- (int (*)(struct cras_iodev*))fake_flush_buffer;
- fake_flush_buffer_called = 0;
-
- fake_sco_out.update_active_node = fake_sco_in.update_active_node =
- (void (*)(struct cras_iodev*, unsigned, unsigned))fake_update_active_node;
- fake_update_active_node_called = 0;
-
- fake_sco_out.start = fake_sco_in.start =
- (int (*)(const struct cras_iodev*))fake_start;
- fake_start_called = 0;
-
- fake_sco_out.no_stream = fake_sco_in.no_stream =
- (int (*)(struct cras_iodev*, int))fake_no_stream;
- fake_no_stream_called = 0;
-
- fake_sco_out.is_free_running = fake_sco_in.is_free_running =
- (int (*)(const struct cras_iodev*))fake_is_free_running;
- fake_is_free_running_called = 0;
-
- fake_sco_out.output_underrun =
- (int (*)(struct cras_iodev*))fake_output_underrun;
- fake_output_underrun_called = 0;
-
- fake_sco_out.get_valid_frames =
- (int (*)(struct cras_iodev*, struct timespec*))fake_get_valid_frames;
- fake_get_valid_frames_called = 0;
-}
-
-namespace {
-
-class HfpAlsaIodev : public testing::Test {
- protected:
- virtual void SetUp() { ResetStubData(); }
-
- virtual void TearDown() {}
-};
-
-TEST_F(HfpAlsaIodev, CreateHfpAlsaOutputIodev) {
- struct cras_iodev* iodev;
- struct hfp_alsa_io* hfp_alsa_io;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- hfp_alsa_io = (struct hfp_alsa_io*)iodev;
-
- EXPECT_EQ(CRAS_STREAM_OUTPUT, iodev->direction);
- EXPECT_EQ(1, cras_bt_device_append_iodev_called);
- EXPECT_EQ(1, cras_iodev_add_node_called);
- EXPECT_EQ(1, cras_iodev_set_active_node_called);
- EXPECT_EQ(&fake_sco_out, hfp_alsa_io->aio);
-
- hfp_alsa_iodev_destroy(iodev);
-
- EXPECT_EQ(1, cras_bt_device_rm_iodev_called);
- EXPECT_EQ(1, cras_iodev_rm_node_called);
- EXPECT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpAlsaIodev, CreateHfpAlsaInputIodev) {
- struct cras_iodev* iodev;
- struct hfp_alsa_io* hfp_alsa_io;
-
- fake_sco_in.direction = CRAS_STREAM_INPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_in, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- hfp_alsa_io = (struct hfp_alsa_io*)iodev;
-
- EXPECT_EQ(CRAS_STREAM_INPUT, iodev->direction);
- EXPECT_EQ(1, cras_bt_device_append_iodev_called);
- EXPECT_EQ(1, cras_iodev_add_node_called);
- EXPECT_EQ(1, cras_iodev_set_active_node_called);
- EXPECT_EQ(&fake_sco_in, hfp_alsa_io->aio);
- /* Input device does not use software gain. */
- EXPECT_EQ(0, iodev->software_volume_needed);
-
- hfp_alsa_iodev_destroy(iodev);
-
- EXPECT_EQ(1, cras_bt_device_rm_iodev_called);
- EXPECT_EQ(1, cras_iodev_rm_node_called);
- EXPECT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpAlsaIodev, OpenDev) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->open_dev(iodev);
-
- EXPECT_EQ(1, fake_open_dev_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, UpdateSupportedFormat) {
- struct cras_iodev* iodev;
- size_t supported_rates[] = {8000, 0};
- size_t supported_channel_counts[] = {1, 0};
- snd_pcm_format_t supported_formats[] = {SND_PCM_FORMAT_S16_LE,
- (snd_pcm_format_t)0};
-
- fake_sco_out.supported_rates = supported_rates;
- fake_sco_out.supported_channel_counts = supported_channel_counts;
- fake_sco_out.supported_formats = supported_formats;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->update_supported_formats(iodev);
-
- // update_supported_format on alsa_io is not called.
- EXPECT_EQ(0, fake_update_supported_formats_called);
- for (size_t i = 0; i < 2; ++i) {
- EXPECT_EQ(supported_rates[i], iodev->supported_rates[i]);
- EXPECT_EQ(supported_channel_counts[i], iodev->supported_channel_counts[i]);
- EXPECT_EQ(supported_formats[i], iodev->supported_formats[i]);
- }
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, ConfigureDev) {
- struct cras_iodev* iodev;
- size_t buf_size = 8192;
- struct hfp_alsa_io* hfp_alsa_io;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- fake_sco_out.buffer_size = buf_size;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- hfp_alsa_io = (struct hfp_alsa_io*)iodev;
- iodev->format = &fake_format;
- iodev->configure_dev(iodev);
-
- EXPECT_EQ(fake_format.num_channels, hfp_alsa_io->aio->format->num_channels);
- EXPECT_EQ(fake_format.frame_rate, hfp_alsa_io->aio->format->frame_rate);
- EXPECT_EQ(fake_format.format, hfp_alsa_io->aio->format->format);
- for (int i = 0; i < CRAS_CH_MAX; i++)
- EXPECT_EQ(fake_format.channel_layout[i],
- hfp_alsa_io->aio->format->channel_layout[i]);
-
- EXPECT_EQ(1, fake_configure_dev_called);
- EXPECT_EQ(1, hfp_set_call_status_called);
- EXPECT_EQ(buf_size, iodev->buffer_size);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, CloseDev) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->close_dev(iodev);
-
- EXPECT_EQ(1, hfp_set_call_status_called);
- EXPECT_EQ(1, cras_iodev_free_format_called);
- EXPECT_EQ(1, fake_close_dev_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, FramesQueued) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->frames_queued(iodev, (struct timespec*)NULL);
-
- EXPECT_EQ(1, fake_frames_queued_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, DelayFrames) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->delay_frames(iodev);
-
- EXPECT_EQ(1, fake_delay_frames_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, GetBuffer) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->get_buffer(iodev, (struct cras_audio_area**)NULL, (unsigned*)NULL);
-
- EXPECT_EQ(1, fake_get_buffer_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, PutBuffer) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->put_buffer(iodev, 0xdeadbeef);
-
- EXPECT_EQ(1, fake_put_buffer_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, FlushBuffer) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->flush_buffer(iodev);
-
- EXPECT_EQ(1, fake_flush_buffer_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, UpdateActiveNode) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->update_active_node(iodev, 0xdeadbeef, 0xdeadbeef);
-
- EXPECT_EQ(1, fake_update_active_node_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, Start) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->start(iodev);
-
- EXPECT_EQ(1, fake_start_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, SetVolume) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->set_volume(iodev);
-
- EXPECT_EQ(1, hfp_event_speaker_gain_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, NoStream) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->min_cb_level = 0xab;
- iodev->max_cb_level = 0xcd;
-
- iodev->no_stream(iodev, 1);
-
- EXPECT_EQ(0xab, fake_sco_out.min_cb_level);
- EXPECT_EQ(0xcd, fake_sco_out.max_cb_level);
- EXPECT_EQ(1, fake_no_stream_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, IsFreeRunning) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->is_free_running(iodev);
-
- EXPECT_EQ(1, fake_is_free_running_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, OutputUnderrun) {
- struct cras_iodev* iodev;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
- iodev->min_cb_level = 0xab;
- iodev->max_cb_level = 0xcd;
-
- iodev->output_underrun(iodev);
-
- EXPECT_EQ(0xab, fake_sco_out.min_cb_level);
- EXPECT_EQ(0xcd, fake_sco_out.max_cb_level);
- EXPECT_EQ(1, fake_output_underrun_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-
-TEST_F(HfpAlsaIodev, GetValidFrames) {
- struct cras_iodev* iodev;
- struct timespec ts;
-
- fake_sco_out.direction = CRAS_STREAM_OUTPUT;
- iodev = hfp_alsa_iodev_create(&fake_sco_out, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY);
-
- iodev->get_valid_frames(iodev, &ts);
-
- EXPECT_EQ(1, fake_get_valid_frames_called);
-
- hfp_alsa_iodev_destroy(iodev);
-}
-} // namespace
-
-extern "C" {
-
-int cras_iodev_set_format(struct cras_iodev* iodev,
- const struct cras_audio_format* fmt) {
- cras_iodev_set_format_called++;
- return 0;
-}
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {
- cras_iodev_free_format_called++;
-}
-
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_add_node_called++;
- iodev->nodes = node;
-}
-
-void cras_iodev_rm_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_rm_node_called++;
- iodev->nodes = NULL;
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {
- cras_iodev_set_active_node_called++;
- iodev->active_node = node;
-}
-
-// From ewma_power
-void ewma_power_disable(struct ewma_power* ewma) {}
-
-size_t cras_system_get_volume() {
- return 0;
-}
-
-const char* cras_bt_device_name(const struct cras_bt_device* device) {
- return "fake-device-name";
-}
-
-const char* cras_bt_device_address(const struct cras_bt_device* device) {
- return "1A:2B:3C:4D:5E:6F";
-}
-
-void cras_bt_device_append_iodev(struct cras_bt_device* device,
- struct cras_iodev* iodev,
- enum cras_bt_device_profile profile) {
- cras_bt_device_append_iodev_called++;
-}
-
-void cras_bt_device_rm_iodev(struct cras_bt_device* device,
- struct cras_iodev* iodev) {
- cras_bt_device_rm_iodev_called++;
-}
-
-const char* cras_bt_device_object_path(const struct cras_bt_device* device) {
- return "/fake/object/path";
-}
-
-int cras_bt_device_get_stable_id(const struct cras_bt_device* device) {
- return 123;
-}
-
-void cras_iodev_free_resources(struct cras_iodev* iodev) {
- cras_iodev_free_resources_called++;
-}
-
-int hfp_set_call_status(struct hfp_slc_handle* handle, int call) {
- hfp_set_call_status_called++;
- return 0;
-}
-
-int hfp_event_speaker_gain(struct hfp_slc_handle* handle, int gain) {
- hfp_event_speaker_gain_called++;
- return 0;
-}
-
-int cras_bt_device_get_sco(struct cras_bt_device* device, int codec) {
- return 0;
-}
-
-void cras_bt_device_put_sco(struct cras_bt_device* device) {}
-
-int hfp_slc_get_selected_codec(struct hfp_slc_handle* handle) {
- return HFP_CODEC_ID_CVSD;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/hfp_info_unittest.cc b/cras/src/tests/hfp_info_unittest.cc
deleted file mode 100644
index 24f536ae..00000000
--- a/cras/src/tests/hfp_info_unittest.cc
+++ /dev/null
@@ -1,586 +0,0 @@
-/* Copyright 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <time.h>
-
-using testing::MatchesRegex;
-using testing::internal::CaptureStdout;
-using testing::internal::GetCapturedStdout;
-
-extern "C" {
-#include "cras_hfp_info.c"
-#include "sbc_codec_stub.h"
-}
-static struct hfp_info* info;
-static struct cras_iodev dev;
-static cras_audio_format format;
-
-static int cras_msbc_plc_create_called;
-static int cras_msbc_plc_handle_good_frames_called;
-static int cras_msbc_plc_handle_bad_frames_called;
-
-static thread_callback thread_cb;
-static void* cb_data;
-static timespec ts;
-
-void ResetStubData() {
- sbc_codec_stub_reset();
- cras_msbc_plc_create_called = 0;
-
- format.format = SND_PCM_FORMAT_S16_LE;
- format.num_channels = 1;
- format.frame_rate = 8000;
- dev.format = &format;
-}
-
-namespace {
-
-TEST(HfpInfo, AddRmDev) {
- ResetStubData();
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
- dev.direction = CRAS_STREAM_OUTPUT;
-
- /* Test add dev */
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
- ASSERT_TRUE(hfp_info_has_iodev(info));
-
- /* Test remove dev */
- ASSERT_EQ(0, hfp_info_rm_iodev(info, dev.direction));
- ASSERT_FALSE(hfp_info_has_iodev(info));
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, AddRmDevInvalid) {
- ResetStubData();
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- dev.direction = CRAS_STREAM_OUTPUT;
-
- /* Remove an iodev which doesn't exist */
- ASSERT_NE(0, hfp_info_rm_iodev(info, dev.direction));
-
- /* Adding an iodev twice returns error code */
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
- ASSERT_NE(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, AcquirePlaybackBuffer) {
- unsigned buffer_frames, buffer_frames2, queued;
- uint8_t* samples;
-
- ResetStubData();
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- hfp_info_start(1, 48, HFP_CODEC_ID_CVSD, info);
- dev.direction = CRAS_STREAM_OUTPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- buffer_frames = 500;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames);
- ASSERT_EQ(500, buffer_frames);
-
- hfp_buf_release(info, dev.direction, 500);
- ASSERT_EQ(500, hfp_buf_queued(info, dev.direction));
-
- /* Assert the amount of frames of available buffer + queued buf is
- * greater than or equal to the buffer size, 2 bytes per frame
- */
- queued = hfp_buf_queued(info, dev.direction);
- buffer_frames = 500;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames);
- ASSERT_GE(info->playback_buf->used_size / 2, buffer_frames + queued);
-
- /* Consume all queued data from read buffer */
- buf_increment_read(info->playback_buf, queued * 2);
-
- queued = hfp_buf_queued(info, dev.direction);
- ASSERT_EQ(0, queued);
-
- /* Assert consecutive acquire buffer will acquire full used size of buffer */
- buffer_frames = 500;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames);
- hfp_buf_release(info, dev.direction, buffer_frames);
-
- buffer_frames2 = 500;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames2);
- hfp_buf_release(info, dev.direction, buffer_frames2);
-
- ASSERT_GE(info->playback_buf->used_size / 2, buffer_frames + buffer_frames2);
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, AcquireCaptureBuffer) {
- unsigned buffer_frames, buffer_frames2;
- uint8_t* samples;
-
- ResetStubData();
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- hfp_info_start(1, 48, HFP_CODEC_ID_CVSD, info);
- dev.direction = CRAS_STREAM_INPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Put fake data 100 bytes(50 frames) in capture buf for test */
- buf_increment_write(info->capture_buf, 100);
-
- /* Assert successfully acquire and release 100 bytes of data */
- buffer_frames = 50;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames);
- ASSERT_EQ(50, buffer_frames);
-
- hfp_buf_release(info, dev.direction, buffer_frames);
- ASSERT_EQ(0, hfp_buf_queued(info, dev.direction));
-
- /* Push fake data to capture buffer */
- buf_increment_write(info->capture_buf, info->capture_buf->used_size - 100);
- buf_increment_write(info->capture_buf, 100);
-
- /* Assert consecutive acquire call will consume the whole buffer */
- buffer_frames = 1000;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames);
- hfp_buf_release(info, dev.direction, buffer_frames);
- ASSERT_GE(1000, buffer_frames);
-
- buffer_frames2 = 1000;
- hfp_buf_acquire(info, dev.direction, &samples, &buffer_frames2);
- hfp_buf_release(info, dev.direction, buffer_frames2);
-
- ASSERT_GE(info->capture_buf->used_size / 2, buffer_frames + buffer_frames2);
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, HfpReadWriteFD) {
- int rc;
- int sock[2];
- uint8_t sample[480];
- uint8_t* buf;
- unsigned buffer_count;
-
- ResetStubData();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- dev.direction = CRAS_STREAM_INPUT;
- hfp_info_start(sock[1], 48, HFP_CODEC_ID_CVSD, info);
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Mock the sco fd and send some fake data */
- send(sock[0], sample, 48, 0);
-
- rc = hfp_read(info);
- ASSERT_EQ(48, rc);
-
- rc = hfp_buf_queued(info, dev.direction);
- ASSERT_EQ(48 / 2, rc);
-
- /* Fill the write buffer*/
- buffer_count = info->capture_buf->used_size;
- buf = buf_write_pointer_size(info->capture_buf, &buffer_count);
- buf_increment_write(info->capture_buf, buffer_count);
- ASSERT_NE((void*)NULL, buf);
-
- rc = hfp_read(info);
- ASSERT_EQ(0, rc);
-
- ASSERT_EQ(0, hfp_info_rm_iodev(info, dev.direction));
- dev.direction = CRAS_STREAM_OUTPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Initial buffer is empty */
- rc = hfp_write(info);
- ASSERT_EQ(0, rc);
-
- buffer_count = 1024;
- buf = buf_write_pointer_size(info->playback_buf, &buffer_count);
- buf_increment_write(info->playback_buf, buffer_count);
-
- rc = hfp_write(info);
- ASSERT_EQ(48, rc);
-
- rc = recv(sock[0], sample, 48, 0);
- ASSERT_EQ(48, rc);
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, StartHfpInfo) {
- int sock[2];
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- hfp_info_start(sock[0], 48, HFP_CODEC_ID_CVSD, info);
- ASSERT_EQ(1, hfp_info_running(info));
- ASSERT_EQ(cb_data, (void*)info);
-
- hfp_info_stop(info);
- ASSERT_EQ(0, hfp_info_running(info));
- ASSERT_EQ(NULL, cb_data);
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, StartHfpInfoAndRead) {
- int rc;
- int sock[2];
- uint8_t sample[480];
-
- ResetStubData();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- /* Start and send two chunk of fake data */
- hfp_info_start(sock[1], 48, HFP_CODEC_ID_CVSD, info);
- send(sock[0], sample, 48, 0);
- send(sock[0], sample, 48, 0);
-
- /* Trigger thread callback */
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- dev.direction = CRAS_STREAM_INPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Expect no data read, since no idev present at previous thread callback */
- rc = hfp_buf_queued(info, dev.direction);
- ASSERT_EQ(0, rc);
-
- /* Trigger thread callback after idev added. */
- ts.tv_sec = 0;
- ts.tv_nsec = 5000000;
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- rc = hfp_buf_queued(info, dev.direction);
- ASSERT_EQ(48 / 2, rc);
-
- /* Assert wait time is unchanged. */
- ASSERT_EQ(0, ts.tv_sec);
- ASSERT_EQ(5000000, ts.tv_nsec);
-
- hfp_info_stop(info);
- ASSERT_EQ(0, hfp_info_running(info));
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, StartHfpInfoAndWrite) {
- int rc;
- int sock[2];
- uint8_t sample[480];
-
- ResetStubData();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- hfp_info_start(sock[1], 48, HFP_CODEC_ID_CVSD, info);
- send(sock[0], sample, 48, 0);
- send(sock[0], sample, 48, 0);
-
- /* Trigger thread callback */
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- /* Without odev in presence, zero packet should be sent. */
- rc = recv(sock[0], sample, 48, 0);
- ASSERT_EQ(48, rc);
-
- dev.direction = CRAS_STREAM_OUTPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Assert queued samples unchanged before output device added */
- ASSERT_EQ(0, hfp_buf_queued(info, dev.direction));
-
- /* Put some fake data and trigger thread callback again */
- buf_increment_write(info->playback_buf, 1008);
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- /* Assert some samples written */
- rc = recv(sock[0], sample, 48, 0);
- ASSERT_EQ(48, rc);
- ASSERT_EQ(480, hfp_buf_queued(info, dev.direction));
-
- hfp_info_stop(info);
- hfp_info_destroy(info);
-}
-
-void send_mSBC_packet(int fd, unsigned seq, int broken_pkt) {
- /* The first three bytes of hci_sco_buf are h2 header, frame count and mSBC
- * sync word. The second octet of H2 header is composed by 4 bits fixed 0x8
- * and 4 bits sequence number 0000, 0011, 1100, 1111.
- */
- uint8_t headers[4] = {0x08, 0x38, 0xc8, 0xf8};
- uint8_t hci_sco_buf[] = {
- 0x01, 0x00, 0xAD, 0xad, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x77,
- 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6, 0xdb,
- 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd, 0xb6,
- 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6d, 0xdd,
- 0xb6, 0xdb, 0x77, 0x6d, 0xb6, 0xdd, 0xdb, 0x6d, 0xb7, 0x76, 0xdb, 0x6c};
- struct msghdr msg = {0};
- struct iovec iov;
- struct cmsghdr* cmsg;
- const unsigned int control_size = CMSG_SPACE(sizeof(int));
- char control[control_size] = {0};
- uint8_t pkt_status = 0;
-
- hci_sco_buf[1] = headers[seq % 4];
-
- /* Assume typical 60 bytes case. */
- msg.msg_iov = &iov;
- msg.msg_iovlen = 1;
- iov.iov_base = hci_sco_buf;
- iov.iov_len = 60;
- msg.msg_control = control;
- msg.msg_controllen = control_size;
-
- if (broken_pkt)
- pkt_status = 0x11;
-
- cmsg = CMSG_FIRSTHDR(&msg);
- cmsg->cmsg_level = SOL_BLUETOOTH;
- cmsg->cmsg_type = BT_SCM_PKT_STATUS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(pkt_status));
- memcpy(CMSG_DATA(cmsg), &pkt_status, sizeof(pkt_status));
-
- sendmsg(fd, &msg, 0);
-}
-
-TEST(HfpInfo, StartHfpInfoAndReadMsbc) {
- int sock[2];
- int pkt_count = 0;
- int rc;
- uint8_t sample[480];
- ResetStubData();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- set_sbc_codec_decoded_out(MSBC_CODE_SIZE);
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
- ASSERT_EQ(0, get_msbc_codec_create_called());
- ASSERT_EQ(0, cras_msbc_plc_create_called);
-
- /* Start and send an mSBC packets with all zero samples */
- hfp_info_start(sock[1], 63, HFP_CODEC_ID_MSBC, info);
- ASSERT_EQ(2, get_msbc_codec_create_called());
- ASSERT_EQ(1, cras_msbc_plc_create_called);
- send_mSBC_packet(sock[0], pkt_count++, 0);
-
- /* Trigger thread callback */
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- /* Expect one empty mSBC packet is send, because no odev in presence. */
- rc = recv(sock[0], sample, MSBC_PKT_SIZE, 0);
- ASSERT_EQ(MSBC_PKT_SIZE, rc);
-
- dev.direction = CRAS_STREAM_INPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Expect no data read, since no idev present at previous thread callback */
- ASSERT_EQ(0, hfp_buf_queued(info, dev.direction));
-
- send_mSBC_packet(sock[0], pkt_count, 0);
-
- /* Trigger thread callback after idev added. */
- thread_cb((struct hfp_info*)cb_data, POLLIN);
- rc = recv(sock[0], sample, MSBC_PKT_SIZE, 0);
- ASSERT_EQ(MSBC_PKT_SIZE, rc);
-
- ASSERT_EQ(pkt_count * MSBC_CODE_SIZE / 2,
- hfp_buf_queued(info, dev.direction));
- ASSERT_EQ(2, cras_msbc_plc_handle_good_frames_called);
- pkt_count++;
- /* When the third packet is lost, we should call the handle_bad_packet and
- * still have right size of samples queued
- */
- pkt_count++;
- send_mSBC_packet(sock[0], pkt_count, 0);
- thread_cb((struct hfp_info*)cb_data, POLLIN);
- rc = recv(sock[0], sample, MSBC_PKT_SIZE, 0);
- ASSERT_EQ(MSBC_PKT_SIZE, rc);
-
- /* Packet 1, 2, 4 are all good frames */
- ASSERT_EQ(3, cras_msbc_plc_handle_good_frames_called);
- ASSERT_EQ(1, cras_msbc_plc_handle_bad_frames_called);
- ASSERT_EQ(pkt_count * MSBC_CODE_SIZE / 2,
- hfp_buf_queued(info, dev.direction));
- pkt_count++;
- /* If the erroneous data reporting marks the packet as broken, we should
- * also call the handle_bad_packet and have the right size of samples queued.
- */
- send_mSBC_packet(sock[0], pkt_count, 1);
-
- set_sbc_codec_decoded_fail(1);
-
- thread_cb((struct hfp_info*)cb_data, POLLIN);
- rc = recv(sock[0], sample, MSBC_PKT_SIZE, 0);
- ASSERT_EQ(MSBC_PKT_SIZE, rc);
-
- ASSERT_EQ(3, cras_msbc_plc_handle_good_frames_called);
- ASSERT_EQ(2, cras_msbc_plc_handle_bad_frames_called);
- ASSERT_EQ(pkt_count * MSBC_CODE_SIZE / 2,
- hfp_buf_queued(info, dev.direction));
- pkt_count++;
- /* If we can't decode the packet, we should also call the handle_bad_packet
- * and have the right size of samples queued
- */
- send_mSBC_packet(sock[0], pkt_count, 0);
-
- set_sbc_codec_decoded_fail(1);
-
- thread_cb((struct hfp_info*)cb_data, POLLIN);
- rc = recv(sock[0], sample, MSBC_PKT_SIZE, 0);
- ASSERT_EQ(MSBC_PKT_SIZE, rc);
-
- ASSERT_EQ(3, cras_msbc_plc_handle_good_frames_called);
- ASSERT_EQ(3, cras_msbc_plc_handle_bad_frames_called);
- ASSERT_EQ(pkt_count * MSBC_CODE_SIZE / 2,
- hfp_buf_queued(info, dev.direction));
-
- hfp_info_stop(info);
- ASSERT_EQ(0, hfp_info_running(info));
-
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, StartHfpInfoAndWriteMsbc) {
- int rc;
- int sock[2];
- uint8_t sample[480];
-
- ResetStubData();
-
- set_sbc_codec_encoded_out(57);
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- info = hfp_info_create();
- ASSERT_NE(info, (void*)NULL);
-
- hfp_info_start(sock[1], 63, HFP_CODEC_ID_MSBC, info);
- send(sock[0], sample, 63, 0);
-
- /* Trigger thread callback */
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- dev.direction = CRAS_STREAM_OUTPUT;
- ASSERT_EQ(0, hfp_info_add_iodev(info, dev.direction, dev.format));
-
- /* Assert queued samples unchanged before output device added */
- ASSERT_EQ(0, hfp_buf_queued(info, dev.direction));
-
- /* Put some fake data and trigger thread callback again */
- send(sock[0], sample, 63, 0);
- buf_increment_write(info->playback_buf, 240);
- thread_cb((struct hfp_info*)cb_data, POLLIN);
-
- /* Assert some samples written */
- rc = recv(sock[0], sample, 60, 0);
- ASSERT_EQ(60, rc);
- ASSERT_EQ(0, hfp_buf_queued(info, dev.direction));
-
- hfp_info_stop(info);
- hfp_info_destroy(info);
-}
-
-TEST(HfpInfo, WBSLoggerPacketStatusDumpBinary) {
- struct packet_status_logger logger;
- char log_regex[64];
- int num_wraps[5] = {0, 0, 0, 1, 1};
- int wp[5] = {40, 150, 162, 100, 32};
-
- /* Expect the log line wraps at correct length to avoid feedback redact. */
- snprintf(log_regex, 64, "([01D]{%d}\n)*", PACKET_STATUS_LOG_LINE_WRAP);
-
- packet_status_logger_init(&logger);
- logger.size = PACKET_STATUS_LEN_BYTES * 8;
- for (int i = 0; i < 5; i++) {
- CaptureStdout();
- logger.num_wraps = num_wraps[i];
- logger.wp = wp[i];
- packet_status_logger_dump_binary(&logger);
- EXPECT_THAT(GetCapturedStdout(), MatchesRegex(log_regex));
- }
-}
-
-} // namespace
-
-extern "C" {
-
-struct audio_thread* cras_iodev_list_get_audio_thread() {
- return NULL;
-}
-
-void audio_thread_add_events_callback(int fd,
- thread_callback cb,
- void* data,
- int events) {
- thread_cb = cb;
- cb_data = data;
- return;
-}
-
-int audio_thread_rm_callback_sync(struct audio_thread* thread, int fd) {
- thread_cb = NULL;
- cb_data = NULL;
- return 0;
-}
-
-void audio_thread_rm_callback(int fd) {}
-
-struct cras_msbc_plc* cras_msbc_plc_create() {
- cras_msbc_plc_create_called++;
- return NULL;
-}
-
-void cras_msbc_plc_destroy(struct cras_msbc_plc* plc) {}
-
-int cras_msbc_plc_handle_bad_frames(struct cras_msbc_plc* plc,
- struct cras_audio_codec* codec,
- uint8_t* output) {
- cras_msbc_plc_handle_bad_frames_called++;
- return MSBC_CODE_SIZE;
-}
-
-int cras_msbc_plc_handle_good_frames(struct cras_msbc_plc* plc,
- const uint8_t* input,
- uint8_t* output) {
- cras_msbc_plc_handle_good_frames_called++;
- return MSBC_CODE_SIZE;
-}
-void packet_status_logger_init(struct packet_status_logger* logger) {}
-
-void packet_status_logger_update(struct packet_status_logger* logger,
- bool val) {}
-}
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/hfp_iodev_unittest.cc b/cras/src/tests/hfp_iodev_unittest.cc
deleted file mode 100644
index 1275ef2c..00000000
--- a/cras/src/tests/hfp_iodev_unittest.cc
+++ /dev/null
@@ -1,409 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "cras_audio_area.h"
-#include "cras_hfp_info.h"
-#include "cras_hfp_iodev.h"
-#include "cras_hfp_slc.h"
-#include "cras_iodev.h"
-}
-
-static struct cras_iodev* iodev;
-static struct cras_bt_device* fake_device;
-static struct hfp_slc_handle* fake_slc;
-static struct hfp_info* fake_info;
-struct cras_audio_format fake_format;
-static size_t cras_bt_device_append_iodev_called;
-static size_t cras_bt_device_rm_iodev_called;
-static size_t cras_iodev_add_node_called;
-static size_t cras_iodev_rm_node_called;
-static size_t cras_iodev_set_active_node_called;
-static size_t cras_iodev_free_format_called;
-static size_t cras_iodev_free_resources_called;
-static size_t cras_bt_device_sco_connect_called;
-static int cras_bt_transport_sco_connect_return_val;
-static size_t hfp_info_add_iodev_called;
-static size_t hfp_info_rm_iodev_called;
-static size_t hfp_info_running_called;
-static int hfp_info_running_return_val;
-static size_t hfp_info_has_iodev_called;
-static int hfp_info_has_iodev_return_val;
-static size_t hfp_info_start_called;
-static size_t hfp_info_stop_called;
-static size_t hfp_buf_acquire_called;
-static unsigned hfp_buf_acquire_return_val;
-static size_t hfp_buf_release_called;
-static unsigned hfp_buf_release_nwritten_val;
-static size_t hfp_fill_output_with_zeros_called;
-static size_t hfp_force_output_level_called;
-static size_t hfp_force_output_level_target;
-static size_t fake_buffer_size = 500;
-static cras_audio_area* mock_audio_area;
-
-void ResetStubData() {
- cras_bt_device_append_iodev_called = 0;
- cras_bt_device_rm_iodev_called = 0;
- cras_iodev_add_node_called = 0;
- cras_iodev_rm_node_called = 0;
- cras_iodev_set_active_node_called = 0;
- cras_iodev_free_format_called = 0;
- cras_iodev_free_resources_called = 0;
- cras_bt_device_sco_connect_called = 0;
- cras_bt_transport_sco_connect_return_val = 0;
- hfp_info_add_iodev_called = 0;
- hfp_info_rm_iodev_called = 0;
- hfp_info_running_called = 0;
- hfp_info_running_return_val = 1;
- hfp_info_has_iodev_called = 0;
- hfp_info_has_iodev_return_val = 0;
- hfp_info_start_called = 0;
- hfp_info_stop_called = 0;
- hfp_buf_acquire_called = 0;
- hfp_buf_acquire_return_val = 0;
- hfp_buf_release_called = 0;
- hfp_buf_release_nwritten_val = 0;
- hfp_fill_output_with_zeros_called = 0;
- hfp_force_output_level_called = 0;
- hfp_force_output_level_target = 0;
-
- fake_info = reinterpret_cast<struct hfp_info*>(0x123);
-
- if (!mock_audio_area) {
- mock_audio_area = (cras_audio_area*)calloc(
- 1, sizeof(*mock_audio_area) + sizeof(cras_channel_area) * 2);
- }
-}
-
-namespace {
-
-class HfpIodev : public testing::Test {
- protected:
- virtual void SetUp() { ResetStubData(); }
-
- virtual void TearDown() {
- free(mock_audio_area);
- mock_audio_area = NULL;
- }
-};
-
-TEST_F(HfpIodev, CreateHfpOutputIodev) {
- iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY, fake_info);
-
- ASSERT_EQ(CRAS_STREAM_OUTPUT, iodev->direction);
- ASSERT_EQ(1, cras_bt_device_append_iodev_called);
- ASSERT_EQ(1, cras_iodev_add_node_called);
- ASSERT_EQ(1, cras_iodev_set_active_node_called);
-
- hfp_iodev_destroy(iodev);
-
- ASSERT_EQ(1, cras_bt_device_rm_iodev_called);
- ASSERT_EQ(1, cras_iodev_rm_node_called);
- ASSERT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpIodev, CreateHfpInputIodev) {
- iodev = hfp_iodev_create(CRAS_STREAM_INPUT, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY, fake_info);
-
- ASSERT_EQ(CRAS_STREAM_INPUT, iodev->direction);
- ASSERT_EQ(1, cras_bt_device_append_iodev_called);
- ASSERT_EQ(1, cras_iodev_add_node_called);
- ASSERT_EQ(1, cras_iodev_set_active_node_called);
- /* Input device does not use software gain. */
- ASSERT_EQ(0, iodev->software_volume_needed);
-
- hfp_iodev_destroy(iodev);
-
- ASSERT_EQ(1, cras_bt_device_rm_iodev_called);
- ASSERT_EQ(1, cras_iodev_rm_node_called);
- ASSERT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpIodev, OpenHfpIodev) {
- iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY, fake_info);
- iodev->format = &fake_format;
-
- /* hfp_info not start yet */
- hfp_info_running_return_val = 0;
- iodev->configure_dev(iodev);
-
- ASSERT_EQ(1, cras_bt_device_sco_connect_called);
- ASSERT_EQ(1, hfp_info_start_called);
- ASSERT_EQ(1, hfp_info_add_iodev_called);
-
- /* hfp_info is running now */
- hfp_info_running_return_val = 1;
-
- iodev->close_dev(iodev);
- hfp_iodev_destroy(iodev);
- ASSERT_EQ(1, hfp_info_rm_iodev_called);
- ASSERT_EQ(1, hfp_info_stop_called);
- ASSERT_EQ(1, cras_iodev_free_format_called);
- ASSERT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpIodev, OpenIodevWithHfpInfoAlreadyRunning) {
- iodev = hfp_iodev_create(CRAS_STREAM_INPUT, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY, fake_info);
-
- iodev->format = &fake_format;
-
- /* hfp_info already started by another device */
- hfp_info_running_return_val = 1;
- iodev->configure_dev(iodev);
-
- ASSERT_EQ(0, cras_bt_device_sco_connect_called);
- ASSERT_EQ(0, hfp_info_start_called);
- ASSERT_EQ(1, hfp_info_add_iodev_called);
-
- hfp_info_has_iodev_return_val = 1;
- iodev->close_dev(iodev);
- hfp_iodev_destroy(iodev);
- ASSERT_EQ(1, hfp_info_rm_iodev_called);
- ASSERT_EQ(0, hfp_info_stop_called);
- ASSERT_EQ(1, cras_iodev_free_format_called);
- ASSERT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpIodev, PutGetBuffer) {
- cras_audio_area* area;
- unsigned frames;
-
- ResetStubData();
- iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY, fake_info);
- iodev->format = &fake_format;
- iodev->configure_dev(iodev);
-
- hfp_buf_acquire_return_val = 100;
- iodev->get_buffer(iodev, &area, &frames);
-
- ASSERT_EQ(1, hfp_buf_acquire_called);
- ASSERT_EQ(100, frames);
-
- iodev->put_buffer(iodev, 40);
- ASSERT_EQ(1, hfp_buf_release_called);
- ASSERT_EQ(40, hfp_buf_release_nwritten_val);
- hfp_iodev_destroy(iodev);
- ASSERT_EQ(1, cras_iodev_free_resources_called);
-}
-
-TEST_F(HfpIodev, NoStreamState) {
- cras_audio_area* area;
- unsigned frames;
-
- ResetStubData();
- iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_device, fake_slc,
- CRAS_BT_DEVICE_PROFILE_HFP_AUDIOGATEWAY, fake_info);
- iodev->format = &fake_format;
- iodev->configure_dev(iodev);
- iodev->min_cb_level = iodev->buffer_size / 2;
-
- hfp_buf_acquire_return_val = 100;
- iodev->get_buffer(iodev, &area, &frames);
- iodev->put_buffer(iodev, 100);
-
- iodev->no_stream(iodev, 1);
- ASSERT_EQ(1, hfp_fill_output_with_zeros_called);
-
- iodev->no_stream(iodev, 0);
- ASSERT_EQ(1, hfp_force_output_level_called);
- ASSERT_EQ(fake_buffer_size / 2, hfp_force_output_level_target);
-
- hfp_iodev_destroy(iodev);
-}
-
-} // namespace
-
-extern "C" {
-void cras_iodev_free_format(struct cras_iodev* iodev) {
- cras_iodev_free_format_called++;
-}
-
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_add_node_called++;
- iodev->nodes = node;
-}
-
-void cras_iodev_rm_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- cras_iodev_rm_node_called++;
- iodev->nodes = NULL;
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {
- cras_iodev_set_active_node_called++;
- iodev->active_node = node;
-}
-
-// From ewma_power
-void ewma_power_disable(struct ewma_power* ewma) {}
-
-// From system_state.
-size_t cras_system_get_volume() {
- return 0;
-}
-
-// From bt device
-int cras_bt_device_sco_connect(struct cras_bt_device* device, int codec) {
- cras_bt_device_sco_connect_called++;
- return cras_bt_transport_sco_connect_return_val;
-}
-
-const char* cras_bt_device_name(const struct cras_bt_device* device) {
- return "fake-device-name";
-}
-
-const char* cras_bt_device_address(const struct cras_bt_device* device) {
- return "1A:2B:3C:4D:5E:6F";
-}
-
-void cras_bt_device_append_iodev(struct cras_bt_device* device,
- struct cras_iodev* iodev,
- enum cras_bt_device_profile profile) {
- cras_bt_device_append_iodev_called++;
-}
-
-void cras_bt_device_rm_iodev(struct cras_bt_device* device,
- struct cras_iodev* iodev) {
- cras_bt_device_rm_iodev_called++;
-}
-
-int cras_bt_device_sco_packet_size(struct cras_bt_device* device,
- int sco_socket,
- int codec) {
- return 48;
-}
-const char* cras_bt_device_object_path(const struct cras_bt_device* device) {
- return "/fake/object/path";
-}
-
-int cras_bt_device_get_stable_id(const struct cras_bt_device* device) {
- return 123;
-}
-
-// From cras_hfp_info
-int hfp_info_add_iodev(struct hfp_info* info,
- enum CRAS_STREAM_DIRECTION direction,
- struct cras_audio_format* format) {
- hfp_info_add_iodev_called++;
- return 0;
-}
-
-int hfp_info_rm_iodev(struct hfp_info* info,
- enum CRAS_STREAM_DIRECTION direction) {
- hfp_info_rm_iodev_called++;
- return 0;
-}
-
-int hfp_info_has_iodev(struct hfp_info* info) {
- hfp_info_has_iodev_called++;
- return hfp_info_has_iodev_return_val;
-}
-
-int hfp_info_running(struct hfp_info* info) {
- hfp_info_running_called++;
- return hfp_info_running_return_val;
-}
-
-int hfp_info_start(int fd, unsigned int mtu, int codec, struct hfp_info* info) {
- hfp_info_start_called++;
- return 0;
-}
-
-int hfp_info_stop(struct hfp_info* info) {
- hfp_info_stop_called++;
- return 0;
-}
-
-int hfp_buf_queued(struct hfp_info* info,
- const enum CRAS_STREAM_DIRECTION direction) {
- return 0;
-}
-
-int hfp_buf_size(struct hfp_info* info, enum CRAS_STREAM_DIRECTION direction) {
- return fake_buffer_size;
-}
-
-void hfp_buf_acquire(struct hfp_info* info,
- enum CRAS_STREAM_DIRECTION direction,
- uint8_t** buf,
- unsigned* count) {
- hfp_buf_acquire_called++;
- *count = hfp_buf_acquire_return_val;
-}
-
-void hfp_buf_release(struct hfp_info* info,
- enum CRAS_STREAM_DIRECTION direction,
- unsigned written_bytes) {
- hfp_buf_release_called++;
- hfp_buf_release_nwritten_val = written_bytes;
-}
-
-int hfp_fill_output_with_zeros(struct hfp_info* info, unsigned int nframes) {
- hfp_fill_output_with_zeros_called++;
- return 0;
-}
-
-void hfp_force_output_level(struct hfp_info* info, unsigned int level) {
- hfp_force_output_level_called++;
- hfp_force_output_level_target = level;
-}
-
-void cras_iodev_init_audio_area(struct cras_iodev* iodev, int num_channels) {
- iodev->area = mock_audio_area;
-}
-
-void cras_iodev_free_audio_area(struct cras_iodev* iodev) {}
-
-void cras_iodev_free_resources(struct cras_iodev* iodev) {
- cras_iodev_free_resources_called++;
-}
-
-int cras_iodev_fill_odev_zeros(struct cras_iodev* odev, unsigned int frames) {
- return 0;
-}
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {
- mock_audio_area->channels[0].buf = base_buffer;
-}
-
-int hfp_set_call_status(struct hfp_slc_handle* handle, int call) {
- return 0;
-}
-
-int hfp_event_speaker_gain(struct hfp_slc_handle* handle, int gain) {
- return 0;
-}
-
-int hfp_slc_get_selected_codec(struct hfp_slc_handle* handle) {
- return HFP_CODEC_ID_CVSD;
-}
-
-bool hfp_slc_get_wideband_speech_supported(struct hfp_slc_handle* handle) {
- return false;
-}
-
-int hfp_slc_codec_connection_setup(struct hfp_slc_handle* handle) {
- return 0;
-}
-
-int hfp_slc_is_hsp(struct hfp_slc_handle* handle) {
- return 0;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/hfp_slc_unittest.cc b/cras/src/tests/hfp_slc_unittest.cc
deleted file mode 100644
index 966278f4..00000000
--- a/cras/src/tests/hfp_slc_unittest.cc
+++ /dev/null
@@ -1,457 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <sys/socket.h>
-
-extern "C" {
-#include "cras_bt_log.h"
-#include "cras_hfp_slc.h"
-#include "cras_telephony.h"
-}
-
-static struct hfp_slc_handle* handle;
-static struct cras_telephony_handle fake_telephony;
-static int cras_bt_device_update_hardware_volume_called;
-static int cras_observer_notify_bt_batter_changed_called;
-static int slc_initialized_cb_called;
-static int slc_disconnected_cb_called;
-static int cras_system_add_select_fd_called;
-static void (*slc_cb)(void* data);
-static void* slc_cb_data;
-static int fake_errno;
-static struct cras_bt_device* device =
- reinterpret_cast<struct cras_bt_device*>(2);
-static void (*cras_tm_timer_cb)(struct cras_timer* t, void* data);
-static void* cras_tm_timer_cb_data;
-
-int slc_initialized_cb(struct hfp_slc_handle* handle);
-int slc_disconnected_cb(struct hfp_slc_handle* handle);
-
-void ResetStubData() {
- slc_initialized_cb_called = 0;
- cras_system_add_select_fd_called = 0;
- cras_bt_device_update_hardware_volume_called = 0;
- cras_observer_notify_bt_batter_changed_called = 0;
- slc_cb = NULL;
- slc_cb_data = NULL;
-}
-
-namespace {
-
-TEST(HfpSlc, CreateSlcHandle) {
- ResetStubData();
-
- handle = hfp_slc_create(0, 0, AG_ENHANCED_CALL_STATUS, device,
- slc_initialized_cb, slc_disconnected_cb);
- ASSERT_EQ(1, cras_system_add_select_fd_called);
- ASSERT_EQ(handle, slc_cb_data);
-
- hfp_slc_destroy(handle);
-}
-
-TEST(HfpSlc, InitializeSlc) {
- int err;
- int sock[2];
- char buf[256];
- char* chp;
- ResetStubData();
-
- btlog = cras_bt_event_log_init();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
- handle = hfp_slc_create(sock[0], 0, AG_ENHANCED_CALL_STATUS, device,
- slc_initialized_cb, slc_disconnected_cb);
-
- err = write(sock[1], "AT+CIND=?\r", 10);
- ASSERT_EQ(10, err);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Assert "\r\n+CIND: ... \r\n" response is received */
- chp = strstr(buf, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- ASSERT_EQ(0, strncmp("\r\n+CIND:", chp, 8));
- chp += 2;
- chp = strstr(chp, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- /* Assert "\r\nOK\r\n" response is received */
- chp += 2;
- chp = strstr(chp, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- ASSERT_EQ(0, strncmp("\r\nOK", chp, 4));
-
- err = write(sock[1], "AT+CMER=3,0,0,1\r", 16);
- ASSERT_EQ(16, err);
- slc_cb(slc_cb_data);
-
- ASSERT_EQ(1, slc_initialized_cb_called);
-
- /* Assert "\r\nOK\r\n" response is received */
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- ASSERT_EQ(0, strncmp("\r\nOK", chp, 4));
-
- err = write(sock[1], "AT+VGS=13\r", 10);
- ASSERT_EQ(err, 10);
- slc_cb(slc_cb_data);
-
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- ASSERT_EQ(0, strncmp("\r\nOK", chp, 4));
-
- ASSERT_EQ(1, cras_bt_device_update_hardware_volume_called);
-
- hfp_slc_destroy(handle);
- cras_bt_event_log_deinit(btlog);
-}
-
-TEST(HfpSlc, DisconnectSlc) {
- int sock[2];
- ResetStubData();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
- handle = hfp_slc_create(sock[0], 0, AG_ENHANCED_CALL_STATUS, device,
- slc_initialized_cb, slc_disconnected_cb);
- /* Close socket right away to make read() get negative err code, and
- * fake the errno to ECONNRESET. */
- close(sock[0]);
- close(sock[1]);
- fake_errno = 104;
- slc_cb(slc_cb_data);
-
- ASSERT_EQ(1, slc_disconnected_cb_called);
-
- hfp_slc_destroy(handle);
-}
-
-TEST(HfpSlc, InitializeSlcSupportsHfIndicator) {
- int err;
- int sock[2];
- char buf[256];
- char* chp;
- ResetStubData();
-
- btlog = cras_bt_event_log_init();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
- handle = hfp_slc_create(sock[0], 0, AG_ENHANCED_CALL_STATUS, device,
- slc_initialized_cb, slc_disconnected_cb);
-
- /* Fake that HF supports HF indicator. */
- err = write(sock[1], "AT+BRSF=256\r", 12);
- ASSERT_EQ(err, 12);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- err = write(sock[1], "AT+CIND=?\r", 10);
- ASSERT_EQ(10, err);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Assert "\r\n+CIND: ... \r\n" response is received */
- chp = strstr(buf, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- ASSERT_EQ(0, strncmp("\r\n+CIND:", chp, 8));
- chp += 2;
- chp = strstr(chp, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- /* Assert "\r\nOK\r\n" response is received */
- chp += 2;
- chp = strstr(chp, "\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- ASSERT_EQ(0, strncmp("\r\nOK", chp, 4));
-
- err = write(sock[1], "AT+CMER=3,0,0,1\r", 16);
- ASSERT_EQ(16, err);
- slc_cb(slc_cb_data);
-
- ASSERT_NE((void*)NULL, cras_tm_timer_cb);
- ASSERT_EQ(0, slc_initialized_cb_called);
-
- /* Assert "\r\nOK\r\n" response is received */
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\nOK\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- err = write(sock[1], "AT+BIND=2\r", 10);
- ASSERT_EQ(err, 10);
- slc_cb(slc_cb_data);
-
- /* Assert "\r\nOK\r\n" response is received */
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\nOK\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- err = write(sock[1], "AT+BIND=?\r", 10);
- ASSERT_EQ(err, 10);
- slc_cb(slc_cb_data);
-
- /* Assert "\r\n+BIND: (2)\r\n" response is received */
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\n+BIND: (1,2)\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- chp = strstr(buf, "\r\nOK\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- err = write(sock[1], "AT+BIND?\r", 9);
- ASSERT_EQ(err, 9);
- slc_cb(slc_cb_data);
-
- /* Assert "\r\n+BIND: 2,1\r\n" response is received */
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\n+BIND: 2,1\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
- chp = strstr(buf, "\r\nOK\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- ASSERT_EQ(1, slc_initialized_cb_called);
-
- err = write(sock[1], "AT+VGS=13\r", 10);
- ASSERT_EQ(err, 10);
- slc_cb(slc_cb_data);
-
- err = read(sock[1], buf, 256);
-
- chp = strstr(buf, "\r\nOK\r\n");
- ASSERT_NE((void*)NULL, (void*)chp);
-
- ASSERT_EQ(1, cras_bt_device_update_hardware_volume_called);
-
- hfp_slc_destroy(handle);
- cras_bt_event_log_deinit(btlog);
-}
-
-TEST(HfpSlc, CodecNegotiation) {
- int codec;
- int err;
- int sock[2];
- char buf[256];
- char* pos;
- ResetStubData();
-
- btlog = cras_bt_event_log_init();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
- handle = hfp_slc_create(sock[0], 0, AG_CODEC_NEGOTIATION, device,
- slc_initialized_cb, slc_disconnected_cb);
-
- codec = hfp_slc_get_selected_codec(handle);
- EXPECT_EQ(HFP_CODEC_ID_CVSD, codec);
-
- /* Fake that HF supports codec negotiation. */
- err = write(sock[1], "AT+BRSF=128\r", 12);
- ASSERT_EQ(err, 12);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Fake that HF supports mSBC codec. */
- err = write(sock[1], "AT+BAC=1,2\r", 11);
- ASSERT_EQ(err, 11);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Fake event reporting command to indicate SLC established. */
- err = write(sock[1], "AT+CMER=3,0,0,1\r", 16);
- ASSERT_EQ(err, 16);
- slc_cb(slc_cb_data);
-
- /* Assert that AG side prefers mSBC codec. */
- codec = hfp_slc_get_selected_codec(handle);
- EXPECT_EQ(HFP_CODEC_ID_MSBC, codec);
-
- /* Fake HF selects mSBC codec. */
- err = write(sock[1], "AT+BCS=2\r", 9);
- ASSERT_EQ(err, 9);
-
- err = hfp_slc_codec_connection_setup(handle);
- /* Assert CRAS initiates codec selection to mSBC. */
- memset(buf, 0, 256);
- err = read(sock[1], buf, 256);
- pos = strstr(buf, "\r\n+BCS:2\r\n");
- ASSERT_NE((void*)NULL, pos);
-
- err = write(sock[1], "AT+VGS=9\r", 9);
- ASSERT_EQ(err, 9);
- slc_cb(slc_cb_data);
-
- hfp_slc_destroy(handle);
- cras_bt_event_log_deinit(btlog);
-}
-
-TEST(HfpSlc, CodecNegotiationCapabilityChanged) {
- int codec;
- int err;
- int sock[2];
- char buf[256];
- char* pos;
- ResetStubData();
-
- btlog = cras_bt_event_log_init();
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
- handle = hfp_slc_create(sock[0], 0, AG_CODEC_NEGOTIATION, device,
- slc_initialized_cb, slc_disconnected_cb);
-
- codec = hfp_slc_get_selected_codec(handle);
- EXPECT_EQ(HFP_CODEC_ID_CVSD, codec);
-
- /* Fake that HF supports codec negotiation. */
- err = write(sock[1], "AT+BRSF=128\r", 12);
- ASSERT_EQ(err, 12);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Fake that HF supports mSBC codec. */
- err = write(sock[1], "AT+BAC=1,2\r", 11);
- ASSERT_EQ(err, 11);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Fake event reporting command to indicate SLC established. */
- err = write(sock[1], "AT+CMER=3,0,0,1\r", 16);
- ASSERT_EQ(err, 16);
- slc_cb(slc_cb_data);
-
- /* Assert that AG side prefers mSBC codec. */
- codec = hfp_slc_get_selected_codec(handle);
- EXPECT_EQ(HFP_CODEC_ID_MSBC, codec);
-
- /* Fake HF selects mSBC codec. */
- err = write(sock[1], "AT+BCS=2\r", 9);
- ASSERT_EQ(err, 9);
-
- err = hfp_slc_codec_connection_setup(handle);
- /* Assert CRAS initiates codec selection to mSBC. */
- memset(buf, 0, 256);
- err = read(sock[1], buf, 256);
- pos = strstr(buf, "\r\n+BCS:2\r\n");
- ASSERT_NE((void*)NULL, pos);
-
- /* Fake that HF changes supported codecs. */
- err = write(sock[1], "AT+BAC=1\r", 9);
- ASSERT_EQ(err, 9);
- slc_cb(slc_cb_data);
- err = read(sock[1], buf, 256);
-
- /* Fake HF selects CVSD codec. */
- err = write(sock[1], "AT+BCS=1\r", 9);
- ASSERT_EQ(err, 9);
-
- err = hfp_slc_codec_connection_setup(handle);
- /* Assert CRAS initiates codec selection to CVSD. */
- memset(buf, 0, 256);
- err = read(sock[1], buf, 256);
- pos = strstr(buf, "\r\n+BCS:1\r\n");
- ASSERT_NE((void*)NULL, pos);
-
- codec = hfp_slc_get_selected_codec(handle);
- EXPECT_EQ(HFP_CODEC_ID_CVSD, codec);
-
- hfp_slc_destroy(handle);
- cras_bt_event_log_deinit(btlog);
-}
-
-} // namespace
-
-int slc_initialized_cb(struct hfp_slc_handle* handle) {
- slc_initialized_cb_called++;
- return 0;
-}
-
-int slc_disconnected_cb(struct hfp_slc_handle* handle) {
- slc_disconnected_cb_called++;
- return 0;
-}
-
-extern "C" {
-
-struct cras_bt_event_log* btlog;
-
-int cras_system_add_select_fd(int fd,
- void (*callback)(void* data),
- void* callback_data) {
- cras_system_add_select_fd_called++;
- slc_cb = callback;
- slc_cb_data = callback_data;
- return 0;
-}
-
-void cras_system_rm_select_fd(int fd) {}
-
-const char* cras_bt_device_address(struct cras_bt_device* device) {
- return "";
-}
-
-void cras_bt_device_update_hardware_volume(struct cras_bt_device* device,
- int volume) {
- cras_bt_device_update_hardware_volume_called++;
-}
-
-void cras_observer_notify_bt_battery_changed(const char* address,
- uint32_t level) {
- cras_observer_notify_bt_batter_changed_called++;
-}
-
-/* To return fake errno */
-int* __errno_location() {
- return &fake_errno;
-}
-
-struct cras_tm* cras_system_state_get_tm() {
- return NULL;
-}
-
-struct cras_timer* cras_tm_create_timer(struct cras_tm* tm,
- unsigned int ms,
- void (*cb)(struct cras_timer* t,
- void* data),
- void* cb_data) {
- cras_tm_timer_cb = cb;
- cras_tm_timer_cb_data = cb_data;
- return reinterpret_cast<struct cras_timer*>(0x404);
-}
-
-int cras_poll(struct pollfd* fds,
- nfds_t nfds,
- struct timespec* timeout,
- const sigset_t* sigmask) {
- return 1;
-}
-
-void cras_tm_cancel_timer(struct cras_tm* tm, struct cras_timer* t) {}
-}
-
-// For telephony
-struct cras_telephony_handle* cras_telephony_get() {
- return &fake_telephony;
-}
-
-void cras_telephony_store_dial_number(int len, const char* num) {}
-
-int cras_telephony_event_answer_call() {
- return 0;
-}
-
-int cras_telephony_event_terminate_call() {
- return 0;
-}
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/input_data_unittest.cc b/cras/src/tests/input_data_unittest.cc
deleted file mode 100644
index 3c6ae9f1..00000000
--- a/cras/src/tests/input_data_unittest.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "buffer_share.c"
-#include "cras_audio_area.h"
-#include "cras_rstream.h"
-#include "input_data.h"
-}
-
-namespace {
-
-#define FAKE_CRAS_APM_PTR reinterpret_cast<struct cras_apm*>(0x99)
-
-#ifdef HAVE_WEBRTC_APM
-static struct cras_audio_area apm_area;
-static unsigned int cras_apm_list_process_offset_val;
-static unsigned int cras_apm_list_process_called;
-static struct cras_apm* cras_apm_list_get_active_ret = NULL;
-static bool cras_apm_list_get_use_tuned_settings_val;
-#endif // HAVE_WEBRTC_APM
-static float cras_rstream_get_volume_scaler_val;
-
-TEST(InputData, GetForInputStream) {
- void* dev_ptr = reinterpret_cast<void*>(0x123);
- struct input_data* data;
- struct cras_rstream stream;
- struct buffer_share* offsets;
- struct cras_audio_area* area;
- struct cras_audio_area dev_area;
- unsigned int offset;
-
-#ifdef HAVE_WEBRTC_APM
- cras_apm_list_process_called = 0;
-#endif // HAVE_WEBRTC_APM
- stream.stream_id = 111;
-
- data = input_data_create(dev_ptr);
- data->ext.configure(&data->ext, 8192, 2, 48000);
-
- // Prepare offsets data for 2 streams.
- offsets = buffer_share_create(8192);
- buffer_share_add_id(offsets, 111, NULL);
- buffer_share_add_id(offsets, 222, NULL);
- buffer_share_offset_update(offsets, 111, 2048);
-
- dev_area.frames = 600;
- data->area = &dev_area;
-
- stream.apm_list = NULL;
- input_data_get_for_stream(data, &stream, offsets, &area, &offset);
-
- // Assert offset is clipped by area->frames
- EXPECT_EQ(600, area->frames);
- EXPECT_EQ(600, offset);
-#ifdef HAVE_WEBRTC_APM
- EXPECT_EQ(0, cras_apm_list_process_called);
- cras_apm_list_get_active_ret = FAKE_CRAS_APM_PTR;
-#endif // HAVE_WEBRTC_APM
-
- input_data_get_for_stream(data, &stream, offsets, &area, &offset);
-
-#ifdef HAVE_WEBRTC_APM
- // Assert APM process uses correct stream offset not the clipped one
- // used for audio area.
- EXPECT_EQ(1, cras_apm_list_process_called);
- EXPECT_EQ(2048, cras_apm_list_process_offset_val);
- EXPECT_EQ(0, offset);
-#else
- // Without the APM, the offset shouldn't be changed.
- EXPECT_EQ(600, offset);
-#endif // HAVE_WEBRTC_APM
-
- input_data_destroy(&data);
- buffer_share_destroy(offsets);
-}
-
-TEST(InputData, GetSWCaptureGain) {
- void* dev_ptr = reinterpret_cast<void*>(0x123);
- struct input_data* data = NULL;
- struct cras_rstream stream;
- float gain;
-
- cras_rstream_get_volume_scaler_val = 0.8f;
- stream.stream_id = 123;
-
-#ifdef HAVE_WEBRTC_APM
- data = input_data_create(dev_ptr);
-
- cras_apm_list_get_active_ret = FAKE_CRAS_APM_PTR;
- cras_apm_list_get_use_tuned_settings_val = 1;
- gain = input_data_get_software_gain_scaler(data, 0.7f, &stream);
- EXPECT_FLOAT_EQ(1.0f, gain);
-
- cras_apm_list_get_active_ret = NULL;
- gain = input_data_get_software_gain_scaler(data, 0.7f, &stream);
- EXPECT_FLOAT_EQ(0.56f, gain);
-
- cras_apm_list_get_active_ret = FAKE_CRAS_APM_PTR;
- cras_apm_list_get_use_tuned_settings_val = 0;
- gain = input_data_get_software_gain_scaler(data, 0.6f, &stream);
- EXPECT_FLOAT_EQ(0.48f, gain);
- input_data_destroy(&data);
-#endif // HAVE_WEBRTC_APM
-
- data = input_data_create(dev_ptr);
- gain = input_data_get_software_gain_scaler(data, 0.6f, &stream);
- EXPECT_FLOAT_EQ(0.48f, gain);
- input_data_destroy(&data);
-}
-
-extern "C" {
-#ifdef HAVE_WEBRTC_APM
-struct cras_apm* cras_apm_list_get_active_apm(void* stream_ptr, void* dev_ptr) {
- return cras_apm_list_get_active_ret;
-}
-int cras_apm_list_process(struct cras_apm* apm,
- struct float_buffer* input,
- unsigned int offset) {
- cras_apm_list_process_called++;
- cras_apm_list_process_offset_val = offset;
- return 0;
-}
-
-struct cras_audio_area* cras_apm_list_get_processed(struct cras_apm* apm) {
- return &apm_area;
-}
-void cras_apm_list_remove_apm(struct cras_apm_list* list, void* dev_ptr) {}
-void cras_apm_list_put_processed(struct cras_apm* apm, unsigned int frames) {}
-bool cras_apm_list_get_use_tuned_settings(struct cras_apm* apm) {
- return cras_apm_list_get_use_tuned_settings_val;
-}
-#endif // HAVE_WEBRTC_APM
-
-float cras_rstream_get_volume_scaler(struct cras_rstream* rstream) {
- return cras_rstream_get_volume_scaler_val;
-}
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/iodev_list_unittest.cc b/cras/src/tests/iodev_list_unittest.cc
deleted file mode 100644
index 8c71214a..00000000
--- a/cras/src/tests/iodev_list_unittest.cc
+++ /dev/null
@@ -1,2362 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-#include <algorithm>
-#include <map>
-
-extern "C" {
-#include "audio_thread.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_main_thread_log.h"
-#include "cras_observer_ops.h"
-#include "cras_ramp.h"
-#include "cras_rstream.h"
-#include "cras_system_state.h"
-#include "cras_tm.h"
-#include "stream_list.h"
-#include "utlist.h"
-}
-
-namespace {
-
-struct cras_server_state server_state_stub;
-struct cras_server_state* server_state_update_begin_return;
-int system_get_mute_return;
-
-/* Data for stubs. */
-static struct cras_observer_ops* observer_ops;
-static int add_stream_called;
-static int rm_stream_called;
-static unsigned int set_node_plugged_called;
-static cras_iodev* audio_thread_remove_streams_active_dev;
-static cras_iodev* audio_thread_set_active_dev_val;
-static int audio_thread_set_active_dev_called;
-static cras_iodev* audio_thread_add_open_dev_dev;
-static int audio_thread_add_open_dev_called;
-static int audio_thread_rm_open_dev_called;
-static int audio_thread_is_dev_open_ret;
-static struct audio_thread thread;
-static struct cras_iodev loopback_input;
-static int cras_iodev_close_called;
-static struct cras_iodev* cras_iodev_close_dev;
-static struct cras_iodev mock_hotword_iodev;
-static struct cras_iodev mock_empty_iodev[2];
-static stream_callback* stream_add_cb;
-static stream_callback* stream_rm_cb;
-static struct cras_rstream* stream_list_get_ret;
-static int server_stream_create_called;
-static int server_stream_destroy_called;
-static int audio_thread_drain_stream_return;
-static int audio_thread_drain_stream_called;
-static int cras_tm_create_timer_called;
-static int cras_tm_cancel_timer_called;
-static void (*cras_tm_timer_cb)(struct cras_timer* t, void* data);
-static void* cras_tm_timer_cb_data;
-static struct timespec clock_gettime_retspec;
-static struct cras_iodev* device_enabled_dev;
-static int device_enabled_count;
-static struct cras_iodev* device_disabled_dev;
-static int device_disabled_count;
-static void* device_enabled_cb_data;
-static void* device_disabled_cb_data;
-static struct cras_rstream* audio_thread_add_stream_stream;
-static struct cras_iodev* audio_thread_add_stream_dev;
-static struct cras_iodev* audio_thread_disconnect_stream_dev;
-static int audio_thread_add_stream_called;
-static unsigned update_active_node_called;
-static struct cras_iodev* update_active_node_iodev_val[5];
-static unsigned update_active_node_node_idx_val[5];
-static unsigned update_active_node_dev_enabled_val[5];
-static int set_swap_mode_for_node_called;
-static int set_swap_mode_for_node_enable;
-static int cras_iodev_start_volume_ramp_called;
-static size_t cras_observer_add_called;
-static size_t cras_observer_remove_called;
-static size_t cras_observer_notify_nodes_called;
-static size_t cras_observer_notify_active_node_called;
-static size_t cras_observer_notify_output_node_volume_called;
-static size_t cras_observer_notify_node_left_right_swapped_called;
-static size_t cras_observer_notify_input_node_gain_called;
-static int cras_iodev_open_called;
-static int cras_iodev_open_ret[8];
-static struct cras_audio_format cras_iodev_open_fmt;
-static int set_mute_called;
-static std::vector<struct cras_iodev*> set_mute_dev_vector;
-static std::vector<unsigned int> audio_thread_dev_start_ramp_dev_vector;
-static int audio_thread_dev_start_ramp_called;
-static enum CRAS_IODEV_RAMP_REQUEST audio_thread_dev_start_ramp_req;
-static std::map<int, bool> stream_list_has_pinned_stream_ret;
-static struct cras_rstream* audio_thread_disconnect_stream_stream;
-static int audio_thread_disconnect_stream_called;
-static struct cras_iodev fake_sco_in_dev, fake_sco_out_dev;
-static struct cras_ionode fake_sco_in_node, fake_sco_out_node;
-static int server_state_hotword_pause_at_suspend;
-
-int dev_idx_in_vector(std::vector<unsigned int> v, unsigned int idx) {
- return std::find(v.begin(), v.end(), idx) != v.end();
-}
-
-int device_in_vector(std::vector<struct cras_iodev*> v,
- struct cras_iodev* dev) {
- return std::find(v.begin(), v.end(), dev) != v.end();
-}
-
-class IoDevTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- cras_iodev_list_reset();
-
- cras_iodev_close_called = 0;
- stream_list_get_ret = 0;
- server_stream_create_called = 0;
- server_stream_destroy_called = 0;
- audio_thread_drain_stream_return = 0;
- audio_thread_drain_stream_called = 0;
- cras_tm_create_timer_called = 0;
- cras_tm_cancel_timer_called = 0;
-
- audio_thread_disconnect_stream_called = 0;
- audio_thread_disconnect_stream_stream = NULL;
- audio_thread_is_dev_open_ret = 0;
- stream_list_has_pinned_stream_ret.clear();
-
- sample_rates_[0] = 44100;
- sample_rates_[1] = 48000;
- sample_rates_[2] = 0;
-
- channel_counts_[0] = 2;
- channel_counts_[1] = 0;
-
- fmt_.format = SND_PCM_FORMAT_S16_LE;
- fmt_.frame_rate = 48000;
- fmt_.num_channels = 2;
-
- memset(&d1_, 0, sizeof(d1_));
- memset(&d2_, 0, sizeof(d2_));
- memset(&d3_, 0, sizeof(d3_));
-
- memset(&node1, 0, sizeof(node1));
- memset(&node2, 0, sizeof(node2));
- memset(&node3, 0, sizeof(node3));
-
- d1_.set_volume = NULL;
- d1_.set_capture_gain = NULL;
- d1_.set_capture_mute = NULL;
- d1_.update_supported_formats = NULL;
- d1_.update_active_node = update_active_node;
- d1_.set_swap_mode_for_node = set_swap_mode_for_node;
- d1_.format = NULL;
- d1_.direction = CRAS_STREAM_OUTPUT;
- d1_.info.idx = -999;
- d1_.nodes = &node1;
- d1_.active_node = &node1;
- strcpy(d1_.info.name, "d1");
- d1_.supported_rates = sample_rates_;
- d1_.supported_channel_counts = channel_counts_;
- d2_.set_volume = NULL;
- d2_.set_capture_gain = NULL;
- d2_.set_capture_mute = NULL;
- d2_.update_supported_formats = NULL;
- d2_.update_active_node = update_active_node;
- d2_.format = NULL;
- d2_.direction = CRAS_STREAM_OUTPUT;
- d2_.info.idx = -999;
- d2_.nodes = &node2;
- d2_.active_node = &node2;
- strcpy(d2_.info.name, "d2");
- d2_.supported_rates = sample_rates_;
- d2_.supported_channel_counts = channel_counts_;
- d3_.set_volume = NULL;
- d3_.set_capture_gain = NULL;
- d3_.set_capture_mute = NULL;
- d3_.update_supported_formats = NULL;
- d3_.update_active_node = update_active_node;
- d3_.format = NULL;
- d3_.direction = CRAS_STREAM_OUTPUT;
- d3_.info.idx = -999;
- d3_.nodes = &node3;
- d3_.active_node = &node3;
- strcpy(d3_.info.name, "d3");
- d3_.supported_rates = sample_rates_;
- d3_.supported_channel_counts = channel_counts_;
-
- loopback_input.set_volume = NULL;
- loopback_input.set_capture_gain = NULL;
- loopback_input.set_capture_mute = NULL;
- loopback_input.update_supported_formats = NULL;
- loopback_input.update_active_node = update_active_node;
- loopback_input.format = NULL;
- loopback_input.direction = CRAS_STREAM_INPUT;
- loopback_input.info.idx = -999;
- loopback_input.nodes = &node3;
- loopback_input.active_node = &node3;
- strcpy(loopback_input.info.name, "loopback_input");
- loopback_input.supported_rates = sample_rates_;
- loopback_input.supported_channel_counts = channel_counts_;
-
- server_state_update_begin_return = &server_state_stub;
- system_get_mute_return = false;
-
- /* Reset stub data. */
- add_stream_called = 0;
- rm_stream_called = 0;
- set_node_plugged_called = 0;
- audio_thread_rm_open_dev_called = 0;
- audio_thread_add_open_dev_called = 0;
- audio_thread_set_active_dev_called = 0;
- audio_thread_add_stream_called = 0;
- update_active_node_called = 0;
- cras_observer_add_called = 0;
- cras_observer_remove_called = 0;
- cras_observer_notify_nodes_called = 0;
- cras_observer_notify_active_node_called = 0;
- cras_observer_notify_output_node_volume_called = 0;
- cras_observer_notify_node_left_right_swapped_called = 0;
- cras_observer_notify_input_node_gain_called = 0;
- cras_iodev_open_called = 0;
- memset(cras_iodev_open_ret, 0, sizeof(cras_iodev_open_ret));
- set_mute_called = 0;
- set_mute_dev_vector.clear();
- set_swap_mode_for_node_called = 0;
- set_swap_mode_for_node_enable = 0;
- cras_iodev_start_volume_ramp_called = 0;
- audio_thread_dev_start_ramp_dev_vector.clear();
- audio_thread_dev_start_ramp_called = 0;
- audio_thread_dev_start_ramp_req = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- for (int i = 0; i < 5; i++)
- update_active_node_iodev_val[i] = NULL;
- DL_APPEND(fake_sco_in_dev.nodes, &fake_sco_in_node);
- DL_APPEND(fake_sco_out_dev.nodes, &fake_sco_out_node);
- fake_sco_in_node.is_sco_pcm = 0;
- fake_sco_out_node.is_sco_pcm = 0;
- mock_empty_iodev[0].state = CRAS_IODEV_STATE_CLOSE;
- mock_empty_iodev[0].update_active_node = update_active_node;
- mock_empty_iodev[1].state = CRAS_IODEV_STATE_CLOSE;
- mock_empty_iodev[1].update_active_node = update_active_node;
- mock_hotword_iodev.update_active_node = update_active_node;
- server_state_hotword_pause_at_suspend = 0;
- }
-
- virtual void TearDown() {
- cras_iodev_list_reset();
- }
-
- static void set_volume_1(struct cras_iodev* iodev) { set_volume_1_called_++; }
-
- static void set_capture_gain_1(struct cras_iodev* iodev) {
- set_capture_gain_1_called_++;
- }
-
- static void set_capture_mute_1(struct cras_iodev* iodev) {
- set_capture_mute_1_called_++;
- }
-
- static void update_active_node(struct cras_iodev* iodev,
- unsigned node_idx,
- unsigned dev_enabled) {
- int i = update_active_node_called++ % 5;
- update_active_node_iodev_val[i] = iodev;
- update_active_node_node_idx_val[i] = node_idx;
- update_active_node_dev_enabled_val[i] = dev_enabled;
- }
-
- static int set_swap_mode_for_node(struct cras_iodev* iodev,
- struct cras_ionode* node,
- int enable) {
- set_swap_mode_for_node_called++;
- set_swap_mode_for_node_enable = enable;
- return 0;
- }
-
- struct cras_iodev d1_;
- struct cras_iodev d2_;
- struct cras_iodev d3_;
- struct cras_audio_format fmt_;
- size_t sample_rates_[3];
- size_t channel_counts_[2];
- static int set_volume_1_called_;
- static int set_capture_gain_1_called_;
- static int set_capture_mute_1_called_;
- struct cras_ionode node1, node2, node3;
-};
-
-int IoDevTestSuite::set_volume_1_called_;
-int IoDevTestSuite::set_capture_gain_1_called_;
-int IoDevTestSuite::set_capture_mute_1_called_;
-
-// Check that Init registers observer client. */
-TEST_F(IoDevTestSuite, InitSetup) {
- cras_iodev_list_init();
- EXPECT_EQ(1, cras_observer_add_called);
- cras_iodev_list_deinit();
- EXPECT_EQ(1, cras_observer_remove_called);
-}
-
-/* Check that the suspend alert from cras_system will trigger suspend
- * and resume call of all iodevs. */
-TEST_F(IoDevTestSuite, SetSuspendResume) {
- struct cras_rstream rstream, rstream2, rstream3;
- struct cras_rstream* stream_list = NULL;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
- memset(&rstream2, 0, sizeof(rstream2));
- memset(&rstream3, 0, sizeof(rstream3));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- DL_APPEND(stream_list, &rstream);
- stream_add_cb(&rstream);
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- DL_APPEND(stream_list, &rstream2);
- stream_add_cb(&rstream2);
- EXPECT_EQ(2, audio_thread_add_stream_called);
-
- audio_thread_rm_open_dev_called = 0;
- observer_ops->suspend_changed(NULL, 1);
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
-
- /* Test disable/enable dev won't cause add_stream to audio_thread. */
- audio_thread_add_stream_called = 0;
- cras_iodev_list_disable_dev(&d1_, false);
- cras_iodev_list_enable_dev(&d1_);
- EXPECT_EQ(0, audio_thread_add_stream_called);
-
- audio_thread_drain_stream_return = 0;
- DL_DELETE(stream_list, &rstream2);
- stream_rm_cb(&rstream2);
- EXPECT_EQ(1, audio_thread_drain_stream_called);
-
- /* Test stream_add_cb won't cause add_stream to audio_thread. */
- audio_thread_add_stream_called = 0;
- DL_APPEND(stream_list, &rstream3);
- stream_add_cb(&rstream3);
- EXPECT_EQ(0, audio_thread_add_stream_called);
-
- audio_thread_add_open_dev_called = 0;
- audio_thread_add_stream_called = 0;
- stream_list_get_ret = stream_list;
- observer_ops->suspend_changed(NULL, 0);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream3, audio_thread_add_stream_stream);
-
- cras_iodev_list_deinit();
- EXPECT_EQ(3, cras_observer_notify_active_node_called);
-}
-
-/* Check that the suspend/resume call of active iodev will be triggered and
- * fallback device will be transciently enabled while adding a new stream whose
- * channel count is higher than the active iodev. */
-TEST_F(IoDevTestSuite, ReopenDevForHigherChannels) {
- struct cras_rstream rstream, rstream2;
- struct cras_rstream* stream_list = NULL;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
- memset(&rstream2, 0, sizeof(rstream2));
- rstream.format = fmt_;
- rstream2.format = fmt_;
- rstream2.format.num_channels = 6;
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d1_.info.max_supported_channels = 2;
-
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream);
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
- EXPECT_EQ(1, cras_iodev_open_called);
- EXPECT_EQ(2, cras_iodev_open_fmt.num_channels);
-
- audio_thread_add_stream_called = 0;
- audio_thread_add_open_dev_called = 0;
- cras_iodev_open_called = 0;
-
- /* stream_list should be descending ordered by channel count. */
- DL_PREPEND(stream_list, &rstream2);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream2);
- /* The channel count(=6) of rstream2 exceeds d1's max_supported_channels(=2),
- * rstream2 will be added directly to d1, which will not be re-opened. */
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(0, audio_thread_add_open_dev_called);
- EXPECT_EQ(0, cras_iodev_open_called);
-
- d1_.info.max_supported_channels = 6;
- stream_rm_cb(&rstream2);
-
- audio_thread_add_stream_called = 0;
- audio_thread_add_open_dev_called = 0;
- cras_iodev_open_called = 0;
-
- stream_add_cb(&rstream2);
- /* Added both rstreams to fallback device, then re-opened d1. */
- EXPECT_EQ(4, audio_thread_add_stream_called);
- EXPECT_EQ(2, audio_thread_add_open_dev_called);
- EXPECT_EQ(2, cras_iodev_open_called);
- EXPECT_EQ(6, cras_iodev_open_fmt.num_channels);
-
- cras_iodev_list_deinit();
-}
-
-/* Check that after resume, all output devices enter ramp mute state if there is
- * any output stream. */
-TEST_F(IoDevTestSuite, RampMuteAfterResume) {
- struct cras_rstream rstream, rstream2;
- struct cras_rstream* stream_list = NULL;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- d1_.initial_ramp_request = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d2_.direction = CRAS_STREAM_INPUT;
- d2_.initial_ramp_request = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- rc = cras_iodev_list_add_input(&d2_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
-
- rstream.direction = CRAS_STREAM_OUTPUT;
- DL_APPEND(stream_list, &rstream);
- stream_add_cb(&rstream);
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- rstream2.direction = CRAS_STREAM_INPUT;
- DL_APPEND(stream_list, &rstream2);
- stream_add_cb(&rstream2);
-
- /* Suspend and resume */
- observer_ops->suspend_changed(NULL, 1);
- stream_list_get_ret = stream_list;
- observer_ops->suspend_changed(NULL, 0);
-
- /* Test only output device that has stream will be muted after resume */
- EXPECT_EQ(d1_.initial_ramp_request, CRAS_IODEV_RAMP_REQUEST_RESUME_MUTE);
- EXPECT_EQ(CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK,
- d2_.initial_ramp_request);
-
- /* Reset d1 ramp_mute and remove output stream to test again */
- d1_.initial_ramp_request = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- DL_DELETE(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_rm_cb(&rstream);
-
- /* Suspend and resume */
- observer_ops->suspend_changed(NULL, 1);
- stream_list_get_ret = stream_list;
- observer_ops->suspend_changed(NULL, 0);
-
- EXPECT_EQ(CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK,
- d1_.initial_ramp_request);
- EXPECT_EQ(CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK,
- d2_.initial_ramp_request);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, InitDevFailShouldEnableFallback) {
- int rc;
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
-
- memset(&rstream, 0, sizeof(rstream));
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 0));
-
- cras_iodev_open_ret[0] = -5;
- cras_iodev_open_ret[1] = 0;
-
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream);
- /* open dev called twice, one for fallback device. */
- EXPECT_EQ(2, cras_iodev_open_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, InitDevWithEchoRef) {
- int rc;
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
-
- memset(&rstream, 0, sizeof(rstream));
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- d1_.echo_reference_dev = &d2_;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d2_.direction = CRAS_STREAM_INPUT;
- snprintf(d2_.active_node->name, CRAS_NODE_NAME_BUFFER_SIZE, "echo ref");
- rc = cras_iodev_list_add_input(&d2_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 0));
- /* No close call happened, because no stream exists. */
- EXPECT_EQ(0, cras_iodev_close_called);
-
- cras_iodev_open_ret[1] = 0;
-
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream);
-
- EXPECT_EQ(1, cras_iodev_open_called);
- EXPECT_EQ(1, server_stream_create_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
-
- DL_DELETE(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_rm_cb(&rstream);
-
- clock_gettime_retspec.tv_sec = 11;
- clock_gettime_retspec.tv_nsec = 0;
- cras_tm_timer_cb(NULL, NULL);
-
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(1, server_stream_destroy_called);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SelectNodeOpenFailShouldScheduleRetry) {
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d2_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d2_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream);
-
- /* Select node triggers: fallback open, d1 close, d2 open, fallback close. */
- cras_iodev_close_called = 0;
- cras_iodev_open_called = 0;
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 1));
- EXPECT_EQ(2, cras_iodev_close_called);
- EXPECT_EQ(2, cras_iodev_open_called);
- EXPECT_EQ(0, cras_tm_create_timer_called);
- EXPECT_EQ(0, cras_tm_cancel_timer_called);
-
- /* Test that if select to d1 and open d1 fail, fallback doesn't close. */
- cras_iodev_open_called = 0;
- cras_iodev_open_ret[0] = 0;
- cras_iodev_open_ret[1] = -5;
- cras_iodev_open_ret[2] = 0;
- cras_tm_timer_cb = NULL;
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- EXPECT_EQ(3, cras_iodev_close_called);
- EXPECT_EQ(&d2_, cras_iodev_close_dev);
- EXPECT_EQ(2, cras_iodev_open_called);
- EXPECT_EQ(0, cras_tm_cancel_timer_called);
-
- /* Assert a timer is scheduled to retry open. */
- EXPECT_NE((void*)NULL, cras_tm_timer_cb);
- EXPECT_EQ(1, cras_tm_create_timer_called);
-
- audio_thread_add_stream_called = 0;
- cras_tm_timer_cb(NULL, cras_tm_timer_cb_data);
- EXPECT_EQ(3, cras_iodev_open_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
-
- /* Retry open success will close fallback dev. */
- EXPECT_EQ(4, cras_iodev_close_called);
- EXPECT_EQ(0, cras_tm_cancel_timer_called);
-
- /* Select to d2 and fake an open failure. */
- cras_iodev_close_called = 0;
- cras_iodev_open_called = 0;
- cras_iodev_open_ret[0] = 0;
- cras_iodev_open_ret[1] = -5;
- cras_iodev_open_ret[2] = 0;
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 1));
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(&d1_, cras_iodev_close_dev);
- EXPECT_EQ(2, cras_tm_create_timer_called);
- EXPECT_NE((void*)NULL, cras_tm_timer_cb);
-
- /* Select to another iodev should cancel the timer. */
- memset(cras_iodev_open_ret, 0, sizeof(cras_iodev_open_ret));
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 1));
- EXPECT_EQ(1, cras_tm_cancel_timer_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, InitDevFailShouldScheduleRetry) {
- int rc;
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
-
- memset(&rstream, 0, sizeof(rstream));
- rstream.format = fmt_;
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 0));
-
- update_active_node_called = 0;
- cras_iodev_open_ret[0] = -5;
- cras_iodev_open_ret[1] = 0;
- cras_tm_timer_cb = NULL;
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream);
- /* open dev called twice, one for fallback device. */
- EXPECT_EQ(2, cras_iodev_open_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(0, update_active_node_called);
- EXPECT_EQ(&mock_empty_iodev[CRAS_STREAM_OUTPUT], audio_thread_add_stream_dev);
-
- EXPECT_NE((void*)NULL, cras_tm_timer_cb);
- EXPECT_EQ(1, cras_tm_create_timer_called);
-
- /* If retry still fail, won't schedule more retry. */
- cras_iodev_open_ret[2] = -5;
- cras_tm_timer_cb(NULL, cras_tm_timer_cb_data);
- EXPECT_EQ(1, cras_tm_create_timer_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
-
- mock_empty_iodev[CRAS_STREAM_OUTPUT].format = &fmt_;
- cras_tm_timer_cb = NULL;
- cras_iodev_open_ret[3] = -5;
- stream_add_cb(&rstream);
- EXPECT_NE((void*)NULL, cras_tm_timer_cb);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- cras_iodev_list_rm_output(&d1_);
- EXPECT_EQ(1, cras_tm_cancel_timer_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, PinnedStreamInitFailShouldScheduleRetry) {
- int rc;
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
-
- memset(&rstream, 0, sizeof(rstream));
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- rstream.is_pinned = 1;
- rstream.pinned_dev_idx = d1_.info.idx;
-
- cras_iodev_open_ret[0] = -5;
- cras_iodev_open_ret[1] = 0;
- cras_tm_timer_cb = NULL;
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
- stream_add_cb(&rstream);
- /* Init pinned dev fail, not proceed to add stream. */
- EXPECT_EQ(1, cras_iodev_open_called);
- EXPECT_EQ(0, audio_thread_add_stream_called);
-
- EXPECT_NE((void*)NULL, cras_tm_timer_cb);
- EXPECT_EQ(1, cras_tm_create_timer_called);
-
- cras_tm_timer_cb(NULL, cras_tm_timer_cb_data);
- EXPECT_EQ(2, cras_iodev_open_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
-
- cras_iodev_list_rm_output(&d1_);
- cras_iodev_list_deinit();
-}
-
-static void device_enabled_cb(struct cras_iodev* dev, void* cb_data) {
- device_enabled_dev = dev;
- device_enabled_count++;
- device_enabled_cb_data = cb_data;
-}
-
-static void device_disabled_cb(struct cras_iodev* dev, void* cb_data) {
- device_disabled_dev = dev;
- device_disabled_count++;
- device_disabled_cb_data = cb_data;
-}
-
-TEST_F(IoDevTestSuite, SelectNode) {
- struct cras_rstream rstream, rstream2;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
- memset(&rstream2, 0, sizeof(rstream2));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- node1.idx = 1;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d2_.direction = CRAS_STREAM_OUTPUT;
- node2.idx = 2;
- rc = cras_iodev_list_add_output(&d2_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- audio_thread_rm_open_dev_called = 0;
-
- device_enabled_count = 0;
- device_disabled_count = 0;
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(
- device_enabled_cb, device_disabled_cb, (void*)0xABCD));
-
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
-
- EXPECT_EQ(1, device_enabled_count);
- EXPECT_EQ(1, cras_observer_notify_active_node_called);
- EXPECT_EQ(&d1_, cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT));
-
- // There should be a disable device call for the fallback device.
- // But no close call actually happened, because no stream exists.
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
- EXPECT_EQ(1, device_disabled_count);
- EXPECT_NE(&d1_, device_disabled_dev);
-
- DL_APPEND(stream_list_get_ret, &rstream);
- stream_add_cb(&rstream);
-
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- DL_APPEND(stream_list_get_ret, &rstream2);
- stream_add_cb(&rstream2);
-
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 2));
-
- // Additional enabled devices: fallback device, d2_.
- EXPECT_EQ(3, device_enabled_count);
- // Additional disabled devices: d1_, fallback device.
- EXPECT_EQ(3, device_disabled_count);
- EXPECT_EQ(2, audio_thread_rm_open_dev_called);
- EXPECT_EQ(2, cras_observer_notify_active_node_called);
- EXPECT_EQ(&d2_, cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT));
-
- // For each stream, the stream is added for fallback device and d2_.
- EXPECT_EQ(6, audio_thread_add_stream_called);
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(NULL, NULL, NULL));
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SelectPreviouslyEnabledNode) {
- struct cras_rstream rstream;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- node1.idx = 1;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d2_.direction = CRAS_STREAM_OUTPUT;
- node2.idx = 2;
- rc = cras_iodev_list_add_output(&d2_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- audio_thread_rm_open_dev_called = 0;
- device_enabled_count = 0;
- device_disabled_count = 0;
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(
- device_enabled_cb, device_disabled_cb, (void*)0xABCD));
-
- // Add an active node.
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
-
- EXPECT_EQ(1, device_enabled_count);
- EXPECT_EQ(1, cras_observer_notify_active_node_called);
- EXPECT_EQ(&d1_, cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT));
-
- // There should be a disable device call for the fallback device.
- EXPECT_EQ(1, device_disabled_count);
- EXPECT_NE(&d1_, device_disabled_dev);
- EXPECT_NE(&d2_, device_disabled_dev);
-
- DL_APPEND(stream_list_get_ret, &rstream);
- stream_add_cb(&rstream);
-
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
-
- // Add a second active node.
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 2));
-
- EXPECT_EQ(2, device_enabled_count);
- EXPECT_EQ(1, device_disabled_count);
- EXPECT_EQ(2, cras_observer_notify_active_node_called);
- EXPECT_EQ(&d1_, cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT));
-
- EXPECT_EQ(2, audio_thread_add_open_dev_called);
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // Select the second added active node - the initially added node should get
- // disabled.
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 2));
-
- EXPECT_EQ(2, device_enabled_count);
- EXPECT_EQ(2, device_disabled_count);
- EXPECT_EQ(3, cras_observer_notify_active_node_called);
-
- EXPECT_EQ(&d2_, cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT));
- EXPECT_EQ(&d1_, device_disabled_dev);
-
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(2, audio_thread_add_open_dev_called);
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(NULL, NULL, NULL));
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, UpdateActiveNode) {
- int rc;
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- d2_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d2_);
- ASSERT_EQ(0, rc);
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 1));
-
- EXPECT_EQ(2, update_active_node_called);
- EXPECT_EQ(&d2_, update_active_node_iodev_val[0]);
- EXPECT_EQ(1, update_active_node_node_idx_val[0]);
- EXPECT_EQ(1, update_active_node_dev_enabled_val[0]);
-
- /* Fake the active node idx on d2_, and later assert this node is
- * called for update_active_node when d2_ disabled. */
- d2_.active_node->idx = 2;
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 0));
-
- EXPECT_EQ(5, update_active_node_called);
- EXPECT_EQ(&d2_, update_active_node_iodev_val[2]);
- EXPECT_EQ(&d1_, update_active_node_iodev_val[3]);
- EXPECT_EQ(2, update_active_node_node_idx_val[2]);
- EXPECT_EQ(0, update_active_node_node_idx_val[3]);
- EXPECT_EQ(0, update_active_node_dev_enabled_val[2]);
- EXPECT_EQ(1, update_active_node_dev_enabled_val[3]);
- EXPECT_EQ(2, cras_observer_notify_active_node_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SelectNonExistingNode) {
- int rc;
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
-
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 0));
- EXPECT_EQ(1, d1_.is_enabled);
-
- /* Select non-existing node should disable all devices. */
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT, cras_make_node_id(2, 1));
- EXPECT_EQ(0, d1_.is_enabled);
- EXPECT_EQ(2, cras_observer_notify_active_node_called);
- cras_iodev_list_deinit();
-}
-
-// Devices with the wrong direction should be rejected.
-TEST_F(IoDevTestSuite, AddWrongDirection) {
- int rc;
-
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_EQ(-EINVAL, rc);
- d1_.direction = CRAS_STREAM_INPUT;
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_EQ(-EINVAL, rc);
-}
-
-// Test adding/removing an iodev to the list.
-TEST_F(IoDevTestSuite, AddRemoveOutput) {
- struct cras_iodev_info* dev_info;
- int rc;
- cras_iodev_list_init();
-
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_EQ(0, rc);
- // Test can't insert same iodev twice.
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_NE(0, rc);
- // Test insert a second output.
- rc = cras_iodev_list_add_output(&d2_);
- EXPECT_EQ(0, rc);
-
- // Test that it is removed.
- rc = cras_iodev_list_rm_output(&d1_);
- EXPECT_EQ(0, rc);
- // Test that we can't remove a dev twice.
- rc = cras_iodev_list_rm_output(&d1_);
- EXPECT_NE(0, rc);
- // Should be 1 dev now.
- rc = cras_iodev_list_get_outputs(&dev_info);
- EXPECT_EQ(1, rc);
- free(dev_info);
- // Passing null should return the number of outputs.
- rc = cras_iodev_list_get_outputs(NULL);
- EXPECT_EQ(1, rc);
- // Remove other dev.
- rc = cras_iodev_list_rm_output(&d2_);
- EXPECT_EQ(0, rc);
- // Should be 0 devs now.
- rc = cras_iodev_list_get_outputs(&dev_info);
- EXPECT_EQ(0, rc);
- free(dev_info);
- EXPECT_EQ(0, cras_observer_notify_active_node_called);
- cras_iodev_list_deinit();
-}
-
-// Test output_mute_changed callback.
-TEST_F(IoDevTestSuite, OutputMuteChangedToMute) {
- cras_iodev_list_init();
-
- cras_iodev_list_add_output(&d1_);
- cras_iodev_list_add_output(&d2_);
- cras_iodev_list_add_output(&d3_);
-
- // d1_ and d2_ are enabled.
- cras_iodev_list_enable_dev(&d1_);
- cras_iodev_list_enable_dev(&d2_);
-
- // Assume d1 and d2 devices are open.
- d1_.state = CRAS_IODEV_STATE_OPEN;
- d2_.state = CRAS_IODEV_STATE_OPEN;
- d3_.state = CRAS_IODEV_STATE_CLOSE;
-
- // Execute the callback.
- observer_ops->output_mute_changed(NULL, 0, 1, 0);
-
- // d1_ and d2_ should set mute state through audio_thread_dev_start_ramp
- // because they are both open.
- EXPECT_EQ(2, audio_thread_dev_start_ramp_called);
- ASSERT_TRUE(
- dev_idx_in_vector(audio_thread_dev_start_ramp_dev_vector, d2_.info.idx));
- ASSERT_TRUE(
- dev_idx_in_vector(audio_thread_dev_start_ramp_dev_vector, d1_.info.idx));
- EXPECT_EQ(CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE, audio_thread_dev_start_ramp_req);
-
- // d3_ should set mute state right away without calling ramp
- // because it is not open.
- EXPECT_EQ(1, set_mute_called);
- EXPECT_EQ(1, set_mute_dev_vector.size());
- ASSERT_TRUE(device_in_vector(set_mute_dev_vector, &d3_));
-
- cras_iodev_list_deinit();
-}
-
-// Test output_mute_changed callback.
-TEST_F(IoDevTestSuite, OutputMuteChangedToUnmute) {
- cras_iodev_list_init();
-
- cras_iodev_list_add_output(&d1_);
- cras_iodev_list_add_output(&d2_);
- cras_iodev_list_add_output(&d3_);
-
- // d1_ and d2_ are enabled.
- cras_iodev_list_enable_dev(&d1_);
- cras_iodev_list_enable_dev(&d2_);
-
- // Assume d1 and d2 devices are open.
- d1_.state = CRAS_IODEV_STATE_OPEN;
- d2_.state = CRAS_IODEV_STATE_CLOSE;
- d3_.state = CRAS_IODEV_STATE_CLOSE;
-
- // Execute the callback.
- observer_ops->output_mute_changed(NULL, 0, 0, 0);
-
- // d1_ should set mute state through audio_thread_dev_start_ramp.
- EXPECT_EQ(1, audio_thread_dev_start_ramp_called);
- ASSERT_TRUE(
- dev_idx_in_vector(audio_thread_dev_start_ramp_dev_vector, d1_.info.idx));
- EXPECT_EQ(CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE, audio_thread_dev_start_ramp_req);
-
- // d2_ and d3_ should set mute state right away because they both
- // are closed.
- EXPECT_EQ(2, set_mute_called);
- EXPECT_EQ(2, set_mute_dev_vector.size());
- ASSERT_TRUE(device_in_vector(set_mute_dev_vector, &d2_));
- ASSERT_TRUE(device_in_vector(set_mute_dev_vector, &d3_));
-
- cras_iodev_list_deinit();
-}
-
-// Test enable/disable an iodev.
-TEST_F(IoDevTestSuite, EnableDisableDevice) {
- struct cras_rstream rstream;
- cras_iodev_list_init();
- device_enabled_count = 0;
- device_disabled_count = 0;
- memset(&rstream, 0, sizeof(rstream));
-
- EXPECT_EQ(0, cras_iodev_list_add_output(&d1_));
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(
- device_enabled_cb, device_disabled_cb, (void*)0xABCD));
-
- // Enable a device, fallback should be diabled accordingly.
- cras_iodev_list_enable_dev(&d1_);
- EXPECT_EQ(&d1_, device_enabled_dev);
- EXPECT_EQ((void*)0xABCD, device_enabled_cb_data);
- EXPECT_EQ(1, device_enabled_count);
- EXPECT_EQ(1, device_disabled_count);
- EXPECT_EQ(&d1_, cras_iodev_list_get_first_enabled_iodev(CRAS_STREAM_OUTPUT));
-
- // Connect a normal stream.
- cras_iodev_open_called = 0;
- stream_add_cb(&rstream);
- EXPECT_EQ(1, cras_iodev_open_called);
-
- stream_list_has_pinned_stream_ret[d1_.info.idx] = 0;
- // Disable a device. Expect dev is closed because there's no pinned stream.
- update_active_node_called = 0;
- cras_iodev_list_disable_dev(&d1_, false);
- EXPECT_EQ(&d1_, device_disabled_dev);
- EXPECT_EQ(2, device_disabled_count);
- EXPECT_EQ((void*)0xABCD, device_disabled_cb_data);
-
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(&d1_, cras_iodev_close_dev);
- EXPECT_EQ(1, update_active_node_called);
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(
- device_enabled_cb, device_disabled_cb, (void*)0xCDEF));
- EXPECT_EQ(2, cras_observer_notify_active_node_called);
-
- EXPECT_EQ(0, cras_iodev_list_set_device_enabled_callback(NULL, NULL, NULL));
- cras_iodev_list_deinit();
-}
-
-// Test adding/removing an input dev to the list.
-TEST_F(IoDevTestSuite, AddRemoveInput) {
- struct cras_iodev_info* dev_info;
- int rc, i;
- uint64_t found_mask;
-
- d1_.direction = CRAS_STREAM_INPUT;
- d2_.direction = CRAS_STREAM_INPUT;
-
- cras_iodev_list_init();
-
- // Check no devices exist initially.
- rc = cras_iodev_list_get_inputs(NULL);
- EXPECT_EQ(0, rc);
-
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_EQ(0, rc);
- EXPECT_GE(d1_.info.idx, 0);
- // Test can't insert same iodev twice.
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_NE(0, rc);
- // Test insert a second input.
- rc = cras_iodev_list_add_input(&d2_);
- EXPECT_EQ(0, rc);
- EXPECT_GE(d2_.info.idx, 1);
- // make sure shared state was updated.
- EXPECT_EQ(2, server_state_stub.num_input_devs);
- EXPECT_EQ(d2_.info.idx, server_state_stub.input_devs[0].idx);
- EXPECT_EQ(d1_.info.idx, server_state_stub.input_devs[1].idx);
-
- // List the outputs.
- rc = cras_iodev_list_get_inputs(&dev_info);
- EXPECT_EQ(2, rc);
- if (rc == 2) {
- found_mask = 0;
- for (i = 0; i < rc; i++) {
- uint32_t idx = dev_info[i].idx;
- EXPECT_EQ(0, (found_mask & (static_cast<uint64_t>(1) << idx)));
- found_mask |= (static_cast<uint64_t>(1) << idx);
- }
- }
- if (rc > 0)
- free(dev_info);
-
- // Test that it is removed.
- rc = cras_iodev_list_rm_input(&d1_);
- EXPECT_EQ(0, rc);
- // Test that we can't remove a dev twice.
- rc = cras_iodev_list_rm_input(&d1_);
- EXPECT_NE(0, rc);
- // Should be 1 dev now.
- rc = cras_iodev_list_get_inputs(&dev_info);
- EXPECT_EQ(1, rc);
- free(dev_info);
- // Remove other dev.
- rc = cras_iodev_list_rm_input(&d2_);
- EXPECT_EQ(0, rc);
- // Shouldn't be any devices left.
- rc = cras_iodev_list_get_inputs(&dev_info);
- EXPECT_EQ(0, rc);
- free(dev_info);
-
- cras_iodev_list_deinit();
-}
-
-// Test adding/removing an input dev to the list without updating the server
-// state.
-TEST_F(IoDevTestSuite, AddRemoveInputNoSem) {
- int rc;
-
- d1_.direction = CRAS_STREAM_INPUT;
- d2_.direction = CRAS_STREAM_INPUT;
-
- server_state_update_begin_return = NULL;
- cras_iodev_list_init();
-
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_EQ(0, rc);
- EXPECT_GE(d1_.info.idx, 0);
- rc = cras_iodev_list_add_input(&d2_);
- EXPECT_EQ(0, rc);
- EXPECT_GE(d2_.info.idx, 1);
-
- EXPECT_EQ(0, cras_iodev_list_rm_input(&d1_));
- EXPECT_EQ(0, cras_iodev_list_rm_input(&d2_));
- cras_iodev_list_deinit();
-}
-
-// Test removing the last input.
-TEST_F(IoDevTestSuite, RemoveLastInput) {
- struct cras_iodev_info* dev_info;
- int rc;
-
- d1_.direction = CRAS_STREAM_INPUT;
- d2_.direction = CRAS_STREAM_INPUT;
-
- cras_iodev_list_init();
-
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_EQ(0, rc);
- rc = cras_iodev_list_add_input(&d2_);
- EXPECT_EQ(0, rc);
-
- // Test that it is removed.
- rc = cras_iodev_list_rm_input(&d1_);
- EXPECT_EQ(0, rc);
- // Add it back.
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_EQ(0, rc);
- // And again.
- rc = cras_iodev_list_rm_input(&d1_);
- EXPECT_EQ(0, rc);
- // Add it back.
- rc = cras_iodev_list_add_input(&d1_);
- EXPECT_EQ(0, rc);
- // Remove other dev.
- rc = cras_iodev_list_rm_input(&d2_);
- EXPECT_EQ(0, rc);
- // Add it back.
- rc = cras_iodev_list_add_input(&d2_);
- EXPECT_EQ(0, rc);
- // Remove both.
- rc = cras_iodev_list_rm_input(&d2_);
- EXPECT_EQ(0, rc);
- rc = cras_iodev_list_rm_input(&d1_);
- EXPECT_EQ(0, rc);
- // Shouldn't be any devices left.
- rc = cras_iodev_list_get_inputs(&dev_info);
- EXPECT_EQ(0, rc);
-
- cras_iodev_list_deinit();
-}
-
-// Test nodes changed notification is sent.
-TEST_F(IoDevTestSuite, NodesChangedNotification) {
- cras_iodev_list_init();
- EXPECT_EQ(1, cras_observer_add_called);
-
- cras_iodev_list_notify_nodes_changed();
- EXPECT_EQ(1, cras_observer_notify_nodes_called);
-
- cras_iodev_list_deinit();
- EXPECT_EQ(1, cras_observer_remove_called);
-}
-
-// Test callback function for left right swap mode is set and called.
-TEST_F(IoDevTestSuite, NodesLeftRightSwappedCallback) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- ionode.dev = &iodev;
- cras_iodev_list_notify_node_left_right_swapped(&ionode);
- EXPECT_EQ(1, cras_observer_notify_node_left_right_swapped_called);
-}
-
-// Test callback function for volume and gain are set and called.
-TEST_F(IoDevTestSuite, VolumeGainCallback) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- ionode.dev = &iodev;
- cras_iodev_list_notify_node_volume(&ionode);
- cras_iodev_list_notify_node_capture_gain(&ionode);
- EXPECT_EQ(1, cras_observer_notify_output_node_volume_called);
- EXPECT_EQ(1, cras_observer_notify_input_node_gain_called);
-}
-
-TEST_F(IoDevTestSuite, IodevListSetNodeAttr) {
- int rc;
-
- cras_iodev_list_init();
-
- // The list is empty now.
- rc = cras_iodev_list_set_node_attr(cras_make_node_id(0, 0),
- IONODE_ATTR_PLUGGED, 1);
- EXPECT_LE(rc, 0);
- EXPECT_EQ(0, set_node_plugged_called);
-
- // Add two device, each with one node.
- d1_.direction = CRAS_STREAM_INPUT;
- EXPECT_EQ(0, cras_iodev_list_add_input(&d1_));
- node1.idx = 1;
- EXPECT_EQ(0, cras_iodev_list_add_output(&d2_));
- node2.idx = 2;
-
- // Mismatch id
- rc = cras_iodev_list_set_node_attr(cras_make_node_id(d2_.info.idx, 1),
- IONODE_ATTR_PLUGGED, 1);
- EXPECT_LT(rc, 0);
- EXPECT_EQ(0, set_node_plugged_called);
-
- // Mismatch id
- rc = cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 2),
- IONODE_ATTR_PLUGGED, 1);
- EXPECT_LT(rc, 0);
- EXPECT_EQ(0, set_node_plugged_called);
-
- // Correct device id and node id
- rc = cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_PLUGGED, 1);
- EXPECT_EQ(rc, 0);
- EXPECT_EQ(1, set_node_plugged_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SetNodeVolumeCaptureGain) {
- int rc;
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
- node1.idx = 1;
- node1.dev = &d1_;
-
- // Do not ramp without software volume.
- d1_.software_volume_needed = 0;
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_VOLUME, 10);
- EXPECT_EQ(1, cras_observer_notify_output_node_volume_called);
- EXPECT_EQ(0, cras_iodev_start_volume_ramp_called);
-
- // Even with software volume, device with NULL ramp won't trigger ramp start.
- d1_.software_volume_needed = 1;
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_VOLUME, 20);
- EXPECT_EQ(2, cras_observer_notify_output_node_volume_called);
- EXPECT_EQ(0, cras_iodev_start_volume_ramp_called);
-
- // System mute prevents volume ramp from starting
- system_get_mute_return = true;
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_VOLUME, 20);
- EXPECT_EQ(3, cras_observer_notify_output_node_volume_called);
- EXPECT_EQ(0, cras_iodev_start_volume_ramp_called);
-
- // Ramp starts only when it's non-NULL, software volume is used, and
- // system is not muted
- system_get_mute_return = false;
- d1_.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_VOLUME, 20);
- EXPECT_EQ(4, cras_observer_notify_output_node_volume_called);
- EXPECT_EQ(1, cras_iodev_start_volume_ramp_called);
-
- d1_.direction = CRAS_STREAM_INPUT;
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_CAPTURE_GAIN, 15);
- EXPECT_EQ(1, cras_observer_notify_input_node_gain_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SetNodeSwapLeftRight) {
- int rc;
-
- cras_iodev_list_init();
-
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
- node1.idx = 1;
- node1.dev = &d1_;
-
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_SWAP_LEFT_RIGHT, 1);
- EXPECT_EQ(1, set_swap_mode_for_node_called);
- EXPECT_EQ(1, set_swap_mode_for_node_enable);
- EXPECT_EQ(1, node1.left_right_swapped);
- EXPECT_EQ(1, cras_observer_notify_node_left_right_swapped_called);
-
- cras_iodev_list_set_node_attr(cras_make_node_id(d1_.info.idx, 1),
- IONODE_ATTR_SWAP_LEFT_RIGHT, 0);
- EXPECT_EQ(2, set_swap_mode_for_node_called);
- EXPECT_EQ(0, set_swap_mode_for_node_enable);
- EXPECT_EQ(0, node1.left_right_swapped);
- EXPECT_EQ(2, cras_observer_notify_node_left_right_swapped_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, AddActiveNode) {
- int rc;
- struct cras_rstream rstream;
-
- memset(&rstream, 0, sizeof(rstream));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- d2_.direction = CRAS_STREAM_OUTPUT;
- d3_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
- rc = cras_iodev_list_add_output(&d2_);
- ASSERT_EQ(0, rc);
- rc = cras_iodev_list_add_output(&d3_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
- d3_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d3_.info.idx, 1));
- ASSERT_EQ(audio_thread_add_open_dev_called, 0);
- ASSERT_EQ(audio_thread_rm_open_dev_called, 0);
-
- // If a stream is added, the device should be opened.
- stream_add_cb(&rstream);
- ASSERT_EQ(audio_thread_add_open_dev_called, 1);
- audio_thread_rm_open_dev_called = 0;
- audio_thread_drain_stream_return = 10;
- stream_rm_cb(&rstream);
- ASSERT_EQ(audio_thread_drain_stream_called, 1);
- ASSERT_EQ(audio_thread_rm_open_dev_called, 0);
- audio_thread_drain_stream_return = 0;
- clock_gettime_retspec.tv_sec = 15;
- clock_gettime_retspec.tv_nsec = 45;
- stream_rm_cb(&rstream);
- ASSERT_EQ(audio_thread_drain_stream_called, 2);
- ASSERT_EQ(0, audio_thread_rm_open_dev_called);
- // Stream should remain open for a while before being closed.
- // Test it is closed after 30 seconds.
- clock_gettime_retspec.tv_sec += 30;
- cras_tm_timer_cb(NULL, NULL);
- ASSERT_EQ(1, audio_thread_rm_open_dev_called);
-
- audio_thread_rm_open_dev_called = 0;
- cras_iodev_list_rm_output(&d3_);
- ASSERT_EQ(audio_thread_rm_open_dev_called, 0);
-
- /* Assert active devices was set to default one, when selected device
- * removed. */
- cras_iodev_list_rm_output(&d1_);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, OutputDevIdleClose) {
- int rc;
- struct cras_rstream rstream;
-
- memset(&rstream, 0, sizeof(rstream));
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- EXPECT_EQ(0, audio_thread_add_open_dev_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // If a stream is added, the device should be opened.
- stream_add_cb(&rstream);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- audio_thread_rm_open_dev_called = 0;
- audio_thread_drain_stream_return = 0;
- clock_gettime_retspec.tv_sec = 15;
- stream_rm_cb(&rstream);
- EXPECT_EQ(1, audio_thread_drain_stream_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
- EXPECT_EQ(1, cras_tm_create_timer_called);
-
- // Expect no rm dev happen because idle time not yet expire, and
- // new timer should be scheduled for the rest of the idle time.
- clock_gettime_retspec.tv_sec += 7;
- cras_tm_timer_cb(NULL, NULL);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
- EXPECT_EQ(2, cras_tm_create_timer_called);
-
- // Expect d1_ be closed upon unplug, and the timer stay armed.
- cras_iodev_list_rm_output(&d1_);
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
- EXPECT_EQ(0, cras_tm_cancel_timer_called);
-
- // When timer eventually fired expect there's no more new
- // timer scheduled because d1_ has closed already.
- clock_gettime_retspec.tv_sec += 4;
- cras_tm_timer_cb(NULL, NULL);
- EXPECT_EQ(2, cras_tm_create_timer_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, DrainTimerCancel) {
- int rc;
- struct cras_rstream rstream;
-
- memset(&rstream, 0, sizeof(rstream));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- EXPECT_EQ(0, audio_thread_add_open_dev_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // If a stream is added, the device should be opened.
- stream_add_cb(&rstream);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- audio_thread_rm_open_dev_called = 0;
- audio_thread_drain_stream_return = 0;
- clock_gettime_retspec.tv_sec = 15;
- clock_gettime_retspec.tv_nsec = 45;
- stream_rm_cb(&rstream);
- EXPECT_EQ(1, audio_thread_drain_stream_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // Add stream again, make sure device isn't closed after timeout.
- audio_thread_add_open_dev_called = 0;
- stream_add_cb(&rstream);
- EXPECT_EQ(0, audio_thread_add_open_dev_called);
-
- clock_gettime_retspec.tv_sec += 30;
- cras_tm_timer_cb(NULL, NULL);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // Remove stream, and check the device is eventually closed.
- audio_thread_rm_open_dev_called = 0;
- audio_thread_drain_stream_called = 0;
- stream_rm_cb(&rstream);
- EXPECT_EQ(1, audio_thread_drain_stream_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- clock_gettime_retspec.tv_sec += 30;
- cras_tm_timer_cb(NULL, NULL);
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, RemoveThenSelectActiveNode) {
- int rc;
- cras_node_id_t id;
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- d2_.direction = CRAS_STREAM_OUTPUT;
-
- /* d1_ will be the default_output */
- rc = cras_iodev_list_add_output(&d1_);
- ASSERT_EQ(0, rc);
- rc = cras_iodev_list_add_output(&d2_);
- ASSERT_EQ(0, rc);
-
- /* Test the scenario that the selected active output removed
- * from active dev list, should be able to select back again. */
- id = cras_make_node_id(d2_.info.idx, 1);
-
- cras_iodev_list_rm_active_node(CRAS_STREAM_OUTPUT, id);
- ASSERT_EQ(audio_thread_rm_open_dev_called, 0);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, CloseDevWithPinnedStream) {
- int rc;
- struct cras_rstream rstream1, rstream2;
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- d1_.info.idx = 1;
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_EQ(0, rc);
-
- memset(&rstream1, 0, sizeof(rstream1));
- memset(&rstream2, 0, sizeof(rstream2));
- rstream2.is_pinned = 1;
- rstream2.pinned_dev_idx = d1_.info.idx;
-
- d1_.format = &fmt_;
- audio_thread_add_open_dev_called = 0;
- EXPECT_EQ(0, audio_thread_add_open_dev_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // Add a normal stream
- stream_add_cb(&rstream1);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- // Add a pinned stream, expect another dev open call triggered.
- cras_iodev_open_called = 0;
- stream_add_cb(&rstream2);
- EXPECT_EQ(1, cras_iodev_open_called);
-
- // Force disable d1_ and make sure d1_ gets closed.
- audio_thread_rm_open_dev_called = 0;
- update_active_node_called = 0;
- cras_iodev_close_called = 0;
- cras_iodev_list_disable_dev(&d1_, 1);
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(&d1_, cras_iodev_close_dev);
- EXPECT_EQ(1, update_active_node_called);
-
- // Add back the two streams, one normal one pinned.
- audio_thread_add_open_dev_called = 0;
- audio_thread_rm_open_dev_called = 0;
- cras_iodev_open_called = 0;
- stream_add_cb(&rstream2);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
- EXPECT_EQ(1, cras_iodev_open_called);
- stream_add_cb(&rstream1);
-
- // Suspend d1_ and make sure d1_ gets closed.
- update_active_node_called = 0;
- cras_iodev_close_called = 0;
- cras_iodev_list_suspend_dev(d1_.info.idx);
- EXPECT_EQ(1, audio_thread_rm_open_dev_called);
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(&d1_, cras_iodev_close_dev);
- EXPECT_EQ(1, update_active_node_called);
-
- cras_iodev_list_resume_dev(d1_.info.idx);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, DisableDevWithPinnedStream) {
- int rc;
- struct cras_rstream rstream1;
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_list_add_output(&d1_);
- EXPECT_EQ(0, rc);
-
- memset(&rstream1, 0, sizeof(rstream1));
- rstream1.is_pinned = 1;
- rstream1.pinned_dev_idx = d1_.info.idx;
-
- d1_.format = &fmt_;
- audio_thread_add_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 1));
- EXPECT_EQ(0, audio_thread_add_open_dev_called);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
-
- // Add a pinned stream.
- cras_iodev_open_called = 0;
- stream_add_cb(&rstream1);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
- EXPECT_EQ(1, cras_iodev_open_called);
-
- // Disable d1_ expect no close dev triggered because pinned stream.
- stream_list_has_pinned_stream_ret[d1_.info.idx] = 1;
- audio_thread_rm_open_dev_called = 0;
- update_active_node_called = 0;
- cras_iodev_close_called = 0;
- cras_iodev_list_disable_dev(&d1_, 0);
- EXPECT_EQ(0, audio_thread_rm_open_dev_called);
- EXPECT_EQ(0, cras_iodev_close_called);
- EXPECT_EQ(0, update_active_node_called);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, AddRemovePinnedStream) {
- struct cras_rstream rstream;
-
- cras_iodev_list_init();
-
- // Add 2 output devices.
- d1_.direction = CRAS_STREAM_OUTPUT;
- d1_.info.idx = 1;
- EXPECT_EQ(0, cras_iodev_list_add_output(&d1_));
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d1_.info.idx, 0));
- EXPECT_EQ(2, update_active_node_called);
- EXPECT_EQ(&d1_, update_active_node_iodev_val[0]);
-
- d2_.direction = CRAS_STREAM_OUTPUT;
- d2_.info.idx = 2;
- EXPECT_EQ(0, cras_iodev_list_add_output(&d2_));
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- // Setup pinned stream.
- memset(&rstream, 0, sizeof(rstream));
- rstream.is_pinned = 1;
- rstream.pinned_dev_idx = d1_.info.idx;
-
- // Add pinned stream to d1.
- update_active_node_called = 0;
- EXPECT_EQ(0, stream_add_cb(&rstream));
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- EXPECT_EQ(1, update_active_node_called);
- // Init d1_ because of pinned stream
- EXPECT_EQ(&d1_, update_active_node_iodev_val[0]);
-
- // Select d2, check pinned stream is not added to d2.
- update_active_node_called = 0;
- stream_list_has_pinned_stream_ret[d1_.info.idx] = 1;
- cras_iodev_list_select_node(CRAS_STREAM_OUTPUT,
- cras_make_node_id(d2_.info.idx, 0));
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(2, update_active_node_called);
- // Unselect d1_ and select to d2_
- EXPECT_EQ(&d2_, update_active_node_iodev_val[0]);
- EXPECT_EQ(&mock_empty_iodev[CRAS_STREAM_OUTPUT],
- update_active_node_iodev_val[1]);
-
- // Remove pinned stream from d1, check d1 is closed after stream removed.
- update_active_node_called = 0;
- stream_list_has_pinned_stream_ret[d1_.info.idx] = 0;
- EXPECT_EQ(0, stream_rm_cb(&rstream));
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(&d1_, cras_iodev_close_dev);
- EXPECT_EQ(1, update_active_node_called);
- // close pinned device
- EXPECT_EQ(&d1_, update_active_node_iodev_val[0]);
-
- // Assume dev is already opened, add pin stream should not trigger another
- // update_active_node call, but will trigger audio_thread_add_stream.
- audio_thread_is_dev_open_ret = 1;
- update_active_node_called = 0;
- EXPECT_EQ(0, stream_add_cb(&rstream));
- EXPECT_EQ(0, update_active_node_called);
- EXPECT_EQ(2, audio_thread_add_stream_called);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SuspendResumePinnedStream) {
- struct cras_rstream rstream;
-
- cras_iodev_list_init();
-
- // Add 2 output devices.
- d1_.direction = CRAS_STREAM_OUTPUT;
- EXPECT_EQ(0, cras_iodev_list_add_output(&d1_));
- d2_.direction = CRAS_STREAM_OUTPUT;
- EXPECT_EQ(0, cras_iodev_list_add_output(&d2_));
-
- d1_.format = &fmt_;
- d2_.format = &fmt_;
-
- // Setup pinned stream.
- memset(&rstream, 0, sizeof(rstream));
- rstream.is_pinned = 1;
- rstream.pinned_dev_idx = d1_.info.idx;
-
- // Add pinned stream to d1.
- EXPECT_EQ(0, stream_add_cb(&rstream));
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
-
- DL_APPEND(stream_list_get_ret, &rstream);
-
- // Test for suspend
-
- // Device state enters no_stream after stream is disconnected.
- d1_.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Device has no pinned stream now. But this pinned stream remains in
- // stream_list.
- stream_list_has_pinned_stream_ret[d1_.info.idx] = 0;
-
- // Suspend
- observer_ops->suspend_changed(NULL, 1);
-
- // Verify that stream is disconnected and d1 is closed.
- EXPECT_EQ(1, audio_thread_disconnect_stream_called);
- EXPECT_EQ(&rstream, audio_thread_disconnect_stream_stream);
- EXPECT_EQ(1, cras_iodev_close_called);
- EXPECT_EQ(&d1_, cras_iodev_close_dev);
-
- // Test for resume
- cras_iodev_open_called = 0;
- audio_thread_add_stream_called = 0;
- audio_thread_add_stream_stream = NULL;
- d1_.state = CRAS_IODEV_STATE_CLOSE;
-
- // Resume
- observer_ops->suspend_changed(NULL, 0);
-
- // Verify that device is opened and stream is attached to the device.
- EXPECT_EQ(1, cras_iodev_open_called);
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, HotwordStreamsAddedThenSuspendResume) {
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
- cras_iodev_list_init();
-
- node1.type = CRAS_NODE_TYPE_HOTWORD;
- d1_.direction = CRAS_STREAM_INPUT;
- EXPECT_EQ(0, cras_iodev_list_add_input(&d1_));
-
- d1_.format = &fmt_;
-
- memset(&rstream, 0, sizeof(rstream));
- rstream.is_pinned = 1;
- rstream.pinned_dev_idx = d1_.info.idx;
- rstream.flags = HOTWORD_STREAM;
-
- /* Add a hotword stream. */
- EXPECT_EQ(0, stream_add_cb(&rstream));
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
-
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
-
- /* Suspend hotword streams, verify the existing stream disconnects
- * from the hotword device and connects to the empty iodev. */
- EXPECT_EQ(0, cras_iodev_list_suspend_hotword_streams());
- EXPECT_EQ(1, audio_thread_disconnect_stream_called);
- EXPECT_EQ(&rstream, audio_thread_disconnect_stream_stream);
- EXPECT_EQ(&d1_, audio_thread_disconnect_stream_dev);
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- EXPECT_EQ(&mock_hotword_iodev, audio_thread_add_stream_dev);
-
- /* Resume hotword streams, verify the stream disconnects from
- * the empty iodev and connects back to the real hotword iodev. */
- EXPECT_EQ(0, cras_iodev_list_resume_hotword_stream());
- EXPECT_EQ(2, audio_thread_disconnect_stream_called);
- EXPECT_EQ(&rstream, audio_thread_disconnect_stream_stream);
- EXPECT_EQ(&mock_hotword_iodev, audio_thread_disconnect_stream_dev);
- EXPECT_EQ(3, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, HotwordStreamsAddedAfterSuspend) {
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
- cras_iodev_list_init();
-
- node1.type = CRAS_NODE_TYPE_HOTWORD;
- d1_.direction = CRAS_STREAM_INPUT;
- EXPECT_EQ(0, cras_iodev_list_add_input(&d1_));
-
- d1_.format = &fmt_;
-
- memset(&rstream, 0, sizeof(rstream));
- rstream.is_pinned = 1;
- rstream.pinned_dev_idx = d1_.info.idx;
- rstream.flags = HOTWORD_STREAM;
-
- /* Suspends hotword streams before a stream connected. */
- EXPECT_EQ(0, cras_iodev_list_suspend_hotword_streams());
- EXPECT_EQ(0, audio_thread_disconnect_stream_called);
- EXPECT_EQ(0, audio_thread_add_stream_called);
-
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
-
- /* Hotword stream connected, verify it is added to the empty iodev. */
- EXPECT_EQ(0, stream_add_cb(&rstream));
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(&mock_hotword_iodev, audio_thread_add_stream_dev);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
-
- /* Resume hotword streams, now the existing hotword stream should disconnect
- * from the empty iodev and connect to the real hotword iodev. */
- EXPECT_EQ(0, cras_iodev_list_resume_hotword_stream());
- EXPECT_EQ(1, audio_thread_disconnect_stream_called);
- EXPECT_EQ(&rstream, audio_thread_disconnect_stream_stream);
- EXPECT_EQ(&mock_hotword_iodev, audio_thread_disconnect_stream_dev);
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, GetSCOPCMIodevs) {
- cras_iodev_list_init();
-
- fake_sco_in_dev.direction = CRAS_STREAM_INPUT;
- fake_sco_in_node.is_sco_pcm = 1;
- cras_iodev_list_add_input(&fake_sco_in_dev);
- fake_sco_out_dev.direction = CRAS_STREAM_OUTPUT;
- fake_sco_out_node.is_sco_pcm = 1;
- cras_iodev_list_add_output(&fake_sco_out_dev);
-
- EXPECT_EQ(&fake_sco_in_dev,
- cras_iodev_list_get_sco_pcm_iodev(CRAS_STREAM_INPUT));
- EXPECT_EQ(&fake_sco_out_dev,
- cras_iodev_list_get_sco_pcm_iodev(CRAS_STREAM_OUTPUT));
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, HotwordStreamsPausedAtSystemSuspend) {
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
- cras_iodev_list_init();
-
- node1.type = CRAS_NODE_TYPE_HOTWORD;
- d1_.direction = CRAS_STREAM_INPUT;
- EXPECT_EQ(0, cras_iodev_list_add_input(&d1_));
-
- d1_.format = &fmt_;
-
- memset(&rstream, 0, sizeof(rstream));
- rstream.is_pinned = 1;
- rstream.pinned_dev_idx = d1_.info.idx;
- rstream.flags = HOTWORD_STREAM;
-
- /* Add a hotword stream. */
- EXPECT_EQ(0, stream_add_cb(&rstream));
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
-
- DL_APPEND(stream_list, &rstream);
- stream_list_get_ret = stream_list;
-
- server_state_hotword_pause_at_suspend = 1;
-
- /* Trigger system suspend. Verify hotword stream is moved to empty dev. */
- observer_ops->suspend_changed(NULL, 1);
- EXPECT_EQ(1, audio_thread_disconnect_stream_called);
- EXPECT_EQ(&rstream, audio_thread_disconnect_stream_stream);
- EXPECT_EQ(&d1_, audio_thread_disconnect_stream_dev);
- EXPECT_EQ(2, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- EXPECT_EQ(&mock_hotword_iodev, audio_thread_add_stream_dev);
-
- /* Trigger system resume. Verify hotword stream is moved to real dev.*/
- observer_ops->suspend_changed(NULL, 0);
- EXPECT_EQ(2, audio_thread_disconnect_stream_called);
- EXPECT_EQ(&rstream, audio_thread_disconnect_stream_stream);
- EXPECT_EQ(&mock_hotword_iodev, audio_thread_disconnect_stream_dev);
- EXPECT_EQ(3, audio_thread_add_stream_called);
- EXPECT_EQ(&rstream, audio_thread_add_stream_stream);
- EXPECT_EQ(&d1_, audio_thread_add_stream_dev);
-
- server_state_hotword_pause_at_suspend = 0;
- audio_thread_disconnect_stream_called = 0;
- audio_thread_add_stream_called = 0;
-
- /* Trigger system suspend. Verify hotword stream is not touched. */
- observer_ops->suspend_changed(NULL, 1);
- EXPECT_EQ(0, audio_thread_disconnect_stream_called);
- EXPECT_EQ(0, audio_thread_add_stream_called);
-
- /* Trigger system resume. Verify hotword stream is not touched.*/
- observer_ops->suspend_changed(NULL, 0);
- EXPECT_EQ(0, audio_thread_disconnect_stream_called);
- EXPECT_EQ(0, audio_thread_add_stream_called);
-
- cras_iodev_list_deinit();
-}
-
-TEST_F(IoDevTestSuite, SetNoiseCancellation) {
- struct cras_rstream rstream;
- struct cras_rstream* stream_list = NULL;
- int rc;
-
- memset(&rstream, 0, sizeof(rstream));
-
- cras_iodev_list_init();
-
- d1_.direction = CRAS_STREAM_INPUT;
- rc = cras_iodev_list_add_input(&d1_);
- ASSERT_EQ(0, rc);
-
- d1_.format = &fmt_;
-
- rstream.direction = CRAS_STREAM_INPUT;
-
- audio_thread_add_open_dev_called = 0;
- audio_thread_rm_open_dev_called = 0;
- cras_iodev_list_add_active_node(CRAS_STREAM_INPUT,
- cras_make_node_id(d1_.info.idx, 1));
- DL_APPEND(stream_list, &rstream);
- stream_add_cb(&rstream);
- stream_list_get_ret = stream_list;
- EXPECT_EQ(1, audio_thread_add_stream_called);
- EXPECT_EQ(1, audio_thread_add_open_dev_called);
-
- // reset_for_noise_cancellation causes device suspend & resume
- // While suspending d1_: rm d1_, open fallback
- // While resuming d1_: rm fallback, open d1_
- cras_iodev_list_reset_for_noise_cancellation();
- EXPECT_EQ(3, audio_thread_add_open_dev_called);
- EXPECT_EQ(2, audio_thread_rm_open_dev_called);
-
- cras_iodev_list_deinit();
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-extern "C" {
-
-// Stubs
-struct main_thread_event_log* main_log;
-
-struct cras_server_state* cras_system_state_update_begin() {
- return server_state_update_begin_return;
-}
-
-void cras_system_state_update_complete() {}
-
-int cras_system_get_mute() {
- return system_get_mute_return;
-}
-
-bool cras_system_get_noise_cancellation_enabled() {
- return false;
-}
-
-struct audio_thread* audio_thread_create() {
- return &thread;
-}
-
-int audio_thread_start(struct audio_thread* thread) {
- return 0;
-}
-
-void audio_thread_destroy(struct audio_thread* thread) {}
-
-int audio_thread_set_active_dev(struct audio_thread* thread,
- struct cras_iodev* dev) {
- audio_thread_set_active_dev_called++;
- audio_thread_set_active_dev_val = dev;
- return 0;
-}
-
-void audio_thread_remove_streams(struct audio_thread* thread,
- enum CRAS_STREAM_DIRECTION dir) {
- audio_thread_remove_streams_active_dev = audio_thread_set_active_dev_val;
-}
-
-int audio_thread_add_open_dev(struct audio_thread* thread,
- struct cras_iodev* dev) {
- audio_thread_add_open_dev_dev = dev;
- audio_thread_add_open_dev_called++;
- return 0;
-}
-
-int audio_thread_rm_open_dev(struct audio_thread* thread,
- enum CRAS_STREAM_DIRECTION dir,
- unsigned int dev_idx) {
- audio_thread_rm_open_dev_called++;
- return 0;
-}
-
-int audio_thread_is_dev_open(struct audio_thread* thread,
- struct cras_iodev* dev) {
- return audio_thread_is_dev_open_ret;
-}
-
-int audio_thread_add_stream(struct audio_thread* thread,
- struct cras_rstream* stream,
- struct cras_iodev** devs,
- unsigned int num_devs) {
- audio_thread_add_stream_called++;
- audio_thread_add_stream_stream = stream;
- audio_thread_add_stream_dev = (num_devs ? devs[0] : NULL);
- return 0;
-}
-
-int audio_thread_disconnect_stream(struct audio_thread* thread,
- struct cras_rstream* stream,
- struct cras_iodev* iodev) {
- audio_thread_disconnect_stream_called++;
- audio_thread_disconnect_stream_stream = stream;
- audio_thread_disconnect_stream_dev = iodev;
- return 0;
-}
-
-int audio_thread_drain_stream(struct audio_thread* thread,
- struct cras_rstream* stream) {
- audio_thread_drain_stream_called++;
- return audio_thread_drain_stream_return;
-}
-
-struct cras_iodev* empty_iodev_create(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_NODE_TYPE node_type) {
- struct cras_iodev* dev;
- if (node_type == CRAS_NODE_TYPE_HOTWORD) {
- dev = &mock_hotword_iodev;
- } else {
- dev = &mock_empty_iodev[direction];
- }
- dev->direction = direction;
- if (dev->active_node == NULL) {
- struct cras_ionode* node = (struct cras_ionode*)calloc(1, sizeof(*node));
- node->type = node_type;
- dev->active_node = node;
- }
- return dev;
-}
-
-void empty_iodev_destroy(struct cras_iodev* iodev) {
- if (iodev->active_node) {
- free(iodev->active_node);
- iodev->active_node = NULL;
- }
-}
-
-struct cras_iodev* test_iodev_create(enum CRAS_STREAM_DIRECTION direction,
- enum TEST_IODEV_TYPE type) {
- return NULL;
-}
-
-void test_iodev_command(struct cras_iodev* iodev,
- enum CRAS_TEST_IODEV_CMD command,
- unsigned int data_len,
- const uint8_t* data) {}
-
-struct cras_iodev* loopback_iodev_create(enum CRAS_LOOPBACK_TYPE type) {
- return &loopback_input;
-}
-
-void loopback_iodev_destroy(struct cras_iodev* iodev) {}
-
-int cras_iodev_open(struct cras_iodev* iodev,
- unsigned int cb_level,
- const struct cras_audio_format* fmt) {
- if (cras_iodev_open_ret[cras_iodev_open_called] == 0)
- iodev->state = CRAS_IODEV_STATE_OPEN;
- cras_iodev_open_fmt = *fmt;
- iodev->format = &cras_iodev_open_fmt;
- return cras_iodev_open_ret[cras_iodev_open_called++];
-}
-
-int cras_iodev_close(struct cras_iodev* iodev) {
- iodev->state = CRAS_IODEV_STATE_CLOSE;
- cras_iodev_close_called++;
- cras_iodev_close_dev = iodev;
- iodev->format = NULL;
- return 0;
-}
-
-int cras_iodev_set_format(struct cras_iodev* iodev,
- const struct cras_audio_format* fmt) {
- return 0;
-}
-
-int cras_iodev_set_mute(struct cras_iodev* iodev) {
- set_mute_called++;
- set_mute_dev_vector.push_back(iodev);
- return 0;
-}
-
-void cras_iodev_set_node_plugged(struct cras_ionode* node, int plugged) {
- set_node_plugged_called++;
-}
-
-bool cras_iodev_support_noise_cancellation(const struct cras_iodev* iodev) {
- return true;
-}
-
-int cras_iodev_start_volume_ramp(struct cras_iodev* odev,
- unsigned int old_volume,
- unsigned int new_volume) {
- cras_iodev_start_volume_ramp_called++;
- return 0;
-}
-bool cras_iodev_is_aec_use_case(const struct cras_ionode* node) {
- return 1;
-}
-bool stream_list_has_pinned_stream(struct stream_list* list,
- unsigned int dev_idx) {
- return stream_list_has_pinned_stream_ret[dev_idx];
-}
-
-struct stream_list* stream_list_create(stream_callback* add_cb,
- stream_callback* rm_cb,
- stream_create_func* create_cb,
- stream_destroy_func* destroy_cb,
- struct cras_tm* timer_manager) {
- stream_add_cb = add_cb;
- stream_rm_cb = rm_cb;
- return reinterpret_cast<stream_list*>(0xf00);
-}
-
-void stream_list_destroy(struct stream_list* list) {}
-
-struct cras_rstream* stream_list_get(struct stream_list* list) {
- return stream_list_get_ret;
-}
-void server_stream_create(struct stream_list* stream_list,
- unsigned int dev_idx) {
- server_stream_create_called++;
-}
-void server_stream_destroy(struct stream_list* stream_list,
- unsigned int dev_idx) {
- server_stream_destroy_called++;
-}
-
-int cras_rstream_create(struct cras_rstream_config* config,
- struct cras_rstream** stream_out) {
- return 0;
-}
-
-void cras_rstream_destroy(struct cras_rstream* rstream) {}
-
-struct cras_tm* cras_system_state_get_tm() {
- return NULL;
-}
-
-struct cras_timer* cras_tm_create_timer(struct cras_tm* tm,
- unsigned int ms,
- void (*cb)(struct cras_timer* t,
- void* data),
- void* cb_data) {
- cras_tm_timer_cb = cb;
- cras_tm_timer_cb_data = cb_data;
- cras_tm_create_timer_called++;
- return reinterpret_cast<struct cras_timer*>(0x404);
-}
-
-void cras_tm_cancel_timer(struct cras_tm* tm, struct cras_timer* t) {
- cras_tm_cancel_timer_called++;
-}
-
-void cras_fmt_conv_destroy(struct cras_fmt_conv* conv) {}
-
-struct cras_fmt_conv* cras_channel_remix_conv_create(unsigned int num_channels,
- const float* coefficient) {
- return NULL;
-}
-
-void cras_channel_remix_convert(struct cras_fmt_conv* conv,
- uint8_t* in_buf,
- size_t frames) {}
-
-struct cras_observer_client* cras_observer_add(
- const struct cras_observer_ops* ops,
- void* context) {
- observer_ops = (struct cras_observer_ops*)calloc(1, sizeof(*ops));
- memcpy(observer_ops, ops, sizeof(*ops));
- cras_observer_add_called++;
- return reinterpret_cast<struct cras_observer_client*>(0x55);
-}
-
-void cras_observer_remove(struct cras_observer_client* client) {
- if (observer_ops)
- free(observer_ops);
- cras_observer_remove_called++;
-}
-
-void cras_observer_notify_nodes(void) {
- cras_observer_notify_nodes_called++;
-}
-
-void cras_observer_notify_active_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id) {
- cras_observer_notify_active_node_called++;
-}
-
-void cras_observer_notify_output_node_volume(cras_node_id_t node_id,
- int32_t volume) {
- cras_observer_notify_output_node_volume_called++;
-}
-
-void cras_observer_notify_node_left_right_swapped(cras_node_id_t node_id,
- int swapped) {
- cras_observer_notify_node_left_right_swapped_called++;
-}
-
-void cras_observer_notify_input_node_gain(cras_node_id_t node_id,
- int32_t gain) {
- cras_observer_notify_input_node_gain_called++;
-}
-
-int audio_thread_dev_start_ramp(struct audio_thread* thread,
- unsigned int dev_idx,
- enum CRAS_IODEV_RAMP_REQUEST request) {
- audio_thread_dev_start_ramp_called++;
- audio_thread_dev_start_ramp_dev_vector.push_back(dev_idx);
- audio_thread_dev_start_ramp_req = request;
- return 0;
-}
-
-#ifdef HAVE_WEBRTC_APM
-struct cras_apm* cras_apm_list_add_apm(struct cras_apm_list* list,
- void* dev_ptr,
- const struct cras_audio_format* fmt,
- bool is_internal_dev) {
- return NULL;
-}
-void cras_apm_list_remove_apm(struct cras_apm_list* list, void* dev_ptr) {}
-int cras_apm_list_init(const char* device_config_dir) {
- return 0;
-}
-#endif
-
-// From librt.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = clock_gettime_retspec.tv_sec;
- tp->tv_nsec = clock_gettime_retspec.tv_nsec;
- return 0;
-}
-
-bool cras_system_get_hotword_pause_at_suspend() {
- return !!server_state_hotword_pause_at_suspend;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/iodev_stub.cc b/cras/src/tests/iodev_stub.cc
deleted file mode 100644
index 2e84faac..00000000
--- a/cras/src/tests/iodev_stub.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <time.h>
-
-#include <unordered_map>
-
-extern "C" {
-#include "cras_iodev.h"
-#include "dev_stream.h"
-#include "utlist.h"
-}
-
-namespace {
-struct cb_data {
- int frames_queued_ret;
- timespec frames_queued_ts;
-};
-std::unordered_map<cras_iodev*, cb_data> frames_queued_map;
-std::unordered_map<cras_iodev*, cb_data> valid_frames_map;
-std::unordered_map<cras_iodev*, timespec> drop_time_map;
-std::unordered_map<const cras_iodev*, double> est_rate_ratio_map;
-std::unordered_map<const cras_iodev*, int> update_rate_map;
-std::unordered_map<const cras_ionode*, int> on_internal_card_map;
-} // namespace
-
-void iodev_stub_reset() {
- frames_queued_map.clear();
- valid_frames_map.clear();
- drop_time_map.clear();
- est_rate_ratio_map.clear();
- update_rate_map.clear();
- on_internal_card_map.clear();
-}
-
-void iodev_stub_est_rate_ratio(cras_iodev* iodev, double ratio) {
- est_rate_ratio_map.insert({iodev, ratio});
-}
-
-void iodev_stub_update_rate(cras_iodev* iodev, int data) {
- update_rate_map.insert({iodev, data});
-}
-
-void iodev_stub_on_internal_card(cras_ionode* node, int data) {
- on_internal_card_map.insert({node, data});
-}
-
-void iodev_stub_frames_queued(cras_iodev* iodev, int ret, timespec ts) {
- cb_data data = {ret, ts};
- frames_queued_map.insert({iodev, data});
-}
-
-void iodev_stub_valid_frames(cras_iodev* iodev, int ret, timespec ts) {
- cb_data data = {ret, ts};
- valid_frames_map.insert({iodev, data});
-}
-
-bool iodev_stub_get_drop_time(cras_iodev* iodev, timespec* ts) {
- auto elem = drop_time_map.find(iodev);
- if (elem != drop_time_map.end()) {
- *ts = elem->second;
- return true;
- }
- return false;
-}
-
-extern "C" {
-
-int cras_iodev_add_stream(struct cras_iodev* iodev, struct dev_stream* stream) {
- DL_APPEND(iodev->streams, stream);
- return 0;
-}
-
-int cras_iodev_get_valid_frames(struct cras_iodev* iodev,
- struct timespec* tstamp) {
- auto elem = valid_frames_map.find(iodev);
- if (elem != valid_frames_map.end()) {
- *tstamp = elem->second.frames_queued_ts;
- return elem->second.frames_queued_ret;
- }
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return 0;
-}
-
-double cras_iodev_get_est_rate_ratio(const struct cras_iodev* iodev) {
- auto elem = est_rate_ratio_map.find(iodev);
- if (elem != est_rate_ratio_map.end()) {
- return elem->second;
- }
- return 1.0f;
-}
-
-int cras_iodev_get_dsp_delay(const struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_frames_queued(struct cras_iodev* iodev,
- struct timespec* tstamp) {
- auto elem = frames_queued_map.find(iodev);
- if (elem != frames_queued_map.end()) {
- *tstamp = elem->second.frames_queued_ts;
- return elem->second.frames_queued_ret;
- }
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return 0;
-}
-
-struct dev_stream* cras_iodev_rm_stream(struct cras_iodev* iodev,
- const struct cras_rstream* stream) {
- return NULL;
-}
-
-int cras_iodev_update_rate(struct cras_iodev* iodev,
- unsigned int level,
- struct timespec* level_tstamp) {
- auto elem = update_rate_map.find(iodev);
- if (elem != update_rate_map.end()) {
- return elem->second;
- }
- return 0;
-}
-
-enum CRAS_IODEV_STATE cras_iodev_state(const struct cras_iodev* iodev) {
- return iodev->state;
-}
-
-unsigned int cras_iodev_all_streams_written(struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_put_input_buffer(struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_put_output_buffer(struct cras_iodev* iodev,
- uint8_t* frames,
- unsigned int nframes,
- int* non_empty,
- struct cras_fmt_conv* output_converter) {
- return 0;
-}
-
-int cras_iodev_get_input_buffer(struct cras_iodev* iodev, unsigned* frames) {
- return 0;
-}
-
-int cras_iodev_get_output_buffer(struct cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned* frames) {
- return 0;
-}
-
-float cras_iodev_get_software_gain_scaler(const struct cras_iodev* iodev) {
- return 0.0;
-}
-
-void cras_iodev_stream_written(struct cras_iodev* iodev,
- struct dev_stream* stream,
- unsigned int nwritten) {}
-
-int cras_iodev_prepare_output_before_write_samples(struct cras_iodev* odev) {
- return 0;
-}
-
-int cras_iodev_buffer_avail(struct cras_iodev* iodev, unsigned hw_level) {
- return 0;
-}
-
-unsigned int cras_iodev_max_stream_offset(const struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_iodev_odev_should_wake(const struct cras_iodev* odev) {
- return 1;
-}
-
-int cras_iodev_output_underrun(struct cras_iodev* odev,
- unsigned int hw_level,
- unsigned int frames_written) {
- return 0;
-}
-
-int cras_iodev_reset_request(struct cras_iodev* iodev) {
- return 0;
-}
-
-unsigned int cras_iodev_stream_offset(struct cras_iodev* iodev,
- struct dev_stream* stream) {
- return 0;
-}
-
-unsigned int cras_iodev_get_num_underruns(const struct cras_iodev* iodev) {
- return 0;
-}
-
-unsigned int cras_iodev_frames_to_play_in_sleep(struct cras_iodev* odev,
- unsigned int* hw_level,
- struct timespec* hw_tstamp) {
- clock_gettime(CLOCK_MONOTONIC_RAW, hw_tstamp);
- *hw_level = 0;
- return 0;
-}
-
-void cras_iodev_update_highest_hw_level(struct cras_iodev* iodev,
- unsigned int hw_level) {}
-
-void cras_iodev_start_stream(struct cras_iodev* iodev,
- struct dev_stream* stream) {}
-
-int cras_iodev_drop_frames_by_time(struct cras_iodev* iodev,
- struct timespec ts) {
- drop_time_map.insert({iodev, ts});
- return 0;
-}
-
-bool cras_iodev_is_on_internal_card(const struct cras_ionode* node) {
- auto elem = on_internal_card_map.find(node);
- if (elem != on_internal_card_map.end()) {
- return elem->second;
- }
- return 1;
-}
-} // extern "C"
diff --git a/cras/src/tests/iodev_stub.h b/cras/src/tests/iodev_stub.h
deleted file mode 100644
index e8016dd3..00000000
--- a/cras/src/tests/iodev_stub.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef IODEV_STUB_H_
-#define IODEV_STUB_H_
-
-#include <time.h>
-
-void iodev_stub_reset();
-
-void iodev_stub_est_rate_ratio(cras_iodev* iodev, double ratio);
-
-void iodev_stub_update_rate(cras_iodev* iodev, int data);
-
-void iodev_stub_on_internal_card(cras_ionode* node, int data);
-
-void iodev_stub_frames_queued(cras_iodev* iodev, int ret, timespec ts);
-
-void iodev_stub_valid_frames(cras_iodev* iodev, int ret, timespec ts);
-
-bool iodev_stub_get_drop_time(cras_iodev* iodev, timespec* ts);
-
-#endif // IODEV_STUB_H_
diff --git a/cras/src/tests/iodev_unittest.cc b/cras/src/tests/iodev_unittest.cc
deleted file mode 100644
index 24b2b38d..00000000
--- a/cras/src/tests/iodev_unittest.cc
+++ /dev/null
@@ -1,2801 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "audio_thread_log.h"
-#include "cras_audio_area.h"
-#include "cras_iodev.h"
-#include "cras_main_thread_log.h"
-#include "cras_ramp.h"
-#include "cras_rstream.h"
-#include "dev_stream.h"
-#include "input_data.h"
-#include "utlist.h"
-
-// Mock software volume scalers.
-float softvol_scalers[101];
-
-// For audio_thread_log.h use.
-int atlog_rw_shm_fd;
-int atlog_ro_shm_fd;
-}
-
-#define BUFFER_SIZE 8192
-
-static const float RAMP_UNMUTE_DURATION_SECS = 0.5;
-static const float RAMP_NEW_STREAM_DURATION_SECS = 0.01;
-static const float RAMP_MUTE_DURATION_SECS = 0.1;
-static const float RAMP_VOLUME_CHANGE_DURATION_SECS = 0.1;
-
-static int cras_iodev_list_disable_dev_called;
-static int select_node_called;
-static enum CRAS_STREAM_DIRECTION select_node_direction;
-static cras_node_id_t select_node_id;
-static struct cras_ionode* node_selected;
-static size_t notify_nodes_changed_called;
-static size_t notify_active_node_changed_called;
-static int dsp_context_new_sample_rate;
-static const char* dsp_context_new_purpose;
-static int dsp_context_free_called;
-static int update_channel_layout_called;
-static int update_channel_layout_return_val;
-static int cras_audio_format_set_channel_layout_called;
-static unsigned int cras_system_get_volume_return;
-static int cras_dsp_get_pipeline_called;
-static int cras_dsp_get_pipeline_ret;
-static int cras_dsp_put_pipeline_called;
-static int cras_dsp_pipeline_get_source_buffer_called;
-static int cras_dsp_pipeline_get_sink_buffer_called;
-static float cras_dsp_pipeline_source_buffer[2][DSP_BUFFER_SIZE];
-static float cras_dsp_pipeline_sink_buffer[2][DSP_BUFFER_SIZE];
-static int cras_dsp_pipeline_get_delay_called;
-static int cras_dsp_pipeline_apply_called;
-static int cras_dsp_pipeline_set_sink_ext_module_called;
-static int cras_dsp_pipeline_apply_sample_count;
-static unsigned int cras_mix_mute_count;
-static unsigned int cras_dsp_num_input_channels_return;
-static unsigned int cras_dsp_num_output_channels_return;
-struct cras_dsp_context* cras_dsp_context_new_return;
-static unsigned int cras_dsp_load_mock_pipeline_called;
-static unsigned int rate_estimator_add_frames_num_frames;
-static unsigned int rate_estimator_add_frames_called;
-static int cras_system_get_mute_return;
-static snd_pcm_format_t cras_scale_buffer_fmt;
-static float cras_scale_buffer_scaler;
-static int cras_scale_buffer_called;
-static unsigned int pre_dsp_hook_called;
-static const uint8_t* pre_dsp_hook_frames;
-static void* pre_dsp_hook_cb_data;
-static unsigned int post_dsp_hook_called;
-static const uint8_t* post_dsp_hook_frames;
-static void* post_dsp_hook_cb_data;
-static int iodev_buffer_size;
-static uint8_t audio_buffer[BUFFER_SIZE];
-static struct cras_audio_area* audio_area;
-static unsigned int put_buffer_nframes;
-static int is_free_running_ret;
-static int no_stream_called;
-static int no_stream_enable;
-// This will be used extensively in cras_iodev.
-struct audio_thread_event_log* atlog;
-static unsigned int simple_no_stream_called;
-static int simple_no_stream_enable;
-static int dev_stream_playback_frames_ret;
-static int device_monitor_reset_device_called;
-static int output_underrun_called;
-static int set_mute_called;
-static int cras_ramp_start_mute_ramp;
-static float cras_ramp_start_from;
-static float cras_ramp_start_to;
-static int cras_ramp_start_duration_frames;
-static int cras_ramp_start_is_called;
-static int cras_ramp_reset_is_called;
-static struct cras_ramp_action cras_ramp_get_current_action_ret;
-static int cras_ramp_update_ramped_frames_num_frames;
-static cras_ramp_cb cras_ramp_start_cb;
-static void* cras_ramp_start_cb_data;
-static int cras_device_monitor_set_device_mute_state_called;
-unsigned int cras_device_monitor_set_device_mute_state_dev_idx;
-static snd_pcm_format_t cras_scale_buffer_increment_fmt;
-static uint8_t* cras_scale_buffer_increment_buff;
-static unsigned int cras_scale_buffer_increment_frame;
-static float cras_scale_buffer_increment_scaler;
-static float cras_scale_buffer_increment_increment;
-static float cras_scale_buffer_increment_target;
-static int cras_scale_buffer_increment_channel;
-static struct cras_audio_format audio_fmt;
-static int buffer_share_add_id_called;
-static int buffer_share_get_new_write_point_ret;
-static int ext_mod_configure_called;
-static struct input_data* input_data_create_ret;
-static double rate_estimator_get_rate_ret;
-static int cras_audio_thread_event_dev_overrun_called;
-
-static char* atlog_name;
-
-// Iodev callback
-int update_channel_layout(struct cras_iodev* iodev) {
- update_channel_layout_called = 1;
- return update_channel_layout_return_val;
-}
-
-void ResetStubData() {
- cras_iodev_list_disable_dev_called = 0;
- select_node_called = 0;
- notify_nodes_changed_called = 0;
- notify_active_node_changed_called = 0;
- dsp_context_new_sample_rate = 0;
- dsp_context_new_purpose = NULL;
- dsp_context_free_called = 0;
- cras_audio_format_set_channel_layout_called = 0;
- cras_dsp_get_pipeline_called = 0;
- cras_dsp_get_pipeline_ret = 0;
- cras_dsp_put_pipeline_called = 0;
- cras_dsp_pipeline_get_source_buffer_called = 0;
- cras_dsp_pipeline_get_sink_buffer_called = 0;
- memset(&cras_dsp_pipeline_source_buffer, 0,
- sizeof(cras_dsp_pipeline_source_buffer));
- memset(&cras_dsp_pipeline_sink_buffer, 0,
- sizeof(cras_dsp_pipeline_sink_buffer));
- cras_dsp_pipeline_get_delay_called = 0;
- cras_dsp_pipeline_apply_called = 0;
- cras_dsp_pipeline_set_sink_ext_module_called = 0;
- cras_dsp_pipeline_apply_sample_count = 0;
- cras_dsp_num_input_channels_return = 2;
- cras_dsp_num_output_channels_return = 2;
- cras_dsp_context_new_return = NULL;
- cras_dsp_load_mock_pipeline_called = 0;
- rate_estimator_add_frames_num_frames = 0;
- rate_estimator_add_frames_called = 0;
- cras_system_get_mute_return = 0;
- cras_system_get_volume_return = 100;
- cras_mix_mute_count = 0;
- pre_dsp_hook_called = 0;
- pre_dsp_hook_frames = NULL;
- post_dsp_hook_called = 0;
- post_dsp_hook_frames = NULL;
- iodev_buffer_size = 0;
- // Assume there is some data in audio buffer.
- memset(audio_buffer, 0xff, sizeof(audio_buffer));
- if (audio_area) {
- free(audio_area);
- audio_area = NULL;
- }
- put_buffer_nframes = 0;
- is_free_running_ret = 0;
- no_stream_called = 0;
- no_stream_enable = 0;
- simple_no_stream_called = 0;
- simple_no_stream_enable = 0;
- dev_stream_playback_frames_ret = 0;
- if (!atlog) {
- if (asprintf(&atlog_name, "/ATlog-%d", getpid()) < 0) {
- exit(-1);
- }
- /* To avoid un-used variable warning. */
- atlog_rw_shm_fd = atlog_ro_shm_fd = -1;
- atlog = audio_thread_event_log_init(atlog_name);
- }
- device_monitor_reset_device_called = 0;
- output_underrun_called = 0;
- set_mute_called = 0;
- cras_ramp_start_mute_ramp = 0;
- cras_ramp_start_from = 0.0;
- cras_ramp_start_to = 0.0;
- cras_ramp_start_duration_frames = 0;
- cras_ramp_start_cb = NULL;
- cras_ramp_start_cb_data = NULL;
- cras_ramp_start_is_called = 0;
- cras_ramp_reset_is_called = 0;
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_NONE;
- cras_ramp_update_ramped_frames_num_frames = 0;
- cras_device_monitor_set_device_mute_state_called = 0;
- cras_device_monitor_set_device_mute_state_dev_idx = 0;
- cras_scale_buffer_called = 0;
- cras_scale_buffer_increment_fmt = SND_PCM_FORMAT_UNKNOWN;
- cras_scale_buffer_increment_buff = NULL;
- cras_scale_buffer_increment_frame = 0;
- cras_scale_buffer_increment_scaler = 0;
- cras_scale_buffer_increment_increment = 0;
- cras_scale_buffer_increment_target = 0.0;
- cras_scale_buffer_increment_channel = 0;
- audio_fmt.format = SND_PCM_FORMAT_S16_LE;
- audio_fmt.frame_rate = 48000;
- audio_fmt.num_channels = 2;
- buffer_share_add_id_called = 0;
- ext_mod_configure_called = 0;
- rate_estimator_get_rate_ret = 0;
- cras_audio_thread_event_dev_overrun_called = 0;
-}
-
-namespace {
-
-// Test fill_time_from_frames
-TEST(IoDevTestSuite, FillTimeFromFramesNormal) {
- struct timespec ts;
-
- cras_iodev_fill_time_from_frames(12000, 48000, &ts);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 249900000);
- EXPECT_LE(ts.tv_nsec, 250100000);
-}
-
-TEST(IoDevTestSuite, FillTimeFromFramesLong) {
- struct timespec ts;
-
- cras_iodev_fill_time_from_frames(120000 - 12000, 48000, &ts);
- EXPECT_EQ(2, ts.tv_sec);
- EXPECT_GE(ts.tv_nsec, 249900000);
- EXPECT_LE(ts.tv_nsec, 250100000);
-}
-
-TEST(IoDevTestSuite, FillTimeFromFramesShort) {
- struct timespec ts;
-
- cras_iodev_fill_time_from_frames(12000 - 12000, 48000, &ts);
- EXPECT_EQ(0, ts.tv_sec);
- EXPECT_EQ(0, ts.tv_nsec);
-}
-
-class IoDevSetFormatTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- ResetStubData();
- sample_rates_[0] = 44100;
- sample_rates_[1] = 48000;
- sample_rates_[2] = 0;
-
- channel_counts_[0] = 2;
- channel_counts_[1] = 0;
- channel_counts_[2] = 0;
-
- pcm_formats_[0] = SND_PCM_FORMAT_S16_LE;
- pcm_formats_[1] = SND_PCM_FORMAT_S32_LE;
- pcm_formats_[2] = static_cast<snd_pcm_format_t>(0);
-
- update_channel_layout_called = 0;
- update_channel_layout_return_val = 0;
-
- memset(&iodev_, 0, sizeof(iodev_));
- iodev_.update_channel_layout = update_channel_layout;
- iodev_.supported_rates = sample_rates_;
- iodev_.supported_channel_counts = channel_counts_;
- iodev_.supported_formats = pcm_formats_;
- iodev_.dsp_context = NULL;
-
- cras_audio_format_set_channel_layout_called = 0;
-
- main_log = main_thread_event_log_init();
- }
-
- virtual void TearDown() {
- cras_iodev_free_format(&iodev_);
- main_thread_event_log_deinit(main_log);
- }
-
- struct cras_iodev iodev_;
- size_t sample_rates_[3];
- size_t channel_counts_[3];
- snd_pcm_format_t pcm_formats_[3];
-};
-
-TEST_F(IoDevSetFormatTestSuite, SupportedFormatSecondary) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev_.direction = CRAS_STREAM_OUTPUT;
- ResetStubData();
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
- EXPECT_EQ(dsp_context_new_sample_rate, 48000);
- EXPECT_STREQ(dsp_context_new_purpose, "playback");
-}
-
-TEST_F(IoDevSetFormatTestSuite, SupportedFormat32bit) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S32_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev_.direction = CRAS_STREAM_OUTPUT;
- ResetStubData();
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S32_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
- EXPECT_EQ(dsp_context_new_sample_rate, 48000);
- EXPECT_STREQ(dsp_context_new_purpose, "playback");
-}
-
-TEST_F(IoDevSetFormatTestSuite, SupportedFormatPrimary) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 44100;
- fmt.num_channels = 2;
- iodev_.direction = CRAS_STREAM_INPUT;
- ResetStubData();
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(44100, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
- EXPECT_EQ(dsp_context_new_sample_rate, 44100);
- EXPECT_STREQ(dsp_context_new_purpose, "capture");
-}
-
-TEST_F(IoDevSetFormatTestSuite, SupportedFormatDivisor) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 96000;
- fmt.num_channels = 2;
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
-}
-
-TEST_F(IoDevSetFormatTestSuite, Supported96k) {
- struct cras_audio_format fmt;
- int rc;
-
- sample_rates_[0] = 48000;
- sample_rates_[1] = 96000;
- sample_rates_[2] = 0;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 96000;
- fmt.num_channels = 2;
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(96000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
-}
-
-TEST_F(IoDevSetFormatTestSuite, LimitLowRate) {
- struct cras_audio_format fmt;
- int rc;
-
- sample_rates_[0] = 48000;
- sample_rates_[1] = 8000;
- sample_rates_[2] = 0;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 8000;
- fmt.num_channels = 2;
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
-}
-
-TEST_F(IoDevSetFormatTestSuite, UnsupportedChannelCount) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 96000;
- fmt.num_channels = 1;
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
-}
-
-TEST_F(IoDevSetFormatTestSuite, SupportedFormatFallbackDefault) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 96008;
- fmt.num_channels = 2;
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(44100, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
-}
-
-TEST_F(IoDevSetFormatTestSuite, UpdateChannelLayoutSuccess) {
- struct cras_audio_format fmt;
- int rc;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 6;
-
- iodev_.supported_channel_counts[0] = 6;
- iodev_.supported_channel_counts[1] = 2;
-
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(6, iodev_.format->num_channels);
-}
-
-TEST_F(IoDevSetFormatTestSuite, UpdateChannelLayoutFail) {
- static const int8_t stereo_layout[] = {0, 1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1};
- struct cras_audio_format fmt;
- int rc, i;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
-
- cras_dsp_context_new_return = reinterpret_cast<cras_dsp_context*>(0xf0f);
-
- update_channel_layout_return_val = -1;
- iodev_.supported_channel_counts[0] = 6;
- iodev_.supported_channel_counts[1] = 2;
-
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(2, iodev_.format->num_channels);
- EXPECT_EQ(0, dsp_context_free_called);
- for (i = 0; i < CRAS_CH_MAX; i++)
- EXPECT_EQ(iodev_.format->channel_layout[i], stereo_layout[i]);
-}
-
-TEST_F(IoDevSetFormatTestSuite, UpdateChannelLayoutFail6ch) {
- static const int8_t default_6ch_layout[] = {0, 1, 2, 3, 4, 5,
- -1, -1, -1, -1, -1};
- struct cras_audio_format fmt;
- int rc, i;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 6;
-
- cras_dsp_context_new_return = reinterpret_cast<cras_dsp_context*>(0xf0f);
-
- update_channel_layout_return_val = -1;
- iodev_.supported_channel_counts[0] = 6;
- iodev_.supported_channel_counts[1] = 2;
-
- rc = cras_iodev_set_format(&iodev_, &fmt);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, iodev_.format->format);
- EXPECT_EQ(48000, iodev_.format->frame_rate);
- EXPECT_EQ(6, iodev_.format->num_channels);
- EXPECT_EQ(0, dsp_context_free_called);
- for (i = 0; i < CRAS_CH_MAX; i++)
- EXPECT_EQ(iodev_.format->channel_layout[i], default_6ch_layout[i]);
-}
-
-// Put buffer tests
-
-static int get_buffer(cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned int* num) {
- size_t sz = sizeof(*audio_area) + sizeof(struct cras_channel_area) * 2;
-
- audio_area = (cras_audio_area*)calloc(1, sz);
- audio_area->frames = *num;
- audio_area->num_channels = 2;
- audio_area->channels[0].buf = audio_buffer;
- channel_area_set_channel(&audio_area->channels[0], CRAS_CH_FL);
- audio_area->channels[0].step_bytes = 4;
- audio_area->channels[1].buf = audio_buffer + 2;
- channel_area_set_channel(&audio_area->channels[1], CRAS_CH_FR);
- audio_area->channels[1].step_bytes = 4;
-
- *area = audio_area;
- return 0;
-}
-
-static int put_buffer(struct cras_iodev* iodev, unsigned int nframes) {
- put_buffer_nframes = nframes;
- if (audio_area) {
- free(audio_area);
- audio_area = NULL;
- }
- return 0;
-}
-
-static int no_stream(struct cras_iodev* odev, int enable) {
- no_stream_called++;
- no_stream_enable = enable;
- // Use default no stream playback to test default behavior.
- return cras_iodev_default_no_stream_playback(odev, enable);
-}
-
-static int is_free_running(const struct cras_iodev* odev) {
- return is_free_running_ret;
-}
-
-static int pre_dsp_hook(const uint8_t* frames,
- unsigned int nframes,
- const struct cras_audio_format* fmt,
- void* cb_data) {
- pre_dsp_hook_called++;
- pre_dsp_hook_frames = frames;
- pre_dsp_hook_cb_data = cb_data;
- return 0;
-}
-
-static int post_dsp_hook(const uint8_t* frames,
- unsigned int nframes,
- const struct cras_audio_format* fmt,
- void* cb_data) {
- post_dsp_hook_called++;
- post_dsp_hook_frames = frames;
- post_dsp_hook_cb_data = cb_data;
- return 0;
-}
-
-static int loopback_hook_control(bool start, void* cb_data) {
- return 0;
-}
-
-TEST(IoDevPutOutputBuffer, SystemMuted) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- cras_system_get_mute_return = 1;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 20, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(20, cras_mix_mute_count);
- EXPECT_EQ(20, put_buffer_nframes);
- EXPECT_EQ(20, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDevPutOutputBuffer, MuteForVolume) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
-
- iodev.nodes = &ionode;
- iodev.active_node = &ionode;
- iodev.active_node->dev = &iodev;
-
- // Case: System volume 100; Node volume 0. => Mute
- cras_system_get_volume_return = 100;
- iodev.active_node->volume = 0;
- EXPECT_EQ(1, cras_iodev_is_zero_volume(&iodev));
-
- // Case: System volume 100; Node volume 50. => Not mute
- cras_system_get_volume_return = 100;
- iodev.active_node->volume = 50;
- EXPECT_EQ(0, cras_iodev_is_zero_volume(&iodev));
-
- // Case: System volume 0; Node volume 50. => Mute
- cras_system_get_volume_return = 0;
- iodev.active_node->volume = 50;
- EXPECT_EQ(1, cras_iodev_is_zero_volume(&iodev));
-
- // Case: System volume 50; Node volume 50. => Mute
- cras_system_get_volume_return = 50;
- iodev.active_node->volume = 50;
- EXPECT_EQ(1, cras_iodev_is_zero_volume(&iodev));
-}
-
-TEST(IoDevPutOutputBuffer, NodeVolumeZeroShouldMute) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- struct cras_ionode ionode;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
-
- iodev.nodes = &ionode;
- iodev.active_node = &ionode;
- iodev.active_node->dev = &iodev;
- iodev.active_node->volume = 0;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 20, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(20, cras_mix_mute_count);
- EXPECT_EQ(20, put_buffer_nframes);
- EXPECT_EQ(20, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDevPutOutputBuffer, SystemMutedWithRamp) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- cras_system_get_mute_return = 1;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
-
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- // Assume ramping is done.
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_NONE;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 20, NULL, nullptr);
- // Output should be muted.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(20, cras_mix_mute_count);
- EXPECT_EQ(20, put_buffer_nframes);
- EXPECT_EQ(20, rate_estimator_add_frames_num_frames);
-
- // Test for the case where ramping is not done yet.
- ResetStubData();
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_PARTIAL;
- rc = cras_iodev_put_output_buffer(&iodev, frames, 20, NULL, nullptr);
-
- // Output should not be muted.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- // Ramped frames should be increased by 20.
- EXPECT_EQ(20, cras_ramp_update_ramped_frames_num_frames);
- EXPECT_EQ(20, put_buffer_nframes);
- EXPECT_EQ(20, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDevPutOutputBuffer, NodeVolumeZeroShouldMuteWithRamp) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- struct cras_ionode ionode;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
-
- iodev.nodes = &ionode;
- iodev.active_node = &ionode;
- iodev.active_node->dev = &iodev;
- iodev.active_node->volume = 0;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
-
- // Assume ramping is done.
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_NONE;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 20, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(20, cras_mix_mute_count);
- EXPECT_EQ(20, put_buffer_nframes);
- EXPECT_EQ(20, rate_estimator_add_frames_num_frames);
-
- // Test for the case where ramping is not done yet.
- ResetStubData();
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_PARTIAL;
- rc = cras_iodev_put_output_buffer(&iodev, frames, 20, NULL, nullptr);
-
- // Output should not be muted.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- // Ramped frames should be increased by 20.
- EXPECT_EQ(20, cras_ramp_update_ramped_frames_num_frames);
- EXPECT_EQ(20, put_buffer_nframes);
- EXPECT_EQ(20, rate_estimator_add_frames_num_frames);
-}
-TEST(IoDevPutOutputBuffer, NoDSP) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- struct cras_ionode ionode;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
-
- iodev.nodes = &ionode;
- iodev.active_node = &ionode;
- iodev.active_node->dev = &iodev;
- iodev.active_node->volume = 100;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 22, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- EXPECT_EQ(22, put_buffer_nframes);
- EXPECT_EQ(22, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDevPutOutputBuffer, DSP) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
- struct cras_loopback pre_dsp;
- struct cras_loopback post_dsp;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.dsp_context = reinterpret_cast<cras_dsp_context*>(0x15);
- cras_dsp_get_pipeline_ret = 0x25;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
- pre_dsp.type = LOOPBACK_POST_MIX_PRE_DSP;
- pre_dsp.hook_data = pre_dsp_hook;
- pre_dsp.hook_control = loopback_hook_control;
- pre_dsp.cb_data = (void*)0x1234;
- DL_APPEND(iodev.loopbacks, &pre_dsp);
- post_dsp.type = LOOPBACK_POST_DSP;
- post_dsp.hook_data = post_dsp_hook;
- post_dsp.hook_control = loopback_hook_control;
- post_dsp.cb_data = (void*)0x5678;
- DL_APPEND(iodev.loopbacks, &post_dsp);
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 32, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- EXPECT_EQ(1, pre_dsp_hook_called);
- EXPECT_EQ(frames, pre_dsp_hook_frames);
- EXPECT_EQ((void*)0x1234, pre_dsp_hook_cb_data);
- EXPECT_EQ(1, post_dsp_hook_called);
- EXPECT_EQ((void*)0x5678, post_dsp_hook_cb_data);
- EXPECT_EQ(32, put_buffer_nframes);
- EXPECT_EQ(32, rate_estimator_add_frames_num_frames);
- EXPECT_EQ(32, cras_dsp_pipeline_apply_sample_count);
- EXPECT_EQ(cras_dsp_get_pipeline_called, cras_dsp_put_pipeline_called);
-}
-
-TEST(IoDevPutOutputBuffer, SoftVol) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.software_volume_needed = 1;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- cras_system_get_volume_return = 13;
- softvol_scalers[13] = 0.435;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 53, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- EXPECT_EQ(53, put_buffer_nframes);
- EXPECT_EQ(53, rate_estimator_add_frames_num_frames);
- EXPECT_EQ(softvol_scalers[13], cras_scale_buffer_scaler);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, cras_scale_buffer_fmt);
-}
-
-TEST(IoDevPutOutputBuffer, SoftVolWithRamp) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
- int n_frames = 53;
- float ramp_scaler = 0.2;
- float increment = 0.001;
- float target = 1.0;
- int volume = 13;
- float volume_scaler = 0.435;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.software_volume_needed = 1;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- // Assume ramping is done.
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_NONE;
-
- cras_system_get_volume_return = volume;
- softvol_scalers[volume] = volume_scaler;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, n_frames, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- EXPECT_EQ(n_frames, put_buffer_nframes);
- EXPECT_EQ(n_frames, rate_estimator_add_frames_num_frames);
- EXPECT_EQ(softvol_scalers[volume], cras_scale_buffer_scaler);
- EXPECT_EQ(SND_PCM_FORMAT_S16_LE, cras_scale_buffer_fmt);
-
- ResetStubData();
- // Assume ramping is not done.
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_PARTIAL;
- cras_ramp_get_current_action_ret.scaler = ramp_scaler;
- cras_ramp_get_current_action_ret.increment = increment;
- cras_ramp_get_current_action_ret.target = target;
-
- cras_system_get_volume_return = volume;
- softvol_scalers[volume] = volume_scaler;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, n_frames, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- // cras_scale_buffer is not called.
- EXPECT_EQ(0, cras_scale_buffer_called);
-
- // Verify the arguments passed to cras_scale_buffer_increment.
- EXPECT_EQ(fmt.format, cras_scale_buffer_increment_fmt);
- EXPECT_EQ(frames, cras_scale_buffer_increment_buff);
- EXPECT_EQ(n_frames, cras_scale_buffer_increment_frame);
- // Initial scaler will be product of software volume scaler and
- // ramp scaler.
- EXPECT_FLOAT_EQ(softvol_scalers[volume] * ramp_scaler,
- cras_scale_buffer_increment_scaler);
- // Increment scaler will be product of software volume scaler and
- // ramp increment.
- EXPECT_FLOAT_EQ(softvol_scalers[volume] * increment,
- cras_scale_buffer_increment_increment);
- EXPECT_FLOAT_EQ(softvol_scalers[volume] * target,
- cras_scale_buffer_increment_target);
- EXPECT_EQ(fmt.num_channels, cras_scale_buffer_increment_channel);
-
- EXPECT_EQ(n_frames, put_buffer_nframes);
- EXPECT_EQ(n_frames, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDevPutOutputBuffer, NoSoftVolWithRamp) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
- int n_frames = 53;
- float ramp_scaler = 0.2;
- float increment = 0.001;
- float target = 1.0;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.software_volume_needed = 0;
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- // Assume ramping is done.
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_NONE;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, n_frames, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- // cras_scale_buffer is not called.
- EXPECT_EQ(0, cras_scale_buffer_called);
- EXPECT_EQ(n_frames, put_buffer_nframes);
- EXPECT_EQ(n_frames, rate_estimator_add_frames_num_frames);
-
- ResetStubData();
- // Assume ramping is not done.
- cras_ramp_get_current_action_ret.type = CRAS_RAMP_ACTION_PARTIAL;
- cras_ramp_get_current_action_ret.scaler = ramp_scaler;
- cras_ramp_get_current_action_ret.increment = increment;
- cras_ramp_get_current_action_ret.target = target;
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, n_frames, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- // cras_scale_buffer is not called.
- EXPECT_EQ(0, cras_scale_buffer_called);
-
- // Verify the arguments passed to cras_scale_buffer_increment.
- EXPECT_EQ(fmt.format, cras_scale_buffer_increment_fmt);
- EXPECT_EQ(frames, cras_scale_buffer_increment_buff);
- EXPECT_EQ(n_frames, cras_scale_buffer_increment_frame);
- EXPECT_FLOAT_EQ(ramp_scaler, cras_scale_buffer_increment_scaler);
- EXPECT_FLOAT_EQ(increment, cras_scale_buffer_increment_increment);
- EXPECT_FLOAT_EQ(1.0, cras_scale_buffer_increment_target);
- EXPECT_EQ(fmt.num_channels, cras_scale_buffer_increment_channel);
-
- EXPECT_EQ(n_frames, put_buffer_nframes);
- EXPECT_EQ(n_frames, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDevPutOutputBuffer, Scale32Bit) {
- struct cras_audio_format fmt;
- struct cras_iodev iodev;
- uint8_t* frames = reinterpret_cast<uint8_t*>(0x44);
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.software_volume_needed = 1;
-
- cras_system_get_volume_return = 13;
- softvol_scalers[13] = 0.435;
-
- fmt.format = SND_PCM_FORMAT_S32_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.put_buffer = put_buffer;
- iodev.rate_est = reinterpret_cast<struct rate_estimator*>(0xdeadbeef);
-
- rc = cras_iodev_put_output_buffer(&iodev, frames, 53, NULL, nullptr);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_mix_mute_count);
- EXPECT_EQ(53, put_buffer_nframes);
- EXPECT_EQ(53, rate_estimator_add_frames_num_frames);
- EXPECT_EQ(SND_PCM_FORMAT_S32_LE, cras_scale_buffer_fmt);
-}
-
-// frames queued/avail tests
-
-static unsigned fr_queued = 0;
-
-static int frames_queued(const struct cras_iodev* iodev,
- struct timespec* tstamp) {
- clock_gettime(CLOCK_MONOTONIC_RAW, tstamp);
- return fr_queued;
-}
-
-TEST(IoDevQueuedBuffer, ZeroMinBufferLevel) {
- struct cras_iodev iodev;
- struct timespec tstamp;
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.frames_queued = frames_queued;
- iodev.min_buffer_level = 0;
- iodev.buffer_size = 200;
- fr_queued = 50;
-
- rc = cras_iodev_frames_queued(&iodev, &tstamp);
- EXPECT_EQ(50, rc);
- rc = cras_iodev_buffer_avail(&iodev, rc);
- EXPECT_EQ(150, rc);
-}
-
-TEST(IoDevQueuedBuffer, NonZeroMinBufferLevel) {
- struct cras_iodev iodev;
- struct timespec hw_tstamp;
- int rc;
-
- ResetStubData();
- memset(&iodev, 0, sizeof(iodev));
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.frames_queued = frames_queued;
- iodev.min_buffer_level = 100;
- iodev.buffer_size = 200;
- fr_queued = 180;
-
- rc = cras_iodev_frames_queued(&iodev, &hw_tstamp);
- EXPECT_EQ(80, rc);
- rc = cras_iodev_buffer_avail(&iodev, rc);
- EXPECT_EQ(20, rc);
-
- /* When fr_queued < min_buffer_level*/
- fr_queued = 80;
- rc = cras_iodev_frames_queued(&iodev, &hw_tstamp);
- EXPECT_EQ(0, rc);
- rc = cras_iodev_buffer_avail(&iodev, rc);
- EXPECT_EQ(100, rc);
-}
-
-static void update_active_node(struct cras_iodev* iodev,
- unsigned node_idx,
- unsigned dev_enabled) {}
-
-static void dev_set_mute(struct cras_iodev* iodev) {
- set_mute_called++;
-}
-
-TEST(IoNodePlug, PlugUnplugNode) {
- struct cras_iodev iodev;
- struct cras_ionode ionode, ionode2;
-
- main_log = main_thread_event_log_init();
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- memset(&ionode2, 0, sizeof(ionode2));
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.update_active_node = update_active_node;
- ionode.dev = &iodev;
- cras_iodev_add_node(&iodev, &ionode);
- ionode2.dev = &iodev;
- cras_iodev_add_node(&iodev, &ionode2);
- cras_iodev_set_active_node(&iodev, &ionode);
- ResetStubData();
- cras_iodev_set_node_plugged(&ionode, 1);
- EXPECT_EQ(0, cras_iodev_list_disable_dev_called);
- cras_iodev_set_node_plugged(&ionode, 0);
- EXPECT_EQ(1, cras_iodev_list_disable_dev_called);
-
- /* Unplug non-active node shouldn't disable iodev. */
- cras_iodev_set_node_plugged(&ionode2, 1);
- EXPECT_EQ(1, cras_iodev_list_disable_dev_called);
- cras_iodev_set_node_plugged(&ionode2, 0);
- EXPECT_EQ(1, cras_iodev_list_disable_dev_called);
- main_thread_event_log_deinit(main_log);
-}
-
-TEST(IoDev, AddRemoveNode) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- ResetStubData();
- EXPECT_EQ(0, notify_nodes_changed_called);
- cras_iodev_add_node(&iodev, &ionode);
- EXPECT_EQ(1, notify_nodes_changed_called);
- cras_iodev_rm_node(&iodev, &ionode);
- EXPECT_EQ(2, notify_nodes_changed_called);
-}
-
-TEST(IoDev, SetActiveNode) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- ResetStubData();
- EXPECT_EQ(0, notify_active_node_changed_called);
- cras_iodev_set_active_node(&iodev, &ionode);
- EXPECT_EQ(1, notify_active_node_changed_called);
-}
-
-TEST(IoDev, SetMute) {
- struct cras_iodev iodev;
- int rc;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.set_mute = dev_set_mute;
- iodev.state = CRAS_IODEV_STATE_CLOSE;
-
- ResetStubData();
- rc = cras_iodev_set_mute(&iodev);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, set_mute_called);
-
- iodev.state = CRAS_IODEV_STATE_OPEN;
- rc = cras_iodev_set_mute(&iodev);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, set_mute_called);
-}
-
-// Test software volume changes for default output.
-TEST(IoDev, SoftwareVolume) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- ResetStubData();
-
- iodev.nodes = &ionode;
- iodev.active_node = &ionode;
- iodev.active_node->dev = &iodev;
-
- iodev.active_node->volume = 100;
- iodev.software_volume_needed = 0;
-
- softvol_scalers[80] = 0.5;
- softvol_scalers[70] = 0.3;
-
- // Check that system volume changes software volume if needed.
- cras_system_get_volume_return = 80;
- // system_volume - 100 + node_volume = 80 - 100 + 100 = 80
- EXPECT_FLOAT_EQ(0.5, cras_iodev_get_software_volume_scaler(&iodev));
-
- // Check that node volume changes software volume if needed.
- iodev.active_node->volume = 90;
- // system_volume - 100 + node_volume = 80 - 100 + 90 = 70
- EXPECT_FLOAT_EQ(0.3, cras_iodev_get_software_volume_scaler(&iodev));
-}
-
-// Test software gain scaler.
-TEST(IoDev, SoftwareGain) {
- struct cras_iodev iodev;
- struct cras_ionode ionode;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&ionode, 0, sizeof(ionode));
- ResetStubData();
-
- iodev.nodes = &ionode;
- iodev.active_node = &ionode;
- iodev.active_node->dev = &iodev;
-
- ionode.capture_gain = 2400;
- ionode.software_volume_needed = 1;
-
- // 2400 * 0.01 dB is 15.848931
- EXPECT_FLOAT_EQ(15.848931, cras_iodev_get_software_gain_scaler(&iodev));
-
- // Software gain scaler should be 1.0 if software gain is not needed.
- ionode.software_volume_needed = 0;
- EXPECT_FLOAT_EQ(1.0, cras_iodev_get_software_gain_scaler(&iodev));
-}
-
-// This get_buffer implementation set returned frames larger than requested
-// frames.
-static int bad_get_buffer(struct cras_iodev* iodev,
- struct cras_audio_area** area,
- unsigned* frames) {
- *frames = *frames + 1;
- return 0;
-}
-
-// Check that if get_buffer implementation returns invalid frames,
-// cras_iodev_get_output_buffer and cras_iodev_get_input_buffer can return
-// error.
-TEST(IoDev, GetBufferInvalidFrames) {
- struct cras_iodev iodev;
- struct cras_audio_area** area = NULL;
- unsigned int frames = 512;
- struct cras_audio_format fmt;
-
- // Format is used in cras_iodev_get_input_buffer;
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
-
- memset(&iodev, 0, sizeof(iodev));
-
- ResetStubData();
-
- iodev.format = &fmt;
- iodev.get_buffer = bad_get_buffer;
-
- EXPECT_EQ(-EINVAL, cras_iodev_get_output_buffer(&iodev, area, &frames));
- EXPECT_EQ(-EINVAL, cras_iodev_get_input_buffer(&iodev, &frames));
-}
-
-static int configure_dev(struct cras_iodev* iodev) {
- iodev->buffer_size = iodev_buffer_size;
- return 0;
-}
-
-TEST(IoDev, OpenOutputDeviceNoStart) {
- struct cras_iodev iodev;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.format = &audio_fmt;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- ResetStubData();
-
- iodev.state = CRAS_IODEV_STATE_CLOSE;
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, 240, &audio_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
- EXPECT_EQ(240, iodev.min_cb_level);
-
- // Test that state is no stream run when there is no start ops.
- EXPECT_EQ(CRAS_IODEV_STATE_NO_STREAM_RUN, iodev.state);
-}
-
-TEST(IoDev, OpenOutputDeviceWithLowRateFmt) {
- struct cras_iodev iodev;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.format = &audio_fmt;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- ResetStubData();
-
- cras_audio_format low_rate_fmt = audio_fmt;
- low_rate_fmt.frame_rate = 8000;
- iodev.state = CRAS_IODEV_STATE_CLOSE;
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, 40, &low_rate_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
-
- // Test that iodev min_cb_level should be set to
- // 40 * 48000 / 8000 = 240
- EXPECT_EQ(240, iodev.min_cb_level);
-}
-
-int fake_start(const struct cras_iodev* iodev) {
- return 0;
-}
-
-TEST(IoDev, OpenOutputDeviceWithStart) {
- struct cras_iodev iodev;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.format = &audio_fmt;
- ResetStubData();
-
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- iodev.start = fake_start;
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, 240, &audio_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
- EXPECT_EQ(240, iodev.min_cb_level);
-
- // Test that state is no stream run when there is start ops.
- EXPECT_EQ(CRAS_IODEV_STATE_OPEN, iodev.state);
-}
-
-TEST(IoDev, OpenInputDeviceNoStart) {
- struct cras_iodev iodev;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.format = &audio_fmt;
- ResetStubData();
-
- iodev.state = CRAS_IODEV_STATE_CLOSE;
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, 240, &audio_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
- EXPECT_EQ(240, iodev.min_cb_level);
-
- // Test that state is normal run when there is start ops.
- EXPECT_EQ(CRAS_IODEV_STATE_NORMAL_RUN, iodev.state);
-}
-
-TEST(IoDev, OpenInputDeviceWithStart) {
- struct cras_iodev iodev;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.format = &audio_fmt;
- ResetStubData();
-
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- iodev.start = fake_start;
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, 240, &audio_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
- EXPECT_EQ(240, iodev.min_cb_level);
-
- // Test that state is normal run even if there is start ops.
- EXPECT_EQ(CRAS_IODEV_STATE_NORMAL_RUN, iodev.state);
-}
-
-TEST(IoDev, OpenInputDeviceWithLowRateFmt) {
- struct cras_iodev iodev;
-
- memset(&iodev, 0, sizeof(iodev));
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.format = &audio_fmt;
- ResetStubData();
-
- cras_audio_format low_rate_fmt = audio_fmt;
- low_rate_fmt.frame_rate = 8000;
- iodev.state = CRAS_IODEV_STATE_CLOSE;
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, 40, &low_rate_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
-
- // Test that iodev min_cb_level should be set to
- // 40 * 48000 / 8000 = 240
- EXPECT_EQ(240, iodev.min_cb_level);
-}
-
-static int simple_no_stream(struct cras_iodev* dev, int enable) {
- simple_no_stream_enable = enable;
- simple_no_stream_called++;
- return 0;
-}
-
-TEST(IoDev, AddRmStream) {
- struct cras_iodev iodev;
- struct cras_rstream rstream1, rstream2;
- struct dev_stream stream1, stream2;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&rstream1, 0, sizeof(rstream1));
- memset(&rstream2, 0, sizeof(rstream2));
- iodev.configure_dev = configure_dev;
- iodev.no_stream = simple_no_stream;
- iodev.format = &audio_fmt;
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- rstream1.cb_threshold = 800;
- stream1.stream = &rstream1;
- stream1.is_running = 0;
- rstream2.cb_threshold = 400;
- stream2.stream = &rstream2;
- stream2.is_running = 0;
- ResetStubData();
-
- iodev_buffer_size = 1024;
- cras_iodev_open(&iodev, rstream1.cb_threshold, &audio_fmt);
- EXPECT_EQ(0, iodev.max_cb_level);
- EXPECT_EQ(512, iodev.min_cb_level);
-
- /* min_cb_level should not exceed half the buffer size. */
- cras_iodev_add_stream(&iodev, &stream1);
- cras_iodev_start_stream(&iodev, &stream1);
- EXPECT_EQ(800, iodev.max_cb_level);
- EXPECT_EQ(512, iodev.min_cb_level);
- EXPECT_EQ(1, buffer_share_add_id_called);
-
- cras_iodev_add_stream(&iodev, &stream2);
- cras_iodev_start_stream(&iodev, &stream2);
- EXPECT_EQ(800, iodev.max_cb_level);
- EXPECT_EQ(400, iodev.min_cb_level);
- EXPECT_EQ(2, buffer_share_add_id_called);
-
- cras_iodev_rm_stream(&iodev, &rstream1);
- EXPECT_EQ(400, iodev.max_cb_level);
- EXPECT_EQ(400, iodev.min_cb_level);
- EXPECT_EQ(0, simple_no_stream_called);
-
- /* When all streams are removed, keep the last min_cb_level for draining. */
- cras_iodev_rm_stream(&iodev, &rstream2);
- EXPECT_EQ(0, iodev.max_cb_level);
- EXPECT_EQ(512, iodev.min_cb_level);
-}
-
-TEST(IoDev, RmStreamUpdateFetchTime) {
- struct cras_iodev iodev;
- struct cras_rstream rstream1, rstream2, rstream3;
- struct dev_stream stream1, stream2, stream3;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&rstream1, 0, sizeof(rstream1));
- memset(&rstream2, 0, sizeof(rstream2));
- memset(&rstream3, 0, sizeof(rstream2));
- memset(&stream1, 0, sizeof(stream2));
- memset(&stream2, 0, sizeof(stream2));
- memset(&stream3, 0, sizeof(stream2));
- iodev.configure_dev = configure_dev;
- iodev.no_stream = simple_no_stream;
- iodev.format = &audio_fmt;
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- rstream1.direction = CRAS_STREAM_OUTPUT;
- rstream2.direction = CRAS_STREAM_OUTPUT;
- rstream3.direction = CRAS_STREAM_OUTPUT;
- stream1.stream = &rstream1;
- stream2.stream = &rstream2;
- stream3.stream = &rstream3;
- ResetStubData();
-
- cras_iodev_open(&iodev, 1024, &audio_fmt);
-
- cras_iodev_add_stream(&iodev, &stream1);
- cras_iodev_start_stream(&iodev, &stream1);
- cras_iodev_add_stream(&iodev, &stream2);
- cras_iodev_start_stream(&iodev, &stream2);
- cras_iodev_add_stream(&iodev, &stream3);
-
- rstream1.next_cb_ts.tv_sec = 2;
- rstream1.next_cb_ts.tv_nsec = 0;
- rstream2.next_cb_ts.tv_sec = 1;
- rstream2.next_cb_ts.tv_nsec = 0;
- rstream3.next_cb_ts.tv_sec = 1;
- rstream3.next_cb_ts.tv_nsec = 0;
-
- /*
- * Because rstream3 has not started yet, the next_cb_ts will be change to the
- * earliest fetch time of remaining streams, which is rstream1.
- */
- cras_iodev_rm_stream(&iodev, &rstream2);
-
- EXPECT_EQ(rstream3.next_cb_ts.tv_sec, rstream1.next_cb_ts.tv_sec);
- EXPECT_EQ(rstream3.next_cb_ts.tv_nsec, rstream1.next_cb_ts.tv_nsec);
-}
-
-TEST(IoDev, StartStreams) {
- struct cras_iodev iodev1, iodev2;
- struct cras_rstream rstream1, rstream2;
- struct dev_stream stream1, stream2;
-
- memset(&iodev1, 0, sizeof(iodev1));
- memset(&iodev2, 0, sizeof(iodev2));
- memset(&rstream1, 0, sizeof(rstream1));
- memset(&rstream2, 0, sizeof(rstream2));
- memset(&stream1, 0, sizeof(stream1));
- memset(&stream2, 0, sizeof(stream2));
- iodev1.configure_dev = configure_dev;
- iodev1.format = &audio_fmt;
- iodev1.state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev1.get_buffer = get_buffer;
- iodev1.put_buffer = put_buffer;
- iodev2.configure_dev = configure_dev;
- iodev2.format = &audio_fmt;
- iodev2.state = CRAS_IODEV_STATE_NORMAL_RUN;
- rstream1.direction = CRAS_STREAM_INPUT;
- rstream2.direction = CRAS_STREAM_OUTPUT;
- stream1.stream = &rstream1;
- stream2.stream = &rstream2;
-
- /* An input stream starts running immediately. */
- ResetStubData();
- iodev1.direction = CRAS_STREAM_INPUT;
- cras_iodev_open(&iodev1, 1024, &audio_fmt);
- cras_iodev_add_stream(&iodev1, &stream1);
- EXPECT_EQ(1, dev_stream_is_running(&stream1));
- EXPECT_EQ(1, buffer_share_add_id_called);
-
- /* An output stream starts running after its first fetch. */
- ResetStubData();
- iodev2.direction = CRAS_STREAM_OUTPUT;
- cras_iodev_open(&iodev2, 1024, &audio_fmt);
- cras_iodev_add_stream(&iodev2, &stream2);
- EXPECT_EQ(0, dev_stream_is_running(&stream2));
- EXPECT_EQ(0, buffer_share_add_id_called);
-}
-
-TEST(IoDev, TriggerOnlyStreamNoBufferShare) {
- struct cras_iodev iodev;
- struct cras_rstream rstream;
- struct dev_stream stream;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&rstream, 0, sizeof(rstream));
- iodev.configure_dev = configure_dev;
- iodev.format = &audio_fmt;
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- rstream.cb_threshold = 800;
- rstream.flags = TRIGGER_ONLY;
- stream.stream = &rstream;
- ResetStubData();
-
- cras_iodev_open(&iodev, rstream.cb_threshold, &audio_fmt);
- /* TRIGGER_ONLY streams shall not be added to buffer_share. */
- cras_iodev_add_stream(&iodev, &stream);
- EXPECT_EQ(0, buffer_share_add_id_called);
-}
-
-TEST(IoDev, FillZeros) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- unsigned int frames = 50;
- int16_t* zeros;
- int rc;
-
- ResetStubData();
-
- memset(&iodev, 0, sizeof(iodev));
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
-
- iodev.direction = CRAS_STREAM_INPUT;
- rc = cras_iodev_fill_odev_zeros(&iodev, frames);
- EXPECT_EQ(-EINVAL, rc);
-
- iodev.direction = CRAS_STREAM_OUTPUT;
- rc = cras_iodev_fill_odev_zeros(&iodev, frames);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(frames, put_buffer_nframes);
- zeros = (int16_t*)calloc(frames * 2, sizeof(*zeros));
- rc = memcmp(audio_buffer, zeros, frames * 2 * 2);
- free(zeros);
- EXPECT_EQ(0, rc);
-}
-
-TEST(IoDev, DefaultNoStreamPlaybackRunning) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- unsigned int hw_level = 50;
- unsigned int min_cb_level = 240;
- unsigned int zeros_to_fill;
- int16_t* zeros;
- int rc;
-
- memset(&iodev, 0, sizeof(iodev));
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.min_cb_level = min_cb_level;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- iodev.frames_queued = frames_queued;
- iodev.min_buffer_level = 0;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.buffer_size = BUFFER_SIZE;
- iodev.no_stream = no_stream;
-
- ResetStubData();
-
- // Device is running. hw_level is less than target.
- // Need to fill to callback level * 2;
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- fr_queued = hw_level;
- zeros_to_fill = min_cb_level * 2 - hw_level;
-
- rc = cras_iodev_default_no_stream_playback(&iodev, 1);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_IODEV_STATE_NO_STREAM_RUN, iodev.state);
- EXPECT_EQ(zeros_to_fill, put_buffer_nframes);
- zeros = (int16_t*)calloc(zeros_to_fill * 2, sizeof(*zeros));
- EXPECT_EQ(0, memcmp(audio_buffer, zeros, zeros_to_fill * 2 * 2));
- free(zeros);
-
- ResetStubData();
-
- // Device is running. hw_level is not less than target.
- // No need to fill zeros.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- hw_level = min_cb_level * 2;
- fr_queued = hw_level;
- zeros_to_fill = 0;
-
- rc = cras_iodev_default_no_stream_playback(&iodev, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_IODEV_STATE_NO_STREAM_RUN, iodev.state);
- EXPECT_EQ(zeros_to_fill, put_buffer_nframes);
-}
-
-TEST(IoDev, PrepareOutputBeforeWriteSamples) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- unsigned int min_cb_level = 240;
- int rc;
- struct cras_rstream rstream1;
- struct dev_stream stream1;
- struct cras_iodev_info info;
-
- memset(&info, 0, sizeof(info));
-
- ResetStubData();
-
- rstream1.cb_threshold = min_cb_level;
- stream1.stream = &rstream1;
- stream1.is_running = 1;
-
- memset(&iodev, 0, sizeof(iodev));
-
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.format = &fmt;
- iodev.min_cb_level = min_cb_level;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- iodev.frames_queued = frames_queued;
- iodev.min_buffer_level = 0;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.buffer_size = BUFFER_SIZE;
- iodev.no_stream = no_stream;
- iodev.configure_dev = configure_dev;
- iodev.start = fake_start;
- iodev.info = info;
- iodev_buffer_size = BUFFER_SIZE;
-
- // Open device.
- cras_iodev_open(&iodev, rstream1.cb_threshold, &fmt);
-
- // Add one stream to device.
- cras_iodev_add_stream(&iodev, &stream1);
-
- // Case 1: Assume device is not started yet.
- iodev.state = CRAS_IODEV_STATE_OPEN;
- // Assume sample is not ready yet.
- dev_stream_playback_frames_ret = 0;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- EXPECT_EQ(0, rc);
- // Device should remain in open state.
- EXPECT_EQ(CRAS_IODEV_STATE_OPEN, iodev.state);
- EXPECT_EQ(0, no_stream_called);
-
- // Assume now sample is ready.
- dev_stream_playback_frames_ret = 100;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- EXPECT_EQ(0, rc);
- // Device should enter normal run state.
- EXPECT_EQ(CRAS_IODEV_STATE_NORMAL_RUN, iodev.state);
- EXPECT_EQ(0, no_stream_called);
- // Need to fill 1 callback level of zeros;
- EXPECT_EQ(min_cb_level, put_buffer_nframes);
-
- ResetStubData();
-
- // Case 2: Assume device is started and is in no stream state.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Sample is not ready yet.
- dev_stream_playback_frames_ret = 0;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- EXPECT_EQ(0, rc);
- // Device should remain in no_stream state.
- EXPECT_EQ(CRAS_IODEV_STATE_NO_STREAM_RUN, iodev.state);
- // Device in no_stream state should call no_stream ops once.
- EXPECT_EQ(1, no_stream_called);
- EXPECT_EQ(1, no_stream_enable);
-
- // Assume now sample is ready.
- dev_stream_playback_frames_ret = 100;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- EXPECT_EQ(0, rc);
- // Device should enter normal run state.
- EXPECT_EQ(CRAS_IODEV_STATE_NORMAL_RUN, iodev.state);
- // Device should call no_stream ops with enable=0 to leave no stream state.
- EXPECT_EQ(2, no_stream_called);
- EXPECT_EQ(0, no_stream_enable);
-
- ResetStubData();
-
- // Case 3: Assume device is started and is in normal run state.
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- EXPECT_EQ(0, rc);
- // Device should remain in normal run state.
- EXPECT_EQ(CRAS_IODEV_STATE_NORMAL_RUN, iodev.state);
- // Device in no_stream state should call no_stream ops once.
- EXPECT_EQ(0, no_stream_called);
-
- ResetStubData();
-
- // Test for device with ramp. Device should start ramping
- // when sample is ready.
-
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
- iodev.initial_ramp_request = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
- // Case 4.1: Assume device with ramp is started and is in no stream state.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Assume sample is ready.
- dev_stream_playback_frames_ret = 100;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- // Device should start ramping up without setting mute callback.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(1, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(0.0, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_to);
- EXPECT_EQ(fmt.frame_rate * RAMP_NEW_STREAM_DURATION_SECS,
- cras_ramp_start_duration_frames);
- EXPECT_EQ(NULL, cras_ramp_start_cb);
- EXPECT_EQ(NULL, cras_ramp_start_cb_data);
-
- ResetStubData();
-
- // Case 4.2: Assume device with ramp is started and is in no stream state.
- // But system is muted.
- iodev.state = CRAS_IODEV_STATE_NO_STREAM_RUN;
- // Assume system is muted.
- cras_system_get_mute_return = 1;
- // Assume sample is ready.
- dev_stream_playback_frames_ret = 100;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- // Device should not start ramping up because system is muted.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_ramp_start_is_called);
-
- ResetStubData();
-
- // Case 5.1: Assume device with ramp is in open state.
- iodev.state = CRAS_IODEV_STATE_OPEN;
- // Assume sample is ready.
- dev_stream_playback_frames_ret = 100;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- // Device should start ramping up without setting mute callback.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(1, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(0.0, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_to);
- EXPECT_EQ(fmt.frame_rate * RAMP_NEW_STREAM_DURATION_SECS,
- cras_ramp_start_duration_frames);
- EXPECT_EQ(NULL, cras_ramp_start_cb);
- EXPECT_EQ(NULL, cras_ramp_start_cb_data);
-
- ResetStubData();
-
- // Case 5.2: Assume device with ramp is in open state. But system is muted.
- iodev.state = CRAS_IODEV_STATE_OPEN;
- // Assume system is muted.
- cras_system_get_mute_return = 1;
- // Assume sample is ready.
- dev_stream_playback_frames_ret = 100;
-
- rc = cras_iodev_prepare_output_before_write_samples(&iodev);
-
- // Device should not start ramping up because system is muted.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_ramp_start_is_called);
-}
-
-TEST(IoDev, StartRampUp) {
- struct cras_iodev iodev;
- int rc;
- struct cras_audio_format fmt;
- enum CRAS_IODEV_RAMP_REQUEST req;
- memset(&iodev, 0, sizeof(iodev));
-
- // Format will be used in cras_iodev_start_ramp to determine ramp duration.
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
-
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
-
- // Case 1: Device is not opened yet.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- req = CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE;
-
- rc = cras_iodev_start_ramp(&iodev, req);
-
- // Ramp request is ignored.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_ramp_start_is_called);
-
- // Case 2: Ramp up without mute.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_OPEN;
- req = CRAS_IODEV_RAMP_REQUEST_UP_START_PLAYBACK;
-
- rc = cras_iodev_start_ramp(&iodev, req);
-
- // Device should start ramping up without setting mute callback.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(1, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(0.0, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_to);
- EXPECT_EQ(fmt.frame_rate * RAMP_NEW_STREAM_DURATION_SECS,
- cras_ramp_start_duration_frames);
- EXPECT_EQ(NULL, cras_ramp_start_cb);
- EXPECT_EQ(NULL, cras_ramp_start_cb_data);
-
- // Case 3: Ramp up for unmute.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_OPEN;
- req = CRAS_IODEV_RAMP_REQUEST_UP_UNMUTE;
-
- rc = cras_iodev_start_ramp(&iodev, req);
-
- // Device should start ramping up.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(1, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(0.0, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_to);
- EXPECT_EQ(fmt.frame_rate * RAMP_UNMUTE_DURATION_SECS,
- cras_ramp_start_duration_frames);
- // Callback for unmute is not used.
- EXPECT_EQ(NULL, cras_ramp_start_cb);
- // Device mute state is set after ramping starts.
- EXPECT_EQ(1, cras_device_monitor_set_device_mute_state_called);
- EXPECT_EQ(iodev.info.idx, cras_device_monitor_set_device_mute_state_dev_idx);
-}
-
-TEST(IoDev, StartRampDown) {
- struct cras_iodev iodev;
- int rc;
- struct cras_audio_format fmt;
- enum CRAS_IODEV_RAMP_REQUEST req;
- memset(&iodev, 0, sizeof(iodev));
-
- // Format will be used in cras_iodev_start_ramp to determine ramp duration.
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
-
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
-
- // Case 1: Device is not opened yet.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- req = CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE;
-
- rc = cras_iodev_start_ramp(&iodev, req);
-
- // Ramp request is ignored.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_ramp_start_is_called);
-
- // Case 2: Ramp down for mute.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_OPEN;
- req = CRAS_IODEV_RAMP_REQUEST_DOWN_MUTE;
-
- rc = cras_iodev_start_ramp(&iodev, req);
-
- // Device should start ramping down with mute callback.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(1, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(0.0, cras_ramp_start_to);
- EXPECT_EQ(fmt.frame_rate * RAMP_MUTE_DURATION_SECS,
- cras_ramp_start_duration_frames);
-
- // Device mute state is not set yet. It should wait for ramp to finish.
- EXPECT_EQ(0, cras_device_monitor_set_device_mute_state_called);
-
- // Assume the callback is set, and it is later called after ramp is done.
- // It should trigger cras_device_monitor_set_device_mute_state.
- cras_ramp_start_cb(cras_ramp_start_cb_data);
- EXPECT_EQ(1, cras_device_monitor_set_device_mute_state_called);
- EXPECT_EQ(iodev.info.idx, cras_device_monitor_set_device_mute_state_dev_idx);
-}
-
-TEST(IoDev, StartVolumeRamp) {
- struct cras_ionode ionode;
- struct cras_iodev iodev;
- int rc;
- struct cras_audio_format fmt;
- int expected_frames;
- float ionode_softvol_scalers[101];
- memset(&iodev, 0, sizeof(iodev));
-
- // Format will be used in cras_iodev_start_ramp to determine ramp duration.
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- expected_frames = fmt.frame_rate * RAMP_VOLUME_CHANGE_DURATION_SECS;
-
- // Assume device has ramp member.
- iodev.ramp = reinterpret_cast<struct cras_ramp*>(0x1);
-
- // Case 1: Device is not opened yet.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- rc = cras_iodev_start_volume_ramp(&iodev, 30, 94);
-
- // Ramp request is ignored.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_ramp_start_is_called);
-
- // Case 2: Volumes are equal.
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_OPEN;
- rc = cras_iodev_start_volume_ramp(&iodev, 70, 70);
-
- // Ramp request is ignored.
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_ramp_start_is_called);
-
- // Case 3: Ramp up, global scalers
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_OPEN;
- softvol_scalers[40] = 0.2;
- softvol_scalers[60] = 0.8;
-
- rc = cras_iodev_start_volume_ramp(&iodev, 40, 60);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(0, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(0.25, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_to);
- EXPECT_EQ(expected_frames, cras_ramp_start_duration_frames);
- EXPECT_EQ(NULL, cras_ramp_start_cb);
- EXPECT_EQ(NULL, cras_ramp_start_cb_data);
-
- // Case 4: Ramp down, device saclers
- ResetStubData();
- iodev.state = CRAS_IODEV_STATE_OPEN;
-
- ionode_softvol_scalers[40] = 0.4;
- ionode_softvol_scalers[60] = 0.5;
- ionode.softvol_scalers = ionode_softvol_scalers;
- iodev.active_node = &ionode;
-
- rc = cras_iodev_start_volume_ramp(&iodev, 60, 40);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, cras_ramp_start_is_called);
- EXPECT_EQ(0, cras_ramp_start_mute_ramp);
- EXPECT_FLOAT_EQ(1.25, cras_ramp_start_from);
- EXPECT_FLOAT_EQ(1.0, cras_ramp_start_to);
- EXPECT_EQ(expected_frames, cras_ramp_start_duration_frames);
- EXPECT_EQ(NULL, cras_ramp_start_cb);
- EXPECT_EQ(NULL, cras_ramp_start_cb_data);
-}
-
-TEST(IoDev, OutputDeviceShouldWake) {
- struct cras_iodev iodev;
- int rc;
-
- memset(&iodev, 0, sizeof(iodev));
-
- ResetStubData();
-
- // Device is not running. No need to wake for this device.
- iodev.state = CRAS_IODEV_STATE_OPEN;
- rc = cras_iodev_odev_should_wake(&iodev);
- EXPECT_EQ(0, rc);
-
- // Device is running. Need to wake for this device.
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- rc = cras_iodev_odev_should_wake(&iodev);
- EXPECT_EQ(1, rc);
-
- // Device is running. Device has is_free_running ops.
- iodev.is_free_running = is_free_running;
- is_free_running_ret = 1;
- rc = cras_iodev_odev_should_wake(&iodev);
- EXPECT_EQ(0, rc);
-
- // Device is running. Device has is_free_running ops.
- is_free_running_ret = 0;
- rc = cras_iodev_odev_should_wake(&iodev);
- EXPECT_EQ(1, rc);
-
- // Ignore input device.
- iodev.direction = CRAS_STREAM_INPUT;
- rc = cras_iodev_odev_should_wake(&iodev);
- EXPECT_EQ(0, rc);
-}
-
-TEST(IoDev, FramesToPlayInSleep) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- unsigned int min_cb_level = 512, hw_level;
- unsigned int got_hw_level, got_frames;
- struct timespec hw_tstamp;
- struct cras_rstream rstream;
- struct dev_stream stream;
-
- memset(&iodev, 0, sizeof(iodev));
- memset(&fmt, 0, sizeof(fmt));
- iodev.frames_queued = frames_queued;
- iodev.min_buffer_level = 0;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.buffer_size = BUFFER_SIZE;
- iodev.min_cb_level = min_cb_level;
- iodev.state = CRAS_IODEV_STATE_NORMAL_RUN;
- iodev.format = &fmt;
- fmt.frame_rate = 48000;
- rstream.cb_threshold = min_cb_level;
- stream.stream = &rstream;
-
- ResetStubData();
-
- cras_iodev_add_stream(&iodev, &stream);
- cras_iodev_start_stream(&iodev, &stream);
-
- // Device is running. There is at least one stream for this device
- // and there are frames waiting to be played. hw_level is greater
- // than min_cb_level.
- dev_stream_playback_frames_ret = 100;
- hw_level = min_cb_level + 50;
- fr_queued = hw_level;
- got_frames =
- cras_iodev_frames_to_play_in_sleep(&iodev, &got_hw_level, &hw_tstamp);
- EXPECT_EQ(got_hw_level, hw_level);
- EXPECT_EQ(got_frames, 50);
- dev_stream_playback_frames_ret = 0;
-
- // Device is running. There is at least one stream for this device.
- // hw_level is greater than min_cb_level.
- hw_level = min_cb_level + 50;
- fr_queued = hw_level;
- got_frames =
- cras_iodev_frames_to_play_in_sleep(&iodev, &got_hw_level, &hw_tstamp);
- EXPECT_EQ(got_hw_level, hw_level);
- EXPECT_EQ(got_frames, 514);
-
- // Device is running. There is at least one stream for this device.
- // hw_level is 2x greater than min_cb_level.
- hw_level = 2 * min_cb_level + 50;
- fr_queued = hw_level;
- got_frames =
- cras_iodev_frames_to_play_in_sleep(&iodev, &got_hw_level, &hw_tstamp);
- EXPECT_EQ(got_hw_level, hw_level);
- EXPECT_EQ(got_frames, 1026);
-
- // Device is running. There is at least one stream for this device.
- // hw_level is less than min_cb_level.
- hw_level = min_cb_level / 2;
- fr_queued = hw_level;
- got_frames =
- cras_iodev_frames_to_play_in_sleep(&iodev, &got_hw_level, &hw_tstamp);
- EXPECT_EQ(got_hw_level, hw_level);
- EXPECT_EQ(got_frames, 208);
-
- // Device is running. There is no stream for this device. The audio thread
- // will wake up until hw_level drops to DEV_NO_STREAM_WAKE_UP_LATEST_TIME,
- // which is defined as 5 milliseconds in cras_iodev.c.
- iodev.streams = NULL;
- hw_level = min_cb_level;
- fr_queued = hw_level;
- got_frames =
- cras_iodev_frames_to_play_in_sleep(&iodev, &got_hw_level, &hw_tstamp);
- EXPECT_EQ(got_hw_level, hw_level);
- EXPECT_EQ(got_frames, hw_level - fmt.frame_rate / 1000 * 5);
-}
-
-TEST(IoDev, GetNumUnderruns) {
- struct cras_iodev iodev;
- memset(&iodev, 0, sizeof(iodev));
-
- EXPECT_EQ(0, cras_iodev_get_num_underruns(&iodev));
-
- iodev.num_underruns = 10;
- EXPECT_EQ(10, cras_iodev_get_num_underruns(&iodev));
-}
-
-TEST(IoDev, RequestReset) {
- struct cras_iodev iodev;
- memset(&iodev, 0, sizeof(iodev));
-
- ResetStubData();
-
- iodev.configure_dev = configure_dev;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.format = &audio_fmt;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
-
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- iodev_buffer_size = 1024;
-
- // Open device.
- cras_iodev_open(&iodev, 240, &audio_fmt);
-
- // The first reset request works.
- EXPECT_EQ(0, cras_iodev_reset_request(&iodev));
- EXPECT_EQ(1, device_monitor_reset_device_called);
-
- // The second reset request will do nothing.
- EXPECT_EQ(0, cras_iodev_reset_request(&iodev));
- EXPECT_EQ(1, device_monitor_reset_device_called);
-
- // Assume device is opened again.
- cras_iodev_open(&iodev, 240, &audio_fmt);
-
- // The reset request works.
- EXPECT_EQ(0, cras_iodev_reset_request(&iodev));
- EXPECT_EQ(2, device_monitor_reset_device_called);
-}
-
-static int output_underrun(struct cras_iodev* iodev) {
- output_underrun_called++;
- return 0;
-}
-
-TEST(IoDev, HandleOutputUnderrun) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- unsigned int frames = 240;
- int16_t* zeros;
- int rc;
-
- ResetStubData();
-
- memset(&iodev, 0, sizeof(iodev));
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.format = &fmt;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.min_cb_level = frames;
-
- // Default case, fill one block of zeros.
- EXPECT_EQ(0, cras_iodev_output_underrun(&iodev, 0, 0));
-
- EXPECT_EQ(frames, put_buffer_nframes);
- zeros = (int16_t*)calloc(frames * 2, sizeof(*zeros));
- rc = memcmp(audio_buffer, zeros, frames * 2 * 2);
- free(zeros);
- EXPECT_EQ(0, rc);
-
- // Test iodev has output_underrun ops.
- iodev.output_underrun = output_underrun;
- EXPECT_EQ(0, cras_iodev_output_underrun(&iodev, 0, 0));
- EXPECT_EQ(1, output_underrun_called);
-}
-
-static void ext_mod_configure(struct ext_dsp_module* ext,
- unsigned int buffer_size,
- unsigned int num_channels,
- unsigned int rate) {
- ext_mod_configure_called++;
-}
-
-TEST(IoDev, SetExtDspMod) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- struct ext_dsp_module ext;
-
- ResetStubData();
-
- memset(&iodev, 0, sizeof(iodev));
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.configure_dev = configure_dev;
- iodev.format = &fmt;
- iodev.format = &fmt;
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- ext.configure = ext_mod_configure;
-
- iodev.dsp_context = reinterpret_cast<cras_dsp_context*>(0xf0f);
- cras_dsp_get_pipeline_ret = 0x25;
-
- cras_iodev_set_ext_dsp_module(&iodev, &ext);
- EXPECT_EQ(0, ext_mod_configure_called);
-
- cras_iodev_open(&iodev, 240, &fmt);
- EXPECT_EQ(1, ext_mod_configure_called);
- EXPECT_EQ(1, cras_dsp_get_pipeline_called);
- EXPECT_EQ(1, cras_dsp_pipeline_set_sink_ext_module_called);
-
- cras_iodev_set_ext_dsp_module(&iodev, NULL);
- EXPECT_EQ(1, ext_mod_configure_called);
- EXPECT_EQ(2, cras_dsp_get_pipeline_called);
- EXPECT_EQ(2, cras_dsp_pipeline_set_sink_ext_module_called);
-
- cras_iodev_set_ext_dsp_module(&iodev, &ext);
- EXPECT_EQ(2, ext_mod_configure_called);
- EXPECT_EQ(3, cras_dsp_get_pipeline_called);
- EXPECT_EQ(3, cras_dsp_pipeline_set_sink_ext_module_called);
-
- /* If pipeline doesn't exist, mock pipeline should be loaded. */
- cras_dsp_get_pipeline_ret = 0x0;
- cras_iodev_set_ext_dsp_module(&iodev, &ext);
- EXPECT_EQ(3, ext_mod_configure_called);
- EXPECT_EQ(5, cras_dsp_get_pipeline_called);
- EXPECT_EQ(1, cras_dsp_load_mock_pipeline_called);
- EXPECT_EQ(4, cras_dsp_pipeline_set_sink_ext_module_called);
-}
-
-TEST(IoDev, InputDspOffset) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- struct cras_rstream rstream1;
- struct dev_stream stream1;
- struct input_data data;
- unsigned int frames = 240;
- int rc;
-
- ResetStubData();
-
- rstream1.cb_threshold = 240;
- rstream1.stream_id = 123;
- stream1.stream = &rstream1;
-
- memset(&iodev, 0, sizeof(iodev));
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.configure_dev = configure_dev;
- iodev.format = &fmt;
- iodev.format = &fmt;
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.buffer_size = 480;
-
- iodev.dsp_context = reinterpret_cast<cras_dsp_context*>(0xf0f);
- cras_dsp_get_pipeline_ret = 0x25;
- input_data_create_ret = &data;
-
- cras_iodev_open(&iodev, 240, &fmt);
-
- cras_iodev_add_stream(&iodev, &stream1);
- cras_iodev_get_input_buffer(&iodev, &frames);
-
- buffer_share_get_new_write_point_ret = 100;
- rc = cras_iodev_put_input_buffer(&iodev);
- EXPECT_EQ(140, iodev.input_dsp_offset);
- EXPECT_EQ(100, rc);
-
- frames = 130;
- cras_iodev_get_input_buffer(&iodev, &frames);
- EXPECT_EQ(130, iodev.input_frames_read);
-
- buffer_share_get_new_write_point_ret = 80;
- rc = cras_iodev_put_input_buffer(&iodev);
- EXPECT_EQ(60, iodev.input_dsp_offset);
- EXPECT_EQ(80, rc);
-}
-
-TEST(IoDev, DropDeviceFramesByTime) {
- struct cras_iodev iodev;
- struct cras_audio_format fmt;
- struct input_data data;
- struct timespec ts;
- int rc;
-
- ResetStubData();
-
- memset(&iodev, 0, sizeof(iodev));
- fmt.format = SND_PCM_FORMAT_S16_LE;
- fmt.frame_rate = 48000;
- fmt.num_channels = 2;
- iodev.configure_dev = configure_dev;
- iodev.format = &fmt;
- iodev.state = CRAS_IODEV_STATE_CLOSE;
- iodev.get_buffer = get_buffer;
- iodev.put_buffer = put_buffer;
- iodev.frames_queued = frames_queued;
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.buffer_size = 480;
- input_data_create_ret = &data;
- cras_iodev_open(&iodev, 240, &fmt);
- rate_estimator_get_rate_ret = 48000.0;
-
- /* hw_level: 240, drop: 48(1ms). */
- fr_queued = 240;
- ts.tv_sec = 0;
- ts.tv_nsec = 1000000;
- rc = cras_iodev_drop_frames_by_time(&iodev, ts);
- EXPECT_EQ(48, rc);
- EXPECT_EQ(48, put_buffer_nframes);
- EXPECT_EQ(1, rate_estimator_add_frames_called);
- EXPECT_EQ(-48, rate_estimator_add_frames_num_frames);
-
- /* hw_level: 360, drop: 240(5ms). */
- fr_queued = 360;
- ts.tv_sec = 0;
- ts.tv_nsec = 5000000;
- rc = cras_iodev_drop_frames_by_time(&iodev, ts);
- EXPECT_EQ(240, rc);
- EXPECT_EQ(240, put_buffer_nframes);
- EXPECT_EQ(2, rate_estimator_add_frames_called);
- EXPECT_EQ(-240, rate_estimator_add_frames_num_frames);
-
- /* hw_level: 360, drop: 480(10ms). Only drop 360 because of lower hw_level. */
- fr_queued = 360;
- ts.tv_sec = 0;
- ts.tv_nsec = 10000000;
- rc = cras_iodev_drop_frames_by_time(&iodev, ts);
- EXPECT_EQ(360, rc);
- EXPECT_EQ(360, put_buffer_nframes);
- EXPECT_EQ(3, rate_estimator_add_frames_called);
- EXPECT_EQ(-360, rate_estimator_add_frames_num_frames);
-}
-
-TEST(IoDev, AecUseCaseCheck) {
- struct cras_ionode node;
-
- /* test output types */
- node.type = CRAS_NODE_TYPE_INTERNAL_SPEAKER;
- EXPECT_EQ(1, cras_iodev_is_aec_use_case(&node));
- node.type = CRAS_NODE_TYPE_HEADPHONE;
- EXPECT_EQ(0, cras_iodev_is_aec_use_case(&node));
- node.type = CRAS_NODE_TYPE_HDMI;
- EXPECT_EQ(0, cras_iodev_is_aec_use_case(&node));
- node.type = CRAS_NODE_TYPE_USB;
- EXPECT_EQ(0, cras_iodev_is_aec_use_case(&node));
- node.type = CRAS_NODE_TYPE_BLUETOOTH;
- EXPECT_EQ(0, cras_iodev_is_aec_use_case(&node));
-
- /* test mic positions */
- node.type = CRAS_NODE_TYPE_MIC;
- node.position = NODE_POSITION_INTERNAL;
- EXPECT_EQ(1, cras_iodev_is_aec_use_case(&node));
- node.position = NODE_POSITION_FRONT;
- EXPECT_EQ(1, cras_iodev_is_aec_use_case(&node));
- node.position = NODE_POSITION_EXTERNAL;
- EXPECT_EQ(0, cras_iodev_is_aec_use_case(&node));
- node.position = NODE_POSITION_REAR;
- EXPECT_EQ(0, cras_iodev_is_aec_use_case(&node));
-}
-
-TEST(IoDev, DeviceOverrun) {
- struct cras_iodev iodev;
-
- iodev.buffer_size = 4096;
- iodev.largest_cb_level = 2048;
- cras_iodev_update_highest_hw_level(&iodev, 4096);
- EXPECT_EQ(0, cras_audio_thread_event_dev_overrun_called);
-
- iodev.largest_cb_level = 1024;
- iodev.highest_hw_level = 1024;
- cras_iodev_update_highest_hw_level(&iodev, 2048);
- EXPECT_EQ(0, cras_audio_thread_event_dev_overrun_called);
-
- cras_iodev_update_highest_hw_level(&iodev, 4096);
- EXPECT_EQ(1, cras_audio_thread_event_dev_overrun_called);
-
- cras_iodev_update_highest_hw_level(&iodev, 4096);
- EXPECT_EQ(1, cras_audio_thread_event_dev_overrun_called);
-}
-
-TEST(IoDev, OnInternalCard) {
- static struct cras_ionode node;
- node.type = CRAS_NODE_TYPE_INTERNAL_SPEAKER;
- EXPECT_EQ(1, cras_iodev_is_on_internal_card(&node));
- node.type = CRAS_NODE_TYPE_HEADPHONE;
- EXPECT_EQ(1, cras_iodev_is_on_internal_card(&node));
- node.type = CRAS_NODE_TYPE_MIC;
- EXPECT_EQ(1, cras_iodev_is_on_internal_card(&node));
- node.type = CRAS_NODE_TYPE_USB;
- EXPECT_EQ(0, cras_iodev_is_on_internal_card(&node));
- node.type = CRAS_NODE_TYPE_BLUETOOTH;
- EXPECT_EQ(0, cras_iodev_is_on_internal_card(&node));
-}
-
-extern "C" {
-
-struct main_thread_event_log* main_log;
-
-// From libpthread.
-int pthread_create(pthread_t* thread,
- const pthread_attr_t* attr,
- void* (*start_routine)(void*),
- void* arg) {
- return 0;
-}
-
-int pthread_join(pthread_t thread, void** value_ptr) {
- return 0;
-}
-
-// Fromt fmt_conv
-void cras_channel_remix_convert(struct cras_fmt_conv* conv,
- uint8_t* in_buf,
- size_t frames) {}
-
-size_t cras_fmt_conv_in_frames_to_out(struct cras_fmt_conv* conv,
- size_t in_frames) {
- return in_frames;
-}
-
-// From buffer_share
-struct buffer_share* buffer_share_create(unsigned int buf_sz) {
- return NULL;
-}
-
-void buffer_share_destroy(struct buffer_share* mix) {}
-
-int buffer_share_offset_update(struct buffer_share* mix,
- unsigned int id,
- unsigned int frames) {
- return 0;
-}
-
-unsigned int buffer_share_get_new_write_point(struct buffer_share* mix) {
- return buffer_share_get_new_write_point_ret;
-}
-
-int buffer_share_add_id(struct buffer_share* mix, unsigned int id, void* data) {
- buffer_share_add_id_called++;
- return 0;
-}
-
-int buffer_share_rm_id(struct buffer_share* mix, unsigned int id) {
- return 0;
-}
-
-unsigned int buffer_share_id_offset(const struct buffer_share* mix,
- unsigned int id) {
- return 0;
-}
-
-// From cras_system_state.
-void cras_system_state_stream_added(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type) {}
-
-void cras_system_state_stream_removed(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type) {}
-
-// From cras_dsp
-struct cras_dsp_context* cras_dsp_context_new(int sample_rate,
- const char* purpose) {
- dsp_context_new_sample_rate = sample_rate;
- dsp_context_new_purpose = purpose;
- return cras_dsp_context_new_return;
-}
-
-void cras_dsp_context_free(struct cras_dsp_context* ctx) {
- dsp_context_free_called++;
-}
-
-void cras_dsp_load_pipeline(struct cras_dsp_context* ctx) {}
-void cras_dsp_load_mock_pipeline(struct cras_dsp_context* ctx,
- unsigned int num_channels) {
- cras_dsp_load_mock_pipeline_called++;
-}
-
-void cras_dsp_set_variable_string(struct cras_dsp_context* ctx,
- const char* key,
- const char* value) {}
-
-void cras_dsp_set_variable_boolean(struct cras_dsp_context* ctx,
- const char* key,
- char value) {}
-
-struct pipeline* cras_dsp_get_pipeline(struct cras_dsp_context* ctx) {
- cras_dsp_get_pipeline_called++;
- return reinterpret_cast<struct pipeline*>(cras_dsp_get_pipeline_ret);
-}
-
-void cras_dsp_put_pipeline(struct cras_dsp_context* ctx) {
- cras_dsp_put_pipeline_called++;
-}
-
-float* cras_dsp_pipeline_get_source_buffer(struct pipeline* pipeline,
- int index) {
- cras_dsp_pipeline_get_source_buffer_called++;
- return cras_dsp_pipeline_source_buffer[index];
-}
-
-float* cras_dsp_pipeline_get_sink_buffer(struct pipeline* pipeline, int index) {
- cras_dsp_pipeline_get_sink_buffer_called++;
- return cras_dsp_pipeline_sink_buffer[index];
-}
-
-int cras_dsp_pipeline_get_delay(struct pipeline* pipeline) {
- cras_dsp_pipeline_get_delay_called++;
- return 0;
-}
-
-int cras_dsp_pipeline_apply(struct pipeline* pipeline,
- uint8_t* buf,
- snd_pcm_format_t format,
- unsigned int frames) {
- cras_dsp_pipeline_apply_called++;
- cras_dsp_pipeline_apply_sample_count = frames;
- return 0;
-}
-
-void cras_dsp_pipeline_add_statistic(struct pipeline* pipeline,
- const struct timespec* time_delta,
- int samples) {}
-void cras_dsp_pipeline_set_sink_ext_module(struct pipeline* pipeline,
- struct ext_dsp_module* ext_module) {
- cras_dsp_pipeline_set_sink_ext_module_called++;
-}
-
-unsigned int cras_dsp_num_output_channels(const struct cras_dsp_context* ctx) {
- return cras_dsp_num_output_channels_return;
-}
-
-unsigned int cras_dsp_num_input_channels(const struct cras_dsp_context* ctx) {
- return cras_dsp_num_input_channels_return;
-}
-
-// From audio thread
-int audio_thread_post_message(struct audio_thread* thread,
- struct audio_thread_msg* msg) {
- return 0;
-}
-
-void cras_iodev_list_select_node(enum CRAS_STREAM_DIRECTION direction,
- cras_node_id_t node_id) {
- select_node_called++;
- select_node_direction = direction;
- select_node_id = node_id;
-}
-
-int cras_iodev_list_node_selected(struct cras_ionode* node) {
- return node == node_selected;
-}
-
-void cras_iodev_list_disable_dev(struct cras_iodev* dev) {
- cras_iodev_list_disable_dev_called++;
-}
-
-void cras_iodev_list_notify_nodes_changed() {
- notify_nodes_changed_called++;
-}
-
-void cras_iodev_list_notify_active_node_changed(
- enum CRAS_STREAM_DIRECTION direction) {
- notify_active_node_changed_called++;
-}
-
-struct cras_audio_area* cras_audio_area_create(int num_channels) {
- return NULL;
-}
-
-void cras_audio_area_destroy(struct cras_audio_area* area) {}
-
-void cras_audio_area_config_channels(struct cras_audio_area* area,
- const struct cras_audio_format* fmt) {}
-
-int cras_audio_format_set_channel_layout(struct cras_audio_format* format,
- const int8_t layout[CRAS_CH_MAX]) {
- int i;
- cras_audio_format_set_channel_layout_called++;
- for (i = 0; i < CRAS_CH_MAX; i++)
- format->channel_layout[i] = layout[i];
- return 0;
-}
-
-float softvol_get_scaler(unsigned int volume_index) {
- return softvol_scalers[volume_index];
-}
-
-size_t cras_system_get_volume() {
- return cras_system_get_volume_return;
-}
-
-int cras_system_get_mute() {
- return cras_system_get_mute_return;
-}
-
-int cras_system_get_capture_mute() {
- return 0;
-}
-
-void cras_scale_buffer(snd_pcm_format_t fmt,
- uint8_t* buffer,
- unsigned int count,
- float scaler) {
- cras_scale_buffer_called++;
- cras_scale_buffer_fmt = fmt;
- cras_scale_buffer_scaler = scaler;
-}
-
-void cras_scale_buffer_increment(snd_pcm_format_t fmt,
- uint8_t* buff,
- unsigned int frame,
- float scaler,
- float increment,
- float target,
- int channel) {
- cras_scale_buffer_increment_fmt = fmt;
- cras_scale_buffer_increment_buff = buff;
- cras_scale_buffer_increment_frame = frame;
- cras_scale_buffer_increment_scaler = scaler;
- cras_scale_buffer_increment_increment = increment;
- cras_scale_buffer_increment_target = target;
- cras_scale_buffer_increment_channel = channel;
-}
-
-size_t cras_mix_mute_buffer(uint8_t* dst, size_t frame_bytes, size_t count) {
- cras_mix_mute_count = count;
- return count;
-}
-
-struct rate_estimator* rate_estimator_create(unsigned int rate,
- const struct timespec* window_size,
- double smooth_factor) {
- return NULL;
-}
-
-void rate_estimator_destroy(struct rate_estimator* re) {}
-
-void rate_estimator_add_frames(struct rate_estimator* re, int fr) {
- rate_estimator_add_frames_called++;
- rate_estimator_add_frames_num_frames = fr;
-}
-
-int rate_estimator_check(struct rate_estimator* re,
- int level,
- struct timespec* now) {
- return 0;
-}
-
-void rate_estimator_reset_rate(struct rate_estimator* re, unsigned int rate) {}
-
-double rate_estimator_get_rate(struct rate_estimator* re) {
- return rate_estimator_get_rate_ret;
-}
-
-unsigned int dev_stream_cb_threshold(const struct dev_stream* dev_stream) {
- if (dev_stream->stream)
- return dev_stream->stream->cb_threshold;
- return 0;
-}
-
-int dev_stream_attached_devs(const struct dev_stream* dev_stream) {
- return 1;
-}
-
-void dev_stream_update_frames(const struct dev_stream* dev_stream) {}
-
-int dev_stream_playback_frames(const struct dev_stream* dev_stream) {
- return dev_stream_playback_frames_ret;
-}
-
-int cras_device_monitor_reset_device(struct cras_iodev* iodev) {
- device_monitor_reset_device_called++;
- return 0;
-}
-
-void cras_ramp_destroy(struct cras_ramp* ramp) {
- return;
-}
-
-int cras_ramp_start(struct cras_ramp* ramp,
- int mute_ramp,
- float from,
- float to,
- int duration_frames,
- cras_ramp_cb cb,
- void* cb_data) {
- cras_ramp_start_is_called++;
- cras_ramp_start_mute_ramp = mute_ramp;
- cras_ramp_start_from = from;
- cras_ramp_start_to = to;
- cras_ramp_start_duration_frames = duration_frames;
- cras_ramp_start_cb = cb;
- cras_ramp_start_cb_data = cb_data;
- return 0;
-}
-
-int cras_ramp_reset(struct cras_ramp* ramp) {
- cras_ramp_reset_is_called++;
- return 0;
-}
-
-struct cras_ramp_action cras_ramp_get_current_action(
- const struct cras_ramp* ramp) {
- return cras_ramp_get_current_action_ret;
-}
-
-int cras_ramp_update_ramped_frames(struct cras_ramp* ramp, int num_frames) {
- cras_ramp_update_ramped_frames_num_frames = num_frames;
- return 0;
-}
-
-int cras_device_monitor_set_device_mute_state(unsigned int dev_idx) {
- cras_device_monitor_set_device_mute_state_called++;
- cras_device_monitor_set_device_mute_state_dev_idx = dev_idx;
- return 0;
-}
-
-static void mod_run(struct ext_dsp_module* ext, unsigned int nframes) {}
-
-static void mod_configure(struct ext_dsp_module* ext,
- unsigned int buffer_size,
- unsigned int num_channels,
- unsigned int rate) {}
-
-struct input_data* input_data_create(void* dev_ptr) {
- if (input_data_create_ret) {
- input_data_create_ret->ext.run = mod_run;
- input_data_create_ret->ext.configure = mod_configure;
- }
- return input_data_create_ret;
-}
-
-void input_data_destroy(struct input_data** data) {}
-void input_data_set_all_streams_read(struct input_data* data,
- unsigned int nframes) {}
-
-int cras_audio_thread_event_underrun() {
- return 0;
-}
-
-int cras_audio_thread_event_dev_overrun() {
- cras_audio_thread_event_dev_overrun_called++;
- return 0;
-}
-
-int cras_server_metrics_device_runtime(struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_server_metrics_device_volume(struct cras_iodev* iodev) {
- return 0;
-}
-
-void ewma_power_init(struct ewma_power* ewma, unsigned int rate){};
-
-void ewma_power_calculate(struct ewma_power* ewma,
- const int16_t* buf,
- unsigned int channels,
- unsigned int size){};
-
-void ewma_power_calculate_area(struct ewma_power* ewma,
- const int16_t* buf,
- struct cras_audio_area* area,
- unsigned int size){};
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- int rc = RUN_ALL_TESTS();
-
- audio_thread_event_log_deinit(atlog, atlog_name);
- free(atlog_name);
- return rc;
-}
diff --git a/cras/src/tests/linear_resampler_unittest.cc b/cras/src/tests/linear_resampler_unittest.cc
deleted file mode 100644
index 6095d5b6..00000000
--- a/cras/src/tests/linear_resampler_unittest.cc
+++ /dev/null
@@ -1,220 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <limits.h>
-#include <stdint.h>
-#include <stdio.h>
-
-extern "C" {
-#include "linear_resampler.h"
-}
-
-#define BUF_SIZE 2048
-
-static uint8_t in_buf[BUF_SIZE];
-static uint8_t out_buf[BUF_SIZE];
-
-TEST(LinearResampler, ReampleToSlightlyLargerRate) {
- int i, rc;
- unsigned int count;
- unsigned int in_offset = 0;
- unsigned int out_offset = 0;
- struct linear_resampler* lr;
-
- memset(in_buf, 0, BUF_SIZE);
- memset(out_buf, 0, BUF_SIZE);
- for (i = 0; i < 100; i++) {
- *((int16_t*)(in_buf + i * 4)) = i * 10;
- *((int16_t*)(in_buf + i * 4 + 2)) = i * 20;
- }
-
- lr = linear_resampler_create(2, 4, 48000, 48001);
-
- count = 20;
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 50);
- EXPECT_EQ(20, rc);
- EXPECT_EQ(20, count);
-
- in_offset += count;
- out_offset += rc;
- count = 20;
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 15);
- EXPECT_EQ(15, rc);
- EXPECT_EQ(15, count);
-
- /* Assert linear interpotation result. */
- for (i = 0; i < 34; i++) {
- EXPECT_GE(*(int16_t*)(in_buf + 4 * i), *(int16_t*)(out_buf + 4 * i));
- EXPECT_LE(*(int16_t*)(in_buf + 4 * i), *(int16_t*)(out_buf + 4 * (i + 1)));
- }
- linear_resampler_destroy(lr);
-}
-
-TEST(LinearResampler, ResampleIntegerFractionToLarger) {
- int i, rc;
- unsigned int count;
- unsigned int in_offset = 0;
- unsigned int out_offset = 0;
- struct linear_resampler* lr;
-
- memset(in_buf, 0, BUF_SIZE);
- memset(out_buf, 0, BUF_SIZE);
- for (i = 0; i < 100; i++) {
- *((int16_t*)(in_buf + i * 4)) = SHRT_MAX - i;
- *((int16_t*)(in_buf + i * 4 + 2)) = SHRT_MAX - i * 10;
- }
-
- /* Rate 10 -> 11 */
- lr = linear_resampler_create(2, 4, 10, 11);
-
- count = 5;
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 10);
- EXPECT_EQ(5, rc);
- EXPECT_EQ(5, count);
-
- in_offset += count;
- out_offset += rc;
- count = 6;
- /* Assert source rate + 1 frames resample to destination rate + 1
- * frames. */
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 10);
- EXPECT_EQ(7, rc);
- EXPECT_EQ(6, count);
-
- in_offset += count;
- out_offset += rc;
- count = 89;
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 100);
- EXPECT_EQ(97, rc);
- EXPECT_EQ(89, count);
-
- /* Assert linear interpotation result. */
- for (i = 0; i < 90; i++) {
- EXPECT_LE(*(int16_t*)(in_buf + 4 * i), *(int16_t*)(out_buf + 4 * i));
- EXPECT_LE(*(int16_t*)(in_buf + 4 * i + 2),
- *(int16_t*)(out_buf + 4 * i + 2));
- }
- linear_resampler_destroy(lr);
-}
-
-TEST(LinearResampler, ResampleIntegerFractionToLess) {
- int i, rc;
- unsigned int count;
- unsigned int in_offset = 0;
- unsigned int out_offset = 0;
- struct linear_resampler* lr;
-
- memset(in_buf, 0, BUF_SIZE);
- memset(out_buf, 0, BUF_SIZE);
- for (i = 0; i < 100; i++) {
- *((int16_t*)(in_buf + i * 4)) = SHRT_MIN + i * 10;
- *((int16_t*)(in_buf + i * 4 + 2)) = SHRT_MIN + i * 20;
- }
-
- /* Rate 10 -> 9 */
- lr = linear_resampler_create(2, 4, 10, 9);
-
- count = 6;
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 6);
- EXPECT_EQ(5, rc);
- EXPECT_EQ(6, count);
-
- in_offset += count;
- out_offset += rc;
- count = 4;
-
- /* Assert source rate frames resample to destination rate frames. */
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 4);
- EXPECT_EQ(4, rc);
- EXPECT_EQ(4, count);
-
- in_offset += count;
- out_offset += rc;
- count = 90;
- rc = linear_resampler_resample(lr, in_buf + 4 * in_offset, &count,
- out_buf + 4 * out_offset, 90);
-
- /* Assert linear interpotation result. */
- for (i = 0; i < 90; i++) {
- EXPECT_LE(*(int16_t*)(in_buf + 4 * i), *(int16_t*)(out_buf + 4 * i));
- EXPECT_LE(*(int16_t*)(in_buf + 4 * i + 2),
- *(int16_t*)(out_buf + 4 * i + 2));
- }
- linear_resampler_destroy(lr);
-}
-
-TEST(LinearResampler, ResampleIntegerNoSrcBuffer) {
- int rc;
- unsigned int count;
- struct linear_resampler* lr;
-
- memset(in_buf, 0, BUF_SIZE);
- memset(out_buf, 0, BUF_SIZE);
-
- /* Rate 10 -> 9 */
- lr = linear_resampler_create(2, 4, 10, 9);
-
- count = 0;
- rc = linear_resampler_resample(lr, in_buf, &count, out_buf, BUF_SIZE);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, count);
- linear_resampler_destroy(lr);
-}
-
-TEST(LinearResampler, ResampleIntegerNoDstBuffer) {
- int rc;
- unsigned int count;
- struct linear_resampler* lr;
-
- memset(in_buf, 0, BUF_SIZE);
- memset(out_buf, 0, BUF_SIZE);
-
- /* Rate 10 -> 9 */
- lr = linear_resampler_create(2, 4, 10, 9);
-
- count = BUF_SIZE;
- rc = linear_resampler_resample(lr, in_buf, &count, out_buf, 0);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, count);
- linear_resampler_destroy(lr);
-}
-
-extern "C" {
-
-void cras_mix_add_scale_stride(int fmt,
- uint8_t* dst,
- uint8_t* src,
- unsigned int count,
- unsigned int dst_stride,
- unsigned int src_stride,
- float scaler) {
- unsigned int i;
-
- for (i = 0; i < count; i++) {
- int32_t sum;
- sum = *(int16_t*)dst + *(int16_t*)src * scaler;
- if (sum > INT16_MAX)
- sum = INT16_MAX;
- else if (sum < INT16_MIN)
- sum = INT16_MIN;
- *(int16_t*)dst = sum;
- dst += dst_stride;
- src += src_stride;
- }
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/loopback_iodev_unittest.cc b/cras/src/tests/loopback_iodev_unittest.cc
deleted file mode 100644
index fde50375..00000000
--- a/cras/src/tests/loopback_iodev_unittest.cc
+++ /dev/null
@@ -1,297 +0,0 @@
-// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-extern "C" {
-// For audio_thread_log.h use.
-struct audio_thread_event_log* atlog;
-int atlog_rw_shm_fd;
-int atlog_ro_shm_fd;
-#include "audio_thread_log.h"
-#include "cras_audio_area.h"
-#include "cras_iodev.h"
-#include "cras_iodev_list.h"
-#include "cras_loopback_iodev.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "dev_stream.h"
-#include "utlist.h"
-}
-
-namespace {
-
-static const unsigned int kBufferFrames = 16384;
-static const unsigned int kFrameBytes = 4;
-static const unsigned int kBufferSize = kBufferFrames * kFrameBytes;
-
-static struct timespec time_now;
-static cras_audio_area* mock_audio_area;
-static loopback_hook_data_t loop_hook;
-static struct cras_iodev* enabled_dev;
-static unsigned int cras_iodev_list_add_input_called;
-static unsigned int cras_iodev_list_rm_input_called;
-static unsigned int cras_iodev_list_set_device_enabled_callback_called;
-static device_enabled_callback_t device_enabled_callback_cb;
-static device_disabled_callback_t device_disabled_callback_cb;
-static void* device_enabled_callback_cb_data;
-static int cras_iodev_list_register_loopback_called;
-static int cras_iodev_list_unregister_loopback_called;
-
-static char* atlog_name;
-
-class LoopBackTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- mock_audio_area = (cras_audio_area*)calloc(
- 1, sizeof(*mock_audio_area) + sizeof(cras_channel_area) * 2);
- for (unsigned int i = 0; i < kBufferSize; i++) {
- buf_[i] = rand();
- }
- fmt_.frame_rate = 48000;
- fmt_.num_channels = 2;
- fmt_.format = SND_PCM_FORMAT_S16_LE;
-
- loop_in_ = loopback_iodev_create(LOOPBACK_POST_MIX_PRE_DSP);
- EXPECT_EQ(1, cras_iodev_list_add_input_called);
- loop_in_->format = &fmt_;
-
- loop_hook = NULL;
- cras_iodev_list_add_input_called = 0;
- cras_iodev_list_rm_input_called = 0;
- cras_iodev_list_set_device_enabled_callback_called = 0;
- cras_iodev_list_register_loopback_called = 0;
- cras_iodev_list_unregister_loopback_called = 0;
-
- ASSERT_FALSE(asprintf(&atlog_name, "/ATlog-%d", getpid()) < 0);
- /* To avoid un-used variable warning. */
- atlog_rw_shm_fd = atlog_ro_shm_fd = -1;
- atlog = audio_thread_event_log_init(atlog_name);
- }
-
- virtual void TearDown() {
- loopback_iodev_destroy(loop_in_);
- EXPECT_EQ(1, cras_iodev_list_rm_input_called);
- EXPECT_EQ(NULL, device_enabled_callback_cb);
- EXPECT_EQ(NULL, device_disabled_callback_cb);
- free(mock_audio_area);
- audio_thread_event_log_deinit(atlog, atlog_name);
- free(atlog_name);
- }
-
- uint8_t buf_[kBufferSize];
- struct cras_audio_format fmt_;
- struct cras_iodev* loop_in_;
-};
-
-TEST_F(LoopBackTestSuite, InstallLoopHook) {
- struct cras_iodev iodev;
- struct timespec tstamp;
-
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.format = &fmt_;
- iodev.streams = NULL;
- iodev.info.idx = 123;
- enabled_dev = &iodev;
-
- // Open loopback devices.
- EXPECT_EQ(0, loop_in_->configure_dev(loop_in_));
- EXPECT_EQ(1, cras_iodev_list_set_device_enabled_callback_called);
- EXPECT_EQ(1, cras_iodev_list_register_loopback_called);
-
- // Signal an output device is enabled.
- device_enabled_callback_cb(&iodev, device_enabled_callback_cb_data);
-
- // Expect that a hook was added to the iodev
- EXPECT_EQ(2, cras_iodev_list_register_loopback_called);
- ASSERT_NE(reinterpret_cast<loopback_hook_data_t>(NULL), loop_hook);
-
- // Check zero frames queued.
- EXPECT_EQ(0, loop_in_->frames_queued(loop_in_, &tstamp));
-
- device_disabled_callback_cb(&iodev, device_enabled_callback_cb_data);
- EXPECT_EQ(1, cras_iodev_list_unregister_loopback_called);
- EXPECT_EQ(3, cras_iodev_list_register_loopback_called);
-
- enabled_dev->info.idx = 456;
- device_enabled_callback_cb(&iodev, device_enabled_callback_cb_data);
- EXPECT_EQ(4, cras_iodev_list_register_loopback_called);
-
- // Close loopback devices.
- EXPECT_EQ(0, loop_in_->close_dev(loop_in_));
- EXPECT_EQ(2, cras_iodev_list_unregister_loopback_called);
- EXPECT_EQ(2, cras_iodev_list_set_device_enabled_callback_called);
-}
-
-TEST_F(LoopBackTestSuite, SelectDevFromAToB) {
- struct cras_iodev iodev1, iodev2;
-
- iodev1.direction = CRAS_STREAM_OUTPUT;
- iodev2.direction = CRAS_STREAM_OUTPUT;
- enabled_dev = &iodev1;
-
- enabled_dev->info.idx = 111;
- EXPECT_EQ(0, loop_in_->configure_dev(loop_in_));
- EXPECT_EQ(1, cras_iodev_list_set_device_enabled_callback_called);
- EXPECT_EQ(1, cras_iodev_list_register_loopback_called);
-
- /* Not the current sender being disabled, assert unregister not called. */
- iodev2.info.idx = 222;
- device_disabled_callback_cb(&iodev2, device_enabled_callback_cb_data);
- EXPECT_EQ(0, cras_iodev_list_unregister_loopback_called);
- EXPECT_EQ(1, cras_iodev_list_register_loopback_called);
-
- enabled_dev = &iodev2;
- device_disabled_callback_cb(&iodev1, device_enabled_callback_cb_data);
- EXPECT_EQ(1, cras_iodev_list_unregister_loopback_called);
- EXPECT_EQ(2, cras_iodev_list_register_loopback_called);
-
- EXPECT_EQ(0, loop_in_->close_dev(loop_in_));
-}
-
-// Test how loopback works if there isn't any output devices open.
-TEST_F(LoopBackTestSuite, OpenIdleSystem) {
- cras_audio_area* area;
- unsigned int nread = 1024;
- struct timespec tstamp;
- int rc;
-
- // No active output device.
- enabled_dev = NULL;
- time_now.tv_sec = 100;
- time_now.tv_nsec = 0;
-
- EXPECT_EQ(0, loop_in_->configure_dev(loop_in_));
- EXPECT_EQ(1, cras_iodev_list_set_device_enabled_callback_called);
-
- // Should be 480 samples after 480/frame rate seconds
- time_now.tv_nsec += 480 * 1e9 / 48000;
- EXPECT_EQ(480, loop_in_->frames_queued(loop_in_, &tstamp));
-
- // Verify frames from loopback record.
- loop_in_->get_buffer(loop_in_, &area, &nread);
- EXPECT_EQ(480, nread);
- memset(buf_, 0, nread * kFrameBytes);
- rc = memcmp(area->channels[0].buf, buf_, nread * kFrameBytes);
- EXPECT_EQ(0, rc);
- loop_in_->put_buffer(loop_in_, nread);
-
- // Check zero frames queued.
- EXPECT_EQ(0, loop_in_->frames_queued(loop_in_, &tstamp));
-
- EXPECT_EQ(0, loop_in_->close_dev(loop_in_));
-}
-
-TEST_F(LoopBackTestSuite, SimpleLoopback) {
- cras_audio_area* area;
- unsigned int nframes = 1024;
- unsigned int nread = 1024;
- int rc;
- struct cras_iodev iodev;
- struct dev_stream stream;
- struct timespec tstamp;
-
- iodev.streams = &stream;
- enabled_dev = &iodev;
-
- loop_in_->configure_dev(loop_in_);
- ASSERT_NE(reinterpret_cast<void*>(NULL), loop_hook);
-
- // Loopback callback for the hook.
- loop_hook(buf_, nframes, &fmt_, loop_in_);
-
- // Verify frames from loopback record.
- loop_in_->get_buffer(loop_in_, &area, &nread);
- EXPECT_EQ(nframes, nread);
- rc = memcmp(area->channels[0].buf, buf_, nframes * kFrameBytes);
- EXPECT_EQ(0, rc);
- loop_in_->put_buffer(loop_in_, nread);
-
- // Check zero frames queued.
- EXPECT_EQ(0, loop_in_->frames_queued(loop_in_, &tstamp));
-
- EXPECT_EQ(0, loop_in_->close_dev(loop_in_));
-}
-
-// TODO(chinyue): Test closing last iodev while streaming loopback data.
-
-/* Stubs */
-extern "C" {
-
-void cras_audio_area_config_buf_pointers(struct cras_audio_area* area,
- const struct cras_audio_format* fmt,
- uint8_t* base_buffer) {
- mock_audio_area->channels[0].buf = base_buffer;
-}
-
-void cras_iodev_free_audio_area(struct cras_iodev* iodev) {}
-
-void cras_iodev_free_format(struct cras_iodev* iodev) {}
-
-void cras_iodev_init_audio_area(struct cras_iodev* iodev, int num_channels) {
- iodev->area = mock_audio_area;
-}
-
-void cras_iodev_add_node(struct cras_iodev* iodev, struct cras_ionode* node) {
- DL_APPEND(iodev->nodes, node);
-}
-
-void cras_iodev_set_active_node(struct cras_iodev* iodev,
- struct cras_ionode* node) {}
-void cras_iodev_list_register_loopback(enum CRAS_LOOPBACK_TYPE loopback_type,
- unsigned int output_dev_idx,
- loopback_hook_data_t hook_data,
- loopback_hook_control_t hook_start,
- unsigned int loopback_dev_idx) {
- cras_iodev_list_register_loopback_called++;
- loop_hook = hook_data;
-}
-
-void cras_iodev_list_unregister_loopback(enum CRAS_LOOPBACK_TYPE loopback_type,
- unsigned int output_dev_idx,
- unsigned int loopback_dev_idx) {
- cras_iodev_list_unregister_loopback_called++;
-}
-
-int cras_iodev_list_add_input(struct cras_iodev* input) {
- cras_iodev_list_add_input_called++;
- return 0;
-}
-
-int cras_iodev_list_rm_input(struct cras_iodev* input) {
- cras_iodev_list_rm_input_called++;
- return 0;
-}
-
-int cras_iodev_list_set_device_enabled_callback(
- device_enabled_callback_t enabled_cb,
- device_disabled_callback_t disabled_cb,
- void* cb_data) {
- cras_iodev_list_set_device_enabled_callback_called++;
- device_enabled_callback_cb = enabled_cb;
- device_disabled_callback_cb = disabled_cb;
- device_enabled_callback_cb_data = cb_data;
- return 0;
-}
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = time_now;
- return 0;
-}
-
-struct cras_iodev* cras_iodev_list_get_first_enabled_iodev(
- enum CRAS_STREAM_DIRECTION direction) {
- return enabled_dev;
-}
-
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/metrics_stub.cc b/cras/src/tests/metrics_stub.cc
deleted file mode 100644
index 96e8918b..00000000
--- a/cras/src/tests/metrics_stub.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-extern "C" {
-#include "cras_server_metrics.h"
-
-int cras_server_metrics_device_runtime(struct cras_iodev* iodev) {
- return 0;
-}
-
-int cras_server_metrics_highest_device_delay(
- unsigned int hw_level,
- unsigned int largest_cb_level,
- enum CRAS_STREAM_DIRECTION direction) {
- return 0;
-}
-
-int cras_server_metrics_highest_hw_level(unsigned hw_level,
- enum CRAS_STREAM_DIRECTION direction) {
- return 0;
-}
-
-int cras_server_metrics_longest_fetch_delay(unsigned delay_msec) {
- return 0;
-}
-
-int cras_server_metrics_missed_cb_event(struct cras_rstream* stream) {
- return 0;
-}
-
-int cras_server_metrics_num_underruns(unsigned num_underruns) {
- return 0;
-}
-
-int cras_server_metrics_hfp_battery_indicator(int battery_indicator_support) {
- return 0;
-}
-
-int cras_server_metrics_hfp_battery_report(int battery_report) {
- return 0;
-}
-
-int cras_server_metrics_hfp_wideband_support(bool supported) {
- return 0;
-}
-
-int cras_server_metrics_hfp_packet_loss(float packet_loss_ratio) {
- return 0;
-}
-
-int cras_server_metrics_hfp_sco_connection_error(
- enum CRAS_METRICS_BT_SCO_ERROR_TYPE type) {
- return 0;
-}
-
-int cras_server_metrics_busyloop(struct timespec* ts, unsigned count) {
- return 0;
-}
-
-int cras_server_metrics_busyloop_length(unsigned count) {
- return 0;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/metrics_stub.h b/cras/src/tests/metrics_stub.h
deleted file mode 100644
index 1d07e3e0..00000000
--- a/cras/src/tests/metrics_stub.h
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef METRICS_STUB_H_
-#define METRICS_STUB_H_
-
-#endif // METRICS_STUB_H_
diff --git a/cras/src/tests/mix_unittest.cc b/cras/src/tests/mix_unittest.cc
deleted file mode 100644
index dbbbdb07..00000000
--- a/cras/src/tests/mix_unittest.cc
+++ /dev/null
@@ -1,1271 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_mix.h"
-#include "cras_shm.h"
-#include "cras_types.h"
-}
-
-namespace {
-
-static const size_t kBufferFrames = 8192;
-static const size_t kNumChannels = 2;
-static const size_t kNumSamples = kBufferFrames * kNumChannels;
-static const float kMaxVolumeToScale = 0.9999999;
-static const float kMinVolumeToScale = 0.0000001;
-
-static inline int need_to_scale(float scaler) {
- return (scaler < 0.99 || scaler > 1.01);
-}
-
-class MixTestSuiteS16_LE : public testing::Test {
- protected:
- virtual void SetUp() {
- fmt_ = SND_PCM_FORMAT_S16_LE;
- mix_buffer_ = (int16_t*)malloc(kBufferFrames * 4);
- src_buffer_ = static_cast<int16_t*>(
- calloc(1, kBufferFrames * 4 + sizeof(cras_audio_shm_header)));
-
- for (size_t i = 0; i < kBufferFrames * 2; i++) {
- src_buffer_[i] = i;
- mix_buffer_[i] = -i;
- }
-
- compare_buffer_ = (int16_t*)malloc(kBufferFrames * 4);
- }
-
- virtual void TearDown() {
- free(mix_buffer_);
- free(compare_buffer_);
- free(src_buffer_);
- }
-
- void _SetupBuffer() {
- for (size_t i = 0; i < kBufferFrames; i++) {
- src_buffer_[i] = i + (INT16_MAX >> 2);
- mix_buffer_[i] = i + (INT16_MAX >> 2);
- compare_buffer_[i] = mix_buffer_[i];
- }
- for (size_t i = kBufferFrames; i < kBufferFrames * 2; i++) {
- src_buffer_[i] = i - (INT16_MAX >> 2);
- mix_buffer_[i] = i - (INT16_MAX >> 2);
- compare_buffer_[i] = mix_buffer_[i];
- }
- }
-
- void TestScaleStride(float scaler) {
- _SetupBuffer();
- for (size_t i = 0; i < kBufferFrames * 2; i += 2) {
- int32_t tmp;
- if (need_to_scale(scaler))
- tmp = mix_buffer_[i] + src_buffer_[i / 2] * scaler;
- else
- tmp = mix_buffer_[i] + src_buffer_[i / 2];
- if (tmp > INT16_MAX)
- tmp = INT16_MAX;
- else if (tmp < INT16_MIN)
- tmp = INT16_MIN;
- compare_buffer_[i] = tmp;
- }
-
- cras_mix_add_scale_stride(fmt_, (uint8_t*)mix_buffer_,
- (uint8_t*)src_buffer_, kBufferFrames, 4, 2,
- scaler);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
- }
-
- void ScaleIncrement(float start_scaler, float increment, float target) {
- float scaler = start_scaler;
- for (size_t i = 0; i < kBufferFrames * 2; i++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > kMaxVolumeToScale) {
- } else if (applied_scaler < kMinVolumeToScale) {
- compare_buffer_[i] = 0;
- } else {
- compare_buffer_[i] = mix_buffer_[i] * applied_scaler;
- }
-
- if (i % 2 == 1)
- scaler += increment;
- }
- }
-
- int16_t* mix_buffer_;
- int16_t* src_buffer_;
- int16_t* compare_buffer_;
- snd_pcm_format_t fmt_;
-};
-
-TEST_F(MixTestSuiteS16_LE, MixFirst) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- EXPECT_EQ(0, memcmp(mix_buffer_, src_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, MixTwo) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] * 2;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, MixTwoClip) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- src_buffer_[i] = INT16_MAX;
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = INT16_MAX;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, MixFirstMuted) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 1, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, MixFirstZeroVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, MixFirstHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] * 0.5;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, MixTwoSecondHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] + (int16_t)(src_buffer_[i] * 0.5);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleFullVolumeIncrement) {
- float increment = 0.01;
- int step = 2;
- float start_scaler = 0.999999999;
- float target = 1.0;
-
- _SetupBuffer();
- // Scale full volume with positive increment will not change buffer.
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * 4);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleMinVolumeIncrement) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.000000001;
- float target = 0.0;
-
- _SetupBuffer();
- // Scale min volume with negative increment will change buffer to zeros.
- memset(compare_buffer_, 0, kBufferFrames * 4);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleVolumePositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleVolumeNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleVolumeStartFullNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 1.0;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleVolumeStartZeroPositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.0;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleVolumePositiveIncrementCappedByTarget) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleVolumeNegativeIncrementCappedByTarget) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleFullVolume) {
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * 4);
- cras_scale_buffer(fmt_, (uint8_t*)mix_buffer_, kNumSamples, 0.999999999);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleMinVolume) {
- memset(compare_buffer_, 0, kBufferFrames * 4);
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.0000000001);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, ScaleHalfVolume) {
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] * 0.5;
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.5);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS16_LE, StrideCopy) {
- TestScaleStride(1.0);
- TestScaleStride(100);
- TestScaleStride(0.5);
-}
-
-class MixTestSuiteS24_LE : public testing::Test {
- protected:
- virtual void SetUp() {
- fmt_ = SND_PCM_FORMAT_S24_LE;
- fr_bytes_ = 4 * kNumChannels;
- mix_buffer_ = (int32_t*)malloc(kBufferFrames * fr_bytes_);
- src_buffer_ = static_cast<int32_t*>(
- calloc(1, kBufferFrames * fr_bytes_ + sizeof(cras_audio_shm_header)));
-
- for (size_t i = 0; i < kBufferFrames * 2; i++) {
- src_buffer_[i] = i;
- mix_buffer_[i] = -i;
- }
-
- compare_buffer_ = (int32_t*)malloc(kBufferFrames * fr_bytes_);
- }
-
- virtual void TearDown() {
- free(mix_buffer_);
- free(compare_buffer_);
- free(src_buffer_);
- }
-
- void _SetupBuffer() {
- for (size_t i = 0; i < kBufferFrames; i++) {
- src_buffer_[i] = i + (0x007fffff >> 2);
- mix_buffer_[i] = i + (0x007fffff >> 2);
- compare_buffer_[i] = mix_buffer_[i];
- }
- for (size_t i = kBufferFrames; i < kBufferFrames * 2; i++) {
- src_buffer_[i] = -i - (0x007fffff >> 2);
- mix_buffer_[i] = -i - (0x007fffff >> 2);
- compare_buffer_[i] = mix_buffer_[i];
- }
- }
-
- void TestScaleStride(float scaler) {
- _SetupBuffer();
- for (size_t i = 0; i < kBufferFrames * 2; i += 2) {
- int32_t tmp;
- if (need_to_scale(scaler))
- tmp = mix_buffer_[i] + Scale(src_buffer_[i / 2], scaler);
- else
- tmp = mix_buffer_[i] + src_buffer_[i / 2];
- if (tmp > 0x007fffff)
- tmp = 0x007fffff;
- else if (tmp < (int32_t)0xff800000)
- tmp = (int32_t)0xff800000;
- compare_buffer_[i] = tmp;
- }
-
- cras_mix_add_scale_stride(fmt_, (uint8_t*)mix_buffer_,
- (uint8_t*)src_buffer_, kBufferFrames, 8, 4,
- scaler);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 8));
- }
-
- void ScaleIncrement(float start_scaler, float increment, float target) {
- float scaler = start_scaler;
-
- for (size_t i = 0; i < kBufferFrames * 2; i++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > kMaxVolumeToScale) {
- } else if (applied_scaler < kMinVolumeToScale) {
- compare_buffer_[i] = 0;
- } else {
- compare_buffer_[i] = Scale(mix_buffer_[i], applied_scaler);
- }
-
- if (i % 2 == 1)
- scaler += increment;
- }
- }
-
- int32_t Scale(int32_t value, float scaler) {
- value = ((uint32_t)(value & 0x00ffffff)) << 8;
- value *= scaler;
- return (value >> 8) & 0x00ffffff;
- }
-
- int32_t* mix_buffer_;
- int32_t* src_buffer_;
- int32_t* compare_buffer_;
- snd_pcm_format_t fmt_;
- unsigned int fr_bytes_;
-};
-
-TEST_F(MixTestSuiteS24_LE, MixFirst) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- EXPECT_EQ(0, memcmp(mix_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, MixTwo) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = Scale(src_buffer_[i], 2);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, MixTwoClip) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- src_buffer_[i] = 0x007fffff;
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0x007fffff;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, MixFirstMuted) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 1, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, MixFirstZeroVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, MixFirstHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = Scale(src_buffer_[i], 0.5);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, MixTwoSecondHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] + Scale(src_buffer_[i], 0.5);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleFullVolumeIncrement) {
- float increment = 0.01;
- int step = 2;
- float start_scaler = 0.999999999;
- float target = 1.0;
-
- _SetupBuffer();
- // Scale full volume with positive increment will not change buffer.
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleMinVolumeIncrement) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.000000001;
- float target = 0.0;
-
- _SetupBuffer();
- // Scale min volume with negative increment will change buffer to zeros.
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleVolumePositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleVolumeNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleVolumeStartFullNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 1.0;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleVolumeStartZeroPositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.0;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleVolumePositiveIncrementCappedByTarget) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleVolumeNegativeIncrementCappedByTarget) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleFullVolume) {
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_);
- cras_scale_buffer(fmt_, (uint8_t*)mix_buffer_, kNumSamples, 0.999999999);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleMinVolume) {
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.0000000001);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, ScaleHalfVolume) {
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = Scale(src_buffer_[i], 0.5);
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.5);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_LE, StrideCopy) {
- TestScaleStride(1.0);
- TestScaleStride(100);
- TestScaleStride(0.1);
-}
-
-class MixTestSuiteS32_LE : public testing::Test {
- protected:
- virtual void SetUp() {
- fmt_ = SND_PCM_FORMAT_S32_LE;
- fr_bytes_ = 4 * kNumChannels;
- mix_buffer_ = (int32_t*)malloc(kBufferFrames * fr_bytes_);
- src_buffer_ = static_cast<int32_t*>(
- calloc(1, kBufferFrames * fr_bytes_ + sizeof(cras_audio_shm_header)));
-
- for (size_t i = 0; i < kBufferFrames * 2; i++) {
- src_buffer_[i] = i;
- mix_buffer_[i] = -i;
- }
-
- compare_buffer_ = (int32_t*)malloc(kBufferFrames * fr_bytes_);
- }
-
- virtual void TearDown() {
- free(mix_buffer_);
- free(compare_buffer_);
- free(src_buffer_);
- }
-
- void _SetupBuffer() {
- for (size_t i = 0; i < kBufferFrames; i++) {
- src_buffer_[i] = i + (INT32_MAX >> 2);
- mix_buffer_[i] = i + (INT32_MAX >> 2);
- compare_buffer_[i] = mix_buffer_[i];
- }
- for (size_t i = kBufferFrames; i < kBufferFrames * 2; i++) {
- src_buffer_[i] = i - (INT32_MAX >> 2);
- mix_buffer_[i] = i - (INT32_MAX >> 2);
- compare_buffer_[i] = mix_buffer_[i];
- }
- }
-
- void TestScaleStride(float scaler) {
- _SetupBuffer();
- for (size_t i = 0; i < kBufferFrames * 2; i += 2) {
- int64_t tmp;
- if (need_to_scale(scaler))
- tmp = mix_buffer_[i] + src_buffer_[i / 2] * scaler;
- else
- tmp = mix_buffer_[i] + src_buffer_[i / 2];
- if (tmp > INT32_MAX)
- tmp = INT32_MAX;
- else if (tmp < INT32_MIN)
- tmp = INT32_MIN;
- compare_buffer_[i] = tmp;
- }
-
- cras_mix_add_scale_stride(fmt_, (uint8_t*)mix_buffer_,
- (uint8_t*)src_buffer_, kBufferFrames, 8, 4,
- scaler);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 8));
- }
-
- void ScaleIncrement(float start_scaler, float increment, float target) {
- float scaler = start_scaler;
-
- for (size_t i = 0; i < kBufferFrames * 2; i++) {
- float applied_scaler = scaler;
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > kMaxVolumeToScale) {
- } else if (applied_scaler < kMinVolumeToScale) {
- compare_buffer_[i] = 0;
- } else {
- compare_buffer_[i] = mix_buffer_[i] * applied_scaler;
- }
-
- if (i % 2 == 1)
- scaler += increment;
- }
- }
-
- int32_t* mix_buffer_;
- int32_t* src_buffer_;
- int32_t* compare_buffer_;
- snd_pcm_format_t fmt_;
- unsigned int fr_bytes_;
-};
-
-TEST_F(MixTestSuiteS32_LE, MixFirst) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- EXPECT_EQ(0, memcmp(mix_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, MixTwo) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] * 2;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, MixTwoClip) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- src_buffer_[i] = INT32_MAX;
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = INT32_MAX;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, MixFirstMuted) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 1, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, MixFirstZeroVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.0);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = 0;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, MixFirstHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] * 0.5;
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, MixTwoSecondHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] + (int32_t)(src_buffer_[i] * 0.5);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleFullVolumeIncrement) {
- float increment = 0.01;
- int step = 2;
- float start_scaler = 0.999999999;
- float target = 1.0;
-
- _SetupBuffer();
- // Scale full volume with positive increment will not change buffer.
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleMinVolumeIncrement) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.000000001;
- float target = 0.0;
-
- _SetupBuffer();
- // Scale min volume with negative increment will change buffer to zeros.
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleVolumePositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleVolumeNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleVolumeStartFullNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 1.0;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleVolumeStartZeroPositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.0;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleVolumePositiveIncrementCappedByTarget) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleVolumeNegativeIncrementCappedByTarget) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleFullVolume) {
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_);
- cras_scale_buffer(fmt_, (uint8_t*)mix_buffer_, kNumSamples, 0.999999999);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleMinVolume) {
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.0000000001);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, ScaleHalfVolume) {
- for (size_t i = 0; i < kBufferFrames * 2; i++)
- compare_buffer_[i] = src_buffer_[i] * 0.5;
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.5);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS32_LE, StrideCopy) {
- TestScaleStride(1.0);
- TestScaleStride(100);
- TestScaleStride(0.1);
-}
-
-class MixTestSuiteS24_3LE : public testing::Test {
- protected:
- virtual void SetUp() {
- fmt_ = SND_PCM_FORMAT_S24_3LE;
- fr_bytes_ = 3 * kNumChannels;
- mix_buffer_ = (uint8_t*)malloc(kBufferFrames * fr_bytes_);
- src_buffer_ = static_cast<uint8_t*>(
- calloc(1, kBufferFrames * fr_bytes_ + sizeof(cras_audio_shm_header)));
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- memcpy(src_buffer_ + 3 * i, &i, 3);
- int32_t tmp = -i * 256;
- memcpy(mix_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
-
- compare_buffer_ = (uint8_t*)malloc(kBufferFrames * fr_bytes_);
- }
-
- virtual void TearDown() {
- free(mix_buffer_);
- free(compare_buffer_);
- free(src_buffer_);
- }
-
- void _SetupBuffer() {
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- for (size_t i = 0; i < kBufferFrames; i++) {
- int32_t tmp = (i << 8) + (INT32_MAX >> 2);
- memcpy(src_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- memcpy(mix_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- for (size_t i = kBufferFrames; i < kBufferFrames * 2; i++) {
- int32_t tmp = (i << 8) - (INT32_MAX >> 2);
- memcpy(src_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- memcpy(mix_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- }
-
- void TestScaleStride(float scaler) {
- _SetupBuffer();
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i += 2) {
- int64_t tmp;
- int32_t src_frame = 0;
- int32_t dst_frame = 0;
- memcpy((uint8_t*)&src_frame + 1, src_buffer_ + 3 * i / 2, 3);
- memcpy((uint8_t*)&dst_frame + 1, mix_buffer_ + 3 * i, 3);
- if (need_to_scale(scaler))
- tmp = (int64_t)dst_frame + (int64_t)src_frame * scaler;
- else
- tmp = (int64_t)dst_frame + (int64_t)src_frame;
- if (tmp > INT32_MAX)
- tmp = INT32_MAX;
- else if (tmp < INT32_MIN)
- tmp = INT32_MIN;
- dst_frame = (int32_t)tmp;
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&dst_frame + 1, 3);
- }
-
- cras_mix_add_scale_stride(fmt_, (uint8_t*)mix_buffer_,
- (uint8_t*)src_buffer_, kBufferFrames, 6, 3,
- scaler);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 6));
- }
-
- void ScaleIncrement(float start_scaler, float increment, float target) {
- float scaler = start_scaler;
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- float applied_scaler = scaler;
- int32_t tmp = 0;
- memcpy((uint8_t*)&tmp + 1, src_buffer_ + 3 * i, 3);
-
- if ((applied_scaler > target && increment > 0) ||
- (applied_scaler < target && increment < 0))
- applied_scaler = target;
-
- if (applied_scaler > kMaxVolumeToScale) {
- } else if (applied_scaler < kMinVolumeToScale) {
- tmp = 0;
- } else {
- tmp *= applied_scaler;
- }
-
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
-
- if (i % 2 == 1)
- scaler += increment;
- }
- }
-
- uint8_t* mix_buffer_;
- uint8_t* src_buffer_;
- uint8_t* compare_buffer_;
- snd_pcm_format_t fmt_;
- unsigned int fr_bytes_;
-};
-
-TEST_F(MixTestSuiteS24_3LE, MixFirst) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- EXPECT_EQ(0, memcmp(mix_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, MixTwo) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- int32_t tmp = 0;
- memcpy((uint8_t*)&tmp + 1, src_buffer_ + 3 * i, 3);
- tmp *= 2;
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, MixTwoClip) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- int32_t tmp = INT32_MAX;
- memcpy(src_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- int32_t tmp = INT32_MAX;
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, MixFirstMuted) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 1, 1.0);
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++)
- memset(compare_buffer_ + 3 * i, 0, 3);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, MixFirstZeroVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.0);
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++)
- memset(compare_buffer_ + 3 * i, 0, 3);
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, MixFirstHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- int32_t tmp = 0;
- memcpy((uint8_t*)&tmp + 1, src_buffer_ + 3 * i, 3);
- tmp *= 0.5;
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, MixTwoSecondHalfVolume) {
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 0, 0, 1.0);
- cras_mix_add(fmt_, (uint8_t*)mix_buffer_, (uint8_t*)src_buffer_, kNumSamples,
- 1, 0, 0.5);
-
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- int32_t tmp1 = 0, tmp2 = 0;
- memcpy((uint8_t*)&tmp1 + 1, src_buffer_ + 3 * i, 3);
- memcpy((uint8_t*)&tmp2 + 1, src_buffer_ + 3 * i, 3);
- tmp1 = tmp1 + (int32_t)(tmp2 * 0.5);
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp1 + 1, 3);
- }
- EXPECT_EQ(0, memcmp(mix_buffer_, compare_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleFullVolumeIncrement) {
- float increment = 0.01;
- int step = 2;
- float start_scaler = 0.999999999;
- float target = 1.0;
-
- _SetupBuffer();
- // Scale full volume with positive increment will not change buffer.
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleMinVolumeIncrement) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.000000001;
- float target = 0.0;
-
- _SetupBuffer();
- // Scale min volume with negative increment will change buffer to zeros.
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleVolumePositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleVolumeNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleVolumeStartFullNegativeIncrement) {
- float increment = -0.0001;
- int step = 2;
- float start_scaler = 1.0;
- float target = 0.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleVolumeStartZeroPositiveIncrement) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.0;
- float target = 1.0;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * 4));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleVolumePositiveIncrementCappedByTarget) {
- float increment = 0.0001;
- int step = 2;
- float start_scaler = 0.1;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleVolumeNegativeIncrementCappedByTarget) {
- float increment = -0.01;
- int step = 2;
- float start_scaler = 0.8;
- float target = 0.5;
-
- _SetupBuffer();
- ScaleIncrement(start_scaler, increment, target);
-
- cras_scale_buffer_increment(fmt_, (uint8_t*)mix_buffer_, kBufferFrames,
- start_scaler, increment, target, step);
- EXPECT_EQ(0, memcmp(compare_buffer_, mix_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleFullVolume) {
- memcpy(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_);
- cras_scale_buffer(fmt_, (uint8_t*)mix_buffer_, kNumSamples, 0.999999999);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleMinVolume) {
- memset(compare_buffer_, 0, kBufferFrames * fr_bytes_);
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.0000000001);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, ScaleHalfVolume) {
- for (size_t i = 0; i < kBufferFrames * kNumChannels; i++) {
- int32_t tmp = 0;
- memcpy((uint8_t*)&tmp + 1, src_buffer_ + 3 * i, 3);
- tmp *= 0.5;
- memcpy(compare_buffer_ + 3 * i, (uint8_t*)&tmp + 1, 3);
- }
- cras_scale_buffer(fmt_, (uint8_t*)src_buffer_, kNumSamples, 0.5);
-
- EXPECT_EQ(0, memcmp(compare_buffer_, src_buffer_, kBufferFrames * fr_bytes_));
-}
-
-TEST_F(MixTestSuiteS24_3LE, StrideCopy) {
- TestScaleStride(1.0);
- TestScaleStride(100);
- TestScaleStride(0.1);
-}
-
-/* Stubs */
-extern "C" {} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/observer_unittest.cc b/cras/src/tests/observer_unittest.cc
deleted file mode 100644
index 2a8fae2c..00000000
--- a/cras/src/tests/observer_unittest.cc
+++ /dev/null
@@ -1,726 +0,0 @@
-// Copyright 2016 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <syslog.h>
-
-#include <map>
-#include <vector>
-
-extern "C" {
-#include "cras_observer.c"
-#include "cras_observer.h"
-#include "cras_types.h"
-}
-
-namespace {
-
-static size_t cras_alert_destroy_called;
-static size_t cras_alert_create_called;
-static std::vector<struct cras_alert*> cras_alert_create_return_values;
-typedef std::map<struct cras_alert*, void*> alert_callback_map;
-static alert_callback_map cras_alert_create_prepare_map;
-static alert_callback_map cras_alert_add_callback_map;
-typedef std::map<struct cras_alert*, unsigned int> alert_flags_map;
-static alert_flags_map cras_alert_create_flags_map;
-static struct cras_alert* cras_alert_pending_alert_value;
-static void* cras_alert_pending_data_value = NULL;
-static size_t cras_alert_pending_data_size_value;
-static size_t cras_iodev_list_update_device_list_called;
-static std::vector<void*> cb_context;
-static size_t cb_output_volume_changed_called;
-static std::vector<int32_t> cb_output_volume_changed_volume;
-static size_t cb_output_mute_changed_called;
-static std::vector<int> cb_output_mute_changed_muted;
-static std::vector<int> cb_output_mute_changed_user_muted;
-static std::vector<int> cb_output_mute_changed_mute_locked;
-static size_t cb_capture_gain_changed_called;
-static std::vector<int32_t> cb_capture_gain_changed_gain;
-static size_t cb_capture_mute_changed_called;
-static std::vector<int> cb_capture_mute_changed_muted;
-static std::vector<int> cb_capture_mute_changed_mute_locked;
-static size_t cb_nodes_changed_called;
-static size_t cb_active_node_changed_called;
-static std::vector<enum CRAS_STREAM_DIRECTION> cb_active_node_changed_dir;
-static std::vector<cras_node_id_t> cb_active_node_changed_node_id;
-static size_t cb_output_node_volume_changed_called;
-static std::vector<cras_node_id_t> cb_output_node_volume_changed_node_id;
-static std::vector<int32_t> cb_output_node_volume_changed_volume;
-static size_t cb_node_left_right_swapped_changed_called;
-static std::vector<cras_node_id_t> cb_node_left_right_swapped_changed_node_id;
-static std::vector<int> cb_node_left_right_swapped_changed_swapped;
-static size_t cb_input_node_gain_changed_called;
-static std::vector<cras_node_id_t> cb_input_node_gain_changed_node_id;
-static std::vector<int32_t> cb_input_node_gain_changed_gain;
-static size_t cb_num_active_streams_changed_called;
-static std::vector<enum CRAS_STREAM_DIRECTION>
- cb_num_active_streams_changed_dir;
-static std::vector<uint32_t> cb_num_active_streams_changed_num;
-static size_t cb_num_input_streams_with_permission_called;
-static std::vector<std::vector<uint32_t>>
- cb_num_input_streams_with_permission_array;
-
-static void ResetStubData() {
- cras_alert_destroy_called = 0;
- cras_alert_create_called = 0;
- cras_alert_create_return_values.clear();
- cras_alert_create_prepare_map.clear();
- cras_alert_create_flags_map.clear();
- cras_alert_add_callback_map.clear();
- cras_alert_pending_alert_value = NULL;
- cras_alert_pending_data_size_value = 0;
- if (cras_alert_pending_data_value) {
- free(cras_alert_pending_data_value);
- cras_alert_pending_data_value = NULL;
- }
- cras_iodev_list_update_device_list_called = 0;
- cb_context.clear();
- cb_output_volume_changed_called = 0;
- cb_output_volume_changed_volume.clear();
- cb_output_mute_changed_called = 0;
- cb_output_mute_changed_muted.clear();
- cb_output_mute_changed_user_muted.clear();
- cb_output_mute_changed_mute_locked.clear();
- cb_capture_gain_changed_called = 0;
- cb_capture_gain_changed_gain.clear();
- cb_capture_mute_changed_called = 0;
- cb_capture_mute_changed_muted.clear();
- cb_capture_mute_changed_mute_locked.clear();
- cb_nodes_changed_called = 0;
- cb_active_node_changed_called = 0;
- cb_active_node_changed_dir.clear();
- cb_active_node_changed_node_id.clear();
- cb_output_node_volume_changed_called = 0;
- cb_output_node_volume_changed_node_id.clear();
- cb_output_node_volume_changed_volume.clear();
- cb_node_left_right_swapped_changed_called = 0;
- cb_node_left_right_swapped_changed_node_id.clear();
- cb_node_left_right_swapped_changed_swapped.clear();
- cb_input_node_gain_changed_called = 0;
- cb_input_node_gain_changed_node_id.clear();
- cb_input_node_gain_changed_gain.clear();
- cb_num_active_streams_changed_called = 0;
- cb_num_active_streams_changed_dir.clear();
- cb_num_active_streams_changed_num.clear();
- cb_num_input_streams_with_permission_called = 0;
- cb_num_input_streams_with_permission_array.clear();
-}
-
-/* System output volume changed. */
-void cb_output_volume_changed(void* context, int32_t volume) {
- cb_output_volume_changed_called++;
- cb_context.push_back(context);
- cb_output_volume_changed_volume.push_back(volume);
-}
-/* System output mute changed. */
-void cb_output_mute_changed(void* context,
- int muted,
- int user_muted,
- int mute_locked) {
- cb_output_mute_changed_called++;
- cb_context.push_back(context);
- cb_output_mute_changed_muted.push_back(muted);
- cb_output_mute_changed_user_muted.push_back(user_muted);
- cb_output_mute_changed_mute_locked.push_back(mute_locked);
-}
-/* System input/capture gain changed. */
-void cb_capture_gain_changed(void* context, int32_t gain) {
- cb_capture_gain_changed_called++;
- cb_context.push_back(context);
- cb_capture_gain_changed_gain.push_back(gain);
-}
-
-/* System input/capture mute changed. */
-void cb_capture_mute_changed(void* context, int muted, int mute_locked) {
- cb_capture_mute_changed_called++;
- cb_context.push_back(context);
- cb_capture_mute_changed_muted.push_back(muted);
- cb_capture_mute_changed_mute_locked.push_back(mute_locked);
-}
-
-/* Device or node topology changed. */
-void cb_nodes_changed(void* context) {
- cb_nodes_changed_called++;
- cb_context.push_back(context);
-}
-
-/* Active node changed. A notification is sent for every change.
- * When there is no active node, node_id is 0. */
-void cb_active_node_changed(void* context,
- enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id) {
- cb_active_node_changed_called++;
- cb_context.push_back(context);
- cb_active_node_changed_dir.push_back(dir);
- cb_active_node_changed_node_id.push_back(node_id);
-}
-
-/* Output node volume changed. */
-void cb_output_node_volume_changed(void* context,
- cras_node_id_t node_id,
- int32_t volume) {
- cb_output_node_volume_changed_called++;
- cb_context.push_back(context);
- cb_output_node_volume_changed_node_id.push_back(node_id);
- cb_output_node_volume_changed_volume.push_back(volume);
-}
-
-/* Node left/right swapped state change. */
-void cb_node_left_right_swapped_changed(void* context,
- cras_node_id_t node_id,
- int swapped) {
- cb_node_left_right_swapped_changed_called++;
- cb_context.push_back(context);
- cb_node_left_right_swapped_changed_node_id.push_back(node_id);
- cb_node_left_right_swapped_changed_swapped.push_back(swapped);
-}
-
-/* Input gain changed. */
-void cb_input_node_gain_changed(void* context,
- cras_node_id_t node_id,
- int32_t gain) {
- cb_input_node_gain_changed_called++;
- cb_context.push_back(context);
- cb_input_node_gain_changed_node_id.push_back(node_id);
- cb_input_node_gain_changed_gain.push_back(gain);
-}
-
-/* Number of active streams changed. */
-void cb_num_active_streams_changed(void* context,
- enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams) {
- cb_num_active_streams_changed_called++;
- cb_context.push_back(context);
- cb_num_active_streams_changed_dir.push_back(dir);
- cb_num_active_streams_changed_num.push_back(num_active_streams);
-}
-
-void cb_num_input_streams_with_permission_changed(
- void* context,
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE]) {
- cb_num_input_streams_with_permission_called++;
- cb_context.push_back(context);
- cb_num_input_streams_with_permission_array.push_back(std::vector<uint32_t>(
- num_input_streams, num_input_streams + CRAS_NUM_CLIENT_TYPE));
-}
-
-class ObserverTest : public testing::Test {
- protected:
- virtual void SetUp() {
- int rc;
-
- ResetStubData();
- rc = cras_observer_server_init();
- ASSERT_EQ(0, rc);
- EXPECT_EQ(17, cras_alert_create_called);
- EXPECT_EQ(reinterpret_cast<void*>(output_volume_alert),
- cras_alert_add_callback_map[g_observer->alerts.output_volume]);
- EXPECT_EQ(reinterpret_cast<void*>(output_mute_alert),
- cras_alert_add_callback_map[g_observer->alerts.output_mute]);
- EXPECT_EQ(reinterpret_cast<void*>(capture_gain_alert),
- cras_alert_add_callback_map[g_observer->alerts.capture_gain]);
- EXPECT_EQ(reinterpret_cast<void*>(capture_mute_alert),
- cras_alert_add_callback_map[g_observer->alerts.capture_mute]);
- EXPECT_EQ(reinterpret_cast<void*>(nodes_alert),
- cras_alert_add_callback_map[g_observer->alerts.nodes]);
- EXPECT_EQ(reinterpret_cast<void*>(nodes_prepare),
- cras_alert_create_prepare_map[g_observer->alerts.nodes]);
- EXPECT_EQ(reinterpret_cast<void*>(active_node_alert),
- cras_alert_add_callback_map[g_observer->alerts.active_node]);
- EXPECT_EQ(CRAS_ALERT_FLAG_KEEP_ALL_DATA,
- cras_alert_create_flags_map[g_observer->alerts.active_node]);
- EXPECT_EQ(
- reinterpret_cast<void*>(output_node_volume_alert),
- cras_alert_add_callback_map[g_observer->alerts.output_node_volume]);
- EXPECT_EQ(reinterpret_cast<void*>(node_left_right_swapped_alert),
- cras_alert_add_callback_map[g_observer->alerts
- .node_left_right_swapped]);
- EXPECT_EQ(reinterpret_cast<void*>(input_node_gain_alert),
- cras_alert_add_callback_map[g_observer->alerts.input_node_gain]);
- EXPECT_EQ(reinterpret_cast<void*>(num_active_streams_alert),
- cras_alert_add_callback_map
- [g_observer->alerts.num_active_streams[CRAS_STREAM_OUTPUT]]);
- EXPECT_EQ(reinterpret_cast<void*>(num_active_streams_alert),
- cras_alert_add_callback_map
- [g_observer->alerts.num_active_streams[CRAS_STREAM_INPUT]]);
- EXPECT_EQ(reinterpret_cast<void*>(num_active_streams_alert),
- cras_alert_add_callback_map[g_observer->alerts.num_active_streams
- [CRAS_STREAM_POST_MIX_PRE_DSP]]);
- EXPECT_EQ(reinterpret_cast<void*>(suspend_changed_alert),
- cras_alert_add_callback_map[g_observer->alerts.suspend_changed]);
- EXPECT_EQ(
- reinterpret_cast<void*>(hotword_triggered_alert),
- cras_alert_add_callback_map[g_observer->alerts.hotword_triggered]);
- EXPECT_EQ(reinterpret_cast<void*>(non_empty_audio_state_changed_alert),
- cras_alert_add_callback_map[g_observer->alerts
- .non_empty_audio_state_changed]);
- EXPECT_EQ(
- reinterpret_cast<void*>(bt_battery_changed_alert),
- cras_alert_add_callback_map[g_observer->alerts.bt_battery_changed]);
-
- cras_observer_get_ops(NULL, &ops1_);
- EXPECT_NE(0, cras_observer_ops_are_empty(&ops1_));
-
- cras_observer_get_ops(NULL, &ops2_);
- EXPECT_NE(0, cras_observer_ops_are_empty(&ops2_));
-
- context1_ = reinterpret_cast<void*>(1);
- context2_ = reinterpret_cast<void*>(2);
- }
-
- virtual void TearDown() {
- cras_observer_server_free();
- EXPECT_EQ(17, cras_alert_destroy_called);
- ResetStubData();
- }
-
- void DoObserverAlert(cras_alert_cb alert, void* data) {
- client1_ = cras_observer_add(&ops1_, context1_);
- client2_ = cras_observer_add(&ops2_, context2_);
- ASSERT_NE(client1_, reinterpret_cast<struct cras_observer_client*>(NULL));
- ASSERT_NE(client2_, reinterpret_cast<struct cras_observer_client*>(NULL));
-
- ASSERT_NE(alert, reinterpret_cast<cras_alert_cb>(NULL));
- alert(NULL, data);
-
- EXPECT_EQ(cb_context[0], context1_);
- EXPECT_EQ(cb_context[1], context2_);
- }
-
- void DoObserverRemoveClear(cras_alert_cb alert, void* data) {
- ASSERT_NE(alert, reinterpret_cast<cras_alert_cb>(NULL));
- ASSERT_NE(client1_, reinterpret_cast<struct cras_observer_client*>(NULL));
- ASSERT_NE(client2_, reinterpret_cast<struct cras_observer_client*>(NULL));
-
- // Test observer removal.
- cras_observer_remove(client1_);
- cb_context.clear();
- alert(NULL, data);
- EXPECT_EQ(cb_context[0], context2_);
- EXPECT_EQ(cb_context.size(), 1);
-
- // Clear out ops1_.
- cras_observer_get_ops(NULL, &ops1_);
- EXPECT_NE(0, cras_observer_ops_are_empty(&ops1_));
-
- // Get the current value of ops2_ into ops1_.
- cras_observer_get_ops(client2_, &ops1_);
- EXPECT_EQ(0, memcmp((void*)&ops1_, (void*)&ops2_, sizeof(ops1_)));
-
- // Clear out opts for client2.
- cras_observer_get_ops(NULL, &ops2_);
- EXPECT_NE(0, cras_observer_ops_are_empty(&ops2_));
- cras_observer_set_ops(client2_, &ops2_);
-
- cras_observer_remove(client2_);
- cb_context.clear();
- alert(NULL, data);
- // No callbacks executed.
- EXPECT_EQ(cb_context.size(), 0);
- }
-
- struct cras_observer_client* client1_;
- struct cras_observer_client* client2_;
- struct cras_observer_ops ops1_;
- struct cras_observer_ops ops2_;
- void* context1_;
- void* context2_;
-};
-
-TEST_F(ObserverTest, NotifyOutputVolume) {
- struct cras_observer_alert_data_volume* data;
- const int32_t volume = 100;
-
- cras_observer_notify_output_volume(volume);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.output_volume);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_volume*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->volume, volume);
-
- ops1_.output_volume_changed = cb_output_volume_changed;
- ops2_.output_volume_changed = cb_output_volume_changed;
- DoObserverAlert(output_volume_alert, data);
- ASSERT_EQ(2, cb_output_volume_changed_called);
- EXPECT_EQ(cb_output_volume_changed_volume[0], volume);
- EXPECT_EQ(cb_output_volume_changed_volume[1], volume);
-
- DoObserverRemoveClear(output_volume_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyOutputMute) {
- struct cras_observer_alert_data_mute* data;
- const int muted = 1;
- const int user_muted = 0;
- const int mute_locked = 0;
-
- cras_observer_notify_output_mute(muted, user_muted, mute_locked);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.output_mute);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_mute*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->muted, muted);
- EXPECT_EQ(data->user_muted, user_muted);
- EXPECT_EQ(data->mute_locked, mute_locked);
-
- ops1_.output_mute_changed = cb_output_mute_changed;
- ops2_.output_mute_changed = cb_output_mute_changed;
- DoObserverAlert(output_mute_alert, data);
- ASSERT_EQ(2, cb_output_mute_changed_called);
- EXPECT_EQ(cb_output_mute_changed_muted[0], muted);
- EXPECT_EQ(cb_output_mute_changed_muted[1], muted);
- EXPECT_EQ(cb_output_mute_changed_user_muted[0], user_muted);
- EXPECT_EQ(cb_output_mute_changed_user_muted[1], user_muted);
- EXPECT_EQ(cb_output_mute_changed_mute_locked[0], mute_locked);
- EXPECT_EQ(cb_output_mute_changed_mute_locked[1], mute_locked);
-
- DoObserverRemoveClear(output_mute_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyCaptureGain) {
- struct cras_observer_alert_data_volume* data;
- const int32_t gain = -20;
-
- cras_observer_notify_capture_gain(gain);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.capture_gain);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_volume*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->volume, gain);
-
- ops1_.capture_gain_changed = cb_capture_gain_changed;
- ops2_.capture_gain_changed = cb_capture_gain_changed;
- DoObserverAlert(capture_gain_alert, data);
- ASSERT_EQ(2, cb_capture_gain_changed_called);
- EXPECT_EQ(cb_capture_gain_changed_gain[0], gain);
- EXPECT_EQ(cb_capture_gain_changed_gain[1], gain);
-
- DoObserverRemoveClear(capture_gain_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyCaptureMute) {
- struct cras_observer_alert_data_mute* data;
- const int muted = 1;
- const int mute_locked = 0;
-
- cras_observer_notify_capture_mute(muted, mute_locked);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.capture_mute);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_mute*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->muted, muted);
- EXPECT_EQ(data->mute_locked, mute_locked);
-
- ops1_.capture_mute_changed = cb_capture_mute_changed;
- ops2_.capture_mute_changed = cb_capture_mute_changed;
- DoObserverAlert(capture_mute_alert, data);
- ASSERT_EQ(2, cb_capture_mute_changed_called);
- EXPECT_EQ(cb_capture_mute_changed_muted[0], muted);
- EXPECT_EQ(cb_capture_mute_changed_muted[1], muted);
- EXPECT_EQ(cb_capture_mute_changed_mute_locked[0], mute_locked);
- EXPECT_EQ(cb_capture_mute_changed_mute_locked[1], mute_locked);
-
- DoObserverRemoveClear(capture_mute_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyNodes) {
- cras_observer_notify_nodes();
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.nodes);
-
- ops1_.nodes_changed = cb_nodes_changed;
- ops2_.nodes_changed = cb_nodes_changed;
- DoObserverAlert(nodes_alert, NULL);
- ASSERT_EQ(2, cb_nodes_changed_called);
-
- DoObserverRemoveClear(nodes_alert, NULL);
-};
-
-TEST_F(ObserverTest, NotifyActiveNode) {
- struct cras_observer_alert_data_active_node* data;
- const enum CRAS_STREAM_DIRECTION dir = CRAS_STREAM_INPUT;
- const cras_node_id_t node_id = 0x0001000100020002;
-
- cras_observer_notify_active_node(dir, node_id);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.active_node);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_active_node*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->node_id, node_id);
- EXPECT_EQ(data->direction, dir);
-
- ops1_.active_node_changed = cb_active_node_changed;
- ops2_.active_node_changed = cb_active_node_changed;
- DoObserverAlert(active_node_alert, data);
- ASSERT_EQ(2, cb_active_node_changed_called);
- EXPECT_EQ(cb_active_node_changed_dir[0], dir);
- EXPECT_EQ(cb_active_node_changed_dir[1], dir);
- EXPECT_EQ(cb_active_node_changed_node_id[0], node_id);
- EXPECT_EQ(cb_active_node_changed_node_id[1], node_id);
-
- DoObserverRemoveClear(active_node_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyOutputNodeVolume) {
- struct cras_observer_alert_data_node_volume* data;
- const cras_node_id_t node_id = 0x0001000100020002;
- const int32_t volume = 100;
-
- cras_observer_notify_output_node_volume(node_id, volume);
- EXPECT_EQ(cras_alert_pending_alert_value,
- g_observer->alerts.output_node_volume);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_node_volume*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->node_id, node_id);
- EXPECT_EQ(data->volume, volume);
-
- ops1_.output_node_volume_changed = cb_output_node_volume_changed;
- ops2_.output_node_volume_changed = cb_output_node_volume_changed;
- DoObserverAlert(output_node_volume_alert, data);
- ASSERT_EQ(2, cb_output_node_volume_changed_called);
- EXPECT_EQ(cb_output_node_volume_changed_volume[0], volume);
- EXPECT_EQ(cb_output_node_volume_changed_volume[1], volume);
- EXPECT_EQ(cb_output_node_volume_changed_node_id[0], node_id);
- EXPECT_EQ(cb_output_node_volume_changed_node_id[1], node_id);
-
- DoObserverRemoveClear(output_node_volume_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyNodeLeftRightSwapped) {
- struct cras_observer_alert_data_node_lr_swapped* data;
- const cras_node_id_t node_id = 0x0001000100020002;
- const int swapped = 1;
-
- cras_observer_notify_node_left_right_swapped(node_id, swapped);
- EXPECT_EQ(cras_alert_pending_alert_value,
- g_observer->alerts.node_left_right_swapped);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_node_lr_swapped*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->node_id, node_id);
- EXPECT_EQ(data->swapped, swapped);
-
- ops1_.node_left_right_swapped_changed = cb_node_left_right_swapped_changed;
- ops2_.node_left_right_swapped_changed = cb_node_left_right_swapped_changed;
- DoObserverAlert(node_left_right_swapped_alert, data);
- ASSERT_EQ(2, cb_node_left_right_swapped_changed_called);
- EXPECT_EQ(cb_node_left_right_swapped_changed_swapped[0], swapped);
- EXPECT_EQ(cb_node_left_right_swapped_changed_swapped[1], swapped);
- EXPECT_EQ(cb_node_left_right_swapped_changed_node_id[0], node_id);
- EXPECT_EQ(cb_node_left_right_swapped_changed_node_id[1], node_id);
-
- DoObserverRemoveClear(node_left_right_swapped_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyInputNodeGain) {
- struct cras_observer_alert_data_node_volume* data;
- const cras_node_id_t node_id = 0x0001000100020002;
- const int32_t gain = -20;
-
- cras_observer_notify_input_node_gain(node_id, gain);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.input_node_gain);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_node_volume*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->node_id, node_id);
- EXPECT_EQ(data->volume, gain);
-
- ops1_.input_node_gain_changed = cb_input_node_gain_changed;
- ops2_.input_node_gain_changed = cb_input_node_gain_changed;
- DoObserverAlert(input_node_gain_alert, data);
- ASSERT_EQ(2, cb_input_node_gain_changed_called);
- EXPECT_EQ(cb_input_node_gain_changed_gain[0], gain);
- EXPECT_EQ(cb_input_node_gain_changed_gain[1], gain);
- EXPECT_EQ(cb_input_node_gain_changed_node_id[0], node_id);
- EXPECT_EQ(cb_input_node_gain_changed_node_id[1], node_id);
-
- DoObserverRemoveClear(input_node_gain_alert, data);
-};
-
-TEST_F(ObserverTest, NotifySuspendChanged) {
- struct cras_observer_alert_data_suspend* data;
-
- cras_observer_notify_suspend_changed(1);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.suspend_changed);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_suspend*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->suspended, 1);
-
- cras_observer_notify_suspend_changed(0);
- EXPECT_EQ(cras_alert_pending_alert_value, g_observer->alerts.suspend_changed);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_suspend*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->suspended, 0);
-}
-
-TEST_F(ObserverTest, NotifyNumActiveStreams) {
- struct cras_observer_alert_data_streams* data;
- const enum CRAS_STREAM_DIRECTION dir = CRAS_STREAM_INPUT;
- const uint32_t active_streams = 10;
-
- cras_observer_notify_num_active_streams(dir, active_streams);
- EXPECT_EQ(cras_alert_pending_alert_value,
- g_observer->alerts.num_active_streams[CRAS_STREAM_INPUT]);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_streams*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->num_active_streams, active_streams);
- EXPECT_EQ(data->direction, dir);
-
- ops1_.num_active_streams_changed = cb_num_active_streams_changed;
- ops2_.num_active_streams_changed = cb_num_active_streams_changed;
- DoObserverAlert(num_active_streams_alert, data);
- ASSERT_EQ(2, cb_num_active_streams_changed_called);
- EXPECT_EQ(cb_num_active_streams_changed_dir[0], dir);
- EXPECT_EQ(cb_num_active_streams_changed_dir[1], dir);
- EXPECT_EQ(cb_num_active_streams_changed_num[0], active_streams);
- EXPECT_EQ(cb_num_active_streams_changed_num[1], active_streams);
-
- DoObserverRemoveClear(num_active_streams_alert, data);
-};
-
-TEST_F(ObserverTest, NotifyNumInputStreamsWithPermission) {
- struct cras_observer_alert_data_input_streams* data;
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE] = {};
- for (unsigned type = 0; type < CRAS_NUM_CLIENT_TYPE; ++type) {
- num_input_streams[type] = (uint32_t)type;
- }
-
- cras_observer_notify_input_streams_with_permission(num_input_streams);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_input_streams*>(
- cras_alert_pending_data_value);
- for (unsigned type = 0; type < CRAS_NUM_CLIENT_TYPE; ++type) {
- EXPECT_EQ(data->num_input_streams[type], num_input_streams[type]);
- }
-
- ops1_.num_input_streams_with_permission_changed =
- cb_num_input_streams_with_permission_changed;
- ops2_.num_input_streams_with_permission_changed =
- cb_num_input_streams_with_permission_changed;
- DoObserverAlert(num_input_streams_with_permission_alert, data);
- ASSERT_EQ(2, cb_num_input_streams_with_permission_called);
- for (auto cb_num_input_streams : cb_num_input_streams_with_permission_array) {
- ASSERT_EQ(cb_num_input_streams.size(), (size_t)CRAS_NUM_CLIENT_TYPE);
- for (unsigned type = 0; type < CRAS_NUM_CLIENT_TYPE; ++type) {
- EXPECT_EQ(cb_num_input_streams[type], num_input_streams[type]);
- }
- }
- DoObserverRemoveClear(num_input_streams_with_permission_alert, data);
-}
-
-TEST_F(ObserverTest, NotifyHotwordTriggered) {
- struct cras_observer_alert_data_hotword_triggered* data;
-
- cras_observer_notify_hotword_triggered(100, 200);
- EXPECT_EQ(cras_alert_pending_alert_value,
- g_observer->alerts.hotword_triggered);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_hotword_triggered*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->tv_sec, 100);
- EXPECT_EQ(data->tv_nsec, 200);
-}
-
-TEST_F(ObserverTest, NonEmpyAudioStateChanged) {
- struct cras_observer_non_empty_audio_state* data;
-
- cras_observer_notify_non_empty_audio_state_changed(1);
- EXPECT_EQ(cras_alert_pending_alert_value,
- g_observer->alerts.non_empty_audio_state_changed);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_non_empty_audio_state*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->non_empty, 1);
-}
-
-TEST_F(ObserverTest, BluetoothBatteryChanged) {
- struct cras_observer_alert_data_bt_battery_changed* data;
- const char* address = "test";
-
- cras_observer_notify_bt_battery_changed(address, 30);
- EXPECT_EQ(cras_alert_pending_alert_value,
- g_observer->alerts.bt_battery_changed);
- ASSERT_EQ(cras_alert_pending_data_size_value, sizeof(*data));
- ASSERT_NE(cras_alert_pending_data_value, reinterpret_cast<void*>(NULL));
- data = reinterpret_cast<struct cras_observer_alert_data_bt_battery_changed*>(
- cras_alert_pending_data_value);
- EXPECT_EQ(data->address, address);
- EXPECT_EQ(data->level, 30);
-}
-
-// Stubs
-extern "C" {
-
-void cras_alert_destroy(struct cras_alert* alert) {
- cras_alert_destroy_called++;
-}
-
-struct cras_alert* cras_alert_create(cras_alert_prepare prepare,
- unsigned int flags) {
- struct cras_alert* alert = NULL;
-
- cras_alert_create_called++;
- alert = reinterpret_cast<struct cras_alert*>(cras_alert_create_called);
- cras_alert_create_return_values.push_back(alert);
- cras_alert_create_flags_map[alert] = flags;
- cras_alert_create_prepare_map[alert] = reinterpret_cast<void*>(prepare);
- return alert;
-}
-
-int cras_alert_add_callback(struct cras_alert* alert,
- cras_alert_cb cb,
- void* arg) {
- cras_alert_add_callback_map[alert] = reinterpret_cast<void*>(cb);
- return 0;
-}
-
-void cras_alert_pending(struct cras_alert* alert) {
- cras_alert_pending_alert_value = alert;
-}
-
-void cras_alert_pending_data(struct cras_alert* alert,
- void* data,
- size_t data_size) {
- cras_alert_pending_alert_value = alert;
- cras_alert_pending_data_size_value = data_size;
- if (cras_alert_pending_data_value)
- free(cras_alert_pending_data_value);
- if (data) {
- cras_alert_pending_data_value = malloc(data_size);
- memcpy(cras_alert_pending_data_value, data, data_size);
- } else
- cras_alert_pending_data_value = NULL;
-}
-
-void cras_iodev_list_update_device_list() {
- cras_iodev_list_update_device_list_called++;
-}
-
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/playback_rclient_unittest.cc b/cras/src/tests/playback_rclient_unittest.cc
deleted file mode 100644
index 31ceda74..00000000
--- a/cras/src/tests/playback_rclient_unittest.cc
+++ /dev/null
@@ -1,308 +0,0 @@
-// Copyright 2019 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <unistd.h>
-
-extern "C" {
-#include "audio_thread.h"
-#include "cras_bt_log.h"
-#include "cras_messages.h"
-#include "cras_rclient.h"
-#include "cras_rstream.h"
-#include "cras_system_state.h"
-
-// Access to data structures and static functions.
-#include "cras_playback_rclient.c"
-#include "cras_rclient_util.c"
-}
-static bool audio_format_valid;
-static unsigned int cras_make_fd_nonblocking_called;
-static unsigned int cras_observer_remove_called;
-static int stream_list_add_called;
-static int stream_list_add_return;
-static unsigned int stream_list_rm_called;
-static struct cras_audio_shm mock_shm;
-static struct cras_rstream mock_rstream;
-
-void ResetStubData() {
- audio_format_valid = true;
- cras_make_fd_nonblocking_called = 0;
- cras_observer_remove_called = 0;
- stream_list_add_called = 0;
- stream_list_add_return = 0;
- stream_list_rm_called = 0;
-}
-
-namespace {
-
-TEST(RClientSuite, CreateSendMessage) {
- struct cras_rclient* rclient;
- int rc;
- struct cras_client_connected msg;
- int pipe_fds[2];
-
- ResetStubData();
-
- rc = pipe(pipe_fds);
- ASSERT_EQ(0, rc);
-
- rclient = cras_playback_rclient_create(pipe_fds[1], 800);
- ASSERT_NE((void*)NULL, rclient);
- EXPECT_EQ(800, rclient->id);
-
- rc = read(pipe_fds[0], &msg, sizeof(msg));
- EXPECT_EQ(sizeof(msg), rc);
- EXPECT_EQ(CRAS_CLIENT_CONNECTED, msg.header.id);
-
- rclient->ops->destroy(rclient);
- EXPECT_EQ(1, cras_observer_remove_called);
- close(pipe_fds[0]);
- close(pipe_fds[1]);
-}
-
-class CPRMessageSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- int rc;
- struct cras_client_connected msg;
-
- rc = pipe(pipe_fds_);
- if (rc < 0)
- return;
-
- rclient_ = cras_playback_rclient_create(pipe_fds_[1], 1);
- rc = read(pipe_fds_[0], &msg, sizeof(msg));
- if (rc < 0)
- return;
-
- fmt = {
- .format = SND_PCM_FORMAT_S16_LE,
- .frame_rate = 48000,
- .num_channels = 2,
- };
- cras_audio_format_set_default_channel_layout(&fmt);
- ResetStubData();
- }
-
- virtual void TearDown() {
- rclient_->ops->destroy(rclient_);
- close(pipe_fds_[0]);
- close(pipe_fds_[1]);
- }
-
- struct cras_rclient* rclient_;
- struct cras_audio_format fmt;
- int pipe_fds_[2];
- int fd_;
-};
-
-TEST_F(CPRMessageSuite, StreamConnectMessage) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x10002;
- cras_fill_connect_message(&msg, CRAS_STREAM_OUTPUT, stream_id,
- CRAS_STREAM_TYPE_DEFAULT, CRAS_CLIENT_TYPE_UNKNOWN,
- 480, 240, /*flags=*/0, /*effects=*/0, fmt,
- NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- fd_ = 100;
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_, 1);
- EXPECT_EQ(1, cras_make_fd_nonblocking_called);
- EXPECT_EQ(1, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(stream_id, out_msg.stream_id);
-}
-
-TEST_F(CPRMessageSuite, StreamConnectMessageInvalidDirection) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x10002;
-
- for (int i = 0; i < CRAS_NUM_DIRECTIONS; i++) {
- const auto dir = static_cast<CRAS_STREAM_DIRECTION>(i);
- if (dir == CRAS_STREAM_OUTPUT)
- continue;
- cras_fill_connect_message(&msg, dir, stream_id, CRAS_STREAM_TYPE_DEFAULT,
- CRAS_CLIENT_TYPE_UNKNOWN, 480, 240, /*flags=*/0,
- /*effects=*/0, fmt, NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- fd_ = 100;
- rc = rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_,
- 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(stream_id, out_msg.stream_id);
- }
-}
-
-TEST_F(CPRMessageSuite, StreamConnectMessageInvalidClientId) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x20002; // stream_id with invalid client_id
- cras_fill_connect_message(&msg, CRAS_STREAM_OUTPUT, stream_id,
- CRAS_STREAM_TYPE_DEFAULT, CRAS_CLIENT_TYPE_UNKNOWN,
- 480, 240, /*flags=*/0, /*effects=*/0, fmt,
- NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- fd_ = 100;
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(stream_id, out_msg.stream_id);
-}
-
-TEST_F(CPRMessageSuite, StreamConnectMessageInvalidAudioFormat) {
- struct cras_client_stream_connected out_msg;
- int rc;
-
- struct cras_connect_message msg;
- cras_stream_id_t stream_id = 0x10002;
- cras_fill_connect_message(&msg, CRAS_STREAM_OUTPUT, stream_id,
- CRAS_STREAM_TYPE_DEFAULT, CRAS_CLIENT_TYPE_UNKNOWN,
- 480, 240, /*flags=*/0, /*effects=*/0, fmt,
- NO_DEVICE);
- ASSERT_EQ(stream_id, msg.stream_id);
-
- audio_format_valid = false; // stubs out verification failure.
-
- fd_ = 100;
- rc =
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, &fd_, 1);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, cras_make_fd_nonblocking_called);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-
- rc = read(pipe_fds_[0], &out_msg, sizeof(out_msg));
- EXPECT_EQ(sizeof(out_msg), rc);
- EXPECT_EQ(-EINVAL, out_msg.err);
- EXPECT_EQ(stream_id, out_msg.stream_id);
-}
-
-TEST_F(CPRMessageSuite, StreamDisconnectMessage) {
- struct cras_disconnect_stream_message msg;
- cras_stream_id_t stream_id = 0x10002;
- cras_fill_disconnect_stream_message(&msg, stream_id);
-
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(1, stream_list_rm_called);
-}
-
-TEST_F(CPRMessageSuite, StreamDisconnectMessageInvalidClientId) {
- struct cras_disconnect_stream_message msg;
- cras_stream_id_t stream_id = 0x20002; // stream_id with invalid client_id
- cras_fill_disconnect_stream_message(&msg, stream_id);
-
- rclient_->ops->handle_message_from_client(rclient_, &msg.header, NULL, 0);
- EXPECT_EQ(0, stream_list_add_called);
- EXPECT_EQ(0, stream_list_rm_called);
-}
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-/* stubs */
-extern "C" {
-
-struct stream_list* cras_iodev_list_get_stream_list() {
- return NULL;
-}
-
-int cras_make_fd_nonblocking(int fd) {
- cras_make_fd_nonblocking_called++;
- return 0;
-}
-
-void cras_observer_remove(struct cras_observer_client* client) {
- cras_observer_remove_called++;
-}
-
-unsigned int cras_rstream_get_effects(const struct cras_rstream* stream) {
- return 0;
-}
-
-int cras_send_with_fds(int sockfd,
- const void* buf,
- size_t len,
- int* fd,
- unsigned int num_fds) {
- return write(sockfd, buf, len);
-}
-
-key_t cras_sys_state_shm_fd() {
- return 1;
-}
-
-void cras_system_set_suspended(int suspended) {}
-
-int stream_list_rm_all_client_streams(struct stream_list* list,
- struct cras_rclient* rclient) {
- return 0;
-}
-
-int stream_list_rm(struct stream_list* list, cras_stream_id_t id) {
- stream_list_rm_called++;
- return 0;
-}
-
-int stream_list_add(struct stream_list* list,
- struct cras_rstream_config* config,
- struct cras_rstream** stream) {
- int ret;
-
- *stream = &mock_rstream;
-
- stream_list_add_called++;
- ret = stream_list_add_return;
- if (ret)
- stream_list_add_return = -EINVAL;
-
- mock_rstream.shm = &mock_shm;
- mock_rstream.direction = config->direction;
- mock_rstream.stream_id = config->stream_id;
-
- return ret;
-}
-
-bool cras_audio_format_valid(const struct cras_audio_format* fmt) {
- return audio_format_valid;
-}
-
-void detect_rtc_stream_pair(struct stream_list* list,
- struct cras_rstream* stream) {
- return;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/polled_interval_checker_unittest.cc b/cras/src/tests/polled_interval_checker_unittest.cc
deleted file mode 100644
index a4aff09c..00000000
--- a/cras/src/tests/polled_interval_checker_unittest.cc
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright 2018 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "polled_interval_checker.h"
-}
-
-static const int INTERVAL_DURATION = 5;
-
-static struct timespec time_now;
-
-static struct polled_interval* create_interval() {
- struct polled_interval* interval =
- pic_polled_interval_create(INTERVAL_DURATION);
- EXPECT_NE(interval, static_cast<struct polled_interval*>(NULL));
- return interval;
-}
-
-TEST(PolledIntervalCheckerTest, CreateDestroy) {
- // Create an interval, checks it is non-null.
- struct polled_interval* interval = create_interval();
-
- pic_polled_interval_destroy(&interval);
-
- // Check it's been set to null.
- EXPECT_EQ(interval, static_cast<struct polled_interval*>(NULL));
-}
-
-TEST(PolledIntervalCheckerTest, BasicFlow) {
- // Set initial time.
- time_now.tv_sec = 1000;
- time_now.tv_nsec = 0;
- pic_update_current_time();
-
- // Create interval starting at initial time.
- struct polled_interval* interval = create_interval();
-
- // Check it hasn't elapsed.
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Increment time by less than the interval duration.
- time_now.tv_sec += INTERVAL_DURATION / 2;
- pic_update_current_time();
-
- // Check the interval hasn't elapsed yet.
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Increment time past the duration of the interval.
- time_now.tv_sec += INTERVAL_DURATION;
-
- // We haven't updated the current time, check the interval hasn't
- // elapsed (that it isn't calling clock_gettime without us asking it to).
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Update time, check the interval has elapsed.
- pic_update_current_time();
- EXPECT_TRUE(pic_interval_elapsed(interval));
- pic_polled_interval_destroy(&interval);
-}
-
-TEST(PolledIntervalCheckerTest, DoesNotResetAutomatically) {
- // Set initial time.
- time_now.tv_sec = 1000;
- time_now.tv_nsec = 0;
- pic_update_current_time();
-
- struct polled_interval* interval = create_interval();
-
- // Initial check.
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Increment time so the interval elapses.
- time_now.tv_sec += INTERVAL_DURATION;
- pic_update_current_time();
-
- // Check the interval has elapsed.
- EXPECT_TRUE(pic_interval_elapsed(interval));
-
- // Increment time further.
- time_now.tv_sec += INTERVAL_DURATION * 2;
- pic_update_current_time();
-
- // Check the interval has still elapsed.
- EXPECT_TRUE(pic_interval_elapsed(interval));
-
- // Check repeated calls return true.
- EXPECT_TRUE(pic_interval_elapsed(interval));
- pic_polled_interval_destroy(&interval);
-}
-
-TEST(PolledIntervalCheckerTest, Reset) {
- // Set initial time.
- time_now.tv_sec = 1000;
- time_now.tv_nsec = 0;
- pic_update_current_time();
-
- struct polled_interval* interval = create_interval();
-
- // Initial check.
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Increment time so the interval elapses.
- time_now.tv_sec += INTERVAL_DURATION;
- pic_update_current_time();
-
- // Check the interval has elapsed.
- EXPECT_TRUE(pic_interval_elapsed(interval));
-
- // Increment time further.
- time_now.tv_sec += INTERVAL_DURATION * 2;
- pic_update_current_time();
-
- // Check the interval has still elapsed.
- EXPECT_TRUE(pic_interval_elapsed(interval));
-
- // Reset the interval.
- pic_interval_reset(interval);
-
- // Check it's been reset.
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Increment time to just before it should elapse again.
- time_now.tv_sec += INTERVAL_DURATION - 1;
- pic_update_current_time();
-
- // Check it still has not elapsed.
- EXPECT_FALSE(pic_interval_elapsed(interval));
-
- // Increment time to one duration after we reset it.
- time_now.tv_sec += 1;
- pic_update_current_time();
-
- // Check the interval has elapsed now.
- EXPECT_TRUE(pic_interval_elapsed(interval));
- pic_polled_interval_destroy(&interval);
-}
-
-/* Stubs */
-extern "C" {
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- *tp = time_now;
- return 0;
-}
-
-} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/ramp_unittest.cc b/cras/src/tests/ramp_unittest.cc
deleted file mode 100644
index a661dffe..00000000
--- a/cras/src/tests/ramp_unittest.cc
+++ /dev/null
@@ -1,513 +0,0 @@
-// Copyright 2016 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_ramp.c"
-}
-
-static int callback_called;
-static void* callback_arg;
-
-void ResetStubData() {
- callback_called = 0;
- callback_arg = NULL;
-}
-
-namespace {
-
-TEST(RampTestSuite, Init) {
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(action.type, CRAS_RAMP_ACTION_NONE);
- EXPECT_FLOAT_EQ(1.0, action.scaler);
- EXPECT_FLOAT_EQ(0.0, action.increment);
- EXPECT_FLOAT_EQ(1.0, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampUpInitialIncrement) {
- float from = 0.0;
- float to = 1.0;
- int duration_frames = 48000;
- float increment = 1.0 / 48000;
- cras_ramp* ramp;
- cras_ramp_action action;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(0.0, action.scaler);
- EXPECT_FLOAT_EQ(increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampUpUpdateRampedFrames) {
- float from = 0.0;
- float to = 1.0;
- int duration_frames = 48000;
- float increment = 1.0 / 48000;
- int rc;
- int ramped_frames = 512;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float scaler = increment * ramped_frames;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(rc, 0);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampUpPassedRamp) {
- float from = 0.0;
- float to = 1.0;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 48000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_NONE, action.type);
- EXPECT_FLOAT_EQ(1.0, action.scaler);
- EXPECT_FLOAT_EQ(0.0, action.increment);
- EXPECT_FLOAT_EQ(1.0, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampUpWhileHalfWayRampDown) {
- float from;
- float to;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 24000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float down_increment = -1.0 / 48000;
- float up_increment;
- float scaler;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- from = 1.0;
- to = 0.0;
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- // Get expected current scaler.
- scaler = 1 + down_increment * ramped_frames;
- // The increment will be calculated by ramping to 1 starting from scaler.
- up_increment = (1 - scaler) / 48000;
-
- from = 0.0;
- to = 1.0;
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(up_increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampUpWhileHalfWayRampUp) {
- float from = 0.0;
- float to = 1.0;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 24000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float first_increment = 1.0 / 48000;
- float second_increment;
- float scaler;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- // Get expected current scaler.
- scaler = first_increment * ramped_frames;
- // The increment will be calculated by ramping to 1 starting from scaler.
- second_increment = (1 - scaler) / 48000;
-
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(second_increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampDownInitialIncrement) {
- float from = 1.0;
- float to = 0.0;
- int duration_frames = 48000;
- float increment = -1.0 / 48000;
- cras_ramp* ramp;
- cras_ramp_action action;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(1.0, action.scaler);
- EXPECT_FLOAT_EQ(increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampDownUpdateRampedFrames) {
- float from = 1.0;
- float to = 0.0;
- int duration_frames = 48000;
- float increment = -1.0 / 48000;
- int rc;
- int ramped_frames = 512;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float scaler = 1 + increment * ramped_frames;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(rc, 0);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampDownPassedRamp) {
- float from = 1.0;
- float to = 0.0;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 48000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_NONE, action.type);
- EXPECT_FLOAT_EQ(1.0, action.scaler);
- EXPECT_FLOAT_EQ(0.0, action.increment);
- EXPECT_FLOAT_EQ(1.0, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampDownWhileHalfWayRampUp) {
- float from;
- float to;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 24000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float up_increment = 1.0 / 48000;
- float down_increment;
- float scaler;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- // Ramp up first.
- from = 0.0;
- to = 1.0;
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- // Get expected current scaler.
- scaler = up_increment * ramped_frames;
- // The increment will be calculated by ramping to 0 starting from scaler.
- down_increment = -scaler / duration_frames;
-
- // Ramp down will start from current scaler.
- from = 1.0;
- to = 0.0;
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(down_increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, NullWontCrash) {
- float from;
- float to;
- int duration_frames = 48000;
- int rc = 0;
- struct cras_ramp* ramp = NULL;
-
- ResetStubData();
-
- from = 0.0;
- to = 1.0;
- rc = cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- EXPECT_EQ(-EINVAL, rc);
-}
-
-TEST(RampTestSuite, RampDownWhileHalfWayRampDown) {
- float from = 1.0;
- float to = 0.0;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 24000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float down_increment = -1.0 / 48000;
- float second_down_increment;
- float scaler;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- // Ramp down.
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- // Get expected current scaler.
- scaler = 1 + down_increment * ramped_frames;
- // The increment will be calculated by ramping to 0 starting from scaler.
- second_down_increment = -scaler / duration_frames;
-
- // Ramp down starting from current scaler.
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(second_down_increment, action.increment);
- EXPECT_FLOAT_EQ(to, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, MuteRamp) {
- float from = 0.0;
- float to = 0.0;
- int duration_frames = 48000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, NULL, NULL);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(0.0, action.scaler);
- EXPECT_FLOAT_EQ(0.0, action.increment);
- EXPECT_FLOAT_EQ(0.0, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, PartialRamp) {
- float from_one = 0.75;
- float to_one = 0.4;
- float from_two = 0.6;
- float to_two = 0.9;
- int duration_frames = 1200;
- int rc;
- int ramped_frames = 600;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- float down_increment = (to_one - from_one) / duration_frames;
- float up_increment;
- float scaler;
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- // Ramp down.
- cras_volume_ramp_start(ramp, from_one, to_one, duration_frames, NULL, NULL);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- scaler = from_one + ramped_frames * down_increment;
- action = cras_ramp_get_current_action(ramp);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(down_increment, action.increment);
- EXPECT_FLOAT_EQ(to_one, action.target);
-
- // Ramp up starting from current scaler.
- cras_volume_ramp_start(ramp, from_two, to_two, duration_frames, NULL, NULL);
-
- // we start by multiplying by previous scaler
- scaler = scaler * from_two;
- action = cras_ramp_get_current_action(ramp);
- up_increment = (to_two - scaler) / duration_frames;
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_PARTIAL, action.type);
- EXPECT_FLOAT_EQ(scaler, action.scaler);
- EXPECT_FLOAT_EQ(up_increment, action.increment);
- EXPECT_FLOAT_EQ(to_two, action.target);
-
- cras_ramp_destroy(ramp);
-}
-
-void ramp_callback(void* arg) {
- callback_called++;
- callback_arg = arg;
-}
-
-TEST(RampTestSuite, RampUpPassedRampCallback) {
- float from = 0.0;
- float to = 1.0;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 48000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- void* cb_data = reinterpret_cast<void*>(0x123);
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, ramp_callback, cb_data);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_NONE, action.type);
- EXPECT_FLOAT_EQ(1.0, action.scaler);
- EXPECT_FLOAT_EQ(0.0, action.increment);
- EXPECT_FLOAT_EQ(1.0, action.target);
- EXPECT_EQ(1, callback_called);
- EXPECT_EQ(cb_data, callback_arg);
-
- cras_ramp_destroy(ramp);
-}
-
-TEST(RampTestSuite, RampDownPassedRampCallback) {
- float from = 1.0;
- float to = 0.0;
- int duration_frames = 48000;
- int rc;
- int ramped_frames = 48000;
- struct cras_ramp* ramp;
- struct cras_ramp_action action;
- void* cb_data = reinterpret_cast<void*>(0x123);
-
- ResetStubData();
-
- ramp = cras_ramp_create();
- cras_mute_ramp_start(ramp, from, to, duration_frames, ramp_callback, cb_data);
-
- rc = cras_ramp_update_ramped_frames(ramp, ramped_frames);
-
- action = cras_ramp_get_current_action(ramp);
-
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_RAMP_ACTION_NONE, action.type);
- EXPECT_FLOAT_EQ(1.0, action.scaler);
- EXPECT_FLOAT_EQ(0.0, action.increment);
- EXPECT_FLOAT_EQ(1.0, action.target);
- EXPECT_EQ(1, callback_called);
- EXPECT_EQ(cb_data, callback_arg);
-
- cras_ramp_destroy(ramp);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- int rc = RUN_ALL_TESTS();
-
- return rc;
-}
diff --git a/cras/src/tests/rate_estimator_unittest.cc b/cras/src/tests/rate_estimator_unittest.cc
deleted file mode 100644
index 778a3cda..00000000
--- a/cras/src/tests/rate_estimator_unittest.cc
+++ /dev/null
@@ -1,182 +0,0 @@
-// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-
-extern "C" {
-#include "rate_estimator.h"
-}
-
-static struct timespec window = {.tv_sec = 0, .tv_nsec = 10000000};
-
-TEST(RateEstimatorTest, EstimateOutputLinear) {
- struct rate_estimator* re;
- struct timespec t = {.tv_sec = 1, .tv_nsec = 0};
- int i, rc, level, tmp;
-
- re = rate_estimator_create(10000, &window, 0.0f);
- level = 240;
- for (i = 0; i < 20; i++) {
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(0, rc);
-
- /* Test that output device consumes 5 frames. */
- tmp = rand() % 10;
- rate_estimator_add_frames(re, 5 + tmp);
- level += tmp;
- t.tv_nsec += 500000;
- }
- t.tv_nsec += 1;
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(1, rc);
- EXPECT_GT(10000, rate_estimator_get_rate(re));
- EXPECT_LT(9999, rate_estimator_get_rate(re));
-
- rate_estimator_destroy(re);
-}
-
-TEST(RateEstimatorTest, EstimateOutputLinear2) {
- struct rate_estimator* re;
- struct timespec t = {.tv_sec = 1, .tv_nsec = 0};
- int level = 240;
- int i, rc, tmp;
-
- int interval_nsec[5] = {1000000, 1500000, 2000000, 2500000, 3000000};
- int frames_written[5] = {30, 25, 20, 15, 10};
-
- re = rate_estimator_create(7470, &window, 0.0f);
- for (i = 0; i < 5; i++) {
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(0, rc);
-
- tmp = rand() % 10;
- rate_estimator_add_frames(re, frames_written[i] + tmp);
- level += tmp;
- t.tv_nsec += interval_nsec[i];
- }
- t.tv_nsec += 1;
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(1, rc);
- /* Calculated rate is 7475.72 */
- EXPECT_GT(7476, rate_estimator_get_rate(re));
- EXPECT_LT(7475, rate_estimator_get_rate(re));
-
- rate_estimator_destroy(re);
-}
-
-TEST(RateEstimatorTest, EstimateRateSkewTooLarge) {
- struct rate_estimator* re;
- struct timespec t = {.tv_sec = 1, .tv_nsec = 0};
- int level = 240;
- int i, rc, tmp;
-
- int interval_nsec[5] = {1000000, 1500000, 2000000, 2500000, 3000000};
- int frames_written[5] = {30, 25, 20, 15, 10};
-
- re = rate_estimator_create(10000, &window, 0.0f);
- for (i = 0; i < 5; i++) {
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(0, rc);
-
- tmp = rand() % 10;
- rate_estimator_add_frames(re, frames_written[i] + tmp);
- level += tmp;
- t.tv_nsec += interval_nsec[i];
- }
- t.tv_nsec += 1;
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(1, rc);
- /* Estimated rate too far from allowed max rate skew */
- EXPECT_EQ(10000, rate_estimator_get_rate(re));
-
- rate_estimator_destroy(re);
-}
-
-TEST(RateEstimatorTest, EstimateOutputSmooth) {
- struct rate_estimator* re;
- struct timespec t = {.tv_sec = 1, .tv_nsec = 0};
- int rc;
-
- re = rate_estimator_create(10010, &window, 0.9f);
- rc = rate_estimator_check(re, 240, &t);
- EXPECT_EQ(0, rc);
-
- /* Test that output device consumes 100 frames in
- * 10ms. */
- rate_estimator_add_frames(re, 55);
- t.tv_nsec += 5000000;
- rc = rate_estimator_check(re, 245, &t);
- EXPECT_EQ(0, rc);
-
- rate_estimator_add_frames(re, 55);
- t.tv_nsec += 5000001;
- rc = rate_estimator_check(re, 250, &t);
- EXPECT_EQ(1, rc);
-
- /* Assert the rate is smoothed 10010 * 0.9 + 10000 * 0.1 */
- EXPECT_LT(10008, rate_estimator_get_rate(re));
- EXPECT_GT(10009, rate_estimator_get_rate(re));
-
- rate_estimator_destroy(re);
-}
-
-TEST(RateEstimatorTest, EstimateInputLinear) {
- struct rate_estimator* re;
- struct timespec t = {.tv_sec = 1, .tv_nsec = 0};
- int i, rc, level, tmp;
-
- re = rate_estimator_create(10000, &window, 0.0f);
- level = 1200;
- for (i = 0; i < 20; i++) {
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(0, rc);
-
- /* Test that stream consumes 5 frames. */
- tmp = rand() % 10;
- rate_estimator_add_frames(re, -(5 + tmp));
- level -= tmp;
- t.tv_nsec += 500000;
- }
- t.tv_nsec += 1;
- rc = rate_estimator_check(re, level, &t);
- EXPECT_EQ(1, rc);
- EXPECT_GT(10000, rate_estimator_get_rate(re));
- EXPECT_LT(9999, rate_estimator_get_rate(re));
-
- rate_estimator_destroy(re);
-}
-
-TEST(RateEstimatorTest, EstimateInputLinear2) {
- struct rate_estimator* re;
- struct timespec t;
- int rc;
- static struct timespec this_window = {.tv_sec = 0, .tv_nsec = 100000000};
-
- re = rate_estimator_create(10000, &this_window, 0.0f);
- t.tv_sec = 1;
- t.tv_nsec = 0;
- rc = rate_estimator_check(re, 200, &t);
- EXPECT_EQ(0, rc);
-
- t.tv_nsec += 50000000;
- rc = rate_estimator_check(re, 700, &t);
- EXPECT_EQ(0, rc);
-
- rate_estimator_add_frames(re, -100);
-
- t.tv_nsec += 50000000;
- rc = rate_estimator_check(re, 1100, &t);
- t.tv_nsec += 1;
- rc = rate_estimator_check(re, 1100, &t);
- EXPECT_EQ(1, rc);
- EXPECT_GT(10000, rate_estimator_get_rate(re));
- EXPECT_LT(9999, rate_estimator_get_rate(re));
-
- rate_estimator_destroy(re);
-}
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/rstream_stub.cc b/cras/src/tests/rstream_stub.cc
deleted file mode 100644
index 18f6f951..00000000
--- a/cras/src/tests/rstream_stub.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <unordered_map>
-
-extern "C" {
-#include "cras_rstream.h"
-}
-
-namespace {
-
-struct cb_data {
- std::unordered_map<unsigned int, unsigned int> dev_offset;
- int pending_reply;
-};
-std::unordered_map<const cras_rstream*, cb_data> data_map;
-
-}; // namespace
-
-void rstream_stub_reset() {
- data_map.clear();
-}
-
-void rstream_stub_dev_offset(const cras_rstream* rstream,
- unsigned int dev_id,
- unsigned int offset) {
- auto data = data_map.find(rstream);
- if (data == data_map.end()) {
- cb_data new_data;
- new_data.dev_offset[dev_id] = offset;
- data_map.insert({rstream, new_data});
- } else {
- data->second.dev_offset[dev_id] = offset;
- }
-}
-
-void rstream_stub_pending_reply(const cras_rstream* rstream, int ret_value) {
- auto data = data_map.find(rstream);
- if (data == data_map.end()) {
- cb_data new_data;
- new_data.pending_reply = ret_value;
- data_map.insert({rstream, new_data});
- } else {
- data->second.pending_reply = ret_value;
- }
-}
-
-extern "C" {
-
-void cras_rstream_record_fetch_interval(struct cras_rstream* rstream,
- const struct timespec* now) {}
-
-void cras_rstream_dev_attach(struct cras_rstream* rstream,
- unsigned int dev_id,
- void* dev_ptr) {}
-
-void cras_rstream_dev_detach(struct cras_rstream* rstream,
- unsigned int dev_id) {}
-
-unsigned int cras_rstream_dev_offset(const struct cras_rstream* rstream,
- unsigned int dev_id) {
- auto elem = data_map.find(rstream);
- if (elem != data_map.end())
- return elem->second.dev_offset[dev_id];
- return 0;
-}
-
-void cras_rstream_dev_offset_update(struct cras_rstream* rstream,
- unsigned int frames,
- unsigned int dev_id) {}
-
-unsigned int cras_rstream_playable_frames(struct cras_rstream* rstream,
- unsigned int dev_id) {
- return 0;
-}
-
-float cras_rstream_get_volume_scaler(struct cras_rstream* rstream) {
- return 1.0;
-}
-
-int cras_rstream_get_mute(const struct cras_rstream* rstream) {
- return 0;
-}
-
-uint8_t* cras_rstream_get_readable_frames(struct cras_rstream* rstream,
- unsigned int offset,
- size_t* frames) {
- return NULL;
-}
-
-void cras_rstream_update_input_write_pointer(struct cras_rstream* rstream) {}
-
-void cras_rstream_update_output_read_pointer(struct cras_rstream* rstream) {}
-
-int cras_rstream_audio_ready(struct cras_rstream* stream, size_t count) {
- cras_shm_buffer_write_complete(stream->shm);
- return 0;
-}
-
-int cras_rstream_request_audio(struct cras_rstream* stream,
- const struct timespec* now) {
- return 0;
-}
-
-void cras_rstream_update_queued_frames(struct cras_rstream* rstream) {}
-
-int cras_rstream_is_pending_reply(const struct cras_rstream* rstream) {
- auto elem = data_map.find(rstream);
- if (elem != data_map.end())
- return elem->second.pending_reply;
- return 0;
-}
-
-int cras_rstream_flush_old_audio_messages(struct cras_rstream* rstream) {
- return 0;
-}
-
-} // extern "C"
diff --git a/cras/src/tests/rstream_stub.h b/cras/src/tests/rstream_stub.h
deleted file mode 100644
index 249bcb76..00000000
--- a/cras/src/tests/rstream_stub.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Copyright 2017 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef RSTREAM_STUB_H_
-#define RSTREAM_STUB_H_
-
-#include <time.h>
-
-void rstream_stub_reset();
-
-void rstream_stub_dev_offset(const cras_rstream* rstream,
- unsigned int dev_id,
- unsigned int offset);
-
-// Stub that rstream is pending the reply from client or not.
-void rstream_stub_pending_reply(const cras_rstream* rstream, int ret_value);
-
-#endif // RSTREAM_STUB_H_
diff --git a/cras/src/tests/rstream_unittest.cc b/cras/src/tests/rstream_unittest.cc
deleted file mode 100644
index d8dae24c..00000000
--- a/cras/src/tests/rstream_unittest.cc
+++ /dev/null
@@ -1,437 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <fcntl.h>
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <sys/mman.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-
-extern "C" {
-#include "cras_audio_area.h"
-#include "cras_messages.h"
-#include "cras_rstream.h"
-#include "cras_shm.h"
-}
-
-#include "metrics_stub.h"
-
-namespace {
-
-class RstreamTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- int rc;
- int sock[2] = {-1, -1};
-
- fmt_.format = SND_PCM_FORMAT_S16_LE;
- fmt_.frame_rate = 48000;
- fmt_.num_channels = 2;
-
- config_.stream_id = 555;
- config_.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- config_.client_type = CRAS_CLIENT_TYPE_UNKNOWN;
- config_.direction = CRAS_STREAM_OUTPUT;
- config_.dev_idx = NO_DEVICE;
- config_.flags = 0;
- config_.format = &fmt_;
- config_.buffer_frames = 4096;
- config_.cb_threshold = 2048;
- config_.client_shm_size = 0;
- config_.client_shm_fd = -1;
-
- // Create a socket pair because it will be used in rstream.
- rc = socketpair(AF_UNIX, SOCK_STREAM, 0, sock);
- ASSERT_EQ(0, rc);
- config_.audio_fd = sock[1];
- client_fd_ = sock[0];
-
- config_.client = NULL;
- }
-
- virtual void TearDown() {
- close(config_.audio_fd);
- close(client_fd_);
- }
-
- static bool format_equal(cras_audio_format* fmt1, cras_audio_format* fmt2) {
- return fmt1->format == fmt2->format &&
- fmt1->frame_rate == fmt2->frame_rate &&
- fmt1->num_channels == fmt2->num_channels;
- }
-
- void stub_client_reply(enum CRAS_AUDIO_MESSAGE_ID id, int frames, int err) {
- int rc;
- struct audio_message aud_msg;
- // Create a message.
- aud_msg.id = id;
- aud_msg.frames = frames;
- aud_msg.error = err;
-
- // Use socket fd to stub message from client.
- rc = write(client_fd_, &aud_msg, sizeof(aud_msg));
- EXPECT_EQ(sizeof(aud_msg), rc);
- return;
- }
-
- struct cras_audio_format fmt_;
- struct cras_rstream_config config_;
- int client_fd_;
-};
-
-TEST_F(RstreamTestSuite, InvalidDirection) {
- struct cras_rstream* s;
- int rc;
-
- config_.direction = (enum CRAS_STREAM_DIRECTION)66;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_NE(0, rc);
-}
-
-TEST_F(RstreamTestSuite, InvalidStreamType) {
- struct cras_rstream* s;
- int rc;
-
- config_.stream_type = (enum CRAS_STREAM_TYPE)7;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_NE(0, rc);
-}
-
-TEST_F(RstreamTestSuite, InvalidBufferSize) {
- struct cras_rstream* s;
- int rc;
-
- config_.buffer_frames = 3;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_NE(0, rc);
-}
-
-TEST_F(RstreamTestSuite, InvalidCallbackThreshold) {
- struct cras_rstream* s;
- int rc;
-
- config_.cb_threshold = 3;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_NE(0, rc);
-}
-
-TEST_F(RstreamTestSuite, InvalidStreamPointer) {
- int rc;
-
- rc = cras_rstream_create(&config_, NULL);
- EXPECT_NE(0, rc);
-}
-
-TEST_F(RstreamTestSuite, CreateOutput) {
- struct cras_rstream* s;
- struct cras_audio_format fmt_ret;
- struct cras_audio_shm* shm_ret;
- struct cras_audio_shm shm_mapped;
- int rc, header_fd = -1, samples_fd = -1;
- size_t shm_size;
-
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
- EXPECT_NE((void*)NULL, s);
- EXPECT_EQ(4096, cras_rstream_get_buffer_frames(s));
- EXPECT_EQ(2048, cras_rstream_get_cb_threshold(s));
- EXPECT_EQ(CRAS_STREAM_TYPE_DEFAULT, cras_rstream_get_type(s));
- EXPECT_EQ(CRAS_STREAM_OUTPUT, cras_rstream_get_direction(s));
- EXPECT_NE((void*)NULL, cras_rstream_shm(s));
- rc = cras_rstream_get_format(s, &fmt_ret);
- EXPECT_EQ(0, rc);
- EXPECT_TRUE(format_equal(&fmt_ret, &fmt_));
-
- // Check if shm is really set up.
- shm_ret = cras_rstream_shm(s);
- ASSERT_NE((void*)NULL, shm_ret);
- cras_rstream_get_shm_fds(s, &header_fd, &samples_fd);
- shm_size = cras_shm_samples_size(shm_ret);
- EXPECT_EQ(shm_size, 32768);
- shm_mapped.header = (struct cras_audio_shm_header*)mmap(
- NULL, cras_shm_header_size(), PROT_READ | PROT_WRITE, MAP_SHARED,
- header_fd, 0);
- EXPECT_NE((void*)NULL, shm_mapped.header);
- cras_shm_copy_shared_config(&shm_mapped);
- EXPECT_EQ(cras_shm_used_size(&shm_mapped), cras_shm_used_size(shm_ret));
- munmap(shm_mapped.header, cras_shm_header_size());
-
- cras_rstream_destroy(s);
-}
-
-TEST_F(RstreamTestSuite, CreateInput) {
- struct cras_rstream* s;
- struct cras_audio_format fmt_ret;
- struct cras_audio_shm* shm_ret;
- struct cras_audio_shm shm_mapped;
- int rc, header_fd = -1, samples_fd = -1;
- size_t shm_size;
-
- config_.direction = CRAS_STREAM_INPUT;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
- EXPECT_NE((void*)NULL, s);
- EXPECT_EQ(4096, cras_rstream_get_buffer_frames(s));
- EXPECT_EQ(2048, cras_rstream_get_cb_threshold(s));
- EXPECT_EQ(CRAS_STREAM_TYPE_DEFAULT, cras_rstream_get_type(s));
- EXPECT_EQ(CRAS_STREAM_INPUT, cras_rstream_get_direction(s));
- EXPECT_NE((void*)NULL, cras_rstream_shm(s));
- rc = cras_rstream_get_format(s, &fmt_ret);
- EXPECT_EQ(0, rc);
- EXPECT_TRUE(format_equal(&fmt_ret, &fmt_));
-
- // Check if shm is really set up.
- shm_ret = cras_rstream_shm(s);
- ASSERT_NE((void*)NULL, shm_ret);
- cras_rstream_get_shm_fds(s, &header_fd, &samples_fd);
- shm_size = cras_shm_samples_size(shm_ret);
- EXPECT_EQ(shm_size, 32768);
- shm_mapped.header = (struct cras_audio_shm_header*)mmap(
- NULL, cras_shm_header_size(), PROT_READ | PROT_WRITE, MAP_SHARED,
- header_fd, 0);
- EXPECT_NE((void*)NULL, shm_mapped.header);
- cras_shm_copy_shared_config(&shm_mapped);
- EXPECT_EQ(cras_shm_used_size(&shm_mapped), cras_shm_used_size(shm_ret));
- munmap(shm_mapped.header, cras_shm_header_size());
-
- cras_rstream_destroy(s);
-}
-
-TEST_F(RstreamTestSuite, VerifyStreamTypes) {
- struct cras_rstream* s;
- int rc;
-
- config_.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_STREAM_TYPE_DEFAULT, cras_rstream_get_type(s));
- EXPECT_NE(CRAS_STREAM_TYPE_MULTIMEDIA, cras_rstream_get_type(s));
- cras_rstream_destroy(s);
-
- config_.stream_type = CRAS_STREAM_TYPE_VOICE_COMMUNICATION;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_STREAM_TYPE_VOICE_COMMUNICATION, cras_rstream_get_type(s));
- cras_rstream_destroy(s);
-
- config_.direction = CRAS_STREAM_INPUT;
- config_.stream_type = CRAS_STREAM_TYPE_SPEECH_RECOGNITION;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_STREAM_TYPE_SPEECH_RECOGNITION, cras_rstream_get_type(s));
- cras_rstream_destroy(s);
-
- config_.stream_type = CRAS_STREAM_TYPE_PRO_AUDIO;
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(CRAS_STREAM_TYPE_PRO_AUDIO, cras_rstream_get_type(s));
- cras_rstream_destroy(s);
-}
-
-TEST_F(RstreamTestSuite, OutputStreamIsPendingReply) {
- struct cras_rstream* s;
- int rc;
- struct timespec ts;
-
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
-
- // Not pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(0, rc);
-
- // Request some data from client.
- rc = cras_rstream_request_audio(s, &ts);
- EXPECT_GT(rc, 0);
-
- // Pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(1, rc);
-
- cras_rstream_destroy(s);
-}
-
-TEST_F(RstreamTestSuite, OutputStreamFlushMessages) {
- struct cras_rstream* s;
- int rc;
- struct timespec ts;
-
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
-
- // Not pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(0, rc);
-
- // Request some data from client.
- rc = cras_rstream_request_audio(s, &ts);
- EXPECT_GT(rc, 0);
-
- // Pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(1, rc);
-
- // Client replies that data is ready.
- stub_client_reply(AUDIO_MESSAGE_DATA_READY, 10, 0);
-
- // Read messages.
- cras_rstream_flush_old_audio_messages(s);
-
- // NOT Pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(0, rc);
-
- cras_rstream_destroy(s);
-}
-
-TEST_F(RstreamTestSuite, InputStreamIsPendingReply) {
- struct cras_rstream* s;
- int rc;
-
- config_.direction = CRAS_STREAM_INPUT;
-
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
-
- // Not pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(0, rc);
-
- // Some data is ready. Sends it to client.
- rc = cras_rstream_audio_ready(s, 10);
- EXPECT_GT(rc, 0);
-
- // Pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(1, rc);
-
- cras_rstream_destroy(s);
-}
-
-TEST_F(RstreamTestSuite, InputStreamFlushMessages) {
- struct cras_rstream* s;
- int rc;
-
- config_.direction = CRAS_STREAM_INPUT;
-
- rc = cras_rstream_create(&config_, &s);
- EXPECT_EQ(0, rc);
-
- // Not pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(0, rc);
-
- // Some data is ready. Sends it to client.
- rc = cras_rstream_audio_ready(s, 10);
- EXPECT_GT(rc, 0);
-
- // Pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(1, rc);
-
- // Client replies that data is captured.
- stub_client_reply(AUDIO_MESSAGE_DATA_CAPTURED, 10, 0);
-
- // Read messages.
- cras_rstream_flush_old_audio_messages(s);
-
- // NOT Pending reply.
- rc = cras_rstream_is_pending_reply(s);
- EXPECT_EQ(0, rc);
-
- cras_rstream_destroy(s);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-/* stubs */
-extern "C" {
-
-struct cras_audio_area* cras_audio_area_create(int num_channels) {
- return NULL;
-}
-
-void cras_audio_area_destroy(struct cras_audio_area* area) {}
-
-void cras_audio_area_config_channels(struct cras_audio_area* area,
- const struct cras_audio_format* fmt) {}
-
-struct buffer_share* buffer_share_create(unsigned int buf_sz) {
- return NULL;
-}
-
-void buffer_share_destroy(struct buffer_share* mix) {}
-
-int buffer_share_offset_update(struct buffer_share* mix,
- unsigned int id,
- unsigned int frames) {
- return 0;
-}
-
-unsigned int buffer_share_get_new_write_point(struct buffer_share* mix) {
- return 0;
-}
-
-int buffer_share_add_id(struct buffer_share* mix, unsigned int id, void* data) {
- return 0;
-}
-
-int buffer_share_rm_id(struct buffer_share* mix, unsigned int id) {
- return 0;
-}
-
-unsigned int buffer_share_id_offset(const struct buffer_share* mix,
- unsigned int id) {
- return 0;
-}
-void ewma_power_init(struct ewma_power* ewma, unsigned int rate) {}
-
-void ewma_power_calculate(struct ewma_power* ewma,
- const int16_t* buf,
- unsigned int channels,
- unsigned int size) {}
-
-void cras_system_state_stream_added(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type) {}
-
-void cras_system_state_stream_removed(enum CRAS_STREAM_DIRECTION direction,
- enum CRAS_CLIENT_TYPE client_type) {}
-
-int cras_server_metrics_stream_create(
- const struct cras_rstream_config* config) {
- return 0;
-}
-
-int cras_server_metrics_stream_destroy(const struct cras_rstream* stream) {
- return 0;
-}
-
-#ifdef HAVE_WEBRTC_APM
-#define FAKE_CRAS_APM_PTR reinterpret_cast<struct cras_apm*>(0x99)
-struct cras_apm_list* cras_apm_list_create(void* stream_ptr, uint64_t effects) {
- return NULL;
-}
-struct cras_apm* cras_apm_list_get_active_apm(void* stream_ptr, void* dev_ptr) {
- return FAKE_CRAS_APM_PTR;
-}
-int cras_apm_list_destroy(struct cras_apm_list* list) {
- return 0;
-}
-uint64_t cras_apm_list_get_effects(struct cras_apm_list* list) {
- return APM_ECHO_CANCELLATION;
-}
-struct cras_apm* cras_apm_list_get(struct cras_apm_list* list, void* dev_ptr) {
- return NULL;
-}
-struct cras_audio_format* cras_apm_list_get_format(struct cras_apm* apm) {
- return NULL;
-}
-#endif
-}
diff --git a/cras/src/tests/sbc_codec_stub.cc b/cras/src/tests/sbc_codec_stub.cc
deleted file mode 100644
index 95bd091c..00000000
--- a/cras/src/tests/sbc_codec_stub.cc
+++ /dev/null
@@ -1,174 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <stdlib.h>
-
-extern "C" {
-#include "cras_audio_codec.h"
-#include "sbc_codec_stub.h"
-}
-
-namespace {
-
-static int create_fail;
-static int create_called;
-static int msbc_create_called;
-static int destroy_called;
-static uint8_t freq_val;
-static uint8_t mode_val;
-static uint8_t subbands_val;
-static uint8_t alloc_val;
-static uint8_t blocks_val;
-static uint8_t bitpool_val;
-static struct cras_audio_codec* sbc_codec;
-static size_t decode_out_decoded_return_val;
-static int decode_fail;
-static size_t encode_out_encoded_return_val;
-static int encode_fail;
-static int cras_sbc_get_frame_length_val;
-static int cras_sbc_get_codesize_val;
-
-}; // namespace
-
-void sbc_codec_stub_reset() {
- create_fail = 0;
- create_called = 0;
- msbc_create_called = 0;
- destroy_called = 0;
- freq_val = 0;
- mode_val = 0;
- subbands_val = 0;
- alloc_val = 0;
- blocks_val = 0;
- bitpool_val = 0;
-
- sbc_codec = NULL;
- decode_out_decoded_return_val = 0;
- encode_out_encoded_return_val = 0;
- decode_fail = 0;
- encode_fail = 0;
-
- cras_sbc_get_frame_length_val = 5;
- cras_sbc_get_codesize_val = 5;
-}
-
-void set_sbc_codec_create_fail(int fail) {
- create_fail = fail;
-}
-
-int get_sbc_codec_create_called() {
- return create_called;
-}
-
-int get_msbc_codec_create_called() {
- return msbc_create_called;
-}
-
-uint8_t get_sbc_codec_create_freq_val() {
- return freq_val;
-}
-
-uint8_t get_sbc_codec_create_mode_val() {
- return mode_val;
-}
-
-uint8_t get_sbc_codec_create_subbands_val() {
- return subbands_val;
-}
-
-uint8_t get_sbc_codec_create_alloc_val() {
- return alloc_val;
-}
-
-uint8_t get_sbc_codec_create_blocks_val() {
- return blocks_val;
-}
-
-uint8_t get_sbc_codec_create_bitpool_val() {
- return bitpool_val;
-}
-
-int get_sbc_codec_destroy_called() {
- return destroy_called;
-}
-
-void set_sbc_codec_decoded_out(size_t ret) {
- decode_out_decoded_return_val = ret;
-}
-
-void set_sbc_codec_decoded_fail(int fail) {
- decode_fail = fail;
-}
-
-void set_sbc_codec_encoded_out(size_t ret) {
- encode_out_encoded_return_val = ret;
-}
-
-void set_sbc_codec_encoded_fail(int fail) {
- encode_fail = fail;
-}
-
-int decode(struct cras_audio_codec* codec,
- const void* input,
- size_t input_len,
- void* output,
- size_t output_len,
- size_t* count) {
- *count = decode_out_decoded_return_val;
- return decode_fail ? -1 : input_len;
-}
-
-int encode(struct cras_audio_codec* codec,
- const void* input,
- size_t input_len,
- void* output,
- size_t output_len,
- size_t* count) {
- // Written half the output buffer.
- *count = encode_out_encoded_return_val;
- return encode_fail ? -1 : input_len;
-}
-
-struct cras_audio_codec* cras_sbc_codec_create(uint8_t freq,
- uint8_t mode,
- uint8_t subbands,
- uint8_t alloc,
- uint8_t blocks,
- uint8_t bitpool) {
- if (!create_fail) {
- sbc_codec = (struct cras_audio_codec*)calloc(1, sizeof(*sbc_codec));
- sbc_codec->decode = decode;
- sbc_codec->encode = encode;
- }
-
- create_called++;
- freq_val = freq;
- mode_val = mode;
- subbands_val = subbands;
- alloc_val = alloc;
- blocks_val = blocks;
- bitpool_val = bitpool;
- return sbc_codec;
-}
-
-struct cras_audio_codec* cras_msbc_codec_create() {
- msbc_create_called++;
- sbc_codec = (struct cras_audio_codec*)calloc(1, sizeof(*sbc_codec));
- sbc_codec->decode = decode;
- sbc_codec->encode = encode;
- return sbc_codec;
-}
-
-void cras_sbc_codec_destroy(struct cras_audio_codec* codec) {
- destroy_called++;
- free(codec);
-}
-
-int cras_sbc_get_codesize(struct cras_audio_codec* codec) {
- return cras_sbc_get_codesize_val;
-}
-
-int cras_sbc_get_frame_length(struct cras_audio_codec* codec) {
- return cras_sbc_get_frame_length_val;
-}
diff --git a/cras/src/tests/sbc_codec_stub.h b/cras/src/tests/sbc_codec_stub.h
deleted file mode 100644
index b166b399..00000000
--- a/cras/src/tests/sbc_codec_stub.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Copyright 2019 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#ifndef SBC_CODEC_STUB_H_
-#define SBC_CODEC_STUB_H_
-
-#include <stdint.h>
-#include <stdlib.h>
-
-void sbc_codec_stub_reset();
-void set_sbc_codec_create_fail(int fail);
-int get_sbc_codec_create_called();
-int get_msbc_codec_create_called();
-uint8_t get_sbc_codec_create_freq_val();
-uint8_t get_sbc_codec_create_mode_val();
-uint8_t get_sbc_codec_create_subbands_val();
-uint8_t get_sbc_codec_create_alloc_val();
-uint8_t get_sbc_codec_create_blocks_val();
-uint8_t get_sbc_codec_create_bitpool_val();
-int get_sbc_codec_destroy_called();
-void set_sbc_codec_decoded_out(size_t ret);
-void set_sbc_codec_decoded_fail(int fail);
-void set_sbc_codec_encoded_out(size_t ret);
-void set_sbc_codec_encoded_fail(int fail);
-
-struct cras_audio_codec* cras_sbc_codec_create(uint8_t freq,
- uint8_t mode,
- uint8_t subbands,
- uint8_t alloc,
- uint8_t blocks,
- uint8_t bitpool);
-struct cras_audio_codec* cras_msbc_codec_create();
-void cras_sbc_codec_destroy(struct cras_audio_codec* codec);
-int cras_sbc_get_codesize(struct cras_audio_codec* codec);
-int cras_sbc_get_frame_length(struct cras_audio_codec* codec);
-
-#endif // SBC_CODEC_STUB_H_
diff --git a/cras/src/tests/server_metrics_unittest.cc b/cras/src/tests/server_metrics_unittest.cc
deleted file mode 100644
index e23906ec..00000000
--- a/cras/src/tests/server_metrics_unittest.cc
+++ /dev/null
@@ -1,403 +0,0 @@
-// Copyright 2016 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-#include <vector>
-
-extern "C" {
-#include "cras_main_message.h"
-#include "cras_rstream.h"
-#include "cras_server_metrics.c"
-}
-
-static enum CRAS_MAIN_MESSAGE_TYPE type_set;
-static struct timespec clock_gettime_retspec;
-std::vector<struct cras_server_metrics_message> sent_msgs;
-
-void ResetStubData() {
- type_set = (enum CRAS_MAIN_MESSAGE_TYPE)0;
- sent_msgs.clear();
-}
-
-namespace {
-
-TEST(ServerMetricsTestSuite, Init) {
- ResetStubData();
-
- cras_server_metrics_init();
-
- EXPECT_EQ(type_set, CRAS_MAIN_METRICS);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsDeviceRuntime) {
- ResetStubData();
- struct cras_iodev iodev;
- struct cras_ionode active_node;
-
- clock_gettime_retspec.tv_sec = 200;
- clock_gettime_retspec.tv_nsec = 0;
- iodev.info.idx = MAX_SPECIAL_DEVICE_IDX;
- iodev.open_ts.tv_sec = 100;
- iodev.open_ts.tv_nsec = 0;
- iodev.direction = CRAS_STREAM_INPUT;
- iodev.active_node = &active_node;
- active_node.type = CRAS_NODE_TYPE_USB;
-
- cras_server_metrics_device_runtime(&iodev);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, DEVICE_RUNTIME);
- EXPECT_EQ(sent_msgs[0].data.device_data.type, CRAS_METRICS_DEVICE_USB);
- EXPECT_EQ(sent_msgs[0].data.device_data.direction, CRAS_STREAM_INPUT);
- EXPECT_EQ(sent_msgs[0].data.device_data.runtime.tv_sec, 100);
-
- sent_msgs.clear();
-
- clock_gettime_retspec.tv_sec = 300;
- clock_gettime_retspec.tv_nsec = 0;
- iodev.open_ts.tv_sec = 100;
- iodev.open_ts.tv_nsec = 0;
- iodev.direction = CRAS_STREAM_OUTPUT;
- iodev.active_node = &active_node;
- active_node.type = CRAS_NODE_TYPE_HEADPHONE;
-
- cras_server_metrics_device_runtime(&iodev);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, DEVICE_RUNTIME);
- EXPECT_EQ(sent_msgs[0].data.device_data.type, CRAS_METRICS_DEVICE_HEADPHONE);
- EXPECT_EQ(sent_msgs[0].data.device_data.direction, CRAS_STREAM_OUTPUT);
- EXPECT_EQ(sent_msgs[0].data.device_data.runtime.tv_sec, 200);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsHighestDeviceDelay) {
- ResetStubData();
- unsigned int hw_level = 1000;
- unsigned int largest_cb_level = 500;
-
- cras_server_metrics_highest_device_delay(hw_level, largest_cb_level,
- CRAS_STREAM_INPUT);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, HIGHEST_DEVICE_DELAY_INPUT);
- EXPECT_EQ(sent_msgs[0].data.value, 2000);
-
- sent_msgs.clear();
-
- cras_server_metrics_highest_device_delay(hw_level, largest_cb_level,
- CRAS_STREAM_OUTPUT);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, HIGHEST_DEVICE_DELAY_OUTPUT);
- EXPECT_EQ(sent_msgs[0].data.value, 2000);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricHighestHardwareLevel) {
- ResetStubData();
- unsigned int hw_level = 1000;
-
- cras_server_metrics_highest_hw_level(hw_level, CRAS_STREAM_INPUT);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, HIGHEST_INPUT_HW_LEVEL);
- EXPECT_EQ(sent_msgs[0].data.value, hw_level);
-
- sent_msgs.clear();
-
- cras_server_metrics_highest_hw_level(hw_level, CRAS_STREAM_OUTPUT);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, HIGHEST_OUTPUT_HW_LEVEL);
- EXPECT_EQ(sent_msgs[0].data.value, hw_level);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsNumUnderruns) {
- ResetStubData();
- unsigned int underrun = 10;
-
- cras_server_metrics_num_underruns(underrun);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, NUM_UNDERRUNS);
- EXPECT_EQ(sent_msgs[0].data.value, underrun);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsMissedCallbackEventInputStream) {
- ResetStubData();
- struct cras_rstream stream;
- struct timespec diff_ts;
-
- stream.flags = 0;
- stream.start_ts.tv_sec = 0;
- stream.start_ts.tv_nsec = 0;
- stream.num_missed_cb = 0;
- stream.direction = CRAS_STREAM_INPUT;
-
- clock_gettime_retspec.tv_sec = 100;
- clock_gettime_retspec.tv_nsec = 0;
- cras_server_metrics_missed_cb_event(&stream);
-
- subtract_timespecs(&clock_gettime_retspec, &stream.start_ts, &diff_ts);
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, MISSED_CB_FIRST_TIME_INPUT);
- EXPECT_EQ(sent_msgs[0].data.value, diff_ts.tv_sec);
- EXPECT_EQ(stream.num_missed_cb, 1);
- EXPECT_EQ(stream.first_missed_cb_ts.tv_sec, clock_gettime_retspec.tv_sec);
- EXPECT_EQ(stream.first_missed_cb_ts.tv_nsec, clock_gettime_retspec.tv_nsec);
-
- clock_gettime_retspec.tv_sec = 200;
- clock_gettime_retspec.tv_nsec = 0;
- cras_server_metrics_missed_cb_event(&stream);
-
- subtract_timespecs(&clock_gettime_retspec, &stream.first_missed_cb_ts,
- &diff_ts);
- EXPECT_EQ(sent_msgs.size(), 2);
- EXPECT_EQ(sent_msgs[1].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[1].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[1].metrics_type, MISSED_CB_SECOND_TIME_INPUT);
- EXPECT_EQ(sent_msgs[1].data.value, diff_ts.tv_sec);
- EXPECT_EQ(stream.num_missed_cb, 2);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsMissedCallbackEventOutputStream) {
- ResetStubData();
- struct cras_rstream stream;
- struct timespec diff_ts;
-
- stream.flags = 0;
- stream.start_ts.tv_sec = 0;
- stream.start_ts.tv_nsec = 0;
- stream.num_missed_cb = 0;
- stream.direction = CRAS_STREAM_OUTPUT;
-
- clock_gettime_retspec.tv_sec = 100;
- clock_gettime_retspec.tv_nsec = 0;
- cras_server_metrics_missed_cb_event(&stream);
-
- subtract_timespecs(&clock_gettime_retspec, &stream.start_ts, &diff_ts);
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, MISSED_CB_FIRST_TIME_OUTPUT);
- EXPECT_EQ(sent_msgs[0].data.value, diff_ts.tv_sec);
- EXPECT_EQ(stream.num_missed_cb, 1);
- EXPECT_EQ(stream.first_missed_cb_ts.tv_sec, clock_gettime_retspec.tv_sec);
- EXPECT_EQ(stream.first_missed_cb_ts.tv_nsec, clock_gettime_retspec.tv_nsec);
-
- clock_gettime_retspec.tv_sec = 200;
- clock_gettime_retspec.tv_nsec = 0;
- cras_server_metrics_missed_cb_event(&stream);
-
- subtract_timespecs(&clock_gettime_retspec, &stream.first_missed_cb_ts,
- &diff_ts);
- EXPECT_EQ(sent_msgs.size(), 2);
- EXPECT_EQ(sent_msgs[1].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[1].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[1].metrics_type, MISSED_CB_SECOND_TIME_OUTPUT);
- EXPECT_EQ(sent_msgs[1].data.value, diff_ts.tv_sec);
- EXPECT_EQ(stream.num_missed_cb, 2);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsStreamCreate) {
- ResetStubData();
- struct cras_rstream_config config;
- struct cras_audio_format format;
-
- config.direction = CRAS_STREAM_INPUT;
- config.cb_threshold = 1024;
- config.flags = BULK_AUDIO_OK;
- format.format = SND_PCM_FORMAT_S16_LE;
- format.frame_rate = 48000;
- config.client_type = CRAS_CLIENT_TYPE_TEST;
- config.format = &format;
- cras_server_metrics_stream_create(&config);
-
- // Log stream config.
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, STREAM_CONFIG);
- EXPECT_EQ(sent_msgs[0].data.stream_config.direction, CRAS_STREAM_INPUT);
- EXPECT_EQ(sent_msgs[0].data.stream_config.cb_threshold, 1024);
- EXPECT_EQ(sent_msgs[0].data.stream_config.flags, BULK_AUDIO_OK);
- EXPECT_EQ(sent_msgs[0].data.stream_config.format, SND_PCM_FORMAT_S16_LE);
- EXPECT_EQ(sent_msgs[0].data.stream_config.rate, 48000);
- EXPECT_EQ(sent_msgs[0].data.stream_config.client_type, CRAS_CLIENT_TYPE_TEST);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsStreamDestroy) {
- ResetStubData();
- struct cras_rstream stream;
- struct timespec diff_ts;
-
- stream.flags = 0;
- stream.start_ts.tv_sec = 0;
- stream.start_ts.tv_nsec = 0;
- clock_gettime_retspec.tv_sec = 1000;
- clock_gettime_retspec.tv_nsec = 0;
- stream.num_missed_cb = 5;
- stream.first_missed_cb_ts.tv_sec = 100;
- stream.first_missed_cb_ts.tv_nsec = 0;
- stream.longest_fetch_interval.tv_sec = 1;
- stream.longest_fetch_interval.tv_nsec = 0;
- stream.sleep_interval_ts.tv_sec = 0;
- stream.sleep_interval_ts.tv_nsec = 5000000;
-
- stream.direction = CRAS_STREAM_INPUT;
- stream.client_type = CRAS_CLIENT_TYPE_TEST;
- stream.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- cras_server_metrics_stream_destroy(&stream);
-
- subtract_timespecs(&clock_gettime_retspec, &stream.start_ts, &diff_ts);
- EXPECT_EQ(sent_msgs.size(), 4);
-
- // Log missed cb frequency.
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, MISSED_CB_FREQUENCY_INPUT);
- EXPECT_EQ(sent_msgs[0].data.value,
- stream.num_missed_cb * 86400 / diff_ts.tv_sec);
-
- // Log missed cb frequency after rescheduling.
- subtract_timespecs(&clock_gettime_retspec, &stream.first_missed_cb_ts,
- &diff_ts);
- EXPECT_EQ(sent_msgs[1].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[1].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[1].metrics_type,
- MISSED_CB_FREQUENCY_AFTER_RESCHEDULING_INPUT);
- EXPECT_EQ(sent_msgs[1].data.value,
- (stream.num_missed_cb - 1) * 86400 / diff_ts.tv_sec);
-
- // Log stream runtime.
- EXPECT_EQ(sent_msgs[2].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[2].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[2].metrics_type, STREAM_RUNTIME);
- EXPECT_EQ(sent_msgs[2].data.stream_data.client_type, CRAS_CLIENT_TYPE_TEST);
- EXPECT_EQ(sent_msgs[2].data.stream_data.stream_type,
- CRAS_STREAM_TYPE_DEFAULT);
- EXPECT_EQ(sent_msgs[2].data.stream_data.direction, CRAS_STREAM_INPUT);
- EXPECT_EQ(sent_msgs[2].data.stream_data.runtime.tv_sec, 1000);
-
- // Log longest fetch delay.
- EXPECT_EQ(sent_msgs[3].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[3].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[3].metrics_type, LONGEST_FETCH_DELAY);
- EXPECT_EQ(sent_msgs[3].data.stream_data.client_type, CRAS_CLIENT_TYPE_TEST);
- EXPECT_EQ(sent_msgs[3].data.stream_data.stream_type,
- CRAS_STREAM_TYPE_DEFAULT);
- EXPECT_EQ(sent_msgs[3].data.stream_data.direction, CRAS_STREAM_INPUT);
- EXPECT_EQ(sent_msgs[3].data.stream_data.runtime.tv_sec, 0);
- EXPECT_EQ(sent_msgs[3].data.stream_data.runtime.tv_nsec, 995000000);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsBusyloop) {
- ResetStubData();
- struct timespec time = {40, 0};
- unsigned count = 3;
-
- cras_server_metrics_busyloop(&time, count);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, BUSYLOOP);
- EXPECT_EQ(sent_msgs[0].data.timespec_data.runtime.tv_sec, 40);
- EXPECT_EQ(sent_msgs[0].data.timespec_data.runtime.tv_nsec, 0);
- EXPECT_EQ(sent_msgs[0].data.timespec_data.count, 3);
-}
-
-TEST(ServerMetricsTestSuite, SetMetricsBusyloopLength) {
- ResetStubData();
- unsigned length = 5;
-
- cras_server_metrics_busyloop_length(length);
-
- EXPECT_EQ(sent_msgs.size(), 1);
- EXPECT_EQ(sent_msgs[0].header.type, CRAS_MAIN_METRICS);
- EXPECT_EQ(sent_msgs[0].header.length,
- sizeof(struct cras_server_metrics_message));
- EXPECT_EQ(sent_msgs[0].metrics_type, BUSYLOOP_LENGTH);
- EXPECT_EQ(sent_msgs[0].data.value, 5);
-}
-
-extern "C" {
-
-int cras_main_message_add_handler(enum CRAS_MAIN_MESSAGE_TYPE type,
- cras_message_callback callback,
- void* callback_data) {
- type_set = type;
- return 0;
-}
-
-void cras_metrics_log_histogram(const char* name,
- int sample,
- int min,
- int max,
- int nbuckets) {}
-
-void cras_metrics_log_sparse_histogram(const char* name, int sample) {}
-
-int cras_main_message_send(struct cras_main_message* msg) {
- // Copy the sent message so we can examine it in the test later.
- struct cras_server_metrics_message sent_msg;
- memcpy(&sent_msg, msg, sizeof(sent_msg));
- sent_msgs.push_back(sent_msg);
- return 0;
-}
-
-int cras_system_state_in_main_thread() {
- return 0;
-}
-
-// From librt.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = clock_gettime_retspec.tv_sec;
- tp->tv_nsec = clock_gettime_retspec.tv_nsec;
- return 0;
-}
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- int rc = RUN_ALL_TESTS();
-
- return rc;
-}
diff --git a/cras/src/tests/shm_unittest.cc b/cras/src/tests/shm_unittest.cc
deleted file mode 100644
index b5df1f69..00000000
--- a/cras/src/tests/shm_unittest.cc
+++ /dev/null
@@ -1,572 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_shm.h"
-#include "cras_types.h"
-}
-
-namespace {
-
-class ShmTestSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- memset(&shm_, 0, sizeof(shm_));
- shm_.header =
- static_cast<cras_audio_shm_header*>(calloc(1, sizeof(*shm_.header)));
- shm_.samples = static_cast<uint8_t*>(calloc(1, 2048));
- shm_.samples_info.length = 2048;
- cras_shm_set_frame_bytes(&shm_, 4);
-
- cras_shm_set_used_size(&shm_, 1024);
- memcpy(&shm_.header->config, &shm_.config, sizeof(shm_.config));
-
- frames_ = 0;
- }
-
- virtual void TearDown() {
- free(shm_.header);
- free(shm_.samples);
- }
-
- struct cras_audio_shm shm_;
- uint8_t* buf_;
- size_t frames_;
-};
-
-// Test that and empty buffer returns 0 readable bytes.
-TEST_F(ShmTestSuite, NoneReadableWhenEmpty) {
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(0, frames_);
- cras_shm_buffer_read(&shm_, frames_);
- EXPECT_EQ(0, shm_.header->read_offset[0]);
-}
-
-// Buffer with 100 frames filled.
-TEST_F(ShmTestSuite, OneHundredFilled) {
- shm_.header->write_offset[0] = 100 * shm_.header->config.frame_bytes;
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(100, frames_);
- EXPECT_EQ(shm_.samples, buf_);
- cras_shm_buffer_read(&shm_, frames_ - 9);
- EXPECT_EQ((frames_ - 9) * shm_.config.frame_bytes,
- shm_.header->read_offset[0]);
- cras_shm_buffer_read(&shm_, 9);
- EXPECT_EQ(0, shm_.header->read_offset[0]);
- EXPECT_EQ(1, shm_.header->read_buf_idx);
-}
-
-// Buffer with 100 frames filled, 50 read.
-TEST_F(ShmTestSuite, OneHundredFilled50Read) {
- shm_.header->write_offset[0] = 100 * shm_.config.frame_bytes;
- shm_.header->read_offset[0] = 50 * shm_.config.frame_bytes;
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(50, frames_);
- EXPECT_EQ((shm_.samples + shm_.header->read_offset[0]), buf_);
- cras_shm_buffer_read(&shm_, frames_ - 10);
- EXPECT_EQ(shm_.header->write_offset[0] - 10 * shm_.config.frame_bytes,
- shm_.header->read_offset[0]);
- cras_shm_buffer_read(&shm_, 10);
- EXPECT_EQ(0, shm_.header->read_offset[0]);
-}
-
-// Buffer with 100 frames filled, 50 read, offset by 25.
-TEST_F(ShmTestSuite, OneHundredFilled50Read25offset) {
- shm_.header->write_offset[0] = 100 * shm_.config.frame_bytes;
- shm_.header->read_offset[0] = 50 * shm_.config.frame_bytes;
- buf_ = cras_shm_get_readable_frames(&shm_, 25, &frames_);
- EXPECT_EQ(25, frames_);
- EXPECT_EQ(shm_.samples + shm_.header->read_offset[0] +
- 25 * shm_.header->config.frame_bytes,
- (uint8_t*)buf_);
-}
-
-// Test wrapping across buffers.
-TEST_F(ShmTestSuite, WrapToNextBuffer) {
- uint32_t used_size = cras_shm_used_size(&shm_);
- uint32_t used_frames = used_size / cras_shm_frame_bytes(&shm_);
- shm_.header->write_offset[0] = (used_size / 2);
- shm_.header->read_offset[0] = (used_size / 4);
- shm_.header->write_offset[1] = (used_size / 2);
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(used_frames / 4, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 0) + (used_size / 4), (uint8_t*)buf_);
- buf_ = cras_shm_get_readable_frames(&shm_, frames_, &frames_);
- EXPECT_EQ(used_frames / 2, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 1), (uint8_t*)buf_);
- /* Mark all but 10 frames as read */
- cras_shm_buffer_read(&shm_, (used_frames / 2) + (used_frames / 4) - 10);
- EXPECT_EQ(0, shm_.header->read_offset[0]);
- EXPECT_EQ(((used_frames / 2) - 10) * shm_.config.frame_bytes,
- shm_.header->read_offset[1]);
- EXPECT_EQ(1, shm_.header->read_buf_idx);
-}
-
-// Test wrapping across buffers reading all samples.
-TEST_F(ShmTestSuite, WrapToNextBufferReadAll) {
- uint32_t used_size = cras_shm_used_size(&shm_);
- uint32_t used_frames = used_size / cras_shm_frame_bytes(&shm_);
- shm_.header->write_offset[0] = (used_size / 2);
- shm_.header->read_offset[0] = (used_size / 4);
- shm_.header->write_offset[1] = (used_size / 2);
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(used_frames / 4, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 0) + (used_size / 4), (uint8_t*)buf_);
- buf_ = cras_shm_get_readable_frames(&shm_, frames_, &frames_);
- EXPECT_EQ(used_frames / 2, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 1), (uint8_t*)buf_);
- /* Mark all frames as read */
- cras_shm_buffer_read(&shm_, (used_frames / 2) + (used_frames / 4));
- EXPECT_EQ(0, shm_.header->read_offset[0]);
- EXPECT_EQ(0, shm_.header->read_offset[1]);
- EXPECT_EQ(0, shm_.header->read_buf_idx);
-}
-
-// Test wrapping last buffer.
-TEST_F(ShmTestSuite, WrapFromFinalBuffer) {
- uint32_t used_size = cras_shm_used_size(&shm_);
- uint32_t used_frames = used_size / cras_shm_frame_bytes(&shm_);
- uint32_t buf_idx = CRAS_NUM_SHM_BUFFERS - 1;
-
- shm_.header->read_buf_idx = buf_idx;
- shm_.header->write_offset[buf_idx] = (used_size / 2);
- shm_.header->read_offset[buf_idx] = (used_size / 4);
- shm_.header->write_offset[0] = (used_size / 2);
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(used_frames / 4, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, buf_idx) + (used_size / 4),
- (uint8_t*)buf_);
-
- buf_ = cras_shm_get_readable_frames(&shm_, frames_, &frames_);
- EXPECT_EQ(used_frames / 2, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 0), (uint8_t*)buf_);
- /* Mark all but 10 frames as read */
- cras_shm_buffer_read(&shm_, (used_frames / 2) + (used_frames / 4) - 10);
- EXPECT_EQ(0, shm_.header->read_offset[buf_idx]);
- EXPECT_EQ(((used_frames / 2) - 10) * shm_.config.frame_bytes,
- shm_.header->read_offset[0]);
- EXPECT_EQ(0, shm_.header->read_buf_idx);
-}
-
-// Test Check available to write returns 0 if not free buffer.
-TEST_F(ShmTestSuite, WriteAvailNotFree) {
- size_t ret;
- shm_.header->write_buf_idx = 0;
- shm_.header->write_offset[0] = 100 * shm_.config.frame_bytes;
- shm_.header->read_offset[0] = 50 * shm_.config.frame_bytes;
- ret = cras_shm_get_num_writeable(&shm_);
- EXPECT_EQ(0, ret);
-}
-
-// Test Check available to write returns num_frames if free buffer.
-TEST_F(ShmTestSuite, WriteAvailValid) {
- size_t ret;
- shm_.header->write_buf_idx = 0;
- shm_.config.used_size = 480 * shm_.config.frame_bytes;
- shm_.header->write_offset[0] = 0;
- shm_.header->read_offset[0] = 0;
- ret = cras_shm_get_num_writeable(&shm_);
- EXPECT_EQ(480, ret);
-}
-
-// Test get frames_written returns the number of frames written.
-TEST_F(ShmTestSuite, GetNumWritten) {
- size_t ret;
- shm_.header->write_buf_idx = 0;
- shm_.config.used_size = 480 * shm_.config.frame_bytes;
- shm_.header->write_offset[0] = 200 * shm_.config.frame_bytes;
- shm_.header->read_offset[0] = 0;
- ret = cras_shm_frames_written(&shm_);
- EXPECT_EQ(200, ret);
-}
-
-// Test that getting the base of the write buffer returns the correct pointer.
-TEST_F(ShmTestSuite, GetWriteBufferBase) {
- uint8_t* ret;
-
- shm_.header->write_buf_idx = 0;
- shm_.header->write_offset[0] = 128 * shm_.config.frame_bytes;
- shm_.header->write_offset[1] = 128 * shm_.config.frame_bytes;
- shm_.header->read_offset[0] = 0;
- shm_.header->read_offset[1] = 0;
- ret = cras_shm_get_write_buffer_base(&shm_);
- EXPECT_EQ(shm_.samples, ret);
-
- shm_.header->write_buf_idx = 1;
- ret = cras_shm_get_write_buffer_base(&shm_);
- EXPECT_EQ(shm_.samples + shm_.config.used_size, ret);
-}
-
-TEST_F(ShmTestSuite, SetVolume) {
- cras_shm_set_volume_scaler(&shm_, 1.0);
- EXPECT_EQ(shm_.header->volume_scaler, 1.0);
- cras_shm_set_volume_scaler(&shm_, 1.4);
- EXPECT_EQ(shm_.header->volume_scaler, 1.0);
- cras_shm_set_volume_scaler(&shm_, -0.5);
- EXPECT_EQ(shm_.header->volume_scaler, 0.0);
- cras_shm_set_volume_scaler(&shm_, 0.5);
- EXPECT_EQ(shm_.header->volume_scaler, 0.5);
-}
-
-// Test that invalid read/write offsets are detected.
-
-TEST_F(ShmTestSuite, InvalidWriteOffset) {
- shm_.header->write_offset[0] = shm_.config.used_size + 50;
- shm_.header->read_offset[0] = 0;
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(shm_.config.used_size / 4, frames_);
-}
-
-TEST_F(ShmTestSuite, InvalidReadOffset) {
- // Should ignore read+_offset and assume 0.
- shm_.header->write_offset[0] = 44;
- shm_.header->read_offset[0] = shm_.config.used_size + 25;
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(shm_.header->write_offset[0] / shm_.config.frame_bytes, frames_);
- EXPECT_EQ(shm_.samples, (uint8_t*)buf_);
-}
-
-TEST_F(ShmTestSuite, InvalidReadAndWriteOffset) {
- shm_.header->write_offset[0] = shm_.config.used_size + 50;
- shm_.header->read_offset[0] = shm_.config.used_size + 25;
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(shm_.config.used_size / 4, frames_);
-}
-
-TEST_F(ShmTestSuite, InputBufferOverrun) {
- int rc;
- shm_.header->write_offset[0] = 0;
- shm_.header->read_offset[0] = 0;
- shm_.header->write_offset[1] = 0;
- shm_.header->read_offset[1] = 0;
-
- shm_.header->write_buf_idx = 0;
- shm_.header->read_buf_idx = 0;
-
- EXPECT_EQ(0, cras_shm_num_overruns(&shm_));
- rc = cras_shm_check_write_overrun(&shm_);
- EXPECT_EQ(0, rc);
- cras_shm_buffer_written(&shm_, 100);
- cras_shm_buffer_write_complete(&shm_);
-
- rc = cras_shm_check_write_overrun(&shm_);
- EXPECT_EQ(0, rc);
- cras_shm_buffer_written(&shm_, 100);
- cras_shm_buffer_write_complete(&shm_);
-
- // Assert two consecutive writes causes overrun.
- rc = cras_shm_check_write_overrun(&shm_);
- EXPECT_EQ(1, rc);
- EXPECT_EQ(1, cras_shm_num_overruns(&shm_));
-}
-
-TEST_F(ShmTestSuite, GetWritableFramesNeedToWrite) {
- unsigned buffer_size = 480;
- unsigned limit = 480;
- unsigned written = 200;
- unsigned frames;
- shm_.header->write_buf_idx = 0;
- shm_.config.used_size = buffer_size * shm_.config.frame_bytes;
- shm_.header->write_offset[0] = written * shm_.config.frame_bytes;
- buf_ = cras_shm_get_writeable_frames(&shm_, limit, &frames);
- EXPECT_EQ(limit - written, frames);
- EXPECT_EQ(shm_.samples + shm_.header->write_offset[0], buf_);
-}
-
-TEST_F(ShmTestSuite, GetWritableFramesNoNeedToWrite) {
- unsigned buffer_size = 480;
- unsigned limit = 240;
- unsigned written = 300;
- unsigned frames;
- shm_.header->write_buf_idx = 0;
- shm_.config.used_size = buffer_size * shm_.config.frame_bytes;
- shm_.header->write_offset[0] = written * shm_.config.frame_bytes;
- buf_ = cras_shm_get_writeable_frames(&shm_, limit, &frames);
- EXPECT_EQ(0, frames);
- EXPECT_EQ(shm_.samples + shm_.header->write_offset[0], buf_);
-}
-
-// Test wrapping of buffers that don't start at normal offsets.
-TEST_F(ShmTestSuite, WrapWithNonstandardBufferLocations) {
- uint32_t frame_bytes = cras_shm_frame_bytes(&shm_);
- uint32_t used_frames = 24;
- uint32_t used_size = used_frames * frame_bytes;
- cras_shm_set_used_size(&shm_, used_size);
- cras_shm_set_buffer_offset(&shm_, 0, 15);
- cras_shm_set_buffer_offset(&shm_, 1, 479);
-
- shm_.header->read_offset[0] = (used_frames / 4) * shm_.config.frame_bytes;
- shm_.header->write_offset[0] = (used_frames / 2) * shm_.config.frame_bytes;
- shm_.header->read_offset[1] = 0;
- shm_.header->write_offset[1] = (used_frames / 3) * shm_.config.frame_bytes;
- buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_);
- EXPECT_EQ(used_frames / 4, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 0) + shm_.header->read_offset[0],
- (uint8_t*)buf_);
- buf_ = cras_shm_get_readable_frames(&shm_, frames_, &frames_);
- EXPECT_EQ(used_frames / 3, frames_);
- EXPECT_EQ(cras_shm_buff_for_idx(&shm_, 1), (uint8_t*)buf_);
- /* Mark all but 5 frames as read */
- cras_shm_buffer_read(&shm_, (used_frames / 4) + (used_frames / 3) - 5);
- EXPECT_EQ(0, shm_.header->read_offset[0]);
- EXPECT_EQ(((used_frames / 3) - 5) * shm_.config.frame_bytes,
- shm_.header->read_offset[1]);
-}
-
-TEST_F(ShmTestSuite, PlaybackWithDifferentSequentialBufferLocations) {
- uint32_t frame_bytes = cras_shm_frame_bytes(&shm_);
- uint32_t used_frames = 24;
- uint32_t used_size = used_frames * frame_bytes;
- cras_shm_set_used_size(&shm_, used_size);
-
- uint32_t first_offset = 2.7 * used_size;
- /* Make samples area long enough to hold all of the buffers starting from
- * first_offset, with an extra 'used_size' bytes of free space at the end. */
- uint32_t samples_length =
- first_offset + used_size * (CRAS_NUM_SHM_BUFFERS + 1);
- free(shm_.samples);
- shm_.samples = static_cast<uint8_t*>(calloc(1, samples_length));
- shm_.samples_info.length = samples_length;
- uint32_t total_frames_written = 0;
-
- // Fill all of the buffers.
- for (unsigned int i = 0; i < CRAS_NUM_SHM_BUFFERS; i++) {
- cras_shm_set_buffer_offset(&shm_, i, first_offset + i * used_size);
- shm_.header->write_in_progress[i] = 1;
- shm_.header->write_offset[i] = 0;
- frames_ = MIN(10 + i, used_frames);
- cras_shm_buffer_written(&shm_, frames_);
- total_frames_written += frames_;
- cras_shm_buffer_write_complete(&shm_);
- }
-
- uint32_t total_frames_available = 0;
-
- // Consume all available frames.
- while ((buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_))) {
- total_frames_available += frames_;
-
- EXPECT_GE(buf_, shm_.samples);
- EXPECT_LE(buf_ + frames_, shm_.samples + samples_length);
- cras_shm_buffer_read(&shm_, frames_);
- }
-
- EXPECT_EQ(total_frames_written, total_frames_available);
-
- uint32_t second_offset = 1.2 * used_size;
-
- // Fill half of the buffers.
- for (unsigned int i = 0; i < CRAS_NUM_SHM_BUFFERS / 2; i++) {
- cras_shm_set_buffer_offset(&shm_, i, second_offset + i * used_size);
- shm_.header->write_in_progress[i] = 1;
- shm_.header->write_offset[i] = 0;
- frames_ = MIN(3 + 2 * i, used_frames);
- cras_shm_buffer_written(&shm_, frames_);
- total_frames_written += frames_;
- cras_shm_buffer_write_complete(&shm_);
- }
-
- // Consume all available frames.
- while ((buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_))) {
- total_frames_available += frames_;
-
- EXPECT_GE(buf_, shm_.samples);
- EXPECT_LE(buf_ + frames_, shm_.samples + samples_length);
- cras_shm_buffer_read(&shm_, frames_);
- }
-
- EXPECT_EQ(total_frames_written, total_frames_available);
-
- // Fill rest of the buffers.
- for (unsigned int i = CRAS_NUM_SHM_BUFFERS / 2; i < CRAS_NUM_SHM_BUFFERS;
- i++) {
- cras_shm_set_buffer_offset(&shm_, i, second_offset + i * used_size);
- shm_.header->write_in_progress[i] = 1;
- shm_.header->write_offset[i] = 0;
- frames_ = MIN(3 + 2 * i, used_frames);
- cras_shm_buffer_written(&shm_, frames_);
- total_frames_written += frames_;
- cras_shm_buffer_write_complete(&shm_);
- }
-
- // Consume all available frames.
- while ((buf_ = cras_shm_get_readable_frames(&shm_, 0, &frames_))) {
- total_frames_available += frames_;
-
- EXPECT_GE(buf_, shm_.samples);
- EXPECT_LE(buf_ + frames_, shm_.samples + samples_length);
- cras_shm_buffer_read(&shm_, frames_);
- }
-
- EXPECT_EQ(total_frames_written, total_frames_available);
-}
-
-TEST_F(ShmTestSuite, GetCheckedBufferOffset) {
- uint32_t used_size = cras_shm_used_size(&shm_);
- uint32_t samples_length = used_size * 8;
- shm_.samples_info.length = samples_length;
-
- uint32_t offset;
-
- for (unsigned int i = 0; i < CRAS_NUM_SHM_BUFFERS; i++) {
- shm_.header->buffer_offset[i] = 0;
- offset = cras_shm_get_checked_buffer_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected valid buffer offset for buffer " << i;
-
- shm_.header->buffer_offset[i] = used_size;
- offset = cras_shm_get_checked_buffer_offset(&shm_, i);
- EXPECT_EQ(used_size, offset)
- << "Expected valid buffer offset for buffer " << i;
-
- shm_.header->buffer_offset[i] = samples_length - 1;
- offset = cras_shm_get_checked_buffer_offset(&shm_, i);
- EXPECT_EQ(samples_length - 1, offset)
- << "Expected valid buffer offset for buffer " << i;
-
- shm_.header->buffer_offset[i] = samples_length;
- offset = cras_shm_get_checked_buffer_offset(&shm_, i);
- EXPECT_EQ(samples_length, offset)
- << "Expected valid buffer offset for buffer " << i;
-
- shm_.header->buffer_offset[i] = samples_length + 1;
- offset = cras_shm_get_checked_buffer_offset(&shm_, i);
- EXPECT_EQ(samples_length, offset)
- << "Expected invalid buffer offset for buffer " << i;
-
- shm_.header->buffer_offset[i] = samples_length + used_size;
- offset = cras_shm_get_checked_buffer_offset(&shm_, i);
- EXPECT_EQ(samples_length, offset)
- << "Expected invalid buffer offset for buffer " << i;
- }
-}
-
-TEST_F(ShmTestSuite, GetCheckedReadOffset) {
- uint32_t used_size = cras_shm_used_size(&shm_);
- uint32_t samples_length = used_size * 8;
- shm_.samples_info.length = samples_length;
-
- uint32_t offset;
-
- for (unsigned int i = 0; i < CRAS_NUM_SHM_BUFFERS; i++) {
- shm_.header->read_offset[i] = 0;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected valid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size / 2;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(used_size / 2, offset)
- << "Expected valid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(used_size, offset)
- << "Expected valid read offset for buffer " << i;
-
- // Read offsets should not be greater than used_size.
- shm_.header->read_offset[i] = used_size + 1;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected invalid read offset for buffer " << i;
-
- shm_.header->buffer_offset[i] = samples_length - used_size / 2;
-
- shm_.header->read_offset[i] = 0;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected valid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size / 4;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(used_size / 4, offset)
- << "Expected valid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size / 2;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(used_size / 2, offset)
- << "Expected valid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size / 2 + 1;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected invalid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected invalid read offset for buffer " << i;
-
- shm_.header->read_offset[i] = used_size + 1;
- offset = cras_shm_get_checked_read_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected invalid read offset for buffer " << i;
- }
-}
-
-TEST_F(ShmTestSuite, GetCheckedWriteOffset) {
- uint32_t used_size = cras_shm_used_size(&shm_);
- uint32_t samples_length = used_size * 8;
- shm_.samples_info.length = samples_length;
-
- uint32_t offset;
-
- for (unsigned int i = 0; i < CRAS_NUM_SHM_BUFFERS; i++) {
- shm_.header->write_offset[i] = 0;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected valid write offset for buffer " << i;
-
- shm_.header->write_offset[i] = used_size / 2;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(used_size / 2, offset)
- << "Expected valid write offset for buffer " << i;
-
- shm_.header->write_offset[i] = used_size;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(used_size, offset)
- << "Expected valid write offset for buffer " << i;
-
- // Write offsets should not be greater than used_size.
- shm_.header->write_offset[i] = used_size + 1;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(used_size, offset)
- << "Expected invalid write offset for buffer " << i;
-
- uint32_t buffer_offset = samples_length - used_size / 2;
- shm_.header->buffer_offset[i] = buffer_offset;
-
- shm_.header->write_offset[i] = 0;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(0, offset) << "Expected valid write offset for buffer " << i;
-
- shm_.header->write_offset[i] = used_size / 4;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(used_size / 4, offset)
- << "Expected valid write offset for buffer " << i;
-
- shm_.header->write_offset[i] = used_size / 2;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(used_size / 2, offset)
- << "Expected valid write offset for buffer " << i;
-
- // Write offsets should not be longer than the samples area.
- shm_.header->write_offset[i] = used_size / 2 + 1;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(samples_length - buffer_offset, offset)
- << "Expected invalid write offset for buffer " << i;
-
- shm_.header->write_offset[i] = used_size;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(samples_length - buffer_offset, offset)
- << "Expected invalid write offset for buffer " << i;
-
- shm_.header->write_offset[i] = used_size + 1;
- offset = cras_shm_get_checked_write_offset(&shm_, i);
- EXPECT_EQ(samples_length - buffer_offset, offset)
- << "Expected invalid write offset for buffer " << i;
- }
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/softvol_curve_unittest.cc b/cras/src/tests/softvol_curve_unittest.cc
deleted file mode 100644
index d1444588..00000000
--- a/cras/src/tests/softvol_curve_unittest.cc
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2015 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "softvol_curve.h"
-}
-
-namespace {
-
-static float ABS_ERROR = 0.0000001;
-
-TEST(SoftvolCurveTest, ScalerDecibelConvert) {
- float scaler;
- scaler = convert_softvol_scaler_from_dB(-2000);
- EXPECT_NEAR(scaler, 0.1f, ABS_ERROR);
- scaler = convert_softvol_scaler_from_dB(-1000);
- EXPECT_NEAR(scaler, 0.3162277f, ABS_ERROR);
- scaler = convert_softvol_scaler_from_dB(-4000);
- EXPECT_NEAR(scaler, 0.01f, ABS_ERROR);
- scaler = convert_softvol_scaler_from_dB(-3500);
- EXPECT_NEAR(scaler, 0.0177828f, ABS_ERROR);
-}
-
-} // namespace
-
-/* Stubs */
-extern "C" {} // extern "C"
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/stream_list_unittest.cc b/cras/src/tests/stream_list_unittest.cc
deleted file mode 100644
index 500774f1..00000000
--- a/cras/src/tests/stream_list_unittest.cc
+++ /dev/null
@@ -1,216 +0,0 @@
-// Copyright 2015 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_rstream.h"
-#include "stream_list.h"
-}
-
-namespace {
-
-static unsigned int add_called;
-static int added_cb(struct cras_rstream* rstream) {
- add_called++;
- return 0;
-}
-
-static unsigned int rm_called;
-static struct cras_rstream* rmed_stream;
-static int removed_cb(struct cras_rstream* rstream) {
- rm_called++;
- rmed_stream = rstream;
- return 0;
-}
-
-static unsigned int create_called;
-static struct cras_rstream_config* create_config;
-static int create_rstream_cb(struct cras_rstream_config* stream_config,
- struct cras_rstream** stream) {
- create_called++;
- create_config = stream_config;
- *stream = (struct cras_rstream*)malloc(sizeof(struct cras_rstream));
- (*stream)->stream_id = stream_config->stream_id;
- (*stream)->direction = stream_config->direction;
- if (stream_config->format)
- (*stream)->format = *(stream_config->format);
- (*stream)->cb_threshold = stream_config->cb_threshold;
- (*stream)->client_type = stream_config->client_type;
- (*stream)->stream_type = stream_config->stream_type;
- clock_gettime(CLOCK_MONOTONIC_RAW, &(*stream)->start_ts);
-
- return 0;
-}
-
-static unsigned int destroy_called;
-static struct cras_rstream* destroyed_stream;
-static void destroy_rstream_cb(struct cras_rstream* rstream) {
- destroy_called++;
- destroyed_stream = rstream;
- free(rstream);
-}
-
-static void reset_test_data() {
- add_called = 0;
- rm_called = 0;
- create_called = 0;
- destroy_called = 0;
-}
-
-TEST(StreamList, AddRemove) {
- struct stream_list* l;
- struct cras_rstream* s1;
- struct cras_rstream_config s1_config;
-
- s1_config.stream_id = 0x3003;
- s1_config.direction = CRAS_STREAM_OUTPUT;
- s1_config.format = NULL;
-
- reset_test_data();
- l = stream_list_create(added_cb, removed_cb, create_rstream_cb,
- destroy_rstream_cb, NULL);
- stream_list_add(l, &s1_config, &s1);
- EXPECT_EQ(1, add_called);
- EXPECT_EQ(1, create_called);
- EXPECT_EQ(&s1_config, create_config);
- EXPECT_EQ(0, stream_list_rm(l, 0x3003));
- EXPECT_EQ(1, rm_called);
- EXPECT_EQ(s1, rmed_stream);
- EXPECT_EQ(1, destroy_called);
- EXPECT_EQ(s1, destroyed_stream);
- stream_list_destroy(l);
-}
-
-TEST(StreamList, AddInDescendingOrderByChannels) {
- struct stream_list* l;
- struct cras_rstream* s1;
- struct cras_rstream* s2;
- struct cras_rstream* s3;
- struct cras_audio_format s1_format, s2_format, s3_format;
- struct cras_rstream_config s1_config, s2_config, s3_config;
-
- s1_config.stream_id = 0x4001;
- s1_config.direction = CRAS_STREAM_INPUT;
- s1_format.num_channels = 6;
- s1_config.format = &s1_format;
-
- s2_config.stream_id = 0x4002;
- s2_config.direction = CRAS_STREAM_OUTPUT;
- s2_format.num_channels = 8;
- s2_config.format = &s2_format;
-
- s3_config.stream_id = 0x4003;
- s3_config.direction = CRAS_STREAM_OUTPUT;
- s3_format.num_channels = 2;
- s3_config.format = &s3_format;
-
- reset_test_data();
- l = stream_list_create(added_cb, removed_cb, create_rstream_cb,
- destroy_rstream_cb, NULL);
- stream_list_add(l, &s1_config, &s1);
- EXPECT_EQ(1, add_called);
- EXPECT_EQ(1, create_called);
- EXPECT_EQ(6, stream_list_get(l)->format.num_channels);
-
- stream_list_add(l, &s2_config, &s2);
- EXPECT_EQ(2, add_called);
- EXPECT_EQ(2, create_called);
- EXPECT_EQ(8, stream_list_get(l)->format.num_channels);
- EXPECT_EQ(6, stream_list_get(l)->next->format.num_channels);
-
- stream_list_add(l, &s3_config, &s3);
- EXPECT_EQ(3, add_called);
- EXPECT_EQ(3, create_called);
- EXPECT_EQ(8, stream_list_get(l)->format.num_channels);
- EXPECT_EQ(6, stream_list_get(l)->next->format.num_channels);
- EXPECT_EQ(2, stream_list_get(l)->next->next->format.num_channels);
- EXPECT_EQ(0, stream_list_rm(l, 0x4001));
- EXPECT_EQ(0, stream_list_rm(l, 0x4002));
- EXPECT_EQ(0, stream_list_rm(l, 0x4003));
- stream_list_destroy(l);
-}
-
-TEST(StreamList, DetectRtcStreamPair) {
- struct stream_list* l;
- struct cras_rstream *s1, *s2, *s3, *s4;
- struct cras_rstream_config s1_config, s2_config, s3_config, s4_config;
-
- s1_config.stream_id = 0x5001;
- s1_config.direction = CRAS_STREAM_OUTPUT;
- s1_config.cb_threshold = 480;
- s1_config.client_type = CRAS_CLIENT_TYPE_CHROME;
- s1_config.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- s1_config.format = NULL;
-
- s2_config.stream_id = 0x5002;
- s2_config.direction = CRAS_STREAM_INPUT;
- s2_config.cb_threshold = 480;
- s2_config.client_type = CRAS_CLIENT_TYPE_CHROME;
- s2_config.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- s2_config.format = NULL;
-
- // s3 is not a RTC stream because the cb threshold is not 480.
- s3_config.stream_id = 0x5003;
- s3_config.direction = CRAS_STREAM_INPUT;
- s3_config.cb_threshold = 500;
- s3_config.client_type = CRAS_CLIENT_TYPE_CHROME;
- s3_config.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- s3_config.format = NULL;
-
- // s4 is not a RTC stream because it is not from the same client with s1.
- s4_config.stream_id = 0x5004;
- s4_config.direction = CRAS_STREAM_INPUT;
- s4_config.cb_threshold = 480;
- s4_config.client_type = CRAS_CLIENT_TYPE_LACROS;
- s4_config.stream_type = CRAS_STREAM_TYPE_DEFAULT;
- s4_config.format = NULL;
-
- reset_test_data();
- l = stream_list_create(added_cb, removed_cb, create_rstream_cb,
- destroy_rstream_cb, NULL);
- stream_list_add(l, &s1_config, &s1);
- EXPECT_EQ(1, add_called);
- EXPECT_EQ(1, create_called);
- EXPECT_EQ(&s1_config, create_config);
-
- stream_list_add(l, &s2_config, &s2);
- detect_rtc_stream_pair(l, s2);
- stream_list_add(l, &s3_config, &s3);
- detect_rtc_stream_pair(l, s3);
- stream_list_add(l, &s4_config, &s4);
- detect_rtc_stream_pair(l, s4);
-
- EXPECT_EQ(CRAS_STREAM_TYPE_VOICE_COMMUNICATION, s1->stream_type);
- EXPECT_EQ(CRAS_STREAM_TYPE_VOICE_COMMUNICATION, s2->stream_type);
- EXPECT_EQ(CRAS_STREAM_TYPE_DEFAULT, s3->stream_type);
- EXPECT_EQ(CRAS_STREAM_TYPE_DEFAULT, s4->stream_type);
-
- EXPECT_EQ(0, stream_list_rm(l, 0x5001));
- EXPECT_EQ(0, stream_list_rm(l, 0x5002));
- EXPECT_EQ(0, stream_list_rm(l, 0x5003));
- EXPECT_EQ(0, stream_list_rm(l, 0x5004));
- stream_list_destroy(l);
-}
-
-extern "C" {
-
-struct cras_timer* cras_tm_create_timer(struct cras_tm* tm,
- unsigned int ms,
- void (*cb)(struct cras_timer* t,
- void* data),
- void* cb_data) {
- return reinterpret_cast<struct cras_timer*>(0x404);
-}
-
-void cras_tm_cancel_timer(struct cras_tm* tm, struct cras_timer* t) {}
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/system_state_unittest.cc b/cras/src/tests/system_state_unittest.cc
deleted file mode 100644
index 45224bc9..00000000
--- a/cras/src/tests/system_state_unittest.cc
+++ /dev/null
@@ -1,576 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-#include <string.h>
-
-extern "C" {
-#include "cras_alert.h"
-#include "cras_board_config.h"
-#include "cras_shm.h"
-#include "cras_system_state.h"
-#include "cras_types.h"
-}
-
-namespace {
-static struct cras_alsa_card* kFakeAlsaCard;
-size_t cras_alsa_card_create_called;
-size_t cras_alsa_card_destroy_called;
-static size_t add_stub_called;
-static size_t rm_stub_called;
-static size_t add_task_stub_called;
-static size_t callback_stub_called;
-static void* select_data_value;
-static void* task_data_value;
-static size_t add_callback_called;
-static cras_alert_cb add_callback_cb;
-static void* add_callback_arg;
-static size_t rm_callback_called;
-static cras_alert_cb rm_callback_cb;
-static void* rm_callback_arg;
-static size_t alert_pending_called;
-static char* device_config_dir;
-static const char* cras_alsa_card_config_dir;
-static size_t cras_observer_notify_output_volume_called;
-static size_t cras_observer_notify_output_mute_called;
-static size_t cras_observer_notify_capture_mute_called;
-static size_t cras_observer_notify_suspend_changed_called;
-static size_t cras_observer_notify_num_active_streams_called;
-static size_t cras_observer_notify_input_streams_with_permission_called;
-static size_t cras_iodev_list_reset_for_noise_cancellation_called;
-static struct cras_board_config fake_board_config;
-static size_t cras_alert_process_all_pending_alerts_called;
-
-static void ResetStubData() {
- cras_alsa_card_create_called = 0;
- cras_alsa_card_destroy_called = 0;
- kFakeAlsaCard = reinterpret_cast<struct cras_alsa_card*>(0x33);
- add_stub_called = 0;
- rm_stub_called = 0;
- add_task_stub_called = 0;
- callback_stub_called = 0;
- add_callback_called = 0;
- rm_callback_called = 0;
- alert_pending_called = 0;
- device_config_dir = NULL;
- cras_alsa_card_config_dir = NULL;
- cras_observer_notify_output_volume_called = 0;
- cras_observer_notify_output_mute_called = 0;
- cras_observer_notify_capture_mute_called = 0;
- cras_observer_notify_suspend_changed_called = 0;
- cras_observer_notify_num_active_streams_called = 0;
- cras_observer_notify_input_streams_with_permission_called = 0;
- cras_alert_process_all_pending_alerts_called = 0;
- cras_iodev_list_reset_for_noise_cancellation_called = 0;
- memset(&fake_board_config, 0, sizeof(fake_board_config));
-}
-
-static int add_stub(int fd,
- void (*cb)(void* data, int revents),
- void* callback_data,
- int events,
- void* select_data) {
- add_stub_called++;
- select_data_value = select_data;
- return 0;
-}
-
-static void rm_stub(int fd, void* select_data) {
- rm_stub_called++;
- select_data_value = select_data;
-}
-
-static int add_task_stub(void (*cb)(void* data),
- void* callback_data,
- void* task_data) {
- add_task_stub_called++;
- task_data_value = task_data;
- return 0;
-}
-
-static void callback_stub(void* data, int revents) {
- callback_stub_called++;
-}
-
-static void task_stub(void* data) {
- callback_stub_called++;
-}
-
-static void do_sys_init() {
- char* shm_name;
- ASSERT_GT(asprintf(&shm_name, "/cras-%d", getpid()), 0);
- int rw_shm_fd;
- int ro_shm_fd;
- struct cras_server_state* exp_state =
- (struct cras_server_state*)cras_shm_setup(shm_name, sizeof(*exp_state),
- &rw_shm_fd, &ro_shm_fd);
- if (!exp_state)
- exit(-1);
- cras_system_state_init(device_config_dir, shm_name, rw_shm_fd, ro_shm_fd,
- exp_state, sizeof(*exp_state));
- free(shm_name);
-}
-
-TEST(SystemStateSuite, DefaultVolume) {
- do_sys_init();
- EXPECT_EQ(100, cras_system_get_volume());
- EXPECT_EQ(0, cras_system_get_mute());
- EXPECT_EQ(0, cras_system_get_capture_mute());
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, SetVolume) {
- do_sys_init();
- cras_system_set_volume(0);
- EXPECT_EQ(0, cras_system_get_volume());
- cras_system_set_volume(50);
- EXPECT_EQ(50, cras_system_get_volume());
- cras_system_set_volume(CRAS_MAX_SYSTEM_VOLUME);
- EXPECT_EQ(CRAS_MAX_SYSTEM_VOLUME, cras_system_get_volume());
- cras_system_set_volume(CRAS_MAX_SYSTEM_VOLUME + 1);
- EXPECT_EQ(CRAS_MAX_SYSTEM_VOLUME, cras_system_get_volume());
- cras_system_state_deinit();
- EXPECT_EQ(4, cras_observer_notify_output_volume_called);
-}
-
-TEST(SystemStateSuite, SetMinMaxVolume) {
- do_sys_init();
- cras_system_set_volume_limits(-10000, -600);
- EXPECT_EQ(-10000, cras_system_get_min_volume());
- EXPECT_EQ(-600, cras_system_get_max_volume());
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, SetUserMute) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_get_mute());
-
- cras_system_set_user_mute(0);
- EXPECT_EQ(0, cras_system_get_mute());
- EXPECT_EQ(0, cras_observer_notify_output_mute_called);
-
- cras_system_set_user_mute(1);
- EXPECT_EQ(1, cras_system_get_mute());
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- cras_system_set_user_mute(22);
- EXPECT_EQ(1, cras_system_get_mute());
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, SetMute) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_get_mute());
-
- cras_system_set_mute(0);
- EXPECT_EQ(0, cras_system_get_mute());
- EXPECT_EQ(0, cras_observer_notify_output_mute_called);
-
- cras_system_set_mute(1);
- EXPECT_EQ(1, cras_system_get_mute());
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- cras_system_set_mute(22);
- EXPECT_EQ(1, cras_system_get_mute());
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, SetSystemMuteThenSwitchUserMute) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_get_mute());
-
- // Set system mute.
- cras_system_set_mute(1);
-
- // Switching user mute will not notify observer.
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
- cras_system_set_user_mute(1);
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
- cras_system_set_user_mute(0);
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- // Unset system mute.
- cras_system_set_mute(0);
- EXPECT_EQ(2, cras_observer_notify_output_mute_called);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, SetUserMuteThenSwitchSystemMute) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_get_mute());
-
- // Set user mute.
- cras_system_set_user_mute(1);
-
- // Switching system mute will not notify observer.
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
- cras_system_set_mute(1);
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
- cras_system_set_mute(0);
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- // Unset user mute.
- cras_system_set_user_mute(0);
- EXPECT_EQ(2, cras_observer_notify_output_mute_called);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, CaptureMuteChangedCallbackMultiple) {
- do_sys_init();
- ResetStubData();
-
- cras_system_set_capture_mute(1);
- EXPECT_EQ(1, cras_system_get_capture_mute());
- EXPECT_EQ(1, cras_observer_notify_capture_mute_called);
- cras_system_set_capture_mute(0);
- EXPECT_EQ(0, cras_system_get_capture_mute());
- EXPECT_EQ(2, cras_observer_notify_capture_mute_called);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, MuteLocked) {
- do_sys_init();
- ResetStubData();
-
- cras_system_set_mute(1);
- EXPECT_EQ(1, cras_system_get_mute());
- EXPECT_EQ(0, cras_system_get_mute_locked());
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- cras_system_set_mute_locked(1);
- cras_system_set_mute(0);
- EXPECT_EQ(1, cras_system_get_mute());
- EXPECT_EQ(1, cras_system_get_mute_locked());
- EXPECT_EQ(1, cras_observer_notify_output_mute_called);
-
- cras_system_set_capture_mute(1);
- EXPECT_EQ(1, cras_system_get_capture_mute());
- EXPECT_EQ(0, cras_system_get_capture_mute_locked());
- EXPECT_EQ(1, cras_observer_notify_capture_mute_called);
-
- cras_system_set_capture_mute_locked(1);
- cras_system_set_capture_mute(0);
- EXPECT_EQ(1, cras_system_get_capture_mute());
- EXPECT_EQ(1, cras_system_get_capture_mute_locked());
- cras_system_state_deinit();
- EXPECT_EQ(2, cras_observer_notify_capture_mute_called);
-}
-
-TEST(SystemStateSuite, Suspend) {
- do_sys_init();
- ResetStubData();
-
- cras_system_set_suspended(1);
- EXPECT_EQ(1, cras_observer_notify_suspend_changed_called);
- EXPECT_EQ(1, cras_alert_process_all_pending_alerts_called);
- EXPECT_EQ(1, cras_system_get_suspended());
-
- cras_system_set_suspended(0);
- EXPECT_EQ(2, cras_observer_notify_suspend_changed_called);
- EXPECT_EQ(0, cras_system_get_suspended());
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, AddCardFailCreate) {
- ResetStubData();
- kFakeAlsaCard = NULL;
- cras_alsa_card_info info;
-
- info.card_type = ALSA_CARD_TYPE_INTERNAL;
- info.card_index = 0;
- do_sys_init();
- EXPECT_EQ(-ENOMEM, cras_system_add_alsa_card(&info));
- EXPECT_EQ(1, cras_alsa_card_create_called);
- EXPECT_EQ(cras_alsa_card_config_dir, device_config_dir);
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, AddCard) {
- ResetStubData();
- cras_alsa_card_info info;
-
- info.card_type = ALSA_CARD_TYPE_INTERNAL;
- info.card_index = 0;
- do_sys_init();
- EXPECT_EQ(0, cras_system_add_alsa_card(&info));
- EXPECT_EQ(1, cras_alsa_card_create_called);
- EXPECT_EQ(cras_alsa_card_config_dir, device_config_dir);
- // Adding the same card again should fail.
- ResetStubData();
- EXPECT_NE(0, cras_system_add_alsa_card(&info));
- EXPECT_EQ(0, cras_alsa_card_create_called);
- // Removing card should destroy it.
- cras_system_remove_alsa_card(0);
- EXPECT_EQ(1, cras_alsa_card_destroy_called);
- cras_system_state_deinit();
-}
-
-TEST(SystemSettingsRegisterSelectDescriptor, AddSelectFd) {
- void* stub_data = reinterpret_cast<void*>(44);
- void* select_data = reinterpret_cast<void*>(33);
- int rc;
-
- ResetStubData();
- do_sys_init();
- rc = cras_system_add_select_fd(7, callback_stub, stub_data, POLLIN);
- EXPECT_NE(0, rc);
- EXPECT_EQ(0, add_stub_called);
- EXPECT_EQ(0, rm_stub_called);
- rc = cras_system_set_select_handler(add_stub, rm_stub, select_data);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, add_stub_called);
- EXPECT_EQ(0, rm_stub_called);
- rc = cras_system_set_select_handler(add_stub, rm_stub, select_data);
- EXPECT_EQ(-EEXIST, rc);
- EXPECT_EQ(0, add_stub_called);
- EXPECT_EQ(0, rm_stub_called);
- rc = cras_system_add_select_fd(7, callback_stub, stub_data, POLLIN);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, add_stub_called);
- EXPECT_EQ(select_data, select_data_value);
- cras_system_rm_select_fd(7);
- EXPECT_EQ(1, rm_stub_called);
- EXPECT_EQ(0, callback_stub_called);
- EXPECT_EQ(select_data, select_data_value);
- cras_system_state_deinit();
-}
-
-TEST(SystemSettingsAddTask, AddTask) {
- void* stub_data = reinterpret_cast<void*>(44);
- void* task_data = reinterpret_cast<void*>(33);
- int rc;
-
- do_sys_init();
- rc = cras_system_add_task(task_stub, stub_data);
- EXPECT_NE(0, rc);
- EXPECT_EQ(0, add_task_stub_called);
- rc = cras_system_set_add_task_handler(add_task_stub, task_data);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(0, add_task_stub_called);
- rc = cras_system_add_task(task_stub, stub_data);
- EXPECT_EQ(0, rc);
- EXPECT_EQ(1, add_task_stub_called);
- EXPECT_EQ(task_data, task_data_value);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemSettingsStreamCount, StreamCount) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_state_get_active_streams());
- cras_system_state_stream_added(CRAS_STREAM_OUTPUT, CRAS_CLIENT_TYPE_CHROME);
- EXPECT_EQ(1, cras_system_state_get_active_streams());
- struct cras_timespec ts1;
- cras_system_state_get_last_stream_active_time(&ts1);
- cras_system_state_stream_removed(CRAS_STREAM_OUTPUT, CRAS_CLIENT_TYPE_CHROME);
- EXPECT_EQ(0, cras_system_state_get_active_streams());
- struct cras_timespec ts2;
- cras_system_state_get_last_stream_active_time(&ts2);
- EXPECT_NE(0, memcmp(&ts1, &ts2, sizeof(ts1)));
- cras_system_state_deinit();
-}
-
-TEST(SystemSettingsStreamCount, StreamCountByDirection) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_state_get_active_streams());
- cras_system_state_stream_added(CRAS_STREAM_OUTPUT, CRAS_CLIENT_TYPE_CHROME);
- cras_system_state_stream_added(CRAS_STREAM_INPUT, CRAS_CLIENT_TYPE_CHROME);
- cras_system_state_stream_added(CRAS_STREAM_POST_MIX_PRE_DSP,
- CRAS_CLIENT_TYPE_CHROME);
- EXPECT_EQ(1, cras_observer_notify_input_streams_with_permission_called);
- EXPECT_EQ(
- 1, cras_system_state_get_active_streams_by_direction(CRAS_STREAM_OUTPUT));
- EXPECT_EQ(
- 1, cras_system_state_get_active_streams_by_direction(CRAS_STREAM_INPUT));
- EXPECT_EQ(1, cras_system_state_get_active_streams_by_direction(
- CRAS_STREAM_POST_MIX_PRE_DSP));
- EXPECT_EQ(3, cras_system_state_get_active_streams());
- EXPECT_EQ(3, cras_observer_notify_num_active_streams_called);
- cras_system_state_stream_removed(CRAS_STREAM_OUTPUT, CRAS_CLIENT_TYPE_CHROME);
- cras_system_state_stream_removed(CRAS_STREAM_INPUT, CRAS_CLIENT_TYPE_CHROME);
- cras_system_state_stream_removed(CRAS_STREAM_POST_MIX_PRE_DSP,
- CRAS_CLIENT_TYPE_CHROME);
- EXPECT_EQ(2, cras_observer_notify_input_streams_with_permission_called);
- EXPECT_EQ(
- 0, cras_system_state_get_active_streams_by_direction(CRAS_STREAM_OUTPUT));
- EXPECT_EQ(
- 0, cras_system_state_get_active_streams_by_direction(CRAS_STREAM_INPUT));
- EXPECT_EQ(0, cras_system_state_get_active_streams_by_direction(
- CRAS_STREAM_POST_MIX_PRE_DSP));
- EXPECT_EQ(0, cras_system_state_get_active_streams());
- EXPECT_EQ(6, cras_observer_notify_num_active_streams_called);
-
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, IgnoreUCMSuffix) {
- fake_board_config.ucm_ignore_suffix = strdup("TEST1,TEST2,TEST3");
- do_sys_init();
-
- EXPECT_EQ(1, cras_system_check_ignore_ucm_suffix("TEST1"));
- EXPECT_EQ(1, cras_system_check_ignore_ucm_suffix("TEST2"));
- EXPECT_EQ(1, cras_system_check_ignore_ucm_suffix("TEST3"));
- EXPECT_EQ(0, cras_system_check_ignore_ucm_suffix("TEST4"));
- cras_system_state_deinit();
-}
-
-TEST(SystemStateSuite, SetNoiseCancellationEnabled) {
- ResetStubData();
- do_sys_init();
-
- EXPECT_EQ(0, cras_system_get_noise_cancellation_enabled());
-
- cras_system_set_noise_cancellation_enabled(0);
- EXPECT_EQ(0, cras_system_get_noise_cancellation_enabled());
- EXPECT_EQ(0, cras_iodev_list_reset_for_noise_cancellation_called);
-
- cras_system_set_noise_cancellation_enabled(1);
- EXPECT_EQ(1, cras_system_get_noise_cancellation_enabled());
- EXPECT_EQ(1, cras_iodev_list_reset_for_noise_cancellation_called);
-
- cras_system_set_noise_cancellation_enabled(1);
- EXPECT_EQ(1, cras_system_get_noise_cancellation_enabled());
- // cras_iodev_list_reset_for_noise_cancellation shouldn't be called if state
- // is already enabled/disabled.
- EXPECT_EQ(1, cras_iodev_list_reset_for_noise_cancellation_called);
-
- cras_system_set_noise_cancellation_enabled(0);
- EXPECT_EQ(0, cras_system_get_noise_cancellation_enabled());
- EXPECT_EQ(2, cras_iodev_list_reset_for_noise_cancellation_called);
-
- cras_system_state_deinit();
-}
-
-extern "C" {
-
-struct cras_alsa_card* cras_alsa_card_create(
- struct cras_alsa_card_info* info,
- const char* device_config_dir,
- struct cras_device_blocklist* blocklist) {
- cras_alsa_card_create_called++;
- cras_alsa_card_config_dir = device_config_dir;
- return kFakeAlsaCard;
-}
-
-void cras_alsa_card_destroy(struct cras_alsa_card* alsa_card) {
- cras_alsa_card_destroy_called++;
-}
-
-size_t cras_alsa_card_get_index(const struct cras_alsa_card* alsa_card) {
- return 0;
-}
-
-struct cras_device_blocklist* cras_device_blocklist_create(
- const char* config_path) {
- return NULL;
-}
-
-void cras_device_blocklist_destroy(struct cras_device_blocklist* blocklist) {}
-
-struct cras_alert* cras_alert_create(cras_alert_prepare prepare,
- unsigned int flags) {
- return NULL;
-}
-
-void cras_alert_destroy(struct cras_alert* alert) {}
-
-int cras_alert_add_callback(struct cras_alert* alert,
- cras_alert_cb cb,
- void* arg) {
- add_callback_called++;
- add_callback_cb = cb;
- add_callback_arg = arg;
- return 0;
-}
-
-int cras_alert_rm_callback(struct cras_alert* alert,
- cras_alert_cb cb,
- void* arg) {
- rm_callback_called++;
- rm_callback_cb = cb;
- rm_callback_arg = arg;
- return 0;
-}
-
-void cras_alert_pending(struct cras_alert* alert) {
- alert_pending_called++;
-}
-
-cras_tm* cras_tm_init() {
- return static_cast<cras_tm*>(malloc(sizeof(unsigned int)));
-}
-
-void cras_tm_deinit(cras_tm* tm) {
- free(tm);
-}
-
-void cras_observer_notify_output_volume(int32_t volume) {
- cras_observer_notify_output_volume_called++;
-}
-
-void cras_observer_notify_output_mute(int muted,
- int user_muted,
- int mute_locked) {
- cras_observer_notify_output_mute_called++;
-}
-
-void cras_observer_notify_capture_mute(int muted, int mute_locked) {
- cras_observer_notify_capture_mute_called++;
-}
-
-void cras_observer_notify_suspend_changed(int suspended) {
- cras_observer_notify_suspend_changed_called++;
-}
-
-void cras_observer_notify_num_active_streams(enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams) {
- cras_observer_notify_num_active_streams_called++;
-}
-
-void cras_observer_notify_input_streams_with_permission(
- uint32_t num_input_streams[CRAS_NUM_CLIENT_TYPE]) {
- cras_observer_notify_input_streams_with_permission_called++;
-}
-
-void cras_board_config_get(const char* config_path,
- struct cras_board_config* board_config) {
- *board_config = fake_board_config;
-}
-
-void cras_alert_process_all_pending_alerts() {
- cras_alert_process_all_pending_alerts_called++;
-}
-
-void cras_iodev_list_reset_for_noise_cancellation() {
- cras_iodev_list_reset_for_noise_cancellation_called++;
-}
-
-} // extern "C"
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/timing_unittest.cc b/cras/src/tests/timing_unittest.cc
deleted file mode 100644
index 964f30c3..00000000
--- a/cras/src/tests/timing_unittest.cc
+++ /dev/null
@@ -1,1246 +0,0 @@
-// Copyright 2017 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <syslog.h>
-#include <time.h>
-
-#include <memory>
-
-extern "C" {
-#include "cras_iodev.h" // stubbed
-#include "cras_rstream.h" // stubbed
-#include "cras_shm.h"
-#include "cras_types.h"
-#include "dev_io.h" // tested
-#include "dev_stream.h" // tested
-#include "utlist.h"
-
-struct audio_thread_event_log* atlog;
-}
-
-#include "dev_io_stubs.h"
-#include "iodev_stub.h"
-#include "metrics_stub.h"
-#include "rstream_stub.h"
-
-#define FAKE_POLL_FD 33
-
-namespace {
-
-class TimingSuite : public testing::Test {
- protected:
- virtual void SetUp() {
- atlog = static_cast<audio_thread_event_log*>(calloc(1, sizeof(*atlog)));
- iodev_stub_reset();
- rstream_stub_reset();
- }
-
- virtual void TearDown() { free(atlog); }
-
- timespec SingleInputDevNextWake(
- size_t dev_cb_threshold,
- size_t dev_level,
- const timespec* level_timestamp,
- cras_audio_format* dev_format,
- const std::vector<StreamPtr>& streams,
- CRAS_NODE_TYPE active_node_type = CRAS_NODE_TYPE_MIC) {
- struct open_dev* dev_list_ = NULL;
-
- DevicePtr dev = create_device(CRAS_STREAM_INPUT, dev_cb_threshold,
- dev_format, active_node_type);
- dev->dev->input_streaming = true;
- DL_APPEND(dev_list_, dev->odev.get());
-
- for (auto const& stream : streams) {
- add_stream_to_dev(dev->dev, stream);
- }
-
- // Set response for frames_queued.
- iodev_stub_frames_queued(dev->dev.get(), dev_level, *level_timestamp);
-
- dev_io_send_captured_samples(dev_list_);
-
- struct timespec dev_time;
- dev_time.tv_sec = level_timestamp->tv_sec + 500; // Far in the future.
- dev_io_next_input_wake(&dev_list_, &dev_time);
- return dev_time;
- }
-
- timespec SingleOutputDevNextWake(
- size_t dev_cb_threshold,
- size_t dev_level,
- const timespec* level_timestamp,
- cras_audio_format* dev_format,
- const std::vector<StreamPtr>& streams,
- const timespec* dev_wake_ts,
- CRAS_NODE_TYPE active_node_type = CRAS_NODE_TYPE_HEADPHONE) {
- struct open_dev* dev_list_ = NULL;
-
- DevicePtr dev = create_device(CRAS_STREAM_OUTPUT, dev_cb_threshold,
- dev_format, active_node_type);
- DL_APPEND(dev_list_, dev->odev.get());
-
- for (auto const& stream : streams) {
- add_stream_to_dev(dev->dev, stream);
- }
-
- dev->odev->wake_ts = *dev_wake_ts;
-
- // Set response for frames_queued.
- iodev_stub_frames_queued(dev->dev.get(), dev_level, *level_timestamp);
-
- struct timespec dev_time;
- dev_time.tv_sec = level_timestamp->tv_sec + 500; // Far in the future.
- dev_io_next_output_wake(&dev_list_, &dev_time);
- return dev_time;
- }
-};
-
-extern "C" {
-// From librt. Fix now at this time.
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- tp->tv_sec = 12345;
- tp->tv_nsec = 987654321;
- return 0;
-}
-};
-
-// Add a new input stream, make sure the initial next_cb_ts is 0.
-TEST_F(TimingSuite, NewInputStreamInit) {
- struct open_dev* odev_list_ = NULL;
- struct open_dev* idev_list_ = NULL;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- DevicePtr dev =
- create_device(CRAS_STREAM_INPUT, 1024, &format, CRAS_NODE_TYPE_MIC);
- DL_APPEND(idev_list_, dev->odev.get());
- struct cras_iodev* iodev = dev->odev->dev;
-
- ShmPtr shm = create_shm(480);
- RstreamPtr rstream =
- create_rstream(1, CRAS_STREAM_INPUT, 480, &format, shm.get());
-
- dev_io_append_stream(&odev_list_, &idev_list_, rstream.get(), &iodev, 1);
-
- EXPECT_EQ(0, rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(0, rstream->next_cb_ts.tv_nsec);
-
- dev_stream_destroy(iodev->streams);
-}
-
-// There is the pseudo code about wake up time for an input device.
-//
-// function set_input_dev_wake_ts(dev):
-// wake_ts = now + 20s #rule_1
-//
-// cap_limit = MIN(dev_stream_capture_avail(stream)) for stream on dev
-//
-// for stream in dev:
-// wake_ts = MIN(get_input_wake_time(stream, cap_limit), wake_ts)
-// for stream on dev #rule_2
-// if cap_limit:
-// wake_ts = MIN(get_input_dev_max_wake_ts(dev), wake_ts) #rule_3
-//
-// device.wake_ts = wake_ts
-//
-// function get_input_wake_time(stream, cap_limit):
-// needed_frames_from_device = dev_stream_capture_avail(stream)
-//
-// if needed_frames_from_device > cap_limit: #rule_4
-// return None
-//
-// if stream is USE_DEV_TIMING and stream is pending reply: #rule_5
-// return None
-//
-// time_for_sample = The time when device gets enough samples #rule_6
-//
-// wake_time_out = MAX(stream.next_cb_ts, time_for_sample) #rule_7
-//
-// if stream is USE_DEV_TIMING:
-// wake_time_out = time_for_sample #rule_8
-//
-// return wake_time_out
-//
-// function get_input_dev_max_wake_ts(dev):
-// return MAX(5ms, The time when hw_level = buffer_size / 2) #rule_9
-//
-//
-// dev_stream_capture_avail: The number of frames free to be written to in a
-// capture stream.
-//
-// The following unittests will check these logics.
-
-// Test rule_1.
-// The device wake up time should be 20s from now.
-TEST_F(TimingSuite, InputWakeTimeNoStreamWithBigBufferDevice) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- std::vector<StreamPtr> streams;
- timespec dev_time =
- SingleInputDevNextWake(4800000, 0, &start, &format, streams);
-
- const timespec add_millis = {20, 0};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_2, rule_4(Stream 1), rule_7(Stream 2)
-// Stream 1: next_cb_ts = now, cb_threshold = 480, dev_offset = 0
-// Stream 2: next_cb_ts = now + 5s, cb_threshold = 480, dev_offset = 200
-// Stream 1 need 480 frames and Stream 2 need 240 frames. So 240 will be the
-// cap_limit and Stream 1 will be ignored. The next wake up time should be
-// the next_cb_ts of stream2.
-TEST_F(TimingSuite, InputWakeTimeTwoStreamsWithFramesInside) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
- stream1->rstream->next_cb_ts = start;
-
- StreamPtr stream2 = create_stream(1, 2, CRAS_STREAM_INPUT, 480, &format);
- stream2->rstream->next_cb_ts = start;
- stream2->rstream->next_cb_ts.tv_sec += 5;
- rstream_stub_dev_offset(stream2->rstream.get(), 1, 200);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
- timespec dev_time =
- SingleInputDevNextWake(480000, 0, &start, &format, streams);
-
- EXPECT_EQ(start.tv_sec + 5, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_2, rule_7
-// Stream 1: next_cb_ts = now + 2s, cb_threshold = 480, dev_offset = 0
-// Stream 2: next_cb_ts = now + 5s, cb_threshold = 480, dev_offset = 0
-// The audio thread will choose the earliest next_cb_ts because the they have
-// the same value of needed_frames_from_device. The next wake up time should
-// be the next_cb_ts of stream1.
-TEST_F(TimingSuite, InputWakeTimeTwoEmptyStreams) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
- stream1->rstream->next_cb_ts = start;
- stream1->rstream->next_cb_ts.tv_sec += 2;
-
- StreamPtr stream2 = create_stream(1, 2, CRAS_STREAM_INPUT, 480, &format);
- stream2->rstream->next_cb_ts = start;
- stream2->rstream->next_cb_ts.tv_sec += 5;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
- timespec dev_time =
- SingleInputDevNextWake(480000, 0, &start, &format, streams);
-
- EXPECT_EQ(start.tv_sec + 2, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_3.
-// If cap_limit is zero from stream, input_dev_max_wake_ts should not
-// be taken into account.
-TEST_F(TimingSuite, InputWakeTimeOneFullStreamWithDeviceWakeUp) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start, stream_wake;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // Set the next stream wake to be 10ms from now.
- const timespec ten_millis = {0, 10 * 1000 * 1000};
- stream_wake = start;
- add_timespecs(&stream_wake, &ten_millis);
- stream->rstream->next_cb_ts = stream_wake;
-
- // Add fake data so the stream has no room for more data.
- AddFakeDataToStream(stream.get(), 480);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec wake_time = SingleInputDevNextWake(240, 0, &start, &format, streams);
-
- // Input device would wake at 5ms from now, but since stream cap_limit == 0
- // the final wake_time is determined by stream.
- EXPECT_EQ(stream_wake.tv_sec, wake_time.tv_sec);
- EXPECT_EQ(stream_wake.tv_nsec, wake_time.tv_nsec);
-}
-
-// Test rule_3 and rule_9.
-// One empty stream with small device buffer. It should wake up when there are
-// buffer_size / 2 frames in device buffer.
-TEST_F(TimingSuite, InputWakeTimeOneStreamWithDeviceWakeUp) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // The next callback of the new stream is 0.
- stream->rstream->next_cb_ts.tv_sec = 0;
- stream->rstream->next_cb_ts.tv_nsec = 0;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(240, 0, &start, &format, streams);
- // The device wake up time should be 5ms from now. At that time there are
- // 240 frames in the device.
- const timespec add_millis = {0, 5 * 1000 * 1000};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_5.
-// The stream with USE_DEV_TIMING flag will be ignore if it is pending reply.
-TEST_F(TimingSuite, InputWakeTimeOneStreamUsingDevTimingWithPendingReply) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // The next callback should be ignored.
- stream->rstream->next_cb_ts = start;
- stream->rstream->next_cb_ts.tv_sec += 10;
- stream->rstream->flags = USE_DEV_TIMING;
- rstream_stub_pending_reply(stream->rstream.get(), 1);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(4800, 0, &start, &format, streams);
-
- // The device wake up time should be 100ms from now. At that time the hw_level
- // is buffer_size / 2.
- const timespec add_millis = {0, 100 * 1000 * 1000};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_6.
-// Add a new stream, the wake up time is the time when it has enough data to
-// post.
-TEST_F(TimingSuite, InputWakeTimeOneStreamWithEmptyDevice) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // The next callback of the new stream is 0.
- stream->rstream->next_cb_ts.tv_sec = 0;
- stream->rstream->next_cb_ts.tv_nsec = 0;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(600, 0, &start, &format, streams);
-
- // The device wake up time should be 10ms from now. At that time the
- // stream will have 480 samples to post.
- const timespec ten_millis = {0, 10 * 1000 * 1000};
- add_timespecs(&start, &ten_millis);
- EXPECT_EQ(0, streams[0]->rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(0, streams[0]->rstream->next_cb_ts.tv_nsec);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_6.
-// Add a new stream with enough frames in device, check the wake up time is
-// right now.
-TEST_F(TimingSuite, InputWakeTimeOneStreamWithFullDevice) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // The next callback of the new stream is 0.
- stream->rstream->next_cb_ts.tv_sec = 0;
- stream->rstream->next_cb_ts.tv_nsec = 0;
-
- // If there are enough frames in the device, we should wake up immediately.
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time =
- SingleInputDevNextWake(480, 480, &start, &format, streams);
- EXPECT_EQ(0, streams[0]->rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(0, streams[0]->rstream->next_cb_ts.tv_nsec);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_8.
-// The stream with USE_DEV_TIMING flag should wake up when it has enough frames
-// to post.
-TEST_F(TimingSuite, InputWakeTimeOneStreamUsingDevTiming) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // The next callback should be ignored.
- stream->rstream->next_cb_ts = start;
- stream->rstream->next_cb_ts.tv_sec += 10;
- stream->rstream->flags = USE_DEV_TIMING;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(600, 0, &start, &format, streams);
-
- // The device wake up time should be 10ms from now. At that time the
- // stream will have 480 samples to post.
- const timespec add_millis = {0, 10 * 1000 * 1000};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_9.
-// The device wake up time should be 10ms from now. At that time the hw_level
-// is buffer_size / 2.
-TEST_F(TimingSuite, InputWakeTimeNoStreamSmallBufferDevice) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- std::vector<StreamPtr> streams;
- timespec dev_time = SingleInputDevNextWake(480, 0, &start, &format, streams);
-
- const timespec add_millis = {0, 10 * 1000 * 1000};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_9.
-// There are more than buffer_size / 2 frames in the device. The device needs
-// to sleep at least 5ms.
-TEST_F(TimingSuite, InputWakeTimeOneStreamWithEnoughFramesInDevice) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // Make next_cb_ts far from now.
- stream->rstream->next_cb_ts = start;
- stream->rstream->next_cb_ts.tv_sec += 10;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time =
- SingleInputDevNextWake(480, 480, &start, &format, streams);
-
- const timespec add_millis = {0, 5 * 1000 * 1000};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// One device, one stream, write a callback of data and check the sleep time is
-// one more wakeup interval.
-TEST_F(TimingSuite, WaitAfterFill) {
- const size_t cb_threshold = 480;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream =
- create_stream(1, 1, CRAS_STREAM_INPUT, cb_threshold, &format);
- // rstream's next callback is now and there is enough data to fill.
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream.get(), 480);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time =
- SingleInputDevNextWake(cb_threshold, 0, &start, &format, streams);
-
- // The next callback should be scheduled 10ms in the future.
- // And the next wake up should reflect the only attached stream.
- const timespec ten_millis = {0, 10 * 1000 * 1000};
- add_timespecs(&start, &ten_millis);
- EXPECT_EQ(start.tv_sec, streams[0]->rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(start.tv_nsec, streams[0]->rstream->next_cb_ts.tv_nsec);
- EXPECT_EQ(dev_time.tv_sec, streams[0]->rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(dev_time.tv_nsec, streams[0]->rstream->next_cb_ts.tv_nsec);
-}
-
-// One device with one stream which has block_size larger than the device buffer
-// level. If the device buffer level = 0, the input device wake time should be
-// set to (buffer_size / 2) / device_rate secs.
-TEST_F(TimingSuite, LargeCallbackStreamWithEmptyBuffer) {
- const size_t cb_threshold = 3000;
- const size_t dev_cb_threshold = 1200;
- const size_t dev_level = 0;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream =
- create_stream(1, 1, CRAS_STREAM_INPUT, cb_threshold, &format);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream->rstream->next_cb_ts = start;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(dev_cb_threshold, dev_level,
- &start, &format, streams);
-
- struct timespec delta;
- subtract_timespecs(&dev_time, &start, &delta);
- // The next dev wake ts should be 25ms since the buffer level is empty and
- // 1200 / 48000 = 0.025.
- EXPECT_EQ(delta.tv_sec, 0);
- EXPECT_LT(delta.tv_nsec, 25000000 + 5000 * 1000);
- EXPECT_GT(delta.tv_nsec, 25000000 - 5000 * 1000);
-}
-
-// One device with one stream which has block_size larger than the device buffer
-// level. If the device buffer level = buffer_size / 2, the input device wake
-// time should be set to max(0, 5ms) = 5ms to prevent busy loop occurs.
-TEST_F(TimingSuite, LargeCallbackStreamWithHalfFullBuffer) {
- const size_t cb_threshold = 3000;
- const size_t dev_cb_threshold = 1200;
- const size_t dev_level = 1200;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream =
- create_stream(1, 1, CRAS_STREAM_INPUT, cb_threshold, &format);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream->rstream->next_cb_ts = start;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(dev_cb_threshold, dev_level,
- &start, &format, streams);
-
- struct timespec delta;
- subtract_timespecs(&dev_time, &start, &delta);
- // The next dev wake ts should be 5ms since the buffer level is half full.
- EXPECT_EQ(delta.tv_sec, 0);
- EXPECT_LT(delta.tv_nsec, 5000000 + 5000 * 1000);
- EXPECT_GT(delta.tv_nsec, 5000000 - 5000 * 1000);
-}
-
-// One device(48k), one stream(44.1k), write a callback of data and check that
-// the sleep time is correct when doing SRC.
-TEST_F(TimingSuite, WaitAfterFillSRC) {
- cras_audio_format dev_format;
- fill_audio_format(&dev_format, 48000);
- cras_audio_format stream_format;
- fill_audio_format(&stream_format, 44100);
-
- StreamPtr stream =
- create_stream(1, 1, CRAS_STREAM_INPUT, 441, &stream_format);
- // rstream's next callback is now and there is enough data to fill.
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream.get(), 441);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time =
- SingleInputDevNextWake(480, 0, &start, &dev_format, streams);
-
- // The next callback should be scheduled 10ms in the future.
- struct timespec delta;
- subtract_timespecs(&dev_time, &start, &delta);
- EXPECT_LT(9900 * 1000, delta.tv_nsec);
- EXPECT_GT(10100 * 1000, delta.tv_nsec);
-}
-
-// One device, two streams. One stream is ready the other still needs data.
-// Checks that the sleep interval is based on the time the device will take to
-// supply the needed samples for stream2.
-TEST_F(TimingSuite, WaitTwoStreamsSameFormat) {
- const size_t cb_threshold = 480;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- // stream1's next callback is now and there is enough data to fill.
- StreamPtr stream1 =
- create_stream(1, 1, CRAS_STREAM_INPUT, cb_threshold, &format);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream1->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream1.get(), cb_threshold);
-
- // stream2 is only half full.
- StreamPtr stream2 =
- create_stream(1, 1, CRAS_STREAM_INPUT, cb_threshold, &format);
- stream2->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream2.get(), 240);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
- timespec dev_time =
- SingleInputDevNextWake(cb_threshold, 0, &start, &format, streams);
-
- // Should wait for approximately 5 milliseconds for 240 samples at 48k.
- struct timespec delta2;
- subtract_timespecs(&dev_time, &start, &delta2);
- EXPECT_LT(4900 * 1000, delta2.tv_nsec);
- EXPECT_GT(5100 * 1000, delta2.tv_nsec);
-}
-
-// One device(44.1), two streams(44.1, 48). One stream is ready the other still
-// needs data. Checks that the sleep interval is based on the time the device
-// will take to supply the needed samples for stream2, stream2 is sample rate
-// converted from the 44.1k device to the 48k stream.
-TEST_F(TimingSuite, WaitTwoStreamsDifferentRates) {
- cras_audio_format s1_format, s2_format;
- fill_audio_format(&s1_format, 44100);
- fill_audio_format(&s2_format, 48000);
-
- // stream1's next callback is now and there is enough data to fill.
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_INPUT, 441, &s1_format);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream1->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream1.get(), 441);
- // stream2's next callback is now but there is only half a callback of data.
- StreamPtr stream2 = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &s2_format);
- stream2->rstream->next_cb_ts = start;
- AddFakeDataToStream(stream2.get(), 240);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
- timespec dev_time =
- SingleInputDevNextWake(441, 0, &start, &s1_format, streams);
-
- // Should wait for approximately 5 milliseconds for 240 48k samples from the
- // 44.1k device.
- struct timespec delta2;
- subtract_timespecs(&dev_time, &start, &delta2);
- EXPECT_LT(4900 * 1000, delta2.tv_nsec);
- EXPECT_GT(5100 * 1000, delta2.tv_nsec);
-}
-
-// One device, two streams. Both streams get a full callback of data and the
-// device has enough samples for the next callback already. Checks that the
-// shorter of the two streams times is used for the next sleep interval.
-TEST_F(TimingSuite, WaitTwoStreamsDifferentWakeupTimes) {
- cras_audio_format s1_format, s2_format;
- fill_audio_format(&s1_format, 44100);
- fill_audio_format(&s2_format, 48000);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- // stream1's next callback is in 3ms.
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_INPUT, 441, &s1_format);
- stream1->rstream->next_cb_ts = start;
- const timespec three_millis = {0, 3 * 1000 * 1000};
- add_timespecs(&stream1->rstream->next_cb_ts, &three_millis);
- AddFakeDataToStream(stream1.get(), 441);
- // stream2 is also ready next cb in 5ms..
- StreamPtr stream2 = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &s2_format);
- stream2->rstream->next_cb_ts = start;
- const timespec five_millis = {0, 5 * 1000 * 1000};
- add_timespecs(&stream2->rstream->next_cb_ts, &five_millis);
- AddFakeDataToStream(stream1.get(), 480);
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
- timespec dev_time =
- SingleInputDevNextWake(441, 441, &start, &s1_format, streams);
-
- // Should wait for approximately 3 milliseconds for stream 1 first.
- struct timespec delta2;
- subtract_timespecs(&dev_time, &start, &delta2);
- EXPECT_LT(2900 * 1000, delta2.tv_nsec);
- EXPECT_GT(3100 * 1000, delta2.tv_nsec);
-}
-
-// One hotword stream attaches to hotword device. Input data has copied from
-// device to stream but total number is less than cb_threshold. Hotword stream
-// should be scheduled wake base on the samples needed to fill full shm.
-TEST_F(TimingSuite, HotwordStreamUseDevTiming) {
- cras_audio_format fmt;
- fill_audio_format(&fmt, 48000);
-
- struct timespec start, delay;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 240, &fmt);
- stream->rstream->flags = HOTWORD_STREAM;
- stream->rstream->next_cb_ts = start;
- delay.tv_sec = 0;
- delay.tv_nsec = 3 * 1000 * 1000;
- add_timespecs(&stream->rstream->next_cb_ts, &delay);
-
- // Add fake data to stream and device so its slightly less than cb_threshold.
- // Expect to wait for samples to fill the full buffer (480 - 192) frames
- // instead of using the next_cb_ts.
- AddFakeDataToStream(stream.get(), 192);
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- timespec dev_time = SingleInputDevNextWake(4096, 0, &start, &fmt, streams);
- struct timespec delta;
- subtract_timespecs(&dev_time, &start, &delta);
- // 288 frames worth of time = 6 ms.
- EXPECT_EQ(6 * 1000 * 1000, delta.tv_nsec);
-}
-
-// One hotword stream attaches to hotword device. Input data burst to a number
-// larger than cb_threshold. Also, stream is pending client reply.
-// In this case stream fd is used to poll for next wake.
-// And the dev wake time is unchanged from the default 20 seconds limit.
-TEST_F(TimingSuite, HotwordStreamBulkDataIsPending) {
- int poll_fd = 0;
- cras_audio_format fmt;
- fill_audio_format(&fmt, 48000);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 240, &fmt);
- stream->rstream->flags = HOTWORD_STREAM;
- stream->rstream->next_cb_ts = start;
-
- AddFakeDataToStream(stream.get(), 480);
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- // Stream is pending the reply from client.
- rstream_stub_pending_reply(streams[0]->rstream.get(), 1);
-
- // There is more than 1 cb_threshold of data in device.
- timespec dev_time = SingleInputDevNextWake(4096, 7000, &start, &fmt, streams,
- CRAS_NODE_TYPE_HOTWORD);
-
- // Need to wait for stream fd in the next ppoll.
- poll_fd = dev_stream_poll_stream_fd(streams[0]->dstream.get());
- EXPECT_EQ(FAKE_POLL_FD, poll_fd);
-
- struct timespec delta;
- subtract_timespecs(&dev_time, &start, &delta);
- // Wake up time should be default 20 seconds because audio thread
- // depends on reply from client to wake it up.
- EXPECT_LT(19, delta.tv_sec);
- EXPECT_GT(21, delta.tv_sec);
-}
-
-// One hotword stream attaches to hotword device. Input data burst to a number
-// larger than cb_threshold. However, stream is not pending client reply.
-// This happens if there was no data during capture_to_stream.
-// In this case stream fd is NOT used to poll for next wake.
-// And the dev wake time is changed to a 0 instead of default 20 seconds.
-TEST_F(TimingSuite, HotwordStreamBulkDataIsNotPending) {
- int poll_fd = 0;
- cras_audio_format fmt;
- fill_audio_format(&fmt, 48000);
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_INPUT, 240, &fmt);
- stream->rstream->flags = HOTWORD_STREAM;
- stream->rstream->next_cb_ts = start;
-
- AddFakeDataToStream(stream.get(), 480);
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
- // Stream is not pending the reply from client.
- rstream_stub_pending_reply(streams[0]->rstream.get(), 0);
-
- // There is more than 1 cb_threshold of data in device.
- timespec dev_time = SingleInputDevNextWake(4096, 7000, &start, &fmt, streams);
-
- // Does not need to wait for stream fd in the next ppoll.
- poll_fd = dev_stream_poll_stream_fd(streams[0]->dstream.get());
- EXPECT_EQ(-1, poll_fd);
-
- struct timespec delta;
- subtract_timespecs(&dev_time, &start, &delta);
- // Wake up time should be very small because there is enough
- // data to be send to client.
- EXPECT_LT(delta.tv_sec, 0.1);
-}
-
-// When a new output stream is added, there are two rules to determine the
-// initial next_cb_ts.
-// 1. If there is a matched input stream, use the next_cb_ts and
-// sleep_interval_ts from that input stream as the initial values.
-// 2. If the device already has streams, the next_cb_ts will be the earliest
-// next callback time from these streams.
-// 3. If there are no other streams, the next_cb_ts will be set to the time
-// when the valid frames in device is lower than cb_threshold. (If it is
-// already lower than cb_threshold, set next_cb_ts to now.)
-
-// Test rule 1.
-// There is a matched input stream. The next_cb_ts of the newly added output
-// stream will use the next_cb_ts from the input stream.
-TEST_F(TimingSuite, NewOutputStreamInitExistMatchedStream) {
- struct open_dev* odev_list_ = NULL;
- struct open_dev* idev_list_ = NULL;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- DevicePtr out_dev = create_device(CRAS_STREAM_OUTPUT, 1024, &format,
- CRAS_NODE_TYPE_HEADPHONE);
- DL_APPEND(odev_list_, out_dev->odev.get());
- struct cras_iodev* out_iodev = out_dev->odev->dev;
-
- DevicePtr in_dev =
- create_device(CRAS_STREAM_INPUT, 1024, &format, CRAS_NODE_TYPE_MIC);
- DL_APPEND(idev_list_, in_dev->odev.get());
-
- StreamPtr in_stream = create_stream(1, 1, CRAS_STREAM_INPUT, 480, &format);
- add_stream_to_dev(in_dev->dev, in_stream);
- in_stream->rstream->next_cb_ts.tv_sec = 54321;
- in_stream->rstream->next_cb_ts.tv_nsec = 12345;
- in_stream->rstream->sleep_interval_ts.tv_sec = 321;
- in_stream->rstream->sleep_interval_ts.tv_nsec = 123;
-
- ShmPtr shm = create_shm(480);
- RstreamPtr rstream =
- create_rstream(1, CRAS_STREAM_OUTPUT, 480, &format, shm.get());
-
- dev_io_append_stream(&odev_list_, &idev_list_, rstream.get(), &out_iodev, 1);
-
- EXPECT_EQ(in_stream->rstream->next_cb_ts.tv_sec, rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(in_stream->rstream->next_cb_ts.tv_nsec,
- rstream->next_cb_ts.tv_nsec);
- EXPECT_EQ(in_stream->rstream->sleep_interval_ts.tv_sec,
- rstream->sleep_interval_ts.tv_sec);
- EXPECT_EQ(in_stream->rstream->sleep_interval_ts.tv_nsec,
- rstream->sleep_interval_ts.tv_nsec);
-
- dev_stream_destroy(out_iodev->streams);
-}
-
-// Test rule 2.
-// The device already has streams, the next_cb_ts will be the earliest
-// next_cb_ts from these streams.
-TEST_F(TimingSuite, NewOutputStreamInitStreamInDevice) {
- struct open_dev* odev_list_ = NULL;
- struct open_dev* idev_list_ = NULL;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- DevicePtr dev = create_device(CRAS_STREAM_OUTPUT, 1024, &format,
- CRAS_NODE_TYPE_HEADPHONE);
- DL_APPEND(odev_list_, dev->odev.get());
- struct cras_iodev* iodev = dev->odev->dev;
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- add_stream_to_dev(dev->dev, stream);
- stream->rstream->next_cb_ts.tv_sec = 54321;
- stream->rstream->next_cb_ts.tv_nsec = 12345;
-
- ShmPtr shm = create_shm(480);
- RstreamPtr rstream =
- create_rstream(1, CRAS_STREAM_OUTPUT, 480, &format, shm.get());
-
- dev_io_append_stream(&odev_list_, &idev_list_, rstream.get(), &iodev, 1);
-
- EXPECT_EQ(stream->rstream->next_cb_ts.tv_sec, rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(stream->rstream->next_cb_ts.tv_nsec, rstream->next_cb_ts.tv_nsec);
-
- dev_stream_destroy(iodev->streams->next);
-}
-
-// Test rule 3.
-// The there are no streams and no frames in device buffer. The next_cb_ts
-// will be set to now.
-TEST_F(TimingSuite, NewOutputStreamInitNoStreamNoFramesInDevice) {
- struct open_dev* odev_list_ = NULL;
- struct open_dev* idev_list_ = NULL;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- DevicePtr dev = create_device(CRAS_STREAM_OUTPUT, 1024, &format,
- CRAS_NODE_TYPE_HEADPHONE);
- DL_APPEND(odev_list_, dev->odev.get());
- struct cras_iodev* iodev = dev->odev->dev;
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- ShmPtr shm = create_shm(480);
- RstreamPtr rstream =
- create_rstream(1, CRAS_STREAM_OUTPUT, 480, &format, shm.get());
-
- dev_io_append_stream(&odev_list_, &idev_list_, rstream.get(), &iodev, 1);
-
- EXPECT_EQ(start.tv_sec, rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(start.tv_nsec, rstream->next_cb_ts.tv_nsec);
-
- dev_stream_destroy(iodev->streams);
-}
-
-// Test rule 2.
-// The there are no streams and some valid frames in device buffer. The
-// next_cb_ts will be set to the time that valid frames in device is lower
-// than cb_threshold.
-TEST_F(TimingSuite, NewOutputStreamInitNoStreamSomeFramesInDevice) {
- struct open_dev* odev_list_ = NULL;
- struct open_dev* idev_list_ = NULL;
-
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- DevicePtr dev = create_device(CRAS_STREAM_OUTPUT, 1024, &format,
- CRAS_NODE_TYPE_HEADPHONE);
- DL_APPEND(odev_list_, dev->odev.get());
- struct cras_iodev* iodev = dev->odev->dev;
-
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- iodev_stub_valid_frames(iodev, 960, start);
-
- ShmPtr shm = create_shm(480);
- RstreamPtr rstream =
- create_rstream(1, CRAS_STREAM_OUTPUT, 480, &format, shm.get());
-
- dev_io_append_stream(&odev_list_, &idev_list_, rstream.get(), &iodev, 1);
-
- // The next_cb_ts should be 10ms from now. At that time there are
- // only 480 valid frames in the device.
- const timespec add_millis = {0, 10 * 1000 * 1000};
- add_timespecs(&start, &add_millis);
- EXPECT_EQ(start.tv_sec, rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(start.tv_nsec, rstream->next_cb_ts.tv_nsec);
-
- dev_stream_destroy(iodev->streams);
-}
-
-// There is the pseudo code about wake up time for a output device.
-//
-// function dev_io_next_output_wake(dev):
-// wake_ts = get_next_stream_wake_from_list(dev.streams)
-// if cras_iodev_odev_should_wake(dev):
-// wake_ts = MIN(wake_ts, dev.wake_ts) # rule_1
-//
-// function get_next_stream_wake_from_list(streams):
-// for stream in streams:
-// if stream is draining: # rule_2
-// continue
-// if stream is pending reply: # rule_3
-// continue
-// if stream is USE_DEV_TIMING: # rule_4
-// continue
-// min_ts = MIN(min_ts, stream.next_cb_ts) # rule_5
-// return min_ts
-//
-// # This function is in iodev so we don't test its logic here.
-// function cras_iodev_odev_should_wake(dev):
-// if dev.is_free_running:
-// return False
-// if dev.state == NORMAL_RUN or dev.state == NO_STREAM_RUN:
-// return True
-// return False
-
-// Test rule_1.
-// The wake up time should be the earlier time amoung streams and devices.
-TEST_F(TimingSuite, OutputWakeTimeOneStreamWithEarlierStreamWakeTime) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- stream->rstream->next_cb_ts = start;
- stream->rstream->next_cb_ts.tv_sec += 1;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
-
- struct timespec dev_wake_ts = start;
- dev_wake_ts.tv_sec += 2;
-
- timespec dev_time =
- SingleOutputDevNextWake(48000, 0, &start, &format, streams, &dev_wake_ts);
-
- EXPECT_EQ(start.tv_sec + 1, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_1.
-// The wake up time should be the earlier time amoung streams and devices.
-TEST_F(TimingSuite, OutputWakeTimeOneStreamWithEarlierDeviceWakeTime) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- stream->rstream->next_cb_ts = start;
- stream->rstream->next_cb_ts.tv_sec += 2;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream));
-
- struct timespec dev_wake_ts = start;
- dev_wake_ts.tv_sec += 1;
-
- timespec dev_time =
- SingleOutputDevNextWake(48000, 0, &start, &format, streams, &dev_wake_ts);
-
- EXPECT_EQ(start.tv_sec + 1, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_2.
-// The stream 1 is draining so it will be ignored. The wake up time should be
-// the next_cb_ts of stream 2.
-TEST_F(TimingSuite, OutputWakeTimeTwoStreamsWithOneIsDraining) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- stream1->rstream->next_cb_ts = start;
- stream1->rstream->next_cb_ts.tv_sec += 2;
- stream1->rstream->is_draining = 1;
- stream1->rstream->queued_frames = 480;
-
- StreamPtr stream2 = create_stream(1, 2, CRAS_STREAM_OUTPUT, 480, &format);
- stream2->rstream->next_cb_ts = start;
- stream2->rstream->next_cb_ts.tv_sec += 5;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
-
- struct timespec dev_wake_ts = start;
- dev_wake_ts.tv_sec += 10;
-
- timespec dev_time =
- SingleOutputDevNextWake(48000, 0, &start, &format, streams, &dev_wake_ts);
-
- EXPECT_EQ(start.tv_sec + 5, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_3.
-// The stream 1 is pending reply so it will be ignored. The wake up time should
-// be the next_cb_ts of stream 2.
-TEST_F(TimingSuite, OutputWakeTimeTwoStreamsWithOneIsPendingReply) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- stream1->rstream->next_cb_ts = start;
- stream1->rstream->next_cb_ts.tv_sec += 2;
- rstream_stub_pending_reply(stream1->rstream.get(), 1);
-
- StreamPtr stream2 = create_stream(1, 2, CRAS_STREAM_OUTPUT, 480, &format);
- stream2->rstream->next_cb_ts = start;
- stream2->rstream->next_cb_ts.tv_sec += 5;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
-
- struct timespec dev_wake_ts = start;
- dev_wake_ts.tv_sec += 10;
-
- timespec dev_time =
- SingleOutputDevNextWake(48000, 0, &start, &format, streams, &dev_wake_ts);
-
- EXPECT_EQ(start.tv_sec + 5, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_4.
-// The stream 1 is uning device timing so it will be ignored. The wake up time
-// should be the next_cb_ts of stream 2.
-TEST_F(TimingSuite, OutputWakeTimeTwoStreamsWithOneIsUsingDevTiming) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- stream1->rstream->next_cb_ts = start;
- stream1->rstream->next_cb_ts.tv_sec += 2;
- stream1->rstream->flags = USE_DEV_TIMING;
-
- StreamPtr stream2 = create_stream(1, 2, CRAS_STREAM_OUTPUT, 480, &format);
- stream2->rstream->next_cb_ts = start;
- stream2->rstream->next_cb_ts.tv_sec += 5;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
-
- struct timespec dev_wake_ts = start;
- dev_wake_ts.tv_sec += 10;
-
- timespec dev_time =
- SingleOutputDevNextWake(48000, 0, &start, &format, streams, &dev_wake_ts);
-
- EXPECT_EQ(start.tv_sec + 5, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// Test rule_5.
-// The wake up time should be the next_cb_ts of streams.
-TEST_F(TimingSuite, OutputWakeTimeTwoStreams) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
-
- StreamPtr stream1 = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
- stream1->rstream->next_cb_ts = start;
- stream1->rstream->next_cb_ts.tv_sec += 2;
-
- StreamPtr stream2 = create_stream(1, 2, CRAS_STREAM_OUTPUT, 480, &format);
- stream2->rstream->next_cb_ts = start;
- stream2->rstream->next_cb_ts.tv_sec += 5;
-
- std::vector<StreamPtr> streams;
- streams.emplace_back(std::move(stream1));
- streams.emplace_back(std::move(stream2));
-
- struct timespec dev_wake_ts = start;
- dev_wake_ts.tv_sec += 10;
-
- timespec dev_time =
- SingleOutputDevNextWake(48000, 0, &start, &format, streams, &dev_wake_ts);
-
- EXPECT_EQ(start.tv_sec + 2, dev_time.tv_sec);
- EXPECT_EQ(start.tv_nsec, dev_time.tv_nsec);
-}
-
-// One device, one stream, fetch stream and check the sleep time is one more
-// wakeup interval.
-TEST_F(TimingSuite, OutputStreamsUpdateAfterFetching) {
- cras_audio_format format;
- fill_audio_format(&format, 48000);
-
- StreamPtr stream = create_stream(1, 1, CRAS_STREAM_OUTPUT, 480, &format);
-
- // rstream's next callback is now.
- struct timespec start;
- clock_gettime(CLOCK_MONOTONIC_RAW, &start);
- stream->rstream->next_cb_ts = start;
-
- struct open_dev* dev_list_ = NULL;
-
- DevicePtr dev = create_device(CRAS_STREAM_OUTPUT, 1024, &format,
- CRAS_NODE_TYPE_HEADPHONE);
- DL_APPEND(dev_list_, dev->odev.get());
-
- add_stream_to_dev(dev->dev, stream);
-
- dev_io_playback_fetch(dev_list_);
-
- // The next callback should be scheduled 10ms in the future.
- const timespec ten_millis = {0, 10 * 1000 * 1000};
- add_timespecs(&start, &ten_millis);
- EXPECT_EQ(start.tv_sec, stream->rstream->next_cb_ts.tv_sec);
- EXPECT_EQ(start.tv_nsec, stream->rstream->next_cb_ts.tv_nsec);
-}
-
-// TODO(yuhsuan): There are some time scheduling rules in cras_iodev. Maybe we
-// can move them into dev_io so that all timing related codes are in the same
-// file or leave them in iodev_unittest like now.
-// 1. Device's wake_ts update: cras_iodev_frames_to_play_in_sleep.
-// 2. wake_ts update when removing stream: cras_iodev_rm_stream.
-
-/* Stubs */
-extern "C" {
-
-int input_data_get_for_stream(struct input_data* data,
- struct cras_rstream* stream,
- struct buffer_share* offsets,
- struct cras_audio_area** area,
- unsigned int* offset) {
- return 0;
-}
-
-int input_data_put_for_stream(struct input_data* data,
- struct cras_rstream* stream,
- struct buffer_share* offsets,
- unsigned int frames) {
- return 0;
-}
-
-float input_data_get_software_gain_scaler(struct input_data* data,
- float idev_sw_gain_scaler,
- struct cras_rstream* stream) {
- return 1.0;
-}
-
-struct cras_audio_format* cras_rstream_post_processing_format(
- const struct cras_rstream* stream,
- void* dev_ptr) {
- return NULL;
-}
-
-int cras_audio_thread_event_drop_samples() {
- return 0;
-}
-
-int cras_audio_thread_event_severe_underrun() {
- return 0;
-}
-
-void* buffer_share_get_data(const struct buffer_share* mix, unsigned int id) {
- return NULL;
-};
-void cras_apm_list_start_apm(struct cras_apm_list* list, void* dev_ptr){};
-void cras_apm_list_stop_apm(struct cras_apm_list* list, void* dev_ptr){};
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- openlog(NULL, LOG_PERROR, LOG_USER);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/utf8_unittest.cc b/cras/src/tests/utf8_unittest.cc
deleted file mode 100644
index 4a13fcfa..00000000
--- a/cras/src/tests/utf8_unittest.cc
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Some UTF character seqeuences in this file were taken from
-// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_utf8.h"
-}
-
-namespace {
-
-TEST(UTF8, ValidStress) {
- size_t pos;
-
- EXPECT_EQ(1, valid_utf8_string("The greek word 'kosme': "
- "\xce\xba\xe1\xbd\xb9\xcf\x83\xce"
- "\xbc\xce\xb5",
- &pos));
- EXPECT_EQ(35, pos);
-
- EXPECT_EQ(1, valid_utf8_string("Playback", &pos));
- EXPECT_EQ(8, pos);
-
- EXPECT_EQ(1, valid_utf8_string("The Euro sign: \xe2\x82\xac", &pos));
- EXPECT_EQ(18, pos);
-
- /* First possible sequence of a certain length. */
- EXPECT_EQ(1, valid_utf8_string("\x01", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(1, valid_utf8_string("\xc2\x80", &pos));
- EXPECT_EQ(2, pos);
- EXPECT_EQ(1, valid_utf8_string("\xe0\xa0\x80", &pos));
- EXPECT_EQ(3, pos);
- EXPECT_EQ(1, valid_utf8_string("\xe1\x80\x80", &pos));
- EXPECT_EQ(3, pos);
- EXPECT_EQ(1, valid_utf8_string("\xf0\x90\x80\x80", &pos));
- EXPECT_EQ(4, pos);
- EXPECT_EQ(1, valid_utf8_string("\xf1\x80\x80\x80", &pos));
- EXPECT_EQ(4, pos);
-
- /* Last possible sequence of a certain length. */
- EXPECT_EQ(1, valid_utf8_string("\x7f", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(1, valid_utf8_string("\xdf\xbf", &pos));
- EXPECT_EQ(2, pos);
- EXPECT_EQ(1, valid_utf8_string("\xef\xbf\xbf", &pos));
- EXPECT_EQ(3, pos);
- EXPECT_EQ(1, valid_utf8_string("\xf4\x8f\xbf\xbf", &pos));
- EXPECT_EQ(4, pos);
-
- /* Other boundary conditions. */
- EXPECT_EQ(1, valid_utf8_string("\xed\x9f\xbf", &pos));
- EXPECT_EQ(3, pos);
- EXPECT_EQ(1, valid_utf8_string("\xee\x80\x80", &pos));
- EXPECT_EQ(3, pos);
- EXPECT_EQ(1, valid_utf8_string("\xef\xbf\xbd", &pos));
- EXPECT_EQ(3, pos);
- EXPECT_EQ(1, valid_utf8_string("\xf0\xbf\xbf\xbf", &pos));
- EXPECT_EQ(4, pos);
-
- /* BOM sequence. */
- EXPECT_EQ(1, valid_utf8_string("\xef\xbb\xbf", &pos));
- EXPECT_EQ(3, pos);
-
- /* Valid UTF-8 that shouldn't appear in text; chose to allow
- * these characters anyway. */
- EXPECT_EQ(1, valid_utf8_string("U+FFFE: \xef\xbf\xbe", &pos));
- EXPECT_EQ(11, pos);
- EXPECT_EQ(1, valid_utf8_string("U+FDD0: \xef\xb7\x90", &pos));
- EXPECT_EQ(11, pos);
- EXPECT_EQ(1, valid_utf8_string("\xf0\x9f\xbf\xbe", &pos));
- EXPECT_EQ(4, pos);
-}
-
-TEST(UTF8, InvalidStress) {
- size_t pos;
-
- /* Malformed continuation bytes. */
- EXPECT_EQ(0, valid_utf8_string("\x80", &pos));
- EXPECT_EQ(0, pos);
- EXPECT_EQ(0, valid_utf8_string("\xbf", &pos));
- EXPECT_EQ(0, pos);
- EXPECT_EQ(0, valid_utf8_string("\x80\xbf", &pos));
- EXPECT_EQ(0, pos);
- EXPECT_EQ(0, valid_utf8_string("\xc2\x80\xbf", &pos));
- EXPECT_EQ(2, pos);
-
- /* Lonely start characters. */
- EXPECT_EQ(0, valid_utf8_string("\xc2 \xc3 \xc4 ", &pos));
- EXPECT_EQ(1, pos);
-
- /* Out of range cases. */
- EXPECT_EQ(0, valid_utf8_string("\xf4\x90\xbf\xbf", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string(" \xf5\x80", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string(" \xe0\x80\x80", &pos));
- EXPECT_EQ(2, pos);
- EXPECT_EQ(0, valid_utf8_string("\xf4\x80\x80\xcf", &pos));
- EXPECT_EQ(3, pos);
-
- /* Stop in mid-sequence. */
- EXPECT_EQ(0, valid_utf8_string("\xf4\x80", &pos));
- EXPECT_EQ(2, pos);
-
- /* Bad characters. */
- EXPECT_EQ(0, valid_utf8_string("\xff", &pos));
- EXPECT_EQ(0, pos);
- EXPECT_EQ(0, valid_utf8_string("\xfe", &pos));
- EXPECT_EQ(0, pos);
-
- /* Overlong representations of ASCII characters. */
- EXPECT_EQ(0, valid_utf8_string("This represents the / character with too"
- "many bytes: \xe0\x80\xaf",
- &pos));
- EXPECT_EQ(53, pos);
- EXPECT_EQ(0, valid_utf8_string("This represents the / character with too"
- "many bytes: \xf0\x80\x80\xaf",
- &pos));
- EXPECT_EQ(53, pos);
-
- /* Should not be interpreted as the ASCII NUL character. */
- EXPECT_EQ(0, valid_utf8_string("This represents the NUL character with too"
- "many bytes: \xe0\x80\x80",
- &pos));
- EXPECT_EQ(55, pos);
- EXPECT_EQ(0, valid_utf8_string("This represents the NUL character with too"
- "many bytes: \xf0\x80\x80\x80",
- &pos));
- EXPECT_EQ(55, pos);
-
- /* Single UTF-16 surrogates. */
- EXPECT_EQ(0, valid_utf8_string("\xed\xa0\x80", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string("\xed\xad\xbf", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string("\xed\xae\x80", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string("\xed\xaf\xbf", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string("\xed\xb0\x80", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string("\xed\xbe\x80", &pos));
- EXPECT_EQ(1, pos);
- EXPECT_EQ(0, valid_utf8_string("\xed\xbf\xbf", &pos));
- EXPECT_EQ(1, pos);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/util_unittest.cc b/cras/src/tests/util_unittest.cc
deleted file mode 100644
index e61336ad..00000000
--- a/cras/src/tests/util_unittest.cc
+++ /dev/null
@@ -1,330 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <string>
-#include <vector>
-
-#include "cras_util.h"
-
-namespace {
-
-static std::vector<struct timespec> time_now;
-
-TEST(Util, SendRecvTwoFileDescriptors) {
- int fd[2];
- int fd2[2];
- int send_fds[2];
- int sock[2];
- char buf[256] = {0};
- int new_fds[2];
- char msg[] = "multi-fd";
- unsigned int num_fds = 2;
-
- /* Create a pipe and a pair of sockets. Then send the write end of
- * the pipe (fd[1]) through the socket, and receive it as
- * new_fd */
- ASSERT_EQ(0, pipe(fd));
- ASSERT_EQ(0, pipe(fd2));
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- send_fds[0] = fd[1];
- send_fds[1] = fd2[1];
- ASSERT_GE(cras_send_with_fds(sock[0], msg, strlen(msg), send_fds, num_fds),
- 0);
- ASSERT_GE(cras_recv_with_fds(sock[1], buf, strlen(msg), new_fds, &num_fds),
- 0);
- ASSERT_STREQ(msg, buf);
- ASSERT_EQ(2, num_fds);
- ASSERT_NE(-1, new_fds[0]);
- ASSERT_NE(-1, new_fds[1]);
-
- close(sock[0]);
- close(sock[1]);
- close(fd[1]);
- close(fd2[1]);
-
- /* Send a character to the new_fd, and receive it from the read end
- * of the pipe (fd[0]) */
- ASSERT_EQ(1, write(new_fds[0], "a", 1));
- ASSERT_EQ(1, read(fd[0], buf, 1));
- ASSERT_EQ('a', buf[0]);
- ASSERT_EQ(1, write(new_fds[1], "b", 1));
- ASSERT_EQ(1, read(fd2[0], buf, 1));
- ASSERT_EQ('b', buf[0]);
-
- close(fd[0]);
- close(fd2[0]);
- close(new_fds[0]);
- close(new_fds[1]);
-}
-
-TEST(Util, SendOneRecvTwoFileDescriptors) {
- int fd[2];
- int sock[2];
- char buf[256] = {0};
- int new_fds[2];
- char msg[] = "multi-fd";
- unsigned int num_fds = 2;
-
- /* Create a pipe and a pair of sockets. Then send the write end of
- * the pipe (fd[1]) through the socket, and receive it as
- * new_fd */
- ASSERT_EQ(0, pipe(fd));
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- ASSERT_GE(cras_send_with_fds(sock[0], msg, strlen(msg), &fd[1], 1), 0);
- ASSERT_GE(cras_recv_with_fds(sock[1], buf, strlen(msg), new_fds, &num_fds),
- 0);
- ASSERT_STREQ(msg, buf);
- ASSERT_EQ(1, num_fds);
- ASSERT_NE(-1, new_fds[0]);
- ASSERT_EQ(-1, new_fds[1]);
-
- close(sock[0]);
- close(sock[1]);
- close(fd[1]);
-
- /* Send a character to the new_fd, and receive it from the read end
- * of the pipe (fd[0]) */
- ASSERT_EQ(1, write(new_fds[0], "a", 1));
- ASSERT_EQ(1, read(fd[0], buf, 1));
- ASSERT_EQ('a', buf[0]);
-
- close(fd[0]);
- close(new_fds[0]);
- close(new_fds[1]);
-}
-
-TEST(Util, SendRecvFileDescriptor) {
- int fd[2];
- int sock[2];
- char buf[256] = {0};
- int new_fd;
- char msg[] = "hello";
- unsigned int num_fds = 1;
-
- /* Create a pipe and a pair of sockets. Then send the write end of
- * the pipe (fd[1]) through the socket, and receive it as
- * new_fd */
- ASSERT_EQ(0, pipe(fd));
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- ASSERT_EQ(5, cras_send_with_fds(sock[0], msg, strlen(msg), &fd[1], num_fds));
- ASSERT_EQ(5,
- cras_recv_with_fds(sock[1], buf, strlen(msg), &new_fd, &num_fds));
- ASSERT_STREQ(msg, buf);
- ASSERT_EQ(1, num_fds);
-
- close(sock[0]);
- close(sock[1]);
- close(fd[1]);
-
- /* Send a character to the new_fd, and receive it from the read end
- * of the pipe (fd[0]) */
- ASSERT_EQ(1, write(new_fd, "a", 1));
- ASSERT_EQ(1, read(fd[0], buf, 1));
- ASSERT_EQ('a', buf[0]);
-
- close(fd[0]);
- close(new_fd);
-}
-
-TEST(Util, SendRecvNoDescriptors) {
- char buf[256] = {0};
- char msg[] = "no descriptors";
- unsigned int num_fds = 0;
- int sock[2];
-
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sock));
-
- ASSERT_GE(cras_send_with_fds(sock[0], msg, strlen(msg), NULL, num_fds), 0);
- ASSERT_GE(cras_recv_with_fds(sock[1], buf, strlen(msg), NULL, &num_fds), 0);
- ASSERT_STREQ(msg, buf);
- ASSERT_EQ(0, num_fds);
-
- close(sock[0]);
- close(sock[1]);
-}
-
-TEST(Util, TimevalAfter) {
- struct timeval t0, t1;
- t0.tv_sec = 0;
- t0.tv_usec = 0;
- t1.tv_sec = 0;
- t1.tv_usec = 0;
- ASSERT_FALSE(timeval_after(&t0, &t1));
- ASSERT_FALSE(timeval_after(&t1, &t0));
- t0.tv_usec = 1;
- ASSERT_TRUE(timeval_after(&t0, &t1));
- ASSERT_FALSE(timeval_after(&t1, &t0));
- t1.tv_sec = 1;
- ASSERT_FALSE(timeval_after(&t0, &t1));
- ASSERT_TRUE(timeval_after(&t1, &t0));
-}
-
-TEST(Util, FramesToTime) {
- struct timespec t;
-
- cras_frames_to_time(24000, 48000, &t);
- EXPECT_EQ(0, t.tv_sec);
- EXPECT_EQ(500000000, t.tv_nsec);
-
- cras_frames_to_time(48000, 48000, &t);
- EXPECT_EQ(1, t.tv_sec);
- EXPECT_EQ(0, t.tv_nsec);
-
- cras_frames_to_time(60000, 48000, &t);
- EXPECT_EQ(1, t.tv_sec);
- EXPECT_EQ(250000000, t.tv_nsec);
-
- cras_frames_to_time(191999, 192000, &t);
- EXPECT_EQ(0, t.tv_sec);
- EXPECT_EQ(999994791, t.tv_nsec);
-}
-
-TEST(Util, TimeToFrames) {
- struct timespec t;
- unsigned int frames;
-
- t.tv_sec = 0;
- t.tv_nsec = 500000000;
- frames = cras_time_to_frames(&t, 48000);
- EXPECT_EQ(24000, frames);
-
- t.tv_sec = 1;
- t.tv_nsec = 500000000;
- frames = cras_time_to_frames(&t, 48000);
- EXPECT_EQ(72000, frames);
-
- t.tv_sec = 0;
- t.tv_nsec = 0;
- frames = cras_time_to_frames(&t, 48000);
- EXPECT_EQ(0, frames);
-}
-
-TEST(Util, FramesToMs) {
- EXPECT_EQ(500, cras_frames_to_ms(24000, 48000));
- EXPECT_EQ(0, cras_frames_to_ms(1, 48000));
- EXPECT_EQ(10, cras_frames_to_ms(480, 48000));
- EXPECT_EQ(10, cras_frames_to_ms(488, 48000));
- EXPECT_EQ(50, cras_frames_to_ms(800, 16000));
-}
-
-TEST(Util, TimespecToMs) {
- struct timespec ts;
-
- ts.tv_sec = 0;
- ts.tv_nsec = 500000000;
- EXPECT_EQ(500, timespec_to_ms(&ts));
-
- ts.tv_sec = 0;
- ts.tv_nsec = 0;
- EXPECT_EQ(0, timespec_to_ms(&ts));
-
- ts.tv_sec = 0;
- ts.tv_nsec = 2;
- EXPECT_EQ(1, timespec_to_ms(&ts));
-
- ts.tv_sec = 0;
- ts.tv_nsec = 10000000;
- EXPECT_EQ(10, timespec_to_ms(&ts));
-
- ts.tv_sec = 1;
- ts.tv_nsec = 0;
- EXPECT_EQ(1000, timespec_to_ms(&ts));
-
- ts.tv_sec = 1;
- ts.tv_nsec = 1;
- EXPECT_EQ(1001, timespec_to_ms(&ts));
-}
-
-TEST(Util, FramesSinceTime) {
- struct timespec t, tn;
- uint64_t frames;
-
- t.tv_sec = 0;
- t.tv_nsec = 500000000;
-
- tn.tv_sec = 2;
- tn.tv_nsec = 0;
- time_now.push_back(tn);
- frames = cras_frames_since_time(&t, 48000);
- EXPECT_EQ(72000, frames);
-
- tn.tv_sec = 0;
- time_now.push_back(tn);
- frames = cras_frames_since_time(&t, 48000);
- EXPECT_EQ(0, frames);
-}
-
-// Test cras_poll().
-TEST(Util, CrasPoll) {
- int pipe_fds[2];
- struct pollfd poll_fd;
- std::string output;
- struct timespec timeout;
- char buf[256];
-
- ASSERT_EQ(0, pipe(pipe_fds));
- poll_fd.fd = pipe_fds[0];
- poll_fd.events = POLLIN;
- ASSERT_NE(0, poll_fd.fd >= 0);
-
- // Simple poll.
- output = "Hello";
- EXPECT_EQ(output.size() + 1,
- write(pipe_fds[1], output.c_str(), output.size() + 1));
- EXPECT_EQ(1, cras_poll(&poll_fd, 1, NULL, NULL));
- ASSERT_EQ(static_cast<ssize_t>(output.size() + 1),
- read(pipe_fds[0], buf, sizeof(buf)));
- EXPECT_EQ(0, strcmp(output.c_str(), buf));
-
- // Negative time.
- timeout.tv_sec = 0;
- timeout.tv_nsec = -10000000;
- EXPECT_EQ(-ETIMEDOUT, cras_poll(&poll_fd, 1, &timeout, NULL));
- timeout.tv_sec = -1;
- timeout.tv_nsec = 10000000;
- EXPECT_EQ(-ETIMEDOUT, cras_poll(&poll_fd, 1, &timeout, NULL));
-
- // Timeout.
- timeout.tv_sec = 0;
- timeout.tv_nsec = 0;
- time_now.push_back(timeout);
- timeout.tv_nsec = 1100000;
- time_now.push_back(timeout);
- timeout.tv_nsec = 1000000;
- EXPECT_EQ(-ETIMEDOUT, cras_poll(&poll_fd, 1, &timeout, NULL));
- EXPECT_EQ(timeout.tv_nsec, -100000);
-
- EXPECT_EQ(0, close(pipe_fds[0]));
- EXPECT_EQ(0, close(pipe_fds[1]));
-}
-
-/* Stubs */
-extern "C" {
-
-int clock_gettime(clockid_t clk_id, struct timespec* tp) {
- std::vector<struct timespec>::iterator i = time_now.begin();
- if (i != time_now.end()) {
- *tp = *i;
- time_now.erase(i);
- } else
- memset(tp, 0, sizeof(*tp));
- return 0;
-}
-
-} // extern "C"
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tests/volume_curve_unittest.cc b/cras/src/tests/volume_curve_unittest.cc
deleted file mode 100644
index 267452aa..00000000
--- a/cras/src/tests/volume_curve_unittest.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <gtest/gtest.h>
-#include <stdio.h>
-
-extern "C" {
-#include "cras_volume_curve.h"
-}
-
-namespace {
-
-TEST(VolumeCurve, DefaultCurve) {
- struct cras_volume_curve* curve;
- curve = cras_volume_curve_create_default();
- ASSERT_NE(static_cast<struct cras_volume_curve*>(NULL), curve);
- EXPECT_EQ(0 - 50 * 50, curve->get_dBFS(curve, 50));
- EXPECT_EQ(0, curve->get_dBFS(curve, 100));
- EXPECT_EQ(0 - 100 * 50, curve->get_dBFS(curve, 0));
- EXPECT_EQ(0 - 25 * 50, curve->get_dBFS(curve, 75));
- cras_volume_curve_destroy(curve);
-}
-
-TEST(VolumeCurve, SteppedCurve) {
- struct cras_volume_curve* curve;
- curve = cras_volume_curve_create_simple_step(-600, 75);
- ASSERT_NE(static_cast<struct cras_volume_curve*>(NULL), curve);
- EXPECT_EQ(-600 - 50 * 75, curve->get_dBFS(curve, 50));
- EXPECT_EQ(-600, curve->get_dBFS(curve, 100));
- EXPECT_EQ(-600 - 100 * 75, curve->get_dBFS(curve, 0));
- EXPECT_EQ(-600 - 25 * 75, curve->get_dBFS(curve, 75));
- cras_volume_curve_destroy(curve);
-}
-
-TEST(VolumeCurve, ExplicitCurve) {
- struct cras_volume_curve* curve;
- long dB_vals[101];
-
- for (unsigned int i = 0; i < 101; i++)
- dB_vals[i] = i * 2 + -400;
- curve = cras_volume_curve_create_explicit(dB_vals);
- ASSERT_NE(static_cast<struct cras_volume_curve*>(NULL), curve);
- for (unsigned int i = 0; i < 101; i++)
- EXPECT_EQ(i * 2 - 400, curve->get_dBFS(curve, i));
- cras_volume_curve_destroy(curve);
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- ::testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
diff --git a/cras/src/tools/cras_monitor/cras_monitor.c b/cras/src/tools/cras_monitor/cras_monitor.c
deleted file mode 100644
index 19252773..00000000
--- a/cras/src/tools/cras_monitor/cras_monitor.c
+++ /dev/null
@@ -1,309 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <getopt.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <string.h>
-#include <syslog.h>
-#include <sys/select.h>
-#include <unistd.h>
-
-#include "cras_client.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "cras_version.h"
-
-static void output_volume_changed(void *context, int32_t volume)
-{
- printf("output volume: %d/100\n", volume);
-}
-
-static void output_mute_changed(void *context, int muted, int user_muted,
- int mute_locked)
-{
- printf("output mute: muted: %d, user_muted: %d, mute_locked: %d\n",
- muted, user_muted, mute_locked);
-}
-
-static void capture_mute_changed(void *context, int muted, int mute_locked)
-{
- printf("capture mute: muted: %d, mute_locked: %d\n", muted,
- mute_locked);
-}
-
-static void nodes_changed(void *context)
-{
- printf("nodes changed\n");
-}
-
-static const char *string_for_direction(enum CRAS_STREAM_DIRECTION dir)
-{
- switch (dir) {
- case CRAS_STREAM_OUTPUT:
- return "output";
- case CRAS_STREAM_INPUT:
- return "input";
- case CRAS_STREAM_POST_MIX_PRE_DSP:
- return "post_mix_pre_dsp";
- default:
- break;
- }
-
- return "undefined";
-}
-
-size_t node_array_index_of_node_id(struct cras_ionode_info *nodes,
- size_t num_nodes, cras_node_id_t node_id)
-{
- uint32_t dev_index = dev_index_of(node_id);
- uint32_t node_index = node_index_of(node_id);
- size_t i;
-
- for (i = 0; i < num_nodes; i++) {
- if (nodes[i].iodev_idx == dev_index &&
- nodes[i].ionode_idx == node_index)
- return i;
- }
- return CRAS_MAX_IONODES;
-}
-
-const char *node_name_for_node_id(struct cras_client *client,
- enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_ionode_info nodes[CRAS_MAX_IONODES];
- struct cras_iodev_info devs[CRAS_MAX_IODEVS];
- size_t num_devs = CRAS_MAX_IODEVS;
- size_t num_nodes = CRAS_MAX_IONODES;
- uint32_t iodev_idx = dev_index_of(node_id);
- size_t node_index;
- char buf[1024];
- int rc;
-
- if (node_id == 0) {
- return strdup("none");
- } else if (iodev_idx <= 2) {
- return strdup("fallback");
- } else if (dir == CRAS_STREAM_POST_MIX_PRE_DSP) {
- snprintf(buf, sizeof(buf), "%s node: %" PRIu64 "\n",
- string_for_direction(dir), node_id);
- return strdup(buf);
- } else if (dir == CRAS_STREAM_OUTPUT) {
- rc = cras_client_get_output_devices(client, devs, nodes,
- &num_devs, &num_nodes);
- } else if (dir == CRAS_STREAM_INPUT) {
- rc = cras_client_get_input_devices(client, devs, nodes,
- &num_devs, &num_nodes);
- } else {
- return strdup("unknown");
- }
-
- if (rc != 0) {
- syslog(LOG_ERR, "Couldn't get output devices: %s\n",
- strerror(-rc));
- snprintf(buf, sizeof(buf), "%u:%u", iodev_idx,
- node_index_of(node_id));
- return strdup(buf);
- }
- node_index = node_array_index_of_node_id(nodes, num_nodes, node_id);
- if (node_index >= num_nodes)
- snprintf(buf, sizeof(buf), "unknown: %zu >= %zu", node_index,
- num_nodes);
- else
- snprintf(buf, sizeof(buf), "%u:%u: %s",
- nodes[node_index].iodev_idx,
- nodes[node_index].ionode_idx, nodes[node_index].name);
- return strdup(buf);
-}
-
-static void active_node_changed(void *context, enum CRAS_STREAM_DIRECTION dir,
- cras_node_id_t node_id)
-{
- struct cras_client *client = (struct cras_client *)context;
- const char *node_name = node_name_for_node_id(client, dir, node_id);
- printf("active node (%s): %s\n", string_for_direction(dir), node_name);
- free((void *)node_name);
-}
-
-static void output_node_volume_changed(void *context, cras_node_id_t node_id,
- int32_t volume)
-{
- struct cras_client *client = (struct cras_client *)context;
- const char *node_name =
- node_name_for_node_id(client, CRAS_STREAM_OUTPUT, node_id);
- printf("output node '%s' volume: %d\n", node_name, volume);
- free((void *)node_name);
-}
-
-static void node_left_right_swapped_changed(void *context,
- cras_node_id_t node_id, int swapped)
-{
- struct cras_client *client = (struct cras_client *)context;
- const char *node_name =
- node_name_for_node_id(client, CRAS_STREAM_OUTPUT, node_id);
- printf("output node '%s' left-right swapped: %d\n", node_name, swapped);
- free((void *)node_name);
-}
-
-static void input_node_gain_changed(void *context, cras_node_id_t node_id,
- int32_t gain)
-{
- struct cras_client *client = (struct cras_client *)context;
- const char *node_name =
- node_name_for_node_id(client, CRAS_STREAM_INPUT, node_id);
- printf("input node '%s' gain: %d\n", node_name, gain);
- free((void *)node_name);
-}
-
-static void num_active_streams_changed(void *context,
- enum CRAS_STREAM_DIRECTION dir,
- uint32_t num_active_streams)
-{
- printf("num active %s streams: %u\n", string_for_direction(dir),
- num_active_streams);
-}
-
-static void server_connection_callback(struct cras_client *client,
- cras_connection_status_t status,
- void *user_arg)
-{
- const char *status_str = "undefined";
- switch (status) {
- case CRAS_CONN_STATUS_FAILED:
- status_str = "error";
- break;
- case CRAS_CONN_STATUS_DISCONNECTED:
- status_str = "disconnected";
- break;
- case CRAS_CONN_STATUS_CONNECTED:
- status_str = "connected";
- break;
- }
- printf("server %s\n", status_str);
-}
-
-static void print_usage(const char *command)
-{
- fprintf(stderr,
- "%s [options]\n"
- " Where [options] are:\n"
- " --sync|-s - Use the synchronous connection functions.\n"
- " --log-level|-l <n> - Set the syslog level (7 == "
- "LOG_DEBUG).\n",
- command);
-}
-
-int main(int argc, char **argv)
-{
- struct cras_client *client;
- int rc;
- int option_character;
- bool synchronous = false;
- int log_level = LOG_WARNING;
- static struct option long_options[] = {
- { "sync", no_argument, NULL, 's' },
- { "log-level", required_argument, NULL, 'l' },
- { NULL, 0, NULL, 0 },
- };
-
- while (true) {
- int option_index = 0;
-
- option_character = getopt_long(argc, argv, "sl:", long_options,
- &option_index);
- if (option_character == -1)
- break;
- switch (option_character) {
- case 's':
- synchronous = !synchronous;
- break;
- case 'l':
- log_level = atoi(optarg);
- if (log_level < 0)
- log_level = LOG_WARNING;
- else if (log_level > LOG_DEBUG)
- log_level = LOG_DEBUG;
- break;
- default:
- print_usage(argv[0]);
- return 1;
- }
- }
-
- if (optind < argc) {
- fprintf(stderr, "%s: Extra arguments.\n", argv[0]);
- print_usage(argv[0]);
- return 1;
- }
-
- openlog("cras_monitor", LOG_PERROR, LOG_USER);
- setlogmask(LOG_UPTO(log_level));
-
- rc = cras_client_create(&client);
- if (rc < 0) {
- syslog(LOG_ERR, "Couldn't create client.");
- return rc;
- }
-
- cras_client_set_connection_status_cb(client, server_connection_callback,
- NULL);
-
- if (synchronous) {
- rc = cras_client_connect(client);
- if (rc != 0) {
- syslog(LOG_ERR, "Could not connect to server.");
- return -rc;
- }
- }
-
- cras_client_set_output_volume_changed_callback(client,
- output_volume_changed);
- cras_client_set_output_mute_changed_callback(client,
- output_mute_changed);
- cras_client_set_capture_mute_changed_callback(client,
- capture_mute_changed);
- cras_client_set_nodes_changed_callback(client, nodes_changed);
- cras_client_set_active_node_changed_callback(client,
- active_node_changed);
- cras_client_set_output_node_volume_changed_callback(
- client, output_node_volume_changed);
- cras_client_set_node_left_right_swapped_changed_callback(
- client, node_left_right_swapped_changed);
- cras_client_set_input_node_gain_changed_callback(
- client, input_node_gain_changed);
- cras_client_set_num_active_streams_changed_callback(
- client, num_active_streams_changed);
- cras_client_set_state_change_callback_context(client, client);
-
- rc = cras_client_run_thread(client);
- if (rc != 0) {
- syslog(LOG_ERR, "Could not start thread.");
- return -rc;
- }
-
- if (!synchronous) {
- rc = cras_client_connect_async(client);
- if (rc) {
- syslog(LOG_ERR, "Couldn't connect to server.\n");
- goto destroy_exit;
- }
- }
-
- while (1) {
- int rc;
- char c;
- rc = read(STDIN_FILENO, &c, 1);
- if (rc < 0 || c == 'q')
- return 0;
- }
-
-destroy_exit:
- cras_client_destroy(client);
- return 0;
-}
diff --git a/cras/src/tools/cras_router/cras_router.c b/cras/src/tools/cras_router/cras_router.c
deleted file mode 100644
index b65b0525..00000000
--- a/cras/src/tools/cras_router/cras_router.c
+++ /dev/null
@@ -1,241 +0,0 @@
-/* Copyright 2016 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-#include <fcntl.h>
-#include <errno.h>
-#include <getopt.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/param.h>
-#include <unistd.h>
-
-#include "cras_client.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "cras_version.h"
-
-#define PLAYBACK_BUFFERED_TIME_IN_NS (5000000)
-
-#define BUF_SIZE 32768
-
-static int keep_looping = 1;
-static int pipefd[2];
-struct cras_audio_format *aud_format;
-
-static int terminate_stream_loop(void)
-{
- keep_looping = 0;
- return write(pipefd[1], "1", 1);
-}
-
-static size_t get_block_size(uint64_t buffer_time_in_ns, size_t rate)
-{
- static struct timespec t;
-
- t.tv_nsec = buffer_time_in_ns;
- t.tv_sec = 0;
- return (size_t)cras_time_to_frames(&t, rate);
-}
-
-/* Run from callback thread. */
-static int got_samples(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- int *fd = (int *)user_arg;
- int ret;
- int write_size;
- int frame_bytes;
-
- frame_bytes = cras_client_format_bytes_per_frame(aud_format);
- write_size = frames * frame_bytes;
- ret = write(*fd, captured_samples, write_size);
- if (ret != write_size)
- printf("Error writing file\n");
- return frames;
-}
-
-/* Run from callback thread. */
-static int put_samples(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- uint32_t frame_bytes = cras_client_format_bytes_per_frame(aud_format);
- int fd = *(int *)user_arg;
- uint8_t buff[BUF_SIZE];
- int nread;
-
- nread = read(fd, buff, MIN(frames * frame_bytes, BUF_SIZE));
- if (nread <= 0) {
- terminate_stream_loop();
- return nread;
- }
-
- memcpy(playback_samples, buff, nread);
- return nread / frame_bytes;
-}
-
-static int stream_error(struct cras_client *client, cras_stream_id_t stream_id,
- int err, void *arg)
-{
- printf("Stream error %d\n", err);
- terminate_stream_loop();
- return 0;
-}
-
-static int start_stream(struct cras_client *client, cras_stream_id_t *stream_id,
- struct cras_stream_params *params, float stream_volume)
-{
- int rc;
-
- rc = cras_client_add_stream(client, stream_id, params);
- if (rc < 0) {
- fprintf(stderr, "adding a stream %d\n", rc);
- return rc;
- }
- return cras_client_set_stream_volume(client, *stream_id, stream_volume);
-}
-
-static int run_file_io_stream(struct cras_client *client, int fd, int loop_fd,
- enum CRAS_STREAM_DIRECTION direction,
- size_t block_size, size_t rate,
- size_t num_channels)
-{
- struct cras_stream_params *params;
- cras_stream_id_t stream_id = 0;
- int stream_playing = 0;
- int *pfd = malloc(sizeof(*pfd));
- *pfd = fd;
- float volume_scaler = 1.0;
-
- if (pipe(pipefd) == -1) {
- perror("failed to open pipe");
- return -errno;
- }
- aud_format = cras_audio_format_create(SND_PCM_FORMAT_S16_LE, rate,
- num_channels);
- if (aud_format == NULL)
- return -ENOMEM;
-
- params = cras_client_unified_params_create(direction, block_size, 0, 0,
- pfd, got_samples,
- stream_error, aud_format);
- if (params == NULL)
- return -ENOMEM;
-
- cras_client_run_thread(client);
- stream_playing =
- start_stream(client, &stream_id, params, volume_scaler) == 0;
- if (!stream_playing)
- return -EINVAL;
-
- int *pfd1 = malloc(sizeof(*pfd1));
- *pfd1 = loop_fd;
- struct cras_stream_params *loop_params;
- cras_stream_id_t loop_stream_id = 0;
-
- direction = CRAS_STREAM_OUTPUT;
-
- loop_params =
- cras_client_unified_params_create(direction, block_size, 0, 0,
- pfd1, put_samples,
- stream_error, aud_format);
- stream_playing = start_stream(client, &loop_stream_id, loop_params,
- volume_scaler) == 0;
- if (!stream_playing)
- return -EINVAL;
-
- fd_set poll_set;
-
- FD_ZERO(&poll_set);
- FD_SET(pipefd[0], &poll_set);
- pselect(pipefd[0] + 1, &poll_set, NULL, NULL, NULL, NULL);
- cras_client_stop(client);
- cras_audio_format_destroy(aud_format);
- cras_client_stream_params_destroy(params);
- free(pfd);
-
- close(pipefd[0]);
- close(pipefd[1]);
-
- return 0;
-}
-
-static struct option long_options[] = { { "help", no_argument, 0, 'h' },
- { "rate", required_argument, 0, 'r' },
- { 0, 0, 0, 0 } };
-
-static void show_usage(void)
-{
- printf("--help - shows this message and exits\n");
- printf("--rate <N> - desired sample rate\n\n");
- printf("Running cras_router will run a loop through ");
- printf("from the currently set input to the currently set output.\n");
- printf("Use cras_test_client --dump_s to see all avaiable nodes and");
- printf(" cras_test_client --set_input/output to set a node.\n");
-}
-
-int main(int argc, char **argv)
-{
- struct cras_client *client;
- size_t rate = 44100;
- size_t num_channels = 2;
- size_t block_size;
- int rc = 0;
- int c, option_index;
-
- option_index = 0;
-
- rc = cras_client_create(&client);
- if (rc < 0) {
- fprintf(stderr, "Couldn't create client.\n");
- return rc;
- }
-
- rc = cras_client_connect(client);
- if (rc) {
- fprintf(stderr, "Couldn't connect to server.\n");
- goto destroy_exit;
- }
-
- while (1) {
- c = getopt_long(argc, argv, "hr:", long_options, &option_index);
- if (c == -1)
- break;
- switch (c) {
- case 'h':
- show_usage();
- goto destroy_exit;
- case 'r':
- rate = atoi(optarg);
- break;
- default:
- break;
- }
- }
-
- block_size = get_block_size(PLAYBACK_BUFFERED_TIME_IN_NS, rate);
-
- /* Run loopthrough */
- int pfd[2];
-
- rc = pipe(pfd);
- if (rc < 0) {
- fprintf(stderr, "Couldn't create loopthrough pipe.\n");
- return rc;
- }
- run_file_io_stream(client, pfd[1], pfd[0], CRAS_STREAM_INPUT,
- block_size, rate, num_channels);
-
-destroy_exit:
- cras_client_destroy(client);
- return rc;
-}
diff --git a/cras/src/tools/cras_test_client/cras_test_client.c b/cras/src/tools/cras_test_client/cras_test_client.c
deleted file mode 100644
index 7a851852..00000000
--- a/cras/src/tools/cras_test_client/cras_test_client.c
+++ /dev/null
@@ -1,2426 +0,0 @@
-/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <getopt.h>
-#include <inttypes.h>
-#include <limits.h>
-#include <math.h>
-#include <pthread.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <syslog.h>
-#include <sys/mman.h>
-#include <sys/param.h>
-#include <sys/select.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "cras_client.h"
-#include "cras_types.h"
-#include "cras_util.h"
-#include "cras_version.h"
-
-#define NOT_ASSIGNED (0)
-#define PLAYBACK_BUFFERED_TIME_IN_US (5000)
-
-#define BUF_SIZE 32768
-
-static const size_t MAX_IODEVS = 10; /* Max devices to print out. */
-static const size_t MAX_IONODES = 20; /* Max ionodes to print out. */
-static const size_t MAX_ATTACHED_CLIENTS = 10; /* Max clients to print out. */
-
-static int pipefd[2];
-static struct timespec last_latency;
-static int show_latency;
-static float last_rms_sqr_sum;
-static int last_rms_size;
-static float total_rms_sqr_sum;
-static int total_rms_size;
-static int show_rms;
-static int show_total_rms;
-static int keep_looping = 1;
-static int exit_after_done_playing = 1;
-static size_t duration_frames;
-static int pause_client = 0;
-static int pause_a_reply = 0;
-static int pause_in_playback_reply = 1000;
-
-static char *channel_layout = NULL;
-static int pin_device_id;
-
-static int play_short_sound = 0;
-static int play_short_sound_periods = 0;
-static int play_short_sound_periods_left = 0;
-
-static int effect_aec = 0;
-static int effect_ns = 0;
-static int effect_agc = 0;
-static int effect_vad = 0;
-static char *aecdump_file = NULL;
-static char time_str[128];
-
-/* Sleep interval between cras_client_read_atlog calls. */
-static const struct timespec follow_atlog_sleep_ts = {
- 0, 50 * 1000 * 1000 /* 50 ms. */
-};
-
-/* Conditional so the client thread can signal that main should exit. */
-static pthread_mutex_t done_mutex = PTHREAD_MUTEX_INITIALIZER;
-static pthread_cond_t done_cond = PTHREAD_COND_INITIALIZER;
-
-struct cras_audio_format *aud_format;
-struct {
- char *name;
- snd_pcm_format_t format;
-} supported_formats[] = {
- { "S16_LE", SND_PCM_FORMAT_S16_LE },
- { "S24_LE", SND_PCM_FORMAT_S24_LE },
- { "S32_LE", SND_PCM_FORMAT_S32_LE },
- { NULL, 0 },
-};
-
-static int terminate_stream_loop()
-{
- keep_looping = 0;
- return write(pipefd[1], "1", 1);
-}
-
-static size_t get_block_size(uint64_t buffer_time_in_us, size_t rate)
-{
- return (size_t)(buffer_time_in_us * rate / 1000000);
-}
-
-static void check_stream_terminate(size_t frames)
-{
- if (duration_frames) {
- if (duration_frames <= frames)
- terminate_stream_loop();
- else
- duration_frames -= frames;
- }
-}
-
-static void fill_time_offset(time_t *sec_offset, int32_t *nsec_offset)
-{
- struct timespec mono_time, real_time;
-
- clock_gettime(CLOCK_MONOTONIC_RAW, &mono_time);
- clock_gettime(CLOCK_REALTIME, &real_time);
- *sec_offset = real_time.tv_sec - mono_time.tv_sec;
- *nsec_offset = real_time.tv_nsec - mono_time.tv_nsec;
-}
-
-/* Compute square sum of samples (for calculation of RMS value). */
-float compute_sqr_sum_16(const int16_t *samples, int size)
-{
- unsigned i;
- float sqr_sum = 0;
-
- for (i = 0; i < size; i++)
- sqr_sum += samples[i] * samples[i];
-
- return sqr_sum;
-}
-
-/* Update the RMS values with the given samples. */
-int update_rms(const uint8_t *samples, int size)
-{
- switch (aud_format->format) {
- case SND_PCM_FORMAT_S16_LE: {
- last_rms_sqr_sum =
- compute_sqr_sum_16((int16_t *)samples, size / 2);
- last_rms_size = size / 2;
- break;
- }
- default:
- return -EINVAL;
- }
-
- total_rms_sqr_sum += last_rms_sqr_sum;
- total_rms_size += last_rms_size;
-
- return 0;
-}
-
-/* Parses a string with format <N>:<M> into a node id*/
-static int parse_node_id(char *input, cras_node_id_t *id_out)
-{
- const char *s;
- char *endptr;
- int dev_index;
- int node_index;
-
- if (!id_out)
- return -EINVAL;
-
- s = strtok(input, ":");
- if (!s)
- return -EINVAL;
- dev_index = strtol(s, &endptr, 10);
- if (*endptr)
- return -EINVAL;
-
- s = strtok(NULL, ":");
- if (!s)
- return -EINVAL;
- node_index = strtol(s, &endptr, 10);
- if (*endptr)
- return -EINVAL;
-
- *id_out = cras_make_node_id(dev_index, node_index);
- return 0;
-}
-
-/* Parses a string with format <N>:<M>:<0-100> into a node id and a value */
-static int parse_node_id_with_value(char *input, cras_node_id_t *id_out,
- int *value_out)
-{
- const char *s;
- char *endptr;
- int dev_index;
- int node_index;
- long int value;
-
- if (!id_out || !value_out)
- return -EINVAL;
-
- s = strtok(input, ":");
- if (!s)
- return -EINVAL;
- dev_index = strtol(s, &endptr, 10);
- if (*endptr)
- return -EINVAL;
-
- s = strtok(NULL, ":");
- if (!s)
- return -EINVAL;
- node_index = strtol(s, &endptr, 10);
- if (*endptr)
- return -EINVAL;
-
- s = strtok(NULL, ":");
- if (!s)
- return -EINVAL;
- value = strtol(s, &endptr, 10);
- if (*endptr)
- return -EINVAL;
- if (value > INT_MAX || value < INT_MIN)
- return -EOVERFLOW;
-
- *id_out = cras_make_node_id(dev_index, node_index);
- *value_out = value;
- return 0;
-}
-
-/* Run from callback thread. */
-static int got_samples(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- int *fd = (int *)user_arg;
- int ret;
- int write_size;
- int frame_bytes;
-
- while (pause_client)
- usleep(10000);
-
- cras_client_calc_capture_latency(captured_time, &last_latency);
-
- frame_bytes = cras_client_format_bytes_per_frame(aud_format);
- write_size = frames * frame_bytes;
-
- /* Update RMS values with all available frames. */
- if (keep_looping) {
- update_rms(captured_samples,
- MIN(write_size, duration_frames * frame_bytes));
- }
-
- check_stream_terminate(frames);
-
- ret = write(*fd, captured_samples, write_size);
- if (ret != write_size)
- printf("Error writing file\n");
- return frames;
-}
-
-/* Run from callback thread. */
-static int put_samples(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames,
- const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- uint32_t frame_bytes = cras_client_format_bytes_per_frame(aud_format);
- int fd = *(int *)user_arg;
- uint8_t buff[BUF_SIZE];
- int nread;
-
- while (pause_client)
- usleep(10000);
-
- if (pause_a_reply) {
- usleep(pause_in_playback_reply);
- pause_a_reply = 0;
- }
-
- check_stream_terminate(frames);
-
- cras_client_calc_playback_latency(playback_time, &last_latency);
-
- if (play_short_sound) {
- if (play_short_sound_periods_left)
- /* Play a period from file. */
- play_short_sound_periods_left--;
- else {
- /* Fill zeros to play silence. */
- memset(playback_samples, 0,
- MIN(frames * frame_bytes, BUF_SIZE));
- return frames;
- }
- }
-
- nread = read(fd, buff, MIN(frames * frame_bytes, BUF_SIZE));
- if (nread <= 0) {
- if (exit_after_done_playing)
- terminate_stream_loop();
- return nread;
- }
-
- memcpy(playback_samples, buff, nread);
- return nread / frame_bytes;
-}
-
-/* Run from callback thread. */
-static int
-put_stdin_samples(struct cras_client *client, cras_stream_id_t stream_id,
- uint8_t *captured_samples, uint8_t *playback_samples,
- unsigned int frames, const struct timespec *captured_time,
- const struct timespec *playback_time, void *user_arg)
-{
- int rc = 0;
- uint32_t frame_bytes = cras_client_format_bytes_per_frame(aud_format);
-
- rc = read(0, playback_samples, (size_t)frames * (size_t)frame_bytes);
- if (rc <= 0) {
- terminate_stream_loop();
- return -1;
- }
-
- return rc / frame_bytes;
-}
-
-static int stream_error(struct cras_client *client, cras_stream_id_t stream_id,
- int err, void *arg)
-{
- printf("Stream error %d\n", err);
- terminate_stream_loop();
- return 0;
-}
-
-static void print_last_latency()
-{
- if (last_latency.tv_sec > 0 || last_latency.tv_nsec > 0)
- printf("%u.%09u\n", (unsigned)last_latency.tv_sec,
- (unsigned)last_latency.tv_nsec);
- else {
- printf("-%lld.%09lld\n", (long long)-last_latency.tv_sec,
- (long long)-last_latency.tv_nsec);
- }
-}
-
-static void print_last_rms()
-{
- if (last_rms_size != 0)
- printf("%.9f\n", sqrt(last_rms_sqr_sum / last_rms_size));
-}
-
-static void print_total_rms()
-{
- if (total_rms_size != 0)
- printf("%.9f\n", sqrt(total_rms_sqr_sum / total_rms_size));
-}
-
-static void print_dev_info(const struct cras_iodev_info *devs, int num_devs)
-{
- unsigned i;
-
- printf("\tID\tMaxCha\tName\n");
- for (i = 0; i < num_devs; i++)
- printf("\t%u\t%u\t%s\n", devs[i].idx,
- devs[i].max_supported_channels, devs[i].name);
-}
-
-static void print_node_info(struct cras_client *client,
- const struct cras_ionode_info *nodes, int num_nodes,
- int is_input)
-{
- unsigned i;
-
- printf("\tStable Id\t ID\t%4s UI Plugged\tL/R swapped\t "
- "Time Hotword\tType\t\tMaxCha Name\n",
- is_input ? "Gain" : " Vol");
- for (i = 0; i < num_nodes; i++) {
- char max_channels_str[7];
- if (is_input) {
- // Print "X" as don't-care for input nodes because
- // cras_client_get_max_supported_channels() is only valid for outputs.
- strcpy(max_channels_str, " X");
- } else {
- uint32_t max_channels;
- int rc = cras_client_get_max_supported_channels(
- client,
- cras_make_node_id(nodes[i].iodev_idx,
- nodes[i].ionode_idx),
- &max_channels);
- if (rc)
- max_channels = 0;
- sprintf(max_channels_str, "%6u", max_channels);
- }
- printf("\t(%08x)\t%u:%u\t%5g %f %7s\t%14s\t%10ld %-7s\t%-16s%-6s%c%s\n",
- nodes[i].stable_id, nodes[i].iodev_idx,
- nodes[i].ionode_idx,
- is_input ? nodes[i].capture_gain / 100.0 :
- (double)nodes[i].volume,
- nodes[i].ui_gain_scaler, nodes[i].plugged ? "yes" : "no",
- nodes[i].left_right_swapped ? "yes" : "no",
- (long)nodes[i].plugged_time.tv_sec,
- nodes[i].active_hotword_model, nodes[i].type,
- max_channels_str, nodes[i].active ? '*' : ' ',
- nodes[i].name);
- }
-}
-
-static void print_device_lists(struct cras_client *client)
-{
- struct cras_iodev_info devs[MAX_IODEVS];
- struct cras_ionode_info nodes[MAX_IONODES];
- size_t num_devs, num_nodes;
- int rc;
-
- num_devs = MAX_IODEVS;
- num_nodes = MAX_IONODES;
- rc = cras_client_get_output_devices(client, devs, nodes, &num_devs,
- &num_nodes);
- if (rc < 0)
- return;
- printf("Output Devices:\n");
- print_dev_info(devs, num_devs);
- printf("Output Nodes:\n");
- print_node_info(client, nodes, num_nodes, 0);
-
- num_devs = MAX_IODEVS;
- num_nodes = MAX_IONODES;
- rc = cras_client_get_input_devices(client, devs, nodes, &num_devs,
- &num_nodes);
- printf("Input Devices:\n");
- print_dev_info(devs, num_devs);
- printf("Input Nodes:\n");
- print_node_info(client, nodes, num_nodes, 1);
-}
-
-static void print_attached_client_list(struct cras_client *client)
-{
- struct cras_attached_client_info clients[MAX_ATTACHED_CLIENTS];
- size_t i;
- int num_clients;
-
- num_clients = cras_client_get_attached_clients(client, clients,
- MAX_ATTACHED_CLIENTS);
- if (num_clients < 0)
- return;
- num_clients = MIN(num_clients, MAX_ATTACHED_CLIENTS);
- printf("Attached clients:\n");
- printf("\tID\tpid\tuid\n");
- for (i = 0; i < num_clients; i++)
- printf("\t%u\t%d\t%d\n", clients[i].id, clients[i].pid,
- clients[i].gid);
-}
-
-static void print_active_stream_info(struct cras_client *client)
-{
- struct timespec ts;
- unsigned num_streams;
-
- num_streams = cras_client_get_num_active_streams(client, &ts);
- printf("Num active streams: %u\n", num_streams);
- printf("Last audio active time: %llu, %llu\n", (long long)ts.tv_sec,
- (long long)ts.tv_nsec);
-}
-
-static void print_system_volumes(struct cras_client *client)
-{
- printf("System Volume (0-100): %zu %s\n"
- "Capture Muted : %s\n",
- cras_client_get_system_volume(client),
- cras_client_get_system_muted(client) ? "(Muted)" : "",
- cras_client_get_system_capture_muted(client) ? "Muted" :
- "Not muted");
-}
-
-static void print_user_muted(struct cras_client *client)
-{
- printf("User muted: %s\n",
- cras_client_get_user_muted(client) ? "Muted" : "Not muted");
-}
-
-/*
- * Convert time value from one clock to the other using given offset
- * in sec and nsec.
- */
-static void convert_time(unsigned int *sec, unsigned int *nsec,
- time_t sec_offset, int32_t nsec_offset)
-{
- sec_offset += *sec;
- nsec_offset += *nsec;
- if (nsec_offset >= 1000000000L) {
- sec_offset++;
- nsec_offset -= 1000000000L;
- } else if (nsec_offset < 0) {
- sec_offset--;
- nsec_offset += 1000000000L;
- }
- *sec = sec_offset;
- *nsec = nsec_offset;
-}
-
-static float get_ewma_power_as_float(uint32_t data)
-{
- float f = 0.0f;
-
- /* Convert from the uint32_t log type back to float.
- * If data cannot be assigned to float, default value will
- * be printed as -inf to hint the problem.
- */
- if (sizeof(uint32_t) == sizeof(float))
- memcpy(&f, &data, sizeof(float));
- else
- printf("%-30s float to uint32_t\n", "MEMORY_NOT_ALIGNED");
-
- /* Convert to dBFS and set to zero if it's
- * insignificantly low. Picking the same threshold
- * 1.0e-10f as in Chrome.
- */
- return (f < 1.0e-10f) ? -INFINITY : 10.0f * log10f(f);
-}
-
-static void show_alog_tag(const struct audio_thread_event_log *log,
- unsigned int tag_idx, int32_t sec_offset,
- int32_t nsec_offset)
-{
- unsigned int tag = (log->log[tag_idx].tag_sec >> 24) & 0xff;
- unsigned int sec = log->log[tag_idx].tag_sec & 0x00ffffff;
- unsigned int nsec = log->log[tag_idx].nsec;
- unsigned int data1 = log->log[tag_idx].data1;
- unsigned int data2 = log->log[tag_idx].data2;
- unsigned int data3 = log->log[tag_idx].data3;
- time_t lt;
- struct tm t;
-
- /* Skip unused log entries. */
- if (log->log[tag_idx].tag_sec == 0 && log->log[tag_idx].nsec == 0)
- return;
-
- /* Convert from monotonic raw clock to realtime clock. */
- convert_time(&sec, &nsec, sec_offset, nsec_offset);
- lt = sec;
- localtime_r(&lt, &t);
- strftime(time_str, 128, "%Y-%m-%dT%H:%M:%S", &t);
-
- printf("%s.%09u cras atlog ", time_str, nsec);
-
- /* Prepare realtime string for arguments. */
- switch (tag) {
- case AUDIO_THREAD_A2DP_FLUSH:
- case AUDIO_THREAD_READ_AUDIO_TSTAMP:
- case AUDIO_THREAD_FILL_AUDIO_TSTAMP:
- case AUDIO_THREAD_STREAM_RESCHEDULE:
- case AUDIO_THREAD_STREAM_SLEEP_TIME:
- case AUDIO_THREAD_STREAM_SLEEP_ADJUST:
- case AUDIO_THREAD_DEV_SLEEP_TIME:
- sec = data2;
- nsec = data3;
- break;
- }
- convert_time(&sec, &nsec, sec_offset, nsec_offset);
- lt = sec;
- localtime_r(&lt, &t);
- strftime(time_str, 128, " %H:%M:%S", &t);
-
- switch (tag) {
- case AUDIO_THREAD_WAKE:
- printf("%-30s num_fds:%d\n", "WAKE", (int)data1);
- break;
- case AUDIO_THREAD_SLEEP:
- printf("%-30s sleep:%09d.%09d non_empty %u\n", "SLEEP",
- (int)data1, (int)data2, (int)data3);
- break;
- case AUDIO_THREAD_READ_AUDIO:
- printf("%-30s dev:%u hw_level:%u read:%u\n", "READ_AUDIO",
- data1, data2, data3);
- break;
- case AUDIO_THREAD_READ_AUDIO_TSTAMP:
- printf("%-30s dev:%u tstamp:%s.%09u\n", "READ_AUDIO_TSTAMP",
- data1, time_str, nsec);
- break;
- case AUDIO_THREAD_READ_AUDIO_DONE: {
- float f = get_ewma_power_as_float(data2);
- printf("%-30s read_remainder:%u power:%f dBFS\n",
- "READ_AUDIO_DONE", data1, f);
- break;
- }
- case AUDIO_THREAD_READ_OVERRUN:
- printf("%-30s dev:%u stream:%x num_overruns:%u\n",
- "READ_AUDIO_OVERRUN", data1, data2, data3);
- break;
- case AUDIO_THREAD_FILL_AUDIO:
- printf("%-30s dev:%u hw_level:%u min_cb_level:%u\n",
- "FILL_AUDIO", data1, data2, data3);
- break;
- case AUDIO_THREAD_FILL_AUDIO_TSTAMP:
- printf("%-30s dev:%u tstamp:%s.%09u\n", "FILL_AUDIO_TSTAMP",
- data1, time_str, nsec);
- break;
- case AUDIO_THREAD_FILL_AUDIO_DONE: {
- float f = get_ewma_power_as_float(data3);
- printf("%-30s hw_level:%u total_written:%u power:%f dBFS\n",
- "FILL_AUDIO_DONE", data1, data2, f);
- break;
- }
- case AUDIO_THREAD_WRITE_STREAMS_WAIT:
- printf("%-30s stream:%x\n", "WRITE_STREAMS_WAIT", data1);
- break;
- case AUDIO_THREAD_WRITE_STREAMS_WAIT_TO:
- printf("%-30s\n", "WRITE_STREAMS_WAIT_TO");
- break;
- case AUDIO_THREAD_WRITE_STREAMS_MIX:
- printf("%-30s write_limit:%u max_offset:%u\n",
- "WRITE_STREAMS_MIX", data1, data2);
- break;
- case AUDIO_THREAD_WRITE_STREAMS_MIXED:
- printf("%-30s write_limit:%u\n", "WRITE_STREAMS_MIXED", data1);
- break;
- case AUDIO_THREAD_WRITE_STREAMS_STREAM:
- printf("%-30s id:%x shm_frames:%u cb_pending:%u\n",
- "WRITE_STREAMS_STREAM", data1, data2, data3);
- break;
- case AUDIO_THREAD_FETCH_STREAM: {
- float f = get_ewma_power_as_float(data3);
- printf("%-30s id:%x cbth:%u power:%f dBFS\n",
- "WRITE_STREAMS_FETCH_STREAM", data1, data2, f);
- break;
- }
- case AUDIO_THREAD_STREAM_ADDED:
- printf("%-30s id:%x dev:%u\n", "STREAM_ADDED", data1, data2);
- break;
- case AUDIO_THREAD_STREAM_REMOVED:
- printf("%-30s id:%x\n", "STREAM_REMOVED", data1);
- break;
- break;
- case AUDIO_THREAD_A2DP_FLUSH:
- printf("%-30s state %u next flush time:%s.%09u\n", "A2DP_FLUSH",
- data1, time_str, nsec);
- break;
- case AUDIO_THREAD_A2DP_THROTTLE_TIME:
- printf("%-30s %u ms, queued:%u\n", "A2DP_THROTTLE_TIME",
- data1 * 1000 + data2 / 1000000, data3);
- break;
- case AUDIO_THREAD_A2DP_WRITE:
- printf("%-30s written:%d queued:%u\n", "A2DP_WRITE", data1,
- data2);
- break;
- case AUDIO_THREAD_DEV_STREAM_MIX:
- printf("%-30s written:%u read:%u\n", "DEV_STREAM_MIX", data1,
- data2);
- break;
- case AUDIO_THREAD_CAPTURE_POST:
- printf("%-30s stream:%x thresh:%u rd_buf:%u\n", "CAPTURE_POST",
- data1, data2, data3);
- break;
- case AUDIO_THREAD_CAPTURE_WRITE:
- printf("%-30s stream:%x write:%u shm_fr:%u\n", "CAPTURE_WRITE",
- data1, data2, data3);
- break;
- case AUDIO_THREAD_CONV_COPY:
- printf("%-30s wr_buf:%u shm_writable:%u offset:%u\n",
- "CONV_COPY", data1, data2, data3);
- break;
- case AUDIO_THREAD_STREAM_FETCH_PENDING:
- printf("%-30s id:%x\n", "STREAM_FETCH_PENGING", data1);
- break;
- case AUDIO_THREAD_STREAM_RESCHEDULE:
- printf("%-30s id:%x next_cb_ts:%s.%09u\n", "STREAM_RESCHEDULE",
- data1, time_str, nsec);
- break;
- case AUDIO_THREAD_STREAM_SLEEP_TIME:
- printf("%-30s id:%x wake:%s.%09u\n", "STREAM_SLEEP_TIME", data1,
- time_str, nsec);
- break;
- case AUDIO_THREAD_STREAM_SLEEP_ADJUST:
- printf("%-30s id:%x from:%s.%09u\n", "STREAM_SLEEP_ADJUST",
- data1, time_str, nsec);
- break;
- case AUDIO_THREAD_STREAM_SKIP_CB:
- printf("%-30s id:%x write_offset_0:%u write_offset_1:%u\n",
- "STREAM_SKIP_CB", data1, data2, data3);
- break;
- case AUDIO_THREAD_DEV_SLEEP_TIME:
- printf("%-30s dev:%u wake:%s.%09u\n", "DEV_SLEEP_TIME", data1,
- time_str, nsec);
- break;
- case AUDIO_THREAD_SET_DEV_WAKE:
- printf("%-30s dev:%u hw_level:%u sleep:%u\n", "SET_DEV_WAKE",
- data1, data2, data3);
- break;
- case AUDIO_THREAD_DEV_ADDED:
- printf("%-30s dev:%u\n", "DEV_ADDED", data1);
- break;
- case AUDIO_THREAD_DEV_REMOVED:
- printf("%-30s dev:%u\n", "DEV_REMOVED", data1);
- break;
- case AUDIO_THREAD_IODEV_CB:
- printf("%-30s revents:%u events:%u\n", "IODEV_CB", data1,
- data2);
- break;
- case AUDIO_THREAD_PB_MSG:
- printf("%-30s msg_id:%u\n", "PB_MSG", data1);
- break;
- case AUDIO_THREAD_ODEV_NO_STREAMS:
- printf("%-30s dev:%u\n", "ODEV_NO_STREAMS", data1);
- break;
- case AUDIO_THREAD_ODEV_LEAVE_NO_STREAMS:
- printf("%-30s dev:%u\n", "ODEV_LEAVE_NO_STREAMS", data1);
- break;
- case AUDIO_THREAD_ODEV_START:
- printf("%-30s dev:%u min_cb_level:%u\n", "ODEV_START", data1,
- data2);
- break;
- case AUDIO_THREAD_FILL_ODEV_ZEROS:
- printf("%-30s dev:%u write:%u\n", "FILL_ODEV_ZEROS", data1,
- data2);
- break;
- case AUDIO_THREAD_ODEV_DEFAULT_NO_STREAMS:
- printf("%-30s dev:%u hw_level:%u target:%u\n",
- "DEFAULT_NO_STREAMS", data1, data2, data3);
- break;
- case AUDIO_THREAD_UNDERRUN:
- printf("%-30s dev:%u hw_level:%u total_written:%u\n",
- "UNDERRUN", data1, data2, data3);
- break;
- case AUDIO_THREAD_SEVERE_UNDERRUN:
- printf("%-30s dev:%u\n", "SEVERE_UNDERRUN", data1);
- break;
- case AUDIO_THREAD_CAPTURE_DROP_TIME:
- printf("%-30s time:%09u.%09d\n", "CAPTURE_DROP_TIME", data1,
- data2);
- break;
- case AUDIO_THREAD_DEV_DROP_FRAMES:
- printf("%-30s dev:%u frames:%u\n", "DEV_DROP_FRAMES", data1,
- data2);
- break;
- case AUDIO_THREAD_LOOPBACK_PUT:
- printf("%-30s nframes_committed:%u\n", "LOOPBACK_PUT", data1);
- break;
- case AUDIO_THREAD_LOOPBACK_GET:
- printf("%-30s nframes_requested:%u avail:%u\n", "LOOPBACK_GET",
- data1, data2);
- break;
- case AUDIO_THREAD_LOOPBACK_SAMPLE_HOOK:
- printf("%-30s frames_to_copy:%u frames_copied:%u\n",
- "LOOPBACK_SAMPLE", data1, data2);
- break;
- case AUDIO_THREAD_DEV_OVERRUN:
- printf("%-30s dev:%u hw_level:%u\n", "DEV_OVERRUN", data1,
- data2);
- break;
- default:
- printf("%-30s tag:%u\n", "UNKNOWN", tag);
- break;
- }
-}
-
-static void print_audio_debug_info(const struct audio_debug_info *info)
-{
- time_t sec_offset;
- int32_t nsec_offset;
- int i, j;
-
- printf("Audio Debug Stats:\n");
- printf("-------------devices------------\n");
- if (info->num_devs > MAX_DEBUG_DEVS)
- return;
-
- for (i = 0; i < info->num_devs; i++) {
- printf("%s dev: %s\n",
- (info->devs[i].direction == CRAS_STREAM_INPUT) ?
- "Input" :
- "Output",
- info->devs[i].dev_name);
- printf("buffer_size: %u\n"
- "min_buffer_level: %u\n"
- "min_cb_level: %u\n"
- "max_cb_level: %u\n"
- "frame_rate: %u\n"
- "num_channels: %u\n"
- "est_rate_ratio: %lf\n"
- "num_underruns: %u\n"
- "num_severe_underruns: %u\n"
- "highest_hw_level: %u\n"
- "runtime: %u.%09u\n"
- "longest_wake: %u.%09u\n"
- "software_gain_scaler: %lf\n",
- (unsigned int)info->devs[i].buffer_size,
- (unsigned int)info->devs[i].min_buffer_level,
- (unsigned int)info->devs[i].min_cb_level,
- (unsigned int)info->devs[i].max_cb_level,
- (unsigned int)info->devs[i].frame_rate,
- (unsigned int)info->devs[i].num_channels,
- info->devs[i].est_rate_ratio,
- (unsigned int)info->devs[i].num_underruns,
- (unsigned int)info->devs[i].num_severe_underruns,
- (unsigned int)info->devs[i].highest_hw_level,
- (unsigned int)info->devs[i].runtime_sec,
- (unsigned int)info->devs[i].runtime_nsec,
- (unsigned int)info->devs[i].longest_wake_sec,
- (unsigned int)info->devs[i].longest_wake_nsec,
- info->devs[i].software_gain_scaler);
- printf("\n");
- }
-
- printf("-------------stream_dump------------\n");
- if (info->num_streams > MAX_DEBUG_STREAMS)
- return;
-
- for (i = 0; i < info->num_streams; i++) {
- int channel;
- printf("stream: 0x%" PRIx64 " dev: %u\n",
- info->streams[i].stream_id,
- (unsigned int)info->streams[i].dev_idx);
- printf("direction: %s\n",
- (info->streams[i].direction == CRAS_STREAM_INPUT) ?
- "Input" :
- "Output");
- printf("stream_type: %s\n",
- cras_stream_type_str(info->streams[i].stream_type));
- printf("client_type: %s\n",
- cras_client_type_str(info->streams[i].client_type));
- printf("buffer_frames: %u\n"
- "cb_threshold: %u\n"
- "effects: 0x%.4x\n"
- "frame_rate: %u\n"
- "num_channels: %u\n"
- "longest_fetch_sec: %u.%09u\n"
- "num_overruns: %u\n"
- "is_pinned: %x\n"
- "pinned_dev_idx: %x\n"
- "num_missed_cb: %u\n"
- "%s: %lf\n"
- "runtime: %u.%09u\n",
- (unsigned int)info->streams[i].buffer_frames,
- (unsigned int)info->streams[i].cb_threshold,
- (unsigned int)info->streams[i].effects,
- (unsigned int)info->streams[i].frame_rate,
- (unsigned int)info->streams[i].num_channels,
- (unsigned int)info->streams[i].longest_fetch_sec,
- (unsigned int)info->streams[i].longest_fetch_nsec,
- (unsigned int)info->streams[i].num_overruns,
- (unsigned int)info->streams[i].is_pinned,
- (unsigned int)info->streams[i].pinned_dev_idx,
- (unsigned int)info->streams[i].num_missed_cb,
- (info->streams[i].direction == CRAS_STREAM_INPUT) ?
- "gain" :
- "volume",
- info->streams[i].stream_volume,
- (unsigned int)info->streams[i].runtime_sec,
- (unsigned int)info->streams[i].runtime_nsec);
- printf("channel map:");
- for (channel = 0; channel < CRAS_CH_MAX; channel++)
- printf("%d ", info->streams[i].channel_layout[channel]);
- printf("\n\n");
- }
-
- printf("Audio Thread Event Log:\n");
-
- fill_time_offset(&sec_offset, &nsec_offset);
- j = info->log.write_pos % info->log.len;
- i = 0;
- printf("start at %d\n", j);
- for (; i < info->log.len; i++) {
- show_alog_tag(&info->log, j, sec_offset, nsec_offset);
- j++;
- j %= info->log.len;
- }
-}
-
-static void audio_debug_info(struct cras_client *client)
-{
- const struct audio_debug_info *info;
- info = cras_client_get_audio_debug_info(client);
- if (!info)
- return;
- print_audio_debug_info(info);
-
- /* Signal main thread we are done after the last chunk. */
- pthread_mutex_lock(&done_mutex);
- pthread_cond_signal(&done_cond);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void show_mainlog_tag(const struct main_thread_event_log *log,
- unsigned int tag_idx, int32_t sec_offset,
- int32_t nsec_offset)
-{
- unsigned int tag = (log->log[tag_idx].tag_sec >> 24) & 0xff;
- unsigned int sec = log->log[tag_idx].tag_sec & 0x00ffffff;
- unsigned int nsec = log->log[tag_idx].nsec;
- unsigned int data1 = log->log[tag_idx].data1;
- unsigned int data2 = log->log[tag_idx].data2;
- unsigned int data3 = log->log[tag_idx].data3;
- time_t lt;
- struct tm t;
-
- /* Skip unused log entries. */
- if (log->log[tag_idx].tag_sec == 0 && log->log[tag_idx].nsec == 0)
- return;
-
- /* Convert from monotomic raw clock to realtime clock. */
- convert_time(&sec, &nsec, sec_offset, nsec_offset);
- lt = sec;
- localtime_r(&lt, &t);
- strftime(time_str, 128, "%Y-%m-%dT%H:%M:%S", &t);
-
- printf("%s.%09u cras mainlog ", time_str, nsec);
-
- switch (tag) {
- case MAIN_THREAD_DEV_CLOSE:
- printf("%-30s dev %u\n", "DEV_CLOSE", data1);
- break;
- case MAIN_THREAD_DEV_DISABLE:
- printf("%-30s dev %u force %u\n", "DEV_DISABLE", data1, data2);
- break;
- case MAIN_THREAD_DEV_INIT:
- printf("%-30s dev %u ch %u rate %u\n", "DEV_INIT", data1, data2,
- data3);
- break;
- case MAIN_THREAD_DEV_REOPEN:
- printf("%-30s new ch %u old ch %u rate %u\n", "DEV_REOPEN",
- data1, data2, data3);
- break;
- case MAIN_THREAD_ADD_ACTIVE_NODE:
- printf("%-30s dev %u\n", "ADD_ACTIVE_NODE", data1);
- break;
- case MAIN_THREAD_SELECT_NODE:
- printf("%-30s dev %u\n", "SELECT_NODE", data1);
- break;
- case MAIN_THREAD_ADD_TO_DEV_LIST:
- printf("%-30s dev %u %s\n", "ADD_TO_DEV_LIST", data1,
- (data2 == CRAS_STREAM_OUTPUT) ? "output" : "input");
- break;
- case MAIN_THREAD_NODE_PLUGGED:
- printf("%-30s dev %u %s\n", "NODE_PLUGGED", data1,
- data2 ? "plugged" : "unplugged");
- break;
- case MAIN_THREAD_INPUT_NODE_GAIN:
- printf("%-30s dev %u gain %u\n", "INPUT_NODE_GAIN", data1,
- data2);
- break;
- case MAIN_THREAD_OUTPUT_NODE_VOLUME:
- printf("%-30s dev %u volume %u\n", "OUTPUT_NODE_VOLUME", data1,
- data2);
- break;
- case MAIN_THREAD_SET_OUTPUT_USER_MUTE:
- printf("%-30s mute %u\n", "SET_OUTPUT_USER_MUTE", data1);
- break;
- case MAIN_THREAD_RESUME_DEVS:
- printf("RESUME_DEVS\n");
- break;
- case MAIN_THREAD_SUSPEND_DEVS:
- printf("SUSPEND_DEVS\n");
- break;
- case MAIN_THREAD_STREAM_ADDED:
- printf("%-30s %s stream 0x%x buffer frames %u\n",
- "STREAM_ADDED",
- (data2 == CRAS_STREAM_OUTPUT ? "output" : "input"),
- data1, data3);
- break;
- case MAIN_THREAD_STREAM_REMOVED:
- printf("%-30s stream 0x%x\n", "STREAM_REMOVED", data1);
- break;
- default:
- printf("%-30s\n", "UNKNOWN");
- break;
- }
-}
-
-static void show_btlog_tag(const struct cras_bt_event_log *log,
- unsigned int tag_idx, int32_t sec_offset,
- int32_t nsec_offset)
-{
- unsigned int tag = (log->log[tag_idx].tag_sec >> 24) & 0xff;
- unsigned int sec = log->log[tag_idx].tag_sec & 0x00ffffff;
- unsigned int nsec = log->log[tag_idx].nsec;
- unsigned int data1 = log->log[tag_idx].data1;
- unsigned int data2 = log->log[tag_idx].data2;
- time_t lt;
- struct tm t;
-
- /* Skip unused log entries. */
- if (log->log[tag_idx].tag_sec == 0 && log->log[tag_idx].nsec == 0)
- return;
-
- /* Convert from monotonic raw clock to realtime clock. */
- convert_time(&sec, &nsec, sec_offset, nsec_offset);
- lt = sec;
- localtime_r(&lt, &t);
- strftime(time_str, 128, "%Y-%m-%dT%H:%M:%S", &t);
-
- printf("%s.%09u cras btlog ", time_str, nsec);
-
- switch (tag) {
- case BT_ADAPTER_ADDED:
- printf("%-30s\n", "ADAPTER_ADDED");
- break;
- case BT_ADAPTER_REMOVED:
- printf("%-30s\n", "ADAPTER_REMOVED");
- break;
- case BT_A2DP_CONFIGURED:
- printf("%-30s connected profiles 0x%.2x\n", "A2DP_CONFIGURED",
- data1);
- break;
- case BT_A2DP_START:
- printf("%-30s\n", "A2DP_START");
- break;
- case BT_A2DP_SUSPENDED:
- printf("%-30s\n", "A2DP_SUSPENDED");
- break;
- case BT_AUDIO_GATEWAY_INIT:
- printf("%-30s supported profiles 0x%.2x\n",
- "AUDIO_GATEWAY_INIT", data1);
- break;
- case BT_AUDIO_GATEWAY_START:
- printf("%-30s \n", "AUDIO_GATEWAY_START");
- break;
- case BT_AVAILABLE_CODECS:
- printf("%-30s codec #%u id %u\n", "AVAILABLE_CODECS", data1,
- data2);
- break;
- case BT_CODEC_SELECTION:
- printf("%-30s dir %u codec id %u\n", "CODEC_SELECTION", data1,
- data2);
- break;
- case BT_DEV_CONNECTED:
- printf("%-30s supported profiles 0x%.2x stable_id 0x%08x\n",
- "DEV_CONNECTED", data1, data2);
- break;
- case BT_DEV_DISCONNECTED:
- printf("%-30s supported profiles 0x%.2x stable_id 0x%08x\n",
- "DEV_DISCONNECTED", data1, data2);
- break;
- case BT_DEV_CONN_WATCH_CB:
- printf("%-30s %u retries left, supported profiles 0x%.2x\n",
- "DEV_CONN_WATCH_CB", data1, data2);
- break;
- case BT_DEV_SUSPEND_CB:
- printf("%-30s profiles supported %u, reason %u\n",
- "DEV_SUSPEND_CB", data1, data2);
- break;
- case BT_HFP_HF_INDICATOR:
- printf("%-30s HF read AG %s indicator\n", "HFP_HF_INDICATOR",
- data1 ? "enabled" : "supported");
- break;
- case BT_HFP_SET_SPEAKER_GAIN:
- printf("%-30s HF set speaker gain %u\n", "HFP_SET_SPEAKER_GAIN",
- data1);
- break;
- case BT_HFP_UPDATE_SPEAKER_GAIN:
- printf("%-30s HF update speaker gain %u\n",
- "HFP_UPDATE_SPEAKER_GAIN", data1);
- break;
- case BT_HFP_NEW_CONNECTION:
- printf("%-30s\n", "HFP_NEW_CONNECTION");
- break;
- case BT_HFP_REQUEST_DISCONNECT:
- printf("%-30s\n", "HFP_REQUEST_DISCONNECT");
- break;
- case BT_HFP_SUPPORTED_FEATURES:
- printf("%-30s role %s features 0x%.4x\n",
- "HFP_SUPPORTED_FEATURES", data1 ? "AG" : "HF", data2);
- break;
- case BT_HSP_NEW_CONNECTION:
- printf("%-30s\n", "HSP_NEW_CONNECTION");
- break;
- case BT_HSP_REQUEST_DISCONNECT:
- printf("%-30s\n", "HSP_REQUEST_DISCONNECT");
- break;
- case BT_NEW_AUDIO_PROFILE_AFTER_CONNECT:
- printf("%-30s old 0x%.2x, new 0x%.2x\n",
- "NEW_AUDIO_PROFILE_AFTER_CONNECT", data1, data2);
- break;
- case BT_RESET:
- printf("%-30s\n", "RESET");
- break;
- case BT_SCO_CONNECT:
- printf("%-30s %s sk %d\n", "SCO_CONNECT",
- data1 ? "success" : "failed", (int)data2);
- break;
- case BT_TRANSPORT_ACQUIRE:
- printf("%-30s %s fd %d\n", "TRANSPORT_ACQUIRE",
- data1 ? "success" : "failed", (int)data2);
- break;
- case BT_TRANSPORT_RELEASE:
- printf("%-30s\n", "TRANSPORT_RELEASE");
- break;
- case BT_TRANSPORT_SET_VOLUME:
- printf("%-30s %d\n", "TRANSPORT_SET_VOLUME", data1);
- break;
- case BT_TRANSPORT_UPDATE_VOLUME:
- printf("%-30s %d\n", "TRANSPORT_UPDATE_VOLUME", data1);
- break;
- default:
- printf("%-30s\n", "UNKNOWN");
- break;
- }
-}
-
-static void convert_to_time_str(const struct timespec *ts, time_t sec_offset,
- int32_t nsec_offset)
-{
- time_t lt = ts->tv_sec;
- struct tm t;
- unsigned int time_nsec;
-
- /* Assuming tv_nsec doesn't exceed 10^9 */
- time_nsec = ts->tv_nsec;
- convert_time((unsigned int *)&lt, &time_nsec, sec_offset, nsec_offset);
- localtime_r(&lt, &t);
- strftime(time_str, 128, "%Y-%m-%dT%H:%M:%S", &t);
- snprintf(time_str + strlen(time_str), 128 - strlen(time_str), ".%09u",
- time_nsec);
-}
-
-static void cras_bt_debug_info(struct cras_client *client)
-{
- const struct cras_bt_debug_info *info;
- time_t sec_offset;
- int32_t nsec_offset;
- int i, j;
- struct timespec ts;
- struct packet_status_logger wbs_logger;
-
- info = cras_client_get_bt_debug_info(client);
- fill_time_offset(&sec_offset, &nsec_offset);
- j = info->bt_log.write_pos;
- i = 0;
- printf("BT debug log:\n");
- for (; i < info->bt_log.len; i++) {
- show_btlog_tag(&info->bt_log, j, sec_offset, nsec_offset);
- j++;
- j %= info->bt_log.len;
- }
-
- printf("-------------WBS packet loss------------\n");
- wbs_logger = info->wbs_logger;
-
- packet_status_logger_begin_ts(&wbs_logger, &ts);
- convert_to_time_str(&ts, sec_offset, nsec_offset);
- printf("%s [begin]\n", time_str);
-
- packet_status_logger_end_ts(&wbs_logger, &ts);
- convert_to_time_str(&ts, sec_offset, nsec_offset);
- printf("%s [end]\n", time_str);
-
- printf("In hex format:\n");
- packet_status_logger_dump_hex(&wbs_logger);
-
- printf("In binary format:\n");
- packet_status_logger_dump_binary(&wbs_logger);
-
- /* Signal main thread we are done after the last chunk. */
- pthread_mutex_lock(&done_mutex);
- pthread_cond_signal(&done_cond);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void main_thread_debug_info(struct cras_client *client)
-{
- const struct main_thread_debug_info *info;
- time_t sec_offset;
- int32_t nsec_offset;
- int i, j;
-
- info = cras_client_get_main_thread_debug_info(client);
- fill_time_offset(&sec_offset, &nsec_offset);
- j = info->main_log.write_pos;
- i = 0;
- printf("Main debug log:\n");
- for (; i < info->main_log.len; i++) {
- show_mainlog_tag(&info->main_log, j, sec_offset, nsec_offset);
- j++;
- j %= info->main_log.len;
- }
-
- /* Signal main thread we are done after the last chunk. */
- pthread_mutex_lock(&done_mutex);
- pthread_cond_signal(&done_cond);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void print_cras_audio_thread_snapshot(
- const struct cras_audio_thread_snapshot *snapshot)
-{
- printf("-------------snapshot------------\n");
- printf("Event time: %" PRId64 ".%ld\n",
- (int64_t)snapshot->timestamp.tv_sec,
- snapshot->timestamp.tv_nsec);
-
- printf("Event type: ");
- switch (snapshot->event_type) {
- case AUDIO_THREAD_EVENT_A2DP_THROTTLE:
- printf("a2dp throttle\n");
- break;
- case AUDIO_THREAD_EVENT_BUSYLOOP:
- printf("busyloop\n");
- break;
- case AUDIO_THREAD_EVENT_UNDERRUN:
- printf("underrun\n");
- break;
- case AUDIO_THREAD_EVENT_SEVERE_UNDERRUN:
- printf("severe underrun\n");
- break;
- case AUDIO_THREAD_EVENT_DROP_SAMPLES:
- printf("drop samples\n");
- break;
- case AUDIO_THREAD_EVENT_DEV_OVERRUN:
- printf("device overrun\n");
- break;
- case AUDIO_THREAD_EVENT_DEBUG:
- printf("debug\n");
- break;
- default:
- printf("no such type\n");
- }
- print_audio_debug_info(&snapshot->audio_debug_info);
-}
-
-static void audio_thread_snapshots(struct cras_client *client)
-{
- const struct cras_audio_thread_snapshot_buffer *snapshot_buffer;
- uint32_t i;
- int j;
- int count = 0;
-
- snapshot_buffer = cras_client_get_audio_thread_snapshot_buffer(client);
- i = snapshot_buffer->pos;
- for (j = 0; j < CRAS_MAX_AUDIO_THREAD_SNAPSHOTS; j++) {
- if (snapshot_buffer->snapshots[i].timestamp.tv_sec ||
- snapshot_buffer->snapshots[i].timestamp.tv_nsec) {
- print_cras_audio_thread_snapshot(
- &snapshot_buffer->snapshots[i]);
- count++;
- }
- i++;
- i %= CRAS_MAX_AUDIO_THREAD_SNAPSHOTS;
- }
- printf("There are %d, snapshots.\n", count);
-
- /* Signal main thread we are done after the last chunk. */
- pthread_mutex_lock(&done_mutex);
- pthread_cond_signal(&done_cond);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static int start_stream(struct cras_client *client, cras_stream_id_t *stream_id,
- struct cras_stream_params *params, float stream_volume)
-{
- int rc;
-
- if (pin_device_id)
- rc = cras_client_add_pinned_stream(client, pin_device_id,
- stream_id, params);
- else
- rc = cras_client_add_stream(client, stream_id, params);
- if (rc < 0) {
- fprintf(stderr, "adding a stream %d\n", rc);
- return rc;
- }
- return cras_client_set_stream_volume(client, *stream_id, stream_volume);
-}
-
-static int parse_channel_layout(char *channel_layout_str,
- int8_t channel_layout[CRAS_CH_MAX])
-{
- int i = 0;
- char *chp;
-
- chp = strtok(channel_layout_str, ",");
- while (chp && i < CRAS_CH_MAX) {
- channel_layout[i++] = atoi(chp);
- chp = strtok(NULL, ",");
- }
-
- return 0;
-}
-
-static void run_aecdump(struct cras_client *client, uint64_t stream_id,
- int start)
-{
- int aecdump_fd;
- if (start) {
- aecdump_fd =
- open(aecdump_file, O_CREAT | O_RDWR | O_TRUNC, 0666);
- if (aecdump_fd == -1) {
- printf("Fail to open file %s", aecdump_file);
- return;
- }
-
- printf("Dumping AEC info to %s, stream %" PRId64 ", fd %d\n",
- aecdump_file, stream_id, aecdump_fd);
- cras_client_set_aec_dump(client, stream_id, 1, aecdump_fd);
- } else {
- cras_client_set_aec_dump(client, stream_id, 0, -1);
- printf("Close AEC dump file %s\n", aecdump_file);
- }
-}
-
-static int run_file_io_stream(struct cras_client *client, int fd,
- enum CRAS_STREAM_DIRECTION direction,
- size_t block_size,
- enum CRAS_STREAM_TYPE stream_type, size_t rate,
- snd_pcm_format_t format, size_t num_channels,
- uint32_t flags, int is_loopback, int is_post_dsp)
-{
- int rc, tty;
- struct cras_stream_params *params;
- cras_unified_cb_t aud_cb;
- cras_stream_id_t stream_id = 0;
- int stream_playing = 0;
- int *pfd = malloc(sizeof(*pfd));
- *pfd = fd;
- fd_set poll_set;
- struct timespec sleep_ts;
- float volume_scaler = 1.0;
- size_t sys_volume = 100;
- int mute = 0;
- int8_t layout[CRAS_CH_MAX];
-
- /* Set the sleep interval between latency/RMS prints. */
- sleep_ts.tv_sec = 1;
- sleep_ts.tv_nsec = 0;
-
- /* Open the pipe file descriptor. */
- rc = pipe(pipefd);
- if (rc == -1) {
- perror("failed to open pipe");
- return -errno;
- }
-
- /* Reset the total RMS value. */
- total_rms_sqr_sum = 0;
- total_rms_size = 0;
-
- if (direction == CRAS_STREAM_INPUT)
- aud_cb = got_samples;
- else
- aud_cb = put_samples;
-
- if (fd == 0) {
- if (direction != CRAS_STREAM_OUTPUT)
- return -EINVAL;
- aud_cb = put_stdin_samples;
- }
-
- aud_format = cras_audio_format_create(format, rate, num_channels);
- if (aud_format == NULL)
- return -ENOMEM;
-
- if (channel_layout) {
- /* Set channel layout to format */
- parse_channel_layout(channel_layout, layout);
- cras_audio_format_set_channel_layout(aud_format, layout);
- }
-
- params = cras_client_unified_params_create(direction, block_size,
- stream_type, flags, pfd,
- aud_cb, stream_error,
- aud_format);
- if (params == NULL)
- return -ENOMEM;
-
- cras_client_stream_params_set_client_type(params,
- CRAS_CLIENT_TYPE_TEST);
-
- if (effect_aec)
- cras_client_stream_params_enable_aec(params);
- if (effect_ns)
- cras_client_stream_params_enable_ns(params);
- if (effect_agc)
- cras_client_stream_params_enable_agc(params);
- if (effect_vad)
- cras_client_stream_params_enable_vad(params);
-
- cras_client_run_thread(client);
- if (is_loopback) {
- enum CRAS_NODE_TYPE type =
- (is_post_dsp ? CRAS_NODE_TYPE_POST_DSP :
- CRAS_NODE_TYPE_POST_MIX_PRE_DSP);
-
- cras_client_connected_wait(client);
- pin_device_id = cras_client_get_first_dev_type_idx(
- client, type, CRAS_STREAM_INPUT);
- }
-
- stream_playing =
- start_stream(client, &stream_id, params, volume_scaler) == 0;
-
- tty = open("/dev/tty", O_RDONLY);
-
- // There could be no terminal available when run in autotest.
- if (tty == -1)
- perror("warning: failed to open /dev/tty");
-
- while (keep_looping) {
- char input;
- int nread;
-
- FD_ZERO(&poll_set);
- if (tty >= 0)
- FD_SET(tty, &poll_set);
- FD_SET(pipefd[0], &poll_set);
- pselect(MAX(tty, pipefd[0]) + 1, &poll_set, NULL, NULL,
- show_latency || show_rms ? &sleep_ts : NULL, NULL);
-
- if (stream_playing && show_latency)
- print_last_latency();
-
- if (stream_playing && show_rms)
- print_last_rms();
-
- if (tty < 0 || !FD_ISSET(tty, &poll_set))
- continue;
-
- nread = read(tty, &input, 1);
- if (nread < 1) {
- fprintf(stderr, "Error reading stdin\n");
- return nread;
- }
- switch (input) {
- case 'p':
- pause_client = !pause_client;
- break;
- case 'i':
- pause_a_reply = 1;
- break;
- case 'q':
- terminate_stream_loop();
- break;
- case 's':
- if (stream_playing)
- break;
-
- /* If started by hand keep running after it finishes. */
- exit_after_done_playing = 0;
-
- stream_playing =
- start_stream(client, &stream_id, params,
- volume_scaler) == 0;
- break;
- case 'r':
- if (!stream_playing)
- break;
- cras_client_rm_stream(client, stream_id);
- stream_playing = 0;
- break;
- case 'u':
- volume_scaler = MIN(volume_scaler + 0.1, 1.0);
- cras_client_set_stream_volume(client, stream_id,
- volume_scaler);
- break;
- case 'd':
- volume_scaler = MAX(volume_scaler - 0.1, 0.0);
- cras_client_set_stream_volume(client, stream_id,
- volume_scaler);
- break;
- case 'k':
- sys_volume = MIN(sys_volume + 1, 100);
- cras_client_set_system_volume(client, sys_volume);
- break;
- case 'j':
- sys_volume = sys_volume == 0 ? 0 : sys_volume - 1;
- cras_client_set_system_volume(client, sys_volume);
- break;
- case 'm':
- mute = !mute;
- cras_client_set_system_mute(client, mute);
- break;
- case '@':
- print_device_lists(client);
- break;
- case '#':
- print_attached_client_list(client);
- break;
- case 'v':
- printf("Volume: %zu%s Min dB: %ld Max dB: %ld\n"
- "Capture: %s\n",
- cras_client_get_system_volume(client),
- cras_client_get_system_muted(client) ?
- "(Muted)" :
- "",
- cras_client_get_system_min_volume(client),
- cras_client_get_system_max_volume(client),
- cras_client_get_system_capture_muted(client) ?
- "Muted" :
- "Not muted");
- break;
- case '\'':
- play_short_sound_periods_left =
- play_short_sound_periods;
- break;
- case '\n':
- break;
- default:
- printf("Invalid key\n");
- break;
- }
- }
-
- if (show_total_rms)
- print_total_rms();
-
- cras_client_stop(client);
-
- cras_audio_format_destroy(aud_format);
- cras_client_stream_params_destroy(params);
- free(pfd);
-
- close(pipefd[0]);
- close(pipefd[1]);
-
- return 0;
-}
-
-static int run_capture(struct cras_client *client, const char *file,
- size_t block_size, enum CRAS_STREAM_TYPE stream_type,
- size_t rate, snd_pcm_format_t format,
- size_t num_channels, uint32_t flags, int is_loopback,
- int is_post_dsp)
-{
- int fd = open(file, O_CREAT | O_RDWR | O_TRUNC, 0666);
- if (fd == -1) {
- perror("failed to open file");
- return -errno;
- }
-
- run_file_io_stream(client, fd, CRAS_STREAM_INPUT, block_size,
- stream_type, rate, format, num_channels, flags,
- is_loopback, is_post_dsp);
-
- close(fd);
- return 0;
-}
-
-static int run_playback(struct cras_client *client, const char *file,
- size_t block_size, enum CRAS_STREAM_TYPE stream_type,
- size_t rate, snd_pcm_format_t format,
- size_t num_channels)
-{
- int fd;
-
- fd = open(file, O_RDONLY);
- if (fd == -1) {
- perror("failed to open file");
- return -errno;
- }
-
- run_file_io_stream(client, fd, CRAS_STREAM_OUTPUT, block_size,
- stream_type, rate, format, num_channels, 0, 0, 0);
-
- close(fd);
- return 0;
-}
-
-static void print_server_info(struct cras_client *client)
-{
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- print_system_volumes(client);
- print_user_muted(client);
- print_device_lists(client);
- print_attached_client_list(client);
- print_active_stream_info(client);
-}
-
-static void show_audio_thread_snapshots(struct cras_client *client)
-{
- struct timespec wait_time;
-
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- cras_client_update_audio_thread_snapshots(client,
- audio_thread_snapshots);
-
- clock_gettime(CLOCK_REALTIME, &wait_time);
- wait_time.tv_sec += 2;
-
- pthread_mutex_lock(&done_mutex);
- pthread_cond_timedwait(&done_cond, &done_mutex, &wait_time);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void show_audio_debug_info(struct cras_client *client)
-{
- struct timespec wait_time;
-
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- cras_client_update_audio_debug_info(client, audio_debug_info);
-
- clock_gettime(CLOCK_REALTIME, &wait_time);
- wait_time.tv_sec += 2;
-
- pthread_mutex_lock(&done_mutex);
- pthread_cond_timedwait(&done_cond, &done_mutex, &wait_time);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void show_cras_bt_debug_info(struct cras_client *client)
-{
- struct timespec wait_time;
-
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- cras_client_update_bt_debug_info(client, cras_bt_debug_info);
-
- clock_gettime(CLOCK_REALTIME, &wait_time);
- wait_time.tv_sec += 2;
-
- pthread_mutex_lock(&done_mutex);
- pthread_cond_timedwait(&done_cond, &done_mutex, &wait_time);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void show_main_thread_debug_info(struct cras_client *client)
-{
- struct timespec wait_time;
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- cras_client_update_main_thread_debug_info(client,
- main_thread_debug_info);
-
- clock_gettime(CLOCK_REALTIME, &wait_time);
- wait_time.tv_sec += 2;
-
- pthread_mutex_lock(&done_mutex);
- pthread_cond_timedwait(&done_cond, &done_mutex, &wait_time);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void hotword_models_cb(struct cras_client *client,
- const char *hotword_models)
-{
- printf("Hotword models: %s\n", hotword_models);
-}
-
-static void print_hotword_models(struct cras_client *client, cras_node_id_t id)
-{
- struct timespec wait_time;
-
- cras_client_run_thread(client);
- cras_client_connected_wait(client);
- cras_client_get_hotword_models(client, id, hotword_models_cb);
-
- clock_gettime(CLOCK_REALTIME, &wait_time);
- wait_time.tv_sec += 2;
-
- pthread_mutex_lock(&done_mutex);
- pthread_cond_timedwait(&done_cond, &done_mutex, &wait_time);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void check_output_plugged(struct cras_client *client, const char *name)
-{
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- printf("%s\n",
- cras_client_output_dev_plugged(client, name) ? "Yes" : "No");
-}
-
-/* Repeatedly mute and un-mute the output until there is an error. */
-static void mute_loop_test(struct cras_client *client, int auto_reconnect)
-{
- int mute = 0;
- int rc;
-
- if (auto_reconnect)
- cras_client_run_thread(client);
- while (1) {
- rc = cras_client_set_user_mute(client, mute);
- printf("cras_client_set_user_mute(%d): %d\n", mute, rc);
- if (rc != 0 && !auto_reconnect)
- return;
- mute = !mute;
- sleep(2);
- }
-}
-
-static void show_atlog(time_t sec_offset, int32_t nsec_offset,
- struct audio_thread_event_log *log, int len,
- uint64_t missing)
-{
- int i;
- printf("Audio Thread Event Log:\n");
-
- if (missing)
- printf("%" PRIu64 " logs are missing.\n", missing);
-
- for (i = 0; i < len; ++i) {
- show_alog_tag(log, i, sec_offset, nsec_offset);
- }
-}
-
-static void unlock_main_thread(struct cras_client *client)
-{
- pthread_mutex_lock(&done_mutex);
- pthread_cond_signal(&done_cond);
- pthread_mutex_unlock(&done_mutex);
-}
-
-static void cras_show_continuous_atlog(struct cras_client *client)
-{
- struct audio_thread_event_log log;
- struct timespec wait_time;
- static time_t sec_offset;
- static int32_t nsec_offset;
- static uint64_t atlog_read_idx = 0, missing;
- int len, rc;
-
- cras_client_run_thread(client);
- cras_client_connected_wait(client); /* To synchronize data. */
- cras_client_get_atlog_access(client, unlock_main_thread);
-
- clock_gettime(CLOCK_REALTIME, &wait_time);
- wait_time.tv_sec += 2;
-
- pthread_mutex_lock(&done_mutex);
- rc = pthread_cond_timedwait(&done_cond, &done_mutex, &wait_time);
- pthread_mutex_unlock(&done_mutex);
-
- if (rc)
- goto fail;
-
- fill_time_offset(&sec_offset, &nsec_offset);
-
- /* Set stdout buffer to line buffered mode. */
- setlinebuf(stdout);
-
- while (1) {
- len = cras_client_read_atlog(client, &atlog_read_idx, &missing,
- &log);
-
- if (len < 0)
- break;
- if (len > 0)
- show_atlog(sec_offset, nsec_offset, &log, len, missing);
- nanosleep(&follow_atlog_sleep_ts, NULL);
- }
-fail:
- printf("Failed to get audio thread log.\n");
-}
-
-// clang-format off
-static struct option long_options[] = {
- {"show_latency", no_argument, &show_latency, 1},
- {"show_rms", no_argument, &show_rms, 1},
- {"show_total_rms", no_argument, &show_total_rms, 1},
- {"select_input", required_argument, 0, 'a'},
- {"block_size", required_argument, 0, 'b'},
- {"num_channels", required_argument, 0, 'c'},
- {"duration_seconds", required_argument, 0, 'd'},
- {"dump_events", no_argument, 0, 'e'},
- {"format", required_argument, 0, 'f'},
- {"capture_gain", required_argument, 0, 'g'},
- {"help", no_argument, 0, 'h'},
- {"dump_server_info", no_argument, 0, 'i'},
- {"check_output_plugged",required_argument, 0, 'j'},
- {"add_active_input", required_argument, 0, 'k'},
- {"dump_dsp", no_argument, 0, 'l'},
- {"dump_audio_thread", no_argument, 0, 'm'},
- {"syslog_mask", required_argument, 0, 'n'},
- {"channel_layout", required_argument, 0, 'o'},
- {"get_aec_group_id", no_argument, 0, 'p'},
- {"user_mute", required_argument, 0, 'q'},
- {"rate", required_argument, 0, 'r'},
- {"reload_dsp", no_argument, 0, 's'},
- {"add_active_output", required_argument, 0, 't'},
- {"mute", required_argument, 0, 'u'},
- {"volume", required_argument, 0, 'v'},
- {"set_node_volume", required_argument, 0, 'w'},
- {"plug", required_argument, 0, 'x'},
- {"select_output", required_argument, 0, 'y'},
- {"playback_delay_us", required_argument, 0, 'z'},
- {"capture_mute", required_argument, 0, '0'},
- {"rm_active_input", required_argument, 0, '1'},
- {"rm_active_output", required_argument, 0, '2'},
- {"swap_left_right", required_argument, 0, '3'},
- {"version", no_argument, 0, '4'},
- {"add_test_dev", required_argument, 0, '5'},
- {"test_hotword_file", required_argument, 0, '6'},
- {"listen_for_hotword", required_argument, 0, '7'},
- {"pin_device", required_argument, 0, '8'},
- {"suspend", required_argument, 0, '9'},
- {"set_node_gain", required_argument, 0, ':'},
- {"play_short_sound", required_argument, 0, '!'},
- {"config_global_remix", required_argument, 0, ';'},
- {"set_hotword_model", required_argument, 0, '<'},
- {"get_hotword_models", required_argument, 0, '>'},
- {"post_dsp", required_argument, 0, 'A'},
- {"stream_id", required_argument, 0, 'B'},
- {"capture_file", required_argument, 0, 'C'},
- {"reload_aec_config", no_argument, 0, 'D'},
- {"effects", required_argument, 0, 'E'},
- {"get_aec_supported", no_argument, 0, 'F'},
- {"aecdump", required_argument, 0, 'G'},
- {"dump_bt", no_argument, 0, 'H'},
- {"set_wbs_enabled", required_argument, 0, 'I'},
- {"follow_atlog", no_argument, 0, 'J'},
- {"connection_type", required_argument, 0, 'K'},
- {"loopback_file", required_argument, 0, 'L'},
- {"mute_loop_test", required_argument, 0, 'M'},
- {"dump_main", no_argument, 0, 'N'},
- {"playback_file", required_argument, 0, 'P'},
- {"stream_type", required_argument, 0, 'T'},
- {0, 0, 0, 0}
-};
-// clang-format on
-
-static void show_usage()
-{
- int i;
-
- printf("--add_active_input <N>:<M> - "
- "Add the ionode with the given id to active input device "
- "list\n");
- printf("--add_active_output <N>:<M> - "
- "Add the ionode with the given id to active output device "
- "list\n");
- printf("--add_test_dev <type> - "
- "Add a test iodev.\n");
- printf("--block_size <N> - "
- "The number for frames per callback(dictates latency).\n");
- printf("--capture_file <name> - "
- "Name of file to record to.\n");
- printf("--capture_gain <dB> - "
- "Set system capture gain in dB*100 (100 = 1dB).\n");
- printf("--capture_mute <0|1> - "
- "Set capture mute state.\n");
- printf("--channel_layout <layout_str> - "
- "Set multiple channel layout.\n");
- printf("--check_output_plugged <output name> - "
- "Check if the output is plugged in\n");
- printf("--connection_type <connection_type> - "
- "Set cras_client connection_type (default to 0).\n"
- " "
- "Argument: 0 - For control client.\n"
- " "
- " 1 - For playback client.\n"
- " "
- " 2 - For capture client.\n"
- " "
- " 3 - For legacy client in vms.\n"
- " "
- " 4 - For unified client in vms.\n");
- printf("--dump_audio_thread - "
- "Dumps audio thread info.\n");
- printf("--dump_bt - "
- "Dumps debug info for bt audio\n");
- printf("--dump_main - "
- "Dumps debug info from main thread\n");
- printf("--dump_dsp - "
- "Print status of dsp to syslog.\n");
- printf("--dump_server_info - "
- "Print status of the server.\n");
- printf("--duration_seconds <N> - "
- "Seconds to record or playback.\n");
- printf("--follow_atlog - "
- "Continuously dumps audio thread event log.\n");
- printf("--format <name> - "
- "The sample format. Either ");
- for (i = 0; supported_formats[i].name; ++i)
- printf("%s ", supported_formats[i].name);
- printf("(default to S16_LE).\n");
- printf("--get_hotword_models <N>:<M> - "
- "Get the supported hotword models of node\n");
- printf("--help - "
- "Print this message.\n");
- printf("--listen_for_hotword <name> - "
- "Listen and capture hotword stream if supported\n");
- printf("--loopback_file <name> - "
- "Name of file to record from loopback device.\n");
- printf("--mute <0|1> - "
- "Set system mute state.\n");
- printf("--mute_loop_test <0|1> - "
- "Continuously loop mute/un-mute.\n"
- " "
- "Argument: 0 - stop on error.\n"
- " "
- " 1 - automatically reconnect to CRAS.\n");
- printf("--num_channels <N> - "
- "Two for stereo.\n");
- printf("--pin_device <N> - "
- "Playback/Capture only on the given device.\n");
- printf("--playback_file <name> - "
- "Name of file to play, "
- "\"-\" to playback raw audio from stdin.\n");
- printf("--play_short_sound <N> - "
- "Plays the content in the file for N periods when ' "
- "is pressed.\n");
- printf("--plug <N>:<M>:<0|1> - "
- "Set the plug state (0 or 1) for the ionode with the given "
- "index M on the device with index N\n");
- printf("--rate <N> - "
- "Specifies the sample rate in Hz.\n");
- printf("--reload_dsp - "
- "Reload dsp configuration from the ini file\n");
- printf("--rm_active_input <N>:<M> - "
- "Removes the ionode with the given id from active input device "
- "list\n");
- printf("--rm_active_output <N>:<M> - "
- "Removes the ionode with the given id from active output device "
- "list\n");
- printf("--select_input <N>:<M> - "
- "Select the ionode with the given id as preferred input\n");
- printf("--select_output <N>:<M> - "
- "Select the ionode with the given id as preferred output\n");
- printf("--set_hotword_model <N>:<M>:<model> - "
- "Set the model to node\n");
- printf("--playback_delay_us <N> - "
- "Set the time in us to delay a reply for playback when i is "
- "pressed\n");
- printf("--post_dsp <0|1> - "
- "Use this flag with --loopback_file. The default value is 0.\n"
- " "
- "Argument: 0 - Record from post-mix, pre-DSP loopback device.\n"
- " "
- " 1 - Record from post-DSP loopback device.\n");
- printf("--set_node_volume <N>:<M>:<0-100> - "
- "Set the volume of the ionode with the given id\n");
- printf("--show_latency - "
- "Display latency while playing or recording.\n");
- printf("--show_rms - "
- "Display RMS value of loopback stream.\n");
- printf("--show_total_rms - "
- "Display total RMS value of loopback stream at the end.\n");
- printf("--suspend <0|1> - "
- "Set audio suspend state.\n");
- printf("--swap_left_right <N>:<M>:<0|1> - "
- "Swap or un-swap (1 or 0) the left and right channel for the "
- "ionode with the given index M on the device with index N\n");
- printf("--stream_type <N> - "
- "Specify the type of the stream.\n");
- printf("--syslog_mask <n> - "
- "Set the syslog mask to the given log level.\n");
- printf("--test_hotword_file <N>:<filename> - "
- "Use filename as a hotword buffer for device N\n");
- printf("--user_mute <0|1> - "
- "Set user mute state.\n");
- printf("--version - "
- "Print the git commit ID that was used to build the client.\n");
- printf("--volume <0-100> - "
- "Set system output volume.\n");
-}
-
-static int cras_client_create_and_connect(struct cras_client **client,
- enum CRAS_CONNECTION_TYPE conn_type)
-{
- int rc;
-
- rc = cras_client_create_with_type(client, conn_type);
- if (rc < 0) {
- fprintf(stderr, "Couldn't create client.\n");
- return rc;
- }
-
- rc = cras_client_connect_timeout(*client, 1000);
- if (rc) {
- fprintf(stderr, "Couldn't connect to server.\n");
- cras_client_destroy(*client);
- return rc;
- }
-
- return 0;
-}
-
-int main(int argc, char **argv)
-{
- struct cras_client *client;
- int c, option_index;
- size_t block_size = NOT_ASSIGNED;
- size_t rate = 48000;
- size_t num_channels = 2;
- float duration_seconds = 0;
- const char *capture_file = NULL;
- const char *playback_file = NULL;
- const char *loopback_file = NULL;
- int post_dsp = 0;
- enum CRAS_STREAM_TYPE stream_type = CRAS_STREAM_TYPE_DEFAULT;
- int rc = 0;
- uint32_t stream_flags = 0;
- cras_stream_id_t stream_id = 0;
- snd_pcm_format_t format = SND_PCM_FORMAT_S16_LE;
- enum CRAS_CONNECTION_TYPE conn_type = CRAS_CONTROL;
- enum CRAS_CONNECTION_TYPE new_conn_type;
-
- option_index = 0;
- openlog("cras_test_client", LOG_PERROR, LOG_USER);
- setlogmask(LOG_UPTO(LOG_INFO));
-
- rc = cras_client_create_and_connect(&client, conn_type);
- if (rc) {
- return rc;
- }
-
- if (argc == 1) {
- /* Nothing specified, default to dump_server_info. */
- print_server_info(client);
- goto destroy_exit;
- }
-
- while (1) {
- c = getopt_long(argc, argv, "o:s:P:C:r:c:f:h", long_options,
- &option_index);
- if (c == -1)
- break;
- switch (c) {
- case 'y':
- case 'a': {
- cras_node_id_t id;
- rc = parse_node_id(optarg, &id);
- if (rc) {
- show_usage();
- return rc;
- }
-
- enum CRAS_STREAM_DIRECTION direction =
- (c == 'y') ? CRAS_STREAM_OUTPUT :
- CRAS_STREAM_INPUT;
- cras_client_select_node(client, direction, id);
- break;
- }
- case 'b':
- block_size = atoi(optarg);
- break;
- case 'c':
- num_channels = atoi(optarg);
- break;
- case 'd':
- duration_seconds = atof(optarg);
- break;
- case 'e':
- show_audio_thread_snapshots(client);
- break;
- case 'f': {
- int i;
-
- for (i = 0; supported_formats[i].name; ++i) {
- if (strcasecmp(optarg,
- supported_formats[i].name) ==
- 0) {
- format = supported_formats[i].format;
- break;
- }
- }
-
- if (!supported_formats[i].name) {
- printf("Unsupported format: %s\n", optarg);
- return -EINVAL;
- }
- break;
- }
- case 'h':
- show_usage();
- break;
- case 'i':
- print_server_info(client);
- break;
- case 'j':
- check_output_plugged(client, optarg);
- break;
- case 'k':
- case 't':
- case '1':
- case '2': {
- cras_node_id_t id;
- rc = parse_node_id(optarg, &id);
- if (rc) {
- show_usage();
- return rc;
- }
-
- enum CRAS_STREAM_DIRECTION dir;
- if (c == 't' || c == '2')
- dir = CRAS_STREAM_OUTPUT;
- else
- dir = CRAS_STREAM_INPUT;
-
- if (c == 'k' || c == 't')
- cras_client_add_active_node(client, dir, id);
- else
- cras_client_rm_active_node(client, dir, id);
- break;
- }
- case 'l':
- cras_client_dump_dsp_info(client);
- break;
- case 'm':
- show_audio_debug_info(client);
- break;
- case 'n': {
- int log_level = atoi(optarg);
-
- setlogmask(LOG_UPTO(log_level));
- break;
- }
- case 'o':
- channel_layout = optarg;
- break;
- case 'p':
- printf("AEC group ID %d\n",
- cras_client_get_aec_group_id(client));
- break;
- case 'q': {
- int mute = atoi(optarg);
- rc = cras_client_set_user_mute(client, mute);
- if (rc < 0) {
- fprintf(stderr, "problem setting mute\n");
- goto destroy_exit;
- }
- break;
- }
- case 'r':
- rate = atoi(optarg);
- break;
- case 's':
- cras_client_reload_dsp(client);
- break;
- case 'u': {
- int mute = atoi(optarg);
- rc = cras_client_set_system_mute(client, mute);
- if (rc < 0) {
- fprintf(stderr, "problem setting mute\n");
- goto destroy_exit;
- }
- break;
- }
- case 'v': {
- int volume = atoi(optarg);
- volume = MIN(100, MAX(0, volume));
- rc = cras_client_set_system_volume(client, volume);
- if (rc < 0) {
- fprintf(stderr, "problem setting volume\n");
- goto destroy_exit;
- }
- break;
- }
- case ':':
- case 'w': {
- cras_node_id_t id;
- int value;
- rc = parse_node_id_with_value(optarg, &id, &value);
- if (rc) {
- show_usage();
- return rc;
- }
-
- if (c == 'w')
- cras_client_set_node_volume(client, id, value);
- else
- cras_client_set_node_capture_gain(client, id,
- value);
- break;
- }
- case 'x': {
- cras_node_id_t id;
- int value;
- rc = parse_node_id_with_value(optarg, &id, &value);
- if (rc) {
- show_usage();
- return rc;
- }
-
- enum ionode_attr attr = IONODE_ATTR_PLUGGED;
- cras_client_set_node_attr(client, id, attr, value);
- break;
- }
- case 'z':
- pause_in_playback_reply = atoi(optarg);
- break;
-
- case '0': {
- int mute = atoi(optarg);
- rc = cras_client_set_system_capture_mute(client, mute);
- if (rc < 0) {
- fprintf(stderr, "problem setting mute\n");
- goto destroy_exit;
- }
- break;
- }
- case '3': {
- cras_node_id_t id;
- int value;
- rc = parse_node_id_with_value(optarg, &id, &value);
- if (rc) {
- show_usage();
- return rc;
- }
-
- cras_client_swap_node_left_right(client, id, value);
- break;
- }
- case '4':
- printf("%s\n", VCSID);
- break;
- case '5': {
- cras_client_add_test_iodev(client, atoi(optarg));
- break;
- }
- case '6': {
- const char *s;
- int dev_index;
-
- s = strtok(optarg, ":");
- if (!s) {
- show_usage();
- return -EINVAL;
- }
- dev_index = atoi(s);
-
- const char *file_name = strtok(NULL, ":");
- if (!file_name) {
- show_usage();
- return -EINVAL;
- }
- cras_client_test_iodev_command(
- client, dev_index,
- TEST_IODEV_CMD_HOTWORD_TRIGGER,
- strlen(file_name) + 1, (uint8_t *)file_name);
- break;
- }
- case '7': {
- stream_flags = HOTWORD_STREAM;
- capture_file = optarg;
- break;
- }
- case '8':
- pin_device_id = atoi(optarg);
- break;
- case '9': {
- int suspend = atoi(optarg);
- cras_client_set_suspend(client, suspend);
- break;
- }
-
- case '!': {
- play_short_sound = 1;
- play_short_sound_periods = atoi(optarg);
- break;
- }
- case ';': {
- char *s;
- int nch;
- int size = 0;
- float *coeff;
-
- s = strtok(optarg, ":");
- nch = atoi(s);
- coeff = (float *)calloc((size_t)nch * (size_t)nch,
- sizeof(*coeff));
- for (size = 0; size < nch * nch; size++) {
- s = strtok(NULL, ",");
- if (NULL == s)
- break;
- coeff[size] = atof(s);
- }
- cras_client_config_global_remix(client, nch, coeff);
- free(coeff);
- break;
- }
- case '<':
- case '>': {
- char *s;
- int dev_index;
- int node_index;
-
- s = strtok(optarg, ":");
- if (!s) {
- show_usage();
- return -EINVAL;
- }
- dev_index = atoi(s);
-
- s = strtok(NULL, ":");
- if (!s) {
- show_usage();
- return -EINVAL;
- }
- node_index = atoi(s);
-
- s = strtok(NULL, ":");
- if (!s && c == ';') {
- //TODO: c never == ';'
- show_usage();
- return -EINVAL;
- }
-
- cras_node_id_t id =
- cras_make_node_id(dev_index, node_index);
- if (c == '<')
- cras_client_set_hotword_model(client, id, s);
- else
- print_hotword_models(client, id);
- break;
- }
-
- case 'A':
- post_dsp = atoi(optarg);
- break;
- case 'B':
- stream_id = atoi(optarg);
- break;
- case 'C':
- capture_file = optarg;
- break;
- case 'D':
- cras_client_reload_aec_config(client);
- break;
- case 'E': {
- char *s;
-
- s = strtok(optarg, ",");
- while (s) {
- if (strcmp("aec", s) == 0)
- effect_aec = 1;
- else if (strcmp("ns", s) == 0)
- effect_ns = 1;
- else if (strcmp("agc", s) == 0)
- effect_agc = 1;
- else if (strcmp("vad", s) == 0)
- effect_vad = 1;
- else
- printf("Unknown effect %s\n", s);
- s = strtok(NULL, ",");
- }
- break;
- }
- case 'F':
- printf("AEC supported %d\n",
- !!cras_client_get_aec_supported(client));
- break;
- case 'G':
- aecdump_file = optarg;
- break;
- case 'H':
- show_cras_bt_debug_info(client);
- break;
- case 'I':
- cras_client_set_bt_wbs_enabled(client, atoi(optarg));
- break;
- case 'J':
- cras_show_continuous_atlog(client);
- break;
- case 'K':
- new_conn_type = atoi(optarg);
- if (cras_validate_connection_type(new_conn_type)) {
- if (new_conn_type != conn_type) {
- cras_client_destroy(client);
- client = NULL;
- rc = cras_client_create_and_connect(
- &client, new_conn_type);
- if (rc) {
- fprintf(stderr,
- "Couldn't connect to "
- "server.\n");
- return rc;
- }
- conn_type = new_conn_type;
- }
- } else {
- printf("Input connection type is not "
- "supported.\n");
- }
- break;
- case 'L':
- loopback_file = optarg;
- break;
- case 'M':
- mute_loop_test(client, atoi(optarg));
- break;
- case 'N':
- show_main_thread_debug_info(client);
- break;
- case 'P':
- playback_file = optarg;
- break;
- case 'T':
- stream_type = atoi(optarg);
- break;
-
- default:
- break;
- }
- }
-
- if (optind < argc) {
- printf("Warning: un-welcome arguments: ");
- while (optind < argc)
- printf("%s ", argv[optind++]);
- printf("\n");
- rc = 1;
- goto destroy_exit;
- }
-
- duration_frames = duration_seconds * rate;
- if (block_size == NOT_ASSIGNED)
- block_size = get_block_size(PLAYBACK_BUFFERED_TIME_IN_US, rate);
-
- if (capture_file != NULL) {
- if (strcmp(capture_file, "-") == 0)
- rc = run_file_io_stream(client, 1, CRAS_STREAM_INPUT,
- block_size, stream_type, rate,
- format, num_channels,
- stream_flags, 0, 0);
- else
- rc = run_capture(client, capture_file, block_size,
- stream_type, rate, format,
- num_channels, stream_flags, 0, 0);
- } else if (playback_file != NULL) {
- if (strcmp(playback_file, "-") == 0)
- rc = run_file_io_stream(client, 0, CRAS_STREAM_OUTPUT,
- block_size, stream_type, rate,
- format, num_channels,
- stream_flags, 0, 0);
- else
- rc = run_playback(client, playback_file, block_size,
- stream_type, rate, format,
- num_channels);
- } else if (loopback_file != NULL) {
- rc = run_capture(client, loopback_file, block_size, stream_type,
- rate, format, num_channels, stream_flags, 1,
- post_dsp);
- } else if (aecdump_file != NULL) {
- run_aecdump(client, stream_id, 1);
- sleep(duration_seconds);
- run_aecdump(client, stream_id, 0);
- }
-
-destroy_exit:
- cras_client_destroy(client);
- return rc;
-}
diff --git a/cras/tools/create_volume_curve.py b/cras/tools/create_volume_curve.py
deleted file mode 100755
index 13a0c59c..00000000
--- a/cras/tools/create_volume_curve.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-import sys
-
-def GenerateSimpleStep(name, max_volume, step_size):
- print '[%s]' % name
- print ' ; Generated by create_volume_curve.py'
- print ' ; simple_step curve, max %d, step %d' % (max_volume, step_size)
- print ' volume_curve = simple_step'
- print ' volume_step = %d' % step_size
- print ' max_volume = %d' % max_volume
-
-def WriteExplicitCurveVal(step, value):
- print ' db_at_%d = %d' % (step, value)
-
-def GenerateExplicit(name):
- print '[%s]' % name
- print ' ; Generated by create_volume_curve.py'
- print ' ; explicit curve'
- print ' volume_curve = explicit'
- for i in range(100):
- print 'Level at step %d:' % (100 - i)
- level = int(raw_input(">"))
- WriteExplicitCurveVal(100 - i, level)
- print 'Level at step 0:'
- level = int(raw_input(">"))
- WriteExplicitCurveVal(0, level)
-
-def GenerateTwoSlope(name, max_volume, step_1, step_2, pivot_point):
- print '[%s]' % name
- print ' ; Generated by create_volume_curve.py'
- print (' ; two_slope, max = %d, pivot = %d, steps %d, %d' %
- (max_volume, pivot_point, step_1, step_2))
- print ' volume_curve = explicit'
- for i in range(0, (100 - pivot_point)):
- WriteExplicitCurveVal(100 - i, max_volume - step_1 * i)
- pivot_dB_val = max_volume - step_1 * (100 - pivot_point)
- WriteExplicitCurveVal(pivot_point, max_volume - step_1 * (100 - pivot_point))
- for i in range(1, pivot_point):
- WriteExplicitCurveVal(pivot_point - i, pivot_dB_val - step_2 * i)
- WriteExplicitCurveVal(0, pivot_dB_val - pivot_point * step_2)
-
-def main():
- print 'What is the name of the jack or output to generate a curve for?'
- jack_name = raw_input(">");
- print 'Which type of curve? (simple_step, explicit, two_slope): '
- curve_type = raw_input(">");
- if curve_type == 'simple_step':
- print 'max volume (dBFS * 100):'
- max_volume = int(raw_input(">"))
- print 'step size (in dBFS * 100)'
- step_size = int(raw_input(">"))
- GenerateSimpleStep(jack_name, max_volume, step_size)
- elif curve_type == 'explicit':
- GenerateExplicit(jack_name)
- elif curve_type == 'two_slope':
- print 'max volume (dBFS * 100):'
- max_volume = int(raw_input(">"))
- print 'Volume step where slope changes:'
- pivot_point = int(raw_input(">"))
- print 'step size 100 to %d(in dBFS * 100)' % pivot_point
- step_1 = int(raw_input(">"))
- print 'step size %d to 0(in dBFS * 100)' % pivot_point
- step_2 = int(raw_input(">"))
- GenerateTwoSlope(jack_name, max_volume, step_1, step_2, pivot_point)
-
-if __name__ == '__main__':
- main()
diff --git a/cros_alsa/.gitignore b/cros_alsa/.gitignore
deleted file mode 100644
index b659239f..00000000
--- a/cros_alsa/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-target/
-.*.rustfmt
-Cargo.lock
diff --git a/cros_alsa/.rustfmt.toml b/cros_alsa/.rustfmt.toml
deleted file mode 100644
index a2db3012..00000000
--- a/cros_alsa/.rustfmt.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-use_field_init_shorthand = true
-use_try_shorthand = true
diff --git a/cros_alsa/Cargo.toml b/cros_alsa/Cargo.toml
deleted file mode 100644
index 2e006e40..00000000
--- a/cros_alsa/Cargo.toml
+++ /dev/null
@@ -1,15 +0,0 @@
-[package]
-name = "cros_alsa"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-description = "The Chromium OS alsa-lib wrapper"
-
-[dependencies]
-alsa-sys = "0.2.0"
-cros_alsa_derive = "*"
-libc = "0.2.65"
-remain = "0.2.1"
-
-[patch.crates-io]
-cros_alsa_derive = { path = "cros_alsa_derive" }
diff --git a/cros_alsa/cros_alsa_derive/Cargo.toml b/cros_alsa/cros_alsa_derive/Cargo.toml
deleted file mode 100644
index 6a4da288..00000000
--- a/cros_alsa/cros_alsa_derive/Cargo.toml
+++ /dev/null
@@ -1,14 +0,0 @@
-[package]
-name = "cros_alsa_derive"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-description = "Derive macros of cors_alsa."
-
-[lib]
-proc-macro = true
-
-[dependencies]
-proc-macro2 = "^1"
-quote = "^1"
-syn = "^1"
diff --git a/cros_alsa/cros_alsa_derive/src/common.rs b/cros_alsa/cros_alsa_derive/src/common.rs
deleted file mode 100644
index 2daaa3be..00000000
--- a/cros_alsa/cros_alsa_derive/src/common.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! This mod provides common constants, structs and functions used across cros_alsa_derive.
-use std::convert::TryFrom;
-
-use syn::{Lit, Meta, NestedMeta, Result};
-
-/// Attribute name of cros_alsa.
-const CROS_ALSA: &str = "cros_alsa";
-
-/// const for `#[cros_alsa(path = "...")]`
-const PATH: &str = "path";
-
-/// Possible `#[cros_alsa("...")]` derive macro helper attributes.
-pub enum CrosAlsaAttr {
- /// Use `#[cros_alsa(path = "crate")]` to replace the crate path of cros_alsa in derive macros.
- Path(syn::Path),
-}
-
-impl CrosAlsaAttr {
- /// Return true if the value is a `Path` variant.
- pub fn is_path(&self) -> bool {
- use CrosAlsaAttr::*;
- match self {
- Path(_) => true,
- // suppress unreachable_patterns warning because there is only one CrosAlsaAttr variant.
- #[allow(unreachable_patterns)]
- _ => false,
- }
- }
-}
-
-impl TryFrom<syn::NestedMeta> for CrosAlsaAttr {
- type Error = syn::Error;
- fn try_from(meta_item: NestedMeta) -> Result<CrosAlsaAttr> {
- match meta_item {
- // Parse `#[cros_alsa(path = "crate")]`
- NestedMeta::Meta(Meta::NameValue(m)) if m.path.is_ident(PATH) => {
- if let Lit::Str(lit_str) = &m.lit {
- return Ok(CrosAlsaAttr::Path(lit_str.parse()?));
- }
- Err(syn::Error::new_spanned(
- &m.lit,
- "expected a valid path for cros_alsa_derive::CrosAlsaAttr::Path",
- ))
- }
- _ => Err(syn::Error::new_spanned(
- meta_item,
- "unrecognized cros_alsa_derive::CrosAlsaAttr",
- )),
- }
- }
-}
-
-/// Parses `#[cros_alsa(path = "...")]` into a list of `CrosAlsaAttr`.
-/// It's used to replace the crate path of cros_alsa in derive macros.
-pub fn parse_cros_alsa_attr(attrs: &[syn::Attribute]) -> Result<Vec<CrosAlsaAttr>> {
- attrs
- .iter()
- .flat_map(|attr| get_cros_alsa_meta_items(attr))
- .flatten()
- .map(CrosAlsaAttr::try_from)
- .collect()
-}
-
-/// Parses and collects `NestedMeta` under `cros_alsa` attribute.
-fn get_cros_alsa_meta_items(attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>> {
- if !attr.path.is_ident(CROS_ALSA) {
- return Ok(Vec::new());
- }
- match attr.parse_meta() {
- Ok(Meta::List(meta)) => Ok(meta.nested.into_iter().collect()),
- _ => Err(syn::Error::new_spanned(attr, "expected #[cros_alsa(...)]")),
- }
-}
diff --git a/cros_alsa/cros_alsa_derive/src/control.rs b/cros_alsa/cros_alsa_derive/src/control.rs
deleted file mode 100644
index 584a5418..00000000
--- a/cros_alsa/cros_alsa_derive/src/control.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! This mod provides derive macros for cros_alsa::control.
-
-use proc_macro::TokenStream;
-use proc_macro2::Span;
-use quote::quote;
-
-use crate::common::{parse_cros_alsa_attr, CrosAlsaAttr};
-
-/// The provide default implementation for `ControlOps`.
-/// Users could hold `Ctl` and `ElemID` as `handle` and `id` in their control structure and use
-/// `#[derive(ControlOps)]` macro to generate default load / save implementations.
-pub fn impl_control_ops(ast: &syn::DeriveInput) -> TokenStream {
- let name = &ast.ident;
- let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
- let attrs = match parse_cros_alsa_attr(&ast.attrs) {
- Ok(attrs) => attrs,
- Err(e) => return e.to_compile_error().into(),
- };
- let path = match attrs.iter().find(|x| x.is_path()) {
- Some(CrosAlsaAttr::Path(path)) => path.clone(),
- None => syn::LitStr::new("cros_alsa", Span::call_site())
- .parse()
- .expect("failed to create a default path for derive macro: ControlOps"),
- };
- let gen = quote! {
- impl #impl_generics #path::ControlOps #impl_generics for #name #ty_generics #where_clause {
- fn load(&mut self) -> ::std::result::Result<<Self as #path::Control #impl_generics>::Item, #path::ControlError> {
- Ok(<Self as #path::Control>::Item::load(self.handle, &self.id)?)
- }
- fn save(&mut self, val: <Self as #path::Control #impl_generics>::Item) -> ::std::result::Result<bool, #path::ControlError> {
- Ok(<Self as #path::Control>::Item::save(self.handle, &self.id, val)?)
- }
- }
- };
- gen.into()
-}
diff --git a/cros_alsa/cros_alsa_derive/src/lib.rs b/cros_alsa/cros_alsa_derive/src/lib.rs
deleted file mode 100644
index 9970de78..00000000
--- a/cros_alsa/cros_alsa_derive/src/lib.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! `cros_alsa_derive` crate provides derive macros for cros_alsa.
-//!
-
-#![deny(missing_docs)]
-extern crate proc_macro;
-
-use proc_macro::TokenStream;
-
-mod common;
-mod control;
-use self::control::impl_control_ops;
-
-#[proc_macro_derive(ControlOps, attributes(cros_alsa))]
-/// Derive macro generating an impl of the trait ControlOps.
-/// To use this derive macro, users should hold `Ctl` and `ElemID` as `handle`
-/// and `id` in their control structure.
-pub fn control_ops_derive(input: TokenStream) -> TokenStream {
- match syn::parse(input) {
- Ok(ast) => impl_control_ops(&ast),
- Err(e) => e.to_compile_error().into(),
- }
-}
diff --git a/cros_alsa/src/card.rs b/cros_alsa/src/card.rs
deleted file mode 100644
index 42beef2c..00000000
--- a/cros_alsa/src/card.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-use std::error;
-use std::fmt;
-
-use remain::sorted;
-
-use crate::control::{self, Control};
-use crate::control_primitive;
-use crate::control_primitive::{Ctl, ElemId, ElemIface};
-use crate::control_tlv::{self, ControlTLV};
-
-pub type Result<T> = std::result::Result<T, Error>;
-
-#[sorted]
-#[derive(Debug)]
-/// Possible errors that can occur in cros-alsa::card.
-pub enum Error {
- /// Failed to call AlsaControlAPI.
- AlsaControlAPI(control_primitive::Error),
- /// Error occurs in Control.
- Control(control::Error),
- /// Error occurs in ControlTLV.
- ControlTLV(control_tlv::Error),
-}
-
-impl error::Error for Error {}
-
-impl From<control::Error> for Error {
- fn from(err: control::Error) -> Error {
- Error::Control(err)
- }
-}
-
-impl From<control_tlv::Error> for Error {
- fn from(err: control_tlv::Error) -> Error {
- Error::ControlTLV(err)
- }
-}
-
-impl From<control_primitive::Error> for Error {
- fn from(err: control_primitive::Error) -> Error {
- Error::AlsaControlAPI(err)
- }
-}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- AlsaControlAPI(e) => write!(f, "{}", e),
- Control(e) => write!(f, "{}", e),
- ControlTLV(e) => write!(f, "{}", e),
- }
- }
-}
-
-/// `Card` represents a sound card.
-#[derive(Debug)]
-pub struct Card {
- handle: Ctl,
- name: String,
-}
-
-impl Card {
- /// Creates a `Card`.
- ///
- /// # Arguments
- ///
- /// * `card_name` - The sound card name, ex: sofcmlmax98390d.
- ///
- /// # Errors
- ///
- /// * If card_name is an invalid CString.
- /// * If snd_ctl_open() fails.
- pub fn new(card_name: &str) -> Result<Self> {
- let handle = Ctl::new(&format!("hw:{}", card_name))?;
- Ok(Card {
- name: card_name.to_owned(),
- handle,
- })
- }
-
- /// Gets sound card name.
- pub fn name(&self) -> &str {
- &self.name
- }
-
- /// Creates a `Control` from control name.
- ///
- /// # Errors
- ///
- /// * If control name is an invalid CString.
- /// * If control does not exist.
- /// * If `Control` elem_type() mismatches the type of underlying mixer control.
- /// * If `Control` size() mismatches the number of value entries of underlying mixer control.
- pub fn control_by_name<'a, T: 'a>(&'a mut self, control_name: &str) -> Result<T>
- where
- T: Control<'a>,
- {
- let id = ElemId::new(ElemIface::Mixer, control_name)?;
- Ok(T::from(&mut self.handle, id)?)
- }
-
- /// Creates a `ControlTLV` from control name.
- ///
- /// # Errors
- ///
- /// * If control name is an invalid CString.
- /// * If control does not exist.
- pub fn control_tlv_by_name<'a>(&'a mut self, control_name: &str) -> Result<ControlTLV<'a>> {
- let id = ElemId::new(ElemIface::Mixer, control_name)?;
- Ok(ControlTLV::new(&mut self.handle, id)?)
- }
-}
diff --git a/cros_alsa/src/control.rs b/cros_alsa/src/control.rs
deleted file mode 100644
index 2bc90256..00000000
--- a/cros_alsa/src/control.rs
+++ /dev/null
@@ -1,297 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! `control` module is meant to provide easier to use and more type safe abstractions
-//! for various alsa mixer controls.
-//!
-//! Each mixer control should implement the `Control` trait to allow itself to be created by `Card`.
-//! Each mixer control could hold `Ctl` as handle and `ElemID` as id and use `#[derive(ControlOps)]` macro
-//! to generate default load / save implementations of the `ControlOps` trait which allows itself to read and
-//! write the underlying hardware.
-//!
-//! # Examples
-//! This is an example of how to define a `SwitchControl`.
-//!
-//! ```
-//! use std::error::Error;
-//!
-//! use cros_alsa::{Ctl, ElemId, Control, ControlError, ControlOps};
-//! use cros_alsa::elem::Elem;
-//!
-//! type Result<T> = std::result::Result<T, ControlError>;
-//!
-//! #[derive(ControlOps)]
-//! pub struct SwitchControl<'a> {
-//! // Must hold `Ctl` as handle and `ElemID` as id to use `#[derive(ControlOps)]`.
-//! handle: &'a mut Ctl,
-//! id: ElemId,
-//! }
-//!
-//! impl<'a> Control<'a> for SwitchControl <'a> {
-//! type Item = [bool; 1];
-//!
-//! fn new(handle: &'a mut Ctl, id: ElemId) -> Self {
-//! Self {
-//! handle,
-//! id,
-//! }
-//! }
-//! }
-//!
-//! impl<'a> SwitchControl<'a> {
-//! /// Reads the state of a switch type mix control.
-//! pub fn state(&mut self) -> Result<bool> {
-//! // Uses ControlOps::load() to read the mixer control.
-//! let v = self.load()?;
-//! Ok(v[0])
-//! }
-//!
-//! /// Updates the control state to true.
-//! pub fn on(&mut self) -> Result<()> {
-//! // Uses ControlOps::save() to write the mixer control.
-//! self.save([true])?;
-//! Ok(())
-//! }
-//! }
-//!
-//! ```
-
-use std::error;
-use std::fmt;
-
-use cros_alsa_derive::ControlOps;
-use remain::sorted;
-
-use crate::control_primitive::{self, Ctl, ElemId, ElemInfo, ElemType};
-use crate::elem::{self, Elem};
-
-/// The Result type of cros-alsa::control.
-pub type Result<T> = std::result::Result<T, Error>;
-
-#[sorted]
-#[derive(Debug)]
-/// Possible errors that can occur in cros-alsa::control.
-pub enum Error {
- /// Failed to call AlsaControlAPI.
- AlsaControlAPI(control_primitive::Error),
- /// Error occurs in Elem.
- Elem(elem::Error),
- /// Elem::size() does not match the element count of the mixer control.
- MismatchElemCount(String, usize, usize),
- /// Elem::elem_type() does not match the data type of the mixer control.
- MismatchElemType(String, ElemType, ElemType),
-}
-
-impl error::Error for Error {}
-
-impl From<control_primitive::Error> for Error {
- fn from(err: control_primitive::Error) -> Error {
- Error::AlsaControlAPI(err)
- }
-}
-
-impl From<elem::Error> for Error {
- fn from(err: elem::Error) -> Error {
- Error::Elem(err)
- }
-}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- AlsaControlAPI(e) => write!(f, "{}", e),
- Elem(e) => write!(f, "{}", e),
- MismatchElemCount(name, count, elem_count) => write!(
- f,
- "invalid `Control::size()` of {}: expect: {}, get: {}",
- name, count, elem_count
- ),
- MismatchElemType(name, t, elem_type) => write!(
- f,
- "invalid `Control::elem_type()` of {}: expect: {}, get: {}",
- name, t, elem_type
- ),
- }
- }
-}
-
-/// Each mixer control should implement the `Control` trait to allow itself to be created by `Card`.
-pub trait Control<'a>: Sized + 'a {
- /// The data type of the mixer control.
- /// Use `ElemType::load()` and `ElemType::save()` to read or write the mixer control.
- type Item: Elem;
-
- /// Called by `Self::from(handle: &'a mut Ctl, id: ElemId)` to create a `Control`.
- fn new(handle: &'a mut Ctl, id: ElemId) -> Self;
- /// Called by `Card` to create a `Control`.
- fn from(handle: &'a mut Ctl, id: ElemId) -> Result<Self> {
- let info = ElemInfo::new(handle, &id)?;
- if info.elem_type()? != Self::elem_type() {
- return Err(Error::MismatchElemType(
- id.name()?.to_owned(),
- info.elem_type()?,
- Self::elem_type(),
- ));
- }
-
- if info.count() != Self::size() {
- return Err(Error::MismatchElemCount(
- id.name()?.to_owned(),
- info.count(),
- Self::size(),
- ));
- }
-
- Ok(Self::new(handle, id))
- }
- /// Called by `Self::from(handle: &'a mut Ctl, id: ElemId)` to validate the data type of a
- /// `Control`.
- fn elem_type() -> ElemType {
- Self::Item::elem_type()
- }
- /// Called by `Self::from(handle: &'a mut Ctl, id: ElemId)` to validate the number of value
- /// entries of a `Control`.
- fn size() -> usize {
- Self::Item::size()
- }
-}
-
-/// Each mixer control could implement the `ControlOps` trait to allow itself to read and
-/// write the underlying hardware`. Users could hold `Ctl` and `ElemID` as `handle` and `id`
-/// in their control structure and use `#[derive(ControlOps)]` macro to generate default
-/// load / save implementations.
-pub trait ControlOps<'a>: Control<'a> {
- /// Reads the values of the mixer control.
- fn load(&mut self) -> Result<<Self as Control<'a>>::Item>;
- /// Saves the values to the mixer control.
- fn save(&mut self, val: <Self as Control<'a>>::Item) -> Result<bool>;
-}
-
-/// `Control` that reads and writes a single integer value entry.
-/// Since this crate is the `cros_alsa` crate, we replace the `cros_alsa`
-/// path to `crate` in derive macros by `cros_alsa` attribute.
-#[derive(ControlOps)]
-#[cros_alsa(path = "crate")]
-pub struct IntControl<'a> {
- handle: &'a mut Ctl,
- id: ElemId,
-}
-
-impl<'a> IntControl<'a> {
- /// Gets an i32 value from the mixer control.
- ///
- /// # Errors
- ///
- /// * If it fails to read from the control.
- pub fn get(&mut self) -> Result<i32> {
- let val = self.load()?;
- Ok(val[0])
- }
-
- /// Updates an i32 value to the mixer control.
- ///
- /// # Errors
- ///
- /// * If it fails to write to the control.
- pub fn set(&mut self, val: i32) -> Result<()> {
- self.save([val])?;
- Ok(())
- }
-}
-
-impl<'a> Control<'a> for IntControl<'a> {
- type Item = [i32; 1];
- fn new(handle: &'a mut Ctl, id: ElemId) -> Self {
- Self { handle, id }
- }
-}
-
-/// Stereo Volume Mixer Control
-/// Since this crate is the `cros_alsa` crate, we replace the `cros_alsa`
-/// path to `crate` in derive macros by `cros_alsa` attribute.
-#[derive(ControlOps)]
-#[cros_alsa(path = "crate")]
-pub struct StereoVolumeControl<'a> {
- handle: &'a mut Ctl,
- id: ElemId,
-}
-
-impl<'a> StereoVolumeControl<'a> {
- /// Reads the left and right volume.
- ///
- /// # Errors
- ///
- /// * If it fails to read from the control.
- pub fn volume(&mut self) -> Result<(i32, i32)> {
- let val = self.load()?;
- Ok((val[0], val[1]))
- }
-
- /// Updates the left and right volume.
- ///
- /// # Errors
- ///
- /// * If it fails to write to the control.
- pub fn set_volume(&mut self, left: i32, right: i32) -> Result<()> {
- self.save([left, right])?;
- Ok(())
- }
-}
-
-impl<'a> Control<'a> for StereoVolumeControl<'a> {
- type Item = [i32; 2];
- fn new(handle: &'a mut Ctl, id: ElemId) -> Self {
- Self { handle, id }
- }
-}
-
-/// `Control` that reads and writes a single boolean value entry.
-/// Since this crate is the `cros_alsa` crate, we replace the `cros_alsa`
-/// path to `crate` in derive macros by `cros_alsa` attribute.
-#[derive(ControlOps)]
-#[cros_alsa(path = "crate")]
-pub struct SwitchControl<'a> {
- handle: &'a mut Ctl,
- id: ElemId,
-}
-
-impl<'a> SwitchControl<'a> {
- /// Reads the state of a switch type mix control.
- ///
- /// # Errors
- ///
- /// * If it fails to read from the control.
- pub fn state(&mut self) -> Result<bool> {
- let v = self.load()?;
- Ok(v[0])
- }
-
- /// Updates the control state to true.
- ///
- /// # Errors
- ///
- /// * If it fails to write to the control.
- pub fn on(&mut self) -> Result<()> {
- self.save([true])?;
- Ok(())
- }
-
- /// Updates the control state to false.
- ///
- /// # Errors
- ///
- /// * If it fails to write to the control.
- pub fn off(&mut self) -> Result<()> {
- self.save([false])?;
- Ok(())
- }
-}
-
-impl<'a> Control<'a> for SwitchControl<'a> {
- type Item = [bool; 1];
- fn new(handle: &'a mut Ctl, id: ElemId) -> Self {
- Self { handle, id }
- }
-}
diff --git a/cros_alsa/src/control_primitive.rs b/cros_alsa/src/control_primitive.rs
deleted file mode 100644
index 227aef27..00000000
--- a/cros_alsa/src/control_primitive.rs
+++ /dev/null
@@ -1,406 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-use std::convert::TryFrom;
-use std::error;
-use std::ffi::{CStr, CString, FromBytesWithNulError, NulError};
-use std::fmt;
-use std::marker::PhantomData;
-use std::ptr;
-use std::slice;
-use std::str;
-
-use alsa_sys::*;
-use libc::strlen;
-use remain::sorted;
-
-pub type Result<T> = std::result::Result<T, Error>;
-
-#[derive(Debug, PartialEq)]
-/// Possible errors that can occur in FFI functions.
-pub enum FFIError {
- Rc(i32),
- NullPtr,
-}
-
-impl fmt::Display for FFIError {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use FFIError::*;
- match self {
- Rc(rc) => write!(f, "{}", snd_strerror(*rc)?),
- NullPtr => write!(f, "the return value is a null pointer"),
- }
- }
-}
-
-#[sorted]
-#[derive(Debug, PartialEq)]
-/// Possible errors that can occur in cros-alsa::control_primitive.
-pub enum Error {
- /// Control with the given name does not exist.
- ControlNotFound(String),
- /// Failed to call snd_ctl_open().
- CtlOpenFailed(FFIError, String),
- /// snd_ctl_elem_id_get_name() returns null.
- ElemIdGetNameFailed,
- /// Failed to call snd_ctl_elem_id_malloc().
- ElemIdMallocFailed(FFIError),
- /// Failed to call snd_ctl_elem_info_malloc().
- ElemInfoMallocFailed(FFIError),
- /// Failed to call snd_ctl_elem_value_malloc().
- ElemValueMallocFailed(FFIError),
- /// The slice used to create a CStr does not have one and only one null
- /// byte positioned at the end.
- FromBytesWithNulError(FromBytesWithNulError),
- /// Failed to convert to a valid ElemType.
- InvalidElemType(u32),
- /// An error indicating that an interior nul byte was found.
- NulError(NulError),
- /// Failed to call snd_strerror().
- SndStrErrorFailed(i32),
- /// UTF-8 validation failed
- Utf8Error(str::Utf8Error),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- ControlNotFound(name) => write!(f, "control: {} does not exist", name),
- CtlOpenFailed(e, name) => write!(f, "{} snd_ctl_open failed: {}", name, e,),
- ElemIdGetNameFailed => write!(f, "snd_ctl_elem_id_get_name failed"),
- ElemIdMallocFailed(e) => write!(f, "snd_ctl_elem_id_malloc failed: {}", e),
- ElemInfoMallocFailed(e) => write!(f, "snd_ctl_elem_info_malloc failed: {}", e),
- ElemValueMallocFailed(e) => write!(f, "snd_ctl_elem_value_malloc failed: {}", e),
- FromBytesWithNulError(e) => write!(f, "invalid CString: {}", e),
- InvalidElemType(v) => write!(f, "invalid ElemType: {}", v),
- NulError(e) => write!(f, "invalid CString: {}", e),
- SndStrErrorFailed(e) => write!(f, "snd_strerror() failed: {}", e),
- Utf8Error(e) => write!(f, "{}", e),
- }
- }
-}
-
-impl From<Error> for fmt::Error {
- fn from(_err: Error) -> fmt::Error {
- fmt::Error
- }
-}
-
-impl From<str::Utf8Error> for Error {
- fn from(err: str::Utf8Error) -> Error {
- Error::Utf8Error(err)
- }
-}
-
-impl From<FromBytesWithNulError> for Error {
- fn from(err: FromBytesWithNulError) -> Error {
- Error::FromBytesWithNulError(err)
- }
-}
-
-impl From<NulError> for Error {
- fn from(err: NulError) -> Error {
- Error::NulError(err)
- }
-}
-
-/// [snd_ctl_elem_iface_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#ga14baa0febb91cc4c5d72dcc825acf518) wrapper.
-#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub enum ElemIface {
- Card = SND_CTL_ELEM_IFACE_CARD as isize,
- Hwdep = SND_CTL_ELEM_IFACE_HWDEP as isize,
- Mixer = SND_CTL_ELEM_IFACE_MIXER as isize,
- PCM = SND_CTL_ELEM_IFACE_PCM as isize,
- Rawmidi = SND_CTL_ELEM_IFACE_RAWMIDI as isize,
- Timer = SND_CTL_ELEM_IFACE_TIMER as isize,
- Sequencer = SND_CTL_ELEM_IFACE_SEQUENCER as isize,
-}
-
-#[derive(Debug, Copy, Clone, PartialEq, Eq)]
-/// [snd_ctl_elem_type_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#gac42e0ed6713b62711af5e80b4b3bcfec) wrapper.
-pub enum ElemType {
- None = SND_CTL_ELEM_TYPE_NONE as isize,
- Boolean = SND_CTL_ELEM_TYPE_BOOLEAN as isize,
- Integer = SND_CTL_ELEM_TYPE_INTEGER as isize,
- Enumerated = SND_CTL_ELEM_TYPE_ENUMERATED as isize,
- Bytes = SND_CTL_ELEM_TYPE_BYTES as isize,
- IEC958 = SND_CTL_ELEM_TYPE_IEC958 as isize,
- Integer64 = SND_CTL_ELEM_TYPE_INTEGER64 as isize,
-}
-
-impl fmt::Display for ElemType {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match self {
- ElemType::None => write!(f, "SND_CTL_ELEM_TYPE_NONE"),
- ElemType::Boolean => write!(f, "SND_CTL_ELEM_TYPE_BOOLEAN"),
- ElemType::Integer => write!(f, "SND_CTL_ELEM_TYPE_INTEGER"),
- ElemType::Enumerated => write!(f, "SND_CTL_ELEM_TYPE_ENUMERATED"),
- ElemType::Bytes => write!(f, "SND_CTL_ELEM_TYPE_BYTES"),
- ElemType::IEC958 => write!(f, "SND_CTL_ELEM_TYPE_IEC958"),
- ElemType::Integer64 => write!(f, "SND_CTL_ELEM_TYPE_INTEGER64"),
- }
- }
-}
-
-impl TryFrom<u32> for ElemType {
- type Error = Error;
- fn try_from(elem_type: u32) -> Result<ElemType> {
- match elem_type {
- SND_CTL_ELEM_TYPE_NONE => Ok(ElemType::None),
- SND_CTL_ELEM_TYPE_BOOLEAN => Ok(ElemType::Boolean),
- SND_CTL_ELEM_TYPE_INTEGER => Ok(ElemType::Integer),
- SND_CTL_ELEM_TYPE_ENUMERATED => Ok(ElemType::Enumerated),
- SND_CTL_ELEM_TYPE_BYTES => Ok(ElemType::Bytes),
- SND_CTL_ELEM_TYPE_IEC958 => Ok(ElemType::IEC958),
- SND_CTL_ELEM_TYPE_INTEGER64 => Ok(ElemType::Integer64),
- _ => Err(Error::InvalidElemType(elem_type)),
- }
- }
-}
-
-/// [snd_ctl_elem_id_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#gad6c3746f1925bfec6a4fd0e913430e55) wrapper.
-pub struct ElemId(
- ptr::NonNull<snd_ctl_elem_id_t>,
- PhantomData<snd_ctl_elem_id_t>,
-);
-
-impl Drop for ElemId {
- fn drop(&mut self) {
- // Safe because self.0.as_ptr() is a valid snd_ctl_elem_id_t*.
- unsafe { snd_ctl_elem_id_free(self.0.as_ptr()) };
- }
-}
-
-impl ElemId {
- /// Creates an `ElemId` object by `ElemIface` and name.
- ///
- /// # Errors
- ///
- /// * If memory allocation fails.
- /// * If ctl_name is not a valid CString.
- pub fn new(iface: ElemIface, ctl_name: &str) -> Result<ElemId> {
- let mut id_ptr = ptr::null_mut();
- // Safe because we provide a valid id_ptr to be filled,
- // and we validate the return code before using id_ptr.
- let rc = unsafe { snd_ctl_elem_id_malloc(&mut id_ptr) };
- if rc < 0 {
- return Err(Error::ElemIdMallocFailed(FFIError::Rc(rc)));
- }
- let id = ptr::NonNull::new(id_ptr).ok_or(Error::ElemIdMallocFailed(FFIError::NullPtr))?;
-
- // Safe because id.as_ptr() is a valid snd_ctl_elem_id_t*.
- unsafe { snd_ctl_elem_id_set_interface(id.as_ptr(), iface as u32) };
- let name = CString::new(ctl_name)?;
- // Safe because id.as_ptr() is a valid snd_ctl_elem_id_t* and name is a safe CString.
- unsafe { snd_ctl_elem_id_set_name(id.as_ptr(), name.as_ptr()) };
- Ok(ElemId(id, PhantomData))
- }
-
- /// Borrows the const inner pointer.
- pub fn as_ptr(&self) -> *const snd_ctl_elem_id_t {
- self.0.as_ptr()
- }
-
- /// Safe [snd_ctl_elem_id_get_name()] (https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#gaa6cfea3ac963bfdaeb8189e03e927a76) wrapper.
- ///
- /// # Errors
- ///
- /// * If snd_ctl_elem_id_get_name() fails.
- /// * If control element name is not a valid CString.
- /// * If control element name is not valid UTF-8 data.
- pub fn name(&self) -> Result<&str> {
- // Safe because self.as_ptr() is a valid snd_ctl_elem_id_t*.
- let name = unsafe { snd_ctl_elem_id_get_name(self.as_ptr()) };
- if name.is_null() {
- return Err(Error::ElemIdGetNameFailed);
- }
- // Safe because name is a valid *const i8, and its life time
- // is the same as the passed reference of self.
- let s = CStr::from_bytes_with_nul(unsafe {
- slice::from_raw_parts(name as *const u8, strlen(name) + 1)
- })?;
- Ok(s.to_str()?)
- }
-}
-
-/// [snd_ctl_elem_value_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#ga266b478eb64f1cdd75e337df4b4b995e) wrapper.
-pub struct ElemValue(
- ptr::NonNull<snd_ctl_elem_value_t>,
- PhantomData<snd_ctl_elem_value_t>,
-);
-
-impl Drop for ElemValue {
- // Safe because self.0.as_ptr() is valid.
- fn drop(&mut self) {
- unsafe { snd_ctl_elem_value_free(self.0.as_ptr()) };
- }
-}
-
-impl ElemValue {
- /// Creates an `ElemValue`.
- ///
- /// # Errors
- ///
- /// * If memory allocation fails.
- pub fn new(id: &ElemId) -> Result<ElemValue> {
- let mut v_ptr = ptr::null_mut();
- // Safe because we provide a valid v_ptr to be filled,
- // and we validate the return code before using v_ptr.
- let rc = unsafe { snd_ctl_elem_value_malloc(&mut v_ptr) };
- if rc < 0 {
- return Err(Error::ElemValueMallocFailed(FFIError::Rc(rc)));
- }
- let value =
- ptr::NonNull::new(v_ptr).ok_or(Error::ElemValueMallocFailed(FFIError::NullPtr))?;
- // Safe because value.as_ptr() is a valid snd_ctl_elem_value_t* and id.as_ptr() is also valid.
- unsafe { snd_ctl_elem_value_set_id(value.as_ptr(), id.as_ptr()) };
- Ok(ElemValue(value, PhantomData))
- }
-
- /// Borrows the mutable inner pointer.
- pub fn as_mut_ptr(&mut self) -> *mut snd_ctl_elem_value_t {
- self.0.as_ptr()
- }
-
- /// Borrows the const inner pointer.
- pub fn as_ptr(&self) -> *const snd_ctl_elem_value_t {
- self.0.as_ptr()
- }
-}
-
-/// [snd_ctl_elem_info_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#ga2cae0bb76df919368e4ff9a7021dd3ab) wrapper.
-pub struct ElemInfo(
- ptr::NonNull<snd_ctl_elem_info_t>,
- PhantomData<snd_ctl_elem_info_t>,
-);
-
-impl Drop for ElemInfo {
- fn drop(&mut self) {
- // Safe because self.0.as_ptr() is a valid snd_ctl_elem_info_t*.
- unsafe { snd_ctl_elem_info_free(self.0.as_ptr()) };
- }
-}
-
-impl ElemInfo {
- /// Creates an `ElemInfo`.
- ///
- /// # Errors
- ///
- /// * If memory allocation fails.
- /// * If control does not exist.
- pub fn new(handle: &mut Ctl, id: &ElemId) -> Result<ElemInfo> {
- let mut info_ptr = ptr::null_mut();
-
- // Safe because we provide a valid info_ptr to be filled,
- // and we validate the return code before using info_ptr.
- let rc = unsafe { snd_ctl_elem_info_malloc(&mut info_ptr) };
- if rc < 0 {
- return Err(Error::ElemInfoMallocFailed(FFIError::Rc(rc)));
- }
- let info =
- ptr::NonNull::new(info_ptr).ok_or(Error::ElemInfoMallocFailed(FFIError::NullPtr))?;
-
- // Safe because info.as_ptr() is a valid snd_ctl_elem_info_t* and id.as_ptr() is also valid.
- unsafe { snd_ctl_elem_info_set_id(info.as_ptr(), id.as_ptr()) };
-
- // Safe because handle.as_mut_ptr() is a valid snd_ctl_t* and info.as_ptr() is a valid
- // snd_ctl_elem_info_t*.
- let rc = unsafe { snd_ctl_elem_info(handle.as_mut_ptr(), info.as_ptr()) };
- if rc < 0 {
- return Err(Error::ControlNotFound(id.name()?.to_owned()));
- }
- Ok(ElemInfo(info, PhantomData))
- }
-
- /// Safe [snd_ctl_elem_info_get_type](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#ga0fec5d22ee58d04f14b59f405adc595e) wrapper.
- pub fn elem_type(&self) -> Result<ElemType> {
- // Safe because self.0.as_ptr() is a valid snd_ctl_elem_info_t*.
- unsafe { ElemType::try_from(snd_ctl_elem_info_get_type(self.0.as_ptr())) }
- }
-
- /// Safe [snd_ctl_elem_info_get_count](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#gaa75a20d4190d324bcda5fd6659a4b377) wrapper.
- pub fn count(&self) -> usize {
- // Safe because self.0.as_ptr() is a valid snd_ctl_elem_info_t*.
- unsafe { snd_ctl_elem_info_get_count(self.0.as_ptr()) as usize }
- }
-
- /// Safe [snd_ctl_elem_info_is_tlv_readable](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#gaac6bb412e5a9fffb5509e98a10de45b5) wrapper.
- pub fn tlv_readable(&self) -> bool {
- // Safe because self.0.as_ptr() is a valid snd_ctl_elem_info_t*.
- unsafe { snd_ctl_elem_info_is_tlv_readable(self.0.as_ptr()) as usize == 1 }
- }
-
- /// Safe [snd_ctl_elem_info_is_tlv_writable](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#gacfbaae80d710b6feac682f8ba10a0341) wrapper.
- pub fn tlv_writable(&self) -> bool {
- // Safe because self.0.as_ptr() is a valid snd_ctl_elem_info_t*.
- unsafe { snd_ctl_elem_info_is_tlv_writable(self.0.as_ptr()) as usize == 1 }
- }
-}
-
-/// [snd_ctl_t](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#ga06628f38def84a0fe3da74041db9d51f) wrapper.
-#[derive(Debug)]
-pub struct Ctl(ptr::NonNull<snd_ctl_t>, PhantomData<snd_ctl_t>);
-
-impl Drop for Ctl {
- fn drop(&mut self) {
- // Safe as we provide a valid snd_ctl_t*.
- unsafe { snd_ctl_close(self.0.as_ptr()) };
- }
-}
-
-impl Ctl {
- /// Creates a `Ctl`.
- /// Safe [snd_ctl_open](https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html#ga58537f5b74c9c1f51699f9908a0d7f56).
- /// Does not support async mode.
- ///
- /// # Errors
- ///
- /// * If `card` is an invalid CString.
- /// * If `snd_ctl_open()` fails.
- pub fn new(card: &str) -> Result<Ctl> {
- let name = CString::new(card)?;
- let mut ctl_ptr = ptr::null_mut();
- // Safe because we provide a valid ctl_ptr to be filled, name is a safe CString
- // and we validate the return code before using ctl_ptr.
- let rc = unsafe { snd_ctl_open(&mut ctl_ptr, name.as_ptr(), 0) };
- if rc < 0 {
- return Err(Error::CtlOpenFailed(
- FFIError::Rc(rc),
- name.to_str()?.to_owned(),
- ));
- }
- let ctl = ptr::NonNull::new(ctl_ptr).ok_or(Error::CtlOpenFailed(
- FFIError::NullPtr,
- name.to_str()?.to_owned(),
- ))?;
- Ok(Ctl(ctl, PhantomData))
- }
-
- /// Borrows the mutable inner pointer
- pub fn as_mut_ptr(&mut self) -> *mut snd_ctl_t {
- self.0.as_ptr()
- }
-}
-
-/// Safe [snd_strerror](https://www.alsa-project.org/alsa-doc/alsa-lib/group___error.html#ga182bbadf2349e11602bc531e8cf22f7e) wrapper.
-///
-/// # Errors
-///
-/// * If `snd_strerror` returns invalid UTF-8 data.
-pub fn snd_strerror(err_num: i32) -> Result<&'static str> {
- // Safe because we validate the return pointer of snd_strerror()
- // before using it.
- let s_ptr = unsafe { alsa_sys::snd_strerror(err_num) };
- if s_ptr.is_null() {
- return Err(Error::SndStrErrorFailed(err_num));
- }
- // Safe because s_ptr is a non-null *const u8 and its lifetime is static.
- let s = CStr::from_bytes_with_nul(unsafe {
- slice::from_raw_parts(s_ptr as *const u8, strlen(s_ptr) + 1)
- })?;
- Ok(s.to_str()?)
-}
diff --git a/cros_alsa/src/control_tlv.rs b/cros_alsa/src/control_tlv.rs
deleted file mode 100644
index e1f35510..00000000
--- a/cros_alsa/src/control_tlv.rs
+++ /dev/null
@@ -1,313 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! `ControlTLV` supports read and write of the alsa TLV byte controls
-//! Users can obtain a ControlTLV by Card::control_tlv_by_name().
-//! # Examples
-//! This is an example of how to use a `TLV`.
-//!
-//! ```
-//! use std::assert_eq;
-//! use std::convert::TryFrom;
-//! use std::error::Error;
-//!
-//! use cros_alsa::{TLV, ControlTLVError};
-//! use cros_alsa::elem::Elem;
-//!
-//! type Result<T> = std::result::Result<T, ControlTLVError>;
-//!
-//! let mut tlv = TLV::new(0, vec![1,2,3,4]);
-//! assert_eq!(4, tlv.len());
-//! assert_eq!(0, tlv.tlv_type());
-//! assert_eq!(2, tlv[1]);
-//! tlv[1] = 8;
-//! assert_eq!(vec![1,8,3,4], tlv.value().to_vec());
-//! assert_eq!(vec![0,16,1,8,3,4], Into::<Vec<u32>>::into(tlv));
-//!
-//! ```
-
-use std::{
- convert::TryFrom,
- fmt,
- ops::{Index, IndexMut},
- slice::SliceIndex,
-};
-use std::{error, mem::size_of};
-
-use remain::sorted;
-
-use crate::control_primitive::{self, Ctl, ElemId, ElemInfo, ElemType};
-
-/// The Result type of cros-alsa::control.
-pub type Result<T> = std::result::Result<T, Error>;
-
-#[sorted]
-#[derive(Debug, PartialEq)]
-/// Possible errors that can occur in cros-alsa::control.
-pub enum Error {
- /// Failed to call AlsaControlAPI.
- AlsaControlAPI(control_primitive::Error),
- /// Failed to convert buffer to TLV struct.
- InvalidTLV,
- /// ElemInfo::count() is not multiple of size_of::<u32>.
- InvalidTLVSize(String, usize),
- /// ElemInfo::elem_type() is not ElemType::Bytes.
- InvalidTLVType(String, ElemType),
- /// The control is not readable.
- TLVNotReadable,
- /// The control is not writeable.
- TLVNotWritable,
- /// Failed to call snd_ctl_elem_tlv_read.
- TLVReadFailed(i32),
- /// Failed to call snd_ctl_elem_tlv_write.
- TVLWriteFailed(i32),
-}
-
-impl error::Error for Error {}
-
-impl From<control_primitive::Error> for Error {
- fn from(err: control_primitive::Error) -> Error {
- Error::AlsaControlAPI(err)
- }
-}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- AlsaControlAPI(e) => write!(f, "{}", e),
- InvalidTLV => write!(f, "failed to convert to TLV"),
- InvalidTLVSize(name, elem_size) => write!(
- f,
- "ElemInfo::size() of {} should be multiple of size_of::<u32>, get: {}",
- name, elem_size
- ),
- InvalidTLVType(name, elem_type) => write!(
- f,
- "invalid ElemInfo::elem_type() of {}: expect: {}, get: {}",
- name,
- ElemType::Bytes,
- elem_type
- ),
- TLVNotReadable => write!(f, "the control is not readable."),
- TLVNotWritable => write!(f, "the control is not writable."),
- TLVReadFailed(rc) => write!(f, "snd_ctl_elem_tlv_read failed: {}", rc),
- TVLWriteFailed(rc) => write!(f, "snd_ctl_elem_tlv_write failed: {}", rc),
- }
- }
-}
-
-/// TLV struct represents the TLV data to be read from
-/// or write to an alsa TLV byte control.
-#[derive(Debug)]
-pub struct TLV {
- /// data[Self::TYPE_OFFSET] contains the tlv type.
- /// data[Self::LEN_OFFSET] contains the length of the value in bytes.
- /// data[Self::VALUE_OFFSET..] contains the data.
- data: Vec<u32>,
-}
-
-impl TLV {
- const TYPE_OFFSET: usize = 0;
- const LEN_OFFSET: usize = 1;
- const VALUE_OFFSET: usize = 2;
- const TLV_HEADER_SIZE_BYTES: usize = Self::VALUE_OFFSET * size_of::<u32>();
-
- /// Initializes a `TLV` by giving the tlv type and tlv value.
- pub fn new(tlv_type: u32, tlv_value: Vec<u32>) -> Self {
- let mut data = vec![0; 2];
- data[Self::TYPE_OFFSET] = tlv_type;
- data[Self::LEN_OFFSET] = (tlv_value.len() * size_of::<u32>()) as u32;
- data.extend(tlv_value.iter());
- Self { data }
- }
-
- /// Returns the type of the tlv.
- pub fn tlv_type(&self) -> u32 {
- self.data[Self::TYPE_OFFSET]
- }
-
- /// Returns the length of the tlv value in dword.
- pub fn len(&self) -> usize {
- self.data[Self::LEN_OFFSET] as usize / size_of::<u32>()
- }
-
- /// Returns whether the tlv value is empty.
- pub fn is_empty(&self) -> bool {
- self.data[Self::LEN_OFFSET] == 0
- }
-
- /// Returns the tlv value in slice.
- pub fn value(&self) -> &[u32] {
- &self.data[Self::VALUE_OFFSET..]
- }
-}
-
-impl<I: SliceIndex<[u32]>> Index<I> for TLV {
- type Output = I::Output;
- #[inline]
- fn index(&self, index: I) -> &Self::Output {
- &self.data[Self::VALUE_OFFSET..][index]
- }
-}
-
-impl<I: SliceIndex<[u32]>> IndexMut<I> for TLV {
- #[inline]
- fn index_mut(&mut self, index: I) -> &mut Self::Output {
- &mut self.data[Self::VALUE_OFFSET..][index]
- }
-}
-
-impl TryFrom<Vec<u32>> for TLV {
- type Error = Error;
-
- /// Constructs a TLV from a vector with the following alsa tlv header validation:
- /// 1 . tlv_buf[Self::LEN_OFFSET] should be multiple of size_of::<u32>
- /// 2 . tlv_buf[Self::LEN_OFFSET] is the length of tlv value in byte and
- /// should be less than the buffer length * size_of::<u32>.
- fn try_from(data: Vec<u32>) -> Result<Self> {
- if data.len() < 2 {
- return Err(Error::InvalidTLV);
- }
-
- if data[Self::LEN_OFFSET] % size_of::<u32>() as u32 != 0 {
- return Err(Error::InvalidTLV);
- }
-
- if data[Self::LEN_OFFSET] / size_of::<u32>() as u32
- > data[Self::VALUE_OFFSET..].len() as u32
- {
- return Err(Error::InvalidTLV);
- }
-
- Ok(Self { data })
- }
-}
-
-impl Into<Vec<u32>> for TLV {
- /// Returns the raw tlv data buffer (including the tlv header).
- fn into(self) -> Vec<u32> {
- self.data
- }
-}
-
-/// `ControlTLV` supports read and write of the alsa TLV byte controls.
-pub struct ControlTLV<'a> {
- handle: &'a mut Ctl,
- id: ElemId,
-}
-
-impl<'a> ControlTLV<'a> {
- /// Called by `Card` to create a `ControlTLV`.
- pub fn new(handle: &'a mut Ctl, id: ElemId) -> Result<Self> {
- let info = ElemInfo::new(handle, &id)?;
- if info.count() % size_of::<u32>() != 0 {
- return Err(Error::InvalidTLVSize(id.name()?.to_owned(), info.count()));
- }
- match info.elem_type()? {
- ElemType::Bytes => Ok(Self { handle, id }),
- _ => Err(Error::InvalidTLVType(
- id.name()?.to_owned(),
- info.elem_type()?,
- )),
- }
- }
-
- /// Reads data from the byte control by `snd_ctl_elem_tlv_read`
- ///
- /// #
- /// # Errors
- ///
- /// * If it fails to read from the control.
- pub fn load(&mut self) -> Result<TLV> {
- if !ElemInfo::new(self.handle, &self.id)?.tlv_readable() {
- return Err(Error::TLVNotReadable);
- }
-
- let tlv_size = ElemInfo::new(self.handle, &self.id)?.count() + TLV::TLV_HEADER_SIZE_BYTES;
-
- let mut tlv_buf = vec![0; tlv_size / size_of::<u32>()];
- // Safe because handle.as_mut_ptr() is a valid *mut snd_ctl_t, id_as_ptr is valid and
- // tlv_buf.as_mut_ptr() is also valid.
- let rc = unsafe {
- alsa_sys::snd_ctl_elem_tlv_read(
- self.handle.as_mut_ptr(),
- self.id.as_ptr(),
- tlv_buf.as_mut_ptr(),
- tlv_size as u32,
- )
- };
- if rc < 0 {
- return Err(Error::TLVReadFailed(rc));
- }
- Ok(TLV::try_from(tlv_buf)?)
- }
-
- /// Writes to the byte control by `snd_ctl_elem_tlv_write`
- ///
- /// # Results
- ///
- /// * `changed` - false on success.
- /// - true on success when value was changed.
- /// #
- /// # Errors
- ///
- /// * If it fails to write to the control.
- pub fn save(&mut self, tlv: TLV) -> Result<bool> {
- if !ElemInfo::new(self.handle, &self.id)?.tlv_writable() {
- return Err(Error::TLVNotReadable);
- }
- // Safe because handle.as_mut_ptr() is a valid *mut snd_ctl_t, id_as_ptr is valid and
- // tlv.as_mut_ptr() is also valid.
- let rc = unsafe {
- alsa_sys::snd_ctl_elem_tlv_write(
- self.handle.as_mut_ptr(),
- self.id.as_ptr(),
- Into::<Vec<u32>>::into(tlv).as_mut_ptr(),
- )
- };
- if rc < 0 {
- return Err(Error::TVLWriteFailed(rc));
- }
- Ok(rc > 0)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- #[test]
- fn test_tlv_try_from_raw_vec() {
- let tlv_buf = vec![0, 12, 2, 3, 4];
- assert!(TLV::try_from(tlv_buf).is_ok());
- }
-
- #[test]
- fn test_tlv_length_is_not_multiple_of_sizeof_int() {
- // Invalid tlv length in data[Self::LEN_OFFSET].
- let tlv_buf = vec![0, 1, 2, 3, 4];
- assert_eq!(TLV::try_from(tlv_buf).unwrap_err(), Error::InvalidTLV);
- }
-
- #[test]
- fn test_tlv_length_larger_than_buff_size() {
- // Invalid tlv length in data[Self::LEN_OFFSET].
- let tlv_buf = vec![0, 16, 2, 3, 4];
- assert_eq!(TLV::try_from(tlv_buf).unwrap_err(), Error::InvalidTLV);
- }
-
- #[test]
- fn test_tlv_length_less_than_two() {
- // tlv buffer length < 2
- let tlv_buf = vec![0];
- assert_eq!(TLV::try_from(tlv_buf).unwrap_err(), Error::InvalidTLV);
- }
-
- #[test]
- fn test_tlv_length_equal_two() {
- // tlv buffer size = 2.
- let tlv_buf = vec![0, 0];
- assert!(TLV::try_from(tlv_buf).is_ok());
- }
-}
diff --git a/cros_alsa/src/elem.rs b/cros_alsa/src/elem.rs
deleted file mode 100644
index 08fe8b62..00000000
--- a/cros_alsa/src/elem.rs
+++ /dev/null
@@ -1,204 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! This module provides different implementations of `Elem` that use the alsa-lib control interface
-//! API to read and write alsa control elements.
-//!
-//! The `Elem::type()` returns the type of value that a control element can interact with,
-//! and it is one of integer, integer64, boolean, enumerators, bytes or IEC958 structure.
-//! The `Elem::size()` returns the number of values it reads from or writes to the hardware
-//! at a time.
-//! The `Elem::load(..)` and `Elem::save(..)` are used by `ControlOps` trait to read and write
-//! the underlying mixer control.
-//!
-//! Users should use the provided implementations of `Elem` to define the associated type in
-//! their owner encapsulation of `Control`.
-
-use std::default::Default;
-use std::error;
-use std::fmt;
-
-use libc::{c_long, c_uint};
-use remain::sorted;
-
-use crate::control_primitive::{self, snd_strerror, Ctl, ElemId, ElemType, ElemValue};
-
-/// The Result type of cros-alsa::elem.
-pub type Result<T> = std::result::Result<T, Error>;
-
-#[sorted]
-#[derive(Debug)]
-/// Possible errors that can occur in cros-alsa::elem.
-pub enum Error {
- /// Failed to call AlsaControlAPI.
- AlsaControlAPI(control_primitive::Error),
- /// Failed to call `snd_ctl_elem_read()`.
- ElemReadFailed(i32),
- /// Failed to call `snd_ctl_elem_write()`.
- ElemWriteFailed(i32),
-}
-
-impl error::Error for Error {}
-
-impl From<control_primitive::Error> for Error {
- fn from(err: control_primitive::Error) -> Error {
- Error::AlsaControlAPI(err)
- }
-}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- AlsaControlAPI(e) => write!(f, "{}", e),
- ElemReadFailed(e) => write!(f, "snd_ctl_elem_read failed: {}", snd_strerror(*e)?),
- ElemWriteFailed(e) => write!(f, "snd_ctl_elem_write failed: {}", snd_strerror(*e)?),
- }
- }
-}
-
-// Uses a recursive macro to generate implementation for [bool; n] and [i32; n], n = 1 to 128.
-// The `$t:ident $($ts:ident)*` part matches and removes one token at a time. It's used for
-// counting recursive steps.
-macro_rules! impl_for_array {
- {$n:expr, $type:ty, $t:ident $($ts:ident)*} => {
- impl Elem for [$type; $n] {
- type T = Self;
- /// Reads [$type; $n] data from the mixer control.
- ///
- /// # Errors
- ///
- /// * If it fails to call `snd_ctl_elem_read()`.
- fn load(handle: &mut Ctl, id: &ElemId) -> Result<Self::T>
- {
- let mut elem = ElemValue::new(id)?;
- // Safe because self.handle.as_mut_ptr() is a valid *mut snd_ctl_t and
- // elem.as_mut_ptr() is also a valid *mut snd_ctl_elem_value_t.
- let rc = unsafe { alsa_sys::snd_ctl_elem_read(handle.as_mut_ptr(), elem.as_mut_ptr()) };
- if rc < 0 {
- return Err(Error::ElemReadFailed(rc));
- }
- let mut ret = [Default::default(); $n];
- for i in 0..$n {
- // Safe because elem.as_ptr() is a valid snd_ctl_elem_value_t* and i is guaranteed to be
- // within a valid range.
- ret[i] = unsafe { <$type>::elem_value_get(&elem, i) };
- }
- Ok(ret)
- }
-
- /// Updates [$type; $n] data to the mixer control.
- ///
- /// # Results
- ///
- /// * `changed` - false on success.
- /// - true on success when value was changed.
- ///
- /// # Errors
- ///
- /// * If it fails to call `snd_ctl_elem_write()`.
- fn save(handle: &mut Ctl, id: &ElemId, val: Self::T) -> Result<bool> {
- let mut elem = ElemValue::new(id)?;
- for i in 0..$n {
- // Safe because elem.as_mut_ptr() is a valid snd_ctl_elem_value_t* and i is guaranteed to be
- // within a valid range.
- unsafe { <$type>::elem_value_set(&mut elem, i, val[i]) };
- }
- // Safe because self.handle.as_mut_ptr() is a valid *mut snd_ctl_t and
- // elem.as_mut_ptr() is also a valid *mut snd_ctl_elem_value_t.
- let rc = unsafe { alsa_sys::snd_ctl_elem_write(handle.as_mut_ptr(), elem.as_mut_ptr()) };
- if rc < 0 {
- return Err(Error::ElemWriteFailed(rc));
- }
- Ok(rc > 0)
- }
-
- /// Gets the data type itself can read and write.
- fn elem_type() -> ElemType {
- <$type>::elem_type()
- }
-
- /// Gets the number of value entries itself can read and write.
- fn size() -> usize {
- $n
- }
- }
- impl_for_array!{($n - 1), $type, $($ts)*}
- };
- {$n:expr, $type:ty,} => {};
-}
-
-// Implements `Elem` for [i32; n] where n = 1 to 128.
-impl_for_array! {128, i32,
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-}
-
-// Implements `Elem` for [bool; n] where n = 1 to 128.
-impl_for_array! {128, bool,
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T
-}
-
-impl CtlElemValue for bool {
- type T = bool;
- /// Gets a bool from the ElemValue.
- unsafe fn elem_value_get(elem: &ElemValue, idx: usize) -> bool {
- alsa_sys::snd_ctl_elem_value_get_boolean(elem.as_ptr(), idx as c_uint) != 0
- }
- /// Sets a bool to the ElemValue.
- unsafe fn elem_value_set(elem: &mut ElemValue, idx: usize, val: bool) {
- alsa_sys::snd_ctl_elem_value_set_boolean(elem.as_mut_ptr(), idx as c_uint, val as c_long);
- }
- /// Returns ElemType::Boolean.
- fn elem_type() -> ElemType {
- ElemType::Boolean
- }
-}
-
-impl CtlElemValue for i32 {
- type T = i32;
- /// Gets an i32 from the ElemValue.
- unsafe fn elem_value_get(elem: &ElemValue, idx: usize) -> i32 {
- alsa_sys::snd_ctl_elem_value_get_integer(elem.as_ptr(), idx as c_uint) as i32
- }
- /// Sets an i32 to the ElemValue.
- unsafe fn elem_value_set(elem: &mut ElemValue, idx: usize, val: i32) {
- alsa_sys::snd_ctl_elem_value_set_integer(elem.as_mut_ptr(), idx as c_uint, val as c_long);
- }
- /// Returns ElemType::Integer.
- fn elem_type() -> ElemType {
- ElemType::Integer
- }
-}
-
-/// All primitive types of a control element should implement `CtlElemValue` trait.
-trait CtlElemValue {
- /// The primitive type of a control element.
- type T;
- /// Gets the value from the ElemValue.
- unsafe fn elem_value_get(value: &ElemValue, idx: usize) -> Self::T;
- /// Sets the value to the ElemValue.
- unsafe fn elem_value_set(value: &mut ElemValue, id: usize, val: Self::T);
- /// Gets the data type itself can read and write.
- fn elem_type() -> ElemType;
-}
-
-/// Use `Elem` trait to access the underlying control element through the given `Ctl` and `ElemId`.
-pub trait Elem: Sized {
- /// The data type of a control element.
- type T;
- /// Reads the value from the mixer control.
- fn load(handle: &mut Ctl, id: &ElemId) -> Result<Self::T>;
- /// Saves the value to the mixer control.
- fn save(handle: &mut Ctl, id: &ElemId, val: Self::T) -> Result<bool>;
- /// Gets the data type itself can read and write.
- fn elem_type() -> ElemType;
- /// Gets the number of value entries itself can read and write.
- fn size() -> usize;
-}
diff --git a/cros_alsa/src/lib.rs b/cros_alsa/src/lib.rs
deleted file mode 100644
index 070d221a..00000000
--- a/cros_alsa/src/lib.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-//! `cros_alsa` crate currently supports interacting with alsa
-//! controls by using the control interface API of alsa-lib.
-//!
-//! # Examples
-//! This is an example of how to use the provided `Control` objects.
-//!
-//! ``` no_run
-//! use std::error::Error;
-//! use std::result::Result;
-//!
-//! use cros_alsa::{Card, SwitchControl, IntControl, StereoVolumeControl};
-//!
-//! fn main() -> Result<(), Box<dyn Error>> {
-//!
-//! let mut card = Card::new("sofmax98390d")?;
-//!
-//! // Uses a SwitchControl to turn on and off a mixer control that has a single boolean state.
-//! let mut calib_ctrl:SwitchControl = card.control_by_name("Left DSM Calibration")?;
-//! calib_ctrl.on()?;
-//! assert_eq!(calib_ctrl.state()?, true);
-//! calib_ctrl.off()?;
-//!
-//! // Uses an IntControl to read and write a mixer control that has a single integer value.
-//! let mut rdc_ctrl:IntControl = card.control_by_name("Left Rdc")?;
-//! let _rdc = rdc_ctrl.get()?;
-//! rdc_ctrl.set(13000)?;
-//!
-//! // Uses a StereoVolumeControl to manipulate stereo volume related functionality.
-//! let mut volume_ctrl:StereoVolumeControl = card.control_by_name("Master Playback Volume")?;
-//! volume_ctrl.set_volume(184, 184)?;
-//!
-//! Ok(())
-//! }
-//! ```
-
-// Allow the maximum recursive depth = 256 for macro expansion.
-#![recursion_limit = "256"]
-#![deny(missing_docs)]
-
-mod card;
-mod control;
-mod control_primitive;
-pub mod control_tlv;
-pub mod elem;
-
-pub use self::card::Card;
-pub use self::control::{Control, ControlOps, IntControl, StereoVolumeControl, SwitchControl};
-pub use self::control_primitive::{Ctl, ElemId};
-pub use self::control_tlv::{ControlTLV, TLV};
-
-pub use self::card::Error as CardError;
-pub use self::control::Error as ControlError;
-pub use self::control_tlv::Error as ControlTLVError;
-pub use self::elem::Error as ElemError;
-
-#[allow(unused_imports)]
-pub use cros_alsa_derive::*;
diff --git a/dbus-config/org.chromium.cras.conf b/dbus-config/org.chromium.cras.conf
deleted file mode 100644
index bd1ecc9f..00000000
--- a/dbus-config/org.chromium.cras.conf
+++ /dev/null
@@ -1,13 +0,0 @@
-<!DOCTYPE busconfig PUBLIC
- "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
- "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
-<busconfig>
- <policy context="default">
- <allow send_destination="org.chromium.cras" />
- </policy>
-
- <policy user="cras">
- <allow own="org.chromium.cras" />
- </policy>
-
-</busconfig>
diff --git a/defs/c.mk b/defs/c.mk
deleted file mode 100644
index 012d973f..00000000
--- a/defs/c.mk
+++ /dev/null
@@ -1,117 +0,0 @@
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This file contains definitions which control the C compiler.
-
-
-COPTIONS = \
- -g \
- -O2 \
- -funit-at-a-time
-
-# Compiler is too old to support
-#
-# -Wframe-larger-than=256
-# -Wlarger-than=4096
-# -Wsync-nand
-
-# Enable GC on unused functions and data
-CGC = \
- -ffunction-sections \
- -fdata-sections
-
-PTHREAD = \
- -pthread
-
-LDGC = \
- -Xlinker --gc-sections
-
-CWARN = \
- -Waddress \
- -Waggregate-return \
- -Wall \
- -Warray-bounds \
- -Wbad-function-cast \
- -Wcast-align \
- -Wchar-subscripts \
- -Wclobbered \
- -Wcomment \
- -Wconversion \
- -Wdeclaration-after-statement \
- -Wdisabled-optimization \
- -Wempty-body \
- -Werror \
- -Wextra \
- -Wfloat-equal \
- -Wformat \
- -Wformat-nonliteral \
- -Wformat-security \
- -Wformat-y2k \
- -Wignored-qualifiers \
- -Wimplicit \
- -Winit-self \
- -Winline \
- -Wlogical-op \
- -Wmain \
- -Wmissing-braces \
- -Wmissing-declarations \
- -Wmissing-field-initializers \
- -Wmissing-format-attribute \
- -Wmissing-include-dirs \
- -Wmissing-noreturn \
- -Wmissing-parameter-type \
- -Wmissing-prototypes \
- -Wnested-externs \
- -Wold-style-declaration \
- -Wold-style-definition \
- -Woverlength-strings \
- -Woverride-init \
- -Wpacked \
- -Wparentheses \
- -Wpointer-arith \
- -Wpointer-sign \
- -Wredundant-decls \
- -Wreturn-type \
- -Wsequence-point \
- -Wshadow \
- -Wsign-compare \
- -Wsign-conversion \
- -Wstack-protector \
- -Wstrict-aliasing \
- -Wstrict-aliasing=3 \
- -Wstrict-overflow \
- -Wstrict-overflow=5 \
- -Wstrict-prototypes \
- -Wswitch \
- -Wswitch-default \
- -Wswitch-enum \
- -Wtrigraphs \
- -Wtype-limits \
- -Wundef \
- -Wuninitialized \
- -Wunknown-pragmas \
- -Wunsafe-loop-optimizations \
- -Wunused-function \
- -Wunused-label \
- -Wunused-parameter \
- -Wunused-value \
- -Wunused-variable \
- -Wvariadic-macros \
- -Wvla \
- -Wvolatile-register-var \
- -Wwrite-strings \
- -pedantic-errors
-
-INCLUDES = \
- -I$(ADHD_DIR)/include \
- -I$(ADHD_SOURCE_DIR) \
- -I$(ADHD_DIR)/cras/src/common \
- -I$(ADHD_DIR)/cras/src/libcras
-
-CFLAGS = \
- -std=gnu99 \
- -MD \
- $(INCLUDES) \
- $(PTHREADS) \
- $(CWARN) $(COPTIONS) $(CGC) $(LDGC)
diff --git a/defs/definitions.mk b/defs/definitions.mk
deleted file mode 100644
index d1085d42..00000000
--- a/defs/definitions.mk
+++ /dev/null
@@ -1,7 +0,0 @@
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-include $(ADHD_DIR)/defs/utilities.mk
-include $(ADHD_DIR)/defs/c.mk
-include $(ADHD_DIR)/defs/make.mk
diff --git a/defs/make.mk b/defs/make.mk
deleted file mode 100644
index c9d2d257..00000000
--- a/defs/make.mk
+++ /dev/null
@@ -1,70 +0,0 @@
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This file contains definitions that are specific to the invocation
-# and usage of Gnu Make.
-
-ifndef VERBOSE
-# Be silent unless 'VERBOSE' is set on the make command line.
-SILENT = --silent
-endif
-
-ifndef ADHD_BUILD_DIR
-export ADHD_BUILD_DIR = $(ADHD_DIR)/build/$(BOARD)
-endif
-
-GAVD_ARCHIVE = $(ADHD_BUILD_DIR)/lib/gavd.a
-
-LIBS = \
- -L$(ADHD_DIR)/cras/src/.libs \
- $(GAVD_ARCHIVE) \
- $(foreach lib,$(MY_LIBS),-l$(lib))
-
-# mkdir: Creates a directory, and all its parents, if it does not exist.
-#
-mkdir = [ ! -d $(1) ] && \
- $(MKDIR) --parents $(1) || true
-
-# remake: Gnu Make function which will create the build directory,
-# then build the first argument by recursively invoking make.
-# The recursive make is performed in the build directory.
-#
-# $(call remake,<label>,<subdirectory>,<makefile>,<target>)
-#
-# ex: @$(call remake,Building,gavd,Makefile,gavd)
-# $(1) $(2) $(3) $(4)
-#
-# REL_DIR:
-#
-# Directory relative from the root of the source tree. REL_DIR is
-# built up using the previous value plus the current target
-# directory.
-#
-# ADHD_SOURCE_DIR:
-#
-# The directory containing the sources for the target directory
-# being built. This is used by Makefiles to access files in the
-# source directory. It has the same value as VPATH.
-#
-# THIS_BUILD_DIR:
-#
-# The build directory which is currently being built. This is the
-# same 'pwd', and the directory in which Make is building.
-#
-# The build is performed in the build directory and VPATH is used to
-# allow Make to find the source files in the source directory.
-#
-remake = \
- +($(if $(REL_DIR), \
- export REL_DIR=$${REL_DIR}/$(2), \
- export REL_DIR=$(2)) && \
- $(call mkdir,$(ADHD_BUILD_DIR)/$${REL_DIR}) && \
- $(MESSAGE) "$(1) $${REL_DIR}"; \
- $(MAKE) $(SILENT) \
- -f $(ADHD_DIR)/$${REL_DIR}/$(3) \
- -C $(ADHD_BUILD_DIR)/$${REL_DIR} \
- VPATH=$(ADHD_DIR)/$${REL_DIR} \
- ADHD_SOURCE_DIR=$(ADHD_DIR)/$${REL_DIR} \
- THIS_BUILD_DIR=$(ADHD_BUILD_DIR)/$${REL_DIR} \
- $(4))
diff --git a/defs/utilities.mk b/defs/utilities.mk
deleted file mode 100644
index 8bc4c046..00000000
--- a/defs/utilities.mk
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This file contains definitions of utilities which are used by the
-# build system. No utility should be used directly by-name in the
-# makefiles; instead, each utility should have a definition here and
-# the macro value should be used.
-#
-# This makes it easy to ensure there are no host OS utility
-# dependencies when cross compiling.
-
-export MKDIR = /bin/mkdir
-export AR = /usr/bin/ar
-export ECHO = /bin/echo
-export MESSAGE = $(ECHO) "$(foreach v,$(shell seq $(MAKELEVEL))," ") [$(MAKELEVEL)] "
-export INSTALL = /usr/bin/install
-export LINK = /bin/ln
diff --git a/init/cras-directories.conf b/init/cras-directories.conf
deleted file mode 100644
index 4a79a186..00000000
--- a/init/cras-directories.conf
+++ /dev/null
@@ -1 +0,0 @@
-d /run/cras 1770 cras cras -
diff --git a/init/cras.conf b/init/cras.conf
deleted file mode 100644
index 20847494..00000000
--- a/init/cras.conf
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Installed by ADHD package.
-# cras upstart job.
-
-description "Chrome OS audio server"
-author "chromium-os-dev@chromium.org"
-
-env CRAS_SOCKET_DIR=/run/cras
-env CRAS_VMS_SOCKET_DIR=/run/cras/vms
-env CRAS_PLUGIN_DIR=/run/cras/vms/plugin
-env CRAS_ARGS=
-
-start on starting system-services
-stop on stopping system-services
-respawn
-
-# Allow the audio server real time priority.
-limit rtprio 12 12
-
-pre-start script
- mkdir -p -m 1770 "${CRAS_SOCKET_DIR}"
- chown -R cras:cras "${CRAS_SOCKET_DIR}"
- mkdir -p -m 1770 "${CRAS_VMS_SOCKET_DIR}"
- chown -R cras:cras "${CRAS_VMS_SOCKET_DIR}"
- for socket_dir in playback unified; do
- mkdir -p -m 1770 "${CRAS_PLUGIN_DIR}/${socket_dir}"
- chown -R cras:cras "${CRAS_PLUGIN_DIR}/${socket_dir}"
- done
- mkdir -m 0755 -p /var/lib/cras
- chown -R cras:cras /var/lib/cras
-end script
-
-exec /bin/sh /usr/share/cros/init/cras.sh
-
-# sound_card_init uses CRAS stop timestamp as a criterion to skip boot time
-# calibration for DSM.
-post-stop script
- echo "$(date +---%\nsecs:\ %s%\nnanos:\ %N)" > /var/lib/cras/stop
-end script
diff --git a/init/cras.service b/init/cras.service
deleted file mode 100644
index bda61c12..00000000
--- a/init/cras.service
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2016 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-[Unit]
-Description=ChromeOS audio server
-PartOf=system-services.target
-After=system-services.target
-
-[Service]
-Restart=on-failure
-LimitRTPRIO=12
-TimeoutStopSec=20
-ExecStart=/bin/sh /usr/share/cros/init/cras.sh
diff --git a/init/cras.sh b/init/cras.sh
deleted file mode 100644
index 91114c00..00000000
--- a/init/cras.sh
+++ /dev/null
@@ -1,64 +0,0 @@
-# Copyright 2016 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Unified build config.
-device_config_dir="$(cros_config /audio/main cras-config-dir)"
-internal_ucm_suffix="$(cros_config /audio/main ucm-suffix)"
-
-# Deprecate HSP since it's just too old.
-# TODO(hychao): Clean up all CRAS codes that are related to HSP once we're
-# sure no headset breaks because of that.
-DISABLE_PROFILE="--disable_profile=hsp"
-
-# Handle legacy config.
-if [ -z "${device_config_dir}" ]; then
- # Disable HSP/HFP on Google WiFi (Gale) with UART-HCI Bluetooth
- # which is incapable of handling SCO audio.
- platform_name="$(mosys platform name)"
- if [ "$platform_name" = "Gale" ]; then
- DISABLE_PROFILE="--disable_profile=hfp,hsp"
- fi
- # For boards that need a different device config, check which config
- # directory to use. Use that directory for both volume curves
- # and DSP config.
- if [ -f /etc/cras/get_device_config_dir ]; then
- device_config_dir="$(sh /etc/cras/get_device_config_dir)"
- fi
- if [ -f /etc/cras/get_internal_ucm_suffix ]; then
- internal_ucm_suffix="$(sh /etc/cras/get_internal_ucm_suffix)"
- fi
-else
- device_config_dir="/etc/cras/${device_config_dir}"
-fi
-
-if [ -n "${device_config_dir}" ]; then
- DEVICE_CONFIG_DIR="--device_config_dir=${device_config_dir}"
- DSP_CONFIG="--dsp_config=${device_config_dir}/dsp.ini"
-fi
-if [ -n "${internal_ucm_suffix}" ]; then
- INTERNAL_UCM_SUFFIX="--internal_ucm_suffix=${internal_ucm_suffix}"
-fi
-
-# Leave cras in the init pid namespace as it uses its PID as an IPC identifier.
-exec minijail0 -u cras -g cras -G --uts -v -l \
- -T static \
- -P /mnt/empty \
- -b /,/ \
- -k 'tmpfs,/run,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
- -b /run/cras,/run/cras,1 \
- -b /run/dbus,/run/dbus,1 \
- -b /run/udev,/run/udev \
- -b /dev,/dev \
- -b /dev/shm,/dev/shm,1 \
- -k proc,/proc,proc \
- -b /sys,/sys \
- -k 'tmpfs,/var,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
- -b /var/lib/metrics/,/var/lib/metrics/,1 \
- -- \
- /sbin/minijail0 -n \
- -S /usr/share/policy/cras-seccomp.policy \
- -- \
- /usr/bin/cras \
- ${DSP_CONFIG} ${DEVICE_CONFIG_DIR} ${DISABLE_PROFILE} \
- ${INTERNAL_UCM_SUFFIX} ${CRAS_ARGS}
diff --git a/scripts/asoc_dapm_graph b/scripts/asoc_dapm_graph
deleted file mode 100755
index fd43736d..00000000
--- a/scripts/asoc_dapm_graph
+++ /dev/null
@@ -1,95 +0,0 @@
-#!/usr/bin/env python
-# Copyright 2014 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Dump DAPM widgets status as a 'dot' graph file.
-
-To generate widget status for a device run
- ssh $REMOTE asoc_dapm_graph > dot.txt && dot -Kfdp -Tpng dot.txt -o widgets.png
-"""
-
-from __future__ import print_function
-import os
-import platform
-import re
-import sys
-import time
-
-ROOTDIR = '/sys/kernel/debug/asoc/'
-# Some widget names are widely used by many codecs, adding them to the graph
-# creates a mess.
-IGNORE_WIDGETS = ('Playback', 'Capture', 'bias_level')
-
-
-def handle_widgets(path):
- """Reads DAPM widget information from sysfs and generates dot graph entry.
-
- Args:
- path: path for sysfs file that exports information about DAPM widget.
- """
- for w in os.listdir(path):
- if w in IGNORE_WIDGETS:
- continue
-
- with open(os.path.join(path, w)) as f:
- lines = f.readlines()
-
- active = lines[0].startswith(w + ': On ')
- color = 'green' if active else 'red'
- print('\t"%s" [color = %s]' % (w, color))
-
- for l in lines[1:]:
- l = l.rstrip()
- # The string format is (in/out) "switch" "widget".
- edge = list(filter(None, re.split(r' (in|out) "(.+)" "(.+)"', l)))
-
- if len(edge) != 3:
- continue
-
- direction = edge[0]
- source = edge[2]
-
- if source in IGNORE_WIDGETS:
- continue
-
- # We need to output the edge only once (e.g. inbound).
- if direction != 'in':
- continue
-
- print('\t"%s" -> "%s"' % (source, w))
-
-
-def handle_card(path):
- """Generates dot graph file for the given card.
-
- Args:
- path: path to sysfs directory that exports DAPM information for a sound card.
- """
- host = platform.uname()[1]
- print('// Generated %s at %s.' % (time.strftime("%c"), host))
- print('// To visualize the graph run "dot -Kfdp -Tpng $SCRIPT_OUTPUT_FILE -o widgets.png".')
- print('digraph G {')
- print('\tbgcolor = grey')
- for root, dirs, files in os.walk(path):
- if 'dapm' in dirs:
- handle_widgets(os.path.join(root, 'dapm'))
- dirs.remove('dapm')
- print('}')
-
-
-def main(argv):
- for c in os.listdir(ROOTDIR):
- path = os.path.join(ROOTDIR, c)
- # We assume that directories in ROOTDIR are cards.
- if os.path.isdir(path):
- handle_card(path)
- sys.exit(0)
-
- print('No cards found', file=sys.stderr)
- sys.exit(1)
-
-
-if __name__ == '__main__':
- main(sys.argv[1:])
-
diff --git a/scripts/audio_diagnostics b/scripts/audio_diagnostics
deleted file mode 100755
index b754c07c..00000000
--- a/scripts/audio_diagnostics
+++ /dev/null
@@ -1,129 +0,0 @@
-#!/bin/sh
-#
-# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-# Collect information about the audio system from top to bottom.
-
-dump_cards() {
- # shellcheck disable=SC2068
- for card in ${@}
- do
- echo "=== amixer -c ${card} scontents ==="
- amixer -c "${card}" scontents
- echo "=== amixer -c ${card} contents ==="
- amixer -c "${card}" contents
- done
-}
-
-# Helper function: in_the_list $1 $2
-# Returns 0 if str $1 is included in delimited str $2; otherwise 1
-in_the_list() {
- for item in $2
- do
- if [ "$1" = "${item}" ]; then
- return 0
- fi
- done
- return 1
-}
-
-echo '=== cras_test_client --dump_server_info ==='
-cras_test_client --dump_server_info
-
-echo '=== cras_test_client --dump_audio_thread ==='
-cras_test_client --dump_audio_thread
-
-echo '=== cras_test_client --dump_main ==='
-cras_test_client --dump_main
-
-echo '=== cras_test_client --dump_bt ==='
-cras_test_client --dump_bt
-
-echo '=== cras_test_client --dump_events ==='
-cras_test_client --dump_events
-
-echo '=== aplay -l ==='
-aplay -l
-echo '=== arecord -l ==='
-arecord -l
-
-output_cards=$(
- aplay -l | grep -E ^card | sed 's/card \([0-9]\+\).*/\1/' | sort -u)
-dump_cards "${output_cards}"
-
-input_cards=$(
- arecord -l | grep -E ^card | sed 's/card \([0-9]\+\).*/\1/' | sort -u)
-dump_cards "${input_cards}"
-
-# HDA codec for codecs on x86.
-codecs=$(find /proc/asound -mindepth 2 -maxdepth 2 -path '*card*/codec#*')
-for codec in ${codecs}
-do
- echo "=== codec: ${codec} ==="
- cat "${codec}"
-done
-
-# I2C dump for codecs on arm.
-# Find lines like "max98088.7-0010" and extract "7 0x0010" from it.
-if [ -e /sys/kernel/debug/asoc/codecs ]; then
- sed_expr='s/^\([^.-]\+\)\.\([0-9]\+\)-\([0-9]\+\)$/\2 0x\3/p'
- sed -n "${sed_expr}" /sys/kernel/debug/asoc/codecs |
- while read -r i2c_addr
- do
- echo "=== i2cdump -f -y ${i2c_addr} ==="
- i2cdump -f -y "${i2c_addr}"
- done
-fi
-
-# Dump registers from regmaps
-
-# List of audio components
-# For kernel>=4.14, it is in /sys/kernel/debug/asoc/components
-# For kernel<4.14, it is in /sys/kernel/debug/asoc/codecs
-if [ -f /sys/kernel/debug/asoc/components ]; then
- audio_comps=$(cat /sys/kernel/debug/asoc/components)
-else
- audio_comps=$(cat /sys/kernel/debug/asoc/codecs)
-fi
-
-# Blocklist regmap name of dumping registers (tracked by b/154177454)
-# Use the blank space as delimiter, e.g. 'name_a name_b name_c'
-name_blocklist='snd_hda_codec_hdmi'
-
-for file_path in /sys/kernel/debug/regmap/*
-do
- [ -e "${file_path}" ] || break # handle the case of no files
- component=$(basename "${file_path}")
-
- # Skip dumping registers if component is not listed in audio_comps
- if ! in_the_list "${component}" "${audio_comps}"; then
- continue
- fi
-
- if [ ! -f "${file_path}/name" ]; then
- echo "Failed at dump registers: ${file_path}"
- continue
- fi
-
- name=$(cat "${file_path}/name")
- echo "=== dump registers component: ${component} name: ${name} ==="
-
- # Skip dumping registers if regmap's name is in name_blocklist
- if in_the_list "${name}" "${name_blocklist}"; then
- echo 'skipped dumping due to b/154177454'
- continue
- fi
-
- # Store back the original value
- # Note: $(cat cache_bypass) returns 'Y' if flag is on; otherwise 'N'
- cache_bypass=$(cat "${file_path}/cache_bypass")
- if [ "${cache_bypass}" = "N" ]; then
- echo 1 > "${file_path}/cache_bypass"
- fi
- cat "${file_path}/registers"
- if [ "${cache_bypass}" = "N" ]; then
- echo 0 > "${file_path}/cache_bypass"
- fi
-done
diff --git a/scripts/audio_thread_log_viewer/README.md b/scripts/audio_thread_log_viewer/README.md
deleted file mode 100644
index 7b2612d3..00000000
--- a/scripts/audio_thread_log_viewer/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-# Audio thread log viewer
-It is a tool to draw a time chart from audio thread log. It can make debug
-easier.
-
-[TOC]
-
-## Prepare an audio thread log
-The easiest way to get audio thread log is typing `cras_test_client --dump_a`
-in ChromeOS shell.
-
-The format should be like
-```
-Audio Thread Event Log:
-start at 4434i
-2019-07-02T15:30:46.539479158 cras atlog SET_DEV_WAKE dev:7 hw_level:216 sleep:168
-2019-07-02T15:30:46.539482658 cras atlog DEV_SLEEP_TIME dev:7 wake: 15:30:46.542974324
-2019-07-02T15:30:46.539492991 cras atlog DEV_SLEEP_TIME dev:8 wake: 15:30:46.539358095
-2019-07-02T15:30:46.539501241 cras atlog SLEEP sleep:000000000.000000000 longest_wake:001553999
-...
-```
-
-## Generate an HTML file
-```
-usage: viewer_c3.py [-h] [-o OUTPUT] [-d] FILE
-
-Draw time chart from audio thread log
-
-positional arguments:
- FILE The audio thread log file
-
-optional arguments:
- -h, --help show this help message and exit
- -o OUTPUT The output HTML file (default: view.html)
- -d Show debug message (default: False)
-```
-
-## View the result
-Open the output from vierwe_c3.py by Chrome. There are several functions in
-this site:
-+ The blue points show the hardware level change of the audio thread logs.
- Click a point can jump to a corresponding line in the log area.
-+ There are some options can be selected. It can show the event in the chart
- so that users can easily see when a stream is added, when a stream is fetched
- , and so on.
-+ The textarea in the lower right corner can be used to note.
diff --git a/scripts/audio_thread_log_viewer/example.html b/scripts/audio_thread_log_viewer/example.html
deleted file mode 100644
index 2fd7c9c7..00000000
--- a/scripts/audio_thread_log_viewer/example.html
+++ /dev/null
@@ -1,783 +0,0 @@
-
-<html meta charset="UTF8">
-<head>
- <!-- Load c3.css -->
- <link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet" type="text/css">
- <!-- Load d3.js and c3.js -->
- <script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
- <script src="https://rawgit.com/masayuki0812/c3/master/c3.js" charset="utf-8"></script>
- <style type="text/css">
- .c3-grid text {
- fill: grey;
- }
- .event_log_box {
- font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;
- font-size: 20px;
- font-style: normal;
- font-variant: normal;
- font-weight: 300;
- line-height: 26.4px;
- white-space: pre;
- height:50%;
- width:48%;
- border:1px solid #ccc;
- overflow:auto;
- }
- .checkbox {
- font-size: 30px;
- border: 2px;
- }
- .device {
- font-size: 15px;
- }
- .stream{
- font-size: 15px;
- }
- .fetch{
- }
- .wake{
- }
- </style>
- <script type="text/javascript">
- var selected = null;
- draw_chart = function() {
- var chart = c3.generate({
- data: {
- x: 'time',
- columns: [
- ['time', 38274.654909156, 38274.657371167, 38274.657668959, 38274.676688159, 38274.676725281, 38274.676926906, 38274.677252890, 38274.697879928, 38274.697916480, 38274.698114806, 38274.698417024, 38274.719199290, 38274.719236981, 38274.719359698, 38274.719663005, 38274.740686503, 38274.740723661, 38274.740850997, 38274.741173582, 38274.762025805, 38274.762062690, 38274.762153748, 38274.762452548, 38274.783326364, 38274.783362532, 38274.783489920, 38274.783790725, 38274.804671376, 38274.804708721, 38274.804838233, 38274.805159078, 38274.826024162, 38274.826062337, 38274.826152748, 38274.826451927, 38274.847346397, 38274.847382560, 38274.847510294, 38274.847815798, 38274.868739650, 38274.868776554, 38274.868889760, 38274.869207769, 38274.890021859, 38274.890059702, 38274.890149892, 38274.890446925, 38274.911642356, 38274.911677780, 38274.911875825, 38274.912200713, 38274.932637511, 38274.932673739, 38274.932804355, 38274.933129716, 38274.954030314, 38274.954067674, 38274.954159335, 38274.954466654, 38274.975643692, 38274.975680354, 38274.975807387, 38274.976120622, 38274.996667671, 38274.996704048, 38274.996833804, 38274.997146185, 38275.017877797, 38275.017914904, 38275.018030670, 38275.018320047, 38275.039145228, 38275.039181369, 38275.039303282, 38275.039595139, 38275.060732607, 38275.060769291, 38275.060896906, 38275.061209809, 38275.082027553, 38275.082064736, 38275.082153665, 38275.082440331, 38275.103326735, 38275.103362951, 38275.103561185, 38275.103915541, 38275.124657946, 38275.124694671, 38275.124818548, 38275.125130858, 38275.146029029, 38275.146065845, 38275.146157000, 38275.146444659, 38275.167643000, 38275.167679011, 38275.167806856, 38275.168119122, 38275.188729928, 38275.188766573, 38275.188894276, 38275.189205852, 38275.210020752, 38275.210058744, 38275.210148466, 38275.210434597],
- ['buffer_level', null, 928, 1952, 1040, 1040, 1040, 2016, 1056, 1056, 1008, 2032, 1024, 1024, 1024, 2048, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032, 1024, 1024, 1024, 2048, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032, 1024, 1024, 1024, 2048, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032, 1024, 1024, 1024, 2000, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032, 1024, 1024, 1024, 2000, 1040, 1040, 1040, 2016, 1056, 1056, 1008, 2032, 1024, 1024, 1024, 2048, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032, 1024, 1024, 1024, 2048, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032, 1024, 1024, 1024, 2000, 1040, 1040, 1040, 2016, 1008, 1008, 1008, 2032],
- ],
- type: 'bar',
- types: {
- buffer_level: 'line',
- },
- onclick: function (d, i) {
- elm = document.getElementById(d.x.toFixed(9));
- if (selected)
- selected.style.color = '';
- if (elm === null) {
- console.error("Can not find element by ID %s", d.x.toFixed(9));
- return;
- }
- elm.style.color = 'blue';
- elm.scrollIntoView();
- selected = elm;
- },
- },
- zoom: {
- enabled: true,
- },
-
- grid: {
- x: {
- lines: [
- {value: 38274.654888011, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.654909156, text: "Added Device 6", position: "start", class: "device"}, {value: 38274.654958862, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.655022911, text: "Add stream 1d0000", position: "middle", class: "stream"}, {value: 38274.655046329, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.656503188, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.676639948, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.676860551, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.697833022, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.698048577, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.719153430, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.719301220, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.740639477, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.740793102, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.761962963, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.762102057, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.783277641, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.783432165, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.804623390, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.804780617, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.825958417, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.826100424, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.847298285, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.847453266, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.868691938, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.868834120, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.889955591, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.890097300, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.911593780, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.911810046, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.932589800, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.932746675, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.953964062, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.954106963, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.975595442, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.975750291, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38274.996619059, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38274.996775539, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.017830417, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.017961913, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.039099808, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.039242696, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.060684606, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.060839575, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.081962397, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.082101703, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.103278902, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.103495004, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.124610042, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.124760504, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.145964152, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.146104176, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.167594886, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.167749677, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.188682360, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.188837092, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.209955429, text: "Fetch 1d0000", position: "end", class: "fetch"}, {value: 38275.210096165, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.222778298, text: "num_fds 1", position: "middle", class: "wake"}, {value: 38275.222796197, text: "Remove stream 1d0000", position: "middle", class: "stream"},
- ],
- },
- },
-
- axis: {
- y: {min: 0, max: 2048},
- },
- });
- };
-
- logs = `Audio Debug Stats:
--------------devices------------
-Output dev: kbl_r5514_5663_max: :0,0
-buffer_size: 16384
-min_buffer_level: 0
-min_cb_level: 8192
-max_cb_level: 0
-frame_rate: 48000
-num_channels: 2
-est_rate_ratio: 1.000000
-num_underruns: 0
-num_severe_underruns: 0
-highest_hw_level: 2048
-runtime: 2.148581272
-software_gain_scaler: 0.000000
-
--------------stream_dump------------
-Audio Thread Event Log:
-start at 2874
-<label id="38204.803651654">2019-08-19T10:36:44.803651654 cras atlog SLEEP sleep:000000000.000000000 longest_wake:001565104</label>
-<label id="38274.654888011">2019-08-19T10:37:54.654888011 cras atlog WAKE num_fds:1</label>
-<label id="38274.654901579">2019-08-19T10:37:54.654901579 cras atlog PB_MSG msg_id:0</label>
-<label id="38274.654906341">2019-08-19T10:37:54.654906341 cras atlog FILL_ODEV_ZEROS dev:6 write:0</label>
-<label id="38274.654909156">2019-08-19T10:37:54.654909156 cras atlog DEV_ADDED dev:6</label>
-<label id="38274.654950513">2019-08-19T10:37:54.654950513 cras atlog SLEEP sleep:000000000.000000000 longest_wake:001565104</label>
-<label id="38274.654958862">2019-08-19T10:37:54.654958862 cras atlog WAKE num_fds:1</label>
-<label id="38274.654966799">2019-08-19T10:37:54.654966799 cras atlog PB_MSG msg_id:3</label>
-<label id="38274.654969277">2019-08-19T10:37:54.654969277 cras atlog WRITE_STREAMS_WAIT stream:1d0000</label>
-<label id="38274.655022911">2019-08-19T10:37:54.655022911 cras atlog STREAM_ADDED id:1d0000 dev:6</label>
-<label id="38274.655046329">2019-08-19T10:37:54.655046329 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:288</label>
-<label id="38274.655069609">2019-08-19T10:37:54.655069609 cras atlog SLEEP sleep:000000000.000000000 longest_wake:001565104</label>
-<label id="38274.656503188">2019-08-19T10:37:54.656503188 cras atlog WAKE num_fds:1</label>
-<label id="38274.656538337">2019-08-19T10:37:54.656538337 cras atlog FILL_ODEV_ZEROS dev:6 write:1024</label>
-<label id="38274.656869440">2019-08-19T10:37:54.656869440 cras atlog ODEV_START dev:6 min_cb_level:1024</label>
-<label id="38274.657368663">2019-08-19T10:37:54.657368663 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.657365837</label>
-<label id="38274.657371167">2019-08-19T10:37:54.657371167 cras atlog FILL_AUDIO dev:6 hw_level:928</label>
-<label id="38274.657376118">2019-08-19T10:37:54.657376118 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.657385868">2019-08-19T10:37:54.657385868 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.657395667">2019-08-19T10:37:54.657395667 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.657398033">2019-08-19T10:37:54.657398033 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.657646876">2019-08-19T10:37:54.657646876 cras atlog FILL_AUDIO_DONE hw_level:928 total_written:1024 min_cb_level:1024</label>
-<label id="38274.657668959">2019-08-19T10:37:54.657668959 cras atlog SET_DEV_WAKE dev:6 hw_level:1952 sleep:1904</label>
-<label id="38274.657671042">2019-08-19T10:37:54.657671042 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.697332693</label>
-<label id="38274.657676157">2019-08-19T10:37:54.657676157 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.676321391</label>
-<label id="38274.657680973">2019-08-19T10:37:54.657680973 cras atlog SLEEP sleep:000000000.018647412 longest_wake:001565104</label>
-<label id="38274.676595788">2019-08-19T10:37:54.676595788 cras atlog WAKE num_fds:0</label>
-<label id="38274.676639948">2019-08-19T10:37:54.676639948 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38274.676685281">2019-08-19T10:37:54.676685281 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.676683159</label>
-<label id="38274.676688159">2019-08-19T10:37:54.676688159 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.676694319">2019-08-19T10:37:54.676694319 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.676696512">2019-08-19T10:37:54.676696512 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.676699365">2019-08-19T10:37:54.676699365 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.676705462">2019-08-19T10:37:54.676705462 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38274.676725281">2019-08-19T10:37:54.676725281 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38274.676727345">2019-08-19T10:37:54.676727345 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.697389256</label>
-<label id="38274.676734968">2019-08-19T10:37:54.676734968 cras atlog SLEEP sleep:000000000.020659324 longest_wake:001565104</label>
-<label id="38274.676860551">2019-08-19T10:37:54.676860551 cras atlog WAKE num_fds:1</label>
-<label id="38274.676924328">2019-08-19T10:37:54.676924328 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.676922156</label>
-<label id="38274.676926906">2019-08-19T10:37:54.676926906 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.676931349">2019-08-19T10:37:54.676931349 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.676943036">2019-08-19T10:37:54.676943036 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.676953027">2019-08-19T10:37:54.676953027 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.676955453">2019-08-19T10:37:54.676955453 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.677231898">2019-08-19T10:37:54.677231898 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38274.677252890">2019-08-19T10:37:54.677252890 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38274.677254980">2019-08-19T10:37:54.677254980 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.718250167</label>
-<label id="38274.677259823">2019-08-19T10:37:54.677259823 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.697654724</label>
-<label id="38274.677264536">2019-08-19T10:37:54.677264536 cras atlog SLEEP sleep:000000000.020396980 longest_wake:001565104</label>
-<label id="38274.697789394">2019-08-19T10:37:54.697789394 cras atlog WAKE num_fds:0</label>
-<label id="38274.697833022">2019-08-19T10:37:54.697833022 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38274.697876956">2019-08-19T10:37:54.697876956 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.697874846</label>
-<label id="38274.697879928">2019-08-19T10:37:54.697879928 cras atlog FILL_AUDIO dev:6 hw_level:1056</label>
-<label id="38274.697885964">2019-08-19T10:37:54.697885964 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.697888192">2019-08-19T10:37:54.697888192 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.697891024">2019-08-19T10:37:54.697891024 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.697897003">2019-08-19T10:37:54.697897003 cras atlog FILL_AUDIO_DONE hw_level:1056 total_written:0 min_cb_level:1024</label>
-<label id="38274.697916480">2019-08-19T10:37:54.697916480 cras atlog SET_DEV_WAKE dev:6 hw_level:1056 sleep:1008</label>
-<label id="38274.697918569">2019-08-19T10:37:54.697918569 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.718913723</label>
-<label id="38274.697926449">2019-08-19T10:37:54.697926449 cras atlog SLEEP sleep:000000000.020992361 longest_wake:001565104</label>
-<label id="38274.698048577">2019-08-19T10:37:54.698048577 cras atlog WAKE num_fds:1</label>
-<label id="38274.698112219">2019-08-19T10:37:54.698112219 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.698110036</label>
-<label id="38274.698114806">2019-08-19T10:37:54.698114806 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.698119339">2019-08-19T10:37:54.698119339 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.698133295">2019-08-19T10:37:54.698133295 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.698138449">2019-08-19T10:37:54.698138449 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.698140835">2019-08-19T10:37:54.698140835 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.698396787">2019-08-19T10:37:54.698396787 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38274.698417024">2019-08-19T10:37:54.698417024 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38274.698419100">2019-08-19T10:37:54.698419100 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.739747637</label>
-<label id="38274.698423907">2019-08-19T10:37:54.698423907 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.718988057</label>
-<label id="38274.698428623">2019-08-19T10:37:54.698428623 cras atlog SLEEP sleep:000000000.020566258 longest_wake:001565104</label>
-<label id="38274.719109903">2019-08-19T10:37:54.719109903 cras atlog WAKE num_fds:0</label>
-<label id="38274.719153430">2019-08-19T10:37:54.719153430 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38274.719196387">2019-08-19T10:37:54.719196387 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.719194274</label>
-<label id="38274.719199290">2019-08-19T10:37:54.719199290 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.719205301">2019-08-19T10:37:54.719205301 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.719207458">2019-08-19T10:37:54.719207458 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.719210354">2019-08-19T10:37:54.719210354 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.719216842">2019-08-19T10:37:54.719216842 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38274.719236981">2019-08-19T10:37:54.719236981 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38274.719239068">2019-08-19T10:37:54.719239068 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.739567597</label>
-<label id="38274.719246952">2019-08-19T10:37:54.719246952 cras atlog SLEEP sleep:000000000.020325687 longest_wake:001565104</label>
-<label id="38274.719301220">2019-08-19T10:37:54.719301220 cras atlog WAKE num_fds:1</label>
-<label id="38274.719357382">2019-08-19T10:37:54.719357382 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.719355237</label>
-<label id="38274.719359698">2019-08-19T10:37:54.719359698 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.719362947">2019-08-19T10:37:54.719362947 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.719377071">2019-08-19T10:37:54.719377071 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.719382615">2019-08-19T10:37:54.719382615 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.719384824">2019-08-19T10:37:54.719384824 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.719643101">2019-08-19T10:37:54.719643101 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38274.719663005">2019-08-19T10:37:54.719663005 cras atlog SET_DEV_WAKE dev:6 hw_level:2048 sleep:2000</label>
-<label id="38274.719664987">2019-08-19T10:37:54.719664987 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.761327047</label>
-<label id="38274.719669473">2019-08-19T10:37:54.719669473 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.740321390</label>
-<label id="38274.719673899">2019-08-19T10:37:54.719673899 cras atlog SLEEP sleep:000000000.020654025 longest_wake:001565104</label>
-<label id="38274.740595499">2019-08-19T10:37:54.740595499 cras atlog WAKE num_fds:0</label>
-<label id="38274.740639477">2019-08-19T10:37:54.740639477 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38274.740683615">2019-08-19T10:37:54.740683615 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.740681512</label>
-<label id="38274.740686503">2019-08-19T10:37:54.740686503 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.740692464">2019-08-19T10:37:54.740692464 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.740694600">2019-08-19T10:37:54.740694600 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.740697433">2019-08-19T10:37:54.740697433 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.740703643">2019-08-19T10:37:54.740703643 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38274.740723661">2019-08-19T10:37:54.740723661 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38274.740725763">2019-08-19T10:37:54.740725763 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.761387612</label>
-<label id="38274.740733471">2019-08-19T10:37:54.740733471 cras atlog SLEEP sleep:000000000.020659319 longest_wake:001565104</label>
-<label id="38274.740793102">2019-08-19T10:37:54.740793102 cras atlog WAKE num_fds:1</label>
-<label id="38274.740848639">2019-08-19T10:37:54.740848639 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.740846573</label>
-<label id="38274.740850997">2019-08-19T10:37:54.740850997 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.740854311">2019-08-19T10:37:54.740854311 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.740868736">2019-08-19T10:37:54.740868736 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.740873892">2019-08-19T10:37:54.740873892 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.740875997">2019-08-19T10:37:54.740875997 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.741153121">2019-08-19T10:37:54.741153121 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38274.741173582">2019-08-19T10:37:54.741173582 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38274.741175606">2019-08-19T10:37:54.741175606 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.782171115</label>
-<label id="38274.741180302">2019-08-19T10:37:54.741180302 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.761654723</label>
-<label id="38274.741184669">2019-08-19T10:37:54.741184669 cras atlog SLEEP sleep:000000000.020476747 longest_wake:001565104</label>
-<label id="38274.761922026">2019-08-19T10:37:54.761922026 cras atlog WAKE num_fds:0</label>
-<label id="38274.761962963">2019-08-19T10:37:54.761962963 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38274.762022826">2019-08-19T10:37:54.762022826 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.762020513</label>
-<label id="38274.762025805">2019-08-19T10:37:54.762025805 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.762031594">2019-08-19T10:37:54.762031594 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.762033738">2019-08-19T10:37:54.762033738 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.762036536">2019-08-19T10:37:54.762036536 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.762042425">2019-08-19T10:37:54.762042425 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38274.762062690">2019-08-19T10:37:54.762062690 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38274.762065186">2019-08-19T10:37:54.762065186 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.782060173</label>
-<label id="38274.762072982">2019-08-19T10:37:54.762072982 cras atlog SLEEP sleep:000000000.019992102 longest_wake:001565104</label>
-<label id="38274.762102057">2019-08-19T10:37:54.762102057 cras atlog WAKE num_fds:1</label>
-<label id="38274.762151699">2019-08-19T10:37:54.762151699 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.762149704</label>
-<label id="38274.762153748">2019-08-19T10:37:54.762153748 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.762156523">2019-08-19T10:37:54.762156523 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.762170916">2019-08-19T10:37:54.762170916 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.762175916">2019-08-19T10:37:54.762175916 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.762178058">2019-08-19T10:37:54.762178058 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.762432618">2019-08-19T10:37:54.762432618 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38274.762452548">2019-08-19T10:37:54.762452548 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38274.762454582">2019-08-19T10:37:54.762454582 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.803783385</label>
-<label id="38274.762458984">2019-08-19T10:37:54.762458984 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.782988056</label>
-<label id="38274.762463390">2019-08-19T10:37:54.762463390 cras atlog SLEEP sleep:000000000.020531186 longest_wake:001565104</label>
-<label id="38274.783234058">2019-08-19T10:37:54.783234058 cras atlog WAKE num_fds:0</label>
-<label id="38274.783277641">2019-08-19T10:37:54.783277641 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38274.783323456">2019-08-19T10:37:54.783323456 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.783321345</label>
-<label id="38274.783326364">2019-08-19T10:37:54.783326364 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.783332069">2019-08-19T10:37:54.783332069 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.783334227">2019-08-19T10:37:54.783334227 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.783337045">2019-08-19T10:37:54.783337045 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.783343042">2019-08-19T10:37:54.783343042 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38274.783362532">2019-08-19T10:37:54.783362532 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38274.783364628">2019-08-19T10:37:54.783364628 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.803693148</label>
-<label id="38274.783372345">2019-08-19T10:37:54.783372345 cras atlog SLEEP sleep:000000000.020325873 longest_wake:001565104</label>
-<label id="38274.783432165">2019-08-19T10:37:54.783432165 cras atlog WAKE num_fds:1</label>
-<label id="38274.783487514">2019-08-19T10:37:54.783487514 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.783485428</label>
-<label id="38274.783489920">2019-08-19T10:37:54.783489920 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.783493117">2019-08-19T10:37:54.783493117 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.783507178">2019-08-19T10:37:54.783507178 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.783512206">2019-08-19T10:37:54.783512206 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.783514361">2019-08-19T10:37:54.783514361 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.783772851">2019-08-19T10:37:54.783772851 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38274.783790725">2019-08-19T10:37:54.783790725 cras atlog SET_DEV_WAKE dev:6 hw_level:2048 sleep:2000</label>
-<label id="38274.783792763">2019-08-19T10:37:54.783792763 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.825454687</label>
-<label id="38274.783797423">2019-08-19T10:37:54.783797423 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.804321389</label>
-<label id="38274.783801803">2019-08-19T10:37:54.783801803 cras atlog SLEEP sleep:000000000.020526265 longest_wake:001565104</label>
-<label id="38274.804579013">2019-08-19T10:37:54.804579013 cras atlog WAKE num_fds:0</label>
-<label id="38274.804623390">2019-08-19T10:37:54.804623390 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38274.804668478">2019-08-19T10:37:54.804668478 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.804666367</label>
-<label id="38274.804671376">2019-08-19T10:37:54.804671376 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.804677338">2019-08-19T10:37:54.804677338 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.804679504">2019-08-19T10:37:54.804679504 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.804682310">2019-08-19T10:37:54.804682310 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.804688741">2019-08-19T10:37:54.804688741 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38274.804708721">2019-08-19T10:37:54.804708721 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38274.804710807">2019-08-19T10:37:54.804710807 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.825372685</label>
-<label id="38274.804718659">2019-08-19T10:37:54.804718659 cras atlog SLEEP sleep:000000000.020659270 longest_wake:001565104</label>
-<label id="38274.804780617">2019-08-19T10:37:54.804780617 cras atlog WAKE num_fds:1</label>
-<label id="38274.804835890">2019-08-19T10:37:54.804835890 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.804833797</label>
-<label id="38274.804838233">2019-08-19T10:37:54.804838233 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.804841501">2019-08-19T10:37:54.804841501 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.804855352">2019-08-19T10:37:54.804855352 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.804860473">2019-08-19T10:37:54.804860473 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.804862636">2019-08-19T10:37:54.804862636 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.805138821">2019-08-19T10:37:54.805138821 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38274.805159078">2019-08-19T10:37:54.805159078 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38274.805161124">2019-08-19T10:37:54.805161124 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.846156596</label>
-<label id="38274.805165757">2019-08-19T10:37:54.805165757 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.825654722</label>
-<label id="38274.805170306">2019-08-19T10:37:54.805170306 cras atlog SLEEP sleep:000000000.020491218 longest_wake:001565104</label>
-<label id="38274.825913546">2019-08-19T10:37:54.825913546 cras atlog WAKE num_fds:0</label>
-<label id="38274.825958417">2019-08-19T10:37:54.825958417 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38274.826020986">2019-08-19T10:37:54.826020986 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.826018114</label>
-<label id="38274.826024162">2019-08-19T10:37:54.826024162 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.826030236">2019-08-19T10:37:54.826030236 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.826032511">2019-08-19T10:37:54.826032511 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.826035326">2019-08-19T10:37:54.826035326 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.826041230">2019-08-19T10:37:54.826041230 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38274.826062337">2019-08-19T10:37:54.826062337 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38274.826064399">2019-08-19T10:37:54.826064399 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.846059769</label>
-<label id="38274.826072024">2019-08-19T10:37:54.826072024 cras atlog SLEEP sleep:000000000.019992730 longest_wake:001565104</label>
-<label id="38274.826100424">2019-08-19T10:37:54.826100424 cras atlog WAKE num_fds:1</label>
-<label id="38274.826150628">2019-08-19T10:37:54.826150628 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.826148583</label>
-<label id="38274.826152748">2019-08-19T10:37:54.826152748 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.826155423">2019-08-19T10:37:54.826155423 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.826170179">2019-08-19T10:37:54.826170179 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.826175702">2019-08-19T10:37:54.826175702 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.826177885">2019-08-19T10:37:54.826177885 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.826431854">2019-08-19T10:37:54.826431854 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38274.826451927">2019-08-19T10:37:54.826451927 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38274.826453912">2019-08-19T10:37:54.826453912 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.867782437</label>
-<label id="38274.826458354">2019-08-19T10:37:54.826458354 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.846988055</label>
-<label id="38274.826462711">2019-08-19T10:37:54.826462711 cras atlog SLEEP sleep:000000000.020531841 longest_wake:001565104</label>
-<label id="38274.847254169">2019-08-19T10:37:54.847254169 cras atlog WAKE num_fds:0</label>
-<label id="38274.847298285">2019-08-19T10:37:54.847298285 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38274.847343532">2019-08-19T10:37:54.847343532 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.847341437</label>
-<label id="38274.847346397">2019-08-19T10:37:54.847346397 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.847352242">2019-08-19T10:37:54.847352242 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.847354402">2019-08-19T10:37:54.847354402 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.847357232">2019-08-19T10:37:54.847357232 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.847363049">2019-08-19T10:37:54.847363049 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38274.847382560">2019-08-19T10:37:54.847382560 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38274.847384657">2019-08-19T10:37:54.847384657 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.867713298</label>
-<label id="38274.847392466">2019-08-19T10:37:54.847392466 cras atlog SLEEP sleep:000000000.020325941 longest_wake:001565104</label>
-<label id="38274.847453266">2019-08-19T10:37:54.847453266 cras atlog WAKE num_fds:1</label>
-<label id="38274.847507893">2019-08-19T10:37:54.847507893 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.847505842</label>
-<label id="38274.847510294">2019-08-19T10:37:54.847510294 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.847513378">2019-08-19T10:37:54.847513378 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.847527509">2019-08-19T10:37:54.847527509 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.847532608">2019-08-19T10:37:54.847532608 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.847534792">2019-08-19T10:37:54.847534792 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.847794682">2019-08-19T10:37:54.847794682 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38274.847815798">2019-08-19T10:37:54.847815798 cras atlog SET_DEV_WAKE dev:6 hw_level:2048 sleep:2000</label>
-<label id="38274.847818230">2019-08-19T10:37:54.847818230 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.889479489</label>
-<label id="38274.847822643">2019-08-19T10:37:54.847822643 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.868321388</label>
-<label id="38274.847827174">2019-08-19T10:37:54.847827174 cras atlog SLEEP sleep:000000000.020500850 longest_wake:001565104</label>
-<label id="38274.868647280">2019-08-19T10:37:54.868647280 cras atlog WAKE num_fds:0</label>
-<label id="38274.868691938">2019-08-19T10:37:54.868691938 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38274.868736756">2019-08-19T10:37:54.868736756 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.868734631</label>
-<label id="38274.868739650">2019-08-19T10:37:54.868739650 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.868745553">2019-08-19T10:37:54.868745553 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.868747712">2019-08-19T10:37:54.868747712 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.868750515">2019-08-19T10:37:54.868750515 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.868756826">2019-08-19T10:37:54.868756826 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38274.868776554">2019-08-19T10:37:54.868776554 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38274.868778635">2019-08-19T10:37:54.868778635 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.889440503</label>
-<label id="38274.868786877">2019-08-19T10:37:54.868786877 cras atlog SLEEP sleep:000000000.020658858 longest_wake:001565104</label>
-<label id="38274.868834120">2019-08-19T10:37:54.868834120 cras atlog WAKE num_fds:1</label>
-<label id="38274.868887396">2019-08-19T10:37:54.868887396 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.868885395</label>
-<label id="38274.868889760">2019-08-19T10:37:54.868889760 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.868892743">2019-08-19T10:37:54.868892743 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.868906663">2019-08-19T10:37:54.868906663 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.868911746">2019-08-19T10:37:54.868911746 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.868913920">2019-08-19T10:37:54.868913920 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.869187106">2019-08-19T10:37:54.869187106 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38274.869207769">2019-08-19T10:37:54.869207769 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38274.869209841">2019-08-19T10:37:54.869209841 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.910204925</label>
-<label id="38274.869214453">2019-08-19T10:37:54.869214453 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.889654721</label>
-<label id="38274.869218854">2019-08-19T10:37:54.869218854 cras atlog SLEEP sleep:000000000.020442575 longest_wake:001565104</label>
-<label id="38274.889911594">2019-08-19T10:37:54.889911594 cras atlog WAKE num_fds:0</label>
-<label id="38274.889955591">2019-08-19T10:37:54.889955591 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38274.890001028">2019-08-19T10:37:54.890001028 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.889998910</label>
-<label id="38274.890021859">2019-08-19T10:37:54.890021859 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.890028088">2019-08-19T10:37:54.890028088 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.890030382">2019-08-19T10:37:54.890030382 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.890033213">2019-08-19T10:37:54.890033213 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.890039166">2019-08-19T10:37:54.890039166 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38274.890059702">2019-08-19T10:37:54.890059702 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38274.890061783">2019-08-19T10:37:54.890061783 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.910057166</label>
-<label id="38274.890069206">2019-08-19T10:37:54.890069206 cras atlog SLEEP sleep:000000000.019992855 longest_wake:001565104</label>
-<label id="38274.890097300">2019-08-19T10:37:54.890097300 cras atlog WAKE num_fds:1</label>
-<label id="38274.890147785">2019-08-19T10:37:54.890147785 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.890145728</label>
-<label id="38274.890149892">2019-08-19T10:37:54.890149892 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.890152824">2019-08-19T10:37:54.890152824 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.890166719">2019-08-19T10:37:54.890166719 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.890171766">2019-08-19T10:37:54.890171766 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.890173949">2019-08-19T10:37:54.890173949 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.890427138">2019-08-19T10:37:54.890427138 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38274.890446925">2019-08-19T10:37:54.890446925 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38274.890448924">2019-08-19T10:37:54.890448924 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.931777812</label>
-<label id="38274.890453296">2019-08-19T10:37:54.890453296 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.910988054</label>
-<label id="38274.890457622">2019-08-19T10:37:54.890457622 cras atlog SLEEP sleep:000000000.020536883 longest_wake:001565104</label>
-<label id="38274.911549604">2019-08-19T10:37:54.911549604 cras atlog WAKE num_fds:0</label>
-<label id="38274.911593780">2019-08-19T10:37:54.911593780 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38274.911639463">2019-08-19T10:37:54.911639463 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.911637349</label>
-<label id="38274.911642356">2019-08-19T10:37:54.911642356 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.911648354">2019-08-19T10:37:54.911648354 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.911650495">2019-08-19T10:37:54.911650495 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.911653308">2019-08-19T10:37:54.911653308 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.911659036">2019-08-19T10:37:54.911659036 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38274.911677780">2019-08-19T10:37:54.911677780 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38274.911679870">2019-08-19T10:37:54.911679870 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.932008544</label>
-<label id="38274.911687437">2019-08-19T10:37:54.911687437 cras atlog SLEEP sleep:000000000.020326063 longest_wake:001565104</label>
-<label id="38274.911810046">2019-08-19T10:37:54.911810046 cras atlog WAKE num_fds:1</label>
-<label id="38274.911873260">2019-08-19T10:37:54.911873260 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.911871103</label>
-<label id="38274.911875825">2019-08-19T10:37:54.911875825 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.911880257">2019-08-19T10:37:54.911880257 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.911894516">2019-08-19T10:37:54.911894516 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.911899775">2019-08-19T10:37:54.911899775 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.911902141">2019-08-19T10:37:54.911902141 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.912179567">2019-08-19T10:37:54.912179567 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38274.912200713">2019-08-19T10:37:54.912200713 cras atlog SET_DEV_WAKE dev:6 hw_level:2000 sleep:1952</label>
-<label id="38274.912202795">2019-08-19T10:37:54.912202795 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.952864609</label>
-<label id="38274.912207619">2019-08-19T10:37:54.912207619 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.932321387</label>
-<label id="38274.912212340">2019-08-19T10:37:54.912212340 cras atlog SLEEP sleep:000000000.020115853 longest_wake:001565104</label>
-<label id="38274.932544653">2019-08-19T10:37:54.932544653 cras atlog WAKE num_fds:0</label>
-<label id="38274.932589800">2019-08-19T10:37:54.932589800 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38274.932634557">2019-08-19T10:37:54.932634557 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.932632438</label>
-<label id="38274.932637511">2019-08-19T10:37:54.932637511 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.932643460">2019-08-19T10:37:54.932643460 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.932645626">2019-08-19T10:37:54.932645626 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.932648431">2019-08-19T10:37:54.932648431 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.932654361">2019-08-19T10:37:54.932654361 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38274.932673739">2019-08-19T10:37:54.932673739 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38274.932675817">2019-08-19T10:37:54.932675817 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.953337688</label>
-<label id="38274.932683307">2019-08-19T10:37:54.932683307 cras atlog SLEEP sleep:000000000.020659279 longest_wake:001565104</label>
-<label id="38274.932746675">2019-08-19T10:37:54.932746675 cras atlog WAKE num_fds:1</label>
-<label id="38274.932802037">2019-08-19T10:37:54.932802037 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.932799966</label>
-<label id="38274.932804355">2019-08-19T10:37:54.932804355 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.932807409">2019-08-19T10:37:54.932807409 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.932821550">2019-08-19T10:37:54.932821550 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.932826892">2019-08-19T10:37:54.932826892 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.932829082">2019-08-19T10:37:54.932829082 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.933108135">2019-08-19T10:37:54.933108135 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38274.933129716">2019-08-19T10:37:54.933129716 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38274.933131709">2019-08-19T10:37:54.933131709 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.974126349</label>
-<label id="38274.933136150">2019-08-19T10:37:54.933136150 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.953654720</label>
-<label id="38274.933140489">2019-08-19T10:37:54.933140489 cras atlog SLEEP sleep:000000000.020520690 longest_wake:001565104</label>
-<label id="38274.953927204">2019-08-19T10:37:54.953927204 cras atlog WAKE num_fds:0</label>
-<label id="38274.953964062">2019-08-19T10:37:54.953964062 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1296</label>
-<label id="38274.954027217">2019-08-19T10:37:54.954027217 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.954024954</label>
-<label id="38274.954030314">2019-08-19T10:37:54.954030314 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.954036483">2019-08-19T10:37:54.954036483 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.954038676">2019-08-19T10:37:54.954038676 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.954041528">2019-08-19T10:37:54.954041528 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.954047105">2019-08-19T10:37:54.954047105 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38274.954067674">2019-08-19T10:37:54.954067674 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38274.954069771">2019-08-19T10:37:54.954069771 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.974064924</label>
-<label id="38274.954077360">2019-08-19T10:37:54.954077360 cras atlog SLEEP sleep:000000000.019992481 longest_wake:001565104</label>
-<label id="38274.954106963">2019-08-19T10:37:54.954106963 cras atlog WAKE num_fds:1</label>
-<label id="38274.954157230">2019-08-19T10:37:54.954157230 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.954155178</label>
-<label id="38274.954159335">2019-08-19T10:37:54.954159335 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38274.954162037">2019-08-19T10:37:54.954162037 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.954177049">2019-08-19T10:37:54.954177049 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.954182292">2019-08-19T10:37:54.954182292 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.954184412">2019-08-19T10:37:54.954184412 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.954439987">2019-08-19T10:37:54.954439987 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:0</label>
-<label id="38274.954442042">2019-08-19T10:37:54.954442042 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.954444204">2019-08-19T10:37:54.954444204 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.954446985">2019-08-19T10:37:54.954446985 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38274.954466654">2019-08-19T10:37:54.954466654 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38274.954468696">2019-08-19T10:37:54.954468696 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.995797668</label>
-<label id="38274.954473224">2019-08-19T10:37:54.954473224 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.974988053</label>
-<label id="38274.954477555">2019-08-19T10:37:54.954477555 cras atlog SLEEP sleep:000000000.020517058 longest_wake:001565104</label>
-<label id="38274.975550997">2019-08-19T10:37:54.975550997 cras atlog WAKE num_fds:0</label>
-<label id="38274.975595442">2019-08-19T10:37:54.975595442 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38274.975640808">2019-08-19T10:37:54.975640808 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.975638709</label>
-<label id="38274.975643692">2019-08-19T10:37:54.975643692 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.975649536">2019-08-19T10:37:54.975649536 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.975651738">2019-08-19T10:37:54.975651738 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.975654643">2019-08-19T10:37:54.975654643 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.975660861">2019-08-19T10:37:54.975660861 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38274.975680354">2019-08-19T10:37:54.975680354 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38274.975682447">2019-08-19T10:37:54.975682447 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:54.996011143</label>
-<label id="38274.975690215">2019-08-19T10:37:54.975690215 cras atlog SLEEP sleep:000000000.020326081 longest_wake:001565104</label>
-<label id="38274.975750291">2019-08-19T10:37:54.975750291 cras atlog WAKE num_fds:1</label>
-<label id="38274.975805101">2019-08-19T10:37:54.975805101 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.975802996</label>
-<label id="38274.975807387">2019-08-19T10:37:54.975807387 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38274.975810666">2019-08-19T10:37:54.975810666 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.975813858">2019-08-19T10:37:54.975813858 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.975818840">2019-08-19T10:37:54.975818840 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.975820997">2019-08-19T10:37:54.975820997 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.976100465">2019-08-19T10:37:54.976100465 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38274.976120622">2019-08-19T10:37:54.976120622 cras atlog SET_DEV_WAKE dev:6 hw_level:2000 sleep:1952</label>
-<label id="38274.976122691">2019-08-19T10:37:54.976122691 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.016784703</label>
-<label id="38274.976127066">2019-08-19T10:37:54.976127066 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:54.996321386</label>
-<label id="38274.976131378">2019-08-19T10:37:54.976131378 cras atlog SLEEP sleep:000000000.020196437 longest_wake:001565104</label>
-<label id="38274.996575651">2019-08-19T10:37:54.996575651 cras atlog WAKE num_fds:0</label>
-<label id="38274.996619059">2019-08-19T10:37:54.996619059 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38274.996664756">2019-08-19T10:37:54.996664756 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.996662645</label>
-<label id="38274.996667671">2019-08-19T10:37:54.996667671 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.996673482">2019-08-19T10:37:54.996673482 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38274.996675649">2019-08-19T10:37:54.996675649 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38274.996678438">2019-08-19T10:37:54.996678438 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38274.996684371">2019-08-19T10:37:54.996684371 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38274.996704048">2019-08-19T10:37:54.996704048 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38274.996706108">2019-08-19T10:37:54.996706108 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.017368028</label>
-<label id="38274.996713503">2019-08-19T10:37:54.996713503 cras atlog SLEEP sleep:000000000.020659377 longest_wake:001565104</label>
-<label id="38274.996775539">2019-08-19T10:37:54.996775539 cras atlog WAKE num_fds:1</label>
-<label id="38274.996831459">2019-08-19T10:37:54.996831459 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:54.996829346</label>
-<label id="38274.996833804">2019-08-19T10:37:54.996833804 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38274.996837127">2019-08-19T10:37:54.996837127 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38274.996840252">2019-08-19T10:37:54.996840252 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38274.996845333">2019-08-19T10:37:54.996845333 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38274.996847487">2019-08-19T10:37:54.996847487 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38274.997125727">2019-08-19T10:37:54.997125727 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38274.997146185">2019-08-19T10:37:54.997146185 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38274.997148232">2019-08-19T10:37:54.997148232 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.038143682</label>
-<label id="38274.997152901">2019-08-19T10:37:54.997152901 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.017654719</label>
-<label id="38274.997157330">2019-08-19T10:37:54.997157330 cras atlog SLEEP sleep:000000000.020504113 longest_wake:001565104</label>
-<label id="38275.017787246">2019-08-19T10:37:55.017787246 cras atlog WAKE num_fds:0</label>
-<label id="38275.017830417">2019-08-19T10:37:55.017830417 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38275.017874949">2019-08-19T10:37:55.017874949 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.017872854</label>
-<label id="38275.017877797">2019-08-19T10:37:55.017877797 cras atlog FILL_AUDIO dev:6 hw_level:1056</label>
-<label id="38275.017883494">2019-08-19T10:37:55.017883494 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.017885650">2019-08-19T10:37:55.017885650 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.017888461">2019-08-19T10:37:55.017888461 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.017894387">2019-08-19T10:37:55.017894387 cras atlog FILL_AUDIO_DONE hw_level:1056 total_written:0 min_cb_level:1024</label>
-<label id="38275.017914904">2019-08-19T10:37:55.017914904 cras atlog SET_DEV_WAKE dev:6 hw_level:1056 sleep:1008</label>
-<label id="38275.017917003">2019-08-19T10:37:55.017917003 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.038912232</label>
-<label id="38275.017924426">2019-08-19T10:37:55.017924426 cras atlog SLEEP sleep:000000000.020992719 longest_wake:001565104</label>
-<label id="38275.017961913">2019-08-19T10:37:55.017961913 cras atlog WAKE num_fds:1</label>
-<label id="38275.018028433">2019-08-19T10:37:55.018028433 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.018026226</label>
-<label id="38275.018030670">2019-08-19T10:37:55.018030670 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.018034173">2019-08-19T10:37:55.018034173 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.018037396">2019-08-19T10:37:55.018037396 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.018042811">2019-08-19T10:37:55.018042811 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.018044970">2019-08-19T10:37:55.018044970 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.018299235">2019-08-19T10:37:55.018299235 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38275.018320047">2019-08-19T10:37:55.018320047 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38275.018322052">2019-08-19T10:37:55.018322052 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.059651033</label>
-<label id="38275.018326693">2019-08-19T10:37:55.018326693 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.038988052</label>
-<label id="38275.018331332">2019-08-19T10:37:55.018331332 cras atlog SLEEP sleep:000000000.020663485 longest_wake:001565104</label>
-<label id="38275.039056011">2019-08-19T10:37:55.039056011 cras atlog WAKE num_fds:0</label>
-<label id="38275.039099808">2019-08-19T10:37:55.039099808 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38275.039142359">2019-08-19T10:37:55.039142359 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.039140236</label>
-<label id="38275.039145228">2019-08-19T10:37:55.039145228 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38275.039150986">2019-08-19T10:37:55.039150986 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.039153113">2019-08-19T10:37:55.039153113 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.039155910">2019-08-19T10:37:55.039155910 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.039161845">2019-08-19T10:37:55.039161845 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38275.039181369">2019-08-19T10:37:55.039181369 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38275.039183576">2019-08-19T10:37:55.039183576 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.059512041</label>
-<label id="38275.039191418">2019-08-19T10:37:55.039191418 cras atlog SLEEP sleep:000000000.020325678 longest_wake:001565104</label>
-<label id="38275.039242696">2019-08-19T10:37:55.039242696 cras atlog WAKE num_fds:1</label>
-<label id="38275.039300872">2019-08-19T10:37:55.039300872 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.039298791</label>
-<label id="38275.039303282">2019-08-19T10:37:55.039303282 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38275.039307147">2019-08-19T10:37:55.039307147 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.039310453">2019-08-19T10:37:55.039310453 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.039315591">2019-08-19T10:37:55.039315591 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.039317911">2019-08-19T10:37:55.039317911 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.039574431">2019-08-19T10:37:55.039574431 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38275.039595139">2019-08-19T10:37:55.039595139 cras atlog SET_DEV_WAKE dev:6 hw_level:2048 sleep:2000</label>
-<label id="38275.039597215">2019-08-19T10:37:55.039597215 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.081259079</label>
-<label id="38275.039602049">2019-08-19T10:37:55.039602049 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.060321385</label>
-<label id="38275.039606641">2019-08-19T10:37:55.039606641 cras atlog SLEEP sleep:000000000.020721508 longest_wake:001565104</label>
-<label id="38275.060641094">2019-08-19T10:37:55.060641094 cras atlog WAKE num_fds:0</label>
-<label id="38275.060684606">2019-08-19T10:37:55.060684606 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38275.060729748">2019-08-19T10:37:55.060729748 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.060727630</label>
-<label id="38275.060732607">2019-08-19T10:37:55.060732607 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38275.060738367">2019-08-19T10:37:55.060738367 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.060740520">2019-08-19T10:37:55.060740520 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.060743314">2019-08-19T10:37:55.060743314 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.060749371">2019-08-19T10:37:55.060749371 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38275.060769291">2019-08-19T10:37:55.060769291 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38275.060771405">2019-08-19T10:37:55.060771405 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.081432962</label>
-<label id="38275.060778851">2019-08-19T10:37:55.060778851 cras atlog SLEEP sleep:000000000.020659012 longest_wake:001565104</label>
-<label id="38275.060839575">2019-08-19T10:37:55.060839575 cras atlog WAKE num_fds:1</label>
-<label id="38275.060894607">2019-08-19T10:37:55.060894607 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.060892493</label>
-<label id="38275.060896906">2019-08-19T10:37:55.060896906 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38275.060900273">2019-08-19T10:37:55.060900273 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.060903465">2019-08-19T10:37:55.060903465 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.060908541">2019-08-19T10:37:55.060908541 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.060910667">2019-08-19T10:37:55.060910667 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.061189546">2019-08-19T10:37:55.061189546 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38275.061209809">2019-08-19T10:37:55.061209809 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38275.061211862">2019-08-19T10:37:55.061211862 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.102207100</label>
-<label id="38275.061216513">2019-08-19T10:37:55.061216513 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.081654718</label>
-<label id="38275.061221096">2019-08-19T10:37:55.061221096 cras atlog SLEEP sleep:000000000.020440532 longest_wake:001565104</label>
-<label id="38275.081923521">2019-08-19T10:37:55.081923521 cras atlog WAKE num_fds:0</label>
-<label id="38275.081962397">2019-08-19T10:37:55.081962397 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38275.082024685">2019-08-19T10:37:55.082024685 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.082022354</label>
-<label id="38275.082027553">2019-08-19T10:37:55.082027553 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.082033348">2019-08-19T10:37:55.082033348 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.082035492">2019-08-19T10:37:55.082035492 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.082038363">2019-08-19T10:37:55.082038363 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.082044372">2019-08-19T10:37:55.082044372 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38275.082064736">2019-08-19T10:37:55.082064736 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38275.082066844">2019-08-19T10:37:55.082066844 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.102062036</label>
-<label id="38275.082074672">2019-08-19T10:37:55.082074672 cras atlog SLEEP sleep:000000000.019992279 longest_wake:001565104</label>
-<label id="38275.082101703">2019-08-19T10:37:55.082101703 cras atlog WAKE num_fds:1</label>
-<label id="38275.082151613">2019-08-19T10:37:55.082151613 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.082149632</label>
-<label id="38275.082153665">2019-08-19T10:37:55.082153665 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.082156304">2019-08-19T10:37:55.082156304 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.082159578">2019-08-19T10:37:55.082159578 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.082164588">2019-08-19T10:37:55.082164588 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.082166781">2019-08-19T10:37:55.082166781 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.082420700">2019-08-19T10:37:55.082420700 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38275.082440331">2019-08-19T10:37:55.082440331 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38275.082442354">2019-08-19T10:37:55.082442354 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.123771185</label>
-<label id="38275.082446864">2019-08-19T10:37:55.082446864 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.102988051</label>
-<label id="38275.082451229">2019-08-19T10:37:55.082451229 cras atlog SLEEP sleep:000000000.020543317 longest_wake:001565104</label>
-<label id="38275.103235081">2019-08-19T10:37:55.103235081 cras atlog WAKE num_fds:0</label>
-<label id="38275.103278902">2019-08-19T10:37:55.103278902 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38275.103323855">2019-08-19T10:37:55.103323855 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.103321735</label>
-<label id="38275.103326735">2019-08-19T10:37:55.103326735 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38275.103332368">2019-08-19T10:37:55.103332368 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.103334547">2019-08-19T10:37:55.103334547 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.103337442">2019-08-19T10:37:55.103337442 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.103343414">2019-08-19T10:37:55.103343414 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38275.103362951">2019-08-19T10:37:55.103362951 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38275.103365027">2019-08-19T10:37:55.103365027 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.123693749</label>
-<label id="38275.103372515">2019-08-19T10:37:55.103372515 cras atlog SLEEP sleep:000000000.020326206 longest_wake:001565104</label>
-<label id="38275.103495004">2019-08-19T10:37:55.103495004 cras atlog WAKE num_fds:1</label>
-<label id="38275.103558662">2019-08-19T10:37:55.103558662 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.103556509</label>
-<label id="38275.103561185">2019-08-19T10:37:55.103561185 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38275.103565634">2019-08-19T10:37:55.103565634 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.103568909">2019-08-19T10:37:55.103568909 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.103574106">2019-08-19T10:37:55.103574106 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.103576534">2019-08-19T10:37:55.103576534 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.103894760">2019-08-19T10:37:55.103894760 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38275.103915541">2019-08-19T10:37:55.103915541 cras atlog SET_DEV_WAKE dev:6 hw_level:2048 sleep:2000</label>
-<label id="38275.103917608">2019-08-19T10:37:55.103917608 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.145579387</label>
-<label id="38275.103922443">2019-08-19T10:37:55.103922443 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.124321384</label>
-<label id="38275.103927126">2019-08-19T10:37:55.103927126 cras atlog SLEEP sleep:000000000.020401063 longest_wake:001565104</label>
-<label id="38275.124565623">2019-08-19T10:37:55.124565623 cras atlog WAKE num_fds:0</label>
-<label id="38275.124610042">2019-08-19T10:37:55.124610042 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38275.124655051">2019-08-19T10:37:55.124655051 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.124652899</label>
-<label id="38275.124657946">2019-08-19T10:37:55.124657946 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38275.124663566">2019-08-19T10:37:55.124663566 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.124665720">2019-08-19T10:37:55.124665720 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.124668612">2019-08-19T10:37:55.124668612 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.124674855">2019-08-19T10:37:55.124674855 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38275.124694671">2019-08-19T10:37:55.124694671 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38275.124696783">2019-08-19T10:37:55.124696783 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.145358605</label>
-<label id="38275.124704191">2019-08-19T10:37:55.124704191 cras atlog SLEEP sleep:000000000.020659309 longest_wake:001565104</label>
-<label id="38275.124760504">2019-08-19T10:37:55.124760504 cras atlog WAKE num_fds:1</label>
-<label id="38275.124816244">2019-08-19T10:37:55.124816244 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.124814108</label>
-<label id="38275.124818548">2019-08-19T10:37:55.124818548 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38275.124821764">2019-08-19T10:37:55.124821764 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.124825000">2019-08-19T10:37:55.124825000 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.124830095">2019-08-19T10:37:55.124830095 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.124832256">2019-08-19T10:37:55.124832256 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.125110455">2019-08-19T10:37:55.125110455 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38275.125130858">2019-08-19T10:37:55.125130858 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38275.125132923">2019-08-19T10:37:55.125132923 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.166128332</label>
-<label id="38275.125137438">2019-08-19T10:37:55.125137438 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.145654717</label>
-<label id="38275.125141823">2019-08-19T10:37:55.125141823 cras atlog SLEEP sleep:000000000.020519397 longest_wake:001565104</label>
-<label id="38275.145927558">2019-08-19T10:37:55.145927558 cras atlog WAKE num_fds:0</label>
-<label id="38275.145964152">2019-08-19T10:37:55.145964152 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1296</label>
-<label id="38275.146026003">2019-08-19T10:37:55.146026003 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.146023734</label>
-<label id="38275.146029029">2019-08-19T10:37:55.146029029 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.146034797">2019-08-19T10:37:55.146034797 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.146036944">2019-08-19T10:37:55.146036944 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.146039804">2019-08-19T10:37:55.146039804 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.146045532">2019-08-19T10:37:55.146045532 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38275.146065845">2019-08-19T10:37:55.146065845 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38275.146067907">2019-08-19T10:37:55.146067907 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.166063093</label>
-<label id="38275.146075679">2019-08-19T10:37:55.146075679 cras atlog SLEEP sleep:000000000.019992516 longest_wake:001565104</label>
-<label id="38275.146104176">2019-08-19T10:37:55.146104176 cras atlog WAKE num_fds:1</label>
-<label id="38275.146154911">2019-08-19T10:37:55.146154911 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.146152940</label>
-<label id="38275.146157000">2019-08-19T10:37:55.146157000 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.146159732">2019-08-19T10:37:55.146159732 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.146162656">2019-08-19T10:37:55.146162656 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.146167707">2019-08-19T10:37:55.146167707 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.146169907">2019-08-19T10:37:55.146169907 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.146425051">2019-08-19T10:37:55.146425051 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38275.146444659">2019-08-19T10:37:55.146444659 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38275.146446660">2019-08-19T10:37:55.146446660 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.187775515</label>
-<label id="38275.146451169">2019-08-19T10:37:55.146451169 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.166988050</label>
-<label id="38275.146455570">2019-08-19T10:37:55.146455570 cras atlog SLEEP sleep:000000000.020539017 longest_wake:001565104</label>
-<label id="38275.167553074">2019-08-19T10:37:55.167553074 cras atlog WAKE num_fds:0</label>
-<label id="38275.167594886">2019-08-19T10:37:55.167594886 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1312</label>
-<label id="38275.167640114">2019-08-19T10:37:55.167640114 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.167637997</label>
-<label id="38275.167643000">2019-08-19T10:37:55.167643000 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38275.167648699">2019-08-19T10:37:55.167648699 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.167650882">2019-08-19T10:37:55.167650882 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.167653697">2019-08-19T10:37:55.167653697 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.167659615">2019-08-19T10:37:55.167659615 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:0 min_cb_level:1024</label>
-<label id="38275.167679011">2019-08-19T10:37:55.167679011 cras atlog SET_DEV_WAKE dev:6 hw_level:1024 sleep:976</label>
-<label id="38275.167681098">2019-08-19T10:37:55.167681098 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.188009795</label>
-<label id="38275.167688811">2019-08-19T10:37:55.167688811 cras atlog SLEEP sleep:000000000.020326143 longest_wake:001565104</label>
-<label id="38275.167749677">2019-08-19T10:37:55.167749677 cras atlog WAKE num_fds:1</label>
-<label id="38275.167804583">2019-08-19T10:37:55.167804583 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.167802506</label>
-<label id="38275.167806856">2019-08-19T10:37:55.167806856 cras atlog FILL_AUDIO dev:6 hw_level:1024</label>
-<label id="38275.167810111">2019-08-19T10:37:55.167810111 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.167813451">2019-08-19T10:37:55.167813451 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.167818458">2019-08-19T10:37:55.167818458 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.167820591">2019-08-19T10:37:55.167820591 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.168098935">2019-08-19T10:37:55.168098935 cras atlog FILL_AUDIO_DONE hw_level:1024 total_written:1024 min_cb_level:1024</label>
-<label id="38275.168119122">2019-08-19T10:37:55.168119122 cras atlog SET_DEV_WAKE dev:6 hw_level:2000 sleep:1952</label>
-<label id="38275.168121172">2019-08-19T10:37:55.168121172 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.208783150</label>
-<label id="38275.168125546">2019-08-19T10:37:55.168125546 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.188321383</label>
-<label id="38275.168129938">2019-08-19T10:37:55.168129938 cras atlog SLEEP sleep:000000000.020197922 longest_wake:001565104</label>
-<label id="38275.188638183">2019-08-19T10:37:55.188638183 cras atlog WAKE num_fds:0</label>
-<label id="38275.188682360">2019-08-19T10:37:55.188682360 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1328</label>
-<label id="38275.188727068">2019-08-19T10:37:55.188727068 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.188724948</label>
-<label id="38275.188729928">2019-08-19T10:37:55.188729928 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38275.188735860">2019-08-19T10:37:55.188735860 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.188738005">2019-08-19T10:37:55.188738005 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.188740801">2019-08-19T10:37:55.188740801 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.188746886">2019-08-19T10:37:55.188746886 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:0 min_cb_level:1024</label>
-<label id="38275.188766573">2019-08-19T10:37:55.188766573 cras atlog SET_DEV_WAKE dev:6 hw_level:1040 sleep:992</label>
-<label id="38275.188768680">2019-08-19T10:37:55.188768680 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.209430581</label>
-<label id="38275.188776647">2019-08-19T10:37:55.188776647 cras atlog SLEEP sleep:000000000.020659030 longest_wake:001565104</label>
-<label id="38275.188837092">2019-08-19T10:37:55.188837092 cras atlog WAKE num_fds:1</label>
-<label id="38275.188891865">2019-08-19T10:37:55.188891865 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.188889848</label>
-<label id="38275.188894276">2019-08-19T10:37:55.188894276 cras atlog FILL_AUDIO dev:6 hw_level:1040</label>
-<label id="38275.188897503">2019-08-19T10:37:55.188897503 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.188900748">2019-08-19T10:37:55.188900748 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.188905918">2019-08-19T10:37:55.188905918 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.188908049">2019-08-19T10:37:55.188908049 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.189185844">2019-08-19T10:37:55.189185844 cras atlog FILL_AUDIO_DONE hw_level:1040 total_written:1024 min_cb_level:1024</label>
-<label id="38275.189205852">2019-08-19T10:37:55.189205852 cras atlog SET_DEV_WAKE dev:6 hw_level:2016 sleep:1968</label>
-<label id="38275.189207862">2019-08-19T10:37:55.189207862 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.230203316</label>
-<label id="38275.189212302">2019-08-19T10:37:55.189212302 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.209654716</label>
-<label id="38275.189216722">2019-08-19T10:37:55.189216722 cras atlog SLEEP sleep:000000000.020444572 longest_wake:001565104</label>
-<label id="38275.209911683">2019-08-19T10:37:55.209911683 cras atlog WAKE num_fds:0</label>
-<label id="38275.209955429">2019-08-19T10:37:55.209955429 cras atlog WRITE_STREAMS_FETCH_STREAM id:1d0000 cbth:1024 delay:1344</label>
-<label id="38275.210000864">2019-08-19T10:37:55.210000864 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.209998749</label>
-<label id="38275.210020752">2019-08-19T10:37:55.210020752 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.210026614">2019-08-19T10:37:55.210026614 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:0 cb_pending:1</label>
-<label id="38275.210028898">2019-08-19T10:37:55.210028898 cras atlog WRITE_STREAMS_MIX write_limit:0 max_offset:0</label>
-<label id="38275.210031723">2019-08-19T10:37:55.210031723 cras atlog WRITE_STREAMS_MIXED write_limit:0</label>
-<label id="38275.210038139">2019-08-19T10:37:55.210038139 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:0 min_cb_level:1024</label>
-<label id="38275.210058744">2019-08-19T10:37:55.210058744 cras atlog SET_DEV_WAKE dev:6 hw_level:1008 sleep:960</label>
-<label id="38275.210060812">2019-08-19T10:37:55.210060812 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.230056030</label>
-<label id="38275.210068424">2019-08-19T10:37:55.210068424 cras atlog SLEEP sleep:000000000.019992546 longest_wake:001565104</label>
-<label id="38275.210096165">2019-08-19T10:37:55.210096165 cras atlog WAKE num_fds:1</label>
-<label id="38275.210146366">2019-08-19T10:37:55.210146366 cras atlog FILL_AUDIO_TSTAMP dev:6 tstamp: 10:37:55.210144294</label>
-<label id="38275.210148466">2019-08-19T10:37:55.210148466 cras atlog FILL_AUDIO dev:6 hw_level:1008</label>
-<label id="38275.210151084">2019-08-19T10:37:55.210151084 cras atlog WRITE_STREAMS_STREAM id:1d0000 shm_frames:1024 cb_pending:0</label>
-<label id="38275.210154312">2019-08-19T10:37:55.210154312 cras atlog WRITE_STREAMS_MIX write_limit:1024 max_offset:0</label>
-<label id="38275.210159347">2019-08-19T10:37:55.210159347 cras atlog DEV_STREAM_MIX written:1024 read:1024</label>
-<label id="38275.210161490">2019-08-19T10:37:55.210161490 cras atlog WRITE_STREAMS_MIXED write_limit:1024</label>
-<label id="38275.210414903">2019-08-19T10:37:55.210414903 cras atlog FILL_AUDIO_DONE hw_level:1008 total_written:1024 min_cb_level:1024</label>
-<label id="38275.210434597">2019-08-19T10:37:55.210434597 cras atlog SET_DEV_WAKE dev:6 hw_level:2032 sleep:1984</label>
-<label id="38275.210436597">2019-08-19T10:37:55.210436597 cras atlog DEV_SLEEP_TIME dev:6 wake: 10:37:55.251765477</label>
-<label id="38275.210441028">2019-08-19T10:37:55.210441028 cras atlog STREAM_SLEEP_TIME id:1d0000 wake: 10:37:55.230988049</label>
-<label id="38275.210445345">2019-08-19T10:37:55.210445345 cras atlog SLEEP sleep:000000000.020549158 longest_wake:001565104</label>
-<label id="38275.222778298">2019-08-19T10:37:55.222778298 cras atlog WAKE num_fds:1</label>
-<label id="38275.222790909">2019-08-19T10:37:55.222790909 cras atlog PB_MSG msg_id:7</label>
-<label id="38275.222796197">2019-08-19T10:37:55.222796197 cras atlog STREAM_REMOVED id:1d0000</label>`;
- put_logs = function () {
- document.getElementById('logs').innerHTML = logs;
- };
-
- set_initial_checkbox_value = function () {
- document.getElementById('device').checked = true;
- document.getElementById('stream').checked = true;
- document.getElementById('fetch').checked = true;
- document.getElementById('wake').checked = true;
- }
-
- window.onload = function() {
- draw_chart();
- put_logs();
- set_initial_checkbox_value();
- };
-
- function handleClick(checkbox) {
- var class_name = checkbox.id;
- var elements = document.getElementsByClassName(class_name);
- var i;
-
- if (checkbox.checked) {
- display_value = "block";
- } else {
- display_value = "none"
- }
-
- console.log("change " + class_name + " to " + display_value);
- for (i = 0; i < elements.length; i++) {
- elements[i].style.display = display_value;
- }
- }
-
- </script>
-</head>
-
-<body>
- <div id="chart" style="height:50%; width:100%" ></div>
- <div style="margin:0 auto"; class="checkbox">
- <label><input type="checkbox" onclick="handleClick(this);" id="device">Show device removed/added event</label>
- <label><input type="checkbox" onclick="handleClick(this);" id="stream">Show stream removed/added event</label>
- <label><input type="checkbox" onclick="handleClick(this);" id="fetch">Show fetch event</label>
- <label><input type="checkbox" onclick="handleClick(this);" id="wake">Show wake by num_fds=1 event</label>
- </div>
- <div class="event_log_box", id="logs", style="float:left;"></div>
- <textarea class="event_log_box", id="text", style="float:right;"></textarea>
-</body>
-</html>
diff --git a/scripts/audio_thread_log_viewer/log.test b/scripts/audio_thread_log_viewer/log.test
deleted file mode 100644
index 8206761d..00000000
--- a/scripts/audio_thread_log_viewer/log.test
+++ /dev/null
@@ -1,6151 +0,0 @@
-Audio Debug Stats:
--------------devices------------
-Output dev: bdw-rt5677: :1,0
-65536 0 1024 0 48000 2 1.000000
--------------stream_dump------------
-Audio Thread Event Log:
-start at 736
- 496098.524565708 DEV_SLEEP_TIME dev:8 wake:000496098.545892346
- 496098.524567126 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.545959543 WAKE num_fds:0
- 496098.545994178 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.546000808 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.546001355 DEV_SLEEP_TIME dev:8 wake:000496098.567328258
- 496098.546002783 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.567581739 WAKE num_fds:0
- 496098.567615773 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.567622518 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.567623059 DEV_SLEEP_TIME dev:8 wake:000496098.588949912
- 496098.567624543 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.589207274 WAKE num_fds:0
- 496098.589240896 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.589247582 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.589248133 DEV_SLEEP_TIME dev:8 wake:000496098.610574976
- 496098.589250062 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.610821201 WAKE num_fds:0
- 496098.610854808 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.610861519 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.610862050 DEV_SLEEP_TIME dev:8 wake:000496098.632188948
- 496098.610863463 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.632443051 WAKE num_fds:0
- 496098.632476082 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.632482753 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.632483289 DEV_SLEEP_TIME dev:8 wake:000496098.653810157
- 496098.632484727 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.654059981 WAKE num_fds:0
- 496098.654093774 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.654100469 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.654101015 DEV_SLEEP_TIME dev:8 wake:000496098.675427884
- 496098.654102514 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.675676644 WAKE num_fds:0
- 496098.675709505 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.675715664 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.675716210 DEV_SLEEP_TIME dev:8 wake:000496098.697043620
- 496098.675717624 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.697292000 WAKE num_fds:0
- 496098.697325252 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.697331912 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.697332439 DEV_SLEEP_TIME dev:8 wake:000496098.718659357
- 496098.697333932 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.718759444 WAKE num_fds:0
- 496098.718791864 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.718798584 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.718799116 DEV_SLEEP_TIME dev:8 wake:000496098.740125964
- 496098.718800569 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.740374739 WAKE num_fds:0
- 496098.740407625 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.740414446 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.740414982 DEV_SLEEP_TIME dev:8 wake:000496098.761741745
- 496098.740416420 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.761990271 WAKE num_fds:0
- 496098.762023593 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.762030293 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.762030839 DEV_SLEEP_TIME dev:8 wake:000496098.783357712
- 496098.762032303 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.783607275 WAKE num_fds:0
- 496098.783640005 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.783646686 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.783647222 DEV_SLEEP_TIME dev:8 wake:000496098.804974110
- 496098.783648665 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.805225207 WAKE num_fds:0
- 496098.805258890 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.805265655 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.805266202 DEV_SLEEP_TIME dev:8 wake:000496098.826592999
- 496098.805267675 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.826841354 WAKE num_fds:0
- 496098.826874200 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.826880900 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.826881567 DEV_SLEEP_TIME dev:8 wake:000496098.848208295
- 496098.826883075 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.848306238 WAKE num_fds:0
- 496098.848338928 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.848345624 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.848346165 DEV_SLEEP_TIME dev:8 wake:000496098.869673018
- 496098.848367619 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.869943940 WAKE num_fds:0
- 496098.869977317 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.869983927 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.869984473 DEV_SLEEP_TIME dev:8 wake:000496098.891311411
- 496098.869985886 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.891556864 WAKE num_fds:0
- 496098.891589740 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.891596290 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.891596837 DEV_SLEEP_TIME dev:8 wake:000496098.912923825
- 496098.891598310 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.913173874 WAKE num_fds:0
- 496098.913207412 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.913214077 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.913214734 DEV_SLEEP_TIME dev:8 wake:000496098.934541466
- 496098.913216312 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.934788182 WAKE num_fds:0
- 496098.934820552 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.934827267 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.934827799 DEV_SLEEP_TIME dev:8 wake:000496098.956154637
- 496098.934829237 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.956406414 WAKE num_fds:0
- 496098.956439565 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.956446341 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.956446872 DEV_SLEEP_TIME dev:8 wake:000496098.977773730
- 496098.956448321 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.978020778 WAKE num_fds:0
- 496098.978053749 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496098.978060374 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.978060916 DEV_SLEEP_TIME dev:8 wake:000496098.999387834
- 496098.978062359 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496098.999634870 WAKE num_fds:0
- 496098.999667952 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496098.999674592 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496098.999675198 DEV_SLEEP_TIME dev:8 wake:000496099.021002041
- 496098.999676632 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.021101388 WAKE num_fds:0
- 496099.021133918 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.021140623 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.021141155 DEV_SLEEP_TIME dev:8 wake:000496099.042468008
- 496099.021142573 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.042718602 WAKE num_fds:0
- 496099.042751734 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.042758414 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.042758961 DEV_SLEEP_TIME dev:8 wake:000496099.064085824
- 496099.042760384 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.064330956 WAKE num_fds:0
- 496099.064382264 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.064388955 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.064389501 DEV_SLEEP_TIME dev:8 wake:000496099.085716384
- 496099.064390929 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.085964449 WAKE num_fds:0
- 496099.085997670 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.086004286 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.086004822 DEV_SLEEP_TIME dev:8 wake:000496099.107331775
- 496099.086006386 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.107586550 WAKE num_fds:0
- 496099.107619801 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.107626397 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.107626938 DEV_SLEEP_TIME dev:8 wake:000496099.128953866
- 496099.107628366 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.129204762 WAKE num_fds:0
- 496099.129237403 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.129244023 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.129244569 DEV_SLEEP_TIME dev:8 wake:000496099.150571487
- 496099.129246008 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.150641335 WAKE num_fds:0
- 496099.150673374 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.150680004 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.150680656 DEV_SLEEP_TIME dev:8 wake:000496099.172007509
- 496099.150682074 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.172256786 WAKE num_fds:0
- 496099.172289878 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.172296493 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.172297034 DEV_SLEEP_TIME dev:8 wake:000496099.193623983
- 496099.172298478 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.193874512 WAKE num_fds:0
- 496099.193907859 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.193914469 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.193915006 DEV_SLEEP_TIME dev:8 wake:000496099.215241949
- 496099.193916414 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.215492809 WAKE num_fds:0
- 496099.215525304 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.215531864 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.215532421 DEV_SLEEP_TIME dev:8 wake:000496099.236859384
- 496099.215533834 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.237111493 WAKE num_fds:0
- 496099.237143973 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.237150678 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.237151210 DEV_SLEEP_TIME dev:8 wake:000496099.258478073
- 496099.237152628 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.258726588 WAKE num_fds:0
- 496099.258759554 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.258766124 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.258766665 DEV_SLEEP_TIME dev:8 wake:000496099.280093668
- 496099.258768219 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.280340434 WAKE num_fds:0
- 496099.280393006 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.280399631 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.280400182 DEV_SLEEP_TIME dev:8 wake:000496099.301727090
- 496099.280401641 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.301975591 WAKE num_fds:0
- 496099.302008723 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.302015493 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.302016025 DEV_SLEEP_TIME dev:8 wake:000496099.323342868
- 496099.302017463 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.323440980 WAKE num_fds:0
- 496099.323477615 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.323484245 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.323484791 DEV_SLEEP_TIME dev:8 wake:000496099.344811715
- 496099.323486230 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.345086125 WAKE num_fds:0
- 496099.345126263 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.345131465 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.345131996 DEV_SLEEP_TIME dev:8 wake:000496099.366460378
- 496099.345133429 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.366708151 WAKE num_fds:0
- 496099.366739964 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.366746760 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.366747432 DEV_SLEEP_TIME dev:8 wake:000496099.388074069
- 496099.366748880 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.388144614 WAKE num_fds:0
- 496099.388176969 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.388183740 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.388184281 DEV_SLEEP_TIME dev:8 wake:000496099.409511159
- 496099.388185724 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.409545707 WAKE num_fds:0
- 496099.409566242 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.409571665 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.409571919 DEV_SLEEP_TIME dev:8 wake:000496099.430899910
- 496099.409572582 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.430927759 WAKE num_fds:0
- 496099.430955957 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.430962098 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.430962539 DEV_SLEEP_TIME dev:8 wake:000496099.452289928
- 496099.430963662 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.452379104 WAKE num_fds:0
- 496099.452413514 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.452418641 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.452419177 DEV_SLEEP_TIME dev:8 wake:000496099.473747588
- 496099.452420710 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.473884983 WAKE num_fds:0
- 496099.473917934 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.473924589 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.473925130 DEV_SLEEP_TIME dev:8 wake:000496099.495252069
- 496099.473926564 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.495367456 WAKE num_fds:0
- 496099.495399996 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.495406612 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.495407158 DEV_SLEEP_TIME dev:8 wake:000496099.516734061
- 496099.495408727 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.516763201 WAKE num_fds:0
- 496099.516795615 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.516802181 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.516802732 DEV_SLEEP_TIME dev:8 wake:000496099.538129745
- 496099.516804095 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.538207146 WAKE num_fds:0
- 496099.538238564 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.538245094 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.538245665 DEV_SLEEP_TIME dev:8 wake:000496099.559572673
- 496099.538247123 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.559628849 WAKE num_fds:0
- 496099.559659896 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.559665359 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.559665890 DEV_SLEEP_TIME dev:8 wake:000496099.580994046
- 496099.559667333 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.581019938 WAKE num_fds:0
- 496099.581050679 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.581057460 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.581057996 DEV_SLEEP_TIME dev:8 wake:000496099.602384964
- 496099.581059284 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.602418768 WAKE num_fds:0
- 496099.602454421 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.602462449 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.602463206 DEV_SLEEP_TIME dev:8 wake:000496099.623788801
- 496099.602465055 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.623858429 WAKE num_fds:0
- 496099.623890809 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.623897589 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.623898131 DEV_SLEEP_TIME dev:8 wake:000496099.645224914
- 496099.623899609 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.645296641 WAKE num_fds:0
- 496099.645334724 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.645340272 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.645340808 DEV_SLEEP_TIME dev:8 wake:000496099.666668954
- 496099.645342192 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.666692849 WAKE num_fds:0
- 496099.666719109 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.666725256 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.666725704 DEV_SLEEP_TIME dev:8 wake:000496099.688053104
- 496099.666726894 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.688074387 WAKE num_fds:0
- 496099.688096225 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.688101841 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.688102175 DEV_SLEEP_TIME dev:8 wake:000496099.709430072
- 496099.688102887 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.709443343 WAKE num_fds:0
- 496099.709455328 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.709459005 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.709459229 DEV_SLEEP_TIME dev:8 wake:000496099.730788957
- 496099.709459736 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.730805574 WAKE num_fds:0
- 496099.730824543 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.730829830 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.730830098 DEV_SLEEP_TIME dev:8 wake:000496099.752158351
- 496099.730830581 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.752172469 WAKE num_fds:0
- 496099.752187265 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.752190979 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.752191240 DEV_SLEEP_TIME dev:8 wake:000496099.773520970
- 496099.752191743 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.773533690 WAKE num_fds:0
- 496099.773549159 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.773552607 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.773552834 DEV_SLEEP_TIME dev:8 wake:000496099.794882783
- 496099.773553393 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.794893261 WAKE num_fds:0
- 496099.794905112 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.794908388 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.794908531 DEV_SLEEP_TIME dev:8 wake:000496099.816238663
- 496099.794908990 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.816248944 WAKE num_fds:0
- 496099.816260791 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.816263965 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.816264138 DEV_SLEEP_TIME dev:8 wake:000496099.837594355
- 496099.816264504 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.837604072 WAKE num_fds:0
- 496099.837616853 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.837619986 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.837620168 DEV_SLEEP_TIME dev:8 wake:000496099.858950398
- 496099.837620511 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.858961345 WAKE num_fds:0
- 496099.858976724 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.858979930 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.858980107 DEV_SLEEP_TIME dev:8 wake:000496099.880310281
- 496099.858980424 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.880319596 WAKE num_fds:0
- 496099.880330501 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.880333657 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.880333835 DEV_SLEEP_TIME dev:8 wake:000496099.901664064
- 496099.880334293 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.901673173 WAKE num_fds:0
- 496099.901683309 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.901686399 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.901686518 DEV_SLEEP_TIME dev:8 wake:000496099.923016808
- 496099.901686986 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.923026422 WAKE num_fds:0
- 496099.923039650 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.923042794 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.923042971 DEV_SLEEP_TIME dev:8 wake:000496099.944373193
- 496099.923043433 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.944382798 WAKE num_fds:0
- 496099.944393969 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.944397102 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.944397285 DEV_SLEEP_TIME dev:8 wake:000496099.965727428
- 496099.944397681 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.965737960 WAKE num_fds:0
- 496099.965751311 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496099.965754524 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.965754702 DEV_SLEEP_TIME dev:8 wake:000496099.987084869
- 496099.965755111 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496099.987093719 WAKE num_fds:0
- 496099.987104561 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496099.987107677 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496099.987107905 DEV_SLEEP_TIME dev:8 wake:000496100.008438069
- 496099.987108340 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.008446847 WAKE num_fds:0
- 496100.008457382 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.008460682 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.008460869 DEV_SLEEP_TIME dev:8 wake:000496100.029790961
- 496100.008461246 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.029818678 WAKE num_fds:0
- 496100.029837149 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.029843078 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.029843305 DEV_SLEEP_TIME dev:8 wake:000496100.051171009
- 496100.029843952 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.051190229 WAKE num_fds:0
- 496100.051209390 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.051214799 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.051215052 DEV_SLEEP_TIME dev:8 wake:000496100.072543113
- 496100.051215796 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.072561196 WAKE num_fds:0
- 496100.072576819 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.072580750 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.072581115 DEV_SLEEP_TIME dev:8 wake:000496100.093910689
- 496100.072581922 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.093973259 WAKE num_fds:0
- 496100.093991762 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.093995366 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.093995594 DEV_SLEEP_TIME dev:8 wake:000496100.115325510
- 496100.093996174 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.115537814 WAKE num_fds:0
- 496100.115557401 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.115560841 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.115561080 DEV_SLEEP_TIME dev:8 wake:000496100.136891036
- 496100.115561681 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.137102895 WAKE num_fds:0
- 496100.137121895 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.137125352 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.137125589 DEV_SLEEP_TIME dev:8 wake:000496100.158455544
- 496100.137126194 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.158690778 WAKE num_fds:0
- 496100.158718867 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.158724914 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.158725362 DEV_SLEEP_TIME dev:8 wake:000496100.180052858
- 496100.158726597 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.180291907 WAKE num_fds:0
- 496100.180334939 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.180341137 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.180341694 DEV_SLEEP_TIME dev:8 wake:000496100.201668888
- 496100.180342901 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.201904895 WAKE num_fds:0
- 496100.201935065 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.201941215 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.201941653 DEV_SLEEP_TIME dev:8 wake:000496100.223269028
- 496100.201942826 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.223392063 WAKE num_fds:0
- 496100.223421828 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.223427926 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.223428484 DEV_SLEEP_TIME dev:8 wake:000496100.244755795
- 496100.223429666 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.245001270 WAKE num_fds:0
- 496100.245034126 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.245041097 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.245041638 DEV_SLEEP_TIME dev:8 wake:000496100.266368371
- 496100.245043102 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.266620745 WAKE num_fds:0
- 496100.266654027 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.266660717 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.266661253 DEV_SLEEP_TIME dev:8 wake:000496100.287988172
- 496100.266662682 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.288238777 WAKE num_fds:0
- 496100.288272199 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.288278840 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.288279496 DEV_SLEEP_TIME dev:8 wake:000496100.309606269
- 496100.288280920 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.309680702 WAKE num_fds:0
- 496100.309714560 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.309721221 SET_DEV_WAKE dev:8 hw_level:2000 sleep:976
- 496100.309721767 DEV_SLEEP_TIME dev:8 wake:000496100.330048685
- 496100.309723215 SLEEP sleep:000000000.020333333 longest_wake:000158140
- 496100.330297374 WAKE num_fds:0
- 496100.330330320 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.330336875 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.330337422 DEV_SLEEP_TIME dev:8 wake:000496100.351664410
- 496100.330338870 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.351764312 WAKE num_fds:0
- 496100.351796516 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.351803227 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.351803773 DEV_SLEEP_TIME dev:8 wake:000496100.373130636
- 496100.351805196 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.373381346 WAKE num_fds:0
- 496100.373414302 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.373421028 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.373421579 DEV_SLEEP_TIME dev:8 wake:000496100.394748397
- 496100.373422997 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.394996512 WAKE num_fds:0
- 496100.395030009 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.395036710 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.395037256 DEV_SLEEP_TIME dev:8 wake:000496100.416364124
- 496100.395038699 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.416614232 WAKE num_fds:0
- 496100.416646743 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.416653363 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.416653904 DEV_SLEEP_TIME dev:8 wake:000496100.437980857
- 496100.416655448 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.438214409 WAKE num_fds:0
- 496100.438247169 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.438253865 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.438254401 DEV_SLEEP_TIME dev:8 wake:000496100.459581389
- 496100.438255839 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.459827454 WAKE num_fds:0
- 496100.459861848 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.459868483 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.459869060 DEV_SLEEP_TIME dev:8 wake:000496100.481195973
- 496100.459870483 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.481448141 WAKE num_fds:0
- 496100.481481212 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.481487983 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.481488559 DEV_SLEEP_TIME dev:8 wake:000496100.502815503
- 496100.481489988 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.503061022 WAKE num_fds:0
- 496100.503093867 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.503100483 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.503101054 DEV_SLEEP_TIME dev:8 wake:000496100.524427977
- 496100.503102497 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.524533081 WAKE num_fds:0
- 496100.524566132 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.524572718 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.524573259 DEV_SLEEP_TIME dev:8 wake:000496100.545900277
- 496100.524574737 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.546150402 WAKE num_fds:0
- 496100.546183914 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.546190600 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.546191141 DEV_SLEEP_TIME dev:8 wake:000496100.567517989
- 496100.546192584 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.567766865 WAKE num_fds:0
- 496100.567800633 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.567807248 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.567807789 DEV_SLEEP_TIME dev:8 wake:000496100.589134742
- 496100.567809222 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.589386409 WAKE num_fds:0
- 496100.589419551 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.589426096 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.589426642 DEV_SLEEP_TIME dev:8 wake:000496100.610753641
- 496100.589428091 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.611000528 WAKE num_fds:0
- 496100.611033584 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.611040440 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.611040991 DEV_SLEEP_TIME dev:8 wake:000496100.632367749
- 496100.611042425 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.632618399 WAKE num_fds:0
- 496100.632651826 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.632658577 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.632659118 DEV_SLEEP_TIME dev:8 wake:000496100.653985931
- 496100.632660526 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.654089236 WAKE num_fds:0
- 496100.654122483 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.654129063 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.654129610 DEV_SLEEP_TIME dev:8 wake:000496100.675456613
- 496100.654131033 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.675707809 WAKE num_fds:0
- 496100.675739668 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.675746323 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.675746884 DEV_SLEEP_TIME dev:8 wake:000496100.697073767
- 496100.675748318 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.697320964 WAKE num_fds:0
- 496100.697371546 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.697378417 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.697378968 DEV_SLEEP_TIME dev:8 wake:000496100.718705691
- 496100.697380422 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.718805258 WAKE num_fds:0
- 496100.718838966 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.718845586 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.718846132 DEV_SLEEP_TIME dev:8 wake:000496100.740173041
- 496100.718847591 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.740425615 WAKE num_fds:0
- 496100.740458811 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.740465657 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.740466203 DEV_SLEEP_TIME dev:8 wake:000496100.761793051
- 496100.740467632 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.761892959 WAKE num_fds:0
- 496100.761925459 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.761932105 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.761932776 DEV_SLEEP_TIME dev:8 wake:000496100.783259524
- 496100.761934220 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.783381637 WAKE num_fds:0
- 496100.783414944 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.783421680 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.783422226 DEV_SLEEP_TIME dev:8 wake:000496100.804749039
- 496100.783423649 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.804853272 WAKE num_fds:0
- 496100.804885807 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.804892417 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.804892963 DEV_SLEEP_TIME dev:8 wake:000496100.826219907
- 496100.804894402 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.826322110 WAKE num_fds:0
- 496100.826373047 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.826380063 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.826380610 DEV_SLEEP_TIME dev:8 wake:000496100.847707192
- 496100.826382018 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.847959501 WAKE num_fds:0
- 496100.847992322 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.847999067 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.847999618 DEV_SLEEP_TIME dev:8 wake:000496100.869326431
- 496100.848001317 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.869578930 WAKE num_fds:0
- 496100.869612292 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.869619023 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.869619574 DEV_SLEEP_TIME dev:8 wake:000496100.890946412
- 496100.869620997 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.891197770 WAKE num_fds:0
- 496100.891230550 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.891237110 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.891237787 DEV_SLEEP_TIME dev:8 wake:000496100.912564655
- 496100.891239220 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.912816197 WAKE num_fds:0
- 496100.912849323 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.912855848 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.912856420 DEV_SLEEP_TIME dev:8 wake:000496100.934183418
- 496100.912857878 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.934430826 WAKE num_fds:0
- 496100.934464102 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.934470708 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.934471254 DEV_SLEEP_TIME dev:8 wake:000496100.955798272
- 496100.934472697 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.955901337 WAKE num_fds:0
- 496100.955933948 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.955940678 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.955941229 DEV_SLEEP_TIME dev:8 wake:000496100.977268047
- 496100.955942683 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.977519955 WAKE num_fds:0
- 496100.977552550 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496100.977559256 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.977559822 DEV_SLEEP_TIME dev:8 wake:000496100.998886650
- 496100.977561271 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496100.999137892 WAKE num_fds:0
- 496100.999169961 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496100.999176612 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496100.999177088 DEV_SLEEP_TIME dev:8 wake:000496101.020504061
- 496100.999178456 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.020757502 WAKE num_fds:0
- 496101.020790759 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.020797399 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.020797941 DEV_SLEEP_TIME dev:8 wake:000496101.042124944
- 496101.020799364 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.042376561 WAKE num_fds:0
- 496101.042409227 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.042415827 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.042416388 DEV_SLEEP_TIME dev:8 wake:000496101.063743316
- 496101.042417987 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.063993676 WAKE num_fds:0
- 496101.064026808 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.064033453 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.064033994 DEV_SLEEP_TIME dev:8 wake:000496101.085360928
- 496101.064035438 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.085608450 WAKE num_fds:0
- 496101.085642659 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.085649365 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.085649901 DEV_SLEEP_TIME dev:8 wake:000496101.106976764
- 496101.085651324 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.107228552 WAKE num_fds:0
- 496101.107261478 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.107268179 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.107268720 DEV_SLEEP_TIME dev:8 wake:000496101.128595704
- 496101.107270164 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.128696698 WAKE num_fds:0
- 496101.128726381 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.128733227 SET_DEV_WAKE dev:8 hw_level:2000 sleep:976
- 496101.128733768 DEV_SLEEP_TIME dev:8 wake:000496101.149060501
- 496101.128735212 SLEEP sleep:000000000.020333333 longest_wake:000158140
- 496101.149310393 WAKE num_fds:0
- 496101.149343359 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.149381326 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.149381917 DEV_SLEEP_TIME dev:8 wake:000496101.170677469
- 496101.149383436 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.170961115 WAKE num_fds:0
- 496101.170994692 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.171001378 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.171001924 DEV_SLEEP_TIME dev:8 wake:000496101.192328802
- 496101.171003367 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.192580429 WAKE num_fds:0
- 496101.192613290 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.192619910 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.192620462 DEV_SLEEP_TIME dev:8 wake:000496101.213947420
- 496101.192621920 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.214192247 WAKE num_fds:0
- 496101.214224998 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.214231573 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.214232119 DEV_SLEEP_TIME dev:8 wake:000496101.235559088
- 496101.214233553 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.235808094 WAKE num_fds:0
- 496101.235840980 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.235847595 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.235848146 DEV_SLEEP_TIME dev:8 wake:000496101.257175089
- 496101.235849590 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.257275849 WAKE num_fds:0
- 496101.257308500 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.257315135 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.257315676 DEV_SLEEP_TIME dev:8 wake:000496101.278642594
- 496101.257317104 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.278887125 WAKE num_fds:0
- 496101.278919525 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.278926135 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.278926676 DEV_SLEEP_TIME dev:8 wake:000496101.300253620
- 496101.278928120 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.300391730 WAKE num_fds:0
- 496101.300424490 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.300431176 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.300431722 DEV_SLEEP_TIME dev:8 wake:000496101.321758585
- 496101.300433160 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.322005658 WAKE num_fds:0
- 496101.322038759 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.322045274 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.322045820 DEV_SLEEP_TIME dev:8 wake:000496101.343372864
- 496101.322047254 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.343623649 WAKE num_fds:0
- 496101.343656334 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.343662930 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.343663471 DEV_SLEEP_TIME dev:8 wake:000496101.364990429
- 496101.343664909 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.365239140 WAKE num_fds:0
- 496101.365272096 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.365278837 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.365279378 DEV_SLEEP_TIME dev:8 wake:000496101.386606216
- 496101.365280832 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.386856460 WAKE num_fds:0
- 496101.386890138 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.386896783 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.386897330 DEV_SLEEP_TIME dev:8 wake:000496101.408224208
- 496101.386898763 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.408472672 WAKE num_fds:0
- 496101.408505724 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.408512364 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.408512905 DEV_SLEEP_TIME dev:8 wake:000496101.429839848
- 496101.408514329 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.429906550 WAKE num_fds:0
- 496101.429938428 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.429944993 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.429945535 DEV_SLEEP_TIME dev:8 wake:000496101.451272568
- 496101.429946993 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.451524275 WAKE num_fds:0
- 496101.451557176 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.451563777 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.451564328 DEV_SLEEP_TIME dev:8 wake:000496101.472891271
- 496101.451565906 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.473137346 WAKE num_fds:0
- 496101.473170368 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.473177068 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.473177609 DEV_SLEEP_TIME dev:8 wake:000496101.494504467
- 496101.473179058 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.494599058 WAKE num_fds:0
- 496101.494630274 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.494636524 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.494637017 DEV_SLEEP_TIME dev:8 wake:000496101.515964292
- 496101.494638308 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.516182970 WAKE num_fds:0
- 496101.516214183 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.516220585 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.516221074 DEV_SLEEP_TIME dev:8 wake:000496101.537548225
- 496101.516222409 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.537791076 WAKE num_fds:0
- 496101.537822243 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.537828687 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.537829164 DEV_SLEEP_TIME dev:8 wake:000496101.559156302
- 496101.537830627 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.559252688 WAKE num_fds:0
- 496101.559283407 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.559289745 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.559290243 DEV_SLEEP_TIME dev:8 wake:000496101.580617438
- 496101.559291526 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.580861870 WAKE num_fds:0
- 496101.580893182 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.580899553 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.580900034 DEV_SLEEP_TIME dev:8 wake:000496101.602227209
- 496101.580901321 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.602471830 WAKE num_fds:0
- 496101.602503226 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.602509601 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.602510086 DEV_SLEEP_TIME dev:8 wake:000496101.623837257
- 496101.602511361 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.624078044 WAKE num_fds:0
- 496101.624109220 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.624115607 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.624116088 DEV_SLEEP_TIME dev:8 wake:000496101.645443234
- 496101.624117382 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.645685689 WAKE num_fds:0
- 496101.645715144 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.645721455 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.645721940 DEV_SLEEP_TIME dev:8 wake:000496101.667049171
- 496101.645723231 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.667144488 WAKE num_fds:0
- 496101.667175468 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.667182259 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.667182761 DEV_SLEEP_TIME dev:8 wake:000496101.688509494
- 496101.667184067 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.688754196 WAKE num_fds:0
- 496101.688785797 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.688792043 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.688792544 DEV_SLEEP_TIME dev:8 wake:000496101.710119799
- 496101.688793835 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.710368568 WAKE num_fds:0
- 496101.710399467 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.710405854 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.710406339 DEV_SLEEP_TIME dev:8 wake:000496101.731733498
- 496101.710407618 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.731827954 WAKE num_fds:0
- 496101.731858565 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.731864803 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.731865301 DEV_SLEEP_TIME dev:8 wake:000496101.753192595
- 496101.731866592 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.753434542 WAKE num_fds:0
- 496101.753465201 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.753471516 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.753472073 DEV_SLEEP_TIME dev:8 wake:000496101.774799220
- 496101.753473400 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.775034482 WAKE num_fds:0
- 496101.775064488 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.775070890 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.775071391 DEV_SLEEP_TIME dev:8 wake:000496101.796398646
- 496101.775072682 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.796638895 WAKE num_fds:0
- 496101.796669879 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.796676257 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.796676734 DEV_SLEEP_TIME dev:8 wake:000496101.818003893
- 496101.796678026 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.818247105 WAKE num_fds:0
- 496101.818277917 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.818284203 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.818284684 DEV_SLEEP_TIME dev:8 wake:000496101.839611936
- 496101.818285967 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.839856667 WAKE num_fds:0
- 496101.839887703 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.839893985 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.839894482 DEV_SLEEP_TIME dev:8 wake:000496101.861221745
- 496101.839895877 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.861461557 WAKE num_fds:0
- 496101.861492472 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.861498774 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.861499264 DEV_SLEEP_TIME dev:8 wake:000496101.882826487
- 496101.861500567 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.883067472 WAKE num_fds:0
- 496101.883097802 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.883104085 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.883104586 DEV_SLEEP_TIME dev:8 wake:000496101.904431816
- 496101.883105897 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.904675842 WAKE num_fds:0
- 496101.904707142 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.904712154 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.904712656 DEV_SLEEP_TIME dev:8 wake:000496101.926041285
- 496101.904713943 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.926286481 WAKE num_fds:0
- 496101.926317412 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.926323746 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.926324244 DEV_SLEEP_TIME dev:8 wake:000496101.947651462
- 496101.926325542 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.947894255 WAKE num_fds:0
- 496101.947925656 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.947932034 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.947932528 DEV_SLEEP_TIME dev:8 wake:000496101.969259655
- 496101.947933819 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.969503271 WAKE num_fds:0
- 496101.969533801 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496101.969540176 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.969540650 DEV_SLEEP_TIME dev:8 wake:000496101.990867828
- 496101.969541940 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496101.991112235 WAKE num_fds:0
- 496101.991142850 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496101.991149285 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496101.991149702 DEV_SLEEP_TIME dev:8 wake:000496102.012476969
- 496101.991151093 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.012720280 WAKE num_fds:0
- 496102.012751156 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.012757551 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.012758032 DEV_SLEEP_TIME dev:8 wake:000496102.034085183
- 496102.012759347 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.034179223 WAKE num_fds:0
- 496102.034209573 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.034215959 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.034216445 DEV_SLEEP_TIME dev:8 wake:000496102.055543612
- 496102.034217748 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.055786354 WAKE num_fds:0
- 496102.055817274 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.055823596 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.055824098 DEV_SLEEP_TIME dev:8 wake:000496102.077151308
- 496102.055825385 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.077396578 WAKE num_fds:0
- 496102.077427578 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.077433828 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.077434386 DEV_SLEEP_TIME dev:8 wake:000496102.098761576
- 496102.077435665 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.099004172 WAKE num_fds:0
- 496102.099035175 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.099041530 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.099042024 DEV_SLEEP_TIME dev:8 wake:000496102.120369198
- 496102.099043326 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.120613023 WAKE num_fds:0
- 496102.120644090 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.120650614 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.120651091 DEV_SLEEP_TIME dev:8 wake:000496102.141978225
- 496102.120652494 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.142225706 WAKE num_fds:0
- 496102.142256890 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.142263153 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.142263645 DEV_SLEEP_TIME dev:8 wake:000496102.163590920
- 496102.142265037 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.163836347 WAKE num_fds:0
- 496102.163867587 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.163873914 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.163874460 DEV_SLEEP_TIME dev:8 wake:000496102.185201638
- 496102.163875798 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.185447500 WAKE num_fds:0
- 496102.185478163 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.185484509 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.185484991 DEV_SLEEP_TIME dev:8 wake:000496102.206812162
- 496102.185486293 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.207058359 WAKE num_fds:0
- 496102.207089563 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.207095821 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.207096391 DEV_SLEEP_TIME dev:8 wake:000496102.228423577
- 496102.207097693 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.228668781 WAKE num_fds:0
- 496102.228701857 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.228707109 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.228707636 DEV_SLEEP_TIME dev:8 wake:000496102.250035927
- 496102.228709310 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.250285696 WAKE num_fds:0
- 496102.250317905 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.250324535 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.250325072 DEV_SLEEP_TIME dev:8 wake:000496102.271651990
- 496102.250326550 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.271905241 WAKE num_fds:0
- 496102.271938628 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.271945223 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.271945764 DEV_SLEEP_TIME dev:8 wake:000496102.293272728
- 496102.271947358 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.293521749 WAKE num_fds:0
- 496102.293554584 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.293561180 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.293561721 DEV_SLEEP_TIME dev:8 wake:000496102.314888689
- 496102.293563174 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.315141390 WAKE num_fds:0
- 496102.315173950 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.315180640 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.315181177 DEV_SLEEP_TIME dev:8 wake:000496102.336508085
- 496102.315182615 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.336608964 WAKE num_fds:0
- 496102.336641554 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.336648134 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.336648786 DEV_SLEEP_TIME dev:8 wake:000496102.357975634
- 496102.336650354 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.358060502 WAKE num_fds:0
- 496102.358092746 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.358099572 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.358100118 DEV_SLEEP_TIME dev:8 wake:000496102.379426886
- 496102.358101582 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.379679310 WAKE num_fds:0
- 496102.379711860 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.379717002 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.379717538 DEV_SLEEP_TIME dev:8 wake:000496102.401045965
- 496102.379718967 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.401289935 WAKE num_fds:0
- 496102.401322290 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.401328976 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.401329512 DEV_SLEEP_TIME dev:8 wake:000496102.422656405
- 496102.401330940 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.422906689 WAKE num_fds:0
- 496102.422940056 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.422946696 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.422947232 DEV_SLEEP_TIME dev:8 wake:000496102.444274171
- 496102.422948681 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.444528128 WAKE num_fds:0
- 496102.444561089 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.444567699 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.444568241 DEV_SLEEP_TIME dev:8 wake:000496102.465895209
- 496102.444569724 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.466143570 WAKE num_fds:0
- 496102.466176561 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.466183417 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.466183943 DEV_SLEEP_TIME dev:8 wake:000496102.487510801
- 496102.466185391 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.487759281 WAKE num_fds:0
- 496102.487792688 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.487799288 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.487799839 DEV_SLEEP_TIME dev:8 wake:000496102.509126787
- 496102.487801283 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.509382158 WAKE num_fds:0
- 496102.509414728 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.509421519 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.509422050 DEV_SLEEP_TIME dev:8 wake:000496102.530748953
- 496102.509423484 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.530997274 WAKE num_fds:0
- 496102.531029418 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.531036073 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.531036610 DEV_SLEEP_TIME dev:8 wake:000496102.552363538
- 496102.531038068 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.552613621 WAKE num_fds:0
- 496102.552646277 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.552652837 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.552653398 DEV_SLEEP_TIME dev:8 wake:000496102.573980382
- 496102.552654847 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.574235683 WAKE num_fds:0
- 496102.574268759 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.574275550 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.574276086 DEV_SLEEP_TIME dev:8 wake:000496102.595602849
- 496102.574277530 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.595703738 WAKE num_fds:0
- 496102.595737742 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.595744357 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.595744903 DEV_SLEEP_TIME dev:8 wake:000496102.617071842
- 496102.595746362 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.617323143 WAKE num_fds:0
- 496102.617380144 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.617386815 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.617387476 DEV_SLEEP_TIME dev:8 wake:000496102.638714259
- 496102.617388925 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.638973490 WAKE num_fds:0
- 496102.639006691 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.639013432 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.639013983 DEV_SLEEP_TIME dev:8 wake:000496102.660340786
- 496102.639015447 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.660417244 WAKE num_fds:0
- 496102.660456845 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.660465896 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.660466528 DEV_SLEEP_TIME dev:8 wake:000496102.681791421
- 496102.660468447 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.682044914 WAKE num_fds:0
- 496102.682077384 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.682084109 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.682084761 DEV_SLEEP_TIME dev:8 wake:000496102.703411513
- 496102.682086214 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.703658395 WAKE num_fds:0
- 496102.703692107 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.703698723 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.703699274 DEV_SLEEP_TIME dev:8 wake:000496102.725026202
- 496102.703700717 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.725275906 WAKE num_fds:0
- 496102.725309578 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.725316209 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.725316870 DEV_SLEEP_TIME dev:8 wake:000496102.746643673
- 496102.725318439 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.746892644 WAKE num_fds:0
- 496102.746925380 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.746932065 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.746932596 DEV_SLEEP_TIME dev:8 wake:000496102.768259499
- 496102.746934020 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.768510786 WAKE num_fds:0
- 496102.768543812 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.768550613 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.768551154 DEV_SLEEP_TIME dev:8 wake:000496102.789877957
- 496102.768552672 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.790129755 WAKE num_fds:0
- 496102.790162812 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.790169432 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.790169988 DEV_SLEEP_TIME dev:8 wake:000496102.811496916
- 496102.790171416 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.811745406 WAKE num_fds:0
- 496102.811779034 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.811785589 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.811786140 DEV_SLEEP_TIME dev:8 wake:000496102.833113134
- 496102.811787564 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.833368700 WAKE num_fds:0
- 496102.833408141 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.833416480 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.833417112 DEV_SLEEP_TIME dev:8 wake:000496102.854742566
- 496102.833418956 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.854847040 WAKE num_fds:0
- 496102.854879640 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.854886280 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.854886832 DEV_SLEEP_TIME dev:8 wake:000496102.876213770
- 496102.854888265 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.876314619 WAKE num_fds:0
- 496102.876375595 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.876382566 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.876383112 DEV_SLEEP_TIME dev:8 wake:000496102.897709815
- 496102.876384550 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.897811827 WAKE num_fds:0
- 496102.897845044 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.897851795 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.897852431 DEV_SLEEP_TIME dev:8 wake:000496102.919179159
- 496102.897853869 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.919280565 WAKE num_fds:0
- 496102.919313952 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.919320728 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.919321274 DEV_SLEEP_TIME dev:8 wake:000496102.940648037
- 496102.919322707 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.940901293 WAKE num_fds:0
- 496102.940934504 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.940941105 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.940941661 DEV_SLEEP_TIME dev:8 wake:000496102.962268614
- 496102.940943109 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.962374715 WAKE num_fds:0
- 496102.962408604 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496102.962415304 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.962415840 DEV_SLEEP_TIME dev:8 wake:000496102.983742834
- 496102.962417289 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496102.983989801 WAKE num_fds:0
- 496102.984022416 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496102.984029127 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496102.984029598 DEV_SLEEP_TIME dev:8 wake:000496103.005356531
- 496102.984031001 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.005604715 WAKE num_fds:0
- 496103.005637877 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.005644412 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.005644948 DEV_SLEEP_TIME dev:8 wake:000496103.026971961
- 496103.005646371 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.027219901 WAKE num_fds:0
- 496103.027252371 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.027259051 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.027259603 DEV_SLEEP_TIME dev:8 wake:000496103.048586471
- 496103.027261016 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.048836534 WAKE num_fds:0
- 496103.048869601 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.048876291 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.048876837 DEV_SLEEP_TIME dev:8 wake:000496103.070203690
- 496103.048878406 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.070456866 WAKE num_fds:0
- 496103.070490058 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.070496793 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.070497324 DEV_SLEEP_TIME dev:8 wake:000496103.091824152
- 496103.070498778 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.092072047 WAKE num_fds:0
- 496103.092104782 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.092111468 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.092112014 DEV_SLEEP_TIME dev:8 wake:000496103.113438897
- 496103.092113457 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.113689061 WAKE num_fds:0
- 496103.113722453 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.113729133 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.113729675 DEV_SLEEP_TIME dev:8 wake:000496103.135056578
- 496103.113731128 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.135140323 WAKE num_fds:0
- 496103.135172087 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.135178677 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.135179223 DEV_SLEEP_TIME dev:8 wake:000496103.156506176
- 496103.135180651 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.156755693 WAKE num_fds:0
- 496103.156789141 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.156795941 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.156796473 DEV_SLEEP_TIME dev:8 wake:000496103.178123281
- 496103.156797911 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.178369600 WAKE num_fds:0
- 496103.178402637 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.178409347 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.178409878 DEV_SLEEP_TIME dev:8 wake:000496103.199736726
- 496103.178411312 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.199985012 WAKE num_fds:0
- 496103.200018454 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.200025154 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.200025706 DEV_SLEEP_TIME dev:8 wake:000496103.221352569
- 496103.200027164 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.221411887 WAKE num_fds:0
- 496103.221449599 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.221457367 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.221458149 DEV_SLEEP_TIME dev:8 wake:000496103.242784100
- 496103.221460163 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.243030786 WAKE num_fds:0
- 496103.243063321 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.243069992 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.243070543 DEV_SLEEP_TIME dev:8 wake:000496103.264397441
- 496103.243071991 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.264449458 WAKE num_fds:0
- 496103.264482559 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.264489289 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.264489826 DEV_SLEEP_TIME dev:8 wake:000496103.285816679
- 496103.264491259 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.285917784 WAKE num_fds:0
- 496103.285950585 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.285957336 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.285957867 DEV_SLEEP_TIME dev:8 wake:000496103.307284700
- 496103.285959300 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.307384411 WAKE num_fds:0
- 496103.307417092 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.307423752 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.307424298 DEV_SLEEP_TIME dev:8 wake:000496103.328751181
- 496103.307425727 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.328852327 WAKE num_fds:0
- 496103.328885203 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.328891733 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.328892279 DEV_SLEEP_TIME dev:8 wake:000496103.350219293
- 496103.328893698 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.350469121 WAKE num_fds:0
- 496103.350501911 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.350508482 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.350509028 DEV_SLEEP_TIME dev:8 wake:000496103.371836026
- 496103.350510602 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.372086512 WAKE num_fds:0
- 496103.372119994 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.372126719 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.372127266 DEV_SLEEP_TIME dev:8 wake:000496103.393454084
- 496103.372128694 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.393705741 WAKE num_fds:0
- 496103.393738817 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.393745367 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.393745909 DEV_SLEEP_TIME dev:8 wake:000496103.415072907
- 496103.393747357 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.415333750 WAKE num_fds:0
- 496103.415396976 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.415404193 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.415404729 DEV_SLEEP_TIME dev:8 wake:000496103.436731547
- 496103.415406162 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.436814764 WAKE num_fds:0
- 496103.436838871 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.436844444 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.436844804 DEV_SLEEP_TIME dev:8 wake:000496103.458172708
- 496103.436845753 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.458400798 WAKE num_fds:0
- 496103.458425703 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.458431340 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.458431693 DEV_SLEEP_TIME dev:8 wake:000496103.479759544
- 496103.458432626 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.479984935 WAKE num_fds:0
- 496103.480009455 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.480014980 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.480015343 DEV_SLEEP_TIME dev:8 wake:000496103.501343283
- 496103.480016274 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.501571552 WAKE num_fds:0
- 496103.501596146 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.501601748 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.501602114 DEV_SLEEP_TIME dev:8 wake:000496103.522930023
- 496103.501603047 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.523156936 WAKE num_fds:0
- 496103.523181532 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.523187086 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.523187437 DEV_SLEEP_TIME dev:8 wake:000496103.544515344
- 496103.523188369 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.544740125 WAKE num_fds:0
- 496103.544764472 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.544770082 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.544770446 DEV_SLEEP_TIME dev:8 wake:000496103.566098335
- 496103.544771384 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.566324453 WAKE num_fds:0
- 496103.566371205 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.566377992 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.566378422 DEV_SLEEP_TIME dev:8 wake:000496103.587705271
- 496103.566379814 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.587786308 WAKE num_fds:0
- 496103.587811809 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.587817500 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.587817863 DEV_SLEEP_TIME dev:8 wake:000496103.609145680
- 496103.587818973 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.609376370 WAKE num_fds:0
- 496103.609400933 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.609406578 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.609406944 DEV_SLEEP_TIME dev:8 wake:000496103.630734830
- 496103.609407885 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.630960573 WAKE num_fds:0
- 496103.630985847 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.630991468 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.630991821 DEV_SLEEP_TIME dev:8 wake:000496103.652319678
- 496103.630992762 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.652564901 WAKE num_fds:0
- 496103.652597787 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.652604413 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.652604944 DEV_SLEEP_TIME dev:8 wake:000496103.673931877
- 496103.652606367 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.674031369 WAKE num_fds:0
- 496103.674064982 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.674071517 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.674072063 DEV_SLEEP_TIME dev:8 wake:000496103.695399066
- 496103.674073511 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.695648238 WAKE num_fds:0
- 496103.695681735 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.695688531 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.695689082 DEV_SLEEP_TIME dev:8 wake:000496103.717015820
- 496103.695690631 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.717266806 WAKE num_fds:0
- 496103.717300549 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.717307220 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.717307761 DEV_SLEEP_TIME dev:8 wake:000496103.738634664
- 496103.717309194 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.738734857 WAKE num_fds:0
- 496103.738766890 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.738773646 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.738774192 DEV_SLEEP_TIME dev:8 wake:000496103.760101015
- 496103.738775641 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.760377525 WAKE num_fds:0
- 496103.760411473 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.760418114 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.760418660 DEV_SLEEP_TIME dev:8 wake:000496103.781745613
- 496103.760420098 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.781991819 WAKE num_fds:0
- 496103.782024419 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.782031049 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.782031595 DEV_SLEEP_TIME dev:8 wake:000496103.803358509
- 496103.782033034 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.803607936 WAKE num_fds:0
- 496103.803640907 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.803647532 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.803648068 DEV_SLEEP_TIME dev:8 wake:000496103.824975016
- 496103.803649532 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.825225166 WAKE num_fds:0
- 496103.825257711 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.825264397 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.825264928 DEV_SLEEP_TIME dev:8 wake:000496103.846591806
- 496103.825266386 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.846843268 WAKE num_fds:0
- 496103.846875868 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.846882468 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.846883004 DEV_SLEEP_TIME dev:8 wake:000496103.868210043
- 496103.846884453 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.868311589 WAKE num_fds:0
- 496103.868369121 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.868377471 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.868378172 DEV_SLEEP_TIME dev:8 wake:000496103.889703602
- 496103.868379906 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.889953992 WAKE num_fds:0
- 496103.889987179 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.889993729 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.889994275 DEV_SLEEP_TIME dev:8 wake:000496103.911321284
- 496103.889995693 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.911575091 WAKE num_fds:0
- 496103.911608678 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.911615268 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.911615805 DEV_SLEEP_TIME dev:8 wake:000496103.932942778
- 496103.911617248 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.933189961 WAKE num_fds:0
- 496103.933222922 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.933229587 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.933230138 DEV_SLEEP_TIME dev:8 wake:000496103.954557037
- 496103.933231577 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.954805246 WAKE num_fds:0
- 496103.954837916 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.954844572 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.954845108 DEV_SLEEP_TIME dev:8 wake:000496103.976172026
- 496103.954846546 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.976423272 WAKE num_fds:0
- 496103.976456529 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496103.976463194 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.976463851 DEV_SLEEP_TIME dev:8 wake:000496103.997790639
- 496103.976465369 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496103.998041575 WAKE num_fds:0
- 496103.998074456 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496103.998081157 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496103.998081628 DEV_SLEEP_TIME dev:8 wake:000496104.019408596
- 496103.998083011 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.019658098 WAKE num_fds:0
- 496104.019691300 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.019697830 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.019698386 DEV_SLEEP_TIME dev:8 wake:000496104.041025390
- 496104.019699855 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.041127397 WAKE num_fds:0
- 496104.041159612 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.041166252 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.041166798 DEV_SLEEP_TIME dev:8 wake:000496104.062493731
- 496104.041168216 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.062742647 WAKE num_fds:0
- 496104.062776280 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.062782875 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.062783416 DEV_SLEEP_TIME dev:8 wake:000496104.084110370
- 496104.062784850 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.084368467 WAKE num_fds:0
- 496104.084401583 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.084408108 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.084408649 DEV_SLEEP_TIME dev:8 wake:000496104.105735673
- 496104.084410068 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.105982034 WAKE num_fds:0
- 496104.106015741 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.106022367 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.106022913 DEV_SLEEP_TIME dev:8 wake:000496104.127349861
- 496104.106024341 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.127600586 WAKE num_fds:0
- 496104.127633903 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.127640669 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.127641320 DEV_SLEEP_TIME dev:8 wake:000496104.148968038
- 496104.127642744 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.149220703 WAKE num_fds:0
- 496104.149253800 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.149260330 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.149260871 DEV_SLEEP_TIME dev:8 wake:000496104.170587935
- 496104.149262269 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.170721179 WAKE num_fds:0
- 496104.170754495 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.170761211 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.170761747 DEV_SLEEP_TIME dev:8 wake:000496104.192088610
- 496104.170763170 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.192334148 WAKE num_fds:0
- 496104.192385321 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.192391932 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.192392483 DEV_SLEEP_TIME dev:8 wake:000496104.213719466
- 496104.192393901 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.213969626 WAKE num_fds:0
- 496104.214003173 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.214009784 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.214010325 DEV_SLEEP_TIME dev:8 wake:000496104.235337263
- 496104.214011758 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.235589010 WAKE num_fds:0
- 496104.235622558 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.235629233 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.235629765 DEV_SLEEP_TIME dev:8 wake:000496104.256956668
- 496104.235631193 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.257204853 WAKE num_fds:0
- 496104.257238110 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.257244850 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.257245391 DEV_SLEEP_TIME dev:8 wake:000496104.278572214
- 496104.257246820 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.278826247 WAKE num_fds:0
- 496104.278861418 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.278868550 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.278869111 DEV_SLEEP_TIME dev:8 wake:000496104.300195693
- 496104.278870524 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.300444238 WAKE num_fds:0
- 496104.300477420 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.300484135 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.300484672 DEV_SLEEP_TIME dev:8 wake:000496104.321811585
- 496104.300486110 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.322062401 WAKE num_fds:0
- 496104.322095693 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.322102308 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.322102975 DEV_SLEEP_TIME dev:8 wake:000496104.343429772
- 496104.322104433 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.343531524 WAKE num_fds:0
- 496104.343564685 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.343571270 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.343571817 DEV_SLEEP_TIME dev:8 wake:000496104.364898785
- 496104.343573265 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.365146048 WAKE num_fds:0
- 496104.365179570 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.365186266 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.365186807 DEV_SLEEP_TIME dev:8 wake:000496104.386513665
- 496104.365188245 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.386763683 WAKE num_fds:0
- 496104.386797366 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.386803886 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.386804427 DEV_SLEEP_TIME dev:8 wake:000496104.408131476
- 496104.386805876 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.408381509 WAKE num_fds:0
- 496104.408415418 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.408422178 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.408422729 DEV_SLEEP_TIME dev:8 wake:000496104.429749482
- 496104.408424293 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.430002674 WAKE num_fds:0
- 496104.430036221 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.430042706 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.430043283 DEV_SLEEP_TIME dev:8 wake:000496104.451370316
- 496104.430044801 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.451618891 WAKE num_fds:0
- 496104.451651647 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.451658357 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.451658904 DEV_SLEEP_TIME dev:8 wake:000496104.472985797
- 496104.451660332 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.473234513 WAKE num_fds:0
- 496104.473268396 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.473274946 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.473275518 DEV_SLEEP_TIME dev:8 wake:000496104.494602496
- 496104.473276971 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.494850299 WAKE num_fds:0
- 496104.494883872 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.494890522 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.494891058 DEV_SLEEP_TIME dev:8 wake:000496104.516217982
- 496104.494892497 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.516465429 WAKE num_fds:0
- 496104.516497849 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.516504484 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.516505025 DEV_SLEEP_TIME dev:8 wake:000496104.537831949
- 496104.516506474 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.538084509 WAKE num_fds:0
- 496104.538116688 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.538123419 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.538123950 DEV_SLEEP_TIME dev:8 wake:000496104.559450813
- 496104.538125398 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.559701493 WAKE num_fds:0
- 496104.559734554 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.559741089 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.559741635 DEV_SLEEP_TIME dev:8 wake:000496104.581068669
- 496104.559743104 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.581317008 WAKE num_fds:0
- 496104.581373920 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.581381016 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.581381557 DEV_SLEEP_TIME dev:8 wake:000496104.602708135
- 496104.581383061 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.602955819 WAKE num_fds:0
- 496104.602989075 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.602995756 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.602996417 DEV_SLEEP_TIME dev:8 wake:000496104.624323190
- 496104.602997951 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.624574071 WAKE num_fds:0
- 496104.624606786 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.624613336 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.624613887 DEV_SLEEP_TIME dev:8 wake:000496104.645940886
- 496104.624615321 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.646039125 WAKE num_fds:0
- 496104.646072131 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.646078791 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.646079338 DEV_SLEEP_TIME dev:8 wake:000496104.667406256
- 496104.646080766 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.667623494 WAKE num_fds:0
- 496104.667664082 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.667672797 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.667673469 DEV_SLEEP_TIME dev:8 wake:000496104.688999335
- 496104.667675403 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.689252361 WAKE num_fds:0
- 496104.689285583 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.689292348 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.689292895 DEV_SLEEP_TIME dev:8 wake:000496104.710619672
- 496104.689294348 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.710870232 WAKE num_fds:0
- 496104.710903940 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.710910650 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.710911312 DEV_SLEEP_TIME dev:8 wake:000496104.732238050
- 496104.710912735 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.732487847 WAKE num_fds:0
- 496104.732520778 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.732527314 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.732527860 DEV_SLEEP_TIME dev:8 wake:000496104.753854878
- 496104.732529308 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.754105003 WAKE num_fds:0
- 496104.754137408 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.754144128 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.754144664 DEV_SLEEP_TIME dev:8 wake:000496104.775471517
- 496104.754146103 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.775719892 WAKE num_fds:0
- 496104.775752763 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.775759303 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.775759849 DEV_SLEEP_TIME dev:8 wake:000496104.797086893
- 496104.775761277 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.797331022 WAKE num_fds:0
- 496104.797383769 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.797390394 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.797390941 DEV_SLEEP_TIME dev:8 wake:000496104.818717909
- 496104.797392374 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.818964300 WAKE num_fds:0
- 496104.818996575 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.819003275 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.819003816 DEV_SLEEP_TIME dev:8 wake:000496104.840330689
- 496104.819005234 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.840580843 WAKE num_fds:0
- 496104.840613864 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.840620555 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.840621086 DEV_SLEEP_TIME dev:8 wake:000496104.861947939
- 496104.840622509 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.862198068 WAKE num_fds:0
- 496104.862231100 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.862237675 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.862238216 DEV_SLEEP_TIME dev:8 wake:000496104.883565189
- 496104.862239805 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.883815458 WAKE num_fds:0
- 496104.883848640 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.883855210 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.883855756 DEV_SLEEP_TIME dev:8 wake:000496104.905182735
- 496104.883857185 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.905430593 WAKE num_fds:0
- 496104.905463559 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.905470210 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.905470756 DEV_SLEEP_TIME dev:8 wake:000496104.926797684
- 496104.905472199 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.927045448 WAKE num_fds:0
- 496104.927078660 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.927085360 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.927085897 DEV_SLEEP_TIME dev:8 wake:000496104.948412810
- 496104.927087325 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.948489252 WAKE num_fds:0
- 496104.948522459 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.948529140 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.948529691 DEV_SLEEP_TIME dev:8 wake:000496104.969856534
- 496104.948531134 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.969958296 WAKE num_fds:0
- 496104.969991277 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496104.969997942 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.969998494 DEV_SLEEP_TIME dev:8 wake:000496104.991325397
- 496104.969999942 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496104.991576864 WAKE num_fds:0
- 496104.991610752 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496104.991617362 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496104.991617838 DEV_SLEEP_TIME dev:8 wake:000496105.012944852
- 496104.991619206 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.013197317 WAKE num_fds:0
- 496105.013229992 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.013236557 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.013237093 DEV_SLEEP_TIME dev:8 wake:000496105.034564082
- 496105.013238527 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.034815719 WAKE num_fds:0
- 496105.034849256 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.034855866 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.034856413 DEV_SLEEP_TIME dev:8 wake:000496105.056183386
- 496105.034857836 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.056432743 WAKE num_fds:0
- 496105.056465699 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.056472284 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.056472830 DEV_SLEEP_TIME dev:8 wake:000496105.077799809
- 496105.056474259 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.078050495 WAKE num_fds:0
- 496105.078083877 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.078090507 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.078091058 DEV_SLEEP_TIME dev:8 wake:000496105.099417966
- 496105.078092492 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.099669604 WAKE num_fds:0
- 496105.099702540 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.099707727 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.099708263 DEV_SLEEP_TIME dev:8 wake:000496105.121036634
- 496105.099709746 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.121285461 WAKE num_fds:0
- 496105.121317951 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.121324611 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.121325268 DEV_SLEEP_TIME dev:8 wake:000496105.142652076
- 496105.121326736 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.142903778 WAKE num_fds:0
- 496105.142936749 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.142943460 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.142943991 DEV_SLEEP_TIME dev:8 wake:000496105.164270849
- 496105.142945419 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.164519885 WAKE num_fds:0
- 496105.164552300 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.164558900 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.164559441 DEV_SLEEP_TIME dev:8 wake:000496105.185886405
- 496105.164560985 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.186137030 WAKE num_fds:0
- 496105.186170513 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.186177243 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.186177769 DEV_SLEEP_TIME dev:8 wake:000496105.207504597
- 496105.186179198 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.207754355 WAKE num_fds:0
- 496105.207786910 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.207793495 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.207794042 DEV_SLEEP_TIME dev:8 wake:000496105.229121015
- 496105.207795495 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.229371835 WAKE num_fds:0
- 496105.229404380 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.229411061 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.229411587 DEV_SLEEP_TIME dev:8 wake:000496105.250738520
- 496105.229413065 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.250989191 WAKE num_fds:0
- 496105.251022533 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.251029098 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.251029649 DEV_SLEEP_TIME dev:8 wake:000496105.272356643
- 496105.251031078 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.272465525 WAKE num_fds:0
- 496105.272498271 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.272505137 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.272505678 DEV_SLEEP_TIME dev:8 wake:000496105.293832411
- 496105.272507131 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.294080130 WAKE num_fds:0
- 496105.294113276 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.294119922 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.294120458 DEV_SLEEP_TIME dev:8 wake:000496105.315447346
- 496105.294121896 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.315695525 WAKE num_fds:0
- 496105.315727564 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.315734204 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.315734751 DEV_SLEEP_TIME dev:8 wake:000496105.337061674
- 496105.315736194 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.337311722 WAKE num_fds:0
- 496105.337363963 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.337370999 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.337371535 DEV_SLEEP_TIME dev:8 wake:000496105.358698148
- 496105.337373004 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.358950763 WAKE num_fds:0
- 496105.358983855 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.358990410 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.358990956 DEV_SLEEP_TIME dev:8 wake:000496105.380317989
- 496105.358992429 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.380568549 WAKE num_fds:0
- 496105.380601365 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.380607900 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.380608451 DEV_SLEEP_TIME dev:8 wake:000496105.401935460
- 496105.380609894 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.402180688 WAKE num_fds:0
- 496105.402212987 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.402219633 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.402220169 DEV_SLEEP_TIME dev:8 wake:000496105.423547082
- 496105.402221627 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.423793407 WAKE num_fds:0
- 496105.423826664 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.423833274 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.423833815 DEV_SLEEP_TIME dev:8 wake:000496105.445160758
- 496105.423835239 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.445409013 WAKE num_fds:0
- 496105.445441924 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.445448494 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.445449045 DEV_SLEEP_TIME dev:8 wake:000496105.466776074
- 496105.445450639 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.467024434 WAKE num_fds:0
- 496105.467057591 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.467064336 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.467064882 DEV_SLEEP_TIME dev:8 wake:000496105.488391700
- 496105.467066331 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.488641904 WAKE num_fds:0
- 496105.488674479 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.488681345 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.488681882 DEV_SLEEP_TIME dev:8 wake:000496105.510008579
- 496105.488683310 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.510259461 WAKE num_fds:0
- 496105.510292828 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.510299403 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.510299944 DEV_SLEEP_TIME dev:8 wake:000496105.531626892
- 496105.510301372 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.531877692 WAKE num_fds:0
- 496105.531910704 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.531917324 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.531917855 DEV_SLEEP_TIME dev:8 wake:000496105.553244793
- 496105.531919283 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.553365934 WAKE num_fds:0
- 496105.553398950 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.553405576 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.553406122 DEV_SLEEP_TIME dev:8 wake:000496105.574733040
- 496105.553407535 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.574834893 WAKE num_fds:0
- 496105.574867167 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.574873822 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.574874354 DEV_SLEEP_TIME dev:8 wake:000496105.596201262
- 496105.574875787 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.596446710 WAKE num_fds:0
- 496105.596479731 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.596486276 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.596486812 DEV_SLEEP_TIME dev:8 wake:000496105.617813856
- 496105.596488281 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.618065669 WAKE num_fds:0
- 496105.618099372 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.618106092 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.618106619 DEV_SLEEP_TIME dev:8 wake:000496105.639433497
- 496105.618108077 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.639683655 WAKE num_fds:0
- 496105.639714487 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.639721508 SET_DEV_WAKE dev:8 hw_level:2000 sleep:976
- 496105.639722054 DEV_SLEEP_TIME dev:8 wake:000496105.660048626
- 496105.639723477 SLEEP sleep:000000000.020333333 longest_wake:000158140
- 496105.660301504 WAKE num_fds:0
- 496105.660334535 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.660367015 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.660367572 DEV_SLEEP_TIME dev:8 wake:000496105.681668625
- 496105.660369040 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.681942991 WAKE num_fds:0
- 496105.681976147 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.681982883 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.681983419 DEV_SLEEP_TIME dev:8 wake:000496105.703310237
- 496105.681984857 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.703558436 WAKE num_fds:0
- 496105.703591708 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.703598413 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.703598950 DEV_SLEEP_TIME dev:8 wake:000496105.724925813
- 496105.703600388 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.725176313 WAKE num_fds:0
- 496105.725208658 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.725215549 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.725216080 DEV_SLEEP_TIME dev:8 wake:000496105.746542803
- 496105.725217568 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.746792781 WAKE num_fds:0
- 496105.746825331 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.746831876 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.746832453 DEV_SLEEP_TIME dev:8 wake:000496105.768159431
- 496105.746833886 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.768409820 WAKE num_fds:0
- 496105.768442711 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.768449406 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.768449953 DEV_SLEEP_TIME dev:8 wake:000496105.789776891
- 496105.768451421 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.790025698 WAKE num_fds:0
- 496105.790058914 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.790065650 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.790066186 DEV_SLEEP_TIME dev:8 wake:000496105.811393034
- 496105.790067619 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.811643934 WAKE num_fds:0
- 496105.811676870 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.811683431 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.811683977 DEV_SLEEP_TIME dev:8 wake:000496105.833010970
- 496105.811685410 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.833259676 WAKE num_fds:0
- 496105.833293284 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.833299784 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.833300325 DEV_SLEEP_TIME dev:8 wake:000496105.854627374
- 496105.833301869 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.854876535 WAKE num_fds:0
- 496105.854909596 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.854916192 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.854916733 DEV_SLEEP_TIME dev:8 wake:000496105.876243686
- 496105.854918171 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.876365955 WAKE num_fds:0
- 496105.876403862 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.876410763 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.876411304 DEV_SLEEP_TIME dev:8 wake:000496105.897738112
- 496105.876412748 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.897985014 WAKE num_fds:0
- 496105.898017996 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.898024566 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.898025112 DEV_SLEEP_TIME dev:8 wake:000496105.919352085
- 496105.898026530 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.919602019 WAKE num_fds:0
- 496105.919635095 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.919641750 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.919642291 DEV_SLEEP_TIME dev:8 wake:000496105.940969270
- 496105.919643785 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.941221058 WAKE num_fds:0
- 496105.941253709 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.941260544 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.941261091 DEV_SLEEP_TIME dev:8 wake:000496105.962587808
- 496105.941262514 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.962838809 WAKE num_fds:0
- 496105.962871800 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496105.962878330 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.962878866 DEV_SLEEP_TIME dev:8 wake:000496105.984205910
- 496105.962880375 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496105.984453327 WAKE num_fds:0
- 496105.984486108 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496105.984492768 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496105.984493239 DEV_SLEEP_TIME dev:8 wake:000496106.005820173
- 496105.984494638 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.006072327 WAKE num_fds:0
- 496106.006105654 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.006112179 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.006112715 DEV_SLEEP_TIME dev:8 wake:000496106.027439754
- 496106.006114163 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.027691130 WAKE num_fds:0
- 496106.027723174 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.027729900 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.027730446 DEV_SLEEP_TIME dev:8 wake:000496106.049057314
- 496106.027731899 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.049118332 WAKE num_fds:0
- 496106.049149760 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.049156335 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.049156886 DEV_SLEEP_TIME dev:8 wake:000496106.070483854
- 496106.049158304 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.070587359 WAKE num_fds:0
- 496106.070620506 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.070627071 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.070627617 DEV_SLEEP_TIME dev:8 wake:000496106.091954571
- 496106.070629041 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.092200591 WAKE num_fds:0
- 496106.092233722 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.092240292 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.092240839 DEV_SLEEP_TIME dev:8 wake:000496106.113567797
- 496106.092242292 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.113817610 WAKE num_fds:0
- 496106.113850350 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.113857006 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.113857657 DEV_SLEEP_TIME dev:8 wake:000496106.135184485
- 496106.113859181 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.135434824 WAKE num_fds:0
- 496106.135468362 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.135474907 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.135475448 DEV_SLEEP_TIME dev:8 wake:000496106.156802487
- 496106.135476881 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.157054420 WAKE num_fds:0
- 496106.157087412 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.157094092 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.157094628 DEV_SLEEP_TIME dev:8 wake:000496106.178421511
- 496106.157096102 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.178468120 WAKE num_fds:0
- 496106.178501477 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.178508318 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.178508849 DEV_SLEEP_TIME dev:8 wake:000496106.199835752
- 496106.178510348 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.200086092 WAKE num_fds:0
- 496106.200118818 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.200125523 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.200126065 DEV_SLEEP_TIME dev:8 wake:000496106.221452913
- 496106.200127518 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.221581095 WAKE num_fds:0
- 496106.221614773 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.221621473 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.221621999 DEV_SLEEP_TIME dev:8 wake:000496106.242948877
- 496106.221623513 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.243200696 WAKE num_fds:0
- 496106.243234359 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.243241069 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.243241610 DEV_SLEEP_TIME dev:8 wake:000496106.264568453
- 496106.243243039 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.264635264 WAKE num_fds:0
- 496106.264667323 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.264673953 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.264674489 DEV_SLEEP_TIME dev:8 wake:000496106.286001423
- 496106.264675948 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.286249247 WAKE num_fds:0
- 496106.286282017 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.286288618 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.286289159 DEV_SLEEP_TIME dev:8 wake:000496106.307616107
- 496106.286290592 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.307868020 WAKE num_fds:0
- 496106.307901131 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.307907807 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.307908353 DEV_SLEEP_TIME dev:8 wake:000496106.329235196
- 496106.307909776 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.329485164 WAKE num_fds:0
- 496106.329518181 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.329525026 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.329525563 DEV_SLEEP_TIME dev:8 wake:000496106.350852295
- 496106.329527071 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.350909770 WAKE num_fds:0
- 496106.350941839 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.350948820 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.350949357 DEV_SLEEP_TIME dev:8 wake:000496106.372276054
- 496106.350950795 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.372524735 WAKE num_fds:0
- 496106.372558297 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.372564937 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.372565469 DEV_SLEEP_TIME dev:8 wake:000496106.393892407
- 496106.372566922 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.394139539 WAKE num_fds:0
- 496106.394172305 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.394178965 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.394179517 DEV_SLEEP_TIME dev:8 wake:000496106.415506450
- 496106.394180940 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.415761560 WAKE num_fds:0
- 496106.415794401 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.415801106 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.415801663 DEV_SLEEP_TIME dev:8 wake:000496106.437128511
- 496106.415803201 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.437377767 WAKE num_fds:0
- 496106.437410964 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.437417664 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.437418206 DEV_SLEEP_TIME dev:8 wake:000496106.458745059
- 496106.437419634 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.458813434 WAKE num_fds:0
- 496106.458845648 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.458852308 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.458852850 DEV_SLEEP_TIME dev:8 wake:000496106.480179718
- 496106.458854293 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.480280397 WAKE num_fds:0
- 496106.480312832 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.480319598 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.480320129 DEV_SLEEP_TIME dev:8 wake:000496106.501646992
- 496106.480321598 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.501898760 WAKE num_fds:0
- 496106.501932046 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.501938717 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.501939258 DEV_SLEEP_TIME dev:8 wake:000496106.523266191
- 496106.501940681 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.523515268 WAKE num_fds:0
- 496106.523547652 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.523554283 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.523554824 DEV_SLEEP_TIME dev:8 wake:000496106.544881747
- 496106.523556262 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.545129010 WAKE num_fds:0
- 496106.545161906 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.545168631 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.545169168 DEV_SLEEP_TIME dev:8 wake:000496106.566495986
- 496106.545170621 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.566746781 WAKE num_fds:0
- 496106.566779802 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.566786387 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.566786938 DEV_SLEEP_TIME dev:8 wake:000496106.588113892
- 496106.566788472 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.588381170 WAKE num_fds:0
- 496106.588413956 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.588420536 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.588421082 DEV_SLEEP_TIME dev:8 wake:000496106.609748050
- 496106.588422505 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.609997674 WAKE num_fds:0
- 496106.610030184 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.610036814 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.610037365 DEV_SLEEP_TIME dev:8 wake:000496106.631364289
- 496106.610038794 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.631612047 WAKE num_fds:0
- 496106.631644993 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.631651568 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.631652109 DEV_SLEEP_TIME dev:8 wake:000496106.652979113
- 496106.631653543 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.653079141 WAKE num_fds:0
- 496106.653111641 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.653118306 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.653118862 DEV_SLEEP_TIME dev:8 wake:000496106.674445796
- 496106.653120301 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.674531169 WAKE num_fds:0
- 496106.674566811 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.674573477 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.674574018 DEV_SLEEP_TIME dev:8 wake:000496106.695900961
- 496106.674575446 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.696158187 WAKE num_fds:0
- 496106.696191840 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.696198555 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.696199092 DEV_SLEEP_TIME dev:8 wake:000496106.717525935
- 496106.696201021 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.717774134 WAKE num_fds:0
- 496106.717807591 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496106.717814186 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.717814727 DEV_SLEEP_TIME dev:8 wake:000496106.739141681
- 496106.717816196 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.739392065 WAKE num_fds:0
- 496106.739426254 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496106.739432934 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496106.739433591 DEV_SLEEP_TIME dev:8 wake:000496106.760760369
- 496106.739435179 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496106.760007023 WAKE num_fds:1
- 496106.760016440 PB_MSG msg_id:1
- 496106.760018008 DEV_REMOVED dev:8
- 496106.760032377 SLEEP sleep:000000000.000000000 longest_wake:000158140
- 496118.354002034 WAKE num_fds:1
- 496118.354013360 PB_MSG msg_id:0
- 496118.354015856 DEV_ADDED dev:8
- 496118.354055002 ODEV_NO_STREAMS dev:8 hw_level:0 write:2048
- 496118.354057131 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496118.354057663 DEV_SLEEP_TIME dev:8 wake:000496118.375389076
- 496118.354058795 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496118.354063185 WAKE num_fds:1
- 496118.354066032 PB_MSG msg_id:2
- 496118.354066598 WRITE_STREAMS_WAIT stream:140000
- 496118.354078641 STREAM_ADDED id:140000 dev:8
- 496118.354085291 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2048
- 496118.354096267 FILL_AUDIO dev:8 hw_level:2048
- 496118.354097760 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.354098121 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.354098893 WRITE_STREAMS_MIXED write_limit:0
- 496118.354111888 FILL_AUDIO_DONE hw_level:2048 total_written:0 min_cb_level:1024
- 496118.354120337 SET_DEV_WAKE dev:8 hw_level:2048 sleep:2048
- 496118.354120738 DEV_SLEEP_TIME dev:8 wake:000496118.396779331
- 496118.354121530 SLEEP sleep:000000000.042666666 longest_wake:000158140
- 496118.354648175 WAKE num_fds:1
- 496118.354678825 FILL_AUDIO dev:8 hw_level:2048
- 496118.354682173 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.354690728 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.354702069 DEV_STREAM_MIX written:1024 read:1024
- 496118.354703026 WRITE_STREAMS_MIXED write_limit:1024
- 496118.354705141 FILL_AUDIO_DONE hw_level:2048 total_written:1024 min_cb_level:1024
- 496118.354706975 STREAM_SLEEP_TIME id:140000 wake:000496118.375409268
- 496118.354714473 SET_DEV_WAKE dev:8 hw_level:3072 sleep:3072
- 496118.354714989 DEV_SLEEP_TIME dev:8 wake:000496118.418706179
- 496118.354716537 SLEEP sleep:000000000.020703089 longest_wake:000158140
- 496118.375445608 WAKE num_fds:0
- 496118.375470776 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.375493288 FILL_AUDIO dev:8 hw_level:2208
- 496118.375498029 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.375498460 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.375499492 WRITE_STREAMS_MIXED write_limit:0
- 496118.375502529 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.375511756 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.375512242 DEV_SLEEP_TIME dev:8 wake:000496118.421503923
- 496118.375514156 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.375625007 WAKE num_fds:1
- 496118.375650521 FILL_AUDIO dev:8 hw_level:2208
- 496118.375652766 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.375665305 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.375680355 DEV_STREAM_MIX written:1024 read:1024
- 496118.375681277 WRITE_STREAMS_MIXED write_limit:1024
- 496118.375683131 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.375684780 STREAM_SLEEP_TIME id:140000 wake:000496118.396742601
- 496118.375692087 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.375692633 DEV_SLEEP_TIME dev:8 wake:000496118.443017306
- 496118.375694217 SLEEP sleep:000000000.021058628 longest_wake:000158140
- 496118.396778232 WAKE num_fds:0
- 496118.396804492 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.396830803 FILL_AUDIO dev:8 hw_level:2176
- 496118.396835373 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.396835890 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.396837007 WRITE_STREAMS_MIXED write_limit:0
- 496118.396839979 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496118.396848248 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496118.396848825 DEV_SLEEP_TIME dev:8 wake:000496118.442174490
- 496118.396850488 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496118.396934603 WAKE num_fds:1
- 496118.396958914 FILL_AUDIO dev:8 hw_level:2176
- 496118.396961299 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.396978694 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.396986317 DEV_STREAM_MIX written:1024 read:1024
- 496118.396987114 WRITE_STREAMS_MIXED write_limit:1024
- 496118.396989123 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.396990582 STREAM_SLEEP_TIME id:140000 wake:000496118.418075934
- 496118.396997628 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.396998149 DEV_SLEEP_TIME dev:8 wake:000496118.463656556
- 496118.396999758 SLEEP sleep:000000000.021086044 longest_wake:000158140
- 496118.418106179 WAKE num_fds:0
- 496118.418127885 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.418148733 FILL_AUDIO dev:8 hw_level:2192
- 496118.418152962 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.418153584 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.418154666 WRITE_STREAMS_MIXED write_limit:0
- 496118.418157608 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.418166053 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.418166554 DEV_SLEEP_TIME dev:8 wake:000496118.463825722
- 496118.418168558 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.418266114 WAKE num_fds:1
- 496118.418294374 FILL_AUDIO dev:8 hw_level:2192
- 496118.418296063 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.418306216 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.418312010 DEV_STREAM_MIX written:1024 read:1024
- 496118.418312576 WRITE_STREAMS_MIXED write_limit:1024
- 496118.418313588 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.418314871 STREAM_SLEEP_TIME id:140000 wake:000496118.439409267
- 496118.418320720 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.418321136 DEV_SLEEP_TIME dev:8 wake:000496118.485314360
- 496118.418322293 SLEEP sleep:000000000.021094907 longest_wake:000158140
- 496118.439496761 WAKE num_fds:0
- 496118.439530519 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.439586553 FILL_AUDIO dev:8 hw_level:2208
- 496118.439591966 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.439592507 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.439593695 WRITE_STREAMS_MIXED write_limit:0
- 496118.439597258 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.439605853 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.439606354 DEV_SLEEP_TIME dev:8 wake:000496118.485598576
- 496118.439608218 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.439716288 WAKE num_fds:1
- 496118.439750747 FILL_AUDIO dev:8 hw_level:2208
- 496118.439752842 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.439767887 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.439772748 DEV_STREAM_MIX written:1024 read:1024
- 496118.439773409 WRITE_STREAMS_MIXED write_limit:1024
- 496118.439774372 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.439775434 STREAM_SLEEP_TIME id:140000 wake:000496118.460742600
- 496118.439781538 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.439781894 DEV_SLEEP_TIME dev:8 wake:000496118.507108286
- 496118.439782906 SLEEP sleep:000000000.020967647 longest_wake:000158140
- 496118.460789142 WAKE num_fds:0
- 496118.460810982 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.460836150 FILL_AUDIO dev:8 hw_level:2176
- 496118.460840610 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.460841127 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.460842124 WRITE_STREAMS_MIXED write_limit:0
- 496118.460844995 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496118.460853270 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496118.460853771 DEV_SLEEP_TIME dev:8 wake:000496118.506179516
- 496118.460855876 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496118.460930107 WAKE num_fds:1
- 496118.460954508 FILL_AUDIO dev:8 hw_level:2176
- 496118.460955716 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.460966080 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.460971678 DEV_STREAM_MIX written:1024 read:1024
- 496118.460972239 WRITE_STREAMS_MIXED write_limit:1024
- 496118.460973136 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.460974234 STREAM_SLEEP_TIME id:140000 wake:000496118.482075933
- 496118.460979857 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.460980238 DEV_SLEEP_TIME dev:8 wake:000496118.527640454
- 496118.460981235 SLEEP sleep:000000000.021102145 longest_wake:000158140
- 496118.482113920 WAKE num_fds:0
- 496118.482135974 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.482159569 FILL_AUDIO dev:8 hw_level:2192
- 496118.482163130 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.482163491 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.482164624 WRITE_STREAMS_MIXED write_limit:0
- 496118.482167216 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.482175522 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.482175939 DEV_SLEEP_TIME dev:8 wake:000496118.527835011
- 496118.482177634 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.482244261 WAKE num_fds:1
- 496118.482270354 FILL_AUDIO dev:8 hw_level:2192
- 496118.482271744 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.482283118 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.482287734 DEV_STREAM_MIX written:1024 read:1024
- 496118.482288242 WRITE_STREAMS_MIXED write_limit:1024
- 496118.482289425 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.482290547 STREAM_SLEEP_TIME id:140000 wake:000496118.503409266
- 496118.482297115 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.482297491 DEV_SLEEP_TIME dev:8 wake:000496118.549289966
- 496118.482298539 SLEEP sleep:000000000.021119300 longest_wake:000158140
- 496118.503438723 WAKE num_fds:0
- 496118.503461769 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.503484060 FILL_AUDIO dev:8 hw_level:2208
- 496118.503488733 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.503489426 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.503490351 WRITE_STREAMS_MIXED write_limit:0
- 496118.503493748 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.503503115 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.503503465 DEV_SLEEP_TIME dev:8 wake:000496118.549495009
- 496118.503505371 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.503555888 WAKE num_fds:1
- 496118.503581022 FILL_AUDIO dev:8 hw_level:2208
- 496118.503582739 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.503592868 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.503597479 DEV_STREAM_MIX written:1024 read:1024
- 496118.503598142 WRITE_STREAMS_MIXED write_limit:1024
- 496118.503599527 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.503600467 STREAM_SLEEP_TIME id:140000 wake:000496118.524742599
- 496118.503605592 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.503605971 DEV_SLEEP_TIME dev:8 wake:000496118.570933428
- 496118.503607064 SLEEP sleep:000000000.021142504 longest_wake:000158140
- 496118.524771187 WAKE num_fds:0
- 496118.524792444 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.524811297 FILL_AUDIO dev:8 hw_level:2224
- 496118.524814347 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.524814633 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.524815430 WRITE_STREAMS_MIXED write_limit:0
- 496118.524817932 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496118.524825913 SET_DEV_WAKE dev:8 hw_level:2224 sleep:2224
- 496118.524826242 DEV_SLEEP_TIME dev:8 wake:000496118.571152173
- 496118.524827565 SLEEP sleep:000000000.046333333 longest_wake:000158140
- 496118.524879030 WAKE num_fds:1
- 496118.524900851 FILL_AUDIO dev:8 hw_level:2176
- 496118.524902685 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.524911230 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.524915787 DEV_STREAM_MIX written:1024 read:1024
- 496118.524916319 WRITE_STREAMS_MIXED write_limit:1024
- 496118.524917543 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.524918588 STREAM_SLEEP_TIME id:140000 wake:000496118.546075932
- 496118.524924426 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.524924899 DEV_SLEEP_TIME dev:8 wake:000496118.591584778
- 496118.524925885 SLEEP sleep:000000000.021157820 longest_wake:000158140
- 496118.546097655 WAKE num_fds:0
- 496118.546112541 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.546126703 FILL_AUDIO dev:8 hw_level:2192
- 496118.546128925 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.546129092 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.546129613 WRITE_STREAMS_MIXED write_limit:0
- 496118.546130952 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.546136209 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.546136370 DEV_SLEEP_TIME dev:8 wake:000496118.591798078
- 496118.546137203 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.546161324 WAKE num_fds:1
- 496118.546173430 FILL_AUDIO dev:8 hw_level:2192
- 496118.546174217 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.546179310 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.546183028 DEV_STREAM_MIX written:1024 read:1024
- 496118.546183368 WRITE_STREAMS_MIXED write_limit:1024
- 496118.546183858 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.546184331 STREAM_SLEEP_TIME id:140000 wake:000496118.567409265
- 496118.546189248 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.546189390 DEV_SLEEP_TIME dev:8 wake:000496118.613184163
- 496118.546189920 SLEEP sleep:000000000.021225102 longest_wake:000158140
- 496118.567424239 WAKE num_fds:0
- 496118.567439411 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.567452286 FILL_AUDIO dev:8 hw_level:2208
- 496118.567454872 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.567455174 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.567455825 WRITE_STREAMS_MIXED write_limit:0
- 496118.567457476 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.567464131 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.567464314 DEV_SLEEP_TIME dev:8 wake:000496118.613458159
- 496118.567465126 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.567490875 WAKE num_fds:1
- 496118.567505725 FILL_AUDIO dev:8 hw_level:2208
- 496118.567506502 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.567511232 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.567512996 DEV_STREAM_MIX written:1024 read:1024
- 496118.567513203 WRITE_STREAMS_MIXED write_limit:1024
- 496118.567513727 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.567514129 STREAM_SLEEP_TIME id:140000 wake:000496118.588742598
- 496118.567518840 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.567518992 DEV_SLEEP_TIME dev:8 wake:000496118.634847296
- 496118.567519449 SLEEP sleep:000000000.021228635 longest_wake:000158140
- 496118.588780218 WAKE num_fds:0
- 496118.588794235 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.588810187 FILL_AUDIO dev:8 hw_level:2224
- 496118.588812252 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.588812393 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.588812942 WRITE_STREAMS_MIXED write_limit:0
- 496118.588814561 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496118.588819039 SET_DEV_WAKE dev:8 hw_level:2224 sleep:2224
- 496118.588819202 DEV_SLEEP_TIME dev:8 wake:000496118.635148443
- 496118.588820036 SLEEP sleep:000000000.046333333 longest_wake:000158140
- 496118.588854210 WAKE num_fds:1
- 496118.588870487 FILL_AUDIO dev:8 hw_level:2176
- 496118.588871082 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.588877727 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.588880046 DEV_STREAM_MIX written:1024 read:1024
- 496118.588880375 WRITE_STREAMS_MIXED write_limit:1024
- 496118.588881027 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.588881474 STREAM_SLEEP_TIME id:140000 wake:000496118.610075931
- 496118.588886516 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.588886664 DEV_SLEEP_TIME dev:8 wake:000496118.655547937
- 496118.588887092 SLEEP sleep:000000000.021194660 longest_wake:000158140
- 496118.610097814 WAKE num_fds:0
- 496118.610123399 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.610137913 FILL_AUDIO dev:8 hw_level:2192
- 496118.610140374 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.610140519 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.610141505 WRITE_STREAMS_MIXED write_limit:0
- 496118.610143585 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.610149415 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.610149652 DEV_SLEEP_TIME dev:8 wake:000496118.655810785
- 496118.610150372 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.610181468 WAKE num_fds:1
- 496118.610197004 FILL_AUDIO dev:8 hw_level:2192
- 496118.610198230 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.610203984 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.610206515 DEV_STREAM_MIX written:1024 read:1024
- 496118.610206788 WRITE_STREAMS_MIXED write_limit:1024
- 496118.610207314 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.610207787 STREAM_SLEEP_TIME id:140000 wake:000496118.631409264
- 496118.610212963 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.610213165 DEV_SLEEP_TIME dev:8 wake:000496118.677207596
- 496118.610213722 SLEEP sleep:000000000.021201668 longest_wake:000158140
- 496118.631437687 WAKE num_fds:0
- 496118.631451138 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.631464477 FILL_AUDIO dev:8 hw_level:2208
- 496118.631466576 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.631466740 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.631467215 WRITE_STREAMS_MIXED write_limit:0
- 496118.631468559 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.631474164 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.631474394 DEV_SLEEP_TIME dev:8 wake:000496118.677468970
- 496118.631475094 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.631557823 WAKE num_fds:1
- 496118.631572529 FILL_AUDIO dev:8 hw_level:2208
- 496118.631573346 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.631578696 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.631580226 DEV_STREAM_MIX written:1024 read:1024
- 496118.631580423 WRITE_STREAMS_MIXED write_limit:1024
- 496118.631581039 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.631581413 STREAM_SLEEP_TIME id:140000 wake:000496118.652742597
- 496118.631585882 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.631585996 DEV_SLEEP_TIME dev:8 wake:000496118.698914565
- 496118.631586399 SLEEP sleep:000000000.021161365 longest_wake:000158140
- 496118.652804884 WAKE num_fds:0
- 496118.652853602 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496118.652906300 FILL_AUDIO dev:8 hw_level:2176
- 496118.652916970 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.652917116 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.652918057 WRITE_STREAMS_MIXED write_limit:0
- 496118.652923991 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496118.652949242 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496118.652950075 DEV_SLEEP_TIME dev:8 wake:000496118.698258600
- 496118.652951721 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496118.653034042 WAKE num_fds:1
- 496118.653082023 FILL_AUDIO dev:8 hw_level:2176
- 496118.653087608 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.653115701 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.653126099 DEV_STREAM_MIX written:1024 read:1024
- 496118.653126366 WRITE_STREAMS_MIXED write_limit:1024
- 496118.653128297 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.653129600 STREAM_SLEEP_TIME id:140000 wake:000496118.674075930
- 496118.653141084 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.653141227 DEV_SLEEP_TIME dev:8 wake:000496118.719796011
- 496118.653142617 SLEEP sleep:000000000.020946585 longest_wake:000158140
- 496118.674106400 WAKE num_fds:0
- 496118.674120878 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.674135054 FILL_AUDIO dev:8 hw_level:2192
- 496118.674137010 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.674137173 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.674137648 WRITE_STREAMS_MIXED write_limit:0
- 496118.674139240 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.674144657 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.674144812 DEV_SLEEP_TIME dev:8 wake:000496118.719806407
- 496118.674145446 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.674178767 WAKE num_fds:1
- 496118.674190201 FILL_AUDIO dev:8 hw_level:2192
- 496118.674190857 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.674195897 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.674197446 DEV_STREAM_MIX written:1024 read:1024
- 496118.674197623 WRITE_STREAMS_MIXED write_limit:1024
- 496118.674197903 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.674198238 STREAM_SLEEP_TIME id:140000 wake:000496118.695409263
- 496118.674202644 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.674202766 DEV_SLEEP_TIME dev:8 wake:000496118.741198093
- 496118.674203141 SLEEP sleep:000000000.021211170 longest_wake:000158140
- 496118.695425973 WAKE num_fds:0
- 496118.695442160 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.695456413 FILL_AUDIO dev:8 hw_level:2208
- 496118.695458598 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.695458801 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.695459398 WRITE_STREAMS_MIXED write_limit:0
- 496118.695461090 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.695466757 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.695466949 DEV_SLEEP_TIME dev:8 wake:000496118.741461697
- 496118.695467723 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.695503662 WAKE num_fds:1
- 496118.695518956 FILL_AUDIO dev:8 hw_level:2208
- 496118.695519793 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.695526046 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.695528211 DEV_STREAM_MIX written:1024 read:1024
- 496118.695528463 WRITE_STREAMS_MIXED write_limit:1024
- 496118.695528914 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.695529424 STREAM_SLEEP_TIME id:140000 wake:000496118.716742596
- 496118.695534156 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.695534347 DEV_SLEEP_TIME dev:8 wake:000496118.762862556
- 496118.695534780 SLEEP sleep:000000000.021213373 longest_wake:000158140
- 496118.716796026 WAKE num_fds:0
- 496118.716844186 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496118.716881094 FILL_AUDIO dev:8 hw_level:2176
- 496118.716892655 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.716892910 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.716894646 WRITE_STREAMS_MIXED write_limit:0
- 496118.716899983 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496118.716910139 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496118.716910410 DEV_SLEEP_TIME dev:8 wake:000496118.762235198
- 496118.716914465 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496118.717037504 WAKE num_fds:1
- 496118.717069219 FILL_AUDIO dev:8 hw_level:2176
- 496118.717073251 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.717093009 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.717099155 DEV_STREAM_MIX written:1024 read:1024
- 496118.717099507 WRITE_STREAMS_MIXED write_limit:1024
- 496118.717100701 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.717101460 STREAM_SLEEP_TIME id:140000 wake:000496118.738075929
- 496118.717107009 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.717107210 DEV_SLEEP_TIME dev:8 wake:000496118.783767828
- 496118.717109169 SLEEP sleep:000000000.020974767 longest_wake:000158140
- 496118.738099922 WAKE num_fds:0
- 496118.738113821 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.738128082 FILL_AUDIO dev:8 hw_level:2192
- 496118.738130192 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.738130387 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.738130972 WRITE_STREAMS_MIXED write_limit:0
- 496118.738132446 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.738137824 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.738138054 DEV_SLEEP_TIME dev:8 wake:000496118.783799661
- 496118.738138719 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.738174290 WAKE num_fds:1
- 496118.738189554 FILL_AUDIO dev:8 hw_level:2192
- 496118.738190236 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.738195073 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.738198050 DEV_STREAM_MIX written:1024 read:1024
- 496118.738198380 WRITE_STREAMS_MIXED write_limit:1024
- 496118.738198938 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.738199357 STREAM_SLEEP_TIME id:140000 wake:000496118.759409262
- 496118.738203929 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.738204062 DEV_SLEEP_TIME dev:8 wake:000496118.805199158
- 496118.738204447 SLEEP sleep:000000000.021210104 longest_wake:000158140
- 496118.759429248 WAKE num_fds:0
- 496118.759443563 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.759460244 FILL_AUDIO dev:8 hw_level:2208
- 496118.759462267 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.759462398 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.759462818 WRITE_STREAMS_MIXED write_limit:0
- 496118.759464345 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.759469501 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.759469655 DEV_SLEEP_TIME dev:8 wake:000496118.805464831
- 496118.759470367 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.759517748 WAKE num_fds:1
- 496118.759531678 FILL_AUDIO dev:8 hw_level:2208
- 496118.759532357 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.759537800 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.759540617 DEV_STREAM_MIX written:1024 read:1024
- 496118.759540905 WRITE_STREAMS_MIXED write_limit:1024
- 496118.759541444 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.759541852 STREAM_SLEEP_TIME id:140000 wake:000496118.780742595
- 496118.759546251 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.759546357 DEV_SLEEP_TIME dev:8 wake:000496118.826875025
- 496118.759546696 SLEEP sleep:000000000.021200903 longest_wake:000158140
- 496118.780759760 WAKE num_fds:0
- 496118.780775008 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.780790131 FILL_AUDIO dev:8 hw_level:2224
- 496118.780791975 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.780792123 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.780792803 WRITE_STREAMS_MIXED write_limit:0
- 496118.780793974 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496118.780800286 SET_DEV_WAKE dev:8 hw_level:2224 sleep:2224
- 496118.780800421 DEV_SLEEP_TIME dev:8 wake:000496118.827128100
- 496118.780801289 SLEEP sleep:000000000.046333333 longest_wake:000158140
- 496118.780847586 WAKE num_fds:1
- 496118.780862518 FILL_AUDIO dev:8 hw_level:2176
- 496118.780863379 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.780868464 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.780870041 DEV_STREAM_MIX written:1024 read:1024
- 496118.780870230 WRITE_STREAMS_MIXED write_limit:1024
- 496118.780870593 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.780870958 STREAM_SLEEP_TIME id:140000 wake:000496118.802075928
- 496118.780875355 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.780875478 DEV_SLEEP_TIME dev:8 wake:000496118.847537449
- 496118.780875847 SLEEP sleep:000000000.021205145 longest_wake:000158140
- 496118.802102780 WAKE num_fds:0
- 496118.802120472 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.802137210 FILL_AUDIO dev:8 hw_level:2192
- 496118.802139917 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.802140064 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.802140609 WRITE_STREAMS_MIXED write_limit:0
- 496118.802142432 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.802147701 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.802147852 DEV_SLEEP_TIME dev:8 wake:000496118.847809557
- 496118.802148516 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.802195380 WAKE num_fds:1
- 496118.802209967 FILL_AUDIO dev:8 hw_level:2192
- 496118.802210703 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.802217788 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.802219789 DEV_STREAM_MIX written:1024 read:1024
- 496118.802219989 WRITE_STREAMS_MIXED write_limit:1024
- 496118.802220449 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.802220872 STREAM_SLEEP_TIME id:140000 wake:000496118.823409261
- 496118.802225303 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.802225418 DEV_SLEEP_TIME dev:8 wake:000496118.869220669
- 496118.802225820 SLEEP sleep:000000000.021188592 longest_wake:000158140
- 496118.823426698 WAKE num_fds:0
- 496118.823441151 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.823457708 FILL_AUDIO dev:8 hw_level:2208
- 496118.823460089 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.823460330 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.823460828 WRITE_STREAMS_MIXED write_limit:0
- 496118.823462430 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.823467790 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.823467949 DEV_SLEEP_TIME dev:8 wake:000496118.869462918
- 496118.823468618 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.823507440 WAKE num_fds:1
- 496118.823521661 FILL_AUDIO dev:8 hw_level:2208
- 496118.823522559 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.823529596 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.823531920 DEV_STREAM_MIX written:1024 read:1024
- 496118.823532244 WRITE_STREAMS_MIXED write_limit:1024
- 496118.823533007 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.823533383 STREAM_SLEEP_TIME id:140000 wake:000496118.844742594
- 496118.823538141 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.823538313 DEV_SLEEP_TIME dev:8 wake:000496118.890866568
- 496118.823538782 SLEEP sleep:000000000.021209359 longest_wake:000158140
- 496118.844793611 WAKE num_fds:0
- 496118.844842455 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496118.844888762 FILL_AUDIO dev:8 hw_level:2176
- 496118.844899355 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.844899489 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.844901921 WRITE_STREAMS_MIXED write_limit:0
- 496118.844909466 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496118.844922258 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496118.844923289 DEV_SLEEP_TIME dev:8 wake:000496118.890245017
- 496118.844926573 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496118.845050151 WAKE num_fds:1
- 496118.845096292 FILL_AUDIO dev:8 hw_level:2176
- 496118.845101172 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.845127890 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.845137332 DEV_STREAM_MIX written:1024 read:1024
- 496118.845138226 WRITE_STREAMS_MIXED write_limit:1024
- 496118.845140015 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.845143090 STREAM_SLEEP_TIME id:140000 wake:000496118.866075927
- 496118.845154493 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.845155261 DEV_SLEEP_TIME dev:8 wake:000496118.911809504
- 496118.845156233 SLEEP sleep:000000000.020933089 longest_wake:000158140
- 496118.866103566 WAKE num_fds:0
- 496118.866119526 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.866134595 FILL_AUDIO dev:8 hw_level:2192
- 496118.866137519 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.866137677 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.866138149 WRITE_STREAMS_MIXED write_limit:0
- 496118.866140088 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.866146294 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.866146511 DEV_SLEEP_TIME dev:8 wake:000496118.911807282
- 496118.866147537 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.866177435 WAKE num_fds:1
- 496118.866192557 FILL_AUDIO dev:8 hw_level:2192
- 496118.866193498 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.866198506 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.866200264 DEV_STREAM_MIX written:1024 read:1024
- 496118.866200426 WRITE_STREAMS_MIXED write_limit:1024
- 496118.866200819 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.866201185 STREAM_SLEEP_TIME id:140000 wake:000496118.887409260
- 496118.866205681 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.866205793 DEV_SLEEP_TIME dev:8 wake:000496118.933201012
- 496118.866206313 SLEEP sleep:000000000.021208248 longest_wake:000158140
- 496118.887425173 WAKE num_fds:0
- 496118.887438794 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.887455874 FILL_AUDIO dev:8 hw_level:2208
- 496118.887457788 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.887457958 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.887458388 WRITE_STREAMS_MIXED write_limit:0
- 496118.887460020 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.887465184 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.887465331 DEV_SLEEP_TIME dev:8 wake:000496118.933460516
- 496118.887465992 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.887502924 WAKE num_fds:1
- 496118.887517026 FILL_AUDIO dev:8 hw_level:2208
- 496118.887517553 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.887522198 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.887524704 DEV_STREAM_MIX written:1024 read:1024
- 496118.887524986 WRITE_STREAMS_MIXED write_limit:1024
- 496118.887525564 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.887525976 STREAM_SLEEP_TIME id:140000 wake:000496118.908742593
- 496118.887530536 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.887530658 DEV_SLEEP_TIME dev:8 wake:000496118.954859148
- 496118.887531007 SLEEP sleep:000000000.021216778 longest_wake:000158140
- 496118.908761014 WAKE num_fds:0
- 496118.908774255 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.908788078 FILL_AUDIO dev:8 hw_level:2224
- 496118.908791095 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.908791227 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.908791643 WRITE_STREAMS_MIXED write_limit:0
- 496118.908792879 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496118.908798303 SET_DEV_WAKE dev:8 hw_level:2224 sleep:2224
- 496118.908798448 DEV_SLEEP_TIME dev:8 wake:000496118.955126660
- 496118.908799066 SLEEP sleep:000000000.046333333 longest_wake:000158140
- 496118.908840065 WAKE num_fds:1
- 496118.908854501 FILL_AUDIO dev:8 hw_level:2176
- 496118.908855141 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.908859990 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.908861559 DEV_STREAM_MIX written:1024 read:1024
- 496118.908861758 WRITE_STREAMS_MIXED write_limit:1024
- 496118.908862178 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.908862536 STREAM_SLEEP_TIME id:140000 wake:000496118.930075926
- 496118.908866946 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.908867060 DEV_SLEEP_TIME dev:8 wake:000496118.975529057
- 496118.908867432 SLEEP sleep:000000000.021213535 longest_wake:000158140
- 496118.930094024 WAKE num_fds:0
- 496118.930107968 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.930124375 FILL_AUDIO dev:8 hw_level:2192
- 496118.930126805 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.930127218 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.930127938 WRITE_STREAMS_MIXED write_limit:0
- 496118.930129478 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.930136050 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.930136345 DEV_SLEEP_TIME dev:8 wake:000496118.975796868
- 496118.930137375 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.930180425 WAKE num_fds:1
- 496118.930195856 FILL_AUDIO dev:8 hw_level:2192
- 496118.930197015 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.930202916 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.930204953 DEV_STREAM_MIX written:1024 read:1024
- 496118.930205305 WRITE_STREAMS_MIXED write_limit:1024
- 496118.930205985 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.930206375 STREAM_SLEEP_TIME id:140000 wake:000496118.951409259
- 496118.930211062 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.930211211 DEV_SLEEP_TIME dev:8 wake:000496118.997206196
- 496118.930211579 SLEEP sleep:000000000.021203063 longest_wake:000158140
- 496118.951427153 WAKE num_fds:0
- 496118.951440867 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496118.951457640 FILL_AUDIO dev:8 hw_level:2208
- 496118.951459818 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.951459979 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.951460418 WRITE_STREAMS_MIXED write_limit:0
- 496118.951462188 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496118.951468096 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496118.951468253 DEV_SLEEP_TIME dev:8 wake:000496118.997462723
- 496118.951469025 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496118.951511365 WAKE num_fds:1
- 496118.951527108 FILL_AUDIO dev:8 hw_level:2208
- 496118.951527922 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.951533170 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.951534775 DEV_STREAM_MIX written:1024 read:1024
- 496118.951534973 WRITE_STREAMS_MIXED write_limit:1024
- 496118.951536328 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496118.951536704 STREAM_SLEEP_TIME id:140000 wake:000496118.972742592
- 496118.951541447 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496118.951541573 DEV_SLEEP_TIME dev:8 wake:000496119.018869867
- 496118.951542050 SLEEP sleep:000000000.021206058 longest_wake:000158140
- 496118.972761770 WAKE num_fds:0
- 496118.972776276 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496118.972797345 FILL_AUDIO dev:8 hw_level:2224
- 496118.972803518 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.972803884 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.972804436 WRITE_STREAMS_MIXED write_limit:0
- 496118.972806221 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496118.972822039 SET_DEV_WAKE dev:8 hw_level:2224 sleep:2224
- 496118.972822283 DEV_SLEEP_TIME dev:8 wake:000496119.019140179
- 496118.972823594 SLEEP sleep:000000000.046333333 longest_wake:000158140
- 496118.972882579 WAKE num_fds:1
- 496118.972898523 FILL_AUDIO dev:8 hw_level:2176
- 496118.972899309 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.972905056 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.972906877 DEV_STREAM_MIX written:1024 read:1024
- 496118.972907047 WRITE_STREAMS_MIXED write_limit:1024
- 496118.972907575 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496118.972907888 STREAM_SLEEP_TIME id:140000 wake:000496118.994075925
- 496118.972912755 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496118.972912878 DEV_SLEEP_TIME dev:8 wake:000496119.039574389
- 496118.972913362 SLEEP sleep:000000000.021168202 longest_wake:000158140
- 496118.994114414 WAKE num_fds:0
- 496118.994140794 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496118.994156916 FILL_AUDIO dev:8 hw_level:2192
- 496118.994159491 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496118.994159650 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496118.994160169 WRITE_STREAMS_MIXED write_limit:0
- 496118.994164191 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496118.994171200 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496118.994171359 DEV_SLEEP_TIME dev:8 wake:000496119.039831814
- 496118.994172168 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496118.994205388 WAKE num_fds:1
- 496118.994222444 FILL_AUDIO dev:8 hw_level:2192
- 496118.994223295 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496118.994229362 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496118.994232914 DEV_STREAM_MIX written:1024 read:1024
- 496118.994233254 WRITE_STREAMS_MIXED write_limit:1024
- 496118.994233932 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496118.994234486 STREAM_SLEEP_TIME id:140000 wake:000496119.015409258
- 496118.994239352 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496118.994239573 DEV_SLEEP_TIME dev:8 wake:000496119.061234321
- 496118.994239966 SLEEP sleep:000000000.021174937 longest_wake:000158140
- 496119.015494273 WAKE num_fds:0
- 496119.015517241 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.015543933 FILL_AUDIO dev:8 hw_level:2208
- 496119.015548213 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.015548684 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.015549922 WRITE_STREAMS_MIXED write_limit:0
- 496119.015552888 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.015562300 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.015563077 DEV_SLEEP_TIME dev:8 wake:000496119.061554262
- 496119.015565252 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.015647747 WAKE num_fds:1
- 496119.015677927 FILL_AUDIO dev:8 hw_level:2208
- 496119.015679811 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.015695257 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.015700629 DEV_STREAM_MIX written:1024 read:1024
- 496119.015701276 WRITE_STREAMS_MIXED write_limit:1024
- 496119.015702835 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.015704443 STREAM_SLEEP_TIME id:140000 wake:000496119.036742591
- 496119.015711715 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.015712136 DEV_SLEEP_TIME dev:8 wake:000496119.083037125
- 496119.015713529 SLEEP sleep:000000000.021038799 longest_wake:000158140
- 496119.036811692 WAKE num_fds:0
- 496119.036832364 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.036857117 FILL_AUDIO dev:8 hw_level:2176
- 496119.036861557 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.036862023 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.036863201 WRITE_STREAMS_MIXED write_limit:0
- 496119.036866368 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.036875123 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.036875629 DEV_SLEEP_TIME dev:8 wake:000496119.082201545
- 496119.036877418 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.036947164 WAKE num_fds:1
- 496119.036973731 FILL_AUDIO dev:8 hw_level:2176
- 496119.036975349 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.036987853 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.036993702 DEV_STREAM_MIX written:1024 read:1024
- 496119.036994293 WRITE_STREAMS_MIXED write_limit:1024
- 496119.036995441 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.036996538 STREAM_SLEEP_TIME id:140000 wake:000496119.058075924
- 496119.037002352 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.037002703 DEV_SLEEP_TIME dev:8 wake:000496119.103662693
- 496119.037003665 SLEEP sleep:000000000.021079897 longest_wake:000158140
- 496119.058114096 WAKE num_fds:0
- 496119.058141173 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.058170250 FILL_AUDIO dev:8 hw_level:2192
- 496119.058174380 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.058174856 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.058176079 WRITE_STREAMS_MIXED write_limit:0
- 496119.058179060 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.058186803 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.058187274 DEV_SLEEP_TIME dev:8 wake:000496119.103846909
- 496119.058189705 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.058271589 WAKE num_fds:1
- 496119.058298411 FILL_AUDIO dev:8 hw_level:2192
- 496119.058300596 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.058314814 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.058320702 DEV_STREAM_MIX written:1024 read:1024
- 496119.058321610 WRITE_STREAMS_MIXED write_limit:1024
- 496119.058323068 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.058324672 STREAM_SLEEP_TIME id:140000 wake:000496119.079409257
- 496119.058343765 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.058344301 DEV_SLEEP_TIME dev:8 wake:000496119.125323950
- 496119.058345935 SLEEP sleep:000000000.021085307 longest_wake:000158140
- 496119.079480188 WAKE num_fds:0
- 496119.079495256 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.079509743 FILL_AUDIO dev:8 hw_level:2208
- 496119.079512120 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.079512360 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.079512974 WRITE_STREAMS_MIXED write_limit:0
- 496119.079514674 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.079521296 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.079521544 DEV_SLEEP_TIME dev:8 wake:000496119.125515340
- 496119.079522548 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.079554700 WAKE num_fds:1
- 496119.079570214 FILL_AUDIO dev:8 hw_level:2208
- 496119.079570828 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.079578731 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.079580760 DEV_STREAM_MIX written:1024 read:1024
- 496119.079581043 WRITE_STREAMS_MIXED write_limit:1024
- 496119.079581535 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.079582051 STREAM_SLEEP_TIME id:140000 wake:000496119.100742590
- 496119.079586774 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.079586940 DEV_SLEEP_TIME dev:8 wake:000496119.146915148
- 496119.079587422 SLEEP sleep:000000000.021160775 longest_wake:000158140
- 496119.100983708 WAKE num_fds:0
- 496119.101006952 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.101039086 FILL_AUDIO dev:8 hw_level:2176
- 496119.101043727 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.101044840 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.101045897 WRITE_STREAMS_MIXED write_limit:0
- 496119.101049455 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.101057769 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.101058316 DEV_SLEEP_TIME dev:8 wake:000496119.146384086
- 496119.101060616 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.101152679 WAKE num_fds:1
- 496119.101184647 FILL_AUDIO dev:8 hw_level:2176
- 496119.101186787 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.101201316 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.101205696 DEV_STREAM_MIX written:1024 read:1024
- 496119.101206237 WRITE_STREAMS_MIXED write_limit:1024
- 496119.101207300 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.101208487 STREAM_SLEEP_TIME id:140000 wake:000496119.122075923
- 496119.101214476 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.101214857 DEV_SLEEP_TIME dev:8 wake:000496119.167874687
- 496119.101215909 SLEEP sleep:000000000.020867902 longest_wake:000158140
- 496119.122173783 WAKE num_fds:0
- 496119.122197212 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.122228920 FILL_AUDIO dev:8 hw_level:2192
- 496119.122234067 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.122234538 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.122235896 WRITE_STREAMS_MIXED write_limit:0
- 496119.122238828 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.122248681 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.122249172 DEV_SLEEP_TIME dev:8 wake:000496119.167907429
- 496119.122251026 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.122367113 WAKE num_fds:1
- 496119.122402269 FILL_AUDIO dev:8 hw_level:2192
- 496119.122404324 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.122419379 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.122424220 DEV_STREAM_MIX written:1024 read:1024
- 496119.122424812 WRITE_STREAMS_MIXED write_limit:1024
- 496119.122425909 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.122427007 STREAM_SLEEP_TIME id:140000 wake:000496119.143409256
- 496119.122433276 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.122433662 DEV_SLEEP_TIME dev:8 wake:000496119.189426520
- 496119.122434704 SLEEP sleep:000000000.020982736 longest_wake:000158140
- 496119.143482275 WAKE num_fds:0
- 496119.143518679 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.143547377 FILL_AUDIO dev:8 hw_level:2208
- 496119.143553840 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.143554353 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.143555696 WRITE_STREAMS_MIXED write_limit:0
- 496119.143561538 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.143570165 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.143570707 DEV_SLEEP_TIME dev:8 wake:000496119.189563077
- 496119.143572956 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.143667142 WAKE num_fds:1
- 496119.143695684 FILL_AUDIO dev:8 hw_level:2208
- 496119.143698005 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.143716969 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.143722870 DEV_STREAM_MIX written:1024 read:1024
- 496119.143723459 WRITE_STREAMS_MIXED write_limit:1024
- 496119.143724850 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.143725889 STREAM_SLEEP_TIME id:140000 wake:000496119.164742589
- 496119.143732011 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.143732364 DEV_SLEEP_TIME dev:8 wake:000496119.211058825
- 496119.143734365 SLEEP sleep:000000000.021017097 longest_wake:000158140
- 496119.164992925 WAKE num_fds:0
- 496119.165016424 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.165048107 FILL_AUDIO dev:8 hw_level:2176
- 496119.165052342 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.165053244 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.165054607 WRITE_STREAMS_MIXED write_limit:0
- 496119.165057874 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.165065933 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.165066519 DEV_SLEEP_TIME dev:8 wake:000496119.210392460
- 496119.165068399 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.165163333 WAKE num_fds:1
- 496119.165194605 FILL_AUDIO dev:8 hw_level:2176
- 496119.165196530 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.165211549 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.165216014 DEV_STREAM_MIX written:1024 read:1024
- 496119.165216566 WRITE_STREAMS_MIXED write_limit:1024
- 496119.165217433 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.165218575 STREAM_SLEEP_TIME id:140000 wake:000496119.186075922
- 496119.165224735 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.165225080 DEV_SLEEP_TIME dev:8 wake:000496119.231884610
- 496119.165226073 SLEEP sleep:000000000.020857978 longest_wake:000158140
- 496119.186110447 WAKE num_fds:0
- 496119.186133796 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.186157525 FILL_AUDIO dev:8 hw_level:2192
- 496119.186161725 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.186162151 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.186163629 WRITE_STREAMS_MIXED write_limit:0
- 496119.186166561 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.186175261 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.186175828 DEV_SLEEP_TIME dev:8 wake:000496119.231834500
- 496119.186177707 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.186268025 WAKE num_fds:1
- 496119.186295584 FILL_AUDIO dev:8 hw_level:2192
- 496119.186297734 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.186308379 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.186312207 DEV_STREAM_MIX written:1024 read:1024
- 496119.186312824 WRITE_STREAMS_MIXED write_limit:1024
- 496119.186313921 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.186315004 STREAM_SLEEP_TIME id:140000 wake:000496119.207409255
- 496119.186320902 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.186321253 DEV_SLEEP_TIME dev:8 wake:000496119.253314533
- 496119.186322296 SLEEP sleep:000000000.021094722 longest_wake:000158140
- 496119.207471590 WAKE num_fds:0
- 496119.207496974 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.207525795 FILL_AUDIO dev:8 hw_level:2208
- 496119.207530271 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.207530767 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.207532561 WRITE_STREAMS_MIXED write_limit:0
- 496119.207535513 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.207543070 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.207543581 DEV_SLEEP_TIME dev:8 wake:000496119.253536665
- 496119.207545335 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.207627590 WAKE num_fds:1
- 496119.207655034 FILL_AUDIO dev:8 hw_level:2208
- 496119.207657244 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.207673451 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.207679410 DEV_STREAM_MIX written:1024 read:1024
- 496119.207680162 WRITE_STREAMS_MIXED write_limit:1024
- 496119.207681600 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.207683068 STREAM_SLEEP_TIME id:140000 wake:000496119.228742588
- 496119.207690606 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.207691172 DEV_SLEEP_TIME dev:8 wake:000496119.275015700
- 496119.207692600 SLEEP sleep:000000000.021060221 longest_wake:000158140
- 496119.228853062 WAKE num_fds:0
- 496119.228876095 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.228907021 FILL_AUDIO dev:8 hw_level:2176
- 496119.228912308 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.228913446 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.228914463 WRITE_STREAMS_MIXED write_limit:0
- 496119.228917315 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.228925719 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.228926215 DEV_SLEEP_TIME dev:8 wake:000496119.274252016
- 496119.228928676 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.229018133 WAKE num_fds:1
- 496119.229047681 FILL_AUDIO dev:8 hw_level:2176
- 496119.229049234 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.229064119 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.229070388 DEV_STREAM_MIX written:1024 read:1024
- 496119.229070959 WRITE_STREAMS_MIXED write_limit:1024
- 496119.229071967 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.229072949 STREAM_SLEEP_TIME id:140000 wake:000496119.250075921
- 496119.229079509 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.229079870 DEV_SLEEP_TIME dev:8 wake:000496119.295739144
- 496119.229080907 SLEEP sleep:000000000.021003443 longest_wake:000158140
- 496119.250343383 WAKE num_fds:0
- 496119.250367173 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.250399042 FILL_AUDIO dev:8 hw_level:2192
- 496119.250403953 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.250404414 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.250406243 WRITE_STREAMS_MIXED write_limit:0
- 496119.250409240 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.250418672 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.250419183 DEV_SLEEP_TIME dev:8 wake:000496119.296078016
- 496119.250421268 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.250517861 WAKE num_fds:1
- 496119.250549253 FILL_AUDIO dev:8 hw_level:2192
- 496119.250551022 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.250566493 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.250571199 DEV_STREAM_MIX written:1024 read:1024
- 496119.250571770 WRITE_STREAMS_MIXED write_limit:1024
- 496119.250572933 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.250573955 STREAM_SLEEP_TIME id:140000 wake:000496119.271409254
- 496119.250580571 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.250580951 DEV_SLEEP_TIME dev:8 wake:000496119.317573489
- 496119.250582019 SLEEP sleep:000000000.020835765 longest_wake:000158140
- 496119.271663162 WAKE num_fds:0
- 496119.271686306 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.271718400 FILL_AUDIO dev:8 hw_level:2208
- 496119.271722684 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.271723126 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.271725130 WRITE_STREAMS_MIXED write_limit:0
- 496119.271728042 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.271736516 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.271737058 DEV_SLEEP_TIME dev:8 wake:000496119.317729726
- 496119.271738827 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.271834628 WAKE num_fds:1
- 496119.271865213 FILL_AUDIO dev:8 hw_level:2160
- 496119.271867238 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.271881546 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.271887019 DEV_STREAM_MIX written:1024 read:1024
- 496119.271887685 WRITE_STREAMS_MIXED write_limit:1024
- 496119.271888612 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496119.271889700 STREAM_SLEEP_TIME id:140000 wake:000496119.292742587
- 496119.271895884 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496119.271896255 DEV_SLEEP_TIME dev:8 wake:000496119.338222557
- 496119.271897242 SLEEP sleep:000000000.020853363 longest_wake:000158140
- 496119.292999314 WAKE num_fds:0
- 496119.293023229 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.293055559 FILL_AUDIO dev:8 hw_level:2176
- 496119.293060059 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.293060520 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.293062169 WRITE_STREAMS_MIXED write_limit:0
- 496119.293065406 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.293073836 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.293074387 DEV_SLEEP_TIME dev:8 wake:000496119.338400093
- 496119.293076161 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.293169717 WAKE num_fds:1
- 496119.293197421 FILL_AUDIO dev:8 hw_level:2176
- 496119.293199205 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.293213278 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.293217447 DEV_STREAM_MIX written:1024 read:1024
- 496119.293218024 WRITE_STREAMS_MIXED write_limit:1024
- 496119.293219562 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.293220524 STREAM_SLEEP_TIME id:140000 wake:000496119.314075920
- 496119.293226634 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.293227014 DEV_SLEEP_TIME dev:8 wake:000496119.359886734
- 496119.293228157 SLEEP sleep:000000000.020855852 longest_wake:000158140
- 496119.314326940 WAKE num_fds:0
- 496119.314367935 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.314398355 FILL_AUDIO dev:8 hw_level:2192
- 496119.314402439 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.314402945 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.314404148 WRITE_STREAMS_MIXED write_limit:0
- 496119.314406874 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.314415835 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.314416366 DEV_SLEEP_TIME dev:8 wake:000496119.360075290
- 496119.314418211 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.314513646 WAKE num_fds:1
- 496119.314545354 FILL_AUDIO dev:8 hw_level:2192
- 496119.314547228 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.314562363 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.314566809 DEV_STREAM_MIX written:1024 read:1024
- 496119.314567295 WRITE_STREAMS_MIXED write_limit:1024
- 496119.314568227 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.314569314 STREAM_SLEEP_TIME id:140000 wake:000496119.335409253
- 496119.314575188 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.314575539 DEV_SLEEP_TIME dev:8 wake:000496119.381568818
- 496119.314576531 SLEEP sleep:000000000.020840435 longest_wake:000158140
- 496119.335516443 WAKE num_fds:0
- 496119.335539261 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.335569801 FILL_AUDIO dev:8 hw_level:2208
- 496119.335574597 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.335575099 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.335576286 WRITE_STREAMS_MIXED write_limit:0
- 496119.335579890 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.335588279 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.335588815 DEV_SLEEP_TIME dev:8 wake:000496119.381581313
- 496119.335590930 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.335683594 WAKE num_fds:1
- 496119.335716806 FILL_AUDIO dev:8 hw_level:2208
- 496119.335718695 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.335733775 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.335738676 DEV_STREAM_MIX written:1024 read:1024
- 496119.335739258 WRITE_STREAMS_MIXED write_limit:1024
- 496119.335740340 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.335741733 STREAM_SLEEP_TIME id:140000 wake:000496119.356742586
- 496119.335747988 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.335748384 DEV_SLEEP_TIME dev:8 wake:000496119.403074355
- 496119.335749381 SLEEP sleep:000000000.021001564 longest_wake:000158140
- 496119.356772896 WAKE num_fds:0
- 496119.356796024 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496119.356818947 FILL_AUDIO dev:8 hw_level:2224
- 496119.356823142 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.356823573 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.356824741 WRITE_STREAMS_MIXED write_limit:0
- 496119.356827893 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496119.356836297 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.356836784 DEV_SLEEP_TIME dev:8 wake:000496119.402162539
- 496119.356838492 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.356924451 WAKE num_fds:1
- 496119.356950401 FILL_AUDIO dev:8 hw_level:2176
- 496119.356952285 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.356965009 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.356969244 DEV_STREAM_MIX written:1024 read:1024
- 496119.356969806 WRITE_STREAMS_MIXED write_limit:1024
- 496119.356971003 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.356972096 STREAM_SLEEP_TIME id:140000 wake:000496119.378075919
- 496119.356977999 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.356978415 DEV_SLEEP_TIME dev:8 wake:000496119.423638251
- 496119.356979448 SLEEP sleep:000000000.021104334 longest_wake:000158140
- 496119.378141728 WAKE num_fds:0
- 496119.378163549 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.378184522 FILL_AUDIO dev:8 hw_level:2192
- 496119.378189328 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.378189804 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.378190987 WRITE_STREAMS_MIXED write_limit:0
- 496119.378193969 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.378202564 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.378203050 DEV_SLEEP_TIME dev:8 wake:000496119.423862198
- 496119.378204924 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.378286091 WAKE num_fds:1
- 496119.378312282 FILL_AUDIO dev:8 hw_level:2192
- 496119.378313760 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.378325999 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.378342576 DEV_STREAM_MIX written:1024 read:1024
- 496119.378343172 WRITE_STREAMS_MIXED write_limit:1024
- 496119.378344185 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.378345337 STREAM_SLEEP_TIME id:140000 wake:000496119.399409252
- 496119.378351411 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.378351822 DEV_SLEEP_TIME dev:8 wake:000496119.445344856
- 496119.378352865 SLEEP sleep:000000000.021064396 longest_wake:000158140
- 496119.399442392 WAKE num_fds:0
- 496119.399463837 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.399490884 FILL_AUDIO dev:8 hw_level:2208
- 496119.399495094 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.399495550 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.399496602 WRITE_STREAMS_MIXED write_limit:0
- 496119.399499955 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.399507778 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.399508294 DEV_SLEEP_TIME dev:8 wake:000496119.445501148
- 496119.399510033 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.399592408 WAKE num_fds:1
- 496119.399619716 FILL_AUDIO dev:8 hw_level:2208
- 496119.399621180 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.399633964 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.399637964 DEV_STREAM_MIX written:1024 read:1024
- 496119.399638485 WRITE_STREAMS_MIXED write_limit:1024
- 496119.399639652 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.399640655 STREAM_SLEEP_TIME id:140000 wake:000496119.420742585
- 496119.399646398 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.399646749 DEV_SLEEP_TIME dev:8 wake:000496119.466973537
- 496119.399647736 SLEEP sleep:000000000.021102381 longest_wake:000158140
- 496119.420990443 WAKE num_fds:0
- 496119.421014493 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.421045224 FILL_AUDIO dev:8 hw_level:2176
- 496119.421050482 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.421050928 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.421052376 WRITE_STREAMS_MIXED write_limit:0
- 496119.421055273 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.421063802 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.421064384 DEV_SLEEP_TIME dev:8 wake:000496119.466390335
- 496119.421066238 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.421162485 WAKE num_fds:1
- 496119.421190410 FILL_AUDIO dev:8 hw_level:2176
- 496119.421192264 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.421208496 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.421213172 DEV_STREAM_MIX written:1024 read:1024
- 496119.421213728 WRITE_STREAMS_MIXED write_limit:1024
- 496119.421214706 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.421215848 STREAM_SLEEP_TIME id:140000 wake:000496119.442075918
- 496119.421222303 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.421222684 DEV_SLEEP_TIME dev:8 wake:000496119.487882013
- 496119.421223726 SLEEP sleep:000000000.020860571 longest_wake:000158140
- 496119.442117753 WAKE num_fds:0
- 496119.442143662 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.442172815 FILL_AUDIO dev:8 hw_level:2192
- 496119.442177621 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.442178072 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.442178974 WRITE_STREAMS_MIXED write_limit:0
- 496119.442181911 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.442190205 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.442190776 DEV_SLEEP_TIME dev:8 wake:000496119.487849729
- 496119.442192661 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.442277682 WAKE num_fds:1
- 496119.442304804 FILL_AUDIO dev:8 hw_level:2192
- 496119.442307466 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.442319594 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.442325988 DEV_STREAM_MIX written:1024 read:1024
- 496119.442326830 WRITE_STREAMS_MIXED write_limit:1024
- 496119.442342225 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.442343733 STREAM_SLEEP_TIME id:140000 wake:000496119.463409251
- 496119.442351025 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.442351657 DEV_SLEEP_TIME dev:8 wake:000496119.509343087
- 496119.442353215 SLEEP sleep:000000000.021066164 longest_wake:000158140
- 496119.463441223 WAKE num_fds:0
- 496119.463463406 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.463494930 FILL_AUDIO dev:8 hw_level:2208
- 496119.463499425 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.463499838 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.463501037 WRITE_STREAMS_MIXED write_limit:0
- 496119.463504016 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.463513001 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.463513429 DEV_SLEEP_TIME dev:8 wake:000496119.509505367
- 496119.463515069 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.463624173 WAKE num_fds:1
- 496119.463650301 FILL_AUDIO dev:8 hw_level:2208
- 496119.463653032 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.463670801 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.463678575 DEV_STREAM_MIX written:1024 read:1024
- 496119.463679252 WRITE_STREAMS_MIXED write_limit:1024
- 496119.463680808 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.463682111 STREAM_SLEEP_TIME id:140000 wake:000496119.484742584
- 496119.463688870 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.463689315 DEV_SLEEP_TIME dev:8 wake:000496119.531014955
- 496119.463690759 SLEEP sleep:000000000.021060962 longest_wake:000158140
- 496119.484761936 WAKE num_fds:0
- 496119.484774842 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496119.484786984 FILL_AUDIO dev:8 hw_level:2224
- 496119.484789594 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.484789778 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.484790606 WRITE_STREAMS_MIXED write_limit:0
- 496119.484791910 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496119.484797359 SET_DEV_WAKE dev:8 hw_level:2224 sleep:2224
- 496119.484797534 DEV_SLEEP_TIME dev:8 wake:000496119.531125750
- 496119.484798276 SLEEP sleep:000000000.046333333 longest_wake:000158140
- 496119.484828393 WAKE num_fds:1
- 496119.484842892 FILL_AUDIO dev:8 hw_level:2176
- 496119.484843484 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.484849786 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.484852445 DEV_STREAM_MIX written:1024 read:1024
- 496119.484852760 WRITE_STREAMS_MIXED write_limit:1024
- 496119.484853392 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.484853881 STREAM_SLEEP_TIME id:140000 wake:000496119.506075917
- 496119.484858408 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.484858539 DEV_SLEEP_TIME dev:8 wake:000496119.551520364
- 496119.484858931 SLEEP sleep:000000000.021222219 longest_wake:000158140
- 496119.506277376 WAKE num_fds:0
- 496119.506291073 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.506307673 FILL_AUDIO dev:8 hw_level:2192
- 496119.506310095 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.506310261 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.506310695 WRITE_STREAMS_MIXED write_limit:0
- 496119.506312020 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.506317760 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.506317950 DEV_SLEEP_TIME dev:8 wake:000496119.551979289
- 496119.506318606 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.506364111 WAKE num_fds:1
- 496119.506379211 FILL_AUDIO dev:8 hw_level:2192
- 496119.506380031 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.506386971 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.506388635 DEV_STREAM_MIX written:1024 read:1024
- 496119.506388839 WRITE_STREAMS_MIXED write_limit:1024
- 496119.506389202 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.506389581 STREAM_SLEEP_TIME id:140000 wake:000496119.527409250
- 496119.506394062 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.506394200 DEV_SLEEP_TIME dev:8 wake:000496119.573389409
- 496119.506394609 SLEEP sleep:000000000.021019841 longest_wake:000158140
- 496119.527434443 WAKE num_fds:0
- 496119.527460343 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.527484093 FILL_AUDIO dev:8 hw_level:2208
- 496119.527489130 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.527489626 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.527490718 WRITE_STREAMS_MIXED write_limit:0
- 496119.527495374 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.527504154 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.527504685 DEV_SLEEP_TIME dev:8 wake:000496119.573496602
- 496119.527508008 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.527588594 WAKE num_fds:1
- 496119.527616604 FILL_AUDIO dev:8 hw_level:2208
- 496119.527619475 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.527633914 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.527640614 DEV_STREAM_MIX written:1024 read:1024
- 496119.527641321 WRITE_STREAMS_MIXED write_limit:1024
- 496119.527643035 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.527644568 STREAM_SLEEP_TIME id:140000 wake:000496119.548742583
- 496119.527651885 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.527653088 DEV_SLEEP_TIME dev:8 wake:000496119.594977240
- 496119.527654657 SLEEP sleep:000000000.021098676 longest_wake:000158140
- 496119.548999664 WAKE num_fds:0
- 496119.549022737 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.549054295 FILL_AUDIO dev:8 hw_level:2176
- 496119.549059261 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.549059843 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.549061186 WRITE_STREAMS_MIXED write_limit:0
- 496119.549064483 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.549072813 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.549073359 DEV_SLEEP_TIME dev:8 wake:000496119.594399250
- 496119.549075689 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.549176036 WAKE num_fds:1
- 496119.549203574 FILL_AUDIO dev:8 hw_level:2176
- 496119.549205544 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.549220529 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.549224718 DEV_STREAM_MIX written:1024 read:1024
- 496119.549225270 WRITE_STREAMS_MIXED write_limit:1024
- 496119.549226192 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.549227244 STREAM_SLEEP_TIME id:140000 wake:000496119.570075916
- 496119.549234205 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.549234591 DEV_SLEEP_TIME dev:8 wake:000496119.615893439
- 496119.549235593 SLEEP sleep:000000000.020849143 longest_wake:000158140
- 496119.570344229 WAKE num_fds:0
- 496119.570367668 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.570397667 FILL_AUDIO dev:8 hw_level:2192
- 496119.570402293 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.570402749 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.570403942 WRITE_STREAMS_MIXED write_limit:0
- 496119.570406964 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.570415654 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.570416160 DEV_SLEEP_TIME dev:8 wake:000496119.616075023
- 496119.570417854 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.570517549 WAKE num_fds:1
- 496119.570548375 FILL_AUDIO dev:8 hw_level:2192
- 496119.570550235 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.570565405 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.570570125 DEV_STREAM_MIX written:1024 read:1024
- 496119.570570832 WRITE_STREAMS_MIXED write_limit:1024
- 496119.570571614 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.570572651 STREAM_SLEEP_TIME id:140000 wake:000496119.591409249
- 496119.570578309 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.570578660 DEV_SLEEP_TIME dev:8 wake:000496119.637572175
- 496119.570579662 SLEEP sleep:000000000.020837074 longest_wake:000158140
- 496119.591447839 WAKE num_fds:0
- 496119.591471083 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.591498381 FILL_AUDIO dev:8 hw_level:2208
- 496119.591502641 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.591503082 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.591504470 WRITE_STREAMS_MIXED write_limit:0
- 496119.591507331 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.591515575 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.591516077 DEV_SLEEP_TIME dev:8 wake:000496119.637508639
- 496119.591517911 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.591605508 WAKE num_fds:1
- 496119.591633272 FILL_AUDIO dev:8 hw_level:2208
- 496119.591634976 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.591649530 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.591655148 DEV_STREAM_MIX written:1024 read:1024
- 496119.591655869 WRITE_STREAMS_MIXED write_limit:1024
- 496119.591657373 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.591658806 STREAM_SLEEP_TIME id:140000 wake:000496119.612742582
- 496119.591665451 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.591665907 DEV_SLEEP_TIME dev:8 wake:000496119.658991447
- 496119.591667235 SLEEP sleep:000000000.021084468 longest_wake:000158140
- 496119.612826659 WAKE num_fds:0
- 496119.612848891 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.612873648 FILL_AUDIO dev:8 hw_level:2176
- 496119.612878048 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.612878489 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.612879697 WRITE_STREAMS_MIXED write_limit:0
- 496119.612882694 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.612890742 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.612891319 DEV_SLEEP_TIME dev:8 wake:000496119.658217229
- 496119.612893073 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.612975583 WAKE num_fds:1
- 496119.613003011 FILL_AUDIO dev:8 hw_level:2176
- 496119.613004364 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.613018011 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.613022115 DEV_STREAM_MIX written:1024 read:1024
- 496119.613022672 WRITE_STREAMS_MIXED write_limit:1024
- 496119.613023754 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.613024812 STREAM_SLEEP_TIME id:140000 wake:000496119.634075915
- 496119.613030515 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.613030896 DEV_SLEEP_TIME dev:8 wake:000496119.679690987
- 496119.613031868 SLEEP sleep:000000000.021051594 longest_wake:000158140
- 496119.634323952 WAKE num_fds:0
- 496119.634365252 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.634397427 FILL_AUDIO dev:8 hw_level:2192
- 496119.634401792 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.634402208 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.634403330 WRITE_STREAMS_MIXED write_limit:0
- 496119.634406733 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.634415082 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.634415644 DEV_SLEEP_TIME dev:8 wake:000496119.680074867
- 496119.634417673 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.634513685 WAKE num_fds:1
- 496119.634542587 FILL_AUDIO dev:8 hw_level:2192
- 496119.634544110 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.634559245 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.634563565 DEV_STREAM_MIX written:1024 read:1024
- 496119.634564222 WRITE_STREAMS_MIXED write_limit:1024
- 496119.634565304 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.634566527 STREAM_SLEEP_TIME id:140000 wake:000496119.655409248
- 496119.634572972 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.634573353 DEV_SLEEP_TIME dev:8 wake:000496119.701566016
- 496119.634574335 SLEEP sleep:000000000.020843232 longest_wake:000158140
- 496119.655663146 WAKE num_fds:0
- 496119.655686319 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.655718418 FILL_AUDIO dev:8 hw_level:2208
- 496119.655723791 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.655724302 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.655725710 WRITE_STREAMS_MIXED write_limit:0
- 496119.655728542 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.655736746 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.655737322 DEV_SLEEP_TIME dev:8 wake:000496119.701729780
- 496119.655739201 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.655836651 WAKE num_fds:1
- 496119.655867467 FILL_AUDIO dev:8 hw_level:2160
- 496119.655869332 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.655883900 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.655888255 DEV_STREAM_MIX written:1024 read:1024
- 496119.655888807 WRITE_STREAMS_MIXED write_limit:1024
- 496119.655890465 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:0
- 496119.655891047 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.655891503 WRITE_STREAMS_MIXED write_limit:0
- 496119.655892059 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496119.655893267 STREAM_SLEEP_TIME id:140000 wake:000496119.676742581
- 496119.655899216 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496119.655899561 DEV_SLEEP_TIME dev:8 wake:000496119.722225999
- 496119.655900579 SLEEP sleep:000000000.020849915 longest_wake:000158140
- 496119.676782360 WAKE num_fds:0
- 496119.676802491 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496119.676828715 FILL_AUDIO dev:8 hw_level:2176
- 496119.676831930 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.676832205 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.676832933 WRITE_STREAMS_MIXED write_limit:0
- 496119.676835095 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.676841542 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.676841833 DEV_SLEEP_TIME dev:8 wake:000496119.722169273
- 496119.676843191 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.676901138 WAKE num_fds:1
- 496119.676923101 FILL_AUDIO dev:8 hw_level:2176
- 496119.676924667 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.676927011 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.676930681 DEV_STREAM_MIX written:1024 read:1024
- 496119.676931111 WRITE_STREAMS_MIXED write_limit:1024
- 496119.676932162 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.676933078 STREAM_SLEEP_TIME id:140000 wake:000496119.698075914
- 496119.676939028 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.676939378 DEV_SLEEP_TIME dev:8 wake:000496119.743599341
- 496119.676940404 SLEEP sleep:000000000.021143239 longest_wake:000158140
- 496119.698136425 WAKE num_fds:0
- 496119.698158456 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.698186947 FILL_AUDIO dev:8 hw_level:2192
- 496119.698191006 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.698191492 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.698192615 WRITE_STREAMS_MIXED write_limit:0
- 496119.698195446 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.698203269 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.698203800 DEV_SLEEP_TIME dev:8 wake:000496119.743863350
- 496119.698205620 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.698283585 WAKE num_fds:1
- 496119.698308688 FILL_AUDIO dev:8 hw_level:2192
- 496119.698310517 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.698312035 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.698315914 DEV_STREAM_MIX written:1024 read:1024
- 496119.698316430 WRITE_STREAMS_MIXED write_limit:1024
- 496119.698317528 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.698318540 STREAM_SLEEP_TIME id:140000 wake:000496119.719409247
- 496119.698324143 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.698324524 DEV_SLEEP_TIME dev:8 wake:000496119.765318074
- 496119.698325461 SLEEP sleep:000000000.021091173 longest_wake:000158140
- 496119.719658229 WAKE num_fds:0
- 496119.719682220 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.719712981 FILL_AUDIO dev:8 hw_level:2208
- 496119.719717286 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.719717742 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.719718839 WRITE_STREAMS_MIXED write_limit:0
- 496119.719721741 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.719730717 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.719731308 DEV_SLEEP_TIME dev:8 wake:000496119.765723665
- 496119.719733202 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.719836902 WAKE num_fds:1
- 496119.719868354 FILL_AUDIO dev:8 hw_level:2160
- 496119.719869998 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.719871687 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.719876724 DEV_STREAM_MIX written:1024 read:1024
- 496119.719877250 WRITE_STREAMS_MIXED write_limit:1024
- 496119.719878513 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496119.719880016 STREAM_SLEEP_TIME id:140000 wake:000496119.740742580
- 496119.719885724 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496119.719886100 DEV_SLEEP_TIME dev:8 wake:000496119.786212602
- 496119.719887067 SLEEP sleep:000000000.020863311 longest_wake:000158140
- 496119.740777485 WAKE num_fds:0
- 496119.740799787 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496119.740819222 FILL_AUDIO dev:8 hw_level:2224
- 496119.740824434 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.740824920 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.740826088 WRITE_STREAMS_MIXED write_limit:0
- 496119.740828989 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496119.740837805 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.740838286 DEV_SLEEP_TIME dev:8 wake:000496119.786163525
- 496119.740840075 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.740937109 WAKE num_fds:1
- 496119.740963259 FILL_AUDIO dev:8 hw_level:2176
- 496119.740965564 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.740968697 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.740973979 DEV_STREAM_MIX written:1024 read:1024
- 496119.740974670 WRITE_STREAMS_MIXED write_limit:1024
- 496119.740975984 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.740977372 STREAM_SLEEP_TIME id:140000 wake:000496119.762075913
- 496119.740983656 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.740984132 DEV_SLEEP_TIME dev:8 wake:000496119.807643386
- 496119.740985510 SLEEP sleep:000000000.021099193 longest_wake:000158140
- 496119.762184771 WAKE num_fds:0
- 496119.762207604 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.762239753 FILL_AUDIO dev:8 hw_level:2192
- 496119.762244123 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.762245146 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.762246414 WRITE_STREAMS_MIXED write_limit:0
- 496119.762249320 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.762257569 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.762258131 DEV_SLEEP_TIME dev:8 wake:000496119.807917415
- 496119.762261579 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.762376087 WAKE num_fds:1
- 496119.762404828 FILL_AUDIO dev:8 hw_level:2192
- 496119.762407088 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.762408577 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.762412676 DEV_STREAM_MIX written:1024 read:1024
- 496119.762413358 WRITE_STREAMS_MIXED write_limit:1024
- 496119.762414671 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.762416124 STREAM_SLEEP_TIME id:140000 wake:000496119.783409246
- 496119.762422289 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.762422689 DEV_SLEEP_TIME dev:8 wake:000496119.829415488
- 496119.762423667 SLEEP sleep:000000000.020993758 longest_wake:000158140
- 496119.783498916 WAKE num_fds:0
- 496119.783520847 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.783546040 FILL_AUDIO dev:8 hw_level:2208
- 496119.783550180 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.783550656 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.783551718 WRITE_STREAMS_MIXED write_limit:0
- 496119.783554464 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.783562839 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.783563390 DEV_SLEEP_TIME dev:8 wake:000496119.829555798
- 496119.783565164 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.783648807 WAKE num_fds:1
- 496119.783676742 FILL_AUDIO dev:8 hw_level:2208
- 496119.783678280 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.783680801 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.783684720 DEV_STREAM_MIX written:1024 read:1024
- 496119.783685236 WRITE_STREAMS_MIXED write_limit:1024
- 496119.783686750 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.783687847 STREAM_SLEEP_TIME id:140000 wake:000496119.804742579
- 496119.783694097 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.783694618 DEV_SLEEP_TIME dev:8 wake:000496119.851020649
- 496119.783695881 SLEEP sleep:000000000.021055263 longest_wake:000158140
- 496119.804846154 WAKE num_fds:0
- 496119.804869563 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.804900975 FILL_AUDIO dev:8 hw_level:2176
- 496119.804905260 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.804906282 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.804907335 WRITE_STREAMS_MIXED write_limit:0
- 496119.804911094 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.804919623 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.804920190 DEV_SLEEP_TIME dev:8 wake:000496119.850245890
- 496119.804922224 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.805017163 WAKE num_fds:1
- 496119.805048155 FILL_AUDIO dev:8 hw_level:2176
- 496119.805049984 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.805051578 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.805055662 DEV_STREAM_MIX written:1024 read:1024
- 496119.805056218 WRITE_STREAMS_MIXED write_limit:1024
- 496119.805057331 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.805058439 STREAM_SLEEP_TIME id:140000 wake:000496119.826075912
- 496119.805064147 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.805064523 DEV_SLEEP_TIME dev:8 wake:000496119.871724664
- 496119.805065520 SLEEP sleep:000000000.021017914 longest_wake:000158140
- 496119.826181499 WAKE num_fds:0
- 496119.826204557 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.826235859 FILL_AUDIO dev:8 hw_level:2192
- 496119.826240500 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.826240931 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.826242559 WRITE_STREAMS_MIXED write_limit:0
- 496119.826245521 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.826253670 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.826254236 DEV_SLEEP_TIME dev:8 wake:000496119.871913500
- 496119.826256056 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.826373791 WAKE num_fds:1
- 496119.826402197 FILL_AUDIO dev:8 hw_level:2192
- 496119.826404943 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.826406793 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.826410982 DEV_STREAM_MIX written:1024 read:1024
- 496119.826411508 WRITE_STREAMS_MIXED write_limit:1024
- 496119.826412541 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.826413729 STREAM_SLEEP_TIME id:140000 wake:000496119.847409245
- 496119.826419271 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.826419938 DEV_SLEEP_TIME dev:8 wake:000496119.893413262
- 496119.826421141 SLEEP sleep:000000000.020995983 longest_wake:000158140
- 496119.847573032 WAKE num_fds:0
- 496119.847597188 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.847631537 FILL_AUDIO dev:8 hw_level:2208
- 496119.847636143 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.847636594 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.847638057 WRITE_STREAMS_MIXED write_limit:0
- 496119.847642778 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.847652751 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.847653332 DEV_SLEEP_TIME dev:8 wake:000496119.893644703
- 496119.847655563 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.847751424 WAKE num_fds:1
- 496119.847777820 FILL_AUDIO dev:8 hw_level:2208
- 496119.847779419 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.847780937 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.847786791 DEV_STREAM_MIX written:1024 read:1024
- 496119.847787337 WRITE_STREAMS_MIXED write_limit:1024
- 496119.847788499 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.847789517 STREAM_SLEEP_TIME id:140000 wake:000496119.868742578
- 496119.847794999 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.847795365 DEV_SLEEP_TIME dev:8 wake:000496119.915122379
- 496119.847796523 SLEEP sleep:000000000.020953532 longest_wake:000158140
- 496119.868841929 WAKE num_fds:0
- 496119.868866084 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.868897878 FILL_AUDIO dev:8 hw_level:2176
- 496119.868902263 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.868903210 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.868904428 WRITE_STREAMS_MIXED write_limit:0
- 496119.868907149 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.868915248 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.868915794 DEV_SLEEP_TIME dev:8 wake:000496119.914241845
- 496119.868917784 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.869015113 WAKE num_fds:1
- 496119.869048987 FILL_AUDIO dev:8 hw_level:2176
- 496119.869050751 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.869053281 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.869058158 DEV_STREAM_MIX written:1024 read:1024
- 496119.869058894 WRITE_STREAMS_MIXED write_limit:1024
- 496119.869059566 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.869060543 STREAM_SLEEP_TIME id:140000 wake:000496119.890075911
- 496119.869066547 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.869066923 DEV_SLEEP_TIME dev:8 wake:000496119.935726768
- 496119.869068086 SLEEP sleep:000000000.021015809 longest_wake:000158140
- 496119.890110720 WAKE num_fds:0
- 496119.890133212 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.890157759 FILL_AUDIO dev:8 hw_level:2192
- 496119.890162880 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.890163321 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.890164504 WRITE_STREAMS_MIXED write_limit:0
- 496119.890167491 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.890175499 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.890176021 DEV_SLEEP_TIME dev:8 wake:000496119.935835435
- 496119.890177800 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.890260912 WAKE num_fds:1
- 496119.890286265 FILL_AUDIO dev:8 hw_level:2192
- 496119.890288195 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.890290149 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.890295557 DEV_STREAM_MIX written:1024 read:1024
- 496119.890296268 WRITE_STREAMS_MIXED write_limit:1024
- 496119.890297671 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.890298914 STREAM_SLEEP_TIME id:140000 wake:000496119.911409244
- 496119.890305374 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.890305805 DEV_SLEEP_TIME dev:8 wake:000496119.957298358
- 496119.890307223 SLEEP sleep:000000000.021110886 longest_wake:000158140
- 496119.911457981 WAKE num_fds:0
- 496119.911482252 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.911511630 FILL_AUDIO dev:8 hw_level:2208
- 496119.911516807 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.911517404 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.911518641 WRITE_STREAMS_MIXED write_limit:0
- 496119.911521668 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.911529396 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.911529912 DEV_SLEEP_TIME dev:8 wake:000496119.957522851
- 496119.911531636 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.911612914 WAKE num_fds:1
- 496119.911641044 FILL_AUDIO dev:8 hw_level:2208
- 496119.911643039 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.911645043 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.911652420 DEV_STREAM_MIX written:1024 read:1024
- 496119.911653147 WRITE_STREAMS_MIXED write_limit:1024
- 496119.911654886 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.911656239 STREAM_SLEEP_TIME id:140000 wake:000496119.932742577
- 496119.911663180 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.911663601 DEV_SLEEP_TIME dev:8 wake:000496119.978989021
- 496119.911665014 SLEEP sleep:000000000.021086889 longest_wake:000158140
- 496119.932781594 WAKE num_fds:0
- 496119.932810225 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496119.932837659 FILL_AUDIO dev:8 hw_level:2176
- 496119.932842344 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.932842941 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.932844214 WRITE_STREAMS_MIXED write_limit:0
- 496119.932847311 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.932856257 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.932856723 DEV_SLEEP_TIME dev:8 wake:000496119.978182037
- 496119.932858742 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.932950314 WAKE num_fds:1
- 496119.932981345 FILL_AUDIO dev:8 hw_level:2176
- 496119.932983395 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.932985836 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.932990792 DEV_STREAM_MIX written:1024 read:1024
- 496119.932991338 WRITE_STREAMS_MIXED write_limit:1024
- 496119.932992311 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.932993358 STREAM_SLEEP_TIME id:140000 wake:000496119.954075910
- 496119.932999216 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.932999838 DEV_SLEEP_TIME dev:8 wake:000496119.999659568
- 496119.933001116 SLEEP sleep:000000000.021083008 longest_wake:000158140
- 496119.954146565 WAKE num_fds:0
- 496119.954162536 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496119.954180693 FILL_AUDIO dev:8 hw_level:2192
- 496119.954183341 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.954183605 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.954184349 WRITE_STREAMS_MIXED write_limit:0
- 496119.954186514 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496119.954192771 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496119.954193049 DEV_SLEEP_TIME dev:8 wake:000496119.999853959
- 496119.954194267 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496119.954240476 WAKE num_fds:1
- 496119.954258950 FILL_AUDIO dev:8 hw_level:2192
- 496119.954259846 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.954260998 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.954266147 DEV_STREAM_MIX written:1024 read:1024
- 496119.954266591 WRITE_STREAMS_MIXED write_limit:1024
- 496119.954267353 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496119.954268157 STREAM_SLEEP_TIME id:140000 wake:000496119.975409243
- 496119.954273532 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496119.954273850 DEV_SLEEP_TIME dev:8 wake:000496120.021267834
- 496119.954274529 SLEEP sleep:000000000.021141409 longest_wake:000158140
- 496119.975463624 WAKE num_fds:0
- 496119.975512667 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496119.975552860 FILL_AUDIO dev:8 hw_level:2208
- 496119.975562763 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.975563259 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.975564547 WRITE_STREAMS_MIXED write_limit:0
- 496119.975572255 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496119.975582799 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496119.975583275 DEV_SLEEP_TIME dev:8 wake:000496120.021574064
- 496119.975585826 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496119.975725950 WAKE num_fds:1
- 496119.975762304 FILL_AUDIO dev:8 hw_level:2208
- 496119.975765351 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.975769365 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.975777188 DEV_STREAM_MIX written:1024 read:1024
- 496119.975777829 WRITE_STREAMS_MIXED write_limit:1024
- 496119.975779543 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496119.975781348 STREAM_SLEEP_TIME id:140000 wake:000496119.996742576
- 496119.975787873 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496119.975788269 DEV_SLEEP_TIME dev:8 wake:000496120.043114219
- 496119.975789411 SLEEP sleep:000000000.020961690 longest_wake:000158140
- 496119.996809488 WAKE num_fds:0
- 496119.996830326 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496119.996856422 FILL_AUDIO dev:8 hw_level:2176
- 496119.996860426 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496119.996860867 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496119.996861919 WRITE_STREAMS_MIXED write_limit:0
- 496119.996864570 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496119.996872348 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496119.996872845 DEV_SLEEP_TIME dev:8 wake:000496120.042199096
- 496119.996874814 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496119.996972104 WAKE num_fds:1
- 496119.996998314 FILL_AUDIO dev:8 hw_level:2176
- 496119.996999908 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496119.997001361 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496119.997005220 DEV_STREAM_MIX written:1024 read:1024
- 496119.997005761 WRITE_STREAMS_MIXED write_limit:1024
- 496119.997006899 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496119.997007997 STREAM_SLEEP_TIME id:140000 wake:000496120.018075909
- 496119.997013484 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496119.997013880 DEV_SLEEP_TIME dev:8 wake:000496120.063674186
- 496119.997014872 SLEEP sleep:000000000.021068389 longest_wake:000158140
- 496120.018176962 WAKE num_fds:0
- 496120.018200617 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.018232290 FILL_AUDIO dev:8 hw_level:2192
- 496120.018237242 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.018237748 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.018238900 WRITE_STREAMS_MIXED write_limit:0
- 496120.018243346 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.018251489 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.018252036 DEV_SLEEP_TIME dev:8 wake:000496120.063911239
- 496120.018254025 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.018371866 WAKE num_fds:1
- 496120.018402292 FILL_AUDIO dev:8 hw_level:2192
- 496120.018404587 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.018406206 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.018410290 DEV_STREAM_MIX written:1024 read:1024
- 496120.018410856 WRITE_STREAMS_MIXED write_limit:1024
- 496120.018412074 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.018413157 STREAM_SLEEP_TIME id:140000 wake:000496120.039409242
- 496120.018419020 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.018419371 DEV_SLEEP_TIME dev:8 wake:000496120.085412691
- 496120.018420468 SLEEP sleep:000000000.020996551 longest_wake:000158140
- 496120.039592015 WAKE num_fds:0
- 496120.039614197 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.039645043 FILL_AUDIO dev:8 hw_level:2208
- 496120.039649328 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.039649764 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.039651312 WRITE_STREAMS_MIXED write_limit:0
- 496120.039654023 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.039662277 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.039662864 DEV_SLEEP_TIME dev:8 wake:000496120.085655417
- 496120.039664573 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.039757006 WAKE num_fds:1
- 496120.039786254 FILL_AUDIO dev:8 hw_level:2208
- 496120.039788358 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.039789902 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.039794478 DEV_STREAM_MIX written:1024 read:1024
- 496120.039795144 WRITE_STREAMS_MIXED write_limit:1024
- 496120.039796482 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.039797560 STREAM_SLEEP_TIME id:140000 wake:000496120.060742575
- 496120.039803468 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.039803824 DEV_SLEEP_TIME dev:8 wake:000496120.107130392
- 496120.039804832 SLEEP sleep:000000000.020945516 longest_wake:000158140
- 496120.060797771 WAKE num_fds:0
- 496120.060820273 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496120.060854302 FILL_AUDIO dev:8 hw_level:2176
- 496120.060859644 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.060860160 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.060861328 WRITE_STREAMS_MIXED write_limit:0
- 496120.060865207 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.060874082 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.060874618 DEV_SLEEP_TIME dev:8 wake:000496120.106199748
- 496120.060876327 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.060978919 WAKE num_fds:1
- 496120.061008252 FILL_AUDIO dev:8 hw_level:2176
- 496120.061010392 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.061012447 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.061017007 DEV_STREAM_MIX written:1024 read:1024
- 496120.061017714 WRITE_STREAMS_MIXED write_limit:1024
- 496120.061018736 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.061019864 STREAM_SLEEP_TIME id:140000 wake:000496120.082075908
- 496120.061025281 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.061025662 DEV_SLEEP_TIME dev:8 wake:000496120.127686029
- 496120.061026895 SLEEP sleep:000000000.021056545 longest_wake:000158140
- 496120.082178195 WAKE num_fds:0
- 496120.082200907 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.082232125 FILL_AUDIO dev:8 hw_level:2192
- 496120.082237612 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.082238705 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.082240629 WRITE_STREAMS_MIXED write_limit:0
- 496120.082243696 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.082252522 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.082253519 DEV_SLEEP_TIME dev:8 wake:000496120.127911745
- 496120.082255629 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.082367060 WAKE num_fds:1
- 496120.082395866 FILL_AUDIO dev:8 hw_level:2192
- 496120.082397595 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.082399144 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.082405188 DEV_STREAM_MIX written:1024 read:1024
- 496120.082405950 WRITE_STREAMS_MIXED write_limit:1024
- 496120.082407373 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.082408405 STREAM_SLEEP_TIME id:140000 wake:000496120.103409241
- 496120.082413963 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.082414670 DEV_SLEEP_TIME dev:8 wake:000496120.149407924
- 496120.082415858 SLEEP sleep:000000000.021001317 longest_wake:000158140
- 496120.103453866 WAKE num_fds:0
- 496120.103476263 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.103506513 FILL_AUDIO dev:8 hw_level:2208
- 496120.103511449 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.103512000 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.103513504 WRITE_STREAMS_MIXED write_limit:0
- 496120.103516381 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.103524870 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.103525436 DEV_SLEEP_TIME dev:8 wake:000496120.149517653
- 496120.103527722 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.103621638 WAKE num_fds:1
- 496120.103650109 FILL_AUDIO dev:8 hw_level:2208
- 496120.103651953 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.103653607 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.103658398 DEV_STREAM_MIX written:1024 read:1024
- 496120.103658960 WRITE_STREAMS_MIXED write_limit:1024
- 496120.103659942 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.103660949 STREAM_SLEEP_TIME id:140000 wake:000496120.124742574
- 496120.103666838 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.103667234 DEV_SLEEP_TIME dev:8 wake:000496120.170993811
- 496120.103668261 SLEEP sleep:000000000.021082096 longest_wake:000158140
- 496120.124785237 WAKE num_fds:0
- 496120.124806356 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496120.124831689 FILL_AUDIO dev:8 hw_level:2176
- 496120.124835618 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.124836190 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.124837197 WRITE_STREAMS_MIXED write_limit:0
- 496120.124840109 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.124848789 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.124849265 DEV_SLEEP_TIME dev:8 wake:000496120.170174865
- 496120.124851064 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.124937794 WAKE num_fds:1
- 496120.124963223 FILL_AUDIO dev:8 hw_level:2176
- 496120.124964751 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.124966350 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.124970339 DEV_STREAM_MIX written:1024 read:1024
- 496120.124970971 WRITE_STREAMS_MIXED write_limit:1024
- 496120.124972018 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.124973111 STREAM_SLEEP_TIME id:140000 wake:000496120.146075907
- 496120.124978849 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.124979235 DEV_SLEEP_TIME dev:8 wake:000496120.191639361
- 496120.124980252 SLEEP sleep:000000000.021103212 longest_wake:000158140
- 496120.146169219 WAKE num_fds:0
- 496120.146191606 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.146222547 FILL_AUDIO dev:8 hw_level:2192
- 496120.146228346 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.146228812 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.146230265 WRITE_STREAMS_MIXED write_limit:0
- 496120.146233297 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.146243125 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.146243676 DEV_SLEEP_TIME dev:8 wake:000496120.191901662
- 496120.146245530 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.146362163 WAKE num_fds:1
- 496120.146392519 FILL_AUDIO dev:8 hw_level:2192
- 496120.146394378 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.146396062 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.146400091 DEV_STREAM_MIX written:1024 read:1024
- 496120.146400963 WRITE_STREAMS_MIXED write_limit:1024
- 496120.146402020 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.146403308 STREAM_SLEEP_TIME id:140000 wake:000496120.167409240
- 496120.146409392 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.146409743 DEV_SLEEP_TIME dev:8 wake:000496120.213402737
- 496120.146410746 SLEEP sleep:000000000.021006503 longest_wake:000158140
- 496120.167670100 WAKE num_fds:0
- 496120.167693524 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.167724260 FILL_AUDIO dev:8 hw_level:2208
- 496120.167728821 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.167729272 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.167730389 WRITE_STREAMS_MIXED write_limit:0
- 496120.167733466 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.167742041 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.167742547 DEV_SLEEP_TIME dev:8 wake:000496120.213734845
- 496120.167744286 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.167843866 WAKE num_fds:1
- 496120.167874216 FILL_AUDIO dev:8 hw_level:2160
- 496120.167876241 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.167878035 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.167882305 DEV_STREAM_MIX written:1024 read:1024
- 496120.167882866 WRITE_STREAMS_MIXED write_limit:1024
- 496120.167883713 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496120.167884645 STREAM_SLEEP_TIME id:140000 wake:000496120.188742573
- 496120.167890554 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496120.167890915 DEV_SLEEP_TIME dev:8 wake:000496120.234217522
- 496120.167892268 SLEEP sleep:000000000.020858384 longest_wake:000158140
- 496120.188990921 WAKE num_fds:0
- 496120.189014721 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.189046640 FILL_AUDIO dev:8 hw_level:2176
- 496120.189050845 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.189051361 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.189052930 WRITE_STREAMS_MIXED write_limit:0
- 496120.189055856 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.189064396 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.189064967 DEV_SLEEP_TIME dev:8 wake:000496120.234390863
- 496120.189067603 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.189162332 WAKE num_fds:1
- 496120.189191139 FILL_AUDIO dev:8 hw_level:2176
- 496120.189193003 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.189194577 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.189199142 DEV_STREAM_MIX written:1024 read:1024
- 496120.189199708 WRITE_STREAMS_MIXED write_limit:1024
- 496120.189200570 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.189201663 STREAM_SLEEP_TIME id:140000 wake:000496120.210075906
- 496120.189207286 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.189207657 DEV_SLEEP_TIME dev:8 wake:000496120.255867863
- 496120.189208654 SLEEP sleep:000000000.020874709 longest_wake:000158140
- 496120.210165596 WAKE num_fds:0
- 496120.210210895 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.210251669 FILL_AUDIO dev:8 hw_level:2192
- 496120.210260850 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.210261337 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.210262830 WRITE_STREAMS_MIXED write_limit:0
- 496120.210268693 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.210279498 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.210280035 DEV_SLEEP_TIME dev:8 wake:000496120.255938211
- 496120.210282661 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.210445466 WAKE num_fds:1
- 496120.210479965 FILL_AUDIO dev:8 hw_level:2192
- 496120.210481915 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.210487217 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.210495035 DEV_STREAM_MIX written:1024 read:1024
- 496120.210495737 WRITE_STREAMS_MIXED write_limit:1024
- 496120.210496979 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.210497957 STREAM_SLEEP_TIME id:140000 wake:000496120.231409239
- 496120.210503740 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.210504116 DEV_SLEEP_TIME dev:8 wake:000496120.277497491
- 496120.210505173 SLEEP sleep:000000000.020911748 longest_wake:000158140
- 496120.231663695 WAKE num_fds:0
- 496120.231687425 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.231718522 FILL_AUDIO dev:8 hw_level:2208
- 496120.231723092 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.231723518 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.231725257 WRITE_STREAMS_MIXED write_limit:0
- 496120.231728700 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.231737390 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.231737977 DEV_SLEEP_TIME dev:8 wake:000496120.277729958
- 496120.231740066 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.231836699 WAKE num_fds:1
- 496120.231867290 FILL_AUDIO dev:8 hw_level:2160
- 496120.231869004 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.231870808 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.231874722 DEV_STREAM_MIX written:1024 read:1024
- 496120.231875253 WRITE_STREAMS_MIXED write_limit:1024
- 496120.231876421 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496120.231877634 STREAM_SLEEP_TIME id:140000 wake:000496120.252742572
- 496120.231883943 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496120.231884314 DEV_SLEEP_TIME dev:8 wake:000496120.298210511
- 496120.231885317 SLEEP sleep:000000000.020865394 longest_wake:000158140
- 496120.252825725 WAKE num_fds:0
- 496120.252847370 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.252873480 FILL_AUDIO dev:8 hw_level:2176
- 496120.252877595 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.252878031 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.252879183 WRITE_STREAMS_MIXED write_limit:0
- 496120.252882060 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.252889973 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.252890449 DEV_SLEEP_TIME dev:8 wake:000496120.298216616
- 496120.252892264 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.252976333 WAKE num_fds:1
- 496120.253004262 FILL_AUDIO dev:8 hw_level:2176
- 496120.253005560 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.253007124 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.253011143 DEV_STREAM_MIX written:1024 read:1024
- 496120.253011674 WRITE_STREAMS_MIXED write_limit:1024
- 496120.253012526 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.253013624 STREAM_SLEEP_TIME id:140000 wake:000496120.274075905
- 496120.253019227 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.253019572 DEV_SLEEP_TIME dev:8 wake:000496120.319679829
- 496120.253020595 SLEEP sleep:000000000.021062742 longest_wake:000158140
- 496120.274106404 WAKE num_fds:0
- 496120.274128715 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.274152144 FILL_AUDIO dev:8 hw_level:2192
- 496120.274156384 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.274156855 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.274157943 WRITE_STREAMS_MIXED write_limit:0
- 496120.274161110 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.274169534 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.274170056 DEV_SLEEP_TIME dev:8 wake:000496120.319829134
- 496120.274171905 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.274253398 WAKE num_fds:1
- 496120.274278085 FILL_AUDIO dev:8 hw_level:2192
- 496120.274279458 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.274281037 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.274285166 DEV_STREAM_MIX written:1024 read:1024
- 496120.274285718 WRITE_STREAMS_MIXED write_limit:1024
- 496120.274286800 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.274287888 STREAM_SLEEP_TIME id:140000 wake:000496120.295409238
- 496120.274293445 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.274293796 DEV_SLEEP_TIME dev:8 wake:000496120.341287447
- 496120.274295009 SLEEP sleep:000000000.021121791 longest_wake:000158140
- 496120.295659600 WAKE num_fds:0
- 496120.295682664 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.295713329 FILL_AUDIO dev:8 hw_level:2208
- 496120.295717534 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.295718386 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.295720250 WRITE_STREAMS_MIXED write_limit:0
- 496120.295723067 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.295731967 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.295732504 DEV_SLEEP_TIME dev:8 wake:000496120.341724505
- 496120.295734333 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.295829954 WAKE num_fds:1
- 496120.295858961 FILL_AUDIO dev:8 hw_level:2160
- 496120.295860870 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.295862925 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.295867099 DEV_STREAM_MIX written:1024 read:1024
- 496120.295867606 WRITE_STREAMS_MIXED write_limit:1024
- 496120.295868347 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496120.295869871 STREAM_SLEEP_TIME id:140000 wake:000496120.316742571
- 496120.295876075 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496120.295876441 DEV_SLEEP_TIME dev:8 wake:000496120.362202743
- 496120.295877448 SLEEP sleep:000000000.020873161 longest_wake:000158140
- 496120.317001495 WAKE num_fds:0
- 496120.317024874 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.317055114 FILL_AUDIO dev:8 hw_level:2176
- 496120.317059414 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.317060487 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.317062541 WRITE_STREAMS_MIXED write_limit:0
- 496120.317065453 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.317073852 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.317074344 DEV_SLEEP_TIME dev:8 wake:000496120.362400199
- 496120.317076313 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.317171929 WAKE num_fds:1
- 496120.317202003 FILL_AUDIO dev:8 hw_level:2176
- 496120.317203762 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.317205486 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.317209596 DEV_STREAM_MIX written:1024 read:1024
- 496120.317210167 WRITE_STREAMS_MIXED write_limit:1024
- 496120.317211310 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.317212497 STREAM_SLEEP_TIME id:140000 wake:000496120.338075904
- 496120.317218276 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.317218647 DEV_SLEEP_TIME dev:8 wake:000496120.383878722
- 496120.317219604 SLEEP sleep:000000000.020863848 longest_wake:000158140
- 496120.338325157 WAKE num_fds:0
- 496120.338373825 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.338405919 FILL_AUDIO dev:8 hw_level:2192
- 496120.338411276 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.338411737 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.338413556 WRITE_STREAMS_MIXED write_limit:0
- 496120.338416749 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.338424973 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.338425564 DEV_SLEEP_TIME dev:8 wake:000496120.384084738
- 496120.338427378 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.338521641 WAKE num_fds:1
- 496120.338549681 FILL_AUDIO dev:8 hw_level:2192
- 496120.338551405 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.338552868 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.338558997 DEV_STREAM_MIX written:1024 read:1024
- 496120.338559533 WRITE_STREAMS_MIXED write_limit:1024
- 496120.338560415 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.338561518 STREAM_SLEEP_TIME id:140000 wake:000496120.359409237
- 496120.338567281 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.338567632 DEV_SLEEP_TIME dev:8 wake:000496120.405561052
- 496120.338568614 SLEEP sleep:000000000.020848185 longest_wake:000158140
- 496120.359662607 WAKE num_fds:0
- 496120.359686227 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.359718331 FILL_AUDIO dev:8 hw_level:2208
- 496120.359722616 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.359723513 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.359724700 WRITE_STREAMS_MIXED write_limit:0
- 496120.359727878 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.359736167 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.359736738 DEV_SLEEP_TIME dev:8 wake:000496120.405729211
- 496120.359738628 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.359837621 WAKE num_fds:1
- 496120.359869219 FILL_AUDIO dev:8 hw_level:2160
- 496120.359871189 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.359873679 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.359877814 DEV_STREAM_MIX written:1024 read:1024
- 496120.359878395 WRITE_STREAMS_MIXED write_limit:1024
- 496120.359879197 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496120.359880245 STREAM_SLEEP_TIME id:140000 wake:000496120.380742570
- 496120.359885867 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496120.359886213 DEV_SLEEP_TIME dev:8 wake:000496120.426213101
- 496120.359887266 SLEEP sleep:000000000.020862802 longest_wake:000158140
- 496120.380845520 WAKE num_fds:0
- 496120.380869776 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.380902542 FILL_AUDIO dev:8 hw_level:2176
- 496120.380906721 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.380907649 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.380909438 WRITE_STREAMS_MIXED write_limit:0
- 496120.380912520 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.380921636 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.380922177 DEV_SLEEP_TIME dev:8 wake:000496120.426247958
- 496120.380924212 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.381017252 WAKE num_fds:1
- 496120.381045913 FILL_AUDIO dev:8 hw_level:2176
- 496120.381048008 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.381049777 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.381053916 DEV_STREAM_MIX written:1024 read:1024
- 496120.381054462 WRITE_STREAMS_MIXED write_limit:1024
- 496120.381055660 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.381057169 STREAM_SLEEP_TIME id:140000 wake:000496120.402075903
- 496120.381063062 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.381063408 DEV_SLEEP_TIME dev:8 wake:000496120.447722903
- 496120.381064390 SLEEP sleep:000000000.021019666 longest_wake:000158140
- 496120.402140933 WAKE num_fds:0
- 496120.402162097 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.402189415 FILL_AUDIO dev:8 hw_level:2192
- 496120.402193519 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.402193985 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.402195153 WRITE_STREAMS_MIXED write_limit:0
- 496120.402198355 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.402206043 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.402206589 DEV_SLEEP_TIME dev:8 wake:000496120.447866189
- 496120.402208318 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.402282184 WAKE num_fds:1
- 496120.402306199 FILL_AUDIO dev:8 hw_level:2192
- 496120.402307868 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.402309497 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.402313747 DEV_STREAM_MIX written:1024 read:1024
- 496120.402314258 WRITE_STREAMS_MIXED write_limit:1024
- 496120.402315240 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.402316273 STREAM_SLEEP_TIME id:140000 wake:000496120.423409236
- 496120.402321866 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.402322251 DEV_SLEEP_TIME dev:8 wake:000496120.469315797
- 496120.402323179 SLEEP sleep:000000000.021093439 longest_wake:000158140
- 496120.423449244 WAKE num_fds:0
- 496120.423476422 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.423503059 FILL_AUDIO dev:8 hw_level:2208
- 496120.423507604 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.423508090 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.423509418 WRITE_STREAMS_MIXED write_limit:0
- 496120.423512510 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.423520454 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.423520975 DEV_SLEEP_TIME dev:8 wake:000496120.469513698
- 496120.423522774 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.423600017 WAKE num_fds:1
- 496120.423628152 FILL_AUDIO dev:8 hw_level:2208
- 496120.423630277 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.423632317 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.423639759 DEV_STREAM_MIX written:1024 read:1024
- 496120.423640521 WRITE_STREAMS_MIXED write_limit:1024
- 496120.423642105 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.423643353 STREAM_SLEEP_TIME id:140000 wake:000496120.444742569
- 496120.423650028 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.423650594 DEV_SLEEP_TIME dev:8 wake:000496120.490976119
- 496120.423651992 SLEEP sleep:000000000.021099783 longest_wake:000158140
- 496120.444785897 WAKE num_fds:0
- 496120.444805768 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496120.444826351 FILL_AUDIO dev:8 hw_level:2176
- 496120.444830240 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.444830731 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.444831889 WRITE_STREAMS_MIXED write_limit:0
- 496120.444835256 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.444842919 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.444843495 DEV_SLEEP_TIME dev:8 wake:000496120.490169752
- 496120.444845274 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.444910946 WAKE num_fds:1
- 496120.444933318 FILL_AUDIO dev:8 hw_level:2176
- 496120.444934841 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.444936269 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.444940083 DEV_STREAM_MIX written:1024 read:1024
- 496120.444940655 WRITE_STREAMS_MIXED write_limit:1024
- 496120.444941451 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.444942519 STREAM_SLEEP_TIME id:140000 wake:000496120.466075902
- 496120.444947921 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.444948317 DEV_SLEEP_TIME dev:8 wake:000496120.511608689
- 496120.444949335 SLEEP sleep:000000000.021133879 longest_wake:000158140
- 496120.466115369 WAKE num_fds:0
- 496120.466135761 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.466155045 FILL_AUDIO dev:8 hw_level:2192
- 496120.466159004 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.466159506 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.466160548 WRITE_STREAMS_MIXED write_limit:0
- 496120.466163319 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.466170927 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.466171518 DEV_SLEEP_TIME dev:8 wake:000496120.511831198
- 496120.466173272 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.466238388 WAKE num_fds:1
- 496120.466260313 FILL_AUDIO dev:8 hw_level:2192
- 496120.466261681 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.466263085 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.466268868 DEV_STREAM_MIX written:1024 read:1024
- 496120.466269444 WRITE_STREAMS_MIXED write_limit:1024
- 496120.466270301 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.466271249 STREAM_SLEEP_TIME id:140000 wake:000496120.487409235
- 496120.466276636 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.466276992 DEV_SLEEP_TIME dev:8 wake:000496120.533270767
- 496120.466278014 SLEEP sleep:000000000.021138468 longest_wake:000158140
- 496120.487490685 WAKE num_fds:0
- 496120.487512195 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.487536877 FILL_AUDIO dev:8 hw_level:2208
- 496120.487540956 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.487541387 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.487542424 WRITE_STREAMS_MIXED write_limit:0
- 496120.487545241 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.487553319 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.487553801 DEV_SLEEP_TIME dev:8 wake:000496120.533546479
- 496120.487555795 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.487637278 WAKE num_fds:1
- 496120.487664200 FILL_AUDIO dev:8 hw_level:2208
- 496120.487665549 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.487667388 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.487671317 DEV_STREAM_MIX written:1024 read:1024
- 496120.487671903 WRITE_STREAMS_MIXED write_limit:1024
- 496120.487672976 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.487673953 STREAM_SLEEP_TIME id:140000 wake:000496120.508742568
- 496120.487679601 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.487679967 DEV_SLEEP_TIME dev:8 wake:000496120.555006830
- 496120.487680884 SLEEP sleep:000000000.021069071 longest_wake:000158140
- 496120.508772677 WAKE num_fds:0
- 496120.508795374 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496120.508815400 FILL_AUDIO dev:8 hw_level:2224
- 496120.508819660 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.508820161 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.508821374 WRITE_STREAMS_MIXED write_limit:0
- 496120.508824196 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496120.508832600 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.508833091 DEV_SLEEP_TIME dev:8 wake:000496120.554158651
- 496120.508834880 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.508902311 WAKE num_fds:1
- 496120.508923881 FILL_AUDIO dev:8 hw_level:2176
- 496120.508925309 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.508926873 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.508931017 DEV_STREAM_MIX written:1024 read:1024
- 496120.508931624 WRITE_STREAMS_MIXED write_limit:1024
- 496120.508932751 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.508933844 STREAM_SLEEP_TIME id:140000 wake:000496120.530075901
- 496120.508939532 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.508939878 DEV_SLEEP_TIME dev:8 wake:000496120.575600019
- 496120.508940905 SLEEP sleep:000000000.021142548 longest_wake:000158140
- 496120.530106994 WAKE num_fds:0
- 496120.530126138 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.530149222 FILL_AUDIO dev:8 hw_level:2192
- 496120.530153271 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.530153772 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.530154915 WRITE_STREAMS_MIXED write_limit:0
- 496120.530157902 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.530166151 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.530166632 DEV_SLEEP_TIME dev:8 wake:000496120.575825851
- 496120.530168476 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.530263270 WAKE num_fds:1
- 496120.530287591 FILL_AUDIO dev:8 hw_level:2192
- 496120.530289390 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.530291224 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.530297243 DEV_STREAM_MIX written:1024 read:1024
- 496120.530298100 WRITE_STREAMS_MIXED write_limit:1024
- 496120.530299073 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.530300030 STREAM_SLEEP_TIME id:140000 wake:000496120.551409234
- 496120.530305537 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.530305923 DEV_SLEEP_TIME dev:8 wake:000496120.597299604
- 496120.530306931 SLEEP sleep:000000000.021109630 longest_wake:000158140
- 496120.551515216 WAKE num_fds:0
- 496120.551539643 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.551571982 FILL_AUDIO dev:8 hw_level:2208
- 496120.551576849 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.551577670 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.551578848 WRITE_STREAMS_MIXED write_limit:0
- 496120.551581605 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.551589884 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.551590535 DEV_SLEEP_TIME dev:8 wake:000496120.597582882
- 496120.551592309 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.551687780 WAKE num_fds:1
- 496120.551717463 FILL_AUDIO dev:8 hw_level:2208
- 496120.551719322 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.551720916 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.551725036 DEV_STREAM_MIX written:1024 read:1024
- 496120.551725582 WRITE_STREAMS_MIXED write_limit:1024
- 496120.551726554 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.551727752 STREAM_SLEEP_TIME id:140000 wake:000496120.572742567
- 496120.551733861 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.551734207 DEV_SLEEP_TIME dev:8 wake:000496120.619060629
- 496120.551735425 SLEEP sleep:000000000.021015271 longest_wake:000158140
- 496120.572824676 WAKE num_fds:0
- 496120.572845770 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.572870968 FILL_AUDIO dev:8 hw_level:2176
- 496120.572875679 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.572876100 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.572877102 WRITE_STREAMS_MIXED write_limit:0
- 496120.572880210 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.572888138 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.572888634 DEV_SLEEP_TIME dev:8 wake:000496120.618214821
- 496120.572890538 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.572971871 WAKE num_fds:1
- 496120.572998568 FILL_AUDIO dev:8 hw_level:2176
- 496120.573000197 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.573001775 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.573005724 DEV_STREAM_MIX written:1024 read:1024
- 496120.573006361 WRITE_STREAMS_MIXED write_limit:1024
- 496120.573007188 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.573008170 STREAM_SLEEP_TIME id:140000 wake:000496120.594075900
- 496120.573013723 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.573014129 DEV_SLEEP_TIME dev:8 wake:000496120.639674380
- 496120.573015131 SLEEP sleep:000000000.021068186 longest_wake:000158140
- 496120.594106428 WAKE num_fds:0
- 496120.594130167 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.594152995 FILL_AUDIO dev:8 hw_level:2192
- 496120.594157060 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.594157621 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.594158964 WRITE_STREAMS_MIXED write_limit:0
- 496120.594162472 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.594171398 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.594171974 DEV_SLEEP_TIME dev:8 wake:000496120.639830446
- 496120.594173888 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.594300360 WAKE num_fds:1
- 496120.594345318 FILL_AUDIO dev:8 hw_level:2192
- 496120.594349362 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.594351888 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.594357862 DEV_STREAM_MIX written:1024 read:1024
- 496120.594359015 WRITE_STREAMS_MIXED write_limit:1024
- 496120.594360694 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.594362272 STREAM_SLEEP_TIME id:140000 wake:000496120.615409233
- 496120.594372245 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.594372631 DEV_SLEEP_TIME dev:8 wake:000496120.661361646
- 496120.594373869 SLEEP sleep:000000000.021047587 longest_wake:000158140
- 496120.615497480 WAKE num_fds:0
- 496120.615518910 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.615544870 FILL_AUDIO dev:8 hw_level:2208
- 496120.615549009 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.615549485 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.615550703 WRITE_STREAMS_MIXED write_limit:0
- 496120.615553650 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.615561789 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.615562275 DEV_SLEEP_TIME dev:8 wake:000496120.661554928
- 496120.615564194 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.615648213 WAKE num_fds:1
- 496120.615675972 FILL_AUDIO dev:8 hw_level:2208
- 496120.615677651 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.615679205 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.615685173 DEV_STREAM_MIX written:1024 read:1024
- 496120.615685690 WRITE_STREAMS_MIXED write_limit:1024
- 496120.615686592 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.615687614 STREAM_SLEEP_TIME id:140000 wake:000496120.636742566
- 496120.615693242 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.615693638 DEV_SLEEP_TIME dev:8 wake:000496120.683020481
- 496120.615694630 SLEEP sleep:000000000.021055418 longest_wake:000158140
- 496120.636988830 WAKE num_fds:0
- 496120.637012740 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.637044844 FILL_AUDIO dev:8 hw_level:2176
- 496120.637049500 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.637050006 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.637051670 WRITE_STREAMS_MIXED write_limit:0
- 496120.637055198 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.637063793 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.637064369 DEV_SLEEP_TIME dev:8 wake:000496120.682389804
- 496120.637066249 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.637165513 WAKE num_fds:1
- 496120.637197221 FILL_AUDIO dev:8 hw_level:2176
- 496120.637199186 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.637200739 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.637204809 DEV_STREAM_MIX written:1024 read:1024
- 496120.637205505 WRITE_STREAMS_MIXED write_limit:1024
- 496120.637206292 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.637207460 STREAM_SLEEP_TIME id:140000 wake:000496120.658075899
- 496120.637213203 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.637213549 DEV_SLEEP_TIME dev:8 wake:000496120.703873655
- 496120.637214581 SLEEP sleep:000000000.020868910 longest_wake:000158140
- 496120.658107059 WAKE num_fds:0
- 496120.658131099 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.658156964 FILL_AUDIO dev:8 hw_level:2192
- 496120.658161169 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.658161655 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.658162793 WRITE_STREAMS_MIXED write_limit:0
- 496120.658165679 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.658173658 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.658174189 DEV_SLEEP_TIME dev:8 wake:000496120.703833628
- 496120.658176143 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.658282023 WAKE num_fds:1
- 496120.658308744 FILL_AUDIO dev:8 hw_level:2192
- 496120.658310418 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.658312052 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.658315991 DEV_STREAM_MIX written:1024 read:1024
- 496120.658316542 WRITE_STREAMS_MIXED write_limit:1024
- 496120.658317565 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.658318632 STREAM_SLEEP_TIME id:140000 wake:000496120.679409232
- 496120.658324140 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.658324521 DEV_SLEEP_TIME dev:8 wake:000496120.725318191
- 496120.658325598 SLEEP sleep:000000000.021091041 longest_wake:000158140
- 496120.679472577 WAKE num_fds:0
- 496120.679499710 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.679534876 FILL_AUDIO dev:8 hw_level:2208
- 496120.679539322 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.679539768 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.679540820 WRITE_STREAMS_MIXED write_limit:0
- 496120.679543962 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.679552066 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.679552552 DEV_SLEEP_TIME dev:8 wake:000496120.725545526
- 496120.679554717 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.679658206 WAKE num_fds:1
- 496120.679687063 FILL_AUDIO dev:8 hw_level:2208
- 496120.679689233 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.679691282 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.679696504 DEV_STREAM_MIX written:1024 read:1024
- 496120.679697211 WRITE_STREAMS_MIXED write_limit:1024
- 496120.679698694 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.679700002 STREAM_SLEEP_TIME id:140000 wake:000496120.700742565
- 496120.679706392 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.679706863 DEV_SLEEP_TIME dev:8 wake:000496120.747032699
- 496120.679708442 SLEEP sleep:000000000.021043199 longest_wake:000158140
- 496120.701001735 WAKE num_fds:0
- 496120.701028687 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.701068313 FILL_AUDIO dev:8 hw_level:2176
- 496120.701073981 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.701074483 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.701075831 WRITE_STREAMS_MIXED write_limit:0
- 496120.701078873 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.701087443 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.701088089 DEV_SLEEP_TIME dev:8 wake:000496120.746413599
- 496120.701089998 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.701178107 WAKE num_fds:1
- 496120.701210877 FILL_AUDIO dev:8 hw_level:2176
- 496120.701214907 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.701217107 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.701224354 DEV_STREAM_MIX written:1024 read:1024
- 496120.701225426 WRITE_STREAMS_MIXED write_limit:1024
- 496120.701226919 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.701228268 STREAM_SLEEP_TIME id:140000 wake:000496120.722075898
- 496120.701235750 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.701236226 DEV_SLEEP_TIME dev:8 wake:000496120.767894327
- 496120.701237489 SLEEP sleep:000000000.020848237 longest_wake:000158140
- 496120.722129751 WAKE num_fds:0
- 496120.722152443 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.722180463 FILL_AUDIO dev:8 hw_level:2192
- 496120.722184517 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.722185986 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.722187118 WRITE_STREAMS_MIXED write_limit:0
- 496120.722190125 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.722198114 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.722198590 DEV_SLEEP_TIME dev:8 wake:000496120.767858014
- 496120.722200319 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.722290758 WAKE num_fds:1
- 496120.722319033 FILL_AUDIO dev:8 hw_level:2192
- 496120.722320817 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.722322326 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.722343188 DEV_STREAM_MIX written:1024 read:1024
- 496120.722344035 WRITE_STREAMS_MIXED write_limit:1024
- 496120.722345638 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.722347122 STREAM_SLEEP_TIME id:140000 wake:000496120.743409231
- 496120.722354043 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.722354504 DEV_SLEEP_TIME dev:8 wake:000496120.789346455
- 496120.722355882 SLEEP sleep:000000000.021062776 longest_wake:000158140
- 496120.743467496 WAKE num_fds:0
- 496120.743516138 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.743566865 FILL_AUDIO dev:8 hw_level:2208
- 496120.743580211 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.743581248 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.743582621 WRITE_STREAMS_MIXED write_limit:0
- 496120.743591356 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.743609794 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.743611438 DEV_SLEEP_TIME dev:8 wake:000496120.789595295
- 496120.743614821 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.743749752 WAKE num_fds:1
- 496120.743794781 FILL_AUDIO dev:8 hw_level:2208
- 496120.743800940 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.743806643 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.743815474 DEV_STREAM_MIX written:1024 read:1024
- 496120.743816401 WRITE_STREAMS_MIXED write_limit:1024
- 496120.743820355 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.743821543 STREAM_SLEEP_TIME id:140000 wake:000496120.764742564
- 496120.743832989 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496120.743833335 DEV_SLEEP_TIME dev:8 wake:000496120.810154400
- 496120.743834934 SLEEP sleep:000000000.020921497 longest_wake:000158140
- 496120.764995124 WAKE num_fds:0
- 496120.765018142 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.765049405 FILL_AUDIO dev:8 hw_level:2176
- 496120.765054130 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.765054607 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.765055724 WRITE_STREAMS_MIXED write_limit:0
- 496120.765059077 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.765067501 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.765068063 DEV_SLEEP_TIME dev:8 wake:000496120.810393783
- 496120.765069787 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.765170805 WAKE num_fds:1
- 496120.765200934 FILL_AUDIO dev:8 hw_level:2176
- 496120.765203149 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.765205049 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.765209123 DEV_STREAM_MIX written:1024 read:1024
- 496120.765209710 WRITE_STREAMS_MIXED write_limit:1024
- 496120.765210597 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.765211584 STREAM_SLEEP_TIME id:140000 wake:000496120.786075897
- 496120.765217232 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.765217583 DEV_SLEEP_TIME dev:8 wake:000496120.831877784
- 496120.765218565 SLEEP sleep:000000000.020864779 longest_wake:000158140
- 496120.786359235 WAKE num_fds:0
- 496120.786386748 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.786424054 FILL_AUDIO dev:8 hw_level:2192
- 496120.786429051 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.786429712 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.786430840 WRITE_STREAMS_MIXED write_limit:0
- 496120.786434593 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.786442146 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.786442732 DEV_SLEEP_TIME dev:8 wake:000496120.832102517
- 496120.786444822 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.786626827 WAKE num_fds:1
- 496120.786663677 FILL_AUDIO dev:8 hw_level:2192
- 496120.786666764 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.786669656 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.786676146 DEV_STREAM_MIX written:1024 read:1024
- 496120.786676853 WRITE_STREAMS_MIXED write_limit:1024
- 496120.786678446 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.786679774 STREAM_SLEEP_TIME id:140000 wake:000496120.807409230
- 496120.786686410 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.786686836 DEV_SLEEP_TIME dev:8 wake:000496120.853679218
- 496120.786688139 SLEEP sleep:000000000.020730012 longest_wake:000158140
- 496120.807445429 WAKE num_fds:0
- 496120.807468548 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.807488058 FILL_AUDIO dev:8 hw_level:2208
- 496120.807491601 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.807491967 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.807492949 WRITE_STREAMS_MIXED write_limit:0
- 496120.807495610 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.807502712 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.807503133 DEV_SLEEP_TIME dev:8 wake:000496120.853496708
- 496120.807504536 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.807594052 WAKE num_fds:1
- 496120.807615998 FILL_AUDIO dev:8 hw_level:2208
- 496120.807617141 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.807618714 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.807623114 DEV_STREAM_MIX written:1024 read:1024
- 496120.807623711 WRITE_STREAMS_MIXED write_limit:1024
- 496120.807624498 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.807625550 STREAM_SLEEP_TIME id:140000 wake:000496120.828742563
- 496120.807631148 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.807631539 DEV_SLEEP_TIME dev:8 wake:000496120.874958417
- 496120.807632491 SLEEP sleep:000000000.021117479 longest_wake:000158140
- 496120.828792742 WAKE num_fds:0
- 496120.828820235 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496120.828856364 FILL_AUDIO dev:8 hw_level:2176
- 496120.828863094 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.828863861 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.828865430 WRITE_STREAMS_MIXED write_limit:0
- 496120.828869083 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.828879402 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.828880214 DEV_SLEEP_TIME dev:8 wake:000496120.874204110
- 496120.828883105 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.829016984 WAKE num_fds:1
- 496120.829054035 FILL_AUDIO dev:8 hw_level:2176
- 496120.829056892 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.829058781 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.829064614 DEV_STREAM_MIX written:1024 read:1024
- 496120.829065461 WRITE_STREAMS_MIXED write_limit:1024
- 496120.829067341 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.829069421 STREAM_SLEEP_TIME id:140000 wake:000496120.850075896
- 496120.829076051 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.829076938 DEV_SLEEP_TIME dev:8 wake:000496120.895735420
- 496120.829078632 SLEEP sleep:000000000.021007142 longest_wake:000158140
- 496120.850120456 WAKE num_fds:0
- 496120.850146552 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.850169236 FILL_AUDIO dev:8 hw_level:2192
- 496120.850174064 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.850174484 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.850175535 WRITE_STREAMS_MIXED write_limit:0
- 496120.850178863 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.850186829 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.850187290 DEV_SLEEP_TIME dev:8 wake:000496120.895846740
- 496120.850189190 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.850269175 WAKE num_fds:1
- 496120.850295709 FILL_AUDIO dev:8 hw_level:2192
- 496120.850297505 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.850299301 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.850306373 DEV_STREAM_MIX written:1024 read:1024
- 496120.850307146 WRITE_STREAMS_MIXED write_limit:1024
- 496120.850308429 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.850309942 STREAM_SLEEP_TIME id:140000 wake:000496120.871409229
- 496120.850316384 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.850316865 DEV_SLEEP_TIME dev:8 wake:000496120.917309275
- 496120.850318385 SLEEP sleep:000000000.021099954 longest_wake:000158140
- 496120.871515551 WAKE num_fds:0
- 496120.871539366 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.871569746 FILL_AUDIO dev:8 hw_level:2208
- 496120.871573680 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.871574046 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.871574918 WRITE_STREAMS_MIXED write_limit:0
- 496120.871578080 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.871584976 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.871585402 DEV_SLEEP_TIME dev:8 wake:000496120.917579043
- 496120.871586780 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.871750112 WAKE num_fds:1
- 496120.871778648 FILL_AUDIO dev:8 hw_level:2208
- 496120.871780162 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.871781846 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.871788481 DEV_STREAM_MIX written:1024 read:1024
- 496120.871789102 WRITE_STREAMS_MIXED write_limit:1024
- 496120.871790060 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.871791287 STREAM_SLEEP_TIME id:140000 wake:000496120.892742562
- 496120.871797371 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.871797833 DEV_SLEEP_TIME dev:8 wake:000496120.939124029
- 496120.871799045 SLEEP sleep:000000000.020951866 longest_wake:000158140
- 496120.892801211 WAKE num_fds:0
- 496120.892847132 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.892888528 FILL_AUDIO dev:8 hw_level:2176
- 496120.892896396 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.892897123 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.892898987 WRITE_STREAMS_MIXED write_limit:0
- 496120.892904364 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.892913505 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.892914112 DEV_SLEEP_TIME dev:8 wake:000496120.938239276
- 496120.892917434 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.893084380 WAKE num_fds:1
- 496120.893127394 FILL_AUDIO dev:8 hw_level:2176
- 496120.893129760 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.893131584 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.893139863 DEV_STREAM_MIX written:1024 read:1024
- 496120.893140660 WRITE_STREAMS_MIXED write_limit:1024
- 496120.893154903 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.893156266 STREAM_SLEEP_TIME id:140000 wake:000496120.914075895
- 496120.893162600 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.893163157 DEV_SLEEP_TIME dev:8 wake:000496120.959822335
- 496120.893164620 SLEEP sleep:000000000.020920226 longest_wake:000158140
- 496120.914118665 WAKE num_fds:0
- 496120.914145071 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.914177055 FILL_AUDIO dev:8 hw_level:2192
- 496120.914181194 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.914181555 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.914182592 WRITE_STREAMS_MIXED write_limit:0
- 496120.914185198 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.914192555 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.914192976 DEV_SLEEP_TIME dev:8 wake:000496120.959852962
- 496120.914194495 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.914342014 WAKE num_fds:1
- 496120.914374870 FILL_AUDIO dev:8 hw_level:2192
- 496120.914377005 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.914378849 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.914384623 DEV_STREAM_MIX written:1024 read:1024
- 496120.914385279 WRITE_STREAMS_MIXED write_limit:1024
- 496120.914386522 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.914387710 STREAM_SLEEP_TIME id:140000 wake:000496120.935409228
- 496120.914393338 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.914393764 DEV_SLEEP_TIME dev:8 wake:000496120.981387174
- 496120.914395007 SLEEP sleep:000000000.021022054 longest_wake:000158140
- 496120.935443284 WAKE num_fds:0
- 496120.935466292 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.935494723 FILL_AUDIO dev:8 hw_level:2208
- 496120.935498757 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.935499143 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.935500250 WRITE_STREAMS_MIXED write_limit:0
- 496120.935502811 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.935509858 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.935510274 DEV_SLEEP_TIME dev:8 wake:000496120.981503844
- 496120.935512088 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.935671401 WAKE num_fds:1
- 496120.935705795 FILL_AUDIO dev:8 hw_level:2208
- 496120.935708366 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.935709944 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.935715983 DEV_STREAM_MIX written:1024 read:1024
- 496120.935716700 WRITE_STREAMS_MIXED write_limit:1024
- 496120.935718204 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.935719502 STREAM_SLEEP_TIME id:140000 wake:000496120.956742561
- 496120.935725365 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.935725731 DEV_SLEEP_TIME dev:8 wake:000496121.003052283
- 496120.935726974 SLEEP sleep:000000000.021023611 longest_wake:000158140
- 496120.956811014 WAKE num_fds:0
- 496120.956833380 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496120.956857200 FILL_AUDIO dev:8 hw_level:2176
- 496120.956860568 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.956860934 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.956861791 WRITE_STREAMS_MIXED write_limit:0
- 496120.956864337 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496120.956871167 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496120.956871538 DEV_SLEEP_TIME dev:8 wake:000496121.002198642
- 496120.956872942 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496120.957023259 WAKE num_fds:1
- 496120.957050822 FILL_AUDIO dev:8 hw_level:2176
- 496120.957052085 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.957053584 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.957059472 DEV_STREAM_MIX written:1024 read:1024
- 496120.957060068 WRITE_STREAMS_MIXED write_limit:1024
- 496120.957060795 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496120.957061727 STREAM_SLEEP_TIME id:140000 wake:000496120.978075894
- 496120.957067446 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496120.957067826 DEV_SLEEP_TIME dev:8 wake:000496121.023727977
- 496120.957068839 SLEEP sleep:000000000.021014583 longest_wake:000158140
- 496120.978110225 WAKE num_fds:0
- 496120.978133193 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496120.978157349 FILL_AUDIO dev:8 hw_level:2192
- 496120.978161774 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.978162401 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.978163603 WRITE_STREAMS_MIXED write_limit:0
- 496120.978166410 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496120.978174498 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496120.978175055 DEV_SLEEP_TIME dev:8 wake:000496121.023834404
- 496120.978176864 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496120.978294115 WAKE num_fds:1
- 496120.978341573 FILL_AUDIO dev:8 hw_level:2192
- 496120.978344284 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.978345853 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.978350043 DEV_STREAM_MIX written:1024 read:1024
- 496120.978350724 WRITE_STREAMS_MIXED write_limit:1024
- 496120.978352358 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496120.978353656 STREAM_SLEEP_TIME id:140000 wake:000496120.999409227
- 496120.978359555 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496120.978359931 DEV_SLEEP_TIME dev:8 wake:000496121.045353110
- 496120.978361198 SLEEP sleep:000000000.021056117 longest_wake:000158140
- 496120.999438377 WAKE num_fds:0
- 496120.999457772 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496120.999481026 FILL_AUDIO dev:8 hw_level:2208
- 496120.999484323 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496120.999484689 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496120.999485541 WRITE_STREAMS_MIXED write_limit:0
- 496120.999487892 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496120.999494517 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496120.999494883 DEV_SLEEP_TIME dev:8 wake:000496121.045488844
- 496120.999496361 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496120.999657453 WAKE num_fds:1
- 496120.999688670 FILL_AUDIO dev:8 hw_level:2208
- 496120.999691136 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496120.999692664 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496120.999698443 DEV_STREAM_MIX written:1024 read:1024
- 496120.999699154 WRITE_STREAMS_MIXED write_limit:1024
- 496120.999700618 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496120.999701906 STREAM_SLEEP_TIME id:140000 wake:000496121.020742560
- 496120.999707408 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496120.999707779 DEV_SLEEP_TIME dev:8 wake:000496121.067034697
- 496120.999709032 SLEEP sleep:000000000.021041196 longest_wake:000158140
- 496121.020803596 WAKE num_fds:0
- 496121.020825632 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.020845974 FILL_AUDIO dev:8 hw_level:2176
- 496121.020849552 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.020849963 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.020850860 WRITE_STREAMS_MIXED write_limit:0
- 496121.020853421 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.020860498 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.020860919 DEV_SLEEP_TIME dev:8 wake:000496121.066187902
- 496121.020862302 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.021012834 WAKE num_fds:1
- 496121.021038699 FILL_AUDIO dev:8 hw_level:2176
- 496121.021040107 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.021041651 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.021047835 DEV_STREAM_MIX written:1024 read:1024
- 496121.021048461 WRITE_STREAMS_MIXED write_limit:1024
- 496121.021049830 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:0
- 496121.021050226 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.021050727 WRITE_STREAMS_MIXED write_limit:0
- 496121.021051388 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.021052396 STREAM_SLEEP_TIME id:140000 wake:000496121.042075893
- 496121.021057968 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.021058349 DEV_SLEEP_TIME dev:8 wake:000496121.087718621
- 496121.021059432 SLEEP sleep:000000000.021023938 longest_wake:000158140
- 496121.042115492 WAKE num_fds:0
- 496121.042141532 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.042168459 FILL_AUDIO dev:8 hw_level:2192
- 496121.042173215 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.042173726 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.042174779 WRITE_STREAMS_MIXED write_limit:0
- 496121.042177791 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.042186050 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.042186571 DEV_SLEEP_TIME dev:8 wake:000496121.087845660
- 496121.042188430 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.042299602 WAKE num_fds:1
- 496121.042374133 FILL_AUDIO dev:8 hw_level:2192
- 496121.042379581 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.042383896 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.042396134 DEV_STREAM_MIX written:1024 read:1024
- 496121.042396845 WRITE_STREAMS_MIXED write_limit:1024
- 496121.042399356 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.042401336 STREAM_SLEEP_TIME id:140000 wake:000496121.063409226
- 496121.042408733 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.042409194 DEV_SLEEP_TIME dev:8 wake:000496121.109400118
- 496121.042411098 SLEEP sleep:000000000.021009108 longest_wake:000158140
- 496121.063442196 WAKE num_fds:0
- 496121.063463530 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.063487531 FILL_AUDIO dev:8 hw_level:2208
- 496121.063490733 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.063491094 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.063491956 WRITE_STREAMS_MIXED write_limit:0
- 496121.063494311 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.063501097 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.063501518 DEV_SLEEP_TIME dev:8 wake:000496121.109495334
- 496121.063502906 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.063638629 WAKE num_fds:1
- 496121.063664449 FILL_AUDIO dev:8 hw_level:2208
- 496121.063665983 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.063667807 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.063672392 DEV_STREAM_MIX written:1024 read:1024
- 496121.063672979 WRITE_STREAMS_MIXED write_limit:1024
- 496121.063673881 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.063674803 STREAM_SLEEP_TIME id:140000 wake:000496121.084742559
- 496121.063680601 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.063680947 DEV_SLEEP_TIME dev:8 wake:000496121.131007700
- 496121.063681985 SLEEP sleep:000000000.021068192 longest_wake:000158140
- 496121.084972982 WAKE num_fds:0
- 496121.084998972 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.085036704 FILL_AUDIO dev:8 hw_level:2176
- 496121.085042467 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.085043004 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.085044231 WRITE_STREAMS_MIXED write_limit:0
- 496121.085047218 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.085055317 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.085055828 DEV_SLEEP_TIME dev:8 wake:000496121.130381869
- 496121.085057853 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.085230672 WAKE num_fds:1
- 496121.085267442 FILL_AUDIO dev:8 hw_level:2176
- 496121.085269406 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.085270950 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.085275450 DEV_STREAM_MIX written:1024 read:1024
- 496121.085276072 WRITE_STREAMS_MIXED write_limit:1024
- 496121.085277325 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.085278387 STREAM_SLEEP_TIME id:140000 wake:000496121.106075892
- 496121.085284005 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.085284386 DEV_SLEEP_TIME dev:8 wake:000496121.151944572
- 496121.085285343 SLEEP sleep:000000000.020797986 longest_wake:000158140
- 496121.106153725 WAKE num_fds:0
- 496121.106176578 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.106205204 FILL_AUDIO dev:8 hw_level:2192
- 496121.106209083 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.106209449 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.106210311 WRITE_STREAMS_MIXED write_limit:0
- 496121.106212756 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.106219677 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.106220093 DEV_SLEEP_TIME dev:8 wake:000496121.151880430
- 496121.106221497 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.106405836 WAKE num_fds:1
- 496121.106434848 FILL_AUDIO dev:8 hw_level:2192
- 496121.106436587 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.106438196 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.106442836 DEV_STREAM_MIX written:1024 read:1024
- 496121.106443453 WRITE_STREAMS_MIXED write_limit:1024
- 496121.106444270 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.106445267 STREAM_SLEEP_TIME id:140000 wake:000496121.127409225
- 496121.106450840 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.106451211 DEV_SLEEP_TIME dev:8 wake:000496121.173444846
- 496121.106452173 SLEEP sleep:000000000.020964379 longest_wake:000158140
- 496121.127456103 WAKE num_fds:0
- 496121.127480189 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.127509316 FILL_AUDIO dev:8 hw_level:2208
- 496121.127514788 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.127515350 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.127516447 WRITE_STREAMS_MIXED write_limit:0
- 496121.127519494 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.127527327 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.127527949 DEV_SLEEP_TIME dev:8 wake:000496121.173520722
- 496121.127529863 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.127623489 WAKE num_fds:1
- 496121.127651173 FILL_AUDIO dev:8 hw_level:2208
- 496121.127653223 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.127655077 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.127661482 DEV_STREAM_MIX written:1024 read:1024
- 496121.127662299 WRITE_STREAMS_MIXED write_limit:1024
- 496121.127663462 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.127664910 STREAM_SLEEP_TIME id:140000 wake:000496121.148742558
- 496121.127671079 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.127671600 DEV_SLEEP_TIME dev:8 wake:000496121.194997566
- 496121.127673084 SLEEP sleep:000000000.021078325 longest_wake:000158140
- 496121.148794283 WAKE num_fds:0
- 496121.148808400 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496121.148823722 FILL_AUDIO dev:8 hw_level:2176
- 496121.148826017 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.148826191 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.148826634 WRITE_STREAMS_MIXED write_limit:0
- 496121.148828005 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.148833984 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.148834180 DEV_SLEEP_TIME dev:8 wake:000496121.194161902
- 496121.148834991 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.148928624 WAKE num_fds:1
- 496121.148951279 FILL_AUDIO dev:8 hw_level:2176
- 496121.148952642 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.148953524 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.148957366 DEV_STREAM_MIX written:1024 read:1024
- 496121.148957752 WRITE_STREAMS_MIXED write_limit:1024
- 496121.148958498 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.148959151 STREAM_SLEEP_TIME id:140000 wake:000496121.170075891
- 496121.148964100 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.148964295 DEV_SLEEP_TIME dev:8 wake:000496121.215625558
- 496121.148965082 SLEEP sleep:000000000.021116999 longest_wake:000158140
- 496121.170295036 WAKE num_fds:0
- 496121.170310195 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.170338189 FILL_AUDIO dev:8 hw_level:2192
- 496121.170340356 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.170340526 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.170341064 WRITE_STREAMS_MIXED write_limit:0
- 496121.170342450 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.170348111 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.170348306 DEV_SLEEP_TIME dev:8 wake:000496121.216009708
- 496121.170349021 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.170436685 WAKE num_fds:1
- 496121.170457636 FILL_AUDIO dev:8 hw_level:2192
- 496121.170458990 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.170459889 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.170463374 DEV_STREAM_MIX written:1024 read:1024
- 496121.170463768 WRITE_STREAMS_MIXED write_limit:1024
- 496121.170464518 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.170465104 STREAM_SLEEP_TIME id:140000 wake:000496121.191409224
- 496121.170469940 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.170470140 DEV_SLEEP_TIME dev:8 wake:000496121.237464872
- 496121.170470759 SLEEP sleep:000000000.020944352 longest_wake:000158140
- 496121.191442767 WAKE num_fds:0
- 496121.191468065 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.191492321 FILL_AUDIO dev:8 hw_level:2208
- 496121.191497173 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.191497739 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.191498982 WRITE_STREAMS_MIXED write_limit:0
- 496121.191502044 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.191510178 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.191510804 DEV_SLEEP_TIME dev:8 wake:000496121.237503387
- 496121.191512688 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.191656004 WAKE num_fds:1
- 496121.191683488 FILL_AUDIO dev:8 hw_level:2208
- 496121.191685171 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.191687051 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.191693110 DEV_STREAM_MIX written:1024 read:1024
- 496121.191693912 WRITE_STREAMS_MIXED write_limit:1024
- 496121.191694869 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.191696172 STREAM_SLEEP_TIME id:140000 wake:000496121.212742557
- 496121.191702466 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.191703003 DEV_SLEEP_TIME dev:8 wake:000496121.259028934
- 496121.191704526 SLEEP sleep:000000000.021046956 longest_wake:000158140
- 496121.212804603 WAKE num_fds:0
- 496121.212826428 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.212845046 FILL_AUDIO dev:8 hw_level:2176
- 496121.212848564 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.212848930 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.212849963 WRITE_STREAMS_MIXED write_limit:0
- 496121.212852378 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.212859840 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.212860281 DEV_SLEEP_TIME dev:8 wake:000496121.258187200
- 496121.212861805 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.213036739 WAKE num_fds:1
- 496121.213070923 FILL_AUDIO dev:8 hw_level:2176
- 496121.213073554 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.213075102 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.213081507 DEV_STREAM_MIX written:1024 read:1024
- 496121.213082214 WRITE_STREAMS_MIXED write_limit:1024
- 496121.213083777 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.213085085 STREAM_SLEEP_TIME id:140000 wake:000496121.234075890
- 496121.213090939 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.213091360 DEV_SLEEP_TIME dev:8 wake:000496121.279751190
- 496121.213092643 SLEEP sleep:000000000.020991366 longest_wake:000158140
- 496121.234340660 WAKE num_fds:0
- 496121.234364265 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.234393978 FILL_AUDIO dev:8 hw_level:2192
- 496121.234398053 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.234398418 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.234399290 WRITE_STREAMS_MIXED write_limit:0
- 496121.234401912 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.234408692 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.234409113 DEV_SLEEP_TIME dev:8 wake:000496121.280069555
- 496121.234410491 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.234595734 WAKE num_fds:1
- 496121.234631867 FILL_AUDIO dev:8 hw_level:2192
- 496121.234634709 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.234636328 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.234640613 DEV_STREAM_MIX written:1024 read:1024
- 496121.234641319 WRITE_STREAMS_MIXED write_limit:1024
- 496121.234643008 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.234644276 STREAM_SLEEP_TIME id:140000 wake:000496121.255409223
- 496121.234650119 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.234650540 DEV_SLEEP_TIME dev:8 wake:000496121.301643780
- 496121.234651838 SLEEP sleep:000000000.020765443 longest_wake:000158140
- 496121.255666578 WAKE num_fds:0
- 496121.255690188 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.255720508 FILL_AUDIO dev:8 hw_level:2208
- 496121.255724261 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.255724632 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.255725509 WRITE_STREAMS_MIXED write_limit:0
- 496121.255728055 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.255734826 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.255735242 DEV_SLEEP_TIME dev:8 wake:000496121.301729027
- 496121.255736630 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.255919587 WAKE num_fds:1
- 496121.255961218 FILL_AUDIO dev:8 hw_level:2160
- 496121.255964646 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.255966716 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.255972560 DEV_STREAM_MIX written:1024 read:1024
- 496121.255973502 WRITE_STREAMS_MIXED write_limit:1024
- 496121.255975742 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496121.255977441 STREAM_SLEEP_TIME id:140000 wake:000496121.276742556
- 496121.256005751 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496121.256006408 DEV_SLEEP_TIME dev:8 wake:000496121.322310077
- 496121.256008177 SLEEP sleep:000000000.020765812 longest_wake:000158140
- 496121.276833494 WAKE num_fds:0
- 496121.276877902 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.276909971 FILL_AUDIO dev:8 hw_level:2176
- 496121.276917979 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.276918350 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.276919974 WRITE_STREAMS_MIXED write_limit:0
- 496121.276924930 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.276932894 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.276933325 DEV_SLEEP_TIME dev:8 wake:000496121.322259882
- 496121.276934914 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.277102220 WAKE num_fds:1
- 496121.277141049 FILL_AUDIO dev:8 hw_level:2176
- 496121.277146141 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.277147930 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.277154756 DEV_STREAM_MIX written:1024 read:1024
- 496121.277155468 WRITE_STREAMS_MIXED write_limit:1024
- 496121.277157577 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.277159051 STREAM_SLEEP_TIME id:140000 wake:000496121.298075889
- 496121.277165325 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.277165756 DEV_SLEEP_TIME dev:8 wake:000496121.343825146
- 496121.277167140 SLEEP sleep:000000000.020917409 longest_wake:000158140
- 496121.298348914 WAKE num_fds:0
- 496121.298371636 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.298402057 FILL_AUDIO dev:8 hw_level:2192
- 496121.298407078 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.298407444 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.298408321 WRITE_STREAMS_MIXED write_limit:0
- 496121.298410827 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.298417593 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.298418013 DEV_SLEEP_TIME dev:8 wake:000496121.344078475
- 496121.298419487 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.298605947 WAKE num_fds:1
- 496121.298642421 FILL_AUDIO dev:8 hw_level:2192
- 496121.298645453 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.298646977 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.298651342 DEV_STREAM_MIX written:1024 read:1024
- 496121.298652024 WRITE_STREAMS_MIXED write_limit:1024
- 496121.298653682 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.298654975 STREAM_SLEEP_TIME id:140000 wake:000496121.319409222
- 496121.298660674 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.298661120 DEV_SLEEP_TIME dev:8 wake:000496121.365654424
- 496121.298662398 SLEEP sleep:000000000.020754798 longest_wake:000158140
- 496121.319517158 WAKE num_fds:0
- 496121.319540282 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.319569664 FILL_AUDIO dev:8 hw_level:2208
- 496121.319573483 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.319573844 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.319574716 WRITE_STREAMS_MIXED write_limit:0
- 496121.319577397 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.319584288 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.319584709 DEV_SLEEP_TIME dev:8 wake:000496121.365578450
- 496121.319586107 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.319772252 WAKE num_fds:1
- 496121.319806747 FILL_AUDIO dev:8 hw_level:2208
- 496121.319809608 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.319811162 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.319817070 DEV_STREAM_MIX written:1024 read:1024
- 496121.319817782 WRITE_STREAMS_MIXED write_limit:1024
- 496121.319819521 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.319820794 STREAM_SLEEP_TIME id:140000 wake:000496121.340742555
- 496121.319826878 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496121.319827319 DEV_SLEEP_TIME dev:8 wake:000496121.386153636
- 496121.319828577 SLEEP sleep:000000000.020922252 longest_wake:000158140
- 496121.340779013 WAKE num_fds:0
- 496121.340801190 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496121.340820529 FILL_AUDIO dev:8 hw_level:2224
- 496121.340824208 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.340824574 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.340825431 WRITE_STREAMS_MIXED write_limit:0
- 496121.340827766 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496121.340835128 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.340835564 DEV_SLEEP_TIME dev:8 wake:000496121.386162156
- 496121.340837022 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.340934888 WAKE num_fds:1
- 496121.340962677 FILL_AUDIO dev:8 hw_level:2176
- 496121.340965148 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.340967083 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.340972921 DEV_STREAM_MIX written:1024 read:1024
- 496121.340973838 WRITE_STREAMS_MIXED write_limit:1024
- 496121.340975302 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.340976885 STREAM_SLEEP_TIME id:140000 wake:000496121.362075888
- 496121.340983536 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.340984062 DEV_SLEEP_TIME dev:8 wake:000496121.407642910
- 496121.340985375 SLEEP sleep:000000000.021099644 longest_wake:000158140
- 496121.362354958 WAKE num_fds:0
- 496121.362378873 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.362408697 FILL_AUDIO dev:8 hw_level:2192
- 496121.362412716 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.362413087 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.362413959 WRITE_STREAMS_MIXED write_limit:0
- 496121.362416470 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.362423406 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.362423822 DEV_SLEEP_TIME dev:8 wake:000496121.408084143
- 496121.362425310 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.362609405 WAKE num_fds:1
- 496121.362644947 FILL_AUDIO dev:8 hw_level:2192
- 496121.362647794 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.362649352 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.362655296 DEV_STREAM_MIX written:1024 read:1024
- 496121.362656003 WRITE_STREAMS_MIXED write_limit:1024
- 496121.362657697 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.362658959 STREAM_SLEEP_TIME id:140000 wake:000496121.383409221
- 496121.362664853 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.362665284 DEV_SLEEP_TIME dev:8 wake:000496121.429658468
- 496121.362666582 SLEEP sleep:000000000.020750753 longest_wake:000158140
- 496121.383661311 WAKE num_fds:0
- 496121.383685507 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.383715957 FILL_AUDIO dev:8 hw_level:2208
- 496121.383719771 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.383720152 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.383721169 WRITE_STREAMS_MIXED write_limit:0
- 496121.383723635 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.383730520 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.383730941 DEV_SLEEP_TIME dev:8 wake:000496121.429724627
- 496121.383732590 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.383917362 WAKE num_fds:1
- 496121.383953876 FILL_AUDIO dev:8 hw_level:2160
- 496121.383956778 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.383958356 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.383964300 DEV_STREAM_MIX written:1024 read:1024
- 496121.383965012 WRITE_STREAMS_MIXED write_limit:1024
- 496121.383966590 FILL_AUDIO_DONE hw_level:2160 total_written:1024 min_cb_level:1024
- 496121.383967858 STREAM_SLEEP_TIME id:140000 wake:000496121.404742554
- 496121.383973662 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496121.383974088 DEV_SLEEP_TIME dev:8 wake:000496121.450300690
- 496121.383975396 SLEEP sleep:000000000.020775197 longest_wake:000158140
- 496121.404849376 WAKE num_fds:0
- 496121.404872895 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.404901997 FILL_AUDIO dev:8 hw_level:2176
- 496121.404905926 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.404906297 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.404907169 WRITE_STREAMS_MIXED write_limit:0
- 496121.404909630 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.404916471 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.404916897 DEV_SLEEP_TIME dev:8 wake:000496121.450243925
- 496121.404918325 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.405102806 WAKE num_fds:1
- 496121.405139886 FILL_AUDIO dev:8 hw_level:2176
- 496121.405142743 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.405144241 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.405150476 DEV_STREAM_MIX written:1024 read:1024
- 496121.405151182 WRITE_STREAMS_MIXED write_limit:1024
- 496121.405152826 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.405154069 STREAM_SLEEP_TIME id:140000 wake:000496121.426075887
- 496121.405159912 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.405160338 DEV_SLEEP_TIME dev:8 wake:000496121.471820239
- 496121.405161661 SLEEP sleep:000000000.020922314 longest_wake:000158140
- 496121.426187061 WAKE num_fds:0
- 496121.426210430 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.426240775 FILL_AUDIO dev:8 hw_level:2192
- 496121.426244468 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.426244844 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.426245716 WRITE_STREAMS_MIXED write_limit:0
- 496121.426248337 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.426255243 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.426255674 DEV_SLEEP_TIME dev:8 wake:000496121.471916076
- 496121.426257068 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.426460306 WAKE num_fds:1
- 496121.426497361 FILL_AUDIO dev:8 hw_level:2192
- 496121.426500183 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.426501801 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.426507575 DEV_STREAM_MIX written:1024 read:1024
- 496121.426508286 WRITE_STREAMS_MIXED write_limit:1024
- 496121.426509890 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.426511163 STREAM_SLEEP_TIME id:140000 wake:000496121.447409220
- 496121.426516901 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.426517322 DEV_SLEEP_TIME dev:8 wake:000496121.493510657
- 496121.426518570 SLEEP sleep:000000000.020898563 longest_wake:000158140
- 496121.447437098 WAKE num_fds:0
- 496121.447459314 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.447478694 FILL_AUDIO dev:8 hw_level:2208
- 496121.447482052 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.447482413 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.447483420 WRITE_STREAMS_MIXED write_limit:0
- 496121.447485916 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.447492992 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.447493413 DEV_SLEEP_TIME dev:8 wake:000496121.493486988
- 496121.447494891 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.447638448 WAKE num_fds:1
- 496121.447662433 FILL_AUDIO dev:8 hw_level:2208
- 496121.447663871 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.447665395 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.447669329 DEV_STREAM_MIX written:1024 read:1024
- 496121.447669940 WRITE_STREAMS_MIXED write_limit:1024
- 496121.447670717 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.447671765 STREAM_SLEEP_TIME id:140000 wake:000496121.468742553
- 496121.447677317 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.447677698 DEV_SLEEP_TIME dev:8 wake:000496121.515004652
- 496121.447678721 SLEEP sleep:000000000.021071234 longest_wake:000158140
- 496121.468810020 WAKE num_fds:0
- 496121.468833494 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.468862756 FILL_AUDIO dev:8 hw_level:2176
- 496121.468866450 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.468866821 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.468867683 WRITE_STREAMS_MIXED write_limit:0
- 496121.468870224 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.468877119 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.468877535 DEV_SLEEP_TIME dev:8 wake:000496121.514204544
- 496121.468878934 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.469065043 WAKE num_fds:1
- 496121.469101332 FILL_AUDIO dev:8 hw_level:2176
- 496121.469104214 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.469105782 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.469110273 DEV_STREAM_MIX written:1024 read:1024
- 496121.469110984 WRITE_STREAMS_MIXED write_limit:1024
- 496121.469112643 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.469113906 STREAM_SLEEP_TIME id:140000 wake:000496121.490075886
- 496121.469119609 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.469120035 DEV_SLEEP_TIME dev:8 wake:000496121.535780076
- 496121.469121338 SLEEP sleep:000000000.020962476 longest_wake:000158140
- 496121.490134710 WAKE num_fds:0
- 496121.490157758 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.490176612 FILL_AUDIO dev:8 hw_level:2192
- 496121.490180090 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.490180455 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.490181328 WRITE_STREAMS_MIXED write_limit:0
- 496121.490183939 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.490191015 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.490191441 DEV_SLEEP_TIME dev:8 wake:000496121.535851602
- 496121.490192819 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.490344027 WAKE num_fds:1
- 496121.490368824 FILL_AUDIO dev:8 hw_level:2192
- 496121.490369947 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.490371526 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.490375760 DEV_STREAM_MIX written:1024 read:1024
- 496121.490376372 WRITE_STREAMS_MIXED write_limit:1024
- 496121.490377103 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.490378071 STREAM_SLEEP_TIME id:140000 wake:000496121.511409219
- 496121.490383679 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.490384044 DEV_SLEEP_TIME dev:8 wake:000496121.557377630
- 496121.490385037 SLEEP sleep:000000000.021031589 longest_wake:000158140
- 496121.511477967 WAKE num_fds:0
- 496121.511498976 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.511518240 FILL_AUDIO dev:8 hw_level:2208
- 496121.511521848 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.511522214 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.511523071 WRITE_STREAMS_MIXED write_limit:0
- 496121.511525662 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.511532739 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.511533159 DEV_SLEEP_TIME dev:8 wake:000496121.557526780
- 496121.511534738 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.511709978 WAKE num_fds:1
- 496121.511744327 FILL_AUDIO dev:8 hw_level:2208
- 496121.511746938 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.511748527 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.511752872 DEV_STREAM_MIX written:1024 read:1024
- 496121.511753583 WRITE_STREAMS_MIXED write_limit:1024
- 496121.511755062 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.511756370 STREAM_SLEEP_TIME id:140000 wake:000496121.532742552
- 496121.511762093 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.511762519 DEV_SLEEP_TIME dev:8 wake:000496121.579089151
- 496121.511763777 SLEEP sleep:000000000.020986734 longest_wake:000158140
- 496121.532787267 WAKE num_fds:0
- 496121.532806276 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496121.532828853 FILL_AUDIO dev:8 hw_level:2176
- 496121.532832171 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.532832546 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.532833393 WRITE_STREAMS_MIXED write_limit:0
- 496121.532835618 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.532842209 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.532842640 DEV_SLEEP_TIME dev:8 wake:000496121.578169939
- 496121.532844013 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.533004248 WAKE num_fds:1
- 496121.533031992 FILL_AUDIO dev:8 hw_level:2176
- 496121.533033139 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.533034768 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.533039339 DEV_STREAM_MIX written:1024 read:1024
- 496121.533039885 WRITE_STREAMS_MIXED write_limit:1024
- 496121.533040546 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.533041479 STREAM_SLEEP_TIME id:140000 wake:000496121.554075885
- 496121.533046991 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.533047332 DEV_SLEEP_TIME dev:8 wake:000496121.599707689
- 496121.533048249 SLEEP sleep:000000000.021034862 longest_wake:000158140
- 496121.554149766 WAKE num_fds:0
- 496121.554166364 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.554188087 FILL_AUDIO dev:8 hw_level:2192
- 496121.554190863 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.554191054 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.554191551 WRITE_STREAMS_MIXED write_limit:0
- 496121.554193238 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.554198768 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.554198995 DEV_SLEEP_TIME dev:8 wake:000496121.599860491
- 496121.554199801 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.554306442 WAKE num_fds:1
- 496121.554337642 FILL_AUDIO dev:8 hw_level:2192
- 496121.554339165 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.554340148 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.554342551 DEV_STREAM_MIX written:1024 read:1024
- 496121.554342938 WRITE_STREAMS_MIXED write_limit:1024
- 496121.554343832 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.554344526 STREAM_SLEEP_TIME id:140000 wake:000496121.575409218
- 496121.554349427 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.554349648 DEV_SLEEP_TIME dev:8 wake:000496121.621344250
- 496121.554350349 SLEEP sleep:000000000.021064968 longest_wake:000158140
- 496121.575454337 WAKE num_fds:0
- 496121.575494936 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.575524409 FILL_AUDIO dev:8 hw_level:2208
- 496121.575533510 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.575533881 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.575535084 WRITE_STREAMS_MIXED write_limit:0
- 496121.575542005 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.575550880 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.575551301 DEV_SLEEP_TIME dev:8 wake:000496121.621544054
- 496121.575553642 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.575716452 WAKE num_fds:1
- 496121.575751844 FILL_AUDIO dev:8 hw_level:2208
- 496121.575754250 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.575758309 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.575767365 DEV_STREAM_MIX written:1024 read:1024
- 496121.575768162 WRITE_STREAMS_MIXED write_limit:1024
- 496121.575770342 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.575771555 STREAM_SLEEP_TIME id:140000 wake:000496121.596742551
- 496121.575778536 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.575778881 DEV_SLEEP_TIME dev:8 wake:000496121.643104391
- 496121.575779819 SLEEP sleep:000000000.020971493 longest_wake:000158140
- 496121.596772698 WAKE num_fds:0
- 496121.596791942 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496121.596812365 FILL_AUDIO dev:8 hw_level:2224
- 496121.596816053 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.596816449 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.596817366 WRITE_STREAMS_MIXED write_limit:0
- 496121.596819742 FILL_AUDIO_DONE hw_level:2224 total_written:0 min_cb_level:1024
- 496121.596827289 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.596827710 DEV_SLEEP_TIME dev:8 wake:000496121.642154277
- 496121.596829168 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.596956217 WAKE num_fds:1
- 496121.596983470 FILL_AUDIO dev:8 hw_level:2176
- 496121.596984933 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.596986747 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.596992150 DEV_STREAM_MIX written:1024 read:1024
- 496121.596992816 WRITE_STREAMS_MIXED write_limit:1024
- 496121.596993984 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.596995237 STREAM_SLEEP_TIME id:140000 wake:000496121.618075884
- 496121.597001296 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.597001767 DEV_SLEEP_TIME dev:8 wake:000496121.663661412
- 496121.597003526 SLEEP sleep:000000000.021081138 longest_wake:000158140
- 496121.618124193 WAKE num_fds:0
- 496121.618142226 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.618162091 FILL_AUDIO dev:8 hw_level:2192
- 496121.618164259 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.618164430 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.618164887 WRITE_STREAMS_MIXED write_limit:0
- 496121.618166527 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.618172515 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.618172712 DEV_SLEEP_TIME dev:8 wake:000496121.663833716
- 496121.618173602 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.618250086 WAKE num_fds:1
- 496121.618275409 FILL_AUDIO dev:8 hw_level:2192
- 496121.618277345 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.618278382 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.618282712 DEV_STREAM_MIX written:1024 read:1024
- 496121.618283080 WRITE_STREAMS_MIXED write_limit:1024
- 496121.618284169 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.618284939 STREAM_SLEEP_TIME id:140000 wake:000496121.639409217
- 496121.618290559 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.618290797 DEV_SLEEP_TIME dev:8 wake:000496121.685284641
- 496121.618291691 SLEEP sleep:000000000.021124576 longest_wake:000158140
- 496121.639440385 WAKE num_fds:0
- 496121.639455997 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.639474693 FILL_AUDIO dev:8 hw_level:2208
- 496121.639476921 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.639477163 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.639477713 WRITE_STREAMS_MIXED write_limit:0
- 496121.639479088 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.639484385 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.639484585 DEV_SLEEP_TIME dev:8 wake:000496121.685479618
- 496121.639485314 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.639571021 WAKE num_fds:1
- 496121.639588187 FILL_AUDIO dev:8 hw_level:2208
- 496121.639588853 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.639589796 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.639591916 DEV_STREAM_MIX written:1024 read:1024
- 496121.639592176 WRITE_STREAMS_MIXED write_limit:1024
- 496121.639592524 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.639592994 STREAM_SLEEP_TIME id:140000 wake:000496121.660742550
- 496121.639597798 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.639598010 DEV_SLEEP_TIME dev:8 wake:000496121.706926113
- 496121.639598591 SLEEP sleep:000000000.021149770 longest_wake:000158140
- 496121.660777354 WAKE num_fds:0
- 496121.660803529 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496121.660831248 FILL_AUDIO dev:8 hw_level:2176
- 496121.660837232 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.660837603 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.660838725 WRITE_STREAMS_MIXED write_limit:0
- 496121.660842188 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.660849174 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.660849605 DEV_SLEEP_TIME dev:8 wake:000496121.706176328
- 496121.660851059 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.660972434 WAKE num_fds:1
- 496121.660998349 FILL_AUDIO dev:8 hw_level:2176
- 496121.661000228 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.661001912 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.661007961 DEV_STREAM_MIX written:1024 read:1024
- 496121.661008622 WRITE_STREAMS_MIXED write_limit:1024
- 496121.661009860 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.661011399 STREAM_SLEEP_TIME id:140000 wake:000496121.682075883
- 496121.661017543 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.661017944 DEV_SLEEP_TIME dev:8 wake:000496121.727677223
- 496121.661018966 SLEEP sleep:000000000.021065326 longest_wake:000158140
- 496121.682107792 WAKE num_fds:0
- 496121.682128911 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.682148682 FILL_AUDIO dev:8 hw_level:2192
- 496121.682152465 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.682152846 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.682153863 WRITE_STREAMS_MIXED write_limit:0
- 496121.682156525 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.682164117 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.682164533 DEV_SLEEP_TIME dev:8 wake:000496121.727824328
- 496121.682166262 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.682264925 WAKE num_fds:1
- 496121.682287552 FILL_AUDIO dev:8 hw_level:2192
- 496121.682289416 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.682291381 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.682297630 DEV_STREAM_MIX written:1024 read:1024
- 496121.682298352 WRITE_STREAMS_MIXED write_limit:1024
- 496121.682299835 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.682301093 STREAM_SLEEP_TIME id:140000 wake:000496121.703409216
- 496121.682306160 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.682306676 DEV_SLEEP_TIME dev:8 wake:000496121.749300442
- 496121.682308029 SLEEP sleep:000000000.021108774 longest_wake:000158140
- 496121.703497071 WAKE num_fds:0
- 496121.703520750 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.703547256 FILL_AUDIO dev:8 hw_level:2208
- 496121.703551261 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.703551837 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.703552945 WRITE_STREAMS_MIXED write_limit:0
- 496121.703555796 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.703563900 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.703564391 DEV_SLEEP_TIME dev:8 wake:000496121.749557079
- 496121.703566491 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.703744086 WAKE num_fds:1
- 496121.703780810 FILL_AUDIO dev:8 hw_level:2208
- 496121.703783762 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.703785371 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.703791515 DEV_STREAM_MIX written:1024 read:1024
- 496121.703792207 WRITE_STREAMS_MIXED write_limit:1024
- 496121.703793886 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.703795229 STREAM_SLEEP_TIME id:140000 wake:000496121.724742549
- 496121.703801448 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.703801869 DEV_SLEEP_TIME dev:8 wake:000496121.771128005
- 496121.703803137 SLEEP sleep:000000000.020947877 longest_wake:000158140
- 496121.724787767 WAKE num_fds:0
- 496121.724808766 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496121.724832015 FILL_AUDIO dev:8 hw_level:2176
- 496121.724835688 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.724836099 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.724837081 WRITE_STREAMS_MIXED write_limit:0
- 496121.724839888 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.724847761 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.724848197 DEV_SLEEP_TIME dev:8 wake:000496121.770174283
- 496121.724849776 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.724991743 WAKE num_fds:1
- 496121.725028934 FILL_AUDIO dev:8 hw_level:2176
- 496121.725031786 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.725033399 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.725039383 DEV_STREAM_MIX written:1024 read:1024
- 496121.725040095 WRITE_STREAMS_MIXED write_limit:1024
- 496121.725041663 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.725042986 STREAM_SLEEP_TIME id:140000 wake:000496121.746075882
- 496121.725049030 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.725049456 DEV_SLEEP_TIME dev:8 wake:000496121.791709096
- 496121.725050830 SLEEP sleep:000000000.021033452 longest_wake:000158140
- 496121.746183507 WAKE num_fds:0
- 496121.746206440 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.746236283 FILL_AUDIO dev:8 hw_level:2192
- 496121.746239977 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.746240348 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.746241220 WRITE_STREAMS_MIXED write_limit:0
- 496121.746243841 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.746250787 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.746251208 DEV_SLEEP_TIME dev:8 wake:000496121.791911514
- 496121.746252752 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.746440178 WAKE num_fds:1
- 496121.746474552 FILL_AUDIO dev:8 hw_level:2192
- 496121.746477209 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.746478887 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.746484646 DEV_STREAM_MIX written:1024 read:1024
- 496121.746485362 WRITE_STREAMS_MIXED write_limit:1024
- 496121.746487167 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.746488465 STREAM_SLEEP_TIME id:140000 wake:000496121.767409215
- 496121.746494258 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.746494684 DEV_SLEEP_TIME dev:8 wake:000496121.813487968
- 496121.746495987 SLEEP sleep:000000000.020921247 longest_wake:000158140
- 496121.767517668 WAKE num_fds:0
- 496121.767540631 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.767570465 FILL_AUDIO dev:8 hw_level:2208
- 496121.767574359 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.767574730 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.767575607 WRITE_STREAMS_MIXED write_limit:0
- 496121.767578077 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.767584953 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.767585374 DEV_SLEEP_TIME dev:8 wake:000496121.813579080
- 496121.767586833 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.767774586 WAKE num_fds:1
- 496121.767808720 FILL_AUDIO dev:8 hw_level:2208
- 496121.767811737 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.767813270 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.767819550 DEV_STREAM_MIX written:1024 read:1024
- 496121.767820261 WRITE_STREAMS_MIXED write_limit:1024
- 496121.767821965 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.767823248 STREAM_SLEEP_TIME id:140000 wake:000496121.788742548
- 496121.767829498 SET_DEV_WAKE dev:8 hw_level:3184 sleep:3184
- 496121.767829924 DEV_SLEEP_TIME dev:8 wake:000496121.834156085
- 496121.767831212 SLEEP sleep:000000000.020919796 longest_wake:000158140
- 496121.788852201 WAKE num_fds:0
- 496121.788875299 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.788905694 FILL_AUDIO dev:8 hw_level:2176
- 496121.788909388 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.788909764 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.788910641 WRITE_STREAMS_MIXED write_limit:0
- 496121.788913157 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.788919962 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.788920378 DEV_SLEEP_TIME dev:8 wake:000496121.834247487
- 496121.788921847 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.789105962 WAKE num_fds:1
- 496121.789141990 FILL_AUDIO dev:8 hw_level:2176
- 496121.789144821 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.789146320 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.789152188 DEV_STREAM_MIX written:1024 read:1024
- 496121.789152905 WRITE_STREAMS_MIXED write_limit:1024
- 496121.789154589 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.789155837 STREAM_SLEEP_TIME id:140000 wake:000496121.810075881
- 496121.789161580 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.789162031 DEV_SLEEP_TIME dev:8 wake:000496121.855822012
- 496121.789163364 SLEEP sleep:000000000.020920535 longest_wake:000158140
- 496121.810105924 WAKE num_fds:0
- 496121.810127257 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.810146862 FILL_AUDIO dev:8 hw_level:2192
- 496121.810150015 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.810150306 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.810151004 WRITE_STREAMS_MIXED write_limit:0
- 496121.810153450 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.810160382 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.810160763 DEV_SLEEP_TIME dev:8 wake:000496121.855821025
- 496121.810162046 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.810236321 WAKE num_fds:1
- 496121.810255739 FILL_AUDIO dev:8 hw_level:2192
- 496121.810256712 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.810257947 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.810261439 DEV_STREAM_MIX written:1024 read:1024
- 496121.810261907 WRITE_STREAMS_MIXED write_limit:1024
- 496121.810262882 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.810263721 STREAM_SLEEP_TIME id:140000 wake:000496121.831409214
- 496121.810269822 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.810270232 DEV_SLEEP_TIME dev:8 wake:000496121.877263347
- 496121.810271515 SLEEP sleep:000000000.021145867 longest_wake:000158140
- 496121.831434429 WAKE num_fds:0
- 496121.831453119 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.831472022 FILL_AUDIO dev:8 hw_level:2208
- 496121.831475096 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.831475410 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.831476122 WRITE_STREAMS_MIXED write_limit:0
- 496121.831478086 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.831484565 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.831484852 DEV_SLEEP_TIME dev:8 wake:000496121.877478858
- 496121.831486095 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.831591475 WAKE num_fds:1
- 496121.831622506 FILL_AUDIO dev:8 hw_level:2208
- 496121.831624705 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.831626162 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.831630221 DEV_STREAM_MIX written:1024 read:1024
- 496121.831630832 WRITE_STREAMS_MIXED write_limit:1024
- 496121.831632757 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.831633906 STREAM_SLEEP_TIME id:140000 wake:000496121.852742547
- 496121.831640127 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.831640498 DEV_SLEEP_TIME dev:8 wake:000496121.898966785
- 496121.831641684 SLEEP sleep:000000000.021109095 longest_wake:000158140
- 496121.852996684 WAKE num_fds:0
- 496121.853020685 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.853051536 FILL_AUDIO dev:8 hw_level:2176
- 496121.853055385 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.853055745 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.853056617 WRITE_STREAMS_MIXED write_limit:0
- 496121.853059665 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.853066580 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.853067001 DEV_SLEEP_TIME dev:8 wake:000496121.898393980
- 496121.853068390 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.853258724 WAKE num_fds:1
- 496121.853296812 FILL_AUDIO dev:8 hw_level:2176
- 496121.853300455 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.853302259 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.853307968 DEV_STREAM_MIX written:1024 read:1024
- 496121.853308880 WRITE_STREAMS_MIXED write_limit:1024
- 496121.853311250 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.853312864 STREAM_SLEEP_TIME id:140000 wake:000496121.874075880
- 496121.853319424 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.853319925 DEV_SLEEP_TIME dev:8 wake:000496121.919978883
- 496121.853321699 SLEEP sleep:000000000.020763663 longest_wake:000158140
- 496121.874121581 WAKE num_fds:0
- 496121.874137484 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.874154658 FILL_AUDIO dev:8 hw_level:2192
- 496121.874157144 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.874157263 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.874157596 WRITE_STREAMS_MIXED write_limit:0
- 496121.874159259 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.874164831 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.874164963 DEV_SLEEP_TIME dev:8 wake:000496121.919826370
- 496121.874165593 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.874230568 WAKE num_fds:1
- 496121.874249311 FILL_AUDIO dev:8 hw_level:2192
- 496121.874250329 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.874251172 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.874253846 DEV_STREAM_MIX written:1024 read:1024
- 496121.874254168 WRITE_STREAMS_MIXED write_limit:1024
- 496121.874254879 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.874255437 STREAM_SLEEP_TIME id:140000 wake:000496121.895409213
- 496121.874260087 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.874260219 DEV_SLEEP_TIME dev:8 wake:000496121.941255230
- 496121.874260704 SLEEP sleep:000000000.021153983 longest_wake:000158140
- 496121.895621418 WAKE num_fds:0
- 496121.895637180 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.895653809 FILL_AUDIO dev:8 hw_level:2208
- 496121.895655732 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.895655866 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.895656225 WRITE_STREAMS_MIXED write_limit:0
- 496121.895657665 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.895662759 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.895662914 DEV_SLEEP_TIME dev:8 wake:000496121.941658210
- 496121.895663513 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.895745235 WAKE num_fds:1
- 496121.895762578 FILL_AUDIO dev:8 hw_level:2208
- 496121.895763511 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.895764286 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.895767203 DEV_STREAM_MIX written:1024 read:1024
- 496121.895767568 WRITE_STREAMS_MIXED write_limit:1024
- 496121.895768193 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.895768676 STREAM_SLEEP_TIME id:140000 wake:000496121.916742546
- 496121.895773163 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.895773318 DEV_SLEEP_TIME dev:8 wake:000496121.963101805
- 496121.895773786 SLEEP sleep:000000000.020974074 longest_wake:000158140
- 496121.916816246 WAKE num_fds:0
- 496121.916829844 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.916847665 FILL_AUDIO dev:8 hw_level:2176
- 496121.916849561 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.916849697 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.916850045 WRITE_STREAMS_MIXED write_limit:0
- 496121.916851345 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.916856369 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.916856526 DEV_SLEEP_TIME dev:8 wake:000496121.962185175
- 496121.916857127 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.916936358 WAKE num_fds:1
- 496121.916953777 FILL_AUDIO dev:8 hw_level:2176
- 496121.916954713 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.916955421 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.916957165 DEV_STREAM_MIX written:1024 read:1024
- 496121.916957412 WRITE_STREAMS_MIXED write_limit:1024
- 496121.916957966 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.916958446 STREAM_SLEEP_TIME id:140000 wake:000496121.938075879
- 496121.916962996 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.916963151 DEV_SLEEP_TIME dev:8 wake:000496121.983624913
- 496121.916963634 SLEEP sleep:000000000.021117632 longest_wake:000158140
- 496121.938161250 WAKE num_fds:0
- 496121.938185050 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496121.938214142 FILL_AUDIO dev:8 hw_level:2192
- 496121.938217785 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.938218156 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.938219033 WRITE_STREAMS_MIXED write_limit:0
- 496121.938221504 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496121.938228400 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496121.938228816 DEV_SLEEP_TIME dev:8 wake:000496121.983889147
- 496121.938230174 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496121.938435592 WAKE num_fds:1
- 496121.938472612 FILL_AUDIO dev:8 hw_level:2192
- 496121.938476607 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.938478346 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.938484390 DEV_STREAM_MIX written:1024 read:1024
- 496121.938485106 WRITE_STREAMS_MIXED write_limit:1024
- 496121.938486865 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496121.938488118 STREAM_SLEEP_TIME id:140000 wake:000496121.959409212
- 496121.938493766 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496121.938494132 DEV_SLEEP_TIME dev:8 wake:000496122.005487627
- 496121.938495390 SLEEP sleep:000000000.020921585 longest_wake:000158140
- 496121.959493040 WAKE num_fds:0
- 496121.959515848 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496121.959537678 FILL_AUDIO dev:8 hw_level:2208
- 496121.959541187 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.959541547 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.959542444 WRITE_STREAMS_MIXED write_limit:0
- 496121.959544775 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496121.959551766 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496121.959552132 DEV_SLEEP_TIME dev:8 wake:000496122.005545807
- 496121.959553570 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496121.959722871 WAKE num_fds:1
- 496121.959757015 FILL_AUDIO dev:8 hw_level:2208
- 496121.959759616 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.959761390 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.959765625 DEV_STREAM_MIX written:1024 read:1024
- 496121.959766331 WRITE_STREAMS_MIXED write_limit:1024
- 496121.959767920 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496121.959769213 STREAM_SLEEP_TIME id:140000 wake:000496121.980742545
- 496121.959775262 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496121.959775628 DEV_SLEEP_TIME dev:8 wake:000496122.027101990
- 496121.959776906 SLEEP sleep:000000000.020973888 longest_wake:000158140
- 496121.980846407 WAKE num_fds:0
- 496121.980870472 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496121.980900422 FILL_AUDIO dev:8 hw_level:2176
- 496121.980904105 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496121.980904476 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496121.980905353 WRITE_STREAMS_MIXED write_limit:0
- 496121.980907799 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496121.980914860 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496121.980915226 DEV_SLEEP_TIME dev:8 wake:000496122.026242354
- 496121.980916564 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496121.981102759 WAKE num_fds:1
- 496121.981138190 FILL_AUDIO dev:8 hw_level:2176
- 496121.981141027 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496121.981142591 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496121.981148414 DEV_STREAM_MIX written:1024 read:1024
- 496121.981149101 WRITE_STREAMS_MIXED write_limit:1024
- 496121.981150754 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496121.981152037 STREAM_SLEEP_TIME id:140000 wake:000496122.002075878
- 496121.981157881 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496121.981158252 DEV_SLEEP_TIME dev:8 wake:000496122.047818162
- 496121.981159515 SLEEP sleep:000000000.020924382 longest_wake:000158140
- 496122.002337641 WAKE num_fds:0
- 496122.002361576 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496122.002391655 FILL_AUDIO dev:8 hw_level:2192
- 496122.002395404 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.002395775 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.002396652 WRITE_STREAMS_MIXED write_limit:0
- 496122.002399092 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496122.002405908 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496122.002406324 DEV_SLEEP_TIME dev:8 wake:000496122.048066736
- 496122.002407727 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496122.002594263 WAKE num_fds:1
- 496122.002630126 FILL_AUDIO dev:8 hw_level:2192
- 496122.002632972 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.002634551 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.002640490 DEV_STREAM_MIX written:1024 read:1024
- 496122.002641201 WRITE_STREAMS_MIXED write_limit:1024
- 496122.002642775 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496122.002644058 STREAM_SLEEP_TIME id:140000 wake:000496122.023409211
- 496122.002649826 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496122.002650252 DEV_SLEEP_TIME dev:8 wake:000496122.069643567
- 496122.002651565 SLEEP sleep:000000000.020765644 longest_wake:000158140
- 496122.023443827 WAKE num_fds:0
- 496122.023465787 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496122.023484866 FILL_AUDIO dev:8 hw_level:2208
- 496122.023488024 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.023488409 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.023489432 WRITE_STREAMS_MIXED write_limit:0
- 496122.023491757 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496122.023499440 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496122.023499856 DEV_SLEEP_TIME dev:8 wake:000496122.069493326
- 496122.023501389 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496122.023673351 WAKE num_fds:1
- 496122.023707245 FILL_AUDIO dev:8 hw_level:2208
- 496122.023709846 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.023711369 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.023715639 DEV_STREAM_MIX written:1024 read:1024
- 496122.023716356 WRITE_STREAMS_MIXED write_limit:1024
- 496122.023717934 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496122.023719237 STREAM_SLEEP_TIME id:140000 wake:000496122.044742544
- 496122.023724981 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496122.023725401 DEV_SLEEP_TIME dev:8 wake:000496122.091052019
- 496122.023726710 SLEEP sleep:000000000.021023858 longest_wake:000158140
- 496122.044805628 WAKE num_fds:0
- 496122.044828160 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496122.044852285 FILL_AUDIO dev:8 hw_level:2176
- 496122.044855738 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.044856109 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.044857096 WRITE_STREAMS_MIXED write_limit:0
- 496122.044859537 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496122.044866443 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496122.044866884 DEV_SLEEP_TIME dev:8 wake:000496122.090193902
- 496122.044868277 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496122.045010320 WAKE num_fds:1
- 496122.045043877 FILL_AUDIO dev:8 hw_level:2176
- 496122.045046408 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.045048012 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.045054056 DEV_STREAM_MIX written:1024 read:1024
- 496122.045054773 WRITE_STREAMS_MIXED write_limit:1024
- 496122.045056376 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496122.045057684 STREAM_SLEEP_TIME id:140000 wake:000496122.066075877
- 496122.045063523 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496122.045063944 DEV_SLEEP_TIME dev:8 wake:000496122.111723799
- 496122.045065247 SLEEP sleep:000000000.021018744 longest_wake:000158140
- 496122.066136582 WAKE num_fds:0
- 496122.066157034 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496122.066179426 FILL_AUDIO dev:8 hw_level:2192
- 496122.066183501 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.066183871 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.066184819 WRITE_STREAMS_MIXED write_limit:0
- 496122.066187029 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496122.066193809 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496122.066194230 DEV_SLEEP_TIME dev:8 wake:000496122.111854797
- 496122.066195614 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496122.066335856 WAKE num_fds:1
- 496122.066358799 FILL_AUDIO dev:8 hw_level:2192
- 496122.066359997 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.066361581 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.066365510 DEV_STREAM_MIX written:1024 read:1024
- 496122.066366071 WRITE_STREAMS_MIXED write_limit:1024
- 496122.066366697 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496122.066367615 STREAM_SLEEP_TIME id:140000 wake:000496122.087409210
- 496122.066372967 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496122.066373363 DEV_SLEEP_TIME dev:8 wake:000496122.133367189
- 496122.066374330 SLEEP sleep:000000000.021042021 longest_wake:000158140
- 496122.087471671 WAKE num_fds:0
- 496122.087493561 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496122.087517421 FILL_AUDIO dev:8 hw_level:2208
- 496122.087520754 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.087521140 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.087521987 WRITE_STREAMS_MIXED write_limit:0
- 496122.087524713 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496122.087531669 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496122.087532090 DEV_SLEEP_TIME dev:8 wake:000496122.133525760
- 496122.087533503 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496122.087705320 WAKE num_fds:1
- 496122.087739699 FILL_AUDIO dev:8 hw_level:2208
- 496122.087742245 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.087743899 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.087748465 DEV_STREAM_MIX written:1024 read:1024
- 496122.087749151 WRITE_STREAMS_MIXED write_limit:1024
- 496122.087750710 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496122.087752033 STREAM_SLEEP_TIME id:140000 wake:000496122.108742543
- 496122.087757781 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496122.087758202 DEV_SLEEP_TIME dev:8 wake:000496122.155084819
- 496122.087759490 SLEEP sleep:000000000.020991057 longest_wake:000158140
- 496122.108799368 WAKE num_fds:0
- 496122.108822551 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496122.108869730 FILL_AUDIO dev:8 hw_level:2176
- 496122.108877628 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.108877999 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.108881858 WRITE_STREAMS_MIXED write_limit:0
- 496122.108886479 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496122.108895164 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496122.108895585 DEV_SLEEP_TIME dev:8 wake:000496122.154221646
- 496122.108897805 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496122.109059453 WAKE num_fds:1
- 496122.109096789 FILL_AUDIO dev:8 hw_level:2176
- 496122.109100518 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.109105585 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.109113262 DEV_STREAM_MIX written:1024 read:1024
- 496122.109114079 WRITE_STREAMS_MIXED write_limit:1024
- 496122.109118204 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496122.109119286 STREAM_SLEEP_TIME id:140000 wake:000496122.130075876
- 496122.109126252 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496122.109126653 DEV_SLEEP_TIME dev:8 wake:000496122.175785456
- 496122.109127856 SLEEP sleep:000000000.020957086 longest_wake:000158140
- 496122.130119813 WAKE num_fds:0
- 496122.130140075 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496122.130163088 FILL_AUDIO dev:8 hw_level:2192
- 496122.130166421 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.130166792 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.130167639 WRITE_STREAMS_MIXED write_limit:0
- 496122.130170480 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496122.130177431 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496122.130177852 DEV_SLEEP_TIME dev:8 wake:000496122.175838254
- 496122.130179326 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496122.130282258 WAKE num_fds:1
- 496122.130303026 FILL_AUDIO dev:8 hw_level:2192
- 496122.130304109 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.130305512 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.130311125 DEV_STREAM_MIX written:1024 read:1024
- 496122.130311711 WRITE_STREAMS_MIXED write_limit:1024
- 496122.130312353 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496122.130313300 STREAM_SLEEP_TIME id:140000 wake:000496122.151409209
- 496122.130318647 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496122.130319053 DEV_SLEEP_TIME dev:8 wake:000496122.197312804
- 496122.130320116 SLEEP sleep:000000000.021096405 longest_wake:000158140
- 496122.151491150 WAKE num_fds:0
- 496122.151513712 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496122.151539091 FILL_AUDIO dev:8 hw_level:2208
- 496122.151542780 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.151543150 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.151544022 WRITE_STREAMS_MIXED write_limit:0
- 496122.151546684 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496122.151553564 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496122.151553985 DEV_SLEEP_TIME dev:8 wake:000496122.197547651
- 496122.151555409 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496122.151727611 WAKE num_fds:1
- 496122.151761519 FILL_AUDIO dev:8 hw_level:2208
- 496122.151764040 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.151765614 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.151770169 DEV_STREAM_MIX written:1024 read:1024
- 496122.151770876 WRITE_STREAMS_MIXED write_limit:1024
- 496122.151772395 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496122.151773642 STREAM_SLEEP_TIME id:140000 wake:000496122.172742542
- 496122.151779361 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496122.151779782 DEV_SLEEP_TIME dev:8 wake:000496122.219106479
- 496122.151781085 SLEEP sleep:000000000.020969396 longest_wake:000158140
- 496122.172792031 WAKE num_fds:0
- 496122.172815340 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2224
- 496122.172845539 FILL_AUDIO dev:8 hw_level:2176
- 496122.172849508 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.172849889 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.172850761 WRITE_STREAMS_MIXED write_limit:0
- 496122.172853217 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496122.172860223 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496122.172860644 DEV_SLEEP_TIME dev:8 wake:000496122.218187577
- 496122.172862143 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496122.173005714 WAKE num_fds:1
- 496122.173028998 FILL_AUDIO dev:8 hw_level:2176
- 496122.173029985 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.173031554 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.173037182 DEV_STREAM_MIX written:1024 read:1024
- 496122.173037808 WRITE_STREAMS_MIXED write_limit:1024
- 496122.173038429 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496122.173039507 STREAM_SLEEP_TIME id:140000 wake:000496122.194075875
- 496122.173045130 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496122.173045476 DEV_SLEEP_TIME dev:8 wake:000496122.239705692
- 496122.173046378 SLEEP sleep:000000000.021036849 longest_wake:000158140
- 496122.194116034 WAKE num_fds:0
- 496122.194140887 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496122.194162928 FILL_AUDIO dev:8 hw_level:2192
- 496122.194167077 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.194167443 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.194168390 WRITE_STREAMS_MIXED write_limit:0
- 496122.194171227 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496122.194178529 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496122.194178980 DEV_SLEEP_TIME dev:8 wake:000496122.239839035
- 496122.194181155 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496122.194266111 WAKE num_fds:1
- 496122.194291179 FILL_AUDIO dev:8 hw_level:2192
- 496122.194292136 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.194294035 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.194300290 DEV_STREAM_MIX written:1024 read:1024
- 496122.194300896 WRITE_STREAMS_MIXED write_limit:1024
- 496122.194301873 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496122.194302780 STREAM_SLEEP_TIME id:140000 wake:000496122.215409208
- 496122.194309255 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496122.194310062 DEV_SLEEP_TIME dev:8 wake:000496122.261302294
- 496122.194311440 SLEEP sleep:000000000.021106914 longest_wake:000158140
- 496122.215448777 WAKE num_fds:0
- 496122.215463923 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496122.215476895 FILL_AUDIO dev:8 hw_level:2208
- 496122.215478751 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.215478927 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.215479448 WRITE_STREAMS_MIXED write_limit:0
- 496122.215480831 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496122.215486357 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496122.215486562 DEV_SLEEP_TIME dev:8 wake:000496122.261481539
- 496122.215487384 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496122.215549002 WAKE num_fds:1
- 496122.215563098 FILL_AUDIO dev:8 hw_level:2208
- 496122.215563611 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.215565341 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.215567658 DEV_STREAM_MIX written:1024 read:1024
- 496122.215567938 WRITE_STREAMS_MIXED write_limit:1024
- 496122.215568239 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496122.215568747 STREAM_SLEEP_TIME id:140000 wake:000496122.236742541
- 496122.215573511 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496122.215573716 DEV_SLEEP_TIME dev:8 wake:000496122.282901820
- 496122.215574324 SLEEP sleep:000000000.021174054 longest_wake:000158140
- 496122.236813718 WAKE num_fds:0
- 496122.236830443 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496122.236848304 FILL_AUDIO dev:8 hw_level:2176
- 496122.236850592 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.236850766 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.236851211 WRITE_STREAMS_MIXED write_limit:0
- 496122.236853866 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496122.236859339 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496122.236859539 DEV_SLEEP_TIME dev:8 wake:000496122.282187883
- 496122.236860303 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496122.236957758 WAKE num_fds:1
- 496122.236979930 FILL_AUDIO dev:8 hw_level:2176
- 496122.236981687 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.236982827 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.236987199 DEV_STREAM_MIX written:1024 read:1024
- 496122.236987605 WRITE_STREAMS_MIXED write_limit:1024
- 496122.236988630 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496122.236989373 STREAM_SLEEP_TIME id:140000 wake:000496122.258075874
- 496122.236994623 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496122.236994884 DEV_SLEEP_TIME dev:8 wake:000496122.303655730
- 496122.236995656 SLEEP sleep:000000000.021086810 longest_wake:000158140
- 496122.258105114 WAKE num_fds:0
- 496122.258126969 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496122.258149697 FILL_AUDIO dev:8 hw_level:2192
- 496122.258153501 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.258153867 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.258154713 WRITE_STREAMS_MIXED write_limit:0
- 496122.258157274 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496122.258164351 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496122.258164817 DEV_SLEEP_TIME dev:8 wake:000496122.303825028
- 496122.258166230 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496122.258305507 WAKE num_fds:1
- 496122.258341639 FILL_AUDIO dev:8 hw_level:2192
- 496122.258343749 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.258345653 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.258351321 DEV_STREAM_MIX written:1024 read:1024
- 496122.258352123 WRITE_STREAMS_MIXED write_limit:1024
- 496122.258353306 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496122.258354649 STREAM_SLEEP_TIME id:140000 wake:000496122.279409207
- 496122.258361405 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496122.258361921 DEV_SLEEP_TIME dev:8 wake:000496122.325354028
- 496122.258363414 SLEEP sleep:000000000.021055179 longest_wake:000158140
- 496122.279475995 WAKE num_fds:0
- 496122.279498647 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496122.279522287 FILL_AUDIO dev:8 hw_level:2208
- 496122.279525795 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.279526166 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.279527153 WRITE_STREAMS_MIXED write_limit:0
- 496122.279529684 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496122.279536585 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496122.279537021 DEV_SLEEP_TIME dev:8 wake:000496122.325530666
- 496122.279538424 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496122.279679094 WAKE num_fds:1
- 496122.279712721 FILL_AUDIO dev:8 hw_level:2208
- 496122.279715312 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.279717558 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.279723471 DEV_STREAM_MIX written:1024 read:1024
- 496122.279724183 WRITE_STREAMS_MIXED write_limit:1024
- 496122.279725726 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496122.279727069 STREAM_SLEEP_TIME id:140000 wake:000496122.300742540
- 496122.279732808 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496122.279733229 DEV_SLEEP_TIME dev:8 wake:000496122.347059836
- 496122.279734562 SLEEP sleep:000000000.021016037 longest_wake:000158140
- 496122.300998522 WAKE num_fds:0
- 496122.301022512 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2176
- 496122.301051805 FILL_AUDIO dev:8 hw_level:2176
- 496122.301055604 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.301055969 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.301056836 WRITE_STREAMS_MIXED write_limit:0
- 496122.301059287 FILL_AUDIO_DONE hw_level:2176 total_written:0 min_cb_level:1024
- 496122.301066183 SET_DEV_WAKE dev:8 hw_level:2176 sleep:2176
- 496122.301066619 DEV_SLEEP_TIME dev:8 wake:000496122.346393648
- 496122.301068007 SLEEP sleep:000000000.045333333 longest_wake:000158140
- 496122.301254372 WAKE num_fds:1
- 496122.301290025 FILL_AUDIO dev:8 hw_level:2176
- 496122.301292946 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.301294495 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.301300178 DEV_STREAM_MIX written:1024 read:1024
- 496122.301300885 WRITE_STREAMS_MIXED write_limit:1024
- 496122.301302534 FILL_AUDIO_DONE hw_level:2176 total_written:1024 min_cb_level:1024
- 496122.301303781 STREAM_SLEEP_TIME id:140000 wake:000496122.322075873
- 496122.301309565 SET_DEV_WAKE dev:8 hw_level:3200 sleep:3200
- 496122.301309981 DEV_SLEEP_TIME dev:8 wake:000496122.367969956
- 496122.301311284 SLEEP sleep:000000000.020772583 longest_wake:000158140
- 496122.322353591 WAKE num_fds:0
- 496122.322376259 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2192
- 496122.322417509 FILL_AUDIO dev:8 hw_level:2192
- 496122.322421443 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.322421804 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.322422681 WRITE_STREAMS_MIXED write_limit:0
- 496122.322424981 FILL_AUDIO_DONE hw_level:2192 total_written:0 min_cb_level:1024
- 496122.322431852 SET_DEV_WAKE dev:8 hw_level:2192 sleep:2192
- 496122.322432273 DEV_SLEEP_TIME dev:8 wake:000496122.368092619
- 496122.322433771 SLEEP sleep:000000000.045666666 longest_wake:000158140
- 496122.322600105 WAKE num_fds:1
- 496122.322628852 FILL_AUDIO dev:8 hw_level:2192
- 496122.322631252 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.322633001 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.322638734 DEV_STREAM_MIX written:1024 read:1024
- 496122.322639617 WRITE_STREAMS_MIXED write_limit:1024
- 496122.322641145 FILL_AUDIO_DONE hw_level:2192 total_written:1024 min_cb_level:1024
- 496122.322642659 STREAM_SLEEP_TIME id:140000 wake:000496122.343409206
- 496122.322648953 SET_DEV_WAKE dev:8 hw_level:3216 sleep:3216
- 496122.322649474 DEV_SLEEP_TIME dev:8 wake:000496122.389642037
- 496122.322651183 SLEEP sleep:000000000.020767169 longest_wake:000158140
- 496122.343460464 WAKE num_fds:0
- 496122.343483111 WRITE_STREAMS_FETCH_STREAM id:140000 cbth:1024 delay:2208
- 496122.343504801 FILL_AUDIO dev:8 hw_level:2208
- 496122.343508630 WRITE_STREAMS_STREAM id:140000 shm_frames:0 cb_pending:1
- 496122.343508996 WRITE_STREAMS_MIX write_limit:0 max_offset:0
- 496122.343510093 WRITE_STREAMS_MIXED write_limit:0
- 496122.343512629 FILL_AUDIO_DONE hw_level:2208 total_written:0 min_cb_level:1024
- 496122.343519871 SET_DEV_WAKE dev:8 hw_level:2208 sleep:2208
- 496122.343520302 DEV_SLEEP_TIME dev:8 wake:000496122.389513687
- 496122.343521810 SLEEP sleep:000000000.046000000 longest_wake:000158140
- 496122.343659067 WAKE num_fds:1
- 496122.343692660 FILL_AUDIO dev:8 hw_level:2208
- 496122.343695401 WRITE_STREAMS_STREAM id:140000 shm_frames:1024 cb_pending:0
- 496122.343697170 WRITE_STREAMS_MIX write_limit:1024 max_offset:0
- 496122.343701300 DEV_STREAM_MIX written:1024 read:1024
- 496122.343702001 WRITE_STREAMS_MIXED write_limit:1024
- 496122.343703570 FILL_AUDIO_DONE hw_level:2208 total_written:1024 min_cb_level:1024
- 496122.343704858 STREAM_SLEEP_TIME id:140000 wake:000496122.364742539
- 496122.343710616 SET_DEV_WAKE dev:8 hw_level:3232 sleep:3232
- 496122.343711027 DEV_SLEEP_TIME dev:8 wake:000496122.411037640
- 496122.343712340 SLEEP sleep:000000000.021038232 longest_wake:000158140
- 496122.359904900 WAKE num_fds:1
- 496122.359908867 PB_MSG msg_id:6
- 496122.359909941 STREAM_REMOVED id:140000
- 496122.359939533 ODEV_NO_STREAMS dev:8 hw_level:2416 write:0
- 496122.359944076 SET_DEV_WAKE dev:8 hw_level:2416 sleep:1392
- 496122.359944442 DEV_SLEEP_TIME dev:8 wake:000496122.388940010
- 496122.359945062 SLEEP sleep:000000000.029000000 longest_wake:000158140
- 496122.388959912 WAKE num_fds:0
- 496122.388982707 ODEV_NO_STREAMS dev:8 hw_level:1024 write:1024
- 496122.388988021 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.388988288 DEV_SLEEP_TIME dev:8 wake:000496122.410316487
- 496122.388988949 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.410345296 WAKE num_fds:0
- 496122.410370857 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.410376456 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.410376727 DEV_SLEEP_TIME dev:8 wake:000496122.431704661
- 496122.410377434 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.431764840 WAKE num_fds:0
- 496122.431833959 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.431843690 SET_DEV_WAKE dev:8 hw_level:2000 sleep:976
- 496122.431844254 DEV_SLEEP_TIME dev:8 wake:000496122.452168375
- 496122.431845811 SLEEP sleep:000000000.020333333 longest_wake:000158140
- 496122.452219198 WAKE num_fds:0
- 496122.452281422 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.452292006 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.452292589 DEV_SLEEP_TIME dev:8 wake:000496122.473616205
- 496122.452294378 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.473669621 WAKE num_fds:0
- 496122.473700008 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.473706996 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.473707244 DEV_SLEEP_TIME dev:8 wake:000496122.495033989
- 496122.473708271 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.495074480 WAKE num_fds:0
- 496122.495131374 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.495146355 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.495147373 DEV_SLEEP_TIME dev:8 wake:000496122.516468874
- 496122.495150668 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.516543702 WAKE num_fds:0
- 496122.516620145 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.516634195 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.516634731 DEV_SLEEP_TIME dev:8 wake:000496122.537955861
- 496122.516638331 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.537993577 WAKE num_fds:0
- 496122.538015496 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.538021060 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.538021339 DEV_SLEEP_TIME dev:8 wake:000496122.559349272
- 496122.538022084 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.559371175 WAKE num_fds:0
- 496122.559406369 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.559412084 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.559412308 DEV_SLEEP_TIME dev:8 wake:000496122.580740216
- 496122.559413309 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.580803483 WAKE num_fds:0
- 496122.580876491 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.580892291 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.580892889 DEV_SLEEP_TIME dev:8 wake:000496122.602212271
- 496122.580896126 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.602249850 WAKE num_fds:0
- 496122.602273699 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.602279632 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.602279889 DEV_SLEEP_TIME dev:8 wake:000496122.623607597
- 496122.602281013 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.623630275 WAKE num_fds:0
- 496122.623652277 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.623657745 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.623657981 DEV_SLEEP_TIME dev:8 wake:000496122.644985979
- 496122.623658807 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.645029671 WAKE num_fds:0
- 496122.645048901 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.645052376 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.645052602 DEV_SLEEP_TIME dev:8 wake:000496122.666382558
- 496122.645053154 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.666591508 WAKE num_fds:0
- 496122.666610205 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.666613617 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.666613845 DEV_SLEEP_TIME dev:8 wake:000496122.687943859
- 496122.666614421 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.688006670 WAKE num_fds:0
- 496122.688026198 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.688029632 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.688029858 DEV_SLEEP_TIME dev:8 wake:000496122.709359852
- 496122.688030443 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.709414448 WAKE num_fds:0
- 496122.709440781 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.709446781 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.709447196 DEV_SLEEP_TIME dev:8 wake:000496122.730774701
- 496122.709448436 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.730857004 WAKE num_fds:0
- 496122.730888497 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.730895228 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.730895769 DEV_SLEEP_TIME dev:8 wake:000496122.752222632
- 496122.730897217 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.752337493 WAKE num_fds:0
- 496122.752370820 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.752377486 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.752378032 DEV_SLEEP_TIME dev:8 wake:000496122.773704945
- 496122.752379530 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.773777745 WAKE num_fds:0
- 496122.773809844 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.773816680 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.773817282 DEV_SLEEP_TIME dev:8 wake:000496122.795143924
- 496122.773818700 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.795180466 WAKE num_fds:0
- 496122.795213337 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.795220052 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.795220588 DEV_SLEEP_TIME dev:8 wake:000496122.816547467
- 496122.795222002 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.816655372 WAKE num_fds:0
- 496122.816688037 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.816694728 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.816695264 DEV_SLEEP_TIME dev:8 wake:000496122.838022122
- 496122.816696782 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.838272918 WAKE num_fds:0
- 496122.838308290 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.838314910 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.838315456 DEV_SLEEP_TIME dev:8 wake:000496122.859642410
- 496122.838316890 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.859692416 WAKE num_fds:0
- 496122.859724926 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.859731943 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.859732479 DEV_SLEEP_TIME dev:8 wake:000496122.881059061
- 496122.859733932 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.881167273 WAKE num_fds:0
- 496122.881200094 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.881206664 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.881207215 DEV_SLEEP_TIME dev:8 wake:000496122.902534184
- 496122.881208654 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.902785139 WAKE num_fds:0
- 496122.902814893 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.902821764 SET_DEV_WAKE dev:8 hw_level:2000 sleep:976
- 496122.902822315 DEV_SLEEP_TIME dev:8 wake:000496122.923148978
- 496122.902823743 SLEEP sleep:000000000.020333333 longest_wake:000158140
- 496122.923196282 WAKE num_fds:0
- 496122.923229584 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.923236269 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.923236810 DEV_SLEEP_TIME dev:8 wake:000496122.944563663
- 496122.923238234 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.944615625 WAKE num_fds:0
- 496122.944650330 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.944657045 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.944657587 DEV_SLEEP_TIME dev:8 wake:000496122.965984470
- 496122.944659050 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.966082719 WAKE num_fds:0
- 496122.966116547 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496122.966123342 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.966123884 DEV_SLEEP_TIME dev:8 wake:000496122.987450657
- 496122.966125332 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496122.987704348 WAKE num_fds:0
- 496122.987737645 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496122.987744150 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496122.987744631 DEV_SLEEP_TIME dev:8 wake:000496123.009071715
- 496122.987746020 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.009107139 WAKE num_fds:0
- 496123.009145457 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.009153220 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.009153892 DEV_SLEEP_TIME dev:8 wake:000496123.030479863
- 496123.009155841 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.030584265 WAKE num_fds:0
- 496123.030618043 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.030624739 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.030625275 DEV_SLEEP_TIME dev:8 wake:000496123.051952138
- 496123.030626703 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.052094028 WAKE num_fds:0
- 496123.052127385 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.052134070 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.052134606 DEV_SLEEP_TIME dev:8 wake:000496123.073461509
- 496123.052136040 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.073511516 WAKE num_fds:0
- 496123.073544643 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.073551248 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.073551789 DEV_SLEEP_TIME dev:8 wake:000496123.094878732
- 496123.073553217 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.094926450 WAKE num_fds:0
- 496123.094961846 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.094968617 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.094969168 DEV_SLEEP_TIME dev:8 wake:000496123.116295946
- 496123.094970737 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.116406874 WAKE num_fds:0
- 496123.116439890 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.116446710 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.116447252 DEV_SLEEP_TIME dev:8 wake:000496123.137774020
- 496123.116448730 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.137883404 WAKE num_fds:0
- 496123.137916390 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.137923126 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.137923672 DEV_SLEEP_TIME dev:8 wake:000496123.159250490
- 496123.137925111 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.159287924 WAKE num_fds:0
- 496123.159335483 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.159343406 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.159344138 DEV_SLEEP_TIME dev:8 wake:000496123.180669833
- 496123.159346042 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.180704931 WAKE num_fds:0
- 496123.180736895 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.180743866 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.180744402 DEV_SLEEP_TIME dev:8 wake:000496123.202071140
- 496123.180745821 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.202319259 WAKE num_fds:0
- 496123.202364484 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.202371294 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.202371830 DEV_SLEEP_TIME dev:8 wake:000496123.223698598
- 496123.202373279 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.223730915 WAKE num_fds:0
- 496123.223763370 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.223770086 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.223770622 DEV_SLEEP_TIME dev:8 wake:000496123.245097470
- 496123.223772065 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.245148129 WAKE num_fds:0
- 496123.245184318 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.245190958 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.245191494 DEV_SLEEP_TIME dev:8 wake:000496123.266518437
- 496123.245192887 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.266776098 WAKE num_fds:0
- 496123.266809636 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.266817093 SET_DEV_WAKE dev:8 hw_level:2000 sleep:976
- 496123.266817634 DEV_SLEEP_TIME dev:8 wake:000496123.287143786
- 496123.266819078 SLEEP sleep:000000000.020333333 longest_wake:000158140
- 496123.287397671 WAKE num_fds:0
- 496123.287432130 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.287438836 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.287439367 DEV_SLEEP_TIME dev:8 wake:000496123.308766250
- 496123.287440785 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.308870132 WAKE num_fds:0
- 496123.308903564 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.308910340 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.308910881 DEV_SLEEP_TIME dev:8 wake:000496123.330237814
- 496123.308912360 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.330308465 WAKE num_fds:0
- 496123.330350260 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.330356966 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.330357512 DEV_SLEEP_TIME dev:8 wake:000496123.351684385
- 496123.330358955 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.351937251 WAKE num_fds:0
- 496123.351970653 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.351977293 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.351977825 DEV_SLEEP_TIME dev:8 wake:000496123.373304743
- 496123.351979268 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.373411526 WAKE num_fds:0
- 496123.373445334 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.373452009 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.373452550 DEV_SLEEP_TIME dev:8 wake:000496123.394779408
- 496123.373453984 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.395033698 WAKE num_fds:0
- 496123.395067641 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.395074336 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.395074883 DEV_SLEEP_TIME dev:8 wake:000496123.416401736
- 496123.395076306 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.416466100 WAKE num_fds:0
- 496123.416499903 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.416506809 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.416507341 DEV_SLEEP_TIME dev:8 wake:000496123.437833978
- 496123.416508784 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.437920547 WAKE num_fds:0
- 496123.437948816 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.437954655 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.437955070 DEV_SLEEP_TIME dev:8 wake:000496123.459282732
- 496123.437956175 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.459515811 WAKE num_fds:0
- 496123.459544842 ODEV_NO_STREAMS dev:8 hw_level:1040 write:1008
- 496123.459550812 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.459551220 DEV_SLEEP_TIME dev:8 wake:000496123.480878732
- 496123.459552302 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.481115112 WAKE num_fds:0
- 496123.481142011 ODEV_NO_STREAMS dev:8 hw_level:992 write:1056
- 496123.481147923 SET_DEV_WAKE dev:8 hw_level:2048 sleep:1024
- 496123.481148342 DEV_SLEEP_TIME dev:8 wake:000496123.502475931
- 496123.481149428 SLEEP sleep:000000000.021333333 longest_wake:000158140
- 496123.488698368 WAKE num_fds:1
- 496123.488701940 PB_MSG msg_id:5
diff --git a/scripts/audio_thread_log_viewer/viewer_c3.py b/scripts/audio_thread_log_viewer/viewer_c3.py
deleted file mode 100755
index f8d4f57a..00000000
--- a/scripts/audio_thread_log_viewer/viewer_c3.py
+++ /dev/null
@@ -1,604 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright 2016 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-
-"""Generates an HTML file with plot of buffer level in the audio thread log."""
-
-import argparse
-import collections
-import logging
-import string
-import time
-
-page_content = string.Template("""
-<html meta charset="UTF8">
-<head>
- <!-- Load c3.css -->
- <link href="https://rawgit.com/masayuki0812/c3/master/c3.css" rel="stylesheet" type="text/css">
- <!-- Load d3.js and c3.js -->
- <script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
- <script src="https://rawgit.com/masayuki0812/c3/master/c3.js" charset="utf-8"></script>
- <style type="text/css">
- .c3-grid text {
- fill: grey;
- }
- .event_log_box {
- font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace;
- font-size: 20px;
- font-style: normal;
- font-variant: normal;
- font-weight: 300;
- line-height: 26.4px;
- white-space: pre;
- height:50%;
- width:48%;
- border:1px solid #ccc;
- overflow:auto;
- }
- .checkbox {
- font-size: 30px;
- border: 2px;
- }
- .device {
- font-size: 15px;
- }
- .stream{
- font-size: 15px;
- }
- .fetch{
- }
- .wake{
- }
- </style>
- <script type="text/javascript">
- var selected = null;
- draw_chart = function() {
- var chart = c3.generate({
- data: {
- x: 'time',
- columns: [
- ['time', $times],
- ['buffer_level', $buffer_levels],
- ],
- type: 'bar',
- types: {
- buffer_level: 'line',
- },
- onclick: function (d, i) {
- elm = document.getElementById(d.x.toFixed(9));
- if (selected)
- selected.style.color = '';
- if (elm === null) {
- console.error("Can not find element by ID %s", d.x.toFixed(9));
- return;
- }
- elm.style.color = 'blue';
- elm.scrollIntoView();
- selected = elm;
- },
- },
- zoom: {
- enabled: true,
- },
-
- grid: {
- x: {
- lines: [
- $grids,
- ],
- },
- },
-
- axis: {
- y: {min: 0, max: $max_y},
- },
- });
- };
-
- logs = `$logs`;
- put_logs = function () {
- document.getElementById('logs').innerHTML = logs;
- };
-
- set_initial_checkbox_value = function () {
- document.getElementById('device').checked = true;
- document.getElementById('stream').checked = true;
- document.getElementById('fetch').checked = true;
- document.getElementById('wake').checked = true;
- }
-
- window.onload = function() {
- draw_chart();
- put_logs();
- set_initial_checkbox_value();
- };
-
- function handleClick(checkbox) {
- var class_name = checkbox.id;
- var elements = document.getElementsByClassName(class_name);
- var i;
-
- if (checkbox.checked) {
- display_value = "block";
- } else {
- display_value = "none"
- }
-
- console.log("change " + class_name + " to " + display_value);
- for (i = 0; i < elements.length; i++) {
- elements[i].style.display = display_value;
- }
- }
-
- </script>
-</head>
-
-<body>
- <div id="chart" style="height:50%; width:100%" ></div>
- <div style="margin:0 auto"; class="checkbox">
- <label><input type="checkbox" onclick="handleClick(this);" id="device">Show device removed/added event</label>
- <label><input type="checkbox" onclick="handleClick(this);" id="stream">Show stream removed/added event</label>
- <label><input type="checkbox" onclick="handleClick(this);" id="fetch">Show fetch event</label>
- <label><input type="checkbox" onclick="handleClick(this);" id="wake">Show wake by num_fds=1 event</label>
- </div>
- <div class="event_log_box", id="logs", style="float:left;"></div>
- <textarea class="event_log_box", id="text", style="float:right;"></textarea>
-</body>
-</html>
-""")
-
-
-def StrToTimestamp(s):
- """Converts a time string to a timestamp.
-
- @param s: A time string like "2019-07-02T15:30:46.684190644".
-
- @returns: Returns a timestamp string like "55846.684190644".
-
- """
- fmt = "%Y-%m-%dT%H:%M:%S"
- t = time.strptime(s[:-10], fmt)
- # Ignore date to avoid a long timestamp.
- ts = t.tm_hour * 3600 + t.tm_min * 60 + t.tm_sec
- return "{:d}.{}".format(ts, s[-9:])
-
-
-Tag = collections.namedtuple('Tag', ['time', 'text', 'position', 'class_name'])
-"""
-The tuple for tags shown on the plot on certain time.
-text is the tag to show, position is the tag position, which is one of
-'start', 'middle', 'end', class_name is one of 'device', 'stream', 'fetch',
-and 'wake' which will be their CSS class name.
-"""
-
-class EventData(object):
- """The base class of an event."""
- def __init__(self, time, name):
- """Initializes an EventData.
-
- @param time: A string for event time.
- @param name: A string for event name.
-
- """
- self.time = time
- self.name = name
- self._text = None
- self._position = None
- self._class_name = None
-
- def GetTag(self):
- """Gets the tag for this event.
-
- @returns: A Tag object. Returns None if no need to show tag.
-
- """
- if self._text:
- return Tag(
- time=self.time, text=self._text, position=self._position,
- class_name=self._class_name)
- return None
-
-
-class DeviceEvent(EventData):
- """Class for device event."""
- def __init__(self, time, name, device):
- """Initializes a DeviceEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param device: A string for device index.
-
- """
- super(DeviceEvent, self).__init__(time, name)
- self.device = device
- self._position = 'start'
- self._class_name = 'device'
-
-
-class DeviceRemovedEvent(DeviceEvent):
- """Class for device removed event."""
- def __init__(self, time, name, device):
- """Initializes a DeviceRemovedEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param device: A string for device index.
-
- """
- super(DeviceRemovedEvent, self).__init__(time, name, device)
- self._text = 'Removed Device %s' % self.device
-
-
-class DeviceAddedEvent(DeviceEvent):
- """Class for device added event."""
- def __init__(self, time, name, device):
- """Initializes a DeviceAddedEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param device: A string for device index.
-
- """
- super(DeviceAddedEvent, self).__init__(time, name, device)
- self._text = 'Added Device %s' % self.device
-
-
-class LevelEvent(DeviceEvent):
- """Class for device event with buffer level."""
- def __init__(self, time, name, device, level):
- """Initializes a LevelEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param device: A string for device index.
- @param level: An int for buffer level.
-
- """
- super(LevelEvent, self).__init__(time, name, device)
- self.level = level
-
-
-class StreamEvent(EventData):
- """Class for event with stream."""
- def __init__(self, time, name, stream):
- """Initializes a StreamEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param stream: A string for stream id.
-
- """
- super(StreamEvent, self).__init__(time, name)
- self.stream = stream
- self._class_name = 'stream'
-
-
-class FetchStreamEvent(StreamEvent):
- """Class for stream fetch event."""
- def __init__(self, time, name, stream):
- """Initializes a FetchStreamEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param stream: A string for stream id.
-
- """
- super(FetchStreamEvent, self).__init__(time, name, stream)
- self._text = 'Fetch %s' % self.stream
- self._position = 'end'
- self._class_name = 'fetch'
-
-
-class StreamAddedEvent(StreamEvent):
- """Class for stream added event."""
- def __init__(self, time, name, stream):
- """Initializes a StreamAddedEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param stream: A string for stream id.
-
- """
- super(StreamAddedEvent, self).__init__(time, name, stream)
- self._text = 'Add stream %s' % self.stream
- self._position = 'middle'
-
-
-class StreamRemovedEvent(StreamEvent):
- """Class for stream removed event."""
- def __init__(self, time, name, stream):
- """Initializes a StreamRemovedEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param stream: A string for stream id.
-
- """
- super(StreamRemovedEvent, self).__init__(time, name, stream)
- self._text = 'Remove stream %s' % self.stream
- self._position = 'middle'
-
-
-class WakeEvent(EventData):
- """Class for wake event."""
- def __init__(self, time, name, num_fds):
- """Initializes a WakeEvent.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param num_fds: A string for number of fd that wakes audio thread up.
-
- """
- super(WakeEvent, self).__init__(time, name)
- self._position = 'middle'
- self._class_name = 'wake'
- if num_fds != '0':
- self._text = 'num_fds %s' % num_fds
-
-
-class C3LogWriter(object):
- """Class to handle event data and fill an HTML page using c3.js library"""
- def __init__(self):
- """Initializes a C3LogWriter."""
- self.times = []
- self.buffer_levels = []
- self.tags = []
- self.max_y = 0
-
- def AddEvent(self, event):
- """Digests an event.
-
- Add a tag if this event needs to be shown on grid.
- Add a buffer level data into buffer_levels if this event has buffer
- level.
-
- @param event: An EventData object.
-
- """
- tag = event.GetTag()
- if tag:
- self.tags.append(tag)
-
- if isinstance(event, LevelEvent):
- self.times.append(event.time)
- self.buffer_levels.append(str(event.level))
- if event.level > self.max_y:
- self.max_y = event.level
- logging.debug('add data for a level event %s: %s',
- event.time, event.level)
-
- if (isinstance(event, DeviceAddedEvent) or
- isinstance(event, DeviceRemovedEvent)):
- self.times.append(event.time)
- self.buffer_levels.append('null')
-
- def _GetGrids(self):
- """Gets the content to be filled for grids.
-
- @returns: A str for grid with format:
- '{value: time1, text: "tag1", position: "position1"},
- {value: time1, text: "tag1"},...'
-
- """
- grids = []
- for tag in self.tags:
- content = ('{value: %s, text: "%s", position: "%s", '
- 'class: "%s"}') % (
- tag.time, tag.text, tag.position, tag.class_name)
- grids.append(content)
- grids_joined = ', '.join(grids)
- return grids_joined
-
- def FillPage(self, page_template):
- """Fills in the page template with content.
-
- @param page_template: A string for HTML page content with variables
- to be filled.
-
- @returns: A string for filled page.
-
- """
- times = ', '.join(self.times)
- buffer_levels = ', '.join(self.buffer_levels)
- grids = self._GetGrids()
- filled = page_template.safe_substitute(
- times=times,
- buffer_levels=buffer_levels,
- grids=grids,
- max_y=str(self.max_y))
- return filled
-
-
-class EventLogParser(object):
- """Class for event log parser."""
- def __init__(self):
- """Initializes an EventLogParse."""
- self.parsed_events = []
-
- def AddEventLog(self, event_log):
- """Digests a line of event log.
-
- @param event_log: A line for event log.
-
- """
- event = self._ParseOneLine(event_log)
- if event:
- self.parsed_events.append(event)
-
- def GetParsedEvents(self):
- """Gets the list of parsed events.
-
- @returns: A list of parsed EventData.
-
- """
- return self.parsed_events
-
- def _ParseOneLine(self, line):
- """Parses one line of event log.
-
- Split a line like
- 2019-07-02T15:30:46.683829810 cras atlog WRITE_STREAMS_FETCH_STREAM id:1e0000 cbth:512 delay:1136
- into time, name, and props where
- time = '54946.683829810'
- name = 'WRITE_STREAMS_FETCH_STREAM'
- props = {
- 'id': 0,
- 'cb_th': 512,
- 'delay': 1136
- }
-
- @param line: A line of event log.
-
- @returns: A EventData object.
-
- """
- line_split = line.split()
- time, name = StrToTimestamp(line_split[0]), line_split[3]
- logging.debug('time: %s, name: %s', time, name)
- props = {}
- for index in xrange(4, len(line_split)):
- key, value = line_split[index].split(':')[:2]
- props[key] = value
- logging.debug('props: %s', props)
- return self._CreateEventData(time, name, props)
-
- def _CreateEventData(self, time, name, props):
- """Creates an EventData based on event name.
-
- @param time: A string for event time.
- @param name: A string for event name.
- @param props: A dict for event properties.
-
- @returns: A EventData object.
-
- """
- if name == 'WRITE_STREAMS_FETCH_STREAM':
- return FetchStreamEvent(time, name, stream=props['id'])
- if name == 'STREAM_ADDED':
- return StreamAddedEvent(time, name, stream=props['id'])
- if name == 'STREAM_REMOVED':
- return StreamRemovedEvent(time, name, stream=props['id'])
- if name in ['FILL_AUDIO', 'SET_DEV_WAKE']:
- return LevelEvent(
- time, name, device=props['dev'],
- level=int(props['hw_level']))
- if name == 'DEV_ADDED':
- return DeviceAddedEvent(time, name, device=props['dev'])
- if name == 'DEV_REMOVED':
- return DeviceRemovedEvent(time, name, device=props['dev'])
- if name == 'WAKE':
- return WakeEvent(time, name, num_fds=props['num_fds'])
- return None
-
-
-class AudioThreadLogParser(object):
- """Class for audio thread log parser."""
- def __init__(self, path):
- """Initializes an AudioThreadLogParser.
-
- @param path: The audio thread log file path.
-
- """
- self.path = path
- self.content = None
-
- def Parse(self):
- """Prases the audio thread logs.
-
- @returns: A list of event log lines.
-
- """
- logging.debug('Using file: %s', self.path)
- with open(self.path, 'r') as f:
- self.content = f.read().splitlines()
-
- # Event logs starting at two lines after 'Audio Thread Event Log'.
- index_start = self.content.index('Audio Thread Event Log:') + 2
- # If input is from audio_diagnostic result, use aplay -l line to find
- # the end of audio thread event logs.
- try:
- index_end = self.content.index('=== aplay -l ===')
- except ValueError:
- logging.debug(
- 'Can not find aplay line. This is not from diagnostic')
- index_end = len(self.content)
- event_logs = self.content[index_start:index_end]
- logging.info('Parsed %s log events', len(event_logs))
- return event_logs
-
- def FillLogs(self, page_template):
- """Fills the HTML page template with contents for audio thread logs.
-
- @param page_template: A string for HTML page content with log variable
- to be filled.
-
- @returns: A string for filled page.
-
- """
- logs = []
- for s in self.content:
- if 'atlog' in s:
- time = StrToTimestamp(s.split()[0])
- logs.append('<label id="{}">{}</label>'.format(time, s))
- else:
- logs.append(s)
- logs = '\n'.join(logs)
-
- return page_template.substitute(logs=logs)
-
-
-def ParseArgs():
- """Parses the arguments.
-
- @returns: The namespace containing parsed arguments.
-
- """
- parser = argparse.ArgumentParser(
- description='Draw time chart from audio thread log',
- formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser.add_argument('FILE', type=str, help='The audio thread log file')
- parser.add_argument('-o', type=str, dest='output',
- default='view.html', help='The output HTML file')
- parser.add_argument('-d', dest='debug', action='store_true',
- default=False, help='Show debug message')
- return parser.parse_args()
-
-
-def Main():
- """The Main program."""
- options = ParseArgs()
- logging.basicConfig(
- format='%(asctime)s:%(levelname)s:%(message)s',
- level=logging.DEBUG if options.debug else logging.INFO)
-
- # Gets lines of event logs.
- audio_thread_log_parser = AudioThreadLogParser(options.FILE)
- event_logs = audio_thread_log_parser.Parse()
-
- # Parses event logs into events.
- event_log_parser = EventLogParser()
- for event_log in event_logs:
- event_log_parser.AddEventLog(event_log)
- events = event_log_parser.GetParsedEvents()
-
- # Reads in events in preparation of filling HTML template.
- c3_writer = C3LogWriter()
- for event in events:
- c3_writer.AddEvent(event)
-
- # Fills in buffer level chart.
- page_content_with_chart = c3_writer.FillPage(page_content)
-
- # Fills in audio thread log into text box.
- page_content_with_chart_and_logs = audio_thread_log_parser.FillLogs(
- string.Template(page_content_with_chart))
-
- with open(options.output, 'w') as f:
- f.write(page_content_with_chart_and_logs)
-
-
-if __name__ == '__main__':
- Main()
diff --git a/scripts/audio_tuning/conf2ini2.py b/scripts/audio_tuning/conf2ini2.py
deleted file mode 100755
index 476ffd56..00000000
--- a/scripts/audio_tuning/conf2ini2.py
+++ /dev/null
@@ -1,166 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-#
-# convert audio.conf from the audio tuning UI to dsp.ini which can be
-# accepted by cras eq/drc plugin.
-
-import json
-import sys
-import fnmatch
-
-biquad_type_name = [
- "none",
- "lowpass",
- "highpass",
- "bandpass",
- "lowshelf",
- "highshelf",
- "peaking",
- "notch",
- "allpass"
- ]
-
-header = """\
-[output_source]
-library=builtin
-label=source
-purpose=playback
-disable=(not (equal? dsp_name "speaker_eq"))
-output_0={src:0}
-output_1={src:1}
-
-[output_sink]
-library=builtin
-label=sink
-purpose=playback
-input_0={dst:0}
-input_1={dst:1}"""
-
-drc_header = """\
-[drc]
-library=builtin
-label=drc
-input_0={%s:0}
-input_1={%s:1}
-output_2={%s:0}
-output_3={%s:1}
-input_4=%-7d ; emphasis_disabled"""
-
-drc_param = """\
-input_%d=%-7g ; f
-input_%d=%-7g ; enable
-input_%d=%-7g ; threshold
-input_%d=%-7g ; knee
-input_%d=%-7g ; ratio
-input_%d=%-7g ; attack
-input_%d=%-7g ; release
-input_%d=%-7g ; boost"""
-
-eq_header = """\
-[eq2]
-library=builtin
-label=eq2
-input_0={%s:0}
-input_1={%s:1}
-output_2={%s:0}
-output_3={%s:1}"""
-
-eq_param = """\
-input_%d=%-7d ; %s
-input_%d=%-7g ; freq
-input_%d=%-7g ; Q
-input_%d=%-7g ; gain"""
-
-def is_true(d, pattern):
- for k in d:
- if fnmatch.fnmatch(k, pattern) and d[k]:
- return True
- return False
-
-def intermediate_name(index):
- return 'intermediate' + ('' if index == 1 else str(index))
-
-def main():
- f = open(sys.argv[1])
- d = json.loads(f.read())
- print header
-
- has_drc = is_true(d, 'global.enable_drc') and is_true(d, 'drc.*.enable')
- has_eq = is_true(d, 'global.enable_eq') and is_true(d, 'eq.*.*.enable')
-
- stages = []
- if has_drc:
- stages.append(print_drc)
- if has_eq:
- stages.append(print_eq)
-
- if is_true(d, 'global.enable_swap') and len(stages) >= 2:
- stages[0], stages[1] = stages[1], stages[0]
-
- for i in range(len(stages)):
- print
- src = 'src' if i == 0 else intermediate_name(i)
- dst = 'dst' if i == len(stages) - 1 else intermediate_name(i + 1)
- stages[i](d, src, dst)
-
-def print_drc(d, src, dst):
- print drc_header % (src, src, dst, dst, int(d['drc.emphasis_disabled']))
- n = 5
- for i in range(3):
- prefix = 'drc.%d.' % i
- f = d[prefix + 'f']
- enable = int(d[prefix + 'enable'])
- threshold = d[prefix + 'threshold']
- knee = d[prefix + 'knee']
- ratio = d[prefix + 'ratio']
- attack = d[prefix + 'attack']
- release = d[prefix + 'release']
- boost = d[prefix + 'boost']
-
- print drc_param % (n, f,
- n+1, enable,
- n+2, threshold,
- n+3, knee,
- n+4, ratio,
- n+5, attack,
- n+6, release,
- n+7, boost)
- n += 8
-
-# Returns two sorted lists, each one contains the enabled eq index for a channel
-def enabled_eq(d):
- eeq = [[], []]
- for k in d:
- s = k.split('.')
- if s[0] == 'eq' and s[3] == 'enable' and d[k]:
- ch_index = int(s[1])
- eq_num = int(s[2])
- eeq[ch_index].append(eq_num)
- return sorted(eeq[0]), sorted(eeq[1])
-
-def print_eq(d, src, dst):
- print eq_header % (src, src, dst, dst)
- eeq = enabled_eq(d)
- eeqn = max(len(eeq[0]), len(eeq[1]))
- n = 4 # the first input index
- for i in range(0, eeqn):
- for ch in (0, 1):
- if i < len(eeq[ch]):
- prefix = 'eq.%d.%d.' % (ch, eeq[ch][i])
- type_name = d[prefix + 'type']
- type_index = biquad_type_name.index(type_name)
- f = d[prefix + 'freq']
- q = d[prefix + 'q']
- g = d[prefix + 'gain']
- else:
- type_name = 'none';
- type_index = 0;
- f = q = g = 0
- print eq_param % (n, type_index, type_name,
- n+1, f, n+2, q, n+3, g)
- n += 4
-
-main()
diff --git a/scripts/audio_tuning/frontend/LICENSE b/scripts/audio_tuning/frontend/LICENSE
deleted file mode 100644
index 0aa7fc93..00000000
--- a/scripts/audio_tuning/frontend/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2006-2009 The Chromium OS Authors. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/scripts/audio_tuning/frontend/app.yaml b/scripts/audio_tuning/frontend/app.yaml
deleted file mode 100644
index 1706e05f..00000000
--- a/scripts/audio_tuning/frontend/app.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-application: audio-tuning
-version: 1
-runtime: python27
-api_version: 1
-threadsafe: true
-
-handlers:
-- url: /(.*\.css)
- mime_type: text/css
- static_files: \1
- upload: (.*\.css)
-
-- url: /(.*\.html)
- mime_type: text/html
- static_files: \1
- upload: (.*\.html)
-
-- url: /(.*\.js)
- mime_type: text/javascript
- static_files: \1
- upload: (.*\.js)
-
-- url: /(LICENSE)
- mime_type: text/plain
- static_files: \1
- upload: (LICENSE)
-
-- url: /
- static_files: audio.html
- upload: audio.html
diff --git a/scripts/audio_tuning/frontend/audio.css b/scripts/audio_tuning/frontend/audio.css
deleted file mode 100644
index 36ee14b9..00000000
--- a/scripts/audio_tuning/frontend/audio.css
+++ /dev/null
@@ -1,88 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-body {
- font-family: sans-serif;
- text-align: center;
-}
-
-#audio_source_url {
- border: 1px solid rgb(144,184,222);
- font-size: large;
-}
-
-.nbox
-{
- border: 1px solid rgb(144,184,222);
- text-align:right;
- position:relative;
- padding: 2px;
-}
-
-.nslider
-{
- width: 175px;
- margin-left: 6px;
-}
-
-.drc_data
-{
- border: solid 1px gray;
- border-radius: 5px;
- display: inline-block;
- padding: 10px;
- margin: 6px;
- width: 370px;
-}
-
-.eq_data {
- border: solid 1px black;
- display: inline-block;
- padding: 10px;
- margin: 6px;
-}
-
-.drc_curve {
- border: 1px solid blue;
- width: 240px;
- height: 180px;
-}
-
-.eq_curve {
- border: 1px solid blue;
- width: 960px;
- height: 270px;
- position: absolute;
- left: 0;
- top: 0;
-}
-
-.eq_curve_parent {
- width: 960px;
- height: 270px;
- margin: 0 auto;
- position: relative;
-}
-
-.enable_check {
- float: right;
- margin: -6px -6px;
-}
-
-.eq_table {
- display: inline-block;
- margin-right: 6px;
-}
-
-#config_file {
- border: 1px solid rgb(144,184,222);
- padding: 2px;
-}
-
-.biquad_type_select {
- background: transparent;
- border: 1px solid rgb(144,184,222);
- padding: 2px;
-}
diff --git a/scripts/audio_tuning/frontend/audio.html b/scripts/audio_tuning/frontend/audio.html
deleted file mode 100644
index cf531983..00000000
--- a/scripts/audio_tuning/frontend/audio.html
+++ /dev/null
@@ -1,54 +0,0 @@
-<!-- Copyright (c) 2013 The Chromium OS Authors. All rights reserved. -->
-<!-- Use of this source code is governed by a BSD-style license that can be -->
-<!-- found in the LICENSE file. -->
-
-<html>
- <head>
- <TITLE>Audio Tuning</TITLE>
- <link rel="stylesheet" href="audio.css" type="text/css">
- <script type="text/javascript" src="audio.js"></script>
- <script type="text/javascript" src="setup_credential.js"></script>
- <script type="text/javascript" src="google_drive_picker.js"></script>
- <script src="https://apis.google.com/js/client.js?onload=onGoogleClientApiLoad"></script>
- </head>
- <h1> Audio Source </h1>
- URL: <input size=100 id="audio_source_url" list=samples autofocus=autofocus
- onchange="audio_source_set(this.value)"> </input>
- <!-- Put your audio clip list here
- <select id=samples onchange="audio_source_select(this)">
- <option value="http://www.example.com/audio/clip1.wav">clip1</option>
- <option value="http://www.example.com/audio/clip2.ogg">clip2</option>
- </select>
- -->
- <input type=button value='Local Audio File' onclick="load_audio()"> </input>
- <input type=button id='google_drive_pick_file' value='Select File from Google Drive' disable> </input>
- <p></p>
- <span id=audio_player_container>
- <audio controls="controls" id="audio_player" loop=loop
- oncanplay="audio_source_canplay()"> </audio>
- </span>
- <span id=audio_loading style='visibility:hidden;color:#e59700'>Loading...</span>
- <span id="global_section">
- </span>
-
- <input type=button value='Save Config' onclick="save_config()" id=save_config disabled> </input>
- <input type=button value='Load Config' onclick="load_config()"> </input>
- <div style="display:none">
- <input type=file id=config_file onchange="config_file_changed()">
- <input type=file id=audio_file onchange="audio_file_changed()">
- <a id=save_config_anchor></a>
- </div>
-
- <h1> DRC </h1>
- <div id="drc_section">
- </div>
- <h1> EQ Left </h1>
- <div id="eq_left_section">
- </div>
- <h1> EQ Right </h1>
- <div id="eq_right_section">
- </div>
- <body>
- </body>
-</html>
-<html>
diff --git a/scripts/audio_tuning/frontend/audio.js b/scripts/audio_tuning/frontend/audio.js
deleted file mode 100644
index 98870cdd..00000000
--- a/scripts/audio_tuning/frontend/audio.js
+++ /dev/null
@@ -1,1994 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* This is a program for tuning audio using Web Audio API. The processing
- * pipeline looks like this:
- *
- * INPUT
- * |
- * +------------+
- * | crossover |
- * +------------+
- * / | \
- * (low band) (mid band) (high band)
- * / | \
- * +------+ +------+ +------+
- * | DRC | | DRC | | DRC |
- * +------+ +------+ +------+
- * \ | /
- * \ | /
- * +-------------+
- * | (+) |
- * +-------------+
- * | |
- * (left) (right)
- * | |
- * +----+ +----+
- * | EQ | | EQ |
- * +----+ +----+
- * | |
- * +----+ +----+
- * | EQ | | EQ |
- * +----+ +----+
- * . .
- * . .
- * +----+ +----+
- * | EQ | | EQ |
- * +----+ +----+
- * \ /
- * \ /
- * |
- * / \
- * / \
- * +-----+ +-----+
- * | FFT | | FFT | (for visualization only)
- * +-----+ +-----+
- * \ /
- * \ /
- * |
- * OUTPUT
- *
- * The parameters of each DRC and EQ can be adjusted or disabled independently.
- *
- * If enable_swap is set to true, the order of the DRC and the EQ stages are
- * swapped (EQ is applied first, then DRC).
- */
-
-/* The GLOBAL state has following parameters:
- * enable_drc - A switch to turn all DRC on/off.
- * enable_eq - A switch to turn all EQ on/off.
- * enable_fft - A switch to turn visualization on/off.
- * enable_swap - A switch to swap the order of EQ and DRC stages.
- */
-
-/* The DRC has following parameters:
- * f - The lower frequency of the band, in Hz.
- * enable - 1 to enable the compressor, 0 to disable it.
- * threshold - The value above which the compression starts, in dB.
- * knee - The value above which the knee region starts, in dB.
- * ratio - The input/output dB ratio after the knee region.
- * attack - The time to reduce the gain by 10dB, in seconds.
- * release - The time to increase the gain by 10dB, in seconds.
- * boost - The static boost value in output, in dB.
- */
-
-/* The EQ has following parameters:
- * enable - 1 to enable the eq, 0 to disable it.
- * type - The type of the eq, the available values are 'lowpass', 'highpass',
- * 'bandpass', 'lowshelf', 'highshelf', 'peaking', 'notch'.
- * freq - The frequency of the eq, in Hz.
- * q, gain - The meaning depends on the type of the filter. See Web Audio API
- * for details.
- */
-
-/* The initial values of parameters for GLOBAL, DRC and EQ */
-var INIT_GLOBAL_ENABLE_DRC = true;
-var INIT_GLOBAL_ENABLE_EQ = true;
-var INIT_GLOBAL_ENABLE_FFT = true;
-var INIT_GLOBAL_ENABLE_SWAP = false;
-var INIT_DRC_XO_LOW = 200;
-var INIT_DRC_XO_HIGH = 2000;
-var INIT_DRC_ENABLE = true;
-var INIT_DRC_THRESHOLD = -24;
-var INIT_DRC_KNEE = 30;
-var INIT_DRC_RATIO = 12;
-var INIT_DRC_ATTACK = 0.003;
-var INIT_DRC_RELEASE = 0.250;
-var INIT_DRC_BOOST = 0;
-var INIT_EQ_ENABLE = true;
-var INIT_EQ_TYPE = 'peaking';
-var INIT_EQ_FREQ = 350;
-var INIT_EQ_Q = 1;
-var INIT_EQ_GAIN = 0;
-
-var NEQ = 8; /* The number of EQs per channel */
-var FFT_SIZE = 2048; /* The size of FFT used for visualization */
-
-var audioContext; /* Web Audio context */
-var nyquist; /* Nyquist frequency, in Hz */
-var sourceNode;
-var audio_graph;
-var audio_ui;
-var analyzer_left; /* The FFT analyzer for left channel */
-var analyzer_right; /* The FFT analyzer for right channel */
-/* get_emphasis_disabled detects if pre-emphasis in drc is disabled by browser.
- * The detection result will be stored in this value. When user saves config,
- * This value is stored in drc.emphasis_disabled in the config. */
-var browser_emphasis_disabled_detection_result;
-/* check_biquad_filter_q detects if the browser implements the lowpass and
- * highpass biquad filters with the original formula or the new formula from
- * Audio EQ Cookbook. Chrome changed the filter implementation in R53, see:
- * https://github.com/GoogleChrome/web-audio-samples/wiki/Detection-of-lowpass-BiquadFilter-implementation
- * The detection result is saved in this value before the page is initialized.
- * make_biquad_q() uses this value to compute Q to ensure consistent behavior
- * on different browser versions.
- */
-var browser_biquad_filter_uses_audio_cookbook_formula;
-
-/* Check the lowpass implementation and return a promise. */
-function check_biquad_filter_q() {
- 'use strict';
- var context = new OfflineAudioContext(1, 128, 48000);
- var osc = context.createOscillator();
- var filter1 = context.createBiquadFilter();
- var filter2 = context.createBiquadFilter();
- var inverter = context.createGain();
-
- osc.type = 'sawtooth';
- osc.frequency.value = 8 * 440;
- inverter.gain.value = -1;
- /* each filter should get a different Q value */
- filter1.Q.value = -1;
- filter2.Q.value = -20;
- osc.connect(filter1);
- osc.connect(filter2);
- filter1.connect(context.destination);
- filter2.connect(inverter);
- inverter.connect(context.destination);
- osc.start();
-
- return context.startRendering().then(function (buffer) {
- return browser_biquad_filter_uses_audio_cookbook_formula =
- Math.max(...buffer.getChannelData(0)) !== 0;
- });
-}
-
-/* Return the Q value to be used with the lowpass and highpass biquad filters,
- * given Q in dB for the original filter formula. If the browser uses the new
- * formula, conversion is made to simulate the original frequency response
- * with the new formula.
- */
-function make_biquad_q(q_db) {
- if (!browser_biquad_filter_uses_audio_cookbook_formula)
- return q_db;
-
- var q_lin = dBToLinear(q_db);
- var q_new = 1 / Math.sqrt((4 - Math.sqrt(16 - 16 / (q_lin * q_lin))) / 2);
- q_new = linearToDb(q_new);
- return q_new;
-}
-
-/* The supported audio element names are different on browsers with different
- * versions.*/
-function fix_audio_elements() {
- try {
- window.AudioContext = window.AudioContext || window.webkitAudioContext;
- window.OfflineAudioContext = (window.OfflineAudioContext ||
- window.webkitOfflineAudioContext);
- }
- catch(e) {
- alert('Web Audio API is not supported in this browser');
- }
-}
-
-function init_audio() {
- audioContext = new AudioContext();
- nyquist = audioContext.sampleRate / 2;
-}
-
-function build_graph() {
- if (sourceNode) {
- audio_graph = new graph();
- sourceNode.disconnect();
- if (get_global('enable_drc') || get_global('enable_eq') ||
- get_global('enable_fft')) {
- connect_from_native(pin(sourceNode), audio_graph);
- connect_to_native(audio_graph, pin(audioContext.destination));
- } else {
- /* no processing needed, directly connect from source to destination. */
- sourceNode.connect(audioContext.destination);
- }
- }
- apply_all_configs();
-}
-
-/* The available configuration variables are:
- *
- * global.{enable_drc, enable_eq, enable_fft, enable_swap}
- * drc.[0-2].{f, enable, threshold, knee, ratio, attack, release, boost}
- * eq.[01].[0-7].{enable, type, freq, q, gain}.
- *
- * Each configuration variable maps a name to a value. For example,
- * "drc.1.attack" is the attack time for the second drc (the "1" is the index of
- * the drc instance), and "eq.0.2.freq" is the frequency of the third eq on the
- * left channel (the "0" means left channel, and the "2" is the index of the
- * eq).
- */
-var all_configs = {}; /* stores all the configuration variables */
-
-function init_config() {
- set_config('global', 'enable_drc', INIT_GLOBAL_ENABLE_DRC);
- set_config('global', 'enable_eq', INIT_GLOBAL_ENABLE_EQ);
- set_config('global', 'enable_fft', INIT_GLOBAL_ENABLE_FFT);
- set_config('global', 'enable_swap', INIT_GLOBAL_ENABLE_SWAP);
- set_config('drc', 0, 'f', 0);
- set_config('drc', 1, 'f', INIT_DRC_XO_LOW);
- set_config('drc', 2, 'f', INIT_DRC_XO_HIGH);
- for (var i = 0; i < 3; i++) {
- set_config('drc', i, 'enable', INIT_DRC_ENABLE);
- set_config('drc', i, 'threshold', INIT_DRC_THRESHOLD);
- set_config('drc', i, 'knee', INIT_DRC_KNEE);
- set_config('drc', i, 'ratio', INIT_DRC_RATIO);
- set_config('drc', i, 'attack', INIT_DRC_ATTACK);
- set_config('drc', i, 'release', INIT_DRC_RELEASE);
- set_config('drc', i, 'boost', INIT_DRC_BOOST);
- }
- for (var i = 0; i <= 1; i++) {
- for (var j = 0; j < NEQ; j++) {
- set_config('eq', i, j, 'enable', INIT_EQ_ENABLE);
- set_config('eq', i, j, 'type', INIT_EQ_TYPE);
- set_config('eq', i, j, 'freq', INIT_EQ_FREQ);
- set_config('eq', i, j, 'q', INIT_EQ_Q);
- set_config('eq', i, j, 'gain', INIT_EQ_GAIN);
- }
- }
-}
-
-/* Returns a string from the first n elements of a, joined by '.' */
-function make_name(a, n) {
- var sub = [];
- for (var i = 0; i < n; i++) {
- sub.push(a[i].toString());
- }
- return sub.join('.');
-}
-
-function get_config() {
- var name = make_name(arguments, arguments.length);
- return all_configs[name];
-}
-
-function set_config() {
- var n = arguments.length;
- var name = make_name(arguments, n - 1);
- all_configs[name] = arguments[n - 1];
-}
-
-/* Convenience function */
-function get_global(name) {
- return get_config('global', name);
-}
-
-/* set_config and apply it to the audio graph and ui. */
-function use_config() {
- var n = arguments.length;
- var name = make_name(arguments, n - 1);
- all_configs[name] = arguments[n - 1];
- if (audio_graph) {
- audio_graph.config(name.split('.'), all_configs[name]);
- }
- if (audio_ui) {
- audio_ui.config(name.split('.'), all_configs[name]);
- }
-}
-
-/* re-apply all the configs to audio graph and ui. */
-function apply_all_configs() {
- for (var name in all_configs) {
- if (audio_graph) {
- audio_graph.config(name.split('.'), all_configs[name]);
- }
- if (audio_ui) {
- audio_ui.config(name.split('.'), all_configs[name]);
- }
- }
-}
-
-/* Returns a zero-padded two digits number, for time formatting. */
-function two(n) {
- var s = '00' + n;
- return s.slice(-2);
-}
-
-/* Returns a time string, used for save file name */
-function time_str() {
- var d = new Date();
- var date = two(d.getDate());
- var month = two(d.getMonth() + 1);
- var hour = two(d.getHours());
- var minutes = two(d.getMinutes());
- return month + date + '-' + hour + minutes;
-}
-
-/* Downloads the current config to a file. */
-function save_config() {
- set_config('drc', 'emphasis_disabled',
- browser_emphasis_disabled_detection_result);
- var a = document.getElementById('save_config_anchor');
- var content = JSON.stringify(all_configs, undefined, 2);
- var uriContent = 'data:application/octet-stream,' +
- encodeURIComponent(content);
- a.href = uriContent;
- a.download = 'audio-' + time_str() + '.conf';
- a.click();
-}
-
-/* Loads a config file. */
-function load_config() {
- document.getElementById('config_file').click();
-}
-
-function config_file_changed() {
- var input = document.getElementById('config_file');
- var file = input.files[0];
- var reader = new FileReader();
- function onloadend() {
- var configs = JSON.parse(reader.result);
- init_config();
- for (var name in configs) {
- all_configs[name] = configs[name];
- }
- build_graph();
- }
- reader.onloadend = onloadend;
- reader.readAsText(file);
- input.value = '';
-}
-
-/* ============================ Audio components ============================ */
-
-/* We wrap Web Audio nodes into our own components. Each component has following
- * methods:
- *
- * function input(n) - Returns a list of pins which are the n-th input of the
- * component.
- *
- * function output(n) - Returns a list of pins which are the n-th output of the
- * component.
- *
- * function config(name, value) - Changes the configuration variable for the
- * component.
- *
- * Each "pin" is just one input/output of a Web Audio node.
- */
-
-/* Returns the top-level audio component */
-function graph() {
- var stages = [];
- var drcs, eqs, ffts;
- if (get_global('enable_drc')) {
- drcs = new drc_3band();
- }
- if (get_global('enable_eq')) {
- eqs = new eq_2chan();
- }
- if (get_global('enable_swap')) {
- if (eqs) stages.push(eqs);
- if (drcs) stages.push(drcs);
- } else {
- if (drcs) stages.push(drcs);
- if (eqs) stages.push(eqs);
- }
- if (get_global('enable_fft')) {
- ffts = new fft_2chan();
- stages.push(ffts);
- }
-
- for (var i = 1; i < stages.length; i++) {
- connect(stages[i - 1], stages[i]);
- }
-
- function input(n) {
- return stages[0].input(0);
- }
-
- function output(n) {
- return stages[stages.length - 1].output(0);
- }
-
- function config(name, value) {
- var p = name[0];
- var s = name.slice(1);
- if (p == 'global') {
- /* do nothing */
- } else if (p == 'drc') {
- if (drcs) {
- drcs.config(s, value);
- }
- } else if (p == 'eq') {
- if (eqs) {
- eqs.config(s, value);
- }
- } else {
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Returns the fft component for two channels */
-function fft_2chan() {
- var splitter = audioContext.createChannelSplitter(2);
- var merger = audioContext.createChannelMerger(2);
-
- analyzer_left = audioContext.createAnalyser();
- analyzer_right = audioContext.createAnalyser();
- analyzer_left.fftSize = FFT_SIZE;
- analyzer_right.fftSize = FFT_SIZE;
-
- splitter.connect(analyzer_left, 0, 0);
- splitter.connect(analyzer_right, 1, 0);
- analyzer_left.connect(merger, 0, 0);
- analyzer_right.connect(merger, 0, 1);
-
- function input(n) {
- return [pin(splitter)];
- }
-
- function output(n) {
- return [pin(merger)];
- }
-
- this.input = input;
- this.output = output;
-}
-
-/* Returns eq for two channels */
-function eq_2chan() {
- var eqcs = [new eq_channel(0), new eq_channel(1)];
- var splitter = audioContext.createChannelSplitter(2);
- var merger = audioContext.createChannelMerger(2);
-
- connect_from_native(pin(splitter, 0), eqcs[0]);
- connect_from_native(pin(splitter, 1), eqcs[1]);
- connect_to_native(eqcs[0], pin(merger, 0));
- connect_to_native(eqcs[1], pin(merger, 1));
-
- function input(n) {
- return [pin(splitter)];
- }
-
- function output(n) {
- return [pin(merger)];
- }
-
- function config(name, value) {
- var p = parseInt(name[0]);
- var s = name.slice(1);
- eqcs[p].config(s, value);
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Returns eq for one channel (left or right). It contains a series of eq
- * filters. */
-function eq_channel(channel) {
- var eqs = [];
- var first = new delay(0);
- var last = first;
- for (var i = 0; i < NEQ; i++) {
- eqs.push(new eq());
- if (get_config('eq', channel, i, 'enable')) {
- connect(last, eqs[i]);
- last = eqs[i];
- }
- }
-
- function input(n) {
- return first.input(0);
- }
-
- function output(n) {
- return last.output(0);
- }
-
- function config(name, value) {
- var p = parseInt(name[0]);
- var s = name.slice(1);
- eqs[p].config(s, value);
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Returns a delay component (output = input with n seconds delay) */
-function delay(n) {
- var delay = audioContext.createDelay();
- delay.delayTime.value = n;
-
- function input(n) {
- return [pin(delay)];
- }
-
- function output(n) {
- return [pin(delay)];
- }
-
- function config(name, value) {
- console.log('invalid parameter: name =', name, 'value =', value);
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Returns an eq filter */
-function eq() {
- var filter = audioContext.createBiquadFilter();
- filter.type = INIT_EQ_TYPE;
- filter.frequency.value = INIT_EQ_FREQ;
- filter.Q.value = INIT_EQ_Q;
- filter.gain.value = INIT_EQ_GAIN;
-
- function input(n) {
- return [pin(filter)];
- }
-
- function output(n) {
- return [pin(filter)];
- }
-
- function config(name, value) {
- switch (name[0]) {
- case 'type':
- filter.type = value;
- break;
- case 'freq':
- filter.frequency.value = parseFloat(value);
- break;
- case 'q':
- value = parseFloat(value);
- if (filter.type == 'lowpass' || filter.type == 'highpass')
- value = make_biquad_q(value);
- filter.Q.value = value;
- break;
- case 'gain':
- filter.gain.value = parseFloat(value);
- break;
- case 'enable':
- break;
- default:
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Returns DRC for 3 bands */
-function drc_3band() {
- var xo = new xo3();
- var drcs = [new drc(), new drc(), new drc()];
-
- var out = [];
- for (var i = 0; i < 3; i++) {
- if (get_config('drc', i, 'enable')) {
- connect(xo, drcs[i], i);
- out = out.concat(drcs[i].output());
- } else {
- /* The DynamicsCompressorNode in Chrome has 6ms pre-delay buffer. So for
- * other bands we need to delay for the same amount of time.
- */
- var d = new delay(0.006);
- connect(xo, d, i);
- out = out.concat(d.output());
- }
- }
-
- function input(n) {
- return xo.input(0);
- }
-
- function output(n) {
- return out;
- }
-
- function config(name, value) {
- if (name[1] == 'f') {
- xo.config(name, value);
- } else if (name[0] != 'emphasis_disabled') {
- var n = parseInt(name[0]);
- drcs[n].config(name.slice(1), value);
- }
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-
-/* This snippet came from LayoutTests/webaudio/dynamicscompressor-simple.html in
- * https://codereview.chromium.org/152333003/. It can determine if
- * emphasis/deemphasis is disabled in the browser. Then it sets the value to
- * drc.emphasis_disabled in the config.*/
-function get_emphasis_disabled() {
- var context;
- var sampleRate = 44100;
- var lengthInSeconds = 1;
- var renderedData;
- // This threshold is experimentally determined. It depends on the the gain
- // value of the gain node below and the dynamics compressor. When the
- // DynamicsCompressor had the pre-emphasis filters, the peak value is about
- // 0.21. Without it, the peak is 0.85.
- var peakThreshold = 0.85;
-
- function checkResult(event) {
- var renderedBuffer = event.renderedBuffer;
- renderedData = renderedBuffer.getChannelData(0);
- // Search for a peak in the last part of the data.
- var startSample = sampleRate * (lengthInSeconds - .1);
- var endSample = renderedData.length;
- var k;
- var peak = -1;
- var emphasis_disabled = 0;
-
- for (k = startSample; k < endSample; ++k) {
- var sample = Math.abs(renderedData[k]);
- if (peak < sample)
- peak = sample;
- }
-
- if (peak >= peakThreshold) {
- console.log("Pre-emphasis effect not applied as expected..");
- emphasis_disabled = 1;
- } else {
- console.log("Pre-emphasis caused output to be decreased to " + peak
- + " (expected >= " + peakThreshold + ")");
- emphasis_disabled = 0;
- }
- browser_emphasis_disabled_detection_result = emphasis_disabled;
- /* save_config button will be disabled until we can decide
- emphasis_disabled in chrome. */
- document.getElementById('save_config').disabled = false;
- }
-
- function runTest() {
- context = new OfflineAudioContext(1, sampleRate * lengthInSeconds,
- sampleRate);
- // Connect an oscillator to a gain node to the compressor. The
- // oscillator frequency is set to a high value for the (original)
- // emphasis to kick in. The gain is a little extra boost to get the
- // compressor enabled.
- //
- var osc = context.createOscillator();
- osc.frequency.value = 15000;
- var gain = context.createGain();
- gain.gain.value = 1.5;
- var compressor = context.createDynamicsCompressor();
- osc.connect(gain);
- gain.connect(compressor);
- compressor.connect(context.destination);
- osc.start();
- context.oncomplete = checkResult;
- context.startRendering();
- }
-
- runTest();
-
-}
-
-/* Returns one DRC filter */
-function drc() {
- var comp = audioContext.createDynamicsCompressor();
-
- /* The supported method names are different on browsers with different
- * versions.*/
- audioContext.createGainNode = (audioContext.createGainNode ||
- audioContext.createGain);
- var boost = audioContext.createGainNode();
- comp.threshold.value = INIT_DRC_THRESHOLD;
- comp.knee.value = INIT_DRC_KNEE;
- comp.ratio.value = INIT_DRC_RATIO;
- comp.attack.value = INIT_DRC_ATTACK;
- comp.release.value = INIT_DRC_RELEASE;
- boost.gain.value = dBToLinear(INIT_DRC_BOOST);
-
- comp.connect(boost);
-
- function input(n) {
- return [pin(comp)];
- }
-
- function output(n) {
- return [pin(boost)];
- }
-
- function config(name, value) {
- var p = name[0];
- switch (p) {
- case 'threshold':
- case 'knee':
- case 'ratio':
- case 'attack':
- case 'release':
- comp[p].value = parseFloat(value);
- break;
- case 'boost':
- boost.gain.value = dBToLinear(parseFloat(value));
- break;
- case 'enable':
- break;
- default:
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Crossover filter
- *
- * INPUT --+-- lp1 --+-- lp2a --+-- LOW (0)
- * | | |
- * | \-- hp2a --/
- * |
- * \-- hp1 --+-- lp2 ------ MID (1)
- * |
- * \-- hp2 ------ HIGH (2)
- *
- * [f1] [f2]
- */
-
-/* Returns a crossover component which splits input into 3 bands */
-function xo3() {
- var f1 = INIT_DRC_XO_LOW;
- var f2 = INIT_DRC_XO_HIGH;
-
- var lp1 = lr4_lowpass(f1);
- var hp1 = lr4_highpass(f1);
- var lp2 = lr4_lowpass(f2);
- var hp2 = lr4_highpass(f2);
- var lp2a = lr4_lowpass(f2);
- var hp2a = lr4_highpass(f2);
-
- connect(lp1, lp2a);
- connect(lp1, hp2a);
- connect(hp1, lp2);
- connect(hp1, hp2);
-
- function input(n) {
- return lp1.input().concat(hp1.input());
- }
-
- function output(n) {
- switch (n) {
- case 0:
- return lp2a.output().concat(hp2a.output());
- case 1:
- return lp2.output();
- case 2:
- return hp2.output();
- default:
- console.log('invalid index ' + n);
- return [];
- }
- }
-
- function config(name, value) {
- var p = name[0];
- var s = name.slice(1);
- if (p == '0') {
- /* Ignore. The lower frequency of the low band is always 0. */
- } else if (p == '1') {
- lp1.config(s, value);
- hp1.config(s, value);
- } else if (p == '2') {
- lp2.config(s, value);
- hp2.config(s, value);
- lp2a.config(s, value);
- hp2a.config(s, value);
- } else {
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.output = output;
- this.input = input;
- this.config = config;
-}
-
-/* Connects two components: the n-th output of c1 and the m-th input of c2. */
-function connect(c1, c2, n, m) {
- n = n || 0; /* default is the first output */
- m = m || 0; /* default is the first input */
- outs = c1.output(n);
- ins = c2.input(m);
-
- for (var i = 0; i < outs.length; i++) {
- for (var j = 0; j < ins.length; j++) {
- var from = outs[i];
- var to = ins[j];
- from.node.connect(to.node, from.index, to.index);
- }
- }
-}
-
-/* Connects from pin "from" to the n-th input of component c2 */
-function connect_from_native(from, c2, n) {
- n = n || 0; /* default is the first input */
- ins = c2.input(n);
- for (var i = 0; i < ins.length; i++) {
- var to = ins[i];
- from.node.connect(to.node, from.index, to.index);
- }
-}
-
-/* Connects from m-th output of component c1 to pin "to" */
-function connect_to_native(c1, to, m) {
- m = m || 0; /* default is the first output */
- outs = c1.output(m);
- for (var i = 0; i < outs.length; i++) {
- var from = outs[i];
- from.node.connect(to.node, from.index, to.index);
- }
-}
-
-/* Returns a LR4 lowpass component */
-function lr4_lowpass(freq) {
- return new double(freq, create_lowpass);
-}
-
-/* Returns a LR4 highpass component */
-function lr4_highpass(freq) {
- return new double(freq, create_highpass);
-}
-
-/* Returns a component by apply the same filter twice. */
-function double(freq, creator) {
- var f1 = creator(freq);
- var f2 = creator(freq);
- f1.connect(f2);
-
- function input(n) {
- return [pin(f1)];
- }
-
- function output(n) {
- return [pin(f2)];
- }
-
- function config(name, value) {
- if (name[0] == 'f') {
- f1.frequency.value = parseFloat(value);
- f2.frequency.value = parseFloat(value);
- } else {
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.input = input;
- this.output = output;
- this.config = config;
-}
-
-/* Returns a lowpass filter */
-function create_lowpass(freq) {
- var lp = audioContext.createBiquadFilter();
- lp.type = 'lowpass';
- lp.frequency.value = freq;
- lp.Q.value = make_biquad_q(0);
- return lp;
-}
-
-/* Returns a highpass filter */
-function create_highpass(freq) {
- var hp = audioContext.createBiquadFilter();
- hp.type = 'highpass';
- hp.frequency.value = freq;
- hp.Q.value = make_biquad_q(0);
- return hp;
-}
-
-/* A pin specifies one of the input/output of a Web Audio node */
-function pin(node, index) {
- var p = new Pin();
- p.node = node;
- p.index = index || 0;
- return p;
-}
-
-function Pin(node, index) {
-}
-
-/* ============================ Event Handlers ============================ */
-
-function audio_source_select(select) {
- var index = select.selectedIndex;
- var url = document.getElementById('audio_source_url');
- url.value = select.options[index].value;
- url.blur();
- audio_source_set(url.value);
-}
-
-/* Loads a local audio file. */
-function load_audio() {
- document.getElementById('audio_file').click();
-}
-
-function audio_file_changed() {
- var input = document.getElementById('audio_file');
- var file = input.files[0];
- var file_url = window.webkitURL.createObjectURL(file);
- input.value = '';
-
- var url = document.getElementById('audio_source_url');
- url.value = file.name;
-
- audio_source_set(file_url);
-}
-
-function audio_source_set(url) {
- var player = document.getElementById('audio_player');
- var container = document.getElementById('audio_player_container');
- var loading = document.getElementById('audio_loading');
- loading.style.visibility = 'visible';
-
- /* Re-create an audio element when the audio source URL is changed. */
- player.pause();
- container.removeChild(player);
- player = document.createElement('audio');
- player.crossOrigin = 'anonymous';
- player.id = 'audio_player';
- player.loop = true;
- player.controls = true;
- player.addEventListener('canplay', audio_source_canplay);
- container.appendChild(player);
- update_source_node(player);
-
- player.src = url;
- player.load();
-}
-
-function audio_source_canplay() {
- var player = document.getElementById('audio_player');
- var loading = document.getElementById('audio_loading');
- loading.style.visibility = 'hidden';
- player.play();
-}
-
-function update_source_node(mediaElement) {
- sourceNode = audioContext.createMediaElementSource(mediaElement);
- build_graph();
-}
-
-function toggle_global_checkbox(name, enable) {
- use_config('global', name, enable);
- build_graph();
-}
-
-function toggle_one_drc(index, enable) {
- use_config('drc', index, 'enable', enable);
- build_graph();
-}
-
-function toggle_one_eq(channel, index, enable) {
- use_config('eq', channel, index, 'enable', enable);
- build_graph();
-}
-
-/* ============================== UI widgets ============================== */
-
-/* Adds a row to the table. The row contains an input box and a slider. */
-function slider_input(table, name, initial_value, min_value, max_value, step,
- suffix, handler) {
- function id(x) {
- return x;
- }
-
- return new slider_input_common(table, name, initial_value, min_value,
- max_value, step, suffix, handler, id, id);
-}
-
-/* This is similar to slider_input, but uses log scale for the slider. */
-function slider_input_log(table, name, initial_value, min_value, max_value,
- suffix, precision, handler, mapping,
- inverse_mapping) {
- function mapping(x) {
- return Math.log(x + 1);
- }
-
- function inv_mapping(x) {
- return (Math.exp(x) - 1).toFixed(precision);
- }
-
- return new slider_input_common(table, name, initial_value, min_value,
- max_value, 1e-6, suffix, handler, mapping,
- inv_mapping);
-}
-
-/* The common implementation of linear and log-scale sliders. Each slider has
- * the following methods:
- *
- * function update(v) - update the slider (and the text box) to the value v.
- *
- * function hide(h) - hide/unhide the slider.
- */
-function slider_input_common(table, name, initial_value, min_value, max_value,
- step, suffix, handler, mapping, inv_mapping) {
- var row = table.insertRow(-1);
- var col_name = row.insertCell(-1);
- var col_box = row.insertCell(-1);
- var col_slider = row.insertCell(-1);
-
- var name_span = document.createElement('span');
- name_span.appendChild(document.createTextNode(name));
- col_name.appendChild(name_span);
-
- var box = document.createElement('input');
- box.defaultValue = initial_value;
- box.type = 'text';
- box.size = 5;
- box.className = 'nbox';
- col_box.appendChild(box);
- var suffix_span = document.createElement('span');
- suffix_span.appendChild(document.createTextNode(suffix));
- col_box.appendChild(suffix_span);
-
- var slider = document.createElement('input');
- slider.defaultValue = Math.log(initial_value);
- slider.type = 'range';
- slider.className = 'nslider';
- slider.min = mapping(min_value);
- slider.max = mapping(max_value);
- slider.step = step;
- col_slider.appendChild(slider);
-
- box.onchange = function() {
- slider.value = mapping(box.value);
- handler(parseFloat(box.value));
- };
-
- slider.onchange = function() {
- box.value = inv_mapping(slider.value);
- handler(parseFloat(box.value));
- };
-
- function update(v) {
- box.value = v;
- slider.value = mapping(v);
- }
-
- function hide(h) {
- var v = h ? 'hidden' : 'visible';
- name_span.style.visibility = v;
- box.style.visibility = v;
- suffix_span.style.visibility = v;
- slider.style.visibility = v;
- }
-
- this.update = update;
- this.hide = hide;
-}
-
-/* Adds a enable/disable checkbox to a div. The method "update" can change the
- * checkbox state. */
-function check_button(div, handler) {
- var check = document.createElement('input');
- check.className = 'enable_check';
- check.type = 'checkbox';
- check.checked = true;
- check.onchange = function() {
- handler(check.checked);
- };
- div.appendChild(check);
-
- function update(v) {
- check.checked = v;
- }
-
- this.update = update;
-}
-
-function empty() {
-}
-
-/* Changes the opacity of a div. */
-function toggle_card(div, enable) {
- div.style.opacity = enable ? 1 : 0.3;
-}
-
-/* Appends a card of DRC controls and graphs to the specified parent.
- * Args:
- * parent - The parent element
- * index - The index of this DRC component (0-2)
- * lower_freq - The lower frequency of this DRC component
- * freq_label - The label for the lower frequency input text box
- */
-function drc_card(parent, index, lower_freq, freq_label) {
- var top = document.createElement('div');
- top.className = 'drc_data';
- parent.appendChild(top);
- function toggle_drc_card(enable) {
- toggle_card(div, enable);
- toggle_one_drc(index, enable);
- }
- var enable_button = new check_button(top, toggle_drc_card);
-
- var div = document.createElement('div');
- top.appendChild(div);
-
- /* Canvas */
- var p = document.createElement('p');
- div.appendChild(p);
-
- var canvas = document.createElement('canvas');
- canvas.className = 'drc_curve';
- p.appendChild(canvas);
-
- canvas.width = 240;
- canvas.height = 180;
- var dd = new DrcDrawer(canvas);
- dd.init();
-
- /* Parameters */
- var table = document.createElement('table');
- div.appendChild(table);
-
- function change_lower_freq(v) {
- use_config('drc', index, 'f', v);
- }
-
- function change_threshold(v) {
- dd.update_threshold(v);
- use_config('drc', index, 'threshold', v);
- }
-
- function change_knee(v) {
- dd.update_knee(v);
- use_config('drc', index, 'knee', v);
- }
-
- function change_ratio(v) {
- dd.update_ratio(v);
- use_config('drc', index, 'ratio', v);
- }
-
- function change_boost(v) {
- dd.update_boost(v);
- use_config('drc', index, 'boost', v);
- }
-
- function change_attack(v) {
- use_config('drc', index, 'attack', v);
- }
-
- function change_release(v) {
- use_config('drc', index, 'release', v);
- }
-
- var f_slider;
- if (lower_freq == 0) { /* Special case for the lowest band */
- f_slider = new slider_input_log(table, freq_label, lower_freq, 0, 1,
- 'Hz', 0, empty);
- f_slider.hide(true);
- } else {
- f_slider = new slider_input_log(table, freq_label, lower_freq, 1,
- nyquist, 'Hz', 0, change_lower_freq);
- }
-
- var sliders = {
- 'f': f_slider,
- 'threshold': new slider_input(table, 'Threshold', INIT_DRC_THRESHOLD,
- -100, 0, 1, 'dB', change_threshold),
- 'knee': new slider_input(table, 'Knee', INIT_DRC_KNEE, 0, 40, 1, 'dB',
- change_knee),
- 'ratio': new slider_input(table, 'Ratio', INIT_DRC_RATIO, 1, 20, 0.001,
- '', change_ratio),
- 'boost': new slider_input(table, 'Boost', 0, -40, 40, 1, 'dB',
- change_boost),
- 'attack': new slider_input(table, 'Attack', INIT_DRC_ATTACK, 0.001,
- 1, 0.001, 's', change_attack),
- 'release': new slider_input(table, 'Release', INIT_DRC_RELEASE,
- 0.001, 1, 0.001, 's', change_release)
- };
-
- function config(name, value) {
- var p = name[0];
- var fv = parseFloat(value);
- switch (p) {
- case 'f':
- case 'threshold':
- case 'knee':
- case 'ratio':
- case 'boost':
- case 'attack':
- case 'release':
- sliders[p].update(fv);
- break;
- case 'enable':
- toggle_card(div, value);
- enable_button.update(value);
- break;
- default:
- console.log('invalid parameter: name =', name, 'value =', value);
- }
-
- switch (p) {
- case 'threshold':
- dd.update_threshold(fv);
- break;
- case 'knee':
- dd.update_knee(fv);
- break;
- case 'ratio':
- dd.update_ratio(fv);
- break;
- case 'boost':
- dd.update_boost(fv);
- break;
- }
- }
-
- this.config = config;
-}
-
-/* Appends a menu of biquad types to the specified table. */
-function biquad_type_select(table, handler) {
- var row = table.insertRow(-1);
- var col_name = row.insertCell(-1);
- var col_menu = row.insertCell(-1);
-
- col_name.appendChild(document.createTextNode('Type'));
-
- var select = document.createElement('select');
- select.className = 'biquad_type_select';
- var options = [
- 'lowpass',
- 'highpass',
- 'bandpass',
- 'lowshelf',
- 'highshelf',
- 'peaking',
- 'notch'
- /* no need: 'allpass' */
- ];
-
- for (var i = 0; i < options.length; i++) {
- var o = document.createElement('option');
- o.appendChild(document.createTextNode(options[i]));
- select.appendChild(o);
- }
-
- select.value = INIT_EQ_TYPE;
- col_menu.appendChild(select);
-
- function onchange() {
- handler(select.value);
- }
- select.onchange = onchange;
-
- function update(v) {
- select.value = v;
- }
-
- this.update = update;
-}
-
-/* Appends a card of EQ controls to the specified parent.
- * Args:
- * parent - The parent element
- * channel - The index of the channel this EQ component is on (0-1)
- * index - The index of this EQ on this channel (0-7)
- * ed - The EQ curve drawer. We will notify the drawer to redraw if the
- * parameters for this EQ changes.
- */
-function eq_card(parent, channel, index, ed) {
- var top = document.createElement('div');
- top.className = 'eq_data';
- parent.appendChild(top);
- function toggle_eq_card(enable) {
- toggle_card(table, enable);
- toggle_one_eq(channel, index, enable);
- ed.update_enable(index, enable);
- }
- var enable_button = new check_button(top, toggle_eq_card);
-
- var table = document.createElement('table');
- table.className = 'eq_table';
- top.appendChild(table);
-
- function change_type(v) {
- ed.update_type(index, v);
- hide_unused_slider(v);
- use_config('eq', channel, index, 'type', v);
- /* Special case: automatically set Q to 0 for lowpass/highpass filters. */
- if (v == 'lowpass' || v == 'highpass') {
- use_config('eq', channel, index, 'q', 0);
- }
- }
-
- function change_freq(v)
- {
- ed.update_freq(index, v);
- use_config('eq', channel, index, 'freq', v);
- }
-
- function change_q(v)
- {
- ed.update_q(index, v);
- use_config('eq', channel, index, 'q', v);
- }
-
- function change_gain(v)
- {
- ed.update_gain(index, v);
- use_config('eq', channel, index, 'gain', v);
- }
-
- var type_select = new biquad_type_select(table, change_type);
-
- var sliders = {
- 'freq': new slider_input_log(table, 'Frequency', INIT_EQ_FREQ, 1,
- nyquist, 'Hz', 0, change_freq),
- 'q': new slider_input_log(table, 'Q', INIT_EQ_Q, 0, 1000, '', 4,
- change_q),
- 'gain': new slider_input(table, 'Gain', INIT_EQ_GAIN, -40, 40, 0.1,
- 'dB', change_gain)
- };
-
- var unused = {
- 'lowpass': [0, 0, 1],
- 'highpass': [0, 0, 1],
- 'bandpass': [0, 0, 1],
- 'lowshelf': [0, 1, 0],
- 'highshelf': [0, 1, 0],
- 'peaking': [0, 0, 0],
- 'notch': [0, 0, 1],
- 'allpass': [0, 0, 1]
- };
- function hide_unused_slider(type) {
- var u = unused[type];
- sliders['freq'].hide(u[0]);
- sliders['q'].hide(u[1]);
- sliders['gain'].hide(u[2]);
- }
-
- function config(name, value) {
- var p = name[0];
- var fv = parseFloat(value);
- switch (p) {
- case 'type':
- type_select.update(value);
- break;
- case 'freq':
- case 'q':
- case 'gain':
- sliders[p].update(fv);
- break;
- case 'enable':
- toggle_card(table, value);
- enable_button.update(value);
- break;
- default:
- console.log('invalid parameter: name =', name, 'value =', value);
- }
-
- switch (p) {
- case 'type':
- ed.update_type(index, value);
- hide_unused_slider(value);
- break;
- case 'freq':
- ed.update_freq(index, fv);
- break;
- case 'q':
- ed.update_q(index, fv);
- break;
- case 'gain':
- ed.update_gain(index, fv);
- break;
- }
- }
-
- this.config = config;
-}
-
-/* Appends the EQ UI for one channel to the specified parent */
-function eq_section(parent, channel) {
- /* Two canvas, one for eq curve, another for fft. */
- var p = document.createElement('p');
- p.className = 'eq_curve_parent';
-
- var canvas_eq = document.createElement('canvas');
- canvas_eq.className = 'eq_curve';
- canvas_eq.width = 960;
- canvas_eq.height = 270;
-
- p.appendChild(canvas_eq);
- var ed = new EqDrawer(canvas_eq, channel);
- ed.init();
-
- var canvas_fft = document.createElement('canvas');
- canvas_fft.className = 'eq_curve';
- canvas_fft.width = 960;
- canvas_fft.height = 270;
-
- p.appendChild(canvas_fft);
- var fd = new FFTDrawer(canvas_fft, channel);
- fd.init();
-
- parent.appendChild(p);
-
- /* Eq cards */
- var eq = {};
- for (var i = 0; i < NEQ; i++) {
- eq[i] = new eq_card(parent, channel, i, ed);
- }
-
- function config(name, value) {
- var p = parseInt(name[0]);
- var s = name.slice(1);
- eq[p].config(s, value);
- }
-
- this.config = config;
-}
-
-function global_section(parent) {
- var checkbox_data = [
- /* config name, text label, checkbox object */
- ['enable_drc', 'Enable DRC', null],
- ['enable_eq', 'Enable EQ', null],
- ['enable_fft', 'Show FFT', null],
- ['enable_swap', 'Swap DRC/EQ', null]
- ];
-
- for (var i = 0; i < checkbox_data.length; i++) {
- config_name = checkbox_data[i][0];
- text_label = checkbox_data[i][1];
-
- var cb = document.createElement('input');
- cb.type = 'checkbox';
- cb.checked = get_global(config_name);
- cb.onchange = function(name) {
- return function() { toggle_global_checkbox(name, this.checked); }
- }(config_name);
- checkbox_data[i][2] = cb;
- parent.appendChild(cb);
- parent.appendChild(document.createTextNode(text_label));
- }
-
- function config(name, value) {
- var i;
- for (i = 0; i < checkbox_data.length; i++) {
- if (checkbox_data[i][0] == name[0]) {
- break;
- }
- }
- if (i < checkbox_data.length) {
- checkbox_data[i][2].checked = value;
- } else {
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.config = config;
-}
-
-window.onload = function() {
- fix_audio_elements();
- check_biquad_filter_q().then(function (flag) {
- console.log('Browser biquad filter uses Audio Cookbook formula:', flag);
- /* Detects if emphasis is disabled and sets
- * browser_emphasis_disabled_detection_result. */
- get_emphasis_disabled();
- init_config();
- init_audio();
- init_ui();
- }).catch(function (reason) {
- alert('Cannot detect browser biquad filter implementation:', reason);
- });
-};
-
-function init_ui() {
- audio_ui = new ui();
-}
-
-/* Top-level UI */
-function ui() {
- var global = new global_section(document.getElementById('global_section'));
- var drc_div = document.getElementById('drc_section');
- var drc_cards = [
- new drc_card(drc_div, 0, 0, ''),
- new drc_card(drc_div, 1, INIT_DRC_XO_LOW, 'Start From'),
- new drc_card(drc_div, 2, INIT_DRC_XO_HIGH, 'Start From')
- ];
-
- var left_div = document.getElementById('eq_left_section');
- var right_div = document.getElementById('eq_right_section');
- var eq_sections = [
- new eq_section(left_div, 0),
- new eq_section(right_div, 1)
- ];
-
- function config(name, value) {
- var p = name[0];
- var i = parseInt(name[1]);
- var s = name.slice(2);
- if (p == 'global') {
- global.config(name.slice(1), value);
- } else if (p == 'drc') {
- if (name[1] == 'emphasis_disabled') {
- return;
- }
- drc_cards[i].config(s, value);
- } else if (p == 'eq') {
- eq_sections[i].config(s, value);
- } else {
- console.log('invalid parameter: name =', name, 'value =', value);
- }
- }
-
- this.config = config;
-}
-
-/* Draws the DRC curve on a canvas. The update*() methods should be called when
- * the parameters change, so the curve can be redrawn. */
-function DrcDrawer(canvas) {
- var canvasContext = canvas.getContext('2d');
-
- var backgroundColor = 'black';
- var curveColor = 'rgb(192,192,192)';
- var gridColor = 'rgb(200,200,200)';
- var textColor = 'rgb(238,221,130)';
- var thresholdColor = 'rgb(255,160,122)';
-
- var dbThreshold = INIT_DRC_THRESHOLD;
- var dbKnee = INIT_DRC_KNEE;
- var ratio = INIT_DRC_RATIO;
- var boost = INIT_DRC_BOOST;
-
- var curve_slope;
- var curve_k;
- var linearThreshold;
- var kneeThresholdDb;
- var kneeThreshold;
- var ykneeThresholdDb;
- var mainLinearGain;
-
- var maxOutputDb = 6;
- var minOutputDb = -36;
-
- function xpixelToDb(x) {
- /* This is right even though it looks like we should scale by width. We
- * want the same pixel/dB scale for both. */
- var k = x / canvas.height;
- var db = minOutputDb + k * (maxOutputDb - minOutputDb);
- return db;
- }
-
- function dBToXPixel(db) {
- var k = (db - minOutputDb) / (maxOutputDb - minOutputDb);
- var x = k * canvas.height;
- return x;
- }
-
- function ypixelToDb(y) {
- var k = y / canvas.height;
- var db = maxOutputDb - k * (maxOutputDb - minOutputDb);
- return db;
- }
-
- function dBToYPixel(db) {
- var k = (maxOutputDb - db) / (maxOutputDb - minOutputDb);
- var y = k * canvas.height;
- return y;
- }
-
- function kneeCurve(x, k) {
- if (x < linearThreshold)
- return x;
-
- return linearThreshold +
- (1 - Math.exp(-k * (x - linearThreshold))) / k;
- }
-
- function saturate(x, k) {
- var y;
- if (x < kneeThreshold) {
- y = kneeCurve(x, k);
- } else {
- var xDb = linearToDb(x);
- var yDb = ykneeThresholdDb + curve_slope * (xDb - kneeThresholdDb);
- y = dBToLinear(yDb);
- }
- return y;
- }
-
- function slopeAt(x, k) {
- if (x < linearThreshold)
- return 1;
- var x2 = x * 1.001;
- var xDb = linearToDb(x);
- var x2Db = linearToDb(x2);
- var yDb = linearToDb(kneeCurve(x, k));
- var y2Db = linearToDb(kneeCurve(x2, k));
- var m = (y2Db - yDb) / (x2Db - xDb);
- return m;
- }
-
- function kAtSlope(desiredSlope) {
- var xDb = dbThreshold + dbKnee;
- var x = dBToLinear(xDb);
-
- var minK = 0.1;
- var maxK = 10000;
- var k = 5;
-
- for (var i = 0; i < 15; i++) {
- var slope = slopeAt(x, k);
- if (slope < desiredSlope) {
- maxK = k;
- } else {
- minK = k;
- }
- k = Math.sqrt(minK * maxK);
- }
- return k;
- }
-
- function drawCurve() {
- /* Update curve parameters */
- linearThreshold = dBToLinear(dbThreshold);
- curve_slope = 1 / ratio;
- curve_k = kAtSlope(1 / ratio);
- kneeThresholdDb = dbThreshold + dbKnee;
- kneeThreshold = dBToLinear(kneeThresholdDb);
- ykneeThresholdDb = linearToDb(kneeCurve(kneeThreshold, curve_k));
-
- /* Calculate mainLinearGain */
- var fullRangeGain = saturate(1, curve_k);
- var fullRangeMakeupGain = Math.pow(1 / fullRangeGain, 0.6);
- mainLinearGain = dBToLinear(boost) * fullRangeMakeupGain;
-
- /* Clear canvas */
- var width = canvas.width;
- var height = canvas.height;
- canvasContext.fillStyle = backgroundColor;
- canvasContext.fillRect(0, 0, width, height);
-
- /* Draw linear response for reference. */
- canvasContext.strokeStyle = gridColor;
- canvasContext.lineWidth = 1;
- canvasContext.beginPath();
- canvasContext.moveTo(dBToXPixel(minOutputDb), dBToYPixel(minOutputDb));
- canvasContext.lineTo(dBToXPixel(maxOutputDb), dBToYPixel(maxOutputDb));
- canvasContext.stroke();
-
- /* Draw 0dBFS output levels from 0dBFS down to -36dBFS */
- for (var dbFS = 0; dbFS >= -36; dbFS -= 6) {
- canvasContext.beginPath();
-
- var y = dBToYPixel(dbFS);
- canvasContext.setLineDash([1, 4]);
- canvasContext.moveTo(0, y);
- canvasContext.lineTo(width, y);
- canvasContext.stroke();
- canvasContext.setLineDash([]);
-
- canvasContext.textAlign = 'center';
- canvasContext.strokeStyle = textColor;
- canvasContext.strokeText(dbFS.toFixed(0) + ' dB', 15, y - 2);
- canvasContext.strokeStyle = gridColor;
- }
-
- /* Draw 0dBFS input line */
- canvasContext.beginPath();
- canvasContext.moveTo(dBToXPixel(0), 0);
- canvasContext.lineTo(dBToXPixel(0), height);
- canvasContext.stroke();
- canvasContext.strokeText('0dB', dBToXPixel(0), height);
-
- /* Draw threshold input line */
- canvasContext.beginPath();
- canvasContext.moveTo(dBToXPixel(dbThreshold), 0);
- canvasContext.lineTo(dBToXPixel(dbThreshold), height);
- canvasContext.moveTo(dBToXPixel(kneeThresholdDb), 0);
- canvasContext.lineTo(dBToXPixel(kneeThresholdDb), height);
- canvasContext.strokeStyle = thresholdColor;
- canvasContext.stroke();
-
- /* Draw the compressor curve */
- canvasContext.strokeStyle = curveColor;
- canvasContext.lineWidth = 3;
-
- canvasContext.beginPath();
- var pixelsPerDb = (0.5 * height) / 40.0;
-
- for (var x = 0; x < width; ++x) {
- var inputDb = xpixelToDb(x);
- var inputLinear = dBToLinear(inputDb);
- var outputLinear = saturate(inputLinear, curve_k);
- outputLinear *= mainLinearGain;
- var outputDb = linearToDb(outputLinear);
- var y = dBToYPixel(outputDb);
-
- canvasContext.lineTo(x, y);
- }
- canvasContext.stroke();
-
- }
-
- function init() {
- drawCurve();
- }
-
- function update_threshold(v)
- {
- dbThreshold = v;
- drawCurve();
- }
-
- function update_knee(v)
- {
- dbKnee = v;
- drawCurve();
- }
-
- function update_ratio(v)
- {
- ratio = v;
- drawCurve();
- }
-
- function update_boost(v)
- {
- boost = v;
- drawCurve();
- }
-
- this.init = init;
- this.update_threshold = update_threshold;
- this.update_knee = update_knee;
- this.update_ratio = update_ratio;
- this.update_boost = update_boost;
-}
-
-/* Draws the EQ curve on a canvas. The update*() methods should be called when
- * the parameters change, so the curve can be redrawn. */
-function EqDrawer(canvas, channel) {
- var canvasContext = canvas.getContext('2d');
- var curveColor = 'rgb(192,192,192)';
- var gridColor = 'rgb(200,200,200)';
- var textColor = 'rgb(238,221,130)';
- var centerFreq = {};
- var q = {};
- var gain = {};
-
- for (var i = 0; i < NEQ; i++) {
- centerFreq[i] = INIT_EQ_FREQ;
- q[i] = INIT_EQ_Q;
- gain[i] = INIT_EQ_GAIN;
- }
-
- function drawCurve() {
- /* Create a biquad node to calculate frequency response. */
- var filter = audioContext.createBiquadFilter();
- var width = canvas.width;
- var height = canvas.height;
- var pixelsPerDb = height / 48.0;
- var noctaves = 10;
-
- /* Prepare the frequency array */
- var frequencyHz = new Float32Array(width);
- for (var i = 0; i < width; ++i) {
- var f = i / width;
-
- /* Convert to log frequency scale (octaves). */
- f = Math.pow(2.0, noctaves * (f - 1.0));
- frequencyHz[i] = f * nyquist;
- }
-
- /* Get the response */
- var magResponse = new Float32Array(width);
- var phaseResponse = new Float32Array(width);
- var totalMagResponse = new Float32Array(width);
-
- for (var i = 0; i < width; i++) {
- totalMagResponse[i] = 1;
- }
-
- for (var i = 0; i < NEQ; i++) {
- if (!get_config('eq', channel, i, 'enable')) {
- continue;
- }
- filter.type = get_config('eq', channel, i, 'type');
- filter.frequency.value = centerFreq[i];
- if (filter.type == 'lowpass' || filter.type == 'highpass')
- filter.Q.value = make_biquad_q(q[i]);
- else
- filter.Q.value = q[i];
- filter.gain.value = gain[i];
- filter.getFrequencyResponse(frequencyHz, magResponse,
- phaseResponse);
- for (var j = 0; j < width; j++) {
- totalMagResponse[j] *= magResponse[j];
- }
- }
-
- /* Draw the response */
- canvasContext.fillStyle = 'rgb(0, 0, 0)';
- canvasContext.fillRect(0, 0, width, height);
- canvasContext.strokeStyle = curveColor;
- canvasContext.lineWidth = 3;
- canvasContext.beginPath();
-
- for (var i = 0; i < width; ++i) {
- var response = totalMagResponse[i];
- var dbResponse = linearToDb(response);
-
- var x = i;
- var y = height - (dbResponse + 24) * pixelsPerDb;
-
- canvasContext.lineTo(x, y);
- }
- canvasContext.stroke();
-
- /* Draw frequency scale. */
- canvasContext.beginPath();
- canvasContext.lineWidth = 1;
- canvasContext.strokeStyle = gridColor;
-
- for (var octave = 0; octave <= noctaves; octave++) {
- var x = octave * width / noctaves;
-
- canvasContext.moveTo(x, 30);
- canvasContext.lineTo(x, height);
- canvasContext.stroke();
-
- var f = nyquist * Math.pow(2.0, octave - noctaves);
- canvasContext.textAlign = 'center';
- canvasContext.strokeText(f.toFixed(0) + 'Hz', x, 20);
- }
-
- /* Draw 0dB line. */
- canvasContext.beginPath();
- canvasContext.moveTo(0, 0.5 * height);
- canvasContext.lineTo(width, 0.5 * height);
- canvasContext.stroke();
-
- /* Draw decibel scale. */
- for (var db = -24.0; db < 24.0; db += 6) {
- var y = height - (db + 24) * pixelsPerDb;
- canvasContext.beginPath();
- canvasContext.setLineDash([1, 4]);
- canvasContext.moveTo(0, y);
- canvasContext.lineTo(width, y);
- canvasContext.stroke();
- canvasContext.setLineDash([]);
- canvasContext.strokeStyle = textColor;
- canvasContext.strokeText(db.toFixed(0) + 'dB', width - 20, y);
- canvasContext.strokeStyle = gridColor;
- }
- }
-
- function update_freq(index, v) {
- centerFreq[index] = v;
- drawCurve();
- }
-
- function update_q(index, v) {
- q[index] = v;
- drawCurve();
- }
-
- function update_gain(index, v) {
- gain[index] = v;
- drawCurve();
- }
-
- function update_enable(index, v) {
- drawCurve();
- }
-
- function update_type(index, v) {
- drawCurve();
- }
-
- function init() {
- drawCurve();
- }
-
- this.init = init;
- this.update_freq = update_freq;
- this.update_q = update_q;
- this.update_gain = update_gain;
- this.update_enable = update_enable;
- this.update_type = update_type;
-}
-
-/* Draws the FFT curve on a canvas. This will update continuously when the audio
- * is playing. */
-function FFTDrawer(canvas, channel) {
- var canvasContext = canvas.getContext('2d');
- var curveColor = 'rgb(255,160,122)';
- var binCount = FFT_SIZE / 2;
- var data = new Float32Array(binCount);
-
- function drawCurve() {
- var width = canvas.width;
- var height = canvas.height;
- var pixelsPerDb = height / 96.0;
-
- canvasContext.clearRect(0, 0, width, height);
-
- /* Get the proper analyzer from the audio graph */
- var analyzer = (channel == 0) ? analyzer_left : analyzer_right;
- if (!analyzer || !get_global('enable_fft')) {
- requestAnimationFrame(drawCurve);
- return;
- }
-
- /* Draw decibel scale. */
- for (var db = -96.0; db <= 0; db += 12) {
- var y = height - (db + 96) * pixelsPerDb;
- canvasContext.strokeStyle = curveColor;
- canvasContext.strokeText(db.toFixed(0) + 'dB', 10, y);
- }
-
- /* Draw FFT */
- analyzer.getFloatFrequencyData(data);
- canvasContext.beginPath();
- canvasContext.lineWidth = 1;
- canvasContext.strokeStyle = curveColor;
- canvasContext.moveTo(0, height);
-
- var frequencyHz = new Float32Array(width);
- for (var i = 0; i < binCount; ++i) {
- var f = i / binCount;
-
- /* Convert to log frequency scale (octaves). */
- var noctaves = 10;
- f = 1 + Math.log(f) / (noctaves * Math.LN2);
-
- /* Draw the magnitude */
- var x = f * width;
- var y = height - (data[i] + 96) * pixelsPerDb;
-
- canvasContext.lineTo(x, y);
- }
-
- canvasContext.stroke();
- requestAnimationFrame(drawCurve);
- }
-
- function init() {
- requestAnimationFrame(drawCurve);
- }
-
- this.init = init;
-}
-
-function dBToLinear(db) {
- return Math.pow(10.0, 0.05 * db);
-}
-
-function linearToDb(x) {
- return 20.0 * Math.log(x) / Math.LN10;
-}
diff --git a/scripts/audio_tuning/frontend/google_drive_picker.js b/scripts/audio_tuning/frontend/google_drive_picker.js
deleted file mode 100644
index 1a375deb..00000000
--- a/scripts/audio_tuning/frontend/google_drive_picker.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Client id obtained from API console credential page should be set before
- * running this script. */
-if (!CLIENT_ID) {
- console.error.log('CLIENT_ID is not set');
-}
-
-/* Initialize a Google Drive picker after Google client API is loaded. */
-function onGoogleClientApiLoad() {
- var picker = new Picker({
- clientId: CLIENT_ID,
- button: document.getElementById('google_drive_pick_file')
- });
-}
-
-/* Initializes a Google Drive picker and loads drive API and picker API.*/
-var Picker = function(options) {
- this.clientId = options.clientId;
- this.button = options.button;
- this.button.addEventListener('click', this.open.bind(this));
-
- gapi.client.load('drive', 'v2');
- gapi.load('picker', {callback: this.onPickerApiLoaded.bind(this) });
-}
-
-/* Enable the button after picker API is loaded. */
-Picker.prototype.onPickerApiLoaded = function() {
- this.button.disabled = false;
-};
-
-/* Let user authenticate and show file picker. */
-Picker.prototype.open = function(){
- if (gapi.auth.getToken()) {
- this.showFilePicker();
- } else {
- this.authenticate(this.showFilePicker.bind(this));
- }
-};
-
-/* Run authenticate using auth API. */
-Picker.prototype.authenticate = function(callback) {
- gapi.auth.authorize(
- {
- client_id: this.clientId + '.apps.googleusercontent.com',
- scope: 'https://www.googleapis.com/auth/drive.readonly',
- immediate: false
- },
- callback);
-};
-
-/* Create a picker using picker API. */
-Picker.prototype.showFilePicker = function() {
- var accessToken = gapi.auth.getToken().access_token;
- this.picker = new google.picker.PickerBuilder().
- addView(google.picker.ViewId.DOCS).
- setAppId(this.clientId).
- setOAuthToken(accessToken).
- setCallback(this.onFilePicked.bind(this)).
- build().
- setVisible(true);
-};
-
-/* Request the file using drive API once a file is picked. */
-Picker.prototype.onFilePicked = function(data) {
- if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
- var file = data[google.picker.Response.DOCUMENTS][0];
- var id = file[google.picker.Document.ID];
- var request = gapi.client.drive.files.get({fileId: id});
- request.execute(this.onFileGet.bind(this));
- }
-};
-
-/* Retrieve the file URL and access token and set it as audio source. */
-Picker.prototype.onFileGet = function(file) {
- var accessToken = gapi.auth.getToken().access_token;
- var authedUrl = file.downloadUrl + "&access_token="
- + encodeURIComponent(accessToken);
- audio_source_set(authedUrl);
-};
diff --git a/scripts/audio_tuning/frontend/setup_credential.js b/scripts/audio_tuning/frontend/setup_credential.js
deleted file mode 100644
index 524b9586..00000000
--- a/scripts/audio_tuning/frontend/setup_credential.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Copyright 2015 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/* Before deploying the project to the website, developer must
- * 1. Enable Google drive API in Google Developers Console.
- * 2. Set "JavaScript origins" and "Referers" in credential page.
- * 3. Fill in <API_KEY> and <CLIENT_ID> below from credential page. */
-document.write('<script src="https://www.google.com/jsapi?key=<API_KEY>" type="text/javascript"></script>');
-CLIENT_ID = '<CLIENT_ID>';
diff --git a/scripts/ini_editor.py b/scripts/ini_editor.py
deleted file mode 100755
index aeeaefbd..00000000
--- a/scripts/ini_editor.py
+++ /dev/null
@@ -1,628 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""
-A script to modify dsp.ini config files.
-A dsp.ini config file is represented by an Ini object.
-An Ini object contains one or more Sections.
-Each Section has a name, a list of Ports, and a list of NonPorts.
-"""
-
-import argparse
-import logging
-import os
-import re
-import StringIO
-import sys
-from collections import namedtuple
-
-Parameter = namedtuple('Parameter', ['value', 'comment'])
-
-
-class Port(object):
- """Class for port definition in ini file.
-
- Properties:
- io: "input" or "output".
- index: an integer for port index.
- definition: a string for the content after "=" in port definition line.
- parameter: a Parameter namedtuple which is parsed from definition.
- """
- @staticmethod
- def ParsePortLine(line):
- """Parses a port definition line in ini file and init a Port object.
-
- Args:
- line: A string possibly containing port definition line like
- "input_0=1; something".
-
- Returns:
- A Port object if input is a valid port definition line. Returns
- None if input is not a valid port definition line.
- """
- result = re.match(r'(input|output)_(\d+)=(.*)', line)
- if result:
- parse_values = result.groups()
- io = parse_values[0]
- index = int(parse_values[1])
- definition = parse_values[2]
- return Port(io, index, definition)
- else:
- return None
-
- def __init__(self, io, index, definition):
- """Initializes a port.
-
- Initializes a port with io, index and definition. The definition will be
- further parsed to Parameter(value, comment) if the format matches
- "<some value> ; <some comment>".
-
- Args:
- io: "input" or "output".
- index: an integer for port index.
- definition: a string for the content after "=" in port definition line.
- """
- self.io = io
- self.index = index
- self.definition = definition
- result = re.match(r'(\S+)\s+; (.+)', definition)
- if result:
- self.parameter = Parameter._make(result.groups())
- else:
- self.parameter = None
-
- def FormatLine(self):
- """Returns a port definition line which is used in ini file."""
- line = '%s_%d=' % (self.io, self.index)
- if self.parameter:
- line +="{:<8}; {:}".format(self.parameter.value, self.parameter.comment)
- else:
- line += self.definition
- return line
-
- def _UpdateIndex(self, index):
- """Updates index of this port.
-
- Args:
- index: The new index.
- """
- self.index = index
-
-
-class NonPort(object):
- """Class for non-port definition in ini file.
-
- Properties:
- name: A string representing the non-port name.
- definition: A string representing the non-port definition.
- """
- @staticmethod
- def ParseNonPortLine(line):
- """Parses a non-port definition line in ini file and init a NonPort object.
-
- Args:
- line: A string possibly containing non-port definition line like
- "library=builtin".
-
- Returns:
- A NonPort object if input is a valid non-port definition line. Returns
- None if input is not a valid non-port definition line.
- """
- result = re.match(r'(\w+)=(.*)', line)
- if result:
- parse_values = result.groups()
- name = parse_values[0]
- definition = parse_values[1]
- return NonPort(name, definition)
- else:
- return None
-
- def __init__(self, name, definition):
- """Initializes a NonPort <name>=<definition>.
-
- Args:
- name: A string representing the non-port name.
- definition: A string representing the non-port definition.
- """
- self.name = name
- self.definition = definition
-
- def FormatLine(self):
- """Formats a string representation of a NonPort.
-
- Returns:
- A string "<name>=<definition>".
- """
- line = '%s=%s' % (self.name, self.definition)
- return line
-
-
-class SectionException(Exception):
- pass
-
-
-class Section(object):
- """Class for section definition in ini file.
-
- Properties:
- name: Section name.
- non_ports: A list containing NonPorts of this section.
- ports: A list containing Ports of this section.
- """
- @staticmethod
- def ParseSectionName(line):
- """Parses a section name.
-
- Args:
- line: A string possibly containing a section name like [drc].
-
- Returns:
- Returns parsed section name without '[' and ']' if input matches
- the syntax [<section name>]. Returns None if not.
- """
- result = re.match(r'\[(\w+)\]', line)
- return result.groups()[0] if result else None
-
- @staticmethod
- def ParseLine(line):
- """Parses a line that belongs to a section.
-
- Returns:
- A Port or NonPort object if input line matches the format. Returns None
- if input line does not match the format of Port nor NonPort.
- """
- if not line:
- return
- parse_port = Port.ParsePortLine(line)
- if parse_port:
- return parse_port
- parse_non_port = NonPort.ParseNonPortLine(line)
- if parse_non_port:
- return parse_non_port
-
- def __init__(self, name):
- """Initializes a Section with given name."""
- self.name = name
- self.non_ports= []
- self.ports = []
-
- def AddLine(self, line):
- """Adds a line to this Section.
-
- Args:
- line: A line to be added to this section. If it matches port or non-port
- format, a Port or NonPort will be added to this section. Otherwise,
- this line is ignored.
- """
- to_add = Section.ParseLine(line)
- if not to_add:
- return
- if isinstance(to_add, Port):
- self.AppendPort(to_add)
- return
- if isinstance(to_add, NonPort):
- self.AppendNonPort(to_add)
- return
-
- def AppendNonPort(self, non_port):
- """Appends a NonPort to non_ports.
-
- Args:
- non_port: A NonPort object to be appended.
- """
- self.non_ports.append(non_port)
-
- def AppendPort(self, port):
- """Appends a Port to ports.
-
- Args:
- port: A Port object to be appended. The port should be appended
- in the order of index, so the index of port should equal to the current
- size of ports list.
-
- Raises:
- SectionException if the index of port is not the current size of ports
- list.
- """
- if not port.index == len(self.ports):
- raise SectionException(
- 'The port with index %r can not be appended to the end of ports'
- ' of size' % (port.index, len(self.ports)))
- else:
- self.ports.append(port)
-
- def InsertLine(self, line):
- """Inserts a line to this section.
-
- Inserts a line containing port or non-port definition to this section.
- If input line matches Port or NonPort format, the corresponding insert
- method InsertNonPort or InsertPort will be called. If input line does not
- match the format, SectionException will be raised.
-
- Args:
- line: A line to be inserted. The line should
-
- Raises:
- SectionException if input line does not match the format of Port or
- NonPort.
- """
- to_insert = Section.ParseLine(line)
- if not to_insert:
- raise SectionException(
- 'The line %s does not match Port or NonPort syntax' % line)
- if isinstance(to_insert, Port):
- self.InsertPort(to_insert)
- return
- if isinstance(to_insert, NonPort):
- self.InsertNonPort(to_insert)
- return
-
- def InsertNonPort(self, non_port):
- """Inserts a NonPort to non_ports list.
-
- Currently there is no ordering for non-port definition. This method just
- appends non_port to non_ports list.
-
- Args:
- non_port: A NonPort object.
- """
- self.non_ports.append(non_port)
-
- def InsertPort(self, port):
- """Inserts a Port to ports list.
-
- The index of port should not be greater than the current size of ports.
- After insertion, the index of each port in ports should be updated to the
- new index of that port in the ports list.
- E.g. Before insertion:
- self.ports=[Port("input", 0, "foo0"),
- Port("input", 1, "foo1"),
- Port("output", 2, "foo2")]
- Now we insert a Port with index 1 by invoking
- InsertPort(Port("output, 1, "bar")),
- Then,
- self.ports=[Port("input", 0, "foo0"),
- Port("output, 1, "bar"),
- Port("input", 2, "foo1"),
- Port("output", 3, "foo2")].
- Note that the indices of foo1 and foo2 had been shifted by one because a
- new port was inserted at index 1.
-
- Args:
- port: A Port object.
-
- Raises:
- SectionException: If the port to be inserted does not have a valid index.
- """
- if port.index > len(self.ports):
- raise SectionException('Inserting port index %d but'
- ' currently there are only %d ports' % (port.index,
- len(self.ports)))
-
- self.ports.insert(port.index, port)
- self._UpdatePorts()
-
- def _UpdatePorts(self):
- """Updates the index property of each Port in ports.
-
- Updates the index property of each Port in ports so the new index property
- is the index of that Port in ports list.
- """
- for index, port in enumerate(self.ports):
- port._UpdateIndex(index)
-
- def Print(self, output):
- """Prints the section definition to output.
-
- The format is:
- [section_name]
- non_port_name_0=non_port_definition_0
- non_port_name_1=non_port_definition_1
- ...
- port_name_0=port_definition_0
- port_name_1=port_definition_1
- ...
-
- Args:
- output: A StringIO.StringIO object.
- """
- output.write('[%s]\n' % self.name)
- for non_port in self.non_ports:
- output.write('%s\n' % non_port.FormatLine())
- for port in self.ports:
- output.write('%s\n' % port.FormatLine())
-
-
-class Ini(object):
- """Class for an ini config file.
-
- Properties:
- sections: A dict containing mapping from section name to Section.
- section_names: A list of section names.
- file_path: The path of this ini config file.
- """
- def __init__(self, input_file):
- """Initializes an Ini object from input config file.
-
- Args:
- input_file: The path to an ini config file.
- """
- self.sections = {}
- self.section_names = []
- self.file_path = input_file
- self._ParseFromFile(input_file)
-
- def _ParseFromFile(self, input_file):
- """Parses sections in the input config file.
-
- Reads in the content of the input config file and parses each sections.
- The parsed sections are stored in sections dict.
- The names of each section is stored in section_names list.
-
- Args:
- input_file: The path to an ini config file.
- """
- content = open(input_file, 'r').read()
- content_lines = content.splitlines()
- self.sections = {}
- self.section_names = []
- current_name = None
- for line in content_lines:
- name = Section.ParseSectionName(line)
- if name:
- self.section_names.append(name)
- self.sections[name] = Section(name)
- current_name = name
- else:
- self.sections[current_name].AddLine(line)
-
- def Print(self, output_file=None):
- """Prints all sections of this Ini object.
-
- Args:
- output_file: The path to write output. If this is not None, writes the
- output to this path. Otherwise, just print the output to console.
-
- Returns:
- A StringIO.StringIO object containing output.
- """
- output = StringIO.StringIO()
- for index, name in enumerate(self.section_names):
- self.sections[name].Print(output)
- if index < len(self.section_names) - 1:
- output.write('\n')
- if output_file:
- with open(output_file, 'w') as f:
- f.write(output.getvalue())
- output.close()
- else:
- print output.getvalue()
- return output
-
- def HasSection(self, name):
- """Checks if this Ini object has a section with certain name.
-
- Args:
- name: The name of the section.
- """
- return name in self.sections
-
- def PrintSection(self, name):
- """Prints a section to console.
-
- Args:
- name: The name of the section.
-
- Returns:
- A StringIO.StringIO object containing output.
- """
- output = StringIO.StringIO()
- self.sections[name].Print(output)
- output.write('\n')
- print output.getvalue()
- return output
-
- def InsertLineToSection(self, name, line):
- """Inserts a line to a section.
-
- Args:
- name: The name of the section.
- line: A line to be inserted.
- """
- self.sections[name].InsertLine(line)
-
-
-def prompt(question, binary_answer=True):
- """Displays the question to the user and wait for input.
-
- Args:
- question: The question to be displayed to user.
- binary_answer: True to expect an yes/no answer from user.
- Returns:
- True/False if binary_answer is True. Otherwise, returns a string
- containing user input to the question.
- """
-
- sys.stdout.write(question)
- answer = raw_input()
- if binary_answer:
- answer = answer.lower()
- if answer in ['y', 'yes']:
- return True
- elif answer in ['n', 'no']:
- return False
- else:
- return prompt(question)
- else:
- return answer
-
-
-class IniEditorException(Exception):
- pass
-
-
-class IniEditor(object):
- """The class for ini file editing command line interface.
-
- Properties:
- input_files: The files to be edited. Note that the same editing command
- can be applied on many config files.
- args: The result of ArgumentParser.parse_args method. It is an object
- containing args as attributes.
- """
- def __init__(self):
- self.input_files = []
- self.args = None
-
- def Main(self):
- """The main method of IniEditor.
-
- Parses the arguments and processes files according to the arguments.
- """
- self.ParseArgs()
- self.ProcessFiles()
-
- def ParseArgs(self):
- """Parses the arguments from command line.
-
- Parses the arguments from command line to determine input_files.
- Also, checks the arguments are valid.
-
- Raises:
- IniEditorException if arguments are not valid.
- """
- parser = argparse.ArgumentParser(
- description=('Edit or show the config files'))
- parser.add_argument('--input_file', '-i', default=None,
- help='Use the specified file as input file. If this '
- 'is not given, the editor will try to find config '
- 'files using config_dirs and board.')
- parser.add_argument('--config_dirs', '-c',
- default='~/trunk/src/third_party/adhd/cras-config',
- help='Config directory. By default it is '
- '~/trunk/src/third_party/adhd/cras-config.')
- parser.add_argument('--board', '-b', default=None, nargs='*',
- help='The boards to apply the changes. Use "all" '
- 'to apply on all boards. '
- 'Use --board <board_1> <board_2> to specify more '
- 'than one boards')
- parser.add_argument('--section', '-s', default=None,
- help='The section to be shown/edited in the ini file.')
- parser.add_argument('--insert', '-n', default=None,
- help='The line to be inserted into the ini file. '
- 'Must be used with --section.')
- parser.add_argument('--output-suffix', '-o', default='.new',
- help='The output file suffix. Set it to "None" if you '
- 'want to apply the changes in-place.')
- self.args = parser.parse_args()
-
- # If input file is given, just edit this file.
- if self.args.input_file:
- self.input_files.append(self.args.input_file)
- # Otherwise, try to find config files in board directories of config
- # directory.
- else:
- if self.args.config_dirs.startswith('~'):
- self.args.config_dirs = os.path.join(
- os.path.expanduser('~'),
- self.args.config_dirs.split('~/')[1])
- all_boards = os.walk(self.args.config_dirs).next()[1]
- # "board" argument must be a valid board name or "all".
- if (not self.args.board or
- (self.args.board != ['all'] and
- not set(self.args.board).issubset(set(all_boards)))):
- logging.error('Please select a board from %s or use "all".' % (
- ', '.join(all_boards)))
- raise IniEditorException('User must specify board if input_file '
- 'is not given.')
- if self.args.board == ['all']:
- logging.info('Applying on all boards.')
- boards = all_boards
- else:
- boards = self.args.board
-
- self.input_files = []
- # Finds dsp.ini files in candidate boards directories.
- for board in boards:
- ini_file = os.path.join(self.args.config_dirs, board, 'dsp.ini')
- if os.path.exists(ini_file):
- self.input_files.append(ini_file)
-
- if self.args.insert and not self.args.section:
- raise IniEditorException('--insert must be used with --section')
-
- def ProcessFiles(self):
- """Processes the config files in input_files.
-
- Showes or edits every selected config file.
- """
- for input_file in self.input_files:
- logging.info('Looking at dsp.ini file at %s', input_file)
- ini = Ini(input_file)
- if self.args.insert:
- self.InsertCommand(ini)
- else:
- self.PrintCommand(ini)
-
- def PrintCommand(self, ini):
- """Prints this Ini object.
-
- Prints all sections or a section in input Ini object if
- args.section is specified and there is such section in this Ini object.
-
- Args:
- ini: An Ini object.
- """
- if self.args.section:
- if ini.HasSection(self.args.section):
- logging.info('Printing section %s.', self.args.section)
- ini.PrintSection(self.args.section)
- else:
- logging.info('There is no section %s in %s',
- self.args.section, ini.file_path)
- else:
- logging.info('Printing ini content.')
- ini.Print()
-
- def InsertCommand(self, ini):
- """Processes insertion editing on Ini object.
-
- Inserts args.insert to section named args.section in input Ini object.
- If input Ini object does not have a section named args.section, this method
- does not do anything. If the editing is valid, prints the changed section
- to console. Writes the editied config file to the same path as input path
- plus a suffix speficied in args.output_suffix. If that suffix is "None",
- prompts and waits for user to confirm editing in-place.
-
- Args:
- ini: An Ini object.
- """
- if not ini.HasSection(self.args.section):
- logging.info('There is no section %s in %s',
- self.args.section, ini.file_path)
- return
-
- ini.InsertLineToSection(self.args.section, self.args.insert)
- logging.info('Changed section:')
- ini.PrintSection(self.args.section)
-
- if self.args.output_suffix == 'None':
- answer = prompt(
- 'Writing output file in-place at %s ? [y/n]' % ini.file_path)
- if not answer:
- sys.exit('Abort!')
- output_file = ini.file_path
- else:
- output_file = ini.file_path + self.args.output_suffix
- logging.info('Writing output file to : %s.', output_file)
- ini.Print(output_file)
-
-
-if __name__ == '__main__':
- logging.basicConfig(
- format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s',
- level=logging.DEBUG)
- IniEditor().Main()
diff --git a/scripts/ini_editor_unittest.py b/scripts/ini_editor_unittest.py
deleted file mode 100755
index b953c147..00000000
--- a/scripts/ini_editor_unittest.py
+++ /dev/null
@@ -1,145 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-
-"""Unittest for ini_editor.py."""
-
-
-import logging
-import os
-import re
-import tempfile
-import unittest
-
-from ini_editor import Ini
-
-SAMPLE_INI="""\
-[output_source]
-library=builtin
-label=source
-purpose=playback
-disable=(equal? output_jack "HDMI")
-output_0={src:0}
-output_1={src:1}
-
-[output_sink]
-library=builtin
-label=sink
-purpose=playback
-disable=(equal? output_jack "HDMI")
-input_0={dst:0}
-input_1={dst:1}
-
-[drc]
-library=builtin
-label=drc
-input_0={src:0}
-input_1={src:1}
-output_2={intermediate:0}
-output_3={intermediate:1}
-input_4=0 ; f
-input_5=0 ; enable
-input_6=-29 ; threshold
-input_7=3 ; knee
-input_8=6.677 ; ratio
-input_9=0.02 ; attack
-input_10=0.2 ; release
-input_11=-7 ; boost
-
-[eq2]
-library=builtin
-label=eq2
-input_0={intermediate:0}
-input_1={intermediate:1}
-output_2={dst:0}
-output_3={dst:1}
-input_4=6 ; peaking
-input_5=380 ; freq
-input_6=3 ; Q
-input_7=-10 ; gain
-input_8=6 ; peaking
-input_9=450 ; freq
-input_10=3 ; Q
-input_11=-12 ; gain
-"""
-
-SAMPLE_INI_DRC="""\
-[drc]
-library=builtin
-label=drc
-input_0={src:0}
-input_1={src:1}
-output_2={intermediate:0}
-output_3={intermediate:1}
-input_4=0 ; f
-input_5=0 ; enable
-input_6=-29 ; threshold
-input_7=3 ; knee
-input_8=6.677 ; ratio
-input_9=0.02 ; attack
-input_10=0.2 ; release
-input_11=-7 ; boost
-
-"""
-
-SAMPLE_INI_DRC_INSERTED="""\
-[drc]
-library=builtin
-label=drc
-input_0={src:0}
-input_1={src:1}
-output_2={intermediate:0}
-output_3={intermediate:1}
-input_4=1 ; new_parameter
-input_5=0 ; f
-input_6=0 ; enable
-input_7=-29 ; threshold
-input_8=3 ; knee
-input_9=6.677 ; ratio
-input_10=0.02 ; attack
-input_11=0.2 ; release
-input_12=-7 ; boost
-
-"""
-
-
-class IniTest(unittest.TestCase):
- """Unittest for Ini class."""
- def setUp(self):
- self.ini_file = tempfile.NamedTemporaryFile(prefix='ini_editor_unittest')
- with open(self.ini_file.name, 'w') as f:
- f.write(SAMPLE_INI)
- self.ini = Ini(self.ini_file.name)
-
- def tearDown(self):
- self.ini_file.close()
-
- def testPrint(self):
- """Unittest for Print method of Ini class."""
- output = self.ini.Print()
- self.assertEqual(output.getvalue(), SAMPLE_INI)
-
- def testHasSection(self):
- """Unittest for HasSection method of Ini class."""
- self.assertTrue(self.ini.HasSection('drc'))
- self.assertFalse(self.ini.HasSection('eq1'))
-
- def testPrintSection(self):
- """Unittest for PrintSection method of Ini class."""
- output = self.ini.PrintSection('drc')
- self.assertEqual(output.getvalue(), SAMPLE_INI_DRC)
-
- def testInsertLineToSection(self):
- """Unittest for InsertLineToSection method of Ini class."""
- self.ini.InsertLineToSection('drc', 'input_4=1 ; new_parameter')
- output = self.ini.PrintSection('drc')
- self.assertEqual(output.getvalue(), SAMPLE_INI_DRC_INSERTED)
-
-
-if __name__ == '__main__':
- logging.basicConfig(
- format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s',
- level=logging.DEBUG)
- unittest.main()
diff --git a/scripts/mic_testing/frontend/LICENSE b/scripts/mic_testing/frontend/LICENSE
deleted file mode 100644
index 0aa7fc93..00000000
--- a/scripts/mic_testing/frontend/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2006-2009 The Chromium OS Authors. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/scripts/mic_testing/frontend/analysis.js b/scripts/mic_testing/frontend/analysis.js
deleted file mode 100644
index 871c7643..00000000
--- a/scripts/mic_testing/frontend/analysis.js
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-/**
- * Gets a random color
- */
-function getRandomColor() {
- var letters = '0123456789ABCDEF'.split('');
- var color = '#';
- for (var i = 0; i < 6; i++) {
- color += letters[Math.floor(Math.random() * 16)];
- }
- return color;
-}
-
-/**
- * Audio channel class
- */
-var AudioChannel = function(buffer) {
- this.init = function(buffer) {
- this.buffer = buffer;
- this.fftBuffer = this.toFFT(this.buffer);
- this.curveColor = getRandomColor();
- this.visible = true;
- }
-
- this.toFFT = function(buffer) {
- var k = Math.ceil(Math.log(buffer.length) / Math.LN2);
- var length = Math.pow(2, k);
- var tmpBuffer = new Float32Array(length);
-
- for (var i = 0; i < buffer.length; i++) {
- tmpBuffer[i] = buffer[i];
- }
- for (var i = buffer.length; i < length; i++) {
- tmpBuffer[i] = 0;
- }
- var fft = new FFT(length);
- fft.forward(tmpBuffer);
- return fft.spectrum;
- }
-
- this.init(buffer);
-}
-
-window.AudioChannel = AudioChannel;
-
-var numberOfCurve = 0;
-
-/**
- * Audio curve class
- */
-var AudioCurve = function(buffers, filename, sampleRate) {
- this.init = function(buffers, filename) {
- this.filename = filename;
- this.id = numberOfCurve++;
- this.sampleRate = sampleRate;
- this.channel = [];
- for (var i = 0; i < buffers.length; i++) {
- this.channel.push(new AudioChannel(buffers[i]));
- }
- }
- this.init(buffers, filename);
-}
-
-window.AudioCurve = AudioCurve;
-
-/**
- * Draw frequency response of curves on the canvas
- * @param {canvas} HTML canvas element to draw frequency response
- * @param {int} Nyquist frequency, in Hz
- */
-var DrawCanvas = function(canvas, nyquist) {
- var HTML_TABLE_ROW_OFFSET = 2;
- var topMargin = 30;
- var leftMargin = 40;
- var downMargin = 10;
- var rightMargin = 30;
- var width = canvas.width - leftMargin - rightMargin;
- var height = canvas.height - topMargin - downMargin;
- var canvasContext = canvas.getContext('2d');
- var pixelsPerDb = height / 96.0;
- var noctaves = 10;
- var curveBuffer = [];
-
- findId = function(id) {
- for (var i = 0; i < curveBuffer.length; i++)
- if (curveBuffer[i].id == id)
- return i;
- return -1;
- }
-
- /**
- * Adds curve on the canvas
- * @param {AudioCurve} audio curve object
- */
- this.add = function(audioCurve) {
- curveBuffer.push(audioCurve);
- addTableList();
- this.drawCanvas();
- }
-
- /**
- * Removes curve from the canvas
- * @param {int} curve index
- */
- this.remove = function(id) {
- var index = findId(id);
- if (index != -1) {
- curveBuffer.splice(index, 1);
- removeTableList(index);
- this.drawCanvas();
- }
- }
-
- removeTableList = function(index) {
- var table = document.getElementById('curve_table');
- table.deleteRow(index + HTML_TABLE_ROW_OFFSET);
- }
-
- addTableList = function() {
- var table = document.getElementById('curve_table');
- var index = table.rows.length - HTML_TABLE_ROW_OFFSET;
- var curve_id = curveBuffer[index].id;
- var tr = table.insertRow(table.rows.length);
- var tdCheckbox = tr.insertCell(0);
- var tdFile = tr.insertCell(1);
- var tdLeft = tr.insertCell(2);
- var tdRight = tr.insertCell(3);
- var tdRemove = tr.insertCell(4);
-
- var checkbox = document.createElement('input');
- checkbox.setAttribute('type', 'checkbox');
- checkbox.checked = true;
- checkbox.onclick = function() {
- setCurveVisible(checkbox, curve_id, 'all');
- }
- tdCheckbox.appendChild(checkbox);
- tdFile.innerHTML = curveBuffer[index].filename;
-
- var checkLeft = document.createElement('input');
- checkLeft.setAttribute('type', 'checkbox');
- checkLeft.checked = true;
- checkLeft.onclick = function() {
- setCurveVisible(checkLeft, curve_id, 0);
- }
- tdLeft.bgColor = curveBuffer[index].channel[0].curveColor;
- tdLeft.appendChild(checkLeft);
-
- if (curveBuffer[index].channel.length > 1) {
- var checkRight = document.createElement('input');
- checkRight.setAttribute('type', 'checkbox');
- checkRight.checked = true;
- checkRight.onclick = function() {
- setCurveVisible(checkRight, curve_id, 1);
- }
- tdRight.bgColor = curveBuffer[index].channel[1].curveColor;
- tdRight.appendChild(checkRight);
- }
-
- var btnRemove = document.createElement('input');
- btnRemove.setAttribute('type', 'button');
- btnRemove.value = 'Remove';
- btnRemove.onclick = function() { removeCurve(curve_id); }
- tdRemove.appendChild(btnRemove);
- }
-
- /**
- * Sets visibility of curves
- * @param {boolean} visible or not
- * @param {int} curve index
- * @param {int,string} channel index.
- */
- this.setVisible = function(checkbox, id, channel) {
- var index = findId(id);
- if (channel == 'all') {
- for (var i = 0; i < curveBuffer[index].channel.length; i++) {
- curveBuffer[index].channel[i].visible = checkbox.checked;
- }
- } else if (channel == 0 || channel == 1) {
- curveBuffer[index].channel[channel].visible = checkbox.checked;
- }
- this.drawCanvas();
- }
-
- /**
- * Draws canvas background
- */
- this.drawBg = function() {
- var gridColor = 'rgb(200,200,200)';
- var textColor = 'rgb(238,221,130)';
-
- /* Draw the background */
- canvasContext.fillStyle = 'rgb(0, 0, 0)';
- canvasContext.fillRect(0, 0, canvas.width, canvas.height);
-
- /* Draw frequency scale. */
- canvasContext.beginPath();
- canvasContext.lineWidth = 1;
- canvasContext.strokeStyle = gridColor;
-
- for (var octave = 0; octave <= noctaves; octave++) {
- var x = octave * width / noctaves + leftMargin;
-
- canvasContext.moveTo(x, topMargin);
- canvasContext.lineTo(x, topMargin + height);
- canvasContext.stroke();
-
- var f = nyquist * Math.pow(2.0, octave - noctaves);
- canvasContext.textAlign = 'center';
- canvasContext.strokeText(f.toFixed(0) + 'Hz', x, 20);
- }
-
- /* Draw 0dB line. */
- canvasContext.beginPath();
- canvasContext.moveTo(leftMargin, topMargin + 0.5 * height);
- canvasContext.lineTo(leftMargin + width, topMargin + 0.5 * height);
- canvasContext.stroke();
-
- /* Draw decibel scale. */
- for (var db = -96.0; db <= 0; db += 12) {
- var y = topMargin + height - (db + 96) * pixelsPerDb;
- canvasContext.beginPath();
- canvasContext.setLineDash([1, 4]);
- canvasContext.moveTo(leftMargin, y);
- canvasContext.lineTo(leftMargin + width, y);
- canvasContext.stroke();
- canvasContext.setLineDash([]);
- canvasContext.strokeStyle = textColor;
- canvasContext.strokeText(db.toFixed(0) + 'dB', 20, y);
- canvasContext.strokeStyle = gridColor;
- }
- }
-
- /**
- * Draws a channel of a curve
- * @param {Float32Array} fft buffer of a channel
- * @param {string} curve color
- * @param {int} sample rate
- */
- this.drawCurve = function(buffer, curveColor, sampleRate) {
- canvasContext.beginPath();
- canvasContext.lineWidth = 1;
- canvasContext.strokeStyle = curveColor;
- canvasContext.moveTo(leftMargin, topMargin + height);
-
- for (var i = 0; i < buffer.length; ++i) {
- var f = i * sampleRate / 2 / nyquist / buffer.length;
-
- /* Convert to log frequency scale (octaves). */
- f = 1 + Math.log(f) / (noctaves * Math.LN2);
- if (f < 0) { continue; }
- /* Draw the magnitude */
- var x = f * width + leftMargin;
- var value = Math.max(20 * Math.log(buffer[i]) / Math.LN10, -96);
- var y = topMargin + height - ((value + 96) * pixelsPerDb);
-
- canvasContext.lineTo(x, y);
- }
- canvasContext.stroke();
- }
-
- /**
- * Draws all curves
- */
- this.drawCanvas = function() {
- this.drawBg();
- for (var i = 0; i < curveBuffer.length; i++) {
- for (var j = 0; j < curveBuffer[i].channel.length; j++) {
- if (curveBuffer[i].channel[j].visible) {
- this.drawCurve(curveBuffer[i].channel[j].fftBuffer,
- curveBuffer[i].channel[j].curveColor,
- curveBuffer[i].sampleRate);
- }
- }
- }
- }
-
- /**
- * Draws current buffer
- * @param {Float32Array} left channel buffer
- * @param {Float32Array} right channel buffer
- * @param {int} sample rate
- */
- this.drawInstantCurve = function(leftData, rightData, sampleRate) {
- this.drawBg();
- var fftLeft = new FFT(leftData.length);
- fftLeft.forward(leftData);
- var fftRight = new FFT(rightData.length);
- fftRight.forward(rightData);
- this.drawCurve(fftLeft.spectrum, "#FF0000", sampleRate);
- this.drawCurve(fftRight.spectrum, "#00FF00", sampleRate);
- }
-
- exportCurveByFreq = function(freqList) {
- function calcIndex(freq, length, sampleRate) {
- var idx = parseInt(freq * length * 2 / sampleRate);
- return Math.min(idx, length - 1);
- }
- /* header */
- channelName = ['L', 'R'];
- cvsString = 'freq';
- for (var i = 0; i < curveBuffer.length; i++) {
- for (var j = 0; j < curveBuffer[i].channel.length; j++) {
- cvsString += ',' + curveBuffer[i].filename + '_' + channelName[j];
- }
- }
- for (var i = 0; i < freqList.length; i++) {
- cvsString += '\n' + freqList[i];
- for (var j = 0; j < curveBuffer.length; j++) {
- var curve = curveBuffer[j];
- for (var k = 0; k < curve.channel.length; k++) {
- var fftBuffer = curve.channel[k].fftBuffer;
- var prevIdx = (i - 1 < 0) ? 0 :
- calcIndex(freqList[i - 1], fftBuffer.length, curve.sampleRate);
- var currIdx = calcIndex(
- freqList[i], fftBuffer.length, curve.sampleRate);
-
- var sum = 0;
- for (var l = prevIdx; l <= currIdx; l++) { // Get average
- var value = 20 * Math.log(fftBuffer[l]) / Math.LN10;
- sum += value;
- }
- cvsString += ',' + sum / (currIdx - prevIdx + 1);
- }
- }
- }
- return cvsString;
- }
-
- /**
- * Exports frequency response of curves into CSV format
- * @param {int} point number in octaves
- * @return {string} a string with CSV format
- */
- this.exportCurve = function(nInOctaves) {
- var freqList= [];
- for (var i = 0; i < noctaves; i++) {
- var fStart = nyquist * Math.pow(2.0, i - noctaves);
- var fEnd = nyquist * Math.pow(2.0, i + 1 - noctaves);
- var powerStart = Math.log(fStart) / Math.LN2;
- var powerEnd = Math.log(fEnd) / Math.LN2;
- for (var j = 0; j < nInOctaves; j++) {
- f = Math.pow(2,
- powerStart + j * (powerEnd - powerStart) / nInOctaves);
- freqList.push(f);
- }
- }
- freqList.push(nyquist);
- return exportCurveByFreq(freqList);
- }
-}
-
-window.DrawCanvas = DrawCanvas;
-
-/**
- * FFT is a class for calculating the Discrete Fourier Transform of a signal
- * with the Fast Fourier Transform algorithm.
- *
- * @param {Number} bufferSize The size of the sample buffer to be computed.
- * Must be power of 2
- * @constructor
- */
-function FFT(bufferSize) {
- this.bufferSize = bufferSize;
- this.spectrum = new Float32Array(bufferSize/2);
- this.real = new Float32Array(bufferSize);
- this.imag = new Float32Array(bufferSize);
-
- this.reverseTable = new Uint32Array(bufferSize);
- this.sinTable = new Float32Array(bufferSize);
- this.cosTable = new Float32Array(bufferSize);
-
- var limit = 1;
- var bit = bufferSize >> 1;
- var i;
-
- while (limit < bufferSize) {
- for (i = 0; i < limit; i++) {
- this.reverseTable[i + limit] = this.reverseTable[i] + bit;
- }
-
- limit = limit << 1;
- bit = bit >> 1;
- }
-
- for (i = 0; i < bufferSize; i++) {
- this.sinTable[i] = Math.sin(-Math.PI/i);
- this.cosTable[i] = Math.cos(-Math.PI/i);
- }
-}
-
-/**
- * Performs a forward transform on the sample buffer.
- * Converts a time domain signal to frequency domain spectra.
- *
- * @param {Array} buffer The sample buffer. Buffer Length must be power of 2
- * @returns The frequency spectrum array
- */
-FFT.prototype.forward = function(buffer) {
- var bufferSize = this.bufferSize,
- cosTable = this.cosTable,
- sinTable = this.sinTable,
- reverseTable = this.reverseTable,
- real = this.real,
- imag = this.imag,
- spectrum = this.spectrum;
-
- var k = Math.floor(Math.log(bufferSize) / Math.LN2);
-
- if (Math.pow(2, k) !== bufferSize) {
- throw "Invalid buffer size, must be a power of 2.";
- }
- if (bufferSize !== buffer.length) {
- throw "Supplied buffer is not the same size as defined FFT. FFT Size: "
- + bufferSize + " Buffer Size: " + buffer.length;
- }
-
- var halfSize = 1,
- phaseShiftStepReal,
- phaseShiftStepImag,
- currentPhaseShiftReal,
- currentPhaseShiftImag,
- off,
- tr,
- ti,
- tmpReal,
- i;
-
- for (i = 0; i < bufferSize; i++) {
- real[i] = buffer[reverseTable[i]];
- imag[i] = 0;
- }
-
- while (halfSize < bufferSize) {
- phaseShiftStepReal = cosTable[halfSize];
- phaseShiftStepImag = sinTable[halfSize];
-
- currentPhaseShiftReal = 1.0;
- currentPhaseShiftImag = 0.0;
-
- for (var fftStep = 0; fftStep < halfSize; fftStep++) {
- i = fftStep;
-
- while (i < bufferSize) {
- off = i + halfSize;
- tr = (currentPhaseShiftReal * real[off]) -
- (currentPhaseShiftImag * imag[off]);
- ti = (currentPhaseShiftReal * imag[off]) +
- (currentPhaseShiftImag * real[off]);
- real[off] = real[i] - tr;
- imag[off] = imag[i] - ti;
- real[i] += tr;
- imag[i] += ti;
-
- i += halfSize << 1;
- }
-
- tmpReal = currentPhaseShiftReal;
- currentPhaseShiftReal = (tmpReal * phaseShiftStepReal) -
- (currentPhaseShiftImag * phaseShiftStepImag);
- currentPhaseShiftImag = (tmpReal * phaseShiftStepImag) +
- (currentPhaseShiftImag * phaseShiftStepReal);
- }
-
- halfSize = halfSize << 1;
- }
-
- i = bufferSize / 2;
- while(i--) {
- spectrum[i] = 2 * Math.sqrt(real[i] * real[i] + imag[i] * imag[i]) /
- bufferSize;
- }
-};
-
-function setCurveVisible(checkbox, id, channel) {
- drawContext.setVisible(checkbox, id, channel);
-}
-
-function removeCurve(id) {
- drawContext.remove(id);
-}
diff --git a/scripts/mic_testing/frontend/app.yaml b/scripts/mic_testing/frontend/app.yaml
deleted file mode 100644
index 723472e1..00000000
--- a/scripts/mic_testing/frontend/app.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-application: mic-testing
-version: 1
-runtime: python27
-api_version: 1
-threadsafe: true
-
-handlers:
-- url: /(.*\.css)
- mime_type: text/css
- static_files: \1
- upload: (.*\.css)
-
-- url: /(.*\.html)
- mime_type: text/html
- static_files: \1
- upload: (.*\.html)
-
-- url: /(.*\.js)
- mime_type: text/javascript
- static_files: \1
- upload: (.*\.js)
-
-- url: /(LICENSE)
- mime_type: text/plain
- static_files: \1
- upload: (LICENSE)
-
-- url: /
- static_files: audio.html
- upload: audio.html
diff --git a/scripts/mic_testing/frontend/audio.css b/scripts/mic_testing/frontend/audio.css
deleted file mode 100644
index 9bd2adc4..00000000
--- a/scripts/mic_testing/frontend/audio.css
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-ul {
- margin: 0;
- padding: 0;
-}
-
-li {
- list-style-type: none;
-}
-
-.tab-page {
- display: table;
- table-layout: fixed;
- text-align: center;
- width: 100%;
-}
-
-.tab-page li {
- display: table-cell;
- padding-right: 1px;
- height: auto;
- vertical-align: bottom;
-}
-
-.tab-page a {
- font-size: x-large;
- font-weight: bold;
- display: block;
- min-height: 100%;
- padding: 4px 10px;
- background-color: #FFFFFF;
- color: black;
- border-radius: 6px 6px 0 0;
- border: 1px solid black;
-}
-
-.tab-page li.selected a {
- font-size: x-large;
- font-weight: bold;
- display: block;
- min-height: 100%;
- padding: 4px 10px;
- background-color: #FFFFFF;
- color: black;
- border-radius: 6px 6px 0 0;
- border: 1px solid black;
- border-bottom: none;
-}
-
-body {
- text-align: center;
-}
-
-td {
- text-align: center;
- vertical-align: middle;
-}
-
-.btn-on-text {
- display: none;
-}
-
-.btn-off-text {
- display: none;
-}
-
-.btn-on .btn-on-text {
- display: block;
- font-size: large;
-}
-
-.btn-off .btn-off-text {
- display: block;
- font-size: large;
-}
-
-.tonegen-vol-cell input {
- width: 20px;
- height: 120px;
- -webkit-appearance: slider-vertical;
-}
-
-.tonegen-vol-cell {
- width: 15%;
-}
-
-.tonegen-main-cell {
- width: 80%;
- text-align: center;
- vertical-align: middle;
-}
-
-.sweep_tone {
- display: block;
- text-align: center;
- vertical-align: middle;
-}
-
-.canvas_detail {
- vertical-align:top;
- display: none;
-}
diff --git a/scripts/mic_testing/frontend/audio.html b/scripts/mic_testing/frontend/audio.html
deleted file mode 100644
index 39759f21..00000000
--- a/scripts/mic_testing/frontend/audio.html
+++ /dev/null
@@ -1,184 +0,0 @@
-<!-- Copyright (c) 2014 The Chromium OS Authors. All rights reserved. -->
-<!-- Use of this source code is governed by a BSD-style license that can be -->
-<!-- found in the LICENSE file. -->
-
-<html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>Audio Quality Test</title>
- <script type="text/javascript" src="audio.js"></script>
- <script type="text/javascript" src="source.js"></script>
- <script type="text/javascript" src="recorder.js"></script>
- <script type="text/javascript" src="analysis.js"></script>
- <link rel="stylesheet" type="text/css" href="audio.css">
- </head>
- <body>
- <ul class="tab-page">
- <li id="play_tab" onclick="switchTab('play_tab')" class="selected"><a>Play</a></li>
- <li id="record_tab" onclick="switchTab('record_tab')"><a>Record</a></li>
- </ul>
- <div id="play_div">
- <h1>Audio Source</h1>
- <input type="radio" name="audio_source" value="sine"
- onclick="setupSourceLayer('sine')"> Sine Tone
- <input type="radio" name="audio_source" value="sweep"
- onclick="setupSourceLayer('sweep')" checked> Sweep Tone
- <input type="radio" name="audio_source" value="file"
- onclick="setupSourceLayer('file')"> Load from file
- <br>
- <br>
- <div id="source_layer" align="center">
- <div id="source_tone">
- <table style="width: 50%;">
- <tr>
- <td class="tonegen-main-cell">
- <table style="width: 100%;">
- <tr>
- <td width="50%">Frequency: (20 Hz ~ SampleRate / 2)</td>
- <td width="30%">Duration</td>
- <td class="sweep_tone">Log</td>
- </tr>
- <tr>
- <td>
- <input type="text" id="freq_start" size=5 maxlength=5 value=1000> Hz
- <div class="sweep_tone">
- <input type="text" id="freq_end" size=5 maxlength=5 value=1000> Hz
- </div>
- </td>
- <td>
- <input type="text" id="tone_sec" size=5 maxlength=5 value=3> Seconds
- </td>
- <td class="sweep_tone">
- <input type="checkbox" id="sweep_log">
- </td>
- </tr>
- </table>
- </td>
- <td class="tonegen-vol-cell">
- <input type="range" min="0" max="20" value="20" id="left_gain"
- onchange="gainChanged();"/>
- <input type="range" min="0" max="20" value="20" id="right_gain"
- onchange="gainChanged();"/>
- <br>
- <div id="gain_label">
- L(20) / R(20)
- </div>
- </td>
- </tr>
- </table>
- </div>
- <div id="source_file">
- <input type="button" value="Local Audio File" onclick="loadAudioFile()"
- style="font-size: large;">
- <br><br>
- <div style="display:none">
- <input type=file id=audio_file onchange="changeAudioFile()">
- </div>
- </div>
- </div>
- <hr>
- <input type="checkbox" id="append_tone" checked> Append 1K Hz start tone and end tone
- <br><br>
- <button id="play_audio" class="btn-off" onclick="playAudioFile()">
- <div>
- <span class="btn-off-text">Play</span>
- <span class="btn-on-text">Stop Play</span>
- </div>
- </button>
- </div>
- <div id="record_div" style="display: none;">
- <h1> Record Samples </h1>
- <input type="radio" name="record_source" value="audio_source"
- onclick="setupRecordSource('audio')">
- Play Audio Source
- <input type="radio" name="record_source" value="microphone" checked
- onclick="setupRecordSource('microphone')">
- Microphone
- <br><br>
- <input type="checkbox" id="detect_tone" checked> Detect 1K Hz start tone and end tone
- <input type="checkbox" id="auto_stop" checked> Auto stop when detected 1K Hz end tone
- <br><br>
- <button id="record_btn" class="btn-off" onclick="recordButtonClicked()">
- <div>
- <span class="btn-off-text">Start Record</span>
- <span class="btn-on-text">Stop Record</span>
- </div>
- </button>
- <br><hr>
- <table align="center">
- <tr>
- <td>
- <div style="overflow:auto; max-height: 250px;">
- <table id="record_list" align="center">
- </table>
- </div>
- </td>
- </tr>
- </table>
-
- </div>
-
- <h1> Frequency Response </h1>
- <table align="center">
- <tr>
- <td width=800>
- <div id="curve_section">
- <canvas id='fr_canvas' width=800 height=300>
- </div>
- </td>
- <td width=400 height=300 class="canvas_detail">
- <div id="curve_list" style="overflow:auto; max-height:300px;">
- <table id="curve_table" width=100% height=100%>
- <tr>
- <td colspan=1>
- <input type="button" value="Load File" onClick="loadButtonClicked();">
- <div style="display:none">
- <input type=file id=sample_file onchange="loadSampleFile()">
- </div>
- </td>
- <td colspan=4>
- <select id="noctaves">
- <option value="3">1/3</option>
- <option value="4">1/4</option>
- <option value="5" selected>1/5</option>
- <option value="6">1/6</option>
- <option value="7">1/7</option>
- <option value="8">1/8</option>
- <option value="9">1/9</option>
- <option value="10">1/10</option>
- </select> Octaves
- <a id='export_csv'>
- <input type="button" value="Export CSV" onClick="exportCSV();">
- </a>
- </td>
- </tr>
- <tr>
- <td>Show</td>
- <td>File name</td>
- <td width=50>Left</td>
- <td width=50>Right</td>
- <td>Remove</td>
- </tr>
- </table>
- </div>
- </td>
- </tr>
- </table>
-
- <div id="debug" style="display:none;">
- <h1>Debug</h1>
- <a id='export_freq'>
- <input type="button" value="Export Freq" onClick="exportFreq();">
- </a>
- <a id='export_buffer'>
- <input type="button" value="Export Buffer">
- </a>
- </div>
-
- <div id="log" style="display:none;">
- <h1>Log</h1>
- <pre id="log"></pre>
- </div>
-
- </body>
-</html>
diff --git a/scripts/mic_testing/frontend/audio.js b/scripts/mic_testing/frontend/audio.js
deleted file mode 100644
index 86974e73..00000000
--- a/scripts/mic_testing/frontend/audio.js
+++ /dev/null
@@ -1,363 +0,0 @@
-/*
- * Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-var FFT_SIZE = 2048;
-
-var audioContext;
-var tonegen;
-var recorder;
-var drawContext;
-var audioPlay, audioBuffer;
-var audioSourceType = "sweep";
-var recordSourceType = "microphone";
-
-/**
- * Switches Play/Record tab
- * @param {string} tab name
- */
-function switchTab(tabName) {
- var canvas_detail = document.getElementsByClassName('canvas_detail');
- switch (tabName) {
- case 'play_tab':
- document.getElementById('record_tab').setAttribute('class', '');
- document.getElementById('record_div').style.display = 'none';
- document.getElementById('play_div').style.display = 'block';
- for (var i = 0; i < canvas_detail.length; i++) {
- canvas_detail[i].style.display = "none";
- }
- drawContext.drawBg();
- break;
- case 'record_tab':
- document.getElementById('play_tab').setAttribute('class', '');
- document.getElementById('play_div').style.display = 'none';
- document.getElementById('record_div').style.display = 'block';
- for (var i = 0; i < canvas_detail.length; i++) {
- canvas_detail[i].style.display = "block";
- }
- drawContext.drawCanvas();
- break;
- }
- document.getElementById(tabName).setAttribute('class', 'selected');
-}
-
-function __log(e, data) {
- log.innerHTML += "\n" + e + " " + (data || '');
-}
-
-function startUserMedia(stream) {
- var input = audioContext.createMediaStreamSource(stream);
- recorder = new Recorder(input);
-}
-
-window.onload = function init() {
- setupSourceLayer(audioSourceType);
- try {
- // webkit shim
- window.AudioContext = window.AudioContext || window.webkitAudioContext;
- navigator.getUserMedia = navigator.getUserMedia ||
- navigator.webkitGetUserMedia;
- window.URL = window.URL || window.webkitURL;
-
- audioContext = new AudioContext;
- } catch (e) {
- alert('No web audio support in this browser!');
- }
-
- navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
- alert('No live audio input: ' + e);
- });
-
- /* Initialize global objects */
- tonegen = new ToneGen();
- audioPlay = new AudioPlay();
-
- var canvas = document.getElementById('fr_canvas');
- drawContext = new DrawCanvas(canvas, audioContext.sampleRate / 2);
- drawContext.drawBg();
-};
-
-/* For Play tab */
-
-/**
- * Sets audio source layer
- * @param {string} audio source type
- */
-function setupSourceLayer(value) {
- var sourceTone = document.getElementById('source_tone');
- var sourceFile = document.getElementById('source_file');
- var sweepTone = document.getElementsByClassName('sweep_tone');
- audioSourceType = value;
- switch (value) {
- case 'sine':
- for (var i = 0; i < sweepTone.length; i++) {
- sweepTone[i].style.display = "none";
- }
- document.getElementById('freq_start').value = 1000;
- document.getElementById('freq_end').value = 1000;
- sourceTone.style.display = "block";
- sourceFile.style.display = "none";
- document.getElementById('play_audio').disabled = false;
- break;
- case 'sweep':
- for (var i = 0; i < sweepTone.length; i++) {
- sweepTone[i].style.display = "block";
- }
- document.getElementById('freq_start').value = 20;
- document.getElementById('freq_end').value = 12000;
- sourceTone.style.display = "block";
- sourceFile.style.display = "none";
- document.getElementById('play_audio').disabled = false;
- break;
- case 'file':
- sourceTone.style.display = "none";
- sourceFile.style.display = "block";
- document.getElementById('play_audio').disabled = true;
- break;
- }
-}
-
-/**
- * Sets left/right gain
- */
-function gainChanged() {
- var leftGain = document.getElementById('left_gain').value;
- var rightGain = document.getElementById('right_gain').value;
- var gainLabel = document.getElementById('gain_label');
- gainLabel.innerHTML = 'L(' + leftGain + ') / R(' + rightGain + ')';
-}
-
-/**
- * Checks sine tone generator parameters and sets audio buffer
- */
-function toneValueCheckSet() {
- var passed = true;
- var freqStart = parseInt(document.getElementById('freq_start').value);
- var freqEnd = parseInt(document.getElementById('freq_end').value);
- var duration = parseFloat(document.getElementById('tone_sec').value);
- var leftGain = parseInt(document.getElementById('left_gain').value);
- var rightGain = parseInt(document.getElementById('right_gain').value);
- var sweepLog = document.getElementById('sweep_log').checked;
-
- function isNumber(value, msg) {
- if (isNaN(value) || value <= 0) {
- alert(msg);
- passed = false;
- }
- }
-
- if (audioSourceType == 'sine') {
- freqEnd = freqStart;
- }
-
- isNumber(freqStart, "Start frequency should be a positive number.");
- isNumber(freqEnd, "Stop frequency should be a positive number.");
- isNumber(duration, "Duration should be a positive number.");
- if (freqEnd > audioContext.sampleRate / 2) {
- alert('Stop frequency is too large.');
- passed = false;
- }
- if (freqStart < 20) {
- alert('Start frequency is too small.');
- passed = false;
- }
- if (passed) {
- /* Passed value check and generate tone buffer */
- tonegen.setFreq(freqStart, freqEnd, sweepLog);
- tonegen.setDuration(duration);
- tonegen.setGain(leftGain / 20, rightGain / 20);
- tonegen.setSampleRate(audioContext.sampleRate);
- tonegen.genBuffer();
- var buffer = tonegen.getBuffer();
- audioPlay.setBuffer(buffer, document.getElementById('append_tone').checked);
- }
- return passed;
-}
-
-function loadAudioFile() {
- document.getElementById('audio_file').click();
-}
-
-/**
- * Loads audio file from local drive
- */
-function changeAudioFile() {
- function loadAudioDone(filename, buffer) {
- audioBuffer = buffer;
- document.getElementById('play_audio').disabled = false;
- }
- var input = document.getElementById('audio_file');
- document.getElementById('play_audio').disabled = true;
- audioPlay.loadFile(input.files[0], loadAudioDone);
- input.value = '';
-}
-
-/**
- * Play audio according source type
- */
-function playAudioFile() {
- /**
- * Callback function to draw frequency response of current buffer
- */
- function getInstantBuffer(leftData, rightData, sampleRate) {
- drawContext.drawInstantCurve(leftData, rightData, sampleRate);
- }
-
- var btn = document.getElementById('play_audio');
- var append = document.getElementById('append_tone').checked;
- if (btn.className == 'btn-off') {
- switch (audioSourceType) {
- case 'sine':
- case 'sweep':
- if (toneValueCheckSet()) {
- audioPlay.play(playAudioFile, getInstantBuffer);
- btn.className = 'btn-on';
- }
- break;
- case 'file':
- audioPlay.setBuffer(audioBuffer, append);
- audioPlay.play(playAudioFile, getInstantBuffer);
- btn.className = 'btn-on';
- break;
- }
- } else {
- audioPlay.stop();
- btn.className = 'btn-off';
- drawContext.drawBg();
- }
-}
-
-/* For Record tab */
-
-/**
- * Sets record source type
- * @param {string} record source type
- */
-function setupRecordSource(value) {
- recordSourceType = value;
- var autoStop = document.getElementById('auto_stop');
- if (value == 'audio') {
- autoStop.disabled = true;
- autoStop.checked = false;
- } else {
- autoStop.disabled = false;
- autoStop.checked = true;
- }
-}
-
-function loadButtonClicked() {
- document.getElementById('sample_file').click();
-}
-
-/**
- * Loads sample file to draw frequency response curve into canvas
- */
-function loadSampleFile() {
- /**
- * Callback function when file loaded
- * @param {string} file name
- * @param {AudioBuffer} file buffer
- */
- function addFileToCanvas(filename, buffer) {
- var newBuffer = [];
- for (var i = 0; i < buffer.numberOfChannels; i++) {
- newBuffer.push(buffer.getChannelData(i));
- }
- drawContext.add(new AudioCurve(newBuffer, filename, buffer.sampleRate));
- }
- var input = document.getElementById('sample_file');
- audioPlay.loadFile(input.files[0], addFileToCanvas);
- input.value = '';
-}
-
-/**
- * Starts/Stops record function
- */
-function recordButtonClicked() {
- /**
- * Callback function to draw frequency response of current recorded buffer
- */
- function getInstantBuffer(leftData, rightData, sampleRate, stop) {
- drawContext.drawInstantCurve(leftData, rightData, sampleRate);
- if (stop)
- recordButtonClicked();
- }
-
- var btn = document.getElementById('record_btn');
- if (btn.className == 'btn-off') {
- var detect = document.getElementById('detect_tone').checked;
- var autoStop = document.getElementById('auto_stop').checked;
- var append = document.getElementById('append_tone').checked;
- if (recordSourceType == 'audio') {
- switch(audioSourceType) {
- case 'sine':
- case 'sweep':
- if (toneValueCheckSet()) {
- audioPlay.play(recordButtonClicked);
- btn.className = 'btn-on';
- }
- break;
- case 'file':
- audioPlay.setBuffer(audioBuffer, append);
- audioPlay.play(recordButtonClicked);
- btn.className = 'btn-on';
- break;
- }
- } else {
- btn.className = 'btn-on';
- }
- recorder.record(getInstantBuffer, detect, autoStop);
- } else {
- recorder.stop();
- if (recordSourceType == 'audio') {
- audioPlay.stop();
- }
- // create WAV download link using audio data blob
- var filename = new Date().toISOString() + '.wav';
- buffer = recorder.getBuffer();
- drawContext.add(new AudioCurve(buffer, filename, audioContext.sampleRate));
- createDownloadLink(filename);
- recorder.clear();
- btn.className = 'btn-off';
- }
-}
-
-/**
- * Creates download link of recorded file
- * @param {string} file name
- */
-function createDownloadLink(filename) {
- var blob = recorder.exportWAV();
- var url = URL.createObjectURL(blob);
- var table = document.getElementById('record_list');
- var au = document.createElement('audio');
- au.controls = true;
- au.src = url;
-
- var hf = document.createElement('a');
- hf.href = url;
- hf.download = filename;
- hf.innerHTML = hf.download;
-
- var tr = table.insertRow(table.rows.length);
- var td_au = tr.insertCell(0);
- var td_hf = tr.insertCell(1);
- td_hf.style = "white-space: nowrap";
- td_au.appendChild(au);
- td_hf.appendChild(hf);
-}
-
-/**
- * Exports frequency response CVS file of curves on the canvas
- */
-function exportCSV() {
- var hf = document.getElementById('export_csv');
- var noctaves = document.getElementById('noctaves').value;
- content = drawContext.exportCurve(noctaves);
- var blob = new Blob([content], {type: 'application/octet-stream'});
- var url = URL.createObjectURL(blob);
- hf.href = url;
- hf.download = 'audio.csv';
-}
diff --git a/scripts/mic_testing/frontend/recorder.js b/scripts/mic_testing/frontend/recorder.js
deleted file mode 100644
index 92f2766f..00000000
--- a/scripts/mic_testing/frontend/recorder.js
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-var Recorder = function(source){
- var bufferLen = 4096;
- var toneFreq = 1000, errorMargin = 0.05;
-
- var context = source.context;
- var sampleRate = context.sampleRate;
- var recBuffersL = [], recBuffersR = [], recLength = 0;
- this.node = (context.createScriptProcessor ||
- context.createJavaScriptNode).call(context, bufferLen, 2, 2);
- var detectAppend = false, autoStop = false, recordCallback;
- var recording = false;
- var freqString;
-
- this.node.onaudioprocess = function(e) {
- if (!recording) return;
-
- var length = e.inputBuffer.getChannelData(0).length;
- var tmpLeft = new Float32Array(length);
- var tmpRight = new Float32Array(length);
- tmpLeft.set(e.inputBuffer.getChannelData(0), 0);
- tmpRight.set(e.inputBuffer.getChannelData(1), 0);
-
- recBuffersL.push(tmpLeft);
- recBuffersR.push(tmpRight);
- recLength += length;
- var stop = false;
-
- if (autoStop && detectTone(getFreqList(tmpLeft)))
- stop = true;
-
- if (recordCallback) {
- var tmpLeft = recBuffersL[recBuffersL.length - 1].subarray(
- -FFT_SIZE-1, -1);
- var tmpRight = recBuffersR[recBuffersR.length - 1].subarray(
- -FFT_SIZE-1, -1);
- recordCallback(tmpLeft, tmpRight, sampleRate, stop);
- }
- }
-
- /**
- * Starts recording
- * @param {function} callback function to get current buffer
- * @param {boolean} detect append tone or not
- * @param {boolean} auto stop when detecting append tone
- */
- this.record = function(cb, detect, stop) {
- recordCallback = cb;
- detectAppend = detect;
- autoStop = stop;
- recording = true;
- }
-
- /**
- * Stops recording
- */
- this.stop = function() {
- recording = false;
- recBuffersL = mergeBuffers(recBuffersL, recLength);
- recBuffersR = mergeBuffers(recBuffersR, recLength);
- if (detectAppend) {
- var freqList = getFreqList(recBuffersL);
- var index = getToneIndices(freqList);
- removeAppendTone(index[0], index[1]);
- exportFreqList(freqList);
- }
- }
-
- /**
- * Gets frequencies list
- * @param {Float32Array} buffer
- * @return {array} frequencies list
- */
- getFreqList = function(buffer) {
- var prevPeak = 0;
- var valid = true;
- var freqList = [];
- for (i = 1; i < recLength; i++) {
- if (buffer[i] > 0.1 &&
- buffer[i] >= buffer[i - 1] && buffer[i] >= buffer[i + 1]) {
- if (valid) {
- var freq = sampleRate / (i - prevPeak);
- freqList.push([freq, prevPeak, i]);
- prevPeak = i;
- valid = false;
- }
- } else if (buffer[i] < -0.1) {
- valid = true;
- }
- }
- return freqList;
- }
-
- /**
- * Checks average frequency is in allowed error margin
- * @param {float} average frequency
- * @return {boolean} checked result pass or fail
- */
- checkFreq = function (average) {
- if (Math.abs(average - toneFreq) / toneFreq < errorMargin)
- return true;
- return false;
- }
-
- /**
- * Detects append tone while recording.
- * @param {array} frequencies list
- * @return {boolean} detected or not
- */
- detectTone = function(freqList) {
- var passCriterion = 50;
- // Initialize function static variables
- if (typeof detectTone.startDetected == 'undefined') {
- detectTone.startDetected = false;
- detectTone.canStop = false;
- detectTone.accumulateTone = 0;
- }
-
- var windowSize = 10, windowSum = 0, i;
- var detected = false;
- for (i = 0; i < freqList.length && i < windowSize; i++) {
- windowSum += freqList[i][0];
- }
- if (checkFreq(windowSum / Math.min(windowSize, freqList.length))) {
- detected = true;
- detectTone.accumulateTone++;
- }
- for (; i < freqList.length; i++) {
- windowSum = windowSum + freqList[i][0] - freqList[i - windowSize][0];
- if (checkFreq(windowSum / windowSize)) {
- detected = true;
- detectTone.accumulateTone++;
- }
- }
- if (detected) {
- if (detectTone.accumulateTone > passCriterion) {
- if (!detectTone.startDetected)
- detectTone.startDetected = true;
- else if (detectTone.canStop) {
- detectTone.startDetected = false;
- detectTone.canStop = false;
- detectTone.accumulateTone = 0;
- return true;
- }
- }
- } else {
- detectTone.accumulateTone = 0;
- if (detectTone.startDetected)
- detectTone.canStop = true;
- }
- return false;
- }
-
- /**
- * Gets start and end indices from a frquencies list except append tone
- * @param {array} frequencies list
- * @return {array} start and end indices
- */
- getToneIndices = function(freqList) {
- // find start and end indices
- var flag, j, k;
- var windowSize = 10, windowSum;
- var index = new Array(2);
- var scanRange = [[0, freqList.length, 1], [freqList.length - 1, -1, -1]];
-
- if (freqList.length == 0) return index;
-
- for (i = 0; i < 2; i++) {
- flag = false;
- windowSum = 0;
- for (j = scanRange[i][0], k = 0; k < windowSize && j != scanRange[i][1];
- j += scanRange[i][2], k++) {
- windowSum += freqList[j][0];
- }
- for (; j != scanRange[i][1]; j += scanRange[i][2]) {
- windowSum = windowSum + freqList[j][0] -
- freqList[j - scanRange[i][2] * windowSize][0];
- var avg = windowSum / windowSize;
- if (checkFreq(avg) && !flag) {
- flag = true;
- }
- if (!checkFreq(avg) && flag) {
- index[i] = freqList[j][1];
- break;
- }
- }
- }
- return index;
- }
-
- /**
- * Removes append tone from recorded buffer
- * @param {int} start index
- * @param {int} end index
- */
- removeAppendTone = function(start, end) {
- if (!isNaN(start) && !isNaN(end) && end > start) {
- recBuffersL = truncateBuffers(recBuffersL, recLength, start, end);
- recBuffersR = truncateBuffers(recBuffersR, recLength, start, end);
- recLength = end - start;
- }
- }
-
- /**
- * Exports frequency list for debugging purpose
- */
- exportFreqList = function(freqList) {
- freqString = sampleRate + '\n';
- for (var i = 0; i < freqList.length; i++) {
- freqString += freqList[i][0] + ' ' + freqList[i][1] + ' ' +
- freqList[i][2] + '\n';
- }
- }
-
- this.getFreq = function() {
- return freqString;
- }
-
- /**
- * Clears recorded buffer
- */
- this.clear = function() {
- recLength = 0;
- recBuffersL = [];
- recBuffersR = [];
- }
-
- /**
- * Gets recorded buffer
- */
- this.getBuffer = function() {
- var buffers = [];
- buffers.push(recBuffersL);
- buffers.push(recBuffersR);
- return buffers;
- }
-
- /**
- * Exports WAV format file
- * @return {blob} audio file blob
- */
- this.exportWAV = function(type) {
- type = type || 'audio/wav';
- var interleaved = interleave(recBuffersL, recBuffersR);
- var dataview = encodeWAV(interleaved);
- var audioBlob = new Blob([dataview], { type: type });
- return audioBlob;
- }
-
- /**
- * Truncates buffer from start index to end index
- * @param {Float32Array} audio buffer
- * @param {int} buffer length
- * @param {int} start index
- * @param {int} end index
- * @return {Float32Array} a truncated buffer
- */
- truncateBuffers = function(recBuffers, recLength, startIdx, endIdx) {
- var buffer = new Float32Array(endIdx - startIdx);
- for (var i = startIdx, j = 0; i < endIdx; i++, j++) {
- buffer[j] = recBuffers[i];
- }
- return buffer;
- }
-
- /**
- * Merges buffer into an array
- * @param {array} a list of Float32Array of audio buffer
- * @param {int} buffer length
- * @return {Float32Array} a merged buffer
- */
- mergeBuffers = function(recBuffers, recLength) {
- var result = new Float32Array(recLength);
- var offset = 0;
- for (var i = 0; i < recBuffers.length; i++){
- result.set(recBuffers[i], offset);
- offset += recBuffers[i].length;
- }
- return result;
- }
-
- /**
- * Interleaves left and right channel buffer
- * @param {Float32Array} left channel buffer
- * @param {Float32Array} right channel buffer
- * @return {Float32Array} an interleaved buffer
- */
- interleave = function(inputL, inputR) {
- var length = inputL.length + inputR.length;
- var result = new Float32Array(length);
-
- var index = 0,
- inputIndex = 0;
-
- while (index < length){
- result[index++] = inputL[inputIndex];
- result[index++] = inputR[inputIndex];
- inputIndex++;
- }
- return result;
- }
-
- floatTo16BitPCM = function(output, offset, input) {
- for (var i = 0; i < input.length; i++, offset+=2){
- var s = Math.max(-1, Math.min(1, input[i]));
- output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
- }
- }
-
- writeString = function(view, offset, string) {
- for (var i = 0; i < string.length; i++){
- view.setUint8(offset + i, string.charCodeAt(i));
- }
- }
-
- /**
- * Encodes audio buffer into WAV format raw data
- * @param {Float32Array} an interleaved buffer
- * @return {DataView} WAV format raw data
- */
- encodeWAV = function(samples) {
- var buffer = new ArrayBuffer(44 + samples.length * 2);
- var view = new DataView(buffer);
-
- /* RIFF identifier */
- writeString(view, 0, 'RIFF');
- /* file length */
- view.setUint32(4, 32 + samples.length * 2, true);
- /* RIFF type */
- writeString(view, 8, 'WAVE');
- /* format chunk identifier */
- writeString(view, 12, 'fmt ');
- /* format chunk length */
- view.setUint32(16, 16, true);
- /* sample format (raw) */
- view.setUint16(20, 1, true);
- /* channel count */
- view.setUint16(22, 2, true);
- /* sample rate */
- view.setUint32(24, sampleRate, true);
- /* byte rate (sample rate * block align) */
- view.setUint32(28, sampleRate * 4, true);
- /* block align (channel count * bytes per sample) */
- view.setUint16(32, 4, true);
- /* bits per sample */
- view.setUint16(34, 16, true);
- /* data chunk identifier */
- writeString(view, 36, 'data');
- /* data chunk length */
- view.setUint32(40, samples.length * 2, true);
-
- floatTo16BitPCM(view, 44, samples);
-
- return view;
- }
-
- source.connect(this.node);
- this.node.connect(context.destination);
-};
-
-window.Recorder = Recorder;
diff --git a/scripts/mic_testing/frontend/source.js b/scripts/mic_testing/frontend/source.js
deleted file mode 100644
index a6f82a3f..00000000
--- a/scripts/mic_testing/frontend/source.js
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-var ToneGen = function() {
- /**
- * Initializes tone generator.
- */
- this.init = function() {
- this.audioContext = new AudioContext();
- }
-
- /**
- * Sets sample rate
- * @param {int} sample rate
- */
- this.setSampleRate = function(sampleRate) {
- this.sampleRate = sampleRate;
- }
-
- /**
- * Sets start/end frequencies and logarithmic sweep
- * @param {int} start frequency
- * @param {int} end frequency
- * @param {boolean} logarithmic sweep or not
- */
- this.setFreq = function(freqStart, freqEnd, sweepLog) {
- this.freqStart = freqStart;
- this.freqEnd = freqEnd;
- this.sweepLog = sweepLog;
- }
-
- /**
- * Sets tone duration
- * @param {float} duration in seconds
- */
- this.setDuration = function(duration) {
- this.duration = parseFloat(duration);
- }
-
- /**
- * Sets left and right gain value
- * @param {float} left gain between 0 and 1
- * @param {float} right gain between 0 and 1
- */
- this.setGain = function(leftGain, rightGain) {
- this.leftGain = parseFloat(leftGain);
- this.rightGain = parseFloat(rightGain);
- }
-
- /**
- * Generates sine tone buffer
- */
- this.genBuffer = function() {
- this.buffer = this.audioContext.createBuffer(2,
- this.sampleRate * this.duration, this.sampleRate);
- var leftChannel = this.buffer.getChannelData(0);
- var rightChannel = this.buffer.getChannelData(1);
- var phi;
- var k = this.freqEnd / this.freqStart;
- var beta = this.duration / Math.log(k);
- for (var i = 0; i < leftChannel.length; i++) {
- if (this.sweepLog) {
- phi = 2 * Math.PI * this.freqStart * beta *
- (Math.pow(k, i / leftChannel.length) - 1.0);
- } else {
- var f = this.freqStart + (this.freqEnd - this.freqStart) *
- i / leftChannel.length / 2;
- phi = f * 2 * Math.PI * i / this.sampleRate;
- }
- leftChannel[i] = this.leftGain * Math.sin(phi);
- rightChannel[i] = this.rightGain * Math.sin(phi);
- }
- }
-
- /**
- * Returns generated sine tone buffer
- * @return {AudioBuffer} audio buffer
- */
- this.getBuffer = function() {
- return this.buffer;
- }
-
- /**
- * Returns append buffer
- * @return {AudioBuffer} append audio buffer
- */
- this.getAppendTone = function(sampleRate) {
- var tone_freq = 1000, duration = 0.5;
- this.setFreq(tone_freq, tone_freq, false);
- this.setDuration(duration);
- this.setGain(1, 1);
- this.setSampleRate(sampleRate);
- this.genBuffer();
- return this.getBuffer();
- }
-
- this.init();
-}
-
-window.ToneGen = ToneGen;
-
-var AudioPlay = function() {
- var playCallback = null;
- var sampleRate;
- var playing = false;
-
- /**
- * Initializes audio play object
- */
- this.init = function() {
- this.audioContext = new AudioContext();
- this.genChannel();
- this.buffer = null;
- sampleRate = this.audioContext.sampleRate;
- }
-
- /**
- * Loads audio file
- * @param {blob} audio file
- * @param {function} callback function when file loaded
- */
- this.loadFile = function(file_blob, done_cb) {
- if (file_blob) {
- var audioContext = this.audioContext;
- reader = new FileReader();
- reader.onloadend = function(e) {
- audioContext.decodeAudioData(e.target.result,
- function(buffer) {
- done_cb(file_blob.name, buffer);
- });
- };
- reader.readAsArrayBuffer(file_blob);
- }
- }
-
- /**
- * Sets audio path
- */
- this.genChannel = function() {
- this.node = (this.audioContext.createScriptProcessor ||
- this.audioContext.createJavaScriptNode).call(
- this.audioContext, 4096, 2, 2);
- this.splitter = this.audioContext.createChannelSplitter(2);
- this.merger = this.audioContext.createChannelMerger(2);
- this.node.connect(this.splitter);
- this.splitter.connect(this.merger, 0, 0);
- this.splitter.connect(this.merger, 1, 1);
- this.merger.connect(this.audioContext.destination);
-
- this.node.onaudioprocess = function(e) {
- for (var i = 0; i < e.inputBuffer.numberOfChannels; i++) {
- e.outputBuffer.getChannelData(i).set(
- e.inputBuffer.getChannelData(i), 0);
- }
- if (!playing) return;
- if (playCallback) {
- var tmpLeft = e.inputBuffer.getChannelData(0).subarray(
- -FFT_SIZE-1, -1);
- var tmpRight = e.inputBuffer.getChannelData(1).subarray(
- -FFT_SIZE-1, -1);
- playCallback(tmpLeft, tmpRight, sampleRate);
- }
- }
- }
-
- /**
- * Plays audio
- * @param {function} callback function when audio end
- * @param {function} callback function to get current buffer
- */
- this.play = function(done_cb, play_cb) {
- playCallback = play_cb;
- this.source = this.audioContext.createBufferSource();
- this.source.buffer = this.buffer;
- this.source.onended = function(e) {
- playing = false;
- this.disconnect();
- if (done_cb) {
- done_cb();
- }
- }
- this.source.connect(this.node);
- this.source.start(0);
- playing = true;
- }
-
- /**
- * Stops audio
- */
- this.stop = function() {
- playing = false;
- this.source.stop();
- this.source.disconnect();
- }
-
- /**
- * Sets audio buffer
- * @param {AudioBuffer} audio buffer
- * @param {boolean} append tone or not
- */
- this.setBuffer = function(buffer, append) {
- if (append) {
- function copyBuffer(src, dest, offset) {
- for (var i = 0; i < dest.numberOfChannels; i++) {
- dest.getChannelData(i).set(src.getChannelData(i), offset);
- }
- }
- var appendTone = tonegen.getAppendTone(buffer.sampleRate);
- var bufferLength = appendTone.length * 2 + buffer.length;
- var newBuffer = this.audioContext.createBuffer(buffer.numberOfChannels,
- bufferLength, buffer.sampleRate);
- copyBuffer(appendTone, newBuffer, 0);
- copyBuffer(buffer, newBuffer, appendTone.length);
- copyBuffer(appendTone, newBuffer, appendTone.length + buffer.length);
- this.buffer = newBuffer;
- } else {
- this.buffer = buffer;
- }
- }
-
- this.init();
-}
-
-window.AudioPlay = AudioPlay;
diff --git a/scripts/volume_tuning/LICENSE b/scripts/volume_tuning/LICENSE
deleted file mode 100644
index 0aa7fc93..00000000
--- a/scripts/volume_tuning/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2006-2009 The Chromium OS Authors. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/scripts/volume_tuning/app.yaml b/scripts/volume_tuning/app.yaml
deleted file mode 100644
index 4c580fa7..00000000
--- a/scripts/volume_tuning/app.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-application: volume-tuning
-version: 1-1-default-volume-step
-runtime: python27
-api_version: 1
-threadsafe: true
-
-handlers:
-- url: /(.*\.css)
- mime_type: text/css
- static_files: \1
- upload: (.*\.css)
-
-- url: /(.*\.html)
- mime_type: text/html
- static_files: \1
- upload: (.*\.html)
-
-- url: /(.*\.js)
- mime_type: text/javascript
- static_files: \1
- upload: (.*\.js)
-
-- url: /(LICENSE)
- mime_type: text/plain
- static_files: \1
- upload: (LICENSE)
-
-- url: /
- static_files: volume.html
- upload: volume.html
diff --git a/scripts/volume_tuning/volume.css b/scripts/volume_tuning/volume.css
deleted file mode 100644
index a40fbb90..00000000
--- a/scripts/volume_tuning/volume.css
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-body {
- font-family: sans-serif;
- text-align: center;
-}
-
-.box
-{
- border: 1px solid rgb(144,184,222);
- text-align:right;
- position:relative;
- padding: 2px;
-}
-
-table {
- display: inline-block;
- background-color: #d8e6f8;
- border-radius: 5px;
- padding: 5px;
-}
-
-canvas {
- display: inline-block;
- vertical-align: top;
- padding-left: 20px;
-}
diff --git a/scripts/volume_tuning/volume.html b/scripts/volume_tuning/volume.html
deleted file mode 100644
index beb71c1a..00000000
--- a/scripts/volume_tuning/volume.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!-- Copyright (c) 2013 The Chromium OS Authors. All rights reserved. -->
-<!-- Use of this source code is governed by a BSD-style license that can be -->
-<!-- found in the LICENSE file. -->
-
-<html>
- <head>
- <TITLE>Volume Tuning</TITLE>
- <link rel="stylesheet" href="volume.css" type="text/css">
- <script type="text/javascript" src="volume.js"></script>
- </head>
- <body>
- <h1> Volume Tuning </h1>
- <table id="minmax"></table>
- <table id="fixes"> </table>
- <canvas id="curve"> </canvas>
- <hr>
- <input type=button value='Download config' onclick="download_config()">
- </input>
- <div style="display:none">
- <a id=save_config_anchor></a>
- </div>
- </body>
-</html>
-<html>
diff --git a/scripts/volume_tuning/volume.js b/scripts/volume_tuning/volume.js
deleted file mode 100644
index 88f39984..00000000
--- a/scripts/volume_tuning/volume.js
+++ /dev/null
@@ -1,315 +0,0 @@
-/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
- * Use of this source code is governed by a BSD-style license that can be
- * found in the LICENSE file.
- */
-
-var NN = 100; // Total number of points
-var FIXES = 25; // Number of fixed points, evenly spaced in the range [0, NN]
-var minmax_boxes = []; // The text input boxes for min/max/step
-var fix_boxes = []; // The text input boxes for fixed points
-
-window.onload = function() {
- init_minmax();
- init_fixes();
- init_canvas();
-};
-
-// Create min/max/step boxes
-function init_minmax() {
- var table = document.getElementById('minmax');
- var names = ['Min:' , 'Max:', 'Step:'];
- for (var i = 0; i < names.length; i++) {
- var row = table.insertRow(-1);
- var col_name = row.insertCell(-1);
- var col_box = row.insertCell(-1);
- var col_db = row.insertCell(-1);
- var box = document.createElement('input');
- box.size = 5;
- box.className = 'box';
- col_name.appendChild(document.createTextNode(names[i]));
- col_name.align = 'right';
- col_box.appendChild(box);
- col_db.appendChild(document.createTextNode('dB'));
- minmax_boxes.push(box);
- box.oninput = redraw;
- }
-}
-
-// Create fixed point boxes
-function init_fixes() {
- var table = document.getElementById('fixes');
- for (var i = 0; i <= FIXES; i++) {
- var row = table.insertRow(-1);
- var col_name = row.insertCell(-1);
- var col_box = row.insertCell(-1);
- var col_db = row.insertCell(-1);
- var box = document.createElement('input');
- box.size = 5;
- box.className = 'box';
- // round fix_pos (the dB value for this fixed point) to one place
- // after decimal point.
- var fix_pos = Math.round(i * NN * 10 / FIXES) / 10;
- col_name.appendChild(document.createTextNode(fix_pos + ':'));
- col_name.align = 'right';
- col_box.appendChild(box);
- col_db.appendChild(document.createTextNode('dB'));
- fix_boxes.push(box);
- box.oninput = redraw;
- }
-}
-
-function init_canvas() {
- redraw();
-}
-
-// Redraw everything on the canvas. This is run every time any input is changed.
-function redraw() {
- var backgroundColor = 'black';
- var gridColor = 'rgb(200,200,200)';
- var dotColor = 'rgb(245,245,0)';
- var marginLeft = 60;
- var marginBottom = 30;
- var marginTop = 20;
- var marginRight = 30;
- var canvas = document.getElementById('curve');
- var ctx = canvas.getContext('2d');
- var w = 800;
- var h = 400;
- canvas.width = w + marginLeft + marginRight;
- canvas.height = h + marginBottom + marginTop;
- ctx.fillStyle = backgroundColor;
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- ctx.lineWidth = 1;
- ctx.font = '16px sans-serif';
- ctx.textAlign = 'center';
-
- // Set up coordinate system
- ctx.translate(marginLeft, h + marginTop);
- ctx.scale(1, -1);
-
- // Draw two lines at x = 0 and y = 0 which are solid lines
- ctx.strokeStyle = gridColor;
- ctx.beginPath();
- ctx.moveTo(0, h + marginTop / 2);
- ctx.lineTo(0, 0);
- ctx.lineTo(w + marginRight / 2, 0);
- ctx.stroke();
-
- // Draw vertical lines and labels on x axis
- ctx.strokeStyle = gridColor;
- ctx.fillStyle = gridColor;
- ctx.beginPath();
- ctx.setLineDash([1, 4]);
- for (var i = 0; i <= FIXES; i++) {
- var x = i * w / FIXES;
- if (i > 0) {
- ctx.moveTo(x, 0);
- ctx.lineTo(x, h + marginTop / 2);
- }
- drawText(ctx, Math.round(i * NN * 10 / FIXES) / 10, x, -20, 'center');
- }
- ctx.stroke();
- ctx.setLineDash([]);
-
- // Draw horizontal lines and labels on y axis
- var min = parseFloat(minmax_boxes[0].value);
- var max = parseFloat(minmax_boxes[1].value);
- var step = parseFloat(minmax_boxes[2].value);
-
- // Soundness checks
- if (isNaN(min) || isNaN(max) || isNaN(step)) return;
- if (min >= max || step <= 0 || (max - min) / step > 10000) return;
-
- // Let s = minimal multiple of step such that
- // vdivs = Math.round((max - min) / s) <= 20
- var vdivs;
- var s = Math.max(1, Math.floor((max - min) / 20 / step)) * step;
- while (true) {
- var vdivs = Math.round((max - min) / s);
- if (vdivs <= 20) break;
- s += step;
- }
-
- // Scale from v to y is
- // y = (v - min) / s * h / vdivs
- ctx.strokeStyle = gridColor;
- ctx.fillStyle = gridColor;
- ctx.beginPath();
- ctx.setLineDash([1, 4]);
- for (var i = 0;; i++) {
- var v = min + s * i;
- var y;
- if (v <= max) {
- y = i * h / vdivs;
- } else {
- v = max;
- y = (max - min) / s * h / vdivs;
- }
- drawText(ctx, v.toFixed(2), -5 , y - 4, 'right');
- if (i > 0) {
- ctx.moveTo(0, y);
- ctx.lineTo(w + marginRight / 2, y);
- }
- if (v >= max) break;
- }
- ctx.stroke();
- ctx.setLineDash([]);
-
- // Draw fixed points
- ctx.strokeStyle = dotColor;
- ctx.fillStyle = dotColor;
- for (var i = 0; i <= FIXES; i++) {
- var v = getFix(i);
- if (isNaN(v)) continue;
- var x = i * w / FIXES;
- var y = (v - min) / s * h / vdivs;
- ctx.beginPath();
- ctx.arc(x, y, 4, 0, 2 * Math.PI);
- ctx.stroke();
- }
-
- // Draw interpolated points
- var points = generatePoints();
- for (var i = 0; i <= NN; i++) {
- var v = points[i];
- if (isNaN(v)) continue;
- var x = i * w / NN;
- var y = (v - min) / s * h / vdivs;
- ctx.beginPath();
- ctx.arc(x, y, 2, 0, 2 * Math.PI);
- ctx.stroke();
- ctx.fill();
- }
-}
-
-// Returns the value of the fixed point with index i
-function getFix(i) {
- var v = parseFloat(fix_boxes[i].value);
- var min = parseFloat(minmax_boxes[0].value);
- var max = parseFloat(minmax_boxes[1].value);
-
- if (isNaN(v)) return v;
- if (v > max) v = max;
- if (v < min) v = min;
- return v;
-}
-
-// Returns a value quantized to the given min/max/step
-function quantize(v) {
- var min = parseFloat(minmax_boxes[0].value);
- var max = parseFloat(minmax_boxes[1].value);
- var step = parseFloat(minmax_boxes[2].value);
-
- v = min + Math.round((v - min) / step) * step;
- if (isNaN(v)) return v;
- if (v > max) v = max;
- if (v < min) v = min;
- return v;
-}
-
-// Generate points indexed by 0 to NN, using interpolation and quantization
-function generatePoints() {
- // Go through all points, for each point:
- // (1) Find the left fix: the max defined fixed point <= current point
- // (2) Find the right fix: the min defined fixed point >= current point
- // (3) If both exist, interpolate value for current point
- // (4) Otherwise skip current point
-
- // Returns left fix index for current point, or NaN if it does not exist
- var find_left = function(current) {
- for (i = FIXES; i >= 0; i--) {
- var x = NN * i / FIXES;
- if (x <= current && !isNaN(getFix(i))) {
- return i;
- }
- }
- return NaN;
- };
-
- // Returns right fix index for current point, or NaN if it does not exist
- var find_right = function(current) {
- for (i = 0; i <= FIXES; i++) {
- var x = NN * i / FIXES;
- if (x >= current && !isNaN(getFix(i))) {
- return i;
- }
- }
- return NaN;
- };
-
- // Interpolate value for point x
- var interpolate = function(x) {
- var left = find_left(x);
- if (isNaN(left)) return NaN;
-
- var right = find_right(x);
- if (isNaN(right)) return NaN;
-
- var xl = NN * left / FIXES;
- var xr = NN * right / FIXES;
- var yl = getFix(left);
- var yr = getFix(right);
-
- if (xl == xr) return yl;
-
- return yl + (yr - yl) * (x - xl) / (xr - xl);
- };
-
- var result = [];
- for (var x = 0; x <= NN; x++) {
- result.push(quantize(interpolate(x)));
- }
- return result;
-}
-
-function drawText(ctx, s, x, y, align) {
- ctx.save();
- ctx.translate(x, y);
- ctx.scale(1, -1);
- ctx.textAlign = align;
- ctx.fillText(s, 0, 0);
- ctx.restore();
-}
-
-// The output config file looks like:
-//
-// [Speaker]
-// volume_curve = explicit
-// db_at_100 = 0
-// db_at_99 = -75
-// db_at_98 = -75
-// ...
-// db_at_1 = -4500
-// db_at_0 = -4800
-// [Headphone]
-// volume_curve = simple_step
-// volume_step = 70
-// max_volume = 0
-//
-function download_config() {
- var content = '';
- content += '[Speaker]\n';
- content += ' volume_curve = explicit\n';
- var points = generatePoints();
- var last = 0;
- for (var i = NN; i >= 0; i--) {
- var v = points[i];
- if (isNaN(points[i])) v = last;
- content += ' db_at_' + i + ' = ' + Math.round(v * 100) + '\n';
- }
-
- content += '[Headphone]\n';
- content += ' volume_curve = simple_step\n';
- content += ' volume_step = 70\n';
- content += ' max_volume = 0\n';
- save_config(content);
-}
-
-function save_config(content) {
- var a = document.getElementById('save_config_anchor');
- var uriContent = 'data:application/octet-stream,' +
- encodeURIComponent(content);
- a.href = uriContent;
- a.download = 'HDA Intel PCH';
- a.click();
-}
diff --git a/seccomp/cras-seccomp-amd64.policy b/seccomp/cras-seccomp-amd64.policy
deleted file mode 100644
index afa6ace6..00000000
--- a/seccomp/cras-seccomp-amd64.policy
+++ /dev/null
@@ -1,95 +0,0 @@
-# Copyright 2018 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-clock_gettime: 1
-getuid: 1
-lstat: 1
-read: 1
-recvfrom: 1
-poll: 1
-ppoll: 1
-fstat: 1
-write: 1
-writev: 1
-open: 1
-openat: 1
-close: 1
-readlinkat: 1
-getrandom: 1
-access: 1
-fcntl: 1
-getdents: 1
-getdents64: 1
-sendmsg: 1
-stat: 1
-statfs: 1
-recvmsg: 1
-brk: 1
-mmap: 1
-getsockopt: 1
-accept: 1
-munmap: 1
-sendto: 1
-readlink: 1
-futex: 1
-lseek: 1
-rt_sigaction: 1
-socket: arg0 == AF_UNIX || arg0 == AF_BLUETOOTH || arg0 == AF_NETLINK
-socketpair: 1
-unlink: 1
-nanosleep: 1
-clock_nanosleep: 1
-pipe: 1
-ftruncate: 1
-fallocate: 1
-mprotect: 1
-connect: 1
-getsockname: 1
-setsockopt: 1
-bind: 1
-restart_syscall: 1
-exit: 1
-exit_group: 1
-rt_sigreturn: 1
-chmod: 1
-geteuid: 1
-uname: 1
-clock_getres: 1
-gettid: 1
-rt_sigprocmask: 1
-fchmod: 1
-getrlimit: 1
-setrlimit: 1
-listen: 1
-clone: 1
-set_robust_list: 1
-setpriority: 1
-getresuid: 1
-getresgid: 1
-sched_setscheduler: 1
-epoll_wait: 1
-getegid: 1
-getgid: 1
-prctl: arg0 == PR_SET_NAME
-epoll_create1: 1
-sched_get_priority_min: 1
-pipe2: 1
-epoll_ctl: 1
-sched_get_priority_max: 1
-lgetxattr: 1
-lsetxattr: 1
-madvise: 1
-sysinfo: 1
-flock: 1
-
-# Allow ioctl command of type 'A' and 'U' for SNDRV_PCM_IOCTL_* and
-# SNDRV_CTL_IOCTL_*, and EVIOCGSW(8), EVIOCGNAME(256), EVIOCGBIT(0x05, 8),
-# HCIGETDEVINFO
-ioctl: arg1 in 0xffff41ff && arg1 & 0x00004100 || arg1 in 0xffff55ff && arg1 & 0x00005500 || arg1 == 0x8008451b || arg1 == 0x81004506 || arg1 == 0x80084525 || arg1 == 0x800448d3
-getpid: 1
-prlimit64: 1
-tgkill: 1
-mremap: 1
-dup: 1
-gettimeofday: 1
diff --git a/seccomp/cras-seccomp-arm.policy b/seccomp/cras-seccomp-arm.policy
deleted file mode 100644
index cbaa622b..00000000
--- a/seccomp/cras-seccomp-arm.policy
+++ /dev/null
@@ -1,104 +0,0 @@
-# Copyright 2018 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-clock_gettime: 1
-clock_gettime64: 1
-poll: 1
-read: 1
-ppoll: 1
-ppoll_time64: 1
-write: 1
-writev: 1
-recv: 1
-send: 1
-recvmsg: 1
-lstat64: 1
-fstat64: 1
-open: 1
-openat: 1
-close: 1
-fcntl64: 1
-readlinkat: 1
-sendmsg: 1
-access: 1
-getrandom: 1
-mmap2: 1
-epoll_wait: 1
-getsockopt: 1
-accept: 1
-stat64: 1
-mprotect: 1
-gettimeofday: 1
-getdents64: 1
-brk: 1
-statfs: 1
-readlink: 1
-munmap: 1
-rt_sigaction: 1
-lgetxattr: 1
-unlink: 1
-lsetxattr: 1
-rt_sigprocmask: 1
-ftruncate: 1
-fallocate: 1
-futex: 1
-futex_time64: 1
-execve: 1
-set_robust_list: 1
-socket: arg0 == AF_UNIX || arg0 == AF_BLUETOOTH || arg0 == AF_NETLINK
-socketpair: 1
-clone: 1
-setsockopt: 1
-geteuid32: 1
-ugetrlimit: 1
-uname: 1
-connect: 1
-bind: 1
-_llseek: 1
-getuid32: 1
-getgid32: 1
-getegid32: 1
-pipe: 1
-flock: 1
-# set_tls: 1
-set_tid_address: 1
-exit_group: 1
-getsockname: 1
-getdents: 1
-nanosleep: 1
-clock_nanosleep: 1
-clock_nanosleep_time64: 1
-epoll_ctl: 1
-sched_setscheduler: 1
-restart_syscall: 1
-rt_sigreturn: 1
-getresuid32: 1
-exit: 1
-prctl: arg0 == PR_SET_NAME
-clock_getres: 1
-clock_getres_time64: 1
-epoll_create1: 1
-fchmod: 1
-setpriority: 1
-setrlimit: 1
-listen: 1
-gettid: 1
-sched_get_priority_min: 1
-chmod: 1
-madvise: 1
-getresgid32: 1
-pipe2: 1
-sched_get_priority_max: 1
-sysinfo: 1
-
-# Allow ioctl command of type 'A' and 'U' for SNDRV_PCM_IOCTL_* and
-# SNDRV_CTL_IOCTL_*, and EVIOCGSW(8), EVIOCGNAME(256), EVIOCGBIT(0x05, 8),
-# HCIGETDEVINFO
-ioctl: arg1 in 0xffff41ff && arg1 & 0x00004100 || arg1 in 0xffff55ff && arg1 & 0x00005500 || arg1 == 0x8008451b || arg1 == 0x81004506 || arg1 == 0x80084525 || arg1 == 0x800448d3
-getpid: 1
-prlimit64: 1
-tgkill: 1
-mremap: 1
-dup: 1
-_newselect: 1
diff --git a/seccomp/cras-seccomp-arm64.policy b/seccomp/cras-seccomp-arm64.policy
deleted file mode 100644
index 4b523552..00000000
--- a/seccomp/cras-seccomp-arm64.policy
+++ /dev/null
@@ -1,90 +0,0 @@
-# Copyright 2018 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-clock_gettime: 1
-# Allow ioctl command of type 'A' and 'U' for SNDRV_PCM_IOCTL_* and
-# SNDRV_CTL_IOCTL_*, and EVIOCGSW(8), EVIOCGNAME(256), EVIOCGBIT(0x05, 8),
-# HCIGETDEVINFO
-ioctl: arg1 in 0xffff41ff && arg1 & 0x00004100 || arg1 in 0xffff55ff && arg1 & 0x00005500 || arg1 == 0x8008451b || arg1 == 0x81004506 || arg1 == 0x80084525 || arg1 == 0x800448d3
-ppoll: 1
-read: 1
-write: 1
-writev: 1
-newfstatat: 1
-fstat: 1
-openat: 1
-close: 1
-readlinkat: 1
-getrandom: 1
-faccessat: 1
-# Don't allow mmap or mprotect with both PROT_WRITE and PROT_EXEC
-mmap: arg2 in 0xfffffffb || arg2 in 0xfffffffd
-mprotect: arg2 in 0xfffffffb || arg2 in 0xfffffffd
-sendmsg: 1
-rt_sigaction: 1
-lseek: 1
-recvmsg: 1
-fcntl: 1
-getdents64: 1
-sendto: 1
-brk: 1
-munmap: 1
-socket: arg0 == AF_UNIX || arg0 == AF_BLUETOOTH || arg0 == AF_NETLINK
-socketpair: 1
-statfs: 1
-getsockopt: 1
-accept: 1
-pipe2: 1
-prctl: arg0 == PR_SET_NAME
-futex: 1
-ftruncate: 1
-fallocate: 1
-connect: 1
-bind: 1
-clock_getres: 1
-clone: 1
-epoll_create1: 1
-epoll_ctl: 1
-epoll_pwait: 1
-execve: 1
-exit: 1
-exit_group: 1
-fchmod: 1
-fchmodat: 1
-flock: 1
-getegid: 1
-geteuid: 1
-getgid: 1
-getresgid: 1
-getresuid: 1
-getrlimit: 1
-getsockname: 1
-gettid: 1
-gettimeofday: 1
-getuid: 1
-lgetxattr: 1
-listen: 1
-lsetxattr: 1
-madvise: 1
-nanosleep: 1
-clock_nanosleep: 1
-restart_syscall: 1
-rt_sigprocmask: 1
-rt_sigreturn: 1
-sched_get_priority_max: 1
-sched_get_priority_min: 1
-sched_setscheduler: 1
-setrlimit: 1
-set_robust_list: 1
-setpriority: 1
-setsockopt: 1
-set_tid_address: 1
-sysinfo: 1
-uname: 1
-unlinkat: 1
-getpid: 1
-prlimit64: 1
-tgkill: 1
-mremap: 1
-dup: 1
diff --git a/sof_sys/.gitignore b/sof_sys/.gitignore
deleted file mode 100644
index fa8d85ac..00000000
--- a/sof_sys/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-Cargo.lock
-target
diff --git a/sof_sys/.rustfmt.toml b/sof_sys/.rustfmt.toml
deleted file mode 100644
index a2db3012..00000000
--- a/sof_sys/.rustfmt.toml
+++ /dev/null
@@ -1,2 +0,0 @@
-use_field_init_shorthand = true
-use_try_shorthand = true
diff --git a/sof_sys/Cargo.toml b/sof_sys/Cargo.toml
deleted file mode 100644
index 21934ee1..00000000
--- a/sof_sys/Cargo.toml
+++ /dev/null
@@ -1,4 +0,0 @@
-[package]
-name = "sof_sys"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
diff --git a/sof_sys/generator/.gitignore b/sof_sys/generator/.gitignore
deleted file mode 100644
index 03314f77..00000000
--- a/sof_sys/generator/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-Cargo.lock
diff --git a/sof_sys/generator/Cargo.toml b/sof_sys/generator/Cargo.toml
deleted file mode 100644
index 672d41da..00000000
--- a/sof_sys/generator/Cargo.toml
+++ /dev/null
@@ -1,6 +0,0 @@
-[package]
-name = "generator"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-[dependencies]
-bindgen = "0.43.0"
diff --git a/sof_sys/generator/README.md b/sof_sys/generator/README.md
deleted file mode 100644
index 3e2ca771..00000000
--- a/sof_sys/generator/README.md
+++ /dev/null
@@ -1 +0,0 @@
-Use `cargo run` to generate rust bindings at sof_sys/src/bindings.rs
diff --git a/sof_sys/generator/src/main.rs b/sof_sys/generator/src/main.rs
deleted file mode 100644
index 60f0102d..00000000
--- a/sof_sys/generator/src/main.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-extern crate bindgen;
-
-use std::fs::File;
-use std::io::Write;
-use std::path::PathBuf;
-
-fn main() {
- let bindings = bindgen::Builder::default()
- .header("wrapper.h")
- .derive_debug(false)
- .clang_arg("-I../../../sound-open-firmware-private/src/include")
- .whitelist_type("sof_abi_hdr")
- .whitelist_type("sof_ipc_ctrl_cmd")
- .generate()
- .expect("Unable to generate bindings");
-
- let header = b"// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-/*
- * generated from files in sound-open-firmware-private/src/include:
- * kernel/header.h
- * ipc/control.h
- */
-
-";
-
- // Write the bindings to the $OUT_DIR/bindings.rs file.
- let out_path = PathBuf::from("../src").join("bindings.rs");
-
- let mut output_file =
- File::create(&out_path).expect(&format!("Couldn't create {:?}", out_path));
- output_file
- .write_all(header)
- .expect("Couldn't write header");
- output_file
- .write_all(bindings.to_string().as_bytes())
- .expect("Couldn't write bindings");
-}
diff --git a/sof_sys/generator/wrapper.h b/sof_sys/generator/wrapper.h
deleted file mode 100644
index 5bac0f57..00000000
--- a/sof_sys/generator/wrapper.h
+++ /dev/null
@@ -1,5 +0,0 @@
-// Copyright 2021 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-#include <kernel/header.h>
-#include <ipc/control.h>
diff --git a/sof_sys/src/bindings.rs b/sof_sys/src/bindings.rs
deleted file mode 100644
index 7bed0dcf..00000000
--- a/sof_sys/src/bindings.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-/*
- * generated from files in sound-open-firmware-private/src/include:
- * kernel/header.h
- * ipc/control.h
- */
-
-/* automatically generated by rust-bindgen */
-
-#[repr(C)]
-#[derive(Default)]
-pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>);
-impl<T> __IncompleteArrayField<T> {
- #[inline]
- pub fn new() -> Self {
- __IncompleteArrayField(::std::marker::PhantomData)
- }
- #[inline]
- pub unsafe fn as_ptr(&self) -> *const T {
- ::std::mem::transmute(self)
- }
- #[inline]
- pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
- ::std::mem::transmute(self)
- }
- #[inline]
- pub unsafe fn as_slice(&self, len: usize) -> &[T] {
- ::std::slice::from_raw_parts(self.as_ptr(), len)
- }
- #[inline]
- pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
- ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
- }
-}
-impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> {
- fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
- fmt.write_str("__IncompleteArrayField")
- }
-}
-impl<T> ::std::clone::Clone for __IncompleteArrayField<T> {
- #[inline]
- fn clone(&self) -> Self {
- Self::new()
- }
-}
-impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {}
-pub type __uint32_t = ::std::os::raw::c_uint;
-/// \brief Header for all non IPC ABI data.
-///
-/// Identifies data type, size and ABI.
-/// Data header used for all component data structures and binary blobs sent to
-/// firmware as runtime data. This data is typically sent by userspace
-/// applications and tunnelled through any OS kernel (via binary kcontrol on
-/// Linux) to the firmware.
-#[repr(C, packed)]
-pub struct sof_abi_hdr {
- ///< 'S', 'O', 'F', '\0'
- pub magic: u32,
- ///< component specific type
- pub type_: u32,
- ///< size in bytes of data excl. this struct
- pub size: u32,
- ///< SOF ABI version
- pub abi: u32,
- ///< reserved for future use
- pub reserved: [u32; 4usize],
- ///< Component data - opaque to core
- pub data: __IncompleteArrayField<u32>,
-}
-#[test]
-fn bindgen_test_layout_sof_abi_hdr() {
- assert_eq!(
- ::std::mem::size_of::<sof_abi_hdr>(),
- 32usize,
- concat!("Size of: ", stringify!(sof_abi_hdr))
- );
- assert_eq!(
- ::std::mem::align_of::<sof_abi_hdr>(),
- 1usize,
- concat!("Alignment of ", stringify!(sof_abi_hdr))
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<sof_abi_hdr>())).magic as *const _ as usize },
- 0usize,
- concat!(
- "Offset of field: ",
- stringify!(sof_abi_hdr),
- "::",
- stringify!(magic)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<sof_abi_hdr>())).type_ as *const _ as usize },
- 4usize,
- concat!(
- "Offset of field: ",
- stringify!(sof_abi_hdr),
- "::",
- stringify!(type_)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<sof_abi_hdr>())).size as *const _ as usize },
- 8usize,
- concat!(
- "Offset of field: ",
- stringify!(sof_abi_hdr),
- "::",
- stringify!(size)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<sof_abi_hdr>())).abi as *const _ as usize },
- 12usize,
- concat!(
- "Offset of field: ",
- stringify!(sof_abi_hdr),
- "::",
- stringify!(abi)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<sof_abi_hdr>())).reserved as *const _ as usize },
- 16usize,
- concat!(
- "Offset of field: ",
- stringify!(sof_abi_hdr),
- "::",
- stringify!(reserved)
- )
- );
- assert_eq!(
- unsafe { &(*(::std::ptr::null::<sof_abi_hdr>())).data as *const _ as usize },
- 32usize,
- concat!(
- "Offset of field: ",
- stringify!(sof_abi_hdr),
- "::",
- stringify!(data)
- )
- );
-}
-///< maps to ALSA volume style controls
-pub const sof_ipc_ctrl_cmd_SOF_CTRL_CMD_VOLUME: sof_ipc_ctrl_cmd = 0;
-///< maps to ALSA enum style controls
-pub const sof_ipc_ctrl_cmd_SOF_CTRL_CMD_ENUM: sof_ipc_ctrl_cmd = 1;
-///< maps to ALSA switch style controls
-pub const sof_ipc_ctrl_cmd_SOF_CTRL_CMD_SWITCH: sof_ipc_ctrl_cmd = 2;
-///< maps to ALSA binary style controls
-pub const sof_ipc_ctrl_cmd_SOF_CTRL_CMD_BINARY: sof_ipc_ctrl_cmd = 3;
-/// Control command type.
-pub type sof_ipc_ctrl_cmd = u32;
diff --git a/sof_sys/src/lib.rs b/sof_sys/src/lib.rs
deleted file mode 100644
index 57119cfa..00000000
--- a/sof_sys/src/lib.rs
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-#![allow(clippy::unreadable_literal)]
-#![allow(clippy::cognitive_complexity)]
-#![allow(non_upper_case_globals)]
-#![allow(non_camel_case_types)]
-#![allow(non_snake_case)]
-
-pub mod bindings;
-#[allow(unused_imports)]
-pub use bindings::sof_abi_hdr;
diff --git a/sound_card_init/.gitignore b/sound_card_init/.gitignore
deleted file mode 100644
index b6e87008..00000000
--- a/sound_card_init/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-# Generated by Cargo
-# will have compiled files and executables
-**/target/
-
-# These are backup files generated by rustfmt
-**/*.rs.bk
diff --git a/sound_card_init/99-sound_card_init.rules b/sound_card_init/99-sound_card_init.rules
deleted file mode 100644
index 82a3aec8..00000000
--- a/sound_card_init/99-sound_card_init.rules
+++ /dev/null
@@ -1,13 +0,0 @@
-# Copyright 2020 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-SUBSYSTEM!="sound", GOTO="sci_end"
-ACTION!="change", GOTO="sci_end"
-KERNEL!="card*", GOTO="sci_end"
-
-GOTO="sci_action"
-
-LABEL="sci_action"
-RUN+="/sbin/initctl start sound_card_init SOUND_CARD_ID=$attr{id}"
-LABEL="sci_end"
diff --git a/sound_card_init/Cargo.lock b/sound_card_init/Cargo.lock
deleted file mode 100644
index c89ad1ec..00000000
--- a/sound_card_init/Cargo.lock
+++ /dev/null
@@ -1,286 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-[[package]]
-name = "alsa-sys"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "644d308f5822c2b39fba5a6d850f74c208bf73c61d1d2dfad62505d6960e4977"
-dependencies = [
- "libc",
- "pkg-config",
-]
-
-[[package]]
-name = "amp"
-version = "0.1.0"
-dependencies = [
- "cros_alsa",
- "dsm",
- "libcras",
- "remain",
- "serde",
- "serde_yaml",
- "sof_sys",
- "sys_util",
-]
-
-[[package]]
-name = "android_log-sys"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85965b6739a430150bdd138e2374a98af0c3ee0d030b3bb7fc3bddff58d0102e"
-
-[[package]]
-name = "assertions"
-version = "0.1.0"
-
-[[package]]
-name = "audio_streams"
-version = "0.1.0"
-dependencies = [
- "sync",
- "sys_util",
-]
-
-[[package]]
-name = "cras-sys"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "data_model",
-]
-
-[[package]]
-name = "cros_alsa"
-version = "0.1.0"
-dependencies = [
- "alsa-sys",
- "cros_alsa_derive",
- "libc",
- "remain",
-]
-
-[[package]]
-name = "cros_alsa_derive"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "data_model"
-version = "0.1.0"
-dependencies = [
- "assertions",
- "libc",
-]
-
-[[package]]
-name = "dsm"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "cros_alsa",
- "libcras",
- "remain",
- "serde",
- "serde_yaml",
- "sys_util",
-]
-
-[[package]]
-name = "dtoa"
-version = "0.4.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88d7ed2934d741c6b37e33e3832298e8850b53fd2d2bea03873375596c7cea4e"
-
-[[package]]
-name = "getopts"
-version = "0.2.21"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5"
-dependencies = [
- "unicode-width",
-]
-
-[[package]]
-name = "libc"
-version = "0.2.82"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "89203f3fba0a3795506acaad8ebce3c80c0af93f994d5a1d7a0b1eeb23271929"
-
-[[package]]
-name = "libcras"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "cras-sys",
- "data_model",
- "libc",
- "sys_util",
-]
-
-[[package]]
-name = "linked-hash-map"
-version = "0.5.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
-
-[[package]]
-name = "pkg-config"
-version = "0.3.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c"
-
-[[package]]
-name = "poll_token_derive"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.24"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
-dependencies = [
- "unicode-xid",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "remain"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70ba1e78fa68412cb93ef642fd4d20b9a941be49ee9333875ebaf13112673ea7"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde"
-version = "1.0.119"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9bdd36f49e35b61d49efd8aa7fc068fd295961fd2286d0b2ee9a4c7a14e99cc3"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.119"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "552954ce79a059ddd5fd68c271592374bd15cab2274970380c000118aeffe1cd"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde_yaml"
-version = "0.8.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "971be8f6e4d4a47163b405a3df70d14359186f9ab0f3a3ec37df144ca1ce089f"
-dependencies = [
- "dtoa",
- "linked-hash-map",
- "serde",
- "yaml-rust",
-]
-
-[[package]]
-name = "sof_sys"
-version = "0.1.0"
-
-[[package]]
-name = "sound_card_init"
-version = "0.1.0"
-dependencies = [
- "amp",
- "audio_streams",
- "cros_alsa",
- "dsm",
- "getopts",
- "libcras",
- "remain",
- "serde",
- "serde_yaml",
- "sof_sys",
- "sys_util",
-]
-
-[[package]]
-name = "syn"
-version = "1.0.58"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cc60a3d73ea6594cd712d830cc1f0390fd71542d8c8cd24e70cc54cdfd5e05d5"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-xid",
-]
-
-[[package]]
-name = "sync"
-version = "0.1.0"
-
-[[package]]
-name = "sys_util"
-version = "0.1.0"
-dependencies = [
- "android_log-sys",
- "data_model",
- "libc",
- "poll_token_derive",
- "sync",
- "syscall_defines",
- "tempfile",
-]
-
-[[package]]
-name = "syscall_defines"
-version = "0.1.0"
-
-[[package]]
-name = "tempfile"
-version = "3.0.7"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "unicode-width"
-version = "0.1.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
-
-[[package]]
-name = "yaml-rust"
-version = "0.4.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
-dependencies = [
- "linked-hash-map",
-]
diff --git a/sound_card_init/Cargo.toml b/sound_card_init/Cargo.toml
deleted file mode 100644
index 9d5a107e..00000000
--- a/sound_card_init/Cargo.toml
+++ /dev/null
@@ -1,33 +0,0 @@
-[package]
-name = "sound_card_init"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-description = "Sound Card Initializer"
-
-[workspace]
-members = [
- "amp",
- "dsm"
-]
-
-[dependencies]
-amp = { path = "amp" }
-audio_streams = "*"
-cros_alsa = "*"
-dsm = { path = "dsm" }
-getopts = "0.2"
-libcras = "*"
-remain = "0.2.1"
-serde = { version = "1.0", features = ["derive"] }
-serde_yaml = "0.8.11"
-sof_sys = "*"
-sys_util = "*"
-
-[patch.crates-io]
-audio_streams = { path = "../audio_streams" } # ignored by ebuild
-cros_alsa = { path = "../cros_alsa" } # ignored by ebuild
-cros_alsa_derive = { path = "../cros_alsa/cros_alsa_derive" } # ignored by ebuild
-libcras = { path = "../cras/client/libcras" } # ignored by ebuild
-sof_sys = { path = "../sof_sys" } # ignored by ebuild
-sys_util = { path = "../../../platform/crosvm/sys_util" } # ignored by ebuild
diff --git a/sound_card_init/amp/Cargo.lock b/sound_card_init/amp/Cargo.lock
deleted file mode 100644
index 679e60cd..00000000
--- a/sound_card_init/amp/Cargo.lock
+++ /dev/null
@@ -1,254 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-[[package]]
-name = "alsa-sys"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "644d308f5822c2b39fba5a6d850f74c208bf73c61d1d2dfad62505d6960e4977"
-dependencies = [
- "libc",
- "pkg-config",
-]
-
-[[package]]
-name = "amp"
-version = "0.1.0"
-dependencies = [
- "cros_alsa",
- "dsm",
- "libcras",
- "remain",
- "serde",
- "serde_yaml",
- "sof_sys",
- "sys_util",
-]
-
-[[package]]
-name = "android_log-sys"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85965b6739a430150bdd138e2374a98af0c3ee0d030b3bb7fc3bddff58d0102e"
-
-[[package]]
-name = "assertions"
-version = "0.1.0"
-
-[[package]]
-name = "audio_streams"
-version = "0.1.0"
-dependencies = [
- "sync",
- "sys_util",
-]
-
-[[package]]
-name = "cras-sys"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "data_model",
-]
-
-[[package]]
-name = "cros_alsa"
-version = "0.1.0"
-dependencies = [
- "alsa-sys",
- "cros_alsa_derive",
- "libc",
- "remain",
-]
-
-[[package]]
-name = "cros_alsa_derive"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "data_model"
-version = "0.1.0"
-dependencies = [
- "assertions",
- "libc",
-]
-
-[[package]]
-name = "dsm"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "cros_alsa",
- "libcras",
- "remain",
- "serde",
- "serde_yaml",
- "sys_util",
-]
-
-[[package]]
-name = "dtoa"
-version = "0.4.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88d7ed2934d741c6b37e33e3832298e8850b53fd2d2bea03873375596c7cea4e"
-
-[[package]]
-name = "libc"
-version = "0.2.84"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1cca32fa0182e8c0989459524dc356b8f2b5c10f1b9eb521b7d182c03cf8c5ff"
-
-[[package]]
-name = "libcras"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "cras-sys",
- "data_model",
- "libc",
- "sys_util",
-]
-
-[[package]]
-name = "linked-hash-map"
-version = "0.5.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
-
-[[package]]
-name = "pkg-config"
-version = "0.3.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c"
-
-[[package]]
-name = "poll_token_derive"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.24"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
-dependencies = [
- "unicode-xid",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "991431c3519a3f36861882da93630ce66b52918dcf1b8e2fd66b397fc96f28df"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "remain"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70ba1e78fa68412cb93ef642fd4d20b9a941be49ee9333875ebaf13112673ea7"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde"
-version = "1.0.123"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "92d5161132722baa40d802cc70b15262b98258453e85e5d1d365c757c73869ae"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.123"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9391c295d64fc0abb2c556bad848f33cb8296276b1ad2677d1ae1ace4f258f31"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde_yaml"
-version = "0.8.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "971be8f6e4d4a47163b405a3df70d14359186f9ab0f3a3ec37df144ca1ce089f"
-dependencies = [
- "dtoa",
- "linked-hash-map",
- "serde",
- "yaml-rust",
-]
-
-[[package]]
-name = "sof_sys"
-version = "0.1.0"
-
-[[package]]
-name = "syn"
-version = "1.0.60"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-xid",
-]
-
-[[package]]
-name = "sync"
-version = "0.1.0"
-
-[[package]]
-name = "sys_util"
-version = "0.1.0"
-dependencies = [
- "android_log-sys",
- "data_model",
- "libc",
- "poll_token_derive",
- "sync",
- "syscall_defines",
- "tempfile",
-]
-
-[[package]]
-name = "syscall_defines"
-version = "0.1.0"
-
-[[package]]
-name = "tempfile"
-version = "3.0.7"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
-
-[[package]]
-name = "yaml-rust"
-version = "0.4.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
-dependencies = [
- "linked-hash-map",
-]
diff --git a/sound_card_init/amp/Cargo.toml b/sound_card_init/amp/Cargo.toml
deleted file mode 100644
index 62e63db7..00000000
--- a/sound_card_init/amp/Cargo.toml
+++ /dev/null
@@ -1,16 +0,0 @@
-[package]
-name = "amp"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-description = "The boot time calibration logic for smart amp"
-
-[dependencies]
-cros_alsa = "*"
-libcras = "*"
-dsm = { path = "../dsm" }
-remain = "0.2.1"
-serde = { version = "1.0", features = ["derive"]}
-serde_yaml = "0.8.11"
-sof_sys = "*"
-sys_util = "*"
diff --git a/sound_card_init/amp/src/lib.rs b/sound_card_init/amp/src/lib.rs
deleted file mode 100644
index 7114233d..00000000
--- a/sound_card_init/amp/src/lib.rs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2021 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! `amp` crate provides `Amp` trait for amplifier initializations and `AmpBuilder`
-//! to create `Amp` objects.
-#![deny(missing_docs)]
-
-mod max98373d;
-mod max98390d;
-use std::path::PathBuf;
-
-use dsm::Error;
-
-use max98373d::Max98373;
-use max98390d::Max98390;
-
-type Result<T> = std::result::Result<T, Error>;
-const CONF_DIR: &str = "/etc/sound_card_init";
-
-/// It creates `Amp` object based on the sound card name.
-pub struct AmpBuilder<'a> {
- sound_card_id: &'a str,
- config_path: PathBuf,
-}
-
-impl<'a> AmpBuilder<'a> {
- /// Creates an `AmpBuilder`.
- /// # Arguments
- ///
- /// * `card_name` - card name.
- /// * `conf_file` - config file name.
- pub fn new(sound_card_id: &'a str, conf_file: &'a str) -> Self {
- let config_path = PathBuf::from(CONF_DIR).join(conf_file);
- AmpBuilder {
- sound_card_id,
- config_path,
- }
- }
-
- /// Creates an `Amp` based on the sound card name.
- pub fn build(&self) -> Result<Box<dyn Amp>> {
- match self.sound_card_id {
- "sofcmlmax98390d" => {
- Ok(Box::new(Max98390::new(self.sound_card_id, &self.config_path)?) as Box<dyn Amp>)
- }
- "sofrt5682" => {
- Ok(Box::new(Max98373::new(self.sound_card_id, &self.config_path)?) as Box<dyn Amp>)
- }
- _ => Err(Error::UnsupportedSoundCard(self.sound_card_id.to_owned())),
- }
- }
-}
-
-/// It defines the required functions of amplifier objects.
-pub trait Amp {
- /// The amplifier boot time calibration flow.
- fn boot_time_calibration(&mut self) -> Result<()>;
-}
diff --git a/sound_card_init/amp/src/max98373d/dsm_param.rs b/sound_card_init/amp/src/max98373d/dsm_param.rs
deleted file mode 100644
index d9257522..00000000
--- a/sound_card_init/amp/src/max98373d/dsm_param.rs
+++ /dev/null
@@ -1,211 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::mem;
-
-use cros_alsa::{Card, TLV};
-use sof_sys::sof_abi_hdr;
-
-use dsm::{self, Error, Result};
-
-/// Amp volume mode enumeration used by set_volume().
-#[derive(Copy, Clone, PartialEq)]
-pub enum VolumeMode {
- /// Low mode protects the speaker by limiting its output volume if the
- /// calibration has not been completed successfully.
- Low = 0x1009B9CF,
- /// High mode removes the speaker output volume limitation after
- /// having successfully completed the calibration.
- High = 0x20000000,
-}
-
-#[derive(Copy, Clone)]
-/// Calibration mode enumeration.
-pub enum CalibMode {
- ON = 0x4,
- OFF = 0x1,
-}
-
-#[derive(Copy, Clone)]
-/// Smart pilot signal mode mode enumeration.
-pub enum SPTMode {
- ON = 0x1,
- OFF = 0x0,
-}
-
-#[derive(Copy, Clone)]
-/// DSM Parem field enumeration.
-enum DsmAPI {
- ParamCount = 0x0,
- CalibMode = 0x1,
- MakeupGain = 0x5,
- DsmRdc = 0x6,
- DsmAmbientTemp = 0x8,
- AdaptiveRdc = 0x12,
- SPTMode = 0x68,
-}
-
-#[derive(Debug)]
-/// It implements functions to access the `DSMParam` fields.
-pub struct DSMParam {
- param_count: usize,
- num_channels: usize,
- tlv: TLV,
-}
-
-impl DSMParam {
- const DWORD_PER_PARAM: usize = 2;
- const VALUE_OFFSET: usize = 1;
- const SOF_HEADER_SIZE: usize = mem::size_of::<sof_abi_hdr>() / mem::size_of::<i32>();
-
- /// Creates an `DSMParam`.
- /// # Arguments
- ///
- /// * `card` - `&Card`.
- /// * `num_channels` - number of channels.
- /// * `ctl_name` - the mixer control name to access the DSM param.
- ///
- /// # Results
- ///
- /// * `DSMParam` - It is initialized by the content of the given byte control .
- ///
- /// # Errors
- ///
- /// * If `Card` creation from sound card name fails.
- pub fn new(card: &mut Card, num_channels: usize, ctl_name: &str) -> Result<Self> {
- let tlv = card.control_tlv_by_name(ctl_name)?.load()?;
- Self::try_from_tlv(tlv, num_channels)
- }
-
- /// Sets DSMParam to the given calibration mode.
- pub fn set_calibration_mode(&mut self, mode: CalibMode) {
- for channel in 0..self.num_channels {
- self.set(channel, DsmAPI::CalibMode, mode as i32);
- }
- }
-
- /// Sets DSMParam to the given smart pilot signal mode.
- pub fn set_spt_mode(&mut self, mode: SPTMode) {
- for channel in 0..self.num_channels {
- self.set(channel, DsmAPI::SPTMode, mode as i32);
- }
- }
-
- /// Sets DSMParam to the given VolumeMode.
- pub fn set_volume_mode(&mut self, mode: VolumeMode) {
- for channel in 0..self.num_channels {
- self.set(channel, DsmAPI::MakeupGain, mode as i32);
- }
- }
-
- /// Reads the calibrated rdc from DSMParam.
- pub fn get_adaptive_rdc(&self) -> Vec<i32> {
- self.get(DsmAPI::AdaptiveRdc)
- }
-
- /// Sets DSMParam to the given the calibrated rdc.
- pub fn set_rdc(&mut self, ch: usize, rdc: i32) {
- self.set(ch, DsmAPI::DsmRdc, rdc);
- }
-
- /// Sets DSMParam to the given calibrated temp.
- pub fn set_ambient_temp(&mut self, ch: usize, temp: i32) {
- self.set(ch, DsmAPI::DsmAmbientTemp, temp);
- }
-
- /// Sets the `id` field to the given `val`.
- fn set(&mut self, channel: usize, id: DsmAPI, val: i32) {
- let pos = Self::value_pos(self.param_count, channel, id);
- self.tlv[pos] = val as u32;
- }
-
- /// Gets the val from the `id` field from all the channels.
- fn get(&self, id: DsmAPI) -> Vec<i32> {
- (0..self.num_channels)
- .map(|channel| {
- let pos = Self::value_pos(self.param_count, channel, id);
- self.tlv[pos] as i32
- })
- .collect()
- }
-
- fn try_from_tlv(tlv: TLV, num_channels: usize) -> Result<Self> {
- let param_count_pos = Self::value_pos(0, 0, DsmAPI::ParamCount);
-
- if tlv.len() < param_count_pos {
- return Err(Error::InvalidDSMParam);
- }
-
- let param_count = tlv[param_count_pos] as usize;
-
- if tlv.len() != Self::SOF_HEADER_SIZE + param_count * num_channels * Self::DWORD_PER_PARAM {
- return Err(Error::InvalidDSMParam);
- }
-
- Ok(Self {
- param_count,
- num_channels,
- tlv,
- })
- }
-
- #[inline]
- fn value_pos(param_count: usize, channel: usize, id: DsmAPI) -> usize {
- Self::SOF_HEADER_SIZE
- + (channel * param_count + id as usize) * Self::DWORD_PER_PARAM
- + Self::VALUE_OFFSET
- }
-}
-
-impl Into<TLV> for DSMParam {
- fn into(self) -> TLV {
- self.tlv
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- const PARAM_COUNT: usize = 138;
- const CHANNEL_COUNT: usize = 2;
-
- #[test]
- fn test_dsmparam_try_from_tlv_ok() {
- let mut data = vec![
- 0u32;
- DSMParam::SOF_HEADER_SIZE
- + CHANNEL_COUNT * PARAM_COUNT * DSMParam::DWORD_PER_PARAM
- ];
- data[DSMParam::value_pos(PARAM_COUNT, 0, DsmAPI::ParamCount)] = PARAM_COUNT as u32;
- data[DSMParam::value_pos(PARAM_COUNT, 1, DsmAPI::ParamCount)] = PARAM_COUNT as u32;
-
- let tlv = TLV::new(0, data);
- assert!(DSMParam::try_from_tlv(tlv, CHANNEL_COUNT).is_ok());
- }
-
- #[test]
- fn test_dsmparam_try_from_invalid_len() {
- let data = vec![0u32; DSMParam::SOF_HEADER_SIZE];
-
- let tlv = TLV::new(0, data);
- assert_eq!(
- DSMParam::try_from_tlv(tlv, CHANNEL_COUNT).unwrap_err(),
- Error::InvalidDSMParam
- );
- }
-
- #[test]
- fn test_dsmparam_try_from_param_count() {
- let data = vec![
- 0u32;
- DSMParam::SOF_HEADER_SIZE
- + CHANNEL_COUNT * PARAM_COUNT * DSMParam::DWORD_PER_PARAM
- ];
-
- let tlv = TLV::new(0, data);
- assert_eq!(
- DSMParam::try_from_tlv(tlv, CHANNEL_COUNT).unwrap_err(),
- Error::InvalidDSMParam
- );
- }
-}
diff --git a/sound_card_init/amp/src/max98373d/mod.rs b/sound_card_init/amp/src/max98373d/mod.rs
deleted file mode 100644
index 1ee29ceb..00000000
--- a/sound_card_init/amp/src/max98373d/mod.rs
+++ /dev/null
@@ -1,274 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! `max98373d` module implements the required initialization workflows for sound
-//! cards that use max98373d smart amp.
-//! It currently supports boot time calibration for max98373d.
-#![deny(missing_docs)]
-mod dsm_param;
-mod settings;
-
-use std::path::Path;
-use std::time::Duration;
-use std::{fs, thread};
-
-use cros_alsa::{Card, IntControl};
-use dsm::{CalibData, Error, Result, SpeakerStatus, ZeroPlayer, DSM};
-use sys_util::info;
-
-use crate::Amp;
-use dsm_param::*;
-use settings::{AmpCalibSettings, DeviceSettings};
-
-/// It implements the amplifier boot time calibration flow.
-pub struct Max98373 {
- card: Card,
- setting: AmpCalibSettings,
-}
-
-impl Amp for Max98373 {
- /// Performs max98373d boot time calibration.
- ///
- /// # Errors
- ///
- /// If any amplifiers fail to complete the calibration.
- fn boot_time_calibration(&mut self) -> Result<()> {
- if !Path::new(&self.setting.dsm_param).exists() {
- return Err(Error::MissingDSMParam);
- }
-
- let num_channels = self.setting.num_channels();
- let dsm = DSM::new(
- &self.card.name(),
- num_channels,
- Self::rdc_to_ohm,
- Self::TEMP_UPPER_LIMIT_CELSIUS,
- Self::TEMP_LOWER_LIMIT_CELSIUS,
- );
- self.set_volume(VolumeMode::Low)?;
-
- let calib = if !self.setting.boot_time_calibration_enabled {
- info!("skip boot time calibration and use vpd values");
- // Needs Rdc updates to be done after internal speaker is ready otherwise
- // it would be overwritten by the DSM blob update.
- dsm.wait_for_speakers_ready()?;
- dsm.get_all_vpd_calibration_value()?
- } else {
- match dsm.check_speaker_over_heated_workflow()? {
- SpeakerStatus::Hot(previous_calib) => previous_calib,
- SpeakerStatus::Cold => {
- let all_temp = self.get_ambient_temp()?;
- let all_rdc = self.do_rdc_calibration()?;
- all_rdc
- .iter()
- .zip(all_temp)
- .enumerate()
- .map(|(ch, (&rdc, temp))| {
- dsm.decide_calibration_value_workflow(ch, CalibData { rdc, temp })
- })
- .collect::<Result<Vec<_>>>()?
- }
- }
- };
- self.apply_calibration_value(&calib)?;
- self.set_volume(VolumeMode::High)?;
- Ok(())
- }
-}
-
-impl Max98373 {
- const TEMP_CALIB_WARM_UP_TIME: Duration = Duration::from_millis(10);
- const RDC_CALIB_WARM_UP_TIME: Duration = Duration::from_millis(500);
- const RDC_CALIB_INTERVAL: Duration = Duration::from_millis(200);
- const CALIB_REPEAT_TIMES: usize = 5;
-
- const TEMP_UPPER_LIMIT_CELSIUS: f32 = 40.0;
- const TEMP_LOWER_LIMIT_CELSIUS: f32 = 0.0;
-
- /// Creates an `Max98373`.
- /// # Arguments
- ///
- /// * `card_name` - card_name.
- /// * `config_path` - config file path.
- ///
- /// # Results
- ///
- /// * `Max98373` - It implements the Max98373 functions of boot time calibration.
- ///
- /// # Errors
- ///
- /// * If `Card` creation from sound card name fails.
- pub fn new(card_name: &str, config_path: &Path) -> Result<Self> {
- let conf = fs::read_to_string(config_path)
- .map_err(|e| Error::FileIOFailed(config_path.to_path_buf(), e))?;
- let settings = DeviceSettings::from_yaml_str(&conf)?;
- Ok(Self {
- card: Card::new(card_name)?,
- setting: settings.amp_calibrations,
- })
- }
-
- /// Triggers the amplifier calibration and reads the calibrated rdc.
- /// To get accurate calibration results, the main thread calibrates the amplifier while
- /// the `zero_player` starts another thread to play zeros to the speakers.
- fn do_rdc_calibration(&mut self) -> Result<Vec<i32>> {
- let mut zero_player: ZeroPlayer = Default::default();
- zero_player.start(Self::RDC_CALIB_WARM_UP_TIME)?;
- // Playback of zeros is started for Self::RDC_CALIB_WARM_UP_TIME, and the main thread
- // can start the calibration.
- self.set_spt_mode(SPTMode::OFF)?;
- self.set_calibration_mode(CalibMode::ON)?;
- // Playback of zeros is started, and the main thread can start the calibration.
- let mut avg_rdc = vec![0; self.setting.num_channels()];
- for _ in 0..Self::CALIB_REPEAT_TIMES {
- let rdc = self.get_adaptive_rdc()?;
- for i in 0..self.setting.num_channels() {
- avg_rdc[i] += rdc[i];
- }
- thread::sleep(Self::RDC_CALIB_INTERVAL);
- }
- self.set_spt_mode(SPTMode::ON)?;
- self.set_calibration_mode(CalibMode::OFF)?;
- zero_player.stop()?;
-
- avg_rdc = avg_rdc
- .iter()
- .map(|val| val / Self::CALIB_REPEAT_TIMES as i32)
- .collect();
- Ok(avg_rdc)
- }
-
- /// Sets the card volume control to the given VolumeMode.
- fn set_volume(&mut self, mode: VolumeMode) -> Result<()> {
- let mut dsm_param = DSMParam::new(
- &mut self.card,
- self.setting.num_channels(),
- &self.setting.dsm_param_read_ctrl,
- )?;
-
- dsm_param.set_volume_mode(mode);
-
- self.card
- .control_tlv_by_name(&self.setting.dsm_param_write_ctrl)?
- .save(dsm_param.into())
- .map_err(Error::DSMParamUpdateFailed)?;
- Ok(())
- }
-
- /// Applies the calibration value to the amp.
- fn apply_calibration_value(&mut self, calib: &[CalibData]) -> Result<()> {
- let mut dsm_param = DSMParam::new(
- &mut self.card,
- self.setting.num_channels(),
- &self.setting.dsm_param_read_ctrl,
- )?;
- for ch in 0..self.setting.num_channels() {
- dsm_param.set_rdc(ch, calib[ch].rdc);
- dsm_param.set_ambient_temp(ch, Self::celsius_to_dsm_unit(calib[ch].temp));
- }
- self.card
- .control_tlv_by_name(&self.setting.dsm_param_write_ctrl)?
- .save(dsm_param.into())
- .map_err(Error::DSMParamUpdateFailed)?;
- Ok(())
- }
-
- /// Rdc (ohm) = [ID:0x12] * 3.66 / 2^27
- #[inline]
- fn rdc_to_ohm(x: i32) -> f32 {
- (3.66 * x as f32) / (1 << 27) as f32
- }
-
- /// Returns the ambient temperature in celsius degree.
- fn get_ambient_temp(&mut self) -> Result<Vec<f32>> {
- let mut zero_player: ZeroPlayer = Default::default();
- zero_player.start(Self::TEMP_CALIB_WARM_UP_TIME)?;
- let mut temps = Vec::new();
- for x in 0..self.setting.num_channels() as usize {
- let temp = self
- .card
- .control_by_name::<IntControl>(&self.setting.temp_ctrl[x])?
- .get()?;
- let celsius = Self::measured_temp_to_celsius(temp);
- temps.push(celsius);
- }
- zero_player.stop()?;
-
- Ok(temps)
- }
-
- /// Converts the measured ambient temperature to celsius unit.
- #[inline]
- fn measured_temp_to_celsius(temp: i32) -> f32 {
- // Measured Temperature (°C) = ([Mixer Val] * 1.28) - 29
- (temp as f32 * 1.28) - 29.0
- }
-
- /// Converts the ambient temperature from celsius to the DsmSetAPI::DsmAmbientTemp unit.
- #[inline]
- fn celsius_to_dsm_unit(celsius: f32) -> i32 {
- // Temperature (℃) = [ID:0x12] / 2^19
- (celsius * (1 << 19) as f32) as i32
- }
-
- /// Sets the amp to the given smart pilot signal mode.
- fn set_spt_mode(&mut self, mode: SPTMode) -> Result<()> {
- let mut dsm_param = DSMParam::new(
- &mut self.card,
- self.setting.num_channels(),
- &self.setting.dsm_param_read_ctrl,
- )?;
- dsm_param.set_spt_mode(mode);
- self.card
- .control_tlv_by_name(&self.setting.dsm_param_write_ctrl)?
- .save(dsm_param.into())
- .map_err(Error::DSMParamUpdateFailed)?;
- Ok(())
- }
-
- /// Sets the amp to the given the calibration mode.
- fn set_calibration_mode(&mut self, mode: CalibMode) -> Result<()> {
- let mut dsm_param = DSMParam::new(
- &mut self.card,
- self.setting.num_channels(),
- &self.setting.dsm_param_read_ctrl,
- )?;
- dsm_param.set_calibration_mode(mode);
- self.card
- .control_tlv_by_name(&self.setting.dsm_param_write_ctrl)?
- .save(dsm_param.into())
- .map_err(Error::DSMParamUpdateFailed)?;
- Ok(())
- }
-
- /// Reads the calibrated rdc.
- /// Must be called when the calibration mode in on.
- fn get_adaptive_rdc(&mut self) -> Result<Vec<i32>> {
- let dsm_param = DSMParam::new(
- &mut self.card,
- self.setting.num_channels(),
- &self.setting.dsm_param_read_ctrl,
- )?;
- Ok(dsm_param.get_adaptive_rdc())
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- #[test]
- fn celsius_to_dsm_unit() {
- assert_eq!(Max98373::celsius_to_dsm_unit(37.0), 0x01280000);
- assert_eq!(Max98373::celsius_to_dsm_unit(50.0), 0x01900000);
- }
-
- #[test]
- fn rdc_to_ohm() {
- assert_eq!(Max98373::rdc_to_ohm(0x05cea0c7), 2.656767);
- }
-
- #[test]
- fn measured_temp_to_celsius() {
- assert_eq!(Max98373::measured_temp_to_celsius(56), 42.68);
- }
-}
diff --git a/sound_card_init/amp/src/max98373d/settings.rs b/sound_card_init/amp/src/max98373d/settings.rs
deleted file mode 100644
index 1d6e64e5..00000000
--- a/sound_card_init/amp/src/max98373d/settings.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::string::String;
-
-use dsm::{self, Error, Result};
-use serde::Deserialize;
-/// `DeviceSettings` includes the settings of max98373. It currently includes:
-/// * the settings of amplifier calibration.
-/// * the path of dsm_param.
-#[derive(Debug, Default, PartialEq, Deserialize, Clone)]
-pub struct DeviceSettings {
- pub amp_calibrations: AmpCalibSettings,
-}
-
-/// `AmpCalibSettings` includes the settings needed for amplifier calibration.
-#[derive(Debug, Default, PartialEq, Deserialize, Clone)]
-pub struct AmpCalibSettings {
- pub dsm_param_read_ctrl: String,
- pub dsm_param_write_ctrl: String,
- pub temp_ctrl: Vec<String>,
- // Path of the dsm_param.bin file.
- pub dsm_param: String,
- pub boot_time_calibration_enabled: bool,
-}
-
-impl AmpCalibSettings {
- /// Returns the number of channels.
- pub fn num_channels(&self) -> usize {
- self.temp_ctrl.len()
- }
-}
-
-impl DeviceSettings {
- /// Creates a `DeviceSettings` from a yaml str.
- pub fn from_yaml_str(conf: &str) -> Result<DeviceSettings> {
- let settings: DeviceSettings = serde_yaml::from_str(conf)
- .map_err(|e| Error::DeserializationFailed("DeviceSettings".to_owned(), e))?;
- Ok(settings)
- }
-}
diff --git a/sound_card_init/amp/src/max98390d/mod.rs b/sound_card_init/amp/src/max98390d/mod.rs
deleted file mode 100644
index 601165ec..00000000
--- a/sound_card_init/amp/src/max98390d/mod.rs
+++ /dev/null
@@ -1,213 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! `max98390d` module implements the required initialization workflows for sound
-//! cards that use max98390d smart amp.
-//! It currently supports boot time calibration for max98390d.
-#![deny(missing_docs)]
-mod settings;
-
-use std::time::Duration;
-use std::{fs, path::Path};
-
-use cros_alsa::{Card, IntControl, SwitchControl};
-use dsm::{CalibData, Error, Result, SpeakerStatus, TempConverter, ZeroPlayer, DSM};
-
-use crate::Amp;
-use settings::{AmpCalibSettings, DeviceSettings};
-
-/// Amp volume mode emulation used by set_volume().
-#[derive(PartialEq, Clone, Copy)]
-enum VolumeMode {
- /// Low mode protects the speaker by limiting its output volume if the
- /// calibration has not been completed successfully.
- Low = 138,
- /// High mode removes the speaker output volume limitation after
- /// having successfully completed the calibration.
- High = 148,
-}
-
-/// It implements the Max98390 functions of boot time calibration.
-#[derive(Debug)]
-pub struct Max98390 {
- card: Card,
- setting: AmpCalibSettings,
-}
-
-impl Amp for Max98390 {
- /// Performs max98390d boot time calibration.
- ///
- /// # Errors
- ///
- /// If the amplifier fails to complete the calibration.
- fn boot_time_calibration(&mut self) -> Result<()> {
- if !Path::new(&self.setting.dsm_param).exists() {
- return Err(Error::MissingDSMParam);
- }
-
- let mut dsm = DSM::new(
- &self.card.name(),
- self.setting.num_channels(),
- Self::rdc_to_ohm,
- Self::TEMP_UPPER_LIMIT_CELSIUS,
- Self::TEMP_LOWER_LIMIT_CELSIUS,
- );
- dsm.set_temp_converter(TempConverter::new(
- Self::dsm_unit_to_celsius,
- Self::celsius_to_dsm_unit,
- ));
-
- self.set_volume(VolumeMode::Low)?;
- let calib = match dsm.check_speaker_over_heated_workflow()? {
- SpeakerStatus::Hot(previous_calib) => previous_calib,
- SpeakerStatus::Cold => self
- .do_calibration()?
- .iter()
- .enumerate()
- .map(|(ch, calib_data)| dsm.decide_calibration_value_workflow(ch, *calib_data))
- .collect::<Result<Vec<_>>>()?,
- };
- self.apply_calibration_value(calib)?;
- self.set_volume(VolumeMode::High)?;
- Ok(())
- }
-}
-
-impl Max98390 {
- const TEMP_UPPER_LIMIT_CELSIUS: f32 = 40.0;
- const TEMP_LOWER_LIMIT_CELSIUS: f32 = 0.0;
- const RDC_CALIB_WARM_UP_TIME: Duration = Duration::from_millis(300);
-
- /// Creates an `Max98390`.
- /// # Arguments
- ///
- /// * `card_name` - card name.
- /// * `config_path` - config file path.
- ///
- /// # Results
- ///
- /// * `Max98390` - It implements the Max98390 functions of boot time calibration.
- ///
- /// # Errors
- ///
- /// * If `Card` creation from sound card name fails.
- pub fn new(card_name: &str, config_path: &Path) -> Result<Self> {
- let conf = fs::read_to_string(config_path)
- .map_err(|e| Error::FileIOFailed(config_path.to_path_buf(), e))?;
- let settings = DeviceSettings::from_yaml_str(&conf)?;
- Ok(Self {
- card: Card::new(card_name)?,
- setting: settings.amp_calibrations,
- })
- }
-
- /// Sets the card volume control to given VolumeMode.
- fn set_volume(&mut self, mode: VolumeMode) -> Result<()> {
- for control in &self.setting.controls {
- self.card
- .control_by_name::<IntControl>(&control.volume_ctrl)?
- .set(mode as i32)?;
- }
- Ok(())
- }
-
- /// Applies the calibration value to the amp.
- fn apply_calibration_value(&mut self, calib: Vec<CalibData>) -> Result<()> {
- for (ch, &CalibData { rdc, temp }) in calib.iter().enumerate() {
- self.card
- .control_by_name::<IntControl>(&self.setting.controls[ch].rdc_ctrl)?
- .set(rdc)?;
- self.card
- .control_by_name::<IntControl>(&self.setting.controls[ch].temp_ctrl)?
- .set(Self::celsius_to_dsm_unit(temp))?;
- }
- Ok(())
- }
-
- /// Triggers the amplifier calibration and reads the calibrated rdc and ambient_temp value
- /// from the mixer control.
- /// To get accurate calibration results, the main thread calibrates the amplifier while
- /// the `zero_player` starts another thread to play zeros to the speakers.
- fn do_calibration(&mut self) -> Result<Vec<CalibData>> {
- let mut zero_player: ZeroPlayer = Default::default();
- zero_player.start(Self::RDC_CALIB_WARM_UP_TIME)?;
- // Playback of zeros is started for Self::RDC_CALIB_WARM_UP_TIME, and the main thread
- // can start the calibration.
- let setting = &self.setting;
- let card = &mut self.card;
- let calib = setting
- .controls
- .iter()
- .map(|control| {
- card.control_by_name::<SwitchControl>(&control.calib_ctrl)?
- .on()?;
- let rdc = card
- .control_by_name::<IntControl>(&control.rdc_ctrl)?
- .get()?;
- let temp = card
- .control_by_name::<IntControl>(&control.temp_ctrl)?
- .get()?;
- card.control_by_name::<SwitchControl>(&control.calib_ctrl)?
- .off()?;
- Ok(CalibData {
- rdc,
- temp: Self::dsm_unit_to_celsius(temp),
- })
- })
- .collect::<Result<Vec<CalibData>>>()?;
- zero_player.stop()?;
- Ok(calib)
- }
-
- /// Converts the ambient temperature from celsius to the DSM unit.
- #[inline]
- fn celsius_to_dsm_unit(celsius: f32) -> i32 {
- (celsius * ((1 << 12) as f32) / 100.0) as i32
- }
-
- /// Converts the ambient temperature from DSM unit to celsius.
- #[inline]
- fn dsm_unit_to_celsius(temp: i32) -> f32 {
- temp as f32 * 100.0 / (1 << 12) as f32
- }
-
- /// Converts the calibrated value to real DC resistance in ohm unit.
- #[inline]
- fn rdc_to_ohm(x: i32) -> f32 {
- 3.66 * (1 << 20) as f32 / x as f32
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- #[test]
- fn celsius_to_dsm_unit() {
- assert_eq!(
- Max98390::celsius_to_dsm_unit(Max98390::TEMP_UPPER_LIMIT_CELSIUS),
- 1638
- );
- assert_eq!(
- Max98390::celsius_to_dsm_unit(Max98390::TEMP_LOWER_LIMIT_CELSIUS),
- 0
- );
- }
-
- #[test]
- fn dsm_unit_to_celsius() {
- assert_eq!(
- Max98390::dsm_unit_to_celsius(1638).round(),
- Max98390::TEMP_UPPER_LIMIT_CELSIUS
- );
- assert_eq!(
- Max98390::dsm_unit_to_celsius(0),
- Max98390::TEMP_LOWER_LIMIT_CELSIUS
- );
- }
-
- #[test]
- fn rdc_to_ohm() {
- assert_eq!(Max98390::rdc_to_ohm(1123160), 3.416956);
- assert_eq!(Max98390::rdc_to_ohm(1157049), 3.3168762);
- }
-}
diff --git a/sound_card_init/amp/src/max98390d/settings.rs b/sound_card_init/amp/src/max98390d/settings.rs
deleted file mode 100644
index 316f25be..00000000
--- a/sound_card_init/amp/src/max98390d/settings.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::string::String;
-
-use dsm::{self, Error, Result};
-use serde::Deserialize;
-
-/// `DeviceSettings` includes the settings of max98390. It currently includes:
-/// * the settings of amplifier calibration.
-/// * the path of dsm_param.
-#[derive(Debug, Default, PartialEq, Deserialize, Clone)]
-pub struct DeviceSettings {
- pub amp_calibrations: AmpCalibSettings,
-}
-#[derive(Debug, Default, PartialEq, Deserialize, Clone)]
-pub struct AmpCalibCtrl {
- // Mixer control to get/set rdc value.
- pub rdc_ctrl: String,
- // Mixer control to get/set ambient temperature value.
- pub temp_ctrl: String,
- // Mixer control to trigger calibration.
- pub calib_ctrl: String,
- // Mixer control to adjust volume.
- pub volume_ctrl: String,
-}
-
-/// `AmpCalibSettings` includes the settings needed for amplifier calibration.
-#[derive(Debug, Default, PartialEq, Deserialize, Clone)]
-pub struct AmpCalibSettings {
- // Mixer control to get/set rdc value.
- pub controls: Vec<AmpCalibCtrl>,
- // Path of the dsm_param.bin file.
- pub dsm_param: String,
-}
-
-impl AmpCalibSettings {
- /// Returns the number of channels.
- pub fn num_channels(&self) -> usize {
- self.controls.len()
- }
-}
-
-impl DeviceSettings {
- /// Creates a `DeviceSettings` from a yaml str.
- pub fn from_yaml_str(conf: &str) -> Result<DeviceSettings> {
- let settings: DeviceSettings = serde_yaml::from_str(conf)
- .map_err(|e| Error::DeserializationFailed("DeviceSettings".to_owned(), e))?;
- Ok(settings)
- }
-}
diff --git a/sound_card_init/dsm/Cargo.lock b/sound_card_init/dsm/Cargo.lock
deleted file mode 100644
index 411c7527..00000000
--- a/sound_card_init/dsm/Cargo.lock
+++ /dev/null
@@ -1,229 +0,0 @@
-# This file is automatically @generated by Cargo.
-# It is not intended for manual editing.
-[[package]]
-name = "alsa-sys"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "644d308f5822c2b39fba5a6d850f74c208bf73c61d1d2dfad62505d6960e4977"
-dependencies = [
- "libc",
- "pkg-config",
-]
-
-[[package]]
-name = "assertions"
-version = "0.1.0"
-
-[[package]]
-name = "audio_streams"
-version = "0.1.0"
-dependencies = [
- "sync",
- "sys_util",
-]
-
-[[package]]
-name = "cras-sys"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "data_model",
-]
-
-[[package]]
-name = "cros_alsa"
-version = "0.1.0"
-dependencies = [
- "alsa-sys",
- "libc",
- "remain",
- "sys_util",
-]
-
-[[package]]
-name = "data_model"
-version = "0.1.0"
-dependencies = [
- "assertions",
-]
-
-[[package]]
-name = "dtoa"
-version = "0.4.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4358a9e11b9a09cf52383b451b49a169e8d797b68aa02301ff586d70d9661ea3"
-
-[[package]]
-name = "libc"
-version = "0.2.69"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99e85c08494b21a9054e7fe1374a732aeadaff3980b6990b94bfd3a70f690005"
-
-[[package]]
-name = "libcras"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "cras-sys",
- "data_model",
- "libc",
- "sys_util",
-]
-
-[[package]]
-name = "linked-hash-map"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae91b68aebc4ddb91978b11a1b02ddd8602a05ec19002801c5666000e05e0f83"
-
-[[package]]
-name = "max98390d"
-version = "0.1.0"
-dependencies = [
- "audio_streams",
- "cros_alsa",
- "libcras",
- "remain",
- "serde",
- "serde_yaml",
- "sound_card_util",
- "sys_util",
-]
-
-[[package]]
-name = "pkg-config"
-version = "0.3.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677"
-
-[[package]]
-name = "poll_token_derive"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "proc-macro2"
-version = "1.0.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "df246d292ff63439fea9bc8c0a270bed0e390d5ebd4db4ba15aba81111b5abe3"
-dependencies = [
- "unicode-xid",
-]
-
-[[package]]
-name = "quote"
-version = "1.0.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f"
-dependencies = [
- "proc-macro2",
-]
-
-[[package]]
-name = "remain"
-version = "0.2.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99c861227fc40c8da6fdaa3d58144ac84c0537080a43eb1d7d45c28f88dcb888"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde"
-version = "1.0.106"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36df6ac6412072f67cf767ebbde4133a5b2e88e76dc6187fa7104cd16f783399"
-dependencies = [
- "serde_derive",
-]
-
-[[package]]
-name = "serde_derive"
-version = "1.0.106"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e549e3abf4fb8621bd1609f11dfc9f5e50320802273b12f3811a67e6716ea6c"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
-[[package]]
-name = "serde_yaml"
-version = "0.8.11"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "691b17f19fc1ec9d94ec0b5864859290dff279dbd7b03f017afda54eb36c3c35"
-dependencies = [
- "dtoa",
- "linked-hash-map",
- "serde",
- "yaml-rust",
-]
-
-[[package]]
-name = "sound_card_util"
-version = "0.1.0"
-dependencies = [
- "cros_alsa",
- "remain",
- "sys_util",
-]
-
-[[package]]
-name = "syn"
-version = "1.0.17"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0df0eb663f387145cab623dea85b09c2c5b4b0aef44e945d928e682fce71bb03"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-xid",
-]
-
-[[package]]
-name = "sync"
-version = "0.1.0"
-
-[[package]]
-name = "sys_util"
-version = "0.1.0"
-dependencies = [
- "data_model",
- "libc",
- "poll_token_derive",
- "sync",
- "syscall_defines",
- "tempfile",
-]
-
-[[package]]
-name = "syscall_defines"
-version = "0.1.0"
-
-[[package]]
-name = "tempfile"
-version = "3.0.7"
-dependencies = [
- "libc",
-]
-
-[[package]]
-name = "unicode-xid"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c"
-
-[[package]]
-name = "yaml-rust"
-version = "0.4.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "65923dd1784f44da1d2c3dbbc5e822045628c590ba72123e1c73d3c230c4434d"
-dependencies = [
- "linked-hash-map",
-]
diff --git a/sound_card_init/dsm/Cargo.toml b/sound_card_init/dsm/Cargo.toml
deleted file mode 100644
index 280896d2..00000000
--- a/sound_card_init/dsm/Cargo.toml
+++ /dev/null
@@ -1,15 +0,0 @@
-[package]
-name = "dsm"
-version = "0.1.0"
-authors = ["The Chromium OS Authors"]
-edition = "2018"
-description = "The boot time calibration logic for smart amp"
-
-[dependencies]
-cros_alsa = "*"
-audio_streams = "*"
-libcras = "*"
-remain = "0.2.1"
-serde = { version = "1.0", features = ["derive"]}
-serde_yaml = "0.8.11"
-sys_util = "*" \ No newline at end of file
diff --git a/sound_card_init/dsm/src/datastore.rs b/sound_card_init/dsm/src/datastore.rs
deleted file mode 100644
index f0180cc2..00000000
--- a/sound_card_init/dsm/src/datastore.rs
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::fs::{remove_file, File};
-use std::io::{prelude::*, BufReader, BufWriter};
-use std::path::PathBuf;
-
-use serde::{Deserialize, Serialize};
-use sys_util::info;
-
-use crate::error::{Error, Result};
-
-/// `Datastore`, which stores and reads calibration values in yaml format.
-#[derive(Debug, Deserialize, Serialize, Copy, Clone)]
-pub enum Datastore {
- /// Indicates using values in VPD.
- UseVPD,
- DSM {
- rdc: i32,
- temp: i32,
- },
-}
-
-impl Datastore {
- /// The dir of datastore.
- pub const DATASTORE_DIR: &'static str = "/var/lib/sound_card_init";
-
- /// Creates a `Datastore` and initializes its fields from the datastore file.
- pub fn from_file(snd_card: &str, channel: usize) -> Result<Datastore> {
- let path = Self::path(snd_card, channel);
- let reader =
- BufReader::new(File::open(&path).map_err(|e| Error::FileIOFailed(path.to_owned(), e))?);
- let datastore: Datastore =
- serde_yaml::from_reader(reader).map_err(|e| Error::SerdeError(path.to_owned(), e))?;
- Ok(datastore)
- }
-
- /// Saves a `Datastore` to file.
- pub fn save(&self, snd_card: &str, channel: usize) -> Result<()> {
- let path = Self::path(snd_card, channel);
-
- let mut writer = BufWriter::new(
- File::create(&path).map_err(|e| Error::FileIOFailed(path.to_owned(), e))?,
- );
- writer
- .write(
- serde_yaml::to_string(self)
- .map_err(|e| Error::SerdeError(path.to_owned(), e))?
- .as_bytes(),
- )
- .map_err(|e| Error::FileIOFailed(path.to_owned(), e))?;
- writer
- .flush()
- .map_err(|e| Error::FileIOFailed(path.to_owned(), e))?;
- info!("update Datastore {}: {:?}", path.to_string_lossy(), self);
- Ok(())
- }
-
- /// Deletes the datastore file.
- pub fn delete(snd_card: &str, channel: usize) -> Result<()> {
- let path = Self::path(snd_card, channel);
- remove_file(&path).map_err(|e| Error::FileIOFailed(path.to_owned(), e))?;
- info!("datastore: {:#?} is deleted.", path);
- Ok(())
- }
-
- fn path(snd_card: &str, channel: usize) -> PathBuf {
- PathBuf::from(Self::DATASTORE_DIR)
- .join(snd_card)
- .join(format!("calib_{}", channel))
- }
-}
diff --git a/sound_card_init/dsm/src/error.rs b/sound_card_init/dsm/src/error.rs
deleted file mode 100644
index 4b6e8dc2..00000000
--- a/sound_card_init/dsm/src/error.rs
+++ /dev/null
@@ -1,128 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::any::Any;
-use std::error;
-use std::fmt;
-use std::io;
-use std::num::ParseIntError;
-use std::path::PathBuf;
-use std::sync::PoisonError;
-use std::time;
-
-use remain::sorted;
-
-use crate::CalibData;
-
-pub type Result<T> = std::result::Result<T, Error>;
-
-#[sorted]
-#[derive(Debug)]
-pub enum Error {
- AlsaCardError(cros_alsa::CardError),
- AlsaControlError(cros_alsa::ControlError),
- AlsaControlTLVError(cros_alsa::ControlTLVError),
- CalibrationTimeout,
- CrasClientFailed(libcras::Error),
- DeserializationFailed(String, serde_yaml::Error),
- DSMParamUpdateFailed(cros_alsa::ControlTLVError),
- FileIOFailed(PathBuf, io::Error),
- InternalSpeakerNotFound,
- InvalidDatastore,
- InvalidDSMParam,
- InvalidShutDownTime,
- InvalidTemperature(f32),
- LargeCalibrationDiff(CalibData),
- MissingDSMParam,
- MutexPoisonError,
- NewPlayStreamFailed(libcras::BoxError),
- NextPlaybackBufferFailed(libcras::BoxError),
- PlaybackFailed(io::Error),
- SerdeError(PathBuf, serde_yaml::Error),
- StartPlaybackTimeout,
- SystemTimeError(time::SystemTimeError),
- UnsupportedSoundCard(String),
- VPDParseFailed(String, ParseIntError),
- WorkerPanics(Box<dyn Any + Send + 'static>),
- ZeroPlayerIsNotRunning,
- ZeroPlayerIsRunning,
-}
-
-impl PartialEq for Error {
- // Implement eq for more Error when needed.
- fn eq(&self, other: &Error) -> bool {
- match (self, other) {
- (Error::InvalidDSMParam, Error::InvalidDSMParam) => true,
- _ => false,
- }
- }
-}
-
-impl From<cros_alsa::CardError> for Error {
- fn from(err: cros_alsa::CardError) -> Error {
- Error::AlsaCardError(err)
- }
-}
-
-impl From<cros_alsa::ControlError> for Error {
- fn from(err: cros_alsa::ControlError) -> Error {
- Error::AlsaControlError(err)
- }
-}
-
-impl From<cros_alsa::ControlTLVError> for Error {
- fn from(err: cros_alsa::ControlTLVError) -> Error {
- Error::AlsaControlTLVError(err)
- }
-}
-
-impl<T> From<PoisonError<T>> for Error {
- fn from(_: PoisonError<T>) -> Error {
- Error::MutexPoisonError
- }
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- AlsaCardError(e) => write!(f, "AlsaCardError: {}", e),
- AlsaControlError(e) => write!(f, "AlsaControlError: {}", e),
- AlsaControlTLVError(e) => write!(f, "AlsaControlTLVError: {}", e),
- CalibrationTimeout => write!(f, "calibration is not finished in time"),
- DSMParamUpdateFailed(e) => write!(f, "failed to update DsmParam, err: {}", e),
- CrasClientFailed(e) => write!(f, "failed to create cras client: {}", e),
- DeserializationFailed(file_path, e) => {
- write!(f, "failed to parse {}: {}", file_path, e)
- }
- FileIOFailed(file_path, e) => write!(f, "{:#?}: {}", file_path, e),
- InvalidShutDownTime => write!(f, "invalid shutdown time"),
- InternalSpeakerNotFound => write!(f, "internal speaker is not found in cras"),
- InvalidTemperature(temp) => write!(
- f,
- "invalid calibration temperature: {}, and there is no datastore",
- temp
- ),
- InvalidDatastore => write!(f, "invalid datastore format"),
- InvalidDSMParam => write!(f, "invalid dsm param from kcontrol"),
- LargeCalibrationDiff(calib) => {
- write!(f, "calibration difference is too large, calib: {:?}", calib)
- }
- MissingDSMParam => write!(f, "missing dsm_param.bin"),
- MutexPoisonError => write!(f, "mutex is poisoned"),
- NewPlayStreamFailed(e) => write!(f, "{}", e),
- NextPlaybackBufferFailed(e) => write!(f, "{}", e),
- PlaybackFailed(e) => write!(f, "{}", e),
- SerdeError(file_path, e) => write!(f, "{:?}: {}", file_path, e),
- StartPlaybackTimeout => write!(f, "playback is not started in time"),
- SystemTimeError(e) => write!(f, "{}", e),
- UnsupportedSoundCard(name) => write!(f, "unsupported sound card: {}", name),
- VPDParseFailed(file_path, e) => write!(f, "failed to parse vpd {}: {}", file_path, e),
- WorkerPanics(e) => write!(f, "run_play_zero_worker panics: {:#?}", e),
- ZeroPlayerIsNotRunning => write!(f, "zero player is not running"),
- ZeroPlayerIsRunning => write!(f, "zero player is running"),
- }
- }
-}
diff --git a/sound_card_init/dsm/src/lib.rs b/sound_card_init/dsm/src/lib.rs
deleted file mode 100644
index 0b3ec64c..00000000
--- a/sound_card_init/dsm/src/lib.rs
+++ /dev/null
@@ -1,335 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! `dsm` crate implements the required initialization workflows for smart amps.
-
-mod datastore;
-mod error;
-pub mod utils;
-mod vpd;
-mod zero_player;
-
-use std::{
- thread,
- time::{Duration, SystemTime, UNIX_EPOCH},
-};
-
-use libcras::{CrasClient, CrasNodeType};
-use sys_util::{error, info};
-
-use crate::datastore::Datastore;
-pub use crate::error::{Error, Result};
-use crate::utils::{run_time, shutdown_time};
-use crate::vpd::VPD;
-pub use crate::zero_player::ZeroPlayer;
-
-#[derive(Debug, Clone, Copy)]
-/// `CalibData` represents the calibration data.
-pub struct CalibData {
- /// The DC resistance of the speaker is DSM unit.
- pub rdc: i32,
- /// The ambient temperature in celsius unit at which the rdc is measured.
- pub temp: f32,
-}
-
-/// `TempConverter` converts the temperature value between celsius and unit in VPD::dsm_calib_temp.
-pub struct TempConverter {
- vpd_to_celsius: fn(i32) -> f32,
- celsius_to_vpd: fn(f32) -> i32,
-}
-
-impl Default for TempConverter {
- fn default() -> Self {
- let vpd_to_celsius = |x: i32| x as f32;
- let celsius_to_vpd = |x: f32| x.round() as i32;
- Self {
- vpd_to_celsius,
- celsius_to_vpd,
- }
- }
-}
-
-impl TempConverter {
- /// Creates a `TempConverter`
- ///
- /// # Arguments
- ///
- /// * `vpd_to_celsius` - function to convert VPD::dsm_calib_temp to celsius unit`
- /// * `celsius_to_vpd` - function to convert celsius unit to VPD::dsm_calib_temp`
- /// # Results
- ///
- /// * `TempConverter` - it converts the temperature value between celsius and unit in VPD::dsm_calib_temp.
- pub fn new(vpd_to_celsius: fn(i32) -> f32, celsius_to_vpd: fn(f32) -> i32) -> Self {
- Self {
- vpd_to_celsius,
- celsius_to_vpd,
- }
- }
-}
-
-/// `SpeakerStatus` are the possible return results of
-/// DSM::check_speaker_over_heated_workflow.
-pub enum SpeakerStatus {
- ///`SpeakerStatus::Cold` means the speakers are not overheated and the Amp can
- /// trigger the boot time calibration.
- Cold,
- /// `SpeakerStatus::Hot(Vec<CalibData>)` means the speakers may be too hot for calibration.
- /// The boot time calibration should be skipped and the Amp should use the previous
- /// calibration values returned by the enum.
- Hot(Vec<CalibData>),
-}
-
-/// `DSM`, which implements the required initialization workflows for smart amps.
-pub struct DSM {
- snd_card: String,
- num_channels: usize,
- temp_converter: TempConverter,
- rdc_to_ohm: fn(i32) -> f32,
- temp_upper_limit: f32,
- temp_lower_limit: f32,
-}
-
-impl DSM {
- const SPEAKER_COOL_DOWN_TIME: Duration = Duration::from_secs(180);
- const CALI_ERROR_UPPER_LIMIT: f32 = 0.3;
- const CALI_ERROR_LOWER_LIMIT: f32 = 0.03;
-
- /// Creates a `DSM`
- ///
- /// # Arguments
- ///
- /// * `snd_card` - `sound card name`.
- /// * `num_channels` - `number of channels`.
- /// * `rdc_to_ohm` - `fn(rdc: i32) -> f32 to convert the CalibData::rdc to ohm unit`.
- /// * `temp_upper_limit` - the high limit of the valid ambient temperature in dsm unit.
- /// * `temp_lower_limit` - the low limit of the valid ambient temperature in dsm unit.
- ///
- /// # Results
- ///
- /// * `DSM` - It implements the required initialization workflows for smart amps.
- pub fn new(
- snd_card: &str,
- num_channels: usize,
- rdc_to_ohm: fn(i32) -> f32,
- temp_upper_limit: f32,
- temp_lower_limit: f32,
- ) -> Self {
- Self {
- snd_card: snd_card.to_owned(),
- num_channels,
- rdc_to_ohm,
- temp_converter: TempConverter::default(),
- temp_upper_limit,
- temp_lower_limit,
- }
- }
-
- /// Sets self.temp_converter to the given temp_converter.
- ///
- /// # Arguments
- ///
- /// * `temp_converter` - the convert function to use.
- pub fn set_temp_converter(&mut self, temp_converter: TempConverter) {
- self.temp_converter = temp_converter;
- }
-
- /// Checks whether the speakers are overheated or not according to the previous shutdown time.
- /// The boot time calibration should be skipped when the speakers may be too hot
- /// and the Amp should use the previous calibration value returned by the
- /// SpeakerStatus::Hot(Vec<CalibData>).
- ///
- /// # Results
- ///
- /// * `SpeakerStatus::Cold` - which means the speakers are not overheated and the Amp can
- /// trigger the boot time calibration.
- /// * `SpeakerStatus::Hot(Vec<CalibData>)` - when the speakers may be too hot. The boot
- /// time calibration should be skipped and the Amp should use the previous calibration values
- /// returned by the enum.
- ///
- /// # Errors
- ///
- /// * The speakers are overheated and there are no previous calibration values stored.
- /// * Cannot determine whether the speakers are overheated as previous shutdown time record is
- /// invalid.
- pub fn check_speaker_over_heated_workflow(&self) -> Result<SpeakerStatus> {
- if self.is_first_boot() {
- return Ok(SpeakerStatus::Cold);
- }
- match self.is_speaker_over_heated() {
- Ok(overheated) => {
- if overheated {
- let calib: Vec<CalibData> = (0..self.num_channels)
- .map(|ch| -> Result<CalibData> { self.get_previous_calibration_value(ch) })
- .collect::<Result<Vec<CalibData>>>()?;
- info!("the speakers are hot, the boot time calibration should be skipped");
- return Ok(SpeakerStatus::Hot(calib));
- }
- Ok(SpeakerStatus::Cold)
- }
- Err(err) => {
- // We cannot assume the speakers are not replaced or not overheated
- // when the shutdown time file is invalid; therefore we can not use the datastore
- // value anymore and we can not trigger boot time calibration.
- for ch in 0..self.num_channels {
- if let Err(e) = Datastore::delete(&self.snd_card, ch) {
- error!("error delete datastore: {}", e);
- }
- }
- Err(err)
- }
- }
- }
-
- /// Decides a good calibration value and updates the stored value according to the following
- /// logic:
- /// * Returns the previous value if the ambient temperature is not within a valid range.
- /// * Returns Error::LargeCalibrationDiff if rdc difference is larger than
- /// `CALI_ERROR_UPPER_LIMIT`.
- /// * Returns the previous value if the rdc difference is smaller than `CALI_ERROR_LOWER_LIMIT`.
- /// * Returns the boot time calibration value and updates the datastore value if the rdc.
- /// difference is between `CALI_ERROR_UPPER_LIMIT` and `CALI_ERROR_LOWER_LIMIT`.
- ///
- /// # Arguments
- ///
- /// * `card` - `&Card`.
- /// * `channel` - `channel number`.
- /// * `calib_data` - `boot time calibrated data`.
- ///
- /// # Results
- ///
- /// * `CalibData` - the calibration data to be applied according to the deciding logic.
- ///
- /// # Errors
- ///
- /// * VPD does not exist.
- /// * rdc difference is larger than `CALI_ERROR_UPPER_LIMIT`.
- /// * Failed to update Datastore.
- pub fn decide_calibration_value_workflow(
- &self,
- channel: usize,
- calib_data: CalibData,
- ) -> Result<CalibData> {
- if calib_data.temp < self.temp_lower_limit || calib_data.temp > self.temp_upper_limit {
- info!("invalid temperature: {}.", calib_data.temp);
- return self
- .get_previous_calibration_value(channel)
- .map_err(|_| Error::InvalidTemperature(calib_data.temp));
- }
- let (datastore_exist, previous_calib) = match self.get_previous_calibration_value(channel) {
- Ok(previous_calib) => (true, previous_calib),
- Err(e) => {
- info!("{}, use vpd as previous calibration value", e);
- (false, self.get_vpd_calibration_value(channel)?)
- }
- };
-
- let diff = {
- let calib_rdc_ohm = (self.rdc_to_ohm)(calib_data.rdc);
- let previous_rdc_ohm = (self.rdc_to_ohm)(previous_calib.rdc);
- (calib_rdc_ohm - previous_rdc_ohm) / previous_rdc_ohm
- };
- if diff > Self::CALI_ERROR_UPPER_LIMIT {
- Err(Error::LargeCalibrationDiff(calib_data))
- } else if diff < Self::CALI_ERROR_LOWER_LIMIT {
- if !datastore_exist {
- Datastore::UseVPD.save(&self.snd_card, channel)?;
- }
- Ok(previous_calib)
- } else {
- Datastore::DSM {
- rdc: calib_data.rdc,
- temp: (self.temp_converter.celsius_to_vpd)(calib_data.temp),
- }
- .save(&self.snd_card, channel)?;
- Ok(calib_data)
- }
- }
-
- /// Gets the calibration values from vpd.
- ///
- /// # Results
- ///
- /// * `Vec<CalibData>` - the calibration values in vpd.
- ///
- /// # Errors
- ///
- /// * Failed to read vpd.
- pub fn get_all_vpd_calibration_value(&self) -> Result<Vec<CalibData>> {
- (0..self.num_channels)
- .map(|ch| self.get_vpd_calibration_value(ch))
- .collect::<Result<Vec<_>>>()
- }
-
- /// Blocks until the internal speakers are ready.
- ///
- /// # Errors
- ///
- /// * Failed to wait the internal speakers to be ready.
- pub fn wait_for_speakers_ready(&self) -> Result<()> {
- let find_speaker = || -> Result<()> {
- let cras_client = CrasClient::new().map_err(Error::CrasClientFailed)?;
- let _node = cras_client
- .output_nodes()
- .find(|node| node.node_type == CrasNodeType::CRAS_NODE_TYPE_INTERNAL_SPEAKER)
- .ok_or(Error::InternalSpeakerNotFound)?;
- Ok(())
- };
- // TODO(b/155007305): Implement cras_client.wait_node_change and use it here.
- const RETRY: usize = 3;
- const RETRY_INTERVAL: Duration = Duration::from_millis(500);
- for _ in 0..RETRY {
- match find_speaker() {
- Ok(_) => return Ok(()),
- Err(e) => error!("retry on finding speaker: {}", e),
- };
- thread::sleep(RETRY_INTERVAL);
- }
- Err(Error::InternalSpeakerNotFound)
- }
-
- fn is_first_boot(&self) -> bool {
- !run_time::exists(&self.snd_card)
- }
-
- // If (Current time - the latest CRAS shutdown time) < cool_down_time, we assume that
- // the speakers may be overheated.
- fn is_speaker_over_heated(&self) -> Result<bool> {
- let last_run = run_time::from_file(&self.snd_card)?;
- let last_shutdown = shutdown_time::from_file()?;
- if last_shutdown < last_run {
- return Err(Error::InvalidShutDownTime);
- }
-
- let now = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map_err(Error::SystemTimeError)?;
-
- let elapsed = now
- .checked_sub(last_shutdown)
- .ok_or(Error::InvalidShutDownTime)?;
-
- if elapsed < Self::SPEAKER_COOL_DOWN_TIME {
- return Ok(true);
- }
- Ok(false)
- }
-
- fn get_previous_calibration_value(&self, ch: usize) -> Result<CalibData> {
- let sci_calib = Datastore::from_file(&self.snd_card, ch)?;
- match sci_calib {
- Datastore::UseVPD => self.get_vpd_calibration_value(ch),
- Datastore::DSM { rdc, temp } => Ok(CalibData {
- rdc,
- temp: (self.temp_converter.vpd_to_celsius)(temp),
- }),
- }
- }
-
- fn get_vpd_calibration_value(&self, channel: usize) -> Result<CalibData> {
- let vpd = VPD::new(channel)?;
- Ok(CalibData {
- rdc: vpd.dsm_calib_r0,
- temp: (self.temp_converter.vpd_to_celsius)(vpd.dsm_calib_temp),
- })
- }
-}
diff --git a/sound_card_init/dsm/src/utils.rs b/sound_card_init/dsm/src/utils.rs
deleted file mode 100644
index 64f6c972..00000000
--- a/sound_card_init/dsm/src/utils.rs
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! It contains common utils shared within sound_card_init.
-#![deny(missing_docs)]
-
-use std::fs::File;
-use std::io::{prelude::*, BufReader, BufWriter};
-use std::path::PathBuf;
-use std::time::Duration;
-
-use crate::datastore::Datastore;
-use crate::error::{Error, Result};
-
-fn duration_from_file(path: &PathBuf) -> Result<Duration> {
- let reader =
- BufReader::new(File::open(&path).map_err(|e| Error::FileIOFailed(path.clone(), e))?);
- serde_yaml::from_reader(reader).map_err(|e| Error::SerdeError(path.clone(), e))
-}
-
-/// The utils to parse CRAS shutdown time file.
-pub mod shutdown_time {
- use super::*;
- // The path of CRAS shutdown time file.
- const SHUTDOWN_TIME_FILE: &str = "/var/lib/cras/stop";
-
- /// Reads the unix time from CRAS shutdown time file.
- pub fn from_file() -> Result<Duration> {
- duration_from_file(&PathBuf::from(SHUTDOWN_TIME_FILE))
- }
-}
-
-/// The utils to create and parse sound_card_init run time file.
-pub mod run_time {
- use std::time::SystemTime;
-
- use super::*;
- // The filename of sound_card_init run time file.
- const RUN_TIME_FILE: &str = "run";
-
- /// Returns the sound_card_init run time file existence.
- pub fn exists(snd_card: &str) -> bool {
- run_time_file(snd_card).exists()
- }
-
- /// Reads the unix time from sound_card_init run time file.
- pub fn from_file(snd_card: &str) -> Result<Duration> {
- duration_from_file(&run_time_file(snd_card))
- }
-
- /// Saves the current unix time to sound_card_init run time file.
- pub fn now_to_file(snd_card: &str) -> Result<()> {
- match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
- Ok(t) => to_file(snd_card, t),
- Err(e) => Err(Error::SystemTimeError(e)),
- }
- }
-
- /// Saves the unix time to sound_card_init run time file.
- pub fn to_file(snd_card: &str, duration: Duration) -> Result<()> {
- let path = run_time_file(snd_card);
- let mut writer =
- BufWriter::new(File::create(&path).map_err(|e| Error::FileIOFailed(path.clone(), e))?);
- writer
- .write_all(
- serde_yaml::to_string(&duration)
- .map_err(|e| Error::SerdeError(path.clone(), e))?
- .as_bytes(),
- )
- .map_err(|e| Error::FileIOFailed(path.clone(), e))?;
- writer
- .flush()
- .map_err(|e| Error::FileIOFailed(path.clone(), e))?;
- Ok(())
- }
-
- fn run_time_file(snd_card: &str) -> PathBuf {
- PathBuf::from(Datastore::DATASTORE_DIR)
- .join(snd_card)
- .join(RUN_TIME_FILE)
- }
-}
diff --git a/sound_card_init/dsm/src/vpd.rs b/sound_card_init/dsm/src/vpd.rs
deleted file mode 100644
index b00864cc..00000000
--- a/sound_card_init/dsm/src/vpd.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::fs::File;
-use std::io::prelude::*;
-use std::io::BufReader;
-use std::path::PathBuf;
-
-use crate::error::{Error, Result};
-
-const VPD_DIR: &str = "/sys/firmware/vpd/ro/vpdfile";
-
-/// `VPD`, which represents the amplifier factory calibration values.
-#[derive(Default, Debug)]
-pub struct VPD {
- pub dsm_calib_r0: i32,
- pub dsm_calib_temp: i32,
-}
-
-impl VPD {
- /// Creates a `VPD` and initializes its fields from VPD_DIR/dsm_calib_r0_{channel}.
- /// # Arguments
- ///
- /// * `channel` - channel number.
- pub fn new(channel: usize) -> Result<VPD> {
- let mut vpd: VPD = Default::default();
- vpd.dsm_calib_r0 = read_vpd_files(&format!("dsm_calib_r0_{}", channel))?;
- vpd.dsm_calib_temp = read_vpd_files(&format!("dsm_calib_temp_{}", channel))?;
- Ok(vpd)
- }
-}
-
-fn read_vpd_files(file: &str) -> Result<i32> {
- let path = PathBuf::from(VPD_DIR).with_file_name(file);
- let io_err = |e| Error::FileIOFailed(path.to_owned(), e);
- let mut reader = BufReader::new(File::open(&path).map_err(io_err)?);
- let mut line = String::new();
- reader.read_line(&mut line).map_err(io_err)?;
- line.parse::<i32>()
- .map_err(|e| Error::VPDParseFailed(path.to_string_lossy().to_string(), e))
-}
diff --git a/sound_card_init/dsm/src/zero_player.rs b/sound_card_init/dsm/src/zero_player.rs
deleted file mode 100644
index 441f7ffa..00000000
--- a/sound_card_init/dsm/src/zero_player.rs
+++ /dev/null
@@ -1,209 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-use std::io::Write;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Condvar, Mutex};
-use std::thread;
-use std::thread::JoinHandle;
-use std::time::Duration;
-
-use audio_streams::SampleFormat;
-use libcras::{CrasClient, CrasNodeType};
-use sys_util::error;
-
-use crate::error::{Error, Result};
-
-/// `ZeroPlayer` provides the functionality to play zeros sample in the background thread.
-#[derive(Default)]
-pub struct ZeroPlayer {
- thread_info: Option<PlayZeroWorkerInfo>,
-}
-
-impl Drop for ZeroPlayer {
- fn drop(&mut self) {
- if self.thread_info.is_some() {
- if let Err(e) = self.stop() {
- error!("{}", e);
- }
- }
- }
-}
-
-impl ZeroPlayer {
- /// It takes about 400 ms to get CRAS_NODE_TYPE_INTERNAL_SPEAKER during the boot time.
- const TIMEOUT: Duration = Duration::from_millis(1000);
-
- /// Returns whether the ZeroPlayer is running.
- pub fn running(&self) -> bool {
- self.thread_info.is_some()
- }
-
- /// Starts to play zeros for at most `max_playback_time`.
- /// This function blocks and returns until playback has started for `min_playback_time`.
- /// This function must be called when self.running() returns false.
- ///
- /// # Arguments
- ///
- /// * `min_playback_time` - It blocks and returns until playback has started for
- /// `min_playback_time`.
- ///
- /// # Errors
- ///
- /// * If it's called when the `ZeroPlayer` is already running.
- /// * Failed to find internal speakers.
- /// * Failed to start the background thread.
- pub fn start(&mut self, min_playback_time: Duration) -> Result<()> {
- if self.running() {
- return Err(Error::ZeroPlayerIsRunning);
- }
- self.thread_info = Some(PlayZeroWorkerInfo::new(min_playback_time));
- if let Some(thread_info) = &mut self.thread_info {
- // Block until playback of zeros has started for min_playback_time or timeout.
- let (lock, cvar) = &*(thread_info.ready);
- let result = cvar.wait_timeout_while(
- lock.lock()?,
- min_playback_time + ZeroPlayer::TIMEOUT,
- |&mut is_ready| !is_ready,
- )?;
- if result.1.timed_out() {
- return Err(Error::StartPlaybackTimeout);
- }
- }
- Ok(())
- }
-
- /// Stops playing zeros in the background thread.
- /// This function must be called when self.running() returns true.
- ///
- /// # Errors
- ///
- /// * If it's called again when the `ZeroPlayer` is not running.
- /// * Failed to play zeros to internal speakers via CRAS client.
- /// * Failed to join the background thread.
- pub fn stop(&mut self) -> Result<()> {
- match self.thread_info.take() {
- Some(mut thread_info) => Ok(thread_info.destroy()?),
- None => Err(Error::ZeroPlayerIsNotRunning),
- }
- }
-}
-
-// Audio thread book-keeping data
-struct PlayZeroWorkerInfo {
- thread: Option<JoinHandle<Result<()>>>,
- // Uses `thread_run` to notify the background thread to stop.
- thread_run: Arc<AtomicBool>,
- // The background thread uses `ready` to notify the main thread that playback
- // of zeros has started for min_playback_time.
- ready: Arc<(Mutex<bool>, Condvar)>,
-}
-
-impl Drop for PlayZeroWorkerInfo {
- fn drop(&mut self) {
- if let Err(e) = self.destroy() {
- error!("{}", e);
- }
- }
-}
-
-impl PlayZeroWorkerInfo {
- // Spawns the PlayZeroWorker.
- fn new(min_playback_time: Duration) -> Self {
- let thread_run = Arc::new(AtomicBool::new(false));
- let ready = Arc::new((Mutex::new(false), Condvar::new()));
- let mut worker = PlayZeroWorker::new(min_playback_time, thread_run.clone(), ready.clone());
- Self {
- thread: Some(thread::spawn(move || -> Result<()> {
- worker.run()?;
- Ok(())
- })),
- thread_run,
- ready,
- }
- }
-
- // Joins the PlayZeroWorker.
- fn destroy(&mut self) -> Result<()> {
- self.thread_run.store(false, Ordering::Relaxed);
- if let Some(handle) = self.thread.take() {
- let res = handle.join().map_err(Error::WorkerPanics)?;
- return match res {
- Err(e) => Err(e),
- Ok(_) => Ok(()),
- };
- }
- Ok(())
- }
-}
-
-struct PlayZeroWorker {
- min_playback_time: Duration,
- // Uses `thread_run` to notify the background thread to stop.
- thread_run: Arc<AtomicBool>,
- // The background thread uses `ready` to notify the main thread that playback
- // of zeros has started for min_playback_time.
- ready: Arc<(Mutex<bool>, Condvar)>,
-}
-
-impl PlayZeroWorker {
- const FRAMES_PER_BUFFER: usize = 256;
- const FRAME_RATE: u32 = 48000;
- const NUM_CHANNELS: usize = 2;
- const FORMAT: SampleFormat = SampleFormat::S16LE;
-
- fn new(
- min_playback_time: Duration,
- thread_run: Arc<AtomicBool>,
- ready: Arc<(Mutex<bool>, Condvar)>,
- ) -> Self {
- Self {
- min_playback_time,
- thread_run,
- ready,
- }
- }
-
- fn run(&mut self) -> Result<()> {
- let mut cras_client = CrasClient::new().map_err(Error::CrasClientFailed)?;
- // TODO(b/155007305): Implement cras_client.wait_node_change and use it here.
- let node = cras_client
- .output_nodes()
- .find(|node| node.node_type == CrasNodeType::CRAS_NODE_TYPE_INTERNAL_SPEAKER)
- .ok_or(Error::InternalSpeakerNotFound)?;
- let local_buffer =
- vec![0u8; Self::FRAMES_PER_BUFFER * Self::NUM_CHANNELS * Self::FORMAT.sample_bytes()];
- let min_playback_iterations = (Self::FRAME_RATE
- * self.min_playback_time.as_millis() as u32)
- / Self::FRAMES_PER_BUFFER as u32
- / 1000;
- let (_control, mut stream) = cras_client
- .new_pinned_playback_stream(
- node.iodev_index,
- Self::NUM_CHANNELS,
- Self::FORMAT,
- Self::FRAME_RATE,
- Self::FRAMES_PER_BUFFER,
- )
- .map_err(|e| Error::NewPlayStreamFailed(e))?;
-
- let mut iter = 0;
- self.thread_run.store(true, Ordering::Relaxed);
- while self.thread_run.load(Ordering::Relaxed) {
- let mut buffer = stream
- .next_playback_buffer()
- .map_err(|e| Error::NextPlaybackBufferFailed(e))?;
- let _write_frames = buffer.write(&local_buffer).map_err(Error::PlaybackFailed)?;
-
- // Notifies the main thread that playback of zeros has started for min_playback_time.
- if iter == min_playback_iterations {
- let (lock, cvar) = &*self.ready;
- let mut is_ready = lock.lock()?;
- *is_ready = true;
- cvar.notify_one();
- }
- iter += 1;
- }
- Ok(())
- }
-}
diff --git a/sound_card_init/seccomp/sound_card_init-seccomp-amd64.policy b/sound_card_init/seccomp/sound_card_init-seccomp-amd64.policy
deleted file mode 100644
index d06f225e..00000000
--- a/sound_card_init/seccomp/sound_card_init-seccomp-amd64.policy
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright 2020 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-access: 1
-arch_prctl: 1
-bind: 1
-brk: 1
-clone: 1
-close: 1
-connect: 1
-dup2: 1
-dup: 1
-epoll_create1: 1
-epoll_ctl: 1
-epoll_wait: 1
-execve: 1
-exit: 1
-exit_group: 1
-fcntl: 1
-fstat: 1
-futex: 1
-getcwd: 1
-getdents: 1
-getdents64: 1
-getegid: 1
-geteuid: 1
-getgid: 1
-getgroups: 1
-getpgid: 1
-getpgrp: 1
-getpid: 1
-getppid: 1
-getpriority: 1
-getrandom: 1
-getresgid: 1
-getresuid: 1
-getsid: 1
-getsockname: 1
-getuid: 1
-ioctl: arg1 == 0x5401 || arg1 == 0xc4c85512 || arg1 == 0x540f || arg1 == 0x80045500 || arg1 == 0xc4c85513 || arg1 == 0x81785501 || arg1 == 0x5413 || arg1 == 0xc1105511 || arg1 == 0x81785501 || arg1 == 0x80045500 || arg1 == 0xc008551a || arg1 == 0xc4c85512 || arg1 == 0xc008551b || arg1 == 0xc1105511
-lseek: 1
-madvise: 1
-mmap: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE
-mprotect: arg2 in ~PROT_EXEC || arg2 in ~PROT_WRITE
-munmap: 1
-nanosleep: 1
-clock_nanosleep: 1
-openat: 1
-pipe2: 1
-ppoll: 1
-prctl: arg0 == 0x3 || arg0 == 0x4
-prlimit64: 1
-read: 1
-recvfrom: 1
-recvmsg: 1
-restart_syscall: 1
-rt_sigaction: 1
-rt_sigprocmask: 1
-rt_sigreturn: 1
-sched_getaffinity: 1
-sched_yield: 1
-sendmsg: 1
-sendto: 1
-set_robust_list: 1
-set_tid_address: 1
-setgid: 1
-setgroups: 1
-setpriority: 1
-setresgid: 1
-setresuid: 1
-setuid: 1
-sigaltstack: 1
-socket: arg0 == 0x10 || arg0 == 0x1
-socketpair: 1
-stat: 1
-statx: 1
-umask: 1
-uname: 1
-unlink: 1
-wait4: 1
-write: 1
diff --git a/sound_card_init/sound_card_init.conf b/sound_card_init/sound_card_init.conf
deleted file mode 100644
index 40bc88f8..00000000
--- a/sound_card_init/sound_card_init.conf
+++ /dev/null
@@ -1,80 +0,0 @@
-# Copyright 2020 The Chromium OS Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# Installed by sound_card_init package.
-# sound_card_init upstart job.
-# sound_card_init is started by /lib/udev/rules.d/99-sound_card_init.rules
-
-description "Chrome OS sound card initializer"
-author "chromium-os-dev@chromium.org"
-
-# sound_card_init is a short-running process, but we don't start it as
-# a task job, because sound_card_init needs the sound card to be ready in
-# CRAS therefore we do not want to block the udev rule processing.
-
-# Make the task killable, because if it has a leak it's better to
-# restart it than to OOM-panic.
-oom score 0
-
-# SOUND_CARD_ID is provided by /lib/udev/rules.d/99-sound_card_init.rules.
-import SOUND_CARD_ID
-
-pre-start script
- if ! echo "${SOUND_CARD_ID}" | grep -Eq "^[a-zA-Z0-9]+$"; then
- logger -t "${UPSTART_JOB}" \
- "Invalid SOUND_CARD_ID supplied"
- exit 1
- else
- mkdir -m 0755 -p /var/lib/sound_card_init/"${SOUND_CARD_ID}"
- chown -R sound_card_init:sound_card_init /var/lib/sound_card_init
- fi
-end script
-
-
-script
- CONFIG="$(cros_config /audio/main sound-card-init-conf)"
- if [ -f /etc/sound_card_init/"${CONFIG}" ]; then
- # Here (in order) are a list of the args added:
- # --uts: Create and enter new UTS namespace (hostname/NIS domain name).
- # -e: doesn't need network access.
- # -l: process doesn't use SysV shared memory or IPC.
- # -N: doesn't need to modify control groups settings.
- # -v: run inside a new VFS namespace.
- # -p -r: process doesn't need to access other processes in the system.
- # -n: process doesn't need new privileges.
- # -P: set /mnt/empty as the root fs.
- # -b: bind /
- # -k: Get a writeable and empty /run tmpfs path.
- # -b: need /run/cras to connect cras.
- # -b: need /dev to send ioctls to the system's block devices.
- # -k: empty /sys tmpfs path.
- # -b: need /sys/firmware/vpd/ro/ access to read the default calibration
- # value in vpd.
- # -k: get a writeable and empty /var tmpfs path.
- # -b: need /var/lib/sound_card_init/$SOUND_CARD_ID writable access for
- # datastore update.
- # -b: need /var/lib/cras readable
- exec minijail0 \
- --uts \
- -e \
- -l \
- -N \
- -v \
- -p -r \
- -n \
- -P /mnt/empty \
- -b / \
- -k 'tmpfs,/run,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
- -b /run/cras \
- -b /dev \
- -k 'tmpfs,/sys,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
- -b /sys/firmware/vpd/ro/ \
- -k 'tmpfs,/var,tmpfs,MS_NODEV|MS_NOEXEC|MS_NOSUID,mode=755,size=10M' \
- -b /var/lib/sound_card_init/"${SOUND_CARD_ID}"/,,1 \
- -b /var/lib/cras/ \
- -u sound_card_init -g sound_card_init -G \
- -S /usr/share/policy/sound_card_init-seccomp.policy \
- /usr/bin/sound_card_init "--id=${SOUND_CARD_ID}" "--conf=${CONFIG}"
- fi
-end script \ No newline at end of file
diff --git a/sound_card_init/src/main.rs b/sound_card_init/src/main.rs
deleted file mode 100644
index 806b7d53..00000000
--- a/sound_card_init/src/main.rs
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2020 The Chromium OS Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//! `sound_card_init` is an user space binary to perform sound card initialization during boot time.
-//!
-//!
-//! # Arguments
-//!
-//! * `sound_card_id` - The sound card name, ex: sofcmlmax98390d.
-//!
-//! Given the `sound_card_id`, this binary parses the CONF_DIR/<sound_card_id>.yaml to perform per sound card initialization.
-//! The upstart job of `sound_card_init` is started by the udev event specified in /lib/udev/rules.d/99-sound_card_init.rules.
-#![deny(missing_docs)]
-use std::env;
-use std::error;
-use std::fmt;
-use std::process;
-use std::string::String;
-
-use getopts::Options;
-use remain::sorted;
-use sys_util::{error, info, syslog};
-
-use amp::AmpBuilder;
-use dsm::utils::run_time;
-
-type Result<T> = std::result::Result<T, Error>;
-
-#[derive(Default)]
-struct Args {
- pub sound_card_id: String,
- pub conf: String,
-}
-
-#[sorted]
-#[derive(Debug)]
-enum Error {
- MissingOption(String),
- ParseArgsFailed(getopts::Fail),
-}
-
-impl error::Error for Error {}
-
-impl fmt::Display for Error {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- use Error::*;
- match self {
- MissingOption(option) => write!(f, "missing required option: {}", option),
- ParseArgsFailed(e) => write!(f, "parse_args failed: {}", e),
- }
- }
-}
-
-fn print_usage(opts: &Options) {
- let brief = "Usage: sound_card_init [options]".to_owned();
- print!("{}", opts.usage(&brief));
-}
-
-fn parse_args() -> Result<Args> {
- let mut opts = Options::new();
- opts.optopt("", "id", "sound card id", "ID");
- opts.optopt(
- "",
- "conf",
- "the config file name. It should be $(cros_config /audio/main sound-card-init-conf)",
- "CONFIG_NAME",
- );
- opts.optflag("h", "help", "print help menu");
- let matches = opts
- .parse(&env::args().collect::<Vec<_>>()[1..])
- .map_err(|e| {
- print_usage(&opts);
- Error::ParseArgsFailed(e)
- })?;
-
- if matches.opt_present("h") {
- print_usage(&opts);
- process::exit(0);
- }
-
- let sound_card_id = matches
- .opt_str("id")
- .ok_or_else(|| Error::MissingOption("id".to_owned()))
- .map_err(|e| {
- print_usage(&opts);
- e
- })?;
-
- let conf = matches
- .opt_str("conf")
- .ok_or_else(|| Error::MissingOption("conf".to_owned()))
- .map_err(|e| {
- print_usage(&opts);
- e
- })?;
-
- Ok(Args {
- sound_card_id,
- conf,
- })
-}
-
-/// Parses the CONF_DIR/${args.conf}.yaml and starts the boot time calibration.
-fn sound_card_init(args: &Args) -> std::result::Result<(), Box<dyn error::Error>> {
- info!("sound_card_id: {}, conf:{}", args.sound_card_id, args.conf);
- AmpBuilder::new(&args.sound_card_id, &args.conf)
- .build()?
- .boot_time_calibration()?;
-
- Ok(())
-}
-
-fn main() {
- syslog::init().expect("failed to initialize syslog");
- let args = match parse_args() {
- Ok(args) => args,
- Err(e) => {
- error!("failed to parse arguments: {}", e);
- return;
- }
- };
-
- match sound_card_init(&args) {
- Ok(_) => info!("sound_card_init finished successfully."),
- Err(e) => error!("sound_card_init: {}", e),
- }
-
- if let Err(e) = run_time::now_to_file(&args.sound_card_id) {
- error!("failed to create sound_card_init run time file: {}", e);
- }
-}
diff --git a/ubsan_blocklist.txt b/ubsan_blocklist.txt
deleted file mode 100644
index 983b1a8d..00000000
--- a/ubsan_blocklist.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-# Suppress float devide-by-zero error in dsp.
-# https://crbug.com/965725
-[float-divide-by-zero]
-src:cras/src/dsp/drc_kernel.c
-fun:dk_update_envelope
diff --git a/ucm-config/for_all_boards/C505 HD Webcam/C505 HD Webcam.conf b/ucm-config/for_all_boards/C505 HD Webcam/C505 HD Webcam.conf
deleted file mode 100644
index 126ac331..00000000
--- a/ucm-config/for_all_boards/C505 HD Webcam/C505 HD Webcam.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Logitech Webcam C505"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/C505 HD Webcam/HiFi.conf b/ucm-config/for_all_boards/C505 HD Webcam/HiFi.conf
deleted file mode 100644
index c7e13426..00000000
--- a/ucm-config/for_all_boards/C505 HD Webcam/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:Webcam"
- cset "name='Mic Capture Volume' 0"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Webcam" {
- Value {
- CapturePCM "hw:Webcam,0"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
diff --git a/ucm-config/for_all_boards/Chat 150 C/Chat 150 C.conf b/ucm-config/for_all_boards/Chat 150 C/Chat 150 C.conf
deleted file mode 100644
index 329d5dc3..00000000
--- a/ucm-config/for_all_boards/Chat 150 C/Chat 150 C.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "ClearOne Chat 150C"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Chat 150 C/HiFi.conf b/ucm-config/for_all_boards/Chat 150 C/HiFi.conf
deleted file mode 100644
index 368796d7..00000000
--- a/ucm-config/for_all_boards/Chat 150 C/HiFi.conf
+++ /dev/null
@@ -1,19 +0,0 @@
-SectionVerb {
- Value {
- DisableSoftwareVolume "1"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Chat 150 C".0 {
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
diff --git a/ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/DELL PROFESSIONAL SOUND BAR AE5.conf b/ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/DELL PROFESSIONAL SOUND BAR AE5.conf
deleted file mode 100644
index e34c8135..00000000
--- a/ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/DELL PROFESSIONAL SOUND BAR AE5.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "DELL PROFESSIONAL SOUND BAR AE5"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/HiFi.conf b/ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/HiFi.conf
deleted file mode 100644
index 67bd2d52..00000000
--- a/ucm-config/for_all_boards/DELL PROFESSIONAL SOUND BAR AE5/HiFi.conf
+++ /dev/null
@@ -1,27 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Dell AE515 USB SoundBar Output".0 {
- Comment "SoundBar Output"
-
- Value {
- PlaybackPCM "hw:AE5,0"
- }
-}
-
-SectionDevice."Dell AE515 USB SoundBar Input".0 {
- Comment "SoundBar Input"
-
- Value {
- CapturePCM "hw:AE5,0"
- }
-}
diff --git a/ucm-config/for_all_boards/Dell AC511 USB SoundBar/Dell AC511 USB SoundBar.conf b/ucm-config/for_all_boards/Dell AC511 USB SoundBar/Dell AC511 USB SoundBar.conf
deleted file mode 100644
index 54913786..00000000
--- a/ucm-config/for_all_boards/Dell AC511 USB SoundBar/Dell AC511 USB SoundBar.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Dell AC511 USB SoundBar"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Dell AC511 USB SoundBar/HiFi.conf b/ucm-config/for_all_boards/Dell AC511 USB SoundBar/HiFi.conf
deleted file mode 100644
index e920e3c2..00000000
--- a/ucm-config/for_all_boards/Dell AC511 USB SoundBar/HiFi.conf
+++ /dev/null
@@ -1,30 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:SoundBar"
-
- cset "name='PCM Playback Volume' 51"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Dell AC511 USB SoundBar Output".0 {
- Comment "SoundBar Output"
-
- Value {
- PlaybackPCM "hw:SoundBar,0"
- }
-}
-
-SectionDevice."Dell AC511 USB SoundBar Input".0 {
- Comment "SoundBar Input"
-
- Value {
- CapturePCM "hw:SoundBar,0"
- }
-}
diff --git a/ucm-config/for_all_boards/Dell-WD15-Dock/Dell-WD15-Dock.conf b/ucm-config/for_all_boards/Dell-WD15-Dock/Dell-WD15-Dock.conf
deleted file mode 100644
index 290758a3..00000000
--- a/ucm-config/for_all_boards/Dell-WD15-Dock/Dell-WD15-Dock.conf
+++ /dev/null
@@ -1,5 +0,0 @@
-Comment "USB-audio on Dell docking station"
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Dell-WD15-Dock/HiFi.conf b/ucm-config/for_all_boards/Dell-WD15-Dock/HiFi.conf
deleted file mode 100644
index c522540f..00000000
--- a/ucm-config/for_all_boards/Dell-WD15-Dock/HiFi.conf
+++ /dev/null
@@ -1,40 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
- EnableSequence [
- cdev "hw:Dock"
- ]
- DisableSequence [
- ]
-}
-
-SectionDevice."Dock Headphone".0 {
- Comment "Headphone"
-
- Value {
- PlaybackPCM "hw:Dock,0"
- }
-}
-
-SectionDevice."Dock Line Out".0 {
- Value {
- PlaybackPCM "hw:Dock,1"
- }
- EnableSequence [
- cdev "hw:Dock"
- cset "name='Line Playback Switch' on"
- ]
- DisableSequence [
- cdev "hw:Dock"
- cset "name='Line Playback Switch' off"
- ]
-}
-
-SectionDevice."Dock Microphone".0 {
- Comment "Microphone"
-
- Value {
- CapturePCM "hw:Dock,0"
- }
-}
diff --git a/ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HUAWEI USB-C HEADSET.conf b/ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HUAWEI USB-C HEADSET.conf
deleted file mode 100644
index c1db5193..00000000
--- a/ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HUAWEI USB-C HEADSET.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "HUAWEI USB-C HEADSET"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HiFi.conf b/ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HiFi.conf
deleted file mode 100644
index d48942bf..00000000
--- a/ucm-config/for_all_boards/HUAWEI USB-C HEADSET/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:HEADSET"
- cset "name='PCM Playback Volume' 45"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."HUAWEI USB-C HEADSET Output".0 {
- Value {
- PlaybackPCM "hw:HEADSET,0"
- }
-}
-
-SectionDevice."HUAWEI USB-C HEADSET Input".0 {
- Value {
- CapturePCM "hw:HEADSET,0"
- }
-}
diff --git a/ucm-config/for_all_boards/Hangouts Meet speakermic/Hangouts Meet speakermic.conf b/ucm-config/for_all_boards/Hangouts Meet speakermic/Hangouts Meet speakermic.conf
deleted file mode 100644
index c114430e..00000000
--- a/ucm-config/for_all_boards/Hangouts Meet speakermic/Hangouts Meet speakermic.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Speakermic for Chrome for meeting"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Hangouts Meet speakermic/HiFi.conf b/ucm-config/for_all_boards/Hangouts Meet speakermic/HiFi.conf
deleted file mode 100644
index b84e696d..00000000
--- a/ucm-config/for_all_boards/Hangouts Meet speakermic/HiFi.conf
+++ /dev/null
@@ -1,8 +0,0 @@
-SectionVerb {
- Value {
- MinBufferLevel "0"
- }
-}
-
-SectionDevice."Headset".0 {
-}
diff --git a/ucm-config/for_all_boards/ICUSBAUDIO7D/HiFi.conf b/ucm-config/for_all_boards/ICUSBAUDIO7D/HiFi.conf
deleted file mode 100644
index c44de8dd..00000000
--- a/ucm-config/for_all_boards/ICUSBAUDIO7D/HiFi.conf
+++ /dev/null
@@ -1,132 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:ICUSBAUDIO7D"
-
- cset "name='Line Capture Switch', off"
- cset "name='Mic Capture Switch', off"
- cset "name='IEC958 In Capture Switch', off"
- cset "name='PCM Capture Switch', off"
- cset "name='Speaker Playback Switch', off"
- cset "name='Mic Playback Switch', off"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Speaker-Headset".0 {
- Comment "Speaker out"
-
- Value {
- PlaybackPCM "hw:ICUSBAUDIO7D,0"
- PlaybackMixerElem "Speaker"
- }
-
- EnableSequence [
- cset "name='Speaker Playback Switch', on"
- ]
-
- DisableSequence [
- cset "name='Speaker Playback Switch', off"
- ]
-}
-
-SectionDevice."Line In".0 {
- Comment "Line In"
-
- Value {
- CapturePCM "hw:ICUSBAUDIO7D,0"
- CaptureMixerElem "Line"
- }
-
- ConflictingDevice [
- "Mic"
- "SPDIF In"
- "PCM"
- ]
-
- EnableSequence [
- cset "name='Line Capture Switch', on"
- cset "name='PCM Capture Source', Line"
- ]
-
- DisableSequence [
- cset "name='Line Capture Switch', off"
- ]
-}
-
-SectionDevice."Mic".0 {
- Comment "Mic Input"
-
- Value {
- CapturePCM "hw:ICUSBAUDIO7D,0"
- CaptureMixerElem "Mic"
- }
-
- ConflictingDevice [
- "Line In"
- "SPDIF In"
- "PCM"
- ]
-
- EnableSequence [
- cset "name='Mic Capture Switch', on"
- cset "name='PCM Capture Source', Mic"
- ]
-
- DisableSequence [
- cset "name='Mic Capture Switch', off"
- ]
-}
-
-SectionDevice."SPDIF In".0 {
- Comment "S/PDIF In"
-
- Value {
- CapturePCM "hw:ICUSBAUDIO7D,0"
- CaptureMixerElem "IEC958 In"
- }
-
- ConflictingDevice [
- "Line In"
- "Mic"
- "PCM"
- ]
-
- EnableSequence [
- cset "name='IEC958 In Capture Switch', on"
- cset "name='PCM Capture Source', IEC958 In"
- ]
-
- DisableSequence [
- cset "name='IEC958 In Capture Switch', off"
- ]
-}
-
-SectionDevice."PCM".0 {
- Comment "PCM Capture"
-
- Value {
- CapturePCM "hw:ICUSBAUDIO7D,0"
- CaptureMixerElem "PCM"
- }
-
- ConflictingDevice [
- "Line In"
- "Mic"
- "SPDIF In"
- ]
-
- EnableSequence [
- cset "name='PCM Capture Switch', on"
- cset "name='PCM Capture Source', Mixer"
- ]
-
- DisableSequence [
- cset "name='PCM Capture Switch', off"
- ]
-}
diff --git a/ucm-config/for_all_boards/ICUSBAUDIO7D/ICUSBAUDIO7D.conf b/ucm-config/for_all_boards/ICUSBAUDIO7D/ICUSBAUDIO7D.conf
deleted file mode 100644
index 3dc10fa7..00000000
--- a/ucm-config/for_all_boards/ICUSBAUDIO7D/ICUSBAUDIO7D.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Startech USB 7D Audio"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Jabra SPEAK 810/HiFi.conf b/ucm-config/for_all_boards/Jabra SPEAK 810/HiFi.conf
deleted file mode 100644
index 313bffef..00000000
--- a/ucm-config/for_all_boards/Jabra SPEAK 810/HiFi.conf
+++ /dev/null
@@ -1,19 +0,0 @@
-SectionVerb {
- Value {
- DisableSoftwareVolume "1"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Jabra Speak 810".0 {
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
diff --git a/ucm-config/for_all_boards/Jabra SPEAK 810/Jabra SPEAK 810.conf b/ucm-config/for_all_boards/Jabra SPEAK 810/Jabra SPEAK 810.conf
deleted file mode 100644
index b8e817c2..00000000
--- a/ucm-config/for_all_boards/Jabra SPEAK 810/Jabra SPEAK 810.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Jabra Speak 810"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Logitech BRIO/HiFi.conf b/ucm-config/for_all_boards/Logitech BRIO/HiFi.conf
deleted file mode 100644
index eb20ee2d..00000000
--- a/ucm-config/for_all_boards/Logitech BRIO/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:BRIO"
- cset "name='Mic Capture Volume' 24"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."BRIO" {
- Value {
- CapturePCM "hw:BRIO,0"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
diff --git a/ucm-config/for_all_boards/Logitech BRIO/Logitech BRIO.conf b/ucm-config/for_all_boards/Logitech BRIO/Logitech BRIO.conf
deleted file mode 100644
index 7059edac..00000000
--- a/ucm-config/for_all_boards/Logitech BRIO/Logitech BRIO.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Logitech BRIO"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Logitech Webcam C930e/HiFi.conf b/ucm-config/for_all_boards/Logitech Webcam C930e/HiFi.conf
deleted file mode 100644
index 95f2fcf8..00000000
--- a/ucm-config/for_all_boards/Logitech Webcam C930e/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:C930e"
- cset "name='Mic Capture Volume' 30"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."C930e" {
- Value {
- CapturePCM "hw:C930e,0"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
diff --git a/ucm-config/for_all_boards/Logitech Webcam C930e/Logitech Webcam C930e.conf b/ucm-config/for_all_boards/Logitech Webcam C930e/Logitech Webcam C930e.conf
deleted file mode 100644
index f6760e2d..00000000
--- a/ucm-config/for_all_boards/Logitech Webcam C930e/Logitech Webcam C930e.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Logitech Webcam C930e"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Loopback/HiFi.conf b/ucm-config/for_all_boards/Loopback/HiFi.conf
deleted file mode 100644
index 254c9956..00000000
--- a/ucm-config/for_all_boards/Loopback/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Loopback Playback".0 {
- Value {
- PlaybackPCM "hw:Loopback,0"
- PlaybackChannels "8"
- }
-}
-
-SectionDevice."Loopback Capture".0 {
- Value {
- CapturePCM "hw:Loopback,1"
- CaptureChannels "8"
- }
-}
diff --git a/ucm-config/for_all_boards/Loopback/Loopback.conf b/ucm-config/for_all_boards/Loopback/Loopback.conf
deleted file mode 100644
index 44abedda..00000000
--- a/ucm-config/for_all_boards/Loopback/Loopback.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Loopback"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/HiFi.conf b/ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/HiFi.conf
deleted file mode 100644
index 9d63e16e..00000000
--- a/ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:TypeC"
- cset "name='PCM Playback Volume' 45"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Mi Earphones Output".0 {
- Value {
- PlaybackPCM "hw:TypeC,0"
- }
-}
-
-SectionDevice."Mi Earphones Input".0 {
- Value {
- CapturePCM "hw:TypeC,0"
- }
-}
diff --git a/ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/Mi Dual Driver Earphones Type-C.conf b/ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/Mi Dual Driver Earphones Type-C.conf
deleted file mode 100644
index df19b47b..00000000
--- a/ucm-config/for_all_boards/Mi Dual Driver Earphones Type-C/Mi Dual Driver Earphones Type-C.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Mi Dual Driver Earphones Type-C"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/PCP-USB/HiFi.conf b/ucm-config/for_all_boards/PCP-USB/HiFi.conf
deleted file mode 100644
index ac5c7ed7..00000000
--- a/ucm-config/for_all_boards/PCP-USB/HiFi.conf
+++ /dev/null
@@ -1,20 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:PCPUSB"
-
- cset "name='Mic Capture Volume' 19"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."PCP USB Input".0 {
- Value {
- CapturePCM "hw:PCPUSB,0"
- }
-}
diff --git a/ucm-config/for_all_boards/PCP-USB/PCP-USB.conf b/ucm-config/for_all_boards/PCP-USB/PCP-USB.conf
deleted file mode 100644
index b4689272..00000000
--- a/ucm-config/for_all_boards/PCP-USB/PCP-USB.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "PCP USB Stethoscope"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Pixel USB-C earbuds/HiFi.conf b/ucm-config/for_all_boards/Pixel USB-C earbuds/HiFi.conf
deleted file mode 100644
index 7a607456..00000000
--- a/ucm-config/for_all_boards/Pixel USB-C earbuds/HiFi.conf
+++ /dev/null
@@ -1,24 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Google Pixel earbuds Output".0 {
- Value {
- PlaybackPCM "hw:earbuds,0"
- }
-}
-
-SectionDevice."Google Pixel earbuds Input".0 {
- Value {
- CapturePCM "hw:earbuds,0"
- IntrinsicSensitivity "-3100"
- }
-}
diff --git a/ucm-config/for_all_boards/Pixel USB-C earbuds/Pixel USB-C earbuds.conf b/ucm-config/for_all_boards/Pixel USB-C earbuds/Pixel USB-C earbuds.conf
deleted file mode 100644
index 4166632c..00000000
--- a/ucm-config/for_all_boards/Pixel USB-C earbuds/Pixel USB-C earbuds.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Pixel USB-C earbuds"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Plantronics DA70/HiFi.conf b/ucm-config/for_all_boards/Plantronics DA70/HiFi.conf
deleted file mode 100644
index 0840b5d1..00000000
--- a/ucm-config/for_all_boards/Plantronics DA70/HiFi.conf
+++ /dev/null
@@ -1,28 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:SoundBar"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Plantronics DA70 Output".0 {
- Comment "DA70 Output"
-
- Value {
- PlaybackPCM "hw:DA70,0"
- }
-}
-
-SectionDevice."Plantronics DA70 Input".0 {
- Comment "DA70 Input"
-
- Value {
- CapturePCM "hw:DA70,0"
- }
-}
diff --git a/ucm-config/for_all_boards/Plantronics DA70/Plantronics DA70.conf b/ucm-config/for_all_boards/Plantronics DA70/Plantronics DA70.conf
deleted file mode 100644
index 7857d470..00000000
--- a/ucm-config/for_all_boards/Plantronics DA70/Plantronics DA70.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "Plantronics DA70"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Scarlett 2i2 USB/HiFi.conf b/ucm-config/for_all_boards/Scarlett 2i2 USB/HiFi.conf
deleted file mode 100644
index f49d6816..00000000
--- a/ucm-config/for_all_boards/Scarlett 2i2 USB/HiFi.conf
+++ /dev/null
@@ -1,27 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
- EnableSequence [
- cdev "hw:USB,0"
- ]
- DisableSequence [
- ]
-}
-
-SectionDevice."Scarlett 2i2 USB Output".0 {
- Comment "Scarlett 2i2 Output"
-
- Value {
- PlaybackPCM "hw:USB,0"
- PlaybackRate "48000"
- }
-}
-
-SectionDevice."Scarlett 2i2 USB Input".0 {
- Comment "Scarlett 2i2 Input"
- Value {
- CapturePCM "hw:USB,0"
- CaptureRate "48000"
- }
-}
diff --git a/ucm-config/for_all_boards/Scarlett 2i2 USB/Scarlett 2i2 USB.conf b/ucm-config/for_all_boards/Scarlett 2i2 USB/Scarlett 2i2 USB.conf
deleted file mode 100644
index 88bac6ba..00000000
--- a/ucm-config/for_all_boards/Scarlett 2i2 USB/Scarlett 2i2 USB.conf
+++ /dev/null
@@ -1,5 +0,0 @@
-Comment "Scarlett 2i2 USB"
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/Scarlett 2i4 USB/HiFi.conf b/ucm-config/for_all_boards/Scarlett 2i4 USB/HiFi.conf
deleted file mode 100644
index 894683cd..00000000
--- a/ucm-config/for_all_boards/Scarlett 2i4 USB/HiFi.conf
+++ /dev/null
@@ -1,27 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
- EnableSequence [
- cdev "hw:USB,0"
- ]
- DisableSequence [
- ]
-}
-
-SectionDevice."Scarlett 2i4 USB Output".0 {
- Comment "Scarlett 2i4 Output"
-
- Value {
- PlaybackPCM "hw:USB,0"
- PlaybackRate "48000"
- }
-}
-
-SectionDevice."Scarlett 2i4 USB Input".0 {
- Comment "Scarlett 2i4 Input"
- Value {
- CapturePCM "hw:USB,0"
- CaptureRate "48000"
- }
-}
diff --git a/ucm-config/for_all_boards/Scarlett 2i4 USB/Scarlett 2i4 USB.conf b/ucm-config/for_all_boards/Scarlett 2i4 USB/Scarlett 2i4 USB.conf
deleted file mode 100644
index 71ea1696..00000000
--- a/ucm-config/for_all_boards/Scarlett 2i4 USB/Scarlett 2i4 USB.conf
+++ /dev/null
@@ -1,5 +0,0 @@
-Comment "Scarlett 2i4 USB"
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/USB 2.0 Camera/HiFi.conf b/ucm-config/for_all_boards/USB 2.0 Camera/HiFi.conf
deleted file mode 100644
index e4121da1..00000000
--- a/ucm-config/for_all_boards/USB 2.0 Camera/HiFi.conf
+++ /dev/null
@@ -1,25 +0,0 @@
-SectionVerb {
- Value {
- FullySpecifiedUCM "1"
- }
-
- EnableSequence [
- cdev "hw:Camera"
- cset "name='Mic Capture Volume' 200"
- ]
-
- DisableSequence [
- ]
-}
-
-SectionDevice."Camera" {
- Value {
- CapturePCM "hw:Camera,0"
- }
-
- EnableSequence [
- ]
-
- DisableSequence [
- ]
-}
diff --git a/ucm-config/for_all_boards/USB 2.0 Camera/USB 2.0 Camera b/ucm-config/for_all_boards/USB 2.0 Camera/USB 2.0 Camera
deleted file mode 100644
index 52bd294a..00000000
--- a/ucm-config/for_all_boards/USB 2.0 Camera/USB 2.0 Camera
+++ /dev/null
@@ -1,6 +0,0 @@
-Comment "ZIQIAN N21 1080P Webcam"
-
-SectionUseCase."HiFi" {
- File "HiFi.conf"
- Comment "Default"
-}
diff --git a/ucm-config/for_all_boards/WD15 Dock b/ucm-config/for_all_boards/WD15 Dock
deleted file mode 120000
index 0d69a72f..00000000
--- a/ucm-config/for_all_boards/WD15 Dock
+++ /dev/null
@@ -1 +0,0 @@
-Dell-WD15-Dock \ No newline at end of file
diff --git a/ucm-config/for_all_boards/WD19 Dock b/ucm-config/for_all_boards/WD19 Dock
deleted file mode 120000
index 0d69a72f..00000000
--- a/ucm-config/for_all_boards/WD19 Dock
+++ /dev/null
@@ -1 +0,0 @@
-Dell-WD15-Dock \ No newline at end of file
diff --git a/unblocked_terms.txt b/unblocked_terms.txt
deleted file mode 100644
index cba7545a..00000000
--- a/unblocked_terms.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-# KEEP THIS COMMENT IN YOUR COPY.
-#
-# Don't delete this file if you want to keep keyword_check enabled even if it's
-# empty.
-#
-# See repohooks/README.md for more details.
-
-master
-\bnative
-white.?list