summaryrefslogtreecommitdiff
path: root/docs/TECH
blob: ded9a7a01b1ea2389ede9dfd8f4dac7897d02735 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
                        Rockbox From A Technical Angle
                        ==============================

Background

  [Most, if not all, of this document is completely outdated. You should rather
  hunt down this info in the Rockbox wiki or source code!]

  Björn Stenberg started this venture back in the late year 2001. The first
  Rockbox code was committed to CVS end of March 2002. Rockbox 1.0 was
  released in June.

Booting and (De)Scrambling

  The built-in firmware in the Archos Jukebox reads a file from disk into
  memory, descrambles it, verifies the checksum and then runs it as code. When
  we build Rockbox images, we scramble the result file to use the same kind of
  scrambling that the original Archos firmware uses so that it can be loaded
  by the built-in firmware.

  1) The built-in firmware starts
  2) It looks in the root directory for a file called "archos.mod" (player)
     or "ajbrec.ajz" (recorder)
  3) If it finds one, it loads the file, descrambles it and runs it

CPU

  The CPU in use is a SH7034 from Hitachi, running at 11.0592MHz (recorder)
  or 12MHz (player).
  Most single instructions are executed in 1 cycle. There is a 4KB internal RAM
  and a 2MB external RAM.

Memory Usage

  All Archos Jukebox models have only 2MB RAM. The RAM is used for everything,
  including code, graphics and config. To be able to play as long as possible
  without having to load more data, the size of the mpeg playing buffer must
  remain as big as possible. Also, since we need to be able to do almost
  everything in Rockbox simultaneously, we use no dynamic memory allocation
  system at all. All sub-parts that needs memory must allocate their needs
  staticly. This puts a great responsibility on all coders.

Playing MPEG

  The MPEG decoding is performed by an external circuit, MAS3507D (for the
  Player/Studio models) or MAS3587F (for the Recorder models).

  The CPU has a serial connection to the MAS for MP3 playback, using serial
  port 0 at approx. 1mbit/s. The MAS has a handshake signal called DEMAND,
  that informs the CPU when it wants more MP3 data. Whenever the DEMAND
  signal goes high, it wants data sent over the serial line, and it wants it
  quickly, within ~1ms. When the MAS has received enough data, it negates the
  DEMAND signal and expects the incoming data stream to stop within 1ms.

  The DEMAND signal is connected to a port pin on the CPU which can generate
  an IRQ, but only on the falling edge. That means that the mpeg driver code
  must poll the DEMAND signal every ms to keep the MAS happy. The mpeg code
  does use the IRQ to detect the falling edge when the MAS is "full".

  Unfortunately, the serial port on the CPU sends the LSB first, and the MAS
  expects the MSB first. Therefore we have to revers the bit order in every
  byte in the loaded MP3 data. This is referred to as "bit swapping" in the
  Rockbox code.

  The internal DMA controller is used to feed the serial port with data. The
  driver works roughly like this:

  1) Load MP3 data into the RAM buffer
  2) Bitswap the data
  3) Load the DMA source pointer to the next 64Kbyte block to be transferred
  4) Wait until DEMAND is high
  5) Enable the DMA
  6) Wait until the falling DEMAND pin generates an IRQ
  7) Disable the DMA
  8) Go to 4

  The DMA generates an IRQ when the 64Kbyte block is transferred, and the
  IRQ handler updates the DMA source pointer.


                    _____________________________
                    |                           |
  DEMAND  __________|                           |_____________
                        _  _  _  _  _  _  _  _  _
  SC0     _____________/ \/ \/ \/ \/ \/ \/ \/ \/ \____________
                       \_/\_/\_/\_/\_/\_/\_/\_/\_/
                      ^                         ^
                      |                         |
              Poll sees the DEMAND       The DEMAND pin generates
              signal go high and         an IRQ that in turn disables
              enables the DMA            the DMA again

Spinning The Disk Up/Down

  To save battery, the spinning of the harddrive must be kept at a minimum.
  Rockbox features a timeout, so that if no action has been performed within N
  seconds, the disk will spin-down automaticly. However, if the disk was used
  for mpeg-loading for music playback, the spin-down will be almost immediate
  as then there's no point in timing out. The N second timer is thus only used
  when the disk-activity is trigged by a user.

FAT and Mounting

  Rockbox scans the partitions of the disk and tries to mount them as fat32
  filesystems at boot.

