· 3 years ago · Nov 16, 2021, 05:39 PM
1diff --git a/Makefile b/Makefile
2index 7e9d8b08c3..144cff3e8e 100644
3--- a/Makefile
4+++ b/Makefile
5@@ -107,8 +107,8 @@ endef
6 $(foreach D,$(FFLIBS),$(eval $(call DOSUBDIR,lib$(D))))
7
8 include $(SRC_PATH)/fftools/Makefile
9-include $(SRC_PATH)/doc/Makefile
10-include $(SRC_PATH)/doc/examples/Makefile
11+#include $(SRC_PATH)/doc/Makefile
12+#include $(SRC_PATH)/doc/examples/Makefile
13
14 libavcodec/avcodec.o libavformat/utils.o libavdevice/avdevice.o libavfilter/avfilter.o libavutil/utils.o libpostproc/postprocess.o libswresample/swresample.o libswscale/utils.o : libavutil/ffversion.h
15
16diff --git a/configure b/configure
17index 4ba72bf84b..c9fc6dc1ba 100755
18--- a/configure
19+++ b/configure
20@@ -3438,6 +3438,7 @@ sndio_indev_deps="sndio"
21 sndio_outdev_deps="sndio"
22 v4l2_indev_deps_any="linux_videodev2_h sys_videoio_h"
23 v4l2_indev_suggest="libv4l2"
24+v4l2_outdev_deps="libdrm"
25 v4l2_outdev_deps_any="linux_videodev2_h sys_videoio_h"
26 v4l2_outdev_suggest="libv4l2"
27 vfwcap_indev_deps="vfw32 vfwcap_defines"
28@@ -3755,9 +3756,9 @@ logfile="ffbuild/config.log"
29 # installation paths
30 prefix_default="/usr/local"
31 bindir_default='${prefix}/bin'
32-datadir_default='${prefix}/share/ffmpeg'
33+datadir_default='${prefix}/share/mythtv'
34 docdir_default='${prefix}/share/doc/ffmpeg'
35-incdir_default='${prefix}/include'
36+incdir_default='${prefix}/include/mythtv'
37 libdir_default='${prefix}/lib'
38 mandir_default='${prefix}/share/man'
39
40@@ -3824,11 +3825,11 @@ disable $EXTERNAL_LIBRARY_LIST $HWACCEL_LIBRARY_LIST
41
42 # build settings
43 SHFLAGS='-shared -Wl,-soname,$$(@F)'
44-LIBPREF="lib"
45+LIBPREF="libmyth"
46 LIBSUF=".a"
47 FULLNAME='$(NAME)$(BUILDSUF)'
48 LIBNAME='$(LIBPREF)$(FULLNAME)$(LIBSUF)'
49-SLIBPREF="lib"
50+SLIBPREF="libmyth"
51 SLIBSUF=".so"
52 SLIBNAME='$(SLIBPREF)$(FULLNAME)$(SLIBSUF)'
53 SLIBNAME_WITH_VERSION='$(SLIBNAME).$(LIBVERSION)'
54@@ -3855,6 +3856,7 @@ OBJCC_O='-o $@'
55 X86ASM_O='-o $@'
56 LD_O='-o $@'
57 LD_LIB='-l%'
58+LD_MYTH_LIB='-lmyth%'
59 LD_PATH='-L'
60 HOSTCC_C='-c'
61 HOSTCC_E='-E -o $@'
62@@ -5440,7 +5442,7 @@ case $target_os in
63 enabled shared && ! enabled small && test_cmd $windres --version && enable gnu_windres
64 enabled x86_32 && check_ldflags -Wl,--large-address-aware
65 shlibdir_default="$bindir_default"
66- SLIBPREF=""
67+ SLIBPREF="libmyth"
68 SLIBSUF=".dll"
69 SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
70 SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
71@@ -5489,7 +5491,7 @@ case $target_os in
72 fi
73 enabled x86_32 && check_ldflags -LARGEADDRESSAWARE
74 shlibdir_default="$bindir_default"
75- SLIBPREF=""
76+ SLIBPREF="libmyth"
77 SLIBSUF=".dll"
78 SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
79 SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(FULLNAME)-$(LIBMAJOR)$(SLIBSUF)'
80@@ -5540,7 +5542,7 @@ case $target_os in
81 add_ldflags -Zomf -Zbin-files -Zargs-wild -Zhigh-mem -Zmap
82 SHFLAGS='$(SUBDIR)$(NAME).def -Zdll -Zomf'
83 LIBSUF="_s.a"
84- SLIBPREF=""
85+ SLIBPREF="myth"
86 SLIBSUF=".dll"
87 SLIBNAME_WITH_VERSION='$(SLIBPREF)$(FULLNAME)-$(LIBVERSION)$(SLIBSUF)'
88 SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(shell echo $(FULLNAME) | cut -c1-6)$(LIBMAJOR)$(SLIBSUF)'
89@@ -6486,7 +6488,7 @@ enabled libzmq && require_pkg_config libzmq "libzmq >= 4.2.1" zmq.h z
90 enabled libzvbi && require_pkg_config libzvbi zvbi-0.2 libzvbi.h vbi_decoder_new &&
91 { test_cpp_condition libzvbi.h "VBI_VERSION_MAJOR > 0 || VBI_VERSION_MINOR > 2 || VBI_VERSION_MINOR == 2 && VBI_VERSION_MICRO >= 28" ||
92 enabled gpl || die "ERROR: libzvbi requires version 0.2.28 or --enable-gpl."; }
93-enabled libxml2 && require_pkg_config libxml2 libxml-2.0 libxml2/libxml/xmlversion.h xmlCheckVersion
94+enabled libxml2 && require_pkg_config libxml2 libxml-2.0 libxml/xmlversion.h xmlCheckVersion
95 enabled mbedtls && { check_pkg_config mbedtls mbedtls mbedtls/x509_crt.h mbedtls_x509_crt_init ||
96 check_pkg_config mbedtls mbedtls mbedtls/ssl.h mbedtls_ssl_init ||
97 check_lib mbedtls mbedtls/ssl.h mbedtls_ssl_init -lmbedtls -lmbedx509 -lmbedcrypto ||
98@@ -7499,6 +7501,7 @@ NVCC_O=$NVCC_O
99 LD_O=$LD_O
100 X86ASM_O=$X86ASM_O
101 LD_LIB=$LD_LIB
102+LD_MYTH_LIB=$LD_MYTH_LIB
103 LD_PATH=$LD_PATH
104 DLLTOOL=$dlltool
105 WINDRES=$windres
106diff --git a/ffbuild/common.mak b/ffbuild/common.mak
107index 164a43932d..380a2b28db 100644
108--- a/ffbuild/common.mak
109+++ b/ffbuild/common.mak
110@@ -126,7 +126,7 @@ FFLIBS := $($(NAME)_FFLIBS) $(FFLIBS-yes) $(FFLIBS)
111 TESTPROGS += $(TESTPROGS-yes)
112
113 LDLIBS = $(FFLIBS:%=%$(BUILDSUF))
114-FFEXTRALIBS := $(LDLIBS:%=$(LD_LIB)) $(foreach lib,EXTRALIBS-$(NAME) $(FFLIBS:%=EXTRALIBS-%),$($(lib))) $(EXTRALIBS)
115+FFEXTRALIBS := $(LDLIBS:%=$(LD_MYTH_LIB)) $(foreach lib,EXTRALIBS-$(NAME) $(FFLIBS:%=EXTRALIBS-%),$($(lib))) $(EXTRALIBS)
116
117 OBJS := $(sort $(OBJS:%=$(SUBDIR)%))
118 SLIBOBJS := $(sort $(SLIBOBJS:%=$(SUBDIR)%))
119diff --git a/ffbuild/library.mak b/ffbuild/library.mak
120index 612bacb980..58a4ef6875 100644
121--- a/ffbuild/library.mak
122+++ b/ffbuild/library.mak
123@@ -22,7 +22,8 @@ $(SUBDIR)$(LIBNAME): $(OBJS)
124 $(AR) $(ARFLAGS) $(AR_O) $^
125 $(RANLIB) $@
126
127-install-headers: install-lib$(NAME)-headers install-lib$(NAME)-pkgconfig
128+#install-headers: install-lib$(NAME)-headers install-lib$(NAME)-pkgconfig
129+install-headers: install-lib$(NAME)-headers
130
131 install-libs-$(CONFIG_STATIC): install-lib$(NAME)-static
132 install-libs-$(CONFIG_SHARED): install-lib$(NAME)-shared
133diff --git a/fftools/Makefile b/fftools/Makefile
134index 5affaa3f56..5624d6df4b 100644
135--- a/fftools/Makefile
136+++ b/fftools/Makefile
137@@ -4,6 +4,9 @@ AVPROGS-$(CONFIG_FFPROBE) += ffprobe
138
139 AVPROGS := $(AVPROGS-yes:%=%$(PROGSSUF)$(EXESUF))
140 PROGS += $(AVPROGS)
141+MYTHPROGS = $(addprefix myth, ${PROGS})
142+MYTHFFLIBS = -lmythavfilter -lmythavformat -lmythavcodec -lmythavresample \
143+-lmythpostproc -lmythswresample -lmythswscale
144
145 AVBASENAMES = ffmpeg ffplay ffprobe
146 ALLAVPROGS = $(AVBASENAMES:%=%$(PROGSSUF)$(EXESUF))
147@@ -33,8 +36,22 @@ all: $(AVPROGS)
148 fftools/ffprobe.o fftools/cmdutils.o: libavutil/ffversion.h | fftools
149 OUTDIRS += fftools
150
151+# ${MYTHPROGS}:
152+mythffmpeg:
153+ cp ffmpeg_g mythffmpeg
154+
155+mythffprobe:
156+ cp ffprobe_g mythffprobe
157+
158+mythffserver:
159+ cp ffserver_g mythffserver
160+
161+mythffplay:
162+ cp ffplay_g mythffplay
163+
164 ifdef AVPROGS
165-install: install-progs install-data
166+install: install-mythprogs
167+
168 endif
169
170 install-progs-yes:
171@@ -44,6 +61,10 @@ install-progs: install-progs-yes $(AVPROGS)
172 $(Q)mkdir -p "$(BINDIR)"
173 $(INSTALL) -c -m 755 $(AVPROGS) "$(BINDIR)"
174
175+install-mythprogs: install-progs-yes $(MYTHPROGS)
176+ $(Q)mkdir -p "$(BINDIR)"
177+ $(INSTALL) -c -m 755 $(MYTHPROGS) "$(BINDIR)"
178+
179 uninstall: uninstall-progs
180
181 uninstall-progs:
182diff --git a/libavcodec/Makefile b/libavcodec/Makefile
183index 33a280cf69..0b8f8b21a9 100644
184--- a/libavcodec/Makefile
185+++ b/libavcodec/Makefile
186@@ -58,6 +58,7 @@ OBJS = ac3_parser.o \
187 utils.o \
188 vorbis_parser.o \
189 xiph.o \
190+ utils-mythtv.o \
191
192 # subsystems
193 OBJS-$(CONFIG_AANDCTTABLES) += aandcttab.o
194diff --git a/libavcodec/audiotoolboxdec.c b/libavcodec/audiotoolboxdec.c
195index bf3e00959f..1fbe7d6acc 100644
196--- a/libavcodec/audiotoolboxdec.c
197+++ b/libavcodec/audiotoolboxdec.c
198@@ -342,7 +342,7 @@ static av_cold int ffat_create_decoder(AVCodecContext *avctx,
199 int bit_rate;
200 if (ff_mpa_decode_header(AV_RB32(pkt->data), &avctx->sample_rate,
201 &in_format.mChannelsPerFrame, &avctx->frame_size,
202- &bit_rate, &codec_id) < 0)
203+ &bit_rate, &codec_id, &avctx->avcodec_dual_language) < 0)
204 return AVERROR_INVALIDDATA;
205 avctx->bit_rate = bit_rate;
206 in_format.mSampleRate = avctx->sample_rate;
207diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
208index 8a71c04230..11d4030702 100644
209--- a/libavcodec/avcodec.h
210+++ b/libavcodec/avcodec.h
211@@ -1368,6 +1368,15 @@ typedef struct AVCodecContext {
212 int refcounted_frames;
213 #endif
214
215+ /**
216+ * set when bilingual audio data has been detected.
217+ * 0 normally, 1 if dual language flag is set
218+ *
219+ * - encoding: unused (called delay in this case...)
220+ * - decoding: set by lavc
221+ */
222+ int avcodec_dual_language;
223+
224 /* - encoding parameters */
225 float qcompress; ///< amount of qscale change between easy & hard scenes (0.0-1.0)
226 float qblur; ///< amount of qscale smoothing over time (0.0-1.0)
227@@ -2690,6 +2699,10 @@ typedef struct AVSubtitleRect {
228 int w; ///< width of pict, undefined when pict is not set
229 int h; ///< height of pict, undefined when pict is not set
230 int nb_colors; ///< number of colors in pict, undefined when pict is not set
231+ int display_x; ///< top left corner of region into which pict is displayed
232+ int display_y; ///< top left corner of region into which pict is displayed
233+ int display_w; ///< width of region into which pict is displayed
234+ int display_h; ///< height of region into which pict is displayed
235
236 #if FF_API_AVPICTURE
237 /**
238@@ -2726,6 +2739,7 @@ typedef struct AVSubtitle {
239 unsigned num_rects;
240 AVSubtitleRect **rects;
241 int64_t pts; ///< Same as packet pts, in AV_TIME_BASE
242+ int forced;
243 } AVSubtitle;
244
245 #if FF_API_NEXT
246@@ -4166,6 +4180,13 @@ int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op));
247 */
248 int avcodec_is_open(AVCodecContext *s);
249
250+
251+/* MythTV */
252+const char *ff_codec_id_string(enum AVCodecID codec_id);
253+const char *ff_codec_type_string(enum AVMediaType codec_type);
254+const uint8_t *avpriv_find_start_code(const uint8_t *p, const uint8_t *end, uint32_t *state);
255+
256+
257 /**
258 * Allocate a CPB properties structure and initialize its fields to default
259 * values.
260diff --git a/libavcodec/codec_desc.c b/libavcodec/codec_desc.c
261index 17f8a14044..d82c1acfb3 100644
262--- a/libavcodec/codec_desc.c
263+++ b/libavcodec/codec_desc.c
264@@ -3461,6 +3461,18 @@ static const AVCodecDescriptor codec_descriptors[] = {
265 .name = "dvd_nav_packet",
266 .long_name = NULL_IF_CONFIG_SMALL("DVD Nav packet"),
267 },
268+ {
269+ .id = AV_CODEC_ID_DSMCC_B,
270+ .type = AVMEDIA_TYPE_DATA,
271+ .name = "dsmcc_b",
272+ .long_name = NULL_IF_CONFIG_SMALL("DSMCC B"),
273+ },
274+ {
275+ .id = AV_CODEC_ID_DVD_NAV,
276+ .type = AVMEDIA_TYPE_DATA,
277+ .name = "dvd_nav_packet",
278+ .long_name = NULL_IF_CONFIG_SMALL("DVD Nav packet"),
279+ },
280 {
281 .id = AV_CODEC_ID_TIMED_ID3,
282 .type = AVMEDIA_TYPE_DATA,
283diff --git a/libavcodec/codec_id.h b/libavcodec/codec_id.h
284index ab7bc68ee2..682ff77667 100644
285--- a/libavcodec/codec_id.h
286+++ b/libavcodec/codec_id.h
287@@ -548,6 +548,14 @@ enum AVCodecID {
288 AV_CODEC_ID_TTML,
289 AV_CODEC_ID_ARIB_CAPTION,
290
291+ /* MythTV */
292+ /* teletext codecs */
293+ AV_CODEC_ID_MPEG2VBI,
294+ AV_CODEC_ID_DVB_VBI,
295+
296+ /* DSMCC codec */
297+ AV_CODEC_ID_DSMCC_B,
298+
299 /* other specific kind of codecs (generally used for attachments) */
300 AV_CODEC_ID_FIRST_UNKNOWN = 0x18000, ///< A dummy ID pointing at the start of various fake codecs.
301 AV_CODEC_ID_TTF = 0x18000,
302diff --git a/libavcodec/dvbsub_parser.c b/libavcodec/dvbsub_parser.c
303index b7a3d6154c..04dfe3bd2b 100644
304--- a/libavcodec/dvbsub_parser.c
305+++ b/libavcodec/dvbsub_parser.c
306@@ -126,7 +126,11 @@ static int dvbsub_parse(AVCodecParserContext *s,
307 {
308 len = AV_RB16(p + 4);
309
310- if (len + 6 <= p_end - p)
311+ // MythTV #5978 "<=" -> "<"
312+ // This is unresolved ffmpeg issue 378, use
313+ // their solution if/when this is fixed upstream.
314+ //if (len + 6 <= p_end - p)
315+ if (len + 6 < p_end - p)
316 {
317 out_size += len + 6;
318
319diff --git a/libavcodec/dvbsubdec.c b/libavcodec/dvbsubdec.c
320index 9bee33e4a2..a89f1735c2 100644
321--- a/libavcodec/dvbsubdec.c
322+++ b/libavcodec/dvbsubdec.c
323@@ -731,11 +731,6 @@ static int save_subtitle_set(AVCodecContext *avctx, AVSubtitle *sub, int *got_ou
324 int ret = 0;
325
326
327- if (display_def) {
328- offset_x = display_def->x;
329- offset_y = display_def->y;
330- }
331-
332 /* Not touching AVSubtitles again*/
333 if (sub->num_rects) {
334 avpriv_request_sample(ctx, "Different Version of Segment asked Twice");
335@@ -782,10 +777,20 @@ static int save_subtitle_set(AVCodecContext *avctx, AVSubtitle *sub, int *got_ou
336 continue;
337
338 rect = sub->rects[i];
339- rect->x = display->x_pos + offset_x;
340- rect->y = display->y_pos + offset_y;
341+ rect->x = display->x_pos;
342+ rect->y = display->y_pos;
343 rect->w = region->width;
344 rect->h = region->height;
345+ if (display_def) {
346+ rect->display_x = display_def->x;
347+ rect->display_y = display_def->y;
348+ rect->display_w = display_def->width;
349+ rect->display_h = display_def->height;
350+ }
351+ else {
352+ rect->display_w = 720;
353+ rect->display_h = 576;
354+ }
355 rect->nb_colors = (1 << region->depth);
356 rect->type = SUBTITLE_BITMAP;
357 rect->linesize[0] = region->width;
358@@ -925,6 +930,11 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
359 else
360 map_table = NULL;
361
362+ if (y_pos >= region->height) {
363+ av_log(avctx, AV_LOG_ERROR, "Invalid y position!\n");
364+ return;
365+ }
366+
367 x_pos = dvbsub_read_2bit_string(avctx, pbuf + (y_pos * region->width),
368 region->width, &buf, buf_end - buf,
369 non_mod, map_table, x_pos);
370@@ -940,6 +950,11 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
371 else
372 map_table = NULL;
373
374+ if (y_pos >= region->height) {
375+ av_log(avctx, AV_LOG_ERROR, "Invalid y position!\n");
376+ return;
377+ }
378+
379 x_pos = dvbsub_read_4bit_string(avctx, pbuf + (y_pos * region->width),
380 region->width, &buf, buf_end - buf,
381 non_mod, map_table, x_pos);
382@@ -950,6 +965,11 @@ static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDis
383 return;
384 }
385
386+ if (y_pos >= region->height) {
387+ av_log(avctx, AV_LOG_ERROR, "Invalid y position!\n");
388+ return;
389+ }
390+
391 x_pos = dvbsub_read_8bit_string(avctx, pbuf + (y_pos * region->width),
392 region->width, &buf, buf_end - buf,
393 non_mod, NULL, x_pos);
394@@ -1131,6 +1151,12 @@ static int dvbsub_parse_clut_segment(AVCodecContext *avctx,
395 if (avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL)
396 return AVERROR_INVALIDDATA;
397 }
398+
399+ // MythTV added
400+ if (alpha == 255)
401+ {
402+ r = g = b = 0;
403+ }
404
405 if (depth & 0x80 && entry_id < 4)
406 clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha);
407@@ -1649,6 +1675,7 @@ static int dvbsub_decode(AVCodecContext *avctx,
408 p = buf;
409 p_end = buf + buf_size;
410
411+ int gotpage, gotregion, gotclut, gotobject, gotdisplay = 0;
412 while (p_end - p >= 6 && *p == 0x0f) {
413 p += 1;
414 segment_type = *p++;
415@@ -1674,19 +1701,23 @@ static int dvbsub_decode(AVCodecContext *avctx,
416 case DVBSUB_PAGE_SEGMENT:
417 ret = dvbsub_parse_page_segment(avctx, p, segment_length, sub, got_sub_ptr);
418 got_segment |= 1;
419+ gotpage = 1;
420 break;
421 case DVBSUB_REGION_SEGMENT:
422 ret = dvbsub_parse_region_segment(avctx, p, segment_length);
423 got_segment |= 2;
424+ gotregion = 1;
425 break;
426 case DVBSUB_CLUT_SEGMENT:
427 ret = dvbsub_parse_clut_segment(avctx, p, segment_length);
428 if (ret < 0) goto end;
429 got_segment |= 4;
430+ gotclut = 1;
431 break;
432 case DVBSUB_OBJECT_SEGMENT:
433 ret = dvbsub_parse_object_segment(avctx, p, segment_length);
434 got_segment |= 8;
435+ gotobject = 1;
436 break;
437 case DVBSUB_DISPLAYDEFINITION_SEGMENT:
438 ret = dvbsub_parse_display_definition_segment(avctx, p,
439@@ -1701,6 +1732,7 @@ static int dvbsub_decode(AVCodecContext *avctx,
440 avctx->height = 576;
441 }
442 got_segment |= 16;
443+ gotdisplay = 1;
444 break;
445 default:
446 ff_dlog(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n",
447@@ -1720,6 +1752,11 @@ static int dvbsub_decode(AVCodecContext *avctx,
448 dvbsub_display_end_segment(avctx, p, 0, sub, got_sub_ptr);
449 }
450
451+ // Some streams do not send a display segment but if we have all the other
452+ // segments then we need no further data. see #9373
453+ if ((gotpage & gotregion & gotclut & gotobject) && !gotdisplay && sub)
454+ dvbsub_display_end_segment(avctx, p, 0, sub, got_sub_ptr);
455+
456 end:
457 if (ret < 0) {
458 *got_sub_ptr = 0;
459diff --git a/libavcodec/dvdsubdec.c b/libavcodec/dvdsubdec.c
460index bf49788e1b..40d7493bc6 100644
461--- a/libavcodec/dvdsubdec.c
462+++ b/libavcodec/dvdsubdec.c
463@@ -400,7 +400,7 @@ static int decode_dvd_subtitles(DVDSubContext *ctx, AVSubtitle *sub_header,
464 } else {
465 sub_header->rects[0]->nb_colors = 4;
466 guess_palette(ctx, (uint32_t*)sub_header->rects[0]->data[1],
467- 0xffff00);
468+ 0xffffff);
469 }
470 sub_header->rects[0]->x = x1;
471 sub_header->rects[0]->y = y1;
472@@ -429,7 +429,10 @@ FF_ENABLE_DEPRECATION_WARNINGS
473 cmd_pos = next_cmd_pos;
474 }
475 if (sub_header->num_rects > 0)
476+ {
477+ sub_header->forced = is_menu;
478 return is_menu;
479+ }
480 fail:
481 reset_rects(sub_header);
482 return -1;
483diff --git a/libavcodec/get_bits.h b/libavcodec/get_bits.h
484index 66fb877599..77f7667855 100644
485--- a/libavcodec/get_bits.h
486+++ b/libavcodec/get_bits.h
487@@ -29,6 +29,10 @@
488
489 #include <stdint.h>
490
491+/* MythTV: Prevent "ISO C++17 does not allow âregisterâ storage class
492+ * specifier" warning. */
493+#define register
494+
495 #include "libavutil/common.h"
496 #include "libavutil/intreadwrite.h"
497 #include "libavutil/log.h"
498@@ -146,7 +150,11 @@ static inline unsigned int show_bits(GetBitContext *s, int n);
499 #define BITS_AVAILABLE(name, gb) name ## _index < name ## _size_plus8
500 #endif
501
502-#define CLOSE_READER(name, gb) (gb)->index = name ## _index
503+// Added the void use of the cache to defeat compiler warnings with newer gcc
504+// (warning: variable 're_cache" set but not used)
505+# define CLOSE_READER(name, gb) \
506+ (gb)->index = name##_index; \
507+ (void)name##_cache
508
509 # ifdef LONG_BITSTREAM_READER
510
511@@ -343,8 +351,8 @@ static inline int get_xbits(GetBitContext *s, int n)
512 #if !CACHED_BITSTREAM_READER
513 static inline int get_xbits_le(GetBitContext *s, int n)
514 {
515- register int sign;
516- register int32_t cache;
517+ int sign;
518+ int32_t cache;
519 OPEN_READER(re, s);
520 av_assert2(n>0 && n<=25);
521 UPDATE_CACHE_LE(re, s);
522@@ -400,6 +408,9 @@ static inline unsigned int get_bits(GetBitContext *s, int n)
523 #else
524 OPEN_READER(re, s);
525 av_assert2(n>0 && n<=25);
526+ /* MythTV: clang-tidy warns "Access to field 'l' results in a
527+ * dereference of a null pointer". No plans to investigate.
528+ * NOLINTNEXTLINE(clang-analyzer-core.NullDereference) */
529 UPDATE_CACHE(re, s);
530 tmp = SHOW_UBITS(re, s, n);
531 LAST_SKIP_BITS(re, s, n);
532@@ -643,6 +654,9 @@ static inline int init_get_bits_xe(GetBitContext *s, const uint8_t *buffer,
533 s->cache = 0;
534 s->bits_left = 0;
535 refill_64(s, is_le);
536+#else
537+ /* MythTV: Fix unused parameter warning. */
538+ (void)is_le;
539 #endif
540
541 return ret;
542diff --git a/libavcodec/golomb.h b/libavcodec/golomb.h
543index 4d531cf805..109e399533 100644
544--- a/libavcodec/golomb.h
545+++ b/libavcodec/golomb.h
546@@ -77,6 +77,9 @@ static inline int get_ue_golomb(GetBitContext *gb)
547 }
548 #else
549 OPEN_READER(re, gb);
550+ /* MythTV: clang-tidy warns "Access to field 'l' results in a
551+ * dereference of a null pointer". No plans to investigate.
552+ * NOLINTNEXTLINE(clang-analyzer-core.NullDereference) */
553 UPDATE_CACHE(re, gb);
554 buf = GET_CACHE(re, gb);
555
556@@ -481,7 +484,7 @@ static inline int get_ur_golomb_jpegls(GetBitContext *gb, int k, int limit,
557 } else {
558 int i;
559 for (i = 0; i + MIN_CACHE_BITS <= limit && SHOW_UBITS(re, gb, MIN_CACHE_BITS) == 0; i += MIN_CACHE_BITS) {
560- if (gb->size_in_bits <= re_index) {
561+ if (gb->size_in_bits <= (int)re_index) {
562 CLOSE_READER(re, gb);
563 return -1;
564 }
565diff --git a/libavcodec/h264_refs.c b/libavcodec/h264_refs.c
566index dae8bd278a..488d283bde 100644
567--- a/libavcodec/h264_refs.c
568+++ b/libavcodec/h264_refs.c
569@@ -766,6 +766,14 @@ int ff_h264_execute_ref_pic_marking(H264Context *h)
570 h->short_ref[0] = h->cur_pic_ptr;
571 h->short_ref_count++;
572 h->cur_pic_ptr->reference |= h->picture_structure;
573+
574+ /* MythTV changes - begin */
575+ // do not add more reference frames than allowed after seeing frame num gap
576+ if (!mmco_count && h->short_ref_count > h->ps.sps->ref_frame_count) {
577+ pic = h->short_ref[h->short_ref_count - 1];
578+ remove_short(h, pic->frame_num, 0);
579+ }
580+ /* MythTV changes - end */
581 }
582 }
583
584diff --git a/libavcodec/internal.h b/libavcodec/internal.h
585index d889c1883e..a6535f2a93 100644
586--- a/libavcodec/internal.h
587+++ b/libavcodec/internal.h
588@@ -279,8 +279,16 @@ static av_always_inline int64_t ff_samples_to_time_base(AVCodecContext *avctx,
589 {
590 if(samples == AV_NOPTS_VALUE)
591 return AV_NOPTS_VALUE;
592+#ifndef _MSC_VER
593 return av_rescale_q(samples, (AVRational){ 1, avctx->sample_rate },
594 avctx->time_base);
595+#else
596+ AVRational rational;
597+ rational.num = 1;
598+ rational.den = avctx->sample_rate;
599+
600+ return av_rescale_q(samples, rational, avctx->time_base);
601+#endif
602 }
603
604 /**
605diff --git a/libavcodec/libavcodec.v b/libavcodec/libavcodec.v
606index f1d5e5bc77..a42620dee4 100644
607--- a/libavcodec/libavcodec.v
608+++ b/libavcodec/libavcodec.v
609@@ -1,6 +1,15 @@
610 LIBAVCODEC_MAJOR {
611 global:
612 av*;
613+ ff_ue_golomb_vlc_code;
614+ ff_golomb_vlc_len;
615+ ff_se_golomb_vlc_code;
616+ ff_codec_type_string;
617+ ff_codec_id_string;
618+ ff_zigzag_direct;
619+ avpriv_find_start_code;
620+ ff_fft_init;
621+ ff_fft_end;
622 local:
623 *;
624 };
625diff --git a/libavcodec/mediacodecdec_common.c b/libavcodec/mediacodecdec_common.c
626index 404ed28227..f51b3d3aae 100644
627--- a/libavcodec/mediacodecdec_common.c
628+++ b/libavcodec/mediacodecdec_common.c
629@@ -481,6 +481,8 @@ static int mediacodec_dec_parse_format(AVCodecContext *avctx, MediaCodecDecConte
630 } else if (strstr(s->codec_name, "OMX.SEC.avc.dec")) {
631 s->slice_height = avctx->height;
632 s->stride = avctx->width;
633+ } else if (strstr(s->codec_name, "OMX.MTK.VIDEO.DECODER.MPEG2")) {
634+ s->slice_height = s->height;
635 } else if (s->slice_height == 0) {
636 s->slice_height = s->height;
637 }
638diff --git a/libavcodec/mpeg12dec.c b/libavcodec/mpeg12dec.c
639index 09bf01247d..1ad23a85dc 100644
640--- a/libavcodec/mpeg12dec.c
641+++ b/libavcodec/mpeg12dec.c
642@@ -2396,6 +2396,191 @@ static void mpeg_decode_user_data(AVCodecContext *avctx,
643 s1->has_afd = 1;
644 s1->afd = p[0] & 0x0f;
645 }
646+ } else if (buf_end - p >= 6 &&
647+ p[0] == 0x43 && p[1] == 0x43 && p[2] == 0x01 && p[3] == 0xf8 &&
648+ p[4] == 0x9e) {
649+#undef fprintf
650+ Mpeg1Context *s1 = avctx->priv_data;
651+ MpegEncContext *s = &s1->mpeg_enc_ctx;
652+ int atsc_cnt_loc = s->tmp_atsc_cc_len;
653+ uint8_t real_count = 0;
654+ unsigned int i;
655+
656+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x40 | (0x1f&real_count);
657+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x00; // em_data
658+
659+ for (i=5; i < (buf_end - p - 2) &&
660+ (s->tmp_atsc_cc_len + 3) < ATSC_CC_BUF_SIZE; i++)
661+ {
662+ if ((p[i]&0xfe) == 0xfe) // CC1&CC2 || CC3&CC4
663+ {
664+ uint8_t type = (p[i] & 0x01) ^ 0x01;
665+ uint8_t cc_data_1 = p[++i];
666+ uint8_t cc_data_2 = p[++i];
667+ uint8_t valid = 1;
668+ uint8_t cc608_hdr = 0xf8 | (valid ? 0x04 : 0x00) | type;
669+ real_count++;
670+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc608_hdr;
671+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc_data_1;
672+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc_data_2;
673+ continue;
674+ }
675+ break;
676+ }
677+ if (!real_count)
678+ {
679+ s->tmp_atsc_cc_len = atsc_cnt_loc;
680+ }
681+ else
682+ {
683+ s->tmp_atsc_cc_buf[atsc_cnt_loc] = 0x40 | (0x1f&real_count);
684+ s->tmp_atsc_cc_len = atsc_cnt_loc + 2 + 3 * real_count;
685+ }
686+ } else if (buf_end - p >= 6 &&
687+ p[0] == 'G' && p[1] == 'A' && p[2] == '9' && p[3] == '4') {
688+ /* Parse CEA-708/608 Closed Captions in ATSC user data */
689+ int user_data_type_code = p[4];
690+ if (user_data_type_code == 0x03) { // caption data
691+ Mpeg1Context *s1 = avctx->priv_data;
692+ MpegEncContext *s = &s1->mpeg_enc_ctx;
693+ int cccnt = p[5] & 0x1f;
694+ int cclen = 3 * cccnt + 2;
695+ int proc = (p[5] >> 6) & 1;
696+ int blen = s->tmp_atsc_cc_len;
697+
698+ p += 5;
699+
700+ if ((cclen <= buf_end - p) && ((cclen + blen) < ATSC_CC_BUF_SIZE)) {
701+ uint8_t *dst = s->tmp_atsc_cc_buf + s->tmp_atsc_cc_len;
702+ memcpy(dst, p, cclen);
703+ s->tmp_atsc_cc_len += cclen;
704+ }
705+ }
706+ else if (user_data_type_code == 0x04) {
707+ // additional CEA-608 data, as per SCTE 21
708+ }
709+ else if (user_data_type_code == 0x05) {
710+ // luma PAM data, as per SCTE 21
711+ }
712+ else if (user_data_type_code == 0x06) {
713+ // bar data (letterboxing info)
714+ }
715+ } else if (buf_end - p >= 3 && p[0] == 0x03 && ((p[1]&0x7f) == 0x01)) {
716+ // SCTE 20 encoding of CEA-608
717+ unsigned int cc_count = p[2]>>3;
718+ unsigned int cc_bits = cc_count * 26;
719+ unsigned int cc_bytes = (cc_bits + 7 - 3) / 8;
720+ Mpeg1Context *s1 = avctx->priv_data;
721+ MpegEncContext *s = &s1->mpeg_enc_ctx;
722+ if (buf_end - p >= (2+cc_bytes) && (s->tmp_scte_cc_len + 2 + 3*cc_count) < SCTE_CC_BUF_SIZE) {
723+ int scte_cnt_loc = s->tmp_scte_cc_len;
724+ uint8_t real_count = 0, marker = 1, i;
725+ GetBitContext gb;
726+ init_get_bits(&gb, p+2, (buf_end-p-2) * sizeof(uint8_t));
727+ get_bits(&gb, 5); // swallow cc_count
728+ s->tmp_scte_cc_buf[s->tmp_scte_cc_len++] = 0x40 | (0x1f&cc_count);
729+ s->tmp_scte_cc_buf[s->tmp_scte_cc_len++] = 0x00; // em_data
730+ for (i = 0; i < cc_count; i++) {
731+ uint8_t valid, cc608_hdr;
732+ uint8_t priority = get_bits(&gb, 2);
733+ uint8_t field_no = get_bits(&gb, 2);
734+ uint8_t line_offset = get_bits(&gb, 5);
735+ uint8_t cc_data_1 = ff_reverse[get_bits(&gb, 8)];
736+ uint8_t cc_data_2 = ff_reverse[get_bits(&gb, 8)];
737+ uint8_t type = (2 == field_no) ? 0x01 : 0x00;
738+ if (!s->top_field_first)
739+ type ^= 0x01;
740+ (void) priority; // we use all the data, don't need priority
741+ marker &= get_bits(&gb, 1);
742+ // dump if marker bit missing
743+ valid = marker;
744+ // ignore forbidden field numbers
745+ valid = valid && (0 != field_no);
746+ // ignore content not in line 21
747+ valid = valid && (11 == line_offset);
748+ if (!valid)
749+ continue;
750+ cc608_hdr = 0xf8 | (valid ? 0x04 : 0x00) | type;
751+ real_count++;
752+ s->tmp_scte_cc_buf[s->tmp_scte_cc_len++] = cc608_hdr;
753+ s->tmp_scte_cc_buf[s->tmp_scte_cc_len++] = cc_data_1;
754+ s->tmp_scte_cc_buf[s->tmp_scte_cc_len++] = cc_data_2;
755+ }
756+ if (!real_count)
757+ {
758+ s->tmp_scte_cc_len = scte_cnt_loc;
759+ }
760+ else
761+ {
762+ s->tmp_scte_cc_buf[scte_cnt_loc] = 0x40 | (0x1f&real_count);
763+ s->tmp_scte_cc_len = scte_cnt_loc + 2 + 3 * real_count;
764+ }
765+ }
766+ } else if (buf_end - p >= 11 &&
767+ p[0] == 0x05 && p[1] == 0x02) {
768+ /* parse EIA-608 captions embedded in a DVB stream. */
769+ Mpeg1Context *s1 = avctx->priv_data;
770+ MpegEncContext *s = &s1->mpeg_enc_ctx;
771+ uint8_t dvb_cc_type = p[7];
772+ p += 8;
773+
774+ /* Predictive frame tag, but MythTV reorders predictive
775+ * frames for us along with the CC data, so we ignore it.
776+ */
777+ if (dvb_cc_type == 0x05) {
778+ dvb_cc_type = p[6];
779+ p += 7;
780+ }
781+
782+ if (dvb_cc_type == 0x02) { /* 2-byte caption, can be repeated */
783+ int type = 0x00; // line 21 field 1 == 0x00, field 2 == 0x01
784+ uint8_t cc608_hdr = 0xf8 | 0x04/*valid*/ | type;
785+ uint8_t hi = p[1] & 0xFF;
786+ uint8_t lo = p[2] & 0xFF;
787+
788+ dvb_cc_type = p[3];
789+
790+ if ((2 <= buf_end - p) && ((3 + s->tmp_atsc_cc_len) < ATSC_CC_BUF_SIZE)) {
791+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x40 | (0x1f&1/*cc_count*/);
792+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x00; // em_data
793+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc608_hdr;
794+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = hi;
795+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = lo;
796+
797+ /* Only repeat characters when the next type flag
798+ * is 0x04 and the characters are repeatable (i.e., less than
799+ * 32 with the parity stripped).
800+ */
801+ if (dvb_cc_type == 0x04 && (hi & 0x7f) < 32) {
802+ if ((2 <= buf_end - p) && ((3 + s->tmp_atsc_cc_len) < ATSC_CC_BUF_SIZE)) {
803+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x40 | (0x1f&1/*cc_count*/);
804+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x00; // em_data
805+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc608_hdr;
806+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = hi;
807+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = lo;
808+ }
809+ }
810+ }
811+
812+ p += 6;
813+ } else if (dvb_cc_type == 0x04) { /* 4-byte caption, not repeated */
814+ if ((4 <= buf_end - p) &&
815+ ((6 + s->tmp_atsc_cc_len) < ATSC_CC_BUF_SIZE)) {
816+ int type = 0x00; // line 21 field 1 == 0x00, field 2 == 0x01
817+ uint8_t cc608_hdr = 0xf8 | 0x04/*valid*/ | type;
818+
819+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x40 | (0x1f&2/*cc_count*/);
820+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = 0x00; // em_data
821+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc608_hdr;
822+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = p[1] & 0xFF;
823+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = p[2] & 0xFF;
824+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = cc608_hdr;
825+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = p[3] & 0xFF;
826+ s->tmp_atsc_cc_buf[s->tmp_atsc_cc_len++] = p[4] & 0xFF;
827+ }
828+
829+ p += 9;
830+ }
831 } else if (buf_end - p >= 6 &&
832 p[0] == 'J' && p[1] == 'P' && p[2] == '3' && p[3] == 'D' &&
833 p[4] == 0x03) { // S3D_video_format_length
834@@ -2427,6 +2612,9 @@ static void mpeg_decode_user_data(AVCodecContext *avctx,
835 } else if (mpeg_decode_a53_cc(avctx, p, buf_size)) {
836 return;
837 }
838+ // For other CEA-608 embedding options see:
839+ /* SCTE 21 */
840+ /* ETSI EN 301 775 */
841 }
842
843 static void mpeg_decode_gop(AVCodecContext *avctx,
844diff --git a/libavcodec/mpeg4videodec.c b/libavcodec/mpeg4videodec.c
845index 2c440a5026..06450919f3 100644
846--- a/libavcodec/mpeg4videodec.c
847+++ b/libavcodec/mpeg4videodec.c
848@@ -132,6 +132,8 @@ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
849 if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
850 return 0;
851
852+// disabling the while loop since it causes playback issues. see #3001
853+#if 0
854 while (v <= 0xFF) {
855 if (s->pict_type == AV_PICTURE_TYPE_B ||
856 (v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
857@@ -140,6 +142,7 @@ static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
858 bits_count += 8 + s->pict_type;
859 v = show_bits(&s->gb, 16);
860 }
861+#endif
862
863 if (bits_count + 8 >= s->gb.size_in_bits) {
864 v >>= 8;
865@@ -2392,7 +2395,9 @@ static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
866 if (get_bits1(gb) != 0) /* fixed_vop_rate */
867 s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
868 else
869- s->avctx->framerate.den = 1;
870+ /* fix for h263 frame rate */
871+ s->avctx->time_base.num = (s->avctx->time_base.den>10000) ? 1001 : 1;
872+ //s->avctx->framerate.den = 1;
873
874 s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
875
876diff --git a/libavcodec/mpegaudio_parser.c b/libavcodec/mpegaudio_parser.c
877index 1005e89aae..573e564c6d 100644
878--- a/libavcodec/mpegaudio_parser.c
879+++ b/libavcodec/mpegaudio_parser.c
880@@ -70,12 +70,12 @@ static int mpegaudio_parse(AVCodecParserContext *s1,
881
882 state= (state<<8) + buf[i++];
883
884- ret = ff_mpa_decode_header(state, &sr, &channels, &frame_size, &bit_rate, &codec_id);
885+ ret = ff_mpa_decode_header(state, &sr, &channels, &frame_size, &bit_rate, &codec_id, &avctx->avcodec_dual_language);
886 if (ret < 4) {
887 if (i > 4)
888 s->header_count = -2;
889 } else {
890- int header_threshold = avctx->codec_id != AV_CODEC_ID_NONE && avctx->codec_id != codec_id;
891+ int header_threshold = (avctx->codec_id != AV_CODEC_ID_NONE && avctx->codec_id != codec_id) || avctx->sample_rate == 0;
892 if((state&SAME_HEADER_MASK) != (s->header&SAME_HEADER_MASK) && s->header)
893 s->header_count= -3;
894 s->header= state;
895diff --git a/libavcodec/mpegaudiodec_template.c b/libavcodec/mpegaudiodec_template.c
896index 4fd9e3a690..b07dcb21d5 100644
897--- a/libavcodec/mpegaudiodec_template.c
898+++ b/libavcodec/mpegaudiodec_template.c
899@@ -1589,6 +1589,10 @@ static int decode_frame(AVCodecContext * avctx, void *data, int *got_frame_ptr,
900 av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
901 return AVERROR_INVALIDDATA;
902 } else if (s->frame_size < buf_size) {
903+ // FIXME, This 'if' statement can be taken out at some point in the
904+ // future. For now, it prevents people's logs filling up with these
905+ // errors when they play .nuv files created by the old mythtranscode
906+ if ((buf_size % s->frame_size) != 0)
907 av_log(avctx, AV_LOG_DEBUG, "incorrect frame size - multiple frames in buffer?\n");
908 buf_size= s->frame_size;
909 }
910diff --git a/libavcodec/mpegaudiodecheader.c b/libavcodec/mpegaudiodecheader.c
911index 6cc79f18b5..cd0f168464 100644
912--- a/libavcodec/mpegaudiodecheader.c
913+++ b/libavcodec/mpegaudiodecheader.c
914@@ -119,7 +119,7 @@ int avpriv_mpegaudio_decode_header(MPADecodeHeader *s, uint32_t header)
915 return 0;
916 }
917
918-int ff_mpa_decode_header(uint32_t head, int *sample_rate, int *channels, int *frame_size, int *bit_rate, enum AVCodecID *codec_id)
919+int ff_mpa_decode_header(uint32_t head, int *sample_rate, int *channels, int *frame_size, int *bit_rate, enum AVCodecID *codec_id, int *dual_language)
920 {
921 MPADecodeHeader s1, *s = &s1;
922
923@@ -150,5 +150,9 @@ int ff_mpa_decode_header(uint32_t head, int *sample_rate, int *channels, int *fr
924 *sample_rate = s->sample_rate;
925 *channels = s->nb_channels;
926 *bit_rate = s->bit_rate;
927+ if (dual_language) {
928+ *dual_language = (s->mode == MPA_DUAL) ? 1 : 0;
929+ }
930+
931 return s->frame_size;
932 }
933diff --git a/libavcodec/mpegaudiodecheader.h b/libavcodec/mpegaudiodecheader.h
934index 1da2a4cb6f..d32f016c66 100644
935--- a/libavcodec/mpegaudiodecheader.h
936+++ b/libavcodec/mpegaudiodecheader.h
937@@ -55,7 +55,7 @@ int avpriv_mpegaudio_decode_header(MPADecodeHeader *s, uint32_t header);
938 /* useful helper to get MPEG audio stream info. Return -1 if error in
939 header, otherwise the coded frame size in bytes */
940 int ff_mpa_decode_header(uint32_t head, int *sample_rate,
941- int *channels, int *frame_size, int *bitrate, enum AVCodecID *codec_id);
942+ int *channels, int *frame_size, int *bitrate, enum AVCodecID *codec_id, int *dual_language);
943
944 /* fast header check for resync */
945 static inline int ff_mpa_check_header(uint32_t header){
946diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
947index 5de0719f83..34f3fce3c8 100644
948--- a/libavcodec/mpegvideo.c
949+++ b/libavcodec/mpegvideo.c
950@@ -1235,6 +1235,16 @@ int ff_mpv_frame_start(MpegEncContext *s, AVCodecContext *avctx)
951 pic->reference = 3;
952 }
953
954+ /* Myth Change - Begin */
955+ /* Put ATSC captions cached from parse_user_data into the correct frame */
956+ memcpy(pic->f->atsc_cc_buf, s->tmp_atsc_cc_buf, s->tmp_atsc_cc_len);
957+ pic->f->atsc_cc_len = s->tmp_atsc_cc_len;
958+ s->tmp_atsc_cc_len = 0;
959+ memcpy(pic->f->scte_cc_buf, s->tmp_scte_cc_buf, s->tmp_scte_cc_len);
960+ pic->f->scte_cc_len = s->tmp_scte_cc_len;
961+ s->tmp_scte_cc_len = 0;
962+ /* Myth Change - End */
963+
964 pic->f->coded_picture_number = s->coded_picture_number++;
965
966 if (alloc_picture(s, pic) < 0)
967diff --git a/libavcodec/mpegvideo.h b/libavcodec/mpegvideo.h
968index 5a99c19656..916b01ab9d 100644
969--- a/libavcodec/mpegvideo.h
970+++ b/libavcodec/mpegvideo.h
971@@ -79,7 +79,7 @@
972 * MpegEncContext.
973 */
974 typedef struct MpegEncContext {
975- AVClass *class;
976+ AVClass *clss;
977
978 int y_dc_scale, c_dc_scale;
979 int ac_pred;
980@@ -253,8 +253,8 @@ typedef struct MpegEncContext {
981 int16_t (*b_direct_mv_table)[2]; ///< MV table (1MV per MB) direct mode B-frame encoding
982 int16_t (*p_field_mv_table[2][2])[2]; ///< MV table (2MV per MB) interlaced P-frame encoding
983 int16_t (*b_field_mv_table[2][2][2])[2];///< MV table (4MV per MB) interlaced B-frame encoding
984- uint8_t (*p_field_select_table[2]);
985- uint8_t (*b_field_select_table[2][2]);
986+ uint8_t *p_field_select_table[2];
987+ uint8_t *b_field_select_table[2][2];
988 int motion_est; ///< ME algorithm
989 int me_penalty_compensation;
990 int me_pre; ///< prepass for motion estimation
991@@ -505,6 +505,15 @@ typedef struct MpegEncContext {
992 char *tc_opt_str; ///< timecode option string
993 AVTimecode tc; ///< timecode context
994
995+#define ATSC_CC_BUF_SIZE 1024
996+ /// Used to hold cached user_data about caption packets before the
997+ /// frame for these packets has been created in MPV_frame_start().
998+ uint8_t tmp_atsc_cc_buf[ATSC_CC_BUF_SIZE];
999+ int tmp_atsc_cc_len;
1000+#define SCTE_CC_BUF_SIZE 1024
1001+ uint8_t tmp_scte_cc_buf[SCTE_CC_BUF_SIZE];
1002+ int tmp_scte_cc_len;
1003+
1004 uint8_t *ptr_lastgob;
1005 int swap_uv; //vcr2 codec is an MPEG-2 variant with U and V swapped
1006 int pack_pblocks; //xvmc needs to keep blocks without gaps.
1007diff --git a/libavcodec/pcm.c b/libavcodec/pcm.c
1008index 19d04e9181..935b6b76c3 100644
1009--- a/libavcodec/pcm.c
1010+++ b/libavcodec/pcm.c
1011@@ -251,7 +251,10 @@ static av_cold int pcm_decode_init(AVCodecContext *avctx)
1012 AVFloatDSPContext *fdsp;
1013 int i;
1014
1015- if (avctx->channels <= 0) {
1016+// Breaks playback of some DVDs which feature an empty audio stream
1017+//
1018+// if (avctx->channels <= 0) {
1019+ if (avctx->channels < 0) {
1020 av_log(avctx, AV_LOG_ERROR, "PCM channels out of bounds\n");
1021 return AVERROR(EINVAL);
1022 }
1023diff --git a/libavcodec/pgssubdec.c b/libavcodec/pgssubdec.c
1024index 9c59a2297f..c39232876b 100644
1025--- a/libavcodec/pgssubdec.c
1026+++ b/libavcodec/pgssubdec.c
1027@@ -62,6 +62,7 @@ typedef struct PGSSubPresentation {
1028 int id_number;
1029 int palette_id;
1030 int object_count;
1031+ int object_forced;
1032 PGSSubObjectRef objects[MAX_OBJECT_REFS];
1033 int64_t pts;
1034 } PGSSubPresentation;
1035@@ -465,6 +466,8 @@ static int parse_presentation_segment(AVCodecContext *avctx,
1036 ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);
1037 }
1038
1039+ ctx->presentation.object_forced = (ctx->presentation.objects[i].composition_flag & 0x40) >> 6;
1040+
1041 ff_dlog(avctx, "Subtitle Placement x=%d, y=%d\n",
1042 ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);
1043
1044@@ -508,6 +511,7 @@ static int display_end_segment(AVCodecContext *avctx, void *data,
1045 memset(sub, 0, sizeof(*sub));
1046 sub->pts = pts;
1047 ctx->presentation.pts = AV_NOPTS_VALUE;
1048+ sub->forced = ctx->presentation.object_forced;
1049 sub->start_display_time = 0;
1050 // There is no explicit end time for PGS subtitles. The end time
1051 // is defined by the start of the next sub which may contain no
1052diff --git a/libavcodec/utils-mythtv.c b/libavcodec/utils-mythtv.c
1053new file mode 100644
1054index 0000000000..2cd62e6228
1055--- /dev/null
1056+++ b/libavcodec/utils-mythtv.c
1057@@ -0,0 +1,244 @@
1058+/*
1059+ * utils for libavcodec
1060+ * Copyright (c) 2001 Fabrice Bellard.
1061+ * Copyright (c) 2003 Michel Bardiaux for the av_log API
1062+ * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
1063+ *
1064+ * This library is free software; you can redistribute it and/or
1065+ * modify it under the terms of the GNU Lesser General Public
1066+ * License as published by the Free Software Foundation; either
1067+ * version 2 of the License, or (at your option) any later version.
1068+ *
1069+ * This library is distributed in the hope that it will be useful,
1070+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
1071+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1072+ * Lesser General Public License for more details.
1073+ *
1074+ * You should have received a copy of the GNU Lesser General Public
1075+ * License along with this library; if not, write to the Free Software
1076+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1077+ */
1078+
1079+/**
1080+ * @file myth_utils.c
1081+ * myth_utils.
1082+ */
1083+
1084+#include "avcodec.h"
1085+
1086+/** \fn codec_id_string(enum AVCodecID)
1087+ * returns a human readable string for the AVCodecID enum.
1088+ */
1089+const char *ff_codec_id_string(enum AVCodecID codec_id)
1090+{
1091+ switch (codec_id)
1092+ {
1093+ case AV_CODEC_ID_NONE: return "NONE";
1094+ case AV_CODEC_ID_MPEG1VIDEO: return "MPEG1VIDEO";
1095+ case AV_CODEC_ID_MPEG2VIDEO: return "MPEG2VIDEO";
1096+ case AV_CODEC_ID_H261: return "H261";
1097+ case AV_CODEC_ID_H263: return "H263";
1098+ case AV_CODEC_ID_RV10: return "RV10";
1099+ case AV_CODEC_ID_RV20: return "RV20";
1100+ case AV_CODEC_ID_MJPEG: return "MJPEG";
1101+ case AV_CODEC_ID_MJPEGB: return "MJPEGB";
1102+ case AV_CODEC_ID_LJPEG: return "LJPEG";
1103+ case AV_CODEC_ID_SP5X: return "SP5X";
1104+ case AV_CODEC_ID_MPEG4: return "MPEG4";
1105+ case AV_CODEC_ID_RAWVIDEO: return "RAWVIDEO";
1106+ case AV_CODEC_ID_MSMPEG4V1: return "MSMPEG4V1";
1107+ case AV_CODEC_ID_MSMPEG4V2: return "MSMPEG4V2";
1108+ case AV_CODEC_ID_MSMPEG4V3: return "MSMPEG4V3";
1109+ case AV_CODEC_ID_WMV1: return "WMV1";
1110+ case AV_CODEC_ID_WMV2: return "WMV2";
1111+ case AV_CODEC_ID_H263P: return "H263P";
1112+ case AV_CODEC_ID_H263I: return "H263I";
1113+ case AV_CODEC_ID_FLV1: return "FLV1";
1114+ case AV_CODEC_ID_SVQ1: return "SVQ1";
1115+ case AV_CODEC_ID_SVQ3: return "SVQ3";
1116+ case AV_CODEC_ID_DVVIDEO: return "DVVIDEO";
1117+ case AV_CODEC_ID_HUFFYUV: return "HUFFYUV";
1118+ case AV_CODEC_ID_CYUV: return "CYUV";
1119+ case AV_CODEC_ID_H264: return "H264";
1120+ case AV_CODEC_ID_H265: return "H265";
1121+ case AV_CODEC_ID_INDEO3: return "INDEO3";
1122+ case AV_CODEC_ID_VP3: return "VP3";
1123+ case AV_CODEC_ID_THEORA: return "THEORA";
1124+ case AV_CODEC_ID_ASV1: return "ASV1";
1125+ case AV_CODEC_ID_ASV2: return "ASV2";
1126+ case AV_CODEC_ID_FFV1: return "FFV1";
1127+ case AV_CODEC_ID_4XM: return "4XM";
1128+ case AV_CODEC_ID_VCR1: return "VCR1";
1129+ case AV_CODEC_ID_CLJR: return "CLJR";
1130+ case AV_CODEC_ID_MDEC: return "MDEC";
1131+ case AV_CODEC_ID_ROQ: return "ROQ";
1132+ case AV_CODEC_ID_INTERPLAY_VIDEO: return "INTERPLAY_VIDEO";
1133+ case AV_CODEC_ID_XAN_WC3: return "XAN_WC3";
1134+ case AV_CODEC_ID_XAN_WC4: return "XAN_WC4";
1135+ case AV_CODEC_ID_RPZA: return "RPZA";
1136+ case AV_CODEC_ID_CINEPAK: return "CINEPAK";
1137+ case AV_CODEC_ID_WS_VQA: return "WS_VQA";
1138+ case AV_CODEC_ID_MSRLE: return "MSRLE";
1139+ case AV_CODEC_ID_MSVIDEO1: return "MSVIDEO1";
1140+ case AV_CODEC_ID_IDCIN: return "IDCIN";
1141+ case AV_CODEC_ID_8BPS: return "8BPS";
1142+ case AV_CODEC_ID_SMC: return "SMC";
1143+ case AV_CODEC_ID_FLIC: return "FLIC";
1144+ case AV_CODEC_ID_TRUEMOTION1: return "TRUEMOTION1";
1145+ case AV_CODEC_ID_VMDVIDEO: return "VMDVIDEO";
1146+ case AV_CODEC_ID_MSZH: return "MSZH";
1147+ case AV_CODEC_ID_ZLIB: return "ZLIB";
1148+ case AV_CODEC_ID_QTRLE: return "QTRLE";
1149+ case AV_CODEC_ID_SNOW: return "SNOW";
1150+ case AV_CODEC_ID_TSCC: return "TSCC";
1151+ case AV_CODEC_ID_ULTI: return "ULTI";
1152+ case AV_CODEC_ID_QDRAW: return "QDRAW";
1153+ case AV_CODEC_ID_VIXL: return "VIXL";
1154+ case AV_CODEC_ID_QPEG: return "QPEG";
1155+#if 0
1156+ case AV_CODEC_ID_XVID: return "XVID";
1157+#endif
1158+ case AV_CODEC_ID_PNG: return "PNG";
1159+ case AV_CODEC_ID_PPM: return "PPM";
1160+ case AV_CODEC_ID_PBM: return "PBM";
1161+ case AV_CODEC_ID_PGM: return "PGM";
1162+ case AV_CODEC_ID_PGMYUV: return "PGMYUV";
1163+ case AV_CODEC_ID_PAM: return "PAM";
1164+ case AV_CODEC_ID_FFVHUFF: return "FFVHUFF";
1165+ case AV_CODEC_ID_RV30: return "RV30";
1166+ case AV_CODEC_ID_RV40: return "RV40";
1167+ case AV_CODEC_ID_VC1: return "VC1";
1168+ case AV_CODEC_ID_WMV3: return "WMV3";
1169+ case AV_CODEC_ID_LOCO: return "LOCO";
1170+ case AV_CODEC_ID_WNV1: return "WNV1";
1171+ case AV_CODEC_ID_AASC: return "AASC";
1172+ case AV_CODEC_ID_INDEO2: return "INDEO2";
1173+ case AV_CODEC_ID_FRAPS: return "FRAPS";
1174+ case AV_CODEC_ID_TRUEMOTION2: return "TRUEMOTION2";
1175+ case AV_CODEC_ID_BMP: return "BMP";
1176+ case AV_CODEC_ID_VP8: return "VP8";
1177+
1178+ /* various pcm "codecs" */
1179+ case AV_CODEC_ID_PCM_S16LE: return "PCM_S16LE";
1180+ case AV_CODEC_ID_PCM_S16BE: return "PCM_S16BE";
1181+ case AV_CODEC_ID_PCM_U16LE: return "PCM_U16LE";
1182+ case AV_CODEC_ID_PCM_U16BE: return "PCM_U16BE";
1183+ case AV_CODEC_ID_PCM_S8: return "PCM_S8";
1184+ case AV_CODEC_ID_PCM_U8: return "PCM_U8";
1185+ case AV_CODEC_ID_PCM_MULAW: return "PCM_MULAW";
1186+ case AV_CODEC_ID_PCM_ALAW: return "PCM_ALAW";
1187+ case AV_CODEC_ID_PCM_S32LE: return "PCM_S32LE";
1188+ case AV_CODEC_ID_PCM_S32BE: return "PCM_S32BE";
1189+ case AV_CODEC_ID_PCM_U32LE: return "PCM_U32LE";
1190+ case AV_CODEC_ID_PCM_U32BE: return "PCM_U32BE";
1191+ case AV_CODEC_ID_PCM_S24LE: return "PCM_S24LE";
1192+ case AV_CODEC_ID_PCM_S24BE: return "PCM_S24BE";
1193+ case AV_CODEC_ID_PCM_U24LE: return "PCM_U24LE";
1194+ case AV_CODEC_ID_PCM_U24BE: return "PCM_U24BE";
1195+ case AV_CODEC_ID_PCM_S24DAUD: return "PCM_S24DAUD";
1196+ case AV_CODEC_ID_PCM_DVD: return "PCM_DVD";
1197+ case AV_CODEC_ID_PCM_BLURAY: return "PCM_BLURAY";
1198+
1199+ /* various adpcm codecs */
1200+ case AV_CODEC_ID_ADPCM_IMA_QT: return "ADPCM_IMA_QT";
1201+ case AV_CODEC_ID_ADPCM_IMA_WAV: return "ADPCM_IMA_WAV";
1202+ case AV_CODEC_ID_ADPCM_IMA_DK3: return "ADPCM_IMA_DK3";
1203+ case AV_CODEC_ID_ADPCM_IMA_DK4: return "ADPCM_IMA_DK4";
1204+ case AV_CODEC_ID_ADPCM_IMA_WS: return "ADPCM_IMA_WS";
1205+ case AV_CODEC_ID_ADPCM_IMA_SMJPEG: return "ADPCM_IMA_SMJPEG";
1206+ case AV_CODEC_ID_ADPCM_MS: return "ADPCM_MS";
1207+ case AV_CODEC_ID_ADPCM_4XM: return "ADPCM_4XM";
1208+ case AV_CODEC_ID_ADPCM_XA: return "ADPCM_XA";
1209+ case AV_CODEC_ID_ADPCM_ADX: return "ADPCM_ADX";
1210+ case AV_CODEC_ID_ADPCM_EA: return "ADPCM_EA";
1211+ case AV_CODEC_ID_ADPCM_G726: return "ADPCM_G726";
1212+ case AV_CODEC_ID_ADPCM_CT: return "ADPCM_CT";
1213+ case AV_CODEC_ID_ADPCM_SWF: return "ADPCM_SWF";
1214+ case AV_CODEC_ID_ADPCM_YAMAHA: return "ADPCM_YAMAHA";
1215+
1216+ /* AMR */
1217+ case AV_CODEC_ID_AMR_NB: return "AMR_NB";
1218+ case AV_CODEC_ID_AMR_WB: return "AMR_WB";
1219+
1220+ /* RealAudio codecs*/
1221+ case AV_CODEC_ID_RA_144: return "RA_144";
1222+ case AV_CODEC_ID_RA_288: return "RA_288";
1223+
1224+ /* various DPCM codecs */
1225+ case AV_CODEC_ID_ROQ_DPCM: return "ROQ_DPCM";
1226+ case AV_CODEC_ID_INTERPLAY_DPCM: return "INTERPLAY_DPCM";
1227+ case AV_CODEC_ID_XAN_DPCM: return "XAN_DPCM";
1228+ case AV_CODEC_ID_SOL_DPCM: return "SOL_DPCM";
1229+
1230+ case AV_CODEC_ID_MP1: return "MP1";
1231+ case AV_CODEC_ID_MP2: return "MP2";
1232+ case AV_CODEC_ID_MP3: return "MP3";
1233+ case AV_CODEC_ID_AAC: return "AAC";
1234+ case AV_CODEC_ID_AAC_LATM: return "AAC/LATM";
1235+ case AV_CODEC_ID_AC3: return "AC3";
1236+ case AV_CODEC_ID_DTS: return "DTS";
1237+ case AV_CODEC_ID_VORBIS: return "VORBIS";
1238+ case AV_CODEC_ID_DVAUDIO: return "DVAUDIO";
1239+ case AV_CODEC_ID_WMAV1: return "WMAV1";
1240+ case AV_CODEC_ID_WMAV2: return "WMAV2";
1241+ case AV_CODEC_ID_MACE3: return "MACE3";
1242+ case AV_CODEC_ID_MACE6: return "MACE6";
1243+ case AV_CODEC_ID_VMDAUDIO: return "VMDAUDIO";
1244+ case AV_CODEC_ID_SONIC: return "SONIC";
1245+ case AV_CODEC_ID_SONIC_LS: return "SONIC_LS";
1246+ case AV_CODEC_ID_FLAC: return "FLAC";
1247+ case AV_CODEC_ID_MP3ADU: return "MP3ADU";
1248+ case AV_CODEC_ID_MP3ON4: return "MP3ON4";
1249+ case AV_CODEC_ID_SHORTEN: return "SHORTEN";
1250+ case AV_CODEC_ID_ALAC: return "ALAC";
1251+ case AV_CODEC_ID_WESTWOOD_SND1: return "WESTWOOD_SND1";
1252+ case AV_CODEC_ID_GSM: return "GSM";
1253+ case AV_CODEC_ID_QDM2: return "QDM2";
1254+ case AV_CODEC_ID_MLP: return "MLP";
1255+ case AV_CODEC_ID_TRUEHD: return "TRUEHD";
1256+ case AV_CODEC_ID_EAC3: return "E-AC3";
1257+ case AV_CODEC_ID_WMAPRO: return "WMAPRO";
1258+
1259+ /* subtitle codecs */
1260+ case AV_CODEC_ID_DVD_SUBTITLE: return "DVD_SUBTITLE";
1261+ case AV_CODEC_ID_DVB_SUBTITLE: return "DVB_SUBTITLE";
1262+ case AV_CODEC_ID_TEXT: return "TEXT SUBTITLE";
1263+ case AV_CODEC_ID_XSUB: return "XSUB SUBTITLE";
1264+ case AV_CODEC_ID_SSA: return "SSA SUBTITLE";
1265+ case AV_CODEC_ID_HDMV_PGS_SUBTITLE: return "HDMV_PGS_SUBTITLE";
1266+ case AV_CODEC_ID_DVB_TELETEXT: return "DVB_TELETEXT";
1267+
1268+ case AV_CODEC_ID_MPEG2VBI: return "MPEG2VBI";
1269+ case AV_CODEC_ID_DVB_VBI: return "DVB_VBI";
1270+
1271+ case AV_CODEC_ID_DSMCC_B: return "DSMCC_B";
1272+
1273+ case AV_CODEC_ID_DVD_NAV: return "DVD NAV";
1274+
1275+ case AV_CODEC_ID_MPEG2TS: return "MPEG2TS";
1276+
1277+ /* Attachment codecs */
1278+ case AV_CODEC_ID_TTF: return "TTF font";
1279+
1280+ case AV_CODEC_ID_PROBE: return "PROBE";
1281+ }
1282+ return "Unknown Codec ID";
1283+}
1284+
1285+/** \fn codec_type_string(enum CodecType)
1286+ * returns a human readable string for the CodecType enum.
1287+ */
1288+const char *ff_codec_type_string(enum AVMediaType codec_type)
1289+{
1290+ switch (codec_type)
1291+ {
1292+ case AVMEDIA_TYPE_UNKNOWN: return "Unknown";
1293+ case AVMEDIA_TYPE_VIDEO: return "Video";
1294+ case AVMEDIA_TYPE_AUDIO: return "Audio";
1295+ case AVMEDIA_TYPE_DATA: return "Data";
1296+ case AVMEDIA_TYPE_SUBTITLE: return "Subtitle";
1297+ case AVMEDIA_TYPE_ATTACHMENT: return "Attachment";
1298+ }
1299+ return "Invalid Codec Type";
1300+};
1301+
1302diff --git a/libavcodec/v4l2_buffers.c b/libavcodec/v4l2_buffers.c
1303index 4b2679eb38..3ee6b135c6 100644
1304--- a/libavcodec/v4l2_buffers.c
1305+++ b/libavcodec/v4l2_buffers.c
1306@@ -21,6 +21,10 @@
1307 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1308 */
1309
1310+#include "config.h"
1311+#if CONFIG_LIBDRM
1312+#include <drm_fourcc.h>
1313+#endif
1314 #include <linux/videodev2.h>
1315 #include <sys/ioctl.h>
1316 #include <sys/mman.h>
1317@@ -30,6 +34,7 @@
1318 #include "libavcodec/avcodec.h"
1319 #include "libavcodec/internal.h"
1320 #include "libavutil/pixdesc.h"
1321+#include "libavutil/hwcontext.h"
1322 #include "v4l2_context.h"
1323 #include "v4l2_buffers.h"
1324 #include "v4l2_m2m.h"
1325@@ -134,6 +139,25 @@ static enum AVColorRange v4l2_get_color_range(V4L2Buffer *buf)
1326 return AVCOL_RANGE_UNSPECIFIED;
1327 }
1328
1329+static void v4l2_get_interlacing(AVFrame *frame, V4L2Buffer *buf)
1330+{
1331+ enum v4l2_field field;
1332+ field = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
1333+ buf->context->format.fmt.pix_mp.field :
1334+ buf->context->format.fmt.pix.field;
1335+
1336+ if (field == V4L2_FIELD_INTERLACED || field == V4L2_FIELD_INTERLACED_TB) {
1337+ frame->interlaced_frame = 1;
1338+ frame->top_field_first = 1;
1339+ } else if (field == V4L2_FIELD_INTERLACED_BT) {
1340+ frame->interlaced_frame = 1;
1341+ frame->top_field_first = 0;
1342+ } else {
1343+ frame->interlaced_frame = 0;
1344+ frame->top_field_first = 0;
1345+ }
1346+}
1347+
1348 static enum AVColorSpace v4l2_get_color_space(V4L2Buffer *buf)
1349 {
1350 enum v4l2_ycbcr_encoding ycbcr;
1351@@ -210,7 +234,81 @@ static enum AVColorTransferCharacteristic v4l2_get_color_trc(V4L2Buffer *buf)
1352 return AVCOL_TRC_UNSPECIFIED;
1353 }
1354
1355-static void v4l2_free_buffer(void *opaque, uint8_t *unused)
1356+#if CONFIG_LIBDRM
1357+static uint8_t * v4l2_get_drm_frame(V4L2Buffer *avbuf)
1358+{
1359+ AVDRMFrameDescriptor *drm_desc = &avbuf->drm_frame;
1360+ AVDRMLayerDescriptor *layer;
1361+
1362+ /* fill the DRM frame descriptor */
1363+ drm_desc->nb_objects = avbuf->num_planes;
1364+ drm_desc->nb_layers = 1;
1365+
1366+ layer = &drm_desc->layers[0];
1367+ layer->nb_planes = avbuf->num_planes;
1368+
1369+ for (int i = 0; i < avbuf->num_planes; i++) {
1370+ layer->planes[i].object_index = i;
1371+ layer->planes[i].offset = 0;
1372+ layer->planes[i].pitch = avbuf->plane_info[i].bytesperline;
1373+ }
1374+
1375+ switch (avbuf->context->av_pix_fmt) {
1376+ case AV_PIX_FMT_YUYV422:
1377+
1378+ layer->format = DRM_FORMAT_YUYV;
1379+ layer->nb_planes = 1;
1380+
1381+ break;
1382+
1383+ case AV_PIX_FMT_NV12:
1384+ case AV_PIX_FMT_NV21:
1385+
1386+ layer->format = avbuf->context->av_pix_fmt == AV_PIX_FMT_NV12 ?
1387+ DRM_FORMAT_NV12 : DRM_FORMAT_NV21;
1388+
1389+ if (avbuf->num_planes > 1)
1390+ break;
1391+
1392+ layer->nb_planes = 2;
1393+
1394+ layer->planes[1].object_index = 0;
1395+ layer->planes[1].offset = avbuf->plane_info[0].bytesperline *
1396+ avbuf->context->format.fmt.pix.height;
1397+ layer->planes[1].pitch = avbuf->plane_info[0].bytesperline;
1398+ break;
1399+
1400+ case AV_PIX_FMT_YUV420P:
1401+
1402+ layer->format = DRM_FORMAT_YUV420;
1403+
1404+ if (avbuf->num_planes > 1)
1405+ break;
1406+
1407+ layer->nb_planes = 3;
1408+
1409+ layer->planes[1].object_index = 0;
1410+ layer->planes[1].offset = avbuf->plane_info[0].bytesperline *
1411+ avbuf->context->format.fmt.pix.height;
1412+ layer->planes[1].pitch = avbuf->plane_info[0].bytesperline >> 1;
1413+
1414+ layer->planes[2].object_index = 0;
1415+ layer->planes[2].offset = layer->planes[1].offset +
1416+ ((avbuf->plane_info[0].bytesperline *
1417+ avbuf->context->format.fmt.pix.height) >> 2);
1418+ layer->planes[2].pitch = avbuf->plane_info[0].bytesperline >> 1;
1419+ break;
1420+
1421+ default:
1422+ drm_desc->nb_layers = 0;
1423+ break;
1424+ }
1425+
1426+ return (uint8_t *) drm_desc;
1427+}
1428+#endif
1429+
1430+static void v4l2_free_buffer(void *opaque, uint8_t *data)
1431 {
1432 V4L2Buffer* avbuf = opaque;
1433 V4L2m2mContext *s = buf_to_m2mctx(avbuf);
1434@@ -234,6 +332,40 @@ static void v4l2_free_buffer(void *opaque, uint8_t *unused)
1435 }
1436 }
1437
1438+#if CONFIG_LIBDRM
1439+static int v4l2_buffer_export_drm(V4L2Buffer* avbuf)
1440+{
1441+ struct v4l2_exportbuffer expbuf;
1442+ int i, ret;
1443+
1444+ for (i = 0; i < avbuf->num_planes; i++) {
1445+ memset(&expbuf, 0, sizeof(expbuf));
1446+
1447+ expbuf.index = avbuf->buf.index;
1448+ expbuf.type = avbuf->buf.type;
1449+ expbuf.plane = i;
1450+
1451+ ret = ioctl(buf_to_m2mctx(avbuf)->fd, VIDIOC_EXPBUF, &expbuf);
1452+ if (ret < 0)
1453+ return AVERROR(errno);
1454+
1455+ if (V4L2_TYPE_IS_MULTIPLANAR(avbuf->buf.type)) {
1456+ /* drm frame */
1457+ avbuf->drm_frame.objects[i].size = avbuf->buf.m.planes[i].length;
1458+ avbuf->drm_frame.objects[i].fd = expbuf.fd;
1459+ avbuf->drm_frame.objects[i].format_modifier = DRM_FORMAT_MOD_LINEAR;
1460+ } else {
1461+ /* drm frame */
1462+ avbuf->drm_frame.objects[0].size = avbuf->buf.length;
1463+ avbuf->drm_frame.objects[0].fd = expbuf.fd;
1464+ avbuf->drm_frame.objects[0].format_modifier = DRM_FORMAT_MOD_LINEAR;
1465+ }
1466+ }
1467+
1468+ return 0;
1469+}
1470+#endif
1471+
1472 static int v4l2_buf_increase_ref(V4L2Buffer *in)
1473 {
1474 V4L2m2mContext *s = buf_to_m2mctx(in);
1475@@ -254,6 +386,26 @@ static int v4l2_buf_increase_ref(V4L2Buffer *in)
1476 return 0;
1477 }
1478
1479+#if CONFIG_LIBDRM
1480+static int v4l2_buf_to_bufref_drm(V4L2Buffer *in, AVBufferRef **buf)
1481+{
1482+ int ret;
1483+
1484+ *buf = av_buffer_create((uint8_t *) &in->drm_frame,
1485+ sizeof(in->drm_frame),
1486+ v4l2_free_buffer,
1487+ in, AV_BUFFER_FLAG_READONLY);
1488+ if (!*buf)
1489+ return AVERROR(ENOMEM);
1490+
1491+ ret = v4l2_buf_increase_ref(in);
1492+ if (ret)
1493+ av_buffer_unref(buf);
1494+
1495+ return ret;
1496+}
1497+#endif
1498+
1499 static int v4l2_buf_to_bufref(V4L2Buffer *in, int plane, AVBufferRef **buf)
1500 {
1501 int ret;
1502@@ -423,9 +575,22 @@ int ff_v4l2_buffer_buf_to_avframe(AVFrame *frame, V4L2Buffer *avbuf)
1503 av_frame_unref(frame);
1504
1505 /* 1. get references to the actual data */
1506- ret = v4l2_buffer_buf_to_swframe(frame, avbuf);
1507- if (ret)
1508- return ret;
1509+ if (buf_to_m2mctx(avbuf)->output_drm) {
1510+#if CONFIG_LIBDRM
1511+ /* 1. get references to the actual data */
1512+ ret = v4l2_buf_to_bufref_drm(avbuf, &frame->buf[0]);
1513+ if (ret)
1514+ return ret;
1515+
1516+ frame->data[0] = (uint8_t *) v4l2_get_drm_frame(avbuf);
1517+ frame->format = AV_PIX_FMT_DRM_PRIME;
1518+ frame->hw_frames_ctx = av_buffer_ref(avbuf->context->frames_ref);
1519+#endif
1520+ } else {
1521+ ret = v4l2_buffer_buf_to_swframe(frame, avbuf);
1522+ if (ret)
1523+ return ret;
1524+ }
1525
1526 /* 2. get frame information */
1527 frame->key_frame = !!(avbuf->buf.flags & V4L2_BUF_FLAG_KEYFRAME);
1528@@ -435,6 +600,7 @@ int ff_v4l2_buffer_buf_to_avframe(AVFrame *frame, V4L2Buffer *avbuf)
1529 frame->color_trc = v4l2_get_color_trc(avbuf);
1530 frame->pts = v4l2_get_pts(avbuf);
1531 frame->pkt_dts = AV_NOPTS_VALUE;
1532+ v4l2_get_interlacing(frame, avbuf);
1533
1534 /* these values are updated also during re-init in v4l2_process_driver_event */
1535 frame->height = avbuf->context->height;
1536@@ -500,6 +666,27 @@ int ff_v4l2_buffer_initialize(V4L2Buffer* avbuf, int index)
1537 avbuf->buf.type = ctx->type;
1538 avbuf->buf.index = index;
1539
1540+ if (buf_to_m2mctx(avbuf)->output_drm) {
1541+ AVHWFramesContext *hwframes;
1542+
1543+ av_buffer_unref(&ctx->frames_ref);
1544+
1545+ ctx->frames_ref = av_hwframe_ctx_alloc(buf_to_m2mctx(avbuf)->device_ref);
1546+ if (!ctx->frames_ref) {
1547+ ret = AVERROR(ENOMEM);
1548+ return ret;
1549+ }
1550+
1551+ hwframes = (AVHWFramesContext*)ctx->frames_ref->data;
1552+ hwframes->format = AV_PIX_FMT_DRM_PRIME;
1553+ hwframes->sw_format = ctx->av_pix_fmt;
1554+ hwframes->width = ctx->width;
1555+ hwframes->height = ctx->height;
1556+ ret = av_hwframe_ctx_init(ctx->frames_ref);
1557+ if (ret < 0)
1558+ return ret;
1559+ }
1560+
1561 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
1562 avbuf->buf.length = VIDEO_MAX_PLANES;
1563 avbuf->buf.m.planes = avbuf->planes;
1564@@ -527,14 +714,22 @@ int ff_v4l2_buffer_initialize(V4L2Buffer* avbuf, int index)
1565
1566 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
1567 avbuf->plane_info[i].length = avbuf->buf.m.planes[i].length;
1568- avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.m.planes[i].length,
1569- PROT_READ | PROT_WRITE, MAP_SHARED,
1570- buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.planes[i].m.mem_offset);
1571+
1572+ if ((V4L2_TYPE_IS_OUTPUT(ctx->type) && buf_to_m2mctx(avbuf)->output_drm) ||
1573+ !buf_to_m2mctx(avbuf)->output_drm) {
1574+ avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.m.planes[i].length,
1575+ PROT_READ | PROT_WRITE, MAP_SHARED,
1576+ buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.planes[i].m.mem_offset);
1577+ }
1578 } else {
1579 avbuf->plane_info[i].length = avbuf->buf.length;
1580- avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.length,
1581- PROT_READ | PROT_WRITE, MAP_SHARED,
1582- buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.offset);
1583+
1584+ if ((V4L2_TYPE_IS_OUTPUT(ctx->type) && buf_to_m2mctx(avbuf)->output_drm) ||
1585+ !buf_to_m2mctx(avbuf)->output_drm) {
1586+ avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.length,
1587+ PROT_READ | PROT_WRITE, MAP_SHARED,
1588+ buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.offset);
1589+ }
1590 }
1591
1592 if (avbuf->plane_info[i].mm_addr == MAP_FAILED)
1593@@ -543,18 +738,24 @@ int ff_v4l2_buffer_initialize(V4L2Buffer* avbuf, int index)
1594
1595 avbuf->status = V4L2BUF_AVAILABLE;
1596
1597- if (V4L2_TYPE_IS_OUTPUT(ctx->type))
1598- return 0;
1599-
1600 if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
1601 avbuf->buf.m.planes = avbuf->planes;
1602 avbuf->buf.length = avbuf->num_planes;
1603-
1604 } else {
1605 avbuf->buf.bytesused = avbuf->planes[0].bytesused;
1606 avbuf->buf.length = avbuf->planes[0].length;
1607 }
1608
1609+ if (V4L2_TYPE_IS_OUTPUT(ctx->type))
1610+ return 0;
1611+
1612+#if CONFIG_LIBDRM
1613+ if (buf_to_m2mctx(avbuf)->output_drm) {
1614+ ret = v4l2_buffer_export_drm(avbuf);
1615+ if (ret)
1616+ return ret;
1617+ }
1618+#endif
1619 return ff_v4l2_buffer_enqueue(avbuf);
1620 }
1621
1622diff --git a/libavcodec/v4l2_buffers.h b/libavcodec/v4l2_buffers.h
1623index 8dbc7fc104..037e667997 100644
1624--- a/libavcodec/v4l2_buffers.h
1625+++ b/libavcodec/v4l2_buffers.h
1626@@ -27,6 +27,7 @@
1627 #include <stdatomic.h>
1628 #include <linux/videodev2.h>
1629
1630+#include "libavutil/hwcontext_drm.h"
1631 #include "avcodec.h"
1632
1633 enum V4L2Buffer_status {
1634@@ -42,6 +43,9 @@ typedef struct V4L2Buffer {
1635 /* each buffer needs to have a reference to its context */
1636 struct V4L2Context *context;
1637
1638+ /* DRM descriptor */
1639+ AVDRMFrameDescriptor drm_frame;
1640+
1641 /* This object is refcounted per-plane, so we need to keep track
1642 * of how many context-refs we are holding. */
1643 AVBufferRef *context_ref;
1644diff --git a/libavcodec/v4l2_context.c b/libavcodec/v4l2_context.c
1645index ff1ea8e57b..81874ea4af 100644
1646--- a/libavcodec/v4l2_context.c
1647+++ b/libavcodec/v4l2_context.c
1648@@ -303,8 +303,8 @@ static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
1649 "packets/frames.\n");
1650 }
1651
1652- /* if we are draining and there are no more capture buffers queued in the driver we are done */
1653- if (!V4L2_TYPE_IS_OUTPUT(ctx->type) && ctx_to_m2mctx(ctx)->draining) {
1654+ /* if there are no more capture buffers queued in the driver, skip polling */
1655+ if (!V4L2_TYPE_IS_OUTPUT(ctx->type)) {
1656 for (i = 0; i < ctx->num_buffers; i++) {
1657 /* capture buffer initialization happens during decode hence
1658 * detection happens at runtime
1659@@ -315,7 +315,9 @@ static V4L2Buffer* v4l2_dequeue_v4l2buf(V4L2Context *ctx, int timeout)
1660 if (ctx->buffers[i].status == V4L2BUF_IN_DRIVER)
1661 goto start;
1662 }
1663- ctx->done = 1;
1664+ /* if we were waiting to drain, all done! */
1665+ if (ctx_to_m2mctx(ctx)->draining)
1666+ ctx->done = 1;
1667 return NULL;
1668 }
1669
1670@@ -457,20 +459,51 @@ static int v4l2_release_buffers(V4L2Context* ctx)
1671 .type = ctx->type,
1672 .count = 0, /* 0 -> unmaps buffers from the driver */
1673 };
1674- int i, j;
1675+ int ret, i, j;
1676
1677 for (i = 0; i < ctx->num_buffers; i++) {
1678 V4L2Buffer *buffer = &ctx->buffers[i];
1679
1680 for (j = 0; j < buffer->num_planes; j++) {
1681 struct V4L2Plane_info *p = &buffer->plane_info[j];
1682+
1683+ if (V4L2_TYPE_IS_OUTPUT(ctx->type)) {
1684+ /* output buffers are not EXPORTED */
1685+ goto unmap;
1686+ }
1687+
1688+ if (ctx_to_m2mctx(ctx)->output_drm) {
1689+ /* use the DRM frame to close */
1690+ if (buffer->drm_frame.objects[j].fd >= 0) {
1691+ if (close(buffer->drm_frame.objects[j].fd) < 0) {
1692+ av_log(logger(ctx), AV_LOG_ERROR, "%s close drm fd "
1693+ "[buffer=%2d, plane=%d, fd=%2d] - %s \n",
1694+ ctx->name, i, j, buffer->drm_frame.objects[j].fd,
1695+ av_err2str(AVERROR(errno)));
1696+ }
1697+ }
1698+ }
1699+unmap:
1700 if (p->mm_addr && p->length)
1701 if (munmap(p->mm_addr, p->length) < 0)
1702 av_log(logger(ctx), AV_LOG_ERROR, "%s unmap plane (%s))\n", ctx->name, av_err2str(AVERROR(errno)));
1703 }
1704 }
1705
1706- return ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
1707+ ret = ioctl(ctx_to_m2mctx(ctx)->fd, VIDIOC_REQBUFS, &req);
1708+ if (ret < 0) {
1709+ av_log(logger(ctx), AV_LOG_ERROR, "release all %s buffers (%s)\n",
1710+ ctx->name, av_err2str(AVERROR(errno)));
1711+
1712+ if (ctx_to_m2mctx(ctx)->output_drm)
1713+ av_log(logger(ctx), AV_LOG_ERROR,
1714+ "Make sure the DRM client releases all FB/GEM objects before closing the codec (ie):\n"
1715+ "for all buffers: \n"
1716+ " 1. drmModeRmFB(..)\n"
1717+ " 2. drmIoctl(.., DRM_IOCTL_GEM_CLOSE,... )\n");
1718+ }
1719+
1720+ return ret;
1721 }
1722
1723 static inline int v4l2_try_raw_format(V4L2Context* ctx, enum AVPixelFormat pixfmt)
1724diff --git a/libavcodec/v4l2_context.h b/libavcodec/v4l2_context.h
1725index 22a9532444..e804e94131 100644
1726--- a/libavcodec/v4l2_context.h
1727+++ b/libavcodec/v4l2_context.h
1728@@ -92,6 +92,8 @@ typedef struct V4L2Context {
1729 */
1730 int done;
1731
1732+ AVBufferRef *frames_ref;
1733+
1734 } V4L2Context;
1735
1736 /**
1737diff --git a/libavcodec/v4l2_m2m.h b/libavcodec/v4l2_m2m.h
1738index b67b216331..adf5997bb5 100644
1739--- a/libavcodec/v4l2_m2m.h
1740+++ b/libavcodec/v4l2_m2m.h
1741@@ -66,6 +66,11 @@ typedef struct V4L2m2mContext {
1742
1743 /* reference back to V4L2m2mPriv */
1744 void *priv;
1745+
1746+ AVBufferRef *device_ref;
1747+
1748+ /* generate DRM frames */
1749+ int output_drm;
1750 } V4L2m2mContext;
1751
1752 typedef struct V4L2m2mPriv {
1753diff --git a/libavcodec/v4l2_m2m_dec.c b/libavcodec/v4l2_m2m_dec.c
1754index ab07c0a24a..4bb142b38a 100644
1755--- a/libavcodec/v4l2_m2m_dec.c
1756+++ b/libavcodec/v4l2_m2m_dec.c
1757@@ -23,12 +23,16 @@
1758
1759 #include <linux/videodev2.h>
1760 #include <sys/ioctl.h>
1761+
1762+#include "libavutil/hwcontext.h"
1763+#include "libavutil/hwcontext_drm.h"
1764 #include "libavutil/pixfmt.h"
1765 #include "libavutil/pixdesc.h"
1766 #include "libavutil/opt.h"
1767 #include "libavcodec/avcodec.h"
1768 #include "libavcodec/decode.h"
1769 #include "libavcodec/internal.h"
1770+#include "libavcodec/hwconfig.h"
1771
1772 #include "v4l2_context.h"
1773 #include "v4l2_m2m.h"
1774@@ -201,7 +205,34 @@ static av_cold int v4l2_decode_init(AVCodecContext *avctx)
1775 capture->av_codec_id = AV_CODEC_ID_RAWVIDEO;
1776 capture->av_pix_fmt = avctx->pix_fmt;
1777
1778+ /* the client requests the codec to generate DRM frames:
1779+ * - data[0] will therefore point to the returned AVDRMFrameDescriptor
1780+ * check the ff_v4l2_buffer_to_avframe conversion function.
1781+ * - the DRM frame format is passed in the DRM frame descriptor layer.
1782+ * check the v4l2_get_drm_frame function.
1783+ */
1784+ switch (ff_get_format(avctx, avctx->codec->pix_fmts)) {
1785+ case AV_PIX_FMT_DRM_PRIME:
1786+ s->output_drm = 1;
1787+ break;
1788+ case AV_PIX_FMT_NONE:
1789+ return 0;
1790+ break;
1791+ default:
1792+ break;
1793+ }
1794+
1795+ s->device_ref = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_DRM);
1796+ if (!s->device_ref) {
1797+ ret = AVERROR(ENOMEM);
1798+ return ret;
1799+ }
1800+
1801 s->avctx = avctx;
1802+ ret = av_hwdevice_ctx_init(s->device_ref);
1803+ if (ret < 0)
1804+ return ret;
1805+
1806 ret = ff_v4l2_m2m_codec_init(priv);
1807 if (ret) {
1808 av_log(avctx, AV_LOG_ERROR, "can't configure decoder\n");
1809@@ -216,19 +247,34 @@ static av_cold int v4l2_decode_close(AVCodecContext *avctx)
1810 return ff_v4l2_m2m_codec_end(avctx->priv_data);
1811 }
1812
1813+static void v4l2_flush(AVCodecContext *avctx)
1814+{
1815+ V4L2m2mPriv *priv = avctx->priv_data;
1816+ V4L2m2mContext* s = priv->context;
1817+
1818+ /* wait for pending buffer references */
1819+ if (atomic_load(&s->refcount))
1820+ while(sem_wait(&s->refsync) == -1 && errno == EINTR);
1821+}
1822+
1823 #define OFFSET(x) offsetof(V4L2m2mPriv, x)
1824 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1825
1826 static const AVOption options[] = {
1827 V4L_M2M_DEFAULT_OPTS,
1828 { "num_capture_buffers", "Number of buffers in the capture context",
1829- OFFSET(num_capture_buffers), AV_OPT_TYPE_INT, {.i64 = 20}, 20, INT_MAX, FLAGS },
1830+ OFFSET(num_capture_buffers), AV_OPT_TYPE_INT, {.i64 = 20}, 2, INT_MAX, FLAGS },
1831 { NULL},
1832 };
1833
1834+static const AVCodecHWConfigInternal *v4l2_m2m_hw_configs[] = {
1835+ HW_CONFIG_INTERNAL(DRM_PRIME),
1836+ NULL
1837+};
1838+
1839 #define M2MDEC_CLASS(NAME) \
1840 static const AVClass v4l2_m2m_ ## NAME ## _dec_class = { \
1841- .class_name = #NAME "_v4l2m2m_decoder", \
1842+ .class_name = #NAME "_v4l2_m2m_decoder", \
1843 .item_name = av_default_item_name, \
1844 .option = options, \
1845 .version = LIBAVUTIL_VERSION_INT, \
1846@@ -245,8 +291,13 @@ static const AVOption options[] = {
1847 .priv_class = &v4l2_m2m_ ## NAME ## _dec_class, \
1848 .init = v4l2_decode_init, \
1849 .receive_frame = v4l2_receive_frame, \
1850- .close = v4l2_decode_close, \
1851+ .close = v4l2_decode_close,\
1852+ .flush = v4l2_flush, \
1853+ .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_DRM_PRIME, \
1854+ AV_PIX_FMT_NV12, \
1855+ AV_PIX_FMT_NONE}, \
1856 .bsfs = bsf_name, \
1857+ .hw_configs = v4l2_m2m_hw_configs, \
1858 .capabilities = AV_CODEC_CAP_HARDWARE | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING, \
1859 .caps_internal = FF_CODEC_CAP_SETS_PKT_DTS | FF_CODEC_CAP_INIT_CLEANUP, \
1860 .wrapper_name = "v4l2m2m", \
1861diff --git a/libavdevice/opengl_enc.c b/libavdevice/opengl_enc.c
1862index 2bdb8da732..69468f62c1 100644
1863--- a/libavdevice/opengl_enc.c
1864+++ b/libavdevice/opengl_enc.c
1865@@ -37,6 +37,9 @@
1866 #include <OpenGL/gl3.h>
1867 #elif HAVE_ES2_GL_H
1868 #include <ES2/gl.h>
1869+#elif HAVE_EGL_EGL_H && HAVE_GLES2_GL2_H
1870+#include <EGL/egl.h>
1871+#include <GLES2/gl2.h>
1872 #else
1873 #include <GL/gl.h>
1874 #include <GL/glext.h>
1875@@ -495,6 +498,8 @@ static int av_cold opengl_load_procedures(OpenGLContext *opengl)
1876 #define SelectedGetProcAddress glXGetProcAddress
1877 #elif HAVE_WGLGETPROCADDRESS
1878 #define SelectedGetProcAddress wglGetProcAddress
1879+#elif HAVE_EGLGETPROCADDRESS
1880+#define SelectedGetProcAddress eglGetProcAddress
1881 #endif
1882
1883 #define LOAD_OPENGL_FUN(name, type) \
1884diff --git a/libavformat/Makefile b/libavformat/Makefile
1885index 0f340f74a0..c24bfbe3c3 100644
1886--- a/libavformat/Makefile
1887+++ b/libavformat/Makefile
1888@@ -21,6 +21,7 @@ OBJS = allformats.o \
1889 sdp.o \
1890 url.o \
1891 utils.o \
1892+ utils-mythtv.o \
1893
1894 OBJS-$(HAVE_LIBC_MSVCRT) += file_open.o
1895
1896@@ -349,6 +350,7 @@ OBJS-$(CONFIG_MPEG2SVCD_MUXER) += mpegenc.o
1897 OBJS-$(CONFIG_MPEG2VIDEO_MUXER) += rawenc.o
1898 OBJS-$(CONFIG_MPEG2VOB_MUXER) += mpegenc.o
1899 OBJS-$(CONFIG_MPEGPS_DEMUXER) += mpeg.o
1900+OBJS-$(CONFIG_MPEGTS_DEMUXER) += mpegts-mythtv.o
1901 OBJS-$(CONFIG_MPEGTS_DEMUXER) += mpegts.o
1902 OBJS-$(CONFIG_MPEGTS_MUXER) += mpegtsenc.o
1903 OBJS-$(CONFIG_MPEGVIDEO_DEMUXER) += mpegvideodec.o rawdec.o
1904diff --git a/libavformat/allformats.c b/libavformat/allformats.c
1905index a38fd1f583..150313e907 100644
1906--- a/libavformat/allformats.c
1907+++ b/libavformat/allformats.c
1908@@ -278,8 +278,10 @@ extern AVOutputFormat ff_mpeg2video_muxer;
1909 extern AVOutputFormat ff_mpeg2vob_muxer;
1910 extern AVInputFormat ff_mpegps_demuxer;
1911 extern AVInputFormat ff_mpegts_demuxer;
1912+extern AVInputFormat ff_mythtv_mpegts_demuxer;
1913 extern AVOutputFormat ff_mpegts_muxer;
1914 extern AVInputFormat ff_mpegtsraw_demuxer;
1915+extern AVInputFormat ff_mythtv_mpegtsraw_demuxer;
1916 extern AVInputFormat ff_mpegvideo_demuxer;
1917 extern AVInputFormat ff_mpjpeg_demuxer;
1918 extern AVOutputFormat ff_mpjpeg_muxer;
1919diff --git a/libavformat/avformat.h b/libavformat/avformat.h
1920index 56708c0241..454254a327 100644
1921--- a/libavformat/avformat.h
1922+++ b/libavformat/avformat.h
1923@@ -1094,6 +1094,14 @@ typedef struct AVStream {
1924 int nb_index_entries;
1925 unsigned int index_entries_allocated_size;
1926
1927+ /* mythtv addons */
1928+ int got_frame;
1929+
1930+ int component_tag; ///< Component tag given in PMT, for MythTV MHEG
1931+ int carousel_id;
1932+ int data_id;
1933+ /* end mythtv addons */
1934+
1935 /**
1936 * Stream Identifier
1937 * This is the MPEG-TS stream identifier +1
1938@@ -1358,6 +1366,16 @@ typedef struct AVFormatContext {
1939 unsigned int packet_size;
1940 int max_delay;
1941
1942+ /* Myth addons */
1943+ int build_index;
1944+
1945+ /* mpeg-ts support */
1946+ void (*streams_changed)(void*);
1947+ void *stream_change_data;
1948+ const uint8_t *cur_pmt_sect;
1949+ int cur_pmt_sect_len;
1950+ /* End Myth addons */
1951+
1952 /**
1953 * Flags modifying the (de)muxer behaviour. A combination of AVFMT_FLAG_*.
1954 * Set by the user before avformat_open_input() / avformat_write_header().
1955@@ -3005,6 +3023,17 @@ int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
1956 */
1957 AVRational av_stream_get_codec_timebase(const AVStream *st);
1958
1959+/* MythTV changes */
1960+
1961+#define MAX_STREAMS 100
1962+
1963+void estimate_timings(AVFormatContext *ic, int64_t old_offset);
1964+void av_estimate_timings(AVFormatContext *ic, int64_t old_offset);
1965+AVStream *av_add_stream(AVFormatContext *s, AVStream *st, int id);
1966+void av_remove_stream(AVFormatContext *s, int id, int remove_ts);
1967+void flush_packet_queue(AVFormatContext *s);
1968+/* End MythTV changes */
1969+
1970 /**
1971 * @}
1972 */
1973diff --git a/libavformat/format.c b/libavformat/format.c
1974index c47490c8eb..3e525ef779 100644
1975--- a/libavformat/format.c
1976+++ b/libavformat/format.c
1977@@ -29,6 +29,12 @@
1978 #include "id3v2.h"
1979 #include "internal.h"
1980
1981+/* MYTHTV CHANGES */
1982+extern AVInputFormat ff_mythtv_mpegts_demuxer;
1983+extern AVInputFormat ff_mythtv_mpegtsraw_demuxer;
1984+extern AVInputFormat ff_mpegts_demuxer;
1985+extern AVInputFormat ff_mpegtsraw_demuxer;
1986+/* END MYTHTV CHANGES */
1987
1988 /**
1989 * @file
1990@@ -192,8 +198,19 @@ ff_const59 AVInputFormat *av_probe_input_format3(ff_const59 AVProbeData *pd, int
1991 if (score > score_max) {
1992 score_max = score;
1993 fmt = (AVInputFormat*)fmt1;
1994- } else if (score == score_max)
1995- fmt = NULL;
1996+ } else if (score == score_max) {
1997+ // if the conflict is between Myth MPEGTS demux and FFMPEG's origin
1998+ // use mythtv's one
1999+ if ((fmt1 == &ff_mpegts_demuxer && fmt == &ff_mythtv_mpegts_demuxer) ||
2000+ (fmt == &ff_mpegts_demuxer && fmt1 == &ff_mythtv_mpegts_demuxer)) {
2001+ fmt = &ff_mythtv_mpegts_demuxer;
2002+ } else if ((fmt1 == &ff_mpegts_demuxer && fmt == &ff_mythtv_mpegtsraw_demuxer) ||
2003+ (fmt == &ff_mpegts_demuxer && fmt1 == &ff_mythtv_mpegtsraw_demuxer)) {
2004+ fmt = &ff_mythtv_mpegtsraw_demuxer;
2005+ } else {
2006+ fmt = NULL;
2007+ }
2008+ }
2009 }
2010 if (nodat == ID3_GREATER_PROBE)
2011 score_max = FFMIN(AVPROBE_SCORE_EXTENSION / 2 - 1, score_max);
2012diff --git a/libavformat/isom.h b/libavformat/isom.h
2013index 5a6d504090..aae6209026 100644
2014--- a/libavformat/isom.h
2015+++ b/libavformat/isom.h
2016@@ -244,7 +244,7 @@ typedef struct MOVStreamContext {
2017 } MOVStreamContext;
2018
2019 typedef struct MOVContext {
2020- const AVClass *class; ///< class for private options
2021+ const AVClass *avclass; ///< class for private options
2022 AVFormatContext *fc;
2023 int time_scale;
2024 int64_t duration; ///< duration of the longest track
2025diff --git a/libavformat/libavformat.v b/libavformat/libavformat.v
2026index 47d5ddcdb1..3607ad2e55 100644
2027--- a/libavformat/libavformat.v
2028+++ b/libavformat/libavformat.v
2029@@ -1,6 +1,24 @@
2030 LIBAVFORMAT_MAJOR {
2031 global:
2032 av*;
2033+ ffurl_read;
2034+ ffurl_read_complete;
2035+ ffurl_seek;
2036+ ffurl_size;
2037+ ffurl_protocol_next;
2038+ ffurl_open;
2039+ ffurl_open_whitelist;
2040+ ffurl_close;
2041+ ffurl_write;
2042+ url_*;
2043+ ff_timefilter_destroy;
2044+ ff_timefilter_new;
2045+ ff_timefilter_update;
2046+ ff_timefilter_reset;
2047+ get_*;
2048+ put_*;
2049+ ff_codec_get_id;
2050+ ff_read_frame_flush;
2051 local:
2052 *;
2053 };
2054diff --git a/libavformat/mov.c b/libavformat/mov.c
2055index 4af796ee31..b86f437cf6 100644
2056--- a/libavformat/mov.c
2057+++ b/libavformat/mov.c
2058@@ -7842,8 +7842,9 @@ static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st)
2059 if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) ||
2060 ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
2061 ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && dts != AV_NOPTS_VALUE &&
2062- ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) ||
2063- (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) {
2064+ /* MythTV change here to use 4*AV_TIME_BASE instead of AV_TIME_BASE */
2065+ ((FFABS(best_dts - dts) <= 4*AV_TIME_BASE && current_sample->pos < sample->pos) ||
2066+ (FFABS(best_dts - dts) > 4*AV_TIME_BASE && dts < best_dts)))))) {
2067 sample = current_sample;
2068 best_dts = dts;
2069 *st = avst;
2070diff --git a/libavformat/mpeg.c b/libavformat/mpeg.c
2071index 79610ec600..84666b1406 100644
2072--- a/libavformat/mpeg.c
2073+++ b/libavformat/mpeg.c
2074@@ -519,34 +519,37 @@ redo:
2075 }
2076
2077 es_type = m->psm_es_type[startcode & 0xff];
2078- if (es_type == STREAM_TYPE_VIDEO_MPEG1) {
2079- codec_id = AV_CODEC_ID_MPEG2VIDEO;
2080- type = AVMEDIA_TYPE_VIDEO;
2081- } else if (es_type == STREAM_TYPE_VIDEO_MPEG2) {
2082- codec_id = AV_CODEC_ID_MPEG2VIDEO;
2083- type = AVMEDIA_TYPE_VIDEO;
2084- } else if (es_type == STREAM_TYPE_AUDIO_MPEG1 ||
2085- es_type == STREAM_TYPE_AUDIO_MPEG2) {
2086- codec_id = AV_CODEC_ID_MP3;
2087- type = AVMEDIA_TYPE_AUDIO;
2088- } else if (es_type == STREAM_TYPE_AUDIO_AAC) {
2089- codec_id = AV_CODEC_ID_AAC;
2090- type = AVMEDIA_TYPE_AUDIO;
2091- } else if (es_type == STREAM_TYPE_VIDEO_MPEG4) {
2092- codec_id = AV_CODEC_ID_MPEG4;
2093- type = AVMEDIA_TYPE_VIDEO;
2094- } else if (es_type == STREAM_TYPE_VIDEO_H264) {
2095- codec_id = AV_CODEC_ID_H264;
2096- type = AVMEDIA_TYPE_VIDEO;
2097- } else if (es_type == STREAM_TYPE_VIDEO_HEVC) {
2098- codec_id = AV_CODEC_ID_HEVC;
2099- type = AVMEDIA_TYPE_VIDEO;
2100- } else if (es_type == STREAM_TYPE_AUDIO_AC3) {
2101- codec_id = AV_CODEC_ID_AC3;
2102- type = AVMEDIA_TYPE_AUDIO;
2103- } else if (m->imkh_cctv && es_type == 0x91) {
2104- codec_id = AV_CODEC_ID_PCM_MULAW;
2105- type = AVMEDIA_TYPE_AUDIO;
2106+ if (es_type == STREAM_TYPE_VIDEO_MPEG1) {
2107+ codec_id = AV_CODEC_ID_MPEG2VIDEO;
2108+ type = AVMEDIA_TYPE_VIDEO;
2109+ } else if (es_type == STREAM_TYPE_VIDEO_MPEG2) {
2110+ codec_id = AV_CODEC_ID_MPEG2VIDEO;
2111+ type = AVMEDIA_TYPE_VIDEO;
2112+ } else if (es_type == STREAM_TYPE_AUDIO_MPEG1 ||
2113+ es_type == STREAM_TYPE_AUDIO_MPEG2) {
2114+ codec_id = AV_CODEC_ID_MP3;
2115+ type = AVMEDIA_TYPE_AUDIO;
2116+ } else if (es_type == STREAM_TYPE_AUDIO_AAC) {
2117+ codec_id = AV_CODEC_ID_AAC;
2118+ type = AVMEDIA_TYPE_AUDIO;
2119+ } else if (es_type == STREAM_TYPE_AUDIO_AAC_LATM) {
2120+ codec_id = AV_CODEC_ID_AAC_LATM;
2121+ type = AVMEDIA_TYPE_AUDIO;
2122+ } else if (es_type == STREAM_TYPE_VIDEO_MPEG4) {
2123+ codec_id = AV_CODEC_ID_MPEG4;
2124+ type = AVMEDIA_TYPE_VIDEO;
2125+ } else if (es_type == STREAM_TYPE_VIDEO_H264) {
2126+ codec_id = AV_CODEC_ID_H264;
2127+ type = AVMEDIA_TYPE_VIDEO;
2128+ } else if (es_type == STREAM_TYPE_VIDEO_HEVC) {
2129+ codec_id = AV_CODEC_ID_HEVC;
2130+ type = AVMEDIA_TYPE_VIDEO;
2131+ } else if (es_type == STREAM_TYPE_AUDIO_AC3) {
2132+ codec_id = AV_CODEC_ID_AC3;
2133+ type = AVMEDIA_TYPE_AUDIO;
2134+ } else if (m->imkh_cctv && es_type == 0x91) {
2135+ codec_id = AV_CODEC_ID_PCM_MULAW;
2136+ type = AVMEDIA_TYPE_AUDIO;
2137 } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
2138 static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
2139 unsigned char buf[8];
2140@@ -600,6 +603,9 @@ redo:
2141 } else if (startcode >= 0x20 && startcode <= 0x3f) {
2142 type = AVMEDIA_TYPE_SUBTITLE;
2143 codec_id = AV_CODEC_ID_DVD_SUBTITLE;
2144+ } else if (startcode == 0x69 || startcode == 0x49) {
2145+ type = AVMEDIA_TYPE_DATA;
2146+ codec_id = AV_CODEC_ID_MPEG2VBI;
2147 } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) {
2148 type = AVMEDIA_TYPE_VIDEO;
2149 codec_id = AV_CODEC_ID_VC1;
2150@@ -625,6 +631,11 @@ skip:
2151 st->internal->request_probe = request_probe;
2152 st->need_parsing = AVSTREAM_PARSE_FULL;
2153
2154+ /* notify the callback of the change in streams */
2155+ if (s->streams_changed) {
2156+ s->streams_changed(s->stream_change_data);
2157+ }
2158+
2159 found:
2160 if (st->discard >= AVDISCARD_ALL)
2161 goto skip;
2162diff --git a/libavformat/mpeg.h b/libavformat/mpeg.h
2163index b635295776..640755deab 100644
2164--- a/libavformat/mpeg.h
2165+++ b/libavformat/mpeg.h
2166@@ -54,6 +54,7 @@
2167 #define STREAM_TYPE_PRIVATE_DATA 0x06
2168 #define STREAM_TYPE_AUDIO_AAC 0x0f
2169 #define STREAM_TYPE_VIDEO_MPEG4 0x10
2170+#define STREAM_TYPE_AUDIO_AAC_LATM 0x11
2171 #define STREAM_TYPE_VIDEO_H264 0x1b
2172 #define STREAM_TYPE_VIDEO_HEVC 0x24
2173 #define STREAM_TYPE_VIDEO_CAVS 0x42
2174diff --git a/libavformat/mpegts-mythtv.c b/libavformat/mpegts-mythtv.c
2175new file mode 100644
2176index 0000000000..e820f134db
2177--- /dev/null
2178+++ b/libavformat/mpegts-mythtv.c
2179@@ -0,0 +1,3234 @@
2180+/*
2181+ * MPEG2 transport stream (aka DVB) demuxer
2182+ * Copyright (c) 2002-2003 Fabrice Bellard
2183+ * Reworked for use with MythTV
2184+ *
2185+ * This file is part of MythTV.
2186+ *
2187+ * FFmpeg is free software; you can redistribute it and/or
2188+ * modify it under the terms of the GNU Lesser General Public
2189+ * License as published by the Free Software Foundation; either
2190+ * version 2.1 of the License, or (at your option) any later version.
2191+ *
2192+ * FFmpeg is distributed in the hope that it will be useful,
2193+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
2194+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2195+ * Lesser General Public License for more details.
2196+ *
2197+ * You should have received a copy of the GNU Lesser General Public
2198+ * License along with FFmpeg; if not, write to the Free Software
2199+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2200+ */
2201+
2202+#include "libavutil/crc.h"
2203+#include "libavutil/intreadwrite.h"
2204+#include "libavutil/log.h"
2205+#include "libavutil/dict.h"
2206+#include "libavutil/mathematics.h"
2207+#include "libavutil/opt.h"
2208+#include "libavutil/avassert.h"
2209+#include "libavcodec/bytestream.h"
2210+#include "libavcodec/avcodec.h"
2211+#include "libavcodec/get_bits.h"
2212+#include "avformat.h"
2213+#include "mpegts-mythtv.h"
2214+#include "internal.h"
2215+#include "avio_internal.h"
2216+#include "mpeg.h"
2217+#include "isom.h"
2218+#include "internal.h"
2219+
2220+/**
2221+ * av_dlog macros
2222+ * copied from libavutil/log.h since they are deprecated and removed from there
2223+ * Useful to print debug messages that shouldn't get compiled in normally.
2224+ */
2225+
2226+#ifdef DEBUG
2227+# define av_dlog(pctx, ...) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__)
2228+#else
2229+# define av_dlog(pctx, ...) do { if (0) av_log(pctx, AV_LOG_DEBUG, __VA_ARGS__); } while (0)
2230+#endif
2231+
2232+/* maximum size in which we look for synchronisation if
2233+ synchronisation is lost */
2234+#define MAX_RESYNC_SIZE 65536
2235+
2236+#define MAX_PES_PAYLOAD 200*1024
2237+
2238+#define MAX_MP4_DESCR_COUNT 16
2239+
2240+#define PMT_NOT_YET_FOUND 0
2241+#define PMT_NOT_IN_PAT 1
2242+#define PMT_FOUND 2
2243+
2244+typedef struct SectionContext SectionContext;
2245+
2246+static SectionContext *add_section_stream(MpegTSContext *ts, int pid, int stream_type);
2247+static void mpegts_cleanup_streams(MpegTSContext *ts);
2248+static int find_in_list(const int *pids, int pid);
2249+
2250+enum MpegTSFilterType {
2251+ MPEGTS_PES,
2252+ MPEGTS_SECTION,
2253+};
2254+
2255+typedef struct MpegTSFilter MpegTSFilter;
2256+
2257+
2258+static int is_pat_same(MpegTSContext *mpegts_ctx,
2259+ int *pmt_pnums, int *pmts_pids, unsigned int pmt_count);
2260+
2261+static void mpegts_add_stream(MpegTSContext *ts, int id, pmt_entry_t* item, uint32_t prog_reg_desc, int pcr_pid);
2262+static int pmt_equal_streams(MpegTSContext *mpegts_ctx,
2263+ pmt_entry_t* items, int item_cnt);
2264+
2265+typedef int PESCallback(MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos);
2266+
2267+typedef struct MpegTSPESFilter {
2268+ PESCallback *pes_cb;
2269+ void *opaque;
2270+} MpegTSPESFilter;
2271+
2272+typedef void SectionCallback(MpegTSFilter *f, const uint8_t *buf, int len);
2273+
2274+typedef void SetServiceCallback(void *opaque, int ret);
2275+
2276+typedef struct MpegTSSectionFilter {
2277+ int section_index;
2278+ int section_h_size;
2279+ uint8_t *section_buf;
2280+ unsigned int check_crc:1;
2281+ unsigned int end_of_section_reached:1;
2282+ SectionCallback *section_cb;
2283+ void *opaque;
2284+} MpegTSSectionFilter;
2285+
2286+struct MpegTSFilter {
2287+ int pid;
2288+ int es_id;
2289+ int last_cc; /* last cc code (-1 if first packet) */
2290+ enum MpegTSFilterType type;
2291+ /** if set, chop off PMT at the end of the TS packet, regardless of the
2292+ * data length given in the packet. This is for use by BBC iPlayer IPTV
2293+ * recordings which seem to only want to send the first packet of the PMT
2294+ * but give a length that requires 3 packets. Without this, those
2295+ * recordings are unplayable */
2296+ int pmt_chop_at_ts;
2297+ union {
2298+ MpegTSPESFilter pes_filter;
2299+ MpegTSSectionFilter section_filter;
2300+ } u;
2301+};
2302+
2303+/** maximum number of PMT's we expect to be described in a PAT */
2304+#define PAT_MAX_PMT 128
2305+
2306+/** maximum number of streams we expect to be described in a PMT */
2307+#define PMT_PIDS_MAX 256
2308+
2309+#define MAX_PIDS_PER_PROGRAM 64
2310+struct Program {
2311+ unsigned int id; //program id/service id
2312+ unsigned int pid; // PMT PID
2313+ unsigned int nb_pids;
2314+ unsigned int pids[MAX_PIDS_PER_PROGRAM];
2315+};
2316+
2317+struct MpegTSContext {
2318+ const AVClass *class;
2319+ /* user data */
2320+ AVFormatContext *stream;
2321+ /** raw packet size, including FEC if present */
2322+ int raw_packet_size;
2323+
2324+ int pos47;
2325+
2326+ /** if true, all pids are analyzed to find streams */
2327+ int auto_guess;
2328+
2329+ /** compute exact PCR for each transport stream packet */
2330+ int mpeg2ts_compute_pcr;
2331+
2332+ int64_t cur_pcr; /**< used to estimate the exact PCR */
2333+ int pcr_incr; /**< used to estimate the exact PCR */
2334+
2335+ /** if set, stop_parse is set when PAT/PMT is found */
2336+ int scanning;
2337+ /* data needed to handle file based ts */
2338+ /** stop parsing loop */
2339+ int stop_parse;
2340+ /** set to PMT_NOT_IN_PAT in pat_cb when scanning is true
2341+ * and the MPEG program number "req_sid" is not found in PAT;
2342+ * set to PMT_FOUND when a PMT with a the "req_sid" program
2343+ * number is found. */
2344+ int pmt_scan_state;
2345+ /** packet containing Audio/Video data */
2346+ AVPacket *pkt;
2347+ /** to detect seek */
2348+ int64_t last_pos;
2349+
2350+ /******************************************/
2351+ /* private mpegts data */
2352+ /* scan context */
2353+ /** structure to keep track of Program->pids mapping */
2354+ unsigned int nb_prg;
2355+ struct Program *prg;
2356+
2357+ /** filter for the PAT */
2358+ MpegTSFilter *pat_filter;
2359+ /** filter for the PMT for the MPEG program number specified by req_sid */
2360+ MpegTSFilter *pmt_filter;
2361+ /** MPEG program number of stream we want to decode */
2362+ int req_sid;
2363+
2364+ /** filters for various streams specified by PMT + for the PAT and PMT */
2365+ MpegTSFilter *pids[NB_PID_MAX];
2366+
2367+ /** number of streams in the last PMT seen */
2368+ int pid_cnt;
2369+ /** list of streams in the last PMT seen */
2370+ int pmt_pids[PMT_PIDS_MAX];
2371+};
2372+
2373+static const AVOption options[] = {
2374+ {"compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT,
2375+ {.dbl = 0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
2376+ { NULL },
2377+};
2378+
2379+static const AVClass mpegtsraw_class = {
2380+ .class_name = "mpegtsraw demuxer",
2381+ .item_name = av_default_item_name,
2382+ .option = options,
2383+ .version = LIBAVUTIL_VERSION_INT,
2384+};
2385+
2386+/* TS stream handling */
2387+
2388+enum MpegTSState {
2389+ MPEGTS_HEADER = 0,
2390+ MPEGTS_PESHEADER,
2391+ MPEGTS_PESHEADER_FILL,
2392+ MPEGTS_PAYLOAD,
2393+ MPEGTS_SKIP,
2394+};
2395+
2396+/* enough for PES header + length */
2397+#define PES_START_SIZE 6
2398+#define PES_HEADER_SIZE 9
2399+#define MAX_PES_HEADER_SIZE (9 + 255)
2400+
2401+typedef struct PESContext {
2402+ int pid;
2403+ int pcr_pid; /**< if -1 then all packets containing PCR are considered */
2404+ int stream_type;
2405+ MpegTSContext *ts;
2406+ AVFormatContext *stream;
2407+ AVStream *st;
2408+ AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */
2409+ enum MpegTSState state;
2410+ /* used to get the format */
2411+ int data_index;
2412+ int flags; /**< copied to the AVPacket flags */
2413+ int total_size;
2414+ int pes_header_size;
2415+ int extended_stream_id;
2416+ int64_t pts, dts;
2417+ int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */
2418+ uint8_t header[MAX_PES_HEADER_SIZE];
2419+ uint8_t *buffer;
2420+ SLConfigDescr sl;
2421+} PESContext;
2422+
2423+extern AVInputFormat ff_mythtv_mpegts_demuxer;
2424+
2425+struct SectionContext {
2426+ int pid;
2427+ int stream_type;
2428+ int new_packet;
2429+ MpegTSContext *ts;
2430+ AVFormatContext *stream;
2431+ AVStream *st;
2432+};
2433+
2434+static void clear_program(MpegTSContext *ts, unsigned int programid)
2435+{
2436+ int i;
2437+
2438+ for(i=0; i<ts->nb_prg; i++)
2439+ if(ts->prg[i].id == programid)
2440+ ts->prg[i].nb_pids = 0;
2441+}
2442+
2443+static void clear_programs(MpegTSContext *ts)
2444+{
2445+ av_freep(&ts->prg);
2446+ ts->nb_prg=0;
2447+}
2448+
2449+static void add_pat_entry(MpegTSContext *ts, unsigned int programid, unsigned int pid)
2450+{
2451+ struct Program *p;
2452+ void *tmp = av_realloc(ts->prg, (ts->nb_prg+1)*sizeof(struct Program));
2453+ if(!tmp)
2454+ return;
2455+ ts->prg = tmp;
2456+ p = &ts->prg[ts->nb_prg];
2457+ p->id = programid;
2458+ p->pid = pid;
2459+ p->nb_pids = 0;
2460+ ts->nb_prg++;
2461+}
2462+
2463+static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid)
2464+{
2465+ int i;
2466+ struct Program *p = NULL;
2467+ for(i=0; i<ts->nb_prg; i++) {
2468+ if(ts->prg[i].id == programid) {
2469+ p = &ts->prg[i];
2470+ break;
2471+ }
2472+ }
2473+ if(!p)
2474+ return;
2475+
2476+ if(p->nb_pids >= MAX_PIDS_PER_PROGRAM)
2477+ return;
2478+ p->pids[p->nb_pids++] = pid;
2479+}
2480+
2481+static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid)
2482+{
2483+ int i;
2484+ for(i=0; i<s->nb_programs; i++) {
2485+ if(s->programs[i]->id == programid) {
2486+ s->programs[i]->pcr_pid = pid;
2487+ break;
2488+ }
2489+ }
2490+}
2491+
2492+static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter);
2493+
2494+/**
2495+ * @brief discard_pid() decides if the pid is to be discarded according
2496+ * to caller's programs selection
2497+ * @param ts : - TS context
2498+ * @param pid : - pid
2499+ * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
2500+ * 0 otherwise
2501+ */
2502+static int discard_pid(MpegTSContext *ts, unsigned int pid)
2503+{
2504+ int i, j, k;
2505+ int used = 0, discarded = 0;
2506+ struct Program *p;
2507+ for(i=0; i<ts->nb_prg; i++) {
2508+ p = &ts->prg[i];
2509+ for(j=0; j<p->nb_pids; j++) {
2510+ if(p->pids[j] != pid)
2511+ continue;
2512+ //is program with id p->id set to be discarded?
2513+ for(k=0; k<ts->stream->nb_programs; k++) {
2514+ if(ts->stream->programs[k]->id == p->id) {
2515+ if(ts->stream->programs[k]->discard == AVDISCARD_ALL)
2516+ discarded++;
2517+ else
2518+ used++;
2519+ }
2520+ }
2521+ }
2522+ }
2523+
2524+ return !used && discarded;
2525+}
2526+
2527+//ugly forward declaration
2528+static void mpegts_push_section(MpegTSFilter *filter, const uint8_t *section, int section_len);
2529+
2530+/** \fn write_section_data(AVFormatContext*,MpegTSFilter*,const uint8_t*,int,int)
2531+ * Assemble PES packets out of TS packets, and then call the "section_cb"
2532+ * function when they are complete.
2533+ *
2534+ * NOTE: "DVB Section" is DVB terminology for an MPEG PES packet.
2535+ */
2536+static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
2537+ const uint8_t *buf, int buf_size, int is_start)
2538+{
2539+ MpegTSSectionFilter *tss = &tss1->u.section_filter;
2540+ int len;
2541+
2542+ assert(tss->section_buf);
2543+
2544+ if (is_start) {
2545+ memcpy(tss->section_buf, buf, buf_size);
2546+ tss->section_index = buf_size;
2547+ tss->section_h_size = -1;
2548+ tss->end_of_section_reached = 0;
2549+ } else {
2550+ if (tss->end_of_section_reached)
2551+ return;
2552+ len = 4096 - tss->section_index;
2553+ if (buf_size < len)
2554+ len = buf_size;
2555+ memcpy(tss->section_buf + tss->section_index, buf, len);
2556+ tss->section_index += len;
2557+ }
2558+
2559+ if (tss->section_cb == mpegts_push_section) {
2560+ SectionContext *sect = tss->opaque;
2561+ sect->new_packet = 1;
2562+ }
2563+ while (!tss->end_of_section_reached) {
2564+ /* compute section length if possible */
2565+ if (tss->section_h_size == -1 && tss->section_index >= 3) {
2566+ len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3;
2567+ if (len > 4096)
2568+ return;
2569+ tss->section_h_size = len;
2570+ }
2571+
2572+ if (tss->section_h_size == -1 ||
2573+ tss->section_index < tss->section_h_size)
2574+ {
2575+ if (tss1->pmt_chop_at_ts && tss->section_buf[0] == PMT_TID)
2576+ {
2577+ /* HACK! To allow BBC IPTV streams with incomplete PMTs (they
2578+ * advertise a length of 383, but only send 182 bytes!), we
2579+ * will not wait for the remainder of the PMT, but accept just
2580+ * what is in the first TS payload, as this is enough to get
2581+ * playback, although some PIDs may be filtered out as a result
2582+ */
2583+ tss->section_h_size = tss->section_index;
2584+ }
2585+ else
2586+ break;
2587+ }
2588+
2589+ if (!tss->check_crc ||
2590+ av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1,
2591+ tss->section_buf, tss->section_h_size) == 0)
2592+ tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
2593+ else
2594+ av_log(s, AV_LOG_WARNING, "write_section_data: PID %#x CRC error\n", tss1->pid);
2595+
2596+ if (tss->section_index > tss->section_h_size) {
2597+ int left = tss->section_index - tss->section_h_size;
2598+ memmove(tss->section_buf, tss->section_buf+tss->section_h_size,
2599+ left);
2600+ tss->section_index = left;
2601+ tss->section_h_size = -1;
2602+ } else {
2603+ tss->end_of_section_reached = 1;
2604+ }
2605+ }
2606+}
2607+
2608+static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
2609+ SectionCallback *section_cb, void *opaque,
2610+ int check_crc)
2611+
2612+{
2613+ MpegTSFilter *filter = ts->pids[pid];
2614+ MpegTSSectionFilter *sec;
2615+
2616+ av_dlog(ts->stream, "Filter: pid=0x%x\n", pid);
2617+
2618+ if (filter) {
2619+#ifdef DEBUG
2620+ av_log(ts->stream, AV_LOG_DEBUG, "Filter Already Exists\n");
2621+#endif
2622+ mpegts_close_filter(ts, filter);
2623+ }
2624+
2625+ if (pid >= NB_PID_MAX || ts->pids[pid])
2626+ return NULL;
2627+ filter = av_mallocz(sizeof(MpegTSFilter));
2628+ if (!filter)
2629+ return NULL;
2630+ ts->pids[pid] = filter;
2631+ filter->type = MPEGTS_SECTION;
2632+ filter->pid = pid;
2633+ filter->es_id = -1;
2634+ filter->last_cc = -1;
2635+ filter->pmt_chop_at_ts = 0;
2636+ sec = &filter->u.section_filter;
2637+ sec->section_cb = section_cb;
2638+ sec->opaque = opaque;
2639+ sec->section_buf = av_malloc(MAX_SECTION_SIZE);
2640+ sec->check_crc = check_crc;
2641+ if (!sec->section_buf) {
2642+ av_free(filter);
2643+ return NULL;
2644+ }
2645+ return filter;
2646+}
2647+
2648+static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
2649+ PESCallback *pes_cb,
2650+ void *opaque)
2651+{
2652+ MpegTSFilter *filter;
2653+ MpegTSPESFilter *pes;
2654+
2655+ if (pid >= NB_PID_MAX || ts->pids[pid])
2656+ return NULL;
2657+ filter = av_mallocz(sizeof(MpegTSFilter));
2658+ if (!filter)
2659+ return NULL;
2660+ ts->pids[pid] = filter;
2661+ filter->type = MPEGTS_PES;
2662+ filter->pid = pid;
2663+ filter->es_id = -1;
2664+ filter->last_cc = -1;
2665+ pes = &filter->u.pes_filter;
2666+ pes->pes_cb = pes_cb;
2667+ pes->opaque = opaque;
2668+ return filter;
2669+}
2670+
2671+static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
2672+{
2673+ int pid;
2674+
2675+ if (!ts || !filter)
2676+ return;
2677+
2678+ pid = filter->pid;
2679+
2680+#ifdef DEBUG
2681+ av_log(NULL, AV_LOG_DEBUG, "Closing Filter: pid=0x%x\n", pid);
2682+#endif
2683+ if (filter == ts->pmt_filter)
2684+ {
2685+ av_log(NULL, AV_LOG_DEBUG, "Closing PMT Filter: pid=0x%x\n", pid);
2686+ ts->pmt_filter = NULL;
2687+ }
2688+ if (filter == ts->pat_filter)
2689+ {
2690+ av_log(NULL, AV_LOG_DEBUG, "Closing PAT Filter: pid=0x%x\n", pid);
2691+ ts->pat_filter = NULL;
2692+ }
2693+
2694+ if (filter->type == MPEGTS_SECTION)
2695+ av_freep(&filter->u.section_filter.section_buf);
2696+ else if (filter->type == MPEGTS_PES) {
2697+ PESContext *pes = filter->u.pes_filter.opaque;
2698+ av_freep(&pes->buffer);
2699+ /* referenced private data will be freed later in
2700+ * avformat_close_input */
2701+ if (!((PESContext *)filter->u.pes_filter.opaque)->st) {
2702+ av_freep(&filter->u.pes_filter.opaque);
2703+ }
2704+ }
2705+
2706+ av_free(filter);
2707+ ts->pids[pid] = NULL;
2708+}
2709+
2710+static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
2711+ int stat[TS_MAX_PACKET_SIZE];
2712+ int i;
2713+ int x=0;
2714+ int best_score=0;
2715+
2716+ memset(stat, 0, packet_size*sizeof(int));
2717+
2718+ for(x=i=0; i<size-3; i++){
2719+ if(buf[i] == 0x47 && !(buf[i+1] & 0x80) && buf[i+3] != 0x47){
2720+ stat[x]++;
2721+ if(stat[x] > best_score){
2722+ best_score= stat[x];
2723+ if(index) *index= x;
2724+ }
2725+ }
2726+
2727+ x++;
2728+ if(x == packet_size) x= 0;
2729+ }
2730+
2731+ return best_score;
2732+}
2733+
2734+/* autodetect fec presence. Must have at least 1024 bytes */
2735+static int get_packet_size(const uint8_t *buf, int size)
2736+{
2737+ int score, fec_score, dvhs_score;
2738+
2739+ if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
2740+ return -1;
2741+
2742+ score = analyze(buf, size, TS_PACKET_SIZE, NULL);
2743+ dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
2744+ fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
2745+// av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
2746+
2747+ if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
2748+ else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
2749+ else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
2750+ else return -1;
2751+}
2752+
2753+typedef struct SectionHeader {
2754+ uint8_t tid;
2755+ uint16_t id;
2756+ uint8_t version;
2757+ uint8_t sec_num;
2758+ uint8_t last_sec_num;
2759+} SectionHeader;
2760+
2761+static inline int get8(const uint8_t **pp, const uint8_t *p_end)
2762+{
2763+ const uint8_t *p;
2764+ int c;
2765+
2766+ p = *pp;
2767+ if (p >= p_end)
2768+ return -1;
2769+ c = *p++;
2770+ *pp = p;
2771+ return c;
2772+}
2773+
2774+static inline int get16(const uint8_t **pp, const uint8_t *p_end)
2775+{
2776+ const uint8_t *p;
2777+ int c;
2778+
2779+ p = *pp;
2780+ if ((p + 1) >= p_end)
2781+ return -1;
2782+ c = AV_RB16(p);
2783+ p += 2;
2784+ *pp = p;
2785+ return c;
2786+}
2787+
2788+/* read and allocate a DVB string preceded by its length */
2789+static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
2790+{
2791+ int len;
2792+ const uint8_t *p;
2793+ char *str;
2794+
2795+ p = *pp;
2796+ len = get8(&p, p_end);
2797+ if (len < 0)
2798+ return NULL;
2799+ if ((p + len) > p_end)
2800+ return NULL;
2801+ str = av_malloc(len + 1);
2802+ if (!str)
2803+ return NULL;
2804+ memcpy(str, p, len);
2805+ str[len] = '\0';
2806+ p += len;
2807+ *pp = p;
2808+ return str;
2809+}
2810+
2811+static int parse_section_header(SectionHeader *h,
2812+ const uint8_t **pp, const uint8_t *p_end)
2813+{
2814+ int val;
2815+
2816+ val = get8(pp, p_end);
2817+ if (val < 0)
2818+ return -1;
2819+ h->tid = val;
2820+ *pp += 2;
2821+ val = get16(pp, p_end);
2822+ if (val < 0)
2823+ return -1;
2824+ h->id = val;
2825+ val = get8(pp, p_end);
2826+ if (val < 0)
2827+ return -1;
2828+ h->version = (val >> 1) & 0x1f;
2829+ val = get8(pp, p_end);
2830+ if (val < 0)
2831+ return -1;
2832+ h->sec_num = val;
2833+ val = get8(pp, p_end);
2834+ if (val < 0)
2835+ return -1;
2836+ h->last_sec_num = val;
2837+
2838+#ifdef DEBUG
2839+ av_log(NULL, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
2840+ h->id, h->sec_num, h->last_sec_num);
2841+#endif
2842+ return 0;
2843+}
2844+
2845+/* mpegts_push_section: return one or more tables. The tables may not completely fill
2846+ the packet and there may be stuffing bytes at the end.
2847+ This is complicated because a single TS packet may result in several tables being
2848+ produced. We may have a "start" bit indicating, in effect, the end of a table but
2849+ the rest of the TS packet after the start may be filled with one or more small tables.
2850+*/
2851+static void mpegts_push_section(MpegTSFilter *filter, const uint8_t *section, int section_len)
2852+{
2853+ SectionContext *sect = filter->u.section_filter.opaque;
2854+ MpegTSContext *ts = sect->ts;
2855+ SectionHeader header;
2856+ AVPacket *pkt = ts->pkt;
2857+ const uint8_t *p = section, *p_end = section + section_len - 4;
2858+
2859+ if (parse_section_header(&header, &p, p_end) < 0)
2860+ {
2861+ av_log(NULL, AV_LOG_DEBUG, "Unable to parse header\n");
2862+ return;
2863+ }
2864+
2865+ if (sect->new_packet && pkt && sect->st && pkt->size == 0) {
2866+ int pktLen = section_len + 184; /* Add enough for a complete TS payload. */
2867+ sect->new_packet = 0;
2868+ av_free_packet(pkt);
2869+ if (av_new_packet(pkt, pktLen) == 0) {
2870+ memcpy(pkt->data, section, section_len);
2871+ memset(pkt->data+section_len, 0xff, pktLen-section_len);
2872+ pkt->stream_index = sect->st->index;
2873+ ts->stop_parse = 1;
2874+ }
2875+ } else if (pkt->data) { /* We've already added at least one table. */
2876+ uint8_t *data = pkt->data;
2877+ int space = pkt->size;
2878+ int table_size = 0;
2879+ while (space > 3 + table_size) {
2880+ table_size = (((data[1] & 0xf) << 8) | data[2]) + 3;
2881+ if (table_size < space) {
2882+ space -= table_size;
2883+ data += table_size;
2884+ } /* Otherwise we've got filler. */
2885+ }
2886+ if (space < section_len) {
2887+ av_log(NULL, AV_LOG_DEBUG, "Insufficient space for additional packet\n");
2888+ return;
2889+ }
2890+ memcpy(data, section, section_len);
2891+ }
2892+}
2893+
2894+typedef struct {
2895+ uint32_t stream_type;
2896+ enum AVMediaType codec_type;
2897+ enum AVCodecID codec_id;
2898+} StreamType;
2899+
2900+static const StreamType ISO_types[] = {
2901+ { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
2902+ { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
2903+ { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
2904+ { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
2905+ { 0x0b, AVMEDIA_TYPE_DATA, AV_CODEC_ID_DSMCC_B }, /* DVB_CAROUSEL_ID */
2906+ { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC },
2907+ { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 },
2908+ { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */
2909+ { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 },
2910+ { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC },
2911+ { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
2912+ { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
2913+ { 0 },
2914+};
2915+
2916+static const StreamType HDMV_types[] = {
2917+ { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY },
2918+ { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
2919+ { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
2920+ { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD },
2921+ { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
2922+ { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */
2923+ { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/
2924+ { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */
2925+ { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */
2926+ { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE },
2927+ { 0 },
2928+};
2929+
2930+/* ATSC ? */
2931+static const StreamType MISC_types[] = {
2932+ { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
2933+ { 0x87, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 },
2934+ { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
2935+ { 0x100, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE },
2936+ { 0x101, AVMEDIA_TYPE_DATA, AV_CODEC_ID_DVB_VBI },
2937+ { 0 },
2938+};
2939+
2940+static const StreamType REGD_types[] = {
2941+ { MKTAG('d','r','a','c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC },
2942+ { MKTAG('A','C','-','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 },
2943+ { MKTAG('B','S','S','D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M },
2944+ { MKTAG('D','T','S','1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
2945+ { MKTAG('D','T','S','2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
2946+ { MKTAG('D','T','S','3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
2947+ { MKTAG('V','C','-','1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 },
2948+ { 0 },
2949+};
2950+
2951+/* descriptor present */
2952+static const StreamType DESC_types[] = {
2953+ { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */
2954+ { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */
2955+ { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS },
2956+ { 0x13, AVMEDIA_TYPE_DATA, AV_CODEC_ID_DSMCC_B }, /* DVB_CAROUSEL_ID */
2957+ { 0x45, AVMEDIA_TYPE_DATA, AV_CODEC_ID_DVB_VBI }, /* DVB_VBI_DATA_ID */
2958+ { 0x46, AVMEDIA_TYPE_DATA, AV_CODEC_ID_DVB_VBI }, /* DVB_VBI_TELETEXT_ID */ //FixMe type subtilte
2959+ { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT },
2960+ { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */
2961+ { 0 },
2962+};
2963+
2964+/* component tags */
2965+static const StreamType COMPONENT_TAG_types[] = {
2966+ { 0x0a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 },
2967+ { 0x52, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO },
2968+};
2969+
2970+static void mpegts_find_stream_type(AVStream *st,
2971+ uint32_t stream_type, const StreamType *types)
2972+{
2973+ for (; types->stream_type; types++) {
2974+ if (stream_type == types->stream_type) {
2975+ st->codecpar->codec_type = types->codec_type;
2976+ st->codecpar->codec_id = types->codec_id;
2977+ st->internal->request_probe = 0;
2978+ return;
2979+ }
2980+ }
2981+}
2982+
2983+static void mpegts_find_stream_type_pmt(pmt_entry_t *st,
2984+ uint32_t stream_type, const StreamType *types)
2985+{
2986+ for (; types->stream_type; types++) {
2987+ if (stream_type == types->stream_type) {
2988+ st->codec_type = types->codec_type;
2989+ st->codec_id = types->codec_id;
2990+ return;
2991+ }
2992+ }
2993+}
2994+
2995+static int mpegts_set_stream_info(AVStream *st, PESContext *pes,
2996+ uint32_t stream_type, uint32_t prog_reg_desc)
2997+{
2998+ int old_codec_type= st->codecpar->codec_type;
2999+ int old_codec_id = st->codecpar->codec_id;
3000+ avpriv_set_pts_info(st, 33, 1, 90000);
3001+ st->priv_data = pes;
3002+ st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
3003+ st->codecpar->codec_id = AV_CODEC_ID_NONE;
3004+ st->need_parsing = AVSTREAM_PARSE_FULL;
3005+ pes->st = st;
3006+ pes->stream_type = stream_type;
3007+
3008+ av_log(pes->stream, AV_LOG_DEBUG,
3009+ "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n",
3010+ st->index, pes->stream_type, pes->pid, (char*)&prog_reg_desc);
3011+
3012+ st->codecpar->codec_tag = pes->stream_type;
3013+
3014+ mpegts_find_stream_type(st, pes->stream_type, ISO_types);
3015+ if ((prog_reg_desc == AV_RL32("HDMV") ||
3016+ prog_reg_desc == AV_RL32("HDPR")) &&
3017+ st->codecpar->codec_id == AV_CODEC_ID_NONE) {
3018+ mpegts_find_stream_type(st, pes->stream_type, HDMV_types);
3019+ if (pes->stream_type == 0x83) {
3020+ // HDMV TrueHD streams also contain an AC3 coded version of the
3021+ // audio track - add a second stream for this
3022+ AVStream *sub_st;
3023+ // priv_data cannot be shared between streams
3024+ PESContext *sub_pes = av_malloc(sizeof(*sub_pes));
3025+ if (!sub_pes)
3026+ return AVERROR(ENOMEM);
3027+ memcpy(sub_pes, pes, sizeof(*sub_pes));
3028+
3029+ sub_st = avformat_new_stream(pes->stream, NULL);
3030+ if (!sub_st) {
3031+ av_free(sub_pes);
3032+ return AVERROR(ENOMEM);
3033+ }
3034+
3035+ sub_st->id = pes->pid;
3036+ avpriv_set_pts_info(sub_st, 33, 1, 90000);
3037+ sub_st->priv_data = sub_pes;
3038+ sub_st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
3039+ sub_st->codecpar->codec_id = AV_CODEC_ID_AC3;
3040+ sub_st->need_parsing = AVSTREAM_PARSE_FULL;
3041+ sub_pes->sub_st = pes->sub_st = sub_st;
3042+ }
3043+ }
3044+ if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
3045+ mpegts_find_stream_type(st, pes->stream_type, MISC_types);
3046+ if (st->codecpar->codec_id == AV_CODEC_ID_NONE){
3047+ st->codecpar->codec_id = old_codec_id;
3048+ st->codecpar->codec_type= old_codec_type;
3049+ }
3050+
3051+ return 0;
3052+}
3053+
3054+static void new_pes_packet(PESContext *pes, AVPacket *pkt)
3055+{
3056+ av_packet_from_data(pkt, pes->buffer, pes->data_index);
3057+
3058+ if(pes->total_size != MAX_PES_PAYLOAD &&
3059+ pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) {
3060+ av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n");
3061+ pes->flags |= AV_PKT_FLAG_CORRUPT;
3062+ }
3063+ memset(pkt->data+pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
3064+
3065+ // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID
3066+ if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76)
3067+ pkt->stream_index = pes->sub_st->index;
3068+ else
3069+ pkt->stream_index = pes->st->index;
3070+ pkt->pts = pes->pts;
3071+ pkt->dts = pes->dts;
3072+ /* store position of first TS packet of this PES packet */
3073+ pkt->pos = pes->ts_packet_pos;
3074+ pkt->flags = pes->flags;
3075+
3076+ /* reset pts values */
3077+ pes->pts = AV_NOPTS_VALUE;
3078+ pes->dts = AV_NOPTS_VALUE;
3079+ pes->buffer = NULL;
3080+ pes->data_index = 0;
3081+ pes->flags = 0;
3082+}
3083+
3084+static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size)
3085+{
3086+ GetBitContext gb;
3087+ int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0;
3088+ int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0;
3089+ int dts_flag = -1, cts_flag = -1;
3090+ int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE;
3091+
3092+ init_get_bits(&gb, buf, buf_size*8);
3093+
3094+ if (sl->use_au_start)
3095+ au_start_flag = get_bits1(&gb);
3096+ if (sl->use_au_end)
3097+ au_end_flag = get_bits1(&gb);
3098+ if (!sl->use_au_start && !sl->use_au_end)
3099+ au_start_flag = au_end_flag = 1;
3100+ if (sl->ocr_len > 0)
3101+ ocr_flag = get_bits1(&gb);
3102+ if (sl->use_idle)
3103+ idle_flag = get_bits1(&gb);
3104+ if (sl->use_padding)
3105+ padding_flag = get_bits1(&gb);
3106+ if (padding_flag)
3107+ padding_bits = get_bits(&gb, 3);
3108+
3109+ if (!idle_flag && (!padding_flag || padding_bits != 0)) {
3110+ if (sl->packet_seq_num_len)
3111+ skip_bits_long(&gb, sl->packet_seq_num_len);
3112+ if (sl->degr_prior_len)
3113+ if (get_bits1(&gb))
3114+ skip_bits(&gb, sl->degr_prior_len);
3115+ if (ocr_flag)
3116+ skip_bits_long(&gb, sl->ocr_len);
3117+ if (au_start_flag) {
3118+ if (sl->use_rand_acc_pt)
3119+ get_bits1(&gb);
3120+ if (sl->au_seq_num_len > 0)
3121+ skip_bits_long(&gb, sl->au_seq_num_len);
3122+ if (sl->use_timestamps) {
3123+ dts_flag = get_bits1(&gb);
3124+ cts_flag = get_bits1(&gb);
3125+ }
3126+ }
3127+ if (sl->inst_bitrate_len)
3128+ inst_bitrate_flag = get_bits1(&gb);
3129+ if (dts_flag == 1)
3130+ dts = get_bits64(&gb, sl->timestamp_len);
3131+ if (cts_flag == 1)
3132+ cts = get_bits64(&gb, sl->timestamp_len);
3133+ if (sl->au_len > 0)
3134+ skip_bits_long(&gb, sl->au_len);
3135+ if (inst_bitrate_flag)
3136+ skip_bits_long(&gb, sl->inst_bitrate_len);
3137+ }
3138+
3139+ if (dts != AV_NOPTS_VALUE)
3140+ pes->dts = dts;
3141+ if (cts != AV_NOPTS_VALUE)
3142+ pes->pts = cts;
3143+
3144+ if (sl->timestamp_len && sl->timestamp_res)
3145+ avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res);
3146+
3147+ return (get_bits_count(&gb) + 7) >> 3;
3148+}
3149+
3150+/* return non zero if a packet could be constructed */
3151+static int mpegts_push_data(MpegTSFilter *filter,
3152+ const uint8_t *buf, int buf_size, int is_start,
3153+ int64_t pos)
3154+{
3155+ PESContext *pes = filter->u.pes_filter.opaque;
3156+ MpegTSContext *ts = pes->ts;
3157+ const uint8_t *p;
3158+ int len, code;
3159+
3160+ if(!ts || !ts->pkt)
3161+ return 0;
3162+
3163+ if (is_start) {
3164+ if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
3165+ new_pes_packet(pes, ts->pkt);
3166+ ts->stop_parse = 1;
3167+ }
3168+ pes->state = MPEGTS_HEADER;
3169+ pes->data_index = 0;
3170+ pes->ts_packet_pos = pos;
3171+ }
3172+ p = buf;
3173+ while (buf_size > 0) {
3174+ switch(pes->state) {
3175+ case MPEGTS_HEADER:
3176+ len = PES_START_SIZE - pes->data_index;
3177+ if (len > buf_size)
3178+ len = buf_size;
3179+ memcpy(pes->header + pes->data_index, p, len);
3180+ pes->data_index += len;
3181+ p += len;
3182+ buf_size -= len;
3183+ if (pes->data_index == PES_START_SIZE) {
3184+ /* we got all the PES or section header. We can now
3185+ decide */
3186+ if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
3187+ pes->header[2] == 0x01) {
3188+ /* it must be an mpeg2 PES stream */
3189+ code = pes->header[3] | 0x100;
3190+ av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code);
3191+
3192+ if ((pes->st && pes->st->discard == AVDISCARD_ALL &&
3193+ (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) ||
3194+ code == 0x1be) /* padding_stream */
3195+ goto skip;
3196+
3197+ /* stream not present in PMT */
3198+ if (!pes->st) {
3199+ pes->st = avformat_new_stream(ts->stream, NULL);
3200+ if (!pes->st)
3201+ return AVERROR(ENOMEM);
3202+ pes->st->id = pes->pid;
3203+ mpegts_set_stream_info(pes->st, pes, 0, 0);
3204+ }
3205+
3206+ pes->total_size = AV_RB16(pes->header + 4);
3207+ /* NOTE: a zero total size means the PES size is
3208+ unbounded */
3209+ if (!pes->total_size)
3210+ pes->total_size = MAX_PES_PAYLOAD;
3211+
3212+ /* allocate pes buffer */
3213+ pes->buffer = av_malloc(pes->total_size+AV_INPUT_BUFFER_PADDING_SIZE);
3214+ if (!pes->buffer)
3215+ return AVERROR(ENOMEM);
3216+
3217+ if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */
3218+ code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */
3219+ code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */
3220+ code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */
3221+ pes->state = MPEGTS_PESHEADER;
3222+ if (pes->st->codecpar->codec_id == AV_CODEC_ID_NONE && !pes->st->internal->request_probe) {
3223+ av_dlog(pes->stream, "pid=%x stream_type=%x probing\n",
3224+ pes->pid, pes->stream_type);
3225+ pes->st->internal->request_probe= 1;
3226+ }
3227+ } else {
3228+ pes->state = MPEGTS_PAYLOAD;
3229+ pes->data_index = 0;
3230+ }
3231+ } else {
3232+ /* otherwise, it should be a table */
3233+ /* skip packet */
3234+ skip:
3235+ pes->state = MPEGTS_SKIP;
3236+ continue;
3237+ }
3238+ }
3239+ break;
3240+ /**********************************************/
3241+ /* PES packing parsing */
3242+ case MPEGTS_PESHEADER:
3243+ len = PES_HEADER_SIZE - pes->data_index;
3244+ if (len < 0)
3245+ return -1;
3246+ if (len > buf_size)
3247+ len = buf_size;
3248+ memcpy(pes->header + pes->data_index, p, len);
3249+ pes->data_index += len;
3250+ p += len;
3251+ buf_size -= len;
3252+ if (pes->data_index == PES_HEADER_SIZE) {
3253+ pes->pes_header_size = pes->header[8] + 9;
3254+ pes->state = MPEGTS_PESHEADER_FILL;
3255+ }
3256+ break;
3257+ case MPEGTS_PESHEADER_FILL:
3258+ len = pes->pes_header_size - pes->data_index;
3259+ if (len < 0)
3260+ return -1;
3261+ if (len > buf_size)
3262+ len = buf_size;
3263+ memcpy(pes->header + pes->data_index, p, len);
3264+ pes->data_index += len;
3265+ p += len;
3266+ buf_size -= len;
3267+ if (pes->data_index == pes->pes_header_size) {
3268+ const uint8_t *r;
3269+ unsigned int flags, pes_ext, skip;
3270+
3271+ flags = pes->header[7];
3272+ r = pes->header + 9;
3273+ pes->pts = AV_NOPTS_VALUE;
3274+ pes->dts = AV_NOPTS_VALUE;
3275+ if ((flags & 0xc0) == 0x80) {
3276+ pes->dts = pes->pts = ff_parse_pes_pts(r);
3277+ r += 5;
3278+ } else if ((flags & 0xc0) == 0xc0) {
3279+ pes->pts = ff_parse_pes_pts(r);
3280+ r += 5;
3281+ pes->dts = ff_parse_pes_pts(r);
3282+ r += 5;
3283+ }
3284+ pes->extended_stream_id = -1;
3285+ if (flags & 0x01) { /* PES extension */
3286+ pes_ext = *r++;
3287+ /* Skip PES private data, program packet sequence counter and P-STD buffer */
3288+ skip = (pes_ext >> 4) & 0xb;
3289+ skip += skip & 0x9;
3290+ r += skip;
3291+ if ((pes_ext & 0x41) == 0x01 &&
3292+ (r + 2) <= (pes->header + pes->pes_header_size)) {
3293+ /* PES extension 2 */
3294+ if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0)
3295+ pes->extended_stream_id = r[1];
3296+ }
3297+ }
3298+
3299+ /* we got the full header. We parse it and get the payload */
3300+ pes->state = MPEGTS_PAYLOAD;
3301+ pes->data_index = 0;
3302+ if (pes->stream_type == 0x12 && buf_size > 0) {
3303+ int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size);
3304+ pes->pes_header_size += sl_header_bytes;
3305+ p += sl_header_bytes;
3306+ buf_size -= sl_header_bytes;
3307+ }
3308+ }
3309+ break;
3310+ case MPEGTS_PAYLOAD:
3311+ if (buf_size > 0 && pes->buffer) {
3312+ if (pes->data_index > 0 && pes->data_index+buf_size > pes->total_size) {
3313+ new_pes_packet(pes, ts->pkt);
3314+ pes->total_size = MAX_PES_PAYLOAD;
3315+ pes->buffer = av_malloc(pes->total_size+AV_INPUT_BUFFER_PADDING_SIZE);
3316+ if (!pes->buffer)
3317+ return AVERROR(ENOMEM);
3318+ ts->stop_parse = 1;
3319+ } else if (pes->data_index == 0 && buf_size > pes->total_size) {
3320+ // pes packet size is < ts size packet and pes data is padded with 0xff
3321+ // not sure if this is legal in ts but see issue #2392
3322+ buf_size = pes->total_size;
3323+ }
3324+ memcpy(pes->buffer+pes->data_index, p, buf_size);
3325+ pes->data_index += buf_size;
3326+ }
3327+ buf_size = 0;
3328+ /* emit complete packets with known packet size
3329+ * decreases demuxer delay for infrequent packets like subtitles from
3330+ * a couple of seconds to milliseconds for properly muxed files.
3331+ * total_size is the number of bytes following pes_packet_length
3332+ * in the pes header, i.e. not counting the first PES_START_SIZE bytes */
3333+ if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD &&
3334+ pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) {
3335+ ts->stop_parse = 1;
3336+ new_pes_packet(pes, ts->pkt);
3337+ }
3338+ break;
3339+ case MPEGTS_SKIP:
3340+ buf_size = 0;
3341+ break;
3342+ }
3343+ }
3344+
3345+ return 0;
3346+}
3347+
3348+static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid)
3349+{
3350+ MpegTSFilter *tss = ts->pids[pid];
3351+ PESContext *pes = 0;
3352+ if (tss) { /* filter already exists */
3353+ if (tss->type == MPEGTS_PES)
3354+ pes = (PESContext*) tss->u.pes_filter.opaque;
3355+ /* otherwise, kill it, and start a new stream */
3356+ mpegts_close_filter(ts, tss);
3357+ }
3358+
3359+ /* create a PES context */
3360+ if (!(pes=av_mallocz(sizeof(PESContext)))) {
3361+ av_log(NULL, AV_LOG_ERROR, "Error: av_mallocz() failed in add_pes_stream");
3362+ return 0;
3363+ }
3364+ pes->ts = ts;
3365+ pes->stream = ts->stream;
3366+ pes->pid = pid;
3367+ pes->pcr_pid = pcr_pid;
3368+ pes->state = MPEGTS_SKIP;
3369+ pes->pts = AV_NOPTS_VALUE;
3370+ pes->dts = AV_NOPTS_VALUE;
3371+ tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
3372+ if (!tss) {
3373+ av_free(pes);
3374+ av_log(NULL, AV_LOG_ERROR, "Error: unable to open "
3375+ "mpegts PES filter in add_pes_stream");
3376+ return 0;
3377+ }
3378+ return pes;
3379+}
3380+
3381+#define MAX_LEVEL 4
3382+typedef struct {
3383+ AVFormatContext *s;
3384+ AVIOContext pb;
3385+ Mp4Descr *descr;
3386+ Mp4Descr *active_descr;
3387+ int descr_count;
3388+ int max_descr_count;
3389+ int level;
3390+} MP4DescrParseContext;
3391+
3392+static int init_MP4DescrParseContext(
3393+ MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf,
3394+ unsigned size, Mp4Descr *descr, int max_descr_count)
3395+{
3396+ int ret;
3397+ if (size > (1<<30))
3398+ return AVERROR_INVALIDDATA;
3399+
3400+ if ((ret = ffio_init_context(&d->pb, (unsigned char*)buf, size, 0,
3401+ NULL, NULL, NULL, NULL)) < 0)
3402+ return ret;
3403+
3404+ d->s = s;
3405+ d->level = 0;
3406+ d->descr_count = 0;
3407+ d->descr = descr;
3408+ d->active_descr = NULL;
3409+ d->max_descr_count = max_descr_count;
3410+
3411+ return 0;
3412+}
3413+
3414+static void update_offsets(AVIOContext *pb, int64_t *off, int *len) {
3415+ int64_t new_off = avio_tell(pb);
3416+ (*len) -= new_off - *off;
3417+ *off = new_off;
3418+}
3419+
3420+static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
3421+ int target_tag);
3422+
3423+static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len)
3424+{
3425+ while (len > 0) {
3426+ if (parse_mp4_descr(d, off, len, 0) < 0)
3427+ return -1;
3428+ update_offsets(&d->pb, &off, &len);
3429+ }
3430+ return 0;
3431+}
3432+
3433+static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len)
3434+{
3435+ avio_rb16(&d->pb); // ID
3436+ avio_r8(&d->pb);
3437+ avio_r8(&d->pb);
3438+ avio_r8(&d->pb);
3439+ avio_r8(&d->pb);
3440+ avio_r8(&d->pb);
3441+ update_offsets(&d->pb, &off, &len);
3442+ return parse_mp4_descr_arr(d, off, len);
3443+}
3444+
3445+static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len)
3446+{
3447+ int id_flags;
3448+ if (len < 2)
3449+ return 0;
3450+ id_flags = avio_rb16(&d->pb);
3451+ if (!(id_flags & 0x0020)) { //URL_Flag
3452+ update_offsets(&d->pb, &off, &len);
3453+ return parse_mp4_descr_arr(d, off, len); //ES_Descriptor[]
3454+ } else {
3455+ return 0;
3456+ }
3457+}
3458+
3459+static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len)
3460+{
3461+ int es_id = 0;
3462+ if (d->descr_count >= d->max_descr_count)
3463+ return -1;
3464+ ff_mp4_parse_es_descr(&d->pb, &es_id);
3465+ d->active_descr = d->descr + (d->descr_count++);
3466+
3467+ d->active_descr->es_id = es_id;
3468+ update_offsets(&d->pb, &off, &len);
3469+ parse_mp4_descr(d, off, len, MP4DecConfigDescrTag);
3470+ update_offsets(&d->pb, &off, &len);
3471+ if (len > 0)
3472+ parse_mp4_descr(d, off, len, MP4SLDescrTag);
3473+ d->active_descr = NULL;
3474+ return 0;
3475+}
3476+
3477+static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len)
3478+{
3479+ Mp4Descr *descr = d->active_descr;
3480+ if (!descr)
3481+ return -1;
3482+ d->active_descr->dec_config_descr = av_malloc(len);
3483+ if (!descr->dec_config_descr)
3484+ return AVERROR(ENOMEM);
3485+ descr->dec_config_descr_len = len;
3486+ avio_read(&d->pb, descr->dec_config_descr, len);
3487+ return 0;
3488+}
3489+
3490+static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len)
3491+{
3492+ Mp4Descr *descr = d->active_descr;
3493+ int predefined;
3494+ if (!descr)
3495+ return -1;
3496+
3497+ predefined = avio_r8(&d->pb);
3498+ if (!predefined) {
3499+ int lengths;
3500+ int flags = avio_r8(&d->pb);
3501+ descr->sl.use_au_start = !!(flags & 0x80);
3502+ descr->sl.use_au_end = !!(flags & 0x40);
3503+ descr->sl.use_rand_acc_pt = !!(flags & 0x20);
3504+ descr->sl.use_padding = !!(flags & 0x08);
3505+ descr->sl.use_timestamps = !!(flags & 0x04);
3506+ descr->sl.use_idle = !!(flags & 0x02);
3507+ descr->sl.timestamp_res = avio_rb32(&d->pb);
3508+ avio_rb32(&d->pb);
3509+ descr->sl.timestamp_len = avio_r8(&d->pb);
3510+ descr->sl.ocr_len = avio_r8(&d->pb);
3511+ descr->sl.au_len = avio_r8(&d->pb);
3512+ descr->sl.inst_bitrate_len = avio_r8(&d->pb);
3513+ lengths = avio_rb16(&d->pb);
3514+ descr->sl.degr_prior_len = lengths >> 12;
3515+ descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f;
3516+ descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f;
3517+ } else {
3518+ avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor");
3519+ }
3520+ return 0;
3521+}
3522+
3523+static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len,
3524+ int target_tag) {
3525+ int tag;
3526+ int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag);
3527+ update_offsets(&d->pb, &off, &len);
3528+ if (len < 0 || len1 > len || len1 <= 0) {
3529+ av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len);
3530+ return -1;
3531+ }
3532+
3533+ if (d->level++ >= MAX_LEVEL) {
3534+ av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n");
3535+ goto done;
3536+ }
3537+
3538+ if (target_tag && tag != target_tag) {
3539+ av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag);
3540+ goto done;
3541+ }
3542+
3543+ switch (tag) {
3544+ case MP4IODescrTag:
3545+ parse_MP4IODescrTag(d, off, len1);
3546+ break;
3547+ case MP4ODescrTag:
3548+ parse_MP4ODescrTag(d, off, len1);
3549+ break;
3550+ case MP4ESDescrTag:
3551+ parse_MP4ESDescrTag(d, off, len1);
3552+ break;
3553+ case MP4DecConfigDescrTag:
3554+ parse_MP4DecConfigDescrTag(d, off, len1);
3555+ break;
3556+ case MP4SLDescrTag:
3557+ parse_MP4SLDescrTag(d, off, len1);
3558+ break;
3559+ }
3560+
3561+done:
3562+ d->level--;
3563+ avio_seek(&d->pb, off + len1, SEEK_SET);
3564+ return 0;
3565+}
3566+
3567+static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size,
3568+ Mp4Descr *descr, int *descr_count, int max_descr_count)
3569+{
3570+ MP4DescrParseContext d;
3571+ if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
3572+ return -1;
3573+
3574+ parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag);
3575+
3576+ *descr_count = d.descr_count;
3577+ return 0;
3578+}
3579+
3580+static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size,
3581+ Mp4Descr *descr, int *descr_count, int max_descr_count)
3582+{
3583+ MP4DescrParseContext d;
3584+ if (init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count) < 0)
3585+ return -1;
3586+
3587+ parse_mp4_descr_arr(&d, avio_tell(&d.pb), size);
3588+
3589+ *descr_count = d.descr_count;
3590+ return 0;
3591+}
3592+
3593+static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
3594+{
3595+ MpegTSContext *ts = filter->u.section_filter.opaque;
3596+ SectionHeader h;
3597+ const uint8_t *p, *p_end;
3598+ AVIOContext pb;
3599+ Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
3600+ int mp4_descr_count = 0;
3601+ int i, pid;
3602+ AVFormatContext *s = ts->stream;
3603+
3604+ p_end = section + section_len - 4;
3605+ p = section;
3606+ if (parse_section_header(&h, &p, p_end) < 0)
3607+ return;
3608+ if (h.tid != M4OD_TID)
3609+ return;
3610+
3611+ mp4_read_od(s, p, (unsigned)(p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT);
3612+
3613+ for (pid = 0; pid < NB_PID_MAX; pid++) {
3614+ if (!ts->pids[pid])
3615+ continue;
3616+ for (i = 0; i < mp4_descr_count; i++) {
3617+ PESContext *pes;
3618+ AVStream *st;
3619+ if (ts->pids[pid]->es_id != mp4_descr[i].es_id)
3620+ continue;
3621+ if (!(ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES)) {
3622+ av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);
3623+ continue;
3624+ }
3625+ pes = ts->pids[pid]->u.pes_filter.opaque;
3626+ st = pes->st;
3627+ if (!st) {
3628+ continue;
3629+ }
3630+
3631+ pes->sl = mp4_descr[i].sl;
3632+
3633+ ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
3634+ mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
3635+ ff_mp4_read_dec_config_descr(s, st, &pb);
3636+ if (st->codecpar->codec_id == AV_CODEC_ID_AAC &&
3637+ st->codecpar->extradata_size > 0)
3638+ st->need_parsing = 0;
3639+ if (st->codecpar->codec_id == AV_CODEC_ID_H264 &&
3640+ st->codecpar->extradata_size > 0)
3641+ st->need_parsing = 0;
3642+
3643+ if (st->codecpar->codec_id <= AV_CODEC_ID_NONE) {
3644+ } else if (st->codecpar->codec_id < AV_CODEC_ID_FIRST_AUDIO) {
3645+ st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
3646+ } else if (st->codecpar->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) {
3647+ st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
3648+ } else if (st->codecpar->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) {
3649+ st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE;
3650+ }
3651+ }
3652+ }
3653+ for (i = 0; i < mp4_descr_count; i++)
3654+ av_free(mp4_descr[i].dec_config_descr);
3655+}
3656+
3657+int ff_parse_mpeg2_descriptor(AVFormatContext *fc, pmt_entry_t *item, int stream_type,
3658+ const uint8_t **pp, const uint8_t *desc_list_end,
3659+ Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
3660+ MpegTSContext *ts, dvb_caption_info_t *dvbci)
3661+{
3662+ const uint8_t *desc_end;
3663+ int desc_len, desc_tag, desc_es_id;
3664+ char *language;
3665+ int i;
3666+
3667+ desc_tag = get8(pp, desc_list_end);
3668+ if (desc_tag < 0)
3669+ return -1;
3670+ desc_len = get8(pp, desc_list_end);
3671+ if (desc_len < 0)
3672+ return -1;
3673+ desc_end = *pp + desc_len;
3674+ if (desc_end > desc_list_end)
3675+ return -1;
3676+
3677+ av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len);
3678+
3679+ if (item->codec_id == AV_CODEC_ID_NONE &&
3680+ stream_type == STREAM_TYPE_PRIVATE_DATA)
3681+ {
3682+ mpegts_find_stream_type_pmt(item, desc_tag, DESC_types);
3683+
3684+ if (item->codec_id != AV_CODEC_ID_NONE)
3685+ stream_type = 0;
3686+ }
3687+
3688+ language = dvbci->language;
3689+
3690+ switch(desc_tag) {
3691+ case 0x02: /* video stream descriptor */
3692+ if (get8(pp, desc_end) & 0x1) {
3693+ dvbci->disposition |= AV_DISPOSITION_STILL_IMAGE;
3694+ }
3695+ break;
3696+#if 0
3697+ case 0x1E: /* SL descriptor */
3698+ desc_es_id = get16(pp, desc_end);
3699+ if (ts && ts->pids[pid])
3700+ ts->pids[pid]->es_id = desc_es_id;
3701+ for (i = 0; i < mp4_descr_count; i++)
3702+ if (mp4_descr[i].dec_config_descr_len &&
3703+ mp4_descr[i].es_id == desc_es_id) {
3704+ AVIOContext pb;
3705+ ffio_init_context(&pb, mp4_descr[i].dec_config_descr,
3706+ mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
3707+ ff_mp4_read_dec_config_descr(fc, st, &pb);
3708+ if (item->codec_id == AV_CODEC_ID_AAC &&
3709+ st->codecpar->extradata_size > 0)
3710+ st->need_parsing = 0;
3711+ if (item->codec_id == AV_CODEC_ID_MPEG4SYSTEMS)
3712+ mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1);
3713+ }
3714+ break;
3715+ case 0x1F: /* FMC descriptor */
3716+ get16(pp, desc_end);
3717+ if (mp4_descr_count > 0 && (item->codec_id == AV_CODEC_ID_AAC_LATM || st->internal->request_probe>0) &&
3718+ mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) {
3719+ AVIOContext pb;
3720+ ffio_init_context(&pb, mp4_descr->dec_config_descr,
3721+ mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL);
3722+ ff_mp4_read_dec_config_descr(fc, st, &pb);
3723+ if (item->codec_id == AV_CODEC_ID_AAC &&
3724+ st->codecpar->extradata_size > 0){
3725+ st->internal->request_probe= st->need_parsing = 0;
3726+ st->codecpar->codec_type= AVMEDIA_TYPE_AUDIO;
3727+ }
3728+ }
3729+ break;
3730+#endif
3731+ case 0x56: /* DVB teletext descriptor */
3732+ language[0] = get8(pp, desc_end);
3733+ language[1] = get8(pp, desc_end);
3734+ language[2] = get8(pp, desc_end);
3735+ language[3] = 0;
3736+ break;
3737+ case 0x59: /* subtitling descriptor */
3738+ language[0] = get8(pp, desc_end);
3739+ language[1] = get8(pp, desc_end);
3740+ language[2] = get8(pp, desc_end);
3741+ language[3] = 0;
3742+ get8(pp, desc_end);
3743+
3744+#if 0
3745+ /* hearing impaired subtitles detection */
3746+ switch(get8(pp, desc_end)) {
3747+ case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */
3748+ case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */
3749+ case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */
3750+ case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */
3751+ case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */
3752+ case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */
3753+ st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
3754+ break;
3755+ }
3756+#endif
3757+
3758+ dvbci->comp_page = get16(pp, desc_end);
3759+ dvbci->anc_page = get16(pp, desc_end);
3760+ dvbci->sub_id = (dvbci->anc_page << 16) | dvbci->comp_page;
3761+
3762+#if 0
3763+ if (st->codecpar->extradata) {
3764+ if (st->codecpar->extradata_size == 4 && memcmp(st->codecpar->extradata, *pp, 4))
3765+ av_log_ask_for_sample(fc, "DVB sub with multiple IDs\n");
3766+ } else {
3767+ st->codecpar->extradata = av_malloc(4 + AV_INPUT_BUFFER_PADDING_SIZE);
3768+ if (st->codecpar->extradata) {
3769+ st->codecpar->extradata_size = 4;
3770+ memcpy(st->codecpar->extradata, *pp, 4);
3771+ }
3772+ }
3773+#endif
3774+ *pp += 4;
3775+ break;
3776+ case 0x0a: /* ISO 639 language descriptor */
3777+ for (i = 0; i + 4 <= desc_len; i += 4) {
3778+ language[i + 0] = get8(pp, desc_end);
3779+ language[i + 1] = get8(pp, desc_end);
3780+ language[i + 2] = get8(pp, desc_end);
3781+ language[i + 3] = ',';
3782+#if 0
3783+ switch (get8(pp, desc_end)) {
3784+ case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break;
3785+ case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break;
3786+ case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break;
3787+ }
3788+ }
3789+#else
3790+ }
3791+ get8(pp, desc_end);
3792+#endif
3793+ if (i) {
3794+ language[i - 1] = 0;
3795+ }
3796+ break;
3797+ case 0x05: /* registration descriptor */
3798+ dvbci->codec_tag = bytestream_get_le32(pp);
3799+ av_dlog(fc, "reg_desc=%.4s\n", (char*)&dvbci->codec_tag);
3800+ if (item->codec_id == AV_CODEC_ID_NONE &&
3801+ stream_type == STREAM_TYPE_PRIVATE_DATA)
3802+ mpegts_find_stream_type_pmt(item, dvbci->codec_tag, REGD_types);
3803+ break;
3804+#if 0
3805+ case 0x52: /* stream identifier descriptor */
3806+ st->stream_identifier = 1 + get8(pp, desc_end);
3807+ break;
3808+#endif
3809+ case DVB_BROADCAST_ID:
3810+ dvbci->data_id = get16(pp, desc_end);
3811+ break;
3812+ case DVB_CAROUSEL_ID:
3813+ {
3814+ int carId = 0;
3815+ carId = get8(pp, desc_end);
3816+ carId = (carId << 8) | get8(pp, desc_end);
3817+ carId = (carId << 8) | get8(pp, desc_end);
3818+ carId = (carId << 8) | get8(pp, desc_end);
3819+ dvbci->carousel_id = carId;
3820+ }
3821+ break;
3822+ case DVB_DATA_STREAM:
3823+ dvbci->component_tag = get8(pp, desc_end);
3824+ /* Audio and video are sometimes encoded in private streams labelled with
3825+ * a component tag. */
3826+#if 0
3827+ if (item->codec_id == AV_CODEC_ID_NONE &&
3828+ desc_count == 1 &&
3829+ stream_type == STREAM_TYPE_PRIVATE_DATA)
3830+ mpegts_find_stream_type_pmt(item, dvbci->component_tag,
3831+ COMPONENT_TAG_types);
3832+#endif
3833+ break;
3834+ case DVB_VBI_TELETEXT_ID:
3835+ language[0] = get8(pp, desc_end);
3836+ language[1] = get8(pp, desc_end);
3837+ language[2] = get8(pp, desc_end);
3838+ dvbci->txt_type = (get8(pp, desc_end)) >> 3;
3839+ break;
3840+ case DVB_VBI_DATA_ID:
3841+ dvbci->vbi_data = 1; //not parsing the data service descriptors
3842+ break;
3843+ default:
3844+ break;
3845+ }
3846+ *pp = desc_end;
3847+ return 0;
3848+}
3849+
3850+static int find_in_list(const int *pids, int pid)
3851+{
3852+ int i;
3853+ for (i=0; i<PMT_PIDS_MAX; i++)
3854+ if (pids[i]==pid)
3855+ return i;
3856+ return -1;
3857+}
3858+
3859+static int is_desired_stream(pmt_entry_t *item)
3860+{
3861+ int val = 0;
3862+ switch (item->codec_type)
3863+ {
3864+ case AVMEDIA_TYPE_VIDEO:
3865+ case AVMEDIA_TYPE_AUDIO:
3866+ case AVMEDIA_TYPE_SUBTITLE:
3867+ val = 1;
3868+ break;
3869+ case AVMEDIA_TYPE_DATA:
3870+ switch (item->codec_id)
3871+ {
3872+ case AV_CODEC_ID_DSMCC_B:
3873+ case AV_CODEC_ID_DVB_VBI:
3874+ val = 1;
3875+ break;
3876+ default:
3877+ break;
3878+ }
3879+ break;
3880+ default:
3881+ /* we ignore the other streams */
3882+ break;
3883+ }
3884+ return val;
3885+}
3886+
3887+#define HANDLE_PMT_ERROR(MSG) \
3888+ do { av_log(NULL, AV_LOG_ERROR, MSG); return; } while (0)
3889+
3890+#define HANDLE_PMT_PARSE_ERROR(PMSG) \
3891+ HANDLE_PMT_ERROR("Something went terribly wrong in PMT parsing" \
3892+ " when looking at " PMSG "\n")
3893+
3894+static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
3895+{
3896+ MpegTSContext *ts = filter->u.section_filter.opaque;
3897+ SectionHeader h1, *h = &h1;
3898+
3899+ int last_item = 0;
3900+ int desc_count = 0;
3901+ int streams_changed = 0;
3902+ PESContext *pes;
3903+ const uint8_t *p, *p_end, *desc_list_end;
3904+ int program_info_length, pcr_pid, pid, stream_type;
3905+ int desc_list_len;
3906+ char *language;
3907+ uint32_t prog_reg_desc = 0; /* registration descriptor */
3908+
3909+ Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = {{ 0 }};
3910+ int mp4_descr_count = 0;
3911+ int i;
3912+
3913+ pmt_entry_t items[PMT_PIDS_MAX];
3914+ memset(&items, 0, sizeof(pmt_entry_t) * PMT_PIDS_MAX);
3915+
3916+ // initialize to codec_type_unknown
3917+ for (int i=0; i < PMT_PIDS_MAX; i++)
3918+ items[i].codec_type = AVMEDIA_TYPE_UNKNOWN;
3919+
3920+ mpegts_cleanup_streams(ts); /* in case someone else removed streams.. */
3921+
3922+ av_dlog(ts->stream, "PMT: len %i\n", section_len);
3923+ hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
3924+
3925+ p_end = section + section_len - 4;
3926+ p = section;
3927+ if (parse_section_header(h, &p, p_end) < 0)
3928+ HANDLE_PMT_PARSE_ERROR("section header");
3929+
3930+ av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d\n",
3931+ h->id, h->sec_num, h->last_sec_num);
3932+
3933+ /* Check if this is really a PMT, and if so the right one */
3934+ if (h->tid != PMT_TID)
3935+ HANDLE_PMT_ERROR("pmt_cb() got a TS packet that doesn't have PMT TID\n");
3936+
3937+ /* if we require a specific PMT, and this isn't it return silently */
3938+ if (ts->req_sid >= 0 && h->id != ts->req_sid)
3939+ {
3940+#ifdef DEBUG
3941+ av_dlog(ts->stream, "We are looking for program 0x%x, not 0x%x",
3942+ ts->req_sid, h->id);
3943+#endif
3944+ return;
3945+ }
3946+
3947+ clear_program(ts, h->id);
3948+ pcr_pid = get16(&p, p_end);
3949+ if (pcr_pid < 0)
3950+ return;
3951+ pcr_pid &= 0x1fff;
3952+ add_pid_to_pmt(ts, h->id, pcr_pid);
3953+ set_pcr_pid(ts->stream, h->id, pcr_pid);
3954+
3955+ av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid);
3956+
3957+ program_info_length = get16(&p, p_end);
3958+ if (program_info_length < 0)
3959+ return;
3960+ program_info_length &= 0xfff;
3961+ while(program_info_length >= 2) {
3962+ uint8_t tag, len;
3963+ tag = get8(&p, p_end);
3964+ len = get8(&p, p_end);
3965+
3966+ av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len);
3967+
3968+ if(len > program_info_length - 2)
3969+ //something else is broken, exit the program_descriptors_loop
3970+ break;
3971+ program_info_length -= len + 2;
3972+ if (tag == 0x1d) { // IOD descriptor
3973+ get8(&p, p_end); // scope
3974+ get8(&p, p_end); // label
3975+ len -= 2;
3976+ mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count,
3977+ &mp4_descr_count, MAX_MP4_DESCR_COUNT);
3978+ } else if (tag == 0x05 && len >= 4) { // registration descriptor
3979+ prog_reg_desc = bytestream_get_le32(&p);
3980+ len -= 4;
3981+ }
3982+ p += len;
3983+ }
3984+ p += program_info_length;
3985+ if (p >= p_end)
3986+ return;
3987+
3988+ // stop parsing after pmt, we found header
3989+ if (!ts->stream->nb_streams)
3990+ ts->stop_parse = 2;
3991+
3992+ for(;;) {
3993+ dvb_caption_info_t dvbci;
3994+ stream_type = get8(&p, p_end);
3995+ if (stream_type < 0)
3996+ break;
3997+ pid = get16(&p, p_end);
3998+ if (pid < 0)
3999+ break;
4000+ pid &= 0x1fff;
4001+
4002+ /* break if we are out of space. */
4003+ if (last_item >= PMT_PIDS_MAX) {
4004+ av_log(NULL, AV_LOG_DEBUG,
4005+ "Could not add new pid 0x%x, i = %i, "
4006+ "would cause overrun\n", pid, last_item);
4007+ assert(0);
4008+ break;
4009+ }
4010+
4011+ items[last_item].pid = pid;
4012+
4013+ mpegts_find_stream_type_pmt(&items[last_item], stream_type, ISO_types);
4014+ if (items[last_item].codec_id == AV_CODEC_ID_NONE) {
4015+ if (prog_reg_desc == AV_RL32("HDMV"))
4016+ mpegts_find_stream_type_pmt(&items[last_item], stream_type, HDMV_types);
4017+ else
4018+ mpegts_find_stream_type_pmt(&items[last_item], stream_type, MISC_types);
4019+ }
4020+
4021+ memset(&dvbci, 0, sizeof(dvb_caption_info_t));
4022+
4023+ desc_list_len = get16(&p, p_end);
4024+ if (desc_list_len < 0)
4025+ break;
4026+ desc_list_len &= 0xfff;
4027+ desc_list_end = p + desc_list_len;
4028+ if (desc_list_end > p_end)
4029+ break;
4030+ for(;;) {
4031+ if (ff_parse_mpeg2_descriptor(ts->stream, &items[last_item], stream_type, &p, desc_list_end,
4032+ mp4_descr, mp4_descr_count, pid, ts, &dvbci) < 0)
4033+ break;
4034+ }
4035+ p = desc_list_end;
4036+
4037+ if (is_desired_stream(&items[last_item])) {
4038+ items[last_item].type = stream_type;
4039+ memcpy(&items[last_item].dvbci, &dvbci,
4040+ sizeof(dvb_caption_info_t));
4041+ last_item++;
4042+ }
4043+
4044+ desc_count++;
4045+ }
4046+
4047+ /* if the pmt has changed delete old streams,
4048+ * create new ones, and notify any listener.
4049+ */
4050+ int equal_streams = pmt_equal_streams(ts, items, last_item);
4051+ if (equal_streams != last_item || ts->pid_cnt != last_item)
4052+ {
4053+ AVFormatContext *avctx = ts->stream;
4054+ int idx;
4055+ /* flush out old AVPackets */
4056+ ff_read_frame_flush(avctx);
4057+
4058+ /* delete old streams */
4059+ for (idx = ts->pid_cnt-1; idx >= equal_streams; idx--)
4060+ av_remove_stream(ts->stream, ts->pmt_pids[idx], 1);
4061+
4062+ /* create new streams */
4063+ for (idx = equal_streams; idx < last_item; idx++)
4064+ mpegts_add_stream(ts, h->id, &items[idx], prog_reg_desc, pcr_pid);
4065+
4066+ /* cache pmt */
4067+ void *tmp0 = avctx->cur_pmt_sect;
4068+ void *tmp1 = av_malloc(section_len);
4069+ memcpy(tmp1, section, section_len);
4070+ avctx->cur_pmt_sect = (uint8_t*) tmp1;
4071+ avctx->cur_pmt_sect_len = section_len;
4072+ if (tmp0)
4073+ av_free(tmp0);
4074+
4075+ /* notify stream_changed listeners */
4076+ if (avctx->streams_changed)
4077+ {
4078+ av_log(NULL, AV_LOG_DEBUG, "streams_changed()\n");
4079+ avctx->streams_changed(avctx->stream_change_data);
4080+ }
4081+ }
4082+
4083+ /* if we are scanning, tell scanner we found the PMT */
4084+ if (ts->scanning)
4085+ {
4086+ ts->pmt_scan_state = PMT_FOUND;
4087+ ts->stop_parse = 1;
4088+ }
4089+}
4090+
4091+static int is_pat_same(MpegTSContext *mpegts_ctx,
4092+ int *pmt_pnums, int *pmt_pids, unsigned int pmt_count)
4093+{
4094+ int idx;
4095+ if (mpegts_ctx->nb_prg != pmt_count)
4096+ return 0;
4097+
4098+ for (idx = 0; idx < pmt_count; idx++)
4099+ {
4100+ if ((mpegts_ctx->prg[idx].id != pmt_pnums[idx]) ||
4101+ (mpegts_ctx->prg[idx].pid != pmt_pids[idx]))
4102+ return 0;
4103+ }
4104+ return 1;
4105+}
4106+
4107+// Find number of equal streams in old and new pmt starting at 0
4108+// and stopping at the first different stream.
4109+static int pmt_equal_streams(MpegTSContext *mpegts_ctx,
4110+ pmt_entry_t* items, int item_cnt)
4111+{
4112+ int limit = mpegts_ctx->pid_cnt < item_cnt ? mpegts_ctx->pid_cnt : item_cnt;
4113+ int idx;
4114+
4115+ for (idx = 0; idx < limit; idx++)
4116+ {
4117+ /* check for pid */
4118+ int loc = find_in_list(mpegts_ctx->pmt_pids, items[idx].pid);
4119+ if (loc < 0)
4120+ {
4121+#ifdef DEBUG
4122+ av_log(NULL, AV_LOG_DEBUG,
4123+ "find_in_list(..,[%d].pid=%d) => -1\n",
4124+ idx, items[idx].pid);
4125+#endif
4126+ break;
4127+ }
4128+
4129+ /* check stream type */
4130+ MpegTSFilter *tss = mpegts_ctx->pids[items[idx].pid];
4131+ if (!tss)
4132+ {
4133+#ifdef DEBUG
4134+ av_log(NULL, AV_LOG_DEBUG,
4135+ "mpegts_ctx->pids[items[%d].pid=%d] => null\n",
4136+ idx, items[idx].pid);
4137+#endif
4138+ break;
4139+ }
4140+ if (tss->type == MPEGTS_PES)
4141+ {
4142+ PESContext *pes = (PESContext*) tss->u.pes_filter.opaque;
4143+ if (!pes)
4144+ {
4145+#ifdef DEBUG
4146+ av_log(NULL, AV_LOG_DEBUG, "pes == null, where idx %d\n", idx);
4147+#endif
4148+ break;
4149+ }
4150+ if (pes->stream_type != items[idx].type)
4151+ {
4152+#ifdef DEBUG
4153+ av_log(NULL, AV_LOG_DEBUG,
4154+ "pes->stream_type != items[%d].type\n", idx);
4155+#endif
4156+ break;
4157+ }
4158+ }
4159+ else if (tss->type == MPEGTS_SECTION)
4160+ {
4161+ SectionContext *sect = (SectionContext*) tss->u.section_filter.opaque;
4162+ if (!sect)
4163+ {
4164+#ifdef DEBUG
4165+ av_log(NULL, AV_LOG_DEBUG, "sect == null, where idx %d\n", idx);
4166+#endif
4167+ break;
4168+ }
4169+ if (sect->stream_type != items[idx].type)
4170+ {
4171+#ifdef DEBUG
4172+ av_log(NULL, AV_LOG_DEBUG,
4173+ "sect->stream_type != items[%d].type\n", idx);
4174+#endif
4175+ break;
4176+ }
4177+ }
4178+ else
4179+ {
4180+#ifdef DEBUG
4181+ av_log(NULL, AV_LOG_DEBUG,
4182+ "tss->type != MPEGTS_PES, where idx %d\n", idx);
4183+#endif
4184+ break;
4185+ }
4186+ }
4187+#ifdef DEBUG
4188+ av_log(NULL, AV_LOG_DEBUG, "pmt_equal_streams:%d old:%d new:%d limit:%d\n",
4189+ idx, mpegts_ctx->pid_cnt, item_cnt, limit);
4190+#endif
4191+ return idx;
4192+}
4193+
4194+static void mpegts_cleanup_streams(MpegTSContext *ts)
4195+{
4196+ int i;
4197+ int orig_pid_cnt = ts->pid_cnt;
4198+ for (i=0; i<ts->pid_cnt; i++)
4199+ {
4200+ if (!ts->pids[ts->pmt_pids[i]])
4201+ {
4202+ mpegts_remove_stream(ts, ts->pmt_pids[i]);
4203+ i--;
4204+ }
4205+ }
4206+ if (orig_pid_cnt != ts->pid_cnt)
4207+ {
4208+ av_log(NULL, AV_LOG_DEBUG,
4209+ "mpegts_cleanup_streams: pid_cnt bfr %d aft %d\n",
4210+ orig_pid_cnt, ts->pid_cnt);
4211+ }
4212+}
4213+
4214+// This was previously in libavutil/internal.h
4215+// Copied here because it is no longer used in the rest of ffmpeg
4216+#define FF_ALLOCZ_OR_GOTO(ctx, p, size, label)\
4217+{\
4218+ p = av_mallocz(size);\
4219+ if (!(p) && (size) != 0) {\
4220+ av_log(ctx, AV_LOG_ERROR, "Cannot allocate memory.\n");\
4221+ goto label;\
4222+ }\
4223+}
4224+
4225+static AVStream *new_section_av_stream(SectionContext *sect, enum AVMediaType type,
4226+ enum AVCodecID id)
4227+{
4228+ FF_ALLOCZ_OR_GOTO(NULL, sect->st, sizeof(AVStream), fail);
4229+
4230+ sect->st = av_new_stream(sect->stream, sect->pid);
4231+
4232+ av_set_pts_info(sect->st, 33, 1, 90000);
4233+
4234+ sect->st->codecpar->codec_type = type;
4235+ sect->st->codecpar->codec_id = id;
4236+ sect->st->priv_data = sect;
4237+ sect->st->need_parsing = AVSTREAM_PARSE_NONE;
4238+
4239+ return sect->st;
4240+fail: /*for the CHECKED_ALLOCZ macro*/
4241+ return NULL;
4242+}
4243+
4244+static void mpegts_add_stream(MpegTSContext *ts, int id, pmt_entry_t* item,
4245+ uint32_t prog_reg_desc, int pcr_pid)
4246+{
4247+ AVStream *st = NULL;
4248+ int pid = item->pid;
4249+
4250+ av_log(NULL, AV_LOG_DEBUG,
4251+ "mpegts_add_stream: at pid 0x%x with type %i\n", item->pid, item->type);
4252+
4253+ if (ts->pid_cnt < PMT_PIDS_MAX)
4254+ {
4255+ if (item->type == STREAM_TYPE_DSMCC_B)
4256+ {
4257+ SectionContext *sect = NULL;
4258+ sect = add_section_stream(ts, item->pid, item->type);
4259+ if (!sect)
4260+ {
4261+ av_log(NULL, AV_LOG_ERROR, "mpegts_add_stream: "
4262+ "error creating Section context for pid 0x%x with type %i\n",
4263+ item->pid, item->type);
4264+ return;
4265+ }
4266+
4267+ st = new_section_av_stream(sect, item->codec_type, item->codec_id);
4268+ if (!st)
4269+ {
4270+ av_log(NULL, AV_LOG_ERROR, "mpegts_add_stream: "
4271+ "error creating A/V stream for pid 0x%x with type %i\n",
4272+ item->pid, item->type);
4273+ return;
4274+ }
4275+
4276+ st->component_tag = item->dvbci.component_tag;
4277+ st->data_id = item->dvbci.data_id;
4278+ st->carousel_id = item->dvbci.carousel_id;
4279+
4280+ ts->pmt_pids[ts->pid_cnt] = item->pid;
4281+ ts->pid_cnt++;
4282+
4283+ av_log(NULL, AV_LOG_DEBUG, "mpegts_add_stream: "
4284+ "stream #%d, has id 0x%x and codec %s, type %s at 0x%x\n",
4285+ st->index, st->id, ff_codec_id_string(st->codecpar->codec_id),
4286+ ff_codec_type_string(st->codecpar->codec_type), st);
4287+ } else {
4288+ PESContext *pes = NULL;
4289+
4290+ if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) {
4291+ pes = ts->pids[pid]->u.pes_filter.opaque;
4292+ st = pes->st;
4293+ } else {
4294+ if (ts->pids[pid]) {
4295+ //wrongly added sdt filter probably
4296+ mpegts_close_filter(ts, ts->pids[pid]);
4297+ }
4298+ pes = add_pes_stream(ts, pid, pcr_pid);
4299+ if (pes)
4300+ st = av_new_stream(pes->stream, pes->pid);
4301+ else
4302+ {
4303+ av_log(NULL, AV_LOG_ERROR, "mpegts_add_stream: "
4304+ "error creating PES context for pid 0x%x with type %i\n",
4305+ item->pid, item->type);
4306+ return;
4307+ }
4308+ }
4309+
4310+ if (!st)
4311+ {
4312+ av_log(NULL, AV_LOG_ERROR, "mpegts_add_stream: "
4313+ "error creating A/V stream for pid 0x%x with type %i\n",
4314+ item->pid, item->type);
4315+ return;
4316+ }
4317+
4318+ if (!pes->stream_type)
4319+ mpegts_set_stream_info(st, pes, item->type, prog_reg_desc);
4320+
4321+ st->codecpar->codec_tag = item->dvbci.codec_tag;
4322+
4323+ if (prog_reg_desc == AV_RL32("HDMV") && item->type == 0x83 && pes->sub_st) {
4324+ av_program_add_stream_index(ts->stream, id, pes->sub_st->index);
4325+ pes->sub_st->codecpar->codec_tag = st->codecpar->codec_tag;
4326+ }
4327+
4328+ if (st->codecpar->codec_type != item->codec_type ||
4329+ st->codecpar->codec_id != item->codec_id) {
4330+ st->codecpar->codec_type = item->codec_type;
4331+ st->codecpar->codec_id = item->codec_id;
4332+ }
4333+
4334+ ts->pmt_pids[ts->pid_cnt] = item->pid;
4335+ ts->pid_cnt++;
4336+
4337+ if (item->dvbci.language[0])
4338+ av_dict_set(&st->metadata, "language", item->dvbci.language, 0);
4339+
4340+ if (item->dvbci.sub_id && (item->codec_id == AV_CODEC_ID_DVB_SUBTITLE))
4341+ st->carousel_id = item->dvbci.sub_id;
4342+
4343+ st->component_tag = item->dvbci.component_tag;
4344+ st->disposition = item->dvbci.disposition;
4345+
4346+ av_log(NULL, AV_LOG_DEBUG, "mpegts_add_stream: "
4347+ "stream #%d, has id 0x%x and codec %s, type %s at 0x%x\n",
4348+ st->index, st->id, ff_codec_id_string(st->codecpar->codec_id),
4349+ ff_codec_type_string(st->codecpar->codec_type), st);
4350+ }
4351+ add_pid_to_pmt(ts, id, pid);
4352+ av_program_add_stream_index(ts->stream, id, st->index);
4353+ }
4354+ else
4355+ {
4356+ av_log(NULL, AV_LOG_ERROR,
4357+ "ERROR: adding pes stream at pid 0x%x, pid_cnt = %i\n",
4358+ item->pid, ts->pid_cnt);
4359+ }
4360+}
4361+
4362+void mpegts_remove_stream(MpegTSContext *ts, int pid)
4363+{
4364+ av_log(NULL, AV_LOG_DEBUG, "mpegts_remove_stream 0x%x\n", pid);
4365+ if (ts->pids[pid])
4366+ {
4367+ av_log(NULL, AV_LOG_DEBUG, "closing filter for pid 0x%x\n", pid);
4368+ mpegts_close_filter(ts, ts->pids[pid]);
4369+ }
4370+ int indx = find_in_list(ts->pmt_pids, pid);
4371+ if (indx >= 0)
4372+ {
4373+ memmove(ts->pmt_pids+indx, ts->pmt_pids+indx+1, PMT_PIDS_MAX-indx-1);
4374+ ts->pmt_pids[PMT_PIDS_MAX-1] = 0;
4375+ ts->pid_cnt--;
4376+ }
4377+ else
4378+ {
4379+ av_log(NULL, AV_LOG_DEBUG, "ERROR: closing filter for pid 0x%x, indx = %i\n", pid, indx);
4380+ }
4381+}
4382+
4383+static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
4384+{
4385+ MpegTSContext *ts = filter->u.section_filter.opaque;
4386+ SectionHeader h1, *h = &h1;
4387+ const uint8_t *p, *p_end;
4388+ int sid, pmt_pid;
4389+ AVProgram *program;
4390+ char buf[256];
4391+
4392+ int pmt_pnums[PAT_MAX_PMT];
4393+ int pmt_pids[PAT_MAX_PMT];
4394+ unsigned int pmt_count = 0;
4395+ int i;
4396+
4397+ av_dlog(ts->stream, "PAT:\n");
4398+ hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
4399+
4400+ p_end = section + section_len - 4;
4401+ p = section;
4402+ if (parse_section_header(h, &p, p_end) < 0)
4403+ return;
4404+ if (h->tid != PAT_TID)
4405+ return;
4406+
4407+ for (i = 0; i < PAT_MAX_PMT; ++i)
4408+ {
4409+ pmt_pnums[i] = get16(&p, p_end);
4410+ if (pmt_pnums[i] < 0)
4411+ break;
4412+
4413+ pmt_pids[i] = get16(&p, p_end) & 0x1fff;
4414+ if (pmt_pids[i] < 0)
4415+ break;
4416+
4417+ if (pmt_pids[i] == 0x0)
4418+ {
4419+ av_log(NULL, AV_LOG_ERROR, "Invalid PAT ignored "
4420+ "MPEG Program Number=0x%x pid=0x%x req_sid=0x%x\n",
4421+ pmt_pnums[i], pmt_pids[i], ts->req_sid);
4422+ return;
4423+ }
4424+
4425+ pmt_count++;
4426+
4427+#ifdef DEBUG
4428+ av_log(ts->stream, AV_LOG_DEBUG,
4429+ "MPEG Program Number=0x%x pid=0x%x req_sid=0x%x\n",
4430+ pmt_pnums[i], pmt_pids[i], ts->req_sid);
4431+#endif
4432+ }
4433+
4434+ if (!is_pat_same(ts, pmt_pnums, pmt_pids, pmt_count))
4435+ {
4436+#ifdef DEBUG
4437+ av_log(NULL, AV_LOG_DEBUG, "New PAT!\n");
4438+#endif
4439+ /* if there were services, get rid of them */
4440+ ts->nb_prg = 0;
4441+
4442+ /* if there are new services, add them */
4443+ for (i = 0; i < pmt_count; ++i)
4444+ {
4445+ snprintf(buf, sizeof(buf), "MPEG Program %x", pmt_pnums[i]);
4446+ add_pat_entry(ts, pmt_pnums[i], pmt_pids[i]);
4447+ }
4448+ }
4449+
4450+ int found = 0;
4451+ for (i = 0; i < pmt_count; ++i)
4452+ {
4453+ /* if an MPEG program number is requested, and this is that program,
4454+ * add a filter for the PMT. */
4455+ if (ts->req_sid == pmt_pnums[i])
4456+ {
4457+#ifdef DEBUG
4458+ av_log(NULL, AV_LOG_DEBUG, "Found program number!\n");
4459+#endif
4460+ /* close old filter if it doesn't match */
4461+ if (ts->pmt_filter)
4462+ {
4463+ MpegTSFilter *f = ts->pmt_filter;
4464+ MpegTSSectionFilter *sec = &f->u.section_filter;
4465+
4466+ if ((f->pid != pmt_pids[i]) ||
4467+ (f->type != MPEGTS_SECTION) ||
4468+ (sec->section_cb != pmt_cb) ||
4469+ (sec->opaque != ts))
4470+ {
4471+ mpegts_close_filter(ts, ts->pmt_filter);
4472+ ts->pmt_filter = NULL;
4473+ }
4474+ }
4475+
4476+ /* create new pmt_filter if we need one */
4477+ if (!ts->pmt_filter)
4478+ {
4479+ ts->pmt_filter = mpegts_open_section_filter(
4480+ ts, pmt_pids[i], pmt_cb, ts, 1);
4481+ }
4482+
4483+ found = 1;
4484+ }
4485+ }
4486+
4487+ /* if we are scanning for any PAT and not a particular PMT,
4488+ * tell parser it is safe to quit. */
4489+ if (ts->req_sid < 0 && ts->scanning)
4490+ {
4491+#ifdef DEBUG
4492+ av_log(NULL, AV_LOG_DEBUG, "Found PAT, ending scan\n");
4493+#endif
4494+ ts->stop_parse = 1;
4495+ }
4496+
4497+ /* if we are looking for a particular MPEG program number,
4498+ * and it is not in this PAT indicate this in "pmt_scan_state"
4499+ * and tell parser it is safe to quit. */
4500+ if (ts->req_sid >= 0 && !found)
4501+ {
4502+#ifdef DEBUG
4503+ av_log(NULL, AV_LOG_DEBUG, "Program 0x%x is not in PAT, ending scan\n",
4504+ ts->req_sid);
4505+#endif
4506+ ts->pmt_scan_state = PMT_NOT_IN_PAT;
4507+ ts->stop_parse = 1;
4508+ }
4509+}
4510+
4511+static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
4512+{
4513+ MpegTSContext *ts = filter->u.section_filter.opaque;
4514+ SectionHeader h1, *h = &h1;
4515+ const uint8_t *p, *p_end, *desc_list_end, *desc_end;
4516+ int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
4517+ char *name, *provider_name;
4518+
4519+ av_dlog(ts->stream, "SDT:\n");
4520+ hex_dump_debug(ts->stream, (uint8_t *)section, section_len);
4521+
4522+ p_end = section + section_len - 4;
4523+ p = section;
4524+ if (parse_section_header(h, &p, p_end) < 0)
4525+ return;
4526+ if (h->tid != SDT_TID)
4527+ return;
4528+ onid = get16(&p, p_end);
4529+ if (onid < 0)
4530+ return;
4531+ val = get8(&p, p_end);
4532+ if (val < 0)
4533+ return;
4534+ for(;;) {
4535+ sid = get16(&p, p_end);
4536+ if (sid < 0)
4537+ break;
4538+ val = get8(&p, p_end);
4539+ if (val < 0)
4540+ break;
4541+ desc_list_len = get16(&p, p_end);
4542+ if (desc_list_len < 0)
4543+ break;
4544+ desc_list_len &= 0xfff;
4545+ desc_list_end = p + desc_list_len;
4546+ if (desc_list_end > p_end)
4547+ break;
4548+ for(;;) {
4549+ desc_tag = get8(&p, desc_list_end);
4550+ if (desc_tag < 0)
4551+ break;
4552+ desc_len = get8(&p, desc_list_end);
4553+ desc_end = p + desc_len;
4554+ if (desc_end > desc_list_end)
4555+ break;
4556+
4557+ av_dlog(ts->stream, "tag: 0x%02x len=%d\n",
4558+ desc_tag, desc_len);
4559+
4560+ switch(desc_tag) {
4561+ case 0x48:
4562+ service_type = get8(&p, p_end);
4563+ if (service_type < 0)
4564+ break;
4565+ provider_name = getstr8(&p, p_end);
4566+ if (!provider_name)
4567+ break;
4568+ name = getstr8(&p, p_end);
4569+ if (name) {
4570+ AVProgram *program = av_new_program(ts->stream, sid);
4571+ if(program) {
4572+ av_dict_set(&program->metadata, "service_name", name, 0);
4573+ av_dict_set(&program->metadata, "service_provider", provider_name, 0);
4574+ }
4575+ }
4576+ av_free(name);
4577+ av_free(provider_name);
4578+ break;
4579+ default:
4580+ break;
4581+ }
4582+ p = desc_end;
4583+ }
4584+ p = desc_list_end;
4585+ }
4586+}
4587+
4588+static SectionContext *add_section_stream(MpegTSContext *ts, int pid, int stream_type)
4589+{
4590+ MpegTSFilter *tss = ts->pids[pid];
4591+ SectionContext *sect = 0;
4592+ if (tss) { /* filter already exists */
4593+ if (tss->type == MPEGTS_SECTION)
4594+ sect = (SectionContext*) tss->u.section_filter.opaque;
4595+
4596+ if (sect && (sect->stream_type == stream_type))
4597+ return sect; /* if it's the same stream type, just return ok */
4598+
4599+ /* otherwise, kill it, and start a new stream */
4600+ mpegts_close_filter(ts, tss);
4601+ }
4602+
4603+ /* create a SECTION context */
4604+ if (!(sect=av_mallocz(sizeof(SectionContext)))) {
4605+ av_log(NULL, AV_LOG_ERROR, "Error: av_mallocz() failed in add_section_stream");
4606+ return 0;
4607+ }
4608+ sect->ts = ts;
4609+ sect->stream = ts->stream;
4610+ sect->pid = pid;
4611+ sect->stream_type = stream_type;
4612+ tss = mpegts_open_section_filter(ts, pid, mpegts_push_section, sect, 1);
4613+ if (!tss) {
4614+ av_free(sect);
4615+ av_log(NULL, AV_LOG_ERROR, "Error: unable to open mpegts Section filter in add_section_stream");
4616+ return 0;
4617+ }
4618+
4619+ return sect;
4620+}
4621+
4622+/* handle one TS packet */
4623+static int handle_packet(MpegTSContext *ts, const uint8_t *packet)
4624+{
4625+ AVFormatContext *s = ts->stream;
4626+ MpegTSFilter *tss;
4627+ int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity,
4628+ has_adaptation, has_payload;
4629+ const uint8_t *p, *p_end;
4630+ int64_t pos;
4631+
4632+ pid = AV_RB16(packet + 1) & 0x1fff;
4633+
4634+ if (!ts->pids[0]) {
4635+ /* make sure we're always scanning for new PAT's */
4636+ av_log(ts->stream, AV_LOG_INFO, "opening pat filter\n");
4637+ ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
4638+ }
4639+
4640+ if(pid && discard_pid(ts, pid))
4641+ {
4642+ av_log(ts->stream, AV_LOG_INFO, "discarding pid %d\n", pid);
4643+ return 0;
4644+ }
4645+
4646+ is_start = packet[1] & 0x40;
4647+ tss = ts->pids[pid];
4648+ if (ts->auto_guess && tss == NULL && is_start) {
4649+ add_pes_stream(ts, pid, -1);
4650+ tss = ts->pids[pid];
4651+ }
4652+ if (!tss)
4653+ return 0;
4654+
4655+ afc = (packet[3] >> 4) & 3;
4656+ if (afc == 0) /* reserved value */
4657+ return 0;
4658+ has_adaptation = afc & 2;
4659+ has_payload = afc & 1;
4660+ is_discontinuity = has_adaptation
4661+ && packet[4] != 0 /* with length > 0 */
4662+ && (packet[5] & 0x80); /* and discontinuity indicated */
4663+
4664+ /* continuity check (currently not used) */
4665+ cc = (packet[3] & 0xf);
4666+ expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc;
4667+ cc_ok = pid == 0x1FFF // null packet PID
4668+ || is_discontinuity
4669+ || tss->last_cc < 0
4670+ || expected_cc == cc;
4671+
4672+ tss->last_cc = cc;
4673+ if (!cc_ok) {
4674+ av_log(ts->stream, AV_LOG_DEBUG,
4675+ "Continuity check failed for pid %d expected %d got %d\n",
4676+ pid, expected_cc, cc);
4677+ if(tss->type == MPEGTS_PES) {
4678+ PESContext *pc = tss->u.pes_filter.opaque;
4679+ pc->flags |= AV_PKT_FLAG_CORRUPT;
4680+ }
4681+ }
4682+
4683+ if (!has_payload)
4684+ return 0;
4685+ p = packet + 4;
4686+ if (has_adaptation) {
4687+ /* skip adaptation field */
4688+ p += p[0] + 1;
4689+ }
4690+ /* if past the end of packet, ignore */
4691+ p_end = packet + TS_PACKET_SIZE;
4692+ if (p >= p_end)
4693+ return 0;
4694+
4695+ pos = avio_tell(ts->stream->pb);
4696+ ts->pos47= pos % ts->raw_packet_size;
4697+
4698+ if (tss->type == MPEGTS_SECTION) {
4699+ if (is_start) {
4700+ /* pointer field present */
4701+ len = *p++;
4702+ if (p + len > p_end)
4703+ {
4704+ av_log(s, AV_LOG_WARNING, "handle_packet: Last section data too long on PID=%#x, %d\n", pid, cc);
4705+ return 0;
4706+ }
4707+ if (len && cc_ok) {
4708+ /* write remaining section bytes */
4709+ write_section_data(s, tss,
4710+ p, len, 0);
4711+ /* check whether filter has been closed */
4712+ if (!ts->pids[pid])
4713+ return 0;
4714+ }
4715+ p += len;
4716+ if (p < p_end) {
4717+ write_section_data(s, tss,
4718+ p, p_end - p, 1);
4719+ }
4720+ } else {
4721+ if (cc_ok) {
4722+ write_section_data(s, tss,
4723+ p, p_end - p, 0);
4724+ }
4725+ }
4726+ } else {
4727+ int ret;
4728+ // Note: The position here points actually behind the current packet.
4729+ if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start,
4730+ pos - ts->raw_packet_size)) < 0)
4731+ return ret;
4732+ }
4733+
4734+ return 0;
4735+}
4736+
4737+/* XXX: try to find a better synchro over several packets (use
4738+ get_packet_size() ?) */
4739+static int mpegts_resync(AVFormatContext *s)
4740+{
4741+ AVIOContext *pb = s->pb;
4742+ int c, i;
4743+
4744+ for(i = 0;i < MAX_RESYNC_SIZE; i++) {
4745+ c = avio_r8(pb);
4746+ if (avio_feof(pb))
4747+ return -1;
4748+ if (c == 0x47) {
4749+ avio_seek(pb, -1, SEEK_CUR);
4750+ return 0;
4751+ }
4752+ }
4753+ av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n");
4754+ /* no sync found */
4755+ return -1;
4756+}
4757+
4758+/* return -1 if error or EOF. Return 0 if OK. */
4759+static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size)
4760+{
4761+ AVIOContext *pb = s->pb;
4762+ int skip, len;
4763+
4764+ for(;;) {
4765+ len = avio_read(pb, buf, TS_PACKET_SIZE);
4766+ if (len != TS_PACKET_SIZE)
4767+ return len < 0 ? len : AVERROR_EOF;
4768+ /* check packet sync byte */
4769+ if (buf[0] != 0x47) {
4770+ /* find a new packet start */
4771+ avio_seek(pb, -TS_PACKET_SIZE, SEEK_CUR);
4772+ if (mpegts_resync(s) < 0)
4773+ return AVERROR(EAGAIN);
4774+ else
4775+ continue;
4776+ } else {
4777+ skip = raw_packet_size - TS_PACKET_SIZE;
4778+ if (skip > 0)
4779+ avio_skip(pb, skip);
4780+ break;
4781+ }
4782+ }
4783+ return 0;
4784+}
4785+
4786+static int handle_packets(MpegTSContext *ts, int nb_packets)
4787+{
4788+ AVFormatContext *s = ts->stream;
4789+ uint8_t packet[TS_PACKET_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
4790+ int packet_num, ret = 0;
4791+
4792+ if (avio_tell(s->pb) != ts->last_pos) {
4793+ int i;
4794+ av_dlog(ts->stream, "Skipping after seek\n");
4795+ /* seek detected, flush pes buffer */
4796+ for (i = 0; i < NB_PID_MAX; i++) {
4797+ if (ts->pids[i]) {
4798+ if (ts->pids[i]->type == MPEGTS_PES) {
4799+ PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
4800+ av_freep(&pes->buffer);
4801+ pes->data_index = 0;
4802+ pes->state = MPEGTS_SKIP; /* skip until pes header */
4803+ }
4804+ ts->pids[i]->last_cc = -1;
4805+ }
4806+ }
4807+ }
4808+
4809+ ts->stop_parse = 0;
4810+ packet_num = 0;
4811+ memset(packet + TS_PACKET_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
4812+ for(;;) {
4813+ packet_num++;
4814+ if (nb_packets != 0 && packet_num >= nb_packets ||
4815+ ts->stop_parse > 1) {
4816+ ret = AVERROR(EAGAIN);
4817+ break;
4818+ }
4819+ if (ts->stop_parse > 0)
4820+ break;
4821+
4822+ ret = read_packet(s, packet, ts->raw_packet_size);
4823+ if (ret != 0)
4824+ break;
4825+ ret = handle_packet(ts, packet);
4826+ if (ret != 0)
4827+ break;
4828+ }
4829+ ts->last_pos = avio_tell(s->pb);
4830+ return ret;
4831+}
4832+
4833+static int mpegts_probe(AVProbeData *p)
4834+{
4835+ const int size= p->buf_size;
4836+ int maxscore=0;
4837+ int sumscore=0;
4838+ int i;
4839+ int check_count= size / TS_FEC_PACKET_SIZE;
4840+#define CHECK_COUNT 10
4841+#define CHECK_BLOCK 100
4842+
4843+ if (check_count < CHECK_COUNT)
4844+ return -1;
4845+
4846+ for (i=0; i<check_count; i+=CHECK_BLOCK){
4847+ int left = FFMIN(check_count - i, CHECK_BLOCK);
4848+ int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL);
4849+ int dvhs_score= analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL);
4850+ int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL);
4851+ score = FFMAX3(score, dvhs_score, fec_score);
4852+ sumscore += score;
4853+ maxscore = FFMAX(maxscore, score);
4854+ }
4855+
4856+ sumscore = sumscore*CHECK_COUNT/check_count;
4857+ maxscore = maxscore*CHECK_COUNT/CHECK_BLOCK;
4858+
4859+ av_dlog(0, "TS score: %d %d\n", sumscore, maxscore);
4860+
4861+ if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT;
4862+ else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT;
4863+ else return -1;
4864+}
4865+
4866+/* return the 90kHz PCR and the extension for the 27MHz PCR. return
4867+ (-1) if not available */
4868+static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
4869+ const uint8_t *packet)
4870+{
4871+ int afc, len, flags;
4872+ const uint8_t *p;
4873+ unsigned int v;
4874+
4875+ afc = (packet[3] >> 4) & 3;
4876+ if (afc <= 1)
4877+ return -1;
4878+ p = packet + 4;
4879+ len = p[0];
4880+ p++;
4881+ if (len == 0)
4882+ return -1;
4883+ flags = *p++;
4884+ len--;
4885+ if (!(flags & 0x10))
4886+ return -1;
4887+ if (len < 6)
4888+ return -1;
4889+ v = AV_RB32(p);
4890+ *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
4891+ *ppcr_low = ((p[4] & 1) << 8) | p[5];
4892+ return 0;
4893+}
4894+
4895+static int mpegts_read_header(AVFormatContext *s)
4896+{
4897+ MpegTSContext *ts = s->priv_data;
4898+ AVIOContext *pb = s->pb;
4899+ uint8_t buf[8*1024] = {0};
4900+ int len, sid, i;
4901+ int64_t pos, probesize =
4902+#if FF_API_PROBESIZE_32
4903+ s->probesize ? s->probesize : s->probesize2;
4904+#else
4905+ s->probesize;
4906+#endif
4907+
4908+ memset(ts->pids, 0, NB_PID_MAX * sizeof(MpegTSFilter *));
4909+
4910+ /* read the first 8192 bytes to get packet size */
4911+ pos = avio_tell(pb);
4912+ len = avio_read(pb, buf, sizeof(buf));
4913+ ts->raw_packet_size = get_packet_size(buf, len);
4914+ av_log(NULL, AV_LOG_DEBUG, "mpegts_read_header: TS packet size = %d\n",
4915+ ts->raw_packet_size);
4916+ if (ts->raw_packet_size <= 0) {
4917+ av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n");
4918+ ts->raw_packet_size = TS_PACKET_SIZE;
4919+ }
4920+ ts->stream = s;
4921+ ts->auto_guess = 0;
4922+
4923+ if (s->iformat == &ff_mythtv_mpegts_demuxer) {
4924+ /* normal demux */
4925+
4926+ if (!ts->auto_guess) {
4927+ /* first do a scan to get all the services */
4928+ /* NOTE: We attempt to seek on non-seekable files as well, as the
4929+ * probe buffer usually is big enough. Only warn if the seek failed
4930+ * on files where the seek should work. */
4931+ if (avio_seek(pb, pos, SEEK_SET) < 0)
4932+ av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n");
4933+
4934+ /* SDT Scan Removed here. It caused startup delays in TS files
4935+ SDT will not exist in a stripped TS file created by myth. */
4936+#if 0
4937+ mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
4938+#endif
4939+
4940+ /* we don't want any PMT pid filters created on first pass */
4941+ ts->req_sid = -1;
4942+
4943+ ts->scanning = 1;
4944+ ts->pat_filter =
4945+ mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
4946+
4947+ handle_packets(ts, probesize / ts->raw_packet_size);
4948+ ts->scanning = 0;
4949+
4950+ if (ts->nb_prg <= 0) {
4951+ /* Guess this is a raw transport stream with no PAT tables. */
4952+ ts->auto_guess = 1;
4953+ s->ctx_flags |= AVFMTCTX_NOHEADER;
4954+ goto do_pcr;
4955+ }
4956+
4957+ ts->scanning = 1;
4958+ ts->pmt_scan_state = PMT_NOT_YET_FOUND;
4959+ /* tune to first service found */
4960+ for (i = 0; ((i < ts->nb_prg) &&
4961+ (ts->pmt_scan_state == PMT_NOT_YET_FOUND)); i++)
4962+ {
4963+#ifdef DEBUG
4964+ av_log(ts->stream, AV_LOG_DEBUG, "Tuning to pnum: 0x%x\n",
4965+ ts->prg[i].id);
4966+#endif
4967+
4968+ /* now find the info for the first service if we found any,
4969+ otherwise try to filter all PATs */
4970+
4971+ avio_seek(pb, pos, SEEK_SET);
4972+ ts->req_sid = sid = ts->prg[i].id;
4973+ handle_packets(ts, probesize / ts->raw_packet_size);
4974+
4975+ /* fallback code to deal with broken streams from
4976+ * DBOX2/Firewire cable boxes. */
4977+ if (ts->pmt_filter &&
4978+ (ts->pmt_scan_state == PMT_NOT_YET_FOUND))
4979+ {
4980+ av_log(NULL, AV_LOG_ERROR,
4981+ "Tuning to pnum: 0x%x without CRC check on PMT\n",
4982+ ts->prg[i].id);
4983+ /* turn off crc checking */
4984+ ts->pmt_filter->u.section_filter.check_crc = 0;
4985+ /* try again */
4986+ avio_seek(pb, pos, SEEK_SET);
4987+ ts->req_sid = sid = ts->prg[i].id;
4988+ handle_packets(ts, probesize / ts->raw_packet_size);
4989+ }
4990+
4991+ /* fallback code to deal with streams that are not complete PMT
4992+ * streams (BBC iPlayer IPTV as an example) */
4993+ if (ts->pmt_filter &&
4994+ (ts->pmt_scan_state == PMT_NOT_YET_FOUND))
4995+ {
4996+ av_log(NULL, AV_LOG_ERROR,
4997+ "Overriding PMT data length, using "
4998+ "contents of first TS packet only!\n");
4999+ ts->pmt_filter->pmt_chop_at_ts = 1;
5000+ /* try again */
5001+ avio_seek(pb, pos, SEEK_SET);
5002+ ts->req_sid = sid = ts->prg[i].id;
5003+ handle_packets(ts, probesize / ts->raw_packet_size);
5004+ }
5005+ }
5006+ ts->scanning = 0;
5007+
5008+ /* if we could not find any PMTs, fail */
5009+ if (ts->pmt_scan_state == PMT_NOT_YET_FOUND)
5010+ {
5011+ av_log(NULL, AV_LOG_ERROR,
5012+ "mpegts_read_header: could not find any PMT's\n");
5013+ goto fail;
5014+ }
5015+ av_dlog(ts->stream, "tuning done\n");
5016+ }
5017+
5018+ s->ctx_flags |= AVFMTCTX_NOHEADER;
5019+ } else {
5020+ AVStream *st;
5021+ int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
5022+ int64_t pcrs[2], pcr_h;
5023+ int packet_count[2];
5024+ uint8_t packet[TS_PACKET_SIZE];
5025+
5026+ /* only read packets */
5027+
5028+ do_pcr:
5029+ st = avformat_new_stream(s, NULL);
5030+ if (!st)
5031+ {
5032+ av_log(NULL, AV_LOG_ERROR, "mpegts_read_header: "
5033+ "av_new_stream() failed\n");
5034+ goto fail;
5035+ }
5036+ avpriv_set_pts_info(st, 60, 1, 27000000);
5037+ st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
5038+ st->codecpar->codec_id = AV_CODEC_ID_MPEG2TS;
5039+
5040+ /* we iterate until we find two PCRs to estimate the bitrate */
5041+ pcr_pid = -1;
5042+ nb_pcrs = 0;
5043+ nb_packets = 0;
5044+ for(;;) {
5045+ ret = read_packet(s, packet, ts->raw_packet_size);
5046+ if (ret < 0)
5047+ {
5048+ av_log(NULL, AV_LOG_ERROR, "mpegts_read_header: "
5049+ "read_packet() failed\n");
5050+ return -1;
5051+ }
5052+ pid = AV_RB16(packet + 1) & 0x1fff;
5053+ if ((pcr_pid == -1 || pcr_pid == pid) &&
5054+ parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
5055+ pcr_pid = pid;
5056+ packet_count[nb_pcrs] = nb_packets;
5057+ pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
5058+ nb_pcrs++;
5059+ if (nb_pcrs >= 2)
5060+ break;
5061+ }
5062+ nb_packets++;
5063+ }
5064+
5065+ /* NOTE1: the bitrate is computed without the FEC */
5066+ /* NOTE2: it is only the bitrate of the start of the stream */
5067+ ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
5068+ ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
5069+ s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
5070+ st->codecpar->bit_rate = s->bit_rate;
5071+ st->start_time = ts->cur_pcr;
5072+ av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",
5073+ st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
5074+ }
5075+
5076+ avio_seek(pb, pos, SEEK_SET);
5077+ return 0;
5078+ fail:
5079+ return -1;
5080+}
5081+
5082+#define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
5083+
5084+static int mpegts_raw_read_packet(AVFormatContext *s,
5085+ AVPacket *pkt)
5086+{
5087+ MpegTSContext *ts = s->priv_data;
5088+ int ret, i;
5089+ int64_t pcr_h, next_pcr_h, pos;
5090+ int pcr_l, next_pcr_l;
5091+ uint8_t pcr_buf[12];
5092+
5093+ if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
5094+ return AVERROR(ENOMEM);
5095+ pkt->pos= avio_tell(s->pb);
5096+ ret = read_packet(s, pkt->data, ts->raw_packet_size);
5097+ if (ret < 0) {
5098+ av_free_packet(pkt);
5099+ return ret;
5100+ }
5101+ if (ts->mpeg2ts_compute_pcr) {
5102+ /* compute exact PCR for each packet */
5103+ if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
5104+ /* we read the next PCR (XXX: optimize it by using a bigger buffer */
5105+ pos = avio_tell(s->pb);
5106+ for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
5107+ avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
5108+ avio_read(s->pb, pcr_buf, 12);
5109+ if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
5110+ /* XXX: not precise enough */
5111+ ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
5112+ (i + 1);
5113+ break;
5114+ }
5115+ }
5116+ avio_seek(s->pb, pos, SEEK_SET);
5117+ /* no next PCR found: we use previous increment */
5118+ ts->cur_pcr = pcr_h * 300 + pcr_l;
5119+ }
5120+ pkt->pts = ts->cur_pcr;
5121+ pkt->duration = ts->pcr_incr;
5122+ ts->cur_pcr += ts->pcr_incr;
5123+ }
5124+ pkt->stream_index = 0;
5125+ return 0;
5126+}
5127+
5128+static int mpegts_read_packet(AVFormatContext *s,
5129+ AVPacket *pkt)
5130+{
5131+ MpegTSContext *ts = s->priv_data;
5132+ int ret, i;
5133+
5134+ ts->pkt = pkt;
5135+ ret = handle_packets(ts, 0);
5136+ if (ret < 0) {
5137+ av_free_packet(ts->pkt);
5138+ /* flush pes data left */
5139+ for (i = 0; i < NB_PID_MAX; i++) {
5140+ if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
5141+ PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
5142+ if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) {
5143+ new_pes_packet(pes, pkt);
5144+ pes->state = MPEGTS_SKIP;
5145+ ret = 0;
5146+ break;
5147+ }
5148+ }
5149+ }
5150+ }
5151+
5152+ return ret;
5153+}
5154+
5155+static int mpegts_read_close(AVFormatContext *s)
5156+{
5157+ MpegTSContext *ts = s->priv_data;
5158+ int i;
5159+
5160+ clear_programs(ts);
5161+
5162+ for(i=0;i<NB_PID_MAX;i++)
5163+ if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
5164+
5165+ return 0;
5166+}
5167+
5168+static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
5169+ int64_t *ppos, int64_t pos_limit)
5170+{
5171+ MpegTSContext *ts = s->priv_data;
5172+ int64_t pos, timestamp;
5173+ uint8_t buf[TS_PACKET_SIZE];
5174+ int pcr_l, pcr_pid = ((PESContext*)s->streams[stream_index]->priv_data)->pcr_pid;
5175+ pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
5176+ while(pos < pos_limit) {
5177+ if (avio_seek(s->pb, pos, SEEK_SET) < 0)
5178+ return AV_NOPTS_VALUE;
5179+ if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
5180+ return AV_NOPTS_VALUE;
5181+ if (buf[0] != 0x47) {
5182+ if (mpegts_resync(s) < 0)
5183+ return AV_NOPTS_VALUE;
5184+ pos = avio_tell(s->pb);
5185+ continue;
5186+ }
5187+ if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) &&
5188+ parse_pcr(×tamp, &pcr_l, buf) == 0) {
5189+ *ppos = pos;
5190+ return timestamp;
5191+ }
5192+ pos += ts->raw_packet_size;
5193+ }
5194+
5195+ return AV_NOPTS_VALUE;
5196+}
5197+
5198+static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
5199+ int64_t *ppos, int64_t pos_limit)
5200+{
5201+ MpegTSContext *ts = s->priv_data;
5202+ int64_t pos;
5203+ pos = ((*ppos + ts->raw_packet_size - 1 - ts->pos47) / ts->raw_packet_size) * ts->raw_packet_size + ts->pos47;
5204+ ff_read_frame_flush(s);
5205+ if (avio_seek(s->pb, pos, SEEK_SET) < 0)
5206+ return AV_NOPTS_VALUE;
5207+ while(pos < pos_limit) {
5208+ int ret;
5209+ AVPacket pkt;
5210+ av_init_packet(&pkt);
5211+ ret= av_read_frame(s, &pkt);
5212+ if(ret < 0)
5213+ return AV_NOPTS_VALUE;
5214+ av_free_packet(&pkt);
5215+ if(pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0){
5216+ ff_reduce_index(s, pkt.stream_index);
5217+ av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */);
5218+ if(pkt.stream_index == stream_index){
5219+ *ppos= pkt.pos;
5220+ return pkt.dts;
5221+ }
5222+ }
5223+ pos = pkt.pos;
5224+ }
5225+
5226+ return AV_NOPTS_VALUE;
5227+}
5228+
5229+#ifdef USE_SYNCPOINT_SEARCH
5230+
5231+static int read_seek2(AVFormatContext *s,
5232+ int stream_index,
5233+ int64_t min_ts,
5234+ int64_t target_ts,
5235+ int64_t max_ts,
5236+ int flags)
5237+{
5238+ int64_t pos;
5239+
5240+ int64_t ts_ret, ts_adj;
5241+ int stream_index_gen_search;
5242+ AVStream *st;
5243+ AVParserState *backup;
5244+
5245+ backup = ff_store_parser_state(s);
5246+
5247+ // detect direction of seeking for search purposes
5248+ flags |= (target_ts - min_ts > (uint64_t)(max_ts - target_ts)) ?
5249+ AVSEEK_FLAG_BACKWARD : 0;
5250+
5251+ if (flags & AVSEEK_FLAG_BYTE) {
5252+ // use position directly, we will search starting from it
5253+ pos = target_ts;
5254+ } else {
5255+ // search for some position with good timestamp match
5256+ if (stream_index < 0) {
5257+ stream_index_gen_search = av_find_default_stream_index(s);
5258+ if (stream_index_gen_search < 0) {
5259+ ff_restore_parser_state(s, backup);
5260+ return -1;
5261+ }
5262+
5263+ st = s->streams[stream_index_gen_search];
5264+ // timestamp for default must be expressed in AV_TIME_BASE units
5265+ ts_adj = av_rescale(target_ts,
5266+ st->time_base.den,
5267+ AV_TIME_BASE * (int64_t)st->time_base.num);
5268+ } else {
5269+ ts_adj = target_ts;
5270+ stream_index_gen_search = stream_index;
5271+ }
5272+ pos = ff_gen_search(s, stream_index_gen_search, ts_adj,
5273+ 0, INT64_MAX, -1,
5274+ AV_NOPTS_VALUE,
5275+ AV_NOPTS_VALUE,
5276+ flags, &ts_ret, mpegts_get_pcr);
5277+ if (pos < 0) {
5278+ ff_restore_parser_state(s, backup);
5279+ return -1;
5280+ }
5281+ }
5282+
5283+ // search for actual matching keyframe/starting position for all streams
5284+ if (ff_gen_syncpoint_search(s, stream_index, pos,
5285+ min_ts, target_ts, max_ts,
5286+ flags) < 0) {
5287+ ff_restore_parser_state(s, backup);
5288+ return -1;
5289+ }
5290+
5291+ ff_free_parser_state(s, backup);
5292+ return 0;
5293+}
5294+
5295+static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags)
5296+{
5297+ int ret;
5298+ if (flags & AVSEEK_FLAG_BACKWARD) {
5299+ flags &= ~AVSEEK_FLAG_BACKWARD;
5300+ ret = read_seek2(s, stream_index, INT64_MIN, target_ts, target_ts, flags);
5301+ if (ret < 0)
5302+ // for compatibility reasons, seek to the best-fitting timestamp
5303+ ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
5304+ } else {
5305+ ret = read_seek2(s, stream_index, target_ts, target_ts, INT64_MAX, flags);
5306+ if (ret < 0)
5307+ // for compatibility reasons, seek to the best-fitting timestamp
5308+ ret = read_seek2(s, stream_index, INT64_MIN, target_ts, INT64_MAX, flags);
5309+ }
5310+ return ret;
5311+}
5312+
5313+#endif
5314+
5315+/**************************************************************/
5316+/* parsing functions - called from other demuxers such as RTP */
5317+
5318+MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
5319+{
5320+ MpegTSContext *ts;
5321+
5322+ ts = av_mallocz(sizeof(MpegTSContext));
5323+ if (!ts)
5324+ return NULL;
5325+ /* no stream case, currently used by RTP */
5326+ ts->raw_packet_size = TS_PACKET_SIZE;
5327+ ts->stream = s;
5328+ ts->auto_guess = 1;
5329+ mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);
5330+ mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);
5331+
5332+ return ts;
5333+}
5334+
5335+/* return the consumed length if a packet was output, or -1 if no
5336+ packet is output */
5337+int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5338+ const uint8_t *buf, int len)
5339+{
5340+ int len1;
5341+
5342+ len1 = len;
5343+ ts->pkt = pkt;
5344+ for(;;) {
5345+ ts->stop_parse = 0;
5346+ if (len < TS_PACKET_SIZE)
5347+ return -1;
5348+ if (buf[0] != 0x47) {
5349+ buf++;
5350+ len--;
5351+ } else {
5352+ handle_packet(ts, buf);
5353+ buf += TS_PACKET_SIZE;
5354+ len -= TS_PACKET_SIZE;
5355+ if (ts->stop_parse == 1)
5356+ break;
5357+ }
5358+ }
5359+ return len1 - len;
5360+}
5361+
5362+void avpriv_mpegts_parse_close(MpegTSContext *ts)
5363+{
5364+ int i;
5365+
5366+ for(i=0;i<NB_PID_MAX;i++)
5367+ av_free(ts->pids[i]);
5368+ av_free(ts);
5369+}
5370+
5371+AVStream *av_new_stream(AVFormatContext *s, int id)
5372+{
5373+ AVStream *st = avformat_new_stream(s, NULL);
5374+ if (st)
5375+ st->id = id;
5376+ return st;
5377+}
5378+
5379+void av_set_pts_info(AVStream *s, int pts_wrap_bits,
5380+ unsigned int pts_num, unsigned int pts_den)
5381+{
5382+ avpriv_set_pts_info(s, pts_wrap_bits, pts_num, pts_den);
5383+}
5384+
5385+AVInputFormat ff_mythtv_mpegts_demuxer = {
5386+ .name = "mpegts",
5387+ .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
5388+ .priv_data_size = sizeof(MpegTSContext),
5389+ .read_probe = mpegts_probe,
5390+ .read_header = mpegts_read_header,
5391+ .read_packet = mpegts_read_packet,
5392+ .read_close = mpegts_read_close,
5393+ .read_timestamp = mpegts_get_dts,
5394+ .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
5395+#ifdef USE_SYNCPOINT_SEARCH
5396+ .read_seek2 = read_seek2,
5397+#endif
5398+};
5399+
5400+AVInputFormat ff_mythtv_mpegtsraw_demuxer = {
5401+ .name = "mpegtsraw",
5402+ .long_name = NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
5403+ .priv_data_size = sizeof(MpegTSContext),
5404+ .read_header = mpegts_read_header,
5405+ .read_packet = mpegts_raw_read_packet,
5406+ .read_close = mpegts_read_close,
5407+ .read_timestamp = mpegts_get_dts,
5408+ .flags = AVFMT_SHOW_IDS|AVFMT_TS_DISCONT,
5409+#ifdef USE_SYNCPOINT_SEARCH
5410+ .read_seek2 = read_seek2,
5411+#endif
5412+ .priv_class = &mpegtsraw_class,
5413+};
5414diff --git a/libavformat/mpegts-mythtv.h b/libavformat/mpegts-mythtv.h
5415new file mode 100644
5416index 0000000000..0f3c767991
5417--- /dev/null
5418+++ b/libavformat/mpegts-mythtv.h
5419@@ -0,0 +1,153 @@
5420+/*
5421+ * MPEG2 transport stream defines
5422+ * Copyright (c) 2003 Fabrice Bellard
5423+ *
5424+ * This file is part of FFmpeg.
5425+ *
5426+ * FFmpeg is free software; you can redistribute it and/or
5427+ * modify it under the terms of the GNU Lesser General Public
5428+ * License as published by the Free Software Foundation; either
5429+ * version 2.1 of the License, or (at your option) any later version.
5430+ *
5431+ * FFmpeg is distributed in the hope that it will be useful,
5432+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
5433+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5434+ * Lesser General Public License for more details.
5435+ *
5436+ * You should have received a copy of the GNU Lesser General Public
5437+ * License along with FFmpeg; if not, write to the Free Software
5438+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
5439+ */
5440+
5441+#ifndef AVFORMAT_MPEGTS_MYTHTV_H
5442+#define AVFORMAT_MPEGTS_MYTHTV_H
5443+
5444+#include "avformat.h"
5445+
5446+#define TS_FEC_PACKET_SIZE 204
5447+#define TS_DVHS_PACKET_SIZE 192
5448+#define TS_PACKET_SIZE 188
5449+#define TS_MAX_PACKET_SIZE 204
5450+
5451+#define NB_PID_MAX 8192
5452+#define MAX_SECTION_SIZE 4096
5453+
5454+/* pids */
5455+#define PAT_PID 0x0000
5456+#define SDT_PID 0x0011
5457+
5458+/* table ids */
5459+#define PAT_TID 0x00
5460+#define PMT_TID 0x02
5461+#define M4OD_TID 0x05
5462+#define SDT_TID 0x42
5463+
5464+#define DVB_CAROUSEL_ID 0x13
5465+#define DVB_VBI_DATA_ID 0x45
5466+#define DVB_VBI_TELETEXT_ID 0x46
5467+#define DVB_TELETEXT_ID 0x56
5468+#define DVB_SUBT_DESCID 0x59
5469+#define DVB_BROADCAST_ID 0x66
5470+#define DVB_DATA_STREAM 0x52
5471+#define STREAM_TYPE_VIDEO_MPEG1 0x01
5472+#define STREAM_TYPE_VIDEO_MPEG2 0x02
5473+#define STREAM_TYPE_AUDIO_MPEG1 0x03
5474+#define STREAM_TYPE_AUDIO_MPEG2 0x04
5475+#define STREAM_TYPE_PRIVATE_SECTION 0x05
5476+#define STREAM_TYPE_PRIVATE_DATA 0x06
5477+#define STREAM_TYPE_DSMCC_B 0x0b
5478+#define STREAM_TYPE_AUDIO_AAC 0x0f
5479+#define STREAM_TYPE_AUDIO_AAC_LATM 0x11
5480+#define STREAM_TYPE_VIDEO_MPEG4 0x10
5481+#define STREAM_TYPE_VIDEO_H264 0x1b
5482+#define STREAM_TYPE_VIDEO_VC1 0xea
5483+#define STREAM_TYPE_VIDEO_DIRAC 0xd1
5484+
5485+#define STREAM_TYPE_AUDIO_AC3 0x81
5486+#define STREAM_TYPE_AUDIO_DTS 0x8a
5487+#define STREAM_TYPE_AUDIO_HDMV_AC3_PLUS 0x84
5488+#define STREAM_TYPE_AUDIO_HDMV_AC3_TRUE_HD 0x83
5489+#define STREAM_TYPE_AUDIO_HDMV_DTS 0x82
5490+#define STREAM_TYPE_AUDIO_HDMV_DTS_HD 0x85
5491+#define STREAM_TYPE_AUDIO_HDMV_DTS_HD_MASTER 0x86
5492+
5493+#define STREAM_TYPE_SUBTITLE_DVB 0x100
5494+#define STREAM_TYPE_VBI_DVB 0x101
5495+
5496+typedef struct MpegTSContext MpegTSContext;
5497+
5498+void mpegts_remove_stream(MpegTSContext *ts, int pid);
5499+MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s);
5500+int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5501+ const uint8_t *buf, int len);
5502+void avpriv_mpegts_parse_close(MpegTSContext *ts);
5503+
5504+typedef struct {
5505+ int use_au_start;
5506+ int use_au_end;
5507+ int use_rand_acc_pt;
5508+ int use_padding;
5509+ int use_timestamps;
5510+ int use_idle;
5511+ int timestamp_res;
5512+ int timestamp_len;
5513+ int ocr_len;
5514+ int au_len;
5515+ int inst_bitrate_len;
5516+ int degr_prior_len;
5517+ int au_seq_num_len;
5518+ int packet_seq_num_len;
5519+} SLConfigDescr;
5520+
5521+typedef struct {
5522+ int es_id;
5523+ int dec_config_descr_len;
5524+ uint8_t *dec_config_descr;
5525+ SLConfigDescr sl;
5526+} Mp4Descr;
5527+
5528+typedef struct
5529+{
5530+ char language[4];
5531+ int comp_page;
5532+ int anc_page;
5533+ int sub_id;
5534+ int txt_type;
5535+ int vbi_data;
5536+ int disposition;
5537+ /* DSMCC data */
5538+ int data_id;
5539+ int carousel_id;
5540+ int component_tag;
5541+ unsigned int codec_tag;
5542+} dvb_caption_info_t;
5543+
5544+typedef struct
5545+{
5546+ int pid;
5547+ int type;
5548+ enum AVCodecID codec_id;
5549+ enum AVMediaType codec_type;
5550+ dvb_caption_info_t dvbci;
5551+} pmt_entry_t;
5552+
5553+
5554+/**
5555+ * Parse an MPEG-2 descriptor
5556+ * @param[in] fc Format context (used for logging only)
5557+ * @param st Stream
5558+ * @param stream_type STREAM_TYPE_xxx
5559+ * @param pp Descriptor buffer pointer
5560+ * @param desc_list_end End of buffer
5561+ * @return <0 to stop processing
5562+ */
5563+int ff_parse_mpeg2_descriptor(AVFormatContext *fc, pmt_entry_t *item, int stream_type,
5564+ const uint8_t **pp, const uint8_t *desc_list_end,
5565+ Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
5566+ MpegTSContext *ts, dvb_caption_info_t *dvbci);
5567+
5568+AVStream *av_new_stream(AVFormatContext *s, int id);
5569+void av_set_pts_info(AVStream *s, int pts_wrap_bits,
5570+ unsigned int pts_num, unsigned int pts_den);
5571+
5572+#endif /* AVFORMAT_MPEGTS_MYTHTV_H */
5573diff --git a/libavformat/mpegts.c b/libavformat/mpegts.c
5574index a3033134f7..1092a9b67c 100644
5575--- a/libavformat/mpegts.c
5576+++ b/libavformat/mpegts.c
5577@@ -1778,7 +1778,7 @@ static const uint8_t opus_channel_map[8][8] = {
5578 { 0,6,1,2,3,4,5,7 },
5579 };
5580
5581-int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
5582+int ff_old_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
5583 const uint8_t **pp, const uint8_t *desc_list_end,
5584 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
5585 MpegTSContext *ts)
5586@@ -2465,7 +2465,7 @@ static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len
5587 if (desc_list_end > p_end)
5588 goto out;
5589 for (;;) {
5590- if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
5591+ if (ff_old_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p,
5592 desc_list_end, mp4_descr,
5593 mp4_descr_count, pid, ts) < 0)
5594 break;
5595@@ -3336,7 +3336,7 @@ static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index,
5596 /**************************************************************/
5597 /* parsing functions - called from other demuxers such as RTP */
5598
5599-MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
5600+MpegTSContext *avpriv_old_mpegts_parse_open(AVFormatContext *s)
5601 {
5602 MpegTSContext *ts;
5603
5604@@ -3357,7 +3357,7 @@ MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s)
5605
5606 /* return the consumed length if a packet was output, or -1 if no
5607 * packet is output */
5608-int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5609+int avpriv_old_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5610 const uint8_t *buf, int len)
5611 {
5612 int len1;
5613@@ -3382,14 +3382,14 @@ int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5614 return len1 - len;
5615 }
5616
5617-void avpriv_mpegts_parse_close(MpegTSContext *ts)
5618+void avpriv_old_mpegts_parse_close(MpegTSContext *ts)
5619 {
5620 mpegts_free(ts);
5621 av_free(ts);
5622 }
5623
5624 AVInputFormat ff_mpegts_demuxer = {
5625- .name = "mpegts",
5626+ .name = "mpegts-ffmpeg",
5627 .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"),
5628 .priv_data_size = sizeof(MpegTSContext),
5629 .read_probe = mpegts_probe,
5630@@ -3402,7 +3402,7 @@ AVInputFormat ff_mpegts_demuxer = {
5631 };
5632
5633 AVInputFormat ff_mpegtsraw_demuxer = {
5634- .name = "mpegtsraw",
5635+ .name = "mpegtsraw-ffmpeg",
5636 .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"),
5637 .priv_data_size = sizeof(MpegTSContext),
5638 .read_header = mpegts_read_header,
5639diff --git a/libavformat/mpegts.h b/libavformat/mpegts.h
5640index 04874e0f42..057c44ba64 100644
5641--- a/libavformat/mpegts.h
5642+++ b/libavformat/mpegts.h
5643@@ -156,10 +156,10 @@
5644
5645 typedef struct MpegTSContext MpegTSContext;
5646
5647-MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s);
5648-int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5649- const uint8_t *buf, int len);
5650-void avpriv_mpegts_parse_close(MpegTSContext *ts);
5651+MpegTSContext *avpriv_old_mpegts_parse_open(AVFormatContext *s);
5652+int avpriv_old_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
5653+ const uint8_t *buf, int len);
5654+void avpriv_old_mpegts_parse_close(MpegTSContext *ts);
5655
5656 typedef struct SLConfigDescr {
5657 int use_au_start;
5658@@ -210,7 +210,7 @@ typedef struct DVBAC3Descriptor {
5659 * @param desc_list_end End of buffer
5660 * @return <0 to stop processing
5661 */
5662-int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
5663+int ff_old_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type,
5664 const uint8_t **pp, const uint8_t *desc_list_end,
5665 Mp4Descr *mp4_descr, int mp4_descr_count, int pid,
5666 MpegTSContext *ts);
5667diff --git a/libavformat/os_support.h b/libavformat/os_support.h
5668index 5e6b32d2dc..f17c4ae8e9 100644
5669--- a/libavformat/os_support.h
5670+++ b/libavformat/os_support.h
5671@@ -72,6 +72,8 @@ static inline int is_dos_path(const char *path)
5672 #if HAVE_DOS_PATHS
5673 if (path[0] && path[1] == ':')
5674 return 1;
5675+#else
5676+ (void)path;
5677 #endif
5678 return 0;
5679 }
5680diff --git a/libavformat/rtpdec_mpegts.c b/libavformat/rtpdec_mpegts.c
5681index 405271f744..ffb3546fce 100644
5682--- a/libavformat/rtpdec_mpegts.c
5683+++ b/libavformat/rtpdec_mpegts.c
5684@@ -20,7 +20,7 @@
5685 */
5686
5687 #include "libavutil/attributes.h"
5688-#include "mpegts.h"
5689+#include "mpegts-mythtv.h"
5690 #include "rtpdec_formats.h"
5691
5692 struct PayloadContext {
5693diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
5694index 25bdf475b3..e7e160b84e 100644
5695--- a/libavformat/rtsp.c
5696+++ b/libavformat/rtsp.c
5697@@ -49,7 +49,7 @@
5698 #include "rtpenc_chain.h"
5699 #include "url.h"
5700 #include "rtpenc.h"
5701-#include "mpegts.h"
5702+#include "mpegts-mythtv.h"
5703
5704 /* Default timeout values for read packet in seconds */
5705 #define READ_PACKET_TIMEOUT_S 10
5706diff --git a/libavformat/utils-mythtv.c b/libavformat/utils-mythtv.c
5707new file mode 100644
5708index 0000000000..436e5d0e73
5709--- /dev/null
5710+++ b/libavformat/utils-mythtv.c
5711@@ -0,0 +1,161 @@
5712+/*
5713+ * MPEG2 transport utilities
5714+ * Copyright (c) 2002-2012 The MythTV Team
5715+ *
5716+ * This file is part of MythTV.
5717+ *
5718+ * FFmpeg is free software; you can redistribute it and/or
5719+ * modify it under the terms of the GNU Lesser General Public
5720+ * License as published by the Free Software Foundation; either
5721+ * version 2.1 of the License, or (at your option) any later version.
5722+ *
5723+ * FFmpeg is distributed in the hope that it will be useful,
5724+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
5725+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5726+ * Lesser General Public License for more details.
5727+ *
5728+ * You should have received a copy of the GNU Lesser General Public
5729+ * License along with FFmpeg; if not, write to the Free Software
5730+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
5731+ */
5732+
5733+#include "avformat.h"
5734+#include "internal.h"
5735+#include "mpegts-mythtv.h"
5736+
5737+#ifdef _WIN32
5738+#define gmtime_r(X, Y) (memcpy(Y, gmtime(X), sizeof(struct tm)), Y)
5739+#define localtime_r(X, Y) (memcpy(Y, localtime(X), sizeof(struct tm)), Y)
5740+#endif
5741+
5742+
5743+/**
5744+ * @brief Add a stream to an MPEG media stream.
5745+ *
5746+ * This is used by mpegts instead of av_new_stream, so we can
5747+ * track new streams as indicated by the PMT.
5748+ *
5749+ * @param s MPEG media stream handle
5750+ * @param st new media stream
5751+ * @param id file format dependent stream id
5752+ */
5753+AVStream *av_add_stream(AVFormatContext *s, AVStream *st, int id)
5754+{
5755+ int i;
5756+
5757+ if (!st)
5758+ {
5759+ av_log(s, AV_LOG_ERROR, "av_add_stream: Error, AVStream is NULL");
5760+ return NULL;
5761+ }
5762+
5763+ av_remove_stream(s, id, 0);
5764+
5765+ if (s->nb_streams >= MAX_STREAMS)
5766+ {
5767+ av_log(s, AV_LOG_ERROR, "av_add_stream: Error, (s->nb_streams >= MAX_STREAMS)");
5768+ return NULL;
5769+ }
5770+
5771+ if (s->iformat) {
5772+ /* no default bitrate if decoding */
5773+ st->codec->bit_rate = 0;
5774+ }
5775+ st->index = s->nb_streams;
5776+ st->id = id;
5777+ st->start_time = AV_NOPTS_VALUE;
5778+ st->duration = AV_NOPTS_VALUE;
5779+ st->cur_dts = AV_NOPTS_VALUE;
5780+ st->first_dts = AV_NOPTS_VALUE;
5781+
5782+ /* default pts settings is MPEG like */
5783+ av_set_pts_info(st, 33, 1, 90000);
5784+ st->last_IP_pts = AV_NOPTS_VALUE;
5785+ for(i=0; i<MAX_REORDER_DELAY+1; i++)
5786+ st->internal->pts_buffer[i]= AV_NOPTS_VALUE;
5787+
5788+ s->streams[s->nb_streams++] = st;
5789+ return st;
5790+}
5791+
5792+
5793+/**
5794+ * @brief Remove a stream from a media stream.
5795+ *
5796+ * This is used by mpegts, so we can track streams as indicated by the PMT.
5797+ *
5798+ * @param s MPEG media stream handle
5799+ * @param id stream id of stream to remove
5800+ * @param remove_ts if true, remove any matching MPEG-TS filter as well
5801+ */
5802+void av_remove_stream(AVFormatContext *s, int id, int remove_ts) {
5803+ int i;
5804+ int changes = 0;
5805+
5806+ for (i=0; i<s->nb_streams; i++) {
5807+ if (s->streams[i]->id != id)
5808+ continue;
5809+
5810+ av_log(NULL, AV_LOG_DEBUG, "av_remove_stream 0x%x\n", id);
5811+
5812+ /* close codec context */
5813+ AVCodecContext *codec_ctx = s->streams[i]->codec;
5814+ if (codec_ctx->codec) {
5815+ avcodec_close(codec_ctx);
5816+ av_free(codec_ctx);
5817+ }
5818+#if 0
5819+ /* make sure format context is not using the codec context */
5820+ if (&s->streams[i] == s->cur_st) {
5821+ av_log(NULL, AV_LOG_DEBUG, "av_remove_stream cur_st = NULL\n");
5822+ s->cur_st = NULL;
5823+ }
5824+#endif
5825+ /* else if (s->cur_st > &s->streams[i]) {
5826+ av_log(NULL, AV_LOG_DEBUG, "av_remove_stream cur_st -= 1\n");
5827+ s->cur_st -= sizeof(AVFormatContext *);
5828+ } */
5829+ else {
5830+ av_log(NULL, AV_LOG_DEBUG,
5831+ "av_remove_stream: no change to cur_st\n");
5832+ }
5833+
5834+ av_log(NULL, AV_LOG_DEBUG, "av_remove_stream: removing... "
5835+ "s->nb_streams=%d i=%d\n", s->nb_streams, i);
5836+ /* actually remove av stream */
5837+ s->nb_streams--;
5838+ if ((s->nb_streams - i) > 0) {
5839+ memmove(&s->streams[i], &s->streams[i+1],
5840+ (s->nb_streams-i)*sizeof(AVFormatContext *));
5841+ }
5842+ else
5843+ s->streams[i] = NULL;
5844+
5845+ /* remove ts filter if remove ts is true and
5846+ * the format decoder is the "mpegts" decoder
5847+ */
5848+ if (remove_ts && s->iformat && s->priv_data &&
5849+ (0 == strncmp(s->iformat->name, "mpegts", 6))) {
5850+ av_log(NULL, AV_LOG_DEBUG,
5851+ "av_remove_stream: mpegts_remove_stream\n");
5852+ MpegTSContext *context = (MpegTSContext*) s->priv_data;
5853+ mpegts_remove_stream(context, id);
5854+ }
5855+ changes = 1;
5856+ }
5857+ if (changes)
5858+ {
5859+ // flush queued packets after a stream change (might need to make smarter)
5860+ flush_packet_queue(s);
5861+
5862+ /* renumber the streams */
5863+ av_log(NULL, AV_LOG_DEBUG, "av_remove_stream: renumbering streams\n");
5864+ for (i=0; i<s->nb_streams; i++)
5865+ s->streams[i]->index=i;
5866+ }
5867+}
5868+
5869+void av_estimate_timings(AVFormatContext *ic, int64_t old_offset)
5870+{
5871+ return estimate_timings(ic, old_offset);
5872+}
5873diff --git a/libavformat/utils.c b/libavformat/utils.c
5874index 75e5350a27..d819bb7c57 100644
5875--- a/libavformat/utils.c
5876+++ b/libavformat/utils.c
5877@@ -54,6 +54,15 @@ const char av_format_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
5878
5879 static AVMutex avformat_mutex = AV_MUTEX_INITIALIZER;
5880
5881+/* MYTHTV CHANGES */
5882+extern AVInputFormat ff_mythtv_mpegts_demuxer;
5883+extern AVInputFormat ff_mythtv_mpegtsraw_demuxer;
5884+extern AVInputFormat ff_mpegts_demuxer;
5885+extern AVInputFormat ff_mpegtsraw_demuxer;
5886+
5887+/* END MYTHTV CHANGES */
5888+
5889+
5890 /**
5891 * @file
5892 * various utility functions for use within FFmpeg
5893@@ -581,6 +590,7 @@ FF_ENABLE_DEPRECATION_WARNINGS
5894 }
5895 }
5896
5897+ s->build_index = 1;
5898 s->duration = s->start_time = AV_NOPTS_VALUE;
5899
5900 /* Allocate private data. */
5901@@ -883,6 +893,9 @@ FF_ENABLE_DEPRECATION_WARNINGS
5902 "Invalid stream index.\n");
5903
5904 st = s->streams[pkt->stream_index];
5905+
5906+ if (!st)
5907+ return -1;
5908
5909 if (update_wrap_reference(s, st, pkt->stream_index, pkt) && st->internal->pts_wrap_behavior == AV_PTS_WRAP_SUB_OFFSET) {
5910 // correct first time stamps to negative values
5911@@ -956,6 +969,10 @@ FF_ENABLE_DEPRECATION_WARNINGS
5912
5913 *pnum = 0;
5914 *pden = 0;
5915+
5916+ if (!st || !st->codecpar)
5917+ return;
5918+
5919 switch (st->codecpar->codec_type) {
5920 case AVMEDIA_TYPE_VIDEO:
5921 if (st->r_frame_rate.num && !pc && s->iformat) {
5922@@ -1122,6 +1139,9 @@ static void update_initial_timestamps(AVFormatContext *s, int stream_index,
5923
5924 uint64_t shift;
5925
5926+ if (!st)
5927+ return;
5928+
5929 if (st->first_dts != AV_NOPTS_VALUE ||
5930 dts == AV_NOPTS_VALUE ||
5931 st->cur_dts == AV_NOPTS_VALUE ||
5932@@ -1186,6 +1206,7 @@ static void update_initial_durations(AVFormatContext *s, AVStream *st,
5933 cur_dts -= duration;
5934 }
5935 }
5936+#if 0 // Very verbose: ffmpeg ticket 1344
5937 if (pktl && pktl->pkt.dts != st->first_dts) {
5938 av_log(s, AV_LOG_DEBUG, "first_dts %s not matching first dts %s (pts %s, duration %"PRId64") in the queue\n",
5939 av_ts2str(st->first_dts), av_ts2str(pktl->pkt.dts), av_ts2str(pktl->pkt.pts), pktl->pkt.duration);
5940@@ -1195,6 +1216,7 @@ static void update_initial_durations(AVFormatContext *s, AVStream *st,
5941 av_log(s, AV_LOG_DEBUG, "first_dts %s but no packet with dts in the queue\n", av_ts2str(st->first_dts));
5942 return;
5943 }
5944+#endif
5945 pktl = s->internal->packet_buffer ? s->internal->packet_buffer : s->internal->parse_queue;
5946 st->first_dts = cur_dts;
5947 } else if (st->cur_dts != RELATIVE_TS_BASE)
5948@@ -1536,6 +1558,11 @@ static int64_t ts_to_samples(AVStream *st, int64_t ts)
5949 return av_rescale(ts, st->time_base.num * st->codecpar->sample_rate, st->time_base.den);
5950 }
5951
5952+/**
5953+ * Simply sets data pointer to null.
5954+ *
5955+ * This will leak memory if no one else frees the memory used by the packet.
5956+ */
5957 static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
5958 {
5959 int ret, i, got_packet = 0;
5960@@ -1552,7 +1579,7 @@ static int read_frame_internal(AVFormatContext *s, AVPacket *pkt)
5961 /* flush the parsers */
5962 for (i = 0; i < s->nb_streams; i++) {
5963 st = s->streams[i];
5964- if (st->parser && st->need_parsing)
5965+ if (st && st->codec && st->parser && st->need_parsing)
5966 parse_packet(s, pkt, st->index, 1);
5967 }
5968 /* all remaining packets are now in parse_queue =>
5969@@ -1616,7 +1643,8 @@ FF_ENABLE_DEPRECATION_WARNINGS
5970 av_ts2str(pkt->dts),
5971 pkt->size, pkt->duration, pkt->flags);
5972
5973- if (st->need_parsing && !st->parser && !(s->flags & AVFMT_FLAG_NOPARSE)) {
5974+ if (st && st->codecpar && st->need_parsing && !st->parser &&
5975+ !(s->flags & AVFMT_FLAG_NOPARSE)) {
5976 st->parser = av_parser_init(st->codecpar->codec_id);
5977 if (!st->parser) {
5978 av_log(s, AV_LOG_VERBOSE, "parser not found for codec "
5979@@ -1635,6 +1663,7 @@ FF_ENABLE_DEPRECATION_WARNINGS
5980 if (!st->need_parsing || !st->parser) {
5981 /* no parsing needed: we just output the packet as is */
5982 compute_pkt_fields(s, st, NULL, pkt, AV_NOPTS_VALUE, AV_NOPTS_VALUE);
5983+ st->got_frame = 0;
5984 if ((s->iformat->flags & AVFMT_GENERIC_INDEX) &&
5985 (pkt->flags & AV_PKT_FLAG_KEY) && pkt->dts != AV_NOPTS_VALUE) {
5986 ff_reduce_index(s, st->index);
5987@@ -1837,7 +1866,7 @@ return_packet:
5988 }
5989
5990 /* XXX: suppress the packet queue */
5991-static void flush_packet_queue(AVFormatContext *s)
5992+void flush_packet_queue(AVFormatContext *s)
5993 {
5994 if (!s->internal)
5995 return;
5996@@ -1851,6 +1880,9 @@ static void flush_packet_queue(AVFormatContext *s)
5997 /*******************************************************/
5998 /* seek support */
5999
6000+/**
6001+ * @brief Finds the index of the first video stream within the AVFormatContext.
6002+ */
6003 int av_find_default_stream_index(AVFormatContext *s)
6004 {
6005 int i;
6006@@ -1904,6 +1936,7 @@ void ff_read_frame_flush(AVFormatContext *s)
6007 av_parser_close(st->parser);
6008 st->parser = NULL;
6009 }
6010+ st->got_frame = 0;
6011 st->last_IP_pts = AV_NOPTS_VALUE;
6012 st->internal->last_dts_for_order_check = AV_NOPTS_VALUE;
6013 if (st->first_dts == AV_NOPTS_VALUE)
6014@@ -2765,10 +2798,15 @@ static void estimate_timings_from_bit_rate(AVFormatContext *ic)
6015 "Estimating duration from bitrate, this may be inaccurate\n");
6016 }
6017
6018+/** Maximum number of bytes we read to determine timing from PTS stream. */
6019 #define DURATION_MAX_READ_SIZE 250000LL
6020 #define DURATION_MAX_RETRY 6
6021
6022-/* only usable for MPEG-PS streams */
6023+/**
6024+ * @brief Estimates timings using PTS stream.
6025+ *
6026+ * only usable for MPEG-PS streams
6027+ */
6028 static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
6029 {
6030 AVPacket *pkt = ic->internal->pkt;
6031@@ -2823,6 +2861,13 @@ static void estimate_timings_from_pts(AVFormatContext *ic, int64_t old_offset)
6032 if (ret != 0)
6033 break;
6034 read_size += pkt->size;
6035+
6036+ if (pkt->stream_index >= ic->nb_streams)
6037+ {
6038+ av_free_packet(pkt);
6039+ continue;
6040+ }
6041+
6042 st = ic->streams[pkt->stream_index];
6043 if (pkt->pts != AV_NOPTS_VALUE &&
6044 (st->start_time != AV_NOPTS_VALUE ||
6045@@ -2913,7 +2958,7 @@ static const char *duration_estimate_name(enum AVDurationEstimationMethod method
6046 return duration_name[method];
6047 }
6048
6049-static void estimate_timings(AVFormatContext *ic, int64_t old_offset)
6050+void estimate_timings(AVFormatContext *ic, int64_t old_offset)
6051 {
6052 int64_t file_size;
6053
6054@@ -3584,6 +3629,12 @@ static int extract_extradata(AVStream *st, const AVPacket *pkt)
6055 return 0;
6056 }
6057
6058+/* absolute maximum size we read until we abort (MythTV) */
6059+#define MAX_READ_SIZE 5000000
6060+
6061+/** Number of frames to read, max. (MythTV) */
6062+#define MAX_FRAMES 45
6063+
6064 static int add_coded_side_data(AVStream *st, AVCodecContext *avctx)
6065 {
6066 int i;
6067@@ -3633,6 +3684,10 @@ int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
6068 max_stream_analyze_duration = 7*AV_TIME_BASE;
6069 }
6070
6071+ int hasaudio = 0;
6072+ int hasvideo = 0;
6073+ int read_packets = 0;
6074+
6075 if (ic->pb)
6076 av_log(ic, AV_LOG_DEBUG, "Before avformat_find_stream_info() pos: %"PRId64" bytes read:%"PRId64" seeks:%d nb_streams:%d\n",
6077 avio_tell(ic->pb), ic->pb->bytes_read, ic->pb->seek_count, ic->nb_streams);
6078@@ -3719,11 +3774,15 @@ FF_ENABLE_DEPRECATION_WARNINGS
6079 }
6080
6081 for (i = 0; i < ic->nb_streams; i++) {
6082+ // MythTV change here
6083+ if (ic->streams[i]->internal->info )
6084+ {
6085 #if FF_API_R_FRAME_RATE
6086 ic->streams[i]->internal->info->last_dts = AV_NOPTS_VALUE;
6087 #endif
6088 ic->streams[i]->internal->info->fps_first_dts = AV_NOPTS_VALUE;
6089 ic->streams[i]->internal->info->fps_last_dts = AV_NOPTS_VALUE;
6090+ }
6091 }
6092
6093 read_size = 0;
6094@@ -3776,23 +3835,36 @@ FF_ENABLE_DEPRECATION_WARNINGS
6095 if (st->first_dts == AV_NOPTS_VALUE &&
6096 !(ic->iformat->flags & AVFMT_NOTIMESTAMPS) &&
6097 st->codec_info_nb_frames < ((st->disposition & AV_DISPOSITION_ATTACHED_PIC) ? 1 : ic->max_ts_probe) &&
6098- (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
6099- st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))
6100- break;
6101+ st->codecpar->codec_id != AV_CODEC_ID_DSMCC_B)
6102+ break;
6103+ if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
6104+ hasvideo = 1;
6105+ else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
6106+ hasaudio = 1;
6107 }
6108 analyzed_all_streams = 0;
6109 if (!missing_streams || !*missing_streams)
6110 if (i == ic->nb_streams) {
6111 analyzed_all_streams = 1;
6112 /* NOTE: If the format has no header, then we need to read some
6113- * packets to get most of the streams, so we cannot stop here. */
6114- if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
6115+ * packets to get most of the streams, so we cannot stop here. */
6116+ /* There are MythTV changes here */
6117+ if (!(ic->ctx_flags & AVFMTCTX_NOHEADER) ||
6118+ (read_size >= MAX_READ_SIZE || read_packets >= MAX_FRAMES) ||
6119+ (hasvideo && hasaudio)) {
6120 /* If we found the info for all the codecs, we can stop. */
6121 ret = count;
6122 av_log(ic, AV_LOG_DEBUG, "All info found\n");
6123 flush_codecs = 0;
6124 break;
6125 }
6126+ /* Is this is an MHEG only stream? Then we really can stop. */
6127+ if (i == 1 && ic->streams[0]->codecpar->codec_id == AV_CODEC_ID_DSMCC_B)
6128+ {
6129+ ret = count;
6130+ av_log(ic, AV_LOG_DEBUG, "All DSM info found\n");
6131+ break;
6132+ }
6133 }
6134 /* We did not get all the codec info, but we read too much data. */
6135 if (read_size >= probesize) {
6136@@ -3813,6 +3885,9 @@ FF_ENABLE_DEPRECATION_WARNINGS
6137 /* NOTE: A new stream can be added there if no header in file
6138 * (AVFMTCTX_NOHEADER). */
6139 ret = read_frame_internal(ic, pkt1);
6140+
6141+ read_packets++;
6142+
6143 if (ret == AVERROR(EAGAIN))
6144 continue;
6145
6146diff --git a/libavformat/wtvdec.c b/libavformat/wtvdec.c
6147index 1d5ba03bef..7cfc4a381a 100644
6148--- a/libavformat/wtvdec.c
6149+++ b/libavformat/wtvdec.c
6150@@ -864,7 +864,7 @@ static int parse_chunks(AVFormatContext *s, int mode, int64_t seekts, int *len_p
6151 buf_size = FFMIN(len - consumed, sizeof(buf));
6152 avio_read(pb, buf, buf_size);
6153 consumed += buf_size;
6154- ff_parse_mpeg2_descriptor(s, st, 0, &pbuf, buf + buf_size, NULL, 0, 0, NULL);
6155+ ff_old_parse_mpeg2_descriptor(s, st, 0, &pbuf, buf + buf_size, NULL, 0, 0, NULL);
6156 }
6157 } else if (!ff_guidcmp(g, EVENTID_AudioTypeSpanningEvent)) {
6158 int stream_index = ff_find_stream_index(s, sid);
6159diff --git a/libavutil/frame.c b/libavutil/frame.c
6160index 75e347bf2f..958b0b7031 100644
6161--- a/libavutil/frame.c
6162+++ b/libavutil/frame.c
6163@@ -435,6 +435,13 @@ FF_DISABLE_DEPRECATION_WARNINGS
6164 FF_ENABLE_DEPRECATION_WARNINGS
6165 #endif
6166
6167+ /* MythTV ATSC Subtitle Support -- Begin */
6168+ dst->atsc_cc_len = src->atsc_cc_len;
6169+ dst->scte_cc_len = src->scte_cc_len;
6170+ memcpy(dst->atsc_cc_buf, src->atsc_cc_buf, src->atsc_cc_len);
6171+ memcpy(dst->scte_cc_buf, src->scte_cc_buf, src->scte_cc_len);
6172+ /* MythTV ATSC Subtitle Support -- End */
6173+
6174 ret = av_buffer_replace(&dst->opaque_ref, src->opaque_ref);
6175 ret |= av_buffer_replace(&dst->private_ref, src->private_ref);
6176 return ret;
6177diff --git a/libavutil/frame.h b/libavutil/frame.h
6178index 7d1f8e2935..d0e4ce2dee 100644
6179--- a/libavutil/frame.h
6180+++ b/libavutil/frame.h
6181@@ -623,6 +623,20 @@ typedef struct AVFrame {
6182 */
6183 int channels;
6184
6185+ /** ATSC CC data CEA-608/708
6186+ * - encoding: unused
6187+ * - decoding: Set by libavcodec
6188+ */
6189+ uint8_t atsc_cc_buf[1024];
6190+ int atsc_cc_len;
6191+
6192+ /** SCTE CC data CEA-608
6193+ * - encoding: unused
6194+ * - decoding: Set by libavcodec
6195+ */
6196+ uint8_t scte_cc_buf[1024];
6197+ int scte_cc_len;
6198+
6199 /**
6200 * size of the corresponding packet containing the compressed
6201 * frame.
6202diff --git a/libpostproc/Makefile b/libpostproc/Makefile
6203index 34317193a8..4aea9c03b0 100644
6204--- a/libpostproc/Makefile
6205+++ b/libpostproc/Makefile
6206@@ -2,6 +2,14 @@ NAME = postproc
6207 DESC = FFmpeg postprocessing library
6208 FFLIBS = avutil
6209
6210+# x86_32 needs -O1 -fomit-frame-pointer to compile inline asm
6211+ifeq ($(ARCH_X86_32), yes)
6212+ CFLAGS += -fomit-frame-pointer
6213+ ifneq (, $(findstring debug, $(CCONFIG)))
6214+ CFLAGS += -O1
6215+ endif
6216+endif
6217+
6218 HEADERS = postprocess.h \
6219 version.h \
6220
6221diff --git a/libpostproc/postprocess.c b/libpostproc/postprocess.c
6222index 8d44165dee..09029b97a3 100644
6223--- a/libpostproc/postprocess.c
6224+++ b/libpostproc/postprocess.c
6225@@ -91,6 +91,8 @@ try to unroll inner for(x=0 ... loop to avoid these damn if(x ... checks
6226 #include "libavutil/avstring.h"
6227 #include "libavutil/ppc/util_altivec.h"
6228
6229+#include "libavutil/cpu.h"
6230+
6231 #include "libavutil/ffversion.h"
6232 const char postproc_ffversion[] = "FFmpeg version " FFMPEG_VERSION;
6233
6234@@ -880,10 +882,26 @@ av_cold pp_context *pp_get_context(int width, int height, int cpuCaps){
6235 PPContext *c= av_mallocz(sizeof(PPContext));
6236 int stride= FFALIGN(width, 16); //assumed / will realloc if needed
6237 int qpStride= (width+15)/16 + 2; //assumed / will realloc if needed
6238+ int cpuflags;
6239
6240 if (!c)
6241 return NULL;
6242
6243+ if (CONFIG_RUNTIME_CPUDETECT &&
6244+ !(cpuCaps & (PP_CPU_CAPS_MMX | PP_CPU_CAPS_MMX2 |
6245+ PP_CPU_CAPS_3DNOW | PP_CPU_CAPS_ALTIVEC ))) {
6246+ cpuflags = av_get_cpu_flags();
6247+
6248+ if (HAVE_MMX && cpuflags & AV_CPU_FLAG_MMX)
6249+ cpuCaps |= PP_CPU_CAPS_MMX;
6250+ if (HAVE_MMX2 && cpuflags & AV_CPU_FLAG_MMX2)
6251+ cpuCaps |= PP_CPU_CAPS_MMX2;
6252+ if (HAVE_AMD3DNOW && cpuflags & AV_CPU_FLAG_3DNOW)
6253+ cpuCaps |= PP_CPU_CAPS_3DNOW;
6254+ if (HAVE_ALTIVEC && cpuflags & AV_CPU_FLAG_ALTIVEC)
6255+ cpuCaps |= PP_CPU_CAPS_ALTIVEC;
6256+ }
6257+
6258 c->av_class = &av_codec_context_class;
6259 if(cpuCaps&PP_FORMAT){
6260 c->hChromaSubSample= cpuCaps&0x3;
6261diff --git a/tools/clean-diff b/tools/clean-diff
6262index 4600702b10..d40f22f34f 100755
6263--- a/tools/clean-diff
6264+++ b/tools/clean-diff
6265@@ -4,8 +4,8 @@ sed '/^+[^+]/!s/ /TaBBaT/g' |\
6266 sed 's/TaBBaT/ /g' |\
6267 sed '/^+[^+]/s/ * $//' |\
6268 tr -d '\015' |\
6269- tr '\n' '°' |\
6270- sed 's/\(@@[^@]*@@°[^@]*\)/\n\1/g' |\
6271- egrep -v '@@[^@]*@@°(( [^°]*°)|([+-][[:space:]]*°)|(-[[:space:]]*([^°]*)°\+[[:space:]]*\5°))*$' |\
6272+ tr '\n' '°' |\
6273+ sed 's/\(@@[^@]*@@°[^@]*\)/\n\1/g' |\
6274+ egrep -v '@@[^@]*@@°(( [^°]*°)|([+-][[:space:]]*°)|(-[[:space:]]*([^°]*)°\+[[:space:]]*\5°))*$' |\
6275 tr -d '\n' |\
6276- tr '°' '\n'
6277+ tr '°' '\n'
6278