Recherche avancée

Médias (1)

Mot : - Tags -/epub

Autres articles (25)

  • Les formats acceptés

    28 janvier 2010, par

    Les commandes suivantes permettent d’avoir des informations sur les formats et codecs gérés par l’installation local de ffmpeg :
    ffmpeg -codecs ffmpeg -formats
    Les format videos acceptés en entrée
    Cette liste est non exhaustive, elle met en exergue les principaux formats utilisés : h264 : H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 m4v : raw MPEG-4 video format flv : Flash Video (FLV) / Sorenson Spark / Sorenson H.263 Theora wmv :
    Les formats vidéos de sortie possibles
    Dans un premier temps on (...)

  • Supporting all media types

    13 avril 2011, par

    Unlike most software and media-sharing platforms, MediaSPIP aims to manage as many different media types as possible. The following are just a few examples from an ever-expanding list of supported formats : images : png, gif, jpg, bmp and more audio : MP3, Ogg, Wav and more video : AVI, MP4, OGV, mpg, mov, wmv and more text, code and other data : OpenOffice, Microsoft Office (Word, PowerPoint, Excel), web (html, CSS), LaTeX, Google Earth and (...)

  • Submit bugs and patches

    13 avril 2011

    Unfortunately a software is never perfect.
    If you think you have found a bug, report it using our ticket system. Please to help us to fix it by providing the following information : the browser you are using, including the exact version as precise an explanation as possible of the problem if possible, the steps taken resulting in the problem a link to the site / page in question
    If you think you have solved the bug, fill in a ticket and attach to it a corrective patch.
    You may also (...)

