-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
win-dshow-replay.cpp
2306 lines (1893 loc) · 62.3 KB
/
win-dshow-replay.cpp
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 <objbase.h>
#include <obs-module.h>
#include <obs.hpp>
#include <util/dstr.hpp>
#include <util/platform.h>
#include <util/windows/WinHandle.hpp>
#include <util/threading.h>
#include "../win-dshow/libdshowcapture/dshowcapture.hpp"
#include "../win-dshow/ffmpeg-decode.h"
#include "../win-dshow/encode-dstr.hpp"
#include <algorithm>
#include <limits>
#include <set>
#include <string>
#include <vector>
#include "replay.h"
#include "media-io/audio-math.h"
#define MAX_TS_VAR 2000000000ULL
/*
* TODO:
* - handle disconnections and reconnections
* - if device not present, wait for device to be plugged in
*/
#undef min
#undef max
using namespace std;
using namespace DShow;
/* settings defines that will cause errors if there are typos */
#define VIDEO_DEVICE_ID "video_device_id"
#define RES_TYPE "res_type"
#define RESOLUTION "resolution"
#define FRAME_INTERVAL "frame_interval"
#define VIDEO_FORMAT "video_format"
#define LAST_VIDEO_DEV_ID "last_video_device_id"
#define LAST_RESOLUTION "last_resolution"
#define BUFFERING_VAL "buffering"
#define FLIP_IMAGE "flip_vertically"
#define AUDIO_OUTPUT_MODE "audio_output_mode"
#define USE_CUSTOM_AUDIO "use_custom_audio_device"
#define AUDIO_DEVICE_ID "audio_device_id"
#define COLOR_SPACE "color_space"
#define COLOR_RANGE "color_range"
#define DEACTIVATE_WNS "deactivate_when_not_showing"
#define AUTOROTATION "autorotation"
#define HW_DECODE "hw_decode"
#define TEXT_INPUT_NAME obs_module_text("VideoCaptureDevice")
#define TEXT_DEVICE obs_module_text("Device")
#define TEXT_CONFIG_VIDEO obs_module_text("ConfigureVideo")
#define TEXT_CONFIG_XBAR obs_module_text("ConfigureCrossbar")
#define TEXT_RES_FPS_TYPE obs_module_text("ResFPSType")
#define TEXT_CUSTOM_RES obs_module_text("ResFPSType.Custom")
#define TEXT_PREFERRED_RES obs_module_text("ResFPSType.DevPreferred")
#define TEXT_FPS_MATCHING obs_module_text("FPS.Matching")
#define TEXT_FPS_HIGHEST obs_module_text("FPS.Highest")
#define TEXT_RESOLUTION obs_module_text("Resolution")
#define TEXT_VIDEO_FORMAT obs_module_text("VideoFormat")
#define TEXT_FORMAT_UNKNOWN obs_module_text("VideoFormat.Unknown")
#define TEXT_BUFFERING obs_module_text("Buffering")
#define TEXT_BUFFERING_AUTO obs_module_text("Buffering.AutoDetect")
#define TEXT_BUFFERING_ON obs_module_text("Buffering.Enable")
#define TEXT_BUFFERING_OFF obs_module_text("Buffering.Disable")
#define TEXT_FLIP_IMAGE obs_module_text("FlipVertically")
#define TEXT_AUTOROTATION obs_module_text("Autorotation")
#define TEXT_HW_DECODE obs_module_text("HardwareDecode")
#define TEXT_AUDIO_MODE obs_module_text("AudioOutputMode")
#define TEXT_MODE_CAPTURE obs_module_text("AudioOutputMode.Capture")
#define TEXT_MODE_DSOUND obs_module_text("AudioOutputMode.DirectSound")
#define TEXT_MODE_WAVEOUT obs_module_text("AudioOutputMode.WaveOut")
#define TEXT_CUSTOM_AUDIO obs_module_text("UseCustomAudioDevice")
#define TEXT_AUDIO_DEVICE obs_module_text("AudioDevice")
#define TEXT_ACTIVATE obs_module_text("Activate")
#define TEXT_DEACTIVATE obs_module_text("Deactivate")
#define TEXT_COLOR_SPACE obs_module_text("ColorSpace")
#define TEXT_COLOR_DEFAULT obs_module_text("ColorSpace.Default")
#define TEXT_COLOR_709 obs_module_text("ColorSpace.709")
#define TEXT_COLOR_601 obs_module_text("ColorSpace.601")
#define TEXT_COLOR_2100PQ obs_module_text("ColorSpace.2100PQ")
#define TEXT_COLOR_2100HLG obs_module_text("ColorSpace.2100HLG")
#define TEXT_COLOR_RANGE obs_module_text("ColorRange")
#define TEXT_RANGE_DEFAULT obs_module_text("ColorRange.Default")
#define TEXT_RANGE_PARTIAL obs_module_text("ColorRange.Partial")
#define TEXT_RANGE_FULL obs_module_text("ColorRange.Full")
#define TEXT_DWNS obs_module_text("DeactivateWhenNotShowing")
enum ResType { ResType_Preferred, ResType_Custom };
enum class BufferingType : int64_t { Auto, On, Off };
void ffmpeg_log(void *bla, int level, const char *msg, va_list args)
{
DStr str;
if (level == AV_LOG_WARNING) {
dstr_copy(str, "warning: ");
} else if (level == AV_LOG_ERROR) {
/* only print first of this message to avoid spam */
static bool suppress_app_field_spam = false;
if (strcmp(msg, "unable to decode APP fields: %s\n") == 0) {
if (suppress_app_field_spam)
return;
suppress_app_field_spam = true;
}
dstr_copy(str, "error: ");
} else if (level < AV_LOG_ERROR) {
dstr_copy(str, "fatal: ");
} else {
return;
}
dstr_cat(str, msg);
if (dstr_end(str) == '\n')
dstr_resize(str, str->len - 1);
blogva(LOG_WARNING, str, args);
av_log_default_callback(bla, level, msg, args);
}
class Decoder {
struct ffmpeg_decode decode;
public:
inline Decoder() { memset(&decode, 0, sizeof(decode)); }
inline ~Decoder() { ffmpeg_decode_free(&decode); }
inline operator ffmpeg_decode *() { return &decode; }
inline ffmpeg_decode *operator->() { return &decode; }
};
class CriticalSection {
CRITICAL_SECTION mutex;
public:
inline CriticalSection() { InitializeCriticalSection(&mutex); }
inline ~CriticalSection() { DeleteCriticalSection(&mutex); }
inline operator CRITICAL_SECTION *() { return &mutex; }
};
class CriticalScope {
CriticalSection &mutex;
CriticalScope() = delete;
CriticalScope &operator=(CriticalScope &cs) = delete;
public:
inline CriticalScope(CriticalSection &mutex_) : mutex(mutex_)
{
EnterCriticalSection(mutex);
}
inline ~CriticalScope() { LeaveCriticalSection(mutex); }
};
enum class Action {
None,
Activate,
ActivateBlock,
Deactivate,
Shutdown,
ConfigVideo,
ConfigAudio,
ConfigCrossbar1,
ConfigCrossbar2,
};
static DWORD CALLBACK DShowThread(LPVOID ptr);
struct DShowReplayInput {
struct replay_filter replay_filter;
obs_source_t *source;
Device device;
bool deactivateWhenNotShowing = false;
bool deviceHasAudio = false;
bool deviceHasSeparateAudioFilter = false;
bool flip = false;
bool active = false;
bool autorotation = true;
bool hw_decode = false;
Decoder audio_decoder;
Decoder video_decoder;
VideoConfig videoConfig;
AudioConfig audioConfig;
enum video_colorspace cs;
obs_source_frame2 frame;
obs_source_audio audio;
long lastRotation = 0;
WinHandle semaphore;
WinHandle activated_event;
WinHandle thread;
CriticalSection mutex;
vector<Action> actions;
inline void QueueAction(Action action)
{
CriticalScope scope(mutex);
actions.push_back(action);
ReleaseSemaphore(semaphore, 1, nullptr);
}
inline void QueueActivate(obs_data_t *settings)
{
bool block =
obs_data_get_bool(settings, "synchronous_activate");
QueueAction(block ? Action::ActivateBlock : Action::Activate);
if (block) {
obs_data_erase(settings, "synchronous_activate");
WaitForSingleObject(activated_event, INFINITE);
}
}
inline DShowReplayInput(obs_source_t *source_, obs_data_t *settings)
: source(source_),
device(InitGraph::False)
{
memset(&audio, 0, sizeof(audio));
memset(&frame, 0, sizeof(frame));
memset(&replay_filter, 0, sizeof(replay_filter));
circlebuf_init(&replay_filter.video_frames);
circlebuf_init(&replay_filter.audio_frames);
pthread_mutex_init(&replay_filter.mutex, NULL);
av_log_set_level(AV_LOG_WARNING);
av_log_set_callback(ffmpeg_log);
semaphore = CreateSemaphore(nullptr, 0, 0x7FFFFFFF, nullptr);
if (!semaphore)
throw "Failed to create semaphore";
activated_event = CreateEvent(nullptr, false, false, nullptr);
if (!activated_event)
throw "Failed to create activated_event";
thread =
CreateThread(nullptr, 0, DShowThread, this, 0, nullptr);
if (!thread)
throw "Failed to create thread";
deactivateWhenNotShowing =
obs_data_get_bool(settings, DEACTIVATE_WNS);
if (obs_data_get_bool(settings, "active")) {
bool showing = obs_source_showing(source);
if (!deactivateWhenNotShowing || showing)
QueueActivate(settings);
active = true;
}
}
inline ~DShowReplayInput()
{
{
CriticalScope scope(mutex);
actions.resize(1);
actions[0] = Action::Shutdown;
}
ReleaseSemaphore(semaphore, 1, nullptr);
WaitForSingleObject(thread, INFINITE);
pthread_mutex_lock(&replay_filter.mutex);
free_video_data(&replay_filter);
free_audio_data(&replay_filter);
pthread_mutex_unlock(&replay_filter.mutex);
circlebuf_free(&replay_filter.video_frames);
circlebuf_free(&replay_filter.audio_frames);
pthread_mutex_destroy(&replay_filter.mutex);
}
void OnVideoOutput(obs_source_frame2 *frame);
void OnEncodedVideoData(enum AVCodecID id, unsigned char *data,
size_t size, long long ts);
void OnAudioOutput(obs_source_audio *audio);
void OnEncodedAudioData(enum AVCodecID id, unsigned char *data,
size_t size, long long ts);
void OnReactivate();
void OnVideoData(const VideoConfig &config, unsigned char *data,
size_t size, long long startTime, long long endTime,
long rotation);
void OnAudioData(const AudioConfig &config, unsigned char *data,
size_t size, long long startTime, long long endTime);
bool UpdateVideoConfig(obs_data_t *settings);
bool UpdateAudioConfig(obs_data_t *settings);
void SetActive(bool active);
inline enum video_colorspace GetColorSpace(obs_data_t *settings) const;
inline enum video_range_type GetColorRange(obs_data_t *settings) const;
inline bool Activate(obs_data_t *settings);
inline void Deactivate();
inline void SetupBuffering(obs_data_t *settings);
void DShowLoop();
};
static DWORD CALLBACK DShowThread(LPVOID ptr)
{
DShowReplayInput *dshowInput = (DShowReplayInput *)ptr;
os_set_thread_name("win-dshow: DShowThread");
CoInitialize(nullptr);
dshowInput->DShowLoop();
CoUninitialize();
return 0;
}
static inline void ProcessMessages()
{
MSG msg;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
/* Always keep directshow in a single thread for a given device */
void DShowReplayInput::DShowLoop()
{
while (true) {
DWORD ret = MsgWaitForMultipleObjects(1, &semaphore, false,
INFINITE, QS_ALLINPUT);
if (ret == (WAIT_OBJECT_0 + 1)) {
ProcessMessages();
continue;
} else if (ret != WAIT_OBJECT_0) {
break;
}
Action action = Action::None;
{
CriticalScope scope(mutex);
if (actions.size()) {
action = actions.front();
actions.erase(actions.begin());
}
}
switch (action) {
case Action::Activate:
case Action::ActivateBlock: {
bool block = action == Action::ActivateBlock;
obs_data_t *settings;
settings = obs_source_get_settings(source);
if (!Activate(settings)) {
obs_source_output_video2(source, nullptr);
}
if (block)
SetEvent(activated_event);
obs_data_release(settings);
break;
}
case Action::Deactivate:
Deactivate();
break;
case Action::Shutdown:
device.ShutdownGraph();
return;
case Action::ConfigVideo:
device.OpenDialog(nullptr, DialogType::ConfigVideo);
break;
case Action::ConfigAudio:
device.OpenDialog(nullptr, DialogType::ConfigAudio);
break;
case Action::ConfigCrossbar1:
device.OpenDialog(nullptr, DialogType::ConfigCrossbar);
break;
case Action::ConfigCrossbar2:
device.OpenDialog(nullptr, DialogType::ConfigCrossbar2);
break;
case Action::None:;
}
}
}
#define FPS_HIGHEST 0LL
#define FPS_MATCHING -1LL
template<typename T, typename U, typename V>
static bool between(T &&lower, U &&value, V &&upper)
{
return value >= lower && value <= upper;
}
static bool ResolutionAvailable(const VideoInfo &cap, int cx, int cy)
{
return between(cap.minCX, cx, cap.maxCX) &&
between(cap.minCY, cy, cap.maxCY);
}
#define DEVICE_INTERVAL_DIFF_LIMIT 20
static bool FrameRateAvailable(const VideoInfo &cap, long long interval)
{
return interval == FPS_HIGHEST || interval == FPS_MATCHING ||
between(cap.minInterval - DEVICE_INTERVAL_DIFF_LIMIT, interval,
cap.maxInterval + DEVICE_INTERVAL_DIFF_LIMIT);
}
static long long FrameRateInterval(const VideoInfo &cap,
long long desired_interval)
{
return desired_interval < cap.minInterval
? cap.minInterval
: min(desired_interval, cap.maxInterval);
}
static inline video_format ConvertVideoFormat(VideoFormat format)
{
switch (format) {
case VideoFormat::ARGB:
return VIDEO_FORMAT_BGRA;
case VideoFormat::XRGB:
return VIDEO_FORMAT_BGRX;
case VideoFormat::I420:
return VIDEO_FORMAT_I420;
case VideoFormat::YV12:
return VIDEO_FORMAT_I420;
case VideoFormat::NV12:
return VIDEO_FORMAT_NV12;
case VideoFormat::Y800:
return VIDEO_FORMAT_Y800;
case VideoFormat::YVYU:
return VIDEO_FORMAT_YVYU;
case VideoFormat::YUY2:
return VIDEO_FORMAT_YUY2;
case VideoFormat::UYVY:
return VIDEO_FORMAT_UYVY;
case VideoFormat::HDYC:
return VIDEO_FORMAT_UYVY;
case VideoFormat::P010:
return VIDEO_FORMAT_P010;
default:
return VIDEO_FORMAT_NONE;
}
}
static inline audio_format ConvertAudioFormat(AudioFormat format)
{
switch (format) {
case AudioFormat::Wave16bit:
return AUDIO_FORMAT_16BIT;
case AudioFormat::WaveFloat:
return AUDIO_FORMAT_FLOAT;
default:
return AUDIO_FORMAT_UNKNOWN;
}
}
static inline enum speaker_layout convert_speaker_layout(uint8_t channels)
{
switch (channels) {
case 0:
return SPEAKERS_UNKNOWN;
case 1:
return SPEAKERS_MONO;
case 2:
return SPEAKERS_STEREO;
case 3:
return SPEAKERS_2POINT1;
case 4:
return SPEAKERS_4POINT0;
case 5:
return SPEAKERS_4POINT1;
case 6:
return SPEAKERS_5POINT1;
case 8:
return SPEAKERS_7POINT1;
default:
return SPEAKERS_UNKNOWN;
}
}
static inline uint64_t uint64_diff(uint64_t ts1, uint64_t ts2)
{
return (ts1 < ts2) ? (ts2 - ts1) : (ts1 - ts2);
}
void DShowReplayInput::OnVideoOutput(struct obs_source_frame2 *frame)
{
const uint64_t os_time = obs_get_video_frame_time();
struct obs_source_frame temp_frame;
enum video_range_type range =
resolve_video_range(frame->format, frame->range);
for (size_t i = 0; i < MAX_AV_PLANES; i++) {
temp_frame.data[i] = frame->data[i];
temp_frame.linesize[i] = frame->linesize[i];
}
temp_frame.width = frame->width;
temp_frame.height = frame->height;
temp_frame.timestamp = frame->timestamp;
temp_frame.format = frame->format;
temp_frame.full_range = range == VIDEO_RANGE_FULL;
temp_frame.flip = frame->flip;
memcpy(&temp_frame.color_matrix, &frame->color_matrix,
sizeof(frame->color_matrix));
memcpy(&temp_frame.color_range_min, &frame->color_range_min,
sizeof(frame->color_range_min));
memcpy(&temp_frame.color_range_max, &frame->color_range_max,
sizeof(frame->color_range_max));
struct obs_source_frame *new_frame = obs_source_frame_create(
frame->format, frame->width, frame->height);
new_frame->refs = 1;
obs_source_frame_copy(new_frame, &temp_frame);
const uint64_t timestamp = frame->timestamp;
uint64_t adjusted_time = timestamp + replay_filter.timing_adjust;
if (replay_filter.timing_adjust &&
uint64_diff(os_time, timestamp) < MAX_TS_VAR) {
adjusted_time = timestamp;
replay_filter.timing_adjust = 0;
} else if (uint64_diff(os_time, adjusted_time) > MAX_TS_VAR) {
replay_filter.timing_adjust = os_time - timestamp;
adjusted_time = os_time;
}
new_frame->timestamp = adjusted_time;
pthread_mutex_lock(&replay_filter.mutex);
circlebuf_push_back(&replay_filter.video_frames, &new_frame,
sizeof(struct obs_source_frame *));
struct obs_source_frame *output;
circlebuf_peek_front(&replay_filter.video_frames, &output,
sizeof(struct obs_source_frame *));
uint64_t cur_duration = new_frame->timestamp - output->timestamp;
while (cur_duration > 0 && cur_duration > replay_filter.duration) {
circlebuf_pop_front(&replay_filter.video_frames, NULL,
sizeof(struct obs_source_frame *));
if (os_atomic_dec_long(&output->refs) <= 0) {
obs_source_frame_destroy(output);
output = NULL;
} else {
int t = 0;
}
if (replay_filter.video_frames.size) {
circlebuf_peek_front(&replay_filter.video_frames,
&output,
sizeof(struct obs_source_frame *));
cur_duration = new_frame->timestamp - output->timestamp;
} else {
cur_duration = 0;
}
}
if (replay_filter.mutex)
pthread_mutex_unlock(&replay_filter.mutex);
}
void DShowReplayInput::OnAudioOutput(obs_source_audio *audio)
{
struct obs_audio_data cached;
memset(&cached, 0, sizeof(cached));
cached.frames = audio->frames;
const uint64_t timestamp = cached.timestamp;
uint64_t adjusted_time = timestamp + replay_filter.timing_adjust;
const uint64_t os_time = os_gettime_ns();
if (replay_filter.timing_adjust &&
uint64_diff(os_time, timestamp) < MAX_TS_VAR) {
adjusted_time = timestamp;
replay_filter.timing_adjust = 0;
} else if (uint64_diff(os_time, adjusted_time) > MAX_TS_VAR) {
replay_filter.timing_adjust = os_time - timestamp;
adjusted_time = os_time;
}
cached.timestamp = adjusted_time;
replay_filter.oai.samples_per_sec = audio->samples_per_sec;
replay_filter.oai.speakers = audio->speakers;
replay_filter.oai.format = audio->format;
bool threshold = !replay_filter.trigger_threshold;
for (size_t i = 0; i < MAX_AV_PLANES; i++) {
if (!audio->data[i]) {
cached.data[i] = NULL;
break;
}
const size_t block_size =
get_audio_bytes_per_channel(audio->format) *
get_audio_channels(audio->speakers);
cached.data[i] = (uint8_t *)bmemdup(audio->data[i],
audio->frames * block_size);
const size_t samples = (size_t)audio->frames *
get_audio_channels(audio->speakers);
for (size_t j = 0; !threshold && j < samples; j++) {
if ((audio->format == AUDIO_FORMAT_16BIT ||
audio->format == AUDIO_FORMAT_16BIT_PLANAR) &&
abs(((int16_t *)audio->data[i])[j]) >
replay_filter.threshold * 32768.0)
threshold = true;
if ((audio->format == AUDIO_FORMAT_32BIT ||
audio->format == AUDIO_FORMAT_32BIT_PLANAR) &&
abs(((int32_t *)audio->data[i])[j]) >
replay_filter.threshold * 2147483648.0)
threshold = true;
if ((audio->format == AUDIO_FORMAT_FLOAT ||
audio->format == AUDIO_FORMAT_FLOAT_PLANAR) &&
fabsf(((float *)audio->data[i])[j]) >
replay_filter.threshold)
threshold = true;
}
}
if (replay_filter.trigger_threshold && threshold) {
replay_filter.trigger_threshold(replay_filter.threshold_data);
}
pthread_mutex_lock(&replay_filter.mutex);
circlebuf_push_back(&replay_filter.audio_frames, &cached,
sizeof(cached));
circlebuf_peek_front(&replay_filter.audio_frames, &cached,
sizeof(cached));
uint64_t cur_duration = adjusted_time - cached.timestamp;
while (replay_filter.audio_frames.size > sizeof(cached) &&
cur_duration >= replay_filter.duration + MAX_TS_VAR) {
circlebuf_pop_front(&replay_filter.audio_frames, NULL,
sizeof(cached));
for (size_t i = 0; i < MAX_AV_PLANES; i++)
bfree(cached.data[i]);
memset(&cached, 0, sizeof(cached));
circlebuf_peek_front(&replay_filter.audio_frames, &cached,
sizeof(cached));
cur_duration = adjusted_time - cached.timestamp;
}
if (replay_filter.mutex)
pthread_mutex_unlock(&replay_filter.mutex);
//replay_filter_check(filter);
}
//#define LOG_ENCODED_VIDEO_TS 1
//#define LOG_ENCODED_AUDIO_TS 1
void DShowReplayInput::OnEncodedVideoData(enum AVCodecID id,
unsigned char *data, size_t size,
long long ts)
{
/* If format or hw decode changes, recreate the decoder */
if (ffmpeg_decode_valid(video_decoder) &&
((video_decoder->codec->id != id) ||
(video_decoder->hw != hw_decode))) {
ffmpeg_decode_free(video_decoder);
}
if (!ffmpeg_decode_valid(video_decoder)) {
if (ffmpeg_decode_init(video_decoder, id, hw_decode) < 0) {
blog(LOG_WARNING, "Could not initialize video decoder");
return;
}
}
bool got_output;
bool success = ffmpeg_decode_video(video_decoder, data, size, &ts, cs,
frame.range, &frame, &got_output);
if (!success) {
blog(LOG_WARNING, "Error decoding video");
return;
}
if (got_output) {
frame.timestamp = (uint64_t)ts * 100;
if (flip)
frame.flip = !frame.flip;
#if LOG_ENCODED_VIDEO_TS
blog(LOG_DEBUG, "video ts: %llu", frame.timestamp);
#endif
OnVideoOutput(&frame);
obs_source_output_video2(source, &frame);
}
}
void DShowReplayInput::OnReactivate()
{
SetActive(true);
}
void DShowReplayInput::OnVideoData(const VideoConfig &config,
unsigned char *data, size_t size,
long long startTime, long long endTime,
long rotation)
{
if (autorotation && rotation != lastRotation) {
lastRotation = rotation;
obs_source_set_async_rotation(source, rotation);
}
if (videoConfig.format == VideoFormat::H264) {
OnEncodedVideoData(AV_CODEC_ID_H264, data, size, startTime);
return;
}
if (videoConfig.format == VideoFormat::MJPEG) {
OnEncodedVideoData(AV_CODEC_ID_MJPEG, data, size, startTime);
return;
}
const int cx = config.cx;
const int cy_abs = config.cy_abs;
frame.timestamp = (uint64_t)startTime * 100;
frame.width = config.cx;
frame.height = cy_abs;
frame.format = ConvertVideoFormat(config.format);
frame.flip = flip;
frame.flags = OBS_SOURCE_FRAME_LINEAR_ALPHA;
/* YUV DIBS are always top-down */
if (config.format == VideoFormat::XRGB ||
config.format == VideoFormat::ARGB) {
/* RGB DIBs are bottom-up by default */
if (!config.cy_flip)
frame.flip = !frame.flip;
}
if (videoConfig.format == VideoFormat::XRGB ||
videoConfig.format == VideoFormat::ARGB) {
frame.data[0] = data;
frame.linesize[0] = cx * 4;
} else if (videoConfig.format == VideoFormat::YVYU ||
videoConfig.format == VideoFormat::YUY2 ||
videoConfig.format == VideoFormat::HDYC ||
videoConfig.format == VideoFormat::UYVY) {
frame.data[0] = data;
frame.linesize[0] = cx * 2;
} else if (videoConfig.format == VideoFormat::I420) {
frame.data[0] = data;
frame.data[1] = frame.data[0] + (cx * cy_abs);
frame.data[2] = frame.data[1] + (cx * cy_abs / 4);
frame.linesize[0] = cx;
frame.linesize[1] = cx / 2;
frame.linesize[2] = cx / 2;
} else if (videoConfig.format == VideoFormat::YV12) {
frame.data[0] = data;
frame.data[2] = frame.data[0] + (cx * cy_abs);
frame.data[1] = frame.data[2] + (cx * cy_abs / 4);
frame.linesize[0] = cx;
frame.linesize[1] = cx / 2;
frame.linesize[2] = cx / 2;
} else if (videoConfig.format == VideoFormat::NV12) {
frame.data[0] = data;
frame.data[1] = frame.data[0] + (cx * cy_abs);
frame.linesize[0] = cx;
frame.linesize[1] = cx;
} else if (videoConfig.format == VideoFormat::Y800) {
frame.data[0] = data;
frame.linesize[0] = cx;
} else if (videoConfig.format == VideoFormat::P010) {
frame.data[0] = data;
frame.data[1] = frame.data[0] + (cx * cy_abs) * 2;
frame.linesize[0] = cx * 2;
frame.linesize[1] = cx * 2;
} else {
/* TODO: other formats */
return;
}
OnVideoOutput(&frame);
obs_source_output_video2(source, &frame);
UNUSED_PARAMETER(endTime); /* it's the enndd tiimmes! */
UNUSED_PARAMETER(size);
}
void DShowReplayInput::OnEncodedAudioData(enum AVCodecID id,
unsigned char *data, size_t size,
long long ts)
{
if (!ffmpeg_decode_valid(audio_decoder)) {
if (ffmpeg_decode_init(audio_decoder, id, false) < 0) {
blog(LOG_WARNING, "Could not initialize audio decoder");
return;
}
}
bool got_output = false;
do {
bool success = ffmpeg_decode_audio(audio_decoder, data, size,
&audio, &got_output);
if (!success) {
blog(LOG_WARNING, "Error decoding audio");
return;
}
if (got_output) {
audio.timestamp = (uint64_t)ts * 100;
#if LOG_ENCODED_AUDIO_TS
blog(LOG_DEBUG, "audio ts: %llu", audio.timestamp);
#endif
OnAudioOutput(&audio);
obs_source_output_audio(source, &audio);
} else {
break;
}
ts += int64_t(audio_decoder->frame->nb_samples) * 10000000LL /
int64_t(audio_decoder->frame->sample_rate);
size = 0;
data = nullptr;
} while (got_output);
}
void DShowReplayInput::OnAudioData(const AudioConfig &config,
unsigned char *data, size_t size,
long long startTime, long long endTime)
{
size_t block_size;
if (config.format == AudioFormat::AAC) {
OnEncodedAudioData(AV_CODEC_ID_AAC, data, size, startTime);
return;
} else if (config.format == AudioFormat::AC3) {
OnEncodedAudioData(AV_CODEC_ID_AC3, data, size, startTime);
return;
} else if (config.format == AudioFormat::MPGA) {
OnEncodedAudioData(AV_CODEC_ID_MP2, data, size, startTime);
return;
}
audio.speakers = convert_speaker_layout((uint8_t)config.channels);
audio.format = ConvertAudioFormat(config.format);
audio.samples_per_sec = (uint32_t)config.sampleRate;
audio.data[0] = data;
block_size = get_audio_bytes_per_channel(audio.format) *
get_audio_channels(audio.speakers);
audio.frames = (uint32_t)(size / block_size);
audio.timestamp = (uint64_t)startTime * 100;
if (audio.format != AUDIO_FORMAT_UNKNOWN) {
OnAudioOutput(&audio);
obs_source_output_audio(source, &audio);
}
UNUSED_PARAMETER(endTime);
}
struct PropertiesData {
DShowReplayInput *input;
vector<VideoDevice> devices;
vector<AudioDevice> audioDevices;
bool GetDevice(VideoDevice &device, const char *encoded_id) const
{
DeviceId deviceId;
DecodeDeviceId(deviceId, encoded_id);
for (const VideoDevice &curDevice : devices) {
if (deviceId.name == curDevice.name &&
deviceId.path == curDevice.path) {
device = curDevice;
return true;
}
}
return false;
}
};
static inline bool ConvertRes(int &cx, int &cy, const char *res)
{
return sscanf(res, "%dx%d", &cx, &cy) == 2;
}
static inline bool FormatMatches(VideoFormat left, VideoFormat right)
{
return left == VideoFormat::Any || right == VideoFormat::Any ||
left == right;
}
static inline bool ResolutionValid(const string &res, int &cx, int &cy)
{
if (!res.size())
return false;
return ConvertRes(cx, cy, res.c_str());
}
static inline bool CapsMatch(const VideoInfo &)
{
return true;
}
template<typename... F> static bool CapsMatch(const VideoDevice &dev, F... fs);
template<typename F, typename... Fs>
static inline bool CapsMatch(const VideoInfo &info, F &&f, Fs... fs)
{
return f(info) && CapsMatch(info, fs...);
}
template<typename... F> static bool CapsMatch(const VideoDevice &dev, F... fs)
{
// no early exit, trigger all side effects.
bool match = false;
for (const VideoInfo &info : dev.caps)
if (CapsMatch(info, fs...))
match = true;
return match;
}
static inline bool MatcherMatchVideoFormat(VideoFormat format, bool &did_match,
const VideoInfo &info)
{
bool match = FormatMatches(format, info.format);
did_match = did_match || match;
return match;
}
static inline bool MatcherClosestFrameRateSelector(long long interval,
long long &best_match,
const VideoInfo &info)
{
long long current = FrameRateInterval(info, interval);
if (llabs(interval - best_match) > llabs(interval - current))
best_match = current;
return true;
}
#if 0
auto ResolutionMatcher = [](int cx, int cy)
{
return [cx, cy](const VideoInfo &info)
{
return ResolutionAvailable(info, cx, cy);
};
};
auto FrameRateMatcher = [](long long interval)
{
return [interval](const VideoInfo &info)
{
return FrameRateAvailable(info, interval);
};
};
auto VideoFormatMatcher = [](VideoFormat format, bool &did_match)
{
return [format, &did_match](const VideoInfo &info)
{
return MatcherMatchVideoFormat(format, did_match, info);
};
};
auto ClosestFrameRateSelector = [](long long interval, long long &best_match)
{
return [interval, &best_match](const VideoInfo &info) mutable -> bool
{
MatcherClosestFrameRateSelector(interval, best_match, info);
};
}
#else
#define ResolutionMatcher(cx, cy) \
[cx, cy](const VideoInfo &info) -> bool { \
return ResolutionAvailable(info, cx, cy); \
}
#define FrameRateMatcher(interval) \
[interval](const VideoInfo &info) -> bool { \
return FrameRateAvailable(info, interval); \
}
#define VideoFormatMatcher(format, did_match) \
[format, &did_match](const VideoInfo &info) mutable -> bool { \
return MatcherMatchVideoFormat(format, did_match, info); \
}
#define ClosestFrameRateSelector(interval, best_match) \
[interval, &best_match](const VideoInfo &info) mutable -> bool { \
return MatcherClosestFrameRateSelector(interval, best_match, \
info); \
}