summaryrefslogtreecommitdiffstats
path: root/perl-install/harddrake/sound.pm
blob: 4c2e41ab04cdb1c37520ff9a870c09edc4e771a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package harddrake::sound;

# 2023-03-18 ghibo: cleanup against perl_checker
# 2023-03-18 anaselli: add reboot requester
# 2023-03-17 ghibo: stop also wireplumber in disable_all_pipewire
# 2023-03-17 ghibo: stop pulseaudio with the running user
# 2023-03-17 anaselli: suspend pipewire before configuring pulseaudio
# 2023-03-13 ghibo: added {start|stop}_{pipewire,wireplumber,pipewire-media-session}(), _pidof_pid(); _user_pid()
# 2023-03-13 ghibo: use rooted_get_stdout instead of get_stdout
# 2023-03-11 Angelo Naselli: added pipewire support
#
#
# TODO: 
#    o ensure sound is not user (either dsp/midi/sequencer/mixer)
#    o fix sound/alsa services

use strict;
use common;
use run_program;
use modules;
use list_modules;
use detect_devices;
use log;

sub is_pulseaudio_enabled() {
    my $soundprofile = common::read_alternative('soundprofile');
    $soundprofile =~ /pulse$/;
}

sub set_pulseaudio {
    my ($val) = @_;

    my $alterative = '/etc/sound/profiles/' . ($val ? 'pulse' : 'alsa');
    return if ! -d $alterative;

    common::symlinkf_update_alternatives('soundprofile', $alterative);

    # (cg) This config file will eventually be dropped, but it is still needed for now
    # as several packages/patches depend on it.
    my $config_file = "$::prefix/etc/sysconfig/pulseaudio";
    $val = 'PULSE_SERVER_TYPE=' . ($val ? 'personal' : 'none') . "\n";
    my $done;
    substInFile {
        if (/^PULSE_SERVER_TYPE=/) {
            $_ = $val;
            $done = 1;
        }
    } $config_file;
    append_to_file($config_file, $val) if !$done;
}


my $pa_startup_scriptfile = "$::prefix/etc/pulse/default.pa";

sub is_pulseaudio_glitchfree_enabled() {
    return -f $pa_startup_scriptfile &&
      cat_($pa_startup_scriptfile) !~ /^load-module\s+module-(udev|hal)-detect\s+tsched=0/m;
}

sub set_pulseaudio_glitchfree {
    my ($val) = @_;

    return if ! -f $pa_startup_scriptfile;

    substInFile {
        if ($val) {
            s/^(load-module\s+module-(udev|hal)-detect)\s+tsched=0/$1/;
        } else {
            s/^(load-module\s+module-(udev|hal)-detect).*/$1 tsched=0/;
        }
    } $pa_startup_scriptfile;
}

sub rooted {
    run_program::rooted($::prefix, @_);
}

sub unload { modules::unload(@_) if $::isStandalone }

sub load { 
    my ($modules_conf, $name) = @_;
    modules::load_and_configure($modules_conf, $name) if $::isStandalone;
}

sub _pidof {
    my ($name) = @_;
    rooted('/usr/bin/pidof', $name);
}

# return the pid of a running command
sub _pidof_pid {
    my ($name) = @_;
    my ($pid) = chomp_(run_program::rooted_get_stdout($::prefix, '/usr/bin/pidof', $name));

    return $pid;
}

# return the username of a running command
sub _user_pid {
    my ($name) = @_;
    my ($pid) = _pidof_pid($name);
    my $user;

    if ($pid) {
        ($user) = chomp_(run_program::rooted_get_stdout($::prefix, '/usr/bin/ps', '-o', 'uname=', '-p', $pid));
    }

    return $user;
}

# stop pulseaudio for the running user
sub stop_pulseaudio {
    my ($pulseaudio_user) = _user_pid('/usr/bin/pulseaudio');

    if ($pulseaudio_user) {
        if (-x '/usr/bin/pulseaudio') {
            rooted('/usr/bin/su', '-l', $pulseaudio_user, '-c', '/usr/bin/pulseaudio --kill');
        }
    }

    # try stopping again (in case the /usr/bin/pulseaudio process is still running, but the executable no longer available)
    my ($pulseaudio_user) = _user_pid('/usr/bin/pulseaudio');
    if ($pulseaudio_user) {
        my ($pulseaudio_pid) = _pidof_pid('/usr/bin/pulseaudio');
        if ($pulseaudio_pid) {
            rooted('/usr/bin/su', '-l', $pulseaudio_user, '-c', '/usr/bin/kill -TERM ' . $pulseaudio_pid);
        }
    }
    return $pulseaudio_user;
}

