Welcome to mirror list, hosted at ThFree Co, Russian Federation.

StreamSwitcher.cpp « AudioSwitcher « switcher « filters « src - github.com/mpc-hc/mpc-hc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 03dc694797ded5e8fc304f95a6df9b00ef828419 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
/*
 * (C) 2003-2006 Gabest
 * (C) 2006-2014 see Authors.txt
 *
 * This file is part of MPC-HC.
 *
 * MPC-HC is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * MPC-HC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdafx.h"
#include <algorithm>
#include "StreamSwitcher.h"
#include "../../../DSUtil/DSUtil.h"

#ifdef STANDALONE_FILTER
#include <InitGuid.h>
#endif
#include "moreuuids.h"

#define BLOCKSTREAM

//
// CStreamSwitcherPassThru
//

CStreamSwitcherPassThru::CStreamSwitcherPassThru(LPUNKNOWN pUnk, HRESULT* phr, CStreamSwitcherFilter* pFilter)
    : CMediaPosition(NAME("CStreamSwitcherPassThru"), pUnk)
    , m_pFilter(pFilter)
{
}

STDMETHODIMP CStreamSwitcherPassThru::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
    CheckPointer(ppv, E_POINTER);
    *ppv = nullptr;

    return
        QI(IMediaSeeking)
        CMediaPosition::NonDelegatingQueryInterface(riid, ppv);
}

template<class T>
HRESULT GetPeer(CStreamSwitcherFilter* pFilter, T** ppT)
{
    *ppT = nullptr;

    CBasePin* pPin = pFilter->GetInputPin();
    if (!pPin) {
        return E_NOTIMPL;
    }

    CComPtr<IPin> pConnected;
    if (FAILED(pPin->ConnectedTo(&pConnected))) {
        return E_NOTIMPL;
    }

    if (CComQIPtr<T> pT = pConnected) {
        *ppT = pT.Detach();
        return S_OK;
    }

    return E_NOTIMPL;
}


#define CallPeerSeeking(call)                               \
    CComPtr<IMediaSeeking> pMS;                             \
    if (FAILED(GetPeer(m_pFilter, &pMS)))                   \
        return E_NOTIMPL;                                   \
    return pMS->##call;

#define CallPeer(call)                                      \
    CComPtr<IMediaPosition> pMP;                            \
    if (FAILED(GetPeer(m_pFilter, &pMP)))                   \
        return E_NOTIMPL;                                   \
    return pMP->##call;

#define CallPeerSeekingAll(call)                            \
    HRESULT hr = E_NOTIMPL;                                 \
    POSITION pos = m_pFilter->m_pInputs.GetHeadPosition();  \
    while (pos) {                                           \
        CBasePin* pPin = m_pFilter->m_pInputs.GetNext(pos); \
        CComPtr<IPin> pConnected;                           \
        if (FAILED(pPin->ConnectedTo(&pConnected)))         \
            continue;                                       \
        if (CComQIPtr<IMediaSeeking> pMS = pConnected) {    \
            HRESULT hr2 = pMS->call;                        \
            if (pPin == m_pFilter->GetInputPin())           \
                hr = hr2;                                   \
        }                                                   \
    }                                                       \
    return hr;

#define CallPeerAll(call)                                   \
    HRESULT hr = E_NOTIMPL;                                 \
    POSITION pos = m_pFilter->m_pInputs.GetHeadPosition();  \
    while (pos) {                                           \
        CBasePin* pPin = m_pFilter->m_pInputs.GetNext(pos); \
        CComPtr<IPin> pConnected;                           \
        if (FAILED(pPin->ConnectedTo(&pConnected)))         \
            continue;                                       \
        if (CComQIPtr<IMediaPosition> pMP = pConnected) {   \
            HRESULT hr2 = pMP->call;                        \
            if (pPin == m_pFilter->GetInputPin())           \
                hr = hr2;                                   \
        }                                                   \
    }                                                       \
    return hr;


// IMediaSeeking

STDMETHODIMP CStreamSwitcherPassThru::GetCapabilities(DWORD* pCaps)
{
    CallPeerSeeking(GetCapabilities(pCaps));
}

STDMETHODIMP CStreamSwitcherPassThru::CheckCapabilities(DWORD* pCaps)
{
    CallPeerSeeking(CheckCapabilities(pCaps));
}

STDMETHODIMP CStreamSwitcherPassThru::IsFormatSupported(const GUID* pFormat)
{
    CallPeerSeeking(IsFormatSupported(pFormat));
}

STDMETHODIMP CStreamSwitcherPassThru::QueryPreferredFormat(GUID* pFormat)
{
    CallPeerSeeking(QueryPreferredFormat(pFormat));
}

STDMETHODIMP CStreamSwitcherPassThru::SetTimeFormat(const GUID* pFormat)
{
    CallPeerSeeking(SetTimeFormat(pFormat));
}

STDMETHODIMP CStreamSwitcherPassThru::GetTimeFormat(GUID* pFormat)
{
    CallPeerSeeking(GetTimeFormat(pFormat));
}

STDMETHODIMP CStreamSwitcherPassThru::IsUsingTimeFormat(const GUID* pFormat)
{
    CallPeerSeeking(IsUsingTimeFormat(pFormat));
}

STDMETHODIMP CStreamSwitcherPassThru::ConvertTimeFormat(LONGLONG* pTarget, const GUID* pTargetFormat, LONGLONG Source, const GUID* pSourceFormat)
{
    CallPeerSeeking(ConvertTimeFormat(pTarget, pTargetFormat, Source, pSourceFormat));
}

STDMETHODIMP CStreamSwitcherPassThru::SetPositions(LONGLONG* pCurrent, DWORD CurrentFlags, LONGLONG* pStop, DWORD StopFlags)
{
    CallPeerSeekingAll(SetPositions(pCurrent, CurrentFlags, pStop, StopFlags));
}

STDMETHODIMP CStreamSwitcherPassThru::GetPositions(LONGLONG* pCurrent, LONGLONG* pStop)
{
    CallPeerSeeking(GetPositions(pCurrent, pStop));
}

STDMETHODIMP CStreamSwitcherPassThru::GetCurrentPosition(LONGLONG* pCurrent)
{
    CallPeerSeeking(GetCurrentPosition(pCurrent));
}

STDMETHODIMP CStreamSwitcherPassThru::GetStopPosition(LONGLONG* pStop)
{
    CallPeerSeeking(GetStopPosition(pStop));
}

STDMETHODIMP CStreamSwitcherPassThru::GetDuration(LONGLONG* pDuration)
{
    CallPeerSeeking(GetDuration(pDuration));
}

STDMETHODIMP CStreamSwitcherPassThru::GetPreroll(LONGLONG* pllPreroll)
{
    CallPeerSeeking(GetPreroll(pllPreroll));
}

STDMETHODIMP CStreamSwitcherPassThru::GetAvailable(LONGLONG* pEarliest, LONGLONG* pLatest)
{
    CallPeerSeeking(GetAvailable(pEarliest, pLatest));
}

STDMETHODIMP CStreamSwitcherPassThru::GetRate(double* pdRate)
{
    CallPeerSeeking(GetRate(pdRate));
}

STDMETHODIMP CStreamSwitcherPassThru::SetRate(double dRate)
{
    if (0.0 == dRate) {
        return E_INVALIDARG;
    }
    CallPeerSeekingAll(SetRate(dRate));
}

// IMediaPosition

STDMETHODIMP CStreamSwitcherPassThru::get_Duration(REFTIME* plength)
{
    CallPeer(get_Duration(plength));
}

STDMETHODIMP CStreamSwitcherPassThru::get_CurrentPosition(REFTIME* pllTime)
{
    CallPeer(get_CurrentPosition(pllTime));
}

STDMETHODIMP CStreamSwitcherPassThru::put_CurrentPosition(REFTIME llTime)
{
    CallPeerAll(put_CurrentPosition(llTime));
}

STDMETHODIMP CStreamSwitcherPassThru::get_StopTime(REFTIME* pllTime)
{
    CallPeer(get_StopTime(pllTime));
}

STDMETHODIMP CStreamSwitcherPassThru::put_StopTime(REFTIME llTime)
{
    CallPeerAll(put_StopTime(llTime));
}

STDMETHODIMP CStreamSwitcherPassThru::get_PrerollTime(REFTIME* pllTime)
{
    CallPeer(get_PrerollTime(pllTime));
}

STDMETHODIMP CStreamSwitcherPassThru::put_PrerollTime(REFTIME llTime)
{
    CallPeerAll(put_PrerollTime(llTime));
}

STDMETHODIMP CStreamSwitcherPassThru::get_Rate(double* pdRate)
{
    CallPeer(get_Rate(pdRate));
}

STDMETHODIMP CStreamSwitcherPassThru::put_Rate(double dRate)
{
    if (0.0 == dRate) {
        return E_INVALIDARG;
    }
    CallPeerAll(put_Rate(dRate));
}

STDMETHODIMP CStreamSwitcherPassThru::CanSeekForward(LONG* pCanSeekForward)
{
    CallPeer(CanSeekForward(pCanSeekForward));
}

STDMETHODIMP CStreamSwitcherPassThru::CanSeekBackward(LONG* pCanSeekBackward)
{
    CallPeer(CanSeekBackward(pCanSeekBackward));
}

//
// CStreamSwitcherAllocator
//

CStreamSwitcherAllocator::CStreamSwitcherAllocator(CStreamSwitcherInputPin* pPin, HRESULT* phr)
    : CMemAllocator(NAME("CStreamSwitcherAllocator"), nullptr, phr)
    , m_pPin(pPin)
    , m_fMediaTypeChanged(false)
{
    ASSERT(phr);
    ASSERT(pPin);
}

#ifdef _DEBUG
CStreamSwitcherAllocator::~CStreamSwitcherAllocator()
{
    ASSERT(m_bCommitted == FALSE);
}
#endif

STDMETHODIMP_(ULONG) CStreamSwitcherAllocator::NonDelegatingAddRef()
{
    return m_pPin->m_pFilter->AddRef();
}

STDMETHODIMP_(ULONG) CStreamSwitcherAllocator::NonDelegatingRelease()
{
    return m_pPin->m_pFilter->Release();
}

STDMETHODIMP CStreamSwitcherAllocator::GetBuffer(
    IMediaSample** ppBuffer,
    REFERENCE_TIME* pStartTime, REFERENCE_TIME* pEndTime,
    DWORD dwFlags)
{
    HRESULT hr = VFW_E_NOT_COMMITTED;

    if (!m_bCommitted) {
        return hr;
    }
    /*
    TRACE(_T("CStreamSwitcherAllocator::GetBuffer m_pPin->m_evBlock.Wait() + %x\n"), this);
        m_pPin->m_evBlock.Wait();
    TRACE(_T("CStreamSwitcherAllocator::GetBuffer m_pPin->m_evBlock.Wait() - %x\n"), this);
    */
    if (m_fMediaTypeChanged) {
        if (!m_pPin || !m_pPin->m_pFilter) {
            return hr;
        }

        CStreamSwitcherOutputPin* pOut = (static_cast<CStreamSwitcherFilter*>(m_pPin->m_pFilter))->GetOutputPin();
        if (!pOut || !pOut->CurrentAllocator()) {
            return hr;
        }

        ALLOCATOR_PROPERTIES Properties, Actual;
        if (FAILED(pOut->CurrentAllocator()->GetProperties(&Actual))) {
            return hr;
        }
        if (FAILED(GetProperties(&Properties))) {
            return hr;
        }

        if (!m_bCommitted || Properties.cbBuffer < Actual.cbBuffer) {
            Properties.cbBuffer = Actual.cbBuffer;
            if (FAILED(Decommit())) {
                return hr;
            }
            if (FAILED(SetProperties(&Properties, &Actual))) {
                return hr;
            }
            if (FAILED(Commit())) {
                return hr;
            }
            ASSERT(Actual.cbBuffer >= Properties.cbBuffer);
            if (Actual.cbBuffer < Properties.cbBuffer) {
                return hr;
            }
        }
    }

    hr = CMemAllocator::GetBuffer(ppBuffer, pStartTime, pEndTime, dwFlags);

    if (m_fMediaTypeChanged && SUCCEEDED(hr)) {
        (*ppBuffer)->SetMediaType(&m_mt);
        m_fMediaTypeChanged = false;
    }

    return hr;
}