Directory Buffer

  When using the "dir browser" in Rockbox to display a single directory, it
  loads all entries in the directory into memory first, then sorts them and
  presents them on screen. The buffer used for all file entries is limited to
  maximum 16K or 400 entries. If the file names are longish, the 16K will run
  out before 400 entries have been used.

  This rather limited buffer size is of course again related to the necessity
  to keep the footprint small to keep the mpeg buffer as large as possible.

Playlist Concepts

  One of the most obvious limitations in the firmware Rockbox tries to
  outperform, was the way playlists were dealt with.

  When loading a playlist (which is a plain text file with file names
  separated by newlines), Rockbox will scan through the file and store indexes
  to all file names in an array. The array itself has a 10000-entry limit (for
  memory size reasons).

  To play a specific song from the playlist, Rockbox checks the index and then
  seeks to that position in the original file on disk and gets the file name
  from there. This way, very little memory is wasted and yet very large
  playlists are supported.

Playing a Directory

  Playing a full directory is using the same technique as with playlists. The
  difference is that the playlist is not a file on disk, but is the directory
  buffer.

Shuffle

  Since the playlist is a an array of indexes to where to read the file name,
  shuffle modifies the order of these indexes in the array. The algorithm is
  pretty much like shuffling a deck of cards, and it uses a pseudo random
  generator called the Mersenne Twister. The randomness is identical for the
  same random seed. This is the secret to good resume. Even when you've shut
  down your unit and re-starts it, using the same random seed as the previous
  time will give exactly the same random order.

Saving Config Data

  The Player/Studio models have no battery-backuped memory while the Recorder
  models have 44 bytes battery-backuped.

  To save data to be persistent and around even after reboots, Rockbox uses
  harddisk sector 63, which is outside the FAT32 filesystem. (Recorder models
  also get some data stored in the battery-backuped area).

  The config is only saved when the disk is spinning. This is important to
  realize, as if you change a config setting and then immediately shuts your
  unit down, the new config is not saved.

  DEVELOPERS:
  The config checksum includes a header with a version number. This version
  number must be increased when the config structure becomes incompatible.
  This makes the checksum check fail, and the settings are reset to default
  values.

Resume Explained

  ...

Charging

  (Charging concerns Recorder models only, the other models have hardware-
  controlled charging that Rockbox can't affect.)

  ...

Profiling

  Rockbox contains a profiling system which can be used to monitor call count
  and time in function for a specific set of functions on a single thread.

  To use this functionality:
  1) Configure a developer build with profiling support.
  2) Make sure that the functions of interest will be compiled with the
     PROFILE_OPTS added to their CFLAGS
  3) On the same thread as these functions will be run, surround the relevent
     running time with calls to profile_thread and profstop.  (For codecs,
     this can be done in the codec.c file for example)
  4) Compile and run the code on the target, after the section to be profiled
     exits (when profstop is called) a profile.out file will be written to
     the player's root.
  5) Use the tools/profile_reader/profile_reader.pl script to convert the 
     profile.out into a human readable format.  This script requires the
     relevent map files and object (or library) files created in the build.
     (ex: ./profile_reader.pl profile.out vorbis.map libTremor.a 0)

  There is also a profile_comparator.pl script which can compare two profile
  runs as output by the above script to show percent change from optimization

  profile_reader.pl requires a recent binutils that can automatically handle
  target object files, or objdump in path to be the target-objdump.
='#n459'>459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
/*
 * header.c
 * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
 * Copyright (C) 2003      Regis Duchesne <hpreg@zoy.org>
 * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
 *
 * This file is part of mpeg2dec, a free MPEG-2 video stream decoder.
 * See http://libmpeg2.sourceforge.net/ for updates.
 *
 * mpeg2dec is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * mpeg2dec is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id$
 * libmpeg2 sync history:
 * 2008-07-01 - CVS revision 1.101
 */

#include "plugin.h"

#include "mpeg2dec_config.h"

#include "mpeg2.h"
#include "attributes.h"
#include "mpeg2_internal.h"

#define SEQ_EXT 2
#define SEQ_DISPLAY_EXT 4
#define QUANT_MATRIX_EXT 8
#define COPYRIGHT_EXT 0x10
#define PIC_DISPLAY_EXT 0x80
#define PIC_CODING_EXT 0x100

