From patchwork Fri Dec 10 21:37:56 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Soft Works X-Patchwork-Id: 32281 Delivered-To: ffmpegpatchwork2@gmail.com Received: by 2002:a6b:cd86:0:0:0:0:0 with SMTP id d128csp2375157iog; Fri, 10 Dec 2021 13:40:39 -0800 (PST) X-Google-Smtp-Source: ABdhPJw9mTrJOUJbCjiYFmURvT4b5DM8lkmq6rJLNsl2K6epLd6HVB10/UDmCuK7nUQ0sS8V1FZ6 X-Received: by 2002:a05:6402:b82:: with SMTP id cf2mr42137895edb.40.1639172439061; Fri, 10 Dec 2021 13:40:39 -0800 (PST) Return-Path: Received: from ffbox0-bg.mplayerhq.hu (ffbox0-bg.ffmpeg.org. [79.124.17.100]) by mx.google.com with ESMTP id gc38si5227240ejc.493.2021.12.10.13.40.38; Fri, 10 Dec 2021 13:40:39 -0800 (PST) Received-SPF: pass (google.com: domain of ffmpeg-devel-bounces@ffmpeg.org designates 79.124.17.100 as permitted sender) client-ip=79.124.17.100; Authentication-Results: mx.google.com; dkim=neutral (body hash did not verify) header.i=@hotmail.com header.s=selector1 header.b=hYMaN1Zm; arc=fail (body hash mismatch); spf=pass (google.com: domain of ffmpeg-devel-bounces@ffmpeg.org designates 79.124.17.100 as permitted sender) smtp.mailfrom=ffmpeg-devel-bounces@ffmpeg.org; dmarc=fail (p=NONE sp=NONE dis=NONE) header.from=hotmail.com Received: from [127.0.1.1] (localhost [127.0.0.1]) by ffbox0-bg.mplayerhq.hu (Postfix) with ESMTP id 968AC68AFBE; Fri, 10 Dec 2021 23:38:06 +0200 (EET) X-Original-To: ffmpeg-devel@ffmpeg.org Delivered-To: ffmpeg-devel@ffmpeg.org Received: from NAM12-MW2-obe.outbound.protection.outlook.com (mail-mw2nam12olkn2073.outbound.protection.outlook.com [40.92.23.73]) by ffbox0-bg.mplayerhq.hu (Postfix) with ESMTPS id 5A12268AF10 for ; Fri, 10 Dec 2021 23:38:02 +0200 (EET) ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=dGXvtBMYxAU5zAt4hHI4qx69NCH44TDdO8wWSUiwXOj0HLZC9KZLaIyL7udylEXnUizE0MUuyiZlgS327EFwIKgrdYOf3xZmb9NTaxlMhImWG/dABLzDzrjK0sQhUvHgnfyQ6S1kecyMOE2GvearlDtsWnZEajB+E81rwRtd5DLAQG7Q9cKbwShyQaSKesDLaYyX/vwm3/QjwyXH5q276EvppI63vkGuGIPwLb/HJIhAc5/aArKdZC1lUM9PDJGqDR45nL1p+2n3ihBMPb82MFRAMG3kskrtRyAlOokeyI1os/879zUAi+jraRaGcAjXKhV+OEdU3cGUBagZHLeFcw== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector9901; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=RcmlA8jhol8Mnj8PGvLPrcUF0lNcYZcQJrG8IjDO8bU=; b=ZAZsEAvXPGFwL4zLm8XdDe/tXQ2D5Skc4cxQFcoG5gm2QwpKSFG3apbYEg5txh/02DI2BK0bPaINm8wr2VB7Eh6ghG7vSFPEpX7X/gUtWqK2SUc0A/zaHuVOj0o4KGlsTFNWATkVp5HEYpJ26gfrHO2HXh89RKhXewf6az1bnSlBsHI5fiVcJB6FPSC8t/cQf0VmCy8CnKrdNGKZLpaB4fgWq+UUMXM3Ejm52G1UqDpMeYdiX97Im4OnWRrfcYZA7Sn0N2bHuXe1PtRknjEHGts52uMTImJGcYs7xNqJ6++xk47dcNDoE2ascIXaucJMrunDzrmg0U5jgeZhqe4Nkw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=none; dmarc=none; dkim=none; arc=none DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=hotmail.com; s=selector1; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck; bh=RcmlA8jhol8Mnj8PGvLPrcUF0lNcYZcQJrG8IjDO8bU=; b=hYMaN1ZmbVDBOIham6d+Fgfw24oPDMKZT1KNnJ7GuGsyFFp/Iot4sO8EvkE83HuosRQQnOF6mUIYfiWt4hH2RGUA+9OmHVsHGTyH1LXBho8UKoS8DAjZkPk5rX/qaNHh6UQ1Vx/KybUE4c7bSV6BfIxQ4ilaLNgmgA8toTpWgz+EBQqCTD20Uz6IuE7e4Uf5b741qz+0PhGluG9lNOffxIuWB5CW/k4LyPqtRkb0pz+1NfUZNjvtcuPDT1Q8OCdJuMW+tzK46sMz/MoMnxAo7Ih7RHjpT0xNDcBICfUszL4ltAhkc5r39Ye1e8Vvgom6gSvn6kFdbunzu9l6Z2BxqQ== Received: from DM8P223MB0365.NAMP223.PROD.OUTLOOK.COM (2603:10b6:8:b::20) by DM8P223MB0191.NAMP223.PROD.OUTLOOK.COM (2603:10b6:8:8::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.4755.20; Fri, 10 Dec 2021 21:37:56 +0000 Received: from DM8P223MB0365.NAMP223.PROD.OUTLOOK.COM ([fe80::9c8d:fc63:9488:9775]) by DM8P223MB0365.NAMP223.PROD.OUTLOOK.COM ([fe80::9c8d:fc63:9488:9775%7]) with mapi id 15.20.4778.015; Fri, 10 Dec 2021 21:37:56 +0000 From: Soft Works To: "ffmpeg-devel@ffmpeg.org" Thread-Topic: [PATCH v23 18/21] avfilter/splitcc: Add splitcc filter for closed caption handling Thread-Index: AQHX7g4xgqym92w7vEyeVTNKuDNASQ== Date: Fri, 10 Dec 2021 21:37:56 +0000 Message-ID: References: <84c6ba3b99bf387e818d59f2161009ead8fb5767.1639172095.git.softworkz@hotmail.com> <0b41271ed30b530c1d55a9b824fc8bbbbd14fe5e.1639172095.git.softworkz@hotmail.com> <9f2875d043147119351f59b6410d718d170574e1.1639172095.git.softworkz@hotmail.com> <62a926e2d86310039653324bdf2a856f09a0fb46.1639172095.git.softworkz@hotmail.com> <75bb9ceffef9e8e2d05ffce8a51c1991d5d3a973.1639172095.git.softworkz@hotmail.com> <554aab35996d92c90ab3b0ecb2c0c6c1278479d6.1639172095.git.softworkz@hotmail.com> <65992926f9356948d7f937ab852f8320b3da4bd9.1639172095.git.softworkz@hotmail.com> <4446daddbc3631c50d69005b790a24e60797a357.1639172095.git.softworkz@hotmail.com> In-Reply-To: Accept-Language: en-US Content-Language: en-US X-MS-Has-Attach: X-MS-TNEF-Correlator: x-ms-exchange-messagesentrepresentingtype: 1 x-tmn: [K7UdszdGxUSjbvt9yjIUaTWWJW75xuaz] x-ms-publictraffictype: Email x-ms-office365-filtering-correlation-id: f513017e-2072-4d6c-1b96-08d9bc255449 x-ms-traffictypediagnostic: DM8P223MB0191:EE_ x-microsoft-antispam: BCL:0; x-microsoft-antispam-message-info: ElAmqZaCGgMbRlgXqJX2EwfI0r0m5Y5xDrB4wrX2pQpCBS2ich/lG4hDGVDamOlQQIv3jhtA3HsC2rg+elB8mRsJ1Z7olWwRE6YVVFCSscg2ZcP9coYud1xW2D6C4TtMGtPzU7uOBzS92PERp3y6Utag3hZQDw4X6s3JdjWX4/FiyzLtVUQIurX9PchqvSK/GJSuQx+d7s3dlXcSz7XAVB1QgF1HisoaZ4fmB+tmxdS89DMcXzqv41CzCWvn59CeHRJp+w3LruuhHMv4xdgb2xykG/dbn4h0FsvSAadMZiW0qMaDSIpdQ7I7l6AzlOpnKaLG1TlloNOPx0nvT1J3PPjZSRpI7cPArm2mLEnQBmOsCRQgG0i5GPFShi9/CTXyAncgYShqtN6hjf9MkJ3CyIRmX8ZyR0SGYEjkgQtkRJMehS2OYVlL+4qVQc2N6qhB5gHwlNoqCcuqeC4BIYrrTUm3ylnxJEgG4D0J+lFbfULVOc5Z0qDptrkyLT842sjIZleLKjA4ANghvFZHUbS2PwRJHPN7+4QF+wgOwctvyHwGIPIGVq1cXFmTdJYWHgmeA9kQ9cSaODNfzs0NLuDS0Mutr/p6n4eLN5MjA5hIQSEdq0Oato2TUfDee81c7CGO x-ms-exchange-antispam-messagedata-chunkcount: 1 x-ms-exchange-antispam-messagedata-0: =?utf-8?q?+vpAkMlUeS2dFDxLS1ZyBX8ykebd?= =?utf-8?q?VsULesVNXquz54MM9mEEva4VtMd3MomCbxGTdJCQlnF6u1pBaxgC9A2j2j1jOqCVx?= =?utf-8?q?jkvmKgKW7z+MGCEIgPQ6BBYM4hNyapWmJNbRLueBws4oCZH78aBxCPYEXa11Phl/c?= =?utf-8?q?ZlwyQ9uTCMu57eP177CyEu5LwtnMUfzT1jADGQc7v0Dga1Rh9R8/BMhKMa/MSPEto?= =?utf-8?q?WKLlIHt4FbWmS5Lg7inM0rshbqUhmwVznPKElyUwx0w/5picMTyelwZDxRvY9M8so?= =?utf-8?q?JdHjAAOL8nBNMlJ1ERYjEiQ5ZJPTHbNVs//bS7PCvseLloB9XM2uUOdH5M0V3BrDC?= =?utf-8?q?f1iMu2ghxEwT2PG6phjTXoV/hTkmKhZ5TfFgrxQm94V1qz48TOG9M7Ffe460ezULL?= =?utf-8?q?dNCEqQVYSYAKP/bImHO2Y1tfw+Jfq6pLmEa3C+PEB+dWAgcMSQLbCnZLbqu8RHLIG?= =?utf-8?q?s6oOZcSxlgLZQTO1bw7yTica4e1tkWfidvownakxMUULpDEbHvv3goVTf2KdcdjXY?= =?utf-8?q?LnrvXj15LZ/9mQh/rBzAmFc1T1pbqi+5zn77dm55EPaff1YBfUYQFZ635o0SNaFln?= =?utf-8?q?DVVdA0w+Q/mgMv5ai78WXRhxCMIpuCNUQ2BndD1mNpxtoMzclt4CRrTLYfuxAHDZ8?= =?utf-8?q?7uK6/0kYvRtMHHFwd4bsxNGysTx2/1kqFXp9ORKWW5nTukoDOjOLIO6zxu0mn1FY8?= =?utf-8?q?hWdPga5ZuF8N4rZav76LWG70dRjLWcbTXeOlZkjshyimHmwSuJjyTNv7TQye7vBkD?= =?utf-8?q?+/Tc3wSXt4oI9+S8/iRw8r0h+qphHs8eksciBk/Ca0x90T3ww5jnkHPeukA5Ikj/P?= =?utf-8?q?a59GTLtRvMhOqtq0kaYA1Oe2lbSKYVYUJxW1IFpD5t4YNnxMLiXFTGqxiXQOJ73nB?= =?utf-8?q?a96q6W2psQwG4jFGRBJKMt8XvQXUU/0VBuOH/WvTWY2A=3D=3D?= MIME-Version: 1.0 X-OriginatorOrg: sct-15-20-4755-11-msonline-outlook-1ff67.templateTenant X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-AuthSource: DM8P223MB0365.NAMP223.PROD.OUTLOOK.COM X-MS-Exchange-CrossTenant-RMS-PersistedConsumerOrg: 00000000-0000-0000-0000-000000000000 X-MS-Exchange-CrossTenant-Network-Message-Id: f513017e-2072-4d6c-1b96-08d9bc255449 X-MS-Exchange-CrossTenant-originalarrivaltime: 10 Dec 2021 21:37:56.2838 (UTC) X-MS-Exchange-CrossTenant-fromentityheader: Hosted X-MS-Exchange-CrossTenant-id: 84df9e7f-e9f6-40af-b435-aaaaaaaaaaaa X-MS-Exchange-CrossTenant-rms-persistedconsumerorg: 00000000-0000-0000-0000-000000000000 X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM8P223MB0191 Subject: [FFmpeg-devel] [PATCH v23 18/21] avfilter/splitcc: Add splitcc filter for closed caption handling X-BeenThere: ffmpeg-devel@ffmpeg.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: FFmpeg development discussions and patches List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Reply-To: FFmpeg development discussions and patches Errors-To: ffmpeg-devel-bounces@ffmpeg.org Sender: "ffmpeg-devel" X-TUID: 1SOT5C7wrR6s - splitcc {V -> VS) Extract closed-caption (A53) data from video frames as subtitle Frames ffmpeg -y -loglevel verbose -i "https://streams.videolan.org/streams/ts/CC/NewsStream-608-ac3.ts" -filter_complex "[0:v]splitcc[vid1],textmod=mode=remove_chars:find='@',[vid1]overlay_textsubs" output.mkv Signed-off-by: softworkz --- configure | 1 + doc/filters.texi | 63 +++++++ libavfilter/Makefile | 1 + libavfilter/allfilters.c | 1 + libavfilter/sf_splitcc.c | 378 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 444 insertions(+) create mode 100644 libavfilter/sf_splitcc.c diff --git a/configure b/configure index 16ab6b46c3..73a7267cf1 100755 --- a/configure +++ b/configure @@ -3704,6 +3704,7 @@ spp_filter_select="fft idctdsp fdctdsp me_cmp pixblockdsp" sr_filter_deps="avformat swscale" sr_filter_select="dnn" stereo3d_filter_deps="gpl" +splitcc_filter_deps="avcodec" subtitles_filter_deps="avformat avcodec libass" super2xsai_filter_deps="gpl" pixfmts_super2xsai_test_deps="super2xsai_filter" diff --git a/doc/filters.texi b/doc/filters.texi index 241c5d469b..743c36c432 100644 --- a/doc/filters.texi +++ b/doc/filters.texi @@ -26054,6 +26054,69 @@ ffmpeg -i INPUT -filter_complex "showspeaker=format=colon:style='@{\\c&HDD0000&\ @end example @end itemize + +@section splitcc + +Split-out closed-caption/A53 subtitles from video frame side data. + +This filter provides an input and an output for video frames, which are just passed through without modification. +The second out provides subtitle frames which are extracted from video frame side data. + +Inputs: +@itemize +@item 0: Video [ALL] +@end itemize + +Outputs: +@itemize +@item 0: Video (same as input) +@item 1: Subtitles [TEXT] +@end itemize + +It accepts the following parameters: + +@table @option + +@item use_cc_styles +Emit closed caption style header. +This will make closed captions appear in white font with a black rectangle background. + +@item real_time +Emit subtitle events as they are decoded for real-time display. + +@item real_time_latency_msec +Minimum elapsed time between emitting real-time subtitle events. +Only applies to real_time mode. + +@item data_field +Select data field. Possible values: + +@table @samp +@item auto +Pick first one that appears. +@item first +@item second +@end table + +@end table + +@subsection Examples + +@itemize +@item +Extract closed captions as text subtitle stream and overlay it onto the video in cc style (black bar background): +@example +ffmpeg -i "https://streams.videolan.org/streams/ts/CC/NewsStream-608-ac3.ts" -filter_complex "[0:v:0]splitcc=use_cc_styles=1[vid1][sub1];[vid1][sub1]overlaytextsubs" output.mkv +@end example + +@item +A nicer variant, using realtime output from cc_dec and rendering it with the render_latest_only parameter from overlaytextsubs to avoid ghosting by timely overlap. +@example +ffmpeg -i "https://streams.videolan.org/streams/ts/CC/NewsStream-608-ac3.ts" -filter_complex "[0:v:0]splitcc=real_time=1:real_time_latency_msec=200[vid1][sub1];[vid1][sub1]overlaytextsubs=render_latest_only=1" output.mkv +@end example +@end itemize + + @section textsub2video Converts text subtitles to video frames. diff --git a/libavfilter/Makefile b/libavfilter/Makefile index 7d7da0c59a..2224e5fe5f 100644 --- a/libavfilter/Makefile +++ b/libavfilter/Makefile @@ -557,6 +557,7 @@ OBJS-$(CONFIG_NULLSINK_FILTER) += vsink_nullsink.o OBJS-$(CONFIG_CENSOR_FILTER) += sf_textmod.o OBJS-$(CONFIG_SHOW_SPEAKER_FILTER) += sf_textmod.o OBJS-$(CONFIG_TEXTMOD_FILTER) += sf_textmod.o +OBJS-$(CONFIG_SPLITCC_FILTER) += sf_splitcc.o OBJS-$(CONFIG_STRIPSTYLES_FILTER) += sf_stripstyles.o # multimedia filters diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c index 27680a2f00..6adde2b9f6 100644 --- a/libavfilter/allfilters.c +++ b/libavfilter/allfilters.c @@ -546,6 +546,7 @@ extern const AVFilter ff_avf_showwavespic; extern const AVFilter ff_vaf_spectrumsynth; extern const AVFilter ff_sf_censor; extern const AVFilter ff_sf_showspeaker; +extern const AVFilter ff_sf_splitcc; extern const AVFilter ff_sf_stripstyles; extern const AVFilter ff_sf_textmod; extern const AVFilter ff_svf_graphicsub2video; diff --git a/libavfilter/sf_splitcc.c b/libavfilter/sf_splitcc.c new file mode 100644 index 0000000000..3556d084d9 --- /dev/null +++ b/libavfilter/sf_splitcc.c @@ -0,0 +1,378 @@ +/* + * Copyright (c) 2021 softworkz + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * subtitle filter for splitting out closed-caption/A53 subtitles from video frame side data + */ + +#include "filters.h" +#include "libavutil/opt.h" +#include "subtitles.h" +#include "libavcodec/avcodec.h" + +static const AVRational ms_tb = {1, 1000}; + +typedef struct SplitCaptionsContext { + const AVClass *class; + enum AVSubtitleType format; + AVCodecContext *cc_dec; + int eof; + AVFrame *next_sub_frame; + AVFrame *empty_sub_frame; + int new_frame; + int64_t next_repetition_pts; + AVBufferRef *subtitle_header; + int use_cc_styles; + int real_time; + int real_time_latency_msec; + int data_field; + int scatter_realtime_output; +} SplitCaptionsContext; + +static int init(AVFilterContext *ctx) +{ + SplitCaptionsContext *s = ctx->priv; + AVDictionary *options = NULL; + + int ret; + const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_EIA_608); + if (!codec) { + av_log(ctx, AV_LOG_ERROR, "failed to find EIA-608/708 decoder\n"); + return AVERROR_DECODER_NOT_FOUND; + } + + if (!((s->cc_dec = avcodec_alloc_context3(codec)))) { + av_log(ctx, AV_LOG_ERROR, "failed to allocate EIA-608/708 decoder\n"); + return AVERROR(ENOMEM); + } + + av_dict_set_int(&options, "real_time", s->real_time, 0); + av_dict_set_int(&options, "real_time_latency_msec", s->real_time_latency_msec, 0); + av_dict_set_int(&options, "data_field", s->data_field, 0); + + if ((ret = avcodec_open2(s->cc_dec, codec, &options)) < 0) { + av_log(ctx, AV_LOG_ERROR, "failed to open EIA-608/708 decoder: %i\n", ret); + return ret; + } + + if (s->use_cc_styles && s->cc_dec->subtitle_header && s->cc_dec->subtitle_header[0] != 0) { + char* subtitle_header = av_strdup((char *)s->cc_dec->subtitle_header); + if (!subtitle_header) + return AVERROR(ENOMEM); + s->subtitle_header = av_buffer_create((uint8_t *)subtitle_header, strlen(subtitle_header) + 1, NULL, NULL, 0); + if (!s->subtitle_header) { + av_free(subtitle_header); + return AVERROR(ENOMEM); + } + } + + return 0; +} + +static void uninit(AVFilterContext *ctx) +{ + SplitCaptionsContext *s = ctx->priv; + av_frame_free(&s->next_sub_frame); + av_frame_free(&s->empty_sub_frame); + av_buffer_unref(&s->subtitle_header); +} + +static int config_input(AVFilterLink *link) +{ + const SplitCaptionsContext *context = link->dst->priv; + + if (context->cc_dec) + context->cc_dec->pkt_timebase = link->time_base; + + return 0; +} + +static int query_formats(AVFilterContext *ctx) +{ + AVFilterFormats *formats; + AVFilterLink *inlink0 = ctx->inputs[0]; + AVFilterLink *outlink0 = ctx->outputs[0]; + AVFilterLink *outlink1 = ctx->outputs[1]; + static const enum AVSubtitleType subtitle_fmts[] = { AV_SUBTITLE_FMT_ASS, AV_SUBTITLE_FMT_NB }; + int ret; + + /* set input0 video formats */ + formats = ff_all_formats(AVMEDIA_TYPE_VIDEO); + if ((ret = ff_formats_ref(formats, &inlink0->outcfg.formats)) < 0) + return ret; + + /* set output0 video formats */ + if ((ret = ff_formats_ref(formats, &outlink0->incfg.formats)) < 0) + return ret; + + /* set output1 subtitle formats */ + formats = ff_make_format_list(subtitle_fmts); + if ((ret = ff_formats_ref(formats, &outlink1->incfg.formats)) < 0) + return ret; + + return 0; +} + +static int config_video_output(AVFilterLink *outlink) +{ + AVFilterContext *ctx = outlink->src; + const AVFilterLink *inlink = outlink->src->inputs[0]; + + outlink->w = ctx->inputs[0]->w; + outlink->h = ctx->inputs[0]->h; + outlink->frame_rate = ctx->inputs[0]->frame_rate; + outlink->time_base = ctx->inputs[0]->time_base; + outlink->sample_aspect_ratio = ctx->inputs[0]->sample_aspect_ratio; + + if (inlink->hw_frames_ctx) + outlink->hw_frames_ctx = av_buffer_ref(inlink->hw_frames_ctx); + + return 0; +} + +static int config_sub_output(AVFilterLink *outlink) +{ + const AVFilterLink *inlink = outlink->src->inputs[0]; + + outlink->time_base = inlink->time_base; + outlink->format = AV_SUBTITLE_FMT_ASS; + outlink->frame_rate = (AVRational){5, 1}; + + return 0; +} + +static int request_sub_frame(AVFilterLink *outlink) +{ + SplitCaptionsContext *s = outlink->src->priv; + int status; + int64_t pts; + + if (!s->empty_sub_frame) { + s->empty_sub_frame = ff_get_subtitles_buffer(outlink, outlink->format); + if (!s->empty_sub_frame) + return AVERROR(ENOMEM); + } + + if (!s->eof && ff_inlink_acknowledge_status(outlink->src->inputs[0], &status, &pts)) { + if (status == AVERROR_EOF) + s->eof = 1; + } + + if (s->eof) + return AVERROR_EOF; + + if (s->next_sub_frame) { + + AVFrame *out = NULL; + s->next_sub_frame->pts++; + + if (s->new_frame) + out = av_frame_clone(s->next_sub_frame); + else if (s->empty_sub_frame) { + s->empty_sub_frame->pts = s->next_sub_frame->pts; + out = av_frame_clone(s->empty_sub_frame); + av_frame_copy_props(out, s->next_sub_frame); + } + + if (!out) + return AVERROR(ENOMEM); + + out->subtitle_pts = av_rescale_q(s->next_sub_frame->pts, outlink->time_base, AV_TIME_BASE_Q); + s->new_frame = 0; + + return ff_filter_frame(outlink, out); + } + + return 0; +} + +static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt) +{ + int ret; + + *got_frame = 0; + + if (pkt) { + ret = avcodec_send_packet(avctx, pkt); + // In particular, we don't expect AVERROR(EAGAIN), because we read all + // decoded frames with avcodec_receive_frame() until done. + if (ret < 0 && ret != AVERROR_EOF) + return ret; + } + + ret = avcodec_receive_frame(avctx, frame); + if (ret < 0 && ret != AVERROR(EAGAIN)) + return ret; + if (ret >= 0) + *got_frame = 1; + + return 0; +} + +static int filter_frame(AVFilterLink *inlink, AVFrame *frame) +{ + AVFrameSideData *sd; + SplitCaptionsContext *s = inlink->dst->priv; + AVFilterLink *outlink0 = inlink->dst->outputs[0]; + AVFilterLink *outlink1 = inlink->dst->outputs[1]; + AVPacket *pkt = NULL; + AVFrame *sub_out = NULL; + + int ret; + + outlink0->format = inlink->format; + + sd = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC); + + if (sd) { + int got_output = 0; + + pkt = av_packet_alloc(); + pkt->buf = av_buffer_ref(sd->buf); + if (!pkt->buf) { + ret = AVERROR(ENOMEM); + goto fail; + } + + pkt->data = sd->data; + pkt->size = (int)sd->size; + pkt->pts = frame->pts; + + sub_out = ff_get_subtitles_buffer(outlink1, AV_SUBTITLE_FMT_ASS); + if (!sub_out) { + ret = AVERROR(ENOMEM); + goto fail; + } + + if ((ret = av_buffer_replace(&sub_out->subtitle_header, s->subtitle_header)) < 0) + goto fail; + + ret = decode(s->cc_dec, sub_out, &got_output, pkt); + + if (ret < 0) + goto fail; + + if (got_output) { + sub_out->pts = frame->pts; + av_frame_free(&s->next_sub_frame); + s->next_sub_frame = sub_out; + sub_out = NULL; + s->new_frame = 1; + s->next_sub_frame->pts = frame->pts; + + if ((ret = av_buffer_replace(&s->next_sub_frame->subtitle_header, s->subtitle_header)) < 0) + goto fail; + + if (s->real_time && s->scatter_realtime_output) { + if (s->next_repetition_pts) + s->next_sub_frame->pts = s->next_repetition_pts; + + s->next_sub_frame->subtitle_end_time = s->real_time_latency_msec; + s->next_repetition_pts = s->next_sub_frame->pts + av_rescale_q(s->real_time_latency_msec, ms_tb, inlink->time_base); + } + + ret = request_sub_frame(outlink1); + if (ret < 0) + goto fail; + } + } + + if (s->real_time && s->scatter_realtime_output && !s->new_frame && s->next_repetition_pts > 0 && frame->pts > s->next_repetition_pts) { + s->new_frame = 1; + s->next_sub_frame->pts = s->next_repetition_pts; + s->next_repetition_pts = s->next_sub_frame->pts + av_rescale_q(s->real_time_latency_msec, ms_tb, inlink->time_base); + } + + if (!s->next_sub_frame) { + s->next_sub_frame = ff_get_subtitles_buffer(outlink1, outlink1->format); + if (!s->next_sub_frame) { + ret = AVERROR(ENOMEM); + goto fail; + } + + s->next_sub_frame->subtitle_end_time = 100; + s->next_sub_frame->pts = frame->pts; + s->new_frame = 1; + + if ((ret = av_buffer_replace(&s->next_sub_frame->subtitle_header, s->subtitle_header)) < 0) + goto fail; + } + + ret = ff_filter_frame(outlink0, frame); + +fail: + av_packet_free(&pkt); + av_frame_free(&sub_out); + return ret; +} + +#define OFFSET(x) offsetof(SplitCaptionsContext, x) +#define FLAGS (AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_FILTERING_PARAM) + +static const AVOption split_cc_options[] = { + { "use_cc_styles", "Emit closed caption style header", OFFSET(use_cc_styles), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS, NULL }, + { "real_time", "emit subtitle events as they are decoded for real-time display", OFFSET(real_time), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS }, + { "real_time_latency_msec", "minimum elapsed time between emitting real-time subtitle events", OFFSET(real_time_latency_msec), AV_OPT_TYPE_INT, { .i64 = 200 }, 0, 500, FLAGS }, + { "scatter_realtime_output", "scatter output events to a duration of real_time_latency_msec", OFFSET(scatter_realtime_output), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS }, + { "data_field", "select data field", OFFSET(data_field), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, FLAGS, "data_field" }, + { "auto", "pick first one that appears", 0, AV_OPT_TYPE_CONST, { .i64 =-1 }, 0, 0, FLAGS, "data_field" }, + { "first", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, FLAGS, "data_field" }, + { "second", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, FLAGS, "data_field" }, + { NULL }, +}; + +AVFILTER_DEFINE_CLASS(split_cc); + +static const AVFilterPad inputs[] = { + { + .name = "default", + .type = AVMEDIA_TYPE_VIDEO, + .filter_frame = filter_frame, + .config_props = config_input, + }, +}; + +static const AVFilterPad outputs[] = { + { + .name = "video_passthrough", + .type = AVMEDIA_TYPE_VIDEO, + .config_props = config_video_output, + }, + { + .name = "subtitles", + .type = AVMEDIA_TYPE_SUBTITLE, + .request_frame = request_sub_frame, + .config_props = config_sub_output, + }, +}; + +const AVFilter ff_sf_splitcc = { + .name = "splitcc", + .description = NULL_IF_CONFIG_SMALL("Extract closed-caption (A53) data from video as subtitle stream."), + .init = init, + .uninit = uninit, + .priv_size = sizeof(SplitCaptionsContext), + .priv_class = &split_cc_class, + .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE, + FILTER_INPUTS(inputs), + FILTER_OUTPUTS(outputs), + FILTER_QUERY_FUNC(query_formats), +};