aboutsummaryrefslogtreecommitdiff
path: root/src/qmmpui/playlistparser.cpp
blob: 083cb35d4c95f316056ba7b2282471e95bf06309 (plain) (blame)
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
/***************************************************************************
 *   Copyright (C) 2008-2014 by Ilya Kotov                                 *
 *   forkotov02@hotmail.ru                                                 *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QPluginLoader>
#include <QRegExp>
#include <QList>
#include <QDir>
#include <QApplication>
#include <QTextStream>
#include <qmmp/qmmp.h>
#include "playlistformat.h"
#include "playlistparser.h"

QList<PlayListFormat*> *PlayListParser::m_formats = 0;

QList<PlayListFormat *> PlayListParser::formats()
{
    checkFormats();
    return *m_formats;
}

QStringList PlayListParser::nameFilters()
{
    checkFormats();
    QStringList filters;
    foreach(PlayListFormat* format, *m_formats)
    {
        filters << format->properties().filters;
    }
    return filters;
}

PlayListFormat *PlayListParser::findByMime(const QString &mime)
{
    checkFormats();
    foreach(PlayListFormat* format, *m_formats)
    {
        if(format->properties().contentTypes.contains(mime))
            return format;
    }
    return 0;
}

PlayListFormat *PlayListParser::findByPath(const QString &filePath)
{
    checkFormats();
    foreach(PlayListFormat* format, *m_formats)
    {
        foreach(QString filter, format->properties().filters)
        {
            QRegExp r(filter, Qt::CaseInsensitive, QRegExp::Wildcard);
            if(r.exactMatch(filePath))
                return format;
        }
    }
    return 0;
}

PlayListFormat *PlayListParser::findByUrl(const QUrl &url)
{
    QString path = url.encodedPath();
    return findByPath(path);
}

void PlayListParser::savePlayList(QList<PlayListTrack *> tracks, const QString &f_name)
{
    if(tracks.isEmpty())
        return;
    PlayListFormat* prs = PlayListParser::findByPath(f_name);
    if (!prs)
        return;
    QFile file(f_name);
    if (file.open(QIODevice::WriteOnly))
    {
        QTextStream ts(&file);
        ts << prs->encode(tracks);
        file.close();
    }
    else
        qWarning("PlayListParser: unable to save playlist, error: %s", qPrintable(file.errorString()));
}

QStringList PlayListParser::loadPlaylist(const QString &f_name)
{
    QStringList list;
    if(!QFile::exists(f_name))
        return list;
    PlayListFormat* prs = PlayListParser::findByPath(f_name);
    if(!prs)
        return list;

    QFile file(f_name);
    if (!file.open(QIODevice::ReadOnly))
    {
        qWarning("PlayListParser: unable to open playlist, error: %s", qPrintable(file.errorString()));
        return list;
    }

    list = prs->decode(QTextStream(&file).readAll());
    if(list.isEmpty())
        qWarning("PlayListParser: error opening %s",qPrintable(f_name));

    for (int i = 0; i < list.size(); ++i)
    {
        if(list.at(i).contains("://"))
            continue;

        if (QFileInfo(list.at(i)).isRelative())
            list[i].prepend(QFileInfo(f_name).canonicalPath () + "/");

        list[i].replace("\\","/");
        list[i].replace("//","/");
    }
    file.close();
    return list;
}

void PlayListParser::checkFormats()
{
    if (m_formats)
        return;

    m_formats = new QList<PlayListFormat*>();
    QDir pluginsDir (Qmmp::pluginsPath());
    pluginsDir.cd("PlayListFormats");
    QStringList filters;
    filters << "*.dll" << "*.so";
    foreach (QString fileName, pluginsDir.entryList(filters, QDir::Files))
    {
        QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
        QObject *plugin = loader.instance();
        if (loader.isLoaded())
            qDebug("PlayListParser: loaded plugin %s", qPrintable(fileName));
        else
            qWarning("PlayListParser: %s", qPrintable(loader.errorString ()));

        PlayListFormat *fmt = 0;
        if (plugin)
            fmt = qobject_cast<PlayListFormat *>(plugin);

        if (fmt)
            m_formats->append(fmt);
    }
}
t api changes' href='/qmmp/commit/src/plugins/Output/alsa/outputalsa.cpp?id=a030a982fc4194e81b21a36c1fb0a505f8e2e28b'>a030a982f
435f1da1d

a030a982f
435f1da1d

a030a982f
435f1da1d

a030a982f
435f1da1d

a030a982f
384917290


a030a982f

9d35f2ce0
a030a982f
435f1da1d
a030a982f

9d35f2ce0
a030a982f
d2d062fa7
3202566a0
b917024aa
a030a982f

9d35f2ce0
a030a982f



eaf8b9067
a030a982f
76f436c36
a030a982f


9d35f2ce0
2d622fd9b
76f436c36




b917024aa
a030a982f

9d35f2ce0
a030a982f
b917024aa
a030a982f

9d35f2ce0
a030a982f



9d35f2ce0
a030a982f






9d35f2ce0
a030a982f
b917024aa
a030a982f

9d35f2ce0
a030a982f









9d35f2ce0
a030a982f

a030a982f
738476128
c685eb34a
76f436c36
f9a510ef0
76f436c36

f9a510ef0
76f436c36
f9a510ef0




5fb7e3e4b
f9a510ef0







76f436c36
f9a510ef0

cff18fc98
76f436c36
a030a982f
579783f73
a030a982f
013ee07b5

2d622fd9b

0e860ae0b
2d622fd9b
49e42f587



2d622fd9b

d2d062fa7
3c32ca73d
d2d062fa7

3c32ca73d
7ef8d11ba

d2d062fa7



37a919696
d2d062fa7


3c32ca73d
d2d062fa7























3c32ca73d

a030a982f
2d622fd9b
d2d062fa7
2d622fd9b
37a919696
d2d062fa7
2d622fd9b

a030a982f
6963d98b9
a030a982f
2d622fd9b
a030a982f


2d622fd9b
a030a982f


37a919696
2d622fd9b
a030a982f

2d622fd9b
a030a982f

2d622fd9b
6963d98b9

11c28d451






6963d98b9






6963d98b9
6963d98b9




37a919696

6963d98b9












a030a982f
6963d98b9
2fa2f4887
6963d98b9















a030a982f
6963d98b9
2fa2f4887
6429b8e08
c685eb34a
6963d98b9

2d622fd9b



11b7655bb
2d622fd9b

d9ad753e7
2d622fd9b

b917024aa
2d622fd9b
a030a982f

b917024aa
2d622fd9b


74afcc2d9
d26eba2fa

b917024aa
ae75e5707
d26eba2fa





74afcc2d9
d26eba2fa
e747c2b87

d26eba2fa

75c4eaf61
d26eba2fa
d26eba2fa


75c4eaf61

d26eba2fa

75c4eaf61
d26eba2fa
75c4eaf61
1ef98753f









75c4eaf61
d26eba2fa

fe29680e9





74afcc2d9
2d622fd9b

2d622fd9b
b917024aa
2d622fd9b


e747c2b87
2d622fd9b

501a20123
2d622fd9b
e747c2b87
2d622fd9b








7b7c016ad
2d622fd9b
7b7c016ad
2d622fd9b



1ef98753f














33b3fdd2f
2d622fd9b


1ef98753f
74afcc2d9
2d622fd9b


















74afcc2d9
2d622fd9b
43bfdf725
2d622fd9b












74afcc2d9
2d622fd9b
2d622fd9b

2d622fd9b






7236148c9
501a20123
2d622fd9b

55fbc20be
2d622fd9b

b917024aa
2d622fd9b










2d622fd9b

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
                                                                            
                                                                            
                                                                            













                                                                            
                                                                            

                                                                             
                    
                          

                  

                   

                   

                        
                              
                       
 
 
                        
 
                                                                 
                                                                          
                                                                 
                                                  












                                                    





                         

 
                                                                                   
 










                                                                                           
                           
 

                                                           
 
                                   
                                                                 


                                                                       
                                                                          

                        

                                            




                                                                
     
                                                                                                 
                     
     
                   
     
                                                                                                            
         
                                                                                     
                               
         



                                                                                                          
         
                                                                                
                         
         
     

                                                          
     

                                        
              

                                            
              

                                            
              

                                            
              


                                           

                                                            
                     
     
                                                                                    

                                                                          
                     
     
                      
 
                                                                                                

                                                                          
                     



                                                                                                                              
                          
     
                         


                                                                                  
                     
     




                                                                                                     
                                                                                                        

                                                                                 
                     
     
                                                                                                        

                                                                                 
                     



                                                                               
                     






                                                                                 
                     
     
                                                                                       

                                                                                 
                     









                                                                               
                     

                         
                               
                                                                     
                                                     
 
                             

                                                           
             
     




                                                           
 







                                                                     
     

                                                                      
 
                                                                 
                            
                                                                                                   
                                              

                    

 
                            
 



                                                                                                         

 
                        
 

                                                                             
     

                                         



                                                                                  
                                                           


                  
     























                                     

 
                                                                  
 
                                                                    
     
                                                         
                                 

     
                                                                             
 
                             
     


                                                          
         


                                                                                  
                                                                                
         

                      
     

                   
 

                                                           






                                              






                                                         
                                      




                     

                                          












                                                                   
                 
     
               















                                                                    
                 
     
      
                                                      
                                        

 



                               
                     

                   
                                 

                                                 
                             
     

                       
                       


                          
                        

                
                      
                                                                 





                                                                        
                         
 

                                 

 
                                                     
 


                     

                                                                                            

 
                                         
 
                       









                                                                                             
               

 





                                             
                                                        

               
                   
                          


                                       
                                             

                   
                                                            
 
                                                     








                                                             
                                                                                  
     
                                                                                   



                           














                                                                                         
                                               


             
 
                                                                   


















                                         
                                                                                     
 
                                   












                                                      
                                                           
 

            






                                                              
 
                                                                          

                                                                
                                                       

                  
                                                                       










                                                            

                            
/***************************************************************************
 *   Copyright (C) 2006-2021 by Ilya Kotov                                 *
 *   forkotov02@ya.ru                                                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include <QSettings>
#include <QSocketNotifier>

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <qmmp/buffer.h>
#include <qmmp/visual.h>
#include <qmmp/statehandler.h>
#include "outputalsa.h"


OutputALSA::OutputALSA()
{
    QSettings settings(Qmmp::configFile(), QSettings::IniFormat);
    QString dev_name = settings.value("ALSA/device","default").toString();
    m_use_mmap = settings.value("ALSA/use_mmap", false).toBool();
    pcm_name = strdup(dev_name.toLatin1().data());
    m_alsa_channels = {
        { SND_CHMAP_NA, Qmmp::CHAN_NULL },
        { SND_CHMAP_MONO, Qmmp::CHAN_FRONT_CENTER },
        { SND_CHMAP_FL, Qmmp::CHAN_FRONT_LEFT },
        { SND_CHMAP_FR, Qmmp::CHAN_FRONT_RIGHT },
        { SND_CHMAP_RL, Qmmp::CHAN_REAR_LEFT },
        { SND_CHMAP_RR, Qmmp::CHAN_REAR_RIGHT },
        { SND_CHMAP_FC, Qmmp::CHAN_FRONT_CENTER },
        { SND_CHMAP_LFE, Qmmp::CHAN_LFE },
        { SND_CHMAP_SL, Qmmp::CHAN_SIDE_LEFT },
        { SND_CHMAP_SR, Qmmp::CHAN_SIDE_RIGHT },
        { SND_CHMAP_RC, Qmmp::CHAN_REAR_CENTER }
    };
}

OutputALSA::~OutputALSA()
{
    uninitialize();
    free (pcm_name);
}

bool OutputALSA::initialize(quint32 freq, ChannelMap map, Qmmp::AudioFormat format)
{
    m_inited = false;

    if (pcm_handle)
        return false;

    if (snd_pcm_open(&pcm_handle, pcm_name, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK) < 0)
    {
        qWarning ("OutputALSA: Error opening PCM device %s", pcm_name);
        return false;
    }

    // we need to configure

    uint rate = freq; /* Sample rate */
    uint exact_rate = freq;   /* Sample rate returned by */

    /* load settings from config */
    QSettings settings(Qmmp::configFile(), QSettings::IniFormat);
    settings.beginGroup("ALSA");
    uint buffer_time = settings.value("buffer_time",500).toUInt()*1000;
    uint period_time = settings.value("period_time",100).toUInt()*1000;
    bool use_pause =  settings.value("use_snd_pcm_pause", false).toBool();
    settings.endGroup();

    snd_pcm_hw_params_t *hwparams = nullptr;
    snd_pcm_sw_params_t *swparams = nullptr;
    int err; //alsa error code

    //hw params
    snd_pcm_hw_params_alloca(&hwparams);
    if ((err = snd_pcm_hw_params_any(pcm_handle, hwparams)) < 0)
    {
        qWarning("OutputALSA: Can not read configuration for PCM device: %s", snd_strerror(err));
        return false;
    }
    if (m_use_mmap)
    {
        if ((err = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_MMAP_INTERLEAVED)) < 0)
        {
            qWarning("OutputALSA: Error setting mmap access: %s", snd_strerror(err));
            m_use_mmap = false;
        }
    }
    if (!m_use_mmap)
    {
        if ((err = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
        {
            qWarning("OutputALSA: Error setting access: %s", snd_strerror(err));
            return false;
        }
    }
    snd_pcm_format_t alsa_format = SND_PCM_FORMAT_UNKNOWN;
    switch (format)
    {
    case Qmmp::PCM_S8:
        alsa_format = SND_PCM_FORMAT_S8;
        break;
    case Qmmp::PCM_S16LE:
        alsa_format = SND_PCM_FORMAT_S16_LE;
        break;
    case Qmmp::PCM_S24LE:
        alsa_format = SND_PCM_FORMAT_S24_LE;
        break;
    case Qmmp::PCM_S32LE:
        alsa_format = SND_PCM_FORMAT_S32_LE;
        break;
    case Qmmp::PCM_FLOAT:
        alsa_format = SND_PCM_FORMAT_FLOAT;
        break;
    default:
        qWarning("OutputALSA: unsupported format detected");
        return false;
    }
    if ((err = snd_pcm_hw_params_set_format(pcm_handle, hwparams, alsa_format)) < 0)
    {
        qDebug("OutputALSA: Error setting format: %s", snd_strerror(err));
        return false;
    }
    exact_rate = rate;

    if ((err = snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &exact_rate, nullptr)) < 0)
    {
        qWarning("OutputALSA: Error setting rate: %s", snd_strerror(err));
        return false;
    }
    if (rate != exact_rate)
    {
        qWarning("OutputALSA: The rate %d Hz is not supported by your hardware.\n==> Using %d Hz instead.", rate, exact_rate);
        rate = exact_rate;
    }
    uint c = map.count();
    if ((err = snd_pcm_hw_params_set_channels_near(pcm_handle, hwparams, &c)) < 0)
    {
        qWarning("OutputALSA: Error setting channels: %s", snd_strerror(err));
        return false;
    }
    if (c != (uint)map.count())
    {
        qWarning("OutputALSA: The channel number %d is not supported by your hardware", map.count());
        qWarning("==> Using %d instead.", c);
    }
    if ((err = snd_pcm_hw_params_set_period_time_near(pcm_handle, hwparams, &period_time, nullptr)) < 0)
    {
        qWarning("OutputALSA: Error setting period time: %s", snd_strerror(err));
        return false;
    }
    if ((err = snd_pcm_hw_params_set_buffer_time_near(pcm_handle, hwparams, &buffer_time, nullptr)) < 0)
    {
        qWarning("OutputALSA: Error setting buffer time: %s", snd_strerror(err));
        return false;
    }
    if ((err = snd_pcm_hw_params(pcm_handle, hwparams)) < 0)
    {
        qWarning("OutputALSA: Error setting HW params: %s", snd_strerror(err));
        return false;
    }
    //read some alsa parameters
    snd_pcm_uframes_t buffer_size = 0;
    snd_pcm_uframes_t period_size = 0;
    if ((err = snd_pcm_hw_params_get_buffer_size(hwparams, &buffer_size)) < 0)
    {
        qWarning("OutputALSA: Error reading buffer size: %s", snd_strerror(err));
        return false;
    }
    if ((err = snd_pcm_hw_params_get_period_size(hwparams, &period_size, nullptr)) < 0)
    {
        qWarning("OutputALSA: Error reading period size: %s", snd_strerror(err));
        return false;
    }
    //swparams
    snd_pcm_sw_params_alloca(&swparams);
    snd_pcm_sw_params_current(pcm_handle, swparams);
    if ((err = snd_pcm_sw_params_set_start_threshold(pcm_handle, swparams,
               buffer_size - period_size)) < 0)
        qWarning("OutputALSA: Error setting threshold: %s", snd_strerror(err));
    if ((err = snd_pcm_sw_params(pcm_handle, swparams)) < 0)
    {
        qWarning("OutputALSA: Error setting SW params: %s", snd_strerror(err));
        return false;
    }
    //setup needed values
    m_chunk_size = period_size;
    m_can_pause = snd_pcm_hw_params_can_pause(hwparams) && use_pause;
    qDebug("OutputALSA: can pause: %d", m_can_pause);

    ChannelMap out_map = map;
    //channel map configuration
    snd_pcm_chmap_t *chmap = snd_pcm_get_chmap(pcm_handle);
    if(chmap)
    {
        out_map.clear();
        char tmp[256];
        memset(tmp,0,256);
        snd_pcm_chmap_print(chmap, 256, tmp);
        qDebug("OutputALSA: received channel map: %s",tmp);

        for(uint i = 0; i < chmap->channels; ++i)
        {
            if(m_alsa_channels.keys().contains(chmap->pos[i]))
                out_map.append(m_alsa_channels.value(chmap->pos[i]));
            else
                out_map.append(Qmmp::CHAN_NULL);
        }
        free(chmap);
    }
    else
        qWarning("OutputALSA: Unable to receive current channel map");

    configure(exact_rate, out_map, format); //apply configuration
    //create alsa prebuffer;
    m_prebuf_size = 2 * snd_pcm_frames_to_bytes(pcm_handle, m_chunk_size); //buffer for two periods
    m_prebuf = (uchar *)malloc(m_prebuf_size);
    m_inited = true;
    return true;
}