/* default intra quant matrix, in zig-zag order */
static const uint8_t default_intra_quantizer_matrix[64] =
{
    8,
    16, 16,
    19, 16, 19,
    22, 22, 22, 22,
    22, 22, 26, 24, 26,
    27, 27, 27, 26, 26, 26,
    26, 27, 27, 27, 29, 29, 29,
    34, 34, 34, 29, 29, 29, 27, 27,
    29, 29, 32, 32, 34, 34, 37,
    38, 37, 35, 35, 34, 35,
    38, 38, 40, 40, 40,
    48, 48, 46, 46,
    56, 56, 58,
    69, 69,
    83
};

const uint8_t default_mpeg2_scan_norm[64] =
{
    /* Zig-Zag scan pattern */
     0,  1,  8, 16,  9,  2,  3, 10,
    17, 24, 32, 25, 18, 11,  4,  5,
    12, 19, 26, 33, 40, 48, 41, 34,
    27, 20, 13,  6,  7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36,
    29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46,
    53, 60, 61, 54, 47, 55, 62, 63
};

const uint8_t default_mpeg2_scan_alt[64] =
{
    /* Alternate scan pattern */
     0, 8,  16, 24,  1,  9,  2, 10,
    17, 25, 32, 40, 48, 56, 57, 49,
    41, 33, 26, 18,  3, 11,  4, 12,
    19, 27, 34, 42, 50, 58, 35, 43,
    51, 59, 20, 28,  5, 13,  6, 14,
    21, 29, 36, 44, 52, 60, 37, 45,
    53, 61, 22, 30,  7, 15, 23, 31,
    38, 46, 54, 62, 39, 47, 55, 63
};

uint8_t mpeg2_scan_norm[64] IDATA_ATTR;
uint8_t mpeg2_scan_alt[64] IDATA_ATTR;

void mpeg2_header_state_init (mpeg2dec_t * mpeg2dec)
{
    if (mpeg2dec->sequence.width != (unsigned)-1)
    {
        mpeg2dec->sequence.width = (unsigned)-1;
        mpeg2_mem_reset(); /* Clean the memory slate */
#if 0
        if (!mpeg2dec->custom_fbuf)
        {
            int i;
            for (i = mpeg2dec->alloc_index_user;
                 i < mpeg2dec->alloc_index; i++)
            {
                mpeg2_free(mpeg2dec->fbuf_alloc[i].fbuf.buf[0]);
#if MPEG2_COLOR
                mpeg2_free(mpeg2dec->fbuf_alloc[i].fbuf.buf[1]);
                mpeg2_free(mpeg2dec->fbuf_alloc[i].fbuf.buf[2]);
#endif
            }
        }

        if (mpeg2dec->convert_start)
        {
            int i;
            for (i = 0; i < 3; i++)
            {
                mpeg2_free(mpeg2dec->yuv_buf[i][0]);
#if MPEG2_COLOR
                mpeg2_free(mpeg2dec->yuv_buf[i][1]);
                mpeg2_free(mpeg2dec->yuv_buf[i][2]);
#endif
            }
        }

        if (mpeg2dec->decoder.convert_id)
        {
            mpeg2_free(mpeg2dec->decoder.convert_id);
        }
#endif
    }

    mpeg2dec->decoder.coding_type = I_TYPE;
    mpeg2dec->decoder.convert = NULL;
    mpeg2dec->decoder.convert_id = NULL;

    mpeg2dec->picture = mpeg2dec->pictures;

    mpeg2dec->fbuf[0] = &mpeg2dec->fbuf_alloc[0].fbuf;
    mpeg2dec->fbuf[1] = &mpeg2dec->fbuf_alloc[1].fbuf;
    mpeg2dec->fbuf[2] = &mpeg2dec->fbuf_alloc[2].fbuf;

    mpeg2dec->first = 1;
    mpeg2dec->alloc_index = 0;
    mpeg2dec->alloc_index_user = 0;
    mpeg2dec->first_decode_slice = 1;
    mpeg2dec->nb_decode_slices = 0xb0 - 1;
    mpeg2dec->convert = NULL;
    mpeg2dec->convert_start = NULL;
    mpeg2dec->custom_fbuf = 0;
    mpeg2dec->yuv_index = 0;
}

void mpeg2_reset_info (mpeg2_info_t * info)
{
    info->current_picture =
    info->current_picture_2nd = NULL;

    info->display_picture =
    info->display_picture_2nd = NULL;

    info->current_fbuf =
    info->display_fbuf =
    info->discard_fbuf = NULL;
}

