2
0

treecoder.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <assert.h>
  11. #include <stdio.h>
  12. #include "vp8/common/treecoder.h"
  13. static void tree2tok(struct vp8_token_struct *const p, vp8_tree t, int i, int v,
  14. int L) {
  15. v += v;
  16. ++L;
  17. do {
  18. const vp8_tree_index j = t[i++];
  19. if (j <= 0) {
  20. p[-j].value = v;
  21. p[-j].Len = L;
  22. } else {
  23. tree2tok(p, t, j, v, L);
  24. }
  25. } while (++v & 1);
  26. }
  27. void vp8_tokens_from_tree(struct vp8_token_struct *p, vp8_tree t) {
  28. tree2tok(p, t, 0, 0, 0);
  29. }
  30. void vp8_tokens_from_tree_offset(struct vp8_token_struct *p, vp8_tree t,
  31. int offset) {
  32. tree2tok(p - offset, t, 0, 0, 0);
  33. }
  34. static void branch_counts(int n, /* n = size of alphabet */
  35. vp8_token tok[/* n */], vp8_tree tree,
  36. unsigned int branch_ct[/* n-1 */][2],
  37. const unsigned int num_events[/* n */]) {
  38. const int tree_len = n - 1;
  39. int t = 0;
  40. assert(tree_len);
  41. do {
  42. branch_ct[t][0] = branch_ct[t][1] = 0;
  43. } while (++t < tree_len);
  44. t = 0;
  45. do {
  46. int L = tok[t].Len;
  47. const int enc = tok[t].value;
  48. const unsigned int ct = num_events[t];
  49. vp8_tree_index i = 0;
  50. do {
  51. const int b = (enc >> --L) & 1;
  52. const int j = i >> 1;
  53. assert(j < tree_len && 0 <= L);
  54. branch_ct[j][b] += ct;
  55. i = tree[i + b];
  56. } while (i > 0);
  57. assert(!L);
  58. } while (++t < n);
  59. }
  60. void vp8_tree_probs_from_distribution(int n, /* n = size of alphabet */
  61. vp8_token tok[/* n */], vp8_tree tree,
  62. vp8_prob probs[/* n-1 */],
  63. unsigned int branch_ct[/* n-1 */][2],
  64. const unsigned int num_events[/* n */],
  65. unsigned int Pfac, int rd) {
  66. const int tree_len = n - 1;
  67. int t = 0;
  68. branch_counts(n, tok, tree, branch_ct, num_events);
  69. do {
  70. const unsigned int *const c = branch_ct[t];
  71. const unsigned int tot = c[0] + c[1];
  72. assert(tot < (1 << 24)); /* no overflow below */
  73. if (tot) {
  74. const unsigned int p = ((c[0] * Pfac) + (rd ? tot >> 1 : 0)) / tot;
  75. probs[t] = p < 256 ? (p ? p : 1) : 255; /* agree w/old version for now */
  76. } else {
  77. probs[t] = vp8_prob_half;
  78. }
  79. } while (++t < tree_len);
  80. }