628 points · by worble · 2y ago · 181 comments
It wasn't that long ago that reading, processing, and rendering the contents of a single image took a noticeable amount of time. But both hardware and software techniques have gotten significantly faster. What may have made sense many years ago (lots of workers on a frame) may not matter today when a single worker can process a frame or a group of frames more efficiently than the overhead of spinning up a bunch of workers to do the same task.
But where to move that split now? Ultra-low-end CPUs now ship with multiple cores and you can get over 100 easily on high-end systems, system RAM is faster than ever, interconnect moves almost a TB/sec on consumer hardware, GPUs are in everything, and SSDs are now faster than the RAM I grew up with (at least on continuous transfer). Basically the systems of today are entirely different beasts to the ones commonly on the market when FFmpeg was created.
This is tremendous work that requires lots of rethinking about how the workload needs to be defined, scheduled, distributed, tracked, and merged back into a final output. Kudos to the team for being willing to take it on. FFmpeg is one of those "pinnacle of open source" infrastructure components that civilizations are built from.
Update: Found here! https://www.youtube.com/watch?v=Z4DS3jiZhfo&t=1221s
IIUC all current encoders that support parallelism work by multiple threads working on the same frame at the same time. Often times the frame is split into regions and each thread focuses on a specific region of the frame. This approach can have a (usually small) quality/efficiency cost and requires per-encoder logic to assemble those regions into a single frame.
What if instead/additionally different keyframe segments are processed independently? So if keyframes are every 60 frames ffmpeg will read 60 frames pass that to the first thread, the next 60 to the next thread, ... then assemble the results basically by concatenating them. It seems like this could be used to parallelize any codec in a fairly generic way and it should be more efficient as there is no thread-communication overhead or splitting of the frame into regions which harms cross-region compression.
Off the top of my head I can only think of two issues:
1. Requires loading N*keyframe period frames into memory as well as the overhead memory for encoding N frames.
2. Variable keyframe support would require special support as the keyframe splits will need to be identified before passing the video to the encoding threads. This may require extra work to be performed upfront.
But both of these seem like they won't be an issue in many cases. Lots of the time I'd be happy to use tons of RAM and output with a fixed keyframe interval.
Probably I would combine this with intra-frame parallelization such as process every frame with 4 threads and then run 8 keyframe segments in parallel. This way I can get really good parallelism but only minor quality loss from 4 regions rather than splitting the video into 32 regions which would harm quality more.
What make you think that? I very much care about encoding performance (for a fixed quality level) for offline use.
Plus, computers aren't quad cores any more, people with powerful streaming rigs probably have 8 or 16 cores; and key frames aren't every second. Suddenly you're in this hellish world where you have to balance latency, CPU utilization and encoding efficiency. 16 cores at a not-so-great 8 seconds of extra latency means terrible efficiency with a key frame every 0.5 second. 16 cores at good efficiency (say, 4 seconds between key frames) means terrible 64 second of extra latency.
It's one of several reasons why live streams of this type are often 10-30 seconds behind live.
* Of course it also depends on where in the pipeline they hook in - some take the feed directly, in which case every frame is essentially a key frame.
That's a good point. In the general case of reading from a pipe you need to buffer it somewhere. But for file-based inputs the buffering concerns aren't relevant, just the working memory.
Also to be able to seek anywhere in the steam without decoding all previous frames.
I'd assume if each thread is working on its own key frame, it would be difficult to make b-frames work? Live content also probably makes it hard.
It also has a lossless codec ffv1 where the entropy coder doesn't reset, so it truly can't be multithreaded.
Big win too! This is going to really speed things up!
If you have a queue of 100k videos to process and a cluster of 100 cores, assigning a video to each core as it becomes available is the most efficient way to process them, because your skipping the thread joining time.
Anytime there is a queue of jobs, assigning the next job in the queue to the next free core is always going to be faster than assigning the next job to multiple cores.
They use custom hardware just for encoding.
fyi they have to transcode over 500h of videos per minute. So multiple that by all the formats they support.
They operate at an insane scale, Netflix looks like a garage project for comparison.
Agree with the general premise, of course, if I've got 10 different videos encoding at once then I don't need additional efficiency because the CPU's already maxed out.
And that was years ago, I wouldn't be surprised to learn it's a bigger number now.
Also, their devs likely want fast feedback on changes - I imagine they might have CI running changes on some standard movies, checking various stats (like SNR) for regressions. Everybody loves if their CI finishes fast, so you might want to compress even a single movie in multiple threads.
(Plus a couple more "legacy" encodes with PIFF instead of CENC for ancient devices, probably.)
New tech advances, sure, they probably do re-encode everything sometimes - even knocking a few MB off the size of a movie saves a measurable amount of $$ at that scale. But are there frequent enough tech advances to do that more than a couple of times a year..? The amount of difficult testing (every TV model group from the past 10 years, or something) required for an encode change is horrible. I'm sure they have better automation than anyone else, but I'm guessing it's still somewhat of a nightmare.
Youtube, OTOH, I really can imagine having thousands of concurrent ffmpeg processes.
You could also imagine they might apply some kind of heuristic to decide to re-encode something based on some condition... Like fine tune encoder settings when a title becomes popular. No idea if they do that, just using some imagination.
* I would be very surprised if Netflix even uses vanilla ffmpeg
I believe the vast majority of ffmpeg usages are web services, or one off encodings.
Subjectively, me compressing my holiday video is much more important than Netflix re-compressing a million of them.
There is a noticeable delay booting up this pipeline for each tool invoke right now. We are working on putting in some optimizations but improvements in FFmpeg will definitely help. https://github.com/trypromptly/LLMStack is the project repo for the curious.
The presentation says it's 700 commits. Was that a separate branch? Or was it slowly merged back to the project?
Well I can look at github I guess
Not that this isn't great. Its fantastic. But TBH its not really going to change my workflow of VapourSynth preprocessing + av1an encoding for "quality" video encodes.
How come it only has 4 measly entries in HN, and none got any traction. I've posted a new entry, just for the curiosity of others.
ffmpeg -v quiet -f data -i file.txt -map 0:0 -c text -f data -[edit]
found the docs; it's available on Linux[1]. I'm definitely looking into it tonight because it can't be worse than writing ffmpeg CLI filtergraphs!
1: http://www.vapoursynth.com/doc/installation.html#linux-insta...
The frameserver is one thing, but an ecosystem of (trustable! open source!) plugins is harder to replicate.
At least we don't need deinterlacers so badly any more, though.
This is a pretty good (but not comprehensive) db of the filters: https://vsdb.top/
are people just itching for reasons to dive into show & tell or to wax poetic about how they have solved the problem for years? I really don't understand people at all, because I don't understand why people do this. and I'm sure I've done it, too.
It's been threaded since its inception, so it seems somewhat topical.
Hype for FEAT is beyond sensibility. People with similar FEAT are bristled by this and wish that their projects received even a fraction of FEAT's hype.
I think it's normal.
Now it can read the next chunk of file while decoding a chunk while applying filters while running multi-threaded encoding while writing the previous chunk.
I expect this will be a big help for complicated setups (applying multiple filters, rendering to multiple outputs with different codecs), but probably not much change for a simple 1-input 1-output transcode.
I'm using FFMPEG to encode MP3 with LAME for an audio hosting service and it would be great to improve encode times for long files.
That said, I don't think we still get input buffering (for HLS).
Talk with ChatGPT about it and see if you can do it.
Just Google it.
I wonder why did it took so long for FFmpeg?
BTW, MS Media foundation is a functional equivalent of FFmpeg. It was released as a part of Windows Vista in 2006, and is heavily multithreaded by design.
The trick to this is continuous iteration and feedback. It's remarkable how far I've gotten with GPT using these simple primitives and I know I'm not the only one.
I do renames in a big window with my IDE.
Interesting.
Here's a sample question I just asked the AI:
We are working on a React mapping application. I am going to give you two components from this application. Our goal is to extract functionality to deduplicate code
We can make a single base component, extract code to hooks, or any other strategy which you think is appropriate
Here is travel.tsx:
<snip>
Here is heatmap.tsx:
<snip>
And here is the response:
To deduplicate code and improve maintainability between the `TravelMap` and `Heatmap` components in your React mapping application, we can identify common functionalities and extract them into reusable hooks or components. Here's a strategy considering your code:
1. *Extract Common Hooks*: Both components use similar hooks for managing markers, popups, and map references. We can create custom hooks that encapsulate these functionalities.
2. *Create Shared Utility Functions*: Functions like `initialViewState`, which are identical in both components, can be moved to a separate utility file and imported where needed.
3. *Refactor Map Layers and Sources*: The way map layers and sources are handled is quite similar in both components. A custom hook or component to manage map layers and sources would be beneficial.
4. *Generalize Popup Handling*: The popup handling in both components can be abstracted into a custom hook or a higher-order component.
5. *Combine Common Styling*: Shared styles, such as `MAP_CONTAINER_STYLE`, can be moved to a common CSS module or a styled-component that can be reused.
6. *Refactor Event Handlers*: Functions like `onMapClick`, `onMouseMove`, and `onMouseLeave` have similar structures. These can be part of a custom hook or a utility function with configurable parameters.
7. *Legend and Live Region Components*: These components are used in a similar way in both `TravelMap` and `Heatmap`. Ensure they are designed to be reusable with different props.
8. *Refactor Map Initialization*: The way the map is initialized and configured is quite similar. This can be abstracted into a custom component or hook.
### Example Implementations:
#### 1. Custom Hook for Map Markers:
```typescript // useMapMarkers.ts import { useState, useCallback } from 'react';
export const useMapMarkers = (initialLat, initialLng, world) => { // Similar marker logic from your components // ...
return {
marker,
onMarkerDrag,
onMarkerDragEnd,
updateMarkerPosition,
// other marker related states and functions
};
};
```#### 2. Shared Utility Function:
```typescript // utils/mapUtils.ts export const initialViewState = (map, mapType) => { // Implementation }; ```
#### 3. Custom Hook for Map Layers and Sources:
```typescript // useMapLayers.ts import { useState, useEffect } from 'react';
export const useMapLayers = (props) => { // Logic to handle layers and sources // ...
return {
dataLayer,
patternLayer,
// other layer related states and functions
};
};
```#### 4. Generalized Popup Handling:
```typescript // useMapPopup.ts import { useState } from 'react';
export const useMapPopup = () => { // Popup logic from your components // ...
return {
popupState,
openPopup,
closePopup,
setPopupData,
// other popup related states and functions
};
};
```### Integration:
Once these hooks and utilities are created, integrate them into your `TravelMap` and `Heatmap` components. Replace the duplicated logic with calls to these shared resources. This will significantly reduce code duplication and make future maintenance easier.
### Testing and Refinement:
After refactoring, thoroughly test both components to ensure that all functionalities work as expected. Watch out for any edge cases or specific behaviors that might be affected by the refactoring.
For those suggestions, I might use five out of eight of them, and probably do one or two things differently. But you cannot, with a straight face, say the model did not understand. It clearly did. It suggested reasonable refactors. If being able to refactor means understanding, I guess we have understanding!
I could continue with this conversation, ask it to produce the full code for the hooks (I have in my custom prompt to provide outlines) and once the hooks are complete, ask it to rewrite the components using the shared code.
Have you ever used one of these models?
I guess you could use AI to help create a coccinelle semantic patch.
I have been refactoring code using gpt-4 for some months now and the limiting factor have been the context size.
GPT-4 turbo now have 128k context and I can provide it with larger portions of the code base for the refactors.
When we have millions of tokens of context, based on what I'm experiencing now, I can see that a refactoring like the one made in ffmpeg would be possible. Or not? What am I missing here?
Couldn't do the same with larger codebases because the context is not enough for the input code and output refactoring.
I most certainly have not. At work, I do greenfield development in a specialized problem domain, and I would not trust a model (or, for that matter, a junior developer) to do any kind of refactor in an acceptable manner. (That aside, there's no way I'm goingto expose company code to any sort of outside party without the approval of upper management).
At home, I program for fun and self-improvement, and a big part of both is thinking hard about problems. Why would I want to wreck that with asking a model to do it for me?