void CStreamSwitcherAllocator::NotifyMediaType(const CMediaType& mt)
{
    CopyMediaType(&m_mt, &mt);
    m_fMediaTypeChanged = true;
}


//
// CStreamSwitcherInputPin
//

CStreamSwitcherInputPin::CStreamSwitcherInputPin(CStreamSwitcherFilter* pFilter, HRESULT* phr, LPCWSTR pName)
    : CBaseInputPin(NAME("CStreamSwitcherInputPin"), pFilter, &pFilter->m_csState, phr, pName)
    , m_Allocator(this, phr)
    , m_bSampleSkipped(FALSE)
    , m_bQualityChanged(FALSE)
    , m_bUsingOwnAllocator(FALSE)
    , m_evBlock(TRUE)
    , m_fCanBlock(false)
    , m_hNotifyEvent(nullptr)
{
    m_bCanReconnectWhenActive = true;
}

class __declspec(uuid("138130AF-A79B-45D5-B4AA-87697457BA87"))
    NeroAudioDecoder {};

STDMETHODIMP CStreamSwitcherInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
    return
        QI(IStreamSwitcherInputPin)
        IsConnected() && GetCLSID(GetFilterFromPin(GetConnected())) == __uuidof(NeroAudioDecoder) && QI(IPinConnection)
        __super::NonDelegatingQueryInterface(riid, ppv);
}

