Example #1
0
    def test_insert_clip(self):
        inserted_middle = vsutil.insert_clip(self.BLACK_SAMPLE_CLIP,
                                             self.WHITE_SAMPLE_CLIP[:10], 50)
        self.assert_same_frame(inserted_middle[0], self.BLACK_SAMPLE_CLIP[0])
        self.assert_same_frame(inserted_middle[50], self.WHITE_SAMPLE_CLIP[0])
        self.assert_same_frame(inserted_middle[60], self.BLACK_SAMPLE_CLIP[60])

        inserted_start = vsutil.insert_clip(self.BLACK_SAMPLE_CLIP,
                                            self.WHITE_SAMPLE_CLIP[:10], 0)
        self.assert_same_frame(inserted_start[0], self.WHITE_SAMPLE_CLIP[0])
        self.assert_same_frame(inserted_start[10], self.BLACK_SAMPLE_CLIP[10])

        inserted_end = vsutil.insert_clip(self.BLACK_SAMPLE_CLIP,
                                          self.WHITE_SAMPLE_CLIP[:10], 90)
        self.assert_same_frame(inserted_end[-1], self.WHITE_SAMPLE_CLIP[9])
        self.assert_same_frame(inserted_end[89], self.BLACK_SAMPLE_CLIP[89])

        # make sure we didn’t lose or add any frames in the process
        self.assert_same_metadata(self.BLACK_SAMPLE_CLIP, inserted_start)
        self.assert_same_metadata(self.BLACK_SAMPLE_CLIP, inserted_middle)
        self.assert_same_metadata(self.BLACK_SAMPLE_CLIP, inserted_end)

        with self.assertRaises(ValueError):
            vsutil.insert_clip(self.BLACK_SAMPLE_CLIP, self.BLACK_SAMPLE_CLIP,
                               90)
Example #2
0
def fade_filter(clip: vs.VideoNode, clip_a: vs.VideoNode, clip_b: vs.VideoNode,
                start_f: int, end_f: int) -> vs.VideoNode:
    """Applies a filter by fading clip_a to clip_b.

    Args:
        clip (vs.VideoNode): Source clip

        clip_a (vs.VideoNode): Fade in clip.

        clip_b (vs.VideoNode): Fade out clip.

        start_f (int): Start frame.

        end_f (int): End frame.

    Returns:
        vs.VideoNode: Faded clip.
    """
    length = end_f - start_f

    def _fade(n: int, clip_a: vs.VideoNode, clip_b: vs.VideoNode,
              length: int) -> vs.VideoNode:  # noqa: PLC0103
        return core.std.Merge(clip_a, clip_b, n / length)

    func = partial(_fade,
                   clip_a=clip_a[start_f:end_f + 1],
                   clip_b=clip_b[start_f:end_f + 1],
                   length=length)
    clip_fad = core.std.FrameEval(clip[start_f:end_f + 1], func)

    return insert_clip(clip, clip_fad, start_f)
Example #3
0
def mask_opening(ref: vs.VideoNode) -> vs.VideoNode:
    mask = core.imwri.Read('rezeros2_ncop_0-16.png') * 17 + core.imwri.Read(
        'rezeros2_ncop_17-18.png') * 2
    mask += core.imwri.Read('rezeros2_ncop_19.png')
    mask += core.imwri.Read('rezeros2_ncop_20.png')
    mask += core.imwri.Read('rezeros2_ncop_21.png')
    mask += core.imwri.Read('rezeros2_ncop_22.png')
    mask += core.imwri.Read('rezeros2_ncop_23.png')
    mask += core.imwri.Read('rezeros2_ncop_24.png')
    mask += core.imwri.Read('rezeros2_ncop_25.png')
    mask += core.imwri.Read('rezeros2_ncop_26.png')
    mask += core.imwri.Read('rezeros2_ncop_27.png')
    mask += core.imwri.Read('rezeros2_ncop_28.png')
    mask += core.imwri.Read('rezeros2_ncop_29.png')
    mask += core.imwri.Read('rezeros2_ncop_30.png')
    mask += core.imwri.Read('rezeros2_ncop_31.png')
    mask += core.imwri.Read('rezeros2_ncop_32.png')
    mask += core.imwri.Read('rezeros2_ncop_33.png')
    mask += core.imwri.Read('rezeros2_ncop_34.png')
    mask += core.imwri.Read('rezeros2_ncop_35.png')
    mask += core.imwri.Read('rezeros2_ncop_36.png')
    mask += core.imwri.Read('rezeros2_ncop_37.png')
    mask += core.imwri.Read('rezeros2_ncop_38.png')

    ref = ref.std.BlankClip(format=vs.GRAY16)
    mask = core.resize.Bicubic(mask, format=vs.GRAY16,
                               matrix_s='709').std.AssumeFPS(ref)

    return insert_clip(ref, mask, OPSTART)
Example #4
0
def pre_filter() -> vs.VideoNode:
    """Pre-filtering to fix some stuff"""
    from vsutil import insert_clip

    src = JP_BD.clip_cut

    # The grain pattern randomly stops in the middle??? ufo, WHAT
    ins = insert_clip(src, src[877:881], 881)

    return ins
Example #5
0
def filterchain() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
    """Main filterchain"""
    import havsfunc as haf
    import lvsfunc as lvf
    import vardefunc as vdf
    from adptvgrnMod import adptvgrnMod
    from ccd import ccd
    from vsutil import depth, insert_clip

    src = JP_BD.clip_cut
    src = depth(src, 16)

    scaled, descale_mask = flt.rescaler(src, height=855)

    denoise_y = core.knlm.KNLMeansCL(scaled, d=2, a=3, h=0.35)
    denoise_uv = ccd(denoise_y, threshold=7, matrix='709')
    stab = haf.GSMC(denoise_uv, radius=1, thSAD=200, planes=[0])
    decs = vdf.noise.decsiz(stab, sigmaS=8, min_in=200 << 8, max_in=232 << 8)

    aa_weak = lvf.aa.nneedi3_clamp(decs, strength=4)
    aa_strong = lvf.sraa(decs, rfactor=1.6)
    aa_clamp = lvf.aa.clamp_aa(decs, aa_weak, aa_strong, strength=2)
    aa_rfs = lvf.rfs(aa_clamp, aa_strong, [(434, 592)])

    halo_mask = lvf.mask.halo_mask(aa_rfs)
    darken = flt.line_darkening(aa_rfs, strength=0.35)
    dehalo = core.std.MaskedMerge(
        darken, lvf.dehalo.bidehalo(darken, sigmaS_final=1.2, sigmaR=11 / 255),
        halo_mask)

    merged_credits = core.std.MaskedMerge(dehalo, src, descale_mask)

    deband = flt.masked_f3kdb(merged_credits,
                              rad=21,
                              thr=[28, 24],
                              grain=[32, 16])
    grain: vs.VideoNode = adptvgrnMod(deband,
                                      seed=42069,
                                      strength=0.25,
                                      luma_scaling=10,
                                      size=1.35,
                                      sharp=80,
                                      grain_chroma=False)

    # Making sure there's no weird dynamic noise on the titlecard
    final = insert_clip(grain, grain[869] * (903 - 869), 869)

    return final
Example #6
0
def pre_freeze() -> vs.VideoNode:
    """Performing some freezeframing in the OP at the Typesetter's request"""
    from adjust import Tweak
    from vsutil import insert_clip

    src = JP_clip.clip_cut

    freeze = core.std.FreezeFrames(src, [s[0] for s in freeze_ranges],
                                   [e[1] for e in freeze_ranges],
                                   [f[2] for f in freeze_ranges])

    to_adjust = freeze[opstart + freeze_ranges[1][0]]
    adjust = Tweak(to_adjust, hue=-18)
    adjust = adjust * (freeze_ranges[2][1] - freeze_ranges[2][0] + 1)
    insert = insert_clip(freeze, adjust, freeze_ranges[2][0])

    return insert
Example #7
0
def fader(clip: vs.VideoNode,
          start_frame: int,
          end_frame: int,
          duration: Optional[int] = None,
          input_frame: Optional[int] = None) -> vs.VideoNode:
    """
    A function to fade a part of a given clip into itself.
    Hyper specific, and probably only useful for clip-to-black fades or something.

    start_frame and end_frame are for trimming the clip. Exclusive.
    duration determines how long the fade is.
    input_frame determines where in the clip the faded clip gets inserted.
    """
    import kagefunc as kgf

    duration = duration or (end_frame - start_frame)
    input_frame = input_frame or start_frame

    fade = kgf.crossfade(clip[start_frame] * duration,
                         clip[end_frame] * duration, duration - 1)
    return insert_clip(clip, fade, input_frame)