qint64 OutputALSA::latency()
{
    snd_pcm_sframes_t delay = 0;
    snd_pcm_delay(pcm_handle, &delay);
    delay = qBound(3000L, delay, 30000L); //filter out possible invalid values
    return m_prebuf_fill * 1000 / sampleRate() / channels() / sampleSize() + delay * 1000 / sampleRate();
}

void OutputALSA::drain()
{
    snd_pcm_uframes_t l = snd_pcm_bytes_to_frames(pcm_handle, m_prebuf_fill);
    while (l > 0)
    {
        long m = alsa_write(m_prebuf, l);
        if (m >= 0)
        {
            l -= m;
            m = snd_pcm_frames_to_bytes(pcm_handle, m); // convert frames to bytes
            m_prebuf_fill -= m;
            memmove(m_prebuf, m_prebuf + m, m_prebuf_fill);
        }
        else
            break;
    }
    snd_pcm_nonblock(pcm_handle, 0);
    snd_pcm_drain(pcm_handle);
    snd_pcm_nonblock(pcm_handle, 1);
}

void OutputALSA::reset()
{
    m_prebuf_fill = 0;
    snd_pcm_drop(pcm_handle);
    snd_pcm_prepare(pcm_handle);
}

void OutputALSA::suspend()
{
    if (m_can_pause)
        snd_pcm_pause(pcm_handle, 1);
    snd_pcm_prepare(pcm_handle);
}

