Newest 'ffmpeg' Questions - Stack Overflow

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

Les articles publiés sur le site

  • encoding with ffmpeg libx265 -pix_fmt gray gives unplayable vid

    9 juin 2017, par netjiro

    What am I missing? I encode an old black and white film clip with ffmpeg libx265 passing -pix_fmt gray. The output is unplayable in both vlc and mplayer (linux), so I assume I'm missing something...

    encoding:

    ffmpeg -i clip.mkv \
        -c:v libx265 -preset slow -x265-params "crf=24" -pix_fmt gray \
        -c:a libopus -b:a 64k \
        -c:s copy \
        out.mkv
    

    vlc errors:

    [00007f8a3ddfe328] blend blend error: no matching alpha blending routine (chroma: RGBA -> GREY)
    [00007f8a3ddfe328] core blend error: blending RGBA to GREY failed
    ... repeated ...
    

    mplayer errors:

    Unexpected decoder output format Planar Y800
    ... repeated ...
    

    ffmpeg encoding output:

    ffmpeg version 3.2.4 Copyright (c) 2000-2017 the FFmpeg developers
      built with gcc 4.9.4 (Gentoo 4.9.4 p1.0, pie-0.6.4)
      configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --docdir=/usr/share/doc/ffmpeg-3.2.4/html --mandir=/usr/share/man --enable-shared --cc=x86_64-pc-linux-gnu-gcc --cxx=x86_64-pc-linux-gnu-g++ --ar=x86_64-pc-linux-gnu-ar --optflags='-march=native -O2 -pipe' --disable-static --enable-avfilter --enable-avresample --disable-stripping --enable-nonfree --enable-version3 --disable-indev=oss --disable-indev=jack --disable-outdev=oss --enable-version3 --enable-bzlib --disable-runtime-cpudetect --disable-debug --disable-gcrypt --disable-gnutls --disable-gmp --enable-gpl --enable-hardcoded-tables --enable-iconv --enable-lzma --enable-network --enable-openssl --enable-postproc --disable-libsmbclient --enable-ffplay --enable-sdl2 --enable-vaapi --enable-vdpau --enable-xlib --enable-libxcb --enable-libxcb-shm --enable-libxcb-xfixes --enable-zlib --enable-libcdio --disable-libiec61883 --disable-libdc1394 --disable-libcaca --enable-openal --enable-opengl --enable-libv4l2 --disable-libpulse --enable-libopencore-amrwb --enable-libopencore-amrnb --disable-libfdk-aac --enable-libopenjpeg --enable-libbluray --enable-libcelt --disable-libgme --disable-libgsm --disable-mmal --enable-libmodplug --enable-libopus --disable-libilbc --disable-librtmp --enable-libssh --enable-libschroedinger --enable-libspeex --enable-libvorbis --enable-libvpx --disable-libzvbi --disable-libbs2b --disable-chromaprint --disable-libebur128 --disable-libflite --disable-frei0r --disable-libfribidi --enable-fontconfig --disable-ladspa --disable-libass --enable-libfreetype --disable-librubberband --disable-libzimg --enable-libsoxr --enable-pthreads --enable-libvo-amrwbenc --enable-libmp3lame --disable-libkvazaar --disable-nvenc --disable-libopenh264 --enable-libsnappy --enable-libtheora --enable-libtwolame --enable-libwavpack --disable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --disable-amd3dnow --disable-amd3dnowext --disable-fma4 --disable-xop --cpu=host --disable-doc --disable-htmlpages --enable-manpages
      libavutil      55. 34.101 / 55. 34.101
      libavcodec     57. 64.101 / 57. 64.101
      libavformat    57. 56.101 / 57. 56.101
      libavdevice    57.  1.100 / 57.  1.100
      libavfilter     6. 65.100 /  6. 65.100
      libavresample   3.  1.  0 /  3.  1.  0
      libswscale      4.  2.100 /  4.  2.100
      libswresample   2.  3.100 /  2.  3.100
      libpostproc    54.  1.100 / 54.  1.100
    x265 [info]: HEVC encoder version 2.2
    x265 [info]: build info [Linux][GCC 4.9.4][64 bit] 8bit+10bit+12bit
    x265 [info]: using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX AVX2 FMA3 LZCNT BMI2
    x265 [info]: Unknown profile, Level-3.1 (Main tier)
    x265 [warning]: No thread pool allocated, --wpp disabled
    x265 [warning]: No thread pool allocated, --lookahead-slices disabled
    x265 [info]: Slices                              : 1
    x265 [info]: frame threads / pool features       : 3 / none
    x265 [info]: Coding QT: max CU size, min CU size : 64 / 8
    x265 [info]: Residual QT: max TU size, max depth : 32 / 1 inter / 1 intra
    x265 [info]: ME / range / subpel / merge         : star / 57 / 3 / 3
    x265 [info]: Keyframe min / max / scenecut / bias: 23 / 250 / 40 / 5.00
    x265 [info]: Lookahead / bframes / badapt        : 25 / 4 / 2
    x265 [info]: b-pyramid / weightp / weightb       : 1 / 1 / 0
    x265 [info]: References / ref-limit  cu / depth  : 4 / on / on
    x265 [info]: AQ: mode / str / qg-size / cu-tree  : 1 / 1.0 / 32 / 1
    x265 [info]: Rate Control / qCompress            : CRF-24.0 / 0.60
    x265 [info]: tools: rect limit-modes rd=4 psy-rd=2.00 rdoq=2 psy-rdoq=1.00
    x265 [info]: tools: rskip signhide tmvp strong-intra-smoothing deblock sao
    Output #0, matroska, to 'out.mkv':
      Metadata:
        encoder         : Lavf57.56.101
        Metadata:
        Stream #0:0(eng): Video: hevc (libx265), gray, 1280x720 [SAR 1:1 DAR 16:9], q=2-31, 23.98 fps, 1k tbn, 23.98 tbc (default)
        Metadata:
          encoder         : Lavc57.64.101 libx265
        Stream #0:1(eng): Audio: opus (libopus) ([255][255][255][255] / 0xFFFFFFFF), 48000 Hz, stereo, flt, 64 kb/s (default)
        Metadata:
          encoder         : Lavc57.64.101 libopus
        Stream #0:2(eng): Subtitle: subrip (default)
    Stream mapping:
      Stream #0:0 -> #0:0 (h264 (native) -> hevc (libx265))
      Stream #0:1 -> #0:1 (eac3 (native) -> opus (libopus))
      Stream #0:3 -> #0:2 (copy)
    Press [q] to stop, [?] for help
    frame= 1439 fps=7.0 q=-0.0 Lsize=    5356kB time=00:01:00.01 bitrate= 731.1kbits/s speed=0.294x    
    video:4940kB audio:382kB subtitle:1kB other streams:0kB global headers:2kB muxing overhead: 0.629434%
    x265 [info]: frame I:      9, Avg QP:22.27  kb/s: 6064.82 
    x265 [info]: frame P:    340, Avg QP:23.62  kb/s: 1950.21 
    x265 [info]: frame B:   1090, Avg QP:29.65  kb/s: 230.75  
    x265 [info]: Weighted P-Frames: Y:0.9% UV:0.0%
    x265 [info]: consecutive B-frames: 2.9% 0.3% 1.4% 72.5% 22.9% 
    
  • Cutting a live stream into separate mp4 files

    9 juin 2017, par Fearhunter

    I am doing a research for cutting a live stream in piece and save it as mp4 files. I am using this source for the proof of concept:

    https://docs.microsoft.com/en-us/azure/media-services/media-services-dotnet-creating-live-encoder-enabled-channel#download-sample

    And this is the example code I use:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.WindowsAzure.MediaServices.Client;
    using Newtonsoft.Json.Linq;
    
    namespace AMSLiveTest
    {
        class Program
        {
            private const string StreamingEndpointName = "streamingendpoint001";
            private const string ChannelName = "channel001";
            private const string AssetlName = "asset001";
            private const string ProgramlName = "program001";
    
            // Read values from the App.config file.
            private static readonly string _mediaServicesAccountName =
            ConfigurationManager.AppSettings["MediaServicesAccountName"];
            private static readonly string _mediaServicesAccountKey =
            ConfigurationManager.AppSettings["MediaServicesAccountKey"];
    
            // Field for service context.
            private static CloudMediaContext _context = null;
            private static MediaServicesCredentials _cachedCredentials = null;
    
            static void Main(string[] args)
            {
                // Create and cache the Media Services credentials in a static class variable.
                _cachedCredentials = new MediaServicesCredentials(
                _mediaServicesAccountName,
                _mediaServicesAccountKey);
                // Used the cached credentials to create CloudMediaContext.
                _context = new CloudMediaContext(_cachedCredentials);
    
                IChannel channel = CreateAndStartChannel();
    
                // Set the Live Encoder to point to the channel's input endpoint:
                string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString();
    
                // Use the previewEndpoint to preview and verify
                // that the input from the encoder is actually reaching the Channel.
                string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString();
    
                IProgram program = CreateAndStartProgram(channel);
                ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength);
                IStreamingEndpoint streamingEndpoint = CreateAndStartStreamingEndpoint();
                GetLocatorsInAllStreamingEndpoints(program.Asset);
    
                // Once you are done streaming, clean up your resources.
                Cleanup(streamingEndpoint, channel);
            }
    
            public static IChannel CreateAndStartChannel()
            {
                //If you want to change the Smooth fragments to HLS segment ratio, you would set the ChannelCreationOptions’s Output property.
    
                IChannel channel = _context.Channels.Create(
                new ChannelCreationOptions
                {
                Name = ChannelName,
                Input = CreateChannelInput(),
                Preview = CreateChannelPreview()
                });
    
                //Starting and stopping Channels can take some time to execute. To determine the state of operations after calling Start or Stop, query the IChannel.State .
    
                channel.Start();
    
                return channel;
            }
    
            private static ChannelInput CreateChannelInput()
            {
                return new ChannelInput
                {
                    StreamingProtocol = StreamingProtocol.RTMP,
                    AccessControl = new ChannelAccessControl
                    {
                        IPAllowList = new List
                                {
                                new IPRange
                            {
                                Name = "TestChannelInput001",
                                // Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
                                // will allow access to IP addresses.
                                Address = IPAddress.Parse("0.0.0.0"),
                                SubnetPrefixLength = 0
                            }
                        }
                    }
                };
            }
    
            private static ChannelPreview CreateChannelPreview()
            {
                return new ChannelPreview
                {
                    AccessControl = new ChannelAccessControl
                    {
                        IPAllowList = new List
                        {
                            new IPRange
                            {
                                Name = "TestChannelPreview001",
                                // Setting 0.0.0.0 for Address and 0 for SubnetPrefixLength
                                // will allow access to IP addresses.
                                Address = IPAddress.Parse("0.0.0.0"),
                                SubnetPrefixLength = 0
                            }
                        }
                    }
                };
            }
    
            public static void UpdateCrossSiteAccessPoliciesForChannel(IChannel channel)
            {
                var clientPolicy =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
                
                    
                        
                            
                                
                            
                            
                               "" include-subpaths=""true""/>
                            
                        
                    
                ";
    
                var xdomainPolicy =
                    @"<?xml version=""1.0"" ?>
                
                    
                ";
    
                channel.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
                channel.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;
    
                channel.Update();
            }
    
            public static IProgram CreateAndStartProgram(IChannel channel)
            {
                IAsset asset = _context.Assets.Create(AssetlName, AssetCreationOptions.None);
    
                // Create a Program on the Channel. You can have multiple Programs that overlap or are sequential;
                // however each Program must have a unique name within your Media Services account.
                IProgram program = channel.Programs.Create(ProgramlName, TimeSpan.FromHours(3), asset.Id);
                program.Start();
    
                return program;
            }
    
            public static ILocator CreateLocatorForAsset(IAsset asset, TimeSpan ArchiveWindowLength)
            {
                // You cannot create a streaming locator using an AccessPolicy that includes write or delete permissions.            
    
                var locator = _context.Locators.CreateLocator
                    (
                        LocatorType.OnDemandOrigin,
                        asset,
                        _context.AccessPolicies.Create
                        (
                            "Live Stream Policy",
                            ArchiveWindowLength,
                            AccessPermissions.Read
                        )
                    );
    
                return locator;
            }
    
            public static IStreamingEndpoint CreateAndStartStreamingEndpoint()
            {
                var options = new StreamingEndpointCreationOptions
                {
                    Name = StreamingEndpointName,
                    ScaleUnits = 1,
                    AccessControl = GetAccessControl(),
                    CacheControl = GetCacheControl()
                };
    
                IStreamingEndpoint streamingEndpoint = _context.StreamingEndpoints.Create(options);
                streamingEndpoint.Start();
    
                return streamingEndpoint;
            }
    
            private static StreamingEndpointAccessControl GetAccessControl()
            {
                return new StreamingEndpointAccessControl
                {
                    IPAllowList = new List
                    {
                        new IPRange
                        {
                            Name = "Allow all",
                            Address = IPAddress.Parse("0.0.0.0"),
                            SubnetPrefixLength = 0
                        }
                    },
    
                    AkamaiSignatureHeaderAuthenticationKeyList = new List
                    {
                        new AkamaiSignatureHeaderAuthenticationKey
                        {
                            Identifier = "My key",
                            Expiration = DateTime.UtcNow + TimeSpan.FromDays(365),
                            Base64Key = Convert.ToBase64String(GenerateRandomBytes(16))
                        }
                    }
                };
            }
    
            private static byte[] GenerateRandomBytes(int length)
            {
                var bytes = new byte[length];
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(bytes);
                }
    
                return bytes;
            }
    
            private static StreamingEndpointCacheControl GetCacheControl()
            {
                return new StreamingEndpointCacheControl
                {
                    MaxAge = TimeSpan.FromSeconds(1000)
                };
            }
    
            public static void UpdateCrossSiteAccessPoliciesForStreamingEndpoint(IStreamingEndpoint streamingEndpoint)
            {
                var clientPolicy =
                    @"<?xml version=""1.0"" encoding=""utf-8""?>
                
                    
                        
                            
                                
                            
                            
                               "" include-subpaths=""true""/>
                            
                        
                    
                ";
    
                var xdomainPolicy =
                    @"<?xml version=""1.0"" ?>
                
                    
                ";
    
                streamingEndpoint.CrossSiteAccessPolicies.ClientAccessPolicy = clientPolicy;
                streamingEndpoint.CrossSiteAccessPolicies.CrossDomainPolicy = xdomainPolicy;
    
                streamingEndpoint.Update();
            }
    
            public static void GetLocatorsInAllStreamingEndpoints(IAsset asset)
            {
                var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
                var ismFile = asset.AssetFiles.AsEnumerable().FirstOrDefault(a => a.Name.EndsWith(".ism"));
                var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");
                var urls = locators.SelectMany(l =>
                            _context
                                .StreamingEndpoints
                                .AsEnumerable()
                                .Where(se => se.State == StreamingEndpointState.Running)
                                .Select(
                                    se =>
                                        template.BindByPosition(new Uri("http://" + se.HostName),
                                        l.ContentAccessComponent,
                                            ismFile.Name)))
                            .ToArray();
    
            }
    
            public static void Cleanup(IStreamingEndpoint streamingEndpoint,
                                        IChannel channel)
            {
                if (streamingEndpoint != null)
                {
                    streamingEndpoint.Stop();
                    streamingEndpoint.Delete();
                }
    
                IAsset asset;
                if (channel != null)
                {
    
                    foreach (var program in channel.Programs)
                    {
                        asset = _context.Assets.Where(se => se.Id == program.AssetId)
                                                .FirstOrDefault();
    
                        program.Stop();
                        program.Delete();
    
                        if (asset != null)
                        {
                            foreach (var l in asset.Locators)
                                l.Delete();
    
                            asset.Delete();
                        }
                    }
    
                    channel.Stop();
                    channel.Delete();
                }
            }
        }
    }
    

    Now I want to make a method to cut a live stream for example every 15 minutes and save it as mp4 but don't know where to start.

    Can someone point me in the right direction?

    Kind regards

    UPDATE:

    I want to save the mp4 files on my hard disk.

  • What is the most suitable H265 setting converting from H264 on ffmpeg ?

    9 juin 2017, par minion007

    Currently, I was trying to convert my videos no matter personal videos or movies from H264 to H265. But that was much harder than what I expected.

    Firstly, it took me over 10 hours to build ffmpeg on Linux and I believe I'm still having some problems on dealing with this.

    Secondly, I notice there is degradation after converting by using the setting or parameters from Internet or ffmpeg official website. On the other hand, the video size would be the same or even bigger than the original video size if I use small crf like 23 or 28.

    For instance, sudo ffmpeg -i input.mp4 -c:v hevc -x265-params lossless -preset medium -crf 30 -c:a copy output.mkv

    sudo ffmpeg -i input.mp4 -c:v libx265 -x265-params lossless -preset medium -crf 30 -c:a copy output.mkv

    the above two settings give me the very small video size (between 21%~23% of the original video) which is the main reason why I want to convert my videos to H265 but drawback would be the quality of converted video is worse than the original video (I would may be between 30%~35% degradation).

    Thirdly, the size of video would be much bigger than the original size of video if I use the lossless parameter.

    sudo ffmpeg -i input.mp4 -c:v libx265 -x265-params lossless=1 -preset medium -crf 30 -c:a copy output.mkv

    the above setting can keep the quality of the original video but size would be huge (above 200% of original video).

    Is there any suggestion?

  • Building ffmpeg on mac results in undefined symbols

    9 juin 2017, par Peter

    Environment: macOS 10.12.5, Xcode 8.3.3, pkg-config installed via brew

    I need to build a minimal version of ffmpeg that supports H.264 decoding. I have downloaded the source for ffmpeg version 3.3.1 and have successfully built it for Windows and Linux. Now, I am trying to build it for mac.

    The specific flags of the configuration that are relevant are:

    --disable-yasm
    --disable-everything
    --enable-decoder=h264
    --enable-decoder=h264_vda
    --enable-vda
    

    After running the configuration, when I run make, all the libraries such as libavcodec.a, libavfilter.a, libavformat.a, are built. However, ffmpeg itself does not get built. The error I get is:

    Undefined symbols for architecture x86_64:
      "_ff_vda_create_decoder", referenced from:
          _vdadec_init in libavcodec.a(vda_h264_dec.o)
      "_ff_vda_destroy_decoder", referenced from:
          _vdadec_init in libavcodec.a(vda_h264_dec.o)
          _vdadec_close in libavcodec.a(vda_h264_dec.o)
    ld: symbol(s) not found for architecture x86_64
    

    Looks like the functions are defined in ./libavcodec/vda_h264.c. However, it appears vda_h264.c is never compiled. Other vda related files such as vda.c and vda_h264_dec.c do get compiled (and added to libavcodec.a).

    I am thinking perhaps I am missing a configuration flag. Can someone please help? Regards.

  • How to play a video using an AVPacket ? [on hold]

    9 juin 2017, par Sanduni Wickramasinghe

    I am reading a mp4 (video) file stored in my local directory. Is there a method to play the video in separate window?

    I can do this with opencv by creating a new window and display the video. But with ffmpeg I have no idea how to do that. I have only found command line arguments to do this which is not useful in my project