Example #8
0
def do_filter():
    """Vapoursynth filtering"""
    src = JPBD.src_cut
    ep11 = JPBD_11.src_cut

    opstart = 0
    opstart_ep11, opend_ep11 = 744, 3140
    h = 720
    w = get_w(h)
    b, c = vdf.get_bicubic_params('robidoux')

    # Fix compositing error in the OP
    ncop, op_11 = src, ep11[opstart_ep11:opend_ep11 + 1]
    fix = lvf.rfs(ncop, op_11, [(0, 79), (1035, 1037)])
    src = depth(fix, 32)

    def denoise_and_rescale(clip):
        denoise = hybrid_denoise(clip, 0.5, 2)
        out = denoise

        luma = get_y(out)
        line_mask = vdf.edge_detect(luma, 'FDOG', 0.05, (1, 1))

        descale = core.descale.Debicubic(luma, w, h, b, c)
        upscale = vdf.fsrcnnx_upscale(descale, None, descale.height * 2,
                                      '_shaders/FSRCNNX_x2_56-16-4-1.glsl',
                                      core.resize.Point)

        antialias = single_rate_antialiasing(upscale,
                                             13,
                                             alpha=0.3,
                                             beta=0.45,
                                             gamma=320,
                                             mdis=18)
        scaled = muvf.SSIM_downsample(antialias,
                                      src.width,
                                      src.height,
                                      kernel='Bicubic')

        rescale = core.std.MaskedMerge(luma, scaled, line_mask)
        merged = vdf.merge_chroma(rescale, out)
        return depth(merged, 16)

    out = denoise_and_rescale(src)
    to_zoom = denoise_and_rescale(depth(JPBD_11.src_cut[8590:8605], 32))

    zoom = core.std.FrameEval(to_zoom, partial(_zoom_prog, clip=to_zoom))
    out = insert_clip(out, zoom, 1685)

    antialias = lvf.rfs(
        out,
        lvf.sraa(out,
                 1.65,
                 9,
                 alpha=0.3,
                 beta=0.45,
                 gamma=240,
                 nrad=3,
                 mdis=25), [(opstart + 840, opstart + 881)])
    out = antialias

    # Slight sharp though CAS
    sharp = hvf.LSFmod(out,
                       strength=75,
                       Smode=3,
                       Lmode=1,
                       edgemode=1,
                       edgemaskHQ=True)
    out = sharp

    dering = gf.HQDeringmod(out, thr=16, darkthr=0.1, show=False)
    out = dering

    warp = xvs.WarpFixChromaBlend(out, thresh=48, depth=8)
    out = warp

    preden = core.knlm.KNLMeansCL(out,
                                  d=0,
                                  a=3,
                                  h=0.6,
                                  device_type='GPU',
                                  channels='Y')
    mask = lvf.denoise.detail_mask(preden, brz_a=2000, brz_b=800, rad=4)
    deband = dbs.f3kpf(out, 17, 42, 42)
    deband_b = placebo.deband(out, 22, 6, 2)
    deband = lvf.rfs(deband, deband_b, [(opstart + 1515, opstart + 1603)])
    deband = core.std.MaskedMerge(deband, out, mask)
    out = deband

    adg_mask = core.adg.Mask(out.std.PlaneStats(),
                             20).std.Expr(f'x x {128<<8} - 0.25 * +')
    grain = core.grain.Add(out, 0.2, constant=True)
    grain = core.std.MaskedMerge(out, grain, adg_mask, 0)
    out = grain

    return depth(out, 10)
Example #9
0
def main() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
    """Vapoursynth filtering"""
    # Don't worry, this script is barely readable anymore even for me
    import rekt
    from awsmfunc import bbmod
    from havsfunc import ContraSharpening
    from lvsfunc.aa import upscaled_sraa
    from lvsfunc.comparison import stack_compare
    from lvsfunc.mask import BoundingBox
    from lvsfunc.util import replace_ranges
    from vardefunc import dcm
    from vardefunc.deband import dumb3kdb
    from vardefunc.mask import FreyChen
    from vsutil import depth, get_y, insert_clip

    src = JP_BD.clip_cut
    b = core.std.BlankClip(src, length=1)

    if opstart is not False:
        src_NCOP = NCOP.clip_cut
        op_scomp = stack_compare(
            src[opstart:opstart + src_NCOP.num_frames - 1] + b,
            src_NCOP[:-op_offset] + b,
            make_diff=True)  # noqa
    if edstart is not False:
        src_NCED = NCED.clip_cut
        #ed_scomp = stack_compare(src[edstart:edstart+src_NCED.num_frames-1]+b, src_NCED[:-ed_offset]+b, make_diff=True)  # noqa

    # Masking credits
    op_mask = dcm(
        src, src[opstart:opstart+src_NCOP.num_frames], src_NCOP,
        start_frame=opstart, thr=25, prefilter=True) if opstart is not False \
        else get_y(core.std.BlankClip(src))
    ed_mask = dcm(
        src, src[edstart:edstart+src_NCED.num_frames], src_NCED,
        start_frame=edstart, thr=25, prefilter=True) if edstart is not False \
        else get_y(core.std.BlankClip(src))
    credit_mask = core.std.Expr([op_mask, ed_mask], expr='x y +')
    credit_mask = depth(credit_mask, 16).std.Binarize()

    # Fixing an animation f**k-up
    for f in op_replace:
        src = insert_clip(src, src[f], f - 1)

    # Edgefixing
    ef = rekt.rektlvls(
        src,
        prot_val=[16, 235],
        min=16,
        max=235,
        rownum=[0, src.height - 1],
        rowval=[16, 16],
        colnum=[0, src.width - 1],
        colval=[16, 16],
    )

    bb_y = bbmod(ef,
                 left=1,
                 top=1,
                 right=1,
                 bottom=1,
                 thresh=32,
                 y=True,
                 u=False,
                 v=False)
    bb_uv = bbmod(bb_y,
                  left=2,
                  top=2,
                  right=2,
                  bottom=2,
                  y=False,
                  u=True,
                  v=True)
    bb32 = depth(bb_uv, 32)

    # --- Very specific filtering that should probably be removed for future episodes entirely
    # Fading for some... well, fades.
    fade = flt.fader(bb32, start_frame=4437, end_frame=4452)
    fade = flt.fader(fade, start_frame=18660, end_frame=18697)

    # Different sport names
    rkt_aa_ranges: Union[Union[int, None, Tuple[Optional[int], Optional[int]]],
                         List[Union[int, None,
                                    Tuple[Optional[int],
                                          Optional[int]]]], None] = [  # noqa
                                              (8824, 8907), (9828, 9911),
                                              (10995, 11078), (11904, 12010)
                                          ]

    rkt_aa = rekt.rekt_fast(fade,
                            fun=lambda x: upscaled_sraa(x),
                            top=854,
                            left=422,
                            bottom=60,
                            right=422)
    rkt_aa = replace_ranges(fade, rkt_aa, rkt_aa_ranges)

    # QP GET!
    rkt_aa2_ranges: Union[Union[int, None, Tuple[Optional[int],
                                                 Optional[int]]],
                          List[Union[int, None,
                                     Tuple[Optional[int],
                                           Optional[int]]]], None] = [  # noqa
                                               (26333, 26333), (28291, 28344),
                                               (30271, 30364)
                                           ]
    rkt_aa2 = rekt.rekt_fast(rkt_aa,
                             fun=lambda x: upscaled_sraa(x),
                             top=714,
                             left=354,
                             bottom=224,
                             right=354)
    rkt_aa2 = replace_ranges(fade, rkt_aa, rkt_aa2_ranges)

    # Table stuff
    rkt_aa3_ranges: Union[Union[int, None, Tuple[Optional[int],
                                                 Optional[int]]],
                          List[Union[int, None,
                                     Tuple[Optional[int],
                                           Optional[int]]]], None] = [  # noqa
                                               (32797, 32952)
                                           ]
    rkt_aa3 = rekt.rekt_fast(rkt_aa2,
                             fun=lambda x: upscaled_sraa(x),
                             top=488,
                             left=312,
                             bottom=390,
                             right=850)
    rkt_aa3 = replace_ranges(fade, rkt_aa2, rkt_aa3_ranges)

    rkt_aa = rkt_aa3

    # Clipping error Nyatalante/Achilles
    fixed_frame = source(
        JP_BD.workdir.to_str() + r"/assets/01/FGCBD_01_8970_fixed.png", rkt_aa)
    fix_error = replace_ranges(rkt_aa, fixed_frame, [(8968, 8970)])

    sp_out32 = fix_error
    sp_out16 = depth(sp_out32, 16)

    # Rescaling
    l_mask = FreyChen().get_mask(get_y(sp_out16)).morpho.Close(size=6)
    l_mask = core.std.Binarize(l_mask, 24 << 8).std.Maximum().std.Maximum()
    scaled, credit_mask = flt.rescaler(sp_out32,
                                       height=720,
                                       shader_file=shader)
    scaled = core.std.MaskedMerge(sp_out16, scaled, l_mask)
    scaled = core.std.MaskedMerge(scaled, sp_out16, credit_mask)

    # Denoising
    denoise = flt.multi_denoise(scaled, l_mask)

    # Anti-aliasing
    aa_clamped = flt.clamp_aa(denoise, strength=3.0)
    aa_rfs = replace_ranges(denoise, aa_clamped, aa_ranges)

    # Fix edges because they get f****d during the denoising and AA stages
    box = BoundingBox((1, 1), (src.width - 2, src.height - 2))
    fix_edges = core.std.MaskedMerge(scaled, aa_rfs, box.get_mask(scaled))

    # Regular debanding, but then...
    deband = flt.multi_debander(fix_edges, sp_out16)

    # --- More very specific filtering that should almost definitely be removed for other episodes
    boxes = [
        BoundingBox((0, 880), (1920, 200)),
        BoundingBox((1367, 0), (552, 1080)),
        BoundingBox((1143, 0), (466, 83)),
        BoundingBox((1233, 84), (237, 84)),
    ]

    boxed_deband = flt.placebo_debander(fix_edges,
                                        iterations=2,
                                        threshold=8,
                                        radius=14,
                                        grain=4)
    boxed_mask = core.std.BlankClip(
        boxed_deband.std.ShufflePlanes(planes=0, colorfamily=vs.GRAY))
    for bx in boxes:  # Gonna be awfully slow but OH WELLLLLL
        boxed_mask = core.std.Expr(
            [boxed_mask, bx.get_mask(boxed_mask)], "x y max")

    boxed_deband_merged = core.std.MaskedMerge(deband, boxed_deband,
                                               boxed_mask)
    boxed_deband_merged = replace_ranges(deband, boxed_deband_merged,
                                         [(20554, 20625)])

    stronger_deband = dumb3kdb(fix_edges, radius=18, threshold=[48, 32])
    stronger_deband = replace_ranges(boxed_deband_merged, stronger_deband,
                                     [(22547, 22912), (28615, 28846),
                                      (33499, 33708), (37223, 37572),
                                      (37636, 37791), (38047, 38102),
                                      (38411, 38733)])

    deband_csharp = ContraSharpening(stronger_deband, scaled, 17)

    sp_out = deband_csharp

    # Back to regular graining
    grain = flt.grain(sp_out)

    return grain
