-
Notifications
You must be signed in to change notification settings - Fork 1
/
pareceive.c
1371 lines (1147 loc) · 35 KB
/
pareceive.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
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <pulse/pulseaudio.h>
#include "libavformat/avio.h"
#include "libavformat/avformat.h"
#include "libswresample/swresample.h"
#include "libavcodec/avcodec.h"
static char *indevice = NULL;
static char *outdevice = NULL;
static pa_context *context = NULL;
static pa_stream *instream = NULL;
static pa_stream *outstream = NULL;
static pa_mainloop_api *mainloop_api = NULL;
#define SILENCE_CHECK_SIZE 12288
static void *inbuffer = NULL;
static size_t inbuffer_length = 0, inbuffer_index = 0;
static void *outbuffer = NULL;
static size_t outbuffer_length = 0, outbuffer_index = 0;
static pa_io_event* stdio_event = NULL;
uint32_t tlength = 0;
static int verbose = 1;
static pa_sample_spec in_sample_spec =
{
.format = PA_SAMPLE_S16LE,
.rate = 48000,
.channels = 2
};
pa_sample_spec out_sample_spec;
const char* input_device_name = "stdin";
#define PA_MAX_BUF (1024*1024*96)
#define MAX_STDIN_READ 16384
size_t stdin_fragsize = 0;
static pa_stream_flags_t inflags = PA_STREAM_FIX_RATE | PA_STREAM_FIX_FORMAT | PA_STREAM_NO_REMIX_CHANNELS | PA_STREAM_NO_REMAP_CHANNELS | PA_STREAM_VARIABLE_RATE | PA_STREAM_DONT_MOVE | PA_STREAM_START_UNMUTED | PA_STREAM_PASSTHROUGH | PA_STREAM_ADJUST_LATENCY;
static pa_stream_flags_t outflags = PA_STREAM_ADJUST_LATENCY;
enum state {NOSIGNAL, PCM, IEC61937} state=NOSIGNAL;
static AVFormatContext *avformatcontext = NULL;
static AVCodecContext *avcodeccontext = NULL;
static AVFrame *avframe;
static AVPacket *pkt;
static SwrContext *swrcontext = NULL;
enum AVSampleFormat swroutformat = AV_SAMPLE_FMT_NONE;
size_t out_bytes_per_sample = 4;
/* A shortcut for terminating the application */
static void quit(int ret)
{
assert(mainloop_api);
mainloop_api->quit(mainloop_api, ret);
}
/* Connection draining complete */
static void context_drain_complete(pa_context *c, void *userdata)
{
pa_context_disconnect(c);
}
/* Start connection draining */
static void start_context_drain(pa_context *c)
{
pa_operation *o = NULL;
if (verbose)
fprintf(stderr, "Draining connection to server.\n");
if (!(o = pa_context_drain(c, context_drain_complete, NULL)))
pa_context_disconnect(c);
else
{
pa_operation_unref(o);
}
}
/* Stream draining complete */
static void stream_drain_complete(pa_stream *s, int success, void *userdata)
{
if (!success)
{
fprintf(stderr, "Failed to drain stream: %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
}
if (verbose)
fprintf(stderr, "Playback stream drained.\n");
pa_stream_disconnect(s);
pa_stream_unref(s);
if(s == outstream)
{
outstream = NULL;
if (!instream && !stdio_event)
start_context_drain(context);
}
}
/* Start draining */
static void start_drain(pa_stream *s)
{
pa_operation *o;
if(verbose)
fprintf(stderr, "Draining output stream\n");
if(!s && !outstream)
{
fprintf(stderr, "The output stream has not been created\n");
if (!instream && !stdio_event)
start_context_drain(context);
return;
}
if(pa_stream_get_state(s) == PA_STREAM_CREATING)
{
fprintf(stderr, "The output stream is still being created\n");
return;
}
pa_stream_set_write_callback(s, NULL, NULL);
if (!(o = pa_stream_drain(s, stream_drain_complete, NULL)))
{
fprintf(stderr, "pa_stream_drain(): %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
return;
}
pa_operation_unref(o);
}
/* Updating stream timing info complete */
static void stream_timing_complete(pa_stream *s, int success, void *userdata)
{
if (!success)
{
fprintf(stderr, "Failed to update timing info for the stream: %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
}
if(verbose)
{
pa_usec_t r_usec;
int negative;
int r;
if(!(r=pa_stream_get_latency(s, &r_usec, &negative)))
fprintf(stderr, "%s stream latency %s%zu usec\n", (s==instream?"Input":"Output"), (negative?"-":""), (size_t)r_usec);
else
fprintf(stderr, "pa_stream_get_latency=%d\n", r);
}
}
static void stream_set_buffer_attr_callback(pa_stream *s, int success, void *userdata)
{
assert(s);
const pa_buffer_attr *a;
if(!success)
{
fprintf(stderr, "Failed to set buffer_attr: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
quit(1);
return;
}
if (!(a = pa_stream_get_buffer_attr(s)))
fprintf(stderr, "pa_stream_get_buffer_attr() failed: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
#ifdef DEBUG_LATENCY
else
{
if(s==instream)
fprintf(stderr, "New inbuffer metrics: maxlength=%u, fragsize=%u\n", a->maxlength, a->fragsize);
else
fprintf(stderr, "New outbuffer metrics: maxlength=%u, tlength=%u, prebuf=%u, minreq=%u\n", a->maxlength, a->tlength, a->prebuf, a->minreq);
}
#endif
}
/* This routine is called whenever the stream state changes */
static void stream_state_callback(pa_stream *s, void *userdata)
{
assert(s);
const pa_buffer_attr *a;
char cmt[PA_CHANNEL_MAP_SNPRINT_MAX], sst[PA_SAMPLE_SPEC_SNPRINT_MAX];
switch (pa_stream_get_state(s))
{
case PA_STREAM_CREATING:
break;
case PA_STREAM_TERMINATED:
if(verbose)
fprintf(stderr, "Stream terminated.\n");
break;
case PA_STREAM_READY:
fprintf(stderr, "Stream successfully created.\n");
if (!(a = pa_stream_get_buffer_attr(s)))
fprintf(stderr, "pa_stream_get_buffer_attr() failed: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
#ifdef DEBUG_LATENCY
else
{
if(s==instream)
fprintf(stderr, "Buffer metrics: maxlength=%u, fragsize=%u\n", a->maxlength, a->fragsize);
else
fprintf(stderr, "Buffer metrics: maxlength=%u, tlength=%u, prebuf=%u, minreq=%u\n", a->maxlength, a->tlength, a->prebuf, a->minreq);
}
#endif
fprintf(stderr, "Using sample spec '%s', channel map '%s'.\n",
pa_sample_spec_snprint(sst, sizeof(sst), pa_stream_get_sample_spec(s)),
pa_channel_map_snprint(cmt, sizeof(cmt), pa_stream_get_channel_map(s)));
fprintf(stderr, "Connected to device %s (%u, %ssuspended).\n",
pa_stream_get_device_name(s),
pa_stream_get_device_index(s),
pa_stream_is_suspended(s) ? "" : "not ");
if(s == instream)
{
pa_operation *o;
in_sample_spec = *pa_stream_get_sample_spec(s);
input_device_name = pa_stream_get_device_name(s);
if (!(o = pa_stream_update_timing_info(s, stream_timing_complete, NULL)))
{
fprintf(stderr, "pa_stream_update_timing_info(): %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
return;
}
pa_operation_unref(o);
}
break;
case PA_STREAM_FAILED:
default:
fprintf(stderr, "Stream error: %s\n", pa_strerror(pa_context_errno(pa_stream_get_context(s))));
quit(1);
}
}
static void stream_suspended_callback(pa_stream *s, void *userdata)
{
assert(s);
if (verbose)
{
if (pa_stream_is_suspended(s))
fprintf(stderr, "Stream device suspended.\n");
else
fprintf(stderr, "Stream device resumed.\n");
}
}
static void stream_underflow_callback(pa_stream *s, void *userdata)
{
assert(s);
if (verbose)
fprintf(stderr, "Stream underrun.\n");
}
static void stream_overflow_callback(pa_stream *s, void *userdata)
{
assert(s);
if (verbose)
fprintf(stderr, "Stream overrun.\n");
}
static void stream_started_callback(pa_stream *s, void *userdata)
{
assert(s);
if (verbose)
fprintf(stderr, "Stream started.\n");
if (!instream && !stdio_event)
start_drain(s);
else
{
pa_operation *o;
if (!(o = pa_stream_update_timing_info(s, stream_timing_complete, NULL)))
{
fprintf(stderr, "pa_stream_update_timing_info(): %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
return;
}
pa_operation_unref(o);
}
}
static void stream_moved_callback(pa_stream *s, void *userdata)
{
pa_operation *o;
assert(s);
if (verbose)
fprintf(stderr, "Stream moved to device %s (%u, %ssuspended).\n", pa_stream_get_device_name(s), pa_stream_get_device_index(s), pa_stream_is_suspended(s) ? "" : "not ");
if(s == instream)
{
in_sample_spec = *pa_stream_get_sample_spec(s);
input_device_name = pa_stream_get_device_name(s);
}
if (!(o = pa_stream_update_timing_info(s, stream_timing_complete, NULL)))
{
fprintf(stderr, "pa_stream_update_timing_info(): %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
return;
}
pa_operation_unref(o);
}
static void stream_buffer_attr_callback(pa_stream *s, void *userdata)
{
pa_operation *o;
assert(s);
if (verbose)
fprintf(stderr, "Stream buffer attributes changed.\n");
if (!(o = pa_stream_update_timing_info(s, stream_timing_complete, NULL)))
{
fprintf(stderr, "pa_stream_update_timing_info(): %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
return;
}
pa_operation_unref(o);
}
static void stream_event_callback(pa_stream *s, const char *name, pa_proplist *pl, void *userdata)
{
char *t;
assert(s);
assert(name);
assert(pl);
t = pa_proplist_to_string_sep(pl, ", ");
fprintf(stderr, "Got event '%s', properties '%s'\n", name, t);
pa_xfree(t);
}
/* Write some data to the stream */
static void do_stream_write(pa_stream *s, size_t length)
{
size_t l;
assert(s);
size_t out_frame_size = pa_frame_size(&out_sample_spec);
if (!outbuffer || !outbuffer_length || !length || !(l = ((length < outbuffer_length ? length : outbuffer_length) / out_frame_size) * out_frame_size))
return;
if (pa_stream_write(s, (uint8_t*) outbuffer + outbuffer_index, l, NULL, 0, PA_SEEK_RELATIVE) < 0)
{
fprintf(stderr, "pa_stream_write() failed: %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
return;
}
outbuffer_length -= l;
outbuffer_index += l;
if (!outbuffer_length)
{
pa_xfree(outbuffer);
outbuffer = NULL;
outbuffer_index = outbuffer_length = 0;
}
else if(outbuffer_index > 4*1024)
{
memmove((uint8_t*) outbuffer, (uint8_t*) outbuffer + outbuffer_index, outbuffer_length);
outbuffer = pa_xrealloc(outbuffer, outbuffer_length);
outbuffer_index = 0;
}
}
/* This is called whenever new data may be written to the stream */
static void stream_write_callback(pa_stream *s, size_t length, void *userdata)
{
assert(s);
if (!length || !outbuffer)
return;
if(tlength && outbuffer_length > tlength*2)
{
#ifdef DEBUG_LATENCY
printf("Outbuffer is too long (%zu > %u*2). Flushing it to reduce latency. Sorry for that!\n", outbuffer_length, tlength);
#endif
outbuffer_index += outbuffer_length - tlength;
outbuffer_length = tlength;
#ifdef DEBUG_LATENCY
printf("outbuffer_length = %zu\n", outbuffer_length);
#endif
}
do_stream_write(s, length);
}
/* Maps FFMpeg sample format to PA sample format */
enum pa_sample_format map_sample_format(enum AVSampleFormat format)
{
const int isbe = (*(uint16_t *)"\0\xff" < 0x100) ? 1 : 0;
switch(av_get_packed_sample_fmt(format))
{
case AV_SAMPLE_FMT_U8:
return PA_SAMPLE_U8;
case AV_SAMPLE_FMT_S16:
return PA_SAMPLE_S16LE + isbe;
case AV_SAMPLE_FMT_S32:
return PA_SAMPLE_S32LE + isbe;
case AV_SAMPLE_FMT_FLT:
return PA_SAMPLE_FLOAT32LE + isbe;
case AV_SAMPLE_FMT_DBL:
fprintf(stderr, "PulseAudio does not support double float sample formats\n");
default:
fprintf(stderr, "Unexpected sample format %s\n", av_get_sample_fmt_name(format));
}
return PA_SAMPLE_INVALID;
}
void map_channel_layout(pa_channel_map* channel_map, AVChannelLayout* channel_layout)
{
pa_channel_map_init(channel_map);
channel_map->channels = channel_layout->nb_channels;
int i;
for(i = 0; i < channel_map->channels; i++)
{
switch(av_channel_layout_channel_from_index(channel_layout, i))
{
case AV_CHAN_FRONT_LEFT:
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_LEFT;
break;
case AV_CHAN_FRONT_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_RIGHT;
break;
case AV_CHAN_FRONT_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_CENTER;
break;
case AV_CHAN_LOW_FREQUENCY:
channel_map->map[i] = PA_CHANNEL_POSITION_LFE;
break;
case AV_CHAN_BACK_LEFT:
channel_map->map[i] = PA_CHANNEL_POSITION_REAR_LEFT;
break;
case AV_CHAN_BACK_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_REAR_RIGHT;
break;
case AV_CHAN_FRONT_LEFT_OF_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
break;
case AV_CHAN_FRONT_RIGHT_OF_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
break;
case AV_CHAN_BACK_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_REAR_CENTER;
break;
case AV_CHAN_SIDE_LEFT:
channel_map->map[i] = PA_CHANNEL_POSITION_SIDE_LEFT;
break;
case AV_CHAN_SIDE_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
case AV_CHAN_TOP_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_CENTER;
break;
case AV_CHAN_TOP_FRONT_LEFT:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_FRONT_LEFT;
break;
case AV_CHAN_TOP_FRONT_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_FRONT_CENTER;
break;
case AV_CHAN_TOP_FRONT_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_FRONT_RIGHT;
break;
case AV_CHAN_TOP_BACK_LEFT:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_REAR_LEFT;
break;
case AV_CHAN_TOP_BACK_CENTER:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_REAR_CENTER;
break;
case AV_CHAN_TOP_BACK_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
break;
case AV_CHAN_STEREO_LEFT: //Stereo downmix
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_LEFT;
break;
case AV_CHAN_STEREO_RIGHT: //See AV_CHAN_STEREO_LEFT
channel_map->map[i] = PA_CHANNEL_POSITION_FRONT_RIGHT;
break;
case AV_CHAN_WIDE_LEFT: // PA does not have wide speakers, so map them to side instead. If both of your setup and source have both wide and side speakers, you may want to change this to PA_CHANNEL_POSITION_AUX*. And if this is the case, please also send me a postcard.
channel_map->map[i] = PA_CHANNEL_POSITION_SIDE_LEFT;
break;
case AV_CHAN_WIDE_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
case AV_CHAN_SURROUND_DIRECT_LEFT:
channel_map->map[i] = PA_CHANNEL_POSITION_SIDE_LEFT;
break;
case AV_CHAN_SURROUND_DIRECT_RIGHT:
channel_map->map[i] = PA_CHANNEL_POSITION_SIDE_RIGHT;
break;
case AV_CHAN_LOW_FREQUENCY_2:
channel_map->map[i] = PA_CHANNEL_POSITION_LFE;
break;
default:
char channel_name[256];
char channel_layout_name[256];
if (av_channel_name(channel_name, sizeof(channel_name), av_channel_layout_channel_from_index(channel_layout, i)) >= sizeof(channel_name))
sprintf(channel_name, "Unknown");
if (av_channel_layout_describe(channel_layout, channel_layout_name, sizeof(channel_layout_name)) >= sizeof(channel_layout_name))
sprintf(channel_layout_name, "Unknown");
fprintf(stderr, "Unexpected channel %d position %s for layout %s\n", i, channel_name, channel_layout_name);
channel_map->map[i] = PA_CHANNEL_POSITION_INVALID;
}
}
}
void open_output_stream(void)
{
pa_channel_map out_channel_map;
pa_buffer_attr buffer_attr;
assert(context);
assert(!outstream);
if(state == IEC61937)
{
out_sample_spec.format = map_sample_format(swroutformat);
out_sample_spec.rate = avcodeccontext->sample_rate;
map_channel_layout(&out_channel_map, &avcodeccontext->ch_layout);
out_sample_spec.channels = out_channel_map.channels;
tlength = avformatcontext->pb->buffer_size / 4 * out_bytes_per_sample * 2;
}
else
{
out_sample_spec.format = in_sample_spec.format;
out_sample_spec.rate = in_sample_spec.rate;
out_sample_spec.channels = in_sample_spec.channels;
if (instream)
{
memcpy(&out_channel_map, pa_stream_get_channel_map(instream), sizeof(pa_channel_map));
tlength = pa_stream_get_buffer_attr(instream)->fragsize;
}
else
{
pa_channel_map_init(&out_channel_map);
out_channel_map.channels = 2;
out_channel_map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;
out_channel_map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;
tlength = 16384;
}
}
fprintf(stderr, "Setting target output latency to %zu usec (%u bytes)\n", (size_t)pa_bytes_to_usec(tlength, &out_sample_spec), tlength);
buffer_attr.fragsize = (uint32_t) -1;
buffer_attr.maxlength = (uint32_t) -1;
buffer_attr.minreq = (uint32_t) -1;
buffer_attr.prebuf = (uint32_t) -1;
buffer_attr.tlength = tlength;
pa_proplist *proplist = pa_proplist_new();
if (!proplist) {
fprintf(stderr, "pa_proplist_new() failed\n");
quit(1);
}
pa_proplist_sets(proplist, PA_PROP_MEDIA_ROLE, "video");
if (!(outstream = pa_stream_new_with_proplist(context, "pareceive output stream", &out_sample_spec, &out_channel_map, proplist)))
{
fprintf(stderr, "pa_stream_new_with_proplist() failed: %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
}
pa_proplist_free(proplist);
pa_stream_set_state_callback(outstream, stream_state_callback, NULL);
pa_stream_set_write_callback(outstream, stream_write_callback, NULL);
pa_stream_set_suspended_callback(outstream, stream_suspended_callback, NULL);
pa_stream_set_moved_callback(outstream, stream_moved_callback, NULL);
pa_stream_set_underflow_callback(outstream, stream_underflow_callback, NULL);
pa_stream_set_overflow_callback(outstream, stream_overflow_callback, NULL);
pa_stream_set_started_callback(outstream, stream_started_callback, NULL);
pa_stream_set_event_callback(outstream, stream_event_callback, NULL);
pa_stream_set_buffer_attr_callback(outstream, stream_buffer_attr_callback, NULL);
if (pa_stream_connect_playback(outstream, outdevice, &buffer_attr, outflags, NULL, NULL) < 0)
{
fprintf(stderr, "pa_stream_connect_playback() failed: %s\n", pa_strerror(pa_context_errno(context)));
quit(1);
}
}
static int readFunction(void* opaque, uint8_t* buf, int buf_size)
{
size_t l = buf_size;
if (!inbuffer)
return AVERROR_EOF;
if (inbuffer_length < l)
return AVERROR_EOF;
memcpy(buf, (uint8_t*) inbuffer + inbuffer_index, l);
inbuffer_length -= (uint32_t) l;
inbuffer_index += (uint32_t) l;
if (!inbuffer_length)
{
pa_xfree(inbuffer);
inbuffer = NULL;
inbuffer_length = inbuffer_index = 0;
}
else if(inbuffer_index > 4*1024)
{
memmove((uint8_t*) inbuffer, (uint8_t*) inbuffer + inbuffer_index, inbuffer_length);
inbuffer = pa_xrealloc(inbuffer, inbuffer_length);
inbuffer_index = 0;
}
return l;
}
void print_averror(const char *str, int err)
{
char errbuf[128];
const char *errbuf_ptr = errbuf;
if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
errbuf_ptr = strerror(AVUNERROR(err));
fprintf(stderr, "%s: %s\n", str, errbuf_ptr);
}
void set_instream_fragsize(uint32_t fragsize)
{
fprintf(stderr, "Setting target input latency to %zu usec (%u bytes)\n", (size_t)pa_bytes_to_usec(fragsize, &in_sample_spec), fragsize);
if(instream)
{
pa_buffer_attr buffer_attr;
memcpy(&buffer_attr, pa_stream_get_buffer_attr(instream), sizeof(pa_buffer_attr));
buffer_attr.fragsize = fragsize;
pa_operation_unref(pa_stream_set_buffer_attr(instream, &buffer_attr, stream_set_buffer_attr_callback, NULL));
}
else
{
stdin_fragsize = fragsize == (uint32_t) -1 ? MAX_STDIN_READ : fragsize;
if(stdin_fragsize > MAX_STDIN_READ)
stdin_fragsize = MAX_STDIN_READ;
}
}
void set_state(enum state newstate)
{
enum state oldstate = state;
if(oldstate == newstate)
return;
if (outstream)
{
if(pa_stream_get_state(outstream) == PA_STREAM_READY)
stream_write_callback(outstream, pa_stream_writable_size(outstream), NULL);
pa_stream_set_write_callback(outstream, NULL, NULL);
start_drain(outstream);
outstream = NULL;
out_sample_spec = in_sample_spec;
fprintf(stderr, "Closed output stream\n");
}
if (outbuffer)
{
pa_xfree(outbuffer);
outbuffer = NULL;
outbuffer_index = outbuffer_length = 0;
}
switch(oldstate)
{
case NOSIGNAL:
break;
case PCM:
break;
case IEC61937:
if(avformatcontext)
{
av_free(avformatcontext->pb->buffer);
av_free(avformatcontext->pb);
avformat_close_input(&avformatcontext);
avcodec_free_context(&avcodeccontext);
swr_free(&swrcontext);
avformat_free_context(avformatcontext);
avformatcontext = NULL;
out_bytes_per_sample = 4;
}
if(inbuffer)
{
if(newstate == PCM)
{
outbuffer = pa_xrealloc(outbuffer, outbuffer_index + outbuffer_length + inbuffer_length);
memcpy((uint8_t*) outbuffer + outbuffer_index + outbuffer_length, (uint8_t*) inbuffer + inbuffer_index, inbuffer_length);
outbuffer_length += inbuffer_length;
}
pa_xfree(inbuffer);
inbuffer = NULL;
inbuffer_index = inbuffer_length = 0;
}
break;
}
state = newstate;
switch(newstate)
{
case NOSIGNAL:
set_instream_fragsize(SILENCE_CHECK_SIZE);
break;
case PCM:
fprintf(stderr, "Playing PCM\n");
open_output_stream();
break;
case IEC61937:
break;
}
}
#define SPDIF_MAX_OFFSET 16384*10
// returns 0 if data is too small for examination, 1 if validation fails and a block size (aka offset) if validation is successful
size_t iec61937_validate(const uint8_t* data, size_t length)
{
static const uint32_t magic = 0x4E1FF872;
size_t firstmagic, secondmagic;
for(firstmagic = 0; firstmagic < length-sizeof(uint32_t)+1; firstmagic++)
if(*(uint32_t*)(data+firstmagic) == magic)
break;
if(firstmagic == length-sizeof(uint32_t)+1)
{
if(length < SPDIF_MAX_OFFSET)
return 0;
else
return 1;
}
for(secondmagic = firstmagic + ((*(uint16_t*)(data+firstmagic+6))>>3) + 8; secondmagic < length-sizeof(uint32_t)+1; secondmagic++)
if(*(uint32_t*)(data+secondmagic) == magic)
break;
if(secondmagic == length-sizeof(uint32_t)+1)
{
if(length < SPDIF_MAX_OFFSET * 2)
return 0;
else
return 1;
}
secondmagic -= firstmagic;
if(secondmagic > SPDIF_MAX_OFFSET)
return 1;
if(length < secondmagic * 2)
return 0;
return secondmagic;
}
//returns 1 if magic found, 0 if not
int iec61937_suspect(const uint8_t* data, size_t length)
{
static const uint32_t magic = 0x4E1FF872;
size_t firstmagic;
for(firstmagic = 0; firstmagic < length-sizeof(uint32_t)+1; firstmagic++)
if(*(uint32_t*)(data+firstmagic) == magic)
break;
return (firstmagic == length-sizeof(uint32_t)+1) ? 0 : 1;
}
/* Process new data */
static void decode_data(const void *data, size_t length, void *userdata)
{
int i=0;
static size_t prevextralength = 0;
assert(data);
assert(length > 0);
if(state==NOSIGNAL)
{
for(i=0; i<length/sizeof(uint32_t); i++)
if(((uint32_t*) data)[i])
break;
if(i<length/sizeof(uint32_t))
set_state(IEC61937);
}
else
{
static pa_usec_t silence=0;
for(i=0; i<length/sizeof(uint32_t); i++)
if(((uint32_t*) data)[i])
break;
if(i<length/sizeof(uint32_t))
{
silence = 0;
}
else
{
silence+=pa_bytes_to_usec(length, &in_sample_spec);
if(silence > 100000)
{
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
silence=0;
return;
}
}
i=0;
}
if(state==IEC61937)
{
inbuffer = pa_xrealloc(inbuffer, inbuffer_index + inbuffer_length + length - i*sizeof(uint32_t));
memcpy((uint8_t*) inbuffer + inbuffer_index + inbuffer_length, (uint32_t*) data + i, length - i*sizeof(uint32_t));
inbuffer_length += length - i*sizeof(uint32_t);
if(!avformatcontext)
{
size_t block_size = iec61937_validate((uint8_t*) inbuffer + inbuffer_index, inbuffer_length);
if (block_size == 0)
{
#ifdef DEBUG_LATENCY
fprintf(stderr, "Buffer is too small, waiting for more data\n");
#endif
return;
}
else if(block_size == 1)
{
fprintf(stderr, "IEC61937 validation failed\n");
set_state(PCM);
return;
}
#ifdef DEBUG_LATENCY
fprintf(stderr, "block_size=%zu\n", block_size);
#endif
if(inbuffer_length < block_size * 3)
{
#ifdef DEBUG_LATENCY
fprintf(stderr, "Buffer is too small, waiting for more data\n");
#endif
return;
}
prevextralength = inbuffer_length;
avformatcontext = avformat_alloc_context();
avformatcontext->pb = avio_alloc_context(av_malloc(block_size), block_size, 0, NULL, readFunction, NULL, NULL);
if( (i = avformat_open_input(&avformatcontext, input_device_name, av_find_input_format("spdif"), NULL)) < 0)
{
print_averror("avformat_open_input", i);
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
return;
}
if( (i=avformat_find_stream_info(avformatcontext, NULL)) < 0)
{
print_averror("avformat_find_stream_info", i);
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
return;
}
//av_dump_format(avformatcontext, 0, input_device_name, 0);
const AVCodec *dec = NULL;
int stream_index = av_find_best_stream(avformatcontext, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
if(stream_index < 0)
{
print_averror("av_find_best_stream", stream_index);
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
return;
}
avcodeccontext = avcodec_alloc_context3(dec);
avcodec_parameters_to_context(avcodeccontext,avformatcontext->streams[stream_index]->codecpar);
if ((i = avcodec_open2(avcodeccontext, dec, NULL)) < 0)
{
print_averror("avcodec_open2", i);
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
return;
}
swroutformat = av_get_packed_sample_fmt(avcodeccontext->sample_fmt);
if(swroutformat == AV_SAMPLE_FMT_DBL)
swroutformat = AV_SAMPLE_FMT_FLT;
if ((i = swr_alloc_set_opts2(&swrcontext,
&avcodeccontext->ch_layout,
swroutformat,
avcodeccontext->sample_rate,
&avcodeccontext->ch_layout,
avcodeccontext->sample_fmt,
avcodeccontext->sample_rate,
0, NULL)) < 0)
{
print_averror("swr_alloc_set_opts2", i);
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
return;
}
swr_init(swrcontext);
out_bytes_per_sample = av_get_bytes_per_sample(swroutformat) * (size_t)avcodeccontext->ch_layout.nb_channels;
pkt->data = NULL;
pkt->size = 0;
set_instream_fragsize(block_size * 2);
open_output_stream();
char buf[256];
avcodec_string(buf, sizeof(buf), avcodeccontext, 0);
fprintf(stderr, "Playing IEC61937: %s\n", buf);
}
}
if(state==IEC61937 && inbuffer_length > avformatcontext->pb->buffer_size * 2)
{
int pcount=0, fcount=0;
while ( inbuffer_length > avformatcontext->pb->buffer_size * 2 && (i = av_read_frame(avformatcontext, pkt)) >= 0)
{
pcount++;
int ret = avcodec_send_packet(avcodeccontext, pkt);
av_packet_unref(pkt);
if(ret<0)
{
print_averror("avcodec_send_packet", ret);
fprintf(stderr, "Playing silence\n");
set_state(NOSIGNAL);
return;
}
while ( (ret = avcodec_receive_frame(avcodeccontext, avframe)) >=0)
{
size_t addlen = swr_get_out_samples(swrcontext, avframe->nb_samples) * out_bytes_per_sample;
outbuffer = pa_xrealloc(outbuffer, outbuffer_index + outbuffer_length + addlen);
uint8_t *outptr = (uint8_t*) outbuffer + outbuffer_length;
outbuffer_length += swr_convert(swrcontext, &outptr, addlen, (const uint8_t **) avframe->extended_data, avframe->nb_samples) * out_bytes_per_sample;
fcount++;
av_frame_unref(avframe);
}