forked from ClusterM/open-bamboo-networking
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdshow_filter.cpp
More file actions
1854 lines (1695 loc) · 70.6 KB
/
dshow_filter.cpp
File metadata and controls
1854 lines (1695 loc) · 70.6 KB
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
// DirectShow Source Filter for the bambu: URL scheme on Windows.
//
// On Linux/macOS Studio drives video via the Bambu_* C ABI exported
// from BambuSource.cpp. On Windows wxMediaCtrl2 instead asks COM for a
// filter registered against bambu: URLs (CLSID
// {233E64FB-2041-4A6C-AFAB-FF9BCF83E7AA}); the C ABI here is used only
// for the on-printer file browser.
//
// This translation unit owns the COM in-proc-server entry points
// (DllGetClassObject / DllCanUnloadNow / DllRegisterServer /
// DllUnregisterServer), a hand-rolled IClassFactory, an IBaseFilter +
// IFileSourceFilter implementation (BambuSourceFilter) plus a single
// output pin (BambuSourceOutPin) that pumps raw H.264 Annex-B samples
// from obn::rtsp::Passthrough downstream to whatever decoder filter
// the graph builder picks (typically Microsoft H.264 Decoder MFT
// fronted by the DMO Wrapper Filter).
//
// We deliberately avoid Microsoft's strmbase/CSource baseclasses --
// they are not part of any vcpkg port we use, and the surface we need
// (one push source pin) is small enough that hand-rolled IUnknown +
// IPin + IBaseFilter QI tables stay readable. The threading model is
// "Both" (apartment + free); the pin owns its own worker thread and
// never reentrantly calls back into the filter graph thread.
//
// Phase B status: H.264 (RTSPS, P1S/X1) is the priority path the user
// asked for first. MJPEG (TLS:6000, A1/P1P) is wired on the same pin
// with a different media type and a separate worker; that path is
// guarded by the URL scheme so a user without an MJPEG printer never
// sees code from the H.264 path race against it.
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
# define NOMINMAX
#endif
#include <windows.h>
#include <objbase.h>
#include <strmif.h>
#include <uuids.h>
#include <dvdmedia.h> // VIDEOINFOHEADER2
#include <amvideo.h>
#include <combaseapi.h>
#include <shlwapi.h>
#include <vfwmsgs.h> // VFW_E_*
#include <olectl.h> // SELFREG_E_CLASS
#include <cwchar>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "rtsp_passthrough.hpp"
#include "source_log.hpp"
#include "tls_socket.hpp"
#include "obn/os_compat.hpp"
#include <openssl/err.h>
#include <openssl/ssl.h>
namespace {
// ----------------------------------------------------------------------------
// CLSID and constants
// ----------------------------------------------------------------------------
// {233E64FB-2041-4A6C-AFAB-FF9BCF83E7AA} -- Studio's wxMediaCtrl2.cpp
// hard-codes this for the bambu: URL scheme. Changing it would mean
// patching Studio.
const GUID CLSID_BambuSource = {
0x233E64FB, 0x2041, 0x4A6C,
{0xAF, 0xAB, 0xFF, 0x9B, 0xCF, 0x83, 0xE7, 0xAA}
};
// MEDIASUBTYPE_H264. dvdmedia.h has it for some SDK revisions but not
// all; define our own copy keyed on the FOURCC layout used by the
// Microsoft H.264 decoder MFT.
const GUID kMediaSubtypeH264 = {
0x34363248, 0x0000, 0x0010,
{0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71}
};
// IID for IFileSourceFilter -- declared in strmif.h but the constant
// itself comes from strmiids.lib at link time. Reference it through
// the IID_PPV_ARGS-style helper below.
extern "C" const IID IID_IFileSourceFilter;
// Filter friendly name surfaced in registry / GraphEdit.
constexpr wchar_t kFilterName[] = L"Bambu Source Filter";
// Registry vendor / scheme metadata. HKCU is enough for both the COM
// in-proc registration and the URL handler entry; both require no
// admin rights and Studio's wxMediaCtrl2 reads from HKCU + HKCR.
constexpr wchar_t kBambuScheme[] = L"bambu";
// Logger context for filter-internal diagnostics. We emit through the
// same file mirror used by the C ABI (obn-bambusource.log) so a single
// file shows the whole picture for Windows users.
using obn::source::log_at;
using obn::source::log_fmt;
using obn::source::LL_DEBUG;
using obn::source::LL_INFO;
using obn::source::LL_WARN;
using obn::source::LL_ERROR;
using obn::source::set_last_error;
// dshow-side "logger callback" sink: nullptr for now. We keep the
// argument shape so log_at() / log_fmt() macros take the same forms
// as in BambuSource.cpp.
constexpr obn::source::Logger kNoLogger = nullptr;
// Module handle, captured in DllMain. Used by DllRegisterServer to
// write the absolute path to InprocServer32.
HMODULE g_module = nullptr;
// Lock count for DllCanUnloadNow. Bumped by every live filter / class
// factory; OLE32 polls this to decide whether to call FreeLibrary.
std::atomic<long> g_lock_count{0};
void module_lock() { g_lock_count.fetch_add(1, std::memory_order_acq_rel); }
void module_unlock() { g_lock_count.fetch_sub(1, std::memory_order_acq_rel); }
// ----------------------------------------------------------------------------
// Diagnostics helpers
// ----------------------------------------------------------------------------
//
// Translating GUIDs to recognizable names makes the trace usable when
// Orca crashes mid-handshake: the IID told to QueryInterface is often
// the only signal we have about which interface negotiation was in
// progress. We keep a small table of the IIDs DShow source filters
// actually see; everything else falls back to the brace-form GUID.
const char* iid_short_name(REFIID iid)
{
struct Entry { const GUID* g; const char* n; };
static const Entry kTable[] = {
{&IID_IUnknown, "IUnknown"},
{&IID_IClassFactory, "IClassFactory"},
{&IID_IPersist, "IPersist"},
{&IID_IMediaFilter, "IMediaFilter"},
{&IID_IBaseFilter, "IBaseFilter"},
{&IID_IFileSourceFilter, "IFileSourceFilter"},
{&IID_IPin, "IPin"},
{&IID_IMemInputPin, "IMemInputPin"},
{&IID_IMemAllocator, "IMemAllocator"},
{&IID_IEnumPins, "IEnumPins"},
{&IID_IEnumMediaTypes, "IEnumMediaTypes"},
{&IID_IQualityControl, "IQualityControl"},
};
for (const auto& e : kTable) {
if (e.g && IsEqualIID(iid, *e.g)) return e.n;
}
return nullptr;
}
// Small printable buffer for an IID. Returns a pointer into a static
// thread_local cache; safe to use as a single argument to log_at().
const char* iid_to_string(REFIID iid)
{
if (const char* s = iid_short_name(iid)) return s;
static thread_local char buf[64];
std::snprintf(buf, sizeof(buf),
"{%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
static_cast<unsigned long>(iid.Data1),
iid.Data2, iid.Data3,
iid.Data4[0], iid.Data4[1],
iid.Data4[2], iid.Data4[3], iid.Data4[4],
iid.Data4[5], iid.Data4[6], iid.Data4[7]);
return buf;
}
// Translate a major/sub media-type GUID pair to a printable label
// for Connect/QueryAccept logs. Falls back to the iid_to_string form.
const char* mediatype_short_name(REFGUID g)
{
if (IsEqualGUID(g, MEDIATYPE_Video)) return "MEDIATYPE_Video";
if (IsEqualGUID(g, MEDIATYPE_Audio)) return "MEDIATYPE_Audio";
if (IsEqualGUID(g, MEDIATYPE_Stream)) return "MEDIATYPE_Stream";
if (IsEqualGUID(g, MEDIASUBTYPE_MJPG)) return "MEDIASUBTYPE_MJPG";
if (IsEqualGUID(g, kMediaSubtypeH264)) return "MEDIASUBTYPE_H264";
if (IsEqualGUID(g, FORMAT_VideoInfo)) return "FORMAT_VideoInfo";
if (IsEqualGUID(g, FORMAT_VideoInfo2)) return "FORMAT_VideoInfo2";
if (IsEqualGUID(g, GUID_NULL)) return "GUID_NULL";
return nullptr;
}
const char* mediatype_to_string(REFGUID g)
{
if (const char* s = mediatype_short_name(g)) return s;
return iid_to_string(g);
}
// ----------------------------------------------------------------------------
// COM helpers
// ----------------------------------------------------------------------------
// Minimal QI table: one IID per row, paired with a function that
// returns a typed pointer. The callbacks return a base IUnknown* so
// the row table can stay homogeneous; we cast back at the call site.
// Standard COM aggregation is NOT supported -- we never set up an
// outer unknown.
struct QiEntry {
REFIID iid;
IUnknown* (*adapt)(void* self);
};
template <typename T>
IUnknown* qi_self(void* self) { return static_cast<T*>(self); }
// AM_MEDIA_TYPE management. dshow callers expect deep-copy semantics
// (pbFormat is CoTaskMemAlloc'd, fixed via FreeMediaType) so we do
// not memcpy AM_MEDIA_TYPE structs blindly.
void am_free_media_type(AM_MEDIA_TYPE* mt)
{
if (!mt) return;
if (mt->cbFormat != 0 && mt->pbFormat) {
::CoTaskMemFree(mt->pbFormat);
mt->cbFormat = 0;
mt->pbFormat = nullptr;
}
if (mt->pUnk) {
mt->pUnk->Release();
mt->pUnk = nullptr;
}
}
void am_delete_media_type(AM_MEDIA_TYPE* mt)
{
if (!mt) return;
am_free_media_type(mt);
::CoTaskMemFree(mt);
}
bool am_copy_media_type(AM_MEDIA_TYPE* dst, const AM_MEDIA_TYPE* src)
{
if (!dst || !src) return false;
*dst = *src;
// Null out anything that holds an aliased ownership before any
// step can fail; we want am_free_media_type(dst) on a partially
// initialised dst to be a no-op rather than double-Release the
// src->pUnk we only just shallow-copied.
dst->pbFormat = nullptr;
dst->cbFormat = 0;
dst->pUnk = nullptr;
if (src->cbFormat != 0 && src->pbFormat) {
dst->pbFormat = static_cast<BYTE*>(::CoTaskMemAlloc(src->cbFormat));
if (!dst->pbFormat) return false;
std::memcpy(dst->pbFormat, src->pbFormat, src->cbFormat);
dst->cbFormat = src->cbFormat;
}
if (src->pUnk) {
src->pUnk->AddRef();
dst->pUnk = src->pUnk;
}
return true;
}
// ----------------------------------------------------------------------------
// URL parser (subset; mirrors BambuSource.cpp's parse_url for the
// shapes that Studio's MediaPlayCtrl::Play actually emits)
// ----------------------------------------------------------------------------
enum class UrlScheme {
Local, // MJPG over TCP/TLS on <port> (default 6000), A1/P1/P1P
Rtsps, // RTSPS on <port> (default 322), X1/P1S/P2S/H-series/X2D
Rtsp, // plain RTSP, dev/test only
};
struct ParsedUrl {
UrlScheme scheme = UrlScheme::Local;
std::string host;
int port = 6000;
std::string user = "bblp";
std::string passwd;
std::string path = "/streaming/live/1";
};
std::string url_decode(const std::string& s)
{
std::string out;
out.reserve(s.size());
auto hex = [](char c) -> int {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return 10 + c - 'a';
if (c >= 'A' && c <= 'F') return 10 + c - 'A';
return -1;
};
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == '%' && i + 2 < s.size()) {
int a = hex(s[i + 1]);
int b = hex(s[i + 2]);
if (a >= 0 && b >= 0) {
out.push_back(static_cast<char>((a << 4) | b));
i += 2;
continue;
}
}
out.push_back(s[i] == '+' ? ' ' : s[i]);
}
return out;
}
bool parse_bambu_url(const std::string& url, ParsedUrl* out)
{
// Orca/Studio's MediaPlayCtrl produces URLs like
// "bambu:///rtsps___bblp:pwd@host/streaming/live/1?proto=rtsps&..."
// "bambu:///rtsp___bblp:pwd@host/streaming/live/1?proto=rtsp&..."
// "bambu:///local/HOST.?port=6000&user=bblp&passwd=..."
// wxURI normalises authority-less URIs and may collapse "///" into
// "//" before handing the URL to IFileSourceFilter::Load (treating the
// "rtsps___bblp:pwd" prefix as userinfo). Accept both forms.
static const char kBambu[] = "bambu:";
if (url.compare(0, sizeof(kBambu) - 1, kBambu) != 0)
return false;
std::size_t p = sizeof(kBambu) - 1;
while (p < url.size() && url[p] == '/') ++p;
std::string body = url.substr(p);
static const std::string p_local = "local/";
static const std::string p_rtsps = "rtsps___";
static const std::string p_rtsp = "rtsp___";
std::string rest;
if (body.compare(0, p_local.size(), p_local) == 0) {
out->scheme = UrlScheme::Local;
out->port = 6000;
rest = body.substr(p_local.size());
} else if (body.compare(0, p_rtsps.size(), p_rtsps) == 0) {
out->scheme = UrlScheme::Rtsps;
out->port = 322;
rest = body.substr(p_rtsps.size());
} else if (body.compare(0, p_rtsp.size(), p_rtsp) == 0) {
out->scheme = UrlScheme::Rtsp;
out->port = 554;
rest = body.substr(p_rtsp.size());
} else {
return false;
}
auto q_pos = rest.find('?');
std::string head = (q_pos == std::string::npos) ? rest : rest.substr(0, q_pos);
std::string query = (q_pos == std::string::npos) ? "" : rest.substr(q_pos + 1);
if (out->scheme == UrlScheme::Rtsps || out->scheme == UrlScheme::Rtsp) {
// user:passwd@host[:port]/path
auto at = head.find('@');
if (at != std::string::npos) {
std::string ui = head.substr(0, at);
head = head.substr(at + 1);
auto col = ui.find(':');
if (col != std::string::npos) {
out->user = url_decode(ui.substr(0, col));
out->passwd = url_decode(ui.substr(col + 1));
} else {
out->user = url_decode(ui);
}
}
auto sl = head.find('/');
if (sl != std::string::npos) {
out->path = head.substr(sl);
head = head.substr(0, sl);
}
} else {
while (!head.empty() && (head.back() == '/' || head.back() == '.'))
head.pop_back();
}
auto col = head.find(':');
if (col != std::string::npos) {
out->host = head.substr(0, col);
try {
out->port = std::stoi(head.substr(col + 1));
} catch (...) {
return false;
}
} else {
out->host = head;
}
// Local-scheme URLs hide credentials in the query string.
std::size_t i = 0;
while (i < query.size()) {
std::size_t e = query.find('&', i);
std::string tok = query.substr(i, (e == std::string::npos) ? query.size() - i : e - i);
std::size_t eq = tok.find('=');
if (eq != std::string::npos) {
std::string k = tok.substr(0, eq);
std::string v = url_decode(tok.substr(eq + 1));
if (k == "user") out->user = v;
else if (k == "passwd") out->passwd = v;
else if (k == "port") {
try { out->port = std::stoi(v); } catch (...) {}
}
}
if (e == std::string::npos) break;
i = e + 1;
}
return !out->host.empty();
}
// UTF-16 -> UTF-8 conversion for IFileSourceFilter::Load(LPCOLESTR).
std::string wide_to_utf8(const wchar_t* w)
{
if (!w || !*w) return {};
int n = ::WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr);
if (n <= 0) return {};
std::string out(static_cast<std::size_t>(n - 1), '\0');
::WideCharToMultiByte(CP_UTF8, 0, w, -1, out.data(), n, nullptr, nullptr);
return out;
}
// ----------------------------------------------------------------------------
// Forward declarations -- pin and filter cross-reference each other
// ----------------------------------------------------------------------------
class BambuSourceFilter;
// Build a single H.264 Annex-B media type. caller owns *mt (deep copy
// semantics; free with am_free_media_type).
bool make_h264_media_type(AM_MEDIA_TYPE* mt)
{
std::memset(mt, 0, sizeof(*mt));
mt->majortype = MEDIATYPE_Video;
mt->subtype = kMediaSubtypeH264;
mt->bFixedSizeSamples = FALSE;
mt->bTemporalCompression = TRUE;
mt->lSampleSize = 0;
mt->formattype = FORMAT_VideoInfo2;
mt->cbFormat = sizeof(VIDEOINFOHEADER2);
mt->pbFormat = static_cast<BYTE*>(::CoTaskMemAlloc(mt->cbFormat));
if (!mt->pbFormat) { mt->cbFormat = 0; return false; }
std::memset(mt->pbFormat, 0, mt->cbFormat);
auto* vih = reinterpret_cast<VIDEOINFOHEADER2*>(mt->pbFormat);
vih->dwBitRate = 0;
vih->dwBitErrorRate = 0;
// 33 ms / frame ~= 30 fps; the decoder ignores AvgTimePerFrame for
// live streams (it derives PTS from sample timestamps), but graph
// builders sanity-check that this is non-zero.
vih->AvgTimePerFrame = 333333; // 100 ns units
vih->dwInterlaceFlags = 0;
vih->dwCopyProtectFlags = 0;
vih->dwPictAspectRatioX = 16;
vih->dwPictAspectRatioY = 9;
vih->dwReserved1 = 0;
vih->dwReserved2 = 0;
vih->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
vih->bmiHeader.biWidth = 1280;
vih->bmiHeader.biHeight = 720;
vih->bmiHeader.biPlanes = 1;
vih->bmiHeader.biBitCount = 24;
vih->bmiHeader.biCompression = MAKEFOURCC('H','2','6','4');
vih->bmiHeader.biSizeImage = 0;
return true;
}
// Build a single MJPEG media type for A1 / P1 / P1P printers
// (TLS:6000 framed JPEG). Studio's downstream is the MJPEG decoder
// MFT or the standard MJPEG video decoder filter; both accept
// MEDIASUBTYPE_MJPG with a VIDEOINFOHEADER carrying a 'MJPG' fourcc.
bool make_mjpeg_media_type(AM_MEDIA_TYPE* mt)
{
std::memset(mt, 0, sizeof(*mt));
mt->majortype = MEDIATYPE_Video;
mt->subtype = MEDIASUBTYPE_MJPG;
mt->bFixedSizeSamples = FALSE;
mt->bTemporalCompression = FALSE; // each JPEG is self-contained
mt->lSampleSize = 0;
mt->formattype = FORMAT_VideoInfo;
mt->cbFormat = sizeof(VIDEOINFOHEADER);
mt->pbFormat = static_cast<BYTE*>(::CoTaskMemAlloc(mt->cbFormat));
if (!mt->pbFormat) { mt->cbFormat = 0; return false; }
std::memset(mt->pbFormat, 0, mt->cbFormat);
auto* vih = reinterpret_cast<VIDEOINFOHEADER*>(mt->pbFormat);
vih->AvgTimePerFrame = 666666; // ~15 fps; A1/P1 cap there
vih->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
vih->bmiHeader.biWidth = 1280;
vih->bmiHeader.biHeight = 720;
vih->bmiHeader.biPlanes = 1;
vih->bmiHeader.biBitCount = 24;
vih->bmiHeader.biCompression = MAKEFOURCC('M','J','P','G');
vih->bmiHeader.biSizeImage = 0;
return true;
}
bool make_media_type_for_scheme(AM_MEDIA_TYPE* mt, UrlScheme scheme)
{
if (scheme == UrlScheme::Local) return make_mjpeg_media_type(mt);
return make_h264_media_type(mt);
}
GUID subtype_for_scheme(UrlScheme scheme)
{
return (scheme == UrlScheme::Local) ? MEDIASUBTYPE_MJPG : kMediaSubtypeH264;
}
// ----------------------------------------------------------------------------
// IEnumMediaTypes (single-type enumerator for the output pin)
// ----------------------------------------------------------------------------
class MediaTypeEnumerator : public IEnumMediaTypes {
public:
MediaTypeEnumerator(UrlScheme scheme) : scheme_(scheme), ref_(1)
{
module_lock();
}
~MediaTypeEnumerator() { module_unlock(); }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override
{
if (!ppv) return E_POINTER;
if (riid == IID_IUnknown || riid == IID_IEnumMediaTypes) {
*ppv = static_cast<IEnumMediaTypes*>(this);
AddRef();
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override
{
return static_cast<ULONG>(ref_.fetch_add(1, std::memory_order_acq_rel) + 1);
}
ULONG STDMETHODCALLTYPE Release() override
{
long n = ref_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (n == 0) delete this;
return static_cast<ULONG>(n);
}
HRESULT STDMETHODCALLTYPE Next(ULONG cMediaTypes, AM_MEDIA_TYPE** ppMediaTypes,
ULONG* pcFetched) override
{
if (!ppMediaTypes) return E_POINTER;
ULONG fetched = 0;
for (ULONG i = 0; i < cMediaTypes; ++i) {
if (cursor_ >= 1) break;
auto* mt = static_cast<AM_MEDIA_TYPE*>(::CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)));
if (!mt) return E_OUTOFMEMORY;
if (!make_media_type_for_scheme(mt, scheme_)) {
::CoTaskMemFree(mt);
return E_OUTOFMEMORY;
}
ppMediaTypes[i] = mt;
++cursor_;
++fetched;
}
if (pcFetched) *pcFetched = fetched;
return (fetched == cMediaTypes) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE Skip(ULONG cMediaTypes) override
{
cursor_ += cMediaTypes;
return (cursor_ <= 1) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE Reset() override { cursor_ = 0; return S_OK; }
HRESULT STDMETHODCALLTYPE Clone(IEnumMediaTypes** ppEnum) override
{
if (!ppEnum) return E_POINTER;
auto* clone = new MediaTypeEnumerator(scheme_);
clone->cursor_ = cursor_;
*ppEnum = clone;
return S_OK;
}
private:
UrlScheme scheme_;
std::atomic<long> ref_;
ULONG cursor_ = 0;
};
// ----------------------------------------------------------------------------
// IEnumPins (single-pin enumerator for the filter)
// ----------------------------------------------------------------------------
class PinEnumerator : public IEnumPins {
public:
PinEnumerator(IPin* pin) : pin_(pin), ref_(1)
{
if (pin_) pin_->AddRef();
module_lock();
}
~PinEnumerator()
{
if (pin_) pin_->Release();
module_unlock();
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override
{
if (!ppv) return E_POINTER;
if (riid == IID_IUnknown || riid == IID_IEnumPins) {
*ppv = static_cast<IEnumPins*>(this);
AddRef();
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override
{
return static_cast<ULONG>(ref_.fetch_add(1, std::memory_order_acq_rel) + 1);
}
ULONG STDMETHODCALLTYPE Release() override
{
long n = ref_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (n == 0) delete this;
return static_cast<ULONG>(n);
}
HRESULT STDMETHODCALLTYPE Next(ULONG cPins, IPin** ppPins, ULONG* pcFetched) override
{
if (!ppPins) return E_POINTER;
ULONG fetched = 0;
for (ULONG i = 0; i < cPins; ++i) {
if (cursor_ >= 1) break;
ppPins[i] = pin_;
if (pin_) pin_->AddRef();
++cursor_;
++fetched;
}
if (pcFetched) *pcFetched = fetched;
return (fetched == cPins) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE Skip(ULONG cPins) override
{
cursor_ += cPins;
return (cursor_ <= 1) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE Reset() override { cursor_ = 0; return S_OK; }
HRESULT STDMETHODCALLTYPE Clone(IEnumPins** ppEnum) override
{
if (!ppEnum) return E_POINTER;
auto* clone = new PinEnumerator(pin_);
clone->cursor_ = cursor_;
*ppEnum = clone;
return S_OK;
}
private:
IPin* pin_;
std::atomic<long> ref_;
ULONG cursor_ = 0;
};
// ----------------------------------------------------------------------------
// BambuSourceOutPin
// ----------------------------------------------------------------------------
//
// Single H.264 output pin. Holds the worker thread that drives
// obn::rtsp::Passthrough and pushes IMediaSamples downstream via
// IMemInputPin::Receive. Connection / disconnection serialise on
// state_mu_; the worker only runs while connected and the filter is in
// State_Running.
class BambuSourceOutPin : public IPin, public IQualityControl {
public:
BambuSourceOutPin(BambuSourceFilter* parent, const wchar_t* name);
~BambuSourceOutPin();
// ---- IUnknown ----
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
// ---- IPin ----
HRESULT STDMETHODCALLTYPE Connect(IPin* pReceivePin, const AM_MEDIA_TYPE* pmt) override;
HRESULT STDMETHODCALLTYPE ReceiveConnection(IPin*, const AM_MEDIA_TYPE*) override
{
return E_UNEXPECTED; // we are an output pin
}
HRESULT STDMETHODCALLTYPE Disconnect() override;
HRESULT STDMETHODCALLTYPE ConnectedTo(IPin** pPin) override;
HRESULT STDMETHODCALLTYPE ConnectionMediaType(AM_MEDIA_TYPE* pmt) override;
HRESULT STDMETHODCALLTYPE QueryPinInfo(PIN_INFO* pInfo) override;
HRESULT STDMETHODCALLTYPE QueryDirection(PIN_DIRECTION* pDir) override
{
if (!pDir) return E_POINTER;
*pDir = PINDIR_OUTPUT;
return S_OK;
}
HRESULT STDMETHODCALLTYPE QueryId(LPWSTR* Id) override;
HRESULT STDMETHODCALLTYPE QueryAccept(const AM_MEDIA_TYPE* pmt) override;
HRESULT STDMETHODCALLTYPE EnumMediaTypes(IEnumMediaTypes** ppEnum) override;
HRESULT STDMETHODCALLTYPE QueryInternalConnections(IPin**, ULONG*) override
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE EndOfStream() override { return S_OK; }
HRESULT STDMETHODCALLTYPE BeginFlush() override { return S_OK; }
HRESULT STDMETHODCALLTYPE EndFlush() override { return S_OK; }
HRESULT STDMETHODCALLTYPE NewSegment(REFERENCE_TIME, REFERENCE_TIME, double) override
{
return S_OK;
}
// ---- IQualityControl ----
HRESULT STDMETHODCALLTYPE Notify(IBaseFilter*, Quality) override { return S_OK; }
HRESULT STDMETHODCALLTYPE SetSink(IQualityControl*) override { return S_OK; }
// ---- internal helpers driven by BambuSourceFilter ----
void start_streaming();
void stop_streaming();
private:
void worker_main();
BambuSourceFilter* const parent_;
std::wstring name_;
std::atomic<long> ref_;
std::mutex state_mu_;
IPin* downstream_ = nullptr; // weak via AddRef'd pointer
IMemInputPin* downstream_input_ = nullptr;
IMemAllocator* allocator_ = nullptr;
AM_MEDIA_TYPE current_mt_{};
bool have_mt_ = false;
std::thread worker_;
std::atomic<bool> worker_stop_{false};
std::atomic<bool> worker_running_{false};
};
// ----------------------------------------------------------------------------
// BambuSourceFilter
// ----------------------------------------------------------------------------
class BambuSourceFilter : public IBaseFilter, public IFileSourceFilter {
public:
BambuSourceFilter();
~BambuSourceFilter();
// ---- IUnknown ----
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
// ---- IPersist ----
HRESULT STDMETHODCALLTYPE GetClassID(CLSID* pClsID) override
{
if (!pClsID) return E_POINTER;
*pClsID = CLSID_BambuSource;
return S_OK;
}
// ---- IMediaFilter ----
HRESULT STDMETHODCALLTYPE Stop() override;
HRESULT STDMETHODCALLTYPE Pause() override;
HRESULT STDMETHODCALLTYPE Run(REFERENCE_TIME tStart) override;
HRESULT STDMETHODCALLTYPE GetState(DWORD dwMs, FILTER_STATE* pState) override;
HRESULT STDMETHODCALLTYPE SetSyncSource(IReferenceClock* pClock) override;
HRESULT STDMETHODCALLTYPE GetSyncSource(IReferenceClock** ppClock) override;
// ---- IBaseFilter ----
HRESULT STDMETHODCALLTYPE EnumPins(IEnumPins** ppEnum) override;
HRESULT STDMETHODCALLTYPE FindPin(LPCWSTR Id, IPin** ppPin) override;
HRESULT STDMETHODCALLTYPE QueryFilterInfo(FILTER_INFO* pInfo) override;
HRESULT STDMETHODCALLTYPE JoinFilterGraph(IFilterGraph* pGraph, LPCWSTR pName) override;
HRESULT STDMETHODCALLTYPE QueryVendorInfo(LPWSTR* pVendorInfo) override;
// ---- IFileSourceFilter ----
HRESULT STDMETHODCALLTYPE Load(LPCOLESTR lpwszFileName,
const AM_MEDIA_TYPE* pmt) override;
HRESULT STDMETHODCALLTYPE GetCurFile(LPOLESTR* ppszFileName,
AM_MEDIA_TYPE* pmt) override;
// ---- internal accessors used by the pin ----
const ParsedUrl& url() const noexcept { return url_; }
FILTER_STATE state() const noexcept { return state_.load(std::memory_order_acquire); }
IReferenceClock* clock() noexcept { return clock_; }
IFilterGraph* graph() noexcept { return graph_; }
private:
std::atomic<long> ref_;
std::mutex mu_;
BambuSourceOutPin* pin_;
std::atomic<FILTER_STATE> state_{State_Stopped};
IReferenceClock* clock_ = nullptr;
IFilterGraph* graph_ = nullptr; // weak: filter graph holds us
std::wstring graph_name_;
std::wstring url_w_;
ParsedUrl url_;
bool url_loaded_ = false;
};
// ============================================================================
// BambuSourceOutPin implementation
// ============================================================================
BambuSourceOutPin::BambuSourceOutPin(BambuSourceFilter* parent, const wchar_t* name)
: parent_(parent), name_(name ? name : L""), ref_(1)
{
std::memset(¤t_mt_, 0, sizeof(current_mt_));
module_lock();
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: Pin ctor this=%p parent=%p", this, parent);
}
BambuSourceOutPin::~BambuSourceOutPin()
{
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: Pin dtor this=%p", this);
stop_streaming();
if (have_mt_) am_free_media_type(¤t_mt_);
if (allocator_) allocator_->Release();
if (downstream_input_) downstream_input_->Release();
if (downstream_) downstream_->Release();
module_unlock();
}
HRESULT STDMETHODCALLTYPE BambuSourceOutPin::QueryInterface(REFIID riid, void** ppv)
{
if (!ppv) return E_POINTER;
if (riid == IID_IUnknown) {
*ppv = static_cast<IPin*>(this);
} else if (riid == IID_IPin) {
*ppv = static_cast<IPin*>(this);
} else if (riid == IID_IQualityControl) {
*ppv = static_cast<IQualityControl*>(this);
} else {
log_at(LL_DEBUG, kNoLogger, nullptr,
"dshow: Pin::QI(%s) -> E_NOINTERFACE",
iid_to_string(riid));
*ppv = nullptr;
return E_NOINTERFACE;
}
AddRef();
log_at(LL_DEBUG, kNoLogger, nullptr,
"dshow: Pin::QI(%s) -> ok", iid_to_string(riid));
return S_OK;
}
ULONG STDMETHODCALLTYPE BambuSourceOutPin::AddRef()
{
return static_cast<ULONG>(ref_.fetch_add(1, std::memory_order_acq_rel) + 1);
}
ULONG STDMETHODCALLTYPE BambuSourceOutPin::Release()
{
long n = ref_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (n == 0) delete this;
return static_cast<ULONG>(n);
}
HRESULT STDMETHODCALLTYPE BambuSourceOutPin::Connect(IPin* pReceivePin,
const AM_MEDIA_TYPE* pmt)
{
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: Pin::Connect downstream=%p pmt=%p", pReceivePin, pmt);
if (pmt) {
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: requested major=%s sub=%s fmt=%s cbFormat=%lu",
mediatype_to_string(pmt->majortype),
mediatype_to_string(pmt->subtype),
mediatype_to_string(pmt->formattype),
static_cast<unsigned long>(pmt->cbFormat));
}
if (!pReceivePin) return E_POINTER;
std::lock_guard<std::mutex> lk(state_mu_);
if (downstream_) {
log_at(LL_WARN, kNoLogger, nullptr,
"dshow: Pin::Connect -> VFW_E_ALREADY_CONNECTED");
return VFW_E_ALREADY_CONNECTED;
}
AM_MEDIA_TYPE candidate{};
UrlScheme scheme = parent_->url().scheme;
if (pmt && pmt->majortype != GUID_NULL) {
if (!am_copy_media_type(&candidate, pmt)) return E_OUTOFMEMORY;
} else {
if (!make_media_type_for_scheme(&candidate, scheme)) return E_OUTOFMEMORY;
}
HRESULT hr = pReceivePin->ReceiveConnection(static_cast<IPin*>(this), &candidate);
if (FAILED(hr)) {
am_free_media_type(&candidate);
log_at(LL_WARN, kNoLogger, nullptr,
"dshow: ReceiveConnection rejected our preferred type, hr=0x%08lx",
static_cast<unsigned long>(hr));
return hr;
}
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: ReceiveConnection accepted");
IMemInputPin* mip = nullptr;
hr = pReceivePin->QueryInterface(IID_IMemInputPin, reinterpret_cast<void**>(&mip));
if (FAILED(hr) || !mip) {
// Roll back the half-completed connection; downstream now
// thinks we are connected and will route Receive() calls to
// a pin we never finished wiring up.
pReceivePin->Disconnect();
am_free_media_type(&candidate);
log_at(LL_WARN, kNoLogger, nullptr,
"dshow: downstream pin lacks IMemInputPin (hr=0x%08lx); rolled back",
static_cast<unsigned long>(hr));
return hr;
}
// Allocator handshake: prefer downstream's, fall back to a default.
IMemAllocator* alloc = nullptr;
hr = mip->GetAllocator(&alloc);
if (FAILED(hr) || !alloc) {
hr = ::CoCreateInstance(CLSID_MemoryAllocator, nullptr, CLSCTX_INPROC_SERVER,
IID_IMemAllocator, reinterpret_cast<void**>(&alloc));
if (FAILED(hr) || !alloc) {
pReceivePin->Disconnect();
am_free_media_type(&candidate);
mip->Release();
log_at(LL_ERROR, kNoLogger, nullptr,
"dshow: no allocator available (hr=0x%08lx)",
static_cast<unsigned long>(hr));
return hr;
}
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: using default IMemAllocator (CLSID_MemoryAllocator)");
} else {
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: using downstream-provided IMemAllocator");
}
ALLOCATOR_PROPERTIES req{};
req.cBuffers = 8;
req.cbBuffer = 256 * 1024; // big enough for one H.264 access unit
req.cbAlign = 1;
req.cbPrefix = 0;
ALLOCATOR_PROPERTIES actual{};
hr = alloc->SetProperties(&req, &actual);
if (FAILED(hr)) {
log_at(LL_WARN, kNoLogger, nullptr,
"dshow: alloc->SetProperties failed hr=0x%08lx",
static_cast<unsigned long>(hr));
}
hr = mip->NotifyAllocator(alloc, FALSE);
if (FAILED(hr)) {
log_at(LL_WARN, kNoLogger, nullptr,
"dshow: NotifyAllocator failed hr=0x%08lx",
static_cast<unsigned long>(hr));
}
// Do NOT Commit() here — downstream is free to call SetProperties
// any time before the graph transitions to State_Paused/Running.
// We Commit() in start_streaming() right before the worker calls
// GetBuffer, then Decommit() in stop_streaming() to wake any
// blocked GetBuffer.
pReceivePin->AddRef();
downstream_ = pReceivePin;
downstream_input_ = mip; // already AddRef'd by QI
allocator_ = alloc;
if (have_mt_) am_free_media_type(¤t_mt_);
current_mt_ = candidate;
have_mt_ = true;
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: Pin::Connect ok (alloc cBuffers=%ld cbBuffer=%ld align=%ld prefix=%ld)",
static_cast<long>(actual.cBuffers),
static_cast<long>(actual.cbBuffer),
static_cast<long>(actual.cbAlign),
static_cast<long>(actual.cbPrefix));
return S_OK;
}
HRESULT STDMETHODCALLTYPE BambuSourceOutPin::Disconnect()
{
log_at(LL_INFO, kNoLogger, nullptr,
"dshow: Pin::Disconnect this=%p downstream=%p",
this, downstream_);
stop_streaming();
std::lock_guard<std::mutex> lk(state_mu_);
if (allocator_) {
// Decommit before Release so any pending GetBuffer in the
// worker (if it raced past stop_streaming) returns immediately
// instead of waiting forever for a freed allocator.
allocator_->Decommit();
}
if (have_mt_) {
am_free_media_type(¤t_mt_);
have_mt_ = false;
}
if (allocator_) { allocator_->Release(); allocator_ = nullptr; }
if (downstream_input_) { downstream_input_->Release(); downstream_input_ = nullptr; }
if (downstream_) { downstream_->Release(); downstream_ = nullptr; }
return S_OK;
}
HRESULT STDMETHODCALLTYPE BambuSourceOutPin::ConnectedTo(IPin** pPin)
{
if (!pPin) return E_POINTER;
std::lock_guard<std::mutex> lk(state_mu_);
if (!downstream_) {
*pPin = nullptr;