Fix naming.
[xy_vsfilter.git] / src / filters / transform / vsfilter / DirectVobSubFilter.cpp
bloba1154071fcf14643e48911d56737b4ea1c3d58fc
1 /*
2 * Copyright (C) 2003-2006 Gabest
3 * http://www.gabest.org
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
8 * any later version.
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with GNU Make; see the file COPYING. If not, write to
17 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 #include "stdafx.h"
23 #include <math.h>
24 #include <time.h>
25 #include "DirectVobSubFilter.h"
26 #include "TextInputPin.h"
27 #include "DirectVobSubPropPage.h"
28 #include "VSFilter.h"
29 #include "systray.h"
30 #include "../../../DSUtil/MediaTypes.h"
31 #include "../../../SubPic/SimpleSubPicProviderImpl.h"
32 #include "../../../SubPic/PooledSubPic.h"
33 #include "../../../subpic/color_conv_table.h"
34 #include "../../../subpic/SimpleSubPicWrapper.h"
36 #include <initguid.h>
37 #include "..\..\..\..\include\moreuuids.h"
39 #include "CAutoTiming.h"
40 #include "xy_logger.h"
43 #define MAX_SUBPIC_QUEUE_LENGTH 1
45 ///////////////////////////////////////////////////////////////////////////
47 /*removeme*/
48 bool g_RegOK = true;//false; // doesn't work with the dvd graph builder
49 #include "valami.cpp"
51 #ifdef __DO_LOG
52 EXTERN_C IMAGE_DOS_HEADER __ImageBase;
53 #endif
55 using namespace DirectVobSubXyOptions;
57 ////////////////////////////////////////////////////////////////////////////
59 // Constructor
62 CDirectVobSubFilter::CDirectVobSubFilter(LPUNKNOWN punk, HRESULT* phr, const GUID& clsid)
63 : CBaseVideoFilter(NAME("CDirectVobSubFilter"), punk, phr, clsid)
64 , m_nSubtitleId(-1)
65 , m_fMSMpeg4Fix(false)
66 , m_fps(25)
68 DbgLog((LOG_TRACE, 3, _T("CDirectVobSubFilter::CDirectVobSubFilter")));
70 // and then, anywhere you need it:
72 #ifdef __DO_LOG
73 LPTSTR strDLLPath = new TCHAR[_MAX_PATH];
74 ::GetModuleFileName( reinterpret_cast<HINSTANCE>(&__ImageBase), strDLLPath, _MAX_PATH);
75 CString dllPath = strDLLPath;
76 dllPath += ".properties";
77 xy_logger::doConfigure( dllPath.GetString() );
78 #endif
80 AFX_MANAGE_STATE(AfxGetStaticModuleState());
82 m_hdc = 0;
83 m_hbm = 0;
84 m_hfont = 0;
87 LOGFONT lf;
88 memset(&lf, 0, sizeof(lf));
89 lf.lfCharSet = DEFAULT_CHARSET;
90 lf.lfOutPrecision = OUT_CHARACTER_PRECIS;
91 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
92 lf.lfQuality = ANTIALIASED_QUALITY;
93 HDC hdc = GetDC(NULL);
94 lf.lfHeight = 28;
95 //MulDiv(20, GetDeviceCaps(hdc, LOGPIXELSY), 54);
96 ReleaseDC(NULL, hdc);
97 lf.lfWeight = FW_BOLD;
98 _tcscpy(lf.lfFaceName, _T("Arial"));
99 m_hfont = CreateFontIndirect(&lf);
102 theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Hint"), _T("The first three are fixed, but you can add more up to ten entries."));
103 theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Path0"), _T("."));
104 theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Path1"), _T("c:\\subtitles"));
105 theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Path2"), _T(".\\subtitles"));
107 m_fLoading = true;
109 m_hSystrayThread = 0;
110 m_tbid.hSystrayWnd = NULL;
111 m_tbid.graph = NULL;
112 m_tbid.fRunOnce = false;
113 m_tbid.fShowIcon = (theApp.m_AppName.Find(_T("zplayer"), 0) < 0 || !!theApp.GetProfileInt(ResStr(IDS_R_GENERAL), ResStr(IDS_RG_ENABLEZPICON), 0));
115 HRESULT hr = S_OK;
116 m_pTextInput.Add(new CTextInputPin(this, m_pLock, &m_csSubLock, &hr));
117 ASSERT(SUCCEEDED(hr));
119 CAMThread::Create();
120 m_frd.EndThreadEvent.Create(0, FALSE, FALSE, 0);
121 m_frd.RefreshEvent.Create(0, FALSE, FALSE, 0);
123 memset(&m_CurrentVIH2, 0, sizeof(VIDEOINFOHEADER2));
125 m_donot_follow_upstream_preferred_order = !m_xy_bool_opt[BOOL_FOLLOW_UPSTREAM_PREFERRED_ORDER];
127 m_time_alphablt = m_time_rasterization = 0;
129 m_script_selected_yuv = CSimpleTextSubtitle::YCbCrMatrix_AUTO;
130 m_script_selected_range = CSimpleTextSubtitle::YCbCrRange_AUTO;
133 CDirectVobSubFilter::~CDirectVobSubFilter()
135 CAutoLock cAutoLock(&m_csQueueLock);
136 if(m_simple_provider)
138 DbgLog((LOG_TRACE, 3, "~CDirectVobSubFilter::Invalidate"));
139 m_simple_provider->Invalidate();
141 m_simple_provider = NULL;
143 if(m_hfont) {DeleteObject(m_hfont); m_hfont = 0;}
144 if(m_hbm) {DeleteObject(m_hbm); m_hbm = 0;}
145 if(m_hdc) {DeleteObject(m_hdc); m_hdc = 0;}
147 for(int i = 0; i < m_pTextInput.GetCount(); i++)
148 delete m_pTextInput[i];
150 m_frd.EndThreadEvent.Set();
151 CAMThread::Close();
153 DbgLog((LOG_TRACE, 3, _T("CDirectVobSubFilter::~CDirectVobSubFilter")));
155 //Trace(_T("CDirectVobSubFilter::~CDirectVobSubFilter"));
156 //ReleaseTracer;
159 STDMETHODIMP CDirectVobSubFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
161 CheckPointer(ppv, E_POINTER);
163 return
164 QI(IDirectVobSub)
165 QI(IDirectVobSub2)
166 QI(IDirectVobSubXy)
167 QI(IFilterVersion)
168 QI(ISpecifyPropertyPages)
169 QI(IAMStreamSelect)
170 __super::NonDelegatingQueryInterface(riid, ppv);
173 // CBaseVideoFilter
175 void CDirectVobSubFilter::GetOutputSize(int& w, int& h, int& arx, int& ary)
177 CSize s(w, h), os = s;
178 AdjustFrameSize(s);
179 w = s.cx;
180 h = s.cy;
182 if(w != os.cx)
184 while(arx < 100) arx *= 10, ary *= 10;
185 arx = arx * w / os.cx;
188 if(h != os.cy)
190 while(ary < 100) arx *= 10, ary *= 10;
191 ary = ary * h / os.cy;
195 HRESULT CDirectVobSubFilter::TryNotCopy(IMediaSample* pIn, const CMediaType& mt, const BITMAPINFOHEADER& bihIn )
197 CSize sub(m_w, m_h);
198 CSize in(bihIn.biWidth, bihIn.biHeight);
199 BYTE* pDataIn = NULL;
200 if(FAILED(pIn->GetPointer(&pDataIn)) || !pDataIn)
201 return S_FALSE;
202 if( sub==in )
204 m_spd.bits = pDataIn;
206 else
208 m_spd.bits = static_cast<BYTE*>(m_pTempPicBuff);
209 bool fYV12 = (mt.subtype == MEDIASUBTYPE_YV12 || mt.subtype == MEDIASUBTYPE_I420 || mt.subtype == MEDIASUBTYPE_IYUV);
210 bool fNV12 = (mt.subtype == MEDIASUBTYPE_NV12 || mt.subtype == MEDIASUBTYPE_NV21);
211 bool fP010 = (mt.subtype == MEDIASUBTYPE_P010 || mt.subtype == MEDIASUBTYPE_P016);
213 int bpp = fP010 ? 16 : (fYV12||fNV12) ? 8 : bihIn.biBitCount;
214 DWORD black = fP010 ? 0x10001000 : (fYV12||fNV12) ? 0x10101010 : (bihIn.biCompression == '2YUY') ? 0x80108010 : 0;
217 if(FAILED(Copy((BYTE*)m_pTempPicBuff, pDataIn, sub, in, bpp, mt.subtype, black)))
218 return E_FAIL;
220 if(fYV12)
222 BYTE* pSubV = (BYTE*)m_pTempPicBuff + (sub.cx*bpp>>3)*sub.cy;
223 BYTE* pInV = pDataIn + (in.cx*bpp>>3)*in.cy;
224 sub.cx >>= 1; sub.cy >>= 1; in.cx >>= 1; in.cy >>= 1;
225 BYTE* pSubU = pSubV + (sub.cx*bpp>>3)*sub.cy;
226 BYTE* pInU = pInV + (in.cx*bpp>>3)*in.cy;
227 if(FAILED(Copy(pSubV, pInV, sub, in, bpp, mt.subtype, 0x80808080)))
228 return E_FAIL;
229 if(FAILED(Copy(pSubU, pInU, sub, in, bpp, mt.subtype, 0x80808080)))
230 return E_FAIL;
232 else if (fP010)
234 BYTE* pSubUV = (BYTE*)m_pTempPicBuff + (sub.cx*bpp>>3)*sub.cy;
235 BYTE* pInUV = pDataIn + (in.cx*bpp>>3)*in.cy;
236 sub.cy >>= 1; in.cy >>= 1;
237 if(FAILED(Copy(pSubUV, pInUV, sub, in, bpp, mt.subtype, 0x80008000)))
238 return E_FAIL;
240 else if(fNV12) {
241 BYTE* pSubUV = (BYTE*)m_pTempPicBuff + (sub.cx*bpp>>3)*sub.cy;
242 BYTE* pInUV = pDataIn + (in.cx*bpp>>3)*in.cy;
243 sub.cy >>= 1;
244 in.cy >>= 1;
245 if(FAILED(Copy(pSubUV, pInUV, sub, in, bpp, mt.subtype, 0x80808080)))
246 return E_FAIL;
249 return S_OK;
252 HRESULT CDirectVobSubFilter::Transform(IMediaSample* pIn)
254 XY_LOG_ONCE(0, _T("CDirectVobSubFilter::Transform"));
255 HRESULT hr;
258 REFERENCE_TIME rtStart, rtStop;
259 if(SUCCEEDED(pIn->GetTime(&rtStart, &rtStop)))
261 double dRate = m_pInput->CurrentRate();
263 m_tPrev = m_pInput->CurrentStartTime() + dRate*rtStart;
265 REFERENCE_TIME rtAvgTimePerFrame = rtStop - rtStart;
266 if(CComQIPtr<ISubClock2> pSC2 = m_pSubClock)
268 REFERENCE_TIME rt;
269 if(S_OK == pSC2->GetAvgTimePerFrame(&rt))
270 rtAvgTimePerFrame = rt;
273 m_fps = 10000000.0/rtAvgTimePerFrame / dRate;
279 CAutoLock cAutoLock(&m_csQueueLock);
281 if(m_simple_provider)
283 m_simple_provider->SetTime(CalcCurrentTime());
284 m_simple_provider->SetFPS(m_fps);
291 const CMediaType& mt = m_pInput->CurrentMediaType();
293 BITMAPINFOHEADER bihIn;
294 ExtractBIH(&mt, &bihIn);
296 hr = TryNotCopy(pIn, mt, bihIn);
297 if( hr!=S_OK )
299 //fix me: log error
300 return hr;
304 SubPicDesc spd = m_spd;
306 CComPtr<IMediaSample> pOut;
307 BYTE* pDataOut = NULL;
308 if(FAILED(hr = GetDeliveryBuffer(spd.w, spd.h, &pOut))
309 || FAILED(hr = pOut->GetPointer(&pDataOut)))
310 return hr;
311 pOut->SetTime(&rtStart, &rtStop);
312 pOut->SetMediaTime(NULL, NULL);
313 pOut->SetDiscontinuity(pIn->IsDiscontinuity() == S_OK);
314 pOut->SetSyncPoint(pIn->IsSyncPoint() == S_OK);
315 pOut->SetPreroll(pIn->IsPreroll() == S_OK);
318 BITMAPINFOHEADER bihOut;
319 ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut);
321 bool fInputFlipped = bihIn.biHeight >= 0 && bihIn.biCompression <= 3;
322 bool fOutputFlipped = bihOut.biHeight >= 0 && bihOut.biCompression <= 3;
324 bool fFlip = fInputFlipped != fOutputFlipped;
325 if(m_fFlipPicture) fFlip = !fFlip;
326 if(m_fMSMpeg4Fix) fFlip = !fFlip;
328 bool fFlipSub = fOutputFlipped;
329 if(m_fFlipSubtitles) fFlipSub = !fFlipSub;
334 CAutoLock cAutoLock(&m_csQueueLock);
336 if(m_simple_provider)
338 CComPtr<ISimpleSubPic> pSubPic;
339 //int timeStamp1 = GetTickCount();
340 bool lookupResult = m_simple_provider->LookupSubPic(CalcCurrentTime(), &pSubPic);
341 //int timeStamp2 = GetTickCount();
342 //m_time_rasterization += timeStamp2-timeStamp1;
344 if(lookupResult && pSubPic)
346 if(fFlip ^ fFlipSub)
347 spd.h = -spd.h;
348 pSubPic->AlphaBlt(&spd);
349 DbgLog((LOG_TRACE,3,"AlphaBlt time:%lu", (ULONG)(CalcCurrentTime()/10000)));
353 CopyBuffer(pDataOut, (BYTE*)spd.bits, spd.w, abs(spd.h)*(fFlip?-1:1), spd.pitch, mt.subtype);
355 PrintMessages(pDataOut);
356 return m_pOutput->Deliver(pOut);
359 // CBaseFilter
361 CBasePin* CDirectVobSubFilter::GetPin(int n)
363 if(n < __super::GetPinCount())
364 return __super::GetPin(n);
366 n -= __super::GetPinCount();
368 if(n >= 0 && n < m_pTextInput.GetCount())
369 return m_pTextInput[n];
371 n -= m_pTextInput.GetCount();
373 return NULL;
376 int CDirectVobSubFilter::GetPinCount()
378 return __super::GetPinCount() + m_pTextInput.GetCount();
381 HRESULT CDirectVobSubFilter::JoinFilterGraph(IFilterGraph* pGraph, LPCWSTR pName)
383 if(pGraph)
385 AFX_MANAGE_STATE(AfxGetStaticModuleState());
387 if(!theApp.GetProfileInt(ResStr(IDS_R_GENERAL), ResStr(IDS_RG_SEENDIVXWARNING), 0))
389 unsigned __int64 ver = GetFileVersion(_T("divx_c32.ax"));
390 if(((ver >> 48)&0xffff) == 4 && ((ver >> 32)&0xffff) == 2)
392 DWORD dwVersion = GetVersion();
393 DWORD dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
394 DWORD dwWindowsMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
396 if(dwVersion < 0x80000000 && dwWindowsMajorVersion >= 5)
398 AfxMessageBox(IDS_DIVX_WARNING);
399 theApp.WriteProfileInt(ResStr(IDS_R_GENERAL), ResStr(IDS_RG_SEENDIVXWARNING), 1);
404 /*removeme*/
405 if(!g_RegOK)
407 DllRegisterServer();
408 g_RegOK = true;
411 else
413 if(m_hSystrayThread)
415 SendMessage(m_tbid.hSystrayWnd, WM_CLOSE, 0, 0);
417 if(WaitForSingleObject(m_hSystrayThread, 10000) != WAIT_OBJECT_0)
419 DbgLog((LOG_TRACE, 0, _T("CALL THE AMBULANCE!!!")));
420 TerminateThread(m_hSystrayThread, (DWORD)-1);
423 m_hSystrayThread = 0;
427 return __super::JoinFilterGraph(pGraph, pName);
430 STDMETHODIMP CDirectVobSubFilter::QueryFilterInfo(FILTER_INFO* pInfo)
432 CheckPointer(pInfo, E_POINTER);
433 ValidateReadWritePtr(pInfo, sizeof(FILTER_INFO));
435 if(!get_Forced())
436 return __super::QueryFilterInfo(pInfo);
438 wcscpy(pInfo->achName, L"DirectVobSub (forced auto-loading version)");
439 if(pInfo->pGraph = m_pGraph) m_pGraph->AddRef();
441 return S_OK;
444 // CTransformFilter
446 HRESULT CDirectVobSubFilter::SetMediaType(PIN_DIRECTION dir, const CMediaType* pmt)
448 HRESULT hr = __super::SetMediaType(dir, pmt);
449 if(FAILED(hr)) return hr;
451 if(dir == PINDIR_INPUT)
453 CAutoLock cAutoLock(&m_csReceive);
455 REFERENCE_TIME atpf =
456 pmt->formattype == FORMAT_VideoInfo ? ((VIDEOINFOHEADER*)pmt->Format())->AvgTimePerFrame :
457 pmt->formattype == FORMAT_VideoInfo2 ? ((VIDEOINFOHEADER2*)pmt->Format())->AvgTimePerFrame :
460 m_fps = atpf ? 10000000.0 / atpf : 25;
462 if (pmt->formattype == FORMAT_VideoInfo2)
463 m_CurrentVIH2 = *(VIDEOINFOHEADER2*)pmt->Format();
465 DbgLog((LOG_TRACE, 3, "SetMediaType => InitSubPicQueue"));
466 InitSubPicQueue();
468 else if(dir == PINDIR_OUTPUT)
473 return hr;
476 HRESULT CDirectVobSubFilter::CheckConnect(PIN_DIRECTION dir, IPin* pPin)
478 if(dir == PINDIR_INPUT)
481 else if(dir == PINDIR_OUTPUT)
483 /*removeme*/
484 if(HmGyanusVagyTeNekem(pPin)) return(E_FAIL);
487 return __super::CheckConnect(dir, pPin);
490 HRESULT CDirectVobSubFilter::CompleteConnect(PIN_DIRECTION dir, IPin* pReceivePin)
492 bool reconnected = false;
493 if(dir == PINDIR_INPUT)
495 DbgLog((LOG_TRACE, 3, TEXT("connect input")));
496 DumpGraph(m_pGraph,0);
497 CComPtr<IBaseFilter> pFilter;
499 // needed when we have a decoder with a version number of 3.x
500 if(SUCCEEDED(m_pGraph->FindFilterByName(L"DivX MPEG-4 DVD Video Decompressor ", &pFilter))
501 && (GetFileVersion(_T("divx_c32.ax")) >> 48) <= 4
502 || SUCCEEDED(m_pGraph->FindFilterByName(L"Microcrap MPEG-4 Video Decompressor", &pFilter))
503 || SUCCEEDED(m_pGraph->FindFilterByName(L"Microsoft MPEG-4 Video Decompressor", &pFilter))
504 && (GetFileVersion(_T("mpg4ds32.ax")) >> 48) <= 3)
506 m_fMSMpeg4Fix = true;
509 else if(dir == PINDIR_OUTPUT)
511 DbgLog((LOG_TRACE, 3, TEXT("connect output")));
512 DumpGraph(m_pGraph,0);
513 const CMediaType* mtIn = &(m_pInput->CurrentMediaType());
514 const CMediaType* mtOut = &(m_pOutput->CurrentMediaType());
515 CMediaType desiredMt;
516 int position = 0;
517 HRESULT hr;
519 bool can_reconnect = false;
520 bool can_transform = (DoCheckTransform(mtIn, mtOut, true)==S_OK);
521 if( mtIn->subtype!=mtOut->subtype )
523 position = GetOutputSubtypePosition(mtOut->subtype);
524 if(position>=0)
526 hr = GetMediaType(position, &desiredMt);
527 if (hr!=S_OK)
529 DbgLog((LOG_ERROR, 3, TEXT("Unexpected error when GetMediaType, position:%d"), position));
531 else
533 hr = DoCheckTransform(&desiredMt, mtOut, true);
534 if (hr!=S_OK)
536 DbgLog((LOG_TRACE, 3, TEXT("Transform not accept:")));
537 DisplayType(0,&desiredMt);
538 DisplayType(0,mtOut);
540 else
542 hr = m_pInput->GetConnected()->QueryAccept(&desiredMt);
543 if(hr!=S_OK)
545 DbgLog((LOG_TRACE, 3, TEXT("Upstream not accept:")));
546 DisplayType(0, &desiredMt);
548 else
550 can_reconnect = true;
551 DbgLog((LOG_ERROR, 3, TEXT("Can use the same subtype!")));
556 else
558 DbgLog((LOG_ERROR, 3, TEXT("Cannot use the same subtype!")));
561 if(!can_reconnect && !can_transform)
563 position = 0;
566 hr = GetMediaType(position, &desiredMt);
567 ++position;
568 //if( FAILED(hr) )
569 if( hr!=S_OK )
570 break;
572 DbgLog((LOG_TRACE, 3, TEXT("Checking reconnect with media type:")));
573 DisplayType(0, &desiredMt);
575 if( DoCheckTransform(&desiredMt, mtOut, true)!=S_OK ||
576 m_pInput->GetConnected()->QueryAccept(&desiredMt)!=S_OK )
578 continue;
580 else
582 can_reconnect = true;
583 break;
585 } while ( true );
587 if ( can_reconnect )
589 if (SUCCEEDED(ReconnectPin(m_pInput, &desiredMt)))
591 reconnected = true;
592 DumpGraph(m_pGraph,0);
593 //m_pInput->SetMediaType(&desiredMt);
594 DbgLog((LOG_TRACE, 3, TEXT("reconnected succeed!")));
597 else if(!can_transform)
599 DbgLog((LOG_TRACE, 3, TEXT("Failed to agree reconnect type!")));
600 if(m_pInput->IsConnected())
602 m_pInput->GetConnected()->Disconnect();
603 m_pInput->Disconnect();
605 if(m_pOutput->IsConnected())
607 m_pOutput->GetConnected()->Disconnect();
608 m_pOutput->Disconnect();
610 return VFW_E_TYPE_NOT_ACCEPTED;
613 if (!reconnected && m_pOutput->IsConnected())
615 if(!m_hSystrayThread && !m_xy_bool_opt[BOOL_HIDE_TRAY_ICON])
617 m_tbid.graph = m_pGraph;
618 m_tbid.dvs = static_cast<IDirectVobSub*>(this);
620 DWORD tid;
621 m_hSystrayThread = CreateThread(0, 0, SystrayThreadProc, &m_tbid, 0, &tid);
623 m_pInput->SetMediaType( &m_pInput->CurrentMediaType() );
626 HRESULT hr = __super::CompleteConnect(dir, pReceivePin);
627 DbgLog((LOG_TRACE, 3, TEXT("connect fininshed!")));
628 DumpGraph(m_pGraph,0);
629 return hr;
632 HRESULT CDirectVobSubFilter::BreakConnect(PIN_DIRECTION dir)
634 if(dir == PINDIR_INPUT)
636 //if(m_pOutput->IsConnected())
638 // m_pOutput->GetConnected()->Disconnect();
639 // m_pOutput->Disconnect();
642 else if(dir == PINDIR_OUTPUT)
644 // not really needed, but may free up a little memory
645 CAutoLock cAutoLock(&m_csQueueLock);
646 m_simple_provider = NULL;
649 return __super::BreakConnect(dir);
652 HRESULT CDirectVobSubFilter::StartStreaming()
654 /* WARNING: calls to m_pGraph member functions from within this function will generate deadlock with Haali
655 * Video Renderer in MPC. Reason is that CAutoLock's variables in IFilterGraph functions are overriden by
656 * CFGManager class.
659 m_fLoading = false;
661 DbgLog((LOG_TRACE, 3, "StartStreaming => InitSubPicQueue"));
662 InitSubPicQueue();
664 m_tbid.fRunOnce = true;
666 put_MediaFPS(m_fMediaFPSEnabled, m_MediaFPS);
668 return __super::StartStreaming();
671 HRESULT CDirectVobSubFilter::StopStreaming()
673 InvalidateSubtitle();
675 //xy Timing
676 //FILE * timingFile = fopen("C:\\vsfilter_timing.txt", "at");
677 //fprintf(timingFile, "%s:%ld %s:%ld\n", "m_time_alphablt", m_time_alphablt, "m_time_rasterization", m_time_rasterization);
678 //fclose(timingFile);
680 return __super::StopStreaming();
683 HRESULT CDirectVobSubFilter::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
685 m_tPrev = tStart;
686 return __super::NewSegment(tStart, tStop, dRate);
691 REFERENCE_TIME CDirectVobSubFilter::CalcCurrentTime()
693 REFERENCE_TIME rt = m_pSubClock ? m_pSubClock->GetTime() : m_tPrev;
694 return (rt - 10000i64*m_SubtitleDelay) * m_SubtitleSpeedMul / m_SubtitleSpeedDiv; // no, it won't overflow if we use normal parameters (__int64 is enough for about 2000 hours if we multiply it by the max: 65536 as m_SubtitleSpeedMul)
697 void CDirectVobSubFilter::InitSubPicQueue()
699 CAutoLock cAutoLock(&m_csQueueLock);
701 CacheManager::GetPathDataMruCache()->SetMaxItemNum(m_xy_int_opt[INT_PATH_DATA_CACHE_MAX_ITEM_NUM]);
702 CacheManager::GetScanLineData2MruCache()->SetMaxItemNum(m_xy_int_opt[INT_SCAN_LINE_DATA_CACHE_MAX_ITEM_NUM]);
703 CacheManager::GetOverlayNoBlurMruCache()->SetMaxItemNum(m_xy_int_opt[INT_OVERLAY_NO_BLUR_CACHE_MAX_ITEM_NUM]);
704 CacheManager::GetOverlayMruCache()->SetMaxItemNum(m_xy_int_opt[INT_OVERLAY_CACHE_MAX_ITEM_NUM]);
706 XyFwGroupedDrawItemsHashKey::GetCacher()->SetMaxItemNum(m_xy_int_opt[INT_BITMAP_MRU_CACHE_ITEM_NUM]);
707 CacheManager::GetBitmapMruCache()->SetMaxItemNum(m_xy_int_opt[INT_BITMAP_MRU_CACHE_ITEM_NUM]);
709 CacheManager::GetClipperAlphaMaskMruCache()->SetMaxItemNum(m_xy_int_opt[INT_CLIPPER_MRU_CACHE_ITEM_NUM]);
710 CacheManager::GetTextInfoCache()->SetMaxItemNum(m_xy_int_opt[INT_TEXT_INFO_CACHE_ITEM_NUM]);
711 CacheManager::GetAssTagListMruCache()->SetMaxItemNum(m_xy_int_opt[INT_ASS_TAG_LIST_CACHE_ITEM_NUM]);
713 SubpixelPositionControler::GetGlobalControler().SetSubpixelLevel( static_cast<SubpixelPositionControler::SUBPIXEL_LEVEL>(m_xy_int_opt[INT_SUBPIXEL_POS_LEVEL]) );
715 m_simple_provider = NULL;
717 const GUID& subtype = m_pInput->CurrentMediaType().subtype;
719 BITMAPINFOHEADER bihIn;
720 ExtractBIH(&m_pInput->CurrentMediaType(), &bihIn);
722 m_spd.type = -1;
724 if(subtype == MEDIASUBTYPE_YV12) m_spd.type = MSP_YV12;
725 else if(subtype == MEDIASUBTYPE_P010) m_spd.type = MSP_P010;
726 else if(subtype == MEDIASUBTYPE_P016) m_spd.type = MSP_P016;
727 else if(subtype == MEDIASUBTYPE_I420 || subtype == MEDIASUBTYPE_IYUV) m_spd.type = MSP_IYUV;
728 else if(subtype == MEDIASUBTYPE_YUY2) m_spd.type = MSP_YUY2;
729 else if(subtype == MEDIASUBTYPE_RGB32) m_spd.type = MSP_RGB32;
730 else if(subtype == MEDIASUBTYPE_RGB24) m_spd.type = MSP_RGB24;
731 else if(subtype == MEDIASUBTYPE_RGB565) m_spd.type = MSP_RGB16;
732 else if(subtype == MEDIASUBTYPE_RGB555) m_spd.type = MSP_RGB15;
733 else if(subtype == MEDIASUBTYPE_NV12) m_spd.type = MSP_NV12;
734 else if(subtype == MEDIASUBTYPE_NV21) m_spd.type = MSP_NV21;
736 m_spd.w = m_w;
737 m_spd.h = m_h;
738 m_spd.bpp = (m_spd.type == MSP_P010 || m_spd.type == MSP_P016) ? 16 :
739 (m_spd.type == MSP_YV12 || m_spd.type == MSP_IYUV || m_spd.type == MSP_NV12 || m_spd.type == MSP_NV21) ? 8 : bihIn.biBitCount;
740 m_spd.pitch = m_spd.w*m_spd.bpp>>3;
742 m_pTempPicBuff.Free();
743 if(m_spd.type == MSP_YV12 || m_spd.type == MSP_IYUV || m_spd.type == MSP_NV12 || m_spd.type == MSP_NV21)
744 m_pTempPicBuff.Allocate(4*m_spd.pitch*m_spd.h);//fix me: can be smaller
745 else if(m_spd.type == MSP_P010 || m_spd.type == MSP_P016)
746 m_pTempPicBuff.Allocate(m_spd.pitch*m_spd.h+m_spd.pitch*m_spd.h/2);
747 else
748 m_pTempPicBuff.Allocate(m_spd.pitch*m_spd.h);
749 m_spd.bits = (void*)m_pTempPicBuff;
751 CSize video(bihIn.biWidth, bihIn.biHeight), window = video;
752 if(AdjustFrameSize(window)) video += video;
753 ASSERT(window == CSize(m_w, m_h));
754 CRect video_rect(CPoint((window.cx - video.cx)/2, (window.cy - video.cy)/2), video);
756 HRESULT hr = S_OK;
757 //m_pSubPicQueue = m_fDoPreBuffering
758 // ? (ISubPicQueue*)new CSubPicQueue(MAX_SUBPIC_QUEUE_LENGTH, pSubPicAllocator, &hr)
759 // : (ISubPicQueue*)new CSubPicQueueNoThread(pSubPicAllocator, &hr);
760 m_simple_provider = new SimpleSubPicProvider2(m_spd.type, CSize(m_w, m_h), window, video_rect, this, &hr);
762 if(FAILED(hr)) m_simple_provider = NULL;
764 XySetSize(DirectVobSubXyOptions::SIZE_ORIGINAL_VIDEO, CSize(m_w, m_h));
765 UpdateSubtitle(false);
767 if(m_hbm) {DeleteObject(m_hbm); m_hbm = NULL;}
768 if(m_hdc) {DeleteDC(m_hdc); m_hdc = NULL;}
770 struct {BITMAPINFOHEADER bih; DWORD mask[3];} b = {{sizeof(BITMAPINFOHEADER), m_w, -(int)m_h, 1, 32, BI_BITFIELDS, 0, 0, 0, 0, 0}, 0xFF0000, 0x00FF00, 0x0000FF};
771 m_hdc = CreateCompatibleDC(NULL);
772 m_hbm = CreateDIBSection(m_hdc, (BITMAPINFO*)&b, DIB_RGB_COLORS, NULL, NULL, 0);
774 BITMAP bm;
775 GetObject(m_hbm, sizeof(bm), &bm);
776 memsetd(bm.bmBits, 0xFF000000, bm.bmHeight*bm.bmWidthBytes);
779 bool CDirectVobSubFilter::AdjustFrameSize(CSize& s)
781 int horizontal, vertical, resx2, resx2minw, resx2minh;
782 get_ExtendPicture(&horizontal, &vertical, &resx2, &resx2minw, &resx2minh);
784 bool fRet = (resx2 == 1) || (resx2 == 2 && s.cx*s.cy <= resx2minw*resx2minh);
786 if(fRet)
788 s.cx <<= 1;
789 s.cy <<= 1;
792 int h;
793 switch(vertical&0x7f)
795 case 1:
796 h = s.cx * 9 / 16;
797 if(s.cy < h || !!(vertical&0x80)) s.cy = (h + 3) & ~3;
798 break;
799 case 2:
800 h = s.cx * 3 / 4;
801 if(s.cy < h || !!(vertical&0x80)) s.cy = (h + 3) & ~3;
802 break;
803 case 3:
804 h = 480;
805 if(s.cy < h || !!(vertical&0x80)) s.cy = (h + 3) & ~3;
806 break;
807 case 4:
808 h = 576;
809 if(s.cy < h || !!(vertical&0x80)) s.cy = (h + 3) & ~3;
810 break;
813 if(horizontal == 1)
815 s.cx = (s.cx + 31) & ~31;
816 s.cy = (s.cy + 1) & ~1;
819 return(fRet);
822 STDMETHODIMP CDirectVobSubFilter::Count(DWORD* pcStreams)
824 if(!pcStreams) return E_POINTER;
826 *pcStreams = 0;
828 int nLangs = 0;
829 if(SUCCEEDED(get_LanguageCount(&nLangs)))
830 (*pcStreams) += nLangs;
832 (*pcStreams) += 2; // enable ... disable
834 (*pcStreams) += 2; // normal flipped
836 return S_OK;
839 #define MAXPREFLANGS 5
841 int CDirectVobSubFilter::FindPreferedLanguage(bool fHideToo)
843 AFX_MANAGE_STATE(AfxGetStaticModuleState());
845 int nLangs;
846 get_LanguageCount(&nLangs);
848 if(nLangs <= 0) return(0);
850 for(int i = 0; i < MAXPREFLANGS; i++)
852 CString tmp;
853 tmp.Format(IDS_RL_LANG, i);
855 CString lang = theApp.GetProfileString(ResStr(IDS_R_PREFLANGS), tmp);
857 if(!lang.IsEmpty())
859 for(int ret = 0; ret < nLangs; ret++)
861 CString l;
862 WCHAR* pName = NULL;
863 get_LanguageName(ret, &pName);
864 l = pName;
865 CoTaskMemFree(pName);
867 if(!l.CompareNoCase(lang)) return(ret);
872 return(0);
875 void CDirectVobSubFilter::UpdatePreferedLanguages(CString l)
877 AFX_MANAGE_STATE(AfxGetStaticModuleState());
879 CString langs[MAXPREFLANGS+1];
881 int i = 0, j = 0, k = -1;
882 for(; i < MAXPREFLANGS; i++)
884 CString tmp;
885 tmp.Format(IDS_RL_LANG, i);
887 langs[j] = theApp.GetProfileString(ResStr(IDS_R_PREFLANGS), tmp);
889 if(!langs[j].IsEmpty())
891 if(!langs[j].CompareNoCase(l)) k = j;
892 j++;
896 if(k == -1)
898 langs[k = j] = l;
899 j++;
902 // move the selected to the top of the list
904 while(k > 0)
906 CString tmp = langs[k]; langs[k] = langs[k-1]; langs[k-1] = tmp;
907 k--;
910 // move "Hide subtitles" to the last position if it wasn't our selection
912 CString hidesubs;
913 hidesubs.LoadString(IDS_M_HIDESUBTITLES);
915 for(k = 1; k < j; k++)
917 if(!langs[k].CompareNoCase(hidesubs)) break;
920 while(k < j-1)
922 CString tmp = langs[k]; langs[k] = langs[k+1]; langs[k+1] = tmp;
923 k++;
926 for(i = 0; i < j; i++)
928 CString tmp;
929 tmp.Format(IDS_RL_LANG, i);
931 theApp.WriteProfileString(ResStr(IDS_R_PREFLANGS), tmp, langs[i]);
935 STDMETHODIMP CDirectVobSubFilter::Enable(long lIndex, DWORD dwFlags)
937 if(!(dwFlags & AMSTREAMSELECTENABLE_ENABLE))
938 return E_NOTIMPL;
940 int nLangs = 0;
941 get_LanguageCount(&nLangs);
943 if(!(lIndex >= 0 && lIndex < nLangs+2+2))
944 return E_INVALIDARG;
946 int i = lIndex-1;
948 if(i == -1 && !m_fLoading) // we need this because when loading something stupid media player pushes the first stream it founds, which is "enable" in our case
950 put_HideSubtitles(false);
952 else if(i >= 0 && i < nLangs)
954 put_HideSubtitles(false);
955 put_SelectedLanguage(i);
957 WCHAR* pName = NULL;
958 if(SUCCEEDED(get_LanguageName(i, &pName)))
960 UpdatePreferedLanguages(CString(pName));
961 if(pName) CoTaskMemFree(pName);
964 else if(i == nLangs && !m_fLoading)
966 put_HideSubtitles(true);
968 else if((i == nLangs+1 || i == nLangs+2) && !m_fLoading)
970 put_Flip(i == nLangs+2, m_fFlipSubtitles);
973 return S_OK;
976 STDMETHODIMP CDirectVobSubFilter::Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD* pdwFlags, LCID* plcid, DWORD* pdwGroup, WCHAR** ppszName, IUnknown** ppObject, IUnknown** ppUnk)
978 AFX_MANAGE_STATE(AfxGetStaticModuleState());
979 const int FLAG_CMD = 1;
980 const int FLAG_EXTERNAL_SUB = 2;
981 const int FLAG_PICTURE_CMD = 4;
982 const int FLAG_VISIBILITY_CMD = 8;
984 const int GROUP_NUM_BASE = 0x648E40;//random number
986 int nLangs = 0;
987 get_LanguageCount(&nLangs);
989 if(!(lIndex >= 0 && lIndex < nLangs+2+2))
990 return E_INVALIDARG;
992 int i = lIndex-1;
994 if(ppmt) *ppmt = CreateMediaType(&m_pInput->CurrentMediaType());
996 if(pdwFlags)
998 *pdwFlags = 0;
1000 if(i == -1 && !m_fHideSubtitles
1001 || i >= 0 && i < nLangs && i == m_iSelectedLanguage
1002 || i == nLangs && m_fHideSubtitles
1003 || i == nLangs+1 && !m_fFlipPicture
1004 || i == nLangs+2 && m_fFlipPicture)
1006 *pdwFlags |= AMSTREAMSELECTINFO_ENABLED;
1010 if(plcid) *plcid = 0;
1012 if(pdwGroup)
1014 *pdwGroup = GROUP_NUM_BASE;
1015 if(i == -1)
1017 *pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_VISIBILITY_CMD;
1019 else if(i >= 0 && i < nLangs)
1021 bool isEmbedded = false;
1022 if( SUCCEEDED(GetIsEmbeddedSubStream(i, &isEmbedded)) )
1024 if(isEmbedded)
1026 *pdwGroup = GROUP_NUM_BASE & ~(FLAG_CMD | FLAG_EXTERNAL_SUB);
1028 else
1030 *pdwGroup = (GROUP_NUM_BASE & ~FLAG_CMD) | FLAG_EXTERNAL_SUB;
1034 else if(i == nLangs)
1036 *pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_VISIBILITY_CMD;
1038 else if(i == nLangs+1)
1040 *pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_PICTURE_CMD;
1042 else if(i == nLangs+2)
1044 *pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_PICTURE_CMD;
1048 if(ppszName)
1050 *ppszName = NULL;
1052 CStringW str;
1053 if(i == -1) str = ResStr(IDS_M_SHOWSUBTITLES);
1054 else if(i >= 0 && i < nLangs)
1056 get_LanguageName(i, ppszName);
1058 else if(i == nLangs)
1060 str = ResStr(IDS_M_HIDESUBTITLES);
1062 else if(i == nLangs+1)
1064 str = ResStr(IDS_M_ORIGINALPICTURE);
1066 else if(i == nLangs+2)
1068 str = ResStr(IDS_M_FLIPPEDPICTURE);
1071 if(!str.IsEmpty())
1073 *ppszName = (WCHAR*)CoTaskMemAlloc((str.GetLength()+1)*sizeof(WCHAR));
1074 if(*ppszName == NULL) return S_FALSE;
1075 wcscpy(*ppszName, str);
1079 if(ppObject) *ppObject = NULL;
1081 if(ppUnk) *ppUnk = NULL;
1083 return S_OK;
1086 STDMETHODIMP CDirectVobSubFilter::GetClassID(CLSID* pClsid)
1088 if(pClsid == NULL) return E_POINTER;
1089 *pClsid = m_clsid;
1090 return NOERROR;
1093 STDMETHODIMP CDirectVobSubFilter::GetPages(CAUUID* pPages)
1095 CheckPointer(pPages, E_POINTER);
1097 pPages->cElems = 8;
1098 pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID)*pPages->cElems);
1100 if(pPages->pElems == NULL) return E_OUTOFMEMORY;
1102 int i = 0;
1103 pPages->pElems[i++] = __uuidof(CDVSMainPPage);
1104 pPages->pElems[i++] = __uuidof(CDVSGeneralPPage);
1105 pPages->pElems[i++] = __uuidof(CDVSMiscPPage);
1106 pPages->pElems[i++] = __uuidof(CDVSMorePPage);
1107 pPages->pElems[i++] = __uuidof(CDVSTimingPPage);
1108 pPages->pElems[i++] = __uuidof(CDVSColorPPage);
1109 pPages->pElems[i++] = __uuidof(CDVSPathsPPage);
1110 pPages->pElems[i++] = __uuidof(CDVSAboutPPage);
1112 return NOERROR;
1115 // IDirectVobSub
1117 STDMETHODIMP CDirectVobSubFilter::put_FileName(WCHAR* fn)
1119 AMTRACE((TEXT(__FUNCTION__),0));
1120 HRESULT hr = CDirectVobSub::put_FileName(fn);
1122 if(hr == S_OK && !Open())
1124 m_FileName.Empty();
1125 hr = E_FAIL;
1128 return hr;
1131 STDMETHODIMP CDirectVobSubFilter::get_LanguageCount(int* nLangs)
1133 HRESULT hr = CDirectVobSub::get_LanguageCount(nLangs);
1135 if(hr == NOERROR && nLangs)
1137 CAutoLock cAutolock(&m_csQueueLock);
1139 *nLangs = 0;
1140 POSITION pos = m_pSubStreams.GetHeadPosition();
1141 while(pos) (*nLangs) += m_pSubStreams.GetNext(pos)->GetStreamCount();
1144 return hr;
1147 STDMETHODIMP CDirectVobSubFilter::get_LanguageName(int iLanguage, WCHAR** ppName)
1149 HRESULT hr = CDirectVobSub::get_LanguageName(iLanguage, ppName);
1151 if(!ppName) return E_POINTER;
1153 if(hr == NOERROR)
1155 CAutoLock cAutolock(&m_csQueueLock);
1157 hr = E_INVALIDARG;
1159 int i = iLanguage;
1161 POSITION pos = m_pSubStreams.GetHeadPosition();
1162 while(i >= 0 && pos)
1164 CComPtr<ISubStream> pSubStream = m_pSubStreams.GetNext(pos);
1166 if(i < pSubStream->GetStreamCount())
1168 pSubStream->GetStreamInfo(i, ppName, NULL);
1169 hr = NOERROR;
1170 break;
1173 i -= pSubStream->GetStreamCount();
1177 return hr;
1180 STDMETHODIMP CDirectVobSubFilter::put_SelectedLanguage(int iSelected)
1182 HRESULT hr = CDirectVobSub::put_SelectedLanguage(iSelected);
1184 if(hr == NOERROR)
1186 UpdateSubtitle(false);
1189 return hr;
1192 STDMETHODIMP CDirectVobSubFilter::put_HideSubtitles(bool fHideSubtitles)
1194 HRESULT hr = CDirectVobSub::put_HideSubtitles(fHideSubtitles);
1196 if(hr == NOERROR)
1198 UpdateSubtitle(false);
1201 return hr;
1204 STDMETHODIMP CDirectVobSubFilter::put_PreBuffering(bool fDoPreBuffering)
1206 HRESULT hr = CDirectVobSub::put_PreBuffering(fDoPreBuffering);
1208 if(hr == NOERROR)
1210 DbgLog((LOG_TRACE, 3, "put_PreBuffering => InitSubPicQueue"));
1211 InitSubPicQueue();
1214 return hr;
1217 STDMETHODIMP CDirectVobSubFilter::put_Placement(bool fOverridePlacement, int xperc, int yperc)
1219 DbgLog((LOG_TRACE, 3, "%s(%d) %s", __FILE__, __LINE__, __FUNCTION__));
1220 HRESULT hr = CDirectVobSub::put_Placement(fOverridePlacement, xperc, yperc);
1222 if(hr == NOERROR)
1224 //DbgLog((LOG_TRACE, 3, "%d %s:UpdateSubtitle(true)", __LINE__, __FUNCTION__));
1225 //UpdateSubtitle(true);
1226 UpdateSubtitle(false);
1229 return hr;
1232 STDMETHODIMP CDirectVobSubFilter::put_VobSubSettings(bool fBuffer, bool fOnlyShowForcedSubs, bool fReserved)
1234 HRESULT hr = CDirectVobSub::put_VobSubSettings(fBuffer, fOnlyShowForcedSubs, fReserved);
1236 if(hr == NOERROR)
1238 // UpdateSubtitle(false);
1239 InvalidateSubtitle();
1242 return hr;
1245 STDMETHODIMP CDirectVobSubFilter::put_TextSettings(void* lf, int lflen, COLORREF color, bool fShadow, bool fOutline, bool fAdvancedRenderer)
1247 HRESULT hr = CDirectVobSub::put_TextSettings(lf, lflen, color, fShadow, fOutline, fAdvancedRenderer);
1249 if(hr == NOERROR)
1251 // UpdateSubtitle(true);
1252 InvalidateSubtitle();
1255 return hr;
1258 STDMETHODIMP CDirectVobSubFilter::put_SubtitleTiming(int delay, int speedmul, int speeddiv)
1260 HRESULT hr = CDirectVobSub::put_SubtitleTiming(delay, speedmul, speeddiv);
1262 if(hr == NOERROR)
1264 InvalidateSubtitle();
1267 return hr;
1270 STDMETHODIMP CDirectVobSubFilter::get_CachesInfo(CachesInfo* caches_info)
1272 CAutoLock cAutoLock(&m_csQueueLock);
1273 HRESULT hr = CDirectVobSub::get_CachesInfo(caches_info);
1275 caches_info->path_cache_cur_item_num = CacheManager::GetPathDataMruCache()->GetCurItemNum();
1276 caches_info->path_cache_hit_count = CacheManager::GetPathDataMruCache()->GetCacheHitCount();
1277 caches_info->path_cache_query_count = CacheManager::GetPathDataMruCache()->GetQueryCount();
1278 caches_info->scanline_cache2_cur_item_num= CacheManager::GetScanLineData2MruCache()->GetCurItemNum();
1279 caches_info->scanline_cache2_hit_count = CacheManager::GetScanLineData2MruCache()->GetCacheHitCount();
1280 caches_info->scanline_cache2_query_count = CacheManager::GetScanLineData2MruCache()->GetQueryCount();
1281 caches_info->non_blur_cache_cur_item_num= CacheManager::GetOverlayNoBlurMruCache()->GetCurItemNum();
1282 caches_info->non_blur_cache_hit_count = CacheManager::GetOverlayNoBlurMruCache()->GetCacheHitCount();
1283 caches_info->non_blur_cache_query_count = CacheManager::GetOverlayNoBlurMruCache()->GetQueryCount();
1284 caches_info->overlay_cache_cur_item_num = CacheManager::GetOverlayMruCache()->GetCurItemNum();
1285 caches_info->overlay_cache_hit_count = CacheManager::GetOverlayMruCache()->GetCacheHitCount();
1286 caches_info->overlay_cache_query_count = CacheManager::GetOverlayMruCache()->GetQueryCount();
1288 caches_info->bitmap_cache_cur_item_num = CacheManager::GetBitmapMruCache()->GetCurItemNum();
1289 caches_info->bitmap_cache_hit_count = CacheManager::GetBitmapMruCache()->GetCacheHitCount();
1290 caches_info->bitmap_cache_query_count = CacheManager::GetBitmapMruCache()->GetQueryCount();
1292 caches_info->interpolate_cache_cur_item_num = CacheManager::GetSubpixelVarianceCache()->GetCurItemNum();
1293 caches_info->interpolate_cache_hit_count = CacheManager::GetSubpixelVarianceCache()->GetCacheHitCount();
1294 caches_info->interpolate_cache_query_count = CacheManager::GetSubpixelVarianceCache()->GetQueryCount();
1295 caches_info->text_info_cache_cur_item_num = CacheManager::GetTextInfoCache()->GetCurItemNum();
1296 caches_info->text_info_cache_hit_count = CacheManager::GetTextInfoCache()->GetCacheHitCount();
1297 caches_info->text_info_cache_query_count = CacheManager::GetTextInfoCache()->GetQueryCount();
1299 caches_info->word_info_cache_cur_item_num = CacheManager::GetAssTagListMruCache()->GetCurItemNum();
1300 caches_info->word_info_cache_hit_count = CacheManager::GetAssTagListMruCache()->GetCacheHitCount();
1301 caches_info->word_info_cache_query_count = CacheManager::GetAssTagListMruCache()->GetQueryCount();
1303 caches_info->scanline_cache_cur_item_num = CacheManager::GetScanLineDataMruCache()->GetCurItemNum();
1304 caches_info->scanline_cache_hit_count = CacheManager::GetScanLineDataMruCache()->GetCacheHitCount();
1305 caches_info->scanline_cache_query_count = CacheManager::GetScanLineDataMruCache()->GetQueryCount();
1307 caches_info->overlay_key_cache_cur_item_num = CacheManager::GetOverlayNoOffsetMruCache()->GetCurItemNum();
1308 caches_info->overlay_key_cache_hit_count = CacheManager::GetOverlayNoOffsetMruCache()->GetCacheHitCount();
1309 caches_info->overlay_key_cache_query_count = CacheManager::GetOverlayNoOffsetMruCache()->GetQueryCount();
1311 caches_info->clipper_cache_cur_item_num = CacheManager::GetClipperAlphaMaskMruCache()->GetCurItemNum();
1312 caches_info->clipper_cache_hit_count = CacheManager::GetClipperAlphaMaskMruCache()->GetCacheHitCount();
1313 caches_info->clipper_cache_query_count = CacheManager::GetClipperAlphaMaskMruCache()->GetQueryCount();
1315 return hr;
1318 STDMETHODIMP CDirectVobSubFilter::get_XyFlyWeightInfo( XyFlyWeightInfo* xy_fw_info )
1320 CAutoLock cAutoLock(&m_csQueueLock);
1321 HRESULT hr = CDirectVobSub::get_XyFlyWeightInfo(xy_fw_info);
1323 xy_fw_info->xy_fw_string_w.cur_item_num = XyFwStringW::GetCacher()->GetCurItemNum();
1324 xy_fw_info->xy_fw_string_w.hit_count = XyFwStringW::GetCacher()->GetCacheHitCount();
1325 xy_fw_info->xy_fw_string_w.query_count = XyFwStringW::GetCacher()->GetQueryCount();
1327 xy_fw_info->xy_fw_grouped_draw_items_hash_key.cur_item_num = XyFwGroupedDrawItemsHashKey::GetCacher()->GetCurItemNum();
1328 xy_fw_info->xy_fw_grouped_draw_items_hash_key.hit_count = XyFwGroupedDrawItemsHashKey::GetCacher()->GetCacheHitCount();
1329 xy_fw_info->xy_fw_grouped_draw_items_hash_key.query_count = XyFwGroupedDrawItemsHashKey::GetCacher()->GetQueryCount();
1331 return hr;
1334 STDMETHODIMP CDirectVobSubFilter::get_MediaFPS(bool* fEnabled, double* fps)
1336 HRESULT hr = CDirectVobSub::get_MediaFPS(fEnabled, fps);
1338 CComQIPtr<IMediaSeeking> pMS = m_pGraph;
1339 double rate;
1340 if(pMS && SUCCEEDED(pMS->GetRate(&rate)))
1342 m_MediaFPS = rate * m_fps;
1343 if(fps) *fps = m_MediaFPS;
1346 return hr;
1349 STDMETHODIMP CDirectVobSubFilter::put_MediaFPS(bool fEnabled, double fps)
1351 HRESULT hr = CDirectVobSub::put_MediaFPS(fEnabled, fps);
1353 CComQIPtr<IMediaSeeking> pMS = m_pGraph;
1354 if(pMS)
1356 if(hr == NOERROR)
1358 hr = pMS->SetRate(m_fMediaFPSEnabled ? m_MediaFPS / m_fps : 1.0);
1361 double dRate;
1362 if(SUCCEEDED(pMS->GetRate(&dRate)))
1363 m_MediaFPS = dRate * m_fps;
1366 return hr;
1369 STDMETHODIMP CDirectVobSubFilter::get_ZoomRect(NORMALIZEDRECT* rect)
1371 return E_NOTIMPL;
1374 STDMETHODIMP CDirectVobSubFilter::put_ZoomRect(NORMALIZEDRECT* rect)
1376 return E_NOTIMPL;
1379 // IDirectVobSub2
1381 STDMETHODIMP CDirectVobSubFilter::put_TextSettings(STSStyle* pDefStyle)
1383 HRESULT hr = CDirectVobSub::put_TextSettings(pDefStyle);
1385 if(hr == NOERROR)
1387 //DbgLog((LOG_TRACE, 3, "%d %s:UpdateSubtitle(true)", __LINE__, __FUNCTION__));
1388 //UpdateSubtitle(true);
1389 UpdateSubtitle(false);
1392 return hr;
1395 STDMETHODIMP CDirectVobSubFilter::put_AspectRatioSettings(CSimpleTextSubtitle::EPARCompensationType* ePARCompensationType)
1397 HRESULT hr = CDirectVobSub::put_AspectRatioSettings(ePARCompensationType);
1399 if(hr == NOERROR)
1401 //DbgLog((LOG_TRACE, 3, "%d %s:UpdateSubtitle(true)", __LINE__, __FUNCTION__));
1402 //UpdateSubtitle(true);
1403 UpdateSubtitle(false);
1406 return hr;
1409 // IDirectVobSubFilterColor
1411 STDMETHODIMP CDirectVobSubFilter::HasConfigDialog(int iSelected)
1413 int nLangs;
1414 if(FAILED(get_LanguageCount(&nLangs))) return E_FAIL;
1415 return E_FAIL;
1416 // TODO: temporally disabled since we don't have a new textsub/vobsub editor dlg for dvs yet
1417 // return(nLangs >= 0 && iSelected < nLangs ? S_OK : E_FAIL);
1420 STDMETHODIMP CDirectVobSubFilter::ShowConfigDialog(int iSelected, HWND hWndParent)
1422 // TODO: temporally disabled since we don't have a new textsub/vobsub editor dlg for dvs yet
1423 return(E_FAIL);
1426 ///////////////////////////////////////////////////////////////////////////
1428 CDirectVobSubFilter2::CDirectVobSubFilter2(LPUNKNOWN punk, HRESULT* phr, const GUID& clsid) :
1429 CDirectVobSubFilter(punk, phr, clsid)
1433 HRESULT CDirectVobSubFilter2::CheckConnect(PIN_DIRECTION dir, IPin* pPin)
1435 CPinInfo pi;
1436 if(FAILED(pPin->QueryPinInfo(&pi))) return E_FAIL;
1438 if(CComQIPtr<IDirectVobSub>(pi.pFilter)) return E_FAIL;
1440 if(dir == PINDIR_INPUT)
1442 CFilterInfo fi;
1443 if(SUCCEEDED(pi.pFilter->QueryFilterInfo(&fi))
1444 && !wcsnicmp(fi.achName, L"Overlay Mixer", 13))
1445 return(E_FAIL);
1447 else
1451 return __super::CheckConnect(dir, pPin);
1454 HRESULT CDirectVobSubFilter2::JoinFilterGraph(IFilterGraph* pGraph, LPCWSTR pName)
1456 XY_AUTO_TIMING(_T("CDirectVobSubFilter2::JoinFilterGraph"));
1457 if(pGraph)
1459 BeginEnumFilters(pGraph, pEF, pBF)
1461 if(pBF != (IBaseFilter*)this && CComQIPtr<IDirectVobSub>(pBF))
1462 return E_FAIL;
1464 EndEnumFilters
1466 // don't look... we will do some serious graph hacking again...
1468 // we will add dvs2 to the filter graph cache
1469 // - if the main app has already added some kind of renderer or overlay mixer (anything which accepts video on its input)
1470 // and
1471 // - if we have a reason to auto-load (we don't want to make any trouble when there is no need :)
1473 // This whole workaround is needed because the video stream will always be connected
1474 // to the pre-added filters first, no matter how high merit we have.
1476 if(!get_Forced())
1478 BeginEnumFilters(pGraph, pEF, pBF)
1480 if(CComQIPtr<IDirectVobSub>(pBF))
1481 continue;
1483 CComPtr<IPin> pInPin = GetFirstPin(pBF, PINDIR_INPUT);
1484 CComPtr<IPin> pOutPin = GetFirstPin(pBF, PINDIR_OUTPUT);
1486 if(!pInPin)
1487 continue;
1489 CComPtr<IPin> pPin;
1490 if(pInPin && SUCCEEDED(pInPin->ConnectedTo(&pPin))
1491 || pOutPin && SUCCEEDED(pOutPin->ConnectedTo(&pPin)))
1492 continue;
1494 if(pOutPin && GetFilterName(pBF) == _T("Overlay Mixer"))
1495 continue;
1497 bool fVideoInputPin = false;
1501 BITMAPINFOHEADER bih = {sizeof(BITMAPINFOHEADER), 384, 288, 1, 16, '2YUY', 384*288*2, 0, 0, 0, 0};
1503 CMediaType cmt;
1504 cmt.majortype = MEDIATYPE_Video;
1505 cmt.subtype = MEDIASUBTYPE_YUY2;
1506 cmt.formattype = FORMAT_VideoInfo;
1507 cmt.pUnk = NULL;
1508 cmt.bFixedSizeSamples = TRUE;
1509 cmt.bTemporalCompression = TRUE;
1510 cmt.lSampleSize = 384*288*2;
1511 VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)cmt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
1512 memset(vih, 0, sizeof(VIDEOINFOHEADER));
1513 memcpy(&vih->bmiHeader, &bih, sizeof(bih));
1514 vih->AvgTimePerFrame = 400000;
1516 if(SUCCEEDED(pInPin->QueryAccept(&cmt)))
1518 fVideoInputPin = true;
1519 break;
1522 VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)cmt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER2));
1523 memset(vih2, 0, sizeof(VIDEOINFOHEADER2));
1524 memcpy(&vih2->bmiHeader, &bih, sizeof(bih));
1525 vih2->AvgTimePerFrame = 400000;
1526 vih2->dwPictAspectRatioX = 384;
1527 vih2->dwPictAspectRatioY = 288;
1529 if(SUCCEEDED(pInPin->QueryAccept(&cmt)))
1531 fVideoInputPin = true;
1532 break;
1535 while(false);
1537 if(fVideoInputPin)
1539 CComPtr<IBaseFilter> pDVS;
1540 if(ShouldWeAutoload(pGraph) && SUCCEEDED(pDVS.CoCreateInstance(__uuidof(CDirectVobSubFilter2))))
1542 CComQIPtr<IDirectVobSub2>(pDVS)->put_Forced(true);
1543 CComQIPtr<IGraphConfig>(pGraph)->AddFilterToCache(pDVS);
1546 break;
1549 EndEnumFilters
1552 else
1556 return __super::JoinFilterGraph(pGraph, pName);
1559 HRESULT CDirectVobSubFilter2::CheckInputType(const CMediaType* mtIn)
1561 XY_AUTO_TIMING(_T("CDirectVobSubFilter2::CheckInputType"));
1562 HRESULT hr = __super::CheckInputType(mtIn);
1564 if(FAILED(hr) || m_pInput->IsConnected()) return hr;
1566 if(!ShouldWeAutoload(m_pGraph)) return VFW_E_TYPE_NOT_ACCEPTED;
1568 GetRidOfInternalScriptRenderer();
1570 return NOERROR;
1573 bool CDirectVobSubFilter2::ShouldWeAutoload(IFilterGraph* pGraph)
1575 XY_AUTO_TIMING(_T("CDirectVobSubFilter2::ShouldWeAutoload"));
1576 TCHAR blacklistedapps[][32] =
1578 _T("WM8EUTIL."), // wmp8 encoder's dummy renderer releases the outputted media sample after calling Receive on its input pin (yes, even when dvobsub isn't registered at all)
1579 _T("explorer."), // as some users reported thumbnail preview loads dvobsub, I've never experienced this yet...
1580 _T("producer."), // this is real's producer
1581 _T("GoogleDesktopIndex."), // Google Desktop
1582 _T("GoogleDesktopDisplay."), // Google Desktop
1583 _T("GoogleDesktopCrawl."), // Google Desktop
1586 for(int i = 0; i < countof(blacklistedapps); i++)
1588 if(theApp.m_AppName.Find(blacklistedapps[i]) >= 0)
1589 return(false);
1592 int level;
1593 bool m_fExternalLoad, m_fWebLoad, m_fEmbeddedLoad;
1594 get_LoadSettings(&level, &m_fExternalLoad, &m_fWebLoad, &m_fEmbeddedLoad);
1596 if(level < 0 || level >= 2) return(false);
1598 bool fRet = false;
1600 if(level == 1)
1601 fRet = m_fExternalLoad = m_fWebLoad = m_fEmbeddedLoad = true;
1603 // find text stream on known splitters
1605 if(!fRet && m_fEmbeddedLoad)
1607 CComPtr<IBaseFilter> pBF;
1608 if((pBF = FindFilter(CLSID_OggSplitter, pGraph)) || (pBF = FindFilter(CLSID_AviSplitter, pGraph))
1609 || (pBF = FindFilter(L"{34293064-02F2-41D5-9D75-CC5967ACA1AB}", pGraph)) // matroska demux
1610 || (pBF = FindFilter(L"{0A68C3B5-9164-4a54-AFAF-995B2FF0E0D4}", pGraph)) // matroska source
1611 || (pBF = FindFilter(L"{149D2E01-C32E-4939-80F6-C07B81015A7A}", pGraph)) // matroska splitter
1612 || (pBF = FindFilter(L"{55DA30FC-F16B-49fc-BAA5-AE59FC65F82D}", pGraph)) // Haali Media Splitter
1613 || (pBF = FindFilter(L"{564FD788-86C9-4444-971E-CC4A243DA150}", pGraph)) // Haali Media Splitter (AR)
1614 || (pBF = FindFilter(L"{8F43B7D9-9D6B-4F48-BE18-4D787C795EEA}", pGraph)) // Haali Simple Media Splitter
1615 || (pBF = FindFilter(L"{52B63861-DC93-11CE-A099-00AA00479A58}", pGraph)) // 3ivx splitter
1616 || (pBF = FindFilter(L"{6D3688CE-3E9D-42F4-92CA-8A11119D25CD}", pGraph)) // our ogg source
1617 || (pBF = FindFilter(L"{9FF48807-E133-40AA-826F-9B2959E5232D}", pGraph)) // our ogg splitter
1618 || (pBF = FindFilter(L"{803E8280-F3CE-4201-982C-8CD8FB512004}", pGraph)) // dsm source
1619 || (pBF = FindFilter(L"{0912B4DD-A30A-4568-B590-7179EBB420EC}", pGraph)) // dsm splitter
1620 || (pBF = FindFilter(L"{3CCC052E-BDEE-408a-BEA7-90914EF2964B}", pGraph)) // mp4 source
1621 || (pBF = FindFilter(L"{61F47056-E400-43d3-AF1E-AB7DFFD4C4AD}", pGraph)) // mp4 splitter
1622 || (pBF = FindFilter(L"{171252A0-8820-4AFE-9DF8-5C92B2D66B04}", pGraph)) // LAV splitter
1623 || (pBF = FindFilter(L"{B98D13E7-55DB-4385-A33D-09FD1BA26338}", pGraph)) // LAV Splitter Source
1624 || (pBF = FindFilter(L"{E436EBB5-524F-11CE-9F53-0020AF0BA770}", pGraph)) // Solveig matroska splitter
1625 || (pBF = FindFilter(L"{1365BE7A-C86A-473C-9A41-C0A6E82C9FA3}", pGraph)) // MPC-HC MPEG PS/TS/PVA source
1626 || (pBF = FindFilter(L"{DC257063-045F-4BE2-BD5B-E12279C464F0}", pGraph)) // MPC-HC MPEG splitter
1627 || (pBF = FindFilter(L"{529A00DB-0C43-4f5b-8EF2-05004CBE0C6F}", pGraph)) // AV splitter
1628 || (pBF = FindFilter(L"{D8980E15-E1F6-4916-A10F-D7EB4E9E10B8}", pGraph)) // AV source
1631 BeginEnumPins(pBF, pEP, pPin)
1633 BeginEnumMediaTypes(pPin, pEM, pmt)
1635 if(pmt->majortype == MEDIATYPE_Text || pmt->majortype == MEDIATYPE_Subtitle)
1637 fRet = true;
1638 break;
1641 EndEnumMediaTypes(pmt)
1642 if(fRet) break;
1644 EndEnumFilters
1648 // find file name
1650 CStringW fn;
1652 BeginEnumFilters(pGraph, pEF, pBF)
1654 if(CComQIPtr<IFileSourceFilter> pFSF = pBF)
1656 LPOLESTR fnw = NULL;
1657 if(!pFSF || FAILED(pFSF->GetCurFile(&fnw, NULL)) || !fnw)
1658 continue;
1659 fn = CString(fnw);
1660 CoTaskMemFree(fnw);
1661 break;
1664 EndEnumFilters
1666 if((m_fExternalLoad || m_fWebLoad) && (m_fWebLoad || !(wcsstr(fn, L"http://") || wcsstr(fn, L"mms://"))))
1668 bool fTemp = m_fHideSubtitles;
1669 fRet = !fn.IsEmpty() && SUCCEEDED(put_FileName((LPWSTR)(LPCWSTR)fn))
1670 || SUCCEEDED(put_FileName(L"c:\\tmp.srt"))
1671 || fRet;
1672 if(fTemp) m_fHideSubtitles = true;
1675 return(fRet);
1678 void CDirectVobSubFilter2::GetRidOfInternalScriptRenderer()
1680 while(CComPtr<IBaseFilter> pBF = FindFilter(L"{48025243-2D39-11CE-875D-00608CB78066}", m_pGraph))
1682 BeginEnumPins(pBF, pEP, pPin)
1684 PIN_DIRECTION dir;
1685 CComPtr<IPin> pPinTo;
1687 if(SUCCEEDED(pPin->QueryDirection(&dir)) && dir == PINDIR_INPUT
1688 && SUCCEEDED(pPin->ConnectedTo(&pPinTo)))
1690 m_pGraph->Disconnect(pPinTo);
1691 m_pGraph->Disconnect(pPin);
1692 m_pGraph->ConnectDirect(pPinTo, GetPin(2 + m_pTextInput.GetCount()-1), NULL);
1695 EndEnumPins
1697 if(FAILED(m_pGraph->RemoveFilter(pBF)))
1698 break;
1702 ///////////////////////////////////////////////////////////////////////////////
1704 bool CDirectVobSubFilter::Open()
1706 AMTRACE((TEXT(__FUNCTION__),0));
1707 XY_AUTO_TIMING(TEXT("CDirectVobSubFilter::Open"));
1709 AFX_MANAGE_STATE(AfxGetStaticModuleState());
1711 CAutoLock cAutolock(&m_csQueueLock);
1713 m_pSubStreams.RemoveAll();
1714 m_fIsSubStreamEmbeded.RemoveAll();
1716 m_frd.files.RemoveAll();
1718 CAtlArray<CString> paths;
1720 for(int i = 0; i < 10; i++)
1722 CString tmp;
1723 tmp.Format(IDS_RP_PATH, i);
1724 CString path = theApp.GetProfileString(ResStr(IDS_R_DEFTEXTPATHES), tmp);
1725 if(!path.IsEmpty()) paths.Add(path);
1728 CAtlArray<SubFile> ret;
1729 GetSubFileNames(m_FileName, paths, ret);
1731 for(int i = 0; i < ret.GetCount(); i++)
1733 if(m_frd.files.Find(ret[i].fn))
1734 continue;
1736 CComPtr<ISubStream> pSubStream;
1738 if(!pSubStream)
1740 // CAutoTiming t(TEXT("CRenderedTextSubtitle::Open"), 0);
1741 XY_AUTO_TIMING(TEXT("CRenderedTextSubtitle::Open"));
1742 CAutoPtr<CRenderedTextSubtitle> pRTS(new CRenderedTextSubtitle(&m_csSubLock));
1743 if(pRTS && pRTS->Open(ret[i].fn, DEFAULT_CHARSET) && pRTS->GetStreamCount() > 0)
1745 pSubStream = pRTS.Detach();
1746 m_frd.files.AddTail(ret[i].fn + _T(".style"));
1750 if(!pSubStream)
1752 CAutoTiming t(TEXT("CVobSubFile::Open"), 0);
1753 CAutoPtr<CVobSubFile> pVSF(new CVobSubFile(&m_csSubLock));
1754 if(pVSF && pVSF->Open(ret[i].fn) && pVSF->GetStreamCount() > 0)
1756 pSubStream = pVSF.Detach();
1757 m_frd.files.AddTail(ret[i].fn.Left(ret[i].fn.GetLength()-4) + _T(".sub"));
1761 if(!pSubStream)
1763 CAutoTiming t(TEXT("ssf::CRenderer::Open"), 0);
1764 CAutoPtr<ssf::CRenderer> pSSF(new ssf::CRenderer(&m_csSubLock));
1765 if(pSSF && pSSF->Open(ret[i].fn) && pSSF->GetStreamCount() > 0)
1767 pSubStream = pSSF.Detach();
1771 if(pSubStream)
1773 m_pSubStreams.AddTail(pSubStream);
1774 m_fIsSubStreamEmbeded.AddTail(false);
1775 m_frd.files.AddTail(ret[i].fn);
1779 for(int i = 0; i < m_pTextInput.GetCount(); i++)
1781 if(m_pTextInput[i]->IsConnected())
1783 m_pSubStreams.AddTail(m_pTextInput[i]->GetSubStream());
1784 m_fIsSubStreamEmbeded.AddTail(true);
1788 if(S_FALSE == put_SelectedLanguage(FindPreferedLanguage()))
1789 UpdateSubtitle(false); // make sure pSubPicProvider of our queue gets updated even if the stream number hasn't changed
1791 m_frd.RefreshEvent.Set();
1793 return(m_pSubStreams.GetCount() > 0);
1796 void CDirectVobSubFilter::UpdateSubtitle(bool fApplyDefStyle)
1798 CAutoLock cAutolock(&m_csQueueLock);
1800 if(!m_simple_provider) return;
1802 InvalidateSubtitle();
1804 CComPtr<ISubStream> pSubStream;
1806 if(!m_fHideSubtitles)
1808 int i = m_iSelectedLanguage;
1810 for(POSITION pos = m_pSubStreams.GetHeadPosition(); i >= 0 && pos; pSubStream = NULL)
1812 pSubStream = m_pSubStreams.GetNext(pos);
1814 if(i < pSubStream->GetStreamCount())
1816 CAutoLock cAutoLock(&m_csSubLock);
1817 pSubStream->SetStream(i);
1818 break;
1821 i -= pSubStream->GetStreamCount();
1825 SetSubtitle(pSubStream, fApplyDefStyle);
1828 void CDirectVobSubFilter::SetSubtitle(ISubStream* pSubStream, bool fApplyDefStyle)
1830 DbgLog((LOG_TRACE, 3, "%s(%d): %s", __FILE__, __LINE__, __FUNCTION__));
1831 DbgLog((LOG_TRACE, 3, "\tpSubStream:%x fApplyDefStyle:%d", pSubStream, (int)fApplyDefStyle));
1832 CAutoLock cAutolock(&m_csQueueLock);
1834 CSize playres(0,0);
1835 m_script_selected_yuv = CSimpleTextSubtitle::YCbCrMatrix_AUTO;
1836 m_script_selected_range = CSimpleTextSubtitle::YCbCrRange_AUTO;
1837 if(pSubStream)
1839 CAutoLock cAutolock(&m_csSubLock);
1841 CLSID clsid;
1842 pSubStream->GetClassID(&clsid);
1844 if(clsid == __uuidof(CVobSubFile))
1846 CVobSubSettings* pVSS = dynamic_cast<CVobSubFile*>(pSubStream);
1848 if(fApplyDefStyle)
1850 pVSS->SetAlignment(m_fOverridePlacement, m_PlacementXperc, m_PlacementYperc, 1, 1);
1851 pVSS->m_fOnlyShowForcedSubs = m_fOnlyShowForcedVobSubs;
1854 else if(clsid == __uuidof(CVobSubStream))
1856 CVobSubSettings* pVSS = dynamic_cast<CVobSubStream*>(pSubStream);
1858 if(fApplyDefStyle)
1860 pVSS->SetAlignment(m_fOverridePlacement, m_PlacementXperc, m_PlacementYperc, 1, 1);
1861 pVSS->m_fOnlyShowForcedSubs = m_fOnlyShowForcedVobSubs;
1864 else if(clsid == __uuidof(CRenderedTextSubtitle))
1866 CRenderedTextSubtitle* pRTS = dynamic_cast<CRenderedTextSubtitle*>(pSubStream);
1868 if(fApplyDefStyle || pRTS->m_fUsingAutoGeneratedDefaultStyle)
1870 STSStyle s = m_defStyle;
1872 if(m_fOverridePlacement)
1874 s.scrAlignment = 2;
1875 int w = pRTS->m_dstScreenSize.cx;
1876 int h = pRTS->m_dstScreenSize.cy;
1877 CRect tmp_rect = s.marginRect.get();
1878 int mw = w - tmp_rect.left - tmp_rect.right;
1879 tmp_rect.bottom = h - MulDiv(h, m_PlacementYperc, 100);
1880 tmp_rect.left = MulDiv(w, m_PlacementXperc, 100) - mw/2;
1881 tmp_rect.right = w - (tmp_rect.left + mw);
1882 s.marginRect = tmp_rect;
1885 pRTS->SetDefaultStyle(s);
1888 pRTS->m_ePARCompensationType = m_ePARCompensationType;
1889 if (m_CurrentVIH2.dwPictAspectRatioX != 0 && m_CurrentVIH2.dwPictAspectRatioY != 0&& m_CurrentVIH2.bmiHeader.biWidth != 0 && m_CurrentVIH2.bmiHeader.biHeight != 0)
1891 pRTS->m_dPARCompensation = ((double)abs(m_CurrentVIH2.bmiHeader.biWidth) / (double)abs(m_CurrentVIH2.bmiHeader.biHeight)) /
1892 ((double)abs((long)m_CurrentVIH2.dwPictAspectRatioX) / (double)abs((long)m_CurrentVIH2.dwPictAspectRatioY));
1895 else
1897 pRTS->m_dPARCompensation = 1.00;
1900 m_script_selected_yuv = pRTS->m_eYCbCrMatrix;
1901 m_script_selected_range = pRTS->m_eYCbCrRange;
1902 pRTS->Deinit();
1903 playres = pRTS->m_dstScreenSize;
1907 if(!fApplyDefStyle)
1909 int i = 0;
1911 POSITION pos = m_pSubStreams.GetHeadPosition();
1912 while(pos)
1914 CComPtr<ISubStream> pSubStream2 = m_pSubStreams.GetNext(pos);
1916 if(pSubStream == pSubStream2)
1918 m_iSelectedLanguage = i + pSubStream2->GetStream();
1919 break;
1922 i += pSubStream2->GetStreamCount();
1926 m_nSubtitleId = reinterpret_cast<DWORD_PTR>(pSubStream);
1928 SetYuvMatrix();
1930 XySetSize(SIZE_ASS_PLAY_RESOLUTION, playres);
1931 if(m_simple_provider)
1932 m_simple_provider->SetSubPicProvider(CComQIPtr<ISubPicProviderEx>(pSubStream));
1935 void CDirectVobSubFilter::InvalidateSubtitle(REFERENCE_TIME rtInvalidate, DWORD_PTR nSubtitleId)
1937 CAutoLock cAutolock(&m_csQueueLock);
1939 if(m_simple_provider)
1941 if(nSubtitleId == -1 || nSubtitleId == m_nSubtitleId)
1943 DbgLog((LOG_TRACE, 3, "InvalidateSubtitle::Invalidate"));
1944 m_simple_provider->Invalidate(rtInvalidate);
1949 //////////////////////////////////////////////////////////////////////////////////////////
1951 void CDirectVobSubFilter::AddSubStream(ISubStream* pSubStream)
1953 CAutoLock cAutoLock(&m_csQueueLock);
1955 POSITION pos = m_pSubStreams.Find(pSubStream);
1956 if(!pos)
1958 m_pSubStreams.AddTail(pSubStream);
1959 m_fIsSubStreamEmbeded.AddTail(true);//todo: fix me
1962 int len = m_pTextInput.GetCount();
1963 for(int i = 0; i < m_pTextInput.GetCount(); i++)
1964 if(m_pTextInput[i]->IsConnected()) len--;
1966 if(len == 0)
1968 HRESULT hr = S_OK;
1969 m_pTextInput.Add(new CTextInputPin(this, m_pLock, &m_csSubLock, &hr));
1973 void CDirectVobSubFilter::RemoveSubStream(ISubStream* pSubStream)
1975 CAutoLock cAutoLock(&m_csQueueLock);
1977 POSITION pos = m_pSubStreams.GetHeadPosition();
1978 POSITION pos2 = m_fIsSubStreamEmbeded.GetHeadPosition();
1979 while(pos!=NULL)
1981 if( m_pSubStreams.GetAt(pos)==pSubStream )
1983 m_pSubStreams.RemoveAt(pos);
1984 m_fIsSubStreamEmbeded.RemoveAt(pos2);
1985 break;
1987 else
1989 m_pSubStreams.GetNext(pos);
1990 m_fIsSubStreamEmbeded.GetNext(pos2);
1995 void CDirectVobSubFilter::Post_EC_OLE_EVENT(CString str, DWORD_PTR nSubtitleId)
1997 if(nSubtitleId != -1 && nSubtitleId != m_nSubtitleId)
1998 return;
2000 CComQIPtr<IMediaEventSink> pMES = m_pGraph;
2001 if(!pMES) return;
2003 CComBSTR bstr1("Text"), bstr2(" ");
2005 str.Trim();
2006 if(!str.IsEmpty()) bstr2 = CStringA(str);
2008 pMES->Notify(EC_OLE_EVENT, (LONG_PTR)bstr1.Detach(), (LONG_PTR)bstr2.Detach());
2011 ////////////////////////////////////////////////////////////////
2013 void CDirectVobSubFilter::SetupFRD(CStringArray& paths, CAtlArray<HANDLE>& handles)
2015 CAutoLock cAutolock(&m_csSubLock);
2017 for(int i = 2; i < handles.GetCount(); i++)
2019 FindCloseChangeNotification(handles[i]);
2022 paths.RemoveAll();
2023 handles.RemoveAll();
2025 handles.Add(m_frd.EndThreadEvent);
2026 handles.Add(m_frd.RefreshEvent);
2028 m_frd.mtime.SetCount(m_frd.files.GetCount());
2030 POSITION pos = m_frd.files.GetHeadPosition();
2031 for(int i = 0; pos; i++)
2033 CString fn = m_frd.files.GetNext(pos);
2035 CFileStatus status;
2036 if(CFileGetStatus(fn, status))
2037 m_frd.mtime[i] = status.m_mtime;
2039 fn.Replace('\\', '/');
2040 fn = fn.Left(fn.ReverseFind('/')+1);
2042 bool fFound = false;
2044 for(int j = 0; !fFound && j < paths.GetCount(); j++)
2046 if(paths[j] == fn) fFound = true;
2049 if(!fFound)
2051 paths.Add(fn);
2053 HANDLE h = FindFirstChangeNotification(fn, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);
2054 if(h != INVALID_HANDLE_VALUE) handles.Add(h);
2059 DWORD CDirectVobSubFilter::ThreadProc()
2061 SetThreadPriority(m_hThread, THREAD_PRIORITY_LOWEST/*THREAD_PRIORITY_BELOW_NORMAL*/);
2063 CStringArray paths;
2064 CAtlArray<HANDLE> handles;
2066 SetupFRD(paths, handles);
2068 while(1)
2070 DWORD idx = WaitForMultipleObjects(handles.GetCount(), handles.GetData(), FALSE, INFINITE);
2072 if(idx == (WAIT_OBJECT_0 + 0)) // m_frd.hEndThreadEvent
2074 break;
2076 if(idx == (WAIT_OBJECT_0 + 1)) // m_frd.hRefreshEvent
2078 SetupFRD(paths, handles);
2080 else if(idx >= (WAIT_OBJECT_0 + 2) && idx < (WAIT_OBJECT_0 + handles.GetCount()))
2082 bool fLocked = true;
2083 IsSubtitleReloaderLocked(&fLocked);
2084 if(fLocked) continue;
2086 if(FindNextChangeNotification(handles[idx - WAIT_OBJECT_0]) == FALSE)
2087 break;
2089 int j = 0;
2091 POSITION pos = m_frd.files.GetHeadPosition();
2092 for(int i = 0; pos && j == 0; i++)
2094 CString fn = m_frd.files.GetNext(pos);
2096 CFileStatus status;
2097 if(CFileGetStatus(fn, status) && m_frd.mtime[i] != status.m_mtime)
2099 for(j = 0; j < 10; j++)
2101 if(FILE* f = _tfopen(fn, _T("rb+")))
2103 fclose(f);
2104 j = 0;
2105 break;
2107 else
2109 Sleep(100);
2110 j++;
2116 if(j > 0)
2118 SetupFRD(paths, handles);
2120 else
2122 Sleep(500);
2124 POSITION pos = m_frd.files.GetHeadPosition();
2125 for(int i = 0; pos; i++)
2127 CFileStatus status;
2128 if(CFileGetStatus(m_frd.files.GetNext(pos), status)
2129 && m_frd.mtime[i] != status.m_mtime)
2131 Open();
2132 SetupFRD(paths, handles);
2133 break;
2138 else
2140 break;
2144 for(int i = 2; i < handles.GetCount(); i++)
2146 FindCloseChangeNotification(handles[i]);
2149 return 0;
2152 void CDirectVobSubFilter::GetInputColorspaces( ColorSpaceId *preferredOrder, UINT *count )
2154 ColorSpaceOpt *color_space=NULL;
2155 int tempCount = 0;
2156 if( XyGetBin(BIN_INPUT_COLOR_FORMAT, reinterpret_cast<LPVOID*>(&color_space), &tempCount)==S_OK )
2158 *count = 0;
2159 for (int i=0;i<tempCount;i++)
2161 if(color_space[i].selected)
2163 preferredOrder[*count] = color_space[i].color_space;
2164 (*count)++;
2168 else
2170 CBaseVideoFilter::GetInputColorspaces(preferredOrder, count);
2172 delete[]color_space;
2175 void CDirectVobSubFilter::GetOutputColorspaces( ColorSpaceId *preferredOrder, UINT *count )
2177 ColorSpaceOpt *color_space=NULL;
2178 int tempCount = 0;
2179 if( XyGetBin(BIN_OUTPUT_COLOR_FORMAT, reinterpret_cast<LPVOID*>(&color_space), &tempCount)==S_OK )
2181 *count = 0;
2182 for (int i=0;i<tempCount;i++)
2184 if(color_space[i].selected)
2186 preferredOrder[*count] = color_space[i].color_space;
2187 (*count)++;
2191 else
2193 CBaseVideoFilter::GetInputColorspaces(preferredOrder, count);
2195 delete []color_space;
2198 HRESULT CDirectVobSubFilter::GetIsEmbeddedSubStream( int iSelected, bool *fIsEmbedded )
2200 CAutoLock cAutolock(&m_csQueueLock);
2202 HRESULT hr = E_INVALIDARG;
2203 if (!fIsEmbedded)
2205 return S_FALSE;
2208 int i = iSelected;
2209 *fIsEmbedded = false;
2211 POSITION pos = m_pSubStreams.GetHeadPosition();
2212 POSITION pos2 = m_fIsSubStreamEmbeded.GetHeadPosition();
2213 while(i >= 0 && pos)
2215 CComPtr<ISubStream> pSubStream = m_pSubStreams.GetNext(pos);
2216 bool isEmbedded = m_fIsSubStreamEmbeded.GetNext(pos2);
2217 if(i < pSubStream->GetStreamCount())
2219 hr = NOERROR;
2220 *fIsEmbedded = isEmbedded;
2221 break;
2224 i -= pSubStream->GetStreamCount();
2226 return hr;
2229 void CDirectVobSubFilter::SetYuvMatrix()
2231 ColorConvTable::YuvMatrixType yuv_matrix = ColorConvTable::BT601;
2232 ColorConvTable::YuvRangeType yuv_range = ColorConvTable::RANGE_TV;
2234 if ( m_xy_int_opt[INT_COLOR_SPACE]==CDirectVobSub::YuvMatrix_AUTO )
2236 switch(m_script_selected_yuv)
2238 case CSimpleTextSubtitle::YCbCrMatrix_BT601:
2239 yuv_matrix = ColorConvTable::BT601;
2240 break;
2241 case CSimpleTextSubtitle::YCbCrMatrix_BT709:
2242 yuv_matrix = ColorConvTable::BT709;
2243 break;
2244 case CSimpleTextSubtitle::YCbCrMatrix_AUTO:
2245 default:
2246 yuv_matrix = ColorConvTable::BT601;
2247 break;
2250 else
2252 switch(m_xy_int_opt[INT_COLOR_SPACE])
2254 case CDirectVobSub::BT_601:
2255 yuv_matrix = ColorConvTable::BT601;
2256 break;
2257 case CDirectVobSub::BT_709:
2258 yuv_matrix = ColorConvTable::BT709;
2259 break;
2260 case CDirectVobSub::GUESS:
2261 default:
2262 yuv_matrix = (m_w > m_bt601Width || m_h > m_bt601Height) ? ColorConvTable::BT709 : ColorConvTable::BT601;
2263 break;
2267 if( m_xy_int_opt[INT_YUV_RANGE]==CDirectVobSub::YuvRange_Auto )
2269 switch(m_script_selected_range)
2271 case CSimpleTextSubtitle::YCbCrRange_PC:
2272 yuv_range = ColorConvTable::RANGE_PC;
2273 break;
2274 case CSimpleTextSubtitle::YCbCrRange_TV:
2275 yuv_range = ColorConvTable::RANGE_TV;
2276 break;
2277 case CSimpleTextSubtitle::YCbCrRange_AUTO:
2278 default:
2279 yuv_range = ColorConvTable::RANGE_TV;
2280 break;
2283 else
2285 switch(m_xy_int_opt[INT_YUV_RANGE])
2287 case CDirectVobSub::YuvRange_TV:
2288 yuv_range = ColorConvTable::RANGE_TV;
2289 break;
2290 case CDirectVobSub::YuvRange_PC:
2291 yuv_range = ColorConvTable::RANGE_PC;
2292 break;
2293 case CDirectVobSub::YuvRange_Auto:
2294 yuv_range = ColorConvTable::RANGE_TV;
2295 break;
2299 ColorConvTable::SetDefaultConvType(yuv_matrix, yuv_range);
2302 // IDirectVobSubXy
2304 STDMETHODIMP CDirectVobSubFilter::XySetBool( int field, bool value )
2306 CAutoLock cAutolock(&m_csQueueLock);
2307 HRESULT hr = CDirectVobSub::XySetBool(field, value);
2308 if(hr != NOERROR)
2310 return hr;
2312 switch(field)
2314 case DirectVobSubXyOptions::BOOL_FOLLOW_UPSTREAM_PREFERRED_ORDER:
2315 m_donot_follow_upstream_preferred_order = !m_xy_bool_opt[BOOL_FOLLOW_UPSTREAM_PREFERRED_ORDER];
2316 break;
2317 default:
2318 hr = E_NOTIMPL;
2319 break;
2321 return hr;
2324 STDMETHODIMP CDirectVobSubFilter::XySetInt( int field, int value )
2326 CAutoLock cAutolock(&m_csQueueLock);
2327 HRESULT hr = CDirectVobSub::XySetInt(field, value);
2328 if(hr != NOERROR)
2330 return hr;
2332 switch(field)
2334 case DirectVobSubXyOptions::INT_COLOR_SPACE:
2335 case DirectVobSubXyOptions::INT_YUV_RANGE:
2336 SetYuvMatrix();
2337 break;
2338 case DirectVobSubXyOptions::INT_OVERLAY_CACHE_MAX_ITEM_NUM:
2339 CacheManager::GetOverlayMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2340 break;
2341 case DirectVobSubXyOptions::INT_SCAN_LINE_DATA_CACHE_MAX_ITEM_NUM:
2342 CacheManager::GetScanLineData2MruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2343 break;
2344 case DirectVobSubXyOptions::INT_PATH_DATA_CACHE_MAX_ITEM_NUM:
2345 CacheManager::GetPathDataMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2346 break;
2347 case DirectVobSubXyOptions::INT_OVERLAY_NO_BLUR_CACHE_MAX_ITEM_NUM:
2348 CacheManager::GetOverlayNoBlurMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2349 break;
2350 case DirectVobSubXyOptions::INT_BITMAP_MRU_CACHE_ITEM_NUM:
2351 CacheManager::GetBitmapMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2352 break;
2353 case DirectVobSubXyOptions::INT_CLIPPER_MRU_CACHE_ITEM_NUM:
2354 CacheManager::GetClipperAlphaMaskMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2355 break;
2356 case DirectVobSubXyOptions::INT_TEXT_INFO_CACHE_ITEM_NUM:
2357 CacheManager::GetTextInfoCache()->SetMaxItemNum(m_xy_int_opt[field]);
2358 break;
2359 case DirectVobSubXyOptions::INT_ASS_TAG_LIST_CACHE_ITEM_NUM:
2360 CacheManager::GetAssTagListMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
2361 break;
2362 case DirectVobSubXyOptions::INT_SUBPIXEL_POS_LEVEL:
2363 SubpixelPositionControler::GetGlobalControler().SetSubpixelLevel( static_cast<SubpixelPositionControler::SUBPIXEL_LEVEL>(m_xy_int_opt[field]) );
2364 break;
2365 default:
2366 hr = E_NOTIMPL;
2367 break;
2370 return hr;