void OutputALSA::resume()
{
    if (m_can_pause)
        snd_pcm_pause(pcm_handle, 0);
    snd_pcm_prepare(pcm_handle);
}

qint64 OutputALSA::writeAudio(unsigned char *data, qint64 maxSize)
{
    if((maxSize = qMin(maxSize, m_prebuf_size - m_prebuf_fill)) > 0)
    {
        memmove(m_prebuf + m_prebuf_fill, data, maxSize);
        m_prebuf_fill += maxSize;
    }

    snd_pcm_uframes_t l = snd_pcm_bytes_to_frames(pcm_handle, m_prebuf_fill);

    while (l >= m_chunk_size)
    {
        snd_pcm_wait(pcm_handle, 10);
        long m;
        if ((m = alsa_write(m_prebuf, m_chunk_size)) >= 0)
        {
            l -= m;
            m = snd_pcm_frames_to_bytes(pcm_handle, m); // convert frames to bytes
            m_prebuf_fill -= m;
            memmove(m_prebuf, m_prebuf + m, m_prebuf_fill); //move data to begin
        }
        else
            return -1;
    }
    return maxSize;
}

long OutputALSA::alsa_write(unsigned char *data, long size)
{
    long m = snd_pcm_avail_update(pcm_handle);
    if(m >= 0 && m < size)
    {
        snd_pcm_wait(pcm_handle, 500);
        return 0;
    }

    if (m_use_mmap)
        m = snd_pcm_mmap_writei (pcm_handle, data, size);
    else
        m = snd_pcm_writei (pcm_handle, data, size);

    if (m == -EAGAIN)
    {
        snd_pcm_wait(pcm_handle, 500);
        return 0;
    }
    else if (m >= 0)
    {
        if (m < size)
        {
            snd_pcm_wait(pcm_handle, 500);
        }
        return m;
    }
    else if (m == -EPIPE)
    {
        qDebug ("OutputALSA: buffer underrun!");
        if ((m = snd_pcm_prepare(pcm_handle)) < 0)
        {
            qDebug ("OutputALSA: Can't recover after underrun: %s",
                    snd_strerror(m));
            /* TODO: reopen the device */
            return -1;
        }
        return 0;
    }
#ifdef ESTRPIPE
    else if (m == -ESTRPIPE)
    {
        qDebug ("OutputALSA: Suspend, trying to resume");
        while ((m = snd_pcm_resume(pcm_handle))
                == -EAGAIN)
            sleep (1);
        if (m < 0)
        {
            qDebug ("OutputALSA: Failed, restarting");
            if ((m = snd_pcm_prepare(pcm_handle)) < 0)
            {
                qDebug ("OutputALSA: Failed to restart device: %s.",
                        snd_strerror(m));
                return -1;
            }
        }
        return 0;
    }
#endif
    qDebug ("OutputALSA: error: %s", snd_strerror(m));
    return snd_pcm_prepare (pcm_handle);
}