// IPinConnection

STDMETHODIMP CStreamSwitcherInputPin::DynamicQueryAccept(const AM_MEDIA_TYPE* pmt)
{
    return QueryAccept(pmt);
}

STDMETHODIMP CStreamSwitcherInputPin::NotifyEndOfStream(HANDLE hNotifyEvent)
{
    if (m_hNotifyEvent) {
        SetEvent(m_hNotifyEvent);
    }
    m_hNotifyEvent = hNotifyEvent;
    return S_OK;
}

STDMETHODIMP CStreamSwitcherInputPin::IsEndPin()
{
    return S_OK;
}

STDMETHODIMP CStreamSwitcherInputPin::DynamicDisconnect()
{
    CAutoLock cAutoLock(&m_csReceive);
    Disconnect();
    return S_OK;
}

// IStreamSwitcherInputPin

STDMETHODIMP_(bool) CStreamSwitcherInputPin::IsActive()
{
    // TODO: lock onto something here
    return (this == (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetInputPin());
}

//

HRESULT CStreamSwitcherInputPin::QueryAcceptDownstream(const AM_MEDIA_TYPE* pmt)
{
    HRESULT hr = S_OK;

    CStreamSwitcherOutputPin* pOut = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetOutputPin();

    if (pOut && pOut->IsConnected()) {
        if (CComPtr<IPinConnection> pPC = pOut->CurrentPinConnection()) {
            hr = pPC->DynamicQueryAccept(pmt);
            if (hr == S_OK) {
                return S_OK;
            }
        }

        hr = pOut->GetConnected()->QueryAccept(pmt);
    }

    return hr;
}

void CStreamSwitcherInputPin::Block(bool fBlock)
{
    if (fBlock) {
        m_evBlock.Reset();
    } else {
        m_evBlock.Set();
    }
}

HRESULT CStreamSwitcherInputPin::InitializeOutputSample(IMediaSample* pInSample, IMediaSample** ppOutSample)
{
    if (!pInSample || !ppOutSample) {
        return E_POINTER;
    }

    CStreamSwitcherOutputPin* pOut = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetOutputPin();
    ASSERT(pOut->GetConnected());

    CComPtr<IMediaSample> pOutSample;

    DWORD dwFlags = m_bSampleSkipped ? AM_GBF_PREVFRAMESKIPPED : 0;

    if (!(m_SampleProps.dwSampleFlags & AM_SAMPLE_SPLICEPOINT)) {
        dwFlags |= AM_GBF_NOTASYNCPOINT;
    }

    HRESULT hr = pOut->GetDeliveryBuffer(&pOutSample
                                         , m_SampleProps.dwSampleFlags & AM_SAMPLE_TIMEVALID ? &m_SampleProps.tStart : nullptr
                                         , m_SampleProps.dwSampleFlags & AM_SAMPLE_STOPVALID ? &m_SampleProps.tStop : nullptr
                                         , dwFlags);

    if (FAILED(hr)) {
        return hr;
    }

    if (!pOutSample) {
        return E_FAIL;
    }

    if (CComQIPtr<IMediaSample2> pOutSample2 = pOutSample) {
        AM_SAMPLE2_PROPERTIES OutProps;
        EXECUTE_ASSERT(SUCCEEDED(pOutSample2->GetProperties(FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, tStart), (PBYTE)&OutProps)));
        OutProps.dwTypeSpecificFlags = m_SampleProps.dwTypeSpecificFlags;
        OutProps.dwSampleFlags =
            (OutProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED) |
            (m_SampleProps.dwSampleFlags & ~AM_SAMPLE_TYPECHANGED);

        OutProps.tStart = m_SampleProps.tStart;
        OutProps.tStop  = m_SampleProps.tStop;
        OutProps.cbData = FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, dwStreamId);

        pOutSample2->SetProperties(FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, dwStreamId), (PBYTE)&OutProps);
        if (m_SampleProps.dwSampleFlags & AM_SAMPLE_DATADISCONTINUITY) {
            m_bSampleSkipped = FALSE;
        }
    } else {
        if (m_SampleProps.dwSampleFlags & AM_SAMPLE_TIMEVALID) {
            pOutSample->SetTime(&m_SampleProps.tStart, &m_SampleProps.tStop);
        }

        if (m_SampleProps.dwSampleFlags & AM_SAMPLE_SPLICEPOINT) {
            pOutSample->SetSyncPoint(TRUE);
        }

        if (m_SampleProps.dwSampleFlags & AM_SAMPLE_DATADISCONTINUITY) {
            pOutSample->SetDiscontinuity(TRUE);
            m_bSampleSkipped = FALSE;
        }

        LONGLONG MediaStart, MediaEnd;
        if (pInSample->GetMediaTime(&MediaStart, &MediaEnd) == NOERROR) {
            pOutSample->SetMediaTime(&MediaStart, &MediaEnd);
        }
    }

    *ppOutSample = pOutSample.Detach();

    return S_OK;
}

// pure virtual

HRESULT CStreamSwitcherInputPin::CheckMediaType(const CMediaType* pmt)
{
    return (static_cast<CStreamSwitcherFilter*>(m_pFilter))->CheckMediaType(pmt);
}

// virtual

