Changing to new interface. [PART 7]
[xy_vsfilter.git] / src / subtitles / RTS.cpp
blob3d02354629510cb5f683ecbe038a1f675f0782d6
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( m_style.get().fBlur>0 || m_style.get().fGaussianBlur>0.000001 )
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, SubPicDesc& spd, 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::GetCWordMruCache()->RemoveAll();
1902 CacheManager::GetPathDataMruCache()->RemoveAll();
1903 CacheManager::GetScanLineData2MruCache()->RemoveAll();
1904 CacheManager::GetOverlayNoBlurMruCache()->RemoveAll();
1905 CacheManager::GetOverlayMruCache()->RemoveAll();
1906 CacheManager::GetAssTagListMruCache()->RemoveAll();
1907 CacheManager::GetSubpixelVarianceCache()->RemoveAll();
1908 CacheManager::GetTextInfoCache()->RemoveAll();
1911 void CRenderedTextSubtitle::ParseEffect(CSubtitle* sub, const CStringW& str)
1913 CStringW::PCXSTR str_start = str.GetString();
1914 CStringW::PCXSTR str_end = str_start + str.GetLength();
1915 str_start = SkipWhiteSpaceLeft(str_start, str_end);
1917 if(!sub || *str_start==0)
1918 return;
1920 str_end = FastSkipWhiteSpaceRight(str_start, str_end);
1922 const WCHAR* s = FindChar(str_start, str_end, L';');
1923 if(*s==L';') {
1924 s++;
1927 const CStringW effect(str_start, s-str_start);
1928 if(!effect.CompareNoCase( L"Banner;" ) )
1930 int delay, lefttoright = 0, fadeawaywidth = 0;
1931 if(swscanf(s, L"%d;%d;%d", &delay, &lefttoright, &fadeawaywidth) < 1) return;
1932 Effect* e = new Effect;
1933 if(!e) return;
1934 sub->m_effects[e->type = EF_BANNER] = e;
1935 e->param[0] = (int)(max(1.0*delay/sub->m_scalex, 1));
1936 e->param[1] = lefttoright;
1937 e->param[2] = (int)(sub->m_scalex*fadeawaywidth);
1938 sub->m_wrapStyle = 2;
1940 else if(!effect.CompareNoCase(L"Scroll up;") || !effect.CompareNoCase(L"Scroll down;"))
1942 int top, bottom, delay, fadeawayheight = 0;
1943 if(swscanf(s, L"%d;%d;%d;%d", &top, &bottom, &delay, &fadeawayheight) < 3) return;
1944 if(top > bottom) {int tmp = top; top = bottom; bottom = tmp;}
1945 Effect* e = new Effect;
1946 if(!e) return;
1947 sub->m_effects[e->type = EF_SCROLL] = e;
1948 e->param[0] = (int)(sub->m_scaley*top*8);
1949 e->param[1] = (int)(sub->m_scaley*bottom*8);
1950 e->param[2] = (int)(max(1.0*delay/sub->m_scaley, 1));
1951 e->param[3] = (effect.GetLength() == 12);
1952 e->param[4] = (int)(sub->m_scaley*fadeawayheight);
1956 void CRenderedTextSubtitle::ParseString(CSubtitle* sub, CStringW str, const FwSTSStyle& style)
1958 if(!sub) return;
1959 str.Replace(L"\\N", L"\n");
1960 str.Replace(L"\\n", (sub->m_wrapStyle < 2 || sub->m_wrapStyle == 3) ? L" " : L"\n");
1961 str.Replace(L"\\h", L"\x00A0");
1962 for(int ite = 0, j = 0, len = str.GetLength(); j <= len; j++)
1964 WCHAR c = str[j];
1965 if(c != L'\n' && c != L' ' && c != 0)
1966 continue;
1967 if(ite < j)
1969 if(PCWord tmp_ptr = new CText(style, str.Mid(ite, j-ite), m_ktype, m_kstart, m_kend))
1971 SharedPtrCWord w(tmp_ptr);
1972 sub->m_words.AddTail(w);
1974 else
1976 ///TODO: overflow handling
1978 m_kstart = m_kend;
1980 if(c == L'\n')
1982 if(PCWord tmp_ptr = new CText(style, CStringW(), m_ktype, m_kstart, m_kend))
1984 SharedPtrCWord w(tmp_ptr);
1985 sub->m_words.AddTail(w);
1987 else
1989 ///TODO: overflow handling
1991 m_kstart = m_kend;
1993 else if(c == L' ')
1995 if(PCWord tmp_ptr = new CText(style, CStringW(c), m_ktype, m_kstart, m_kend))
1997 SharedPtrCWord w(tmp_ptr);
1998 sub->m_words.AddTail(w);
2000 else
2002 ///TODO: overflow handling
2004 m_kstart = m_kend;
2006 ite = j+1;
2008 return;
2011 void CRenderedTextSubtitle::ParsePolygon(CSubtitle* sub, const CStringW& str, const FwSTSStyle& style)
2013 if(!sub || !str.GetLength() || !m_nPolygon) return;
2015 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))
2017 SharedPtrCWord w(tmp_ptr);
2018 ///Todo: fix me
2019 //if( PCWord w_cache = m_wordCache.lookup(*w) )
2021 // sub->m_words.AddTail(w_cache);
2022 // delete w;
2024 //else
2026 sub->m_words.AddTail(w);
2028 m_kstart = m_kend;
2032 bool CRenderedTextSubtitle::ParseSSATag( AssTagList *assTags, const CStringW& str )
2034 if(!assTags) return(false);
2035 int nTags = 0, nUnrecognizedTags = 0;
2036 for(int i = 0, j; (j = str.Find(L'\\', i)) >= 0; i = j)
2038 POSITION pos = assTags->AddTail();
2039 AssTag& assTag = assTags->GetAt(pos);
2040 assTag.cmdType = CMD_COUNT;
2042 j++;
2043 CStringW::PCXSTR str_start = str.GetString() + j;
2044 CStringW::PCXSTR pc = str_start;
2045 while( iswspace(*pc) )
2047 pc++;
2049 j += pc-str_start;
2050 str_start = pc;
2051 while( *pc && *pc != L'(' && *pc != L'\\' )
2053 pc++;
2055 j += pc-str_start;
2056 if( pc-str_start>0 )
2058 while( iswspace(*--pc) );
2059 pc++;
2062 const CStringW cmd(str_start, pc-str_start);
2063 if(cmd.IsEmpty()) continue;
2065 CAtlArray<CStringW>& params = assTag.strParams;
2066 if(str[j] == L'(')
2068 j++;
2069 CStringW::PCXSTR str_start = str.GetString() + j;
2070 CStringW::PCXSTR pc = str_start;
2071 while( iswspace(*pc) )
2073 pc++;
2075 j += pc-str_start;
2076 str_start = pc;
2077 while( *pc && *pc != L')' )
2079 pc++;
2081 j += pc-str_start;
2082 if( pc-str_start>0 )
2084 while( iswspace(*--pc) );
2085 pc++;
2088 CStringW::PCXSTR param_start = str_start;
2089 CStringW::PCXSTR param_end = pc;
2090 while( param_start<param_end )
2092 param_start = SkipWhiteSpaceLeft(param_start, param_end);
2094 CStringW::PCXSTR newstart = FindChar(param_start, param_end, L',');
2095 CStringW::PCXSTR newend = FindChar(param_start, param_end, L'\\');
2096 if(newstart > param_start && newstart < newend)
2098 newstart = FastSkipWhiteSpaceRight(param_start, newstart);
2099 CStringW s(param_start, newstart - param_start);
2101 if(!s.IsEmpty()) params.Add(s);
2102 param_start = newstart + 1;
2104 else if(param_start<param_end)
2106 CStringW s(param_start, param_end - param_start);
2108 params.Add(s);
2109 param_start = param_end;
2114 AssCmdType cmd_type = CMD_COUNT;
2115 int cmd_length = min(MAX_CMD_LENGTH, cmd.GetLength());
2116 for( ;cmd_length>=MIN_CMD_LENGTH;cmd_length-- )
2118 if( m_cmdMap.Lookup(cmd.Left(cmd_length), cmd_type) )
2119 break;
2121 if(cmd_length<MIN_CMD_LENGTH)
2122 cmd_type = CMD_COUNT;
2123 switch( cmd_type )
2125 case CMD_fax:
2126 case CMD_fay:
2127 case CMD_fe:
2128 case CMD_fn:
2129 case CMD_frx:
2130 case CMD_fry:
2131 case CMD_frz:
2132 case CMD_fr:
2133 case CMD_fscx:
2134 case CMD_fscy:
2135 case CMD_fsc:
2136 case CMD_fsp:
2137 case CMD_fs:
2138 case CMD_i:
2139 case CMD_kt:
2140 case CMD_kf:
2141 case CMD_K:
2142 case CMD_ko:
2143 case CMD_k:
2144 case CMD_pbo:
2145 case CMD_p:
2146 case CMD_q:
2147 case CMD_r:
2148 case CMD_shad:
2149 case CMD_s:
2150 case CMD_an:
2151 case CMD_a:
2152 case CMD_blur:
2153 case CMD_bord:
2154 case CMD_be:
2155 case CMD_b:
2156 case CMD_u:
2157 case CMD_xbord:
2158 case CMD_xshad:
2159 case CMD_ybord:
2160 case CMD_yshad:
2161 // default:
2162 params.Add(cmd.Mid(cmd_length));
2163 break;
2164 case CMD_c:
2165 case CMD_1c :
2166 case CMD_2c :
2167 case CMD_3c :
2168 case CMD_4c :
2169 case CMD_1a :
2170 case CMD_2a :
2171 case CMD_3a :
2172 case CMD_4a :
2173 case CMD_alpha:
2174 params.Add(cmd.Mid(cmd_length).Trim(L"&H"));
2175 break;
2176 case CMD_clip:
2177 case CMD_iclip:
2178 case CMD_fade:
2179 case CMD_fad:
2180 case CMD_move:
2181 case CMD_org:
2182 case CMD_pos:
2183 break;
2184 case CMD_t:
2185 if (!params.IsEmpty())
2186 ParseSSATag(&assTag.embeded, params[params.GetCount()-1]);
2187 break;
2188 case CMD_COUNT:
2189 nUnrecognizedTags++;
2190 break;
2193 assTag.cmdType = cmd_type;
2195 nTags++;
2197 return(true);
2200 bool CRenderedTextSubtitle::ParseSSATag( CSubtitle* sub, const AssTagList& assTags, STSStyle& style, const STSStyle& org, bool fAnimate /*= false*/ )
2202 if(!sub) return(false);
2204 POSITION pos = assTags.GetHeadPosition();
2205 while(pos)
2207 const AssTag& assTag = assTags.GetNext(pos);
2208 AssCmdType cmd_type = assTag.cmdType;
2209 const CAtlArray<CStringW>& params = assTag.strParams;
2211 // TODO: call ParseStyleModifier(cmd, params, ..) and move the rest there
2212 const CStringW& p = params.GetCount() > 0 ? params[0] : CStringW("");
2213 switch ( cmd_type )
2215 case CMD_1c :
2217 const int i = 0;
2218 DWORD c = wcstol(p, NULL, 16);
2219 style.colors[i] = !p.IsEmpty()
2220 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2221 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2222 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2223 : org.colors[i];
2224 break;
2226 case CMD_2c :
2228 const int i = 1;
2229 DWORD c = wcstol(p, NULL, 16);
2230 style.colors[i] = !p.IsEmpty()
2231 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2232 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2233 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2234 : org.colors[i];
2235 break;
2237 case CMD_3c :
2239 const int i = 2;
2240 DWORD c = wcstol(p, NULL, 16);
2241 style.colors[i] = !p.IsEmpty()
2242 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2243 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2244 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2245 : org.colors[i];
2246 break;
2248 case CMD_4c :
2250 const int i = 3;
2251 DWORD c = wcstol(p, NULL, 16);
2252 style.colors[i] = !p.IsEmpty()
2253 ? (((int)CalcAnimation(c&0xff, style.colors[i]&0xff, fAnimate))&0xff
2254 |((int)CalcAnimation(c&0xff00, style.colors[i]&0xff00, fAnimate))&0xff00
2255 |((int)CalcAnimation(c&0xff0000, style.colors[i]&0xff0000, fAnimate))&0xff0000)
2256 : org.colors[i];
2257 break;
2259 case CMD_1a :
2261 int i = 0;
2262 style.alpha[i] = !p.IsEmpty()
2263 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2264 : org.alpha[i];
2265 break;
2267 case CMD_2a :
2269 int i = 1;
2270 style.alpha[i] = !p.IsEmpty()
2271 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2272 : org.alpha[i];
2273 break;
2275 case CMD_3a :
2277 int i = 2;
2278 style.alpha[i] = !p.IsEmpty()
2279 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2280 : org.alpha[i];
2281 break;
2283 case CMD_4a :
2285 int i = 3;
2286 style.alpha[i] = !p.IsEmpty()
2287 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2288 : org.alpha[i];
2289 break;
2291 case CMD_alpha:
2293 for(int i = 0; i < 4; i++)
2295 style.alpha[i] = !p.IsEmpty()
2296 ? (BYTE)CalcAnimation(wcstol(p, NULL, 16), style.alpha[i], fAnimate)
2297 : org.alpha[i];
2299 break;
2301 case CMD_an:
2303 int n = wcstol(p, NULL, 10);
2304 if(sub->m_scrAlignment < 0)
2305 sub->m_scrAlignment = (n > 0 && n < 10) ? n : org.scrAlignment;
2306 break;
2308 case CMD_a:
2310 int n = wcstol(p, NULL, 10);
2311 if(sub->m_scrAlignment < 0)
2312 sub->m_scrAlignment = (n > 0 && n < 12) ? ((((n-1)&3)+1)+((n&4)?6:0)+((n&8)?3:0)) : org.scrAlignment;
2313 break;
2315 case CMD_blur:
2317 double n = CalcAnimation(wcstod(p, NULL), style.fGaussianBlur, fAnimate);
2318 style.fGaussianBlur = !p.IsEmpty()
2319 ? (n < 0 ? 0 : n)
2320 : org.fGaussianBlur;
2321 break;
2323 case CMD_bord:
2325 double dst = wcstod(p, NULL);
2326 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2327 style.outlineWidthX = !p.IsEmpty()
2328 ? (nx < 0 ? 0 : nx)
2329 : org.outlineWidthX;
2330 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2331 style.outlineWidthY = !p.IsEmpty()
2332 ? (ny < 0 ? 0 : ny)
2333 : org.outlineWidthY;
2334 break;
2336 case CMD_be:
2338 int n = (int)(CalcAnimation(wcstod(p, NULL), style.fBlur, fAnimate)+0.5);
2339 style.fBlur = !p.IsEmpty()
2341 : org.fBlur;
2342 break;
2344 case CMD_b:
2346 int n = wcstol(p, NULL, 10);
2347 style.fontWeight = !p.IsEmpty()
2348 ? (n == 0 ? FW_NORMAL : n == 1 ? FW_BOLD : n >= 100 ? n : org.fontWeight)
2349 : org.fontWeight;
2350 break;
2352 case CMD_clip:
2353 case CMD_iclip:
2355 bool invert = (cmd_type == CMD_iclip);
2356 if(params.GetCount() == 1 && !sub->m_pClipper)
2358 sub->m_pClipper.reset( new CClipper(params[0], CSize(m_size.cx>>3, m_size.cy>>3), sub->m_scalex, sub->m_scaley, invert) );
2360 else if(params.GetCount() == 2 && !sub->m_pClipper)
2362 int scale = max(wcstol(p, NULL, 10), 1);
2363 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) );
2365 else if(params.GetCount() == 4)
2367 CRect r;
2368 sub->m_clipInverse = invert;
2369 r.SetRect(
2370 wcstod(params[0], NULL)+0.5,
2371 wcstod(params[1], NULL)+0.5,
2372 wcstod(params[2], NULL)+0.5,
2373 wcstod(params[3], NULL)+0.5);
2374 CPoint o(0, 0);
2375 if(sub->m_relativeTo == 1) // TODO: this should also apply to the other two clippings above
2377 o.x = m_vidrect.left>>3;
2378 o.y = m_vidrect.top>>3;
2380 sub->m_clip.SetRect(
2381 (int)CalcAnimation(sub->m_scalex*r.left + o.x, sub->m_clip.left, fAnimate),
2382 (int)CalcAnimation(sub->m_scaley*r.top + o.y, sub->m_clip.top, fAnimate),
2383 (int)CalcAnimation(sub->m_scalex*r.right + o.x, sub->m_clip.right, fAnimate),
2384 (int)CalcAnimation(sub->m_scaley*r.bottom + o.y, sub->m_clip.bottom, fAnimate));
2386 break;
2388 case CMD_c:
2390 DWORD c = wcstol(p, NULL, 16);
2391 style.colors[0] = !p.IsEmpty()
2392 ? (((int)CalcAnimation(c&0xff, style.colors[0]&0xff, fAnimate))&0xff
2393 |((int)CalcAnimation(c&0xff00, style.colors[0]&0xff00, fAnimate))&0xff00
2394 |((int)CalcAnimation(c&0xff0000, style.colors[0]&0xff0000, fAnimate))&0xff0000)
2395 : org.colors[0];
2396 break;
2398 case CMD_fade:
2399 case CMD_fad:
2401 sub->m_fAnimated2 = true;
2402 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])
2404 if(Effect* e = new Effect)
2406 for(int i = 0; i < 3; i++)
2407 e->param[i] = wcstol(params[i], NULL, 10);
2408 for(int i = 0; i < 4; i++)
2409 e->t[i] = wcstol(params[3+i], NULL, 10);
2410 sub->m_effects[EF_FADE] = e;
2413 else if(params.GetCount() == 2 && !sub->m_effects[EF_FADE]) // {\fad(t1=t[1], t2=t[2])
2415 if(Effect* e = new Effect)
2417 e->param[0] = e->param[2] = 0xff;
2418 e->param[1] = 0x00;
2419 for(int i = 1; i < 3; i++)
2420 e->t[i] = wcstol(params[i-1], NULL, 10);
2421 e->t[0] = e->t[3] = -1; // will be substituted with "start" and "end"
2422 sub->m_effects[EF_FADE] = e;
2425 break;
2427 case CMD_fax:
2429 style.fontShiftX = !p.IsEmpty()
2430 ? CalcAnimation(wcstod(p, NULL), style.fontShiftX, fAnimate)
2431 : org.fontShiftX;
2432 break;
2434 case CMD_fay:
2436 style.fontShiftY = !p.IsEmpty()
2437 ? CalcAnimation(wcstod(p, NULL), style.fontShiftY, fAnimate)
2438 : org.fontShiftY;
2439 break;
2441 case CMD_fe:
2443 int n = wcstol(p, NULL, 10);
2444 style.charSet = !p.IsEmpty()
2446 : org.charSet;
2447 break;
2449 case CMD_fn:
2451 if(!p.IsEmpty() && p != L'0')
2452 style.fontName = CString(p).Trim();
2453 else
2454 style.fontName = org.fontName;
2455 break;
2457 case CMD_frx:
2459 style.fontAngleX = !p.IsEmpty()
2460 ? CalcAnimation(wcstod(p, NULL), style.fontAngleX, fAnimate)
2461 : org.fontAngleX;
2462 break;
2464 case CMD_fry:
2466 style.fontAngleY = !p.IsEmpty()
2467 ? CalcAnimation(wcstod(p, NULL), style.fontAngleY, fAnimate)
2468 : org.fontAngleY;
2469 break;
2471 case CMD_frz:
2472 case CMD_fr:
2474 style.fontAngleZ = !p.IsEmpty()
2475 ? CalcAnimation(wcstod(p, NULL), style.fontAngleZ, fAnimate)
2476 : org.fontAngleZ;
2477 break;
2479 case CMD_fscx:
2481 double n = CalcAnimation(wcstod(p, NULL), style.fontScaleX, fAnimate);
2482 style.fontScaleX = !p.IsEmpty()
2483 ? ((n < 0) ? 0 : n)
2484 : org.fontScaleX;
2485 break;
2487 case CMD_fscy:
2489 double n = CalcAnimation(wcstod(p, NULL), style.fontScaleY, fAnimate);
2490 style.fontScaleY = !p.IsEmpty()
2491 ? ((n < 0) ? 0 : n)
2492 : org.fontScaleY;
2493 break;
2495 case CMD_fsc:
2497 style.fontScaleX = org.fontScaleX;
2498 style.fontScaleY = org.fontScaleY;
2499 break;
2501 case CMD_fsp:
2503 style.fontSpacing = !p.IsEmpty()
2504 ? CalcAnimation(wcstod(p, NULL), style.fontSpacing, fAnimate)
2505 : org.fontSpacing;
2506 break;
2508 case CMD_fs:
2510 if(!p.IsEmpty())
2512 if(p[0] == L'-' || p[0] == L'+')
2514 double n = CalcAnimation(style.fontSize + style.fontSize*wcstod(p, NULL)/10, style.fontSize, fAnimate);
2515 style.fontSize = (n > 0) ? n : org.fontSize;
2517 else
2519 double n = CalcAnimation(wcstod(p, NULL), style.fontSize, fAnimate);
2520 style.fontSize = (n > 0) ? n : org.fontSize;
2523 else
2525 style.fontSize = org.fontSize;
2527 break;
2529 case CMD_i:
2531 int n = wcstol(p, NULL, 10);
2532 style.fItalic = !p.IsEmpty()
2533 ? (n == 0 ? false : n == 1 ? true : org.fItalic)
2534 : org.fItalic;
2535 break;
2537 case CMD_kt:
2539 m_kstart = !p.IsEmpty()
2540 ? wcstod(p, NULL)*10
2541 : 0;
2542 m_kend = m_kstart;
2543 break;
2544 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2546 case CMD_kf:
2547 case CMD_K:
2549 m_ktype = 1;
2550 m_kstart = m_kend;
2551 m_kend += !p.IsEmpty()
2552 ? wcstod(p, NULL)*10
2553 : 1000;
2554 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2555 break;
2557 case CMD_ko:
2559 m_ktype = 2;
2560 m_kstart = m_kend;
2561 m_kend += !p.IsEmpty()
2562 ? wcstod(p, NULL)*10
2563 : 1000;
2564 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2565 break;
2567 case CMD_k:
2569 m_ktype = 0;
2570 m_kstart = m_kend;
2571 m_kend += !p.IsEmpty()
2572 ? wcstod(p, NULL)*10
2573 : 1000;
2574 sub->m_fAnimated2 = true;//fix me: define m_fAnimated m_fAnimated2 strictly
2575 break;
2577 case CMD_move: // {\move(x1=param[0], y1=param[1], x2=param[2], y2=param[3][, t1=t[0], t2=t[1]])}
2579 if((params.GetCount() == 4 || params.GetCount() == 6) && !sub->m_effects[EF_MOVE])
2581 if(Effect* e = new Effect)
2583 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2584 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2585 e->param[2] = (int)(sub->m_scalex*wcstod(params[2], NULL)*8);
2586 e->param[3] = (int)(sub->m_scaley*wcstod(params[3], NULL)*8);
2587 e->t[0] = e->t[1] = -1;
2588 if(params.GetCount() == 6)
2590 for(int i = 0; i < 2; i++)
2591 e->t[i] = wcstol(params[4+i], NULL, 10);
2593 sub->m_effects[EF_MOVE] = e;
2594 sub->m_fAnimated2 = true;
2597 break;
2599 case CMD_org: // {\org(x=param[0], y=param[1])}
2601 if(params.GetCount() == 2 && !sub->m_effects[EF_ORG])
2603 if(Effect* e = new Effect)
2605 e->param[0] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2606 e->param[1] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2607 sub->m_effects[EF_ORG] = e;
2610 break;
2612 case CMD_pbo:
2614 m_polygonBaselineOffset = wcstol(p, NULL, 10);
2615 break;
2617 case CMD_pos:
2619 if(params.GetCount() == 2 && !sub->m_effects[EF_MOVE])
2621 if(Effect* e = new Effect)
2623 e->param[0] = e->param[2] = (int)(sub->m_scalex*wcstod(params[0], NULL)*8);
2624 e->param[1] = e->param[3] = (int)(sub->m_scaley*wcstod(params[1], NULL)*8);
2625 e->t[0] = e->t[1] = 0;
2626 sub->m_effects[EF_MOVE] = e;
2629 break;
2631 case CMD_p:
2633 int n = wcstol(p, NULL, 10);
2634 m_nPolygon = (n <= 0 ? 0 : n);
2635 break;
2637 case CMD_q:
2639 int n = wcstol(p, NULL, 10);
2640 sub->m_wrapStyle = !p.IsEmpty() && (0 <= n && n <= 3)
2642 : m_defaultWrapStyle;
2643 break;
2645 case CMD_r:
2647 STSStyle* val;
2648 style = (!p.IsEmpty() && m_styles.Lookup(WToT(p), val) && val) ? *val : org;
2649 break;
2651 case CMD_shad:
2653 double dst = wcstod(p, NULL);
2654 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2655 style.shadowDepthX = !p.IsEmpty()
2656 ? (nx < 0 ? 0 : nx)
2657 : org.shadowDepthX;
2658 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2659 style.shadowDepthY = !p.IsEmpty()
2660 ? (ny < 0 ? 0 : ny)
2661 : org.shadowDepthY;
2662 break;
2664 case CMD_s:
2666 int n = wcstol(p, NULL, 10);
2667 style.fStrikeOut = !p.IsEmpty()
2668 ? (n == 0 ? false : n == 1 ? true : org.fStrikeOut)
2669 : org.fStrikeOut;
2670 break;
2672 case CMD_t: // \t([<t1>,<t2>,][<accel>,]<style modifiers>)
2674 CStringW param;
2675 m_animStart = m_animEnd = 0;
2676 m_animAccel = 1;
2677 if(params.GetCount() == 1)
2679 param = params[0];
2681 else if(params.GetCount() == 2)
2683 m_animAccel = wcstod(params[0], NULL);
2684 param = params[1];
2686 else if(params.GetCount() == 3)
2688 m_animStart = (int)wcstod(params[0], NULL);
2689 m_animEnd = (int)wcstod(params[1], NULL);
2690 param = params[2];
2692 else if(params.GetCount() == 4)
2694 m_animStart = wcstol(params[0], NULL, 10);
2695 m_animEnd = wcstol(params[1], NULL, 10);
2696 m_animAccel = wcstod(params[2], NULL);
2697 param = params[3];
2699 ParseSSATag(sub, assTag.embeded, style, org, true);
2700 sub->m_fAnimated = true;
2701 sub->m_fAnimated2 = true;
2702 break;
2704 case CMD_u:
2706 int n = wcstol(p, NULL, 10);
2707 style.fUnderline = !p.IsEmpty()
2708 ? (n == 0 ? false : n == 1 ? true : org.fUnderline)
2709 : org.fUnderline;
2710 break;
2712 case CMD_xbord:
2714 double dst = wcstod(p, NULL);
2715 double nx = CalcAnimation(dst, style.outlineWidthX, fAnimate);
2716 style.outlineWidthX = !p.IsEmpty()
2717 ? (nx < 0 ? 0 : nx)
2718 : org.outlineWidthX;
2719 break;
2721 case CMD_xshad:
2723 double dst = wcstod(p, NULL);
2724 double nx = CalcAnimation(dst, style.shadowDepthX, fAnimate);
2725 style.shadowDepthX = !p.IsEmpty()
2726 ? nx
2727 : org.shadowDepthX;
2728 break;
2730 case CMD_ybord:
2732 double dst = wcstod(p, NULL);
2733 double ny = CalcAnimation(dst, style.outlineWidthY, fAnimate);
2734 style.outlineWidthY = !p.IsEmpty()
2735 ? (ny < 0 ? 0 : ny)
2736 : org.outlineWidthY;
2737 break;
2739 case CMD_yshad:
2741 double dst = wcstod(p, NULL);
2742 double ny = CalcAnimation(dst, style.shadowDepthY, fAnimate);
2743 style.shadowDepthY = !p.IsEmpty()
2744 ? ny
2745 : org.shadowDepthY;
2746 break;
2748 default:
2749 break;
2752 return(true);
2755 bool CRenderedTextSubtitle::ParseSSATag(CSubtitle* sub, const CStringW& str, STSStyle& style, const STSStyle& org, bool fAnimate)
2757 if(!sub) return(false);
2759 SharedPtrConstAssTagList assTags;
2760 AssTagListMruCache *ass_tag_cache = CacheManager::GetAssTagListMruCache();
2761 POSITION pos = ass_tag_cache->Lookup(str);
2762 if (pos==NULL)
2764 AssTagList *tmp = new AssTagList();
2765 ParseSSATag(tmp, str);
2766 assTags.reset(tmp);
2767 ass_tag_cache->UpdateCache(str, assTags);
2769 else
2771 assTags = ass_tag_cache->GetAt(pos);
2772 ass_tag_cache->UpdateCache( pos );
2774 return ParseSSATag(sub, *assTags, style, org, fAnimate);
2777 bool CRenderedTextSubtitle::ParseHtmlTag(CSubtitle* sub, CStringW str, STSStyle& style, STSStyle& org)
2779 if(str.Find(L"!--") == 0)
2780 return(true);
2781 bool fClosing = str[0] == L'/';
2782 str.Trim(L" /");
2783 int i = str.Find(L' ');
2784 if(i < 0) i = str.GetLength();
2785 CStringW tag = str.Left(i).MakeLower();
2786 str = str.Mid(i).Trim();
2787 CAtlArray<CStringW> attribs, params;
2788 while((i = str.Find(L'=')) > 0)
2790 attribs.Add(str.Left(i).Trim().MakeLower());
2791 str = str.Mid(i+1);
2792 for(i = 0; _istspace(str[i]); i++);
2793 str = str.Mid(i);
2794 if(str[0] == L'\"') {str = str.Mid(1); i = str.Find(L'\"');}
2795 else i = str.Find(L' ');
2796 if(i < 0) i = str.GetLength();
2797 params.Add(str.Left(i).Trim().MakeLower());
2798 str = str.Mid(i+1);
2800 if(tag == L"text")
2802 else if(tag == L"b" || tag == L"strong")
2803 style.fontWeight = !fClosing ? FW_BOLD : org.fontWeight;
2804 else if(tag == L"i" || tag == L"em")
2805 style.fItalic = !fClosing ? true : org.fItalic;
2806 else if(tag == L"u")
2807 style.fUnderline = !fClosing ? true : org.fUnderline;
2808 else if(tag == L"s" || tag == L"strike" || tag == L"del")
2809 style.fStrikeOut = !fClosing ? true : org.fStrikeOut;
2810 else if(tag == L"font")
2812 if(!fClosing)
2814 for(size_t i = 0; i < attribs.GetCount(); i++)
2816 if(params[i].IsEmpty()) continue;
2817 int nColor = -1;
2818 if(attribs[i] == L"face")
2820 style.fontName = params[i];
2822 else if(attribs[i] == L"size")
2824 if(params[i][0] == L'+')
2825 style.fontSize += wcstol(params[i], NULL, 10);
2826 else if(params[i][0] == L'-')
2827 style.fontSize -= wcstol(params[i], NULL, 10);
2828 else
2829 style.fontSize = wcstol(params[i], NULL, 10);
2831 else if(attribs[i] == L"color")
2833 nColor = 0;
2835 else if(attribs[i] == L"outline-color")
2837 nColor = 2;
2839 else if(attribs[i] == L"outline-level")
2841 style.outlineWidthX = style.outlineWidthY = wcstol(params[i], NULL, 10);
2843 else if(attribs[i] == L"shadow-color")
2845 nColor = 3;
2847 else if(attribs[i] == L"shadow-level")
2849 style.shadowDepthX = style.shadowDepthY = wcstol(params[i], NULL, 10);
2851 if(nColor >= 0 && nColor < 4)
2853 CString key = WToT(params[i]).TrimLeft(L'#');
2854 DWORD val;
2855 if(g_colors.Lookup(key, val))
2856 style.colors[nColor] = val;
2857 else if((style.colors[nColor] = _tcstol(key, NULL, 16)) == 0)
2858 style.colors[nColor] = 0x00ffffff; // default is white
2859 style.colors[nColor] = ((style.colors[nColor]>>16)&0xff)|((style.colors[nColor]&0xff)<<16)|(style.colors[nColor]&0x00ff00);
2863 else
2865 style.fontName = org.fontName;
2866 style.fontSize = org.fontSize;
2867 memcpy(style.colors, org.colors, sizeof(style.colors));
2870 else if(tag == L"k" && attribs.GetCount() == 1 && attribs[0] == L"t")
2872 m_ktype = 1;
2873 m_kstart = m_kend;
2874 m_kend += wcstol(params[0], NULL, 10);
2876 else
2877 return(false);
2878 return(true);
2881 double CRenderedTextSubtitle::CalcAnimation(double dst, double src, bool fAnimate)
2883 int s = m_animStart ? m_animStart : 0;
2884 int e = m_animEnd ? m_animEnd : m_delay;
2885 if(fabs(dst-src) >= 0.0001 && fAnimate)
2887 if(m_time < s) dst = src;
2888 else if(s <= m_time && m_time < e)
2890 double t = pow(1.0 * (m_time - s) / (e - s), m_animAccel);
2891 dst = (1 - t) * src + t * dst;
2893 // else dst = dst;
2895 return(dst);
2898 CSubtitle* CRenderedTextSubtitle::GetSubtitle(int entry)
2900 CSubtitle* sub;
2901 if(m_subtitleCache.Lookup(entry, sub))
2903 if(sub->m_fAnimated) {delete sub; sub = NULL;}
2904 else return(sub);
2906 sub = new CSubtitle();
2907 if(!sub) return(NULL);
2908 CStringW str = GetStrW(entry, true);
2909 STSStyle stss, orgstss;
2910 GetStyle(entry, &stss);
2911 if (stss.fontScaleX == stss.fontScaleY && m_dPARCompensation != 1.0)
2913 switch(m_ePARCompensationType)
2915 case EPCTUpscale:
2916 if (m_dPARCompensation < 1.0)
2917 stss.fontScaleY /= m_dPARCompensation;
2918 else
2919 stss.fontScaleX *= m_dPARCompensation;
2920 break;
2921 case EPCTDownscale:
2922 if (m_dPARCompensation < 1.0)
2923 stss.fontScaleX *= m_dPARCompensation;
2924 else
2925 stss.fontScaleY /= m_dPARCompensation;
2926 break;
2927 case EPCTAccurateSize:
2928 stss.fontScaleX *= m_dPARCompensation;
2929 break;
2932 orgstss = stss;
2933 sub->m_clip.SetRect(0, 0, m_size.cx>>3, m_size.cy>>3);
2934 sub->m_scrAlignment = -stss.scrAlignment;
2935 sub->m_wrapStyle = m_defaultWrapStyle;
2936 sub->m_fAnimated = false;
2937 sub->m_relativeTo = stss.relativeTo;
2938 sub->m_scalex = m_dstScreenSize.cx > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Width() : m_size.cx) / (m_dstScreenSize.cx*8) : 1.0;
2939 sub->m_scaley = m_dstScreenSize.cy > 0 ? 1.0 * (stss.relativeTo == 1 ? m_vidrect.Height() : m_size.cy) / (m_dstScreenSize.cy*8) : 1.0;
2940 m_animStart = m_animEnd = 0;
2941 m_animAccel = 1;
2942 m_ktype = m_kstart = m_kend = 0;
2943 m_nPolygon = 0;
2944 m_polygonBaselineOffset = 0;
2945 ParseEffect(sub, m_entries.GetAt(entry).effect);
2946 while(!str.IsEmpty())
2948 bool fParsed = false;
2949 int i;
2950 if(str[0] == L'{' && (i = str.Find(L'}')) > 0)
2952 if(fParsed = ParseSSATag(sub, str.Mid(1, i-1), stss, orgstss))
2953 str = str.Mid(i+1);
2955 else if(str[0] == L'<' && (i = str.Find(L'>')) > 0)
2957 if(fParsed = ParseHtmlTag(sub, str.Mid(1, i-1), stss, orgstss))
2958 str = str.Mid(i+1);
2960 if(fParsed)
2962 i = str.FindOneOf(L"{<");
2963 if(i < 0) i = str.GetLength();
2964 if(i == 0) continue;
2966 else
2968 i = str.Mid(1).FindOneOf(L"{<");
2969 if(i < 0) i = str.GetLength()-1;
2970 i++;
2972 STSStyle tmp = stss;
2973 tmp.fontSize = sub->m_scaley*tmp.fontSize*64;
2974 tmp.fontSpacing = sub->m_scalex*tmp.fontSpacing*64;
2975 tmp.outlineWidthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2976 tmp.outlineWidthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2977 tmp.shadowDepthX *= (m_fScaledBAS ? sub->m_scalex : 1) * 8;
2978 tmp.shadowDepthY *= (m_fScaledBAS ? sub->m_scaley : 1) * 8;
2979 FwSTSStyle fw_tmp(tmp);
2980 if(m_nPolygon)
2982 ParsePolygon(sub, str.Left(i), fw_tmp);
2984 else
2986 ParseString(sub, str.Left(i), fw_tmp);
2988 str = str.Mid(i);
2990 if( sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL] )
2991 sub->m_fAnimated2 = true;
2992 // just a "work-around" solution... in most cases nobody will want to use \org together with moving but without rotating the subs
2993 if(sub->m_effects[EF_ORG] && (sub->m_effects[EF_MOVE] || sub->m_effects[EF_BANNER] || sub->m_effects[EF_SCROLL]))
2994 sub->m_fAnimated = true;
2995 sub->m_scrAlignment = abs(sub->m_scrAlignment);
2996 STSEntry stse = m_entries.GetAt(entry);
2997 CRect marginRect = stse.marginRect;
2998 if(marginRect.left == 0) marginRect.left = orgstss.marginRect.get().left;
2999 if(marginRect.top == 0) marginRect.top = orgstss.marginRect.get().top;
3000 if(marginRect.right == 0) marginRect.right = orgstss.marginRect.get().right;
3001 if(marginRect.bottom == 0) marginRect.bottom = orgstss.marginRect.get().bottom;
3002 marginRect.left = (int)(sub->m_scalex*marginRect.left*8);
3003 marginRect.top = (int)(sub->m_scaley*marginRect.top*8);
3004 marginRect.right = (int)(sub->m_scalex*marginRect.right*8);
3005 marginRect.bottom = (int)(sub->m_scaley*marginRect.bottom*8);
3006 if(stss.relativeTo == 1)
3008 marginRect.left += m_vidrect.left;
3009 marginRect.top += m_vidrect.top;
3010 marginRect.right += m_size.cx - m_vidrect.right;
3011 marginRect.bottom += m_size.cy - m_vidrect.bottom;
3013 sub->CreateClippers(m_size);
3014 sub->MakeLines(m_size, marginRect);
3015 m_subtitleCache[entry] = sub;
3016 return(sub);
3021 STDMETHODIMP CRenderedTextSubtitle::NonDelegatingQueryInterface(REFIID riid, void** ppv)
3023 CheckPointer(ppv, E_POINTER);
3024 *ppv = NULL;
3025 return
3026 QI(IPersist)
3027 QI(ISubStream)
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(SubPicDesc& spd, 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, spd.w, spd.h);
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, spd.w, (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 XySubRenderFrameCreater *render_frame_creater = XySubRenderFrameCreater::GetDefaultCreater();
3362 if(m_size != CSize(spd.w*8, spd.h*8) || m_vidrect != CRect(spd.vidrect.left*8, spd.vidrect.top*8, spd.vidrect.right*8, spd.vidrect.bottom*8))
3364 Init(CSize(spd.w, spd.h), spd.vidrect);
3365 render_frame_creater->SetOutputRect(CRect(0,0,spd.w,spd.h));
3366 render_frame_creater->SetClipRect(CRect(0,0,spd.w,spd.h));
3368 XyColorSpace color_space = XY_CS_ARGB;
3369 switch(spd.type)
3371 case MSP_AYUV_PLANAR:
3372 color_space = XY_CS_AYUV_PLANAR;
3373 break;
3374 case MSP_XY_AUYV:
3375 color_space = XY_CS_AUYV;
3376 break;
3377 case MSP_AYUV:
3378 color_space = XY_CS_AYUV;
3379 break;
3380 default:
3381 color_space = XY_CS_ARGB;
3382 break;
3384 render_frame_creater->SetColorSpace(color_space);
3386 CSubtitle2List sub2List;
3387 HRESULT hr = ParseScript(spd, rt, fps, &sub2List);
3388 if(hr!=S_OK)
3390 return hr;
3393 CompositeDrawItemListList compDrawItemListList;
3394 DoRender(spd, sub2List, &rectList, &compDrawItemListList);
3396 XySubRenderFrame *sub_render_frame;
3397 CompositeDrawItem::Draw(&sub_render_frame, compDrawItemListList);
3399 if (sub_render_frame)
3401 SharedPtrXySubRenderFrame auto_cleaner(sub_render_frame);
3402 int count = 0;
3403 hr = sub_render_frame->GetBitmapCount(&count);
3404 if(FAILED(hr))
3406 return hr;
3408 int color_space;
3409 hr = sub_render_frame->GetXyColorSpace(&color_space);
3410 if(FAILED(hr))
3412 return hr;
3414 for (int i=0;i<count;i++)
3416 POINT pos;
3417 SIZE size;
3418 LPCVOID pixels;
3419 int pitch;
3420 hr = sub_render_frame->GetBitmap(i, NULL, &pos, &size, &pixels, &pitch );
3421 if(FAILED(hr))
3423 return hr;
3425 if (color_space==XY_CS_AYUV_PLANAR)
3427 XyPlannerFormatExtra plans;
3428 hr = sub_render_frame->GetBitmapExtra(i, &plans);
3429 if(FAILED(hr))
3431 return hr;
3433 XyBitmap::AlphaBltPlannar(spd, pos, size, plans, pitch);
3435 else
3437 XyBitmap::AlphaBltPack(spd, pos, size, pixels, pitch);
3441 return (!rectList.IsEmpty()) ? S_OK : S_FALSE;
3444 void CRenderedTextSubtitle::DoRender( SubPicDesc& spd, const CSubtitle2List& sub2List,
3445 CAtlList<CRect> *rectList, CompositeDrawItemListList *compDrawItemListList /*output*/)
3447 //check input and log error
3448 POSITION pos=sub2List.GetHeadPosition();
3449 while ( pos!=NULL )
3451 const CSubtitle2& sub2 = sub2List.GetNext(pos);
3452 CompositeDrawItemList& compDrawItemList = compDrawItemListList->GetAt(compDrawItemListList->AddTail());
3453 RenderOneSubtitle(spd, sub2, rectList, &compDrawItemList);
3457 void CRenderedTextSubtitle::RenderOneSubtitle( SubPicDesc& spd, const CSubtitle2& sub2,
3458 CAtlList<CRect>* rectList, CompositeDrawItemList* compDrawItemList /*output*/)
3460 CSubtitle* s = sub2.s;
3461 const CRect& clipRect = sub2.clipRect;
3462 const CPoint& org = sub2.org;
3463 const CPoint& org2 = sub2.org2;
3464 const CPoint& p2 = sub2.p;
3465 int alpha = sub2.alpha;
3466 int time = sub2.time;
3467 if(!s) return;
3469 SharedPtrCClipperPaintMachine clipper( new CClipperPaintMachine(s->m_pClipper) );
3471 CRect iclipRect[4];
3472 iclipRect[0] = CRect(0, 0, spd.w, clipRect.top);
3473 iclipRect[1] = CRect(0, clipRect.top, clipRect.left, clipRect.bottom);
3474 iclipRect[2] = CRect(clipRect.right, clipRect.top, spd.w, clipRect.bottom);
3475 iclipRect[3] = CRect(0, clipRect.bottom, spd.w, spd.h);
3476 CRect bbox2(0,0,0,0);
3477 POSITION pos = s->GetHeadLinePosition();
3478 CPoint p = p2;
3479 while(pos)
3481 CLine* l = s->GetNextLine(pos);
3482 p.x = (s->m_scrAlignment%3) == 1 ? org.x
3483 : (s->m_scrAlignment%3) == 0 ? org.x - l->m_width
3484 : org.x - (l->m_width/2);
3486 CompositeDrawItemList tmpCompDrawItemList;
3487 if (s->m_clipInverse)
3489 CompositeDrawItemList tmp1,tmp2,tmp3,tmp4;
3490 for (int i=0;i<l->GetWordCount();i++)
3492 tmp1.AddTail();
3493 tmp2.AddTail();
3494 tmp3.AddTail();
3495 tmp4.AddTail();
3497 bbox2 |= l->PaintAll(&tmp1, spd, iclipRect[0], clipper, p, org2, time, alpha);
3498 bbox2 |= l->PaintAll(&tmp2, spd, iclipRect[1], clipper, p, org2, time, alpha);
3499 bbox2 |= l->PaintAll(&tmp3, spd, iclipRect[2], clipper, p, org2, time, alpha);
3500 bbox2 |= l->PaintAll(&tmp4, spd, iclipRect[3], clipper, p, org2, time, alpha);
3501 tmpCompDrawItemList.AddTailList(&tmp1);
3502 tmpCompDrawItemList.AddTailList(&tmp2);
3503 tmpCompDrawItemList.AddTailList(&tmp3);
3504 tmpCompDrawItemList.AddTailList(&tmp4);
3506 else
3508 for (int i=0;i<l->GetWordCount();i++)
3510 tmpCompDrawItemList.AddTail();
3512 bbox2 |= l->PaintAll(&tmpCompDrawItemList, spd, clipRect, clipper, p, org2, time, alpha);
3514 compDrawItemList->AddTailList(&tmpCompDrawItemList);
3515 p.y += l->m_ascent + l->m_descent;
3517 rectList->AddTail(bbox2);
3520 STDMETHODIMP CRenderedTextSubtitle::Render(SubPicDesc& spd, REFERENCE_TIME rt, double fps, RECT& bbox)
3522 CAtlList<CRect> rectList;
3523 HRESULT result = RenderEx(spd, rt, fps, rectList);
3524 POSITION pos = rectList.GetHeadPosition();
3525 CRect bbox2(0,0,0,0);
3526 while(pos!=NULL)
3528 bbox2 |= rectList.GetNext(pos);
3530 bbox = bbox2;
3531 return result;
3534 // IPersist
3536 STDMETHODIMP CRenderedTextSubtitle::GetClassID(CLSID* pClassID)
3538 return pClassID ? *pClassID = __uuidof(this), S_OK : E_POINTER;
3541 // ISubStream
3543 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStreamCount()
3545 return(1);
3548 STDMETHODIMP CRenderedTextSubtitle::GetStreamInfo(int iStream, WCHAR** ppName, LCID* pLCID)
3550 if(iStream != 0) return E_INVALIDARG;
3551 if(ppName)
3553 if(!(*ppName = (WCHAR*)CoTaskMemAlloc((m_name.GetLength()+1)*sizeof(WCHAR))))
3554 return E_OUTOFMEMORY;
3555 wcscpy(*ppName, CStringW(m_name));
3557 if(pLCID)
3559 *pLCID = 0; // TODO
3561 return S_OK;
3564 STDMETHODIMP_(int) CRenderedTextSubtitle::GetStream()
3566 return(0);
3569 STDMETHODIMP CRenderedTextSubtitle::SetStream(int iStream)
3571 return iStream == 0 ? S_OK : E_FAIL;
3574 STDMETHODIMP CRenderedTextSubtitle::Reload()
3576 CFileStatus s;
3577 if(!CFile::GetStatus(m_path, s)) return E_FAIL;
3578 return !m_path.IsEmpty() && Open(m_path, DEFAULT_CHARSET) ? S_OK : E_FAIL;
3581 STDMETHODIMP_(bool) CRenderedTextSubtitle::IsColorTypeSupported( int type )
3583 return type==MSP_AYUV_PLANAR ||
3584 type==MSP_AYUV ||
3585 type==MSP_XY_AUYV ||
3586 type==MSP_RGBA;