# stop pipewire services for the running user
sub stop_pipewire {
    my ($pipewire_user) = _user_pid('/usr/bin/pipewire');

    if ($pipewire_user) {
        rooted('/usr/bin/systemctl', '--machine=' . $pipewire_user . '@.host', '--user', 'stop', 'pipewire-pulse.service', 'pipewire-pulse.socket', 'pipewire.service', 'pipewire.socket');
    }

    return $pipewire_user;
}

# start pulseaudio for the specified user
sub start_pulseaudio {
    my ($pulseaudio_user) = @_;

    if ($pulseaudio_user) {
        rooted('/usr/bin/su', '-l', $pulseaudio_user, '-c', '/usr/bin/pulseaudio --start');
    }
}

# start pipewire services for the specified user
sub start_pipewire {
    my ($pipewire_user) = @_;

    if ($pipewire_user) {
        rooted('/usr/bin/systemctl', '--machine=' . $pipewire_user . '@.host', '--user', 'start', 'pipewire.socket', 'pipewire.service', 'pipewire-pulse.socket', 'pipewire-pulse.service');
    }
}

# stop wireplumber services for the running user
sub stop_wireplumber {
    my ($pipewire_user) = _user_pid('/usr/bin/wireplumber');

    if ($pipewire_user) {
        rooted('/usr/bin/systemctl', '--machine=' . $pipewire_user . '@.host', '--user', 'stop', 'wireplumber.service');
    }

    return $pipewire_user;
}

# start wireplumber
sub start_wireplumber {
    my ($pipewire_user) = @_;

    if ($pipewire_user) {
         rooted('/usr/bin/systemctl', '--machine=' . $pipewire_user . '@.host', '--user', 'start', 'wireplumber.service');
    }
}

# stop pipewire-media-session services for the running user
sub stop_pipewire_media_session {
    my ($pipewire_user) = _user_pid('/usr/bin/pipewire-media-session');

    if ($pipewire_user) {
        rooted('/usr/bin/systemctl', '--machine=' . $pipewire_user . '@.host', '--user', 'stop', 'pipewire-media-session.service');
    }

    return $pipewire_user;
}

# start pipewire-media-session services for the specified user
sub start_pipewire_media_session {
    my ($pipewire_user) = @_;

    if ($pipewire_user) {
        rooted('/usr/bin/systemctl', '--machine=' . $pipewire_user . '@.host', '--user', 'start', 'pipewire-media-session.service');
    }
}

sub configure_pipewire_wireplumber {
    my ($in) = @_;
    my ($pipewire_wp_user);

    # preserve pulseaudio user
    my ($pulseaudio_user) = _user_pid('/usr/bin/pulseaudio');

    # stop pipewire and pipewire-media-session services (if any) before removing any packages
    # and preserve pipewire-media-session user
    $pipewire_wp_user = stop_pipewire_media_session();
    stop_pipewire();

    my $required_installed = $in->do_pkgs->ensure_are_installed(
        ['task-pipewire',
        'wireplumber',
        'pavucontrol']
    );

    if (!$required_installed)
    {
        $in->ask_warn(N("Couldn't install the required packages"),
                      N("Please check the repositories are correctly configured")
        );
        return;
    }

    set_pulseaudio(0);

    # first of all disabling what has to be disabled to avoid conflicts
    if ($in->do_pkgs->is_installed('pipewire-media-session')) {
        rooted('/usr/bin/systemctl', '--global', 'disable', 'pipewire-media-session.service');
    }

    if ($in->do_pkgs->is_installed('pipewire')) {
        foreach ('pipewire.socket', 'pipewire.service') {
            rooted('/usr/bin/systemctl', '--global', 'enable', $_);
        }
    }

    if ($in->do_pkgs->is_installed('pipewire-pulseaudio')) {
        foreach ('pipewire-pulse.socket', 'pipewire-pulse.service') {
            rooted('/usr/bin/systemctl', '--global', 'enable', $_);
        }
    }

    if ($in->do_pkgs->is_installed('wireplumber')) {
        rooted('/usr/bin/systemctl', '--global', 'enable', 'wireplumber.service');
    }


    # stop pulseaudio process if still floating after the switch
    stop_pulseaudio();

    if ($pulseaudio_user) {
    # restart pipewire and wireplumber with the same user as initial pulseaudio
        start_pipewire($pulseaudio_user);
        start_wireplumber($pulseaudio_user);
    }
    else {
        if ($pipewire_wp_user) {
        # restart pipewire and wireplumber with the same user as pipewire-media-session
            start_pipewire($pipewire_wp_user);
            start_wireplumber($pipewire_wp_user);
        }
    }

    #Plasma tricks
    if ($in->do_pkgs->is_installed('plasma-desktop')) {
        $in->do_pkgs->ensure_are_installed(
            [ 'pavucontrol-qt',
              'kpipewire' ]
        );
    }
}

