aboutsummaryrefslogtreecommitdiffstats
path: root/youtube/watch_formats.py
blob: 7dad3252cd9f0109a29179a79d98135925971f5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""Video format helpers for yt-local."""

import math
from typing import Any, Dict, Optional


def codec_name(vcodec: str) -> str:
    """Extract codec short name from codec string."""
    if vcodec.startswith('avc'):
        return 'h264'
    elif vcodec.startswith('av01'):
        return 'av1'
    elif vcodec.startswith('vp'):
        return 'vp'
    else:
        return 'unknown'


def video_quality_string(fmt: Dict[str, Any]) -> str:
    """Return video quality string (e.g., '1920x1080 30fps')."""
    if fmt.get('vcodec'):
        result = f"{fmt.get('width') or '?'}x{fmt.get('height') or '?'}"
        if fmt.get('fps'):
            result += f" {fmt['fps']}fps"
        return result
    elif fmt.get('acodec'):
        return 'audio only'
    return '?'


def short_video_quality_string(fmt: Dict[str, Any]) -> str:
    """Return short video quality string (e.g., '1080p60 AV1')."""
    result = f"{fmt.get('quality') or '?'}p"
    if fmt.get('fps'):
        result += str(fmt['fps'])
    vcodec = fmt.get('vcodec', '')
    if vcodec.startswith('av01'):
        result += ' AV1'
    elif vcodec.startswith('avc'):
        result += ' h264'
    else:
        result += f" {vcodec}"
    return result


def audio_quality_string(fmt: Dict[str, Any]) -> str:
    """Return audio quality string (e.g., '128k 44.1kHz')."""
    if fmt.get('acodec'):
        if fmt.get('audio_bitrate'):
            result = f"{fmt['audio_bitrate']}k"
        else:
            result = '?k'
        if fmt.get('audio_sample_rate'):
            result += f" {'%.3G' % (fmt['audio_sample_rate']/1000)}kHz"
        return result
    elif fmt.get('vcodec'):
        return 'video only'
    return '?'


def format_bytes(bytes_val: Optional[float]) -> str:
    """Convert bytes to human-readable string (e.g., '1.5 MiB')."""
    if bytes_val is None:
        return 'N/A'
    if type(bytes_val) is str:
        bytes_val = float(bytes_val)
    if bytes_val == 0.0:
        exponent = 0
    else:
        exponent = int(math.log(bytes_val, 1024.0))
    suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
    converted = float(bytes_val) / float(1024 ** exponent)
    return '%.2f%s' % (converted, suffix)


__all__ = [
    'codec_name',
    'video_quality_string',
    'short_video_quality_string',
    'audio_quality_string',
    'format_bytes',
]