HRESULT CStreamSwitcherInputPin::CheckConnect(IPin* pPin)
{
    return (IPin*)(static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetOutputPin() == pPin
           ? E_FAIL
           : __super::CheckConnect(pPin);
}

HRESULT CStreamSwitcherInputPin::CompleteConnect(IPin* pReceivePin)
{
    HRESULT hr = __super::CompleteConnect(pReceivePin);
    if (FAILED(hr)) {
        return hr;
    }

    (static_cast<CStreamSwitcherFilter*>(m_pFilter))->CompleteConnect(PINDIR_INPUT, this, pReceivePin);

    m_fCanBlock = false;
    bool fForkedSomewhere = false;

    CStringW fileName;
    CStringW pinName;

    IPin* pPin = (IPin*)this;
    IBaseFilter* pBF = (IBaseFilter*)m_pFilter;

    pPin = GetUpStreamPin(pBF, pPin);
    if (pPin) {
        pBF = GetFilterFromPin(pPin);
    }
    while (pPin && pBF) {
        if (IsSplitter(pBF)) {
            pinName = GetPinName(pPin);
        }

        CLSID clsid = GetCLSID(pBF);
        if (clsid == CLSID_AviSplitter || clsid == CLSID_OggSplitter) {
            m_fCanBlock = true;
        }

        int nIn, nOut, nInC, nOutC;
        CountPins(pBF, nIn, nOut, nInC, nOutC);
        fForkedSomewhere = fForkedSomewhere || nIn > 1 || nOut > 1;

        DWORD cStreams = 0;
        if (CComQIPtr<IAMStreamSelect> pSSF = pBF) {
            hr = pSSF->Count(&cStreams);
            if (SUCCEEDED(hr)) {
                for (int i = 0; i < (int)cStreams; i++) {
                    AM_MEDIA_TYPE* pmt = nullptr;
                    hr = pSSF->Info(i, &pmt, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
                    if (SUCCEEDED(hr) && pmt && pmt->majortype == MEDIATYPE_Audio) {
                        m_pSSF = pSSF;
                        DeleteMediaType(pmt);
                        break;
                    }
                    DeleteMediaType(pmt);
                }
            }
        }

        if (CComQIPtr<IFileSourceFilter> pFSF = pBF) {
            WCHAR* pszName = nullptr;
            AM_MEDIA_TYPE mt;
            if (SUCCEEDED(pFSF->GetCurFile(&pszName, &mt)) && pszName) {
                fileName = pszName;
                CoTaskMemFree(pszName);

                fileName.Replace('\\', '/');
                CStringW fn = fileName.Mid(fileName.ReverseFind('/') + 1);
                if (!fn.IsEmpty()) {
                    fileName = fn;
                }

                // Haali & LAVFSplitter return only one "Audio" pin name, cause CMainFrame::OnInitMenuPopup lookup find the wrong popmenu,
                // add space at the end to prevent this, internal filter never return "Audio" only.
                if (!pinName.IsEmpty()) {
                    fileName = pinName + L" ";
                }

                WCHAR* pName = DEBUG_NEW WCHAR[fileName.GetLength() + 1];
                if (pName) {
                    wcscpy_s(pName, fileName.GetLength() + 1, fileName);
                    if (m_pName) {
                        delete [] m_pName;
                    }
                    m_pName = pName;
                    if (cStreams == 1) { // Simple external track, no need to use the info from IAMStreamSelect
                        m_pSSF.Release();
                    }
                }
            }

            break;
        }

        pPin = GetFirstPin(pBF);

        pPin = GetUpStreamPin(pBF, pPin);
        if (pPin) {
            pBF = GetFilterFromPin(pPin);
        }
    }

    if (!fForkedSomewhere) {
        m_fCanBlock = true;
    }

    m_hNotifyEvent = nullptr;

    return S_OK;
}

HRESULT CStreamSwitcherInputPin::Active()
{
    Block(!IsActive());

    return __super::Active();
}

HRESULT CStreamSwitcherInputPin::Inactive()
{
    Block(false);

    return __super::Inactive();
}

// IPin

STDMETHODIMP CStreamSwitcherInputPin::QueryAccept(const AM_MEDIA_TYPE* pmt)
{
    HRESULT hr = __super::QueryAccept(pmt);
    if (S_OK != hr) {
        return hr;
    }

    return QueryAcceptDownstream(pmt);
}

STDMETHODIMP CStreamSwitcherInputPin::ReceiveConnection(IPin* pConnector, const AM_MEDIA_TYPE* pmt)
{
    // FIXME: this locked up once
    //    CAutoLock cAutoLock(&((CStreamSwitcherFilter*)m_pFilter)->m_csReceive);

    HRESULT hr;
    if (S_OK != (hr = QueryAcceptDownstream(pmt))) {
        return VFW_E_TYPE_NOT_ACCEPTED;
    }

    if (m_Connected && m_Connected != pConnector) {
        return VFW_E_ALREADY_CONNECTED;
    }

    SAFE_RELEASE(m_Connected);

    return SUCCEEDED(__super::ReceiveConnection(pConnector, pmt)) ? S_OK : E_FAIL;
}

STDMETHODIMP CStreamSwitcherInputPin::GetAllocator(IMemAllocator** ppAllocator)
{
    CheckPointer(ppAllocator, E_POINTER);

    if (m_pAllocator == nullptr) {
        (m_pAllocator = &m_Allocator)->AddRef();
    }

    (*ppAllocator = m_pAllocator)->AddRef();

    return NOERROR;
}

STDMETHODIMP CStreamSwitcherInputPin::NotifyAllocator(IMemAllocator* pAllocator, BOOL bReadOnly)
{
    HRESULT hr = __super::NotifyAllocator(pAllocator, bReadOnly);
    if (FAILED(hr)) {
        return hr;
    }

    m_bUsingOwnAllocator = (pAllocator == (IMemAllocator*)&m_Allocator);

    return S_OK;
}

STDMETHODIMP CStreamSwitcherInputPin::BeginFlush()
{
    CAutoLock cAutoLock(&(static_cast<CStreamSwitcherFilter*>(m_pFilter))->m_csState);

    HRESULT hr;

    CStreamSwitcherFilter* pSSF = static_cast<CStreamSwitcherFilter*>(m_pFilter);

    CStreamSwitcherOutputPin* pOut = pSSF->GetOutputPin();
    if (!IsConnected() || !pOut || !pOut->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }

    if (FAILED(hr = __super::BeginFlush())) {
        return hr;
    }

    return IsActive() ? pSSF->DeliverBeginFlush() : Block(false), S_OK;
}

STDMETHODIMP CStreamSwitcherInputPin::EndFlush()
{
    CAutoLock cAutoLock(&(static_cast<CStreamSwitcherFilter*>(m_pFilter))->m_csState);

    HRESULT hr;

    CStreamSwitcherFilter* pSSF = static_cast<CStreamSwitcherFilter*>(m_pFilter);

    CStreamSwitcherOutputPin* pOut = pSSF->GetOutputPin();
    if (!IsConnected() || !pOut || !pOut->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }

    if (FAILED(hr = __super::EndFlush())) {
        return hr;
    }

    return IsActive() ? pSSF->DeliverEndFlush() : Block(true), S_OK;
}

STDMETHODIMP CStreamSwitcherInputPin::EndOfStream()
{
    CAutoLock cAutoLock(&m_csReceive);

    CStreamSwitcherFilter* pSSF = static_cast<CStreamSwitcherFilter*>(m_pFilter);

    CStreamSwitcherOutputPin* pOut = pSSF->GetOutputPin();
    if (!IsConnected() || !pOut || !pOut->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }

    if (m_hNotifyEvent) {
        SetEvent(m_hNotifyEvent), m_hNotifyEvent = nullptr;
        return S_OK;
    }

    return IsActive() ? pSSF->DeliverEndOfStream() : S_OK;
}

// IMemInputPin

STDMETHODIMP CStreamSwitcherInputPin::Receive(IMediaSample* pSample)
{
    AM_MEDIA_TYPE* pmt = nullptr;
    if (SUCCEEDED(pSample->GetMediaType(&pmt)) && pmt) {
        const CMediaType mt(*pmt);
        DeleteMediaType(pmt), pmt = nullptr;
        SetMediaType(&mt);
    }

    // DAMN!!!!!! this doesn't work if the stream we are blocking
    // shares the same thread with another stream, mpeg splitters
    // are usually like that. Our nicely built up multithreaded
    // strategy is useless because of this, ARRRRRRGHHHHHH.

#ifdef BLOCKSTREAM
    if (m_fCanBlock) {
        m_evBlock.Wait();
    }
#endif

    if (!IsActive()) {
#ifdef BLOCKSTREAM
        if (m_fCanBlock) {
            return S_FALSE;
        }
#endif

        TRACE(_T("&^$#@ : a stupid fix for this stupid problem\n"));
        //Sleep(32);
        return E_FAIL; // a stupid fix for this stupid problem
    }

    CAutoLock cAutoLock(&m_csReceive);

    CStreamSwitcherOutputPin* pOut = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetOutputPin();
    ASSERT(pOut->GetConnected());

    HRESULT hr = __super::Receive(pSample);
    if (S_OK != hr) {
        return hr;
    }

    if (m_SampleProps.dwStreamId != AM_STREAM_MEDIA) {
        return pOut->Deliver(pSample);
    }

    //

    ALLOCATOR_PROPERTIES props, actual;
    m_pAllocator->GetProperties(&props);
    pOut->CurrentAllocator()->GetProperties(&actual);

    REFERENCE_TIME rtStart = 0, rtStop = 0;
    if (S_OK == pSample->GetTime(&rtStart, &rtStop)) {
        //
    }

    long cbBuffer = pSample->GetActualDataLength();

    CMediaType mtOut = m_mt;
    mtOut = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->CreateNewOutputMediaType(mtOut, cbBuffer);

    bool fTypeChanged = false;

    if (mtOut != pOut->CurrentMediaType() || cbBuffer > actual.cbBuffer) {
        fTypeChanged = true;

        m_SampleProps.dwSampleFlags |= AM_SAMPLE_TYPECHANGED/*|AM_SAMPLE_DATADISCONTINUITY|AM_SAMPLE_TIMEDISCONTINUITY*/;

        if (props.cBuffers < 8 && mtOut.majortype == MEDIATYPE_Audio) {
            props.cBuffers = 8;
        }

        props.cbBuffer = cbBuffer;

        if (actual.cbAlign != props.cbAlign
                || actual.cbPrefix != props.cbPrefix
                || actual.cBuffers < props.cBuffers
                || actual.cbBuffer < props.cbBuffer) {
            pOut->DeliverBeginFlush();
            pOut->DeliverEndFlush();
            pOut->CurrentAllocator()->Decommit();
            pOut->CurrentAllocator()->SetProperties(&props, &actual);
            pOut->CurrentAllocator()->Commit();
        }
    }

    CComPtr<IMediaSample> pOutSample;
    if (FAILED(InitializeOutputSample(pSample, &pOutSample))) {
        return E_FAIL;
    }

    pmt = nullptr;
    if (SUCCEEDED(pOutSample->GetMediaType(&pmt)) && pmt) {
        const CMediaType mt(*pmt);
        DeleteMediaType(pmt), pmt = nullptr;
        // TODO
        ASSERT(0);
    }

    if (fTypeChanged) {
        pOut->SetMediaType(&mtOut);
        (static_cast<CStreamSwitcherFilter*>(m_pFilter))->OnNewOutputMediaType(m_mt, mtOut);
        pOutSample->SetMediaType(&mtOut);
    }

    // Transform

    hr = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->Transform(pSample, pOutSample);

    if (S_OK == hr) {
        hr = pOut->Deliver(pOutSample);
        m_bSampleSkipped = FALSE;
    } else if (S_FALSE == hr) {
        hr = S_OK;
        pOutSample = nullptr;
        m_bSampleSkipped = TRUE;

        if (!m_bQualityChanged) {
            m_pFilter->NotifyEvent(EC_QUALITY_CHANGE, 0, 0);
            m_bQualityChanged = TRUE;
        }
    }

    return hr;
}

STDMETHODIMP CStreamSwitcherInputPin::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
    if (!IsConnected()) {
        return S_OK;
    }

    CAutoLock cAutoLock(&m_csReceive);

    CStreamSwitcherFilter* pSSF = static_cast<CStreamSwitcherFilter*>(m_pFilter);

    CStreamSwitcherOutputPin* pOut = pSSF->GetOutputPin();
    if (!pOut || !pOut->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }

    return pSSF->DeliverNewSegment(tStart, tStop, dRate);
}

//
// CStreamSwitcherOutputPin
//

CStreamSwitcherOutputPin::CStreamSwitcherOutputPin(CStreamSwitcherFilter* pFilter, HRESULT* phr)
    : CBaseOutputPin(NAME("CStreamSwitcherOutputPin"), pFilter, &pFilter->m_csState, phr, L"Out")
{
    //  m_bCanReconnectWhenActive = true;
}

STDMETHODIMP CStreamSwitcherOutputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
    CheckPointer(ppv, E_POINTER);
    ValidateReadWritePtr(ppv, sizeof(PVOID));
    *ppv = nullptr;

    if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) {
        if (m_pStreamSwitcherPassThru == nullptr) {
            HRESULT hr = S_OK;
            m_pStreamSwitcherPassThru = (IUnknown*)(INonDelegatingUnknown*)
                                        DEBUG_NEW CStreamSwitcherPassThru(GetOwner(), &hr, static_cast<CStreamSwitcherFilter*>(m_pFilter));

            if (!m_pStreamSwitcherPassThru) {
                return E_OUTOFMEMORY;
            }
            if (FAILED(hr)) {
                return hr;
            }
        }

        return m_pStreamSwitcherPassThru->QueryInterface(riid, ppv);
    }
    /*
        else if (riid == IID_IStreamBuilder)
        {
            return GetInterface((IStreamBuilder*)this, ppv);
        }
    */
    return CBaseOutputPin::NonDelegatingQueryInterface(riid, ppv);
}