sub configure_pipewire_media_session {
    my ($in) = @_;
    my ($pipewire_ms_user);

    # preserve pulseaudio user
    my ($pulseaudio_user) = _user_pid('/usr/bin/pulseaudio');

    # stop pipewire and wireplumber services (if any) before removing any package
    # and preserve wireplumber user
    $pipewire_ms_user = stop_wireplumber();
    stop_pipewire();


    my $required_installed = $in->do_pkgs->ensure_are_installed(
        ['task-pipewire',
        'pipewire-media-session',
        'pavucontrol']
    );

    if (!$required_installed)
    {
        $in->ask_warn(N("Couldn't install the required packages"),
                      N("Please check the repositories are correctly configured")
        );
        return;
    }

    set_pulseaudio(0);

    # first of all disabling what has to be disabled to avoid conflicts
    if ($in->do_pkgs->is_installed('wireplumber')) {
        rooted('/usr/bin/systemctl', '--global', 'disable', 'wireplumber.service');
    }

    if ($in->do_pkgs->is_installed('pipewire')) {
        foreach ('pipewire.socket', 'pipewire.service') {
            rooted('/usr/bin/systemctl', '--global', 'enable', $_);
        }
    }

    if ($in->do_pkgs->is_installed('pipewire-pulseaudio')) {
        foreach ('pipewire-pulse.socket', 'pipewire-pulse.service') {
            rooted('/usr/bin/systemctl', '--global', 'enable', $_);
        }
    }

    if ($in->do_pkgs->is_installed('pipewire-media-session')) {
        rooted('/usr/bin/systemctl', '--global', 'enable', 'pipewire-media-session.service');
    }

    # stop pulseaudio process if still floating after the switch
    stop_pulseaudio();

    if ($pulseaudio_user) {
    # restart pipewire and wireplumber with the same user as initial pulseaudio
        start_pipewire($pulseaudio_user);
        start_pipewire_media_session($pulseaudio_user);
    }
    else {
        if ($pipewire_ms_user) {
        # restart pipewire and wireplumber with the same user as pipewire-media-session
            start_pipewire($pipewire_ms_user);
            start_pipewire_media_session($pipewire_ms_user);
        }
    }

    #Plasma tricks
    if ($in->do_pkgs->is_installed('plasma-desktop')) {
        $in->do_pkgs->ensure_are_installed(
            [ 'pavucontrol-qt',
              'kpipewire' ]
        );
    }
}

sub disable_all_pipewire {
    my ($in) = @_;

    if ($in->do_pkgs->is_installed('wireplumber')) {
        rooted('/usr/bin/systemctl', '--global', 'disable', 'wireplumber.service');
    }

    if ($in->do_pkgs->is_installed('pipewire')) {
        foreach ('pipewire.socket', 'pipewire.service') {
            rooted('/usr/bin/systemctl', '--global', 'disable', $_);
        }
    }

    if ($in->do_pkgs->is_installed('pipewire-pulseaudio')) {
        foreach ('pipewire-pulse.socket', 'pipewire-pulse.service') {
            rooted('/usr/bin/systemctl', '--global', 'disable', $_);
        }
    }

    if ($in->do_pkgs->is_installed('pipewire-media-session')) {
        rooted('/usr/bin/systemctl', '--global', 'disable', 'pipewire-media-session.service');
    }
}

