forked from albertz/music-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ffmpeg.c
2244 lines (1909 loc) · 66.8 KB
/
ffmpeg.c
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Python module for playing audio
// compile:
// gcc -c ffmpeg.o -I /System/Library/Frameworks/Python.framework/Headers/
// libtool -dynamic -o ffmpeg.so ffmpeg.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc
// loosely based on ffplay.c
// https://github.com/FFmpeg/ffmpeg/blob/master/ffplay.c
// Similar to PyFFmpeg. http://code.google.com/p/pyffmpeg/
// This module is intended to be much simpler/high-level, though.
// Pyton interface:
// createPlayer() -> player object with:
// queue: song generator
// playing: True or False, initially False
// volume: 1.0 is norm; this is just a factor to each sample. default is 0.9
// volumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10)
// curSong: current song (read only)
// curSongPos: current song pos (read only)
// curSongLen: current song len (read only)
// curSongGainFactor: current song gain. read from song.gain (see below). can also be written
// seekAbs(t) / seekRel(t): seeking functions (t in seconds, accepts float)
// nextSong(): skip to next song function
// song object expected interface:
// readPacket(bufSize): should return some string
// seekRaw(offset, whence): should seek and return the current pos
// gain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored
// url: some url, can be anything printable (not used at the moment)
// and other functions, see their embedded doc ...
// Import Python first. This will define _GNU_SOURCE. This is needed to get strdup (and maybe others). We could also define _GNU_SOURCE ourself, but pyconfig.h from Python has troubles then and redeclares some other stuff. So, to just import Python first is the simplest way.
#include <Python.h>
#include <pythread.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <libavcodec/avfft.h>
#include <portaudio.h>
#include <chromaprint.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stddef.h>
//#define DEBUG 1
#define SAMPLERATE 44100
#define NUMCHANNELS 2
#define AUDIO_BUFFER_SIZE 2048
/* Some confusion about Python functions and their reference counting:
PyObject_GetAttrString: returns new reference!
PyDict_SetItem: increments reference on key and value!
PyDict_SetItemString: increments reference on value!
PyDict_GetItemString: does not inc ref of returned obj, i.e. borrowed ref! (unlike PyObject_GetAttrString)
PyTuple_Pack: increments references on passed objects
PyTuple_SetItem: does *not* increment references, i.e. steals ref (unlike PyDict_SetItem)
PyList_Append: inc ref of passed object
PyList_SetItem: does *not* inc ref on obj!
*/
static int PyDict_SetItemString_retain(PyObject* dict, const char* key, PyObject* value) {
int ret = PyDict_SetItemString(dict, key, value);
Py_DECREF(value);
return ret;
}
typedef struct AudioParams {
int freq;
int channels;
int64_t channel_layout;
enum AVSampleFormat fmt;
} AudioParams;
// see smoothClip()
typedef struct SmoothClipCalc {
float x1, x2;
double a,b,c,d;
} SmoothClipCalc;
// The player structure. Create by ffmpeg.createPlayer().
// This struct is initialized in player_init().
typedef struct {
PyObject_HEAD
// public
PyObject* queue;
int playing;
PyObject* curSong;
double curSongLen;
PyObject* curSongMetadata;
float curSongGainFactor;
float volume;
SmoothClipCalc volumeSmoothClip; // see smoothClip()
// private
AVFormatContext* inStream;
PaStream* outStream;
PyObject* dict;
int nextSongOnEof;
int skipPyExceptions; // for all callbacks, mainly song.readPacket
/* Important note about the lock:
To avoid deadlocks with on thread waiting on the Python GIL and another on this lock,
we must ensure a strict order in which we might acquire both locks:
When we acquire this/players lock, the PyGIL *must not* be held.
When we held this/players lock, the PyGIL can be acquired.
In practice, if we want this lock, if we hold already the PyGIL, we usually use this code:
Py_INCREF(player); // to assure that we have a real own ref
Py_BEGIN_ALLOW_THREADS
PyThread_acquire_lock(player->lock, WAIT_LOCK);
// do something (note that we dont hold the PyGIL here!)
PyThread_release_lock(player->lock);
Py_END_ALLOW_THREADS
Py_DECREF(player);
If we hold this lock and we also want to get the PyGIL, we use
PyGILState_Ensure()/PyGILState_Release() as usual.
We use this order because in the PaStream handling thread, we might just want to get
the players lock but don't always need the PyGIL.
*/
PyThread_type_lock lock;
// audio_decode
int audio_stream;
double audio_clock;
AVStream *audio_st;
DECLARE_ALIGNED(16,uint8_t,audio_buf2)[AVCODEC_MAX_AUDIO_FRAME_SIZE * 4];
uint8_t silence_buf[AUDIO_BUFFER_SIZE];
uint8_t *audio_buf;
uint8_t *audio_buf1;
unsigned int audio_buf_size; /* in bytes */
int audio_buf_index; /* in bytes */
int audio_write_buf_size;
AVPacket audio_pkt_temp;
AVPacket audio_pkt;
int do_flush;
struct AudioParams audio_src;
struct AudioParams audio_tgt;
struct SwrContext *swr_ctx;
// double audio_current_pts;
// double audio_current_pts_drift;
AVFrame *frame;
} PlayerObject;
/*
For values y < 0, mirror.
For values y in [0,x1], this is just y (i.e. identity function).
For values y >= x2, this is just 1 (i.e. constant 1 function).
For y in [x1,x2], we use a cubic spline interpolation to just make it smooth.
Use smoothClip_setX() to set the spline factors.
*/
static double smoothClip(SmoothClipCalc* s, double y) {
if(y < 0) return -smoothClip(s, -y);
if(y <= s->x1) return y;
if(y >= s->x2) return 1;
y = s->a * y*y*y + s->b * y*y + s->c * y + s->d;
if(y <= s->x1) return s->x1;
if(y >= 1) return 1;
return y;
}
static void smoothClip_setX(SmoothClipCalc* s, float x1, float x2) {
if(x1 < 0) x1 = 0;
if(x1 > 1) x1 = 1;
if(x2 < x1) x2 = x1;
s->x1 = x1;
s->x2 = x2;
if(x1 == x2) {
s->a = 0;
s->b = 0;
s->c = 1;
s->d = 0;
return;
}
s->a = ((x1 + x2 - 2.) / pow(x2 - x1, 3.));
s->b = ((- (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((7. * pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - 1.) / (4. * x2 - 4.));
s->c = (1. / 2.) * ((((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) + ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - ((4. * (- (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((7. * pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - 1.)) / (4. * x2 - 4.)) + 1.);
s->d = (1. / 4.) * ((((x1 + x2 - 2.) * pow(x1, 3.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((pow(x2, 2.) * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((2. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + x1 - ((pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((4. * (- (((x1 + x2 - 2.) * pow(x1, 2.)) / pow(x2 - x1, 3.)) - ((4. * x2 * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) + ((6. * (x1 + x2 - 2.) * x1) / pow(x2 - x1, 3.)) - ((7. * pow(x2, 2.) * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) + ((6. * x2 * (x1 + x2 - 2.)) / pow(x2 - x1, 3.)) - 1.)) / (4. * x2 - 4.)) + 1.);
}
static int player_read_packet(PlayerObject* player, uint8_t* buf, int buf_size) {
// We assume that we have the PlayerObject lock at this point but not neccessarily the Python GIL.
//printf("player_read_packet %i\n", buf_size);
Py_ssize_t ret = -1;
PyObject *readPacketFunc = NULL, *args = NULL, *retObj = NULL;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
if(player->curSong == NULL) goto final;
readPacketFunc = PyObject_GetAttrString(player->curSong, "readPacket");
if(readPacketFunc == NULL) goto final;
args = PyTuple_New(1);
PyTuple_SetItem(args, 0, PyInt_FromLong(buf_size));
retObj = PyObject_CallObject(readPacketFunc, args);
if(retObj == NULL) goto final;
if(!PyString_Check(retObj)) {
printf("song.readPacket didn't returned a string but a %s\n", retObj->ob_type->tp_name);
goto final;
}
ret = PyString_Size(retObj);
if(ret > buf_size) {
printf("song.readPacket returned more than buf_size\n");
ret = buf_size;
}
if(ret < 0) {
ret = -1;
goto final;
}
memcpy(buf, PyString_AsString(retObj), ret);
final:
Py_XDECREF(retObj);
Py_XDECREF(args);
Py_XDECREF(readPacketFunc);
if(player->skipPyExceptions && PyErr_Occurred())
PyErr_Print();
PyGILState_Release(gstate);
return (int) ret;
}
static int64_t player_seek(PlayerObject* player, int64_t offset, int whence) {
// We assume that we have the PlayerObject lock at this point but not neccessarily the Python GIL.
//printf("player_seek %lli %i\n", offset, whence);
int64_t ret = -1;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject *seekRawFunc = NULL, *args = NULL, *retObj = NULL;
if(player->curSong == NULL) goto final;
if(whence < 0 || whence > 2) goto final; // AVSEEK_SIZE and others not supported atm
seekRawFunc = PyObject_GetAttrString(player->curSong, "seekRaw");
if(seekRawFunc == NULL) goto final;
args = PyTuple_New(2);
if(args == NULL) goto final;
PyTuple_SetItem(args, 0, PyLong_FromLongLong(offset));
PyTuple_SetItem(args, 1, PyInt_FromLong(whence));
retObj = PyObject_CallObject(seekRawFunc, args);
if(retObj == NULL) goto final; // pass through any Python exception
// NOTE: I don't really know what would be the best strategy in case of overflow...
if(PyInt_Check(retObj))
ret = (int) PyInt_AsLong(retObj);
else if(PyLong_Check(retObj))
ret = (int) PyLong_AsLong(retObj);
else {
printf("song.seekRaw didn't returned an int but a %s\n", retObj->ob_type->tp_name);
goto final;
}
final:
Py_XDECREF(retObj);
Py_XDECREF(args);
Py_XDECREF(seekRawFunc);
if(player->skipPyExceptions && PyErr_Occurred())
PyErr_Print();
PyGILState_Release(gstate);
return ret;
}
static int _player_av_read_packet(void *opaque, uint8_t *buf, int buf_size) {
return player_read_packet((PlayerObject*)opaque, buf, buf_size);
}
static int64_t _player_av_seek(void *opaque, int64_t offset, int whence) {
return player_seek((PlayerObject*)opaque, offset, whence);
}
static
AVIOContext* initIoCtx(PlayerObject* player) {
int buffer_size = 1024 * 4;
unsigned char* buffer = av_malloc(buffer_size);
AVIOContext* io = avio_alloc_context(
buffer,
buffer_size,
0, // writeflag
player, // opaque
_player_av_read_packet,
NULL, // write_packet
_player_av_seek
);
return io;
}
static
AVFormatContext* initFormatCtx(PlayerObject* player) {
AVFormatContext* fmt = avformat_alloc_context();
if(!fmt) return NULL;
fmt->pb = initIoCtx(player);
if(!fmt->pb) {
printf("initIoCtx failed\n");
}
fmt->flags |= AVFMT_FLAG_CUSTOM_IO;
return fmt;
}
static int stream_seekRel(PlayerObject* player, double incr) {
int seek_by_bytes = 0;
double pos = 0;
if(seek_by_bytes) {
if (player->audio_stream >= 0 && player->audio_pkt.pos >= 0) {
pos = player->audio_pkt.pos;
} else
pos = avio_tell(player->inStream->pb);
if (player->inStream->bit_rate)
incr *= player->inStream->bit_rate / 8.0;
else
incr *= 180000.0;
pos += incr;
}
else {
pos = player->audio_clock;
pos += incr;
pos *= AV_TIME_BASE;
incr *= AV_TIME_BASE;
}
int64_t seek_target = pos;
int64_t seek_min = incr > 0 ? seek_target - incr + 2: INT64_MIN;
int64_t seek_max = incr < 0 ? seek_target - incr - 2: INT64_MAX;
int seek_flags = 0;
if(seek_by_bytes) seek_flags |= AVSEEK_FLAG_BYTE;
player->do_flush = 1;
return
avformat_seek_file(
player->inStream, /*player->audio_stream*/ -1,
seek_min,
seek_target,
seek_max,
seek_flags
);
}
static int stream_seekAbs(PlayerObject* player, double pos) {
int seek_by_bytes = 0;
if(player->curSongLen <= 0)
seek_by_bytes = 1;
int seek_flags = 0;
if(seek_by_bytes) seek_flags |= AVSEEK_FLAG_BYTE;
if(seek_by_bytes) {
if (player->inStream->bit_rate)
pos *= player->inStream->bit_rate / 8.0;
else
pos *= 180000.0;
}
else {
pos *= AV_TIME_BASE;
}
player->do_flush = 1;
return
avformat_seek_file(
player->inStream, /*player->audio_stream*/ -1,
INT64_MIN,
(int64_t) pos,
INT64_MAX,
seek_flags
);
}
static void player_resetStreamPackets(PlayerObject* player) {
av_free_packet(&player->audio_pkt);
memset(&player->audio_pkt, 0, sizeof(player->audio_pkt));
memset(&player->audio_pkt_temp, 0, sizeof(player->audio_pkt_temp));
}
/* open a given stream. Return 0 if OK */
// called by player_openInputStream()
static int stream_component_open(PlayerObject *is, AVFormatContext* ic, int stream_index)
{
AVCodecContext *avctx;
AVCodec *codec;
// AVDictionaryEntry *t = NULL;
if (stream_index < 0 || stream_index >= ic->nb_streams)
return -1;
avctx = ic->streams[stream_index]->codec;
codec = avcodec_find_decoder(avctx->codec_id);
if (!codec) {
printf("avcodec_find_decoder failed\n");
return -1;
}
//avctx->workaround_bugs = workaround_bugs;
//avctx->lowres = lowres;
if(avctx->lowres > codec->max_lowres){
av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
codec->max_lowres);
avctx->lowres= codec->max_lowres;
}
//avctx->idct_algo = idct;
//avctx->skip_frame = skip_frame;
//avctx->skip_idct = skip_idct;
//avctx->skip_loop_filter = skip_loop_filter;
//avctx->error_concealment = error_concealment;
if(avctx->lowres) avctx->flags |= CODEC_FLAG_EMU_EDGE;
//if (fast) avctx->flags2 |= CODEC_FLAG2_FAST;
if(codec->capabilities & CODEC_CAP_DR1)
avctx->flags |= CODEC_FLAG_EMU_EDGE;
if (avcodec_open2(avctx, codec, NULL /*opts*/) < 0) {
printf("avcodec_open2 failed\n");
return -1;
}
/* prepare audio output */
//if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
// is->audio_tgt = is->audio_src;
//}
ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;
switch (avctx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
is->audio_stream = stream_index;
is->audio_st = ic->streams[stream_index];
is->audio_buf_size = 0;
is->audio_buf_index = 0;
/* init averaging filter */
//is->audio_diff_avg_coef = exp(log(0.01) / AUDIO_DIFF_AVG_NB);
//is->audio_diff_avg_count = 0;
/* since we do not have a precise anough audio fifo fullness,
we correct audio sync only if larger than this threshold */
//is->audio_diff_threshold = 2.0 * is->audio_hw_buf_size / av_samples_get_buffer_size(NULL, is->audio_tgt.channels, is->audio_tgt.freq, is->audio_tgt.fmt, 1);
player_resetStreamPackets(is);
//packet_queue_start(&is->audioq);
//SDL_PauseAudio(0);
break;
default:
printf("stream_component_open: not an audio stream\n");
return -1;
}
return 0;
}
// this is mostly safe to call
static char* objStrDup(PyObject* obj) {
PyGILState_STATE gstate = PyGILState_Ensure();
char* str = NULL;
PyObject* earlierError = PyErr_Occurred();
if(!obj)
str = "<None>";
else if(PyString_Check(obj))
str = PyString_AsString(obj);
else {
PyObject* strObj = NULL;
if(PyUnicode_Check(obj))
strObj = PyUnicode_AsUTF8String(obj);
else {
PyObject* unicodeObj = PyObject_Unicode(obj);
if(unicodeObj) {
strObj = PyUnicode_AsUTF8String(unicodeObj);
Py_DECREF(unicodeObj);
}
}
if(strObj) {
str = PyString_AsString(strObj);
Py_DECREF(strObj);
}
else
str = "<CantConvertToString>";
}
if(!earlierError && PyErr_Occurred())
PyErr_Print();
assert(str);
str = strdup(str);
PyGILState_Release(gstate);
return str;
}
static char* objAttrStrDup(PyObject* obj, const char* attrStr) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* attrObj = PyObject_GetAttrString(obj, attrStr);
char* str = objStrDup(attrObj);
Py_XDECREF(attrObj);
PyGILState_Release(gstate);
return str;
}
static void player_setSongMetadata(PlayerObject* player) {
Py_XDECREF(player->curSongMetadata);
player->curSongMetadata = NULL;
if(!player->inStream) return;
if(!player->inStream->metadata) return;
AVDictionary* m = player->inStream->metadata;
player->curSongMetadata = PyDict_New();
assert(player->curSongMetadata);
AVDictionaryEntry *tag=NULL;
while((tag=av_dict_get(m, "", tag, AV_DICT_IGNORE_SUFFIX))) {
if(strcmp("language", tag->key) == 0)
continue;
PyDict_SetItemString_retain(player->curSongMetadata, tag->key, PyString_FromString(tag->value));
}
if(player->curSongLen > 0) {
PyDict_SetItemString_retain(player->curSongMetadata, "duration", PyFloat_FromDouble(player->curSongLen));
}
else if(PyDict_GetItemString(player->curSongMetadata, "duration")) {
// we have an earlier duration metadata which is a string now.
// convert it to float.
PyObject* floatObj = PyFloat_FromString(PyDict_GetItemString(player->curSongMetadata, "duration"), NULL);
if(!floatObj) {
PyErr_Clear();
PyDict_DelItemString(player->curSongMetadata, "duration");
}
else {
PyDict_SetItemString_retain(player->curSongMetadata, "duration", floatObj);
}
}
}
static void closeInputStream(AVFormatContext* formatCtx) {
if(formatCtx->pb) {
if(formatCtx->pb->buffer) {
av_free(formatCtx->pb->buffer);
formatCtx->pb->buffer = NULL;
}
// avformat_close_input freeing this indirectly? I got a crash here in avio_close
//av_free(formatCtx->pb);
//formatCtx->pb = NULL;
}
for(int i = 0; i < formatCtx->nb_streams; ++i) {
avcodec_close(formatCtx->streams[i]->codec);
}
avformat_close_input(&formatCtx);
}
static void player_closeInputStream(PlayerObject* player) {
player_resetStreamPackets(player);
if(player->inStream) {
closeInputStream(player->inStream);
player->inStream = NULL;
}
}
static void player_closeOutputStream(PlayerObject* player) {
// we expect that we have the lock here.
// we must release the lock so that any thread-join can be done.
PaStream* stream = player->outStream;
player->outStream = NULL;
PyThread_release_lock(player->lock);
Pa_CloseStream(stream);
PyThread_acquire_lock(player->lock, WAIT_LOCK);
}
static void player_stopOutputStream(PlayerObject* player) {
// we expect that we have the lock here.
// we must release the lock so that any thread-join can be done.
PaStream* stream = player->outStream;
PyThread_release_lock(player->lock);
Pa_StopStream(stream);
PyThread_acquire_lock(player->lock, WAIT_LOCK);
}
static
int player_openInputStream(PlayerObject* player) {
char* urlStr = NULL;
assert(player->curSong != NULL);
PyObject* curSong = player->curSong;
player_closeInputStream(player);
AVFormatContext* formatCtx = initFormatCtx(player);
if(!formatCtx) {
printf("initFormatCtx failed\n");
goto final;
}
urlStr = objAttrStrDup(curSong, "url"); // the url is just for debugging, the song object provides its own IO
int ret = avformat_open_input(&formatCtx, urlStr, NULL, NULL);
if(ret != 0) {
printf("avformat_open_input failed\n");
goto final;
}
ret = avformat_find_stream_info(formatCtx, NULL);
if(ret < 0) {
printf("avformat_find_stream_info failed\n");
goto final;
}
#ifdef DEBUG
av_dump_format(formatCtx, 0, urlStr, 0);
#endif
ret = av_find_best_stream(formatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, 0, 0);
if(ret < 0) {
printf("no audio stream found in song\n");
goto final;
}
player->audio_stream = ret;
ret = stream_component_open(player, formatCtx, player->audio_stream);
if(ret < 0) {
printf("no audio stream found in song\n");
goto final;
}
player->inStream = formatCtx;
formatCtx = NULL;
// Get the song len: There is formatCtx.duration in AV_TIME_BASE
// and there is stream.duration in stream time base.
assert(player->audio_st);
player->curSongLen = av_q2d(player->audio_st->time_base) * player->audio_st->duration;
//if(player->curSongLen < 0) { // happens in some cases, e.g. some flac files
// player->curSongLen = av_q2d(AV_TIME_BASE_Q) * formatCtx->duration; // doesnt make it better though...
//}
if(player->curSongLen < 0)
player->curSongLen = -1;
player_setSongMetadata(player);
player->curSongGainFactor = 1;
if(PyObject_HasAttrString(player->curSong, "gain")) {
PyObject* gainObj = PyObject_GetAttrString(player->curSong, "gain");
if(gainObj) {
float gain = 0;
if(!PyArg_Parse(gainObj, "f", &gain))
printf("song.gain is not a float");
else
player->curSongGainFactor = pow(10, gain / 20);
Py_DECREF(gainObj);
}
else { // !gainObj
// strange. reset any errors...
if(PyErr_Occurred())
PyErr_Print();
}
}
// TODO: maybe alternatively try to read from metatags?
final:
if(urlStr) free(urlStr);
if(formatCtx) closeInputStream(formatCtx);
if(player->inStream) return 0;
return -1;
}
static int player_getNextSong(PlayerObject* player, int skipped) {
// We must hold the player lock here.
int ret = -1;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject* oldSong = player->curSong;
player->curSong = NULL;
if(player->queue == NULL) {
PyErr_SetString(PyExc_RuntimeError, "player queue is not set");
goto final;
}
if(!PyIter_Check(player->queue)) {
PyErr_SetString(PyExc_RuntimeError, "player queue is not an iterator");
goto final;
}
player->curSong = PyIter_Next(player->queue);
// pass through any Python errors
if(!player->curSong || PyErr_Occurred())
goto final;
int errorOnOpening = 0;
if(player_openInputStream(player) != 0) {
// This is not fatal, so don't make a Python exception.
// When we are in playing state, we will just skip to the next song.
// This can happen if we don't support the format or whatever.
printf("cannot open input stream\n");
errorOnOpening = 1;
}
else if(!player->inStream) {
// This is strange, player_openInputStream should have returned !=0.
printf("strange error on open input stream\n");
errorOnOpening = 1;
}
else
// everything fine!
ret = 0;
// make callback onSongChange
if(player->dict) {
PyObject* onSongChange = PyDict_GetItemString(player->dict, "onSongChange");
if(onSongChange && onSongChange != Py_None) {
PyObject* kwargs = PyDict_New();
assert(kwargs);
if(oldSong)
PyDict_SetItemString(kwargs, "oldSong", oldSong);
else
PyDict_SetItemString(kwargs, "oldSong", Py_None);
PyDict_SetItemString(kwargs, "newSong", player->curSong);
PyDict_SetItemString_retain(kwargs, "skipped", PyBool_FromLong(skipped));
PyDict_SetItemString_retain(kwargs, "errorOnOpening", PyBool_FromLong(errorOnOpening));
PyObject* retObj = PyEval_CallObjectWithKeywords(onSongChange, NULL, kwargs);
Py_XDECREF(retObj);
// errors are not fatal from the callback, so handle it now and go on
if(PyErr_Occurred()) {
PyErr_Print(); // prints traceback to stderr, resets error indicator. also handles sys.excepthook if it is set (see pythonrun.c, it's not said explicitely in the docs)
}
Py_DECREF(kwargs);
}
}
final:
Py_XDECREF(oldSong);
PyGILState_Release(gstate);
return ret;
}
/* return the wanted number of samples to get better sync if sync_type is video
* or external master clock */
static int synchronize_audio(PlayerObject *is, int nb_samples)
{
int wanted_nb_samples = nb_samples;
return wanted_nb_samples;
}
static int volumeAdjustNeeded(PlayerObject* p) {
if(p->volume != 1) return 1;
if(p->volumeSmoothClip.x1 != p->volumeSmoothClip.x2) return 1;
if(p->curSongGainFactor != 1) return 1;
return 0;
}
// called from player_fillOutStream
/* decode one audio frame and returns its uncompressed size */
static int audio_decode_frame(PlayerObject *is, double *pts_ptr)
{
// We assume that we have the PlayerObject lock at this point but not neccessarily the Python GIL.
if(is->inStream == NULL) return -1;
if(is->audio_st == NULL) return -1;
AVPacket *pkt_temp = &is->audio_pkt_temp;
AVPacket *pkt = &is->audio_pkt;
AVCodecContext *dec = is->audio_st->codec;
int len1, len2, data_size, resampled_data_size;
int64_t dec_channel_layout;
int got_frame;
double pts;
int new_packet = 0;
int flush_complete = 0;
int wanted_nb_samples;
for (;;) {
/* NOTE: the audio packet can contain several frames */
while (pkt_temp->size > 0 || (!pkt_temp->data && new_packet)) {
if (!is->frame) {
if (!(is->frame = avcodec_alloc_frame()))
return AVERROR(ENOMEM);
} else
avcodec_get_frame_defaults(is->frame);
if (!is->playing)
return -1;
if (flush_complete)
break;
new_packet = 0;
len1 = avcodec_decode_audio4(dec, is->frame, &got_frame, pkt_temp);
if (len1 < 0) {
/* if error, we skip the frame */
pkt_temp->size = 0;
break;
}
//printf("avcodec_decode_audio4: %i\n", len1);
pkt_temp->data += len1;
pkt_temp->size -= len1;
if (!got_frame) {
/* stop sending empty packets if the decoder is finished */
if (!pkt_temp->data && dec->codec->capabilities & CODEC_CAP_DELAY)
flush_complete = 1;
continue;
}
data_size = av_samples_get_buffer_size(NULL, dec->channels,
is->frame->nb_samples,
dec->sample_fmt, 1);
dec_channel_layout =
(dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ?
dec->channel_layout : av_get_default_channel_layout(dec->channels);
wanted_nb_samples = synchronize_audio(is, is->frame->nb_samples);
if (dec->sample_fmt != is->audio_src.fmt ||
dec_channel_layout != is->audio_src.channel_layout ||
dec->sample_rate != is->audio_src.freq ||
(wanted_nb_samples != is->frame->nb_samples && !is->swr_ctx)) {
swr_free(&is->swr_ctx);
is->swr_ctx = swr_alloc_set_opts(NULL,
is->audio_tgt.channel_layout, is->audio_tgt.fmt, is->audio_tgt.freq,
dec_channel_layout, dec->sample_fmt, dec->sample_rate,
0, NULL);
if (!is->swr_ctx || swr_init(is->swr_ctx) < 0) {
fprintf(stderr, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels,
is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);
break;
}
is->audio_src.channel_layout = dec_channel_layout;
is->audio_src.channels = dec->channels;
is->audio_src.freq = dec->sample_rate;
is->audio_src.fmt = dec->sample_fmt;
/*printf("conversion of %d Hz %s %d channels to %d Hz %s %d channels!\n",
dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels,
is->audio_tgt.freq, av_get_sample_fmt_name(is->audio_tgt.fmt), is->audio_tgt.channels);*/
}
if (is->swr_ctx) {
const uint8_t **in = (const uint8_t **)is->frame->extended_data;
uint8_t *out[] = {is->audio_buf2};
int out_count = sizeof(is->audio_buf2) / is->audio_tgt.channels / av_get_bytes_per_sample(is->audio_tgt.fmt);
if (wanted_nb_samples != is->frame->nb_samples) {
if (swr_set_compensation(is->swr_ctx, (wanted_nb_samples - is->frame->nb_samples) * is->audio_tgt.freq / dec->sample_rate,
wanted_nb_samples * is->audio_tgt.freq / dec->sample_rate) < 0) {
fprintf(stderr, "swr_set_compensation() failed\n");
break;
}
}
len2 = swr_convert(is->swr_ctx, out, out_count, in, is->frame->nb_samples);
if (len2 < 0) {
fprintf(stderr, "swr_convert() failed\n");
break;
}
if (len2 == out_count) {
fprintf(stderr, "warning: audio buffer is probably too small\n");
swr_init(is->swr_ctx);
}
is->audio_buf = is->audio_buf2;
resampled_data_size = len2 * is->audio_tgt.channels * av_get_bytes_per_sample(is->audio_tgt.fmt);
} else {
is->audio_buf = is->frame->data[0];
resampled_data_size = data_size;
}
if(volumeAdjustNeeded(is)) {
for(size_t i = 0; i < resampled_data_size / 2; ++i) {
int16_t* sampleAddr = (int16_t*) is->audio_buf + i;
int32_t sample = *sampleAddr; // TODO: endian swap?
float sampleFloat = sample / ((float) 0x8000);
sampleFloat *= is->volume;
sampleFloat *= is->curSongGainFactor;
sampleFloat = smoothClip(&is->volumeSmoothClip, sampleFloat);
if(sampleFloat < -1) sampleFloat = -1;
if(sampleFloat > 1) sampleFloat = 1;
sample = sampleFloat * (float) 0x8000;
if(sample < -0x8000) sample = -0x8000;
if(sample > 0x7fff) sample = 0x7fff;
*sampleAddr = (int16_t) sample; // TODO: endian swap?
}
}
/* if no pts, then compute it */
pts = is->audio_clock;
*pts_ptr = pts;
is->audio_clock += (double)data_size /
(dec->channels * dec->sample_rate * av_get_bytes_per_sample(dec->sample_fmt));
/*{
static double last_clock;
printf("audio: delay=%0.3f clock=%0.3f pts=%0.3f\n",
is->audio_clock - last_clock,
is->audio_clock, pts);
last_clock = is->audio_clock;
}*/
return resampled_data_size;
}
/* free the current packet */
av_free_packet(pkt);
memset(pkt_temp, 0, sizeof(*pkt_temp));
if (!is->playing /* || is->audioq.abort_request */) {
return -1;
}
/* read next packet */
/*if ((new_packet = packet_queue_get(&is->audioq, pkt, 1)) < 0)
return -1;
if (pkt->data == flush_pkt.data) {
avcodec_flush_buffers(dec);
flush_complete = 0;
}
*/
if(is->do_flush) {
avcodec_flush_buffers(dec);
flush_complete = 0;
is->do_flush = 0;
}
while(1) {
int ret = av_read_frame(is->inStream, pkt);
if (ret < 0) {
//if (ic->pb && ic->pb->error)
// printf("av_read_frame error\n");
int eof = 0;
if (ret == AVERROR_EOF || url_feof(is->inStream->pb))
eof = 1;
if(eof && is->nextSongOnEof) {
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PlayerObject* player = is;
if(player->dict) {
Py_INCREF(player->dict);
PyObject* onSongFinished = PyDict_GetItemString(player->dict, "onSongFinished");
if(onSongFinished && onSongFinished != Py_None) {
Py_INCREF(onSongFinished);
PyObject* kwargs = PyDict_New();
assert(kwargs);
if(player->curSong)
PyDict_SetItemString(kwargs, "song", player->curSong);
PyObject* retObj = PyEval_CallObjectWithKeywords(onSongFinished, NULL, kwargs);
Py_XDECREF(retObj);
// errors are not fatal from the callback, so handle it now and go on
if(PyErr_Occurred())
PyErr_Print();
Py_DECREF(kwargs);
Py_DECREF(onSongFinished);
}
Py_DECREF(player->dict);
}
// switch to next song
player_getNextSong(is, 0);
if(PyErr_Occurred())
PyErr_Print();
PyGILState_Release(gstate);
}
return -1;
}
if(pkt->stream_index == is->audio_stream)
break;
av_free_packet(pkt);
}
*pkt_temp = *pkt;
/* if update the audio clock with the pts */
if (pkt->pts != AV_NOPTS_VALUE) {
is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts;
}
}
}
// called from paStreamCallback
static
int player_fillOutStream(PlayerObject* player, uint8_t* stream, unsigned long len) {