Recherche avancée

Médias (91)

Sur d’autres sites (351)

  • FFmpeg : Audio is sped up after compressing AVI video [closed]

    21 août 2023, par Karen S

    I have an AVI video and I want to reduce the file size. When I run the FFmpeg command below, the resulting audio in the video is sped up, and the last bit of the video has no audio.

    


    The FFmpeg command

    


    ffmpeg -i "in.avi" -vcodec libx264 -acodec copy -crf 26 -vf "scale=-1:'min(720,ih)', yadif=1" out.avi


    


    The output messages

    


    ffmpeg version 2023-06-11-git-09621fd7d9-full_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 12.2.0 (Rev10, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libaribb24 --enable-libaribcaption --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libjxl --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-liblensfun --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libvpl --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libcodec2 --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      58. 13.100 / 58. 13.100
  libavcodec     60. 17.100 / 60. 17.100
  libavformat    60.  6.100 / 60.  6.100
  libavdevice    60.  2.100 / 60.  2.100
  libavfilter     9.  8.101 /  9.  8.101
  libswscale      7.  3.100 /  7.  3.100
  libswresample   4. 11.100 /  4. 11.100
  libpostproc    57.  2.100 / 57.  2.100
[avi @ 000002255f70d540] Switching to NI mode, due to poor interleaving
Input #0, avi, from 'in.avi':
  Duration: 00:10:40.64, start: 0.000000, bitrate: 28852 kb/s
  Stream #0:0: Video: dvvideo, yuv411p, 720x480 [SAR 32:27 DAR 16:9], 25000 kb/s, SAR 8:9 DAR 4:3, 60k fps, 29.97 tbr, 60k tbn
  Stream #0:1: Audio: pcm_s16le, 48000 Hz, stereo, s16, 1536 kb/s
  Stream #0:2: Audio: pcm_s16le, 32000 Hz, stereo, s16, 1024 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (dvvideo (native) -> h264 (libx264))
  Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
[libx264 @ 000002255fbc4940] using SAR=8/9
[libx264 @ 000002255fbc4940] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 000002255fbc4940] profile High 4:2:2, level 3.1, 4:2:2, 8-bit
Output #0, avi, to 'out.avi':
  Metadata:
    ISFT            : Lavf60.6.100
  Stream #0:0: Video: h264 (H264 / 0x34363248), yuv422p(tv, progressive), 720x480 [SAR 8:9 DAR 4:3], q=2-31, 59.94 fps, 59.94 tbn
    Metadata:
      encoder         : Lavc60.17.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A
  Stream #0:1: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 48000 Hz, stereo, s16, 1536 kb/s
[dvvideo @ 000002255fb36d80] Concealing bitstream errors.33 bitrate=2437.5kbits/s speed=0.902x
    Last message repeated 15 times
[dvvideo @ 000002255fb36d80] Concealing bitstream errors.77 bitrate=2439.5kbits/s speed=0.902x
    Last message repeated 60 times
[dvvideo @ 0000022560071680] Concealing bitstream errors.72 bitrate=2461.8kbits/s speed=0.895x
    Last message repeated 18 times