Sur d’autres sites (4471)

  • Processing Big Data Problems

    8 janvier 2011, par Multimedia Mike — Big Data

    I’m becoming more interested in big data problems, i.e., extracting useful information out of absurdly sized sets of input data. I know it’s a growing field and there is a lot to read on the subject. But you know how I roll— just think of a problem to solve and dive right in.

    Here’s how my adventure unfolded.

    The Corpus
    I need to run a command line program on a set of files I have collected. This corpus is on the order of 350,000 files. The files range from 7 bytes to 175 MB. Combined, they occupy around 164 GB of storage space.

    Oh, and said storage space resides on an external, USB 2.0-connected hard drive. Stop laughing.

    A file is named according to the SHA-1 hash of its data. The files are organized in a directory hierarchy according to the first 6 hex digits of the SHA-1 hash (e.g., a file named a4d5832f... is stored in a4/d5/83/a4d5832f...). All of this file hash, path, and size information is stored in an SQLite database.

    First Pass
    I wrote a Python script that read all the filenames from the database, fed them into a pool of worker processes using Python’s multiprocessing module, and wrote some resulting data for each file back to the SQLite database. My Eee PC has a single-core, hyperthreaded Atom which presents 2 CPUs to the system. Thus, 2 worker threads crunched the corpus. It took awhile. It took somewhere on the order of 9 or 10 or maybe even 12 hours. It took long enough that I’m in no hurry to re-run the test and get more precise numbers.

    At least I extracted my initial set of data from the corpus. Or did I ?

    Think About The Future

    A few days later, I went back to revisit the data only to notice that the SQLite database was corrupted. To add insult to that bit of injury, the script I had written to process the data was also completely corrupted (overwritten with something unrelated to Python code). BTW, this is was on a RAID brick configured for redundancy. So that’s strike 3 in my personal dealings with RAID technology.

    I moved the corpus to a different external drive and also verified the files after writing (easy to do since I already had the SHA-1 hashes on record).

    The corrupted script was pretty simple to rewrite, even a little better than before. Then I got to re-run it. However, this run was on a faster machine, a hyperthreaded, quad-core beast that exposes 8 CPUs to the system. The reason I wasn’t too concerned about the poor performance with my Eee PC is that I knew I was going to be able to run in on this monster later.

    So I let the rewritten script rip. The script gave me little updates regarding its progress. As it did so, I ran some rough calculations and realized that it wasn’t predicted to finish much sooner than it would have if I were running it on the Eee PC.

    Limiting Factors
    It had been suggested to me that I/O bandwidth of the external USB drive might be a limiting factor. This is when I started to take that idea very seriously.

    The first idea I had was to move the SQLite database to a different drive. The script records data to the database for every file processed, though it only commits once every 100 UPDATEs, so at least it’s not constantly syncing the disc. I ran before and after tests with a small subset of the corpus and noticed a substantial speedup thanks to this policy chance.

    Then I remembered hearing something about "atime" which is access time. Linux filesystems, per default, record the time that a file was last accessed. You can watch this in action by running 'stat <file> ; cat <file> > /dev/null ; stat <file>' and observe that the "Access" field has been updated to NOW(). This also means that every single file that gets read from the external drive still causes an additional write. To avoid this, I started mounting the external drive with '-o noatime' which instructs Linux not to record "last accessed" time for files.

    On the limited subset test, this more than doubled script performance. I then wondered about mounting the external drive as read-only. This had the same performance as noatime. I thought about using both options together but verified that access times are not updated for a read-only filesystem.

    A Note On Profiling
    Once you start accessing files in Linux, those files start getting cached in RAM. Thus, if you profile, say, reading a gigabyte file from a disk and get 31 MB/sec, and then repeat the same test, you’re likely to see the test complete instantaneously. That’s because the file is already sitting in memory, cached. This is useful in general application use, but not if you’re trying to profile disk performance.

    Thus, in between runs, do (as root) 'sync; echo 3 > /proc/sys/vm/drop_caches' in order to wipe caches (explained here).

    Even Better ?
    I re-ran the test using these little improvements. Now it takes somewhere around 5 or 6 hours to run.

    I contrived an artificially large file on the external drive and did some 'dd' tests to measure what the drive could really do. The drive consistently measured a bit over 31 MB/sec. If I could read and process the data at 30 MB/sec, the script would be done in about 95 minutes.

    But it’s probably rather unreasonable to expect that kind of transfer rate for lots of smaller files scattered around a filesystem. However, it can’t be that helpful to have 8 different processes constantly asking the HD for 8 different files at any one time.

    So I wrote a script called stream-corpus.py which simply fetched all the filenames from the database and loaded the contents of each in turn, leaving the data to be garbage-collected at Python’s leisure. This test completed in 174 minutes, just shy of 3 hours. I computed an average read speed of around 17 MB/sec.

    Single-Reader Script
    I began to theorize that if I only have one thread reading, performance should improve greatly. To test this hypothesis without having to do a lot of extra work, I cleared the caches and ran stream-corpus.py until 'top' reported that about half of the real memory had been filled with data. Then I let the main processing script loose on the data. As both scripts were using sorted lists of files, they iterated over the filenames in the same order.

    Result : The processing script tore through the files that had obviously been cached thanks to stream-corpus.py, degrading drastically once it had caught up to the streaming script.

    Thus, I was incented to reorganize the processing script just slightly. Now, there is a reader thread which reads each file and stuffs the name of the file into an IPC queue that one of the worker threads can pick up and process. Note that no file data is exchanged between threads. No need— the operating system is already implicitly holding onto the file data, waiting in case someone asks for it again before something needs that bit of RAM. Technically, this approach accesses each file multiple times. But it makes little practical difference thanks to caching.

    Result : About 183 minutes to process the complete corpus (which works out to a little over 16 MB/sec).

    Why Multiprocess
    Is it even worthwhile to bother multithreading this operation ? Monitoring the whole operation via 'top', most instances of the processing script are barely using any CPU time. Indeed, it’s likely that only one of the worker threads is doing any work most of the time, pulling a file out of the IPC queue as soon the reader thread triggers its load into cache. Right now, the processing is usually pretty quick. There are cases where the processing (external program) might hang (one of the reasons I’m running this project is to find those cases) ; the multiprocessing architecture at least allows other processes to take over until a hanging process is timed out and killed by its monitoring process.

    Further, the processing is pretty simple now but is likely to get more intensive in future iterations. Plus, there’s the possibility that I might move everything onto a more appropriately-connected storage medium which should help alleviate the bottleneck bravely battled in this post.

    There’s also the theoretical possibility that the reader thread could read too far ahead of the processing threads. Obviously, that’s not too much of an issue in the current setup. But to guard against it, the processes could share a variable that tracks the total number of bytes that have been processed. The reader thread adds filesizes to the count while the processing threads subtract file sizes. The reader thread would delay reading more if the number got above a certain threshold.

    Leftovers
    I wondered if the order of accessing the files mattered. I didn’t write them to the drive in any special order. The drive is formatted with Linux ext3. I ran stream-corpus.py on all the filenames sorted by filename (remember the SHA-1 naming convention described above) and also by sorting them randomly.

    Result : It helps immensely for the filenames to be sorted. The sorted variant was a little more than twice as fast as the random variant. Maybe it has to do with accessing all the files in a single directory before moving onto another directory.

    Further, I have long been under the impression that the best read speed you can expect from USB 2.0 was 27 Mbytes/sec (even though 480 Mbit/sec is bandied about in relation to the spec). This comes from profiling I performed with an external enclosure that supports both USB 2.0 and FireWire-400 (and eSata). FW-400 was able to read the same file at nearly 40 Mbytes/sec that USB 2.0 could only read at 27 Mbytes/sec. Other sources I have read corroborate this number. But this test (using different hardware), achieved over 31 Mbytes/sec.

  • Transcoded video stream unplayable in QuickTime player

    30 novembre 2017, par Nikolai Linetskiy

    Currently I’m writing software for transcoding media files using ffmpeg libs. The problem is that in case of H264 QuickTime cannot play result stream and shows black screen. Audio streams work as expected. I have read that QuickTime can deal only with yuv420p pixel format and that is true for encoded video.

    I looked through the ffmpeg examples and ffmpeg source code and could not find anything find any clues where the problem might be. I would really appreciate any help.

    The only thing I managed to get from QuickTime is
    SeqAndPicParamSetFromCFDictionaryRef, bad config record message in console. Same thing is logged by AVPlayer from AVFoundation.

    Here is the initialization of output streams and encoders.

    int status;

    // avformat_alloc_output_context2()
    if ((status = formatContext.open(destFilename)) < 0) {
       return status;
    }

    AVDictionary *fmtOptions = nullptr;
    av_dict_set(&fmtOptions, "movflags", "faststart", 0);
    av_dict_set(&fmtOptions, "brand", "mp42", 0);

    streams.resize(input->getStreamsCount());
    for (int i = 0; i < input->getStreamsCount(); ++i) {
       AVStream *inputStream = input->getStreamAtIndex(i);
       CodecContext &decoderContext = input->getDecoderAtIndex(i);

       // retrieve output codec by codec id
       auto encoderCodecId = decoderContext.getCodecID();;
       if (decoderContext.getCodecType() == AVMEDIA_TYPE_VIDEO || decoderContext.getCodecType() == AVMEDIA_TYPE_AUDIO) {
           int codecIdKey = decoderContext.getCodecType() == AVMEDIA_TYPE_AUDIO ? IPROC_KEY_INT(TargetAudioCodecID) : IPROC_KEY_INT(TargetVideoCodecID);
           auto codecIdParam = static_cast<avcodecid>(params[codecIdKey]);
           if (codecIdParam != AV_CODEC_ID_NONE) {
               encoderCodecId = codecIdParam;
           }
       }
       AVCodec *encoder = nullptr;
       if ((encoder = avcodec_find_encoder(encoderCodecId)) == nullptr) {
           status = AVERROR_ENCODER_NOT_FOUND;
           return status;
       }

       // create stream with specific codec and format
       AVStream *outputStream = nullptr;
       // avformat_new_stream()
       if ((outputStream = formatContext.newStream(encoder)) == nullptr) {
           return AVERROR(ENOMEM);
       }


       CodecContext encoderContext;
       // avcodec_alloc_context3()
       if ((status = encoderContext.init(encoder)) &lt; 0) {
           return status;
       }

       outputStream->disposition = inputStream->disposition;
       encoderContext.getRawCtx()->chroma_sample_location = decoderContext.getRawCtx()->chroma_sample_location;

       if (encoderContext.getCodecType() == AVMEDIA_TYPE_VIDEO) {
           auto lang = av_dict_get(input->getStreamAtIndex(i)->metadata, "language", nullptr, 0);
           if (lang) {
               av_dict_set(&amp;outputStream->metadata, "language", lang->value, 0);
           }

           // prepare encoder context
           int targetWidth = params[IPROC_KEY_INT(TargetVideoWidth)];
           int targetHeight = params[IPROC_KEY_INT(TargetVideHeight)];



           encoderContext.width() = targetWidth > 0 ? targetWidth : decoderContext.width();
           encoderContext.height() = targetHeight > 0 ? targetHeight : decoderContext.height();
           encoderContext.pixelFormat() = encoder->pix_fmts ? encoder->pix_fmts[0] : decoderContext.pixelFormat();;
           encoderContext.timeBase() = decoderContext.timeBase();
           encoderContext.getRawCtx()->level = 31;
           encoderContext.getRawCtx()->gop_size = 25;

           double far = static_cast<double>(encoderContext.getRawCtx()->width) / encoderContext.getRawCtx()->height;
           double dar = static_cast<double>(decoderContext.width()) / decoderContext.height();
           encoderContext.sampleAspectRatio() = av_d2q(dar / far, 255);


           encoderContext.getRawCtx()->bits_per_raw_sample = FFMIN(decoderContext.getRawCtx()->bits_per_raw_sample,
                                                                   av_pix_fmt_desc_get(encoderContext.pixelFormat())->comp[0].depth);
           encoderContext.getRawCtx()->framerate = inputStream->r_frame_rate;
           outputStream->avg_frame_rate = encoderContext.getRawCtx()->framerate;

           VideoFilterGraphParameters params;
           params.height = encoderContext.height();
           params.width = encoderContext.width();
           params.pixelFormat = encoderContext.pixelFormat();
           if ((status = generateGraph(decoderContext, encoderContext, params, streams[i].filterGraph)) &lt; 0) {
               return status;
           }

       } else if (encoderContext.getCodecType() == AVMEDIA_TYPE_AUDIO) {
           auto lang = av_dict_get(input->getStreamAtIndex(i)->metadata, "language", nullptr, 0);
           if (lang) {
               av_dict_set(&amp;outputStream->metadata, "language", lang->value, 0);
           }

           encoderContext.sampleRate() = params[IPROC_KEY_INT(TargetAudioSampleRate)] ? : decoderContext.sampleRate();
           encoderContext.channels() = params[IPROC_KEY_INT(TargetAudioChannels)] ? : decoderContext.channels();
           auto paramChannelLayout = params[IPROC_KEY_INT(TargetAudioChannelLayout)];
           if (paramChannelLayout) {
               encoderContext.channelLayout() = paramChannelLayout;
           } else {
               encoderContext.channelLayout() = av_get_default_channel_layout(encoderContext.channels());
           }

           AVSampleFormat sampleFormatParam = static_cast<avsampleformat>(params[IPROC_KEY_INT(TargetAudioSampleFormat)]);
           if (sampleFormatParam != AV_SAMPLE_FMT_NONE) {
               encoderContext.sampleFormat() = sampleFormatParam;
           } else if (encoder->sample_fmts) {
               encoderContext.sampleFormat() = encoder->sample_fmts[0];
           } else {
               encoderContext.sampleFormat() = decoderContext.sampleFormat();
           }

           encoderContext.timeBase().num = 1;
           encoderContext.timeBase().den = encoderContext.sampleRate();

           AudioFilterGraphParameters params;
           params.channelLayout = encoderContext.channelLayout();
           params.channels = encoderContext.channels();
           params.format = encoderContext.sampleFormat();
           params.sampleRate = encoderContext.sampleRate();
           if ((status = generateGraph(decoderContext, encoderContext, params, streams[i].filterGraph)) &lt; 0) {
               return status;
           }
       }

       // before using encoder, we should open it and update its parameters
       printf("Codec bits per sample %d\n", av_get_bits_per_sample(encoderCodecId));
       AVDictionary *options = nullptr;
       // avcodec_open2()
       if ((status = encoderContext.open(encoder, &amp;options)) &lt; 0) {
           return status;
       }
       if (streams[i].filterGraph) {
           streams[i].filterGraph.setOutputFrameSize(encoderContext.getFrameSize());
       }
       // avcodec_parameters_from_context()
       if ((status = encoderContext.fillParamters(outputStream->codecpar)) &lt; 0) {
           return status;
       }
       outputStream->codecpar->format = encoderContext.getRawCtx()->pix_fmt;

       if (formatContext.getRawCtx()->oformat->flags &amp; AVFMT_GLOBALHEADER) {
           encoderContext.getRawCtx()->flags |= CODEC_FLAG_GLOBAL_HEADER;
       }

       if (encoderContext.getRawCtx()->nb_coded_side_data) {
           int i;

           for (i = 0; i &lt; encoderContext.getRawCtx()->nb_coded_side_data; i++) {
               const AVPacketSideData *sd_src = &amp;encoderContext.getRawCtx()->coded_side_data[i];
               uint8_t *dst_data;

               dst_data = av_stream_new_side_data(outputStream, sd_src->type, sd_src->size);
               if (!dst_data)
                   return AVERROR(ENOMEM);
               memcpy(dst_data, sd_src->data, sd_src->size);
           }
       }

       /*
        * Add global input side data. For now this is naive, and copies it
        * from the input stream's global side data. All side data should
        * really be funneled over AVFrame and libavfilter, then added back to
        * packet side data, and then potentially using the first packet for
        * global side data.
        */
       for (int i = 0; i &lt; inputStream->nb_side_data; i++) {
           AVPacketSideData *sd = &amp;inputStream->side_data[i];
           uint8_t *dst = av_stream_new_side_data(outputStream, sd->type, sd->size);
           if (!dst)
               return AVERROR(ENOMEM);
           memcpy(dst, sd->data, sd->size);
       }

       // copy timebase while removing common factors
       if (outputStream->time_base.num &lt;= 0 || outputStream->time_base.den &lt;= 0) {
           outputStream->time_base = av_add_q(encoderContext.timeBase(), (AVRational){0, 1});
       }

       // copy estimated duration as a hint to the muxer
       if (outputStream->duration &lt;= 0 &amp;&amp; inputStream->duration > 0) {
           outputStream->duration = av_rescale_q(inputStream->duration, inputStream->time_base, outputStream->time_base);
       }

       streams[i].codecType = encoderContext.getRawCtx()->codec_type;
       streams[i].codec = std::move(encoderContext);
       streams[i].streamIndex = i;
    }

    // avio_open() and avformat_write_header()
    if ((status = formatContext.writeHeader(fmtOptions)) &lt; 0) {
       return status;
    }

    formatContext.dumpFormat();
    </avsampleformat></double></double></avcodecid>

    Reading from stream.

    int InputProcessor::performStep() {
       int status;

       Packet nextPacket;
       if ((status = input->getFormatContext().readFrame(nextPacket)) &lt; 0) {
           return status;
       }
       ++streams[nextPacket.getStreamIndex()].readPackets;
       int streamIndex = nextPacket.getStreamIndex();
       CodecContext &amp;decoder = input->getDecoderAtIndex(streamIndex);
       AVStream *inputStream = input->getStreamAtIndex(streamIndex);

       if (streams[nextPacket.getStreamIndex()].readPackets == 1) {
           for (int i = 0; i &lt; inputStream->nb_side_data; ++i) {
               AVPacketSideData *src_sd = &amp;inputStream->side_data[i];
               uint8_t *dst_data;

               if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX) {
                   continue;
               }
               if (av_packet_get_side_data(nextPacket.getRawPtr(), src_sd->type, nullptr)) {
                   continue;
               }
               dst_data = av_packet_new_side_data(nextPacket.getRawPtr(), src_sd->type, src_sd->size);
               if (!dst_data) {
                   return AVERROR(ENOMEM);
               }
               memcpy(dst_data, src_sd->data, src_sd->size);
           }
       }

       nextPacket.rescaleTimestamps(inputStream->time_base, decoder.timeBase());

       status = decodePacket(&amp;nextPacket, nextPacket.getStreamIndex());
       if (status &lt; 0 &amp;&amp; status != AVERROR(EAGAIN)) {
           return status;
       }
       return 0;
    }

    Here is decoding/encoding code.

    int InputProcessor::decodePacket(Packet *packet, int streamIndex) {
       int status;
       int sendStatus;

       auto &amp;decoder = input->getDecoderAtIndex(streamIndex);

       do {
           if (packet == nullptr) {

               sendStatus = decoder.flushDecodedFrames();
           } else {
               sendStatus = decoder.sendPacket(*packet);
           }

           if (sendStatus &lt; 0 &amp;&amp; sendStatus != AVERROR(EAGAIN) &amp;&amp; sendStatus != AVERROR_EOF) {
               return sendStatus;
           }
           if (sendStatus == 0 &amp;&amp; packet) {
               ++streams[streamIndex].decodedPackets;
           }

           Frame decodedFrame;
           while (true) {
               if ((status = decoder.receiveFrame(decodedFrame)) &lt; 0) {
                   break;
               }
               ++streams[streamIndex].decodedFrames;
               if ((status = filterAndWriteFrame(&amp;decodedFrame, streamIndex)) &lt; 0) {
                   break;
               }
               decodedFrame.unref();
           }
       } while (sendStatus == AVERROR(EAGAIN));

    return status;
    }

    int InputProcessor::encodeAndWriteFrame(Frame *frame, int streamIndex) {
       assert(input->isValid());
       assert(formatContext);

       int status = 0;
       int sendStatus;

       Packet packet;

       CodecContext &amp;encoderContext = streams[streamIndex].codec;

       do {
           if (frame) {
               sendStatus = encoderContext.sendFrame(*frame);
           } else {
               sendStatus = encoderContext.flushEncodedPackets();
           }
           if (sendStatus &lt; 0 &amp;&amp; sendStatus != AVERROR(EAGAIN) &amp;&amp; sendStatus != AVERROR_EOF) {
               return status;
           }
           if (sendStatus == 0 &amp;&amp; frame) {
               ++streams[streamIndex].encodedFrames;
           }

           while (true) {
               if ((status = encoderContext.receivePacket(packet)) &lt; 0) {
                   break;
               }
               ++streams[streamIndex].encodedPackets;
               packet.setStreamIndex(streamIndex);
               auto sourceTimebase = encoderContext.timeBase();
               auto dstTimebase = formatContext.getStreams()[streamIndex]->time_base;
               packet.rescaleTimestamps(sourceTimebase, dstTimebase);
               if ((status = formatContext.writeFrameInterleaved(packet)) &lt; 0) {
                   return status;
               }
               packet.unref();
           }
       } while (sendStatus == AVERROR(EAGAIN));

       if (status != AVERROR(EAGAIN)) {
           return status;
       }

       return 0;
    }

    FFprobe output for original video.

    Input #0, matroska,webm, from 'testvideo':
     Metadata:
       title           : TestVideo
       encoder         : libebml v1.3.0 + libmatroska v1.4.0
       creation_time   : 2014-12-23T03:38:05.000000Z
     Duration: 00:02:29.25, start: 0.000000, bitrate: 79549 kb/s
       Stream #0:0(rus): Video: h264 (High 4:4:4 Predictive), yuv444p10le(pc, bt709, progressive), 2048x858 [SAR 1:1 DAR 1024:429], 24 fps, 24 tbr, 1k tbn, 48 tbc (default)
       Stream #0:1(rus): Audio: pcm_s24le, 48000 Hz, 6 channels, s32 (24 bit), 6912 kb/s (default)

    Transcoded :

    Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '123.mp4':
     Metadata:
       major_brand     : mp42
       minor_version   : 512
       compatible_brands: isomiso2avc1mp41
       encoder         : Lavf57.71.100
     Duration: 00:02:29.27, start: 0.000000, bitrate: 4282 kb/s
       Stream #0:0(rus): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 192:143 DAR 1024:429], 3940 kb/s, 24.01 fps, 24 tbr, 12288 tbn, 96 tbc (default)
       Metadata:
         handler_name    : VideoHandler
       Stream #0:1(rus): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, 5.1, fltp, 336 kb/s (default)
       Metadata:
         handler_name    : SoundHandler
  • Resultant video stream unplayable

    29 novembre 2017, par Nikolai Linetskiy

    Currently I’m writing software for transcoding media files using ffmpeg libs. The problem is that in case of H264 QuickTime cannot play result stream and shows black screen. Audio streams work as expected. I have read that QuickTime can deal only with yuv420p pixel format and that is true for encoded video.

    I looked through the ffmpeg examples and ffmpeg source code and could not find anything find any clues where the problem might be. I would really appreciate any help.

    The only thing I managed to get from QuickTime is
    SeqAndPicParamSetFromCFDictionaryRef, bad config record message in console. Same thing is logged by AVPlayer from AVFoundation.

    Here is the initialization of output streams and encoders.

    int status;

    // avformat_alloc_output_context2()
    if ((status = formatContext.open(destFilename)) &lt; 0) {
       return status;
    }

    AVDictionary *fmtOptions = nullptr;
    av_dict_set(&amp;fmtOptions, "movflags", "faststart", 0);
    av_dict_set(&amp;fmtOptions, "brand", "mp42", 0);

    streams.resize(input->getStreamsCount());
    for (int i = 0; i &lt; input->getStreamsCount(); ++i) {
       AVStream *inputStream = input->getStreamAtIndex(i);
       CodecContext &amp;decoderContext = input->getDecoderAtIndex(i);

       // retrieve output codec by codec id
       auto encoderCodecId = decoderContext.getCodecID();;
       if (decoderContext.getCodecType() == AVMEDIA_TYPE_VIDEO || decoderContext.getCodecType() == AVMEDIA_TYPE_AUDIO) {
           int codecIdKey = decoderContext.getCodecType() == AVMEDIA_TYPE_AUDIO ? IPROC_KEY_INT(TargetAudioCodecID) : IPROC_KEY_INT(TargetVideoCodecID);
           auto codecIdParam = static_cast<avcodecid>(params[codecIdKey]);
           if (codecIdParam != AV_CODEC_ID_NONE) {
               encoderCodecId = codecIdParam;
           }
       }
       AVCodec *encoder = nullptr;
       if ((encoder = avcodec_find_encoder(encoderCodecId)) == nullptr) {
           status = AVERROR_ENCODER_NOT_FOUND;
           return status;
       }

       // create stream with specific codec and format
       AVStream *outputStream = nullptr;
       // avformat_new_stream()
       if ((outputStream = formatContext.newStream(encoder)) == nullptr) {
           return AVERROR(ENOMEM);
       }


       CodecContext encoderContext;
       // avcodec_alloc_context3()
       if ((status = encoderContext.init(encoder)) &lt; 0) {
           return status;
       }

       outputStream->disposition = inputStream->disposition;
       encoderContext.getRawCtx()->chroma_sample_location = decoderContext.getRawCtx()->chroma_sample_location;

       if (encoderContext.getCodecType() == AVMEDIA_TYPE_VIDEO) {
           auto lang = av_dict_get(input->getStreamAtIndex(i)->metadata, "language", nullptr, 0);
           if (lang) {
               av_dict_set(&amp;outputStream->metadata, "language", lang->value, 0);
           }

           // prepare encoder context
           int targetWidth = params[IPROC_KEY_INT(TargetVideoWidth)];
           int targetHeight = params[IPROC_KEY_INT(TargetVideHeight)];



           encoderContext.width() = targetWidth > 0 ? targetWidth : decoderContext.width();
           encoderContext.height() = targetHeight > 0 ? targetHeight : decoderContext.height();
           encoderContext.pixelFormat() = encoder->pix_fmts ? encoder->pix_fmts[0] : decoderContext.pixelFormat();;
           encoderContext.timeBase() = decoderContext.timeBase();
           encoderContext.getRawCtx()->level = 31;
           encoderContext.getRawCtx()->gop_size = 25;

           double far = static_cast<double>(encoderContext.getRawCtx()->width) / encoderContext.getRawCtx()->height;
           double dar = static_cast<double>(decoderContext.width()) / decoderContext.height();
           encoderContext.sampleAspectRatio() = av_d2q(dar / far, 255);


           encoderContext.getRawCtx()->bits_per_raw_sample = FFMIN(decoderContext.getRawCtx()->bits_per_raw_sample,
                                                                   av_pix_fmt_desc_get(encoderContext.pixelFormat())->comp[0].depth);
           encoderContext.getRawCtx()->framerate = inputStream->r_frame_rate;
           outputStream->avg_frame_rate = encoderContext.getRawCtx()->framerate;

           VideoFilterGraphParameters params;
           params.height = encoderContext.height();
           params.width = encoderContext.width();
           params.pixelFormat = encoderContext.pixelFormat();
           if ((status = generateGraph(decoderContext, encoderContext, params, streams[i].filterGraph)) &lt; 0) {
               return status;
           }

       } else if (encoderContext.getCodecType() == AVMEDIA_TYPE_AUDIO) {
           auto lang = av_dict_get(input->getStreamAtIndex(i)->metadata, "language", nullptr, 0);
           if (lang) {
               av_dict_set(&amp;outputStream->metadata, "language", lang->value, 0);
           }

           encoderContext.sampleRate() = params[IPROC_KEY_INT(TargetAudioSampleRate)] ? : decoderContext.sampleRate();
           encoderContext.channels() = params[IPROC_KEY_INT(TargetAudioChannels)] ? : decoderContext.channels();
           auto paramChannelLayout = params[IPROC_KEY_INT(TargetAudioChannelLayout)];
           if (paramChannelLayout) {
               encoderContext.channelLayout() = paramChannelLayout;
           } else {
               encoderContext.channelLayout() = av_get_default_channel_layout(encoderContext.channels());
           }

           AVSampleFormat sampleFormatParam = static_cast<avsampleformat>(params[IPROC_KEY_INT(TargetAudioSampleFormat)]);
           if (sampleFormatParam != AV_SAMPLE_FMT_NONE) {
               encoderContext.sampleFormat() = sampleFormatParam;
           } else if (encoder->sample_fmts) {
               encoderContext.sampleFormat() = encoder->sample_fmts[0];
           } else {
               encoderContext.sampleFormat() = decoderContext.sampleFormat();
           }

           encoderContext.timeBase().num = 1;
           encoderContext.timeBase().den = encoderContext.sampleRate();

           AudioFilterGraphParameters params;
           params.channelLayout = encoderContext.channelLayout();
           params.channels = encoderContext.channels();
           params.format = encoderContext.sampleFormat();
           params.sampleRate = encoderContext.sampleRate();
           if ((status = generateGraph(decoderContext, encoderContext, params, streams[i].filterGraph)) &lt; 0) {
               return status;
           }
       }

       // before using encoder, we should open it and update its parameters
       printf("Codec bits per sample %d\n", av_get_bits_per_sample(encoderCodecId));
       AVDictionary *options = nullptr;
       // avcodec_open2()
       if ((status = encoderContext.open(encoder, &amp;options)) &lt; 0) {
           return status;
       }
       if (streams[i].filterGraph) {
           streams[i].filterGraph.setOutputFrameSize(encoderContext.getFrameSize());
       }
       // avcodec_parameters_from_context()
       if ((status = encoderContext.fillParamters(outputStream->codecpar)) &lt; 0) {
           return status;
       }
       outputStream->codecpar->format = encoderContext.getRawCtx()->pix_fmt;

       if (formatContext.getRawCtx()->oformat->flags &amp; AVFMT_GLOBALHEADER) {
           encoderContext.getRawCtx()->flags |= CODEC_FLAG_GLOBAL_HEADER;
       }

       if (encoderContext.getRawCtx()->nb_coded_side_data) {
           int i;

           for (i = 0; i &lt; encoderContext.getRawCtx()->nb_coded_side_data; i++) {
               const AVPacketSideData *sd_src = &amp;encoderContext.getRawCtx()->coded_side_data[i];
               uint8_t *dst_data;

               dst_data = av_stream_new_side_data(outputStream, sd_src->type, sd_src->size);
               if (!dst_data)
                   return AVERROR(ENOMEM);
               memcpy(dst_data, sd_src->data, sd_src->size);
           }
       }

       /*
        * Add global input side data. For now this is naive, and copies it
        * from the input stream's global side data. All side data should
        * really be funneled over AVFrame and libavfilter, then added back to
        * packet side data, and then potentially using the first packet for
        * global side data.
        */
       for (int i = 0; i &lt; inputStream->nb_side_data; i++) {
           AVPacketSideData *sd = &amp;inputStream->side_data[i];
           uint8_t *dst = av_stream_new_side_data(outputStream, sd->type, sd->size);
           if (!dst)
               return AVERROR(ENOMEM);
           memcpy(dst, sd->data, sd->size);
       }

       // copy timebase while removing common factors
       if (outputStream->time_base.num &lt;= 0 || outputStream->time_base.den &lt;= 0) {
           outputStream->time_base = av_add_q(encoderContext.timeBase(), (AVRational){0, 1});
       }

       // copy estimated duration as a hint to the muxer
       if (outputStream->duration &lt;= 0 &amp;&amp; inputStream->duration > 0) {
           outputStream->duration = av_rescale_q(inputStream->duration, inputStream->time_base, outputStream->time_base);
       }

       streams[i].codecType = encoderContext.getRawCtx()->codec_type;
       streams[i].codec = std::move(encoderContext);
       streams[i].streamIndex = i;
    }

    // avio_open() and avformat_write_header()
    if ((status = formatContext.writeHeader(fmtOptions)) &lt; 0) {
       return status;
    }

    formatContext.dumpFormat();
    </avsampleformat></double></double></avcodecid>

    Reading from stream.

    int InputProcessor::performStep() {
       int status;

       Packet nextPacket;
       if ((status = input->getFormatContext().readFrame(nextPacket)) &lt; 0) {
           return status;
       }
       ++streams[nextPacket.getStreamIndex()].readPackets;
       int streamIndex = nextPacket.getStreamIndex();
       CodecContext &amp;decoder = input->getDecoderAtIndex(streamIndex);
       AVStream *inputStream = input->getStreamAtIndex(streamIndex);

       if (streams[nextPacket.getStreamIndex()].readPackets == 1) {
           for (int i = 0; i &lt; inputStream->nb_side_data; ++i) {
               AVPacketSideData *src_sd = &amp;inputStream->side_data[i];
               uint8_t *dst_data;

               if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX) {
                   continue;
               }
               if (av_packet_get_side_data(nextPacket.getRawPtr(), src_sd->type, nullptr)) {
                   continue;
               }
               dst_data = av_packet_new_side_data(nextPacket.getRawPtr(), src_sd->type, src_sd->size);
               if (!dst_data) {
                   return AVERROR(ENOMEM);
               }
               memcpy(dst_data, src_sd->data, src_sd->size);
           }
       }

       nextPacket.rescaleTimestamps(inputStream->time_base, decoder.timeBase());

       status = decodePacket(&amp;nextPacket, nextPacket.getStreamIndex());
       if (status &lt; 0 &amp;&amp; status != AVERROR(EAGAIN)) {
           return status;
       }
       return 0;
    }

    Here is decoding/encoding code.

    int InputProcessor::decodePacket(Packet *packet, int streamIndex) {
       int status;
       int sendStatus;

       auto &amp;decoder = input->getDecoderAtIndex(streamIndex);

       do {
           if (packet == nullptr) {

               sendStatus = decoder.flushDecodedFrames();
           } else {
               sendStatus = decoder.sendPacket(*packet);
           }

           if (sendStatus &lt; 0 &amp;&amp; sendStatus != AVERROR(EAGAIN) &amp;&amp; sendStatus != AVERROR_EOF) {
               return sendStatus;
           }
           if (sendStatus == 0 &amp;&amp; packet) {
               ++streams[streamIndex].decodedPackets;
           }

           Frame decodedFrame;
           while (true) {
               if ((status = decoder.receiveFrame(decodedFrame)) &lt; 0) {
                   break;
               }
               ++streams[streamIndex].decodedFrames;
               if ((status = filterAndWriteFrame(&amp;decodedFrame, streamIndex)) &lt; 0) {
                   break;
               }
               decodedFrame.unref();
           }
       } while (sendStatus == AVERROR(EAGAIN));

    return status;
    }

    int InputProcessor::encodeAndWriteFrame(Frame *frame, int streamIndex) {
       assert(input->isValid());
       assert(formatContext);

       int status = 0;
       int sendStatus;

       Packet packet;

       CodecContext &amp;encoderContext = streams[streamIndex].codec;

       do {
           if (frame) {
               sendStatus = encoderContext.sendFrame(*frame);
           } else {
               sendStatus = encoderContext.flushEncodedPackets();
           }
           if (sendStatus &lt; 0 &amp;&amp; sendStatus != AVERROR(EAGAIN) &amp;&amp; sendStatus != AVERROR_EOF) {
               return status;
           }
           if (sendStatus == 0 &amp;&amp; frame) {
               ++streams[streamIndex].encodedFrames;
           }

           while (true) {
               if ((status = encoderContext.receivePacket(packet)) &lt; 0) {
                   break;
               }
               ++streams[streamIndex].encodedPackets;
               packet.setStreamIndex(streamIndex);
               auto sourceTimebase = encoderContext.timeBase();
               auto dstTimebase = formatContext.getStreams()[streamIndex]->time_base;
               packet.rescaleTimestamps(sourceTimebase, dstTimebase);
               if ((status = formatContext.writeFrameInterleaved(packet)) &lt; 0) {
                   return status;
               }
               packet.unref();
           }
       } while (sendStatus == AVERROR(EAGAIN));

       if (status != AVERROR(EAGAIN)) {
           return status;
       }

       return 0;
    }

    FFprobe output for original video.

    Input #0, matroska,webm, from 'testvideo':
     Metadata:
       title           : TestVideo
       encoder         : libebml v1.3.0 + libmatroska v1.4.0
       creation_time   : 2014-12-23T03:38:05.000000Z
     Duration: 00:02:29.25, start: 0.000000, bitrate: 79549 kb/s
       Stream #0:0(rus): Video: h264 (High 4:4:4 Predictive), yuv444p10le(pc, bt709, progressive), 2048x858 [SAR 1:1 DAR 1024:429], 24 fps, 24 tbr, 1k tbn, 48 tbc (default)
       Stream #0:1(rus): Audio: pcm_s24le, 48000 Hz, 6 channels, s32 (24 bit), 6912 kb/s (default)

    Transcoded :

    Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '123.mp4':
     Metadata:
       major_brand     : mp42
       minor_version   : 512
       compatible_brands: isomiso2avc1mp41
       encoder         : Lavf57.71.100
     Duration: 00:02:29.27, start: 0.000000, bitrate: 4282 kb/s
       Stream #0:0(rus): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 192:143 DAR 1024:429], 3940 kb/s, 24.01 fps, 24 tbr, 12288 tbn, 96 tbc (default)
       Metadata:
         handler_name    : VideoHandler
       Stream #0:1(rus): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, 5.1, fltp, 336 kb/s (default)
       Metadata:
         handler_name    : SoundHandler