More aggressive blur detection.
[xy_vsfilter.git] / src / subtitles / RTS.cpp
bloba113e2b8aea3b5904bc8914590f7feda1b15aaeb
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 "RTS.h"
26 #include "draw_item.h"
27 #include "cache_manager.h"
28 #include "subpixel_position_controler.h"
29 #include "xy_overlay_paint_machine.h"
30 #include "xy_clipper_paint_machine.h"
32 // WARNING: this isn't very thread safe, use only one RTS a time.
33 static HDC g_hDC;
34 static int g_hDC_refcnt = 0;
36 static long revcolor(long c)
38 return ((c&0xff0000)>>16) + (c&0xff00) + ((c&0xff)<<16);
41 // Skip all leading whitespace
42 inline CStringW::PCXSTR SkipWhiteSpaceLeft(const CStringW& str)
44 CStringW::PCXSTR psz = str.GetString();
46 while( iswspace( *psz ) )
48 psz++;
50 return psz;
53 // Skip all trailing whitespace
54 inline CStringW::PCXSTR SkipWhiteSpaceRight(const CStringW& str)
56 CStringW::PCXSTR psz = str.GetString();
57 CStringW::PCXSTR pszLast = psz + str.GetLength() - 1;
58 bool first_white = false;
59 while( iswspace( *pszLast ) )
61 pszLast--;
62 if(pszLast<psz)
63 break;
65 return pszLast;
68 // Skip all leading whitespace
69 inline CStringW::PCXSTR SkipWhiteSpaceLeft(CStringW::PCXSTR start, CStringW::PCXSTR end)
71 while( start!=end && iswspace( *start ) )
73 start++;
75 return start;
78 // Skip all trailing whitespace, first char must NOT be white space
79 inline CStringW::PCXSTR FastSkipWhiteSpaceRight(CStringW::PCXSTR start, CStringW::PCXSTR end)
81 while( iswspace( *--end ) );
82 return end+1;
85 inline CStringW::PCXSTR FindChar(CStringW::PCXSTR start, CStringW::PCXSTR end, WCHAR c)
87 while( start!=end && *start!=c )
89 start++;
91 return start;
94 //////////////////////////////////////////////////////////////////////////////////////////////
96 // CMyFont
98 CMyFont::CMyFont(const STSStyleBase& style)
100 LOGFONT lf;
101 memset(&lf, 0, sizeof(lf));
102 lf <<= style;
103 lf.lfHeight = (LONG)(style.fontSize+0.5);
104 lf.lfOutPrecision = OUT_TT_PRECIS;
105 lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
106 lf.lfQuality = ANTIALIASED_QUALITY;
107 lf.lfPitchAndFamily = DEFAULT_PITCH|FF_DONTCARE;
108 if(!CreateFontIndirect(&lf))
110 _tcscpy(lf.lfFaceName, _T("Arial"));
111 CreateFontIndirect(&lf);
113 HFONT hOldFont = SelectFont(g_hDC, *this);
114 TEXTMETRIC tm;
115 GetTextMetrics(g_hDC, &tm);
116 m_ascent = ((tm.tmAscent + 4) >> 3);
117 m_descent = ((tm.tmDescent + 4) >> 3);
118 SelectFont(g_hDC, hOldFont);
121 // CWord
123 CWord::CWord(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend)
124 : m_style(style), m_str(str)
125 , m_width(0), m_ascent(0), m_descent(0)
126 , m_ktype(ktype), m_kstart(kstart), m_kend(kend)
127 , m_fLineBreak(false), m_fWhiteSpaceChar(false)
128 //, m_pOpaqueBox(NULL)
130 if(m_str.IsEmpty())
132 m_fWhiteSpaceChar = m_fLineBreak = true;
134 m_width = 0;
137 CWord::CWord( const CWord& src)
139 m_str = src.m_str;
140 m_fWhiteSpaceChar = src.m_fWhiteSpaceChar;
141 m_fLineBreak = src.m_fLineBreak;
142 m_style = src.m_style;
143 m_pOpaqueBox = src.m_pOpaqueBox;//allow since it is shared_ptr
144 m_ktype = src.m_ktype;
145 m_kstart = src.m_kstart;
146 m_kend = src.m_kend;
147 m_width = src.m_width;
148 m_ascent = src.m_ascent;
149 m_descent = src.m_descent;
152 CWord::~CWord()
154 //if(m_pOpaqueBox) delete m_pOpaqueBox;
157 bool CWord::Append(const SharedPtrCWord& w)
159 if(!(m_style == w->m_style)
160 || m_fLineBreak || w->m_fLineBreak
161 || w->m_kstart != w->m_kend || m_ktype != w->m_ktype) return(false);
162 m_fWhiteSpaceChar = m_fWhiteSpaceChar && w->m_fWhiteSpaceChar;
163 m_str += w->m_str;
164 m_width += w->m_width;
165 return(true);
168 void CWord::PaintFromOverlay(const CPoint& p, const CPoint& trans_org2, OverlayKey &subpixel_variance_key, SharedPtrOverlay& overlay)
170 if( SubpixelPositionControler::GetGlobalControler().UseBilinearShift() )
172 CPoint psub = SubpixelPositionControler::GetGlobalControler().GetSubpixel(p);
173 if( (psub.x!=(p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK)
174 || psub.y!=(p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK)) )
176 overlay.reset(overlay->GetSubpixelVariance((p.x&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) - psub.x,
177 (p.y&SubpixelPositionControler::EIGHT_X_EIGHT_MASK) - psub.y));
178 OverlayMruCache* overlay_cache = CacheManager::GetSubpixelVarianceCache();
179 overlay_cache->UpdateCache(subpixel_variance_key, overlay);
184 void CWord::PaintFromNoneBluredOverlay(SharedPtrOverlay raterize_result, const OverlayKey& overlay_key, SharedPtrOverlay* overlay)
186 if( Rasterizer::IsItReallyBlur(m_style.get().fBlur, m_style.get().fGaussianBlur) )
188 overlay->reset(new Overlay());
189 if(!Rasterizer::Blur(*raterize_result, m_style.get().fBlur, m_style.get().fGaussianBlur, *overlay))
191 *overlay = raterize_result;
194 else
196 *overlay = raterize_result;
198 OverlayMruCache* overlay_cache = CacheManager::GetOverlayMruCache();
199 overlay_cache->UpdateCache(overlay_key, *overlay);
202 bool CWord::PaintFromScanLineData2(const CPoint& psub, const ScanLineData2& scan_line_data2, const OverlayKey& key, SharedPtrOverlay* overlay)
204 SharedPtrOverlay raterize_result(new Overlay());
205 if(!Rasterizer::Rasterize(scan_line_data2, psub.x, psub.y, raterize_result))
207 return false;
209 OverlayNoBlurMruCache* overlay_no_blur_cache = CacheManager::GetOverlayNoBlurMruCache();
210 overlay_no_blur_cache->UpdateCache(key, raterize_result);
211 PaintFromNoneBluredOverlay(raterize_result, key, overlay);
212 return true;
215 bool CWord::PaintFromPathData(const CPoint& psub, const CPoint& trans_org, const PathData& path_data, const OverlayKey& key, SharedPtrOverlay* overlay )
217 bool result = false;
219 PathData *path_data2 = new PathData(path_data);//fix me: this copy operation can be saved if no transform is needed
220 SharedPtrConstPathData shared_ptr_path_data2(path_data2);
221 bool need_transform = NeedTransform();
222 if(need_transform)
223 Transform(path_data2, CPoint(trans_org.x*8, trans_org.y*8));
225 CPoint left_top;
226 CSize size;
227 path_data2->AlignLeftTop(&left_top, &size);
229 int border_x = static_cast<int>(m_style.get().outlineWidthX+0.5);
230 int border_y = static_cast<int>(m_style.get().outlineWidthY+0.5);
231 int wide_border = border_x>border_y ? border_x:border_y;
232 if (m_style.get().borderStyle==1)
234 border_x = border_y = 0;
237 OverlayNoOffsetMruCache* overlay_key_cache = CacheManager::GetOverlayNoOffsetMruCache();
238 OverlayNoOffsetKey overlay_no_offset_key(shared_ptr_path_data2, psub.x, psub.y, border_x, border_y);
239 overlay_no_offset_key.UpdateHashValue();
240 POSITION pos = overlay_key_cache->Lookup(overlay_no_offset_key);
242 OverlayNoBlurMruCache* overlay_cache = CacheManager::GetOverlayNoBlurMruCache();
243 if (pos!=NULL)
245 OverlayNoBlurKey overlay_key = overlay_key_cache->GetAt(pos);
246 pos = overlay_cache->Lookup(overlay_key);
248 if (pos)
250 SharedPtrOverlay raterize_result( new Overlay() );
251 *raterize_result = *overlay_cache->GetAt(pos);
252 raterize_result->mOffsetX = left_top.x - psub.x - ((wide_border+7)&~7);
253 raterize_result->mOffsetY = left_top.y - psub.y - ((wide_border+7)&~7);
254 PaintFromNoneBluredOverlay(raterize_result, key, overlay);
255 result = true;
256 overlay_cache->UpdateCache(key, raterize_result);
258 else
260 ScanLineDataMruCache* scan_line_data_cache = CacheManager::GetScanLineDataMruCache();
261 pos = scan_line_data_cache->Lookup(overlay_no_offset_key);
262 SharedPtrConstScanLineData scan_line_data;
263 if( pos != NULL )
265 scan_line_data = scan_line_data_cache->GetAt(pos);
266 scan_line_data_cache->UpdateCache(pos);
268 else
270 ScanLineData *tmp = new ScanLineData();
271 scan_line_data.reset(tmp);
272 if(!tmp->ScanConvert(*path_data2, size))
274 return false;
276 scan_line_data_cache->UpdateCache(overlay_no_offset_key, scan_line_data);
278 ScanLineData2 *tmp = new ScanLineData2(left_top, scan_line_data);
279 SharedPtrScanLineData2 scan_line_data2( tmp );
280 if(m_style.get().borderStyle == 0 && (m_style.get().outlineWidthX+m_style.get().outlineWidthY > 0))
282 if(!tmp->CreateWidenedRegion(border_x, border_y))
284 return false;
287 ScanLineData2MruCache* scan_line_data2_cache = CacheManager::GetScanLineData2MruCache();
288 scan_line_data2_cache->UpdateCache(key, scan_line_data2);
289 result = PaintFromScanLineData2(psub, *tmp, key, overlay);
291 if (result)
293 overlay_key_cache->UpdateCache(overlay_no_offset_key, key);
295 return result;
298 bool CWord::PaintFromRawData( const CPoint& psub, const CPoint& trans_org, const OverlayKey& key, SharedPtrOverlay* overlay )
300 PathDataMruCache* path_data_cache = CacheManager::GetPathDataMruCache();
302 PathData *tmp=new PathData();
303 SharedPtrPathData path_data(tmp);
304 if(!CreatePath(tmp))
306 return false;
308 path_data_cache->UpdateCache(key, path_data);
309 return PaintFromPathData(psub, trans_org, *tmp, key, overlay);
312 bool CWord::DoPaint(const CPoint& psub, const CPoint& trans_org, SharedPtrOverlay* overlay, const OverlayKey& key)
314 bool result = true;
315 OverlayNoBlurMruCache* overlay_no_blur_cache = CacheManager::GetOverlayNoBlurMruCache();
316 POSITION pos = overlay_no_blur_cache->Lookup(key);
318 if(pos!=NULL)
320 SharedPtrOverlay raterize_result = overlay_no_blur_cache->GetAt(pos);
321 overlay_no_blur_cache->UpdateCache( pos );
322 PaintFromNoneBluredOverlay(raterize_result, key, overlay);
324 else
326 ScanLineData2MruCache* scan_line_data_cache = CacheManager::GetScanLineData2MruCache();
327 pos = scan_line_data_cache->Lookup(key);
328 if(pos!=NULL)
330 SharedPtrConstScanLineData2 scan_line_data = scan_line_data_cache->GetAt(pos);
331 scan_line_data_cache->UpdateCache( pos );
332 result = PaintFromScanLineData2(psub, *scan_line_data, key, overlay);
334 else
336 PathDataMruCache* path_data_cache = CacheManager::GetPathDataMruCache();
337 POSITION pos_path = path_data_cache->Lookup(key);
338 if(pos_path!=NULL)
340 SharedPtrConstPathData path_data = path_data_cache->GetAt(pos_path); //important! copy not ref
341 path_data_cache->UpdateCache( pos_path );
342 result = PaintFromPathData(psub, trans_org, *path_data, key, overlay);
344 else
346 result = PaintFromRawData(psub, trans_org, key, overlay);
350 return result;
353 bool CWord::NeedTransform()
355 return (fabs(m_style.get().fontScaleX - 100) > 0.000001) ||
356 (fabs(m_style.get().fontScaleY - 100) > 0.000001) ||
357 (fabs(m_style.get().fontAngleX) > 0.000001) ||
358 (fabs(m_style.get().fontAngleY) > 0.000001) ||
359 (fabs(m_style.get().fontAngleZ) > 0.000001) ||
360 (fabs(m_style.get().fontShiftX) > 0.000001) ||
361 (fabs(m_style.get().fontShiftY) > 0.000001);
364 void CWord::Transform(PathData* path_data, const CPoint& org)
366 //// CPUID from VDub
367 //bool fSSE2 = !!(g_cpuid.m_flags & CCpuID::sse2);
369 //if(fSSE2) { // SSE code
370 // Transform_SSE2(path_data, org);
371 //} else // C-code
372 Transform_C(path_data, org);
375 void CWord::Transform_C(PathData* path_data, const CPoint &org )
377 double scalex = m_style.get().fontScaleX/100;
378 double scaley = m_style.get().fontScaleY/100;
380 double caz = cos((3.1415/180)*m_style.get().fontAngleZ);
381 double saz = sin((3.1415/180)*m_style.get().fontAngleZ);
382 double cax = cos((3.1415/180)*m_style.get().fontAngleX);
383 double sax = sin((3.1415/180)*m_style.get().fontAngleX);
384 double cay = cos((3.1415/180)*m_style.get().fontAngleY);
385 double say = sin((3.1415/180)*m_style.get().fontAngleY);
387 #ifdef _VSMOD
388 // patch m003. random text points
389 double xrnd = m_style.get().mod_rand.X*100;
390 double yrnd = m_style.get().mod_rand.Y*100;
391 double zrnd = m_style.get().mod_rand.Z*100;
393 srand(m_style.get().mod_rand.Seed);
395 // patch m008. distort
396 int xsz,ysz;
397 double dst1x,dst1y,dst2x,dst2y,dst3x,dst3y;
398 int minx = INT_MAX, miny = INT_MAX, maxx = -INT_MAX, maxy = -INT_MAX;
400 bool is_dist = m_style.get().mod_distort.enabled;
401 if (is_dist) {
402 for(int i = 0; i < path_data->mPathPoints; i++) {
403 if(minx > path_data->mpPathPoints[i].x) {
404 minx = path_data->mpPathPoints[i].x;
406 if(miny > path_data->mpPathPoints[i].y) {
407 miny = path_data->mpPathPoints[i].y;
409 if(maxx < path_data->mpPathPoints[i].x) {
410 maxx = path_data->mpPathPoints[i].x;
412 if(maxy < path_data->mpPathPoints[i].y) {
413 maxy = path_data->mpPathPoints[i].y;
417 xsz = max(maxx - minx, 0);
418 ysz = max(maxy - miny, 0);
420 dst1x = m_style.get().mod_distort.pointsx[0];
421 dst1y = m_style.get().mod_distort.pointsy[0];
422 dst2x = m_style.get().mod_distort.pointsx[1];
423 dst2y = m_style.get().mod_distort.pointsy[1];
424 dst3x = m_style.get().mod_distort.pointsx[2];
425 dst3y = m_style.get().mod_distort.pointsy[2];
427 #endif
429 for (int i = 0; i < path_data->mPathPoints; i++) {
430 double x, y, z, xx, yy, zz;
432 x = path_data->mpPathPoints[i].x;
433 y = path_data->mpPathPoints[i].y;
434 #ifdef _VSMOD
435 // patch m002. Z-coord
436 z = m_style.get().mod_z;
438 double u, v;
439 if (is_dist) {
440 u = (x-minx) / xsz;
441 v = (y-miny) / ysz;
443 x = minx+(0 + (dst1x - 0)*u + (dst3x-0)*v+(0+dst2x-dst1x-dst3x)*u*v)*xsz;
444 y = miny+(0 + (dst1y - 0)*u + (dst3y-0)*v+(0+dst2y-dst1y-dst3y)*u*v)*ysz;
445 //P = P0 + (P1 - P0)u + (P3 - P0)v + (P0 + P2 - P1 - P3)uv
448 // patch m003. random text points
449 x = xrnd > 0 ? (xrnd - rand() % (int)(xrnd * 2 + 1)) / 100.0 + x : x;
450 y = yrnd > 0 ? (yrnd - rand() % (int)(yrnd * 2 + 1)) / 100.0 + y : y;
451 z = zrnd > 0 ? (zrnd - rand() % (int)(zrnd * 2 + 1)) / 100.0 + z : z;
452 #else
453 z = 0;
454 #endif
455 double _x = x;
456 x = scalex * (x + m_style.get().fontShiftX * y) - org.x;
457 y = scaley * (y + m_style.get().fontShiftY * _x) - org.y;
459 xx = x*caz + y*saz;
460 yy = -(x*saz - y*caz);
461 zz = z;
463 x = xx;
464 y = yy*cax + zz*sax;
465 z = yy*sax - zz*cax;
467 xx = x*cay + z*say;
468 yy = y;
469 zz = x*say - z*cay;
471 zz = max(zz, -19000);
473 x = (xx * 20000) / (zz + 20000);
474 y = (yy * 20000) / (zz + 20000);
476 path_data->mpPathPoints[i].x = (LONG)(x + org.x + 0.5);
477 path_data->mpPathPoints[i].y = (LONG)(y + org.y + 0.5);
481 void CWord::Transform_SSE2(PathData* path_data, const CPoint &org )
483 // __m128 union data type currently not supported with Intel C++ Compiler, so just call C version
484 #ifdef __ICL
485 Transform_C(org);
486 #else
487 // SSE code
488 // speed up ~1.5-1.7x
489 double scalex = m_style.get().fontScaleX/100;
490 double scaley = m_style.get().fontScaleY/100;
492 double caz = cos((3.1415/180)*m_style.get().fontAngleZ);
493 double saz = sin((3.1415/180)*m_style.get().fontAngleZ);
494 double cax = cos((3.1415/180)*m_style.get().fontAngleX);
495 double sax = sin((3.1415/180)*m_style.get().fontAngleX);
496 double cay = cos((3.1415/180)*m_style.get().fontAngleY);
497 double say = sin((3.1415/180)*m_style.get().fontAngleY);
499 __m128 __xshift = _mm_set_ps1(m_style.get().fontShiftX);
500 __m128 __yshift = _mm_set_ps1(m_style.get().fontShiftY);
502 __m128 __xorg = _mm_set_ps1(org.x);
503 __m128 __yorg = _mm_set_ps1(org.y);
505 __m128 __xscale = _mm_set_ps1(scalex);
506 __m128 __yscale = _mm_set_ps1(scaley);
508 #ifdef _VSMOD
509 // patch m003. random text points
510 double xrnd = m_style.get().mod_rand.X*100;
511 double yrnd = m_style.get().mod_rand.Y*100;
512 double zrnd = m_style.get().mod_rand.Z*100;
514 srand(m_style.get().mod_rand.Seed);
516 __m128 __xsz = _mm_setzero_ps();
517 __m128 __ysz = _mm_setzero_ps();
519 __m128 __dst1x, __dst1y, __dst213x, __dst213y, __dst3x, __dst3y;
521 __m128 __miny;
522 __m128 __minx = _mm_set_ps(INT_MAX, INT_MAX, 0, 0);
523 __m128 __max = _mm_set_ps(-INT_MAX, -INT_MAX, 1, 1);
525 bool is_dist = m_style.get().mod_distort.enabled;
526 if(is_dist) {
527 for(int i = 0; i < path_data->mPathPoints; i++) {
528 __m128 __point = _mm_set_ps(path_data->mpPathPoints[i].x, path_data->mpPathPoints[i].y, 0, 0);
529 __minx = _mm_min_ps(__minx, __point);
530 __max = _mm_max_ps(__max, __point);
533 __m128 __zero = _mm_setzero_ps();
534 __max = _mm_sub_ps(__max, __minx); // xsz, ysz, 1, 1
535 __max = _mm_max_ps(__max, __zero);
537 __xsz = _mm_shuffle_ps(__max, __max, _MM_SHUFFLE(3,3,3,3));
538 __ysz = _mm_shuffle_ps(__max, __max, _MM_SHUFFLE(2,2,2,2));
540 __miny = _mm_shuffle_ps(__minx, __minx, _MM_SHUFFLE(2,2,2,2));
541 __minx = _mm_shuffle_ps(__minx, __minx, _MM_SHUFFLE(3,3,3,3));
543 __dst1x = _mm_set_ps1(m_style.get().mod_distort.pointsx[0]);
544 __dst1y = _mm_set_ps1(m_style.get().mod_distort.pointsy[0]);
545 __dst3x = _mm_set_ps1(m_style.get().mod_distort.pointsx[2]);
546 __dst3y = _mm_set_ps1(m_style.get().mod_distort.pointsy[2]);
547 __dst213x = _mm_set_ps1(m_style.get().mod_distort.pointsx[1]); // 2 - 1 - 3
548 __dst213x = _mm_sub_ps(__dst213x, __dst1x);
549 __dst213x = _mm_sub_ps(__dst213x, __dst3x);
551 __dst213y = _mm_set_ps1(m_style.get().mod_distort.pointsy[1]);
552 __dst213x = _mm_sub_ps(__dst213y, __dst1y);
553 __dst213x = _mm_sub_ps(__dst213y, __dst3y);
555 #endif
557 __m128 __caz = _mm_set_ps1(caz);
558 __m128 __saz = _mm_set_ps1(saz);
559 __m128 __cax = _mm_set_ps1(cax);
560 __m128 __sax = _mm_set_ps1(sax);
561 __m128 __cay = _mm_set_ps1(cay);
562 __m128 __say = _mm_set_ps1(say);
564 // this can be paralleled for openmp
565 int mPathPointsD4 = path_data->mPathPoints / 4;
566 int mPathPointsM4 = path_data->mPathPoints % 4;
568 for(ptrdiff_t i = 0; i < mPathPointsD4 + 1; i++) {
569 POINT* const temp_points = path_data->mpPathPoints + 4 * i;
571 __m128 __pointx, __pointy;
572 // we can't use load .-.
573 if(i != mPathPointsD4) {
574 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, temp_points[2].x, temp_points[3].x);
575 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, temp_points[2].y, temp_points[3].y);
576 } else { // last cycle
577 switch(mPathPointsM4) {
578 default:
579 case 0:
580 continue;
581 case 1:
582 __pointx = _mm_set_ps(temp_points[0].x, 0, 0, 0);
583 __pointy = _mm_set_ps(temp_points[0].y, 0, 0, 0);
584 break;
585 case 2:
586 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, 0, 0);
587 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, 0, 0);
588 break;
589 case 3:
590 __pointx = _mm_set_ps(temp_points[0].x, temp_points[1].x, temp_points[2].x, 0);
591 __pointy = _mm_set_ps(temp_points[0].y, temp_points[1].y, temp_points[2].y, 0);
592 break;
596 #ifdef _VSMOD
597 __m128 __pointz = _mm_set_ps1(m_style.get().mod_z);
599 // distort
600 if(is_dist) {
601 //P = P0 + (P1 - P0)u + (P3 - P0)v + (P0 + P2 - P1 - P3)uv
602 __m128 __u = _mm_sub_ps(__pointx, __minx);
603 __m128 __v = _mm_sub_ps(__pointy, __miny);
604 __m128 __1_xsz = _mm_rcp_ps(__xsz);
605 __m128 __1_ysz = _mm_rcp_ps(__ysz);
606 __u = _mm_mul_ps(__u, __1_xsz);
607 __v = _mm_mul_ps(__v, __1_ysz);
609 // x
610 __pointx = _mm_mul_ps(__dst213x, __u);
611 __pointx = _mm_mul_ps(__pointx, __v);
613 __m128 __tmpx = _mm_mul_ps(__dst3x, __v);
614 __pointx = _mm_add_ps(__pointx, __tmpx);
615 __tmpx = _mm_mul_ps(__dst1x, __u);
616 __pointx = _mm_add_ps(__pointx, __tmpx);
618 __pointx = _mm_mul_ps(__pointx, __xsz);
619 __pointx = _mm_add_ps(__pointx, __minx);
621 // y
622 __pointy = _mm_mul_ps(__dst213y, __u);
623 __pointy = _mm_mul_ps(__pointy, __v);
625 __m128 __tmpy = _mm_mul_ps(__dst3y, __v);
626 __pointy = _mm_add_ps(__pointy, __tmpy);
627 __tmpy = _mm_mul_ps(__dst1y, __u);
628 __pointy = _mm_add_ps(__pointy, __tmpy);
630 __pointy = _mm_mul_ps(__pointy, __ysz);
631 __pointy = _mm_add_ps(__pointy, __miny);
634 // randomize
635 if(xrnd!=0 || yrnd!=0 || zrnd!=0) {
636 __declspec(align(16)) float rx[4], ry[4], rz[4];
637 for(int k=0; k<4; k++) {
638 rx[k] = xrnd > 0 ? (xrnd - rand() % (int)(xrnd * 2 + 1)) : 0;
639 ry[k] = yrnd > 0 ? (yrnd - rand() % (int)(yrnd * 2 + 1)) : 0;
640 rz[k] = zrnd > 0 ? (zrnd - rand() % (int)(zrnd * 2 + 1)) : 0;
642 __m128 __001 = _mm_set_ps1(0.01f);
644 if(xrnd!=0) {
645 __m128 __rx = _mm_load_ps(rx);
646 __rx = _mm_mul_ps(__rx, __001);
647 __pointx = _mm_add_ps(__pointx, __rx);
650 if(yrnd!=0) {
651 __m128 __ry = _mm_load_ps(ry);
652 __ry = _mm_mul_ps(__ry, __001);
653 __pointy = _mm_add_ps(__pointy, __ry);
656 if(zrnd!=0) {
657 __m128 __rz = _mm_load_ps(rz);
658 __rz = _mm_mul_ps(__rz, __001);
659 __pointz = _mm_add_ps(__pointz, __rz);
662 #else
663 __m128 __pointz = _mm_set_ps1(0);
664 #endif
666 // scale and shift
667 __m128 __tmpx;
668 if(m_style.get().fontShiftX!=0) {
669 __tmpx = _mm_mul_ps(__xshift, __pointy);
670 __tmpx = _mm_add_ps(__tmpx, __pointx);
671 } else {
672 __tmpx = __pointx;
674 __tmpx = _mm_mul_ps(__tmpx, __xscale);
675 __tmpx = _mm_sub_ps(__tmpx, __xorg);
677 __m128 __tmpy;
678 if(m_style.get().fontShiftY!=0) {
679 __tmpy = _mm_mul_ps(__yshift, __pointx);
680 __tmpy = _mm_add_ps(__tmpy, __pointy);
681 } else {
682 __tmpy = __pointy;
684 __tmpy = _mm_mul_ps(__tmpy, __yscale);
685 __tmpy = _mm_sub_ps(__tmpy, __yorg);
687 // rotate
688 __m128 __xx = _mm_mul_ps(__tmpx, __caz);
689 __m128 __yy = _mm_mul_ps(__tmpy, __saz);
690 __pointx = _mm_add_ps(__xx, __yy);
691 __xx = _mm_mul_ps(__tmpx, __saz);
692 __yy = _mm_mul_ps(__tmpy, __caz);
693 __pointy = _mm_sub_ps(__yy, __xx);
695 __m128 __zz = _mm_mul_ps(__pointz, __sax);
696 __yy = _mm_mul_ps(__pointy, __cax);
697 __pointy = _mm_add_ps(__yy, __zz);
698 __zz = _mm_mul_ps(__pointz, __cax);
699 __yy = _mm_mul_ps(__pointy, __sax);
700 __pointz = _mm_sub_ps(__zz, __yy);
702 __xx = _mm_mul_ps(__pointx, __cay);
703 __zz = _mm_mul_ps(__pointz, __say);
704 __pointx = _mm_add_ps(__xx, __zz);
705 __xx = _mm_mul_ps(__pointx, __say);
706 __zz = _mm_mul_ps(__pointz, __cay);
707 __pointz = _mm_sub_ps(__xx, __zz);
709 __zz = _mm_set_ps1(-19000);
710 __pointz = _mm_max_ps(__pointz, __zz);
712 __m128 __20000 = _mm_set_ps1(20000);
713 __zz = _mm_add_ps(__pointz, __20000);
714 __zz = _mm_rcp_ps(__zz);
716 __pointx = _mm_mul_ps(__pointx, __20000);
717 __pointx = _mm_mul_ps(__pointx, __zz);
719 __pointy = _mm_mul_ps(__pointy, __20000);
720 __pointy = _mm_mul_ps(__pointy, __zz);
722 __pointx = _mm_add_ps(__pointx, __xorg);
723 __pointy = _mm_add_ps(__pointy, __yorg);
725 __m128 __05 = _mm_set_ps1(0.5);
727 __pointx = _mm_add_ps(__pointx, __05);
728 __pointy = _mm_add_ps(__pointy, __05);
730 if(i == mPathPointsD4) { // last cycle
731 for(int k=0; k<mPathPointsM4; k++) {
732 temp_points[k].x = static_cast<LONG>(__pointx.m128_f32[3-k]);
733 temp_points[k].y = static_cast<LONG>(__pointy.m128_f32[3-k]);
735 } else {
736 for(int k=0; k<4; k++) {
737 temp_points[k].x = static_cast<LONG>(__pointx.m128_f32[3-k]);
738 temp_points[k].y = static_cast<LONG>(__pointy.m128_f32[3-k]);
742 #endif // __ICL
745 bool CWord::CreateOpaqueBox()
747 if(m_pOpaqueBox) return(true);
748 STSStyle style = m_style.get();
749 style.borderStyle = 0;
750 style.outlineWidthX = style.outlineWidthY = 0;
751 style.colors[0] = m_style.get().colors[2];
752 style.alpha[0] = m_style.get().alpha[2];
753 int w = (int)(m_style.get().outlineWidthX + 0.5);
754 int h = (int)(m_style.get().outlineWidthY + 0.5);
755 CStringW str;
756 str.Format(L"m %d %d l %d %d %d %d %d %d",
757 -w, -h,
758 m_width+w, -h,
759 m_width+w, m_ascent+m_descent+h,
760 -w, m_ascent+m_descent+h);
761 m_pOpaqueBox.reset( new CPolygon(FwSTSStyle(style), str, 0, 0, 0, 1.0/8, 1.0/8, 0) );
762 return(!!m_pOpaqueBox);
765 bool CWord::operator==( const CWord& rhs ) const
767 return (this==&rhs) || (
768 m_str == rhs.m_str &&
769 m_fWhiteSpaceChar == rhs.m_fWhiteSpaceChar &&
770 m_fLineBreak == rhs.m_fLineBreak &&
771 m_style == rhs.m_style && //fix me:?
772 m_ktype == rhs.m_ktype &&
773 m_kstart == rhs.m_kstart &&
774 m_kend == rhs.m_kend &&
775 m_width == rhs.m_width &&
776 m_ascent == rhs.m_ascent &&
777 m_descent == rhs.m_descent);
778 //m_pOpaqueBox
782 // CText
784 CText::CText(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend)
785 : CWord(style, str, ktype, kstart, kend)
787 if(m_str == L" ")
789 m_fWhiteSpaceChar = true;
791 SharedPtrTextInfo text_info;
792 TextInfoCacheKey text_info_key;
793 text_info_key.m_str = m_str;
794 text_info_key.m_style = m_style;
795 text_info_key.UpdateHashValue();
796 TextInfoMruCache* text_info_cache = CacheManager::GetTextInfoCache();
797 POSITION pos = text_info_cache->Lookup(text_info_key);
798 if(pos==NULL)
800 TextInfo* tmp=new TextInfo();
801 GetTextInfo(tmp, m_style, m_str);
802 text_info.reset(tmp);
803 text_info_cache->UpdateCache(text_info_key, text_info);
805 else
807 text_info = text_info_cache->GetAt(pos);
808 text_info_cache->UpdateCache( pos );
810 this->m_ascent = text_info->m_ascent;
811 this->m_descent = text_info->m_descent;
812 this->m_width = text_info->m_width;
815 CText::CText( const CText& src ):CWord(src)
817 m_width = src.m_width;
820 SharedPtrCWord CText::Copy()
822 SharedPtrCWord result(new CText(*this));
823 return result;
826 bool CText::Append(const SharedPtrCWord& w)
828 boost::shared_ptr<CText> p = boost::dynamic_pointer_cast<CText>(w);
829 return (p && CWord::Append(w));
832 bool CText::CreatePath(PathData* path_data)
834 FwCMyFont font(m_style);
835 HFONT hOldFont = SelectFont(g_hDC, font.get());
836 int width = 0;
837 if(m_style.get().fontSpacing || (long)GetVersion() < 0)
839 bool bFirstPath = true;
840 for(LPCWSTR s = m_str; *s; s++)
842 CSize extent;
843 if(!GetTextExtentPoint32W(g_hDC, s, 1, &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return(false);}
844 path_data->PartialBeginPath(g_hDC, bFirstPath);
845 bFirstPath = false;
846 TextOutW(g_hDC, 0, 0, s, 1);
847 path_data->PartialEndPath(g_hDC, width, 0);
848 width += extent.cx + (int)m_style.get().fontSpacing;
851 else
853 CSize extent;
854 if(!GetTextExtentPoint32W(g_hDC, m_str, m_str.GetLength(), &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return(false);}
855 path_data->BeginPath(g_hDC);
856 TextOutW(g_hDC, 0, 0, m_str, m_str.GetLength());
857 path_data->EndPath(g_hDC);
859 SelectFont(g_hDC, hOldFont);
860 return(true);
863 void CText::GetTextInfo(TextInfo *output, const FwSTSStyle& style, const CStringW& str )
865 FwCMyFont font(style);
866 output->m_ascent = (int)(style.get().fontScaleY/100*font.get().m_ascent);
867 output->m_descent = (int)(style.get().fontScaleY/100*font.get().m_descent);
869 HFONT hOldFont = SelectFont(g_hDC, font.get());
870 if(style.get().fontSpacing || (long)GetVersion() < 0)
872 bool bFirstPath = true;
873 for(LPCWSTR s = str; *s; s++)
875 CSize extent;
876 if(!GetTextExtentPoint32W(g_hDC, s, 1, &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return;}
877 output->m_width += extent.cx + (int)style.get().fontSpacing;
879 // m_width -= (int)m_style.get().fontSpacing; // TODO: subtract only at the end of the line
881 else
883 CSize extent;
884 if(!GetTextExtentPoint32W(g_hDC, str, wcslen(str), &extent)) {SelectFont(g_hDC, hOldFont); ASSERT(0); return;}
885 output->m_width += extent.cx;
887 output->m_width = (int)(style.get().fontScaleX/100*output->m_width + 4) >> 3;
888 SelectFont(g_hDC, hOldFont);
891 // CPolygon
893 CPolygon::CPolygon(const FwSTSStyle& style, const CStringW& str, int ktype, int kstart, int kend, double scalex, double scaley, int baseline)
894 : CWord(style, str, ktype, kstart, kend)
895 , m_scalex(scalex), m_scaley(scaley), m_baseline(baseline)
897 ParseStr();
900 CPolygon::CPolygon(CPolygon& src) : CWord(src)
902 m_scalex = src.m_scalex;
903 m_scaley = src.m_scaley;
904 m_baseline = src.m_baseline;
905 m_width = src.m_width;
906 m_ascent = src.m_ascent;
907 m_descent = src.m_descent;
908 m_pathTypesOrg.Copy(src.m_pathTypesOrg);
909 m_pathPointsOrg.Copy(src.m_pathPointsOrg);
911 CPolygon::~CPolygon()
915 SharedPtrCWord CPolygon::Copy()
917 SharedPtrCWord result(DNew CPolygon(*this));
918 return result;
921 bool CPolygon::Append(const SharedPtrCWord& w)
923 // TODO
924 return(false);
927 bool CPolygon::Get6BitFixedPoint(CStringW& str, LONG& ret)
929 LPWSTR s = (LPWSTR)(LPCWSTR)str, e = s;
930 ret = wcstod(str, &e) * 64;
931 str.Delete(0,e-s);
932 XY_LOG_INFO(ret);
933 return(e > s);
936 bool CPolygon::GetPOINT(CStringW& str, POINT& ret)
938 return(Get6BitFixedPoint(str, ret.x) && Get6BitFixedPoint(str, ret.y));
941 bool CPolygon::ParseStr()
943 if(m_pathTypesOrg.GetCount() > 0) return(true);
944 CPoint p;
945 int j, lastsplinestart = -1, firstmoveto = -1, lastmoveto = -1;
946 CStringW str = m_str;
947 str.SpanIncluding(L"mnlbspc 0123456789");
948 str.Replace(L"m", L"*m");
949 str.Replace(L"n", L"*n");
950 str.Replace(L"l", L"*l");
951 str.Replace(L"b", L"*b");
952 str.Replace(L"s", L"*s");
953 str.Replace(L"p", L"*p");
954 str.Replace(L"c", L"*c");
955 int k = 0;
956 for(CStringW s = str.Tokenize(L"*", k); !s.IsEmpty(); s = str.Tokenize(L"*", k))
958 WCHAR c = s[0];
959 s.TrimLeft(L"mnlbspc ");
960 switch(c)
962 case 'm':
963 lastmoveto = m_pathTypesOrg.GetCount();
964 if(firstmoveto == -1)
965 firstmoveto = lastmoveto;
966 while(GetPOINT(s, p)) {
967 m_pathTypesOrg.Add(PT_MOVETO);
968 m_pathPointsOrg.Add(p);
970 break;
971 case 'n':
972 while(GetPOINT(s, p)) {
973 m_pathTypesOrg.Add(PT_MOVETONC);
974 m_pathPointsOrg.Add(p);
976 break;
977 case 'l':
978 if (m_pathPointsOrg.GetCount() < 1) {
979 break;
981 while(GetPOINT(s, p)) {
982 m_pathTypesOrg.Add(PT_LINETO);
983 m_pathPointsOrg.Add(p);
985 break;
986 case 'b':
987 j = m_pathTypesOrg.GetCount();
988 if (j < 1) {
989 break;
991 while(GetPOINT(s, p)) {
992 m_pathTypesOrg.Add(PT_BEZIERTO);
993 m_pathPointsOrg.Add(p);
994 j++;
996 j = m_pathTypesOrg.GetCount() - ((m_pathTypesOrg.GetCount()-j)%3);
997 m_pathTypesOrg.SetCount(j);
998 m_pathPointsOrg.SetCount(j);
999 break;
1000 case 's':
1001 if (m_pathPointsOrg.GetCount() < 1) {
1002 break;
1005 j = lastsplinestart = m_pathTypesOrg.GetCount();
1006 int i = 3;
1007 while(i-- && GetPOINT(s, p)) {
1008 m_pathTypesOrg.Add(PT_BSPLINETO);
1009 m_pathPointsOrg.Add(p);
1010 j++;
1012 if(m_pathTypesOrg.GetCount()-lastsplinestart < 3) {
1013 m_pathTypesOrg.SetCount(lastsplinestart);
1014 m_pathPointsOrg.SetCount(lastsplinestart);
1015 lastsplinestart = -1;
1018 // no break here
1019 case 'p':
1020 if (m_pathPointsOrg.GetCount() < 3) {
1021 break;
1023 while(GetPOINT(s, p)) {
1024 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1025 m_pathPointsOrg.Add(p);
1027 break;
1028 case 'c':
1029 if(lastsplinestart > 0)
1031 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1032 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1033 m_pathTypesOrg.Add(PT_BSPLINEPATCHTO);
1034 p = m_pathPointsOrg[lastsplinestart-1]; // we need p for temp storage, because operator [] will return a reference to CPoint and Add() may reallocate its internal buffer (this is true for MFC 7.0 but not for 6.0, hehe)
1035 m_pathPointsOrg.Add(p);
1036 p = m_pathPointsOrg[lastsplinestart];
1037 m_pathPointsOrg.Add(p);
1038 p = m_pathPointsOrg[lastsplinestart+1];
1039 m_pathPointsOrg.Add(p);
1040 lastsplinestart = -1;
1042 break;
1043 default:
1044 break;
1047 if(lastmoveto == -1 || firstmoveto > 0)
1049 m_pathTypesOrg.RemoveAll();
1050 m_pathPointsOrg.RemoveAll();
1051 return(false);
1053 int minx = INT_MAX, miny = INT_MAX, maxx = -INT_MAX, maxy = -INT_MAX;
1054 for(size_t i = 0; i < m_pathTypesOrg.GetCount(); i++)
1056 m_pathPointsOrg[i].x = (int)(m_scalex * m_pathPointsOrg[i].x);
1057 m_pathPointsOrg[i].y = (int)(m_scaley * m_pathPointsOrg[i].y);
1058 if(minx > m_pathPointsOrg[i].x) minx = m_pathPointsOrg[i].x;
1059 if(miny > m_pathPointsOrg[i].y) miny = m_pathPointsOrg[i].y;
1060 if(maxx < m_pathPointsOrg[i].x) maxx = m_pathPointsOrg[i].x;
1061 if(maxy < m_pathPointsOrg[i].y) maxy = m_pathPointsOrg[i].y;
1063 m_width = max(maxx - minx, 0);
1064 m_ascent = max(maxy - miny, 0);
1065 int baseline = (int)(64 * m_scaley * m_baseline);
1066 m_descent = baseline;
1067 m_ascent -= baseline;
1068 m_width = ((int)(m_style.get().fontScaleX/100 * m_width) + 4) >> 3;
1069 m_ascent = ((int)(m_style.get().fontScaleY/100 * m_ascent) + 4) >> 3;
1070 m_descent = ((int)(m_style.get().fontScaleY/100 * m_descent) + 4) >> 3;
1071 return(true);
1074 bool CPolygon::CreatePath(PathData* path_data)
1076 int len = m_pathTypesOrg.GetCount();
1077 if(len == 0) return(false);
1078 if(path_data->mPathPoints != len)
1080 path_data->mpPathTypes = (BYTE*)realloc(path_data->mpPathTypes, len*sizeof(BYTE));
1081 path_data->mpPathPoints = (POINT*)realloc(path_data->mpPathPoints, len*sizeof(POINT));
1082 if(!path_data->mpPathTypes || !path_data->mpPathPoints) return(false);
1083 path_data->mPathPoints = len;
1085 memcpy(path_data->mpPathTypes, m_pathTypesOrg.GetData(), len*sizeof(BYTE));
1086 memcpy(path_data->mpPathPoints, m_pathPointsOrg.GetData(), len*sizeof(POINT));
1087 return(true);
1090 // CClipper
1092 CClipper::CClipper(CStringW str, CSize size, double scalex, double scaley, bool inverse)
1093 : m_polygon( new CPolygon(FwSTSStyle(), str, 0, 0, 0, scalex, scaley, 0) )
1094 , m_size(size), m_inverse(inverse)
1095 , m_effectType(-1), m_painted(false)
1100 CClipper::~CClipper()
1104 GrayImage2* CClipper::PaintSimpleClipper()
1106 GrayImage2* result = NULL;
1107 if(m_size.cx < 0 || m_size.cy < 0)
1108 return result;
1110 SharedPtrOverlay overlay;
1111 CWordPaintMachine::PaintBody( m_polygon, CPoint(0, 0), CPoint(0, 0), &overlay );
1112 int w = overlay->mOverlayWidth, h = overlay->mOverlayHeight;
1113 int x = (overlay->mOffsetX+4)>>3, y = (overlay->mOffsetY+4)>>3;
1114 result = new GrayImage2();
1115 if( !result )
1116 return result;
1117 result->data = overlay->mBody;
1118 result->pitch = overlay->mOverlayPitch;
1119 result->size.SetSize(w, h);
1120 result->left_top.SetPoint(x, y);
1121 return result;
1124 GrayImage2* CClipper::PaintBaseClipper()
1126 GrayImage2* result = NULL;
1127 //m_pAlphaMask = NULL;
1128 if(m_size.cx < 0 || m_size.cy < 0)
1129 return result;
1131 SharedPtrOverlay overlay;
1132 CWordPaintMachine::PaintBody( m_polygon, CPoint(0, 0), CPoint(0, 0), &overlay );
1133 int w = overlay->mOverlayWidth, h = overlay->mOverlayHeight;
1134 int x = (overlay->mOffsetX+4)>>3, y = (overlay->mOffsetY+4)>>3;
1135 int xo = 0, yo = 0;
1136 if(x < 0) {xo = -x; w -= -x; x = 0;}
1137 if(y < 0) {yo = -y; h -= -y; y = 0;}
1138 if(x+w > m_size.cx) w = m_size.cx-x;
1139 if(y+h > m_size.cy) h = m_size.cy-y;
1140 if(w <= 0 || h <= 0) return result;
1142 result = new GrayImage2();
1143 if( !result )
1144 return result;
1145 result->data.reset( reinterpret_cast<BYTE*>(xy_malloc(m_size.cx*m_size.cy)), xy_free );
1146 result->pitch = m_size.cx;
1147 result->size = m_size;
1148 result->left_top.SetPoint(0, 0);
1150 BYTE * result_data = result->data.get();
1151 if(!result_data)
1153 delete result;
1154 return NULL;
1157 memset( result_data, 0, m_size.cx*m_size.cy );
1159 const BYTE* src = overlay->mBody.get() + (overlay->mOverlayPitch * yo + xo);
1160 BYTE* dst = result_data + m_size.cx * y + x;
1161 while(h--)
1163 //for(int wt=0; wt<w; ++wt)
1164 // dst[wt] = src[wt];
1165 memcpy(dst, src, w);
1166 src += overlay->mOverlayPitch;
1167 dst += m_size.cx;
1169 if(m_inverse)
1171 BYTE* dst = result_data;
1172 for(int i = m_size.cx*m_size.cy; i>0; --i, ++dst)
1173 *dst = 0x40 - *dst; // mask is 6 bit
1175 return result;
1178 GrayImage2* CClipper::PaintBannerClipper()
1180 int width = m_effect.param[2];
1181 int w = m_size.cx, h = m_size.cy;
1183 GrayImage2* result = PaintBaseClipper();
1184 if(!result)
1185 return result;
1187 int da = (64<<8)/width;
1188 BYTE* am = result->data.get();
1189 for(int j = 0; j < h; j++, am += w)
1191 int a = 0;
1192 int k = min(width, w);
1193 for(int i = 0; i < k; i++, a += da)
1194 am[i] = (am[i]*a)>>14;
1195 a = 0x40<<8;
1196 k = w-width;
1197 if(k < 0) {a -= -k*da; k = 0;}
1198 for(int i = k; i < w; i++, a -= da)
1199 am[i] = (am[i]*a)>>14;
1201 return result;
1204 GrayImage2* CClipper::PaintScrollClipper()
1206 int height = m_effect.param[4];
1207 int w = m_size.cx, h = m_size.cy;
1209 GrayImage2* result = PaintBaseClipper();
1210 if(!result)
1211 return result;
1213 BYTE* data = result->data.get();
1215 int da = (64<<8)/height;
1216 int a = 0;
1217 int k = m_effect.param[0]>>3;
1218 int l = k+height;
1219 if(k < 0) {a += -k*da; k = 0;}
1220 if(l > h) {l = h;}
1221 if(k < h)
1223 BYTE* am = &data[k*w];
1224 memset(data, 0, am - data);
1225 for(int j = k; j < l; j++, a += da)
1227 for(int i = 0; i < w; i++, am++)
1228 *am = ((*am)*a)>>14;
1231 da = -(64<<8)/height;
1232 a = 0x40<<8;
1233 l = m_effect.param[1]>>3;
1234 k = l-height;
1235 if(k < 0) {a += -k*da; k = 0;}
1236 if(l > h) {l = h;}
1237 if(k < h)
1239 BYTE* am = &data[k*w];
1240 int j = k;
1241 for(; j < l; j++, a += da)
1243 for(int i = 0; i < w; i++, am++)
1244 *am = ((*am)*a)>>14;
1246 memset(am, 0, (h-j)*w);
1248 return result;
1251 GrayImage2* CClipper::Paint()
1253 GrayImage2* result = NULL;
1254 switch(m_effectType)
1256 case -1:
1257 if (!m_inverse)
1259 result = PaintSimpleClipper();
1261 else
1263 result = PaintBaseClipper();
1265 break;
1266 case EF_BANNER:
1267 result = PaintBannerClipper();
1268 break;
1269 case EF_SCROLL:
1270 result = PaintScrollClipper();
1271 break;
1273 return result;
1276 void CClipper::SetEffect( const Effect& effect, int effectType )
1278 m_effectType = effectType;
1279 m_effect = effect;
1282 SharedPtrGrayImage2 CClipper::GetAlphaMask( const SharedPtrCClipper& clipper )
1284 SharedPtrGrayImage2 result;
1285 CClipperPaintMachine paint_machine(clipper);
1286 paint_machine.Paint(&result);
1287 return result;
1290 // CLine
1292 CLine::~CLine()
1294 //POSITION pos = GetHeadPosition();
1295 //while(pos) delete GetNext(pos);
1298 void CLine::Compact()
1300 POSITION pos = GetHeadPosition();
1301 while(pos)
1303 SharedPtrCWord w = GetNext(pos);
1304 if(!w->m_fWhiteSpaceChar) break;
1305 m_width -= w->m_width;
1306 // delete w;
1307 RemoveHead();
1309 pos = GetTailPosition();
1310 while(pos)
1312 SharedPtrCWord w = GetPrev(pos);
1313 if(!w->m_fWhiteSpaceChar) break;
1314 m_width -= w->m_width;
1315 // delete w;
1316 RemoveTail();
1318 if(IsEmpty()) return;
1319 CLine l;
1320 l.AddTailList(this);
1321 RemoveAll();
1322 SharedPtrCWord last;
1323 pos = l.GetHeadPosition();
1324 while(pos)
1326 SharedPtrCWord w = l.GetNext(pos);
1327 if(!last || !last->Append(w))
1328 AddTail(last = w->Copy());
1330 m_ascent = m_descent = m_borderX = m_borderY = 0;
1331 pos = GetHeadPosition();
1332 while(pos)
1334 SharedPtrCWord w = GetNext(pos);
1335 if(m_ascent < w->m_ascent) m_ascent = w->m_ascent;
1336 if(m_descent < w->m_descent) m_descent = w->m_descent;
1337 if(m_borderX < w->m_style.get().outlineWidthX) m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1338 if(m_borderY < w->m_style.get().outlineWidthY) m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1342 CRect CLine::PaintAll( CompositeDrawItemList* output, const CRect& clipRect,
1343 const SharedPtrCClipperPaintMachine &clipper, CPoint p, const CPoint& org, const int time, const int alpha )
1345 CRect bbox(0, 0, 0, 0);
1346 POSITION pos = GetHeadPosition();
1347 POSITION outputPos = output->GetHeadPosition();
1348 while(pos)
1350 SharedPtrCWord w = GetNext(pos);
1351 CompositeDrawItem& outputItem = output->GetNext(outputPos);
1352 if(w->m_fLineBreak) return(bbox); // should not happen since this class is just a line of text without any breaks
1353 CPoint shadowPos, outlinePos, bodyPos, transOrg;
1354 shadowPos.x = p.x + static_cast<int>(w->m_style.get().shadowDepthX+0.5);
1355 shadowPos.y = p.y + m_ascent - w->m_ascent + static_cast<int>(w->m_style.get().shadowDepthY+0.5);
1356 outlinePos = CPoint(p.x, p.y + m_ascent - w->m_ascent);
1357 bodyPos = CPoint(p.x, p.y + m_ascent - w->m_ascent);
1358 bool hasShadow = w->m_style.get().shadowDepthX != 0 || w->m_style.get().shadowDepthY != 0;
1359 bool hasOutline = w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0 && !(w->m_ktype == 2 && time < w->m_kstart);
1360 bool hasBody = true;
1362 SharedPtrOverlayPaintMachine shadow_pm, outline_pm, body_pm;
1363 CWordPaintMachine::CreatePaintMachines(w, shadowPos, outlinePos, bodyPos, org,
1364 hasShadow ? &shadow_pm : NULL,
1365 hasOutline ? &outline_pm : NULL,
1366 hasBody ? &body_pm : NULL);
1368 //shadow
1369 if(hasShadow)
1371 DWORD a = 0xff - w->m_style.get().alpha[3];
1372 if(alpha > 0) a = MulDiv(a, 0xff - alpha, 0xff);
1373 COLORREF shadow = revcolor(w->m_style.get().colors[3]) | (a<<24);
1374 DWORD sw[6] = {shadow, -1};
1375 sw[0] = XySubRenderFrameCreater::GetDefaultCreater()->TransColor(sw[0]);
1376 if(w->m_style.get().borderStyle == 0)
1378 outputItem.shadow.reset(
1379 DrawItem::CreateDrawItem(shadow_pm, clipRect, clipper, shadowPos.x, shadowPos.y, sw,
1380 w->m_ktype > 0 || w->m_style.get().alpha[0] < 0xff,
1381 (w->m_style.get().outlineWidthX+w->m_style.get().outlineWidthY > 0) && !(w->m_ktype == 2 && time < w->m_kstart))
1384 else if(w->m_style.get().borderStyle == 1)
1386 outputItem.shadow.reset(
1387 DrawItem::CreateDrawItem( shadow_pm, clipRect, clipper, shadowPos.x, shadowPos.y, sw, true, false)
1391 //outline
1392 if(hasOutline)
1394 DWORD aoutline = w->m_style.get().alpha[2];
1395 if(alpha > 0) aoutline += MulDiv(alpha, 0xff - w->m_style.get().alpha[2], 0xff);
1396 COLORREF outline = revcolor(w->m_style.get().colors[2]) | ((0xff-aoutline)<<24);
1397 DWORD sw[6] = {outline, -1};
1398 sw[0] = XySubRenderFrameCreater::GetDefaultCreater()->TransColor(sw[0]);
1399 if(w->m_style.get().borderStyle == 0)
1401 outputItem.outline.reset(
1402 DrawItem::CreateDrawItem(outline_pm, clipRect, clipper, outlinePos.x, outlinePos.y, sw, !w->m_style.get().alpha[0] && !w->m_style.get().alpha[1] && !alpha, true)
1405 else if(w->m_style.get().borderStyle == 1)
1407 outputItem.outline.reset(
1408 DrawItem::CreateDrawItem(outline_pm, clipRect, clipper, outlinePos.x, outlinePos.y, sw, true, false)
1412 //body
1413 if(hasBody)
1415 // colors
1416 DWORD aprimary = w->m_style.get().alpha[0];
1417 if(alpha > 0) aprimary += MulDiv(alpha, 0xff - w->m_style.get().alpha[0], 0xff);
1418 COLORREF primary = revcolor(w->m_style.get().colors[0]) | ((0xff-aprimary)<<24);
1419 DWORD asecondary = w->m_style.get().alpha[1];
1420 if(alpha > 0) asecondary += MulDiv(alpha, 0xff - w->m_style.get().alpha[1], 0xff);
1421 COLORREF secondary = revcolor(w->m_style.get().colors[1]) | ((0xff-asecondary)<<24);
1422 DWORD sw[6] = {primary, 0, secondary};
1423 // karaoke
1424 double t;
1425 if(w->m_ktype == 0 || w->m_ktype == 2)
1427 t = time < w->m_kstart ? 0 : 1;
1429 else if(w->m_ktype == 1)
1431 if(time < w->m_kstart) t = 0;
1432 else if(time < w->m_kend)
1434 t = 1.0 * (time - w->m_kstart) / (w->m_kend - w->m_kstart);
1435 double angle = fmod(w->m_style.get().fontAngleZ, 360.0);
1436 if(angle > 90 && angle < 270)
1438 t = 1-t;
1439 COLORREF tmp = sw[0];
1440 sw[0] = sw[2];
1441 sw[2] = tmp;
1444 else t = 1.0;
1446 if(t >= 1)
1448 sw[1] = 0xffffffff;
1450 sw[3] = (int)(w->m_style.get().outlineWidthX + t*w->m_width) >> 3;
1451 sw[4] = sw[2];
1452 sw[5] = 0x00ffffff;
1453 sw[0] = XySubRenderFrameCreater::GetDefaultCreater()->TransColor(sw[0]);
1454 sw[2] = XySubRenderFrameCreater::GetDefaultCreater()->TransColor(sw[2]);
1455 sw[4] = XySubRenderFrameCreater::GetDefaultCreater()->TransColor(sw[4]);
1456 outputItem.body.reset(
1457 DrawItem::CreateDrawItem(body_pm, clipRect, clipper, bodyPos.x, bodyPos.y, sw, true, false)
1460 bbox |= CompositeDrawItem::GetDirtyRect(outputItem);
1461 p.x += w->m_width;
1463 return(bbox);
1466 void CLine::AddWord2Tail( SharedPtrCWord words )
1468 __super::AddTail(words);
1471 bool CLine::IsEmpty()
1473 return __super::IsEmpty();
1476 int CLine::GetWordCount()
1478 return GetCount();
1481 // CSubtitle
1483 CSubtitle::CSubtitle()
1485 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1486 m_clipInverse = false;
1487 m_scalex = m_scaley = 1;
1488 m_fAnimated2 = false;
1491 CSubtitle::~CSubtitle()
1493 Empty();
1496 void CSubtitle::Empty()
1498 POSITION pos = GetHeadPosition();
1499 while(pos) delete GetNext(pos);
1500 // pos = m_words.GetHeadPosition();
1501 // while(pos) delete m_words.GetNext(pos);
1502 for(int i = 0; i < EF_NUMBEROFEFFECTS; i++) {if(m_effects[i]) delete m_effects[i];}
1503 memset(m_effects, 0, sizeof(Effect*)*EF_NUMBEROFEFFECTS);
1506 int CSubtitle::GetFullWidth()
1508 int width = 0;
1509 POSITION pos = m_words.GetHeadPosition();
1510 while(pos) width += m_words.GetNext(pos)->m_width;
1511 return(width);
1514 int CSubtitle::GetFullLineWidth(POSITION pos)
1516 int width = 0;
1517 while(pos)
1519 SharedPtrCWord w = m_words.GetNext(pos);
1520 if(w->m_fLineBreak) break;
1521 width += w->m_width;
1523 return(width);
1526 int CSubtitle::GetWrapWidth(POSITION pos, int maxwidth)
1528 if(m_wrapStyle == 0 || m_wrapStyle == 3)
1530 if(maxwidth > 0)
1532 // int fullwidth = GetFullWidth();
1533 int fullwidth = GetFullLineWidth(pos);
1534 int minwidth = fullwidth / ((abs(fullwidth) / maxwidth) + 1);
1535 int width = 0, wordwidth = 0;
1536 while(pos && width < minwidth)
1538 SharedPtrCWord w = m_words.GetNext(pos);
1539 wordwidth = w->m_width;
1540 if(abs(width + wordwidth) < abs(maxwidth)) width += wordwidth;
1542 maxwidth = width;
1543 if(m_wrapStyle == 3 && pos) maxwidth -= wordwidth;
1546 else if(m_wrapStyle == 1)
1548 // maxwidth = maxwidth;
1550 else if(m_wrapStyle == 2)
1552 maxwidth = INT_MAX;
1554 return(maxwidth);
1557 CLine* CSubtitle::GetNextLine(POSITION& pos, int maxwidth)
1559 if(pos == NULL) return(NULL);
1560 CLine* ret = new CLine();
1561 if(!ret) return(NULL);
1562 ret->m_width = ret->m_ascent = ret->m_descent = ret->m_borderX = ret->m_borderY = 0;
1563 maxwidth = GetWrapWidth(pos, maxwidth);
1564 bool fEmptyLine = true;
1565 while(pos)
1567 SharedPtrCWord w = m_words.GetNext(pos);
1568 if(ret->m_ascent < w->m_ascent) ret->m_ascent = w->m_ascent;
1569 if(ret->m_descent < w->m_descent) ret->m_descent = w->m_descent;
1570 if(ret->m_borderX < w->m_style.get().outlineWidthX) ret->m_borderX = (int)(w->m_style.get().outlineWidthX+0.5);
1571 if(ret->m_borderY < w->m_style.get().outlineWidthY) ret->m_borderY = (int)(w->m_style.get().outlineWidthY+0.5);
1572 if(w->m_fLineBreak)
1574 if(fEmptyLine) {ret->m_ascent /= 2; ret->m_descent /= 2; ret->m_borderX = ret->m_borderY = 0;}
1575 ret->Compact();
1576 return(ret);
1578 fEmptyLine = false;
1579 bool fWSC = w->m_fWhiteSpaceChar;
1580 int width = w->m_width;
1581 POSITION pos2 = pos;
1582 while(pos2)
1584 if(m_words.GetAt(pos2)->m_fWhiteSpaceChar != fWSC
1585 || m_words.GetAt(pos2)->m_fLineBreak) break;
1586 SharedPtrCWord w2 = m_words.GetNext(pos2);
1587 width += w2->m_width;
1589 if((ret->m_width += width) <= maxwidth || ret->IsEmpty())
1591 ret->AddWord2Tail(w);
1592 while(pos != pos2)
1594 ret->AddWord2Tail(m_words.GetNext(pos));
1596 pos = pos2;
1598 else
1600 if(pos) m_words.GetPrev(pos);
1601 else pos = m_words.GetTailPosition();
1602 ret->m_width -= width;
1603 break;
1606 ret->Compact();
1607 return(ret);
1610 void CSubtitle::CreateClippers(CSize size)
1612 size.cx >>= 3;
1613 size.cy >>= 3;
1614 if(m_effects[EF_BANNER] && m_effects[EF_BANNER]->param[2])
1616 int w = size.cx, h = size.cy;
1617 if(!m_pClipper)
1619 CStringW str;
1620 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1621 m_pClipper.reset( new CClipper(str, size, 1, 1, false) );
1622 if(!m_pClipper) return;
1624 m_pClipper->SetEffect( *m_effects[EF_BANNER], EF_BANNER );
1626 else if(m_effects[EF_SCROLL] && m_effects[EF_SCROLL]->param[4])
1628 int height = m_effects[EF_SCROLL]->param[4];
1629 int w = size.cx, h = size.cy;
1630 if(!m_pClipper)
1632 CStringW str;
1633 str.Format(L"m %d %d l %d %d %d %d %d %d", 0, 0, w, 0, w, h, 0, h);
1634 m_pClipper.reset( new CClipper(str, size, 1, 1, false) );
1635 if(!m_pClipper) return;
1637 m_pClipper->SetEffect(*m_effects[EF_SCROLL], EF_SCROLL);
1641 void CSubtitle::MakeLines(CSize size, CRect marginRect)
1643 CSize spaceNeeded(0, 0);
1644 bool fFirstLine = true;
1645 m_topborder = m_bottomborder = 0;
1646 CLine* l = NULL;
1647 POSITION pos = m_words.GetHeadPosition();
1648 while(pos)
1650 l = GetNextLine(pos, size.cx - marginRect.left - marginRect.right);
1651 if(!l) break;
1652 if(fFirstLine) {m_topborder = l->m_borderY; fFirstLine = false;}
1653 spaceNeeded.cx = max(l->m_width+l->m_borderX, spaceNeeded.cx);
1654 spaceNeeded.cy += l->m_ascent + l->m_descent;
1655 AddTail(l);
1657 if(l) m_bottomborder = l->m_borderY;
1658 m_rect = CRect(
1659 CPoint((m_scrAlignment%3) == 1 ? marginRect.left
1660 : (m_scrAlignment%3) == 2 ? (marginRect.left + (size.cx - marginRect.right) - spaceNeeded.cx + 1) / 2
1661 : (size.cx - marginRect.right - spaceNeeded.cx),
1662 m_scrAlignment <= 3 ? (size.cy - marginRect.bottom - spaceNeeded.cy)
1663 : m_scrAlignment <= 6 ? (marginRect.top + (size.cy - marginRect.bottom) - spaceNeeded.cy + 1) / 2
1664 : marginRect.top),
1665 spaceNeeded);
1668 POSITION CSubtitle::GetHeadLinePosition()
1670 return __super::GetHeadPosition();
1673 CLine* CSubtitle::GetNextLine( POSITION& pos )
1675 return __super::GetNext(pos);
1678 // CScreenLayoutAllocator
1680 void CScreenLayoutAllocator::Empty()
1682 m_subrects.RemoveAll();
1685 void CScreenLayoutAllocator::AdvanceToSegment(int segment, const CAtlArray<int>& sa)
1687 POSITION pos = m_subrects.GetHeadPosition();
1688 while(pos)
1690 POSITION prev = pos;
1691 SubRect& sr = m_subrects.GetNext(pos);
1692 bool fFound = false;
1693 if(abs(sr.segment - segment) <= 1) // using abs() makes it possible to play the subs backwards, too :)
1695 for(size_t i = 0; i < sa.GetCount() && !fFound; i++)
1697 if(sa[i] == sr.entry)
1699 sr.segment = segment;
1700 fFound = true;
1704 if(!fFound) m_subrects.RemoveAt(prev);
1708 CRect CScreenLayoutAllocator::AllocRect(CSubtitle* s, int segment, int entry, int layer, int collisions)
1710 // TODO: handle collisions == 1 (reversed collisions)
1711 POSITION pos = m_subrects.GetHeadPosition();
1712 while(pos)
1714 SubRect& sr = m_subrects.GetNext(pos);
1715 if(sr.segment == segment && sr.entry == entry)
1717 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1720 CRect r = s->m_rect + CRect(0, s->m_topborder, 0, s->m_bottomborder);
1721 bool fSearchDown = s->m_scrAlignment > 3;
1722 bool fOK;
1725 fOK = true;
1726 pos = m_subrects.GetHeadPosition();
1727 while(pos)
1729 SubRect& sr = m_subrects.GetNext(pos);
1730 if(layer == sr.layer && !(r & sr.r).IsRectEmpty())
1732 if(fSearchDown)
1734 r.bottom = sr.r.bottom + r.Height();
1735 r.top = sr.r.bottom;
1737 else
1739 r.top = sr.r.top - r.Height();
1740 r.bottom = sr.r.top;
1742 fOK = false;
1746 while(!fOK);
1747 SubRect sr;
1748 sr.r = r;
1749 sr.segment = segment;
1750 sr.entry = entry;
1751 sr.layer = layer;
1752 m_subrects.AddTail(sr);
1753 return(sr.r + CRect(0, -s->m_topborder, 0, -s->m_bottomborder));
1756 // CRenderedTextSubtitle
1758 CAtlMap<CStringW, CRenderedTextSubtitle::AssCmdType, CStringElementTraits<CStringW>> CRenderedTextSubtitle::m_cmdMap;
1760 CRenderedTextSubtitle::CRenderedTextSubtitle(CCritSec* pLock)
1761 : CSubPicProviderImpl(pLock)
1763 if( m_cmdMap.IsEmpty() )
1765 InitCmdMap();
1767 m_size = CSize(0, 0);
1768 if(g_hDC_refcnt == 0)
1770 g_hDC = CreateCompatibleDC(NULL);
1771 SetBkMode(g_hDC, TRANSPARENT);
1772 SetTextColor(g_hDC, 0xffffff);
1773 SetMapMode(g_hDC, MM_TEXT);
1775 g_hDC_refcnt++;
1778 CRenderedTextSubtitle::~CRenderedTextSubtitle()
1780 Deinit();
1781 g_hDC_refcnt--;
1782 if(g_hDC_refcnt == 0) DeleteDC(g_hDC);
1785 void CRenderedTextSubtitle::InitCmdMap()
1787 if( m_cmdMap.IsEmpty() )
1789 m_cmdMap.SetAt(L"1c", CMD_1c);
1790 m_cmdMap.SetAt(L"2c", CMD_2c);
1791 m_cmdMap.SetAt(L"3c", CMD_3c);
1792 m_cmdMap.SetAt(L"4c", CMD_4c);
1793 m_cmdMap.SetAt(L"1a", CMD_1a);
1794 m_cmdMap.SetAt(L"2a", CMD_2a);
1795 m_cmdMap.SetAt(L"3a", CMD_3a);
1796 m_cmdMap.SetAt(L"4a", CMD_4a);
1797 m_cmdMap.SetAt(L"alpha", CMD_alpha);
1798 m_cmdMap.SetAt(L"an", CMD_an);
1799 m_cmdMap.SetAt(L"a", CMD_a);
1800 m_cmdMap.SetAt(L"blur", CMD_blur);
1801 m_cmdMap.SetAt(L"bord", CMD_bord);
1802 m_cmdMap.SetAt(L"be", CMD_be);
1803 m_cmdMap.SetAt(L"b", CMD_b);
1804 m_cmdMap.SetAt(L"clip", CMD_clip);
1805 m_cmdMap.SetAt(L"iclip", CMD_iclip);
1806 m_cmdMap.SetAt(L"c", CMD_c);
1807 m_cmdMap.SetAt(L"fade", CMD_fade);
1808 m_cmdMap.SetAt(L"fad", CMD_fad);
1809 m_cmdMap.SetAt(L"fax", CMD_fax);
1810 m_cmdMap.SetAt(L"fay", CMD_fay);
1811 m_cmdMap.SetAt(L"fe", CMD_fe);
1812 m_cmdMap.SetAt(L"fn", CMD_fn);
1813 m_cmdMap.SetAt(L"frx", CMD_frx);
1814 m_cmdMap.SetAt(L"fry", CMD_fry);
1815 m_cmdMap.SetAt(L"frz", CMD_frz);
1816 m_cmdMap.SetAt(L"fr", CMD_fr);
1817 m_cmdMap.SetAt(L"fscx", CMD_fscx);
1818 m_cmdMap.SetAt(L"fscy", CMD_fscy);
1819 m_cmdMap.SetAt(L"fsc", CMD_fsc);
1820 m_cmdMap.SetAt(L"fsp", CMD_fsp);
1821 m_cmdMap.SetAt(L"fs", CMD_fs);
1822 m_cmdMap.SetAt(L"i", CMD_i);
1823 m_cmdMap.SetAt(L"kt", CMD_kt);
1824 m_cmdMap.SetAt(L"kf", CMD_kf);
1825 m_cmdMap.SetAt(L"K", CMD_K);
1826 m_cmdMap.SetAt(L"ko", CMD_ko);
1827 m_cmdMap.SetAt(L"k", CMD_k);
1828 m_cmdMap.SetAt(L"move", CMD_move);
1829 m_cmdMap.SetAt(L"org", CMD_org);
1830 m_cmdMap.SetAt(L"pbo", CMD_pbo);
1831 m_cmdMap.SetAt(L"pos", CMD_pos);
1832 m_cmdMap.SetAt(L"p", CMD_p);
1833 m_cmdMap.SetAt(L"q", CMD_q);
1834 m_cmdMap.SetAt(L"r", CMD_r);
1835 m_cmdMap.SetAt(L"shad", CMD_shad);
1836 m_cmdMap.SetAt(L"s", CMD_s);
1837 m_cmdMap.SetAt(L"t", CMD_t);
1838 m_cmdMap.SetAt(L"u", CMD_u);
1839 m_cmdMap.SetAt(L"xbord", CMD_xbord);
1840 m_cmdMap.SetAt(L"xshad", CMD_xshad);
1841 m_cmdMap.SetAt(L"ybord", CMD_ybord);
1842 m_cmdMap.SetAt(L"yshad", CMD_yshad);
1846 void CRenderedTextSubtitle::Copy(CSimpleTextSubtitle& sts)
1848 __super::Copy(sts);
1849 m_size = CSize(0, 0);
1850 if(CRenderedTextSubtitle* pRTS = dynamic_cast<CRenderedTextSubtitle*>(&sts))
1852 m_size = pRTS->m_size;
1856 void CRenderedTextSubtitle::Empty()
1858 Deinit();
1859 __super::Empty();
1862 void CRenderedTextSubtitle::OnChanged()
1864 __super::OnChanged();
1865 POSITION pos = m_subtitleCache.GetStartPosition();
1866 while(pos)
1868 int i;
1869 CSubtitle* s;
1870 m_subtitleCache.GetNextAssoc(pos, i, s);
1871 delete s;
1873 m_subtitleCache.RemoveAll();
1874 m_sla.Empty();
1877 bool CRenderedTextSubtitle::Init(CSize size, CRect vidrect)
1879 Deinit();
1880 m_size = CSize(size.cx*8, size.cy*8);
1881 m_vidrect = CRect(vidrect.left*8, vidrect.top*8, vidrect.right*8, vidrect.bottom*8);
1882 m_sla.Empty();
1883 return(true);
1886 void CRenderedTextSubtitle::Deinit()
1888 POSITION pos = m_subtitleCache.GetStartPosition();
1889 while(pos)
1891 int i;
1892 CSubtitle* s;
1893 m_subtitleCache.GetNextAssoc(pos, i, s);
1894 delete s;
1896 m_subtitleCache.RemoveAll();
1897 m_sla.Empty();
1898 m_size = CSize(0, 0);
1899 m_vidrect.SetRectEmpty();
1901 CacheManager::GetPathDataMruCache()->RemoveAll();
1902 CacheManager::GetScanLineData2MruCache()->RemoveAll();
1903 CacheManager::GetOverlayNoBlurMruCache()->RemoveAll();
1904 CacheManager::GetOverlayMruCache()->RemoveAll();
1905 CacheManager::GetAssTagListMruCache()->RemoveAll();
1906 CacheManager::GetSubpixelVarianceCache()->RemoveAll();
1907 CacheManager::GetTextInfoCache()->RemoveAll();
1910 void CRenderedTextSubtitle::ParseEffect(CSubtitle* sub, const CStringW& str)
1912 CStringW::PCXSTR str_start = str.GetString();
1913 CStringW::PCXSTR str_end = str_start + str.GetLength();
1914 str_start = SkipWhiteSpaceLeft(str_start, str_end);
1916 if(!sub || *str_start==0)
1917 return;
1919 str_end = FastSkipWhiteSpaceRight(str_start, str_end);
1921 const WCHAR* s = FindChar(str_start, str_end, L';');
1922 if(*s==L';') {
1923 s++;
1926 const CStringW effect(str_start, s-str_start);
1927 if(!effect.CompareNoCase( L"Banner;" ) )
1929 int delay, lefttoright = 0, fadeawaywidth = 0;
1930 if(swscanf(s, L"%d;%d;%d", &delay, &lefttoright, &fadeawaywidth) < 1) return;
1931 Effect* e = new Effect;
1932 if(!e) return;
1933 sub->m_effects[e->type = EF_BANNER] = e;
1934 e->param[0] = (int)(max(1.0*delay/sub->m_scalex, 1));
1935 e->param[1] = lefttoright;
1936 e->param[2] = (int)(sub->m_scalex*fadeawaywidth);
1937 sub->m_wrapStyle = 2;
1939 else if(!effect.CompareNoCase(L"Scroll up;") || !effect.CompareNoCase(L"Scroll down;"))
1941 int top, bottom, delay, fadeawayheight = 0;
1942 if(swscanf(s, L"%d;%d;%d;%d", &top, &bottom, &delay, &fadeawayheight) < 3) return;
1943 if(top > bottom) {int tmp = top; top = bottom; bottom = tmp;}
1944 Effect* e = new Effect;
1945 if(!e) return;
1946 sub->m_effects[e->type = EF_SCROLL] = e;
1947 e->param[0] = (int)(sub->m_scaley*top*8);
1948 e->param[1] = (int)(sub->m_scaley*bottom*8);
1949 e->param[2] = (int)(max(1.0*delay/sub->m_scaley, 1));
1950 e->param[3] = (effect.GetLength() == 12);
1951 e->param[4] = (int)(sub->m_scaley*fadeawayheight);
1955 void CRenderedTextSubtitle::ParseString(CSubtitle* sub, CStringW str, const FwSTSStyle& style)
1957 if(!sub) return;
1958 str.Replace(L"\\N", L"\n");
1959 str.Replace(L"\\n", (sub->m_wrapStyle < 2 || sub->m_wrapStyle == 3) ? L" " : L"\n");
1960 str.Replace(L"\\h", L"\x00A0");
1961 for(int ite = 0, j = 0, len = str.GetLength(); j <= len; j++)
1963 WCHAR c = str[j];
1964 if(c != L'\n' && c != L' ' && c != 0)
1965 continue;
1966 if(ite < j)
1968 if(PCWord tmp_ptr = new CText(style, str.Mid(ite, j-ite), m_ktype, m_kstart, m_kend))
1970 SharedPtrCWord w(tmp_ptr);
1971 sub->m_words.AddTail(w);
1973 else
1975 ///TODO: overflow handling
1977 m_kstart = m_kend;
1979 if(c == L'\n')
1981 if(PCWord tmp_ptr = new CText(style, CStringW(), m_ktype, m_kstart, m_kend))
1983 SharedPtrCWord w(tmp_ptr);
1984 sub->m_words.AddTail(w);
1986 else
1988 ///TODO: overflow handling
1990 m_kstart = m_kend;
1992 else if(c == L' ')
1994 if(PCWord tmp_ptr = new CText(style, CStringW(c), m_ktype, m_kstart, m_kend))
1996 SharedPtrCWord w(tmp_ptr);
1997 sub->m_words.AddTail(w);
1999 else
2001 ///TODO: overflow handling
2003 m_kstart = m_kend;
2005 ite = j+1;
2007 return;
2010 void CRenderedTextSubtitle::ParsePolygon(CSubtitle* sub, const CStringW& str, const FwSTSStyle& style)
2012 if(!sub || !str.GetLength() || !m_nPolygon) return;
2014 if(PCWord tmp_ptr = new CPolygon(style, str, m_ktype, m_kstart, m_kend, sub->m_scalex/(1<<(m_nPolygon-1)), sub->m_scaley/(1<<(m_nPolygon-1)), m_polygonBaselineOffset))
2016 SharedPtrCWord w(tmp_ptr);
2017 ///Todo: fix me
2018 //if( PCWord w_cache = m_wordCache.lookup(*w) )
2020 // sub->m_words.AddTail(w_cache);
2021 // delete w;
2023 //else
2025 sub->m_words.AddTail(w);
2027 m_kstart = m_kend;
2031 bool CRenderedTextSubtitle::ParseSSATag( AssTagList *assTags, const CStringW& str )
2033 if(!assTags) return(false);
2034 int nTags = 0, nUnrecognizedTags = 0;
2035 for(int i = 0, j; (j = str.Find(L'\\', i)) >= 0; i = j)
2037 POSITION pos = assTags->AddTail();
2038 AssTag& assTag = assTags->GetAt(pos);
2039 assTag.cmdType = CMD_COUNT;
2041 j++;
2042 CStringW::PCXSTR str_start = str.GetString() + j;
2043 CStringW::PCXSTR pc = str_start;
2044 while( iswspace(*pc) )
2046 pc++;
2048 j += pc-str_start;
2049 str_start = pc;
2050 while( *pc && *pc != L'(' && *pc != L'\\' )
2052 pc++;
2054 j += pc-str_start;
2055 if( pc-str_start>0 )
2057 while( iswspace(*--pc) );
2058 pc++;
2061 const CStringW cmd(str_start, pc-str_start);
2062 if(cmd.IsEmpty()) continue;
2064 CAtlArray<CStringW>& params = assTag.strParams;
2065 if(str[j] == L'(')
2067 j++;
2068 CStringW::PCXSTR str_start = str.GetString() + j;
2069 CStringW::PCXSTR pc = str_start;
2070 while( iswspace(*pc) )
2072 pc++;
2074 j += pc-str_start;
2075 str_start = pc;
2076 while( *pc && *pc != L')' )
2078 pc++;
2080 j += pc-str_start;
2081 if( pc-str_start>0 )
2083 while( iswspace(*--pc) );
2084 pc++;
2087 CStringW::PCXSTR param_start = str_start;
2088 CStringW::PCXSTR param_end = pc;
2089 while( param_start<param_end )
2091 param_start = SkipWhiteSpaceLeft(param_start, param_end);
2093 CStringW::PCXSTR newstart = FindChar(param_start, param_end, L',');
2094 CStringW::PCXSTR newend = FindChar(param_start, param_end, L'\\');
2095 if(newstart > param_start && newstart < newend)
2097 newstart = FastSkipWhiteSpaceRight(param_start, newstart);
2098 CStringW s(param_start, newstart - param_start);
2100 if(!s.IsEmpty()) params.Add(s);
2101 param_start = newstart + 1;
2103 else if(param_start<param_end)
2105 CStringW s(param_start, param_end - param_start);
2107 params.Add(s);
2108 param_start = param_end;
2113 AssCmdType cmd_type = CMD_COUNT;
2114 int cmd_length = min(MAX_CMD_LENGTH, cmd.GetLength());
2115 for( ;cmd_length>=MIN_CMD_LENGTH;cmd_length-- )
2117 if( m_cmdMap.Lookup(cmd.Left(cmd_length), cmd_type) )
2118 break;
2120 if(cmd_length<MIN_CMD_LENGTH)
2121 cmd_type = CMD_COUNT;
2122 switch( cmd_type )
2124 case CMD_fax:
2125 case CMD_fay:
2126 case CMD_fe:
2127 case CMD_fn:
2128 case CMD_frx:
2129 case CMD_fry:
2130 case CMD_frz:
2131 case CMD_fr:
2132 case CMD_fscx:
2133 case CMD_fscy:
2134 case CMD_fsc:
2135 case CMD_fsp:
2136 case CMD_fs:
2137 case CMD_i:
2138 case CMD_kt:
2139 case CMD_kf:
2140 case CMD_K:
2141 case CMD_ko:
2142 case CMD_k:
2143 case CMD_pbo:
2144 case CMD_p:
2145 case CMD_q:
2146 case CMD_r:
2147 case CMD_shad:
2148 case CMD_s:
2149 case CMD_an:
2150 case CMD_a:
2151 case CMD_blur:
2152 case CMD_bord:
2153 case CMD_be:
2154 case CMD_b:
2155 case CMD_u:
2156 case CMD_xbord:
2157 case CMD_xshad:
2158 case CMD_ybord:
2159 case CMD_yshad:
2160 // default:
2161 params.Add(cmd.Mid(cmd_length));
2162 break;
2163 case CMD_c:
2164 case CMD_1c :
2165 case CMD_2c :
2166 case CMD_3c :
2167 case CMD_4c :
2168 case CMD_1a :
2169 case CMD_2a :
2170 case CMD_3a :
2171 case CMD_4a :
2172 case CMD_alpha:
2173 params.Add(cmd.Mid(cmd_length).Trim(L"&H"));
2174 break;
2175 case CMD_clip:
2176 case CMD_iclip:
2177 case CMD_fade:
2178 case CMD_fad:
2179 case CMD_move:
2180 case CMD_org:
2181 case CMD_pos:
2182 break;
2183 case CMD_t:
2184 if (!params.IsEmpty())
2185 ParseSSATag(&assTag.embeded, params[params.GetCount()-1]);
2186 break;
2187 case CMD_COUNT:
2188 nUnrecognizedTags++;
2189 break;
2192 assTag.cmdType = cmd_type;
2194 nTags++;
2196 return(true);
2199 bool CRenderedTextSubtitle::ParseSSATag( CSubtitle* sub, const AssTagList& assTags, STSStyle& style, const STSStyle& org, bool fAnimate /*= false*/ )
2201 if(!sub) return(false);
2203 POSITION pos = assTags.GetHeadPosition();
2204 while(pos)
2206 const AssTag& assTag = assTags.GetNext(pos);
2207 AssCmdType cmd_type = assTag.cmdType;
2208 const CAtlArray<CStringW>& params = assTag.strParams;
2210 // TODO: call ParseStyleModifier(cmd, params, ..) and move the rest there
2211 const CStringW& p = params.GetCount() > 0 ? params[0] : CStringW("");
2212 switch ( cmd_type )
2214 case CMD_1c :
2216 const int i = 0;
2217 DWORD c = wcstol(p, NULL, 16);
2218 style.colors[i] = !p.IsEmpty()
2219 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2220 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2221 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2222 : org.colors[i];
2223 break;
2225 case CMD_2c :
2227 const int i = 1;
2228 DWORD c = wcstol(p, NULL, 16);
2229 style.colors[i] = !p.IsEmpty()
2230 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2231 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2232 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2233 : org.colors[i];
2234 break;
2236 case CMD_3c :
2238 const int i = 2;
2239 DWORD c = wcstol(p, NULL, 16);
2240 style.colors[i] = !p.IsEmpty()
2241 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2242 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2243 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2244 : org.colors[i];
2245 break;
2247 case CMD_4c :
2249 const int i = 3;
2250 DWORD c = wcstol(p, NULL, 16);
2251 style.colors[i] = !p.IsEmpty()
2252 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2253 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2254 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2255 : org.colors[i];
2256 break;
2258 case CMD_1a :
2260 int i = 0;
2261 style.alpha[i] = !p.IsEmpty()
2262 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2263 : org.alpha[i];
2264 break;
2266 case CMD_2a :
2268 int i = 1;
2269 style.alpha[i] = !p.IsEmpty()
2270 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2271 : org.alpha[i];
2272 break;
2274 case CMD_3a :
2276 int i = 2;
2277 style.alpha[i] = !p.IsEmpty()
2278 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2279 : org.alpha[i];
2280 break;
2282 case CMD_4a :
2284 int i = 3;
2285 style.alpha[i] = !p.IsEmpty()
2286 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2287 : org.alpha[i];
2288 break;
2290 case CMD_alpha:
2292 for(int i = 0; i < 4; i++)
2294 style.alpha[i] = !p.IsEmpty()
2295 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2296 : org.alpha[i];
2298 break;
2300 case CMD_an:
2302 int n = wcstol(p, NULL, 10);
2303 if(sub->m_scrAlignment < 0)
2304 sub->m_scrAlignment = (n > 0 && n < 10) ? n : org.scrAlignment;
2305 break;
2307 case CMD_a:
2309 int n = wcstol(p, NULL, 10);
2310 if(sub->m_scrAlignment < 0)
2311 sub->m_scrAlignment = (n > 0 && n < 12) ? ((((n-1)&3)+1)+((n&4)?6:0)+((n&8)?3:0)) : org.scrAlignment;
2312 break;
2314 case CMD_blur:
2316 double n = CalcAnimation(wcstod(p, NULL), style.fGaussianBlur, fAnimate);
2317 style.fGaussianBlur = !p.IsEmpty()
2318 ? (n < 0 ? 0 : n)
2319 : org.fGaussianBlur;
2320 break;
2322 case CMD_bord:
2324 double dst = wcstod(p, NULL);
2325 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2326 style.outlineWidthX = !p.IsEmpty()
2327 ? (nx < 0 ? 0 : nx)
2328 : org.outlineWidthX;
2329 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2330 style.outlineWidthY = !p.IsEmpty()
2331 ? (ny < 0 ? 0 : ny)
2332 : org.outlineWidthY;
2333 break;
2335 case CMD_be:
2337 int n = (int)(CalcAnimation(wcstod(p, NULL), style.fBlur, fAnimate)+0.5);
2338 style.fBlur = !p.IsEmpty()
2340 : org.fBlur;
2341 break;
2343 case CMD_b:
2345 int n = wcstol(p, NULL, 10);
2346 style.fontWeight = !p.IsEmpty()
2347 ? (n == 0 ? FW_NORMAL : n == 1 ? FW_BOLD : n >= 100 ? n : org.fontWeight)
2348 : org.fontWeight;
2349 break;
2351 case CMD_clip:
2352 case CMD_iclip:
2354 bool invert = (cmd_type == CMD_iclip);
2355 if(params.GetCount() == 1 && !sub->m_pClipper)
2357 sub->m_pClipper.reset( new CClipper(params[0], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex, sub->m_scaley, invert) );
2359 else if(params.GetCount() == 2 && !sub->m_pClipper)
2361 int scale = max(wcstol(p, NULL, 10), 1);
2362 sub->m_pClipper.reset( new CClipper(params[1], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex/(1<<(scale-1)), sub->m_scaley/(1<<(scale-1)), invert) );
2364 else if(params.GetCount() == 4)
2366 CRect r;
2367 sub->m_clipInverse = invert;
2368 r.SetRect(
2369 wcstod(params[0], NULL)+0.5,
2370 wcstod(params[1], NULL)+0.5,
2371 wcstod(params[2], NULL)+0.5,
2372 wcstod(params[3], NULL)+0.5);
2373 CPoint o(0, 0);
2374 if(sub->m_relativeTo == 1) // TODO: this should also apply to the other two clippings above
2376 o.x = m_vidrect.left>>3;
2377 o.y = m_vidrect.top>>3;
2379 sub->m_clip.SetRect(
2380 (int)CalcAnimation(sub->m_scalex*r.left + o.x, sub->m_clip.left, fAnimate),
2381 (int)CalcAnimation(sub->m_scaley*r.top + o.y, sub->m_clip.top, fAnimate),
2382 (int)CalcAnimation(sub->m_scalex*r.right + o.x, sub->m_clip.right, fAnimate),
2383 (int)CalcAnimation(sub->m_scaley*r.bottom + o.y, sub->m_clip.bottom, fAnimate));
2385 break;
2387 case CMD_c:
2389 DWORD c = wcstol(p, NULL, 16);
2390 style.colors[0] = !p.IsEmpty()
2391 ? (((int)CalcAnimation(c&0xff, style.colors[0]&0xff, fAnimate))&0xff
2392 |((int)CalcAnimation(c&0xff00, style.colors[0]&0xff00, fAnimate))&0xff00
2393 |((int)CalcAnimation(c&0xff0000, style.colors[0]&0xff0000, fAnimate))&0xff0000)
2394 : org.colors[0];
2395 break;
2397 case CMD_fade:
2398 case CMD_fad:
2400 sub->m_fAnimated2 = true;
2401 if(params.GetCount() == 7 && !sub->m_effects[EF_FADE])// {\fade(a1=param[0], a2=param[1], a3=param[2], t1=t[0], t2=t[1], t3=t[2], t4=t[3])
2403 if(Effect* e = new Effect)
2405 for(int i = 0; i < 3; i++)
2406 e->param[i] = wcstol(params[i], NULL, 10);
2407 for(int i = 0; i < 4; i++)
2408 e->t[i] = wcstol(params[3+i], NULL, 10);
2409 sub->m_effects[EF_FADE] = e;
2412 else if(params.GetCount() == 2 && !sub->m_effects[EF_FADE]) // {\fad(t1=t[1], t2=t[2])
2414 if(Effect* e = new Effect)
2416 e->param[0] = e->param[2] = 0xff;
2417 e->param[1] = 0x00;
2418 for(int i = 1; i < 3; i++)
2419 e->t[i] = wcstol(params[i-1], NULL, 10);
2420 e->t[0] = e->t[3] = -1; // will be substituted with "start" and "end"
2421 sub->m_effects[EF_FADE] = e;
2424 break;
2426 case CMD_fax:
2428 style.fontShiftX = !p.IsEmpty()
2429 ? CalcAnimation(wcstod(p, NULL), style.fontShiftX, fAnimate)
2430 : org.fontShiftX;
2431 break;
2433 case CMD_fay:
2435 style.fontShiftY = !p.IsEmpty()
2436 ? CalcAnimation(wcstod(p, NULL), style.fontShiftY, fAnimate)
2437 : org.fontShiftY;
2438 break;
2440 case CMD_fe:
2442 int n = wcstol(p, NULL, 10);
2443 style.charSet = !p.IsEmpty()
2445 : org.charSet;
2446 break;
2448 case CMD_fn:
2450 if(!p.IsEmpty() && p != L'0')
2451 style.fontName = CString(p).Trim();
2452 else
2453 style.fontName = org.fontName;
2454 break;
2456 case CMD_frx:
2458 style.fontAngleX = !p.IsEmpty()
2459 ? CalcAnimation(wcstod(p, NULL), style.fontAngleX, fAnimate)
2460 : org.fontAngleX;
2461 break;
2463 case CMD_fry:
2465 style.fontAngleY = !p.IsEmpty()
2466 ? CalcAnimation(wcstod(p, NULL), style.fontAngleY, fAnimate)
2467 : org.fontAngleY;
2468 break;
2470 case CMD_frz:
2471 case CMD_fr:
2473 style.fontAngleZ = !p.IsEmpty()
2474 ? CalcAnimation(wcstod(p, NULL), style.fontAngleZ, fAnimate)
2475 : org.fontAngleZ;
2476 break;
2478 case CMD_fscx:
2480 double n = CalcAnimation(wcstod(p, NULL), style.fontScaleX, fAnimate);
2481 style.fontScaleX = !p.IsEmpty()
2482 ? ((n < 0) ? 0 : n)
2483 : org.fontScaleX;
2484 break;
2486 case CMD_fscy:
2488 double n = CalcAnimation(wcstod(p, NULL), style.fontScaleY, fAnimate);
2489 style.fontScaleY = !p.IsEmpty()
2490 ? ((n < 0) ? 0 : n)
2491 : org.fontScaleY;
2492 break;
2494 case CMD_fsc:
2496 style.fontScaleX = org.fontScaleX;
2497 style.fontScaleY = org.fontScaleY;
2498 break;
2500 case CMD_fsp:
2502 style.fontSpacing = !p.IsEmpty()
2503 ? CalcAnimation(wcstod(p, NULL), style.fontSpacing, fAnimate)
2504 : org.fontSpacing;
2505 break;
2507 case CMD_fs:
2509 if(!p.IsEmpty())
2511 if(p[0] == L'-' || p[0] == L'+')
2513 double n = CalcAnimation(style.fontSize + style.fontSize*wcstod(p, NULL)/10, style.fontSize, fAnimate);
2514 style.fontSize = (n > 0) ? n : org.fontSize;
2516 else
2518 double n = CalcAnimation(wcstod(p, NULL), style.fontSize, fAnimate);
2519 style.fontSize = (n > 0) ? n : org.fontSize;
2522 else
2524 style.fontSize = org.fontSize;
2526 break;
2528 case CMD_i:
2530 int n = wcstol(p, NULL, 10);
2531 style.fItalic = !p.IsEmpty()
2532 ? (n == 0 ? false : n == 1 ? true : org.fItalic)
2533 : org.fItalic;
2534 break;
2536 case CMD_kt:
2538 m_kstart = !p.IsEmpty()
2539 ? wcstod(p, NULL)*10
2540 : 0;
2541 m_kend = m_kstart;
2542 break;
2543 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2545 case CMD_kf:
2546 case CMD_K:
2548 m_ktype = 1;
2549 m_kstart = m_kend;
2550 m_kend += !p.IsEmpty()
2551 ? wcstod(p, NULL)*10
2552 : 1000;
2553 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2554 break;
2556 case CMD_ko:
2558 m_ktype = 2;
2559 m_kstart = m_kend;
2560 m_kend += !p.IsEmpty()
2561 ? wcstod(p, NULL)*10
2562 : 1000;
2563 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2564 break;
2566 case CMD_k:
2568 m_ktype = 0;
2569 m_kstart = m_kend;
2570 m_kend += !p.IsEmpty()
2571 ? wcstod(p, NULL)*10
2572 : 1000;
2573 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2574 break;
2576 case CMD_move: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3][, t1=t[0], t2=t[1]])}
2578 if((params.GetCount() == 4 || params.GetCount() == 6) && !sub->m_effects[EF_MOVE])
2580 if(Effect* e = new Effect)
2582 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2583 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2584 e->param[2] = (int)(sub->m_scalex*wcstod(params[2], NULL)*8);
2585 e->param[3] = (int)(sub->m_scaley*wcstod(params[3], NULL)*8);
2586 e->t[0] = e->t[1] = -1;
2587 if(params.GetCount() == 6)
2589 for(int i = 0; i < 2; i++)
2590 e->t[i] = wcstol(params[4+i], NULL, 10);
2592 sub->m_effects[EF_MOVE] = e;
2593 sub->m_fAnimated2 = true;
2596 break;
2598 case CMD_org: // {\org(x=param[0], y=param[1])}
2600 if(params.GetCount() == 2 && !sub->m_effects[EF_ORG])
2602 if(Effect* e = new Effect)
2604 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2605 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2606 sub->m_effects[EF_ORG] = e;
2609 break;
2611 case CMD_pbo:
2613 m_polygonBaselineOffset = wcstol(p, NULL, 10);
2614 break;
2616 case CMD_pos:
2618 if(params.GetCount() == 2 && !sub->m_effects[EF_MOVE])
2620 if(Effect* e = new Effect)
2622 e->param[0] = e->param[2] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2623 e->param[1] = e->param[3] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2624 e->t[0] = e->t[1] = 0;
2625 sub->m_effects[EF_MOVE] = e;
2628 break;
2630 case CMD_p:
2632 int n = wcstol(p, NULL, 10);
2633 m_nPolygon = (n <= 0 ? 0 : n);
2634 break;
2636 case CMD_q:
2638 int n = wcstol(p, NULL, 10);
2639 sub->m_wrapStyle = !p.IsEmpty() && (0 <= n && n <= 3)
2641 : m_defaultWrapStyle;
2642 break;
2644 case CMD_r:
2646 STSStyle* val;
2647 style = (!p.IsEmpty() && m_styles.Lookup(WToT(p), val) && val) ? *val : org;
2648 break;
2650 case CMD_shad:
2652 double dst = wcstod(p, NULL);
2653 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2654 style.shadowDepthX = !p.IsEmpty()
2655 ? (nx < 0 ? 0 : nx)
2656 : org.shadowDepthX;
2657 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2658 style.shadowDepthY = !p.IsEmpty()
2659 ? (ny < 0 ? 0 : ny)
2660 : org.shadowDepthY;
2661 break;
2663 case CMD_s:
2665 int n = wcstol(p, NULL, 10);
2666 style.fStrikeOut = !p.IsEmpty()
2667 ? (n == 0 ? false : n == 1 ? true : org.fStrikeOut)
2668 : org.fStrikeOut;
2669 break;
2671 case CMD_t: // \t([<t1>,<t2>,][<accel>,]<style modifiers>)
2673 CStringW param;
2674 m_animStart = m_animEnd = 0;
2675 m_animAccel = 1;
2676 if(params.GetCount() == 1)
2678 param = params[0];
2680 else if(params.GetCount() == 2)
2682 m_animAccel = wcstod(params[0], NULL);
2683 param = params[1];
2685 else if(params.GetCount() == 3)
2687 m_animStart = (int)wcstod(params[0], NULL);
2688 m_animEnd = (int)wcstod(params[1], NULL);
2689 param = params[2];
2691 else if(params.GetCount() == 4)
2693 m_animStart = wcstol(params[0], NULL, 10);
2694 m_animEnd = wcstol(params[1], NULL, 10);
2695 m_animAccel = wcstod(params[2], NULL);
2696 param = params[3];
2698 ParseSSATag(sub, assTag.embeded, style, org, true);
2699 sub->m_fAnimated = true;
2700 sub->m_fAnimated2 = true;
2701 break;
2703 case CMD_u:
2705 int n = wcstol(p, NULL, 10);
2706 style.fUnderline = !p.IsEmpty()
2707 ? (n == 0 ? false : n == 1 ? true : org.fUnderline)
2708 : org.fUnderline;
2709 break;
2711 case CMD_xbord:
2713 double dst = wcstod(p, NULL);
2714 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2715 style.outlineWidthX = !p.IsEmpty()
2716 ? (nx < 0 ? 0 : nx)
2717 : org.outlineWidthX;
2718 break;
2720 case CMD_xshad:
2722 double dst = wcstod(p, NULL);
2723 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2724 style.shadowDepthX = !p.IsEmpty()
2725 ? nx
2726 : org.shadowDepthX;
2727 break;
2729 case CMD_ybord:
2731 double dst = wcstod(p, NULL);
2732 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2733 style.outlineWidthY = !p.IsEmpty()
2734 ? (ny < 0 ? 0 : ny)
2735 : org.outlineWidthY;
2736 break;
2738 case CMD_yshad:
2740 double dst = wcstod(p, NULL);
2741 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2742 style.shadowDepthY = !p.IsEmpty()
2743 ? ny
2744 : org.shadowDepthY;
2745 break;
2747 default:
2748 break;
2751 return(true);
2754 bool CRenderedTextSubtitle::ParseSSATag(CSubtitle* sub, const CStringW& str, STSStyle& style, const STSStyle& org, bool fAnimate)
2756 if(!sub) return(false);
2758 SharedPtrConstAssTagList assTags;
2759 AssTagListMruCache *ass_tag_cache = CacheManager::GetAssTagListMruCache();
2760 POSITION pos = ass_tag_cache->Lookup(str);
2761 if (pos==NULL)
2763 AssTagList *tmp = new AssTagList();
2764 ParseSSATag(tmp, str);
2765 assTags.reset(tmp);
2766 ass_tag_cache->UpdateCache(str, assTags);
2768 else
2770 assTags = ass_tag_cache->GetAt(pos);
2771 ass_tag_cache->UpdateCache( pos );
2773 return ParseSSATag(sub, *assTags, style, org, fAnimate);
2776 bool CRenderedTextSubtitle::ParseHtmlTag(CSubtitle* sub, CStringW str, STSStyle& style, STSStyle& org)
2778 if(str.Find(L"!--") == 0)
2779 return(true);
2780 bool fClosing = str[0] == L'/';
2781 str.Trim(L" /");
2782 int i = str.Find(L' ');
2783 if(i < 0) i = str.GetLength();
2784 CStringW tag = str.Left(i).MakeLower();
2785 str = str.Mid(i).Trim();
2786 CAtlArray<CStringW> attribs, params;
2787 while((i = str.Find(L'=')) > 0)
2789 attribs.Add(str.Left(i).Trim().MakeLower());
2790 str = str.Mid(i+1);
2791 for(i = 0; _istspace(str[i]); i++);
2792 str = str.Mid(i);
2793 if(str[0] == L'\"') {str = str.Mid(1); i = str.Find(L'\"');}
2794 else i = str.Find(L' ');
2795 if(i < 0) i = str.GetLength();
2796 params.Add(str.Left(i).Trim().MakeLower());
2797 str = str.Mid(i+1);
2799 if(tag == L"text")
2801 else if(tag == L"b" || tag == L"strong")
2802 style.fontWeight = !fClosing ? FW_BOLD : org.fontWeight;
2803 else if(tag == L"i" || tag == L"em")
2804 style.fItalic = !fClosing ? true : org.fItalic;
2805 else if(tag == L"u")
2806 style.fUnderline = !fClosing ? true : org.fUnderline;
2807 else if(tag == L"s" || tag == L"strike" || tag == L"del")
2808 style.fStrikeOut = !fClosing ? true : org.fStrikeOut;
2809 else if(tag == L"font")
2811 if(!fClosing)
2813 for(size_t i = 0; i < attribs.GetCount(); i++)
2815 if(params[i].IsEmpty()) continue;
2816 int nColor = -1;
2817 if(attribs[i] == L"face")
2819 style.fontName = params[i];
2821 else if(attribs[i] == L"size")
2823 if(params[i][0] == L'+')
2824 style.fontSize += wcstol(params[i], NULL, 10);
2825 else if(params[i][0] == L'-')
2826 style.fontSize -= wcstol(params[i], NULL, 10);
2827 else
2828 style.fontSize = wcstol(params[i], NULL, 10);
2830 else if(attribs[i] == L"color")
2832 nColor = 0;
2834 else if(attribs[i] == L"outline-color")
2836 nColor = 2;
2838 else if(attribs[i] == L"outline-level")
2840 style.outlineWidthX = style.outlineWidthY = wcstol(params[i], NULL, 10);
2842 else if(attribs[i] == L"shadow-color")
2844 nColor = 3;
2846 else if(attribs[i] == L"shadow-level")
2848 style.shadowDepthX = style.shadowDepthY = wcstol(params[i], NULL, 10);
2850 if(nColor >= 0 && nColor < 4)
2852 CString key = WToT(params[i]).TrimLeft(L'#');
2853 DWORD val;
2854 if(g_colors.Lookup(key, val))
2855 style.colors[nColor] = val;
2856 else if((style.colors[nColor] = _tcstol(key, NULL, 16)) == 0)
2857 style.colors[nColor] = 0x00ffffff; // default is white
2858 style.colors[nColor] = ((style.colors[nColor]>>16)&0xff)|((style.colors[nColor]&0xff)<<16)|(style.colors[nColor]&0x00ff00);
2862 else
2864 style.fontName = org.fontName;
2865 style.fontSize = org.fontSize;
2866 memcpy(style.colors, org.colors, sizeof(style.colors));
2869 else if(tag == L"k" && attribs.GetCount() == 1 && attribs[0] == L"t")
2871 m_ktype = 1;
2872 m_kstart = m_kend;
2873 m_kend += wcstol(params[0], NULL, 10);
2875 else
2876 return(false);
2877 return(true);
2880 double CRenderedTextSubtitle::CalcAnimation(double dst, double src, bool fAnimate)
2882 int s = m_animStart ? m_animStart : 0;
2883 int e = m_animEnd ? m_animEnd : m_delay;
2884 if(fabs(dst-src) >= 0.0001 && fAnimate)
2886 if(m_time < s) dst = src;
2887 else if(s <= m_time && m_time < e)
2889 double t = pow(1.0 * (m_time - s) / (e - s), m_animAccel);
2890 dst = (1 - t) * src + t * dst;
2892 // else dst = dst;
2894 return(dst);
2897 CSubtitle* CRenderedTextSubtitle::GetSubtitle(int entry)
2899 CSubtitle* sub;
2900 if(m_subtitleCache.Lookup(entry, sub))
2902 if(sub->m_fAnimated) {delete sub; sub = NULL;}
2903 else return(sub);
2905 sub = new CSubtitle();
2906 if(!sub) return(NULL);
2907 CStringW str = GetStrW(entry, true);
2908 STSStyle stss, orgstss;
2909 GetStyle(entry, &stss);
2910 if (stss.fontScaleX == stss.fontScaleY && m_dPARCompensation != 1.0)
2912 switch(m_ePARCompensationType)
2914 case EPCTUpscale:
2915 if (m_dPARCompensation < 1.0)
2916 stss.fontScaleY /= m_dPARCompensation;
2917 else
2918 stss.fontScaleX *= m_dPARCompensation;
2919 break;
2920 case EPCTDownscale:
2921 if (m_dPARCompensation < 1.0)
2922 stss.fontScaleX *= m_dPARCompensation;
2923 else
2924 stss.fontScaleY /= m_dPARCompensation;
2925 break;
2926 case EPCTAccurateSize:
2927 stss.fontScaleX *= m_dPARCompensation;
2928 break;
2931 orgstss = stss;
2932 sub->m_clip.SetRect(0, 0, m_size.cx>>3, m_size.cy>>3);
2933 sub->m_scrAlignment = -stss.scrAlignment;
2934 sub->m_wrapStyle = m_defaultWrapStyle;
2935 sub->m_fAnimated = false;
2936 sub->m_relativeTo = stss.relativeTo;
2937 sub->m_scalex = m_dstScreenSize.cx > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Width() : m_size.cx) / (m_dstScreenSize.cx*8) : 1.0;
2938 sub->m_scaley = m_dstScreenSize.cy > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Height() : m_size.cy) / (m_dstScreenSize.cy*8) : 1.0;
2939 m_animStart = m_animEnd = 0;
2940 m_animAccel = 1;
2941 m_ktype = m_kstart = m_kend = 0;
2942 m_nPolygon = 0;
2943 m_polygonBaselineOffset = 0;
2944 ParseEffect(sub, m_entries.GetAt(entry).effect);
2945 while(!str.IsEmpty())
2947 bool fParsed = false;
2948 int i;
2949 if(str[0] == L'{' && (i = str.Find(L'}')) > 0)
2951 if(fParsed = ParseSSATag(sub, str.Mid(1, i-1), stss, orgstss))
2952 str = str.Mid(i+1);
2954 else if(str[0] == L'<' && (i = str.Find(L'>')) > 0)
2956 if(fParsed = ParseHtmlTag(sub, str.Mid(1, i-1), stss, orgstss))
2957 str = str.Mid(i+1);
2959 if(fParsed)
2961 i = str.FindOneOf(L"{<");
2962 if(i < 0) i = str.GetLength();
2963 if(i == 0) continue;
2965 else
2967 i = str.Mid(1).FindOneOf(L"{<");
2968 if(i < 0) i = str.GetLength()-1;
2969 i++;
2971 STSStyle tmp = stss;
2972 tmp.fontSize = sub->m_scaley*tmp.fontSize*64;
2973 tmp.fontSpacing = sub->m_scalex*tmp.fontSpacing*64;
2974 tmp.outlineWidthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2975 tmp.outlineWidthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2976 tmp.shadowDepthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2977 tmp.shadowDepthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2978 FwSTSStyle fw_tmp(tmp);
2979 if(m_nPolygon)
2981 ParsePolygon(sub, str.Left(i), fw_tmp);
2983 else
2985 ParseString(sub, str.Left(i), fw_tmp);
2987 str = str.Mid(i);
2989 if( sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL] )
2990 sub->m_fAnimated2 = true;
2991 // just a "work-around" solution... in most cases nobody will want to use \org together with moving but without rotating the subs
2992 if(sub->m_effects[EF_ORG] && (sub->m_effects[EF_MOVE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]))
2993 sub->m_fAnimated = true;
2994 sub->m_scrAlignment = abs(sub->m_scrAlignment);
2995 STSEntry stse = m_entries.GetAt(entry);
2996 CRect marginRect = stse.marginRect;
2997 if(marginRect.left == 0) marginRect.left = orgstss.marginRect.get().left;
2998 if(marginRect.top == 0) marginRect.top = orgstss.marginRect.get().top;
2999 if(marginRect.right == 0) marginRect.right = orgstss.marginRect.get().right;
3000 if(marginRect.bottom == 0) marginRect.bottom = orgstss.marginRect.get().bottom;
3001 marginRect.left = (int)(sub->m_scalex*marginRect.left*8);
3002 marginRect.top = (int)(sub->m_scaley*marginRect.top*8);
3003 marginRect.right = (int)(sub->m_scalex*marginRect.right*8);
3004 marginRect.bottom = (int)(sub->m_scaley*marginRect.bottom*8);
3005 if(stss.relativeTo == 1)
3007 marginRect.left += m_vidrect.left;
3008 marginRect.top += m_vidrect.top;
3009 marginRect.right += m_size.cx - m_vidrect.right;
3010 marginRect.bottom += m_size.cy - m_vidrect.bottom;
3012 sub->CreateClippers(m_size);
3013 sub->MakeLines(m_size, marginRect);
3014 m_subtitleCache[entry] = sub;
3015 return(sub);
3020 STDMETHODIMP CRenderedTextSubtitle::NonDelegatingQueryInterface(REFIID riid, void** ppv)
3022 CheckPointer(ppv, E_POINTER);
3023 *ppv = NULL;
3024 return
3025 QI(IPersist)
3026 QI(ISubStream)
3027 QI(ISubPicProviderEx2)
3028 QI(ISubPicProvider)
3029 QI(ISubPicProviderEx)
3030 __super::NonDelegatingQueryInterface(riid, ppv);
3033 // ISubPicProvider
3035 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetStartPosition(REFERENCE_TIME rt, double fps)
3037 m_fps = fps;
3038 if (m_fps>0)
3040 m_period = 1000/m_fps;
3041 if(m_period<=0)
3043 m_period = 1;
3046 else
3048 //Todo: fix me. max has been defined as a macro. Use #define NOMINMAX to fix it.
3049 //std::numeric_limits<int>::max();
3050 m_period = INT_MAX;
3053 int iSegment;
3054 int subIndex = 1;//If a segment has animate effect then it corresponds to several subpics.
3055 //subIndex, 1 based, indicates which subpic the result corresponds to.
3056 rt /= 10000i64;
3057 const STSSegment *stss = SearchSubs((int)rt, fps, &iSegment, NULL);
3058 if(stss==NULL)
3059 return NULL;
3060 else if(stss->animated)
3062 int start = TranslateSegmentStart(iSegment, fps);
3063 if(rt > start)
3064 subIndex = (rt-start)/m_period + 1;
3066 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d DUR:%d rt:%lu", stss->animated, iSegment, subIndex, RTS_ANIMATE_SUBPIC_DUR, (ULONG)rt/10000));
3067 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
3068 //if(iSegment < 0) iSegment = 0;
3069 //return(GetNext((POSITION)iSegment));
3072 STDMETHODIMP_(POSITION) CRenderedTextSubtitle::GetNext(POSITION pos)
3074 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3075 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3076 const STSSegment *stss = GetSegment(iSegment);
3077 ASSERT(stss!=NULL && stss->subs.GetCount()>0);
3078 //DbgLog((LOG_TRACE, 3, "stss:%x count:%d", stss, stss->subs.GetCount()));
3079 if(!stss->animated)
3081 iSegment++;
3082 subIndex = 1;
3084 else
3086 int start, end;
3087 TranslateSegmentStartEnd(iSegment, m_fps, start, end);
3088 if(start+m_period*subIndex < end)
3089 subIndex++;
3090 else
3092 iSegment++;
3093 subIndex = 1;
3096 if(GetSegment(iSegment) != NULL)
3098 ASSERT(GetSegment(iSegment)->subs.GetCount()>0);
3099 return (POSITION)(subIndex | (iSegment<<RTS_POS_SEGMENT_INDEX_BITS));
3101 else
3102 return NULL;
3105 //@return: <0 if segment not found
3106 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStart(POSITION pos, double fps)
3108 //return(10000i64 * TranslateSegmentStart((int)pos-1, fps));
3109 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3110 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3111 int start = TranslateSegmentStart(iSegment, fps);
3112 const STSSegment *stss = GetSegment(iSegment);
3113 if(stss!=NULL)
3115 return (start + (subIndex-1)*m_period)*10000i64;
3117 else
3119 return -1;
3123 //@return: <0 if segment not found
3124 STDMETHODIMP_(REFERENCE_TIME) CRenderedTextSubtitle::GetStop(POSITION pos, double fps)
3126 // return(10000i64 * TranslateSegmentEnd((int)pos-1, fps));
3127 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3128 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3129 int start, end, ret;
3130 TranslateSegmentStartEnd(iSegment, fps, start, end);
3131 const STSSegment *stss = GetSegment(iSegment);
3132 if(stss!=NULL)
3134 if(!stss->animated)
3135 ret = end;
3136 else
3138 ret = start+subIndex*m_period;
3139 if(ret > end)
3140 ret = end;
3142 return ret*10000i64;
3144 else
3145 return -1;
3148 //@start, @stop: -1 if segment not found; @stop may < @start if subIndex exceed uppper bound
3149 STDMETHODIMP_(VOID) CRenderedTextSubtitle::GetStartStop(POSITION pos, double fps, /*out*/REFERENCE_TIME &start, /*out*/REFERENCE_TIME &stop)
3151 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3152 int subIndex = ((int)pos & RTS_POS_SUB_INDEX_MASK);
3153 int tempStart, tempEnd;
3154 TranslateSegmentStartEnd(iSegment, fps, tempStart, tempEnd);
3155 start = tempStart;
3156 stop = tempEnd;
3157 const STSSegment *stss = GetSegment(iSegment);
3158 if(stss!=NULL)
3160 if(stss->animated)
3162 start += (subIndex-1)*m_period;
3163 if(start+m_period < stop)
3164 stop = start+m_period;
3166 //DbgLog((LOG_TRACE, 3, "animated:%d seg:%d idx:%d start:%d stop:%lu", stss->animated, iSegment, subIndex, (ULONG)start, (ULONG)stop));
3167 start *= 10000i64;
3168 stop *= 10000i64;
3170 else
3172 start = -1;
3173 stop = -1;
3177 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsAnimated(POSITION pos)
3179 int iSegment = ((int)pos>>RTS_POS_SEGMENT_INDEX_BITS);
3180 if(iSegment>=0 && iSegment<m_segments.GetCount())
3181 return m_segments[iSegment].animated;
3182 else
3183 return false;
3184 //return(true);
3187 struct LSub {int idx, layer, readorder;};
3189 static int lscomp(const void* ls1, const void* ls2)
3191 int ret = ((LSub*)ls1)->layer - ((LSub*)ls2)->layer;
3192 if(!ret) ret = ((LSub*)ls1)->readorder - ((LSub*)ls2)->readorder;
3193 return(ret);
3196 STDMETHODIMP CRenderedTextSubtitle::ParseScript(const SIZE& output_size, REFERENCE_TIME rt, double fps, CSubtitle2List *outputSub2List )
3198 //fix me: check input and log error
3199 int t = (int)(rt / 10000);
3200 int segment;
3201 //const
3202 STSSegment* stss = SearchSubs2(t, fps, &segment);
3203 if(!stss) return S_FALSE;
3204 // clear any cached subs not in the range of +/-30secs measured from the segment's bounds
3206 POSITION pos = m_subtitleCache.GetStartPosition();
3207 while(pos)
3209 int key;
3210 CSubtitle* value;
3211 m_subtitleCache.GetNextAssoc(pos, key, value);
3212 STSEntry& stse = m_entries.GetAt(key);
3213 if(stse.end <= (t-30000) || stse.start > (t+30000))
3215 delete value;
3216 m_subtitleCache.RemoveKey(key);
3217 pos = m_subtitleCache.GetStartPosition();
3221 m_sla.AdvanceToSegment(segment, stss->subs);
3222 CAtlArray<LSub> subs;
3223 for(int i = 0, j = stss->subs.GetCount(); i < j; i++)
3225 LSub ls;
3226 ls.idx = stss->subs[i];
3227 ls.layer = m_entries.GetAt(stss->subs[i]).layer;
3228 ls.readorder = m_entries.GetAt(stss->subs[i]).readorder;
3229 subs.Add(ls);
3231 qsort(subs.GetData(), subs.GetCount(), sizeof(LSub), lscomp);
3233 for(int i = 0, j = subs.GetCount(); i < j; i++)
3235 int entry = subs[i].idx;
3236 STSEntry stse = m_entries.GetAt(entry);
3238 int start = TranslateStart(entry, fps);
3239 m_time = t - start;
3240 m_delay = TranslateEnd(entry, fps) - start;
3242 CSubtitle* s = GetSubtitle(entry);
3243 if(!s) continue;
3244 stss->animated |= s->m_fAnimated2;
3245 CRect clipRect = s->m_clip & CRect(0,0, output_size.cx, output_size.cy);
3246 CRect r = s->m_rect;
3247 CSize spaceNeeded = r.Size();
3248 // apply the effects
3249 bool fPosOverride = false, fOrgOverride = false;
3250 int alpha = 0x00;
3251 CPoint org2;
3252 for(int k = 0; k < EF_NUMBEROFEFFECTS; k++)
3254 if(!s->m_effects[k]) continue;
3255 switch(k)
3257 case EF_MOVE: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3], t1=t[0], t2=t[1])}
3259 CPoint p;
3260 CPoint p1(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3261 CPoint p2(s->m_effects[k]->param[2], s->m_effects[k]->param[3]);
3262 int t1 = s->m_effects[k]->t[0];
3263 int t2 = s->m_effects[k]->t[1];
3264 if(t2 < t1) {int t = t1; t1 = t2; t2 = t;}
3265 if(t1 <= 0 && t2 <= 0) {t1 = 0; t2 = m_delay;}
3266 if(m_time <= t1) p = p1;
3267 else if (p1 == p2) p = p1;
3268 else if(t1 < m_time && m_time < t2)
3270 double t = 1.0*(m_time-t1)/(t2-t1);
3271 p.x = (int)((1-t)*p1.x + t*p2.x);
3272 p.y = (int)((1-t)*p1.y + t*p2.y);
3274 else p = p2;
3275 r = CRect(
3276 CPoint((s->m_scrAlignment%3) == 1 ? p.x : (s->m_scrAlignment%3) == 0 ? p.x - spaceNeeded.cx : p.x - (spaceNeeded.cx+1)/2,
3277 s->m_scrAlignment <= 3 ? p.y - spaceNeeded.cy : s->m_scrAlignment <= 6 ? p.y - (spaceNeeded.cy+1)/2 : p.y),
3278 spaceNeeded);
3279 if(s->m_relativeTo == 1)
3280 r.OffsetRect(m_vidrect.TopLeft());
3281 fPosOverride = true;
3283 break;
3284 case EF_ORG: // {\org(x=param[0], y=param[1])}
3286 org2 = CPoint(s->m_effects[k]->param[0], s->m_effects[k]->param[1]);
3287 fOrgOverride = true;
3289 break;
3290 case EF_FADE: // {\fade(a1=param[0], a2=param[1], a3=param[2], t1=t[0], t2=t[1], t3=t[2], t4=t[3]) or {\fad(t1=t[1], t2=t[2])
3292 int t1 = s->m_effects[k]->t[0];
3293 int t2 = s->m_effects[k]->t[1];
3294 int t3 = s->m_effects[k]->t[2];
3295 int t4 = s->m_effects[k]->t[3];
3296 if(t1 == -1 && t4 == -1) {t1 = 0; t3 = m_delay-t3; t4 = m_delay;}
3297 if(m_time < t1) alpha = s->m_effects[k]->param[0];
3298 else if(m_time >= t1 && m_time < t2)
3300 double t = 1.0 * (m_time - t1) / (t2 - t1);
3301 alpha = (int)(s->m_effects[k]->param[0]*(1-t) + s->m_effects[k]->param[1]*t);
3303 else if(m_time >= t2 && m_time < t3) alpha = s->m_effects[k]->param[1];
3304 else if(m_time >= t3 && m_time < t4)
3306 double t = 1.0 * (m_time - t3) / (t4 - t3);
3307 alpha = (int)(s->m_effects[k]->param[1]*(1-t) + s->m_effects[k]->param[2]*t);
3309 else if(m_time >= t4) alpha = s->m_effects[k]->param[2];
3311 break;
3312 case EF_BANNER: // Banner;delay=param[0][;leftoright=param[1];fadeawaywidth=param[2]]
3314 int left = s->m_relativeTo == 1 ? m_vidrect.left : 0,
3315 right = s->m_relativeTo == 1 ? m_vidrect.right : m_size.cx;
3316 r.left = !!s->m_effects[k]->param[1]
3317 ? (left/*marginRect.left*/ - spaceNeeded.cx) + (int)(m_time*8.0/s->m_effects[k]->param[0])
3318 : (right /*- marginRect.right*/) - (int)(m_time*8.0/s->m_effects[k]->param[0]);
3319 r.right = r.left + spaceNeeded.cx;
3320 clipRect &= CRect(left>>3, clipRect.top, right>>3, clipRect.bottom);
3321 fPosOverride = true;
3323 break;
3324 case EF_SCROLL: // Scroll up/down(toptobottom=param[3]);top=param[0];bottom=param[1];delay=param[2][;fadeawayheight=param[4]]
3326 r.top = !!s->m_effects[k]->param[3]
3327 ? s->m_effects[k]->param[0] + (int)(m_time*8.0/s->m_effects[k]->param[2]) - spaceNeeded.cy
3328 : s->m_effects[k]->param[1] - (int)(m_time*8.0/s->m_effects[k]->param[2]);
3329 r.bottom = r.top + spaceNeeded.cy;
3330 CRect cr(0, (s->m_effects[k]->param[0] + 4) >> 3, output_size.cx, (s->m_effects[k]->param[1] + 4) >> 3);
3331 if(s->m_relativeTo == 1)
3332 r.top += m_vidrect.top,
3333 r.bottom += m_vidrect.top,
3334 cr.top += m_vidrect.top>>3,
3335 cr.bottom += m_vidrect.top>>3;
3336 clipRect &= cr;
3337 fPosOverride = true;
3339 break;
3340 default:
3341 break;
3344 if(!fPosOverride && !fOrgOverride && !s->m_fAnimated)
3345 r = m_sla.AllocRect(s, segment, entry, stse.layer, m_collisions);
3346 CPoint org;
3347 org.x = (s->m_scrAlignment%3) == 1 ? r.left : (s->m_scrAlignment%3) == 2 ? r.CenterPoint().x : r.right;
3348 org.y = s->m_scrAlignment <= 3 ? r.bottom : s->m_scrAlignment <= 6 ? r.CenterPoint().y : r.top;
3349 if(!fOrgOverride) org2 = org;
3350 CPoint p2(0, r.top);
3351 // Rectangles for inverse clip
3353 CSubtitle2& sub2 = outputSub2List->GetAt(outputSub2List->AddTail( CSubtitle2(s, clipRect, org, org2, p2, alpha, m_time) ));
3356 return (subs.GetCount()) ? S_OK : S_FALSE;
3359 STDMETHODIMP CRenderedTextSubtitle::RenderEx(SubPicDesc& spd, REFERENCE_TIME rt, double fps, CAtlList<CRect>& rectList)
3361 CSize output_size = CSize(spd.w,spd.h);
3362 rectList.RemoveAll();
3364 CComPtr<IXySubRenderFrame> sub_render_frame;
3365 HRESULT hr = RenderEx(&sub_render_frame, spd.type, output_size, spd.vidrect, rt, fps);
3366 if (SUCCEEDED(hr) && sub_render_frame)
3368 int count = 0;
3369 hr = sub_render_frame->GetBitmapCount(&count);
3370 if(FAILED(hr))
3372 return hr;
3374 int color_space;
3375 hr = sub_render_frame->GetXyColorSpace(&color_space);
3376 if(FAILED(hr))
3378 return hr;
3380 for (int i=0;i<count;i++)
3382 POINT pos;
3383 SIZE size;
3384 LPCVOID pixels;
3385 int pitch;
3386 hr = sub_render_frame->GetBitmap(i, NULL, &pos, &size, &pixels, &pitch );
3387 if(FAILED(hr))
3389 return hr;
3391 rectList.AddTail(CRect(pos, size));
3392 if (color_space==XY_CS_AYUV_PLANAR)
3394 XyPlannerFormatExtra plans;
3395 hr = sub_render_frame->GetBitmapExtra(i, &plans);
3396 if(FAILED(hr))
3398 return hr;
3400 XyBitmap::AlphaBltPlannar(spd, pos, size, plans, pitch);
3402 else
3404 XyBitmap::AlphaBltPack(spd, pos, size, pixels, pitch);
3408 return (!rectList.IsEmpty()) ? S_OK : S_FALSE;
3411 STDMETHODIMP CRenderedTextSubtitle::RenderEx(IXySubRenderFrame**subRenderFrame, int spd_type, const SIZE& output_size, const CRect& video_rect, REFERENCE_TIME rt, double fps)
3413 if (!subRenderFrame)
3415 return S_FALSE;
3418 XyColorSpace color_space = XY_CS_ARGB;
3419 switch(spd_type)
3421 case MSP_AYUV_PLANAR:
3422 color_space = XY_CS_AYUV_PLANAR;
3423 break;
3424 case MSP_XY_AUYV:
3425 color_space = XY_CS_AUYV;
3426 break;
3427 case MSP_AYUV:
3428 color_space = XY_CS_AYUV;
3429 break;
3430 default:
3431 color_space = XY_CS_ARGB;
3432 break;
3435 XySubRenderFrameCreater *render_frame_creater = XySubRenderFrameCreater::GetDefaultCreater();
3436 render_frame_creater->SetColorSpace(color_space);
3438 if(m_size != CSize(output_size.cx*8, output_size.cy*8)
3439 || m_vidrect != CRect(video_rect.left*8, video_rect.top*8, video_rect.right*8, video_rect.bottom*8))
3441 Init(output_size, video_rect);
3442 render_frame_creater->SetOutputRect(CRect(0,0,output_size.cx,output_size.cy));
3443 render_frame_creater->SetClipRect(CRect(0,0,output_size.cx,output_size.cy));
3446 CSubtitle2List sub2List;
3447 HRESULT hr = ParseScript(output_size, rt, fps, &sub2List);
3448 if(hr!=S_OK)
3450 return hr;
3453 CompositeDrawItemListList compDrawItemListList;
3454 DoRender(output_size, sub2List, &compDrawItemListList);
3456 XySubRenderFrame *sub_render_frame;
3457 CompositeDrawItem::Draw(&sub_render_frame, compDrawItemListList);
3458 (*subRenderFrame = sub_render_frame)->AddRef();
3460 return hr;
3463 void CRenderedTextSubtitle::DoRender( const SIZE& output_size, const CSubtitle2List& sub2List,
3464 CompositeDrawItemListList *compDrawItemListList /*output*/)
3466 //check input and log error
3467 POSITION pos=sub2List.GetHeadPosition();
3468 while ( pos!=NULL )
3470 const CSubtitle2& sub2 = sub2List.GetNext(pos);
3471 CompositeDrawItemList& compDrawItemList = compDrawItemListList->GetAt(compDrawItemListList->AddTail());
3472 RenderOneSubtitle(output_size, sub2, &compDrawItemList);
3476 void CRenderedTextSubtitle::RenderOneSubtitle( const SIZE& output_size, const CSubtitle2& sub2,
3477 CompositeDrawItemList* compDrawItemList /*output*/)
3479 CSubtitle* s = sub2.s;
3480 const CRect& clipRect = sub2.clipRect;
3481 const CPoint& org = sub2.org;
3482 const CPoint& org2 = sub2.org2;
3483 const CPoint& p2 = sub2.p;
3484 int alpha = sub2.alpha;
3485 int time = sub2.time;
3486 if(!s) return;
3488 SharedPtrCClipperPaintMachine clipper( new CClipperPaintMachine(s->m_pClipper) );
3490 CRect iclipRect[4];
3491 iclipRect[0] = CRect(0, 0, output_size.cx, clipRect.top);
3492 iclipRect[1] = CRect(0, clipRect.top, clipRect.left, clipRect.bottom);
3493 iclipRect[2] = CRect(clipRect.right, clipRect.top, output_size.cx, clipRect.bottom);
3494 iclipRect[3] = CRect(0, clipRect.bottom, output_size.cx, output_size.cy);
3495 CRect bbox2(0,0,0,0);
3496 POSITION pos = s->GetHeadLinePosition();
3497 CPoint p = p2;
3498 while(pos)
3500 CLine* l = s->GetNextLine(pos);
3501 p.x = (s->m_scrAlignment%3) == 1 ? org.x
3502 : (s->m_scrAlignment%3) == 0 ? org.x - l->m_width
3503 : org.x - (l->m_width/2);
3505 CompositeDrawItemList tmpCompDrawItemList;
3506 if (s->m_clipInverse)
3508 CompositeDrawItemList tmp1,tmp2,tmp3,tmp4;
3509 for (int i=0;i<l->GetWordCount();i++)
3511 tmp1.AddTail();
3512 tmp2.AddTail();
3513 tmp3.AddTail();
3514 tmp4.AddTail();
3516 bbox2 |= l->PaintAll(&tmp1, iclipRect[0], clipper, p, org2, time, alpha);
3517 bbox2 |= l->PaintAll(&tmp2, iclipRect[1], clipper, p, org2, time, alpha);
3518 bbox2 |= l->PaintAll(&tmp3, iclipRect[2], clipper, p, org2, time, alpha);
3519 bbox2 |= l->PaintAll(&tmp4, iclipRect[3], clipper, p, org2, time, alpha);
3520 tmpCompDrawItemList.AddTailList(&tmp1);
3521 tmpCompDrawItemList.AddTailList(&tmp2);
3522 tmpCompDrawItemList.AddTailList(&tmp3);
3523 tmpCompDrawItemList.AddTailList(&tmp4);
3525 else
3527 for (int i=0;i<l->GetWordCount();i++)
3529 tmpCompDrawItemList.AddTail();
3531 bbox2 |= l->PaintAll(&tmpCompDrawItemList, clipRect, clipper, p, org2, time, alpha);
3533 compDrawItemList->AddTailList(&tmpCompDrawItemList);
3534 p.y += l->m_ascent + l->m_descent;
3538 STDMETHODIMP CRenderedTextSubtitle::Render(SubPicDesc& spd, REFERENCE_TIME rt, double fps, RECT& bbox)
3540 CAtlList<CRect> rectList;
3541 HRESULT result = RenderEx(spd, rt, fps, rectList);
3542 POSITION pos = rectList.GetHeadPosition();
3543 CRect bbox2(0,0,0,0);
3544 while(pos!=NULL)
3546 bbox2 |= rectList.GetNext(pos);
3548 bbox = bbox2;
3549 return result;
3552 // IPersist
3554 STDMETHODIMP CRenderedTextSubtitle::GetClassID(CLSID* pClassID)
3556 return pClassID ? *pClassID = __uuidof(this), S_OK : E_POINTER;
3559 // ISubStream
3561 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStreamCount()
3563 return(1);
3566 STDMETHODIMP CRenderedTextSubtitle::GetStreamInfo(int iStream, WCHAR** ppName, LCID* pLCID)
3568 if(iStream != 0) return E_INVALIDARG;
3569 if(ppName)
3571 if(!(*ppName = (WCHAR*)CoTaskMemAlloc((m_name.GetLength()+1)*sizeof(WCHAR))))
3572 return E_OUTOFMEMORY;
3573 wcscpy(*ppName, CStringW(m_name));
3575 if(pLCID)
3577 *pLCID = 0; // TODO
3579 return S_OK;
3582 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStream()
3584 return(0);
3587 STDMETHODIMP CRenderedTextSubtitle::SetStream(int iStream)
3589 return iStream == 0 ? S_OK : E_FAIL;
3592 STDMETHODIMP CRenderedTextSubtitle::Reload()
3594 CFileStatus s;
3595 if(!CFile::GetStatus(m_path, s)) return E_FAIL;
3596 return !m_path.IsEmpty() && Open(m_path, DEFAULT_CHARSET) ? S_OK : E_FAIL;
3599 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsColorTypeSupported( int type )
3601 return type==MSP_AYUV_PLANAR ||
3602 type==MSP_AYUV ||
3603 type==MSP_XY_AUYV ||
3604 type==MSP_RGBA;
3607 STDMETHODIMP CRenderedTextSubtitle::Lock()
3609 return CSubPicProviderImpl::Lock();
3612 STDMETHODIMP CRenderedTextSubtitle::Unlock()
3614 return CSubPicProviderImpl::Unlock();