Example #10
0
def do_filter():
    """Vapoursynth filtering"""
    src = JPBD.src_cut

    src01 = JPBD_01.src_cut
    fr_s01, fr_e01 = 30492, 30536
    fr_s, fr_e = 1529, 1573
    src = insert_clip(src, src01[fr_s01:fr_e01 + 1], fr_s)

    image01 = core.imwri.Read('1080elements_mv01_01.png', alpha=True)
    image01[0] = core.resize.Bicubic(image01[0], format=vs.YUV420P8,
                                     matrix=1) * src.num_frames
    image01[0] = core.std.AssumeFPS(image01[0], src)

    image02 = core.imwri.Read('1080elements_mv01_02.png', alpha=True)
    image02[0] = core.resize.Bicubic(image02[0], format=vs.YUV420P8,
                                     matrix=1) * src.num_frames
    image02[0] = core.std.AssumeFPS(image02[0], src)

    src = lvf.rfs(src, core.std.MaskedMerge(src, image01[0], image01[1]),
                  [(fr_s, 1534)])
    src = lvf.rfs(src, core.std.MaskedMerge(src, image02[0], image02[1]),
                  [(1535, fr_e)])

    src = depth(src, 16)
    out = src

    h = 846
    w = get_w(h)
    cubic_filters = ['catrom', 'mitchell', 'robidoux', 'robidoux sharp']
    cubic_filters = [vdf.get_bicubic_params(cf) for cf in cubic_filters]

    degrain = hybrid_denoise(out, 0.35, 1.2, dict(a=2, d=1))
    out = degrain

    y = get_y(out)
    y32 = depth(y, 32)
    lineart = vdf.edge_detect(y32, 'kirsch', 0.055,
                              (1, 1)).std.Median().std.Inflate()

    descale_clips = [
        core.descale.Debicubic(y32, w, h, b, c) for b, c in cubic_filters
    ]
    descale = core.std.Expr(descale_clips,
                            'x y z a min min min x y z max max min')

    conv = core.std.Convolution(descale, [1, 2, 1, 2, 0, 2, 1, 2, 1])
    thr, coef = 0.013, 3
    descale_fix = core.std.Expr([descale, conv],
                                f'x y - abs {thr} < y x ?').std.PlaneStats()
    adapt_mask = core.adg.Mask(
        descale_fix,
        12).std.Invert().std.Expr(f'x 0.5 - {coef} * 0.5 + 0 max 1 min')

    descale = core.std.MaskedMerge(descale, descale_fix, adapt_mask)

    upscale = vdf.fsrcnnx_upscale(descale,
                                  w * 2,
                                  h * 2,
                                  r'shaders\FSRCNNX_x2_56-16-4-1.glsl',
                                  upscaler_smooth=eedi3_upscale,
                                  profile='zastin',
                                  sharpener=partial(gf.DetailSharpen,
                                                    sstr=1.25,
                                                    power=4))

    aa_strong = sraa_eedi3(upscale, 13, alpha=0.3, beta=0.5, gamma=40)
    aa = aa_strong

    down = muvf.SSIM_downsample(aa,
                                src.width,
                                src.height,
                                filter_param_a=0,
                                filter_param_b=0)

    upscale = depth(core.std.MaskedMerge(y32, down, lineart), 16)

    merged = vdf.merge_chroma(upscale, out)
    out = merged

    y = get_y(out)
    detail_light_mask = lvf.denoise.detail_mask(y, brz_a=2500, brz_b=1200)

    pf = iterate(out, core.std.Maximum, 2).std.Convolution([10] * 9, planes=0)
    diff = core.std.MakeDiff(out, pf)

    deband = core.f3kdb.Deband(pf,
                               17,
                               36,
                               36,
                               36,
                               12,
                               12,
                               2,
                               keep_tv_range=True,
                               output_depth=16)

    deband = core.std.MergeDiff(deband, diff)
    deband = core.std.MaskedMerge(deband, out, detail_light_mask)
    out = deband

    grain = adptvgrnMod(out,
                        0.25,
                        0.15,
                        size=out.height / h,
                        sharp=80,
                        luma_scaling=10,
                        static=True)
    out = grain

    # # Restore 1080p stuff
    ref = src
    rescale_mask = vdf.drm(ref, h, mthr=65, sw=4, sh=4)
    credit = out
    credit = core.std.MaskedMerge(credit, ref, rescale_mask, 0)

    credit = lvf.rfs(credit, ref, [(431, 516), (2582, src.num_frames - 1)])
    out = credit

    return depth(out, 10).std.Limiter(16 << 2, [235 << 2, 240 << 2])
Example #11
0
 def preqpfileflt(self) -> None:
     """Pre-QP file generation filtering so the scenes match properly"""
     self.file.clip_cut = replace_ranges(self.file.clip_cut,
                                         JPBD_NCOP2.clip_cut, replace_op)
     self.file.clip_cut = insert_clip(self.file.clip_cut,
                                      JPBD_NCOP2.clip_cut[826:1038], 823)
Example #12
0
def do_filter():
    """Vapoursynth filtering"""
    src = JPBD.src_cut
    src = depth(src, 16)
    out = src

    h = 900
    w = get_w(h)

    # Remove the grain
    ref = hvf.SMDegrain(out, tr=1, thSAD=300, plane=4)
    degrain = mvf.BM3D(out, sigma=[1.5, 1], radius1=1, ref=ref)
    degrain = insert_clip(degrain, smhdegrain(out[5539:5670], 2, 280), 5539)
    degrain = insert_clip(degrain, smhdegrain(out[5933:5992], 2, 200), 5933)
    degrain = insert_clip(degrain, smhdegrain(out[6115:6180], 2, 200), 6115)
    degrain = insert_clip(degrain, smhdegrain(out[6180:6281], 2, 200), 6180)
    degrain = insert_clip(degrain, smhdegrain(out[39303:39482], 2, 280), 39303)
    degrain = insert_clip(degrain, smhdegrain(out[40391:40837], 2, 200), 40391)
    degrain = insert_clip(degrain, smhdegrain(out[40908:41087], 2, 280), 40908)
    degrain = insert_clip(degrain, smhdegrain(out[41671:41791], 2, 280), 41671)
    degrain = insert_clip(degrain, smhdegrain(out[41791:41977], 2, 280), 41791)
    degrain = insert_clip(degrain, smhdegrain(out[41977:42073], 2, 280), 41977)

    degrain = insert_clip(degrain, smhdegrain(out[43083:44462], 2, 350), 43083)
    degrain = lvf.rfs(degrain, out, [(51749, 52387)])
    out = depth(degrain, 32)

    luma = get_y(out)
    line_mask = vdf.edge_detect(luma, 'kirsch', 0.075,
                                (1, 1)).std.Median().std.Inflate()

    descale = core.descale.Debilinear(luma, w, h)
    upscale = eedi3_upscale(descale)
    antialias = single_rate_antialiasing(upscale,
                                         13,
                                         alpha=0.2,
                                         beta=0.6,
                                         gamma=300,
                                         mdis=15).resize.Bicubic(
                                             src.width, src.height)

    rescale = core.std.MaskedMerge(luma, antialias, line_mask)
    merged = vdf.merge_chroma(rescale, out)
    out = depth(merged, 16)

    y = get_y(out)
    detail_light_mask = lvf.denoise.detail_mask(y.std.Median(),
                                                brz_a=2500,
                                                brz_b=1200)

    pf = out.std.Convolution([1] * 9).std.Merge(out, 0.45)

    diffdb = core.std.MakeDiff(out, pf)

    deband = dumb3kdb(pf, 16, 30)
    deband_b = dbs.f3kbilateral(pf, 20, 100)
    deband = lvf.rfs(deband, deband_b, [(43083, 44461)])

    deband = core.std.MergeDiff(deband, diffdb)
    deband = core.std.MaskedMerge(deband, out, detail_light_mask)

    deband = lvf.rfs(deband, out, [(51749, 52387)])
    out = deband

    sharp = hvf.LSFmod(out,
                       strength=65,
                       Smode=3,
                       Lmode=1,
                       edgemode=1,
                       edgemaskHQ=True)
    out = sharp

    ref = get_y(out).std.PlaneStats()
    adgmask_a = core.adg.Mask(ref, 30)
    adgmask_b = core.adg.Mask(ref, 12)

    stgrain = sizedgrn(out, 0.1, 0.05, 1.00)
    stgrain = core.std.MaskedMerge(out, stgrain, adgmask_b)
    stgrain = core.std.MaskedMerge(out, stgrain, adgmask_a.std.Invert())

    dygrain = sizedgrn(out, 0.2, 0.05, 1.05, sharp=60, static=False)
    dygrain = core.std.MaskedMerge(out, dygrain, adgmask_a)
    grain = core.std.MergeDiff(dygrain, out.std.MakeDiff(stgrain))
    out = grain

    ref = src
    rescale_mask = vdf.drm(ref, h, mthr=65, sw=4, sh=4)
    credit = out
    credit = lvf.rfs(credit, core.std.MaskedMerge(credit, ref, rescale_mask,
                                                  0), [(0, 2956),
                                                       (43104, 45749)])
    credit = lvf.rfs(credit, ref, [(45824, 50401),
                                   (52388, src.num_frames - 1)])
    out = credit

    return depth(out, 10)
