History

avcodec/mjpegenc_huffman: Avoid AV_QSORT to sort entries by length

It is unnecessary, as we already have the entries sorted by probability and therefore implicitly by length. All we need on top of that to build the tree is the number of entries of a given length. Doing so gives a 3.6% speedup of ff_mjpeg_encode_huffman_close() here; it also saves about 640B of .text here. The new code puts values with higher probability to the left of the tree. The old code did not and therefore the FATE checksums needed to be updated. Due to MJPEG's 0xFF unescaping file sizes as well as file checksums needed to be updated; the decoded picture hashes stayed the same. Given that codes on the left of the tree have on average fewer bits set than codes on the right, the file sizes mostly improve (all except vsynth3-mjpeg-444).

Andreas Rheinhardt committed 1 year ago

Commit ff9f3fb1 parent c8ce9de22 files · +118 −133Browse files

Showing the changes to libavcodec (2 of 22 files). Show all

Unified · Split

2 files
  1. libavcodec/mjpegenc_huffman.c +19 −45
  2. libavcodec/tests/mjpegenc_huffman.c +57 −46
libavcodec/mjpegenc_huffman.c+19−45
@@ -43,14 +43,6 @@ typedef struct PackageMergerList { · 42 unmodified lines
4343 int items[257 * 16]; ///< chain of all individual values that make up items A, B, A, B, C, A, B, C, D, C, D, D, E
4444 } PackageMergerList;
4545
46−/**
47− * Used to store optimal huffman encoding results
48− */
49−typedef struct HuffTable {
50− int code; ///< code is the input value
51− int length; ///< length of the encoding
52−} HuffTable;
53−
5446 /**
5547 * Comparison function for two PTables by prob
5648 *
@@ -65,20 +57,6 @@ static int compare_by_prob(const void *a, const void *b) · 8 unmodified lines
6557 return a_val.prob - b_val.prob;
6658 }
6759
68−/**
69− * Comparison function for two HuffTables by length
70− *
71− * @param a First HuffTable to compare
72− * @param b Second HuffTable to compare
73− * @return < 0 for less than, 0 for equals, > 0 for greater than
74− */
75−static int compare_by_length(const void *a, const void *b)
76−{
77− HuffTable a_val = *(HuffTable *) a;
78− HuffTable b_val = *(HuffTable *) b;
79− return a_val.length - b_val.length;
80−}
81−
8260 /**
8361 * Computes the length of the Huffman encoding for each distinct input value.
8462 * Uses package merge algorithm as follows:
@@ -92,15 +70,16 @@ static int compare_by_length(const void *a, const void *b) · 7 unmodified lines
9270 * 8. the length of the huffman code for symbol s will be equal to the number of times the symbol occurs in the select elements
9371 * Go to guru.multimedia.cx/small-tasks-for-ffmpeg/ for more details
9472 *
95− * All probabilities should be positive integers. The output is sorted by code,
96− * not by length.
73+ * All probabilities should be nonnegative integers.
9774 *
98− * @param prob_table input array of a PTable for each distinct input value
99− * @param distincts output array of a HuffTable that will be populated by this function
100− * @param size size of the prob_table array
101− * @param max_length max length of an encoding
75+ * @param prob_table[in,out] array of a PTable for each distinct input value,
76+ * will be sorted according to ascending probability
77+ * @param counts[out] the number of values of a given length
78+ * @param size number of elements of the prob_table array
79+ * @param max_length max length of a code
10280 */
103−static void mjpegenc_huffman_compute_bits(PTable *prob_table, HuffTable *distincts,
81+static void mjpegenc_huffman_compute_bits(PTable *prob_table,
82+ uint8_t counts[/* max_length + 1 */],
10483 int size, int max_length)
10584 {
10685 PackageMergerList list_a, list_b, *to = &list_a, *from = &list_b, *temp;
@@ -159,14 +138,9 @@ static void mjpegenc_huffman_compute_bits(PTable *prob_table, HuffTable *distinc · 52 unmodified lines
159138 }
160139 // we don't want to return the 256 bit count (it was just in here to prevent
161140 // all 1s encoding)
162− j = 0;
163− for (i = 0; i < 256; i++) {
164− if (nbits[i] > 0) {
165− distincts[j].code = i;
166− distincts[j].length = nbits[i];
167− j++;
168− }
169− }
141+ memset(counts, 0, sizeof(counts[0]) * (max_length + 1));
142+ for (int i = 0; i < 256; ++i)
143+ counts[nbits[i]]++;
170144 }
171145
172146 void ff_mjpeg_encode_huffman_init(MJpegEncHuffmanContext *s)
@@ -186,7 +160,6 @@ void ff_mjpeg_encode_huffman_close(MJpegEncHuffmanContext *s, uint8_t bits[17], · 13 unmodified lines
186160 uint8_t val[], int max_nval)
187161 {
188162 PTable val_counts[257];
189− HuffTable distincts[256];
190163
191164 av_assert1(max_nval <= FF_ARRAY_ELEMS(val_counts) - 1);
192165
@@ -201,12 +174,13 @@ void ff_mjpeg_encode_huffman_close(MJpegEncHuffmanContext *s, uint8_t bits[17], · 8 unmodified lines
201174 }
202175 val_counts[nval].value = 256;
203176 val_counts[nval].prob = 0;
204− mjpegenc_huffman_compute_bits(val_counts, distincts, nval + 1, 16);
205− AV_QSORT(distincts, nval, HuffTable, compare_by_length);
206177
207− memset(bits, 0, sizeof(bits[0]) * 17);
208− for (int i = 0; i < nval; i++) {
209− val[i] = distincts[i].code;
210− bits[distincts[i].length]++;
211− }
178+ mjpegenc_huffman_compute_bits(val_counts, bits, nval + 1, 16);
179+
180+ // val_counts[0] is the fake element we added earlier.
181+ av_assert1(val_counts[0].prob == 0 && val_counts[0].value == 256);
182+ // The following loop puts the values with higher occurence first,
183+ // ensuring that they get the shorter codes.
184+ for (int i = 0; i < nval; ++i)
185+ val[i] = val_counts[nval - i].value;
212186 }
libavcodec/tests/mjpegenc_huffman.c+57−46
@@ -34,10 +34,9 @@ · 33 unmodified lines
3434 static int check_lengths(int L, const int *probs, int nprobs,
3535 int expected_length, const uint8_t expected_len_counts[/* L + 1 */])
3636 {
37− HuffTable lengths[256];
3837 PTable val_counts[256];
39− uint8_t len_counts[17] = { 0 };
40− int actual_length = 0, i, j, k, prob, length;
38+ uint8_t len_counts[17];
39+ int actual_length = 0, i;
4140 int ret = 0;
4241 av_assert0(nprobs <= 256);
4342 av_assert0(L < FF_ARRAY_ELEMS(len_counts));
@@ -46,20 +45,12 @@ static int check_lengths(int L, const int *probs, int nprobs, · 2 unmodified lines
4645 val_counts[i] = (PTable){.value = i, .prob = probs[i]};
4746 }
4847
49− mjpegenc_huffman_compute_bits(val_counts, lengths, nprobs, L);
48+ mjpegenc_huffman_compute_bits(val_counts, len_counts, nprobs, L);
5049
51− for (int i = 0; i < nprobs; ++i) {
52− if (lengths[i].length > L) {
53− fprintf(stderr,
54− "Len %d of element %d of Huffman table with %d elements exceeds max length %d\n",
55− lengths[i].length, i, nprobs, L);
56− return 1;
57− }
58− len_counts[lengths[i].length]++;
59− }
6050 // Test that the lengths can be made part of a complete, prefix-free tree:
61− unsigned code = 0;
51+ unsigned code = 0, count = 0;
6252 for (int i = 1; i <= L; ++i) {
53+ count += len_counts[i];
6354 code <<= 1;
6455 code += len_counts[i];
6556 }
@@ -67,22 +58,36 @@ static int check_lengths(int L, const int *probs, int nprobs, · 1 unmodified line
6758 fprintf(stderr, "Huffman tree overdetermined/invalid\n");
6859 ret = 1;
6960 }
70−
71− for (i = 0; i < nprobs; i++) {
72− // Find the value's prob and length
73− for (j = 0; j < nprobs; j++)
74− if (val_counts[j].value == i) break;
75− for (k = 0; k < nprobs; k++)
76− if (lengths[k].code == i) break;
77− if (!(j < nprobs && k < nprobs)) return 1;
78− prob = val_counts[j].prob;
79− length = lengths[k].length;
80−
81− if (prob) {
82− actual_length += prob * length;
61+ if (count != nprobs) {
62+ fprintf(stderr, "Total count %u does not match expected value %d\n",
63+ count, nprobs);
64+ ret = 1;
65+ }
66+ // Test that the input values have been properly ordered.
67+ for (unsigned i = 0; i < count; ++i) {
68+ if (val_counts[i].prob != probs[val_counts[i].value]) {
69+ fprintf(stderr, "PTable not properly reordered\n");
70+ ret = 1;
71+ }
72+ if (i && val_counts[i - 1].prob > val_counts[i].prob) {
73+ fprintf(stderr, "PTable not order ascendingly: [%u] = %d > [%u] = %d\n",
74+ i - 1, val_counts[i - 1].prob, i, val_counts[i].prob);
75+ ret = 1;
76+ }
77+ unsigned j;
78+ for (j = 0; j < count; ++j)
79+ if (val_counts[j].value == i)
80+ break;
81+ if (j >= count) {
82+ fprintf(stderr, "Element %u missing after sorting\n", i);
83+ ret = 1;
8384 }
84−
85− if (length > L || length < 1) return 1;
85+ }
86+ for (int len = L, j = 0; len; --len) {
87+ int prob = 0;
88+ for (int end = j + len_counts[len]; j < end; ++j)
89+ prob += val_counts[j].prob;
90+ actual_length += prob * len;
8691 }
8792 // Check that the total length is optimal
8893 if (actual_length != expected_length) ret = 1;
@@ -141,7 +146,10 @@ static const uint8_t len_counts_sat[] = { · 52 unmodified lines
141146 // http://guru.multimedia.cx/small-tasks-for-ffmpeg/
142147 int main(int argc, char **argv)
143148 {
144− int i, ret = 0;
149+ enum {
150+ MAX_LEN = 3,
151+ };
152+ int ret = 0;
145153 // Probabilities of symbols 0..4
146154 PTable val_counts[] = {
147155 {.value = 0, .prob = 1},
@@ -151,30 +159,33 @@ int main(int argc, char **argv) · 3 unmodified lines
151159 {.value = 4, .prob = 21},
152160 };
153161 // Expected code lengths for each symbol
154− static const HuffTable expected[] = {
155− {.code = 0, .length = 3},
156− {.code = 1, .length = 3},
157− {.code = 2, .length = 3},
158− {.code = 3, .length = 3},
159− {.code = 4, .length = 1},
162+ static const uint8_t expected[MAX_LEN + 1] = {
163+ [1] = 1, [3] = 4,
160164 };
161165 // Actual code lengths
162− HuffTable distincts[5];
166+ uint8_t len_counts[MAX_LEN + 1];
163167
164168 // Build optimal huffman tree using an internal function, to allow for
165169 // smaller-than-normal test cases. This mutates val_counts by sorting.
166− mjpegenc_huffman_compute_bits(val_counts, distincts,
167− FF_ARRAY_ELEMS(distincts), 3);
170+ mjpegenc_huffman_compute_bits(val_counts, len_counts,
171+ FF_ARRAY_ELEMS(val_counts), MAX_LEN);
168172
169− for (i = 0; i < FF_ARRAY_ELEMS(distincts); i++) {
170− if (distincts[i].code != expected[i].code ||
171− distincts[i].length != expected[i].length) {
173+ for (unsigned i = 1; i < FF_ARRAY_ELEMS(len_counts); i++) {
174+ if (len_counts[i] != expected[i]) {
172175 fprintf(stderr,
173176 "Built huffman does not equal expectations. "
174− "Expected: code %d probability %d, "
175− "Actual: code %d probability %d\n",
176− expected[i].code, expected[i].length,
177− distincts[i].code, distincts[i].length);
177+ "Expected: %d codes of length %u, "
178+ "Actual: %d codes of length %u\n",
179+ (int)expected[i], i,
180+ (int)len_counts[i], i);
181+ ret = 1;
182+ }
183+ }
184+ for (unsigned i = 1; i < FF_ARRAY_ELEMS(val_counts); ++i) {
185+ if (val_counts[i - 1].prob > val_counts[i].prob) {
186+ fprintf(stderr, "Probability table not ordered ascendingly. "
187+ "val_counts[%u] == %d, val_counts[%u] == %d\n",
188+ i - 1, val_counts[i - 1].prob, i, val_counts[i].prob);
178189 ret = 1;
179190 }
180191 }

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t