void OutputALSA::uninitialize()
{
    if (!m_inited)
        return;
    m_inited = false;
    if (pcm_handle)
    {
        snd_pcm_drop(pcm_handle);
        qDebug("OutputALSA: closing pcm_handle");
        snd_pcm_close(pcm_handle);
        pcm_handle = nullptr;
    }
    if (m_prebuf)
        free(m_prebuf);
    m_prebuf = nullptr;
}
/* ****** MIXER ******* */

VolumeALSA::VolumeALSA()
{
    //alsa mixer
    m_mixer = nullptr;
    QSettings settings(Qmmp::configFile(), QSettings::IniFormat);
    QString card = settings.value("ALSA/mixer_card","hw:0").toString();
    QString dev = settings.value("ALSA/mixer_device", "PCM").toString();
    setupMixer(card, dev);
}


VolumeALSA::~VolumeALSA()
{
    if (m_mixer)
        snd_mixer_close(m_mixer);
}

void VolumeALSA::setVolume(const VolumeSettings &vol)
{
    if (!pcm_element)
        return;

    snd_mixer_selem_set_playback_volume(pcm_element, SND_MIXER_SCHN_FRONT_LEFT, vol.left);
    snd_mixer_selem_set_playback_volume(pcm_element, SND_MIXER_SCHN_FRONT_RIGHT, vol.right);
}