Example #13
0
def do_filter():
    """Vapoursynth filtering"""
    src = JPBD.src_cut
    src += src[-1]
    ep10 = JPBD_10.src_cut

    h = 720
    w = get_w(h)
    b, c = vdf.get_bicubic_params('robidoux')
    opstart, opend = 2973, 5370
    edstart, edend = 31887, src.num_frames - 1
    opstart_ep10, opend_ep10 = 768, 3164
    full_stuff = [(5449, 5580), (16465, 16620)]

    # Fix compositing error in the OP
    op_src, op_10 = src[opstart:opend + 1], ep10[opstart_ep10:opend_ep10 + 1]
    fix = lvf.rfs(op_src, op_10, [(0, 79), (1035, 1037)])
    fix_src = insert_clip(src, fix, opstart)
    src = depth(fix_src, 32)

    denoise = hybrid_denoise(src, 0.5, 2)
    out = denoise

    luma = get_y(out)
    line_mask = vdf.edge_detect(luma, 'FDOG', 0.05, (1, 1))

    descale = core.descale.Debicubic(luma, w, h, b, c)
    upscale = vdf.fsrcnnx_upscale(descale, None, descale.height * 2,
                                  '_shaders/FSRCNNX_x2_56-16-4-1.glsl',
                                  core.resize.Point)

    antialias = single_rate_antialiasing(upscale,
                                         13,
                                         alpha=0.3,
                                         beta=0.45,
                                         gamma=320,
                                         mdis=18)

    scaled = muvf.SSIM_downsample(antialias,
                                  src.width,
                                  src.height,
                                  kernel='Bicubic')
    rescale = core.std.MaskedMerge(luma, scaled, line_mask)
    merged = vdf.merge_chroma(rescale, out)
    out = depth(merged, 16)

    antialias = lvf.rfs(
        out,
        lvf.sraa(out,
                 1.65,
                 9,
                 alpha=0.3,
                 beta=0.45,
                 gamma=240,
                 nrad=3,
                 mdis=25), [(opstart + 840, opstart + 881)])
    out = antialias

    # Slight sharp though CAS
    sharp = hvf.LSFmod(out,
                       strength=75,
                       Smode=3,
                       Lmode=1,
                       edgemode=1,
                       edgemaskHQ=True)
    out = sharp

    dering = gf.HQDeringmod(out, thr=16, darkthr=0.1)
    out = dering

    warp = xvs.WarpFixChromaBlend(out, thresh=48, depth=8)
    out = warp

    preden = core.knlm.KNLMeansCL(out,
                                  d=0,
                                  a=3,
                                  h=0.6,
                                  device_type='GPU',
                                  channels='Y')
    deband_mask = lvf.denoise.detail_mask(preden, brz_a=2000, brz_b=800, rad=4)

    deband = dbs.f3kpf(out, 17, 42, 42)
    deband_b = placebo.deband(out, 22, 6, 2)
    deband = lvf.rfs(deband, deband_b, [(opstart + 1515, opstart + 1603)])

    deband_c = placebo.deband(deband, 17, 5, 1)
    deband_c = dbs.f3kbilateral(deband_c, 22, 64, 64)
    deband = lvf.rfs(deband, deband_c, [(15612, 15695)])

    deband_mask2 = vdf.edge_detect(
        out.knlm.KNLMeansCL(d=2, a=2, h=0.4, device_type='GPU', channels='Y'),
        'FDOG', 1100, (8, 1))
    deband_mask2 = iterate(deband_mask2, core.std.Deflate, 4)
    deband_d = placebo.deband(out, 16, 12, 3)
    deband_d = core.std.MaskedMerge(deband_d, out, deband_mask2)
    deband = lvf.rfs(deband, deband_d, [(16339, 16542)])

    deband = core.std.MaskedMerge(deband, out, deband_mask)

    out = deband

    adg_mask = core.adg.Mask(out.std.PlaneStats(),
                             20).std.Expr(f'x x {128<<8} - 0.25 * +')
    grain = core.grain.Add(out, 0.2, constant=True)
    grain = core.std.MaskedMerge(out, grain, adg_mask, 0)
    out = grain

    rescale_mask = vdf.drm(luma, b=b, c=c, sw=4, sh=4)
    ref, rescale_mask, src, src_ncop, src_nced = [
        depth(x, 16) for x in
        [denoise, rescale_mask, src, JPBD_NCOP.src_cut, JPBD_NCED.src_cut]
    ]

    credit = lvf.rfs(out, core.std.MaskedMerge(out, ref, rescale_mask),
                     full_stuff)
    out = credit

    src_c, src_ncop, src_nced = [
        c.knlm.KNLMeansCL(a=7, h=35, d=0, device_type='gpu')
        for c in [src, src_ncop, src_nced]
    ]

    opening_mask = vdf.dcm(out, src_c[opstart:opend + 1],
                           src_ncop[:opend - opstart + 1], opstart, opend, 4,
                           4).std.Inflate()
    ending_mask = vdf.dcm(out, src_c[edstart:edend + 1],
                          src_nced[:edend - edstart + 1], edstart, edend, 4,
                          4).std.Inflate()
    credit_mask = core.std.Expr([opening_mask, ending_mask], 'x y +')

    credit = lvf.rfs(out, core.std.MaskedMerge(out, ref, credit_mask),
                     [(opstart, opend), (edstart, edend)])
    out = credit

    return depth(out, 10)
Example #14
0
def filterchain() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
    """Main filterchain"""
    import havsfunc as haf
    import lvsfunc as lvf
    import muvsfunc as muf
    import debandshit as dbs
    import vardefunc as vdf
    from vsutil import depth, get_y, insert_clip, join, plane

    src = JP_DVD.clip_cut.std.AssumeFPS(fpsnum=24000, fpsden=1001)
    src_ncop, src_nced = JP_BD_NCOP.clip_cut, JP_BD_NCED.clip_cut
    src_ncop = src_ncop + src_ncop[-1] * 11
    src_nced = src_nced + src_nced[-1]
    src_03 = JP_BD_03.clip_cut

    src_ncop = flt.rekt(src_ncop)
    src_nced = flt.rekt(src_nced)
    src_03 = flt.rekt(src_03)

    # Fixing an animation error in the NCOP
    sqmask_ncop = lvf.mask.BoundingBox((419, 827), (1500, 68))
    masked_ncop = core.std.MaskedMerge(src_ncop, src_03, sqmask_ncop.get_mask(src_ncop))
    masked_ncop = lvf.rfs(src_ncop, masked_ncop, [(opstart+2064, opstart+2107)])

    op_mask = vdf.dcm(
        src_03, src_03[opstart:opstart+masked_ncop.num_frames-op_offset], masked_ncop[:-op_offset],
        start_frame=opstart, thr=85, prefilter=True) if opstart is not False \
        else get_y(core.std.BlankClip(src))
    op_mask = depth(core.resize.Bicubic(op_mask, 1296, 728).std.Crop(top=4, bottom=4), 16)

    # Stick credits ontop of NC because it looks way better
    masked_ncop = src_ncop.resize.Bicubic(chromaloc_in=1, chromaloc=0)
    cwarp_ncop = masked_ncop.warp.AWarpSharp2(thresh=88, blur=3, type=1, depth=6, planes=[1, 2])
    descale_ncop = lvf.kernels.Bicubic().descale(plane(depth(src_ncop, 16), 0), 1280, 720)
    chroma_down_ncop = core.resize.Bicubic(cwarp_ncop, 1280, 720, vs.YUV444P16)
    scaled_ncop = join([descale_ncop, plane(chroma_down_ncop, 1), plane(chroma_down_ncop, 2)])
    scaled_ncop = scaled_ncop.resize.Bicubic(1296, 728).std.Crop(top=4, bottom=4)
    downscale_03 = src_03.resize.Bicubic(1296, 728, vs.YUV444P16).std.Crop(top=4, bottom=4)
    merge_credits_03 = core.std.MaskedMerge(scaled_ncop, downscale_03, op_mask)

    for prop, val in PROPS_DVD:
        src = src.std.SetFrameProp(prop, intval=val)

    dvd_i444 = vdf.scale.to_444(depth(src, 32), src.width, src.height, join_planes=True)
    dvd_rgb = dvd_i444.resize.Bicubic(format=vs.RGB24, dither_type='error_diffusion', matrix_in=6)

    upscale = vsgan.run(dvd_rgb)
    conv = core.resize.Bicubic(upscale, format=vs.YUV444P16, matrix=1)
    scaled = depth(muf.SSIM_downsample(conv, 1296, 720), 16)

    splice_op = lvf.rfs(scaled, merge_credits_03, [(0, 203), (263, 1740), (1836, 2018)])

    # Splicing for the ED. Halves of the ED have visuals, others are credits
    masked_nced = src_nced.resize.Bicubic(chromaloc_in=1, chromaloc=0)
    cwarp_nced = masked_nced.warp.AWarpSharp2(thresh=88, blur=3, type=1, depth=6, planes=[1, 2])
    descale_nced = lvf.kernels.Bicubic().descale(plane(depth(src_nced, 16), 0), 1280, 720)
    chroma_down_nced = core.resize.Bicubic(cwarp_nced, 1280, 720, vs.YUV444P16)
    scaled_nced = join([descale_nced, plane(chroma_down_nced, 1), plane(chroma_down_nced, 2)])
    scaled_nced = scaled_nced.resize.Bicubic(1296, 728).std.Crop(top=4, bottom=4)

    ed_nc = scaled_nced
    ed_dvd = splice_op[31888:]

    sq_top = lvf.mask.BoundingBox((0, 0), (ed_nc.width, ed_nc.height/2)).get_mask(ed_nc)
    sq_left = lvf.mask.BoundingBox((0, 0), (ed_nc.width/2, ed_nc.height)).get_mask(ed_nc)
    sq_right = sq_left.std.Invert()

    mask_top = core.std.MaskedMerge(ed_dvd, ed_nc, sq_top)
    mask_left = core.std.MaskedMerge(ed_dvd, ed_nc, sq_left)
    mask_right = core.std.MaskedMerge(ed_dvd, ed_nc, sq_right)

    ed_splice = lvf.rfs(ed_dvd, mask_top, [(0, 1213), (1613, 1673), (1794, None)])
    ed_splice = lvf.rfs(ed_splice, mask_left, [(1390, 1503)])
    ed_splice = lvf.rfs(ed_splice, mask_right, [(1214, 1389), (1504, 1612), (1674, 1793)])

    splice_ed = insert_clip(splice_op, ed_splice, edstart)

    # Back to more regular filtering
    stab = haf.GSMC(splice_ed, radius=2, planes=[0])
    decs = vdf.noise.decsiz(stab, sigmaS=8, min_in=208 << 8, max_in=232 << 8)

    detail_mask = flt.detail_mask(decs, brz=(1800, 3500))
    deband = dbs.debanders.dumb3kdb(decs, threshold=32, grain=16)
    deband_masked = core.std.MaskedMerge(deband, decs, detail_mask)

    grain = vdf.noise.Graigasm(  # Mostly stolen from Varde tbh
        thrs=[x << 8 for x in (32, 80, 128, 176)],
        strengths=[(0.25, 0.0), (0.2, 0.0), (0.15, 0.0), (0.0, 0.0)],
        sizes=(1.2, 1.15, 1.05, 1),
        sharps=(65, 50, 40, 40),
        grainers=[
            vdf.noise.AddGrain(seed=69420, constant=True),
            vdf.noise.AddGrain(seed=69420, constant=False),
            vdf.noise.AddGrain(seed=69420, constant=False)
        ]).graining(deband_masked)

    return grain