sub configure_pulseaudio {
    my ($in) = @_;

    # preserve pipewire running user
    my ($pipewire_user) = _user_pid('/usr/bin/pipewire');

    # stop pipewire, wireplumber and pipewire-media-session services (if any) before removing any packages
    my ($wireplumber_user) = stop_wireplumber();
    my ($pipewire_media_session_user) = stop_pipewire_media_session();
    my ($pipewire_user_preserve) = stop_pipewire();

    # now packages
    $in->do_pkgs->remove('pipewire-alsa');

    my $required_installed = $in->do_pkgs->ensure_are_installed(
        ['task-pulseaudio',
        'pavucontrol']
    );

    if (!$required_installed)
    {
        $in->ask_warn(N("Couldn't install the required packages"),
                      N("Please check the repositories are correctly configured")
        );

        # restore previous pipewire (if any) processes if something goes wrong with pulseaudio installation
        if ($pipewire_user_preserve) {
            start_pipewire($pipewire_user_preserve);
        }

        if ($wireplumber_user) {
            start_wireplumber($wireplumber_user);
        }

        if ($pipewire_media_session_user) {
            start_pipewire_media_session($pipewire_media_session_user);
        }

        return;
    }


    # disable all the pipewire stuff before managing packages
    disable_all_pipewire($in);

    #Plasma tricks
    if ($in->do_pkgs->is_installed('plasma-desktop')) {
        $in->do_pkgs->ensure_is_installed('pavucontrol-qt');
    }

    # start pulseaudio with same pipewire preserved user
    if ($pipewire_user) {
        start_pulseaudio($pipewire_user);
    }
}

sub config {
    my ($in, $modules_conf, $device) = @_;
    my $driver = $device->{current_driver} || $device->{driver};

    my @alternative = $driver ne $device->{driver} ? $device->{driver} : ();
    if ($driver eq "unknown") {
        $in->ask_warn(N("No known driver"),
                      N("There's no known driver for your sound card (%s)",
                        $device->{description}));
    } else {
        push @alternative, $driver;
        my %des = modules::category2modules_and_description('multimedia/sound');
        
        my $is_pulseaudio_installed = -f $pa_startup_scriptfile && -d '/etc/sound/profiles/pulse';
        my $is_pulseaudio_enabled_val = is_pulseaudio_enabled();
        my $is_pulseaudio_glitchfree_enabled_val = is_pulseaudio_glitchfree_enabled();

        my $audiosystem = 'None';
        if ($is_pulseaudio_enabled_val && $is_pulseaudio_glitchfree_enabled_val) {
            $audiosystem = 'PulseAudioGF';
        } elsif ($is_pulseaudio_enabled_val) {
            $audiosystem = 'PulseAudio';
        } elsif (_pidof('/usr/bin/wireplumber')) {
            $audiosystem = 'PipeWireWP';
        } elsif (_pidof('/usr/bin/pipewire-media-session')) {
            $audiosystem = 'PipeWireMS';
        }

        my $write_config = sub {
            if ($audiosystem eq 'None') {
            #### ALSA alone
                disable_all_pipewire($in);
                set_pulseaudio(0);
                set_pulseaudio_glitchfree(0);
                # TODO check if adding autospawn = no to /etc/pulse/client.conf is needed
            } elsif ($audiosystem eq 'PulseAudio') {
            #### PulseAudio
                configure_pulseaudio($in);
                set_pulseaudio(1);
                set_pulseaudio_glitchfree(0);
                my $lib = get_libdir();
                $in->do_pkgs->ensure_is_installed($lib . 'alsa-plugins-pulseaudio',
                                                  '/usr/' . $lib . '/alsa-lib/libasound_module_pcm_pulse.so');
            } elsif ($audiosystem eq 'PulseAudioGF') {
            #### PulseAudio with Glitch-Free mode
                configure_pulseaudio($in);
                set_pulseaudio(1);
                set_pulseaudio_glitchfree(1);
                my $lib = get_libdir();
                $in->do_pkgs->ensure_is_installed($lib . 'alsa-plugins-pulseaudio',
                                                  '/usr/' . $lib . '/alsa-lib/libasound_module_pcm_pulse.so');
            } elsif ($audiosystem eq 'PipeWireWP') {
            #### PipeWire with WirePlumber
                configure_pipewire_wireplumber($in);
            } elsif ($audiosystem eq 'PipeWireMS') {
            #### PipeWire with PipeWire Media Session
                configure_pipewire_media_session($in);
            } else {
            #### Unmanaged value
                #TODO Error here
            }

            $in->ask_warn('', N("You need to reboot for changes to take effect"));

        };

        my @common = (
            {
                label => N("Select the sound server"),
                title => 1,
            },
            {
                val => \$audiosystem,
                list => [
                    'None',
                    'PulseAudio',
                    'PulseAudioGF',
                    'PipeWireWP',
                    'PipeWireMS',
                ],
                format => sub {
                    my ($choice) = @_;
                    +{
                        'None' => N("None"),
                        'PulseAudio' => N("PulseAudio"),
                        'PulseAudioGF' => N("PulseAudio with Glitch-Free mode"),
                        'PipeWireWP' => N("PipeWire with WirePlumber"),
                        'PipeWireMS' => N("PipeWire with PipeWire Media Session"),
                    }->{$choice};
                },
                type => 'list',
            },
            {
                advanced => 1,
                val => N("Reset sound mixer to default values"),
                clicked => sub { run_program::run('reset_sound') }
            },
            {
                val => N("Troubleshooting"), disabled => sub {},
                clicked => sub { &trouble($in) }
            },
        );

        if ($driver eq 'unknown') {
            if ($in->ask_from_({
                title => N("No alternative driver"),
                messages => N("There's no known OSS/ALSA alternative driver for your sound card (%s) which currently uses \"%s\"",
                              $device->{description}, $driver),
                          },
                          \@common,
                           )) {
                $write_config->();
            }
        } elsif ($in->ask_from_({ title => N("Sound configuration"),
                                  interactive_help_id => 'soundConfig',
                                  messages => 
				    $device->{description} .
				  "\n\n" . N("Your card uses the \"%s\" driver", $driver),
				},
                               \@common,
                                ))
        {
            $write_config->();
        }
    }
}