HRESULT CStreamSwitcherOutputPin::QueryAcceptUpstream(const AM_MEDIA_TYPE* pmt)
{
    HRESULT hr = S_FALSE;

    CStreamSwitcherInputPin* pIn = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetInputPin();

    if (pIn && pIn->IsConnected() && (pIn->IsUsingOwnAllocator() || pIn->CurrentMediaType() == *pmt)) {
        if (CComQIPtr<IPin> pPinTo = pIn->GetConnected()) {
            if (S_OK != (hr = pPinTo->QueryAccept(pmt))) {
                return VFW_E_TYPE_NOT_ACCEPTED;
            }
        } else {
            return E_FAIL;
        }
    }

    return hr;
}

// pure virtual

HRESULT CStreamSwitcherOutputPin::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties)
{
    CStreamSwitcherInputPin* pIn = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetInputPin();
    if (!pIn || !pIn->IsConnected()) {
        return E_UNEXPECTED;
    }

    CComPtr<IMemAllocator> pAllocatorIn;
    pIn->GetAllocator(&pAllocatorIn);
    if (!pAllocatorIn) {
        return E_UNEXPECTED;
    }

    HRESULT hr;
    if (FAILED(hr = pAllocatorIn->GetProperties(pProperties))) {
        return hr;
    }

    if (pProperties->cBuffers < 8 && pIn->CurrentMediaType().majortype == MEDIATYPE_Audio) {
        pProperties->cBuffers = 8;
    }

    ALLOCATOR_PROPERTIES Actual;
    if (FAILED(hr = pAllocator->SetProperties(pProperties, &Actual))) {
        return hr;
    }

    return (pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer
            ? E_FAIL
            : NOERROR);
}