Example #15
0
    def main(self) -> vs.VideoNode:
        """Vapoursynth filtering"""
        src = JPBD.clip_cut
        src = depth(src, 16)
        src_cru = WEB_CRU.clip_cut
        src_aod = WEB_AOD.clip_cut


        # Dehardsubbing using .ass file
        masksub = Mask.hardsub_mask(src_aod.std.BlankClip(), SUB, FONTDIR)
        dehardsub = core.std.MaskedMerge(src_aod, src_cru, masksub)
        src_web = dehardsub


        # AoD is poorly rescaled
        src_y, src_cru_y, src_web_y = map(get_y, [src, src_cru, src_web])

        thr = 10
        src_web_y = core.std.Expr([src_web_y, src_cru_y], f'x y - abs {thr} < x y * sqrt y ?')
        src_web_y = depth(src_web_y, 16)

        ringrid = core.rgvs.Repair(src_web_y, src_web_y.std.Convolution([1]*9), 11)
        ringrid = core.std.Expr([ringrid, src_web_y], 'x y min')

        # Remove ringing with AoD+CR
        ring_mask = Mask.ringing_mask(src_y)
        bdweb = core.std.MaskedMerge(src_y, ringrid, ring_mask)
        out = vdf.misc.merge_chroma(bdweb, src)



        # Restore BD changes
        dering_src = hvf.EdgeCleaner(src, 20, hot=True)

        diff_mask = Mask.diff_mask((src, src_cru), brz=4750.0)
        bdchanges = core.std.MaskedMerge(out, dering_src, diff_mask)
        bdchanges = lvf.rfs(out, bdchanges, [(17008, 17085), (17200, 17283)])
        bdchanges = lvf.rfs(bdchanges, src, [(17551, 17730)])
        out = bdchanges


        ref = Denoise.ref_denoise(get_y(out), tr=1)
        denoise = Denoise.hybrid_denoise(
            depth(out, 32), knlm_h=0.15, sigma=1,
            knlm_args=dict(d=1, a=3, s=3), bm3d_args=dict(ref=depth(ref, 32))
        )
        denoise = depth(denoise, 16)
        out = denoise



        pre = get_y(out)


        # Remove haloing
        dehalo = gf.MaskedDHA(pre, rx=1.4, ry=1.4, darkstr=0.1, brightstr=1.0, maskpull=40, maskpush=255)
        bila = core.bilateral.Bilateral(dehalo, sigmaS=1, sigmaR=0.08)
        dehalorp = core.rgvs.Repair(dehalo, bila, 13)
        dehalo = core.std.MaskedMerge(dehalo, dehalorp, ring_mask.std.Maximum(), 0)
        dehalo = core.std.Expr([dehalo, pre], 'x y min')
        out = dehalo




        # Antialiasing sraaaaaaaaaa
        lineart = vdf.mask.ExPrewitt().get_mask(out, 4000, 7500).std.Convolution([1] * 25)
        aaa = AA().upscaled_sraaaaaaaaaa(out, height=1620)
        out = aaa




        unwarp = self.line_darkening(out, 0.075).warp.AWarpSharp2(depth=-1)
        out = unwarp


        motion = hvf.SMDegrain(out, tr=3, thSADC=600, RefineMotion=True)
        masked = core.std.MaskedMerge(out, motion, lineart)
        out = masked




        mergechroma = vdf.misc.merge_chroma(out, denoise)
        out = mergechroma


        ref = depth(src_cru, 16)
        cred_mask = Mask.credits_mask(src, JPBD_NCOP.clip_cut, JPBD_NCED.clip_cut, OPSTART, OPEND, EDSTART, EDEND)
        cred = out
        cred = lvf.rfs(cred, core.std.MaskedMerge(cred, ref, cred_mask, 0), [(OPSTART, OPEND), (EDSTART, EDEND)])
        out = cred



        db_mask = Mask.deband_mask(out, (4000, 4000, 4000), (2000, 2000, 2000))

        deband_1 = vdf.deband.dumb3kdb(out, 17, [36, 48])
        deband_2 = vdf.deband.dumb3kdb(out, 17, 30, sample_mode=4, use_neo=True)
        deband_a = vdf.placebo.deband(out, 22, threshold=8, iterations=3, grain=0)


        th_lo, th_hi = 22 << 8, 28 << 8
        strength = f'{th_hi} x - {th_hi} {th_lo} - /'
        deband = core.std.Expr(
            [out.std.Convolution([1]*9), deband_1, deband_2],
            [f'x {th_lo} > x {th_hi} < and z ' + strength + ' * y 1 ' + strength + f' - * + x {th_lo} <= z y ? ?',
             'x y * sqrt x z * sqrt * y * z * 0.25 pow'])

        deband = lvf.rfs(deband, deband_a, [(OPSTART+1382, OPSTART+1433)])
        deband = core.std.MaskedMerge(deband, out, db_mask)
        out = deband



        newpan = self.refine_motion(out[17284:17329], [1, 5, 9, 14, 18, 22, 27, 31, 35], out)
        motion = insert_clip(out, newpan, 17284)
        out = motion





        ref = get_y(out).std.PlaneStats()
        adgmask_a = ref.adg.Mask(25)
        adgmask_b = ref.adg.Mask(10)

        stgrain_a = core.grain.Add(out, 0.1, 0, seed=333, constant=True)
        stgrain_a = core.std.MaskedMerge(out, stgrain_a, adgmask_b.std.Invert())

        stgrain_b = sizedgrn(out, 0.2, 0.1, 1.15, sharp=80, static=True, fade_edges=False, protect_neutral=False, seed=333)
        stgrain_b = core.std.MaskedMerge(out, stgrain_b, adgmask_b)
        stgrain_b = core.std.MaskedMerge(out, stgrain_b, adgmask_a.std.Invert())
        stgrain = core.std.MergeDiff(stgrain_b, out.std.MakeDiff(stgrain_a))

        dygrain = sizedgrn(out, 0.3, 0.1, 1.25, sharp=80, static=False, fade_edges=False, protect_neutral=False, seed=333)
        dygrain = core.std.MaskedMerge(out, dygrain, adgmask_a)
        grain = core.std.MergeDiff(dygrain, out.std.MakeDiff(stgrain))
        out = grain


        return depth(out, 10).std.Limiter(16 << 2, [235 << 2, 240 << 2], [0, 1, 2])
