/work/vvenc/source/Lib/EncoderLib/EncGOP.h
Line | Count | Source |
1 | | /* ----------------------------------------------------------------------------- |
2 | | The copyright in this software is being made available under the Clear BSD |
3 | | License, included below. No patent rights, trademark rights and/or |
4 | | other Intellectual Property Rights other than the copyrights concerning |
5 | | the Software are granted under this license. |
6 | | |
7 | | The Clear BSD License |
8 | | |
9 | | Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors. |
10 | | All rights reserved. |
11 | | |
12 | | Redistribution and use in source and binary forms, with or without modification, |
13 | | are permitted (subject to the limitations in the disclaimer below) provided that |
14 | | the following conditions are met: |
15 | | |
16 | | * Redistributions of source code must retain the above copyright notice, |
17 | | this list of conditions and the following disclaimer. |
18 | | |
19 | | * Redistributions in binary form must reproduce the above copyright |
20 | | notice, this list of conditions and the following disclaimer in the |
21 | | documentation and/or other materials provided with the distribution. |
22 | | |
23 | | * Neither the name of the copyright holder nor the names of its |
24 | | contributors may be used to endorse or promote products derived from this |
25 | | software without specific prior written permission. |
26 | | |
27 | | NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY |
28 | | THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND |
29 | | CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
30 | | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
31 | | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR |
32 | | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
33 | | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
34 | | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR |
35 | | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER |
36 | | IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
37 | | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
38 | | POSSIBILITY OF SUCH DAMAGE. |
39 | | |
40 | | |
41 | | ------------------------------------------------------------------------------------------- */ |
42 | | /** \file EncGOP.h |
43 | | \brief GOP encoder class (header) |
44 | | */ |
45 | | |
46 | | #pragma once |
47 | | |
48 | | #include "EncSampleAdaptiveOffset.h" |
49 | | #include "VLCWriter.h" |
50 | | #include "SEIwrite.h" |
51 | | #include "SEIEncoder.h" |
52 | | #include "Analyze.h" |
53 | | #include "EncPicture.h" |
54 | | #include "CommonLib/Picture.h" |
55 | | #include "CommonLib/CommonDef.h" |
56 | | #include "CommonLib/Nal.h" |
57 | | #include "EncHRD.h" |
58 | | |
59 | | #include <map> |
60 | | #include <set> |
61 | | #include <tuple> |
62 | | #include "EncStage.h" |
63 | | #include "SEIFilmGrainAnalyzer.h" |
64 | | |
65 | | #include <vector> |
66 | | #include <list> |
67 | | #include <stdlib.h> |
68 | | #include <atomic> |
69 | | |
70 | | |
71 | | #include "Utilities/NoMallocThreadPool.h" |
72 | | #include <mutex> |
73 | | #include <condition_variable> |
74 | | |
75 | | //! \ingroup EncoderLib |
76 | | //! \{ |
77 | | |
78 | | namespace vvenc { |
79 | | |
80 | | // ==================================================================================================================== |
81 | | |
82 | | class InputByteStream; |
83 | | class DecLib; |
84 | | class EncHRD; |
85 | | class MsgLog; |
86 | | class GOPCfg; |
87 | | |
88 | | // ==================================================================================================================== |
89 | | |
90 | | class EncGOP; |
91 | | struct FinishTaskParam { |
92 | | EncGOP* gopEncoder; |
93 | | EncPicture* picEncoder; |
94 | | Picture* pic; |
95 | | unsigned setupNum; ///< the picture's place in the order of the setup tasks (when its setup runs as a task) |
96 | 0 | FinishTaskParam() : gopEncoder( nullptr ), picEncoder( nullptr ), pic( nullptr ), setupNum( 0 ) {} |
97 | 1.43k | FinishTaskParam( EncGOP* _g, EncPicture* _e, Picture* _p ) : gopEncoder( _g ), picEncoder( _e ), pic( _p ), setupNum( 0 ) {} |
98 | | }; |
99 | | |
100 | | // ==================================================================================================================== |
101 | | struct RateCapParam { |
102 | | unsigned accumActualBits = 0; |
103 | | unsigned accumTargetBits = 0; |
104 | | unsigned accumGopCounter = 0; |
105 | | double nonRateCapEstim = 0.0; |
106 | | int gopAdaptedQPAdj = 0; |
107 | | |
108 | | void reset() |
109 | 1.43k | { |
110 | 1.43k | accumActualBits = 0; |
111 | 1.43k | accumTargetBits = 0; |
112 | 1.43k | accumGopCounter = 0; |
113 | 1.43k | } |
114 | | }; |
115 | | |
116 | | // ==================================================================================================================== |
117 | | // film grain parameters estimated by the film grain analysis, as signalled in the FGC SEI |
118 | | struct FilmGrainParam { |
119 | | int log2ScaleFactor = 0; |
120 | | SeiFgc::CompModel compModel[ MAX_NUM_COMP ]; |
121 | | |
122 | 0 | FilmGrainParam() = default; |
123 | | // The parameters of the analysis, with the grain strength set to strength percent of the analysed grain. |
124 | | FilmGrainParam( const FGAnalyzer& fgAnalyzer, double strength ) |
125 | 0 | { |
126 | 0 | fgAnalyzer.getSignalledParameters( strength, log2ScaleFactor, compModel ); |
127 | 0 | for( auto& cm : compModel ) |
128 | 0 | { |
129 | | // only the signalled intervals and model values, as the SEI writer expects |
130 | 0 | cm.intensityValues.resize( cm.numIntensityIntervals ); |
131 | 0 | for( auto& iv : cm.intensityValues ) |
132 | 0 | { |
133 | 0 | iv.compModelValue.resize( cm.numModelValues ); |
134 | 0 | } |
135 | 0 | } |
136 | 0 | } |
137 | | }; |
138 | | |
139 | | class EncGOP : public EncStage |
140 | | { |
141 | | private: |
142 | | MsgLog& msg; |
143 | | |
144 | | Analyze m_AnalyzeAll; |
145 | | Analyze m_AnalyzeI; |
146 | | Analyze m_AnalyzeP; |
147 | | Analyze m_AnalyzeB; |
148 | | |
149 | | std::function<void( void*, vvencYUVBuffer* )> m_recYuvBufFunc; |
150 | | void* m_recYuvBufCtx; |
151 | | |
152 | | NoMallocThreadPool* m_threadPool; |
153 | | std::mutex m_gopEncMutex; |
154 | | std::condition_variable m_gopEncCond; |
155 | | // pictures finished so far and the count waitForFreeEncoders last returned on (both guarded by m_gopEncMutex) |
156 | | uint64_t m_numPicsFinished = 0; |
157 | | uint64_t m_numPicsFinishedWaited = 0; |
158 | | XUCache m_shrdUnitCache; |
159 | | std::mutex m_unitCacheMutex; |
160 | | |
161 | | const VVEncCfg* m_pcEncCfg; |
162 | | const GOPCfg* m_gopCfg; |
163 | | RateCtrl* m_pcRateCtrl; |
164 | | HLSWriter m_HLSWriter; |
165 | | SEIWriter m_seiWriter; |
166 | | SEIEncoder m_seiEncoder; |
167 | | BlkStat m_BlkStat; |
168 | | |
169 | | ParameterSetMap<SPS> m_spsMap; |
170 | | ParameterSetMap<PPS> m_ppsMap; |
171 | | EncHRD m_EncHRD; |
172 | | VPS m_VPS; |
173 | | DCI m_DCI; |
174 | | |
175 | | bool m_isPreAnalysis; |
176 | | bool m_bFirstWrite; |
177 | | bool m_bRefreshPending; |
178 | | int m_lastCodingNum; |
179 | | int m_numPicsCoded; |
180 | | int m_numPicsInMissing; |
181 | | int m_numPicsOutOffset; |
182 | | uint64_t m_lastCts; |
183 | | int m_pocRecOut; |
184 | | int m_ticksPerFrameMul4; |
185 | | int m_lastIDR; |
186 | | int m_lastRasPoc; |
187 | | int m_pocCRA; |
188 | | int m_associatedIRAPPOC; |
189 | | vvencNalUnitType m_associatedIRAPType; |
190 | | RateCapParam m_rcap; |
191 | | |
192 | | ThreadRsrcPool m_threadRsrc; ///< CU encoders of the worker threads, shared by all picture encoders |
193 | | bool m_picSetupTasks; ///< the pictures' setups run as thread pool tasks, see xEncodePicture |
194 | | unsigned m_numSetupsQueued; ///< setup tasks queued so far (main thread only) |
195 | | std::atomic<unsigned> m_numSetupsDone; ///< setup tasks finished so far, which lets the next one in order run |
196 | | int64_t m_numPicsStarted; ///< pictures that got a picture encoder so far (main thread only) |
197 | | std::list<EncPicture*> m_freePicEncoderList; |
198 | | std::list<Picture*> m_gopEncListInput; |
199 | | std::list<Picture*> m_gopEncListOutput; |
200 | | std::list<Picture*> m_procList; |
201 | | std::list<Picture*> m_rcUpdateList; |
202 | | std::list<Picture*> m_rcInputReorderList; // used in RC in IFP lines synchro mode |
203 | | std::deque<PicApsGlobal*> m_globalApsList; |
204 | | std::vector<int> m_globalCtuQpVector; |
205 | | bool m_forceSCC; |
206 | | |
207 | | FGAnalyzer m_fgAnalyzer; ///< film grain analysis (--fga) |
208 | | |
209 | | // An analysis, run as a thread pool task. The tasks run one after the other in coding order (each waits |
210 | | // for the previous one), because every analysis adds to the statistics of the previous ones. |
211 | | struct FgaTask |
212 | | { |
213 | | EncGOP* gop = nullptr; |
214 | | Picture* pic = nullptr; |
215 | | int codingNum = 0; |
216 | | int startPoc = std::numeric_limits<int>::min(); ///< the first picture in output order its result is for; written pictures keep theirs |
217 | | bool sceneCut = false; ///< a scene cut lies between the previously analysed picture and this one |
218 | | FilmGrainParam result; |
219 | | WaitCounter counter; |
220 | | }; |
221 | | std::deque<std::unique_ptr<FgaTask>> m_fgaTasks; ///< analyses whose access unit is not written yet |
222 | | std::unique_ptr<FgaTask> m_fgaConsumed; ///< the last consumed task, kept until the next one has run |
223 | | FgaTask* m_fgaLast = nullptr; ///< the last submitted task |
224 | | int m_fgaPrevAnalysedPoc = std::numeric_limits<int>::min(); ///< POC of the last analysed picture |
225 | | // The film grain parameter sets by the POC from which they apply in output order: an analysis applies from the |
226 | | // picture after the previously analysed one, or from a scene cut between them, but never before the picture after |
227 | | // the last written one. The latest few are kept. |
228 | | static constexpr size_t FGC_PARAM_SETS = 8; |
229 | | std::map<int, FilmGrainParam> m_fgcByStartPoc; |
230 | | bool m_fgcCompSignalled[ MAX_NUM_COMP ] = { false, false, false }; ///< components present in a parameter set so far |
231 | | // The POCs of the latest access units written in the current coded layer video sequence (more than two GOPs), and |
232 | | // whether a RASL picture carried a film grain SEI since the last other picture; to decide where the SEI is needed. |
233 | | static constexpr size_t FGC_SEI_HISTORY = 160; |
234 | | std::set<int> m_fgcWrittenPocs; |
235 | | bool m_fgcRaslSeiPending = false; |
236 | | // The film grain SEI fitted to the grain the coding lost (xScaleToLostGrain): per component, intensity interval and |
237 | | // temporal layer, the interval's summed spectra of the latest LOST_GRAIN_POOL pictures of that layer and the last |
238 | | // cut-offs and scaling factor written; per component and temporal layer, the last cut-off shift. Cleared at every |
239 | | // random access point (--fga 2 and 3). |
240 | | struct LostGrainSums |
241 | | { |
242 | | double orig[ 256 ] = {}; |
243 | | double reco[ 256 ] = {}; |
244 | | int blocks = 0; |
245 | | int poc = 0; |
246 | | }; |
247 | | // Only the layer's pictures at most this many pictures before the current one are pooled: the lower temporal layers' |
248 | | // pictures are 4, 8 or more apart, so their pools reached 12, 24 or more pictures back, into different content, while |
249 | | // the highest layer's reached 6. On gangster_chase the pictures of layers 3 and 4 then got 1.6-2.2 times the scaling |
250 | | // factor of the layer-5 pictures between them (--fga 3: 112 / 84 / 82 against 49-53). |
251 | | static constexpr int LOST_GRAIN_POOL_SPAN = 6; |
252 | | struct LostGrainFitted |
253 | | { |
254 | | int h, w, scale; |
255 | | }; |
256 | | using LostGrainKey = std::tuple<int, int, int, unsigned>; ///< component, interval lower and upper bound, temporal layer |
257 | | static constexpr size_t LOST_GRAIN_POOL = 4; |
258 | | std::map<LostGrainKey, std::deque<LostGrainSums>> m_lostGrainHistory; |
259 | | std::map<LostGrainKey, LostGrainFitted> m_lostGrainFitted; |
260 | | std::map<std::pair<int, unsigned>, std::pair<int, int>> m_lostGrainShift; ///< (component, layer) -> (dh, dw) |
261 | | // With the auto-regressive model (--fga 3): per component, the grain of the filter last signalled (FGAnalyzer::arGrain |
262 | | // is computed once per filter, the fit runs for every picture). |
263 | | struct ArGrainOfFilter |
264 | | { |
265 | | std::vector<int> filter; ///< log2 scale factor, then the model values after the scaling factor |
266 | | FGAnalyzer::ArGrain grain; |
267 | | }; |
268 | | ArGrainOfFilter m_arGrain[ MAX_NUM_COMP ]; |
269 | | |
270 | | public: |
271 | | EncGOP( MsgLog& msglog ); |
272 | | virtual ~EncGOP(); |
273 | | |
274 | | void setRecYUVBufferCallback( void* ctx, std::function<void( void*, vvencYUVBuffer* )> func ); |
275 | | |
276 | | void init ( const VVEncCfg& encCfg, const GOPCfg* gopCfg, RateCtrl& rateCtrl, NoMallocThreadPool* threadPool, bool isPreAnalysis ); |
277 | | void printOutSummary ( const bool printMSEBasedSNR, const bool printSequenceMSE, const bool printHexPsnr ); |
278 | | void getParameterSets ( AccessUnitList& accessUnit ); |
279 | | |
280 | | protected: |
281 | | virtual void initPicture ( Picture* pic ); |
282 | | virtual void processPictures( const PicList& picList, AccessUnitList& auList, PicList& doneList, PicList& freeList ); |
283 | | virtual bool hasEnoughPictures( const PicList& picList ) const; |
284 | | virtual bool waitForFreeEncoders(); |
285 | | virtual void startReadyPictures(); |
286 | | |
287 | | private: |
288 | | void xUpdateRasInit ( Slice* slice ); |
289 | | void xProcessPictures ( AccessUnitList& auList, PicList& doneList ); |
290 | | bool xIsLockStep () const; |
291 | | bool xFetchOnEveryPass ( bool lockStepMode ) const; |
292 | | void xStartPictures ( bool lockStepMode, bool fetchOnEveryPass, int maxStarts ); // maxStarts 0: no limit |
293 | | void xEncodePicture ( Picture* pic, EncPicture* picEncoder ); |
294 | | void xOutputRecYuv ( const PicList& picList ); |
295 | | void xReleasePictures ( const PicList& picList, PicList& freeList ); |
296 | | bool xFgaReadsSource ( const Picture& pic ) const; |
297 | | |
298 | | void xInitVPS ( VPS &vps ) const; |
299 | | void xInitDCI ( DCI &dci, const SPS &sps, const int dciId ) const; |
300 | | void xInitConstraintInfo ( ConstraintInfo &ci ) const; |
301 | | void xInitSPS ( SPS &sps ) const; |
302 | | void xInitPPS ( PPS &pps, const SPS &sps ) const; |
303 | | void xInitPPSforTiles ( PPS &pps, const SPS &sps ) const; |
304 | | void xInitRPL ( SPS &sps ) const; |
305 | | void xInitHrdParameters ( SPS &sps ); |
306 | | |
307 | | vvencNalUnitType xGetNalUnitType ( const GOPEntry* _gopEntry ) const; |
308 | | bool xIsSliceTemporalSwitchingPoint ( const Slice* slice, const PicList& picList ) const; |
309 | | |
310 | | void xSetupPicAps ( Picture* pic ); |
311 | | void xAnalyzeFilmGrain ( Picture& pic ); |
312 | | void xRunFgaTask ( FgaTask& task ); |
313 | | void xWaitFgaTasks (); |
314 | | void xInitPicsInCodingOrder ( const PicList& picList ); |
315 | | void xGetProcessingLists ( std::list<Picture*>& procList, std::list<Picture*>& rcUpdateList, const bool lockStepMode ); |
316 | | void xUpdateVAStartOfLastGop ( Picture& keyPic ) const; |
317 | | void xInitGopQpCascade ( Picture& keyPic, PicList::const_iterator picItr, const PicList& picList ); |
318 | | void xInitFirstSlice ( Picture& pic, const PicList& picList, bool isEncodeLtRef ); |
319 | | void xInitSliceTMVPFlag ( PicHeader* picHeader, const Slice* slice ); |
320 | | void xUpdateRPRtmvp ( PicHeader* picHeader, Slice* slice ); |
321 | | void xInitSliceMvdL1Zero ( PicHeader* picHeader, const Slice* slice ); |
322 | | void xSelectReferencePictureList ( Slice* slice ) const; |
323 | | void xSyncAlfAps ( Picture& pic ); |
324 | | |
325 | | void xUpdateRcIfp (); |
326 | | void xWritePicture ( Picture& pic, AccessUnitList& au, bool isEncodeLtRef ); |
327 | | int xWriteParameterSets ( Picture& pic, AccessUnitList& accessUnit, HLSWriter& hlsWriter ); |
328 | | int xWritePictureSlices ( Picture& pic, AccessUnitList& accessUnit, HLSWriter& hlsWriter ); |
329 | | void xAddFilmGrainParameters ( const FgaTask& task ); |
330 | | const FilmGrainParam& xFilmGrainParametersAt( int poc ) const; |
331 | | SeiFgc xFilmGrainSei ( const FilmGrainParam& param, ChromaFormat chromaFormat ); |
332 | | bool xFilmGrainSeiNeeded ( const Slice& slice, const SeiFgc& sei, ChromaFormat chromaFormat ); |
333 | | bool xFitsLostGrain ( ) const; |
334 | | void xStoreLostGrainSpectra ( Picture& pic ) const; |
335 | | void xScaleToLostGrain ( Picture& pic, const Slice& slice, SeiFgc& sei ); |
336 | | void xFitLostGrainAr ( int c, unsigned layer, int bitDepth, int log2ScaleFactor, |
337 | | const std::vector<FGAnalyzer::LostGrainPower>& power, SeiFgc::CompModel& cm ); |
338 | | void xFitLostGrain ( int c, unsigned layer, int bitDepth, bool chroma420, int log2ScaleFactor, |
339 | | const std::vector<FGAnalyzer::LostGrainPower>& power, SeiFgc::CompModel& cm ); |
340 | | void xWriteLeadingSEIs ( Picture& pic, AccessUnitList& accessUnit ); |
341 | | void xWriteTrailingSEIs ( const Picture& pic, AccessUnitList& accessUnit, std::string& digestStr ); |
342 | | int xWriteVPS ( AccessUnitList &accessUnit, const VPS *vps, HLSWriter& hlsWriter ); |
343 | | int xWriteDCI ( AccessUnitList &accessUnit, const DCI *dci, HLSWriter& hlsWriter ); |
344 | | int xWriteSPS ( AccessUnitList &accessUnit, const SPS *sps, HLSWriter& hlsWriter ); |
345 | | int xWritePPS ( AccessUnitList &accessUnit, const PPS *pps, const SPS *sps, HLSWriter& hlsWriter ); |
346 | | int xWriteAPS ( AccessUnitList &accessUnit, const APS *aps, HLSWriter& hlsWriter, vvencNalUnitType eNalUnitType ); |
347 | | void xWriteAccessUnitDelimiter ( AccessUnitList &accessUnit, Slice* slice, bool IrapOrGdr, HLSWriter& hlsWriter ); |
348 | | void xWriteSEI ( vvencNalUnitType naluType, SEIMessages& seiMessages, AccessUnitList &accessUnit, AccessUnitList::iterator &auPos, int temporalId, const SPS *sps ); |
349 | | void xWriteSEISeparately ( vvencNalUnitType naluType, SEIMessages& seiMessages, AccessUnitList &accessUnit, AccessUnitList::iterator &auPos, int temporalId, const SPS *sps ); |
350 | | void xAttachSliceDataToNalUnit ( OutputNALUnit& rNalu, const OutputBitstream* pcBitstreamRedirect ); |
351 | | void xCabacZeroWordPadding ( const Picture& pic, const Slice* slice, uint32_t binCountsInNalUnits, uint32_t numBytesInVclNalUnits, std::ostringstream &nalUnitData ); |
352 | | |
353 | | void xUpdateRateCap(); |
354 | | void xUpdateRateCapBits ( const Picture* pic, const uint32_t uibits ); |
355 | | void xAddPSNRStats( const Picture* pic, CPelUnitBuf cPicD, AccessUnitList&, bool printFrameMSE, double* PSNR_Y, bool isEncodeLtRef ); |
356 | | uint64_t xFindDistortionPlane ( const CPelBuf& pic0, const CPelBuf& pic1, uint32_t rshift ) const; |
357 | | void xPrintPictureInfo ( const Picture& pic, AccessUnitList& accessUnit, const std::string& digestStr, bool printFrameMSE, bool isEncodeLtRef ); |
358 | 2.84k | inline bool xEncodersFinished () { return ( int ) m_freePicEncoderList.size() >= std::max(1, m_pcEncCfg->m_maxParallelFrames); } |
359 | | inline bool xLockStepPicsFinished () |
360 | 0 | { |
361 | 0 | std::lock_guard<std::mutex> lock( m_gopEncMutex ); |
362 | 0 | return ( int ) m_freePicEncoderList.size() >= std::max(1, m_pcEncCfg->m_maxParallelFrames); |
363 | 0 | } |
364 | | void xForceScc ( Picture& pic ); |
365 | | |
366 | | };// END CLASS DEFINITION EncGOP |
367 | | |
368 | | } // namespace vvenc |
369 | | |
370 | | //! \} |
371 | | |