static void info_user_data (mpeg2dec_t * mpeg2dec)
{
    if (mpeg2dec->user_data_len)
    {
        mpeg2dec->info.user_data = mpeg2dec->chunk_buffer;
        mpeg2dec->info.user_data_len = mpeg2dec->user_data_len - 3;
    }
}

int mpeg2_header_sequence (mpeg2dec_t * mpeg2dec)
{
    static const unsigned int frame_period[16] =
    {
        0, 1126125, 1125000, 1080000, 900900, 900000, 540000, 450450, 450000,
        /* unofficial: xing 15 fps */
        1800000,
        /* unofficial: libmpeg3 "Unofficial economy rates" 5/10/12/15 fps */
        5400000, 2700000, 2250000, 1800000, 0, 0
    };

    uint8_t * buffer = mpeg2dec->chunk_start;
    mpeg2_sequence_t * sequence = &mpeg2dec->new_sequence;
    int i;

    if ((buffer[6] & 0x20) != 0x20)        /* missing marker_bit */
        return 1;

    i = (buffer[0] << 16) | (buffer[1] << 8) | buffer[2];

    if (!(sequence->display_width = sequence->picture_width = i >> 12))
        return 1;

    if (!(sequence->display_height = sequence->picture_height = i & 0xfff))
        return 1;

    sequence->width = (sequence->picture_width + 15) & ~15;
    sequence->height = (sequence->picture_height + 15) & ~15;
    sequence->chroma_width = sequence->width >> 1;
    sequence->chroma_height = sequence->height >> 1;

    sequence->flags = SEQ_FLAG_PROGRESSIVE_SEQUENCE |
                      SEQ_VIDEO_FORMAT_UNSPECIFIED;

    sequence->pixel_width = buffer[3] >> 4;        /* aspect ratio */
    sequence->frame_period = frame_period[buffer[3] & 15];

    sequence->byte_rate = (buffer[4]<<10) | (buffer[5]<<2) | (buffer[6]>>6);

    sequence->vbv_buffer_size = ((buffer[6]<<16) | (buffer[7]<<8)) & 0x1ff800;

    if (buffer[7] & 4)
        sequence->flags |= SEQ_FLAG_CONSTRAINED_PARAMETERS;

    mpeg2dec->copy_matrix = 3;

    if (buffer[7] & 2)
    {
        for (i = 0; i < 64; i++)
        {
            mpeg2dec->new_quantizer_matrix[0][mpeg2_scan_norm[i]] =
                (buffer[i+7] << 7) | (buffer[i+8] >> 1);
        }

        buffer += 64;
    }
    else
    {
        for (i = 0; i < 64; i++)
        {
            mpeg2dec->new_quantizer_matrix[0][mpeg2_scan_norm[i]] =
                default_intra_quantizer_matrix[i];
        }
    }

    if (buffer[7] & 1)
    {
        for (i = 0; i < 64; i++)
        {
            mpeg2dec->new_quantizer_matrix[1][mpeg2_scan_norm[i]] =
                buffer[i+8];
        }
    }
    else
    {
        rb->memset (mpeg2dec->new_quantizer_matrix[1], 16, 64);
    }

    sequence->profile_level_id = 0x80;
    sequence->colour_primaries = 0;
    sequence->transfer_characteristics = 0;
    sequence->matrix_coefficients = 0;

    mpeg2dec->ext_state = SEQ_EXT;
    mpeg2dec->state = STATE_SEQUENCE;

    mpeg2dec->display_offset_x =
    mpeg2dec->display_offset_y = 0;

    return 0;
}