[dvvideo @ 0000022560071680] Concealing bitstream errors.12 bitrate=2459.9kbits/s speed=0.894x
[out#0/avi @ 000002255f70d8c0] video:110055kB audio:80088kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.724923%
frame=38400 fps= 57 q=-1.0 Lsize=  191521kB time=00:10:40.60 bitrate=2449.2kbits/s speed=0.946x
[libx264 @ 000002255fbc4940] frame I:165   Avg QP:27.36  size: 37180
[libx264 @ 000002255fbc4940] frame P:9710  Avg QP:30.58  size:  7328
[libx264 @ 000002255fbc4940] frame B:28525 Avg QP:35.24  size:  1241
[libx264 @ 000002255fbc4940] consecutive B-frames:  0.8%  0.3%  0.3% 98.6%
[libx264 @ 000002255fbc4940] mb I  I16..4: 10.3% 67.6% 22.1%
[libx264 @ 000002255fbc4940] mb P  I16..4:  1.0%  3.8%  0.8%  P16..4: 40.7% 12.1%  8.6%  0.0%  0.0%    skip:33.0%
[libx264 @ 000002255fbc4940] mb B  I16..4:  0.1%  0.2%  0.0%  B16..8: 36.9%  1.8%  0.4%  direct: 1.4%  skip:59.1%  L0:45.0% L1:51.8% BI: 3.1%
[libx264 @ 000002255fbc4940] 8x8 transform intra:66.5% inter:68.7%
[libx264 @ 000002255fbc4940] coded y,uvDC,uvAC intra: 60.3% 64.7% 10.1% inter: 10.7% 6.9% 0.1%
[libx264 @ 000002255fbc4940] i16 v,h,dc,p: 21% 35% 10% 34%
[libx264 @ 000002255fbc4940] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 11% 23% 19%  6%  8%  7% 12%  6%  9%
[libx264 @ 000002255fbc4940] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 13% 25% 16%  6% 10%  7% 12%  5%  6%
[libx264 @ 000002255fbc4940] i8c dc,h,v,p: 58% 19% 18%  5%
[libx264 @ 000002255fbc4940] Weighted P-Frames: Y:3.0% UV:1.5%
[libx264 @ 000002255fbc4940] ref P L0: 56.9% 16.8% 19.3%  6.7%  0.2%
[libx264 @ 000002255fbc4940] ref B L0: 87.5% 10.4%  2.2%
[libx264 @ 000002255fbc4940] ref B L1: 93.2%  6.8%
[libx264 @ 000002255fbc4940] kb/s:1407.29


    


    Since the audio stream is being copied I don't understand why the resulting audio sounds sped up. The video looks fine, it's just the audio that is the issue.

    


    I've tried other options too, such as converting the audio to aac or mp3 and the resulting audio still sounds sped up and high pitched.

    


    Does anyone know why the audio isn't simply being copied the way it sounds in the original AVI video and do you have any suggestions for how to fix the issue ?

    


  • Youtube automatic creating and starting live stream with ffmpeg Python

    20 août 2023, par MrKolia1_1

    I'm trying to create a new broadcast on the channel and then start the stream so that the video is broadcast, the problem is that I can't start the broadcast after it is created, it is in the scheduled, how can I start the broadcast ?

    


    enter image description here

    


    import datetime
import json
import os
import threading
import time

import cv2
import subprocess
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

APP_TOKEN_FILE = "client_secret.json"
USER_TOKEN_FILE = "user_token.json"

SCOPES = [
    'https://www.googleapis.com/auth/youtube.force-ssl',
    'https://www.googleapis.com/auth/userinfo.profile',
]


def get_stream_info(stream_id):
    creds = get_creds_saved()
    service = build('youtube', 'v3', credentials=creds)

    request = service.liveBroadcasts().list(
        part='snippet,contentDetails,status',
        id=stream_id
    )

    response = request.execute()

    if 'items' in response and len(response['items']) > 0:
        return response['items'][0]
    else:
        return None


def get_creds_cons():
    # Create credentials via console flow
    flow = InstalledAppFlow.from_client_secrets_file(APP_TOKEN_FILE, SCOPES)
    return flow.run_console()


def get_creds_saved():
    creds = None

    if os.path.exists(USER_TOKEN_FILE):
        # Load user credentials from a saved file
        creds = Credentials.from_authorized_user_file(USER_TOKEN_FILE, SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # Create new credentials via local server flow
            flow = InstalledAppFlow.from_client_secrets_file(APP_TOKEN_FILE, SCOPES)
            creds = flow.run_local_server(port=0)

        with open(USER_TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())

    return creds


def get_service():
    # Get YouTube API service using credentials
    creds = get_creds_saved()
    service = build('youtube', 'v3', credentials=creds)
    return service


def create_live_stream(title, description):
    service = get_service()
    scheduled_start_time = datetime.datetime.utcnow().isoformat()

    request = service.liveBroadcasts().insert(
        part="snippet,status,contentDetails",
        body={
            "snippet": {
                "title": title,
                "description": description,
                "scheduledStartTime": scheduled_start_time,
            },
            "status": {
                "privacyStatus": "private",
                "lifeCycleStatus": "ready",
                "recordingStatus": "notRecording",
                "selfDeclaredMadeForKids": False
            },
            "contentDetails": {
                "enableAutoStart": False
            }
        }
    )
    response = request.execute()
    return response['id']


def stream_video(video_path, stream_key):
    args = [
        '-re',
        '-i', video_path,
        '-c:v', 'libx264',
        '-preset', 'veryfast',
        '-c:a', 'aac',
        '-f', 'flv',
        f'rtmp://a.rtmp.youtube.com/live2/{stream_key}'
    ]

    subprocess.run(['ffmpeg'] + args)


def get_scheduled_stream_info(stream_id):
    creds = get_creds_saved()
    service = build('youtube', 'v3', credentials=creds)

    request = service.liveBroadcasts().list(
        part='snippet,status',
        id=stream_id
    )

    response = request.execute()

    if 'items' in response and len(response['items']) > 0:
        return response['items'][0]
    else:
        return None



if __name__ == '__main__':
    print("** Hello, Azzrael_YT subscribers!!!\n")

    strId = create_live_stream("tittle", "description")
    pretty_json = json.dumps(get_scheduled_stream_info(strId), indent=4)

    print(pretty_json)

    # Stream video
    video_path = "C:/Users/admin/PycharmProjects/pythonProject/video.mp4"  # Update this with your video file path
    stream_key = 'dh9z-jtkx-wbq3-6wvp-2tac'  # Replace with your YouTube stream key
    video_thread = threading.Thread(target=stream_video, args=(video_path, stream_key))
    #video_thread.start()



    


    json responce info from created stream :
,
"scheduledStartTime" : "2023-08-20T10:51:22Z",
"isDefaultBroadcast" : false,
"liveChatId" : "KicKGFVDZ01UNS1CLVNfV0FJencxVXY4cC1ZQRILSG9QU0RJZ2hQMkE"
,
"status" : 
"lifeCycleStatus" : "created",
"privacyStatus" : "private",
"recordingStatus" : "notRecording",
"madeForKids" : false,
"selfDeclaredMadeForKids" : false



    


  • FFMPEG : TS video copied to MP4, missing 3 first frames [closed]

    21 août 2023, par Vasilis Lemonidis

    Running :

    


    ffmpeg -i test.ts -fflags +genpts -c copy -y test.mp4


    


    for this test.ts, which has 30 frames, readable by opencv, I end up with 28 frames, out of which 27 are readable by opencv. More specifically :

    


    ffprobe -v error -select_streams v:0 -count_packets  -show_entries stream=nb_read_packets -of csv=p=0 tmp.ts 


    


    returns 30.

    


    ffprobe -v error -select_streams v:0 -count_packets     -show_entries stream=nb_read_packets -of csv=p=0 tmp.mp4


    


    returns 28.

    


    Using OpenCV in that manner

    


    cap = cv2.VideoCapture(tmp_path)
readMat = []
while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        readMat.append(frame)


    


    I get for the ts file 30 frames, while for the mp4 27 frames.

    


    Could someone explain why the discrepancies ? I get no error during the transformation from ts to mp4 :

    


    ffmpeg version N-111746-gd53acf452f Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 11.3.0 (GCC)
  configuration: --ld=g++ --bindir=/bin --extra-libs='-lpthread -lm' --pkg-config-flags=--static --enable-static --enable-gpl --enable-libaom --enable-libass --enable-libfreetype --enable-libmp3lame --enable-libopus --enable-libsvtav1 --enable-libdav1d --enable-libvorbis --enable-libvpx --enable-libx264 --enable-libx265 --enable-nonfree --enable-cuda-nvcc --enable-cuvid --enable-nvenc --enable-libnpp 
  libavutil      58. 16.101 / 58. 16.101
  libavcodec     60. 23.100 / 60. 23.100
  libavformat    60. 10.100 / 60. 10.100
  libavdevice    60.  2.101 / 60.  2.101
  libavfilter     9. 10.100 /  9. 10.100
  libswscale      7.  3.100 /  7.  3.100
  libswresample   4. 11.100 /  4. 11.100
  libpostproc    57.  2.100 / 57.  2.100
[mpegts @ 0x4237240] DTS discontinuity in stream 0: packet 5 with DTS 306003, packet 6 with DTS 396001
Input #0, mpegts, from 'tmp.ts':
  Duration: 00:00:21.33, start: 3.400000, bitrate: 15 kb/s
  Program 1 
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
  Stream #0:0[0x100]: Video: h264 (High) ([27][0][0][0] / 0x001B), yuv420p(progressive), 300x300, 1 fps, 3 tbr, 90k tbn
Output #0, mp4, to 'test.mp4':
  Metadata:
    encoder         : Lavf60.10.100
  Stream #0:0: Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 300x300, q=2-31, 1 fps, 3 tbr, 90k tbn
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
Press [q] to stop, [?] for help
[out#0/mp4 @ 0x423e280] video:25kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 4.192123%
frame=   30 fps=0.0 q=-1.0 Lsize=      26kB time=00:00:21.00 bitrate=  10.3kbits/s speed=1e+04x 


    


    Additional information

    


    The origin of the video I am processing comes from a continuous stitching operation of still images ts videos, produced by this class update method :

    


    import cv2
import os
import subprocess
from tempfile import NamedTemporaryFile
class VideoUpdater:
    def __init__(
        self, video_path: str, framerate: int, timePerFrame: Optional[int] = None
    ):
        """
        Video updater takes in a video path, and updates it using a supplied frame, based on a given framerate.
        Args:
            video_path: str: Specify the path to the video file
            framerate: int: Set the frame rate of the video
        """
        if not video_path.endswith(".mp4"):
            LOGGER.warning(
                f"File type {os.path.splitext(video_path)[1]} not supported for streaming, switching to ts"
            )
            video_path = os.path.splitext(video_path)[0] + ".mp4"

        self._ps = None
        self.env = {
            
        }
        self.ffmpeg = "/usr/bin/ffmpeg "

        self.video_path = video_path
        self.ts_path = video_path.replace(".mp4", ".ts")
        self.tfile = None
        self.framerate = framerate
        self._video = None
        self.last_frame = None
        self.curr_frame = None


    def update(self, frame: np.ndarray):
        if len(frame.shape) == 2:
            frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
        else:
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
        self.writeFrame(frame)

    def writeFrame(self, frame: np.ndarray):
        """
        The writeFrame function takes a frame and writes it to the video file.
        Args:
            frame: np.ndarray: Write the frame to a temporary file
        """


        tImLFrame = NamedTemporaryFile(suffix=".png")
        tVidLFrame = NamedTemporaryFile(suffix=".ts")

        cv2.imwrite(tImLFrame.name, frame)
        ps = subprocess.Popen(
            self.ffmpeg
            + rf"-loop 1 -r {self.framerate} -i {tImLFrame.name} -t {self.framerate} -vcodec libx264 -pix_fmt yuv420p -y {tVidLFrame.name}",
            env=self.env,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        ps.communicate()
        if os.path.isfile(self.ts_path):
            # this does not work to watch, as timestamps are not updated
            ps = subprocess.Popen(
                self.ffmpeg
                + rf'-i "concat:{self.ts_path}|{tVidLFrame.name}" -c copy -y {self.ts_path.replace(".ts", ".bak.ts")}',
                env=self.env,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            ps.communicate()
            shutil.move(self.ts_path.replace(".ts", ".bak.ts"), self.ts_path)

        else:
            shutil.copyfile(tVidLFrame.name, self.ts_path)
        # fixing timestamps, we dont have to wait for this operation
        ps = subprocess.Popen(
            self.ffmpeg
            + rf"-i {self.ts_path} -fflags +genpts -c copy -y {self.video_path}",
            env=self.env,
            shell=True,
            # stdout=subprocess.PIPE,
            # stderr=subprocess.PIPE,
        )
        tImLFrame.close()
        tVidLFrame.close()