Example #16
0
def do_filter():
    """Vapoursynth filtering"""
    src = JPBD.src_cut
    ep10 = JPBD_10.src_cut

    h = 720
    w = get_w(h)
    b, c = vdf.get_bicubic_params('robidoux')
    opstart, opend = 672, 3068
    edstart, edend = 31888, src.num_frames - 1
    opstart_ep10, opend_ep10 = 768, 3164
    full_stuff = [(3853, 3984), (16130, 16279)]

    # Fix borders of the henshin
    start, end = 26596, 27387
    white_clip = core.std.BlankClip(src, color=[235, 128, 128])

    # Good length for the three henshins
    hibiki = TRANSFOS.src_cut[912:1716]
    hibiki = core.std.DeleteFrames(hibiki, [203, 204])
    hibiki = core.std.DeleteFrames(hibiki, range(316, 320))
    hibiki = core.std.DeleteFrames(hibiki, range(391, 394))

    tsubasa = TRANSFOS.src_cut[2178:2738]
    tsubasa = core.std.DuplicateFrames(white_clip[:8] + tsubasa, range(10, 20))
    tsubasa = core.std.DuplicateFrames(tsubasa, range(196, 203))
    tsubasa = core.std.DuplicateFrames(tsubasa, [443, 443, 443])

    yukine = TRANSFOS.src_cut[3240:3828]

    # The intro
    intro = 203
    new_tranfos = hibiki[:intro]

    # Adjust croppings
    hibiki_crop_a = core.std.Crop(hibiki[intro:], src.width / 3, src.width / 3,
                                  0, 0)
    dev = -150
    hibiki_crop_b = core.std.Crop(hibiki[intro:], src.width / 3 + dev,
                                  src.width / 3 - dev, 0, 0)
    dev = -270
    hibiki_crop_c = core.std.Crop(hibiki[intro:], src.width / 3 + dev,
                                  src.width / 3 - dev, 0, 0)
    hibiki_crop = lvf.rfs(hibiki_crop_a, hibiki_crop_b,
                          [(391 - intro, 471 - intro)])
    hibiki_crop = lvf.rfs(hibiki_crop, hibiki_crop_c,
                          [(472 - intro, 552 - intro)])

    tsubasa_crop_a = core.std.Crop(tsubasa, src.width / 3, src.width / 3, 0, 0)
    dev = -400
    tsubasa_crop_b = core.std.Crop(tsubasa, src.width / 3 + dev,
                                   src.width / 3 - dev, 0, 0)
    tsubasa_crop = lvf.rfs(tsubasa_crop_a, tsubasa_crop_b,
                           [(445 - intro, 460 - intro)])
    tsubasa_crop = (tsubasa_crop[:461 - intro] + core.std.FrameEval(
        tsubasa_crop[461 - intro:478 - intro],
        partial(_prog_crop, clip=tsubasa[461 - intro:478 - intro], dev=dev)) +
                    tsubasa_crop[478 - intro:])

    yukine_crop = core.std.Crop(yukine, src.width / 3, src.width / 3, 0, 0)

    # Stack & merge
    new_tranfos += core.std.StackHorizontal(
        [tsubasa_crop, hibiki_crop, yukine_crop])
    src = insert_clip(src, new_tranfos[:end - start], start)

    # Fix compositing error in the OP
    op_src, op_10 = src[opstart:opend + 1], ep10[opstart_ep10:opend_ep10 + 1]
    fix = lvf.rfs(op_src, op_10, [(0, 79), (1035, 1037)])
    fix_src = insert_clip(src, fix, opstart)
    src = depth(fix_src, 32)

    denoise = hybrid_denoise(src, 0.5, 2)
    out = denoise

    luma = get_y(out)
    line_mask = vdf.edge_detect(luma, 'FDOG', 0.05, (1, 1))

    descale = core.descale.Debicubic(luma, w, h, b, c)
    upscale = vdf.fsrcnnx_upscale(descale, None, descale.height * 2,
                                  '_shaders/FSRCNNX_x2_56-16-4-1.glsl',
                                  core.resize.Point)
    upscale_smooth = vdf.nnedi3_upscale(descale, pscrn=1)
    upscale = vdf.fade_filter(upscale, upscale, upscale_smooth, 18018, 18068)
    upscale = lvf.rfs(upscale, upscale_smooth, [(18068, 18134)])

    antialias = single_rate_antialiasing(upscale,
                                         13,
                                         alpha=0.3,
                                         beta=0.45,
                                         gamma=320,
                                         mdis=18)

    scaled = muvf.SSIM_downsample(antialias,
                                  src.width,
                                  src.height,
                                  kernel='Bicubic')
    rescale = core.std.MaskedMerge(luma, scaled, line_mask)
    merged = vdf.merge_chroma(rescale, out)
    out = depth(merged, 16)

    antialias = lvf.rfs(
        out,
        lvf.sraa(out,
                 1.65,
                 9,
                 alpha=0.3,
                 beta=0.45,
                 gamma=240,
                 nrad=3,
                 mdis=25), [(opstart + 840, opstart + 881)])
    antialias_a = lvf.sraa(out,
                           1.3,
                           3,
                           alpha=0.3,
                           beta=0.45,
                           gamma=40,
                           nrad=3,
                           mdis=25)
    antialias_b = lvf.sraa(out,
                           1.85,
                           13,
                           alpha=0.3,
                           beta=0.6,
                           gamma=400,
                           nrad=2,
                           mdis=15)
    antialias = vdf.fade_filter(antialias, antialias_a, antialias_b, 12718,
                                12861)
    antialias = lvf.rfs(antialias, antialias_b, [(24063, 24149)])
    out = antialias

    # Slight sharp though CAS
    sharp = hvf.LSFmod(out,
                       strength=75,
                       Smode=3,
                       Lmode=1,
                       edgemode=1,
                       edgemaskHQ=True)
    out = sharp

    dering = gf.HQDeringmod(out, thr=16, darkthr=0.1)
    out = dering

    warp = xvs.WarpFixChromaBlend(out, thresh=48, depth=8)
    out = warp

    preden = core.knlm.KNLMeansCL(out,
                                  d=0,
                                  a=3,
                                  h=0.6,
                                  device_type='GPU',
                                  channels='Y')
    deband_mask = lvf.denoise.detail_mask(preden, brz_a=2000, brz_b=800, rad=4)

    deband = dbs.f3kpf(out, 17, 42, 42)
    deband_b = placebo.deband(out, 22, 6, 2)
    deband = lvf.rfs(deband, deband_b, [(opstart + 1515, opstart + 1603)])

    deband_c = placebo.deband(out, 10, 3, 1)
    deband = lvf.rfs(deband, deband_c, [(241, 300), (11076, 11183)])

    deband = core.std.MaskedMerge(deband, out, deband_mask)

    out = deband

    adg_mask = core.adg.Mask(out.std.PlaneStats(),
                             20).std.Expr(f'x x {128<<8} - 0.25 * +')
    grain = core.grain.Add(out, 0.2, constant=True)
    grain = core.std.MaskedMerge(out, grain, adg_mask, 0)
    out = grain

    rescale_mask = vdf.drm(luma, b=b, c=c, sw=4, sh=4)
    ref, rescale_mask, src, src_ncop, src_nced = [
        depth(x, 16) for x in
        [denoise, rescale_mask, src, JPBD_NCOP.src_cut, JPBD_NCED.src_cut]
    ]

    credit = lvf.rfs(out, core.std.MaskedMerge(out, ref, rescale_mask),
                     full_stuff)
    out = credit

    src_c, src_ncop, src_nced = [
        c.knlm.KNLMeansCL(a=7, h=35, d=0, device_type='gpu')
        for c in [src, src_ncop, src_nced]
    ]

    opening_mask = vdf.dcm(out, src_c[opstart:opend + 1],
                           src_ncop[:opend - opstart + 1], opstart, opend, 4,
                           4).std.Inflate()
    ending_mask = vdf.dcm(out, src_c[edstart:edend + 1],
                          src_nced[:edend - edstart + 1], edstart, edend, 4,
                          4).std.Inflate()
    credit_mask = core.std.Expr([opening_mask, ending_mask], 'x y +')

    credit = lvf.rfs(out, core.std.MaskedMerge(out, ref, credit_mask),
                     [(opstart, opend), (edstart, edend)])
    out = credit

    return depth(out, 10)
Example #17
0
def recursive_apply_mask(
    src_a: vs.VideoNode,
    src_b: vs.VideoNode,
    mask_folder: Union[str, Path],
    iter: int = 1,
) -> vs.VideoNode:
    """
    Recursively check `mask_folder` for a .png or .ass file
    After it found all of them, it will use the mask
    to merge together the two clips.

    Acceptable filename format:
    - frameNum.png
    - frameStart-frameEnd.png
    - itsUpToYou.ass
    Example:
    - 2500.png
    - 2000-2004.png
    - maskep1.ass

    Parameters
    ----------
    src_a: :class:`VideoNode`
        The first clip.
    src_b: :class:`VideoNode`
        The second clip.
    mask_folder: :class:`Union[str, Path]`
        The folder that contains the masks.
    iter: :class:`int`
        How many times we will need to iterate the mask.

    Returns
    -------
    :class:`VideoNode`
        The merged clip.
    """

    if isinstance(mask_folder, str):
        mask_folder = Path(mask_folder)
    has_plugin_or_raise(["fmtc", "imwri"])

    imwri = core.imwri
    masks_png = mask_folder.glob("*.png")
    for mask in masks_png:
        frame = os_path.basename(mask).rsplit(".", 1)[0]
        frame = [int(i) for i in frame.split("-")][:2]
        if len(frame) < 2:
            frame = [frame[0], frame[0]]
        first_f, last_f = frame

        image = fvf.Depth(
            imwri.Read(str(mask), ).resize.Point(format=vs.GRAYS,
                                                 matrix_s="709"),
            src_a.format.bits_per_sample,
        ).std.AssumeFPS(
            fpsnum=src_a.fps.numerator,
            fpsden=src_a.fps.denominator,
        )

        src_a_n, src_b_n = src_a[first_f:last_f + 1], src_b[first_f:last_f + 1]

        image = image * ((last_f + 1) - first_f)
        image = get_y(image)
        src_masked = core.std.MaskedMerge(src_a_n, src_b_n, image)
        for _ in range(iter - 1):
            src_masked = src_masked.std.MaskedMerge(src_b_n, image)
        src_a = insert_clip(src_a, insert=src_masked, start_frame=first_f)

    masks_ass = mask_folder.glob("*.ass")
    for mask in masks_ass:
        blank_mask = src_a.std.BlankClip()
        ass_mask = get_y(blank_mask.sub.TextFile(str(mask)))

        src_a = core.std.MaskedMerge(src_a, src_b, ass_mask)
    return src_a
Example #18
0
def do_filter():
    """Vapoursynth filtering"""
    src = JPBD.src_cut
    ep10 = JPBD_10.src_cut

    h = 720
    w = get_w(h)
    b, c = vdf.get_bicubic_params('robidoux')
    opstart, opend = 744, 3140
    opstart_ep10, opend_ep10 = 768, 3164
    full_stuff = [(3145, 3269), (18289, 18444), (29158, 33410)]

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 2),
                           right=1212)
    fixstudioshit = lvf.rfs(src, border, [31759])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1212)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31760])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1274)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [(31761, 31762)])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1300)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31763])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1322)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31764])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1342)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31765])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1356)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31766])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1368)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31767])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1376)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [31768])

    border = rkt.rekt_fast(src,
                           lambda x: core.fb.FillBorders(x, 0, 0, 0, 6),
                           right=1382)
    fixstudioshit = lvf.rfs(fixstudioshit, border, [(31769, 31793)])

    src = fixstudioshit

    # Fix compositing error in the OP
    op_src, op_10 = src[opstart:opend + 1], ep10[opstart_ep10:opend_ep10 + 1]
    fix = lvf.rfs(op_src, op_10, [(0, 79), (1035, 1037)])
    fix_src = insert_clip(src, fix, opstart)
    src = depth(fix_src, 32)

    denoise = hybrid_denoise(src, 0.5, 2)
    out = denoise

    luma = get_y(out)
    line_mask = vdf.edge_detect(luma, 'FDOG', 0.05, (1, 1))

    descale = core.descale.Debicubic(luma, w, h, b, c)
    upscale = vdf.fsrcnnx_upscale(descale, None, descale.height * 2,
                                  '_shaders/FSRCNNX_x2_56-16-4-1.glsl',
                                  core.resize.Point)

    antialias = single_rate_antialiasing(upscale,
                                         13,
                                         alpha=0.3,
                                         beta=0.45,
                                         gamma=320,
                                         mdis=18)

    scaled = muvf.SSIM_downsample(antialias,
                                  src.width,
                                  src.height,
                                  kernel='Bicubic')
    rescale = core.std.MaskedMerge(luma, scaled, line_mask)
    merged = vdf.merge_chroma(rescale, out)
    out = depth(merged, 16)

    antialias = lvf.rfs(
        out,
        lvf.sraa(out,
                 1.65,
                 9,
                 alpha=0.3,
                 beta=0.45,
                 gamma=240,
                 nrad=3,
                 mdis=25), [(opstart + 840, opstart + 881)])
    out = antialias

    # Slight sharp though CAS
    sharp = hvf.LSFmod(out,
                       strength=75,
                       Smode=3,
                       Lmode=1,
                       edgemode=1,
                       edgemaskHQ=True)
    out = sharp

    dering = gf.HQDeringmod(out, thr=16, darkthr=0.1)
    out = dering

    warp = xvs.WarpFixChromaBlend(out, thresh=48, depth=8)
    out = warp

    preden = core.knlm.KNLMeansCL(out,
                                  d=0,
                                  a=3,
                                  h=0.6,
                                  device_type='GPU',
                                  channels='Y')
    deband_mask = lvf.denoise.detail_mask(preden, brz_a=2000, brz_b=800, rad=4)

    deband = dbs.f3kpf(out, 17, 42, 42)
    deband_b = placebo.deband(out, 22, 6, 2)
    deband = lvf.rfs(deband, deband_b, [(opstart + 1515, opstart + 1603)])

    deband_c = placebo.deband(out, 17, 6, 3)
    deband = lvf.rfs(deband, deband_c, [(12529, 12615)])

    deband_d = placebo.deband(out, 10, 3, 1)
    deband = lvf.rfs(deband, deband_d, [(21077, 21304), (22141, 22278),
                                        (22861, 22944), (29354, 29425),
                                        (33555, 33614)])

    deband = core.std.MaskedMerge(deband, out, deband_mask)

    out = deband

    adg_mask = core.adg.Mask(out.std.PlaneStats(),
                             20).std.Expr(f'x x {128<<8} - 0.25 * +')
    grain = core.grain.Add(out, 0.2, constant=True)
    grain = core.std.MaskedMerge(out, grain, adg_mask, 0)
    out = grain

    rescale_mask = vdf.drm(luma, b=b, c=c, sw=4, sh=4)
    ref, rescale_mask, src, src_ncop = [
        depth(x, 16) for x in [denoise, rescale_mask, src, JPBD_NCOP.src_cut]
    ]

    credit = lvf.rfs(out, core.std.MaskedMerge(out, ref, rescale_mask),
                     full_stuff)
    out = credit

    src_c, src_ncop = [
        c.knlm.KNLMeansCL(a=7, h=35, d=0, device_type='gpu')
        for c in [src, src_ncop]
    ]

    opening_mask = vdf.dcm(out, src_c[opstart:opend + 1],
                           src_ncop[:opend - opstart + 1], opstart, opend, 4,
                           4).std.Inflate()

    credit = lvf.rfs(out, core.std.MaskedMerge(out, ref, opening_mask),
                     [(opstart, opend)])
    out = credit

    return depth(out, 10)