static int sequence_ext (mpeg2dec_t * mpeg2dec)
{
    uint8_t * buffer = mpeg2dec->chunk_start;
    mpeg2_sequence_t * sequence = &mpeg2dec->new_sequence;
    uint32_t flags;

    if (!(buffer[3] & 1))
        return 1;

    sequence->profile_level_id = (buffer[0] << 4) | (buffer[1] >> 4);

    sequence->picture_width += ((buffer[1] << 13) | (buffer[2] << 5)) & 0x3000;
    sequence->display_width = sequence->picture_width;

    sequence->picture_height += (buffer[2] << 7) & 0x3000;
    sequence->display_height = sequence->picture_height;

    sequence->width = (sequence->picture_width + 15) & ~15;
    sequence->height = (sequence->picture_height + 15) & ~15;

    flags = sequence->flags | SEQ_FLAG_MPEG2;

    if (!(buffer[1] & 8))
    {
        flags &= ~SEQ_FLAG_PROGRESSIVE_SEQUENCE;
        sequence->height = (sequence->height + 31) & ~31;
    }

    if (buffer[5] & 0x80)
        flags |= SEQ_FLAG_LOW_DELAY;

    sequence->flags = flags;
    sequence->chroma_width = sequence->width;
    sequence->chroma_height = sequence->height;

    switch (buffer[1] & 6)
    {
    case 0:        /* invalid */
        return 1;
    case 2:        /* 4:2:0 */
        sequence->chroma_height >>= 1;
    case 4:        /* 4:2:2 */
        sequence->chroma_width >>= 1;
    }

    sequence->byte_rate += ((buffer[2]<<25) | (buffer[3]<<17)) & 0x3ffc0000;

    sequence->vbv_buffer_size |= buffer[4] << 21;

    sequence->frame_period =
        sequence->frame_period * ((buffer[5]&31)+1) / (((buffer[5]>>2)&3)+1);

    mpeg2dec->ext_state = SEQ_DISPLAY_EXT;

    return 0;
}

static int sequence_display_ext (mpeg2dec_t * mpeg2dec)
{
    uint8_t * buffer = mpeg2dec->chunk_start;
    mpeg2_sequence_t * sequence = &mpeg2dec->new_sequence;
    int x;

    sequence->flags = (sequence->flags & ~SEQ_MASK_VIDEO_FORMAT) |
             ((buffer[0] << 4) & SEQ_MASK_VIDEO_FORMAT);

    if (buffer[0] & 1)
    {
        sequence->flags |= SEQ_FLAG_COLOUR_DESCRIPTION;
        sequence->colour_primaries = buffer[1];
        sequence->transfer_characteristics = buffer[2];
        sequence->matrix_coefficients = buffer[3];
        buffer += 3;
    }

    if (!(buffer[2] & 2))        /* missing marker_bit */
        return 1;

    x = (buffer[1] << 6) | (buffer[2] >> 2);
    if (x)
        sequence->display_width = x;

    x = ((buffer[2] & 1) << 13) | (buffer[3] << 5) | (buffer[4] >> 3);
    if (x)
        sequence->display_height = x;

    return 0;
}

static inline void simplify (unsigned int * u, unsigned int * v) 
{ 
    unsigned int a, b, tmp; 
 
    a = *u;
    b = *v; 

    /* find greatest common divisor */ 
    while (a)
    {
        tmp = a;
        a = b % tmp;
        b = tmp; 
    } 

    *u /= b;
    *v /= b; 
} 

static inline void finalize_sequence (mpeg2_sequence_t * sequence)
{
    int width;
    int height;

    sequence->byte_rate *= 50;

    if (sequence->flags & SEQ_FLAG_MPEG2)
    {
        switch (sequence->pixel_width)
        {
        case 1:                /* square pixels */
            sequence->pixel_width =
            sequence->pixel_height = 1;
            return;
        case 2:                /* 4:3 aspect ratio */
            width = 4;
            height = 3;
            break;
        case 3:                /* 16:9 aspect ratio */
            width = 16;
            height = 9;
            break;
        case 4:                /* 2.21:1 aspect ratio */
            width = 221;
            height = 100;
            break;
        default:        /* illegal */
            sequence->pixel_width =
            sequence->pixel_height = 0;
            return;
        }

        width *= sequence->display_height;
        height *= sequence->display_width;
    }
    else
    {
        if (sequence->byte_rate == 50 * 0x3ffff)
            sequence->byte_rate = 0;        /* mpeg-1 VBR */

        switch (sequence->pixel_width)
        {
        case 0:
        case 15:        /* illegal */
            sequence->pixel_width =
            sequence->pixel_height = 0;
            return;
        case 1:        /* square pixels */
            sequence->pixel_width =
            sequence->pixel_height = 1;
            return;
        case 3:        /* 720x576 16:9 */
            sequence->pixel_width = 64;
            sequence->pixel_height = 45;
            return;
        case 6:        /* 720x480 16:9 */
            sequence->pixel_width = 32;
            sequence->pixel_height = 27;
            return;
        case 8:        /* BT.601 625 lines 4:3 */
            sequence->pixel_width = 59;
            sequence->pixel_height = 54;
            return;
        case 12:       /* BT.601 525 lines 4:3 */
            sequence->pixel_width = 10;
            sequence->pixel_height = 11;
            return;
        default:
            height = 88 * sequence->pixel_width + 1171;
            width = 2000;
        }
    }

    sequence->pixel_width = width;
    sequence->pixel_height = height;

    simplify(&sequence->pixel_width, &sequence->pixel_height);
}

