Newest 'ffmpeg' Questions - Stack Overflow

http://stackoverflow.com/questions/tagged/ffmpeg

Les articles publiés sur le site

  • Facebook Reels Upload always failing

    21 juin, par Evrard A.

    I'm trying to upload Reels through Facebook Graph API. The video is created with the following ffmpeg command.

    cmd = [
                'ffmpeg',
                '-i', video_path,
                '-i', voice_path,
                '-i', music_path,
    
                '-filter_complex',
                '[1:a]loudnorm=I=-16:LRA=11:TP=-1.5,adelay=0|0[a1];' +
                '[2:a]volume=0.2,afade=t=in:ss=0:d=0.02,afade=t=out:st=28:d=0.03[a2];' +
                '[a1][a2]amix=inputs=2:duration=first:dropout_transition=0[aout]',
    
                '-map', '0:v:0',
                '-map', '[aout]',
    
                '-vf',
                 f"subtitles='{str(ass_path)}',format=yuv420p,scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2,setsar=1",  # Incrustation des sous-titres
    
                '-r', '30',
                '-g', '60',
                '-keyint_min', '60',
                '-sc_threshold', '0',
                '-x264opts', 'no-scenecut',
    
                '-c:v', 'libx264',
                '-profile:v', 'baseline',
                '-level', '4.1',
                '-pix_fmt', 'yuv420p',
                '-color_range', 'tv',
                '-colorspace', 'bt709',
    
                '-b:v', '9500k',
                '-maxrate', '9500k',
                '-bufsize', '19000k',
    
                '-c:a', 'aac',
                '-b:a', '192k',
                '-ac', '2',
                '-ar', '48000',
    
                '-movflags', '+faststart',
                '-video_track_timescale', '15360',
                '-max_muxing_queue_size', '9999',
    
                '-y', self.output_video_path if self.output_video_path else f'{parts[0]}.subtitled.{parts[1]}'
            ]
    
            subprocess.run(cmd, check=True)
    

    Here is the class method I use to publish:

      import requests, os,  time
      from datetime import datetime, timedelta
      from moviepy.editor import VideoFileClip
       
      def post_reel(
          self,
          page_id: str,
          page_access_token: str,
          video_file_path: str,
          video_description: str,
          tags: list = None, # type: ignore
          publish_now: bool = True
      ):
          def extract_first_frame(video_path: str, output_image_path: str, time_in_seconds: float = 1):
              """
              Extrait une frame à time_in_seconds et la sauvegarde comme miniature.
              """
              try:
                  clip = VideoFileClip(video_path)
                  clip.save_frame(output_image_path, t=time_in_seconds)
                  print(f"[THUMBNAIL] Frame at {time_in_seconds}s saved to {output_image_path}")
                  return output_image_path
              except Exception as e:
                  print(f"[ERROR] Could not extract thumbnail: {str(e)}")
                  return None
    
          def wait_for_video_ready(video_id, page_access_token, timeout=300, poll_interval=10):
              """
              Attends que la vidéo soit complètement traitée et publiée.
              """
              status_url = f"{self.BASE_API_URL}/{video_id}"
              params = {
                  "access_token": page_access_token,
                  "fields": "status"
              }
    
              start = time.time()
              while time.time() - start < timeout:
                  try:
                      r = requests.get(url=status_url, params=params)
                      r.raise_for_status()
                      status = r.json().get("status", {})
                      processing = status.get("processing_phase", {}).get("status")
                      publishing = status.get("publishing_phase", {}).get("status")
                      video_status = status.get("video_status")
    
                      print(f"[WAIT] video_status={video_status}, processing={processing}, publishing={publishing}")
    
                      if processing == "complete" and publishing == "complete":
                          print("[READY] Reel processed and published")
                          return True
                      elif processing == "error":
                         print(r.json())
    
                  except Exception as e:
                      print(f"[ERROR] during polling: {e}")
    
                  time.sleep(poll_interval)
    
              print("[TIMEOUT] Video did not finish processing in time.")
              return False
    
          try:
              # Step 1: Initialize upload
              init_url = f"{self.BASE_API_URL}/{page_id}/video_reels"
              init_params = {"upload_phase": "start"}
              init_payload = {'access_token': page_access_token}
    
              r = requests.post(url=init_url, data=init_payload, params=init_params)
              r.raise_for_status()
              response = r.json()
              video_id = response["video_id"]
              upload_url = response["upload_url"]
              print(f"[INIT OK] Video ID: {video_id}")
    
              # Step 2: Upload video
              file_size = os.path.getsize(video_file_path)
              headers = {
                  'Authorization': f"OAuth {page_access_token}",
                  'offset': "0",
                  'file_size': str(file_size),
              }
    
              with open(video_file_path, 'rb') as f:
                  files = {'source': f}
                  r = requests.post(url=upload_url, data=files, headers=headers)
                  r.raise_for_status()
                  upload_response = r.json()
    
              if not upload_response.get("success"):
                  print("[ERROR] Upload failed.")
                  return None
              print(f"[UPLOAD OK]")
    
              # Step 3: Check video status
              status_check_url = f'{self.BASE_API_URL}/{video_id}'
              check_params = {
                  "access_token": page_access_token,
                  "fields": "status"
              }
              r = requests.get(url=status_check_url, params=check_params)
              r.raise_for_status()
              print(f"[STATUS CHECK] {r.json()}")
    
              # Step 4: Finalize video
              finalize_params = {
                  "video_id": video_id,
                  "upload_phase": "finish",
                  "published": "true",
                  "access_token": page_access_token,
                  "video_state": "PUBLISHED" if publish_now else "SCHEDULED",
                  "title": video_description,
                  "description": video_description
              }
    
              if not publish_now:
                  finalize_params["scheduled_publish_time"] = int((datetime.now() + timedelta(days=1)).timestamp())
    
              if tags:
                  finalize_params["tags"] = ",".join(tags)
    
              r = requests.post(url=init_url, params=finalize_params, headers=headers)
              r.raise_for_status()
              finalize_response = r.json()
              post_id = finalize_response.get("post_id")
              print(f"[FINALIZE OK] Post ID: {post_id}")
              
              # WAIT UNTIL PUBLISHED
              if not wait_for_video_ready(video_id, page_access_token):
                  print("[ERROR] Reel processing timeout or failure")
                  return None
              
              # Step 5: Extract and upload thumbnail
              thumbnail_path = f"temp_thumb_{video_id}.jpg"
              if extract_first_frame(video_file_path, thumbnail_path):
                  thumb_url = f"{self.BASE_API_URL}/{video_id}/thumbnails"
                  with open(thumbnail_path, 'rb') as img:
                      files = {'source': img}
                      thumb_payload = {'access_token': page_access_token}
                      r = requests.post(url=thumb_url, files=files, data=thumb_payload)
                      r.raise_for_status()
                      print("[THUMBNAIL UPLOADED]")
                  # Clean up temp file
                  os.remove(thumbnail_path)
                  print("[THUMBNAIL CLEANED UP]")
    
              return post_id
    
          except Exception as e:
              print(f"[ERROR] {str(e)}")
              return None
    

    Here are the logs I get :

    • [INIT OK] Video ID: 1020853163558419
    • [UPLOAD OK]
    • [STATUS CHECK]
    {
      "status": {
        "video_status": "upload_complete",
        "uploading_phase": {
          "status": "complete",
          "bytes_transferred": 37780189
        },
        "processing_phase": {
          "status": "not_started"
        },
        "publishing_phase": {
          "status": "not_started"
        },
        "copyright_check_status": {
          "status": "in_progress"
        }
      },
      "id": "1020853163558419"
    }
    
    • [FINALIZE OK] Post ID: 122162302376476425
    • [WAIT] video_status=upload_complete, processing=not_started, publishing=not_started
    • [WAIT] video_status=error, processing=error, publishing=not_started
    {
      "status": {
        "video_status": "error",
        "uploading_phase": {
          "status": "complete",
          "bytes_transferred": 37780189
        },
        "processing_phase": {
          "status": "error",
          "errors": [
            {
              "code": 1363008,
              "message": "Video Creation failed, please try again."
            }
          ]
        },
        "publishing_phase": {
          "status": "not_started"
        },
        "copyright_check_status": {
          "status": "in_progress"
        }
      },
      "id": "1020853163558419"
    }
    

    It seems the error code 1363008 is related to the video properties format but even after following Facebook Reels video format recommandations, I can't make it work.

    Can you help me with this please ?

    I failed getting usefull help with ChatGPT 😅, and thanks in advance for anyone who answers or comments my question.

  • How to convert cmd pipe to powershell in context of binary data (ffmpeg and streamlink)

    20 juin, par Filip Krawczyk

    I'd like to convert a pipe of video stream between streamlink and ffmpeg from cmd to Powershell. But from what I searched powershell only supports piping objects.

    Is there any way to reproduce this in Powershell without using Start-Process -FilePath "cmd" -ArgumentList [...]? I'd prefer not to use it because I need access to the exit code.

    streamlink $stream_url best -O | ffmpeg -i pipe: "output_file.mp4"
    

    note: the line above had some args removed for better clarity

  • "Could not find com.arthenica:ffmpeg-kit-https:6.0-2" after ffmpeg_kit_flutter deprecation

    20 juin, par Tarun Hasija

    I am at latest flutter 3.32.4

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':ffmpeg_kit_flutter:compileDebugJavaWithJavac'.
    > Could not resolve all files for configuration ':ffmpeg_kit_flutter:debugCompileClasspath'.
       > Could not find com.arthenica:ffmpeg-kit-https:6.0-2.
         Required by:
             project :ffmpeg_kit_flutter
    
    * Try:
    > Run with --stacktrace option to get the stack trace.
    > Run with --info or --debug option to get more log output.
    > Run with --scan to get full insights.
    > Get more help at https://help.gradle.org.
    
    BUILD FAILED in 25s
    Error: Gradle task assembleStagingDebug failed with exit code 1
    
  • How to join two images into one with FFmpeg ? [duplicate]

    20 juin, par n2v2rda2

    There are two images: a.jpg and b.jpg.

    I just want to know how to join them into one image using ffmpeg.

    How should I finish the ffmpeg -i a.jpg -i b.jpg command to get a c.jpg output image?

    This is an example of what I am trying to achieve:

    1. a.jpg

      a.jpg

    2. b.jpg

      b.jpg

    3. c.jpg

      a.jpg and b.jpg side-by-side on one image

  • Can't convert .ts files that downloaded from .m3u8 file to mp4

    20 juin, par smartnima

    I Have This Files:

    001.ts  014.ts  027.ts  040.ts  053.ts  066.ts  079.ts  092.ts  105.ts  118.ts  131.ts  144.ts  157.ts  170.ts  183.ts  196.ts  209.ts  222.ts  235.ts  248.ts  261.ts  274.ts  287.ts  300.ts  313.ts  326.ts
    002.ts  015.ts  028.ts  041.ts  054.ts  067.ts  080.ts  093.ts  106.ts  119.ts  132.ts  145.ts  158.ts  171.ts  184.ts  197.ts  210.ts  223.ts  236.ts  249.ts  262.ts  275.ts  288.ts  301.ts  314.ts  327.ts
    003.ts  016.ts  029.ts  042.ts  055.ts  068.ts  081.ts  094.ts  107.ts  120.ts  133.ts  146.ts  159.ts  172.ts  185.ts  198.ts  211.ts  224.ts  237.ts  250.ts  263.ts  276.ts  289.ts  302.ts  315.ts  328.ts
    004.ts  017.ts  030.ts  043.ts  056.ts  069.ts  082.ts  095.ts  108.ts  121.ts  134.ts  147.ts  160.ts  173.ts  186.ts  199.ts  212.ts  225.ts  238.ts  251.ts  264.ts  277.ts  290.ts  303.ts  316.ts  329.ts
    005.ts  018.ts  031.ts  044.ts  057.ts  070.ts  083.ts  096.ts  109.ts  122.ts  135.ts  148.ts  161.ts  174.ts  187.ts  200.ts  213.ts  226.ts  239.ts  252.ts  265.ts  278.ts  291.ts  304.ts  317.ts  330.ts
    006.ts  019.ts  032.ts  045.ts  058.ts  071.ts  084.ts  097.ts  110.ts  123.ts  136.ts  149.ts  162.ts  175.ts  188.ts  201.ts  214.ts  227.ts  240.ts  253.ts  266.ts  279.ts  292.ts  305.ts  318.ts  331.ts
    007.ts  020.ts  033.ts  046.ts  059.ts  072.ts  085.ts  098.ts  111.ts  124.ts  137.ts  150.ts  163.ts  176.ts  189.ts  202.ts  215.ts  228.ts  241.ts  254.ts  267.ts  280.ts  293.ts  306.ts  319.ts  332.ts
    008.ts  021.ts  034.ts  047.ts  060.ts  073.ts  086.ts  099.ts  112.ts  125.ts  138.ts  151.ts  164.ts  177.ts  190.ts  203.ts  216.ts  229.ts  242.ts  255.ts  268.ts  281.ts  294.ts  307.ts  320.ts  333.ts
    009.ts  022.ts  035.ts  048.ts  061.ts  074.ts  087.ts  100.ts  113.ts  126.ts  139.ts  152.ts  165.ts  178.ts  191.ts  204.ts  217.ts  230.ts  243.ts  256.ts  269.ts  282.ts  295.ts  308.ts  321.ts  334.ts
    010.ts  023.ts  036.ts  049.ts  062.ts  075.ts  088.ts  101.ts  114.ts  127.ts  140.ts  153.ts  166.ts  179.ts  192.ts  205.ts  218.ts  231.ts  244.ts  257.ts  270.ts  283.ts  296.ts  309.ts  322.ts
    011.ts  024.ts  037.ts  050.ts  063.ts  076.ts  089.ts  102.ts  115.ts  128.ts  141.ts  154.ts  167.ts  180.ts  193.ts  206.ts  219.ts  232.ts  245.ts  258.ts  271.ts  284.ts  297.ts  310.ts  323.ts
    012.ts  025.ts  038.ts  051.ts  064.ts  077.ts  090.ts  103.ts  116.ts  129.ts  142.ts  155.ts  168.ts  181.ts  194.ts  207.ts  220.ts  233.ts  246.ts  259.ts  272.ts  285.ts  298.ts  311.ts  324.ts
    013.ts  026.ts  039.ts  052.ts  065.ts  078.ts  091.ts  104.ts  117.ts  130.ts  143.ts  156.ts  169.ts  182.ts  195.ts  208.ts  221.ts  234.ts  247.ts  260.ts  273.ts  286.ts  299.ts  312.ts  325.ts
    

    That I Downloaded With This Python Program (m3u8 File Does Not Work!):

    import requests
    import shutil
    import os
    import subprocess
    
    
    def strip_end(text, suffix):
        if not text.endswith(suffix):
            return text
        return text[:len(text)-len(suffix)]
    
    
    def download_file(url):
        cwd = os.getcwd()
        command = f"wget -O {cwd}/ts_files/{url.split('/')[-1]} {url}"
        subprocess.call(command, shell=True)
    
    
    base_url = "https://stream.example.com/video/2021/example/720p_{}.ts"
    
    if not os.path.exists('ts_files'):
        print('ts_file folder is not found, creating the folder.')
        os.makedirs('ts_files')
    
    i = 1
    while True:
        if len(str(i)) == 1:
            num = f"00{i}"
        elif len(str(i)) == 2:
            num = f"0{i}"
        else:
            num = str(i)
        url = base_url.replace("{}", num)
        r = requests.get(url, stream=True)
        print(f'downloading {i}')
        if r.status_code != 404:
            download_file(url)  # comment out this line to download ts files.
        else:
            print("404")
            break
        i = i+1
    
    cwd = os.getcwd()  # Get the current working directory (cwd)
    TS_DIR = 'ts_files'
    with open('merged.ts', 'wb') as merged:
        for ts_file in os.listdir(f'{cwd}/{TS_DIR}'):
            with open(f'{cwd}/{TS_DIR}/{ts_file}', 'rb') as mergefile:
                shutil.copyfileobj(mergefile, merged)
    
    

    My Problem Is When I Want To Convert All This Files To One .ts File And Then An MP4 File With ffmpeg, I Get An Error:

    nima@funlife:~/ts_files$ cat ./*.ts > all.ts
    nima@funlife:~/ts_files$ ffmpeg -i all.ts -acodec copy -vcodec copy all.mp4
    ffmpeg version 5.0.1-3+b1 Copyright (c) 2000-2022 the FFmpeg developers
      built with gcc 11 (Debian 11.3.0-4)
      configuration: --prefix=/usr --extra-version=3+b1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libdav1d --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libglslang --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librabbitmq --enable-librist --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libsvtav1 --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzimg --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opencl --enable-opengl --enable-sdl2 --disable-sndio --enable-pocketsphinx --enable-librsvg --enable-libmfx --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libplacebo --enable-libx264 --enable-shared
      libavutil      57. 17.100 / 57. 17.100
      libavcodec     59. 18.100 / 59. 18.100
      libavformat    59. 16.100 / 59. 16.100
      libavdevice    59.  4.100 / 59.  4.100
      libavfilter     8. 24.100 /  8. 24.100
      libswscale      6.  4.100 /  6.  4.100
      libswresample   4.  3.100 /  4.  3.100
      libpostproc    56.  3.100 / 56.  3.100
    all.ts: Invalid data found when processing input
    

    .ts Files Content Is Like This:

     }��,.g���}��
                 �����c����Ww�c���c���eo��m�����ŧ�  䱉
    �b(+��D�FG�zPe��7�&#bz�1ɶ���                      C
    �`,��>Ϲc4J��̀��T�I}�"��ކ�R�1��w͋�   "� <�#B`ƪ�̸�co
                                                 �9���+��W�
    P���N���w��T\5g��
    \�E�N�E�v��͑4f��U�@]�ΩX�U�x�E��bwm=ְ�iA�����p���M�����\=�_�I3C�hL�h����0)�ο��*��`���eZ� �ؗ4To�0V��S,�+�>�8_]�W�lNJD�|7e�2s�1X)̃5�0h�������~8ߩg���?e��EK�>۷�L
                 ��:6|������>\  �N�WW��,�w
    bk��1?*��/��/�5��k����~��                 Lޕ}�a���2�{��l��$�d=����g�{a2��L�����
                             jҫַ��ʿ�"1`ZZ.he)�=�x��E_4:Vg�����H=���x1�����}��W::y�
    

    Are They Encrypted Or Something? I'm Trying To Do This Works With Debian 11.3.0-4, Python 3.10.5

    Edit: Thanks Johnny, I Saw This Post: How to concatenate two MP4 files using FFmpeg? I Tried But I Get An Error Again!

    nima@funlife:~/ts_files$ ffmpeg -f concat -i file.txt -c copy output.ts
    ffmpeg version 5.0.1-3+b1 Copyright (c) 2000-2022 the FFmpeg developers
      built with gcc 11 (Debian 11.3.0-4)
      configuration: --prefix=/usr --extra-version=3+b1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libdav1d --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libglslang --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librabbitmq --enable-librist --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libsrt --enable-libssh --enable-libsvtav1 --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzimg --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opencl --enable-opengl --enable-sdl2 --disable-sndio --enable-pocketsphinx --enable-librsvg --enable-libmfx --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libplacebo --enable-libx264 --enable-shared
      libavutil      57. 17.100 / 57. 17.100
      libavcodec     59. 18.100 / 59. 18.100
      libavformat    59. 16.100 / 59. 16.100
      libavdevice    59.  4.100 / 59.  4.100
      libavfilter     8. 24.100 /  8. 24.100
      libswscale      6.  4.100 /  6.  4.100
      libswresample   4.  3.100 /  4.  3.100
      libpostproc    56.  3.100 / 56.  3.100
    [concat @ 0x55932dbf2500] Impossible to open '001.ts'
    file.txt: Invalid data found when processing input
    

    Same Error With ffmpeg -f concat -safe 0 -i file.txt -c copy output.ts

    file.txt is The List Of Files!