Repository: yt-dlp/yt-dlp
File: yt_dlp/extractor/bilibili.py (Python)

Code before:
                duration=traverse_obj(initial_state, ('videoData', 'duration', {int_or_none})),
                __post_extractor=self.extract_comments(aid))
        else:
            formats = self.extract_formats(play_info)

            if not traverse_obj(play_info, ('dash')):
                # we only have legacy formats and need additional work
                has_qn = lambda x: x in traverse_obj(formats, (..., 'quality'))
                for qn in traverse_obj(play_info, ('accept_quality', lambda _, v: not has_qn(v), {int})):
                    formats.extend(traverse_obj(
                        self.extract_formats(self._download_playinfo(video_id, cid, headers=headers, qn=qn)),
                        (lambda _, v: not has_qn(v.get('quality')))))
                self.check_missing_formats(play_info, formats)
                if traverse_obj(formats, lambda _, v: v['fragments']) and traverse_obj(formats, lambda _, v: not v.get('fragments')):  # We are having both flv and mp4 formats here
                    # Flv and mp4 are incompatible due to `multi_video` workaround, so we need to drop one of them
                    if not self._configuration_arg('_prefer_multi_flv'):
                        # `_prefer_multi_flv` is mainly for writing test case, user should hardly need this
                        dropping = ', '.join(traverse_obj(formats, (
                            lambda _, v: v['fragments'], {lambda x: f'"{x["format_note"]}" ({x["format_id"]})'})))
                        formats = traverse_obj(formats, lambda _, v: not v.get('fragments'))
                        if dropping:
                            self.to_screen(f'Dropping incompatible flv format(s) {dropping} when mp4 exists. Use `--extractor-args "bilibili:_prefer_multi_flv=1"` if you require flv formats.')
                    else:
                        formats = traverse_obj(
                            formats, lambda _, v: v['quality'] == int(self._configuration_arg('_prefer_multi_flv')[0]),
                        ) or [max(traverse_obj(formats, lambda _, v: v['fragments']), key=lambda x: x['quality'])]

            if formats[0].get('fragments'):
                # We have flv formats, which are individual short videos with their own timestamps and metainfo
                # Binary concatenation corrupts their timestamps, so we need a `multi_video` workaround
                return {
                    **metainfo,
                    '_type': 'multi_video',
                    'entries': [{
                        'id': f'{metainfo["id"]}_{idx}',
                        'title': metainfo['title'],
                        'http_headers': metainfo['http_headers'],
                        'formats': [{
                            **fragment,
                            'format_id': formats[0].get('format_id'),
                        }],
                        'subtitles': self.extract_subtitles(video_id, cid) if idx == 0 else None,
                        '__post_extractor': self.extract_comments(aid) if idx == 0 else None,
                    } for idx, fragment in enumerate(formats[0]['fragments'])],
                    'duration': float_or_none(play_info.get('timelength'), scale=1000),
                }
            else:
                return {
                    **metainfo,
                    'formats': formats,
                    'duration': float_or_none(play_info.get('timelength'), scale=1000),

Review comment (refactor):

```suggestion
                        formats = traverse_obj(
                            # XXX: Filtering by extractor-arg is for testing purposes
                            formats, lambda _, v: v['quality'] == int(self._configuration_arg('prefer_multi_flv')[0]),
                        ) or [max(flv_formats, key=lambda x: x['quality'])]
```

Code after:
            return self.playlist_result(
                self._get_interactive_entries(video_id, cid, metainfo, headers=headers), **metainfo,
                duration=traverse_obj(initial_state, ('videoData', 'duration', {int_or_none})),
                __post_extractor=self.extract_comments(aid))
        else:
            formats = self.extract_formats(play_info)

            if not traverse_obj(play_info, ('dash')):
                # we only have legacy formats and need additional work
                has_qn = lambda x: x in traverse_obj(formats, (..., 'quality'))
                for qn in traverse_obj(play_info, ('accept_quality', lambda _, v: not has_qn(v), {int})):
                    formats.extend(traverse_obj(
                        self.extract_formats(self._download_playinfo(video_id, cid, headers=headers, qn=qn)),
                        lambda _, v: not has_qn(v['quality'])))
                self._check_missing_formats(play_info, formats)
                flv_formats = traverse_obj(formats, lambda _, v: v['fragments'])
                if flv_formats and len(flv_formats) < len(formats):
                    # Flv and mp4 are incompatible due to `multi_video` workaround, so drop one
                    if not self._configuration_arg('prefer_multi_flv'):
                        dropped_fmts = ', '.join(
                            f'{f.get("format_note")} ({f.get("format_id")})' for f in flv_formats)
                        formats = traverse_obj(formats, lambda _, v: not v.get('fragments'))
                        if dropped_fmts:
                            self.to_screen(
                                f'Dropping incompatible flv format(s) {dropped_fmts} since mp4 is available. '
                                'To extract flv, pass --extractor-args "bilibili:prefer_multi_flv"')
                    else:
                        formats = traverse_obj(
                            # XXX: Filtering by extractor-arg is for testing purposes
                            formats, lambda _, v: v['quality'] == int(self._configuration_arg('prefer_multi_flv')[0]),
                        ) or [max(flv_formats, key=lambda x: x['quality'])]

            if traverse_obj(formats, (0, 'fragments')):
                # We have flv formats, which are individual short videos with their own timestamps and metainfo
                # Binary concatenation corrupts their timestamps, so we need a `multi_video` workaround
                return {
                    **metainfo,
                    '_type': 'multi_video',
                    'entries': [{
                        'id': f'{metainfo["id"]}_{idx}',
                        'title': metainfo['title'],
                        'http_headers': metainfo['http_headers'],
                        'formats': [{
                            **fragment,
                            'format_id': formats[0].get('format_id'),
                        }],
                        'subtitles': self.extract_subtitles(video_id, cid) if idx == 0 else None,
                        '__post_extractor': self.extract_comments(aid) if idx == 0 else None,
                    } for idx, fragment in enumerate(formats[0]['fragments'])],
                    'duration': float_or_none(play_info.get('timelength'), scale=1000),
                }