// virtual

class __declspec(uuid("AEFA5024-215A-4FC7-97A4-1043C86FD0B8"))
    MatrixMixer {};

HRESULT CStreamSwitcherOutputPin::CheckConnect(IPin* pPin)
{
    CComPtr<IBaseFilter> pBF = GetFilterFromPin(pPin);

    return
        IsAudioWaveRenderer(pBF) || GetCLSID(pBF) == __uuidof(MatrixMixer)
        ? __super::CheckConnect(pPin)
        : E_FAIL;

    //  return CComQIPtr<IPinConnection>(pPin) ? CBaseOutputPin::CheckConnect(pPin) : E_NOINTERFACE;
    //  return CBaseOutputPin::CheckConnect(pPin);
}

HRESULT CStreamSwitcherOutputPin::BreakConnect()
{
    m_pPinConnection = nullptr;
    return __super::BreakConnect();
}

HRESULT CStreamSwitcherOutputPin::CompleteConnect(IPin* pReceivePin)
{
    m_pPinConnection = CComQIPtr<IPinConnection>(pReceivePin);
    HRESULT hr = __super::CompleteConnect(pReceivePin);

    CStreamSwitcherInputPin* pIn = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetInputPin();
    CMediaType mt;
    if (SUCCEEDED(hr) && pIn && pIn->IsConnected()
            && SUCCEEDED(pIn->GetConnected()->ConnectionMediaType(&mt)) && m_mt != mt) {
        if (pIn->GetConnected()->QueryAccept(&m_mt) == S_OK) {
            hr = m_pFilter->ReconnectPin(pIn->GetConnected(), &m_mt);
        } else {
            hr = VFW_E_TYPE_NOT_ACCEPTED;
        }
    }

    return hr;
}

HRESULT CStreamSwitcherOutputPin::CheckMediaType(const CMediaType* pmt)
{
    return (static_cast<CStreamSwitcherFilter*>(m_pFilter))->CheckMediaType(pmt);
}

HRESULT CStreamSwitcherOutputPin::GetMediaType(int iPosition, CMediaType* pmt)
{
    CStreamSwitcherInputPin* pIn = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetInputPin();
    if (!pIn || !pIn->IsConnected()) {
        return E_UNEXPECTED;
    }

    CComPtr<IEnumMediaTypes> pEM;
    if (FAILED(pIn->GetConnected()->EnumMediaTypes(&pEM))) {
        return VFW_S_NO_MORE_ITEMS;
    }

    if (iPosition > 0 && FAILED(pEM->Skip(iPosition))) {
        return VFW_S_NO_MORE_ITEMS;
    }

    AM_MEDIA_TYPE* tmp = nullptr;
    if (S_OK != pEM->Next(1, &tmp, nullptr) || !tmp) {
        return VFW_S_NO_MORE_ITEMS;
    }

    CopyMediaType(pmt, tmp);
    DeleteMediaType(tmp);
    /*
        if (iPosition < 0) return E_INVALIDARG;
        if (iPosition > 0) return VFW_S_NO_MORE_ITEMS;

        CopyMediaType(pmt, &pIn->CurrentMediaType());
    */
    return S_OK;
}

// IPin

STDMETHODIMP CStreamSwitcherOutputPin::QueryAccept(const AM_MEDIA_TYPE* pmt)
{
    HRESULT hr = __super::QueryAccept(pmt);
    if (S_OK != hr) {
        return hr;
    }

    return QueryAcceptUpstream(pmt);
}

// IQualityControl

STDMETHODIMP CStreamSwitcherOutputPin::Notify(IBaseFilter* pSender, Quality q)
{
    CStreamSwitcherInputPin* pIn = (static_cast<CStreamSwitcherFilter*>(m_pFilter))->GetInputPin();
    if (!pIn || !pIn->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }
    return pIn->PassNotify(q);
}

// IStreamBuilder

STDMETHODIMP CStreamSwitcherOutputPin::Render(IPin* ppinOut, IGraphBuilder* pGraph)
{
    CComPtr<IBaseFilter> pBF;
    pBF.CoCreateInstance(CLSID_DSoundRender);
    if (!pBF || FAILED(pGraph->AddFilter(pBF, L"Default DirectSound Device"))) {
        return E_FAIL;
    }

    if (FAILED(pGraph->ConnectDirect(ppinOut, GetFirstDisconnectedPin(pBF, PINDIR_INPUT), nullptr))) {
        pGraph->RemoveFilter(pBF);
        return E_FAIL;
    }

    return S_OK;
}

STDMETHODIMP CStreamSwitcherOutputPin::Backout(IPin* ppinOut, IGraphBuilder* pGraph)
{
    return S_OK;
}

//
// CStreamSwitcherFilter
//