Example #19
0
def filterchain() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
    """Vapoursynth filtering"""
    import lvsfunc as lvf
    import rekt
    import vardefunc as vdf
    from awsmfunc import bbmod
    from muvsfunc import SSIM_downsample
    from vsutil import depth, get_y, insert_clip, join, plane

    src = JP_BD.clip_cut

    # Fixing animation f**k-ups
    if freeze_ranges:
        src = core.std.FreezeFrames(
            src,
            [s[0] for s in freeze_ranges],
            [e[1] for e in freeze_ranges],
            [f[2] for f in freeze_ranges]
        )

    # Edgefixing
    ef = rekt.rektlvls(
        src, prot_val=[16, 235], min=16, max=235,
        rownum=[0, src.height-1], rowval=[16, 16],
        colnum=[0, src.width-1], colval=[16, 16],
    )

    bb_y = bbmod(ef, left=1, top=1, right=1, bottom=1, thresh=32, y=True, u=False, v=False)
    bb_uv = bbmod(bb_y, left=2, top=2, right=2, bottom=2, y=False, u=True, v=True)

    cshift = flt.shift_chroma(bb_uv, left=0.6)
    cshift = lvf.rfs(bb_uv, cshift, cshift_left_ranges)

    bb32 = depth(cshift, 32)
    bb32_y = get_y(bb32)

    # Descaling + DPIR while it's at a lower res (so I can actually run it because >memory issues xd)
    descale = lvf.kernels.Catrom().descale(bb32_y, 1280, 720)
    downscale = lvf.kernels.Catrom(format=vs.YUV444PS).scale(bb32, 1280, 720)
    descale_444 = join([descale, plane(downscale, 1), plane(downscale, 2)])
    denoise_y = lvf.deblock.vsdpir(descale_444, strength=2.75, mode='deblock', matrix=1, i444=True, cuda=True)

    supersample = vdf.scale.fsrcnnx_upscale(get_y(denoise_y), shader_file=shader_file, downscaler=None)
    downscaled = SSIM_downsample(supersample, src.width, src.height, smooth=((3 ** 2 - 1) / 12) ** 0.5,
                                 sigmoid=True, filter_param_a=0, filter_param_b=0)

    # Create credit mask
    upscale = lvf.kernels.Catrom().scale(descale, src.width, src.height)
    credit_mask = lvf.scale.descale_detail_mask(bb32_y, upscale, threshold=0.055) \
        .std.Deflate().std.Deflate().std.Minimum()

    # Merge early for additional accuracy with DPIR
    merged = core.std.MaskedMerge(downscaled, bb32_y, credit_mask)

    down_y = lvf.kernels.Catrom().scale(merged, src.width/2, src.height/2)
    down_i444 = join([down_y, plane(bb32, 1), plane(bb32, 2)])
    deblock_down = lvf.deblock.vsdpir(down_i444, strength=3, mode='denoise', matrix=1, i444=True, cuda=True)

    scaled = depth(join([merged, plane(deblock_down, 1), plane(deblock_down, 2)]), 16)

    # Final bit of "denoising"
    dft = core.dfttest.DFTTest(scaled, sigma=2.0, tbsize=5, tosize=3, planes=[0])
    decs = vdf.noise.decsiz(dft, sigmaS=4, min_in=208 << 8, max_in=232 << 8)

    # AA
    baa = lvf.aa.based_aa(decs, str(shader_file))
    sraa = lvf.sraa(decs, rfactor=1.65)
    clmp = lvf.aa.clamp_aa(decs, baa, sraa, strength=1.3)

    dehalo = lvf.dehalo.masked_dha(clmp, rx=1.4, ry=1.4, brightstr=0.4)
    cwarp = core.warp.AWarpSharp2(dehalo, thresh=72, blur=3, type=1, depth=4, planes=[1, 2])

    # Merge credits (if applicable)
    merged = core.std.MaskedMerge(cwarp, depth(bb32, 16), depth(credit_mask, 16))

    deband = core.average.Mean([
        flt.masked_f3kdb(merged, rad=16, thr=[20, 24], grain=[24, 12]),
        flt.masked_f3kdb(merged, rad=20, thr=[28, 24], grain=[24, 12]),
        flt.masked_placebo(merged, rad=6, thr=2.5, itr=2, grain=4)
    ])

    grain = vdf.noise.Graigasm(
        thrs=[x << 8 for x in (32, 80, 128, 176)],
        strengths=[(0.25, 0.0), (0.20, 0.0), (0.15, 0.0), (0.0, 0.0)],
        sizes=(1.20, 1.15, 1.10, 1),
        sharps=(80, 70, 60, 50),
        grainers=[
            vdf.noise.AddGrain(seed=69420, constant=False),
            vdf.noise.AddGrain(seed=69420, constant=False),
            vdf.noise.AddGrain(seed=69420, constant=True)
        ]).graining(deband)

    no_flt = lvf.rfs(grain, depth(bb32, 16), no_filter)

    if edstart is not False:
        src_nced = depth(JP_NCED.clip_cut, 16)
        no_flt = insert_clip(no_flt, src_nced, edstart)

    return no_flt
Example #20
0
def do_filter():
    """Vapoursynth filtering"""
    def _nneedi3_clamp(clip: vs.VideoNode, strength: int = 1)-> vs.VideoNode:
        bits = clip.format.bits_per_sample - 8
        thr = strength * (1 >> bits)

        luma = get_y(clip)

        def _strong(clip: vs.VideoNode)-> vs.VideoNode:
            args = dict(alpha=0.25, beta=0.5, gamma=40, nrad=2, mdis=20, vcheck=3)
            clip = core.eedi3m.EEDI3(clip, 1, True, **args).std.Transpose()
            clip = core.eedi3m.EEDI3(clip, 1, True, **args).std.Transpose()
            return core.resize.Spline36(clip, luma.width, luma.height, src_left=-.5, src_top=-.5)

        def _weak(clip: vs.VideoNode)-> vs.VideoNode:
            args = dict(nsize=3, nns=2, qual=2)
            clip = core.znedi3.nnedi3(clip, 1, True, **args).std.Transpose()
            clip = core.znedi3.nnedi3(clip, 1, True, **args).std.Transpose()
            return core.resize.Spline36(clip, luma.width, luma.height, src_left=-.5, src_top=-.5)

        clip_aa = core.std.Expr([_strong(luma), _weak(luma), luma],
                                'x z - y z - * 0 < y x y {0} + min y {0} - max ?'.format(thr))
        return vdf.merge_chroma(clip_aa, clip)


    def _perform_endcard(path: str, ref: vs.VideoNode)-> vs.VideoNode:
        endcard = lvf.src(path).std.AssumeFPS(ref)
        endcard = core.std.CropRel(endcard, left=7, top=0, right=11, bottom=22)
        endcard = core.resize.Bicubic(endcard, ref.width, ref.height, vs.RGBS, dither_type='error_diffusion')

        endcard = core.w2xc.Waifu2x(endcard, noise=3, scale=1, photo=True)

        endcard = core.resize.Bicubic(endcard, format=vs.YUV444PS, matrix_s='709', dither_type='error_diffusion')
        endcard = lvf.util.quick_resample(endcard, lambda c: core.neo_f3kdb.Deband(c, 15, 36, 36, 36, 24, 24, 4))

        return Tweak(endcard, sat=1.4, cont=1.2)


    def _perform_motion_mask(clip: vs.VideoNode, brz: int)-> vs.VideoNode:
        clip = depth(clip, 8)
        sup = core.hqdn3d.Hqdn3d(clip).neo_fft3d.FFT3D().mv.Super(sharp=1)
        fv1 = core.mv.Analyse(sup, isb=False, delta=1, truemotion=False, dct=2)
        fv2 = core.mv.Analyse(sup, isb=True, delta=1, truemotion=True, dct=2)

        momask1 = core.mv.Mask(clip, fv1, ml=2, kind=1)
        momask2 = core.mv.Mask(clip, fv2, ml=3, kind=1)
        momask = core.std.Merge(momask1, momask2).rgvs.RemoveGrain(3).std.Binarize(brz)
        momask = momask.std.Minimum().std.Minimum()

        return depth(get_y(momask), 16)


    src = JPBD.src_cut
    src = depth(src, 16)

    denoise_a = CoolDegrain(src, tr=2, thsad=48, blksize=8, overlap=4, plane=4)
    denoise = denoise_a


    antialias = _nneedi3_clamp(denoise)
    antialias_a = TAAmbk(antialias, aatype='Eedi3', cycle=3)
    antialias_b = lvf.sraa(denoise, 2, 13)

    motion_mask = _perform_motion_mask(denoise[16914:17001], 140).std.FreezeFrames([0, 18, 57], [2, 38, 86], [2, 38, 57])
    motion_mask = insert_clip(src.std.BlankClip(format=vs.GRAY16), motion_mask, 16914)


    antialias = lvf.rfs(antialias, core.std.MaskedMerge(antialias_a, antialias, motion_mask), [(16914, 17000)])
    antialias = lvf.rfs(antialias, antialias_b, [(18084, 18179)])


    predenoise = mClean(antialias, thSAD=200, chroma=False)
    detail_mask = lvf.denoise.detail_mask(predenoise, rad=2, radc=2, brz_a=3250, brz_b=1250)
    ret_mask = kgf.retinex_edgemask(predenoise).std.Binarize(9250).std.Median().std.Inflate()
    line_mask = core.std.Expr([detail_mask, ret_mask], 'x y max')


    deband_a = core.neo_f3kdb.Deband(antialias, 17, 42, 42, 42, 12, 0, sample_mode=4, keep_tv_range=True)
    deband_a = core.std.MaskedMerge(deband_a, antialias, line_mask)
    deband = deband_a


    grain = kgf.adaptive_grain(deband, 0.25, luma_scaling=10)


    ending = lvf.rfs(grain, src, [(32079, 33098)])


    endcard = _perform_endcard(r'[BDMV][200902][Magia Record][Vol.5]\Scans\endcard13_front_descreen.png', src)
    endcard_length = 119
    final = core.std.Splice([ending, endcard * endcard_length], True)
    final = core.resize.Bicubic(final, format=vs.YUV420P10, dither_type='error_diffusion')
    final = core.std.Limiter(final, 16, [235 << 2, 240 << 2])

    return depth(final, 10), endcard_length