sub trouble {
    my ($in) = @_;
    $in->ask_warn(N("Sound troubleshooting"),
                  formatAlaTeX(
                               #-PO: keep the double empty lines between sections, this is formatted a la LaTeX
                               N("Below are some basic tips to help debug audio problems, but for accurate and up-to-date tips and tricks, please see:

https://wiki.mageia.org/en/Support:DebuggingSoundProblems



- General Recommendation: Enable PulseAudio. If you have opted to not to use PulseAudio, we would strongly advise you enable it. For the vast majority of desktop use cases, PulseAudio is the recommended and best supported option.



- \"kmix\" (KDE), \"gnome-control-center sound\" (GNOME) and \"pavucontrol\" (generic) will launch graphical applications to allow you to view your sound devices and adjust volume levels


- \"ps aux | grep pulseaudio\" will check that PulseAudio is running.


- \"pactl stat\" will check that you can connect to the PulseAudio daemon correctly.


- \"pactl list sink-inputs\" will tell you which programs are currently playing sound via PulseAudio.


- \"systemctl status osspd.service\" will tell you the current state of the OSS Proxy Daemon. This is used to enable sound from legacy applications which use the OSS sound API. You should install the \"ossp\" package if you need this functionality.


- \"pacmd ls\" will give you a LOT of debug information about the current state of your audio.


- \"lspcidrake -v | grep -i audio\" will tell you which low-level driver your card uses by default.


- \"/usr/sbin/lsmod | grep snd\" will enable you to check which sound related kernel modules (drivers) are loaded.


- \"alsamixer -c 0\" will give you a text-based mixer to the low level ALSA mixer controls for first sound card


- \"/usr/sbin/fuser -v /dev/snd/pcm* /dev/dsp\" will tell which programs are currently using the sound card directly (normally this should only show PulseAudio)
")));
}

sub configure_one_sound_slot {
    my ($modules_conf, $index, $driver) = @_;
    $modules_conf->set_sound_slot("sound-slot-$index", $driver);
    $modules_conf->set_options($driver, "xbox=1") if $driver eq "snd_intel8x0" && detect_devices::is_xbox();
    $modules_conf->set_options('snd-ac97-codec', "power_save=1") if $driver =~ /^snd/ && detect_devices::isLaptop();
}

sub configure_sound_slots {
    my ($modules_conf) = @_;
    my $altered = 0;
    each_index {
        my $default_driver = $modules_conf->get_alias("sound-slot-$::i");
        if (!member($default_driver, $_->{driver})) {
            $altered ||= $default_driver;
            configure_one_sound_slot($modules_conf, $::i, $_->{driver});
        }
    } detect_devices::getSoundDevices();
    $modules_conf->write if $altered && $::isStandalone;
}


1;