+static uint8_t* teletext_data_unit_from_op47_vbi_packet(int line, uint16_t *py, uint8_t *tgt)
+{
+ int i;
+
+ if (py[0] != 0x255 || py[1] != 0x255 || py[2] != 0x227)
+ return tgt;
+
+ fill_data_unit_head(line, tgt);
+
+ py += 3;
+ tgt += 4;
+
+ for (i = 0; i < 42; i++)
+ *tgt++ = ff_reverse[py[i] & 255];
+
+ return tgt;
+}
+
+static int linemask_matches(int line, int64_t mask)
+{
+ int shift = -1;
+ if (line >= 6 && line <= 22)
+ shift = line - 6;
+ if (line >= 318 && line <= 335)
+ shift = line - 318 + 17;
+ return shift >= 0 && ((1ULL << shift) & mask);
+}
+
+static uint8_t* teletext_data_unit_from_op47_data(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines)
+{
+ if (py < pend - 9) {
+ if (py[0] == 0x151 && py[1] == 0x115 && py[3] == 0x102) { // identifier, identifier, format code for WST teletext
+ uint16_t *descriptors = py + 4;
+ int i;
+ py += 9;
+ for (i = 0; i < 5 && py < pend - 45; i++, py += 45) {
+ int line = (descriptors[i] & 31) + (!(descriptors[i] & 128)) * 313;
+ if (line && linemask_matches(line, wanted_lines))
+ tgt = teletext_data_unit_from_op47_vbi_packet(line, py, tgt);
+ }
+ }
+ }
+ return tgt;
+}
+
+static uint8_t* teletext_data_unit_from_ancillary_packet(uint16_t *py, uint16_t *pend, uint8_t *tgt, int64_t wanted_lines, int allow_multipacket)
+{
+ uint16_t did = py[0]; // data id
+ uint16_t sdid = py[1]; // secondary data id
+ uint16_t dc = py[2] & 255; // data count
+ py += 3;
+ pend = FFMIN(pend, py + dc);
+ if (did == 0x143 && sdid == 0x102) { // subtitle distribution packet
+ tgt = teletext_data_unit_from_op47_data(py, pend, tgt, wanted_lines);
+ } else if (allow_multipacket && did == 0x143 && sdid == 0x203) { // VANC multipacket
+ py += 2; // priority, line/field
+ while (py < pend - 3) {
+ tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
+ py += 4 + (py[2] & 255); // ndid, nsdid, ndc, line/field
+ }
+ }
+ return tgt;
+}
+
+static uint8_t* teletext_data_unit_from_vanc_data(uint8_t *src, uint8_t *tgt, int64_t wanted_lines)
+{
+ uint16_t y[1920];
+ uint16_t *py = y;
+ uint16_t *pend = y + 1920;
+ /* The 10-bit VANC data is packed in V210, we only need the luma component. */
+ while (py < pend) {
+ *py++ = (src[1] >> 2) + ((src[2] & 15) << 6);
+ *py++ = src[4] + ((src[5] & 3) << 8);
+ *py++ = (src[6] >> 4) + ((src[7] & 63) << 4);
+ src += 8;
+ }
+ py = y;
+ while (py < pend - 6) {
+ if (py[0] == 0 && py[1] == 0x3ff && py[2] == 0x3ff) { // ancillary data flag
+ py += 3;
+ tgt = teletext_data_unit_from_ancillary_packet(py, pend, tgt, wanted_lines, 0);
+ py += py[2] & 255;
+ } else {
+ py++;
+ }
+ }
+ return tgt;
+}
+