Русские Блоги
В стандарте кодирования видео H.264 / AVC вся структура системы разделена на два уровня: уровень кодирования видео (VCL) и уровень сетевой абстракции (NAL). Среди них первый отвечает за эффективное представление содержимого видеоданных, а второй отвечает за форматирование данных и предоставление информации заголовка, чтобы гарантировать, что данные подходят для передачи по различным каналам и носителям. NAL занимает один байт.
H264 передает NALU по сети. Структура NALU следующая: заголовок NAL + RBSP. Фактический поток данных при передаче показан на рисунке:
Блок NAL (NALU): основная синтаксическая структура NAL, которая содержит байт информации заголовка и серию байтовых потоков, называемых полезной нагрузкой необработанной байтовой последовательности (RBSP) из VCL. Когда поток данных хранится на носителе: Добавьте начальный код: 0x00000001 (или 0x000001) перед каждым NALU, чтобы указать начальную и конечную позицию NALU. Каждый кадр данных, который мы обычно используем, является блоком NAL (кроме SPS и PPS).
Кодер помещает каждый NAL в пакет независимо и полностью.Поскольку пакет имеет заголовок, декодер может легко обнаружить границу NAL и, в свою очередь, извлечь NAL для декодирования. Перед каждым NAL находится начальный код 0x00 00 01 (или 0x00 00 00 01). Декодер определяет каждый стартовый код как идентификатор начала NAL. Когда обнаруживается следующий начальный код, текущий NAL заканчивается. В то же время H.264 предусматривает, что обнаружение 0x000000 также может означать конец текущего NAL. Итак, что мне делать, когда в данных в NAL появляется 0x000001 или 0x000000? H.264 вводит механизм предотвращения конкуренции. Если кодировщик обнаруживает присутствие 0x000001 или 0x000000 в данных NAL, кодировщик вставляет новый байт 0x03 перед последним байтом, например:
0x000000->0x00000300
0x000001->0x00000301
0x000002->0x00000302
0x000003->0x00000303
Когда декодер обнаруживает 0x000003, он отбрасывает 03 и восстанавливает исходные данные (операция распаковки). Когда декодер выполняет декодирование, он сначала читает байты данных NAL, подсчитывает длину NAL, а затем начинает декодирование.
Заголовок NALU состоит из одного байта и имеет следующий синтаксис:
+—————+
|0|1|2|3|4|5|6|7|
+-+-+-+-+-+-+-+-+
|F|NRI| Type |
+—————+
F: 1 бит.
Forbidden_zero_bit. В спецификации H.264 указано, что этот бит должен быть равен 0.
NRI: 2 бита.
nal_ref_idc. Возьмите 00
11, это, кажется, указывает на важность этого NALU, например, декодер 00 NALU может отбросить его, не влияя на воспроизведение изображения, 0
3, чем больше значение, тем важнее текущий NAL, он в первую очередь необходимо защитить. Если текущий NAL является срезом, принадлежащий к системе отсчета, или набору параметров последовательности или важному блоку, таким как набор параметров изображения, этот синтаксис элемент должен быть больше 0.
Тип: 5 бит.
Nal_unit_type. Тип этой единицы NALU. Краткое описание выглядит следующим образом:
0 Нет определения
1 полоса кодирования изображения без IDR (кадр bp)
slice_layer_without_partitioning_rbsp( )
2 Блок сегментации данных полосы кодирования A
slice_data_partition_a_layer_rbsp( )
3 Блок сегментации данных полосы кодирования B
slice_data_partition_b_layer_rbsp( )
4 Блок сегментации данных полосы кодирования C
slice_data_partition_c_layer_rbsp( )
5 кодовых полос IDR изображений (i-frame)
slice_layer_without_partitioning_rbsp( )
6 Дополнительная расширенная информация (SEI)
sei_rbsp( )
7 Набор параметров последовательности (кадр sps)
seq_parameter_set_rbsp( )
8 Набор параметров изображения
pic_parameter_set_rbsp (кадр в секунду)
9 Разделитель блока доступа
access_unit_delimiter_rbsp( )
10 Конец последовательности
end_of_seq_rbsp( )
11 Конец трансляции
end_of_stream_rbsp( )
12 Заполните данные
filler_data_rbsp( )
13 Расширение набора параметров последовательности
seq_parameter_set_extension_rbsp( )
14 . 18 Зарезервировано
19 Кодирующие полосы неразделенного вспомогательного кодированного изображения
slice_layer_without_partitioning_rbsp( )
20 . 23 Зарезервировано
24 STAP-A Одноразовый пакет
25 STAP-B Одноразовый пакет
26 MTAP16 Многократный пакет времени
27 MTAP24 Многократный пакет времени
28 FU-A Фрагментированный блок
29 ФУ-Б Фрагментированный блок
30-31 не определено
При обнаружении 00 00 00 01 67 это означает кадр sps
При обнаружении 00 00 00 01 68 это означает кадр pps
Поскольку информация о длине не дается в грамматике NAL, фактическая система передачи и хранения должна добавлять дополнительные заголовки, чтобы реализовать разграничение каждого блока NAL.
Среди них файл AVI и широковещательный поток MPEG TS принимают формат синтаксиса байтового потока, то есть код синхронизации 0x00000001 добавляется перед блоком NAL, а следующий видеокадр H.264 читается из файла AVI или MPEG TS. Пакет PES Форма лапши существует:
Для файлов MP4 перед блоком NAL нет кода синхронизации, но есть код длины в несколько байтов, чтобы указать длину блока NAL. Число байтов, занимаемых этим кодом длины, дается заголовком файла MP4; в Кроме того, он читается из MP4. Видеокадр не содержит PPS и SPS, эта информация находится в заголовке файла MP4, парсер должен получить их при открытии файла. Кадр H.264, считанный из файла MP4, часто имеет следующую форму (при условии, что длина кода составляет 2 байта):
Анализ алгоритмов, связанных с синтаксисом H264
1. Беззнаковое экспоненциальное энтропийное кодирование Колумба.
1.1 Процесс кодирования
1. Добавьте 1 к числу, которое нужно закодировать, и преобразуйте его в наименьшую двоичную последовательность (при условии, что всего M битов);
2. Добавьте M-1 0 перед этой двоичной последовательностью;
3、enjoy!
1.1.1 Пример
Выполните беззнаковое экспоненциальное энтропийное кодирование Колумба на 4
1. Преобразуйте 4 плюс 1 (то есть 5) в наименьшую двоичную последовательность, которая равна 101 (это M = 3).
2. Добавьте M-1 перед этой двоичной последовательностью, то есть два нуля.
3. Полученная последовательность беззнакового энтропийного кодирования Колумба 4 равна 00101.
1.2 Процесс декодирования
1. Получите N последовательных нулей в начале двоичной последовательности.
2. Значение N + 1 бита после чтения, если это X
3. X-1 получает декодированное значение.
1.2.1 Пример
Например, выполнить беззнаковое экспоненциальное энтропийное декодирование Колумба на 00101
1. Получите N последовательных нулей в начале, в это время N = 2
2. Считайте значение N + 1 бита в обратном направлении, то есть 101, что равно 5.
3. 5-1 = 4 Получите его декодированное кодовое значение, наслаждайтесь!
1.3 Другое
Обратите внимание, что беззнаковая экспонента 0, двоичная последовательность энтропийного кодирования Колумба равна 1
2 Знаковое экспоненциальное энтропийное кодирование Колумба
2.1 Процесс кодирования
1. Преобразуйте абсолютное значение числа, которое нужно закодировать, в наименьшую двоичную последовательность (при условии, что всего M бит).
2. Добавьте знаковый бит после этой двоичной последовательности, 0 означает положительное значение, 1 означает отрицательное значение.
3. Добавьте M 0 перед этой двоичной последовательностью.
4、enjoy
2.1.1 Пример 1
Например, экспоненциальное энтропийное кодирование Колумба со знаком выполняется на 4
Абсолютное значение 1, 4 преобразуется в наименьшую двоичную последовательность, которая равна 100 (в это время M = 3).
2. Бит знака добавлен сзади, 0 — 1000.
3. Добавьте M 0 впереди, то есть 0001000.
4、enjoy
2.1.2 Пример 2
Например, экспоненциальное энтропийное кодирование Колумба со знаком для -15
1. Абсолютное значение -7 преобразуется в наименьшую двоичную последовательность, которая равна 1111 (в настоящее время M = 4).
2. Бит знака добавлен сзади, 1, что составляет 11111.
3. Добавьте M 0 впереди, то есть 000011111.
4、enjoy
2.2 Процесс декодирования
1. Получите N последовательных нулей в начале двоичной последовательности.
2. Значение N бит после чтения, если это X
3. Получите последний знаковый бит
4. Получите декодированное значение кода.
2.2.1 Пример 1
Например, выполнить экспоненциальное энтропийное декодирование Голомба со знаком для двоичной последовательности 0001000.
1. Получите N последовательных нулей в начале, в это время N = 3
2. Затем получите N как значение, то есть 100 равно 4.
3. Получить последний знаковый бит, 0 — положительное значение.
4. Следовательно, значение декодированного кода этой последовательности равно 4
2.2.2 Пример 2
Например, выполнить экспоненциальное энтропийное декодирование Голомба со знаком для двоичной последовательности 000011111
1. Получите N последовательных нулей в начале, в это время N = 4
2. Затем возьмите N в качестве значения, то есть 1111 равно 15.
3. Получите последний знаковый бит, 1, который является отрицательным значением.
4. Следовательно, значение декодированного кода этой последовательности равно -15.
The H.264 Sequence Parameter Set
This is a follow-up to my World’s Smallest H.264 Encoder post. I’ve received several emails asking about precise details of things in two entities in the H.264 bitstream: the Sequence Parameter Set (SPS) and the Picture Parameter Set (PPS). Both entities contain information that an H.264 decoder needs to decode the video data, for example, the resolution and frame rate of the video.
Recall that an H.264 bitstream contains a sequence of Network Abstraction Layer (NAL) units. The SPS and PPS are both types of NAL units. The SPS NAL unit contains parameters that apply to a series of consecutive coded video pictures, referred to as a “coded video sequence” in the H.264 standard. The PPS NAL unit contains parameters that apply to the decoding of one or more individual pictures inside a coded video sequence.
Using the SPS & PPS for Data Stream
In the case of my simple encoder, we emitted a single SPS and PPS at the start of the video data stream, but in the case of a more complex encoder, it would not be uncommon to see them inserted periodically in the data for two reasons — first, often a decoder will need to start decoding midstream, and second, because the encoder may wish to vary parameters for different parts of the stream in order to achieve better compression or quality goals.
In my trivial encoder, the h.264 SPS and PPS were hardcoded in hex as:
Let’s decode this into something readable from the spec. The first thing I did was to look at section 7 of the H.264 specification. I saw that at a minimum I had to choose how to fill in the SPS parameters in the table below. In the table, as in the standard, the type u(n) indicates an unsigned integer of n bits, and ue(v) indicates an unsigned exponential-Golomb-coded value of a variable number of bits. The spec doesn’t seem to define the maximum number of bits anywhere, but the reference encoder software uses 32. (People wishing to explore the security of decoder software may find it interesting to violate this assumption!)
Parameter Name | Type | Value | Comments |
forbidden_zero_bit | u(1) | 0 | Despite being forbidden, it must be set to 0! |
nal_ref_idc | u(2) | 3 | 3 means it is “important” (this is an SPS). |
nal_unit_type | u(5) | 7 | Indicates this is a sequence parameter set. |
profile_idc | u(8) | 66 | Baseline profile. |
constraint_set0_flag | u(1) | 0 | We’re not going to honor constraints. |
constraint_set1_flag | u(1) | 0 | We’re not going to honor constraints. |
constraint_set2_flag | u(1) | 0 | We’re not going to honor constraints. |
constraint_set3_flag | u(1) | 0 | We’re not going to honor constraints. |
reserved_zero_4bits | u(4) | 0 | Better set them to zero. |
level_idc | u(8) | 10 | Level 1, sec A.3.1. |
seq_parameter_set_id | ue(v) | 0 | We’ll just use id 0. |
log2_max_frame_num_minus4 | ue(v) | 0 | Let’s have as few frame numbers as possible. |
pic_order_cnt_type | ue(v) | 0 | Keep things simple. |
log2_max_pic_order_cnt_lsb_minus4 | ue(v) | 0 | Fewer is better. |
num_ref_frames | ue(v) | 0 | We will only send I slices. |
gaps_in_frame_num_value_allowed_flag | u(1) | 0 | We will have no gaps. |
pic_width_in_mbs_minus_1 | ue(v) | 7 | SQCIF is 8 macroblocks wide. |
pic_height_in_map_units_minus_1 | ue(v) | 5 | SQCIF is 6 macroblocks high. |
frame_mbs_only_flag | u(1) | 1 | We will not to field/frame encoding. |
direct_8x8_inference_flag | u(1) | 0 | Used for B slices. We will not send B slices. |
frame_cropping_flag | u(1) | 0 | We will not do frame cropping. |
vui_prameters_present_flag | u(1) | 0 | We will not send VUI data. |
rbsp_stop_one_bit | u(1) | 1 | Stop bit. I missed this at first and it caused me much trouble. |
Some key things here are the profile ( profile_idc ) and level ( level_idc ) that I chose, and the picture width and height. If you encode the above table in hex, you will get the values in the SPS array declared above.
SPS, PPS Parameters
A question I got a couple of times in email was about the width and height parameters — specifically, what to do if the picture width or height is not an integer multiple of macroblock size. Recall that, for the 4:2:0 sampling scheme in my encoder, a macroblock consists of 16×16 luma samples. In this case, you would set the frame_cropping_flag to 1, and reduce the number of pixels in the horizontal and vertical direction with the frame_crop_left_offset , frame_crop_right_offset , frame_crop_top_offset , and frame_crop_bottom_offset parameters, which are conditionally present in the bitstream only if the frame_cropping_flag is set to one.
One interesting problem that we see fairly often with H.264 is when the container format (MP4, MOV, etc.) contains different values for some of these parameters than the SPS and PPS. In this case, we find different video players handle the streams differently.
Decoding H.264 Bitstreams Using the H264Bitstream Tool & SPS, PPS
A handy tool for decoding H.264 bitstreams, including the SPS, is the h264bitstream tool. It comes with a command-line program that decodes a bitstream to the parameter names defined in the h.264 specification. Let’s look at its output for a sample mp4 file I downloaded from youtube. First, I extract the H.264 NAL units from the file using ffmpeg:
The NAL units now reside in the file of.h264 . I then run the h264_analyze command from the h264bitstream package to produce the following output:
The only additional thing I’d like to point out here is that this particular SPS also contains information about the frame rate of the video (see timing_info_present_flag ). These parameters must be closely checked when you generate bitstreams to ensure they agree with the container format that the H.264 will eventually be muxed into. Even a small error, such as 29.97 fps in one place and 30 fps in another, can result in severe audio/video synchronization problems.
Next time, I will write about the H.264 Picture Parameter Set (PPS).
If you enjoyed this blog, subscribe to our quarterly newsletter below!
What is SPS and PPS in h264?
The SPS NAL unit contains parameters that apply to a series of consecutive coded video pictures, referred to as a “coded video sequence” in the H. 264 standard. The PPS NAL unit contains parameters that apply to the decoding of one or more individual pictures inside a coded video sequence.
What is SPS in video?
sequence parameter sets (SPS), which apply to a series of consecutive coded video pictures called a coded video sequence. picture parameter sets (PPS), which apply to the decoding of one or more individual pictures within a coded video sequence.
Is H 264 a codec?
A codec based on the H. 264 standard compresses a digital video file (or stream) so that it only requires half of the storage space (or network bandwidth) of MPEG-2. Through this compression, the codec is able to maintain the same video quality despite using only half of the storage space.
What are PPS and SPS?
GPS provides two different positioning services: the Precise Positioning Service (PPS) and the Standard Positioning Service (SPS).
Is H 264 better than h265?
265 codec, also referred to as High-Efficiency Video Coding (HEVC), is the worthy successor to H. 264. 264, this newer standard offers from 25% to 50% better data compression at the same level of video quality. It basically delivers high-quality videos at the same bitrate.
What does G stand for in GPS?
GPS is an abbreviation for global positioning system. a GPS receiver.
Which is the main parameter used in pseudo ranging?
Pseudo ranging uses time parameter as its main constituent.
What are the types of GPS?
Types of GPS systems
- Street navigation systems (sat-nav) You’ll never get lost driving with this type of GPS, since it gives turn-by-turn directions, including mileage, speed and estimated time of arrival.
- Sports GPS systems and watches.
- PDA based systems.
- Phones with GPS.
- For kids too!
What are the fixes for the x264 encoder?
Fixes segfaults on Windows where the stack is only 16-byte aligned. 5x speed up vs C code. This version supports converting aarch64 assembly for MS armasm64.exe. crashes if such a read crosses a page boundary into an invalid page. using memory-mapped input frames. This may sometimes require copying the
What was the purpose of the H.264 project?
The intent of the H.264/AVC project was to create a standard capable of providing good video quality at substantially lower bit rates than previous standards (i.e., half or less the bit rate of MPEG-2, H.263, or MPEG-4 Part 2 ), without increasing the complexity of design so much that it would be impractical or excessively expensive to implement.
Is the H.264 standard a family of standards?
The H.264 standard can be viewed as a “family of standards” composed of a number of different profiles, although its “High profile” is by far the mostly commonly used format. A specific decoder decodes at least one, but not necessarily all profiles.
What kind of coding is used in H.264?
H.264 was standardized by the ITU-T Video Coding Experts Group (VCEG) together with the ISO/IEC JTC1 Moving Picture Experts Group (MPEG). The project partnership effort is known as the Joint Video Team (JVT).
What’s the difference between PPS and SPS in video codecs?
Answer Wiki. In the context of video codecs, PPS refers to Picture Parameter Set and SPS refers to Sequence Parameter Set. Let me give you a bit of a background before we start to understand these.
Why was parameter set introduced in H.264?
During the design of H.264/AVC, it was recognized that the vulnerability of a picture header is an architectural issue of the video codec itself, rather than a transport problem, and therefore the parameter set concept was introduced as a fix for the issue.
What’s the difference between SPS and PPS in GPS?
SPS & PPS is abbreviation of Standard Positioning Service & Precise Positioning Service. 2 services methodology used in GPS (Global Positioning System) Technology. A fast and secure file transfer service for large media files. Transfer large media files with no file size or bandwidth limits. Try Media Shuttle for yourself. You dismissed this ad.
What is the mainmodulehazard Communication Standard ( HCS / GHS )?
MAINMODULEHAZARD COMMUNICATION STANDARD WITH GLOBALLY HARMONIZED SYSTEM OF CLASSIFICATION AND LABELING OF CHEMICALS(HCS/GHS) ACKNOWLEDGEMENT UNITED STATES DEPARTMENT OF LABOROccupational Health and Safety Administration (OSHA)Susan Harwood Training Follow-On Grant
Sps pps что это
What is SPS PPS in video?
sequence parameter sets (SPS), which apply to a series of consecutive coded video pictures called a coded video sequence. picture parameter sets (PPS), which apply to the decoding of one or more individual pictures within a coded video sequence.
What is Vui in h264?
Video Usability Information (VUI): Carries information necessary to reconstruct video from the reconstructed picture/slices.
What is IDR frame?
An IDR frame is a special type of I-frame in H. 264. An IDR frame specifies that no frame after the IDR frame can reference any frame before it. This makes seeking the H. 264 file easier and more responsive in the player. Dec 27, 2011
Which is better H 264 or H 265?
265 is a video compression standard that was designed for the newest generation of high-resolution video. Compared to H. 264, this newer standard offers from 25% to 50% better data compression at the same level of video quality. It basically delivers high-quality videos at the same bitrate. Mar 19, 2021
Which is better x264 or H264?
The benefit of h. 264 is better compression than, say, Mpeg 2, or Mpeg 4 part 2 (Xvid, Divx). «Better compression» means better quality at the same size as those other codecs, smaller size with the same quality, or something in between. x264 is an open source h.
What is difference between H264 and H265?
H265 is the newer iteration of video compression in the same lineage of the H264 codec. It is able to achieve a file size reductions approximately 64% smaller at 4k, and 57% smaller at 1080p than its H264 counterpart. However, this comes at the cost of more processing power. Sep 2, 2020
What are IP and B frames?
An I‑frame (Intra-coded picture) is a complete image, like a JPG or BMP image file. . A B‑frame (Bidirectional predicted picture) saves even more space by using differences between the current frame and both the preceding and following frames to specify its content.
What is IDR interval?
In KineMaster, the IDR interval is the average time between IDR frames in a video clip.
Is lower keyframe interval better?
The higher the keyframe interval, generally the more compression that is being applied to the content, although that doesn’t mean a noticeable reduction in quality. Apr 13, 2021
Related questions
Related
Is MPEG 4 better than h264?
264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk. The image quality is also better and playback is more fluent than with basic MPEG-4 compression. Nov 9, 2009
Related
Is h264 good quality?
H. 264 was created to provide high-quality transmission of full-motion video with lower bandwidth requirements and lower latency traditional video standards, such as MPEG-2. H. 264 uses a very efficient codec that provides high-quality images and uses a minimal amount of bandwidth.
Related
Is HEVC better than MKV?
MKV files encoded in HEVC format has a lower bit rate than an H. 264 MKV file, therefore, it can reduce the file size to 40-50% smaller than the H. 264 file while still retains the video quality to the same file in H. . 264 is still one of the most popular formats used in the compression of videos. Sep 22, 2015