VolumeSettings VolumeALSA::volume() const
{
    VolumeSettings vol;

    if(pcm_element)
    {
        long value = 0;
        snd_mixer_handle_events(m_mixer);
        snd_mixer_selem_get_playback_volume(pcm_element, SND_MIXER_SCHN_FRONT_LEFT, &value);
        vol.left = value;
        snd_mixer_selem_get_playback_volume(pcm_element, SND_MIXER_SCHN_FRONT_RIGHT, &value);
        vol.right = value;
    }
    return vol;
}

Volume::VolumeFlags VolumeALSA::flags() const
{

    return Volume::HasNotifySignal;
}

int VolumeALSA::setupMixer(QString card, QString device)
{
    char *name;
    int err, index;
    pcm_element = nullptr;

    qDebug("OutputALSA: setupMixer()");

    if ((err = getMixer(&m_mixer, card)) < 0)
        return err;

    parseMixerName(device.toLatin1().data(), &name, &index);

    pcm_element = getMixerElem(m_mixer, name, index);

    free(name);

    if (!pcm_element)
    {
        qWarning("OutputALSA: Failed to find mixer element");
        return -1;
    }

    if((err = snd_mixer_selem_set_playback_volume_range(pcm_element, 0, 100)) < 0)
    {
        qWarning("OutputALSA: Unable to set volume range: %s", snd_strerror(-err));
        pcm_element = NULL;
        return -1;
    }

    // setup socket notifiers to monitor the state changes of the mixer
    int n = snd_mixer_poll_descriptors_count(m_mixer);
    if(n > 0)
    {
        struct pollfd* fds = new struct pollfd[n];
        n = snd_mixer_poll_descriptors(m_mixer, fds, n);
        for(int i = 0; i < n; ++i)
        {
            int sock = fds[i].fd;
            QSocketNotifier* sn = new QSocketNotifier(sock, QSocketNotifier::Read, this);
            connect(sn, SIGNAL(activated(int)), SIGNAL(changed()));
        }
        delete []fds;
    }

    qDebug("OutputALSA: setupMixer() success");
    return 0;
}


