2 Copyright 2008 Mark Calderbank, 2020 Chris Tallon
4 This file is part of VOMP.
6 VOMP is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 VOMP is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with VOMP. If not, see <https://www.gnu.org/licenses/>.
19 /* Sections of code and general methods adopted from VDR version 1.6.0
20 * dvbsubtitle.c (GPL version 2 or later)
21 * Original author: Marco Schluessler <marco@lordzodiac.de>
22 * With some input from the "subtitle plugin"
23 * by Pekka Virtanen <pekka.virtanen@sci.fi>
26 /* Reference ETSI EN 300 743 V1.3.1 (2006-11) */
38 #include "osdreceiver.h"
42 #include "dvbsubtitles.h"
44 static const char* TAG = "DVBSubtitles";
46 DVBSubtitleCLUT::DVBSubtitleCLUT()
52 for (int i = 0; i < 4; ++i) palette2.setColour(i, defaultPalette2[i]);
53 for (int i = 0; i < 16; ++i) palette4.setColour(i, defaultPalette4[i]);
54 for (int i = 0; i < 256; ++i) palette8.setColour(i, defaultPalette8[i]);
57 const u4 DVBSubtitleCLUT::defaultPalette2[4] = {
58 0x00000000, 0xFFFFFFFF, 0xFF000000, 0xFF808080
61 const u4 DVBSubtitleCLUT::defaultPalette4[16] = {
62 0x00000000, 0xFFFF0000, 0xFF00FF00, 0xFFFFFF00,
63 0xFF0000FF, 0xFFFF00FF, 0xFF00FFFF, 0xFFFFFFFF,
64 0xFF000000, 0xFF800000, 0xFF008000, 0xFF808000,
65 0xFF000080, 0xFF800080, 0xFF008080, 0xFF808080
68 const u4 DVBSubtitleCLUT::defaultPalette8[256] = {
69 0x00000000, 0x40FF0000, 0x4000FF00, 0x40FFFF00, // 0000 0000
70 0x400000FF, 0x40FF00FF, 0x4000FFFF, 0x40FFFFFF, // 0000 0100
71 0x80000000, 0x80550000, 0x80005500, 0x80555500, // 0000 1000
72 0x80000055, 0x80550055, 0x80005555, 0x80555555, // 0000 1100
73 0xFFAA0000, 0xFFFF0000, 0xFFAA5500, 0xFFFF5500, // 0001 0000
74 0xFFAA0055, 0xFFFF0055, 0xFFAA5555, 0xFFFF5555, // 0001 0100
75 0x80AA0000, 0x80FF0000, 0x80AA5500, 0x80FF5500, // 0001 1000
76 0x80AA0055, 0x80FF0055, 0x80AA5555, 0x80FF5555, // 0001 1100
77 0xFF00AA00, 0xFF55AA00, 0xFF00FF00, 0xFF55FF00, // 0010 0000
78 0xFF00AA55, 0xFF55AA55, 0xFF00FF55, 0xFF55FF55, // 0010 0100
79 0x8000AA00, 0x8055AA00, 0x8000FF00, 0x8055FF00, // 0010 1000
80 0x8000AA55, 0x8055AA55, 0x8000FF55, 0x8055FF55, // 0010 1100
81 0xFFAAAA00, 0xFFFFAA00, 0xFFAAFF00, 0xFFFFFF00, // 0011 0000
82 0xFFAAAA55, 0xFFFFAA55, 0xFFAAFF55, 0xFFFFFF55, // 0011 0100
83 0x80AAAA00, 0x80FFAA00, 0x80AAFF00, 0x80FFFF00, // 0011 1000
84 0x80AAAA55, 0x80FFAA55, 0x80AAFF55, 0x80FFFF55, // 0011 1100
85 0xFF0000AA, 0xFF5500AA, 0xFF0055AA, 0xFF5555AA, // 0100 0000
86 0xFF0000FF, 0xFF5500FF, 0xFF0055FF, 0xFF5555FF, // 0100 0100
87 0x800000AA, 0x805500AA, 0x800055AA, 0x805555AA, // 0100 1000
88 0x800000FF, 0x805500FF, 0x800055FF, 0x805555FF, // 0100 1100
89 0xFFAA00AA, 0xFFFF00AA, 0xFFAA55AA, 0xFFFF55AA, // 0101 0000
90 0xFFAA00FF, 0xFFFF00FF, 0xFFAA55FF, 0xFFFF55FF, // 0101 0100
91 0x80AA00AA, 0x80FF00AA, 0x80AA55AA, 0x80FF55AA, // 0101 1000
92 0x80AA00FF, 0x80FF00FF, 0x80AA55FF, 0x80FF55FF, // 0101 1100
93 0xFF00AAAA, 0xFF55AAAA, 0xFF00FFAA, 0xFF55FFAA, // 0110 0000
94 0xFF00AAFF, 0xFF55AAFF, 0xFF00FFFF, 0xFF55FFFF, // 0110 0100
95 0x8000AAAA, 0x8055AAAA, 0x8000FFAA, 0x8055FFAA, // 0110 1000
96 0x8000AAFF, 0x8055AAFF, 0x8000FFFF, 0x8055FFFF, // 0110 1100
97 0xFFAAAAAA, 0xFFFFAAAA, 0xFFAAFFAA, 0xFFFFFFAA, // 0111 0000
98 0xFFAAAAFF, 0xFFFFAAFF, 0xFFAAFFFF, 0xFFFFFFFF, // 0111 0100
99 0x80AAAAAA, 0x80FFAAAA, 0x80AAFFAA, 0x80FFFFAA, // 0111 1000
100 0x80AAAAFF, 0x80FFAAFF, 0x80AAFFFF, 0x80FFFFFF, // 0111 1100
101 0xFF808080, 0xFFAA8080, 0xFF80AA80, 0xFFAAAA80, // 1000 0000
102 0xFF8080AA, 0xFFAA80AA, 0xFF80AAAA, 0xFFAAAAAA, // 1000 0100
103 0xFF000000, 0xFF2A0000, 0xFF002A00, 0xFF2A2A00, // 1000 1000
104 0xFF00002A, 0xFF2A002A, 0xFF002A2A, 0xFF2A2A2A, // 1000 1100
105 0xFFD58080, 0xFFFF8080, 0xFFD5AA80, 0xFFFFAA80, // 1001 0000
106 0xFFD580AA, 0xFFFF80AA, 0xFFD5AAAA, 0xFFFFAAAA, // 1001 0100
107 0xFF550000, 0xFF7F0000, 0xFF552A00, 0xFF7F2A00, // 1001 1000
108 0xFF55002A, 0xFF7F002A, 0xFF552A2A, 0xFF7F2A2A, // 1001 1100
109 0xFF80D580, 0xFFAAD580, 0xFF80FF80, 0xFFAAFF80, // 1010 0000
110 0xFF80D5AA, 0xFFAAD5AA, 0xFF80FFAA, 0xFFAAFFAA, // 1010 0100
111 0xFF005500, 0xFF2A5500, 0xFF007F00, 0xFF2A7F00, // 1010 1000
112 0xFF00552A, 0xFF2A552A, 0xFF007F2A, 0xFF2A7F2A, // 1010 1100
113 0xFFD5D580, 0xFFFFD580, 0xFFD5FF80, 0xFFFFFF80, // 1011 0000
114 0xFFD5D5AA, 0xFFFFD5AA, 0xFFD5FFAA, 0xFFFFFFAA, // 1011 0100
115 0xFF555500, 0xFF7F5500, 0xFF557F00, 0xFF7F7F00, // 1011 1000
116 0xFF55552A, 0xFF7F552A, 0xFF557F2A, 0xFF7F7F2A, // 1011 1100
117 0xFF8080D5, 0xFFAA80D5, 0xFF80AAD5, 0xFFAAAAD5, // 1100 0000
118 0xFF8080FF, 0xFFAA80FF, 0xFF80AAFF, 0xFFAAAAFF, // 1100 0100
119 0xFF000055, 0xFF2A0055, 0xFF002A55, 0xFF2A2A55, // 1100 1000
120 0xFF00007F, 0xFF2A007F, 0xFF002A7F, 0xFF2A2A7F, // 1100 1100
121 0xFFD580D5, 0xFFFF80D5, 0xFFD5AAD5, 0xFFFFAAD5, // 1101 0000
122 0xFFD580FF, 0xFFFF80FF, 0xFFD5AAFF, 0xFFFFAAFF, // 1101 0100
123 0xFF550055, 0xFF7F0055, 0xFF552A55, 0xFF7F2A55, // 1101 1000
124 0xFF55007F, 0xFF7F007F, 0xFF552A7F, 0xFF7F2A7F, // 1101 1100
125 0xFF80D5D5, 0xFFAAD5D5, 0xFF80FFD5, 0xFFAAFFD5, // 1110 0000
126 0xFF80D5FF, 0xFFAAD5FF, 0xFF80FFFF, 0xFFAAFFFF, // 1110 0100
127 0xFF005555, 0xFF2A5555, 0xFF007F55, 0xFF2A7F55, // 1110 1000
128 0xFF00557F, 0xFF2A557F, 0xFF007F7F, 0xFF2A7F7F, // 1110 1100
129 0xFFD5D5D5, 0xFFFFD5D5, 0xFFD5FFD5, 0xFFFFFFD5, // 1111 0000
130 0xFFD5D5FF, 0xFFFFD5FF, 0xFFD5FFFF, 0xFFFFFFFF, // 1111 0100
131 0xFF555555, 0xFF7F5555, 0xFF557F55, 0xFF7F7F55, // 1111 1000
132 0xFF55557F, 0xFF7F557F, 0xFF557F7F, 0xFF7F7F7F, // 1111 1100
135 void DVBSubtitleCLUT::setEntry(int bpp, u4 index, u1 Y, u1 Cr, u1 Cb, u1 T)
139 if (Y2 == 0) { Y2 = 16; A = 0; } else A = 255 - T;
142 case 2: palette2.setYCrCbA(index, Y2, Cr, Cb, A); break;
143 case 4: palette4.setYCrCbA(index, Y2, Cr, Cb, A); break;
144 case 8: palette8.setYCrCbA(index, Y2, Cr, Cb, A); break;
148 const Palette& DVBSubtitleCLUT::getPalette(int bpp) const
152 case 2: return palette2; break;
153 case 4: return palette4; break;
154 default: return palette8; break;
158 DVBSubtitleRegion::DVBSubtitleRegion()
164 void DVBSubtitleRegion::setDepth(u4 d)
166 if (d < 4) palette.setBpp(1 << d);
169 DVBSubtitlePage::DVBSubtitlePage()
175 serviceAcquired(false)
178 void DVBSubtitlePage::setState(u1 s)
181 if (state == 1) // Acquisition point - page refresh
182 if (!serviceAcquired) // Service not acquired lets treat this as mode change
184 if (state == 2) // Mode change - new epoch
186 serviceAcquired = true;
189 currentDisplay.clear();
190 pendingDisplay.clear();
195 void DVBSubtitlePage::updateRegionPalettes(const DVBSubtitleCLUT& clut)
197 RegionMap::iterator region;
198 for (region = regions.begin(); region != regions.end(); ++region)
199 if (region->second.CLUTid == clut.CLUTid)
200 region->second.palette = clut.getPalette(region->second.palette.getBpp());
203 DVBSubtitleDisplayDefinition::DVBSubtitleDisplayDefinition()
209 class DVBSubtitleObject
216 DVBSubtitleRegion* region;
217 u4 horizontalPosition;
220 typedef std::vector<struct RegionRef> UseList;
225 void initMapTables();
228 void drawLine(const RegionRef& use, u4 x, u4 y, u1 colour, u4 len);
229 u1 get2Bits(const u1* data, u4& index);
230 u1 get4Bits(const u1* data, u4& index);
231 bool decode2BppCodeString(const u1* data, u4& index, const struct RegionRef& use, u4& x, u4 y);
232 bool decode4BppCodeString(const u1* data, u4& index, const struct RegionRef& use, u4& x, u4 y);
233 bool decode8BppCodeString(const u1* data, u4& index, const struct RegionRef& use, u4& x, u4 y);
235 DVBSubtitleObject(u4 id = 0);
236 void setNonModColourFlag(u1 flag) { nonModColourFlag = flag; }
237 void findWhereUsed(DVBSubtitlePage&);
238 void decodeSubBlock(const u1* data, u4 length, bool even);
241 DVBSubtitleObject::DVBSubtitleObject(u4 id)
244 currentMapTable(NULL),
250 void DVBSubtitleObject::initMapTables()
252 map2to4[0] = 0x0; map2to4[1] = 0x7; map2to4[2] = 0x8; map2to4[3] = 0xF;
253 map2to8[0] = 0x00; map2to8[1] = 0x77; map2to8[2] = 0x88; map2to8[3] = 0xFF;
254 map4to8[0] = 0x00; map4to8[1] = 0x11; map4to8[2] = 0x22; map4to8[3] = 0x33;
255 map4to8[4] = 0x44; map4to8[5] = 0x55; map4to8[6] = 0x66; map4to8[7] = 0x77;
256 map4to8[8] = 0x88; map4to8[9] = 0x99; map4to8[10]= 0xAA; map4to8[11]= 0xBB;
257 map4to8[12]= 0xCC; map4to8[13]= 0xDD; map4to8[14]= 0xEE; map4to8[15]= 0xFF;
260 void DVBSubtitleObject::findWhereUsed(DVBSubtitlePage& page)
263 DVBSubtitlePage::RegionMap::iterator i;
264 for (i = page.regions.begin(); i != page.regions.end(); ++i)
266 DVBSubtitleRegion::ObjectList::iterator j;
267 for (j = i->second.objects.begin(); j != i->second.objects.end(); ++j)
269 if (j->objectID == objectID)
271 struct RegionRef usage;
272 usage.region = &(i->second);
273 usage.horizontalPosition = j->horizontalPosition;
274 usage.verticalPosition = j->verticalPosition;
275 useList.push_back(usage);
281 void DVBSubtitleObject::drawLine(const RegionRef& use, u4 x, u4 y,
284 if (nonModColourFlag && colour == 1) return;
285 x += use.horizontalPosition;
286 y += use.verticalPosition;
287 for (u4 pos = x; pos < x + len; ++pos)
288 use.region->setIndex(pos, y, colour);
291 u1 DVBSubtitleObject::get2Bits(const u1* data, u4& index)
293 u1 result = data[index];
300 return (result >> bitPos) & 0x03;
303 u1 DVBSubtitleObject::get4Bits(const u1* data, u4& index)
305 u1 result = data[index];
316 return result & 0x0F;
319 bool DVBSubtitleObject::decode2BppCodeString(const u1* data, u4& index, const struct RegionRef& use, u4& x, u4 y)
321 u4 rl = 0, colour = 0;
322 u1 code = get2Bits(data, index);
330 code = get2Bits(data, index);
331 if (code & 2) // Switch 1
333 rl = ((code & 1) << 2) + get2Bits(data, index) + 3;
334 colour = get2Bits(data, index);
336 else if (code & 1) rl = 1; // Colour 0
339 code = get2Bits(data, index);
343 return false; // end of 2-bit/pixel_code_string
348 rl = (get2Bits(data, index) << 2) + get2Bits(data, index) + 12;
349 colour = get2Bits(data, index);
352 rl = (get2Bits(data, index) << 6) + (get2Bits(data, index) << 4) +
353 (get2Bits(data, index) << 2) + get2Bits(data, index) + 29;
354 colour = get2Bits(data, index);
359 drawLine(use, x, y, colour, rl);
364 bool DVBSubtitleObject::decode4BppCodeString(const u1* data, u4& index, const struct RegionRef& use, u4& x, u4 y)
366 u4 rl = 0, colour = 0;
367 u1 code = get4Bits(data, index);
375 code = get4Bits(data, index);
376 if (code & 8) // Switch 1
378 if (code & 4) // Switch 2
380 switch (code & 3) // Switch 3
389 rl = get4Bits(data, index) + 9;
390 colour = get4Bits(data, index);
393 rl = (get4Bits(data, index) << 4) + get4Bits(data, index) + 25;
394 colour = get4Bits(data, index);
401 colour = get4Bits(data, index);
406 if (!code) return false; // end of 4-bit/pixel_code_string
407 rl = code + 2; // Colour 0
410 drawLine(use, x, y, colour, rl);
415 bool DVBSubtitleObject::decode8BppCodeString(const u1* data, u4& index, const struct RegionRef& use, u4& x, u4 y)
417 u4 rl = 0, colour = 0;
418 u1 code = data[index++];
426 code = data[index++];
429 colour = data[index++];
431 return false; // else colour 0
433 drawLine(use, x, y, colour, rl);
438 void DVBSubtitleObject::decodeSubBlock(const u1* data, u4 length, bool even)
440 UseList::const_iterator use;
441 for (use = useList.begin(); use != useList.end(); ++use)
443 u4 x = 0; u4 y = even ? 0 : 1; u4 index = 0;
444 while (index < length)
446 switch (data[index++])
449 switch (use->region->palette.getBpp())
451 case 8: currentMapTable = map2to8; break;
452 case 4: currentMapTable = map2to4; break;
453 default: currentMapTable = NULL;
456 while (decode2BppCodeString(data, index, *use,x,y) && index < length);
457 if (!bitPos) index++;
460 if (use->region->palette.getBpp() == 8)
461 currentMapTable = map4to8;
463 currentMapTable = NULL;
465 while (decode4BppCodeString(data, index, *use,x,y) && index < length);
466 if (!bitPos) index++;
469 while (decode8BppCodeString(data, index, *use,x,y) && index < length);
472 map2to4[0] = data[index] >> 4;
473 map2to4[1] = data[index++] & 0x0F;
474 map2to4[2] = data[index] >> 4;
475 map2to4[3] = data[index++] & 0x0F;
478 for (int i = 0; i < 4; i++) map2to8[i] = data[index++];
481 for (int i = 0; i < 16; i++) map4to8[i] = data[index++];
491 static u8 PTSDifference(u8 pts1, u8 pts2)
493 // Assume pts1, pts2 < 2^33; calculate pts1 - pts2
497 return (1LL<<33) + pts1 - pts2;
500 DVBSubtitles::DVBSubtitles(OSDReceiver* tosd)
502 pageOnDisplay(65536),
508 void DVBSubtitles::put(const PESPacket& packet)
510 // Player object play feed thread comes here, via the demuxer
511 // input_mutex only used in put() here, start(), stop() and threadMethod()
512 // So, roll old Thread::mutex/cond into input_mutex?
517 if (packet.getPTS() != PESPacket::PTS_INVALID)
519 worklist.push_back(packet);
520 signalRecalcWLTO = true;
521 LogNT::getInstance()->debug(TAG, "Received packet: PTS: {}, size: {}, type: {}", packet.getPTS(), packet.getSize(), packet.getPacketType());
524 dvbsCond.notify_one();
528 LogNT::getInstance()->debug(TAG, "PUT DROPPING INVALID PACKET: PTS: {}, size: {}, type: {}", packet.getPTS(), packet.getSize(), packet.getPacketType());
531 input_mutex.unlock();
534 bool DVBSubtitles::decodePacket(const PESPacket& packet)
536 const u1* data = packet.getData();
537 u4 packetSize = packet.getSize();
538 if (packetSize < 9) return false;
539 u4 segmentOffset = data[8] + 11;
540 while (packetSize > segmentOffset)
542 if (data[segmentOffset] == 0xFF) return true; // 'End of PES' marker
543 if (data[segmentOffset] != 0x0F) return false; // Out of sync
544 if (packetSize <= segmentOffset + 5) return false; // Packet truncated
545 u1 segmentType = data[segmentOffset + 1];
546 u4 pageID = (data[segmentOffset + 2] << 8)
547 + data[segmentOffset + 3];
548 u4 segmentLength = (data[segmentOffset + 4] << 8)
549 + data[segmentOffset + 5];
550 if (pageOnDisplay == 65536) pageOnDisplay = pageID;
551 if (pageOnDisplay != pageID) return false;
552 if (packetSize <= segmentOffset + 5 + segmentLength) return false;
553 const u1* segmentData = &data[segmentOffset + 6];
554 pages[pageID]; // Create this page if it doesn't exist
555 PageMap::iterator pageEntry = pages.find(pageID);
556 if (pageEntry == pages.end()) return false;
557 DVBSubtitlePage& page = pageEntry->second;
558 if (packet.getPTS() != PESPacket::PTS_INVALID) page.pts = packet.getPTS();
561 case 0x10: // Page composition
563 if (segmentLength < 2) break;
564 page.setState((segmentData[1] & 0x0C) >> 2);
565 if (!page.serviceAcquired) break;
566 u1 pageVersion = (segmentData[1] & 0xF0) >> 4;
567 if (pageVersion == page.version) break; // No update
568 page.version = pageVersion;
569 page.timeout = segmentData[0];
570 page.pendingDisplay.clear();
572 while (segmentLength > parsePos + 5)
574 u1 regionID = segmentData[parsePos];
575 page.regions[regionID]; // Create the region if it doesn't exist
576 DVBSubtitlePage::Coords coords;
577 coords.x = (segmentData[parsePos + 2] << 8) +
578 segmentData[parsePos + 3];
579 coords.y = (segmentData[parsePos + 4] << 8) +
580 segmentData[parsePos + 5];
581 page.pendingDisplay[regionID] = coords;
586 case 0x11: // Region composition
588 if (segmentLength < 10) break;
589 u1 regionID = segmentData[0];
590 page.regions[regionID]; // Create the region if it doesn't exist
591 DVBSubtitlePage::RegionMap::iterator regionEntry;
592 regionEntry = page.regions.find(regionID);
593 if (regionEntry == page.regions.end()) return false;
594 DVBSubtitleRegion& region = regionEntry->second;
595 u1 regionVersion = (segmentData[1] & 0xF0) >> 4;
596 if (regionVersion == region.version) break; // No update
597 region.version = regionVersion;
598 bool regionFillFlag = (segmentData[1] & 0x08) >> 3;
599 u4 regionWidth = (segmentData[2] << 8) + segmentData[3];
600 u4 regionHeight = (segmentData[4] << 8) + segmentData[5];
601 region.setSize(regionWidth, regionHeight);
602 region.level = (segmentData[6] & 0xE0) >> 5;
603 region.setDepth((segmentData[6] & 0x1C) >> 2);
604 region.CLUTid = segmentData[7];
605 page.CLUTs[region.CLUTid]; // Create the CLUT if it doesn't exist
606 DVBSubtitlePage::CLUTMap::iterator clut;
607 clut = page.CLUTs.find(region.CLUTid);
608 if (clut == page.CLUTs.end()) return false;
609 region.palette = clut->second.getPalette(region.palette.getBpp());
610 if (regionFillFlag) switch (region.palette.getBpp())
612 case 2: region.setAllIndices((segmentData[9] & 0x0C) >> 2); break;
613 case 4: region.setAllIndices((segmentData[9] & 0xF0) >> 4); break;
614 case 8: region.setAllIndices(segmentData[8]); break;
616 region.objects.clear();
618 while (segmentLength > parsePos + 5)
620 u4 objectID = (segmentData[parsePos] << 8) +
621 segmentData[parsePos + 1];
622 DVBSubtitleRegion::ObjectRef objref;
623 objref.objectID = objectID;
624 u4 objectType = (segmentData[parsePos + 2] & 0xC0) >> 6;
625 objref.horizontalPosition = ((segmentData[parsePos + 2] & 0x0F) << 8) +
626 segmentData[parsePos + 3];
627 objref.verticalPosition = ((segmentData[parsePos + 4] & 0x0F) << 8) +
628 segmentData[parsePos + 5];
629 if (objectType == 0) region.objects.push_back(objref);
634 case 0x12: // CLUT definition
636 if (segmentLength < 2) break;
637 u1 CLUTid = segmentData[0];
638 DVBSubtitlePage::CLUTMap::iterator clutEntry;
639 clutEntry = page.CLUTs.find(CLUTid);
640 if (clutEntry == page.CLUTs.end()) return false;
641 DVBSubtitleCLUT& clut = clutEntry->second;
642 clut.CLUTid = CLUTid;
643 u1 clutVersion = (segmentData[1] & 0xF0) >> 4;
644 if (clutVersion == clut.version) break; // No update
645 clut.version = clutVersion;
647 while (segmentLength > parsePos + 3)
649 u1 clutEntryID = segmentData[parsePos];
650 bool fullRangeFlag = segmentData[parsePos + 1] & 0x01;
654 if (segmentLength <= parsePos + 5) break;
655 Y = segmentData[parsePos + 2];
656 Cr = segmentData[parsePos + 3];
657 Cb = segmentData[parsePos + 4];
658 T = segmentData[parsePos + 5];
662 Y = segmentData[parsePos + 2] & 0xFC;
663 Cr = (segmentData[parsePos + 2] & 0x03) << 6;
664 Cr |= (segmentData[parsePos + 3] & 0xC0) >> 2;
665 Cb = (segmentData[parsePos + 3] & 0x3C) << 2;
666 T = (segmentData[parsePos + 3] & 0x03) << 6;
668 u1 entryFlags = segmentData[parsePos + 1];
669 if (entryFlags & 0x80) clut.setEntry(2, clutEntryID, Y,Cr,Cb,T);
670 if (entryFlags & 0x40) clut.setEntry(4, clutEntryID, Y,Cr,Cb,T);
671 if (entryFlags & 0x20) clut.setEntry(8, clutEntryID, Y,Cr,Cb,T);
672 parsePos += fullRangeFlag ? 6 : 4;
674 page.updateRegionPalettes(clut);
677 case 0x13: // Object data
679 if (segmentLength < 3) break;
680 u4 objectID = (segmentData[0] << 8) + segmentData[1];
681 DVBSubtitleObject object(objectID);
682 object.findWhereUsed(page);
683 u1 codingMethod = (segmentData[2] & 0x0C) >> 2;
684 object.setNonModColourFlag(segmentData[2] & 0x01);
685 if (codingMethod == 0x00) // Coding of pixels
687 if (segmentLength < 7) break;
688 u4 topFieldLen = (segmentData[3] << 8) + segmentData[4];
689 u4 bottomFieldLen = (segmentData[5] << 8) + segmentData[6];
690 if (segmentLength < 7 + topFieldLen + bottomFieldLen) break;
691 object.decodeSubBlock(segmentData + 7, topFieldLen, true);
693 object.decodeSubBlock(segmentData + 7 + topFieldLen,
694 bottomFieldLen, false);
696 object.decodeSubBlock(segmentData + 7, topFieldLen, false);
698 else if (codingMethod == 0x01) // Coded as a string of characters
704 case 0x14: {// Display definition
705 if (segmentLength<5) break;
706 u4 ddsversion=(segmentData[0]&0xf0)>>4;
707 if (ddsversion==dds.version) break; // no update ncessary
708 dds.version=ddsversion;
709 dds.displaywindow=!(!(segmentData[0]&0x08));
710 dds.framewidth=(segmentData[1] << 8) + segmentData[2];
711 dds.frameheight=(segmentData[3] << 8) + segmentData[4];
712 if (segmentLength<13) break;
713 if (dds.displaywindow) {
714 dds.windowx=(segmentData[4] << 8) + segmentData[5];
715 dds.windoww=(segmentData[6] << 8) + segmentData[7]-dds.windowx;
716 dds.windowy=(segmentData[8] << 8) + segmentData[9];
717 dds.windowh=(segmentData[10] << 8) + segmentData[11]-dds.windowy;
721 dds.windoww=dds.framewidth;
722 dds.windowh=dds.frameheight;
726 case 0x80: // End of display set
729 page.currentDisplay = page.pendingDisplay;
732 segmentOffset += (segmentLength + 6);
734 return false; // Fall through from while loop: we ran out of data
737 void DVBSubtitles::finishPage(const DVBSubtitlePage& page)
739 if (page.dirty && !osdMenuShowing)
744 DVBSubtitlePage::DisplayMap::const_iterator i,j;
745 for (i = page.currentDisplay.begin(); i != page.currentDisplay.end(); ++i)
746 { // For each currently displayed region, if the region has been
747 // moved or removed, blank out its previous screen position
748 j = page.pendingDisplay.find(i->first);
749 if (j == page.pendingDisplay.end() ||
750 j->second.x != i->second.x ||
751 j->second.y != i->second.y)
753 DVBSubtitlePage::RegionMap::const_iterator region_iter;
754 region_iter = page.regions.find(i->first);
755 if (region_iter == page.regions.end()) continue;
756 LogNT::getInstance()->debug(TAG, "Clear region {}", i->first);
757 if (!osdMenuShowing) osd->clearOSDArea(i->second.x, i->second.y,
758 region_iter->second.getWidth(), region_iter->second.getHeight(),dds);
762 for (i = page.pendingDisplay.begin(); i != page.pendingDisplay.end(); ++i)
763 { // Display each pending region
764 DVBSubtitlePage::RegionMap::const_iterator region_iter;
765 region_iter = page.regions.find(i->first);
766 if (region_iter == page.regions.end()) continue;
767 LogNT::getInstance()->debug(TAG, "Display region {}", i->first);
768 if (!osdMenuShowing) osd->drawOSDBitmap(i->second.x, i->second.y,
769 region_iter->second,dds);
771 // after displaying regions set the page timeout timer
773 subtitleTimeoutPoint = std::chrono::system_clock::now() + std::chrono::seconds(page.timeout);
774 subtitleTimeoutPointActive = true;
776 LogNT::getInstance()->debug(TAG, "SubtitleTimeout {}", page.timeout);
779 void DVBSubtitles::start()
781 LogNT::getInstance()->debug(TAG, "subs start");
785 DBG = fopen("dfifo", "a");
787 fprintf(DBG, "\033[H\033[2J");
794 dds=DVBSubtitleDisplayDefinition();
798 dvbsThread = std::thread([this] { threadMethod(); });
800 input_mutex.unlock();
803 void DVBSubtitles::stop()
805 LogNT::getInstance()->debug(TAG, "subs stop");
810 LogNT::getInstance()->error(TAG, "STOP called, already dead!");
811 input_mutex.unlock();
815 running = false; // disables put()
818 dvbsCond.notify_one();
819 input_mutex.unlock();
823 input_mutex.unlock();
825 clearDisplayedPages();
833 void DVBSubtitles::show()
835 LogNT::getInstance()->debug(TAG, "subs show");
839 output_mutex.unlock();
842 void DVBSubtitles::hide()
844 LogNT::getInstance()->debug(TAG, "subs hide");
847 clearDisplayedPages();
850 void DVBSubtitles::clearDisplayedPages()
854 PageMap::const_iterator pageEntry = pages.find(pageOnDisplay);
855 if (pageEntry != pages.end())
857 const DVBSubtitlePage& page = pageEntry->second;
858 DVBSubtitlePage::DisplayMap::const_iterator i;
859 for (i = page.currentDisplay.begin(); i != page.currentDisplay.end(); ++i)
861 DVBSubtitlePage::RegionMap::const_iterator region_iter;
862 region_iter = page.regions.find(i->first);
863 if (region_iter == page.regions.end()) continue;
864 if (!osdMenuShowing) osd->clearOSDArea(i->second.x, i->second.y,
865 region_iter->second.getWidth(), region_iter->second.getHeight(),dds);
869 pageOnDisplay = 65536;
871 output_mutex.unlock();
874 void DVBSubtitles::pause()
876 LogNT::getInstance()->debug(TAG, "subs pause");
881 LogNT::getInstance()->error(TAG, "pause called, already dead!");
882 input_mutex.unlock();
888 dvbsCond.notify_one();
889 input_mutex.unlock();
892 void DVBSubtitles::unPause()
894 LogNT::getInstance()->debug(TAG, "subs unpause");
899 LogNT::getInstance()->error(TAG, "pause called, already dead!");
900 input_mutex.unlock();
905 signalRecalcWLTO = true;
906 dvbsCond.notify_one();
907 input_mutex.unlock();
912 #pragma warning(disable : 4146)
915 void DVBSubtitles::threadMethod()
917 std::unique_lock<std::mutex> ul(input_mutex); // Lock here, force start() to return before this does anything
922 std::chrono::time_point<std::chrono::system_clock> worklistTimeoutPoint;
923 bool worklistTimeoutPointActive{};
929 // FIXME dvbsubsdebug
930 // TEMP DEBUG - re-enable nowPTS below when this goes
931 u8 nowPTS = Video::getInstance()->getCurrentTimestamp();
932 fprintf(DBG, "\033[H\033[2J");
933 fprintf(DBG, "Now: %s %llu\n", tp2str(std::chrono::system_clock::now()).c_str(), Video::getInstance()->getCurrentTimestamp());
934 for (auto p : worklist)
936 fprintf(DBG, "packet PTS %llu SIZE %i\tTIME %s\n", p.getPTS(), p.getSize(),
937 tp2str(std::chrono::system_clock::now() + std::chrono::milliseconds(PTSDifference(p.getPTS(), nowPTS) / 90)).c_str());
946 LogNT::getInstance()->info(TAG, "Thread exiting");
950 else if (signalPause)
953 subtitleTimeoutPointActive = false;
954 worklistTimeoutPointActive = false;
956 else if (signalRecalcWLTO) // once per incoming packet, and other times
958 signalRecalcWLTO = false;
962 subtitleTimeoutPointActive = false;
963 worklistTimeoutPointActive = false;
968 u8 nowPTS = Video::getInstance()->getCurrentTimestamp();
973 // Video is not started yet. DVBSub packet has come in. Don't set worklistTimeoutPoint,
974 // just store the packet and allow next signal to start things off
975 LogNT::getInstance()->debug(TAG, "signalRecalcWLTO but Video PTS == 0");
977 else if (worklist.size()) // It is possible to be called to recalc when there are no packets
979 worklistTimeoutPointActive = true;
980 LogNT::getInstance()->debug(TAG, "Calc: Num packets available: {}", worklist.size());
982 u8 pktPTS = worklist.front().getPTS();
983 u8 diff = PTSDifference(pktPTS, nowPTS);
984 diff /= 90; // convert diff to ms (PTS difference is in 1/90000s)
985 if (diff < 60 * 1000)
987 worklistTimeoutPoint = std::chrono::system_clock::now() + std::chrono::milliseconds(diff);
988 LogNT::getInstance()->debug(TAG, "Calc'd new worklistTimeoutPoint");
992 // We have a problem. An action so far in the future should have
993 // been culled. Probably the action is already due and PTSDifference
994 // wrapped around. Therefore we sleep for a minimal time instead.
996 // FIXME check if this still works
997 worklistTimeoutPoint = std::chrono::system_clock::now();
998 LogNT::getInstance()->debug(TAG, "Problem packet");
1003 else if (waitExpireST) // do real work - subtitletimeout
1005 LogNT::getInstance()->debug(TAG, "Subtitle timeout occurred");
1006 waitExpireST = false;
1007 subtitleTimeoutPointActive = false;
1008 output_mutex.lock();
1009 if (showing && !osdMenuShowing) osd->clearOSD();
1010 output_mutex.unlock();
1012 else if (waitExpireWL) // do real work - worklist - could be multiple packets to do
1014 LogNT::getInstance()->debug(TAG, "Something to do");
1016 waitExpireWL = false;
1017 worklistTimeoutPointActive = false;
1019 // u8 nowPTS = Video::getInstance()->getCurrentTimestamp();
1021 // Guaranteed to be at least one packet in the worklist
1022 PESPacket packet = worklist.front();
1023 u8 pktPTS = worklist.front().getPTS();
1027 worklist.pop_front();
1029 output_mutex.lock();
1030 if (showing) decodePacket(packet);
1031 output_mutex.unlock();
1033 // Repeat this loop only if there is another packet and it's the same PTS as this one
1034 // Not sure this ever happens.
1035 if (worklist.size() && (worklist.front().getPTS() == pktPTS))
1037 packet = worklist.front();
1046 if (worklist.size())
1048 signalRecalcWLTO = true;
1049 continue; // restart the loop and force a recalc
1056 if (PTSDifference(nowPTS, pktPTS) < 2*90000 // need this? we should be here exactly on time
1057 || PTSDifference(pktPTS, nowPTS) < 4000)
1058 { // It is due for processing or discarding.
1059 worklist.pop_front();
1061 output_mutex.lock();
1062 if (showing) decodePacket(packet);
1063 output_mutex.unlock();
1065 else if (PTSDifference(pktPTS, nowPTS) >= 60*90000)
1066 { // Seems like a bad or very old entry. Get rid of it.
1068 worklist.pop_front();
1073 // Loop has exited. Either worklist is now empty or the next packet doesn't match the PTSDifference ranges
1081 // 1. sleep until timeout
1082 // 2. sleep until next worklist
1083 // 3. sleep until signalled
1085 if (!subtitleTimeoutPointActive && !worklistTimeoutPointActive)
1087 LogNT::getInstance()->debug(TAG, "No WL or STT. Infinite wait");
1088 dvbsCond.wait(ul); // Wait until signalled
1090 else if (subtitleTimeoutPointActive)
1092 if (worklistTimeoutPointActive && (worklistTimeoutPoint < subtitleTimeoutPoint))
1094 LogNT::getInstance()->debug(TAG, "WaitFor: WL");
1095 if (dvbsCond.wait_until(ul, worklistTimeoutPoint) == std::cv_status::timeout) waitExpireWL = true;
1099 LogNT::getInstance()->debug(TAG, "WaitFor: ST");
1100 if (dvbsCond.wait_until(ul, subtitleTimeoutPoint) == std::cv_status::timeout) waitExpireST = true;
1105 LogNT::getInstance()->debug(TAG, "WaitFor: WL");
1106 if (dvbsCond.wait_until(ul, worklistTimeoutPoint) == std::cv_status::timeout) waitExpireWL = true;
1111 struct timespec sleeptime;
1112 sleeptime.tv_sec = 0;
1113 sleeptime.tv_nsec = 0;
1114 uint64_t wakeup = 0;
1115 timeout_clear=false;
1118 if (subtitleTimeoutPointActive && (subtitleTimeoutPoint < std::chrono::system_clock::now())) // do we have a subtitle timeout
1120 subtitleTimeoutPointActive = false;
1123 // if (SubtitleTimeout.TimedOut()) // do we have a subtitle timeout
1125 output_mutex.lock();
1126 if (showing && !osdMenuShowing) {
1127 if (!timeout_clear) {
1128 osd->clearOSD(); // if we have the timeout, lets clear the OSD
1132 output_mutex.unlock();
1134 else if (showing) // if not lets check when will we have it
1136 // Get milliseconds until the timeout
1137 wakeup = std::chrono::duration_cast<std::chrono::milliseconds>(subtitleTimeoutPoint - std::chrono::system_clock::now()).count();
1138 LogNT::getInstance()->debug(TAG, "A1: {}", wakeup);
1141 wakeup = -(SubtitleTimeout.Elapsed());
1143 LogNT::getInstance()->debug(TAG, "A2: {}", wakeup);
1145 if (wakeup > 0 && sleeptime.tv_nsec == 0 && sleeptime.tv_sec == 0)
1146 // We are not done, we still have a Subtitle Timeout!
1148 sleeptime.tv_sec = (int)(wakeup / 1000);
1149 sleeptime.tv_nsec = (long)(wakeup % 1000) * 10000L / 1000L * 100000L;
1150 timeout_clear=false;
1155 //if (dvbsThreadStop) return;
1161 { // We have done the current work and no more has arrived. Sleep.
1162 if (sleeptime.tv_sec == 0 && sleeptime.tv_nsec == 0)
1164 LogNT::getInstance()->debug(TAG, "Sleeping until nudged.");
1165 threadWaitForSignal();
1169 LogNT::getInstance()->debug(TAG, "Sleeping for {} and {}", sleeptime.tv_sec, sleeptime.tv_nsec);
1170 struct timespec targetTime;
1172 getClockRealTime(&targetTime);
1174 targetTime.tv_nsec += sleeptime.tv_nsec;
1175 if (targetTime.tv_nsec > 999999999)
1177 targetTime.tv_sec += 1;
1178 targetTime.tv_nsec -= 1000000000;
1180 targetTime.tv_sec += sleeptime.tv_sec;
1181 threadWaitForSignalTimed(&targetTime);
1184 threadNudged = false;
1186 bool finished = false;
1193 pktPTS = PESPacket::PTS_INVALID;
1195 if (!worklist.empty())
1196 pktPTS = worklist.front().getPTS();
1197 input_mutex.unlock();
1198 if (pktPTS != PESPacket::PTS_INVALID)
1199 { // An entry exists in the work list
1200 nowPTS = Video::getInstance()->getCurrentTimestamp();
1201 if (PTSDifference(nowPTS, pktPTS) < 2*90000 ||
1202 PTSDifference(pktPTS, nowPTS) < 4000)
1203 { // It is due for processing or discarding.
1206 if (!worklist.empty())
1208 PESPacket packet = worklist.front();
1209 worklist.pop_front();
1210 input_mutex.unlock();
1211 output_mutex.lock();
1212 if (showing) decodePacket(packet);
1213 output_mutex.unlock();
1215 else input_mutex.unlock();
1217 else if (PTSDifference(pktPTS, nowPTS) >= 60*90000)
1218 { // Seems like a bad or very old entry. Get rid of it.
1221 if (!worklist.empty()) worklist.pop_front();
1222 input_mutex.unlock();
1226 // Calculate how long to sleep for
1227 wait = SUBTITLE_TIMEOUT_MS; // Max sleep while checking subtitle timeout
1228 sleeptime.tv_sec = 0;
1229 sleeptime.tv_nsec = 0;
1230 if (pktPTS != PESPacket::PTS_INVALID)
1231 { // A future action exists
1232 nowPTS = Video::getInstance()->getCurrentTimestamp();
1233 u8 diff = PTSDifference(pktPTS, nowPTS);
1234 diff /= 90; // convert diff in ms as PTS difference in 1/90000s
1235 if (diff < 60 * 1000)
1237 if (diff < (u8)wait)
1239 sleeptime.tv_nsec = (long)(wait % 1000) * 10000L / 1000L * 100000L;
1242 { // We have a problem. An action so far in the future should have
1243 // been culled. Probably the action is already due and PTSDifference
1244 // wrapped around. Therefore we sleep for a minimal time instead.
1245 sleeptime.tv_nsec = 1;
1253 void DVBSubtitles::setOSDMenuVisibility(bool visible)
1255 output_mutex.lock();
1256 osdMenuShowing = visible;
1257 output_mutex.unlock();