int mpeg2_guess_aspect (const mpeg2_sequence_t * sequence, 
                        unsigned int * pixel_width, 
                        unsigned int * pixel_height) 
{ 
    static const struct
    { 
        unsigned int width, height; 
    } video_modes[] =
    {
        {720, 576}, /* 625 lines, 13.5 MHz (D1, DV, DVB, DVD) */ 
        {704, 576}, /* 625 lines, 13.5 MHz (1/1 D1, DVB, DVD, 4CIF) */ 
        {544, 576}, /* 625 lines, 10.125 MHz (DVB, laserdisc) */ 
        {528, 576}, /* 625 lines, 10.125 MHz (3/4 D1, DVB, laserdisc) */ 
        {480, 576}, /* 625 lines, 9 MHz (2/3 D1, DVB, SVCD) */ 
        {352, 576}, /* 625 lines, 6.75 MHz (D2, 1/2 D1, CVD, DVB, DVD) */ 
        {352, 288}, /* 625 lines, 6.75 MHz, 1 field (D4, VCD, DVB, DVD, CIF) */ 
        {176, 144}, /* 625 lines, 3.375 MHz, half field (QCIF) */ 
        {720, 486}, /* 525 lines, 13.5 MHz (D1) */ 
        {704, 486}, /* 525 lines, 13.5 MHz */ 
        {720, 480}, /* 525 lines, 13.5 MHz (DV, DSS, DVD) */ 
        {704, 480}, /* 525 lines, 13.5 MHz (1/1 D1, ATSC, DVD) */ 
        {544, 480}, /* 525 lines. 10.125 MHz (DSS, laserdisc) */ 
        {528, 480}, /* 525 lines. 10.125 MHz (3/4 D1, laserdisc) */ 
        {480, 480}, /* 525 lines, 9 MHz (2/3 D1, SVCD) */ 
        {352, 480}, /* 525 lines, 6.75 MHz (D2, 1/2 D1, CVD, DVD) */ 
        {352, 240}  /* 525 lines. 6.75 MHz, 1 field (D4, VCD, DSS, DVD) */ 
    }; 
    unsigned int width, height, pix_width, pix_height, i, DAR_16_9; 
 
    *pixel_width = sequence->pixel_width; 
    *pixel_height = sequence->pixel_height; 
    width = sequence->picture_width; 
    height = sequence->picture_height; 

    for (i = 0; i < sizeof (video_modes) / sizeof (video_modes[0]); i++) 
    {
        if (width == video_modes[i].width && height == video_modes[i].height) 
            break; 
    }

    if (i == ARRAYLEN(video_modes) || 
        (sequence->pixel_width == 1 && sequence->pixel_height == 1) ||
        width != sequence->display_width || height != sequence->display_height)
    {
        return 0; 
    }
 
    for (pix_height = 1; height * pix_height < 480; pix_height <<= 1);
    height *= pix_height; 

    for (pix_width = 1; width * pix_width <= 352; pix_width <<= 1); 
    width *= pix_width; 
 
    if (!(sequence->flags & SEQ_FLAG_MPEG2))
    {
        static unsigned int mpeg1_check[2][2] = {{11, 54}, {27, 45}}; 
        DAR_16_9 = (sequence->pixel_height == 27 || 
                    sequence->pixel_height == 45); 
        if (width < 704 || 
            sequence->pixel_height != mpeg1_check[DAR_16_9][height == 576]) 
            return 0; 
    }
    else
    { 
        DAR_16_9 = (3 * sequence->picture_width * sequence->pixel_width > 
                    4 * sequence->picture_height * sequence->pixel_height); 
        switch (width)
        { 
        case 528:
        case 544:
            pix_width *= 4;
            pix_height *= 3;
            break;
        case 480:
            pix_width *= 3;
            pix_height *= 2;
            break;
        }