void VolumeALSA::parseMixerName(char *str, char **name, int *index)
{
    char *end;

    while (isspace(*str))
        str++;

    if ((end = strchr(str, ',')) != NULL)
    {
        *name = strndup(str, end - str);
        end++;
        *index = atoi(end);
    }
    else
    {
        *name = strdup(str);
        *index = 0;
    }
}

snd_mixer_elem_t* VolumeALSA::getMixerElem(snd_mixer_t *mixer, char *name, int index)
{
    snd_mixer_selem_id_t* selem_id;
    snd_mixer_elem_t* elem;
    snd_mixer_selem_id_alloca(&selem_id);

    if (index != -1)
        snd_mixer_selem_id_set_index(selem_id, index);
    if (name != NULL)
        snd_mixer_selem_id_set_name(selem_id, name);

    elem = snd_mixer_find_selem(mixer, selem_id);

    return elem;
}

int VolumeALSA::getMixer(snd_mixer_t **mixer, QString card)
{
    int err;

    if ((err = snd_mixer_open(mixer, 0)) < 0)
    {
        qWarning("OutputALSA: Failed to open empty mixer: %s",
                 snd_strerror(-err));
        mixer = NULL;
        return -1;
    }

    if ((err = snd_mixer_attach(*mixer, card.toLatin1().constData())) < 0)
    {
        qWarning("OutputALSA: Attaching to mixer %s failed: %s",
                 qPrintable(card), snd_strerror(-err));
        return -1;
    }
    if ((err = snd_mixer_selem_register(*mixer, nullptr, nullptr)) < 0)
    {
        qWarning("OutputALSA: Failed to register mixer: %s",
                 snd_strerror(-err));
        return -1;
    }
    if ((err = snd_mixer_load(*mixer)) < 0)
    {
        qWarning("OutputALSA: Failed to load mixer: %s",
                 snd_strerror(-err));
        return -1;
    }
    return (*mixer != NULL);
}