CStreamSwitcherFilter::CStreamSwitcherFilter(LPUNKNOWN lpunk, HRESULT* phr, const CLSID& clsid)
    : CBaseFilter(NAME("CStreamSwitcherFilter"), lpunk, &m_csState, clsid)
    , m_pInput(nullptr)
    , m_pOutput(nullptr)
{
    if (phr) {
        *phr = S_OK;
    }

    HRESULT hr = S_OK;

    do {
        CAutoPtr<CStreamSwitcherInputPin> pInput;
        CAutoPtr<CStreamSwitcherOutputPin> pOutput;

        hr = S_OK;
        pInput.Attach(DEBUG_NEW CStreamSwitcherInputPin(this, &hr, L"Channel 1"));
        if (!pInput || FAILED(hr)) {
            break;
        }

        hr = S_OK;
        pOutput.Attach(DEBUG_NEW CStreamSwitcherOutputPin(this, &hr));
        if (!pOutput || FAILED(hr)) {
            break;
        }

        CAutoLock cAutoLock(&m_csPins);

        m_pInputs.AddHead(m_pInput = pInput.Detach());
        m_pOutput = pOutput.Detach();

        return;
    } while (false);

    if (phr) {
        *phr = E_FAIL;
    }
}

CStreamSwitcherFilter::~CStreamSwitcherFilter()
{
    CAutoLock cAutoLock(&m_csPins);

    POSITION pos = m_pInputs.GetHeadPosition();
    while (pos) {
        delete m_pInputs.GetNext(pos);
    }
    m_pInputs.RemoveAll();
    m_pInput = nullptr;

    delete m_pOutput;
    m_pOutput = nullptr;
}

STDMETHODIMP CStreamSwitcherFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
    return
        QI(IAMStreamSelect)
        __super::NonDelegatingQueryInterface(riid, ppv);
}

//

int CStreamSwitcherFilter::GetPinCount()
{
    CAutoLock cAutoLock(&m_csPins);

    return (1 + (int)m_pInputs.GetCount());
}

CBasePin* CStreamSwitcherFilter::GetPin(int n)
{
    CAutoLock cAutoLock(&m_csPins);

    if (n < 0 || n >= GetPinCount()) {
        return nullptr;
    } else if (n == 0) {
        return m_pOutput;
    } else {
        return m_pInputs.GetAt(m_pInputs.FindIndex(n - 1));
    }
}

int CStreamSwitcherFilter::GetConnectedInputPinCount()
{
    CAutoLock cAutoLock(&m_csPins);

    int nConnected = 0;
    POSITION pos = m_pInputs.GetHeadPosition();

    while (pos) {
        if (m_pInputs.GetNext(pos)->IsConnected()) {
            nConnected++;
        }
    }

    return nConnected;
}

CStreamSwitcherInputPin* CStreamSwitcherFilter::GetConnectedInputPin(int n)
{
    if (n >= 0) {
        POSITION pos = m_pInputs.GetHeadPosition();
        while (pos) {
            CStreamSwitcherInputPin* pPin = m_pInputs.GetNext(pos);
            if (pPin->IsConnected()) {
                if (n == 0) {
                    return pPin;
                }
                n--;
            }
        }
    }

    return nullptr;
}

CStreamSwitcherInputPin* CStreamSwitcherFilter::GetInputPin()
{
    return m_pInput;
}

CStreamSwitcherOutputPin* CStreamSwitcherFilter::GetOutputPin()
{
    return m_pOutput;
}

//

HRESULT CStreamSwitcherFilter::CompleteConnect(PIN_DIRECTION dir, CBasePin* pPin, IPin* pReceivePin)
{
    if (dir == PINDIR_INPUT) {
        CAutoLock cAutoLock(&m_csPins);

        int nConnected = GetConnectedInputPinCount();

        if (nConnected == 1) {
            m_pInput = static_cast<CStreamSwitcherInputPin*>(pPin);
        }

        if ((size_t)nConnected == m_pInputs.GetCount()) {
            CStringW name;
            name.Format(L"Channel %ld", ++m_PinVersion);

            HRESULT hr = S_OK;
            CStreamSwitcherInputPin* pPin = DEBUG_NEW CStreamSwitcherInputPin(this, &hr, name);
            if (!pPin || FAILED(hr)) {
                delete pPin;
                return E_FAIL;
            }
            m_pInputs.AddTail(pPin);
        }
    }

    return S_OK;
}

// this should be very thread safe, I hope it is, it must be... :)

void CStreamSwitcherFilter::SelectInput(CStreamSwitcherInputPin* pInput)
{
    // make sure no input thinks it is active
    m_pInput = nullptr;

    // release blocked GetBuffer in our own allocator & block all Receive
    POSITION pos = m_pInputs.GetHeadPosition();
    while (pos) {
        CStreamSwitcherInputPin* pPin = m_pInputs.GetNext(pos);
        pPin->Block(false);
        // a few Receive calls can arrive here, but since m_pInput == nullptr neighter of them gets delivered
        pPin->Block(true);
    }

    // this will let waiting GetBuffer() calls go on inside our Receive()
    if (m_pOutput) {
        m_pOutput->DeliverBeginFlush();
        m_pOutput->DeliverEndFlush();
    }

    if (!pInput) {
        return;
    }

    // set new input
    m_pInput = pInput;

    // let it go
    m_pInput->Block(false);
}

//

HRESULT CStreamSwitcherFilter::Transform(IMediaSample* pIn, IMediaSample* pOut)
{
    BYTE* pDataIn  = nullptr;
    BYTE* pDataOut = nullptr;

    HRESULT hr;
    if (FAILED(hr = pIn->GetPointer(&pDataIn))) {
        return hr;
    }
    if (FAILED(hr = pOut->GetPointer(&pDataOut))) {
        return hr;
    }

    long len  = pIn->GetActualDataLength();
    long size = pOut->GetSize();

    if (!pDataIn || !pDataOut /*|| len > size || len <= 0*/) {
        return S_FALSE;    // FIXME
    }

    memcpy(pDataOut, pDataIn, std::min(len, size));
    pOut->SetActualDataLength(std::min(len, size));

    return S_OK;
}

CMediaType CStreamSwitcherFilter::CreateNewOutputMediaType(CMediaType mt, long& cbBuffer)
{
    return mt;
}

HRESULT CStreamSwitcherFilter::DeliverEndOfStream()
{
    return m_pOutput ? m_pOutput->DeliverEndOfStream() : E_FAIL;
}

HRESULT CStreamSwitcherFilter::DeliverBeginFlush()
{
    return m_pOutput ? m_pOutput->DeliverBeginFlush() : E_FAIL;
}

HRESULT CStreamSwitcherFilter::DeliverEndFlush()
{
    return m_pOutput ? m_pOutput->DeliverEndFlush() : E_FAIL;
}

HRESULT CStreamSwitcherFilter::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
    return m_pOutput ? m_pOutput->DeliverNewSegment(tStart, tStop, dRate) : E_FAIL;
}