Example #21
0
def filterchain() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
    """Main VapourSynth filterchain"""
    import EoEfunc as eoe
    import lvsfunc as lvf
    import vardefunc as vdf
    from ccd import ccd
    from finedehalo import fine_dehalo
    from vsutil import depth, get_y, insert_clip

    src = JP_BD.clip_cut
    src_c = src
    src_ncop, src_nced = JP_NCOP.clip_cut, JP_NCED.clip_cut
    b = core.std.BlankClip(src, length=1)

    # OP/ED stack comps to check if they line up
    if opstart is not False:
        op_scomp = lvf.scomp(src[opstart:opstart+src_ncop.num_frames-1]+b, src_ncop[:-op_offset]+b) \
            .text.Text('src', 7).text.Text('op', 9)
    if edstart is not False:
        ed_scomp = lvf.scomp(src[edstart:edstart+src_nced.num_frames-1]+b, src_nced[:-ed_offset]+b) \
            .text.Text('src', 7).text.Text('ed', 9)

    # Splicing in NCs and diff'ing back the credits
    if opstart is not False:
        src = insert_clip(src, src_ncop[:-op_offset], opstart)
        src = lvf.rfs(src, src_c, [(opstart + 811, opstart + 859)])
    if edstart is not False:
        src = insert_clip(src, src_nced[:-ed_offset], edstart)

    den_src, den_ncs = map(partial(core.dfttest.DFTTest, sigma=10),
                           [src_c, src])
    den_src, den_ncs = depth(den_src, 32), depth(den_ncs, 32)
    diff = core.std.MakeDiff(den_src, den_ncs).dfttest.DFTTest(sigma=50.0)

    # For some reason there's noise from previous credits remaining? Removing that here
    diff_brz = vdf.misc.merge_chroma(diff.std.Binarize(0.03), diff)
    diff = core.std.Expr([diff, diff_brz], "x y min")

    src = depth(src, 16)

    # This noise can burn in hell.
    denoise_pre = get_y(src.dfttest.DFTTest(sigma=1.0))
    denoise_ret = core.retinex.MSRCP(denoise_pre,
                                     sigma=[50, 200, 350],
                                     upper_thr=0.005)
    denoise_mask = flt.detail_mask(denoise_ret, sigma=2.0,
                                   lines_brz=3000).rgvs.RemoveGrain(4)

    denoise_pre = core.dfttest.DFTTest(src, sigma=4.0)
    denoise_smd = eoe.dn.CMDegrain(src,
                                   tr=5,
                                   thSAD=275,
                                   freq_merge=True,
                                   prefilter=denoise_pre)
    denoise_masked = core.std.MaskedMerge(denoise_smd, src, denoise_mask)

    denoise_uv = ccd(denoise_masked, threshold=6)
    decs = vdf.noise.decsiz(denoise_uv,
                            sigmaS=8,
                            min_in=200 << 8,
                            max_in=235 << 8)

    # F**K THIS SHOW'S LINEART HOLY SHIT
    baa = lvf.aa.based_aa(decs.std.Transpose(), str(shader_file), gamma=120)
    baa = lvf.aa.based_aa(baa.std.Transpose(), str(shader_file), gamma=120)
    sraa = lvf.sraa(decs, rfactor=1.4)
    clmp_aa = lvf.aa.clamp_aa(decs, baa, sraa, strength=1.65)

    # AAing introduces some haloing (zzzzzz)
    restr_edges = fine_dehalo(clmp_aa, decs)
    restr_dark = core.std.Expr([clmp_aa, restr_edges], "x y min")

    # Masking credits at the end if there's no NCED
    get_max = core.std.Expr([restr_dark, decs], "x y max")

    if opstart is False:
        restr_dark = lvf.rfs(restr_dark, get_max, [(None, 3500)])
    if edstart is False:
        restr_dark = lvf.rfs(restr_dark, get_max, [(-5000, None)])

    deband = core.average.Mean([
        flt.masked_f3kdb(restr_dark, rad=17, thr=[28, 20], grain=[12, 8]),
        flt.masked_f3kdb(restr_dark, rad=21, thr=[36, 32], grain=[24, 12]),
        flt.masked_placebo(restr_dark, rad=6.5, thr=2.5, itr=2, grain=4)
    ])

    grain = vdf.noise.Graigasm(thrs=[x << 8 for x in (32, 80, 128, 176)],
                               strengths=[(0.25, 0.0), (0.20, 0.0),
                                          (0.15, 0.0), (0.0, 0.0)],
                               sizes=(1.20, 1.15, 1.10, 1),
                               sharps=(80, 70, 60, 50),
                               grainers=[
                                   vdf.noise.AddGrain(seed=69420,
                                                      constant=True),
                                   vdf.noise.AddGrain(seed=69420,
                                                      constant=False),
                                   vdf.noise.AddGrain(seed=69420,
                                                      constant=False)
                               ]).graining(deband)

    merge_creds = core.std.MergeDiff(depth(grain, 32), diff)

    return merge_creds
Example #22
0
    def creditless(self, src_clip: vs.VideoNode, credit_clip: vs.VideoNode, nc_clip: vs.VideoNode,
                   start_frame: int, thr: int, expand: int = 2, *,
                   prefilter: bool = False, bilateral_args: Dict[str, Any] = {}) -> vs.VideoNode:
        """Makes a mask based on difference from 2 clips.

        Args:
            src_clip (vs.VideoNode):
                Source clip. Can be Gray, YUV or RGB.

            credit_clip (vs.VideoNode): Credit clip.
                It will be resampled according to the src_clip.

            nc_clip (vs.VideoNode): Creditless clip.
                It will be resampled according to the src_clip.

            start_frame (int): Start frame.

            thr (int): Binarize threshold.
                25 is a good starting value in 8 bit.

            expand (int, optional):
                Growing/shrinking shape. 0 is allowed. Defaults to 2.

            prefilter (bool, optional):
                Blurs the credit_clip and nc_clip with Bilateral to avoid false posivive
                such as noise and compression artifacts.
                Defaults to False.

            bilateral_args (Dict[str, Any], optional):
                Additionnal and overrided Bilateral parameters if prefilter=True. Defaults to {}.

        Returns:
            vs.VideoNode: Credit mask clip.

        Example:
            import vardefunc as vdf

            opstart, opend = 792, 2948

            opmask = diff_creditless_mask(clip, clip[opstart:opend+1], ncop[:opend+1-opstart], opstart, thr=25, prefilter=True)
        """
        if src_clip.format is None:
            raise FormatError('diff_creditless_mask: Variable format not allowed!')

        gray_only = src_clip.format.num_planes == 1
        clips = [credit_clip, nc_clip]

        if prefilter:
            bilargs: Dict[str, Any] = dict(sigmaS=((5 ** 2 - 1) / 12) ** 0.5, sigmaR=0.5)
            bilargs |= bilateral_args
            clips = [c.bilateral.Bilateral(**bilargs) for c in clips]


        clips = [
            c.resize.Bicubic(
                format=src_clip.format.replace(
                    bits_per_sample=get_depth(src_clip),
                    subsampling_w=0, subsampling_h=0).id
            ) for c in clips]

        diff = core.std.Expr(
            sum(map(split, clips), []),
            mae_expr(gray_only),
            format=src_clip.format.replace(color_family=vs.GRAY).id
        )

        mask = PrewittStd().get_mask(diff).std.Binarize(thr)
        mask = self._minmax(mask, 2 + expand, True)

        blank = core.std.BlankClip(
            src_clip, format=src_clip.format.replace(
                color_family=vs.GRAY, subsampling_w=0, subsampling_h=0
            ).id
        )
        mask = insert_clip(blank, mask, start_frame)

        return mask