// IAMStreamSelect

STDMETHODIMP CStreamSwitcherFilter::Count(DWORD* pcStreams)
{
    CheckPointer(pcStreams, E_POINTER);

    CAutoLock cAutoLock(&m_csPins);

    *pcStreams = 0;
    POSITION pos = m_pInputs.GetHeadPosition();
    while (pos) {
        CStreamSwitcherInputPin* pInputPin = m_pInputs.GetNext(pos);

        if (pInputPin->IsConnected()) {
            if (CComPtr<IAMStreamSelect> pSSF = pInputPin->GetStreamSelectionFilter()) {
                DWORD cStreams = 0;
                HRESULT hr = pSSF->Count(&cStreams);
                if (SUCCEEDED(hr)) {
                    for (int i = 0; i < (int)cStreams; i++) {
                        AM_MEDIA_TYPE* pmt = nullptr;
                        hr = pSSF->Info(i, &pmt, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
                        if (SUCCEEDED(hr) && pmt && pmt->majortype == MEDIATYPE_Audio) {
                            (*pcStreams)++;
                        }
                        DeleteMediaType(pmt);
                    }
                }
            } else {
                (*pcStreams)++;
            }
        }
    }

    return S_OK;
}

// pdwGroup value is set to:
//  - 0 if the track isn't controlled by any underlying IAMStreamSelect interface
//  - 1 if the track is controlled by an underlying IAMStreamSelect interface and is not selected at that level
//  - 2 if the track is controlled by an underlying IAMStreamSelect interface and is selected at that level
STDMETHODIMP CStreamSwitcherFilter::Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD* pdwFlags, LCID* plcid, DWORD* pdwGroup, WCHAR** ppszName, IUnknown** ppObject, IUnknown** ppUnk)
{
    CAutoLock cAutoLock(&m_csPins);

    IUnknown* pObject = nullptr;
    bool bFound = false;
    POSITION pos = m_pInputs.GetHeadPosition();
    while (pos && !bFound) {
        CStreamSwitcherInputPin* pInputPin = m_pInputs.GetNext(pos);

        if (pInputPin->IsConnected()) {
            if (CComPtr<IAMStreamSelect> pSSF = pInputPin->GetStreamSelectionFilter()) {
                DWORD cStreams = 0;
                HRESULT hr = pSSF->Count(&cStreams);
                if (SUCCEEDED(hr)) {
                    for (int i = 0; i < (int)cStreams; i++) {
                        AM_MEDIA_TYPE* pmt = nullptr;
                        DWORD dwFlags;
                        LPWSTR pszName = nullptr;
                        hr = pSSF->Info(i, &pmt, &dwFlags, plcid, nullptr, &pszName, nullptr, nullptr);
                        if (SUCCEEDED(hr) && pmt && pmt->majortype == MEDIATYPE_Audio) {
                            if (lIndex == 0) {
                                bFound = true;
                                pObject = pSSF;

                                if (ppmt) {
                                    *ppmt = pmt;
                                } else {
                                    DeleteMediaType(pmt);
                                }

                                if (pdwFlags) {
                                    *pdwFlags = (m_pInput == pInputPin) ? dwFlags : 0;
                                }

                                if (pdwGroup) {
                                    *pdwGroup = (dwFlags & (AMSTREAMSELECTINFO_ENABLED | AMSTREAMSELECTINFO_EXCLUSIVE)) ? 2 : 1;
                                }

                                if (ppszName) {
                                    *ppszName = pszName;
                                } else {
                                    CoTaskMemFree(pszName);
                                }

                                break;
                            } else {
                                lIndex--;
                            }
                        }
                        DeleteMediaType(pmt);
                        CoTaskMemFree(pszName);
                    }
                }
            } else if (lIndex == 0) {
                bFound = true;

                if (ppmt) {
                    *ppmt = CreateMediaType(&m_pOutput->CurrentMediaType());
                }

                if (pdwFlags) {
                    *pdwFlags = (m_pInput == pInputPin) ? AMSTREAMSELECTINFO_EXCLUSIVE : 0;
                }

                if (plcid) {
                    *plcid = 0;
                }

                if (pdwGroup) {
                    *pdwGroup = 0;
                }

                if (ppszName) {
                    *ppszName = (WCHAR*)CoTaskMemAlloc((wcslen(pInputPin->Name()) + 1) * sizeof(WCHAR));
                    if (*ppszName) {
                        wcscpy_s(*ppszName, wcslen(pInputPin->Name()) + 1, pInputPin->Name());
                    }
                }
            } else {
                lIndex--;
            }
        }
    }

    if (!bFound) {
        return E_INVALIDARG;
    }

    if (ppObject) {
        *ppObject = pObject;
        if (pObject) {
            pObject->AddRef();
        }
    }

    if (ppUnk) {
        *ppUnk = nullptr;
    }

    return S_OK;
}

STDMETHODIMP CStreamSwitcherFilter::Enable(long lIndex, DWORD dwFlags)
{
    if (dwFlags != AMSTREAMSELECTENABLE_ENABLE) {
        return E_NOTIMPL;
    }

    PauseGraph;

    bool bFound = false;
    int i = 0;
    CStreamSwitcherInputPin* pNewInputPin = nullptr;
    POSITION pos = m_pInputs.GetHeadPosition();
    while (pos && !bFound) {
        pNewInputPin = m_pInputs.GetNext(pos);

        if (pNewInputPin->IsConnected()) {
            if (CComPtr<IAMStreamSelect> pSSF = pNewInputPin->GetStreamSelectionFilter()) {
                DWORD cStreams = 0;
                HRESULT hr = pSSF->Count(&cStreams);
                if (SUCCEEDED(hr)) {
                    for (i = 0; i < (int)cStreams; i++) {
                        AM_MEDIA_TYPE* pmt = nullptr;
                        hr = pSSF->Info(i, &pmt, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
                        if (SUCCEEDED(hr) && pmt && pmt->majortype == MEDIATYPE_Audio) {
                            if (lIndex == 0) {
                                bFound = true;
                                DeleteMediaType(pmt);
                                break;
                            } else {
                                lIndex--;
                            }
                        }
                        DeleteMediaType(pmt);
                    }
                }
            } else if (lIndex == 0) {
                bFound = true;
            } else {
                lIndex--;
            }
        }
    }

    if (!bFound) {
        return E_INVALIDARG;
    }

    SelectInput(pNewInputPin);

    if (CComPtr<IAMStreamSelect> pSSF = pNewInputPin->GetStreamSelectionFilter()) {
        pSSF->Enable(i, dwFlags);
    }

    ResumeGraph;

    return S_OK;
}